From 1507cea077838852bfa3658a0d6ef5f419fd8437 Mon Sep 17 00:00:00 2001 From: Dan Date: Wed, 18 Nov 2026 20:29:05 -0800 Subject: [PATCH] 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 --- README.md | 2 +- apps/even-client/src/core/controller.ts | 72 ++++- apps/even-client/src/core/hud.ts | 13 + apps/even-client/src/core/reducer.ts | 22 +- apps/even-client/src/device/evenAdapter.ts | 17 +- apps/even-client/src/device/port.ts | 15 +- apps/even-client/src/device/previewDevice.ts | 13 +- apps/even-client/test/layout.test.ts | 2 + docs/architecture.md | 2 + docs/deploy-droplet.md | 8 +- docs/handoff/2026-11-18-cody-round-4.md | 74 +++++ docs/security.md | 6 +- docs/test-evidence.md | 61 ++++ services/bridge/src/db.ts | 42 ++- services/bridge/src/main.ts | 5 +- services/bridge/test/units.test.ts | 82 ++++- tests/fakes/fakeDevice.ts | 14 +- tests/integration/clientSecurity.test.ts | 38 ++- tests/integration/durableRequestId.test.ts | 316 +++++++++++++++++++ 19 files changed, 759 insertions(+), 45 deletions(-) create mode 100644 docs/handoff/2026-11-18-cody-round-4.md create mode 100644 tests/integration/durableRequestId.test.ts diff --git a/README.md b/README.md index cdab788..e512ecd 100644 --- a/README.md +++ b/README.md @@ -12,7 +12,7 @@ small bridge between the two. | Path | State | |---|---| | Client, bridge and contract | Implemented. | -| Automated tests with fakes (182) | Passing. | +| Automated tests with fakes (194) | Passing. | | Client in Even's official simulator | Passing (6 scenarios). Simulator only. | | Bridge against a real Hermes gateway | Passing (9 scenarios) with a **stub model**. | | Built-in speech-to-text (Whisper, in the bridge) | Passing (11 scenarios) on a real speech recording, including with no network. Not yet on audio from the glasses. | diff --git a/apps/even-client/src/core/controller.ts b/apps/even-client/src/core/controller.ts index 7e7a0a6..5e4ac9c 100644 --- a/apps/even-client/src/core/controller.ts +++ b/apps/even-client/src/core/controller.ts @@ -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 } | null = null; private createChain: Promise = Promise.resolve(); private stopped = false; @@ -115,7 +119,11 @@ export class Controller { // ------------------------------------------------------------------ public async start(): Promise { - 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 { + 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 { - 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 { + 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 { + /** `'unreadable'` when the host would not say what is stored; never guessed as "nothing". */ + private async load(): Promise { + 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; if (typeof parsed.bridgeUrl !== 'string' || typeof parsed.token !== 'string' || !parsed.token) return null; @@ -720,8 +767,11 @@ export class Controller { } } - private async save(): Promise { - 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 { + 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 { diff --git a/apps/even-client/src/core/hud.ts b/apps/even-client/src/core/hud.ts index dcf5d25..317808e 100644 --- a/apps/even-client/src/core/hud.ts +++ b/apps/even-client/src/core/hud.ts @@ -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. diff --git a/apps/even-client/src/core/reducer.ts b/apps/even-client/src/core/reducer.ts index 18d1207..ea26640 100644 --- a/apps/even-client/src/core/reducer.ts +++ b/apps/even-client/src/core/reducer.ts @@ -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); diff --git a/apps/even-client/src/device/evenAdapter.ts b/apps/even-client/src/device/evenAdapter.ts index f8ebb38..acae165 100644 --- a/apps/even-client/src/device/evenAdapter.ts +++ b/apps/even-client/src/device/evenAdapter.ts @@ -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 { - return this.enqueue(() => this.bridge.getLocalStorage(key), ''); + async storageGet(key: string): Promise { + const read = await this.enqueueBounded(() => 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 { - await this.enqueue(() => this.bridge.setLocalStorage(key, value), false); + async storageSet(key: string, value: string): Promise { + 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; } } diff --git a/apps/even-client/src/device/port.ts b/apps/even-client/src/device/port.ts index 26eafdb..d2cb6a6 100644 --- a/apps/even-client/src/device/port.ts +++ b/apps/even-client/src/device/port.ts @@ -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; - storageGet(key: string): Promise; - storageSet(key: string, value: string): Promise; + /** + * 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; + /** + * 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; } diff --git a/apps/even-client/src/device/previewDevice.ts b/apps/even-client/src/device/previewDevice.ts index 8a690bf..67647d4 100644 --- a/apps/even-client/src/device/previewDevice.ts +++ b/apps/even-client/src/device/previewDevice.ts @@ -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 {} - async storageGet(key: string): Promise { + async storageGet(key: string): Promise { try { - return localStorage.getItem(key) ?? ''; + return { ok: true, value: localStorage.getItem(key) ?? '' }; } catch { - return ''; + return { ok: false }; } } - async storageSet(key: string, value: string): Promise { + async storageSet(key: string, value: string): Promise { try { if (value) localStorage.setItem(key, value); else localStorage.removeItem(key); + return true; } catch { - /* preview only */ + return false; } } } diff --git a/apps/even-client/test/layout.test.ts b/apps/even-client/test/layout.test.ts index 5ca3e01..02d6c61 100644 --- a/apps/even-client/test/layout.test.ts +++ b/apps/even-client/test/layout.test.ts @@ -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]; }; diff --git a/docs/architecture.md b/docs/architecture.md index 6f9fee2..3a673a1 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -66,6 +66,8 @@ accepted -> transcribing -> thinking -> done Order of operations for one turn: +0. On the phone, before any of this: the app stores the request id in app storage and waits + for the host to confirm the write. No confirmation, no request. 1. Validate, authenticate, check the conversation belongs to the device and is open, and that no other turn is running in it. Insert the turn row keyed by the client's request id. A repeat of the same request id returns the existing turn. diff --git a/docs/deploy-droplet.md b/docs/deploy-droplet.md index d7d06aa..07d10c8 100644 --- a/docs/deploy-droplet.md +++ b/docs/deploy-droplet.md @@ -52,9 +52,13 @@ accurate) and run `fetch-model` again. 3. **User and directories.** ```sh useradd --system --home /opt/hermeven --shell /usr/sbin/nologin hermeven - mkdir -p /opt/hermeven /var/lib/hermeven /etc/hermeven - chown hermeven:hermeven /var/lib/hermeven + mkdir -p /opt/hermeven /etc/hermeven + # The state directory is the service user's alone: mode 0700, set explicitly. + install -d -m 0700 -o hermeven -g hermeven /var/lib/hermeven ``` + The bridge also enforces this itself: at start it sets the directory that holds the database + to 0700 even if it already existed with looser permissions, and refuses to start if it + cannot (for example a directory owned by another user). 4. **Code.** Clone the repository into `/opt/hermeven`, then `npm ci`. (The dev dependencies are needed: the bridge runs through `tsx`.) 5. **Configuration.** Copy `deploy/bridge.env.example` to `/etc/hermeven/bridge.env`, fill it diff --git a/docs/handoff/2026-11-18-cody-round-4.md b/docs/handoff/2026-11-18-cody-round-4.md new file mode 100644 index 0000000..70c9512 --- /dev/null +++ b/docs/handoff/2026-11-18-cody-round-4.md @@ -0,0 +1,74 @@ +# Handoff for Cody, Round 4 + +From: Claude (implementation). Date: 2026-11-18. + +**Not reviewed.** Cody's Round 3 verdict applies to `e1c02d5` only. Whether CODY-003 and CODY-006 +are now closed is Cody's call on the new SHA. + +| Item | Value | +|---|---| +| Repository | `git@git.xylo.gg:Xylo-Digital/hermeven.git` | +| Branch | `cody/slice-1-review` | +| Reviewed in Round 3 | `e1c02d52661987df7caaec9bd132855df90cb814` | +| `main` | `0c9dcd864f16782097471e5bbf57cbd701c26616` (unchanged; nothing merged) | +| New head for Round 4 | the tip of `cody/slice-1-review` after this push; exact SHA in the push report | + +## CODY-003: request identity durable before submission + +| Required correction | What was done | +|---|---| +| 1. Storage success/failure explicit at the DevicePort boundary | `storageSet` returns `Promise`; `storageGet` returns `{ ok: true, value } \| { ok: false }` (`device/port.ts`). All three implementations updated. | +| 2. Never submit until persistence is positively confirmed | `Controller.submit()` returns without contacting the bridge unless `setActiveRequest()` resolved `true`. The controller tracks the last id the host confirmed (`confirmedActive`), so an unconfirmed id is written again on the next attempt instead of being assumed stored. | +| 3. On timeout or failure, remain safely unsent and show a retryable state | New `not_saved` event: phase `disconnected`, reason `storage`, resend allowed. The pending question is kept in memory. | +| 4. Same immutable request id across deliberate retries | The retry is the existing `resubmit` effect with the original request id. | +| 5. A caller timeout is not evidence the write succeeded | `EvenDevice.storageSet` returns `true` only for a host `true` received before the timeout. | + +Beyond the letter of the finding, because it is the same failure on the read side: storage that +cannot be read at start is reported as unknown rather than as "not paired", and pairing over it is +refused. A pairing the phone cannot save is revoked on the bridge instead of living in memory. + +## CODY-006: pre-existing state directories + +| Required correction | What was done | +|---|---| +| 1. Enforce 0700 even when the directory exists | `secureStateDir()` in `db.ts` runs on every open, before anything is created inside. | +| 2. Clear operator-facing error if it cannot be secured | `StateDirectoryError` names the directory, the required mode and the remedy; `main.ts` prints it as "Cannot start: ...". | +| 3. Deployment instructions create or chmod explicitly | `docs/deploy-droplet.md` uses `install -d -m 0700 -o hermeven -g hermeven /var/lib/hermeven`. | +| 4. Database, WAL, SHM stay 0600 | Unchanged, and re-asserted in the new tests. | + +## Checks + +| Check | Result | +|---|---| +| `npm run typecheck` | exit 0 | +| `npm test` | 194 passed, 0 failed (was 182) | +| `npm run client:build` | built | +| `npm run test:real-stt` | 11 passed, 0 failed (all 11 existing tests) | +| `npm run test:real-hermes` | 9 passed, 0 failed | +| `npm run test:simulator` | 6 passed, 0 failed | +| `git diff --check` | clean | + +No check was omitted. The proofs are listed in `docs/test-evidence.md` under "Round 4". + +## The eight resolved findings + +Not touched in substance. Their regression tests are unchanged and passing, apart from one +assertion in the CODY-002 queue test that now expects the explicit `{ ok: false }` read result. + +## Things the author is unsure about + +- **Whether the Even phone app confirms `setLocalStorage` promptly, or at all.** The simulator's + host does. If the phone's does not, this gate stops every question. That would be the correct + failure under this finding, but it would make the app unusable, and it can only be learned on a + device. +- While a host storage call is stuck, HUD updates queued behind it are not drawn (a consequence of + CODY-002's strict serialisation). The "could not save" message therefore appears only once the + host answers again. +- `secureStateDir` will set any directory it is pointed at to 0700. Pointing the database into a + directory shared with other software would lock that software out. +- The refusal test relies on `/tmp` being owned by another user; where it is not, the test reports + "NOT RUN" instead of passing. + +## Not claimed + +No physical device, no droplet, no deployment, no production change. Nothing merged to `main`. diff --git a/docs/security.md b/docs/security.md index cd9a597..f997215 100644 --- a/docs/security.md +++ b/docs/security.md @@ -36,7 +36,8 @@ devices. Not reviewed by anyone but its author yet; see `docs/handoff/`. | Cross-origin browser abuse | CORS allows only exact configured origins and sends no credentials mode. CORS is not treated as authentication: every route still needs the bearer credential. | yes | | Secrets or content in logs | Logs carry ids, states, codes and timings. Request logging is off, a redaction list backs it up, and Hermes's own diagnostic text is never relayed or logged. | yes | | Substituted speech-model files | The model is pinned to a commit id with a SHA-256 for every file. Files are fetched ahead of time and verified; the bridge re-verifies on every load, never downloads at run time, and reads from a directory that can be read-only. There is no unpinned mode. | yes, including with no network at all | -| State files readable by other users | The database is created owner-only before SQLite opens it (so its WAL and SHM files inherit that), in a 0700 directory; the systemd unit sets `UMask=0077`. | yes, under umask 0022 | +| State files readable by other users | The directory holding the database is set to 0700 at every start, whether it was just created or already existed, and the bridge refuses to start if it cannot be. The database is created owner-only before SQLite opens it (so its WAL and SHM files inherit that); the systemd unit sets `UMask=0077`. | yes, under umask 0022, for new and pre-existing directories | +| A running turn forgotten by the app | The request id is stored on the phone before anything is sent, and the request is not sent until the phone has confirmed the write. A write that times out or is refused holds the request back, unsent, for a retry under the same id. | yes, with the production Even adapter and a stalled host write | | Recordings retained | Audio exists only in memory for the length of one transcription call and is never written to disk by the bridge. | by construction; not independently audited | | Agent approves its own privileged action | The bridge never calls Hermes's approval endpoint. | yes | | Markup injection from an agent answer into the phone page | The page is built with `textContent` only. | by construction | @@ -71,6 +72,9 @@ Stated so they are not mistaken for protections. 4. **In the simulator, raw audio frames are echoed to the WebView console.** Whether the phone does the same is unknown and is on the device checklist. If it does, recordings would be visible to whoever can read that console. +4a. **The state directory must be the bridge's own.** Because it is forced to 0700, pointing + `HERMEVEN_DB_PATH` into a directory shared with other software will lock that software out; + a directory owned by another user is refused. 5. **TLS is not terminated by the bridge.** A reverse proxy or private network must provide it. A misconfigured proxy could expose plain HTTP. 6. **Rate limits are in memory** and reset on restart. Behind a proxy, per-address limits are only diff --git a/docs/test-evidence.md b/docs/test-evidence.md index 429f914..2cbda99 100644 --- a/docs/test-evidence.md +++ b/docs/test-evidence.md @@ -312,3 +312,64 @@ This was not a droplet. `deploy/` and `docs/deploy-droplet.md` remain unrun. Unchanged from the list above: no physical G2, no audio from the glasses, no real model or tools behind Hermes, no approval prompt from a real Hermes, no droplet, no HTTPS termination. + +## Round 4: after Cody's Round 3 review (2026-11-18) + +Cody reviewed `e1c02d5`: eight findings resolved, CODY-003 and CODY-006 still open. This section +records what was run after correcting those two. + +``` +$ npm run typecheck exit 0 +$ npm test Test Files 11 passed (11) Tests 194 passed (194) (3 consecutive runs) +$ npm run client:build built +$ npm run test:real-stt Tests 11 passed (11) (all 11 existing tests, including the no-network run) +$ npm run test:real-hermes Tests 9 passed (9) +$ npm run test:simulator Tests 6 passed (6) (3 consecutive runs) +$ git diff --check clean +``` + +No check was omitted. + +### CODY-003: request identity durable before submission + +`tests/integration/durableRequestId.test.ts` uses the production `EvenDevice` adapter with a +stand-in Even host whose `setLocalStorage` completes only when the test releases it. The bridge +is real; Hermes is the test fake. + +| Scenario | Result | +|---|---| +| Host write stalled past the adapter timeout: zero `POST /v1/turns`, no turn on the bridge, no Hermes run, the durable copy does not hold the id; a retry while still stalled is held back again under the same id | pass | +| Host completes the write: the id becomes durable and that alone sends nothing. Deliberate retry: admitted, every reply dropped. Page restart: re-attached under the same request id, exactly one Hermes run for it, and no HUD text after admission says "not sent" | pass | +| Same sequence with a hanging agent, restart, then double tap: Hermes is asked to stop and the turn settles as cancelled | pass | +| Cancel while still held back for storage: nothing is sent, nothing exists on the bridge | pass | +| Host answers the write with `false`: held back; succeeds on retry once the host accepts | pass | +| Page dies during the stall and the host writes late: the next start finds no such turn on the bridge and says so | pass | +| Storage unreadable at start: not treated as "not paired"; pairing over it is refused and the code is not spent | pass | +| Pairing that the phone cannot save: revoked on the bridge, not kept in memory | pass | +| Adapter unit test (fake timers): only a timely `true` is success; timeout and `false` are "not confirmed"; a stalled read is "unknown", not "empty" | pass | + +In the simulator, the real SDK host answered storage writes with a confirmation, so questions +were sent normally (the simulator suite would otherwise fail). **Whether the Even phone app +confirms `setLocalStorage` the same way, and how quickly, is unknown until it runs on a phone.** +If the phone never confirms a write, no question can be sent; the HUD would say "Could not save +your request on the phone". + +One consequence worth knowing: host calls are sent strictly one at a time, so while a storage +write is stuck, HUD updates queued behind it are not drawn until it completes. + +### CODY-006: state directory permissions + +`services/bridge/test/units.test.ts`: + +| Scenario | Result | +|---|---| +| Child process under umask 0022, state directory pre-created at 0755: after opening the database and creating WAL and SHM, directory 0700, database, WAL and SHM 0600 | pass | +| Pre-existing directories at 0750, 0777, 0711 and 0701 all end at exactly 0700 | pass | +| A directory that cannot be secured (`/tmp`, owned by another user): `StateDirectoryError` naming the directory, the required mode and the fix; no file created; the directory left unchanged | pass | +| A path whose parent is a file: refused | pass | +| Retained: new directory under umask 0022, and the check that no state file is ever group- or world-accessible during creation | pass | + +### Did the new tests have teeth? + +Eight ways of removing these two fixes were tried against the default suite; all eight were +caught (between 1 and 6 failing tests each). diff --git a/services/bridge/src/db.ts b/services/bridge/src/db.ts index 871bf34..2313ce1 100644 --- a/services/bridge/src/db.ts +++ b/services/bridge/src/db.ts @@ -1,5 +1,5 @@ import Database from 'better-sqlite3'; -import { chmodSync, closeSync, existsSync, mkdirSync, openSync } from 'node:fs'; +import { chmodSync, closeSync, existsSync, mkdirSync, openSync, statSync } from 'node:fs'; import { dirname } from 'node:path'; export type Db = Database.Database; @@ -87,14 +87,42 @@ export function secureDbFiles(path: string): void { for (const file of sidecars(path)) if (existsSync(file)) chmodSync(file, FILE_MODE); } +/** The state directory could not be made private. The message is written for the operator. */ +export class StateDirectoryError extends Error { + override name = 'StateDirectoryError'; +} + +/** + * Make the directory that holds the database owner-only (0700), whether it was just created + * or already existed, and confirm it. A directory that cannot be restricted (not ours, or on + * a filesystem without permissions) is refused: the bridge does not keep credentials where + * other users can list or replace files. + */ +export function secureStateDir(dir: string): void { + if (!existsSync(dir)) mkdirSync(dir, { recursive: true, mode: DIR_MODE }); + const explain = (why: string) => + new StateDirectoryError( + `The state directory ${dir} ${why}. The bridge keeps device credentials there and needs a ` + + `directory of its own, owned by the user it runs as, with mode 0700. ` + + `Create one (for example: install -d -m 0700 ${dir}) or point HERMEVEN_DB_PATH at one.`, + ); + let info = statSync(dir); + if (!info.isDirectory()) throw explain('is not a directory'); + if ((info.mode & 0o777) !== DIR_MODE) { + try { + chmodSync(dir, DIR_MODE); + } catch { + throw explain('is accessible to other users and could not be restricted'); + } + info = statSync(dir); + if ((info.mode & 0o777) !== DIR_MODE) throw explain('did not keep mode 0700 after it was set'); + } +} + export function openDb(path: string): Db { if (path !== ':memory:') { - const dir = dirname(path); - if (!existsSync(dir)) { - mkdirSync(dir, { recursive: true, mode: DIR_MODE }); - // mkdir's mode is masked by the umask; state the result explicitly. - chmodSync(dir, DIR_MODE); - } + // Before anything is created inside it. + secureStateDir(dirname(path)); // Create the file ourselves, owner-only, BEFORE SQLite opens it. SQLite gives the WAL and // SHM files the same permissions as the database file, so they are never world-readable, // not even for a moment. diff --git a/services/bridge/src/main.ts b/services/bridge/src/main.ts index 55d247e..b67fade 100644 --- a/services/bridge/src/main.ts +++ b/services/bridge/src/main.ts @@ -1,5 +1,6 @@ import { LOG_REDACT, createBridge } from './app.ts'; import { ConfigError, loadConfig } from './config.ts'; +import { StateDirectoryError } from './db.ts'; import { loadEnvFile } from './env.ts'; import { BuiltinWhisperStt } from './stt/builtinWhisper.ts'; @@ -49,6 +50,8 @@ async function main(): Promise { main().catch((err: unknown) => { // Configuration problems are operator-facing; never print the environment. - console.error(err instanceof ConfigError ? `Configuration error: ${err.message}` : err); + if (err instanceof ConfigError) console.error(`Configuration error: ${err.message}`); + else if (err instanceof StateDirectoryError) console.error(`Cannot start: ${err.message}`); + else console.error(err); process.exit(1); }); diff --git a/services/bridge/test/units.test.ts b/services/bridge/test/units.test.ts index c77920c..5451b9e 100644 --- a/services/bridge/test/units.test.ts +++ b/services/bridge/test/units.test.ts @@ -5,7 +5,7 @@ import { join } from 'node:path'; import { fileURLToPath } from 'node:url'; import { describe, expect, it } from 'vitest'; import { ConfigError, loadConfig } from '../src/config.ts'; -import { openDb } from '../src/db.ts'; +import { openDb, StateDirectoryError } from '../src/db.ts'; import { Devices } from '../src/devices.ts'; import { buildRunBody } from '../src/hermes/adapter.ts'; import { mapRunStatus } from '../src/hermes/runsAdapter.ts'; @@ -91,6 +91,86 @@ describe('state files are owner-only whatever the umask (CODY-006)', () => { } }); + it('a PRE-EXISTING state directory at 0755 is tightened to 0700 under umask 0022, with database, WAL and SHM at 0600', () => { + const root = mkdtempSync(join(tmpdir(), 'hermeven-perm-')); + const stateDir = join(root, 'state'); + const dbPath = join(stateDir, 'hermeven.sqlite'); + const script = ` + process.umask(0o022); + const fs = await import('node:fs'); + fs.mkdirSync(${JSON.stringify(stateDir)}); + fs.chmodSync(${JSON.stringify(stateDir)}, 0o755); + const m = (p) => (fs.statSync(p).mode & 0o777).toString(8); + const before = m(${JSON.stringify(stateDir)}); + const { openDb } = await import(${JSON.stringify(fileURLToPath(new URL('../src/db.ts', import.meta.url)))}); + const db = openDb(${JSON.stringify(dbPath)}); + db.prepare("INSERT INTO pairing_codes (code_hash, created_at, expires_at) VALUES ('x', 1, 2)").run(); + console.log(JSON.stringify({ umask: process.umask().toString(8), before, dir: m(${JSON.stringify(stateDir)}), db: m(${JSON.stringify(dbPath)}), wal: m(${JSON.stringify(dbPath + '-wal')}), shm: m(${JSON.stringify(dbPath + '-shm')}) })); + db.close(); + `; + try { + const out = execFileSync(process.execPath, ['--import', 'tsx', '--input-type=module', '-e', script], { + encoding: 'utf8', + cwd: fileURLToPath(new URL('..', import.meta.url)), + }); + expect(JSON.parse(out.trim().split('\n').at(-1)!)).toEqual({ umask: '22', before: '755', dir: '700', db: '600', wal: '600', shm: '600' }); + expect(mode(stateDir)).toBe(0o700); + } finally { + rmSync(root, { recursive: true, force: true }); + } + }); + + it('other loose directory modes (0750, 0777, 0711) are all tightened to exactly 0700', async () => { + const { chmodSync, mkdirSync } = await import('node:fs'); + for (const loose of [0o750, 0o777, 0o711, 0o701]) { + const root = mkdtempSync(join(tmpdir(), 'hermeven-perm-')); + const stateDir = join(root, 'state'); + mkdirSync(stateDir); + chmodSync(stateDir, loose); + try { + openDb(join(stateDir, 'hermeven.sqlite')).close(); + expect(mode(stateDir), loose.toString(8)).toBe(0o700); + expect(mode(join(stateDir, 'hermeven.sqlite'))).toBe(0o600); + } finally { + rmSync(root, { recursive: true, force: true }); + } + } + }); + + it('a directory that cannot be secured stops the bridge with an operator-facing error, and nothing is created in it', async () => { + const { existsSync, statSync: stat } = await import('node:fs'); + // A world-writable directory owned by someone else (root's /tmp) cannot be chmod-ed by us. + const shared = '/tmp'; + if (!existsSync(shared) || stat(shared).uid === process.getuid?.()) { + console.info('[units] NOT RUN: no directory owned by another user is available to test the refusal'); + return; + } + const dbPath = join(shared, `hermeven-refusal-test-${process.pid}.sqlite`); + let error: unknown; + try { + openDb(dbPath).close(); + } catch (err) { + error = err; + } + expect(error).toBeInstanceOf(StateDirectoryError); + expect((error as Error).message).toContain('/tmp'); + expect((error as Error).message).toMatch(/mode 0700/); + expect((error as Error).message).toMatch(/install -d -m 0700|HERMEVEN_DB_PATH/); + expect(existsSync(dbPath)).toBe(false); + expect(stat(shared).mode & 0o777).not.toBe(0o700); // and we did not change it + }); + + it('a path whose parent is a file is refused clearly', async () => { + const { writeFileSync } = await import('node:fs'); + const root = mkdtempSync(join(tmpdir(), 'hermeven-perm-')); + try { + writeFileSync(join(root, 'not-a-dir'), 'x'); + expect(() => openDb(join(root, 'not-a-dir', 'db.sqlite'))).toThrow(); + } finally { + rmSync(root, { recursive: true, force: true }); + } + }); + it('an existing database with loose permissions is tightened when opened', async () => { const { chmodSync } = await import('node:fs'); const root = mkdtempSync(join(tmpdir(), 'hermeven-perm-')); diff --git a/tests/fakes/fakeDevice.ts b/tests/fakes/fakeDevice.ts index 40d4faa..a3520cf 100644 --- a/tests/fakes/fakeDevice.ts +++ b/tests/fakes/fakeDevice.ts @@ -1,6 +1,6 @@ import type { HudFrame } from '../../apps/even-client/src/core/hud.ts'; import type { DeviceEvent } from '../../apps/even-client/src/device/events.ts'; -import type { DevicePort } from '../../apps/even-client/src/device/port.ts'; +import type { DevicePort, StorageRead } from '../../apps/even-client/src/device/port.ts'; /** * TEST FAKE. Not glasses, not the simulator. @@ -51,11 +51,17 @@ export class FakeDevice implements DevicePort { async requestExit(): Promise { this.exitRequests += 1; } - async storageGet(key: string): Promise { - return this.storage.get(key) ?? ''; + /** Set to make storage writes report "not confirmed" without writing. */ + storageWritesFail = false; + storageReadsFail = false; + async storageGet(key: string): Promise { + if (this.storageReadsFail) return { ok: false }; + return { ok: true, value: this.storage.get(key) ?? '' }; } - async storageSet(key: string, value: string): Promise { + async storageSet(key: string, value: string): Promise { + if (this.storageWritesFail) return false; this.storage.set(key, value); + return true; } // ---- test controls diff --git a/tests/integration/clientSecurity.test.ts b/tests/integration/clientSecurity.test.ts index 1dd4024..2a3ba5f 100644 --- a/tests/integration/clientSecurity.test.ts +++ b/tests/integration/clientSecurity.test.ts @@ -215,7 +215,7 @@ describe('CODY-002: host calls stay serialised and a late microphone start ends await tick(); expect(host.calls.map((x) => x.name)).toEqual(['get']); await vi.advanceTimersByTimeAsync(CALL_TIMEOUT_MS + 1); - expect(await a).toBe(''); // bounded for the caller + expect(await a).toEqual({ ok: false }); // bounded for the caller, and reported as unknown await b; await c; expect(host.calls.map((x) => x.name)).toEqual(['get']); // still only the stuck call at the host @@ -227,4 +227,40 @@ describe('CODY-002: host calls stay serialised and a late microphone start ends expect(host.calls.map((x) => x.name)).toEqual(['get', 'set', 'exit']); expect(host.maxInFlight()).toBe(1); }); + + it('storage: only a timely `true` from the host is success; a timeout or `false` is "not confirmed", a stalled read is "unknown"', async () => { + const host = fakeHost(); + const device = new EvenDevice(host.bridge as never); + + const confirmed = device.storageSet('k', 'v'); + await tick(); + host.pending()[0]!.resolve(true); + expect(await confirmed).toBe(true); + + const refused = device.storageSet('k', 'v'); + await tick(); + host.pending()[0]!.resolve(false); + expect(await refused).toBe(false); + + const stalled = device.storageSet('k', 'v'); + await vi.advanceTimersByTimeAsync(CALL_TIMEOUT_MS + 1); + expect(await stalled).toBe(false); // the wait ran out; that is not a successful write + host.pending()[0]!.resolve(true); // ...even though the host completes it later + await tick(); + + const read = device.storageGet('k'); + await tick(); + host.pending()[0]!.resolve('value'); + expect(await read).toEqual({ ok: true, value: 'value' }); + + const empty = device.storageGet('k'); + await tick(); + host.pending()[0]!.resolve(''); + expect(await empty).toEqual({ ok: true, value: '' }); + + const unknown = device.storageGet('k'); + await vi.advanceTimersByTimeAsync(CALL_TIMEOUT_MS + 1); + expect(await unknown).toEqual({ ok: false }); + expect(host.maxInFlight()).toBe(1); + }); }); diff --git a/tests/integration/durableRequestId.test.ts b/tests/integration/durableRequestId.test.ts new file mode 100644 index 0000000..befe5fe --- /dev/null +++ b/tests/integration/durableRequestId.test.ts @@ -0,0 +1,316 @@ +import { measureTextWrap } from '@evenrealities/pretext'; +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { Controller, type Snapshot } from '../../apps/even-client/src/core/controller.ts'; +import { renderHud } from '../../apps/even-client/src/core/hud.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'; + +/** + * CODY-003, at the production seam: the REAL EvenDevice adapter (the one that ships), driven + * by a stand-in Even host whose `setLocalStorage` settles only when the test says so. The + * bridge is real; Hermes is the test fake. No glasses are involved. + * + * What is being proven: a request is never sent until the phone has positively confirmed + * storing its id, and a wait that merely ran out is not treated as confirmation. + */ +const STORAGE_KEY = 'hermeven.v1'; +const ADAPTER_TIMEOUT_MS = 120; + +/** Stand-in for the Even app host. Storage here is the "durable" copy that survives a page restart. */ +class FakeEvenHost { + readonly durable = new Map(); + stallWrites = false; + private held: Array<() => void> = []; + writesStarted = 0; + texts: string[] = []; + private hub = new Set<(event: unknown) => void>(); + + readonly bridge = { + createStartUpPageContainer: async () => 0, + textContainerUpgrade: async (update: { content?: string }) => { + this.texts.push(String(update.content ?? '')); + return true; + }, + audioControl: async () => true, + shutDownPageContainer: async () => true, + getLocalStorage: async (key: string) => this.durable.get(key) ?? '', + setLocalStorage: (key: string, value: string) => + new Promise((resolve) => { + this.writesStarted += 1; + const apply = () => { + this.durable.set(key, value); + resolve(true); + }; + if (this.stallWrites) this.held.push(apply); + else apply(); + }), + onEvenHubEvent: (cb: (event: unknown) => void) => { + this.hub.add(cb); + return () => this.hub.delete(cb); + }, + onDeviceStatusChanged: () => () => undefined, + }; + + heldWrites(): number { + return this.held.length; + } + /** The host finally completes the writes it was sitting on, in order. */ + releaseWrites(): void { + for (const apply of this.held.splice(0)) apply(); + } + stored(): { activeRequestId: string | null; activeCancelled?: boolean; token: string } { + return JSON.parse(this.durable.get(STORAGE_KEY) || '{}'); + } + tap(): void { + for (const cb of this.hub) cb({ sysEvent: {} }); // a tap arrives with no eventType + } + doubleTap(): void { + for (const cb of this.hub) cb({ sysEvent: { eventType: 3 } }); + } +} + +let h: Harness; +let host: FakeEvenHost; +let controller: Controller; +let snapshot: Snapshot; +let net: { dropReplies: boolean; turnPosts: string[] }; + +function makeController(): 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, + submitAttempts: 2, + submitRetryMs: 20, + makeClient: (baseUrl, token) => + new BridgeClient({ + baseUrl, + token, + timeoutMs: 500, + fetchImpl: async (input, init) => { + const url = new URL(String(input)); + if (init?.method === 'POST' && url.pathname === '/v1/turns') { + net.turnPosts.push(JSON.parse(String(init.body)).request_id); + } + const res = await fetch(input, init); + if (net.dropReplies) { + await res.arrayBuffer(); + throw new TypeError('reply lost'); + } + return res; + }, + }), + onChange: (s) => { + snapshot = s; + }, + }); +} + +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}/${snapshot?.state.disconnectedFrom}`); + await new Promise((r) => setTimeout(r, 10)); + } +} +const phase = () => snapshot.state.phase; +const hud = () => renderHud(snapshot.state, Date.now()).body; +const bridgeTurn = (id: string) => h.bridge.db.prepare('SELECT state, outcome, cancel_requested FROM turns WHERE request_id = ?').get(id) as + | { state: string; outcome: string | null; cancel_requested: number } + | undefined; + +/** Pair, and ask one ordinary question so a conversation exists. */ +async function ready(): Promise { + host = new FakeEvenHost(); + controller = makeController(); + await controller.start(); + const { code } = h.bridge.devices.createPairingCode(); + await controller.pair(h.url, code, 'production-adapter'); + controller.askText('hello'); + await until('first answer', () => phase() === 'answer'); + expect(h.hermes.executions).toBe(1); + net.turnPosts.length = 0; +} + +/** Storage stalls beyond the adapter timeout: the request must be held back, provably unsent. */ +async function stallThenAsk(question: string): Promise { + host.stallWrites = true; + controller.askText(question); + await until('held back for storage', () => phase() === 'disconnected' && snapshot.state.disconnectedFrom === 'storage'); + const requestId = snapshot.state.requestId!; + // Well past the adapter's timeout, and still nothing has gone to the bridge. + await new Promise((r) => setTimeout(r, ADAPTER_TIMEOUT_MS * 2)); + expect(host.heldWrites()).toBeGreaterThanOrEqual(1); + expect(net.turnPosts).toEqual([]); + expect(bridgeTurn(requestId)).toBeUndefined(); + expect(h.hermes.executions).toBe(1); + // The durable copy does not have the id: the caller's timeout was not a successful write. + expect(host.stored().activeRequestId).toBeNull(); + // Before admission, "nothing has been sent" is simply true. + expect(hud()).toContain('Nothing has been sent'); + return requestId; +} + +async function restartPage(): Promise { + await controller.stop(); + controller = makeController(); // a new page: new adapter, same host storage + await controller.start(); +} + +beforeEach(async () => { + net = { dropReplies: false, turnPosts: [] }; + h = await createHarness(); +}); +afterEach(async () => { + await controller?.stop(); + host?.releaseWrites(); + await h?.close(); +}); + +describe('CODY-003 with the production EvenDevice adapter and a stalled host storage write', () => { + it('stalled storage: zero submits. Confirmed storage, admitted, reply dropped, page restart: same id, one execution, never a false "not sent"', async () => { + await ready(); + h.hermes.next({ kind: 'complete', afterMs: 400, output: 'invoice paid once' }); + const requestId = await stallThenAsk('pay the invoice'); + + // A retry while storage is still stuck is held back again, under the same request id. + host.tap(); + await new Promise((r) => setTimeout(r, ADAPTER_TIMEOUT_MS * 2)); + expect(snapshot.state.requestId).toBe(requestId); + expect(snapshot.state.disconnectedFrom).toBe('storage'); + expect(net.turnPosts).toEqual([]); + + // The host recovers and completes the writes it was holding. Persistence is now real. + host.stallWrites = false; + host.releaseWrites(); + await until('id durable on the host', () => host.stored().activeRequestId === requestId); + expect(net.turnPosts).toEqual([]); // a late write landing must not, by itself, send anything + + // Deliberate retry: admitted by the bridge, but every reply is lost. + net.dropReplies = true; + host.tap(); + await until('ambiguous after admission', () => phase() === 'disconnected' && snapshot.state.disconnectedFrom === 'bridge'); + await until('admitted and running', () => h.hermes.executions === 2); + expect(new Set(net.turnPosts)).toEqual(new Set([requestId])); // the same immutable id on every attempt + expect(bridgeTurn(requestId)).toBeDefined(); + expect(host.stored().activeRequestId).toBe(requestId); + // After admission the HUD makes no claim that the request was not sent. + expect(hud()).not.toMatch(/nothing has been sent|not been sent|was not sent/i); + expect(hud()).toContain('not confirmed yet'); + const textsAtAdmission = host.texts.length; + + // The page dies and restarts; only host storage survives. + net.dropReplies = false; + await restartPage(); + await until('answer after restart', () => phase() === 'answer'); + expect(snapshot.lastTurn!.request_id).toBe(requestId); + expect(snapshot.lastTurn!.answer_text).toBe('invoice paid once'); + expect(h.hermes.executions).toBe(2); // "hello" plus exactly one run of this request + expect(h.hermes.requests.filter((r) => r.method === 'POST' && r.path === '/v1/runs')).toHaveLength(2); + expect(net.turnPosts.filter((id) => id === requestId).length).toBe(net.turnPosts.length); + // Nothing drawn on the glasses after admission said "not sent" either. + for (const text of host.texts.slice(textsAtAdmission)) expect(text).not.toMatch(/nothing has been sent|not been sent/i); + await until('slot cleared durably', () => host.stored().activeRequestId === null); + }); + + it('cancellation remains possible after the same sequence and a restart', async () => { + await ready(); + h.hermes.next({ kind: 'hang' }); + const requestId = await stallThenAsk('start the long job'); + host.stallWrites = false; + host.releaseWrites(); + await until('id durable on the host', () => host.stored().activeRequestId === requestId); + net.dropReplies = true; + host.tap(); + await until('admitted and running', () => h.hermes.executions === 2); + await until('ambiguous', () => phase() === 'disconnected' && snapshot.state.disconnectedFrom === 'bridge'); + + net.dropReplies = false; + await restartPage(); + await until('re-attached', () => phase() === 'thinking' && snapshot.state.requestId === requestId); + + host.doubleTap(); + expect(phase()).toBe('cancelled'); + await until('Hermes asked to stop', () => h.hermes.requests.some((r) => r.path.endsWith('/stop'))); + await until('turn settled as cancelled', () => bridgeTurn(requestId)?.state === 'done'); + expect(bridgeTurn(requestId)).toEqual({ state: 'done', outcome: 'cancelled', cancel_requested: 1 }); + expect(h.hermes.executions).toBe(2); + await until('slot cleared durably', () => host.stored().activeRequestId === null); + }); + + it('cancelling while still held back for storage sends nothing and leaves nothing on the bridge', async () => { + await ready(); + const requestId = await stallThenAsk('never mind'); + host.doubleTap(); + expect(phase()).toBe('cancelled'); + host.stallWrites = false; + host.releaseWrites(); + await new Promise((r) => setTimeout(r, 300)); + expect(net.turnPosts).toEqual([]); + expect(bridgeTurn(requestId)).toBeUndefined(); + expect(h.hermes.executions).toBe(1); + // And the app is usable again afterwards. + controller.askText('something else'); + await until('answer', () => phase() === 'answer'); + expect(h.hermes.executions).toBe(2); + }); + + it('a host that answers the write with false (refused, not timed out) also holds the request back', async () => { + await ready(); + const realSet = host.bridge.setLocalStorage; + host.bridge.setLocalStorage = async () => false; + controller.askText('refused write'); + await until('held back', () => phase() === 'disconnected' && snapshot.state.disconnectedFrom === 'storage'); + expect(net.turnPosts).toEqual([]); + host.bridge.setLocalStorage = realSet; + host.tap(); + await until('answer', () => phase() === 'answer'); + expect(net.turnPosts).toHaveLength(1); + expect(h.hermes.executions).toBe(2); + }); + + it('if the page dies while the write is still stalled, the late write is harmless: nothing ran, and the next start says so', async () => { + await ready(); + const requestId = await stallThenAsk('lost with the page'); + await controller.stop(); + // The host finishes the write after the page is gone. + host.stallWrites = false; + host.releaseWrites(); + expect(host.stored().activeRequestId).toBe(requestId); + controller = makeController(); + await controller.start(); + await until('confirmed absent', () => phase() === 'error'); + expect(snapshot.state.error).toMatchObject({ code: 'not_delivered', retryable: true }); + expect(bridgeTurn(requestId)).toBeUndefined(); + expect(h.hermes.executions).toBe(1); + }); +}); + +describe('storage results are explicit at the device boundary', () => { + it('unreadable storage at start is not mistaken for "not paired", and pairing over it is refused', async () => { + host = new FakeEvenHost(); + host.bridge.getLocalStorage = () => new Promise(() => undefined); // never answers + controller = makeController(); + await controller.start(); + expect(phase()).toBe('unpaired'); + expect(snapshot.state.storageFault).toBe(true); + expect(hud()).toContain('Saved settings could not be read'); + const { code } = h.bridge.devices.createPairingCode(); + await expect(controller.pair(h.url, code, 'x')).rejects.toThrow(/could not be read/); + expect(h.bridge.devices.list()).toHaveLength(0); // the pairing code was not even spent + }); + + it('a pairing the phone cannot save is undone on the bridge rather than kept in memory only', async () => { + host = new FakeEvenHost(); + controller = makeController(); + await controller.start(); + host.stallWrites = true; + const { code } = h.bridge.devices.createPairingCode(); + await expect(controller.pair(h.url, code, 'x')).rejects.toThrow(/could not save the pairing/); + expect(snapshot?.paired ?? false).toBe(false); + const [device] = h.bridge.devices.list(); + expect(device!.revoked_at).not.toBeNull(); + }); +});