Skip to content

Craft Anything: understand how any software works, and craft your own.

Rust

Choose an agent app's program in Settings → AI (#117)

BFlat1a199ec531d5
diff --git a/apps/craft-anything-cli/src/ai_cmd.rs b/apps/craft-anything-cli/src/ai_cmd.rs
index 952b7ac1..6f61e150 100644
--- a/apps/craft-anything-cli/src/ai_cmd.rs
+++ b/apps/craft-anything-cli/src/ai_cmd.rs
@@ -56,6 +56,9 @@ pub enum AiCommand {
On { name: String },
/// Turn a backend off: nothing uses it, and it keeps its settings and key.
Off { name: String },
+ /// Set the program an agent app runs, when it's installed where it isn't found (leave the
+ /// path out to find it by its usual name again).
+ Program { name: String, path: Option<String> },
/// Send a tiny request and report latency.
Test { name: String },
/// Choose the backend that builds (leave the name out to go back to automatic).
@@ -239,6 +242,13 @@ pub fn ai(cli: &Cli, c: &AiCommand, f: Format) -> u8 {
Err(e) => fail(&e, f),
}
}
+ AiCommand::Program { name, path } => match hub.set_command(name, path.as_deref()) {
+ Ok(found) => {
+ emit(&json!({"name": name, "program": path, "found": found}), f);
+ if found { 0 } else { 1 }
+ }
+ Err(e) => fail(&e, f),
+ },
AiCommand::Builder { name } => match hub.set_role(craft_anything_ai::Role::Builder, name.as_deref()) {
Ok(()) => {
emit(&json!({"builder": name}), f);
diff --git a/crates/ai/src/cli_agents/acp.rs b/crates/ai/src/cli_agents/acp.rs
index 28cda5ed..a65a89b6 100644
--- a/crates/ai/src/cli_agents/acp.rs
+++ b/crates/ai/src/cli_agents/acp.rs
@@ -503,7 +503,7 @@ impl AcpConversation {
}
})
.label(name.clone())
- .remediation(format!("Install {name} or set its path in Settings → AI."))
+ .remediation(format!("Install {name}, or choose its program in Settings → AI."))
.spawn()?;
let stdin = proc.take_stdin();
self.proc = Some(proc);
diff --git a/crates/ai/src/cli_agents/mod.rs b/crates/ai/src/cli_agents/mod.rs
index c8360d59..456d7026 100644
--- a/crates/ai/src/cli_agents/mod.rs
+++ b/crates/ai/src/cli_agents/mod.rs
@@ -469,7 +469,7 @@ fn run_cli(spec: &CliSpec, text: &str, tx: &Sender<AgentEvent>, stop: &Stop, ses
let _ = tx_err.send(AgentEvent::Output { text: l.to_string() });
}
})
- .remediation(format!("Install {} or set its path in Settings → AI.", display_for(&agent)));
+ .remediation(format!("Install {}, or choose its program in Settings → AI.", display_for(&agent)));
if let Some(p) = spec.project.as_ref().filter(|_| remote.is_none()) {
proc = proc.cwd(p);
}
diff --git a/crates/ai/src/lib.rs b/crates/ai/src/lib.rs
index 4bcfa08d..60035706 100644
--- a/crates/ai/src/lib.rs
+++ b/crates/ai/src/lib.rs
@@ -360,6 +360,21 @@ impl AiHub {
Ok(true)
}
+ /// The program an agent app runs (`None` or empty: found by its usual name, on PATH and in the
+ /// usual install folders). Returns false when there was no such backend.
+ pub fn set_command(&self, name: &str, command: Option<&str>) -> Result<bool, ToolError> {
+ let mut cfg = self.config();
+ let Some(b) = cfg.backends.iter_mut().find(|b| b.config.name == name) else { return Ok(false) };
+ b.options.command = command.map(str::trim).filter(|c| !c.is_empty()).map(str::to_string);
+ self.save_config(&cfg)?;
+ Ok(true)
+ }
+
+ /// The program each agent app set to one runs, by backend name.
+ pub fn commands(&self) -> std::collections::BTreeMap<String, String> {
+ self.config().backends.into_iter().filter_map(|b| Some((b.config.name, b.options.command?))).collect()
+ }
+
/// Remove a backend and its stored key. Returns false when there was no such backend.
pub fn remove_backend(&self, name: &str) -> Result<bool, ToolError> {
let mut cfg = self.config();
diff --git a/crates/ai/src/tests.rs b/crates/ai/src/tests.rs
index afaabe9a..11115b0e 100644
--- a/crates/ai/src/tests.rs
+++ b/crates/ai/src/tests.rs
@@ -159,6 +159,19 @@ fn the_person_chooses_who_builds() {
assert_eq!(h.chosen(Role::Builder), None, "back to automatic");
}
+/// #53: an agent app installed where it isn't looked for gets its program set (and cleared).
+#[test]
+fn an_agent_apps_program_is_set_and_cleared() {
+ let (h, _d) = hub();
+ add(&h, "OpenCode", BackendKind::AgentCli, "http://127.0.0.1:9", None);
+ assert!(h.commands().is_empty());
+ assert!(h.set_command("OpenCode", Some(" /opt/oc/bin/opencode ")).unwrap());
+ assert_eq!(h.commands().get("OpenCode").map(String::as_str), Some("/opt/oc/bin/opencode"));
+ assert!(!h.set_command("Nobody", Some("/x")).unwrap(), "only a configured backend");
+ assert!(h.set_command("OpenCode", Some(" ")).unwrap());
+ assert!(h.commands().is_empty(), "blank finds it by its usual name again");
+}
+
fn add(h: &AiHub, name: &str, kind: BackendKind, base: &str, key: Option<&str>) {
h.add_backend(
BackendConfig { name: name.into(), kind, model: String::new(), base_url: Some(base.into()), ssh_host: None, enabled: true },
diff --git a/crates/ui-egui/src/builders.rs b/crates/ui-egui/src/builders.rs
index 87700c05..da685f0b 100644
--- a/crates/ui-egui/src/builders.rs
+++ b/crates/ui-egui/src/builders.rs
@@ -83,6 +83,15 @@ impl CraftApp {
});
}
+ /// Run an agent app from this program (`None`: find it by its usual name again).
+ pub fn set_agent_program(&mut self, name: &str, program: Option<String>) {
+ let (hub, name) = (self.hub.clone(), name.to_string());
+ self.jobs.spawn(tr("Set an AI's program"), false, move |_| {
+ hub.set_command(&name, program.as_deref()).map_err(|e| e.message)?;
+ Ok(crate::backends(&hub))
+ });
+ }
+
/// Remove an AI and its stored key.
pub fn remove_backend(&mut self, name: &str) {
let (hub, name) = (self.hub.clone(), name.to_string());
diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs
index 977a8cf9..49016405 100644
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@ -151,8 +151,9 @@ pub enum Done {
result: Result<Value, ToolError>,
},
Detected(Vec<Detected>),
- /// The configured backends, and the ones chosen to build with and to extract with.
- Backends(Vec<BackendConfig>, Option<String>, Option<String>),
+ /// The configured backends, the ones chosen to build with and to extract with, and the
+ /// program each agent app set to one runs.
+ Backends(Vec<BackendConfig>, Option<String>, Option<String>, std::collections::BTreeMap<String, String>),
Picked {
pick: Pick,
path: Option<PathBuf>,
@@ -241,6 +242,8 @@ pub enum Pick {
GameFolder,
/// Where to save a picture from a game.
SavePicture,
+ /// The program an agent app runs ([`CraftApp::picking_program_for`] says which).
+ AgentProgram,
}
/// One open target, as the UI shows it.
@@ -326,6 +329,10 @@ pub struct CraftApp {
pub jobs: jobs::Jobs<Done>,
pub conversation: Option<Box<dyn Conversation>>,
pub backends: Vec<BackendConfig>,
+ /// The program each agent app set to one runs, by backend name (Settings → AI).
+ pub agent_programs: std::collections::BTreeMap<String, String>,
+ /// The agent app whose program the file dialog is choosing.
+ pub picking_program_for: Option<String>,
/// The backend the person chose to build with (Settings → AI), if any.
pub builder: Option<String>,
/// The backend chosen to take a game's files out in Deep mode, if any.
@@ -416,6 +423,8 @@ impl CraftApp {
jobs: jobs::Jobs::default(),
conversation: None,
backends: Vec::new(),
+ agent_programs: Default::default(),
+ picking_program_for: None,
builder: None,
extractor: None,
detected: None,
@@ -917,6 +926,7 @@ impl CraftApp {
Pick::ExtraProjectsDir => pollster::block_on(d.set_title(tr("Pick a folder with projects in it")).pick_folder()),
Pick::GameFolder => pollster::block_on(d.set_title(tr("Pick the game's folder")).pick_folder()),
Pick::SavePicture => pollster::block_on(d.set_title(tr("Save the picture")).add_filter("PNG", &["png"]).set_file_name(&suggested).save_file()),
+ Pick::AgentProgram => pollster::block_on(d.set_title(tr("Where is the program?")).pick_file()),
Pick::Pictures | Pick::Attach => None,
};
Ok(Done::Picked { pick, path: handle.map(|h| h.path().to_path_buf()) })
@@ -1252,13 +1262,14 @@ impl CraftApp {
self.log(false, format!("Found {} AI option(s) on this computer", d.len()));
self.detected = Some(d);
}
- Done::Backends(b, builder, extractor) => {
+ Done::Backends(b, builder, extractor, programs) => {
if self.state.backend.as_ref().is_some_and(|n| !b.iter().any(|c| &c.name == n)) {
self.state.backend = None;
}
self.backends = b;
self.builder = builder;
self.extractor = extractor;
+ self.agent_programs = programs;
}
Done::BackendAdded { name, result } => match result {
Ok(()) => {
@@ -1292,6 +1303,11 @@ impl CraftApp {
Pick::ExtraProjectsDir => self.add_project_folder(path),
Pick::GameFolder => game_files::folder_picked(self, path),
Pick::SavePicture => game_files::save_to(self, path),
+ Pick::AgentProgram => {
+ if let Some(name) = self.picking_program_for.take() {
+ self.set_agent_program(&name, Some(path.display().to_string()));
+ }
+ }
// Several files: these come back as Done::Pictures / Done::ToAttach.
Pick::Pictures | Pick::Attach => {}
}
@@ -1604,7 +1620,7 @@ pub fn app_icon(size: f32) -> egui::Image<'static> {
/// Run an action; a panic is logged and swallowed so one bad action never takes the app down.
/// The configured backends and the ones chosen to build and to extract (read off the UI thread).
pub(crate) fn backends(hub: &AiHub) -> Done {
- Done::Backends(hub.backends(), hub.chosen(craft_anything_ai::Role::Builder), hub.chosen(craft_anything_ai::Role::Extractor))
+ Done::Backends(hub.backends(), hub.chosen(craft_anything_ai::Role::Builder), hub.chosen(craft_anything_ai::Role::Extractor), hub.commands())
}
pub fn guard<R>(what: &str, f: impl FnOnce() -> R) -> Option<R> {
diff --git a/crates/ui-egui/src/settings_ui.rs b/crates/ui-egui/src/settings_ui.rs
index 3077d96b..6df0e5e3 100644
--- a/crates/ui-egui/src/settings_ui.rs
+++ b/crates/ui-egui/src/settings_ui.rs
@@ -305,6 +305,7 @@ fn ai(app: &mut CraftApp, ui: &mut Ui) {
ui.label(RichText::new(tr("No AI is set up yet. The built-in engines still work; an AI adds plain-words answers.")).color(t.text_dim));
}
let (mut pick, mut builds, mut extracts, mut toggle, mut remove) = (None, None, None, None, None);
+ let (mut choose_program, mut usual_program) = (None, None);
// The AI whose Remove was pressed once: asked again before its key is deleted.
let confirm_id = egui::Id::new("remove-ai");
let confirming: Option<String> = ui.data(|d| d.get_temp(confirm_id));
@@ -325,6 +326,23 @@ fn ai(app: &mut CraftApp, ui: &mut Ui) {
)
.truncate(),
);
+ // An agent app on this computer: which program runs it, for one installed
+ // where it isn't looked for (#53).
+ if b.kind == BackendKind::AgentCli && b.ssh_host.as_deref().is_none_or(|h| h.trim().is_empty()) {
+ let program = app.agent_programs.get(&b.name);
+ ui.horizontal_wrapped(|ui| {
+ // The links at the caption's size, so the line reads as one.
+ ui.style_mut().override_font_id = Some(egui::FontId::proportional(theme::CAPTION));
+ let text = program.map_or_else(|| tr("Program: found automatically"), |p| trf("Program: {path}", &[("path", p)]));
+ ui.add(egui::Label::new(RichText::new(text).color(t.text_faint).size(theme::CAPTION)).truncate());
+ if widgets::link(ui, "Choose…").clicked() {
+ choose_program = Some(b.name.clone());
+ }
+ if program.is_some() && widgets::link(ui, "Find it automatically").clicked() {
+ usual_program = Some(b.name.clone());
+ }
+ });
+ }
});
});
ui.add_space(6.0);
@@ -386,6 +404,13 @@ fn ai(app: &mut CraftApp, ui: &mut Ui) {
if let Some((name, on)) = toggle {
app.set_backend_enabled(&name, on);
}
+ if let Some(name) = choose_program {
+ app.picking_program_for = Some(name);
+ app.pick(Pick::AgentProgram);
+ }
+ if let Some(name) = usual_program {
+ app.set_agent_program(&name, None);
+ }
if let Some(name) = remove {
ui.data_mut(|d| d.remove::<String>(confirm_id));
app.remove_backend(&name);
diff --git a/crates/ui-egui/tests/headless_parity.rs b/crates/ui-egui/tests/headless_parity.rs
index 3e6f1f37..23925d3f 100644
--- a/crates/ui-egui/tests/headless_parity.rs
+++ b/crates/ui-egui/tests/headless_parity.rs
@@ -47,6 +47,7 @@ const ACTIONS: &[Action] = &[
a("start_make", "start a new project from the Home prompt", Cli("rebuild <target> <request> --build-with --backend --generate-assets")),
a("set_backend_enabled", "turn an AI on or off", Cli("ai on <name> / ai off <name>")),
a("remove_backend", "remove an AI and its key", Cli("ai remove <name>")),
+ a("set_agent_program", "run an agent app from a program it isn't found as", Cli("ai program <name> <path>")),
a("refresh_projects", "list the projects", Tool(&["project_list"])),
a("remember_project", "keep a project in a picked folder in the list", Tool(&["rebuild_start"])),
a("add_project_folder", "list projects from another folder too", Tool(&["settings_set"])),
diff --git a/crates/ui-egui/tests/smoke.rs b/crates/ui-egui/tests/smoke.rs
index 9d6be990..93ccdbe2 100644
--- a/crates/ui-egui/tests/smoke.rs
+++ b/crates/ui-egui/tests/smoke.rs
@@ -917,6 +917,32 @@ fn command_palette_opens_and_lists_tools() {
assert!(!h.state().state.palette.open);
}
+/// #53: an agent app installed where it isn't looked for gets its program chosen in Settings → AI,
+/// and goes back to being found by its usual name.
+#[test]
+fn an_agent_apps_program_is_set_in_settings() {
+ use craft_anything_ai::{BackendConfig, BackendKind};
+ let mut h = harness(|| {
+ let a = demo::app(demo::engine(Mode::Experienced, true));
+ let cfg =
+ BackendConfig { name: "OpenCode".into(), kind: BackendKind::AgentCli, model: "opencode".into(), base_url: None, ssh_host: None, enabled: true };
+ a.hub.add_backend(cfg, None).unwrap();
+ a
+ });
+ h.state_mut().refresh_backends();
+ assert!(wait(&mut h, |a| a.backends.iter().any(|b| b.name == "OpenCode")));
+ h.state_mut().state.settings_open = true;
+ h.state_mut().state.settings_tab = craft_anything_ui_egui::state::SettingsTab::Ai;
+ h.run_steps(2);
+ h.get_by_label("Program: found automatically");
+ h.state_mut().set_agent_program("OpenCode", Some("/opt/oc/opencode".into()));
+ assert!(wait(&mut h, |a| a.agent_programs.get("OpenCode").map(String::as_str) == Some("/opt/oc/opencode")));
+ h.run_steps(2);
+ h.get_by_label("Program: /opt/oc/opencode");
+ h.get_by_label("Find it automatically").click();
+ assert!(wait(&mut h, |a| a.agent_programs.is_empty()));
+}
+
#[test]
fn settings_window_tabs_draw() {
let mut h = harness(|| {