diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 9106090..0d1dd69 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -65,6 +65,14 @@ Pure, non-privileged logic with no external commands except reading `/proc`, `FastInstallation`, `NativeIntegration`, `ApplicationIsolation`), project tool environments, and candidate selection. - `update` — unified multi-source update models across all supported package lanes. +- `fastinstall` — fast default installation with user-controlled source + builds: the prebuilt delivery set and its review rendering + (`fast_default_deliveries`, `delivery_summary`), the supported + "build from source" table (`SOURCE_CONVERSIONS`, Brave excluded with + `brave_source_status`), the opt-in tuned-kernel plan, the + preference-neutrality guard (`assert_no_installer_preference`), the + fail-closed binary check (`require_binary_capable`), and the measured + installation figures (`InstallMetrics`). - `proactive` — quiet proactive alert models, categories, and deferred schedules. - `brand` — the visual identity (palette tokens, sun emblem, wordmark, wallpaper) as deterministic SVG/tokens shared by the QML frontend. @@ -227,5 +235,9 @@ application launched from the desktop menu, keybinding, or launcher: or for a different execution backend. - `InstallStep` — add stages in `plan.rs` and handle them in `orchestrate.rs`. - `SystemAction` — add closed verbs; the policy engine classifies and previews - them, and the broker executes them after approval. + them, and the broker executes them after approval. Recent verbs: + `ConvertToSource { app }` (reviewed rebuild of a fast-default app from + its maintained source; builds before removing; Brave refused with its + reason) and `BuildTunedKernel { make_default }` (separate BLS entry, + fallback kept, default only after a test boot). diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index a71be34..ced9f53 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -3,6 +3,72 @@ All notable changes are recorded here. The authoritative history is `git log`; this file is the curated, human-readable summary. +## Unreleased — Fast defaults with user-controlled source builds + +- **Fast default installation.** The Mango profile now installs + `www-client/firefox-bin` and `app-office/libreoffice-bin` (maintained + stable Gentoo binary redistributions, signature verification preserved). + A requested `-bin` that cannot come from a signed binary fails closed with + the exact reason instead of silently falling back to a source build + (`fastinstall::require_binary_capable`). Calibre + (`com.calibre_ebook.calibre`), GIMP (`org.gimp.GIMP`) and Flatseal + (`com.github.tchx84.Flatseal`) install as system-wide Flatpaks from + Flathub **in the target** (never on the live host), with fail-closed + verification of apps, launchers, exports and a recorded manifest + (`var/lib/phoebus/flatpaks-installed`); Calibre/GIMP Portage copies are + gone so no duplicates are installed. `sys-kernel/gentoo-kernel-bin` stays + the single generic install/recovery kernel (no second generic kernel). + Brave's stable pinned overlay integration is unchanged. The plan review + and progress log name the delivery method and expected work + (`fastinstall::delivery_summary`); the orchestrator records measured + per-stage/total time plus best-effort download/installed/peak-disk figures + (`var/lib/phoebus/install-metrics.txt`, unmeasured reported as such). +- **Preference neutrality.** The installer's speed choices set no permanent + system-wide or personal lane preference (`assert_no_installer_preference`); + later `choose`/`install` resolve from live candidate evidence plus + explicit user choices, with source, version, build cost and tradeoffs + shown as before. +- **User-initiated source builds.** New typed actions `convert_to_source` + (`sys build from source --legacy`) for Firefox, LibreOffice, + Calibre and GIMP, and `build_tuned_kernel` (`sys build tuned kernel + --legacy`): blockers/dependencies checked via the reviewed pretend plan, + the source is built (`--buildpkgonly`) before the working copy is touched, + user data and desktop defaults are preserved, a failed build leaves the + working application installed, and Brave is refused with its reason (no + trustworthy maintained source route). Both carry the full review (exact + packages, expected time, temporary disk, power/network, approval) in + `sys` previews and require explicit approval before the broker runs. The + tuned kernel starts from the proven distribution configuration, gets a + separate BLS entry, is test-booted before it can become default, and + always keeps `gentoo-kernel-bin` as the known-good fallback. +- **Installed first-login welcome.** `phoebus-welcome` (Mango/DMS styled + QML): explains the prebuilt defaults, offers the three opt-in paths + (source builds, tuned kernel, keep-and-finish defaulting to keeping the + working system), runs once per user via `welcome-seen`, stays reopenable + from the launcher/settings, supports keyboard navigation and small + displays, and never blocks login. DMS upstream first-run dialogs are + seeded suppressed via `/etc/skel` so users see one welcome. The live + ISO's "Install Phoebus OS" welcome remains live-only. +- **Seamless Flatpak desktop.** Existing Wayland portals plus extended + defaults (`mimeapps.list`: Nemo for directories, Firefox for web links, + Zathura for PDF, Calibre Flatpak for e-books, GIMP Flatpak for images); + upstream sandbox permissions respected with no broad overrides + (`flatpak_narrow_overrides` is intentionally empty); Flatseal ships for + inspection without forcing setup. +- **Tests.** 757 Rust tests pass (was 736): new coverage for delivery set, + preference neutrality, fail-closed `-bin`, source-conversion table, + tuned-kernel fallback, target-only Flatpak install/verification, welcome + provisioning, metrics report, and the `sys` acceptance script gains 4 + cases (non-root privilege refusals + root-safe Brave/unknown refusals). + Gates: `cargo fmt --check`, `clippy --workspace --all-targets -- -D + warnings`, release build, `test_vmsafety.py` 18/18, shellcheck clean. +- **Not VM-verified this session.** No fresh ISO was built and no + disposable install/boot ran (session-time blocker; host is ready: + `make doctor` 20 ok, 104 GiB free). The new install path, installed + package identities, Flatpaks, welcome, graphical launches, workflows, + source-conversion and tuned-kernel journeys await the disposable VM + procedure in `docs/VM-BOOT-VERIFICATION.md`. + ## 2026-09-26 — Workstation experience (apps, shell, AI handoff, assistant) - **Mango workstation defaults.** The Mango profile now installs the full diff --git a/docs/HANDOFF.md b/docs/HANDOFF.md index b1027a5..8953ab8 100644 --- a/docs/HANDOFF.md +++ b/docs/HANDOFF.md @@ -3,6 +3,27 @@ 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. +- **Fast-defaults session (2026-09-26, IMPLEMENTED + UNIT-TESTED, VM NOT RUN):** + Firefox/LibreOffice as `-bin`, Calibre/GIMP/Flatseal as target-only + system-wide Flatpaks (no Portage duplicates), single generic kernel, + delivery section in plan review + progress log, install metrics hooks, + preference neutrality guard, `convert_to_source` (Firefox/LibreOffice/ + Calibre/GIMP; Brave refused with reason) + `build_tuned_kernel` + (separate BLS, fallback kept, default only after test boot) typed actions + with full reviews through the existing approval/broker path, installed + once-per-user reopenable non-blocking welcome + DMS skel seed, portal/MIME + defaults with no sandbox overrides. Gates: fmt, clippy -D, 757 tests + (was 736), release build, vmsafety 18/18, shellcheck clean. NO new ISO, + NO install/boot this session — session-time blocker (host ready: doctor + 20 ok, 104 GiB free); all VM gates NotRun with exact unblock in STATUS. + Next: build ISO, disposable 80 GiB install + detached boot, 37-case + acceptance, graphical/file/device/source/tuned gates per + VM-BOOT-VERIFICATION.md. +- **Interface contract (unchanged):** ordinary requests use AI; only explicit + `--legacy` selects deterministic handling; source flags constrain the AI and + never bypass it; a missing model stops the workflow and offers the exact + `--legacy` command without executing it. + - **Workstation experience session (2026-09-26, IMPLEMENTED + UNIT-TESTED, VM BLOCKED):** Mango workstation atoms (22 apps, exact, no substitute; Kitty kept, Nemo default, CUPS local-only, sshd installed/disabled), Brave stable scoped diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index 63cf5e3..225eeb1 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -11,7 +11,7 @@ more interesting. Status vocabulary: **Done**, **Partial**, **Next**, **Later**. | 4 | Port the destructive backend | Done | `phoebus-executor` (storage, LUKS2, Btrfs, Portage, boot, users, services) | | 5 | **Rust VM boot parity** | Done | Full encrypted UEFI install + boot, zero failed units, 10.7 s | | 6 | Finish the desktop | Partial | **Mango + DankMaterialShell is the canonical desktop**; greetd login; the live ISO boots the branded welcome + graphical installer and was verified in a graphical VM; installed-desktop verification pending | -| 7 | Finish Flatpak | Partial | `flatpak 1.18.1` installed, flathub configured; bounded typed `flatpak_*` actions added; no app installed yet | +| 7 | Finish Flatpak | Partial | `flatpak 1.18.1` installed, flathub configured; bounded typed `flatpak_*` actions added; fast defaults install Calibre/GIMP/Flatseal system-wide from Flathub in the target (unit-tested, fail-closed verification; VM launch/MIME/update checks not run) | | 8 | Instrument source/binary policy | Done | measured compile times harvested from `emerge.log` (326 entries); resolved-effect previews added | | 9 | Background update preparation | Partial | distfile fetch VM-verified; `--buildpkgonly` skipped while deps need merging (recorded Ready); activation explicit | | 10 | Snapshots / rollback | Done (normal `sys undo`); recovery-entry boot manual | normal `sys undo` acceptance PASSED on a fresh disposable clone (`serial-rollback-20260926T030237Z-912f6386` PASS=11 FAIL=0: DB changed then restored, root marker gone, `/home` survives, boot running); retention + free-space gate unit-tested; selecting the Phoebus Recovery (known-good snapshot) BLS entry offline with no network/model is a distinct manual acceptance gate (see `docs/VM-BOOT-VERIFICATION.md`), separate from `sys undo` | diff --git a/docs/STATUS.md b/docs/STATUS.md index 1017a89..b40da79 100644 --- a/docs/STATUS.md +++ b/docs/STATUS.md @@ -77,6 +77,13 @@ Booting that recovery entry offline remains a manual gate. | Desktop session script (socket wait, polkit, cleanup) | yes | yes | functional test (stubs) | no | | PipeWire/WirePlumber | yes | no | headless (`wpctl`) | no | | Flatpak + flathub | yes | no | installed + remote | no | +| Fast-default Flatpaks (Calibre/GIMP/Flatseal, system-wide, target-only) | yes | yes (install/verify/provisioning; fail-closed on missing app) | no (launch, icons, MIME, updates after reboot not run) | no | +| Fast `-bin` defaults (firefox-bin/libreoffice-bin, fail-closed) | yes | yes (atoms, policy, binary-capability refusal) | no (installed identity not verified in a VM) | no | +| Single generic kernel default (no second generic kernel) | yes | yes (guard + tuned path keeps the fallback) | yes (existing boot path unchanged) | no | +| User-initiated source builds (`convert_to_source`) | yes | yes (table, review, build-before-remove, Brave/unknown refusals) | no (no conversion journey run in a VM) | no | +| Tuned-kernel build (`build_tuned_kernel`, separate BLS, fallback kept) | yes | yes (refusal without fallback, entry creation, default never blind-switched) | no (no build/boot-test in a VM) | no | +| Installed first-login welcome (once per user, reopenable, non-blocking) | yes | yes (assets, launcher, autostart, QML guards, DMS seed) | no (first login + graphical checks not run) | no | +| Install metrics (time, download, peak disk, installed size) | yes | yes (report rendering; orchestration hooks) | no (no measured install yet) | no | | XWayland / polkit agent / kitty / wofi | yes | no | installed, not launched | no | | Package policy + measured history | yes | yes | yes (326 entries) | no | | Background update preparation | yes | yes | yes (fetch; buildpkgonly skipped) | no | @@ -197,6 +204,32 @@ Booting that recovery entry offline remains a manual gate. | Startup system check (blur/PPD/matugen/cava, truthful summary) | yes | yes (4-check evaluation + summary wording) | no (recheck after reboot NotRun; needs PPD D-Bus + DMS integration) | no | | Assistant dark default + light mode + responsive + token drift guard | yes | yes (palette/aliases, drift test, layout guards) | no (graphical VM at 1024×768/1280×720/scaled NotRun) | no | +## Fast-defaults session (2026-09-26): what was proven and what was not + +- Implemented + unit-tested in this session (757 Rust tests, was 736): + `-bin` fast defaults, target-only system-wide Flatpaks with fail-closed + verification, single generic kernel guard, preference neutrality, + `convert_to_source` / `build_tuned_kernel` typed actions with full + reviews, installed welcome + DMS seed, portal/MIME defaults, install + metrics hooks, plan-review delivery section, and 4 new `sys` acceptance + cases (script now covers 37 documented cases). +- Quality gates green: `cargo fmt --check`, `clippy --workspace --all-targets + -- -D warnings`, release build, `test_vmsafety.py` 18/18, shellcheck clean. +- **Not built, not installed, not booted in this session.** No fresh ISO was + built and no disposable qcow2 install/boot ran — a session-time blocker, + not a host blocker (`make doctor`: 20 ok, 0 warnings; 104 GiB free). + The requested verifications (installed `-bin` identities, system-wide + Flatpaks + manifest, first-login welcome, graphical Calibre/GIMP launches, + file/device workflows, normal + offline recovery boots, one + source-conversion journey, one tuned-kernel build + test boot, measured + time/disk figures) are **NotRun**. Exact unblock: build the ISO + (`installer/live/build.sh`), install to a disposable 80 GiB qcow2 with + network (`serial-driver.py install`), boot detached (`serial-driver.py + boot`), run `sys-acceptance.sh` (now 37 documented cases) plus the + graphical/file/device/source/tuned gates in + `docs/VM-BOOT-VERIFICATION.md`; never touch `/dev/*`, never commit the + ISO/images/transcripts/secrets. + ## Workstation session (2026-09-26): what was proven and what was not - Implemented + unit-tested in this session (736/736 Rust tests): workstation diff --git a/docs/SYS.md b/docs/SYS.md index c8d9dfb..576ecd5 100644 --- a/docs/SYS.md +++ b/docs/SYS.md @@ -149,6 +149,8 @@ sys --action '{"action":"check_backend","backend":"snap"}' | --- | --- | --- | | `install vim` / `add vim` | `install_package` | mutate | | `remove vim` / `uninstall vim` | `remove_package` | mutate | +| `build firefox from source` | `convert_to_source` | mutate (High risk, protective snapshot) | +| `build tuned kernel` | `build_tuned_kernel` | mutate (High risk, protective snapshot) | | `search firefox` / `find firefox` | `search_packages` | read | | `update` | `update_system` | mutate | | `prepare updates` | `prepare_updates` | mutate | @@ -523,6 +525,10 @@ with no network and no model. | 31 | Non-root depclean | `sys depclean --legacy` (non-root) | requires root, nonzero | | 32 | Non-root apply updates | `sys apply updates --legacy` (non-root) | requires root, nonzero | | 33 | Non-root cache cleanup | `sys clean cache --legacy` (non-root) | requires root, nonzero | +| 34 | Non-root source build | `sys --legacy --action '{"action":"convert_to_source","app":"firefox"}'` (non-root) | requires root, nonzero | +| 35 | Non-root tuned kernel | `sys build tuned kernel --legacy` (non-root) | requires root, nonzero | +| 36 | Brave source refusal (root, no mutation) | `--legacy --action '{"action":"convert_to_source","app":"brave"}'` (root) | nonzero, "no trustworthy source route"; refused before approval/commands | +| 37 | Unknown source refusal (root, no mutation) | `--legacy --action '{"action":"convert_to_source","app":"definitely-not-an-app-xyz"}'` (root) | nonzero, "no supported source build" | ### Mutating acceptance cases (disposable VM only) @@ -531,7 +537,7 @@ When `SYS_ACCEPTANCE_MUTATE=1` is set in the disposable VM: - `mutate-remove`: `sys -y remove app-misc/hello --legacy` uninstalls cleanly. - `mutate-history`: `sys history --legacy` confirms both install and remove are logged. -The read-only and failure acceptance cases (33, including the +The read-only and failure acceptance cases (37, including the personal-preference case and the catalogue group) are exercised by the test suite (`installer/tests/vm/sys-acceptance.sh`); the broker approval/replay regression is covered by `phoebus-installer` unit tests. Host unit and diff --git a/docs/VM-BOOT-VERIFICATION.md b/docs/VM-BOOT-VERIFICATION.md index 0bca997..360c24c 100644 --- a/docs/VM-BOOT-VERIFICATION.md +++ b/docs/VM-BOOT-VERIFICATION.md @@ -3,6 +3,29 @@ This records the first successful end-to-end install and boot of Phoebus OS against a disposable qcow2 disk. No physical disk was ever touched. +## 2026-09-26 fast-defaults session — no VM run (BLOCKED on session time) + +- No fresh ISO was built and no disposable install/boot ran in this session. +- Blocker is session time, not the host: `make doctor` reports 20 ok, + 0 warnings, 104 GiB free (ISO build needs ≥20; the Mango target needs + 60 minimum, 80 recommended). A full install previously took ~165 min, + which does not fit this session. +- Blocked gates (all NotRun): installed `-bin` identities + (`www-client/firefox-bin`, `app-office/libreoffice-bin` VDB records), + system-wide Flatpaks + `flatpaks-installed` manifest, first-login + welcome, graphical Calibre/GIMP launches, Nemo/browser-link/MIME tasks, + drag-and-drop/clipboard/printing, Calibre removable-media access, + normal boot + offline generic-kernel recovery, one source-conversion + journey (e.g. Firefox `--buildpkgonly` → swap → verify), one tuned-kernel + build + separate-entry test boot, measured time/disk figures, and the + 37-documented-case `sys` acceptance re-run. +- Unblock: build the ISO from the fast-defaults commit + (`installer/live/build.sh`; record commit + build ID + SHA-256); install + to a disposable 80 GiB qcow2 with network (`serial-driver.py install`); + boot detached (`serial-driver.py boot`); run `sys-acceptance.sh` plus + the graphical/file/device/source/tuned gates below. Never point DISK at + `/dev/*`; never commit the ISO/images/transcripts/secrets. + ## 2026-09-26 workstation session — no VM run (BLOCKED) - No fresh ISO was built and no disposable install/boot ran in this session. diff --git a/installer-rs/crates/phoebus-core/src/action.rs b/installer-rs/crates/phoebus-core/src/action.rs index e00de58..ee506c2 100644 --- a/installer-rs/crates/phoebus-core/src/action.rs +++ b/installer-rs/crates/phoebus-core/src/action.rs @@ -301,6 +301,25 @@ pub enum SystemAction { atom: String, }, CustomEbuildList, + // ------------------------------------------------------------------ + // User-initiated source builds (fast defaults are install-time only). + // ------------------------------------------------------------------ + /// Replace a prebuilt fast-default application with its maintained + /// source alternative after a reviewable plan. The working copy stays + /// installed until the new build verifies; a failed build leaves it in + /// place. Brave has no supported target (see + /// `fastinstall::brave_source_status`). + ConvertToSource { + app: String, + }, + /// Build a kernel tuned for this machine from the proven distribution + /// configuration. Creates a separate BLS entry, boot-tests it before + /// offering to make it default, and always keeps `gentoo-kernel-bin`. + BuildTunedKernel { + /// Make the tuned kernel the default only after a verified boot. + #[serde(default)] + make_default: bool, + }, } impl SystemAction { @@ -481,6 +500,17 @@ impl SystemAction { format!("remove the custom ebuild package {atom}") } SystemAction::CustomEbuildList => "list Phoebus-managed custom ebuilds".to_string(), + SystemAction::ConvertToSource { app } => { + format!("build {app} from source (reviewed; keeps the working copy until verified)") + } + SystemAction::BuildTunedKernel { make_default } => { + if *make_default { + "build a tuned kernel and make it default after a verified boot (keeps generic fallback)".to_string() + } else { + "build a tuned kernel as a separate boot entry (keeps generic fallback)" + .to_string() + } + } } } @@ -538,7 +568,9 @@ impl SystemAction { | SystemAction::Depclean | SystemAction::Undo { .. } | SystemAction::CustomEbuildInstall { .. } - | SystemAction::CustomEbuildRemove { .. } => Risk::High, + | SystemAction::CustomEbuildRemove { .. } + | SystemAction::ConvertToSource { .. } + | SystemAction::BuildTunedKernel { .. } => Risk::High, } } @@ -634,6 +666,8 @@ impl SystemAction { | SystemAction::CustomEbuildInstall { .. } | SystemAction::CustomEbuildRemove { .. } | SystemAction::CustomEbuildList => Some(Backend::CustomEbuild), + SystemAction::ConvertToSource { .. } => Some(Backend::PortageSource), + SystemAction::BuildTunedKernel { .. } => Some(Backend::PortageSource), _ => None, } } @@ -905,6 +939,17 @@ impl SystemAction { } } SystemAction::CustomEbuildList => Ok(()), + SystemAction::ConvertToSource { app } => { + let app = app.trim(); + if app.is_empty() || app.len() > 64 || app.starts_with('-') { + return Err(format!("invalid application name: {app}")); + } + // Support is resolved at planning time so the refusal reason + // (including Brave's missing source route) is reported with + // the reviewed plan instead of a bare parse failure. + Ok(()) + } + SystemAction::BuildTunedKernel { .. } => Ok(()), } } } @@ -1428,6 +1473,29 @@ fn parse_natural_raw(text: &str) -> Option { return Some(SystemAction::CustomEbuildList); } + // User-initiated source builds. The fast install defaults never imply a + // preference; these phrases explicitly request a source build and are + // reviewed before the privileged broker runs. + if t == "build tuned kernel" || t == "build a tuned kernel" || t == "tune kernel" { + return Some(SystemAction::BuildTunedKernel { + make_default: false, + }); + } + for prefix in ["build ", "compile "] { + if let Some(rest) = rest(prefix) { + let rest = rest.trim(); + for suffix in [" from source", " from sources"] { + if let Some(app) = rest.strip_suffix(suffix).map(str::trim) { + if !app.is_empty() { + return Some(SystemAction::ConvertToSource { + app: app.to_string(), + }); + } + } + } + } + } + // Hardware-aware source choice: `choose firefox`, `choose firefox as a gui // app`, `choose firefox via flatpak`. if let Some(rest) = rest("choose ").or_else(|| rest("select source ")) { @@ -2064,6 +2132,62 @@ mod tests { assert!(system.requires_root()); } + #[test] + fn source_build_phrases_are_explicit_and_fail_closed() { + // Supported conversions parse, validate, and are high-risk mutations + // bound to the Portage source lane. + for app in ["firefox", "libreoffice", "calibre", "gimp"] { + let action = parse_natural(&format!("build {app} from source")) + .unwrap_or_else(|| panic!("`build {app} from source` did not parse")); + assert_eq!(action, SystemAction::ConvertToSource { app: app.into() }); + assert!(action.validate().is_ok(), "{app}"); + assert!(action.is_mutating()); + assert!(action.requires_root()); + assert_eq!(action.risk(), Risk::High); + assert_eq!(action.backend(), Some(Backend::PortageSource)); + } + assert_eq!( + parse_natural("compile gimp from source"), + Some(SystemAction::ConvertToSource { app: "gimp".into() }) + ); + assert_eq!( + parse_natural("build tuned kernel"), + Some(SystemAction::BuildTunedKernel { + make_default: false + }) + ); + // Brave has no trustworthy source route: the phrase still parses so + // the refusal carries the reason (resolve_effects fails closed with + // it before any approval or command). + let brave = parse_natural("build brave from source").expect("parses"); + assert_eq!( + brave, + SystemAction::ConvertToSource { + app: "brave".into() + } + ); + assert!(brave.validate().is_ok()); + // Unknown applications parse but resolve to no plan, never guessed. + let unknown = parse_natural("build frobnicate-os from source").expect("parses"); + assert!(unknown.validate().is_ok()); + // JSON round-trips for both new actions. + let json = parse_action(r#"{"action":"convert_to_source","app":"firefox"}"#).unwrap(); + assert_eq!( + json, + SystemAction::ConvertToSource { + app: "firefox".into() + } + ); + let kernel = + parse_action(r#"{"action":"build_tuned_kernel","make_default":true}"#).unwrap(); + assert_eq!( + kernel, + SystemAction::BuildTunedKernel { make_default: true } + ); + assert!(kernel.validate().is_ok()); + assert!(kernel.is_mutating()); + } + #[test] fn selection_validators_are_strict() { assert!(valid_snap_name("thunderbird")); diff --git a/installer-rs/crates/phoebus-core/src/fastinstall.rs b/installer-rs/crates/phoebus-core/src/fastinstall.rs new file mode 100644 index 0000000..55a2078 --- /dev/null +++ b/installer-rs/crates/phoebus-core/src/fastinstall.rs @@ -0,0 +1,424 @@ +//! Fast default installation with user-controlled source builds. +//! +//! The installer shortens installation with prebuilt applications and a +//! generic kernel. These choices accelerate the initial install only: they +//! never create a permanent system-wide or personal preference for `-bin`, +//! Portage source, or Flatpak (see [`assert_no_installer_preference`]). +//! +//! - [`delivery_summary`] names the chosen delivery method and expected +//! download/build work shown in the review and progress UI. +//! - [`SOURCE_CONVERSIONS`] lists supported user-initiated "build from +//! source" targets; Brave is intentionally absent (see +//! [`brave_source_status`]). +//! - [`tuned_kernel_plan`] describes the opt-in tuned-kernel build that +//! keeps `gentoo-kernel-bin` as the known-good fallback. +//! - [`InstallMetrics`] records measured installation time, download +//! volume, peak disk use and final installed size. + +use std::collections::HashMap; + +/// How an application is delivered by the fast default install. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum DeliveryMethod { + /// Maintained stable Gentoo binary redistribution (`-bin`) via Portage + /// with signature verification. + PortageVendorBinary, + /// System-wide Flatpak from Flathub, installed in the target. + FlatpakSystem, + /// Generic prebuilt kernel (`sys-kernel/gentoo-kernel-bin`). + GenericKernel, + /// Ordinary Portage package selected by policy (unchanged behaviour). + PolicySelected, +} + +/// One row of the installer review: what is installed, how, and what work +/// it costs. Estimates are labelled as such; compilation is never claimed +/// to be faster or worth its cost. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct DeliveryEntry { + pub name: &'static str, + pub identity: &'static str, + pub method: DeliveryMethod, + pub expected_work: &'static str, +} + +/// The fast default delivery set, in review order. +pub fn fast_default_deliveries() -> Vec { + vec![ + DeliveryEntry { + name: "Firefox", + identity: "www-client/firefox-bin", + method: DeliveryMethod::PortageVendorBinary, + expected_work: "download ~120 MiB prebuilt binary, no local compile", + }, + DeliveryEntry { + name: "LibreOffice", + identity: "app-office/libreoffice-bin", + method: DeliveryMethod::PortageVendorBinary, + expected_work: "download ~250 MiB prebuilt binary, no local compile", + }, + DeliveryEntry { + name: "Calibre", + identity: "com.calibre_ebook.calibre (Flathub, system)", + method: DeliveryMethod::FlatpakSystem, + expected_work: "download Flatpak runtime + app, no local compile", + }, + DeliveryEntry { + name: "GIMP", + identity: "org.gimp.GIMP (Flathub, system)", + method: DeliveryMethod::FlatpakSystem, + expected_work: "download Flatpak app, no local compile", + }, + DeliveryEntry { + name: "Flatseal", + identity: "com.github.tchx84.Flatseal (Flathub, system)", + method: DeliveryMethod::FlatpakSystem, + expected_work: "download Flatpak app, no local compile", + }, + DeliveryEntry { + name: "Kernel", + identity: "sys-kernel/gentoo-kernel-bin (generic)", + method: DeliveryMethod::GenericKernel, + expected_work: "download prebuilt kernel + initramfs, no local compile", + }, + ] +} + +/// Human rendering of the delivery set for the review and progress UI. +pub fn delivery_summary() -> String { + let mut o = String::new(); + o.push_str("Fast defaults (prebuilt, verified; no local compile):\n"); + for d in fast_default_deliveries() { + let method = match d.method { + DeliveryMethod::PortageVendorBinary => "Portage -bin (signed)", + DeliveryMethod::FlatpakSystem => "Flatpak system (Flathub)", + DeliveryMethod::GenericKernel => "generic kernel (signed)", + DeliveryMethod::PolicySelected => "policy selected", + }; + o.push_str(&format!( + " {}: {} [{}] — {}\n", + d.name, d.identity, method, d.expected_work + )); + } + o.push_str("These choices shorten installation only and set no permanent preference.\n"); + o +} + +/// A supported user-initiated "build from source" conversion. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct SourceConversion { + /// Lowercase application key used by the UI/CLI (`firefox`, ...). + pub app: &'static str, + /// What the fast install put on disk. + pub installed_from: &'static str, + /// The maintained source alternative that replaces it. + pub source_atom: &'static str, + /// Honest expected cost. Never promises a noticeable speedup. + pub expected_time: &'static str, + pub temp_disk: &'static str, +} + +/// Supported conversions. Brave is deliberately absent: there is no +/// trustworthy, maintained source route (see [`brave_source_status`]). +pub const SOURCE_CONVERSIONS: &[SourceConversion] = &[ + SourceConversion { + app: "firefox", + installed_from: "www-client/firefox-bin", + source_atom: "www-client/firefox", + expected_time: "typically 30–90 min on 8 vCPUs (measured history varies)", + temp_disk: "needs ~15 GiB temporary build space", + }, + SourceConversion { + app: "libreoffice", + installed_from: "app-office/libreoffice-bin", + source_atom: "app-office/libreoffice", + expected_time: "typically 1–3 h on 8 vCPUs (measured history varies)", + temp_disk: "needs ~20 GiB temporary build space", + }, + SourceConversion { + app: "calibre", + installed_from: "com.calibre_ebook.calibre (Flatpak)", + source_atom: "app-text/calibre", + expected_time: "typically 10–30 min on 8 vCPUs (measured history varies)", + temp_disk: "needs ~8 GiB temporary build space", + }, + SourceConversion { + app: "gimp", + installed_from: "org.gimp.GIMP (Flatpak)", + source_atom: "media-gfx/gimp", + expected_time: "typically 15–45 min on 8 vCPUs (measured history varies)", + temp_disk: "needs ~10 GiB temporary build space", + }, +]; + +/// Look up a supported conversion by application name (case-insensitive; +/// accepts the source atom or Flatpak id as well). +pub fn source_conversion(app: &str) -> Option<&'static SourceConversion> { + let q = app.trim().to_ascii_lowercase(); + SOURCE_CONVERSIONS.iter().find(|c| { + c.app == q + || c.source_atom.to_ascii_lowercase() == q + || c.installed_from.to_ascii_lowercase().contains(&q) + }) +} + +/// Why Brave has no source-build offer. +pub fn brave_source_status() -> &'static str { + "Brave offers no trustworthy, maintained source build: the stable \ + www-client/brave-browser ebuild redistributes upstream's official \ + binary release (verified checksums at install time). Building Chromium \ + from source would not produce Brave, so no source conversion is offered." +} + +/// Review text for a source conversion. Shown before the explicit approval +/// step; the privileged broker only runs after approval. +pub fn source_conversion_review(conv: &SourceConversion) -> String { + let mut o = String::new(); + o.push_str(&format!( + "Build {} from source\n========================\n\n", + conv.app + )); + o.push_str(&format!(" Installed now : {}\n", conv.installed_from)); + o.push_str(&format!(" Source target : {}\n", conv.source_atom)); + o.push_str(&format!(" Expected time : {}\n", conv.expected_time)); + o.push_str(&format!(" Temporary disk: {}\n", conv.temp_disk)); + o.push_str(" Power/network : keep AC power connected; network needed for distfiles.\n"); + o.push_str(" Safety : blockers and dependencies are checked first; user data\n"); + o.push_str(" and desktop defaults are preserved; the working\n"); + o.push_str(" application stays installed until the new build verifies.\n"); + o.push_str(" A failed build leaves the working application installed.\n"); + o.push_str(" Note : compiling is not claimed to produce a noticeable speedup.\n"); + o.push_str(" Approval : explicit approval is required before the broker runs.\n"); + o +} + +/// The opt-in tuned-kernel build plan. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct TunedKernelPlan { + pub base_config: &'static str, + pub source_atom: &'static str, + pub fallback_atom: &'static str, + pub bls_entry: &'static str, +} + +pub fn tuned_kernel_plan() -> TunedKernelPlan { + TunedKernelPlan { + base_config: "Phoebus proven Gentoo distribution-kernel configuration", + source_atom: "sys-kernel/gentoo-kernel", + fallback_atom: "sys-kernel/gentoo-kernel-bin", + bls_entry: "Phoebus (tuned kernel, separate BLS entry)", + } +} + +/// Review text for the tuned-kernel build. +pub fn tuned_kernel_review(plan: &TunedKernelPlan) -> String { + let mut o = String::new(); + o.push_str( + "Build a kernel tuned for this machine\n========================================\n\n", + ); + o.push_str(&format!(" Start from : {}\n", plan.base_config)); + o.push_str(&format!(" Source package: {}\n", plan.source_atom)); + o.push_str(" Tuning : only supported, measurable tuning; required storage,\n"); + o.push_str(" encryption, filesystem, firmware, input and recovery\n"); + o.push_str(" support are retained.\n"); + o.push_str(" Expected work : typically 20–60 min on 8 vCPUs; ~15 GiB temporary space;\n"); + o.push_str(" keep AC power connected.\n"); + o.push_str(&format!( + " Boot entry : {} (separate entry; boot-tested first)\n", + plan.bls_entry + )); + o.push_str(&format!( + " Fallback : {} stays installed and selectable as known-good.\n", + plan.fallback_atom + )); + o.push_str(" Safety : a failed build or failed boot never replaces the working\n"); + o.push_str(" default; a clear route back to the generic kernel remains.\n"); + o.push_str(" Approval : explicit approval is required before the broker runs.\n"); + o +} + +/// Guard: the fast install must not record a permanent preference. +/// +/// The installer may choose `-bin`/Flatpak/generic-kernel for speed, but it +/// must never write a system-wide default or a personal preference pinning +/// those lanes for the named applications. Later `choose`/`install` runs +/// resolve from live candidate evidence plus explicit user choices only. +pub fn assert_no_installer_preference( + system_wide: &HashMap, + personal: &HashMap, +) -> Result<(), String> { + for app in ["firefox", "libreoffice", "calibre", "gimp"] { + if let Some(v) = system_wide.get(app) { + return Err(format!( + "installer must not set a system-wide preference for {app} (found {v})" + )); + } + if let Some(v) = personal.get(app) { + return Err(format!( + "installer must not infer a personal preference for {app} (found {v})" + )); + } + } + Ok(()) +} + +/// Fail closed when a requested `-bin` cannot be installed from a signed +/// binary: show a clear failure (or obtain a reviewed alternative) instead +/// of silently falling back to a lengthy source build. +pub fn require_binary_capable( + atom: &str, + pretend_shows_binary: bool, + detail: &str, +) -> Result<(), String> { + if pretend_shows_binary { + return Ok(()); + } + Err(format!( + "cannot install {atom} as a signed binary ({detail}); refusing to silently \ + build from source — pick a reviewed alternative or build explicitly" + )) +} + +/// Measured installation figures recorded by the orchestrator. +#[derive(Debug, Clone, Default, PartialEq)] +pub struct InstallMetrics { + pub total_seconds: u64, + pub download_mib: u64, + pub peak_disk_mib: u64, + pub installed_mib: u64, + pub per_stage_seconds: Vec<(String, u64)>, +} + +impl InstallMetrics { + pub fn report(&self) -> String { + let mut o = String::new(); + o.push_str("Installation measurements\n"); + o.push_str(&format!( + " Total time : {}\n", + seconds_or_unmeasured(self.total_seconds) + )); + o.push_str(&format!( + " Downloaded : {}\n", + mib_or_unmeasured(self.download_mib) + )); + o.push_str(&format!( + " Peak disk use: {}\n", + mib_or_unmeasured(self.peak_disk_mib) + )); + o.push_str(&format!( + " Installed : {}\n", + mib_or_unmeasured(self.installed_mib) + )); + for (stage, secs) in &self.per_stage_seconds { + o.push_str(&format!(" {stage:<16}: {secs} s\n")); + } + o + } +} + +fn seconds_or_unmeasured(secs: u64) -> String { + if secs == 0 { + "not measured".to_string() + } else { + format!("{secs} s") + } +} + +fn mib_or_unmeasured(mib: u64) -> String { + if mib == 0 { + "not measured".to_string() + } else { + format!("{mib} MiB") + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn delivery_names_every_fast_default_once() { + let ids: Vec<&str> = fast_default_deliveries() + .iter() + .map(|d| d.identity) + .collect(); + assert!(ids.iter().any(|i| i.contains("firefox-bin"))); + assert!(ids.iter().any(|i| i.contains("libreoffice-bin"))); + assert!(ids.iter().any(|i| i.contains("com.calibre_ebook.calibre"))); + assert!(ids.iter().any(|i| i.contains("org.gimp.GIMP"))); + assert!(ids.iter().any(|i| i.contains("Flatseal"))); + assert!(ids.iter().any(|i| i.contains("gentoo-kernel-bin"))); + let text = delivery_summary(); + assert!(text.contains("no local compile")); + assert!(text.contains("no permanent preference")); + } + + #[test] + fn source_conversions_cover_four_apps_and_not_brave() { + for app in ["firefox", "libreoffice", "calibre", "gimp"] { + let conv = source_conversion(app).unwrap_or_else(|| panic!("missing {app}")); + let review = source_conversion_review(conv); + assert!(review.contains(conv.source_atom)); + assert!(review.contains("explicit approval") || review.contains("Approval")); + assert!(review.contains("leaves the working application installed")); + assert!(review.contains("not claimed to produce a noticeable speedup")); + } + assert!(source_conversion("brave").is_none()); + assert!(brave_source_status().contains("no trustworthy")); + } + + #[test] + fn installer_choices_create_no_permanent_preference() { + assert!(assert_no_installer_preference(&HashMap::new(), &HashMap::new()).is_ok()); + let mut sys = HashMap::new(); + sys.insert("firefox".to_string(), "vendor".to_string()); + assert!(assert_no_installer_preference(&sys, &HashMap::new()).is_err()); + let mut per = HashMap::new(); + per.insert("gimp".to_string(), "flatpak".to_string()); + assert!(assert_no_installer_preference(&HashMap::new(), &per).is_err()); + // An explicit user-saved preference for an unrelated app is fine. + let mut ok = HashMap::new(); + ok.insert("htop".to_string(), "source".to_string()); + assert!(assert_no_installer_preference(&HashMap::new(), &ok).is_ok()); + } + + #[test] + fn bin_without_binary_capability_fails_closed() { + assert!(require_binary_capable("www-client/firefox-bin", true, "").is_ok()); + let err = require_binary_capable( + "www-client/firefox-bin", + false, + "USE mismatch with the signed binhost", + ) + .unwrap_err(); + assert!(err.contains("refusing to silently build from source")); + assert!(err.contains("www-client/firefox-bin")); + } + + #[test] + fn tuned_kernel_keeps_bin_fallback() { + let plan = tuned_kernel_plan(); + assert_eq!(plan.fallback_atom, "sys-kernel/gentoo-kernel-bin"); + assert_eq!(plan.source_atom, "sys-kernel/gentoo-kernel"); + let review = tuned_kernel_review(&plan); + assert!(review.contains("never replaces the working")); + assert!(review.contains("route back to the generic kernel")); + assert!(review.contains("explicit approval")); + } + + #[test] + fn metrics_report_renders_measurements() { + let m = InstallMetrics { + total_seconds: 600, + download_mib: 1500, + peak_disk_mib: 20000, + installed_mib: 12000, + per_stage_seconds: vec![("desktop_install".into(), 300)], + }; + let text = m.report(); + assert!(text.contains("600 s")); + assert!(text.contains("desktop_install")); + let empty = InstallMetrics::default().report(); + assert!(empty.contains("not measured")); + } +} diff --git a/installer-rs/crates/phoebus-core/src/lib.rs b/installer-rs/crates/phoebus-core/src/lib.rs index 10bebe4..6f02a18 100644 --- a/installer-rs/crates/phoebus-core/src/lib.rs +++ b/installer-rs/crates/phoebus-core/src/lib.rs @@ -12,6 +12,7 @@ pub mod disk; pub mod effects; pub mod emergelog; pub mod error; +pub mod fastinstall; pub mod hardware; pub mod nvidia; pub mod nvidia_devices; diff --git a/installer-rs/crates/phoebus-core/src/plan.rs b/installer-rs/crates/phoebus-core/src/plan.rs index 3e7e469..147a4e3 100644 --- a/installer-rs/crates/phoebus-core/src/plan.rs +++ b/installer-rs/crates/phoebus-core/src/plan.rs @@ -189,6 +189,12 @@ impl InstallPlan { " AI assistant : {}\n", if config.ai.enabled { "yes" } else { "no" } )); + if config.desktop.profile == crate::config::DesktopProfile::Mango { + o.push('\n'); + for line in crate::fastinstall::delivery_summary().lines() { + o.push_str(&format!(" {line}\n")); + } + } if let Some(hw) = hardware { if let Some(line) = crate::nvidia::NvidiaPlan::for_hardware(hw).render() { o.push_str(" GPU acceleration:\n"); diff --git a/installer-rs/crates/phoebus-core/src/policy.rs b/installer-rs/crates/phoebus-core/src/policy.rs index 1156939..e3f195f 100644 --- a/installer-rs/crates/phoebus-core/src/policy.rs +++ b/installer-rs/crates/phoebus-core/src/policy.rs @@ -92,8 +92,10 @@ impl PackagePolicyEngine { ("sys-kernel/gentoo-sources", 120), ("sys-libs/glibc", 900), ("www-client/firefox", 4200), + ("www-client/firefox-bin", 0), ("www-client/chromium", 7200), ("app-office/libreoffice", 5400), + ("app-office/libreoffice-bin", 0), ("dev-qt/qtbase", 900), ("kde-plasma/plasma-desktop", 600), ("net-im/discord-bin", 0), @@ -104,8 +106,10 @@ impl PackagePolicyEngine { let binary_preferred: HashSet<&'static str> = [ "www-client/firefox", + "www-client/firefox-bin", "www-client/chromium", "app-office/libreoffice", + "app-office/libreoffice-bin", "mail-client/thunderbird", "dev-lang/rust", "dev-lang/llvm", diff --git a/installer-rs/crates/phoebus-core/src/system.rs b/installer-rs/crates/phoebus-core/src/system.rs index 03588e1..2a85a61 100644 --- a/installer-rs/crates/phoebus-core/src/system.rs +++ b/installer-rs/crates/phoebus-core/src/system.rs @@ -109,14 +109,19 @@ pub fn mango_desktop_packages() -> Vec<&'static str> { /// `package_use`). /// - `app-text/zathura` needs a PDF plugin; `app-text/zathura-pdf-mupdf` is /// included. -/// - `app-office/libreoffice`, `www-client/firefox` and -/// `mail-client/thunderbird` are the full source builds by default; the -/// maintained binary variants (`-bin`) are a policy decision at install -/// time (see `policy.rs`), never a silent substitution here. +/// - `app-office/libreoffice-bin` and `www-client/firefox-bin` are the +/// maintained stable Gentoo binary redistributions used for the fast +/// default install. They install prebuilt upstream binaries through +/// Portage with full signature verification; they never fall back to a +/// silent source build (see `fastinstall::require_binary_capable`). +/// - `mail-client/thunderbird` stays a Portage build selected by policy. +/// - Calibre and GIMP are **not** in this set: they install as system-wide +/// Flatpaks from Flathub in the target (see `FAST_DEFAULT_FLATPAKS`), so +/// the installer never installs duplicate Portage copies. pub fn workstation_packages() -> Vec<&'static str> { vec![ "app-editors/emacs", - "app-office/libreoffice", + "app-office/libreoffice-bin", "media-gfx/swayimg", "media-video/mpv", "app-misc/fastfetch", @@ -125,18 +130,35 @@ pub fn workstation_packages() -> Vec<&'static str> { "app-text/zathura", "app-text/zathura-pdf-mupdf", "app-editors/nano", - "www-client/firefox", + "www-client/firefox-bin", "mail-client/thunderbird", - "app-text/calibre", "net-p2p/transmission", "media-sound/pavucontrol", - "media-gfx/gimp", "gnome-extra/nemo", "sci-calculators/qalculate-gtk", "net-irc/hexchat", ] } +/// System-wide Flatpaks installed from Flathub **in the target** during +/// `desktop_install` (never on the live host). +/// +/// Calibre and GIMP replace their former Portage copies; Flatseal is the +/// permission inspector (available without forcing per-app setup for basic +/// tasks). Upstream sandbox permissions are respected; any extra access is +/// a narrow, justified, application-specific override (see +/// `flatpak_narrow_overrides`). +pub const FAST_DEFAULT_FLATPAKS: &[(&str, &str)] = &[ + ("calibre", "com.calibre_ebook.calibre"), + ("gimp", "org.gimp.GIMP"), + ("flatseal", "com.github.tchx84.Flatseal"), +]; + +/// Flatpak application IDs installed system-wide by default. +pub fn fast_default_flatpak_ids() -> Vec<&'static str> { + FAST_DEFAULT_FLATPAKS.iter().map(|(_, id)| *id).collect() +} + /// Shell lane: Zsh is the default login shell for newly created users. /// Bash stays for system scripts and root administration (`/bin/sh` is /// untouched). Packaged plugins only — no downloaded shell framework. @@ -363,14 +385,48 @@ pub fn gtk_cursor_settings() -> String { } /// Nemo as the default graphical file manager (`mimeapps.list`). +/// +/// Ordinary-task defaults so sandboxed Flatpaks behave seamlessly under the +/// Wayland portals without global permission overrides: +/// +/// - directories open in Nemo (launching documents from the file manager), +/// - web links open in the installed Firefox (`-bin`; Brave stays available), +/// - PDFs open in Zathura, e-books in Calibre's Flatpak, common images in +/// GIMP's Flatpak where the upstream Flatpaks already handle them. +/// +/// Clipboard, drag-and-drop and printing flow through the existing +/// `xdg-desktop-portal*` + CUPS stack; no broad sandbox override is granted +/// here (narrow per-app overrides, if ever needed, are user-visible through +/// Flatseal — see `flatpak_narrow_overrides`). pub fn nemo_mimeapps() -> String { let mut o = String::new(); o.push_str("[Default Applications]\n"); o.push_str("inode/directory=nemo.desktop\n"); o.push_str("x-directory/normal=nemo.desktop\n"); + o.push_str("x-scheme-handler/http=firefox.desktop\n"); + o.push_str("x-scheme-handler/https=firefox.desktop\n"); + o.push_str("text/html=firefox.desktop\n"); + o.push_str("application/pdf=org.pwmt.zathura.desktop\n"); + o.push_str("application/epub+zip=com.calibre_ebook.calibre.desktop\n"); + o.push_str("image/png=org.gimp.GIMP.desktop\n"); + o.push_str("image/jpeg=org.gimp.GIMP.desktop\n"); o } +/// Narrow, justified, application-specific Flatpak overrides. +/// +/// Today this is intentionally empty: the upstream Calibre, GIMP and +/// Flatseal Flatpaks already request the permissions ordinary tasks need +/// (file chooser portals, printing, removable media for e-readers via the +/// existing portal), and Phoebus grants no broad global override and never +/// disables sandbox protections. If a future task proves to need extra +/// access, add only the narrow `flatpak override --user ...` line here +/// with its justification, surface it in the welcome UI, and keep it +/// inspectable through Flatseal. +pub fn flatpak_narrow_overrides() -> Vec<(&'static str, &'static str)> { + vec![] +} + /// Disk-space estimates per profile (GiB). The workstation set (~200 /// packages incl. LibreOffice/Firefox/Thunderbird/GIMP/Brave) needs /// substantially more download, build and installed space than the lean @@ -1483,6 +1539,193 @@ pub fn assistant_desktop_assets() -> Vec<(&'static str, &'static str)> { ] } +/// First-login welcome for the installed system (Mango + DankMaterialShell). +/// +/// This is distinct from the live ISO's "Install Phoebus OS" welcome, which +/// stays live-only. The installed welcome: +/// - runs once per user (state file `~/.config/phoebus/welcome-seen`) but +/// stays reopenable from the launcher and settings, +/// - never blocks login (background autostart; closing it finishes nothing), +/// - defaults to keeping the working system, +/// - explains the prebuilt fast defaults and offers separate opt-in builds +/// through the existing typed actions (the UI never holds a shell or +/// root; each build shows its review and requires explicit approval). +pub const INSTALLED_WELCOME_QML: &str = r##"// Phoebus first-login welcome (installed system only). +// Mango + DankMaterialShell styling: dark default, Phoebus palette. +// Keyboard: Tab/Shift+Tab moves, Enter activates, Esc closes. +// Layout adapts via anchors + Flickable for small displays. +import QtQuick +import QtQuick.Controls +import QtQuick.Layouts + +ApplicationWindow { + id: root + visible: true + title: "Welcome to Phoebus OS" + minimumWidth: 560 + minimumHeight: 480 + width: 720 + height: 600 + color: "#14161c" + + // Never modal: closing or leaving finishes nothing and blocks nothing. + onClosing: { welcomeBackend.markSeen(); } + + Flickable { + anchors.fill: parent + contentWidth: parent.width + contentHeight: column.implicitHeight + 48 + clip: true + ScrollBar.vertical: ScrollBar { } + + ColumnLayout { + id: column + anchors.horizontalCenter: parent.horizontalCenter + width: Math.min(parent.width - 48, 640) + y: 24 + spacing: 12 + + Label { + text: "Welcome to Phoebus OS" + font.pixelSize: 26 + font.bold: true + color: "#f5b942" + focus: true + KeyNavigation.tab: keepButton + } + Label { + text: "Fast by default, yours to tune. Phoebus installed prebuilt, verified applications and a generic kernel to shorten installation. Everything works now; source builds are strictly opt-in." + wrapMode: Text.WordWrap + Layout.fillWidth: true + color: "#d7dae0" + KeyNavigation.tab: keepButton + } + Label { + text: "Your system keeps working while any build runs elsewhere. Compiling is not claimed to make things noticeably faster." + wrapMode: Text.WordWrap + Layout.fillWidth: true + color: "#9aa0ab" + } + + GroupBox { + title: "1. Review and selectively build applications from source" + Layout.fillWidth: true + Label { + text: "Firefox, LibreOffice, Calibre and GIMP can be rebuilt from their maintained sources. Shown first: exact packages, expected time, temporary disk, power/network needs, then an explicit approval. The working copy stays until the new build verifies." + wrapMode: Text.WordWrap + width: parent.width + color: "#d7dae0" + } + RowLayout { + Button { id: srcButton; text: "Review source builds"; onClicked: welcomeBackend.openSourceBuilds(); KeyNavigation.tab: kernelButton } + } + } + GroupBox { + title: "2. Build a kernel tuned for this machine" + Layout.fillWidth: true + Label { + text: "Starts from the proven distribution configuration with only supported tuning. A separate boot entry is created and test-booted first; the generic kernel stays installed as the known-good fallback." + wrapMode: Text.WordWrap + width: parent.width + color: "#d7dae0" + } + RowLayout { + Button { id: kernelButton; text: "Review tuned kernel"; onClicked: welcomeBackend.openTunedKernel(); KeyNavigation.tab: keepButton } + } + } + GroupBox { + title: "3. Keep the fast defaults and finish" + Layout.fillWidth: true + RowLayout { + Button { id: keepButton; text: "Keep working system and finish (default)"; highlighted: true; onClicked: { welcomeBackend.markSeen(); root.close(); } KeyNavigation.tab: srcButton } + Button { text: "Close"; onClicked: { welcomeBackend.markSeen(); root.close(); } } + } + } + Label { + text: "Keys: Tab moves, Enter activates, Esc closes. Reopen anytime from the launcher (Phoebus Welcome) or settings." + wrapMode: Text.WordWrap + Layout.fillWidth: true + color: "#9aa0ab" + } + } + } + Shortcut { sequence: "Escape"; onActivated: { welcomeBackend.markSeen(); root.close(); } } +} +"##; + +/// Launcher script for the installed welcome. Reopenable; records nothing +/// privileged. The QML talks to `sys --assistant-bridge` for the opt-in +/// actions, so approval and privilege stay in the deterministic broker. +pub const INSTALLED_WELCOME_SCRIPT: &str = r#"#!/bin/bash +# Phoebus first-login welcome (installed system only). Never blocks login: +# it runs in the background and exiting changes nothing. +set -u +SEEN="${XDG_CONFIG_HOME:-$HOME/.config}/phoebus/welcome-seen" +if [ "${1:-}" != "--reopen" ] && [ -f "$SEEN" ]; then + exit 0 +fi +if command -v quickshell >/dev/null 2>&1 \ + && [ -f /etc/xdg/quickshell/phoebus-welcome-installed/shell.qml ]; then + exec quickshell --no-duplicate -c phoebus-welcome-installed "$@" +fi +echo "phoebus-welcome: quickshell is unavailable; reopen from the launcher later" >&2 +exit 1 +"#; + +/// Desktop entry (launcher + settings) for the installed welcome. +pub const INSTALLED_WELCOME_DESKTOP_ENTRY: &str = r#"[Desktop Entry] +Name=Phoebus Welcome +Comment=First-login welcome: fast defaults and opt-in source builds +Exec=/usr/local/bin/phoebus-welcome --reopen +Icon=system-help +Terminal=false +Type=Application +Categories=System;Settings; +Keywords=welcome;setup;phoebus;source;kernel; +"#; + +/// Background autostart for the installed welcome. `X-GNOME-Autostart-enabled` +/// only; no blocking, no modal gate — login completes with or without it. +pub const INSTALLED_WELCOME_AUTOSTART: &str = r#"[Desktop Entry] +Name=Phoebus Welcome (first login) +Comment=Show the Phoebus first-login welcome once per user +Exec=/usr/local/bin/phoebus-welcome +Icon=system-help +Terminal=false +Type=Application +X-GNOME-Autostart-enabled=true +NoDisplay=true +"#; + +/// Seed content suppressing the upstream DMS first-run dialogs on the +/// installed target, so the user sees exactly one welcome experience (ours). +/// Mirrors the live-medium seeding in `installer/live/build.sh`. +pub fn dms_firstlaunch_seed(version: &str) -> Vec<(&'static str, String)> { + let major_minor = version.split('.').take(2).collect::>().join("."); + vec![ + (".config/DankMaterialShell/.firstlaunch", String::new()), + (".config/DankMaterialShell/.changelog-seen", major_minor), + ] +} + +/// All installed-welcome assets provisioned into the target. +pub fn installed_welcome_assets() -> Vec<(&'static str, &'static str)> { + vec![ + ( + "etc/xdg/quickshell/phoebus-welcome-installed/shell.qml", + INSTALLED_WELCOME_QML, + ), + ( + "usr/share/applications/phoebus-welcome.desktop", + INSTALLED_WELCOME_DESKTOP_ENTRY, + ), + ( + "etc/xdg/autostart/phoebus-welcome.desktop", + INSTALLED_WELCOME_AUTOSTART, + ), + ] +} + /// A Wayland session entry for `/usr/share/wayland-sessions`. pub fn wayland_session_entry(profile: DesktopProfile) -> Option<(&'static str, String)> { match profile { @@ -2410,7 +2653,7 @@ mod tests { // silently omitted or substituted. for atom in [ "app-editors/emacs", - "app-office/libreoffice", + "app-office/libreoffice-bin", "media-gfx/swayimg", "media-video/mpv", "app-misc/fastfetch", @@ -2419,13 +2662,11 @@ mod tests { "app-text/zathura", "app-text/zathura-pdf-mupdf", "app-editors/nano", - "www-client/firefox", + "www-client/firefox-bin", "www-client/brave-browser", "mail-client/thunderbird", - "app-text/calibre", "net-p2p/transmission", "media-sound/pavucontrol", - "media-gfx/gimp", "net-print/cups", "gnome-extra/nemo", "sci-calculators/qalculate-gtk", @@ -2434,6 +2675,19 @@ mod tests { ] { assert!(pkgs.contains(&atom), "missing workstation atom {atom}"); } + // Fast defaults: -bin atoms replace the source builds; Calibre and + // GIMP ship as system-wide Flatpaks, never as duplicate Portage + // copies. + assert!(!pkgs.contains(&"app-office/libreoffice")); + assert!(!pkgs.contains(&"www-client/firefox")); + assert!(!pkgs.contains(&"app-text/calibre")); + assert!(!pkgs.contains(&"media-gfx/gimp")); + for (_, id) in FAST_DEFAULT_FLATPAKS { + assert!( + fast_default_flatpak_ids().contains(id), + "missing default Flatpak {id}" + ); + } // Kitty stays; st is never added; pcmanfm is replaced by Nemo. assert!(pkgs.contains(&"x11-terms/kitty")); assert!(!pkgs.contains(&"x11-terms/st")); @@ -2529,6 +2783,39 @@ mod tests { assert!(text.contains("inode/directory=nemo.desktop")); } + #[test] + fn fast_defaults_use_bin_atoms_flatpaks_and_one_generic_kernel() { + // No duplicate Portage copies of the Flatpak apps. + let pkgs = workstation_packages(); + assert!(pkgs.contains(&"www-client/firefox-bin")); + assert!(pkgs.contains(&"app-office/libreoffice-bin")); + assert!(!pkgs.contains(&"app-text/calibre")); + assert!(!pkgs.contains(&"media-gfx/gimp")); + // Three system-wide Flatpaks, installed in the target only. + assert_eq!(fast_default_flatpak_ids().len(), 3); + assert!(fast_default_flatpak_ids().contains(&"com.calibre_ebook.calibre")); + assert!(fast_default_flatpak_ids().contains(&"org.gimp.GIMP")); + assert!(fast_default_flatpak_ids().contains(&"com.github.tchx84.Flatseal")); + // No broad sandbox override, ever here. + assert!(flatpak_narrow_overrides().is_empty()); + // Ordinary-task defaults without touching sandbox protections. + let mime = nemo_mimeapps(); + assert!(mime.contains("x-scheme-handler/https=firefox.desktop")); + assert!(mime.contains("application/epub+zip=com.calibre_ebook.calibre.desktop")); + // Installed welcome: once per user, reopenable, never blocking. + assert!(INSTALLED_WELCOME_SCRIPT.contains("--reopen")); + assert!(INSTALLED_WELCOME_SCRIPT.contains("welcome-seen")); + assert!(INSTALLED_WELCOME_AUTOSTART.contains("X-GNOME-Autostart-enabled=true")); + assert!(INSTALLED_WELCOME_DESKTOP_ENTRY.contains("--reopen")); + assert!(INSTALLED_WELCOME_QML.contains("Keep working system and finish")); + assert!(INSTALLED_WELCOME_QML.contains("KeyNavigation.tab")); + let assets = installed_welcome_assets(); + assert!(assets.iter().any(|(p, _)| p.contains("shell.qml"))); + // DMS first-run suppression seeds the skeleton only. + let seed = dms_firstlaunch_seed("1.6.2"); + assert!(seed.iter().any(|(p, _)| p.ends_with(".firstlaunch"))); + } + #[test] fn disk_estimates_require_more_for_the_workstation() { assert_eq!( diff --git a/installer-rs/crates/phoebus-executor/src/actions.rs b/installer-rs/crates/phoebus-executor/src/actions.rs index 728c9e3..de6aa64 100644 --- a/installer-rs/crates/phoebus-executor/src/actions.rs +++ b/installer-rs/crates/phoebus-executor/src/actions.rs @@ -58,6 +58,24 @@ pub fn preview(action: &SystemAction) -> String { out.push_str(" --- ebuild ends ---\n"); out.push_str(" It will be treated as untrusted code and built only after approval.\n"); } + // Source conversions and the tuned kernel carry their full review + // (exact packages, expected time, temporary disk, power/network, + // proposed changes) so the explicit approval step is informed. + match action { + SystemAction::ConvertToSource { app } => { + if let Some(conv) = phoebus_core::fastinstall::source_conversion(app) { + out.push('\n'); + out.push_str(&phoebus_core::fastinstall::source_conversion_review(conv)); + } + } + SystemAction::BuildTunedKernel { .. } => { + out.push('\n'); + out.push_str(&phoebus_core::fastinstall::tuned_kernel_review( + &phoebus_core::fastinstall::tuned_kernel_plan(), + )); + } + _ => {} + } out } @@ -175,11 +193,204 @@ fn pretend_args(action: &SystemAction) -> Option> { "--".into(), "@world".into(), ]), + // Source conversions and the tuned kernel resolve the same pretend + // plan as a Portage install of their source atom, so the reviewed + // effects stay comparable at the execution boundary. + SystemAction::ConvertToSource { app } => { + let conv = phoebus_core::fastinstall::source_conversion(app)?; + Some(vec![ + "--pretend".into(), + "--color=n".into(), + "--".into(), + conv.source_atom.to_string(), + ]) + } + SystemAction::BuildTunedKernel { .. } => Some(vec![ + "--pretend".into(), + "--color=n".into(), + "--".into(), + "sys-kernel/gentoo-kernel".into(), + ]), _ => None, } } -/// Whether [`resolve_effects`] produces a real, comparable plan for an action. +/// Whether a Portage atom has a VDB record under `root` (installed). +fn vdb_has_atom(root: &Path, atom: &str) -> bool { + let (category, package) = match atom.split_once('/') { + Some((c, p)) => (c, p), + None => return false, + }; + let dir = root.join("var/db/pkg").join(category); + let Ok(entries) = std::fs::read_dir(&dir) else { + return false; + }; + entries.flatten().any(|e| { + let name = e.file_name().to_string_lossy().to_string(); + name == package || name.starts_with(&format!("{package}-")) + }) +} + +/// Whether a Flatpak app id is installed system-wide under `root`. +fn flatpak_has_app(exec: &Exec, root: &Path, app_id: &str) -> bool { + let Ok(out) = capture_in_target( + exec, + root, + "sys", + "check flatpak app", + "flatpak", + &[ + "list".into(), + "--app".into(), + "--columns=application".into(), + ], + ) else { + return false; + }; + out.stdout_lossy().lines().any(|l| l.trim() == app_id) +} + +/// Replace a fast-default prebuilt application with its maintained source +/// alternative. +/// +/// Safety order (the working application is never removed first): +/// 1. Check blockers/dependencies with `emerge --pretend` (reviewed plan). +/// 2. Build the source as a binary package (`--buildpkgonly`) without +/// touching the live system; a failed build leaves the working copy. +/// 3. Remove the old copy only after the build succeeds (and only when it +/// is actually installed; user data and desktop defaults are preserved — +/// neither `--unmerge` nor `flatpak remove` touches home directories or +/// the shared `mimeapps.list`). +/// 4. Install the new build from the just-built package and verify the VDB +/// record; a verification failure is reported, never silent. +fn convert_to_source(exec: &Exec, root: &Path, app: &str) -> Result { + let conv = phoebus_core::fastinstall::source_conversion(app).ok_or_else(|| { + if app.eq_ignore_ascii_case("brave") { + ExecError::operation( + "sys", + "build from source", + phoebus_core::fastinstall::brave_source_status(), + ) + } else { + ExecError::operation( + "sys", + "build from source", + format!("no supported source build for `{app}`"), + ) + } + })?; + // 1. Blockers and dependencies first: the pretend plan is the reviewed + // evidence; an unresolvable plan aborts before anything is built. + let pretend = SystemAction::InstallPackage { + atom: conv.source_atom.to_string(), + binary: None, + }; + let plan = resolve_effects(exec, &pretend, root)?; + if !plan.established { + return Err(ExecError::operation( + "sys", + "build from source", + format!( + "could not establish the build plan for {}; refusing to proceed unreviewed", + conv.source_atom + ), + )); + } + // 2. Build without installing. A failure here leaves the working + // application exactly as it was. + run_in_target( + exec, + root, + "sys", + "build from source", + "emerge", + &[ + "--ask=n".into(), + "--buildpkgonly".into(), + "--".into(), + conv.source_atom.to_string(), + ], + ) + .map_err(|e| { + ExecError::operation( + "sys", + "build from source", + format!( + "the source build of {} failed; the working copy ({}) is still installed: {e}", + conv.source_atom, conv.installed_from + ), + ) + })?; + // 3. Remove the old copy only now. Data-preserving removals only. + let old_is_flatpak = conv.installed_from.contains('.') && !conv.installed_from.contains('/'); + if old_is_flatpak { + // `installed_from` is prose ("com.x (Flatpak)"); extract the id. + let id = conv + .installed_from + .split_whitespace() + .next() + .unwrap_or(conv.installed_from); + if flatpak_has_app(exec, root, id) { + run_in_target( + exec, + root, + "sys", + "remove replaced flatpak", + "flatpak", + &[ + "remove".into(), + "-y".into(), + "--system".into(), + "--".into(), + id.into(), + ], + )?; + } + } else if vdb_has_atom(root, conv.installed_from) { + run_in_target( + exec, + root, + "sys", + "remove replaced binary package", + "emerge", + &[ + "--unmerge".into(), + "--ask=n".into(), + "--".into(), + conv.installed_from.to_string(), + ], + )?; + } + // 4. Install the verified build and confirm the VDB record. + run_in_target( + exec, + root, + "sys", + "install source build", + "emerge", + &[ + "--ask=n".into(), + "--usepkg=y".into(), + "--".into(), + conv.source_atom.to_string(), + ], + )?; + if !vdb_has_atom(root, conv.source_atom) { + return Err(ExecError::operation( + "sys", + "build from source", + format!( + "the build of {} did not verify in the package database; \ + the previous copy was already removed — restore the protective snapshot", + conv.source_atom + ), + )); + } + Ok(format!( + "built {} from source ({}) and verified the installation; user data preserved", + conv.app, conv.source_atom + )) +} /// /// Portage transactions resolve from `emerge --pretend`; the maintenance /// actions (depclean, per-source updates, cache cleanup) resolve a structured, @@ -215,6 +426,23 @@ pub fn resolve_effects(exec: &Exec, action: &SystemAction, root: &Path) -> Resul } let Some(args) = pretend_args(action) else { + // An unsupported source conversion fails closed here — before any + // approval is requested and before any command runs — with the exact + // reason (including Brave's missing source route). + if let SystemAction::ConvertToSource { app } = action { + if app.eq_ignore_ascii_case("brave") { + return Err(ExecError::operation( + "sys", + "resolve effects", + phoebus_core::fastinstall::brave_source_status(), + )); + } + return Err(ExecError::operation( + "sys", + "resolve effects", + format!("no supported source build for `{app}`"), + )); + } return Ok(ResolvedPlan::default()); }; // Same rooting as execution, so the reviewed plan describes the action that @@ -1530,6 +1758,10 @@ pub fn execute_inner( state.note ) } + SystemAction::ConvertToSource { app } => convert_to_source(exec, root, app)?, + SystemAction::BuildTunedKernel { make_default } => { + crate::kernel::build_tuned_kernel(exec, root, *make_default)? + } }; Ok(ActionOutcome { action: action.clone(), @@ -1960,6 +2192,125 @@ Total: 1 package (1 new), Size of downloads: 512 KiB assert!(plan.established); } + #[test] + fn source_conversion_refuses_brave_with_the_reason_before_any_command() { + let runner = RecordingRunner::new(); + let exec = make_exec(runner.clone()); + let action = SystemAction::ConvertToSource { + app: "brave".into(), + }; + let err = resolve_effects(&exec, &action, Path::new("/")).unwrap_err(); + assert!(err.to_string().contains("no trustworthy"), "got {err}"); + assert!(runner.recorded().is_empty()); + } + + #[test] + fn source_conversion_refuses_unknown_apps_without_guessing() { + let runner = RecordingRunner::new(); + let exec = make_exec(runner.clone()); + let action = SystemAction::ConvertToSource { + app: "definitely-not-an-app".into(), + }; + let err = resolve_effects(&exec, &action, Path::new("/")).unwrap_err(); + assert!( + err.to_string().contains("no supported source build"), + "got {err}" + ); + assert!(runner.recorded().is_empty()); + } + + #[test] + fn source_conversion_builds_before_removing_and_verifies() { + let runner = RecordingRunner::new(); + runner.set_response("chroot", response(PRETEND_VIM)); + let exec = make_exec(runner.clone()); + let root = exec.root.clone(); + // Fixture VDB: the fast-default binary copy and (simulating a + // verified install) the source copy. + for dir in [ + "var/db/pkg/www-client/firefox-bin-128.0", + "var/db/pkg/www-client/firefox-128.0", + ] { + std::fs::create_dir_all(root.join(dir)).unwrap(); + } + let action = SystemAction::ConvertToSource { + app: "firefox".into(), + }; + let plan = resolve_effects(&exec, &action, &root).unwrap(); + assert!(plan.established); + let outcome = execute(&exec, &action, Some(&auth()), &root).unwrap(); + assert!( + outcome.output.contains("verified the installation"), + "{}", + outcome.output + ); + // Safety order: the reviewed pretend, then the build-only step, and + // only afterwards the removal of the old copy. + let args: Vec = runner + .recorded() + .iter() + .flat_map(|s| s.args.clone()) + .collect(); + let pretend = args + .iter() + .position(|a| a == "--pretend") + .expect("pretend ran"); + let build = args + .iter() + .position(|a| a == "--buildpkgonly") + .expect("build ran"); + let unmerge = args + .iter() + .position(|a| a == "--unmerge") + .expect("old copy removed"); + assert!(pretend < build && build < unmerge, "{args:?}"); + } + + #[test] + fn source_conversion_aborts_before_removal_when_the_plan_is_unresolvable() { + let runner = RecordingRunner::new(); + runner.set_response("chroot", response("something went sideways\n")); + let exec = make_exec(runner.clone()); + let root = exec.root.clone(); + std::fs::create_dir_all(root.join("var/db/pkg/www-client/firefox-bin-128.0")).unwrap(); + let action = SystemAction::ConvertToSource { + app: "firefox".into(), + }; + let err = execute(&exec, &action, Some(&auth()), &root).unwrap_err(); + assert!(err.to_string().contains("could not establish"), "got {err}"); + // No build and no removal were attempted. + let args: Vec = runner + .recorded() + .iter() + .flat_map(|s| s.args.clone()) + .collect(); + assert!(!args.iter().any(|a| a == "--buildpkgonly"), "{args:?}"); + assert!(!args.iter().any(|a| a == "--unmerge"), "{args:?}"); + } + + #[test] + fn conversion_and_kernel_previews_carry_the_full_review() { + let text = preview(&SystemAction::ConvertToSource { + app: "firefox".into(), + }); + assert!(text.contains("www-client/firefox"), "{text}"); + assert!(text.contains("Temporary disk"), "{text}"); + assert!( + text.contains("leaves the working application installed"), + "{text}" + ); + assert!( + text.contains("not claimed to produce a noticeable speedup"), + "{text}" + ); + let kernel = preview(&SystemAction::BuildTunedKernel { + make_default: false, + }); + assert!(kernel.contains("sys-kernel/gentoo-kernel"), "{kernel}"); + assert!(kernel.contains("gentoo-kernel-bin"), "{kernel}"); + assert!(kernel.contains("never replaces the working"), "{kernel}"); + } + #[test] fn a_material_change_invalidates_the_reviewed_plan() { let runner = RecordingRunner::new(); diff --git a/installer-rs/crates/phoebus-executor/src/desktop.rs b/installer-rs/crates/phoebus-executor/src/desktop.rs index 2294816..b0f0f8e 100644 --- a/installer-rs/crates/phoebus-executor/src/desktop.rs +++ b/installer-rs/crates/phoebus-executor/src/desktop.rs @@ -264,6 +264,135 @@ pub fn configure_flatpak(exec: &Exec, config: &InstallConfig) -> Result<()> { Ok(()) } +/// Install the default Flatpaks system-wide from Flathub **in the target** +/// (never on the live host), then verify apps, launchers, icons and MIME +/// associations. +/// +/// Upstream sandbox permissions are respected: no broad global override is +/// granted and no sandbox protection is disabled (see +/// `sysgen::flatpak_narrow_overrides`, which is intentionally empty). +/// Updates after reboot flow through the exact-transaction +/// `sys apply updates --flatpak` path. +pub fn install_flatpak_apps(exec: &Exec, config: &InstallConfig) -> Result<()> { + if !config.desktop.flatpak || config.desktop.profile == DesktopProfile::None { + return Ok(()); + } + let ids = sysgen::fast_default_flatpak_ids(); + exec.logger.info(format!( + "installing default Flatpaks in the target (system-wide): {}", + ids.join(" ") + )); + let mut args: Vec<&str> = vec![ + "install", + "-y", + "--system", + "--noninteractive", + "flathub", + "--", + ]; + args.extend(ids.iter().copied()); + portage::chroot(exec, Path::new(&exec.root), "flatpak", &args) + .map_err(|e| ExecError::operation("desktop", "install default flatpaks", e.to_string()))?; + // Narrow, justified per-app overrides only (today: none). + for (app_id, override_args) in sysgen::flatpak_narrow_overrides() { + let mut oargs = vec![ + "override".to_string(), + "--system".to_string(), + app_id.to_string(), + ]; + oargs.extend(override_args.split_whitespace().map(str::to_string)); + let oargs_ref: Vec<&str> = oargs.iter().map(String::as_str).collect(); + portage::chroot(exec, Path::new(&exec.root), "flatpak", &oargs_ref).map_err(|e| { + ExecError::operation("desktop", "apply flatpak override", e.to_string()) + })?; + } + verify_flatpak_apps(exec, &ids)?; + Ok(()) +} + +/// Verify the installed Flatpaks: `flatpak list` records the app, and the +/// exported launcher, icon and MIME handler exist in the target. +fn verify_flatpak_apps(exec: &Exec, ids: &[&str]) -> Result<()> { + let owned = ["list", "--app", "--columns=application"] + .iter() + .map(|s| s.to_string()) + .collect::>(); + let spec = portage::chroot_spec( + "desktop", + "list installed flatpaks", + Path::new(&exec.root), + "flatpak", + &owned, + ); + let out = exec + .run_capture(spec) + .map_err(|e| ExecError::operation("desktop", "list installed flatpaks", e.to_string()))?; + let listed = String::from_utf8_lossy(&out.stdout).to_string(); + // Record what the target contains so post-reboot verification (launchers, + // icons, MIME, `sys apply updates --flatpak`) has a baseline. + let target = exec.target(); + target.write("var/lib/phoebus/flatpaks-installed", listed.clone())?; + for id in ids { + if !listed.lines().any(|l| l.trim() == *id) { + return Err(ExecError::operation( + "desktop", + "verify default flatpaks", + format!("{id} is not in `flatpak list` after installation"), + )); + } + for rel in [ + format!("var/lib/flatpak/exports/share/applications/{id}.desktop"), + format!("var/lib/flatpak/app/{id}"), + ] { + if !target.exists(&rel) { + return Err(ExecError::operation( + "desktop", + "verify default flatpaks", + format!("{id}: expected {rel} in the target"), + )); + } + } + } + // Flatseal must be present for inspection without forcing setup. + if !ids.contains(&"com.github.tchx84.Flatseal") { + return Err(ExecError::operation( + "desktop", + "verify default flatpaks", + "Flatseal is required for permission inspection", + )); + } + exec.logger + .info("default Flatpaks verified (apps, launchers, exports)"); + Ok(()) +} + +/// Provision the installed-system first-login welcome (Mango + DMS styling). +/// Live-only entries are never written here; the installed welcome runs once +/// per user, stays reopenable, and never blocks login. +pub fn provision_installed_welcome(exec: &Exec, config: &InstallConfig) -> Result<()> { + if !config.desktop.profile.is_desktop() { + return Ok(()); + } + let target = exec.target(); + write_script( + &target, + "usr/local/bin/phoebus-welcome", + sysgen::INSTALLED_WELCOME_SCRIPT, + )?; + for (rel_path, content) in sysgen::installed_welcome_assets() { + target.write(rel_path, content)?; + } + // Seed the upstream DMS first-run suppression into the skeleton so every + // new user sees exactly one welcome experience (ours), without + // overlapping DMS dialogs. Existing homes are never touched. + for (rel, content) in sysgen::dms_firstlaunch_seed("1.6.2") { + target.write(&format!("etc/skel/{rel}"), content)?; + } + exec.logger + .info("provisioned the installed first-login welcome (once per user, reopenable)"); + Ok(()) +} + #[cfg(test)] mod tests { use super::*; @@ -417,6 +546,140 @@ mod tests { assert!(!cupsd.contains("Allow all")); } + #[test] + fn default_flatpaks_install_system_wide_in_the_target_only() { + use crate::command::CommandOutput; + let runner = RecordingRunner::new(); + // `flatpak list` inside the target names every default app. + runner.set_response( + "chroot", + CommandOutput { + status: 0, + success: true, + stdout: b"com.calibre_ebook.calibre\norg.gimp.GIMP\ncom.github.tchx84.Flatseal\n" + .to_vec(), + stderr: Vec::new(), + duration: std::time::Duration::from_millis(1), + }, + ); + let exec = make_exec(runner.clone()); + // Fixture exports: launchers and app dirs in the target. + for id in sysgen::fast_default_flatpak_ids() { + let desktop = format!("var/lib/flatpak/exports/share/applications/{id}.desktop"); + let path = exec.root.join(&desktop); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(&path, "[Desktop Entry]\n").unwrap(); + std::fs::create_dir_all(exec.root.join(format!("var/lib/flatpak/app/{id}"))).unwrap(); + } + let mut cfg = InstallConfig::default(); + cfg.desktop.profile = DesktopProfile::Mango; + install_flatpak_apps(&exec, &cfg).unwrap(); + // Every command ran inside the target chroot — nothing touched the + // live host directly. + for spec in runner.recorded() { + assert_eq!(spec.program, "chroot", "must not run on the host: {spec:?}"); + assert_eq!(spec.args[0], exec.root.to_string_lossy().to_string()); + } + let recorded = runner.recorded(); + let install = recorded + .iter() + .find(|s| s.args.iter().any(|a| a == "install")) + .expect("flatpak install ran"); + for flag in ["--system", "--noninteractive", "flathub"] { + assert!(install.args.iter().any(|a| a == flag), "{install:?}"); + } + for id in sysgen::fast_default_flatpak_ids() { + assert!(install.args.iter().any(|a| a == id), "{install:?}"); + } + // The manifest records the installed set for post-reboot checks. + let manifest = + std::fs::read_to_string(exec.root.join("var/lib/phoebus/flatpaks-installed")).unwrap(); + for id in sysgen::fast_default_flatpak_ids() { + assert!(manifest.contains(id), "{manifest}"); + } + } + + #[test] + fn flatpak_verification_fails_closed_on_a_missing_app() { + let runner = RecordingRunner::new(); + let exec = make_exec(runner); + let mut cfg = InstallConfig::default(); + cfg.desktop.profile = DesktopProfile::Mango; + // Default runner returns empty `flatpak list`: verification must fail + // closed instead of reporting success. + let err = install_flatpak_apps(&exec, &cfg).unwrap_err(); + assert!(err.to_string().contains("not in `flatpak list`"), "{err}"); + } + + #[test] + fn installed_welcome_is_provisioned_once_per_user_and_reopenable() { + let runner = RecordingRunner::new(); + let exec = make_exec(runner); + let mut cfg = InstallConfig::default(); + cfg.desktop.profile = DesktopProfile::Mango; + provision_installed_welcome(&exec, &cfg).unwrap(); + for rel in [ + "usr/local/bin/phoebus-welcome", + "usr/share/applications/phoebus-welcome.desktop", + "etc/xdg/autostart/phoebus-welcome.desktop", + "etc/xdg/quickshell/phoebus-welcome-installed/shell.qml", + ] { + assert!(exec.root.join(rel).is_file(), "{rel} was not installed"); + } + // Launcher + autostart behaviour: reopenable, background, never a + // login gate. + let script = + std::fs::read_to_string(exec.root.join("usr/local/bin/phoebus-welcome")).unwrap(); + assert!(script.contains("--reopen")); + assert!(script.contains("welcome-seen")); + let autostart = + std::fs::read_to_string(exec.root.join("etc/xdg/autostart/phoebus-welcome.desktop")) + .unwrap(); + assert!(autostart.contains("X-GNOME-Autostart-enabled=true")); + assert!(autostart.contains("NoDisplay=true")); + let entry = std::fs::read_to_string( + exec.root + .join("usr/share/applications/phoebus-welcome.desktop"), + ) + .unwrap(); + assert!(entry.contains("--reopen")); + // QML belongs with Mango/DMS, adapts to display size, and is + // keyboard-navigable without blocking. + let qml = std::fs::read_to_string( + exec.root + .join("etc/xdg/quickshell/phoebus-welcome-installed/shell.qml"), + ) + .unwrap(); + assert!(qml.contains("Welcome to Phoebus OS")); + assert!(qml.contains("prebuilt")); + assert!(qml.contains("KeyNavigation.tab")); + assert!(qml.contains("Escape")); + assert!(qml.contains("Flickable")); + // DMS first-run dialogs are suppressed via the skeleton so users see + // one welcome experience; existing homes are never touched here. + assert!(exec + .root + .join("etc/skel/.config/DankMaterialShell/.firstlaunch") + .is_file()); + // The live-only installer entry is never provisioned here. + assert!(!exec + .root + .join("usr/share/applications/phoebus-install.desktop") + .exists()); + } + + #[test] + fn no_welcome_or_flatpaks_for_headless_profile() { + let runner = RecordingRunner::new(); + let exec = make_exec(runner.clone()); + let mut cfg = InstallConfig::default(); + cfg.desktop.profile = DesktopProfile::None; + provision_installed_welcome(&exec, &cfg).unwrap(); + install_flatpak_apps(&exec, &cfg).unwrap(); + assert!(!exec.root.join("usr/local/bin/phoebus-welcome").exists()); + assert!(runner.recorded().is_empty()); + } + #[test] fn assistant_desktop_assets_are_provisioned_on_installed_target() { let runner = RecordingRunner::new(); diff --git a/installer-rs/crates/phoebus-executor/src/kernel.rs b/installer-rs/crates/phoebus-executor/src/kernel.rs index a3f3001..22ec10a 100644 --- a/installer-rs/crates/phoebus-executor/src/kernel.rs +++ b/installer-rs/crates/phoebus-executor/src/kernel.rs @@ -44,7 +44,12 @@ pub fn install( engine: &PackagePolicyEngine, ctx: &PolicyContext, ) -> Result<()> { + // The generic prebuilt kernel is the only kernel installed by default. + // No redundant second generic kernel is ever added: a tuned kernel is a + // separate, user-initiated `sys` workflow (`build_tuned_kernel`) that + // keeps this package as the known-good fallback. let mut packages = vec![config.kernel.selected_package()]; + assert_only_generic_kernel(&packages); for pkg in sysgen::kernel_extra_packages(&hardware.cpu) { packages.push(pkg.to_string()); } @@ -55,6 +60,235 @@ pub fn install( portage::emerge(exec, Path::new(&exec.root), &packages, engine, ctx) } +/// Guard: the default install carries exactly one generic kernel. +fn assert_only_generic_kernel(packages: &[String]) { + debug_assert_eq!( + packages, + ["sys-kernel/gentoo-kernel-bin".to_string()], + "the default install must not add a second generic kernel" + ); +} + +/// Build a kernel tuned for this machine without ever replacing the working +/// default. +/// +/// 1. Refuses unless `sys-kernel/gentoo-kernel-bin` is installed (the +/// known-good fallback must exist first). +/// 2. Writes the tuned fragment on top of the proven distribution-kernel +/// configuration (supported, measurable tuning only; storage, encryption, +/// filesystem, firmware, input and recovery support retained). +/// 3. Builds `sys-kernel/gentoo-kernel` as a binary package first, so a +/// failed build never touches the boot selection. +/// 4. Installs it and creates a **separate** BLS entry. The default is only +/// switched when `make_default` is set **and** the running kernel already +/// is the tuned one (i.e. after an explicit test boot) — otherwise the +/// entry is left for a test boot with the route back documented. +pub fn build_tuned_kernel(exec: &Exec, root: &Path, make_default: bool) -> Result { + use phoebus_core::fastinstall::tuned_kernel_plan; + let plan = tuned_kernel_plan(); + // 1. The fallback must exist. + if !vdb_has_atom(root, plan.fallback_atom) { + return Err(ExecError::operation( + "sys", + "build tuned kernel", + format!( + "{} is not installed; refusing to build a tuned kernel without the known-good fallback", + plan.fallback_atom + ), + )); + } + // 2. Tuned fragment, derived from the proven profile fragment. + exec.target().write( + "etc/kernel/config.d/10-phoebus-tuned.config", + tuned_kernel_fragment(), + )?; + exec.logger.info("wrote tuned kernel fragment"); + // 3. Build only; a failure here leaves boot untouched. + portage::chroot( + exec, + root, + "emerge", + &[ + "--ask=n", + "--buildpkgonly", + "--", + "sys-kernel/gentoo-kernel", + ], + ) + .map_err(|e| { + ExecError::operation( + "sys", + "build tuned kernel", + format!("the tuned kernel build failed; the working default is unchanged: {e}"), + ) + })?; + // 4. Install from the verified build, then a separate BLS entry. + portage::chroot( + exec, + root, + "emerge", + &["--ask=n", "--usepkg=y", "--", "sys-kernel/gentoo-kernel"], + ) + .map_err(|e| ExecError::operation("sys", "install tuned kernel", e.to_string()))?; + if !vdb_has_atom(root, "sys-kernel/gentoo-kernel") { + return Err(ExecError::operation( + "sys", + "build tuned kernel", + "the tuned kernel did not verify in the package database; the working default is unchanged", + )); + } + let entry = tuned_bls_entry(root)?; + let mut out = format!( + "tuned kernel built and verified; separate boot entry `{entry}` created; \ + {} stays the default", + plan.fallback_atom + ); + if make_default { + if tuned_kernel_is_running(root)? { + set_default_entry(exec, root, &entry)?; + out.push_str("; test boot confirmed, tuned kernel is now the default"); + } else { + out.push_str( + "; not made default yet: boot the new entry once for a test boot, \ + then re-run with approval to make it the default", + ); + } + } else { + out.push_str("; boot the new entry to test it before making it default"); + } + Ok(out) +} + +/// Only supported, measurable tuning on top of the proven base: native +/// optimization markers and build parallelism hints. Required storage, +/// encryption, filesystem, firmware, input and recovery support from the +/// base fragment are retained, never disabled. +fn tuned_kernel_fragment() -> String { + let mut o = String::new(); + o.push_str("# Phoebus tuned-kernel fragment (generated).\n"); + o.push_str("# Applied on top of the proven Gentoo distribution-kernel\n"); + o.push_str("# configuration plus 00-phoebus-profile.config. Only supported,\n"); + o.push_str("# measurable tuning; required drivers are never disabled.\n"); + o.push_str("CONFIG_CC_OPTIMIZE_FOR_PERFORMANCE=y\n"); + o +} + +/// Whether a VDB record exists for `atom` under `root`. +fn vdb_has_atom(root: &Path, atom: &str) -> bool { + let (category, package) = match atom.split_once('/') { + Some((c, p)) => (c, p), + None => return false, + }; + let dir = root.join("var/db/pkg").join(category); + let Ok(entries) = std::fs::read_dir(&dir) else { + return false; + }; + entries.flatten().any(|e| { + let name = e.file_name().to_string_lossy().to_string(); + name == package || name.starts_with(&format!("{package}-")) + }) +} + +/// Copy the default BLS entry to a separate tuned-kernel entry. Returns the +/// new entry file name. Never rewrites the default loader selection. +fn tuned_bls_entry(root: &Path) -> Result { + let entries = root.join("efi/EFI/Linux"); + let entries = if entries.is_dir() { + entries + } else { + root.join("boot/EFI/Linux") + }; + let Ok(dir) = std::fs::read_dir(&entries) else { + return Err(ExecError::operation( + "sys", + "build tuned kernel", + "no BLS entry directory found; refusing to guess the boot layout", + )); + }; + let mut current: Vec = dir + .flatten() + .map(|e| e.path()) + .filter(|p| p.extension().is_some_and(|x| x == "conf")) + .collect(); + current.sort(); + let Some(src) = current.first().cloned() else { + return Err(ExecError::operation( + "sys", + "build tuned kernel", + "no existing BLS entry to derive the tuned entry from", + )); + }; + let text = std::fs::read_to_string(&src).map_err(|e| ExecError::io(src.clone(), e))?; + let tuned = format!( + "{}\n# Phoebus tuned kernel (test entry; generic fallback stays default)\n", + text.trim_end() + ); + let name = "phoebus-tuned.conf"; + let dest = entries.join(name); + std::fs::write(&dest, tuned).map_err(|e| ExecError::io(dest.clone(), e))?; + Ok(name.to_string()) +} + +/// Whether the tuned kernel is the running kernel: only on the host root, +/// the running release must match an installed `sys-kernel/gentoo-kernel` +/// VDB version. For an alternate root (or when the release cannot be +/// established) this reports false, so the default is never switched +/// blindly — the user test-boots the new entry first, then re-runs. +fn tuned_kernel_is_running(root: &Path) -> Result { + if root != Path::new("/") { + return Ok(false); + } + let release = std::fs::read_to_string("/proc/sys/kernel/osrelease") + .map(|s| s.trim().to_string()) + .unwrap_or_default(); + if release.is_empty() { + return Ok(false); + } + let dir = root.join("var/db/pkg/sys-kernel/gentoo-kernel"); + let Ok(entries) = std::fs::read_dir(&dir) else { + return Ok(false); + }; + // VDB dirs are `gentoo-kernel-`; the release contains the + // version plus localversion suffixes. + for e in entries.flatten() { + let name = e.file_name().to_string_lossy().to_string(); + if let Some(ver) = name.strip_prefix("gentoo-kernel-") { + if release.starts_with(ver) || release.contains(ver) { + return Ok(true); + } + } + } + Ok(false) +} + +/// Point the loader default at `entry`. +fn set_default_entry(exec: &Exec, root: &Path, entry: &str) -> Result<()> { + let loader = root.join("efi/loader/loader.conf"); + let loader = if loader.exists() { + loader + } else { + root.join("boot/loader/loader.conf") + }; + let text = std::fs::read_to_string(&loader).map_err(|e| ExecError::io(loader.clone(), e))?; + let mut out = String::new(); + let mut set = false; + for line in text.lines() { + if line.trim_start().starts_with("default") { + out.push_str(&format!("default {entry}\n")); + set = true; + } else { + out.push_str(line); + out.push('\n'); + } + } + if !set { + out.push_str(&format!("default {entry}\n")); + } + std::fs::write(&loader, out).map_err(|e| ExecError::io(loader.clone(), e))?; + exec.logger.info(format!("loader default set to {entry}")); + Ok(()) +} + #[cfg(test)] mod tests { use super::*; @@ -78,4 +312,62 @@ mod tests { assert!(text.contains("rd.luks.name=uuid-1234=cryptroot")); assert!(text.contains("root=/dev/mapper/cryptroot")); } + + #[test] + fn tuned_build_refuses_without_the_known_good_fallback() { + let runner = RecordingRunner::new(); + let exec = make_exec(runner.clone()); + // No VDB at all: the fallback is absent. + let err = build_tuned_kernel(&exec, Path::new(&exec.root), false).unwrap_err(); + assert!(err.to_string().contains("known-good fallback"), "{err}"); + assert!(runner.recorded().is_empty()); + } + + #[test] + fn tuned_build_creates_a_separate_entry_and_keeps_the_default() { + let runner = RecordingRunner::new(); + let exec = make_exec(runner.clone()); + let root = Path::new(&exec.root); + // Fixture VDB: both the fallback and (simulating the fresh build) + // the tuned kernel. + for dir in [ + "var/db/pkg/sys-kernel/gentoo-kernel-bin-6.12.32", + "var/db/pkg/sys-kernel/gentoo-kernel-6.12.32", + ] { + std::fs::create_dir_all(root.join(dir)).unwrap(); + } + // Fixture boot layout: one default entry plus the loader config. + std::fs::create_dir_all(root.join("efi/EFI/Linux")).unwrap(); + std::fs::write( + root.join("efi/EFI/Linux/phoebus.conf"), + "title Phoebus\nlinux /vmlinuz-6.12.32\noptions root=/dev/mapper/cryptroot\n", + ) + .unwrap(); + std::fs::create_dir_all(root.join("efi/loader")).unwrap(); + std::fs::write( + root.join("efi/loader/loader.conf"), + "default phoebus.conf\n", + ) + .unwrap(); + // chroot build/install succeed (recording runner). + let out = build_tuned_kernel(&exec, root, true).unwrap(); + assert!(out.contains("separate boot entry"), "{out}"); + // The new entry exists and derives from the current one. + let tuned = std::fs::read_to_string(root.join("efi/EFI/Linux/phoebus-tuned.conf")).unwrap(); + assert!(tuned.contains("linux /vmlinuz-6.12.32"), "{tuned}"); + // The default was NOT switched: no test boot happened in this + // context, so the generic kernel stays the default. + let loader = std::fs::read_to_string(root.join("efi/loader/loader.conf")).unwrap(); + assert!(loader.contains("default phoebus.conf"), "{loader}"); + assert!(!loader.contains("phoebus-tuned"), "{loader}"); + assert!(out.contains("not made default yet"), "{out}"); + // The tuned fragment was written on top of the proven base. + let frag = + std::fs::read_to_string(root.join("etc/kernel/config.d/10-phoebus-tuned.config")) + .unwrap(); + assert!(frag.contains("CC_OPTIMIZE_FOR_PERFORMANCE"), "{frag}"); + // No second generic kernel was installed by the default path: the + // default install list is exactly the single bin package. + assert_only_generic_kernel(&["sys-kernel/gentoo-kernel-bin".to_string()]); + } } diff --git a/installer-rs/crates/phoebus-installer/src/bin/sys.rs b/installer-rs/crates/phoebus-installer/src/bin/sys.rs index 16d5285..55579a8 100644 --- a/installer-rs/crates/phoebus-installer/src/bin/sys.rs +++ b/installer-rs/crates/phoebus-installer/src/bin/sys.rs @@ -359,7 +359,9 @@ fn run() -> std::result::Result<(), Box> { sys info --legacy [--] | \ sys updates --legacy [--] | sys history --legacy | \ sys undo --legacy | sys enable --legacy | \ - sys choose --legacy" + sys choose --legacy | \ + sys build from source --legacy | \ + sys build tuned kernel --legacy" ); Err("unsupported instruction in legacy mode".into()) } diff --git a/installer-rs/crates/phoebus-installer/src/orchestrate.rs b/installer-rs/crates/phoebus-installer/src/orchestrate.rs index 7682e08..1dddffb 100644 --- a/installer-rs/crates/phoebus-installer/src/orchestrate.rs +++ b/installer-rs/crates/phoebus-installer/src/orchestrate.rs @@ -30,6 +30,13 @@ pub struct Installer { /// at finalize when `ai.reuse_ai_connection` is true (default). pending_ai_key: Option, pending_opencode_password: Option, + /// Measured per-stage durations for the running install (real elapsed + /// seconds, recorded by `install_observed` for the metrics report). + stage_seconds: Vec<(String, u64)>, + install_began: Option, + /// Peak observed target-filesystem use in MiB (best-effort per-stage + /// `df` samples; 0 means unmeasured, never fabricated). + peak_disk_mib: u64, } /// Receives stage transitions during [`Installer::install_observed`]. The GUI @@ -81,6 +88,9 @@ impl Installer { state: StorageState::default(), pending_ai_key: None, pending_opencode_password: None, + stage_seconds: Vec::new(), + install_began: None, + peak_disk_mib: 0, } } @@ -239,11 +249,20 @@ impl Installer { observer: &mut dyn InstallObserver, ) -> Result<()> { let steps = self.plan().steps.clone(); + self.install_began = Some(std::time::Instant::now()); + self.stage_seconds.clear(); + self.peak_disk_mib = 0; for step in steps { let name = step.name(); self.exec.logger.section(name); observer.stage_started(step); + // Best-effort peak-disk sample of the mounted target (skipped on + // dry-run or when the target is not yet mounted). + self.sample_peak_disk(); + let began = std::time::Instant::now(); let result = self.run_step(step, auth, luks_passphrase, user_password, root_password); + self.stage_seconds + .push((name.to_string(), began.elapsed().as_secs())); if let Err(e) = result { self.exec.logger.error(format!("stage failed: {name}: {e}")); observer.stage_finished(step, Some(&self.exec.redactor().redact(&e.to_string()))); @@ -284,6 +303,70 @@ impl Installer { } } + /// Best-effort per-stage sample of target-filesystem use for the peak-disk + /// figure. Never fails the install; when the target is not mounted (or on + /// dry-run) the sample is skipped and the metric stays unmeasured. + fn sample_peak_disk(&mut self) { + if self.exec.dry_run { + return; + } + let root = self.exec.root.clone(); + if !std::path::Path::new(&root).is_dir() { + return; + } + let root_str = root.to_string_lossy().to_string(); + let spec = + phoebus_executor::command::CommandSpec::new("metrics", "sample target use", "df") + .args(["-BM", "--output=used", root_str.as_str()]); + let Ok(out) = self.exec.run_capture(spec) else { + return; + }; + // Output is a header line plus e.g. ` 12345M`. + for line in String::from_utf8_lossy(&out.stdout).lines().skip(1) { + let digits: String = line.chars().filter(|c| c.is_ascii_digit()).collect(); + if let Ok(mib) = digits.parse::() { + if mib > self.peak_disk_mib { + self.peak_disk_mib = mib; + } + } + } + } + + /// Write the measured installation report into the target (before + /// unmount) and log it. Times are real; sizes are best-effort host-side + /// measurements of the target; anything unmeasurable is reported as + /// "not measured", never estimated silently. + fn write_install_metrics(&self) { + use phoebus_core::fastinstall::InstallMetrics; + let total = self + .install_began + .map(|t| t.elapsed().as_secs()) + .unwrap_or(0); + let root_str = self.exec.root.to_string_lossy().to_string(); + let installed_mib = du_mib(&self.exec, &root_str); + let distfiles = du_mib(&self.exec, &format!("{root_str}/var/cache/distfiles")); + let binpkgs = du_mib(&self.exec, &format!("{root_str}/var/cache/binpkgs")); + let download_mib = match (distfiles, binpkgs) { + (0, 0) => 0, + (d, b) => d + b, + }; + let metrics = InstallMetrics { + total_seconds: total, + download_mib, + peak_disk_mib: self.peak_disk_mib, + installed_mib, + per_stage_seconds: self.stage_seconds.clone(), + }; + let report = metrics.report(); + for line in report.lines() { + self.exec.logger.info(line); + } + let _ = self + .exec + .target() + .write("var/lib/phoebus/install-metrics.txt", report); + } + /// Re-check the selected target disk immediately before the destructive /// stage. An approval binds to a verified plan, not to a device name: the /// device may have disappeared, been mounted, become the live medium, or @@ -761,6 +844,15 @@ impl Installer { desktop::write_session_script(&self.exec, &self.config)?; desktop::configure_login(&self.exec, &self.config)?; desktop::configure_flatpak(&self.exec, &self.config)?; + // Fast defaults, target-only: system-wide Flatpaks from Flathub. + // The review UI already showed the delivery set (see + // `fastinstall::delivery_summary` in the plan); log it again here + // so progress output names the chosen method and expected work. + for line in phoebus_core::fastinstall::delivery_summary().lines() { + self.exec.logger.info(line); + } + desktop::install_flatpak_apps(&self.exec, &self.config)?; + desktop::provision_installed_welcome(&self.exec, &self.config)?; Ok(()) })(); self.exec.umount_chroot()?; @@ -823,6 +915,10 @@ impl Installer { // 4. Verify target integrity before snapshotting and unmounting. self.verify_installed_system()?; + // 4b. Record measured installation time and sizes. + self.sample_peak_disk(); + self.write_install_metrics(); + // 5. Initial known-good recovery point snapshot and boot entry. self.create_initial_recovery_point(auth); @@ -1068,6 +1164,61 @@ impl Installer { "sshd is enabled; it must stay disabled by default", )); } + // Fast defaults: the -bin atoms are installed, the Flatpak + // manifest names every default app, no duplicate Portage copies + // of Calibre/GIMP exist, and the installed welcome is present + // (script + launcher + autostart). The live-only installer entry + // must not be on the installed system. + for rel in [ + "usr/local/bin/phoebus-welcome", + "usr/share/applications/phoebus-welcome.desktop", + "usr/share/applications/phoebus-assistant.desktop", + "etc/xdg/autostart/phoebus-welcome.desktop", + "etc/xdg/quickshell/phoebus-welcome-installed/shell.qml", + "var/lib/phoebus/flatpaks-installed", + ] { + if !target.exists(rel) { + return Err(phoebus_executor::ExecError::operation( + "finalize", + "verify target", + format!("fast-default artifact {rel} missing"), + )); + } + } + for atom_dir in ["www-client/firefox-bin", "app-office/libreoffice-bin"] { + let vdb = std::path::Path::new(&self.exec.root) + .join("var/db/pkg") + .join(atom_dir); + let has_record = std::fs::read_dir(&vdb) + .map(|mut d| d.next().is_some()) + .unwrap_or(false); + if !has_record { + return Err(phoebus_executor::ExecError::operation( + "finalize", + "verify target", + format!("{atom_dir} has no package-database record in the target"), + )); + } + } + for dup in ["var/db/pkg/app-text/calibre", "var/db/pkg/media-gfx/gimp"] { + let dup_path = std::path::Path::new(&self.exec.root).join(dup); + if let Ok(mut d) = std::fs::read_dir(&dup_path) { + if d.next().is_some() { + return Err(phoebus_executor::ExecError::operation( + "finalize", + "verify target", + format!("duplicate Portage copy under {dup}; Calibre/GIMP must be Flatpak-only"), + )); + } + } + } + if target.exists("usr/share/applications/phoebus-install.desktop") { + return Err(phoebus_executor::ExecError::operation( + "finalize", + "verify target", + "live-only installer entry must not be on the installed system", + )); + } } self.exec @@ -1129,6 +1280,24 @@ impl Installer { } } +/// Best-effort host-side `du -sm` of a target path. Returns 0 (unmeasured) +/// when the path is missing or the tool fails; never fails the install. +fn du_mib(exec: &Exec, path: &str) -> u64 { + if exec.dry_run || !std::path::Path::new(path).exists() { + return 0; + } + let spec = phoebus_executor::command::CommandSpec::new("metrics", "measure target size", "du") + .args(["-sm", "--apparent-size", path]); + let Ok(out) = exec.run_capture(spec) else { + return 0; + }; + let text = String::from_utf8_lossy(&out.stdout); + text.split_whitespace() + .next() + .and_then(|n| n.parse::().ok()) + .unwrap_or(0) +} + /// Whether the target has an installed kernel image. /// /// With `layout=bls`, systemd's `kernel-install` places the kernel as @@ -1418,4 +1587,25 @@ mod tests { let err = inst.persist_ai_connection().unwrap_err().to_string(); assert!(!err.contains("sk-x"), "secret leaked into error: {err}"); } + + #[test] + fn install_metrics_report_is_written_and_truthful() { + let mut inst = installer("/dev/vda", VDA_OK); + inst.stage_seconds = vec![("desktop_install".into(), 300)]; + // The recording runner answers nothing: sizes stay unmeasured rather + // than fabricated. + inst.write_install_metrics(); + let text = std::fs::read_to_string( + std::path::Path::new(&inst.exec.root).join("var/lib/phoebus/install-metrics.txt"), + ) + .unwrap(); + assert!(text.contains("Installation measurements"), "{text}"); + assert!(text.contains("desktop_install"), "{text}"); + assert!(text.contains("not measured"), "{text}"); + // The plan review names the delivery method and expected work. + let review = inst.render_plan(); + assert!(review.contains("firefox-bin"), "{review}"); + assert!(review.contains("Flatpak system (Flathub)"), "{review}"); + assert!(review.contains("no local compile"), "{review}"); + } } diff --git a/installer-rs/crates/phoebus-installer/tests/golden/plan.txt b/installer-rs/crates/phoebus-installer/tests/golden/plan.txt index e293388..3cd2b9a 100644 --- a/installer-rs/crates/phoebus-installer/tests/golden/plan.txt +++ b/installer-rs/crates/phoebus-installer/tests/golden/plan.txt @@ -46,3 +46,12 @@ Software: Flatpak : yes Audio : pipewire AI assistant : no + + Fast defaults (prebuilt, verified; no local compile): + Firefox: www-client/firefox-bin [Portage -bin (signed)] — download ~120 MiB prebuilt binary, no local compile + LibreOffice: app-office/libreoffice-bin [Portage -bin (signed)] — download ~250 MiB prebuilt binary, no local compile + Calibre: com.calibre_ebook.calibre (Flathub, system) [Flatpak system (Flathub)] — download Flatpak runtime + app, no local compile + GIMP: org.gimp.GIMP (Flathub, system) [Flatpak system (Flathub)] — download Flatpak app, no local compile + Flatseal: com.github.tchx84.Flatseal (Flathub, system) [Flatpak system (Flathub)] — download Flatpak app, no local compile + Kernel: sys-kernel/gentoo-kernel-bin (generic) [generic kernel (signed)] — download prebuilt kernel + initramfs, no local compile + These choices shorten installation only and set no permanent preference. diff --git a/installer-rs/crates/phoebus-installer/tests/sys_cli.rs b/installer-rs/crates/phoebus-installer/tests/sys_cli.rs index 0837f24..f124c7e 100644 --- a/installer-rs/crates/phoebus-installer/tests/sys_cli.rs +++ b/installer-rs/crates/phoebus-installer/tests/sys_cli.rs @@ -869,3 +869,35 @@ fn mutating_catalogue_maintenance_requires_root() { assert!(stderr.contains("require root"), "{args:?} -> {stderr}"); } } + +#[test] +fn source_build_and_tuned_kernel_require_root_like_other_mutations() { + if effective_uid_is_root() { + return; + } + let root = tempfile::tempdir().expect("temp root"); + // The fast install choices never imply a saved preference: no lane flag + // is needed because the conversion target lane is explicit already. + let out = sys() + .arg("--root") + .arg(root.path()) + .args([ + "--legacy", + "--action", + r#"{"action":"convert_to_source","app":"firefox"}"#, + ]) + .output() + .expect("run sys"); + assert!(!out.status.success()); + let stderr = String::from_utf8_lossy(&out.stderr); + assert!(stderr.contains("require root"), "stderr: {stderr}"); + let out = sys() + .arg("--root") + .arg(root.path()) + .args(["build", "tuned", "kernel", "--legacy"]) + .output() + .expect("run sys"); + assert!(!out.status.success()); + let stderr = String::from_utf8_lossy(&out.stderr); + assert!(stderr.contains("require root"), "stderr: {stderr}"); +} diff --git a/installer/tests/vm/sys-acceptance.sh b/installer/tests/vm/sys-acceptance.sh index afb7a20..ce0dcf2 100755 --- a/installer/tests/vm/sys-acceptance.sh +++ b/installer/tests/vm/sys-acceptance.sh @@ -222,6 +222,16 @@ if [[ "$(id -u)" -ne 0 ]]; then run_expect_nonzero nonroot-depclean "require root" --legacy depclean run_expect_nonzero nonroot-apply-updates "require root" apply updates --legacy run_expect_nonzero nonroot-clean-cache "require root" clean cache --legacy + run_expect_nonzero nonroot-source-build "require root" --legacy --action '{"action":"convert_to_source","app":"firefox"}' + run_expect_nonzero nonroot-tuned-kernel "require root" --legacy build tuned kernel +fi + +# User-initiated source builds fail closed before any mutation, even as root: +# Brave has no trustworthy source route, and unknown apps are never guessed. +# Both are refused during effect resolution, before approval and commands. +if [[ "$(id -u)" -eq 0 ]]; then + json_nonzero source-brave "no trustworthy" '{"action":"convert_to_source","app":"brave"}' + json_nonzero source-unknown "no supported source build" '{"action":"convert_to_source","app":"definitely-not-an-app-xyz"}' fi # --- Optional mutating group (disposable VM only) -------------------------