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:
Dan
2026-11-18 19:49:14 -08:00
co-authored by Claude Fable 5.2
parent 3d5691dfa3
commit e1c02d5266
43 changed files with 2104 additions and 227 deletions
+131 -38
View File
@@ -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}`;