Something went wrong. Try again.
An experimental port of NetBSD, FreeBSD, OpenBSD, and XNU to unkernel unkernel.dev
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194// SPDX-License-Identifier: MIT// Copyright (C) 2026 Pooya Parsa <pooya@pi0.io>// The Bluetooth applet (#tb-bt, its panel #tb-bt-panel): the guest's hci0// and Browser Bluetooth's devices (bluetooth.ts; Settings, Bluetooth, has// the same plus the help text and the custom service UUIDs).// - The item: the rune, dim while the adapter is off or the system does not// run, with the count of devices the guest has a link to; red when the// controller could not be attached. Hidden where no kind of adapter can// be used (no Web Bluetooth: v.why), where the browser sees no Bluetooth// adapter on the computer (v.unavailable), and under sm.// - The panel: the state as the pill (Off, Not running, No adapter, Error,// Attaching, N connected, Scanning, On), then a row "Bluetooth" with a// switch (#tb-bt-power, role switch; the whole row toggles it, at once,// and the panel stays): off is setBluetoothAdapter("off"), on the adapter// used last this load, else the first one usable here.// - Off: a one-line hint, nothing else (no devices, no footer action).// - On: the adapter behind hci0 (bluetooth.ts ADAPTERS, without Off): its// name while there is one kind, a select (#tb-bt-adapter) once there are// more; a short status line (hci0's address, powered, scanning, or why// it is not attached); then each device added (#tb-bt-dev-<id>, the id// made safe) with its name, the address the guest sees it at and whether// it is connected or in range, and its actions: Terminal// (#tb-bt-dev-<id>-term, an icon: bluetoothctl on it in the Bluetooth// app; the panel closes) and Forget (#tb-bt-dev-<id>-forget: from the// guest and the site's permissions; the panel stays); with none, a line// on what to add. The footer's action is Add device… (#tb-bt-add,// disabled until the system runs): the browser's chooser from the click// itself (addBluetoothDevice()); the panel stays open, so the device// shows up in it (closed meanwhile, as one opened by hover may be, the// device is added all the same and the toast says so).// - The header's Monitor button is the kernel log, where bluetooth.ts logs the// adapter attached.import type { KeyboardEvent } from "react";import { addBluetoothDevice, forgetBluetoothDevice, setBluetoothAdapter, useBluetooth, type AdapterId, type AdapterView, type BluetoothView } from "../../bluetooth.ts";import { launch } from "../../launcher.ts";import { bluetoothShell } from "../../apps/tools/bluetooth.ts";import { deviceAddress, formatAddress, type GattDeviceInfo } from "../../sdk.ts";import type { PopoverProps } from "../ControlCenter.tsx";import { BluetoothIcon, PromptIcon } from "../icons.tsx";import { AppletButton, AppletPanel, ICON, type AppletItemProps, type AppletTone } from "./Applet.tsx";import { Count, DeviceList, DeviceRow, Empty, RowButton, RowIcon, idPart, keepFocus, type DeviceTone } from "./Devices.tsx";
const ID = "bt";
/** The adapter used last this load (the switch turns it on again). */let lastOn: Exclude<AdapterId, "off"> | undefined;
/** The kinds of adapter, without Off. */const kinds = (v: BluetoothView) => v.adapters.filter((a): a is AdapterView & { id: Exclude<AdapterId, "off"> } => a.id !== "off");
/** What the switch turns on: the adapter used last, else the first usable here, else Browser Bluetooth. */function onChoice(v: BluetoothView): Exclude<AdapterId, "off"> { const usable = kinds(v).filter((a) => !a.why); return usable.find((a) => a.id === lastOn)?.id ?? usable[0]?.id ?? "browser";}
/** The adapter chosen can be used here (it is not Off, and nothing blocks it). */const adapterOn = (v: BluetoothView) => v.adapter !== "off" && !v.adapters.find((a) => a.id === v.adapter)?.why;
/** The applet's state: the pill's word and tone, and a one-line summary (the item's tooltip). */function summary(v: BluetoothView): { word: string; tone: AppletTone; line: string } { if (v.adapter === "off") return { word: "Off", tone: "off", line: "Bluetooth: off" }; if (!adapterOn(v)) return { word: "Unavailable", tone: "warn", line: "Bluetooth: the adapter chosen cannot be used here" }; if (!v.running || !v.state) return { word: "Not running", tone: "pending", line: "Bluetooth: once the system runs" }; if (v.unavailable) return { word: "No adapter", tone: "warn", line: "Bluetooth: the browser sees no Bluetooth adapter on this computer, or it is off" }; if (!v.state.attached) return v.state.error ? { word: "Error", tone: "err", line: `Bluetooth: ${v.state.error}` } : { word: "Attaching", tone: "pending", line: "Bluetooth: attaching" }; const n = v.connected.length; if (n) return { word: `${n} connected`, tone: "ok", line: `Bluetooth: on, ${n} device${n === 1 ? "" : "s"} connected` }; if (v.scanning) return { word: "Scanning", tone: "ok", line: "Bluetooth: on, the guest is scanning" }; return { word: "On", tone: "ok", line: `Bluetooth: on${v.devices.length ? `, ${v.devices.length} device${v.devices.length === 1 ? "" : "s"} added` : ""}` };}
/** hci0 in a few words (the pill has the connections), and whether it is a problem. */function status(v: BluetoothView): { text: string; warn: boolean } { const a = v.adapters.find((x) => x.id === v.adapter); if (a?.why) return { text: `Not available here: ${a.why}`, warn: true }; if (!v.running || !v.state) return { text: "hci0 comes once the system runs", warn: false }; if (v.unavailable) return { text: "The browser sees no Bluetooth adapter on this computer, or it is off", warn: true }; const s = v.state; if (!s.attached) return s.error ? { text: `Not attached: ${s.error}`, warn: true } : { text: "Attaching hci0…", warn: false }; return { text: `hci0${v.address ? ` ${v.address}` : ""}, ${s.open ? "powered on" : "powered off"}${v.scanning ? ", scanning" : ""}`, warn: false };}
export function BluetoothItem(props: AppletItemProps) { const v = useBluetooth(); if (v.why || v.unavailable) return null; const s = summary(v); const n = adapterOn(v) && v.running ? v.connected.length : 0; return ( <AppletButton id={ID} title={s.line} wide off={v.adapter === "off" || !v.running} tone={s.tone} {...props}> <BluetoothIcon size={ICON} /> {n > 0 && <Count n={n} />} </AppletButton> );}
/** The panel's first row: "Bluetooth" and the switch; the whole row toggles it. */function Power({ v }: { v: BluetoothView }) { const on = v.adapter !== "off"; return ( <button id="tb-bt-power" type="button" role="switch" aria-checked={on} data-autofocus={on ? undefined : ""} title={on ? "Turn Bluetooth off: the guest's hci0 goes" : "Turn Bluetooth on: the guest gets hci0"} onClick={() => setBluetoothAdapter(on ? "off" : onChoice(v))} className="mx-2 flex min-w-0 items-center gap-3 rounded-lg px-2 py-2 text-left font-sans text-[12.5px] text-fg hover:bg-ink/[0.07] focus-visible:bg-ink/[0.07] focus-visible:outline-none pointer-coarse:py-3"> <span className="min-w-0 flex-1 truncate">Bluetooth</span> <span aria-hidden="true" className={`relative h-[18px] w-8 flex-none rounded-full transition-colors ${on ? "bg-accent" : "bg-ink/20"}`}> <span className={`absolute top-[2px] size-[14px] rounded-full bg-white shadow-sm ring-1 ring-black/5 transition-[left] ${on ? "left-[16px]" : "left-[2px]"}`} /> </span> </button> );}
/** The adapter behind hci0: its name with one kind, a select with more (bluetooth.ts ADAPTERS). */function AdapterChoice({ v }: { v: BluetoothView }) { const list = kinds(v); // The panel's keys (BarPopover: the arrows move between buttons) are not the select's. const own = (e: KeyboardEvent) => { if (e.key !== "Tab") e.stopPropagation(); }; return ( <div className="flex min-w-0 items-center gap-3 text-[11.5px]"> <span className="flex-none text-faint">Adapter</span> {list.length > 1 ? ( <select id="tb-bt-adapter" aria-label="Adapter" value={v.adapter} onKeyDown={own} onChange={(e) => setBluetoothAdapter(e.currentTarget.value as AdapterId)} className="field h-7 min-w-0 flex-1 px-2 font-sans text-[12px]"> {list.map((a) => <option key={a.id} value={a.id} disabled={!!a.why}>{a.label}{a.why ? ` — ${a.why}` : ""}</option>)} </select> ) : ( <span id="tb-bt-adapter" className="ml-auto min-w-0 truncate text-muted" title={list[0]?.label}>{list.find((a) => a.id === v.adapter)?.label ?? list[0]?.label}</span> )} </div> );}
/** A device's state in a few words, and its tone. */function devState(v: BluetoothView, d: GattDeviceInfo): { detail: string; tone: DeviceTone } { if (v.connected.includes(d.id)) return { detail: "connected", tone: "ok" }; if (d.seen) return { detail: `in range${d.rssi !== undefined ? `, ${d.rssi} dBm` : ""}`, tone: "idle" }; return { detail: "not connected", tone: "idle" };}
export function BluetoothPanel(props: PopoverProps) { const v = useBluetooth(); const s = summary(v); const on = v.adapter !== "off"; const usable = adapterOn(v); if (usable && v.adapter !== "off") lastOn = v.adapter; const st = status(v); const panelId = `tb-${ID}-panel`; const notRunning = "Once the system runs"; return ( <AppletPanel id={ID} title="Bluetooth" icon={<BluetoothIcon size={16} />} state={s.word} tone={s.tone} monitor="log" settings="bluetooth" width={360} {...props} actions={usable ? () => ( <button id="tb-bt-add" type="button" data-autofocus="" className="btn btn-sm btn-primary my-1 pointer-coarse:h-9" disabled={!v.running} title={!v.running ? notRunning : "Pick a Bluetooth device for the guest"} onClick={() => addBluetoothDevice()}>Add device…</button> ) : undefined}> {(pick) => v.why ? <Empty id="tb-bt-empty">Bluetooth is not available: {v.why}.</Empty> : ( <> <div className="flex flex-col py-1"> <Power v={v} /> {on ? ( <div className="flex flex-col gap-1 px-4 pt-1 pb-1.5 font-sans"> <AdapterChoice v={v} /> <p id="tb-bt-status" className={`truncate text-[11.5px] select-text ${st.warn ? "text-warn" : "text-faint"}`} title={st.text}>{st.text}</p> </div> ) : ( <p id="tb-bt-status" className="px-4 pt-0.5 pb-1.5 font-sans text-[11.5px] text-faint">The guest has no Bluetooth adapter.</p> )} </div> {usable && (v.devices.length ? ( <DeviceList id="tb-bt-devs" label="Bluetooth devices"> {v.devices.map((d) => { const k = idPart(d.id), addr = formatAddress(deviceAddress(d.id)), ds = devState(v, d); return ( <DeviceRow key={d.id} id={`tb-bt-dev-${k}`} tone={ds.tone} label={d.name || "Unnamed device"} where={addr} detail={ds.detail}> <RowIcon id={`tb-bt-dev-${k}-term`} label="Terminal" disabled={!v.running} title={!v.running ? notRunning : "Terminal: bluetoothctl on this device (the Bluetooth app; it installs BlueZ the first time)"} onClick={() => pick({ label: "Terminal", run: () => void launch(bluetoothShell(addr)) })}><PromptIcon size={14} /></RowIcon> <RowButton id={`tb-bt-dev-${k}-forget`} title="Take it from the guest (a connection drops) and from this site's Bluetooth permissions" onClick={() => keepFocus(panelId, () => forgetBluetoothDevice(d.id))}>Forget</RowButton> </DeviceRow> ); })} </DeviceList> ) : ( <Empty id="tb-bt-empty"> No device added. Add a BLE device (a sensor, a micro:bit), then scan for it in the guest (<code className="font-mono text-fg">bluetoothctl</code>, <code className="font-mono text-fg">scan on</code>). </Empty> ))} </> )} </AppletPanel> );}