phoebus_os/installer-rs/crates/phoebus-core/src/system.rs
Phoebus 7ebb616c99
Some checks are pending
ci / test (push) Waiting to run
feat(ai,desktop): unify administration layer, provision QML, and add conversation continuity
Unifies AI-first administration across the CLI (sys) and desktop GUI
(phoebus-assistant) through a shared service layer, fixes installed
desktop QML asset provisioning, adds Polkit elevation, and introduces
contextual conversation continuity.

- Extract phoebus_installer::service shared by CLI and desktop assistant bridge:
  - Reviewable plan staging (PreparedPlan) with SHA-256 cryptographic digests,
    15-minute TTL expiration, and replay prevention (PlanStore).
  - Pre-mutation system state revalidation binding execution strictly to the reviewed plan.
  - Honest recommendations displaying genuine provenance and unmeasured compile times.
  - Two-phase transaction logging (begin before mutation, finish with verification).
- Provision installed desktop assets and Polkit policy in phoebus-executor::desktop:
  - Added gui-apps/quickshell to canonical Mango desktop packages.
  - Embed 13 QML and policy files into target root under /usr/share/phoebus/assistant/.
  - Installed Polkit policy (club.phoebus.sys.policy) allowing unprivileged users to
    authenticate mutating plans via pkexec without blanket passwordless sudo.
- Eliminate startup freeze and polling in phoebus-assistant:
  - Multi-source update queries moved to on-demand tab switching.
  - Handshake timer reduced to one-shot 100ms with fast deterministic check.
- Add phoebus_installer::conversation:
  - Bounded 10-turn history with credential redaction.
  - Contextual follow-up resolution for comparisons, backend switching, and confirmation.
- Implement unified cross-source removal (plan_removal) preserving user data by default.
- Verified: all 486 workspace tests pass, release and crt-static builds succeed,
  and 23/23 VM acceptance cases pass (PASS=23 FAIL=0).
2026-09-24 17:21:16 -07:00

1900 lines
73 KiB
Rust

//! Pure generators and package sets shared by plan, validation and executor.
//!
//! Keeping these as pure functions makes the exact text written into the
//! target unit-testable and keeps parity with the proven Bash output.
use crate::config::{DesktopProfile, InstallConfig};
use crate::hardware::{CpuInfo, GpuVendor, HardwareReport};
// ---------------------------------------------------------------------------
// Package sets
// ---------------------------------------------------------------------------
/// Packages every Phoebus system needs beyond the stage3.
pub fn base_packages() -> Vec<&'static str> {
vec![
"app-admin/sudo",
"net-misc/networkmanager",
"sys-auth/polkit",
"sys-fs/cryptsetup",
"sys-fs/btrfs-progs",
]
}
/// Extra packages implied by the detected CPU.
pub fn kernel_extra_packages(cpu: &CpuInfo) -> Vec<&'static str> {
let mut out = vec!["sys-kernel/linux-firmware"];
if cpu.has_feature("vmx") {
out.push("sys-firmware/intel-microcode");
}
if cpu.has_feature("svm") {
out.push("sys-firmware/amd-ucode");
}
out
}
pub fn desktop_packages(profile: DesktopProfile) -> Vec<&'static str> {
match profile {
DesktopProfile::None => vec![],
DesktopProfile::Mango => mango_desktop_packages(),
}
}
/// The canonical desktop: Mango + DankMaterialShell, plus terminal and desktop portals.
pub fn mango_desktop_packages() -> Vec<&'static str> {
vec![
// Compositor & shell (GURU overlay)
"gui-wm/mangowm",
"gui-apps/dankmaterialshell",
"gui-apps/danksearch",
"gui-apps/quickshell",
"dev-vcs/git",
"sys-apps/accountsservice",
"sys-power/upower",
"kde-frameworks/kimageformats",
"x11-misc/pcmanfm",
"net-wireless/bluez",
"gnome-base/gnome-keyring",
// Wayland clipboard and screen capture
"gui-apps/wl-clipboard",
"gui-apps/grim",
"gui-apps/slurp",
"gui-libs/gtk-layer-shell",
// XWayland & Terminal
"x11-base/xwayland",
"x11-terms/kitty",
// System and Privilege
"net-misc/networkmanager",
"sys-auth/polkit",
"gnome-extra/polkit-gnome",
// Login & Greeter
"gui-libs/greetd",
"gui-apps/tuigreet",
// Desktop portals
"sys-apps/xdg-desktop-portal",
"sys-apps/xdg-desktop-portal-gtk",
"gui-libs/xdg-desktop-portal-wlr",
]
}
pub fn desktop_audio_packages() -> Vec<&'static str> {
vec!["media-video/pipewire", "media-video/wireplumber"]
}
pub fn network_target_services() -> Vec<&'static str> {
vec!["NetworkManager", "systemd-resolved"]
}
pub fn desktop_services(profile: DesktopProfile) -> Vec<&'static str> {
let mut out = vec!["NetworkManager", "systemd-resolved"];
if profile == DesktopProfile::Mango {
out.push("bluetooth");
}
out
}
/// Services enabled only after the desktop packages are installed (greetd is
/// not present until `desktop_install`).
pub fn desktop_login_services() -> Vec<&'static str> {
vec!["greetd"]
}
/// The services that should be enabled in the target, deduplicated.
pub fn target_services(config: &InstallConfig) -> Vec<String> {
let mut out: Vec<String> = Vec::new();
for svc in network_target_services()
.into_iter()
.chain(desktop_services(config.desktop.profile))
{
if !out.iter().any(|s| s == svc) {
out.push(svc.to_string());
}
}
out
}
/// Gentoo profile constants.
pub const PROFILE_SYSTEMD_MINIMAL: &str = "default/linux/amd64/23.0/systemd";
pub const PROFILE_SYSTEMD_DESKTOP: &str = "default/linux/amd64/23.0/desktop/systemd";
/// The Gentoo profile to use.
///
/// A minimal systemd profile is correct for a core/server install. A desktop
/// install should inherit from the supported stable desktop/systemd profile so
/// that X/Wayland/dbus/policykit USE defaults are consistent instead of being
/// reconstructed by hand. An explicit non-default profile always wins.
pub fn selected_profile(config: &InstallConfig) -> String {
let configured = &config.stage3.gentoo_profile;
if config.desktop.profile != DesktopProfile::None && configured == PROFILE_SYSTEMD_MINIMAL {
PROFILE_SYSTEMD_DESKTOP.to_string()
} else {
configured.clone()
}
}
// ---------------------------------------------------------------------------
// Portage configuration
// ---------------------------------------------------------------------------
pub fn makeopts(cores: u32, memory_mib: u64, build_jobs: Option<u32>) -> String {
let cores = if cores == 0 { 4 } else { cores };
let mem_jobs = std::cmp::max(1, memory_mib / 2048) as u32;
let derived = std::cmp::max(1, std::cmp::min(cores + 1, mem_jobs));
// An explicit request is still capped by available memory so a proposal
// cannot make the build exhaust RAM.
let jobs = build_jobs
.map(|j| std::cmp::max(1, std::cmp::min(j, mem_jobs)))
.unwrap_or(derived);
format!("-j{jobs} -l{cores}")
}
pub fn video_cards(hardware: &HardwareReport) -> String {
let nvidia = crate::nvidia::NvidiaPlan::for_hardware(hardware);
let mut cards: Vec<String> = Vec::new();
let push = |card: &str, cards: &mut Vec<String>| {
if !cards.iter().any(|c| c == card) {
cards.push(card.to_string());
}
};
for vendor in hardware.gpu_vendors() {
match vendor {
GpuVendor::Intel => push("intel", &mut cards),
GpuVendor::Amd => {
push("amdgpu", &mut cards);
push("radeonsi", &mut cards);
}
// An NVIDIA GPU the selected proprietary/open branch cannot serve
// uses the in-tree nouveau driver; it is never claimed as NVIDIA.
GpuVendor::Nvidia => {
if nvidia.supported {
push("nvidia", &mut cards);
} else {
push("nouveau", &mut cards);
}
}
GpuVendor::Unknown => {}
}
}
if cards.is_empty() {
cards.push("dummy".into());
}
cards.join(" ")
}
pub fn make_conf(config: &InstallConfig, hardware: &HardwareReport) -> String {
let mut o = String::new();
o.push_str(&format!(
"# {} Portage configuration\n",
config.system.distro_name
));
o.push_str("# Generated by the installer. Safe to edit.\n\n");
o.push_str("COMMON_FLAGS=\"-O2 -pipe -march=native\"\n");
o.push_str("CFLAGS=\"${COMMON_FLAGS}\"\n");
o.push_str("CXXFLAGS=\"${COMMON_FLAGS}\"\n");
o.push_str("FCFLAGS=\"${COMMON_FLAGS}\"\n");
o.push_str("FFLAGS=\"${COMMON_FLAGS}\"\n\n");
o.push_str(&format!(
"MAKEOPTS=\"{}\"\n",
makeopts(
hardware.cpu.cores,
hardware.memory_mib,
config.packages.build_jobs
)
));
o.push_str("EMERGE_DEFAULT_OPTS=\"--binpkg-respect-use=y --with-bdeps=y --backtrack=100\"\n\n");
o.push_str("ACCEPT_KEYWORDS=\"amd64\"\n");
o.push_str(&format!(
"ACCEPT_LICENSE=\"{}\"\n\n",
config.packages.accept_license
));
o.push_str("# Keep the global USE set close to the profile/binhost baseline so that\n");
o.push_str("# signed binaries can be reused; per-package USE lives in package.use.\n");
o.push_str("# dbus/policykit are part of the standard systemd desktop baseline and\n");
o.push_str("# are required by NetworkManager/wpa_supplicant and polkit respectively.\n");
o.push_str("USE=\"systemd dbus policykit\"\n");
o.push_str(&format!("VIDEO_CARDS=\"{}\"\n", video_cards(hardware)));
o.push_str("INPUT_DEVICES=\"libinput\"\n");
o.push_str("LINGUAS=\"en\"\n");
o
}
pub fn repos_conf() -> String {
let mut o = String::new();
o.push_str("[gentoo]\n");
o.push_str("location = /var/db/repos/gentoo\n");
o.push_str("sync-type = rsync\n");
o.push_str("sync-uri = rsync://rsync.gentoo.org/gentoo-portage\n");
o.push_str("auto-sync = yes\n");
o
}
/// The GURU community overlay, which packages Mango and DankMaterialShell.
///
/// GURU is git-only (no rsync), so `dev-vcs/git` must be installed before it
/// can be synced. It is a reviewed, signed-over-git community overlay; the
/// installer scopes `~amd64` to the specific packages rather than unmasking it.
pub const GURU_REPO_URI: &str = "https://anongit.gentoo.org/git/repo/proj/guru.git";
pub fn guru_repos_conf() -> String {
let mut o = String::new();
o.push_str("[guru]\n");
o.push_str("location = /var/db/repos/guru\n");
o.push_str("sync-type = git\n");
o.push_str(&format!("sync-uri = {GURU_REPO_URI}\n"));
// GURU is git-only and git is not installed yet during the first
// `emerge --sync`; syncing it explicitly after installing git keeps the
// initial main-tree sync from failing.
o.push_str("auto-sync = no\n");
o
}
/// Whether the selected desktop needs the GURU overlay.
pub fn uses_guru(config: &InstallConfig) -> bool {
config.desktop.profile == DesktopProfile::Mango
}
/// The reviewed `~amd64` keyword set for the Mango + DankMaterialShell stack.
///
/// These are the GURU packages and the GURU-only dependency (`scenefx`). The
/// comment is explicit that this is scoped, not a global `~amd64` switch, and
/// that Portage must not silently unmask further packages: an operator reviews
/// `emerge --pretend` output and extends the file deliberately.
pub fn accept_keywords_mango() -> String {
let mut o = String::new();
o.push_str("# Mango + DankMaterialShell: reviewed, scoped testing keywords.\n");
o.push_str("# This is NOT a global ~amd64 switch. GURU ships these as ~amd64.\n");
o.push_str("gui-wm/mangowm\n");
o.push_str("gui-apps/dankmaterialshell\n");
o.push_str("gui-apps/danksearch\n");
o.push_str("gui-apps/quickshell\n");
o.push_str("gui-libs/scenefx\n");
o.push_str("x11-misc/pcmanfm\n");
o.push_str("x11-libs/libfm\n");
o.push_str("dev-cpp/cpptrace\n");
o.push_str("dev-libs/libdwarf\n");
o
}
pub const BINHOST_OPENRC: &str =
"https://distfiles.gentoo.org/releases/amd64/binpackages/23.0/x86-64";
pub const BINHOST_HARDENED: &str =
"https://distfiles.gentoo.org/releases/amd64/binpackages/23.0/x86-64_hardened";
/// The official signed binhost matching a profile family.
///
/// Gentoo publishes binary packages for the OpenRC and hardened profiles. There
/// is no official systemd binhost, so a systemd system reuses binaries only for
/// packages whose USE matches the OpenRC/hardened build; systemd, polkit,
/// NetworkManager, dbus and util-linux still compile from source. Enabling
/// `systemd` in the global USE therefore does not force needless rebuilds of
/// packages that lack the flag, and this stays a scoped (non-`~amd64`) change.
pub fn binhost_for_profile(profile: &str) -> &'static str {
if profile.contains("hardened") {
BINHOST_HARDENED
} else {
BINHOST_OPENRC
}
}
/// The binhost URI actually used: an explicit configuration value, otherwise
/// the official host for the selected profile.
pub fn resolved_binhost_uri(config: &InstallConfig) -> String {
let configured = config.stage3.binhost_uri.trim();
if configured.is_empty() {
binhost_for_profile(&selected_profile(config)).to_string()
} else {
configured.to_string()
}
}
pub fn binrepos_conf(config: &InstallConfig) -> String {
let mut o = String::new();
o.push_str("[gentoo]\n");
o.push_str("priority = 1\n");
o.push_str(&format!("sync-uri = {}\n", resolved_binhost_uri(config)));
o.push_str("location = /var/cache/binhost/gentoo\n");
o.push_str("verify-signature = true\n");
o
}
pub fn package_use(config: &InstallConfig, hardware: &HardwareReport) -> String {
let mut o = String::new();
o.push_str(&format!(
"# {} installer policy\n",
config.system.distro_name
));
o.push_str("# Core system: systemd is the init system.\n");
o.push_str("# policykit is required by sys-auth/polkit[systemd];\n");
o.push_str("# cryptsetup builds systemd-cryptsetup for the encrypted root initramfs.\n");
o.push_str("sys-apps/systemd boot policykit cryptsetup\n");
o.push_str("# Distribution kernel + systemd-boot generation.\n");
o.push_str("# installkernel REQUIRED_USE: systemd-boot? ( systemd );\n");
o.push_str("# the `uki` flag is NOT set: this system uses the BLS layout with\n");
o.push_str("# uki_generator=none, so ukify is never invoked and its extra\n");
o.push_str("# dependencies (and binary-package mismatch) are avoided.\n");
o.push_str("sys-kernel/installkernel dracut systemd systemd-boot\n");
o.push_str("sys-apps/dbus systemd\n");
o.push_str("sys-auth/polkit systemd\n");
o.push_str("sys-apps/util-linux systemd\n");
o.push_str("# Avoid the Sphinx/Pillow documentation chain for base storage tools;\n");
o.push_str("# its truetype/introspection edges form a circular dependency.\n");
o.push_str("sys-fs/btrfs-progs -man\n");
o.push_str("sys-fs/cryptsetup -man\n");
o.push_str("dev-python/pillow -truetype\n");
o.push_str("# Networking\n");
o.push_str("net-misc/networkmanager systemd\n");
// Audio (PipeWire + WirePlumber are the standard stack). Emit pipewire
// once; the previous duplicate entry is gone. `systemd` is added only for
// the desktop profile that installs PipeWire.
o.push_str("# Audio (PipeWire + WirePlumber are the standard stack)\n");
let pipewire = if config.desktop.profile == DesktopProfile::None {
"media-video/pipewire sound-server".to_string()
} else {
"media-video/pipewire sound-server systemd".to_string()
};
o.push_str(&pipewire);
o.push('\n');
if config.desktop.profile != DesktopProfile::None {
o.push_str("# Desktop (Wayland-first, XWayland compatibility)\n");
o.push_str("x11-libs/cairo X\n");
o.push_str("x11-libs/gtk+ X wayland\n");
o.push_str("gui-libs/gtk wayland\n");
o.push_str("media-libs/libglvnd X\n");
o.push_str("x11-terms/kitty wayland\n");
}
if config.desktop.profile == DesktopProfile::Mango {
o.push_str("# Mango + DankMaterialShell desktop dependencies\n");
o.push_str("dev-cpp/cpptrace unwind\n");
o.push_str("sys-libs/zlib minizip\n");
}
// Scoped use entries from validated configuration/AI proposals.
if !config.packages.package_use.is_empty() {
o.push_str("# Accepted scoped USE changes\n");
for entry in &config.packages.package_use {
let prefix = if entry.enabled { "" } else { "-" };
o.push_str(&format!("{} {}{}\n", entry.atom, prefix, entry.flag));
}
}
// NVIDIA accelerated driver. Derived from the PCI device IDs, never from a
// name or an AI proposal; Maxwell/Pascal/Volta keep the proprietary branch
// (`-kernel-open`) while Turing and newer use NVIDIA's open modules.
let nvidia = crate::nvidia::NvidiaPlan::for_hardware(hardware);
let nvidia_use = nvidia.gentoo_package_use();
if !nvidia_use.is_empty() {
o.push_str("# NVIDIA accelerated driver (hardware-derived)\n");
for line in &nvidia_use {
o.push_str(line);
o.push('\n');
}
}
o
}
/// Scoped `package.mask` lines. Maxwell/Pascal/Volta must stay on the last
/// NVIDIA series that supports them (580); the next series is masked.
pub fn package_mask(config: &InstallConfig, hardware: &HardwareReport) -> String {
let _ = config;
let nvidia = crate::nvidia::NvidiaPlan::for_hardware(hardware);
let mask = nvidia.gentoo_package_mask();
let mut o = String::new();
if !mask.is_empty() {
o.push_str("# NVIDIA: proprietary branch required for Maxwell/Pascal/Volta.\n");
for line in &mask {
o.push_str(line);
o.push('\n');
}
}
o
}
pub fn accept_keywords_policy(hardware: &HardwareReport) -> String {
let mut o = String::new();
o.push_str("# Phoebus: scoped testing keywords for hardware/desktop enablement.\n");
o.push_str("# This is NOT a global ~amd64 switch.\n");
o.push_str("sys-kernel/linux-firmware\n");
// The NVIDIA driver is a hardware enabler; the keyword is scoped to the
// atom so the branch selection (and its pinned mask) stays deterministic.
let nvidia = crate::nvidia::NvidiaPlan::for_hardware(hardware);
for line in nvidia.gentoo_accept_keywords() {
o.push_str(&line);
o.push('\n');
}
o
}
pub fn install_conf() -> String {
let mut o = String::new();
o.push_str("# /etc/kernel/install.conf - Gentoo installkernel\n");
o.push_str("# When /etc/kernel/install.conf exists it is used INSTEAD of the\n");
o.push_str("# package default in /usr/lib/kernel/install.conf, so every required\n");
o.push_str("# generator must be listed here.\n");
o.push_str("# installkernel always requires uki_generator when dracut generates\n");
o.push_str("# the initramfs; \"none\" disables UKI assembly for the BLS layout.\n");
o.push_str("layout=bls\n");
o.push_str("initrd_generator=dracut\n");
o.push_str("uki_generator=none\n");
o
}
/// The generic dracut configuration.
///
/// It deliberately does **not** force the NVIDIA modules: `force_drivers`
/// naming a module that does not exist yet makes the first kernel build fail.
/// The NVIDIA fragment is written by the NVIDIA install stage, after the
/// driver's modules exist, and the initramfs is regenerated there.
pub fn dracut_conf(config: &InstallConfig) -> String {
let mut o = String::new();
o.push_str(&format!(
"# {} dracut configuration\n",
config.system.distro_name
));
o.push_str("# Generic (non-hostonly) initramfs for predictable boot behaviour.\n");
o.push_str("hostonly=\"no\"\n");
o.push_str("compress=\"zstd\"\n");
o.push_str("add_dracutmodules+=\" crypt btrfs \"\n");
o
}
/// The NVIDIA dracut fragment that forces the DRM/modeset modules (and their
/// firmware) into the initramfs, so the compositor never starts against a
/// modeset-less GPU. Only meaningful once the modules are installed.
pub fn nvidia_dracut_conf(hardware: &HardwareReport) -> Option<String> {
crate::nvidia::NvidiaPlan::for_hardware(hardware).dracut_conf()
}
pub fn kernel_profile_config(config: &InstallConfig) -> String {
let profile = config.kernel.profile.as_str();
let mut o = String::new();
o.push_str(&format!(
"# {} kernel profile: {profile}\n",
config.system.distro_name
));
o.push_str("# Applied on top of the Gentoo distribution kernel configuration.\n");
o.push_str("# The base configuration is intentionally kept: it supports common\n");
o.push_str("# peripherals the user may attach later.\n\n");
o.push_str("# Storage / modern filesystems and encryption\n");
for line in [
"CONFIG_BTRFS_FS=y",
"CONFIG_BTRFS_FS_POSIX_ACL=y",
"CONFIG_DM_CRYPT=y",
"CONFIG_DM_INTEGRITY=y",
"CONFIG_NVME_CORE=y",
"CONFIG_BLK_DEV_NVME=y",
] {
o.push_str(line);
o.push('\n');
}
o.push_str("\n# Input / USB / common buses\n");
for line in [
"CONFIG_HID_GENERIC=y",
"CONFIG_USB_HID=y",
"CONFIG_USB_XHCI_HCD=y",
] {
o.push_str(line);
o.push('\n');
}
o.push_str("\n# systemd / containers / virtualisation guests\n");
for line in [
"CONFIG_CGROUPS=y",
"CONFIG_NAMESPACES=y",
"CONFIG_VIRTIO=y",
"CONFIG_VIRTIO_PCI=y",
"CONFIG_VIRTIO_BLK=y",
"CONFIG_VIRTIO_NET=y",
] {
o.push_str(line);
o.push('\n');
}
o.push_str("\n# Compression used by Btrfs\n");
for line in ["CONFIG_ZSTD_COMPRESS=y", "CONFIG_ZSTD_DECOMPRESS=y"] {
o.push_str(line);
o.push('\n');
}
o
}
// ---------------------------------------------------------------------------
// Mango + DankMaterialShell (canonical Phoebus desktop)
// ---------------------------------------------------------------------------
/// The Mango session entry point written to `/usr/local/bin/phoebus-session-mango`.
///
/// It starts exactly one compositor (mango), one shell, notification, lock and
/// idle implementation (all provided by DankMaterialShell), and one polkit
/// agent (Quickshell's, enabled by the shell's `policykit` feature). It seeds
/// user configuration from the packaged defaults only when absent, so
/// upgrades never overwrite customization.
pub const PHOEBUS_MANGO_SESSION_SCRIPT: &str = r#"#!/bin/bash
# Phoebus Mango + DankMaterialShell session (generated by the installer).
#
# Hotkeys (dwm / dwl standard with DMS integration):
# Mod+Shift+Return terminal Mod+Return zoom (swap master)
# Mod+j / Mod+k focus next / prev window Mod+h / l shrink / grow master
# Mod+Shift+j / k swap window down / up Mod+i / d inc / dec master count
# Mod+1..9 switch workspace / tag Mod+Shift+1..9 move window to tag
# Mod+t / m / f tile / monocle / full Mod+Shift+Space toggle float
# Mod+Shift+c / q close window Mod+Shift+e exit session
# Mod+Space / Mod+p launcher (spotlight) Mod+V clipboard history
# Mod+N notifications Mod+a Phoebus assistant
# Mod+Alt+L lock screen
set -u
if [ -z "${XDG_RUNTIME_DIR:-}" ]; then
export XDG_RUNTIME_DIR="/run/user/$(id -u)"
fi
if [ ! -d "$XDG_RUNTIME_DIR" ]; then
echo "phoebus-session-mango: XDG_RUNTIME_DIR $XDG_RUNTIME_DIR is missing" >&2
exit 1
fi
# Do NOT set WAYLAND_DISPLAY before starting the compositor: wlroots would
# select its nested Wayland backend instead of the DRM backend and fail. The
# compositor creates the socket; it is discovered and exported afterwards (for
# the systemd user manager and the shell).
export XDG_SESSION_TYPE=wayland
export XDG_CURRENT_DESKTOP=mango
export XDG_SESSION_DESKTOP=mango
export MOZ_ENABLE_WAYLAND=1
export QT_QPA_PLATFORM=wayland
export QT_QPA_PLATFORMTHEME=gtk3
export QT_QPA_PLATFORMTHEME_QT6=gtk3
export GDK_BACKEND=wayland,x11
export ELECTRON_OZONE_PLATFORM_HINT=auto
export _JAVA_AWT_WM_NONREPARENTING=1
if [ -z "${DBUS_SESSION_BUS_ADDRESS:-}" ] && command -v dbus-run-session >/dev/null 2>&1; then
exec dbus-run-session -- "$0" "$@"
fi
# Seed user configuration from the packaged defaults exactly once; never
# overwrite what the user has customized.
mango_conf="$HOME/.config/mango/config.conf"
mkdir -p "$HOME/.config/mango/dms"
if [ ! -e "$mango_conf" ] && [ -r /etc/xdg/mango/config.conf ]; then
cp /etc/xdg/mango/config.conf "$mango_conf"
fi
# DMS manages these fragments; they must exist before Mango sources them.
for f in colors layout outputs; do
[ -e "$HOME/.config/mango/dms/$f.conf" ] || : > "$HOME/.config/mango/dms/$f.conf"
done
HELPERS=""
start_helper() {
"$@" >/dev/null 2>&1 &
HELPERS="$HELPERS $!"
}
cleanup() {
trap - EXIT INT TERM
for pid in $HELPERS; do
kill "$pid" 2>/dev/null || true
done
if command -v systemctl >/dev/null 2>&1; then
systemctl --user stop mango-session.target >/dev/null 2>&1 || true
fi
}
trap cleanup EXIT INT TERM
mango &
MANGO_PID=$!
# Discover the socket the compositor creates (don't constrain its name) and
# only then export WAYLAND_DISPLAY for the shell and the user manager.
socket=""
waited=0
while [ -z "$socket" ]; do
for candidate in "$XDG_RUNTIME_DIR"/wayland-*; do
if [ -S "$candidate" ]; then
socket="$candidate"
export WAYLAND_DISPLAY="$(basename "$candidate")"
break
fi
done
[ -n "$socket" ] && break
if ! kill -0 "$MANGO_PID" 2>/dev/null; then
echo "phoebus-session-mango: mango exited before creating a Wayland socket" >&2
exit 1
fi
if [ "$waited" -ge 100 ]; then
echo "phoebus-session-mango: timed out waiting for a Wayland socket" >&2
kill "$MANGO_PID" 2>/dev/null || true
exit 1
fi
sleep 0.1
waited=$((waited + 1))
done
# In virtual environments (e.g. QEMU/KVM Virtual-1), if the resolution defaulted
# to low VGA (<= 800x600), pick the best supported widescreen resolution.
if command -v wlr-randr >/dev/null 2>&1; then
for out in $(wlr-randr 2>/dev/null | awk '/^[A-Za-z0-9-]+ "/ {print $1}'); do
if wlr-randr --output "$out" 2>/dev/null | grep -qE "current.*(640x480|800x600)"; then
for m in 1280x768 1440x900 1920x1080 1024x768; do
if wlr-randr --output "$out" --mode "$m" 2>/dev/null; then
break
fi
done
fi
done
fi
# Export the graphical environment to the systemd user manager so user
# services (dms.service, portals) can reach the compositor.
if command -v dbus-update-activation-environment >/dev/null 2>&1; then
dbus-update-activation-environment --systemd \
WAYLAND_DISPLAY XDG_CURRENT_DESKTOP XDG_SESSION_TYPE XDG_RUNTIME_DIR \
QT_QPA_PLATFORM >/dev/null 2>&1 || true
fi
# Exactly one shell: DMS, bound to mango-session.target. Verify it actually
# started and fall back to a direct `dms run` if the user manager did not.
started=0
if command -v systemctl >/dev/null 2>&1 \
&& systemctl --user start mango-session.target >/dev/null 2>&1; then
sleep 0.5
if systemctl --user is-active --quiet dms.service 2>/dev/null; then
started=1
fi
fi
if [ "$started" = 0 ] && command -v dms >/dev/null 2>&1; then
start_helper dms run
elif [ "$started" = 0 ]; then
echo "phoebus-session-mango: dms not found; the shell will not start" >&2
fi
# Live medium only: open the branded welcome/installation launcher once the
# session is up. The marker exists only on the live rootfs, so an installed
# system never starts it. This never authorizes or starts disk changes.
if [ -e /etc/phoebus/live ] && command -v phoebus-welcome >/dev/null 2>&1; then
start_helper phoebus-welcome
fi
# Run until the compositor exits; the EXIT trap stops the shell and helpers.
wait "$MANGO_PID"
"#;
/// Packaged default Mango configuration. DMS writes its managed fragments under
/// `~/.config/mango/dms/`; this file only provides a sane baseline and the
/// DMS keybindings. It is copied to the user's config on first session start.
pub const MANGO_CONFIG_DEFAULT: &str = r#"# Phoebus default Mango configuration (packaged; copied once, then user-owned).
# DMS manages colors/layout/outputs in ~/.config/mango/dms/*.conf.
source=~/.config/mango/dms/colors.conf
source=~/.config/mango/dms/layout.conf
source=~/.config/mango/dms/outputs.conf
env=QT_QPA_PLATFORM,wayland
env=ELECTRON_OZONE_PLATFORM_HINT,auto
env=QT_QPA_PLATFORMTHEME,gtk3
border_radius=12
borderpx=0
focused_opacity=1.0
unfocused_opacity=0.9
gappih=5
gappiv=5
gappoh=5
gappov=5
shadows=1
shadow_only_floating=1
shadows_size=10
shadows_blur=15
# Master-stack layout defaults (dwm / dwl standard)
new_is_master=0
default_mfact=0.55
default_nmaster=1
tag_num=9
# Tag rules: default to master-and-stack tiling layout
tagrule=id:1,layout_name:tile
tagrule=id:2,layout_name:tile
tagrule=id:3,layout_name:tile
tagrule=id:4,layout_name:tile
tagrule=id:5,layout_name:tile
tagrule=id:6,layout_name:tile
tagrule=id:7,layout_name:tile
tagrule=id:8,layout_name:tile
tagrule=id:9,layout_name:tile
layerrule=noanim:1,layer_name:^dms
windowrule=isfloating:1,appid:^com.danklinux.dms$
windowrule=isfullscreen:1,title:^Install Phoebus OS$
# ===========================================================================
# Standard DWM / DWL Keybindings
# ===========================================================================
# Terminal & Launcher
bind=SUPER+SHIFT,Return,spawn,kitty
bind=SUPER,Return,zoom,
bind=SUPER,p,spawn,dms ipc call spotlight toggle
bind=SUPER,space,spawn,dms ipc call spotlight toggle
# Display resolution shortcuts (instant switch for VMs and external displays)
bind=SUPER+SHIFT,F12,spawn,sh -c 'out=$(wlr-randr 2>/dev/null | awk "/^[A-Za-z0-9-]+ / {print \$1; exit}"); [ -n "$out" ] && wlr-randr --output "$out" --mode 1920x1080'
bind=SUPER+SHIFT,F11,spawn,sh -c 'out=$(wlr-randr 2>/dev/null | awk "/^[A-Za-z0-9-]+ / {print \$1; exit}"); [ -n "$out" ] && wlr-randr --output "$out" --mode 1440x900'
bind=SUPER+SHIFT,F10,spawn,sh -c 'out=$(wlr-randr 2>/dev/null | awk "/^[A-Za-z0-9-]+ / {print \$1; exit}"); [ -n "$out" ] && wlr-randr --output "$out" --mode 1280x768'
bind=SUPER+SHIFT,F9,spawn,sh -c 'out=$(wlr-randr 2>/dev/null | awk "/^[A-Za-z0-9-]+ / {print \$1; exit}"); [ -n "$out" ] && wlr-randr --output "$out" --mode 1024x768'
# Focus navigation (dwm focusstack)
bind=SUPER,j,focusstack,next
bind=SUPER,k,focusstack,prev
bind=SUPER,Down,focusdir,down
bind=SUPER,Up,focusdir,up
bind=SUPER,Left,focusdir,left
bind=SUPER,Right,focusdir,right
# Window movement & swapping (dwm movestack / exchange)
bind=SUPER+SHIFT,j,exchange_client,down
bind=SUPER+SHIFT,k,exchange_client,up
bind=SUPER+SHIFT,Down,exchange_client,down
bind=SUPER+SHIFT,Up,exchange_client,up
bind=SUPER+SHIFT,Left,exchange_client,left
bind=SUPER+SHIFT,Right,exchange_client,right
# Master area sizing (dwm setmfact)
bind=SUPER,h,setmfact,-0.05
bind=SUPER,l,setmfact,+0.05
# Number of master windows (dwm incnmaster)
bind=SUPER,i,incnmaster,+1
bind=SUPER,d,incnmaster,-1
# Window close (dwm killclient: Mod+Shift+c and Mod+Shift+q)
bind=SUPER+SHIFT,c,killclient,
bind=SUPER+SHIFT,q,killclient,
# Layout switching
bind=SUPER,t,setlayout,tile
bind=SUPER,f,togglefullscreen,
bind=SUPER,m,setlayout,monocle
bind=SUPER+SHIFT,space,togglefloating,
bind=SUPER+SHIFT,t,switch_layout,
bind=SUPER+SHIFT,r,reload_config,
bind=SUPER,r,reload_config,
# Tag / Workspace switching (dwm tag navigation)
bind=SUPER,Tab,view,-1
bind=SUPER,1,view,1,0
bind=SUPER,2,view,2,0
bind=SUPER,3,view,3,0
bind=SUPER,4,view,4,0
bind=SUPER,5,view,5,0
bind=SUPER,6,view,6,0
bind=SUPER,7,view,7,0
bind=SUPER,8,view,8,0
bind=SUPER,9,view,9,0
bind=SUPER,0,view,0,0
# Move window to tag (dwm tag)
bind=SUPER+SHIFT,1,tag,1,0
bind=SUPER+SHIFT,2,tag,2,0
bind=SUPER+SHIFT,3,tag,3,0
bind=SUPER+SHIFT,4,tag,4,0
bind=SUPER+SHIFT,5,tag,5,0
bind=SUPER+SHIFT,6,tag,6,0
bind=SUPER+SHIFT,7,tag,7,0
bind=SUPER+SHIFT,8,tag,8,0
bind=SUPER+SHIFT,9,tag,9,0
bind=SUPER+SHIFT,0,tag,0,0
# Multi-tag toggle (dwm toggleview / toggletag)
bind=SUPER+CTRL,1,toggleview,1
bind=SUPER+CTRL,2,toggleview,2
bind=SUPER+CTRL,3,toggleview,3
bind=SUPER+CTRL,4,toggleview,4
bind=SUPER+CTRL,5,toggleview,5
bind=SUPER+CTRL,6,toggleview,6
bind=SUPER+CTRL,7,toggleview,7
bind=SUPER+CTRL,8,toggleview,8
bind=SUPER+CTRL,9,toggleview,9
bind=SUPER+CTRL+SHIFT,1,toggletag,1
bind=SUPER+CTRL+SHIFT,2,toggletag,2
bind=SUPER+CTRL+SHIFT,3,toggletag,3
bind=SUPER+CTRL+SHIFT,4,toggletag,4
bind=SUPER+CTRL+SHIFT,5,toggletag,5
bind=SUPER+CTRL+SHIFT,6,toggletag,6
bind=SUPER+CTRL+SHIFT,7,toggletag,7
bind=SUPER+CTRL+SHIFT,8,toggletag,8
bind=SUPER+CTRL+SHIFT,9,toggletag,9
# Monitor switching (dwm focusmon / tagmon)
bind=SUPER,comma,focusmon,left
bind=SUPER,period,focusmon,right
bind=SUPER+SHIFT,comma,tagmon,left
bind=SUPER+SHIFT,period,tagmon,right
# Mouse bindings (dwm mouse controls: move/resize/toggle float)
mousebind=SUPER,btn_left,moveresize,curmove
mousebind=SUPER,btn_right,moveresize,curresize
mousebind=SUPER,btn_middle,togglefloating,
# ===========================================================================
# Phoebus & DMS Desktop Integration
# ===========================================================================
bind=SUPER,v,spawn,dms ipc call clipboard toggle
bind=SUPER+CTRL,m,spawn,dms ipc call processlist focusOrToggle
bind=SUPER+CTRL,comma,spawn,dms ipc call settings focusOrToggle
bind=SUPER,n,spawn,dms ipc call notifications toggle
bind=SUPER,a,spawn,phoebus-assistant
# Security & Session
bind=SUPER+ALT,l,spawn,dms ipc call lock lock
bind=SUPER+SHIFT,e,quit,
# Audio
bind=NONE,XF86AudioRaiseVolume,spawn,dms ipc call audio increment 3
bind=NONE,XF86AudioLowerVolume,spawn,dms ipc call audio decrement 3
bind=NONE,XF86AudioMute,spawn,dms ipc call audio mute
# Brightness
bind=NONE,XF86MonBrightnessUp,spawn,dms ipc call brightness increment 5
bind=NONE,XF86MonBrightnessDown,spawn,dms ipc call brightness decrement 5
"#;
/// The systemd user target the DMS service is bound to. Using a target means
/// the shell starts and stops with the Mango session and does not run under
/// another desktop.
pub const MANGO_SESSION_TARGET: &str = r#"# Phoebus Mango session target (generated by the installer).
[Unit]
Description=Phoebus Mango + DankMaterialShell session
Requires=graphical-session.target
After=graphical-session.target
"#;
/// The `phoebus-assistant` launcher: launches the Quickshell desktop assistant
/// GUI if available, or falls back to a terminal for `sys ask`.
pub const PHOEBUS_ASSISTANT_SCRIPT: &str = r#"#!/bin/bash
# Open the Phoebus assistant. If graphical environment and quickshell are available,
# launch the desktop assistant GUI. Otherwise fall back to a terminal with `sys ask`.
set -u
if [ -n "${WAYLAND_DISPLAY:-}" ] || [ -n "${DISPLAY:-}" ]; then
if command -v quickshell >/dev/null 2>&1 \
&& [ -f /etc/xdg/quickshell/phoebus-assistant/shell.qml ]; then
exec quickshell --no-duplicate -c phoebus-assistant
fi
fi
if command -v kitty >/dev/null 2>&1; then
exec kitty --title "Phoebus Assistant" -e bash -lc \
'read -rp "Phoebus assistant request: " r; sudo sys ask "$r"; \
echo; read -rp "Press Enter to close"'
fi
echo "phoebus-assistant: neither quickshell nor kitty is available" >&2
exit 1
"#;
pub const PHOEBUS_ASSISTANT_DESKTOP_ENTRY: &str = r#"[Desktop Entry]
Name=Phoebus Assistant
Comment=AI-first system administration and assistance
Exec=/usr/local/bin/phoebus-assistant
Icon=system-help
Terminal=false
Type=Application
Categories=System;Settings;
Keywords=system;admin;assistant;ai;sys;install;update;
"#;
pub const PHOEBUS_POLKIT_POLICY: &str = r#"<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE policyconfig PUBLIC
"-//freedesktop//DTD PolicyKit Policy Configuration 1.0//EN"
"http://www.freedesktop.org/standards/PolicyKit/1.0/policyconfig.dtd">
<policyconfig>
<vendor>Phoebus OS</vendor>
<vendor_url>https://phoebus.club</vendor_url>
<icon_name>system-help</icon_name>
<action id="club.phoebus.sys.exec">
<description>Execute Phoebus system administration plan</description>
<message>Authentication is required to apply the system administration plan</message>
<defaults>
<allow_any>auth_admin</allow_any>
<allow_inactive>auth_admin</allow_inactive>
<allow_active>auth_admin_keep</allow_active>
</defaults>
<annotate key="org.freedesktop.policykit.exec.path">/usr/local/bin/sys</annotate>
<annotate key="org.freedesktop.policykit.exec.allow_gui">true</annotate>
</action>
</policyconfig>
"#;
pub fn assistant_desktop_assets() -> Vec<(&'static str, &'static str)> {
vec![
(
"usr/share/polkit-1/actions/club.phoebus.sys.policy",
PHOEBUS_POLKIT_POLICY,
),
(
"etc/xdg/quickshell/phoebus-assistant/shell.qml",
include_str!("../../../../installer/live/desktop/phoebus-assistant/shell.qml"),
),
(
"etc/xdg/quickshell/phoebus-assistant/AssistantBridge.qml",
include_str!(
"../../../../installer/live/desktop/phoebus-assistant/AssistantBridge.qml"
),
),
(
"etc/xdg/quickshell/phoebus-assistant/Common/qmldir",
include_str!("../../../../installer/live/desktop/common/qmldir"),
),
(
"etc/xdg/quickshell/phoebus-assistant/Common/Theme.qml",
include_str!("../../../../installer/live/desktop/common/Theme.qml"),
),
(
"etc/xdg/quickshell/phoebus-assistant/Common/Bridge.qml",
include_str!("../../../../installer/live/desktop/common/Bridge.qml"),
),
(
"etc/xdg/quickshell/phoebus-assistant/Common/PhoebusButton.qml",
include_str!("../../../../installer/live/desktop/common/PhoebusButton.qml"),
),
(
"etc/xdg/quickshell/phoebus-assistant/Common/PhoebusCard.qml",
include_str!("../../../../installer/live/desktop/common/PhoebusCard.qml"),
),
(
"etc/xdg/quickshell/phoebus-assistant/Common/PhoebusChip.qml",
include_str!("../../../../installer/live/desktop/common/PhoebusChip.qml"),
),
(
"etc/xdg/quickshell/phoebus-assistant/Common/PhoebusChoice.qml",
include_str!("../../../../installer/live/desktop/common/PhoebusChoice.qml"),
),
(
"etc/xdg/quickshell/phoebus-assistant/Common/PhoebusCombo.qml",
include_str!("../../../../installer/live/desktop/common/PhoebusCombo.qml"),
),
(
"etc/xdg/quickshell/phoebus-assistant/Common/PhoebusEmblem.qml",
include_str!("../../../../installer/live/desktop/common/PhoebusEmblem.qml"),
),
(
"etc/xdg/quickshell/phoebus-assistant/Common/PhoebusField.qml",
include_str!("../../../../installer/live/desktop/common/PhoebusField.qml"),
),
(
"etc/xdg/quickshell/phoebus-assistant/Common/PhoebusToggle.qml",
include_str!("../../../../installer/live/desktop/common/PhoebusToggle.qml"),
),
]
}
/// A Wayland session entry for `/usr/share/wayland-sessions`.
pub fn wayland_session_entry(profile: DesktopProfile) -> Option<(&'static str, String)> {
match profile {
DesktopProfile::Mango => Some((
"phoebus-mango.desktop",
"# Phoebus Mango session (generated by the installer).\n\
[Desktop Entry]\n\
Name=Phoebus (Mango + DarkMaterial)\n\
Comment=Mango compositor with DankMaterialShell\n\
Exec=/usr/local/bin/phoebus-session-mango\n\
TryExec=/usr/local/bin/phoebus-session-mango\n\
Type=Application\n\
DesktopNames=mango\n"
.to_string(),
)),
DesktopProfile::None => None,
}
}
/// The installed-system greetd configuration: authenticate, then run the
/// canonical Mango session. There is deliberately **no** `[initial_session]`:
/// the installed system always requires authentication (unlike the live ISO).
pub fn greetd_config(default_cmd: &str) -> String {
format!(
"# /etc/greetd/config.toml - Phoebus login (generated by the installer).\n\
# Authentication is always required; the live ISO uses a separate\n\
# autologin configuration.\n\
[terminal]\n\
vt = 7\n\
\n\
[default_session]\n\
command = \"tuigreet --time --remember --remember-session --sessions /usr/share/wayland-sessions --cmd {default_cmd}\"\n\
user = \"greeter\"\n"
)
}
/// The live-ISO greetd configuration: a live-only automatic login into the
/// desktop, with a greeter fallback. This must never be written to an installed
/// system.
pub fn greetd_config_live(live_user: &str, session_cmd: &str) -> String {
format!(
"# /etc/greetd/config.toml - Phoebus live session (LIVE ONLY).\n\
# Automatic login is intentional on the live medium and is not copied\n\
# to an installed system.\n\
[terminal]\n\
vt = 7\n\
\n\
[initial_session]\n\
command = \"{session_cmd}\"\n\
user = \"{live_user}\"\n\
\n\
[default_session]\n\
command = \"tuigreet --time --sessions /usr/share/wayland-sessions --cmd {session_cmd}\"\n\
user = \"greeter\"\n"
)
}
/// The session command used as the default desktop for a profile.
pub fn default_session_command(_profile: DesktopProfile) -> &'static str {
"/usr/local/bin/phoebus-session-mango"
}
/// The live ISO's unprivileged user.
pub const LIVE_USER: &str = "phoebus";
/// The live medium's passwordless privilege policy.
///
/// The recovery console keeps full root through the **password-authenticated**
/// `sudo` group (the live-only `phoebus`/`phoebus` credential, printed in
/// `installer/live/README.md`), so a serial or VT operator can still repair a
/// broken live session. Unattended escalation is limited to the two typed
/// brokers — the installer and `sys` — which validate actions before doing
/// anything. `systemctl` power actions are included because the welcome and
/// installer UIs offer them. There is no `ALL` command, no `sh -c`, and no
/// wildcard: a permitted program cannot become a general shell.
pub const LIVE_SUDOERS: &str = "\
# Phoebus live-medium privilege policy (generated).
# The recovery console authenticates with the live-only password; only the
# typed brokers below can escalate without a prompt. Do not add ALL or
# wildcards here.
phoebus ALL=(root) NOPASSWD: /usr/local/bin/phoebus-installer
phoebus ALL=(root) NOPASSWD: /usr/local/bin/sys
phoebus ALL=(root) NOPASSWD: /usr/bin/systemctl poweroff
phoebus ALL=(root) NOPASSWD: /usr/bin/systemctl reboot
";
/// `phoebus-nvidia-load`: live-only. It runs before the graphical session and
/// asks the installer for a deterministic decision based on the actual PCI
/// display devices and the bundled branch's capabilities. Systems without an
/// NVIDIA GPU keep the in-tree driver; an unsupported GPU explicitly binds
/// `nouveau`; fail-safe graphics loads nothing. A failed accelerated load is a
/// fallback, never a failed unit.
pub const PHOEBUS_NVIDIA_LOAD_SCRIPT: &str = r#"#!/bin/bash
# Select the live medium's display driver before greetd/Mango starts.
#
# `phoebus-installer --live-gpu-plan` classifies every PCI display controller
# and compares it with the bundled branch, then prints:
# action=load-nvidia -> load the bundled accelerated stack
# action=nouveau-fallback-> explicitly bind the in-tree nouveau driver
# action=no-device -> no NVIDIA GPU; leave auto-detection alone
# action=disabled -> fail-safe boot; load no NVIDIA module
#
# `blacklist nouveau` in /etc/modprobe.d stops nouveau *auto-binding* a
# supported GPU; it does not block an explicit `modprobe nouveau`, which is
# exactly what the fallback path uses. Debian's nvidia-kernel-dkms maps the
# upstream module names used here onto nvidia-current*.
set -u
BIN=/usr/local/bin/phoebus-installer
log() { logger -t phoebus-nvidia -- "$*" 2>/dev/null || true; }
plan="$("$BIN" --live-gpu-plan 2>/dev/null || true)"
action="$(printf '%s\n' "$plan" | sed -n 's/^action=//p' | head -n1)"
case "$action" in
load-nvidia)
if modprobe nvidia-drm; then
modprobe nvidia-uvm || log "nvidia-uvm did not load (not fatal)"
log "loaded the NVIDIA accelerated driver: $(printf '%s' "$plan" | tr '\n' ';')"
exit 0
fi
log "NVIDIA initialisation failed; falling back to nouveau"
modprobe nouveau || log "nouveau did not load either; run phoebus-gpu-report"
;;
nouveau-fallback)
log "NVIDIA GPU is not supported by the bundled branch; using nouveau: $(printf '%s' "$plan" | tr '\n' ';')"
modprobe nouveau || log "nouveau did not load; run phoebus-gpu-report"
;;
disabled)
log "fail-safe graphics requested; not loading the NVIDIA stack"
;;
*)
log "no NVIDIA display device; leaving driver auto-detection in charge"
;;
esac
exit 0
"#;
/// `phoebus-nvidia.service`: load the driver before greetd/Mango.
pub const PHOEBUS_NVIDIA_SERVICE: &str = r#"[Unit]
Description=Load the NVIDIA accelerated driver (Phoebus live)
Documentation=man:nvidia(4)
After=systemd-modules-load.service
Before=display-manager.service greetd.service
# Recovery intent is authoritative: the fail-safe entry sets
# phoebus.nvidia=off, so the unit does not even run there.
ConditionKernelCommandLine=!phoebus.nvidia=off
[Service]
Type=oneshot
RemainAfterExit=yes
ExecStart=/usr/local/bin/phoebus-nvidia-load
TimeoutStartSec=30
[Install]
WantedBy=multi-user.target
"#;
/// `phoebus-gpu-report`: live diagnostics when NVIDIA initialisation is
/// suspect. Read-only.
pub const PHOEBUS_GPU_REPORT_SCRIPT: &str = r#"#!/bin/bash
# Phoebus GPU diagnostics: what claimed the display, and did nvidia_drm come up?
set -u
echo "== display devices =="
lspci -nnk 2>/dev/null | grep -A3 -Ei 'VGA|3D controller|Display controller' || echo "(lspci unavailable)"
echo
echo "== loaded GPU modules =="
grep -E 'nvidia|nouveau' /proc/modules 2>/dev/null || echo "(neither nvidia nor nouveau is loaded)"
echo
echo "== nvidia_drm modeset =="
cat /sys/module/nvidia_drm/parameters/modeset 2>/dev/null || echo "(nvidia_drm not loaded)"
echo
echo "== nvidia-smi =="
nvidia-smi 2>&1 | head -20 || true
echo
echo "== recent kernel GPU messages =="
dmesg 2>/dev/null | grep -Ei 'nvidia|nouveau|drm' | tail -30 \
|| echo "(dmesg needs privileges; try: sudo dmesg | grep -Ei 'nvidia|nouveau|drm')"
"#;
/// A named desktop asset, so the live ISO build and the installer use exactly
/// the same configuration and session scripts. `None` for an unknown name.
pub fn desktop_asset(name: &str) -> Option<String> {
let default_cmd = default_session_command(DesktopProfile::Mango);
let live_cmd = "/usr/local/bin/phoebus-session-mango";
Some(match name {
"session-mango" => PHOEBUS_MANGO_SESSION_SCRIPT.to_string(),
"assistant" => PHOEBUS_ASSISTANT_SCRIPT.to_string(),
"install" => PHOEBUS_INSTALL_SCRIPT.to_string(),
"welcome" => PHOEBUS_WELCOME_SCRIPT.to_string(),
"mango-config" => MANGO_CONFIG_DEFAULT.to_string(),
"mango-session-target" => MANGO_SESSION_TARGET.to_string(),
"install-desktop" => PHOEBUS_INSTALL_DESKTOP_ENTRY.to_string(),
"greetd-installed" => greetd_config(default_cmd),
"greetd-live" => greetd_config_live(LIVE_USER, live_cmd),
// Live-only privilege policy (scoped, never NOPASSWD: ALL).
"live-sudoers" => LIVE_SUDOERS.to_string(),
// Live-only NVIDIA driver loading and diagnostics.
"nvidia-load" => PHOEBUS_NVIDIA_LOAD_SCRIPT.to_string(),
"nvidia-service" => PHOEBUS_NVIDIA_SERVICE.to_string(),
"gpu-report" => PHOEBUS_GPU_REPORT_SCRIPT.to_string(),
"wayland-session-mango" => wayland_session_entry(DesktopProfile::Mango)?.1,
// The brand system lives in `brand`; route the shared `--emit-asset`
// plumbing through it so the live build has one source of assets.
_ => return crate::brand::brand_asset(name),
})
}
/// `phoebus-install`: open the graphical installer frontend, falling back to
/// the deterministic TUI/CLI. It never starts a destructive operation by
/// itself: the plan, disk protection, AI requirement, credential handling and
/// the ERASE confirmation all stay in force. A second invocation never opens a
/// duplicate installer session.
pub const PHOEBUS_INSTALL_SCRIPT: &str = r#"#!/bin/bash
# Open the Phoebus installer. This only launches the installer UI; the user
# still reviews the plan, supplies credentials and confirms ERASE.
set -u
# Prevent duplicate installer sessions. Quickshell's --no-duplicate also
# guards this, but the check lets us tell the user why nothing opened.
if pgrep -f "quickshell.*phoebus-install" >/dev/null 2>&1; then
echo "The Phoebus installer is already open." >&2
exit 0
fi
# The graphical installer is the primary path; it needs a Wayland session.
if [ "${XDG_SESSION_TYPE:-}" = "wayland" ] || [ -n "${WAYLAND_DISPLAY:-}" ]; then
if command -v quickshell >/dev/null 2>&1 \
&& [ -f /etc/xdg/quickshell/phoebus-install/shell.qml ]; then
pkill -f "quickshell.*phoebus-welcome" 2>/dev/null || true
exec quickshell --no-duplicate -c phoebus-install
fi
fi
# Deterministic fallback (TUI, then CLI) works with no model and no Wayland.
conf="/etc/phoebus/install.conf"
args=()
[ -f "$conf" ] && args+=(--config "$conf")
installer=""
for candidate in /usr/local/bin/phoebus-installer phoebus-installer; do
if command -v "$candidate" >/dev/null 2>&1; then
installer="$candidate"
break
fi
done
if [ -z "$installer" ]; then
echo "phoebus-install: installer not found" >&2
exit 1
fi
# Re-entrant wrapper: the inner invocation (inside the terminal) just runs.
if [ "${1:-}" = "--in-terminal" ]; then
"$installer" "${args[@]}"
rc=$?
echo
read -rp "Press Enter to close" _ || true
exit "$rc"
fi
if command -v kitty >/dev/null 2>&1; then
exec kitty --title "Install Phoebus OS" -e "$0" --in-terminal
fi
if [ "$(id -u)" -eq 0 ]; then
exec "$installer" "${args[@]}"
else
exec sudo -n "$installer" "${args[@]}"
fi
"#;
/// `phoebus-welcome`: open (or focus, via the single-instance guard) the live
/// welcome window. Only installed on the live medium.
pub const PHOEBUS_WELCOME_SCRIPT: &str = r#"#!/bin/bash
# Live-medium welcome and installation launcher.
set -u
if pgrep -f "quickshell.*phoebus-welcome" >/dev/null 2>&1; then
exit 0
fi
if command -v quickshell >/dev/null 2>&1 \
&& [ -f /etc/xdg/quickshell/phoebus-welcome/shell.qml ]; then
exec quickshell --no-duplicate -c phoebus-welcome
fi
echo "phoebus-welcome: quickshell or the welcome config is missing" >&2
exit 1
"#;
/// The application entry that makes the installer discoverable in the desktop
/// launcher ("Install Phoebus OS"). It is live-medium only.
pub const PHOEBUS_INSTALL_DESKTOP_ENTRY: &str = "\
[Desktop Entry]\n\
Type=Application\n\
Name=Install Phoebus OS\n\
GenericName=System installer\n\
Comment=Install Phoebus OS to disk\n\
Exec=/usr/local/bin/phoebus-install\n\
TryExec=/usr/local/bin/phoebus-install\n\
Icon=phoebus\n\
Terminal=false\n\
Categories=System;Settings;\n\
Keywords=install;phoebus;setup;\n";
/// Btrfs mount options, matching the proven behavior.
pub fn btrfs_mount_opts(compress: &str, ssd: bool) -> String {
let mut opts = format!("noatime,compress={compress},space_cache=v2");
if ssd {
opts.push_str(",ssd");
}
opts
}
// ---------------------------------------------------------------------------
// fstab / crypttab / cmdline
// ---------------------------------------------------------------------------
pub fn fstab(
config: &InstallConfig,
root_source: &str,
efi_uuid: Option<&str>,
btrfs_opts: &str,
) -> String {
fstab_with_subvols(
config,
root_source,
efi_uuid,
btrfs_opts,
&config.storage.root_subvolume(),
"@var",
)
}
/// As `fstab`, but for an explicit root and `/var` subvolume. A rollback
/// rewrites the restored root's fstab so it mounts its own generation rather
/// than the name the snapshot happened to be captured under.
pub fn fstab_with_subvols(
config: &InstallConfig,
root_source: &str,
efi_uuid: Option<&str>,
btrfs_opts: &str,
root_subvol: &str,
var_subvol: &str,
) -> String {
let mut o = String::new();
o.push_str(&format!("# /etc/fstab: {}\n", config.system.distro_name));
o.push_str("# Generated by the installer. Use `findmnt --verify` to check.\n#\n");
o.push_str("# <file system>\t<mount point>\t<type>\t<options>\t<dump>\t<pass>\n");
if let Some(uuid) = efi_uuid {
o.push_str(&format!(
"UUID={uuid}\t{}\tvfat\tumask=0077,shortname=winnt\t0\t2\n",
config.storage.efi_mount
));
}
for (subvol, mountpoint, pass) in [
(root_subvol, "/", 1),
("@home", "/home", 2),
(var_subvol, "/var", 2),
("@snapshots", "/.snapshots", 2),
("@swap", "/swap", 2),
] {
o.push_str(&format!(
"{root_source}\t{mountpoint}\tbtrfs\t{btrfs_opts},subvol={subvol}\t0\t{pass}\n"
));
}
o.push_str("/swap/swapfile\tnone\tswap\tdefaults\t0\t0\n");
o
}
pub fn crypttab(name: &str, part_uuid: &str) -> String {
let mut o = String::new();
o.push_str("# /etc/crypttab: unlock the root volume at boot.\n");
o.push_str("# <name>\t<device>\t<keyfile>\t<options>\n");
o.push_str(&format!("{name} UUID={part_uuid} none luks,discard\n"));
o
}
/// The kernel command line.
///
/// `luks_uuid` is required when encryption is on; `root_source` is used for an
/// unencrypted Btrfs root (a UUID= reference).
pub fn kernel_cmdline(
config: &InstallConfig,
luks_uuid: Option<&str>,
root_source: &str,
) -> Result<String, String> {
kernel_cmdline_with_root(
config,
luks_uuid,
root_source,
&config.storage.root_subvolume(),
)
}
/// As `kernel_cmdline`, but selecting an explicit root subvolume. The explicit
/// `rootflags=subvol=` always wins over the Btrfs default subvolume, so a
/// rollback must rewrite it here as well as in the boot loader entry.
pub fn kernel_cmdline_with_root(
config: &InstallConfig,
luks_uuid: Option<&str>,
root_source: &str,
root_subvol: &str,
) -> Result<String, String> {
let mut cmdline = String::new();
if config.is_encrypted() {
let uuid = luks_uuid.ok_or_else(|| "missing LUKS UUID".to_string())?;
let name = &config.encryption.name;
// rd.luks.name=<uuid>=<name> makes dracut/systemd create the mapper
// under the configured name; rd.luks.uuid alone yields luks-<uuid>.
cmdline.push_str(&format!("rd.luks.name={uuid}={name} "));
cmdline.push_str(&format!("root=/dev/mapper/{name} "));
} else {
if root_source.is_empty() {
return Err("unencrypted cmdline requires an explicit root source".into());
}
cmdline.push_str(&format!("root={root_source} "));
}
cmdline.push_str(&format!(
"rootfstype=btrfs rootflags=subvol={root_subvol} rw quiet"
));
if !config.kernel.console.is_empty() {
cmdline.push(' ');
cmdline.push_str(&config.kernel.console);
}
Ok(cmdline)
}
pub fn locale_gen_line(locale: &str) -> String {
format!("{locale} UTF-8\n")
}
#[cfg(test)]
mod tests {
use super::*;
use crate::config::{DesktopProfile, Encryption, InstallConfig};
use crate::hardware::CpuInfo;
#[test]
fn base_packages_include_storage_tools() {
let pkgs = base_packages();
assert!(pkgs.contains(&"sys-fs/cryptsetup"));
assert!(pkgs.contains(&"sys-fs/btrfs-progs"));
assert!(pkgs.contains(&"net-misc/networkmanager"));
}
#[test]
fn kernel_extras_follow_cpu_features() {
let cpu = CpuInfo {
features: vec!["vmx".into()],
..Default::default()
};
let pkgs = kernel_extra_packages(&cpu);
assert!(pkgs.contains(&"sys-kernel/linux-firmware"));
assert!(pkgs.contains(&"sys-firmware/intel-microcode"));
assert!(!pkgs.contains(&"sys-firmware/amd-ucode"));
}
#[test]
fn fstab_mounts_all_subvolumes_including_swap() {
let cfg = InstallConfig::default();
let text = fstab(
&cfg,
"/dev/mapper/cryptroot",
Some("EFI-UUID"),
"noatime,compress=zstd:3,space_cache=v2",
);
assert!(text.contains("UUID=EFI-UUID\t/efi\tvfat"));
assert!(text.contains("\t/\tbtrfs\t"));
assert!(text.contains("subvol=@home"));
assert!(text.contains("subvol=@var"));
assert!(text.contains("subvol=@snapshots"));
assert!(text.contains("subvol=@swap"));
assert!(text.contains("/swap/swapfile\tnone\tswap"));
}
#[test]
fn crypttab_uses_partition_uuid() {
let text = crypttab("cryptroot", "0000-1111");
assert!(text.contains("cryptroot UUID=0000-1111 none luks,discard"));
}
#[test]
fn cmdline_uses_rd_luks_name() {
let cfg = InstallConfig::default();
let cmd = kernel_cmdline(&cfg, Some("0000-1111"), "").unwrap();
assert!(cmd.contains("rd.luks.name=0000-1111=cryptroot"));
assert!(cmd.contains("root=/dev/mapper/cryptroot"));
assert!(!cmd.contains("rd.luks.uuid="));
assert!(cmd.contains("console=tty0"));
}
#[test]
fn install_conf_has_uki_generator_none() {
let text = install_conf();
assert!(text.contains("layout=bls"));
assert!(text.contains("initrd_generator=dracut"));
assert!(text.contains("uki_generator=none"));
}
#[test]
fn desktop_includes_portals_for_flatpak_and_wayland() {
let pkgs = desktop_packages(DesktopProfile::Mango);
assert!(pkgs.contains(&"sys-apps/xdg-desktop-portal"));
assert!(pkgs.contains(&"sys-apps/xdg-desktop-portal-gtk"));
assert!(pkgs.contains(&"gui-libs/xdg-desktop-portal-wlr"));
assert!(desktop_packages(DesktopProfile::None).is_empty());
}
#[test]
fn desktop_none_has_no_x_use_block() {
let mut cfg = InstallConfig::default();
cfg.desktop.profile = DesktopProfile::None;
let text = package_use(&cfg, &crate::hardware::HardwareReport::default());
assert!(!text.contains("x11-libs/cairo X"));
cfg.desktop.profile = DesktopProfile::Mango;
let text = package_use(&cfg, &crate::hardware::HardwareReport::default());
assert!(text.contains("x11-libs/cairo X"));
assert!(text.contains("media-libs/libglvnd X"));
assert!(text.contains("sys-fs/btrfs-progs -man"));
assert!(text.contains("sys-fs/cryptsetup -man"));
assert!(text.contains("dev-python/pillow -truetype"));
}
#[test]
fn make_conf_does_not_globally_enable_testing() {
let cfg = InstallConfig::default();
let hw = crate::hardware::HardwareReport::default();
let text = make_conf(&cfg, &hw);
assert!(text.contains("ACCEPT_KEYWORDS=\"amd64\""));
assert!(!text.contains("~amd64"));
assert!(text.contains("--backtrack=100"));
}
#[test]
fn makeopts_caps_explicit_jobs_by_memory() {
assert_eq!(makeopts(8, 8192, None), "-j4 -l8");
assert_eq!(makeopts(8, 8192, Some(2)), "-j2 -l8");
assert_eq!(makeopts(8, 8192, Some(99)), "-j4 -l8");
assert_eq!(makeopts(0, 0, None), "-j1 -l4");
}
#[test]
fn package_use_is_clean_and_keeps_required_flags() {
let mut cfg = InstallConfig::default();
cfg.desktop.profile = DesktopProfile::Mango;
let text = package_use(&cfg, &crate::hardware::HardwareReport::default());
// Required boot/encryption/session flags stay.
assert!(text.contains("sys-apps/systemd boot policykit cryptsetup"));
assert!(text.contains("sys-kernel/installkernel dracut systemd systemd-boot"));
// BLS does not need the `uki` flag, and the empty wireplumber line and
// the duplicate pipewire line are gone.
assert!(!text.contains(" systemd-boot uki"));
assert!(!text.contains("media-video/wireplumber\n"));
assert_eq!(text.matches("media-video/pipewire").count(), 1);
assert!(text.contains("media-video/pipewire sound-server systemd"));
}
#[test]
fn package_use_appends_validated_entries() {
let mut cfg = InstallConfig::default();
cfg.packages.package_use.push(crate::config::PackageUse {
atom: "www-client/firefox".into(),
flag: "wayland".into(),
enabled: false,
});
let text = package_use(&cfg, &crate::hardware::HardwareReport::default());
assert!(text.contains("www-client/firefox -wayland"));
}
#[test]
fn binhost_selection_follows_profile() {
assert_eq!(binhost_for_profile(PROFILE_SYSTEMD_MINIMAL), BINHOST_OPENRC);
assert_eq!(
binhost_for_profile("default/linux/amd64/23.0/hardened/systemd"),
BINHOST_HARDENED
);
let mut cfg = InstallConfig::default();
cfg.stage3.binhost_uri.clear();
cfg.stage3.gentoo_profile = "default/linux/amd64/23.0/hardened/systemd".into();
assert_eq!(resolved_binhost_uri(&cfg), BINHOST_HARDENED);
cfg.stage3.binhost_uri = "https://example.invalid/binpkgs".into();
assert_eq!(
resolved_binhost_uri(&cfg),
"https://example.invalid/binpkgs"
);
assert!(binrepos_conf(&cfg).contains("verify-signature = true"));
}
#[test]
fn desktop_selects_desktop_systemd_profile() {
let mut cfg = InstallConfig::default();
// The default profile is a desktop, so it selects the desktop profile.
assert_eq!(cfg.desktop.profile, DesktopProfile::Mango);
assert_eq!(selected_profile(&cfg), PROFILE_SYSTEMD_DESKTOP);
// An explicit `none` keeps the minimal systemd profile.
cfg.desktop.profile = DesktopProfile::None;
assert_eq!(selected_profile(&cfg), PROFILE_SYSTEMD_MINIMAL);
// An explicit non-default Gentoo profile is respected.
cfg.stage3.gentoo_profile = "default/linux/amd64/23.0/hardened/systemd".into();
assert_eq!(
selected_profile(&cfg),
"default/linux/amd64/23.0/hardened/systemd"
);
}
#[test]
fn services_deduplicated() {
let mut cfg = InstallConfig::default();
cfg.desktop.profile = DesktopProfile::Mango;
let svcs = target_services(&cfg);
assert!(svcs.contains(&"NetworkManager".to_string()));
assert!(svcs.contains(&"bluetooth".to_string()));
let count = svcs.iter().filter(|s| *s == "NetworkManager").count();
assert_eq!(count, 1);
}
#[test]
fn encrypted_cmdline_requires_uuid() {
let cfg = InstallConfig::default();
assert_eq!(cfg.encryption.mode, Encryption::Luks2);
assert!(kernel_cmdline(&cfg, None, "").is_err());
}
#[test]
fn mango_profile_selects_guru_stack() {
let pkgs = desktop_packages(DesktopProfile::Mango);
assert!(pkgs.contains(&"gui-wm/mangowm"));
assert!(pkgs.contains(&"gui-apps/dankmaterialshell"));
assert!(pkgs.contains(&"gui-apps/danksearch"));
assert!(pkgs.contains(&"dev-vcs/git"));
// Standalone dwl and helpers must not be present.
assert!(!pkgs.contains(&"gui-wm/dwl"));
assert!(!pkgs.contains(&"gui-apps/waybar"));
assert!(!pkgs.contains(&"gui-apps/wofi"));
assert!(!pkgs.contains(&"gui-apps/mako"));
assert!(!pkgs.contains(&"gui-apps/swaybg"));
assert!(!pkgs.contains(&"gui-apps/swayidle"));
assert!(!pkgs.contains(&"gui-apps/swaylock"));
// Portals and the shared Wayland stack are present.
assert!(pkgs.contains(&"sys-apps/xdg-desktop-portal-gtk"));
assert!(pkgs.contains(&"gui-libs/xdg-desktop-portal-wlr"));
// An explicit Mango profile selects the desktop/systemd Gentoo profile.
let mut cfg = InstallConfig::default();
cfg.desktop.profile = DesktopProfile::Mango;
assert_eq!(selected_profile(&cfg), PROFILE_SYSTEMD_DESKTOP);
assert!(uses_guru(&cfg));
assert!(target_services(&cfg).contains(&"bluetooth".to_string()));
}
#[test]
fn mango_keywords_are_scoped_not_global() {
let text = accept_keywords_mango();
for atom in [
"gui-wm/mangowm",
"gui-apps/dankmaterialshell",
"gui-apps/quickshell",
"gui-libs/scenefx",
"x11-misc/pcmanfm",
"x11-libs/libfm",
"dev-cpp/cpptrace",
"dev-libs/libdwarf",
] {
assert!(text.contains(atom), "missing {atom}");
}
assert!(!text.contains("*/*"));
// No bare global keyword line; `~amd64` may only appear in comments.
assert!(!text.lines().any(|l| l.trim() == "~amd64"));
assert!(!text.contains("ACCEPT_KEYWORDS"));
let repos = guru_repos_conf();
assert!(repos.contains("[guru]"));
assert!(repos.contains("sync-type = git"));
assert!(repos.contains("anongit.gentoo.org"));
}
#[test]
fn mango_session_contract() {
let script = PHOEBUS_MANGO_SESSION_SCRIPT;
// Exactly one compositor and one shell.
assert!(script.contains("mango &"));
assert!(script.contains("dms run"));
assert!(script.contains("mango-session.target"));
// The dwl helpers must never start in the Mango session.
for helper in ["waybar", "mako", "swaybg", "swayidle", "swaylock"] {
assert!(
!script.contains(helper),
"Mango session must not start the dwl helper {helper}"
);
}
// User config is seeded, never overwritten.
assert!(script.contains("if [ ! -e \"$mango_conf\" ]"));
assert!(script.contains("dbus-update-activation-environment --systemd"));
assert!(script.contains("wait \"$MANGO_PID\""));
// WAYLAND_DISPLAY must not be set before the compositor starts, or
// wlroots selects its nested Wayland backend instead of DRM.
let mango_at = script.find("mango &").unwrap();
let wayland_at = script.find("WAYLAND_DISPLAY=").unwrap();
assert!(
wayland_at > mango_at,
"WAYLAND_DISPLAY must only be set after mango starts"
);
let config = MANGO_CONFIG_DEFAULT;
assert!(config.contains("dms ipc call lock lock"));
assert!(config.contains("dms ipc call spotlight toggle"));
assert!(config.contains("XF86AudioRaiseVolume"));
assert!(config.contains("XF86MonBrightnessDown"));
assert!(config.contains("phoebus-assistant"));
assert!(config.contains("source=~/.config/mango/dms/"));
assert!(config.contains("focusstack,next"));
assert!(config.contains("focusstack,prev"));
assert!(config.contains("zoom,"));
assert!(config.contains("setmfact,-0.05"));
assert!(config.contains("setmfact,+0.05"));
assert!(config.contains("killclient,"));
assert!(config.contains("view,1,0"));
assert!(config.contains("tag,1,0"));
assert!(config.contains("setlayout,tile"));
assert!(config.contains("togglefloating,"));
let (name, entry) = wayland_session_entry(DesktopProfile::Mango).unwrap();
assert_eq!(name, "phoebus-mango.desktop");
assert!(entry.contains("Exec=/usr/local/bin/phoebus-session-mango"));
}
#[test]
fn installed_login_authenticates_and_defaults_to_mango() {
let cfg = greetd_config("/usr/local/bin/phoebus-session-mango");
assert!(
cfg.parse::<toml::Value>().is_ok(),
"greetd_config must produce valid TOML"
);
assert!(cfg.contains("[terminal]"));
assert!(cfg.contains("vt = 7"));
assert!(cfg.contains("[default_session]"));
// The installed system must never autologin.
assert!(!cfg.contains("[initial_session]"));
assert!(cfg.contains("tuigreet"));
assert!(cfg.contains("--sessions /usr/share/wayland-sessions"));
assert!(cfg.contains("--cmd /usr/local/bin/phoebus-session-mango"));
// The live configuration is separate and does autologin.
let live = greetd_config_live("phoebus", "/usr/local/bin/phoebus-session-mango");
assert!(
live.parse::<toml::Value>().is_ok(),
"greetd_config_live must produce valid TOML"
);
assert!(live.contains("[initial_session]"));
assert!(live.contains("user = \"phoebus\""));
assert!(live.contains("[default_session]"));
assert_eq!(
default_session_command(DesktopProfile::Mango),
"/usr/local/bin/phoebus-session-mango"
);
assert_eq!(
default_session_command(DesktopProfile::None),
"/usr/local/bin/phoebus-session-mango"
);
}
#[test]
fn install_launcher_is_discoverable_but_not_automatic() {
assert!(PHOEBUS_INSTALL_DESKTOP_ENTRY.contains("Name=Install Phoebus"));
assert!(PHOEBUS_INSTALL_DESKTOP_ENTRY.contains("Exec=/usr/local/bin/phoebus-install"));
// It may run the installer UI, never an unattended destructive install.
assert!(!PHOEBUS_INSTALL_SCRIPT.contains("--yes"));
assert!(!PHOEBUS_INSTALL_SCRIPT.contains("--install"));
assert!(!PHOEBUS_INSTALL_SCRIPT.contains("--no-ai"));
assert!(PHOEBUS_INSTALL_SCRIPT.contains("sudo -n"));
}
#[test]
fn desktop_assets_are_shared_between_live_and_installed() {
assert!(desktop_asset("session-mango").unwrap().contains("dms run"));
assert!(desktop_asset("mango-config")
.unwrap()
.contains("dms ipc call"));
// The live and installed greetd configs differ only in autologin.
assert!(desktop_asset("greetd-live")
.unwrap()
.contains("[initial_session]"));
assert!(!desktop_asset("greetd-installed")
.unwrap()
.contains("[initial_session]"));
assert!(desktop_asset("greetd-installed")
.unwrap()
.contains("phoebus-session-mango"));
assert!(desktop_asset("wayland-session-dwl").is_none());
assert!(desktop_asset("session-dwl").is_none());
assert!(desktop_asset("install-desktop")
.unwrap()
.contains("Install Phoebus"));
assert!(desktop_asset("does-not-exist").is_none());
}
#[test]
fn live_sudoers_is_scoped_and_valid() {
let sudoers = desktop_asset("live-sudoers").unwrap();
assert!(sudoers.contains("/usr/local/bin/phoebus-installer"));
assert!(sudoers.contains("/usr/local/bin/sys"));
assert!(sudoers.contains("systemctl poweroff"));
// The unattended rule must never be a general root escape.
assert!(!sudoers.contains("NOPASSWD: ALL"), "{sudoers}");
assert!(!sudoers.contains("(ALL)"), "{sudoers}");
assert!(!sudoers.contains('*'), "{sudoers}");
assert!(sudoers.ends_with('\n'));
// `visudo` is the authority on syntax; validate when the host has it.
let Ok(mut child) = std::process::Command::new("visudo")
.args(["-cf", "/dev/stdin"])
.stdin(std::process::Stdio::piped())
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::piped())
.spawn()
else {
return;
};
{
use std::io::Write;
if let Some(stdin) = child.stdin.as_mut() {
let _ = stdin.write_all(sudoers.as_bytes());
}
}
if let Ok(out) = child.wait_with_output() {
assert!(
out.status.success(),
"visudo rejected the live policy: {}",
String::from_utf8_lossy(&out.stderr)
);
}
}
#[test]
fn live_nvidia_assets_are_bounded_and_ordered_before_greetd() {
let load = desktop_asset("nvidia-load").unwrap();
// The decision comes from the installer, not a vendor-name grep.
assert!(load.contains("--live-gpu-plan"));
assert!(load.contains("nouveau-fallback"));
assert!(load.contains("modprobe nvidia-drm"));
// A failed accelerated load must not fail the boot unit.
assert!(!load.contains("exit 1"));
let service = desktop_asset("nvidia-service").unwrap();
assert!(service.contains("Before=display-manager.service greetd.service"));
assert!(service.contains("ConditionKernelCommandLine=!phoebus.nvidia=off"));
assert!(service.contains("ExecStart=/usr/local/bin/phoebus-nvidia-load"));
let report = desktop_asset("gpu-report").unwrap();
assert!(report.contains("nvidia-smi"));
assert!(report.contains("nvidia_drm"));
}
fn nvidia_hw(id: &str) -> HardwareReport {
let mut hw = HardwareReport::default();
hw.gpus.push(crate::hardware::GpuInfo {
vendor: GpuVendor::Nvidia,
description: id.into(),
pci_id: Some(id.into()),
pci_address: None,
});
hw
}
#[test]
fn nvidia_turing_uses_open_modules_and_scoped_keywords() {
let cfg = InstallConfig::default();
let hw = nvidia_hw("10de:1e04");
assert_eq!(video_cards(&hw), "nvidia");
let use_text = package_use(&cfg, &hw);
assert!(use_text.contains("x11-drivers/nvidia-drivers dist-kernel kernel-open"));
assert!(package_mask(&cfg, &hw).trim().is_empty());
assert!(accept_keywords_policy(&hw).contains("x11-drivers/nvidia-drivers ~amd64"));
// The generic initramfs must not force modules that do not exist yet;
// the NVIDIA fragment is written once the driver is installed.
assert!(!dracut_conf(&cfg).contains("force_drivers"));
let nvidia = nvidia_dracut_conf(&hw).expect("nvidia dracut fragment");
assert!(nvidia.contains("force_drivers+="));
assert!(nvidia.contains("nvidia_drm"));
}
#[test]
fn nvidia_pascal_uses_proprietary_and_is_capped_after_580() {
let cfg = InstallConfig::default();
let hw = nvidia_hw("10de:1b81");
let use_text = package_use(&cfg, &hw);
assert!(use_text.contains("x11-drivers/nvidia-drivers dist-kernel -kernel-open"));
assert_eq!(
package_mask(&cfg, &hw),
"# NVIDIA: proprietary branch required for Maxwell/Pascal/Volta.\n\
>=x11-drivers/nvidia-drivers-581\n"
);
}
#[test]
fn nvidia_kepler_uses_nouveau_not_a_claim_of_nvidia() {
let cfg = InstallConfig::default();
let hw = nvidia_hw("10de:0fc0");
assert_eq!(video_cards(&hw), "nouveau");
assert!(!package_use(&cfg, &hw).contains("nvidia-drivers"));
assert!(package_mask(&cfg, &hw).is_empty());
assert!(!accept_keywords_policy(&hw).contains("nvidia-drivers"));
assert!(nvidia_dracut_conf(&hw).is_none());
assert!(!dracut_conf(&cfg).contains("nvidia"));
}
#[test]
fn hybrid_nvidia_keeps_the_integrated_gpu_in_video_cards() {
let mut hw = nvidia_hw("10de:2482");
hw.gpus.push(crate::hardware::GpuInfo {
vendor: GpuVendor::Intel,
description: "Intel UHD".into(),
pci_id: Some("8086:9a60".into()),
pci_address: None,
});
let cards = video_cards(&hw);
assert!(cards.contains("nvidia"));
assert!(cards.contains("intel"));
}
}