diff --git a/src/lib/modules/device/messages.ts b/src/lib/modules/device/messages.ts index ff5e6e1..28a3dbd 100644 --- a/src/lib/modules/device/messages.ts +++ b/src/lib/modules/device/messages.ts @@ -59,6 +59,10 @@ const en = { `the watch refused to replace “${name}” — flash again and pick a different dial to replace`, aodNoPreview: "the always-on screen has no preview thumbnail, and the watch can crash in a loop on it. Open the face in the editor and flash it from there — the editor puts the thumbnail back.", + unreadableFace: + "FMC can't read this file, so it can't check that the watch will survive it. Nothing was sent to the watch.", + unmeasurableFace: + "FMC can't measure how much memory this face needs, and too much makes a Watch 3 Pro restart in a loop. Nothing was sent to the watch.", imageOverLimit: (w: string, h: string, max: string) => `an image is ${w}×${h} px, over the ${max} px limit — the watch can run out of memory loading it and restart in a loop. Resize it in the editor first.`, screenOverBudget: (aod: boolean, need: string, max: string) => @@ -161,6 +165,10 @@ export const bt = dict(en, { `часы отказались заменить «${name}» — загрузите ещё раз и выберите другой циферблат для замены`, aodNoPreview: "у экрана always-on нет миниатюры, и часы могут на нём зациклиться на перезагрузке. Откройте циферблат в редакторе и загрузите оттуда — редактор вернёт миниатюру.", + unreadableFace: + "FMC не может прочитать этот файл и проверить, безопасен ли он для часов. На часы ничего не отправлено.", + unmeasurableFace: + "FMC не может посчитать, сколько памяти нужно этому циферблату, а от нехватки памяти Watch 3 Pro зацикливается на перезагрузке. На часы ничего не отправлено.", imageOverLimit: (w, h, max) => `изображение ${w}×${h} px больше предела в ${max} px — часам может не хватить памяти, и они зациклятся на перезагрузке. Сначала уменьшите его в редакторе.`, screenOverBudget: (aod, need, max) => @@ -258,6 +266,10 @@ export const bt = dict(en, { `годинник відмовився замінити «${name}» — завантажте ще раз і виберіть інший циферблат для заміни`, aodNoPreview: "екран always-on не має мініатюри, і годинник може циклічно перезавантажуватися на ньому. Відкрийте циферблат у редакторі й завантажте звідти — редактор поверне мініатюру.", + unreadableFace: + "FMC не може прочитати цей файл і перевірити, чи безпечний він для годинника. На годинник нічого не надіслано.", + unmeasurableFace: + "FMC не може порахувати, скільки пам’яті потрібно цьому циферблату, а через брак пам’яті Watch 3 Pro циклічно перезавантажується. На годинник нічого не надіслано.", imageOverLimit: (w, h, max) => `зображення ${w}×${h} px перевищує межу ${max} px — годиннику може забракнути пам'яті, і він циклічно перезавантажуватиметься. Спершу зменште його в редакторі.`, screenOverBudget: (aod, need, max) => @@ -355,6 +367,10 @@ export const bt = dict(en, { `el reloj se negó a reemplazar «${name}» — vuelve a enviarla y elige otra esfera para reemplazar`, aodNoPreview: "la pantalla siempre activa no tiene miniatura, y el reloj puede quedarse reiniciándose en bucle con ella. Abre la esfera en el editor y envíala desde allí — el editor repone la miniatura.", + unreadableFace: + "FMC no puede leer este archivo ni comprobar que sea seguro para el reloj. No se envió nada al reloj.", + unmeasurableFace: + "FMC no puede calcular cuánta memoria necesita esta esfera y, si le falta memoria, el Watch 3 Pro se reinicia en bucle. No se envió nada al reloj.", imageOverLimit: (w, h, max) => `una imagen mide ${w}×${h} px, más del límite de ${max} px — el reloj puede quedarse sin memoria al cargarla y reiniciarse en bucle. Redúcela primero en el editor.`, screenOverBudget: (aod, need, max) => @@ -454,6 +470,10 @@ export const bt = dict(en, { `घड़ी ने “${name}” को बदलने से मना किया — फिर से भेजें और बदलने के लिए दूसरा फ़ेस चुनें`, aodNoPreview: "ऑलवेज़-ऑन स्क्रीन का थंबनेल नहीं है, और घड़ी उस पर बार-बार रीस्टार्ट हो सकती है। फ़ेस को एडिटर में खोलें और वहीं से भेजें — एडिटर थंबनेल वापस जोड़ देता है।", + unreadableFace: + "FMC इस फ़ाइल को पढ़ नहीं सकता, इसलिए यह जाँच नहीं सकता कि यह घड़ी के लिए सुरक्षित है। घड़ी पर कुछ नहीं भेजा गया।", + unmeasurableFace: + "FMC यह नहीं माप सकता कि इस फ़ेस को कितनी मेमोरी चाहिए, और मेमोरी कम पड़ने पर Watch 3 Pro बार-बार रीस्टार्ट होती है। घड़ी पर कुछ नहीं भेजा गया।", imageOverLimit: (w, h, max) => `एक इमेज ${w}×${h} px की है, ${max} px की सीमा से बड़ी — घड़ी की मेमोरी खत्म हो सकती है और वह बार-बार रीस्टार्ट हो सकती है। पहले एडिटर में इसे छोटा करें।`, screenOverBudget: (aod, need, max) => @@ -558,6 +578,8 @@ const RULES: Rule[] = [ [/^the watch refused to replace “(.+)” — /, (w, m) => w.refusedReplace(m[1])], [/^dial delete failed \((.+)\)$/, (w, m) => w.deleteFailed(m[1])], lit("aodNoPreview"), + lit("unreadableFace"), + lit("unmeasurableFace"), [ /^an image is (\d+)×(\d+) px, over the (\d+) px limit/, (w, m) => w.imageOverLimit(m[1], m[2], m[3]), diff --git a/src/lib/modules/editor/core/format/bin.ts b/src/lib/modules/editor/core/format/bin.ts index d72062d..99890fc 100644 --- a/src/lib/modules/editor/core/format/bin.ts +++ b/src/lib/modules/editor/core/format/bin.ts @@ -4,7 +4,7 @@ import type { Face, FaceNode, Resource } from "./raw"; import { TAG, handKinds, hex, i16, u16, u32, unhex } from "./raw"; -import { overBudget, SCREEN_BUDGET } from "./budget"; +import { measurable, overBudget, SCREEN_BUDGET } from "./budget"; interface TLVNode { tag: number; @@ -410,8 +410,9 @@ const largest = (resources: Resource[], side: number) => /** Throws when the file holds something the watch may not survive: an image too big to load, a * screen past a Watch 3 Pro's memory (`device` is the watch it goes to, devices.ts), or an - * always-on screen without its thumbnail. A file we can't parse isn't blocked here — the watch's - * installer still gets to refuse it. Run fitForWatch first: it shrinks what it can. */ + * always-on screen without its thumbnail. It fails closed: a file we can't parse goes to no + * watch, and one we can't measure doesn't go to a Watch 3 Pro — the watch's installer takes + * faces that then boot-loop it. Run fitForWatch first: it shrinks what it can. */ export function assertFlashable(bin: Uint8Array, device: string | null = null): void { let face: Face, resources: Resource[], screens: FaceNode[]; @@ -419,7 +420,9 @@ export function assertFlashable(bin: Uint8Array, device: string | null = null): face = parseBin(bin); ({ resources, screens } = face); } catch { - return; + throw new Error( + "FMC can't read this file, so it can't check that the watch will survive it. Nothing was sent to the watch.", + ); } // all 223 stock AOD screens (Pro 2 and Pro 3) carry a 0x28 thumbnail, and the FMC face that // crash-looped a Watch 3 Pro on AOD was the one whose AOD screen had none (#49). ponytail: the @@ -438,6 +441,10 @@ export function assertFlashable(bin: Uint8Array, device: string | null = null): throw new Error( `an image is ${big.w}×${big.h} px, over the ${MAX_IMAGE_SIDE} px limit — the watch can run out of memory loading it and restart in a loop. Resize it in the editor first.`, ); + if (device === "watch_3_pro" && !measurable(face)) + throw new Error( + "FMC can't measure how much memory this face needs, and too much makes a Watch 3 Pro restart in a loop. Nothing was sent to the watch.", + ); const heavy = device === "watch_3_pro" ? overBudget(face)[0] : undefined; if (heavy) diff --git a/src/lib/modules/editor/core/format/budget.ts b/src/lib/modules/editor/core/format/budget.ts index 7bcedb0..5d44f10 100644 --- a/src/lib/modules/editor/core/format/budget.ts +++ b/src/lib/modules/editor/core/format/budget.ts @@ -87,6 +87,46 @@ export function screenMemory(screen: FaceNode, resources: Resource[]): ScreenMem }; } +/** The colour formats decodedBytes knows. */ +const MEASURED = new Set([1, 4, 5, 13, 14, 24, 28]); +/** The tags that hold layers in every face of the catalog and both factory corpora. */ +const CONTAINERS = new Set([ + TAG.main, + TAG.aod, + TAG.image, + 0x38, + TAG.number, + TAG.group, + TAG.hand, + 0x80, + 0x81, + 0x82, + 0x83, + 0x84, + 0x85, + 0x89, +]); + +/** + * Whether screenBytes sees everything the face shows. Whatever the parser couldn't follow counts + * as zero there, so a face with any of it has no known size: a screen or a container that didn't + * parse into layers, an image reference that leads to no resource (kept as `tail`; all zeroes + * is no image), an image in a format decodedBytes doesn't know. + * ponytail: containers are a list, so one with a tag not seen yet could still hide images — add + * the tag here when a corpus turns one up. + */ +export function measurable({ screens, resources }: Face): boolean { + const ok = (n: FaceNode, top: boolean): boolean => { + if (n.tag === TAG.preview) return true; + if (n.images) return n.images.every((i) => MEASURED.has(resources[i].cf)); + if (n.tag === TAG.struct && (n.hex || /[^0]/.test(n.tail ?? ""))) return false; + if (n.hex && (top || CONTAINERS.has(n.tag))) return false; + return n.subs?.every((s) => ok(s, false)) ?? true; + }; + + return screens.every((s) => ok(s, true)); +} + /** The screens of a face that a Watch 3 Pro can't hold, with what each needs. */ export const overBudget = (face: Face) => face.screens diff --git a/tests/analytics-flash-failed.browser.test.ts b/tests/analytics-flash-failed.browser.test.ts index f3a7472..c1b8dad 100644 --- a/tests/analytics-flash-failed.browser.test.ts +++ b/tests/analytics-flash-failed.browser.test.ts @@ -3,6 +3,7 @@ import { test, expect, vi } from "vitest"; import { bleModel } from "$lib/modules/device/model"; import "$lib/modules/analytics/model"; +import url from "./__fixtures__/Analog__287__Simple_Dial.bin?url"; const sent = vi.hoisted((): [string, unknown][] => []); @@ -31,7 +32,10 @@ vi.mock("$lib/modules/device/lib/ble", async (importOriginal) => { test("a flash cut off by a disconnect still names the watch it was going to", async () => { bleModel.connectRequested(); await vi.waitFor(() => expect(bleModel.$bleInfo.getState()).not.toBeNull()); - bleModel.flashRequested({ bin: new Uint8Array() }); + // a face the gate lets through: one it refuses never gets as far as the link + const bin = new Uint8Array(await (await fetch(url)).arrayBuffer()); + + bleModel.flashRequested({ bin }); // the file goes through a worker first (fitForWatchOffThread), which a loaded run starts slowly await vi.waitFor(() => expect(sent).toHaveLength(2), { timeout: 5000 }); diff --git a/tests/flashable.test.ts b/tests/flashable.test.ts index 54f1bea..4b0cb34 100644 --- a/tests/flashable.test.ts +++ b/tests/flashable.test.ts @@ -1,12 +1,14 @@ -import { readFileSync } from "node:fs"; -import { expect, test } from "vitest"; +import { readdirSync, readFileSync } from "node:fs"; +import { describe, expect, test } from "vitest"; import { assertFlashable, buildBin, flashWarning, parseBin, + shownResources, TAG, } from "$lib/modules/editor/core/format"; +import type { Face, FaceNode } from "$lib/modules/editor/core/format"; import { fromLegacy, toLegacy } from "$lib/modules/editor/core/document/doc"; import { withPreviews } from "$lib/modules/editor/core/document/factory"; @@ -55,3 +57,62 @@ test("an AOD screen without its preview is refused, and the editor's export rest expect(withPreviews(fixed, face.resources[0])).toBe(fixed); // nothing left to restore expect(() => assertFlashable(buildBin(toLegacy(fixed)))).not.toThrow(); }); + +// The face that boot-looped a Watch 3 Pro went through the gate in each of these shapes: whatever +// the parser couldn't read was counted as zero bytes, or not checked at all. +test("a file that does not parse is refused for every watch", () => { + const cut = bytes.slice(); + + cut[cut.length - 36] ^= 1; // the footer no longer repeats the header + expect(() => parseBin(cut)).toThrow(); + for (const device of [null, "watch_pro_2", "watch_3_pro"]) + expect(() => assertFlashable(cut, device)).toThrow(/can't read this file/); +}); + +describe("what can't be measured is refused for a Watch 3 Pro, and only for it", () => { + const refused = (change: (main: FaceNode, face: Face) => void) => { + const face = parseBin(bytes); + + change( + face.screens.find((s) => s.tag === TAG.main)!, + face, + ); + const bin = buildBin(face); + + expect(() => assertFlashable(bin, "watch_3_pro")).toThrow(/can't measure/); + expect(() => assertFlashable(bin, "watch_pro_2")).not.toThrow(); + }; + + test("a shown image in an unknown colour format", () => + refused((main, face) => { + const [shown] = shownResources(main, face.resources); + + face.resources[shown] = { ...face.resources[shown], cf: 6 }; + })); + test("an image reference that leads to no resource", () => + refused((main) => { + main.subs!.push({ + tag: TAG.image, + subs: [{ tag: TAG.struct, x: 0, y: 0, meta: "00".repeat(14), tail: "010100ffffff7f" }], + }); + })); + test("a screen whose layers don't parse", () => + refused((main) => { + delete main.subs; + main.hex = "30ffff"; + })); + test("a layer whose contents don't parse", () => + refused((main) => { + main.subs!.push({ tag: TAG.group, hex: "30ffff" }); + })); +}); + +test("every factory face can be measured", () => { + const dir = new URL("./__fixtures__/", import.meta.url); + + for (const name of readdirSync(dir).filter((f) => f.endsWith(".bin"))) { + const bin = new Uint8Array(readFileSync(new URL(name, dir))); + + expect(() => assertFlashable(bin, "watch_3_pro"), name).not.toThrow(); + } +});