diff --git a/app/g2/ble-image-optimizer.ts b/app/g2/ble-image-optimizer.ts new file mode 100644 index 00000000..46948a67 --- /dev/null +++ b/app/g2/ble-image-optimizer.ts @@ -0,0 +1,34 @@ +import { concat, rle4 } from './ble-protocol' + +/** Android BleImageOptimizer's mode-3 changed rectangle. Coordinates are in + * units of 4 columns / 2 rows; pixels are top-down packed 4bpp, high nibble first. + * null means identical, incomparable, or a full-screen box: use dedup/mode 6. + */ +export function buildBoundingBoxPayload(previous: Uint8Array | null, next: Uint8Array, + width: number, height: number, frameId: number, deflate: (data: Uint8Array) => Uint8Array): Uint8Array | null { + if (!Number.isInteger(width) || !Number.isInteger(height) || width <= 0 || height <= 0 || + width % 4 || height % 2 || width / 4 > 255 || height / 2 > 255 || + !previous || previous.length !== width * height / 2 || next.length !== previous.length) return null + const stride = width / 2 + let minX = stride, maxX = -1, minY = height, maxY = -1 + for (let y = 0; y < height; y++) { + const row = y * stride + for (let x = 0; x < stride; x++) { + if (previous[row + x] === next[row + x]) continue + minX = Math.min(minX, x); maxX = Math.max(maxX, x) + minY = Math.min(minY, y); maxY = y + } + } + if (maxY < 0) return null + const left = (minX * 2) & ~3, right = Math.min(width, ((maxX + 1) * 2 + 3) & ~3) + const top = minY & ~1, bottom = Math.min(height, (maxY + 2) & ~1) + const boxWidth = right - left, boxHeight = bottom - top + if (boxWidth === width && boxHeight === height) return null + const regionStride = boxWidth / 2, region = new Uint8Array(regionStride * boxHeight) + for (let y = 0; y < boxHeight; y++) { + const start = (top + y) * stride + left / 2 + region.set(next.subarray(start, start + regionStride), y * regionStride) + } + return concat(new Uint8Array([3, left / 4, top / 2, boxWidth / 4, boxHeight / 2, + frameId & 255, (frameId >>> 8) & 255]), deflate(rle4(region))) +} diff --git a/app/g2/ble-traffic-counters.ts b/app/g2/ble-traffic-counters.ts new file mode 100644 index 00000000..d37023aa --- /dev/null +++ b/app/g2/ble-traffic-counters.ts @@ -0,0 +1,17 @@ +/** Same units as Android FaceclawBleManager: protocol messages, framed write + * bytes accepted by the transport, and fully acknowledged display updates. + * Totals survive reconnects and the setting being switched off. + */ +export class BleTrafficCounters { + private messages = 0 + private bytes = 0 + private frames = 0 + recordWrite(bytes: number): void { this.bytes += bytes } + recordMessage(): void { this.messages++ } + recordDisplayFrame(): void { this.frames++ } + sample(): { messages: number; bytes: number; frames: number } { + return { messages: this.messages, bytes: this.bytes, frames: this.frames } + } +} +// The iOS BLE session and phone UI both run in the main isolate. +export const iosBleTraffic = new BleTrafficCounters() diff --git a/app/g2/glasses-session.ts b/app/g2/glasses-session.ts index 7066fc99..e18190b5 100644 --- a/app/g2/glasses-session.ts +++ b/app/g2/glasses-session.ts @@ -1,4 +1,6 @@ import * as protocol from './ble-protocol' +import { iosBleTraffic } from './ble-traffic-counters' +import { buildBoundingBoxPayload } from './ble-image-optimizer' import { hexToBytes } from '../util/hex-util' import { deviceAddressError } from './ios-peripheral-identity' @@ -20,6 +22,10 @@ export type SessionState = { phase: 'disconnected' | 'connecting' | 'connected' type PendingAck = { resolve: (message: protocol.ProtocolMessage) => void; reject: (error: Error) => void; timer: number | null; command: number; label: string } class AckTimeout extends Error {} +// Match Android ConnectionOptions.WINDOW_SIZE. This bounds complete image +// messages queued for writing or awaiting ACK, not individual BLE packets. +const DISPLAY_WINDOW_SIZE = 3 +type DisplayFrame = { packed: Uint8Array; payload: Uint8Array; offset: number; pending: number } /** G2 session independent of the phone OS. Images go to L, control to R, as on Android. */ export class GlassesSession { @@ -43,6 +49,12 @@ export class GlassesSession { private addresses: SessionAddresses | null = null private latest: Uint8Array | null = null private displayed: Uint8Array | null = null + private lastEnqueued: Uint8Array | null = null + // Match Android: advance only for emitted deltas, skipping 0 / 0xffff. + private nextImageFrameId = 1 + private displayFrames: DisplayFrame[] = [] + private displaySending: DisplayFrame | null = null + private displayInFlight = 0 private pumping = false private lastHeartbeat = 0 private lastLease = 0 @@ -192,8 +204,15 @@ export class GlassesSession { if (!identifier) return Promise.reject(new Error(`No ${role} device connected`)) const frames = protocol.frameMessage(payload, sid, flag, this.sequence++, this.limits[role]) const previous = this.writes.get(identifier) ?? Promise.resolve() - const work = previous.catch(() => {}).then(async () => { - for (const frame of frames) { this.check(generation); await this.transport.write(identifier, protocol.G2_WRITE, frame) } + // A failed write poisons this link's queue until reset: do not transmit + // later fragments after a hole in the image stream. + const work = previous.then(async () => { + for (const frame of frames) { + this.check(generation) + await this.transport.write(identifier, protocol.G2_WRITE, frame) + iosBleTraffic.recordWrite(frame.length) + } + iosBleTraffic.recordMessage() }) // A whole message owns the write queue; heartbeat packets cannot split an image message. this.writes.set(identifier, work) @@ -312,6 +331,49 @@ export class GlassesSession { if (this.timer !== null || this.pumping || this.state.phase !== 'connected') return this.timer = setTimeout(() => { this.timer = null; void this.pump() }, delay) } + private canSendDisplay(): boolean { + // Also bound completed frames retained behind a missing/out-of-order ACK. + return this.displayInFlight < DISPLAY_WINDOW_SIZE && !!(this.displaySending || + (this.latest && !this.charging && this.displayFrames.length < DISPLAY_WINDOW_SIZE)) + } + private fillDisplayWindow(generation: number): void { + while (this.canSendDisplay()) { + if (!this.displaySending) { + const packed = this.latest!; this.latest = null + // Compare with the last enqueued image, not the last ACKed one. In an + // A -> B -> A sequence, B may still be in flight when A is requested. + if (this.lastEnqueued && packed.every((value, i) => value === this.lastEnqueued![i])) continue + const delta = buildBoundingBoxPayload(this.lastEnqueued, packed, 640, 480, this.nextImageFrameId, this.deflate) + const payload = delta ?? protocol.concat(new Uint8Array([6]), this.deflate(protocol.rle4(packed))) + if (payload.length > 165888) throw new Error('Compressed frame exceeds the glasses image buffer') + if (delta) { + this.nextImageFrameId = this.nextImageFrameId >= 0xfffe ? 1 : this.nextImageFrameId + 1 + this.log(`Display bbox ${delta[3] * 4}x${delta[4] * 2}+${delta[1] * 4}+${delta[2] * 2} fid=${delta[5] | (delta[6] << 8)} (${payload.length} bytes)`) + } else this.log(`Display full 640x480 (${payload.length} bytes)`) + this.displaySending = { packed, payload, offset: 0, pending: 0 } + this.displayFrames.push(this.displaySending); this.lastEnqueued = packed + } + const frame = this.displaySending, offset = frame.offset + frame.offset += 3800; frame.pending++; this.displayInFlight++ + if (frame.offset >= frame.payload.length) this.displaySending = null + // send() serializes whole messages on L, but request() waits for each + // magic's ACK independently. Fill the other slots without awaiting it. + void this.request('left', protocol.SID.hub, magic => protocol.imageFragment(magic, frame.payload, offset), 'Display frame').then(() => { + if (generation !== this.generation) return + frame.pending--; this.displayInFlight--; this.lastHeartbeat = Date.now() + // Retire in submission order even if relayed ACKs arrive out of order. + // A frame counts only after every fragment has been acknowledged. + while (this.displayFrames.length) { + const completed = this.displayFrames[0] + if (completed.offset < completed.payload.length || completed.pending) break + this.displayFrames.shift(); this.displayed = completed.packed + this.state.frames++; iosBleTraffic.recordDisplayFrame(); this.onState({ ...this.state }) + this.log(`Display frame ${this.state.frames} acknowledged (${completed.payload.length} bytes)`) + } + this.wake() + }).catch(error => { if (generation === this.generation) this.fail(error, true) }) + } + } private async pump(): Promise { if (this.pumping || this.state.phase !== 'connected') return this.pumping = true; const generation = this.generation @@ -327,19 +389,10 @@ export class GlassesSession { const settings = await this.request('right', protocol.SID.settings, protocol.settingsQuery, 'Battery query') this.applySettings(settings); this.lastSettings = Date.now() } - const frame = this.latest; this.latest = null - if (frame && !this.charging && (!this.displayed || !frame.every((value, i) => value === this.displayed![i]))) { - const payload = protocol.concat(new Uint8Array([6]), this.deflate(protocol.rle4(frame))) - if (payload.length > 165888) throw new Error('Compressed frame exceeds the glasses image buffer') - for (let offset = 0; offset < payload.length; offset += 3800) { - await this.request('left', protocol.SID.hub, magic => protocol.imageFragment(magic, payload, offset), 'Display frame') - this.check(generation); this.lastHeartbeat = Date.now() - } - this.displayed = frame; this.state.frames++; this.onState({ ...this.state }) - this.log(`Display frame ${this.state.frames} acknowledged (${payload.length} bytes)`) - } else if (frame && this.charging) this.latest = frame + this.check(generation) + this.fillDisplayWindow(generation) } catch (error) { if (generation === this.generation) this.fail(error, true) } - finally { if (generation === this.generation) { this.pumping = false; this.schedule(this.latest && !this.charging ? 0 : 1000) } } + finally { if (generation === this.generation) { this.pumping = false; this.schedule(this.canSendDisplay() ? 0 : 1000) } } } private reset(): void { ++this.generation @@ -352,6 +405,7 @@ export class GlassesSession { const pending = [...this.pending.values()]; this.pending.clear() for (const request of pending) { if (request.timer) clearTimeout(request.timer); request.reject(new Error('Connection ended')) } this.receiver.clear(); this.writes.clear(); this.latest = this.displayed = null + this.lastEnqueued = null; this.displayFrames = []; this.displaySending = null; this.displayInFlight = 0 } private closeLinks(): void { const ids = this.ids; this.ids = {}; this.limits = {} diff --git a/app/native/ble-traffic.ios.ts b/app/native/ble-traffic.ios.ts new file mode 100644 index 00000000..ef3f9a25 --- /dev/null +++ b/app/native/ble-traffic.ios.ts @@ -0,0 +1,3 @@ +import { iosBleTraffic } from '../g2/ble-traffic-counters' +export type { BleTrafficSample } from './ble-traffic' +export function sampleBleTraffic(): { messages: number; bytes: number; frames: number } { return iosBleTraffic.sample() } diff --git a/app/phone-ui/ble-bandwidth-meter.ts b/app/phone-ui/ble-bandwidth-meter.ts new file mode 100644 index 00000000..b534f009 --- /dev/null +++ b/app/phone-ui/ble-bandwidth-meter.ts @@ -0,0 +1,27 @@ +import type { BleTrafficSample } from '../native/ble-traffic' + +/** Shared Android/iOS five-second traffic readout. Poll once per second. */ +export class BleBandwidthMeter { + private history: Array<{ atMs: number; bytes: number; frames: number }> = [] + reset(): void { this.history = [] } + sample(sample: BleTrafficSample, atMs: number): string { + const previous = this.history[this.history.length - 1] + if (previous && (atMs <= previous.atMs || sample.bytes < previous.bytes || sample.frames < previous.frames)) this.reset() + this.history.push({ atMs, bytes: sample.bytes, frames: sample.frames }) + while (this.history.length && this.history[0]!.atMs < atMs - 5000) this.history.shift() + let label = `BLE sent: ${formatCount(sample.messages)} messages, ${formatCount(sample.bytes)} bytes` + const oldest = this.history[0]!, elapsedSec = (atMs - oldest.atMs) / 1000 + if (elapsedSec > 0) { + const byteDelta = sample.bytes - oldest.bytes, frameDelta = sample.frames - oldest.frames + label += ` · ${formatByteRate(byteDelta / elapsedSec)}, ${(frameDelta / elapsedSec).toFixed(1)} fps` + if (frameDelta > 0) label += `, ${formatCount(byteDelta / frameDelta)} B/frame` + } + return label + } +} +function formatCount(value: number): string { return String(Math.round(value)).replace(/\B(?=(\d{3})+(?!\d))/g, ',') } +function formatByteRate(bytesPerSec: number): string { + if (bytesPerSec >= 1e6) return (bytesPerSec / 1e6).toFixed(2) + ' MB/s' + if (bytesPerSec >= 1e3) return (bytesPerSec / 1e3).toFixed(1) + ' kB/s' + return Math.round(bytesPerSec) + ' B/s' +} diff --git a/app/phone-ui/main-page.ios.ts b/app/phone-ui/main-page.ios.ts index a681c919..6e50eac8 100644 --- a/app/phone-ui/main-page.ios.ts +++ b/app/phone-ui/main-page.ios.ts @@ -3,7 +3,9 @@ import { createConfigureDevicesPage } from './config-page.ios' import { ALL_APPS } from '../apps/all-apps' import { IosPreviewController } from '../g2/ios-preview-controller' import { PhoneGestureRecognizer } from './phone-gestures' -import { onAnySettingChanged, previewColorSetting } from '../ui/dashboard-settings' +import { BleBandwidthMeter } from './ble-bandwidth-meter' +import { sampleBleTraffic } from '../native/ble-traffic' +import { onAnySettingChanged, previewColorSetting, showBleBandwidthSetting } from '../ui/dashboard-settings' import { loadDeviceAddresses } from '../g2/device-addresses' import { deviceAddressError } from '../g2/ios-peripheral-identity' @@ -11,7 +13,7 @@ export function createMainPage(): Page { const page = new Page() page.actionBarHidden = true const root = new GridLayout() - root.rows = 'auto,*' + root.rows = 'auto,*,auto' page.content = root const header = new GridLayout() header.columns = '*,auto'; header.padding = '12 20' @@ -127,20 +129,44 @@ export function createMainPage(): Page { view.padding = '16 8'; view.fontSize = 14 GridLayout.setColumn(view, index); footer.addChild(view) } + const bandwidth = new Label() + bandwidth.accessibilityIdentifier = 'ble-bandwidth-indicator' + bandwidth.fontSize = 10; bandwidth.textWrap = true; bandwidth.padding = '2 8 4' + bandwidth.color = new Color('#68756c'); bandwidth.isUserInteractionEnabled = false + bandwidth.visibility = 'collapse' + GridLayout.setRow(bandwidth, 2); root.addChild(bandwidth) + const bandwidthMeter = new BleBandwidthMeter() + let bandwidthTimer: ReturnType | null = null + let foreground = false + function stopBandwidth(): void { + if (bandwidthTimer !== null) clearInterval(bandwidthTimer) + bandwidthTimer = null; bandwidthMeter.reset() + } + function syncBandwidth(): void { + if (!foreground) { stopBandwidth(); return } + const enabled = showBleBandwidthSetting.get() + bandwidth.visibility = enabled ? 'visible' : 'collapse' + if (!enabled) { stopBandwidth(); return } + if (bandwidthTimer !== null) return + const refresh = () => { bandwidth.text = bandwidthMeter.sample(sampleBleTraffic(), Date.now()) } + refresh(); bandwidthTimer = setInterval(refresh, 1000) + } let lastLayout = '' function layout(): void { const size = root.getActualSize() if (size.width <= 0 || size.height <= 0) return - const key = `${size.width}:${size.height}:${selectedTab}` + const metricsHeight = bandwidth.visibility === 'visible' ? bandwidth.getActualSize().height : 0 + const availableHeight = size.height - metricsHeight + const key = `${size.width}:${availableHeight}:${selectedTab}` if (key === lastLayout) return lastLayout = key; padInput.cancel(); mirrorInput.cancel() const landscape = size.width > size.height body.rows = landscape ? '*' : 'auto,*'; body.columns = landscape ? '*,320' : '*' GridLayout.setRow(controls, landscape ? 0 : 1); GridLayout.setColumn(controls, landscape ? 1 : 0) - const width = landscape ? Math.min(size.width - 320, (size.height - 64) * 4 / 3) : size.width + const width = landscape ? Math.min(size.width - 320, (availableHeight - 64) * 4 / 3) : size.width mirror.width = width; mirror.height = width * 3 / 4 pad.width = selectedTab === 'ring' ? 150 : Math.min(360, (landscape ? 320 : size.width) - 32) - pad.height = Math.max(120, Math.min(250, size.height - (landscape ? 180 : width * 3 / 4 + 200))) + pad.height = Math.max(120, Math.min(250, availableHeight - (landscape ? 180 : width * 3 / 4 + 200))) } // iOS emits layoutChanged inside its layout pass. Defer mutations so // NativeScript does not clear our new layout request at the end of that pass. @@ -150,17 +176,18 @@ export function createMainPage(): Page { layoutTimer = setTimeout(() => { layoutTimer = null; layout() }, 0) }) const pause = () => { + foreground = false; stopBandwidth() if (layoutTimer !== null) clearTimeout(layoutTimer) layoutTimer = null padInput.cancel(); mirrorInput.cancel(); controller.pause() } - const resume = () => controller.resume() + const resume = () => { foreground = true; controller.resume(); syncBandwidth() } let offSettings: (() => void) | null = null let firstLoad = true page.on('loaded', () => { Application.on(Application.suspendEvent, pause); Application.on(Application.resumeEvent, resume) - offSettings?.(); offSettings = onAnySettingChanged(() => { sizeButton.text = controller.displayModeLabel }) - selectTab(selectedTab); controller.resume() + offSettings?.(); offSettings = onAnySettingChanged(() => { sizeButton.text = controller.displayModeLabel; syncBandwidth() }) + selectTab(selectedTab); resume() if (firstLoad) { firstLoad = false // Match Android's reconnect-on-launch behavior once addresses are saved. diff --git a/app/phone-ui/main-view-model.ts b/app/phone-ui/main-view-model.ts index 29ad6251..bc1a5de3 100644 --- a/app/phone-ui/main-view-model.ts +++ b/app/phone-ui/main-view-model.ts @@ -1,3 +1,4 @@ +import { BleBandwidthMeter } from "./ble-bandwidth-meter"; import { Application, Dialogs, @@ -1268,7 +1269,7 @@ export class MainViewModel extends Observable { private _bleBandwidthLabel = ""; private bleBandwidthTimer: ReturnType | null = null; // Recent counter samples, one per poll tick, for the windowed rates. - private bleRateHistory: Array<{ atMs: number; bytes: number; frames: number }> = []; + private readonly bleBandwidthMeter = new BleBandwidthMeter(); get bleBandwidthVisibility(): "visible" | "collapse" { return showBleBandwidthSetting.get() ? "visible" : "collapse"; @@ -1297,29 +1298,13 @@ export class MainViewModel extends Observable { this.bleBandwidthTimer = null; } // Don't let a later re-enable compute a rate across the disabled gap. - this.bleRateHistory = []; + this.bleBandwidthMeter.reset(); } private refreshBleBandwidth(): void { let label: string; try { - const sample = sampleBleTraffic(); - const atMs = Date.now(); - this.bleRateHistory.push({ atMs, bytes: sample.bytes, frames: sample.frames }); - while (this.bleRateHistory.length > 0 && this.bleRateHistory[0]!.atMs < atMs - BLE_RATE_WINDOW_MS) { - this.bleRateHistory.shift(); - } - label = `BLE sent: ${formatCount(sample.messages)} messages, ${formatCount(sample.bytes)} bytes`; - const oldest = this.bleRateHistory[0]!; - const elapsedSec = (atMs - oldest.atMs) / 1000; - if (elapsedSec > 0) { - const byteDelta = sample.bytes - oldest.bytes; - const frameDelta = sample.frames - oldest.frames; - label += ` · ${formatByteRate(byteDelta / elapsedSec)}, ${(frameDelta / elapsedSec).toFixed(1)} fps`; - if (frameDelta > 0) { - label += `, ${formatCount(byteDelta / frameDelta)} B/frame`; - } - } + label = this.bleBandwidthMeter.sample(sampleBleTraffic(), Date.now()); } catch (error) { label = `BLE sent: ${this.formatError(error)}`; } @@ -1342,20 +1327,6 @@ export class MainViewModel extends Observable { } } -/** 1234567 -> "1,234,567"; kept exact rather than rounded so growth is visible at a glance. */ -function formatCount(value: number): string { - return String(Math.round(value)).replace(/\B(?=(\d{3})+(?!\d))/g, ","); -} - -/** How far back the BLE bandwidth indicator's rates look. */ -const BLE_RATE_WINDOW_MS = 5000; - -function formatByteRate(bytesPerSec: number): string { - if (bytesPerSec >= 1e6) return (bytesPerSec / 1e6).toFixed(2) + " MB/s"; - if (bytesPerSec >= 1e3) return (bytesPerSec / 1e3).toFixed(1) + " kB/s"; - return Math.round(bytesPerSec) + " B/s"; -} - /** NativeScript swipe direction -> the watch-scheme directional gesture. */ function swipeKind(direction: SwipeDirection): "swipe-up" | "swipe-down" | "swipe-left" | "swipe-right" { switch (direction) { diff --git a/app/ui/dashboard-settings.ts b/app/ui/dashboard-settings.ts index 780663ae..64a81870 100644 --- a/app/ui/dashboard-settings.ts +++ b/app/ui/dashboard-settings.ts @@ -444,7 +444,7 @@ export const showBleBandwidthSetting = new ConfigSettingBoolean({ storageKey: "developer.showBleBandwidth", defaultValue: false, description: - "Show a running total of Bluetooth messages and bytes sent, at the bottom of the phone app's main screen.", + "Show Bluetooth messages and bytes sent, throughput, acknowledged display fps, and bytes per frame at the bottom of the phone screen. Rates use a five-second window; bytes include control traffic and protocol framing.", }); export type RingConnectionMode = "glasses" | "direct"; diff --git a/app/ui/dashboard/settings-menus.ts b/app/ui/dashboard/settings-menus.ts index 8ccb6ef9..7d183a43 100644 --- a/app/ui/dashboard/settings-menus.ts +++ b/app/ui/dashboard/settings-menus.ts @@ -233,8 +233,9 @@ function settingsSections(): SettingsSection[] { }, ]; if (!global.isIOS) return sections; - const deferred = new Set(["Assistant", "Navigate", "Watch", "Developer"]); + const deferred = new Set(["Assistant", "Navigate", "Watch"]); return sections.map(section => { + if (section.label === "Developer") return { ...section, items: [toggleSettingMenuItem(showBleBandwidthSetting)] }; if (section.label === "Voice") return { label: "Voice", items: [{ label: "On-device dictation (Apple)", disabled: true, onSelect: () => {}, description: "Uses the glasses microphone and your iPhone's speech language. No API key needed. Open Voice from the phone or glasses menu, speak, then click to finish and send the text into an app.", diff --git a/tests/ble-bandwidth.test.cjs b/tests/ble-bandwidth.test.cjs new file mode 100644 index 00000000..c9ce838e --- /dev/null +++ b/tests/ble-bandwidth.test.cjs @@ -0,0 +1,24 @@ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { BleBandwidthMeter } = require('../.test-build/app/phone-ui/ble-bandwidth-meter.js'); +test('bandwidth meter matches Android units, includes control bytes and counts acknowledged frames', () => { + const meter = new BleBandwidthMeter(); + assert.equal(meter.sample({ messages: 10, bytes: 1000, frames: 2 }, 0), 'BLE sent: 10 messages, 1,000 bytes'); + assert.equal(meter.sample({ messages: 13, bytes: 4000, frames: 4 }, 1000), + 'BLE sent: 13 messages, 4,000 bytes · 3.0 kB/s, 2.0 fps, 1,500 B/frame'); + meter.reset(); + meter.sample({ messages: 0, bytes: 0, frames: 0 }, 0); + assert.equal(meter.sample({ messages: 1, bytes: 20, frames: 0 }, 1000), 'BLE sent: 1 messages, 20 bytes · 20 B/s, 0.0 fps'); +}); +test('bandwidth rates decay to zero at idle and reset over suspend/toggle/counter resets', () => { + const meter = new BleBandwidthMeter(); + meter.sample({ messages: 0, bytes: 0, frames: 0 }, 0); + for (let second = 1; second <= 6; second++) { + const label = meter.sample({ messages: 10, bytes: 5000, frames: 5 }, second * 1000); + if (second === 6) assert.match(label, /0 B\/s, 0.0 fps$/); + } + meter.reset(); + assert.doesNotMatch(meter.sample({ messages: 20, bytes: 9000, frames: 10 }, 20000), /fps/); + assert.doesNotMatch(meter.sample({ messages: 0, bytes: 0, frames: 0 }, 21000), /fps/); + assert.doesNotMatch(meter.sample({ messages: 1, bytes: 10, frames: 0 }, 30000), /fps/); +}); diff --git a/tests/ble-image-optimizer.test.cjs b/tests/ble-image-optimizer.test.cjs new file mode 100644 index 00000000..b0767fc8 --- /dev/null +++ b/tests/ble-image-optimizer.test.cjs @@ -0,0 +1,67 @@ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { deflate } = require('pako'); +const { buildBoundingBoxPayload: bbox } = require('../.test-build/app/g2/ble-image-optimizer.js'); +const { applyDisplayPayload } = require('./helpers/display-payload.cjs'); +const { rle4 } = require('../.test-build/app/g2/ble-protocol.js'); + +test('mode-3 payload matches the production Android encoder byte for byte', () => { + // Generated with javac from g2protocol/BleImageOptimizer.java, 2026-09-08. + const vectors = [ + [0, 0, 0xab, '03000001013412789c93924e000000e70096'], + [319, 479, 0x12, '039fef01013412789c4b1014020001570084'], + [3, 5, 0xa5, '03010201013412789c4b90120500016c0090'], + ]; + for (const [x, y, value, expected] of vectors) { + const base = new Uint8Array(320 * 480), next = base.slice(); next[y * 320 + x] = value; + const payload = bbox(base, next, 640, 480, 0x1234, deflate); + assert.equal(Buffer.from(payload).toString('hex'), expected); + assert.deepEqual(applyDisplayPayload(base, payload), next); + } +}); + +test('bounding boxes include both nibbles, preserve neighboring pixels and cover all four screen edges', () => { + const base = Uint8Array.from({ length: 320 * 480 }, (_, i) => i & 255); + for (const x of [0, 1, 2, 3, 4, 637, 638, 639]) for (const y of [0, 1, 2, 477, 478, 479]) { + const next = base.slice(); next[y * 320 + (x >> 1)] ^= x % 2 ? 15 : 240; + const payload = bbox(base, next, 640, 480, 1, deflate); + assert.deepEqual([...payload.slice(1, 5)], [Math.floor(x / 4), Math.floor(y / 2), 1, 1]); + assert.deepEqual(applyDisplayPayload(base, payload), next); + } +}); + +test('unchanged, incompatible and full-screen boxes fall back without compressing a region', () => { + const base = new Uint8Array(320 * 480), next = base.slice(); next[0] = next[next.length - 1] = 255; + const compress = () => assert.fail('A fallback must not compress a bounding box'); + assert.equal(bbox(base, base, 640, 480, 1, compress), null); + assert.equal(bbox(base, next, 640, 480, 1, compress), null); + assert.equal(bbox(null, next, 640, 480, 1, compress), null); + assert.equal(bbox(base.subarray(1), next, 640, 480, 1, compress), null); + assert.equal(bbox(base, next.subarray(1), 640, 480, 1, compress), null); + for (const [w, h] of [[0, 480], [639, 480], [640, 479], [1024, 480], [640, 512]]) + assert.equal(bbox(base, next, w, h, 1, compress), null); +}); + +test('seeded sparse edits reconstruct exactly across successive bounding-box updates', () => { + let seed = 42; + const random = limit => { seed = (Math.imul(seed, 1664525) + 1013904223) >>> 0; return seed % limit; }; + let base = Uint8Array.from({ length: 320 * 480 }, () => random(256)); + for (let fid = 1; fid <= 60; fid++) { + const next = base.slice(), bx = random(280), by = random(440); + for (let n = 0; n < 20; n++) next[(by + random(40)) * 320 + bx + random(40)] ^= 0xff; + const payload = bbox(base, next, 640, 480, fid, deflate); + assert.ok(payload); assert.equal(payload[5] | (payload[6] << 8), fid); + assert.deepEqual(applyDisplayPayload(base, payload), next); + base = next; + } +}); + +test('a small edit compresses only its region and reduces bytes on a busy screen', () => { + const base = Uint8Array.from({ length: 320 * 480 }, (_, i) => i & 255), next = base.slice(); + next[100 * 320 + 100] ^= 255; + let compressedInputBytes = 0; + const payload = bbox(base, next, 640, 480, 1, bytes => { compressedInputBytes += bytes.length; return deflate(bytes); }); + assert.ok(compressedInputBytes <= 8); // A 4x2 rectangle, at most one RLE byte per pixel. + assert.ok(payload.length < (1 + deflate(rle4(next)).length) / 10); + assert.deepEqual(applyDisplayPayload(base, payload), next); +}); diff --git a/tests/helpers/display-payload.cjs b/tests/helpers/display-payload.cjs new file mode 100644 index 00000000..9159763f --- /dev/null +++ b/tests/helpers/display-payload.cjs @@ -0,0 +1,25 @@ +const assert = require('node:assert/strict'); +const { inflateSync } = require('node:zlib'); + +// Independent firmware-format decoder for reconstruction tests (not app code). +function applyDisplayPayload(base, payload, width = 640, height = 480) { + const mode = payload[0]; assert.ok(mode === 3 || mode === 6); + const [left, top, w, h] = mode === 3 + ? [payload[1] * 4, payload[2] * 2, payload[3] * 4, payload[4] * 2] : [0, 0, width, height]; + assert.ok(w > 0 && h > 0 && left + w <= width && top + h <= height); + const tokens = inflateSync(payload.subarray(mode === 3 ? 7 : 1)); + const pixels = []; + for (let i = 0; i < tokens.length;) { + const token = tokens[i++], color = token & 15; + let count = token >>> 4; + if (!count) { count = tokens[i++]; if (!count) { count = tokens[i] | (tokens[i + 1] << 8); i += 2; } } + assert.ok(count > 0 && pixels.length + count <= w * h); + for (let n = 0; n < count; n++) pixels.push(color); + } + assert.equal(pixels.length, w * h); + const out = base.slice(); + for (let y = 0; y < h; y++) for (let x = 0; x < w; x += 2) + out[(top + y) * (width / 2) + (left + x) / 2] = (pixels[y * w + x] << 4) | pixels[y * w + x + 1]; + return out; +} +module.exports = { applyDisplayPayload }; diff --git a/tests/ios-app-host.test.cjs b/tests/ios-app-host.test.cjs index 2621b745..9f20046f 100644 --- a/tests/ios-app-host.test.cjs +++ b/tests/ios-app-host.test.cjs @@ -135,3 +135,49 @@ test('background glasses input still composites frames; phone resume preserves t controller.resume(); flush(); assert.equal(starts, 1); assert.equal(controller.connectionState.phase, 'disconnected'); }); + +test('iOS bandwidth footer toggles live, polls only in foreground and resets its rate window on resume', () => { + const views = [], intervals = new Map(), appEvents = new Map(), settingListeners = new Set(); + let enabled = false, atMs = 0, totals = { messages: 0, bytes: 0, frames: 0 }, nextId = 0; + class View { + events = new Map(); children = []; + constructor() { views.push(this); } + on(event, fn) { this.events.set(event, fn); } + addChild(view) { this.children.push(view); } + getActualSize() { return { width: 0, height: 0 }; } + static setRow() {} static setColumn() {} + } + const core = { Application: { suspendEvent: 'suspend', resumeEvent: 'resume', + on: (key, fn) => appEvents.set(key, fn), off: key => appEvents.delete(key) }, + Button: View, Color: class {}, Dialogs: {}, GridLayout: View, Image: View, Label: View, Page: View, StackLayout: View }; + const modules = { + '@nativescript/core': core, + '../apps/all-apps': { ALL_APPS: [] }, + '../g2/ios-preview-controller': { IosPreviewController: class { resume() {} pause() {} } }, + './phone-gestures': { PhoneGestureRecognizer: class { cancel() {} } }, + './ble-bandwidth-meter': require('../.test-build/app/phone-ui/ble-bandwidth-meter.js'), + '../native/ble-traffic': { sampleBleTraffic: () => totals }, + '../ui/dashboard-settings': { showBleBandwidthSetting: { get: () => enabled }, + onAnySettingChanged: fn => { settingListeners.add(fn); return () => settingListeners.delete(fn); } }, + '../g2/device-addresses': { loadDeviceAddresses: () => ({}) }, + '../g2/ios-peripheral-identity': { deviceAddressError: () => 'no test devices' }, + }; + const { createMainPage } = load('app/phone-ui/main-page.ios.ts', { + require: id => modules[id] ?? {}, Date: { now: () => atMs }, + setInterval: fn => { const id = ++nextId; intervals.set(id, fn); return id; }, clearInterval: id => intervals.delete(id), + setTimeout: () => 1, clearTimeout() {}, + }); + const page = createMainPage(), footer = views.find(v => v.accessibilityIdentifier === 'ble-bandwidth-indicator'); + page.events.get('loaded')(); assert.equal(intervals.size, 0); assert.equal(footer.visibility, 'collapse'); + enabled = true; for (const fn of settingListeners) fn(); + assert.equal(intervals.size, 1); assert.equal(footer.visibility, 'visible'); + totals = { messages: 4, bytes: 2000, frames: 2 }; atMs = 1000; for (const fn of intervals.values()) fn(); + assert.match(footer.text, /2.0 fps, 1,000 B\/frame/); + appEvents.get('suspend')(); assert.equal(intervals.size, 0); + const previousText = footer.text; + totals = { messages: 40, bytes: 20000, frames: 20 }; atMs = 20000; + for (const fn of settingListeners) fn(); assert.equal(footer.text, previousText); assert.equal(intervals.size, 0); + appEvents.get('resume')(); assert.equal(intervals.size, 1); assert.doesNotMatch(footer.text, /fps/); + 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); +}); diff --git a/tests/ios-ble.test.cjs b/tests/ios-ble.test.cjs index 19eb12a1..d4633fab 100644 --- a/tests/ios-ble.test.cjs +++ b/tests/ios-ble.test.cjs @@ -256,3 +256,241 @@ test('release while microphone enable awaits ACK sends disable last and rejects const mic = h.transport.sent.filter(s => s.message.command === 15); assert.equal(p.readInteger(p.readBytes(mic.at(-1).message.payload, 18), 1), 0); }); + +test('iOS traffic counts framed writes and logical messages, and advances fps only after the complete image ACK', async t => { + const { iosBleTraffic } = require('../.test-build/app/g2/ble-traffic-counters.js'); + const h = harness(t); await h.session.start(addresses); + const before = iosBleTraffic.sample(); + let writtenBytes = 0; + const write = h.transport.write.bind(h.transport); + h.transport.write = async (...args) => { await write(...args); writtenBytes += args[2].length; }; + // Force multiple EvenHub messages so first-message ACK is not mistaken for a frame. + h.session.deflate = () => new Uint8Array(8000).fill(1); + h.transport.hold = true; + h.session.setFrame(new Uint8Array(640 * 480).fill(255)); + await until(() => iosBleTraffic.sample().messages > before.messages); + assert.equal(iosBleTraffic.sample().frames, before.frames); + assert.equal(iosBleTraffic.sample().bytes - before.bytes, writtenBytes); + h.transport.hold = false; + for (const held of h.transport.held) h.transport.ack(held.id, held.message); + await until(() => h.session.state.frames === 1); + const after = iosBleTraffic.sample(); + assert.equal(after.messages - before.messages, 3); + assert.equal(after.frames - before.frames, 1); + assert.equal(after.bytes - before.bytes, writtenBytes); + assert.ok(writtenBytes > 8001); // Includes protobuf, fragmentation headers and CRCs. + h.session.setFrame(new Uint8Array(640 * 480).fill(255)); + await h.session.pump(); + assert.deepEqual(iosBleTraffic.sample(), after); // Deduplicated image is not an ACKed frame. + await h.session.stop(); + assert.equal(iosBleTraffic.sample().frames, after.frames); // No reset on disconnect. +}); + +const imageMessages = transport => transport.sent.filter(s => s.message.sid === p.SID.hub && s.message.command === 3); +const imageBody = sent => p.readBytes(sent.message.payload, 5); +const ack = (transport, sent) => transport.ack(sent.id, sent.message); +const tick = () => new Promise(resolve => setImmediate(resolve)); + +test('display window sends three complete messages before any ACK and refills on an out-of-order ACK', async t => { + const h = harness(t); await h.session.start(addresses); + // Five protocol messages, each split into many negotiated-MTU BLE writes. + const compressed = Uint8Array.from({ length: 16000 }, (_, i) => i & 255); + h.session.deflate = () => compressed; h.transport.hold = true; + h.session.setFrame(new Uint8Array(640 * 480).fill(255)); + await until(() => imageMessages(h.transport).length === 3); + await tick(); assert.equal(imageMessages(h.transport).length, 3); + assert.equal(h.session.state.frames, 0); + const first = imageMessages(h.transport); + ack(h.transport, first[1]); // Relayed ACKs need not arrive in submission order. + await until(() => imageMessages(h.transport).length === 4); + ack(h.transport, first[1]); // Duplicate ACK must not open another slot. + await tick(); assert.equal(imageMessages(h.transport).length, 4); + ack(h.transport, first[2]); + await until(() => imageMessages(h.transport).length === 5); + const sent = imageMessages(h.transport); + assert.deepEqual(sent.map(s => p.readInteger(imageBody(s), 6)), [0, 1, 2, 3, 4]); + assert.deepEqual(p.concat(...sent.map(s => p.readBytes(imageBody(s), 8))), p.concat(new Uint8Array([6]), compressed)); + ack(h.transport, sent[4]); ack(h.transport, sent[3]); + await tick(); assert.equal(h.session.state.frames, 0); // First fragment still unacknowledged. + ack(h.transport, sent[0]); + await until(() => h.session.state.frames === 1); + assert.equal(h.session.displayInFlight, 0); assert.equal(h.session.displayFrames.length, 0); +}); + +test('display pipelines across frames, deduplicates against enqueued images and coalesces to the newest waiting frame', async t => { + const h = harness(t); await h.session.start(addresses); h.transport.hold = true; + const submit = async value => { h.session.setFrame(new Uint8Array(640 * 480).fill(value)); await h.session.pump(); await tick(); }; + await submit(0); await until(() => imageMessages(h.transport).length === 1); + await submit(0); assert.equal(imageMessages(h.transport).length, 1); // Duplicate still in flight. + await submit(255); await submit(0); // A -> B -> A must transmit all three. + await until(() => imageMessages(h.transport).length === 3); + const sent = imageMessages(h.transport); + assert.deepEqual(p.readBytes(imageBody(sent[0]), 8), p.readBytes(imageBody(sent[2]), 8)); + await submit(80); await submit(160); // Only the newest waiting frame survives. + assert.equal(imageMessages(h.transport).length, 3); + ack(h.transport, sent[2]); ack(h.transport, sent[1]); await tick(); + assert.equal(h.session.state.frames, 0); + assert.equal(h.session.displayFrames.length, 3); // Bounded behind the missing oldest ACK. + assert.equal(imageMessages(h.transport).length, 3); + ack(h.transport, sent[0]); + await until(() => imageMessages(h.transport).length === 4); + assert.equal(h.session.state.frames, 3); + const newest = imageMessages(h.transport)[3]; + assert.deepEqual(p.readBytes(imageBody(newest), 8), p.concat(new Uint8Array([6]), deflate(p.rle4(p.packGray4(new Uint8Array(640 * 480).fill(160), 640, 480))))); + ack(h.transport, newest); await until(() => h.session.state.frames === 4); + await submit(160); assert.equal(imageMessages(h.transport).length, 4); +}); + +test('ACK timeout starts after transport writes drain; a lost display ACK flushes the whole pipeline', async t => { + const h = harness(t); await h.session.start(addresses); + const request = h.session.request.bind(h.session); + h.session.request = (role, sid, build, label, ...rest) => request(role, sid, build, label, ...(label === 'Display frame' ? [40] : rest)); + const write = h.transport.write.bind(h.transport); + let release; + const blocked = new Promise(resolve => { release = resolve; }); + h.transport.write = async (...args) => { if (args[0] === 'L') await blocked; await write(...args); }; + h.transport.hold = true; h.session.deflate = () => new Uint8Array(16000); + h.session.setFrame(new Uint8Array(640 * 480)); await h.session.pump(); + await new Promise(resolve => setTimeout(resolve, 65)); + assert.equal(h.session.state.phase, 'connected'); assert.equal(imageMessages(h.transport).length, 0); + release(); await until(() => imageMessages(h.transport).length === 3); + const stale = imageMessages(h.transport); + await until(() => h.session.state.phase === 'retrying'); + assert.match(h.session.state.status, /Display frame was not acknowledged/); + assert.equal(h.session.displayInFlight, 0); assert.equal(h.session.displayFrames.length, 0); + assert.equal(h.session.lastEnqueued, null); assert.equal(h.session.pending.size, 0); + for (const sent of stale) ack(h.transport, sent); + await tick(); assert.equal(h.session.state.frames, 0); assert.equal(imageMessages(h.transport).length, 3); + // A new session must resend even the identical image; old ACKs cannot count it. + await h.session.stop(); h.transport.hold = false; await h.session.start(addresses); + h.session.deflate = deflate; h.transport.hold = true; + h.session.setFrame(new Uint8Array(640 * 480)); + await until(() => imageMessages(h.transport).length === 4); + for (const sent of stale) ack(h.transport, sent); + await tick(); assert.equal(h.session.state.frames, 0); + ack(h.transport, imageMessages(h.transport)[3]); await until(() => h.session.state.frames === 1); +}); + +test('failed transport write prevents queued display messages from being written', async t => { + const h = harness(t); await h.session.start(addresses); + let attempts = 0; + const write = h.transport.write.bind(h.transport); + h.transport.write = async (...args) => { + if (args[0] === 'L') { attempts++; throw new Error('test write failed'); } + return write(...args); + }; + h.session.deflate = () => new Uint8Array(16000); + h.session.setFrame(new Uint8Array(640 * 480)); + await until(() => h.session.state.phase === 'retrying'); + assert.equal(attempts, 1); assert.equal(h.session.pending.size, 0); + assert.equal(h.session.displayInFlight, 0); assert.equal(h.session.state.frames, 0); +}); + +test('disconnect cancels the display window and sends cleanup after the queued images stop', async t => { + const h = harness(t); await h.session.start(addresses); + h.transport.hold = true; h.session.deflate = () => new Uint8Array(16000); + h.session.setFrame(new Uint8Array(640 * 480)); + await until(() => imageMessages(h.transport).length === 3); + const stale = imageMessages(h.transport); + h.transport.hold = false; await h.session.stop(); + for (const sent of stale) ack(h.transport, sent); + await tick(); + assert.equal(h.session.state.phase, 'disconnected'); assert.equal(h.session.state.frames, 0); + assert.equal(h.session.displayInFlight, 0); assert.equal(h.session.displayFrames.length, 0); + const images = imageMessages(h.transport); + assert.equal(images.length, 4); assert.deepEqual(p.readBytes(imageBody(images[3]), 8), new Uint8Array([11])); +}); + +test('a full display window leaves glasses input, microphone control and audio responsive', async t => { + const h = harness(t); await h.session.start(addresses); + h.transport.hold = true; h.session.deflate = () => new Uint8Array(16000); + h.session.setFrame(new Uint8Array(640 * 480)); + await until(() => imageMessages(h.transport).length === 3); + const input = p.bytes(13, p.bytes(3, p.concat(p.integer(1, 9), p.integer(2, 3)))); + h.transport.emit({ kind: 'notification', identifier: 'R', characteristic: p.G2_NOTIFY, + data: hex(p.concat(...p.frameMessage(input, p.SID.hub, 1, 22))) }); + assert.equal(h.input.length, 1); assert.equal(h.input[0].eventSource, 3); + const audio = [], enabling = h.session.setMicrophone(true, packet => audio.push(hex(packet))); + await until(() => h.transport.sent.some(s => s.message.command === 15)); + ack(h.transport, h.transport.sent.find(s => s.message.command === 15)); await enabling; + h.transport.emit({ kind: 'notification', identifier: 'L', characteristic: p.G2_RENDER_NOTIFY, data: '010203' }); + assert.deepEqual(audio, ['010203']); + assert.equal(imageMessages(h.transport).length, 3); assert.equal(h.session.state.frames, 0); + assert.equal(h.session.displayInFlight, 3); +}); + +test('pipelined bounding boxes reconstruct moving and erased content against the last queued frame', async t => { + const { applyDisplayPayload } = require('./helpers/display-payload.cjs'); + const h = harness(t); await h.session.start(addresses); h.transport.hold = true; + const base = new Uint8Array(640 * 480), a = base.slice(), b = base.slice(); + a[11 * 640 + 13] = 255; b[11 * 640 + 101] = 160; + const frames = [base, a, b]; + for (let i = 0; i < frames.length; i++) { + h.session.setFrame(frames[i]); await h.session.pump(); + await until(() => imageMessages(h.transport).length === i + 1); + } + const messages = imageMessages(h.transport), payloads = messages.map(m => p.readBytes(imageBody(m), 8)); + assert.deepEqual(payloads.map(b => b[0]), [6, 3, 3]); + assert.deepEqual(payloads.slice(1).map(b => b[5] | (b[6] << 8)), [1, 2]); + assert.equal(h.session.state.frames, 0); // All three updates precede any ACK. + let shadow = new Uint8Array(320 * 480); + for (let i = 0; i < payloads.length; i++) { + shadow = applyDisplayPayload(shadow, payloads[i]); + assert.deepEqual(shadow, p.packGray4(frames[i], 640, 480)); + } + // A late ACK for the old full frame must not replace the delta comparison base. + ack(h.transport, messages[0]); await until(() => h.session.state.frames === 1); + h.session.setFrame(base); await h.session.pump(); + await until(() => imageMessages(h.transport).length === 4); + const clear = p.readBytes(imageBody(imageMessages(h.transport)[3]), 8); + assert.equal(clear[0], 3); assert.equal(clear[1], 25); // Only B's dot needs clearing. + assert.deepEqual(applyDisplayPayload(shadow, clear), p.packGray4(base, 640, 480)); + for (const message of imageMessages(h.transport).slice(1)) ack(h.transport, message); + await until(() => h.session.state.frames === 4); +}); + +test('delta ids skip reserved values and advance only on emitted deltas; reconnect reseeds with a full frame', async t => { + const h = harness(t); await h.session.start(addresses); + const submit = async gray => { + const before = h.session.state.frames; h.session.setFrame(gray); + await until(() => h.session.state.frames === before + 1); + return p.readBytes(imageBody(imageMessages(h.transport).at(-1)), 8); + }; + const base = new Uint8Array(640 * 480), next = base.slice(); next[1234] = 255; + assert.equal((await submit(base))[0], 6); + h.session.nextImageFrameId = 0xfffe; + const delta = await submit(next); assert.equal(delta[5] | (delta[6] << 8), 0xfffe); + h.session.setFrame(next); await h.session.pump(); await tick(); + assert.equal(h.session.nextImageFrameId, 1); + const full = await submit(new Uint8Array(640 * 480).fill(255)); assert.equal(full[0], 6); + assert.equal(h.session.nextImageFrameId, 1); + const clear = await submit(next); assert.equal(clear[0], 6); // Whole-screen bounding box. + const wrapped = await submit(base); assert.equal(wrapped[5] | (wrapped[6] << 8), 1); + await h.session.stop(); await h.session.start(addresses); + assert.equal((await submit(base))[0], 6); // Even the same pixels need a trusted full base. +}); + +test('a lost delta ACK invalidates the queued base and late delta ACKs cannot seed a new session', async t => { + const h = harness(t); await h.session.start(addresses); + const base = new Uint8Array(640 * 480); h.session.setFrame(base); + await until(() => h.session.state.frames === 1); + const request = h.session.request.bind(h.session); + h.session.request = (role, sid, build, label, ...rest) => request(role, sid, build, label, ...(label === 'Display frame' ? [50] : rest)); + h.transport.hold = true; + const a = base.slice(), b = base.slice(); a[1234] = 255; b[4321] = 255; + h.session.setFrame(a); await h.session.pump(); + h.session.setFrame(b); await h.session.pump(); + await until(() => imageMessages(h.transport).length === 3); + const stale = imageMessages(h.transport).slice(1); + assert.deepEqual(stale.map(m => p.readBytes(imageBody(m), 8)[0]), [3, 3]); + ack(h.transport, stale[1]); // Even a later successful delta does not rescue a hole. + await until(() => h.session.state.phase === 'retrying'); + assert.equal(h.session.lastEnqueued, null); assert.equal(h.session.state.frames, 1); + await h.session.stop(); h.transport.hold = false; await h.session.start(addresses); + h.transport.hold = true; h.session.setFrame(b); await h.session.pump(); + await until(() => imageMessages(h.transport).length === 4); + const reseed = imageMessages(h.transport)[3]; assert.equal(p.readBytes(imageBody(reseed), 8)[0], 6); + for (const message of stale) ack(h.transport, message); + await tick(); assert.equal(h.session.state.frames, 1); + ack(h.transport, reseed); await until(() => h.session.state.frames === 2); +}); diff --git a/tests/tsconfig.json b/tests/tsconfig.json index 4e947d45..068ece2a 100644 --- a/tests/tsconfig.json +++ b/tests/tsconfig.json @@ -12,6 +12,7 @@ }, "include": [ "../app/g2/ble-protocol.ts", + "../app/phone-ui/ble-bandwidth-meter.ts", "../app/apps/terminal/hub-header.ts", "../app/g2/ios-peripheral-identity.ts", "../app/g2/glasses-session.ts",