Address Cody review round 2: all ten findings (CODY-001 to CODY-010)
CODY-001 Bridge URL must be HTTPS (HTTP only to loopback), in the client and
in manifest generation.
CODY-002 Even host calls stay serialised until the SDK call really settles;
a microphone start that completes after its timeout is followed by
a stop.
CODY-003 Request id is stored before the first submit and cleared only on a
definitive answer; lost replies are treated as ambiguous and
reconciled under the same id; HUD no longer claims "not sent".
CODY-004 Revoking a device cancels its in-flight turns, aborts
transcription and asks Hermes to stop, from HTTP and CLI paths.
CODY-005 Speech model pinned to a commit with per-file SHA-256; fetched and
verified ahead of time; verified on every load; never downloaded
at run time; no unpinned configuration.
CODY-006 State directory 0700, database/WAL/SHM 0600 regardless of umask.
CODY-007 credential_expired handled like unauthorized on every path.
CODY-008 Approval wait start and paused agent deadline persisted and
restored across restarts (schema v2).
CODY-009 Exactly one conversation create per epoch, sent in sequence, with
stale results dropped before persistence.
CODY-010 Wrong pairing guesses no longer consume the outstanding code;
failures are indistinguishable.
Checks: typecheck clean; npm test 182 passed; client build ok;
test:real-stt 11 passed (including with no network); 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:
@@ -24,11 +24,20 @@ if (origin !== raw) {
|
||||
console.error(`[manifest] HERMEVEN_BRIDGE_ORIGIN must be a bare origin (scheme://host[:port]), got a path or trailing slash.`);
|
||||
process.exit(1);
|
||||
}
|
||||
if (!origin.startsWith('https://')) {
|
||||
console.warn('[manifest] The bridge origin is not https. Acceptable only for a local development build.');
|
||||
// Same rule as the app enforces at run time (src/net/bridgeClient.ts): HTTPS, or HTTP to
|
||||
// loopback for the simulator. A packaged app must never be allowed to send the device
|
||||
// credential and recordings over plain HTTP to a LAN or public host.
|
||||
const { protocol, hostname } = new URL(origin);
|
||||
const loopback = hostname === 'localhost' || hostname === '[::1]' || /^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(hostname);
|
||||
if (protocol !== 'https:' && !(protocol === 'http:' && loopback)) {
|
||||
console.error('[manifest] HERMEVEN_BRIDGE_ORIGIN must be https:// (plain http is accepted only for loopback).');
|
||||
process.exit(1);
|
||||
}
|
||||
if (protocol === 'http:') {
|
||||
console.warn('[manifest] Loopback HTTP origin: this build is for the simulator only and cannot work on a phone.');
|
||||
}
|
||||
const template = readFileSync(resolve(here, '../app.template.json'), 'utf8');
|
||||
const out = resolve(here, '../dist-manifest/app.json');
|
||||
const out = process.env.HERMEVEN_MANIFEST_OUT ?? resolve(here, '../dist-manifest/app.json');
|
||||
mkdirSync(dirname(out), { recursive: true });
|
||||
writeFileSync(out, template.replace('__HERMEVEN_BRIDGE_ORIGIN__', origin));
|
||||
console.log(`[manifest] wrote ${out}`);
|
||||
|
||||
@@ -16,8 +16,14 @@ interface Stored {
|
||||
tokenExpiresAt: string;
|
||||
pairingExpiresAt: string;
|
||||
conversationId: string | null;
|
||||
/** A turn that was in flight; re-attached by polling after a restart, never resubmitted. */
|
||||
/**
|
||||
* The request id of a turn that may exist on the bridge. Written BEFORE the first submit and
|
||||
* cleared only on a definitive answer: a terminal result, a definite rejection, or the bridge
|
||||
* confirming it has no such turn. After a restart it is re-attached by polling.
|
||||
*/
|
||||
activeRequestId: string | null;
|
||||
/** The user abandoned that turn but the bridge has not yet acknowledged the cancel. */
|
||||
activeCancelled: boolean;
|
||||
}
|
||||
|
||||
export interface DiagEntry {
|
||||
@@ -81,6 +87,8 @@ export class Controller {
|
||||
private pending: PendingInput | null = null;
|
||||
private lastTurn: TurnResult | null = null;
|
||||
private hudReady = false;
|
||||
private creating: { epoch: number; promise: Promise<string> } | null = null;
|
||||
private createChain: Promise<void> = Promise.resolve();
|
||||
private stopped = false;
|
||||
private ticker: ReturnType<typeof setInterval> | null = null;
|
||||
private readonly log: DiagEntry[] = [];
|
||||
@@ -134,13 +142,16 @@ export class Controller {
|
||||
}
|
||||
}
|
||||
}
|
||||
// A turn the user had abandoned is not shown again; its cancel is simply delivered now.
|
||||
const abandoned = this.stored?.activeCancelled ? this.stored.activeRequestId : null;
|
||||
this.dispatch({
|
||||
type: 'init',
|
||||
paired: this.stored !== null,
|
||||
conversationId: this.stored?.conversationId ?? null,
|
||||
captureMaxSeconds,
|
||||
resumeRequestId: this.stored?.activeRequestId ?? null,
|
||||
resumeRequestId: abandoned ? null : (this.stored?.activeRequestId ?? null),
|
||||
});
|
||||
if (abandoned) void this.cancelTurn(abandoned);
|
||||
}
|
||||
|
||||
/** Stop for good: every pending retry and poll loop winds down and nothing more is drawn or emitted. */
|
||||
@@ -180,6 +191,7 @@ export class Controller {
|
||||
pairingExpiresAt: credential.pairing_expires_at,
|
||||
conversationId: null,
|
||||
activeRequestId: null,
|
||||
activeCancelled: false,
|
||||
};
|
||||
await this.save();
|
||||
this.note('pairing', `paired as ${credential.device_id}`);
|
||||
@@ -210,7 +222,13 @@ export class Controller {
|
||||
|
||||
async renew(): Promise<void> {
|
||||
if (!this.client || !this.stored) return;
|
||||
const credential = await this.client.renew();
|
||||
let credential;
|
||||
try {
|
||||
credential = await this.client.renew();
|
||||
} catch (err) {
|
||||
if (err instanceof BridgeApiError) await this.afterAuthFailure(err);
|
||||
throw err;
|
||||
}
|
||||
this.client.token = credential.token;
|
||||
this.stored = { ...this.stored, token: credential.token, tokenExpiresAt: credential.token_expires_at };
|
||||
await this.save();
|
||||
@@ -224,6 +242,7 @@ export class Controller {
|
||||
this.status = await this.client.device();
|
||||
} catch (err) {
|
||||
this.note('bridge', `status check failed: ${describe(err)}`);
|
||||
if (err instanceof BridgeApiError) await this.afterAuthFailure(err);
|
||||
}
|
||||
this.emit();
|
||||
}
|
||||
@@ -275,7 +294,7 @@ export class Controller {
|
||||
case 'cancel_turn':
|
||||
return await this.cancelTurn(effect.requestId);
|
||||
case 'create_conversation':
|
||||
return await this.createConversation(effect.generation);
|
||||
return await this.createConversation(effect.epoch);
|
||||
case 'exit_dialog':
|
||||
return await this.device.requestExit();
|
||||
}
|
||||
@@ -296,9 +315,15 @@ export class Controller {
|
||||
this.capture = capture;
|
||||
this.micOpen = true;
|
||||
const ok = await this.device.startMic();
|
||||
if (this.capture !== capture) {
|
||||
// Cancelled while the microphone was opening.
|
||||
if (!this.capture) await this.closeMic();
|
||||
if (this.capture !== capture || this.stale(generation)) {
|
||||
// Cancelled while the microphone was opening. Stop unconditionally unless a newer
|
||||
// capture now owns the microphone: a stop that turns out to be redundant is harmless.
|
||||
if (!this.capture || this.capture === capture) {
|
||||
this.capture = null;
|
||||
this.micOpen = false;
|
||||
this.stopTicker();
|
||||
await this.device.stopMic();
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (!ok) {
|
||||
@@ -364,24 +389,64 @@ export class Controller {
|
||||
return this.stopped || generation !== this.state.generation;
|
||||
}
|
||||
|
||||
private async ensureConversation(): Promise<string> {
|
||||
if (this.state.conversationId) return this.state.conversationId;
|
||||
const created = await this.client!.createConversation();
|
||||
if (this.stored) {
|
||||
this.stored = { ...this.stored, conversationId: created.conversation_id };
|
||||
await this.save();
|
||||
}
|
||||
this.dispatch({ type: 'conversation_created', generation: this.state.generation, conversationId: created.conversation_id });
|
||||
return created.conversation_id;
|
||||
/**
|
||||
* The current conversation id, creating one if there is none. At most one create is in
|
||||
* flight per conversation epoch, and creates are sent strictly one after another, so the
|
||||
* bridge and the app can never disagree about which conversation is the live one: the last
|
||||
* create the app sent is the last one the bridge processed.
|
||||
*/
|
||||
private ensureConversation(): Promise<string> {
|
||||
if (this.state.conversationId) return Promise.resolve(this.state.conversationId);
|
||||
const epoch = this.state.conversationEpoch;
|
||||
if (this.creating && this.creating.epoch === epoch) return this.creating.promise;
|
||||
|
||||
const client = this.client;
|
||||
const promise = this.createChain.then(async () => {
|
||||
if (!client || this.stopped || epoch !== this.state.conversationEpoch) throw new StaleConversationError();
|
||||
const created = await client.createConversation();
|
||||
// Checked BEFORE anything is stored: a result for a conversation the user has since
|
||||
// replaced (or for a pairing that has ended) is dropped, not persisted.
|
||||
if (this.stopped || epoch !== this.state.conversationEpoch || this.client !== client) throw new StaleConversationError();
|
||||
if (this.stored) {
|
||||
this.stored = { ...this.stored, conversationId: created.conversation_id };
|
||||
await this.save();
|
||||
}
|
||||
this.note('conversation', `conversation ${created.conversation_id}`);
|
||||
this.dispatch({ type: 'conversation_created', epoch, conversationId: created.conversation_id });
|
||||
return created.conversation_id;
|
||||
});
|
||||
this.createChain = promise.then(
|
||||
() => undefined,
|
||||
() => undefined,
|
||||
);
|
||||
const entry = { epoch, promise };
|
||||
this.creating = entry;
|
||||
void this.createChain.then(() => {
|
||||
if (this.creating === entry) this.creating = null;
|
||||
});
|
||||
return promise;
|
||||
}
|
||||
|
||||
private async submit(generation: number, requestId: string): Promise<void> {
|
||||
const pending = this.pending;
|
||||
if (!this.client || !pending || pending.requestId !== requestId) return;
|
||||
// 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);
|
||||
for (let attempt = 1; ; attempt++) {
|
||||
if (this.stale(generation)) return;
|
||||
try {
|
||||
const conversationId = await this.ensureConversation();
|
||||
let conversationId: string;
|
||||
try {
|
||||
conversationId = await this.ensureConversation();
|
||||
} catch (err) {
|
||||
if (!(err instanceof StaleConversationError)) throw err;
|
||||
// The conversation was replaced while it was being created; use the new one.
|
||||
if (this.stale(generation)) return;
|
||||
attempt -= 1;
|
||||
continue;
|
||||
}
|
||||
if (this.stale(generation)) return;
|
||||
const base = { requestId, conversationId, locale: this.options.locale };
|
||||
// The same request id on every attempt: the bridge deduplicates, so a retry after a
|
||||
@@ -396,15 +461,16 @@ export class Controller {
|
||||
void this.cancelTurn(requestId);
|
||||
return;
|
||||
}
|
||||
await this.setActiveRequest(requestId);
|
||||
this.note('turn', `accepted ${requestId}${result.replayed ? ' (duplicate ignored by bridge)' : ''}`);
|
||||
this.onResult(generation, result);
|
||||
if (!result.terminal) await this.poll(generation, requestId);
|
||||
return;
|
||||
} catch (err) {
|
||||
if (err instanceof BridgeApiError) {
|
||||
// A contract error is a definite "this turn was not created".
|
||||
this.note('turn', `rejected: ${err.body.code}`);
|
||||
this.pending = null;
|
||||
await this.setActiveRequest(null);
|
||||
if (!this.stale(generation)) this.dispatch({ type: 'turn_rejected', generation, error: this.hudError(err) });
|
||||
await this.afterAuthFailure(err);
|
||||
return;
|
||||
@@ -412,6 +478,8 @@ export class Controller {
|
||||
if (!(err instanceof BridgeNetworkError)) throw err;
|
||||
this.note('bridge', `submit attempt ${attempt} failed: ${err.message}`);
|
||||
if (attempt >= this.submitAttempts) {
|
||||
// Ambiguous: a request may have been admitted even though no reply came back. The
|
||||
// request id stays stored; a retry or a restart reconciles under the same id.
|
||||
if (!this.stale(generation)) this.dispatch({ type: 'network_lost', generation, stage: 'submit' });
|
||||
return;
|
||||
}
|
||||
@@ -439,8 +507,13 @@ export class Controller {
|
||||
if (this.stale(generation)) return;
|
||||
if (err instanceof BridgeApiError) {
|
||||
this.note('turn', `status rejected: ${err.body.code}`);
|
||||
// not_found is the bridge confirming the turn does not exist: it was never admitted.
|
||||
await this.setActiveRequest(null);
|
||||
this.dispatch({ type: 'turn_rejected', generation, error: this.hudError(err) });
|
||||
const error: HudError =
|
||||
err.body.code === 'not_found'
|
||||
? { code: 'not_delivered', hud: 'Your last request did not reach the bridge. Please ask again.', retryable: true }
|
||||
: this.hudError(err);
|
||||
this.dispatch({ type: 'turn_rejected', generation, error });
|
||||
await this.afterAuthFailure(err);
|
||||
return;
|
||||
}
|
||||
@@ -458,7 +531,7 @@ export class Controller {
|
||||
let pages: string[] | null = null;
|
||||
if (result.terminal) {
|
||||
this.lastTurn = result;
|
||||
void this.setActiveRequest(null);
|
||||
void this.clearActiveRequest(result.request_id);
|
||||
this.note(
|
||||
'turn',
|
||||
`done ${result.request_id}: ${result.outcome}${result.error ? ` (${result.error.code})` : ''}` +
|
||||
@@ -479,42 +552,48 @@ export class Controller {
|
||||
}
|
||||
|
||||
private async cancelTurn(requestId: string): Promise<void> {
|
||||
await this.setActiveRequest(null);
|
||||
if (!this.client) return;
|
||||
// Keep the id, marked as abandoned, until the bridge acknowledges the cancel. If the cancel
|
||||
// cannot be delivered now it is retried on the next start, so an abandoned turn is not
|
||||
// left running unnoticed and is never shown to the user again.
|
||||
if (this.stored && this.stored.activeRequestId === requestId && !this.stored.activeCancelled) {
|
||||
this.stored = { ...this.stored, activeCancelled: true };
|
||||
await this.save();
|
||||
}
|
||||
const client = this.client;
|
||||
if (!client) return;
|
||||
for (let attempt = 1; attempt <= 3; attempt++) {
|
||||
try {
|
||||
const result = await this.client.cancelTurn(requestId);
|
||||
const result = await client.cancelTurn(requestId);
|
||||
this.note('turn', `cancel requested for ${requestId}; bridge state ${result.state}`);
|
||||
await this.clearActiveRequest(requestId);
|
||||
return;
|
||||
} catch (err) {
|
||||
if (err instanceof BridgeApiError) {
|
||||
// not_found: the request never reached the bridge, so there is nothing to cancel.
|
||||
this.note('turn', `cancel answered ${err.body.code}`);
|
||||
await this.clearActiveRequest(requestId);
|
||||
await this.afterAuthFailure(err);
|
||||
return;
|
||||
}
|
||||
if (this.stopped) return;
|
||||
await sleep(this.submitRetryMs);
|
||||
}
|
||||
}
|
||||
this.note('turn', `cancel for ${requestId} could not be delivered; the agent may still be running`);
|
||||
this.note('turn', `cancel for ${requestId} could not be delivered yet; it will be retried`);
|
||||
}
|
||||
|
||||
private async createConversation(generation: number): Promise<void> {
|
||||
if (!this.client) return;
|
||||
private async createConversation(epoch: number): Promise<void> {
|
||||
if (!this.client || epoch !== this.state.conversationEpoch) return;
|
||||
try {
|
||||
const created = await this.client.createConversation();
|
||||
if (this.stored) {
|
||||
this.stored = { ...this.stored, conversationId: created.conversation_id };
|
||||
await this.save();
|
||||
}
|
||||
this.note('conversation', `new conversation ${created.conversation_id}`);
|
||||
this.dispatch({ type: 'conversation_created', generation, conversationId: created.conversation_id });
|
||||
await this.ensureConversation();
|
||||
} catch (err) {
|
||||
if (err instanceof StaleConversationError) return;
|
||||
const error: HudError =
|
||||
err instanceof BridgeApiError
|
||||
? this.hudError(err)
|
||||
: { code: 'network', hud: 'Could not reach the bridge.', retryable: true };
|
||||
this.note('conversation', `create failed: ${describe(err)}`);
|
||||
this.dispatch({ type: 'conversation_failed', generation, error });
|
||||
this.dispatch({ type: 'conversation_failed', epoch, error });
|
||||
if (err instanceof BridgeApiError) await this.afterAuthFailure(err);
|
||||
}
|
||||
}
|
||||
@@ -588,8 +667,11 @@ export class Controller {
|
||||
}
|
||||
|
||||
private async afterAuthFailure(err: BridgeApiError): Promise<void> {
|
||||
if (err.body.code !== 'unauthorized') return;
|
||||
// Revoked or unknown credential: holding on to it helps nobody.
|
||||
if (err.body.code !== 'unauthorized' && err.body.code !== 'credential_expired') return;
|
||||
if (!this.stored) return;
|
||||
// Revoked, unknown or expired: the stored credential can no longer do anything (an expired
|
||||
// token cannot even renew itself), so it is forgotten and the pairing screen comes back.
|
||||
this.note('auth', `credential no longer accepted: ${err.body.code}`);
|
||||
await this.forget();
|
||||
this.dispatch({ type: 'unpaired' });
|
||||
}
|
||||
@@ -607,11 +689,16 @@ export class Controller {
|
||||
}
|
||||
|
||||
private async setActiveRequest(requestId: string | null): Promise<void> {
|
||||
if (!this.stored || this.stored.activeRequestId === requestId) return;
|
||||
this.stored = { ...this.stored, activeRequestId: requestId };
|
||||
if (!this.stored || (this.stored.activeRequestId === requestId && !this.stored.activeCancelled)) return;
|
||||
this.stored = { ...this.stored, activeRequestId: requestId, activeCancelled: false };
|
||||
await this.save();
|
||||
}
|
||||
|
||||
/** Clear the stored request id only if it is still this one (a newer turn may own the slot). */
|
||||
private async clearActiveRequest(requestId: string): Promise<void> {
|
||||
if (this.stored?.activeRequestId === requestId) await this.setActiveRequest(null);
|
||||
}
|
||||
|
||||
private async load(): Promise<Stored | null> {
|
||||
try {
|
||||
const raw = await this.device.storageGet(STORAGE_KEY);
|
||||
@@ -626,6 +713,7 @@ export class Controller {
|
||||
pairingExpiresAt: String(parsed.pairingExpiresAt ?? ''),
|
||||
conversationId: typeof parsed.conversationId === 'string' ? parsed.conversationId : null,
|
||||
activeRequestId: typeof parsed.activeRequestId === 'string' ? parsed.activeRequestId : null,
|
||||
activeCancelled: parsed.activeCancelled === true,
|
||||
};
|
||||
} catch {
|
||||
return null;
|
||||
@@ -670,6 +758,11 @@ export function pollDelay(elapsedMs: number): number {
|
||||
return 1000;
|
||||
}
|
||||
|
||||
/** The conversation this create was for has been replaced; its result must not be used. */
|
||||
class StaleConversationError extends Error {
|
||||
override name = 'StaleConversationError';
|
||||
}
|
||||
|
||||
function describe(err: unknown): string {
|
||||
if (err instanceof BridgeApiError) return `${err.body.code} (HTTP ${err.status})`;
|
||||
if (err instanceof Error) return `${err.name}: ${err.message}`;
|
||||
|
||||
@@ -93,7 +93,9 @@ export function renderHud(state: AppState, nowMs: number): HudFrame {
|
||||
return { body: 'Glasses disconnected.', status: 'Reconnect to continue' };
|
||||
}
|
||||
return state.canResend
|
||||
? { body: 'No connection to the bridge.\n\nYour request has not been sent.', status: 'Tap: retry · Double-tap: discard' }
|
||||
? // 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.
|
||||
{ body: 'No connection to the bridge.\n\nYour request is not confirmed yet.', status: 'Tap: retry · Double-tap: discard' }
|
||||
: { body: 'Connection lost.\n\nStill waiting for the answer…', status: 'Reconnecting · Double-tap: cancel' };
|
||||
|
||||
case 'error':
|
||||
|
||||
@@ -38,6 +38,10 @@ export interface AppState {
|
||||
*/
|
||||
generation: number;
|
||||
conversationId: string | null;
|
||||
/** Bumped whenever the conversation is reset; a create result from an older epoch is dropped. */
|
||||
conversationEpoch: number;
|
||||
/** A new conversation has been requested and not yet confirmed. */
|
||||
creatingConversation: boolean;
|
||||
requestId: string | null;
|
||||
captureStartedAt: number | null;
|
||||
captureMaxSeconds: number;
|
||||
@@ -57,6 +61,8 @@ export const initialState: AppState = {
|
||||
phase: 'unpaired',
|
||||
generation: 0,
|
||||
conversationId: null,
|
||||
conversationEpoch: 0,
|
||||
creatingConversation: false,
|
||||
requestId: null,
|
||||
captureStartedAt: null,
|
||||
captureMaxSeconds: 30,
|
||||
@@ -83,8 +89,8 @@ export type AppEvent =
|
||||
| { type: 'capture_started'; generation: number; at: number }
|
||||
| { type: 'capture_failed'; generation: number; reason: 'mic_refused' | 'mic_stalled' | 'empty' }
|
||||
| { type: 'capture_limit'; generation: number }
|
||||
| { type: 'conversation_created'; generation: number; conversationId: string }
|
||||
| { type: 'conversation_failed'; generation: number; error: HudError }
|
||||
| { type: 'conversation_created'; epoch: number; conversationId: string }
|
||||
| { type: 'conversation_failed'; epoch: number; error: HudError }
|
||||
/** `pages` is the already-paginated plain-text answer when the result carries one. */
|
||||
| { type: 'turn_update'; generation: number; result: TurnResult; pages: string[] | null }
|
||||
| { type: 'turn_rejected'; generation: number; error: HudError }
|
||||
@@ -101,7 +107,7 @@ export type Effect =
|
||||
| { type: 'resubmit'; generation: number; requestId: string }
|
||||
| { type: 'poll'; generation: number; requestId: string }
|
||||
| { type: 'cancel_turn'; requestId: string }
|
||||
| { type: 'create_conversation'; generation: number }
|
||||
| { type: 'create_conversation'; epoch: number }
|
||||
| { type: 'exit_dialog' };
|
||||
|
||||
export interface Step {
|
||||
@@ -153,6 +159,7 @@ export function reduce(state: AppState, event: AppEvent): Step {
|
||||
generation: state.generation + 1,
|
||||
captureMaxSeconds: event.captureMaxSeconds,
|
||||
conversationId: event.conversationId,
|
||||
conversationEpoch: state.conversationEpoch + 1,
|
||||
};
|
||||
if (!event.paired) return same({ ...base, phase: 'unpaired' });
|
||||
if (event.resumeRequestId) {
|
||||
@@ -169,7 +176,12 @@ export function reduce(state: AppState, event: AppEvent): Step {
|
||||
case 'unpaired': {
|
||||
const effects: Effect[] = state.phase === 'listening' ? [{ type: 'discard_capture' }] : [];
|
||||
return {
|
||||
state: { ...initialState, generation: state.generation + 1, captureMaxSeconds: state.captureMaxSeconds },
|
||||
state: {
|
||||
...initialState,
|
||||
generation: state.generation + 1,
|
||||
conversationEpoch: state.conversationEpoch + 1,
|
||||
captureMaxSeconds: state.captureMaxSeconds,
|
||||
},
|
||||
effects,
|
||||
};
|
||||
}
|
||||
@@ -238,21 +250,36 @@ export function reduce(state: AppState, event: AppEvent): Step {
|
||||
case 'new_conversation': {
|
||||
// Only from a resting state: a reset must never be mistaken for cancelling the backend.
|
||||
if (!IDLE.has(state.phase)) return same(state);
|
||||
const generation = state.generation + 1;
|
||||
// One is already on its way: a second press must not start a second create.
|
||||
if (state.creatingConversation) return same(state);
|
||||
const conversationEpoch = state.conversationEpoch + 1;
|
||||
return {
|
||||
state: { ...clearTurn(state), phase: 'ready', generation, conversationId: null, notice: 'New conversation' },
|
||||
effects: [{ type: 'create_conversation', generation }],
|
||||
state: {
|
||||
...clearTurn(state),
|
||||
phase: 'ready',
|
||||
generation: state.generation + 1,
|
||||
conversationId: null,
|
||||
conversationEpoch,
|
||||
creatingConversation: true,
|
||||
notice: 'New conversation',
|
||||
},
|
||||
effects: [{ type: 'create_conversation', epoch: conversationEpoch }],
|
||||
};
|
||||
}
|
||||
|
||||
case 'conversation_created': {
|
||||
if (event.generation !== state.generation) return same(state);
|
||||
return same({ ...state, conversationId: event.conversationId });
|
||||
// Keyed to the conversation epoch, not the turn generation: the user may already have
|
||||
// started a question (which bumps the generation) while the conversation was being made.
|
||||
if (event.epoch !== state.conversationEpoch) return same(state);
|
||||
return same({ ...state, conversationId: event.conversationId, creatingConversation: false });
|
||||
}
|
||||
|
||||
case 'conversation_failed': {
|
||||
if (event.generation !== state.generation) return same(state);
|
||||
return same({ ...clearTurn(state), phase: 'error', error: event.error });
|
||||
if (event.epoch !== state.conversationEpoch) return same(state);
|
||||
// If a question is in flight, its own submit reports the failure; only a resting screen
|
||||
// is replaced by the error.
|
||||
if (!IDLE.has(state.phase)) return same({ ...state, creatingConversation: false });
|
||||
return same({ ...clearTurn(state), creatingConversation: false, phase: 'error', error: event.error });
|
||||
}
|
||||
|
||||
case 'capture_started': {
|
||||
|
||||
@@ -14,23 +14,14 @@ import type { DevicePort } from './port.ts';
|
||||
const BODY = { id: 1, name: 'body' } as const;
|
||||
const STATUS = { id: 2, name: 'status' } as const;
|
||||
|
||||
/** A flaky BLE hop can hang a bridge call for a long time; never let one block the UI forever. */
|
||||
const CALL_TIMEOUT_MS = 8000;
|
||||
/** A flaky BLE hop can hang a host call for a long time; never let one block the UI forever. */
|
||||
export const CALL_TIMEOUT_MS = 8000;
|
||||
|
||||
function withTimeout<T>(promise: Promise<T>, fallback: T): Promise<T> {
|
||||
return new Promise((resolve) => {
|
||||
const timer = setTimeout(() => resolve(fallback), CALL_TIMEOUT_MS);
|
||||
promise.then(
|
||||
(value) => {
|
||||
clearTimeout(timer);
|
||||
resolve(value);
|
||||
},
|
||||
() => {
|
||||
clearTimeout(timer);
|
||||
resolve(fallback);
|
||||
},
|
||||
);
|
||||
});
|
||||
interface Bounded<T> {
|
||||
/** The caller's answer: the real result, or the fallback if the host took too long. */
|
||||
value: T;
|
||||
/** True when `value` is the fallback because the host had not answered in time. */
|
||||
timedOut: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -43,15 +34,37 @@ export class EvenDevice implements DevicePort {
|
||||
private pending: HudFrame | null = null;
|
||||
private flushing = false;
|
||||
private ready = false;
|
||||
/** All host calls go through one queue: concurrent bridge calls are documented as unsafe. */
|
||||
/**
|
||||
* All host calls go through one queue: concurrent bridge calls are documented as unsafe.
|
||||
* The queue advances only when the host call has ACTUALLY settled. A caller that gives up
|
||||
* waiting gets a fallback answer, but the next host call still waits its turn, so two calls
|
||||
* are never in flight together and a late completion is always followed, in order, by
|
||||
* whatever was queued behind it.
|
||||
*/
|
||||
private queue: Promise<unknown> = Promise.resolve();
|
||||
|
||||
constructor(private readonly bridge: EvenAppBridge) {}
|
||||
constructor(
|
||||
private readonly bridge: EvenAppBridge,
|
||||
private readonly callTimeoutMs: number = CALL_TIMEOUT_MS,
|
||||
) {}
|
||||
|
||||
private enqueue<T>(call: () => Promise<T>, fallback: T): Promise<T> {
|
||||
const next = this.queue.then(() => withTimeout(call(), fallback));
|
||||
this.queue = next.catch(() => undefined);
|
||||
return next;
|
||||
private enqueueBounded<T>(call: () => Promise<T>, fallback: T): Promise<Bounded<T>> {
|
||||
// What the host really does, serialised behind every earlier call.
|
||||
const settled: Promise<T> = this.queue.then(call).catch(() => fallback);
|
||||
this.queue = settled;
|
||||
// What the caller sees: the same result, or the fallback after the timeout. The timer
|
||||
// starts when the call is requested, so time spent queued behind a stuck call counts.
|
||||
return new Promise((resolve) => {
|
||||
const timer = setTimeout(() => resolve({ value: fallback, timedOut: true }), this.callTimeoutMs);
|
||||
void settled.then((value) => {
|
||||
clearTimeout(timer);
|
||||
resolve({ value, timedOut: false });
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
private async enqueue<T>(call: () => Promise<T>, fallback: T): Promise<T> {
|
||||
return (await this.enqueueBounded(call, fallback)).value;
|
||||
}
|
||||
|
||||
async init(frame: HudFrame): Promise<boolean> {
|
||||
@@ -136,10 +149,21 @@ export class EvenDevice implements DevicePort {
|
||||
}
|
||||
}
|
||||
|
||||
startMic(): Promise<boolean> {
|
||||
return this.enqueue(() => this.bridge.audioControl(true, AudioInputSource.Glasses), false);
|
||||
async startMic(): Promise<boolean> {
|
||||
const started = await this.enqueueBounded(() => this.bridge.audioControl(true, AudioInputSource.Glasses), false);
|
||||
if (started.timedOut) {
|
||||
// The caller is being told "the microphone did not open" and will not stop it. But the
|
||||
// host may still open it later. Queue a stop now: it runs strictly after the pending
|
||||
// start settles, so whatever the start ends up doing, the microphone finishes closed.
|
||||
void this.enqueueBounded(() => this.bridge.audioControl(false), false);
|
||||
}
|
||||
return started.value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Always sends the stop, even if a start is still pending or was never confirmed: closing a
|
||||
* closed microphone is harmless, leaving one open is not. Queued behind any pending start.
|
||||
*/
|
||||
async stopMic(): Promise<void> {
|
||||
await this.enqueue(() => this.bridge.audioControl(false), false);
|
||||
}
|
||||
|
||||
@@ -35,10 +35,30 @@ export interface BridgeClientOptions {
|
||||
fetchImpl?: typeof fetch;
|
||||
}
|
||||
|
||||
/**
|
||||
* Hosts on which plain HTTP is tolerated: this machine only, for the simulator and the
|
||||
* browser preview. Exact matches, so `127.0.0.1.example.com` or `localhost.example.com`
|
||||
* do not qualify, and neither does any LAN or public address.
|
||||
*/
|
||||
export function isLoopbackHost(hostname: string): boolean {
|
||||
return hostname === 'localhost' || hostname === '[::1]' || /^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(hostname);
|
||||
}
|
||||
|
||||
/**
|
||||
* The device credential and the user's recordings travel to this URL, so it must be HTTPS.
|
||||
* The one exception is HTTP to loopback, which never leaves the machine.
|
||||
*/
|
||||
export function normalizeBridgeUrl(raw: string): string {
|
||||
const url = new URL(raw.trim());
|
||||
if (url.protocol !== 'https:' && url.protocol !== 'http:') throw new Error('Bridge URL must start with https://');
|
||||
return url.origin + url.pathname.replace(/\/+$/, '');
|
||||
let url: URL;
|
||||
try {
|
||||
url = new URL(raw.trim());
|
||||
} catch {
|
||||
throw new Error('Enter the bridge address as a full URL, for example https://bridge.example');
|
||||
}
|
||||
if (url.username || url.password) throw new Error('The bridge address must not contain a user name or password.');
|
||||
if (url.protocol === 'https:') return url.origin + url.pathname.replace(/\/+$/, '');
|
||||
if (url.protocol === 'http:' && isLoopbackHost(url.hostname)) return url.origin + url.pathname.replace(/\/+$/, '');
|
||||
throw new Error('The bridge address must start with https://');
|
||||
}
|
||||
|
||||
export class BridgeClient {
|
||||
|
||||
@@ -329,11 +329,37 @@ describe('pairing, restore and conversations', () => {
|
||||
const s = ready();
|
||||
const step = reduce(s, { type: 'new_conversation' });
|
||||
expect(step.state.conversationId).toBeNull();
|
||||
expect(step.effects).toEqual([{ type: 'create_conversation', generation: step.state.generation }]);
|
||||
const stale = reduce(step.state, { type: 'conversation_created', generation: s.generation, conversationId: 'old' });
|
||||
expect(step.state.creatingConversation).toBe(true);
|
||||
expect(step.effects).toEqual([{ type: 'create_conversation', epoch: step.state.conversationEpoch }]);
|
||||
const stale = reduce(step.state, { type: 'conversation_created', epoch: s.conversationEpoch, conversationId: 'old' });
|
||||
expect(stale.state.conversationId).toBeNull();
|
||||
const fresh = reduce(step.state, { type: 'conversation_created', generation: step.state.generation, conversationId: 'new' });
|
||||
const fresh = reduce(step.state, { type: 'conversation_created', epoch: step.state.conversationEpoch, conversationId: 'new' });
|
||||
expect(fresh.state.conversationId).toBe('new');
|
||||
expect(fresh.state.creatingConversation).toBe(false);
|
||||
});
|
||||
|
||||
it('a second "new conversation" while one is being created starts nothing (CODY-009)', () => {
|
||||
const first = reduce(ready(), { type: 'new_conversation' });
|
||||
const second = reduce(first.state, { type: 'new_conversation' });
|
||||
expect(second.state).toBe(first.state);
|
||||
expect(second.effects).toEqual([]);
|
||||
});
|
||||
|
||||
it('the conversation result is accepted even after a question has started, because it is keyed to the conversation, not the turn (CODY-009)', () => {
|
||||
const created = reduce(ready(), { type: 'new_conversation' });
|
||||
const asking = reduce(created.state, { type: 'submit_text', freshId: ID1, text: 'hi' });
|
||||
expect(asking.state.generation).toBeGreaterThan(created.state.generation);
|
||||
const done = reduce(asking.state, { type: 'conversation_created', epoch: created.state.conversationEpoch, conversationId: 'new' });
|
||||
expect(done.state.conversationId).toBe('new');
|
||||
expect(done.state.phase).toBe('thinking');
|
||||
});
|
||||
|
||||
it('a conversation result from before a re-pair or a later reset is dropped', () => {
|
||||
const created = reduce(ready(), { type: 'new_conversation' });
|
||||
const repaired = reduce(created.state, { type: 'init', paired: true, conversationId: null, captureMaxSeconds: 30, resumeRequestId: null });
|
||||
expect(reduce(repaired.state, { type: 'conversation_created', epoch: created.state.conversationEpoch, conversationId: 'x' }).state).toBe(repaired.state);
|
||||
const failedLate = reduce(repaired.state, { type: 'conversation_failed', epoch: created.state.conversationEpoch, error: { code: 'x', hud: 'x', retryable: false } });
|
||||
expect(failedLate.state).toBe(repaired.state);
|
||||
});
|
||||
|
||||
it('unpairing while listening closes the microphone', () => {
|
||||
|
||||
Reference in New Issue
Block a user