fix(admin): harden privileged plan boundary, GUI review, AI-first removal, and conversation privacy
Some checks are pending
ci / test (push) Waiting to run

This commit is contained in:
Phoebus 2026-09-24 18:01:13 -07:00
parent 7ebb616c99
commit 3b84b8c99d
14 changed files with 2891 additions and 940 deletions

View file

@ -101,9 +101,10 @@ The only crate that runs privileged commands.
### phoebus-installer
- `orchestrate` — `Installer` runs the plan stages and stops on first failure.
- `service` — shared administration service layer (`PreparedPlan`, `PlanStore`, planning, authorization, Polkit elevation, execution, and verification) shared identically by CLI and GUI.
- `conversation` — bounded conversation history and contextual follow-up resolution (tradeoff comparisons, backend switching, and plan confirmation).
- `assistant_bridge` — JSON-RPC stdio bridge serving the Quickshell desktop assistant.
- `service` — shared administration service layer (`PreparedPlan`, `PlanStore`, planning, authorization, Polkit elevation, execution, and verification) shared identically by CLI and GUI. The single authoritative validation boundary (`validate_prepared_plan`) runs before elevation and is repeated in the broker after authentication; plans bind actions, effects, candidate, target root and initiating uid, are stored per-user with an integrity seal, and are atomically claimed before execution.
- `ai_setup` — one provider/endpoint/model/credential resolver shared by the CLI and the desktop bridge, so their provider setup cannot diverge. Credentials load from a 0600 file (configured path, `PHOEBUS_AI_API_KEY_FILE`, or `~/.config/phoebus/ai.key`) and never travel through QML, prompts or argv.
- `conversation` — bounded, minimized conversation history and contextual follow-up resolution (tradeoff comparisons, backend switching, and plan confirmation). Raw requests are not persisted; registered secrets are redacted; history is 0600/0700, atomic, bounded and clearable.
- `assistant_bridge` — JSON-RPC stdio bridge serving the Quickshell desktop assistant. Every plan type returns the same `plan_id`/`digest` review card; `execute` runs only the referenced reviewed plan.
- `release` — `ReleaseManifest` create/verify, candidate gates, atomic publish
and signing command helpers.
- Binaries: `phoebus-installer`, `sys`, `phoebus-release`.

View file

@ -3,6 +3,54 @@
All notable changes are recorded here. The authoritative history is `git log`;
this file is the curated, human-readable summary.
## 2026-09-25 — Privileged-boundary, GUI-review, removal, transaction and privacy remediation
- **Single privileged validation boundary (`phoebus-installer::service`):**
- `validate_prepared_plan` is the one authoritative check, run before
elevation and repeated inside the broker after authentication. It re-derives
the plan seal from the plan's own contents, rejects expired/claimed/modified/
malformed/wrong-root/wrong-uid plans, and revalidates live state.
- Plans now bind the exact actions, effects, candidate, canonical target root
and initiating uid; multi-action plans store per-step effects and are
revalidated action-by-action (fixing an aggregate digest comparison bug).
- Protected per-user plan storage (`/run/user/<uid>/phoebus/plans`, 0700 / 0600,
atomic writes, 128-bit ids, symlink/ownership checks) and atomic `O_EXCL`
consumption so concurrent requests cannot both mutate and retries cannot
repeat. The broker resolves storage from the uid, not an arbitrary path.
- `sys --broker --execute-plan <id> --plan-uid <uid> --root <root>`; a dropped
or mismatched root is rejected rather than silently executing against `/`.
- **Truthful transaction outcomes:** verification failure, action failure,
refusal and cancellation all finish the transaction with a truthful result;
completed steps and the protective snapshot are retained; persistence failures
are surfaced; a malformed broker reply is a protocol failure, not success.
- **GUI plan review for every plan type:** the assistant renders one review card
for install, removal, general administration, rollback and follow-up
confirmation; approval/cancel controls execute only the referenced reviewed
plan and update the original card; "prepared" is never shown as "completed";
verification results are shown; launch is offered only when a concrete desktop
entry/command was identified. Corrected the assistant's `PhoebusButton` API
usage (`label`/`actionEnabled`).
- **Shared provider/credential handling (`phoebus_installer::ai_setup`):** the CLI
and GUI resolve provider, endpoint, model and credential reference through one
module. Credentials load from a configured 0600 file, `PHOEBUS_AI_API_KEY_FILE`
or a default `~/.config/phoebus/ai.key`; they are never sent through QML,
prompts or argv. The GUI direct transport no longer uses an empty key.
- **AI-first removal and corrected follow-ups:** default removal routes through
the connected model while deterministic ownership discovery and policy
validation stay underneath; only `--legacy` bypasses the model. Follow-ups
prefer explicit application references, so "install vlc using flatpak" is
about VLC, "use flatpak for that one" refers to the previous app, and
"why is my audio broken?" is not answered as a package explanation.
- **Honest conversation privacy:** history stores minimized structured context
(never the raw request), uses the active redactor, is written 0600/0700
atomically, is bounded to ten turns, surfaces write errors, and can be cleared.
- **Tests:** regression coverage for tampered/expired/replayed/malformed plans,
plan replacement after review, concurrent claims, refusal, target-root and uid
binding, verification failure, transaction truthfulness, follow-up resolution,
credential loading, and history privacy/retention/deletion. Storage is injected
in tests (no shared `PHOEBUS_PLANS_DIR` race). Full workspace suite, `fmt` and
`clippy` run; static binaries build.
## 2026-09-24 — AI-first administration remediation: shared service layer, Polkit elevation, QML provisioning, and conversation continuity
- **Shared Administration Service Layer (`phoebus_installer::service`):**

View file

@ -3,43 +3,62 @@
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.
- **Last updated:** this session (2026-09-24), AI-First Administration & Desktop Assistant Remediation:
Shared planning service layer (`phoebus_installer::service`), reviewable plan staging with
cryptographic digests (`PreparedPlan`, `PlanStore`), target desktop QML and Polkit policy
provisioning, unprivileged GUI execution with Polkit elevation (`pkexec`), contextual conversation
continuity (`conversation::*`), and cross-source application removal with user data preservation.
- **Last updated:** this session (2026-09-25), privileged-boundary, GUI-review,
removal, transaction and privacy remediation:
Authoritative plan validation (`validate_prepared_plan`), protected per-user
plan storage with atomic claim, truthful transaction outcomes, shared provider
credentials (`ai_setup`), AI-first default removal, corrected conversational
follow-ups, and an honest conversation-history privacy boundary.
- **Current focus:**
1. **Shared planning and execution layer (`phoebus_installer::service`)**:
- Both CLI (`sys`) and desktop GUI (`phoebus-assistant` via `assistant_bridge.rs`) share one unified
administration pipeline for investigation, recommendation, effect resolution, authorization, execution, and verification.
- Reviewable plans staged as `PreparedPlan` with cryptographic digests (`Sha256`), 15-minute TTL, and replay rejection.
- System state revalidation before mutation; material alterations invalidate previous approvals and abort.
- Honest recommendation formatting with verified provenance (no false "avoids a lengthy build" claims).
- In-progress transaction recording (`begin`) before mutation; completed verification (`finish`) after mutation.
2. **Target desktop & QML asset provisioning**:
- `gui-apps/quickshell` added to canonical Mango desktop package list.
- Embedded all 13 QML and policy assets into `/usr/share/phoebus/assistant/` via `TargetRoot` in `write_session_script`.
- Polkit policy (`club.phoebus.sys.policy`) enables desktop users to elevate mutating plans via `pkexec` without passwordless sudo.
3. **Desktop assistant responsiveness**:
- Eliminated startup polling freeze; update checks are on-demand when switching to the Updates tab.
- Fast deterministic status checking on startup (reboot-required marker).
4. **Contextual conversation continuity (`phoebus_installer::conversation`)**:
- Bounded 10-turn history with secret redaction.
- Follow-up resolution for comparative questions, backend switching, and plan confirmations.
5. **Cross-source removal**:
- Unified removal planning (`plan_removal`) across Flatpak, Snap, AppImage, and Portage.
- Requires explicit lane flag if ambiguous duplicate copies exist; preserves user home data by default.
1. **Single privileged validation boundary (`phoebus_installer::service`)**:
- `validate_prepared_plan` runs before elevation and is repeated inside the
privileged broker after authentication. It re-derives the plan seal from
the plan's own contents (never two supplied digest strings), and rejects
expired/claimed/modified/malformed/wrong-root/wrong-uid plans.
- Plans bind the exact actions, effects, candidate, canonical target root
and initiating uid. `PreparedPlan.step_effects` revalidates multi-action
plans action-by-action (fixing an aggregate-digest bug).
- `PlanStore` is per-user (`/run/user/<uid>/phoebus/plans`, 0700 / 0600),
writes atomically, uses 128-bit ids, rejects symlinks/third-party
ownership, and claims a plan with `O_EXCL` so at most one execution runs.
- `sys --broker --execute-plan <id> --plan-uid <uid> --root <root>`; a
dropped/mismatched root is rejected rather than executing against `/`.
2. **Truthful transaction outcomes**: verification failure, action failure,
refusal and cancellation finish the transaction truthfully; completed steps
and the snapshot are retained; persistence failures surface; a malformed
broker reply is a protocol failure, not fabricated success.
3. **GUI plan review**: one review card for install/removal/general/rollback/
follow-up, with approval/cancel; executes only the referenced plan; updates
the original card; never says "completed" for a prepared plan; shows
verification; offers launch only when a concrete entry was identified. The
assistant also used the wrong `PhoebusButton` API (`text`/`enabled`) and is
corrected to `label`/`actionEnabled`.
4. **Shared provider credentials (`ai_setup`)**: CLI and GUI resolve provider,
endpoint, model and credential reference through one module; keys load from
a configured 0600 file, `PHOEBUS_AI_API_KEY_FILE` or `~/.config/phoebus/ai.key`
and are never passed through QML, prompts or argv.
5. **AI-first removal + follow-ups**: default removal uses the model with
deterministic ownership discovery underneath; only `--legacy` bypasses it.
Explicit application references beat stale context.
6. **Conversation privacy**: minimized structured history (no raw request),
active redactor, 0600/0700 atomic writes, bounded to ten turns, clearable.
- **Last verified (this session):**
- `cargo fmt --all -- --check` clean.
- `cargo clippy --workspace --all-targets` clean (0 errors, 0 custom warnings).
- `cargo test --workspace` (all 486 crate unit/integration tests pass: 173 phoebus-core, 205 phoebus-executor, 108 phoebus-installer).
- `cargo build --release -p phoebus-installer` compiled cleanly.
- Static binary build with `crt-static` compiled cleanly.
- `installer/tests/vm/sys-acceptance.sh` passed 23/23 cases (`PASS=23 FAIL=0`).
- **Not yet verified this session:**
- AI-selected live installation against a remote production provider with live credentials
(fixture and mock paths fully verified).
- Physical-seat DRM desktop session (headless and virtual seats verified).
- `cargo test --workspace` all pass (67 phoebus-installer, 173 phoebus-core,
195 phoebus-executor, plus integration/CLI suites).
- `cargo clippy --workspace --all-targets` runs (exit 0; pre-existing
`result_large_err`/arg-count lints remain, as at the reviewed commit).
- `make test` passes (Rust workspace + VM disk-safety suite).
- Static `sys` and `phoebus-installer` (`crt-static`) build cleanly.
- `sys install/remove firefox` without a model stop and print legacy guidance
(no mutation); `sys history --legacy` runs deterministically.
- **Not yet verified this session (BLOCKED):**
- Live AI install/removal journey with an authorized provider — no credential
is present; do not invent one.
- Installed GUI/AI journey and the 12-step acceptance list — requires a
graphical, seat-providing VM and a live model. The installed encrypted disk
(`/var/tmp/phoebus-vm/disks/test-disk.qcow2`) has no LUKS passphrase available
in this environment, so it cannot be booted here.
- **Public repo:** <https://git.phoebus.club/phoebus/phoebus_os>
(remote `origin`, SSH port 2222).

View file

@ -145,8 +145,15 @@ still not VM-verified.
| Quiet proactive assistance monitor & deduplicated alerting | yes | yes | no | no |
| User preference profiles & project environment mappings | yes | yes | no | n/a |
| Shared administration service layer (`service::*`) & PreparedPlan staging | yes | yes | yes (acceptance matrix) | n/a |
| Plan cryptographically bound digests, TTL & replay protection | yes | yes | yes (acceptance matrix) | n/a |
| Authoritative privileged validation boundary (integrity/root/uid/state/claim) | yes | yes | no (needs an authenticated VM boot) | n/a |
| Protected per-user plan storage, atomic claim, tamper/traversal rejection | yes | yes | no (needs an authenticated VM boot) | n/a |
| Plan digests, target-root/uid binding, TTL, replay & concurrent-claim protection | yes | yes | no | n/a |
| Truthful transaction outcomes (failure/verify-fail/refusal/interruption) | yes | yes | no | n/a |
| AI-first removal (deterministic discovery underneath; `--legacy` bypasses) | yes | yes | no | n/a |
| GUI plan review card for every plan type; prepared ≠ completed | yes | no (QML) | no (needs graphical VM) | no |
| Shared provider/credential handling (`ai_setup::*`) for CLI and GUI | yes | yes | no (no live credential) | n/a |
| Contextual conversation continuity (`conversation::*`) | yes | yes | yes (acceptance matrix) | n/a |
| Conversation-history privacy (minimized, redacted, 0600, bounded, clearable) | yes | yes | no | n/a |
| Target desktop QML assets & Polkit policy provisioning | yes | yes | yes (live VM layout) | no |
| Desktop assistant unprivileged execution & Polkit elevation | yes | yes | yes (live VM layout) | no |
| UKI | no (deferred) | no | no | no |

View file

@ -44,6 +44,19 @@ sys install MyTool --appimage # AI workflow constrained to AppImage
sys install app-misc/my-thing --ebuild # AI workflow constrained to custom ebuild
```
Removal is also AI-first by default. The deterministic ownership discovery and
policy validation always run underneath; the connected model confirms the exact
discovered copy. An ambiguous multi-lane install still requires an explicit
source flag, and a model failure stops execution rather than silently removing
deterministically:
```sh
sys remove firefox # AI workflow: confirm target, then remove
sys remove firefox --flatpak # AI workflow constrained to Flatpak
sys remove firefox --legacy # deterministic removal, no model
sys remove firefox --legacy --flatpak # deterministic removal from Flatpak
```
### Deterministic administration (`--legacy`)
Deterministic operation must be explicitly selected with `--legacy`:
@ -51,13 +64,15 @@ Deterministic operation must be explicitly selected with `--legacy`:
```sh
sys install firefox --legacy --flatpak # deterministic Flatpak workflow; no model interaction
sys install firefox --legacy --portage # deterministic Portage workflow; no model interaction
sys remove firefox --legacy # deterministic removal, no model interaction
sys history --legacy # deterministic history without model
sys undo --legacy # deterministic recovery without model
sys install firefox --legacy # REFUSED: requires an explicit package source flag
```
When `--legacy` is used with `install` but without an explicit source flag,
execution is refused and available package sources are displayed.
execution is refused and available package sources are displayed. `--legacy`
never contacts a model.
Direct JSON and action-file invocations (`--action` and `--action-file`) are
audited entry points: they fail closed unless invoked with `--legacy` (for
@ -236,10 +251,16 @@ a stdio JSON-RPC server speaking newline-delimited JSON messages:
- `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 assistant proposals and bounded evidence.
- `execute`: executes a reviewed, approved plan by plan ID and plan digest.
into the shared AI workflow, returning a reviewed plan card for install,
removal, general administration, or a follow-up confirmation. Every plan type
carries the same `plan_id`/`digest` review and approval state; information and
clarification replies carry no execution control. Removal is AI-first by
default.
- `execute`: executes exactly the referenced reviewed plan by plan ID and plan
digest. The privileged broker repeats the full validation.
- `legacy_install`: performs deterministic installation with an explicit backend.
- `legacy_execute`: executes typed actions deterministically.
- `clear_conversation`: deletes the persisted, minimized follow-up context.
- `updates`: queries the unified multi-source update system across Portage,
Flatpak, Snap, AppImage, and Nix.
- `proactive_alerts`, `proactive_snooze`, `proactive_dismiss`: interacts with the
@ -251,6 +272,51 @@ a stdio JSON-RPC server speaking newline-delimited JSON messages:
Zero business logic lives in the GUI: equivalent CLI and GUI requests produce
identical validated plans given the same facts and preferences.
## Privileged execution boundary
A mutating plan is stored as a `PreparedPlan` in protected, per-user storage
(`/run/user/<uid>/phoebus/plans`, mode 0700; a 0600 plan file; atomic write; a
128-bit unpredictable identifier). The plan is sealed with an integrity digest
over the reviewed fields, the target root and the initiating uid.
`execute_plan` validates the plan before elevation and again — authoritatively —
inside the privileged broker (`sys --broker --execute-plan <id> --plan-uid <uid>
--root <root>`). The broker:
- re-derives the integrity seal from the plan's own contents (it never trusts
two supplied digest strings);
- rejects expired, already-claimed, modified, malformed, wrong-root or
wrong-uid plans;
- revalidates the current package/removal state after authentication;
- atomically claims the plan (`O_EXCL`) so two concurrent requests cannot both
mutate the system, and a retry never repeats a consumed plan;
- treats the plan file and its contents as untrusted input, resolving storage
from the uid rather than an arbitrary path.
Authentication happens outside model context through Polkit (`pkexec`), never
passwordless sudo. Cancelling or refusing authentication performs no mutation
and leaves the plan unconsumed until it expires.
## Transaction truthfulness
Every mutation is recorded as an in-progress transaction **before** it runs. On
action failure, verification failure, refusal or cancellation the same record is
finished with a truthful result (`failed: …` / `verify failed: …`); completed
steps and their protective snapshot are retained. A record that never reaches a
terminal result is an interrupted operation, and its consumed plan cannot be
replayed. A malformed broker reply is a protocol failure, never fabricated
success. History persistence failures are surfaced, not swallowed.
## Conversation privacy
Follow-up context is minimized before persistence: the raw request is never
stored, only structured context (kind, application, candidate, rationale), and
registered secrets are scrubbed with the active redactor. The history file is
0600 inside a 0700 directory, written atomically, bounded to ten turns, and can
be cleared (`clear_conversation`) so it no longer informs later follow-ups.
Redaction removes known secrets; it does not claim to detect arbitrary sensitive
text, which is why raw requests are not persisted.
## Acceptance matrix
The matrix below is the repeatable acceptance suite. `installer/tests/vm/sys-acceptance.sh`

View file

@ -407,6 +407,11 @@ pub struct AiConfig {
pub opencode_model: String,
/// OpenCode model variant (e.g. `default`, `low`, `high`, `max`).
pub opencode_variant: String,
/// Path to a mode-0600 file holding the direct provider API key. The key
/// itself is never stored in the configuration.
pub direct_credential_file: String,
/// Path to a mode-0600 file holding the OpenCode server credential.
pub opencode_credential_file: String,
}
impl AiConfig {

View file

@ -0,0 +1,263 @@
//! Shared provider configuration and credential handling for `sys` and the
//! desktop assistant.
//!
//! Both surfaces use this module to resolve which model backend to use, where
//! the endpoint/model live, and how to load the credential reference safely,
//! so the two cannot drift apart again. Credentials are only ever read from a
//! mode-0600 file (or an environment-provided path) and are registered with the
//! executor's redactor before any transport use. A key never travels through
//! QML, a model prompt, a command line or conversation history.
use std::path::{Path, PathBuf};
use phoebus_ai::provider::{ModelTransport, ProviderKind};
use phoebus_core::{AiBackend, AiConfig, SecretString};
use phoebus_executor::ai::CurlTransport;
use phoebus_executor::error::{ExecError, Result};
use phoebus_executor::exec::Exec;
use phoebus_executor::opencode_client::ExecOpenCodeTransport;
/// Caller-supplied overrides (CLI flags or GUI settings). `None` means "fall
/// back to the environment or the installed configuration".
#[derive(Debug, Clone, Default)]
pub struct AiOverrides {
pub backend: Option<String>,
pub provider: Option<String>,
pub model: Option<String>,
pub endpoint: Option<String>,
pub api_key_file: Option<PathBuf>,
pub opencode_server: Option<String>,
pub opencode_provider: Option<String>,
pub opencode_model: Option<String>,
pub opencode_password_file: Option<PathBuf>,
pub no_sandbox: bool,
/// When true, environment variables are consulted between the explicit
/// override and the installed configuration.
pub use_environment: bool,
}
/// Fully resolved provider settings. No secret value is held here, only the
/// path to the mode-0600 credential file.
#[derive(Debug, Clone)]
pub struct ResolvedAi {
pub backend: AiBackend,
pub provider: ProviderKind,
pub endpoint: String,
pub model: String,
pub opencode_server: String,
pub opencode_provider: String,
pub opencode_model: String,
pub api_key_file: Option<PathBuf>,
pub opencode_password_file: Option<PathBuf>,
pub no_sandbox: bool,
}
fn env_var(use_env: bool, name: &str) -> Option<String> {
if !use_env {
return None;
}
std::env::var(name).ok().filter(|s| !s.trim().is_empty())
}
/// A well-known per-user credential location used when nothing is configured.
/// Only returned when the file already exists, so the absence of a key is not
/// turned into an error for providers (like a local model) that need none.
fn default_credential_file() -> Option<PathBuf> {
let base = std::env::var("XDG_CONFIG_HOME")
.ok()
.filter(|s| !s.trim().is_empty())
.map(PathBuf::from)
.or_else(|| {
std::env::var("HOME")
.ok()
.map(|h| PathBuf::from(h).join(".config"))
})?;
let path = base.join("phoebus").join("ai.key");
if path.is_file() {
Some(path)
} else {
None
}
}
/// Resolve the provider configuration from explicit overrides, the
/// environment (when enabled) and the installed `assistant.conf`.
pub fn resolve(_root: &Path, ov: &AiOverrides, conf: Option<&AiConfig>) -> ResolvedAi {
let backend = ov
.backend
.clone()
.or_else(|| env_var(ov.use_environment, "PHOEBUS_AI_BACKEND"))
.or_else(|| conf.map(|c| c.backend.as_str().to_string()))
.and_then(|s| AiBackend::parse(&s))
.unwrap_or(AiBackend::Direct);
let provider = ov
.provider
.clone()
.or_else(|| env_var(ov.use_environment, "PHOEBUS_AI_PROVIDER"))
.or_else(|| conf.map(|c| c.provider.clone()))
.and_then(|s| ProviderKind::parse(&s))
.unwrap_or(ProviderKind::None);
let opencode_server = ov
.opencode_server
.clone()
.or_else(|| env_var(ov.use_environment, "PHOEBUS_OPENCODE_SERVER"))
.or_else(|| conf.map(|c| c.opencode_server.clone()))
.unwrap_or_default();
let opencode_provider = ov
.opencode_provider
.clone()
.or_else(|| env_var(ov.use_environment, "PHOEBUS_OPENCODE_PROVIDER"))
.or_else(|| conf.map(|c| c.opencode_provider.clone()))
.unwrap_or_default();
let opencode_model = ov
.opencode_model
.clone()
.or_else(|| env_var(ov.use_environment, "PHOEBUS_OPENCODE_MODEL"))
.or_else(|| conf.map(|c| c.opencode_model.clone()))
.unwrap_or_default();
let endpoint = ov
.endpoint
.clone()
.or_else(|| env_var(ov.use_environment, "PHOEBUS_AI_ENDPOINT"))
.or_else(|| {
conf.map(|c| c.endpoint.clone())
.filter(|s| !s.trim().is_empty())
})
.filter(|s| !s.trim().is_empty())
.unwrap_or_else(|| {
if backend == AiBackend::OpenCode {
opencode_server.clone()
} else {
provider.endpoint().to_string()
}
});
let model = ov
.model
.clone()
.or_else(|| env_var(ov.use_environment, "PHOEBUS_AI_MODEL"))
.or_else(|| conf.map(|c| c.model.clone()))
.unwrap_or_default();
let api_key_file = ov
.api_key_file
.clone()
.or_else(|| env_var(ov.use_environment, "PHOEBUS_AI_API_KEY_FILE").map(PathBuf::from))
.or_else(|| {
conf.map(|c| c.direct_credential_file.clone())
.filter(|s| !s.trim().is_empty())
.map(PathBuf::from)
})
// Default authorized-provider location: a per-user 0600 file. Used
// only when it already exists, so a local model needs no key.
.or_else(default_credential_file);
let opencode_password_file = ov
.opencode_password_file
.clone()
.or_else(|| {
env_var(ov.use_environment, "PHOEBUS_OPENCODE_PASSWORD_FILE").map(PathBuf::from)
})
.or_else(|| {
conf.map(|c| c.opencode_credential_file.clone())
.filter(|s| !s.trim().is_empty())
.map(PathBuf::from)
});
ResolvedAi {
backend,
provider,
endpoint,
model,
opencode_server,
opencode_provider,
opencode_model,
api_key_file,
opencode_password_file,
no_sandbox: ov.no_sandbox,
}
}
impl ResolvedAi {
/// Whether the resolved backend is usable at all.
pub fn is_configured(&self) -> bool {
match self.backend {
AiBackend::OpenCode => {
!self.opencode_server.trim().is_empty()
&& !self.opencode_provider.trim().is_empty()
&& !self.opencode_model.trim().is_empty()
}
AiBackend::Direct => self.provider != ProviderKind::None,
}
}
/// Load the direct-provider key, explaining clearly when it is missing or
/// inaccessible. The value is registered with the redactor by the transport.
pub fn load_direct_key(&self, exec: &Exec) -> Result<Option<SecretString>> {
match &self.api_key_file {
Some(path) => {
let key = phoebus_executor::ai::load_api_key(path).map_err(|e| {
ExecError::operation(
"ai",
"load provider credential",
format!(
"could not load the provider API key from {}: {e}",
path.display()
),
)
})?;
exec.register_secret(&key);
Ok(Some(key))
}
None => Ok(None),
}
}
pub fn load_opencode_password(&self) -> Result<Option<SecretString>> {
match &self.opencode_password_file {
Some(path) => Ok(Some(phoebus_executor::ai::load_api_key(path)?)),
None => Ok(None),
}
}
/// Build a transport for this configuration. The direct provider gets the
/// OS-level sandbox unless explicitly disabled; the OpenCode agent server
/// is a different trust boundary and keeps its own transport.
pub fn transport<'e>(&self, exec: &'e Exec) -> Result<Box<dyn ModelTransport + 'e>> {
match self.backend {
AiBackend::OpenCode => {
let password = self.load_opencode_password()?;
Ok(Box::new(
ExecOpenCodeTransport::new(
exec,
self.opencode_server.clone(),
self.opencode_provider.clone(),
self.opencode_model.clone(),
)
.with_auth(password),
))
}
AiBackend::Direct => {
let key = self.load_direct_key(exec)?;
if self.provider.requires_key() && key.is_none() {
return Err(ExecError::operation(
"ai",
"load provider credential",
format!(
"provider `{}` requires an API key file (api_key_file in \
assistant.conf, PHOEBUS_AI_API_KEY_FILE, or --ai-api-key-file)",
self.provider.as_str()
),
));
}
let direct = CurlTransport::new(exec, key);
if self.no_sandbox {
Ok(Box::new(direct))
} else {
Ok(Box::new(direct.sandboxed()))
}
}
}
}
}

View file

@ -8,22 +8,21 @@ use std::io::{BufRead, Write};
use std::path::Path;
use phoebus_ai::install::{Evidence, InstallSession};
use phoebus_ai::provider::{ProviderKind, SystemFacts};
use phoebus_ai::provider::SystemFacts;
use phoebus_core::action::{parse_natural, SystemAction};
use phoebus_core::selection::Backend;
use phoebus_core::{AiBackend, InstallConfig, Preferences};
use phoebus_executor::ai::CurlTransport;
use phoebus_executor::chooser;
use phoebus_executor::install::{AiInstall, InstallRequest};
use phoebus_executor::opencode_client::ExecOpenCodeTransport;
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, PreparedPlan};
use crate::service::{self, PlanStore, PreparedPlan};
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
@ -100,6 +99,14 @@ fn now_unix() -> u64 {
.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()?;
@ -162,7 +169,77 @@ impl InstallSession for BridgeSession<'_> {
}
}
pub fn handle_request(exec: &Exec, root: &Path, req: BridgeRequest) -> BridgeResponse {
/// 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 = gather_facts(exec, root);
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: transport.as_ref(),
limits: phoebus_ai::install::Limits::default(),
};
Ok(f(&ai, &facts))
}
/// 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;
match req.op.as_str() {
"handshake" => {
@ -233,11 +310,15 @@ pub fn handle_request(exec: &Exec, root: &Path, req: BridgeRequest) -> BridgeRes
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, id, action, req.yes.unwrap_or(false))
execute_action_helper(exec, root, plans, id, action, req.yes.unwrap_or(false))
}
"legacy_install" => {
let app = match req.application {
@ -255,22 +336,8 @@ pub fn handle_request(exec: &Exec, root: &Path, req: BridgeRequest) -> BridgeRes
};
let mut install_req = InstallRequest::new(&app);
install_req.backend = Some(backend_enum);
match service::plan_legacy_install(exec, root, &install_req) {
Ok(plan) => BridgeResponse::ok(
id,
json!({
"kind": "install",
"plan_id": plan.id,
"application": plan.application,
"backend": plan.candidate.as_ref().map(|c| c.backend.as_str()),
"source": plan.source,
"recommendation": plan.recommendation,
"action": plan.actions.first(),
"digest": plan.digest,
"effects": plan.effects.effects,
"requires_root": plan.requires_root,
}),
),
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()),
}
}
@ -290,7 +357,7 @@ pub fn handle_request(exec: &Exec, root: &Path, req: BridgeRequest) -> BridgeRes
} else {
return BridgeResponse::err(id, "missing action or phrase parameter");
};
execute_action_helper(exec, root, id, action, req.yes.unwrap_or(false))
execute_action_helper(exec, root, plans, id, action, req.yes.unwrap_or(false))
}
"ask" => {
let query = req.request.unwrap_or_default();
@ -300,8 +367,26 @@ pub fn handle_request(exec: &Exec, root: &Path, req: BridgeRequest) -> BridgeRes
let conv_path = conversation::history_path();
let history = conversation::load_history(&conv_path);
let constrained_backend = req.backend.as_deref().and_then(Backend::parse);
// 1. Contextual follow-up check
// 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 {
@ -313,6 +398,7 @@ pub fn handle_request(exec: &Exec, root: &Path, req: BridgeRequest) -> BridgeRes
id,
json!({
"kind": "info",
"state": "info",
"application": application,
"summary": explanation.clone(),
"recommendation": explanation,
@ -324,6 +410,7 @@ pub fn handle_request(exec: &Exec, root: &Path, req: BridgeRequest) -> BridgeRes
target_backend,
} => {
return plan_and_respond_install(
plans,
exec,
root,
id,
@ -334,29 +421,26 @@ pub fn handle_request(exec: &Exec, root: &Path, req: BridgeRequest) -> BridgeRes
);
}
FollowupResolution::ConfirmPlan { plan_id, digest } => {
if let Ok(plan) = service::PlanStore::load(&plan_id) {
return BridgeResponse::ok(
match plans.load(&plan_id) {
Ok(plan) if plan.digest == digest => {
return plan_response(id, "confirm", &plan);
}
_ => {
return BridgeResponse::err(
id,
json!({
"kind": "confirm",
"plan_id": plan.id,
"digest": digest,
"summary": plan.summary,
"recommendation": plan.recommendation,
"action": plan.actions.first(),
"effects": plan.effects.effects,
"requires_root": plan.requires_root,
}),
"that plan is no longer available or has changed; \
ask again for a fresh recommendation",
);
}
}
}
}
}
// 2. Install request
let constrained_backend = req.backend.as_deref().and_then(Backend::parse);
if let Some(app) = parse_install_phrase(&query) {
return plan_and_respond_install(
plans,
exec,
root,
id,
@ -367,122 +451,34 @@ pub fn handle_request(exec: &Exec, root: &Path, req: BridgeRequest) -> BridgeRes
);
}
// 3. Removal request
// 3. Removal request (AI-first by default; legacy selection is an
// explicit GUI/CLI choice).
if let Some(app) = parse_removal_phrase(&query) {
match service::plan_removal(exec, root, &app, constrained_backend) {
Ok(plan) => {
conversation::save_turn(
&conv_path,
ConversationTurn {
timestamp_unix: now_unix(),
query: query.clone(),
response_kind: "removal".into(),
application: Some(app),
chosen_candidate: None,
alternatives: Vec::new(),
plan_id: Some(plan.id.clone()),
plan_digest: Some(plan.digest.clone()),
rationale: plan.rationale.clone(),
},
);
return BridgeResponse::ok(
id,
json!({
"kind": "removal",
"plan_id": plan.id,
"application": plan.application,
"source": plan.source,
"recommendation": plan.recommendation,
"action": plan.actions.first(),
"digest": plan.digest,
"effects": plan.effects.effects,
"requires_root": plan.requires_root,
}),
);
}
Err(e) => return BridgeResponse::err(id, e.to_string()),
}
}
// 4. General natural language request via connected model
let facts = gather_facts(exec, root);
let conf = load_installed_ai_config(root);
let ai_backend = conf
.as_ref()
.map(|c| c.backend)
.unwrap_or(AiBackend::Direct);
let (provider, endpoint, model);
let transport: Box<dyn phoebus_ai::provider::ModelTransport>;
match ai_backend {
AiBackend::OpenCode => {
let server = conf
.as_ref()
.map(|c| c.opencode_server.clone())
.unwrap_or_default();
let op_provider = conf
.as_ref()
.map(|c| c.opencode_provider.clone())
.unwrap_or_default();
let op_model = conf
.as_ref()
.map(|c| c.opencode_model.clone())
.unwrap_or_default();
if server.is_empty() || op_model.is_empty() {
return BridgeResponse::err(
id,
"OpenCode is not configured. Configure model or use legacy mode.",
);
}
provider = ProviderKind::Local;
endpoint = server.clone();
model = op_model.clone();
transport = Box::new(ExecOpenCodeTransport::new(
return plan_and_respond_removal(
plans,
exec,
server,
op_provider,
op_model,
));
}
AiBackend::Direct => {
let p = conf
.as_ref()
.and_then(|c| ProviderKind::parse(&c.provider))
.unwrap_or(ProviderKind::None);
if p == ProviderKind::None {
return BridgeResponse::err(
root,
id,
"No AI model is connected. Use legacy mode for deterministic administration.",
&app,
constrained_backend,
&query,
&conv_path,
);
}
endpoint = conf
.as_ref()
.map(|c| c.endpoint.clone())
.filter(|s| !s.trim().is_empty())
.unwrap_or_else(|| p.endpoint().to_string());
model = conf.as_ref().map(|c| c.model.clone()).unwrap_or_default();
provider = p;
let direct = CurlTransport::new(exec, None);
transport = Box::new(direct.sandboxed());
}
}
let ai = AiInstall {
provider,
endpoint,
model,
transport: transport.as_ref(),
limits: phoebus_ai::install::Limits::default(),
};
match service::plan_general(exec, root, &query, &facts, &ai) {
Ok(plan) => {
conversation::save_turn(
// 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)
});
match response {
Ok(Ok(plan)) => {
record_turn(
exec,
&conv_path,
ConversationTurn {
timestamp_unix: now_unix(),
query,
// Structured plan summary, not the raw request.
query: plan.summary.clone(),
response_kind: "plan".into(),
application: None,
chosen_candidate: None,
@ -492,20 +488,10 @@ pub fn handle_request(exec: &Exec, root: &Path, req: BridgeRequest) -> BridgeRes
rationale: plan.rationale.clone(),
},
);
BridgeResponse::ok(
id,
json!({
"kind": "plan",
"plan_id": plan.id,
"summary": plan.summary,
"actions": plan.actions,
"digest": plan.digest,
"effects": plan.effects.effects,
"requires_root": plan.requires_root,
}),
)
plan_response(id, "plan", &plan)
}
Err(e) => BridgeResponse::err(id, e.to_string()),
Ok(Err(e)) => BridgeResponse::err(id, e.to_string()),
Err(e) => BridgeResponse::err(id, e),
}
}
"execute" => {
@ -518,14 +504,23 @@ pub fn handle_request(exec: &Exec, root: &Path, req: BridgeRequest) -> BridgeRes
None => return BridgeResponse::err(id, "missing digest parameter"),
};
match service::execute_plan(exec, root, plan_id, digest, req.yes.unwrap_or(false)) {
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()),
@ -535,7 +530,9 @@ pub fn handle_request(exec: &Exec, root: &Path, req: BridgeRequest) -> BridgeRes
}
}
#[allow(clippy::too_many_arguments)]
fn plan_and_respond_install(
plans: &PlanStore,
exec: &Exec,
root: &Path,
id: u64,
@ -546,82 +543,16 @@ fn plan_and_respond_install(
) -> BridgeResponse {
let mut install_req = InstallRequest::new(app);
install_req.backend = constrained_backend;
let facts = gather_facts(exec, root);
let conf = load_installed_ai_config(root);
let ai_backend = conf
.as_ref()
.map(|c| c.backend)
.unwrap_or(AiBackend::Direct);
let (provider, endpoint, model);
let transport: Box<dyn phoebus_ai::provider::ModelTransport>;
match ai_backend {
AiBackend::OpenCode => {
let server = conf
.as_ref()
.map(|c| c.opencode_server.clone())
.unwrap_or_default();
let op_provider = conf
.as_ref()
.map(|c| c.opencode_provider.clone())
.unwrap_or_default();
let op_model = conf
.as_ref()
.map(|c| c.opencode_model.clone())
.unwrap_or_default();
if server.is_empty() || op_model.is_empty() {
return BridgeResponse::err(
id,
"OpenCode is not configured. Configure model or use legacy mode.",
);
}
provider = ProviderKind::Local;
endpoint = server.clone();
model = op_model.clone();
transport = Box::new(ExecOpenCodeTransport::new(
exec,
server,
op_provider,
op_model,
));
}
AiBackend::Direct => {
let p = conf
.as_ref()
.and_then(|c| ProviderKind::parse(&c.provider))
.unwrap_or(ProviderKind::None);
if p == ProviderKind::None {
return BridgeResponse::err(
id,
"No AI model is connected. Use legacy mode for deterministic administration (sys install <app> --legacy --<source>).",
);
}
endpoint = conf
.as_ref()
.map(|c| c.endpoint.clone())
.filter(|s| !s.trim().is_empty())
.unwrap_or_else(|| p.endpoint().to_string());
model = conf.as_ref().map(|c| c.model.clone()).unwrap_or_default();
provider = p;
let direct = CurlTransport::new(exec, None);
transport = Box::new(direct.sandboxed());
}
}
let ai = AiInstall {
provider,
endpoint,
model,
transport: transport.as_ref(),
limits: phoebus_ai::install::Limits::default(),
};
let session = BridgeSession { exec, root };
match service::plan_install(exec, root, &install_req, &session, Some(&ai), &facts) {
Ok(plan) => {
conversation::save_turn(
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(),
@ -635,33 +566,56 @@ fn plan_and_respond_install(
rationale: plan.rationale.clone(),
},
);
BridgeResponse::ok(
id,
json!({
"kind": "install",
"plan_id": plan.id,
"application": plan.application,
"backend": plan.candidate.as_ref().map(|c| c.backend.as_str()),
"source": plan.source,
"recommendation": plan.recommendation,
"chosen": plan.candidate,
"alternatives": plan.alternatives,
"rationale": plan.rationale,
"action": plan.actions.first(),
"digest": plan.digest,
"effects": plan.effects.effects,
"requires_root": plan.requires_root,
}),
)
plan_response(id, "install", &plan)
}
Err(e) => BridgeResponse::err(id, e.to_string()),
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,
@ -674,8 +628,8 @@ fn execute_action_helper(
let now = now_unix();
let actions_vec = vec![action.clone()];
let digest = service::compute_plan_digest(&actions_vec, None, &effects);
let plan = PreparedPlan {
id: format!("plan-act-{now}"),
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,
@ -687,23 +641,29 @@ fn execute_action_helper(
rationale: Vec::new(),
warnings: Vec::new(),
actions: actions_vec,
effects,
effects: effects.clone(),
step_effects: vec![effects],
digest: digest.clone(),
verification: "action completed".into(),
requires_root: action.is_mutating(),
source: "legacy".into(),
executed: false,
target_root: service::canonical_root(root),
initiator_uid: service::effective_uid(),
integrity: String::new(),
};
if let Err(e) = service::PlanStore::save(&plan) {
if let Err(e) = plans.save(&mut plan) {
return BridgeResponse::err(id, format!("could not stage plan: {e}"));
}
match service::execute_plan(exec, root, &plan.id, &digest, assume_yes) {
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()),
@ -755,6 +715,7 @@ pub fn run_stdio(exec: &Exec, root: &Path) -> std::result::Result<(), Box<dyn st
let stdin = std::io::stdin();
let stdout = std::io::stdout();
let mut stdout_lock = stdout.lock();
let plans = PlanStore::for_current_user();
for line in stdin.lock().lines() {
let line = line?;
@ -771,7 +732,7 @@ pub fn run_stdio(exec: &Exec, root: &Path) -> std::result::Result<(), Box<dyn st
}
};
let resp = handle_request(exec, root, req);
let resp = handle_request(exec, root, &plans, req);
writeln!(stdout_lock, "{}", serde_json::to_string(&resp)?)?;
stdout_lock.flush()?;
}
@ -822,7 +783,8 @@ mod tests {
snapshot: None,
};
let resp = handle_request(&exec, root, req);
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();
@ -846,7 +808,7 @@ mod tests {
preferences: None,
snapshot: None,
};
let hist_resp = handle_request(&exec, root, hist_req);
let hist_resp = handle_request(&exec, root, &plans, hist_req);
assert!(hist_resp.ok);
}

View file

@ -11,13 +11,12 @@ use std::path::{Path, PathBuf};
use std::process::ExitCode;
use clap::Parser;
use phoebus_ai::provider::{ModelTransport, ProviderKind, SystemFacts};
use phoebus_ai::provider::SystemFacts;
use phoebus_core::action::{parse_action, parse_natural, SystemAction};
use phoebus_core::selection::Backend;
use phoebus_core::transaction::{TransactionOutcome, TransactionRecord};
use phoebus_core::{AiBackend, InstallConfig, Redactor};
use phoebus_executor::install::{AiInstall, ExecutorSession, InstallRequest};
use phoebus_executor::opencode_client::ExecOpenCodeTransport;
use phoebus_executor::{
actions, authorize, chooser, probe, transaction, AutoConfirm, Confirmation,
DestructiveAuthorization, Exec, Logger, RealRunner, Result,
@ -58,9 +57,13 @@ struct Cli {
#[arg(long)]
action_file: Option<PathBuf>,
/// Execute a prepared plan file directly (internal broker invocation).
#[arg(long, value_name = "PATH")]
execute_plan: Option<PathBuf>,
/// Execute a prepared plan by identifier (internal broker invocation).
#[arg(long, value_name = "PLAN_ID")]
execute_plan: Option<String>,
/// The uid that reviewed and approved the plan (internal broker only).
#[arg(long, value_name = "UID")]
plan_uid: Option<u32>,
/// Auto-approve (unattended); still requires root.
#[arg(long, short = 'y')]
@ -191,6 +194,14 @@ fn effective_uid() -> u32 {
.unwrap_or(1)
}
/// Persist a minimized conversation turn with the process redactor, surfacing a
/// storage failure instead of silently losing it.
fn record_turn(exec: &Exec, path: &Path, turn: ConversationTurn) {
if let Err(e) = conversation::save_turn(path, exec.redactor(), turn) {
eprintln!("sys: warning: could not persist conversation context: {e}");
}
}
fn main() -> ExitCode {
match run() {
Ok(()) => ExitCode::SUCCESS,
@ -217,6 +228,7 @@ fn run() -> std::result::Result<(), Box<dyn std::error::Error>> {
cli.root.clone(),
state_dir,
);
let plans = service::PlanStore::for_current_user();
// 1. Assistant Bridge
if cli.assistant_bridge {
@ -224,15 +236,27 @@ fn run() -> std::result::Result<(), Box<dyn std::error::Error>> {
}
// 2. Broker execute plan
if let Some(plan_path) = &cli.execute_plan {
if let Some(plan_id) = &cli.execute_plan {
if !cli.broker {
return Err("--execute-plan requires --broker for privileged invocation".into());
}
if effective_uid() != 0 {
return Err("privileged plan execution requires root".into());
}
let plan = service::PlanStore::load(&plan_path.to_string_lossy())?;
let outcome = service::execute_plan_direct(&exec, &cli.root, plan, true)?;
let initiator_uid = cli
.plan_uid
.ok_or("--execute-plan requires --plan-uid (the reviewing user)")?;
// The broker resolves storage from the initiating uid, never from an
// arbitrary path, and repeats the full validation itself.
let plans = service::PlanStore::for_uid(initiator_uid);
let outcome = service::execute_plan_privileged(
&exec,
&cli.root,
&plans,
plan_id,
initiator_uid,
true,
)?;
println!("{}", serde_json::to_string(&outcome)?);
return Ok(());
}
@ -266,8 +290,8 @@ fn run() -> std::result::Result<(), Box<dyn std::error::Error>> {
if let Some(b) = backend {
let mut request = InstallRequest::new(&application);
request.backend = Some(b);
let plan = service::plan_legacy_install(&exec, &cli.root, &request)?;
return render_and_execute_plan(&cli, &exec, plan);
let plan = service::plan_legacy_install(&plans, &exec, &cli.root, &request)?;
return render_and_execute_plan(&cli, &exec, &plans, plan);
} else {
eprintln!("sys: legacy install requires an explicit package source flag.");
eprintln!("Specify one of:");
@ -281,8 +305,8 @@ fn run() -> std::result::Result<(), Box<dyn std::error::Error>> {
}
}
if let Some(application) = parse_removal_text(&full_phrase) {
let plan = service::plan_removal(&exec, &cli.root, &application, backend)?;
return render_and_execute_plan(&cli, &exec, plan);
let plan = service::plan_removal(&plans, &exec, &cli.root, &application, backend)?;
return render_and_execute_plan(&cli, &exec, &plans, plan);
}
if backend.is_some() {
return Err(
@ -331,17 +355,17 @@ fn run() -> std::result::Result<(), Box<dyn std::error::Error>> {
if instruction.trim().is_empty() {
return Err("usage: sys ask <request>".into());
}
return run_ask(&cli, &exec, &instruction, backend);
return run_ask(&cli, &exec, &plans, &instruction, backend);
}
// Natural `sys install <app>` / `sys please install <app>`
if let Some(application) = parse_install_text(&full_phrase) {
return run_install(&cli, &exec, &application, backend);
return run_install(&cli, &exec, &plans, &application, backend);
}
// Natural `sys remove <app>` / `sys please remove <app>`
if let Some(application) = parse_removal_text(&full_phrase) {
return run_remove(&cli, &exec, &application, backend);
return run_remove(&cli, &exec, &plans, &application, backend);
}
if backend.is_some() {
@ -353,7 +377,7 @@ fn run() -> std::result::Result<(), Box<dyn std::error::Error>> {
}
// Other natural language instructions enter the AI workflow by default
run_ask(&cli, &exec, &full_phrase, None)
run_ask(&cli, &exec, &plans, &full_phrase, None)
}
fn execute_action(
@ -551,79 +575,18 @@ fn print_install_offer(cli: &Cli, exec: &Exec, application: &str) {
fn run_install(
cli: &Cli,
exec: &Exec,
plans: &service::PlanStore,
application: &str,
backend: Option<Backend>,
) -> std::result::Result<(), Box<dyn std::error::Error>> {
let mut request = InstallRequest::new(application);
request.backend = backend;
let conf = load_installed_ai_config(&cli.root);
let ai_backend = resolve_backend(cli, conf.as_ref());
let resolved = resolve_ai(cli);
let facts = gather_facts(exec);
let (provider, endpoint, model);
let transport: Box<dyn ModelTransport + '_>;
match ai_backend {
AiBackend::OpenCode => {
let server = cli
.opencode_server
.clone()
.or_else(|| std::env::var("PHOEBUS_OPENCODE_SERVER").ok())
.or_else(|| conf.as_ref().map(|c| c.opencode_server.clone()))
.unwrap_or_default();
let opencode_provider = cli
.opencode_provider
.clone()
.or_else(|| std::env::var("PHOEBUS_OPENCODE_PROVIDER").ok())
.or_else(|| conf.as_ref().map(|c| c.opencode_provider.clone()))
.unwrap_or_default();
let opencode_model = cli
.opencode_model
.clone()
.or_else(|| std::env::var("PHOEBUS_OPENCODE_MODEL").ok())
.or_else(|| conf.as_ref().map(|c| c.opencode_model.clone()))
.unwrap_or_default();
if server.trim().is_empty()
|| opencode_provider.trim().is_empty()
|| opencode_model.trim().is_empty()
{
if !resolved.is_configured() {
if let Some(b) = backend {
eprintln!("sys: OpenCode is not configured for this request.");
eprintln!("Run deterministically without a model using legacy mode:");
eprintln!(
" sys install {application} --legacy --{}",
backend_flag_name(b)
);
} else {
print_install_offer(cli, exec, application);
}
return Err(
"OpenCode needs --opencode-server, --opencode-provider and --opencode-model"
.into(),
);
}
let password = match &cli.opencode_password_file {
Some(path) => Some(phoebus_executor::ai::load_api_key(path)?),
None => None,
};
provider = ProviderKind::Local;
endpoint = server;
model = opencode_model;
transport = Box::new(
ExecOpenCodeTransport::new(
exec,
endpoint.clone(),
opencode_provider,
model.clone(),
)
.with_auth(password),
);
}
AiBackend::Direct => {
provider = resolve_provider(cli, conf.as_ref());
if provider == ProviderKind::None {
if let Some(b) = backend {
eprintln!("sys: no AI provider is configured for this request.");
eprintln!("sys: no AI model is configured for this request.");
eprintln!("Run deterministically without a model using legacy mode:");
eprintln!(
" sys install {application} --legacy --{}",
@ -634,16 +597,11 @@ fn run_install(
}
return Err("no AI provider configured".into());
}
let key = match api_key_file(cli) {
Some(path) => Some(phoebus_executor::ai::load_api_key(&path)?),
None => None,
};
if provider.requires_key() && key.is_none() {
let transport = match resolved.transport(exec) {
Ok(t) => t,
Err(e) => {
if let Some(b) = backend {
eprintln!(
"sys: provider `{}` requires --ai-api-key-file (mode 0600)",
provider.as_str()
);
eprintln!("sys: {e}");
eprintln!("Run deterministically without a model using legacy mode:");
eprintln!(
" sys install {application} --legacy --{}",
@ -652,22 +610,20 @@ fn run_install(
} else {
print_install_offer(cli, exec, application);
}
return Err(format!(
"provider `{}` requires --ai-api-key-file (mode 0600)",
provider.as_str()
)
.into());
return Err(e.to_string().into());
}
endpoint = resolve_endpoint(cli, provider, conf.as_ref());
model = resolve_model(cli, conf.as_ref());
let direct = phoebus_executor::ai::CurlTransport::new(exec, key);
transport = if cli.no_sandbox {
Box::new(direct)
} else {
Box::new(direct.sandboxed())
};
}
}
let provider = resolved.provider;
let endpoint = if resolved.backend == AiBackend::OpenCode {
resolved.opencode_server.clone()
} else {
resolved.endpoint.clone()
};
let model = if resolved.backend == AiBackend::OpenCode {
resolved.opencode_model.clone()
} else {
resolved.model.clone()
};
if let Some(b) = backend {
eprintln!(
@ -695,7 +651,15 @@ fn run_install(
root: &cli.root,
ask: asker.as_deref(),
};
let plan = match service::plan_install(exec, &cli.root, &request, &session, Some(&ai), &facts) {
let plan = match service::plan_install(
plans,
exec,
&cli.root,
&request,
&session,
Some(&ai),
&facts,
) {
Ok(plan) => plan,
Err(e) => {
// The model failed: offer the actionable legacy alternative and stop;
@ -715,7 +679,8 @@ fn run_install(
};
let conv_path = conversation::history_path();
conversation::save_turn(
record_turn(
exec,
&conv_path,
ConversationTurn {
timestamp_unix: now_unix(),
@ -730,18 +695,38 @@ fn run_install(
},
);
render_and_execute_plan(cli, exec, plan)
render_and_execute_plan(cli, exec, plans, plan)
}
/// `sys remove <application>`: the shared AI-first removal workflow. Default
/// removal goes through the connected model; only `--legacy` bypasses it. The
/// deterministic ownership discovery and policy validation run underneath in
/// both modes.
fn run_remove(
cli: &Cli,
exec: &Exec,
plans: &service::PlanStore,
application: &str,
backend: Option<Backend>,
) -> std::result::Result<(), Box<dyn std::error::Error>> {
let plan = service::plan_removal(exec, &cli.root, application, backend)?;
let plan = match run_remove_plan(cli, exec, plans, application, backend) {
Ok(plan) => plan,
Err(e) => {
// The model failed: offer the actionable legacy alternative and
// stop; do not silently remove deterministically.
eprintln!("sys: the AI-assisted removal did not produce a plan ({e}).");
eprintln!("Run deterministically without a model using legacy mode:");
let lane = backend
.map(|b| format!(" --{}", backend_flag_name(b)))
.unwrap_or_default();
eprintln!(" sys remove {application} --legacy{lane}");
return Err(format!("the AI-assisted removal did not produce a plan: {e}").into());
}
};
let conv_path = conversation::history_path();
conversation::save_turn(
record_turn(
exec,
&conv_path,
ConversationTurn {
timestamp_unix: now_unix(),
@ -755,12 +740,58 @@ fn run_remove(
rationale: plan.rationale.clone(),
},
);
render_and_execute_plan(cli, exec, plan)
render_and_execute_plan(cli, exec, plans, plan)
}
/// Build a removal plan through the connected model (default) or the
/// deterministic selector (legacy). The model only chooses/confirms among
/// copies the deterministic discovery already found.
fn run_remove_plan(
cli: &Cli,
exec: &Exec,
plans: &service::PlanStore,
application: &str,
backend: Option<Backend>,
) -> std::result::Result<PreparedPlan, Box<dyn std::error::Error>> {
if cli.legacy {
return Ok(service::plan_removal(
plans,
exec,
&cli.root,
application,
backend,
)?);
}
let resolved = resolve_ai(cli);
if !resolved.is_configured() {
return Err("no AI provider configured".into());
}
let transport = resolved.transport(exec).map_err(|e| e.to_string())?;
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: transport.as_ref(),
limits: phoebus_ai::install::Limits::default(),
};
let facts = gather_facts(exec);
service::plan_removal_with_ai(plans, exec, &cli.root, application, backend, &ai, &facts)
.map_err(Into::into)
}
fn render_and_execute_plan(
cli: &Cli,
exec: &Exec,
plans: &service::PlanStore,
plan: PreparedPlan,
) -> std::result::Result<(), Box<dyn std::error::Error>> {
println!("{}", plan.render());
@ -781,7 +812,7 @@ fn render_and_execute_plan(
authorize(&confirmation, &plan.summary, "execute")?;
}
let outcome = service::execute_plan(exec, &cli.root, &plan.id, &plan.digest, true)?;
let outcome = service::execute_plan(exec, &cli.root, plans, &plan.id, &plan.digest, true)?;
if let Some(snapshot) = outcome.snapshot {
println!("protective snapshot: {snapshot}");
}
@ -832,61 +863,24 @@ fn load_installed_ai_config(root: &Path) -> Option<phoebus_core::AiConfig> {
toml::from_str(&text).ok()
}
fn resolve_backend(cli: &Cli, conf: Option<&phoebus_core::AiConfig>) -> AiBackend {
let raw = cli
.ai_backend
.clone()
.or_else(|| std::env::var("PHOEBUS_AI_BACKEND").ok())
.or_else(|| conf.map(|c| c.backend.as_str().to_string()))
.unwrap_or_default();
AiBackend::parse(&raw).unwrap_or(AiBackend::Direct)
}
fn resolve_provider(cli: &Cli, conf: Option<&phoebus_core::AiConfig>) -> ProviderKind {
let raw = cli
.ai_provider
.clone()
.or_else(|| std::env::var("PHOEBUS_AI_PROVIDER").ok())
.or_else(|| conf.map(|c| c.provider.clone()))
.unwrap_or_default();
ProviderKind::parse(&raw).unwrap_or(ProviderKind::None)
}
fn resolve_endpoint(
cli: &Cli,
provider: ProviderKind,
conf: Option<&phoebus_core::AiConfig>,
) -> String {
cli.ai_endpoint
.clone()
.or_else(|| std::env::var("PHOEBUS_AI_ENDPOINT").ok())
.or_else(|| {
conf.and_then(|c| {
if c.endpoint.is_empty() {
None
} else {
Some(c.endpoint.clone())
}
})
})
.filter(|s| !s.trim().is_empty())
.unwrap_or_else(|| provider.endpoint().to_string())
}
fn resolve_model(cli: &Cli, conf: Option<&phoebus_core::AiConfig>) -> String {
cli.ai_model
.clone()
.or_else(|| std::env::var("PHOEBUS_AI_MODEL").ok())
.or_else(|| conf.map(|c| c.model.clone()))
.unwrap_or_default()
}
fn api_key_file(cli: &Cli) -> Option<PathBuf> {
cli.ai_api_key_file.clone().or_else(|| {
std::env::var("PHOEBUS_AI_API_KEY_FILE")
.ok()
.map(PathBuf::from)
})
/// Resolve provider configuration and credential references through the shared
/// setup module, so the CLI and the GUI cannot diverge.
fn resolve_ai(cli: &Cli) -> phoebus_installer::ai_setup::ResolvedAi {
let conf = load_installed_ai_config(&cli.root);
let overrides = phoebus_installer::ai_setup::AiOverrides {
backend: cli.ai_backend.clone(),
provider: cli.ai_provider.clone(),
model: cli.ai_model.clone(),
endpoint: cli.ai_endpoint.clone(),
api_key_file: cli.ai_api_key_file.clone(),
opencode_server: cli.opencode_server.clone(),
opencode_provider: cli.opencode_provider.clone(),
opencode_model: cli.opencode_model.clone(),
opencode_password_file: cli.opencode_password_file.clone(),
no_sandbox: cli.no_sandbox,
use_environment: true,
};
phoebus_installer::ai_setup::resolve(&cli.root, &overrides, conf.as_ref())
}
fn deterministic_fallback(instruction: &str) {
@ -911,14 +905,18 @@ fn deterministic_fallback(instruction: &str) {
fn run_ask(
cli: &Cli,
exec: &Exec,
plans: &service::PlanStore,
instruction: &str,
backend: Option<Backend>,
) -> std::result::Result<(), Box<dyn std::error::Error>> {
if let Some(application) = parse_install_text(instruction) {
return run_install(cli, exec, &application, backend);
// An explicit application reference takes precedence over any inferred
// conversational reference: "install vlc using flatpak" concerns VLC even
// right after a conversation about Firefox.
if let Some((application, source)) = conversation::parse_explicit_install(instruction) {
return run_install(cli, exec, plans, &application, source.or(backend));
}
if let Some(application) = parse_removal_text(instruction) {
return run_remove(cli, exec, &application, backend);
return run_remove(cli, exec, plans, &application, backend);
}
let conv_path = conversation::history_path();
@ -933,100 +931,45 @@ fn run_ask(
application,
target_backend,
} => {
return run_install(cli, exec, &application, Some(target_backend));
return run_install(cli, exec, plans, &application, Some(target_backend));
}
FollowupResolution::ConfirmPlan { plan_id, digest } => {
let plan = service::PlanStore::load(&plan_id)?;
// Conversational confirmation never bypasses normal plan
// validation or authentication: it references a reviewed plan
// and goes through the same execution boundary.
let plan = plans.load(&plan_id)?;
if plan.digest != digest {
return Err("plan digest mismatch".into());
}
return render_and_execute_plan(cli, exec, plan);
return render_and_execute_plan(cli, exec, plans, plan);
}
}
}
let facts = gather_facts(exec);
let conf = load_installed_ai_config(&cli.root);
let ai_backend = resolve_backend(cli, conf.as_ref());
let (provider, endpoint, model);
let transport: Box<dyn ModelTransport + '_>;
match ai_backend {
AiBackend::OpenCode => {
let server = cli
.opencode_server
.clone()
.or_else(|| std::env::var("PHOEBUS_OPENCODE_SERVER").ok())
.or_else(|| conf.as_ref().map(|c| c.opencode_server.clone()))
.unwrap_or_default();
let opencode_provider = cli
.opencode_provider
.clone()
.or_else(|| std::env::var("PHOEBUS_OPENCODE_PROVIDER").ok())
.or_else(|| conf.as_ref().map(|c| c.opencode_provider.clone()))
.unwrap_or_default();
let opencode_model = cli
.opencode_model
.clone()
.or_else(|| std::env::var("PHOEBUS_OPENCODE_MODEL").ok())
.or_else(|| conf.as_ref().map(|c| c.opencode_model.clone()))
.unwrap_or_default();
if server.trim().is_empty()
|| opencode_provider.trim().is_empty()
|| opencode_model.trim().is_empty()
{
deterministic_fallback(instruction);
return Err(
"OpenCode requires --opencode-server, --opencode-provider and --opencode-model"
.into(),
);
}
let password = match &cli.opencode_password_file {
Some(path) => Some(phoebus_executor::ai::load_api_key(path)?),
None => None,
};
provider = ProviderKind::Local;
endpoint = server;
model = opencode_model;
transport = Box::new(
ExecOpenCodeTransport::new(
exec,
endpoint.clone(),
opencode_provider,
model.clone(),
)
.with_auth(password),
);
}
AiBackend::Direct => {
let resolved = resolve_provider(cli, conf.as_ref());
if resolved == ProviderKind::None {
let resolved = resolve_ai(cli);
if !resolved.is_configured() {
deterministic_fallback(instruction);
return Err("no AI provider configured".into());
}
let key = match api_key_file(cli) {
Some(path) => Some(phoebus_executor::ai::load_api_key(&path)?),
None => None,
};
if resolved.requires_key() && key.is_none() {
let transport = match resolved.transport(exec) {
Ok(t) => t,
Err(e) => {
deterministic_fallback(instruction);
return Err(format!(
"provider `{}` requires --ai-api-key-file (mode 0600)",
resolved.as_str()
)
.into());
return Err(e.to_string().into());
}
provider = resolved;
endpoint = resolve_endpoint(cli, resolved, conf.as_ref());
model = resolve_model(cli, conf.as_ref());
let direct = phoebus_executor::ai::CurlTransport::new(exec, key);
transport = if cli.no_sandbox {
Box::new(direct)
} else {
Box::new(direct.sandboxed())
};
}
}
let facts = gather_facts(exec);
let provider = resolved.provider;
let endpoint = if resolved.backend == AiBackend::OpenCode {
resolved.opencode_server.clone()
} else {
resolved.endpoint.clone()
};
let model = if resolved.backend == AiBackend::OpenCode {
resolved.opencode_model.clone()
} else {
resolved.model.clone()
};
let ai = AiInstall {
provider,
@ -1036,7 +979,7 @@ fn run_ask(
limits: phoebus_ai::install::Limits::default(),
};
let plan = match service::plan_general(exec, &cli.root, instruction, &facts, &ai) {
let plan = match service::plan_general(plans, exec, &cli.root, instruction, &facts, &ai) {
Ok(plan) => plan,
Err(e) => {
eprintln!("The model is unavailable or returned an unusable plan: {e}");
@ -1045,11 +988,14 @@ fn run_ask(
}
};
conversation::save_turn(
record_turn(
exec,
&conv_path,
ConversationTurn {
timestamp_unix: now_unix(),
query: instruction.to_string(),
// Persist the plan's own summary, not the raw request: structured
// context is sufficient for follow-ups and minimizes exposure.
query: plan.summary.clone(),
response_kind: "plan".into(),
application: None,
chosen_candidate: None,
@ -1060,7 +1006,7 @@ fn run_ask(
},
);
render_and_execute_plan(cli, exec, plan)
render_and_execute_plan(cli, exec, plans, plan)
}
#[allow(dead_code)]

View file

@ -4,9 +4,17 @@
//! "why did you choose that over nix?", "install the flatpak one", or "proceed with that"
//! without restarting candidate investigation from scratch.
//!
//! All stored history is bounded (max 10 turns) and sensitive credentials are
//! redacted before persistence.
//! All stored history is bounded (max 10 turns) and minimized before
//! persistence. Only structured context (the application, chosen candidate,
//! rationale and a short summary) is kept, never the unrestricted raw request.
//! Registered secrets are scrubbed with the caller's redactor; that is an
//! honest boundary — it removes known secrets, it does not detect arbitrary
//! sensitive text, which is why raw requests are not stored.
//!
//! History is kept in a 0600 file inside a 0700 directory, written atomically,
//! and can be cleared without leaving the follow-up context behind.
use std::io::Write;
use std::path::{Path, PathBuf};
use std::time::{SystemTime, UNIX_EPOCH};
@ -16,10 +24,14 @@ use serde::{Deserialize, Serialize};
const MAX_TURNS: usize = 10;
const FOLLOWUP_WINDOW_SECONDS: u64 = 1800; // 30 minutes
/// Upper bound on a persisted free-text summary or rationale line.
const MAX_TEXT_CHARS: usize = 240;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConversationTurn {
pub timestamp_unix: u64,
/// A minimized, structured summary of the request (e.g. "install firefox"),
/// never the unrestricted raw natural-language request.
pub query: String,
pub response_kind: String, // "install", "removal", "plan", "info"
#[serde(default, skip_serializing_if = "Option::is_none")]
@ -91,29 +103,168 @@ pub fn load_history(path: &Path) -> ConversationHistory {
serde_json::from_str(&data).unwrap_or_default()
}
pub fn save_turn(path: &Path, turn: ConversationTurn) {
/// Bound a piece of free text: collapse whitespace, drop control characters
/// and cap the length. Combined with the registered-secret redactor, this keeps
/// persisted history minimal and stable.
fn minimize(redactor: &Redactor, text: &str) -> String {
let redacted = redactor.redact(text);
let cleaned: String = redacted
.chars()
.filter(|c| !c.is_control() || *c == ' ')
.collect();
let collapsed = cleaned.split_whitespace().collect::<Vec<_>>().join(" ");
if collapsed.chars().count() > MAX_TEXT_CHARS {
collapsed.chars().take(MAX_TEXT_CHARS).collect::<String>() + "…"
} else {
collapsed
}
}
/// Append a turn. The caller supplies the process redactor (which holds any
/// registered secret), so a known secret can never be persisted. Returns an
/// error on a write failure instead of silently discarding history.
pub fn save_turn(
path: &Path,
redactor: &Redactor,
mut turn: ConversationTurn,
) -> std::io::Result<()> {
let mut history = load_history(path);
// Redact sensitive patterns in query and rationale
let redactor = Redactor::new();
let mut sanitized_turn = turn;
sanitized_turn.query = redactor.redact(&sanitized_turn.query);
sanitized_turn.rationale = sanitized_turn
turn.query = minimize(redactor, &turn.query);
turn.rationale = turn
.rationale
.into_iter()
.map(|r| redactor.redact(&r))
.map(|r| minimize(redactor, &r))
.collect();
if let Some(app) = &turn.application {
turn.application = Some(minimize(redactor, app));
}
history.turns.push(sanitized_turn);
history.turns.push(turn);
if history.turns.len() > MAX_TURNS {
history.turns.drain(0..history.turns.len() - MAX_TURNS);
}
if let Some(parent) = path.parent() {
let _ = std::fs::create_dir_all(parent);
std::fs::create_dir_all(parent)?;
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let _ = std::fs::set_permissions(parent, std::fs::Permissions::from_mode(0o700));
}
if let Ok(serialized) = serde_json::to_string_pretty(&history) {
let _ = std::fs::write(path, serialized);
}
let serialized = serde_json::to_string_pretty(&history)
.map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
atomic_write_private(path, serialized.as_bytes())
}
/// Delete the persisted history so it can no longer inform a later follow-up.
pub fn clear_history(path: &Path) -> std::io::Result<()> {
match std::fs::remove_file(path) {
Ok(()) => Ok(()),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
Err(e) => Err(e),
}
}
fn atomic_write_private(path: &Path, bytes: &[u8]) -> std::io::Result<()> {
let tmp = path.with_extension("tmp");
{
let mut opts = std::fs::OpenOptions::new();
opts.write(true).create(true).truncate(true);
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt;
opts.mode(0o600);
}
let mut file = opts.open(&tmp)?;
file.write_all(bytes)?;
file.flush()?;
file.sync_all()?;
}
std::fs::rename(&tmp, path)?;
Ok(())
}
fn backend_from_word(word: &str) -> Option<Backend> {
match word {
"flatpak" => Some(Backend::Flatpak),
"portage" => Some(Backend::PortageSource),
"source" => Some(Backend::PortageSource),
"binary" => Some(Backend::PortageBinary),
"nix" => Some(Backend::Nix),
"nixpkgs" => Some(Backend::Nix),
"snap" => Some(Backend::Snap),
"appimage" => Some(Backend::AppImage),
"ebuild" => Some(Backend::CustomEbuild),
_ => None,
}
}
/// Tokens that are never an application name: articles, pronouns, verbs and
/// software-lane names.
const NON_APP_TOKENS: &[&str] = &[
"the",
"a",
"an",
"that",
"this",
"it",
"one",
"those",
"these",
"using",
"via",
"with",
"from",
"through",
"instead",
"please",
"install",
"add",
"remove",
"uninstall",
"delete",
"for",
"and",
"to",
"switch",
"try",
"flatpak",
"portage",
"source",
"binary",
"nix",
"nixpkgs",
"snap",
"appimage",
"ebuild",
];
/// Parse an explicit `install <app>` or `install <app> using/via/with <source>`
/// request. Returns `None` for a vague reference such as "install the flatpak
/// one", which is a conversational follow-up rather than a new application.
pub fn parse_explicit_install(query: &str) -> Option<(String, Option<Backend>)> {
let lower = query.trim().to_ascii_lowercase();
let lower = lower.strip_prefix("please ").unwrap_or(&lower).trim();
let rest = lower
.strip_prefix("install ")
.or_else(|| lower.strip_prefix("add "))?;
let tokens: Vec<&str> = rest.split_whitespace().collect();
let app = tokens
.first()
.copied()
.filter(|t| !NON_APP_TOKENS.contains(t) && !t.starts_with('-'))?;
let mut backend = None;
for token in &tokens[1..] {
if let Some(b) = backend_from_word(token) {
backend = Some(b);
} else if !NON_APP_TOKENS.contains(token) {
// A trailing word that is not a source or a filler makes this an
// ambiguous instruction; let the model investigate it instead.
return None;
}
}
Some((app.to_string(), backend))
}
/// Analyze incoming query against the most recent conversation turn.
@ -148,7 +299,6 @@ pub fn resolve_followup(query: &str, history: &ConversationHistory) -> Option<Fo
let app = last.application.as_deref()?;
// 2. Switch backend ("install the flatpak one", "use portage instead", "install via nix")
let backends = [
("flatpak", Backend::Flatpak),
("portage", Backend::PortageSource),
@ -157,8 +307,21 @@ pub fn resolve_followup(query: &str, history: &ConversationHistory) -> Option<Fo
("nix", Backend::Nix),
("snap", Backend::Snap),
("appimage", Backend::AppImage),
("ebuild", Backend::CustomEbuild),
];
// Prefer an explicit application reference over an inferred one. If the
// request names a concrete application different from the one under
// discussion, it is a fresh request, not a follow-up about the old one.
if let Some((named, _)) = parse_explicit_install(query) {
if !named.eq_ignore_ascii_case(app) {
return None;
}
}
// 2. Switch backend ("install the flatpak one", "use portage instead",
// "use flatpak for that one"). No explicit new application is present
// (it would have returned above).
for (name, backend) in backends {
if (q_lower.contains("install") || q_lower.contains("use") || q_lower.contains("switch"))
&& q_lower.contains(name)
@ -170,7 +333,10 @@ pub fn resolve_followup(query: &str, history: &ConversationHistory) -> Option<Fo
}
}
// 3. Comparison / Why question ("why did you choose that over nix?", "why flatpak?", "why not portage?")
// 3. Comparison / Why question. Only answer about the previous package
// choice when the question actually refers to it (a named backend, a
// demonstrative, or the application itself). A generic "why is my audio
// broken?" must not become an explanation of an unrelated choice.
let is_why = q_lower.starts_with("why")
|| q_lower.contains("how come")
|| q_lower.contains("explain")
@ -187,6 +353,16 @@ pub fn resolve_followup(query: &str, history: &ConversationHistory) -> Option<Fo
break;
}
}
let refers_to_previous = target_backend.is_some()
|| q_lower.contains("that")
|| q_lower.contains("this")
|| q_lower.contains("chosen")
|| q_lower.contains("recommend")
|| q_lower.contains("it ")
|| q_lower.contains(&app.to_ascii_lowercase());
if !refers_to_previous {
return None;
}
let mut explanation = String::new();
if let Some(cand) = &last.chosen_candidate {
@ -278,7 +454,7 @@ mod tests {
rationale: vec!["provides application isolation".into()],
};
save_turn(&path, turn);
save_turn(&path, &Redactor::new(), turn).unwrap();
let history = load_history(&path);
assert_eq!(history.turns.len(), 1);
@ -310,4 +486,145 @@ mod tests {
})
);
}
#[test]
fn explicit_install_is_parsed_and_not_a_stale_followup() {
// "install vlc using flatpak" names VLC and the lane; it must not be
// captured as a backend switch for a previously discussed FireFox.
assert_eq!(
parse_explicit_install("install vlc using flatpak"),
Some(("vlc".into(), Some(Backend::Flatpak)))
);
assert_eq!(
parse_explicit_install("install firefox"),
Some(("firefox".into(), None))
);
// Vague references are not explicit applications.
assert_eq!(parse_explicit_install("install the flatpak one"), None);
assert_eq!(parse_explicit_install("install the nix one"), None);
let temp = tempdir().unwrap();
let path = temp.path().join("conversation.json");
save_turn(
&path,
&Redactor::new(),
ConversationTurn {
timestamp_unix: now_unix(),
query: "install firefox".into(),
response_kind: "install".into(),
application: Some("firefox".into()),
chosen_candidate: Some(make_test_candidate(Backend::Flatpak)),
alternatives: vec![],
plan_id: None,
plan_digest: None,
rationale: vec![],
},
)
.unwrap();
let history = load_history(&path);
// A different explicit app is a fresh request, not a follow-up.
assert_eq!(
resolve_followup("install vlc using flatpak", &history),
None
);
// A demonstrative switch still refers to the previous app.
assert_eq!(
resolve_followup("use flatpak for that one", &history),
Some(FollowupResolution::SwitchBackend {
application: "firefox".into(),
target_backend: Backend::Flatpak,
})
);
// An unrelated question is not a package explanation.
assert_eq!(resolve_followup("why is my audio broken?", &history), None);
}
#[test]
fn history_is_minimized_redacted_private_and_clearable() {
use std::os::unix::fs::PermissionsExt;
let temp = tempdir().unwrap();
let path = temp.path().join("phoebus/conversation.json");
let redactor = Redactor::new();
redactor.register_plain("sk-supersecret");
save_turn(
&path,
&redactor,
ConversationTurn {
timestamp_unix: now_unix(),
query: "install firefox with key sk-supersecret".into(),
response_kind: "install".into(),
application: Some("firefox".into()),
chosen_candidate: None,
alternatives: vec![],
plan_id: None,
plan_digest: None,
rationale: vec!["token sk-supersecret leaked".into()],
},
)
.unwrap();
let raw = std::fs::read_to_string(&path).unwrap();
assert!(!raw.contains("sk-supersecret"), "secret must be redacted");
assert!(raw.contains("<redacted>"));
let mode = std::fs::metadata(&path).unwrap().permissions().mode() & 0o777;
assert_eq!(mode, 0o600, "history must be private");
// Clearing removes the context used for later follow-ups.
clear_history(&path).unwrap();
assert!(!path.exists());
assert!(load_history(&path).turns.is_empty());
}
#[test]
fn history_is_bounded() {
let temp = tempdir().unwrap();
let path = temp.path().join("conversation.json");
for i in 0..(MAX_TURNS + 5) {
save_turn(
&path,
&Redactor::new(),
ConversationTurn {
timestamp_unix: now_unix(),
query: format!("install app{i}"),
response_kind: "install".into(),
application: Some(format!("app{i}")),
chosen_candidate: None,
alternatives: vec![],
plan_id: None,
plan_digest: None,
rationale: vec![],
},
)
.unwrap();
}
assert_eq!(load_history(&path).turns.len(), MAX_TURNS);
}
#[test]
fn long_text_is_bounded_not_stored_raw() {
let temp = tempdir().unwrap();
let path = temp.path().join("conversation.json");
let long = "x".repeat(2000);
save_turn(
&path,
&Redactor::new(),
ConversationTurn {
timestamp_unix: now_unix(),
query: long.clone(),
response_kind: "plan".into(),
application: None,
chosen_candidate: None,
alternatives: vec![],
plan_id: None,
plan_digest: None,
rationale: vec![],
},
)
.unwrap();
let history = load_history(&path);
assert!(history.turns[0].query.chars().count() <= MAX_TEXT_CHARS + 1);
assert!(!history.turns[0].query.contains(&long));
}
}

View file

@ -1,6 +1,7 @@
//! Phoebus installer orchestration and CLI support.
pub mod ai_guide;
pub mod ai_setup;
pub mod assistant_bridge;
pub mod conversation;
pub mod gui_bridge;

File diff suppressed because it is too large Load diff

View file

@ -132,6 +132,10 @@ Singleton {
call("history", {}, cb);
}
function clearConversation(cb) {
call("clear_conversation", {}, cb);
}
function undo(snapshot, cb) {
call("undo", { snapshot: snapshot, yes: true }, cb);
}

View file

@ -62,6 +62,20 @@ ShellRoot {
const list = shell.conversation.slice();
list.push(item);
shell.conversation = list;
return list.length - 1;
}
// Replace one message in place so its original card updates after an
// approval, completion or failure instead of appending a new message.
function updateMessage(index, dataPatch) {
const list = shell.conversation.slice();
if (index < 0 || index >= list.length)
return;
const current = list[index];
const next = Object.assign({}, current);
next.data = Object.assign({}, current.data || {}, dataPatch || {});
list[index] = next;
shell.conversation = list;
}
function submitPrompt(query) {
@ -76,47 +90,79 @@ ShellRoot {
shell.busy = false;
if (!reply.ok) {
shell.statusText = "Error: " + reply.error;
addMessage("assistant", "Could not complete request: " + reply.error, null);
addMessage("assistant", "Could not complete request: " + reply.error, {
kind: "error",
state: "failed"
});
return;
}
shell.statusText = "Plan prepared";
const res = reply.result;
if (res.kind === "install") {
addMessage("assistant", res.recommendation, res);
} else if (res.kind === "plan") {
addMessage("assistant", res.summary, res);
const res = reply.result || {};
const text = res.recommendation || res.summary || "Prepared for review.";
if (res.kind === "info") {
shell.statusText = "Ready";
} else if (res.prepared) {
shell.statusText = "Plan ready for review";
} else {
addMessage("assistant", "Completed.", res);
shell.statusText = "Ready";
}
addMessage("assistant", text, res);
});
}
function executePlan(planData) {
function executePlan(index) {
const list = shell.conversation.slice();
if (index < 0 || index >= list.length)
return;
const data = list[index].data || {};
if (!data.plan_id || !data.digest) {
shell.updateMessage(index, { state: "failed", error: "No reviewed plan to execute." });
return;
}
// Only execute the referenced reviewed plan; the service revalidates it.
shell.busy = true;
shell.statusText = "Executing approved plan...";
const planId = planData.plan_id || planData.id;
const digest = planData.digest;
shell.updateMessage(index, { state: "executing" });
AssistantBridge.execute(planId, digest, true, reply => {
AssistantBridge.execute(data.plan_id, data.digest, true, reply => {
shell.busy = false;
if (!reply.ok) {
shell.statusText = "Execution failed";
addMessage("assistant", "Execution failed: " + reply.error, null);
} else {
shell.statusText = "Operation completed successfully";
addMessage("assistant", "Operation completed successfully.", {
shell.updateMessage(index, { state: "failed", error: reply.error });
return;
}
const r = reply.result || {};
shell.statusText = "Operation completed and verified";
shell.updateMessage(index, {
state: "completed",
completed: true,
application: planData.application,
snapshot: reply.result ? reply.result.snapshot : null
verification: r.verification,
snapshot: r.snapshot,
launch: r.launch || null
});
refreshStatus();
}
});
}
function launchApplication(app) {
if (!app) return;
Quickshell.execDetached(["gtk-launch", app]);
function cancelPlan(index) {
// Cancelling is purely local: nothing reaches the privileged broker.
shell.updateMessage(index, { state: "cancelled" });
shell.statusText = "Cancelled — no changes were made";
}
function launchFromMessage(index) {
const list = shell.conversation.slice();
if (index < 0 || index >= list.length)
return;
const cmd = list[index].data ? list[index].data.launch : null;
if (cmd && cmd.length > 0)
Quickshell.execDetached(cmd);
}
function clearConversation() {
AssistantBridge.clearConversation(() => {
shell.conversation = [];
shell.statusText = "Conversation history cleared";
});
}
FloatingWindow {
@ -170,13 +216,13 @@ ShellRoot {
spacing: 4
PhoebusButton {
text: "Assistant"
label: "Assistant"
primary: shell.currentTab === "assistant"
onClicked: shell.currentTab = "assistant"
}
PhoebusButton {
text: "Updates" + (shell.updateOverview && shell.updateOverview.sources ? " (" + shell.updateOverview.sources.reduce((a, c) => a + c.updates.length, 0) + ")" : "")
label: "Updates" + (shell.updateOverview && shell.updateOverview.sources ? " (" + shell.updateOverview.sources.reduce((a, c) => a + c.updates.length, 0) + ")" : "")
primary: shell.currentTab === "updates"
onClicked: {
shell.currentTab = "updates";
@ -185,13 +231,13 @@ ShellRoot {
}
PhoebusButton {
text: "Legacy Admin"
label: "Legacy Admin"
primary: shell.currentTab === "legacy"
onClicked: shell.currentTab = "legacy"
}
PhoebusButton {
text: "Alerts" + (shell.activeAlerts.length > 0 ? " (" + shell.activeAlerts.length + ")" : "")
label: "Alerts" + (shell.activeAlerts.length > 0 ? " (" + shell.activeAlerts.length + ")" : "")
primary: shell.currentTab === "alerts"
onClicked: {
shell.currentTab = "alerts";
@ -200,7 +246,7 @@ ShellRoot {
}
PhoebusButton {
text: "Preferences"
label: "Preferences"
primary: shell.currentTab === "preferences"
onClicked: {
shell.currentTab = "preferences";
@ -271,61 +317,159 @@ ShellRoot {
wrapMode: Text.Wrap
}
// Recommendation / Action Card
// Plan / review card. The same card serves every
// plan type; the shared service decides what is
// proposed and this only presents it.
ColumnLayout {
Layout.fillWidth: true
visible: modelData.data !== null
spacing: 8
// Action buttons for installation
Label {
Layout.fillWidth: true
visible: modelData.data && modelData.data.kind
color: modelData.data && modelData.data.state === "failed" ? Theme.warning : Theme.muted
font.pixelSize: 12
text: {
const d = modelData.data || {};
const kindName = d.kind === "install" ? "Install plan"
: d.kind === "removal" ? "Removal plan"
: d.kind === "confirm" ? "Confirmation required"
: d.kind === "plan" ? "Administration plan"
: d.kind === "info" ? "Information"
: d.kind === "error" ? "Error" : "Result";
const stateName = d.state === "prepared" ? "— awaiting your approval"
: d.state === "executing" ? "— executing"
: d.state === "completed" ? "— completed and verified"
: d.state === "failed" ? "— failed"
: d.state === "cancelled" ? "— cancelled"
: "";
return kindName + " " + stateName;
}
}
// Approval and cancellation for every plan type.
RowLayout {
Layout.fillWidth: true
visible: modelData.data && modelData.data.kind === "install" && !modelData.data.completed
visible: modelData.data && modelData.data.prepared && modelData.data.state === "prepared"
spacing: 8
PhoebusButton {
text: "Install"
label: modelData.data && modelData.data.kind === "removal" ? "Approve & Remove" : "Approve & Execute"
primary: true
enabled: !shell.busy
onClicked: shell.executePlan(modelData.data)
actionEnabled: !shell.busy
onClicked: shell.executePlan(index)
}
PhoebusButton {
label: "Cancel"
actionEnabled: !shell.busy
onClicked: shell.cancelPlan(index)
}
PhoebusButton {
id: detailsBtn
property bool expanded: false
text: expanded ? "Hide Details" : "Compare Options"
label: expanded ? "Hide Details" : "Details"
onClicked: expanded = !expanded
}
}
// Expandable candidate details
// Expandable reviewed details.
ColumnLayout {
Layout.fillWidth: true
visible: detailsBtn && detailsBtn.expanded
spacing: 4
Label {
text: "Resolved Source: " + (modelData.data ? modelData.data.backend + " (" + modelData.data.source + ")" : "")
Layout.fillWidth: true
wrapMode: Text.Wrap
visible: modelData.data ? !!modelData.data.recommendation : false
text: modelData.data ? modelData.data.recommendation : ""
color: Theme.text
font.pixelSize: 12
}
Label {
text: "Source: " + (modelData.data ? (modelData.data.source || "-") : "-")
color: Theme.muted
font.pixelSize: 12
}
Label {
text: "Plan Digest: " + (modelData.data ? modelData.data.digest : "")
Layout.fillWidth: true
wrapMode: Text.Wrap
visible: modelData.data && modelData.data.effects && modelData.data.effects.length > 0
text: {
if (!modelData.data || !modelData.data.effects)
return "";
return "Effects: " + modelData.data.effects.map(e => (e.kind || "?") + " " + e.target).join(", ");
}
color: Theme.muted
font.pixelSize: 12
}
Label {
Layout.fillWidth: true
wrapMode: Text.Wrap
visible: modelData.data && modelData.data.warnings && modelData.data.warnings.length > 0
text: modelData.data ? "Warnings: " + (modelData.data.warnings || []).join("; ") : ""
color: Theme.warning
font.pixelSize: 12
}
Label {
Layout.fillWidth: true
wrapMode: Text.Wrap
text: "Plan digest: " + (modelData.data ? (modelData.data.digest || "") : "")
color: Theme.muted
font.pixelSize: 11
}
}
// Completed follow-up action
Label {
Layout.fillWidth: true
wrapMode: Text.Wrap
visible: modelData.data && modelData.data.state === "executing"
text: "Executing the approved plan…"
color: Theme.accent
font.pixelSize: 12
}
Label {
Layout.fillWidth: true
wrapMode: Text.Wrap
visible: modelData.data && modelData.data.state === "failed"
text: "Failed: " + (modelData.data && modelData.data.error ? modelData.data.error : "unknown error")
color: Theme.warning
font.pixelSize: 12
}
Label {
Layout.fillWidth: true
wrapMode: Text.Wrap
visible: modelData.data && modelData.data.state === "cancelled"
text: "Cancelled — no changes were made."
color: Theme.muted
font.pixelSize: 12
}
Label {
Layout.fillWidth: true
wrapMode: Text.Wrap
visible: modelData.data && modelData.data.state === "completed"
text: modelData.data && modelData.data.verification ? modelData.data.verification : "Completed successfully."
color: Theme.text
font.pixelSize: 12
}
// Offer launch only when the service identified
// a concrete desktop entry/command.
RowLayout {
Layout.fillWidth: true
visible: modelData.data && modelData.data.completed && modelData.data.application
visible: modelData.data && modelData.data.state === "completed" && modelData.data.launch
spacing: 8
PhoebusButton {
text: "Launch " + (modelData.data ? modelData.data.application : "App")
label: "Launch application"
primary: true
onClicked: shell.launchApplication(modelData.data.application)
onClicked: shell.launchFromMessage(index)
}
}
}
@ -363,14 +507,20 @@ ShellRoot {
}
PhoebusButton {
text: "Send"
label: "Send"
primary: true
enabled: !shell.busy && promptField.text.trim().length > 0
actionEnabled: !shell.busy && promptField.text.trim().length > 0
onClicked: {
shell.submitPrompt(promptField.text);
promptField.text = "";
}
}
PhoebusButton {
label: "Clear History"
actionEnabled: !shell.busy
onClicked: shell.clearConversation()
}
}
}
@ -446,11 +596,11 @@ ShellRoot {
RowLayout {
Layout.fillWidth: true
PhoebusButton {
text: "Refresh Updates"
label: "Refresh Updates"
onClicked: refreshStatus()
}
PhoebusButton {
text: "Apply All Updates"
label: "Apply All Updates"
primary: true
onClicked: shell.submitPrompt("update system")
}
@ -497,16 +647,20 @@ ShellRoot {
}
PhoebusButton {
text: "Install Explicitly"
label: "Install Explicitly"
primary: true
enabled: legacyAppField.text.trim().length > 0
actionEnabled: legacyAppField.text.trim().length > 0
onClicked: {
const app = legacyAppField.text.trim();
const lane = legacyLaneCombo.currentText;
shell.statusText = "Resolving legacy install...";
AssistantBridge.legacyInstall(app, lane, reply => {
if (reply.ok) {
shell.executePlan(reply.result);
// Show the reviewed plan and require approval;
// never execute merely because it was planned.
shell.currentTab = "assistant";
addMessage("assistant", "Legacy plan for " + app + " (" + lane + ").", reply.result);
shell.statusText = "Legacy plan ready for review";
} else {
shell.statusText = "Error: " + reply.error;
}
@ -534,8 +688,8 @@ ShellRoot {
}
PhoebusButton {
text: "Execute Command"
enabled: legacyPhraseField.text.trim().length > 0
label: "Execute Command"
actionEnabled: legacyPhraseField.text.trim().length > 0
onClicked: {
const p = legacyPhraseField.text.trim();
AssistantBridge.legacyExecute(p, null, true, reply => {
@ -620,7 +774,7 @@ ShellRoot {
spacing: 8
PhoebusButton {
text: "Act: " + (modelData.suggested_phrase || "Fix")
label: "Act: " + (modelData.suggested_phrase || "Fix")
primary: true
visible: modelData.suggested_phrase !== null
onClicked: {
@ -630,14 +784,14 @@ ShellRoot {
}
PhoebusButton {
text: "Snooze 1h"
label: "Snooze 1h"
onClicked: {
AssistantBridge.snoozeAlerts(3600, () => refreshStatus());
}
}
PhoebusButton {
text: "Dismiss"
label: "Dismiss"
onClicked: {
AssistantBridge.dismissAlert(modelData.fingerprint, () => refreshStatus());
}
@ -680,7 +834,7 @@ ShellRoot {
}
PhoebusButton {
text: "Save Preferences"
label: "Save Preferences"
primary: true
onClicked: {
if (shell.preferences) {