feat(assistant): show sys activity and recover malformed plans
Some checks are pending
ci / test (push) Waiting to run

This commit is contained in:
Phoebus 2026-10-03 08:53:02 -07:00
parent 71dd1f6c5d
commit 259eccd11c
12 changed files with 552 additions and 61 deletions

View file

@ -39,7 +39,9 @@ installation or administrative logic:
- `sys --assistant-bridge` speaks newline-delimited JSON-RPC on stdin/stdout, - `sys --assistant-bridge` speaks newline-delimited JSON-RPC on stdin/stdout,
providing a uniform interface for the desktop assistant (`phoebus-assistant`) providing a uniform interface for the desktop assistant (`phoebus-assistant`)
for conversational interaction, legacy actions, unified updates, proactive alerts, 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 ### 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 its maintained source; builds before removing; Brave refused with its
reason) and `BuildTunedKernel { make_default }` (separate BLS entry, reason) and `BuildTunedKernel { make_default }` (separate BLS entry,
fallback kept, default only after a test boot). fallback kept, default only after a test boot).

View file

@ -5,6 +5,23 @@ this file is the curated, human-readable summary.
## Unreleased — Fast defaults with user-controlled source builds ## 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 <term> --legacy - **AppImage catalog search (2026-10-03).** `sys search <term> --legacy
--appimage` now combines managed images with matching leads from the --appimage` now combines managed images with matching leads from the
AppImage project's community feed. Results include readable descriptions AppImage project's community feed. Results include readable descriptions

View file

@ -3,6 +3,32 @@
Rolling note between work sessions. **Update this file before you finish**, then Rolling note between work sessions. **Update this file before you finish**, then
commit it. It should be short and current; use `git log` for detail. commit it. It should be short and current; use `git log` for detail.
- **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 community search (2026-10-03):** The previous `sys search`
AppImage lane showed only Phoebus-managed files. It now also reads the AppImage lane showed only Phoebus-managed files. It now also reads the
AppImage project's HTTPS community feed on the running system, ranks matching AppImage project's HTTPS community feed on the running system, ranks matching

View file

@ -48,6 +48,29 @@ disposable VM; `serial-driver.py recovery` now automates the same check.
## Matrix ## 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 <term> --legacy AppImage catalog discovery (2026-10-03): `sys search <term> --legacy
--appimage` searches managed images and the AppImage community feed on the --appimage` searches managed images and the AppImage community feed on the
running system. Remote matches are `catalog lead` entries with a catalog page running system. Remote matches are `catalog lead` entries with a catalog page

View file

@ -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; 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. long steps repeat their current label and elapsed time every ten seconds.
Progress never includes command arguments, command output, or credentials. Progress never includes command arguments, command output, or credentials.
Results remain on stdout. Broker JSON and the assistant's stdio protocol do Results remain on stdout. Broker JSON does not emit human progress. The
not emit human progress. Informational model answers are wrapped as prose and 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. omit the approval digest when no action is proposed.
> [!NOTE] > [!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 interface that delegates all logic to `sys --assistant-bridge`. The bridge runs
a stdio JSON-RPC server speaking newline-delimited JSON messages: 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. - `handshake`: validates client identity and checks active AI model connectivity.
- `ask`: submits a conversational request (`install firefox`, `why is audio broken?`) - `ask`: submits a conversational request (`install firefox`, `why is audio broken?`)
into the shared AI workflow, returning a reviewed plan card for install, into the shared AI workflow, returning a reviewed plan card for install,

View file

@ -358,13 +358,35 @@ pub fn investigate_install(
let mut chat = build_open_request(provider, model, facts, request); let mut chat = build_open_request(provider, model, facts, request);
let mut repeated: std::collections::BTreeMap<String, usize> = std::collections::BTreeMap::new(); let mut repeated: std::collections::BTreeMap<String, usize> = std::collections::BTreeMap::new();
let mut turns = 0usize; let mut turns = 0usize;
let mut malformed_replies = 0usize;
while turns < limits.max_turns { while turns < limits.max_turns {
turns += 1; turns += 1;
let body = messages_body(&chat)?; let body = messages_body(&chat)?;
let response = transport.send(provider, endpoint, &body)?; let response = transport.send(provider, endpoint, &body)?;
let content = extract_content(&response)?; 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 { match step {
InstallStep::Ask { question } => { InstallStep::Ask { question } => {
@ -754,4 +776,147 @@ mod tests {
.unwrap_err(); .unwrap_err();
assert!(matches!(err, AiError::ProviderUnavailable(_))); 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);
}
} }

View file

@ -84,6 +84,16 @@ fn now_unix() -> u64 {
/// Run deterministic checks against the system. Returns all currently detected alerts. /// Run deterministic checks against the system. Returns all currently detected alerts.
pub fn check_system(exec: &Exec, root: &Path) -> Vec<ProactiveAlert> { pub fn check_system(exec: &Exec, root: &Path) -> Vec<ProactiveAlert> {
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<ProactiveAlert> {
check_system_inner(exec, root, false)
}
fn check_system_inner(exec: &Exec, root: &Path, include_updates: bool) -> Vec<ProactiveAlert> {
let now = now_unix(); let now = now_unix();
let mut alerts = Vec::new(); let mut alerts = Vec::new();
@ -203,25 +213,27 @@ pub fn check_system(exec: &Exec, root: &Path) -> Vec<ProactiveAlert> {
} }
// 5. Updates ready for review check // 5. Updates ready for review check
let overview = check_unified_updates(exec, root); if include_updates {
if overview.total_updates() > 0 { let overview = check_unified_updates(exec, root);
alerts.push(ProactiveAlert { if overview.total_updates() > 0 {
id: format!("updates-{}", now), alerts.push(ProactiveAlert {
category: ProactiveCategory::UpdatesReady, id: format!("updates-{}", now),
title: format!("{} updates ready for review", overview.total_updates()), category: ProactiveCategory::UpdatesReady,
message: format!( title: format!("{} updates ready for review", overview.total_updates()),
"Updates available across package sources: {} Portage, {} Flatpak, {} Snap.", message: format!(
overview.updates_for(phoebus_core::selection::Backend::PortageBinary) "Updates available across package sources: {} Portage, {} Flatpak, {} Snap.",
+ overview.updates_for(phoebus_core::selection::Backend::PortageSource), overview.updates_for(phoebus_core::selection::Backend::PortageBinary)
overview.updates_for(phoebus_core::selection::Backend::Flatpak), + overview.updates_for(phoebus_core::selection::Backend::PortageSource),
overview.updates_for(phoebus_core::selection::Backend::Snap), overview.updates_for(phoebus_core::selection::Backend::Flatpak),
), overview.updates_for(phoebus_core::selection::Backend::Snap),
severity: "info".into(), ),
actionable: true, severity: "info".into(),
suggested_phrase: Some("Show me what needs updating".into()), actionable: true,
created_unix: now, suggested_phrase: Some("Show me what needs updating".into()),
fingerprint: format!("updates_ready:{}", overview.total_updates()), created_unix: now,
}); fingerprint: format!("updates_ready:{}", overview.total_updates()),
});
}
} }
alerts alerts
@ -235,6 +247,23 @@ pub fn active_alerts(
exec: &Exec, exec: &Exec,
root: &Path, root: &Path,
storage: &UserStorage, storage: &UserStorage,
) -> (Vec<ProactiveAlert>, ProactiveState) {
active_alerts_inner(exec, root, storage, true)
}
pub fn active_alerts_quick(
exec: &Exec,
root: &Path,
storage: &UserStorage,
) -> (Vec<ProactiveAlert>, ProactiveState) {
active_alerts_inner(exec, root, storage, false)
}
fn active_alerts_inner(
exec: &Exec,
root: &Path,
storage: &UserStorage,
include_updates: bool,
) -> (Vec<ProactiveAlert>, ProactiveState) { ) -> (Vec<ProactiveAlert>, ProactiveState) {
let now = now_unix(); let now = now_unix();
let mut state = load_state(storage, root); let mut state = load_state(storage, root);
@ -245,7 +274,11 @@ pub fn active_alerts(
return (Vec::new(), state); 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 let filtered = all
.into_iter() .into_iter()
.filter(|a| !state.is_dismissed(&a.fingerprint)) .filter(|a| !state.is_dismissed(&a.fingerprint))
@ -349,6 +382,18 @@ mod tests {
assert!(!state3.is_active(now_unix())); 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] #[test]
fn alert_state_is_isolated_per_user() { fn alert_state_is_isolated_per_user() {
let temp = tempdir().unwrap(); let temp = tempdir().unwrap();

View file

@ -6,13 +6,17 @@
use std::io::{BufRead, Write}; use std::io::{BufRead, Write};
use std::path::Path; use std::path::Path;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex};
use phoebus_ai::install::{Evidence, InstallSession}; 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::action::{parse_natural, SystemAction};
use phoebus_core::selection::Backend; use phoebus_core::selection::Backend;
use phoebus_core::{AiBackend, InstallConfig, Preferences}; use phoebus_core::{AiBackend, InstallConfig, Preferences};
use phoebus_executor::chooser; use phoebus_executor::chooser;
use phoebus_executor::exec::ProgressEvent;
use phoebus_executor::install::{AiInstall, InstallRequest}; use phoebus_executor::install::{AiInstall, InstallRequest};
use phoebus_executor::personal::UserStorage; use phoebus_executor::personal::UserStorage;
use phoebus_executor::proactive; use phoebus_executor::proactive;
@ -153,8 +157,14 @@ impl InstallSession for BridgeSession<'_> {
requests requests
.iter() .iter()
.map(|request| { .map(|request| {
let phase = self
.exec
.progress_phase(&format!("Checking {}", request.describe()));
let output = match actions::execute(self.exec, request, None, self.root) { 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}"), Err(e) => format!("investigation failed: {e}"),
}; };
Evidence { Evidence {
@ -187,7 +197,13 @@ fn with_bridge_ai<T>(
); );
} }
let transport = resolved.transport(exec).map_err(|e| e.to_string())?; 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); let facts = gather_facts(exec, root);
facts_phase.complete();
let progress_transport = ProgressTransport {
exec,
inner: transport.as_ref(),
};
let ai = AiInstall { let ai = AiInstall {
provider: resolved.provider, provider: resolved.provider,
endpoint: if resolved.backend == AiBackend::OpenCode { endpoint: if resolved.backend == AiBackend::OpenCode {
@ -200,12 +216,28 @@ fn with_bridge_ai<T>(
} else { } else {
resolved.model.clone() resolved.model.clone()
}, },
transport: transport.as_ref(), transport: &progress_transport,
limits: phoebus_ai::install::Limits::default(), limits: phoebus_ai::install::Limits::default(),
}; };
Ok(f(&ai, &facts)) 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 /// The shared, complete review card for any prepared plan. QML renders this
/// directly; administrative decisions stay in the service. /// directly; administrative decisions stay in the service.
fn plan_response(id: u64, kind: &str, plan: &PreparedPlan) -> BridgeResponse { fn plan_response(id: u64, kind: &str, plan: &PreparedPlan) -> BridgeResponse {
@ -250,7 +282,7 @@ pub fn handle_request(
"handshake" => { "handshake" => {
let ai_conf = load_installed_ai_config(root); let ai_conf = load_installed_ai_config(root);
let prefs = chooser::load_preferences(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 // Check reboot required deterministically without running expensive update checks
let reboot_req = root.join("run/reboot-required").exists() let reboot_req = root.join("run/reboot-required").exists()
|| root.join("var/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"), "ai_backend": ai_conf.as_ref().map(|c| c.backend.as_str()).unwrap_or("direct"),
"preferences": prefs, "preferences": prefs,
"active_alerts_count": alerts.len(), "active_alerts_count": alerts.len(),
"active_alerts": alerts,
"reboot_required": reboot_req, "reboot_required": reboot_req,
}), }),
) )
@ -550,13 +583,17 @@ fn plan_and_respond_install(
conv_path: &Path, conv_path: &Path,
) -> BridgeResponse { ) -> BridgeResponse {
if constrained_backend == Some(Backend::AppImage) { 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( return BridgeResponse::ok(
id, id,
json!({ json!({
"kind": "info", "kind": "info",
"state": "info", "state": "info",
"application": app, "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<String> {
} }
/// Run line-delimited JSON-RPC loop on stdio. /// Run line-delimited JSON-RPC loop on stdio.
pub fn run_stdio(exec: &Exec, root: &Path) -> std::result::Result<(), Box<dyn std::error::Error>> { pub fn run_stdio(exec: Exec, root: &Path) -> std::result::Result<(), Box<dyn std::error::Error>> {
let stdin = std::io::stdin(); let stdin = std::io::stdin();
let stdout = std::io::stdout(); let output_lock = Arc::new(Mutex::new(()));
let mut stdout_lock = stdout.lock(); 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(); let plans = PlanStore::for_current_user();
for line in stdin.lock().lines() { for line in stdin.lock().lines() {
@ -747,19 +796,67 @@ pub fn run_stdio(exec: &Exec, root: &Path) -> std::result::Result<(), Box<dyn st
Ok(r) => r, Ok(r) => r,
Err(e) => { Err(e) => {
let resp = BridgeResponse::err(0, format!("invalid JSON request: {e}")); let resp = BridgeResponse::err(0, format!("invalid JSON request: {e}"));
writeln!(stdout_lock, "{}", serde_json::to_string(&resp)?)?; write_protocol_line(&output_lock, &serde_json::to_string(&resp)?)?;
stdout_lock.flush()?;
continue; continue;
} }
}; };
let resp = handle_request(exec, root, &plans, req); active_id.store(req.id, Ordering::SeqCst);
writeln!(stdout_lock, "{}", serde_json::to_string(&resp)?)?; let request_phase = bridge_request_label(&req.op).map(|label| exec.progress_phase(label));
stdout_lock.flush()?; 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(()) 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)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
@ -944,6 +1041,7 @@ mod tests {
assert_eq!(resp.id, 1); assert_eq!(resp.id, 1);
let res = resp.result.unwrap(); let res = resp.result.unwrap();
assert_eq!(res["protocol_version"], ASSISTANT_PROTOCOL_VERSION); assert_eq!(res["protocol_version"], ASSISTANT_PROTOCOL_VERSION);
assert!(res["active_alerts"].is_array());
// Test history request // Test history request
let hist_req = BridgeRequest { let hist_req = BridgeRequest {

View file

@ -300,7 +300,7 @@ fn run() -> std::result::Result<(), Box<dyn std::error::Error>> {
// 1. Assistant Bridge // 1. Assistant Bridge
if cli.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 // 2. Broker execute plan

View file

@ -4,7 +4,8 @@
//! Deterministic operation is explicitly selected with `--legacy`. //! Deterministic operation is explicitly selected with `--legacy`.
//! JSON action entry points require `--legacy` or `--broker`. //! JSON action entry points require `--legacy` or `--broker`.
use std::process::Command; use std::io::Write;
use std::process::{Command, Stdio};
fn sys() -> Command { fn sys() -> Command {
Command::new(env!("CARGO_BIN_EXE_sys")) Command::new(env!("CARGO_BIN_EXE_sys"))
@ -19,6 +20,42 @@ fn effective_uid_is_root() -> bool {
.unwrap_or(false) .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<serde_json::Value> = 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] #[test]
fn natural_option_like_operand_is_rejected_in_legacy_mode() { fn natural_option_like_operand_is_rejected_in_legacy_mode() {
let out = sys() let out = sys()

View file

@ -43,10 +43,10 @@ Singleton {
proc.running = false; proc.running = false;
} }
function call(op, payload, onDone) { function call(op, payload, onDone, onProgress) {
const id = root.nextId++; const id = root.nextId++;
if (onDone) if (onDone)
root.pending[id] = onDone; root.pending[id] = { done: onDone, progress: onProgress || null };
const request = Object.assign({ id: id, op: op }, payload || {}); const request = Object.assign({ id: id, op: op }, payload || {});
const line = JSON.stringify(request) + "\n"; const line = JSON.stringify(request) + "\n";
if (!proc.running) { if (!proc.running) {
@ -71,9 +71,14 @@ Singleton {
return; return;
} }
if (msg.id !== undefined && root.pending[msg.id]) { 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]; delete root.pending[msg.id];
cb(msg); callback.done(msg);
} }
} }
@ -88,12 +93,12 @@ Singleton {
}); });
} }
function ask(query, backend, cb) { function ask(query, backend, cb, onProgress) {
call("ask", { request: query, backend: backend }, cb); call("ask", { request: query, backend: backend }, cb, onProgress);
} }
function execute(planId, digest, yes, cb) { function execute(planId, digest, yes, cb, onProgress) {
call("execute", { plan_id: planId, digest: digest, yes: yes }, cb); call("execute", { plan_id: planId, digest: digest, yes: yes }, cb, onProgress);
} }
function legacyInstall(application, backend, cb) { function legacyInstall(application, backend, cb) {
@ -160,7 +165,7 @@ Singleton {
const cb = root.pending[ids[i]]; const cb = root.pending[ids[i]];
delete root.pending[ids[i]]; delete root.pending[ids[i]];
try { try {
cb({ ok: false, error: "The assistant bridge stopped (exit " + exitCode + ")." }); cb.done({ ok: false, error: "The assistant bridge stopped (exit " + exitCode + ")." });
} catch (e) {} } catch (e) {}
} }
} }

View file

@ -56,12 +56,9 @@ ShellRoot {
shell.aiConfigured = !!result.ai_configured; shell.aiConfigured = !!result.ai_configured;
shell.aiBackend = result.ai_backend || "direct"; shell.aiBackend = result.ai_backend || "direct";
shell.aiError = ""; shell.aiError = "";
shell.activeAlerts = result.active_alerts || [];
if (shell.currentTab === "updates") if (shell.currentTab === "updates")
shell.checkUpdates(); shell.checkUpdates();
AssistantBridge.getProactiveAlerts(reply => {
if (reply.ok && reply.result)
shell.activeAlerts = reply.result.alerts || [];
});
AssistantBridge.getPreferences(reply => { AssistantBridge.getPreferences(reply => {
if (reply.ok && reply.result) { if (reply.ok && reply.result) {
shell.preferences = reply.result; shell.preferences = reply.result;
@ -76,6 +73,12 @@ ShellRoot {
if (currentTab === "updates" && !shell.updateOverview && !shell.busy) { if (currentTab === "updates" && !shell.updateOverview && !shell.busy) {
checkUpdates(); checkUpdates();
} }
if (currentTab === "alerts") {
AssistantBridge.getProactiveAlerts(reply => {
if (reply.ok && reply.result)
shell.activeAlerts = reply.result.alerts || [];
});
}
} }
function refreshStatus() { function refreshStatus() {
@ -150,6 +153,33 @@ ShellRoot {
shell.conversation = list; 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) { function submitPrompt(query) {
if (shell.assistantPending || !query || query.trim().length === 0) if (shell.assistantPending || !query || query.trim().length === 0)
return; return;
@ -157,7 +187,7 @@ ShellRoot {
addMessage("user", q, null); addMessage("user", q, null);
const pendingIndex = addMessage("assistant", const pendingIndex = addMessage("assistant",
"Investigating your request. Checking available options can take several minutes.", "Investigating your request. Checking available options can take several minutes.",
{ kind: "progress", state: "running" }); { kind: "progress", state: "running", activity: [] });
shell.assistantElapsedSeconds = 0; shell.assistantElapsedSeconds = 0;
shell.assistantPending = true; shell.assistantPending = true;
shell.busy = true; shell.busy = true;
@ -166,15 +196,22 @@ ShellRoot {
AssistantBridge.ask(q, null, reply => { AssistantBridge.ask(q, null, reply => {
shell.assistantPending = false; shell.assistantPending = false;
shell.busy = false; shell.busy = false;
const activity = (shell.conversation[pendingIndex].data || {}).activity || [];
if (!reply.ok) { if (!reply.ok) {
const detail = reply.error || "The assistant did not return a result."; const detail = reply.error || "The assistant did not return a result.";
const message = detail.includes("proposal JSON is invalid") const invalidModelStep = 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." || 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; : "Could not complete request: " + detail;
shell.statusText = "Request failed"; shell.statusText = "Request failed";
finishMessage(pendingIndex, message, { finishMessage(pendingIndex, message, {
kind: "error", kind: "error",
state: "error" state: "error",
activity: activity
}); });
return; return;
} }
@ -187,8 +224,8 @@ ShellRoot {
} else { } else {
shell.statusText = "Ready"; shell.statusText = "Ready";
} }
finishMessage(pendingIndex, text, res); finishMessage(pendingIndex, text, Object.assign({}, res, { activity: activity }));
}); }, progress => shell.recordActivity(pendingIndex, progress));
} }
function executePlan(index) { function executePlan(index) {
@ -222,7 +259,7 @@ ShellRoot {
launch: r.launch || null launch: r.launch || null
}); });
refreshStatus(); refreshStatus();
}); }, progress => shell.recordActivity(index, progress));
} }
function cancelPlan(index) { function cancelPlan(index) {
@ -282,7 +319,6 @@ ShellRoot {
interval: 120 interval: 120
onTriggered: { onTriggered: {
if (shell.panelOpen) { if (shell.panelOpen) {
window.requestActivate();
promptField.forceActiveFocus(); 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. // Approval and cancellation for every plan type.
RowLayout { RowLayout {
Layout.fillWidth: true Layout.fillWidth: true