- systemd Automatic Boot Assessment: BLS +<tries> parsing/formatting and phoebus-boot-confirm.service - Preflight safety gates: 10 GiB storage preflight check and atomic @ and @var pre-update snapshots - Tiered update channels: Core, Proven (default), Edge - Userspace AI agent framework: agent_jail Bubblewrap isolation, desktop_config undoable mutations, phoebus-mcp server, sys propose staging bridge - Fixed parent directory creation race condition in personal storage - Verified with cargo fmt, clippy, and full workspace test suite
401 lines
12 KiB
Rust
401 lines
12 KiB
Rust
//! Safe, typed desktop configuration and checkpoint engine for MangoWM + DankMaterialShell.
|
|
//!
|
|
//! Unlike Omarchy's unvetted Bash glue scripts which risk command injection and
|
|
//! desktop corruption, Phoebus OS uses schema-validated configuration mutations
|
|
//! paired with an automatic checkpoint/undo mechanism.
|
|
//!
|
|
//! When an AI agent (or user) modifies desktop settings (accent colors, themes,
|
|
//! or window manager keybindings):
|
|
//! 1. Inputs are validated against known schemas (e.g. valid hex colors, safe key combinations).
|
|
//! 2. An automatic checkpoint snapshot is recorded before applying changes.
|
|
//! 3. Changes are written atomically.
|
|
//! 4. If the desktop behavior breaks or is undesired, `undo()` restores the previous checkpoint.
|
|
|
|
use std::fs;
|
|
use std::path::{Path, PathBuf};
|
|
|
|
use serde::{Deserialize, Serialize};
|
|
|
|
use crate::error::{ExecError, Result};
|
|
|
|
/// Theme options for DarkMaterialShell (DMS).
|
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
|
|
pub struct DmsThemeConfig {
|
|
#[serde(skip_serializing_if = "Option::is_none")]
|
|
pub accent_color: Option<String>,
|
|
#[serde(skip_serializing_if = "Option::is_none")]
|
|
pub dark_mode: Option<bool>,
|
|
#[serde(skip_serializing_if = "Option::is_none")]
|
|
pub wallpaper_path: Option<String>,
|
|
}
|
|
|
|
impl DmsThemeConfig {
|
|
/// Validates the theme values (e.g. hex colors, file paths).
|
|
pub fn validate(&self) -> Result<()> {
|
|
if let Some(ref color) = self.accent_color {
|
|
if !is_valid_hex_color(color) {
|
|
return Err(ExecError::operation(
|
|
"desktop",
|
|
"theme_validate",
|
|
format!(
|
|
"invalid accent color '{color}': must be a 6-digit hex string (#RRGGBB)"
|
|
),
|
|
));
|
|
}
|
|
}
|
|
if let Some(ref wp) = self.wallpaper_path {
|
|
if wp.contains('\0') || wp.contains('\n') {
|
|
return Err(ExecError::operation(
|
|
"desktop",
|
|
"theme_validate",
|
|
"wallpaper path contains control characters",
|
|
));
|
|
}
|
|
}
|
|
Ok(())
|
|
}
|
|
}
|
|
|
|
/// A validated keybinding for MangoWM.
|
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
|
pub struct MangoKeybinding {
|
|
pub combo: String,
|
|
pub action: String,
|
|
}
|
|
|
|
impl MangoKeybinding {
|
|
pub fn validate(&self) -> Result<()> {
|
|
let trimmed_combo = self.combo.trim();
|
|
if trimmed_combo.is_empty() {
|
|
return Err(ExecError::operation(
|
|
"desktop",
|
|
"keybinding_validate",
|
|
"key combo cannot be empty",
|
|
));
|
|
}
|
|
if trimmed_combo.contains('\0') || trimmed_combo.contains('\n') {
|
|
return Err(ExecError::operation(
|
|
"desktop",
|
|
"keybinding_validate",
|
|
"key combo contains control characters",
|
|
));
|
|
}
|
|
|
|
let trimmed_action = self.action.trim();
|
|
if trimmed_action.is_empty() {
|
|
return Err(ExecError::operation(
|
|
"desktop",
|
|
"keybinding_validate",
|
|
"action cannot be empty",
|
|
));
|
|
}
|
|
if trimmed_action.contains('\0') || trimmed_action.contains('\n') {
|
|
return Err(ExecError::operation(
|
|
"desktop",
|
|
"keybinding_validate",
|
|
"action contains control characters",
|
|
));
|
|
}
|
|
Ok(())
|
|
}
|
|
}
|
|
|
|
/// Validates whether a string is a `#RRGGBB` hex color.
|
|
pub fn is_valid_hex_color(s: &str) -> bool {
|
|
if !s.starts_with('#') {
|
|
return false;
|
|
}
|
|
let hex_part = &s[1..];
|
|
if hex_part.len() != 6 {
|
|
return false;
|
|
}
|
|
hex_part.chars().all(|c| c.is_ascii_hexdigit())
|
|
}
|
|
|
|
/// Directory where desktop auto-checkpoints are saved for undo.
|
|
pub fn checkpoint_dir_for_home(home: &Path) -> PathBuf {
|
|
home.join(".local/state/phoebus/desktop-checkpoints")
|
|
}
|
|
|
|
/// Directory where DMS settings live.
|
|
pub fn dms_config_dir_for_home(home: &Path) -> PathBuf {
|
|
home.join(".config/dms")
|
|
}
|
|
|
|
/// File where MangoWM config lives.
|
|
pub fn mango_config_file_for_home(home: &Path) -> PathBuf {
|
|
home.join(".config/mango/config.toml")
|
|
}
|
|
|
|
/// Records a snapshot checkpoint of the current desktop configuration before a mutation.
|
|
pub fn create_checkpoint(home: &Path, label: &str) -> Result<PathBuf> {
|
|
let cp_base = checkpoint_dir_for_home(home);
|
|
fs::create_dir_all(&cp_base).map_err(|e| ExecError::Io {
|
|
path: cp_base.clone(),
|
|
source: e,
|
|
})?;
|
|
|
|
let timestamp = std::time::SystemTime::now()
|
|
.duration_since(std::time::UNIX_EPOCH)
|
|
.unwrap_or_default()
|
|
.as_secs();
|
|
|
|
let safe_label: String = label
|
|
.chars()
|
|
.map(|c| if c.is_ascii_alphanumeric() { c } else { '_' })
|
|
.collect();
|
|
|
|
let snapshot_dir = cp_base.join(format!("{timestamp}_{safe_label}"));
|
|
fs::create_dir_all(&snapshot_dir).map_err(|e| ExecError::Io {
|
|
path: snapshot_dir.clone(),
|
|
source: e,
|
|
})?;
|
|
|
|
// Copy DMS config if present
|
|
let dms_dir = dms_config_dir_for_home(home);
|
|
let dms_theme_file = dms_dir.join("theme.json");
|
|
if dms_theme_file.exists() {
|
|
let dest = snapshot_dir.join("dms_theme.json");
|
|
fs::copy(&dms_theme_file, &dest).map_err(|e| ExecError::Io {
|
|
path: dest,
|
|
source: e,
|
|
})?;
|
|
}
|
|
|
|
// Copy Mango config if present
|
|
let mango_file = mango_config_file_for_home(home);
|
|
if mango_file.exists() {
|
|
let dest = snapshot_dir.join("mango_config.toml");
|
|
fs::copy(&mango_file, &dest).map_err(|e| ExecError::Io {
|
|
path: dest,
|
|
source: e,
|
|
})?;
|
|
}
|
|
|
|
// Write metadata
|
|
let meta = format!("timestamp={timestamp}\nlabel={label}\n");
|
|
let meta_file = snapshot_dir.join("metadata.ini");
|
|
fs::write(&meta_file, meta).map_err(|e| ExecError::Io {
|
|
path: meta_file,
|
|
source: e,
|
|
})?;
|
|
|
|
Ok(snapshot_dir)
|
|
}
|
|
|
|
/// Applies a theme configuration to DMS with schema validation and auto-checkpoint.
|
|
pub fn apply_dms_theme(home: &Path, theme: &DmsThemeConfig) -> Result<()> {
|
|
theme.validate()?;
|
|
|
|
// Create a safety checkpoint before writing
|
|
create_checkpoint(home, "pre_theme_change")?;
|
|
|
|
let dms_dir = dms_config_dir_for_home(home);
|
|
fs::create_dir_all(&dms_dir).map_err(|e| ExecError::Io {
|
|
path: dms_dir.clone(),
|
|
source: e,
|
|
})?;
|
|
|
|
let theme_file = dms_dir.join("theme.json");
|
|
let json_bytes = serde_json::to_vec_pretty(theme)
|
|
.map_err(|e| ExecError::operation("desktop", "dms_theme_serialize", e.to_string()))?;
|
|
|
|
// Atomic write
|
|
let tmp_file = dms_dir.join("theme.json.tmp");
|
|
fs::write(&tmp_file, json_bytes).map_err(|e| ExecError::Io {
|
|
path: tmp_file.clone(),
|
|
source: e,
|
|
})?;
|
|
fs::rename(&tmp_file, &theme_file).map_err(|e| ExecError::Io {
|
|
path: theme_file,
|
|
source: e,
|
|
})?;
|
|
|
|
Ok(())
|
|
}
|
|
|
|
/// Adds or updates a MangoWM keybinding with schema validation and auto-checkpoint.
|
|
pub fn add_mango_keybinding(home: &Path, keybinding: &MangoKeybinding) -> Result<()> {
|
|
keybinding.validate()?;
|
|
|
|
create_checkpoint(home, "pre_keybinding_change")?;
|
|
|
|
let mango_file = mango_config_file_for_home(home);
|
|
if let Some(parent) = mango_file.parent() {
|
|
fs::create_dir_all(parent).map_err(|e| ExecError::Io {
|
|
path: parent.to_path_buf(),
|
|
source: e,
|
|
})?;
|
|
}
|
|
|
|
let mut current_content = if mango_file.exists() {
|
|
fs::read_to_string(&mango_file).map_err(|e| ExecError::Io {
|
|
path: mango_file.clone(),
|
|
source: e,
|
|
})?
|
|
} else {
|
|
String::new()
|
|
};
|
|
|
|
let bind_entry = format!(
|
|
"\n# Keybinding added by agent\n[[keybinding]]\ncombo = \"{}\"\naction = \"{}\"\n",
|
|
keybinding.combo, keybinding.action
|
|
);
|
|
current_content.push_str(&bind_entry);
|
|
|
|
let tmp_file = mango_file.with_extension("toml.tmp");
|
|
fs::write(&tmp_file, current_content).map_err(|e| ExecError::Io {
|
|
path: tmp_file.clone(),
|
|
source: e,
|
|
})?;
|
|
fs::rename(&tmp_file, &mango_file).map_err(|e| ExecError::Io {
|
|
path: mango_file,
|
|
source: e,
|
|
})?;
|
|
|
|
Ok(())
|
|
}
|
|
|
|
/// Reverts the latest desktop configuration change using the latest recorded checkpoint.
|
|
pub fn undo_latest_checkpoint(home: &Path) -> Result<String> {
|
|
let cp_base = checkpoint_dir_for_home(home);
|
|
if !cp_base.exists() {
|
|
return Err(ExecError::operation(
|
|
"desktop",
|
|
"undo",
|
|
"no desktop checkpoints found to undo",
|
|
));
|
|
}
|
|
|
|
let mut entries = Vec::new();
|
|
let read_dir = fs::read_dir(&cp_base).map_err(|e| ExecError::Io {
|
|
path: cp_base.clone(),
|
|
source: e,
|
|
})?;
|
|
|
|
for entry in read_dir {
|
|
let entry = entry.map_err(|e| ExecError::Io {
|
|
path: cp_base.clone(),
|
|
source: e,
|
|
})?;
|
|
if entry.file_type().map(|t| t.is_dir()).unwrap_or(false) {
|
|
entries.push(entry.path());
|
|
}
|
|
}
|
|
|
|
entries.sort();
|
|
let latest = match entries.pop() {
|
|
Some(p) => p,
|
|
None => {
|
|
return Err(ExecError::operation(
|
|
"desktop",
|
|
"undo",
|
|
"no desktop checkpoints available to undo",
|
|
))
|
|
}
|
|
};
|
|
|
|
let dms_backup = latest.join("dms_theme.json");
|
|
if dms_backup.exists() {
|
|
let target = dms_config_dir_for_home(home).join("theme.json");
|
|
fs::copy(&dms_backup, &target).map_err(|e| ExecError::Io {
|
|
path: target,
|
|
source: e,
|
|
})?;
|
|
}
|
|
|
|
let mango_backup = latest.join("mango_config.toml");
|
|
if mango_backup.exists() {
|
|
let target = mango_config_file_for_home(home);
|
|
fs::copy(&mango_backup, &target).map_err(|e| ExecError::Io {
|
|
path: target,
|
|
source: e,
|
|
})?;
|
|
}
|
|
|
|
let dir_name = latest
|
|
.file_name()
|
|
.unwrap_or_default()
|
|
.to_string_lossy()
|
|
.to_string();
|
|
|
|
// Clean up the restored checkpoint
|
|
let _ = fs::remove_dir_all(&latest);
|
|
|
|
Ok(dir_name)
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
#[test]
|
|
fn hex_color_validation() {
|
|
assert!(is_valid_hex_color("#1a1b26"));
|
|
assert!(is_valid_hex_color("#FFFFFF"));
|
|
assert!(is_valid_hex_color("#000000"));
|
|
assert!(!is_valid_hex_color("1a1b26")); // missing #
|
|
assert!(!is_valid_hex_color("#1a1b2")); // too short
|
|
assert!(!is_valid_hex_color("#1a1b2677")); // too long
|
|
assert!(!is_valid_hex_color("#gggggg")); // invalid hex
|
|
}
|
|
|
|
#[test]
|
|
fn dms_theme_validation_rejects_bad_colors() {
|
|
let theme = DmsThemeConfig {
|
|
accent_color: Some("bad-color".into()),
|
|
dark_mode: Some(true),
|
|
wallpaper_path: None,
|
|
};
|
|
assert!(theme.validate().is_err());
|
|
}
|
|
|
|
#[test]
|
|
fn mango_keybinding_rejects_empty_and_control_chars() {
|
|
let empty_combo = MangoKeybinding {
|
|
combo: "".into(),
|
|
action: "spawn kitty".into(),
|
|
};
|
|
assert!(empty_combo.validate().is_err());
|
|
|
|
let newline_action = MangoKeybinding {
|
|
combo: "Mod4+Return".into(),
|
|
action: "spawn kitty\nrm -rf /".into(),
|
|
};
|
|
assert!(newline_action.validate().is_err());
|
|
}
|
|
|
|
#[test]
|
|
fn apply_theme_creates_checkpoint_and_undo_restores() {
|
|
let temp_dir = tempfile::tempdir().unwrap();
|
|
let home = temp_dir.path();
|
|
|
|
// 1. Initial theme
|
|
let theme1 = DmsThemeConfig {
|
|
accent_color: Some("#112233".into()),
|
|
dark_mode: Some(true),
|
|
wallpaper_path: None,
|
|
};
|
|
apply_dms_theme(home, &theme1).unwrap();
|
|
|
|
let theme_file = dms_config_dir_for_home(home).join("theme.json");
|
|
let content1 = fs::read_to_string(&theme_file).unwrap();
|
|
assert!(content1.contains("#112233"));
|
|
|
|
// 2. Mutated theme by agent
|
|
let theme2 = DmsThemeConfig {
|
|
accent_color: Some("#445566".into()),
|
|
dark_mode: Some(false),
|
|
wallpaper_path: None,
|
|
};
|
|
apply_dms_theme(home, &theme2).unwrap();
|
|
let content2 = fs::read_to_string(&theme_file).unwrap();
|
|
assert!(content2.contains("#445566"));
|
|
|
|
// 3. Undo restores previous theme
|
|
let restored = undo_latest_checkpoint(home).unwrap();
|
|
assert!(!restored.is_empty());
|
|
let content_restored = fs::read_to_string(&theme_file).unwrap();
|
|
assert!(content_restored.contains("#112233"));
|
|
}
|
|
}
|