// SPDX-License-Identifier: MIT // Copyright (C) 2026 Pooya Parsa // Bluetooth for the guest: the controller behind its hci0 (vm.bluetooth, // js/core/bluetooth.ts). Every boot offers the guest kwbt (boot.ts passes // `bluetooth: true`; with no controller attached the guest has no hci0), and // once the machine runs the adapter chosen here is attached to it, to each // new machine again (a resumed session's included: its kernel drops the // hci0 it had). // - The adapter (Settings > Bluetooth, Settings.tsx; a // page preference, `kw.bt-adapter`, applied at once: the old controller // is detached, the guest's hci0 goes and the new one comes) is one of // ADAPTERS, each a kind of controller with what blocks it here, or Off. // One kind now: Browser Bluetooth, an emulated LE controller // (VirtualLeController, js/core/bluetooth-le.ts) over Web Bluetooth // (WebBluetoothCentral, js/web/bluetooth.ts), at a BD_ADDR made once per // browser profile (`kw.bt-address`). // - Add device… (the same section) opens the browser's chooser from the // click; the device picked is the guest's to scan for and connect to. // Forget drops it (device.forget()). Devices allowed before come back // where the browser has getDevices(). // - Web Bluetooth gives the page only the GATT services named when a device // is added: the SIG's standard ones and a few common vendor ones are built // in, and the section's custom service UUIDs (`kw.bt-uuids`) are added to // the next Add device. // - The guest starting a scan while no device is added gets a toast with an // Add Bluetooth device button, the same chooser (once in 20 s). // Where Web Bluetooth is missing (Firefox, Safari, an insecure context) no // controller is attached and the section says why. import { useSyncExternalStore } from "react"; import { KW } from "./kw.ts"; import { store } from "./prefs.ts"; import { VirtualLeController, WEB_BLUETOOTH_BLOCKLIST, WebBluetoothCentral, canonicalUuid, formatAddress, parseAddress, randomControllerAddress, webBluetooth, webBluetoothAvailable, webBluetoothBlocker, type BluetoothController, type BluetoothState, type GattDeviceInfo, type KernelHandle, type VirtualLeActivity, } from "./sdk.ts"; /** What the guest's hci0 is: one of ADAPTERS' kinds, or none. */ export type AdapterId = "off" | "browser"; /** A kind of controller for the guest. */ interface Adapter { id: Exclude; /** The choice's name in Settings. */ label: string; /** Why it cannot be used here, or undefined. */ blocker(): string | undefined; /** A controller for a machine (a new one for each). */ create(): BluetoothController; } const ADAPTERS: Adapter[] = [ { id: "browser", label: "Browser Bluetooth (BLE devices)", blocker: webBluetoothBlocker, create: () => new VirtualLeController({ central: browserCentral()!, address: localAddress(), label: "Browser Bluetooth", log: (m) => log(m) }), }, ]; const OFF_LABEL = "Off (no Bluetooth in the guest)"; export interface AdapterView { id: AdapterId; label: string; /** Why it cannot be used here, or null. */ why: string | null; } export interface BluetoothView { /** The adapter chosen (`kw.bt-adapter`), and the choices with what blocks each. */ adapter: AdapterId; adapters: AdapterView[]; /** Why no kind of adapter can be used here, or null. */ why: string | null; /** The browser sees no Bluetooth adapter (getAvailability() false). */ unavailable: boolean; /** The machine runs with kwbt. */ running: boolean; /** vm.bluetooth's state, null before the machine runs. */ state: BluetoothState | null; /** The attached controller's address, if it is ours. */ address: string | null; /** The guest scans, and the devices it has a link to (ids). */ scanning: boolean; connected: string[]; /** Browser Bluetooth's devices (added, or allowed before). */ devices: GattDeviceInfo[]; /** The custom service UUIDs as typed (`kw.bt-uuids`). */ uuids: string; } let vm: KernelHandle | undefined; let log: (msg: string) => void = (m) => console.warn(m); let central: WebBluetoothCentral | undefined; /** The controller this module attached to the running machine, and its activity's unsubscribe. */ let current: { id: AdapterId; ctl: BluetoothController; off: () => void } | undefined; let applying: Promise = Promise.resolve(); let unavailable = false; let wasScanning = false; let offered = 0; const listeners = new Set<() => void>(); let view: BluetoothView | undefined; let adapterViews: AdapterView[] | undefined; /** The choices, with what blocks each (checked once). */ function adapters(): AdapterView[] { adapterViews ??= [...ADAPTERS.map((a) => ({ id: a.id, label: a.label, why: a.blocker() ?? null })), { id: "off" as const, label: OFF_LABEL, why: null }]; return adapterViews; } /** The adapter chosen: the preference, else Browser Bluetooth. */ function choice(): AdapterId { const v = store("bt-adapter"); return v === "off" || ADAPTERS.some((a) => a.id === v) ? (v as AdapterId) : "browser"; } /** The guest's BD_ADDR: random, made once and kept (a new one each load where storage is refused). */ function localAddress(): string { const saved = store("bt-address"); if (saved) { try { parseAddress(saved); return saved; } catch {} } const a = formatAddress(randomControllerAddress()); store("bt-address", a); return a; } /** The custom service UUIDs as typed: the ones that parse (canonical), those that do not, and those Web Bluetooth blocks. */ export function parseUuids(text: string): { uuids: string[]; bad: string[]; blocked: string[] } { const uuids: string[] = [], bad: string[] = [], blocked: string[] = []; for (const t of text.split(/[\s,]+/)) { if (!t) continue; let u: string; try { u = canonicalUuid(t); } catch { bad.push(t); continue; } if (WEB_BLUETOOTH_BLOCKLIST.has(u)) blocked.push(t); else if (!uuids.includes(u)) uuids.push(u); } return { uuids, bad, blocked }; } /** Browser Bluetooth's central (one per page, kept across machines), or undefined without Web Bluetooth. */ function browserCentral(): WebBluetoothCentral | undefined { if (central || webBluetoothBlocker()) return central; central = new WebBluetoothCentral({ services: parseUuids(store("bt-uuids") ?? "").uuids, label: "Browser Bluetooth", log: (m) => log(m) }); central.onDevice(() => publish()); central.onRemove(() => publish()); void central.init().then(() => publish()); webBluetooth()?.addEventListener("availabilitychanged", (e) => { unavailable = (e as Event & { value?: boolean }).value === false; publish(); }); void webBluetoothAvailable().then((ok) => { unavailable = !ok; publish(); }); return central; } function compute(): BluetoothView { const bt = vm?.bluetooth; const ctl = current && bt?.controller === current.ctl ? current.ctl : undefined; const act: VirtualLeActivity = ctl instanceof VirtualLeController ? ctl.activity : { scanning: false, connected: [] }; const list = adapters(); const usable = list.some((a) => a.id !== "off" && !a.why); return { adapter: choice(), adapters: list, why: usable ? null : list.filter((a) => a.why).map((a) => a.why).join("; ") || null, unavailable, running: !!bt, state: bt ? bt.state : null, address: ctl instanceof VirtualLeController ? ctl.addressText : null, scanning: act.scanning, connected: act.connected, devices: central?.devices() ?? [], uuids: store("bt-uuids") ?? "", }; } let publishTimer: ReturnType | undefined; /** The view again, at most every 200 ms (advertisements come often while the guest scans). */ function publish(): void { publishTimer ??= setTimeout(() => { publishTimer = undefined; view = compute(); for (const l of listeners) l(); }, 200); } /** The guest's Bluetooth, for the Settings section. */ export function useBluetooth(): BluetoothView { return useSyncExternalStore((l) => { listeners.add(l); return () => listeners.delete(l); }, () => (view ??= compute())); } /** The guest started or stopped a scan, or a link came or went. */ function onActivity(a: VirtualLeActivity): void { // A scan with no device to find: offer the chooser where the user is (the button's click is the // gesture requestDevice() needs). Once in 20 s, and not while a device is added. if (a.scanning && !wasScanning) { const now = Date.now(); if (now - offered >= 20000 && central && !central.devices().length) { offered = now; KW.ui?.toast("A program is looking for Bluetooth devices", { action: "Add Bluetooth device", run: addBluetoothDevice, ms: 15000 }); } } wasScanning = a.scanning; publish(); } /** Attach the chosen adapter to the machine, after detaching what it has (one change at a time). */ function apply(): void { applying = applying.then(async () => { const bt = vm?.bluetooth; if (!bt) return; const want = choice(); if (current && current.id === want && bt.controller === current.ctl) return; current?.off(); current = undefined; wasScanning = false; if (bt.controller) await bt.detach(); const kind = ADAPTERS.find((a) => a.id === want); if (!kind || kind.blocker()) return; const ctl = kind.create(); const off = ctl instanceof VirtualLeController ? ctl.onActivity(onActivity) : () => {}; current = { id: want, ctl, off }; await bt.attach(ctl); log(`[bluetooth] ${ctl.label ?? kind.label}${ctl instanceof VirtualLeController ? ` (${ctl.addressText})` : ""} is the guest's hci0`); }).catch((e: unknown) => { log(`[bluetooth] ${(e as Error)?.message ?? e}`); }).finally(publish); } /** The machine runs: its hci0 follows vm.bluetooth, and the chosen adapter is attached. */ export function attachBluetooth(machine: KernelHandle, hostLog: (msg: string) => void): void { const bt = machine.bluetooth; if (!bt) return; vm = machine; log = hostLog; current?.off(); current = undefined; bt.onChange(() => publish()); void machine.exited.then(() => { if (vm !== machine) return; vm = undefined; current?.off(); current = undefined; publish(); }); apply(); } /** The adapter choice (Settings): kept, and applied to the running machine at once. */ export function setBluetoothAdapter(id: AdapterId): void { store("bt-adapter", id); publish(); apply(); } /** The custom service UUIDs (Settings): kept, and asked for at the next Add device. */ export function setBluetoothUuids(text: string): void { store("bt-uuids", text); if (central) central.services = parseUuids(text).uuids; publish(); } /** Add device…: the browser's chooser (call from the click itself); the device picked is the guest's to find. */ export function addBluetoothDevice(): void { const c = browserCentral(); if (!c) return; c.requestDevice().then((d) => { KW.ui?.toast(`${d.name || "The device"} is added: scan for it in the guest (bluetoothctl, then scan on)`); }, (e: unknown) => { // NotFoundError "User cancelled the requestDevice() chooser.": closed without a device. const err = e as Error | null; if (err?.name === "NotFoundError" && /cancel/i.test(err.message)) return; KW.ui?.toast(`Bluetooth: ${err?.message ?? e}`); }); } /** Forget: the device goes from the guest (a link to it drops) and from the browser's permissions. */ export async function forgetBluetoothDevice(id: string): Promise { await central?.forget(id); publish(); }