From e5559dc5e7594bbe5a6c109a811df8e9abe23bef Mon Sep 17 00:00:00 2001 From: Dan Date: Sat, 21 Nov 2026 12:14:39 -0800 Subject: [PATCH] Wait for the Even app host before choosing browser-preview mode Found on the first real-phone run: the Even app's WebView provided window.flutter_inappwebview after the page's script had started, so the page wrongly fell back to browser-preview mode and never created the HUD page on the glasses. The page now waits (up to 6 s, polling and listening for the WebView's platform-ready event) and, if the host appears later still, reloads once into the real mode. Diagnostics show how long detection took and the browser's user agent. Tests: 205 passed (7 new); simulator 6 passed. Not reviewed. Co-Authored-By: Claude Fable 5.2 --- apps/even-client/src/device/hostDetect.ts | 79 +++++++++++++++++++ apps/even-client/src/main.ts | 29 ++++++- apps/even-client/src/ui/phone.ts | 1 + tests/integration/hostDetect.test.ts | 94 +++++++++++++++++++++++ 4 files changed, 199 insertions(+), 4 deletions(-) create mode 100644 apps/even-client/src/device/hostDetect.ts create mode 100644 tests/integration/hostDetect.test.ts diff --git a/apps/even-client/src/device/hostDetect.ts b/apps/even-client/src/device/hostDetect.ts new file mode 100644 index 0000000..5c79335 --- /dev/null +++ b/apps/even-client/src/device/hostDetect.ts @@ -0,0 +1,79 @@ +/** + * Decide whether this page is running inside the Even app. + * + * The Even app's WebView provides `window.flutter_inappwebview.callHandler`, but not + * necessarily before the page's own script starts: on a real phone it appeared after our + * module had already run (first device test, 2026-11-21), although the simulator provides it + * at once. So the page waits for it, and also listens for the WebView's own "platform ready" + * event, before concluding it is in an ordinary browser. + */ +export interface HostWindow { + flutter_inappwebview?: { callHandler?: unknown }; + addEventListener(type: string, listener: () => void): void; + removeEventListener(type: string, listener: () => void): void; +} + +export interface HostDetection { + found: boolean; + /** How long the page waited before deciding. */ + waitedMs: number; +} + +export const HOST_WAIT_MS = 6000; +/** The event flutter_inappwebview dispatches on `window` once its JavaScript bridge is usable. */ +export const PLATFORM_READY_EVENT = 'flutterInAppWebViewPlatformReady'; + +export function hostPresent(win: HostWindow): boolean { + return typeof win.flutter_inappwebview?.callHandler === 'function'; +} + +export function waitForEvenHost( + win: HostWindow, + options: { timeoutMs?: number; pollMs?: number; now?: () => number } = {}, +): Promise { + const timeoutMs = options.timeoutMs ?? HOST_WAIT_MS; + const pollMs = options.pollMs ?? 50; + const now = options.now ?? Date.now; + const started = now(); + return new Promise((resolve) => { + let done = false; + const finish = (found: boolean) => { + if (done) return; + done = true; + clearInterval(poll); + clearTimeout(deadline); + win.removeEventListener(PLATFORM_READY_EVENT, onReady); + resolve({ found, waitedMs: now() - started }); + }; + const check = () => { + if (hostPresent(win)) finish(true); + }; + // The event alone is not proof (anything can dispatch it); it only prompts a re-check. + const onReady = () => check(); + const poll = setInterval(check, pollMs); + const deadline = setTimeout(() => finish(hostPresent(win)), timeoutMs); + win.addEventListener(PLATFORM_READY_EVENT, onReady); + check(); + }); +} + +/** + * After the page has settled on browser-preview mode, keep watching: if the Even host turns + * up after all, call `onLate` once (the page reloads itself into the real mode). + */ +export function watchForLateHost(win: HostWindow, onLate: () => void, pollMs = 500): () => void { + let fired = false; + const check = () => { + if (fired || !hostPresent(win)) return; + fired = true; + stop(); + onLate(); + }; + const timer = setInterval(check, pollMs); + win.addEventListener(PLATFORM_READY_EVENT, check); + const stop = () => { + clearInterval(timer); + win.removeEventListener(PLATFORM_READY_EVENT, check); + }; + return stop; +} diff --git a/apps/even-client/src/main.ts b/apps/even-client/src/main.ts index 5996527..c81d8f5 100644 --- a/apps/even-client/src/main.ts +++ b/apps/even-client/src/main.ts @@ -2,6 +2,7 @@ import { waitForEvenAppBridge } from '@evenrealities/even_hub_sdk'; import { measureTextWrap } from '@evenrealities/pretext'; import { Controller } from './core/controller.ts'; import { EvenDevice } from './device/evenAdapter.ts'; +import { waitForEvenHost, watchForLateHost, type HostWindow } from './device/hostDetect.ts'; import { BrowserPreviewDevice } from './device/previewDevice.ts'; import type { DevicePort } from './device/port.ts'; import { mountPhoneUi } from './ui/phone.ts'; @@ -13,15 +14,35 @@ import './ui/phone.css'; * bridge, so a clearly-labelled preview device is used instead: it has no * microphone and proves nothing about hardware. */ +const RELOAD_FLAG = 'hermeven.reloadedForHost'; + async function resolveDevice(): Promise<{ device: DevicePort; runtime: string }> { - const hasHost = typeof (window as { flutter_inappwebview?: unknown }).flutter_inappwebview !== 'undefined'; - if (hasHost) { + const host = window as unknown as HostWindow; + // The Even app can provide its connection a moment after the page starts, so wait for it + // rather than deciding on the first instant. + const detection = await waitForEvenHost(host); + if (detection.found) { const bridge = await waitForEvenAppBridge(); - return { device: new EvenDevice(bridge), runtime: 'Even app host (SDK 0.0.16)' }; + return { device: new EvenDevice(bridge), runtime: `Even app host (SDK 0.0.16), found after ${detection.waitedMs} ms` }; } const preview = document.getElementById('preview')!; preview.hidden = false; - return { device: new BrowserPreviewDevice(preview), runtime: 'Browser preview: no glasses, no microphone' }; + // If the host appears later still, reload once into the real mode (once, so a host that + // comes and goes cannot put the page in a reload loop). + watchForLateHost(host, () => { + let already = false; + try { + already = sessionStorage.getItem(RELOAD_FLAG) === '1'; + sessionStorage.setItem(RELOAD_FLAG, '1'); + } catch { + already = true; + } + if (!already) location.reload(); + }); + return { + device: new BrowserPreviewDevice(preview), + runtime: `Browser preview: no glasses, no microphone (no Even host after ${detection.waitedMs} ms)`, + }; } const { device, runtime } = await resolveDevice(); diff --git a/apps/even-client/src/ui/phone.ts b/apps/even-client/src/ui/phone.ts index cbd9094..fb04cca 100644 --- a/apps/even-client/src/ui/phone.ts +++ b/apps/even-client/src/ui/phone.ts @@ -196,6 +196,7 @@ export function mountPhoneUi(root: HTMLElement, controller: Controller, defaults rows(diagList, [ ['Runtime', defaults.runtime], ['Page origin', location.origin], + ['Browser', navigator.userAgent], ['HUD page', s.hudReady ? 'created' : 'not created'], ['Device id', s.deviceId || 'none'], ['Conversation id', s.state.conversationId ?? 'none'], diff --git a/tests/integration/hostDetect.test.ts b/tests/integration/hostDetect.test.ts new file mode 100644 index 0000000..a0888fe --- /dev/null +++ b/tests/integration/hostDetect.test.ts @@ -0,0 +1,94 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { HOST_WAIT_MS, PLATFORM_READY_EVENT, waitForEvenHost, watchForLateHost, type HostWindow } from '../../apps/even-client/src/device/hostDetect.ts'; + +/** + * Found on the first real-phone run (2026-11-21): the Even app's connection was not yet on + * `window` when the page's script started, and the page wrongly chose browser-preview mode. + */ +function fakeWindow() { + const listeners = new Map void>>(); + const win: HostWindow & { fire(type: string): void; listenerCount(): number } = { + addEventListener: (type, l) => void (listeners.get(type) ?? listeners.set(type, new Set()).get(type)!).add(l), + removeEventListener: (type, l) => void listeners.get(type)?.delete(l), + fire: (type) => listeners.get(type)?.forEach((l) => l()), + listenerCount: () => [...listeners.values()].reduce((n, s) => n + s.size, 0), + }; + return win; +} +const host = { callHandler: () => undefined }; + +beforeEach(() => vi.useFakeTimers()); +afterEach(() => vi.useRealTimers()); + +describe('detecting the Even app host', () => { + it('present from the start (the simulator): found at once', async () => { + const win = fakeWindow(); + win.flutter_inappwebview = host; + expect(await waitForEvenHost(win)).toEqual({ found: true, waitedMs: 0 }); + expect(win.listenerCount()).toBe(0); + }); + + it('appears shortly after the page starts (the real phone): found, not mistaken for a browser', async () => { + const win = fakeWindow(); + const detecting = waitForEvenHost(win); + await vi.advanceTimersByTimeAsync(800); + win.flutter_inappwebview = host; + await vi.advanceTimersByTimeAsync(60); + const result = await detecting; + expect(result.found).toBe(true); + expect(result.waitedMs).toBeGreaterThanOrEqual(800); + expect(result.waitedMs).toBeLessThan(1000); + }); + + it("the WebView's platform-ready event triggers an immediate check", async () => { + const win = fakeWindow(); + const detecting = waitForEvenHost(win, { pollMs: 100_000 }); + await vi.advanceTimersByTimeAsync(300); + win.flutter_inappwebview = host; + win.fire(PLATFORM_READY_EVENT); + expect((await detecting).found).toBe(true); + }); + + it('the event alone, with no host object, proves nothing', async () => { + const win = fakeWindow(); + const detecting = waitForEvenHost(win); + win.fire(PLATFORM_READY_EVENT); + await vi.advanceTimersByTimeAsync(HOST_WAIT_MS + 10); + expect((await detecting).found).toBe(false); + }); + + it('an object without a callable callHandler is not a host', async () => { + const win = fakeWindow(); + win.flutter_inappwebview = {}; + const detecting = waitForEvenHost(win); + await vi.advanceTimersByTimeAsync(HOST_WAIT_MS + 10); + expect((await detecting).found).toBe(false); + }); + + it('a plain browser: gives up after the wait and cleans up', async () => { + const win = fakeWindow(); + const detecting = waitForEvenHost(win); + await vi.advanceTimersByTimeAsync(HOST_WAIT_MS - 10); + let settled = false; + void detecting.then(() => (settled = true)); + await Promise.resolve(); + expect(settled).toBe(false); + await vi.advanceTimersByTimeAsync(20); + expect(await detecting).toEqual({ found: false, waitedMs: HOST_WAIT_MS }); + expect(win.listenerCount()).toBe(0); + }); + + it('a host that turns up after preview mode was chosen triggers exactly one late callback', async () => { + const win = fakeWindow(); + let late = 0; + watchForLateHost(win, () => (late += 1)); + await vi.advanceTimersByTimeAsync(3000); + expect(late).toBe(0); + win.flutter_inappwebview = host; + await vi.advanceTimersByTimeAsync(600); + win.fire(PLATFORM_READY_EVENT); + await vi.advanceTimersByTimeAsync(5000); + expect(late).toBe(1); + expect(win.listenerCount()).toBe(0); + }); +});