// SPDX-License-Identifier: MIT // Copyright (C) 2026 Pooya Parsa // Serial devices for the guest: Web Serial ports (navigator.serial) attached // to its /dev/ttyACM0..3 (vm.serial, js/core/serial.ts; the SerialPort // wrapper is js/web/serial.ts). The machine always has the four ports // (boot.ts passes `serial: true`, which costs nothing until a guest program // opens one); nothing here touches Web Serial before the machine runs. // - Connect (Settings > Serial ports, Settings.tsx): // requestPort() from the click, then the port goes to the first free // slot. // - A guest program that opens a port with no device (vm.serial's // onWanted) gets a toast with a Connect button, the same chooser. // - Ports this origin was allowed before (getPorts()) are attached once // the machine runs, and again when plugged in (navigator.serial's // "connect"), to the ttyACM they had if it is free; unplugging one // ("disconnect", which the backend hears) is a hangup for a guest program // that has it open, and frees the slot. // - Disconnect detaches the port and forgets it (SerialPort.forget()), so // the next boot does not attach it again. // Where Web Serial is missing (browsers other than Chromium-based desktop // ones, an insecure context) the section says why and offers nothing. import { useSyncExternalStore } from "react"; import { KW } from "./kw.ts"; import { WebSerialBackend, webSerial, webSerialBackend, webSerialBlocker, type KernelHandle, type SerialPortState, type WebSerialPort } from "./sdk.ts"; export interface SerialView { /** Why there is no Web Serial here, or null. */ why: string | null; /** The machine runs with serial ports. */ running: boolean; /** One per guest port (/dev/ttyACM0..), attached or not. */ ports: SerialPortState[]; } let view: SerialView = { why: null, running: false, ports: [] }; let blockerChecked = false; const listeners = new Set<() => void>(); let vm: KernelHandle | undefined; const backends = new Map(); /** The slot each port had last, so that a board plugged in again gets its ttyACM back when it is free. */ const lastSlot = new Map(); let log: (msg: string) => void = (m) => console.warn(m); let publishTimer: ReturnType | undefined; /** The view again, at most every 200 ms (a flash writes many chunks; Settings renders all the time). */ function publish(): void { publishTimer ??= setTimeout(() => { publishTimer = undefined; const s = vm?.serial; view = { why: view.why, running: !!s, ports: s ? s.states : [] }; for (const l of listeners) l(); }, 200); } function snapshot(): SerialView { if (!blockerChecked) { blockerChecked = true; view = { ...view, why: webSerialBlocker() ?? null }; } return view; } /** The serial ports' state, for the Settings section. */ export function useSerial(): SerialView { return useSyncExternalStore((l) => { listeners.add(l); return () => listeners.delete(l); }, snapshot); } /** The machine runs: its ports follow vm.serial, and the ports allowed before are attached. */ export function attachSerial(machine: KernelHandle, hostLog: (msg: string) => void): void { const s = machine.serial; if (!s) return; vm = machine; log = hostLog; s.onChange(() => publish()); // A guest program opened a port with no device (ENODEV): offer the chooser where the user is. The // button's click is the gesture requestPort() needs. Once in 20 s, and not while a device is attached. let offered = 0; s.onWanted((slot) => { const now = Date.now(); if (now - offered < 20000 || webSerialBlocker() || s.states.some((p) => p.attached)) return; offered = now; KW.ui?.toast(`A program wants a serial device on /dev/ttyACM${slot}`, { action: "Connect…", run: connectSerial, ms: 15000 }); }); void machine.exited.then(() => { if (vm === machine) vm = undefined; publish(); }); publish(); const ns = webSerial(); if (webSerialBlocker() || !ns) return; ns.addEventListener("connect", (e) => { const port = e.target as WebSerialPort; const slot = attachPort(port); if (slot !== undefined) KW.ui?.toast(`${backends.get(port)!.info.label} plugged in: /dev/ttyACM${slot}`); }); void ns.getPorts().then((ports) => { for (const p of ports) { // A port granted before but not plugged in now (Chrome 124+ says): its "connect" attaches it. if (p.connected === false) continue; const slot = attachPort(p); if (slot !== undefined) log(`[serial] ${backends.get(p)!.info.label}, allowed before, is /dev/ttyACM${slot}`); } }, (e: unknown) => log(`[serial] getPorts(): ${(e as Error)?.message ?? e}`)); } function attachPort(port: WebSerialPort): number | undefined { const s = vm?.serial; if (!s) return undefined; let b = backends.get(port); if (!b) backends.set(port, (b = webSerialBackend(port, { log }))); if (s.slotOf(b) >= 0) return undefined; const was = lastSlot.get(port); try { const slot = s.attach(b, was !== undefined && !s.backend(was) ? was : undefined); lastSlot.set(port, slot); return slot; } catch (e) { KW.ui?.toast((e as Error).message); return undefined; } } /** Connect…: pick a port (Chrome's chooser; call from the click itself) and attach it to the first free /dev/ttyACM. */ export function connectSerial(): void { const ns = webSerial(); if (!ns || !vm?.serial) return; ns.requestPort().then((port) => { const slot = attachPort(port); const b = backends.get(port); if (slot !== undefined) KW.ui?.toast(`${b!.info.label} is /dev/ttyACM${slot} in the guest`); else if (b && vm?.serial && vm.serial.slotOf(b) >= 0) KW.ui?.toast(`${b.info.label} is /dev/ttyACM${vm.serial.slotOf(b)} already`); }, (e: unknown) => { // NotFoundError: the chooser was closed without a port. if ((e as Error)?.name !== "NotFoundError") KW.ui?.toast(`Serial: ${(e as Error)?.message ?? e}`); }); } /** Disconnect: detach the port from the guest (a program using it sees a hangup) and forget it. */ export async function disconnectSerial(slot: number): Promise { const s = vm?.serial; const b = s?.backend(slot); if (!s || !b) return; await s.detach(slot); if (b instanceof WebSerialBackend) { backends.delete(b.port); lastSlot.delete(b.port); await b.port.forget?.().catch(() => {}); } publish(); }