import type { Controller, Snapshot } from '../core/controller.ts'; import { BridgeApiError, BridgeNetworkError, normalizeBridgeUrl } from '../net/bridgeClient.ts'; import { mountSoundCheck } from './soundCheck.ts'; /** * Phone-side page: pairing, status, diagnostics, typed input and disconnect. * Built with DOM APIs and textContent only, so nothing from the bridge or the * agent is ever interpreted as HTML. */ function el( tag: K, props: Partial & { class?: string } = {}, children: Array = [], ): HTMLElementTagNameMap[K] { const node = document.createElement(tag); const { class: className, ...rest } = props; if (className) node.className = className; Object.assign(node, rest); for (const child of children) node.append(child); return node; } function explain(err: unknown): string { if (err instanceof BridgeApiError) return `${err.body.message} (${err.body.code})`; if (err instanceof BridgeNetworkError) { return ( 'Could not reach the bridge. Check the address, that the bridge is running, that this app build ' + "lists the bridge in its network whitelist, and that the bridge allows this page's origin." ); } return err instanceof Error ? err.message : 'Something went wrong.'; } const PHASE_LABEL: Record = { unpaired: 'Not paired', menu: 'Menu (choose a mode on the glasses)', ready: 'Ready', listening: 'Listening (microphone open)', transcribing: 'Transcribing', thinking: 'Thinking', approval: 'Approval required', answer: 'Answer shown', error: 'Error', disconnected: 'Disconnected', cancelled: 'Cancelled', }; export function mountPhoneUi(root: HTMLElement, controller: Controller, defaults: { bridgeUrl: string; runtime: string }): (s: Snapshot) => void { root.replaceChildren(); const message = el('p', { class: 'message', role: 'status' } as never); const say = (text: string, bad = false) => { message.textContent = text; message.className = bad ? 'message bad' : 'message'; }; async function guarded(button: HTMLButtonElement, action: () => Promise): Promise { button.disabled = true; try { const result = await action(); if (result) say(result); } catch (err) { say(explain(err), true); } finally { button.disabled = false; } } // ---- pairing const urlInput = el('input', { type: 'url', value: defaults.bridgeUrl, placeholder: 'https://bridge.example', autocomplete: 'off' }); const codeInput = el('input', { type: 'text', placeholder: 'ABCDE-FGHJK', autocomplete: 'off', autocapitalize: 'characters' } as never); const nameInput = el('input', { type: 'text', value: 'G2', maxLength: 60 }); const pairButton = el('button', { type: 'button', textContent: 'Pair' }); pairButton.addEventListener('click', () => guarded(pairButton, async () => { const url = normalizeBridgeUrl(urlInput.value); await controller.pair(url, codeInput.value.trim(), nameInput.value.trim() || 'G2'); codeInput.value = ''; return 'Paired.'; }), ); const pairing = el('section', {}, [ el('h2', { textContent: 'Pair with your bridge' }), el('p', { class: 'hint', textContent: 'On the bridge host run “npm run bridge:cli -- pair” and enter the code it prints. Codes work once and expire in a few minutes.' }), el('label', {}, ['Bridge address', urlInput]), el('label', {}, ['Pairing code', codeInput]), el('label', {}, ['Device name', nameInput]), pairButton, ]); // ---- status const statusList = el('dl'); const refreshButton = el('button', { type: 'button', class: 'secondary', textContent: 'Refresh' }); refreshButton.addEventListener('click', () => guarded(refreshButton, () => controller.refreshStatus())); const renewButton = el('button', { type: 'button', class: 'secondary', textContent: 'Renew credential' }); renewButton.addEventListener('click', () => guarded(renewButton, async () => (await controller.renew(), 'Credential renewed.'))); const disconnectButton = el('button', { type: 'button', class: 'danger', textContent: 'Disconnect' }); disconnectButton.addEventListener('click', () => guarded(disconnectButton, async () => { const { revoked } = await controller.disconnect(); return revoked ? 'Disconnected. The credential was revoked and removed from this phone.' : 'Removed from this phone, but the bridge could not be reached. Revoke this device on the bridge host to finish.'; }), ); const status = el('section', {}, [ el('h2', { textContent: 'Connection' }), statusList, el('div', { class: 'row' }, [refreshButton, renewButton, disconnectButton]), ]); // ---- conversation and typed input const textInput = el('textarea', { rows: 3, placeholder: 'Type a question (for testing, or when speaking is not possible)' }); const askButton = el('button', { type: 'button', textContent: 'Ask' }); askButton.addEventListener('click', () => { controller.askText(textInput.value); textInput.value = ''; }); const cancelButton = el('button', { type: 'button', class: 'secondary', textContent: 'Cancel request' }); cancelButton.addEventListener('click', () => controller.cancel()); const newButton = el('button', { type: 'button', class: 'secondary', textContent: 'New conversation' }); newButton.addEventListener('click', () => controller.newConversation()); const phase = el('p', { class: 'phase' }); const captureNote = el('p', { class: 'hint' }); const turnView = el('div', { class: 'turn' }); const conversation = el('section', {}, [ el('h2', { textContent: 'Conversation' }), phase, captureNote, el('label', {}, ['Typed question', textInput]), el('div', { class: 'row' }, [askButton, cancelButton, newButton]), turnView, ]); // ---- diagnostics const diagList = el('dl'); const logView = el('pre', { class: 'log' }); const diagnostics = el('details', {}, [ el('summary', { textContent: 'Diagnostics' }), el('p', { class: 'hint', textContent: 'Identifiers, states and timings only. Questions and answers are not written to this log.' }), diagList, logView, ]); root.append(el('h1', { textContent: 'Hermeven' }), message, pairing, status, conversation, mountSoundCheck(document, window), diagnostics); const rows = (list: HTMLElement, entries: Array<[string, string]>) => { list.replaceChildren(...entries.flatMap(([k, v]) => [el('dt', { textContent: k }), el('dd', { textContent: v })])); }; const when = (iso: string) => (iso ? new Date(iso).toLocaleString() : 'unknown'); return (s: Snapshot) => { pairing.hidden = s.paired; status.hidden = !s.paired; conversation.hidden = !s.paired; rows(statusList, [ ['Bridge', s.bridgeUrl], ['Agent', s.status ? (s.status.agent_reachable ? 'reachable' : 'not reachable from the bridge') : 'not checked'], ['Speech-to-text', s.status ? (s.status.stt_configured ? 'configured' : 'not configured (typed questions only)') : 'not checked'], [ 'Spoken answers', !s.voice.offered ? 'not available (the bridge has no voices set up, or this page cannot play sound)' : s.voice.on ? `on${s.voice.speaking ? ', speaking now' : ''}: answers are sent to the speech provider and played on whatever sound output the phone is using` : 'off. Switch on with “Voice” on the glasses’ opening menu; it is off again at every launch.', ], ['Credential valid until', when(s.tokenExpiresAt)], ['Pairing valid until', when(s.pairingExpiresAt)], ['Stored on this phone', 'In the Even app’s app storage, which is not an encrypted vault. The credential is revocable and expires.'], ]); phase.textContent = PHASE_LABEL[s.state.phase] ?? s.state.phase; captureNote.textContent = s.wake.enabled ? `Hands free: the glasses’ microphone is open whenever the app is at rest (the status line starts with “●”). ` + `Each stretch of speech goes to your bridge, which keeps it only if it begins with an agent’s name. ` + `Say a name and then your question, or tap to ask. Double tap at Ready goes back to the menu and closes the microphone. ` + (s.wake.listening ? 'Listening now.' : 'Not listening at the moment.') : `Recording starts only when you tap the glasses, shows “● REC” for as long as the microphone is open, ` + `and stops by itself after ${s.state.captureMaxSeconds} seconds.`; const inFlight = ['listening', 'transcribing', 'thinking', 'approval', 'disconnected'].includes(s.state.phase); askButton.disabled = inFlight; newButton.disabled = inFlight; cancelButton.disabled = !inFlight; const t = s.lastTurn; turnView.replaceChildren(); if (s.state.error) { turnView.append(el('p', { class: 'bad', textContent: `${s.state.error.hud} [${s.state.error.code}]` })); } if (t) { if (t.input_text) turnView.append(el('h3', { textContent: 'Sent to the agent' }), el('p', { textContent: t.input_text })); if (t.answer_text !== null) { turnView.append( el('h3', { textContent: t.outcome === 'incomplete' ? 'Partial answer' : 'Answer' }), el('p', { class: 'answer', textContent: t.answer_text }), ); } turnView.append( el('p', { class: 'hint', textContent: `Outcome: ${t.outcome ?? 'pending'}${t.error ? ` · ${t.error.code}` : ''}` + `${t.cancel_requested ? ' · cancel was requested' : ''}`, }), ); } rows(diagList, [ ['Runtime', defaults.runtime], ['Page origin', location.origin], ['Browser', navigator.userAgent], ['HUD page', s.hudReady ? 'created' : 'not created'], ['Opened from', s.launchSource === 'glassesMenu' ? 'the glasses (menu or voice)' : s.launchSource === 'appMenu' ? 'the phone app' : 'not reported'], ['Glasses input', s.glassesInput || 'not available in this mode'], ['Device id', s.deviceId || 'none'], ['Conversation id', s.state.conversationId ?? 'none'], ['Request id', s.state.requestId ?? 'none'], ['Generation', String(s.state.generation)], ['Audio format', s.status ? `${s.status.audio_format.encoding} ${s.status.audio_format.sample_rate} Hz × ${s.status.audio_format.channels}` : 'unknown'], [ 'Deadlines', s.status ? `transcribe ${s.status.limits.transcribe_deadline_seconds} s · agent ${s.status.limits.agent_deadline_seconds} s · approval ${s.status.limits.approval_wait_seconds} s` : 'unknown', ], ]); logView.textContent = s.log .slice(-60) .map((e) => `${new Date(e.at).toISOString().slice(11, 23)} ${e.kind.padEnd(12)} ${e.detail}`) .join('\n'); }; }