From f6926f4c6d2dbbf1186bb75f77d8abff7977b277 Mon Sep 17 00:00:00 2001 From: snekxs <26660858+snekxs@users.noreply.github.com> Date: Tue, 17 Nov 2026 14:07:20 -0600 Subject: [PATCH 1/3] fix(native-hid): Bridge reads the Keychron battery itself, before OpenMouse connects brands.mjs pointed Keychron at drivers/keychron/hid (KeychronHidClient), which mouse-protocol no longer has: it was split into the 8K, 1K, 4K, 8K Nordic and Nape clients. Every native read failed with "Cannot find module", so a Keychron mouse only got a battery once the web panel reported one. The entry now lists the five clients in registry order. The TurboLink 8K receiver also answers Keychron8kHidClient on three interfaces, and only the 0xffc1 one reports the battery. The helper took the first answer, so it would still have shown none. select-client.mjs now prefers an answer with a battery and falls back to the first answer when none has one, as for a wired mouse. A test checks that every driver class brands.mjs names exists in the protocol package, so a future rename fails the tests instead of quietly stopping battery reads. --- native-hid/src/apply.mjs | 20 ++----- native-hid/src/brands.mjs | 8 ++- native-hid/src/select-client.mjs | 50 ++++++++++++++++ native-hid/src/select-client.test.mjs | 82 +++++++++++++++++++++++++++ 4 files changed, 144 insertions(+), 16 deletions(-) create mode 100644 native-hid/src/select-client.mjs create mode 100644 native-hid/src/select-client.test.mjs diff --git a/native-hid/src/apply.mjs b/native-hid/src/apply.mjs index 199e22ac..c2f53ee4 100644 --- a/native-hid/src/apply.mjs +++ b/native-hid/src/apply.mjs @@ -40,6 +40,7 @@ globalThis.window ??= globalThis; import { BRAND_DRIVERS, brandKey } from "./brands.mjs"; import { applyX11PollingRate, x11DeviceInfos } from "./attack-shark-x11.mjs"; import { candidateDevices, probeVerifiedDevice } from "./hid-device-adapter.mjs"; +import { selectClient } from "./select-client.mjs"; import { devices } from "node-hid"; import { automate } from "./automation.mjs"; @@ -115,21 +116,10 @@ async function main() { } } - const attempts = []; - let client = null; - let status = null; - outer: for (const vendorId of entry.vendorIds) { - for (const device of candidateDevices(vendorId, entry)) { - for (const candidate of entry.classes) { - try { - ({ client, status } = await probe(device, candidate)); - break outer; - } catch (error) { - attempts.push(`${candidate.exportName} on ${device.productName || "unknown device"}: ${error.message}`); - } - } - } - } + const pairs = entry.vendorIds.flatMap((vendorId) => + candidateDevices(vendorId, entry).flatMap((device) => entry.classes.map((candidate) => ({ device, candidate }))), + ); + const { client, status, attempts } = await selectClient(pairs, probe); if (!client) { console.error( diff --git a/native-hid/src/brands.mjs b/native-hid/src/brands.mjs index 80a1fef5..56b8f7e3 100644 --- a/native-hid/src/brands.mjs +++ b/native-hid/src/brands.mjs @@ -119,7 +119,13 @@ export const BRAND_DRIVERS = { }, keychron: { vendorIds: [0x3434], - classes: [client("@openmouse/protocol/drivers/keychron/hid", "KeychronHidClient")], + classes: [ + client("@openmouse/protocol/drivers/keychron/mouse-8k-hid", "Keychron8kHidClient"), + client("@openmouse/protocol/drivers/keychron/mouse-1k-hid", "Keychron1kHidClient"), + client("@openmouse/protocol/drivers/keychron/mouse-4k-hid", "Keychron4kHidClient"), + client("@openmouse/protocol/drivers/keychron/mouse-8k-nordic-hid", "Keychron8kNordicHidClient"), + client("@openmouse/protocol/drivers/keychron/nape-hid", "KeychronNapeHidClient"), + ], }, fantech: { vendorIds: [0x3151], diff --git a/native-hid/src/select-client.mjs b/native-hid/src/select-client.mjs new file mode 100644 index 00000000..1a715fe1 --- /dev/null +++ b/native-hid/src/select-client.mjs @@ -0,0 +1,50 @@ +// Picks which interface and driver class of a brand to talk to. +// +// A receiver can expose several interfaces that a driver class opens and +// reads without error, but only one of them carries the mouse's battery: the +// Keychron TurboLink 8K answers Keychron8kHidClient on its consumer, vendor +// 0xffc1 and 0x8c interfaces, and only 0xffc1 reports the G6 HE 8K's battery. +// Taking the first answer would report no battery at all, so an answer with a +// battery wins, and the first answer is only used when none has one (a wired +// mouse, for instance). +// +// A battery-less answer is closed before probing on rather than held open: +// some receivers stop answering on one collection while a sibling is read +// (see candidateDevices()), so it is probed again if it ends up the pick. + +/** + * @param {Array<{ device: object, candidate: object }>} pairs - every + * (interface, driver class) combination, in preference order. + * @param {(device: object, candidate: object) => Promise<{ client: object, status: object }>} probe + * opens and reads one pair; rejects (and leaves the device closed) on failure. + * @returns {Promise<{ client: object | null, status: object | null, attempts: string[] }>} + */ +export async function selectClient(pairs, probe) { + const attempts = []; + let fallback = null; + for (const { device, candidate } of pairs) { + let found; + try { + found = await probe(device, candidate); + } catch (error) { + attempts.push(`${candidate.exportName} on ${device.productName || "unknown device"}: ${error.message}`); + continue; + } + if (hasBattery(found.status)) return { ...found, attempts }; + fallback ??= { device, candidate }; + await found.client.close?.().catch(() => undefined); + await device.close?.().catch(() => undefined); + } + if (fallback) { + try { + return { ...(await probe(fallback.device, fallback.candidate)), attempts }; + } catch (error) { + attempts.push(`${fallback.candidate.exportName} on ${fallback.device.productName || "unknown device"}: ${error.message}`); + } + } + return { client: null, status: null, attempts }; +} + +function hasBattery(status) { + return typeof status?.batteryPercent === "number" && Number.isFinite(status.batteryPercent); +} diff --git a/native-hid/src/select-client.test.mjs b/native-hid/src/select-client.test.mjs new file mode 100644 index 00000000..451bc0c1 --- /dev/null +++ b/native-hid/src/select-client.test.mjs @@ -0,0 +1,82 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; + +import { selectClient } from "./select-client.mjs"; +import { BRAND_DRIVERS } from "./brands.mjs"; + +function fakeDevice(name) { + return { productName: name, closed: 0, close: async function () { this.closed += 1; } }; +} + +const candidate = (exportName) => ({ exportName }); + +/** A probe that answers from `replies`, keyed by device name. */ +function probeFrom(replies, log = []) { + return async (device, which) => { + log.push(device.productName); + const reply = replies[device.productName]; + if (reply instanceof Error) throw reply; + return { client: { close: async () => undefined, which }, status: reply }; + }; +} + +test("an interface with a battery wins over an earlier one without", async () => { + const consumer = fakeDevice("consumer"); + const vendor = fakeDevice("vendor"); + const result = await selectClient( + [ + { device: consumer, candidate: candidate("A") }, + { device: vendor, candidate: candidate("A") }, + ], + probeFrom({ consumer: { batteryPercent: null }, vendor: { batteryPercent: 22 } }), + ); + assert.equal(result.status.batteryPercent, 22); + // The battery-less interface was let go before the next one was read. + assert.equal(consumer.closed, 1); +}); + +test("the first answer is used when no interface reports a battery", async () => { + const log = []; + const result = await selectClient( + [ + { device: fakeDevice("first"), candidate: candidate("A") }, + { device: fakeDevice("second"), candidate: candidate("A") }, + ], + probeFrom({ first: { batteryPercent: null, dpi: 800 }, second: { batteryPercent: null, dpi: 1600 } }, log), + ); + assert.equal(result.status.dpi, 800); + // Probed again after the others, since it was closed in between. + assert.deepEqual(log, ["first", "second", "first"]); +}); + +test("a battery answer stops the search", async () => { + const log = []; + await selectClient( + [ + { device: fakeDevice("first"), candidate: candidate("A") }, + { device: fakeDevice("second"), candidate: candidate("A") }, + ], + probeFrom({ first: { batteryPercent: 50 }, second: { batteryPercent: 60 } }, log), + ); + assert.deepEqual(log, ["first"]); +}); + +test("failures are reported when nothing answers", async () => { + const result = await selectClient( + [{ device: fakeDevice("only"), candidate: candidate("A") }], + probeFrom({ only: new Error("no reply") }), + ); + assert.equal(result.client, null); + assert.deepEqual(result.attempts, ["A on only: no reply"]); +}); + +test("every driver class a brand names exists in the protocol package", async () => { + // Some driver modules touch `window` when loaded, as apply.mjs allows for. + globalThis.window ??= globalThis; + for (const [brand, entry] of Object.entries(BRAND_DRIVERS)) { + for (const { module, exportName } of entry.classes) { + const loaded = await import(module); + assert.equal(typeof loaded[exportName], "function", `${brand}: ${module} has no ${exportName}`); + } + } +}); From 1923f1cdee1d1470115ee8230e9ec9e90c52a991 Mon Sep 17 00:00:00 2001 From: snekxs <26660858+snekxs@users.noreply.github.com> Date: Tue, 17 Nov 2026 14:09:01 -0600 Subject: [PATCH 2/3] fix(native-hid): only retry the class that answered when looking for a battery After an answer without a battery, the helper tried every remaining class on every interface. Each failed probe can wait out its 3 s timeout, so a wired mouse of a brand with several classes (Razer has five) could run past Bridge's 10 s limit on the helper and lose a DPI read that works today. Only the class that answered is now tried on the other interfaces, which is all the Keychron receiver needs. --- native-hid/src/select-client.mjs | 6 ++++++ native-hid/src/select-client.test.mjs | 21 +++++++++++++++++++++ 2 files changed, 27 insertions(+) diff --git a/native-hid/src/select-client.mjs b/native-hid/src/select-client.mjs index 1a715fe1..a94df49e 100644 --- a/native-hid/src/select-client.mjs +++ b/native-hid/src/select-client.mjs @@ -8,6 +8,11 @@ // battery wins, and the first answer is only used when none has one (a wired // mouse, for instance). // +// Once a class has answered, only that class is tried on the remaining +// interfaces: the class is known to fit the device, and trying every other +// class on every interface could take long enough (each failed probe may +// wait out its timeout) to run past Bridge's limit on the helper. +// // A battery-less answer is closed before probing on rather than held open: // some receivers stop answering on one collection while a sibling is read // (see candidateDevices()), so it is probed again if it ends up the pick. @@ -23,6 +28,7 @@ export async function selectClient(pairs, probe) { const attempts = []; let fallback = null; for (const { device, candidate } of pairs) { + if (fallback && (candidate.exportName !== fallback.candidate.exportName || device === fallback.device)) continue; let found; try { found = await probe(device, candidate); diff --git a/native-hid/src/select-client.test.mjs b/native-hid/src/select-client.test.mjs index 451bc0c1..13020177 100644 --- a/native-hid/src/select-client.test.mjs +++ b/native-hid/src/select-client.test.mjs @@ -49,6 +49,27 @@ test("the first answer is used when no interface reports a battery", async () => assert.deepEqual(log, ["first", "second", "first"]); }); +test("after a battery-less answer only that class is tried on other interfaces", async () => { + const tried = []; + const first = fakeDevice("first"); + const second = fakeDevice("second"); + const [a, b] = [candidate("A"), candidate("B")]; + const result = await selectClient( + [ + { device: first, candidate: a }, + { device: first, candidate: b }, + { device: second, candidate: b }, + { device: second, candidate: a }, + ], + async (device, which) => { + tried.push(`${which.exportName}@${device.productName}`); + return { client: { close: async () => undefined }, status: { batteryPercent: device === second ? 40 : null } }; + }, + ); + assert.equal(result.status.batteryPercent, 40); + assert.deepEqual(tried, ["A@first", "A@second"]); +}); + test("a battery answer stops the search", async () => { const log = []; await selectClient( From 4b74465488e2f355b92a5ecfa8a24cac2655eb64 Mon Sep 17 00:00:00 2001 From: snekxs <26660858+snekxs@users.noreply.github.com> Date: Tue, 17 Nov 2026 15:27:57 -0600 Subject: [PATCH 3/3] fix(native-hid): keep settings writes on the first mouse, and bound the battery search Preferring an answer with a battery also chose the target of DPI and polling-rate writes, so with two mice of one brand connected a profile could be applied to the second because it reported a battery. Only status reads prefer a battery now; writes take the first mouse that answers, as before. The battery search had no bound of its own, so stalled sibling interfaces could run a read past Bridge's 10 s limit on the helper. It now stops 4 s after the first battery-less answer, whose status is kept instead of being read a second time. --- native-hid/src/apply.mjs | 2 +- native-hid/src/select-client.mjs | 61 ++++++++++++++++++--------- native-hid/src/select-client.test.mjs | 46 ++++++++++++++++++-- 3 files changed, 85 insertions(+), 24 deletions(-) diff --git a/native-hid/src/apply.mjs b/native-hid/src/apply.mjs index c2f53ee4..fbe90052 100644 --- a/native-hid/src/apply.mjs +++ b/native-hid/src/apply.mjs @@ -119,7 +119,7 @@ async function main() { const pairs = entry.vendorIds.flatMap((vendorId) => candidateDevices(vendorId, entry).flatMap((device) => entry.classes.map((candidate) => ({ device, candidate }))), ); - const { client, status, attempts } = await selectClient(pairs, probe); + const { client, status, attempts } = await selectClient(pairs, probe, { preferBattery: input.action === "status" }); if (!client) { console.error( diff --git a/native-hid/src/select-client.mjs b/native-hid/src/select-client.mjs index a94df49e..c3db9536 100644 --- a/native-hid/src/select-client.mjs +++ b/native-hid/src/select-client.mjs @@ -1,56 +1,77 @@ // Picks which interface and driver class of a brand to talk to. // -// A receiver can expose several interfaces that a driver class opens and -// reads without error, but only one of them carries the mouse's battery: the -// Keychron TurboLink 8K answers Keychron8kHidClient on its consumer, vendor -// 0xffc1 and 0x8c interfaces, and only 0xffc1 reports the G6 HE 8K's battery. -// Taking the first answer would report no battery at all, so an answer with a -// battery wins, and the first answer is only used when none has one (a wired -// mouse, for instance). +// Settings writes take the first pair that answers, so a request always +// changes the same mouse it always did. +// +// A status read prefers an answer with a battery. A receiver can expose +// several interfaces that a driver class opens and reads without error, but +// only one of them carries the mouse's battery: the Keychron TurboLink 8K +// answers Keychron8kHidClient on its consumer, vendor 0xffc1 and 0x8c +// interfaces, and only 0xffc1 reports the G6 HE 8K's battery. Taking the first +// answer would report no battery at all, so an answer with a battery wins, and +// the first answer's status is used when none has one (a wired mouse, for +// instance). // // Once a class has answered, only that class is tried on the remaining // interfaces: the class is known to fit the device, and trying every other // class on every interface could take long enough (each failed probe may -// wait out its timeout) to run past Bridge's limit on the helper. +// wait out its timeout) to run past Bridge's limit on the helper. That +// search also has a budget of its own, so stalled sibling interfaces cannot +// hold up a read whose status is already in hand. // // A battery-less answer is closed before probing on rather than held open: // some receivers stop answering on one collection while a sibling is read -// (see candidateDevices()), so it is probed again if it ends up the pick. +// (see candidateDevices()). Its status is kept, so it is never read twice. + +/** How long a status read keeps looking for a battery after a first answer + * without one. Bridge stops the helper after 10 s. */ +const BATTERY_SEARCH_MS = 4000; /** * @param {Array<{ device: object, candidate: object }>} pairs - every * (interface, driver class) combination, in preference order. * @param {(device: object, candidate: object) => Promise<{ client: object, status: object }>} probe * opens and reads one pair; rejects (and leaves the device closed) on failure. + * @param {{ preferBattery?: boolean, batterySearchMs?: number }} [options] - + * `preferBattery` for status reads only: the returned client may then be + * closed already, and only its status is to be used. * @returns {Promise<{ client: object | null, status: object | null, attempts: string[] }>} */ -export async function selectClient(pairs, probe) { +export async function selectClient(pairs, probe, { preferBattery = false, batterySearchMs = BATTERY_SEARCH_MS } = {}) { const attempts = []; let fallback = null; + let deadline = Infinity; for (const { device, candidate } of pairs) { if (fallback && (candidate.exportName !== fallback.candidate.exportName || device === fallback.device)) continue; + const remaining = deadline - Date.now(); + if (remaining <= 0) break; let found; try { - found = await probe(device, candidate); + found = await (fallback ? within(probe(device, candidate), remaining) : probe(device, candidate)); } catch (error) { attempts.push(`${candidate.exportName} on ${device.productName || "unknown device"}: ${error.message}`); continue; } - if (hasBattery(found.status)) return { ...found, attempts }; - fallback ??= { device, candidate }; + if (!preferBattery || hasBattery(found.status)) return { ...found, attempts }; + if (!fallback) { + fallback = { device, candidate, ...found }; + deadline = Date.now() + batterySearchMs; + } await found.client.close?.().catch(() => undefined); await device.close?.().catch(() => undefined); } - if (fallback) { - try { - return { ...(await probe(fallback.device, fallback.candidate)), attempts }; - } catch (error) { - attempts.push(`${fallback.candidate.exportName} on ${fallback.device.productName || "unknown device"}: ${error.message}`); - } - } + if (fallback) return { client: fallback.client, status: fallback.status, attempts }; return { client: null, status: null, attempts }; } +function within(promise, ms) { + let timer; + const timeout = new Promise((_resolve, reject) => { + timer = setTimeout(() => reject(new Error(`no answer within the ${ms} ms left for a battery search`)), ms); + }); + return Promise.race([promise, timeout]).finally(() => clearTimeout(timer)); +} + function hasBattery(status) { return typeof status?.batteryPercent === "number" && Number.isFinite(status.batteryPercent); } diff --git a/native-hid/src/select-client.test.mjs b/native-hid/src/select-client.test.mjs index 13020177..38202d1a 100644 --- a/native-hid/src/select-client.test.mjs +++ b/native-hid/src/select-client.test.mjs @@ -9,6 +9,8 @@ function fakeDevice(name) { } const candidate = (exportName) => ({ exportName }); +const status = { preferBattery: true }; + /** A probe that answers from `replies`, keyed by device name. */ function probeFrom(replies, log = []) { @@ -29,13 +31,14 @@ test("an interface with a battery wins over an earlier one without", async () => { device: vendor, candidate: candidate("A") }, ], probeFrom({ consumer: { batteryPercent: null }, vendor: { batteryPercent: 22 } }), + status, ); assert.equal(result.status.batteryPercent, 22); // The battery-less interface was let go before the next one was read. assert.equal(consumer.closed, 1); }); -test("the first answer is used when no interface reports a battery", async () => { +test("the first answer's status is used when no interface reports a battery", async () => { const log = []; const result = await selectClient( [ @@ -43,10 +46,45 @@ test("the first answer is used when no interface reports a battery", async () => { device: fakeDevice("second"), candidate: candidate("A") }, ], probeFrom({ first: { batteryPercent: null, dpi: 800 }, second: { batteryPercent: null, dpi: 1600 } }, log), + status, + ); + assert.equal(result.status.dpi, 800); + // Its status was kept, so it is not read a second time. + assert.deepEqual(log, ["first", "second"]); +}); + +test("settings writes take the first mouse that answers, battery or not", async () => { + const log = []; + const result = await selectClient( + [ + { device: fakeDevice("first"), candidate: candidate("A") }, + { device: fakeDevice("second"), candidate: candidate("A") }, + ], + probeFrom({ first: { batteryPercent: null, dpi: 800 }, second: { batteryPercent: 60, dpi: 1600 } }, log), + ); + assert.equal(result.status.dpi, 800); + assert.deepEqual(log, ["first"]); +}); + +test("the battery search stops at its budget when a sibling interface stalls", async () => { + const started = Date.now(); + const result = await selectClient( + [ + { device: fakeDevice("first"), candidate: candidate("A") }, + { device: fakeDevice("stalled"), candidate: candidate("A") }, + { device: fakeDevice("never"), candidate: candidate("A") }, + ], + async (device) => { + if (device.productName === "stalled") return new Promise(() => {}); + if (device.productName === "never") throw new Error("must not be reached"); + return { client: { close: async () => undefined }, status: { batteryPercent: null, dpi: 800 } }; + }, + { preferBattery: true, batterySearchMs: 50 }, ); + assert.ok(Date.now() - started < 1000); assert.equal(result.status.dpi, 800); - // Probed again after the others, since it was closed in between. - assert.deepEqual(log, ["first", "second", "first"]); + assert.match(result.attempts[0], /^A on stalled: no answer within/); + assert.equal(result.attempts.length, 1); }); test("after a battery-less answer only that class is tried on other interfaces", async () => { @@ -65,6 +103,7 @@ test("after a battery-less answer only that class is tried on other interfaces", tried.push(`${which.exportName}@${device.productName}`); return { client: { close: async () => undefined }, status: { batteryPercent: device === second ? 40 : null } }; }, + status, ); assert.equal(result.status.batteryPercent, 40); assert.deepEqual(tried, ["A@first", "A@second"]); @@ -78,6 +117,7 @@ test("a battery answer stops the search", async () => { { device: fakeDevice("second"), candidate: candidate("A") }, ], probeFrom({ first: { batteryPercent: 50 }, second: { batteryPercent: 60 } }, log), + status, ); assert.deepEqual(log, ["first"]); });