diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index bddb1c4..6423cc5 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -39,7 +39,9 @@ installation or administrative logic: - `sys --assistant-bridge` speaks newline-delimited JSON-RPC on stdin/stdout, providing a uniform interface for the desktop assistant (`phoebus-assistant`) for conversational interaction, legacy actions, unified updates, proactive alerts, - and user preferences (ADR 0010, ADR 0013). + and user preferences (ADR 0010, ADR 0013). Redacted progress events share + each request ID and precede its final response, so the assistant can show + broker and model-wait activity without exposing command output or credentials. ### phoebus-core @@ -242,4 +244,3 @@ application launched from the desktop menu, keybinding, or launcher: its maintained source; builds before removing; Brave refused with its reason) and `BuildTunedKernel { make_default }` (separate BLS entry, fallback kept, default only after a test boot). - diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index b521a51..6f6a1f3 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -5,6 +5,23 @@ this file is the curated, human-readable summary. ## Unreleased — Fast defaults with user-controlled source builds +- **Visible assistant activity (2026-10-03).** The `sys` assistant bridge now + streams redacted phase events with the request ID. The QML conversation card + shows each phase as running, completed, or failed during investigation and + approved execution, and keeps the activity after the final result. Model + calls and system-fact collection have explicit phases. A malformed install + model reply or typed investigation gets up to two bounded corrections before + failing closed. Neither a retry nor progress can approve a package change. + Startup now checks reboot, storage, service, and failed-operation alerts + quickly; the full update scan runs when the Alerts or Updates view opens, + so it cannot hold the assistant handshake and queue conversations. The + running VM shows live fact checks and model waits for the user's Balena + Etcher request, and completed activity for AppImage catalog discovery. The + final VM run stopped safely after eight model turns without a valid plan; + no package was installed. The card explains the failure in plain language. + Opening the scratchpad now focuses the prompt without calling an unsupported + floating-window activation method that aborted the focus timer. + - **AppImage catalog search (2026-10-03).** `sys search --legacy --appimage` now combines managed images with matching leads from the AppImage project's community feed. Results include readable descriptions diff --git a/docs/HANDOFF.md b/docs/HANDOFF.md index 580ec32..aeab3c3 100644 --- a/docs/HANDOFF.md +++ b/docs/HANDOFF.md @@ -3,6 +3,32 @@ Rolling note between work sessions. **Update this file before you finish**, then commit it. It should be short and current; use `git log` for detail. +- **Visible assistant activity (2026-10-03):** The assistant bridge now sends + redacted `sys` phase events keyed by request ID before the final reply; QML + displays and retains each phase in the conversation card. System-fact reads, + model waits, typed investigations, and reviewed execution report progress. + The malformed-JSON error observed for `i want to install balena etcher` + now triggers up to two bounded corrections and retries, with no execution + on failure. + The VM then exposed a slow startup handshake caused by a full proactive + update scan. Startup now runs quick reboot/storage/service/transaction + checks, while full update discovery runs when Alerts or Updates is opened. + The running VM now has the updated user-local static `sys` and QML: the + assistant connects promptly and displays fact checks, model waits, and + AppImage search stages (`assistant-activity-model-wait.png` and + `assistant-activity-verified.png` under `/var/tmp/phoebus-vm`). A broken + scratchpad activation call was removed so the prompt receives focus. The + exact natural Etcher request first failed closed when the model omitted an + `action` field. One correction got past that error, but the model then used + an invalid spaced application name. The final two-correction build was + installed in the VM (SHA-256 + `0b2fcbf92faa06dcacbb366b91bcf08f8ac3a73bc2ec70e704a08faf328a3738`). + It made read-only checks, then stopped after eight turns without a valid + proposal; no install was approved or executed. The GUI now explains that + outcome in user terms. Screenshot: `two-retry-scrolled.png`. Rust format, + strict clippy, workspace tests, dynamic/static release builds, and the VM + harness tests pass. Fresh ISO verification remains gated by disk space. + - **AppImage community search (2026-10-03):** The previous `sys search` AppImage lane showed only Phoebus-managed files. It now also reads the AppImage project's HTTPS community feed on the running system, ranks matching diff --git a/docs/STATUS.md b/docs/STATUS.md index bc118d1..e5cfbe5 100644 --- a/docs/STATUS.md +++ b/docs/STATUS.md @@ -48,6 +48,29 @@ disposable VM; `serial-driver.py recovery` now automates the same check. ## Matrix +Assistant activity stream (2026-10-03): `sys --assistant-bridge` emits redacted +progress JSON lines before its final response, keyed by the same ID. The GUI +keeps those lines visible on the corresponding conversation or approval card. +System facts, each model call, read-only investigations, and approved execution +report phases. A malformed install-model JSON reply or typed investigation +gets up to two bounded retries; repeated malformed replies fail closed. Rust unit and +CLI protocol tests cover the retry and event ordering. The startup handshake uses quick proactive +checks; full update discovery runs when the Alerts or Updates view opens. +The running disposable VM displayed model waits and read-only candidate checks +for `i want to install balena etcher` while pending +(`/var/tmp/phoebus-vm/assistant-activity-model-wait.png`). An AppImage catalog +request retained its completed `sys` activity in the card +(`/var/tmp/phoebus-vm/assistant-activity-verified.png`). The first natural +Etcher run failed closed because the model omitted a required `action` field. +With one retry, the model then submitted an invalid application name. The final +two-correction build was installed in the VM and checked the exact natural +request again; the model checked candidates but exhausted eight turns without +a valid proposal. No installation was approved or executed. The failure card +and activity are captured in `/var/tmp/phoebus-vm/two-retry-scrolled.png`. +The GUI now gives a plain explanation for this bounded failure. The +scratchpad now focuses its prompt on opening in the running VM +(`/var/tmp/phoebus-vm/prompt-focus-test.png`). + AppImage catalog discovery (2026-10-03): `sys search --legacy --appimage` searches managed images and the AppImage community feed on the running system. Remote matches are `catalog lead` entries with a catalog page diff --git a/docs/SYS.md b/docs/SYS.md index 2065e12..5acb9d0 100644 --- a/docs/SYS.md +++ b/docs/SYS.md @@ -30,8 +30,10 @@ evidence, reviewing effects, applying each approved action, and verifying the result. A command that takes more than a moment shows its operation label; long steps repeat their current label and elapsed time every ten seconds. Progress never includes command arguments, command output, or credentials. -Results remain on stdout. Broker JSON and the assistant's stdio protocol do -not emit human progress. Informational model answers are wrapped as prose and +Results remain on stdout. Broker JSON does not emit human progress. The +assistant's stdio protocol sends redacted progress JSON lines before the final +reply, keyed by request ID; its GUI displays these phases in the conversation +card. Informational model answers are wrapped as prose and omit the approval digest when no action is proposed. > [!NOTE] @@ -461,6 +463,18 @@ The desktop assistant GUI (`phoebus-assistant`) is a lightweight Quickshell QML interface that delegates all logic to `sys --assistant-bridge`. The bridge runs a stdio JSON-RPC server speaking newline-delimited JSON messages: +For work that takes time, the bridge emits zero or more intermediate +`{"id":17,"event":"progress","progress":{"label":"...","state":"started"}}` +messages before the final response with the same ID. A matching `completed` +or `failed` event closes each phase. Labels pass through the shared secret +redactor; command arguments, output, model messages, and credentials are not +sent to QML. The assistant displays the activity under the relevant request +or approved plan and retains it after completion. Callers must wait for a +final response rather than treating a progress event as the reply. +Malformed model JSON or typed investigation steps receive up to two bounded +correction requests. A third malformed reply returns an error; no action is +executed from that reply. + - `handshake`: validates client identity and checks active AI model connectivity. - `ask`: submits a conversational request (`install firefox`, `why is audio broken?`) into the shared AI workflow, returning a reviewed plan card for install, diff --git a/installer-rs/crates/phoebus-ai/src/install.rs b/installer-rs/crates/phoebus-ai/src/install.rs index d023f41..c002f83 100644 --- a/installer-rs/crates/phoebus-ai/src/install.rs +++ b/installer-rs/crates/phoebus-ai/src/install.rs @@ -358,13 +358,35 @@ pub fn investigate_install( let mut chat = build_open_request(provider, model, facts, request); let mut repeated: std::collections::BTreeMap = std::collections::BTreeMap::new(); let mut turns = 0usize; + let mut malformed_replies = 0usize; while turns < limits.max_turns { turns += 1; let body = messages_body(&chat)?; let response = transport.send(provider, endpoint, &body)?; let content = extract_content(&response)?; - let step = parse_step(&content)?; + let step = match parse_step(&content) { + Ok(step) => step, + Err(error @ (AiError::Json(_) | AiError::Rejected(_))) + if malformed_replies < 2 && turns < limits.max_turns => + { + malformed_replies += 1; + chat.messages.push(ChatMessage { + role: "user".into(), + content: format!( + "Your last reply was invalid ({error}). Return exactly one JSON object \ + with version 2 and kind investigate, ask, or propose. Investigation \ + requests must be typed action objects, for example \ + {{\"action\":\"discover_candidates\",\"query\":\"etcher\"}}. \ + A proposal application must be a canonical name without spaces, \ + for example \"etcher\". Copy candidate IDs only from actual evidence. \ + Do not include Markdown or explanatory text." + ), + }); + continue; + } + Err(error) => return Err(error), + }; match step { InstallStep::Ask { question } => { @@ -754,4 +776,147 @@ mod tests { .unwrap_err(); assert!(matches!(err, AiError::ProviderUnavailable(_))); } + + #[test] + fn malformed_model_json_gets_one_bounded_retry() { + let transport = crate::provider::ScriptedTransport::new(vec![ + chat_response("Here is a plan: {broken"), + chat_response(ok_proposal()), + ]); + let session = Sessions { + evidence: std::cell::RefCell::new(Vec::new()), + answer: None, + }; + let proposal = investigate_install( + ProviderKind::Local, + "http://127.0.0.1:11434/v1/chat/completions", + "m", + &facts(), + "install firefox", + &transport, + &session, + &|_| Ok(()), + &Limits::default(), + ) + .unwrap(); + assert_eq!(proposal.candidate, "org.mozilla.firefox"); + let requests = transport.requests(); + assert_eq!(requests.len(), 2); + assert!(requests[1].contains("Your last reply was invalid")); + } + + #[test] + fn malformed_investigation_action_gets_one_bounded_retry() { + let invalid = r#"{"version":2,"kind":"investigate","requests":[{"query":"etcher"}]}"#; + let transport = crate::provider::ScriptedTransport::new(vec![ + chat_response(invalid), + chat_response(ok_proposal()), + ]); + let session = Sessions { + evidence: std::cell::RefCell::new(Vec::new()), + answer: None, + }; + let proposal = investigate_install( + ProviderKind::Local, + "http://127.0.0.1:11434/v1/chat/completions", + "m", + &facts(), + "install etcher", + &transport, + &session, + &|_| Ok(()), + &Limits::default(), + ) + .unwrap(); + assert_eq!(proposal.candidate, "org.mozilla.firefox"); + assert!(session.evidence.borrow().is_empty()); + assert!(transport.requests()[1].contains("typed action objects")); + } + + #[test] + fn repeatedly_malformed_investigation_actions_still_fail_closed() { + let invalid = r#"{"version":2,"kind":"investigate","requests":[{"query":"etcher"}]}"#; + let transport = crate::provider::ScriptedTransport::new(vec![ + chat_response(invalid), + chat_response(invalid), + chat_response(invalid), + ]); + let session = Sessions { + evidence: std::cell::RefCell::new(Vec::new()), + answer: None, + }; + let err = investigate_install( + ProviderKind::Local, + "http://127.0.0.1:11434/v1/chat/completions", + "m", + &facts(), + "install etcher", + &transport, + &session, + &|_| Ok(()), + &Limits::default(), + ) + .unwrap_err(); + assert!(matches!(err, AiError::Rejected(_))); + assert!(session.evidence.borrow().is_empty()); + assert_eq!(transport.requests().len(), 3); + } + + #[test] + fn a_second_format_correction_can_fix_a_proposal_name() { + let invalid_action = + r#"{"version":2,"kind":"investigate","requests":[{"query":"etcher"}]}"#; + let invalid_name = r#"{"version":2,"kind":"propose","proposal":{"application":"balena etcher","backend":"flatpak","candidate":"io.balena.etcher","reason":"desktop app"}}"#; + let transport = crate::provider::ScriptedTransport::new(vec![ + chat_response(invalid_action), + chat_response(invalid_name), + chat_response(ok_proposal()), + ]); + let session = Sessions { + evidence: std::cell::RefCell::new(Vec::new()), + answer: None, + }; + let proposal = investigate_install( + ProviderKind::Local, + "http://127.0.0.1:11434/v1/chat/completions", + "m", + &facts(), + "install etcher", + &transport, + &session, + &|_| Ok(()), + &Limits::default(), + ) + .unwrap(); + assert_eq!(proposal.application, "firefox"); + assert_eq!(transport.requests().len(), 3); + assert!(transport.requests()[2].contains("canonical name without spaces")); + } + + #[test] + fn repeatedly_malformed_model_json_still_fails_closed() { + let transport = crate::provider::ScriptedTransport::new(vec![ + chat_response("{broken"), + chat_response("{broken again"), + chat_response("{still broken"), + ]); + let session = Sessions { + evidence: std::cell::RefCell::new(Vec::new()), + answer: None, + }; + let err = investigate_install( + ProviderKind::Local, + "http://127.0.0.1:11434/v1/chat/completions", + "m", + &facts(), + "install firefox", + &transport, + &session, + &|_| Ok(()), + &Limits::default(), + ) + .unwrap_err(); + assert!(matches!(err, AiError::Json(_))); + assert_eq!(transport.requests().len(), 3); + } } diff --git a/installer-rs/crates/phoebus-executor/src/proactive.rs b/installer-rs/crates/phoebus-executor/src/proactive.rs index 3952af3..16007e2 100644 --- a/installer-rs/crates/phoebus-executor/src/proactive.rs +++ b/installer-rs/crates/phoebus-executor/src/proactive.rs @@ -84,6 +84,16 @@ fn now_unix() -> u64 { /// Run deterministic checks against the system. Returns all currently detected alerts. pub fn check_system(exec: &Exec, root: &Path) -> Vec { + check_system_inner(exec, root, true) +} + +/// Fast startup checks. Update discovery is performed when the Alerts or +/// Updates view is opened so it cannot hold the assistant handshake open. +pub fn check_system_quick(exec: &Exec, root: &Path) -> Vec { + check_system_inner(exec, root, false) +} + +fn check_system_inner(exec: &Exec, root: &Path, include_updates: bool) -> Vec { let now = now_unix(); let mut alerts = Vec::new(); @@ -203,25 +213,27 @@ pub fn check_system(exec: &Exec, root: &Path) -> Vec { } // 5. Updates ready for review check - let overview = check_unified_updates(exec, root); - if overview.total_updates() > 0 { - alerts.push(ProactiveAlert { - id: format!("updates-{}", now), - category: ProactiveCategory::UpdatesReady, - title: format!("{} updates ready for review", overview.total_updates()), - message: format!( - "Updates available across package sources: {} Portage, {} Flatpak, {} Snap.", - overview.updates_for(phoebus_core::selection::Backend::PortageBinary) - + overview.updates_for(phoebus_core::selection::Backend::PortageSource), - overview.updates_for(phoebus_core::selection::Backend::Flatpak), - overview.updates_for(phoebus_core::selection::Backend::Snap), - ), - severity: "info".into(), - actionable: true, - suggested_phrase: Some("Show me what needs updating".into()), - created_unix: now, - fingerprint: format!("updates_ready:{}", overview.total_updates()), - }); + if include_updates { + let overview = check_unified_updates(exec, root); + if overview.total_updates() > 0 { + alerts.push(ProactiveAlert { + id: format!("updates-{}", now), + category: ProactiveCategory::UpdatesReady, + title: format!("{} updates ready for review", overview.total_updates()), + message: format!( + "Updates available across package sources: {} Portage, {} Flatpak, {} Snap.", + overview.updates_for(phoebus_core::selection::Backend::PortageBinary) + + overview.updates_for(phoebus_core::selection::Backend::PortageSource), + overview.updates_for(phoebus_core::selection::Backend::Flatpak), + overview.updates_for(phoebus_core::selection::Backend::Snap), + ), + severity: "info".into(), + actionable: true, + suggested_phrase: Some("Show me what needs updating".into()), + created_unix: now, + fingerprint: format!("updates_ready:{}", overview.total_updates()), + }); + } } alerts @@ -235,6 +247,23 @@ pub fn active_alerts( exec: &Exec, root: &Path, storage: &UserStorage, +) -> (Vec, ProactiveState) { + active_alerts_inner(exec, root, storage, true) +} + +pub fn active_alerts_quick( + exec: &Exec, + root: &Path, + storage: &UserStorage, +) -> (Vec, ProactiveState) { + active_alerts_inner(exec, root, storage, false) +} + +fn active_alerts_inner( + exec: &Exec, + root: &Path, + storage: &UserStorage, + include_updates: bool, ) -> (Vec, ProactiveState) { let now = now_unix(); let mut state = load_state(storage, root); @@ -245,7 +274,11 @@ pub fn active_alerts( return (Vec::new(), state); } - let all = check_system(exec, root); + let all = if include_updates { + check_system(exec, root) + } else { + check_system_quick(exec, root) + }; let filtered = all .into_iter() .filter(|a| !state.is_dismissed(&a.fingerprint)) @@ -349,6 +382,18 @@ mod tests { assert!(!state3.is_active(now_unix())); } + #[test] + fn startup_alert_check_skips_expensive_update_discovery() { + let temp = tempdir().unwrap(); + let root = temp.path(); + let runner = RecordingRunner::new(); + let exec = make_exec(runner.clone(), root); + let store = local_storage(&tempdir().unwrap().keep()); + + let _ = active_alerts_quick(&exec, root, &store); + assert_eq!(runner.programs(), vec!["df", "systemctl"]); + } + #[test] fn alert_state_is_isolated_per_user() { let temp = tempdir().unwrap(); diff --git a/installer-rs/crates/phoebus-installer/src/assistant_bridge.rs b/installer-rs/crates/phoebus-installer/src/assistant_bridge.rs index da98743..3370184 100644 --- a/installer-rs/crates/phoebus-installer/src/assistant_bridge.rs +++ b/installer-rs/crates/phoebus-installer/src/assistant_bridge.rs @@ -6,13 +6,17 @@ 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::SystemFacts; +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; @@ -153,8 +157,14 @@ impl InstallSession for BridgeSession<'_> { 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) => outcome.output, + Ok(outcome) => { + phase.complete(); + outcome.output + } Err(e) => format!("investigation failed: {e}"), }; Evidence { @@ -187,7 +197,13 @@ fn with_bridge_ai( ); } 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 { @@ -200,12 +216,28 @@ fn with_bridge_ai( } else { resolved.model.clone() }, - transport: transport.as_ref(), + 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 { + 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 { @@ -250,7 +282,7 @@ pub fn handle_request( "handshake" => { let ai_conf = load_installed_ai_config(root); let prefs = chooser::load_preferences(root); - let (alerts, _) = proactive::active_alerts(exec, root, &storage); + 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() @@ -265,6 +297,7 @@ pub fn handle_request( "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, }), ) @@ -550,13 +583,17 @@ fn plan_and_respond_install( 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": phoebus_executor::install::appimage_discovery_guidance(exec, root, app), + "recommendation": recommendation, }), ); } @@ -732,10 +769,22 @@ fn parse_removal_phrase(text: &str) -> Option { } /// Run line-delimited JSON-RPC loop on stdio. -pub fn run_stdio(exec: &Exec, root: &Path) -> std::result::Result<(), Box> { +pub fn run_stdio(exec: Exec, root: &Path) -> std::result::Result<(), Box> { let stdin = std::io::stdin(); - let stdout = std::io::stdout(); - let mut stdout_lock = stdout.lock(); + 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() { @@ -747,19 +796,67 @@ pub fn run_stdio(exec: &Exec, root: &Path) -> std::result::Result<(), Box r, Err(e) => { let resp = BridgeResponse::err(0, format!("invalid JSON request: {e}")); - writeln!(stdout_lock, "{}", serde_json::to_string(&resp)?)?; - stdout_lock.flush()?; + write_protocol_line(&output_lock, &serde_json::to_string(&resp)?)?; continue; } }; - let resp = handle_request(exec, root, &plans, req); - writeln!(stdout_lock, "{}", serde_json::to_string(&resp)?)?; - stdout_lock.flush()?; + 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::*; @@ -944,6 +1041,7 @@ mod tests { 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 { diff --git a/installer-rs/crates/phoebus-installer/src/bin/sys.rs b/installer-rs/crates/phoebus-installer/src/bin/sys.rs index f7315ce..935afb2 100644 --- a/installer-rs/crates/phoebus-installer/src/bin/sys.rs +++ b/installer-rs/crates/phoebus-installer/src/bin/sys.rs @@ -300,7 +300,7 @@ fn run() -> std::result::Result<(), Box> { // 1. Assistant Bridge if cli.assistant_bridge { - return phoebus_installer::assistant_bridge::run_stdio(&exec, &cli.root); + return phoebus_installer::assistant_bridge::run_stdio(exec, &cli.root); } // 2. Broker execute plan diff --git a/installer-rs/crates/phoebus-installer/tests/sys_cli.rs b/installer-rs/crates/phoebus-installer/tests/sys_cli.rs index 4ac4710..d110395 100644 --- a/installer-rs/crates/phoebus-installer/tests/sys_cli.rs +++ b/installer-rs/crates/phoebus-installer/tests/sys_cli.rs @@ -4,7 +4,8 @@ //! Deterministic operation is explicitly selected with `--legacy`. //! JSON action entry points require `--legacy` or `--broker`. -use std::process::Command; +use std::io::Write; +use std::process::{Command, Stdio}; fn sys() -> Command { Command::new(env!("CARGO_BIN_EXE_sys")) @@ -19,6 +20,42 @@ fn effective_uid_is_root() -> bool { .unwrap_or(false) } +#[test] +fn assistant_bridge_streams_progress_before_its_final_reply() { + let root = tempfile::tempdir().expect("temp root"); + let mut child = sys() + .arg("--root") + .arg(root.path()) + .arg("--assistant-bridge") + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .spawn() + .expect("start bridge"); + child + .stdin + .take() + .expect("bridge stdin") + .write_all(b"{\"id\":17,\"op\":\"ask\",\"request\":\"\"}\n") + .expect("send request"); + let output = child.wait_with_output().expect("bridge output"); + assert!(output.status.success()); + let lines: Vec = String::from_utf8(output.stdout) + .expect("utf8 protocol") + .lines() + .map(|line| serde_json::from_str(line).expect("JSON protocol line")) + .collect(); + assert!( + lines.len() >= 3, + "expected start, finish and response: {lines:?}" + ); + assert_eq!(lines[0]["id"], 17); + assert_eq!(lines[0]["event"], "progress"); + assert_eq!(lines[0]["progress"]["state"], "started"); + assert_eq!(lines[lines.len() - 2]["progress"]["state"], "failed"); + assert_eq!(lines.last().expect("response")["ok"], false); + assert!(lines.iter().all(|line| line["id"] == 17)); +} + #[test] fn natural_option_like_operand_is_rejected_in_legacy_mode() { let out = sys() diff --git a/installer/live/desktop/phoebus-assistant/AssistantBridge.qml b/installer/live/desktop/phoebus-assistant/AssistantBridge.qml index 0a36cb3..75e407f 100644 --- a/installer/live/desktop/phoebus-assistant/AssistantBridge.qml +++ b/installer/live/desktop/phoebus-assistant/AssistantBridge.qml @@ -43,10 +43,10 @@ Singleton { proc.running = false; } - function call(op, payload, onDone) { + function call(op, payload, onDone, onProgress) { const id = root.nextId++; if (onDone) - root.pending[id] = onDone; + root.pending[id] = { done: onDone, progress: onProgress || null }; const request = Object.assign({ id: id, op: op }, payload || {}); const line = JSON.stringify(request) + "\n"; if (!proc.running) { @@ -71,9 +71,14 @@ Singleton { return; } if (msg.id !== undefined && root.pending[msg.id]) { - const cb = root.pending[msg.id]; + const callback = root.pending[msg.id]; + if (msg.event === "progress") { + if (callback.progress) + callback.progress(msg.progress || {}); + return; + } delete root.pending[msg.id]; - cb(msg); + callback.done(msg); } } @@ -88,12 +93,12 @@ Singleton { }); } - function ask(query, backend, cb) { - call("ask", { request: query, backend: backend }, cb); + function ask(query, backend, cb, onProgress) { + call("ask", { request: query, backend: backend }, cb, onProgress); } - function execute(planId, digest, yes, cb) { - call("execute", { plan_id: planId, digest: digest, yes: yes }, cb); + function execute(planId, digest, yes, cb, onProgress) { + call("execute", { plan_id: planId, digest: digest, yes: yes }, cb, onProgress); } function legacyInstall(application, backend, cb) { @@ -160,7 +165,7 @@ Singleton { const cb = root.pending[ids[i]]; delete root.pending[ids[i]]; try { - cb({ ok: false, error: "The assistant bridge stopped (exit " + exitCode + ")." }); + cb.done({ ok: false, error: "The assistant bridge stopped (exit " + exitCode + ")." }); } catch (e) {} } } diff --git a/installer/live/desktop/phoebus-assistant/shell.qml b/installer/live/desktop/phoebus-assistant/shell.qml index 1e74918..79182a4 100644 --- a/installer/live/desktop/phoebus-assistant/shell.qml +++ b/installer/live/desktop/phoebus-assistant/shell.qml @@ -56,12 +56,9 @@ ShellRoot { shell.aiConfigured = !!result.ai_configured; shell.aiBackend = result.ai_backend || "direct"; shell.aiError = ""; + shell.activeAlerts = result.active_alerts || []; if (shell.currentTab === "updates") shell.checkUpdates(); - AssistantBridge.getProactiveAlerts(reply => { - if (reply.ok && reply.result) - shell.activeAlerts = reply.result.alerts || []; - }); AssistantBridge.getPreferences(reply => { if (reply.ok && reply.result) { shell.preferences = reply.result; @@ -76,6 +73,12 @@ ShellRoot { if (currentTab === "updates" && !shell.updateOverview && !shell.busy) { checkUpdates(); } + if (currentTab === "alerts") { + AssistantBridge.getProactiveAlerts(reply => { + if (reply.ok && reply.result) + shell.activeAlerts = reply.result.alerts || []; + }); + } } function refreshStatus() { @@ -150,6 +153,33 @@ ShellRoot { shell.conversation = list; } + function recordActivity(index, progress) { + const item = shell.conversation[index]; + if (!item || !progress || !progress.label) + return; + const activity = (item.data && item.data.activity ? item.data.activity : []).slice(); + const state = progress.state || "started"; + let position = -1; + if (state !== "started") { + for (let i = activity.length - 1; i >= 0; i--) { + if (activity[i].label === progress.label && activity[i].state === "started") { + position = i; + break; + } + } + } + const entry = { label: progress.label, state: state }; + if (position >= 0) + activity[position] = entry; + else + activity.push(entry); + shell.updateMessage(index, { activity: activity.slice(-30) }); + if (index === shell.conversation.length - 1) + Qt.callLater(() => chatList.positionViewAtEnd()); + if (state === "started") + shell.statusText = progress.label; + } + function submitPrompt(query) { if (shell.assistantPending || !query || query.trim().length === 0) return; @@ -157,7 +187,7 @@ ShellRoot { addMessage("user", q, null); const pendingIndex = addMessage("assistant", "Investigating your request. Checking available options can take several minutes.", - { kind: "progress", state: "running" }); + { kind: "progress", state: "running", activity: [] }); shell.assistantElapsedSeconds = 0; shell.assistantPending = true; shell.busy = true; @@ -166,15 +196,22 @@ ShellRoot { AssistantBridge.ask(q, null, reply => { shell.assistantPending = false; shell.busy = false; + const activity = (shell.conversation[pendingIndex].data || {}).activity || []; if (!reply.ok) { const detail = reply.error || "The assistant did not return a result."; - const message = detail.includes("proposal JSON is invalid") - ? "The connected model returned an invalid install plan. Nothing was installed. Try again, or use Legacy to choose an exact package and source." + const invalidModelStep = detail.includes("proposal JSON is invalid") + || detail.includes("invalid action JSON") + || detail.includes("change rejected: invalid action") + || detail.includes("change rejected: invalid application name") + || detail.includes("the investigation did not reach a valid proposal within"); + const message = invalidModelStep + ? "The connected model could not finish a valid install plan. Nothing was installed. Try again, specify a package source, or use Legacy to choose an exact package." : "Could not complete request: " + detail; shell.statusText = "Request failed"; finishMessage(pendingIndex, message, { kind: "error", - state: "error" + state: "error", + activity: activity }); return; } @@ -187,8 +224,8 @@ ShellRoot { } else { shell.statusText = "Ready"; } - finishMessage(pendingIndex, text, res); - }); + finishMessage(pendingIndex, text, Object.assign({}, res, { activity: activity })); + }, progress => shell.recordActivity(pendingIndex, progress)); } function executePlan(index) { @@ -222,7 +259,7 @@ ShellRoot { launch: r.launch || null }); refreshStatus(); - }); + }, progress => shell.recordActivity(index, progress)); } function cancelPlan(index) { @@ -282,7 +319,6 @@ ShellRoot { interval: 120 onTriggered: { if (shell.panelOpen) { - window.requestActivate(); promptField.forceActiveFocus(); } } @@ -547,6 +583,30 @@ ShellRoot { } } + ColumnLayout { + Layout.fillWidth: true + visible: !!(modelData.data && modelData.data.activity && modelData.data.activity.length) + spacing: 3 + + Label { + text: "sys activity" + color: Theme.muted + font.bold: true + font.pixelSize: 12 + } + + Repeater { + model: modelData.data && modelData.data.activity ? modelData.data.activity : [] + delegate: Label { + Layout.fillWidth: true + text: "[" + (modelData.state === "completed" ? "done" : modelData.state === "failed" ? "failed" : "running") + "] " + modelData.label + color: modelData.state === "failed" ? Theme.warning : modelData.state === "started" ? Theme.accent : Theme.muted + font.pixelSize: 12 + wrapMode: Text.Wrap + } + } + } + // Approval and cancellation for every plan type. RowLayout { Layout.fillWidth: true