From a7916a54790f2408cc433225314ebf3e533cf4fe Mon Sep 17 00:00:00 2001 From: JMO Date: Tue, 22 Sep 2026 22:09:11 -0700 Subject: [PATCH 1/4] Make the firmware upgrade reachable from older custom firmware Glasses running an older Faceclaw firmware revision cannot be upgraded at all. The flash asks for confirmation on the lens first, and that firmware never shows the prompt, so the one path off it is closed. Measured on revision 13 (base 2.2.9.22). showPrompt writes the EvenHub create-prompt page to the right arm and waits for an ack. The lens accepts the write at the GATT layer and then answers nothing and displays nothing: four attempts, four onWriteCharacteristic status=0 length=165, no reply. buildCreatePromptPage documents its geometry as stock-firmware-safe "so this works before flashing", and that does not hold there. Three faults, each only visible once the previous one is fixed. An unacked prompt page was fatal. Flashing is the only way off that firmware, so failing here leaves the glasses permanently unupgradable. An unacked page now falls back to the phone-side confirmation that the low-battery retry already uses, on a screen that says what is being given up: the on-lens step is what proves the glasses are the wearer's. connectArm made a single attempt. The lens is routinely unavailable for a moment just after a previous link to it closed, which is exactly the state a retry is in, so the fallback failed instantly with "could not connect to the right arm". FaceclawFirmwareFlasher.connectLensResilient already retries within a window for this reason; connectArmResilient mirrors it and reports each attempt. That retry then tripped the lost-connection latch. Disconnecting between attempts fires onConnectionStateChange, which set rightLost AND finished and counted down the selection latch, so a successful second attempt still aborted with "Lost connection to the glasses". The callback now ignores drops while the arms are still being established. Logging, because a failed flash used to leave almost nothing to read. emitLog reached logcat, but emitState, emitProgress and emitComplete on the flasher, and emitState and emitResult on the prompt communicator, went only to the in-app listener, so the line carrying the reason existed only on the phone screen. Seven `catch (Exception ignored)` blocks across the two classes now log with the Throwable, matching the call sites elsewhere that already do. tests/flash-prompt-fallback.test.cjs covers the decision at its seam through the existing load-typescript loader. The first test fails against the current view model and passes with this change; the second is a regression guard and passes either way, so an unrelated failure cannot quietly skip the on-lens confirmation. Verified on hardware: both lenses flashed through this path after it had been a dead end. --- .../faceclaw/app/FaceclawFirmwareFlasher.java | 40 +++++++-- .../app/FaceclawFlashPromptCommunicator.java | 85 +++++++++++++++++-- app/phone-ui/onboarding-flash-view-model.ts | 31 ++++++- tests/flash-prompt-fallback.test.cjs | 62 ++++++++++++++ 4 files changed, 202 insertions(+), 16 deletions(-) create mode 100644 tests/flash-prompt-fallback.test.cjs diff --git a/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawFirmwareFlasher.java b/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawFirmwareFlasher.java index 3a941ac6..91f5bcaa 100644 --- a/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawFirmwareFlasher.java +++ b/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawFirmwareFlasher.java @@ -133,7 +133,8 @@ public class FaceclawFirmwareFlasher implements FaceclawBleListener { cancel(); try { bleManager.close(); - } catch (Exception ignored) { + } catch (Exception e) { + Log.w(TAG, "close: ble manager close failed", e); } } @@ -207,7 +208,8 @@ public class FaceclawFirmwareFlasher implements FaceclawBleListener { emitLog(lens + " lens: all components verified"); try { bleManager.disconnect(address); - } catch (Exception ignored) { + } catch (Exception e) { + Log.w(TAG, "disconnect after " + lens + " lens failed: address=" + address, e); } } @@ -349,7 +351,9 @@ public class FaceclawFirmwareFlasher implements FaceclawBleListener { emitLog(lens + " connect attempt " + attempt + " failed (" + lastError + "); retrying..."); try { bleManager.disconnect(address); - } catch (Exception ignored) { + } catch (Exception e) { + // Routine between retries: the link is usually already gone. + Log.d(TAG, "disconnect before retry failed: address=" + address, e); } sleepInterruptibly(RETRY_DELAY_MS); } @@ -545,6 +549,8 @@ public class FaceclawFirmwareFlasher implements FaceclawBleListener { } BleProtocol.ParsedFrame frame = BleProtocol.parseFrame(data); if (!frame.ok || frame.pb.length < 2) { + // Dropped acks surface upstream as an unexplained timeout, so say so here. + Log.d(TAG, "ignoring ack frame: ok=" + frame.ok + " len=" + frame.pb.length); return; } dataAcks.add(Arrays.copyOf(frame.pb, Math.min(frame.pb.length, 2))); @@ -552,9 +558,7 @@ public class FaceclawFirmwareFlasher implements FaceclawBleListener { @Override public void onConnectionStateChange(String address, boolean connected) { - if (!connected) { - Log.i(TAG, "disconnected: " + address); - } + Log.i(TAG, (connected ? "connected: " : "disconnected: ") + address); } // ---- helpers ------------------------------------------------------------- @@ -562,7 +566,8 @@ public class FaceclawFirmwareFlasher implements FaceclawBleListener { private void teardown() { try { bleManager.close(); - } catch (Exception ignored) { + } catch (Exception e) { + Log.w(TAG, "teardown: ble manager close failed", e); } } @@ -665,6 +670,13 @@ public class FaceclawFirmwareFlasher implements FaceclawBleListener { private void emitProgress(String lens, int componentIndex, int componentCount, int blockIndex, int blockCount, long bytesSent, long bytesTotal) { + // Per-block, so DEBUG and behind isLoggable: thousands of these per flash, and + // without the guard the message is built every time even when nobody reads it. + // The component boundaries are the interesting ones and emitLog reports those. + if (Log.isLoggable(TAG, Log.DEBUG)) { + Log.d(TAG, "progress " + lens + " component " + (componentIndex + 1) + "/" + componentCount + + " block " + (blockIndex + 1) + "/" + blockCount + " " + bytesSent + "/" + bytesTotal + " bytes"); + } mainHandler.post(() -> { FaceclawFirmwareFlasherListener current = listener; if (current != null) { @@ -675,6 +687,13 @@ public class FaceclawFirmwareFlasher implements FaceclawBleListener { private void emitState(String state, String detail) { final String safeDetail = detail == null ? "" : detail; + // These went only to the in-app listener, so a failed flash left its reason on + // the phone screen and nowhere a log could be read from afterwards. + if ("error".equals(state)) { + Log.e(TAG, "state=" + state + (safeDetail.isEmpty() ? "" : " -- " + safeDetail)); + } else { + Log.i(TAG, "state=" + state + (safeDetail.isEmpty() ? "" : " -- " + safeDetail)); + } mainHandler.post(() -> { FaceclawFirmwareFlasherListener current = listener; if (current != null) { @@ -685,6 +704,13 @@ public class FaceclawFirmwareFlasher implements FaceclawBleListener { private void emitComplete(boolean success, String detail) { final String safeDetail = detail == null ? "" : detail; + // The single most important line of a flash, and it used to be invisible to + // logcat: on failure this carries the reason. + if (success) { + Log.i(TAG, "complete success -- " + safeDetail); + } else { + Log.e(TAG, "complete FAILED -- " + safeDetail); + } mainHandler.post(() -> { FaceclawFirmwareFlasherListener current = listener; if (current != null) { diff --git a/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawFlashPromptCommunicator.java b/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawFlashPromptCommunicator.java index ef342706..833a34b2 100644 --- a/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawFlashPromptCommunicator.java +++ b/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawFlashPromptCommunicator.java @@ -4,6 +4,7 @@ import android.bluetooth.BluetoothGatt; import android.content.Context; import android.os.Handler; import android.os.Looper; +import android.os.SystemClock; import android.util.Log; import java.util.List; @@ -54,6 +55,15 @@ public class FaceclawFlashPromptCommunicator implements FaceclawBleListener { private static final int SELECTION_TIMEOUT_MS = 120_000; private static final int CREATE_ACK_TIMEOUT_MS = 3_000; private static final int BATTERY_ACK_TIMEOUT_MS = 3_000; + /** + * A single connect attempt is not enough. The lens is routinely unavailable for a + * moment right after a previous link to it closed, which is exactly the situation + * this class is in whenever the user retries. FaceclawFirmwareFlasher already + * retries within a window for the same reason; this matches it rather than + * failing on the first refusal. + */ + private static final int ARM_CONNECT_WINDOW_MS = 30_000; + private static final int ARM_RETRY_DELAY_MS = 2_500; private final Context context; private final String rightAddress; @@ -75,6 +85,14 @@ public class FaceclawFlashPromptCommunicator implements FaceclawBleListener { private volatile boolean rightConnected = false; private volatile boolean leftConnected = false; private volatile boolean rightLost = false; + /** + * True while the arms are still being brought up. connectArmResilient disconnects + * between retries, which fires onConnectionStateChange, and that callback latches + * rightLost AND finished -- so without this guard a deliberate retry-disconnect + * ends the whole run, even when the very next attempt connects. Only a drop AFTER + * both arms are up is a lost connection. + */ + private volatile boolean establishing = true; private volatile Boolean approved = null; private volatile ScheduledExecutorService heartbeatExecutor; @@ -121,7 +139,8 @@ public class FaceclawFlashPromptCommunicator implements FaceclawBleListener { stopHeartbeat(); try { bleManager.close(); - } catch (Exception ignored) { + } catch (Exception e) { + Log.w(TAG, "close: ble manager close failed", e); } } @@ -148,6 +167,8 @@ public class FaceclawFlashPromptCommunicator implements FaceclawBleListener { } } + // Both arms are up: from here a disconnect really is a lost connection. + establishing = false; emitState("connected", ""); // Auth both arms now (pairing prompts, if any, happen here) before // anything else, so both bonds exist by the time flashing starts. @@ -185,7 +206,10 @@ public class FaceclawFlashPromptCommunicator implements FaceclawBleListener { } try { sendShutdown(); - } catch (Exception ignored) { + } catch (Exception e) { + // The lens is about to be torn down either way, but a shutdown that + // never lands is why it can come back up in an odd state. + Log.w(TAG, "sendShutdown failed", e); } if (!Boolean.TRUE.equals(approved)) { emitResult(false); @@ -224,9 +248,7 @@ public class FaceclawFlashPromptCommunicator implements FaceclawBleListener { } private void connectArm(String address, String arm) { - if (!bleManager.connect(address, ConnectionOptions.CONNECT_TIMEOUT_MS)) { - throw new IllegalStateException("could not connect to the " + arm + " arm (" + address + ")"); - } + connectArmResilient(address, arm); bleManager.requestConnectionPriority(address, BluetoothGatt.CONNECTION_PRIORITY_HIGH); bleManager.requestMtu(address, ConnectionOptions.DESIRED_MTU, ConnectionOptions.CONNECT_TIMEOUT_MS); if (!bleManager.discoverServices(address, ConnectionOptions.SERVICES_TIMEOUT_MS)) { @@ -238,6 +260,51 @@ public class FaceclawFlashPromptCommunicator implements FaceclawBleListener { emitLog("connected " + arm + " arm"); } + private void sleepInterruptibly(int ms) { + try { + Thread.sleep(ms); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } + + /** + * Keep trying to open the link until the window closes, reporting each attempt. + * Mirrors FaceclawFirmwareFlasher.connectLensResilient. + */ + private void connectArmResilient(String address, String arm) { + long deadline = SystemClock.elapsedRealtime() + ARM_CONNECT_WINDOW_MS; + String lastError = "unknown"; + int attempt = 0; + while (SystemClock.elapsedRealtime() < deadline && !cancelled) { + attempt++; + try { + if (bleManager.connect(address, ConnectionOptions.CONNECT_TIMEOUT_MS)) { + if (attempt > 1) { + emitLog("connected " + arm + " arm (attempt " + attempt + ")"); + } + return; + } + lastError = "connect refused"; + } catch (Exception e) { + lastError = e.getMessage() == null ? e.toString() : e.getMessage(); + } + emitLog(arm + " arm connect attempt " + attempt + " failed (" + lastError + "); retrying..."); + try { + bleManager.disconnect(address); + } catch (Exception e) { + // Expected between retries: the link is usually already gone. + Log.d(TAG, "disconnect before retry failed: address=" + address, e); + } + sleepInterruptibly(ARM_RETRY_DELAY_MS); + } + if (cancelled) { + throw new IllegalStateException("Cancelled."); + } + throw new IllegalStateException( + "could not connect to the " + arm + " arm after " + attempt + " attempts: " + lastError); + } + /** * Security-auth exchange on sid=0x80: firmware 2.2.9 will not run a * session (and closes the link after ~30 s) without it, and on an @@ -412,7 +479,8 @@ public class FaceclawFlashPromptCommunicator implements FaceclawBleListener { stopHeartbeat(); try { bleManager.close(); - } catch (Exception ignored) { + } catch (Exception e) { + Log.w(TAG, "teardown: ble manager close failed", e); } rightConnected = false; leftConnected = false; @@ -485,7 +553,7 @@ public class FaceclawFlashPromptCommunicator implements FaceclawBleListener { if (address.equalsIgnoreCase(rightAddress)) { rightConnected = false; synchronized (lock) { - if (!finished && !cancelled) { + if (!establishing && !finished && !cancelled) { rightLost = true; finished = true; selectionLatch.countDown(); @@ -518,6 +586,8 @@ public class FaceclawFlashPromptCommunicator implements FaceclawBleListener { private void emitState(String state, String detail) { final String safeDetail = detail == null ? "" : detail; + // Listener-only until now, so a prompt that never appeared left no trace in a log. + Log.i(TAG, "state=" + state + (safeDetail.isEmpty() ? "" : " -- " + safeDetail)); mainHandler.post(() -> { FaceclawFlashPromptListener current = listener; if (current != null) { @@ -536,6 +606,7 @@ public class FaceclawFlashPromptCommunicator implements FaceclawBleListener { } private void emitResult(boolean approvedResult) { + Log.i(TAG, "result=" + (approvedResult ? "approved" : "declined")); mainHandler.post(() -> { FaceclawFlashPromptListener current = listener; if (current != null) { diff --git a/app/phone-ui/onboarding-flash-view-model.ts b/app/phone-ui/onboarding-flash-view-model.ts index 3249c97c..a99e4880 100644 --- a/app/phone-ui/onboarding-flash-view-model.ts +++ b/app/phone-ui/onboarding-flash-view-model.ts @@ -56,6 +56,8 @@ export class OnboardingFlashViewModel extends Observable { private flasher: FirmwareFlasher | null = null; private flasherUnsubscribers: Array<() => void> = []; private retryAction: () => void = () => this.beginPrompt(); + /** Overrides the error screen's "Retry" when the action is not a retry. */ + private primaryLabelOverride: string | null = null; constructor(options?: { mode?: FlashMode; fromOnboarding?: boolean; autoStart?: boolean }) { super(); @@ -174,7 +176,7 @@ export class OnboardingFlashViewModel extends Observable { case "flashed": return "Finish"; case "error": - return "Retry"; + return this.primaryLabelOverride ?? "Retry"; default: return ""; } @@ -329,6 +331,25 @@ export class OnboardingFlashViewModel extends Observable { break; case "error": this.busy = false; + // An unacked prompt page is not a connection failure. The lens accepts the + // write at the GATT layer and then never answers, which is what firmware + // older than the revision this build needs does -- measured on revision 13, + // four writes accepted with status 0 and no reply, nothing shown on the lens. + // Flashing is the only way OFF that firmware, so failing here leaves the + // glasses permanently unupgradable. Fall back to the phone-side confirmation + // that the low-battery retry already uses, and say plainly what is being + // given up: the on-lens step is what proves these are the wearer's glasses. + if (/prompt page not acked/i.test(detail)) { + this.toError( + "Your glasses are on older firmware that can't show the confirmation prompt, so it can't be " + + "confirmed on the lens. You can confirm here instead. Only continue if these are your glasses " + + "and you want to install Faceclaw's custom firmware.", + () => this.beginPrompt({ skipPrompt: true }), + "Confirm On Your Phone", + "Confirm & Install", + ); + break; + } this.toError(detail || "Connection failed.", () => this.beginPrompt({ skipPrompt })); break; } @@ -569,7 +590,13 @@ export class OnboardingFlashViewModel extends Observable { }); } - private toError(message: string, retry: () => void, headline = "Something Went Wrong"): void { + private toError( + message: string, + retry: () => void, + headline = "Something Went Wrong", + primaryLabel: string | null = null, + ): void { + this.primaryLabelOverride = primaryLabel; this.retryAction = retry; this.status = message; this.setPhase("error"); diff --git a/tests/flash-prompt-fallback.test.cjs b/tests/flash-prompt-fallback.test.cjs new file mode 100644 index 00000000..a82151a8 --- /dev/null +++ b/tests/flash-prompt-fallback.test.cjs @@ -0,0 +1,62 @@ +// The flash cannot always ask for confirmation on the lens: firmware older than +// the revision this build needs accepts the create-prompt write and then never +// answers it. Flashing is the only way off that firmware, so an unacked prompt +// must not be a dead end. These cover the decision at that seam. +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { loader } = require('./helpers/load-typescript.cjs'); + +function fixture() { + class Observable { notifyPropertyChange() {} } + const load = loader({}, { + '@nativescript/core': { Observable, Frame: { topmost: () => null } }, + './onboarding-navigation': { finishOnboardingNavigation() {} }, + './onboarding-state': { setOnboardingCompleted() {}, setPreviewOnlyMode() {} }, + '../native/ble-permissions': { ensureBlePermissions: async () => {} }, + '../g2/device-addresses': { + isValidMacAddress: () => true, + loadDeviceAddresses: () => ({ right: 'R', left: 'L' }), + saveDeviceAddresses() {}, + }, + '../g2/firmware-builder': { + buildCustomFirmware: async () => '', buildStockFirmware: async () => '', + FirmwareBuildError: class extends Error {}, FirmwareProgress: {}, + }, + '../native/device-discovery': { buildAddressSet: () => new Set(), DeviceDiscoveryBridge: class {} }, + '../native/firmware-flasher': { FirmwareFlasher: class {} }, + '../native/flash-prompt-communicator': { FlashPromptCommunicator: class {} }, + '../g2/reconnect-policy': { resumeAutoReconnect() {}, suppressAutoReconnect() {} }, + '../util/format-error': { formatErrorMessage: (e) => String(e) }, + }); + const mod = load('app/phone-ui/onboarding-flash-view-model.ts'); + const Model = mod.OnboardingFlashViewModel ?? Object.values(mod).find((v) => typeof v === 'function'); + const model = new Model(); + const beginArgs = []; + model.beginPrompt = async (options) => { beginArgs.push(options); }; + return { model, beginArgs }; +} + +test('an unacked prompt page offers the phone-side confirmation instead of dead-ending', () => { + const { model, beginArgs } = fixture(); + model.handlePromptState('error', 'prompt page not acked: AA:BB:CC:DD:EE:FF', false); + assert.equal(model.phase, 'error'); + assert.equal(model.headline, 'Confirm On Your Phone'); + assert.equal(model.primaryLabel, 'Confirm & Install', 'the action is a confirmation, not a retry'); + assert.match(model.status, /can't show the confirmation prompt/i); + model.retryAction(); + // The loader runs the module in its own vm realm, so the options object has that + // realm's prototype and deepStrictEqual would reject it. Compare the field. + assert.equal(beginArgs.length, 1); + assert.equal(beginArgs[0].skipPrompt, true, 'confirming must skip the lens prompt, not re-ask for it'); +}); + +test('any other prompt failure still reports as an ordinary retry', () => { + const { model, beginArgs } = fixture(); + model.handlePromptState('error', 'discoverServices failed: right arm', false); + assert.equal(model.phase, 'error'); + assert.equal(model.headline, 'Something Went Wrong'); + assert.equal(model.primaryLabel, 'Retry'); + model.retryAction(); + assert.equal(beginArgs.length, 1); + assert.equal(beginArgs[0].skipPrompt, false, 'an ordinary failure must not silently skip the lens prompt'); +}); From 423f9fbcd1f9ec484def08dff9b42c6afb774d72 Mon Sep 17 00:00:00 2001 From: JMO Date: Wed, 23 Sep 2026 08:12:19 -0700 Subject: [PATCH 2/4] Refuse the flash with a reason when the glasses are in silent mode Silent mode blanks the display and stops the firmware dispatching input while BLE and GATT stay up, so the create-prompt page is written, accepted, and never rendered. There is no touchpad event available to answer it with, and the flash ends after four attempts on "prompt page not acked", which tells the wearer nothing about what is wrong or what to do about it. readBattery was already performing a sid-0x09 settings read whose ack carries silentMode next to the battery, and the field was being discarded. readSettings is factored out so one read serves both callers, and requireNotSilent runs it before the prompt page is written. A positive report throws, and the existing error path turns the message into what the wearer sees: that the glasses are in silent mode, and that long-pressing both touchpads leaves it. It refuses only on a positive report. An arm that does not answer, and firmware whose ack omits the field, both fall through to the prompt exactly as before, so older firmware is unaffected and a missing answer can never block a flash. This replaces the phone-side confirmation fallback that was here before. An unacked page is not by itself evidence that the prompt was never displayed, and the on-lens step is what proves the glasses being flashed are the ones in front of you, so overriding it on a timeout gave up more than it was worth. --- .../app/FaceclawFlashPromptCommunicator.java | 57 +++++++++++++++-- app/phone-ui/onboarding-flash-view-model.ts | 31 +--------- tests/flash-prompt-fallback.test.cjs | 62 ------------------- 3 files changed, 55 insertions(+), 95 deletions(-) delete mode 100644 tests/flash-prompt-fallback.test.cjs diff --git a/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawFlashPromptCommunicator.java b/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawFlashPromptCommunicator.java index 833a34b2..a0707a19 100644 --- a/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawFlashPromptCommunicator.java +++ b/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawFlashPromptCommunicator.java @@ -51,6 +51,15 @@ public class FaceclawFlashPromptCommunicator implements FaceclawBleListener { // Index 0 = decline, index 1 = approve. Kept short for the ~50-col grid. private static final String[] ITEMS = new String[] {"No, cancel", "Yes, flash"}; + /** + * Shown instead of a bare "prompt page not acked" timeout. Silent mode is + * entered and left by the same gesture on the glasses and nothing here can + * clear it, so the instruction has to travel with the error. + */ + private static final String SILENT_MODE_MESSAGE = + "Your glasses are in silent mode, so they cannot show the confirmation prompt. " + + "Long-press both touchpads on the glasses to leave silent mode, then try again."; + private static final int HEARTBEAT_INTERVAL_MS = 4_000; private static final int SELECTION_TIMEOUT_MS = 120_000; private static final int CREATE_ACK_TIMEOUT_MS = 3_000; @@ -183,6 +192,12 @@ public class FaceclawFlashPromptCommunicator implements FaceclawBleListener { sendPrelude(rightAddress); if (!skipPrompt) { + // Ask before writing a page that cannot be answered: silent mode + // blanks the display and stops the firmware dispatching input while + // BLE stays up, so the create-prompt write is still accepted and the + // flash would spend four attempts timing out on an error that says + // nothing about the reason. + requireNotSilent(rightAddress); showPrompt(rightAddress); startHeartbeat(); emitState("prompting", ""); @@ -376,6 +391,18 @@ public class FaceclawFlashPromptCommunicator implements FaceclawBleListener { } private int readBattery(String address, String arm) throws InterruptedException { + BleProtocol.BatterySnapshot snapshot = readSettings(address, arm); + return snapshot == null ? -1 : snapshot.battery; + } + + /** + * The sid-0x09 settings read behind both the battery gate and the + * silent-mode check. One ack carries both fields, so neither caller needs + * a query of its own. Returns null when the arm does not answer or the ack + * carries no settings payload. + */ + private BleProtocol.BatterySnapshot readSettings(String address, String arm) + throws InterruptedException { for (int attempt = 0; attempt < 2 && !cancelled; attempt++) { int magic = allocMagic(); byte[] ack = writeAndAwaitAck( @@ -386,16 +413,38 @@ public class FaceclawFlashPromptCommunicator implements FaceclawBleListener { BleProtocol.buildSettingsQuery(magic), BATTERY_ACK_TIMEOUT_MS); if (ack == null) { - emitLog("battery read attempt " + (attempt + 1) + " unacked: " + arm + " arm"); + emitLog("settings read attempt " + (attempt + 1) + " unacked: " + arm + " arm"); continue; } BleProtocol.BatterySnapshot snapshot = BleProtocol.parseSettingsBattery(ack); if (snapshot != null) { - return snapshot.battery; + return snapshot; } - emitLog("battery read ack had no battery field: " + arm + " arm"); + emitLog("settings read ack had no settings payload: " + arm + " arm"); + } + return null; + } + + /** + * Refuse the prompt only when the arm POSITIVELY reports silent mode. An + * arm that does not answer, and firmware whose ack omits the field + * (silentMode -1), both fall through to the prompt, so behavior on older + * firmware is unchanged and a missing answer never blocks a flash. + */ + private void requireNotSilent(String address) throws InterruptedException { + BleProtocol.BatterySnapshot snapshot = readSettings(address, "right"); + String state; + if (snapshot == null) { + state = "unknown (arm did not answer)"; + } else if (snapshot.silentMode < 0) { + state = "unknown (ack omits the field)"; + } else { + state = snapshot.silentMode > 0 ? "on" : "off"; + } + emitLog("silent mode before prompt: " + state); + if (snapshot != null && snapshot.silentMode > 0) { + throw new IllegalStateException(SILENT_MODE_MESSAGE); } - return -1; } /** Write and wait for the matching ack; returns the ack's protobuf (may be empty), or null on timeout/write failure. */ diff --git a/app/phone-ui/onboarding-flash-view-model.ts b/app/phone-ui/onboarding-flash-view-model.ts index a99e4880..3249c97c 100644 --- a/app/phone-ui/onboarding-flash-view-model.ts +++ b/app/phone-ui/onboarding-flash-view-model.ts @@ -56,8 +56,6 @@ export class OnboardingFlashViewModel extends Observable { private flasher: FirmwareFlasher | null = null; private flasherUnsubscribers: Array<() => void> = []; private retryAction: () => void = () => this.beginPrompt(); - /** Overrides the error screen's "Retry" when the action is not a retry. */ - private primaryLabelOverride: string | null = null; constructor(options?: { mode?: FlashMode; fromOnboarding?: boolean; autoStart?: boolean }) { super(); @@ -176,7 +174,7 @@ export class OnboardingFlashViewModel extends Observable { case "flashed": return "Finish"; case "error": - return this.primaryLabelOverride ?? "Retry"; + return "Retry"; default: return ""; } @@ -331,25 +329,6 @@ export class OnboardingFlashViewModel extends Observable { break; case "error": this.busy = false; - // An unacked prompt page is not a connection failure. The lens accepts the - // write at the GATT layer and then never answers, which is what firmware - // older than the revision this build needs does -- measured on revision 13, - // four writes accepted with status 0 and no reply, nothing shown on the lens. - // Flashing is the only way OFF that firmware, so failing here leaves the - // glasses permanently unupgradable. Fall back to the phone-side confirmation - // that the low-battery retry already uses, and say plainly what is being - // given up: the on-lens step is what proves these are the wearer's glasses. - if (/prompt page not acked/i.test(detail)) { - this.toError( - "Your glasses are on older firmware that can't show the confirmation prompt, so it can't be " + - "confirmed on the lens. You can confirm here instead. Only continue if these are your glasses " + - "and you want to install Faceclaw's custom firmware.", - () => this.beginPrompt({ skipPrompt: true }), - "Confirm On Your Phone", - "Confirm & Install", - ); - break; - } this.toError(detail || "Connection failed.", () => this.beginPrompt({ skipPrompt })); break; } @@ -590,13 +569,7 @@ export class OnboardingFlashViewModel extends Observable { }); } - private toError( - message: string, - retry: () => void, - headline = "Something Went Wrong", - primaryLabel: string | null = null, - ): void { - this.primaryLabelOverride = primaryLabel; + private toError(message: string, retry: () => void, headline = "Something Went Wrong"): void { this.retryAction = retry; this.status = message; this.setPhase("error"); diff --git a/tests/flash-prompt-fallback.test.cjs b/tests/flash-prompt-fallback.test.cjs deleted file mode 100644 index a82151a8..00000000 --- a/tests/flash-prompt-fallback.test.cjs +++ /dev/null @@ -1,62 +0,0 @@ -// The flash cannot always ask for confirmation on the lens: firmware older than -// the revision this build needs accepts the create-prompt write and then never -// answers it. Flashing is the only way off that firmware, so an unacked prompt -// must not be a dead end. These cover the decision at that seam. -const test = require('node:test'); -const assert = require('node:assert/strict'); -const { loader } = require('./helpers/load-typescript.cjs'); - -function fixture() { - class Observable { notifyPropertyChange() {} } - const load = loader({}, { - '@nativescript/core': { Observable, Frame: { topmost: () => null } }, - './onboarding-navigation': { finishOnboardingNavigation() {} }, - './onboarding-state': { setOnboardingCompleted() {}, setPreviewOnlyMode() {} }, - '../native/ble-permissions': { ensureBlePermissions: async () => {} }, - '../g2/device-addresses': { - isValidMacAddress: () => true, - loadDeviceAddresses: () => ({ right: 'R', left: 'L' }), - saveDeviceAddresses() {}, - }, - '../g2/firmware-builder': { - buildCustomFirmware: async () => '', buildStockFirmware: async () => '', - FirmwareBuildError: class extends Error {}, FirmwareProgress: {}, - }, - '../native/device-discovery': { buildAddressSet: () => new Set(), DeviceDiscoveryBridge: class {} }, - '../native/firmware-flasher': { FirmwareFlasher: class {} }, - '../native/flash-prompt-communicator': { FlashPromptCommunicator: class {} }, - '../g2/reconnect-policy': { resumeAutoReconnect() {}, suppressAutoReconnect() {} }, - '../util/format-error': { formatErrorMessage: (e) => String(e) }, - }); - const mod = load('app/phone-ui/onboarding-flash-view-model.ts'); - const Model = mod.OnboardingFlashViewModel ?? Object.values(mod).find((v) => typeof v === 'function'); - const model = new Model(); - const beginArgs = []; - model.beginPrompt = async (options) => { beginArgs.push(options); }; - return { model, beginArgs }; -} - -test('an unacked prompt page offers the phone-side confirmation instead of dead-ending', () => { - const { model, beginArgs } = fixture(); - model.handlePromptState('error', 'prompt page not acked: AA:BB:CC:DD:EE:FF', false); - assert.equal(model.phase, 'error'); - assert.equal(model.headline, 'Confirm On Your Phone'); - assert.equal(model.primaryLabel, 'Confirm & Install', 'the action is a confirmation, not a retry'); - assert.match(model.status, /can't show the confirmation prompt/i); - model.retryAction(); - // The loader runs the module in its own vm realm, so the options object has that - // realm's prototype and deepStrictEqual would reject it. Compare the field. - assert.equal(beginArgs.length, 1); - assert.equal(beginArgs[0].skipPrompt, true, 'confirming must skip the lens prompt, not re-ask for it'); -}); - -test('any other prompt failure still reports as an ordinary retry', () => { - const { model, beginArgs } = fixture(); - model.handlePromptState('error', 'discoverServices failed: right arm', false); - assert.equal(model.phase, 'error'); - assert.equal(model.headline, 'Something Went Wrong'); - assert.equal(model.primaryLabel, 'Retry'); - model.retryAction(); - assert.equal(beginArgs.length, 1); - assert.equal(beginArgs[0].skipPrompt, false, 'an ordinary failure must not silently skip the lens prompt'); -}); From 67c0671b9976aa73994386dbeff446db7f2b8b39 Mon Sep 17 00:00:00 2001 From: JMO Date: Wed, 23 Sep 2026 08:46:56 -0700 Subject: [PATCH 3/4] Log what the lens answers the prompt page with An ack is not a render: the lens can accept the create-prompt page and display nothing, so a null check on the reply throws away the only thing that can say what it did. The page size going out and the ack payload coming back are both logged now. --- .../app/FaceclawFlashPromptCommunicator.java | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawFlashPromptCommunicator.java b/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawFlashPromptCommunicator.java index a0707a19..8e9657f1 100644 --- a/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawFlashPromptCommunicator.java +++ b/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawFlashPromptCommunicator.java @@ -366,9 +366,15 @@ public class FaceclawFlashPromptCommunicator implements FaceclawBleListener { int magic = allocMagic(); byte[] page = BleProtocol.buildCreatePromptPage( magic, TEXT_NAME, TEXT_CONTAINER_ID, warningText, LIST_NAME, LIST_CONTAINER_ID, ITEMS); + emitLog("prompt page attempt " + (attempt + 1) + " writing " + page.length + " bytes to " + address); pageAck = writeAndAwaitAck(address, BleProtocol.SID_EVENHUB, BleProtocol.FLAG_REQUEST, magic, page, CREATE_ACK_TIMEOUT_MS); if (pageAck == null) { emitLog("prompt page attempt " + (attempt + 1) + " unacked: " + address); + } else { + // An ack is not a render. The lens can accept the page and show + // nothing, so the payload it answers with is the only thing that + // can say why; log it rather than only null-checking it. + emitLog("prompt page ack payload (" + pageAck.length + " bytes): " + toHex(pageAck)); } } if (pageAck == null) { @@ -633,6 +639,15 @@ public class FaceclawFlashPromptCommunicator implements FaceclawBleListener { }); } + /** Ack payloads are short; hex is the only honest way to log an opaque reply. */ + private static String toHex(byte[] bytes) { + StringBuilder out = new StringBuilder(bytes.length * 2); + for (byte b : bytes) { + out.append(String.format(java.util.Locale.ROOT, "%02x", b & 255)); + } + return out.toString(); + } + private void emitState(String state, String detail) { final String safeDetail = detail == null ? "" : detail; // Listener-only until now, so a prompt that never appeared left no trace in a log. From 727a3c0378889dc0534ee9bddff6c2bf9796bbe9 Mon Sep 17 00:00:00 2001 From: JMO Date: Fri, 25 Sep 2026 08:16:55 -0700 Subject: [PATCH 4/4] Refuse the flash prompt with a reason when the glasses are in silent mode Ported to the shared Kotlin FlashPromptFlow after the Java was converted. The settings ack the battery read already parses carries silentMode; read it before writing the prompt page, and refuse only on a positive report. An arm that does not answer, or an ack without the field, falls through to the prompt as before. --- .../app/g2protocol/FlashPromptFlow.kt | 54 ++++++++++++++++--- .../kotlin/com/faceclaw/app/StockFlowsTest.kt | 44 +++++++++++++-- 2 files changed, 89 insertions(+), 9 deletions(-) diff --git a/native/kotlin/shared/src/commonMain/kotlin/com/faceclaw/app/g2protocol/FlashPromptFlow.kt b/native/kotlin/shared/src/commonMain/kotlin/com/faceclaw/app/g2protocol/FlashPromptFlow.kt index d1b5a3f8..9fb44fa5 100644 --- a/native/kotlin/shared/src/commonMain/kotlin/com/faceclaw/app/g2protocol/FlashPromptFlow.kt +++ b/native/kotlin/shared/src/commonMain/kotlin/com/faceclaw/app/g2protocol/FlashPromptFlow.kt @@ -13,7 +13,9 @@ import kotlin.concurrent.Volatile * pairing prompt, and doing both here means both prompts appear at the start rather than one * popping up half way through flashing the second lens. While connected, each arm's battery * level is read (they are independent batteries) so the caller can refuse to flash on a low - * charge. + * charge. Before the prompt is shown, the right arm's settings are read once more so a lens + * that reports silent mode (which blanks the display and ignores input) is refused with the + * way out instead of a prompt nobody can see. * * With `skipPrompt` the on-glasses confirmation is not shown: the flow is just connect + auth + * battery read + result(approved). Used to re-check the battery after the user has already @@ -38,6 +40,15 @@ class FlashPromptFlow( const val LIST_CONTAINER_ID = 2 // Index 0 = decline, index 1 = approve. Kept short for the ~50-col grid. val ITEMS = arrayOf("No, cancel", "Yes, flash") + + /** + * Shown instead of a bare "prompt page not acked" error. Silent mode is entered and left + * by the same gesture on the glasses and nothing here can clear it, so the instruction + * has to travel with the error. + */ + const val SILENT_MODE_MESSAGE = + "Your glasses are in silent mode, so they cannot show the confirmation prompt. " + + "Long-press both touchpads on the glasses to leave silent mode, then try again." } private val rightAddress = rightAddress.trim() @@ -121,6 +132,11 @@ class FlashPromptFlow( session.sendPrelude(rightAddress, ": $rightAddress") if (!skipPrompt) { + // Ask before writing a page that cannot be answered: silent mode blanks the + // display and stops the firmware dispatching input while BLE stays up, so the + // create-prompt write is still acked and the user is left waiting on a prompt + // that never appears. + requireNotSilent(rightAddress) showPrompt(rightAddress) startHeartbeat() listener.onState("prompting", "") @@ -238,23 +254,49 @@ class FlashPromptFlow( listener.onBattery(right, left) } - private fun readBattery(address: String, arm: String): Int { + private fun readBattery(address: String, arm: String): Int = readSettingsSnapshot(address, arm)?.battery ?: -1 + + /** + * The sid-0x09 settings read behind both the battery gate and the silent-mode check; one + * ack carries both fields. Two attempts, since on 2.2.9 a request sent right after the + * prelude can be dropped. Null when the arm does not answer or the ack has no battery field. + */ + private fun readSettingsSnapshot(address: String, arm: String): BleProtocol.BatterySnapshot? { var attempt = 0 while (attempt < 2 && !cancelled) { val ack = session.readSettings(address, timings.batteryAckTimeoutMs) if (ack == null) { - emitLog("battery read attempt " + (attempt + 1) + " unacked: " + arm + " arm") + emitLog("settings read attempt " + (attempt + 1) + " unacked: " + arm + " arm") attempt++ continue } val snapshot = BleProtocol.parseSettingsBattery(ack) if (snapshot != null) { - return snapshot.battery + return snapshot } - emitLog("battery read ack had no battery field: $arm arm") + emitLog("settings read ack had no battery field: $arm arm") attempt++ } - return -1 + return null + } + + /** + * Refuse the prompt only when the arm POSITIVELY reports silent mode. An arm that does not + * answer, and firmware whose ack omits the field, both fall through to the prompt exactly as + * before, so a missing answer can never block a flash. + */ + private fun requireNotSilent(address: String) { + val snapshot = readSettingsSnapshot(address, "right") + val state = when { + snapshot == null -> "unknown (arm did not answer)" + snapshot.silentMode < 0 -> "unknown (ack omits the field)" + snapshot.silentMode > 0 -> "on" + else -> "off" + } + emitLog("silent mode before prompt: $state") + if (snapshot != null && snapshot.silentMode > 0) { + throw IllegalStateException(SILENT_MODE_MESSAGE) + } } private fun startHeartbeat() { diff --git a/tests/kotlin/src/commonTest/kotlin/com/faceclaw/app/StockFlowsTest.kt b/tests/kotlin/src/commonTest/kotlin/com/faceclaw/app/StockFlowsTest.kt index 9573d705..1506f7e1 100644 --- a/tests/kotlin/src/commonTest/kotlin/com/faceclaw/app/StockFlowsTest.kt +++ b/tests/kotlin/src/commonTest/kotlin/com/faceclaw/app/StockFlowsTest.kt @@ -60,11 +60,12 @@ private fun field(number: Int, text: String): ByteArray = field(number, text.enc private fun authSuccess(magic: Int) = BleProtocol.encodeVarintField(1, 4) + BleProtocol.encodeVarintField(2, magic) + field(3, ByteArray(0)) private fun authPending(magic: Int) = BleProtocol.encodeVarintField(1, 4) + BleProtocol.encodeVarintField(2, magic) + field(3, BleProtocol.encodeVarintField(1, 1)) private fun ack(magic: Int) = BleProtocol.encodeVarintField(1, 1) + BleProtocol.encodeVarintField(2, magic) -private fun settingsAck(magic: Int, battery: Int = -1, left: String = "", right: String = "", extension: String = ""): ByteArray { +private fun settingsAck(magic: Int, battery: Int = -1, left: String = "", right: String = "", extension: String = "", silentMode: Int = -1): ByteArray { var request = ByteArray(0) if (left.isNotEmpty()) request += field(5, left) if (right.isNotEmpty()) request += field(6, right) if (battery >= 0) request += BleProtocol.encodeVarintField(12, battery) + if (silentMode >= 0) request += BleProtocol.encodeVarintField(14, silentMode) var pb = BleProtocol.encodeVarintField(1, 2) + BleProtocol.encodeVarintField(2, magic) + field(4, request) if (extension.isNotEmpty()) pb += field(100, extension) return pb @@ -205,11 +206,11 @@ class StockFlowsTest { override fun onResult(approved: Boolean) { result = approved } } - private fun promptResponder(link: FakeStockLink, selection: Int?, batteries: Map): (FakeStockLink.Written) -> Unit = { w -> + private fun promptResponder(link: FakeStockLink, selection: Int?, batteries: Map, silentMode: Int = -1): (FakeStockLink.Written) -> Unit = { w -> when (w.sid) { BleProtocol.SID_SECURITY_AUTH -> link.notify(w.address, authSuccess(w.magic), w.sid) BleProtocol.PRELUDE_ACK_SID -> link.notify(w.address, ack(BleProtocol.PRELUDE_ACK_MAGIC), w.sid) - BleProtocol.SID_UI_SETTING -> link.notify(w.address, settingsAck(w.magic, batteries[w.address] ?: -1), w.sid) + BleProtocol.SID_UI_SETTING -> link.notify(w.address, settingsAck(w.magic, batteries[w.address] ?: -1, silentMode = silentMode), w.sid) BleProtocol.SID_EVENHUB -> { val cmd = BleProtocol.readVarintFieldValue(BleProtocol.stripTrailingCrc(w.pb), 1, -1) link.notify(w.address, ack(w.magic), w.sid) @@ -275,6 +276,43 @@ class StockFlowsTest { assertEquals("disconnected:Lost connection to the glasses.", events.states.last()) } + @Test + fun promptRefusesOnlyWhenTheLensReportsSilentMode() { + // Silent mode on: refused with the way out, before any page is written. + val silentOn = FakeStockLink() + silentOn.responder = promptResponder(silentOn, 1, mapOf(R to 85), silentMode = 1) + var events = PromptEvents() + FlashPromptFlow(silentOn, R, "", "w", false, events, fast, testPlatform()).run() + assertEquals(null, events.result) + assertEquals("error:${FlashPromptFlow.SILENT_MODE_MESSAGE}", events.states.last()) + assertTrue(events.logs.any { it == "silent mode before prompt: on" }) + assertFalse(silentOn.writes.any { it.sid == BleProtocol.SID_EVENHUB }) + assertTrue(silentOn.closed) + + // Silent mode off: the prompt is shown and answered as usual. + val silentOff = FakeStockLink() + silentOff.responder = promptResponder(silentOff, 1, mapOf(R to 85), silentMode = 0) + events = PromptEvents() + FlashPromptFlow(silentOff, R, "", "w", false, events, fast, testPlatform()).run() + assertEquals(true, events.result, events.logs.joinToString("\n")) + assertTrue(events.logs.any { it == "silent mode before prompt: off" }) + + // Firmware whose ack omits the field: unknown is not a refusal. + val omitted = FakeStockLink() + omitted.responder = promptResponder(omitted, 1, mapOf(R to 85)) + events = PromptEvents() + FlashPromptFlow(omitted, R, "", "w", false, events, fast, testPlatform()).run() + assertEquals(true, events.result, events.logs.joinToString("\n")) + assertTrue(events.logs.any { it == "silent mode before prompt: unknown (ack omits the field)" }) + + // skipPrompt re-checks the battery only; silent mode does not block it. + val skipped = FakeStockLink() + skipped.responder = promptResponder(skipped, null, mapOf(R to 85), silentMode = 1) + events = PromptEvents() + FlashPromptFlow(skipped, R, "", "w", true, events, fast, testPlatform()).run() + assertEquals(true, events.result) + } + // ---- OTA --------------------------------------------------------------- private fun putU32(buf: ByteArray, offset: Int, value: Long) { for (i in 0 until 4) buf[offset + i] = ((value ushr (8 * i)) and 0xff).toByte() }