From b462fe08dd6444de8ca43d5495aabc9d2fdb1e96 Mon Sep 17 00:00:00 2001 From: Onyx Date: Fri, 20 Nov 2026 19:01:25 +0100 Subject: [PATCH 1/2] fix(bridge): reload the page once when the user allows the local network prompt On a first visit the page tries Bridge at once and the browser shows its local network permission prompt. The 1.5 second connect timeout expires while the user reads it, the page carries on without Bridge, and clicking Allow changed nothing until a manual reload. Watch the permission (trying the known permission names). When it changes from prompt or denied to granted and Bridge is still not active two seconds later, reload the page once per session. The state is also written to the Bridge log when Bridge cannot be reached. --- src/features/bridge/bridge-hid.ts | 3 + .../bridge/local-network-permission.test.ts | 85 +++++++++++++++++++ .../bridge/local-network-permission.ts | 56 ++++++++++++ src/main.tsx | 13 ++- 4 files changed, 156 insertions(+), 1 deletion(-) create mode 100644 src/features/bridge/local-network-permission.test.ts create mode 100644 src/features/bridge/local-network-permission.ts diff --git a/src/features/bridge/bridge-hid.ts b/src/features/bridge/bridge-hid.ts index 8ee7b024..119cf178 100644 --- a/src/features/bridge/bridge-hid.ts +++ b/src/features/bridge/bridge-hid.ts @@ -19,6 +19,7 @@ // Bridge to serve the app itself over loopback, which is a separate change. import { HID_FILTERS } from "../../device/hid-filters.ts"; +import { refreshLocalNetworkPermission } from "./local-network-permission.ts"; import { describeHidDevice, markHidActivity } from "../../device/hid-diagnostics.ts"; @@ -677,6 +678,8 @@ export async function installBridgeHid(options: { force?: boolean } = {}): Promi if (navigator.hid && !options.force) return true; const transport = await openSocket(BRIDGE_SOCKET_URL); if (!transport) { + const permission = await refreshLocalNetworkPermission(); + bridgeLog("warn", "bridge unreachable", { detail: { permission } }); setBridgeHidActive(false); return Boolean(navigator.hid); } diff --git a/src/features/bridge/local-network-permission.test.ts b/src/features/bridge/local-network-permission.test.ts new file mode 100644 index 00000000..f7db78af --- /dev/null +++ b/src/features/bridge/local-network-permission.test.ts @@ -0,0 +1,85 @@ +import assert from "node:assert/strict"; +import { afterEach, test } from "node:test"; + +import { + onLocalNetworkPermissionGranted, + refreshLocalNetworkPermission, + reloadOnceForBridge, +} from "./local-network-permission.ts"; + +const original = Object.getOwnPropertyDescriptor(globalThis, "navigator"); + +function stubNavigator(value: unknown): void { + Object.defineProperty(globalThis, "navigator", { value, configurable: true, writable: true }); +} + +afterEach(() => { + if (original) Object.defineProperty(globalThis, "navigator", original); + else delete (globalThis as { navigator?: unknown }).navigator; +}); + +test("reports the state of the first permission name the browser knows", async () => { + const asked: string[] = []; + stubNavigator({ + permissions: { + query: async ({ name }: { name: string }) => { + asked.push(name); + if (name === "loopback-network") throw new TypeError("unknown permission"); + return { state: "denied" }; + }, + }, + }); + assert.equal(await refreshLocalNetworkPermission(), "denied"); + assert.deepEqual(asked, ["loopback-network", "local-network-access"]); +}); + +test("passes granted and prompt through", async () => { + for (const state of ["granted", "prompt"]) { + stubNavigator({ permissions: { query: async () => ({ state }) } }); + assert.equal(await refreshLocalNetworkPermission(), state); + } +}); + +test("is unknown when no permission name can be queried or the API is missing", async () => { + stubNavigator({ permissions: { query: async () => { throw new TypeError("unknown permission"); } } }); + assert.equal(await refreshLocalNetworkPermission(), "unknown"); + stubNavigator({}); + assert.equal(await refreshLocalNetworkPermission(), "unknown"); +}); + +test("allowing the prompt fires the granted callback once, an already allowed page never does", async () => { + const status = { state: "prompt", onchange: null as null | (() => void) }; + stubNavigator({ permissions: { query: async () => status } }); + await refreshLocalNetworkPermission(); + let granted = 0; + const stop = onLocalNetworkPermissionGranted(() => void (granted += 1)); + status.state = "granted"; + status.onchange?.(); + status.onchange?.(); + assert.equal(granted, 1); + + const already = { state: "granted", onchange: null as null | (() => void) }; + stubNavigator({ permissions: { query: async () => already } }); + await refreshLocalNetworkPermission(); + already.onchange?.(); + assert.equal(granted, 1); + assert.equal(status.onchange, null, "the old status is released"); + stop(); +}); + +test("reloads for Bridge only once per session", () => { + const session = new Map(); + let reloads = 0; + const define = (name: string, value: unknown): void => { + Object.defineProperty(globalThis, name, { value, configurable: true, writable: true }); + }; + define("sessionStorage", { getItem: (k: string) => session.get(k) ?? null, setItem: (k: string, v: string) => void session.set(k, v) }); + define("location", { reload: () => void (reloads += 1) }); + reloadOnceForBridge(); + reloadOnceForBridge(); + assert.equal(reloads, 1); + define("sessionStorage", { getItem: () => { throw new Error("blocked"); }, setItem: () => { throw new Error("blocked"); } }); + reloadOnceForBridge(); + assert.equal(reloads, 1, "no reload when storage is unavailable, so it cannot loop"); + for (const name of ["sessionStorage", "location"]) delete (globalThis as Record)[name]; +}); diff --git a/src/features/bridge/local-network-permission.ts b/src/features/bridge/local-network-permission.ts new file mode 100644 index 00000000..47b4b6ee --- /dev/null +++ b/src/features/bridge/local-network-permission.ts @@ -0,0 +1,56 @@ +export type LocalNetworkPermission = "granted" | "prompt" | "denied" | "unknown"; + +const PERMISSION_NAMES = ["loopback-network", "local-network-access", "local-network"]; +const RELOAD_KEY = "openmouse.bridge-reloaded"; + +let current: LocalNetworkPermission = "unknown"; +let watched: PermissionStatus | null = null; +const grantedListeners = new Set<() => void>(); + +function watch(status: PermissionStatus): void { + if (watched === status) return; + if (watched) watched.onchange = null; + watched = status; + status.onchange = () => { + const before = current; + const after = status.state as LocalNetworkPermission; + if (after === before) return; + current = after; + if (after === "granted" && (before === "prompt" || before === "denied")) { + for (const listener of grantedListeners) listener(); + } + }; +} + +export function onLocalNetworkPermissionGranted(listener: () => void): () => void { + grantedListeners.add(listener); + return () => grantedListeners.delete(listener); +} + +export function reloadOnceForBridge(): void { + try { + if (sessionStorage.getItem(RELOAD_KEY)) return; + sessionStorage.setItem(RELOAD_KEY, "1"); + } catch { + return; + } + location.reload(); +} + +export async function refreshLocalNetworkPermission(): Promise { + let next: LocalNetworkPermission = "unknown"; + if (typeof navigator !== "undefined" && navigator.permissions?.query) { + for (const name of PERMISSION_NAMES) { + try { + const status = await navigator.permissions.query({ name } as unknown as PermissionDescriptor); + next = status.state; + watch(status); + break; + } catch { + continue; + } + } + } + current = next; + return current; +} diff --git a/src/main.tsx b/src/main.tsx index 7375a51e..a7508e5b 100644 --- a/src/main.tsx +++ b/src/main.tsx @@ -4,7 +4,12 @@ import "./platform/analytics"; import "./styles/index.css"; import { App } from "./app/App"; import { UnsupportedNotice } from "./app/UnsupportedNotice"; -import { installBridgeHid } from "./features/bridge/bridge-hid"; +import { installBridgeHid, isBridgeHidActive } from "./features/bridge/bridge-hid"; +import { + onLocalNetworkPermissionGranted, + refreshLocalNetworkPermission, + reloadOnceForBridge, +} from "./features/bridge/local-network-permission"; import { unsupportedNotice } from "./platform/browser-support"; import { start } from "./device/controller"; import { mountOfflineBanner } from "./platform/offline-banner"; @@ -51,6 +56,12 @@ const root = createRoot(controlApp); // Prefer Bridge when it is installed: native HID can reach protected mouse // collections that Chrome 153+ correctly withholds from WebHID. If Bridge is // absent, installation falls back to the browser's own WebHID implementation. +onLocalNetworkPermissionGranted(() => { + setTimeout(() => { + if (!isBridgeHidActive()) reloadOnceForBridge(); + }, 2000); +}); +void refreshLocalNetworkPermission(); void installBridgeHid({ force: true }).then(async (hasHid) => { await ensureDisplayLocale(initialUiLocale()); const notice = unsupportedNotice({ From 8dbb9c1ac109a09d37373a8317c912910b07a994 Mon Sep 17 00:00:00 2001 From: Snekxs <26660858+snekxs@users.noreply.github.com> Date: Sat, 21 Nov 2026 01:21:23 -0600 Subject: [PATCH 2/2] fix(bridge): fire a permission grant from one place and keep the shim flag with its owner - Record query and change-event observations through one transition, so a refresh that sees the grant reloads instead of being overwritten by the later event. - Clear the Bridge active flag only when no shim is installed, so an earlier failed attempt resuming after the permission query cannot report a newer install off. - Cover both races with tests. --- src/features/bridge/bridge-hid.test.ts | 53 ++++++++++++++++++- src/features/bridge/bridge-hid.ts | 15 ++++-- .../bridge/local-network-permission.test.ts | 14 +++++ .../bridge/local-network-permission.ts | 28 ++++++---- 4 files changed, 95 insertions(+), 15 deletions(-) diff --git a/src/features/bridge/bridge-hid.test.ts b/src/features/bridge/bridge-hid.test.ts index 52e4b41e..abc4c854 100644 --- a/src/features/bridge/bridge-hid.test.ts +++ b/src/features/bridge/bridge-hid.test.ts @@ -1,7 +1,7 @@ import assert from "node:assert/strict"; import { test } from "node:test"; -import { bridgeEmptyResultMessage, bridgeHid, type BridgeTransport } from "./bridge-hid.ts"; +import { bridgeEmptyResultMessage, bridgeHid, installBridgeHid, isBridgeHidActive, type BridgeTransport } from "./bridge-hid.ts"; interface Fake { transport: BridgeTransport; @@ -183,3 +183,54 @@ test("an empty Bridge result with known devices names the VID/PID", () => { assert.match(message, /Pulsar X2/); assert.match(message, /VID/); }); + +test("a failed install does not clear the flag of a newer install", async () => { + const sockets: FakeSocket[] = []; + class FakeSocket extends EventTarget { + constructor() { + super(); + sockets.push(this); + } + send(): void {} + close(): void {} + emit(type: string, props: Record = {}): void { + this.dispatchEvent(Object.assign(new Event(type), props)); + } + } + const originalWebSocket = Object.getOwnPropertyDescriptor(globalThis, "WebSocket"); + const originalNavigator = Object.getOwnPropertyDescriptor(globalThis, "navigator"); + const queried = Promise.withResolvers(); + const permission = Promise.withResolvers<{ state: string }>(); + const nav = { + permissions: { + query: () => { + queried.resolve(); + return permission.promise; + }, + }, + }; + Object.defineProperty(globalThis, "WebSocket", { value: FakeSocket, configurable: true, writable: true }); + Object.defineProperty(globalThis, "navigator", { value: nav, configurable: true, writable: true }); + try { + const failing = installBridgeHid({ force: true }); + sockets[0].emit("error"); + await queried.promise; + + const succeeding = installBridgeHid({ force: true }); + sockets[1].emit("open"); + assert.equal(await succeeding, true); + assert.equal(isBridgeHidActive(), true); + + permission.resolve({ state: "prompt" }); + assert.equal(await failing, true); + assert.equal(isBridgeHidActive(), true, "the earlier failure must not report the newer shim off"); + + sockets[1].emit("close", { code: 1000, reason: "" }); + assert.equal(isBridgeHidActive(), false); + } finally { + if (originalWebSocket) Object.defineProperty(globalThis, "WebSocket", originalWebSocket); + else Reflect.deleteProperty(globalThis, "WebSocket"); + if (originalNavigator) Object.defineProperty(globalThis, "navigator", originalNavigator); + else Reflect.deleteProperty(globalThis, "navigator"); + } +}); diff --git a/src/features/bridge/bridge-hid.ts b/src/features/bridge/bridge-hid.ts index 119cf178..713b674a 100644 --- a/src/features/bridge/bridge-hid.ts +++ b/src/features/bridge/bridge-hid.ts @@ -531,6 +531,7 @@ export function bridgeHid(transport: BridgeTransport, onDisconnect?: () => void) // "disconnected" the instant Bridge's process goes away, without polling // bridgeStatus() itself just to answer "is it there". let bridgeHidActive = false; +let installedShim: HID | null = null; const bridgeHidActiveListeners = new Set<(active: boolean) => void>(); function setBridgeHidActive(active: boolean): void { @@ -680,15 +681,21 @@ export async function installBridgeHid(options: { force?: boolean } = {}): Promi if (!transport) { const permission = await refreshLocalNetworkPermission(); bridgeLog("warn", "bridge unreachable", { detail: { permission } }); - setBridgeHidActive(false); + // A newer attempt can install its shim while the permission query is in + // flight. This attempt owns nothing then, so it must not report Bridge off. + if (!installedShim) setBridgeHidActive(false); return Boolean(navigator.hid); } - // Only a disconnect from the currently installed shim clears the flag, so - // a superseded socket closing late cannot deactivate its replacement. + // Only the shim that is still `navigator.hid` clears the flag, so a + // superseded socket closing late cannot deactivate its replacement. const shim = bridgeHid(transport, () => { - if (typeof navigator !== "undefined" && navigator.hid === shim) setBridgeHidActive(false); + if (typeof navigator !== "undefined" && navigator.hid === shim) { + installedShim = null; + setBridgeHidActive(false); + } }); Object.defineProperty(navigator, "hid", { value: shim, configurable: true }); + installedShim = shim; setBridgeHidActive(true); return true; } diff --git a/src/features/bridge/local-network-permission.test.ts b/src/features/bridge/local-network-permission.test.ts index f7db78af..b5f8a2a9 100644 --- a/src/features/bridge/local-network-permission.test.ts +++ b/src/features/bridge/local-network-permission.test.ts @@ -67,6 +67,20 @@ test("allowing the prompt fires the granted callback once, an already allowed pa stop(); }); +test("a refresh that observes the grant fires the callback once", async () => { + const status = { state: "prompt", onchange: null as null | (() => void) }; + stubNavigator({ permissions: { query: async () => status } }); + await refreshLocalNetworkPermission(); + let granted = 0; + const stop = onLocalNetworkPermissionGranted(() => void (granted += 1)); + status.state = "granted"; + await refreshLocalNetworkPermission(); + assert.equal(granted, 1); + await refreshLocalNetworkPermission(); + assert.equal(granted, 1, "seeing granted again is not a new grant"); + stop(); +}); + test("reloads for Bridge only once per session", () => { const session = new Map(); let reloads = 0; diff --git a/src/features/bridge/local-network-permission.ts b/src/features/bridge/local-network-permission.ts index 47b4b6ee..85b3fe24 100644 --- a/src/features/bridge/local-network-permission.ts +++ b/src/features/bridge/local-network-permission.ts @@ -7,19 +7,27 @@ let current: LocalNetworkPermission = "unknown"; let watched: PermissionStatus | null = null; const grantedListeners = new Set<() => void>(); +/** + * Records an observation, from either the query or the change event, so both + * paths agree on when a grant is new. Only `prompt` or `denied` becoming + * `granted` counts: the page's first look at an already granted site is + * `unknown` → `granted` and must stay silent, and seeing `granted` again is + * not a new grant. The change event can arrive after a refresh already + * recorded the same result, so both go through here. + */ +function transition(next: LocalNetworkPermission): void { + const before = current; + current = next; + if (next === "granted" && (before === "prompt" || before === "denied")) { + for (const listener of grantedListeners) listener(); + } +} + function watch(status: PermissionStatus): void { if (watched === status) return; if (watched) watched.onchange = null; watched = status; - status.onchange = () => { - const before = current; - const after = status.state as LocalNetworkPermission; - if (after === before) return; - current = after; - if (after === "granted" && (before === "prompt" || before === "denied")) { - for (const listener of grantedListeners) listener(); - } - }; + status.onchange = () => transition(status.state as LocalNetworkPermission); } export function onLocalNetworkPermissionGranted(listener: () => void): () => void { @@ -51,6 +59,6 @@ export async function refreshLocalNetworkPermission(): Promise