// SPDX-License-Identifier: MIT // Copyright (C) 2026 Pooya Parsa // The Options: one control per setting (config.ts) except ?simulate and // ?showcase, in groups that Settings (Settings.tsx) shows in its sections: // MachineOptions (CPUs, memory, worker thread, JIT, verbose boot, kernel // command line), DistroOptions (distro, safe mode), StorageOptions (data disk), // NetworkOptions (Wisp), DisplayOptions (display, guest GL, guest Vulkan, sound) and // SessionOptions (suspend in the background, ask before closing); Tailscale's // are TailscaleSettings.tsx, on this file's controls. Reboot saves them in // localStorage and reloads (ui.nextSettings()). // Terminal style: on/off options are [x] check boxes, Network and Distro are // (•) radio choices, CPUs and Memory are sliders over their counts and sizes. // FontSize is the same kind of slider; it applies at once and is kept in // localStorage. The // CPUs slider is disabled, with the reason, where the page cannot boot more // than one (config.ts smpBlocker()). Distro (?distro=) lists the page's images and none. // Guest GL (?gl=, on by default where the display is) is disabled, unticked, with the reason, // where the page cannot offer it (config.ts glBlocker()) or the Distro chosen is not one of // GL_DISTROS; its stored value stays. Guest Vulkan (?vk=, on by default) likewise, where the // page cannot offer it (config.ts vkBlocker()) or the Distro chosen is not one of VK_DISTROS. // Suspend in the background (?autosuspend=, autosuspend.ts) offers off, at once, 30 s and 5 min, // plus a ?autosuspend= of other seconds; this device's default is marked. // // The fields are controlled by the store. Besides onChange, native listeners // on each group's form (OptionsForm; capture phase, so non-bubbling events // count too) read every change: React drops an event whose value was set // from script (autofill, the browser tests), and the store would miss it. A // check box stores its data-on or data-off value, so the options keep the // values nextSettings() reads. import { useEffect, useRef, useState, type ChangeEvent, type KeyboardEvent, type ReactNode } from "react"; import { AUTO_SUSPEND_CHOICES, autoSuspendLabel } from "../autosuspend.ts"; import { DATA_SIZE_DEFAULT, DATA_SIZE_UNCAPPED, DEFAULT_CMDLINE, dataSizeCap, DEFAULT_DISTRO, DISTROS_OFFERED, GL_DISTROS, VK_DISTROS } from "../config.ts"; import { capitalize } from "../format.ts"; import { KW } from "../kw.ts"; import { useStore, type Options as Opts } from "../store.ts"; import { autoFont } from "../ui.ts"; import { chooseExitNode } from "../tailscale.ts"; import { StorageQuota, useStorageEstimate } from "./StorageQuota.tsx"; /** A field changed: the store's option of its name, or the font size (applied at once). */ export function onField(e: Event | ChangeEvent) { const t = e.target as HTMLInputElement | HTMLSelectElement; if (!t.name) return; let v = t.value; // The exit node's typed name: chosen once the field is left or Enter pressed (TailscaleSettings.tsx), not on each key. if (t.name === "tsexit" && t.type === "text") { if (e.type === "change") chooseExitNode(t.value); return; } if (t instanceof HTMLInputElement && t.type === "checkbox") v = (t.checked ? t.dataset.on : t.dataset.off) ?? ""; else if (t instanceof HTMLInputElement && t.type === "range") v = t.dataset.values?.split(",")[openStop(t, +t.value)] ?? ""; else if (t instanceof HTMLInputElement && t.type === "radio" && !t.checked) return; pick(t.name, v); } /** A slider's stop index, moved to the nearest stop that is not off (data-off: their indices). */ function openStop(t: HTMLInputElement, i: number): number { const off = new Set((t.dataset.off ?? "").split(",").filter(Boolean).map(Number)); for (let d = 0; d <= +t.max; d++) { if (i - d >= 0 && !off.has(i - d)) return i - d; if (i + d <= +t.max && !off.has(i + d)) return i + d; } return i; } const pick = (name: string, v: string) => (name === "font" ? KW.ui!.setFont(v) : name === "tsexit" ? chooseExitNode(v) : name === "theme" ? KW.ui!.setTheme(v) : name === "termtheme" ? KW.ui!.setTermTheme(v) : name === "termglass" ? KW.ui!.setTermGlass(v) : KW.ui!.setOption(name as keyof Opts, v as never)); type FieldName = keyof Opts | "theme" | "termtheme" | "termglass"; export function Field({ label, wide, hidden, id, children }: { label: string; wide?: boolean; hidden?: boolean; id?: string; children: ReactNode }) { return ( ); } /** * [x] Label, with a note under it. The input is real (keyboard, screen readers), drawn as text. * A forced box is shown ticked and disabled, its stored value kept (Worker thread with several CPUs); * a blocked one unticked and disabled, its stored value kept (Guest GL with another distro). */ export function Check({ id, name, on, off, value, label, note, forced, blocked }: { id: string; name: FieldName; on: string; off: string; value: string; label: string; note?: string; forced?: boolean; blocked?: boolean }) { const checked = !blocked && (forced || value === on); const locked = forced || blocked; return ( ); } /** (•) one of several; `detail` in a quieter tone after the label; `onPick` for a radio without a name (no option). */ function Radio({ id, name, value, current, label, detail, onPick }: { id: string; name?: FieldName; value: string; current: string; label: string; detail?: string; onPick?: () => void }) { const checked = value === current; return ( ); } /** * `warn`: a choice to try, not to keep (red when selected, with `warnNote` under the slider). * `off`: shown, but not a choice (greyed; the thumb moves to the nearest other stop). */ type Stop = { value: string; tick: string; label: string; note?: string; warn?: boolean; off?: boolean }; /** * A slider over a few stops (value: the stop's index; data-values maps it * back), with the current value beside the label and each stop's tick label * under it, plus an optional note under that (Memory: "auto" under the size * auto picks). A tick is clickable and lines up with the thumb's centre there. * A disabled slider (CPUs where only one is possible) says why in its note. */ function Slider({ id, name, label, value, stops, disabled, note, noteId, warnNote }: { id: string; name: string; label: string; value: string; stops: Stop[]; disabled?: boolean; note?: string; noteId?: string; warnNote?: string; }) { const i = Math.max(0, stops.findIndex((s) => s.value === value)), last = stops.length - 1; const at = (k: number) => `calc(${last ? k / last : 0} * (100% - var(--thumb)) + var(--thumb) / 2)`; const cur = stops[i]!.label; const warn = !disabled && !!stops[i]!.warn; if (warn && warnNote) note = warnNote; return (
{cur}
s.value).join(",")} data-off={stops.flatMap((s, k) => (s.off ? [k] : [])).join(",")} disabled={disabled} aria-valuetext={cur} aria-describedby={note ? noteId : undefined} onChange={onField} className="slider w-full disabled:cursor-not-allowed disabled:opacity-50" style={{ "--fill": at(i), ...(warn ? { "--tone": "var(--color-err)" } : {}) } as never} />
s.note) ? "h-7" : "h-3.5"} ${disabled ? "opacity-50" : ""}`} aria-hidden="true"> {stops.map((s, k) => ( pick(name, s.value)} style={{ left: at(k) }} className={`absolute top-0 flex -translate-x-1/2 flex-col items-center tabular-nums ${disabled ? "" : s.off ? "cursor-not-allowed opacity-40" : "cursor-pointer hover:text-fg"} ${k === i ? (warn ? "text-err" : "text-fg") : ""}`}> {s.tick}{s.note && {s.note}} ))}
{note && {note}}
); } const SIZES = [64, 128, 256, 512, 1024, 2048, 4096]; const CPU_COUNTS = [1, 2, 4, 8, 16]; const FONTS = [11, 12, 13, 14, 15, 16, 18]; /** * A group of options (Settings has one per section): a form whose fields the * store follows, by their onChange and by native listeners on the form * (capture phase), which see the changes React drops (the top of this file). */ export function OptionsForm({ children }: { children: ReactNode }) { const form = useRef(null); useEffect(() => { const f = form.current!; f.addEventListener("change", onField, true); f.addEventListener("input", onField, true); return () => { f.removeEventListener("change", onField, true); f.removeEventListener("input", onField, true); }; }, []); return
e.preventDefault()}>{children}
; } /** Enter in a text field reboots, like the button. */ export const enter = (e: KeyboardEvent) => { if (e.key === "Enter") { e.preventDefault(); KW.ui!.reboot(); } }; /** A column of check boxes. */ const Checks = ({ children }: { children: ReactNode }) =>
{children}
; /** Machine: CPUs, memory, the worker thread, the JIT, the kernel command line and verbose boot. */ export function MachineOptions() { const cfg = KW.config; const o = useStore((s) => s.options); // Memory stops: the sizes, the one auto picks on this device (marked, and // choosing it means auto) and a ?mem= that is none of them. const mib = (n: number) => (n < 1024 ? `${n} MiB` : `${+(n / 1024).toFixed(1)} GiB`); const sizes = [...new Set([...SIZES, cfg.memAutoMiB, ...(cfg.memParam ? [Number(cfg.memParam)] : [])])].sort((a, b) => a - b); const mem: Stop[] = sizes.map((n) => ({ value: n === cfg.memAutoMiB ? "auto" : String(n), tick: n < 1024 ? String(n) : `${+(n / 1024).toFixed(1)}G`, label: n === cfg.memAutoMiB ? `Auto (${mib(n)})` : mib(n), note: n === cfg.memAutoMiB ? "auto" : undefined, })); const memValue = o.mem === String(cfg.memAutoMiB) ? "auto" : o.mem; // CPUs: 1, 2, 4, 8, 16 up to the host's threads, the host's threads themselves (the most // there is to try), the suggested count and a ?cpus= that is none of them. Past the // suggestion (one in WebKit) a count is there to try: red when selected. const cpuOk = cfg.cpuSuggested || 1; const cpus: Stop[] = [...new Set([...CPU_COUNTS.filter((n) => n <= cfg.cpuMax), cfg.cpuMax, ...(cfg.cpuSuggested ? [cfg.cpuSuggested] : []), cfg.smpParam])].sort((a, b) => a - b) .map((n) => { const sug = n === cfg.cpuSuggested && n > 1; return { value: String(n), tick: String(n), label: `${n} CPU${n > 1 ? "s" : ""}${sug ? " (suggested)" : ""}`, note: sug ? "suggested" : undefined, warn: n > cpuOk }; }); const cpuWarn = `To try: more than ${cpuOk} CPU${cpuOk > 1 ? "s" : ""} leaves this device's threads busy (a busy host stalls the guest) and gains little; boot is slower and each CPU takes 9 MiB of guest memory, and as much in a suspended session.`; // More than one CPU runs each in a Web Worker (config.ts: worker), so Worker thread is ticked and locked. const smp = o.cpus !== "1" && !cfg.smpBlocked; const cpuNote = cfg.smpBlocked ? `One CPU on this page: ${cfg.smpBlocked}.` : cfg.smpWhy ? `This boot runs on one CPU: ${cfg.smpWhy}.` : cfg.resumeCpus ? `This boot runs on ${cfg.resumeCpus} CPUs, those of the suspended session it resumes.` : "More than one boots the SMP kernel, each CPU in a Web Worker (as with Worker thread); a suspended session resumes on as many."; return (
); } /** Distro: the image (?distro=) and safe mode (the plain image as the root). */ export function DistroOptions() { const cfg = KW.config; const o = useStore((s) => s.options); // Distro: the images (debian first) and none, the base shell. const mib1 = (n: number) => `${(n / 1048576).toFixed(n < 10485760 ? 1 : 0)} MiB`; const distros = [...DISTROS_OFFERED.map((d) => ({ value: d.name, label: capitalize(d.name), title: `${d.url}, ${mib1(d.size)}, streamed` })), { value: "none", label: "None (base shell)", title: "no distro image: the base initramfs's busybox shell" }]; const distroNote = cfg.distroWhy ? `${cfg.distroWhy}.` : `A read-only image under the root overlay; its changes are kept per distro on the data disk. Default ${DEFAULT_DISTRO}.`; return (
Distro
{distros.map((d) => ( ))}
{distroNote}
); } /** Storage: the data disk (/data, saved in this browser). */ /** * Storage: the data disk, and its size (?datasize=, GiB). A size above the * saved disk's grows it at the next boot (openDataDisk()'s size, the guest's * kwbox growfs). Any whole GiB from the default, or the saved disk's size (a * disk never shrinks), up to what the disk can fill: the browser's quota for * the page less the site's other data (config.ts dataSizeCap(), which boot.ts * clamps ?datasize= to, as a larger disk would fail its writes with EIO once * the quota is used up); 64 where the browser reports no quota. Under it the * quota line (StorageQuota.tsx: the disk's state, the quota, what uses it, * the chosen size, why the disk is limited). In a tab without the disk (it * is open in another tab) the size is not offered: that tab has the disk. */ export function StorageOptions() { const o = useStore((s) => s.options); const disk = useStore((s) => s.disk); const elsewhere = useStore((s) => s.diskElsewhere); const have = disk?.saved ? Math.floor(disk.size / 1073741824) : 0; const est = useStorageEstimate(); const cap = dataSizeCap(est ?? undefined, disk?.saved ? disk.used : 0, have); const asked = Number(o.datasize); const min = Math.max(DATA_SIZE_DEFAULT, have); const max = Number.isFinite(cap) ? cap : Math.max(DATA_SIZE_UNCAPPED, have, asked); const value = Math.min(max, Math.max(asked, min)); const [live, setLive] = useState(null); // the whole GiB the slider is dragged to return (
); } /** * Disk size: a slider from `min` to `max` GiB and a number field beside it for * an exact size. The slider follows the pointer smoothly while dragged (step * "any", its position kept here), shows and marks (`onLive`, the quota bar's * size mark) the whole GiB it is on, and sets the option once let go (its * change event); the arrow keys step one GiB, Page Up and Down ten, Home and * End go to either end. The number field applies a typed size once it is in * range, and the nearest one in range on Enter or when left. Neither has a * name: the form's listeners leave them alone. */ function DiskSize({ value, min, max, disabled, note, onLive }: { value: number; min: number; max: number; disabled: boolean; note?: string; onLive: (n: number | null) => void }) { const [draft, setDraft] = useState(null); const [drag, setDrag] = useState(null); const range = useRef(null); const fixed = disabled || min >= max; const clamp = (n: number) => Math.min(max, Math.max(min, Math.round(n))); const set = (n: number) => pick("datasize", String(clamp(n))); const at = (n: number) => `calc(${max > min ? (n - min) / (max - min) : 0} * (100% - var(--thumb)) + var(--thumb) / 2)`; const shown = drag === null ? value : clamp(drag); // Let go (or a click on the track): the whole GiB it is on becomes the option. const release = useRef(() => {}); release.current = () => { if (drag === null) return; setDrag(null); onLive(null); set(drag); }; useEffect(() => { const el = range.current!; const done = () => release.current(); el.addEventListener("change", done); return () => el.removeEventListener("change", done); }, []); const commit = (v: string) => { setDraft(null); if (/^\d+$/.test(v.trim())) set(Number(v)); }; const KEYS: Record number> = { ArrowLeft: (n) => n - 1, ArrowDown: (n) => n - 1, ArrowRight: (n) => n + 1, ArrowUp: (n) => n + 1, PageDown: (n) => n - 10, PageUp: (n) => n + 10, Home: () => min, End: () => max, }; return (
{ const v = e.currentTarget.value; setDraft(v); if (/^\d+$/.test(v) && +v >= min && +v <= max) pick("datasize", v); }} onBlur={(e) => commit(e.currentTarget.value)} onKeyDown={(e) => { if (e.key === "Enter") { e.preventDefault(); commit(e.currentTarget.value); } }} className="field h-6 w-[4.5rem] px-1.5 text-right tabular-nums" /> GiB
{ const v = +e.currentTarget.value; setDrag(v); onLive(clamp(v)); }} onKeyDown={(e) => { const to = KEYS[e.key]; if (!to || e.altKey || e.ctrlKey || e.metaKey) return; e.preventDefault(); setDrag(null); onLive(null); set(to(value)); }} className="slider w-full disabled:cursor-not-allowed disabled:opacity-50" style={{ "--fill": at(drag ?? value) } as never} /> {note ?? "Grows when you reboot, never shrinks; space is used as /data fills"}
); } /** Network: Wisp (the default servers or custom ones) or none. */ export function NetworkOptions() { const o = useStore((s) => s.options); return (
Network
{o.net === "default" && ( Through {__KW_WISP__.length ? "this page's" : "this project's"} Wisp server, which sees the guest's connections. )}
); } /** Display and sound: the framebuffer and input devices, guest GL, sound, the microphone, the camera. */ export function DisplayOptions() { const cfg = KW.config; const o = useStore((s) => s.options); // Guest GL: Debian only, and only where the page has the renderer and WebGL2. const glOff = cfg.glBlocked ?? (GL_DISTROS.includes(o.distro) ? null : `${GL_DISTROS.join(", ")} only (its Mesa has the virgl driver)`); const glNote = glOff ? `Off: ${glOff}` : cfg.glWhy ? `This boot runs without it: ${cfg.glWhy}` : "guest Mesa on this browser's WebGL2 (virgl), through /dev/dri (virtio-gpu); loaded on first use"; // Guest Vulkan: Debian only, and only where the page has the translator and WebGPU. const vkOff = cfg.vkBlocked ?? (VK_DISTROS.includes(o.distro) ? null : `${VK_DISTROS.join(", ")} only`); const vkNote = vkOff ? `Off: ${vkOff}` : cfg.vkWhy ? `This boot runs without it: ${cfg.vkWhy}` : "Vulkan 1.0 in the guest on this browser's WebGPU (kwvk); loaded on first use"; return ( ); } /** Session: suspending in the background, and asking before the tab closes. */ export function SessionOptions() { const cfg = KW.config; const o = useStore((s) => s.options); // Suspend in the background: the choices, a ?autosuspend= of other seconds, this device's default marked. const autoValues = [...new Set([...AUTO_SUSPEND_CHOICES, cfg.autosuspendParam])]; const autoNote = `When the tab has been hidden that long, a system you have used since it booted is saved as with Suspend and paused; shown again, it goes on where it was (or, if the browser dropped the page meanwhile, resumes from the saved session). Default: ${autoSuspendLabel(cfg.autosuspendDefault).toLowerCase()} ${cfg.mobile ? "on phones and tablets, which may drop a background tab at any time" : "on desktops, where a background tab keeps running"}.`; return (
Suspend in the background
{autoValues.map((v) => ( ))}
{autoNote}
); } /** The terminal font size (Settings, Display and sound): applied at once, no reboot. Stops like Memory's: auto's size marked, and a size from a pinch. */ export function FontSize() { const fontPref = useStore((s) => s.fontPref); const autoPx = autoFont(); const px = [...new Set([...FONTS, autoPx, ...(fontPref !== "auto" ? [Number(fontPref)] : [])])].sort((a, b) => a - b); const fonts: Stop[] = px.map((n) => ({ value: n === autoPx ? "auto" : String(n), tick: String(n), label: n === autoPx ? `Auto (${n} px)` : `${n} px`, note: n === autoPx ? "auto" : undefined, })); const fontValue = fontPref === String(autoPx) ? "auto" : fontPref; return (
); } export function Theme() { const theme = useStore((s) => s.theme); return (
Theme
); } export function TermTheme() { const termTheme = useStore((s) => s.termTheme); return (
Colours
); } export function TermGlass() { const termGlass = useStore((s) => s.termGlass); return (
); }