//! Typed graphical frontend bridge. //! //! The Quickshell/QML installer never parses terminal output and never touches //! disks: it speaks newline-delimited JSON to this bridge over stdin/stdout. //! The bridge owns one [`Installer`] and is the only thing that can reach the //! deterministic backend. It reuses `InstallConfig`, validation, the plan, the //! audited [`DestructiveAuthorization`] flow and `Installer::install_observed`, //! so the graphical path cannot diverge from the TUI/CLI path. //! //! Secrets arrive over the stdin pipe (never argv, logs, config files or model //! context) and are registered with the redactor immediately. Progress events //! report the real backend stages; categories name the kind of work, and no //! percentage is ever invented. //! //! Run with `phoebus-installer --gui-bridge`. use std::io::{self, BufRead, Write}; use crate::{ai_guide, InstallObserver, Installer}; use phoebus_ai::provider::{ModelTransport, ProviderKind, SystemFacts}; use phoebus_core::{AiBackend, InstallConfig, InstallStep, SecretString}; use phoebus_executor::ai::CurlTransport; use phoebus_executor::auth::{authorize, Confirmation}; use phoebus_executor::{Exec, Result as ExecResult}; use serde::Deserialize; use serde_json::{json, Value}; /// The version of the bridge protocol understood by the QML frontend. pub const PROTOCOL_VERSION: u32 = 1; const MAX_LOG_TAIL: usize = 200; /// Upper bound on one request line. The frontend sends small, typed requests; /// anything larger is refused before parsing rather than buffered blindly. const MAX_LINE_BYTES: usize = 256 * 1024; /// Upper bound on a single secret value (passwords/passphrases/API keys). const MAX_SECRET_BYTES: usize = 16 * 1024; // --------------------------------------------------------------------------- // Protocol types // --------------------------------------------------------------------------- #[derive(Debug, Deserialize)] #[serde(deny_unknown_fields)] struct Request { id: u64, op: String, #[serde(default)] config: Option, #[serde(default)] secrets: Option, #[serde(default)] erase: Option, #[serde(default)] final_confirm: Option, #[serde(default)] plan_digest: Option, #[serde(default)] lines: Option, } #[derive(Debug, Default, Deserialize)] #[serde(deny_unknown_fields)] struct SecretsPatch { #[serde(default)] luks: Option, #[serde(default)] user_password: Option, #[serde(default)] root_password: Option, #[serde(default)] ai_api_key: Option, /// The OpenCode server password (basic auth). Distinct from a model /// provider API key and never stored in the configuration. #[serde(default)] opencode_password: Option, } /// A `Confirmation` whose answers come from an explicit GUI request. The ERASE /// phrase is checked here, so the audited [`authorize`] flow is unchanged. struct BridgeConfirm { erase: bool, final_ok: bool, } impl Confirmation for BridgeConfirm { fn confirm_erase(&self, _preview: &str) -> ExecResult { Ok(self.erase) } fn confirm_final(&self, _message: &str) -> ExecResult { Ok(self.final_ok) } } /// Writes progress events for the real backend stages and records the coarse /// disk-change phase so a failure can be explained accurately. struct JsonObserver { tx: std::sync::mpsc::Sender, id: u64, phase: std::rc::Rc>, } impl JsonObserver { fn emit(&mut self, step: InstallStep, status: &str, error: Option<&str>) { let (category, label) = step_meta(step); let event = json!({ "event": "progress", "id": self.id, "op": "start_install", "stage": step.name(), "category": category, "label": label, "status": status, "error": error, }); let _ = self.tx.send(event); } } impl InstallObserver for JsonObserver { fn stage_started(&mut self, step: InstallStep) { if step == InstallStep::StoragePrepare { self.phase.set(DiskPhase::InStorage); } self.emit(step, "started", None); } fn stage_finished(&mut self, step: InstallStep, error: Option<&str>) { if step == InstallStep::StoragePrepare && error.is_none() { self.phase.set(DiskPhase::AfterStorage); } self.emit( step, if error.is_some() { "failed" } else { "finished" }, error, ); } } /// Category + human label for a backend stage. Categories are the four the /// product distinguishes (download, compile, configure, verify) plus prepare. fn step_meta(step: InstallStep) -> (&'static str, &'static str) { match step { InstallStep::StoragePrepare => ("prepare", "Preparing the target disk"), InstallStep::StageInstall => ("download", "Downloading the Gentoo stage3"), InstallStep::FstabGenerate => ("configure", "Writing filesystem tables"), InstallStep::PortageConfigure => ("download", "Configuring and syncing Portage"), InstallStep::PackagesBase => ("compile", "Installing base packages"), InstallStep::KernelInstall => ("compile", "Building and installing the kernel"), InstallStep::NvidiaDrivers => ("compile", "Installing the NVIDIA driver"), InstallStep::BootInstall => ("configure", "Installing the boot loader"), InstallStep::UsersConfigure => ("configure", "Creating your account"), InstallStep::ServicesConfigure => ("configure", "Enabling system services"), InstallStep::DesktopInstall => ("compile", "Installing the desktop"), InstallStep::Finalize => ("verify", "Finalising and verifying"), } } // --------------------------------------------------------------------------- // Bridge // --------------------------------------------------------------------------- pub struct Bridge { installer: Installer, luks: Option, user_password: Option, root_password: Option, api_key: Option, opencode_password: Option, approved_digest: Option, /// Set only after a real, validated AI interaction (a proposal reviewed for /// the direct path, or a validated model response for OpenCode). A mere /// provider name never satisfies the mandatory-AI gate. validated_ai: Option, phase: std::rc::Rc>, /// One destructive transaction at a time. An approval is single-use: it is /// consumed when the install starts so a replay, a second frontend or a /// reconnected client cannot start a second overlapping installation. installing: bool, installed: bool, quit: bool, } impl Bridge { pub fn new(config: InstallConfig, exec: Exec) -> Self { let installer = Installer::new(config, exec); Self { installer, luks: None, user_password: None, root_password: None, api_key: None, opencode_password: None, approved_digest: None, validated_ai: None, phase: std::rc::Rc::new(std::cell::Cell::new(DiskPhase::BeforeStorage)), installing: false, installed: false, quit: false, } } /// Build directly on an installer (tests, embedded callers). pub fn with_installer(installer: Installer) -> Self { Self { installer, luks: None, user_password: None, root_password: None, api_key: None, opencode_password: None, approved_digest: None, validated_ai: None, phase: std::rc::Rc::new(std::cell::Cell::new(DiskPhase::BeforeStorage)), installing: false, installed: false, quit: false, } } /// Whether the caller asked the bridge to stop. pub fn should_quit(&self) -> bool { self.quit } /// Parse and dispatch one request line, writing events/responses to `out`. pub fn handle_line(&mut self, line: &str, out: &mut (dyn Write + Send)) -> io::Result<()> { let line = line.trim(); if line.is_empty() { return Ok(()); } if line.len() > MAX_LINE_BYTES { return write_json( out, &json!({ "ok": false, "error": format!("request too large ({} bytes)", line.len()), }), ); } let request: Request = match serde_json::from_str(line) { Ok(request) => request, Err(e) => { return write_json( out, &json!({ "ok": false, "error": format!("bad request: {e}") }), ) } }; self.dispatch(request, out) } fn dispatch(&mut self, request: Request, out: &mut (dyn Write + Send)) -> io::Result<()> { let id = request.id; let op = request.op.clone(); let result = match request.op.as_str() { "handshake" => self.handshake(), "readiness" => self.readiness(), "options" => self.options(), "ai_catalog" => self.ai_catalog(), "disks" => self.disks(), "set_config" => self.set_config(&request), "set_secrets" => self.set_secrets(&request), "validate" => self.validate(), "plan" => self.plan(), "destructive_preview" => self.destructive_preview(), "ai_check" => self.ai_check(), "ai_test" => self.ai_test(), "approve" => self.approve(&request), "start_install" => return self.start_install(id, &request, out), "log_tail" => self.log_tail(&request), "quit" => { self.quit = true; Ok(json!({ "bye": true })) } other => Err(format!("unknown op `{other}`")), }; match result { Ok(data) => write_json( out, &json!({ "id": id, "ok": true, "op": op, "data": data }), ), Err(error) => { // AI connection failures carry a stable, machine-readable kind // so the frontend can distinguish an authentication failure // from an unreachable server, a missing model or bad transport. // The human message stays authoritative and redacted. let mut payload = json!({ "id": id, "ok": false, "op": op, "error": error }); if matches!( op.as_str(), "ai_catalog" | "ai_check" | "ai_test" | "readiness" ) { payload["error_kind"] = json!(connection_error_kind( payload["error"].as_str().unwrap_or("") )); } write_json(out, &payload) } } } // -- read-only ops ------------------------------------------------------ fn handshake(&self) -> Result { let facts = self.installer.system_facts(); let network = network_ready(); let mut defaults = self.installer.config.clone(); let detected_tz = live_timezone(); if defaults.system.timezone == "UTC" && detected_tz != "UTC" { defaults.system.timezone = detected_tz; } let detected_km = live_keymap(); if defaults.system.keymap == "us" && detected_km != "us" { defaults.system.keymap = detected_km; } defaults.desktop.profile = phoebus_core::config::DesktopProfile::Mango; defaults.storage.filesystem = phoebus_core::config::Filesystem::Btrfs; defaults.desktop.flatpak = true; defaults.packages.nix = true; defaults.packages.binary_packages = true; Ok(json!({ "protocol": PROTOCOL_VERSION, "version": phoebus_core::VERSION, "iso_version": iso_version(), "build_id": std::env::var("PHOEBUS_BUILD_ID").unwrap_or_else(|_| "dev".into()), "live": std::path::Path::new("/etc/phoebus/live").exists(), "defaults": defaults, "readiness": { "network": network, "firmware": self.installer.hardware.firmware_str(), "memory_mib": self.installer.hardware.memory_mib, "cpu_cores": self.installer.hardware.cpu.cores, "cpu_model": self.installer.hardware.cpu.model, "desktop": defaults.desktop.profile.as_str(), "keymap_live": live_keymap(), }, "facts": facts, })) } /// A deeper, on-demand readiness probe. Unlike [`Self::handshake`] this may /// make one bounded network request, so the frontend calls it when the /// network step is shown or the user asks to re-check. It never changes /// configuration or state, so refreshing readiness cannot reset the wizard. fn readiness(&self) -> Result { let link = network_ready(); let services = service_reachability(&self.installer); Ok(json!({ "network": link, "network_services": services.reachable, "network_detail": services.detail, "network_target": services.target, "firmware": self.installer.hardware.firmware_str(), "memory_mib": self.installer.hardware.memory_mib, "cpu_cores": self.installer.hardware.cpu.cores, "cpu_model": self.installer.hardware.cpu.model, "desktop": self.installer.config.desktop.profile.as_str(), "keymap_live": live_keymap(), })) } /// Selectable options for the language/region step. Reading these from the /// live system means the user picks from the real timezones, locales and /// keymaps instead of typing them from memory. fn options(&self) -> Result { Ok(json!({ "timezones": labeled_options(system_timezones(), humanize_timezone), "locales": labeled_options(system_locales(), humanize_locale), "keymaps": labeled_options(system_keymaps(), humanize_keymap), // The live session's own layout, so the frontend can be truthful // about whether a selection affects the running graphical session. "keymap_live": live_keymap(), })) } /// The providers and models the configured AI connection actually offers: /// the OpenCode catalog, or an OpenAI-compatible `/models` list. Read-only; /// never returns provider credentials. fn ai_catalog(&self) -> Result { use phoebus_executor::opencode_client::{CurlHttpClient, HttpClient, OpenCodeClient}; use phoebus_executor::opencode_server::Endpoint; let redact = self.installer.exec.redactor(); match self.installer.config.ai.backend { AiBackend::OpenCode => { // The catalog only needs the server; the model is optional. let server = self.installer.config.ai.opencode_server.trim().to_string(); if server.is_empty() { return Err("OpenCode requires a server URL".into()); } let provider = self .installer .config .ai .opencode_provider .trim() .to_string(); let model = self.installer.config.ai.opencode_model.trim().to_string(); let endpoint = Endpoint::parse(&server) .map_err(|e| format!("invalid OpenCode endpoint: {e}"))?; let target = endpoint .checked_target() .map_err(|e| redact.redact(&e.to_string()))?; let http = CurlHttpClient::new(&self.installer.exec); // The provider catalog can be several MiB on a busy server. let client = OpenCodeClient::new(&http, endpoint.base(), &provider, &model) .with_auth(self.opencode_password.clone()) .with_max_body(16 * 1024 * 1024) .with_resolve(Some((endpoint.host.clone(), endpoint.port, target.ip()))); match client.catalog() { Ok(catalog) => { let providers: Vec = catalog .providers .iter() .map( |p| json!({ "id": p.id, "name": p.name, "connected": p.connected }), ) .collect(); let models: Vec = catalog .providers .iter() .find(|p| p.id == provider) .or_else(|| catalog.providers.iter().find(|p| !p.models.is_empty())) .map(|p| { p.models .iter() .map(|m| { let label = if m.name != m.id { format!("{} ({})", m.name, m.id) } else { m.name.clone() }; json!({ "id": m.id, "name": m.name, "label": label, "value": m.id, "variants": m.variants, }) }) .collect() }) .unwrap_or_default(); Ok(json!({ "backend": "opencode", "providers": providers, "models": models, })) } Err(e) => Err(redact.redact(&e.to_string())), } } AiBackend::Direct => { let raw = self.installer.config.ai.provider.clone(); let provider = ProviderKind::parse(&raw) .ok_or_else(|| format!("unknown AI provider `{raw}`"))?; if provider == ProviderKind::None { return Err("no AI provider selected".into()); } let endpoint = if self.installer.config.ai.endpoint.is_empty() { provider.endpoint().to_string() } else { self.installer.config.ai.endpoint.clone() }; let url = models_url(&endpoint); let mut request = phoebus_executor::opencode_client::HttpRequest::get(url); request.auth_user = String::new(); // OpenAI-compatible: Bearer request.auth = self.api_key.clone(); let http = CurlHttpClient::new(&self.installer.exec); match http.request(&request) { Ok(response) if response.is_success() => { let models: Vec = parse_model_ids(&response.body) .into_iter() .map(|id| { json!({ "id": id, "name": id, "label": id, "value": id, "variants": ["default"], }) }) .collect(); Ok(json!({ "backend": "direct", "providers": [ { "id": provider.as_str(), "name": provider.as_str(), "connected": true } ], "models": models, })) } Ok(response) => Err(format!("model list returned HTTP {}", response.status)), Err(e) => Err(redact.redact(&e.to_string())), } } } } fn disks(&mut self) -> Result { self.installer.disks = phoebus_executor::probe::probe_disks(self.installer.exec.runner.as_ref()); let runner = self.installer.exec.runner.as_ref(); let disks: Vec = self .installer .disks .iter() .map(|d| { let partitions = phoebus_executor::probe::disk_partitions(runner, &d.path); json!({ "path": d.path, "identifier": d.path, "model": d.model.clone().unwrap_or_else(|| "Unknown disk".into()), "size_bytes": d.size_bytes, "size_human": d.size_human(), "transport": d.transport.clone().unwrap_or_else(|| "unknown".into()), "removable": d.removable, "protected": d.is_protected(), "protection": d.protection().map(|r| r.describe()), "live_medium": d.live_media, "kind": format!("{:?}", d.kind).to_lowercase(), "partitions": partitions, }) }) .collect(); Ok(json!({ "disks": disks })) } fn validate(&self) -> Result { let issues = self.installer.validate(); let complete = issues.is_empty(); Ok(json!({ "complete": complete, "issues": issues.iter().map(|i| json!({ "field": i.field, "message": i.message, })).collect::>(), })) } fn plan(&self) -> Result { let issues = self.installer.validate(); let plan = self.installer.plan(); Ok(json!({ "human": self.installer.render_plan(), "plan_digest": self.plan_digest(), "steps": plan.steps.iter().map(|s| json!({ "stage": s.name(), "category": step_meta(*s).0, "label": step_meta(*s).1, })).collect::>(), "validation": issues.iter().map(|i| json!({ "field": i.field, "message": i.message, })).collect::>(), "review": self.review(), })) } fn destructive_preview(&self) -> Result { Ok(json!({ "text": self.installer.destructive_preview(), "plan_digest": self.plan_digest(), })) } fn log_tail(&self, request: &Request) -> Result { let path = self.installer.exec.log_path().to_path_buf(); let text = std::fs::read_to_string(&path).unwrap_or_default(); let want = request.lines.unwrap_or(40).min(MAX_LOG_TAIL); // The logger already redacted, but re-redact on read so a rotated or // externally-written file can never leak a registered secret. let redacted = self.installer.exec.redactor().redact(&text); let lines: Vec<&str> = redacted.lines().rev().take(want).collect(); let tail: Vec<&str> = lines.into_iter().rev().collect(); Ok(json!({ "path": path.display().to_string(), "lines": tail, })) } // -- configuration ------------------------------------------------------ fn set_config(&mut self, request: &Request) -> Result { let mut config: InstallConfig = serde_json::from_value( request .config .clone() .ok_or_else(|| "set_config requires a `config` object".to_string())?, ) .map_err(|e| format!("invalid configuration: {e}"))?; // Secrets never live in the configuration. Reject an attempt to smuggle // one in, rather than silently persisting it. if config .to_toml_string() .map(|t| contains_secret_marker(&t)) .unwrap_or(false) { return Err("configuration must not contain secret material".into()); } // The bridge is an installer for this machine; the dry-run/log paths are // backend concerns and not user-selectable from the GUI. config.runtime.dry_run = self.installer.config.runtime.dry_run; let ai_before = ai_digest(&self.installer.config); self.installer.reconfigure(config); self.approved_digest = None; // Only a change to the AI connection settings invalidates the AI // validation. Choosing a disk, typing a hostname or similar must not // throw away a successful model interaction. if ai_digest(&self.installer.config) != ai_before { self.validated_ai = None; } let issues = self.installer.validate(); Ok(json!({ "accepted": true, "plan_digest": self.plan_digest(), "complete": issues.is_empty(), "issues": issues.iter().map(|i| json!({ "field": i.field, "message": i.message, })).collect::>(), })) } fn set_secrets(&mut self, request: &Request) -> Result { let patch = request .secrets .as_ref() .ok_or_else(|| "set_secrets requires a `secrets` object".to_string())?; for value in [ &patch.luks, &patch.user_password, &patch.root_password, &patch.ai_api_key, &patch.opencode_password, ] .into_iter() .flatten() { if value.len() > MAX_SECRET_BYTES { return Err("secret value is too large".into()); } } if let Some(v) = &patch.luks { let s = SecretString::new(v.clone()); self.installer.exec.register_secret(&s); self.luks = Some(s); } if let Some(v) = &patch.user_password { let s = SecretString::new(v.clone()); self.installer.exec.register_secret(&s); self.user_password = Some(s); } if let Some(v) = &patch.root_password { let s = SecretString::new(v.clone()); self.installer.exec.register_secret(&s); self.root_password = Some(s); } let mut ai_credential_changed = false; if let Some(v) = &patch.ai_api_key { let s = SecretString::new(v.clone()); self.installer.exec.register_secret(&s); self.api_key = Some(s); ai_credential_changed = true; } if let Some(v) = &patch.opencode_password { let s = SecretString::new(v.clone()); self.installer.exec.register_secret(&s); self.opencode_password = Some(s); ai_credential_changed = true; } // Only an AI credential change invalidates the AI validation; account // and disk secrets do not. if ai_credential_changed { self.validated_ai = None; } // Report only presence, never values. Ok(json!({ "luks_set": self.luks.is_some(), "user_password_set": self.user_password.is_some(), "root_password_set": self.root_password.is_some(), "ai_api_key_set": self.api_key.is_some(), "opencode_password_set": self.opencode_password.is_some(), })) } // -- AI ----------------------------------------------------------------- fn ai_check(&mut self) -> Result { let facts = self.installer.system_facts(); let backend = self.installer.config.ai.backend; let api_key = self.api_key.clone(); let opencode_password = self.opencode_password.clone(); let value = { let Installer { exec, config, .. } = &mut self.installer; let redactor = exec.redactor(); match backend { AiBackend::OpenCode => { let transport = opencode_transport(exec, config, opencode_password)?; review_opencode(config, redactor, facts, &transport)? } AiBackend::Direct => { let transport = CurlTransport::new(exec, api_key.clone()); review_proposal(config, redactor, facts, api_key.is_some(), &transport)? } } }; self.approved_digest = None; // Bind the validated interaction to the exact configuration it was // validated against; any later change clears it. self.validated_ai = Some(ai_digest(&self.installer.config)); Ok(value) } /// A real, minimal model interaction that obtains and validates a JSON model /// response without changing the configuration. This is "Test connection". fn ai_test(&mut self) -> Result { use phoebus_ai::provider::{build_request, extract_content}; let backend = self.installer.config.ai.backend; let facts = self.installer.system_facts(); let redactor = self.installer.exec.redactor(); let (kind, endpoint, model, label) = match backend { AiBackend::OpenCode => { let (server, provider, model, _) = opencode_parts(&self.installer.config)?; (ProviderKind::Local, server, model, provider) } AiBackend::Direct => { let raw = self.installer.config.ai.provider.clone(); let provider = ProviderKind::parse(&raw) .ok_or_else(|| format!("unknown AI provider `{raw}`"))?; if provider == ProviderKind::None { return Err("no AI provider selected".into()); } let endpoint = if self.installer.config.ai.endpoint.is_empty() { provider.endpoint().to_string() } else { self.installer.config.ai.endpoint.clone() }; let model = if self.installer.config.ai.model.is_empty() { provider.default_model().to_string() } else { self.installer.config.ai.model.clone() }; (provider, endpoint, model, provider.as_str().to_string()) } }; let request = build_request(kind, &model, &facts); let body = serde_json::to_string(&request) .map_err(|e| format!("could not build the test request: {e}"))?; let response = match backend { AiBackend::OpenCode => { let transport = opencode_transport( &self.installer.exec, &self.installer.config, self.opencode_password.clone(), )?; transport.send(kind, &endpoint, &body) } AiBackend::Direct => { let transport = CurlTransport::new(&self.installer.exec, self.api_key.clone()); transport.send(kind, &endpoint, &body) } } .map_err(|e| format!("connection failed: {}", redactor.redact(&e.to_string())))?; let content = extract_content(&response).map_err(|e| { format!( "model response was not usable: {}", redactor.redact(&e.to_string()) ) })?; serde_json::from_str::(&content) .map_err(|_| "model response was not JSON".to_string())?; Ok(json!({ "connected": true, "backend": backend.as_str(), "provider": label, "model": model, "response": content, })) } /// Validate the provider connection and review the proposal (fail-closed). /// Exposed so tests can drive it with a canned transport. pub fn ai_check_with(&mut self, transport: &dyn ModelTransport) -> Result { let facts = self.installer.system_facts(); let api_key_present = self.api_key.is_some(); let value = { let Installer { exec, config, .. } = &mut self.installer; review_proposal(config, exec.redactor(), facts, api_key_present, transport)? }; self.approved_digest = None; self.validated_ai = Some(ai_digest(&self.installer.config)); Ok(value) } // -- authorization and install ------------------------------------------ fn approve(&mut self, request: &Request) -> Result { let phrase = request.erase.clone().unwrap_or_default(); if phrase != "ERASE" { return Err("type ERASE exactly to authorize disk changes".into()); } if request.final_confirm != Some(true) { return Err("the final confirmation is required".into()); } let digest = self.plan_digest(); self.approved_digest = Some(digest.clone()); Ok(json!({ "approved": true, "plan_digest": digest })) } fn start_install( &mut self, id: u64, request: &Request, out: &mut (dyn Write + Send), ) -> io::Result<()> { let result = self.run_install(id, request, out); match result { Ok(data) => write_json( out, &json!({ "id": id, "ok": true, "op": "start_install", "data": data }), ), Err(error) => write_json( out, &json!({ "id": id, "ok": false, "op": "start_install", "error": error }), ), } } fn run_install( &mut self, id: u64, request: &Request, out: &mut (dyn Write + Send), ) -> Result { if self.installing { return Err("an installation is already in progress".into()); } if self.installed { return Err( "this session has already installed Phoebus; start a new session to \ install again" .into(), ); } // The plan may not have changed since the user approved it. let current = self.plan_digest(); match (&self.approved_digest, &request.plan_digest) { (Some(approved), Some(presented)) if approved == presented && presented == ¤t => { } _ => { return Err( "the installation plan is not approved (or changed since approval); \ review the plan and confirm ERASE again" .into(), ) } } // AI is mandatory to install unless this is a dry run or an explicit // break-glass. A validated interaction is required: merely naming a // provider is not enough. The validation is bound to the current // configuration, so a change since validation invalidates it. let dry_run = self.installer.config.runtime.dry_run; if !dry_run { let break_glass = std::env::var("PHOEBUS_NO_AI") .map(|v| matches!(v.to_ascii_lowercase().as_str(), "1" | "yes" | "true")) .unwrap_or(false); let validated = self.validated_ai.as_deref() == Some(ai_digest(&self.installer.config).as_str()); if !validated && !break_glass { return Err( "installing Phoebus requires a successful, validated AI interaction for \ the current configuration; connect and validate a model, or set \ PHOEBUS_NO_AI=1 for a deterministic install" .into(), ); } } let issues = self.installer.validate(); if !issues.is_empty() { let text = issues .iter() .map(|i| i.to_string()) .collect::>() .join("; "); return Err(format!("configuration is incomplete: {text}")); } let preview = self.installer.destructive_preview(); let confirm = BridgeConfirm { erase: request.erase.as_deref() == Some("ERASE"), final_ok: request.final_confirm == Some(true), }; let auth = authorize(&confirm, &preview, "Start the installation now?") .map_err(|e| self.installer.exec.redactor().redact(&e.to_string()))?; let (tx, rx) = std::sync::mpsc::channel::(); let tx_log = tx.clone(); let log_listener = std::sync::Arc::new(move |chunk: &str| { for line in chunk.lines() { let line = line.trim(); if !line.is_empty() { let _ = tx_log.send(json!({ "event": "log", "line": line, })); } } }); self.installer.exec.logger.add_listener(log_listener); let mut observer = JsonObserver { tx: tx.clone(), id, phase: self.phase.clone(), }; self.phase.set(DiskPhase::BeforeStorage); // Consume the approval and mark the session busy before any destructive // work: a replay or a second frontend can never reach storage_prepare. self.approved_digest = None; self.validated_ai = None; self.installing = true; let outcome = std::thread::scope(|s| { s.spawn(move || { while let Ok(event) = rx.recv() { let _ = write_json(out, &event); } }); let res = self.installer.install_observed( &auth, self.luks.as_ref(), self.user_password.as_ref(), self.root_password.as_ref(), &mut observer, ); // Drop the observer before the scope joins: its `tx` clone is the // last sender, and the writer thread only exits when every sender // is gone. Keeping it alive past the closure deadlocks the join. drop(observer); self.installer.exec.logger.clear_listeners(); drop(tx); res }); self.installing = false; match outcome { Ok(()) => { self.installed = true; Ok(json!({ "complete": true, "dry_run": dry_run, "log_path": self.installer.exec.log_path().display().to_string(), "next_actions": [ "Remove the installation medium.", "Restart the computer and boot Phoebus OS.", ], })) } Err(e) => { let message = self.installer.exec.redactor().redact(&e.to_string()); let (disk_changed, next_actions) = disk_change_report(self.phase.get()); Err(format!( "installation failed: {message}\n\ disk_changed: {disk_changed}\n\ next: {}", next_actions.join(" ") )) } } } // -- helpers ------------------------------------------------------------ /// A stable digest binding an approval to the exact plan shown. Any change /// to the configuration (including AI-applied changes) changes it. fn plan_digest(&self) -> String { config_digest(&self.installer.config) } fn review(&self) -> Value { let c = &self.installer.config; let mut subsystems = vec![c.system.init_system.clone()]; if c.desktop.profile.is_desktop() { subsystems.push(c.desktop.audio_stack.clone()); if c.desktop.flatpak { subsystems.push("flatpak".into()); } } if c.packages.nix { subsystems.push("nix".into()); } if c.storage.filesystem == phoebus_core::Filesystem::Btrfs { subsystems.push("btrfs snapshots".into()); } json!({ "target_disk": c.storage.disk, "erase": self.installer.destructive_preview(), "filesystem": c.storage.filesystem.as_str(), "encryption": c.encryption.mode.as_str(), "desktop": c.desktop.profile.as_str(), "subvolumes": c.storage.subvols, "subsystems": subsystems, "hostname": c.system.hostname, "username": c.user.username, "timezone": c.system.timezone, "locale": c.system.locale, "keymap": c.system.keymap, }) } } fn contains_secret_marker(toml: &str) -> bool { let lower = toml.to_ascii_lowercase(); ["passphrase", "password", "api_key", "secret"] .iter() .any(|m| lower.contains(m)) } /// Coarse phase of the last reported progress event, used to explain whether /// disk changes occurred. Updated by the observer from the real stage order. #[derive(Debug, Clone, Copy, PartialEq, Eq)] enum DiskPhase { BeforeStorage, InStorage, AfterStorage, } fn disk_change_report(phase: DiskPhase) -> (&'static str, Vec<&'static str>) { match phase { DiskPhase::BeforeStorage => ( "none", vec!["Review the installer log, then retry the installation."], ), DiskPhase::InStorage => ( "partial", vec![ "The target disk may have been partially modified.", "Review the installer log before retrying.", ], ), DiskPhase::AfterStorage => ( "yes", vec![ "The target disk was re-partitioned.", "Review the installer log, then restart the installation (the disk is re-created from scratch).", ], ), } } /// True when a default route exists. Read-only, no privileges. fn network_ready() -> bool { let Ok(text) = std::fs::read_to_string("/proc/net/route") else { return false; }; text.lines().skip(1).any(|line| { let mut fields = line.split_whitespace(); let _iface = fields.next(); matches!(fields.next(), Some("00000000")) }) } /// The result of a bounded reachability check against the configured /// installation source. A default route proves a local link; only a completed /// request proves the installation services are actually reachable. struct ServiceReachability { reachable: bool, detail: String, target: String, } fn service_reachability(installer: &Installer) -> ServiceReachability { use phoebus_executor::opencode_client::{CurlHttpClient, HttpClient, HttpRequest}; let config = &installer.config; let target = if !config.stage3.url.trim().is_empty() { config.stage3.url.trim().to_string() } else { config.stage3.mirror.trim().to_string() }; if target.is_empty() { return ServiceReachability { reachable: false, detail: "No installation source is configured.".into(), target, }; } let mut request = HttpRequest::get(target.clone()); // Keep the check snappy: the user is waiting on it. request.timeout = std::time::Duration::from_secs(8); request.connect_timeout = std::time::Duration::from_secs(5); request.max_body = 64 * 1024; let http = CurlHttpClient::new(&installer.exec); match http.request(&request) { Ok(_) => ServiceReachability { reachable: true, detail: "Installation services are reachable.".into(), target, }, Err(e) => ServiceReachability { reachable: false, detail: installer.exec.redactor().redact(&e.to_string()), target, }, } } /// The live medium's console keymap, read without privileges. Used to tell the /// truth about whether choosing a layout changes the running session. fn live_keymap() -> String { if let Ok(text) = std::fs::read_to_string("/etc/vconsole.conf") { for line in text.lines() { if let Some(value) = line.trim().strip_prefix("KEYMAP=") { let value = value.trim().trim_matches('"'); if !value.is_empty() { return value.to_string(); } } } } std::env::var("XKB_DEFAULT_LAYOUT") .ok() .filter(|v| !v.trim().is_empty()) .unwrap_or_else(|| "us".into()) } /// The live medium's timezone, read from /etc/localtime symlink or /etc/timezone. fn live_timezone() -> String { if let Ok(dest) = std::fs::read_link("/etc/localtime") { let path = dest.display().to_string(); if let Some(pos) = path.find("zoneinfo/") { let tz = &path[pos + "zoneinfo/".len()..]; if !tz.is_empty() { return tz.to_string(); } } } if let Ok(text) = std::fs::read_to_string("/etc/timezone") { let trimmed = text.trim(); if !trimmed.is_empty() { return trimmed.to_string(); } } "UTC".to_string() } /// Classify a connection error into a stable kind. The frontend uses this to /// show an actionable recovery instead of a raw transport string. fn connection_error_kind(message: &str) -> &'static str { let m = message.to_ascii_lowercase(); if m.contains("authentication required") || m.contains("requires authentication") || m.contains("no api key") || m.contains("requires an api key") { "authentication_required" } else if m.contains("authentication rejected") || m.contains("rejected the supplied") || m.contains("http 401") || m.contains("http 403") { "authentication_rejected" } else if m.contains("insecure_transport") || m.contains("plain http") || m.contains("must use https") { "insecure_transport" } else if m.contains("http 404") || m.contains("model not found") || m.contains("unknown model") || m.contains("no such model") { "model_unavailable" } else if m.contains("timed out") || m.contains("timeout") || m.contains("connection refused") || m.contains("could not connect") || m.contains("failed to connect") || m.contains("transport") || m.contains("unreachable") { "unreachable" } else { "error" } } /// Turn a plain value list into `{value, label}` pairs so the frontend can show /// human-readable names while the backend keeps validating the real identifier. fn labeled_options(values: Vec, label: fn(&str) -> String) -> Vec { values .into_iter() .map(|value| { let text = label(&value); json!({ "value": value, "label": text }) }) .collect() } fn humanize_timezone(zone: &str) -> String { match zone { "UTC" => "UTC — Coordinated Universal Time".to_string(), _ => zone.replace('_', " ").replace('/', " / "), } } /// A friendly language (and region, when known) name for a POSIX locale, with /// the technical identifier kept at the end for advanced users. fn humanize_locale(locale: &str) -> String { let base = locale.split('.').next().unwrap_or(locale); let mut parts = base.split('_'); let language = parts.next().unwrap_or(""); let region = parts.next(); match (language_name(language), region.and_then(region_name)) { (Some(lang), Some(region)) => format!("{lang} ({region}) — {locale}"), (Some(lang), None) => format!("{lang} — {locale}"), _ => locale.to_string(), } } fn language_name(code: &str) -> Option<&'static str> { Some(match code { "en" => "English", "de" => "German", "fr" => "French", "es" => "Spanish", "it" => "Italian", "pt" => "Portuguese", "nl" => "Dutch", "pl" => "Polish", "ru" => "Russian", "uk" => "Ukrainian", "cs" => "Czech", "sk" => "Slovak", "sv" => "Swedish", "nb" | "no" => "Norwegian", "da" => "Danish", "fi" => "Finnish", "el" => "Greek", "tr" => "Turkish", "hu" => "Hungarian", "ro" => "Romanian", "bg" => "Bulgarian", "hr" => "Croatian", "sr" => "Serbian", "sl" => "Slovenian", "et" => "Estonian", "lv" => "Latvian", "lt" => "Lithuanian", "ja" => "Japanese", "ko" => "Korean", "zh" => "Chinese", "hi" => "Hindi", "bn" => "Bengali", "ar" => "Arabic", "he" => "Hebrew", "fa" => "Persian", "th" => "Thai", "vi" => "Vietnamese", "id" => "Indonesian", "ms" => "Malay", "sw" => "Swahili", "ca" => "Catalan", "gl" => "Galician", "eu" => "Basque", "is" => "Icelandic", "ga" => "Irish", "cy" => "Welsh", "sq" => "Albanian", "mk" => "Macedonian", "be" => "Belarusian", "az" => "Azerbaijani", "kk" => "Kazakh", "uz" => "Uzbek", "ka" => "Georgian", "hy" => "Armenian", "af" => "Afrikaans", _ => return None, }) } fn region_name(code: &str) -> Option<&'static str> { Some(match code.to_ascii_uppercase().as_str() { "US" => "United States", "GB" => "United Kingdom", "DE" => "Germany", "FR" => "France", "ES" => "Spain", "IT" => "Italy", "PT" => "Portugal", "BR" => "Brazil", "NL" => "Netherlands", "BE" => "Belgium", "AT" => "Austria", "CH" => "Switzerland", "PL" => "Poland", "RU" => "Russia", "UA" => "Ukraine", "CZ" => "Czechia", "SK" => "Slovakia", "SE" => "Sweden", "NO" => "Norway", "DK" => "Denmark", "FI" => "Finland", "GR" => "Greece", "TR" => "Türkiye", "HU" => "Hungary", "RO" => "Romania", "BG" => "Bulgaria", "HR" => "Croatia", "RS" => "Serbia", "SI" => "Slovenia", "EE" => "Estonia", "LV" => "Latvia", "LT" => "Lithuania", "JP" => "Japan", "KR" => "South Korea", "CN" => "China", "TW" => "Taiwan", "IN" => "India", "SG" => "Singapore", "AU" => "Australia", "NZ" => "New Zealand", "CA" => "Canada", "MX" => "Mexico", "AR" => "Argentina", "ZA" => "South Africa", "IE" => "Ireland", "IL" => "Israel", "AE" => "United Arab Emirates", "SA" => "Saudi Arabia", "TH" => "Thailand", "VN" => "Vietnam", "ID" => "Indonesia", "MY" => "Malaysia", "PH" => "Philippines", _ => return None, }) } /// A friendly keyboard name for a console keymap identifier, with the technical /// name kept so an advanced user can still see exactly what will be set. fn humanize_keymap(name: &str) -> String { let base = name.split('-').next().unwrap_or(name); let language = match base { "us" => "English (US)", "gb" | "uk" => "English (UK)", "au" => "English (Australia)", "nz" => "English (New Zealand)", "za" => "English (South Africa)", "de" => "German", "fr" => "French", "es" => "Spanish", "it" => "Italian", "pt" => "Portuguese", "br" | "br-abnt2" => "Portuguese (Brazil)", "latam" => "Spanish (Latin America)", "nl" => "Dutch", "be" => "Belgian", "dk" => "Danish", "no" => "Norwegian", "se" => "Swedish", "fi" => "Finnish", "is" => "Icelandic", "pl" => "Polish", "cz" => "Czech", "sk" => "Slovak", "hu" => "Hungarian", "ro" => "Romanian", "bg" => "Bulgarian", "gr" => "Greek", "ru" => "Russian", "ua" => "Ukrainian", "tr" => "Turkish", "il" => "Hebrew", "ara" => "Arabic", "in" => "Indian", "jp" | "jp106" => "Japanese", "kr" => "Korean", "cn" => "Chinese", "tw" => "Chinese (Taiwan)", "ca" => "Canadian", "cf" => "Canadian (French)", "ch" => "Swiss", "at" => "German (Austria)", "ie" => "Irish", "si" => "Slovenian", "hr" => "Croatian", "ee" => "Estonian", "lt" => "Lithuanian", "lv" => "Latvian", "mk" => "Macedonian", "rs" => "Serbian", "by" => "Belarusian", "kz" => "Kazakh", "al" => "Albanian", "ba" => "Bosnian", "ph" => "Filipino", "id" => "Indonesian", "my" => "Malay", "mt" => "Maltese", "np" => "Nepali", "pk" => "Urdu", "uz" => "Uzbek", "et" => "Amharic", "bd" => "Bangla", "af" => "Dari", "dz" => "Berber", "kh" => "Khmer", "la" => "Lao", "me" => "Montenegrin", "mn" => "Mongolian", "us-dvorak" | "dvorak" => "Dvorak", "colemak" => "Colemak", "mac-us" => "Mac (US)", "sg" => "Swiss German", "th" => "Thai", "vn" => "Vietnamese", "ir" | "fa" => "Persian", "az" => "Azerbaijani", "ge" => "Georgian", "am" => "Armenian", _ => "", }; if language.is_empty() { name.to_string() } else if language == name { language.to_string() } else { format!("{language} — {name}") } } fn iso_version() -> String { if let Ok(text) = std::fs::read_to_string("/etc/phoebus/version") { let t = text.trim(); if !t.is_empty() { return t.to_string(); } } phoebus_core::VERSION.to_string() } fn write_json(out: &mut dyn Write, value: &Value) -> io::Result<()> { serde_json::to_writer(&mut *out, value)?; out.write_all(b"\n")?; out.flush() } /// A deterministic digest of the configuration plus the step sequence. Any /// material change to the plan changes the digest, invalidating an approval. fn config_digest(config: &InstallConfig) -> String { use sha2::{Digest, Sha256}; let mut hasher = Sha256::new(); hasher.update(config.to_toml_string().unwrap_or_default().as_bytes()); for step in InstallStep::sequence() { hasher.update(step.name().as_bytes()); } format!("{:x}", hasher.finalize()) } /// The OpenCode server URL, provider id, model id and variant, validated for presence. fn opencode_parts(config: &InstallConfig) -> Result<(String, String, String, String), String> { let server = config.ai.opencode_server.trim().to_string(); let provider = config.ai.opencode_provider.trim().to_string(); let model = config.ai.opencode_model.trim().to_string(); let variant = config.ai.opencode_variant().to_string(); if server.is_empty() { return Err("OpenCode requires a server URL".into()); } if provider.is_empty() { return Err("OpenCode requires a provider".into()); } if model.is_empty() { return Err("OpenCode requires a model".into()); } // Fail fast on an unsafe endpoint, before any request is attempted. phoebus_executor::opencode_server::Endpoint::parse(&server) .map_err(|e| format!("invalid OpenCode endpoint: {e}"))?; Ok((server, provider, model, variant)) } /// Time zones offered by the live system, from the zoneinfo database. fn system_timezones() -> Vec { let mut zones: std::collections::BTreeSet = std::collections::BTreeSet::new(); if let Ok(text) = std::fs::read_to_string("/usr/share/zoneinfo/zone.tab") { for line in text.lines() { let line = line.trim(); if line.is_empty() || line.starts_with('#') { continue; } if let Some(tz) = line.split_whitespace().nth(2) { zones.insert(tz.to_string()); } } } if zones.is_empty() { for zone in [ "UTC", "Europe/London", "Europe/Berlin", "Europe/Paris", "America/New_York", "America/Chicago", "America/Denver", "America/Los_Angeles", "Asia/Tokyo", "Asia/Shanghai", "Asia/Kolkata", "Australia/Sydney", ] { zones.insert(zone.to_string()); } } zones.into_iter().take(2000).collect() } /// Locales from the system's i18n database (or a common fallback set). fn system_locales() -> Vec { let mut locales: std::collections::BTreeSet = std::collections::BTreeSet::new(); if let Ok(text) = std::fs::read_to_string("/usr/share/i18n/SUPPORTED") { for line in text.lines() { let line = line.trim(); if line.is_empty() || line.starts_with('#') { continue; } if let Some(locale) = line.split_whitespace().next() { if locale.contains("UTF-8") { locales.insert(locale.to_string()); } } } } if locales.is_empty() { for locale in [ "en_US.UTF-8", "en_GB.UTF-8", "de_DE.UTF-8", "fr_FR.UTF-8", "es_ES.UTF-8", "it_IT.UTF-8", "pt_BR.UTF-8", "pt_PT.UTF-8", "ja_JP.UTF-8", "zh_CN.UTF-8", "zh_TW.UTF-8", "ko_KR.UTF-8", "ru_RU.UTF-8", "nl_NL.UTF-8", "pl_PL.UTF-8", "sv_SE.UTF-8", "da_DK.UTF-8", "nb_NO.UTF-8", "fi_FI.UTF-8", "cs_CZ.UTF-8", "uk_UA.UTF-8", "tr_TR.UTF-8", ] { locales.insert(locale.to_string()); } } let mut list: Vec = locales.into_iter().take(2000).collect(); if let Some(pos) = list.iter().position(|x| x == "en_US.UTF-8") { let us = list.remove(pos); list.insert(0, us); } list } /// Keyboard layouts from XKB rules (or a standard desktop fallback set). fn system_keymaps() -> Vec { for path in [ "/usr/share/X11/xkb/rules/evdev.lst", "/usr/share/X11/xkb/rules/base.lst", ] { if let Ok(content) = std::fs::read_to_string(path) { let mut in_layout = false; let mut list = Vec::new(); for line in content.lines() { let trimmed = line.trim(); if trimmed.starts_with('!') { if trimmed == "! layout" { in_layout = true; } else if in_layout { break; } continue; } if in_layout && !trimmed.is_empty() { if let Some(code) = trimmed.split_whitespace().next() { if code != "custom" { list.push(code.to_string()); } } } } if !list.is_empty() { if let Some(pos) = list.iter().position(|x| x == "us") { let us = list.remove(pos); list.insert(0, us); } return list; } } } // Fallback list of standard desktop keyboard layouts vec![ "us", "gb", "de", "fr", "es", "latam", "it", "pt", "br", "nl", "be", "ch", "at", "dk", "no", "se", "fi", "pl", "cz", "sk", "hu", "ro", "bg", "gr", "ru", "ua", "tr", "il", "ara", "in", "jp", "kr", "cn", "tw", "ca", "ie", "si", "hr", "ee", "lt", "lv", "rs", "by", "kz", "th", "vn", "ir", "az", "ge", "am", "al", "ba", "dvorak", "colemak", ] .into_iter() .map(String::from) .collect() } /// The OpenAI-compatible model-list URL for a chat-completions endpoint. fn models_url(endpoint: &str) -> String { let trimmed = endpoint.trim().trim_end_matches('/'); if let Some(base) = trimmed.strip_suffix("/chat/completions") { format!("{base}/models") } else { format!("{trimmed}/models") } } /// Extract model ids from an OpenAI-compatible `/models` response. fn parse_model_ids(body: &str) -> Vec { let mut ids: std::collections::BTreeSet = std::collections::BTreeSet::new(); if let Ok(value) = serde_json::from_str::(body) { if let Some(data) = value.get("data").and_then(|d| d.as_array()) { for item in data { if let Some(id) = item.get("id").and_then(|v| v.as_str()) { ids.insert(id.to_string()); } } } if ids.is_empty() { if let Some(models) = value.get("models").and_then(|m| m.as_array()) { for item in models { if let Some(id) = item .get("id") .and_then(|v| v.as_str()) .or_else(|| item.get("name").and_then(|v| v.as_str())) { ids.insert(id.to_string()); } } } } } ids.into_iter().collect() } fn opencode_transport<'a>( exec: &'a Exec, config: &InstallConfig, password: Option, ) -> Result, String> { let (server, provider, model, variant) = opencode_parts(config)?; let mut transport = phoebus_executor::opencode_client::ExecOpenCodeTransport::new( exec, server, provider, model, ) .with_auth(password); if !variant.is_empty() && variant != "default" { transport = transport.with_variant(variant); } Ok(transport) } #[allow(clippy::too_many_arguments)] fn finish_review( config: &mut InstallConfig, redactor: &phoebus_core::Redactor, facts: SystemFacts, kind: ProviderKind, endpoint: &str, provider_label: &str, model: &str, transport: &dyn ModelTransport, backend: &str, ) -> Result { let outcome = ai_guide::generate_and_review_at(config, &facts, kind, endpoint, model, transport) .map_err(|e| { // Error messages are redacted before they reach the GUI. format!( "connection or proposal failed: {}", redactor.redact(&e.to_string()) ) })?; let applied: Vec = outcome .applied .iter() .filter(|c| !c.description.to_lowercase().starts_with("flatpak")) .map(|c| { json!({ "description": c.description, "reason": c.reason, "evidence": c.evidence, }) }) .collect(); Ok(json!({ "connected": true, "backend": backend, "provider": provider_label, "model": model, "endpoint": endpoint, "applied": applied, "config": config, "plan_digest": config_digest(config), })) } /// OpenCode proposal review: the adapter talks the agent protocol and the /// shared strict proposal parser/review applies the accepted changes. fn review_opencode( config: &mut InstallConfig, redactor: &phoebus_core::Redactor, facts: SystemFacts, transport: &dyn ModelTransport, ) -> Result { let (server, provider_id, model, _variant) = opencode_parts(config)?; finish_review( config, redactor, facts, ProviderKind::Local, &server, &provider_id, &model, transport, "opencode", ) } /// A deterministic digest of only the AI connection settings. The mandatory-AI /// validation is bound to this, so choosing a disk or typing an account /// password does not discard a successful model interaction, while changing the /// provider, model, endpoint or server does. fn ai_digest(config: &InstallConfig) -> String { use sha2::{Digest, Sha256}; let ai = &config.ai; let mut hasher = Sha256::new(); for field in [ ai.backend.as_str(), ai.provider.as_str(), ai.model.as_str(), ai.endpoint.as_str(), ai.opencode_server.as_str(), ai.opencode_provider.as_str(), ai.opencode_model.as_str(), ai.opencode_variant.as_str(), ] { hasher.update(field.as_bytes()); hasher.update([0u8]); } format!("{:x}", hasher.finalize()) } /// Parse the direct provider from the configuration, validate the connection /// and apply the reviewed proposal. This is the same `ai_guide` path the TUI /// uses. fn review_proposal( config: &mut InstallConfig, redactor: &phoebus_core::Redactor, facts: SystemFacts, api_key_present: bool, transport: &dyn ModelTransport, ) -> Result { let raw = config.ai.provider.clone(); let provider = ProviderKind::parse(&raw).ok_or_else(|| format!("unknown AI provider `{raw}`"))?; if provider == ProviderKind::None { return Err("no AI provider selected".into()); } let endpoint = if config.ai.endpoint.is_empty() { provider.endpoint().to_string() } else { config.ai.endpoint.clone() }; let model = if config.ai.model.is_empty() { provider.default_model().to_string() } else { config.ai.model.clone() }; if provider.requires_key() && !api_key_present { return Err(format!( "provider `{}` requires an API key", provider.as_str() )); } finish_review( config, redactor, facts, provider, &endpoint, provider.as_str(), &model, transport, "direct", ) } /// The stdio entry point used by `--gui-bridge`. pub fn run_stdio() -> io::Result<()> { // The live medium may preseed the wizard's starting configuration. The // deterministic CLI already honours `/etc/phoebus/install.conf`; the // graphical wizard uses the same file so the two paths agree. A test or // automation caller can point at another file with `PHOEBUS_GUI_CONFIG`. // Only the defaults change: validation, the plan, the AI gate and the // ERASE authorization are all unchanged. let explicit = std::env::var("PHOEBUS_GUI_CONFIG") .ok() .filter(|p| !p.trim().is_empty()); let mut config = if let Some(path) = explicit { InstallConfig::load_from_path(std::path::Path::new(path.trim())).map_err(|e| { io::Error::new( io::ErrorKind::InvalidInput, format!("cannot load PHOEBUS_GUI_CONFIG: {e}"), ) })? } else { let default = std::path::Path::new("/etc/phoebus/install.conf"); if default.is_file() { InstallConfig::load_from_path(default).unwrap_or_else(|e| { eprintln!("ignoring /etc/phoebus/install.conf: {e}"); InstallConfig::default() }) } else { InstallConfig::default() } }; // Test/automation hook: a dry run is non-destructive, so it is safe to // expose through the environment for the harness. It never changes the // authorization requirements. if std::env::var("PHOEBUS_DRY_RUN") .map(|v| matches!(v.to_ascii_lowercase().as_str(), "1" | "yes" | "true")) .unwrap_or(false) { config.runtime.dry_run = true; } let mut state_dir = std::path::PathBuf::from(&config.runtime.state_dir); if std::fs::create_dir_all(&state_dir).is_err() { state_dir = std::path::PathBuf::from("/tmp/phoebus-installer"); std::fs::create_dir_all(&state_dir).ok(); } let logger = phoebus_executor::Logger::open( state_dir.join("install.log"), phoebus_core::Redactor::new(), false, ); let logger_clone = logger.clone(); let runner = phoebus_executor::RealRunner::with_sink(std::sync::Arc::new(move |text: &str| { logger_clone.stream_output(text); })); let exec = Exec::new( Box::new(runner), logger, config.runtime.dry_run, config.storage.install_root.clone(), state_dir, ); let mut bridge = Bridge::new(config, exec); let stdin = io::stdin(); let mut out = io::stdout(); for line in stdin.lock().lines() { let line = line?; bridge.handle_line(&line, &mut out)?; if bridge.should_quit() { break; } } Ok(()) } #[cfg(test)] mod tests { use super::*; use phoebus_ai::provider::TestTransport; use phoebus_core::{Disk, DiskKind, Redactor}; use phoebus_executor::{Logger, RecordingRunner}; fn test_bridge() -> Bridge { let runner = RecordingRunner::new(); let dir = tempfile::tempdir().unwrap().keep(); let logger = Logger::open(dir.join("install.log"), Redactor::new(), false); let mut config = InstallConfig::default(); // The bridge preserves the backend's dry-run flag; set it on the // installer so the whole staged flow runs without touching a disk. config.runtime.dry_run = true; config.system.hostname = "phoebus".into(); config.system.timezone = "UTC".into(); config.user.username = "tester".into(); config.storage.disk = "/dev/vda".into(); let exec = Exec::new( Box::new(runner), logger, true, dir.join("root"), dir.clone(), ); let mut installer = Installer::new(config, exec); installer.disks.push(Disk { path: "/dev/vda".into(), model: Some("QEMU HARDDISK".into()), size_bytes: 30 * 1024 * 1024 * 1024, transport: Some("virtio".into()), removable: false, read_only: false, mounted: false, is_block_device: true, kind: DiskKind::Physical, live_media: false, }); Bridge::with_installer(installer) } fn call(bridge: &mut Bridge, request: &str) -> Vec { let mut out: Vec = Vec::new(); bridge.handle_line(request, &mut out).unwrap(); String::from_utf8(out) .unwrap() .lines() .filter(|l| !l.trim().is_empty()) .map(|l| serde_json::from_str(l).expect("json line")) .collect() } fn response(lines: &[Value]) -> Value { lines .iter() .find(|v| v.get("ok").is_some()) .cloned() .expect("a response line") } fn config_json(bridge: &Bridge) -> Value { serde_json::to_value(&bridge.installer.config).unwrap() } fn set_valid_config(bridge: &mut Bridge) -> Value { let mut c = config_json(bridge); c["system"]["hostname"] = json!("phoebus-box"); c["user"]["username"] = json!("tester"); c["storage"]["disk"] = json!("/dev/vda"); let req = json!({ "id": 2, "op": "set_config", "config": c }); let lines = call(bridge, &req.to_string()); response(&lines) } fn approve(bridge: &mut Bridge) -> (String, Value) { let req = json!({ "id": 90, "op": "approve", "erase": "ERASE", "final_confirm": true }); let lines = call(bridge, &req.to_string()); let resp = response(&lines); let digest = resp["data"]["plan_digest"].as_str().unwrap().to_string(); (digest, resp) } #[test] fn handshake_reports_protocol_and_readiness() { let mut bridge = test_bridge(); let lines = call(&mut bridge, r#"{"id":1,"op":"handshake"}"#); let resp = response(&lines); assert_eq!(resp["ok"], json!(true)); assert_eq!(resp["data"]["protocol"], json!(PROTOCOL_VERSION)); assert!(resp["data"]["readiness"]["memory_mib"].is_number()); assert_eq!( resp["data"]["defaults"]["desktop"]["profile"], json!("mango") ); } #[test] fn validate_reports_missing_user_and_disk() { let mut bridge = test_bridge(); // Strip the valid user/disk to prove validation is wired through. let mut c = config_json(&bridge); c["user"]["username"] = json!(""); c["storage"]["disk"] = json!(""); let _ = call( &mut bridge, &json!({ "id": 2, "op": "set_config", "config": c }).to_string(), ); let lines = call(&mut bridge, r#"{"id":3,"op":"validate"}"#); let resp = response(&lines); assert_eq!(resp["data"]["complete"], json!(false)); let fields: Vec<&str> = resp["data"]["issues"] .as_array() .unwrap() .iter() .map(|i| i["field"].as_str().unwrap()) .collect(); assert!(fields.contains(&"username")); assert!(fields.contains(&"target_disk")); } #[test] fn plan_review_carries_the_backend_facts() { let mut bridge = test_bridge(); set_valid_config(&mut bridge); let lines = call(&mut bridge, r#"{"id":4,"op":"plan"}"#); let resp = response(&lines); assert_eq!(resp["ok"], json!(true)); assert_eq!(resp["data"]["review"]["target_disk"], json!("/dev/vda")); assert_eq!(resp["data"]["review"]["encryption"], json!("luks2")); assert_eq!(resp["data"]["review"]["desktop"], json!("mango")); let subsystems = resp["data"]["review"]["subsystems"].as_array().unwrap(); for want in ["systemd", "pipewire", "flatpak", "nix"] { assert!( subsystems.iter().any(|s| s == want), "review is missing subsystem {want}" ); } assert!(resp["data"]["human"] .as_str() .unwrap() .contains("Installation plan")); } #[test] fn destructive_preview_matches_the_plan_digest() { let mut bridge = test_bridge(); set_valid_config(&mut bridge); let lines = call(&mut bridge, r#"{"id":5,"op":"destructive_preview"}"#); let resp = response(&lines); let digest = resp["data"]["plan_digest"].as_str().unwrap().to_string(); assert_eq!(digest, bridge.plan_digest()); assert!(resp["data"]["text"] .as_str() .unwrap() .contains("ALL DATA ON THIS DEVICE WILL BE DESTROYED.")); } #[test] fn approval_requires_erase_and_final_confirmation() { let mut bridge = test_bridge(); set_valid_config(&mut bridge); let wrong = call( &mut bridge, r#"{"id":6,"op":"approve","erase":"erase","final_confirm":true}"#, ); assert_eq!(response(&wrong)["ok"], json!(false)); let no_final = call( &mut bridge, r#"{"id":7,"op":"approve","erase":"ERASE","final_confirm":false}"#, ); assert_eq!(response(&no_final)["ok"], json!(false)); let (_, ok) = approve(&mut bridge); assert_eq!(ok["ok"], json!(true)); } #[test] fn start_install_requires_a_matching_approval() { let mut bridge = test_bridge(); set_valid_config(&mut bridge); // No approval at all. let none = call( &mut bridge, r#"{"id":8,"op":"start_install","erase":"ERASE","final_confirm":true}"#, ); assert_eq!(response(&none)["ok"], json!(false)); // A stale digest (the plan changed after approval) is refused. let (digest, _) = approve(&mut bridge); let mut c = config_json(&bridge); c["system"]["hostname"] = json!("changed-after-approval"); let _ = call( &mut bridge, &json!({ "id": 9, "op": "set_config", "config": c }).to_string(), ); let stale = call( &mut bridge, &json!({ "id": 10, "op": "start_install", "erase": "ERASE", "final_confirm": true, "plan_digest": digest }) .to_string(), ); assert_eq!(response(&stale)["ok"], json!(false)); } #[test] fn approved_dry_run_completes_and_reports_real_stages() { let mut bridge = test_bridge(); set_valid_config(&mut bridge); let (digest, _) = approve(&mut bridge); let lines = call( &mut bridge, &json!({ "id": 11, "op": "start_install", "erase": "ERASE", "final_confirm": true, "plan_digest": digest }) .to_string(), ); let resp = response(&lines); assert_eq!(resp["ok"], json!(true), "response: {resp}"); assert_eq!(resp["data"]["complete"], json!(true)); assert_eq!(resp["data"]["dry_run"], json!(true)); // The real stage sequence was emitted with categories, not percentages. let events: Vec<&Value> = lines .iter() .filter(|v| v.get("event") == Some(&json!("progress"))) .collect(); let started: Vec<&str> = events .iter() .filter(|e| e["status"] == json!("started")) .map(|e| e["stage"].as_str().unwrap()) .collect(); assert_eq!(started.first(), Some(&"storage_prepare")); assert_eq!(started.last(), Some(&"finalize")); assert!(events.iter().all(|e| e["category"].is_string())); assert!( events.iter().all(|e| e.get("percent").is_none()), "no invented percentage may appear" ); } #[test] fn ai_check_applies_a_reviewed_proposal_and_voids_approval() { let mut bridge = test_bridge(); set_valid_config(&mut bridge); let (_, _) = approve(&mut bridge); let mut c = config_json(&bridge); c["ai"]["provider"] = json!("deepseek"); c["ai"]["model"] = json!("deepseek-chat"); let _ = call( &mut bridge, &json!({ "id": 12, "op": "set_config", "config": c }).to_string(), ); let _ = call( &mut bridge, r#"{"id":19,"op":"set_secrets","secrets":{"ai_api_key":"test-key"}}"#, ); let proposal = r#"{"version":1,"changes":[{"action":"set_kernel_profile","value":"safe"}],"rationale":[{"action":"set_kernel_profile","reason":"stability","evidence":["proven boot"]}]}"#; let transport = TestTransport::proposal(proposal); let value = bridge.ai_check_with(&transport).unwrap(); assert_eq!(value["connected"], json!(true)); assert_eq!( value["applied"][0]["description"], json!("kernel profile = safe") ); assert_eq!( bridge.installer.config.kernel.profile, phoebus_core::KernelProfile::Safe ); assert!(bridge.approved_digest.is_none()); } #[test] fn ai_check_fails_closed_without_a_provider() { let mut bridge = test_bridge(); let transport = TestTransport::proposal(r#"{"version":1,"changes":[]}"#); assert!(bridge.ai_check_with(&transport).is_err()); } #[test] fn secrets_never_appear_in_responses_and_the_log() { let mut bridge = test_bridge(); set_valid_config(&mut bridge); let secret = "correct-horse-battery-staple"; let req = json!({ "id": 13, "op": "set_secrets", "secrets": { "luks": secret, "user_password": secret } }); let lines = call(&mut bridge, &req.to_string()); assert_eq!(response(&lines)["data"]["luks_set"], json!(true)); // Presence only, never the value. assert!(!lines.iter().any(|v| v.to_string().contains(secret))); // A log tail is redacted too. let tail = call(&mut bridge, r#"{"id":14,"op":"log_tail","lines":100}"#); assert!(!response(&tail).to_string().contains(secret)); } #[test] fn unknown_ops_and_unknown_fields_fail_closed() { let mut bridge = test_bridge(); assert_eq!( response(&call(&mut bridge, r#"{"id":15,"op":"nope"}"#))["ok"], json!(false) ); assert_eq!( response(&call( &mut bridge, r#"{"id":16,"op":"handshake","surprise":true}"# ))["ok"], json!(false) ); } #[test] fn config_may_not_smuggle_a_secret() { let mut bridge = test_bridge(); let mut c = config_json(&bridge); c["system"]["distro_name"] = json!("passphrase is hunter2"); let lines = call( &mut bridge, &json!({ "id": 17, "op": "set_config", "config": c }).to_string(), ); assert_eq!(response(&lines)["ok"], json!(false)); } #[test] fn quit_is_reported() { let mut bridge = test_bridge(); let lines = call(&mut bridge, r#"{"id":18,"op":"quit"}"#); assert_eq!(response(&lines)["data"]["bye"], json!(true)); assert!(bridge.should_quit()); } #[test] fn start_install_cannot_be_replayed_after_success() { let mut bridge = test_bridge(); set_valid_config(&mut bridge); let (digest, _) = approve(&mut bridge); let first = call( &mut bridge, &json!({ "id": 20, "op": "start_install", "erase": "ERASE", "final_confirm": true, "plan_digest": digest }) .to_string(), ); assert_eq!(response(&first)["ok"], json!(true)); assert!(bridge.installed); // A second frontend (or a retry) re-approves and tries again: refused. let (digest2, _) = approve(&mut bridge); let second = call( &mut bridge, &json!({ "id": 21, "op": "start_install", "erase": "ERASE", "final_confirm": true, "plan_digest": digest2 }) .to_string(), ); assert_eq!(response(&second)["ok"], json!(false)); assert!( response(&second)["error"] .as_str() .unwrap() .contains("already installed"), "unexpected error: {}", response(&second)["error"] ); } #[test] fn oversized_request_line_is_refused() { let mut bridge = test_bridge(); let huge = format!( r#"{{"id":1,"op":"handshake","pad":"{}"}}"#, "x".repeat(MAX_LINE_BYTES) ); let lines = call(&mut bridge, &huge); let resp = response(&lines); assert_eq!(resp["ok"], json!(false)); assert!(resp["error"].as_str().unwrap().contains("too large")); } #[test] fn oversized_secret_is_refused() { let mut bridge = test_bridge(); let secret = "x".repeat(MAX_SECRET_BYTES + 1); let lines = call( &mut bridge, &json!({ "id": 22, "op": "set_secrets", "secrets": { "luks": secret } }).to_string(), ); assert_eq!(response(&lines)["ok"], json!(false)); } #[test] fn deeply_nested_json_is_rejected_without_panicking() { let mut bridge = test_bridge(); let depth = 300; let nested = format!("{}{}{}", "[".repeat(depth), "0", "]".repeat(depth)); let line = format!(r#"{{"id":23,"op":"handshake","config":{nested}}}"#); let lines = call(&mut bridge, &line); assert_eq!(response(&lines)["ok"], json!(false)); } /// A non-dry bridge whose runner reports `/dev/vda`, so revalidation and /// the install stages run against the fake runner (never a real disk). fn test_bridge_non_dry() -> Bridge { let runner = RecordingRunner::new(); runner.set_response( "lsblk", phoebus_executor::CommandOutput { status: 0, success: true, stdout: b"NAME=\"vda\" MODEL=\"QEMU HARDDISK\" SIZE=\"32212254720\" TRAN=\"virtio\" RM=\"0\" RO=\"0\"\n".to_vec(), stderr: Vec::new(), duration: std::time::Duration::from_millis(1), }, ); let dir = tempfile::tempdir().unwrap().keep(); let logger = Logger::open(dir.join("install.log"), Redactor::new(), false); let mut config = InstallConfig::default(); config.runtime.dry_run = false; config.system.hostname = "phoebus".into(); config.system.timezone = "UTC".into(); config.user.username = "tester".into(); config.storage.disk = "/dev/vda".into(); let exec = Exec::new( Box::new(runner), logger, false, dir.join("root"), dir.clone(), ); let mut installer = Installer::new(config, exec); installer.disks.push(Disk { path: "/dev/vda".into(), model: Some("QEMU HARDDISK".into()), size_bytes: 30 * 1024 * 1024 * 1024, transport: Some("virtio".into()), removable: false, read_only: false, mounted: false, is_block_device: true, kind: DiskKind::Physical, live_media: false, }); Bridge::with_installer(installer) } fn arm_ai(bridge: &mut Bridge) -> Value { let mut c = config_json(bridge); c["ai"]["provider"] = json!("deepseek"); c["ai"]["model"] = json!("deepseek-chat"); let _ = call( bridge, &json!({ "id": 30, "op": "set_config", "config": c }).to_string(), ); bridge.api_key = Some(SecretString::new("test-key")); let proposal = r#"{"version":1,"changes":[{"action":"set_kernel_profile","value":"safe"}],"rationale":[{"action":"set_kernel_profile","reason":"stability","evidence":["x"]}]}"#; bridge .ai_check_with(&TestTransport::proposal(proposal)) .expect("ai_check") } fn start(bridge: &mut Bridge, digest: &str) -> Value { let lines = call( bridge, &json!({ "id": 31, "op": "start_install", "erase": "ERASE", "final_confirm": true, "plan_digest": digest }) .to_string(), ); response(&lines) } #[test] fn a_provider_name_alone_does_not_satisfy_the_ai_requirement() { let mut bridge = test_bridge_non_dry(); set_valid_config(&mut bridge); // Provider configured and key present, but no validated interaction. let mut c = config_json(&bridge); c["ai"]["provider"] = json!("deepseek"); let _ = call( &mut bridge, &json!({ "id": 40, "op": "set_config", "config": c }).to_string(), ); bridge.api_key = Some(SecretString::new("test-key")); let (digest, _) = approve(&mut bridge); let resp = start(&mut bridge, &digest); assert_eq!(resp["ok"], json!(false)); assert!( resp["error"] .as_str() .unwrap() .contains("validated AI interaction"), "unexpected error: {}", resp["error"] ); } #[test] fn a_validated_interaction_satisfies_the_ai_requirement() { let mut bridge = test_bridge_non_dry(); set_valid_config(&mut bridge); arm_ai(&mut bridge); let (digest, _) = approve(&mut bridge); let resp = start(&mut bridge, &digest); // It may fail later in the fake storage stage, but never on the AI gate. assert!( !resp["error"] .as_str() .unwrap_or("") .contains("validated AI interaction"), "the AI gate wrongly rejected a validated interaction: {}", resp["error"] ); } #[test] fn a_config_change_invalidates_the_validated_interaction() { let mut bridge = test_bridge_non_dry(); set_valid_config(&mut bridge); arm_ai(&mut bridge); // Change the model after validation. let mut c = config_json(&bridge); c["ai"]["model"] = json!("deepseek-reasoner"); let _ = call( &mut bridge, &json!({ "id": 41, "op": "set_config", "config": c }).to_string(), ); let (digest, _) = approve(&mut bridge); let resp = start(&mut bridge, &digest); assert_eq!(resp["ok"], json!(false)); assert!(resp["error"] .as_str() .unwrap() .contains("validated AI interaction")); } #[test] fn a_non_ai_config_change_keeps_the_validated_interaction() { // Choosing a disk or editing the account must not discard a successful // model interaction: this was the bug that refused a fully-validated // install at the final step. let mut bridge = test_bridge_non_dry(); set_valid_config(&mut bridge); arm_ai(&mut bridge); let mut c = config_json(&bridge); c["system"]["hostname"] = json!("renamed-box"); let _ = call( &mut bridge, &json!({ "id": 60, "op": "set_config", "config": c }).to_string(), ); let (digest, _) = approve(&mut bridge); let resp = start(&mut bridge, &digest); assert!( !resp["error"] .as_str() .unwrap_or("") .contains("validated AI interaction"), "a non-AI change wrongly invalidated the interaction: {}", resp["error"] ); } #[test] fn an_account_secret_does_not_invalidate_but_an_ai_key_does() { let mut bridge = test_bridge_non_dry(); set_valid_config(&mut bridge); arm_ai(&mut bridge); let _ = call( &mut bridge, r#"{"id":61,"op":"set_secrets","secrets":{"user_password":"secret-pass-1","luks":"luks-pass-1234"}}"#, ); let (digest, _) = approve(&mut bridge); let resp = start(&mut bridge, &digest); assert!( !resp["error"] .as_str() .unwrap_or("") .contains("validated AI interaction"), "an account secret wrongly invalidated the interaction: {}", resp["error"] ); // A changed AI credential must invalidate it. let mut bridge = test_bridge_non_dry(); set_valid_config(&mut bridge); arm_ai(&mut bridge); let _ = call( &mut bridge, r#"{"id":62,"op":"set_secrets","secrets":{"ai_api_key":"a-different-key"}}"#, ); let (digest, _) = approve(&mut bridge); let resp = start(&mut bridge, &digest); assert!(resp["error"] .as_str() .unwrap() .contains("validated AI interaction")); } #[test] fn a_secret_change_invalidates_the_validated_interaction() { let mut bridge = test_bridge_non_dry(); set_valid_config(&mut bridge); arm_ai(&mut bridge); let _ = call( &mut bridge, r#"{"id":42,"op":"set_secrets","secrets":{"ai_api_key":"new-key"}}"#, ); let (digest, _) = approve(&mut bridge); let resp = start(&mut bridge, &digest); assert_eq!(resp["ok"], json!(false)); assert!(resp["error"] .as_str() .unwrap() .contains("validated AI interaction")); } #[test] fn options_are_available_for_the_region_pickers() { let mut bridge = test_bridge(); let lines = call(&mut bridge, r#"{"id":50,"op":"options"}"#); let data = &response(&lines)["data"]; assert!(!data["timezones"].as_array().unwrap().is_empty()); assert!(!data["locales"].as_array().unwrap().is_empty()); assert!(!data["keymaps"].as_array().unwrap().is_empty()); } #[test] fn models_url_is_derived_from_the_chat_endpoint() { assert_eq!( models_url("https://api.deepseek.com/chat/completions"), "https://api.deepseek.com/models" ); assert_eq!( models_url("https://api.openai.com/v1/chat/completions"), "https://api.openai.com/v1/models" ); assert_eq!( models_url("http://127.0.0.1:11434/v1/chat/completions"), "http://127.0.0.1:11434/v1/models" ); } #[test] fn parse_model_ids_reads_common_shapes() { assert_eq!( parse_model_ids(r#"{"data":[{"id":"b"},{"id":"a"},{"id":"a"}]}"#), vec!["a", "b"] ); assert_eq!(parse_model_ids(r#"{"models":[{"name":"m"}]}"#), vec!["m"]); assert!(parse_model_ids("").is_empty()); } #[test] fn ai_test_is_a_known_operation_and_fails_without_a_provider() { let mut bridge = test_bridge(); let lines = call(&mut bridge, r#"{"id":43,"op":"ai_test"}"#); let resp = response(&lines); // Not "unknown op": the operation exists and reports the configuration // problem instead. assert_eq!(resp["ok"], json!(false)); assert!( !resp["error"].as_str().unwrap().contains("unknown op"), "{}", resp["error"] ); } #[test] fn connection_error_kind_classifies_common_failures() { assert_eq!( connection_error_kind("server requires authentication (HTTP 401)"), "authentication_required" ); assert_eq!( connection_error_kind("server rejected the supplied authentication (HTTP 403)"), "authentication_rejected" ); assert_eq!( connection_error_kind("model list returned HTTP 401"), "authentication_rejected" ); assert_eq!( connection_error_kind("plain http to a non-loopback address is refused"), "insecure_transport" ); assert_eq!( connection_error_kind("could not connect to the model server"), "unreachable" ); assert_eq!( connection_error_kind("transport response had no status"), "unreachable" ); assert_eq!(connection_error_kind("something unexpected"), "error"); } #[test] fn humanized_labels_keep_the_identifier_and_add_a_name() { assert!(humanize_locale("en_US.UTF-8").contains("English")); assert!(humanize_locale("de_DE.UTF-8").contains("German")); assert!(humanize_locale("en_US.UTF-8").contains("en_US.UTF-8")); assert_eq!(humanize_locale("xx_YY.UTF-8"), "xx_YY.UTF-8"); assert!(humanize_keymap("de").contains("German")); assert!(humanize_keymap("de-nodeadkeys").contains("German")); assert!(humanize_keymap("us").contains("English (US)")); assert_eq!(humanize_keymap("zzz"), "zzz"); assert!(humanize_timezone("Europe/Berlin").contains("Europe")); } #[test] fn options_carry_labels_and_the_live_keymap() { let mut bridge = test_bridge(); let lines = call(&mut bridge, r#"{"id":70,"op":"options"}"#); let data = &response(&lines)["data"]; for key in ["timezones", "locales", "keymaps"] { let entries = data[key].as_array().unwrap(); assert!(!entries.is_empty(), "{key} was empty"); assert!( entries .iter() .all(|o| o.get("value").is_some() && o.get("label").is_some()), "{key} entries need a value and a label" ); } assert!(data["keymap_live"].is_string()); } #[test] fn readiness_reports_link_and_service_reachability_separately() { let mut bridge = test_bridge(); let lines = call(&mut bridge, r#"{"id":71,"op":"readiness"}"#); let resp = response(&lines); assert_eq!(resp["ok"], json!(true), "response: {resp}"); let data = &resp["data"]; assert!(data["network"].is_boolean()); assert!( data["network_services"].is_boolean(), "service reachability must be its own fact, not inferred from the link" ); assert!(data["network_detail"].is_string()); assert!(data["keymap_live"].is_string()); } #[test] fn ai_catalog_errors_are_machine_readable() { let mut bridge = test_bridge(); let lines = call(&mut bridge, r#"{"id":72,"op":"ai_catalog"}"#); let resp = response(&lines); assert_eq!(resp["ok"], json!(false)); assert!( resp["error_kind"].is_string(), "an AI connection error must carry a kind: {resp}" ); } }