Address Cody review round 3: CODY-003 and CODY-006

CODY-003 Request identity is durable before submission. Storage results are
         explicit at the DevicePort boundary (storageSet resolves true only
         on the host's own timely confirmation; storageGet distinguishes
         unknown from empty). A request is not sent until the phone has
         confirmed storing its id; a timeout or refusal holds it back,
         unsent and retryable under the same id. Unreadable storage at
         start is not treated as unpaired; an unsaveable pairing is revoked.
CODY-006 The state directory is set to 0700 on every open, including when
         it already existed, and the bridge refuses to start with an
         operator-facing error if it cannot be. Deployment guide creates
         it with install -d -m 0700.

Checks: typecheck clean; npm test 194 passed; client build ok;
test:real-stt 11 passed; test:real-hermes 9 passed; test:simulator 6
passed; git diff --check clean.

Not reviewed. No physical-device, droplet or production evidence.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
Dan
2026-11-18 20:29:05 -08:00
co-authored by Claude Fable 5.2
parent e1c02d5266
commit 1507cea077
19 changed files with 759 additions and 45 deletions
+61 -11
View File
@@ -87,6 +87,10 @@ export class Controller {
private pending: PendingInput | null = null;
private lastTurn: TurnResult | null = null;
private hudReady = false;
/** The request id last CONFIRMED stored by the host (`undefined` = not known). */
private confirmedActive: string | null | undefined = undefined;
/** App storage could not be read at start: nothing is assumed about what it holds. */
private storageFault = false;
private creating: { epoch: number; promise: Promise<string> } | null = null;
private createChain: Promise<void> = Promise.resolve();
private stopped = false;
@@ -115,7 +119,11 @@ export class Controller {
// ------------------------------------------------------------------ public
async start(): Promise<void> {
this.stored = await this.load();
const loaded = await this.load();
this.storageFault = loaded === 'unreadable';
this.stored = loaded === 'unreadable' ? null : loaded;
if (this.stored) this.confirmedActive = this.stored.activeCancelled ? undefined : this.stored.activeRequestId;
if (this.storageFault) this.note('storage', 'app storage could not be read; saved pairing state is unknown');
this.hudReady = await this.device.init(renderHud(this.state, this.now()));
this.note('hud', this.hudReady ? 'HUD page created' : 'HUD page was refused by the host');
this.unsubscribers.push(
@@ -150,6 +158,7 @@ export class Controller {
conversationId: this.stored?.conversationId ?? null,
captureMaxSeconds,
resumeRequestId: abandoned ? null : (this.stored?.activeRequestId ?? null),
storageFault: this.storageFault,
});
if (abandoned) void this.cancelTurn(abandoned);
}
@@ -179,6 +188,10 @@ export class Controller {
/** Explicit pairing from the phone. Throws with a user-presentable message on failure. */
async pair(bridgeUrl: string, code: string, deviceName: string): Promise<void> {
if (this.storageFault) {
// Pairing now would overwrite storage we could not read, which may hold a running turn.
throw new Error('Saved settings could not be read. Close Hermeven and open it again before pairing.');
}
const client = this.makeClient(bridgeUrl, '');
const credential = await client.claim(code, deviceName);
client.token = credential.token;
@@ -193,7 +206,15 @@ export class Controller {
activeRequestId: null,
activeCancelled: false,
};
await this.save();
if (!(await this.save())) {
// A pairing that exists only in memory would vanish on the next start and leave a live
// credential behind on the bridge. Undo it instead.
this.stored = null;
this.client = null;
await client.revoke().catch(() => undefined);
throw new Error('The phone could not save the pairing, so it was not kept. Get a new pairing code and try again.');
}
this.confirmedActive = null;
this.note('pairing', `paired as ${credential.device_id}`);
let captureMaxSeconds: number = DEFAULT_LIMITS.captureMaxSeconds;
try {
@@ -433,7 +454,15 @@ export class Controller {
// Remember the request id before anything is sent. From here until the bridge gives a
// definite answer, this request may or may not exist there; if the page dies in between,
// the next start re-attaches to it by id instead of forgetting a turn that is running.
await this.setActiveRequest(requestId);
//
// Nothing is sent until the phone has CONFIRMED storing the id. An unanswered or refused
// write stops here, with the request provably unsent and kept for a retry under the same id.
if (!(await this.setActiveRequest(requestId))) {
this.note('turn', `request ${requestId} held back: its id could not be stored`);
if (!this.stale(generation)) this.dispatch({ type: 'not_saved', generation });
return;
}
if (this.stale(generation)) return;
for (let attempt = 1; ; attempt++) {
if (this.stale(generation)) return;
try {
@@ -688,10 +717,19 @@ export class Controller {
}
}
private async setActiveRequest(requestId: string | null): Promise<void> {
if (!this.stored || (this.stored.activeRequestId === requestId && !this.stored.activeCancelled)) return;
this.stored = { ...this.stored, activeRequestId: requestId, activeCancelled: false };
await this.save();
/**
* Record which request may exist on the bridge. Resolves true only when the phone has
* positively confirmed storing it; a write that timed out or failed is retried on the next
* call rather than assumed.
*/
private async setActiveRequest(requestId: string | null): Promise<boolean> {
if (!this.stored) return false;
const unchanged = this.stored.activeRequestId === requestId && !this.stored.activeCancelled;
if (unchanged && this.confirmedActive === requestId) return true;
if (!unchanged) this.stored = { ...this.stored, activeRequestId: requestId, activeCancelled: false };
const ok = await this.save();
this.confirmedActive = ok ? requestId : undefined;
return ok;
}
/** Clear the stored request id only if it is still this one (a newer turn may own the slot). */
@@ -699,9 +737,18 @@ export class Controller {
if (this.stored?.activeRequestId === requestId) await this.setActiveRequest(null);
}
private async load(): Promise<Stored | null> {
/** `'unreadable'` when the host would not say what is stored; never guessed as "nothing". */
private async load(): Promise<Stored | null | 'unreadable'> {
let raw = '';
for (let attempt = 1; ; attempt++) {
const read = await this.device.storageGet(STORAGE_KEY);
if (read.ok) {
raw = read.value;
break;
}
if (attempt >= 3) return 'unreadable';
}
try {
const raw = await this.device.storageGet(STORAGE_KEY);
if (!raw) return null;
const parsed = JSON.parse(raw) as Partial<Stored>;
if (typeof parsed.bridgeUrl !== 'string' || typeof parsed.token !== 'string' || !parsed.token) return null;
@@ -720,8 +767,11 @@ export class Controller {
}
}
private async save(): Promise<void> {
await this.device.storageSet(STORAGE_KEY, this.stored ? JSON.stringify(this.stored) : '');
/** True only when the host confirmed the write. See DevicePort.storageSet. */
private async save(): Promise<boolean> {
const ok = await this.device.storageSet(STORAGE_KEY, this.stored ? JSON.stringify(this.stored) : '');
if (!ok) this.note('storage', 'a write to app storage was not confirmed');
return ok;
}
private async forget(): Promise<void> {
+13
View File
@@ -45,6 +45,12 @@ function clock(seconds: number): string {
export function renderHud(state: AppState, nowMs: number): HudFrame {
switch (state.phase) {
case 'unpaired':
if (state.storageFault) {
return {
body: 'Hermeven\n\nSaved settings could not be read.\nClose Hermeven and open it again.',
status: 'Double-tap: exit',
};
}
return { body: 'Hermeven\n\nNot connected.\nOpen Hermeven on your phone to pair.', status: 'Double-tap: exit' };
case 'ready':
@@ -92,6 +98,13 @@ export function renderHud(state: AppState, nowMs: number): HudFrame {
if (state.disconnectedFrom === 'glasses') {
return { body: 'Glasses disconnected.', status: 'Reconnect to continue' };
}
if (state.disconnectedFrom === 'storage') {
// True as stated: the request is only ever sent after its id has been saved.
return {
body: 'Could not save your request on the phone.\n\nNothing has been sent.',
status: 'Tap: retry · Double-tap: discard',
};
}
return state.canResend
? // Deliberately not "has not been sent": a request can be admitted even when no reply
// comes back, so the honest statement is that it is unconfirmed.
+19 -3
View File
@@ -52,8 +52,13 @@ export interface AppState {
error: HudError | null;
/** In DISCONNECTED: the request never reached the bridge, so resending it is safe. */
canResend: boolean;
/** Why we are disconnected: the bridge link, or the glasses themselves. */
disconnectedFrom: 'bridge' | 'glasses' | null;
/**
* Why we are stopped: the bridge link, the glasses themselves, or the phone's app storage
* (the request id could not be saved, so the request was deliberately not sent).
*/
disconnectedFrom: 'bridge' | 'glasses' | 'storage' | null;
/** App storage could not be read at start; saved pairing state is unknown. */
storageFault: boolean;
notice: string | null;
}
@@ -72,11 +77,12 @@ export const initialState: AppState = {
error: null,
canResend: false,
disconnectedFrom: null,
storageFault: false,
notice: null,
};
export type AppEvent =
| { type: 'init'; paired: boolean; conversationId: string | null; captureMaxSeconds: number; resumeRequestId: string | null }
| { type: 'init'; paired: boolean; conversationId: string | null; captureMaxSeconds: number; resumeRequestId: string | null; storageFault?: boolean }
| { type: 'unpaired' }
/** Semantic actions. `freshId` is a new UUID supplied by the caller in case a turn starts. */
| { type: 'activate'; freshId: string }
@@ -95,6 +101,8 @@ export type AppEvent =
| { type: 'turn_update'; generation: number; result: TurnResult; pages: string[] | null }
| { type: 'turn_rejected'; generation: number; error: HudError }
| { type: 'network_lost'; generation: number; stage: 'submit' | 'poll' }
/** The request id could not be stored, so the request was held back. Nothing was sent. */
| { type: 'not_saved'; generation: number }
| { type: 'network_restored'; generation: number }
| { type: 'glasses_status'; connected: boolean }
| { type: 'app_exit' };
@@ -160,6 +168,7 @@ export function reduce(state: AppState, event: AppEvent): Step {
captureMaxSeconds: event.captureMaxSeconds,
conversationId: event.conversationId,
conversationEpoch: state.conversationEpoch + 1,
storageFault: event.storageFault === true,
};
if (!event.paired) return same({ ...base, phase: 'unpaired' });
if (event.resumeRequestId) {
@@ -352,6 +361,13 @@ export function reduce(state: AppState, event: AppEvent): Step {
return same({ ...state, phase: 'disconnected', disconnectedFrom: 'bridge', canResend: event.stage === 'submit' });
}
case 'not_saved': {
if (event.generation !== state.generation) return same(state);
if (!IN_FLIGHT.has(state.phase) && state.phase !== 'disconnected') return same(state);
// Same request id is kept, so a retry is the same request, not a new one.
return same({ ...state, phase: 'disconnected', disconnectedFrom: 'storage', canResend: true });
}
case 'network_restored': {
if (event.generation !== state.generation || state.phase !== 'disconnected' || state.disconnectedFrom !== 'bridge') {
return same(state);
+12 -5
View File
@@ -9,7 +9,7 @@ import {
} from '@evenrealities/even_hub_sdk';
import { BODY_BOX, HUD, STATUS_BOX, type HudFrame } from '../core/hud.ts';
import { MENU_ITEM, normalizeEvent, type DeviceEvent, type RawEvenHubEvent } from './events.ts';
import type { DevicePort } from './port.ts';
import type { DevicePort, StorageRead } from './port.ts';
const BODY = { id: 1, name: 'body' } as const;
const STATUS = { id: 2, name: 'status' } as const;
@@ -192,11 +192,18 @@ export class EvenDevice implements DevicePort {
await this.enqueue(() => this.bridge.shutDownPageContainer(1), false);
}
storageGet(key: string): Promise<string> {
return this.enqueue(() => this.bridge.getLocalStorage(key), '');
async storageGet(key: string): Promise<StorageRead> {
const read = await this.enqueueBounded<string | null>(() => this.bridge.getLocalStorage(key), null);
// A timeout or a host error is "unknown", not "empty": the caller must not conclude that
// nothing was stored.
if (read.timedOut || typeof read.value !== 'string') return { ok: false };
return { ok: true, value: read.value };
}
async storageSet(key: string, value: string): Promise<void> {
await this.enqueue(() => this.bridge.setLocalStorage(key, value), false);
async storageSet(key: string, value: string): Promise<boolean> {
const write = await this.enqueueBounded(() => this.bridge.setLocalStorage(key, value), false);
// Only the host's own `true`, received in time, counts. If the caller's wait ran out the
// host call is still pending in the queue and may complete later; that is not confirmation.
return !write.timedOut && write.value === true;
}
}
+13 -2
View File
@@ -1,6 +1,8 @@
import type { HudFrame } from '../core/hud.ts';
import type { DeviceEvent } from './events.ts';
export type StorageRead = { ok: true; value: string } | { ok: false };
/** Everything Hermeven needs from the glasses runtime. Implemented by the Even adapter and by test fakes. */
export interface DevicePort {
/** Create the HUD page. Resolves false when the host refused it. */
@@ -14,6 +16,15 @@ export interface DevicePort {
onConnection(listener: (connected: boolean) => void): () => void;
/** Ask the OS to show its own exit confirmation. */
requestExit(): Promise<void>;
storageGet(key: string): Promise<string>;
storageSet(key: string, value: string): Promise<void>;
/**
* Read a stored value. `{ ok: false }` means the host did not answer (or failed): the value
* is UNKNOWN, which is different from "nothing stored" (`{ ok: true, value: '' }`).
*/
storageGet(key: string): Promise<StorageRead>;
/**
* Store a value. Resolves `true` ONLY when the host positively confirmed the write.
* `false` covers a refusal, an error and a timeout; after a timeout the write may still
* land later, so `false` is "not confirmed", never "not written" and never "written".
*/
storageSet(key: string, value: string): Promise<boolean>;
}
+7 -6
View File
@@ -1,6 +1,6 @@
import type { HudFrame } from '../core/hud.ts';
import type { DeviceEvent } from './events.ts';
import type { DevicePort } from './port.ts';
import type { DevicePort, StorageRead } from './port.ts';
/**
* Stand-in for the glasses when the page runs in a plain browser (no Even host).
@@ -68,20 +68,21 @@ export class BrowserPreviewDevice implements DevicePort {
async requestExit(): Promise<void> {}
async storageGet(key: string): Promise<string> {
async storageGet(key: string): Promise<StorageRead> {
try {
return localStorage.getItem(key) ?? '';
return { ok: true, value: localStorage.getItem(key) ?? '' };
} catch {
return '';
return { ok: false };
}
}
async storageSet(key: string, value: string): Promise<void> {
async storageSet(key: string, value: string): Promise<boolean> {
try {
if (value) localStorage.setItem(key, value);
else localStorage.removeItem(key);
return true;
} catch {
/* preview only */
return false;
}
}
}
+2
View File
@@ -165,6 +165,7 @@ describe('HUD frames', () => {
{ ...base, disconnectedFrom: 'glasses' },
{ ...base, disconnectedFrom: 'bridge', canResend: true },
{ ...base, disconnectedFrom: 'bridge', canResend: false },
{ ...base, disconnectedFrom: 'storage', canResend: true },
];
}
if (phase === 'error') {
@@ -174,6 +175,7 @@ describe('HUD frames', () => {
];
}
if (phase === 'ready') return [base, { ...base, notice: 'New conversation' }];
if (phase === 'unpaired') return [base, { ...base, storageFault: true }];
return [base];
};