diff --git a/app/apps/nightscout/nightscout-app.ts b/app/apps/nightscout/nightscout-app.ts index b2fbdb00..2f6c536e 100644 --- a/app/apps/nightscout/nightscout-app.ts +++ b/app/apps/nightscout/nightscout-app.ts @@ -62,6 +62,7 @@ export function createNightscoutAppWindow(options: InProcessAppOptions): InProce submitFrame: options.submitFrame, setSurfaceVisible: options.setSurfaceVisible, removeSurface: options.removeSurface, + reconfigureSurface: options.reconfigureSurface, onClosed: () => { windowRenders.delete(render); syncNightscout(); diff --git a/app/g2/ios-preview-controller.ts b/app/g2/ios-preview-controller.ts index 37106104..566eeed8 100644 --- a/app/g2/ios-preview-controller.ts +++ b/app/g2/ios-preview-controller.ts @@ -1,6 +1,7 @@ import { Dialogs, File, knownFolders, path, type ImageSource } from '@nativescript/core' import { iosBluetooth } from '../native/ios-bluetooth' import { iosVoiceInput } from '../native/ios-voice-input' +import { nightscoutBridge } from '../native/nightscout-bridge' import { GlassesSession, type SessionState } from './glasses-session' import { GlanceHost, type GlanceDisplay } from './glance-host' import { OsEventTypeList } from './events' @@ -11,7 +12,7 @@ import { ALL_APPS } from '../apps/all-apps' import type { AppContext, AppDefinition, AppLaunchParams } from '../apps/app-definition' import { WorkerAppHost } from '../ui/shell/worker-window' import { createInProcessWindow, YieldAtRootLayer, type InProcessAppOptions, type InProcessWindow } from '../ui/shell/in-process-window' -import { getStringSettingById } from '../ui/dashboard-settings' +import { getStringSettingById, nightscoutSiteUrlSetting, nightscoutApiTokenSetting } from '../ui/dashboard-settings' import { readPhoneBatteryState } from '../native/phone-battery' import { iosAppUnavailableReason } from '../apps/ios-availability' import { SurfaceCompositor } from '../graphics/surface-compositor' @@ -152,6 +153,7 @@ export class IosPreviewController { this.runtimeRunning = running for (const window of shell.getWindows()) window.setScreenOn?.(running && shell.isScreenOn()) if (!running) { + void nightscoutBridge.stop().catch(error => this.fail(error)) this.glance.dismiss() this.compositor.setScreenBlanked(!shell.isScreenOn()) this.offSettings?.(); this.offSettings = null @@ -163,6 +165,7 @@ export class IosPreviewController { return } UIDevice.currentDevice.batteryMonitoringEnabled = true + void nightscoutBridge.start().catch(error => this.fail(error)) for (const name of [UIDeviceBatteryLevelDidChangeNotification, UIDeviceBatteryStateDidChangeNotification]) { this.batteryObservers.push(NSNotificationCenter.defaultCenter.addObserverForNameObjectQueueUsingBlock(name, null, NSOperationQueue.mainQueue, () => this.requestShellRender())) } @@ -307,15 +310,20 @@ export class IosPreviewController { create: (options: InProcessAppOptions) => InProcessWindow): Promise { const existing = this.inProcessApps.get(windowId) if (existing) { shell.focusWindow(windowId); existing.requestRender(); this.requestShellRender(); return } + // Apps can request a render while their factory runs (Nightscout's tray + // subscription does). The surface only exists once the factory returns. + // The explicit render below supplies a fresh frame after configuration. + let surfaceReady = false const app = create({ - actions: this.actions, submitFrame: planes => this.submit(surfaceId, planes), + actions: this.actions, submitFrame: planes => surfaceReady ? this.submit(surfaceId, planes) : Promise.resolve(), setSurfaceVisible: visible => { this.compositor.setSurfaceVisible(surfaceId, visible); this.scheduleFrame() }, - removeSurface: () => { this.compositor.removeSurface(surfaceId); this.scheduleFrame() }, + removeSurface: () => { surfaceReady = false; this.compositor.removeSurface(surfaceId); this.scheduleFrame() }, reconfigureSurface: () => { const window = shell.getWindows().find(w => w.windowId === windowId); if (window) this.configureWindow(window); this.requestShellRender() }, onClosed: () => { this.inProcessApps.delete(windowId) }, }) this.inProcessApps.set(windowId, app) this.configureWindow(app.window) + surfaceReady = true shell.registerWindow(app.window); shell.focusWindow(windowId) app.requestRender(); this.requestShellRender() } @@ -419,6 +427,9 @@ export class IosPreviewController { private async editSetting(setting: { editorTitle: string; get(): string; set(value: string): void }): Promise { if (!this.active) { this.logBluetooth('Editing text settings requires opening Faceclaw on the phone'); return } const result = await Dialogs.prompt({ title: setting.editorTitle, defaultText: setting.get(), okButtonText: 'Save', cancelButtonText: 'Cancel' }) - if (result.result) setting.set(result.text) + if (result.result) { + setting.set(result.text) + if (setting === nightscoutSiteUrlSetting || setting === nightscoutApiTokenSetting) await nightscoutBridge.refreshNow() + } } } diff --git a/app/graphics/surface-compositor.ios.ts b/app/graphics/surface-compositor.ios.ts index 8cb04f50..30fc81f7 100644 --- a/app/graphics/surface-compositor.ios.ts +++ b/app/graphics/surface-compositor.ios.ts @@ -5,6 +5,7 @@ declare const FaceclawKitIosSurfaceCompositor: any /** Retained pixels, clipping, layers and composition live in shared Kotlin. */ export class SurfaceCompositor { private native: any + private readonly surfaces = new Set() constructor(readonly width: number, readonly height: number) { if (!Number.isInteger(width) || !Number.isInteger(height) || width <= 0 || height <= 0) throw new Error('Invalid compositor size') this.native = FaceclawKitIosSurfaceCompositor.alloc().initWithWidthHeight(width, height) @@ -13,8 +14,9 @@ export class SurfaceCompositor { if (![options.x, options.y, options.width, options.height, options.zOrder].every(Number.isInteger) || options.width <= 0 || options.height <= 0) throw new Error('Invalid surface geometry') this.native.configureIdXYWidthHeightZOrderTransparent(id, options.x, options.y, options.width, options.height, options.zOrder, options.transparency === 'color-key') + this.surfaces.add(id) } - removeSurface(id: string): void { this.native.removeId(id) } + removeSurface(id: string): void { this.native.removeId(id); this.surfaces.delete(id) } setSurfaceVisible(id: string, visible: boolean): void { this.native.visibleIdVisible(id, visible) } setUnderlayDim(belowZOrder: number, factor: number): void { if (!Number.isFinite(factor)) throw new Error('Invalid dim factor') @@ -22,6 +24,9 @@ export class SurfaceCompositor { } setScreenBlanked(blanked: boolean): void { this.native.blankBlanked(blanked) } submitSurfaceFrame(id: string, pixels: Uint8Array, rect: SurfaceRect): void { + // Keep lifecycle errors catchable in JS; an undeclared Kotlin exception + // crossing the Objective-C boundary terminates the process. + if (!this.surfaces.has(id)) throw new Error(`Unknown surface: ${id}`) if (![rect.x, rect.y, rect.width, rect.height].every(Number.isInteger) || rect.width <= 0 || rect.height <= 0 || pixels.length !== rect.width * rect.height) throw new Error('Invalid frame buffer or rectangle') this.native.submitIdDataXYWidthHeight(id, toData(pixels), rect.x, rect.y, rect.width, rect.height) diff --git a/app/native/nightscout-bridge.ts b/app/native/nightscout-bridge.ts index 5da6237d..646b6622 100644 --- a/app/native/nightscout-bridge.ts +++ b/app/native/nightscout-bridge.ts @@ -167,10 +167,12 @@ export class NightscoutBridge { await this.refreshNow(); return; } - await this.refreshNow(); + // Register polling before awaiting HTTP so stop() during the first fetch + // cannot leave a timer behind, and concurrent starts share one timer. this.refreshHandle = setInterval(() => { void this.refreshNow(); }, NIGHTSCOUT_REFRESH_MS); + await this.refreshNow(); } async stop(): Promise { diff --git a/tests/ios-app-host.test.cjs b/tests/ios-app-host.test.cjs index 5a180c9b..2d4b702c 100644 --- a/tests/ios-app-host.test.cjs +++ b/tests/ios-app-host.test.cjs @@ -72,7 +72,7 @@ test('settings-driven repaint runs after font cache invalidation, regardless of test('background glasses input still composites frames; phone resume preserves the session; explicit stop stays stopped', async () => { const tasks = new Map(), screenStates = [], inputs = [], frames = [], previews = [], states = []; - let nextTask = 0, starts = 0, stops = 0, session; + let nextTask = 0, starts = 0, stops = 0, pollStarts = 0, pollStops = 0, session; const window = { windowId: 'launcher', surfaceId: 'launcher', appId: 'launcher', title: 'Apps', setScreenOn: on => screenStates.push(on), requestRender() {} }; const shell = { configure() {}, registerWindow() {}, wake() {}, focusWindow() {}, @@ -92,6 +92,7 @@ test('background glasses input still composites frames; phone resume preserves t '@nativescript/core': { File: { fromPath: () => ({ writeTextSync() {} }) }, knownFolders: { documents: () => ({ path: '/tmp' }) }, path }, '../native/ios-voice-input': { iosVoiceInput: { handleSessionEnded() {} } }, '../native/ios-bluetooth': { iosBluetooth: () => ({}) }, './glasses-session': { GlassesSession: Session }, + '../native/nightscout-bridge': { nightscoutBridge: { async start() { pollStarts++; }, async stop() { pollStops++; } } }, './glance-host': { GlanceHost: class { dismiss() {} isVisible() { return false; } } }, './device-addresses': { loadDeviceAddresses: () => ({}) }, './ios-peripheral-identity': { deviceAddressError: () => null }, '../apps/launcher/launcher-app': { createLauncherWindow: () => window, LAUNCHER_SURFACE_ID: 'launcher' }, @@ -122,6 +123,7 @@ test('background glasses input still composites frames; phone resume preserves t const previewCount = previews.length, stateCount = states.length; controller.pause(); controller.pause(); // NativeScript also unloads its root page on background entry. assert.equal(stops, 0); assert.ok(screenStates.every(Boolean)); + assert.equal(pollStarts, 1); assert.equal(pollStops, 0, 'connected glasses keep Nightscout polling in background'); session.onInput({ eventType: 3, eventSource: 1 }); await controller.inputQueue; flush(); assert.equal(inputs.length, 1); assert.ok(frames.length >= 2); @@ -130,11 +132,13 @@ test('background glasses input still composites frames; phone resume preserves t assert.equal(starts, 1); assert.ok(previews.length > previewCount); controller.pause(); await controller.disconnect(); flush(); assert.equal(stops, 1); assert.equal(screenStates.at(-1), false); + assert.equal(pollStops, 1); const frameCount = frames.length; session.onInput({ eventType: 3, eventSource: 1 }); await controller.inputQueue; flush(); assert.equal(inputs.length, 1); assert.equal(frames.length, frameCount); controller.resume(); flush(); assert.equal(starts, 1); assert.equal(controller.connectionState.phase, 'disconnected'); + assert.equal(pollStarts, 2, 'resuming the phone restarts Nightscout polling'); }); test('iOS bandwidth footer toggles live, polls only in foreground and resets its rate window on resume', () => { @@ -182,3 +186,57 @@ test('iOS bandwidth footer toggles live, polls only in foreground and resets its enabled = false; for (const fn of settingListeners) fn(); assert.equal(footer.visibility, 'collapse'); assert.equal(intervals.size, 0); page.events.get('unloaded')(); assert.equal(appEvents.size, 0); assert.equal(settingListeners.size, 0); }); + +test('iOS configures an in-process surface before submitting constructor-triggered frames', async () => { + const submitted = [], surfaces = new Set(); + const shell = { getWindows: () => [], configure() {}, registerWindow() {}, focusWindow() {}, foregroundWindow: () => null }; + const api = load('app/g2/ios-preview-controller.ts', { + require: name => ({ + '../ui/shell/shell': { shell }, + '../ui/shell/geometry': { appViewportRect: () => ({ x: 0, y: 0, width: 2, height: 1 }) }, + '../graphics/plane': { flattenPlanes: planes => planes[0] }, + })[name] ?? {}, + console, + }); + // Exercise the real launch method with a strict compositor boundary. App + // construction paints synchronously, as Nightscout's tray subscription does. + const controller = Object.create(api.IosPreviewController.prototype); + controller.inProcessApps = new Map(); + controller.requestShellRender = () => {}; + controller.scheduleFrame = () => {}; + controller.compositor = { + configureSurface(id) { surfaces.add(id); }, setSurfaceVisible() {}, + removeSurface(id) { surfaces.delete(id); }, + submitSurfaceFrame(id, pixels) { assert.ok(surfaces.has(id), `unconfigured ${id}`); submitted.push([...pixels]); }, + }; + let plumbing, early; + const fresh = [{ pixels: new Uint8Array([30, 40]), width: 2, height: 1 }]; + await controller.launchInProcessApp('nightscout', 'window:nightscout', options => { + plumbing = options; + early = options.submitFrame([{ pixels: new Uint8Array([10, 20]), width: 2, height: 1 }]); + return { window: { windowId: 'nightscout', surfaceId: 'window:nightscout', appId: 'nightscout' }, + requestRender: () => options.submitFrame(fresh) }; + }); + await early; + assert.deepEqual(submitted, [[30, 40]]); + plumbing.removeSurface(); + await plumbing.submitFrame(fresh); + assert.deepEqual(submitted, [[30, 40]], 'late callbacks cannot submit to a removed surface'); +}); + +test('iOS compositor rejects missing and removed surfaces before crossing into Kotlin', () => { + let nativeSubmissions = 0; + const native = { configureIdXYWidthHeightZOrderTransparent() {}, removeId() {}, submitIdDataXYWidthHeight() { nativeSubmissions++; } }; + const api = load('app/graphics/surface-compositor.ios.ts', { + require: () => ({ toData: data => data }), + FaceclawKitIosSurfaceCompositor: { alloc: () => ({ initWithWidthHeight: () => native }) }, + }); + const c = new api.SurfaceCompositor(2, 1), pixels = new Uint8Array([1, 2]); + const rect = { x: 0, y: 0, width: 2, height: 1 }; + assert.throws(() => c.submitSurfaceFrame('nightscout', pixels, rect), /Unknown surface/); + c.configureSurface('nightscout', { ...rect, zOrder: 0, transparency: 'opaque' }); + c.submitSurfaceFrame('nightscout', pixels, rect); + c.removeSurface('nightscout'); + assert.throws(() => c.submitSurfaceFrame('nightscout', pixels, rect), /Unknown surface/); + assert.equal(nativeSubmissions, 1); +}); diff --git a/tests/ios-glanceboard.test.cjs b/tests/ios-glanceboard.test.cjs index 51a03554..e8cb9e07 100644 --- a/tests/ios-glanceboard.test.cjs +++ b/tests/ios-glanceboard.test.cjs @@ -72,7 +72,9 @@ function fixture() { knownFolders: { documents: () => ({ path: '/tmp' }) }, path }, '../native/ios-bluetooth': { iosBluetooth: () => ({}) }, '../native/ios-voice-input': { iosVoiceInput: { handleSessionEnded() {} } }, - './glasses-session': { GlassesSession: Session }, './glance-host': { GlanceHost }, './events': events, + './glasses-session': { GlassesSession: Session }, + '../native/nightscout-bridge': { nightscoutBridge: { async start() {}, async stop() {} } }, + './glance-host': { GlanceHost }, './events': events, './device-addresses': { loadDeviceAddresses: () => ({}) }, './ios-peripheral-identity': { deviceAddressError: () => null }, '../apps/launcher/launcher-app': { createLauncherWindow: () => window, LAUNCHER_SURFACE_ID: 'launcher' }, '../apps/all-apps': { ALL_APPS: [{ appId: 'glanceboard', glanceboard: provider }] }, diff --git a/tests/nightscout.test.cjs b/tests/nightscout.test.cjs index 2e65706e..03e69c2b 100644 --- a/tests/nightscout.test.cjs +++ b/tests/nightscout.test.cjs @@ -154,3 +154,30 @@ test('bridge exposes numeric measurements and treats absent values as unknown', await bridge.refreshNow(); assert.equal(bridge.snapshot().reservoirUnits, 0); }); + +test('polling starts once and stops even while the initial HTTP request is pending', async () => { + let resolveHttp, calls = 0, nextTimer = 0; + const pending = new Promise(resolve => { resolveHttp = resolve; }); + const timers = new Map(); + const module = load('app/native/nightscout-bridge.ts', { + '../ui/dashboard-settings': { nightscoutSiteUrlSetting: { get: () => 'https://example.test' }, nightscoutApiTokenSetting: { get: () => 'test' } }, + '../util/http': { async fetchWithUserAgent() { + calls++; + await pending; + return { ok: true, json: async () => [] }; + } }, + }, { Date, console, setInterval(fn) { const id = ++nextTimer; timers.set(id, fn); return id; }, clearInterval(id) { timers.delete(id); } }); + const bridge = new module.NightscoutBridge(); + const first = bridge.start(), second = bridge.start(); + assert.equal(timers.size, 1); + assert.equal(calls, 5); + const stopping = bridge.stop(); + assert.equal(timers.size, 0); + resolveHttp(); + await Promise.all([first, second, stopping]); + assert.equal(timers.size, 0, 'finishing the first refresh must not restart polling'); + await bridge.start(); + assert.equal(timers.size, 1); + assert.equal(calls, 10); + await bridge.stop(); +});