From 4b2af9fd8bb79c83b3bfbbb035d760e0362db714 Mon Sep 17 00:00:00 2001 From: Egor Kolesnikov Date: Sat, 21 Nov 2026 09:31:16 +0200 Subject: [PATCH 1/3] Rescue: give each notification subscription 3 seconds, and skip the ones it doesn't need MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit On a Watch 3 Pro stuck in a boot loop, every attempt now stalls on the first startNotifications — the first step the watch itself has to answer, since Windows can serve the service list from its cache — until the watch restarts about 17 s later. Rescue now listens only on the command and data channels (plus the shell when it has to pair) and gives up on a subscription after 3 s, so a dead try ends fast and leaves time for more tries in the windows the watch is up. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01CQSU8Nr9jJ3ALiRfiDuC6m --- src/lib/modules/device/lib/ble.ts | 45 +++++++++++++++++++++++++++--- src/lib/modules/device/messages.ts | 6 ++++ tests/ble-within.test.ts | 12 ++++++++ 3 files changed, 59 insertions(+), 4 deletions(-) create mode 100644 tests/ble-within.test.ts diff --git a/src/lib/modules/device/lib/ble.ts b/src/lib/modules/device/lib/ble.ts index d4099f9..bc39736 100644 --- a/src/lib/modules/device/lib/ble.ts +++ b/src/lib/modules/device/lib/ble.ts @@ -76,6 +76,22 @@ export const capacityOf = (name: string | null) => /watch (3 pro|pro 3)/i.test(name ?? "") ? WF_CAPACITY_PRO3 : WF_CAPACITY; const KEY_STORE = "fmc_authkey"; +const LISTEN = ["cmdRead", "dataRead", "shellRead", "otaRead"] as const; + +type ListenKey = (typeof LISTEN)[number]; +// commands and their answers, and the data channel a face delete runs over; the shell to pair +const RESCUE_LISTEN = (keyed: boolean): ListenKey[] => + keyed ? ["cmdRead", "dataRead"] : ["cmdRead", "dataRead", "shellRead"]; +const RESCUE_SUB_MS = 3000; +/** `p`, or `err()` if it hasn't settled within `ms`. */ +export const within = (p: Promise, ms: number, err: () => Error): Promise => { + let timer: ReturnType | undefined; + + return Promise.race([ + p, + new Promise((_, rej) => (timer = setTimeout(() => rej(err()), ms))), + ]).finally(() => clearTimeout(timer)); +}; // how long the rescue page waits for a pairing to be confirmed before it reconnects and asks again const RESCUE_PAIR_MS = 30000; const loadKey = (): Uint8Array | null => { @@ -299,9 +315,19 @@ export class Watch { } throw e; } - const subscribe = async () => { - for (const key of ["cmdRead", "dataRead", "shellRead", "otaRead"] as const) { + // Rescue listens only where its actions get answers — the shell only when it has to pair, the + // firmware-update channel never — and gives each subscription RESCUE_SUB_MS. On a watch stuck + // in a boot loop this is the first step the watch itself has to answer (Windows can serve the + // service list from its cache), and it answers at once or not before it restarts ~17 s later: + // failing fast leaves time for more tries in the windows it is up. + const subscribed = new Set(); + const subscribe = async ( + keys: readonly ListenKey[] = rescue ? RESCUE_LISTEN(Boolean(loadKey())) : LISTEN, + ) => { + for (const key of keys) { const ch = this.chars[UUID[key]]; + + if (subscribed.has(ch?.uuid)) continue; // shell service is only needed for first-time pairing; some firmwares hide it. The // firmware-update channel only for a firmware update, which checks for it itself if (!ch) { @@ -314,7 +340,14 @@ export class Watch { write: ch.properties.write, writeNoResp: ch.properties.writeWithoutResponse, }); - await ch.startNotifications(); + await (rescue + ? within( + ch.startNotifications(), + RESCUE_SUB_MS, + () => new Error(`the watch didn't answer the ${key} subscription`), + ) + : ch.startNotifications()); + subscribed.add(ch.uuid); ch.addEventListener("characteristicvaluechanged", (e) => { const value = (e.target as BluetoothRemoteGATTCharacteristic).value!; const bytes = new Uint8Array(value.buffer, value.byteOffset, value.byteLength); @@ -365,9 +398,13 @@ export class Watch { await connectOrRepick("reconnection"); await subscribe(); } + await subscribe(["shellRead"]); await this.pair(pairMs); } - } else await this.pair(pairMs); + } else { + await subscribe(["shellRead"]); + await this.pair(pairMs); + } if (!rescue) await this.fetchInfo(); } catch (e) { // without this a failed pair()/authenticate() leaves the physical GATT link hanging: diff --git a/src/lib/modules/device/messages.ts b/src/lib/modules/device/messages.ts index 4bd73bc..ae2aa59 100644 --- a/src/lib/modules/device/messages.ts +++ b/src/lib/modules/device/messages.ts @@ -34,6 +34,7 @@ const en = { timedOut: (what: string) => `${what} timed out — the watch is probably connected to another app or browser tab; close it (phone app, fmc CLI, old editor tab) and retry`, charNotFound: (key: string) => `characteristic ${key} not found`, + subNoAnswer: (key: string) => `the watch didn't answer the ${key} subscription`, timeoutWaiting: (cmd: string) => `timeout waiting for ${cmd}`, pairingNotFound: "pairing service not found — reconnect and try again; if this keeps happening the watch may be using a new service UUID (see SERVICES in ble.ts)", @@ -135,6 +136,7 @@ export const bt = dict(en, { timedOut: (what) => `${what}: время ожидания истекло — вероятно, часы подключены к другому приложению или вкладке; закройте его (приложение на телефоне, fmc CLI, старую вкладку редактора) и повторите`, charNotFound: (key) => `характеристика ${key} не найдена`, + subNoAnswer: (key) => `часы не ответили на подписку ${key}`, timeoutWaiting: (cmd) => `нет ответа на ${cmd}`, pairingNotFound: "сервис сопряжения не найден — переподключитесь и попробуйте снова; если повторяется, возможно, у часов новый UUID сервиса (см. SERVICES в ble.ts)", @@ -230,6 +232,7 @@ export const bt = dict(en, { timedOut: (what) => `${what}: час очікування вичерпано — мабуть, годинник під'єднаний до іншого застосунку чи вкладки; закрийте їх (застосунок на телефоні, fmc CLI, стару вкладку редактора) і повторіть`, charNotFound: (key) => `характеристику ${key} не знайдено`, + subNoAnswer: (key) => `годинник не відповів на підписку ${key}`, timeoutWaiting: (cmd) => `немає відповіді на ${cmd}`, pairingNotFound: "сервіс сполучення не знайдено — під'єднайтеся знову; якщо це повторюється, можливо, годинник має новий UUID сервісу (див. SERVICES у ble.ts)", @@ -325,6 +328,7 @@ export const bt = dict(en, { timedOut: (what) => `${what}: se agotó el tiempo — seguramente el reloj está conectado a otra app o pestaña; ciérrala (la app del teléfono, fmc CLI, una pestaña antigua del editor) y reintenta`, charNotFound: (key) => `no se encontró la característica ${key}`, + subNoAnswer: (key) => `el reloj no respondió a la suscripción ${key}`, timeoutWaiting: (cmd) => `sin respuesta a ${cmd}`, pairingNotFound: "no se encontró el servicio de emparejamiento — reconecta e inténtalo de nuevo; si se repite, puede que el reloj use un UUID de servicio nuevo (ver SERVICES en ble.ts)", @@ -422,6 +426,7 @@ export const bt = dict(en, { timedOut: (what) => `${what}: समय समाप्त — घड़ी शायद किसी दूसरे ऐप या टैब से जुड़ी है; उसे बंद करें (फ़ोन ऐप, fmc CLI, एडिटर का पुराना टैब) और फिर कोशिश करें`, charNotFound: (key) => `कैरेक्टरिस्टिक ${key} नहीं मिली`, + subNoAnswer: (key) => `घड़ी ने ${key} सब्सक्रिप्शन का जवाब नहीं दिया`, timeoutWaiting: (cmd) => `${cmd} का जवाब नहीं आया`, pairingNotFound: "पेयरिंग सर्विस नहीं मिली — फिर से कनेक्ट करके कोशिश करें; बार-बार हो तो घड़ी शायद नया सर्विस UUID इस्तेमाल कर रही है (ble.ts में SERVICES देखें)", @@ -525,6 +530,7 @@ const RULES: Rule[] = [ lit("noWebBluetooth"), [/^(.+) timed out — the watch is probably connected/, (w, m) => w.timedOut(m[1])], [/^characteristic (.+) not found$/, (w, m) => w.charNotFound(m[1])], + [/^the watch didn't answer the (.+) subscription$/, (w, m) => w.subNoAnswer(m[1])], [/^timeout waiting for (\S+)$/, (w, m) => w.timeoutWaiting(m[1])], lit("pairingNotFound"), [/^pairing rejected: (.+)$/s, (w, m) => w.pairingRejected(m[1])], diff --git a/tests/ble-within.test.ts b/tests/ble-within.test.ts new file mode 100644 index 0000000..8898a9e --- /dev/null +++ b/tests/ble-within.test.ts @@ -0,0 +1,12 @@ +// Rescue gives each notification subscription a few seconds: a step the watch never answers must +// end, and one it answers must not leave a late rejection behind. +import { expect, test } from "vitest"; +import { within } from "$lib/modules/device/lib/ble"; + +test("within rejects a promise that doesn't settle in time", async () => { + await expect(within(new Promise(() => {}), 10, () => new Error("late"))).rejects.toThrow("late"); +}); + +test("within passes a prompt answer through", async () => { + await expect(within(Promise.resolve(7), 10, () => new Error("late"))).resolves.toBe(7); +}); From 566a32db77562c9f3b9405f78addaa69190f743f Mon Sep 17 00:00:00 2001 From: Egor Kolesnikov Date: Sat, 21 Nov 2026 10:22:58 +0200 Subject: [PATCH 2/3] Rescue: send the time before a factory reset, and repeat authName until answered MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Found in the Watch 3 Pro firmware and confirmed in the cmf-watch-utils emulator: - the watch ignores a factory reset until a time write (0x8004) has marked the link live, and a clock more than 2 min off takes the time only on the second write — so the reset now goes out after the time, twice, in the reference client's format; - the watch drops every frame for its first 200 ms on a link, so the first authName was lost whenever rescue connected quickly; rescue now re-sends it every 100 ms until the watch answers. Before this, the rescue page's reset could not have worked on any watch. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01CQSU8Nr9jJ3ALiRfiDuC6m --- src/lib/modules/device/lib/ble.ts | 34 ++++++++++++++++++++++++++----- tests/ble-factory-reset.test.ts | 25 +++++++++++++++++++++++ 2 files changed, 54 insertions(+), 5 deletions(-) create mode 100644 tests/ble-factory-reset.test.ts diff --git a/src/lib/modules/device/lib/ble.ts b/src/lib/modules/device/lib/ble.ts index bc39736..ca868e8 100644 --- a/src/lib/modules/device/lib/ble.ts +++ b/src/lib/modules/device/lib/ble.ts @@ -92,6 +92,10 @@ export const within = (p: Promise, ms: number, err: () => Error): Promise< new Promise((_, rej) => (timer = setTimeout(() => rej(err()), ms))), ]).finally(() => clearTimeout(timer)); }; +// The watch drops every frame for its first 200 ms on a link (the command channel opens on a +// timer in its connected callback; WP3 firmware, seen in the emulator), so on rescue — which +// connects as early as it can — authName is re-sent at this pace until it is answered. +const RESCUE_NAME_MS = 100; // how long the rescue page waits for a pairing to be confirmed before it reconnects and asks again const RESCUE_PAIR_MS = 30000; const loadKey = (): Uint8Array | null => { @@ -376,7 +380,7 @@ export class Watch { if (k) { try { - await this.authenticate(k); + await this.authenticate(k, rescue); } catch (e) { // a stale key (the watch was re-paired/reset) shows up as authFailed or silence on the first // encrypted exchange (authMac = 0x49); other errors don't touch the saved key. On rescue @@ -996,7 +1000,8 @@ export class Watch { await this.authenticate(k1); } - async authenticate(k1: Uint8Array) { + /** `repeatName`: re-send authName until the watch answers it — see RESCUE_NAME_MS. */ + async authenticate(k1: Uint8Array, repeatName = false) { this.status("authenticating…"); await this.codec.setKey(k1); // the watch sends authFailed if it can't decrypt with the key — we react immediately instead of waiting for the timeout @@ -1008,8 +1013,16 @@ export class Watch { const wait = (key: number) => Promise.race([this.waitFor(key), failed]); try { - await this.send(CMD.authName, cat(new Uint8Array([MARKER]), utf8("fmc"))); - await wait(CMD.authMac); + const name = () => this.send(CMD.authName, cat(new Uint8Array([MARKER]), utf8("fmc"))); + + await name(); + const again = repeatName ? setInterval(() => name().catch(() => {}), RESCUE_NAME_MS) : 0; + + try { + await wait(CMD.authMac); + } finally { + clearInterval(again); + } await this.send(CMD.authNonceReq, new Uint8Array([MARKER])); const nonce = await wait(CMD.authNonceRep); @@ -1022,8 +1035,19 @@ export class Watch { } // Gadgetbridge's FACTORY_RESET: the marker byte and nothing else. The watch wipes itself and - // reboots; it won't answer, so there is nothing to wait for. + // reboots; it won't answer, so there is nothing to wait for. It ignores the reset until a time + // write has marked the link live (SetLinkFlg in the 0x8004 handler; WP3 firmware, confirmed in + // the cmf-watch-utils emulator), and a clock more than 2 min off takes the time only on the + // second write: so the time twice, then the reset. The payload is the reference client's + // (cmf_watch.py: >ii unix seconds, UTC offset in ms) — a malformed one once reset a watch. async factoryReset() { + const time = new Uint8Array(8); + const dv = new DataView(time.buffer); + + dv.setInt32(0, Math.floor(Date.now() / 1000)); + dv.setInt32(4, -new Date().getTimezoneOffset() * 60000); + await this.send(CMD.time, time); + await this.send(CMD.time, time); await this.send(CMD.factoryReset, new Uint8Array([MARKER])); } diff --git a/tests/ble-factory-reset.test.ts b/tests/ble-factory-reset.test.ts new file mode 100644 index 0000000..8129068 --- /dev/null +++ b/tests/ble-factory-reset.test.ts @@ -0,0 +1,25 @@ +// The watch ignores a factory reset until a time write marks the link live, and a clock more +// than 2 minutes off takes the time only on the second write (WP3 firmware, in the emulator). +import { expect, test } from "vitest"; +import { Watch } from "$lib/modules/device/lib/ble"; +import { CMD, MARKER } from "$lib/modules/device/lib/ble-protocol"; + +test("factory reset goes out after two time writes in the reference format", async () => { + const w = new Watch(); + const sent: [number, Uint8Array][] = []; + + w.send = async (key: number, payload?: Uint8Array) => { + sent.push([key, payload ?? new Uint8Array()]); + }; + const before = Math.floor(Date.now() / 1000); + + await w.factoryReset(); + + expect(sent.map(([k]) => k)).toEqual([CMD.time, CMD.time, CMD.factoryReset]); + const dv = new DataView(sent[0][1].buffer); + + expect(sent[0][1].length).toBe(8); + expect(dv.getInt32(0)).toBeGreaterThanOrEqual(before); + expect(dv.getInt32(4)).toBe(-new Date().getTimezoneOffset() * 60000); + expect([...sent[2][1]]).toEqual([MARKER]); +}); From 8ce02267473604d97710d645c47115cee37152c4 Mon Sep 17 00:00:00 2001 From: Egor Kolesnikov Date: Sat, 21 Nov 2026 10:41:10 +0200 Subject: [PATCH 3/3] Rescue: 500 ms per subscription and authName every 20 ms, from emulator timings The cmf-watch-utils emulator (WP3 firmware) puts numbers on both: a live watch answers a subscription in 8-11 ms, while one past its crash keeps advertising and accepting a link but answers nothing until it reboots, so waiting 3 s only delays the next try. And authName re-sent every 20 ms lands 5-6 ms after the 200 ms gate instead of 38-61 ms, with exactly one handled. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01CQSU8Nr9jJ3ALiRfiDuC6m --- src/lib/modules/device/lib/ble.ts | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/lib/modules/device/lib/ble.ts b/src/lib/modules/device/lib/ble.ts index ca868e8..c334864 100644 --- a/src/lib/modules/device/lib/ble.ts +++ b/src/lib/modules/device/lib/ble.ts @@ -82,7 +82,11 @@ type ListenKey = (typeof LISTEN)[number]; // commands and their answers, and the data channel a face delete runs over; the shell to pair const RESCUE_LISTEN = (keyed: boolean): ListenKey[] => keyed ? ["cmdRead", "dataRead"] : ["cmdRead", "dataRead", "shellRead"]; -const RESCUE_SUB_MS = 3000; +// A live watch answers a subscription in 8–11 ms (emulator); one past its crash, still +// advertising and accepting a link, never does until it reboots. ponytail: 500 ms, not the +// emulator's 300, to leave room for a slow host stack — lower it if real logs show no answer +// ever takes that long. +const RESCUE_SUB_MS = 500; /** `p`, or `err()` if it hasn't settled within `ms`. */ export const within = (p: Promise, ms: number, err: () => Error): Promise => { let timer: ReturnType | undefined; @@ -95,7 +99,7 @@ export const within = (p: Promise, ms: number, err: () => Error): Promise< // The watch drops every frame for its first 200 ms on a link (the command channel opens on a // timer in its connected callback; WP3 firmware, seen in the emulator), so on rescue — which // connects as early as it can — authName is re-sent at this pace until it is answered. -const RESCUE_NAME_MS = 100; +const RESCUE_NAME_MS = 20; // how long the rescue page waits for a pairing to be confirmed before it reconnects and asks again const RESCUE_PAIR_MS = 30000; const loadKey = (): Uint8Array | null => {