From 093571cfe4149463f323fd6048a6ce58bbe710ac Mon Sep 17 00:00:00 2001 From: bherbruck Date: Sun, 25 Oct 2026 13:51:55 +0000 Subject: [PATCH] Connect AI apps at start-up, with a preference to turn it off (#6388) At launch the app adds the solidcraft entry to each installed AI client off the window thread, names newly connected clients once, and refreshes a stale path. Settings > Assistant has "Make SolidCraft available to AI apps on this computer" (on by default); off removes the entries it added. Entries the user changed are left alone; automation runs never touch the files. Co-authored-by: Claude Opus 5.5 --- apps/solidcraft/src/main.rs | 4 + assets/locales/en.json | 3 + assets/locales/ja.json | 3 + assets/locales/zh.json | 3 + crates/engine/src/agent_setup.rs | 150 ++++++++++++++++++--- crates/ui-egui/src/agent_chat/settings.rs | 3 + crates/ui-egui/src/ai_connect.rs | 156 ++++++++++++++++++++++ crates/ui-egui/src/lib.rs | 5 + crates/ui-egui/src/prefs.rs | 3 + docs/mcp.md | 6 + 10 files changed, 320 insertions(+), 16 deletions(-) create mode 100644 crates/ui-egui/src/ai_connect.rs diff --git a/apps/solidcraft/src/main.rs b/apps/solidcraft/src/main.rs index 5386eb523..e053850fd 100644 --- a/apps/solidcraft/src/main.rs +++ b/apps/solidcraft/src/main.rs @@ -114,6 +114,10 @@ impl eframe::App for App { // A DMG install has no installer step: put solidcraft-cli on PATH, quietly. #[cfg(target_os = "macos")] std::thread::spawn(solidcraft_ui_egui::cli_link::install_on_launch); + // Automation runs (a control port was asked for) leave the user's AI apps alone. + if !self.take_focus_unwanted { + solidcraft_ui_egui::ai_connect::begin(&mut self.solve); + } if let Some(dir) = self.starting.take() { startup::started(&dir); } diff --git a/assets/locales/en.json b/assets/locales/en.json index fbe714e08..81019ef28 100644 --- a/assets/locales/en.json +++ b/assets/locales/en.json @@ -606,10 +606,13 @@ "Z angle": "Z angle", "Z distance": "Z distance", "Zebra": "Zebra", + "ai.connected_toast": "SolidCraft is now available in {clients}. Restart them to use it (Settings > Assistant).", "ai.prefs.allow_control": "Let AI agents connect (control channel / MCP)", "ai.prefs.allow_control_note": "Opens a control channel on this computer only (127.0.0.1, port 27878 or the next free one). A program that connects must also show a secret token that only your user account can read, made fresh at every start. Takes effect the next time SolidCraft starts. Off: nothing listens unless you start SolidCraft with --control.", "ai.prefs.availability": "Assistant controls", "ai.prefs.background_commands": "Run agent commands in the background", + "ai.prefs.connect_apps": "Make SolidCraft available to AI apps on this computer", + "ai.prefs.connect_apps_note": "When SolidCraft starts, adds it as an MCP server to the AI apps found on this computer (OpenCode, Claude Desktop, Claude Code, Cursor, Codex, Gemini CLI, Copilot CLI, Windsurf, Zed, VS Code), so an agent can use it without any setup. Only the solidcraft entry is added or its path refreshed; an entry you changed is left alone, and the file is backed up first. Off: the entries it added are removed. Help > Connect AI assistants… does this by hand.", "ai.prefs.follow_camera": "Turn the camera to sketches", "ai.prefs.follow_camera_off": "Automatic camera following is off.", "ai.prefs.follow_camera_on": "The camera turns to face sketches the agent creates.", diff --git a/assets/locales/ja.json b/assets/locales/ja.json index 93a3993b7..12881aa74 100644 --- a/assets/locales/ja.json +++ b/assets/locales/ja.json @@ -606,10 +606,13 @@ "Z angle": "Z角度", "Z distance": "Z距離", "Zebra": "ゼブラ", + "ai.connected_toast": "SolidCraft が {clients} で使えるようになりました。使うには再起動してください(設定 > アシスタント)。", "ai.prefs.allow_control": "AI エージェントの接続を許可(コントロールチャンネル / MCP)", "ai.prefs.allow_control_note": "このコンピューター内だけのコントロールチャンネル(127.0.0.1、ポート 27878 または次に空いているポート)を開きます。接続するプログラムは、起動のたびに作られ、あなたのユーザーアカウントだけが読める秘密のトークンも提示する必要があります。次に SolidCraft を起動したときから有効です。オフ:--control を付けて起動しない限り、何も待ち受けません。", "ai.prefs.availability": "アシスタントの操作", "ai.prefs.background_commands": "エージェントのコマンドをバックグラウンドで実行", + "ai.prefs.connect_apps": "このコンピューターの AI アプリで SolidCraft を使えるようにする", + "ai.prefs.connect_apps_note": "SolidCraft の起動時に、このコンピューターで見つかった AI アプリ(OpenCode、Claude Desktop、Claude Code、Cursor、Codex、Gemini CLI、Copilot CLI、Windsurf、Zed、VS Code)へ MCP サーバーとして追加します。追加または更新するのは solidcraft のエントリのみで、変更済みのエントリには触れず、ファイルは先にバックアップされます。オフにすると追加したエントリを削除します。", "ai.prefs.follow_camera": "カメラをスケッチに向ける", "ai.prefs.follow_camera_off": "カメラの自動追従はオフです。", "ai.prefs.follow_camera_on": "エージェントが作成するスケッチにカメラを向けます。", diff --git a/assets/locales/zh.json b/assets/locales/zh.json index af7c4aca4..38a877e57 100644 --- a/assets/locales/zh.json +++ b/assets/locales/zh.json @@ -606,10 +606,13 @@ "Z angle": "Z 角度", "Z distance": "Z 距离", "Zebra": "斑马纹", + "ai.connected_toast": "SolidCraft 现已可在 {clients} 中使用。请重启它们(设置 > 助手)。", "ai.prefs.allow_control": "允许 AI 代理连接(控制通道 / MCP)", "ai.prefs.allow_control_note": "仅在本机开放控制通道(127.0.0.1,端口 27878 或下一个空闲端口)。连接的程序还必须出示一个每次启动时新生成、只有你的用户账户能读取的秘密令牌。下次启动 SolidCraft 时生效。关闭:除非用 --control 启动,否则不监听任何端口。", "ai.prefs.availability": "助手控制", "ai.prefs.background_commands": "在后台执行代理命令", + "ai.prefs.connect_apps": "让此电脑上的 AI 应用可以使用 SolidCraft", + "ai.prefs.connect_apps_note": "SolidCraft 启动时,会把自己作为 MCP 服务器添加到此电脑上找到的 AI 应用(OpenCode、Claude Desktop、Claude Code、Cursor、Codex、Gemini CLI、Copilot CLI、Windsurf、Zed、VS Code)。只添加或更新 solidcraft 条目;你修改过的条目不会被改动,文件会先备份。关闭后,会删除它添加的条目。", "ai.prefs.follow_camera": "将相机转向草图", "ai.prefs.follow_camera_off": "相机自动跟随已关闭。", "ai.prefs.follow_camera_on": "相机将转向代理创建的草图。", diff --git a/crates/engine/src/agent_setup.rs b/crates/engine/src/agent_setup.rs index 49f04eec8..8dbed63ad 100644 --- a/crates/engine/src/agent_setup.rs +++ b/crates/engine/src/agent_setup.rs @@ -429,18 +429,42 @@ fn insert_member(text: &mut String, obj: &Obj, key: &str, value: &Value) { } } +/// Delete member `i` of `obj` from the text, with its comma. +fn remove_member(text: &mut String, obj: &Obj, i: usize) { + let Some(m) = obj.members.get(i) else { return }; + if let Some(next) = obj.members.get(i + 1) { + text.replace_range(m.key_at..next.key_at, ""); + } else if i > 0 + && let Some(prev) = obj.members.get(i - 1) + { + text.replace_range(prev.val.1..m.val.1, ""); + } else { + text.replace_range(obj.open + 1..obj.close, ""); + } +} + /// What happened to one server entry. #[derive(Debug, PartialEq)] enum Change { Added, Updated, Unchanged, + /// Taken out (a SolidCraft entry of ours). + Removed, /// Not touched, because the user's own entry is there. Custom, } +/// What a run does with the entries. +#[derive(Clone, Copy, PartialEq)] +enum Mode { + Add, + /// Take out the entries setup wrote (the user's own are left). + Remove, +} + /// Set the entries in the JSON text, in the object under the top-level `list_key`. -fn edit_json(text: &mut String, shape: Shape, exe: &str, live: bool) -> Result, String> { +fn edit_json(text: &mut String, shape: Shape, exe: &str, live: bool, mode: Mode) -> Result, String> { let mut out = Vec::new(); let key = shape.list_key(); if text.trim().is_empty() { @@ -451,6 +475,7 @@ fn edit_json(text: &mut String, shape: Shape, exe: &str, live: bool) -> Result m.val.0, Some(_) => return Err(format!("`{key}` is not a JSON object")), + None if mode == Mode::Remove => return Ok(Vec::new()), None => { insert_member(text, &root, key, &json!({})); let root = root_object(text)?; @@ -468,6 +493,12 @@ fn edit_json(text: &mut String, shape: Shape, exe: &str, live: bool) -> Result judge(parsed.as_ref(), exe, &args), }; let change = match (verdict, existing) { + (Verdict::Add, _) if mode == Mode::Remove => continue, + (Verdict::Same | Verdict::Stale, Some(_)) if mode == Mode::Remove => { + let at = obj.members.iter().position(|m| m.key == name).unwrap_or(0); + remove_member(text, &obj, at); + Change::Removed + } (Verdict::Add, _) => { insert_member(text, &obj, name, &new); Change::Added @@ -492,7 +523,7 @@ fn edit_json(text: &mut String, shape: Shape, exe: &str, live: bool) -> Result Result, String> { +fn edit_toml(text: &mut String, exe: &str, live: bool, mode: Mode) -> Result, String> { use toml_edit::{Array, DocumentMut, Item, Table, value}; let mut doc: DocumentMut = text.parse().map_err(|e: toml_edit::TomlError| e.to_string())?; let mut out = Vec::new(); @@ -513,6 +544,13 @@ fn edit_toml(text: &mut String, exe: &str, live: bool) -> Result None, }; let change = match judge(existing.as_ref(), exe, &args) { + Verdict::Add if mode == Mode::Remove => continue, + Verdict::Same | Verdict::Stale if mode == Mode::Remove => { + if let Some(t) = doc.get_mut("mcp_servers").and_then(Item::as_table_mut) { + t.remove(name); + } + Change::Removed + } Verdict::Add => { let mut t = Table::new(); t["command"] = value(exe); @@ -566,7 +604,7 @@ fn toml_to_json(t: &toml_edit::Table) -> Value { // --------------------------------------------------------------------------------------------- /// One client's outcome, a line of the report. -fn configure_file(t: &Target, exe: &str, live: bool, dry_run: bool) -> Result { +fn configure_file(t: &Target, exe: &str, live: bool, dry_run: bool, mode: Mode) -> Result<(String, Vec<(&'static str, Change)>), String> { let fail = |e: String| format!("{}: {e}; left unchanged", t.file.display()); let existing = match std::fs::read_to_string(&t.file) { Ok(s) => Some(s), @@ -574,33 +612,39 @@ fn configure_file(t: &Target, exe: &str, live: bool, dry_run: bool) -> Result return Err(format!("{}: {e}", t.file.display())), }; let mut text = existing.clone().unwrap_or_default(); - let changes = if t.shape == Shape::Codex { edit_toml(&mut text, exe, live) } else { edit_json(&mut text, t.shape, exe, live) }.map_err(fail)?; + let changes = + if t.shape == Shape::Codex { edit_toml(&mut text, exe, live, mode) } else { edit_json(&mut text, t.shape, exe, live, mode) }.map_err(fail)?; let said: Vec = changes .iter() .map(|(name, c)| match c { Change::Added => format!("added {name}"), Change::Updated => format!("updated the path of {name}"), Change::Unchanged => format!("{name} already set up"), + Change::Removed => format!("removed {name}"), Change::Custom => format!("{name} left as you have it (it is not a plain SolidCraft entry)"), }) .collect(); let said = said.join(", "); let changed = existing.as_deref() != Some(text.as_str()); + let done = |m: String| Ok((m, changes)); if dry_run { - return Ok(if changed { format!("would write {} ({said}):\n{text}", t.file.display()) } else { format!("no change needed ({said})") }); + return done(if changed { format!("would write {} ({said}):\n{text}", t.file.display()) } else { format!("no change needed ({said})") }); } if !changed { - return Ok(said); + return done(said); } if existing.is_some() { let mut bak = t.file.clone().into_os_string(); bak.push(".bak"); - std::fs::copy(&t.file, &bak).map_err(|e| format!("{}: cannot back up: {e}", t.file.display()))?; + // The first backup is the user's original: later runs keep it. + if !Path::new(&bak).exists() { + std::fs::copy(&t.file, &bak).map_err(|e| format!("{}: cannot back up: {e}", t.file.display()))?; + } } else if let Some(dir) = t.file.parent() { std::fs::create_dir_all(dir).map_err(|e| format!("{}: {e}", dir.display()))?; } std::fs::write(&t.file, text).map_err(|e| format!("{}: {e}", t.file.display()))?; - Ok(format!("{said} ({})", t.file.display())) + done(format!("{said} ({})", t.file.display())) } /// Set up every detected client (or `--client NAME`; flags `--dry-run`, `--live`) for the @@ -627,8 +671,8 @@ pub fn setup(args: &[String], env: &Env, exe: &str) -> Result<(Vec, bool let mut lines = Vec::new(); let mut ok = true; for t in detect(env, only) { - match configure_file(&t, exe, live, dry_run) { - Ok(m) => lines.push(format!("{}: {m}", t.client)), + match configure_file(&t, exe, live, dry_run, Mode::Add) { + Ok((m, _)) => lines.push(format!("{}: {m}", t.client)), Err(e) => { ok = false; lines.push(format!("{}: failed: {e}", t.client)); @@ -644,6 +688,33 @@ pub fn setup(args: &[String], env: &Env, exe: &str) -> Result<(Vec, bool Ok((lines, ok)) } +/// What a quiet run did: the clients that got a new entry, and the ones that took one out. +#[derive(Debug, Default, PartialEq)] +pub struct Quiet { + pub added: Vec<&'static str>, + pub removed: Vec<&'static str>, +} + +/// Make `solidcraft-cli` at `exe` available to every installed client (`Mode::Add`), or take +/// the entries setup wrote out of them again (`remove`). Quiet and best effort, for the app: a +/// client that fails is skipped. The rules for the user's own entries are the same as `setup`'s. +pub fn quiet(env: &Env, exe: &str, remove: bool) -> Quiet { + let mode = if remove { Mode::Remove } else { Mode::Add }; + let mut q = Quiet::default(); + for t in detect(env, None) { + // Adding writes `solidcraft` only (plain `mcp` finds the app by itself); removing also + // takes out a `solidcraft-live` that is ours. + let Ok((_, changes)) = configure_file(&t, exe, remove, false, mode) else { continue }; + if changes.iter().any(|(n, c)| *n == "solidcraft" && *c == Change::Added) { + q.added.push(t.client); + } + if changes.iter().any(|(_, c)| *c == Change::Removed) { + q.removed.push(t.client); + } + } + q +} + #[cfg(test)] mod tests { use super::*; @@ -652,7 +723,7 @@ mod tests { fn edit(text: &str, shape: Shape) -> (String, Vec<(&'static str, Change)>) { let mut t = text.to_owned(); - let c = edit_json(&mut t, shape, EXE, false).unwrap(); + let c = edit_json(&mut t, shape, EXE, false, Mode::Add).unwrap(); (t, c) } @@ -721,7 +792,7 @@ mod tests { #[test] fn broken_json_is_an_error() { for bad in ["[1]", "{\"a\": ", "{\"a\": 1} x", "{\"mcpServers\": 3}"] { - assert!(edit_json(&mut bad.to_owned(), Shape::McpServers, EXE, false).is_err(), "{bad}"); + assert!(edit_json(&mut bad.to_owned(), Shape::McpServers, EXE, false, Mode::Add).is_err(), "{bad}"); } } @@ -729,21 +800,68 @@ mod tests { fn codex_toml_keeps_comments_and_other_tables() { let src = "# my codex\nmodel = \"x\"\n\n[mcp_servers.other]\ncommand = \"o\" # mine\n"; let mut t = src.to_owned(); - let c = edit_toml(&mut t, EXE, true).unwrap(); + let c = edit_toml(&mut t, EXE, true, Mode::Add).unwrap(); assert_eq!(c, [("solidcraft", Change::Added), ("solidcraft-live", Change::Added)]); assert!(t.starts_with(src), "{t}"); assert!(t.contains("[mcp_servers.solidcraft]") && t.contains(&format!("command = \"{EXE}\"")), "{t}"); // Stale path, then a user-changed entry. let mut stale = "[mcp_servers.solidcraft]\ncommand = \"/old/solidcraft-cli\"\nargs = [\"mcp\"]\nstartup_timeout_sec = 30\n".to_owned(); - assert_eq!(edit_toml(&mut stale, EXE, false).unwrap(), [("solidcraft", Change::Updated)]); + assert_eq!(edit_toml(&mut stale, EXE, false, Mode::Add).unwrap(), [("solidcraft", Change::Updated)]); assert!(stale.contains("startup_timeout_sec = 30") && stale.contains(EXE), "{stale}"); let mut custom = "[mcp_servers.solidcraft]\ncommand = \"/x/solidcraft-cli\"\nargs = [\"mcp\", \"--headless\"]\n".to_owned(); let before = custom.clone(); - assert_eq!(edit_toml(&mut custom, EXE, false).unwrap(), [("solidcraft", Change::Custom)]); + assert_eq!(edit_toml(&mut custom, EXE, false, Mode::Add).unwrap(), [("solidcraft", Change::Custom)]); assert_eq!(custom, before); // An empty file works too. let mut empty = String::new(); - edit_toml(&mut empty, EXE, false).unwrap(); + edit_toml(&mut empty, EXE, false, Mode::Add).unwrap(); assert!(empty.contains("[mcp_servers.solidcraft]"), "{empty}"); } + + #[test] + fn removing_takes_out_only_our_entries_and_keeps_the_rest() { + let src = "{\n \"mcpServers\": {\n \"a\": {\"command\": \"x\"},\n \"solidcraft\": {\"command\": \"/old/solidcraft-cli\", \"args\": [\"mcp\"]},\n \"solidcraft-live\": {\"command\": \"/old/solidcraft-cli\", \"args\": [\"mcp\", \"--connect\", \"127.0.0.1:7878\"]}\n },\n \"k\": 1\n}\n"; + let mut t = src.to_owned(); + let c = edit_json(&mut t, Shape::McpServers, EXE, true, Mode::Remove).unwrap(); + assert_eq!(c, [("solidcraft", Change::Removed), ("solidcraft-live", Change::Removed)]); + let v: Value = serde_json::from_str(&t).unwrap(); + assert_eq!(v, json!({"mcpServers": {"a": {"command": "x"}}, "k": 1})); + // The user's own entry stays. + let mut mine = r#"{"mcpServers": {"solidcraft": {"command": "node", "args": ["mcp"]}}}"#.to_owned(); + let before = mine.clone(); + assert_eq!(edit_json(&mut mine, Shape::McpServers, EXE, true, Mode::Remove).unwrap(), [("solidcraft", Change::Custom)]); + assert_eq!(mine.trim_end(), before); + // Nothing there: nothing happens, no list is created. + let mut none = "{\"k\": 1}".to_owned(); + assert!(edit_json(&mut none, Shape::McpServers, EXE, true, Mode::Remove).unwrap().is_empty()); + assert_eq!(none.trim_end(), "{\"k\": 1}"); + // TOML. + let mut toml = + "[mcp_servers.other]\ncommand = \"o\"\n\n[mcp_servers.solidcraft]\ncommand = \"/old/solidcraft-cli\"\nargs = [\"mcp\"]\n".to_owned(); + assert_eq!(edit_toml(&mut toml, EXE, false, Mode::Remove).unwrap(), [("solidcraft", Change::Removed)]); + assert!(toml.contains("[mcp_servers.other]") && !toml.contains("solidcraft"), "{toml}"); + } + + #[test] + fn quiet_adds_only_the_plain_entry_and_names_new_clients_once() { + let h = std::env::temp_dir().join(format!("solidcraft-quiet-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&h); + std::fs::create_dir_all(h.join(".cursor")).unwrap(); + std::fs::create_dir_all(h.join(".gemini")).unwrap(); + let env = Env { home: Some(h.clone()), appdata: None, local_appdata: None, xdg_config: Some(h.join("xdg")), codex_home: None }; + let q = quiet(&env, EXE, false); + assert_eq!(q.added, ["cursor", "gemini"]); + let t = std::fs::read_to_string(h.join(".cursor/mcp.json")).unwrap(); + assert!(t.contains("\"solidcraft\"") && !t.contains("solidcraft-live"), "{t}"); + // A second run changes nothing and names nobody. + assert_eq!(quiet(&env, EXE, false), Quiet::default()); + // An old path is refreshed without being called new. + std::fs::write(h.join(".cursor/mcp.json"), t.replace(EXE, "/gone/solidcraft-cli")).unwrap(); + assert_eq!(quiet(&env, EXE, false), Quiet::default()); + assert!(std::fs::read_to_string(h.join(".cursor/mcp.json")).unwrap().contains(EXE)); + // Turning it off takes the entries out again. + assert_eq!(quiet(&env, EXE, true).removed, ["cursor", "gemini"]); + assert!(!std::fs::read_to_string(h.join(".cursor/mcp.json")).unwrap().contains("solidcraft")); + let _ = std::fs::remove_dir_all(&h); + } } diff --git a/crates/ui-egui/src/agent_chat/settings.rs b/crates/ui-egui/src/agent_chat/settings.rs index 4c10d4d96..58a8c06fd 100644 --- a/crates/ui-egui/src/agent_chat/settings.rs +++ b/crates/ui-egui/src/agent_chat/settings.rs @@ -154,6 +154,9 @@ pub fn page(app: &mut SolveApp, ui: &mut egui::Ui) { let response = ui_kit::checkbox(ui, tr("ai.prefs.allow_control"), &mut app.preferences.agent_control) .on_hover_text(tr("ai.prefs.allow_control_note")); crate::scenario::publish_handle("prefs:agent_control", response.rect.center()); + let response = ui_kit::checkbox(ui, tr("ai.prefs.connect_apps"), &mut app.preferences.connect_ai_apps) + .on_hover_text(tr("ai.prefs.connect_apps_note")); + crate::scenario::publish_handle("prefs:connect_ai_apps", response.rect.center()); } if cfg!(target_arch = "wasm32") { ui_kit::text(ui, tr("ui.agent_chat_desktop_only"), ui_kit::Text::Hint("desktop")); diff --git a/crates/ui-egui/src/ai_connect.rs b/crates/ui-egui/src/ai_connect.rs new file mode 100644 index 000000000..2314c241b --- /dev/null +++ b/crates/ui-egui/src/ai_connect.rs @@ -0,0 +1,156 @@ +//! Makes SolidCraft available to the AI apps on this computer without a step from the user: at +//! start-up, off the window thread, the `solidcraft` entry is added to each installed client +//! (`solidcraft_engine::agent_setup`), and a status message names the clients that got it for the +//! first time. The preference "Make SolidCraft available to AI apps on this computer" turns it +//! off, which takes the entries out again. Best effort: nothing here can fail the launch. + +use crate::SolveApp; + +/// What the app keeps between frames. +#[derive(Default)] +pub struct State { + /// The host asked for this (`begin`); tests and automation runs never do, so they never + /// touch the user's client files. + armed: bool, + /// The preference as last acted on. + applied: Option, + job: Option>>, +} + +/// Start managing the client files for this run (the desktop app's normal launch). +pub fn begin(app: &mut SolveApp) { + app.ai_connect.armed = !cfg!(target_arch = "wasm32"); +} + +/// The clients already announced, so a client is named once however often its entry is made again. +fn announced_file() -> Option { + solidcraft_engine::recovery::data_dir().map(|d| d.join("ai-apps-connected.json")) +} + +fn read_announced(path: &std::path::Path) -> Vec { + std::fs::read_to_string(path).ok().and_then(|s| serde_json::from_str(&s).ok()).unwrap_or_default() +} + +/// The clients in `added` that were not announced before, and the list to save. +pub fn new_clients(announced: &[String], added: &[&str]) -> (Vec, Vec) { + let fresh: Vec = added.iter().filter(|c| !announced.iter().any(|a| a == *c)).map(|c| (*c).to_owned()).collect(); + let mut all = announced.to_vec(); + all.extend(fresh.iter().cloned()); + (fresh, all) +} + +/// How a client is named to the user. +pub fn client_name(id: &str) -> &str { + match id { + "opencode" => "OpenCode", + "claude-desktop" => "Claude Desktop", + "claude-code" => "Claude Code", + "cursor" => "Cursor", + "codex" => "Codex", + "gemini" => "Gemini CLI", + "copilot" => "Copilot CLI", + "windsurf" => "Windsurf", + "zed" => "Zed", + "vscode" => "VS Code", + other => other, + } +} + +#[cfg(not(target_arch = "wasm32"))] +fn spawn(remove: bool) -> Option>> { + use solidcraft_engine::agent_setup as setup; + let cli = crate::agent_chat::find_cli()?; + let cli = setup::plain_path(&cli.canonicalize().unwrap_or(cli)); + let (tx, rx) = std::sync::mpsc::channel(); + std::thread::Builder::new() + .name("ai-connect".into()) + .spawn(move || { + let q = setup::quiet(&setup::Env::from_process(), &cli, remove); + if remove { + // Turned off: the next time it is on, the clients are news again. + if let Some(f) = announced_file() { + let _ = std::fs::remove_file(f); + } + let _ = tx.send(Vec::new()); + } else { + let _ = tx.send(q.added); + } + }) + .ok()?; + Some(rx) +} + +#[cfg(target_arch = "wasm32")] +fn spawn(_remove: bool) -> Option>> { + None +} + +/// Every frame: start the job when the preference differs from what was last done, and report +/// what a finished one found. +pub fn tick(app: &mut SolveApp) { + if !app.ai_connect.armed { + return; + } + let want = app.preferences.connect_ai_apps; + if app.ai_connect.job.is_none() && app.ai_connect.applied != Some(want) { + // At the first frame, off means nothing to do: entries are removed when it is turned off. + let remove = !want; + let first = app.ai_connect.applied.is_none(); + app.ai_connect.applied = Some(want); + if !(remove && first) { + app.ai_connect.job = spawn(remove); + } + } + let Some(rx) = &app.ai_connect.job else { return }; + match rx.try_recv() { + Ok(added) => { + app.ai_connect.job = None; + if added.is_empty() { + return; + } + let Some(file) = announced_file() else { return }; + let (fresh, all) = new_clients(&read_announced(&file), &added); + if fresh.is_empty() { + return; + } + if let Some(dir) = file.parent() { + let _ = std::fs::create_dir_all(dir); + } + let _ = std::fs::write(&file, serde_json::to_string(&all).unwrap_or_default()); + let names = fresh.iter().map(|c| client_name(c)).collect::>().join(", "); + app.set_status(crate::i18n::format("ai.connected_toast", &[("clients", &names)]), false); + } + Err(std::sync::mpsc::TryRecvError::Empty) => {} + Err(std::sync::mpsc::TryRecvError::Disconnected) => app.ai_connect.job = None, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_client_is_named_once() { + let (fresh, all) = new_clients(&[], &["cursor", "codex"]); + assert_eq!(fresh, ["cursor", "codex"]); + let (fresh, all) = new_clients(&all, &["cursor", "zed"]); + assert_eq!(fresh, ["zed"]); + assert_eq!(all, ["cursor", "codex", "zed"]); + assert!(new_clients(&all, &["cursor"]).0.is_empty()); + } + + #[test] + fn nothing_runs_unless_the_host_asked() { + let mut app = SolveApp::new(Default::default(), Default::default()); + tick(&mut app); + assert!(app.ai_connect.applied.is_none() && app.ai_connect.job.is_none()); + } + + #[test] + fn it_is_on_by_default_and_saved_off_stays_off() { + assert!(crate::prefs::Prefs::default().connect_ai_apps); + let mut app = SolveApp::new(Default::default(), Default::default()); + app.load_prefs(&serde_json::json!({ "preferences": { "connect_ai_apps": false } }).to_string()); + assert!(!app.preferences.connect_ai_apps); + } +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 042b4b9d7..b5d898a15 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -12,6 +12,7 @@ use crate::ui_kit::{Container, Surface}; pub mod access; pub mod agent_chat; pub mod agent_cursor; +pub mod ai_connect; pub mod bom_panel; pub mod browser; pub mod browser_canvas; @@ -520,6 +521,8 @@ pub struct SolveApp { pub agent: agent_cursor::AgentCursor, /// The agent chat panel (docs/design/in-app-agent-chat.md). pub agent_chat: agent_chat::AgentChat, + /// Making SolidCraft available to the AI apps installed here ([`ai_connect`]). + pub ai_connect: ai_connect::State, pending_shots: Vec<(u64, Option, std::sync::mpsc::Sender, f64)>, shot_chat_turns: std::collections::HashMap>, queued_shots: Vec<(u64, f64, u32)>, @@ -643,6 +646,7 @@ impl SolveApp { synthetic_mods: egui::Modifiers::default(), control_rx: None, agent_chat: Default::default(), + ai_connect: Default::default(), control_held: Default::default(), control_job: None, control_answering: Vec::new(), @@ -725,6 +729,7 @@ impl SolveApp { self.render_workspace.defer_path_host(key, move || solidcraft_gpu::path::host_on_adapter(&adapter).map_err(|e| e.to_string())); } render_workspace::sync_backend(self); + ai_connect::tick(self); self.msaa_supported = rs.msaa_supported.clone(); let info = rs.adapter.get_info(); self.help.gpu = Some(format!("{} ({:?}, {:?})", info.name.trim(), info.backend, info.device_type)); diff --git a/crates/ui-egui/src/prefs.rs b/crates/ui-egui/src/prefs.rs index cf93af5af..02cb2ba5d 100644 --- a/crates/ui-egui/src/prefs.rs +++ b/crates/ui-egui/src/prefs.rs @@ -633,6 +633,9 @@ preference_settings! { /// Let AI agents connect: the localhost control channel (MCP) opens on the default port at /// start-up, unless `--control`/`SOLIDCRAFT_CONTROL_PORT` name one. Read at start-up. agent_control: bool = true, PAGE_AI; + /// Add SolidCraft's MCP server to the AI apps installed on this computer at start-up + /// ([`crate::ai_connect`]); off takes the entries out again. + connect_ai_apps: bool = true, PAGE_AI; /// Agents the user added (the installed ones are found by themselves). API keys are never /// here: they live in the system keychain. agents: Vec = Vec::new(); diff --git a/docs/mcp.md b/docs/mcp.md index cc1957ee1..10f6f2456 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -167,6 +167,12 @@ refreshes the path of an entry it wrote; an entry you changed (extra arguments, is left as you have it. `--live` also adds `solidcraft-live`, which bridges to the open app (port 7878, see below). Restart the client afterwards. +SolidCraft also does this by itself: when the app starts it adds the `solidcraft` entry to each +installed client (and refreshes its path after an update), and says once which clients it +connected. It never touches an entry you changed. **Settings > Assistant > Make SolidCraft +available to AI apps on this computer** turns it off, which removes the entries it added. Runs +with `--control` or `SOLIDCRAFT_CONTROL_PORT` (automation) leave your clients alone. + To configure a client by hand instead, these are the entries. OpenCode (`opencode.json`): ```json