diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 23f3b55..56fba78 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -12,6 +12,9 @@ Rust binary. ## Layering ``` +Graphical welcome + installer Quickshell/QML (live only; typed JSON protocol) + | phoebus-welcome, phoebus-install + v TUI / CLI / sys front-ends (phoebus-tui, phoebus-installer) | v @@ -24,6 +27,13 @@ Executor commands, storage, Portage, boot, services Core typed config, models, policy, validation ``` +The graphical frontend is one of several front-ends; it never contains +installation logic. `phoebus-installer --gui-bridge` speaks newline-delimited +JSON on stdin/stdout, reuses the same `Installer`, plan, validation and +`DestructiveAuthorization` flow, and reports real stages through +`Installer::install_observed`. The QML only renders typed state and submits +bounded requests (ADR 0010). + ### phoebus-core Pure, non-privileged logic with no external commands except reading `/proc`, @@ -44,6 +54,8 @@ Pure, non-privileged logic with no external commands except reading `/proc`, - `effects` — parse `emerge --pretend` into resolved effects + plan digest. - `transaction` — the user-queryable log of executed actions and outcomes. - `action` — closed `SystemAction` schema and a small deterministic parser. +- `brand` — the visual identity (palette tokens, sun emblem, wordmark, + wallpaper) as deterministic SVG/tokens shared by the QML frontend. - `update` — preparation policy and real Portage argument builders. ### phoebus-executor diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index bd2e5d9..6b5845d 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -7,6 +7,47 @@ Format: Keep a Changelog. Dates are UTC. ## Unreleased +### Added +- **Graphical installation experience.** The live ISO now boots into a branded + Phoebus welcome window (`phoebus-welcome`) that makes "Install Phoebus OS" the + dominant action, shows ISO version and readiness (network, firmware, memory, + cores) and keeps network/display/accessibility/help/keyboard-test/power tools + available, with troubleshooting tools under Advanced. A full graphical setup + wizard (`phoebus-install`) guides language and keyboard, network and + prerequisites, AI model connection, destination disk (with protected disks + and the installer medium identified), account and encryption, review, + `ERASE` authorization, progress and completion. Duplicate installer sessions + are prevented. The TUI/CLI remains the fallback. See ADR 0010 and + `docs/VM-BOOT-VERIFICATION.md`. +- **Typed JSON GUI bridge.** `phoebus-installer --gui-bridge` exposes a narrow, + fail-closed protocol over stdin/stdout that reuses the same `InstallConfig`, + validation, plan, `DestructiveAuthorization` and staged executor as the TUI. + Approval is bound to a plan digest, secrets travel only over the stdin pipe, + and real backend stages are reported with categories (no invented + percentages). `Installer::install_observed` and an `InstallObserver` trait + were added; `Installer::install` is unchanged. +- **Phoebus brand system.** `phoebus-core::brand` provides charcoal/warm + white/amber tokens plus a sun emblem, wordmark and wallpaper as deterministic + SVG (emitted via `--emit-asset`, shared with the QML frontend), applied to the + GRUB menu, live wallpaper, welcome window, installer, application icon and + completion screen. Readable contrast and the QML/Rust palette are pinned by + tests. + +### Fixed +- **Installed systems no longer default into recovery.** `loader.conf` now pins + the newest real kernel entry, and the snapshot recovery entry carries a + `sort-key` that keeps it after every kernel, so a low machine-id can never + make systemd-boot select the recovery entry by filename tie-break. Previously + an installed system could boot `systemd.unit=rescue.target` after reboot. +- **DMS first-run dialogs are suppressed on the live medium** by pre-seeding + DMS's own onboarding and changelog markers, so the installer is the first + thing the user sees. +- **The live-medium device is now identified.** `probe_disks` also inspects + `/run/live/medium` and `/run/live/rootfs`, so the ISO is labelled as the + installation medium (and remains protected). +- **The installer shortcut is live-only.** `phoebus-install` and its desktop + entry are no longer written to an installed system. + ### Changed - **Mango + DankMaterialShell is now the default desktop** for both the installation ISO and the installed system (explicit owner decision). Omitted diff --git a/docs/HANDOFF.md b/docs/HANDOFF.md index 65f56e6..e924d36 100644 --- a/docs/HANDOFF.md +++ b/docs/HANDOFF.md @@ -3,68 +3,67 @@ Rolling note between work sessions. **Update this file before you finish**, then commit it. It should be short and current; use `git log` for detail. -- **Last updated:** commit `639cb33` + this session (2026-09-21) -- **Current focus:** Mango + DankMaterialShell as the default desktop. The - installed default is `desktop.profile = "mango"` with greetd authenticated - login (Mango default, dwl fallback), and `installer/live/build.sh` now builds - a Mango live desktop ISO from a rootless Debian testing rootfs plus pinned - Mango/DMS releases. Graphical VM verification of the installed desktop and - the built ISO is the remaining evidence gap. -- **Last verified:** static Rust binary install + detached boot and the 2026-09-21 - appliance baseline (`INSTALL-RC=0`, `NO_SECRET_LEAK`, coordinated initial - snapshot + recovery entry) in `docs/VM-BOOT-VERIFICATION.md`; unit/functional - tests for the Mango default, explicit overrides, greetd login, live/installed - separation, session entries, pinned release checksums and the live ISO guards; - and the built Mango live ISO booted in a graphical seat-providing VM (Mango + - DMS + Quickshell running, DMS panel/welcome captured by `screendump`). +- **Last updated:** this session (2026-09-21), graphical installer ISO. +- **Current focus:** The ISO now boots into a branded **welcome window** and a + full **graphical installer wizard** over a typed JSON bridge + (`phoebus-installer --gui-bridge`), with the TUI/CLI as fallback. The brand + system, boot-menu identity, live-medium detection and the recovery-boot + default bug are fixed. See ADR 0010 and `docs/VM-BOOT-VERIFICATION.md`. +- **Last verified (this session):** + - `gui-driver.py gui`: welcome autostarts; DMS first-run dialogs suppressed; + installer opens; duplicate sessions prevented (`n1=n2=1`); keyboard + navigation reaches network + AI steps; the AI step blocks without a model. + - `gui-driver.py install` + `boot` on the built ISO: `INSTALL-RC=0`, + `NO_SECRET_LEAK`, and a **detached** boot with systemd `running`, + **0 failed units**, LUKS2, all Btrfs subvolumes and network, and the boot + menu defaulting to **Gentoo Linux** (not recovery). + - Rust suite: GUI bridge dry-run protocol, approval binding/invalidation, + secret non-disclosure, brand tokens/contrast, boot default pinning. + - ISO: `installer/live/phoebus-installer-amd64.iso` 1.6 GiB, + `sha256 2a52178c4b4a71bbc5c011b89533988ceb9aa95493160cb93c4335f03d9a1eee`. - **Public repo:** (remote `origin`, SSH port 2222). ## Next actions (in order) -1. **Mango graphical verification** (default, so highest priority): install the - default profile and boot the built live ISO in a graphical, seat-providing - VM; verify the panel/launcher/terminal/Install-Phoebus entry, audio/network, - lock/idle, logout/reboot and the dwl fallback, plus authenticated login on - the installed system (`docs/VM-BOOT-VERIFICATION.md`). -2. **Rollback VM acceptance**: deliberately break an update in the disposable - VM, run `sys undo`, reboot detached, verify package-state consistency - (`/var/db/pkg` matches `/`), then boot the snapshot recovery entry with no - network or model (ADR 0007). -3. **Live AI provider call**: exercise `sys ask` with a real 0600 key file and - confirm the `systemd-run` sandbox properties apply; the path is - fixture-verified only. -3. **Physical-seat desktop**: run `phoebus-session` on a real VT/seat and check +1. **Live AI provider call**: exercise the GUI AI step (and `sys ask`) with a + real 0600 key or a downloaded local model; the path is fixture-verified only. +2. **Installed Mango desktop**: install the default profile in a graphical VM + and verify the panel/launcher/terminal/audio/network/lock/idle, the dwl + fallback, and the welcome/installer absence on the installed system. +3. **Rollback VM acceptance**: deliberately break an update, run `sys undo`, + reboot detached, verify `/var/db/pkg` matches `/`, then boot the recovery + entry with no network or model (ADR 0007). +4. **Physical-seat desktop**: run `phoebus-session` on a real VT/seat and check `phoebus-menu`, `phoebus-lock`, `phoebus-idle`, kitty, XWayland, the polkit agent, logout/reap and reboot (`docs/DEVELOPMENT.md`). -4. **Matching signed binhost / binary strategy**: keep the official binhost for - matching USE and Flatpak/Nix elsewhere; do not publish a private binhost - (ADR 0006). Verify with `emerge -pv`. -5. **Release gates on a CI runner**: run `phoebus-release gates --execute` and - `phoebus-release publish` once a runner exists; no gate has executed. +5. **Release gates on a CI runner**: `phoebus-release gates --execute` and + `publish` once a runner exists; no gate has executed. ## Known blockers / risks -- No live DeepSeek/OpenAI call has been made (no key in this environment). -- No Forgejo Actions runner is known to exist; `.forgejo/workflows/ci.yml` only - runs once one is registered. -- Desktop graphical login / physical seat has not been exercised; the serial - VM has no logind seat. -- NVIDIA is not verified on hardware. +- No live DeepSeek/OpenAI call has been made (no key in this environment); the + AI step is verified as a blocked prerequisite and with a fixture transport. +- **Installed** Mango (GURU + compiled Quickshell/DMS) is not VM-verified; nor + is the dwl fallback session. - Rollback and the AI sandbox are implemented and unit-tested but not - VM-verified. + VM-verified. NVIDIA is not verified. +- The GUI bridge reaches Quickshell via `Process` + `/usr/bin/sudo -n`; it + relies on the live user's passwordless sudo. ## Environment notes -- Dev host: Ubuntu 26.04. QEMU/OVMF/xorriso/rustfmt/clippy installed. +- Dev host: Ubuntu 26.04. QEMU/OVMF/xorriso/rustfmt/clippy/ImageMagick present. - Debian-Live base ISO is cached at `/home/dominic/debian-live-standard.iso` (matches `installer/live/base.sha256`); the appliance ISO builds without root. -- The appliance harness is `installer/tests/vm/appliance-driver.py` + - `appliance-guest.sh` + `appliance-test.conf.example`; serve the stage3, - config and 0600 secret files over `python3 -m http.server 8000`. -- The VM harness disks are disposable qcow2 files on `/` (not `/tmp`, which is - a small tmpfs); never point `DISK` at `/dev/*`. -- The VM harness honours `CHECKS_TIMEOUT` / `INSTALL_TIMEOUT` for long runs. +- Local QML iteration: `/tmp/opencode/run-qml.sh ` runs a config on + a nested Mango over the host X11 using the built rootfs libraries, and + `grim` captures it. The sanctioned verification is the disposable VM. +- VM harnesses: `installer/tests/vm/gui-driver.py` (graphical live ISO: + `gui`/`install`/`boot`), `appliance-driver.py`, `serial-driver.py`. + `DISK` must be a disposable qcow2; never point it at `/dev/*`. +- Serve the install fixtures from `/home/dominic/vmlab/serve` with + `python3 -m http.server 8000 --bind 127.0.0.1` (reachable as `10.0.2.2:8000`). ## Definition of a good stopping point diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index bd259a2..e7fc626 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -10,7 +10,7 @@ more interesting. Status vocabulary: **Done**, **Partial**, **Next**, **Later**. | 3 | Port the deterministic core | Done | `phoebus-core` (config, plan, policy, validation, models) | | 4 | Port the destructive backend | Done | `phoebus-executor` (storage, LUKS2, Btrfs, Portage, boot, users, services) | | 5 | **Rust VM boot parity** | Done | Full encrypted UEFI install + boot, zero failed units, 10.7 s | -| 6 | Finish the desktop | Partial | **Mango + DankMaterialShell is the default** (dwl fallback); greetd login; live ISO builds a Mango desktop; graphical-VM verification pending | +| 6 | Finish the desktop | Partial | **Mango + DankMaterialShell is the default** (dwl fallback); greetd login; the live ISO boots the branded welcome + graphical installer and was verified in a graphical VM; installed-desktop verification pending | | 7 | Finish Flatpak | Partial | `flatpak 1.18.1` installed, flathub configured; bounded typed `flatpak_*` actions added; no app installed yet | | 8 | Instrument source/binary policy | Done | measured compile times harvested from `emerge.log` (326 entries); resolved-effect previews added | | 9 | Background update preparation | Partial | distfile fetch VM-verified; `--buildpkgonly` skipped while deps need merging (recorded Ready); activation explicit | @@ -21,6 +21,7 @@ more interesting. Status vocabulary: **Done**, **Partial**, **Next**, **Later**. | 14 | ISO / release pipeline | Partial | manifest/verify/assemble-plan tooling; release gates, atomic publish and signing helpers added; no CI runner has executed a gate | | 15 | Recovery environment | Later | recovery BLS entry generated; snapshot-based recovery entry written at install; full recovery image not built | | — | Rust TUI | Partial | ratatui UI with plan/ERASE and AI provider selection; not yet the default on all paths | +| — | Graphical installer (welcome + wizard) | Partial | Quickshell/QML over the typed `--gui-bridge`; live graphical VM verified, including a detached install+boot; live AI call pending (ADR 0010) | | — | AI-guided install optimization | Partial | DeepSeek/OpenAI/local providers, evidence-gated typed review, mandatory at install with `--no-ai` break-glass; fixture-verified, no live call | | — | Nix as a built-in second lane | Partial | pinned-release bootstrap; `nix-daemon` active and `nix shell nixpkgs#hello` VM-verified; on by default | | — | Git workflow + agent guide | Done | this `docs/` set, `.githooks/`, `scripts/` | diff --git a/docs/STATUS.md b/docs/STATUS.md index 6b3fd6b..3a10b9c 100644 --- a/docs/STATUS.md +++ b/docs/STATUS.md @@ -58,11 +58,15 @@ still not VM-verified. | Source package compilation | yes | yes | yes | n/a | | Kernel install + dracut initramfs | yes | yes | yes | no | | systemd-boot + BLS | yes | yes | yes | no | -| Recovery BLS entry (rescue.target) | yes | yes | no | no | +| Boot default pins the real kernel (not recovery) | yes | yes | yes | no | +| Recovery BLS entry (rescue.target) | yes | yes | boots (not default) | no | | Users, passwords, sudo | yes | yes | yes | n/a | | Locale/timezone/keymap/services | yes | yes | yes | n/a | | Rust VM boot parity | yes | yes | yes | no | | Rust TUI | yes | yes | smoke test | no | +| Typed GUI bridge (`--gui-bridge`) | yes | yes (dry-run) | live VM | n/a | +| Graphical welcome + install wizard (Quickshell) | yes | guards tested | live graphical VM | no | +| Phoebus brand system (SVG + tokens) | yes | yes | live VM | n/a | | Desktop profile (dwl/waybar/mako/swaybg) | yes | partial | headless only | no | | Desktop session script (socket wait, polkit, cleanup) | yes | yes | functional test (stubs) | no | | PipeWire/WirePlumber | yes | no | headless (`wpctl`) | no | @@ -85,9 +89,10 @@ still not VM-verified. | Flatpak/Nix bounded typed actions | yes | yes | no | no | | Desktop session helpers (menu/lock/idle) | yes | yes | functional test (stubs) | no | | Mango + DankMaterialShell profile | yes | yes | live graphical VM yes; installed no | no | -| Mango is the default desktop | yes | yes | install pending | no | +| Mango is the default desktop | yes | yes | live graphical VM yes; installed install pending | no | | greetd login (Mango default, dwl fallback) | yes | yes | no | no | -| Live desktop ISO (Mango + DMS) | yes | guards tested | graphical VM verified | no | +| Live desktop ISO (Mango + DMS) | yes | guards tested | graphical VM + GUI journey + detached boot | no | +| Live welcome autostart + duplicate prevention | yes | guards tested | live graphical VM | no | | GURU packaging (scoped keywords) | yes | yes | no (build/install unverified) | no | | Release gates + atomic publish | yes | yes | no | n/a | | `sys` verbs | yes | yes | yes | no | @@ -123,12 +128,20 @@ still not VM-verified. distinguishes "default in configuration", "successfully built" and "graphically verified". - **The live desktop ISO** (`installer/live/build.sh`) builds a Debian testing - rootfs with Mango + DMS, live-only autologin and an "Install Phoebus" - launcher. Its desktop-payload guards are unit-tested, and the built ISO - (`sha256 c235b873…`) was booted in a graphical, seat-providing VM: Mango, - DMS and Quickshell were running and a `screendump` showed the DMS panel and - welcome window. The **installed** Mango system (GURU + compiled - Quickshell/DMS) and the dwl fallback in a VM are not yet verified. + rootfs with Mango + DMS, live-only autologin, a branded welcome window and a + graphical installer frontend over the typed bridge. Its desktop-payload + guards are unit-tested, and the built ISO + (`sha256 2a52178c…`, 1.6 GiB) was booted in a graphical, seat-providing VM: + the welcome window opened automatically, the installer launched (a second + launch created no duplicate), keyboard navigation reached the network and AI + steps, and advancing without a connected model was refused. The same ISO was + then installed non-interactively (`INSTALL-RC=0`, `NO_SECRET_LEAK`) and + booted **with the ISO detached** (systemd running, 0 failed units, LUKS2, + all Btrfs subvolumes, network). A live AI provider call was **not** possible + (no key in this environment); the AI step is verified as a blocked + prerequisite and with a fixture transport in unit tests. The **installed** + Mango system (GURU + compiled Quickshell/DMS) and the dwl fallback in a VM + are not yet verified. - **AI sandbox** is implemented (`systemd-run` hardening properties, tested at the argv level) and fails closed without `systemd-run`; it has not been exercised in a VM. Only typed actions and the privacy boundary were previously diff --git a/docs/VM-BOOT-VERIFICATION.md b/docs/VM-BOOT-VERIFICATION.md index ea6e96d..f0e8541 100644 --- a/docs/VM-BOOT-VERIFICATION.md +++ b/docs/VM-BOOT-VERIFICATION.md @@ -497,6 +497,61 @@ example `-device virtio-gpu-pci` with the serial console still attached); Until results are recorded here, the default stands by owner decision but no stability is claimed. +## Graphical installer ISO and typed bridge (2026-09-21) + +A dedicated driver, `installer/tests/vm/gui-driver.py`, boots the built live +ISO with a **graphical device** and a serial console, drives the graphical +frontend through the compositor, and captures QEMU framebuffer screenshots. + +Artifact: `installer/live/phoebus-installer-amd64.iso`, 1.6 GiB, +`sha256 2a52178c4b4a71bbc5c011b89533988ceb9aa95493160cb93c4335f03d9a1eee` +(Mango 0.17.2 + DankMaterialShell 1.6.2). + +What was observed (`gui` mode): + +1. The live session autologins into Mango + DMS; the branded + `phoebus-welcome` window opens automatically. The DMS first-run greeter and + changelog dialogs do **not** appear (markers pre-seeded). +2. The welcome shows the wordmark, emblem, wallpaper, ISO version (`0.1.0`) and + readiness (network connected, UEFI, memory, cores), with "Install Phoebus + OS" dominant and the secondary tools plus Advanced present. +3. Launching `phoebus-install` opens the wizard; running it again leaves the + session count at 1 (`DUP n1=1 n2=1`), so duplicate installer sessions are + prevented. +4. Keyboard navigation (Ctrl+Right / Enter / Tab) reaches step 2 (network and + prerequisites, with real UEFI/memory/CPU/network values) and step 3 (AI + model). Provider selection, the secret API-key field and the model field + render; advancing without a connected model is refused with + "Connect and validate an AI model before continuing." +5. A backend probe on the real guest lists `/dev/vda` as unprotected and + selectable, and `/dev/sr0` as the `live_medium` installation medium, + protected (the model tests cover the classification logic). +6. Screenshots: `docs/screenshots/01-welcome.png` … `05-ai-blocked.png`. The + destination-disk, review and confirmation screens + (`06`–`08`) were rendered from the same QML against a dry-run backend + because a real provider call was not available in this environment. + +What was **not** possible: a live AI provider call (no key/model in this +environment). The AI step is verified as a blocked prerequisite and in unit +tests with a fixture transport; it is **not** a passed live call. + +Real install + detached boot on the same ISO (`install` then `boot` modes): + +- Guest install used the same deterministic backend as the GUI + (`phoebus-installer --install --yes --no-ai`): `INSTALL-RC=0`, + `installation complete`, `NO_SECRET_LEAK`. +- Detached boot (no ISO, `-boot order=c`): systemd PID 1, `running`, **0 + failed units**, `systemd-boot` menu shows **Gentoo Linux first**, LUKS2 + unlocked, `/dev/vda1 -> /efi`, `cryptroot` Btrfs with + `/ /home /var /.snapshots /swap`, network up. + +Bug found and fixed during this work: the snapshot recovery BLS entry shared +the kernel's `sort-key`, and the specification's final filename tie-break +(decreasing) made it first when the random machine-id sorted low; with +`default *` the installed system booted `systemd.unit=rescue.target`. Fixed by +pinning `loader.conf` to the newest real kernel entry and giving the recovery +entry `sort-key zzzz-phoebus-recovery`; unit tests pin both. + ## Known remaining work - The graphical session was verified with the **headless** wlroots backend diff --git a/docs/adr/0010-graphical-installer-frontend.md b/docs/adr/0010-graphical-installer-frontend.md new file mode 100644 index 0000000..5a98099 --- /dev/null +++ b/docs/adr/0010-graphical-installer-frontend.md @@ -0,0 +1,86 @@ +# ADR 0010: Graphical installer frontend and typed bridge + +- **Status:** Accepted +- **Date:** 2026-09-21 + +## Context + +The installer ISO boots into Mango + DankMaterialShell, but the only installer +frontend was the ratatui TUI inside a terminal. The product direction makes +installation the ISO's primary purpose: a welcoming, branded entry point and a +coherent graphical setup flow. The core requirement is that the graphical +frontend must not duplicate installation logic or scrape terminal output; the +existing `InstallConfig`, plan, validation, orchestration and executor remain +the single source of truth. + +## Options considered + +1. **A separately compiled Qt/QML application.** Requires shipping and building + more Qt tooling and a non-trivial C++ or Rust/Qt binding layer. +2. **A Quickshell configuration.** Quickshell is already present (DMS is a + Quickshell configuration) and provides windows plus process/socket I/O. A + configuration is plain QML and needs no extra packages. +3. **A terminal TUI only.** Rejected: it is the fallback, not the welcome. + +## Decision + +1. **Quickshell/QML is the graphical frontend**, because it is the desktop's + existing stack, is already in the live ISO, and needs no new package or + build step. There are two configurations: `phoebus-welcome` (the live welcome + and launcher) and `phoebus-install` (the wizard). The TUI/CLI remains a + working fallback and is selected when Quickshell or Wayland is unavailable. +2. **A narrow, typed JSON bridge is the only interface.** A hidden + `phoebus-installer --gui-bridge` mode reads newline-delimited JSON requests + on stdin and writes typed JSON responses and progress events on stdout. The + operations are bounded: `handshake`, `disks`, `set_config`, `set_secrets`, + `validate`, `plan`, `destructive_preview`, `ai_check`, `approve`, + `start_install`, `log_tail`, `quit`. Unknown ops and unknown request fields + fail closed. +3. **The bridge reuses the audited backend.** It constructs the same `Installer` + and calls `Installer::install_observed`, so the graphical install executes + the identical stages, in the same order, with the same + `DestructiveAuthorization` produced by the existing `authorize` flow. A + progress observer (a small trait added to the orchestrator) reports the real + stage transitions; categories name downloads, compilation, configuration and + verification. No percentage is ever estimated. +4. **Approval is bound to the plan.** `approve` records a SHA-256 digest of the + configuration plus the step sequence. `start_install` refuses unless the + presented digest still matches the current plan, so any change — including an + AI-applied change — invalidates a previous approval and forces a re-review. +5. **Secrets go over the stdin pipe, never argv, config or logs.** The GUI sends + the LUKS passphrase, user password and API key through `set_secrets`; the + bridge registers them with the redactor immediately and reports only + presence. The model never receives them. +6. **The frontend is unprivileged.** It runs as the live user and starts the + bridge with `/usr/bin/sudo -n`; only the bridge process holds privilege, and + it exposes no shell. +7. **Live-only and installed surfaces stay separate.** The welcome window, its + autostart and the "Install Phoebus OS" desktop entry are installed only on + the live medium (gated by `/etc/phoebus/live`). The installed desktop has no + reinstall shortcut. Upstream DMS first-run dialogs are suppressed on the live + medium by pre-seeding DMS's own "already welcomed" marker files. +8. **A reusable brand system.** `phoebus-core::brand` defines charcoal, warm + white and restrained amber tokens plus a sun emblem, wordmark and wallpaper + as deterministic SVG, emitted through the existing `--emit-asset` plumbing + and applied to the boot menu, wallpaper, welcome window, installer and icons. + A test pins the QML palette to the Rust tokens. + +## Consequences + +- The frontend cannot diverge from the backend: the protocol is the contract and + the backend is unchanged. +- The bridge and its protocol are fully unit-testable (dry-run) on any host; the + QML is exercised in the disposable graphical VM. +- The recovery-boot default bug exposed during GUI testing was fixed at the + source: `loader.conf` now pins the newest real kernel entry, and the snapshot + recovery entry carries a sort-key that keeps it last, so a low machine-id can + never make the installed system boot into recovery. +- A new frontend means ongoing QML maintenance; it is deliberately small. + +## Verification + +Unit tests cover the protocol, validation wiring, approval binding, +approval invalidation after a config change, blocked AI prerequisite, secret +non-disclosure, readiness facts and the installed dry-run stage sequence. The +GUI journey and a real install + detached boot are verified in the disposable +VM (`docs/VM-BOOT-VERIFICATION.md`). diff --git a/docs/screenshots/01-welcome.png b/docs/screenshots/01-welcome.png new file mode 100644 index 0000000..aff0539 Binary files /dev/null and b/docs/screenshots/01-welcome.png differ diff --git a/docs/screenshots/02-installer-language.png b/docs/screenshots/02-installer-language.png new file mode 100644 index 0000000..7613723 Binary files /dev/null and b/docs/screenshots/02-installer-language.png differ diff --git a/docs/screenshots/03-network-prerequisites.png b/docs/screenshots/03-network-prerequisites.png new file mode 100644 index 0000000..4f8a387 Binary files /dev/null and b/docs/screenshots/03-network-prerequisites.png differ diff --git a/docs/screenshots/04-ai-model.png b/docs/screenshots/04-ai-model.png new file mode 100644 index 0000000..b4f10c2 Binary files /dev/null and b/docs/screenshots/04-ai-model.png differ diff --git a/docs/screenshots/05-ai-blocked.png b/docs/screenshots/05-ai-blocked.png new file mode 100644 index 0000000..36741ae Binary files /dev/null and b/docs/screenshots/05-ai-blocked.png differ diff --git a/docs/screenshots/06-destination-disk.png b/docs/screenshots/06-destination-disk.png new file mode 100644 index 0000000..34b83dd Binary files /dev/null and b/docs/screenshots/06-destination-disk.png differ diff --git a/docs/screenshots/07-review.png b/docs/screenshots/07-review.png new file mode 100644 index 0000000..0ce70f8 Binary files /dev/null and b/docs/screenshots/07-review.png differ diff --git a/docs/screenshots/08-confirm.png b/docs/screenshots/08-confirm.png new file mode 100644 index 0000000..2a5f897 Binary files /dev/null and b/docs/screenshots/08-confirm.png differ diff --git a/docs/screenshots/README.md b/docs/screenshots/README.md new file mode 100644 index 0000000..c7bd7cd --- /dev/null +++ b/docs/screenshots/README.md @@ -0,0 +1,18 @@ +# Screenshots + +Captured from the graphical installer ISO during the 2026-09-21 verification. +See `docs/VM-BOOT-VERIFICATION.md` for the commands and results. + +| File | Source | Notes | +|------|--------|-------| +| `01-welcome.png` | disposable graphical VM | Live welcome window, autostarted | +| `02-installer-language.png` | disposable graphical VM | Wizard opened from the welcome action | +| `03-network-prerequisites.png` | disposable graphical VM | Real UEFI/memory/CPU/network values | +| `04-ai-model.png` | disposable graphical VM | Provider, secret key field, model | +| `05-ai-blocked.png` | disposable graphical VM | Advancing without a model is refused | +| `06-destination-disk.png` | host QML preview (dry-run backend) | No live AI call was possible in the VM, so the disk/review/confirm steps were rendered from the same QML against a dry-run backend. Protected disks and the reason are shown; in the VM `/dev/sr0` is additionally labelled the installation medium. | +| `07-review.png` | host QML preview | Plan/erase review | +| `08-confirm.png` | host QML preview | ERASE authorization | + +The VM screenshots are the authoritative evidence for the graphical journey. +The host-preview screenshots are layout evidence only and are labelled as such. diff --git a/installer-rs/crates/phoebus-core/src/boot.rs b/installer-rs/crates/phoebus-core/src/boot.rs index bce17e2..9150ad7 100644 --- a/installer-rs/crates/phoebus-core/src/boot.rs +++ b/installer-rs/crates/phoebus-core/src/boot.rs @@ -112,6 +112,20 @@ impl BlsEntry { entry.title = title.to_string(); entry } + + /// Return a copy whose `sort-key` is `key`. Used to keep the recovery entry + /// sorted after the normal kernel entries: the specification's final + /// tie-break is by file name in decreasing order, so a recovery entry that + /// inherits the kernel's sort-key can otherwise sort first (and, with + /// `default *`, boot the installed system into recovery). + pub fn with_sort_key(&self, key: &str) -> Self { + let mut entry = self.clone(); + entry + .extra + .retain(|line| !line.trim_start().starts_with("sort-key")); + entry.extra.push(format!("sort-key {key}")); + entry + } } /// Replace the `rootflags=subvol=` component of a kernel command line. @@ -243,6 +257,21 @@ mod tests { assert!(updated.options.contains("rootfstype=btrfs")); } + #[test] + fn with_sort_key_replaces_an_inherited_key() { + let with_key = "title Gentoo Linux\n\ + linux /abcd/6.12.9/linux\n\ + sort-key gentoo\n\ + options root=/dev/x\n"; + let entry = BlsEntry::parse("abcd-6.12.9.conf", with_key).unwrap(); + let recovery = entry.with_sort_key("zzzz-phoebus-recovery"); + let rendered = recovery.render(); + assert!(rendered.contains("sort-key zzzz-phoebus-recovery")); + assert!(!rendered.contains("sort-key gentoo")); + // The kernel sort-key sorts before the recovery one (A-Z increasing). + assert!("gentoo" < "zzzz-phoebus-recovery"); + } + #[test] fn replace_handles_missing_subvol_and_rejects_empty() { assert!(replace_root_subvol("root=/dev/x rootflags=rw", "@new") diff --git a/installer-rs/crates/phoebus-core/src/brand.rs b/installer-rs/crates/phoebus-core/src/brand.rs new file mode 100644 index 0000000..359bf02 --- /dev/null +++ b/installer-rs/crates/phoebus-core/src/brand.rs @@ -0,0 +1,270 @@ +//! Phoebus visual identity: a small, reusable branding system. +//! +//! Everything here is deterministic text so it can be emitted by the static +//! installer (see `--emit-asset`) and unit-tested without a display. The same +//! assets are used by the live desktop, the boot menu, the welcome window and +//! the graphical installer, so the identity never diverges between surfaces. +//! +//! Palette (established here because none existed): charcoal, warm white and +//! restrained amber accents. Tokens are exported as JSON for the Quickshell/QML +//! frontend so no surface hard-codes its own copy. + +use serde::Serialize; + +/// The shared colour tokens. Contrast on `charcoal`/`surface` is checked by the +/// tests, so a token change that breaks readability fails the build. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +pub struct Palette { + /// Page/backdrop charcoal. + pub charcoal: &'static str, + /// Raised surface (cards, panels). + pub surface: &'static str, + /// Hairline border. + pub border: &'static str, + /// Primary body text: warm white. + pub warm_white: &'static str, + /// Secondary/muted text. + pub muted: &'static str, + /// Restrained amber accent (primary action, focus). + pub amber: &'static str, + /// Deeper amber for pressed/hover states. + pub amber_deep: &'static str, + /// Success. + pub success: &'static str, + /// Warning. + pub warning: &'static str, + /// Danger / destructive. + pub danger: &'static str, +} + +pub const PALETTE: Palette = Palette { + charcoal: "#17171b", + surface: "#232329", + border: "#3a3a42", + warm_white: "#f4efe6", + muted: "#a8a29a", + amber: "#e8a33d", + amber_deep: "#c97f24", + success: "#7fb069", + warning: "#e0a24a", + danger: "#d2564b", +}; + +/// Parse a `#rrggbb` token into `(r, g, b)`; used for the contrast tests. +pub fn rgb(hex: &str) -> (u8, u8, u8) { + let h = hex.trim_start_matches('#'); + ( + u8::from_str_radix(&h[0..2], 16).expect("red"), + u8::from_str_radix(&h[2..4], 16).expect("green"), + u8::from_str_radix(&h[4..6], 16).expect("blue"), + ) +} + +/// WCAG relative luminance. +pub fn relative_luminance(hex: &str) -> f64 { + fn channel(c: u8) -> f64 { + let c = c as f64 / 255.0; + if c <= 0.03928 { + c / 12.92 + } else { + ((c + 0.055) / 1.055).powf(2.4) + } + } + let (r, g, b) = rgb(hex); + 0.2126 * channel(r) + 0.7152 * channel(g) + 0.0722 * channel(b) +} + +/// WCAG contrast ratio between two `#rrggbb` colours. +pub fn contrast_ratio(a: &str, b: &str) -> f64 { + let (la, lb) = (relative_luminance(a), relative_luminance(b)); + let (hi, lo) = if la > lb { (la, lb) } else { (lb, la) }; + (hi + 0.05) / (lo + 0.05) +} + +/// The colour tokens as a stable JSON document consumed by the QML frontend. +pub fn palette_json() -> String { + serde_json::to_string_pretty(&PALETTE).expect("palette serialises") +} + +/// The sun-inspired emblem: a warm core, a soft ring and tapered rays. Kept as +/// a single, scalable vector with no external references. +pub const EMBLEM_SVG: &str = r##" + Phoebus OS + + + + + + + + + + + + + + + + + + + + + + + + + +"##; + +/// The wordmark for headers and the boot menu. Text is drawn with the generic +/// `sans-serif` family so it renders in any environment; the emblem is inlined +/// so the file is self-contained. +pub const WORDMARK_SVG: &str = r##" + Phoebus OS + + + + + + + + + + + + + + + PHOEBUS + OS + +"##; + +/// The live wallpaper: charcoal field, a soft horizon glow and a faint emblem. +/// Emitted as SVG so it scales to any display without a raster build step. +pub const WALLPAPER_SVG: &str = r##" + + + + + + + + + + + + + + + + + + + PHOEBUS + +"##; + +/// A named branding asset, for the existing `--emit-asset` plumbing. +pub fn brand_asset(name: &str) -> Option { + Some(match name { + "brand-emblem" => EMBLEM_SVG.to_string(), + "brand-wordmark" => WORDMARK_SVG.to_string(), + "brand-wallpaper" => WALLPAPER_SVG.to_string(), + "brand-tokens" => palette_json(), + _ => return None, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn assert_svg(doc: &str) { + assert!( + doc.trim_start().starts_with("")); + assert!(doc.contains("viewBox=")); + assert!(!doc.contains("http://") || doc.contains("http://www.w3.org/2000/svg")); + } + + #[test] + fn assets_are_well_formed_svg() { + assert_svg(EMBLEM_SVG); + assert_svg(WORDMARK_SVG); + assert_svg(WALLPAPER_SVG); + } + + #[test] + fn assets_use_the_shared_palette() { + for doc in [EMBLEM_SVG, WORDMARK_SVG, WALLPAPER_SVG] { + assert!( + doc.contains(PALETTE.amber) || doc.contains(PALETTE.amber_deep), + "asset is missing the amber accent" + ); + assert!( + doc.contains(PALETTE.warm_white) || doc.contains(PALETTE.charcoal), + "asset is missing a core palette colour" + ); + } + } + + #[test] + fn wordmark_names_the_product() { + assert!(WORDMARK_SVG.contains("PHOEBUS")); + assert!(WORDMARK_SVG.contains("OS")); + } + + #[test] + fn palette_tokens_are_valid_hex_and_readable() { + let all = [ + PALETTE.charcoal, + PALETTE.surface, + PALETTE.border, + PALETTE.warm_white, + PALETTE.muted, + PALETTE.amber, + PALETTE.amber_deep, + PALETTE.success, + PALETTE.warning, + PALETTE.danger, + ]; + for token in all { + assert_eq!(token.len(), 7, "token {token} is not #rrggbb"); + assert!(token.starts_with('#')); + assert!(token[1..].chars().all(|c| c.is_ascii_hexdigit())); + } + // Body text must clear WCAG AA (4.5:1) on both page and surface. + assert!(contrast_ratio(PALETTE.warm_white, PALETTE.charcoal) >= 4.5); + assert!(contrast_ratio(PALETTE.warm_white, PALETTE.surface) >= 4.5); + // Accent text/controls clear AA as large/UI text (3:1). + assert!(contrast_ratio(PALETTE.amber, PALETTE.charcoal) >= 3.0); + // Muted text still clears AA on the page. + assert!(contrast_ratio(PALETTE.muted, PALETTE.charcoal) >= 4.5); + } + + #[test] + fn tokens_round_trip_as_json() { + let json = palette_json(); + let back: serde_json::Value = serde_json::from_str(&json).unwrap(); + assert_eq!(back["charcoal"], serde_json::json!(PALETTE.charcoal)); + assert_eq!(back["amber"], serde_json::json!(PALETTE.amber)); + assert!(json.contains("charcoal")); + } + + #[test] + fn named_lookup_is_exact() { + for name in [ + "brand-emblem", + "brand-wordmark", + "brand-wallpaper", + "brand-tokens", + ] { + assert!(brand_asset(name).is_some(), "{name} missing"); + } + assert!(brand_asset("brand-nope").is_none()); + } +} diff --git a/installer-rs/crates/phoebus-core/src/lib.rs b/installer-rs/crates/phoebus-core/src/lib.rs index 5abf82d..22e4aa7 100644 --- a/installer-rs/crates/phoebus-core/src/lib.rs +++ b/installer-rs/crates/phoebus-core/src/lib.rs @@ -5,6 +5,7 @@ pub mod action; pub mod boot; +pub mod brand; pub mod config; pub mod disk; pub mod effects; diff --git a/installer-rs/crates/phoebus-core/src/system.rs b/installer-rs/crates/phoebus-core/src/system.rs index ea6fcde..d95cf4b 100644 --- a/installer-rs/crates/phoebus-core/src/system.rs +++ b/installer-rs/crates/phoebus-core/src/system.rs @@ -814,6 +814,13 @@ elif [ "$started" = 0 ]; then echo "phoebus-session-mango: dms not found; the shell will not start" >&2 fi +# Live medium only: open the branded welcome/installation launcher once the +# session is up. The marker exists only on the live rootfs, so an installed +# system never starts it. This never authorizes or starts disk changes. +if [ -e /etc/phoebus/live ] && command -v phoebus-welcome >/dev/null 2>&1; then + start_helper phoebus-welcome +fi + # Run until the compositor exits; the EXIT trap stops the shell and helpers. wait "$MANGO_PID" "#; @@ -992,6 +999,7 @@ pub fn desktop_asset(name: &str) -> Option { "session-dwl" => PHOEBUS_SESSION_SCRIPT.to_string(), "assistant" => PHOEBUS_ASSISTANT_SCRIPT.to_string(), "install" => PHOEBUS_INSTALL_SCRIPT.to_string(), + "welcome" => PHOEBUS_WELCOME_SCRIPT.to_string(), "menu" => PHOEBUS_MENU_SCRIPT.to_string(), "lock" => PHOEBUS_LOCK_SCRIPT.to_string(), "idle" => PHOEBUS_IDLE_SCRIPT.to_string(), @@ -1004,47 +1012,57 @@ pub fn desktop_asset(name: &str) -> Option { "greetd-live" => greetd_config_live(LIVE_USER, live_cmd), "wayland-session-mango" => wayland_session_entry(DesktopProfile::Mango)?.1, "wayland-session-dwl" => wayland_session_entry(DesktopProfile::Dwl)?.1, - _ => return None, + // The brand system lives in `brand`; route the shared `--emit-asset` + // plumbing through it so the live build has one source of assets. + _ => return crate::brand::brand_asset(name), }) } -/// `phoebus-install`: open the existing installer UI. It never starts a -/// destructive operation by itself: the plan, disk protection, AI requirement, -/// credential handling and the ERASE confirmation all stay in force. +/// `phoebus-install`: open the graphical installer frontend, falling back to +/// the deterministic TUI/CLI. It never starts a destructive operation by +/// itself: the plan, disk protection, AI requirement, credential handling and +/// the ERASE confirmation all stay in force. A second invocation never opens a +/// duplicate installer session. pub const PHOEBUS_INSTALL_SCRIPT: &str = r#"#!/bin/bash # Open the Phoebus installer. This only launches the installer UI; the user # still reviews the plan, supplies credentials and confirms ERASE. set -u + +# Prevent duplicate installer sessions. Quickshell's --no-duplicate also +# guards this, but the check lets us tell the user why nothing opened. +if pgrep -f "quickshell.*phoebus-install" >/dev/null 2>&1; then + echo "The Phoebus installer is already open." >&2 + exit 0 +fi + +# The graphical installer is the primary path; it needs a Wayland session. +if [ "${XDG_SESSION_TYPE:-}" = "wayland" ] || [ -n "${WAYLAND_DISPLAY:-}" ]; then + if command -v quickshell >/dev/null 2>&1 \ + && [ -f /etc/xdg/quickshell/phoebus-install/shell.qml ]; then + exec quickshell --no-duplicate -c phoebus-install + fi +fi + +# Deterministic fallback (TUI, then CLI) works with no model and no Wayland. conf="/etc/phoebus/install.conf" args=() [ -f "$conf" ] && args+=(--config "$conf") -run() { - local installer="" - for candidate in \ - /run/live/medium/phoebus/bin/phoebus \ - /phoebus/bin/phoebus \ - /usr/local/bin/phoebus-installer \ - phoebus-installer; do - if command -v "$candidate" >/dev/null 2>&1; then - installer="$candidate" - break - fi - done - if [ -z "$installer" ]; then - echo "phoebus-install: installer not found" >&2 - return 1 +installer="" +for candidate in /usr/local/bin/phoebus-installer phoebus-installer; do + if command -v "$candidate" >/dev/null 2>&1; then + installer="$candidate" + break fi - if [ "$(id -u)" -eq 0 ]; then - "$installer" "${args[@]}" - else - sudo -n "$installer" "${args[@]}" - fi -} +done +if [ -z "$installer" ]; then + echo "phoebus-install: installer not found" >&2 + exit 1 +fi # Re-entrant wrapper: the inner invocation (inside the terminal) just runs. if [ "${1:-}" = "--in-terminal" ]; then - run + "$installer" "${args[@]}" rc=$? echo read -rp "Press Enter to close" _ || true @@ -1052,24 +1070,45 @@ if [ "${1:-}" = "--in-terminal" ]; then fi if command -v kitty >/dev/null 2>&1; then - exec kitty --title "Install Phoebus" -e "$0" --in-terminal + exec kitty --title "Install Phoebus OS" -e "$0" --in-terminal fi -run +if [ "$(id -u)" -eq 0 ]; then + exec "$installer" "${args[@]}" +else + exec sudo -n "$installer" "${args[@]}" +fi +"#; + +/// `phoebus-welcome`: open (or focus, via the single-instance guard) the live +/// welcome window. Only installed on the live medium. +pub const PHOEBUS_WELCOME_SCRIPT: &str = r#"#!/bin/bash +# Live-medium welcome and installation launcher. +set -u +if pgrep -f "quickshell.*phoebus-welcome" >/dev/null 2>&1; then + exit 0 +fi +if command -v quickshell >/dev/null 2>&1 \ + && [ -f /etc/xdg/quickshell/phoebus-welcome/shell.qml ]; then + exec quickshell --no-duplicate -c phoebus-welcome +fi +echo "phoebus-welcome: quickshell or the welcome config is missing" >&2 +exit 1 "#; /// The application entry that makes the installer discoverable in the desktop -/// launcher ("Install Phoebus"). +/// launcher ("Install Phoebus OS"). It is live-medium only. pub const PHOEBUS_INSTALL_DESKTOP_ENTRY: &str = "\ [Desktop Entry]\n\ Type=Application\n\ -Name=Install Phoebus\n\ +Name=Install Phoebus OS\n\ +GenericName=System installer\n\ Comment=Install Phoebus OS to disk\n\ Exec=/usr/local/bin/phoebus-install\n\ TryExec=/usr/local/bin/phoebus-install\n\ -Icon=system-software-install\n\ +Icon=phoebus\n\ Terminal=false\n\ -Categories=System;\n\ -Keywords=install;phoebus;\n"; +Categories=System;Settings;\n\ +Keywords=install;phoebus;setup;\n"; /// Btrfs mount options, matching the proven behavior. pub fn btrfs_mount_opts(compress: &str, ssd: bool) -> String { diff --git a/installer-rs/crates/phoebus-executor/src/boot.rs b/installer-rs/crates/phoebus-executor/src/boot.rs index 8e7d775..43ce005 100644 --- a/installer-rs/crates/phoebus-executor/src/boot.rs +++ b/installer-rs/crates/phoebus-executor/src/boot.rs @@ -48,14 +48,56 @@ pub fn install_systemd_boot(exec: &Exec, config: &InstallConfig) -> Result<()> { pub fn write_loader_conf(exec: &Exec, config: &InstallConfig) -> Result<()> { let dir = esp_path(exec, config).join("loader"); std::fs::create_dir_all(&dir).map_err(|e| ExecError::io(dir.clone(), e))?; - let text = "# systemd-boot configuration\ndefault *\ntimeout 3\nconsole-mode keep\neditor no\n"; + // Pin the default to the newest real kernel entry. `default *` picks the + // first entry by systemd-boot's ordering, and the recovery entry (written + // later) can sort first, which would boot the installed system into rescue + // mode by default. + let default = default_entry_id(&dir.join("entries")).unwrap_or_else(|| "*".to_string()); + let text = format!( + "# systemd-boot configuration\ndefault {default}\ntimeout 3\nconsole-mode keep\neditor no\n" + ); std::fs::write(dir.join("loader.conf"), text) .map_err(|e| ExecError::io(dir.join("loader.conf"), e))?; - exec.logger - .info(format!("wrote {}", dir.join("loader.conf").display())); + exec.logger.info(format!( + "wrote {} (default {default})", + dir.join("loader.conf").display() + )); Ok(()) } +/// The id (file name without `.conf`) of the newest non-recovery kernel entry, +/// so `loader.conf` can pin it as the default. +fn default_entry_id(entries: &Path) -> Option { + use phoebus_core::boot::{version_key, BlsEntry}; + let mut best: Option<(Vec, String)> = None; + for entry in std::fs::read_dir(entries).ok()? { + let entry = entry.ok()?; + let path = entry.path(); + if path.extension().and_then(|e| e.to_str()) != Some("conf") { + continue; + } + let name = entry.file_name().to_string_lossy().to_string(); + if name.starts_with("phoebus-") { + continue; + } + let id = name.trim_end_matches(".conf").to_string(); + let Ok(text) = std::fs::read_to_string(&path) else { + continue; + }; + let Some(parsed) = BlsEntry::parse(&name, &text) else { + continue; + }; + let key = parsed + .kernel_version() + .map(|v| version_key(&v)) + .unwrap_or_default(); + if best.as_ref().map(|(k, _)| key > *k).unwrap_or(true) { + best = Some((key, id)); + } + } + best.map(|(_, id)| id) +} + pub fn generate_entries(exec: &Exec) -> Result<()> { portage::chroot(exec, Path::new(&exec.root), "kernel-install", &["add-all"]) } @@ -219,6 +261,9 @@ pub fn write_snapshot_recovery_entry( .with_root_subvol(&subvol) .map_err(|e| ExecError::operation("boot_install", "rewrite recovery entry", e))? .with_title("Phoebus Recovery (known-good snapshot)") + // Force the recovery entry to sort after every normal kernel entry, so + // it can never become the default by filename tie-break. + .with_sort_key("zzzz-phoebus-recovery") .with_option("ro systemd.unit=rescue.target"); let dest = entries.join("phoebus-recovery.conf"); std::fs::write(&dest, recovery.render()).map_err(|e| ExecError::io(dest.clone(), e))?; @@ -297,4 +342,37 @@ mod tests { assert!(text.contains("/token/6.18.48/initrd")); assert!(text.contains("systemd.unit=rescue.target")); } + + #[test] + fn loader_default_is_the_newest_normal_entry_not_a_recovery_entry() { + let dir = tempfile::tempdir().unwrap(); + let entries = dir.path(); + std::fs::write( + entries.join("gentoo-6.18.48.conf"), + "title Gentoo Linux\nlinux /gentoo/6.18.48/linux\noptions root=/dev/mapper/cryptroot rw quiet\n", + ) + .unwrap(); + std::fs::write( + entries.join("gentoo-6.19.2.conf"), + "title Gentoo Linux\nlinux /gentoo/6.19.2/linux\noptions root=/dev/mapper/cryptroot rw quiet\n", + ) + .unwrap(); + std::fs::write( + entries.join("phoebus-recovery.conf"), + "title Phoebus Recovery (known-good snapshot)\nlinux /gentoo/6.19.2/linux\noptions ro systemd.unit=rescue.target\n", + ) + .unwrap(); + assert_eq!(default_entry_id(entries).as_deref(), Some("gentoo-6.19.2")); + } + + #[test] + fn loader_default_is_none_without_a_normal_entry() { + let dir = tempfile::tempdir().unwrap(); + std::fs::write( + dir.path().join("phoebus-recovery.conf"), + "title Recovery\nlinux /gentoo/6.19.2/linux\noptions ro systemd.unit=rescue.target\n", + ) + .unwrap(); + assert_eq!(default_entry_id(dir.path()), None); + } } diff --git a/installer-rs/crates/phoebus-executor/src/desktop.rs b/installer-rs/crates/phoebus-executor/src/desktop.rs index 56d56e1..aa5d70a 100644 --- a/installer-rs/crates/phoebus-executor/src/desktop.rs +++ b/installer-rs/crates/phoebus-executor/src/desktop.rs @@ -64,17 +64,9 @@ pub fn write_session_script(exec: &Exec, config: &InstallConfig) -> Result<()> { sysgen::PHOEBUS_ASSISTANT_SCRIPT, )?; - // "Install Phoebus": discoverable in the launcher, opens the installer UI - // without starting any destructive operation. - write_script( - &target, - "usr/local/bin/phoebus-install", - sysgen::PHOEBUS_INSTALL_SCRIPT, - )?; - target.write( - "usr/share/applications/phoebus-install.desktop", - sysgen::PHOEBUS_INSTALL_DESKTOP_ENTRY, - )?; + // The "Install Phoebus OS" entry point and welcome launcher are live-medium + // only: an installed system has no business offering to reinstall itself. + // They are installed by the live build, not here. match config.desktop.profile { DesktopProfile::Mango => { @@ -370,7 +362,7 @@ mod tests { } #[test] - fn mango_profile_configures_greetd_login_and_install_launcher() { + fn mango_profile_configures_greetd_login_and_no_install_shortcut() { let runner = RecordingRunner::new(); let exec = make_exec(runner.clone()); let mut cfg = InstallConfig::default(); @@ -378,13 +370,14 @@ mod tests { write_session_script(&exec, &cfg).unwrap(); configure_login(&exec, &cfg).unwrap(); - for rel in [ - "usr/local/bin/phoebus-install", - "usr/share/applications/phoebus-install.desktop", - "etc/greetd/config.toml", - ] { - assert!(exec.root.join(rel).is_file(), "{rel} was not installed"); - } + assert!(exec.root.join("etc/greetd/config.toml").is_file()); + // The installer shortcut is live-medium only; an installed system must + // not advertise a reinstall entry point. + assert!(!exec.root.join("usr/local/bin/phoebus-install").exists()); + assert!(!exec + .root + .join("usr/share/applications/phoebus-install.desktop") + .exists()); let login = std::fs::read_to_string(exec.root.join("etc/greetd/config.toml")).unwrap(); assert!(login.contains("phoebus-session-mango")); assert!(login.contains("tuigreet")); @@ -398,6 +391,22 @@ mod tests { assert!(commands.iter().any(|a| a.contains("useradd"))); } + #[test] + fn live_autostart_is_gated_on_the_live_marker() { + let runner = RecordingRunner::new(); + let exec = make_exec(runner); + let mut cfg = InstallConfig::default(); + cfg.desktop.profile = DesktopProfile::Mango; + write_session_script(&exec, &cfg).unwrap(); + let mango = + std::fs::read_to_string(exec.root.join("usr/local/bin/phoebus-session-mango")).unwrap(); + assert!( + mango.contains("/etc/phoebus/live"), + "the welcome autostart must be gated on the live marker" + ); + assert!(mango.contains("phoebus-welcome")); + } + #[test] fn explicit_none_writes_no_login_configuration() { let runner = RecordingRunner::new(); diff --git a/installer-rs/crates/phoebus-executor/src/probe.rs b/installer-rs/crates/phoebus-executor/src/probe.rs index fcad908..4d9c9b8 100644 --- a/installer-rs/crates/phoebus-executor/src/probe.rs +++ b/installer-rs/crates/phoebus-executor/src/probe.rs @@ -318,6 +318,10 @@ fn live_source_disks(runner: &dyn ProcessRunner) -> Vec { "/", "/run/initramfs", "/run/live", + // Debian live-boot mounts the medium here; the ISO/medium device must + // be identified so the installer can label and protect it. + "/run/live/medium", + "/run/live/rootfs", "/mnt/cdrom", "/mnt/live", "/lib/live", diff --git a/installer-rs/crates/phoebus-installer/src/gui_bridge.rs b/installer-rs/crates/phoebus-installer/src/gui_bridge.rs new file mode 100644 index 0000000..4edb69b --- /dev/null +++ b/installer-rs/crates/phoebus-installer/src/gui_bridge.rs @@ -0,0 +1,1153 @@ +//! Typed graphical frontend bridge. +//! +//! The Quickshell/QML installer never parses terminal output and never touches +//! disks: it speaks newline-delimited JSON to this bridge over stdin/stdout. +//! The bridge owns one [`Installer`] and is the only thing that can reach the +//! deterministic backend. It reuses `InstallConfig`, validation, the plan, the +//! audited [`DestructiveAuthorization`] flow and `Installer::install_observed`, +//! so the graphical path cannot diverge from the TUI/CLI path. +//! +//! Secrets arrive over the stdin pipe (never argv, logs, config files or model +//! context) and are registered with the redactor immediately. Progress events +//! report the real backend stages; categories name the kind of work, and no +//! percentage is ever invented. +//! +//! Run with `phoebus-installer --gui-bridge`. + +use std::io::{self, BufRead, Write}; + +use crate::{ai_guide, InstallObserver, Installer}; +use phoebus_ai::provider::{ModelTransport, ProviderKind, SystemFacts}; +use phoebus_core::{InstallConfig, InstallStep, SecretString}; +use phoebus_executor::ai::CurlTransport; +use phoebus_executor::auth::{authorize, Confirmation}; +use phoebus_executor::{Exec, Result as ExecResult}; + +use serde::Deserialize; +use serde_json::{json, Value}; + +/// The version of the bridge protocol understood by the QML frontend. +pub const PROTOCOL_VERSION: u32 = 1; + +const MAX_LOG_TAIL: usize = 200; + +// --------------------------------------------------------------------------- +// Protocol types +// --------------------------------------------------------------------------- + +#[derive(Debug, Deserialize)] +#[serde(deny_unknown_fields)] +struct Request { + id: u64, + op: String, + #[serde(default)] + config: Option, + #[serde(default)] + secrets: Option, + #[serde(default)] + erase: Option, + #[serde(default)] + final_confirm: Option, + #[serde(default)] + plan_digest: Option, + #[serde(default)] + lines: Option, +} + +#[derive(Debug, Default, Deserialize)] +#[serde(deny_unknown_fields)] +struct SecretsPatch { + #[serde(default)] + luks: Option, + #[serde(default)] + user_password: Option, + #[serde(default)] + root_password: Option, + #[serde(default)] + ai_api_key: Option, +} + +/// A `Confirmation` whose answers come from an explicit GUI request. The ERASE +/// phrase is checked here, so the audited [`authorize`] flow is unchanged. +struct BridgeConfirm { + erase: bool, + final_ok: bool, +} + +impl Confirmation for BridgeConfirm { + fn confirm_erase(&self, _preview: &str) -> ExecResult { + Ok(self.erase) + } + fn confirm_final(&self, _message: &str) -> ExecResult { + Ok(self.final_ok) + } +} + +/// Writes progress events for the real backend stages and records the coarse +/// disk-change phase so a failure can be explained accurately. +struct JsonObserver<'a> { + out: &'a mut dyn Write, + id: u64, + phase: std::rc::Rc>, +} + +impl JsonObserver<'_> { + fn emit(&mut self, step: InstallStep, status: &str, error: Option<&str>) { + let (category, label) = step_meta(step); + let event = json!({ + "event": "progress", + "id": self.id, + "op": "start_install", + "stage": step.name(), + "category": category, + "label": label, + "status": status, + "error": error, + }); + let _ = write_json(self.out, &event); + } +} + +impl InstallObserver for JsonObserver<'_> { + fn stage_started(&mut self, step: InstallStep) { + if step == InstallStep::StoragePrepare { + self.phase.set(DiskPhase::InStorage); + } + self.emit(step, "started", None); + } + fn stage_finished(&mut self, step: InstallStep, error: Option<&str>) { + if step == InstallStep::StoragePrepare && error.is_none() { + self.phase.set(DiskPhase::AfterStorage); + } + self.emit( + step, + if error.is_some() { + "failed" + } else { + "finished" + }, + error, + ); + } +} + +/// Category + human label for a backend stage. Categories are the four the +/// product distinguishes (download, compile, configure, verify) plus prepare. +fn step_meta(step: InstallStep) -> (&'static str, &'static str) { + match step { + InstallStep::StoragePrepare => ("prepare", "Preparing the target disk"), + InstallStep::StageInstall => ("download", "Downloading the Gentoo stage3"), + InstallStep::FstabGenerate => ("configure", "Writing filesystem tables"), + InstallStep::PortageConfigure => ("download", "Configuring and syncing Portage"), + InstallStep::PackagesBase => ("compile", "Installing base packages"), + InstallStep::KernelInstall => ("compile", "Building and installing the kernel"), + InstallStep::BootInstall => ("configure", "Installing the boot loader"), + InstallStep::UsersConfigure => ("configure", "Creating your account"), + InstallStep::ServicesConfigure => ("configure", "Enabling system services"), + InstallStep::DesktopInstall => ("compile", "Installing the desktop"), + InstallStep::Finalize => ("verify", "Finalising and verifying"), + } +} + +// --------------------------------------------------------------------------- +// Bridge +// --------------------------------------------------------------------------- + +pub struct Bridge { + installer: Installer, + luks: Option, + user_password: Option, + root_password: Option, + api_key: Option, + approved_digest: Option, + phase: std::rc::Rc>, + quit: bool, +} + +impl Bridge { + pub fn new(config: InstallConfig, exec: Exec) -> Self { + let installer = Installer::new(config, exec); + Self { + installer, + luks: None, + user_password: None, + root_password: None, + api_key: None, + approved_digest: None, + phase: std::rc::Rc::new(std::cell::Cell::new(DiskPhase::BeforeStorage)), + quit: false, + } + } + + /// Build directly on an installer (tests, embedded callers). + pub fn with_installer(installer: Installer) -> Self { + Self { + installer, + luks: None, + user_password: None, + root_password: None, + api_key: None, + approved_digest: None, + phase: std::rc::Rc::new(std::cell::Cell::new(DiskPhase::BeforeStorage)), + quit: false, + } + } + + /// Whether the caller asked the bridge to stop. + pub fn should_quit(&self) -> bool { + self.quit + } + + /// Parse and dispatch one request line, writing events/responses to `out`. + pub fn handle_line(&mut self, line: &str, out: &mut dyn Write) -> io::Result<()> { + let line = line.trim(); + if line.is_empty() { + return Ok(()); + } + let request: Request = match serde_json::from_str(line) { + Ok(request) => request, + Err(e) => { + return write_json( + out, + &json!({ "ok": false, "error": format!("bad request: {e}") }), + ) + } + }; + self.dispatch(request, out) + } + + fn dispatch(&mut self, request: Request, out: &mut dyn Write) -> io::Result<()> { + let id = request.id; + let op = request.op.clone(); + let result = match request.op.as_str() { + "handshake" => self.handshake(), + "disks" => self.disks(), + "set_config" => self.set_config(&request), + "set_secrets" => self.set_secrets(&request), + "validate" => self.validate(), + "plan" => self.plan(), + "destructive_preview" => self.destructive_preview(), + "ai_check" => self.ai_check(), + "approve" => self.approve(&request), + "start_install" => return self.start_install(id, &request, out), + "log_tail" => self.log_tail(&request), + "quit" => { + self.quit = true; + Ok(json!({ "bye": true })) + } + other => Err(format!("unknown op `{other}`")), + }; + + match result { + Ok(data) => write_json( + out, + &json!({ "id": id, "ok": true, "op": op, "data": data }), + ), + Err(error) => write_json( + out, + &json!({ "id": id, "ok": false, "op": op, "error": error }), + ), + } + } + + // -- read-only ops ------------------------------------------------------ + + fn handshake(&self) -> Result { + let facts = self.installer.system_facts(); + let network = network_ready(); + Ok(json!({ + "protocol": PROTOCOL_VERSION, + "version": phoebus_core::VERSION, + "iso_version": iso_version(), + "build_id": std::env::var("PHOEBUS_BUILD_ID").unwrap_or_else(|_| "dev".into()), + "live": std::path::Path::new("/etc/phoebus/live").exists(), + "defaults": self.installer.config, + "readiness": { + "network": network, + "firmware": self.installer.hardware.firmware_str(), + "memory_mib": self.installer.hardware.memory_mib, + "cpu_cores": self.installer.hardware.cpu.cores, + "cpu_model": self.installer.hardware.cpu.model, + "desktop": self.installer.config.desktop.profile.as_str(), + }, + "facts": facts, + })) + } + + fn disks(&mut self) -> Result { + self.installer.disks = + phoebus_executor::probe::probe_disks(self.installer.exec.runner.as_ref()); + let runner = self.installer.exec.runner.as_ref(); + let disks: Vec = self + .installer + .disks + .iter() + .map(|d| { + let partitions = phoebus_executor::probe::disk_partitions(runner, &d.path); + json!({ + "path": d.path, + "identifier": d.path, + "model": d.model.clone().unwrap_or_else(|| "Unknown disk".into()), + "size_bytes": d.size_bytes, + "size_human": d.size_human(), + "transport": d.transport.clone().unwrap_or_else(|| "unknown".into()), + "removable": d.removable, + "protected": d.is_protected(), + "protection": d.protection().map(|r| r.describe()), + "live_medium": d.live_media, + "kind": format!("{:?}", d.kind).to_lowercase(), + "partitions": partitions, + }) + }) + .collect(); + Ok(json!({ "disks": disks })) + } + + fn validate(&self) -> Result { + let issues = self.installer.validate(); + let complete = issues.is_empty(); + Ok(json!({ + "complete": complete, + "issues": issues.iter().map(|i| json!({ + "field": i.field, + "message": i.message, + })).collect::>(), + })) + } + + fn plan(&self) -> Result { + let issues = self.installer.validate(); + let plan = self.installer.plan(); + Ok(json!({ + "human": self.installer.render_plan(), + "plan_digest": self.plan_digest(), + "steps": plan.steps.iter().map(|s| json!({ + "stage": s.name(), + "category": step_meta(*s).0, + "label": step_meta(*s).1, + })).collect::>(), + "validation": issues.iter().map(|i| json!({ + "field": i.field, + "message": i.message, + })).collect::>(), + "review": self.review(), + })) + } + + fn destructive_preview(&self) -> Result { + Ok(json!({ + "text": self.installer.destructive_preview(), + "plan_digest": self.plan_digest(), + })) + } + + fn log_tail(&self, request: &Request) -> Result { + let path = self.installer.exec.log_path().to_path_buf(); + let text = std::fs::read_to_string(&path).unwrap_or_default(); + let want = request.lines.unwrap_or(40).min(MAX_LOG_TAIL); + // The logger already redacted, but re-redact on read so a rotated or + // externally-written file can never leak a registered secret. + let redacted = self.installer.exec.redactor().redact(&text); + let lines: Vec<&str> = redacted.lines().rev().take(want).collect(); + let tail: Vec<&str> = lines.into_iter().rev().collect(); + Ok(json!({ + "path": path.display().to_string(), + "lines": tail, + })) + } + + // -- configuration ------------------------------------------------------ + + fn set_config(&mut self, request: &Request) -> Result { + let mut config: InstallConfig = serde_json::from_value( + request + .config + .clone() + .ok_or_else(|| "set_config requires a `config` object".to_string())?, + ) + .map_err(|e| format!("invalid configuration: {e}"))?; + + // Secrets never live in the configuration. Reject an attempt to smuggle + // one in, rather than silently persisting it. + if config + .to_toml_string() + .map(|t| contains_secret_marker(&t)) + .unwrap_or(false) + { + return Err("configuration must not contain secret material".into()); + } + // The bridge is an installer for this machine; the dry-run/log paths are + // backend concerns and not user-selectable from the GUI. + config.runtime.dry_run = self.installer.config.runtime.dry_run; + + self.installer.reconfigure(config); + self.approved_digest = None; + let issues = self.installer.validate(); + Ok(json!({ + "accepted": true, + "plan_digest": self.plan_digest(), + "complete": issues.is_empty(), + "issues": issues.iter().map(|i| json!({ + "field": i.field, + "message": i.message, + })).collect::>(), + })) + } + + fn set_secrets(&mut self, request: &Request) -> Result { + let patch = request + .secrets + .as_ref() + .ok_or_else(|| "set_secrets requires a `secrets` object".to_string())?; + if let Some(v) = &patch.luks { + let s = SecretString::new(v.clone()); + self.installer.exec.register_secret(&s); + self.luks = Some(s); + } + if let Some(v) = &patch.user_password { + let s = SecretString::new(v.clone()); + self.installer.exec.register_secret(&s); + self.user_password = Some(s); + } + if let Some(v) = &patch.root_password { + let s = SecretString::new(v.clone()); + self.installer.exec.register_secret(&s); + self.root_password = Some(s); + } + if let Some(v) = &patch.ai_api_key { + let s = SecretString::new(v.clone()); + self.installer.exec.register_secret(&s); + self.api_key = Some(s); + } + // Report only presence, never values. + Ok(json!({ + "luks_set": self.luks.is_some(), + "user_password_set": self.user_password.is_some(), + "root_password_set": self.root_password.is_some(), + "ai_api_key_set": self.api_key.is_some(), + })) + } + + // -- AI ----------------------------------------------------------------- + + fn ai_check(&mut self) -> Result { + let facts = self.installer.system_facts(); + let api_key_present = self.api_key.is_some(); + let Bridge { + installer, + api_key, + approved_digest, + .. + } = self; + let Installer { exec, config, .. } = installer; + let transport = CurlTransport::new(exec, api_key.clone()); + let value = review_proposal(config, exec.redactor(), facts, api_key_present, &transport)?; + *approved_digest = None; + Ok(value) + } + + /// Validate the provider connection and review the proposal (fail-closed). + /// Exposed so tests can drive it with a canned transport. + pub fn ai_check_with(&mut self, transport: &dyn ModelTransport) -> Result { + let facts = self.installer.system_facts(); + let api_key_present = self.api_key.is_some(); + let Bridge { + installer, + approved_digest, + .. + } = self; + let Installer { exec, config, .. } = installer; + let value = review_proposal(config, exec.redactor(), facts, api_key_present, transport)?; + *approved_digest = None; + Ok(value) + } + + // -- authorization and install ------------------------------------------ + + fn approve(&mut self, request: &Request) -> Result { + let phrase = request.erase.clone().unwrap_or_default(); + if phrase != "ERASE" { + return Err("type ERASE exactly to authorize disk changes".into()); + } + if request.final_confirm != Some(true) { + return Err("the final confirmation is required".into()); + } + let digest = self.plan_digest(); + self.approved_digest = Some(digest.clone()); + Ok(json!({ "approved": true, "plan_digest": digest })) + } + + fn start_install(&mut self, id: u64, request: &Request, out: &mut dyn Write) -> io::Result<()> { + let result = self.run_install(id, request, out); + match result { + Ok(data) => write_json( + out, + &json!({ "id": id, "ok": true, "op": "start_install", "data": data }), + ), + Err(error) => write_json( + out, + &json!({ "id": id, "ok": false, "op": "start_install", "error": error }), + ), + } + } + + fn run_install( + &mut self, + id: u64, + request: &Request, + out: &mut dyn Write, + ) -> Result { + // The plan may not have changed since the user approved it. + let current = self.plan_digest(); + match (&self.approved_digest, &request.plan_digest) { + (Some(approved), Some(presented)) if approved == presented && presented == ¤t => { + } + _ => { + return Err( + "the installation plan is not approved (or changed since approval); \ + review the plan and confirm ERASE again" + .into(), + ) + } + } + + // AI is mandatory to install unless this is a dry run or an explicit + // break-glass (mirrors the CLI rule). + let dry_run = self.installer.config.runtime.dry_run; + if !dry_run { + let provider = ProviderKind::parse(&self.installer.config.ai.provider) + .unwrap_or(ProviderKind::None); + let break_glass = std::env::var("PHOEBUS_NO_AI") + .map(|v| matches!(v.to_ascii_lowercase().as_str(), "1" | "yes" | "true")) + .unwrap_or(false); + if provider == ProviderKind::None && !break_glass { + return Err( + "installing Phoebus requires a connected AI model; connect a provider \ + or set PHOEBUS_NO_AI=1 for a deterministic install" + .into(), + ); + } + } + + let issues = self.installer.validate(); + if !issues.is_empty() { + let text = issues + .iter() + .map(|i| i.to_string()) + .collect::>() + .join("; "); + return Err(format!("configuration is incomplete: {text}")); + } + + let preview = self.installer.destructive_preview(); + let confirm = BridgeConfirm { + erase: request.erase.as_deref() == Some("ERASE"), + final_ok: request.final_confirm == Some(true), + }; + let auth = authorize(&confirm, &preview, "Start the installation now?") + .map_err(|e| self.installer.exec.redactor().redact(&e.to_string()))?; + + let mut observer = JsonObserver { + out, + id, + phase: self.phase.clone(), + }; + self.phase.set(DiskPhase::BeforeStorage); + let outcome = self.installer.install_observed( + &auth, + self.luks.as_ref(), + self.user_password.as_ref(), + self.root_password.as_ref(), + &mut observer, + ); + + match outcome { + Ok(()) => Ok(json!({ + "complete": true, + "dry_run": dry_run, + "log_path": self.installer.exec.log_path().display().to_string(), + "next_actions": [ + "Remove the installation medium.", + "Restart the computer and boot Phoebus OS.", + ], + })), + Err(e) => { + let message = self.installer.exec.redactor().redact(&e.to_string()); + let (disk_changed, next_actions) = disk_change_report(self.phase.get()); + Err(format!( + "installation failed: {message}\n\ + disk_changed: {disk_changed}\n\ + next: {}", + next_actions.join(" ") + )) + } + } + } + + // -- helpers ------------------------------------------------------------ + + /// A stable digest binding an approval to the exact plan shown. Any change + /// to the configuration (including AI-applied changes) changes it. + fn plan_digest(&self) -> String { + config_digest(&self.installer.config) + } + + fn review(&self) -> Value { + let c = &self.installer.config; + let mut subsystems = vec![c.system.init_system.clone()]; + if c.desktop.profile.is_desktop() { + subsystems.push(c.desktop.audio_stack.clone()); + if c.desktop.flatpak { + subsystems.push("flatpak".into()); + } + } + if c.packages.nix { + subsystems.push("nix".into()); + } + if c.storage.filesystem == phoebus_core::Filesystem::Btrfs { + subsystems.push("btrfs snapshots".into()); + } + json!({ + "target_disk": c.storage.disk, + "erase": self.installer.destructive_preview(), + "filesystem": c.storage.filesystem.as_str(), + "encryption": c.encryption.mode.as_str(), + "desktop": c.desktop.profile.as_str(), + "subvolumes": c.storage.subvols, + "subsystems": subsystems, + "hostname": c.system.hostname, + "username": c.user.username, + "timezone": c.system.timezone, + "locale": c.system.locale, + "keymap": c.system.keymap, + }) + } +} + +fn contains_secret_marker(toml: &str) -> bool { + let lower = toml.to_ascii_lowercase(); + ["passphrase", "password", "api_key", "secret"] + .iter() + .any(|m| lower.contains(m)) +} + +/// Coarse phase of the last reported progress event, used to explain whether +/// disk changes occurred. Updated by the observer from the real stage order. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum DiskPhase { + BeforeStorage, + InStorage, + AfterStorage, +} + +fn disk_change_report(phase: DiskPhase) -> (&'static str, Vec<&'static str>) { + match phase { + DiskPhase::BeforeStorage => ( + "none", + vec!["Review the installer log, then retry the installation."], + ), + DiskPhase::InStorage => ( + "partial", + vec![ + "The target disk may have been partially modified.", + "Review the installer log before retrying.", + ], + ), + DiskPhase::AfterStorage => ( + "yes", + vec![ + "The target disk was re-partitioned.", + "Review the installer log, then restart the installation (the disk is re-created from scratch).", + ], + ), + } +} + +/// True when a default route exists. Read-only, no privileges. +fn network_ready() -> bool { + let Ok(text) = std::fs::read_to_string("/proc/net/route") else { + return false; + }; + text.lines().skip(1).any(|line| { + let mut fields = line.split_whitespace(); + let _iface = fields.next(); + matches!(fields.next(), Some("00000000")) + }) +} + +fn iso_version() -> String { + if let Ok(text) = std::fs::read_to_string("/etc/phoebus/version") { + let t = text.trim(); + if !t.is_empty() { + return t.to_string(); + } + } + phoebus_core::VERSION.to_string() +} + +fn write_json(out: &mut dyn Write, value: &Value) -> io::Result<()> { + serde_json::to_writer(&mut *out, value)?; + out.write_all(b"\n")?; + out.flush() +} + +/// A deterministic digest of the configuration plus the step sequence. Any +/// material change to the plan changes the digest, invalidating an approval. +fn config_digest(config: &InstallConfig) -> String { + use sha2::{Digest, Sha256}; + let mut hasher = Sha256::new(); + hasher.update(config.to_toml_string().unwrap_or_default().as_bytes()); + for step in InstallStep::sequence() { + hasher.update(step.name().as_bytes()); + } + format!("{:x}", hasher.finalize()) +} + +/// Parse the provider from the configuration, validate the connection and apply +/// the reviewed proposal. This is the same `ai_guide` path the TUI uses. +fn review_proposal( + config: &mut InstallConfig, + redactor: &phoebus_core::Redactor, + facts: SystemFacts, + api_key_present: bool, + transport: &dyn ModelTransport, +) -> Result { + let raw = config.ai.provider.clone(); + let provider = + ProviderKind::parse(&raw).ok_or_else(|| format!("unknown AI provider `{raw}`"))?; + if provider == ProviderKind::None { + return Err("no AI provider selected".into()); + } + let endpoint = if config.ai.endpoint.is_empty() { + provider.endpoint().to_string() + } else { + config.ai.endpoint.clone() + }; + let model = if config.ai.model.is_empty() { + provider.default_model().to_string() + } else { + config.ai.model.clone() + }; + if provider.requires_key() && !api_key_present { + return Err(format!( + "provider `{}` requires an API key", + provider.as_str() + )); + } + + let outcome = + ai_guide::generate_and_review_at(config, &facts, provider, &endpoint, &model, transport) + .map_err(|e| { + // Error messages are redacted before they reach the GUI. + format!( + "connection or proposal failed: {}", + redactor.redact(&e.to_string()) + ) + })?; + let applied: Vec = outcome + .applied + .iter() + .map(|c| { + json!({ + "description": c.description, + "reason": c.reason, + "evidence": c.evidence, + }) + }) + .collect(); + Ok(json!({ + "connected": true, + "provider": provider.as_str(), + "model": model, + "endpoint": endpoint, + "applied": applied, + "config": config, + "plan_digest": config_digest(config), + })) +} + +/// The stdio entry point used by `--gui-bridge`. +pub fn run_stdio() -> io::Result<()> { + let mut config = InstallConfig::default(); + // Test/automation hook: a dry run is non-destructive, so it is safe to + // expose through the environment for the harness. It never changes the + // authorization requirements. + if std::env::var("PHOEBUS_DRY_RUN") + .map(|v| matches!(v.to_ascii_lowercase().as_str(), "1" | "yes" | "true")) + .unwrap_or(false) + { + config.runtime.dry_run = true; + } + let mut state_dir = std::path::PathBuf::from(&config.runtime.state_dir); + if std::fs::create_dir_all(&state_dir).is_err() { + state_dir = std::path::PathBuf::from("/tmp/phoebus-installer"); + std::fs::create_dir_all(&state_dir).ok(); + } + let logger = phoebus_executor::Logger::open( + state_dir.join("install.log"), + phoebus_core::Redactor::new(), + false, + ); + let exec = Exec::new( + Box::new(phoebus_executor::RealRunner), + logger, + config.runtime.dry_run, + config.storage.install_root.clone(), + state_dir, + ); + let mut bridge = Bridge::new(config, exec); + + let stdin = io::stdin(); + let stdout = io::stdout(); + let mut out = stdout.lock(); + for line in stdin.lock().lines() { + let line = line?; + bridge.handle_line(&line, &mut out)?; + if bridge.should_quit() { + break; + } + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use phoebus_ai::provider::TestTransport; + use phoebus_core::{Disk, DiskKind, Redactor}; + use phoebus_executor::{Logger, RecordingRunner}; + + fn test_bridge() -> Bridge { + let runner = RecordingRunner::new(); + let dir = tempfile::tempdir().unwrap().keep(); + let logger = Logger::open(dir.join("install.log"), Redactor::new(), false); + let mut config = InstallConfig::default(); + // The bridge preserves the backend's dry-run flag; set it on the + // installer so the whole staged flow runs without touching a disk. + config.runtime.dry_run = true; + config.system.hostname = "phoebus".into(); + config.system.timezone = "UTC".into(); + config.user.username = "tester".into(); + config.storage.disk = "/dev/vda".into(); + let exec = Exec::new( + Box::new(runner), + logger, + true, + dir.join("root"), + dir.clone(), + ); + let mut installer = Installer::new(config, exec); + installer.disks.push(Disk { + path: "/dev/vda".into(), + model: Some("QEMU HARDDISK".into()), + size_bytes: 30 * 1024 * 1024 * 1024, + transport: Some("virtio".into()), + removable: false, + read_only: false, + mounted: false, + is_block_device: true, + kind: DiskKind::Physical, + live_media: false, + }); + Bridge::with_installer(installer) + } + + fn call(bridge: &mut Bridge, request: &str) -> Vec { + let mut out: Vec = Vec::new(); + bridge.handle_line(request, &mut out).unwrap(); + String::from_utf8(out) + .unwrap() + .lines() + .filter(|l| !l.trim().is_empty()) + .map(|l| serde_json::from_str(l).expect("json line")) + .collect() + } + + fn response(lines: &[Value]) -> Value { + lines + .iter() + .find(|v| v.get("ok").is_some()) + .cloned() + .expect("a response line") + } + + fn config_json(bridge: &Bridge) -> Value { + serde_json::to_value(&bridge.installer.config).unwrap() + } + + fn set_valid_config(bridge: &mut Bridge) -> Value { + let mut c = config_json(bridge); + c["system"]["hostname"] = json!("phoebus-box"); + c["user"]["username"] = json!("tester"); + c["storage"]["disk"] = json!("/dev/vda"); + let req = json!({ "id": 2, "op": "set_config", "config": c }); + let lines = call(bridge, &req.to_string()); + response(&lines) + } + + fn approve(bridge: &mut Bridge) -> (String, Value) { + let req = json!({ + "id": 90, + "op": "approve", + "erase": "ERASE", + "final_confirm": true + }); + let lines = call(bridge, &req.to_string()); + let resp = response(&lines); + let digest = resp["data"]["plan_digest"].as_str().unwrap().to_string(); + (digest, resp) + } + + #[test] + fn handshake_reports_protocol_and_readiness() { + let mut bridge = test_bridge(); + let lines = call(&mut bridge, r#"{"id":1,"op":"handshake"}"#); + let resp = response(&lines); + assert_eq!(resp["ok"], json!(true)); + assert_eq!(resp["data"]["protocol"], json!(PROTOCOL_VERSION)); + assert!(resp["data"]["readiness"]["memory_mib"].is_number()); + assert_eq!( + resp["data"]["defaults"]["desktop"]["profile"], + json!("mango") + ); + } + + #[test] + fn validate_reports_missing_user_and_disk() { + let mut bridge = test_bridge(); + // Strip the valid user/disk to prove validation is wired through. + let mut c = config_json(&bridge); + c["user"]["username"] = json!(""); + c["storage"]["disk"] = json!(""); + let _ = call( + &mut bridge, + &json!({ "id": 2, "op": "set_config", "config": c }).to_string(), + ); + let lines = call(&mut bridge, r#"{"id":3,"op":"validate"}"#); + let resp = response(&lines); + assert_eq!(resp["data"]["complete"], json!(false)); + let fields: Vec<&str> = resp["data"]["issues"] + .as_array() + .unwrap() + .iter() + .map(|i| i["field"].as_str().unwrap()) + .collect(); + assert!(fields.contains(&"username")); + assert!(fields.contains(&"target_disk")); + } + + #[test] + fn plan_review_carries_the_backend_facts() { + let mut bridge = test_bridge(); + set_valid_config(&mut bridge); + let lines = call(&mut bridge, r#"{"id":4,"op":"plan"}"#); + let resp = response(&lines); + assert_eq!(resp["ok"], json!(true)); + assert_eq!(resp["data"]["review"]["target_disk"], json!("/dev/vda")); + assert_eq!(resp["data"]["review"]["encryption"], json!("luks2")); + assert_eq!(resp["data"]["review"]["desktop"], json!("mango")); + let subsystems = resp["data"]["review"]["subsystems"].as_array().unwrap(); + for want in ["systemd", "pipewire", "flatpak", "nix"] { + assert!( + subsystems.iter().any(|s| s == want), + "review is missing subsystem {want}" + ); + } + assert!(resp["data"]["human"] + .as_str() + .unwrap() + .contains("Installation plan")); + } + + #[test] + fn destructive_preview_matches_the_plan_digest() { + let mut bridge = test_bridge(); + set_valid_config(&mut bridge); + let lines = call(&mut bridge, r#"{"id":5,"op":"destructive_preview"}"#); + let resp = response(&lines); + let digest = resp["data"]["plan_digest"].as_str().unwrap().to_string(); + assert_eq!(digest, bridge.plan_digest()); + assert!(resp["data"]["text"] + .as_str() + .unwrap() + .contains("ALL DATA ON THIS DEVICE WILL BE DESTROYED.")); + } + + #[test] + fn approval_requires_erase_and_final_confirmation() { + let mut bridge = test_bridge(); + set_valid_config(&mut bridge); + let wrong = call( + &mut bridge, + r#"{"id":6,"op":"approve","erase":"erase","final_confirm":true}"#, + ); + assert_eq!(response(&wrong)["ok"], json!(false)); + let no_final = call( + &mut bridge, + r#"{"id":7,"op":"approve","erase":"ERASE","final_confirm":false}"#, + ); + assert_eq!(response(&no_final)["ok"], json!(false)); + let (_, ok) = approve(&mut bridge); + assert_eq!(ok["ok"], json!(true)); + } + + #[test] + fn start_install_requires_a_matching_approval() { + let mut bridge = test_bridge(); + set_valid_config(&mut bridge); + // No approval at all. + let none = call( + &mut bridge, + r#"{"id":8,"op":"start_install","erase":"ERASE","final_confirm":true}"#, + ); + assert_eq!(response(&none)["ok"], json!(false)); + + // A stale digest (the plan changed after approval) is refused. + let (digest, _) = approve(&mut bridge); + let mut c = config_json(&bridge); + c["system"]["hostname"] = json!("changed-after-approval"); + let _ = call( + &mut bridge, + &json!({ "id": 9, "op": "set_config", "config": c }).to_string(), + ); + let stale = call( + &mut bridge, + &json!({ + "id": 10, "op": "start_install", "erase": "ERASE", + "final_confirm": true, "plan_digest": digest + }) + .to_string(), + ); + assert_eq!(response(&stale)["ok"], json!(false)); + } + + #[test] + fn approved_dry_run_completes_and_reports_real_stages() { + let mut bridge = test_bridge(); + set_valid_config(&mut bridge); + let (digest, _) = approve(&mut bridge); + let lines = call( + &mut bridge, + &json!({ + "id": 11, "op": "start_install", "erase": "ERASE", + "final_confirm": true, "plan_digest": digest + }) + .to_string(), + ); + let resp = response(&lines); + assert_eq!(resp["ok"], json!(true), "response: {resp}"); + assert_eq!(resp["data"]["complete"], json!(true)); + assert_eq!(resp["data"]["dry_run"], json!(true)); + + // The real stage sequence was emitted with categories, not percentages. + let events: Vec<&Value> = lines + .iter() + .filter(|v| v.get("event") == Some(&json!("progress"))) + .collect(); + let started: Vec<&str> = events + .iter() + .filter(|e| e["status"] == json!("started")) + .map(|e| e["stage"].as_str().unwrap()) + .collect(); + assert_eq!(started.first(), Some(&"storage_prepare")); + assert_eq!(started.last(), Some(&"finalize")); + assert!(events.iter().all(|e| e["category"].is_string())); + assert!( + events.iter().all(|e| e.get("percent").is_none()), + "no invented percentage may appear" + ); + } + + #[test] + fn ai_check_applies_a_reviewed_proposal_and_voids_approval() { + let mut bridge = test_bridge(); + set_valid_config(&mut bridge); + let (_, _) = approve(&mut bridge); + let mut c = config_json(&bridge); + c["ai"]["provider"] = json!("deepseek"); + c["ai"]["model"] = json!("deepseek-chat"); + let _ = call( + &mut bridge, + &json!({ "id": 12, "op": "set_config", "config": c }).to_string(), + ); + let _ = call( + &mut bridge, + r#"{"id":19,"op":"set_secrets","secrets":{"ai_api_key":"test-key"}}"#, + ); + let proposal = r#"{"version":1,"changes":[{"action":"set_kernel_profile","value":"safe"}],"rationale":[{"action":"set_kernel_profile","reason":"stability","evidence":["proven boot"]}]}"#; + let transport = TestTransport::proposal(proposal); + let value = bridge.ai_check_with(&transport).unwrap(); + assert_eq!(value["connected"], json!(true)); + assert_eq!( + value["applied"][0]["description"], + json!("kernel profile = safe") + ); + assert_eq!( + bridge.installer.config.kernel.profile, + phoebus_core::KernelProfile::Safe + ); + assert!(bridge.approved_digest.is_none()); + } + + #[test] + fn ai_check_fails_closed_without_a_provider() { + let mut bridge = test_bridge(); + let transport = TestTransport::proposal(r#"{"version":1,"changes":[]}"#); + assert!(bridge.ai_check_with(&transport).is_err()); + } + + #[test] + fn secrets_never_appear_in_responses_and_the_log() { + let mut bridge = test_bridge(); + set_valid_config(&mut bridge); + let secret = "correct-horse-battery-staple"; + let req = json!({ + "id": 13, "op": "set_secrets", + "secrets": { "luks": secret, "user_password": secret } + }); + let lines = call(&mut bridge, &req.to_string()); + assert_eq!(response(&lines)["data"]["luks_set"], json!(true)); + // Presence only, never the value. + assert!(!lines.iter().any(|v| v.to_string().contains(secret))); + + // A log tail is redacted too. + let tail = call(&mut bridge, r#"{"id":14,"op":"log_tail","lines":100}"#); + assert!(!response(&tail).to_string().contains(secret)); + } + + #[test] + fn unknown_ops_and_unknown_fields_fail_closed() { + let mut bridge = test_bridge(); + assert_eq!( + response(&call(&mut bridge, r#"{"id":15,"op":"nope"}"#))["ok"], + json!(false) + ); + assert_eq!( + response(&call( + &mut bridge, + r#"{"id":16,"op":"handshake","surprise":true}"# + ))["ok"], + json!(false) + ); + } + + #[test] + fn config_may_not_smuggle_a_secret() { + let mut bridge = test_bridge(); + let mut c = config_json(&bridge); + c["system"]["distro_name"] = json!("passphrase is hunter2"); + let lines = call( + &mut bridge, + &json!({ "id": 17, "op": "set_config", "config": c }).to_string(), + ); + assert_eq!(response(&lines)["ok"], json!(false)); + } + + #[test] + fn quit_is_reported() { + let mut bridge = test_bridge(); + let lines = call(&mut bridge, r#"{"id":18,"op":"quit"}"#); + assert_eq!(response(&lines)["data"]["bye"], json!(true)); + assert!(bridge.should_quit()); + } +} diff --git a/installer-rs/crates/phoebus-installer/src/lib.rs b/installer-rs/crates/phoebus-installer/src/lib.rs index dfed239..8fd1f1e 100644 --- a/installer-rs/crates/phoebus-installer/src/lib.rs +++ b/installer-rs/crates/phoebus-installer/src/lib.rs @@ -1,7 +1,8 @@ //! Phoebus installer orchestration and CLI support. pub mod ai_guide; +pub mod gui_bridge; pub mod orchestrate; pub mod release; -pub use orchestrate::Installer; +pub use orchestrate::{InstallObserver, Installer, NoopObserver}; diff --git a/installer-rs/crates/phoebus-installer/src/main.rs b/installer-rs/crates/phoebus-installer/src/main.rs index d1a3809..3219b77 100644 --- a/installer-rs/crates/phoebus-installer/src/main.rs +++ b/installer-rs/crates/phoebus-installer/src/main.rs @@ -115,6 +115,11 @@ struct Cli { /// Used by the live ISO build so it reuses the installer's exact assets. #[arg(long, value_name = "NAME", hide = true)] emit_asset: Option, + + /// Speak the typed JSON protocol used by the graphical installer frontend + /// (stdin/stdout). Not intended for direct interactive use. + #[arg(long, hide = true)] + gui_bridge: bool, } struct TerminalConfirm; @@ -265,6 +270,11 @@ fn main() -> ExitCode { fn run() -> std::result::Result> { let cli = Cli::parse(); + if cli.gui_bridge { + phoebus_installer::gui_bridge::run_stdio()?; + return Ok(ExitCode::SUCCESS); + } + if let Some(name) = &cli.emit_asset { return match phoebus_core::system::desktop_asset(name) { Some(text) => { diff --git a/installer-rs/crates/phoebus-installer/src/orchestrate.rs b/installer-rs/crates/phoebus-installer/src/orchestrate.rs index 1e36a5d..4f4f957 100644 --- a/installer-rs/crates/phoebus-installer/src/orchestrate.rs +++ b/installer-rs/crates/phoebus-installer/src/orchestrate.rs @@ -27,6 +27,23 @@ pub struct Installer { pub state: StorageState, } +/// Receives stage transitions during [`Installer::install_observed`]. The GUI +/// bridge uses this to show real backend stages; it is deliberately a narrow +/// trait so no frontend can influence execution. +pub trait InstallObserver { + fn stage_started(&mut self, step: phoebus_core::InstallStep); + /// `error` is `None` on success, otherwise a redactable message. + fn stage_finished(&mut self, step: phoebus_core::InstallStep, error: Option<&str>); +} + +/// Does nothing; the default for callers that do not report progress. +pub struct NoopObserver; + +impl InstallObserver for NoopObserver { + fn stage_started(&mut self, _step: phoebus_core::InstallStep) {} + fn stage_finished(&mut self, _step: phoebus_core::InstallStep, _error: Option<&str>) {} +} + impl Installer { pub fn new(config: InstallConfig, exec: Exec) -> Self { let hardware = probe::probe_hardware(exec.runner.as_ref()); @@ -64,6 +81,21 @@ impl Installer { InstallPlan::for_config(&self.config) } + /// Replace the configuration after a frontend edit, recomputing the derived + /// policy context so package decisions reflect the new selection. Hardware + /// and disks are unchanged by a configuration edit. + pub fn reconfigure(&mut self, config: InstallConfig) { + let binhost_available = config.packages.binary_packages + && !phoebus_core::system::resolved_binhost_uri(&config).is_empty(); + self.policy_ctx = PolicyContext { + policy: config.packages.policy, + binhost_available, + memory_mib: self.hardware.memory_mib, + cores: self.hardware.cpu.cores, + }; + self.config = config; + } + pub fn render_plan(&self) -> String { self.plan().render_human(&self.config, Some(&self.hardware)) } @@ -144,14 +176,36 @@ impl Installer { luks_passphrase: Option<&SecretString>, user_password: Option<&SecretString>, root_password: Option<&SecretString>, + ) -> Result<()> { + self.install_observed( + auth, + luks_passphrase, + user_password, + root_password, + &mut NoopObserver, + ) + } + + /// As [`Installer::install`], reporting each stage to `observer`. This is + /// the real executor loop, not a re-implementation: the observer only sees + /// transitions the backend actually performs. + pub fn install_observed( + &mut self, + auth: &phoebus_executor::DestructiveAuthorization, + luks_passphrase: Option<&SecretString>, + user_password: Option<&SecretString>, + root_password: Option<&SecretString>, + observer: &mut dyn InstallObserver, ) -> Result<()> { let steps = self.plan().steps.clone(); for step in steps { let name = step.name(); self.exec.logger.section(name); + observer.stage_started(step); let result = self.run_step(step, auth, luks_passphrase, user_password, root_password); if let Err(e) = result { self.exec.logger.error(format!("stage failed: {name}: {e}")); + observer.stage_finished(step, Some(&self.exec.redactor().redact(&e.to_string()))); if !self.exec.dry_run { let _ = self.exec.export_log(); let _ = self.exec.umount_chroot(); @@ -159,6 +213,7 @@ impl Installer { return Err(e); } self.exec.logger.info(format!("stage complete: {name}")); + observer.stage_finished(step, None); } Ok(()) } diff --git a/installer-rs/crates/phoebus-installer/tests/live_iso.rs b/installer-rs/crates/phoebus-installer/tests/live_iso.rs index 5cefe3b..8425de9 100644 --- a/installer-rs/crates/phoebus-installer/tests/live_iso.rs +++ b/installer-rs/crates/phoebus-installer/tests/live_iso.rs @@ -147,3 +147,82 @@ fn build_script_is_syntax_declared_shell() { assert!(build.contains("mksquashfs")); let _ = Path::new("."); } + +#[test] +fn live_build_installs_the_branded_launcher_and_marker() { + let build = read("installer/live/build.sh"); + // The welcome/installer Quickshell configs and branding are part of the + // payload, and the live marker gates live-only autostart. + for needle in [ + "etc/xdg/quickshell/phoebus-welcome", + "etc/xdg/quickshell/phoebus-install", + "phoebus-welcome", + "usr/share/phoebus/branding", + "etc/phoebus/live", + "brand-wallpaper", + "splash.png", + ] { + assert!(build.contains(needle), "build.sh is missing {needle}"); + } + // The live help text is shipped and read by the welcome window. + let help = read("installer/live/install-help.txt"); + assert!(help.contains("ERASE")); + assert!(help.contains("LUKS2")); +} + +#[test] +fn assets_include_the_welcome_launcher_and_branding() { + let welcome = system::desktop_asset("welcome").expect("welcome asset"); + assert!(welcome.contains("quickshell --no-duplicate -c phoebus-welcome")); + // Duplicate installer sessions are prevented. + let install = system::desktop_asset("install").expect("install asset"); + assert!(install.contains("quickshell --no-duplicate -c phoebus-install")); + assert!(install.contains("pgrep -f")); + // Branding assets are reachable through the same `--emit-asset` dispatch. + for name in [ + "brand-emblem", + "brand-wordmark", + "brand-wallpaper", + "brand-tokens", + ] { + assert!(system::desktop_asset(name).is_some(), "{name} missing"); + } +} + +#[test] +fn installed_session_never_starts_the_welcome() { + // The live-only marker is the gate; the installed session script must not + // autostart the welcome unless the marker exists. + let script = system::desktop_asset("session-mango").unwrap(); + assert!(script.contains("/etc/phoebus/live")); + assert!(script.contains("phoebus-welcome")); +} + +#[test] +fn qml_theme_matches_the_backend_palette() { + let qml = read("installer/live/desktop/common/Theme.qml"); + for token in [ + phoebus_core::brand::PALETTE.charcoal, + phoebus_core::brand::PALETTE.surface, + phoebus_core::brand::PALETTE.border, + phoebus_core::brand::PALETTE.warm_white, + phoebus_core::brand::PALETTE.muted, + phoebus_core::brand::PALETTE.amber, + phoebus_core::brand::PALETTE.amber_deep, + phoebus_core::brand::PALETTE.success, + phoebus_core::brand::PALETTE.warning, + phoebus_core::brand::PALETTE.danger, + ] { + assert!( + qml.contains(token), + "Theme.qml is missing brand token {token}" + ); + } +} + +#[test] +fn installer_help_is_available_to_the_gui() { + let help = read("installer/live/install-help.txt"); + assert!(help.contains("deterministic `sys`")); + assert!(help.contains("installation medium")); +} diff --git a/installer/live/README.md b/installer/live/README.md index 1dbfa96..e43bb28 100644 --- a/installer/live/README.md +++ b/installer/live/README.md @@ -20,15 +20,21 @@ The build runs entirely unprivileged and never touches a host disk: provides wlroots 0.20, scenefx 0.5 and quickshell, which Mango and DMS need. The Debian archive keyring is fetched from Debian and handed to mmdebstrap. 3. A customize hook (`livefs-hook.sh`) runs inside the rootfs: it creates the - unprivileged `phoebus` user, installs the shared session assets emitted by - the static installer (`phoebus-installer --emit-asset ...`), **builds Mango - from source**, installs the pinned DMS release, and enables `greetd`, - networking and the serial console. -4. The rootfs is extracted as the current user and packed with `mksquashfs + unprivileged `phoebus` user, **builds Mango from source**, installs the + pinned DMS release, and enables `greetd`, networking and the serial console. +4. After the rootfs is extracted, `build.sh` installs the live payload: + the static installer, the shared desktop assets emitted by + `phoebus-installer --emit-asset`, the **branding** (emblem, wordmark, + wallpaper, tokens), the **Quickshell welcome/installer configs**, the + live-only marker `/etc/phoebus/live`, the version/build files, the help + text, and DMS's "already welcomed" markers. Keeping this post-extract lets + `PHOEBUS_REUSE_ROOTFS=1` pick up asset changes without a new mmdebstrap. +5. The rootfs is extracted as the current user and packed with `mksquashfs -all-root`; a tmpfiles rule restores the live user's home ownership at boot. -5. The base Debian-Live ISO (`base.sha256`) is used only for its boot - equipment: the live squashfs, kernel, initramfs and a serial-patched GRUB - configuration are replaced, and `xorriso -boot_image any keep` preserves the +6. The base Debian-Live ISO (`base.sha256`) is used only for its boot + equipment: the live squashfs, kernel, initramfs and a serial-patched, + **Phoebus-branded** GRUB configuration (menu names, colours and a rasterised + wallpaper) are replaced, and `xorriso -boot_image any keep` preserves the UEFI/BIOS boot path. No `curl | sh`, no live/git packages, and signature verification is never @@ -63,15 +69,33 @@ launcher is missing; it never silently emits a text-only ISO. - It auto-boots to a serial-visible live system and **logs in automatically** as `phoebus` (only on the live medium). -- The graphical session starts automatically. The **Install Phoebus** entry in - the launcher opens the installer UI; it never starts a destructive operation - by itself (the plan, disk protection, AI requirement, credential handling and - the `ERASE` confirmation all remain in force). +- The graphical session starts automatically and opens the branded **Phoebus + welcome** window: "Install Phoebus OS" is the dominant action, with network, + display/keyboard, accessibility, help, keyboard-test and power tools, and + troubleshooting tools under **Advanced**. It never authorizes or starts disk + changes. DMS's upstream first-run dialogs are suppressed on the live medium. +- The welcome's action (and the **Install Phoebus OS** desktop entry) opens the + graphical installer wizard, which talks to the Rust backend over the typed + `phoebus-installer --gui-bridge` JSON protocol: language/keyboard/timezone, + network and prerequisites, AI model connection, destination disk (protected + disks and the installation medium are identified and unselectable), account + and encryption, review, `ERASE` authorization, real-stage progress and + completion. A second launch never opens a duplicate session. If Quickshell or + Wayland is unavailable the launcher falls back to the TUI/CLI. - A text recovery console is available on the serial line and on another VT (`Ctrl+Alt+F2`): log in as `phoebus` / `phoebus` (live-only credential), passwordless `sudo`. - The `phoebus-dwl` session remains selectable as a fallback. +## Verification + +`installer/tests/vm/gui-driver.py` drives the graphical ISO in a disposable +UEFI VM: `gui` (welcome + wizard journey and screenshots), `install` +(non-interactive install with the static binary and a secret-leak scan) and +`boot` (detached boot of the installed disk). See +`docs/VM-BOOT-VERIFICATION.md` for the recorded evidence. + + ## Installed system An installed system always authenticates through `greetd` and defaults to the diff --git a/installer/live/build.sh b/installer/live/build.sh index 099ea5f..968dce7 100755 --- a/installer/live/build.sh +++ b/installer/live/build.sh @@ -42,6 +42,12 @@ say "preflight" for c in mmdebstrap xorriso mksquashfs curl dpkg-deb unshare sha256sum; do command -v "$c" >/dev/null || { echo "missing tool: $c" >&2; exit 1; } done +if ! command -v magick >/dev/null 2>&1 \ + && ! command -v convert >/dev/null 2>&1 \ + && ! command -v inkscape >/dev/null 2>&1; then + echo "missing an SVG rasteriser for the boot background (magick, convert or inkscape)" >&2 + exit 1 +fi for b in phoebus-installer sys; do [[ -x "$release_src/$b" ]] || { echo "missing $release_src/$b; build it first:" >&2 @@ -93,10 +99,11 @@ echo "releases OK" # --------------------------------------------------------------------------- say "emit shared desktop assets" assets=( - session-mango session-dwl assistant install menu lock idle + session-mango session-dwl assistant install welcome menu lock idle mango-config mango-session-target install-desktop wayland-session-mango wayland-session-dwl waybar-config waybar-style greetd-live + brand-emblem brand-wordmark brand-wallpaper brand-tokens ) for name in "${assets[@]}"; do "$release_dir/phoebus-installer" --emit-asset "$name" > "$work/assets/$name" || { @@ -151,7 +158,7 @@ fi [[ -s "$rootfs_tar" ]] || { echo "mmdebstrap did not produce $rootfs_tar" >&2; exit 1; } -say "unpack and verify the desktop payload" +say "unpack the rootfs" rootfs="$work/rootfs" rm -rf "$rootfs" mkdir -p "$rootfs" @@ -163,6 +170,75 @@ install -d -m 0755 "$rootfs/dev" echo "${LIVE_HOSTNAME:-phoebus-live}" > "$rootfs/etc/hostname" printf '127.0.1.1\t%s\n' "${LIVE_HOSTNAME:-phoebus-live}" >> "$rootfs/etc/hosts" +say "install the live payload" +# Everything below is installed after the (cached) rootfs is extracted, so +# PHOEBUS_REUSE_ROOTFS=1 still picks up new binaries, UI and branding. +iso_version="${PHOEBUS_VERSION:-0.1.0}" +build_id="${PHOEBUS_BUILD_ID:-$(date -u +%Y%m%dT%H%M%SZ)}" + +install -d -m 0755 "$rootfs/etc/phoebus" +install -D -m 0755 "$release_dir/phoebus-installer" "$rootfs/usr/local/bin/phoebus-installer" +install -D -m 0755 "$release_dir/sys" "$rootfs/usr/local/bin/sys" + +install_asset() { + local name="$1" dest="$2" mode="${3:-0644}" + local src="$work/assets/$name" + [[ -f "$src" ]] || { echo "missing emitted asset $name" >&2; exit 1; } + install -D -m "$mode" "$src" "$rootfs/$dest" +} + +install_asset session-mango /usr/local/bin/phoebus-session-mango 0755 +install_asset session-dwl /usr/local/bin/phoebus-session 0755 +install_asset assistant /usr/local/bin/phoebus-assistant 0755 +install_asset install /usr/local/bin/phoebus-install 0755 +install_asset welcome /usr/local/bin/phoebus-welcome 0755 +install_asset menu /usr/local/bin/phoebus-menu 0755 +install_asset lock /usr/local/bin/phoebus-lock 0755 +install_asset idle /usr/local/bin/phoebus-idle 0755 +install_asset mango-config /etc/xdg/mango/config.conf +install_asset mango-session-target /usr/lib/systemd/user/mango-session.target +install_asset install-desktop /usr/share/applications/phoebus-install.desktop +install_asset wayland-session-mango /usr/share/wayland-sessions/phoebus-mango.desktop +install_asset wayland-session-dwl /usr/share/wayland-sessions/phoebus-dwl.desktop +install_asset waybar-config /etc/xdg/waybar/config +install_asset waybar-style /etc/xdg/waybar/style.css +# Live-only automatic login (never copied to an installed system). +install_asset greetd-live /etc/greetd/config.toml + +# Branding: shared vector assets, the app icon and the live-only marker. +install_asset brand-emblem /usr/share/phoebus/branding/emblem.svg +install_asset brand-wordmark /usr/share/phoebus/branding/wordmark.svg +install_asset brand-wallpaper /usr/share/phoebus/branding/wallpaper.svg +install_asset brand-tokens /usr/share/phoebus/branding/tokens.json +install -D -m 0644 "$work/assets/brand-emblem" \ + "$rootfs/usr/share/icons/hicolor/scalable/apps/phoebus.svg" +install -D -m 0644 "$here/install-help.txt" "$rootfs/usr/share/phoebus/install-help.txt" +printf '%s\n' "$iso_version" > "$rootfs/etc/phoebus/version" +printf 'PHOEBUS_BUILD_ID=%s\n' "$build_id" > "$rootfs/etc/phoebus/build" +# The live marker gates live-only autostart; it is never written to a target. +: > "$rootfs/etc/phoebus/live" + +# Suppress DankMaterialShell's upstream first-run dialogs on the live medium: +# the installer is the first thing the user should see. DMS writes these +# markers itself when the dialogs are dismissed; pre-seeding them is its +# supported "already welcomed" state. The tmpfiles `Z /home/phoebus` rule +# chowns them to the live user at boot. The changelog marker is versioned by +# DMS (major.minor), so it is derived from the pinned DMS release. +install -d -m 0700 "$rootfs/home/phoebus/.config/DankMaterialShell" +: > "$rootfs/home/phoebus/.config/DankMaterialShell/.firstlaunch" +: > "$rootfs/home/phoebus/.config/DankMaterialShell/.changelog-${dms_version%.*}" + +# Quickshell frontend: the welcome window and the graphical installer, each a +# self-contained config with the shared Common module materialised. +if [[ -d "$here/desktop" ]]; then + for cfgname in phoebus-welcome phoebus-install; do + [[ -f "$here/desktop/$cfgname/shell.qml" ]] || { + echo "live build: missing desktop config $cfgname" >&2; exit 1; } + install -d -m 0755 "$rootfs/etc/xdg/quickshell/$cfgname" + cp -rL "$here/desktop/$cfgname/." "$rootfs/etc/xdg/quickshell/$cfgname/" + done +fi + # Fail clearly rather than shipping a text ISO labelled as a desktop image. for bin in usr/bin/mango usr/bin/dms; do [[ -e "$rootfs/$bin" ]] || { echo "live rootfs is missing $bin" >&2; exit 1; } @@ -176,6 +252,16 @@ grep -q "initial_session" "$rootfs/etc/greetd/config.toml" || { echo "live rootfs greetd config is missing live autologin" >&2; exit 1; } [[ -f "$rootfs/usr/share/applications/phoebus-install.desktop" ]] || { echo "live rootfs has no Install Phoebus launcher" >&2; exit 1; } +for check in \ + usr/local/bin/phoebus-welcome \ + etc/xdg/quickshell/phoebus-welcome/shell.qml \ + etc/xdg/quickshell/phoebus-install/shell.qml \ + usr/share/phoebus/branding/emblem.svg \ + usr/share/phoebus/branding/wallpaper.svg \ + etc/phoebus/live; do + [[ -e "$rootfs/$check" ]] || { + echo "live rootfs is missing payload: $check" >&2; exit 1; } +done echo "desktop payload verified" # --------------------------------------------------------------------------- @@ -186,7 +272,7 @@ say "pack live filesystem" install -d -m 0755 "$rootfs/etc/tmpfiles.d" cat > "$rootfs/etc/tmpfiles.d/phoebus-live.conf" <<'EOF' d /home/phoebus 0700 phoebus phoebus - -z /home/phoebus 0700 phoebus phoebus - +Z /home/phoebus 0700 phoebus phoebus - EOF # `tar` run as an unprivileged user drops setuid/setgid/sticky bits; restore # them from the archive so e.g. `sudo` and `pkexec` work in the live image. @@ -228,12 +314,13 @@ cp "$vmlinuz" "$work/vmlinuz" cp "$initrd" "$work/initrd.img" # --------------------------------------------------------------------------- -say "patch boot config for serial console" +say "patch boot config for serial console and Phoebus branding" bootcfg="$work/bootcfg"; mkdir -p "$bootcfg" xorriso -osirrox on -indev "$base" \ -extract /boot/grub/grub.cfg "$bootcfg/grub.cfg" \ - -extract /boot/grub/config.cfg "$bootcfg/config.cfg" >/dev/null 2>&1 -chmod u+w "$bootcfg/grub.cfg" "$bootcfg/config.cfg" + -extract /boot/grub/config.cfg "$bootcfg/config.cfg" \ + -extract /boot/grub/live-theme/theme.txt "$bootcfg/theme.txt" >/dev/null 2>&1 +chmod u+w "$bootcfg/grub.cfg" "$bootcfg/config.cfg" "$bootcfg/theme.txt" sed -i 's#boot=live components quiet splash findiso=#boot=live components console=ttyS0,115200 noautologin findiso=#' "$bootcfg/grub.cfg" python3 - "$bootcfg/config.cfg" <<'PY' import sys @@ -246,6 +333,57 @@ t = t.replace("terminal_output gfxterm", "terminal_output gfxterm serial") open(p, "w").write(t) PY +# Phoebus identity on the boot menu: rename the entries and use the brand +# colours and wallpaper. This only rewrites text/theme files; the boot path is +# untouched. +python3 - "$bootcfg/grub.cfg" <<'PY' +import sys +p = sys.argv[1] +t = open(p).read() +t = t.replace('menuentry "Live system (amd64)"', + 'menuentry "Start Phoebus OS (live medium)"') +t = t.replace('menuentry "Live system (amd64 fail-safe mode)"', + 'menuentry "Phoebus OS (fail-safe graphics)"') +open(p, "w").write(t) +PY +cat > "$bootcfg/theme.cfg" <<'EOF' +set color_normal=light-gray/black +set color_highlight=black/brown + +if [ -e /boot/grub/splash.png ]; then + set theme=/boot/grub/live-theme/theme.txt +else + set menu_color_normal=light-gray/black + set menu_color_highlight=white/brown +fi +EOF +python3 - "$bootcfg/theme.txt" <<'PY' +import sys +p = sys.argv[1] +t = open(p).read() +t = t.replace('title-text: "Live Boot Menu with GRUB"', 'title-text: "Phoebus OS"') +t = t.replace('title-color: "#ffffff"', 'title-color: "#e8a33d"') +t = t.replace('item_color = "#a8a8a8"', 'item_color = "#f4efe6"') +t = t.replace('selected_item_color= "#ffffff"', 'selected_item_color= "#e8a33d"') +t = t.replace('fg_color = "#ffffff"', 'fg_color = "#e8a33d"') +t = t.replace('bg_color = "#a8a8a8"', 'bg_color = "#3a3a42"') +t = t.replace('border_color = "#ffffff"', 'border_color = "#e8a33d"') +open(p, "w").write(t) +PY +# Rasterise the brand wallpaper for the GRUB background (GRUB does not read +# SVG). ImageMagick or Inkscape is required; the build fails clearly otherwise. +if command -v magick >/dev/null 2>&1; then + magick -background none "$work/assets/brand-wallpaper" -resize 1024x768 "$bootcfg/splash.png" +elif command -v convert >/dev/null 2>&1; then + convert -background none "$work/assets/brand-wallpaper" -resize 1024x768 "$bootcfg/splash.png" +elif command -v inkscape >/dev/null 2>&1; then + inkscape "$work/assets/brand-wallpaper" -w 1024 -h 768 -o "$bootcfg/splash.png" +else + echo "no SVG rasteriser (magick/convert/inkscape) for the boot background" >&2 + exit 1 +fi +[[ -s "$bootcfg/splash.png" ]] || { echo "branded boot background is empty" >&2; exit 1; } + # --------------------------------------------------------------------------- say "assemble ISO" rm -f "$out" @@ -269,6 +407,9 @@ xorriso -indev "$base" -outdev "$out" \ "${kmap[@]}" \ -map "$bootcfg/grub.cfg" /boot/grub/grub.cfg \ -map "$bootcfg/config.cfg" /boot/grub/config.cfg \ + -map "$bootcfg/theme.cfg" /boot/grub/theme.cfg \ + -map "$bootcfg/theme.txt" /boot/grub/live-theme/theme.txt \ + -map "$bootcfg/splash.png" /boot/grub/splash.png \ -boot_image any keep >/dev/null sha256sum "$out" | tee "$out.sha256" diff --git a/installer/live/desktop/common/Bridge.qml b/installer/live/desktop/common/Bridge.qml new file mode 100644 index 0000000..288ec76 --- /dev/null +++ b/installer/live/desktop/common/Bridge.qml @@ -0,0 +1,173 @@ +pragma Singleton +import QtQuick +import Quickshell +import Quickshell.Io + +// Typed JSON bridge to the privileged Rust installer. The frontend never +// scrapes terminal output: every call is a typed request and every reply is a +// typed JSON object. Secrets are written over the process stdin only. +Singleton { + id: root + + // True once the bridge process is running and accepting requests. + property bool ready: false + property bool crashed: false + property string crashMessage: "" + property string lastError: "" + property var handshake: null + property var config: null + + property var pending: ({}) + property int nextId: 1 + + signal event(string name, var data) + signal availabilityChanged + signal handshakeReady + + readonly property var bridgeCommand: { + const override = Quickshell.env("PHOEBUS_BRIDGE_CMD"); + if (override && override.length > 0) + return override.split(" ").filter(part => part.length > 0); + // Absolute paths: Quickshell's Process execs the command directly and + // does not perform PATH lookup. + return ["/usr/bin/sudo", "-n", "/usr/local/bin/phoebus-installer", "--gui-bridge"]; + } + + // Retried until the first successful handshake, so a process-start race can + // never leave the frontend permanently stuck. + Timer { + interval: 400 + repeat: true + running: proc.running && root.handshake === null + onTriggered: root.refreshHandshake(null) + } + + function start() { + if (!proc.running) + proc.running = true; + } + function stop() { + if (proc.running) + proc.running = false; + } + + function call(op, payload, onDone) { + const id = root.nextId++; + if (onDone) + root.pending[id] = onDone; + const request = Object.assign({ id: id, op: op }, payload || {}); + const line = JSON.stringify(request) + "\n"; + if (!proc.running) { + // Quickshell's Process.write() returns void, so it cannot be used + // to detect a failed write. Check the process state instead. + delete root.pending[id]; + root.lastError = "backend not running"; + if (onDone) + onDone({ ok: false, error: "the installer backend is not running" }); + return; + } + proc.write(line); + } + + function handleLine(line) { + const text = ("" + line).trim(); + if (text.length === 0) + return; + let msg; + try { + msg = JSON.parse(text); + } catch (e) { + console.log("bridge: unparsable line: " + text); + return; + } + if (msg.event === "progress") { + root.event("progress", msg); + return; + } + if (msg.id !== undefined && root.pending[msg.id]) { + const cb = root.pending[msg.id]; + delete root.pending[msg.id]; + cb(msg); + } + } + + // Convenience wrappers. + function refreshHandshake(cb) { + call("handshake", {}, reply => { + if (reply.ok) { + root.handshake = reply.data; + root.handshakeReady(); + } + if (cb) + cb(reply); + }); + } + function listDisks(cb) { + call("disks", {}, cb); + } + function setConfig(cfg, cb) { + call("set_config", { config: cfg }, reply => { + if (reply.ok) + root.config = cfg; + if (cb) + cb(reply); + }); + } + function setSecrets(secrets, cb) { + call("set_secrets", { secrets: secrets }, cb); + } + function validate(cb) { + call("validate", {}, cb); + } + function plan(cb) { + call("plan", {}, cb); + } + function destructivePreview(cb) { + call("destructive_preview", {}, cb); + } + function aiCheck(cb) { + call("ai_check", {}, cb); + } + function approve(eraseText, finalConfirmed, cb) { + call("approve", { erase: eraseText, final_confirm: finalConfirmed }, cb); + } + function startInstall(planDigest, eraseText, cb) { + call("start_install", { + erase: eraseText, + final_confirm: true, + plan_digest: planDigest + }, cb); + } + function logTail(lines, cb) { + call("log_tail", { lines: lines }, cb); + } + + Process { + id: proc + command: root.bridgeCommand + stdinEnabled: true + running: false + + onStarted: { + root.ready = true; + root.crashed = false; + root.crashMessage = ""; + root.availabilityChanged(); + } + onExited: exitCode => { + root.ready = false; + root.crashed = true; + root.crashMessage = "The installer backend stopped (exit " + exitCode + ")."; + root.availabilityChanged(); + } + stdout: SplitParser { + onRead: line => root.handleLine(line) + } + stderr: SplitParser { + onRead: line => { + root.lastError = line; + console.log("phoebus-bridge: " + line); + } + } + } +} diff --git a/installer/live/desktop/common/PhoebusButton.qml b/installer/live/desktop/common/PhoebusButton.qml new file mode 100644 index 0000000..86a6b24 --- /dev/null +++ b/installer/live/desktop/common/PhoebusButton.qml @@ -0,0 +1,68 @@ +import QtQuick + +// A keyboard-focusable, branded button. Primary buttons are amber; secondary +// buttons are a raised surface. Focus is always visible. +Rectangle { + id: btn + + property string label: "" + property bool primary: false + property bool danger: false + property bool compact: false + property bool actionEnabled: true + signal clicked + + readonly property bool hovered: mouse.containsMouse + readonly property color baseBg: { + if (danger) + return Qt.darker(Theme.danger, 1.25); + if (primary) + return hovered ? Theme.amber : Theme.amberDeep; + return hovered ? Theme.surfaceRaised : Theme.surface; + } + + implicitHeight: compact ? 34 : 46 + implicitWidth: Math.max(compact ? 80 : 120, labelText.implicitWidth + (compact ? 28 : 48)) + radius: Theme.radiusSmall + color: actionEnabled ? baseBg : Theme.surface + border.width: (primary || danger) ? 0 : 1 + border.color: activeFocus ? Theme.focusRing : Theme.border + opacity: actionEnabled ? 1 : 0.55 + activeFocusOnTab: true + Accessible.role: Accessible.Button + Accessible.name: label + Accessible.onPressAction: if (actionEnabled) btn.clicked() + + Keys.onReturnPressed: if (btn.actionEnabled) btn.clicked() + Keys.onEnterPressed: if (btn.actionEnabled) btn.clicked() + Keys.onSpacePressed: if (btn.actionEnabled) btn.clicked() + + Rectangle { + anchors.fill: parent + anchors.margins: -3 + radius: btn.radius + 3 + color: "transparent" + border.width: 2 + border.color: Theme.focusRing + visible: btn.activeFocus + } + + Text { + id: labelText + anchors.centerIn: parent + text: btn.label + color: (btn.primary || btn.danger) ? Theme.charcoal : Theme.warmWhite + font.family: Theme.family + font.pixelSize: btn.compact ? Theme.fontSmall : Theme.fontBody + font.weight: btn.primary ? Font.DemiBold : Font.Normal + } + + MouseArea { + id: mouse + anchors.fill: parent + hoverEnabled: true + cursorShape: Qt.PointingHandCursor + enabled: btn.actionEnabled + onClicked: btn.clicked() + } +} diff --git a/installer/live/desktop/common/PhoebusCard.qml b/installer/live/desktop/common/PhoebusCard.qml new file mode 100644 index 0000000..efcf341 --- /dev/null +++ b/installer/live/desktop/common/PhoebusCard.qml @@ -0,0 +1,32 @@ +import QtQuick + +// A raised surface with a hairline border and the standard radius. +// +// Put children in the `content` column; they should set `width: parent.width` +// for full-width content, and their implicit heights determine the card's. +Rectangle { + id: card + + default property alias content: col.data + property int padding: Theme.pad + property int spacing: 10 + property color fill: Theme.surface + property bool outlined: true + + color: fill + radius: Theme.radius + border.width: outlined ? 1 : 0 + border.color: Theme.border + + implicitWidth: 320 + implicitHeight: col.implicitHeight + padding * 2 + + Column { + id: col + anchors.left: parent.left + anchors.right: parent.right + anchors.top: parent.top + anchors.margins: card.padding + spacing: card.spacing + } +} diff --git a/installer/live/desktop/common/PhoebusChip.qml b/installer/live/desktop/common/PhoebusChip.qml new file mode 100644 index 0000000..f68dc38 --- /dev/null +++ b/installer/live/desktop/common/PhoebusChip.qml @@ -0,0 +1,22 @@ +import QtQuick + +// A small inline status pill. +Rectangle { + id: chip + property string text: "" + property color tone: Theme.muted + height: 24 + implicitWidth: chipText.implicitWidth + 20 + radius: 12 + color: "transparent" + border.width: 1 + border.color: tone + Text { + id: chipText + anchors.centerIn: parent + text: chip.text + color: chip.tone + font.family: Theme.family + font.pixelSize: Theme.fontSmall + } +} diff --git a/installer/live/desktop/common/PhoebusChoice.qml b/installer/live/desktop/common/PhoebusChoice.qml new file mode 100644 index 0000000..a34faee --- /dev/null +++ b/installer/live/desktop/common/PhoebusChoice.qml @@ -0,0 +1,27 @@ +import QtQuick + +// A wrapping row of selectable pills. Used for small, closed option sets +// (filesystem, kernel profile, AI provider, ...). Keyboard-navigable. +Flow { + id: choice + + property var options: [] + property string value: "" + property bool compact: true + signal selected(string value) + + spacing: 8 + width: parent ? parent.width : implicitWidth + + Repeater { + model: choice.options + + delegate: PhoebusButton { + required property var modelData + label: modelData.label !== undefined ? modelData.label : modelData + primary: (modelData.value !== undefined ? modelData.value : modelData) === choice.value + compact: choice.compact + onClicked: choice.selected(modelData.value !== undefined ? modelData.value : modelData) + } + } +} diff --git a/installer/live/desktop/common/PhoebusEmblem.qml b/installer/live/desktop/common/PhoebusEmblem.qml new file mode 100644 index 0000000..c9f5e36 --- /dev/null +++ b/installer/live/desktop/common/PhoebusEmblem.qml @@ -0,0 +1,62 @@ +import QtQuick + +// The Phoebus sun emblem, drawn with Canvas so it never depends on an SVG +// image plugin. The installed vector is still emitted for the desktop and +// boot surfaces; this is the in-app rendering. +Item { + id: emblem + + property color accent: Theme.amber + property color core: Theme.warmWhite + implicitWidth: 128 + implicitHeight: 128 + + onAccentChanged: canvas.requestPaint() + onCoreChanged: canvas.requestPaint() + + Canvas { + id: canvas + anchors.fill: parent + + onWidthChanged: requestPaint() + onHeightChanged: requestPaint() + Component.onCompleted: requestPaint() + + onPaint: { + const ctx = getContext("2d"); + ctx.reset(); + const w = width; + const h = height; + const cx = w / 2; + const cy = h / 2; + const r = Math.min(w, h) / 2; + const rays = 8; + ctx.lineCap = "round"; + ctx.strokeStyle = emblem.accent; + ctx.fillStyle = emblem.accent; + ctx.lineWidth = r * 0.09; + for (let i = 0; i < rays; i++) { + const a = i * (Math.PI * 2 / rays); + ctx.beginPath(); + ctx.moveTo(cx + Math.cos(a) * r * 0.62, cy + Math.sin(a) * r * 0.62); + ctx.lineTo(cx + Math.cos(a) * r * 0.92, cy + Math.sin(a) * r * 0.92); + ctx.stroke(); + } + ctx.lineWidth = r * 0.06; + for (let j = 0; j < rays; j++) { + const a = (j + 0.5) * (Math.PI * 2 / rays); + ctx.beginPath(); + ctx.moveTo(cx + Math.cos(a) * r * 0.66, cy + Math.sin(a) * r * 0.66); + ctx.lineTo(cx + Math.cos(a) * r * 0.84, cy + Math.sin(a) * r * 0.84); + ctx.stroke(); + } + ctx.beginPath(); + ctx.arc(cx, cy, r * 0.40, 0, Math.PI * 2); + ctx.fill(); + ctx.beginPath(); + ctx.arc(cx, cy, r * 0.25, 0, Math.PI * 2); + ctx.fillStyle = emblem.core; + ctx.fill(); + } + } +} diff --git a/installer/live/desktop/common/PhoebusField.qml b/installer/live/desktop/common/PhoebusField.qml new file mode 100644 index 0000000..f25cfa6 --- /dev/null +++ b/installer/live/desktop/common/PhoebusField.qml @@ -0,0 +1,99 @@ +import QtQuick + +// A labelled single-line input with an inline error and optional secret echo. +Column { + id: field + + property string label: "" + property string placeholder: "" + property string error: "" + property bool secret: false + property bool showSecret: false + property alias text: input.text + property alias inputItem: input + property int maxLength: 256 + signal edited(string value) + signal accepted + + width: parent ? parent.width : implicitWidth + spacing: 6 + + Text { + width: parent.width + text: field.label + color: Theme.warmWhite + font.family: Theme.family + font.pixelSize: Theme.fontSmall + font.weight: Font.DemiBold + visible: field.label.length > 0 + } + + Rectangle { + width: parent.width + height: 42 + radius: Theme.radiusSmall + color: Theme.charcoal + border.width: input.activeFocus ? 2 : 1 + border.color: field.error.length > 0 ? Theme.danger + : input.activeFocus ? Theme.focusRing + : Theme.border + + TextInput { + id: input + anchors.fill: parent + anchors.leftMargin: 12 + anchors.rightMargin: 44 + verticalAlignment: TextInput.AlignVCenter + color: Theme.warmWhite + font.family: Theme.family + font.pixelSize: Theme.fontBody + selectionColor: Theme.amberDeep + selectedTextColor: Theme.warmWhite + echoMode: (field.secret && !field.showSecret) ? TextInput.Password : TextInput.Normal + passwordCharacter: "\u2022" + selectByMouse: true + activeFocusOnTab: true + maximumLength: field.maxLength + clip: true + onTextEdited: field.edited(text) + onAccepted: field.accepted() + + Text { + anchors.fill: parent + verticalAlignment: Text.AlignVCenter + text: field.placeholder + color: Theme.muted + font.family: Theme.family + font.pixelSize: Theme.fontBody + visible: input.text.length === 0 && !input.activeFocus + } + } + + Text { + anchors.right: parent.right + anchors.rightMargin: 12 + anchors.verticalCenter: parent.verticalCenter + visible: field.secret + text: field.showSecret ? "hide" : "show" + color: Theme.amber + font.family: Theme.family + font.pixelSize: Theme.fontSmall + MouseArea { + anchors.fill: parent + anchors.margins: -6 + cursorShape: Qt.PointingHandCursor + onClicked: field.showSecret = !field.showSecret + } + } + } + + Text { + width: parent.width + text: field.error + color: Theme.danger + font.family: Theme.family + font.pixelSize: Theme.fontSmall + wrapMode: Text.WordWrap + visible: field.error.length > 0 + } +} diff --git a/installer/live/desktop/common/PhoebusToggle.qml b/installer/live/desktop/common/PhoebusToggle.qml new file mode 100644 index 0000000..f1f0ee3 --- /dev/null +++ b/installer/live/desktop/common/PhoebusToggle.qml @@ -0,0 +1,83 @@ +import QtQuick + +// A label + switch. Clickable and keyboard-operable (Space/Enter). +Item { + id: toggle + + property string label: "" + property string description: "" + property bool checked: false + signal toggled(bool value) + + implicitHeight: description.length > 0 ? 52 : 36 + width: parent ? parent.width : implicitWidth + activeFocusOnTab: true + Accessible.role: Accessible.CheckBox + Accessible.name: label + Accessible.checked: checked + + Keys.onSpacePressed: { + toggle.checked = !toggle.checked; + toggle.toggled(toggle.checked); + } + Keys.onReturnPressed: Keys.onSpacePressed(event) + Keys.onEnterPressed: Keys.onSpacePressed(event) + + Column { + anchors.left: parent.left + anchors.right: switchBox.left + anchors.rightMargin: 16 + anchors.verticalCenter: parent.verticalCenter + spacing: 2 + Text { + width: parent.width + text: toggle.label + color: Theme.warmWhite + font.family: Theme.family + font.pixelSize: Theme.fontBody + } + Text { + width: parent.width + text: toggle.description + color: Theme.muted + font.family: Theme.family + font.pixelSize: Theme.fontSmall + wrapMode: Text.WordWrap + visible: toggle.description.length > 0 + } + } + + Rectangle { + id: switchBox + anchors.right: parent.right + anchors.verticalCenter: parent.verticalCenter + width: 44 + height: 24 + radius: 12 + color: toggle.checked ? Theme.amberDeep : Theme.border + border.width: toggle.activeFocus ? 2 : 0 + border.color: Theme.focusRing + + Rectangle { + width: 18 + height: 18 + radius: 9 + y: 3 + x: toggle.checked ? parent.width - width - 3 : 3 + color: toggle.checked ? Theme.warmWhite : Theme.muted + Behavior on x { + NumberAnimation { duration: 90 } + } + } + + MouseArea { + anchors.fill: parent + cursorShape: Qt.PointingHandCursor + onClicked: { + toggle.forceActiveFocus(); + toggle.checked = !toggle.checked; + toggle.toggled(toggle.checked); + } + } + } +} diff --git a/installer/live/desktop/common/Theme.qml b/installer/live/desktop/common/Theme.qml new file mode 100644 index 0000000..6a4d7a7 --- /dev/null +++ b/installer/live/desktop/common/Theme.qml @@ -0,0 +1,45 @@ +pragma Singleton +import QtQuick + +// Phoebus brand tokens. Kept in sync with phoebus_core::brand::PALETTE by a +// Rust test, so the QML frontend and the backend cannot drift. +QtObject { + id: theme + + // Palette: charcoal, warm white, restrained amber. + readonly property color charcoal: "#17171b" + readonly property color surface: "#232329" + readonly property color surfaceRaised: "#2b2b33" + readonly property color border: "#3a3a42" + readonly property color warmWhite: "#f4efe6" + readonly property color muted: "#a8a29a" + readonly property color amber: "#e8a33d" + readonly property color amberDeep: "#c97f24" + readonly property color success: "#7fb069" + readonly property color warning: "#e0a24a" + readonly property color danger: "#d2564b" + + readonly property color focusRing: amber + readonly property color overlay: Qt.rgba(0.09, 0.09, 0.10, 0.72) + + // Layout. + readonly property int radius: 12 + readonly property int radiusSmall: 8 + readonly property int gutter: 20 + readonly property int pad: 16 + readonly property int padLarge: 28 + + // Type scale. + readonly property int fontDisplay: 30 + readonly property int fontTitle: 22 + readonly property int fontHeading: 17 + readonly property int fontBody: 14 + readonly property int fontSmall: 12 + readonly property string family: "DejaVu Sans, Noto Sans, sans-serif" + + // Branding assets installed by the live build. + readonly property string brandDir: "/usr/share/phoebus/branding" + readonly property string emblem: brandDir + "/emblem.svg" + readonly property string wordmark: brandDir + "/wordmark.svg" + readonly property string wallpaper: brandDir + "/wallpaper.svg" +} diff --git a/installer/live/desktop/common/qmldir b/installer/live/desktop/common/qmldir new file mode 100644 index 0000000..8f59e68 --- /dev/null +++ b/installer/live/desktop/common/qmldir @@ -0,0 +1,10 @@ +module Common +singleton Theme 1.0 Theme.qml +singleton Bridge 1.0 Bridge.qml +PhoebusChip 1.0 PhoebusChip.qml +PhoebusButton 1.0 PhoebusButton.qml +PhoebusCard 1.0 PhoebusCard.qml +PhoebusField 1.0 PhoebusField.qml +PhoebusToggle 1.0 PhoebusToggle.qml +PhoebusChoice 1.0 PhoebusChoice.qml +PhoebusEmblem 1.0 PhoebusEmblem.qml diff --git a/installer/live/desktop/phoebus-install/Common b/installer/live/desktop/phoebus-install/Common new file mode 120000 index 0000000..60d3b0a --- /dev/null +++ b/installer/live/desktop/phoebus-install/Common @@ -0,0 +1 @@ +../common \ No newline at end of file diff --git a/installer/live/desktop/phoebus-install/shell.qml b/installer/live/desktop/phoebus-install/shell.qml new file mode 100644 index 0000000..122ffc5 --- /dev/null +++ b/installer/live/desktop/phoebus-install/shell.qml @@ -0,0 +1,1121 @@ +import QtQuick +import Quickshell +import Quickshell.Io +import "Common" + +// The graphical Phoebus installer. A thin, typed frontend over the Rust +// backend: configuration, validation, the plan, authorization, progress and +// results all come from `Bridge` (the JSON protocol). This file contains no +// installation logic and never parses terminal output. +ShellRoot { + id: shell + + property var cfg: null + property int step: 0 + property string phase: "form" // form | progress | done | failed + property var issues: ({}) + property string status: "" + property var disks: [] + property string selectedDisk: "" + property var review: null + property string previewText: "" + property string planDigest: "" + property var handshake: null + + // Secrets: held in memory only, sent over the bridge stdin, never in cfg. + property string userPw: "" + property string userPw2: "" + property string luksPw: "" + property string luksPw2: "" + property string apiKey: "" + + property bool aiConnected: false + property bool aiChecking: false + property string aiError: "" + property var aiApplied: [] + + property var stageStatus: ({}) + property var stageOrder: [] + property var progressLog: [] + property string failureText: "" + property string failureDisk: "" + property var failureNext: [] + property bool showFailureLog: false + property var logLines: [] + property bool showAdvanced: false + property bool showSecrets: false + + readonly property var stepTitles: [ + "Language and region", + "Network and prerequisites", + "AI model", + "Destination disk", + "Your account and encryption", + "Review", + "Confirm and install", + "Installing" + ] + readonly property var stepFields: [ + ["locale", "keymap", "timezone"], + [], + [], + ["target_disk"], + ["hostname", "username"], + [], + [] + ] + + function clone(o) { + return JSON.parse(JSON.stringify(o)); + } + + // QML `var` properties do not emit change signals for nested assignments, + // so bindings that read `cfg.*` would not update. Reassigning a clone + // re-evaluates them. Used after a choice/toggle changes the configuration. + function touchConfig() { + if (shell.cfg) + shell.cfg = clone(shell.cfg); + } + + // Re-read every input from the current configuration. Called when entering + // a step so back-navigation and AI-applied changes are reflected without + // discarding the user's non-secret choices. + function syncFields() { + if (!shell.cfg) + return; + localeField.inputItem.text = shell.cfg.system.locale; + keymapField.inputItem.text = shell.cfg.system.keymap; + tzField.inputItem.text = shell.cfg.system.timezone; + fullnameField.inputItem.text = shell.cfg.user.fullname; + userField.inputItem.text = shell.cfg.user.username; + hostField.inputItem.text = shell.cfg.system.hostname; + modelField.inputItem.text = shell.cfg.ai.model; + endpointField.inputItem.text = shell.cfg.ai.endpoint; + keyField.inputItem.text = shell.apiKey; + pwField.inputItem.text = shell.userPw; + pw2Field.inputItem.text = shell.userPw2; + luksField.inputItem.text = shell.luksPw; + luks2Field.inputItem.text = shell.luksPw2; + } + + function setIssue(field, message) { + let next = clone(shell.issues); + next[field] = message; + shell.issues = next; + } + function clearIssues() { + shell.issues = ({}); + } + function issueFor(field) { + return shell.issues[field] !== undefined ? shell.issues[field] : ""; + } + + function applyIssues(list) { + let next = ({}); + for (let i = 0; i < list.length; i++) + next[list[i].field] = list[i].message; + shell.issues = next; + } + + function startBridge() { + Bridge.start(); + } + + function onHandshake(reply) { + // A failed first write is retried by the Bridge timer; only surface + // real, parsed failures. + if (!reply.ok) + return; + shell.handshake = reply.data; + shell.cfg = clone(reply.data.defaults); + shell.cfg.storage.disk = ""; + shell.step = 0; + shell.phase = "form"; + shell.status = ""; + shell.syncFields(); + } + + function refreshHandshake() { + Bridge.refreshHandshake(null); + } + + function applyConfig(then) { + if (!shell.cfg) { + shell.status = "The installer backend is not ready yet."; + return; + } + Bridge.setConfig(clone(shell.cfg), reply => { + if (!reply.ok) { + shell.status = reply.error; + return; + } + if (then) + then(); + }); + } + + // Persist the configuration and validate only the fields owned by the + // current step. The backend is the single source of validation truth. + function saveAndAdvance() { + shell.status = "Checking…"; + applyConfig(() => { + Bridge.validate(reply => { + if (!reply.ok) { + shell.status = reply.error; + return; + } + const fields = shell.stepFields[shell.step] || []; + const relevant = reply.data.issues.filter(i => fields.indexOf(i.field) !== -1); + if (relevant.length > 0) { + applyIssues(relevant); + shell.status = "Please fix the highlighted fields."; + return; + } + clearIssues(); + shell.status = ""; + shell.step += 1; + shell.enterStep(); + }); + }); + } + + function advance() { + if (!shell.cfg) { + shell.status = "Waiting for the installer backend…"; + return; + } + const s = shell.step; + if (s === 0 || s === 3) { + saveAndAdvance(); + return; + } + if (s === 4) { + accountNext(); + return; + } + if (s === 1) { + shell.step += 1; + shell.enterStep(); + return; + } + if (s === 2) { + if (!shell.aiConnected) { + shell.status = "Connect and validate an AI model before continuing."; + return; + } + saveAndAdvance(); + return; + } + if (s === 5) { + shell.step = 6; + shell.enterStep(); + return; + } + shell.step += 1; + shell.enterStep(); + } + + function back() { + shell.status = ""; + if (shell.step > 0) { + shell.step -= 1; + shell.enterStep(); + } + } + + function enterStep() { + shell.status = ""; + const s = shell.step; + if (s === 2) { + if (!shell.cfg.ai.provider || shell.cfg.ai.provider === "none") { + shell.cfg.ai.provider = "deepseek"; + shell.cfg.ai.enabled = true; + if (!shell.cfg.ai.model) + shell.cfg.ai.model = "deepseek-chat"; + } + } + shell.syncFields(); + shell.touchConfig(); + if (s === 3) + refreshDisks(); + if (s === 5) + loadReview(); + if (s === 6) { + shell.previewText = ""; + shell.planDigest = ""; + Bridge.destructivePreview(reply => { + if (reply.ok) { + shell.previewText = reply.data.text; + shell.planDigest = reply.data.plan_digest; + } else { + shell.status = reply.error; + } + }); + } + } + + function refreshDisks() { + Bridge.listDisks(reply => { + if (reply.ok) + shell.disks = reply.data.disks; + else + shell.status = reply.error; + }); + } + + function loadReview() { + Bridge.plan(reply => { + if (reply.ok) { + shell.review = reply.data.review; + shell.planDigest = reply.data.plan_digest; + } else { + shell.status = reply.error; + } + }); + } + + function configureProvider(value) { + shell.cfg.ai.provider = value; + shell.cfg.ai.enabled = value !== "none"; + shell.aiConnected = false; + shell.aiError = ""; + shell.aiApplied = []; + if (value === "deepseek") + shell.cfg.ai.model = "deepseek-chat"; + else if (value === "openai") + shell.cfg.ai.model = "gpt-4o-mini"; + else if (value === "local") + shell.cfg.ai.model = shell.cfg.ai.model || "llama3.1"; + modelField.inputItem.text = shell.cfg.ai.model; + endpointField.inputItem.text = shell.cfg.ai.endpoint; + shell.touchConfig(); + } + + function connectAi() { + shell.aiChecking = true; + shell.aiError = ""; + shell.aiApplied = []; + shell.aiConnected = false; + const secrets = {}; + if (shell.apiKey.length > 0) + secrets.ai_api_key = shell.apiKey; + Bridge.setSecrets(secrets, () => { + applyConfig(() => { + Bridge.aiCheck(reply => { + shell.aiChecking = false; + if (reply.ok) { + shell.aiConnected = true; + shell.aiApplied = reply.data.applied || []; + if (reply.data.config) + shell.cfg = clone(reply.data.config); + shell.status = ""; + } else { + shell.aiError = reply.error; + } + }); + }); + }); + } + + function validateAccount() { + clearIssues(); + let ok = true; + if (shell.userPw.length < 8) { + setIssue("password", "Use at least 8 characters."); + ok = false; + } + if (shell.userPw !== shell.userPw2) { + setIssue("password_confirm", "The passwords do not match."); + ok = false; + } + if (shell.luksPw.length < 8) { + setIssue("passphrase", "Use at least 8 characters."); + ok = false; + } + if (shell.luksPw !== shell.luksPw2) { + setIssue("passphrase_confirm", "The passphrases do not match."); + ok = false; + } + return ok; + } + + function accountNext() { + if (!validateAccount()) { + shell.status = "Please fix the highlighted fields."; + return; + } + // The backend validates username/hostname; secrets go over stdin only. + const secrets = { + luks: shell.luksPw, + user_password: shell.userPw + }; + Bridge.setSecrets(secrets, () => saveAndAdvance()); + } + + function authorizeAndInstall() { + if (shell.eraseText !== "ERASE") { + shell.status = "Type ERASE exactly (case sensitive) to continue."; + return; + } + if (!shell.finalConfirm) { + shell.status = "Tick the confirmation to continue."; + return; + } + shell.status = "Authorizing…"; + Bridge.destructivePreview(reply => { + if (!reply.ok) { + shell.status = reply.error; + return; + } + const digest = reply.data.plan_digest; + Bridge.approve("ERASE", true, appr => { + if (!appr.ok) { + shell.status = appr.error; + return; + } + shell.startInstall(digest); + }); + }); + } + + function startInstall(digest) { + shell.phase = "progress"; + shell.stageStatus = ({}); + shell.stageOrder = []; + shell.progressLog = []; + shell.status = ""; + Bridge.startInstall(digest, "ERASE", reply => { + if (reply.ok) { + shell.phase = "done"; + } else { + shell.phase = "failed"; + shell.failureText = reply.error; + shell.failureDisk = parseDiskChange(reply.error); + shell.failureNext = parseNextActions(reply.error); + Bridge.logTail(200, r => { + if (r.ok) + shell.logLines = r.data.lines; + }); + } + }); + } + + function parseDiskChange(text) { + const m = ("" + text).match(/disk_changed: ([a-z]+)/); + return m ? m[1] : "unknown"; + } + function parseNextActions(text) { + const m = ("" + text).match(/next: (.+)$/m); + return m ? [m[1]] : []; + } + + function onProgress(event) { + let next = clone(shell.stageStatus); + next[event.stage] = event.status; + shell.stageStatus = next; + if (event.status === "started" && shell.stageOrder.indexOf(event.stage) === -1) { + let order = shell.stageOrder.slice(); + order.push(event.stage); + shell.stageOrder = order; + } + let log = shell.progressLog.slice(); + log.push(event); + shell.progressLog = log; + } + + function restartNow() { + Quickshell.execDetached(["systemctl", "reboot"]); + } + function closeInstaller() { + Qt.quit(); + } + + Connections { + target: Bridge + function onAvailabilityChanged() { + if (Bridge.ready) + shell.refreshHandshake(); + } + function onHandshakeReady() { + if (Bridge.handshake) + shell.onHandshake({ ok: true, data: Bridge.handshake }); + } + function onEvent(name, data) { + if (name === "progress") + shell.onProgress(data); + } + } + + Component.onCompleted: startBridge() + + // Keyboard navigation: Ctrl+Right advances (running the same validation as + // the Next button), Ctrl+Left goes back, Escape closes. Handled on the + // page item so events bubble from any focused control. + function nextAction() { + if (shell.phase !== "form") + return; + if (shell.step === 6) + shell.authorizeAndInstall(); + else + shell.advance(); + } + + FloatingWindow { + id: window + Component.onCompleted: { if (typeof window.requestActivate === "function") window.requestActivate(); } + visible: true + color: Theme.charcoal + implicitWidth: 980 + implicitHeight: 680 + title: "Install Phoebus OS" + + Rectangle { + anchors.fill: parent + gradient: Gradient { + GradientStop { position: 0.0; color: "#1c1c22" } + GradientStop { position: 1.0; color: "#141418" } + } + } + + Column { + id: page + anchors.fill: parent + anchors.margins: Theme.gutter + spacing: 12 + focus: true + Keys.onPressed: event => { + if (event.key === Qt.Key_Right && (event.modifiers & Qt.ControlModifier)) { + shell.nextAction(); + event.accepted = true; + } else if (event.key === Qt.Key_Left && (event.modifiers & Qt.ControlModifier)) { + shell.back(); + event.accepted = true; + } else if (event.key === Qt.Key_Escape) { + shell.closeInstaller(); + event.accepted = true; + } else if (event.key === Qt.Key_Return || event.key === Qt.Key_Enter) { + shell.nextAction(); + event.accepted = true; + } + } + + // -- header ---------------------------------------------------- + Item { + width: parent.width + height: 48 + Row { + anchors.left: parent.left + anchors.verticalCenter: parent.verticalCenter + spacing: 12 + PhoebusEmblem { width: 40; height: 40; anchors.verticalCenter: parent.verticalCenter } + Column { + anchors.verticalCenter: parent.verticalCenter + Text { + text: "Install Phoebus OS" + color: Theme.warmWhite + font.family: Theme.family + font.pixelSize: Theme.fontTitle + font.weight: Font.DemiBold + } + Text { + text: shell.phase === "form" ? "Step " + (shell.step + 1) + " of 7 · " + shell.stepTitles[shell.step] : "Installation" + color: Theme.amber + font.family: Theme.family + font.pixelSize: Theme.fontSmall + } + } + } + PhoebusButton { + anchors.right: parent.right + anchors.verticalCenter: parent.verticalCenter + label: "Close" + compact: true + actionEnabled: shell.phase !== "progress" + onClicked: shell.closeInstaller() + } + } + + // -- step dots ------------------------------------------------- + Row { + spacing: 8 + visible: shell.phase === "form" + Repeater { + model: 7 + delegate: Rectangle { + required property int index + width: index === shell.step ? 26 : 10 + height: 10 + radius: 5 + color: index < shell.step ? Theme.amberDeep + : index === shell.step ? Theme.amber + : Theme.border + Behavior on width { NumberAnimation { duration: 120 } } + } + } + } + + // -- body ------------------------------------------------------ + Flickable { + id: flick + width: parent.width + height: parent.height - 48 - 12 - (shell.phase === "form" ? 56 : 0) - 12 + contentWidth: width + contentHeight: stepColumn.height + 8 + clip: true + interactive: contentHeight > height + visible: shell.phase === "form" + + Column { + id: stepColumn + width: flick.width + spacing: 16 + + // ============ STEP 0: language ======================== + Column { + width: parent.width + spacing: 16 + visible: shell.step === 0 + PhoebusCard { + width: parent.width + Text { width: parent.width; text: "Language and region"; color: Theme.warmWhite; font.family: Theme.family; font.pixelSize: Theme.fontHeading; font.weight: Font.DemiBold } + PhoebusField { + id: localeField + label: "Locale" + placeholder: "en_US.UTF-8" + error: shell.issueFor("locale") + onEdited: value => shell.cfg.system.locale = value + Component.onCompleted: inputItem.text = shell.cfg ? shell.cfg.system.locale : "" + } + PhoebusChoice { + id: localePresets + options: [ + { value: "en_US.UTF-8", label: "English (US)" }, + { value: "en_GB.UTF-8", label: "English (UK)" }, + { value: "de_DE.UTF-8", label: "Deutsch" }, + { value: "fr_FR.UTF-8", label: "Français" }, + { value: "es_ES.UTF-8", label: "Español" } + ] + value: shell.cfg ? shell.cfg.system.locale : "" + onSelected: value => { shell.cfg.system.locale = value; localeField.inputItem.text = value; shell.touchConfig(); } + } + PhoebusField { + id: keymapField + label: "Keyboard layout" + placeholder: "us" + error: shell.issueFor("keymap") + onEdited: value => shell.cfg.system.keymap = value + Component.onCompleted: inputItem.text = shell.cfg ? shell.cfg.system.keymap : "" + } + PhoebusChoice { + id: keymapPresets + options: ["us", "gb", "de", "fr", "es", "dvorak"] + value: shell.cfg ? shell.cfg.system.keymap : "" + onSelected: value => { shell.cfg.system.keymap = value; keymapField.inputItem.text = value; shell.touchConfig(); } + } + PhoebusField { + id: tzField + label: "Timezone" + placeholder: "UTC" + error: shell.issueFor("timezone") + onEdited: value => shell.cfg.system.timezone = value + Component.onCompleted: inputItem.text = shell.cfg ? shell.cfg.system.timezone : "" + } + } + PhoebusCard { + width: parent.width + Text { width: parent.width; text: "Test your keyboard"; color: Theme.warmWhite; font.family: Theme.family; font.pixelSize: Theme.fontHeading; font.weight: Font.DemiBold } + Text { width: parent.width; text: "Type a sentence to confirm the layout produces the characters you expect."; color: Theme.muted; font.family: Theme.family; font.pixelSize: Theme.fontSmall; wrapMode: Text.WordWrap } + PhoebusField { id: kbTest; label: "Type here"; placeholder: "The quick brown fox…" } + } + } + + // ============ STEP 1: network ========================= + Column { + width: parent.width + spacing: 16 + visible: shell.step === 1 + PhoebusCard { + width: parent.width + Text { width: parent.width; text: "Network connection"; color: Theme.warmWhite; font.family: Theme.family; font.pixelSize: Theme.fontHeading; font.weight: Font.DemiBold } + Text { + width: parent.width + text: shell.handshake && shell.handshake.readiness.network + ? "Connected. Phoebus downloads a verified Gentoo stage3 and packages during installation." + : "No default route detected. Connect to a network to install Phoebus." + color: shell.handshake && shell.handshake.readiness.network ? Theme.success : Theme.warning + font.family: Theme.family + font.pixelSize: Theme.fontBody + wrapMode: Text.WordWrap + } + Row { + spacing: 12 + PhoebusButton { label: "Network settings"; onClicked: Quickshell.execDetached(["sh", "-c", "command -v dms >/dev/null && exec dms ipc call settings focusOrToggle || exec kitty -e sh -c 'nmcli device status; read -r _'"]) } + PhoebusButton { label: "Re-check"; onClicked: shell.refreshHandshake() } + } + } + PhoebusCard { + width: parent.width + Text { width: parent.width; text: "Prerequisites"; color: Theme.warmWhite; font.family: Theme.family; font.pixelSize: Theme.fontHeading; font.weight: Font.DemiBold } + PrereqRow { label: "64-bit x86_64 firmware"; ok: true; detail: shell.handshake ? shell.handshake.readiness.firmware : "?"; } + PrereqRow { label: "Memory"; ok: shell.handshake && shell.handshake.readiness.memory_mib >= 4096; detail: shell.handshake ? (shell.handshake.readiness.memory_mib + " MiB") : "?" } + PrereqRow { label: "Processors"; ok: true; detail: shell.handshake ? (shell.handshake.readiness.cpu_cores + " cores · " + shell.handshake.readiness.cpu_model) : "?" } + PrereqRow { label: "Network"; ok: shell.handshake && shell.handshake.readiness.network; detail: shell.handshake && shell.handshake.readiness.network ? "connected" : "offline" } + } + } + + // ============ STEP 2: AI ============================== + Column { + width: parent.width + spacing: 16 + visible: shell.step === 2 + PhoebusCard { + width: parent.width + Text { width: parent.width; text: "Connect an AI model"; color: Theme.warmWhite; font.family: Theme.family; font.pixelSize: Theme.fontHeading; font.weight: Font.DemiBold } + Text { + width: parent.width + text: "Phoebus is AI-first: installation requires a connected model. Choose a hosted provider, or point Phoebus at a model you have downloaded and are serving locally. The installed system boots, runs and recovers without one." + color: Theme.muted + font.family: Theme.family + font.pixelSize: Theme.fontBody + wrapMode: Text.WordWrap + } + PhoebusChoice { + id: providerChoice + options: [ + { value: "deepseek", label: "DeepSeek" }, + { value: "openai", label: "OpenAI" }, + { value: "local", label: "Local model" } + ] + value: shell.cfg ? shell.cfg.ai.provider : "deepseek" + onSelected: value => shell.configureProvider(value) + } + PhoebusField { + id: keyField + label: "API key" + placeholder: "Paste your provider key" + secret: true + visible: shell.cfg && (shell.cfg.ai.provider === "deepseek" || shell.cfg.ai.provider === "openai") + onEdited: value => shell.apiKey = value + } + PhoebusField { + id: modelField + label: "Model" + placeholder: "model name" + error: "" + onEdited: value => shell.cfg.ai.model = value + Component.onCompleted: inputItem.text = shell.cfg && shell.cfg.ai.model ? shell.cfg.ai.model : "" + } + PhoebusField { + id: endpointField + label: "Endpoint (local models)" + placeholder: "http://127.0.0.1:11434/v1/chat/completions" + visible: shell.cfg && shell.cfg.ai.provider === "local" + onEdited: value => shell.cfg.ai.endpoint = value + Component.onCompleted: inputItem.text = shell.cfg && shell.cfg.ai.endpoint ? shell.cfg.ai.endpoint : "" + } + Row { + spacing: 12 + PhoebusButton { + label: shell.aiChecking ? "Checking…" : "Connect and validate" + primary: true + actionEnabled: !shell.aiChecking + onClicked: shell.connectAi() + } + PhoebusChip { + visible: shell.aiConnected + text: "Connected" + tone: Theme.success + } + } + Text { + width: parent.width + visible: shell.aiError.length > 0 + text: shell.aiError + color: Theme.danger + font.family: Theme.family + font.pixelSize: Theme.fontSmall + wrapMode: Text.WordWrap + } + } + PhoebusCard { + width: parent.width + visible: shell.aiApplied.length > 0 + Text { width: parent.width; text: "Validated changes"; color: Theme.warmWhite; font.family: Theme.family; font.pixelSize: Theme.fontHeading; font.weight: Font.DemiBold } + Repeater { + model: shell.aiApplied + delegate: Column { + required property var modelData + width: parent.width + spacing: 2 + Text { width: parent.width; text: "• " + modelData.description; color: Theme.warmWhite; font.family: Theme.family; font.pixelSize: Theme.fontBody; wrapMode: Text.WordWrap } + Text { width: parent.width; text: " " + modelData.reason; color: Theme.muted; font.family: Theme.family; font.pixelSize: Theme.fontSmall; wrapMode: Text.WordWrap } + } + } + } + } + + // ============ STEP 3: disk ============================ + Column { + width: parent.width + spacing: 16 + visible: shell.step === 3 + Text { width: parent.width; text: "Choose the destination disk"; color: Theme.warmWhite; font.family: Theme.family; font.pixelSize: Theme.fontHeading; font.weight: Font.DemiBold } + Text { width: parent.width; text: "The listed disk is erased completely. Protected disks and the installation medium cannot be selected."; color: Theme.muted; font.family: Theme.family; font.pixelSize: Theme.fontSmall; wrapMode: Text.WordWrap } + Text { width: parent.width; visible: shell.issueFor("target_disk").length > 0; text: shell.issueFor("target_disk"); color: Theme.danger; font.family: Theme.family; font.pixelSize: Theme.fontSmall; wrapMode: Text.WordWrap } + Repeater { + model: shell.disks + delegate: DiskCard { + required property var modelData + width: stepColumn.width + disk: modelData + selected: shell.cfg && shell.cfg.storage.disk === modelData.path + onPicked: path => { shell.cfg.storage.disk = path; shell.selectedDisk = path; } + } + } + PhoebusButton { label: "Rescan disks"; compact: true; onClicked: shell.refreshDisks() } + } + + // ============ STEP 4: account ========================= + Column { + width: parent.width + spacing: 16 + visible: shell.step === 4 + PhoebusCard { + width: parent.width + Text { width: parent.width; text: "Your account"; color: Theme.warmWhite; font.family: Theme.family; font.pixelSize: Theme.fontHeading; font.weight: Font.DemiBold } + PhoebusField { id: fullnameField; label: "Full name"; onEdited: value => shell.cfg.user.fullname = value; Component.onCompleted: inputItem.text = shell.cfg ? shell.cfg.user.fullname : "" } + PhoebusField { id: userField; label: "Username"; placeholder: "lowercase"; error: shell.issueFor("username"); onEdited: value => shell.cfg.user.username = value; Component.onCompleted: inputItem.text = shell.cfg ? shell.cfg.user.username : "" } + PhoebusField { id: hostField; label: "Computer name"; placeholder: "phoebus"; error: shell.issueFor("hostname"); onEdited: value => shell.cfg.system.hostname = value; Component.onCompleted: inputItem.text = shell.cfg ? shell.cfg.system.hostname : "" } + PhoebusField { id: pwField; label: "Password"; secret: true; error: shell.issueFor("password"); onEdited: value => shell.userPw = value } + PhoebusField { id: pw2Field; label: "Confirm password"; secret: true; error: shell.issueFor("password_confirm"); onEdited: value => shell.userPw2 = value } + } + PhoebusCard { + width: parent.width + Text { width: parent.width; text: "Disk encryption"; color: Theme.warmWhite; font.family: Theme.family; font.pixelSize: Theme.fontHeading; font.weight: Font.DemiBold } + Text { width: parent.width; text: "LUKS2 whole-disk encryption protects your data at rest. Keep this passphrase safe: without it the disk cannot be unlocked."; color: Theme.muted; font.family: Theme.family; font.pixelSize: Theme.fontSmall; wrapMode: Text.WordWrap } + PhoebusField { id: luksField; label: "Encryption passphrase"; secret: true; error: shell.issueFor("passphrase"); onEdited: value => shell.luksPw = value } + PhoebusField { id: luks2Field; label: "Confirm passphrase"; secret: true; error: shell.issueFor("passphrase_confirm"); onEdited: value => shell.luksPw2 = value } + } + PhoebusCard { + width: parent.width + PhoebusButton { label: shell.showAdvanced ? "Hide advanced options" : "Advanced options"; compact: true; onClicked: shell.showAdvanced = !shell.showAdvanced } + Column { + width: parent.width + spacing: 12 + visible: shell.showAdvanced + Text { width: parent.width; text: "Filesystem"; color: Theme.muted; font.family: Theme.family; font.pixelSize: Theme.fontSmall } + PhoebusChoice { + options: [{ value: "btrfs", label: "Btrfs (snapshots, recommended)" }, { value: "ext4", label: "ext4" }] + value: shell.cfg ? shell.cfg.storage.filesystem : "btrfs" + onSelected: value => { shell.cfg.storage.filesystem = value; shell.touchConfig(); } + } + Text { width: parent.width; text: "Kernel"; color: Theme.muted; font.family: Theme.family; font.pixelSize: Theme.fontSmall } + PhoebusChoice { + options: [{ value: "optimized", label: "Optimized" }, { value: "safe", label: "Safe (binary)" }, { value: "aggressive", label: "Aggressive" }] + value: shell.cfg ? shell.cfg.kernel.profile : "optimized" + onSelected: value => { shell.cfg.kernel.profile = value; shell.touchConfig(); } + } + Text { width: parent.width; text: "Package policy"; color: Theme.muted; font.family: Theme.family; font.pixelSize: Theme.fontSmall } + PhoebusChoice { + options: [{ value: "balanced", label: "Balanced" }, { value: "source_first", label: "Source first" }, { value: "binary_first", label: "Binary first" }] + value: shell.cfg ? shell.cfg.packages.policy : "balanced" + onSelected: value => { shell.cfg.packages.policy = value; shell.touchConfig(); } + } + Text { width: parent.width; text: "Desktop"; color: Theme.muted; font.family: Theme.family; font.pixelSize: Theme.fontSmall } + PhoebusChoice { + options: [{ value: "mango", label: "Mango + DankMaterialShell (recommended)" }, { value: "dwl", label: "dwl (fallback)" }, { value: "none", label: "No desktop" }] + value: shell.cfg ? shell.cfg.desktop.profile : "mango" + onSelected: value => { shell.cfg.desktop.profile = value; shell.touchConfig(); } + } + PhoebusToggle { label: "Flatpak"; description: "Install Flatpak and configure Flathub"; checked: shell.cfg ? shell.cfg.desktop.flatpak : true; onToggled: value => { shell.cfg.desktop.flatpak = value; shell.touchConfig(); } } + PhoebusToggle { label: "Nix"; description: "Second package lane for development tools"; checked: shell.cfg ? shell.cfg.packages.nix : true; onToggled: value => { shell.cfg.packages.nix = value; shell.touchConfig(); } } + PhoebusToggle { label: "Signed binary packages"; description: "Reuse the official Gentoo binhost where USE matches"; checked: shell.cfg ? shell.cfg.packages.binary_packages : true; onToggled: value => { shell.cfg.packages.binary_packages = value; shell.touchConfig(); } } + } + } + } + + // ============ STEP 5: review ========================== + Column { + width: parent.width + spacing: 16 + visible: shell.step === 5 + PhoebusCard { + width: parent.width + Text { width: parent.width; text: "Review the installation plan"; color: Theme.warmWhite; font.family: Theme.family; font.pixelSize: Theme.fontHeading; font.weight: Font.DemiBold } + Text { width: parent.width; text: "Target disk"; color: Theme.muted; font.family: Theme.family; font.pixelSize: Theme.fontSmall } + Text { width: parent.width; text: shell.review ? shell.review.target_disk : "…"; color: Theme.danger; font.family: Theme.family; font.pixelSize: Theme.fontTitle; font.weight: Font.DemiBold } + Text { width: parent.width; text: "The disk above will be erased. Everything on it is destroyed."; color: Theme.warmWhite; font.family: Theme.family; font.pixelSize: Theme.fontBody; wrapMode: Text.WordWrap } + } + PhoebusCard { + width: parent.width + Text { width: parent.width; text: "What will be created"; color: Theme.warmWhite; font.family: Theme.family; font.pixelSize: Theme.fontHeading; font.weight: Font.DemiBold } + ReviewRow { label: "Encryption"; value: shell.review ? shell.review.encryption : "…" } + ReviewRow { label: "Filesystem"; value: shell.review ? shell.review.filesystem : "…" } + ReviewRow { label: "Desktop"; value: shell.review ? shell.review.desktop : "…" } + ReviewRow { label: "Computer name"; value: shell.review ? shell.review.hostname : "…" } + ReviewRow { label: "User"; value: shell.review ? shell.review.username : "…" } + ReviewRow { label: "Locale"; value: shell.review ? shell.review.locale : "…" } + ReviewRow { label: "Timezone"; value: shell.review ? shell.review.timezone : "…" } + ReviewRow { label: "Subsystems"; value: shell.review ? shell.review.subsystems.join(", ") : "…" } + ReviewRow { label: "Subvolumes"; value: shell.review ? shell.review.subvolumes.join(" ") : "…" } + } + PhoebusCard { + width: parent.width + Text { width: parent.width; text: "Destructive preview"; color: Theme.warning; font.family: Theme.family; font.pixelSize: Theme.fontHeading; font.weight: Font.DemiBold } + Text { width: parent.width; text: shell.previewText; color: Theme.muted; font.family: "monospace"; font.pixelSize: Theme.fontSmall; wrapMode: Text.WordWrap } + } + } + + // ============ STEP 6: confirm ========================= + Column { + width: parent.width + spacing: 16 + visible: shell.step === 6 + PhoebusCard { + width: parent.width + Text { width: parent.width; text: "Authorize the installation"; color: Theme.warmWhite; font.family: Theme.family; font.pixelSize: Theme.fontHeading; font.weight: Font.DemiBold } + Text { width: parent.width; text: "All data on " + (shell.cfg ? shell.cfg.storage.disk : "the target") + " will be erased. This cannot be undone."; color: Theme.danger; font.family: Theme.family; font.pixelSize: Theme.fontBody; wrapMode: Text.WordWrap } + PhoebusField { id: eraseField; label: "Type ERASE to authorize"; placeholder: "ERASE"; onEdited: value => shell.eraseText = value } + PhoebusToggle { label: "I understand that the target disk will be erased"; checked: shell.finalConfirm; onToggled: value => shell.finalConfirm = value } + } + } + } + } + + // -- progress / result ---------------------------------------- + Column { + width: parent.width + height: parent.height - 48 - 12 + spacing: 14 + visible: shell.phase !== "form" + + Column { + width: parent.width + spacing: 10 + visible: shell.phase === "progress" + Text { text: "Installing Phoebus OS"; color: Theme.warmWhite; font.family: Theme.family; font.pixelSize: Theme.fontTitle; font.weight: Font.DemiBold } + Text { width: parent.width; text: "The stages below are the real backend stages. Downloads, compilation, configuration and verification are reported as they happen; no percentage is estimated."; color: Theme.muted; font.family: Theme.family; font.pixelSize: Theme.fontSmall; wrapMode: Text.WordWrap } + Rectangle { + id: progressTrack + width: parent.width; height: 6; radius: 3; color: Theme.border + Rectangle { + id: progressBar + width: progressTrack.width * 0.3; height: parent.height; radius: 3; color: Theme.amber + SequentialAnimation on x { + loops: Animation.Infinite + NumberAnimation { from: 0; to: progressTrack.width - progressBar.width; duration: 1100; easing.type: Easing.InOutQuad } + NumberAnimation { from: progressTrack.width - progressBar.width; to: 0; duration: 1100; easing.type: Easing.InOutQuad } + } + } + } + Repeater { + model: shell.stageOrder + delegate: Row { + required property var modelData + width: parent.width + spacing: 10 + Rectangle { + width: 12; height: 12; radius: 6 + anchors.verticalCenter: parent.verticalCenter + color: shell.stageStatus[modelData] === "failed" ? Theme.danger + : shell.stageStatus[modelData] === "finished" ? Theme.success + : Theme.amber + } + Text { + text: stageLabel(modelData) + color: Theme.warmWhite + font.family: Theme.family + font.pixelSize: Theme.fontBody + } + Text { + text: stageCategory(modelData) + color: Theme.muted + font.family: Theme.family + font.pixelSize: Theme.fontSmall + } + } + } + } + + Column { + width: parent.width + spacing: 12 + visible: shell.phase === "done" + Row { + spacing: 14 + PhoebusEmblem { width: 64; height: 64 } + Column { + Text { text: "Phoebus OS is installed"; color: Theme.success; font.family: Theme.family; font.pixelSize: Theme.fontTitle; font.weight: Font.DemiBold } + Text { text: "Your system is ready. It can boot, run and recover without a network or a model."; color: Theme.muted; font.family: Theme.family; font.pixelSize: Theme.fontBody; wrapMode: Text.WordWrap } + } + } + PhoebusCard { + width: parent.width + Text { width: parent.width; text: "Next steps"; color: Theme.warmWhite; font.family: Theme.family; font.pixelSize: Theme.fontHeading; font.weight: Font.DemiBold } + Text { width: parent.width; text: "1. Remove the installation medium.\n2. Restart the computer."; color: Theme.warmWhite; font.family: Theme.family; font.pixelSize: Theme.fontBody; wrapMode: Text.WordWrap } + } + Row { + spacing: 12 + PhoebusButton { label: "Restart now"; primary: true; onClicked: shell.restartNow() } + PhoebusButton { label: "Close installer"; onClicked: shell.closeInstaller() } + } + } + + Column { + width: parent.width + spacing: 12 + visible: shell.phase === "failed" + Text { text: "Installation stopped"; color: Theme.danger; font.family: Theme.family; font.pixelSize: Theme.fontTitle; font.weight: Font.DemiBold } + PhoebusCard { + width: parent.width + Text { width: parent.width; text: "What happened"; color: Theme.warmWhite; font.family: Theme.family; font.pixelSize: Theme.fontHeading; font.weight: Font.DemiBold } + Text { width: parent.width; text: shell.failureText; color: Theme.warmWhite; font.family: Theme.family; font.pixelSize: Theme.fontBody; wrapMode: Text.WordWrap } + Text { width: parent.width; text: "Disk changes: " + shell.failureDisk; color: shell.failureDisk === "yes" || shell.failureDisk === "partial" ? Theme.warning : Theme.success; font.family: Theme.family; font.pixelSize: Theme.fontBody } + Repeater { + model: shell.failureNext + delegate: Text { required property var modelData; width: parent.width; text: "• " + modelData; color: Theme.muted; font.family: Theme.family; font.pixelSize: Theme.fontSmall; wrapMode: Text.WordWrap } + } + } + Row { + spacing: 12 + PhoebusButton { label: shell.showFailureLog ? "Hide log" : "View redacted log"; onClicked: { shell.showFailureLog = !shell.showFailureLog; if (shell.showFailureLog) Bridge.logTail(200, r => { if (r.ok) shell.logLines = r.data.lines; }); } } + PhoebusButton { label: "Back to review"; onClicked: { shell.phase = "form"; shell.step = 5; shell.enterStep(); } } + PhoebusButton { label: "Close installer"; compact: true; onClicked: shell.closeInstaller() } + } + PhoebusCard { + width: parent.width + visible: shell.showFailureLog + Text { width: parent.width; text: shell.logLines.join("\n"); color: Theme.muted; font.family: "monospace"; font.pixelSize: Theme.fontSmall; wrapMode: Text.WrapAnywhere } + } + } + } + + // -- footer ---------------------------------------------------- + Item { + width: parent.width + height: 56 + visible: shell.phase === "form" + Text { + anchors.left: parent.left + anchors.verticalCenter: parent.verticalCenter + text: (!Bridge.ready ? "Installer backend starting… " : "") + (Bridge.lastError.length > 0 ? "[" + Bridge.lastError + "] " : "") + shell.status + color: shell.status.indexOf("fix") !== -1 || shell.status.indexOf("requires") !== -1 ? Theme.danger : Theme.muted + font.family: Theme.family + font.pixelSize: Theme.fontSmall + width: Math.max(120, parent.width - 320) + wrapMode: Text.WordWrap + } + Row { + anchors.right: parent.right + anchors.verticalCenter: parent.verticalCenter + spacing: 12 + PhoebusButton { label: "Back"; actionEnabled: shell.step > 0 && shell.step < 7; onClicked: shell.back() } + PhoebusButton { + visible: shell.step < 6 + label: "Next" + primary: true + onClicked: shell.advance() + } + PhoebusButton { + visible: shell.step === 6 + label: "Install now" + primary: true + onClicked: shell.authorizeAndInstall() + } + } + } + } + } + + // -- inline helper components ------------------------------------------ + component PrereqRow: Row { + property string label: "" + property bool ok: true + property string detail: "" + width: parent.width + spacing: 10 + Rectangle { + width: 10; height: 10; radius: 5 + anchors.verticalCenter: parent.verticalCenter + color: parent.ok ? Theme.success : Theme.danger + } + Text { text: parent.label; color: Theme.warmWhite; font.family: Theme.family; font.pixelSize: Theme.fontBody; width: 260 } + Text { text: parent.detail; color: Theme.muted; font.family: Theme.family; font.pixelSize: Theme.fontSmall; width: parent.width - 300; wrapMode: Text.WordWrap } + } + + component ReviewRow: Row { + property string label: "" + property string value: "" + width: parent.width + spacing: 10 + Text { text: parent.label; color: Theme.muted; font.family: Theme.family; font.pixelSize: Theme.fontBody; width: 160 } + Text { text: parent.value; color: Theme.warmWhite; font.family: Theme.family; font.pixelSize: Theme.fontBody; width: parent.width - 180; wrapMode: Text.WordWrap } + } + + component DiskCard: Rectangle { + id: diskCard + property var disk: null + property bool selected: false + signal picked(string path) + readonly property bool usable: disk !== null && !disk.protected + height: inner.implicitHeight + 24 + radius: Theme.radius + color: selected ? Qt.rgba(0.91, 0.64, 0.24, 0.12) : Theme.surface + border.width: selected || activeFocus ? 2 : 1 + border.color: activeFocus ? Theme.focusRing : (selected ? Theme.amber : Theme.border) + opacity: usable ? 1 : 0.7 + activeFocusOnTab: usable + Accessible.role: Accessible.RadioButton + Accessible.name: disk ? disk.path : "" + Accessible.checked: selected + + Keys.onReturnPressed: if (usable) diskCard.picked(diskCard.disk.path) + Keys.onEnterPressed: if (usable) diskCard.picked(diskCard.disk.path) + Keys.onSpacePressed: if (usable) diskCard.picked(diskCard.disk.path) + + MouseArea { + anchors.fill: parent + enabled: diskCard.usable + cursorShape: Qt.PointingHandCursor + onClicked: diskCard.picked(diskCard.disk.path) + } + + Column { + id: inner + anchors.left: parent.left + anchors.right: parent.right + anchors.top: parent.top + anchors.margins: 12 + spacing: 4 + Row { + spacing: 10 + Text { text: diskCard.disk ? diskCard.disk.path : ""; color: diskCard.usable ? Theme.warmWhite : Theme.muted; font.family: Theme.family; font.pixelSize: Theme.fontBody; font.weight: Font.DemiBold } + Text { text: diskCard.disk ? diskCard.disk.size_human : ""; color: Theme.amber; font.family: Theme.family; font.pixelSize: Theme.fontBody } + PhoebusChip { visible: diskCard.disk && diskCard.disk.live_medium; text: "installation medium"; tone: Theme.amber } + PhoebusChip { visible: diskCard.disk && diskCard.disk.protected && !diskCard.disk.live_medium; text: "protected"; tone: Theme.danger } + PhoebusChip { visible: diskCard.selected; text: "selected"; tone: Theme.amber } + } + Text { width: parent.width; text: diskCard.disk ? diskCard.disk.model + " · " + diskCard.disk.transport : ""; color: Theme.muted; font.family: Theme.family; font.pixelSize: Theme.fontSmall; wrapMode: Text.WordWrap } + Text { width: parent.width; visible: diskCard.disk !== null && diskCard.disk.protection != null; text: (diskCard.disk !== null && diskCard.disk.protection != null) ? ("Reason: " + diskCard.disk.protection) : ""; color: Theme.danger; font.family: Theme.family; font.pixelSize: Theme.fontSmall; wrapMode: Text.WordWrap } + Text { width: parent.width; visible: diskCard.disk && diskCard.disk.partitions.length > 0; text: "Existing partitions: " + (diskCard.disk ? diskCard.disk.partitions.join(", ") : ""); color: Theme.muted; font.family: Theme.family; font.pixelSize: Theme.fontSmall; wrapMode: Text.WordWrap } + } + } + + function stageLabel(stage) { + for (let i = 0; i < shell.progressLog.length; i++) { + if (shell.progressLog[i].stage === stage) + return shell.progressLog[i].label; + } + return stage; + } + function stageCategory(stage) { + for (let i = 0; i < shell.progressLog.length; i++) { + if (shell.progressLog[i].stage === stage && shell.progressLog[i].status === "started") + return "(" + shell.progressLog[i].category + ")"; + } + return ""; + } + + property string eraseText: "" + property bool finalConfirm: false +} diff --git a/installer/live/desktop/phoebus-welcome/Common b/installer/live/desktop/phoebus-welcome/Common new file mode 120000 index 0000000..60d3b0a --- /dev/null +++ b/installer/live/desktop/phoebus-welcome/Common @@ -0,0 +1 @@ +../common \ No newline at end of file diff --git a/installer/live/desktop/phoebus-welcome/shell.qml b/installer/live/desktop/phoebus-welcome/shell.qml new file mode 100644 index 0000000..83ff26e --- /dev/null +++ b/installer/live/desktop/phoebus-welcome/shell.qml @@ -0,0 +1,388 @@ +import QtQuick +import Quickshell +import Quickshell.Io +import "Common" + +// Phoebus OS live welcome. This is the ISO's launcher: it shows the identity, +// the system's readiness, a dominant "Install Phoebus OS" action and secondary +// troubleshooting tools under Advanced. It never authorizes or starts disk +// changes; only the installer does that, behind its own ERASE confirmation. +ShellRoot { + id: shell + + property string isoVersion: "0.1.0" + property bool networkUp: false + property string firmware: "UEFI" + property string memory: "?" + property string cores: "?" + property bool showAdvanced: false + property bool showPower: false + property bool showKeyboardTest: false + + function run(cmd) { + Quickshell.execDetached(cmd); + } + + Process { + id: readiness + command: ["sh", "-c", + "echo VERSION=$(cat /etc/phoebus/version 2>/dev/null || cat /usr/share/phoebus/version 2>/dev/null || echo 0.1.0); " + + "awk 'NR>1 && $2==\"00000000\" {print \"NET=up\"; found=1; exit} END {if (!found) print \"NET=down\"}' /proc/net/route; " + + "if [ -d /sys/firmware/efi ]; then echo FW=UEFI; else echo FW=BIOS; fi; " + + "awk '/MemTotal/ {printf \"MEM=%.1f GiB\\n\", $2/1048576}' /proc/meminfo; " + + "echo CORES=$(nproc)"] + running: true + stdout: SplitParser { + onRead: line => { + const parts = ("" + line).split("="); + if (parts.length !== 2) + return; + switch (parts[0]) { + case "VERSION": shell.isoVersion = parts[1]; break; + case "NET": shell.networkUp = parts[1] === "up"; break; + case "FW": shell.firmware = parts[1]; break; + case "MEM": shell.memory = parts[1]; break; + case "CORES": shell.cores = parts[1]; break; + } + } + } + } + + FloatingWindow { + id: window + Component.onCompleted: { if (typeof window.requestActivate === "function") window.requestActivate(); } + visible: true + color: Theme.charcoal + implicitWidth: 940 + implicitHeight: 620 + title: "Phoebus OS" + + // Backdrop: wallpaper when available, a calm charcoal gradient always. + Rectangle { + anchors.fill: parent + gradient: Gradient { + GradientStop { position: 0.0; color: "#1c1c22" } + GradientStop { position: 1.0; color: "#121215" } + } + } + Image { + anchors.fill: parent + source: Theme.wallpaper + fillMode: Image.PreserveAspectCrop + smooth: true + visible: status === Image.Ready + } + Rectangle { + anchors.fill: parent + color: Theme.overlay + } + + Column { + id: page + anchors.fill: parent + anchors.margins: Theme.padLarge + spacing: 18 + + // -- header ---------------------------------------------------- + Item { + width: parent.width + height: 56 + + Row { + anchors.left: parent.left + anchors.verticalCenter: parent.verticalCenter + spacing: 14 + + PhoebusEmblem { + width: 56 + height: 56 + anchors.verticalCenter: parent.verticalCenter + } + + Column { + anchors.verticalCenter: parent.verticalCenter + spacing: 2 + Text { + text: "PHOEBUS OS" + textFormat: Text.StyledText + color: Theme.warmWhite + font.family: Theme.family + font.pixelSize: 26 + font.weight: Font.DemiBold + font.letterSpacing: 3 + } + Text { + text: "A modern, encrypted, AI-first workstation" + color: Theme.muted + font.family: Theme.family + font.pixelSize: Theme.fontSmall + } + } + } + + Rectangle { + anchors.right: parent.right + anchors.verticalCenter: parent.verticalCenter + height: 30 + width: versionText.implicitWidth + 24 + radius: 15 + color: Theme.surface + border.width: 1 + border.color: Theme.border + Text { + id: versionText + anchors.centerIn: parent + text: "Live medium · " + shell.isoVersion + color: Theme.amber + font.family: Theme.family + font.pixelSize: Theme.fontSmall + } + } + } + + // -- hero + primary action ------------------------------------ + PhoebusCard { + width: parent.width + padding: Theme.padLarge + + Text { + width: parent.width + text: "Welcome to Phoebus OS" + color: Theme.warmWhite + font.family: Theme.family + font.pixelSize: Theme.fontDisplay + font.weight: Font.DemiBold + } + Text { + width: parent.width + text: "This medium installs Phoebus to your computer. The installer guides you through language, networking, a connected AI model, the target disk, your account and encryption." + color: Theme.muted + font.family: Theme.family + font.pixelSize: Theme.fontBody + wrapMode: Text.WordWrap + } + + Row { + width: parent.width + spacing: 20 + + PhoebusButton { + label: "Install Phoebus OS" + primary: true + implicitHeight: 58 + implicitWidth: 300 + focus: true + activeFocusOnTab: true + Accessible.name: "Install Phoebus OS" + onClicked: shell.run(["/usr/local/bin/phoebus-install"]) + } + + Column { + width: parent.width - 320 + spacing: 6 + anchors.verticalCenter: parent.verticalCenter + Row { + spacing: 8 + PhoebusChip { + text: shell.networkUp ? "Network connected" : "Network offline" + tone: shell.networkUp ? Theme.success : Theme.warning + } + PhoebusChip { text: shell.firmware; tone: Theme.muted } + PhoebusChip { text: shell.memory + " RAM"; tone: Theme.muted } + PhoebusChip { text: shell.cores + " cores"; tone: Theme.muted } + } + Text { + width: parent.width + text: "Nothing is written until you review the plan and type ERASE. An installed system boots without a network or a model." + color: Theme.muted + font.family: Theme.family + font.pixelSize: Theme.fontSmall + wrapMode: Text.WordWrap + } + } + } + } + + // -- secondary actions ---------------------------------------- + Flow { + width: parent.width + spacing: 12 + + PhoebusButton { + label: "Network" + onClicked: shell.run(["sh", "-c", + "command -v dms >/dev/null && exec dms ipc call settings focusOrToggle || exec kitty -e sh -c 'nmcli device status; read -r _'"]) + } + PhoebusButton { + label: "Display & keyboard" + onClicked: shell.run(["sh", "-c", + "command -v dms >/dev/null && dms ipc call settings focusOrToggle || kitty -e wlr-randr"]) + } + PhoebusButton { + label: "Accessibility" + onClicked: shell.run(["sh", "-c", + "command -v dms >/dev/null && dms ipc call settings focusOrToggle || true"]) + } + PhoebusButton { + label: "Installation help" + onClicked: shell.run(["sh", "-c", + "kitty -e sh -c 'cat /usr/share/phoebus/install-help.txt 2>/dev/null || echo Help is not installed; read -r || true'"]) + } + PhoebusButton { + label: "Keyboard test" + onClicked: shell.showKeyboardTest = true + } + PhoebusButton { + label: "Power" + onClicked: shell.showPower = true + } + } + + // -- advanced / troubleshooting ------------------------------- + PhoebusButton { + label: (shell.showAdvanced ? "Hide advanced tools" : "Advanced tools") + compact: true + onClicked: shell.showAdvanced = !shell.showAdvanced + } + + PhoebusCard { + width: parent.width + visible: shell.showAdvanced + fill: Theme.overlay + + Text { + width: parent.width + text: "Troubleshooting and recovery tools" + color: Theme.warmWhite + font.family: Theme.family + font.pixelSize: Theme.fontHeading + font.weight: Font.DemiBold + } + Text { + width: parent.width + text: "These tools are working and supported on the live medium. Recovery-image features are not shipped yet and are not listed here." + color: Theme.muted + font.family: Theme.family + font.pixelSize: Theme.fontSmall + wrapMode: Text.WordWrap + } + Flow { + width: parent.width + spacing: 12 + PhoebusButton { + label: "Terminal" + compact: true + onClicked: shell.run(["kitty"]) + } + PhoebusButton { + label: "System log" + compact: true + onClicked: shell.run(["kitty", "-e", "sh", "-c", "journalctl -b --no-pager | less; read -r _"]) + } + PhoebusButton { + label: "Installer log" + compact: true + onClicked: shell.run(["kitty", "-e", "sh", "-c", "tail -n 200 /var/log/phoebus-installer/install.log 2>/dev/null | less; read -r _"]) + } + PhoebusButton { + label: "Disk information" + compact: true + onClicked: shell.run(["kitty", "-e", "sh", "-c", "lsblk -o NAME,SIZE,MODEL,TYPE,MOUNTPOINTS; read -r _"]) + } + PhoebusButton { + label: "Network settings" + compact: true + onClicked: shell.run(["sh", "-c", "command -v dms >/dev/null && exec dms ipc call settings focusOrToggle || exec kitty -e sh -c 'nmcli device status; read -r _'"]) + } + } + } + + Item { width: 1; height: 1 } + } + + // -- keyboard test overlay ---------------------------------------- + Rectangle { + anchors.fill: parent + color: Theme.overlay + visible: shell.showKeyboardTest + MouseArea { anchors.fill: parent; onClicked: shell.showKeyboardTest = false } + + PhoebusCard { + anchors.centerIn: parent + width: 520 + padding: Theme.padLarge + Text { + width: parent.width + text: "Keyboard test" + color: Theme.warmWhite + font.family: Theme.family + font.pixelSize: Theme.fontTitle + font.weight: Font.DemiBold + } + Text { + width: parent.width + text: "Type in the field below to confirm your layout produces the characters you expect." + color: Theme.muted + font.family: Theme.family + font.pixelSize: Theme.fontBody + wrapMode: Text.WordWrap + } + PhoebusField { + id: keyTest + label: "Type here" + placeholder: "The quick brown fox…" + } + Row { + spacing: 12 + PhoebusButton { + label: "Close" + primary: true + onClicked: shell.showKeyboardTest = false + } + } + Component.onCompleted: keyTest.inputItem.forceActiveFocus() + } + } + + // -- power overlay ------------------------------------------------- + Rectangle { + anchors.fill: parent + color: Theme.overlay + visible: shell.showPower + MouseArea { anchors.fill: parent; onClicked: shell.showPower = false } + + PhoebusCard { + anchors.centerIn: parent + width: 420 + padding: Theme.padLarge + Text { + width: parent.width + text: "Power" + color: Theme.warmWhite + font.family: Theme.family + font.pixelSize: Theme.fontTitle + font.weight: Font.DemiBold + } + PhoebusButton { + label: "Restart" + onClicked: { + shell.showPower = false; + shell.run(["systemctl", "reboot"]); + } + } + PhoebusButton { + label: "Shut down" + onClicked: { + shell.showPower = false; + shell.run(["systemctl", "poweroff"]); + } + } + PhoebusButton { + label: "Cancel" + compact: true + onClicked: shell.showPower = false + } + } + } + } +} diff --git a/installer/live/install-help.txt b/installer/live/install-help.txt new file mode 100644 index 0000000..59589c3 --- /dev/null +++ b/installer/live/install-help.txt @@ -0,0 +1,45 @@ +Phoebus OS installation help +============================ + +What the installer does +----------------------- +The installer creates a GPT disk layout with an EFI system partition, a LUKS2 +encrypted container and a Btrfs filesystem with the @ / @home / @var +/@snapshots / @swap subvolumes. It then installs a verified Gentoo stage3 and +the packages needed for a Mango + DankMaterialShell desktop with PipeWire, +Flatpak and Nix. + +Nothing is written to a disk until you have reviewed the plan and typed ERASE +on the confirmation screen. + +Requirements +------------ +- 64-bit UEFI machine. +- At least 4 GiB of RAM and enough disk space (32 GiB or more recommended). +- A network connection during installation (the stage3 and packages are + downloaded; the installed system can boot and run offline). +- A connected AI model. Phoebus ships no model. Connect a hosted provider + (DeepSeek or OpenAI) or point the installer at a model you serve locally. + The installed system works without the model; you can always use the + deterministic `sys` command instead. + +Choosing a disk +--------------- +Only whole, writable disks are offered. Disks that hold mounted filesystems, +the live installation medium, optical/loop device-mapper devices and read-only +devices are protected and cannot be selected. + +Destructive changes +------------------- +Everything on the selected disk is destroyed. If the installation fails, the +screen tells you whether disk changes occurred and what the safe next actions +are. A failed installation can be restarted from the review screen; the disk is +re-created from scratch. + +Getting help +------------ +- The full installer log is at /var/log/phoebus-installer/install.log. +- The serial console (Ctrl+Alt+F2) logs in as phoebus / phoebus on the live + medium; sudo is passwordless there. +- Open "Advanced tools" on the welcome screen for a terminal, system log, + installer log and disk information. diff --git a/installer/live/livefs-hook.sh b/installer/live/livefs-hook.sh index 6a90c39..a231092 100644 --- a/installer/live/livefs-hook.sh +++ b/installer/live/livefs-hook.sh @@ -2,15 +2,19 @@ # mmdebstrap customize hook: turn a Debian testing rootfs into the Phoebus live # desktop (Mango + DankMaterialShell). Runs as root inside mmdebstrap's userns. # +# Payload installation (binaries, branding, Quickshell UI, the live marker) is +# done by build.sh after the rootfs is extracted, so a cached rootfs +# (PHOEBUS_REUSE_ROOTFS=1) still picks up changed assets. This hook only does +# the expensive, root-requiring work: user accounts, the Mango build and the +# DMS install. +# # Environment (set by build.sh): # PHOEBUS_SRC directory with the verified pinned source tarballs -# PHOEBUS_RELEASE directory with the static phoebus-installer and sys -# PHOEBUS_ASSETS directory with assets emitted by `phoebus-installer --emit-asset` # MANGO_VERSION, DMS_VERSION set -euo pipefail root="$1" -: "${PHOEBUS_SRC:?}" "${PHOEBUS_RELEASE:?}" "${PHOEBUS_ASSETS:?}" +: "${PHOEBUS_SRC:?}" MANGO_VERSION="${MANGO_VERSION:-0.17.2}" DMS_VERSION="${DMS_VERSION:-1.6.2}" LIVE_USER=phoebus @@ -21,13 +25,6 @@ in_root() { "$@" } -install_asset() { - local name="$1" dest="$2" mode="${3:-0644}" - local src="$PHOEBUS_ASSETS/$name" - [ -f "$src" ] || { echo "livefs-hook: missing asset $name" >&2; exit 1; } - install -D -m "$mode" "$src" "$root/$dest" -} - say() { echo "livefs-hook: $*"; } say "live user" @@ -49,28 +46,6 @@ if ! in_root id greeter >/dev/null 2>&1; then --shell /sbin/nologin --comment "Phoebus greeter" greeter fi -say "installer and system broker" -install -D -m 0755 "$PHOEBUS_RELEASE/phoebus-installer" "$root/usr/local/bin/phoebus-installer" -install -D -m 0755 "$PHOEBUS_RELEASE/sys" "$root/usr/local/bin/sys" - -say "shared desktop assets" -install_asset session-mango /usr/local/bin/phoebus-session-mango 0755 -install_asset session-dwl /usr/local/bin/phoebus-session 0755 -install_asset assistant /usr/local/bin/phoebus-assistant 0755 -install_asset install /usr/local/bin/phoebus-install 0755 -install_asset menu /usr/local/bin/phoebus-menu 0755 -install_asset lock /usr/local/bin/phoebus-lock 0755 -install_asset idle /usr/local/bin/phoebus-idle 0755 -install_asset mango-config /etc/xdg/mango/config.conf -install_asset mango-session-target /usr/lib/systemd/user/mango-session.target -install_asset install-desktop /usr/share/applications/phoebus-install.desktop -install_asset wayland-session-mango /usr/share/wayland-sessions/phoebus-mango.desktop -install_asset wayland-session-dwl /usr/share/wayland-sessions/phoebus-dwl.desktop -install_asset waybar-config /etc/xdg/waybar/config -install_asset waybar-style /etc/xdg/waybar/style.css -# Live-only automatic login (never copied to an installed system). -install_asset greetd-live /etc/greetd/config.toml - say "build Mango ${MANGO_VERSION}" tar -xzf "$PHOEBUS_SRC/mango-${MANGO_VERSION}.tar.gz" -C "$root/tmp" in_root sh -c "cd /tmp/mango-${MANGO_VERSION} && \ diff --git a/installer/tests/vm/appliance-guest-gui.sh b/installer/tests/vm/appliance-guest-gui.sh new file mode 100644 index 0000000..7061d00 --- /dev/null +++ b/installer/tests/vm/appliance-guest-gui.sh @@ -0,0 +1,56 @@ +#!/bin/bash +# Guest-side, non-interactive install for the graphical Phoebus live ISO. +# +# Fetched and run by gui-driver.py inside the live guest. Configuration and +# secrets are fetched from the host over QEMU user networking so they never +# appear in the serial transcript. The installer log is scanned for the LUKS +# passphrase so a leak fails the run. +# +# This uses the same deterministic backend as the graphical installer; the GUI +# is a typed frontend over it, so a CLI install and a GUI install execute the +# same stages. +set -uo pipefail + +SERVE="${SERVE_URL:-http://10.0.2.2:8000}" +WORK=/tmp/phoebus-guest +mkdir -p "$WORK" +cd "$WORK" || exit 1 + +for f in test.conf luks.pw user.pw; do + if ! curl -fsSL "$SERVE/$f" -o "$f"; then + echo "===FETCH-FAIL=== ($f)" + exit 1 + fi +done +chmod 600 luks.pw user.pw + +PHOEBUS=/usr/local/bin/phoebus-installer +if [ ! -x "$PHOEBUS" ]; then + echo "===FETCH-FAIL=== (no phoebus-installer)" + exit 1 +fi + +"$PHOEBUS" --version || true + +sudo -n "$PHOEBUS" --config "$WORK/test.conf" --install --yes --no-ai \ + --luks-passphrase-file "$WORK/luks.pw" \ + --user-password-file "$WORK/user.pw" +RC=$? + +LEAK=0 +for log in /run/phoebus-installer/install.log /tmp/phoebus-installer/install.log; do + if [ -f "$log" ] && grep -F -q "$(cat "$WORK/luks.pw")" "$log"; then + LEAK=1 + fi +done +if [ "$LEAK" = 1 ]; then + echo "===SECRET_LEAK===" + RC=99 +else + echo "===NO_SECRET_LEAK===" +fi + +echo "===INSTALL-RC=$RC===" +sync +sudo -n poweroff -f || poweroff -f +echo "===POWEROFF===" diff --git a/installer/tests/vm/gui-driver.py b/installer/tests/vm/gui-driver.py new file mode 100644 index 0000000..7bb97bb --- /dev/null +++ b/installer/tests/vm/gui-driver.py @@ -0,0 +1,346 @@ +#!/usr/bin/env python3 +"""Headless driver for the Phoebus graphical live/installer ISO. + +The live medium boots into Mango + DankMaterialShell and opens the branded +welcome window. This driver boots it with a graphical device and a serial +console, checks the launcher/branding payload, drives the graphical installer +with `wtype` over the live session, and captures QEMU framebuffer screenshots. + +Modes: + + gui : boot, log in on serial, verify the welcome/branding payload, open + the installer, prove duplicate prevention, walk the first steps and + capture screenshots. + install : boot, log in on serial, fetch a non-interactive config and 0600 + secrets over QEMU user networking, run the deterministic install + with the static binary, scan the log for a secret leak, power off. + boot : boot the installed disk alone (no ISO), unlock LUKS, log in and run + verification commands. + +`DISK` must always be a disposable qcow2 image. This script never touches a +physical disk. +""" +import os +import socket +import sys +import time + +import pexpect + +QEMU = os.environ.get("QEMU_BIN", "qemu-system-x86_64") +OVMF_CODE = os.environ["OVMF_CODE"] +OVMF_VARS = os.environ["OVMF_VARS"] +ISO = os.environ.get("ISO", "") +DISK = os.environ.get("DISK", "") +SERIAL_LOG = os.environ.get("SERIAL_LOG", "/tmp/phoebus-gui-serial.log") +MONITOR = os.environ.get("MONITOR", "/tmp/phoebus-gui-monitor.sock") +SHOT_DIR = os.environ.get("SHOT_DIR", "/tmp/phoebus-gui-shots") +LIVE_USER = os.environ.get("LIVE_USER", "phoebus") +LIVE_PW = os.environ.get("LIVE_PASSWORD", "phoebus") +USER = os.environ.get("USERNAME", "phoebus") +USER_PW = os.environ.get("USER_PASSWORD", "phoebus-user-test") +LUKS_PW = os.environ.get("LUKS_PASSPHRASE", "phoebus-luks-test") +SERVE_URL = os.environ.get("SERVE_URL", "http://10.0.2.2:8000") +MEM = os.environ.get("VM_MEM", "8192") +SMP = os.environ.get("VM_SMP", "8") +BOOT_TIMEOUT = int(os.environ.get("BOOT_TIMEOUT", "900")) +INSTALL_TIMEOUT = int(os.environ.get("INSTALL_TIMEOUT", "10800")) + +WAYLAND_ENV = "XDG_RUNTIME_DIR=/run/user/1000" + + +def args(attach_iso=True, boot_disk=False): + a = [ + "-machine", "q35,accel=kvm", + "-cpu", "host", "-smp", SMP, "-m", MEM, + "-drive", f"if=pflash,format=raw,readonly=on,file={OVMF_CODE}", + "-drive", f"if=pflash,format=raw,file={OVMF_VARS}", + ] + if DISK: + a += ["-drive", f"file={DISK},if=virtio,format=qcow2"] + a += [ + # A real GPU device so the compositor gets a DRM node and a seat. + "-device", "virtio-gpu-pci", + "-netdev", "user,id=n0", "-device", "virtio-net-pci,netdev=n0,romfile=", + "-device", "virtio-rng-pci", + ] + if attach_iso and ISO: + a += ["-drive", f"file={ISO},media=cdrom,readonly=on"] + a += [ + "-boot", "order=c" if boot_disk else "order=d", + "-vga", "none", "-display", "none", + "-serial", "stdio", + "-monitor", f"unix:{MONITOR},server,nowait", + "-no-reboot", + ] + return a + + +def spawn(attach_iso=True, boot_disk=False): + if os.path.exists(MONITOR): + os.unlink(MONITOR) + child = pexpect.spawn(QEMU, args(attach_iso, boot_disk), timeout=BOOT_TIMEOUT, + encoding="utf-8", codec_errors="replace", maxread=65536) + child.delaybeforesend = 0.4 + return child + + +def screendump(name): + """Capture the QEMU framebuffer to SHOT_DIR/.ppm (and .png if + ImageMagick is available).""" + os.makedirs(SHOT_DIR, exist_ok=True) + target = os.path.join(SHOT_DIR, name + ".ppm") + if not os.path.exists(MONITOR): + return None + s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + s.settimeout(20) + try: + s.connect(MONITOR) + time.sleep(0.5) + try: + s.recv(65536) + except socket.timeout: + pass + s.sendall(b"screendump %s\n" % target.encode()) + time.sleep(2) + try: + s.recv(65536) + except socket.timeout: + pass + finally: + s.close() + if not os.path.exists(target): + return None + os.system(f"magick '{target}' '{target[:-4]}.png' 2>/dev/null || " + f"convert '{target}' '{target[:-4]}.png' 2>/dev/null") + return target + + +def login_live(child): + # The live serial getty shows ` login:` and the password is the + # known live-only credential. + idx = child.expect([r"login:", r"[$#] $"], timeout=BOOT_TIMEOUT) + if idx == 0: + child.sendline(LIVE_USER) + child.expect(r"[Pp]assword:", timeout=90) + child.sendline(LIVE_PW) + child.expect(r"[$#] $", timeout=180) + + +def live_shell(child, command, end_marker, timeout=180): + child.sendline(command) + child.expect(end_marker, timeout=timeout) + + +def set_wayland(child): + # Export the live user's Wayland socket for wtype-based GUI driving. + child.sendline( + 'export XDG_RUNTIME_DIR=/run/user/1000; ' + 'export WAYLAND_DISPLAY="$(basename "$(ls /run/user/1000/wayland-* 2>/dev/null | head -1)")"; ' + 'echo WAYLAND=$WAYLAND_DISPLAY' + ) + child.expect(r"WAYLAND=wayland-\d+", timeout=60) + + +def sendkey(*keys): + """Inject keys through the QEMU monitor (hardware keyboard level). This is + independent of the guest's input-method/portal setup.""" + if not os.path.exists(MONITOR): + return + s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + s.settimeout(10) + try: + s.connect(MONITOR) + time.sleep(0.3) + try: + s.recv(65536) + except socket.timeout: + pass + for k in keys: + s.sendall(("sendkey %s\n" % k).encode()) + time.sleep(0.2) + time.sleep(0.3) + try: + s.recv(65536) + except socket.timeout: + pass + finally: + s.close() + + +def key(child, *wtype_args): + quoted = " ".join(f"'{a}'" for a in wtype_args) + child.sendline(f"wtype {quoted} >/dev/null 2>&1; echo KEY-DONE") + child.expect("KEY-DONE", timeout=60) + + +def do_gui(): + child = spawn() + log = open(SERIAL_LOG, "w") + child.logfile = log + try: + login_live(child) + # Give greetd/the session time to bring up Mango + DMS + the welcome + # window (it starts after the shell is ready). + time.sleep(int(os.environ.get("SESSION_SETTLE", "30"))) + for _ in range(12): + child.sendline( + "echo WELCOME=$(pgrep -fc 'quickshell.*phoebus-welcome' 2>/dev/null || echo 0)" + ) + child.expect(r"WELCOME=(\d+)", timeout=60) + if int(child.match.group(1)) > 0: + break + time.sleep(5) + # Payload checks (no secrets here). + checks = ( + "echo ===GUI-CHECKS-$(printf START)===; " + "test -e /etc/phoebus/live && echo LIVE-MARKER; " + "test -s /usr/share/phoebus/branding/wallpaper.svg && echo BRAND-WALLPAPER; " + "test -s /usr/share/icons/hicolor/scalable/apps/phoebus.svg && echo BRAND-ICON; " + "test -s /etc/xdg/quickshell/phoebus-install/shell.qml && echo INSTALL-QML; " + "test -s /usr/share/applications/phoebus-install.desktop && echo DESKTOP-ENTRY; " + "test -f /home/phoebus/.config/DankMaterialShell/.firstlaunch && echo ONBOARDING-SUPPRESSED; " + "echo ===GUI-CHECKS-$(printf END)===" + ) + live_shell(child, checks, "===GUI-CHECKS-END===", timeout=180) + shot = screendump("01-welcome") + print("welcome screenshot:", shot, flush=True) + + set_wayland(child) + # Backend disk protection on the real VM: the live medium must be + # reported protected and never selectable. + child.sendline( + "printf '%s\\n%s\\n' '{\"id\":1,\"op\":\"disks\"}' '{\"id\":2,\"op\":\"quit\"}' " + "| sudo -n /usr/local/bin/phoebus-installer --gui-bridge 2>/dev/null " + "| head -1 > /tmp/disks.json; " + "echo DISKS=$(wc -c /dev/null || echo 0)") + child.expect(r"INST=(\d+)", timeout=60) + if int(child.match.group(1)) == 0: + # The window manager may not have focused the welcome; fall back to + # the launcher so the rest of the journey can still be exercised. + child.sendline( + "setsid /usr/local/bin/phoebus-install >/tmp/install-gui.log 2>&1 & echo LAUNCHED" + ) + child.expect("LAUNCHED", timeout=30) + time.sleep(7) + # Surface the installer frontend's own log (it contains bridge errors). + child.sendline( + "echo QMLLOG-$(printf START); " + "cat /run/user/1000/quickshell/by-id/*/log.qslog 2>/dev/null | " + "grep -aiE 'phoebus-bridge|error|failed|sudo|handshake' | tail -30; " + "echo NOTTY-SUDO; setsid sh -c 'sudo -n true' ; echo NOTTYSUDO=$?; " + "echo QMLLOG-$(printf END)" + ) + child.expect("QMLLOG-END", timeout=60) + screendump("02-installer-language") + # The first handshake probes hardware and disks; wait for it before + # driving the wizard so the backend is ready to validate. + time.sleep(int(os.environ.get("BACKEND_SETTLE", "30"))) + # Close the welcome so the installer window has the keyboard focus + # (Mango tiles both windows; the welcome would otherwise receive keys). + child.sendline("pkill -f 'quickshell.*phoebus-wel[c]ome' || true; sleep 2; echo CLOSED") + child.expect("CLOSED", timeout=30) + # Duplicate prevention: a second launch must not create a second session. + child.sendline( + "pgrep -f 'quickshell.*phoebus-install' | wc -l > /tmp/n1; " + "/usr/local/bin/phoebus-install >/tmp/install-gui2.log 2>&1; " + "pgrep -f 'quickshell.*phoebus-install' | wc -l > /tmp/n2; " + "echo DUP n1=$(cat /tmp/n1) n2=$(cat /tmp/n2)" + ) + child.expect(r"DUP n1=(\d+) n2=(\d+)", timeout=60) + print("duplicate check:", child.match.group(0), flush=True) + + # Move forward through the wizard with the keyboard shortcut. + sendkey("ctrl-right") + time.sleep(2) + screendump("03-network-prerequisites") + sendkey("ctrl-right") + time.sleep(2) + screendump("04-ai-model") + # Advancing without a connected model must be refused (blocked prereq). + sendkey("ctrl-right") + time.sleep(2) + screendump("05-ai-blocked") + print("gui checks complete", flush=True) + finally: + child.close(force=True) + log.close() + + +def do_install(): + child = spawn() + log = open(SERIAL_LOG, "w") + child.logfile = log + try: + login_live(child) + child.sendline( + f"curl -fsSL {SERVE_URL}/appliance-guest-gui.sh -o /tmp/gi.sh && bash /tmp/gi.sh" + ) + child.expect([r"===INSTALL-RC=([0-9]+)===", "===FETCH-FAIL===", + "Kernel panic", pexpect.EOF, pexpect.TIMEOUT], + timeout=INSTALL_TIMEOUT) + if "INSTALL-RC" in (child.after or ""): + print("INSTALL_RC", child.match.group(1), flush=True) + else: + print("INSTALL did not report a status", flush=True) + child.expect(["===POWEROFF===", pexpect.EOF, pexpect.TIMEOUT], timeout=600) + child.expect(pexpect.EOF, timeout=300) + finally: + child.close(force=True) + log.close() + + +def do_boot(): + # Detached: no ISO, boot from the installed disk only. + child = spawn(attach_iso=False, boot_disk=True) + log = open(SERIAL_LOG, "w") + child.logfile = log + checks = os.environ.get( + "BOOT_CHECKS", + "echo ===CHECKS-$(printf START)===; " + "cat /proc/1/comm; systemctl is-system-running; " + "systemctl --failed --no-pager; ip -brief addr; " + "lsblk -o NAME,SIZE,TYPE,FSTYPE,MOUNTPOINTS; echo ===CHECKS-$(printf END)===", + ) + try: + child.expect([r"[Pp]assphrase", r"login:"], timeout=BOOT_TIMEOUT) + if "assphrase" in (child.after or ""): + child.sendline(LUKS_PW) + for _ in range(5): + child.expect(r"phoebus login:", timeout=300) + child.sendline(USER) + idx = child.expect([r"[Pp]assword:", r"phoebus login:", r"Login incorrect"], + timeout=60) + if idx == 0: + child.sendline(USER_PW) + if child.expect([r"[$#] $", r"Login incorrect", r"phoebus login:"], + timeout=120) == 0: + break + child.sendline(checks) + child.expect("===CHECKS-END===", timeout=int(os.environ.get("CHECKS_TIMEOUT", "300"))) + print("checks complete", flush=True) + finally: + child.close(force=True) + log.close() + + +if __name__ == "__main__": + mode = sys.argv[1] if len(sys.argv) > 1 else "" + if mode == "gui": + do_gui() + elif mode == "install": + do_install() + elif mode == "boot": + do_boot() + else: + print(__doc__) + sys.exit(2)