// SPDX-License-Identifier: MIT // Copyright (C) 2026 Pooya Parsa // The page's UI state: one small external store that the imperative side // (ui.ts, boot.ts, display.ts) writes and the React components (components/) // read with useStore(). Updates replace the changed fields, so a selector that // returns a field gets the same reference until that field changes. The // terminals' state is termtabs.ts's, the windows' wm.ts's. import { useSyncExternalStore } from "react"; import type { KWError } from "./kw.ts"; import type { TailscaleExitNodeStatus, TailscaleExitStatus, TailscaleState } from "./sdk.ts"; export type State = "checking" | "loading" | "booting" | "running" | "halted" | "error"; export type CheckResult = "pass" | "fail" | "warn" | "info"; /** * A section of the system apps (sysapps.ts): Settings has boot (Machine), * distro, storage, network, display, desktop, session, keys and about; System has * status, env, log and errors. guest, the old dialog's Guest tab, is an alias of storage. */ export type Tab = "status" | "env" | "log" | "errors" | "keys" | "guest" | "boot" | "distro" | "storage" | "network" | "display" | "serial" | "bluetooth" | "usb" | "desktop" | "session" | "about"; export interface Check { id: string; label: string; r: CheckResult; value: string; note: string } /** The touch controls' right side (components/Display.tsx). */ export type PadLayout = "gamepad" | "keys"; /** Touch on the picture with the tablet open: the pointer goes to the finger (mouse), or drags move it (trackpad). */ export type TouchMode = "mouse" | "trackpad"; export interface DisplayState { /** A program has /dev/fb0 open; mode is its size. */ attached: boolean; width: number; height: number; /** Which evdev devices a program has open. */ keyboard: boolean; mouse: boolean; tablet: boolean; /** Touch devices: draw the display a quarter turn round over the page while the page is portrait (kept in localStorage). */ rotate: boolean; /** Touch devices: the buttons' layout (kept in localStorage). */ layout: PadLayout; /** Touch devices: how touches on the picture move the pointer (kept in localStorage). */ touchMode: TouchMode; /** Touch devices: the stick and buttons are shown (off for a demo or a desktop; kept in localStorage). */ controls: boolean; } /** A Wayland app's window (wayland.ts), as wland lists it. */ export interface WaylandWindow { key: string; title: string; focused: boolean; minimized: boolean } /** The Wayland apps (wayland.ts; their windows are the window manager's: wayland.ts waylandFocused()). */ export interface WaylandState { /** The page listens for wland's relay (the kernel has vsock and kwshm). */ available: boolean; /** The relay is connected: the compositor runs (the Dock's #dock-wayland). */ attached: boolean; windows: WaylandWindow[]; } /** * A question in the confirm dialog; `cancel` labels the other button (default "Cancel"), `url` shows * under the message. `untrusted` (the guest asks, open.ts): OK (focused, as always), Enter and y * confirm only after a moment, so a key or a click meant for the terminal does not confirm it. * `icon`: the mark over the title, plain or with a badge (default: caution for `danger`, else plain). */ export interface Ask { title: string; msg: string; ok: string; cancel?: string; danger?: boolean; /** Only its two buttons answer: no Esc, y, n or Enter elsewhere. */ required?: boolean; url?: string; untrusted?: boolean; icon?: "mark" | "caution" | "error"; id: number } /** * The boot's progress (ui.ts drives it): what the top bar's boot indicator * shows (components/BootIndicator.tsx) until user space first prints * (`done`, which never goes back). A failure before then shows there too * (the store's `fatal`, while not done). */ export interface BootState { /** The current step, without "…" ("Downloading the kernel"), and what is known of it ("3.1 of 8.4 MiB", or ""). */ label: string; detail: string; /** The ring, 0 to 1: the boot stages' share, the download's bytes within its own (ui.ts BOOT_SPAN). It never goes back. */ progress: number; /** A suspended session is being restored: the label stays "Resuming". */ resuming: boolean; /** The console has nothing to show yet (before boot.ts writes, during a quiet resume): its window shows a faint placeholder. */ blank: boolean; done: boolean; } /** * Where Suspend is (boot.ts sets it with the state: ui.setState's third * argument): saving the session while the machine runs ("saving"), the * machine held at its snapshot point once saved ("held": Pause, or a suspend * in the background; it runs on when continued), or stopped once saved * ("stopped", the state halted: the Resume card, or a resume when the tab is * shown). null otherwise. */ export type SuspendStep = "saving" | "held" | "stopped"; /** * The machine's phase, one name for each case the page tells apart (phase()): * starting (checking, downloading, booting), running, suspending (Suspend * saves it; it still runs), held (saved and held: paused by hand or in the * background), suspended (stopped once saved), halted (stopped otherwise: * powered off, halted, restarting, not started, or a failed suspend), error. */ export type Phase = "starting" | "running" | "suspending" | "held" | "suspended" | "halted" | "error"; /** The machine's phase (Phase), from its state, Suspend's step and the paused and suspended flags. */ export function phase(s: UiState): Phase { switch (s.state) { case "error": return "error"; case "halted": return s.suspended || s.suspend === "stopped" ? "suspended" : "halted"; case "running": return s.paused || s.suspend === "held" ? "held" : s.suspend === "saving" ? "suspending" : "running"; default: return "starting"; } } /** * The system runs (also while Suspend saves it, or holds it): what needs it * (a new terminal, the launcher, Suspend) is enabled only then. */ export const isRunning = (s: UiState): boolean => s.state === "running"; /** Checking the browser, downloading or booting: the boot is under way. */ export const isStarting = (s: UiState): boolean => s.state === "checking" || s.state === "loading" || s.state === "booting"; /** The kernel runs (booting or running): a reboot loses what it holds, so it asks first. */ export const isUp = (s: UiState): boolean => s.state === "booting" || s.state === "running"; /** The machine stopped for good on this load (halted, suspended or failed): nothing new opens on it. */ export const isStopped = (s: UiState): boolean => s.state === "halted" || s.state === "error"; /** The machine is held (suspending, held, suspended): nothing should exec into it (stats.ts blocked() says which). */ export const isHeld = (s: UiState): boolean => { const p = phase(s); return p === "suspending" || p === "held" || p === "suspended"; }; export interface UiState { state: State; /** The state's name as shown (#tb-status-label, System, Copy diagnostics): "Running", "Paused", "Powered off"...; code tells the phase by phase(), not by it. */ label: string; /** Where Suspend is (SuspendStep), set with the state; null: not suspending. */ suspend: SuspendStep | null; /** Suspend saved the system and the kernel stopped (halted): the page offers Resume (components/Overlays.tsx, TopBar.tsx). */ suspended: boolean; /** The saved session's size in bytes, for the Resume card (0: not known). */ suspendedBytes: number; boot: BootState; checks: Check[]; /** KW.errors, copied on each change. */ errors: KWError[]; fatal: { title: string; msg: string; hint: string } | null; /** The toast (ui.toast()); `action`: its one button's label. */ toast: { msg: string; id: number; action?: string } | null; /** The data disk's state in a few words (Settings, Storage: #data-status): where it is kept, or why it is not saved. */ dataStatus: string; /** The state's details (its title: the store's name, what it holds), and its tone: warn (not saved), err (saves fail). */ dataDetail: { detail?: string; tone?: "warn" | "err" }; /** The data disk's blocks in use (non-zero, written at some point) and its size, in bytes; null: none. */ disk: { used: number; size: number; saved: boolean } | null; /** The data disk is open in another tab and this tab runs without it (boot.ts claimDisk()): its Disk size is set there. */ diskElsewhere: boolean; /** * This tab gave way to the one that has the data disk and the browser did * not close it: the card over the desktop (Overlays.tsx OtherTabCard), with * a note under its message ("" for none); null: no card. */ otherTab: string | null; /** The safe-mode explanation in the Data disk section, or null. */ safeNote: string | null; /** * The distro this load boots, as the About dialog shows it (its name, * then its image id once the guest said it, from /run/kw-base); null with * ?distro=none. */ distro: { name: string; image: string; url: string } | null; /** The key bar's Ctrl is armed. */ ctrl: boolean; /** The key bar is showing (phones, on-screen keyboard up). */ keysOn: boolean; pasteOpen: boolean; /** A question in the confirm dialog (ui.ask()), or null. */ ask: Ask | null; /** Paused by hand (boot.ts, autosuspend.ts Pause): saved and held; the notice offers Continue (components/Overlays.tsx). */ paused: boolean; /** The shortcut prefix (Ctrl-A, keys.ts) was pressed: the next key is a command. */ prefix: boolean; /** The Font size option: "auto" or a size in px. */ fontPref: string; fontSize: number; theme: "auto" | "dark" | "light"; shownTheme: "dark" | "light"; termTheme: "auto" | "dark" | "light"; termGlass: "on" | "off"; /** The Copy diagnostics fallback text, shown when the clipboard is unavailable. */ copyText: string | null; display: DisplayState; wayland: WaylandState; /** The app launcher (components/Launcher.tsx) covers the page. */ launcher: boolean; /** The Options as chosen (components/Options.tsx), read by nextSettings(). */ options: Options; /** The guest's Tailscale node (tailscale.ts), shown in Settings, Network. */ tailscale: TailscaleView; } /** * The Tailscale node as Settings shows it (tailscale.ts, from the client's * status events). `state`: "off" (not this load), "blocked" (the option is * on but config.ts tailscaleWhy says why not), "ask" (the page's URL asks to * turn it on or change its server: off this boot until the user accepts, * `askServer`), "loading" (its module loads * or the kernel is being made), "failed" (it did not start: `error`), or the * client's own state ("needs-login" with `authURL`, "running"...). */ export interface TailscaleView { state: "off" | "blocked" | "ask" | "loading" | "failed" | TailscaleState; /** With "ask": the login server the URL names. */ askServer?: string; /** The interactive login's URL, while it waits for the user. */ authURL?: string; /** The node's MagicDNS name, its addresses (IPv4 first), its home DERP region's name and the peers (online ones). */ name: string; addresses: string[]; relay: string; peers: number; online: number; /** The tailnet's other devices, by name: the IPv4 address, whether control says it is online (null: not said), the routes it offers beyond its addresses and whether it offers itself as an exit node. */ devices: { id: number; name: string; address: string; online: boolean | null; routes: string[]; exitNode: boolean }[]; /** The login server's name (Tailscale, or the host of ?tsserver=). */ server: string; /** Why it is blocked or failed, or the last error control or DERP reported. */ error?: string; /** A node identity is saved in this browser for this load's login server (tailscale.ts). */ saved: boolean; /** The peers that offer themselves as exit nodes (offline ones too), by name; [] before the first netmap. */ exitNodes: TailscaleExitNodeStatus[]; /** The running node's exit node: the choice, the peer it names and whether it is usable (else why not); null with none chosen or no node. */ exitNode: TailscaleExitStatus | null; } export interface Options { mem: string; net: "default" | "custom" | "off"; wisp: string; jit: "on" | "off"; verbose: "clear" | "keep"; display: "on" | "off"; sound: "on" | "off"; /** Microphone (?mic=0: off), with the sound card. */ mic: "on" | "off"; /** Camera (?cam=0: off). */ cam: "on" | "off"; append: string; data: "on" | "off"; /** The data disk's size in GiB (?datasize=; config.ts dataSizeCap()). */ datasize: string; root: "overlay" | "safe"; worker: "on" | "off"; /** CPUs, "1" to "16" (?cpus=). */ cpus: string; /** The distro image (?distro=): a name, or "none". */ distro: string; /** Suspend in the background (?autosuspend=): "0" (off), "now" or seconds. */ autosuspend: string; /** Ask before closing (?askleave=0: off). */ askleave: "on" | "off"; /** Guest GL (?gl=), Debian only; on by default where the display is. */ gl: "on" | "off"; /** Guest Vulkan (?vk=), Debian only; on by default where WebGPU is. */ vk: "on" | "off"; /** Tailscale (?tailscale=1), off by default; its login server, that server's key and the node's host name (?tsserver=, ?tsserverkey=, ?tshost=). */ tailscale: "on" | "off"; tsserver: string; tsserverkey: string; tshost: string; /** A new Tailscale auth key typed in Settings ("": keep the saved one, if any). Not a setting: Reboot saves it in localStorage (tailscale.ts), never in the URL. */ tsauthkey: string; /** * The Tailscale exit node ("": none): a peer's MagicDNS name, host name or 100.x address. Not a * setting: kept in localStorage per login server (tailscale.ts), applied at once to a node of this * load's server, else saved by Reboot for the server chosen. */ tsexit: string; } type Listener = () => void; export function createStore(init: T) { let s = init; const listeners = new Set(); return { get: (): T => s, set(patch: Partial | ((s: T) => Partial)) { s = { ...s, ...(typeof patch === "function" ? patch(s) : patch) }; for (const l of listeners) l(); }, subscribe(l: Listener) { listeners.add(l); return () => { listeners.delete(l); }; }, }; } export type Store = ReturnType>; let store: Store | null = null; /** The page's store; ui.ts creates it (initStore) before anything renders. */ export function ui$(): Store { if (!store) throw new Error("the UI store is not initialised"); return store; } export function initStore(init: UiState): Store { store = createStore(init); return store; } /** A field of the UI state; the component re-renders when it changes. */ export function useStore(select: (s: UiState) => U): U { const s = ui$(); return useSyncExternalStore(s.subscribe, () => select(s.get())); }