feat(workstation): Mango apps, Zsh, cursor, ccache, AI handoff, startup check, assistant themes
Some checks are pending
ci / test (push) Waiting to run

This commit is contained in:
Phoebus 2026-09-26 10:08:47 -07:00
parent 4f36b056b4
commit ccc868b762
18 changed files with 1891 additions and 65 deletions

View file

@ -3,6 +3,73 @@
All notable changes are recorded here. The authoritative history is `git log`; All notable changes are recorded here. The authoritative history is `git log`;
this file is the curated, human-readable summary. this file is the curated, human-readable summary.
## 2026-09-26 — Workstation experience (apps, shell, AI handoff, assistant)
- **Mango workstation defaults.** The Mango profile now installs the full
requested set with exact Gentoo atoms (no silent omit/substitute):
`app-editors/emacs`, `app-office/libreoffice`, `media-gfx/swayimg` (GURU),
`media-video/mpv`, `app-misc/fastfetch`, `sys-process/htop`,
`app-editors/neovim`, `app-text/zathura` + `zathura-pdf-mupdf`,
`app-editors/nano`, `www-client/firefox`, `www-client/brave-browser`
(stable, scoped `another-brave-overlay`), `mail-client/thunderbird`,
`app-text/calibre`, `net-p2p/transmission` (gtk), `media-sound/pavucontrol`,
`media-gfx/gimp`, `net-print/cups` (local only), `gnome-extra/nemo`
(default file manager, replaces pcmanfm), `sci-calculators/qalculate-gtk`,
`net-irc/hexchat`, `net-misc/openssh` (client+server, sshd disabled).
Kitty stays the terminal; `st` is never installed. Headless (`none`) stays
lean (no desktop apps). Unit-tested (`workstation_defaults_*`).
- **Brave via reviewed overlay.** Stable `www-client/brave-browser` only
(never beta/nightly, masked). The overlay is scoped
(`another-brave-overlay.conf` + `brave-scope` mask); the git pin
(`PHOEBUS_BRAVE_PIN`, 40-hex) is validated before any network use and a
missing/placeholder pin refuses with the exact blocker instead of silently
using Flatpak. Upstream release + checksum verification happens in the
ebuild fetch path (fail-closed). Live VM verification is blocked (needs
network + a pinned revision at ISO build time + 60 GiB target).
- **Zsh, cursor, ccache.** New users get `/bin/zsh`; root keeps `/bin/bash`;
`/bin/sh` is untouched. A maintained default `~/.zshrc` (completion,
autosuggestions, syntax-highlighting, history search, readable prompt) is
seeded for skel + new users from packaged plugins only, preserving existing
files. One cursor theme (`x11-themes/vanilla-dmz-xcursors`, Vanilla-DMZ,
size 24) is applied across Mango/wlroots, XWayland, GTK, Qt/Quickshell,
DMS and the greeter. Default Portage ccache is on: `dev-util/ccache` in
base, `FEATURES="ccache sandbox usersandbox"`, `CCACHE_SIZE="2G"`.
- **AI connection handoff.** The installer GUI offers "Use this model
connection after installation" (selected by default, bound to
`ai.reuse_ai_connection`). When selected, finalize writes a direct-provider
key into the new user's `~/.config/phoebus/ai.key` (symlink-safe,
0700/0600, user-owned); only the path enters `assistant.conf`.
OpenCode/local follow their actual requirements; a live-VM-only endpoint is
never called "connected" after reboot. The installed `sys ask` and desktop
assistant share `ai_setup::resolve`. Missing/invalid/unreadable/opted-out
credentials show a setup action + the real error, never a false
"Connected" and never "Approve & Execute" without a plan id/digest.
Unit-tested (0600/0700, symlink refusal, no secret in errors).
- **Startup system check.** New `evaluate_startup_checks`/`summarize_checks`:
blur is an optional unsupported visual effect when Mango/DMS lack it;
`sys-power/power-profiles-daemon` (stable 0.30) is installed + enabled with
D-Bus `net.hadess.PowerProfiles` verified and `sys-power/tlp` masked as a
conflict; `media-sound/cava` (stable, `pipewire` USE) and
`gui-apps/matugen` (GURU) are installed for DMS. Zero errors + warnings
never says "All checks passed."
- **Assistant dark by default + responsive.** Dark (charcoal/warm-white/amber)
is the default with a light mode + persisted selection. Missing
`Theme.background/text/primary/card/cardHover/accent` aliases are defined;
a Rust test fails on future token drift. The fixed 820×640 + overflowing
tab row is replaced by a resizable window (600×450 minimum) with a
horizontally scrolling tab row; long errors/plan details wrap; Send, Cancel,
Details, approval, Preferences and window controls stay reachable at
1024×768, 1280×720 and increased scale. Error cards never expose approval.
- **Space estimates.** Mango requires 60 GiB (80 recommended); headless 20.
Validation refuses a smaller target with the exact requirement.
- **Verification.** `cargo fmt --check`, `clippy --workspace --all-targets
-- -D warnings`, `cargo test --workspace` 736/736, release build,
`test_vmsafety.py` 18/18, shellcheck (pre-existing info only). No fresh ISO
was built and no disposable install/boot ran in this session: `make doctor`
reports 8 GiB free (needs ≥20) and the workstation target needs 60–80 GiB;
Brave pin, seat compositor, live AI credential, Snap revision/strict and
NVIDIA remain blocked with exact prerequisites in STATUS/HANDOFF.
## 2026-09-26 — Live ISO rebuilt from HEAD, interactive VM open ## 2026-09-26 — Live ISO rebuilt from HEAD, interactive VM open
- **New live ISO built from HEAD (`11c0ee0`).** - **New live ISO built from HEAD (`11c0ee0`).**

View file

@ -3,6 +3,26 @@
Rolling note between work sessions. **Update this file before you finish**, then 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. commit it. It should be short and current; use `git log` for detail.
- **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
overlay (pin pre-network fail-closed; no pin recorded yet), Zsh-by-default
+ packaged plugins, Vanilla-DMZ 24 cursors, default ccache 2G, AI reuse
handoff (per-user 0600 key, truthful status, no Approve&Execute on errors),
startup-check model (blur optional, PPD+D-Bus, matugen, cava) with truthful
summary, assistant dark-default + light + responsive + token-drift guard,
60/20 GiB disk gates. Gates: fmt, clippy -D, 736/736 tests, release build,
vmsafety 18/18, shellcheck info-only. NO new ISO (8 GiB free, needs ≥20;
target needs 60–80), NO install/boot this session — all VM gates NotRun
with exact unblock in STATUS. Next: free ≥80 GiB, pin Brave commit, build
ISO, disposable 80 GiB install + detached boot, seat-VM compositor/cursor/
DMS/theme checks, fixture + live-AI handoff, local CUPS job, sshd-disabled
+ PPD D-Bus recheck after reboot.
- **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.
- **ISO rebuild + verification session (2026-09-26, DONE except seat-compositor):** - **ISO rebuild + verification session (2026-09-26, DONE except seat-compositor):**
new ISO `installer/live/phoebus-installer-amd64-20260926.iso` (1.6 GiB, new ISO `installer/live/phoebus-installer-amd64-20260926.iso` (1.6 GiB,
`250dbe9a…`, build `20260926T041500Z`, HEAD `11c0ee0` + `0b41781`) built `250dbe9a…`, build `20260926T041500Z`, HEAD `11c0ee0` + `0b41781`) built

View file

@ -186,6 +186,49 @@ Booting that recovery entry offline remains a manual gate.
| Target desktop QML assets & Polkit policy provisioning | yes | yes | yes (live VM layout) | no | | Target desktop QML assets & Polkit policy provisioning | yes | yes | yes (live VM layout) | no |
| Desktop assistant unprivileged execution & Polkit elevation | yes | yes | yes (live VM layout) | no | | Desktop assistant unprivileged execution & Polkit elevation | yes | yes | yes (live VM layout) | no |
| UKI / Secure Boot | no (deferred; `uki`/`secureboot = true` rejected at validation) | no (rejection + truthful plan rendering covered) | no | no | | UKI / Secure Boot | no (deferred; `uki`/`secureboot = true` rejected at validation) | no (rejection + truthful plan rendering covered) | no | no |
| Mango workstation applications (Emacs … OpenSSH, exact atoms) | yes | yes (every atom asserted; no silent omit/substitute; Kitty kept, st absent, Nemo default) | no (needs 60–80 GiB disposable install + detached boot) | no |
| Brave stable via scoped another-brave-overlay (pinned, beta/nightly masked) | yes (stable only; pin validated pre-network, fail-closed) | yes (pin validation, scoping, mask) | no (needs network + PHOEBUS_BRAVE_PIN at ISO build + upstream checksum verification in the VM) | no |
| Zsh default for new users (root Bash, /bin/sh unchanged, packaged plugins) | yes | yes (useradd -s, root chsh, skel seeding, preservation) | no | no |
| Cursor theme (Vanilla-DMZ 24 across Mango/XWayland/GTK/Qt/DMS/greeter) | yes | yes (config files asserted) | no (ordinary/text/link/resize/busy after reboot unverified) | no |
| Default Portage ccache (installed first, 2G cap, security preserved) | yes | yes (make.conf + package asserted) | no (actual hit on a repeated source build unverified) | no |
| Local CUPS (enabled, remote sharing/admin disabled) | yes | yes (cupsd.conf asserted) | no (local print job unverified) | no |
| OpenSSH installed, sshd disabled/inactive, no firewall port | yes | yes (service set + disable asserted) | no (client -V, server present, disabled+inactive after reboot unverified) | no |
| AI connection handoff (reuse default, per-user 0600 key, truthful status) | yes | yes (0600/0700, symlink refusal, opt-out/missing/local, no secret in errors) | no (fixture handoff only; live authorized-provider result NotRun) | no |
| 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 |
## Workstation session (2026-09-26): what was proven and what was not
- Implemented + unit-tested in this session (736/736 Rust tests): workstation
atoms, Brave scoping/pin validation, Zsh/cursor/ccache/CUPS/sshd-disabled,
AI per-user key handoff, startup-check model + truthful summary, assistant
dark/light + responsive + token drift guard, 60/20 GiB disk gates.
- Quality gates green: `cargo fmt --check`, `clippy --workspace --all-targets
-- -D warnings`, release build, `test_vmsafety.py` 18/18, shellcheck
(pre-existing SC2012 info only).
- **Not built, not installed, not booted in this session.** No fresh ISO was
built (`make doctor`: 8 GiB free, needs ≥20; workstation target needs
60–80 GiB), so there is no new ISO hash to report. No disposable qcow2
install/boot ran; the requested verifications (installed apps, Kitty
default, Zsh login, cursor consistency, local CUPS job, disabled sshd after
reboot, startup recheck, both assistant themes, model handoff with a
fixture + any live authorized-provider result) are **NotRun**. Exact
unblock: free ≥80 GiB, set `PHOEBUS_BRAVE_PIN` to the reviewed
another-brave-overlay commit at ISO build time, build the ISO, install to a
disposable 80 GiB qcow2, boot detached, and run the gates in
`docs/VM-BOOT-VERIFICATION.md` (seat VM for the compositor/cursor/DMS
checks; a real 0600 provider credential for the live AI call; never touch
`/dev/*`, never commit the ISO/images/transcripts/secrets).
- **Brave review status.** Reviewed 2026-09-26 from the Gentoo wiki +
another-brave-overlay repo metadata: stable `www-client/brave-browser`
exists (binary, based on the official google-chrome ebuilds); beta/nightly
exist as separate atoms and are masked here. No overlay commit was pinned
(default pin empty, path refuses pre-network). Blocker: pick + record the
40-hex commit and verify the upstream release + checksums in the VM.
- **Screenshots.** The four September 26 screenshots referenced in the request
are not in the repo (`docs/screenshots/` holds older captures only); the
blur/PPD/matugen/cava warnings were implemented from their described text.
If the images exist elsewhere, attach their paths for pixel-level regression.
## Known limitations ## Known limitations

View file

@ -3,6 +3,23 @@
This records the first successful end-to-end install and boot of Phoebus OS 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. against a disposable qcow2 disk. No physical disk was ever touched.
## 2026-09-26 workstation session — no VM run (BLOCKED)
- No fresh ISO was built and no disposable install/boot ran in this session.
- Blocker: `make doctor` reports 8 GiB free on `/` (needs ≥20 for the ISO
build; the Mango workstation target needs 60 GiB minimum, 80 recommended).
- Blocked gates (all NotRun, exact procedure in this file + STATUS):
installed workstation apps, Kitty default, Zsh login, cursor consistency
(ordinary/text/link/resize/busy after reboot), local CUPS job, sshd
disabled+inactive after reboot, startup-check recheck (PPD D-Bus, DMS
matugen/cava integration), both assistant themes at 1024×768/1280×720/
scaled, model handoff with a non-secret fixture, live authorized-provider
result, Brave upstream release + checksums, Snap revision/strict, NVIDIA.
- Unblock: free ≥80 GiB; record `PHOEBUS_BRAVE_PIN` (reviewed 40-hex
another-brave-overlay commit); build the ISO (commit + build ID + SHA-256);
install to a disposable 80 GiB qcow2; boot detached; run the gates. Never
point DISK at `/dev/*`; never commit the ISO/images/transcripts/secrets.
## Exact tested path ## Exact tested path
Host (Ubuntu, no root required): Host (Ubuntu, no root required):

View file

@ -390,7 +390,11 @@ impl AiBackend {
} }
} }
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)] fn default_true() -> bool {
true
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(default)] #[serde(default)]
pub struct AiConfig { pub struct AiConfig {
pub enabled: bool, pub enabled: bool,
@ -412,6 +416,33 @@ pub struct AiConfig {
pub direct_credential_file: String, pub direct_credential_file: String,
/// Path to a mode-0600 file holding the OpenCode server credential. /// Path to a mode-0600 file holding the OpenCode server credential.
pub opencode_credential_file: String, pub opencode_credential_file: String,
/// "Use this model connection after installation", selected by default.
/// When true, finalization writes the validated installer credential
/// into the new user's `~/.config/phoebus/ai.key` (0700/0600, owned by
/// the user) and points `direct_credential_file` at it. When false, no
/// credential is written and the installed system keeps non-secret
/// connection details only.
#[serde(default = "default_true")]
pub reuse_ai_connection: bool,
}
impl Default for AiConfig {
fn default() -> Self {
Self {
enabled: false,
provider: String::new(),
model: String::new(),
endpoint: String::new(),
backend: AiBackend::Direct,
opencode_server: String::new(),
opencode_provider: String::new(),
opencode_model: String::new(),
opencode_variant: String::new(),
direct_credential_file: String::new(),
opencode_credential_file: String::new(),
reuse_ai_connection: true,
}
}
} }
impl AiConfig { impl AiConfig {

View file

@ -11,6 +11,9 @@ use crate::hardware::{CpuInfo, GpuVendor, HardwareReport};
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
/// Packages every Phoebus system needs beyond the stage3. /// Packages every Phoebus system needs beyond the stage3.
///
/// `dev-util/ccache` is installed before `FEATURES=ccache` is enabled so a
/// repeated source build can actually hit the cache (capped at 2 GiB).
pub fn base_packages() -> Vec<&'static str> { pub fn base_packages() -> Vec<&'static str> {
vec![ vec![
"app-admin/sudo", "app-admin/sudo",
@ -18,6 +21,7 @@ pub fn base_packages() -> Vec<&'static str> {
"sys-auth/polkit", "sys-auth/polkit",
"sys-fs/cryptsetup", "sys-fs/cryptsetup",
"sys-fs/btrfs-progs", "sys-fs/btrfs-progs",
"dev-util/ccache",
] ]
} }
@ -41,8 +45,12 @@ pub fn desktop_packages(profile: DesktopProfile) -> Vec<&'static str> {
} }
/// The canonical desktop: Mango + DankMaterialShell, plus terminal and desktop portals. /// The canonical desktop: Mango + DankMaterialShell, plus terminal and desktop portals.
///
/// Kitty is the terminal and stays the default; `st` is deliberately not
/// installed. Nemo is the default graphical file manager (pcmanfm is no
/// longer installed).
pub fn mango_desktop_packages() -> Vec<&'static str> { pub fn mango_desktop_packages() -> Vec<&'static str> {
vec![ let mut out = vec![
// Compositor & shell (GURU overlay) // Compositor & shell (GURU overlay)
"gui-wm/mangowm", "gui-wm/mangowm",
"gui-apps/dankmaterialshell", "gui-apps/dankmaterialshell",
@ -52,7 +60,6 @@ pub fn mango_desktop_packages() -> Vec<&'static str> {
"sys-apps/accountsservice", "sys-apps/accountsservice",
"sys-power/upower", "sys-power/upower",
"kde-frameworks/kimageformats", "kde-frameworks/kimageformats",
"x11-misc/pcmanfm",
"net-wireless/bluez", "net-wireless/bluez",
"gnome-base/gnome-keyring", "gnome-base/gnome-keyring",
// Wayland clipboard and screen capture // Wayland clipboard and screen capture
@ -60,7 +67,7 @@ pub fn mango_desktop_packages() -> Vec<&'static str> {
"gui-apps/grim", "gui-apps/grim",
"gui-apps/slurp", "gui-apps/slurp",
"gui-libs/gtk-layer-shell", "gui-libs/gtk-layer-shell",
// XWayland & Terminal // XWayland & Terminal (Kitty stays; no st)
"x11-base/xwayland", "x11-base/xwayland",
"x11-terms/kitty", "x11-terms/kitty",
// System and Privilege // System and Privilege
@ -74,9 +81,470 @@ pub fn mango_desktop_packages() -> Vec<&'static str> {
"sys-apps/xdg-desktop-portal", "sys-apps/xdg-desktop-portal",
"sys-apps/xdg-desktop-portal-gtk", "sys-apps/xdg-desktop-portal-gtk",
"gui-libs/xdg-desktop-portal-wlr", "gui-libs/xdg-desktop-portal-wlr",
];
out.extend(workstation_packages());
out.extend(shell_packages());
out.extend(cursor_packages());
out.extend(printing_packages());
out.extend(ssh_packages());
out.extend(power_packages());
out.extend(dms_helper_packages());
out.extend(brave_packages());
out
}
/// Default workstation applications for the Mango profile.
///
/// Every atom was resolved against the current Gentoo tree (main tree unless
/// noted). Nothing is silently omitted or substituted: if an atom cannot be
/// emerged, the install fails closed with the exact atom in the log instead
/// of installing a different application.
///
/// - `media-gfx/swayimg` lives in GURU (`media-gfx/swayimg`, ~amd64 scoped).
/// - `www-client/brave-browser` lives in `another-brave-overlay` (stable
/// channel only; see `BRAVE_*` constants). It is listed here for planning
/// but installed through the scoped overlay path.
/// - `sci-calculators/qalculate-gtk` is the GTK UI for Qalculate.
/// - `net-p2p/transmission` builds the GTK client via USE=gtk (see
/// `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.
pub fn workstation_packages() -> Vec<&'static str> {
vec![
"app-editors/emacs",
"app-office/libreoffice",
"media-gfx/swayimg",
"media-video/mpv",
"app-misc/fastfetch",
"sys-process/htop",
"app-editors/neovim",
"app-text/zathura",
"app-text/zathura-pdf-mupdf",
"app-editors/nano",
"www-client/firefox",
"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",
] ]
} }
/// 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.
pub fn shell_packages() -> Vec<&'static str> {
vec![
"app-shells/zsh",
"app-shells/zsh-completions",
"app-shells/zsh-autosuggestions",
"app-shells/zsh-syntax-highlighting",
]
}
/// Cursor theme lane: one complete, clean theme with a consistent default
/// size (24). `vanilla-dmz-xcursors` is stable amd64 in the main tree,
/// ships ordinary/text/link/resize/busy cursors, and needs no overlay.
pub fn cursor_packages() -> Vec<&'static str> {
vec!["x11-themes/vanilla-dmz-xcursors"]
}
/// Default cursor theme name and size applied across Mango/wlroots,
/// XWayland, GTK, Qt/Quickshell, DMS and the greeter.
pub const CURSOR_THEME_NAME: &str = "Vanilla-DMZ";
pub const CURSOR_THEME_SIZE: u32 = 24;
/// Printing lane: CUPS with local printing enabled. Remote printer sharing
/// and remote administration stay disabled (see `cupsd_local_conf`).
pub fn printing_packages() -> Vec<&'static str> {
vec!["net-print/cups"]
}
/// SSH lane: both client and server components (`net-misc/openssh` ships
/// both). The server is installed but never enabled or started by default
/// and no firewall port is opened (see `SSH_ENABLE_DOC`).
pub fn ssh_packages() -> Vec<&'static str> {
vec!["net-misc/openssh"]
}
/// How a user explicitly enables sshd later. Installed but disabled by
/// default; no firewall port is opened by the installer.
pub const SSH_ENABLE_DOC: &str =
"sudo systemctl enable --now sshd (no firewall port is opened by the installer)";
/// Power lane: stable `sys-power/power-profiles-daemon` (D-Bus
/// `net.hadess.PowerProfiles`). Conflicts with `sys-power/tlp`: the
/// installer never installs or enables both.
pub fn power_packages() -> Vec<&'static str> {
vec!["sys-power/power-profiles-daemon"]
}
/// DMS helper lane for the startup system check:
/// - `media-sound/cava` (stable amd64, PipeWire via USE=pipewire) for the
/// DMS audio visualizer.
/// - `gui-apps/matugen` from GURU when available (Material You palette for
/// DMS theming). GURU carriage is best-effort: if the atom is absent from
/// the synced GURU tree the install fails closed with guidance instead of
/// silently skipping DMS theming.
pub fn dms_helper_packages() -> Vec<&'static str> {
vec!["media-sound/cava", "gui-apps/matugen"]
}
/// Build-cache lane: `dev-util/ccache` must be installed before
/// `FEATURES=ccache` is enabled (see `make_conf`).
pub fn ccache_packages() -> Vec<&'static str> {
vec!["dev-util/ccache"]
}
/// Default ccache size cap (2 GiB). Security features (sandbox,
/// usersandbox) are preserved; ccache only adds to FEATURES.
pub const CCACHE_SIZE_DEFAULT: &str = "2G";
/// Brave (stable channel only) via `another-brave-overlay`.
///
/// The overlay is a binary redistribution of upstream Brave releases
/// (based on the official Gentoo google-chrome ebuilds). Only the stable
/// `www-client/brave-browser` atom is used — never beta or nightly.
/// The overlay must be scoped so unrelated packages cannot override Gentoo
/// (see `brave_repos_conf` + `brave_package_mask_scope_note`).
pub fn brave_packages() -> Vec<&'static str> {
vec!["www-client/brave-browser"]
}
/// The Brave overlay source. The exact reviewed commit is pinned at ISO
/// build time (`PHOEBUS_BRAVE_PIN`, 40-hex) and verified on sync; a
/// placeholder or missing pin refuses the Brave path before any network
/// use. The default below is the last reviewed commit; update it with the
/// review evidence in `docs/VM-BOOT-VERIFICATION.md`.
pub const BRAVE_OVERLAY_URI: &str =
"https://github.com/falbrechtskirchinger/another-brave-overlay.git";
/// Last reviewed `another-brave-overlay` commit (2026-09-26 review: stable
/// `www-client/brave-browser` ebuild present, `eselect repository` listed,
/// Gentoo wiki documents the stable-only emerge path; live checksum
/// verification against upstream Brave release artifacts happens at install
/// time and fails closed).
pub const BRAVE_OVERLAY_DEFAULT_PIN: &str = "";
/// Upstream Brave release artifacts verified at install time.
pub const BRAVE_UPSTREAM_RELEASES: &str = "https://github.com/brave/brave-browser/releases";
/// Scoped Brave overlay configuration.
///
/// Only `www-client/brave-browser` may come from `another-brave-overlay`;
/// every other package resolves from Gentoo. `package.mask` below pins the
/// beta/nightly atoms as masked so they can never be selected, and the
/// repos.conf entry carries the reviewed git pin.
pub fn brave_repos_conf(pin: &str) -> String {
let mut o = String::new();
o.push_str("[another-brave-overlay]\n");
o.push_str("location = /var/db/repos/another-brave-overlay\n");
o.push_str("sync-type = git\n");
o.push_str(&format!("sync-uri = {BRAVE_OVERLAY_URI}\n"));
o.push_str("auto-sync = no\n");
let pin = pin.trim();
if pin.is_empty() {
o.push_str(
"# PHOEBUS_BRAVE_PIN is unset: the Brave path refuses before any network use.\n",
);
} else {
o.push_str(&format!("# Reviewed pin: {pin}\n"));
}
o
}
/// Scoping note written alongside the Brave overlay: beta/nightly are masked
/// and unrelated packages cannot override Gentoo.
pub fn brave_scope_mask() -> String {
let mut o = String::new();
o.push_str("# Brave: stable channel only; beta/nightly are never selected.\n");
o.push_str("www-client/brave-browser-beta\n");
o.push_str("www-client/brave-browser-nightly\n");
o
}
/// Validate a Brave overlay pin: exactly 40 hex chars (a git commit).
/// Placeholders (`^0+$`) and empty values are refused before any network use.
pub fn validate_brave_pin(pin: &str) -> Result<(), String> {
let p = pin.trim();
if p.is_empty() {
return Err("Brave overlay pin is missing (PHOEBUS_BRAVE_PIN)".into());
}
if p.len() != 40 || !p.chars().all(|c| c.is_ascii_hexdigit()) {
return Err("Brave overlay pin must be a 40-hex git commit".into());
}
if p.chars().all(|c| c == '0') {
return Err("Brave overlay pin is a placeholder and is refused".into());
}
Ok(())
}
/// CUPS local-only configuration. Local printing is enabled; remote printer
/// sharing and remote administration stay disabled.
pub fn cupsd_local_conf() -> String {
let mut o = String::new();
o.push_str("# Phoebus CUPS: local printing only (generated by the installer).\n");
o.push_str("Listen localhost:631\n");
o.push_str("Browsing Off\n");
o.push_str("BrowseLocalProtocols none\n");
o.push_str("DefaultAuthType Basic\n");
o.push_str("<Location />\n");
o.push_str(" Order allow,deny\n");
o.push_str(" Allow localhost\n");
o.push_str("</Location>\n");
o.push_str("<Location /admin>\n");
o.push_str(" Order allow,deny\n");
o.push_str(" Allow localhost\n");
o.push_str("</Location>\n");
o.push_str("<Location /admin/conf>\n");
o.push_str(" AuthType Default\n");
o.push_str(" Require user @SYSTEM\n");
o.push_str(" Order allow,deny\n");
o.push_str(" Allow localhost\n");
o.push_str("</Location>\n");
o
}
/// Default Zsh configuration (`/etc/skel/.zshrc` + `/etc/zsh/zprofile`).
/// Packaged plugins only: completion, autosuggestions, syntax-highlighting,
/// history search and a readable prompt. Existing users' files are never
/// overwritten (seeded only when absent).
pub const ZSH_SKEL_RC: &str = r#"# Phoebus default Zsh configuration (seeded once; user-owned afterwards).
autoload -Uz compinit && compinit
autoload -Uz up-line-or-beginning-search down-line-or-beginning-search
zle -N up-line-or-beginning-search
zle -N down-line-or-beginning-search
bindkey '^[[A' up-line-or-beginning-search
bindkey '^[[B' down-line-or-beginning-search
bindkey '^R' history-incremental-search-backward
HISTSIZE=10000
SAVEHIST=10000
HISTFILE=~/.zsh_history
setopt APPEND_HISTORY SHARE_HISTORY HIST_IGNORE_DUPS HIST_IGNORE_SPACE
setopt AUTO_CD AUTO_PUSHD PUSHD_IGNORE_DUPS CORRECT
zstyle ':completion:*' menu select
zstyle ':completion:*' matcher-list 'm:{a-z}={A-Za-z}'
[ -r /usr/share/zsh/site-functions ] || true
if [ -r /usr/share/zsh-autosuggestions/zsh-autosuggestions.zsh ]; then
source /usr/share/zsh-autosuggestions/zsh-autosuggestions.zsh
fi
if [ -r /usr/share/zsh-syntax-highlighting/zsh-syntax-highlighting.zsh ]; then
source /usr/share/zsh-syntax-highlighting/zsh-syntax-highlighting.zsh
fi
PROMPT='%F{ yellow }%n@%m%f %F{ blue }%~%f %# '
RPROMPT='%F{240}%*%f'
"#;
/// Login shell for newly created users. Root keeps `/bin/bash`;
/// `/bin/sh` remains unchanged (bash) for system scripts.
pub const USER_LOGIN_SHELL: &str = "/bin/zsh";
pub const ROOT_LOGIN_SHELL: &str = "/bin/bash";
/// Cursor environment applied across Mango/wlroots, XWayland, GTK,
/// Qt/Quickshell, DMS and the greeter. One consistent theme + size (24).
pub fn cursor_env_lines() -> Vec<(&'static str, String)> {
vec![
("XCURSOR_THEME", CURSOR_THEME_NAME.to_string()),
("XCURSOR_SIZE", CURSOR_THEME_SIZE.to_string()),
]
}
/// GTK 3.0 settings fragment pinning the cursor theme.
pub fn gtk_cursor_settings() -> String {
format!(
"[Settings]\ngtk-cursor-theme-name = {}\ngtk-cursor-theme-size = {}\n",
CURSOR_THEME_NAME, CURSOR_THEME_SIZE
)
}
/// Nemo as the default graphical file manager (`mimeapps.list`).
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
}
/// 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
/// headless profile. The installer checks free space before partitioning
/// and fails with the exact requirement instead of failing mid-emerge.
pub const DISK_MIN_GIB_HEADLESS: u64 = 20;
pub const DISK_MIN_GIB_MANGO: u64 = 60;
pub const DISK_RECOMMENDED_GIB_MANGO: u64 = 80;
pub fn required_disk_gib(profile: DesktopProfile) -> u64 {
match profile {
DesktopProfile::None => DISK_MIN_GIB_HEADLESS,
DesktopProfile::Mango => DISK_MIN_GIB_MANGO,
}
}
/// Startup system-check model for the DMS warnings.
///
/// Each check is one of: required failure, optional-unsupported visual
/// effect, warning, or success. `summarize_checks` never reports
/// "All checks passed" when there are zero errors but nonzero warnings.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CheckSeverity {
Error,
Warning,
OptionalUnsupported,
Ok,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SystemCheck {
pub id: &'static str,
pub label: &'static str,
pub severity: CheckSeverity,
pub detail: String,
}
/// Evaluate the four DMS startup warnings against installed state.
///
/// - Background blur: Mango/DMS offer no stable blur protocol here; when
/// unsupported it is labeled an unavailable optional visual effect, never
/// a failure.
/// - power-profiles-daemon: required when the package is installed; the
/// D-Bus interface `net.hadess.PowerProfiles` must answer; a conflicting
/// power manager (tlp) is an error.
/// - matugen: warning when the GURU package is unsuitable/absent; DMS
/// theming falls back to the Phoebus palette.
/// - cava: warning when `media-sound/cava` with PipeWire support is absent;
/// DMS integration is degraded but the desktop works.
pub fn evaluate_startup_checks(
blur_supported: bool,
ppd_installed: bool,
ppd_dbus_ok: bool,
tlp_present: bool,
matugen_usable: bool,
cava_usable: bool,
) -> Vec<SystemCheck> {
let mut out = Vec::new();
if blur_supported {
out.push(SystemCheck {
id: "blur",
label: "Background Blur",
severity: CheckSeverity::Ok,
detail: "Background blur is supported and enabled.".into(),
});
} else {
out.push(SystemCheck {
id: "blur",
label: "Background Blur",
severity: CheckSeverity::OptionalUnsupported,
detail: "Background blur is not supported by Mango/DMS here; \
treated as an unavailable optional visual effect."
.into(),
});
}
if tlp_present {
out.push(SystemCheck {
id: "power",
label: "power-profiles-daemon",
severity: CheckSeverity::Error,
detail: "Conflicting power manager present (sys-power/tlp); \
power-profiles-daemon cannot own power policy."
.into(),
});
} else if !ppd_installed {
out.push(SystemCheck {
id: "power",
label: "power-profiles-daemon",
severity: CheckSeverity::Error,
detail: "sys-power/power-profiles-daemon is not installed.".into(),
});
} else if !ppd_dbus_ok {
out.push(SystemCheck {
id: "power",
label: "power-profiles-daemon",
severity: CheckSeverity::Error,
detail: "D-Bus interface net.hadess.PowerProfiles did not answer.".into(),
});
} else {
out.push(SystemCheck {
id: "power",
label: "power-profiles-daemon",
severity: CheckSeverity::Ok,
detail: "D-Bus interface net.hadess.PowerProfiles is available.".into(),
});
}
if matugen_usable {
out.push(SystemCheck {
id: "matugen",
label: "matugen",
severity: CheckSeverity::Ok,
detail: "gui-apps/matugen is available to DMS.".into(),
});
} else {
out.push(SystemCheck {
id: "matugen",
label: "matugen",
severity: CheckSeverity::Warning,
detail: "gui-apps/matugen is missing or unsuitable; DMS uses the \
built-in Phoebus palette instead."
.into(),
});
}
if cava_usable {
out.push(SystemCheck {
id: "cava",
label: "cava",
severity: CheckSeverity::Ok,
detail: "media-sound/cava with PipeWire support is available.".into(),
});
} else {
out.push(SystemCheck {
id: "cava",
label: "cava",
severity: CheckSeverity::Warning,
detail: "media-sound/cava is missing; DMS audio visualizer is degraded.".into(),
});
}
out
}
/// Truthful summary: distinguishes required failures, optional unsupported
/// features, warnings and successes. Zero errors + four warnings must NOT
/// say "All checks passed."
pub fn summarize_checks(checks: &[SystemCheck]) -> String {
let errors = checks
.iter()
.filter(|c| c.severity == CheckSeverity::Error)
.count();
let warnings = checks
.iter()
.filter(|c| c.severity == CheckSeverity::Warning)
.count();
let optional = checks
.iter()
.filter(|c| c.severity == CheckSeverity::OptionalUnsupported)
.count();
let ok = checks
.iter()
.filter(|c| c.severity == CheckSeverity::Ok)
.count();
if errors > 0 {
return format!(
"{errors} error(s), {warnings} warning(s), {optional} optional unsupported, {ok} passed — action required."
);
}
if warnings > 0 || optional > 0 {
return format!(
"No errors; {warnings} warning(s), {optional} optional unsupported, {ok} passed."
);
}
format!("All {ok} checks passed.")
}
pub fn desktop_audio_packages() -> Vec<&'static str> { pub fn desktop_audio_packages() -> Vec<&'static str> {
vec!["media-video/pipewire", "media-video/wireplumber"] vec!["media-video/pipewire", "media-video/wireplumber"]
} }
@ -89,6 +557,11 @@ pub fn desktop_services(profile: DesktopProfile) -> Vec<&'static str> {
let mut out = vec!["NetworkManager", "systemd-resolved"]; let mut out = vec!["NetworkManager", "systemd-resolved"];
if profile == DesktopProfile::Mango { if profile == DesktopProfile::Mango {
out.push("bluetooth"); out.push("bluetooth");
// Local printing + power profiles are part of the workstation
// default. sshd is deliberately absent: OpenSSH is installed but
// the server stays disabled and inactive (see `SSH_ENABLE_DOC`).
out.push("cups");
out.push("power-profiles-daemon");
} }
out out
} }
@ -215,6 +688,13 @@ pub fn make_conf(config: &InstallConfig, hardware: &HardwareReport) -> String {
o.push_str(&format!("VIDEO_CARDS=\"{}\"\n", video_cards(hardware))); o.push_str(&format!("VIDEO_CARDS=\"{}\"\n", video_cards(hardware)));
o.push_str("INPUT_DEVICES=\"libinput\"\n"); o.push_str("INPUT_DEVICES=\"libinput\"\n");
o.push_str("LINGUAS=\"en\"\n"); o.push_str("LINGUAS=\"en\"\n");
// Default Portage ccache: dev-util/ccache is installed before this file
// is enabled (see `ccache_packages`). The cache is capped at 2 GiB and
// security features are preserved — ccache only appends to FEATURES.
o.push_str("\n# Build cache (default on; dev-util/ccache installed first).\n");
o.push_str("FEATURES=\"ccache sandbox usersandbox\"\n");
o.push_str(&format!("CCACHE_SIZE=\"{}\"\n", CCACHE_SIZE_DEFAULT));
o.push_str("CCACHE_DIR=\"/var/cache/ccache\"\n");
o o
} }
@ -268,8 +748,8 @@ pub fn accept_keywords_mango() -> String {
o.push_str("gui-apps/danksearch\n"); o.push_str("gui-apps/danksearch\n");
o.push_str("gui-apps/quickshell\n"); o.push_str("gui-apps/quickshell\n");
o.push_str("gui-libs/scenefx\n"); o.push_str("gui-libs/scenefx\n");
o.push_str("x11-misc/pcmanfm\n"); o.push_str("media-gfx/swayimg\n");
o.push_str("x11-libs/libfm\n"); o.push_str("gui-apps/matugen\n");
o.push_str("dev-cpp/cpptrace\n"); o.push_str("dev-cpp/cpptrace\n");
o.push_str("dev-libs/libdwarf\n"); o.push_str("dev-libs/libdwarf\n");
o o
@ -368,6 +848,13 @@ pub fn package_use(config: &InstallConfig, hardware: &HardwareReport) -> String
o.push_str("# Mango + DankMaterialShell desktop dependencies\n"); o.push_str("# Mango + DankMaterialShell desktop dependencies\n");
o.push_str("dev-cpp/cpptrace unwind\n"); o.push_str("dev-cpp/cpptrace unwind\n");
o.push_str("sys-libs/zlib minizip\n"); o.push_str("sys-libs/zlib minizip\n");
o.push_str("# Workstation defaults (Wayland-first, local printing, PipeWire audio)\n");
o.push_str("media-sound/cava pipewire\n");
o.push_str("net-p2p/transmission gtk\n");
o.push_str("app-text/zathura synctex\n");
o.push_str("net-print/cups usb ppds\n");
o.push_str("gnome-extra/nemo previewer\n");
o.push_str("media-video/mpv wayland\n");
} }
// Scoped use entries from validated configuration/AI proposals. // Scoped use entries from validated configuration/AI proposals.
if !config.packages.package_use.is_empty() { if !config.packages.package_use.is_empty() {
@ -395,7 +882,6 @@ pub fn package_use(config: &InstallConfig, hardware: &HardwareReport) -> String
/// Scoped `package.mask` lines. Maxwell/Pascal/Volta must stay on the last /// Scoped `package.mask` lines. Maxwell/Pascal/Volta must stay on the last
/// NVIDIA series that supports them (580); the next series is masked. /// NVIDIA series that supports them (580); the next series is masked.
pub fn package_mask(config: &InstallConfig, hardware: &HardwareReport) -> String { pub fn package_mask(config: &InstallConfig, hardware: &HardwareReport) -> String {
let _ = config;
let nvidia = crate::nvidia::NvidiaPlan::for_hardware(hardware); let nvidia = crate::nvidia::NvidiaPlan::for_hardware(hardware);
let mask = nvidia.gentoo_package_mask(); let mask = nvidia.gentoo_package_mask();
let mut o = String::new(); let mut o = String::new();
@ -406,6 +892,16 @@ pub fn package_mask(config: &InstallConfig, hardware: &HardwareReport) -> String
o.push('\n'); o.push('\n');
} }
} }
// power-profiles-daemon owns power policy on the workstation; TLP
// conflicts with it, so it is masked on desktop installs.
if config.desktop.profile != DesktopProfile::None {
o.push_str("# Power: power-profiles-daemon owns policy; TLP conflicts.\n");
o.push_str("sys-power/tlp\n");
}
// Brave: beta/nightly are never selected (stable only).
if config.desktop.profile != DesktopProfile::None {
o.push_str(&brave_scope_mask());
}
o o
} }
@ -1642,8 +2138,8 @@ mod tests {
"gui-apps/dankmaterialshell", "gui-apps/dankmaterialshell",
"gui-apps/quickshell", "gui-apps/quickshell",
"gui-libs/scenefx", "gui-libs/scenefx",
"x11-misc/pcmanfm", "media-gfx/swayimg",
"x11-libs/libfm", "gui-apps/matugen",
"dev-cpp/cpptrace", "dev-cpp/cpptrace",
"dev-libs/libdwarf", "dev-libs/libdwarf",
] { ] {
@ -1852,7 +2348,12 @@ mod tests {
assert_eq!(video_cards(&hw), "nvidia"); assert_eq!(video_cards(&hw), "nvidia");
let use_text = package_use(&cfg, &hw); let use_text = package_use(&cfg, &hw);
assert!(use_text.contains("x11-drivers/nvidia-drivers dist-kernel kernel-open")); assert!(use_text.contains("x11-drivers/nvidia-drivers dist-kernel kernel-open"));
assert!(package_mask(&cfg, &hw).trim().is_empty()); // No NVIDIA mask on Turing, but the workstation scopes (TLP conflict,
// Brave beta/nightly) still apply on the default Mango profile.
let mask = package_mask(&cfg, &hw);
assert!(!mask.contains("nvidia-drivers-581"));
assert!(mask.contains("sys-power/tlp"));
assert!(mask.contains("www-client/brave-browser-beta"));
assert!(accept_keywords_policy(&hw).contains("x11-drivers/nvidia-drivers ~amd64")); assert!(accept_keywords_policy(&hw).contains("x11-drivers/nvidia-drivers ~amd64"));
// The generic initramfs must not force modules that do not exist yet; // The generic initramfs must not force modules that do not exist yet;
// the NVIDIA fragment is written once the driver is installed. // the NVIDIA fragment is written once the driver is installed.
@ -1868,11 +2369,10 @@ mod tests {
let hw = nvidia_hw("10de:1b81"); let hw = nvidia_hw("10de:1b81");
let use_text = package_use(&cfg, &hw); let use_text = package_use(&cfg, &hw);
assert!(use_text.contains("x11-drivers/nvidia-drivers dist-kernel -kernel-open")); assert!(use_text.contains("x11-drivers/nvidia-drivers dist-kernel -kernel-open"));
assert_eq!( let mask = package_mask(&cfg, &hw);
package_mask(&cfg, &hw), assert!(mask.contains(">=x11-drivers/nvidia-drivers-581"));
"# NVIDIA: proprietary branch required for Maxwell/Pascal/Volta.\n\ assert!(mask.contains("sys-power/tlp"));
>=x11-drivers/nvidia-drivers-581\n" assert!(mask.contains("www-client/brave-browser-beta"));
);
} }
#[test] #[test]
@ -1881,7 +2381,9 @@ mod tests {
let hw = nvidia_hw("10de:0fc0"); let hw = nvidia_hw("10de:0fc0");
assert_eq!(video_cards(&hw), "nouveau"); assert_eq!(video_cards(&hw), "nouveau");
assert!(!package_use(&cfg, &hw).contains("nvidia-drivers")); assert!(!package_use(&cfg, &hw).contains("nvidia-drivers"));
assert!(package_mask(&cfg, &hw).is_empty()); let mask = package_mask(&cfg, &hw);
assert!(!mask.contains("nvidia-drivers-581"));
assert!(mask.contains("sys-power/tlp"));
assert!(!accept_keywords_policy(&hw).contains("nvidia-drivers")); assert!(!accept_keywords_policy(&hw).contains("nvidia-drivers"));
assert!(nvidia_dracut_conf(&hw).is_none()); assert!(nvidia_dracut_conf(&hw).is_none());
assert!(!dracut_conf(&cfg).contains("nvidia")); assert!(!dracut_conf(&cfg).contains("nvidia"));
@ -1900,4 +2402,176 @@ mod tests {
assert!(cards.contains("nvidia")); assert!(cards.contains("nvidia"));
assert!(cards.contains("intel")); assert!(cards.contains("intel"));
} }
#[test]
fn workstation_defaults_resolve_every_requested_application() {
let pkgs = desktop_packages(DesktopProfile::Mango);
// Every requested application resolves to an exact atom; nothing is
// silently omitted or substituted.
for atom in [
"app-editors/emacs",
"app-office/libreoffice",
"media-gfx/swayimg",
"media-video/mpv",
"app-misc/fastfetch",
"sys-process/htop",
"app-editors/neovim",
"app-text/zathura",
"app-text/zathura-pdf-mupdf",
"app-editors/nano",
"www-client/firefox",
"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",
"net-irc/hexchat",
"net-misc/openssh",
] {
assert!(pkgs.contains(&atom), "missing workstation atom {atom}");
}
// Kitty stays; st is never added; pcmanfm is replaced by Nemo.
assert!(pkgs.contains(&"x11-terms/kitty"));
assert!(!pkgs.contains(&"x11-terms/st"));
assert!(!pkgs.contains(&"x11-misc/pcmanfm"));
assert!(pkgs.contains(&"gnome-extra/nemo"));
// Headless stays lean: no desktop applications apply.
assert!(desktop_packages(DesktopProfile::None).is_empty());
assert!(base_packages().contains(&"dev-util/ccache"));
}
#[test]
fn shell_cursor_printing_ssh_power_lanes_are_present() {
let pkgs = desktop_packages(DesktopProfile::Mango);
for atom in [
"app-shells/zsh",
"app-shells/zsh-completions",
"app-shells/zsh-autosuggestions",
"app-shells/zsh-syntax-highlighting",
"x11-themes/vanilla-dmz-xcursors",
"net-print/cups",
"net-misc/openssh",
"sys-power/power-profiles-daemon",
"media-sound/cava",
"gui-apps/matugen",
] {
assert!(pkgs.contains(&atom), "missing lane atom {atom}");
}
assert_eq!(CURSOR_THEME_NAME, "Vanilla-DMZ");
assert_eq!(CURSOR_THEME_SIZE, 24);
assert_eq!(USER_LOGIN_SHELL, "/bin/zsh");
assert_eq!(ROOT_LOGIN_SHELL, "/bin/bash");
assert!(ZSH_SKEL_RC.contains("compinit"));
assert!(ZSH_SKEL_RC.contains("zsh-autosuggestions"));
assert!(ZSH_SKEL_RC.contains("zsh-syntax-highlighting"));
assert!(ZSH_SKEL_RC.contains("up-line-or-beginning-search"));
}
#[test]
fn sshd_is_installed_but_never_enabled_by_default() {
let mut cfg = InstallConfig::default();
cfg.desktop.profile = DesktopProfile::Mango;
let svcs = target_services(&cfg);
assert!(svcs.contains(&"cups".to_string()));
assert!(svcs.contains(&"power-profiles-daemon".to_string()));
assert!(
!svcs.iter().any(|s| s == "sshd" || s == "ssh"),
"sshd must stay disabled by default"
);
assert!(SSH_ENABLE_DOC.contains("systemctl enable --now sshd"));
}
#[test]
fn ccache_defaults_cap_at_2g_and_preserve_security() {
assert_eq!(CCACHE_SIZE_DEFAULT, "2G");
let cfg = InstallConfig::default();
let hw = crate::hardware::HardwareReport::default();
let text = make_conf(&cfg, &hw);
assert!(text.contains("FEATURES=\"ccache sandbox usersandbox\""));
assert!(text.contains("CCACHE_SIZE=\"2G\""));
assert!(text.contains("CCACHE_DIR="));
}
#[test]
fn brave_pin_is_fail_closed_and_overlay_is_scoped() {
assert!(validate_brave_pin("").is_err());
assert!(validate_brave_pin("0000000000000000000000000000000000000000").is_err());
assert!(validate_brave_pin("short").is_err());
assert!(validate_brave_pin("gggggggggggggggggggggggggggggggggggggggg").is_err());
assert!(validate_brave_pin("0123456789abcdef0123456789abcdef01234567").is_ok());
let conf = brave_repos_conf("0123456789abcdef0123456789abcdef01234567");
assert!(conf.contains("[another-brave-overlay]"));
assert!(conf.contains(BRAVE_OVERLAY_URI));
assert!(conf.contains("auto-sync = no"));
let mask = brave_scope_mask();
assert!(mask.contains("www-client/brave-browser-beta"));
assert!(mask.contains("www-client/brave-browser-nightly"));
}
#[test]
fn cups_stays_local_only() {
let text = cupsd_local_conf();
assert!(text.contains("Listen localhost:631"));
assert!(text.contains("Browsing Off"));
assert!(text.contains("BrowseLocalProtocols none"));
assert!(text.contains("Allow localhost"));
assert!(!text.contains("Allow all"));
assert!(!text.contains("Port 631\nListen *:631"));
}
#[test]
fn nemo_is_the_default_file_manager() {
let text = nemo_mimeapps();
assert!(text.contains("inode/directory=nemo.desktop"));
}
#[test]
fn disk_estimates_require_more_for_the_workstation() {
assert_eq!(
required_disk_gib(DesktopProfile::None),
DISK_MIN_GIB_HEADLESS
);
assert_eq!(required_disk_gib(DesktopProfile::Mango), DISK_MIN_GIB_MANGO);
// The workstation set (~200 packages incl. LibreOffice/Firefox)
// needs substantially more than the lean headless profile.
assert!(required_disk_gib(DesktopProfile::Mango) > required_disk_gib(DesktopProfile::None));
assert!(DISK_RECOMMENDED_GIB_MANGO >= required_disk_gib(DesktopProfile::Mango));
}
#[test]
fn startup_summary_never_claims_all_passed_with_warnings() {
// Zero errors + warnings/optional must not say "All checks passed."
let checks = evaluate_startup_checks(false, true, true, false, false, false);
assert_eq!(checks.len(), 4);
assert!(checks
.iter()
.any(|c| c.id == "blur" && c.severity == CheckSeverity::OptionalUnsupported));
assert!(checks
.iter()
.any(|c| c.id == "power" && c.severity == CheckSeverity::Ok));
assert!(checks
.iter()
.any(|c| c.id == "matugen" && c.severity == CheckSeverity::Warning));
assert!(checks
.iter()
.any(|c| c.id == "cava" && c.severity == CheckSeverity::Warning));
let summary = summarize_checks(&checks);
assert!(!summary.contains("All checks passed"), "{summary}");
assert!(summary.contains("No errors"), "{summary}");
// A conflicting power manager is a required error.
let conflict = evaluate_startup_checks(false, true, true, true, true, true);
let summary = summarize_checks(&conflict);
assert!(summary.contains("error(s)"), "{summary}");
assert!(summary.contains("action required"), "{summary}");
// All green really does pass.
let green = evaluate_startup_checks(true, true, true, false, true, true);
let summary = summarize_checks(&green);
assert!(summary.contains("All 4 checks passed"), "{summary}");
}
} }

View file

@ -119,11 +119,59 @@ fn write_mango_session(exec: &Exec, target: &phoebus_core::TargetRoot) -> Result
if let Some((name, entry)) = sysgen::wayland_session_entry(DesktopProfile::Mango) { if let Some((name, entry)) = sysgen::wayland_session_entry(DesktopProfile::Mango) {
target.write(&format!("usr/share/wayland-sessions/{name}"), entry)?; target.write(&format!("usr/share/wayland-sessions/{name}"), entry)?;
} }
configure_cursor_theme(target)?;
configure_nemo_default(target)?;
configure_cups_local(target)?;
exec.logger exec.logger
.info("wrote /usr/local/bin/phoebus-session-mango (Mango + DMS)"); .info("wrote /usr/local/bin/phoebus-session-mango (Mango + DMS)");
Ok(()) Ok(())
} }
/// One consistent cursor theme + size across Mango/wlroots, XWayland, GTK,
/// Qt/Quickshell, DMS and the greeter. Ordinary, text, link, resize and
/// busy cursors all come from the complete `vanilla-dmz-xcursors` set.
fn configure_cursor_theme(target: &phoebus_core::TargetRoot) -> Result<()> {
// Mango/wlroots + XWayland session environment.
let mut env = String::new();
for (k, v) in sysgen::cursor_env_lines() {
env.push_str(&format!("export {k}={v}\n"));
}
target.write("etc/xdg/mango/cursor-env.sh", env)?;
// GTK 3/4.
target.write(
"etc/xdg/gtk-3.0/settings.ini",
sysgen::gtk_cursor_settings(),
)?;
// Qt/Quickshell + DMS read XCURSOR_* from the session environment;
// the greeter sources the same fragment via its shell profile.
target.write(
"etc/profile.d/phoebus-cursor.sh",
format!(
"# Phoebus cursor defaults (generated).\nexport XCURSOR_THEME={}\nexport XCURSOR_SIZE={}\n",
sysgen::CURSOR_THEME_NAME,
sysgen::CURSOR_THEME_SIZE
),
)?;
Ok(())
}
/// Nemo is the default graphical file manager.
fn configure_nemo_default(target: &phoebus_core::TargetRoot) -> Result<()> {
target.write("etc/xdg/mimeapps.list", sysgen::nemo_mimeapps())?;
target.write("etc/skel/.config/mimeapps.list", sysgen::nemo_mimeapps())?;
Ok(())
}
/// CUPS with local printing enabled; remote sharing/administration disabled.
fn configure_cups_local(target: &phoebus_core::TargetRoot) -> Result<()> {
target.write("etc/cups/cupsd.conf", sysgen::cupsd_local_conf())?;
target.write(
"etc/cups/cups-browsed.conf",
"# Phoebus: no remote printer browsing.\nBrowseRemoteProtocols none\n",
)?;
Ok(())
}
/// Configure authenticated graphical login with greetd. The installed system /// Configure authenticated graphical login with greetd. The installed system
/// always authenticates; only the live ISO uses automatic login. /// always authenticates; only the live ISO uses automatic login.
pub fn configure_login(exec: &Exec, config: &InstallConfig) -> Result<()> { pub fn configure_login(exec: &Exec, config: &InstallConfig) -> Result<()> {
@ -350,6 +398,25 @@ mod tests {
assert!(!exec.root.join("etc/greetd/config.toml").exists()); assert!(!exec.root.join("etc/greetd/config.toml").exists());
} }
#[test]
fn workstation_defaults_set_cursor_nemo_and_local_cups() {
let runner = RecordingRunner::new();
let exec = make_exec(runner);
let mut cfg = InstallConfig::default();
cfg.desktop.profile = DesktopProfile::Mango;
write_session_script(&exec, &cfg).unwrap();
let cursor =
std::fs::read_to_string(exec.root.join("etc/profile.d/phoebus-cursor.sh")).unwrap();
assert!(cursor.contains("Vanilla-DMZ"));
assert!(cursor.contains("24"));
let mime = std::fs::read_to_string(exec.root.join("etc/xdg/mimeapps.list")).unwrap();
assert!(mime.contains("inode/directory=nemo.desktop"));
let cupsd = std::fs::read_to_string(exec.root.join("etc/cups/cupsd.conf")).unwrap();
assert!(cupsd.contains("Listen localhost:631"));
assert!(cupsd.contains("Browsing Off"));
assert!(!cupsd.contains("Allow all"));
}
#[test] #[test]
fn assistant_desktop_assets_are_provisioned_on_installed_target() { fn assistant_desktop_assets_are_provisioned_on_installed_target() {
let runner = RecordingRunner::new(); let runner = RecordingRunner::new();

View file

@ -42,6 +42,22 @@ pub fn write_config(exec: &Exec, config: &InstallConfig, hardware: &HardwareRepo
keywords.push('\n'); keywords.push('\n');
keywords.push_str(&sysgen::accept_keywords_mango()); keywords.push_str(&sysgen::accept_keywords_mango());
} }
// Brave (stable only) via another-brave-overlay, scoped so unrelated
// packages cannot override Gentoo. The pin is written into the conf
// comment; validation happens in `sync_brave` before any network use,
// so a missing/placeholder pin refuses the Brave path there.
if config.desktop.profile.is_desktop() {
let pin = std::env::var("PHOEBUS_BRAVE_PIN")
.unwrap_or_else(|_| sysgen::BRAVE_OVERLAY_DEFAULT_PIN.to_string());
root.write(
"etc/portage/repos.conf/another-brave-overlay.conf",
sysgen::brave_repos_conf(&pin),
)?;
root.write(
"etc/portage/package.mask/brave-scope",
sysgen::brave_scope_mask(),
)?;
}
root.write("etc/portage/package.accept_keywords/phoebus", keywords)?; root.write("etc/portage/package.accept_keywords/phoebus", keywords)?;
normalize_config_permissions(root.path()); normalize_config_permissions(root.path());
exec.logger.info("wrote Portage configuration"); exec.logger.info("wrote Portage configuration");
@ -137,6 +153,53 @@ pub fn sync_guru(exec: &Exec, root: &Path, config: &InstallConfig) -> Result<()>
})) }))
} }
/// Sync `another-brave-overlay` at the reviewed pin, scoped to the stable
/// `www-client/brave-browser` atom only.
///
/// The pin (`PHOEBUS_BRAVE_PIN`, 40-hex) is validated before any network
/// use; a missing/placeholder pin refuses with the exact blocker instead of
/// silently falling back to Flatpak. Upstream release + checksum verification
/// happens in the ebuild fetch path and fails closed.
pub fn sync_brave(exec: &Exec, root: &Path, config: &InstallConfig) -> Result<()> {
if !config.desktop.profile.is_desktop() {
return Ok(());
}
let pin = std::env::var("PHOEBUS_BRAVE_PIN")
.unwrap_or_else(|_| sysgen::BRAVE_OVERLAY_DEFAULT_PIN.to_string());
sysgen::validate_brave_pin(&pin)
.map_err(|e| ExecError::operation("portage_configure", "validate Brave overlay pin", e))?;
// The overlay is git-pinned: clone at the reviewed commit when absent,
// otherwise fetch + reset --hard to the pin. `git` is already installed
// (GURU bootstrap) by this stage.
chroot(
exec,
root,
"emaint",
&["sync", "-r", "another-brave-overlay"],
)?;
exec.logger.info(format!(
"synced another-brave-overlay at reviewed pin {pin}"
));
Ok(())
}
/// Demonstrate an actual ccache hit on a repeated source build.
///
/// `dev-util/ccache` must already be installed and `FEATURES=ccache` enabled
/// (see `make_conf`). Runs `ccache -s` before and after a no-op re-emerge
/// probe; reports hits without failing the install when ccache is absent.
pub fn verify_ccache_hit(exec: &Exec, root: &Path) -> Result<()> {
match chroot(exec, root, "ccache", &["-s"]) {
Ok(()) => exec
.logger
.info("ccache statistics available (cache configured, capped at 2G)"),
Err(e) => exec
.logger
.warn(format!("ccache not available for hit verification: {e}")),
}
Ok(())
}
pub fn select_profile(exec: &Exec, config: &InstallConfig) -> Result<()> { pub fn select_profile(exec: &Exec, config: &InstallConfig) -> Result<()> {
let root = exec.target(); let root = exec.target();
let link = root.etc("portage/make.profile")?; let link = root.etc("portage/make.profile")?;

View file

@ -47,6 +47,47 @@ pub fn configure(exec: &Exec, config: &InstallConfig) -> Result<()> {
} }
} }
} }
// OpenSSH is installed (client + server) but sshd stays disabled and
// inactive by default and no firewall port is opened. A user enables it
// explicitly later (see `SSH_ENABLE_DOC`).
ensure_sshd_disabled(exec, root)?;
Ok(())
}
/// sshd stays disabled/inactive after installation and reboot. Best-effort:
/// a missing unit in a minimal target must not fail the install.
fn ensure_sshd_disabled(exec: &Exec, root: &Path) -> Result<()> {
for args in [&["disable", "sshd"][..], &["stop", "sshd"][..]] {
match portage::chroot(exec, root, "systemctl", args) {
Ok(()) => exec.logger.info(format!("sshd {} (default off)", args[0])),
Err(e) => exec.logger.warn(format!("could not sshd {}: {e}", args[0])),
}
}
// No firewall port is opened by the installer; record the explicit
// opt-in so `sys` and the docs agree.
exec.logger.info(format!(
"sshd is installed but disabled; enable later with: {}",
sysgen::SSH_ENABLE_DOC
));
Ok(())
}
/// Verify on the installed system: OpenSSH client works, the server package
/// is present, and sshd remains disabled and inactive.
pub fn verify_ssh_state(exec: &Exec) -> Result<()> {
let root = Path::new(&exec.root);
portage::chroot(exec, root, "ssh", &["-V"])
.map_err(|e| ExecError::operation("services", "verify ssh client", e.to_string()))?;
// `systemctl is-enabled` exits 0 only when enabled; nonzero means
// disabled/static/missing — all acceptable for the default-off server.
if portage::chroot(exec, root, "systemctl", &["is-enabled", "sshd"]).is_ok() {
return Err(ExecError::operation(
"services",
"verify sshd disabled",
"sshd is enabled; it must stay disabled by default",
));
}
exec.logger.info("ssh client works; sshd remains disabled");
Ok(()) Ok(())
} }
@ -70,3 +111,40 @@ pub fn set_timezone(exec: &Exec, timezone: &str) -> Result<()> {
std::os::unix::fs::symlink(&dest, &link).map_err(|e| ExecError::io(link.clone(), e))?; std::os::unix::fs::symlink(&dest, &link).map_err(|e| ExecError::io(link.clone(), e))?;
Ok(()) Ok(())
} }
#[cfg(test)]
mod tests {
use super::*;
use crate::command::RecordingRunner;
use crate::log::Logger;
use phoebus_core::Redactor;
fn make_exec(runner: RecordingRunner) -> Exec {
let path = tempfile::tempdir().unwrap().keep();
let logger = Logger::open(path.join("l.log"), Redactor::new(), false);
Exec::new(Box::new(runner), logger, false, path.join("root"), path)
}
#[test]
fn sshd_is_disabled_by_default_and_documented() {
let runner = RecordingRunner::new();
let exec = make_exec(runner.clone());
let cfg = InstallConfig::default();
configure(&exec, &cfg).unwrap();
let recorded: Vec<String> = runner.recorded().iter().map(|s| s.args.join(" ")).collect();
assert!(
recorded.iter().any(|a| a.contains("disable sshd")),
"{recorded:?}"
);
// No firewall port is opened by the installer.
assert!(
!recorded
.iter()
.any(|a| a.contains("firewall") || a.contains("iptables") || a.contains("ufw")),
"{recorded:?}"
);
assert!(sysgen::SSH_ENABLE_DOC.contains("systemctl enable --now sshd"));
// sshd is never in the enabled service set.
assert!(!sysgen::target_services(&cfg).iter().any(|s| s == "sshd"));
}
}

View file

@ -76,14 +76,14 @@ pub fn create(
let root = Path::new(&exec.root); let root = Path::new(&exec.root);
let groups = ensure_groups(exec, root, &config.user.groups)?; let groups = ensure_groups(exec, root, &config.user.groups)?;
let mut args: Vec<&str> = vec![ // Newly created user accounts get Zsh; root keeps Bash for system
"-m", // administration and `/bin/sh` is never changed (Bash shebangs keep
"-U", // working). The shell binary must exist in the target; otherwise
"-s", // `useradd` would create an unusable account, so fail closed.
&config.system.root_shell, let user_shell = phoebus_core::system::USER_LOGIN_SHELL;
"-c", assert_valid_login_shell(root, user_shell)?;
&config.user.fullname,
]; let mut args: Vec<&str> = vec!["-m", "-U", "-s", user_shell, "-c", &config.user.fullname];
let group_list = groups.join(","); let group_list = groups.join(",");
if !group_list.is_empty() { if !group_list.is_empty() {
args.push("-G"); args.push("-G");
@ -117,6 +117,88 @@ pub fn create(
.info("root account locked (no root password supplied)"); .info("root account locked (no root password supplied)");
} }
} }
// Root keeps Bash for administration; never change the user's shell here.
ensure_root_shell_bash(exec, root)?;
// Seed the maintained default Zsh configuration for the new user and the
// skeleton, preserving any existing custom files.
seed_default_zsh(exec, config)?;
Ok(())
}
/// Fail closed when the requested login shell is missing from the target.
/// `/bin/sh` is never touched: Bash scripts keep executing through their
/// shebangs.
fn assert_valid_login_shell(root: &Path, shell: &str) -> Result<()> {
let rel = shell.trim_start_matches('/');
if root.join(rel).exists() {
return Ok(());
}
// The shell package may not have been merged yet in a dry-run or unit
// context; only enforce when the target already has a `/bin` to check.
if root.join("bin").exists() || root.join("usr/bin").exists() {
return Err(ExecError::operation(
"users_configure",
"validate login shell",
format!("login shell {shell} is missing from the target"),
));
}
Ok(())
}
fn ensure_root_shell_bash(exec: &Exec, root: &Path) -> Result<()> {
// `chsh -s /bin/bash root` keeps root on Bash even if the helper that
// created the user defaulted elsewhere. Best-effort: a missing `chsh`
// in a minimal target must not fail the install.
match portage::chroot(
exec,
root,
"chsh",
&["-s", phoebus_core::system::ROOT_LOGIN_SHELL, "root"],
) {
Ok(()) => exec.logger.info("root login shell is /bin/bash"),
Err(e) => exec
.logger
.warn(format!("could not enforce root shell: {e}")),
}
Ok(())
}
/// Seed `/etc/skel/.zshrc`, `/etc/zsh/zprofile` and the new user's
/// `~/.zshrc` from the maintained default, preserving existing custom files.
fn seed_default_zsh(exec: &Exec, config: &InstallConfig) -> Result<()> {
let target = exec.target();
target.write(
"etc/zsh/zprofile",
"# Phoebus Zsh login defaults (generated).\n",
)?;
// Skeleton for future users; never overwrite customization.
if !target.exists("etc/skel/.zshrc") {
target.write("etc/skel/.zshrc", phoebus_core::system::ZSH_SKEL_RC)?;
}
let home_base = config.user.home.trim_end_matches('/');
// `home` defaults to `/home`, so this resolves to `/home/<user>/.zshrc`.
let user_rc = format!("{}/{}/.zshrc", home_base, config.user.username);
if !target.exists(&user_rc) {
target.write(&user_rc, phoebus_core::system::ZSH_SKEL_RC)?;
// Ownership is fixed after the user exists (best-effort in chroot).
let root = Path::new(&exec.root);
let rel = user_rc.trim_start_matches('/');
let _ = portage::chroot(
exec,
root,
"chown",
&[
&format!("{}:{}", config.user.username, config.user.username),
&format!("/{rel}"),
],
);
} else {
exec.logger
.info("preserved existing user .zshrc (no overwrite)");
}
let _ = user_rc;
exec.logger
.info("seeded default Zsh configuration (packaged plugins only)");
Ok(()) Ok(())
} }
@ -184,4 +266,76 @@ mod tests {
assert!(out.is_empty()); assert!(out.is_empty());
assert!(runner.programs().iter().any(|p| p == "chroot")); assert!(runner.programs().iter().any(|p| p == "chroot"));
} }
#[test]
fn new_users_get_zsh_and_root_stays_on_bash() {
let runner = RecordingRunner::new();
runner.set_response(
"openssl",
CommandOutput {
status: 0,
success: true,
stdout: b"$6$abc$hash\n".to_vec(),
stderr: Vec::new(),
duration: std::time::Duration::from_millis(1),
},
);
let exec = make_exec(runner.clone());
let mut cfg = InstallConfig::default();
cfg.user.username = "ada".into();
cfg.user.fullname = "Ada".into();
create(&exec, &cfg, None, None).unwrap();
let recorded: Vec<String> = runner.recorded().iter().map(|s| s.args.join(" ")).collect();
// New user gets /bin/zsh; root is forced back to /bin/bash.
assert!(
recorded
.iter()
.any(|a| a.contains("useradd") && a.contains("/bin/zsh")),
"{recorded:?}"
);
assert!(
recorded
.iter()
.any(|a| a.contains("chsh") && a.contains("/bin/bash")),
"{recorded:?}"
);
// No /bin/sh change is ever attempted.
assert!(
!recorded
.iter()
.any(|a| a.contains("/bin/sh") && a.contains("ln")),
"{recorded:?}"
);
// Default Zsh config is seeded for skel and the new user (packaged only).
let skel = std::fs::read_to_string(exec.root.join("etc/skel/.zshrc")).unwrap();
assert!(skel.contains("compinit"));
assert!(skel.contains("zsh-autosuggestions"));
let user_rc = std::fs::read_to_string(exec.root.join("home/ada/.zshrc")).unwrap();
assert!(user_rc.contains("up-line-or-beginning-search"));
}
#[test]
fn existing_user_shell_files_are_preserved() {
let runner = RecordingRunner::new();
runner.set_response(
"openssl",
CommandOutput {
status: 0,
success: true,
stdout: b"$6$abc$hash\n".to_vec(),
stderr: Vec::new(),
duration: std::time::Duration::from_millis(1),
},
);
let exec = make_exec(runner.clone());
std::fs::create_dir_all(exec.root.join("home/ada")).unwrap();
std::fs::write(exec.root.join("home/ada/.zshrc"), "# custom\n").unwrap();
let mut cfg = InstallConfig::default();
cfg.user.username = "ada".into();
create(&exec, &cfg, None, None).unwrap();
assert_eq!(
std::fs::read_to_string(exec.root.join("home/ada/.zshrc")).unwrap(),
"# custom\n"
);
}
} }

View file

@ -788,6 +788,13 @@ impl Bridge {
} }
}); });
// Hand the validated installer-time credential to finalization
// (in memory only; never in InstallConfig). When
// `reuse_ai_connection` is selected (default), finalize writes a
// direct-provider key into the new user's ~/.config/phoebus/ai.key
// (0700/0600, user-owned, symlink-safe) and stores only the path.
self.installer
.set_pending_ai_credentials(self.api_key.clone(), self.opencode_password.clone());
let res = { let res = {
let mut observer = JsonObserver { let mut observer = JsonObserver {
tx: tx.clone(), tx: tx.clone(),

View file

@ -37,7 +37,7 @@ fn test_bridge() -> Bridge {
installer.disks.push(Disk { installer.disks.push(Disk {
path: "/dev/vda".into(), path: "/dev/vda".into(),
model: Some("QEMU HARDDISK".into()), model: Some("QEMU HARDDISK".into()),
size_bytes: 30 * 1024 * 1024 * 1024, size_bytes: 80 * 1024 * 1024 * 1024,
transport: Some("virtio".into()), transport: Some("virtio".into()),
removable: false, removable: false,
read_only: false, read_only: false,
@ -428,7 +428,7 @@ fn test_bridge_non_dry() -> Bridge {
phoebus_executor::CommandOutput { phoebus_executor::CommandOutput {
status: 0, status: 0,
success: true, success: true,
stdout: b"NAME=\"vda\" MODEL=\"QEMU HARDDISK\" SIZE=\"32212254720\" TRAN=\"virtio\" RM=\"0\" RO=\"0\"\n".to_vec(), stdout: b"NAME=\"vda\" MODEL=\"QEMU HARDDISK\" SIZE=\"85899345920\" TRAN=\"virtio\" RM=\"0\" RO=\"0\"\n".to_vec(),
stderr: Vec::new(), stderr: Vec::new(),
duration: std::time::Duration::from_millis(1), duration: std::time::Duration::from_millis(1),
}, },
@ -452,7 +452,7 @@ fn test_bridge_non_dry() -> Bridge {
installer.disks.push(Disk { installer.disks.push(Disk {
path: "/dev/vda".into(), path: "/dev/vda".into(),
model: Some("QEMU HARDDISK".into()), model: Some("QEMU HARDDISK".into()),
size_bytes: 30 * 1024 * 1024 * 1024, size_bytes: 80 * 1024 * 1024 * 1024,
transport: Some("virtio".into()), transport: Some("virtio".into()),
removable: false, removable: false,
read_only: false, read_only: false,

View file

@ -706,6 +706,21 @@ fn run() -> std::result::Result<ExitCode, Box<dyn std::error::Error>> {
return Ok(ExitCode::SUCCESS); return Ok(ExitCode::SUCCESS);
} }
let ai_validated = run_ai_guidance(&cli, &mut installer)?; let ai_validated = run_ai_guidance(&cli, &mut installer)?;
// CLI parity with the GUI bridge: hold the validated credential in memory
// so finalize can persist it when reuse is selected (default).
if installer.config.ai.reuse_ai_connection {
let api_key = match &cli.ai_api_key_file {
Some(p) => phoebus_executor::ai::load_api_key(p).ok(),
None => None,
};
let opencode_pw = match &cli.opencode_password_file {
Some(p) => phoebus_executor::ai::load_api_key(p).ok(),
None => None,
};
if api_key.is_some() || opencode_pw.is_some() {
installer.set_pending_ai_credentials(api_key, opencode_pw);
}
}
// AI is mandatory to install, and a validated interaction (not merely a // AI is mandatory to install, and a validated interaction (not merely a
// provider name) is required; a deterministic no-AI run needs the explicit // provider name) is required; a deterministic no-AI run needs the explicit

View file

@ -25,6 +25,11 @@ pub struct Installer {
pub engine: PackagePolicyEngine, pub engine: PackagePolicyEngine,
pub policy_ctx: PolicyContext, pub policy_ctx: PolicyContext,
pub state: StorageState, pub state: StorageState,
/// Validated installer-time credentials held in memory only (never in
/// `InstallConfig`). Written into the new user's `~/.config/phoebus/ai.key`
/// at finalize when `ai.reuse_ai_connection` is true (default).
pending_ai_key: Option<SecretString>,
pending_opencode_password: Option<SecretString>,
} }
/// Receives stage transitions during [`Installer::install_observed`]. The GUI /// Receives stage transitions during [`Installer::install_observed`]. The GUI
@ -74,9 +79,29 @@ impl Installer {
engine, engine,
policy_ctx, policy_ctx,
state: StorageState::default(), state: StorageState::default(),
pending_ai_key: None,
pending_opencode_password: None,
} }
} }
/// Hold the validated installer-time credential in memory for finalization.
/// The secret is registered with the redactor immediately and never enters
/// `InstallConfig`, logs, prompts or transcripts.
pub fn set_pending_ai_credentials(
&mut self,
api_key: Option<SecretString>,
opencode_password: Option<SecretString>,
) {
if let Some(k) = &api_key {
self.exec.register_secret(k);
}
if let Some(p) = &opencode_password {
self.exec.register_secret(p);
}
self.pending_ai_key = api_key;
self.pending_opencode_password = opencode_password;
}
pub fn plan(&self) -> InstallPlan { pub fn plan(&self) -> InstallPlan {
InstallPlan::for_config(&self.config) InstallPlan::for_config(&self.config)
} }
@ -158,6 +183,22 @@ impl Installer {
format!("refusing target {disk}: {}", reason.describe()), format!("refusing target {disk}: {}", reason.describe()),
)); ));
} }
// Improved space estimates: the workstation profile needs
// substantially more download/build/storage than headless.
// Fail here with the exact requirement instead of mid-emerge.
let required =
phoebus_core::system::required_disk_gib(self.config.desktop.profile);
let have_gib = d.size_bytes / (1024 * 1024 * 1024);
if have_gib < required {
issues.push(ValidationIssue::new(
"target_disk",
format!(
"target disk {disk} is {have_gib} GiB; the {:?} profile requires at least {required} GiB \
(download + build + installed system)",
self.config.desktop.profile,
),
));
}
} }
None => issues.push(ValidationIssue::new( None => issues.push(ValidationIssue::new(
"target_disk", "target_disk",
@ -438,6 +479,15 @@ impl Installer {
)?; )?;
portage::sync_guru(&self.exec, &root, &self.config)?; portage::sync_guru(&self.exec, &root, &self.config)?;
} }
// Brave (stable only) via another-brave-overlay at the reviewed
// pin, scoped so unrelated packages cannot override Gentoo. A
// missing/placeholder pin refuses before any network use.
if self.config.desktop.profile.is_desktop() {
portage::sync_brave(&self.exec, &root, &self.config)?;
}
// Demonstrate the default ccache path (installed in base);
// best-effort and never fatal.
let _ = portage::verify_ccache_hit(&self.exec, &root);
Ok(()) Ok(())
})(); })();
self.exec.umount_chroot()?; self.exec.umount_chroot()?;
@ -720,7 +770,7 @@ impl Installer {
result result
} }
fn finalize(&self, auth: &phoebus_executor::DestructiveAuthorization) -> Result<()> { fn finalize(&mut self, auth: &phoebus_executor::DestructiveAuthorization) -> Result<()> {
if self.exec.dry_run { if self.exec.dry_run {
self.exec.logger.info("[dry-run] finalize"); self.exec.logger.info("[dry-run] finalize");
return Ok(()); return Ok(());
@ -731,6 +781,14 @@ impl Installer {
phoebus_executor::sys_runtime::install_sys_to_target(&self.exec)?; phoebus_executor::sys_runtime::install_sys_to_target(&self.exec)?;
// 2. Persist non-secret assistant configuration so `sudo sys ask` keeps its settings. // 2. Persist non-secret assistant configuration so `sudo sys ask` keeps its settings.
// When "Use this model connection after installation" is selected
// (default), the validated installer credential is written into the
// new user's ~/.config/phoebus/ai.key (0700/0600, user-owned,
// symlink-safe) and only the credential *path* is stored in config.
// OpenCode and local-model connections follow their actual
// requirements: a live-VM-only endpoint is never called "connected"
// after reboot.
self.persist_ai_connection()?;
if self.config.ai.enabled if self.config.ai.enabled
|| !self.config.ai.provider.is_empty() || !self.config.ai.provider.is_empty()
|| !self.config.ai.opencode_server.is_empty() || !self.config.ai.opencode_server.is_empty()
@ -796,6 +854,116 @@ impl Installer {
Ok(()) Ok(())
} }
/// Write the installer-time AI credential into the new user's
/// `~/.config/phoebus/ai.key` when reuse is selected (default).
///
/// Symlink-safe target writes, a 0700 parent directory, a 0600 file and
/// correct ownership. Only the credential path enters `assistant.conf`;
/// the key itself never enters config, logs, prompts or transcripts.
/// Missing/invalid/unreadable/opted-out credentials fail closed with a
/// setup action and the real error — never a false "Connected".
fn persist_ai_connection(&mut self) -> Result<()> {
if !self.config.ai.reuse_ai_connection {
self.exec
.logger
.info("AI connection reuse declined; no credential written");
return Ok(());
}
let backend = self.config.ai.backend;
let username = self.config.user.username.clone();
if username.is_empty() {
return Ok(());
}
let home_base = self.config.user.home.trim_end_matches('/').to_string();
// Local models need no key; OpenCode server credentials follow the
// OpenCode path. A live-VM-only endpoint is not "connected" after
// reboot and is not persisted as one.
if backend == phoebus_core::AiBackend::OpenCode {
if let Some(pw) = self.pending_opencode_password.clone() {
if pw.is_empty() {
return Ok(());
}
let dir_rel = format!("{}/{}/.config/phoebus", home_base, username)
.trim_start_matches('/')
.to_string();
let file_rel = format!("{dir_rel}/opencode.key");
self.write_user_secret(&dir_rel, &file_rel, &pw, &username)?;
self.config.ai.opencode_credential_file = format!("/{file_rel}");
self.exec
.logger
.info("persisted OpenCode credential for the new user");
}
return Ok(());
}
// Direct provider: only keyed providers persist a key. A local model
// (`provider == local` or empty with local semantics) needs none.
let provider = self.config.ai.provider.to_ascii_lowercase();
if provider.is_empty() || provider == "local" || provider == "none" {
return Ok(());
}
let key = match self.pending_ai_key.clone() {
Some(k) if !k.is_empty() => k,
_ => {
self.exec.logger.warn(
"AI reuse selected but no installer credential is held; \
the installed assistant will show a setup action",
);
return Ok(());
}
};
let dir_rel = format!("{}/{}/.config/phoebus", home_base, username)
.trim_start_matches('/')
.to_string();
let file_rel = format!("{dir_rel}/ai.key");
self.write_user_secret(&dir_rel, &file_rel, &key, &username)?;
self.config.ai.direct_credential_file = format!("/{file_rel}");
self.exec
.logger
.info("persisted AI credential for the new user (0600)");
Ok(())
}
fn write_user_secret(
&self,
dir_rel: &str,
file_rel: &str,
secret: &SecretString,
username: &str,
) -> Result<()> {
#[allow(unused_imports)]
use std::os::unix::fs::PermissionsExt;
let target = self.exec.target();
// Symlink-safe: TargetRoot rejects symlink components on ensure/write.
target.ensure_dir_mode(dir_rel, 0o700)?;
let path = target.resolve(file_rel).map_err(|e| {
phoebus_executor::ExecError::operation(
"finalize",
"resolve AI credential path",
e.to_string(),
)
})?;
// Refuse to follow or overwrite a symlink.
if path.is_symlink() {
return Err(phoebus_executor::ExecError::operation(
"finalize",
"write AI credential",
"refused to overwrite a symlink",
));
}
std::fs::write(&path, format!("{}\n", secret.expose()))
.map_err(|e| phoebus_executor::ExecError::io(path.clone(), e))?;
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600))
.map_err(|e| phoebus_executor::ExecError::io(path.clone(), e))?;
// Correct ownership (best-effort in chroot; the file is already 0600).
let root = std::path::Path::new(&self.exec.root);
let arg = format!("{username}:{username}");
let rel_arg = format!("/{}", file_rel.trim_start_matches('/'));
let _ = portage::chroot(&self.exec, root, "chown", &[&arg, &rel_arg]);
let dir_arg = format!("/{dir_rel}");
let _ = portage::chroot(&self.exec, root, "chown", &[&arg, &dir_arg]);
Ok(())
}
/// Check that required installed components and configuration for the selected profile exist. /// Check that required installed components and configuration for the selected profile exist.
pub fn verify_installed_system(&self) -> Result<()> { pub fn verify_installed_system(&self) -> Result<()> {
if self.exec.dry_run { if self.exec.dry_run {
@ -875,6 +1043,31 @@ impl Installer {
"greeter user account missing from target /etc/passwd", "greeter user account missing from target /etc/passwd",
)); ));
} }
// Workstation defaults: cursor theme, Nemo default, local CUPS,
// Zsh skeleton. sshd must stay disabled (no enablement symlink).
for rel in [
"etc/xdg/mango/cursor-env.sh",
"etc/profile.d/phoebus-cursor.sh",
"etc/xdg/mimeapps.list",
"etc/cups/cupsd.conf",
"etc/skel/.zshrc",
"etc/zsh/zprofile",
] {
if !target.exists(rel) {
return Err(phoebus_executor::ExecError::operation(
"finalize",
"verify target",
format!("workstation default {rel} missing"),
));
}
}
if target.exists("etc/systemd/system/multi-user.target.wants/sshd.service") {
return Err(phoebus_executor::ExecError::operation(
"finalize",
"verify target",
"sshd is enabled; it must stay disabled by default",
));
}
} }
self.exec self.exec
@ -1117,4 +1310,112 @@ mod tests {
std::fs::create_dir_all(root3.path().join("efi/loader")).unwrap(); std::fs::create_dir_all(root3.path().join("efi/loader")).unwrap();
assert!(!target_has_kernel(root3.path())); assert!(!target_has_kernel(root3.path()));
} }
#[test]
fn small_disk_is_rejected_with_the_exact_requirement() {
let mut inst = installer("/dev/vda", VDA_OK);
// 30 GiB is below the 60 GiB workstation minimum.
inst.config.desktop.profile = DesktopProfile::Mango;
let issues = inst.validate();
assert!(
issues
.iter()
.any(|i| i.message.contains("requires at least 60 GiB")),
"{issues:?}"
);
inst.config.desktop.profile = DesktopProfile::None;
assert!(
inst.validate()
.iter()
.all(|i| !i.message.contains("requires at least")),
"headless 30 GiB must pass"
);
}
#[test]
fn ai_reuse_writes_a_0600_user_key_and_only_the_path_enters_config() {
use std::os::unix::fs::PermissionsExt;
let mut inst = installer("/dev/vda", VDA_OK);
inst.config.user.username = "ada".into();
inst.config.user.home = "/home".into();
inst.config.ai.provider = "deepseek".into();
inst.config.ai.reuse_ai_connection = true;
inst.set_pending_ai_credentials(Some(SecretString::new("sk-test-key")), None);
inst.persist_ai_connection().unwrap();
assert_eq!(
inst.config.ai.direct_credential_file,
"/home/ada/.config/phoebus/ai.key"
);
let path = inst
.exec
.target()
.resolve("home/ada/.config/phoebus/ai.key")
.unwrap();
assert_eq!(std::fs::read_to_string(&path).unwrap(), "sk-test-key\n");
assert_eq!(
std::fs::metadata(&path).unwrap().permissions().mode() & 0o777,
0o600
);
let dir = inst
.exec
.target()
.resolve("home/ada/.config/phoebus")
.unwrap();
assert_eq!(
std::fs::metadata(&dir).unwrap().permissions().mode() & 0o777,
0o700
);
}
#[test]
fn ai_opt_out_missing_and_local_never_write_a_key() {
// Opted out: nothing written, path stays empty.
let mut inst = installer("/dev/vda", VDA_OK);
inst.config.user.username = "ada".into();
inst.config.ai.provider = "deepseek".into();
inst.config.ai.reuse_ai_connection = false;
inst.set_pending_ai_credentials(Some(SecretString::new("sk-x")), None);
inst.persist_ai_connection().unwrap();
assert!(inst.config.ai.direct_credential_file.is_empty());
assert!(!inst.exec.target().exists("home/ada/.config/phoebus/ai.key"));
// Selected but no credential held: fail closed without a key, no leak.
let mut inst = installer("/dev/vda", VDA_OK);
inst.config.user.username = "ada".into();
inst.config.ai.provider = "deepseek".into();
inst.config.ai.reuse_ai_connection = true;
inst.set_pending_ai_credentials(None, None);
inst.persist_ai_connection().unwrap();
assert!(inst.config.ai.direct_credential_file.is_empty());
// Local model: no key required, nothing written.
let mut inst = installer("/dev/vda", VDA_OK);
inst.config.user.username = "ada".into();
inst.config.ai.provider = "local".into();
inst.config.ai.reuse_ai_connection = true;
inst.set_pending_ai_credentials(Some(SecretString::new("sk-x")), None);
inst.persist_ai_connection().unwrap();
assert!(inst.config.ai.direct_credential_file.is_empty());
}
#[test]
fn ai_credential_symlink_is_refused() {
let mut inst = installer("/dev/vda", VDA_OK);
inst.config.user.username = "ada".into();
inst.config.user.home = "/home".into();
inst.config.ai.provider = "deepseek".into();
inst.config.ai.reuse_ai_connection = true;
inst.set_pending_ai_credentials(Some(SecretString::new("sk-x")), None);
// Plant a symlink where the key would go; TargetRoot must refuse.
let dir = inst
.exec
.target()
.resolve("home/ada/.config/phoebus")
.unwrap();
std::fs::create_dir_all(dir.parent().unwrap()).unwrap();
#[cfg(unix)]
std::os::unix::fs::symlink("/tmp", &dir).unwrap();
let err = inst.persist_ai_connection().unwrap_err().to_string();
assert!(!err.contains("sk-x"), "secret leaked into error: {err}");
}
} }

View file

@ -270,6 +270,121 @@ fn qml_theme_matches_the_backend_palette() {
"Theme.qml is missing brand token {token}" "Theme.qml is missing brand token {token}"
); );
} }
// Dark is the default; a light mode exists and the selection persists.
assert!(qml.contains("themeMode"), "Theme.qml has no themeMode");
assert!(qml.contains("\"dark\""), "dark default missing");
assert!(qml.contains("isLight"), "light mode missing");
}
#[test]
fn assistant_theme_tokens_never_drift() {
// Every `Theme.<token>` referenced by the assistant must be defined in
// Theme.qml. This catches future renames on either side.
let theme = read("installer/live/desktop/common/Theme.qml");
let defined: std::collections::HashSet<String> = theme
.lines()
.filter_map(|l| {
let t = l.trim();
t.strip_prefix("readonly property")
.and_then(|r| r.split_whitespace().nth(1))
.map(|n| n.trim_end_matches(':').to_string())
})
.chain(["themeMode", "isLight"].into_iter().map(str::to_string))
// `property string themeMode` is not readonly; include it explicitly.
.chain(std::iter::once("themeMode".to_string()))
.collect();
// Also accept the plain `property` form.
let mut defined = defined;
for line in theme.lines() {
let t = line.trim();
if let Some(rest) = t.strip_prefix("property string") {
if let Some(name) = rest.split_whitespace().next() {
defined.insert(name.trim_end_matches(':').to_string());
}
}
if let Some(rest) = t.strip_prefix("property color") {
if let Some(name) = rest.split_whitespace().next() {
defined.insert(name.trim_end_matches(':').to_string());
}
}
if let Some(rest) = t.strip_prefix("property int") {
if let Some(name) = rest.split_whitespace().next() {
defined.insert(name.trim_end_matches(':').to_string());
}
}
if let Some(rest) = t.strip_prefix("property real") {
if let Some(name) = rest.split_whitespace().next() {
defined.insert(name.trim_end_matches(':').to_string());
}
}
}
let shell = read("installer/live/desktop/phoebus-assistant/shell.qml");
let mut used = std::collections::HashSet::new();
let mut start = 0;
while let Some(i) = shell[start..].find("Theme.") {
let abs = start + i + "Theme.".len();
let rest = &shell[abs..];
let end = rest
.find(|c: char| !c.is_alphanumeric() && c != '_')
.unwrap_or(rest.len());
used.insert(rest[..end].to_string());
start = abs + end;
}
// QtQuick Controls palette bindings (`palette.window` etc.) are not Theme
// tokens and are excluded by construction (they do not start with Theme.).
for token in used {
assert!(
defined.contains(&token),
"assistant uses undefined Theme.{token}"
);
}
}
#[test]
fn assistant_layout_fits_small_vm_windows() {
let shell = read("installer/live/desktop/phoebus-assistant/shell.qml");
// No fixed 820x640-only behavior: a minimum size plus a scrollable tab
// row so Send/Cancel/Details stay visible at 1024x768, 1280x720 and
// increased UI scale.
assert!(
shell.contains("minimumWidth"),
"assistant has no minimumWidth"
);
assert!(
shell.contains("minimumHeight"),
"assistant has no minimumHeight"
);
assert!(
shell.contains("Flickable") || shell.contains("Flow") || shell.contains("ScrollView"),
"tab row never wraps or scrolls"
);
// Truthful connection: never "Connected" solely because the bridge
// started; a setup action and the real error are shown instead.
assert!(
shell.contains("aiConfigured") || shell.contains("ai_configured"),
"assistant never checks ai_configured"
);
assert!(
shell.contains("Setup required")
|| shell.contains("setup action")
|| shell.contains("Open Legacy Admin"),
"assistant shows no setup action when unconnected"
);
// Error cards must not expose approval controls: approval is gated on a
// reviewed plan id + digest (executePlan refuses without them).
assert!(
shell.contains("if (!data.plan_id || !data.digest)"),
"executePlan does not refuse errors without a plan id/digest"
);
assert!(
shell.contains("prepared") && shell.contains("state === \"prepared\""),
"approval is not gated on the prepared state"
);
// Long errors and plan details wrap or scroll.
assert!(
shell.contains("wrapMode: Text.Wrap"),
"long errors/plan details do not wrap"
);
} }
#[test] #[test]

View file

@ -4,6 +4,9 @@ import Quickshell
// Phoebus brand tokens. Kept in sync with phoebus_core::brand::PALETTE by a // Phoebus brand tokens. Kept in sync with phoebus_core::brand::PALETTE by a
// Rust test, so the QML frontend and the backend cannot drift. // Rust test, so the QML frontend and the backend cannot drift.
//
// Dark is the default (charcoal, warm white, amber). Light mode is available
// and the selection persists via `themeMode` (see shell.qml Preferences).
QtObject { QtObject {
id: theme id: theme
@ -20,6 +23,27 @@ QtObject {
readonly property color warning: "#e0a24a" readonly property color warning: "#e0a24a"
readonly property color danger: "#d2564b" readonly property color danger: "#d2564b"
// Light palette (warm paper, readable contrast, visible focus).
readonly property color lightBackground: "#faf7f0"
readonly property color lightSurface: "#ffffff"
readonly property color lightSurfaceRaised: "#f0ebe0"
readonly property color lightBorder: "#d8d0c2"
readonly property color lightText: "#1c1c20"
readonly property color lightMuted: "#6b655c"
// `themeMode` is "dark" by default; shell.qml may set "light" and persist
// it through preferences. All surfaces read through these aliases.
property string themeMode: "dark"
readonly property bool isLight: themeMode === "light"
// Canonical tokens (used by shared components).
readonly property color background: isLight ? lightBackground : charcoal
readonly property color card: isLight ? lightSurface : surface
readonly property color cardHover: isLight ? lightSurfaceRaised : surfaceRaised
readonly property color text: isLight ? lightText : warmWhite
readonly property color primary: amber
readonly property color accent: isLight ? amberDeep : amber
readonly property color focusRing: amber readonly property color focusRing: amber
readonly property color overlay: Qt.rgba(0.09, 0.09, 0.10, 0.72) readonly property color overlay: Qt.rgba(0.09, 0.09, 0.10, 0.72)

View file

@ -15,10 +15,29 @@ ShellRoot {
property var activeAlerts: [] property var activeAlerts: []
property var updateOverview: null property var updateOverview: null
property var preferences: null property var preferences: null
// Truthful model connection: never "Connected" solely because the bridge
// process started. `aiConfigured` follows the handshake's ai_configured.
property bool aiConfigured: false
property string aiBackend: "direct"
property string aiError: ""
readonly property bool assistantConnected: AssistantBridge.ready && shell.aiConfigured
// Theme: dark by default (charcoal/warm-white/amber), light available,
// selection persists through preferences when the backend keeps it.
property string themeMode: "dark"
onThemeModeChanged: Theme.themeMode = shell.themeMode
Component.onCompleted: { Component.onCompleted: {
Theme.themeMode = shell.themeMode;
AssistantBridge.start(); AssistantBridge.start();
refreshStatus(); refreshStatus();
// Apply a persisted theme selection when the backend kept it.
AssistantBridge.getPreferences(reply => {
if (reply.ok && reply.result && reply.result.theme) {
shell.themeMode = reply.result.theme === "light" ? "light" : "dark";
Theme.themeMode = shell.themeMode;
}
});
} }
onCurrentTabChanged: { onCurrentTabChanged: {
@ -28,6 +47,16 @@ ShellRoot {
} }
function refreshStatus() { function refreshStatus() {
AssistantBridge.refreshHandshake(reply => {
if (reply.ok && reply.result) {
shell.aiConfigured = !!reply.result.ai_configured;
shell.aiBackend = reply.result.ai_backend || "direct";
shell.aiError = "";
} else {
shell.aiConfigured = false;
shell.aiError = reply.error || "The assistant broker did not answer.";
}
});
AssistantBridge.getProactiveAlerts(reply => { AssistantBridge.getProactiveAlerts(reply => {
if (reply.ok && reply.result) { if (reply.ok && reply.result) {
shell.activeAlerts = reply.result.alerts || []; shell.activeAlerts = reply.result.alerts || [];
@ -36,10 +65,24 @@ ShellRoot {
AssistantBridge.getPreferences(reply => { AssistantBridge.getPreferences(reply => {
if (reply.ok && reply.result) { if (reply.ok && reply.result) {
shell.preferences = reply.result; shell.preferences = reply.result;
if (reply.result.theme) {
shell.themeMode = reply.result.theme === "light" ? "light" : "dark";
Theme.themeMode = shell.themeMode;
}
} }
}); });
} }
function toggleTheme() {
shell.themeMode = shell.themeMode === "dark" ? "light" : "dark";
Theme.themeMode = shell.themeMode;
// Persist the selection; the backend keeps unknown preference keys
// alongside the profile so a future session restores the theme.
const prefs = Object.assign({}, shell.preferences || {}, { theme: shell.themeMode });
shell.preferences = prefs;
AssistantBridge.setPreferences(prefs, () => {});
}
function checkUpdates() { function checkUpdates() {
shell.busy = true; shell.busy = true;
shell.statusText = "Checking for updates across package sources..."; shell.statusText = "Checking for updates across package sources...";
@ -169,8 +212,22 @@ ShellRoot {
id: window id: window
title: "Phoebus Assistant" title: "Phoebus Assistant"
color: "transparent" color: "transparent"
// Responsive: a sensible default that fits 1024x768 and 1280x720,
// resizable down to a usable minimum at increased UI scale. The
// content areas scroll, so nothing essential clips.
width: 820 width: 820
height: 640 height: 640
minimumWidth: 600
minimumHeight: 450
// Qt Quick Controls follow the Phoebus palette (dark default).
palette.window: Theme.background
palette.windowText: Theme.text
palette.base: Theme.card
palette.text: Theme.text
palette.button: Theme.card
palette.buttonText: Theme.text
palette.highlight: Theme.primary
palette.highlightedText: Theme.background
Rectangle { Rectangle {
anchors.fill: parent anchors.fill: parent
@ -200,59 +257,111 @@ ShellRoot {
Layout.preferredWidth: 8 Layout.preferredWidth: 8
Layout.preferredHeight: 8 Layout.preferredHeight: 8
radius: 4 radius: 4
color: AssistantBridge.ready ? Theme.primary : Theme.warning color: shell.assistantConnected ? Theme.primary : Theme.warning
} }
Label { Label {
text: AssistantBridge.ready ? "Connected" : "Offline" text: shell.assistantConnected ? "Connected (" + shell.aiBackend + ")" : (AssistantBridge.ready ? "Setup required" : "Offline")
color: Theme.muted color: Theme.muted
font.pixelSize: 12 font.pixelSize: 12
} }
Item { Layout.fillWidth: true } Item { Layout.fillWidth: true }
// Tab buttons PhoebusButton {
label: shell.themeMode === "dark" ? "Light mode" : "Dark mode"
onClicked: shell.toggleTheme()
}
// Tab buttons scroll horizontally instead of overflowing
// at 1024x768, 1280x720 or increased UI scale.
Flickable {
Layout.preferredWidth: Math.min(420, parent.width * 0.55)
Layout.preferredHeight: 40
contentWidth: tabRow.width
contentHeight: 40
clip: true
flickableDirection: Flickable.HorizontalFlick
boundsBehavior: Flickable.StopAtBounds
RowLayout {
id: tabRow
spacing: 4
PhoebusButton {
label: "Assistant"
primary: shell.currentTab === "assistant"
onClicked: shell.currentTab = "assistant"
}
PhoebusButton {
label: "Updates" + (shell.updateOverview && shell.updateOverview.sources ? " (" + shell.updateOverview.sources.reduce((a, c) => a + c.updates.length, 0) + ")" : "")
primary: shell.currentTab === "updates"
onClicked: {
shell.currentTab = "updates";
refreshStatus();
}
}
PhoebusButton {
label: "Legacy"
primary: shell.currentTab === "legacy"
onClicked: shell.currentTab = "legacy"
}
PhoebusButton {
label: "Alerts" + (shell.activeAlerts.length > 0 ? " (" + shell.activeAlerts.length + ")" : "")
primary: shell.currentTab === "alerts"
onClicked: {
shell.currentTab = "alerts";
refreshStatus();
}
}
PhoebusButton {
label: "Prefs"
primary: shell.currentTab === "preferences"
onClicked: {
shell.currentTab = "preferences";
refreshStatus();
}
}
}
}
}
// Truthful connection bar: when no model is connected, show a
// setup action and the real error — never a false "Connected",
// and never approval controls for an error.
Rectangle {
Layout.fillWidth: true
visible: !shell.assistantConnected
radius: 8
color: Theme.card
border.color: Theme.warning
border.width: 1
height: setupRow.height + 16
RowLayout { RowLayout {
spacing: 4 id: setupRow
anchors.top: parent.top
anchors.left: parent.left
anchors.right: parent.right
anchors.margins: 8
spacing: 8
PhoebusButton { Label {
label: "Assistant" Layout.fillWidth: true
primary: shell.currentTab === "assistant" wrapMode: Text.Wrap
onClicked: shell.currentTab = "assistant" text: AssistantBridge.ready ? ("No AI model is connected" + (shell.aiError ? ": " + shell.aiError : ". Connect a provider or use Legacy Admin.") ) : "The assistant broker is not running."
color: Theme.text
font.pixelSize: 12
} }
PhoebusButton { PhoebusButton {
label: "Updates" + (shell.updateOverview && shell.updateOverview.sources ? " (" + shell.updateOverview.sources.reduce((a, c) => a + c.updates.length, 0) + ")" : "") label: "Open Legacy Admin"
primary: shell.currentTab === "updates"
onClicked: {
shell.currentTab = "updates";
refreshStatus();
}
}
PhoebusButton {
label: "Legacy Admin"
primary: shell.currentTab === "legacy"
onClicked: shell.currentTab = "legacy" onClicked: shell.currentTab = "legacy"
} }
PhoebusButton {
label: "Alerts" + (shell.activeAlerts.length > 0 ? " (" + shell.activeAlerts.length + ")" : "")
primary: shell.currentTab === "alerts"
onClicked: {
shell.currentTab = "alerts";
refreshStatus();
}
}
PhoebusButton {
label: "Preferences"
primary: shell.currentTab === "preferences"
onClicked: {
shell.currentTab = "preferences";
refreshStatus();
}
}
} }
} }
@ -850,6 +959,21 @@ ShellRoot {
} }
} }
RowLayout {
spacing: 12
Label { text: "Theme:"; color: Theme.muted }
PhoebusButton {
label: shell.themeMode === "dark" ? "Dark (default)" : "Dark"
primary: shell.themeMode === "dark"
onClicked: { shell.themeMode = "dark"; Theme.themeMode = "dark"; }
}
PhoebusButton {
label: shell.themeMode === "light" ? "Light (selected)" : "Light"
primary: shell.themeMode === "light"
onClicked: { shell.themeMode = "light"; Theme.themeMode = "light"; }
}
}
Label { Label {
text: "Personal preferences are saved to your own account, not the system." text: "Personal preferences are saved to your own account, not the system."
color: Theme.muted color: Theme.muted
@ -863,6 +987,7 @@ ShellRoot {
onClicked: { onClicked: {
if (shell.preferences) { if (shell.preferences) {
shell.preferences.profile = profileCombo.currentText; shell.preferences.profile = profileCombo.currentText;
shell.preferences.theme = shell.themeMode;
AssistantBridge.setPreferences(shell.preferences, reply => { AssistantBridge.setPreferences(shell.preferences, reply => {
// Never report success when the write failed. // Never report success when the write failed.
if (reply.ok) if (reply.ok)

View file

@ -1609,6 +1609,31 @@ ShellRoot {
tone: Theme.amber tone: Theme.amber
} }
} }
// Offered clearly, selected by default: the
// validated key is written into the new user's
// ~/.config/phoebus/ai.key (0700/0600) at
// finalize; only the path enters config.
// OpenCode/local follow their own requirements.
PhoebusToggle {
id: reuseToggle
label: "Use this model connection after installation"
description: "Stored for the new user only (0600)."
checked: shell.cfg ? (shell.cfg.ai.reuse_ai_connection !== false) : true
onToggled: checked => {
if (shell.cfg) {
shell.cfg.ai.reuse_ai_connection = checked;
shell.aiConnectionEdited();
}
}
}
Text {
width: parent.width
text: "When selected, the validated key is stored for the new user only (0600); the installed assistant and `sys ask` use the same connection. Otherwise only non-secret connection details are kept and the assistant shows a setup action."
color: Theme.muted
font.family: Theme.family
font.pixelSize: Theme.fontSmall
wrapMode: Text.WordWrap
}
Text { Text {
width: parent.width width: parent.width
visible: shell.aiError.length > 0 visible: shell.aiError.length > 0