diff --git a/apps/even-client/app.template.json b/apps/even-client/app.template.json index a5a05a4..97cea94 100644 --- a/apps/even-client/app.template.json +++ b/apps/even-client/app.template.json @@ -2,7 +2,7 @@ "package_id": "xylo.hermeven", "edition": "202601", "name": "Pepper", - "version": "0.1.0", + "version": "0.1.1", "min_sdk_version": "0.0.16", "entrypoint": "index.html", "permissions": [ diff --git a/apps/even-client/src/boot.ts b/apps/even-client/src/boot.ts index 8f24f17..ce71209 100644 --- a/apps/even-client/src/boot.ts +++ b/apps/even-client/src/boot.ts @@ -29,6 +29,8 @@ export interface BootOptions { hostWaitMs?: number; /** Development build: mirror diagnostics to the console. */ dev?: boolean; + /** `false` keeps the app on the glasses indefinitely (automated simulator runs). */ + idleExit?: boolean; /** Reload hook, replaceable in tests. */ reload?: () => void; } @@ -90,6 +92,7 @@ export async function boot(doc: Document, win: Window, options: BootOptions = {} measure: (text, width) => measureTextWrap(text, width).lineCount, locale: win.navigator.language || 'en-US', onChange: (snapshot) => update(snapshot), + ...(options.idleExit === false ? { idleExit: null } : {}), // Development builds mirror diagnostics to the console (visible in the simulator and the // Even dev console). Diagnostics never contain questions, answers or credentials. onNote: options.dev ? (entry) => console.info(`[hermeven] ${entry.kind}: ${entry.detail}`) : undefined, @@ -98,6 +101,12 @@ export async function boot(doc: Document, win: Window, options: BootOptions = {} // The real page is on screen: the start-up status has done its job. startup?.remove(); + // Touching or typing on the phone page means someone is using it: Pepper does not leave the + // glasses (which also closes this page) while that is going on. + for (const type of ['pointerdown', 'keydown', 'input'] as const) { + doc.addEventListener(type, () => controller.notePhoneActivity(), { passive: true }); + } + // Never leave the microphone open behind a page that is going away. win.addEventListener('beforeunload', () => void controller.stop()); diff --git a/apps/even-client/src/core/controller.ts b/apps/even-client/src/core/controller.ts index 8c7d874..04ec994 100644 --- a/apps/even-client/src/core/controller.ts +++ b/apps/even-client/src/core/controller.ts @@ -24,6 +24,8 @@ interface Stored { activeRequestId: string | null; /** The user abandoned that turn but the bridge has not yet acknowledged the cancel. */ activeCancelled: boolean; + /** When the last turn in `conversationId` finished (ms since epoch), if known. */ + lastTurnAt?: number; } export interface DiagEntry { @@ -41,6 +43,8 @@ export interface Snapshot { pairingExpiresAt: string; status: DeviceStatusResponse | null; hudReady: boolean; + /** How this session was opened, when the device says. */ + launchSource: string; /** What the glasses runtime has delivered, by type only (empty when the device cannot say). */ glassesInput: string; /** Last settled turn, complete and untruncated, for the phone. */ @@ -48,6 +52,17 @@ export interface Snapshot { log: DiagEntry[]; } +export interface IdleExitMs { + /** An answer is on screen and has not been touched. Paging or any gesture restarts it. */ + answer: number | null; + /** Ready and waiting for a question. */ + ready: number | null; + /** An error or "Cancelled" message is on screen. */ + message: number | null; +} + +export const DEFAULT_IDLE_EXIT_MS: IdleExitMs = { answer: 20_000, ready: 30_000, message: 10_000 }; + export interface ControllerOptions { device: DevicePort; measure: MeasureLines; @@ -66,6 +81,15 @@ export interface ControllerOptions { micStallMs?: number; /** A long press held at least this long, then released, sends what was recorded (push-to-talk). */ holdToTalkMs?: number; + /** + * Leave the glasses after this long with nothing happening, per resting screen. `null` + * disables it for that screen; `idleExit: null` disables it altogether. + */ + idleExit?: Partial | null; + /** After a phone-page interaction, do not leave by ourselves for this long. */ + phoneGraceMs?: number; + /** A question asked after this long a silence starts a new conversation. */ + conversationGapMs?: number; } interface Capture { @@ -110,6 +134,19 @@ export class Controller { private readonly submitRetryMs: number; private readonly micStallMs: number; private readonly holdToTalkMs: number; + private readonly idleExitMs: IdleExitMs | null; + private readonly phoneGraceMs: number; + private readonly conversationGapMs: number; + private idleTimer: ReturnType | null = null; + /** + * Leaving by ourselves is only armed once the glasses are actually being used: a gesture has + * arrived, or the session was opened from the glasses. A page opened from the phone to set + * things up is never closed under the user's fingers. + */ + private idleArmed = false; + private phoneBusyUntil = 0; + private launchSource: 'appMenu' | 'glassesMenu' | 'unknown' = 'unknown'; + private exited = false; /** Set while a long press that STARTED a recording is still held down. */ private heldPress: { generation: number; at: number } | null = null; @@ -122,6 +159,9 @@ export class Controller { this.submitRetryMs = options.submitRetryMs ?? 1500; this.micStallMs = options.micStallMs ?? 3000; this.holdToTalkMs = options.holdToTalkMs ?? 700; + this.idleExitMs = options.idleExit === null ? null : { ...DEFAULT_IDLE_EXIT_MS, ...options.idleExit }; + this.phoneGraceMs = options.phoneGraceMs ?? 120_000; + this.conversationGapMs = options.conversationGapMs ?? 10 * 60_000; } // ------------------------------------------------------------------ public @@ -131,6 +171,18 @@ export class Controller { this.storageFault = loaded === 'unreadable'; this.stored = loaded === 'unreadable' ? null : loaded; if (this.stored) this.confirmedActive = this.stored.activeCancelled ? undefined : this.stored.activeRequestId; + // Pepper now leaves the glasses between questions, so "the same conversation" cannot mean + // "until the app closes". A question after a long silence starts a new conversation; one + // soon after the last answer continues it. + if ( + this.stored?.conversationId && + !this.stored.activeRequestId && + this.stored.lastTurnAt !== undefined && + this.now() - this.stored.lastTurnAt > this.conversationGapMs + ) { + this.note('conversation', 'last question was a while ago: the next one starts a new conversation'); + this.stored = { ...this.stored, conversationId: null }; + } 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'); @@ -139,6 +191,14 @@ export class Controller { // Refresh the phone's Diagnostics when the glasses deliver something, even if it changes // no state (an ignored or unrecognised event is exactly what needs to be visible). this.device.onInputActivity?.(() => this.emit()) ?? (() => undefined), + this.device.onLaunchSource?.((source) => { + this.launchSource = source; + this.note('lifecycle', `opened from ${source}`); + // Opened from the glasses (their menu, or by voice): the glasses are in use. + if (source === 'glassesMenu') this.idleArmed = true; + this.scheduleIdleExit(); + this.emit(); + }) ?? (() => undefined), this.device.onConnection((connected) => { this.note('glasses', connected ? 'connected' : 'disconnected'); this.dispatch({ type: 'glasses_status', connected }); @@ -178,6 +238,8 @@ export class Controller { async stop(): Promise { this.stopped = true; for (const off of this.unsubscribers.splice(0)) off(); + if (this.idleTimer) clearTimeout(this.idleTimer); + this.idleTimer = null; this.stopTicker(); await this.closeMic(); } @@ -192,6 +254,7 @@ export class Controller { pairingExpiresAt: this.stored?.pairingExpiresAt ?? '', status: this.status, hudReady: this.hudReady, + launchSource: this.launchSource, glassesInput: this.device.inputSummary?.() ?? '', lastTurn: this.lastTurn, log: [...this.log], @@ -302,6 +365,53 @@ export class Controller { for (const effect of step.effects) void this.run(effect); this.render(); this.emit(); + this.scheduleIdleExit(); + } + + /** The phone page is being used (touch or key): do not leave under the user's fingers. */ + notePhoneActivity(): void { + this.phoneBusyUntil = this.now() + this.phoneGraceMs; + this.scheduleIdleExit(); + } + + /** + * (Re)start the countdown to leaving the glasses. Called after every state change and every + * gesture, so any activity restarts it. It only runs on a resting screen: never while + * recording, transcribing, waiting for the agent or for an approval, or while disconnected + * with a request outstanding. + */ + private scheduleIdleExit(): void { + if (this.idleTimer) clearTimeout(this.idleTimer); + this.idleTimer = null; + if (this.stopped || this.exited || !this.idleExitMs || !this.idleArmed || !this.hudReady) return; + const phase = this.state.phase; + const wait = + phase === 'answer' + ? this.idleExitMs.answer + : phase === 'ready' + ? this.idleExitMs.ready + : phase === 'error' || phase === 'cancelled' + ? this.idleExitMs.message + : null; + if (wait === null) return; + const delay = Math.max(wait, this.phoneBusyUntil - this.now() + wait); + const generation = this.state.generation; + this.idleTimer = setTimeout(() => { + this.idleTimer = null; + // Something happened in the meantime, or the screen is no longer a resting one. + if (this.stopped || this.exited || this.state.generation !== generation || this.state.phase !== phase) return; + if (this.now() < this.phoneBusyUntil) return this.scheduleIdleExit(); + void this.leaveGlasses(`idle on ${phase}`); + }, delay); + } + + private async leaveGlasses(reason: string): Promise { + if (this.exited) return; + this.exited = true; + this.note('lifecycle', `leaving the glasses: ${reason}`); + this.emit(); + await this.closeMic(); + await this.device.exitNow(); } // ----------------------------------------------------------------- effects @@ -572,6 +682,7 @@ export class Controller { let pages: string[] | null = null; if (result.terminal) { this.lastTurn = result; + if (this.stored) this.stored = { ...this.stored, lastTurnAt: this.now() }; void this.clearActiveRequest(result.request_id); this.note( 'turn', @@ -642,6 +753,14 @@ export class Controller { // ------------------------------------------------------------------ device private onDeviceEvent(event: DeviceEvent): void { + if (event.type !== 'audio') { + // Any gesture from the glasses means they are in use, and restarts the idle countdown + // even when it changes no state (paging past the last page, for example). + if (event.type !== 'foreground_enter' && event.type !== 'foreground_exit' && event.type !== 'system_exit' && event.type !== 'abnormal_exit') { + this.idleArmed = true; + } + this.scheduleIdleExit(); + } switch (event.type) { case 'audio': return this.onAudio(event.pcm); @@ -794,6 +913,7 @@ export class Controller { conversationId: typeof parsed.conversationId === 'string' ? parsed.conversationId : null, activeRequestId: typeof parsed.activeRequestId === 'string' ? parsed.activeRequestId : null, activeCancelled: parsed.activeCancelled === true, + lastTurnAt: typeof parsed.lastTurnAt === 'number' ? parsed.lastTurnAt : undefined, }; } catch { return null; diff --git a/apps/even-client/src/device/evenAdapter.ts b/apps/even-client/src/device/evenAdapter.ts index a575613..fde36a9 100644 --- a/apps/even-client/src/device/evenAdapter.ts +++ b/apps/even-client/src/device/evenAdapter.ts @@ -234,6 +234,15 @@ export class EvenDevice implements DevicePort { await this.enqueue(() => this.bridge.shutDownPageContainer(1), false); } + async exitNow(): Promise { + // Mode 0: leave immediately. The Even app then closes the phone-side page too. + await this.enqueue(() => this.bridge.shutDownPageContainer(0), false); + } + + onLaunchSource(listener: (source: 'appMenu' | 'glassesMenu') => void): () => void { + return this.bridge.onLaunchSource((source) => listener(source)); + } + 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 diff --git a/apps/even-client/src/device/port.ts b/apps/even-client/src/device/port.ts index 12f093a..61d581d 100644 --- a/apps/even-client/src/device/port.ts +++ b/apps/even-client/src/device/port.ts @@ -16,6 +16,14 @@ export interface DevicePort { onConnection(listener: (connected: boolean) => void): () => void; /** Ask the OS to show its own exit confirmation. */ requestExit(): Promise; + /** + * Leave the glasses now, with no confirmation, returning them to their normal screen. Used + * when the app has been idle: while it is open it occupies the display and (seen on a real + * G2) phone notifications do not reach the lenses. + */ + exitNow(): Promise; + /** Optional: how this session was opened (`glassesMenu` covers the menu and voice launch). */ + onLaunchSource?(listener: (source: 'appMenu' | 'glassesMenu') => void): () => void; /** * 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: '' }`). diff --git a/apps/even-client/src/device/previewDevice.ts b/apps/even-client/src/device/previewDevice.ts index 67647d4..fe0250f 100644 --- a/apps/even-client/src/device/previewDevice.ts +++ b/apps/even-client/src/device/previewDevice.ts @@ -68,6 +68,12 @@ export class BrowserPreviewDevice implements DevicePort { async requestExit(): Promise {} + /** The preview cannot leave anything; it only says so. */ + async exitNow(): Promise { + this.body.textContent = '(Pepper would now leave the glasses.)'; + this.status.textContent = ''; + } + async storageGet(key: string): Promise { try { return { ok: true, value: localStorage.getItem(key) ?? '' }; diff --git a/apps/even-client/src/main.ts b/apps/even-client/src/main.ts index 7e773bc..82d102b 100644 --- a/apps/even-client/src/main.ts +++ b/apps/even-client/src/main.ts @@ -10,6 +10,8 @@ import './ui/phone.css'; const { controller } = await boot(document, window, { bridgeUrl: import.meta.env.VITE_HERMEVEN_BRIDGE_URL ?? '', dev: import.meta.env.DEV, + // Development only: `?idleExit=off` keeps the app open, for automated simulator runs. + idleExit: !(import.meta.env.DEV && new URLSearchParams(location.search).get('idleExit') === 'off'), }); // Development-only convenience for automated simulator runs, where nothing can type into the diff --git a/apps/even-client/src/ui/phone.ts b/apps/even-client/src/ui/phone.ts index 02caa31..d546f26 100644 --- a/apps/even-client/src/ui/phone.ts +++ b/apps/even-client/src/ui/phone.ts @@ -198,6 +198,7 @@ export function mountPhoneUi(root: HTMLElement, controller: Controller, defaults ['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'], diff --git a/tests/fakes/fakeDevice.ts b/tests/fakes/fakeDevice.ts index a3c29f9..a099a8a 100644 --- a/tests/fakes/fakeDevice.ts +++ b/tests/fakes/fakeDevice.ts @@ -51,6 +51,19 @@ export class FakeDevice implements DevicePort { async requestExit(): Promise { this.exitRequests += 1; } + /** Times the app left the glasses by itself. */ + exits = 0; + async exitNow(): Promise { + this.exits += 1; + } + private readonly launchListeners = new Set<(source: 'appMenu' | 'glassesMenu') => void>(); + onLaunchSource(listener: (source: 'appMenu' | 'glassesMenu') => void): () => void { + this.launchListeners.add(listener); + return () => this.launchListeners.delete(listener); + } + launchedFrom(source: 'appMenu' | 'glassesMenu'): void { + for (const l of this.launchListeners) l(source); + } /** Set to make storage writes report "not confirmed" without writing. */ storageWritesFail = false; storageReadsFail = false; diff --git a/tests/integration/client-bridge.test.ts b/tests/integration/client-bridge.test.ts index 94bc346..5b3099e 100644 --- a/tests/integration/client-bridge.test.ts +++ b/tests/integration/client-bridge.test.ts @@ -34,8 +34,12 @@ async function until(what: string, predicate: () => boolean, timeoutMs = 4000): } const phase = () => snapshot.state.phase; +let controllerExtras: Partial[0]> = {}; function makeController(dev: FakeDevice): Controller { return new Controller({ + // Off unless a test turns it on: most tests sit on a screen longer than a short timeout. + idleExit: null, + ...controllerExtras, device: dev, measure: (text, width) => measureTextWrap(text, width).lineCount, locale: 'en-US', @@ -82,6 +86,7 @@ async function pairedController(): Promise { beforeEach(async () => { network = { down: false, dropReplies: false, hook: null, sent: [] }; + controllerExtras = {}; h = await createHarness({ env: { HERMEVEN_CAPTURE_MAX_SECONDS: '2' } }); }); afterEach(async () => { @@ -681,3 +686,157 @@ describe('long press (a real G2 reported a slow tap as a long press)', () => { expect(snapshot.state.conversationId).not.toBeNull(); }); }); + +const quiet = (ms: number) => new Promise((r) => setTimeout(r, ms)); + +describe('leaving the glasses when idle (the app blocks notifications while it is open)', () => { + const FAST = { answer: 150, ready: 250, message: 100 }; + + it('after an answer sits untouched, Pepper leaves the glasses once, without a confirmation dialog', async () => { + controllerExtras = { idleExit: FAST }; + await pairedController(); + device.launchedFrom('glassesMenu'); + controller.askText('hello'); + await until('answer', () => phase() === 'answer'); + expect(device.exits).toBe(0); + await until('left the glasses', () => device.exits === 1, 1500); + await quiet(400); + expect(device.exits).toBe(1); + expect(device.exitRequests).toBe(0); // not the "are you sure?" dialog + expect(device.micOpen).toBe(false); + expect(snapshot.log.some((e) => e.detail.includes('leaving the glasses: idle on answer'))).toBe(true); + }); + + it('paging, or any gesture, restarts the countdown', async () => { + controllerExtras = { idleExit: FAST }; + await pairedController(); + device.launchedFrom('glassesMenu'); + h.hermes.next({ kind: 'complete', output: Array.from({ length: 80 }, (_, i) => `Sentence ${i + 1} of a long answer.`).join(' ') }); + controller.askText('long one'); + await until('answer', () => phase() === 'answer'); + for (let i = 0; i < 6; i++) { + await quiet(90); // each gap is shorter than the 150 ms timeout + device.swipeDown(); + } + expect(device.exits).toBe(0); // 540 ms have passed, well over the timeout, but never idle + await until('left once it was left alone', () => device.exits === 1, 1500); + }); + + it('never leaves while recording, transcribing, thinking or waiting for an approval', async () => { + controllerExtras = { idleExit: FAST }; + await pairedController(); + device.launchedFrom('glassesMenu'); + device.tap(); + await until('listening', () => phase() === 'listening' && device.micOpen); + device.speak(0.2); + await quiet(250); // (shorter than the 300 ms microphone-stall check in these tests) + expect(device.exits).toBe(0); + h.hermes.next({ kind: 'complete', afterMs: 500, output: 'slow answer' }); + device.tap(); + await until('thinking', () => phase() === 'thinking'); + await quiet(350); + expect(phase()).toBe('thinking'); + expect(device.exits).toBe(0); + await until('answer', () => phase() === 'answer'); + + h.hermes.next({ kind: 'approval' }); + controller.askText('needs approval'); + await until('approval', () => phase() === 'approval'); + await quiet(350); + expect(device.exits).toBe(0); + device.doubleTap(); + }); + + it('at Ready with nothing asked, and after an error or a cancel, it also leaves', async () => { + controllerExtras = { idleExit: FAST }; + await pairedController(); + device.launchedFrom('glassesMenu'); + await until('left from Ready', () => device.exits === 1, 1500); + + await controller.stop(); + const stored = device.storage; + device = new FakeDevice(); + for (const [k, v] of stored) device.storage.set(k, v); + controller = makeController(device); + await controller.start(); + device.launchedFrom('glassesMenu'); + device.micAllowed = false; + device.tap(); + await until('error', () => phase() === 'error'); + await until('left from the error screen', () => device.exits === 1, 1500); + }); + + it('opened from the phone with no gesture yet, it stays: setting up on the phone is not interrupted', async () => { + controllerExtras = { idleExit: FAST }; + await pairedController(); + device.launchedFrom('appMenu'); + controller.askText('typed on the phone'); + await until('answer', () => phase() === 'answer'); + await quiet(500); + expect(device.exits).toBe(0); + // The first gesture on the glasses means they are in use: from then on it applies. + device.swipeDown(); + await until('left after the glasses were used', () => device.exits === 1, 1500); + }); + + it('touching the phone page holds it open for the grace period', async () => { + controllerExtras = { idleExit: FAST, phoneGraceMs: 500 }; + await pairedController(); + device.launchedFrom('glassesMenu'); + controller.askText('hello'); + await until('answer', () => phase() === 'answer'); + controller.notePhoneActivity(); + await quiet(450); // three timeouts' worth + expect(device.exits).toBe(0); + await until('left after the grace period', () => device.exits === 1, 2000); + }); + + it('can be switched off entirely', async () => { + controllerExtras = { idleExit: null }; + await pairedController(); + device.launchedFrom('glassesMenu'); + controller.askText('hello'); + await until('answer', () => phase() === 'answer'); + await quiet(600); + expect(device.exits).toBe(0); + }); +}); + +describe('conversations now that Pepper leaves between questions', () => { + it('a question soon after the last one continues the conversation across a relaunch', async () => { + await pairedController(); + controller.askText('My dog is called Biscuit.'); + await until('answer', () => phase() === 'answer'); + await until('saved', () => typeof JSON.parse(device.storage.get('hermeven.v1')!).lastTurnAt === 'number'); + await controller.stop(); + const reborn = new FakeDevice(); + for (const [k, v] of device.storage) reborn.storage.set(k, v); + device = reborn; + controller = makeController(device); + await controller.start(); + controller.askText('What is my dog called?'); + await until('answer', () => phase() === 'answer'); + expect(device.frame.body).toContain('turn=2'); + expect(h.hermes.sessions.size).toBe(1); + }); + + it('a question after a long silence starts a new conversation', async () => { + await pairedController(); + controller.askText('My dog is called Biscuit.'); + await until('answer', () => phase() === 'answer'); + await until('saved', () => typeof JSON.parse(device.storage.get('hermeven.v1')!).lastTurnAt === 'number'); + await controller.stop(); + const reborn = new FakeDevice(); + for (const [k, v] of device.storage) reborn.storage.set(k, v); + device = reborn; + controllerExtras = { conversationGapMs: 50 }; + await quiet(120); + controller = makeController(device); + await controller.start(); + expect(snapshot.state.conversationId).toBeNull(); + controller.askText('What is my dog called?'); + await until('answer', () => phase() === 'answer'); + expect(device.frame.body).toContain('turn=1'); + expect(h.hermes.sessions.size).toBe(2); + }); +}); diff --git a/tests/integration/durableRequestId.test.ts b/tests/integration/durableRequestId.test.ts index befe5fe..49d7597 100644 --- a/tests/integration/durableRequestId.test.ts +++ b/tests/integration/durableRequestId.test.ts @@ -50,6 +50,7 @@ class FakeEvenHost { return () => this.hub.delete(cb); }, onDeviceStatusChanged: () => () => undefined, + onLaunchSource: () => () => undefined, }; heldWrites(): number { diff --git a/tests/simulator/simulator.test.ts b/tests/simulator/simulator.test.ts index 70a283c..d55ae33 100644 --- a/tests/simulator/simulator.test.ts +++ b/tests/simulator/simulator.test.ts @@ -166,7 +166,8 @@ beforeAll(async () => { const automationPort = await freePort(); automation = `http://127.0.0.1:${automationPort}`; const bin = require.resolve('@evenrealities/sim-linux-x64/bin/evenhub-simulator'); - const url = `${pageOrigin}/?bridge=${encodeURIComponent(h.url)}&pair=${encodeURIComponent(code)}`; + // idleExit=off: this suite drives the app for longer than the idle timeout between steps. + const url = `${pageOrigin}/?idleExit=off&bridge=${encodeURIComponent(h.url)}&pair=${encodeURIComponent(code)}`; // alsa:null yields silence: the simulator never opens a real microphone in this test. sim = spawn(bin, [url, '--automation-port', String(automationPort), '--no-glow', '--aid', 'alsa:null'], { stdio: ['ignore', 'pipe', 'pipe'],