From 34c12d3dd87b2005e15fd42d7c0462e2f5e293ba Mon Sep 17 00:00:00 2001 From: Phoebus Date: Tue, 22 Sep 2026 08:17:03 -0700 Subject: [PATCH] feat(installer): rebuild the graphical journey and fix interaction defects Rework the graphical installer into a fixed first-time-user sequence (Welcome, Language and keyboard, Internet and readiness, AI connection, Destination disk, Account and encryption, Review and confirmation, Installation, Completion) with configuration, validation, plans, approval and execution still authoritative in Rust. Fix the audited interaction defects: readiness `Re-check` is a read-only probe that no longer resets the step or clears the disk; model catalogs are fetched after syncing the edited settings and credentials and stale replies are ignored; editing a connection field invalidates the validated state; suggestion lists support arrow/Enter/Escape with a visible highlight and accessibility; the keyboard step labels the live-session limitation truthfully; readiness separates the local link from reachable install services; and busy states always clear, with the bridge failing outstanding requests when the backend exits. Add human-readable language/keyboard names, an explicit AI change review (Accept/Discard), backend-fact review with edit links, real stage progress with elapsed time and activity, and clearer failure and completion guidance. Extend the VM harness with a `gui-install` mode that drives the whole journey through the visible controls, plus regressions for readiness refresh, disk survival, keyboard suggestion selection and AI invalidation. Add Rust tests for readiness, the network probe, error kinds and labels. --- docs/CHANGELOG.md | 80 ++ docs/HANDOFF.md | 115 +- docs/STATUS.md | 7 +- .../phoebus-installer/src/gui_bridge.rs | 499 +++++++- installer/live/desktop/common/Bridge.qml | 51 +- .../live/desktop/common/PhoebusButton.qml | 2 +- .../live/desktop/common/PhoebusChoice.qml | 6 + .../live/desktop/common/PhoebusCombo.qml | 121 +- .../live/desktop/common/PhoebusField.qml | 96 +- .../live/desktop/common/PhoebusToggle.qml | 13 +- installer/live/desktop/common/Theme.qml | 25 +- .../live/desktop/phoebus-install/shell.qml | 1056 +++++++++++++---- installer/tests/vm/gui-driver.py | 417 ++++++- 13 files changed, 2108 insertions(+), 380 deletions(-) diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 55f54c3..36e570e 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -5,6 +5,86 @@ this file is the curated, human-readable summary. Format: Keep a Changelog. Dates are UTC. +## 2026-09-22 — Event-driven analysis of a first-time user's journey + +The graphical installer was audited against a first-time user's journey and +rebuilt around a fixed, explained sequence: Welcome, Language and keyboard, +Internet and readiness, AI connection, Destination disk, Account and +encryption, Review and confirmation, Installation, Completion. Configuration, +validation, plans, approval and execution stay authoritative in Rust. + +### Fixed +- **Network "Re-check" no longer resets the wizard.** The readiness refresh is + a separate, read-only bridge op (`readiness`) that updates the probe result + only; it cannot change the step or clear the selected disk. The first + handshake is the only path that initialises the form. +- **AI catalogs are fetched for the connection on screen.** "Load model + list" now pushes the edited configuration and credentials before requesting + the catalog, classifies authentication/unreachable/model failures with a + stable `error_kind`, and ignores a stale reply that a newer request + superseded. +- **The AI connection indicator is invalidated when it should be.** Editing the + provider, model, endpoint, server or a credential clears the green + "Validated" state and requires revalidation; irrelevant account or disk edits + preserve it. A regression assert in the VM harness edits the model and checks + the state flips. +- **Suggestion lists are keyboard-operable.** Arrow keys move a visible + highlight, Enter selects it, Escape dismisses the list, and the highlight is + exposed through `Accessible` roles. Enter in an open list is consumed so it + cannot also advance the wizard. +- **Busy work always completes.** The bridge now fails every outstanding + request when the backend exits, so no spinner can hang; AI connect/test and + catalog loads are single-flight; every failure path clears its busy state and + shows an actionable retry. +- **Keyboard focus is scrolled into view**, so a keyboard user never tabs to an + off-screen control, and the `PhoebusToggle` Return handler is fixed (it + previously called a signal handler as a function). + +### Changed +- **Human-readable language, keyboard and time-zone names** (e.g. "English + (United States) — en_US.UTF-8", "German — de") are returned by the backend; + the stable identifier is still what is validated and written. +- **The keyboard step tells the truth about the live session.** The live + session keeps its own layout; the selected layout is applied to the installed + system, and the typing test is labelled as testing the live keyboard. A live + Wayland layout switch is not implemented. +- **Internet readiness distinguishes a local link from reachable installation + services** and re-checks on demand without disturbing the form. +- **AI setup explains why a model is required and what is shared** (hardware and + storage facts; never passwords, passphrases, keys, names or files), shows the + proposed changes, and requires an explicit Accept or Discard before the step + can advance. +- **Disk selection prominently shows model, capacity and device identity**, and + states exactly which disk will be erased; protected disks explain why they + cannot be selected. The ERASE confirmation and approval binding are unchanged. +- **The account step explains login password versus encryption passphrase**, and + password reveal controls are keyboard-focusable. Technical settings moved + behind Advanced. +- **Progress shows real stages, elapsed time and activity**, with a redacted + Details log; the failure screen explains whether disk changes occurred and + what is safe to do next; completion explains restart, media removal, unlock + and first login. +- **The graphical harness gained a `gui-install` mode** that presses the real + controls through the whole journey (AI connect, disk, account, ERASE, + install) on a disposable disk, plus regression checks for readiness refresh, + disk survival and AI invalidation. `PHOEBUS_GUI_CONFIG`/`/etc/phoebus/install.conf` + let a live medium preseed wizard defaults without weakening any check. + +### Verified +- `cargo fmt --all -- --check` and `cargo clippy --workspace --all-targets` + clean (pre-existing `result_large_err` advisories unchanged); the Rust + workspace tests are green and `make test` (Rust + 16 harness tests) passes. +- Disposable graphical VM: `gui` 28/28 PASS (welcome, launcher, duplicate + prevention, keyboard suggestion selection, network, AI gate blocked and + reported, no bridge errors) and `opencode` 18/18 PASS (real model response, + validated proposal, model edit invalidates the connection). +- `gui-install` passed every journey assertion on a fresh 30 GiB qcow2, + including `gui-install-erase-confirmed`; the backend then reported real + progress (disk prepare, stage3 download, fstab, Portage sync, base packages, + kernel) with elapsed time and categories, and no fabricated percentage. The + complete install and detached boot result is recorded in + `docs/VM-BOOT-VERIFICATION.md`. + ## 2026-09-22 — `sys` administration hardening Correctness work on the deterministic `sys` broker and the assistant path that diff --git a/docs/HANDOFF.md b/docs/HANDOFF.md index 9a3c6cf..9be51e3 100644 --- a/docs/HANDOFF.md +++ b/docs/HANDOFF.md @@ -3,78 +3,73 @@ 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:** this session (2026-09-22), `sys` administration hardening. -- **Current focus:** Hardened `sys` into a reliable administration tool. - (1) All package/service/Flatpak execution now honours `--root` through one - `target_spec`/chroot path (offline `systemctl --root` for enable/disable), - and runtime-only service operations are rejected before any command when an - alternate root is requested. (2) Every action is validated at the execution - boundary (`parse_natural` now validates its own output); option-like operands - are rejected and operands are passed after `--`. (3) `sys ask` stops at the - first failure, records completed/failed/unattempted actions, and exits - nonzero. (4) Ordinary mutating commands are recorded, the generic protective - snapshot id is preserved, and recording failures are visible. (5) A genuinely - empty package plan is distinguished from unparseable emerge output, which is - refused. (6) Added typed `start/stop/restart_service` and ordinary commands - for Flatpak, Nix preparation and snapshots. +- **Last updated:** this session (2026-09-22), graphical installer journey + polish and reliability. +- **Current focus:** Reworked the graphical installer into a fixed, + first-time-user journey — Welcome, Language and keyboard, Internet and + readiness, AI connection, Destination disk, Account and encryption, Review + and confirmation, Installation, Completion — while keeping configuration, + validation, plans, approval and execution authoritative in Rust. Fixed the + interaction defects called out in the audit: the readiness refresh no longer + resets the wizard; model catalogs are fetched after syncing the edited + settings/credentials and stale replies are ignored; editing a connection + field invalidates the validated state; suggestion lists have full keyboard + navigation; the keyboard step is labelled truthfully (the live session keeps + its layout); readiness separates a local link from reachable install services; + and every busy state now clears on failure with an actionable retry (the + bridge fails outstanding requests when the backend exits). AI changes require + an explicit Accept or Discard; the review screen is built from backend facts + with edit links; progress reports real stages, elapsed time and activity. - **Last verified (this session):** - - 368 Rust tests green (including 3 new CLI integration tests) + 16 harness - tests; `cargo fmt --all -- --check` and `cargo clippy --workspace - --all-targets` clean (exit 0). Static `phoebus-installer`/`sys` build. - - Unit/integration evidence for all six fixes: preview and execution both - chroot to the same alternate root; runtime service ops reject an alternate - root without invoking anything; invalid actions are refused by the manual, - JSON and AI parsers and at the executor; `execute_plan` marks later actions - unattempted after a failure; unparseable emerge output is refused while a - real `0 packages` plan is accepted; a material plan change aborts before - the mutation. -- **Not yet verified this session:** the destructive **rollback VM - acceptance** (`sys undo`). See the blocker below — rollback stays explicitly - unverified. The OpenCode live tests are environment-gated and were skipped - (no `PHOEBUS_OPENCODE_LIVE_*`), and the full graphical install past the AI - gate and a separate physical computer remain unverified from the previous - session. + - `cargo fmt --all -- --check` and `cargo clippy --workspace --all-targets` + clean (only the pre-existing `result_large_err` advisory); the Rust + workspace tests pass and `make test` (Rust + 16 harness tests) is green. + - Disposable graphical VM, rebuilt ISO + (`sha256 125d002b…`, 1.6 GiB): `gui` **28/28** PASS and `opencode` **18/18** + PASS, including the keyboard-suggestion regression, the blocked AI gate, + a real model response and validated proposal, and the new + "editing the model invalidates the connection" regression. + - `gui-install` (new mode) passed every journey assertion on a fresh 30 GiB + qcow2 — AI connect/accept, disk, account, ERASE, confirmation toggle — + and the backend then reported real stages with elapsed time and no + fabricated percentage. The completed install + detached boot evidence is + recorded in `docs/VM-BOOT-VERIFICATION.md`. +- **Not yet verified this session:** the Apple/installed **Mango desktop** + rollback and NVIDIA checks are unchanged; rollback (`sys undo`) and the AI + sandbox remain unit-tested but not VM-verified, and the physical-seat desktop + and a separate physical computer remain open (see blockers). - **Public repo:** (remote `origin`, SSH port 2222). ## Next actions (in order) -1. **Complete the graphical install with a real model**: download a small local - OpenAI-compatible model (or supply a 0600 provider key), then run - `gui-driver.py gui` through disk/account/review/ERASE/install/rebooot twice - on fresh qcow2 disks and record the passing journeys. The current automated - journey passes to the AI gate 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 (BLOCKED this session)**: 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). Needed: - (a) free the >=20 GiB `make doctor` wants for the harness (the root fs has - ~12 GiB free); (b) an automated driver for the break-update/undo/recovery - sequence — `appliance-driver.py` only implements `install`/`boot`. Until - both exist, `sys undo` stays unverified. -4. **Narrow the live broker privilege**: replace the live-only - `NOPASSWD: ALL` rule for the GUI bridge with the smallest practical - command-scoped rule once a safe sudoers form is verified (ADR 0011 context). -5. **Physical-seat desktop**: run `phoebus-session` on a real VT/seat and check +1. **Installed Mango desktop**: install the default profile (Mango + DMS) 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. +2. **Rollback VM acceptance (BLOCKED)**: 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). Needed: (a) free the + >=20 GiB `make doctor` wants for the harness; (b) an automated driver for the + break-update/undo/recovery sequence — the harness has no such mode. +3. **Narrow the live broker privilege**: replace the live-only `NOPASSWD: ALL` + rule for the GUI bridge with the smallest practical command-scoped rule once + a safe sudoers form is verified (ADR 0011 context). +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`). -6. **Release gates on a CI runner**: `phoebus-release gates --execute` and +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 key and no local model are available; the **full GUI - install past the AI step** and two fresh-disk graphical installs are NOT - verified (normal installation requires a connected model). 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. + is the dwl fallback session. The `gui-install` journey intentionally preseeded + a no-desktop, safe-kernel configuration to bound the harness run, so it proves + the wizard and the install pipeline, not the desktop build. - **Rollback (`sys undo`) is implemented and unit-tested but NOT VM-verified (BLOCKED).** Exact blockers: `make doctor` reports ~13 GiB free versus the - >=20 GiB the harness wants (root fs ~12 GiB free), and the harness has no - automated break-update/undo/recovery-boot mode. The AI sandbox is likewise + >=20 GiB the harness wants, and the harness has no automated + break-update/undo/recovery-boot mode. The AI sandbox is likewise implemented/unit-tested but not VM-verified. NVIDIA is not verified. - A **separate physical computer** for the OpenCode transport test is not available (BLOCKED); a forwarded-hop + unauthenticated-LAN-refusal host-local @@ -94,8 +89,10 @@ commit it. It should be short and current; use `git log` for detail. 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/*`. + `gui`/`opencode`/`gui-install`/`install`/`boot`), `appliance-driver.py`, + `serial-driver.py`. `DISK` must be a disposable qcow2; never point it at + `/dev/*`. A `gui-install` run leaves its installed disk for a following + `boot` run. - 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`). diff --git a/docs/STATUS.md b/docs/STATUS.md index 0213c62..964f98b 100644 --- a/docs/STATUS.md +++ b/docs/STATUS.md @@ -64,8 +64,8 @@ still not VM-verified. | 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 | +| Typed GUI bridge (`--gui-bridge`) | yes | yes (dry-run) | live VM + full journey | n/a | +| Graphical welcome + install wizard (Quickshell) | yes | yes | live graphical VM + full GUI journey | 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 | @@ -106,7 +106,8 @@ still not VM-verified. | OpenCode server capability probe | yes | yes | real host probe + auth + policy | n/a | | OpenCode proposal adapter (real inference) | yes | yes | real model (`deepseek-v4-flash`) | n/a | | OpenCode in GUI / CLI / `sys ask` | yes | yes | GUI AI step + `sys ask` live | n/a | -| OpenCode full graphical install | yes | yes | AI gate passed; install not run | n/a | +| OpenCode full graphical install | yes | yes | full GUI journey through ERASE + backend stages | n/a | +| GUI readiness refresh / AI revalidation / keyboard nav | yes | yes (Rust) | VM harness regressions | n/a | | Mandatory AI requires a validated interaction | yes | yes | bridge + CLI | n/a | | GURU packaging (scoped keywords) | yes | yes | no (build/install unverified) | no | | Release gates + atomic publish | yes | yes | no | n/a | diff --git a/installer-rs/crates/phoebus-installer/src/gui_bridge.rs b/installer-rs/crates/phoebus-installer/src/gui_bridge.rs index c15f424..1742783 100644 --- a/installer-rs/crates/phoebus-installer/src/gui_bridge.rs +++ b/installer-rs/crates/phoebus-installer/src/gui_bridge.rs @@ -258,6 +258,7 @@ impl Bridge { let op = request.op.clone(); let result = match request.op.as_str() { "handshake" => self.handshake(), + "readiness" => self.readiness(), "options" => self.options(), "ai_catalog" => self.ai_catalog(), "disks" => self.disks(), @@ -283,10 +284,22 @@ impl Bridge { out, &json!({ "id": id, "ok": true, "op": op, "data": data }), ), - Err(error) => write_json( - out, - &json!({ "id": id, "ok": false, "op": op, "error": error }), - ), + Err(error) => { + // AI connection failures carry a stable, machine-readable kind + // so the frontend can distinguish an authentication failure + // from an unreachable server, a missing model or bad transport. + // The human message stays authoritative and redacted. + let mut payload = json!({ "id": id, "ok": false, "op": op, "error": error }); + if matches!( + op.as_str(), + "ai_catalog" | "ai_check" | "ai_test" | "readiness" + ) { + payload["error_kind"] = json!(connection_error_kind( + payload["error"].as_str().unwrap_or("") + )); + } + write_json(out, &payload) + } } } @@ -309,19 +322,44 @@ impl Bridge { "cpu_cores": self.installer.hardware.cpu.cores, "cpu_model": self.installer.hardware.cpu.model, "desktop": self.installer.config.desktop.profile.as_str(), + "keymap_live": live_keymap(), }, "facts": facts, })) } + /// A deeper, on-demand readiness probe. Unlike [`Self::handshake`] this may + /// make one bounded network request, so the frontend calls it when the + /// network step is shown or the user asks to re-check. It never changes + /// configuration or state, so refreshing readiness cannot reset the wizard. + fn readiness(&self) -> Result { + let link = network_ready(); + let services = service_reachability(&self.installer); + Ok(json!({ + "network": link, + "network_services": services.reachable, + "network_detail": services.detail, + "network_target": services.target, + "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(), + "keymap_live": live_keymap(), + })) + } + /// Selectable options for the language/region step. Reading these from the /// live system means the user picks from the real timezones, locales and /// keymaps instead of typing them from memory. fn options(&self) -> Result { Ok(json!({ - "timezones": system_timezones(), - "locales": system_locales(), - "keymaps": system_keymaps(), + "timezones": labeled_options(system_timezones(), humanize_timezone), + "locales": labeled_options(system_locales(), humanize_locale), + "keymaps": labeled_options(system_keymaps(), humanize_keymap), + // The live session's own layout, so the frontend can be truthful + // about whether a selection affects the running graphical session. + "keymap_live": live_keymap(), })) } @@ -949,6 +987,337 @@ fn network_ready() -> bool { }) } +/// The result of a bounded reachability check against the configured +/// installation source. A default route proves a local link; only a completed +/// request proves the installation services are actually reachable. +struct ServiceReachability { + reachable: bool, + detail: String, + target: String, +} + +fn service_reachability(installer: &Installer) -> ServiceReachability { + use phoebus_executor::opencode_client::{CurlHttpClient, HttpClient, HttpRequest}; + + let config = &installer.config; + let target = if !config.stage3.url.trim().is_empty() { + config.stage3.url.trim().to_string() + } else { + config.stage3.mirror.trim().to_string() + }; + if target.is_empty() { + return ServiceReachability { + reachable: false, + detail: "No installation source is configured.".into(), + target, + }; + } + let mut request = HttpRequest::get(target.clone()); + // Keep the check snappy: the user is waiting on it. + request.timeout = std::time::Duration::from_secs(8); + request.connect_timeout = std::time::Duration::from_secs(5); + request.max_body = 64 * 1024; + let http = CurlHttpClient::new(&installer.exec); + match http.request(&request) { + Ok(_) => ServiceReachability { + reachable: true, + detail: "Installation services are reachable.".into(), + target, + }, + Err(e) => ServiceReachability { + reachable: false, + detail: installer.exec.redactor().redact(&e.to_string()), + target, + }, + } +} + +/// The live medium's console keymap, read without privileges. Used to tell the +/// truth about whether choosing a layout changes the running session. +fn live_keymap() -> String { + if let Ok(text) = std::fs::read_to_string("/etc/vconsole.conf") { + for line in text.lines() { + if let Some(value) = line.trim().strip_prefix("KEYMAP=") { + let value = value.trim().trim_matches('"'); + if !value.is_empty() { + return value.to_string(); + } + } + } + } + std::env::var("XKB_DEFAULT_LAYOUT") + .ok() + .filter(|v| !v.trim().is_empty()) + .unwrap_or_else(|| "us".into()) +} + +/// Classify a connection error into a stable kind. The frontend uses this to +/// show an actionable recovery instead of a raw transport string. +fn connection_error_kind(message: &str) -> &'static str { + let m = message.to_ascii_lowercase(); + if m.contains("authentication required") + || m.contains("requires authentication") + || m.contains("no api key") + || m.contains("requires an api key") + { + "authentication_required" + } else if m.contains("authentication rejected") + || m.contains("rejected the supplied") + || m.contains("http 401") + || m.contains("http 403") + { + "authentication_rejected" + } else if m.contains("insecure_transport") + || m.contains("plain http") + || m.contains("must use https") + { + "insecure_transport" + } else if m.contains("http 404") + || m.contains("model not found") + || m.contains("unknown model") + || m.contains("no such model") + { + "model_unavailable" + } else if m.contains("timed out") + || m.contains("timeout") + || m.contains("connection refused") + || m.contains("could not connect") + || m.contains("failed to connect") + || m.contains("transport") + || m.contains("unreachable") + { + "unreachable" + } else { + "error" + } +} + +/// Turn a plain value list into `{value, label}` pairs so the frontend can show +/// human-readable names while the backend keeps validating the real identifier. +fn labeled_options(values: Vec, label: fn(&str) -> String) -> Vec { + values + .into_iter() + .map(|value| { + let text = label(&value); + json!({ "value": value, "label": text }) + }) + .collect() +} + +fn humanize_timezone(zone: &str) -> String { + match zone { + "UTC" => "UTC — Coordinated Universal Time".to_string(), + _ => zone.replace('_', " ").replace('/', " / "), + } +} + +/// A friendly language (and region, when known) name for a POSIX locale, with +/// the technical identifier kept at the end for advanced users. +fn humanize_locale(locale: &str) -> String { + let base = locale.split('.').next().unwrap_or(locale); + let mut parts = base.split('_'); + let language = parts.next().unwrap_or(""); + let region = parts.next(); + match (language_name(language), region.and_then(region_name)) { + (Some(lang), Some(region)) => format!("{lang} ({region}) — {locale}"), + (Some(lang), None) => format!("{lang} — {locale}"), + _ => locale.to_string(), + } +} + +fn language_name(code: &str) -> Option<&'static str> { + Some(match code { + "en" => "English", + "de" => "German", + "fr" => "French", + "es" => "Spanish", + "it" => "Italian", + "pt" => "Portuguese", + "nl" => "Dutch", + "pl" => "Polish", + "ru" => "Russian", + "uk" => "Ukrainian", + "cs" => "Czech", + "sk" => "Slovak", + "sv" => "Swedish", + "nb" | "no" => "Norwegian", + "da" => "Danish", + "fi" => "Finnish", + "el" => "Greek", + "tr" => "Turkish", + "hu" => "Hungarian", + "ro" => "Romanian", + "bg" => "Bulgarian", + "hr" => "Croatian", + "sr" => "Serbian", + "sl" => "Slovenian", + "et" => "Estonian", + "lv" => "Latvian", + "lt" => "Lithuanian", + "ja" => "Japanese", + "ko" => "Korean", + "zh" => "Chinese", + "hi" => "Hindi", + "bn" => "Bengali", + "ar" => "Arabic", + "he" => "Hebrew", + "fa" => "Persian", + "th" => "Thai", + "vi" => "Vietnamese", + "id" => "Indonesian", + "ms" => "Malay", + "sw" => "Swahili", + "ca" => "Catalan", + "gl" => "Galician", + "eu" => "Basque", + "is" => "Icelandic", + "ga" => "Irish", + "cy" => "Welsh", + "sq" => "Albanian", + "mk" => "Macedonian", + "be" => "Belarusian", + "az" => "Azerbaijani", + "kk" => "Kazakh", + "uz" => "Uzbek", + "ka" => "Georgian", + "hy" => "Armenian", + "af" => "Afrikaans", + _ => return None, + }) +} + +fn region_name(code: &str) -> Option<&'static str> { + Some(match code.to_ascii_uppercase().as_str() { + "US" => "United States", + "GB" => "United Kingdom", + "DE" => "Germany", + "FR" => "France", + "ES" => "Spain", + "IT" => "Italy", + "PT" => "Portugal", + "BR" => "Brazil", + "NL" => "Netherlands", + "BE" => "Belgium", + "AT" => "Austria", + "CH" => "Switzerland", + "PL" => "Poland", + "RU" => "Russia", + "UA" => "Ukraine", + "CZ" => "Czechia", + "SK" => "Slovakia", + "SE" => "Sweden", + "NO" => "Norway", + "DK" => "Denmark", + "FI" => "Finland", + "GR" => "Greece", + "TR" => "Türkiye", + "HU" => "Hungary", + "RO" => "Romania", + "BG" => "Bulgaria", + "HR" => "Croatia", + "RS" => "Serbia", + "SI" => "Slovenia", + "EE" => "Estonia", + "LV" => "Latvia", + "LT" => "Lithuania", + "JP" => "Japan", + "KR" => "South Korea", + "CN" => "China", + "TW" => "Taiwan", + "IN" => "India", + "SG" => "Singapore", + "AU" => "Australia", + "NZ" => "New Zealand", + "CA" => "Canada", + "MX" => "Mexico", + "AR" => "Argentina", + "ZA" => "South Africa", + "IE" => "Ireland", + "IL" => "Israel", + "AE" => "United Arab Emirates", + "SA" => "Saudi Arabia", + "TH" => "Thailand", + "VN" => "Vietnam", + "ID" => "Indonesia", + "MY" => "Malaysia", + "PH" => "Philippines", + _ => return None, + }) +} + +/// A friendly keyboard name for a console keymap identifier, with the technical +/// name kept so an advanced user can still see exactly what will be set. +fn humanize_keymap(name: &str) -> String { + let base = name.split('-').next().unwrap_or(name); + let language = match base { + "us" => "English (US)", + "gb" | "uk" => "English (UK)", + "de" => "German", + "fr" => "French", + "es" => "Spanish", + "it" => "Italian", + "pt" => "Portuguese", + "br" | "br-abnt2" => "Portuguese (Brazil)", + "latam" => "Spanish (Latin America)", + "nl" => "Dutch", + "be" => "Belgian", + "dk" => "Danish", + "no" => "Norwegian", + "se" => "Swedish", + "fi" => "Finnish", + "is" => "Icelandic", + "pl" => "Polish", + "cz" => "Czech", + "sk" => "Slovak", + "hu" => "Hungarian", + "ro" => "Romanian", + "bg" => "Bulgarian", + "gr" => "Greek", + "ru" => "Russian", + "ua" => "Ukrainian", + "tr" => "Turkish", + "il" => "Hebrew", + "ara" => "Arabic", + "in" => "Indian", + "jp106" => "Japanese", + "kr" => "Korean", + "cn" => "Chinese", + "tw" => "Chinese (Taiwan)", + "ca" => "Canadian", + "cf" => "Canadian (French)", + "ch" => "Swiss", + "at" => "German (Austria)", + "ie" => "Irish", + "si" => "Slovenian", + "hr" => "Croatian", + "ee" => "Estonian", + "lt" => "Lithuanian", + "lv" => "Latvian", + "mk" => "Macedonian", + "rs" => "Serbian", + "by" => "Belarusian", + "kz" => "Kazakh", + "us-dvorak" | "dvorak" => "Dvorak", + "colemak" => "Colemak", + "mac-us" => "Mac (US)", + "sg" => "Swiss German", + "th" => "Thai", + "vn" => "Vietnamese", + "fa" => "Persian", + "az" => "Azerbaijani", + "ge" => "Georgian", + "am" => "Armenian", + _ => "", + }; + if language.is_empty() { + name.to_string() + } else if language == name { + language.to_string() + } else { + format!("{language} — {name}") + } +} + fn iso_version() -> String { if let Ok(text) = std::fs::read_to_string("/etc/phoebus/version") { let t = text.trim(); @@ -1378,7 +1747,33 @@ fn review_proposal( /// The stdio entry point used by `--gui-bridge`. pub fn run_stdio() -> io::Result<()> { - let mut config = InstallConfig::default(); + // The live medium may preseed the wizard's starting configuration. The + // deterministic CLI already honours `/etc/phoebus/install.conf`; the + // graphical wizard uses the same file so the two paths agree. A test or + // automation caller can point at another file with `PHOEBUS_GUI_CONFIG`. + // Only the defaults change: validation, the plan, the AI gate and the + // ERASE authorization are all unchanged. + let explicit = std::env::var("PHOEBUS_GUI_CONFIG") + .ok() + .filter(|p| !p.trim().is_empty()); + let mut config = if let Some(path) = explicit { + InstallConfig::load_from_path(std::path::Path::new(path.trim())).map_err(|e| { + io::Error::new( + io::ErrorKind::InvalidInput, + format!("cannot load PHOEBUS_GUI_CONFIG: {e}"), + ) + })? + } else { + let default = std::path::Path::new("/etc/phoebus/install.conf"); + if default.is_file() { + InstallConfig::load_from_path(default).unwrap_or_else(|e| { + eprintln!("ignoring /etc/phoebus/install.conf: {e}"); + InstallConfig::default() + }) + } else { + 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. @@ -2098,4 +2493,92 @@ mod tests { resp["error"] ); } + + #[test] + fn connection_error_kind_classifies_common_failures() { + assert_eq!( + connection_error_kind("server requires authentication (HTTP 401)"), + "authentication_required" + ); + assert_eq!( + connection_error_kind("server rejected the supplied authentication (HTTP 403)"), + "authentication_rejected" + ); + assert_eq!( + connection_error_kind("model list returned HTTP 401"), + "authentication_rejected" + ); + assert_eq!( + connection_error_kind("plain http to a non-loopback address is refused"), + "insecure_transport" + ); + assert_eq!( + connection_error_kind("could not connect to the model server"), + "unreachable" + ); + assert_eq!( + connection_error_kind("transport response had no status"), + "unreachable" + ); + assert_eq!(connection_error_kind("something unexpected"), "error"); + } + + #[test] + fn humanized_labels_keep_the_identifier_and_add_a_name() { + assert!(humanize_locale("en_US.UTF-8").contains("English")); + assert!(humanize_locale("de_DE.UTF-8").contains("German")); + assert!(humanize_locale("en_US.UTF-8").contains("en_US.UTF-8")); + assert_eq!(humanize_locale("xx_YY.UTF-8"), "xx_YY.UTF-8"); + assert!(humanize_keymap("de").contains("German")); + assert!(humanize_keymap("de-nodeadkeys").contains("German")); + assert!(humanize_keymap("us").contains("English (US)")); + assert_eq!(humanize_keymap("zzz"), "zzz"); + assert!(humanize_timezone("Europe/Berlin").contains("Europe")); + } + + #[test] + fn options_carry_labels_and_the_live_keymap() { + let mut bridge = test_bridge(); + let lines = call(&mut bridge, r#"{"id":70,"op":"options"}"#); + let data = &response(&lines)["data"]; + for key in ["timezones", "locales", "keymaps"] { + let entries = data[key].as_array().unwrap(); + assert!(!entries.is_empty(), "{key} was empty"); + assert!( + entries + .iter() + .all(|o| o.get("value").is_some() && o.get("label").is_some()), + "{key} entries need a value and a label" + ); + } + assert!(data["keymap_live"].is_string()); + } + + #[test] + fn readiness_reports_link_and_service_reachability_separately() { + let mut bridge = test_bridge(); + let lines = call(&mut bridge, r#"{"id":71,"op":"readiness"}"#); + let resp = response(&lines); + assert_eq!(resp["ok"], json!(true), "response: {resp}"); + let data = &resp["data"]; + assert!(data["network"].is_boolean()); + assert!( + data["network_services"].is_boolean(), + "service reachability must be its own fact, not inferred from the link" + ); + assert!(data["network_detail"].is_string()); + assert!(data["keymap_live"].is_string()); + } + + #[test] + fn ai_catalog_errors_are_machine_readable() { + let mut bridge = test_bridge(); + let lines = call(&mut bridge, r#"{"id":72,"op":"ai_catalog"}"#); + let resp = response(&lines); + assert_eq!(resp["ok"], json!(false)); + assert!( + resp["error_kind"].is_string(), + "an AI connection error must carry a kind: {resp}" + ); + } } diff --git a/installer/live/desktop/common/Bridge.qml b/installer/live/desktop/common/Bridge.qml index b3e54b8..53dce50 100644 --- a/installer/live/desktop/common/Bridge.qml +++ b/installer/live/desktop/common/Bridge.qml @@ -16,6 +16,7 @@ Singleton { property string lastError: "" property var handshake: null property var config: null + property bool restarting: false property var pending: ({}) property int nextId: 1 @@ -23,6 +24,10 @@ Singleton { signal event(string name, var data) signal availabilityChanged signal handshakeReady + // Emitted when the backend exits while the frontend is still using it. The + // frontend must reset any state that depended on the backend (notably AI + // validation) and offer a recovery. + signal backendLost(string message) readonly property var bridgeCommand: { const override = Quickshell.env("PHOEBUS_BRIDGE_CMD"); @@ -42,6 +47,16 @@ Singleton { onTriggered: root.refreshHandshake(null) } + Timer { + id: restartTimer + interval: 500 + repeat: false + onTriggered: { + root.start(); + root.restarting = false; + } + } + function start() { if (!proc.running) proc.running = true; @@ -51,6 +66,33 @@ Singleton { proc.running = false; } + // Restart the backend after a crash. The bridge keeps no privileged state, + // so this is safe; the frontend re-pushes its configuration on the next + // action and must revalidate the AI connection. + function restart() { + if (root.restarting) + return; + root.restarting = true; + root.handshake = null; + root.stop(); + restartTimer.start(); + } + + // Complete every outstanding request when the process dies, so no caller is + // left waiting and no busy indicator can stay stuck forever. + function failPending(message) { + const ids = Object.keys(root.pending); + for (let i = 0; i < ids.length; i++) { + const cb = root.pending[ids[i]]; + delete root.pending[ids[i]]; + try { + cb({ ok: false, error: message, error_kind: "backend_gone" }); + } catch (e) { + console.log("bridge: pending callback failed: " + e); + } + } + } + function call(op, payload, onDone) { const id = root.nextId++; if (onDone) @@ -63,7 +105,7 @@ Singleton { delete root.pending[id]; root.lastError = "backend not running"; if (onDone) - onDone({ ok: false, error: "the installer backend is not running" }); + onDone({ ok: false, error: "the installer backend is not running", error_kind: "backend_gone" }); return; } proc.write(line); @@ -105,6 +147,9 @@ Singleton { function listDisks(cb) { call("disks", {}, cb); } + function readiness(cb) { + call("readiness", {}, cb); + } function options(cb) { call("options", {}, cb); } @@ -164,10 +209,14 @@ Singleton { root.availabilityChanged(); } onExited: exitCode => { + const wasRunning = root.ready; root.ready = false; root.crashed = true; root.crashMessage = "The installer backend stopped (exit " + exitCode + ")."; + root.failPending("the installer backend stopped before answering"); root.availabilityChanged(); + if (wasRunning && !root.restarting) + root.backendLost(root.crashMessage); } stdout: SplitParser { onRead: line => root.handleLine(line) diff --git a/installer/live/desktop/common/PhoebusButton.qml b/installer/live/desktop/common/PhoebusButton.qml index 86a6b24..31150eb 100644 --- a/installer/live/desktop/common/PhoebusButton.qml +++ b/installer/live/desktop/common/PhoebusButton.qml @@ -21,7 +21,7 @@ Rectangle { return hovered ? Theme.surfaceRaised : Theme.surface; } - implicitHeight: compact ? 34 : 46 + implicitHeight: compact ? Theme.controlHeightCompact : Theme.controlHeightLarge implicitWidth: Math.max(compact ? 80 : 120, labelText.implicitWidth + (compact ? 28 : 48)) radius: Theme.radiusSmall color: actionEnabled ? baseBg : Theme.surface diff --git a/installer/live/desktop/common/PhoebusChoice.qml b/installer/live/desktop/common/PhoebusChoice.qml index a34faee..16dd2bd 100644 --- a/installer/live/desktop/common/PhoebusChoice.qml +++ b/installer/live/desktop/common/PhoebusChoice.qml @@ -10,10 +10,16 @@ Flow { property bool compact: true signal selected(string value) + function focusFirst() { + if (repeater.count > 0) + repeater.itemAt(0).forceActiveFocus(); + } + spacing: 8 width: parent ? parent.width : implicitWidth Repeater { + id: repeater model: choice.options delegate: PhoebusButton { diff --git a/installer/live/desktop/common/PhoebusCombo.qml b/installer/live/desktop/common/PhoebusCombo.qml index ae59c21..337693e 100644 --- a/installer/live/desktop/common/PhoebusCombo.qml +++ b/installer/live/desktop/common/PhoebusCombo.qml @@ -1,10 +1,12 @@ import QtQuick // A labelled input with an inline, filtered suggestion list. The user can type -// to narrow the list or click an entry to choose it, and a custom value is -// still allowed. Used for timezone, locale, keymap, provider and model so the -// user picks from what the system actually offers instead of typing from -// memory. +// to narrow the list, click an entry, or use the arrow keys: Up/Down move a +// visible highlight, Enter selects it, Escape closes the list. A custom value +// is still allowed. Used for timezone, locale, keymap, provider and model so +// the user picks from what the system actually offers instead of typing from +// memory. `options` may be strings or `{value,label}` pairs; the value is the +// identifier the backend validates, the label is what the user reads. Column { id: combo @@ -13,10 +15,14 @@ Column { property string error: "" property var options: [] property int maxVisible: 8 - property string hint: "Type to filter, click to choose" + property string hint: "Type to filter · ↑ ↓ to choose · Enter to select" property alias text: field.text property alias inputItem: field.inputItem property var suggestions: [] + property int highlightIndex: -1 + property bool dismissed: false + readonly property bool open: field.inputItem.activeFocus && !combo.dismissed + && combo.suggestions.length > 0 signal edited(string value) signal selected(string value) @@ -24,16 +30,53 @@ Column { width: parent ? parent.width : implicitWidth spacing: 4 + function optionValue(option) { + return (option !== null && typeof option === "object") ? ("" + option.value) : ("" + option); + } + function optionLabel(option) { + return (option !== null && typeof option === "object" && option.label !== undefined) + ? ("" + option.label) : ("" + option); + } + function refresh() { const query = (field.text || "").toLowerCase(); const all = combo.options || []; const out = []; for (let i = 0; i < all.length && out.length < combo.maxVisible; i++) { - const option = "" + all[i]; - if (query.length === 0 || option.toLowerCase().indexOf(query) !== -1) - out.push(option); + const value = combo.optionValue(all[i]); + const label = combo.optionLabel(all[i]); + if (query.length === 0 + || value.toLowerCase().indexOf(query) !== -1 + || label.toLowerCase().indexOf(query) !== -1) + out.push({ value: value, label: label }); } combo.suggestions = out; + if (combo.highlightIndex >= out.length) + combo.highlightIndex = out.length - 1; + } + + function choose(index) { + if (index < 0 || index >= combo.suggestions.length) + return; + const chosen = combo.suggestions[index]; + field.inputItem.text = chosen.value; + combo.suggestions = []; + combo.highlightIndex = -1; + combo.dismissed = false; + combo.selected(chosen.value); + } + + function commit() { + if (combo.open && combo.highlightIndex >= 0) + combo.choose(combo.highlightIndex); + else { + combo.suggestions = []; + combo.dismissed = true; + } + } + + function forceFocus() { + field.inputItem.forceActiveFocus(); } onOptionsChanged: combo.refresh() @@ -45,40 +88,78 @@ Column { label: combo.label placeholder: combo.placeholder error: combo.error - onEdited: value => { combo.edited(value); combo.refresh(); } + escapeConsumed: combo.open + returnConsumed: combo.open + onEdited: value => { + combo.dismissed = false; + combo.refresh(); + combo.edited(value); + } + onKeyUp: { + if (combo.suggestions.length === 0) + return; + combo.dismissed = false; + combo.highlightIndex = combo.highlightIndex < 0 + ? combo.suggestions.length - 1 + : (combo.highlightIndex <= 0 + ? combo.suggestions.length - 1 : combo.highlightIndex - 1); + } + onKeyDown: { + if (combo.suggestions.length === 0) + return; + combo.dismissed = false; + combo.highlightIndex = combo.highlightIndex < 0 + ? 0 + : (combo.highlightIndex >= combo.suggestions.length - 1 + ? 0 : combo.highlightIndex + 1); + } + onKeyEscape: combo.dismissed = true + onAccepted: combo.commit() } - // Show the first suggestions as soon as the field takes focus. + // Show suggestions as soon as the field takes focus, and clear the + // highlight when it loses focus. Connections { target: field.inputItem function onActiveFocusChanged() { - if (field.inputItem.activeFocus) + if (field.inputItem.activeFocus) { + combo.dismissed = false; combo.refresh(); + } else { + combo.dismissed = false; + combo.highlightIndex = -1; + } } } Column { width: parent.width spacing: 0 - visible: field.inputItem.activeFocus && combo.suggestions.length > 0 + visible: combo.open Repeater { - model: field.inputItem.activeFocus ? combo.suggestions : [] + model: combo.open ? combo.suggestions : [] delegate: Rectangle { + id: row required property var modelData + required property int index width: parent.width height: 30 - color: hover.containsMouse ? Theme.surfaceRaised : Theme.surface + color: index === combo.highlightIndex ? Theme.amberDeep + : (hover.containsMouse ? Theme.surfaceRaised : Theme.surface) border.width: 1 - border.color: Theme.border + border.color: index === combo.highlightIndex ? Theme.amber : Theme.border + Accessible.role: Accessible.ListItem + Accessible.name: row.modelData.label + Accessible.selected: index === combo.highlightIndex Text { anchors.verticalCenter: parent.verticalCenter anchors.left: parent.left anchors.right: parent.right anchors.leftMargin: 12 anchors.rightMargin: 12 - text: modelData + text: row.modelData.label elide: Text.ElideRight - color: Theme.warmWhite + color: index === combo.highlightIndex ? Theme.charcoal : Theme.warmWhite font.family: Theme.family font.pixelSize: Theme.fontSmall } @@ -87,11 +168,7 @@ Column { anchors.fill: parent hoverEnabled: true cursorShape: Qt.PointingHandCursor - onClicked: { - field.inputItem.text = modelData; - combo.selected(modelData); - combo.suggestions = []; - } + onClicked: combo.choose(index) } } } diff --git a/installer/live/desktop/common/PhoebusField.qml b/installer/live/desktop/common/PhoebusField.qml index f25cfa6..16b70d7 100644 --- a/installer/live/desktop/common/PhoebusField.qml +++ b/installer/live/desktop/common/PhoebusField.qml @@ -1,6 +1,9 @@ import QtQuick // A labelled single-line input with an inline error and optional secret echo. +// +// It forwards the arrow/Escape keys as signals so a wrapping combo box can +// implement keyboard selection without the field knowing about suggestions. Column { id: field @@ -9,15 +12,29 @@ Column { property string error: "" property bool secret: false property bool showSecret: false + // When true, an Escape key is consumed here (used to close a suggestion + // list). Otherwise it bubbles so the window can react to it. + property bool escapeConsumed: false + // When true, Return/Enter is consumed here (used to select a highlighted + // suggestion). Otherwise it bubbles so the page can advance. + property bool returnConsumed: false property alias text: input.text property alias inputItem: input property int maxLength: 256 + signal edited(string value) signal accepted + signal keyUp + signal keyDown + signal keyEscape width: parent ? parent.width : implicitWidth spacing: 6 + function forceFocus() { + input.forceActiveFocus(); + } + Text { width: parent.width text: field.label @@ -30,7 +47,7 @@ Column { Rectangle { width: parent.width - height: 42 + height: Theme.controlHeight radius: Theme.radiusSmall color: Theme.charcoal border.width: input.activeFocus ? 2 : 1 @@ -42,7 +59,7 @@ Column { id: input anchors.fill: parent anchors.leftMargin: 12 - anchors.rightMargin: 44 + anchors.rightMargin: field.secret ? 52 : 12 verticalAlignment: TextInput.AlignVCenter color: Theme.warmWhite font.family: Theme.family @@ -55,8 +72,34 @@ Column { activeFocusOnTab: true maximumLength: field.maxLength clip: true + Accessible.role: Accessible.EditableText + Accessible.name: field.label.length > 0 ? field.label : field.placeholder + Accessible.description: field.error onTextEdited: field.edited(text) - onAccepted: field.accepted() + + Keys.onReturnPressed: event => { + const consumed = field.returnConsumed; + field.accepted(); + event.accepted = consumed; + } + Keys.onEnterPressed: event => { + const consumed = field.returnConsumed; + field.accepted(); + event.accepted = consumed; + } + Keys.onUpPressed: event => { + event.accepted = true; + field.keyUp(); + } + Keys.onDownPressed: event => { + event.accepted = true; + field.keyDown(); + } + Keys.onEscapePressed: event => { + const consumed = field.escapeConsumed; + field.keyEscape(); + event.accepted = consumed; + } Text { anchors.fill: parent @@ -69,20 +112,51 @@ Column { } } - Text { + // The show/hide control is a real focus stop, reachable with Tab and + // operable with Space/Enter, so revealing a password never requires a + // mouse. + Item { + id: reveal anchors.right: parent.right - anchors.rightMargin: 12 + anchors.rightMargin: 10 anchors.verticalCenter: parent.verticalCenter + width: 40 + height: 26 visible: field.secret - text: field.showSecret ? "hide" : "show" - color: Theme.amber - font.family: Theme.family - font.pixelSize: Theme.fontSmall + activeFocusOnTab: field.secret + Accessible.role: Accessible.Button + Accessible.name: field.showSecret ? "Hide " + field.label : "Show " + field.label + Accessible.onPressAction: reveal.toggle() + + function toggle() { + field.showSecret = !field.showSecret; + } + + Keys.onReturnPressed: reveal.toggle() + Keys.onEnterPressed: reveal.toggle() + Keys.onSpacePressed: reveal.toggle() + + Rectangle { + anchors.fill: parent + radius: Theme.radiusSmall + color: "transparent" + border.width: 2 + border.color: Theme.focusRing + visible: reveal.activeFocus + } + + Text { + anchors.centerIn: parent + 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 + onClicked: reveal.toggle() } } } diff --git a/installer/live/desktop/common/PhoebusToggle.qml b/installer/live/desktop/common/PhoebusToggle.qml index f1f0ee3..5bfc173 100644 --- a/installer/live/desktop/common/PhoebusToggle.qml +++ b/installer/live/desktop/common/PhoebusToggle.qml @@ -16,12 +16,19 @@ Item { Accessible.name: label Accessible.checked: checked - Keys.onSpacePressed: { + Keys.onPressed: event => { + if (event.key === Qt.Key_Return || event.key === Qt.Key_Enter + || event.key === Qt.Key_Space) { + toggle.checked = !toggle.checked; + toggle.toggled(toggle.checked); + event.accepted = true; + } + } + + function toggleValue() { toggle.checked = !toggle.checked; toggle.toggled(toggle.checked); } - Keys.onReturnPressed: Keys.onSpacePressed(event) - Keys.onEnterPressed: Keys.onSpacePressed(event) Column { anchors.left: parent.left diff --git a/installer/live/desktop/common/Theme.qml b/installer/live/desktop/common/Theme.qml index 6a4d7a7..d425361 100644 --- a/installer/live/desktop/common/Theme.qml +++ b/installer/live/desktop/common/Theme.qml @@ -1,5 +1,6 @@ pragma Singleton import QtQuick +import Quickshell // Phoebus brand tokens. Kept in sync with phoebus_core::brand::PALETTE by a // Rust test, so the QML frontend and the backend cannot drift. @@ -22,6 +23,14 @@ QtObject { readonly property color focusRing: amber readonly property color overlay: Qt.rgba(0.09, 0.09, 0.10, 0.72) + // Text scale. `PHOEBUS_UI_SCALE` lets a display or accessibility setup + // enlarge everything; the content areas scroll, so a larger scale still + // fits at 1024x768. + readonly property real scale: { + const value = parseFloat(Quickshell.env("PHOEBUS_UI_SCALE")); + return (isNaN(value) || value < 0.5 || value > 4) ? 1.0 : value; + } + // Layout. readonly property int radius: 12 readonly property int radiusSmall: 8 @@ -29,12 +38,18 @@ QtObject { readonly property int pad: 16 readonly property int padLarge: 28 + // Control sizing follows the text scale so labels never clip. + readonly property int controlHeight: Math.round(42 * scale) + readonly property int controlHeightLarge: Math.round(46 * scale) + readonly property int controlHeightCompact: Math.round(34 * scale) + readonly property int rowHeight: Math.round(30 * scale) + // 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 int fontDisplay: Math.round(30 * scale) + readonly property int fontTitle: Math.round(22 * scale) + readonly property int fontHeading: Math.round(17 * scale) + readonly property int fontBody: Math.round(14 * scale) + readonly property int fontSmall: Math.round(12 * scale) readonly property string family: "DejaVu Sans, Noto Sans, sans-serif" // Branding assets installed by the live build. diff --git a/installer/live/desktop/phoebus-install/shell.qml b/installer/live/desktop/phoebus-install/shell.qml index b80f116..3f36b52 100644 --- a/installer/live/desktop/phoebus-install/shell.qml +++ b/installer/live/desktop/phoebus-install/shell.qml @@ -7,10 +7,18 @@ import "Common" // 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. +// +// The journey is a fixed sequence a first-time user can follow: +// Welcome -> Language and keyboard -> Internet and readiness -> AI connection +// -> Destination disk -> Account and encryption -> Review and confirmation +// -> Installation -> Completion ShellRoot { id: shell property var cfg: null + // Set once the first handshake has created the configuration. Later + // handshakes (a readiness refresh or a backend restart) must not reset it. + property bool initialized: false property int step: 0 property string phase: "form" // form | progress | done | failed property var issues: ({}) @@ -18,13 +26,19 @@ ShellRoot { property var disks: [] property string selectedDisk: "" property var review: null + property var reviewSteps: [] property string previewText: "" property string planDigest: "" property var handshake: null + property var readiness: null + property bool checkingReadiness: false // Selectable system lists (timezones/locales/keymaps) and the AI catalog. property var options: ({ timezones: [], locales: [], keymaps: [] }) + property string liveKeymap: "us" property var aiCatalog: ({ providers: [], models: [] }) property string aiCatalogError: "" + property string aiCatalogStatus: "" + property bool aiCatalogLoading: false readonly property var aiProviderIds: (shell.aiCatalog.providers || []).map(p => p.id) // Secrets: held in memory only, sent over the bridge stdin, never in cfg. @@ -40,6 +54,8 @@ ShellRoot { property bool aiChecking: false property string aiError: "" property var aiApplied: [] + property bool aiReviewAccepted: false + property var preAiConfig: null // "Test connection" state: a real, validated model response was obtained. property bool aiTesting: false property bool aiTested: false @@ -57,24 +73,27 @@ ShellRoot { property var logLines: [] property bool showAdvanced: false property bool showSecrets: false + property bool installStarting: false + property double installStartedMs: 0 + property int elapsedSeconds: 0 + property string lastActivity: "" readonly property var stepTitles: [ - "Language and region", - "Network and prerequisites", - "AI model", + "Welcome", + "Language and keyboard", + "Internet and readiness", + "AI connection", "Destination disk", - "Your account and encryption", - "Review", - "Confirm and install", - "Installing" + "Account and encryption", + "Review and confirmation" ] readonly property var stepFields: [ + [], ["locale", "keymap", "timezone"], [], [], ["target_disk"], ["hostname", "username"], - [], [] ] @@ -82,6 +101,23 @@ ShellRoot { return JSON.parse(JSON.stringify(o)); } + // The accessible name of the focused control. Used by the harness to prove + // where keyboard focus is, instead of inferring it from a screenshot. + function focusedName() { + const win = page.Window.window; + const item = win ? win.activeFocusItem : null; + if (!item || item === page) + return "none"; + let name = ""; + try { name = item.Accessible.name || ""; } catch (e) { name = ""; } + if (!name) { + try { name = item.objectName || ""; } catch (e) { name = ""; } + } + if (!name) + name = "" + item; + return ("" + name).replace(/\s+/g, "_").slice(0, 48); + } + // A compact, secret-free state line for the harness. It lets a test assert // the actual current step and AI connection state instead of inferring them // from a screenshot or the mere survival of the process. @@ -92,6 +128,12 @@ ShellRoot { + " aiConnected=" + shell.aiConnected + " aiTested=" + shell.aiTested + " aiApplied=" + shell.aiApplied.length + + " aiReview=" + shell.aiReviewAccepted + + " disk=" + shell.selectedDisk + + " locale=" + (shell.cfg ? shell.cfg.system.locale : "") + + " keymap=" + (shell.cfg ? shell.cfg.system.keymap : "") + + " confirm=" + shell.finalConfirm + + " focus=" + shell.focusedName() + " aiError=" + shell.aiError.replace(/\n/g, " ").slice(0, 200) + " aiTest=" + shell.aiTestMessage.replace(/\n/g, " ").slice(0, 200)); } @@ -101,6 +143,7 @@ ShellRoot { onAiErrorChanged: logState("error") onAiTestedChanged: logState("test") onAiTestMessageChanged: logState("testmsg") + onFinalConfirmChanged: logState("confirm") // QML `var` properties do not emit change signals for nested assignments, // so bindings that read `cfg.*` would not update. Reassigning a clone @@ -108,6 +151,15 @@ ShellRoot { function touchConfig() { if (shell.cfg) shell.cfg = clone(shell.cfg); + shell.invalidateApproval(); + } + + // A material change to the configuration invalidates the destructive + // approval. The backend enforces this too; the frontend mirrors it so the + // user is never shown a stale confirmation. + function invalidateApproval() { + shell.previewText = ""; + shell.planDigest = ""; } // Re-read every input from the current configuration. Called when entering @@ -154,6 +206,52 @@ ShellRoot { shell.issues = next; } + // Move focus to the field a validation error belongs to, so the user is + // taken straight to the first problem. + function fieldForIssue(field) { + const map = { + locale: localeField, + keymap: keymapField, + timezone: tzField, + username: userField, + hostname: hostField, + password: pwField, + password_confirm: pw2Field, + passphrase: luksField, + passphrase_confirm: luks2Field, + erase: eraseField + }; + return map[field] !== undefined ? map[field] : null; + } + + function focusIssueField(field) { + if (field === "target_disk") { + diskFocusAnchor.forceActiveFocus(); + return; + } + const item = shell.fieldForIssue(field); + if (item && item.forceFocus) + item.forceFocus(); + else if (item && item.inputItem) + item.inputItem.forceActiveFocus(); + } + + function focusCurrentStep() { + const targets = [ + welcomeNext, localeField, networkRetry, null, + diskFocusAnchor, fullnameField, eraseField + ]; + if (shell.step === 3) { + providerChoice.focusFirst(); + return; + } + const item = targets[shell.step]; + if (item && item.forceFocus) + item.forceFocus(); + else if (item && item.forceActiveFocus) + item.forceActiveFocus(); + } + function startBridge() { Bridge.start(); } @@ -164,6 +262,15 @@ ShellRoot { if (!reply.ok) return; shell.handshake = reply.data; + if (reply.data.readiness) + shell.readiness = clone(reply.data.readiness); + if (reply.data.readiness && reply.data.readiness.keymap_live) + shell.liveKeymap = reply.data.readiness.keymap_live; + // A readiness refresh, availability change or restart must not reset + // the wizard. Only the first handshake creates the configuration. + if (shell.initialized) + return; + shell.initialized = true; shell.cfg = clone(reply.data.defaults); shell.cfg.storage.disk = ""; shell.step = 0; @@ -177,39 +284,153 @@ ShellRoot { Bridge.refreshHandshake(null); } - // Fetch the real timezones/locales/keymaps the live system offers. - function loadOptions() { - Bridge.options(reply => { - if (reply.ok) - shell.options = reply.data; + // Refresh only readiness. This is what the network step's "Re-check" uses: + // it never resets the step, the selected disk or any typed answer. + function refreshReadiness() { + if (!Bridge.ready) { + shell.status = "The installer backend is starting…"; + return; + } + if (shell.checkingReadiness) + return; + shell.checkingReadiness = true; + Bridge.readiness(reply => { + shell.checkingReadiness = false; + if (reply.ok) { + shell.readiness = reply.data; + if (reply.data.keymap_live) + shell.liveKeymap = reply.data.keymap_live; + if (shell.handshake) + shell.handshake = Object.assign({}, shell.handshake, { readiness: reply.data }); + if (!reply.data.network) + shell.status = "No network connection was detected."; + else if (!reply.data.network_services) + shell.status = "Connected, but the installation services could not be reached."; + else + shell.status = ""; + } else { + shell.status = reply.error; + } }); } - // Fetch the providers/models the configured AI connection offers. - function loadAiCatalog() { - Bridge.aiCatalog(reply => { + // Fetch the real timezones/locales/keymaps the live system offers. + function loadOptions() { + Bridge.options(reply => { if (reply.ok) { - shell.aiCatalog = reply.data; - shell.aiCatalogError = ""; - } else { - shell.aiCatalog = { providers: [], models: [] }; - shell.aiCatalogError = reply.error; + shell.options = reply.data; + if (reply.data.keymap_live) + shell.liveKeymap = reply.data.keymap_live; } }); } + // Fetch the providers/models for the connection currently shown in the + // form. The edited settings and credentials are pushed first, so the + // catalog is never requested for a stale configuration. Stale replies are + // ignored via a monotonically increasing request id. + property int aiCatalogSeq: 0 + function loadAiCatalog() { + if (!shell.cfg) { + shell.aiCatalogError = "The installer backend is not ready yet."; + shell.aiCatalogStatus = "error"; + return; + } + if (shell.aiCatalogLoading) + return; + shell.aiCatalogLoading = true; + shell.aiCatalogError = ""; + shell.aiCatalogStatus = "loading"; + const seq = ++shell.aiCatalogSeq; + Bridge.setSecrets(shell.collectAiSecrets(), secretsReply => { + if (!secretsReply.ok) { + shell.aiCatalogLoading = false; + shell.aiCatalogStatus = "error"; + shell.aiCatalogError = "Could not send the connection settings: " + (secretsReply.error || "unknown error"); + return; + } + Bridge.setConfig(clone(shell.cfg), cfgReply => { + if (!cfgReply.ok) { + shell.aiCatalogLoading = false; + shell.aiCatalogStatus = "error"; + shell.aiCatalogError = cfgReply.error; + return; + } + Bridge.aiCatalog(reply => { + if (seq !== shell.aiCatalogSeq) + return; // a newer request superseded this one + shell.aiCatalogLoading = false; + if (reply.ok) { + shell.aiCatalog = reply.data; + shell.aiCatalogStatus = (reply.data.models || []).length > 0 ? "ok" : "empty"; + shell.aiCatalogError = ""; + } else { + shell.aiCatalog = { providers: [], models: [] }; + shell.aiCatalogStatus = reply.error_kind || "error"; + shell.aiCatalogError = shell.friendlyAiError(reply.error_kind, reply.error); + } + }); + }); + }); + } + + function collectAiSecrets() { + const secrets = {}; + if (shell.apiKey.length > 0) + secrets.ai_api_key = shell.apiKey; + if (shell.opencodePassword.length > 0) + secrets.opencode_password = shell.opencodePassword; + return secrets; + } + + // Any change to the connection settings requires revalidation; unrelated + // account or disk edits must preserve a valid connection. + function aiConnectionEdited() { + if (shell.aiConnected || shell.aiTested || shell.aiTestMessage.length > 0) + shell.aiError = "Connection settings changed. Connect and validate again."; + shell.aiConnected = false; + shell.aiTested = false; + shell.aiTestMessage = ""; + shell.aiReviewAccepted = false; + shell.aiApplied = []; + } + + function friendlyAiError(kind, raw) { + switch (kind) { + case "authentication_required": + return "The server requires a password or API key. Enter it and connect again."; + case "authentication_rejected": + return "Authentication was rejected. Check your API key or server password, then connect again."; + case "insecure_transport": + return "The endpoint must use HTTPS unless it runs on this computer (loopback)."; + case "model_unavailable": + return "That model is not available on this connection. Choose another model and try again."; + case "unreachable": + return "Could not reach the server. Check the address, the network, and that the model is running, then retry."; + case "backend_gone": + return "The installer backend stopped. Restart it and try again."; + default: + return raw && raw.length > 0 ? raw : "The request failed. Check the settings and retry."; + } + } + function applyConfig(then) { if (!shell.cfg) { shell.status = "The installer backend is not ready yet."; + if (then) + then(false, shell.status); return; } Bridge.setConfig(clone(shell.cfg), reply => { if (!reply.ok) { shell.status = reply.error; + if (then) + then(false, reply.error); return; } + shell.invalidateApproval(); if (then) - then(); + then(true, ""); }); } @@ -217,7 +438,11 @@ ShellRoot { // current step. The backend is the single source of validation truth. function saveAndAdvance() { shell.status = "Checking…"; - applyConfig(() => { + shell.applyConfig((ok, error) => { + if (!ok) { + shell.status = error; + return; + } Bridge.validate(reply => { if (!reply.ok) { shell.status = reply.error; @@ -228,6 +453,7 @@ ShellRoot { if (relevant.length > 0) { applyIssues(relevant); shell.status = "Please fix the highlighted fields."; + shell.focusIssueField(relevant[0].field); return; } clearIssues(); @@ -244,20 +470,26 @@ ShellRoot { return; } const s = shell.step; - if (s === 0 || s === 3) { - saveAndAdvance(); - return; - } - if (s === 4) { - accountNext(); - return; - } - if (s === 1) { - shell.step += 1; + if (s === 0) { + shell.step = 1; shell.enterStep(); return; } + if (s === 1 || s === 4) { + saveAndAdvance(); + return; + } if (s === 2) { + if (shell.readiness && shell.readiness.network) { + shell.step = 3; + shell.enterStep(); + } else { + shell.status = "Connect to a network to continue."; + shell.focusCurrentStep(); + } + return; + } + if (s === 3) { if (!shell.aiConnected) { // Show the guidance beside the AI controls, not only in the // footer, so the fix is obvious. @@ -265,12 +497,20 @@ ShellRoot { shell.status = ""; return; } + if (!shell.aiReviewAccepted) { + shell.aiError = "Review the model's proposed changes: accept them or discard them before continuing."; + shell.status = ""; + return; + } saveAndAdvance(); return; } if (s === 5) { - shell.step = 6; - shell.enterStep(); + accountNext(); + return; + } + if (s === 6) { + authorizeAndInstall(); return; } shell.step += 1; @@ -285,37 +525,40 @@ ShellRoot { } } + function ensureAiDefaults() { + if (shell.isOpenCode) + return; + 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"; + } + } + function enterStep() { shell.status = ""; const s = shell.step; - if (s === 2) { - if (!shell.isOpenCode && (!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"; - } - } + if (s === 3) + shell.ensureAiDefaults(); shell.syncFields(); shell.touchConfig(); if (s === 2) - shell.loadAiCatalog(); + shell.refreshReadiness(); if (s === 3) + shell.loadAiCatalog(); + if (s === 4) 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; - } - }); - } + if (s === 6) + loadReviewAndPreview(); + focusStepTimer.start(); + } + + Timer { + id: focusStepTimer + interval: 80 + repeat: false + onTriggered: shell.focusCurrentStep() } function refreshDisks() { @@ -327,14 +570,23 @@ ShellRoot { }); } - function loadReview() { + function loadReviewAndPreview() { + shell.review = null; Bridge.plan(reply => { if (reply.ok) { shell.review = reply.data.review; - shell.planDigest = reply.data.plan_digest; + shell.reviewSteps = reply.data.steps || []; } else { shell.status = reply.error; } + Bridge.destructivePreview(preview => { + if (preview.ok) { + shell.previewText = preview.data.text; + shell.planDigest = preview.data.plan_digest; + } else { + shell.status = preview.error; + } + }); }); } @@ -345,6 +597,7 @@ ShellRoot { shell.aiTestMessage = ""; shell.aiError = ""; shell.aiApplied = []; + shell.aiReviewAccepted = false; if (value === "opencode") { // OpenCode is an agent server with its own protocol; it is not an // OpenAI-compatible endpoint, so it has its own backend and fields. @@ -373,27 +626,35 @@ ShellRoot { shell.loadAiCatalog(); } - // A lightweight real interaction used by "Test connection": it obtains and - // validates a model response without proposing installation changes. + // A real, minimal model interaction that obtains and validates a JSON model + // response without proposing installation changes. This is "Test connection". function testAi() { + if (shell.aiTesting || shell.aiChecking) + return; shell.aiTesting = true; shell.aiTested = false; shell.aiTestMessage = ""; shell.aiError = ""; - const secrets = {}; - if (shell.opencodePassword.length > 0) - secrets.opencode_password = shell.opencodePassword; - if (shell.apiKey.length > 0) - secrets.ai_api_key = shell.apiKey; - Bridge.setSecrets(secrets, () => { - applyConfig(() => { + Bridge.setSecrets(shell.collectAiSecrets(), secretsReply => { + if (!secretsReply.ok) { + shell.aiTesting = false; + shell.aiTestMessage = "Could not send the connection settings: " + (secretsReply.error || "unknown error"); + return; + } + shell.applyConfig((ok, error) => { + if (!ok) { + shell.aiTesting = false; + shell.aiTestMessage = "Could not save the connection settings: " + error; + return; + } Bridge.aiTest(reply => { shell.aiTesting = false; if (reply.ok) { shell.aiTested = true; - shell.aiTestMessage = "Model responded"; + shell.aiTestMessage = "The model answered a test question."; } else { - shell.aiTestMessage = reply.error; + shell.aiTested = false; + shell.aiTestMessage = shell.friendlyAiError(reply.error_kind, reply.error); } }); }); @@ -401,52 +662,94 @@ ShellRoot { } function connectAi() { + if (shell.aiChecking || shell.aiTesting) + return; + if (!shell.cfg) { + shell.aiError = "The installer backend is not ready yet."; + return; + } shell.aiChecking = true; shell.aiError = ""; + shell.aiTestMessage = ""; shell.aiApplied = []; + shell.aiReviewAccepted = false; shell.aiConnected = false; - const secrets = {}; - if (shell.apiKey.length > 0) - secrets.ai_api_key = shell.apiKey; - if (shell.opencodePassword.length > 0) - secrets.opencode_password = shell.opencodePassword; - Bridge.setSecrets(secrets, () => { - applyConfig(() => { + shell.preAiConfig = clone(shell.cfg); + Bridge.setSecrets(shell.collectAiSecrets(), secretsReply => { + if (!secretsReply.ok) { + shell.aiChecking = false; + shell.aiError = "Could not send the connection settings: " + (secretsReply.error || "unknown error"); + return; + } + shell.applyConfig((ok, error) => { + if (!ok) { + shell.aiChecking = false; + shell.aiError = "Could not save the connection settings: " + error; + return; + } Bridge.aiCheck(reply => { shell.aiChecking = false; if (reply.ok) { shell.aiConnected = true; shell.aiApplied = reply.data.applied || []; + shell.aiReviewAccepted = shell.aiApplied.length === 0; if (reply.data.config) shell.cfg = clone(reply.data.config); shell.status = ""; + shell.logState("applied"); } else { - shell.aiError = reply.error; + shell.aiError = shell.friendlyAiError(reply.error_kind, reply.error); } }); }); }); } + function acceptAiChanges() { + shell.aiReviewAccepted = true; + shell.aiError = ""; + shell.logState("review"); + } + + function discardAiChanges() { + if (shell.preAiConfig) { + shell.cfg = clone(shell.preAiConfig); + shell.applyConfig(() => {}); + } + shell.aiConnected = false; + shell.aiTested = false; + shell.aiApplied = []; + shell.aiReviewAccepted = false; + shell.aiError = "The proposed changes were discarded. Connect and validate again to continue."; + shell.logState("review"); + } + function validateAccount() { clearIssues(); let ok = true; + let first = ""; if (shell.userPw.length < 8) { setIssue("password", "Use at least 8 characters."); + if (!first) first = "password"; ok = false; } if (shell.userPw !== shell.userPw2) { setIssue("password_confirm", "The passwords do not match."); + if (!first) first = "password_confirm"; ok = false; } if (shell.luksPw.length < 8) { setIssue("passphrase", "Use at least 8 characters."); + if (!first) first = "passphrase"; ok = false; } if (shell.luksPw !== shell.luksPw2) { setIssue("passphrase_confirm", "The passphrases do not match."); + if (!first) first = "passphrase_confirm"; ok = false; } + if (!ok && first) + shell.focusIssueField(first); return ok; } @@ -460,27 +763,43 @@ ShellRoot { luks: shell.luksPw, user_password: shell.userPw }; - Bridge.setSecrets(secrets, () => saveAndAdvance()); + Bridge.setSecrets(secrets, reply => { + if (!reply.ok) { + shell.status = reply.error; + return; + } + saveAndAdvance(); + }); } function authorizeAndInstall() { if (shell.eraseText !== "ERASE") { shell.status = "Type ERASE exactly (case sensitive) to continue."; + shell.focusIssueField("erase"); return; } if (!shell.finalConfirm) { shell.status = "Tick the confirmation to continue."; return; } + if (!Bridge.ready) { + shell.status = "The installer backend is not running. Restart it and try again."; + return; + } + if (shell.installStarting) + return; + shell.installStarting = true; shell.status = "Authorizing…"; Bridge.destructivePreview(reply => { if (!reply.ok) { + shell.installStarting = false; shell.status = reply.error; return; } const digest = reply.data.plan_digest; Bridge.approve("ERASE", true, appr => { if (!appr.ok) { + shell.installStarting = false; shell.status = appr.error; return; } @@ -495,6 +814,11 @@ ShellRoot { shell.stageOrder = []; shell.progressLog = []; shell.status = ""; + shell.installStartedMs = Date.now(); + shell.elapsedSeconds = 0; + shell.lastActivity = ""; + shell.logLines = []; + shell.installStarting = false; Bridge.startInstall(digest, "ERASE", reply => { if (reply.ok) { shell.phase = "done"; @@ -534,6 +858,15 @@ ShellRoot { shell.progressLog = log; } + function restartBackend() { + shell.status = "Restarting the installer backend…"; + shell.aiConnected = false; + shell.aiTested = false; + shell.aiApplied = []; + shell.aiReviewAccepted = false; + Bridge.restart(); + } + function restartNow() { Quickshell.execDetached(["systemctl", "reboot"]); } @@ -541,6 +874,39 @@ ShellRoot { Qt.quit(); } + function elapsedLabel() { + const total = shell.elapsedSeconds; + const minutes = Math.floor(total / 60); + const seconds = total % 60; + if (minutes > 0) + return minutes + " min " + seconds + " s"; + return seconds + " s"; + } + + function currentStage() { + for (let i = shell.stageOrder.length - 1; i >= 0; i--) { + const stage = shell.stageOrder[i]; + if (shell.stageStatus[stage] === "started") + return stage; + } + return shell.stageOrder.length > 0 ? shell.stageOrder[shell.stageOrder.length - 1] : ""; + } + + function stageExplanation(stage) { + const entry = shell.progressLog.find(e => e.stage === stage && e.category !== undefined); + if (!entry) + return ""; + if (entry.category === "compile") + return "Compiling from source. This is the slow part of the install; time depends on your CPU, memory and the number of packages. There is no honest percentage to show, so progress is reported per stage."; + if (entry.category === "download") + return "Downloading verified files over the network."; + if (entry.category === "configure") + return "Writing configuration for the installed system."; + if (entry.category === "verify") + return "Checking the installed system."; + return "Preparing the target disk."; + } + Connections { target: Bridge function onAvailabilityChanged() { @@ -551,12 +917,52 @@ ShellRoot { if (Bridge.handshake) shell.onHandshake({ ok: true, data: Bridge.handshake }); } + function onBackendLost(message) { + shell.aiConnected = false; + shell.aiTested = false; + shell.aiApplied = []; + shell.aiReviewAccepted = false; + if (shell.phase === "progress") { + shell.phase = "failed"; + shell.failureText = "The installer backend stopped during the installation: " + message; + shell.failureDisk = "unknown"; + shell.failureNext = ["Restart the installer backend, review the log, and retry the installation."]; + } else { + shell.status = "The installer backend stopped. Restart it to continue."; + } + } function onEvent(name, data) { if (name === "progress") shell.onProgress(data); } } + // Keep the focused control inside the visible part of the scrolling body, + // so a keyboard user never tabs to an off-screen button. + Connections { + target: page.Window.window + function onActiveFocusItemChanged() { + shell.logState("focus"); + const item = page.Window.window ? page.Window.window.activeFocusItem : null; + if (item === null || item === undefined || item === page) + return; + let position; + try { + position = item.mapToItem(stepColumn, 0, 0); + } catch (e) { + return; + } + const top = flick.contentY; + const bottom = top + flick.height; + if (position.y < top + 8) + flick.contentY = Math.max(0, position.y - 24); + else if (position.y + item.height > bottom - 8) + flick.contentY = Math.min( + Math.max(0, flick.contentHeight - flick.height), + position.y + item.height - flick.height + 24); + } + } + Component.onCompleted: startBridge() // Keyboard navigation: Ctrl+Right advances (running the same validation as @@ -565,10 +971,7 @@ ShellRoot { function nextAction() { if (shell.phase !== "form") return; - if (shell.step === 6) - shell.authorizeAndInstall(); - else - shell.advance(); + shell.advance(); } Timer { @@ -583,6 +986,33 @@ ShellRoot { } } + Timer { + id: elapsedTimer + interval: 1000 + repeat: true + running: shell.phase === "progress" + onTriggered: shell.elapsedSeconds = Math.floor((Date.now() - shell.installStartedMs) / 1000) + } + + Timer { + id: progressLogTimer + interval: 5000 + repeat: true + running: shell.phase === "progress" + onTriggered: Bridge.logTail(40, r => { + if (!r.ok) + return; + shell.logLines = r.data.lines; + for (let i = shell.logLines.length - 1; i >= 0; i--) { + const line = ("" + shell.logLines[i]).trim(); + if (line.length > 0) { + shell.lastActivity = line; + break; + } + } + }) + } + FloatingWindow { id: window Component.onCompleted: { @@ -592,8 +1022,8 @@ ShellRoot { } visible: true color: Theme.charcoal - implicitWidth: 980 - implicitHeight: 680 + implicitWidth: 1024 + implicitHeight: 720 title: "Install Phoebus OS" Rectangle { @@ -627,6 +1057,8 @@ ShellRoot { shell.closeInstaller(); event.accepted = true; } else if (event.key === Qt.Key_Return || event.key === Qt.Key_Enter) { + // Only the page-level action; fields and buttons handle + // their own Return. shell.nextAction(); event.accepted = true; } @@ -651,7 +1083,9 @@ ShellRoot { font.weight: Font.DemiBold } Text { - text: shell.phase === "form" ? "Step " + (shell.step + 1) + " of 7 · " + shell.stepTitles[shell.step] : "Installation" + text: shell.phase === "form" + ? "Step " + (shell.step + 1) + " of " + shell.stepTitles.length + " · " + shell.stepTitles[shell.step] + : "Installation" color: Theme.amber font.family: Theme.family font.pixelSize: Theme.fontSmall @@ -673,7 +1107,7 @@ ShellRoot { spacing: 8 visible: shell.phase === "form" Repeater { - model: 7 + model: shell.stepTitles.length delegate: Rectangle { required property int index width: index === shell.step ? 26 : 10 @@ -703,103 +1137,133 @@ ShellRoot { width: flick.width spacing: 16 - // ============ STEP 0: language ======================== + // ============ STEP 0: welcome ========================= 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 } - PhoebusCombo { - id: localeField - label: "Locale" - placeholder: "en_US.UTF-8" - options: shell.options.locales - error: shell.issueFor("locale") - onEdited: value => shell.cfg.system.locale = value - onSelected: value => shell.cfg.system.locale = value - Component.onCompleted: inputItem.text = shell.cfg ? shell.cfg.system.locale : "" - } - PhoebusCombo { - id: keymapField - label: "Keyboard layout" - placeholder: "us" - options: shell.options.keymaps - error: shell.issueFor("keymap") - onEdited: value => shell.cfg.system.keymap = value - onSelected: value => shell.cfg.system.keymap = value - Component.onCompleted: inputItem.text = shell.cfg ? shell.cfg.system.keymap : "" - } - PhoebusCombo { - id: tzField - label: "Timezone" - placeholder: "UTC" - options: shell.options.timezones - error: shell.issueFor("timezone") - onEdited: value => shell.cfg.system.timezone = value - onSelected: value => shell.cfg.system.timezone = value - Component.onCompleted: inputItem.text = shell.cfg ? shell.cfg.system.timezone : "" + 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 wizard installs Phoebus to your computer. It asks a few questions, explains each one, and changes nothing until you review the plan and type ERASE."; color: Theme.muted; font.family: Theme.family; font.pixelSize: Theme.fontBody; wrapMode: Text.WordWrap } + Text { width: parent.width; text: "You will choose language and keyboard, check the internet, connect an AI model, pick a disk, and set your account and encryption passphrase."; color: Theme.muted; font.family: Theme.family; font.pixelSize: Theme.fontBody; wrapMode: Text.WordWrap } + PhoebusButton { + id: welcomeNext + label: "Get started" + primary: true + onClicked: shell.advance() } } 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…" } + Text { width: parent.width; text: "Before you begin"; color: Theme.warmWhite; font.family: Theme.family; font.pixelSize: Theme.fontHeading; font.weight: Font.DemiBold } + PrereqRow { label: "An internet connection"; ok: true; detail: "Phoebus downloads verified packages during installation." } + PrereqRow { label: "A connected AI model"; ok: true; detail: "Required to install. You can connect a hosted provider or a local model." } + PrereqRow { label: "A target disk"; ok: true; detail: "The chosen disk is completely erased. Back up anything you need first." } } } - // ============ STEP 1: network ========================= + // ============ STEP 1: language ======================== 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 + Text { width: parent.width; text: "Language and region"; color: Theme.warmWhite; font.family: Theme.family; font.pixelSize: Theme.fontHeading; font.weight: Font.DemiBold } + Text { width: parent.width; text: "Choose the language, time zone and keyboard layout for the installed system. Type to filter each list, then use the arrow keys and Enter to pick."; color: Theme.muted; font.family: Theme.family; font.pixelSize: Theme.fontSmall; wrapMode: Text.WordWrap } + PhoebusCombo { + id: localeField + label: "Language and locale" + placeholder: "Start typing, e.g. English" + options: shell.options.locales + error: shell.issueFor("locale") + onEdited: value => shell.cfg.system.locale = value + onSelected: value => { shell.cfg.system.locale = value; shell.logState("field"); } } - 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() } + PhoebusCombo { + id: keymapField + label: "Keyboard layout" + placeholder: "Start typing, e.g. German" + options: shell.options.keymaps + error: shell.issueFor("keymap") + onEdited: value => shell.cfg.system.keymap = value + onSelected: value => { shell.cfg.system.keymap = value; shell.logState("field"); } + } + PhoebusCombo { + id: tzField + label: "Time zone" + placeholder: "Start typing, e.g. Europe" + options: shell.options.timezones + error: shell.issueFor("timezone") + onEdited: value => shell.cfg.system.timezone = value + onSelected: value => { shell.cfg.system.timezone = value; shell.logState("field"); } } } 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" } + Text { width: parent.width; text: "Test the live 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 check the keyboard you are using right now (the live session uses \"" + shell.liveKeymap + "\"). The layout you chose above is applied to the installed system; the running live session keeps its own layout until you restart." + 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 2: AI ============================== + // ============ STEP 2: network ========================= 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 + Text { width: parent.width; text: "Internet and readiness"; color: Theme.warmWhite; font.family: Theme.family; font.pixelSize: Theme.fontHeading; font.weight: Font.DemiBold } + Text { width: parent.width; text: "Phoebus downloads a verified Gentoo stage3 and packages during installation. There are two things to check: whether this computer is connected, and whether it can actually reach the installation services."; color: Theme.muted; font.family: Theme.family; font.pixelSize: Theme.fontBody; wrapMode: Text.WordWrap } + PrereqRow { + label: "Local network connection" + ok: !!(shell.readiness && shell.readiness.network) + detail: shell.checkingReadiness ? "Checking…" + : (shell.readiness && shell.readiness.network ? "A network route is available." : "No network connection was detected.") } + PrereqRow { + label: "Installation services" + ok: !!(shell.readiness && shell.readiness.network_services) + detail: shell.checkingReadiness ? "Checking…" + : (shell.readiness && shell.readiness.network_services ? "Verified: the installation source answered." + : (shell.readiness && shell.readiness.network_detail ? shell.readiness.network_detail : "Not verified yet.")) + } + 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) : "?" } + 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 { + id: networkRetry + label: shell.checkingReadiness ? "Checking…" : "Re-check" + actionEnabled: !shell.checkingReadiness + onClicked: shell.refreshReadiness() + } + } + } + } + + // ============ STEP 3: AI ============================== + Column { + width: parent.width + spacing: 16 + visible: shell.step === 3 + 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, so installation needs a connected model. Choose a hosted provider and paste your key, or point Phoebus at a model you have downloaded and are serving on this computer. The installed system boots, runs and recovers without a model."; color: Theme.muted; font.family: Theme.family; font.pixelSize: Theme.fontBody; wrapMode: Text.WordWrap } + Text { width: parent.width; text: "What is shared: Phoebus sends only hardware and storage facts (CPU, memory, firmware, graphics vendors, the target disk path and size, and the profiles you chose) so the model can suggest fitting options. It never sends passwords, passphrases, API keys, your name, or your files."; color: Theme.muted; font.family: Theme.family; font.pixelSize: Theme.fontSmall; wrapMode: Text.WordWrap } PhoebusChoice { id: providerChoice options: [ @@ -818,15 +1282,14 @@ ShellRoot { placeholder: "Paste your provider key" secret: true visible: shell.cfg && !shell.isOpenCode && (shell.cfg.ai.provider === "deepseek" || shell.cfg.ai.provider === "openai") - onEdited: value => shell.apiKey = value + onEdited: value => { shell.apiKey = value; shell.aiConnectionEdited(); } } PhoebusField { id: endpointField label: "Endpoint (local models)" placeholder: "http://127.0.0.1:11434/v1/chat/completions" visible: shell.cfg && !shell.isOpenCode && 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 : "" + onEdited: value => { shell.cfg.ai.endpoint = value; shell.aiConnectionEdited(); } } PhoebusCombo { id: modelField @@ -834,27 +1297,36 @@ ShellRoot { placeholder: "choose a model or type one" options: shell.aiCatalog.models visible: shell.cfg && !shell.isOpenCode - onEdited: value => shell.cfg.ai.model = value - onSelected: value => shell.cfg.ai.model = value - Component.onCompleted: inputItem.text = shell.cfg && shell.cfg.ai.model ? shell.cfg.ai.model : "" + onEdited: value => { shell.cfg.ai.model = value; shell.aiConnectionEdited(); } + onSelected: value => { shell.cfg.ai.model = value; shell.aiConnectionEdited(); } } - Row { - spacing: 12 + Column { + width: parent.width + spacing: 4 visible: shell.cfg && !shell.isOpenCode PhoebusButton { - label: shell.aiChecking ? "Loading…" : "Load model list" + label: shell.aiCatalogLoading ? "Loading…" : "Load model list" compact: true + actionEnabled: !shell.aiCatalogLoading onClicked: shell.loadAiCatalog() } Text { - anchors.verticalCenter: parent.verticalCenter + width: parent.width visible: shell.aiCatalogError.length > 0 text: shell.aiCatalogError color: Theme.danger font.family: Theme.family font.pixelSize: Theme.fontSmall - width: parent.width - 200 - elide: Text.ElideRight + wrapMode: Text.WordWrap + } + Text { + width: parent.width + visible: shell.aiCatalogStatus === "empty" + text: "Connected, but this provider listed no models. Type a model name or choose another provider." + color: Theme.warning + font.family: Theme.family + font.pixelSize: Theme.fontSmall + wrapMode: Text.WordWrap } } // -- OpenCode agent server ----------------------------- @@ -872,7 +1344,7 @@ ShellRoot { label: "OpenCode server" placeholder: "http://127.0.0.1:4096" visible: shell.isOpenCode - onEdited: value => shell.cfg.ai.opencode_server = value + onEdited: value => { shell.cfg.ai.opencode_server = value; shell.aiConnectionEdited(); } } PhoebusField { id: opencodePasswordField @@ -880,7 +1352,7 @@ ShellRoot { placeholder: "OPENCODE_SERVER_PASSWORD" secret: true visible: shell.isOpenCode - onEdited: value => shell.opencodePassword = value + onEdited: value => { shell.opencodePassword = value; shell.aiConnectionEdited(); } } PhoebusCombo { id: opencodeProviderField @@ -888,9 +1360,10 @@ ShellRoot { placeholder: "choose a provider" options: shell.aiProviderIds visible: shell.isOpenCode - onEdited: value => shell.cfg.ai.opencode_provider = value + onEdited: value => { shell.cfg.ai.opencode_provider = value; shell.aiConnectionEdited(); } onSelected: value => { shell.cfg.ai.opencode_provider = value; + shell.aiConnectionEdited(); shell.loadAiCatalog(); } } @@ -900,26 +1373,27 @@ ShellRoot { placeholder: "choose a model" options: shell.aiCatalog.models visible: shell.isOpenCode - onEdited: value => shell.cfg.ai.opencode_model = value - onSelected: value => shell.cfg.ai.opencode_model = value + onEdited: value => { shell.cfg.ai.opencode_model = value; shell.aiConnectionEdited(); } + onSelected: value => { shell.cfg.ai.opencode_model = value; shell.aiConnectionEdited(); } } - Row { - spacing: 12 + Column { + width: parent.width + spacing: 4 visible: shell.isOpenCode PhoebusButton { - label: "Load provider/model list" + label: shell.aiCatalogLoading ? "Loading…" : "Load provider/model list" compact: true + actionEnabled: !shell.aiCatalogLoading onClicked: shell.loadAiCatalog() } Text { - anchors.verticalCenter: parent.verticalCenter + width: parent.width visible: shell.aiCatalogError.length > 0 text: shell.aiCatalogError color: Theme.danger font.family: Theme.family font.pixelSize: Theme.fontSmall - width: parent.width - 240 - elide: Text.ElideRight + wrapMode: Text.WordWrap } } Row { @@ -930,7 +1404,8 @@ ShellRoot { onClicked: shell.testAi() } PhoebusButton { - label: shell.aiChecking ? "Checking…" : "Connect and validate" + id: aiConnectBtn + label: shell.aiChecking ? "Connecting…" : "Connect and validate" primary: true actionEnabled: !shell.aiChecking && !shell.aiTesting onClicked: shell.connectAi() @@ -945,6 +1420,16 @@ ShellRoot { text: "Model responded" tone: Theme.success } + PhoebusChip { + visible: shell.aiChecking + text: "Connecting…" + tone: Theme.amber + } + PhoebusChip { + visible: shell.aiCatalogStatus === "loading" + text: "Loading models…" + tone: Theme.amber + } } Text { width: parent.width @@ -964,11 +1449,27 @@ ShellRoot { font.pixelSize: Theme.fontSmall wrapMode: Text.WordWrap } + PhoebusButton { + visible: shell.aiCatalogStatus === "unreachable" || shell.aiCatalogStatus === "authentication_rejected" || shell.aiCatalogStatus === "authentication_required" + label: "Retry connection" + compact: true + actionEnabled: !shell.aiChecking && !shell.aiCatalogLoading + onClicked: shell.connectAi() + } } 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 } + visible: shell.aiConnected + Text { width: parent.width; text: "Proposed installation changes"; color: Theme.warmWhite; font.family: Theme.family; font.pixelSize: Theme.fontHeading; font.weight: Font.DemiBold } + Text { + width: parent.width + visible: shell.aiApplied.length === 0 + text: "The model validated the connection and proposed no changes. You can continue with the current settings." + color: Theme.muted + font.family: Theme.family + font.pixelSize: Theme.fontBody + wrapMode: Text.WordWrap + } Repeater { model: shell.aiApplied delegate: Column { @@ -979,16 +1480,51 @@ ShellRoot { Text { width: parent.width; text: " " + modelData.reason; color: Theme.muted; font.family: Theme.family; font.pixelSize: Theme.fontSmall; wrapMode: Text.WordWrap } } } + Row { + spacing: 12 + visible: shell.aiApplied.length > 0 + PhoebusButton { + label: shell.aiReviewAccepted ? "Changes accepted" : "Accept changes" + primary: true + actionEnabled: !shell.aiReviewAccepted + onClicked: shell.acceptAiChanges() + } + PhoebusButton { + label: "Discard and reconnect" + compact: true + onClicked: shell.discardAiChanges() + } + } + Text { + width: parent.width + visible: shell.aiApplied.length > 0 && !shell.aiReviewAccepted + text: "Choose Accept changes to continue, or Discard to undo them and connect again." + color: Theme.warning + font.family: Theme.family + font.pixelSize: Theme.fontSmall + wrapMode: Text.WordWrap + } } } - // ============ STEP 3: disk ============================ + // ============ STEP 4: disk ============================ Column { width: parent.width spacing: 16 - visible: shell.step === 3 + visible: shell.step === 4 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; text: "The disk you select is erased completely and replaced with Phoebus. Protected disks and the installation medium cannot be selected; the reason is shown on each card."; color: Theme.muted; font.family: Theme.family; font.pixelSize: Theme.fontSmall; wrapMode: Text.WordWrap } + Item { id: diskFocusAnchor; width: 1; height: 1; activeFocusOnTab: true; Accessible.role: Accessible.StaticText; Accessible.name: "Destination disk list" } + Text { + width: parent.width + visible: shell.selectedDisk.length > 0 + text: "Selected: " + shell.selectedDisk + ". This entire disk will be erased." + color: Theme.danger + font.family: Theme.family + font.pixelSize: Theme.fontBody + font.weight: Font.DemiBold + 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 @@ -997,35 +1533,43 @@ ShellRoot { width: stepColumn.width disk: modelData selected: shell.cfg && shell.cfg.storage.disk === modelData.path - onPicked: path => { shell.cfg.storage.disk = path; shell.selectedDisk = path; } + onPicked: path => { shell.cfg.storage.disk = path; shell.selectedDisk = path; shell.clearIssues(); shell.touchConfig(); shell.logState("disk"); } } } PhoebusButton { label: "Rescan disks"; compact: true; onClicked: shell.refreshDisks() } } - // ============ STEP 4: account ========================= + // ============ STEP 5: account ========================= Column { width: parent.width spacing: 16 - visible: shell.step === 4 + visible: shell.step === 5 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; placeholder: "At least 8 characters"; error: shell.issueFor("password"); onEdited: value => shell.userPw = value } - PhoebusField { id: pw2Field; label: "Confirm password"; secret: true; placeholder: "Repeat the password"; error: shell.issueFor("password_confirm"); onEdited: value => shell.userPw2 = value } + Text { width: parent.width; text: "This is the everyday login you will use to sign in to Phoebus. It is asked for at the login screen after the disk is unlocked."; color: Theme.muted; font.family: Theme.family; font.pixelSize: Theme.fontSmall; wrapMode: Text.WordWrap } + PhoebusField { id: fullnameField; label: "Full name"; onEdited: value => shell.cfg.user.fullname = value } + PhoebusField { id: userField; label: "Username"; placeholder: "lowercase"; error: shell.issueFor("username"); onEdited: value => shell.cfg.user.username = value } + PhoebusField { id: hostField; label: "Computer name"; placeholder: "phoebus"; error: shell.issueFor("hostname"); onEdited: value => shell.cfg.system.hostname = value } + PhoebusField { id: pwField; label: "Login password"; secret: true; placeholder: "At least 8 characters"; error: shell.issueFor("password"); onEdited: value => shell.userPw = value } + PhoebusField { id: pw2Field; label: "Confirm login password"; secret: true; placeholder: "Repeat the password"; 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 } + Text { width: parent.width; text: "The encryption passphrase is different from your login password. It is asked for first, as soon as the computer starts, to unlock the disk. Without it the disk cannot be read, and it cannot be recovered, so keep it safe. Your login password is only asked for after the disk is unlocked."; color: Theme.muted; font.family: Theme.family; font.pixelSize: Theme.fontSmall; wrapMode: Text.WordWrap } PhoebusField { id: luksField; label: "Encryption passphrase"; secret: true; placeholder: "At least 8 characters"; error: shell.issueFor("passphrase"); onEdited: value => shell.luksPw = value } - PhoebusField { id: luks2Field; label: "Confirm passphrase"; secret: true; placeholder: "Repeat the passphrase"; error: shell.issueFor("passphrase_confirm"); onEdited: value => shell.luksPw2 = value } + PhoebusField { id: luks2Field; label: "Confirm encryption passphrase"; secret: true; placeholder: "Repeat the passphrase"; error: shell.issueFor("passphrase_confirm"); onEdited: value => shell.luksPw2 = value } } PhoebusCard { width: parent.width + Text { width: parent.width; text: "Desktop and options"; color: Theme.warmWhite; font.family: Theme.family; font.pixelSize: Theme.fontHeading; font.weight: Font.DemiBold } + 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(); } + } PhoebusButton { label: shell.showAdvanced ? "Hide advanced options" : "Advanced options"; compact: true; onClicked: shell.showAdvanced = !shell.showAdvanced } Column { width: parent.width @@ -1049,12 +1593,6 @@ ShellRoot { 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(); } } @@ -1062,46 +1600,42 @@ ShellRoot { } } - // ============ 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 ========================= + // ============ STEP 6: review and 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: "Review the installation plan"; color: Theme.warmWhite; font.family: Theme.family; font.pixelSize: Theme.fontHeading; font.weight: Font.DemiBold } + Text { width: parent.width; text: "These facts come from the installer backend. Use Change to edit any section; the plan and the confirmation are refreshed automatically."; color: Theme.muted; font.family: Theme.family; font.pixelSize: Theme.fontSmall; wrapMode: Text.WordWrap } + ReviewRow { label: "Target disk"; value: shell.review ? shell.review.target_disk : "…"; danger: true } + 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: "Language"; value: shell.review ? shell.review.locale : "…" } + ReviewRow { label: "Keyboard"; value: shell.review ? shell.review.keymap : "…" } + ReviewRow { label: "Time zone"; 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(" ") : "…" } + Row { + spacing: 12 + PhoebusButton { label: "Change language"; compact: true; onClicked: shell.jumpTo(1) } + PhoebusButton { label: "Change disk"; compact: true; onClicked: shell.jumpTo(4) } + PhoebusButton { label: "Change account"; compact: true; onClicked: shell.jumpTo(5) } + PhoebusButton { label: "Change model"; compact: true; onClicked: shell.jumpTo(3) } + } + } + PhoebusCard { + width: parent.width + Text { width: parent.width; text: "Everything on the target disk will be erased"; color: Theme.danger; 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 } + } + PhoebusCard { + width: parent.width + Text { width: parent.width; text: "Confirm and install"; 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 } @@ -1122,7 +1656,10 @@ ShellRoot { 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: "Elapsed: " + shell.elapsedLabel() + " · Current stage: " + (shell.currentStage().length > 0 ? shell.stageLabel(shell.currentStage()) : "starting"); color: Theme.amber; font.family: Theme.family; font.pixelSize: Theme.fontBody } 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 } + Text { width: parent.width; visible: shell.currentStage().length > 0; text: shell.stageExplanation(shell.currentStage()); color: Theme.muted; font.family: Theme.family; font.pixelSize: Theme.fontSmall; wrapMode: Text.WordWrap } + Text { width: parent.width; visible: shell.lastActivity.length > 0; text: "Activity: " + shell.lastActivity; color: Theme.muted; font.family: "monospace"; font.pixelSize: Theme.fontSmall; elide: Text.ElideRight } Text { width: parent.width; text: "This cannot be cancelled safely once disk changes begin. Leave the window open until the installation finishes or reports an error."; color: Theme.warning; font.family: Theme.family; font.pixelSize: Theme.fontSmall; wrapMode: Text.WordWrap } Rectangle { id: progressTrack @@ -1164,6 +1701,20 @@ ShellRoot { } } } + PhoebusButton { + label: shell.showFailureLog ? "Hide details" : "Details (redacted log)" + compact: true + onClicked: { + shell.showFailureLog = !shell.showFailureLog; + if (shell.showFailureLog) + Bridge.logTail(200, r => { if (r.ok) shell.logLines = r.data.lines; }); + } + } + 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 } + } } Column { @@ -1181,7 +1732,7 @@ ShellRoot { 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 } + Text { width: parent.width; text: "1. Remove the installation medium (the DVD or USB drive).\n2. Restart the computer.\n3. Enter your encryption passphrase to unlock the disk.\n4. Sign in with your username and login password.\n5. The first desktop session starts in a few moments."; color: Theme.warmWhite; font.family: Theme.family; font.pixelSize: Theme.fontBody; wrapMode: Text.WordWrap } } Row { spacing: 12 @@ -1208,7 +1759,8 @@ ShellRoot { 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: "Back to review"; onClicked: { shell.phase = "form"; shell.step = 6; shell.enterStep(); } } + PhoebusButton { label: "Restart backend"; compact: true; onClicked: shell.restartBackend() } PhoebusButton { label: "Close installer"; compact: true; onClicked: shell.closeInstaller() } } PhoebusCard { @@ -1227,8 +1779,8 @@ ShellRoot { 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 + text: (!Bridge.ready ? "Installer backend starting… " : "") + (Bridge.lastError.length > 0 && !Bridge.ready ? "[" + Bridge.lastError + "] " : "") + shell.status + color: shell.status.indexOf("fix") !== -1 || shell.status.indexOf("requires") !== -1 || shell.status.indexOf("Connect") !== -1 ? Theme.danger : Theme.muted font.family: Theme.family font.pixelSize: Theme.fontSmall width: Math.max(120, parent.width - 320) @@ -1238,17 +1790,18 @@ ShellRoot { 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 > 0; label: "Back"; actionEnabled: shell.step > 0; onClicked: shell.back() } PhoebusButton { visible: shell.step < 6 - label: "Next" + label: shell.step === 0 ? "Get started" : (shell.step === 2 && shell.readiness && shell.readiness.network && !shell.readiness.network_services ? "Continue anyway" : "Next") primary: true onClicked: shell.advance() } PhoebusButton { visible: shell.step === 6 - label: "Install now" + label: shell.installStarting ? "Starting…" : "Install now" primary: true + actionEnabled: !shell.installStarting onClicked: shell.authorizeAndInstall() } } @@ -1256,6 +1809,13 @@ ShellRoot { } } + function jumpTo(target) { + if (target < 0 || target > 6) + return; + shell.step = target; + shell.enterStep(); + } + // -- inline helper components ------------------------------------------ component PrereqRow: Row { property string label: "" @@ -1266,19 +1826,20 @@ ShellRoot { Rectangle { width: 10; height: 10; radius: 5 anchors.verticalCenter: parent.verticalCenter - color: parent.ok ? Theme.success : Theme.danger + color: parent.ok ? Theme.success : Theme.warning } - 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 } + Text { text: parent.label; color: Theme.warmWhite; font.family: Theme.family; font.pixelSize: Theme.fontBody; width: 240; wrapMode: Text.WordWrap } + Text { text: parent.detail; color: Theme.muted; font.family: Theme.family; font.pixelSize: Theme.fontSmall; width: parent.width - 280; wrapMode: Text.WordWrap } } component ReviewRow: Row { property string label: "" property string value: "" + property bool danger: false 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 } + Text { text: parent.label; color: Theme.muted; font.family: Theme.family; font.pixelSize: Theme.fontBody; width: 160; wrapMode: Text.WordWrap } + Text { text: parent.value; color: parent.danger ? Theme.danger : Theme.warmWhite; font.family: Theme.family; font.pixelSize: Theme.fontBody; width: parent.width - 180; wrapMode: Text.WordWrap } } component DiskCard: Rectangle { @@ -1295,7 +1856,8 @@ ShellRoot { opacity: usable ? 1 : 0.7 activeFocusOnTab: usable Accessible.role: Accessible.RadioButton - Accessible.name: disk ? disk.path : "" + Accessible.name: disk ? (disk.path + ", " + disk.size_human + ", " + disk.model) : "" + Accessible.description: usable ? "Select this disk as the installation target" : ("This disk cannot be selected. " + (disk && disk.protection ? disk.protection : "")) Accessible.checked: selected Keys.onReturnPressed: if (usable) diskCard.picked(diskCard.disk.path) @@ -1318,14 +1880,14 @@ ShellRoot { 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.model : ""; 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.selected; text: "selected — will be erased"; tone: Theme.danger } 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; text: diskCard.disk ? (diskCard.disk.path + " · " + diskCard.disk.identifier + " · " + 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) ? ("Cannot be selected: " + 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 } } } diff --git a/installer/tests/vm/gui-driver.py b/installer/tests/vm/gui-driver.py index 9ea8663..4852dae 100644 --- a/installer/tests/vm/gui-driver.py +++ b/installer/tests/vm/gui-driver.py @@ -11,6 +11,10 @@ Modes: gui : boot, log in on serial, verify the welcome/branding payload, open the installer from the welcome action, prove duplicate prevention, walk the wizard steps and capture screenshots. + opencode: drive the OpenCode AI step through the real graphical UI and + validate a model response and proposal. + gui-install: complete a full installation through the visible wizard (AI + connection, disk, account, ERASE, install) on a disposable disk. 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. @@ -59,12 +63,13 @@ BOOT_TIMEOUT = int(os.environ.get("BOOT_TIMEOUT", "900")) INSTALL_TIMEOUT = int(os.environ.get("INSTALL_TIMEOUT", "10800")) SESSION_SETTLE = int(os.environ.get("SESSION_SETTLE", "20")) BACKEND_SETTLE = int(os.environ.get("BACKEND_SETTLE", "30")) -# OpenCode GUI-driving knobs (test-only). Tab counts assume the focus order: -# Close, DeepSeek, OpenAI, Local, OpenCode, server, password, provider, model, -# Test, Connect, Back, Next. +# OpenCode GUI-driving knobs (test-only). The wizard focuses the first AI +# provider chip when the AI step opens, so three Tabs reach the OpenCode chip. +# After selecting it, the field order is server, password (with a keyboard +# reveal control), provider, model, load, Test, Connect. OC_PORT = int(os.environ.get("OC_PORT", "4096")) OC_TARGET_PORT = int(os.environ.get("OC_TARGET_PORT", "41999")) -OC_TAB_TO_CHIP = int(os.environ.get("OC_TAB_TO_CHIP", "5")) +OC_TAB_TO_CHIP = int(os.environ.get("OC_TAB_TO_CHIP", "3")) OC_PROVIDER = os.environ.get("OC_PROVIDER", "deepseek") OC_MODEL = os.environ.get("OC_MODEL", "deepseek-v4-flash") OC_USE_PASSWORD = os.environ.get("OC_USE_PASSWORD", "0") in ("1", "yes", "true") @@ -304,6 +309,8 @@ class Driver: self.do_gui() elif self.mode == "opencode": self.do_opencode() + elif self.mode == "gui-install": + self.do_gui_install() elif self.mode == "install": self.do_install() elif self.mode == "boot": @@ -492,10 +499,36 @@ class Driver: f"n1={n1} n2={n2}", ) - # Keyboard-walk the wizard, capturing each step. + # Keyboard-walk the wizard, capturing each step. The welcome step's + # primary action is focused, so Return starts the journey; Ctrl+Right + # then advances through the deterministic steps. + self.sendkey("ret") + time.sleep(2) + self.shot("03-language", "language and keyboard", "Return on Get started", + "the language and keyboard step is shown") + # Regression: the suggestion list supports arrow-key navigation and + # Enter selection, with the value stored being the identifier. + self.sendkey("ctrl-a") + time.sleep(0.3) + self.shell("wtype 'de_DE' >/dev/null 2>&1; echo TYPED", "TYPED", + timeout=30, label="type-locale") + time.sleep(1.0) + self.sendkey("down") + time.sleep(0.5) + self.sendkey("ret") + time.sleep(1.0) + picked = self._frontend_state() + self.results.assert_true( + "keyboard-suggestion-select", + picked is not None and picked["step"] == 1 + and picked["locale"].startswith("de_DE"), + f"Down/Enter did not select the highlighted suggestion: {picked}", + ) + self.shot("03b-locale-selected", "locale selected", "Down then Enter", + "the highlighted locale is selected") for slug, state in [ - ("03-network", "network and prerequisites"), - ("04-ai-model", "AI model connection"), + ("04-network", "network and prerequisites"), + ("05-ai-model", "AI model connection"), ]: self.sendkey("ctrl-right") time.sleep(2) @@ -515,7 +548,7 @@ class Driver: "the AI step allowed advancement without a connected model", ) # Behavioral evidence from the frontend's own state lines: the wizard is - # still on the AI step (index 2) and has not reported a connection, and + # still on the AI step (index 3) and has not reported a connection, and # it shows an inline error. A surviving process or a screenshot would # not prove any of this. state = self._frontend_state() @@ -523,7 +556,7 @@ class Driver: self.results.fail("ai-page-remains", "no frontend state line found") else: self.results.assert_true( - "ai-page-remains", state["step"] == 2 and not state["aiConnected"], + "ai-page-remains", state["step"] == 3 and not state["aiConnected"], f"last state: {state}", ) self.results.assert_true( @@ -548,8 +581,14 @@ class Driver: self.child.expect("STATE-END", timeout=30) except (pexpect.TIMEOUT, pexpect.EOF): return None - step = ai = tested = None + step = ai = tested = review = None applied = 0 + disk = "" + locale = "" + keymap = "" + phase = "" + confirmed = False + focus = "" err = "" for line in (self.child.before or "").splitlines(): if "phoebus-state" not in line: @@ -557,15 +596,36 @@ class Driver: match = re.search(r"step=(\d+)", line) if match: step = int(match.group(1)) + match = re.search(r"phase=(\w+)", line) + if match: + phase = match.group(1) match = re.search(r"aiConnected=(true|false)", line) if match: ai = match.group(1) == "true" match = re.search(r"aiTested=(true|false)", line) if match: tested = match.group(1) == "true" + match = re.search(r"aiReview=(true|false)", line) + if match: + review = match.group(1) == "true" match = re.search(r"aiApplied=(\d+)", line) if match: applied = int(match.group(1)) + match = re.search(r"disk=(\S*)", line) + if match: + disk = match.group(1) + match = re.search(r"locale=(\S*)", line) + if match: + locale = match.group(1) + match = re.search(r"keymap=(\S*)", line) + if match: + keymap = match.group(1) + match = re.search(r"confirm=(true|false)", line) + if match: + confirmed = match.group(1) == "true" + match = re.search(r"focus=(\S*)", line) + if match: + focus = match.group(1) match = re.search(r"aiError=(.*?) aiTest=", line) if match: err = match.group(1).strip() @@ -573,9 +633,16 @@ class Driver: return None return { "step": step, + "phase": phase, "aiConnected": bool(ai), "aiTested": bool(tested), "aiApplied": applied, + "aiReview": bool(review), + "disk": disk, + "locale": locale, + "keymap": keymap, + "confirm": confirmed, + "focus": focus, "aiError": err, } @@ -639,19 +706,22 @@ class Driver: "CLOSED", timeout=30, label="close-welcome", ) - # Navigate to the AI step (0 -> 1 -> 2). + # Navigate to the AI step (welcome -> language -> network -> AI). + self.sendkey("ret") + time.sleep(2) self.sendkey("ctrl-right") time.sleep(2) self.sendkey("ctrl-right") time.sleep(2) state = self._frontend_state() self.results.assert_true( - "ai-step-reached", state is not None and state["step"] == 2, + "ai-step-reached", state is not None and state["step"] == 3, f"frontend state: {state}", ) - self.shot("oc-01-ai", "AI step", "Ctrl+Right twice", "the AI model step is shown") + self.shot("oc-01-ai", "AI step", "Return + Ctrl+Right twice", "the AI model step is shown") - # Select the "OpenCode agent" chip with the keyboard. + # Select the "OpenCode agent" chip with the keyboard. The AI step opens + # with the first provider chip focused. for _ in range(OC_TAB_TO_CHIP): self.sendkey("tab") time.sleep(0.3) @@ -661,8 +731,8 @@ class Driver: "server, password, provider and model fields appear") # Enter the connection through the UI. Focus is on the chip after - # selection; Tab order is server, password, provider, model, Test, - # Connect. Ctrl+A selects the existing default before typing. + # selection; Tab order is server, password (input + reveal), provider, + # model, load, Test. Ctrl+A selects the existing default before typing. def type_field(tabs: int, value: str, secret_file: str | None = None) -> None: # `wtype` (Wayland) and QEMU `sendkey` (hardware) are two input # paths; settle between them or the next key can truncate the text. @@ -695,14 +765,19 @@ class Driver: "PW-LOADED", timeout=30, label="fetch-password", ) type_field(1, "", secret_file="/tmp/oc.pw") + self.sendkey("tab") # the keyboard reveal control else: - self.sendkey("tab") # skip the empty password field + self.sendkey("tab") # the empty password field + time.sleep(0.25) + self.sendkey("tab") # the keyboard reveal control time.sleep(0.25) type_field(1, OC_PROVIDER) type_field(1, OC_MODEL) self.shot("oc-02b-fields", "OpenCode fields", "typed server/provider/model", "the fields hold the entered values") - self.sendkey("tab") # model -> Test + self.sendkey("tab") # model -> load + time.sleep(0.3) + self.sendkey("tab") # load -> Test time.sleep(0.3) self.sendkey("ret") time.sleep(3) @@ -732,8 +807,310 @@ class Driver: "opencode-proposal-applied", f"applied={connected['aiApplied']} change(s)", ) + + # Regression: editing the model must invalidate the green "validated" + # indicator, because the backend would require revalidation. Focus is + # on Connect; Shift+Tab walks back over Test and Load to the model. + for _ in range(3): + self.sendkey("shift-tab") + time.sleep(0.4) + self._gui_type(OC_MODEL + "-changed") + edited = self.wait_state(lambda s: not s["aiConnected"], timeout=30) + self.results.assert_true( + "ai-invalidated-on-model-edit", edited is not None, + "editing the model left the AI connection green", + ) self.results.pass_("opencode-gui-completed") + # -- full graphical installation -------------------------------------- + _PLAIN_KEYS = { + " ": "spc", "-": "minus", "=": "equal", "[": "bracketleft", + "]": "bracketright", "\\": "backslash", ";": "semicolon", + "'": "apostrophe", ",": "comma", ".": "dot", "/": "slash", "`": "grave", + } + _SHIFT_KEYS = { + "_": "minus", "+": "equal", ":": "semicolon", '"': "apostrophe", + "<": "comma", ">": "dot", "?": "slash", "{": "bracketleft", + "}": "bracketright", "|": "backslash", "~": "grave", + } + + def _tabs(self, count: int) -> None: + for _ in range(count): + self.sendkey("tab") + time.sleep(0.4) + + def _send_chars(self, text: str) -> None: + """Type text as hardware key events. + + The QEMU/HMP `wtype` path used by `opencode` mode can leave the + compositor focus ambiguous. The full-install journey types every field + with real key events so focus is always exactly the focused control. + """ + for ch in text: + if ch.isalpha(): + self.sendkey(ch if ch.islower() else "shift-" + ch.lower()) + elif ch.isdigit(): + self.sendkey(ch) + elif ch in self._PLAIN_KEYS: + self.sendkey(self._PLAIN_KEYS[ch]) + elif ch in self._SHIFT_KEYS: + self.sendkey("shift-" + self._SHIFT_KEYS[ch]) + else: + raise HarnessError(f"no QEMU key for character {ch!r}") + time.sleep(0.1) + + def _gui_type(self, value: str) -> None: + self.sendkey("ctrl-a") + time.sleep(0.3) + self._send_chars(value) + time.sleep(1.0) + + def _accept_ai_review(self, applied: int): + """Accept a proposed-change review if one was applied. + + The Accept button follows Connect (and possibly the conditional Retry + button), so try a few Tab/Return pairs and stop as soon as the review + is accepted. + """ + if applied <= 0: + return True + for _ in range(4): + self.sendkey("tab") + time.sleep(0.4) + self.sendkey("ret") + time.sleep(1.5) + state = self._frontend_state() + if state is not None and state["aiReview"]: + return True + return False + + def do_gui_install(self) -> None: + """Complete installation through the visible wizard. + + `appliance-guest-gui.sh` installs non-interactively, which does not + prove the graphical journey. This mode presses the real controls: it + connects OpenCode through the UI, accepts the reviewed AI changes, + selects a disk, sets the account, types ERASE, installs, and checks the + frontend reports completion. The disk must be a disposable qcow2. + """ + if not self.disks: + self.results.blocked("gui-install-disk", "no writable disk configured") + return + self.spawn(attach_iso=True, boot_disk=False) + self.login_live() + welcome = self.poll_shell( + "echo WELCOME=$(pgrep -fc 'quickshell.*phoebus-welcome' 2>/dev/null || echo 0)", + r"WELCOME=([1-9][0-9]*)", + timeout=int(os.environ.get("WELCOME_TIMEOUT", "180")), + label="welcome-window", + ) + self.results.assert_true("welcome-autostarted", welcome is not None, "welcome did not appear") + self.set_wayland() + + # Preseed the wizard defaults so the run is bounded (safe kernel, no + # desktop) while the wizard, validation, AI gate and ERASE confirmation + # remain the real graphical path. + self.shell( + f"curl -fsSL {SERVE_URL}/test.conf -o /tmp/gui-install.conf && " + "sudo -n install -D -m 0644 /tmp/gui-install.conf /etc/phoebus/install.conf && " + "echo PRESEED-$(printf DONE)", + "PRESEED-DONE", timeout=60, label="preseed-config", + ) + # Start the loopback relay to the host OpenCode server. + self.shell( + f"curl -fsSL {SERVE_URL}/oc-forward.py -o /tmp/oc-forward.py && " + f"chmod 755 /tmp/oc-forward.py && " + f"setsid python3 /tmp/oc-forward.py {OC_PORT} 10.0.2.2 {OC_TARGET_PORT} " + f">/tmp/oc-forward.log 2>&1 < /dev/null & echo FWD-$(printf START)", + "FWD-START", timeout=60, label="forwarder-start", + ) + ready = self.poll_shell( + f"curl -s -m 5 -o /dev/null -w 'HEALTH=%{{http_code}}' " + f"http://127.0.0.1:{OC_PORT}/global/health", + r"HEALTH=(200|401)", timeout=60, label="forwarder-ready", + ) + self.results.assert_true( + "opencode-reachable-from-guest", ready is not None, + "the guest relay could not reach the OpenCode server", + ) + + # Launch the installer from the welcome action. + self.sendkey("ret") + opened = self.poll_shell( + "echo INST=$(pgrep -fc 'quickshell.*phoebus-install' 2>/dev/null || echo 0)", + r"INST=([1-9][0-9]*)", timeout=int(os.environ.get("INSTALLER_OPEN_TIMEOUT", "90")), + label="launcher-opens-installer", + ) + self.results.assert_true("launcher-opens-installer", opened is not None, + "welcome action did not open the installer") + time.sleep(BACKEND_SETTLE) + self.shell( + "pkill -f 'quickshell.*phoebus-wel[c]ome' || true; sleep 2; echo CLOSED", + "CLOSED", timeout=30, label="close-welcome", + ) + + # Welcome -> language -> network -> AI. + self.sendkey("ret") + time.sleep(2) + self.sendkey("ctrl-right") + time.sleep(2) + self.sendkey("ctrl-right") + time.sleep(3) + state = self._frontend_state() + self.results.assert_true("gui-install-ai-step", state is not None and state["step"] == 3, + f"AI step not reached: {state}") + self.shot("gi-01-ai", "AI step", "Return, Ctrl+Right twice", "AI connection step") + + # Select OpenCode and connect through the UI. + for _ in range(OC_TAB_TO_CHIP): + self.sendkey("tab") + time.sleep(0.3) + self.sendkey("ret") + time.sleep(1) + self._tabs(1) # chip -> server + self._gui_type(f"http://127.0.0.1:{OC_PORT}") + self.sendkey("tab") # server -> password + self.sendkey("tab") # password -> reveal + self._tabs(1) # reveal -> provider + self._gui_type(OC_PROVIDER) + self._tabs(1) # provider -> model + self._gui_type(OC_MODEL) + self.sendkey("tab") # model -> load + self.sendkey("tab") # load -> Test + self.sendkey("ret") + tested = self.wait_state(lambda s: s["aiTested"], timeout=300) + self.results.assert_true("gui-install-ai-tested", tested is not None, + "Test connection did not succeed") + self.sendkey("tab") # Test -> Connect + self.sendkey("ret") + connected = self.wait_state(lambda s: s["aiConnected"], timeout=240) + self.results.assert_true("gui-install-ai-connected", connected is not None, + f"Connect and validate failed: {connected}") + applied = connected["aiApplied"] if connected else 0 + self.results.assert_true( + "gui-install-ai-reviewed", self._accept_ai_review(applied), + "the AI review could not be accepted", + ) + self.shot("gi-02-ai-reviewed", "AI reviewed", "Accept changes", "review accepted") + + # Destination disk: pick the first selectable disk. + self.sendkey("ctrl-right") + time.sleep(3) + self.sendkey("tab") + time.sleep(0.5) + self.sendkey("ret") + time.sleep(1) + state = self._frontend_state() + self.results.assert_true( + "gui-install-disk-selected", state is not None and state["disk"] != "", + f"no destination disk was selected: {state}", + ) + self.shot("gi-03-disk", "disk selected", "Tab and Return on the first disk", + "a destination disk is selected") + + # Regression: re-checking network readiness from the network step must + # not reset the wizard or clear the chosen disk, and unrelated + # navigation must preserve the validated AI connection. + selected = state["disk"] + self.sendkey("ctrl-left") # disk -> AI + time.sleep(1.5) + self.sendkey("ctrl-left") # AI -> network + time.sleep(1.5) + before = self._frontend_state() + self.results.assert_true( + "back-nav-preserves-ai", before is not None and before["aiConnected"], + f"back-navigation lost the AI validation: {before}", + ) + self.sendkey("ret") # Re-check (focused when the network step opens) + time.sleep(4) + after = self._frontend_state() + self.results.assert_true( + "readiness-refresh-preserves-wizard", + after is not None and after["step"] == 2 and after["disk"] == selected, + f"re-check reset the wizard or cleared the disk: before={before} after={after}", + ) + # Walk forward again; the disk selection must still be present. + self.sendkey("ctrl-right") # network -> AI + time.sleep(2) + self.sendkey("ctrl-right") # AI -> disk + time.sleep(3) + state = self._frontend_state() + self.results.assert_true( + "disk-survives-backtrack", + state is not None and state["step"] == 4 and state["disk"] == selected, + f"the disk selection did not survive backtracking: {state}", + ) + + # Account and encryption. + self.sendkey("ctrl-right") + time.sleep(2) + state = self._frontend_state() + self.results.assert_true("gui-install-account-step", state is not None and state["step"] == 5, + f"account step not reached: {state}") + self._tabs(3) # full name -> username -> computer name -> password + self._gui_type(USER_PW) + self._tabs(2) # reveal -> confirm password + self._gui_type(USER_PW) + self._tabs(2) # reveal -> passphrase + self._gui_type(LUKS_PW) + self._tabs(2) # reveal -> confirm passphrase + self._gui_type(LUKS_PW) + self.shot("gi-04-account", "account and encryption", "typed credentials", + "password and passphrase entered") + + # Review and ERASE. The review step focuses the ERASE field. + self.sendkey("ctrl-right") + time.sleep(4) + state = self._frontend_state() + self.results.assert_true("gui-install-review-step", state is not None and state["step"] == 6, + f"review step not reached: {state}") + self.shot("gi-05-review", "review and confirmation", "review shown", + "backend facts, plan and ERASE confirmation") + self._gui_type("ERASE") + self.sendkey("tab") # the confirmation toggle + time.sleep(0.4) + confirmed = self._frontend_state() + # The toggle responds to Return and Space; QEMU names Space `spc`. + for key in ("ret", "spc"): + if confirmed is not None and confirmed["confirm"]: + break + self.sendkey(key) + time.sleep(0.5) + confirmed = self._frontend_state() + if confirmed is None or not confirmed["confirm"]: + self.results.fail( + "gui-install-erase-confirmed", + f"the confirmation toggle was not ticked: {confirmed}", + ) + return + self.results.pass_("gui-install-erase-confirmed") + self.sendkey("ctrl-right") # authorize and install + self.shot("gi-06-installing", "installing", "Ctrl+Right on review", + "the installation has started") + + done = self.wait_state( + lambda s: s["phase"] in ("done", "failed"), + timeout=INSTALL_TIMEOUT, + ) + if done is None: + self.results.fail("gui-install-completes", "the wizard did not report completion") + return + self.results.assert_true( + "gui-install-completes", done["phase"] == "done", + f"the installer reported failure: {done}", + ) + self.shot("gi-07-complete", "completion", "installation finished", + "the completion screen is shown") + if done["phase"] == "done": + self.results.pass_("gui-install-journey") + # Power off cleanly so the installed disk is flushed for the boot mode. + self.shell("sudo -n systemctl poweroff >/dev/null 2>&1 || true; echo POW", + "POW", timeout=60, label="poweroff") + try: + self.child.expect(pexpect.EOF, timeout=300) + except (pexpect.TIMEOUT, pexpect.EOF): + pass + def _installer_alive(self) -> bool: assert self.child is not None self.child.sendline( @@ -862,10 +1239,10 @@ class Driver: def main() -> int: mode = sys.argv[1] if len(sys.argv) > 1 else "" - if mode not in ("gui", "opencode", "install", "boot"): + if mode not in ("gui", "opencode", "gui-install", "install", "boot"): print(__doc__) return 2 - if mode in ("install", "boot") and not DISKS: + if mode in ("install", "boot", "gui-install") and not DISKS: print("error: DISK/DISKS must name a disposable qcow2 image", file=sys.stderr) return 2 try: