phoebus_os/installer-rs/crates/phoebus-installer/src/assistant_bridge.rs
2026-10-03 08:53:02 -07:00

1137 lines
40 KiB
Rust

//! JSON-RPC assistant bridge for the Phoebus desktop assistant.
//!
//! Exposes the exact same AI investigation, deterministic resolution,
//! policy checks, authorization boundary, and transaction recording to the
//! desktop GUI as `sys` CLI through the shared service layer.
use std::io::{BufRead, Write};
use std::path::Path;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex};
use phoebus_ai::install::{Evidence, InstallSession};
use phoebus_ai::provider::{ModelTransport, ProviderKind, SystemFacts};
use phoebus_ai::AiError;
use phoebus_core::action::{parse_natural, SystemAction};
use phoebus_core::selection::Backend;
use phoebus_core::{AiBackend, InstallConfig, Preferences};
use phoebus_executor::chooser;
use phoebus_executor::exec::ProgressEvent;
use phoebus_executor::install::{AiInstall, InstallRequest};
use phoebus_executor::personal::UserStorage;
use phoebus_executor::proactive;
use phoebus_executor::probe;
use phoebus_executor::transaction;
use phoebus_executor::update::check_unified_updates;
use phoebus_executor::{actions, Exec};
use crate::ai_setup;
use crate::conversation::{self, ConversationTurn, FollowupResolution};
use crate::service::{self, PlanStore, PreparedPlan};
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
pub const ASSISTANT_PROTOCOL_VERSION: u32 = 1;
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct BridgeRequest {
pub id: u64,
pub op: String,
#[serde(default)]
pub request: Option<String>,
#[serde(default)]
pub application: Option<String>,
#[serde(default)]
pub backend: Option<String>,
#[serde(default)]
pub phrase: Option<String>,
#[serde(default)]
pub plan_id: Option<String>,
#[serde(default)]
pub action: Option<Value>,
#[serde(default)]
pub actions: Option<Vec<Value>>,
#[serde(default)]
pub digest: Option<String>,
#[serde(default)]
pub yes: Option<bool>,
#[serde(default)]
pub duration_seconds: Option<u64>,
#[serde(default)]
pub fingerprint: Option<String>,
#[serde(default)]
pub preferences: Option<Preferences>,
#[serde(default)]
pub snapshot: Option<String>,
}
#[derive(Debug, Serialize)]
pub struct BridgeResponse {
pub id: u64,
pub ok: bool,
#[serde(skip_serializing_if = "Option::is_none")]
pub result: Option<Value>,
#[serde(skip_serializing_if = "Option::is_none")]
pub error: Option<String>,
}
impl BridgeResponse {
pub fn ok(id: u64, result: Value) -> Self {
Self {
id,
ok: true,
result: Some(result),
error: None,
}
}
pub fn err(id: u64, message: impl Into<String>) -> Self {
Self {
id,
ok: false,
result: None,
error: Some(message.into()),
}
}
}
fn now_unix() -> u64 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or(0)
}
/// Persist a minimized turn with the registered-secret redactor, surfacing a
/// storage failure rather than silently dropping the context.
fn record_turn(exec: &Exec, path: &Path, turn: ConversationTurn) {
if let Err(e) = conversation::save_turn(path, exec.redactor(), turn) {
eprintln!("assistant-bridge: could not persist conversation context: {e}");
}
}
fn load_installed_ai_config(root: &Path) -> Option<phoebus_core::AiConfig> {
let conf_path = root.join("etc/phoebus/assistant.conf");
let text = std::fs::read_to_string(&conf_path).ok()?;
toml::from_str(&text).ok()
}
fn gather_facts(exec: &Exec, root: &Path) -> SystemFacts {
let conf_path = root.join("etc/phoebus/install.toml");
let config = std::fs::read_to_string(&conf_path)
.ok()
.and_then(|text| InstallConfig::from_toml(&text).ok())
.unwrap_or_default();
let hardware = probe::probe_hardware(exec.runner.as_ref());
let history = phoebus_core::load_history(&root.join("var/lib/phoebus/compile-times.tsv"));
let binhost = root.join("etc/portage/binrepos.conf").exists();
let mut facts = SystemFacts::from_system(&config, &hardware, &history, binhost, None);
let hw = chooser::hardware_facts(exec, root);
facts.storage_free_mib = hw.storage_free_mib;
facts.wayland = hw.wayland;
facts.available_backends = hw
.available_backends
.iter()
.map(|b| b.as_str().to_string())
.collect();
let prefs = chooser::load_preferences(root);
facts.saved_preferences = prefs
.per_app
.iter()
.map(|(app, b)| (app.clone(), b.as_str().to_string()))
.collect();
facts.recovery_snapshots = root.join(phoebus_executor::snapshot::SNAPSHOT_DIR).is_dir();
facts
}
struct BridgeSession<'a> {
exec: &'a Exec,
root: &'a Path,
}
impl InstallSession for BridgeSession<'_> {
fn investigate(&self, requests: &[SystemAction]) -> Vec<Evidence> {
requests
.iter()
.map(|request| {
let phase = self
.exec
.progress_phase(&format!("Checking {}", request.describe()));
let output = match actions::execute(self.exec, request, None, self.root) {
Ok(outcome) => {
phase.complete();
outcome.output
}
Err(e) => format!("investigation failed: {e}"),
};
Evidence {
request: request.describe(),
output,
}
})
.collect()
}
fn ask(&self, _question: &str) -> Option<String> {
None
}
}
/// Resolve the connected provider and credentials through the shared setup
/// module, then run `f` with the result. Never exposes the credential to QML.
fn with_bridge_ai<T>(
exec: &Exec,
root: &Path,
f: impl FnOnce(&AiInstall, &SystemFacts) -> T,
) -> std::result::Result<T, String> {
let conf = load_installed_ai_config(root);
let resolved = ai_setup::resolve(root, &ai_setup::AiOverrides::default(), conf.as_ref());
if !resolved.is_configured() {
return Err(
"No AI model is connected. Connect a provider or use Legacy Admin for \
deterministic administration."
.into(),
);
}
let transport = resolved.transport(exec).map_err(|e| e.to_string())?;
let facts_phase = exec.progress_phase("Reading system and package facts");
let facts = gather_facts(exec, root);
facts_phase.complete();
let progress_transport = ProgressTransport {
exec,
inner: transport.as_ref(),
};
let ai = AiInstall {
provider: resolved.provider,
endpoint: if resolved.backend == AiBackend::OpenCode {
resolved.opencode_server.clone()
} else {
resolved.endpoint.clone()
},
model: if resolved.backend == AiBackend::OpenCode {
resolved.opencode_model.clone()
} else {
resolved.model.clone()
},
transport: &progress_transport,
limits: phoebus_ai::install::Limits::default(),
};
Ok(f(&ai, &facts))
}
struct ProgressTransport<'a> {
exec: &'a Exec,
inner: &'a dyn ModelTransport,
}
impl ModelTransport for ProgressTransport<'_> {
fn send(&self, provider: ProviderKind, url: &str, body: &str) -> Result<String, AiError> {
let phase = self.exec.progress_phase("Waiting for the connected model");
let response = self.inner.send(provider, url, body);
if response.is_ok() {
phase.complete();
}
response
}
}
/// The shared, complete review card for any prepared plan. QML renders this
/// directly; administrative decisions stay in the service.
fn plan_response(id: u64, kind: &str, plan: &PreparedPlan) -> BridgeResponse {
BridgeResponse::ok(
id,
json!({
"kind": kind,
"state": "prepared",
"prepared": true,
"plan_id": plan.id,
"summary": plan.summary,
"recommendation": plan.recommendation,
"application": plan.application,
"backend": plan.candidate.as_ref().map(|c| c.backend.as_str()),
"source": plan.source,
"chosen": plan.candidate,
"alternatives": plan.alternatives,
"rationale": plan.rationale,
"action": plan.actions.first(),
"actions": plan.actions,
"digest": plan.digest,
"effects": plan.effects.effects,
"warnings": plan.warnings,
"requires_root": plan.requires_root,
"verification": plan.verification,
}),
)
}
pub fn handle_request(
exec: &Exec,
root: &Path,
plans: &PlanStore,
req: BridgeRequest,
) -> BridgeResponse {
let id = req.id;
// Personal state always belongs to the invoking desktop user. When the
// bridge runs under an elevated command this resolves SUDO_UID/PKEXEC_UID,
// so the CLI and GUI see the same preferences.
let storage = UserStorage::for_initiating_user();
match req.op.as_str() {
"handshake" => {
let ai_conf = load_installed_ai_config(root);
let prefs = chooser::load_preferences(root);
let (alerts, _) = proactive::active_alerts_quick(exec, root, &storage);
// Check reboot required deterministically without running expensive update checks
let reboot_req = root.join("run/reboot-required").exists()
|| root.join("var/run/reboot-required").exists()
|| Path::new("/run/reboot-required").exists();
BridgeResponse::ok(
id,
json!({
"version": phoebus_core::VERSION,
"protocol_version": ASSISTANT_PROTOCOL_VERSION,
"root": root.display().to_string(),
"ai_configured": ai_conf.is_some(),
"ai_backend": ai_conf.as_ref().map(|c| c.backend.as_str()).unwrap_or("direct"),
"preferences": prefs,
"active_alerts_count": alerts.len(),
"active_alerts": alerts,
"reboot_required": reboot_req,
}),
)
}
"proactive_alerts" => {
let (alerts, state) = proactive::active_alerts(exec, root, &storage);
BridgeResponse::ok(
id,
json!({
"alerts": alerts,
"state": state,
}),
)
}
"proactive_snooze" => {
let dur = req.duration_seconds.unwrap_or(3600);
match proactive::snooze(exec, root, &storage, dur) {
Ok(()) => BridgeResponse::ok(id, json!({ "snoozed_seconds": dur })),
Err(e) => BridgeResponse::err(id, format!("could not save snooze: {e}")),
}
}
"proactive_dismiss" => {
let fp = req.fingerprint.unwrap_or_default();
match proactive::dismiss(exec, root, &storage, &fp) {
Ok(()) => BridgeResponse::ok(id, json!({ "dismissed": fp })),
Err(e) => BridgeResponse::err(id, format!("could not save dismissal: {e}")),
}
}
"updates" => {
let overview = check_unified_updates(exec, root);
BridgeResponse::ok(id, json!(overview))
}
"get_preferences" => {
let prefs = chooser::load_preferences(root);
BridgeResponse::ok(id, json!(prefs))
}
"set_preferences" => {
// Personal preferences are written to the user's own 0600 config,
// never to root-owned `/etc`. A write failure is reported as a
// failure so the GUI never claims "saved" when it did not persist.
if let Some(prefs) = req.preferences {
match chooser::save_personal_preferences(&storage, &prefs) {
Ok(()) => BridgeResponse::ok(id, json!({ "saved": true })),
Err(e) => BridgeResponse::err(id, format!("could not save preferences: {e}")),
}
} else {
BridgeResponse::err(id, "missing preferences payload")
}
}
"history" => match transaction::read(root) {
Ok(log) => BridgeResponse::ok(id, json!(log.records)),
Err(e) => BridgeResponse::err(id, e.to_string()),
},
"clear_conversation" => match conversation::clear_history(&conversation::history_path()) {
Ok(()) => BridgeResponse::ok(id, json!({ "cleared": true })),
Err(e) => BridgeResponse::err(id, e.to_string()),
},
"undo" => {
let action = SystemAction::Undo {
snapshot: req.snapshot,
};
execute_action_helper(exec, root, plans, id, action, req.yes.unwrap_or(false))
}
"legacy_install" => {
let app = match req.application {
Some(a) => a,
None => return BridgeResponse::err(id, "missing application parameter"),
};
let backend_enum = match req.backend.as_deref().and_then(Backend::parse) {
Some(b) => b,
None => {
return BridgeResponse::err(
id,
"legacy_install requires an explicit backend (--flatpak, --portage, --nix, --snap, --appimage, --ebuild)",
)
}
};
let mut install_req = InstallRequest::new(&app);
install_req.backend = Some(backend_enum);
match service::plan_legacy_install(plans, exec, root, &install_req) {
Ok(plan) => plan_response(id, "install", &plan),
Err(e) => BridgeResponse::err(id, e.to_string()),
}
}
"legacy_execute" => {
let action = if let Some(val) = req.action {
match serde_json::from_value::<SystemAction>(val) {
Ok(a) => a,
Err(e) => return BridgeResponse::err(id, format!("invalid action JSON: {e}")),
}
} else if let Some(phrase) = req.phrase {
match parse_natural(&phrase) {
Some(a) => a,
None => {
return BridgeResponse::err(id, format!("could not parse phrase: {phrase}"))
}
}
} else {
return BridgeResponse::err(id, "missing action or phrase parameter");
};
execute_action_helper(exec, root, plans, id, action, req.yes.unwrap_or(false))
}
"ask" => {
let query = req.request.unwrap_or_default();
if query.trim().is_empty() {
return BridgeResponse::err(id, "empty request");
}
let conv_path = conversation::history_path();
let history = conversation::load_history(&conv_path);
let constrained_backend = req.backend.as_deref().and_then(Backend::parse);
// 0. An explicit application reference always wins over inferred
// conversational context ("install vlc using flatpak").
if let Some((app, source)) = conversation::parse_explicit_install(&query) {
return plan_and_respond_install(
plans,
exec,
root,
id,
&app,
source.or(constrained_backend),
&query,
&conv_path,
);
}
// 1. Contextual follow-up check. Conversational context only ever
// produces further investigation or a reference to a reviewed
// plan; it never executes anything directly.
if let Some(followup) = conversation::resolve_followup(&query, &history) {
match followup {
FollowupResolution::Comparison {
application,
explanation,
..
} => {
return BridgeResponse::ok(
id,
json!({
"kind": "info",
"state": "info",
"application": application,
"summary": explanation.clone(),
"recommendation": explanation,
}),
);
}
FollowupResolution::SwitchBackend {
application,
target_backend,
} => {
return plan_and_respond_install(
plans,
exec,
root,
id,
&application,
Some(target_backend),
&query,
&conv_path,
);
}
FollowupResolution::ConfirmPlan { plan_id, digest } => {
match plans.load(&plan_id) {
Ok(plan) if plan.digest == digest => {
return plan_response(id, "confirm", &plan);
}
_ => {
return BridgeResponse::err(
id,
"that plan is no longer available or has changed; \
ask again for a fresh recommendation",
);
}
}
}
}
}
// 2. Install request
if let Some(app) = parse_install_phrase(&query) {
return plan_and_respond_install(
plans,
exec,
root,
id,
&app,
constrained_backend,
&query,
&conv_path,
);
}
// 3. Removal request (AI-first by default; legacy selection is an
// explicit GUI/CLI choice).
if let Some(app) = parse_removal_phrase(&query) {
return plan_and_respond_removal(
plans,
exec,
root,
id,
&app,
constrained_backend,
&query,
&conv_path,
);
}
// 4. General natural language request via the connected model.
let response = with_bridge_ai(exec, root, |ai, facts| {
service::plan_general(plans, exec, root, &query, facts, ai, constrained_backend)
});
match response {
Ok(Ok(plan)) => {
record_turn(
exec,
&conv_path,
ConversationTurn {
timestamp_unix: now_unix(),
// Structured plan summary, not the raw request.
query: plan.summary.clone(),
response_kind: "plan".into(),
application: None,
chosen_candidate: None,
alternatives: Vec::new(),
plan_id: Some(plan.id.clone()),
plan_digest: Some(plan.digest.clone()),
rationale: plan.rationale.clone(),
},
);
plan_response(id, "plan", &plan)
}
Ok(Err(e)) => BridgeResponse::err(id, e.to_string()),
Err(e) => BridgeResponse::err(id, e),
}
}
"execute" => {
let plan_id = match req.plan_id.as_deref() {
Some(p) => p,
None => return BridgeResponse::err(id, "missing plan_id parameter"),
};
let digest = match req.digest.as_deref() {
Some(d) => d,
None => return BridgeResponse::err(id, "missing digest parameter"),
};
match service::execute_plan(
exec,
root,
plans,
plan_id,
digest,
req.yes.unwrap_or(false),
) {
Ok(outcome) => BridgeResponse::ok(
id,
json!({
"completed": outcome.completed,
"state": "completed",
"snapshot": outcome.snapshot,
"result": outcome.result,
"verification": outcome.verification,
"launch": outcome.launch,
}),
),
Err(e) => BridgeResponse::err(id, e.to_string()),
}
}
unknown => BridgeResponse::err(id, format!("unknown bridge op: {unknown}")),
}
}
#[allow(clippy::too_many_arguments)]
fn plan_and_respond_install(
plans: &PlanStore,
exec: &Exec,
root: &Path,
id: u64,
app: &str,
constrained_backend: Option<Backend>,
query: &str,
conv_path: &Path,
) -> BridgeResponse {
if constrained_backend == Some(Backend::AppImage) {
let phase = exec.progress_phase("Searching AppImage catalog leads");
let recommendation =
phoebus_executor::install::appimage_discovery_guidance(exec, root, app);
phase.complete();
return BridgeResponse::ok(
id,
json!({
"kind": "info",
"state": "info",
"application": app,
"recommendation": recommendation,
}),
);
}
let mut install_req = InstallRequest::new(app);
install_req.backend = constrained_backend;
let session = BridgeSession { exec, root };
let result = with_bridge_ai(exec, root, |ai, facts| {
service::plan_install(plans, exec, root, &install_req, &session, Some(ai), facts)
});
match result {
Ok(Ok(plan)) => {
record_turn(
exec,
conv_path,
ConversationTurn {
timestamp_unix: now_unix(),
query: query.to_string(),
response_kind: "install".into(),
application: Some(app.to_string()),
chosen_candidate: plan.candidate.clone(),
alternatives: plan.alternatives.clone(),
plan_id: Some(plan.id.clone()),
plan_digest: Some(plan.digest.clone()),
rationale: plan.rationale.clone(),
},
);
plan_response(id, "install", &plan)
}
Ok(Err(e)) => BridgeResponse::err(id, e.to_string()),
Err(e) => BridgeResponse::err(id, e),
}
}
#[allow(clippy::too_many_arguments)]
fn plan_and_respond_removal(
plans: &PlanStore,
exec: &Exec,
root: &Path,
id: u64,
app: &str,
constrained_backend: Option<Backend>,
query: &str,
conv_path: &Path,
) -> BridgeResponse {
let result = with_bridge_ai(exec, root, |ai, facts| {
service::plan_removal_with_ai(plans, exec, root, app, constrained_backend, ai, facts)
});
match result {
Ok(Ok(plan)) => {
record_turn(
exec,
conv_path,
ConversationTurn {
timestamp_unix: now_unix(),
query: query.to_string(),
response_kind: "removal".into(),
application: Some(app.to_string()),
chosen_candidate: None,
alternatives: Vec::new(),
plan_id: Some(plan.id.clone()),
plan_digest: Some(plan.digest.clone()),
rationale: plan.rationale.clone(),
},
);
plan_response(id, "removal", &plan)
}
Ok(Err(e)) => BridgeResponse::err(id, e.to_string()),
Err(e) => BridgeResponse::err(id, e),
}
}
fn execute_action_helper(
exec: &Exec,
root: &Path,
plans: &PlanStore,
id: u64,
action: SystemAction,
assume_yes: bool,
) -> BridgeResponse {
let mut effects = match actions::resolve_effects(exec, &action, root) {
Ok(plan) => plan,
Err(e) => return BridgeResponse::err(id, format!("could not resolve effects: {e}")),
};
effects.recompute_digest();
let now = now_unix();
let actions_vec = vec![action.clone()];
let step_effects = vec![effects.clone()];
let digest = service::compute_plan_digest(&actions_vec, None, &effects, &step_effects);
let mut plan = PreparedPlan {
id: service::fresh_plan_id("act"),
created_unix: now,
expires_unix: now + service::DEFAULT_PLAN_TTL_SECONDS,
kind: service::PlanKind::General,
summary: action.describe(),
recommendation: action.describe(),
application: None,
candidate: None,
alternatives: Vec::new(),
rationale: Vec::new(),
warnings: Vec::new(),
actions: actions_vec,
effects,
step_effects,
digest: digest.clone(),
verification: "action completed".into(),
requires_root: action.requires_root(),
source: "legacy".into(),
executed: false,
target_root: service::canonical_root(root),
initiator_uid: service::effective_uid(),
integrity: String::new(),
};
if let Err(e) = plans.save(&mut plan) {
return BridgeResponse::err(id, format!("could not stage plan: {e}"));
}
match service::execute_plan(exec, root, plans, &plan.id, &digest, assume_yes) {
Ok(outcome) => BridgeResponse::ok(
id,
json!({
"output": outcome.result,
"snapshot": outcome.snapshot,
"verification": outcome.verification,
"state": "completed",
}),
),
Err(e) => BridgeResponse::err(id, e.to_string()),
}
}
fn parse_install_phrase(text: &str) -> Option<String> {
let mut trimmed = text.trim();
for prefix in ["please ", "Please "] {
if let Some(rest) = trimmed.strip_prefix(prefix) {
trimmed = rest.trim();
break;
}
}
let lower = trimmed.to_ascii_lowercase();
for prefix in ["install ", "add "] {
if lower.starts_with(prefix) {
let app = trimmed[prefix.len()..].trim();
if !app.is_empty() && !app.contains(char::is_whitespace) && !app.starts_with('-') {
return Some(app.to_string());
}
}
}
None
}
fn parse_removal_phrase(text: &str) -> Option<String> {
let mut trimmed = text.trim();
for prefix in ["please ", "Please "] {
if let Some(rest) = trimmed.strip_prefix(prefix) {
trimmed = rest.trim();
break;
}
}
let lower = trimmed.to_ascii_lowercase();
for prefix in ["remove ", "uninstall ", "delete "] {
if lower.starts_with(prefix) {
let app = trimmed[prefix.len()..].trim();
if !app.is_empty() && !app.contains(char::is_whitespace) && !app.starts_with('-') {
return Some(app.to_string());
}
}
}
None
}
/// Run line-delimited JSON-RPC loop on stdio.
pub fn run_stdio(exec: Exec, root: &Path) -> std::result::Result<(), Box<dyn std::error::Error>> {
let stdin = std::io::stdin();
let output_lock = Arc::new(Mutex::new(()));
let active_id = Arc::new(AtomicU64::new(0));
let progress_lock = Arc::clone(&output_lock);
let progress_id = Arc::clone(&active_id);
let exec = exec.with_progress(Arc::new(move |event| {
let id = progress_id.load(Ordering::SeqCst);
if id == 0 {
return;
}
let message = progress_message(id, event);
if let Ok(line) = serde_json::to_string(&message) {
let _ = write_protocol_line(&progress_lock, &line);
}
}));
let plans = PlanStore::for_current_user();
for line in stdin.lock().lines() {
let line = line?;
if line.trim().is_empty() {
continue;
}
let req: BridgeRequest = match serde_json::from_str(&line) {
Ok(r) => r,
Err(e) => {
let resp = BridgeResponse::err(0, format!("invalid JSON request: {e}"));
write_protocol_line(&output_lock, &serde_json::to_string(&resp)?)?;
continue;
}
};
active_id.store(req.id, Ordering::SeqCst);
let request_phase = bridge_request_label(&req.op).map(|label| exec.progress_phase(label));
let resp = handle_request(&exec, root, &plans, req);
if let Some(phase) = request_phase {
if resp.ok {
phase.complete();
}
}
write_protocol_line(&output_lock, &serde_json::to_string(&resp)?)?;
active_id.store(0, Ordering::SeqCst);
}
Ok(())
}
fn bridge_request_label(op: &str) -> Option<&'static str> {
match op {
"ask" => Some("Investigating your request"),
"execute" | "legacy_execute" | "undo" => Some("Executing the reviewed action"),
"legacy_install" => Some("Checking the selected package"),
"updates" => Some("Checking package updates"),
_ => None,
}
}
fn progress_message(id: u64, event: ProgressEvent) -> serde_json::Value {
match event {
ProgressEvent::Started { label, detail } => json!({
"id": id, "event": "progress", "progress": {
"label": label, "state": "started", "detail": detail
}
}),
ProgressEvent::Finished {
label,
detail,
success,
elapsed,
} => json!({
"id": id, "event": "progress", "progress": {
"label": label,
"state": if success { "completed" } else { "failed" },
"detail": detail,
"elapsed_ms": elapsed.as_millis()
}
}),
}
}
fn write_protocol_line(lock: &Mutex<()>, line: &str) -> std::io::Result<()> {
let _guard = lock
.lock()
.map_err(|_| std::io::Error::other("assistant output lock poisoned"))?;
let mut stdout = std::io::stdout().lock();
writeln!(stdout, "{line}")?;
stdout.flush()
}
#[cfg(test)]
mod tests {
use super::*;
use phoebus_core::Redactor;
use phoebus_executor::command::RecordingRunner;
use phoebus_executor::Logger;
use tempfile::tempdir;
fn make_test_exec(root: &Path) -> Exec {
let temp = tempdir().unwrap().keep();
let logger = Logger::open(temp.join("test.log"), Redactor::new(), false);
Exec::new(
Box::new(RecordingRunner::new()),
logger,
false,
root.to_path_buf(),
temp,
)
}
fn request(op: &str) -> BridgeRequest {
BridgeRequest {
id: 1,
op: op.into(),
request: None,
application: None,
backend: None,
phrase: None,
plan_id: None,
action: None,
actions: None,
digest: None,
yes: None,
duration_seconds: None,
fingerprint: None,
preferences: None,
snapshot: None,
}
}
/// Serializes tests that redirect personal storage through the process
/// environment.
static ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
/// Take the environment lock without cascading a panic from another test
/// into every waiter (a poisoned mutex would otherwise fail all three
/// env-dependent tests).
fn env_lock() -> std::sync::MutexGuard<'static, ()> {
ENV_LOCK
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner())
}
struct EnvGuard {
key: &'static str,
original: Option<std::ffi::OsString>,
}
impl EnvGuard {
fn set(key: &'static str, val: &std::ffi::OsStr) -> Self {
let original = std::env::var_os(key);
std::env::set_var(key, val);
Self { key, original }
}
}
impl Drop for EnvGuard {
fn drop(&mut self) {
match &self.original {
Some(orig) => std::env::set_var(self.key, orig),
None => std::env::remove_var(self.key),
}
}
}
#[test]
fn personal_preferences_roundtrip_and_use_user_storage() {
let _env = env_lock();
let base = tempdir().unwrap();
let _guard = EnvGuard::set("PHOEBUS_PERSONAL_DIR", base.path().as_os_str());
let temp = tempdir().unwrap();
let root = temp.path();
let exec = make_test_exec(root);
let plans = PlanStore::with_dir(tempdir().unwrap().keep());
let mut prefs = Preferences::default();
prefs.per_app.insert("vlc".into(), Backend::Snap);
let mut save = request("set_preferences");
save.preferences = Some(prefs);
let resp = handle_request(&exec, root, &plans, save);
assert!(resp.ok, "{:?}", resp.error);
// Stored in the user's own config, never root-owned /etc.
let user_file = base.path().join(".config/phoebus/package-preferences.toml");
assert!(user_file.is_file(), "expected {}", user_file.display());
assert!(!root.join("etc/phoebus/package-preferences.toml").exists());
let resp = handle_request(&exec, root, &plans, request("get_preferences"));
assert!(resp.ok);
assert_eq!(resp.result.unwrap()["per_app"]["vlc"], "snap");
}
#[test]
fn a_failed_preference_save_is_reported_as_a_failure() {
let _env = env_lock();
let blocker = tempdir().unwrap();
let not_a_dir = blocker.path().join("file");
std::fs::write(&not_a_dir, "x").unwrap();
let _guard = EnvGuard::set("PHOEBUS_PERSONAL_DIR", not_a_dir.as_os_str());
let temp = tempdir().unwrap();
let root = temp.path();
let exec = make_test_exec(root);
let plans = PlanStore::with_dir(tempdir().unwrap().keep());
let mut save = request("set_preferences");
save.preferences = Some(Preferences::default());
let resp = handle_request(&exec, root, &plans, save);
assert!(!resp.ok, "a failed write must not report success");
assert!(resp.error.unwrap().to_lowercase().contains("could not"));
}
#[test]
fn snooze_and_dismiss_persist_to_user_storage() {
let _env = env_lock();
let base = tempdir().unwrap();
let _guard = EnvGuard::set("PHOEBUS_PERSONAL_DIR", base.path().as_os_str());
let temp = tempdir().unwrap();
let root = temp.path();
let exec = make_test_exec(root);
let plans = PlanStore::with_dir(tempdir().unwrap().keep());
let mut snooze = request("proactive_snooze");
snooze.duration_seconds = Some(3600);
let resp = handle_request(&exec, root, &plans, snooze);
assert!(resp.ok, "snooze failed: {:?}", resp.error);
let mut dismiss = request("proactive_dismiss");
dismiss.fingerprint = Some("reboot_required".into());
assert!(handle_request(&exec, root, &plans, dismiss).ok);
let state_file = base
.path()
.join(".local/state/phoebus/proactive-state.toml");
assert!(state_file.is_file(), "expected {}", state_file.display());
let text = std::fs::read_to_string(&state_file).unwrap();
assert!(text.contains("reboot_required"), "{text}");
}
#[test]
fn test_handshake_and_history() {
let _env = env_lock();
let personal = tempdir().unwrap();
let _guard = EnvGuard::set("PHOEBUS_PERSONAL_DIR", personal.path().as_os_str());
let temp = tempdir().unwrap();
let root = temp.path();
let exec = make_test_exec(root);
let req = BridgeRequest {
id: 1,
op: "handshake".into(),
request: None,
application: None,
backend: None,
phrase: None,
plan_id: None,
action: None,
actions: None,
digest: None,
yes: None,
duration_seconds: None,
fingerprint: None,
preferences: None,
snapshot: None,
};
let plans = PlanStore::with_dir(tempdir().unwrap().keep());
let resp = handle_request(&exec, root, &plans, req);
assert!(resp.ok);
assert_eq!(resp.id, 1);
let res = resp.result.unwrap();
assert_eq!(res["protocol_version"], ASSISTANT_PROTOCOL_VERSION);
assert!(res["active_alerts"].is_array());
// Test history request
let hist_req = BridgeRequest {
id: 2,
op: "history".into(),
request: None,
application: None,
backend: None,
phrase: None,
plan_id: None,
action: None,
actions: None,
digest: None,
yes: None,
duration_seconds: None,
fingerprint: None,
preferences: None,
snapshot: None,
};
let hist_resp = handle_request(&exec, root, &plans, hist_req);
assert!(hist_resp.ok);
}
#[test]
fn test_parse_install_phrase() {
assert_eq!(
parse_install_phrase("install firefox"),
Some("firefox".into())
);
assert_eq!(
parse_install_phrase("please install firefox"),
Some("firefox".into())
);
assert_eq!(parse_install_phrase("add vlc"), Some("vlc".into()));
assert_eq!(parse_install_phrase("why is audio broken"), None);
}
#[test]
fn appimage_install_request_returns_catalog_information_without_a_plan() {
let root = tempdir().unwrap();
let exec = make_test_exec(root.path());
let plans = PlanStore::with_dir(tempdir().unwrap().keep());
let response = plan_and_respond_install(
&plans,
&exec,
root.path(),
7,
"Etcher",
Some(Backend::AppImage),
"install Etcher with appimage",
&root.path().join("history.json"),
);
assert!(response.ok);
let result = response.result.unwrap();
assert_eq!(result["kind"], "info");
assert!(result.get("plan_id").is_none());
assert!(result["recommendation"]
.as_str()
.unwrap()
.contains("no verified artifact hash"));
}
#[test]
fn natural_appimage_install_phrase_reaches_catalog_information() {
let root = tempdir().unwrap();
let exec = make_test_exec(root.path());
let plans = PlanStore::with_dir(tempdir().unwrap().keep());
let mut req = request("ask");
req.request = Some("i want to install balenaEtcher with appimage".into());
let response = handle_request(&exec, root.path(), &plans, req);
assert!(response.ok);
let result = response.result.unwrap();
assert_eq!(result["kind"], "info");
assert!(result["recommendation"]
.as_str()
.unwrap()
.contains("AppImage search for balenaetcher"));
}
#[test]
fn test_parse_removal_phrase() {
assert_eq!(
parse_removal_phrase("remove firefox"),
Some("firefox".into())
);
assert_eq!(parse_removal_phrase("uninstall vlc"), Some("vlc".into()));
assert_eq!(
parse_removal_phrase("delete thunderbird"),
Some("thunderbird".into())
);
assert_eq!(parse_removal_phrase("install firefox"), None);
}
}