import type { TurnResult } from '@hermeven/contracts'; /** * Pure interaction state machine. No I/O, no clocks, no randomness: everything * that varies arrives inside an event, and everything to be done leaves as an * effect. That is what makes cancellation and stale-result races testable. * * READY -> LISTENING -> TRANSCRIBING -> THINKING -> ANSWER * with ERROR, DISCONNECTED and CANCELLED as explicit outcomes. */ export type Phase = | 'unpaired' /** The opening menu: choose a mode. Nothing records and nothing is in flight. */ | 'menu' | 'ready' | 'listening' | 'transcribing' | 'thinking' | 'approval' | 'answer' | 'error' | 'disconnected' | 'cancelled'; export interface HudError { /** Stable code for the phone diagnostics view. */ code: string; /** One short line for the HUD. */ hud: string; /** Whether asking again (as a deliberate new turn) is reasonable. */ retryable: boolean; } /** An agent the bridge lets this device talk to. */ export interface Agent { id: string; name: string; } /** * How the app is being used. Both modes talk to the same agents through the same path; the * only difference is whether the microphone listens for a name while at rest. * - agents: the microphone opens on a tap, and the app leaves the glasses when idle. * - handsfree: the microphone is open at rest, and the app stays until closed. */ export type Mode = 'agents' | 'handsfree'; export const MODE_LABEL: Record = { handsfree: 'Hands free', agents: 'Agents' }; export interface AppState { phase: Phase; /** The app opens on a menu, and double tap at Ready goes back to it (instead of exiting). */ menu: boolean; menuIndex: number; mode: Mode; /** Hands free can be offered: this build has it, and nothing has said the bridge cannot do it. */ handsFree: boolean; /** The bridge can read answers aloud and this page can play sound: the menu offers Voice. */ voiceOffered: boolean; /** Answers are read aloud. Chosen on the menu; off at every launch, never saved. */ voice: boolean; /** * The agents the bridge offers, default first. Empty when there is only one (or the bridge * predates agent selection): nothing about agents is then shown or sent. */ agents: Agent[]; /** The agent questions go to. Null = the default (the first in `agents`). */ agentId: string | null; /** * Bumped whenever the user starts, cancels or abandons something. Every * asynchronous effect carries the generation it was issued under, and an * event from an older generation is dropped. */ 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; /** The recording was started by saying an agent's name: it sends itself when the speaker stops. */ captureAuto: boolean; /** * The microphone is open at rest, listening for an agent's name. Reported by the controller * from what the microphone actually did, so the HUD's indicator is never a guess. */ wakeListening: boolean; /** The request in flight was spoken (recorded), not typed. */ spoken: boolean; /** The spoken question as the bridge transcribed it. Shown while the agent works. */ heard: string | null; /** * The words of the recording in progress, as far as they have been transcribed. Already cut * by the controller to what fits the screen. A preview only: it is never what is sent. */ preview: string | null; pages: string[]; pageIndex: number; /** The answer is a partial one (agent stopped short). Shown on the HUD. */ partial: boolean; error: HudError | null; /** In DISCONNECTED: the request never reached the bridge, so resending it is safe. */ canResend: boolean; /** * 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; } export const initialState: AppState = { phase: 'unpaired', menu: false, menuIndex: 0, mode: 'agents', handsFree: false, voiceOffered: false, voice: false, agents: [], agentId: null, generation: 0, conversationId: null, conversationEpoch: 0, creatingConversation: false, requestId: null, captureStartedAt: null, captureMaxSeconds: 30, captureAuto: false, wakeListening: false, spoken: false, heard: null, preview: null, pages: [], pageIndex: 0, partial: false, 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; storageFault?: boolean; agents?: Agent[]; agentId?: string | null; /** Open on the menu. Without it the app opens at Ready, hands free if that is available. */ menu?: boolean; handsFree?: boolean; } /** Hands free turned out not to be possible (the bridge cannot do it): fall back to Agents. */ | { type: 'handsfree_lost' } /** Whether answers can be read aloud at all (asked of the bridge after pairing). */ | { type: 'voice_offered'; offered: boolean } /** The user picked another agent (a swipe at Ready). `conversationId` is that agent's own, if it has one. */ | { type: 'agent_selected'; agentId: string; conversationId: string | null } /** * The current agent is no longer offered and nothing is in flight with it: fall back to the * default agent and ITS conversation. Unlike a selection this applies on any resting screen, * and leaves what is on screen (the removed agent's last answer or error) in place. */ | { type: 'agent_reconciled'; agentId: string; conversationId: string | null } | { type: 'unpaired' } /** * An agent was addressed by name and the question followed in the same breath ("Wendy, what * time is it"). `agentId` and `conversationId` are that agent's; null agent = no choice offered. */ | { type: 'wake_text'; freshId: string; agentId: string | null; conversationId: string | null; text: string } /** Only the name was said: record what follows and send it when the speaker stops. */ | { type: 'wake_listen'; freshId: string; agentId: string | null; conversationId: string | null } /** A recording started by name heard nothing: back to rest, nothing sent. */ | { type: 'capture_abandoned'; generation: number } | { type: 'wake_status'; listening: boolean } /** Semantic actions. `freshId` is a new UUID supplied by the caller in case a turn starts. */ | { type: 'activate'; freshId: string } | { type: 'back' } | { type: 'next_page' } | { type: 'prev_page' } | { type: 'new_conversation' } | { type: 'cancel' } | { type: 'submit_text'; freshId: string; text: string } | { type: 'capture_started'; generation: number; at: number } /** The words so far in the recording being made (already fitted to the screen). */ | { type: 'capture_preview'; generation: number; text: string } | { type: 'capture_failed'; generation: number; reason: 'mic_refused' | 'mic_stalled' | 'empty' } | { type: 'capture_limit'; generation: number } | { 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 } | { 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' }; export type Effect = | { type: 'start_capture'; generation: number; auto?: boolean } | { type: 'stop_capture_and_submit'; generation: number; requestId: string } | { type: 'discard_capture' } | { type: 'submit_text'; generation: number; requestId: string; text: string } | { type: 'resubmit'; generation: number; requestId: string } | { type: 'poll'; generation: number; requestId: string } | { type: 'cancel_turn'; requestId: string } | { type: 'create_conversation'; epoch: number } | { type: 'exit_dialog' }; export interface Step { state: AppState; effects: Effect[]; } const IDLE: ReadonlySet = new Set(['ready', 'answer', 'error', 'cancelled']); const IN_FLIGHT: ReadonlySet = new Set(['transcribing', 'thinking', 'approval']); /** The menu's entries, in order. Hands free comes first whenever it can be offered. */ export type MenuItem = Mode | 'voice'; export function menuItems(state: Pick): MenuItem[] { const modes: MenuItem[] = state.handsFree ? ['handsfree', 'agents'] : ['agents']; return state.voiceOffered ? [...modes, 'voice'] : modes; } /** How a menu entry reads. Voice is a switch, so it shows its setting. */ export function menuLabel(item: MenuItem, state: Pick): string { return item === 'voice' ? `Voice: ${state.voice ? 'on' : 'off'}` : MODE_LABEL[item]; } /** The agent questions go to now, or undefined when the bridge offers no choice. */ export function currentAgent(state: AppState): Agent | undefined { if (state.agents.length === 0) return undefined; return state.agents.find((a) => a.id === state.agentId) ?? state.agents[0]; } function clearTurn(state: AppState): AppState { return { ...state, requestId: null, captureStartedAt: null, captureAuto: false, spoken: false, heard: null, preview: null, pages: [], pageIndex: 0, partial: false, error: null, canResend: false, disconnectedFrom: null, notice: null, }; } function same(state: AppState): Step { return { state, effects: [] }; } /** * Turn to the agent that was addressed by name, with its own conversation. Null when that * agent is not one on offer. A change of agent or conversation starts a new conversation epoch, * so a conversation still being created for the previous one cannot land here. */ function address(state: AppState, agentId: string | null, conversationId: string | null): AppState | null { if (state.agents.length > 0 && agentId !== null && !state.agents.some((a) => a.id === agentId)) return null; const sameAgent = state.agents.length === 0 || agentId === null || agentId === currentAgent(state)?.id; if (sameAgent && conversationId === state.conversationId) return state; return { ...state, agentId: sameAgent ? state.agentId : agentId, conversationId, conversationEpoch: state.conversationEpoch + 1, creatingConversation: false, }; } /** Abandon whatever is in progress. The generation bump is what silences late results. */ function abandon(state: AppState): Step { const effects: Effect[] = []; if (state.phase === 'listening') effects.push({ type: 'discard_capture' }); else if (state.requestId && (IN_FLIGHT.has(state.phase) || state.phase === 'disconnected')) { // Also drops any audio still held for a resend, and asks the bridge to stop the agent. effects.push({ type: 'discard_capture' }, { type: 'cancel_turn', requestId: state.requestId }); } return { state: { ...clearTurn(state), phase: 'cancelled', generation: state.generation + 1 }, effects, }; } export function reduce(state: AppState, event: AppEvent): Step { switch (event.type) { case 'init': { const base: AppState = { ...initialState, generation: state.generation + 1, captureMaxSeconds: event.captureMaxSeconds, conversationId: event.conversationId, conversationEpoch: state.conversationEpoch + 1, storageFault: event.storageFault === true, agents: event.agents ?? [], agentId: event.agentId ?? null, menu: event.menu === true, handsFree: event.handsFree === true, // With a menu, hands free is something the user chooses. Without one it is simply on. mode: event.menu !== true && event.handsFree === true ? 'handsfree' : 'agents', }; if (!event.paired) return same({ ...base, phase: 'unpaired' }); if (event.resumeRequestId) { // A turn was in flight when the page last died. Re-attach by polling: never resubmit, // and never reopen the microphone on our own. return { state: { ...base, phase: 'thinking', requestId: event.resumeRequestId }, effects: [{ type: 'poll', generation: base.generation, requestId: event.resumeRequestId }], }; } return same({ ...base, phase: base.menu ? 'menu' : 'ready' }); } case 'voice_offered': { if (event.offered === state.voiceOffered) return same(state); const next = { ...state, voiceOffered: event.offered, voice: event.offered && state.voice }; return same({ ...next, menuIndex: Math.min(state.menuIndex, menuItems(next).length - 1) }); } case 'handsfree_lost': { if (!state.handsFree) return same(state); const wasOn = state.mode === 'handsfree'; return same({ ...state, handsFree: false, mode: 'agents', menuIndex: 0, wakeListening: false, notice: wasOn && state.phase === 'ready' ? 'Hands free is not available' : state.notice, }); } case 'agent_selected': { // Only from Ready: never while something is recording, in flight or on screen. Each agent // has its own conversation, so the conversation is swapped with it, under a new epoch so a // conversation still being created for the previous agent cannot land on this one. if (state.phase !== 'ready') return same(state); if (!state.agents.some((a) => a.id === event.agentId)) return same(state); if (event.agentId === currentAgent(state)?.id) return same(state); return same({ ...clearTurn(state), phase: 'ready', generation: state.generation + 1, agentId: event.agentId, conversationId: event.conversationId, conversationEpoch: state.conversationEpoch + 1, creatingConversation: false, }); } case 'agent_reconciled': { if (!IDLE.has(state.phase)) return same(state); return same({ ...state, agentId: event.agentId, conversationId: event.conversationId, conversationEpoch: state.conversationEpoch + 1, creatingConversation: false, }); } case 'unpaired': { const effects: Effect[] = state.phase === 'listening' ? [{ type: 'discard_capture' }] : []; return { state: { ...initialState, generation: state.generation + 1, conversationEpoch: state.conversationEpoch + 1, captureMaxSeconds: state.captureMaxSeconds, }, effects, }; } case 'wake_text': { if (!IDLE.has(state.phase)) return same(state); const addressed = address(state, event.agentId, event.conversationId); if (!addressed) return same(state); const generation = state.generation + 1; return { state: { ...clearTurn(addressed), phase: 'thinking', generation, requestId: event.freshId, heard: event.text }, effects: [{ type: 'submit_text', generation, requestId: event.freshId, text: event.text }], }; } case 'wake_listen': { if (!IDLE.has(state.phase)) return same(state); const addressed = address(state, event.agentId, event.conversationId); if (!addressed) return same(state); const generation = state.generation + 1; return { state: { ...clearTurn(addressed), phase: 'listening', generation, requestId: event.freshId, captureAuto: true }, effects: [{ type: 'start_capture', generation, auto: true }], }; } case 'capture_abandoned': { if (event.generation !== state.generation || state.phase !== 'listening') return same(state); return { state: { ...clearTurn(state), phase: 'ready', generation: state.generation + 1 }, effects: [{ type: 'discard_capture' }], }; } case 'wake_status': return same(event.listening === state.wakeListening ? state : { ...state, wakeListening: event.listening }); case 'activate': { if (state.phase === 'menu') { const item = menuItems(state)[state.menuIndex] ?? 'agents'; // Voice is a switch: it flips and the menu stays. if (item === 'voice') return same({ ...state, voice: !state.voice }); const mode: Mode = item; return same({ ...clearTurn(state), phase: 'ready', mode, generation: state.generation + 1 }); } if (IDLE.has(state.phase)) { const generation = state.generation + 1; return { state: { ...clearTurn(state), phase: 'listening', generation, requestId: event.freshId }, effects: [{ type: 'start_capture', generation }], }; } if (state.phase === 'listening' && state.requestId) { return { state: { ...state, phase: 'transcribing', captureStartedAt: null, spoken: true }, effects: [{ type: 'stop_capture_and_submit', generation: state.generation, requestId: state.requestId }], }; } if (state.phase === 'disconnected' && state.canResend && state.requestId) { // Same request id: the bridge deduplicates, so this cannot run the turn twice. return { state: { ...state, phase: 'transcribing', disconnectedFrom: null }, effects: [{ type: 'resubmit', generation: state.generation, requestId: state.requestId }], }; } return same(state); } case 'capture_limit': { if (event.generation !== state.generation || state.phase !== 'listening' || !state.requestId) return same(state); return { state: { ...state, phase: 'transcribing', captureStartedAt: null, spoken: true }, effects: [{ type: 'stop_capture_and_submit', generation: state.generation, requestId: state.requestId }], }; } case 'submit_text': { // Typed on the phone. Also accepted on the menu: it does not need a mode. if (!IDLE.has(state.phase) && state.phase !== 'menu') return same(state); const generation = state.generation + 1; return { state: { ...clearTurn(state), phase: 'thinking', generation, requestId: event.freshId }, effects: [{ type: 'submit_text', generation, requestId: event.freshId, text: event.text }], }; } case 'back': { if (state.phase === 'ready' && state.menu) { // Leaving a mode. Hands free ends here: the microphone closes with it. return same({ ...clearTurn(state), phase: 'menu', mode: 'agents', menuIndex: 0, generation: state.generation + 1 }); } if (state.phase === 'ready' || state.phase === 'unpaired' || state.phase === 'menu') return { state, effects: [{ type: 'exit_dialog' }] }; if (state.phase === 'listening' || IN_FLIGHT.has(state.phase) || state.phase === 'disconnected') return abandon(state); // answer / error / cancelled: step back to the root page. return same({ ...clearTurn(state), phase: 'ready' }); } case 'cancel': { if (state.phase === 'listening' || IN_FLIGHT.has(state.phase) || state.phase === 'disconnected') return abandon(state); return same(state); } case 'next_page': case 'prev_page': { const delta = event.type === 'next_page' ? 1 : -1; if (state.phase === 'menu') { const menuIndex = Math.min(menuItems(state).length - 1, Math.max(0, state.menuIndex + delta)); return same(menuIndex === state.menuIndex ? state : { ...state, menuIndex }); } if (state.phase !== 'answer') return same(state); const pageIndex = Math.min(state.pages.length - 1, Math.max(0, state.pageIndex + delta)); return same(pageIndex === state.pageIndex ? state : { ...state, pageIndex }); } 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); // 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: state.generation + 1, conversationId: null, conversationEpoch, creatingConversation: true, notice: 'New conversation', }, effects: [{ type: 'create_conversation', epoch: conversationEpoch }], }; } case 'conversation_created': { // 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.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': { if (event.generation !== state.generation || state.phase !== 'listening') return same(state); return same({ ...state, captureStartedAt: event.at }); } case 'capture_preview': { if (event.generation !== state.generation || state.phase !== 'listening') return same(state); return same(event.text === state.preview ? state : { ...state, preview: event.text || null }); } case 'capture_failed': { if (event.generation !== state.generation) return same(state); if (state.phase !== 'listening' && state.phase !== 'transcribing') return same(state); const hud = event.reason === 'mic_refused' ? 'Microphone unavailable.' : event.reason === 'mic_stalled' ? 'Microphone stopped.' : 'Nothing was recorded.'; return { state: { ...clearTurn(state), phase: 'error', error: { code: event.reason, hud, retryable: true } }, effects: [{ type: 'discard_capture' }], }; } case 'turn_update': { if (event.generation !== state.generation || event.result.request_id !== state.requestId) return same(state); if (!IN_FLIGHT.has(state.phase) && state.phase !== 'disconnected') return same(state); const result = event.result; if (!result.terminal) { // A recording the bridge has accepted but not yet started on is still being transcribed. const waiting = result.state === 'transcribing' || (result.state === 'accepted' && state.spoken && !result.input_text); const phase: Phase = waiting ? 'transcribing' : result.state === 'approval_required' ? 'approval' : 'thinking'; // Once the bridge has the transcript of a spoken question, that is what the agent is // being sent, and it is shown in place of the preview. const heard = state.heard ?? (state.spoken && !waiting ? (result.input_text ?? null) : null); return same({ ...state, phase, heard, preview: waiting ? state.preview : null, disconnectedFrom: null, canResend: false }); } const settled = { ...clearTurn(state), requestId: state.requestId }; switch (result.outcome) { case 'succeeded': case 'incomplete': return same({ ...settled, phase: 'answer', pages: event.pages ?? [''], pageIndex: 0, partial: result.outcome === 'incomplete', }); case 'cancelled': return same({ ...settled, phase: result.error ? 'error' : 'cancelled', error: result.error ? { code: result.error.code, hud: result.error.message, retryable: result.error.retryable } : null, }); default: return same({ ...settled, phase: 'error', error: { code: result.error?.code ?? 'internal', hud: result.error?.message ?? 'The request did not complete.', retryable: result.error?.retryable ?? false, }, }); } } case 'turn_rejected': { if (event.generation !== state.generation) return same(state); return { state: { ...clearTurn(state), phase: 'error', error: event.error }, effects: [{ type: 'discard_capture' }] }; } case 'network_lost': { if (event.generation !== state.generation) return same(state); if (!IN_FLIGHT.has(state.phase) && state.phase !== 'disconnected') return same(state); 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); } return same({ ...state, phase: 'thinking', disconnectedFrom: null, canResend: false }); } case 'glasses_status': { if (event.connected) { if (state.phase === 'disconnected' && state.disconnectedFrom === 'glasses') { // Back to rest. The microphone is never reopened without a fresh tap. return same({ ...clearTurn(state), phase: 'ready' }); } return same(state); } if (state.phase === 'listening') { return { state: { ...clearTurn(state), phase: 'disconnected', disconnectedFrom: 'glasses', generation: state.generation + 1, }, effects: [{ type: 'discard_capture' }], }; } if (IDLE.has(state.phase)) return same({ ...state, phase: 'disconnected', disconnectedFrom: 'glasses', canResend: false }); // A turn already in flight keeps running on the bridge; its result is still wanted. return same(state); } case 'app_exit': { if (state.phase !== 'listening') return same(state); return { state: { ...clearTurn(state), phase: 'ready', generation: state.generation + 1 }, effects: [{ type: 'discard_capture' }], }; } } }