diff --git a/apps/photocraft-cli/tests/cli.rs b/apps/photocraft-cli/tests/cli.rs index a215e10a7a..1ce5b38008 100644 --- a/apps/photocraft-cli/tests/cli.rs +++ b/apps/photocraft-cli/tests/cli.rs @@ -759,6 +759,10 @@ fn mcp_install_writes_the_live_entry() { let entry = &v["mcpServers"]["photocraft"]; assert_eq!(entry["args"], json!(["mcp", "--live"]), "{out}"); assert!(entry["command"].as_str().unwrap().contains("photocraft-cli"), "{out}"); + // Cursor never opened here: nothing is written, and the error says what to do. + let o = bin().args(["mcp", "install", "--client", "cursor"]).env("HOME", &home).env("USERPROFILE", &home).output().unwrap(); + assert!(!o.status.success() && String::from_utf8_lossy(&o.stderr).contains("open it once"), "{o:?}"); + assert!(!home.join(".cursor").exists()); let cursor = home.join(".cursor/mcp.json"); std::fs::create_dir_all(cursor.parent().unwrap()).unwrap(); std::fs::write(&cursor, r#"{"mcpServers": {"other": {"command": "x"}}}"#).unwrap(); diff --git a/crates/automation/src/agent_link.rs b/crates/automation/src/agent_link.rs index ba2991f7df..fcee4f8722 100644 --- a/crates/automation/src/agent_link.rs +++ b/crates/automation/src/agent_link.rs @@ -228,72 +228,176 @@ pub struct ClientEnv { pub home: Option, /// `%APPDATA%` (Windows). pub appdata: Option, + /// `%LOCALAPPDATA%` (Windows): Microsoft Store (MSIX) installs keep their settings in + /// `Packages` there. + pub local_appdata: Option, /// `$XDG_CONFIG_HOME` (Linux). pub xdg_config: Option, /// `$PATH`, searched for the `claude` command. pub path: Option, } +/// The platform whose settings locations apply: a parameter, so tests cover all three. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Platform { + Mac, + Windows, + Other, +} + +impl Platform { + const CURRENT: Platform = if cfg!(target_os = "macos") { + Platform::Mac + } else if cfg!(windows) { + Platform::Windows + } else { + Platform::Other + }; +} + +/// Where one install of a client keeps its MCP servers: `file`, in `folder`, which the client +/// creates when it first starts (so a missing folder means the client isn't set up there). +struct Location { + folder: PathBuf, + file: PathBuf, +} + +const CLAUDE_DESKTOP_CONFIG: &str = "claude_desktop_config.json"; + +/// Microsoft Store (MSIX) packages of Claude Desktop, by folder-name prefix in +/// `%LOCALAPPDATA%\Packages`. Windows redirects a packaged app's `%APPDATA%` into its package +/// (`LocalCache\Roaming`), so such an install reads its configuration there and never sees +/// `%APPDATA%\Claude`. +const CLAUDE_PACKAGE_PREFIXES: [&str; 2] = ["Claude_", "Anthropic.Claude"]; + impl ClientEnv { pub fn from_env() -> Self { let var = |k: &str| std::env::var_os(k).filter(|v| !v.is_empty()); ClientEnv { - home: var("HOME").or_else(|| var("USERPROFILE")).map(PathBuf::from), + // Windows apps (Cursor, Claude) use the profile folder; `HOME` there is often a Unix + // shell's (Git Bash, MSYS) and can point elsewhere. + home: if cfg!(windows) { var("USERPROFILE").or_else(|| var("HOME")) } else { var("HOME").or_else(|| var("USERPROFILE")) }.map(PathBuf::from), appdata: var("APPDATA").map(PathBuf::from), + local_appdata: var("LOCALAPPDATA").map(PathBuf::from), xdg_config: var("XDG_CONFIG_HOME").map(PathBuf::from), path: var("PATH"), } } - /// Where `client` keeps its MCP servers in a JSON file (`None` for Claude Code, which is - /// configured through its own command, and for [`Client::Json`]). - pub fn config_file(&self, client: Client) -> Option { - match client { - Client::ClaudeDesktop if cfg!(target_os = "macos") => { - self.home.as_ref().map(|h| h.join("Library/Application Support/Claude/claude_desktop_config.json")) + /// The JSON files `client`'s installs on this computer read their MCP servers from (empty for + /// Claude Code, which is configured through its own command, for [`Client::Json`], and when + /// the client isn't set up here). + pub fn config_files(&self, client: Client) -> Vec { + self.config_files_on(client, Platform::CURRENT) + } + + fn config_files_on(&self, client: Client, platform: Platform) -> Vec { + self.locations(client, platform).into_iter().filter(|l| l.folder.is_dir()).map(|l| l.file).collect() + } + + fn locations(&self, client: Client, platform: Platform) -> Vec { + let at = |folder: PathBuf, name: &str| Location { file: folder.join(name), folder }; + match (client, platform) { + (Client::ClaudeDesktop, Platform::Mac) => { + self.home.iter().map(|h| at(h.join("Library").join("Application Support").join("Claude"), CLAUDE_DESKTOP_CONFIG)).collect() } - Client::ClaudeDesktop if cfg!(windows) => self.appdata.as_ref().map(|a| a.join("Claude").join("claude_desktop_config.json")), - Client::ClaudeDesktop => { - self.xdg_config.clone().or_else(|| self.home.as_ref().map(|h| h.join(".config"))).map(|c| c.join("Claude").join("claude_desktop_config.json")) + (Client::ClaudeDesktop, Platform::Windows) => { + let packaged = self + .claude_packages() + .into_iter() + .map(|package| Location { file: package.join("LocalCache").join("Roaming").join("Claude").join(CLAUDE_DESKTOP_CONFIG), folder: package }); + packaged.chain(self.appdata.iter().map(|a| at(a.join("Claude"), CLAUDE_DESKTOP_CONFIG))).collect() } - Client::Cursor => self.home.as_ref().map(|h| h.join(".cursor").join("mcp.json")), - Client::ClaudeCode | Client::Json => None, + (Client::ClaudeDesktop, Platform::Other) => self + .xdg_config + .clone() + .or_else(|| self.home.as_ref().map(|h| h.join(".config"))) + .into_iter() + .map(|c| at(c.join("Claude"), CLAUDE_DESKTOP_CONFIG)) + .collect(), + (Client::Cursor, _) => self.home.iter().map(|h| at(h.join(".cursor"), "mcp.json")).collect(), + (Client::ClaudeCode | Client::Json, _) => Vec::new(), } } + /// Claude Desktop's Microsoft Store packages ([`CLAUDE_PACKAGE_PREFIXES`]). + fn claude_packages(&self) -> Vec { + let Some(packages) = self.local_appdata.as_ref().map(|l| l.join("Packages")) else { return Vec::new() }; + let Ok(entries) = std::fs::read_dir(packages) else { return Vec::new() }; + let mut found: Vec = entries + .flatten() + .filter(|e| CLAUDE_PACKAGE_PREFIXES.iter().any(|p| e.file_name().to_string_lossy().starts_with(p))) + .map(|e| e.path()) + .filter(|p| p.is_dir()) + .collect(); + found.sort(); + found + } + /// The `claude` command: on `PATH`, else where its installers put it (an app started from /// the Dock or Start menu has a minimal `PATH`). pub fn claude_command(&self) -> Option { - let exe = if cfg!(windows) { "claude.exe" } else { "claude" }; - let on_path = self.path.iter().flat_map(std::env::split_paths).map(|d| d.join(exe)); - let known = self.home.iter().flat_map(|h| [h.join(".local/bin").join(exe), h.join(".claude/local").join(exe)]); - let system = ["/opt/homebrew/bin/claude", "/usr/local/bin/claude"].map(PathBuf::from).into_iter().filter(|_| !cfg!(windows)); - on_path.chain(known).chain(system).find(|p| p.is_file()) + self.claude_command_on(Platform::CURRENT) + } + + fn claude_command_on(&self, platform: Platform) -> Option { + // Windows: the native installer's `claude.exe`, or npm's `claude.cmd` script. + let names: &[&str] = if platform == Platform::Windows { &["claude.exe", "claude.cmd"] } else { &["claude"] }; + let on_path: Vec = self.path.iter().flat_map(std::env::split_paths).flat_map(|d| names.iter().map(move |n| d.join(n))).collect(); + let mut known: Vec = Vec::new(); + if let Some(h) = &self.home { + let native = h.join(".local").join("bin"); + known.extend(names.iter().map(|n| native.join(n))); + known.push(h.join(".claude").join("local").join(names[0])); + } + if platform == Platform::Windows { + known.extend(self.appdata.iter().map(|a| a.join("npm").join("claude.cmd"))); + } else { + known.extend(["/opt/homebrew/bin/claude", "/usr/local/bin/claude"].map(PathBuf::from)); + } + on_path.into_iter().chain(known).find(|p| p.is_file()) } } /// What [`install`] did, for the user. #[derive(Clone, Debug, PartialEq, Eq)] pub enum Installed { - /// Wrote `file` (the previous version is kept beside it as `backup`). - File { file: PathBuf, backup: Option, unchanged: bool }, - /// Ran `claude mcp add-json`. + /// Wrote the configuration of each install of the client found (Claude Desktop on Windows + /// can have a Microsoft Store one and a classic one). + Files(Vec), + /// Ran `claude mcp add`. ClaudeCode, /// The configuration to paste. Json(String), } +/// One configuration file [`install`] wrote. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Written { + pub file: PathBuf, + /// The previous version, kept beside it. + pub backup: Option, + /// It already started PhotoCraft this way, so it was left alone. + pub unchanged: bool, +} + impl Installed { /// One sentence for a status line or the terminal. pub fn message(&self, client: Client) -> String { let restart = match client { - Client::ClaudeDesktop => " Restart Claude Desktop to connect.", - Client::Cursor => " Cursor picks it up in Settings › MCP.", + Client::ClaudeDesktop => " Quit Claude Desktop completely (not just its window) and open it again to connect.", + Client::Cursor => " Restart Cursor to connect; PhotoCraft then shows under Customize › MCPs.", _ => "", }; match self { - Installed::File { file, unchanged: true, .. } => format!("{} already starts PhotoCraft ({}).{restart}", client.name(), file.display()), - Installed::File { file, .. } => format!("Added PhotoCraft to {} ({}).{restart}", client.name(), file.display()), + Installed::Files(files) => { + let list = files.iter().map(|w| w.file.display().to_string()).collect::>().join("; "); + if files.iter().all(|w| w.unchanged) { + format!("{} already starts PhotoCraft ({list}).{restart}", client.name()) + } else { + format!("Added PhotoCraft to {} ({list}).{restart}", client.name()) + } + } Installed::ClaudeCode => "Added PhotoCraft to Claude Code (user scope). Start a new Claude Code session to connect.".into(), Installed::Json(text) => text.clone(), } @@ -303,19 +407,35 @@ impl Installed { /// Add PhotoCraft (started by `launch`) to `client`'s MCP servers, replacing an older /// `photocraft` entry and keeping everything else in its configuration. pub fn install(client: Client, launch: &McpLaunch, env: &ClientEnv) -> Result { + install_on(client, launch, env, Platform::CURRENT) +} + +fn install_on(client: Client, launch: &McpLaunch, env: &ClientEnv, platform: Platform) -> Result { match client { Client::Json => Ok(Installed::Json(launch.config_json())), Client::ClaudeCode => install_claude_code(launch, env), Client::ClaudeDesktop | Client::Cursor => { - let file = - env.config_file(client).ok_or_else(|| AutomationError::Other(format!("can't find {}'s settings folder (no home folder)", client.name())))?; - merge_into_file(&file, launch) + let files = env.config_files_on(client, platform); + if files.is_empty() { + return Err(not_set_up(client, &env.locations(client, platform))); + } + files.iter().map(|file| merge_into_file(file, launch)).collect::>().map(Installed::Files) } } } +/// No install of `client` found: writing a configuration nobody reads would look like success. +fn not_set_up(client: Client, looked: &[Location]) -> AutomationError { + let name = client.name(); + if looked.is_empty() { + return AutomationError::Other(format!("can't find {name}'s settings folder (no home folder)")); + } + let folders = looked.iter().map(|l| l.folder.display().to_string()).collect::>().join(" or "); + AutomationError::Other(format!("{name} isn't set up on this computer (no {folders} folder): install it and open it once, then try again")) +} + /// Merge the `photocraft` entry into a JSON configuration with an `mcpServers` object. -fn merge_into_file(file: &Path, launch: &McpLaunch) -> Result { +fn merge_into_file(file: &Path, launch: &McpLaunch) -> Result { let existing = read_small(file)?; let mut root = match existing.as_deref().map(str::trim) { None | Some("") => Map::new(), @@ -331,7 +451,7 @@ fn merge_into_file(file: &Path, launch: &McpLaunch) -> Result Result None, }; photocraft_format::atomic_write(file, format!("{text}\n").as_bytes()).map_err(|e| io_error(file, e))?; - Ok(Installed::File { file: file.to_path_buf(), backup, unchanged: false }) + Ok(Written { file: file.to_path_buf(), backup, unchanged: false }) } fn install_claude_code(launch: &McpLaunch, env: &ClientEnv) -> Result { - let claude = env.claude_command().ok_or_else(|| { - AutomationError::Other(format!( - "the `claude` command wasn't found; run this in a terminal instead: claude mcp add --scope user {SERVER_NAME} -- {}", - launch.shell_line() - )) - })?; - let entry = json!({"type": "stdio", "command": launch.command, "args": launch.args}); + let by_hand = format!("claude mcp add --scope user {SERVER_NAME} -- {}", launch.shell_line()); + let claude = + env.claude_command().ok_or_else(|| AutomationError::Other(format!("the `claude` command wasn't found; run this in a terminal instead: {by_hand}")))?; + // npm installs `claude` as a Node script, and Node sits beside it (nvm, Homebrew): put that + // folder first on `PATH`, which is minimal for an app started from the Dock or Start menu. + let path = std::env::join_paths(claude.parent().map(Path::to_path_buf).into_iter().chain(env.path.iter().flat_map(std::env::split_paths))).ok(); let run = |args: &[&str]| { - std::process::Command::new(&claude) - .args(args) - .stdin(std::process::Stdio::null()) - .output() - .map_err(|e| AutomationError::Other(format!("{}: {e}", claude.display()))) + let mut c = std::process::Command::new(&claude); + c.args(args).stdin(std::process::Stdio::null()); + if let Some(p) = &path { + c.env("PATH", p); + } + c.output() }; - // `add-json` refuses a name that exists: replace an older entry (ours, by name). + // `add` refuses a name that exists: replace an older entry (ours, by name). let _ = run(&["mcp", "remove", "--scope", "user", SERVER_NAME]); - let out = run(&["mcp", "add-json", "--scope", "user", SERVER_NAME, &entry.to_string()])?; - if out.status.success() { - Ok(Installed::ClaudeCode) - } else { - let why = String::from_utf8_lossy(if out.stderr.is_empty() { &out.stdout } else { &out.stderr }).trim().to_string(); - Err(AutomationError::Other(format!("claude mcp add-json failed: {why}"))) - } + let mut add = vec!["mcp", "add", "--scope", "user", SERVER_NAME, "--", launch.command.as_str()]; + add.extend(launch.args.iter().map(String::as_str)); + let why = match run(&add) { + Ok(out) if out.status.success() => return Ok(Installed::ClaudeCode), + Ok(out) => String::from_utf8_lossy(if out.stderr.is_empty() { &out.stdout } else { &out.stderr }).trim().to_string(), + Err(e) => format!("{}: {e}", claude.display()), + }; + Err(AutomationError::Other(format!("adding PhotoCraft to Claude Code failed ({why}); run this in a terminal instead: {by_hand}"))) } #[cfg(test)] @@ -393,7 +514,13 @@ mod tests { } fn env_at(home: &Path) -> ClientEnv { - ClientEnv { home: Some(home.to_path_buf()), appdata: Some(home.join("AppData")), xdg_config: None, path: None } + ClientEnv { + home: Some(home.to_path_buf()), + appdata: Some(home.join("AppData").join("Roaming")), + local_appdata: Some(home.join("AppData").join("Local")), + xdg_config: None, + path: None, + } } #[test] @@ -479,30 +606,84 @@ mod tests { #[test] fn install_adds_the_entry_and_keeps_other_servers_and_settings() { - let home = temp("install"); - let env = env_at(&home); let launch = McpLaunch::cli(Path::new("/opt/PhotoCraft/photocraft-cli")); - for client in [Client::ClaudeDesktop, Client::Cursor] { - let file = env.config_file(client).unwrap(); - assert!(file.starts_with(&home), "{}", file.display()); - // A fresh install creates the file. - let first = install(client, &launch, &env).unwrap(); - assert_eq!(first, Installed::File { file: file.clone(), backup: None, unchanged: false }); - let v: Value = serde_json::from_str(&std::fs::read_to_string(&file).unwrap()).unwrap(); - assert_eq!(v["mcpServers"]["photocraft"], launch.entry()); - // Other servers and settings survive; an old photocraft entry is replaced. - std::fs::write(&file, r#"{"theme": "dark", "mcpServers": {"other": {"command": "x"}, "photocraft": {"command": "old"}}}"#).unwrap(); - let again = install(client, &launch, &env).unwrap(); - let Installed::File { backup: Some(backup), unchanged: false, .. } = &again else { panic!("{again:?}") }; - assert!(std::fs::read_to_string(backup).unwrap().contains("\"old\""), "the previous file is kept"); - let v: Value = serde_json::from_str(&std::fs::read_to_string(&file).unwrap()).unwrap(); - assert_eq!(v["theme"], "dark"); - assert_eq!(v["mcpServers"]["other"]["command"], "x"); - assert_eq!(v["mcpServers"]["photocraft"], launch.entry()); - // Installing again changes nothing. - assert!(matches!(install(client, &launch, &env).unwrap(), Installed::File { unchanged: true, .. })); - assert!(again.message(client).contains(client.name())); + for platform in [Platform::Mac, Platform::Windows, Platform::Other] { + for client in [Client::ClaudeDesktop, Client::Cursor] { + let home = temp("install"); + let env = env_at(&home); + let [location] = &env.locations(client, platform)[..] else { panic!("{client:?} on {platform:?}") }; + let file = location.file.clone(); + assert!(file.starts_with(&home), "{}", file.display()); + // The client created its folder when it first started; a fresh install creates the file. + std::fs::create_dir_all(&location.folder).unwrap(); + let first = install_on(client, &launch, &env, platform).unwrap(); + assert_eq!(first, Installed::Files(vec![Written { file: file.clone(), backup: None, unchanged: false }])); + let v: Value = serde_json::from_str(&std::fs::read_to_string(&file).unwrap()).unwrap(); + assert_eq!(v["mcpServers"]["photocraft"], launch.entry()); + // Other servers and settings survive; an old photocraft entry is replaced. + std::fs::write(&file, r#"{"theme": "dark", "mcpServers": {"other": {"command": "x"}, "photocraft": {"command": "old"}}}"#).unwrap(); + let again = install_on(client, &launch, &env, platform).unwrap(); + let Installed::Files(written) = &again else { panic!("{again:?}") }; + let [Written { backup: Some(backup), unchanged: false, .. }] = &written[..] else { panic!("{again:?}") }; + assert!(std::fs::read_to_string(backup).unwrap().contains("\"old\""), "the previous file is kept"); + let v: Value = serde_json::from_str(&std::fs::read_to_string(&file).unwrap()).unwrap(); + assert_eq!(v["theme"], "dark"); + assert_eq!(v["mcpServers"]["other"]["command"], "x"); + assert_eq!(v["mcpServers"]["photocraft"], launch.entry()); + // Installing again changes nothing. + let same = install_on(client, &launch, &env, platform).unwrap(); + assert!(matches!(&same, Installed::Files(w) if w.iter().all(|w| w.unchanged)), "{same:?}"); + assert!(again.message(client).contains(client.name())); + assert!(same.message(client).contains("already")); + let _ = std::fs::remove_dir_all(&home); + } } + } + + #[test] + fn a_client_that_was_never_opened_gets_no_file_and_an_explanation() { + let launch = McpLaunch::cli(Path::new("/x/photocraft-cli")); + for platform in [Platform::Mac, Platform::Windows, Platform::Other] { + for client in [Client::ClaudeDesktop, Client::Cursor] { + let home = temp("not-set-up"); + let env = env_at(&home); + let e = install_on(client, &launch, &env, platform).unwrap_err().to_string(); + assert!(e.contains(client.name()) && e.contains("open it once"), "{e}"); + assert!(env.locations(client, platform).iter().all(|l| e.contains(&l.folder.display().to_string()) && !l.file.exists()), "{e}"); + let _ = std::fs::remove_dir_all(&home); + } + } + } + + /// Claude Desktop from the Microsoft Store reads `%APPDATA%` inside its package + /// (anthropics/claude-code#26073), so the entry goes there, and to a classic install too. + #[test] + fn claude_desktop_from_the_microsoft_store_gets_the_entry_in_its_package() { + let home = temp("msix"); + let env = env_at(&home); + let launch = McpLaunch::cli(Path::new("C:/PhotoCraft/photocraft-cli.exe")); + let packages = home.join("AppData").join("Local").join("Packages"); + let store = packages.join("Claude_pzs8sxrjxfjjc"); + std::fs::create_dir_all(&store).unwrap(); + std::fs::create_dir_all(packages.join("Microsoft.WindowsCalculator_8wekyb3d8bbwe")).unwrap(); + let packaged = store.join("LocalCache").join("Roaming").join("Claude").join(CLAUDE_DESKTOP_CONFIG); + let classic = home.join("AppData").join("Roaming").join("Claude").join(CLAUDE_DESKTOP_CONFIG); + // Installed from the Store and never opened: the package is enough to know where it reads. + assert_eq!(env.config_files_on(Client::ClaudeDesktop, Platform::Windows), std::slice::from_ref(&packaged)); + let done = install_on(Client::ClaudeDesktop, &launch, &env, Platform::Windows).unwrap(); + assert_eq!(done, Installed::Files(vec![Written { file: packaged.clone(), backup: None, unchanged: false }])); + assert!(!classic.exists(), "no file where this install never looks"); + let v: Value = serde_json::from_str(&std::fs::read_to_string(&packaged).unwrap()).unwrap(); + assert_eq!(v["mcpServers"]["photocraft"], launch.entry()); + // A classic install as well (or Claude's own Edit Config file): both get the entry. + std::fs::create_dir_all(classic.parent().unwrap()).unwrap(); + let both = install_on(Client::ClaudeDesktop, &launch, &env, Platform::Windows).unwrap(); + let Installed::Files(written) = &both else { panic!("{both:?}") }; + assert_eq!(written.iter().map(|w| (w.file.clone(), w.unchanged)).collect::>(), [(packaged.clone(), true), (classic.clone(), false)]); + let message = both.message(Client::ClaudeDesktop); + assert!(message.contains(&packaged.display().to_string()) && message.contains(&classic.display().to_string()), "{message}"); + // Other platforms never look in Packages. + assert!(env.config_files_on(Client::ClaudeDesktop, Platform::Other).is_empty()); let _ = std::fs::remove_dir_all(&home); } @@ -511,7 +692,7 @@ mod tests { let home = temp("install-bad"); let env = env_at(&home); let launch = McpLaunch::cli(Path::new("/x/photocraft-cli")); - let file = env.config_file(Client::Cursor).unwrap(); + let file = home.join(".cursor").join("mcp.json"); std::fs::create_dir_all(file.parent().unwrap()).unwrap(); for text in ["{ broken", "[1, 2]", r#"{"mcpServers": []}"#] { std::fs::write(&file, text).unwrap(); @@ -525,7 +706,7 @@ mod tests { #[test] fn claude_code_without_the_claude_command_names_the_command_to_run() { let home = temp("claude-code"); - let env = ClientEnv { home: Some(home.clone()), appdata: None, xdg_config: None, path: Some(home.join("empty").into_os_string()) }; + let env = ClientEnv { path: Some(home.join("empty").into_os_string()), ..env_at(&home) }; if env.claude_command().is_some() { return; // A system-wide `claude` (Homebrew, /usr/local) is installed here. } @@ -534,10 +715,77 @@ mod tests { let _ = std::fs::remove_dir_all(&home); } + #[test] + fn claude_command_is_found_where_its_installers_put_it() { + let home = temp("claude-find"); + let env = ClientEnv { path: Some(home.join("empty").into_os_string()), ..env_at(&home) }; + let place = |p: PathBuf| { + std::fs::create_dir_all(p.parent().unwrap()).unwrap(); + std::fs::write(&p, "").unwrap(); + p + }; + assert_eq!(env.claude_command_on(Platform::Windows), None); + // npm on Windows: a `claude.cmd` script in %APPDATA%\npm. + let npm = place(home.join("AppData").join("Roaming").join("npm").join("claude.cmd")); + assert_eq!(env.claude_command_on(Platform::Windows), Some(npm)); + // The native installer wins over npm, on every platform. + let native = place(home.join(".local").join("bin").join("claude.exe")); + assert_eq!(env.claude_command_on(Platform::Windows), Some(native)); + let unix = place(home.join(".local").join("bin").join("claude")); + assert_eq!(env.claude_command_on(Platform::Mac), Some(unix)); + // `PATH` first. + let on_path = place(home.join("tools").join("claude.cmd")); + let env = ClientEnv { path: Some(home.join("tools").into_os_string()), ..env_at(&home) }; + assert_eq!(env.claude_command_on(Platform::Windows), Some(on_path)); + let _ = std::fs::remove_dir_all(&home); + } + + /// A fake `claude` records what it was run with: `mcp add` with the launch command after + /// `--`, and its own folder first on `PATH` (where npm's Node is). + #[cfg(unix)] + #[test] + fn claude_code_install_runs_claude_mcp_add() { + use std::os::unix::fs::PermissionsExt; + let home = temp("claude-run"); + let bin = home.join(".local").join("bin"); + std::fs::create_dir_all(&bin).unwrap(); + let log = home.join("calls.txt"); + let fail = home.join("fail"); + let script = format!( + "#!/bin/sh\nprintf 'PATH=%s\\n' \"$PATH\" >> '{log}'\nprintf '%s ' \"$@\" >> '{log}'\nprintf '\\n' >> '{log}'\nif [ \"$2\" = add ] && [ -e '{fail}' ]; then echo 'boom' >&2; exit 1; fi\n", + log = log.display(), + fail = fail.display() + ); + let claude = bin.join("claude"); + std::fs::write(&claude, script).unwrap(); + std::fs::set_permissions(&claude, std::fs::Permissions::from_mode(0o755)).unwrap(); + let env = ClientEnv { path: Some(home.join("empty").into_os_string()), ..env_at(&home) }; + let launch = McpLaunch::cli(Path::new("/x/photocraft-cli")); + // Writing an executable while other test threads fork can briefly leave it busy (ETXTBSY). + let run = || { + for _ in 0..50 { + match install(Client::ClaudeCode, &launch, &env) { + Err(e) if e.to_string().contains("busy") => std::thread::sleep(std::time::Duration::from_millis(20)), + r => return r, + } + } + install(Client::ClaudeCode, &launch, &env) + }; + assert_eq!(run().unwrap(), Installed::ClaudeCode); + let calls = std::fs::read_to_string(&log).unwrap(); + assert!(calls.contains("mcp remove --scope user photocraft \n"), "{calls}"); + assert!(calls.contains("mcp add --scope user photocraft -- /x/photocraft-cli mcp --live \n"), "{calls}"); + assert!(calls.contains(&format!("PATH={}:", bin.display())), "claude's folder comes first: {calls}"); + std::fs::write(&fail, "").unwrap(); + let e = run().unwrap_err().to_string(); + assert!(e.contains("boom") && e.contains("claude mcp add --scope user photocraft -- /x/photocraft-cli mcp --live"), "{e}"); + let _ = std::fs::remove_dir_all(&home); + } + #[test] fn json_client_returns_the_configuration() { let launch = McpLaunch::cli(Path::new("/x/photocraft-cli")); - let env = ClientEnv { home: None, appdata: None, xdg_config: None, path: None }; + let env = ClientEnv { home: None, appdata: None, local_appdata: None, xdg_config: None, path: None }; let Installed::Json(text) = install(Client::Json, &launch, &env).unwrap() else { panic!() }; assert_eq!(text, launch.config_json()); assert!(install(Client::Cursor, &launch, &env).is_err(), "no home folder: an error, not a panic"); diff --git a/crates/automation/src/live.rs b/crates/automation/src/live.rs index 092e86eb16..2225f11dd2 100644 --- a/crates/automation/src/live.rs +++ b/crates/automation/src/live.rs @@ -189,7 +189,14 @@ pub fn launcher(cli: &Path) -> Option { if !app.is_file() { return None; } - Command::new(app) + if cfg!(windows) { + let (program, args) = windows_launch(&app, std::env::var_os("SystemRoot").as_deref()); + let mut c = Command::new(program); + c.args(args); + c + } else { + Command::new(app) + } } } }; @@ -202,6 +209,21 @@ pub fn launcher(cli: &Path) -> Option { })) } +/// How Windows starts the app at `app`: through Explorer, as a double-click would. The app is then +/// no child of the CLI, so it outlives the MCP client ending the CLI's process tree (Claude Code +/// does on Windows), and it runs outside the container of a Microsoft Store client (Claude +/// Desktop): there, new files under `%APPDATA%` land in the client's package, where the app +/// started from the Start menu would never see the settings saved meanwhile. Explorer reads a +/// comma as a separator, so such a path is started directly. (`%WINDIR%` can be empty under a +/// Store client, hence `%SystemRoot%`.) +fn windows_launch(app: &Path, system_root: Option<&std::ffi::OsStr>) -> (PathBuf, Vec) { + if app.to_string_lossy().contains(',') { + return (app.to_path_buf(), Vec::new()); + } + let root = system_root.filter(|r| !r.is_empty()).map_or_else(|| PathBuf::from(r"C:\Windows"), PathBuf::from); + (root.join("explorer.exe"), vec![app.as_os_str().to_os_string()]) +} + /// Keep the app running when the MCP client stops the CLI (and its process group). fn detach(c: &mut std::process::Command) { #[cfg(unix)] @@ -219,3 +241,24 @@ fn detach(c: &mut std::process::Command) { #[cfg(not(any(unix, windows)))] let _ = c; } + +#[cfg(test)] +mod tests { + use super::*; + use std::ffi::OsStr; + + #[test] + fn windows_starts_the_app_through_explorer() { + let app = Path::new(r"C:\Program Files\PhotoCraft\photocraft.exe"); + let (program, args) = windows_launch(app, Some(OsStr::new(r"D:\Win"))); + assert_eq!(program, Path::new(r"D:\Win").join("explorer.exe")); + assert_eq!(args, [app.as_os_str()]); + // No usable %SystemRoot%: the default Windows folder. + let default = Path::new(r"C:\Windows").join("explorer.exe"); + assert_eq!(windows_launch(app, Some(OsStr::new(""))).0, default); + assert_eq!(windows_launch(app, None).0, default); + // Explorer would split this path at the comma. + let comma = Path::new(r"C:\Apps, tools\photocraft.exe"); + assert_eq!(windows_launch(comma, None), (comma.to_path_buf(), Vec::new())); + } +} diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index ae6d69d5eb..7572256351 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -3758,7 +3758,7 @@ navigator Zoom Zvětšení Managed by the launch options (--control). Spravováno parametry spuštění (--control). Agents can connect on 127.0.0.1:{port}. Agenti se mohou připojit na 127.0.0.1:{port}. Off: agents can't connect. Vypnuto: agenti se nemohou připojit. - 0 picks a free port 0 zvolí volný port + 0 picks a free port; AI apps find it by themselves 0 zvolí volný port; aplikace AI si ho najdou samy Folder agents can open from Složka, ze které mohou agenti otevírat Folder agents can save to Složka, do které mohou agenti ukládat When PhotoCraft is closed Když je PhotoCraft zavřený diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 3f170a65a9..c8b0971cec 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -3148,7 +3148,7 @@ curves Smooth Glätten Managed by the launch options (--control). Von den Startoptionen verwaltet (--control). Agents can connect on 127.0.0.1:{port}. Agenten können sich über 127.0.0.1:{port} verbinden. Off: agents can't connect. Aus: Agenten können sich nicht verbinden. - 0 picks a free port 0 wählt einen freien Port + 0 picks a free port; AI apps find it by themselves 0 wählt einen freien Port; KI-Apps finden ihn selbst Folder agents can open from Ordner, aus dem Agenten öffnen dürfen Folder agents can save to Ordner, in den Agenten speichern dürfen When PhotoCraft is closed Wenn PhotoCraft geschlossen ist diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index fafb9b6a7c..10d0118759 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -3848,7 +3848,7 @@ curves Smooth Εξομάλυνση Managed by the launch options (--control). Διαχειρίζεται από τις επιλογές εκκίνησης (--control). Agents can connect on 127.0.0.1:{port}. Οι πράκτορες μπορούν να συνδεθούν στο 127.0.0.1:{port}. Off: agents can't connect. Ανενεργό: οι πράκτορες δεν μπορούν να συνδεθούν. - 0 picks a free port Το 0 επιλέγει μια ελεύθερη θύρα + 0 picks a free port; AI apps find it by themselves Το 0 επιλέγει μια ελεύθερη θύρα· οι εφαρμογές AI τη βρίσκουν μόνες τους Folder agents can open from Φάκελος από τον οποίο ανοίγουν οι πράκτορες Folder agents can save to Φάκελος όπου αποθηκεύουν οι πράκτορες When PhotoCraft is closed Όταν το PhotoCraft είναι κλειστό diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 23e97328bc..7631824906 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -2835,7 +2835,7 @@ curves Smooth Suavizar Managed by the launch options (--control). Gestionado por las opciones de inicio (--control). Agents can connect on 127.0.0.1:{port}. Los agentes pueden conectarse en 127.0.0.1:{port}. Off: agents can't connect. Desactivado: los agentes no pueden conectarse. - 0 picks a free port 0 elige un puerto libre + 0 picks a free port; AI apps find it by themselves 0 elige un puerto libre; las apps de IA lo encuentran solas Folder agents can open from Carpeta desde la que los agentes pueden abrir Folder agents can save to Carpeta en la que los agentes pueden guardar When PhotoCraft is closed Cuando PhotoCraft está cerrado diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 56762f1a0e..3b9262dc22 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -3152,7 +3152,7 @@ curves Smooth Lisser Managed by the launch options (--control). Géré par les options de lancement (--control). Agents can connect on 127.0.0.1:{port}. Les agents peuvent se connecter sur 127.0.0.1:{port}. Off: agents can't connect. Désactivé : les agents ne peuvent pas se connecter. - 0 picks a free port 0 choisit un port libre + 0 picks a free port; AI apps find it by themselves 0 choisit un port libre ; les applications d’IA le trouvent d’elles-mêmes Folder agents can open from Dossier où les agents peuvent ouvrir Folder agents can save to Dossier où les agents peuvent enregistrer When PhotoCraft is closed Quand PhotoCraft est fermé diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 4f33903e2a..af01c0e40c 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -4071,7 +4071,7 @@ cameraRaw Yellow Sárga Managed by the launch options (--control). Az indítási kapcsolók kezelik (--control). Agents can connect on 127.0.0.1:{port}. Az ügynökök a 127.0.0.1:{port} címen csatlakozhatnak. Off: agents can't connect. Ki: az ügynökök nem csatlakozhatnak. - 0 picks a free port 0: szabad port választása + 0 picks a free port; AI apps find it by themselves 0: szabad port választása; az AI-alkalmazások maguktól megtalálják Folder agents can open from Mappa, ahonnan az ügynökök megnyithatnak Folder agents can save to Mappa, ahová az ügynökök menthetnek When PhotoCraft is closed Ha a PhotoCraft be van zárva diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 2190820cec..184d07296e 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -3139,7 +3139,7 @@ curves Smooth Haluskan Managed by the launch options (--control). Dikelola oleh opsi peluncuran (--control). Agents can connect on 127.0.0.1:{port}. Agen dapat terhubung di 127.0.0.1:{port}. Off: agents can't connect. Mati: agen tidak dapat terhubung. - 0 picks a free port 0 memilih port yang bebas + 0 picks a free port; AI apps find it by themselves 0 memilih port yang bebas; aplikasi AI menemukannya sendiri Folder agents can open from Folder tempat agen dapat membuka Folder agents can save to Folder tempat agen dapat menyimpan When PhotoCraft is closed Saat PhotoCraft ditutup diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index cc2c5b7f77..7e4dd88352 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -4113,7 +4113,7 @@ navigator Zoom Zoom Managed by the launch options (--control). Gestito dalle opzioni di avvio (--control). Agents can connect on 127.0.0.1:{port}. Gli agenti possono connettersi su 127.0.0.1:{port}. Off: agents can't connect. Disattivato: gli agenti non possono connettersi. - 0 picks a free port 0 sceglie una porta libera + 0 picks a free port; AI apps find it by themselves 0 sceglie una porta libera; le app di IA la trovano da sole Folder agents can open from Cartella da cui gli agenti possono aprire Folder agents can save to Cartella in cui gli agenti possono salvare When PhotoCraft is closed Quando PhotoCraft è chiuso diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 0a9e47be7b..2636ec97e8 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -3827,7 +3827,7 @@ curves Smooth スムーズ Managed by the launch options (--control). 起動オプションで管理されています (--control)。 Agents can connect on 127.0.0.1:{port}. エージェントは 127.0.0.1:{port} で接続できます。 Off: agents can't connect. オフ:エージェントは接続できません。 - 0 picks a free port 0 で空いているポートを選択 + 0 picks a free port; AI apps find it by themselves 0 で空いているポートを選択(AI アプリが自動で見つけます) Folder agents can open from エージェントが開けるフォルダー Folder agents can save to エージェントが保存できるフォルダー When PhotoCraft is closed PhotoCraft が閉じているとき diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index cf546fd520..72db306a2a 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -3325,7 +3325,7 @@ curves Smooth 매끄럽게 Managed by the launch options (--control). 실행 옵션으로 관리됨 (--control). Agents can connect on 127.0.0.1:{port}. 에이전트가 127.0.0.1:{port}에서 연결할 수 있습니다. Off: agents can't connect. 끔: 에이전트가 연결할 수 없습니다. - 0 picks a free port 0은 빈 포트를 선택 + 0 picks a free port; AI apps find it by themselves 0은 빈 포트를 선택 (AI 앱이 알아서 찾음) Folder agents can open from 에이전트가 열 수 있는 폴더 Folder agents can save to 에이전트가 저장할 수 있는 폴더 When PhotoCraft is closed PhotoCraft가 닫혀 있을 때 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 412dedd8cd..725111554f 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -3910,7 +3910,7 @@ curves Smooth Vloeiend maken Managed by the launch options (--control). Beheerd door de startopties (--control). Agents can connect on 127.0.0.1:{port}. Agents kunnen verbinden via 127.0.0.1:{port}. Off: agents can't connect. Uit: agents kunnen niet verbinden. - 0 picks a free port 0 kiest een vrije poort + 0 picks a free port; AI apps find it by themselves 0 kiest een vrije poort; AI-apps vinden die zelf Folder agents can open from Map waaruit agents mogen openen Folder agents can save to Map waarin agents mogen opslaan When PhotoCraft is closed Als PhotoCraft gesloten is diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index c4896cd6c9..f439bf9906 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -3748,7 +3748,7 @@ curves Smooth Wygładź Managed by the launch options (--control). Zarządzane przez opcje uruchamiania (--control). Agents can connect on 127.0.0.1:{port}. Agenci mogą łączyć się pod adresem 127.0.0.1:{port}. Off: agents can't connect. Wyłączone: agenci nie mogą się łączyć. - 0 picks a free port 0 wybiera wolny port + 0 picks a free port; AI apps find it by themselves 0 wybiera wolny port; aplikacje AI znajdą go same Folder agents can open from Folder, z którego agenci mogą otwierać Folder agents can save to Folder, w którym agenci mogą zapisywać When PhotoCraft is closed Gdy PhotoCraft jest zamknięty diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 23935471f4..6e54802553 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -3940,7 +3940,7 @@ layerLabel No Color Sem cor Managed by the launch options (--control). Gerenciado pelas opções de inicialização (--control). Agents can connect on 127.0.0.1:{port}. Os agentes podem se conectar em 127.0.0.1:{port}. Off: agents can't connect. Desativado: os agentes não podem se conectar. - 0 picks a free port 0 escolhe uma porta livre + 0 picks a free port; AI apps find it by themselves 0 escolhe uma porta livre; os apps de IA a encontram sozinhos Folder agents can open from Pasta da qual os agentes podem abrir Folder agents can save to Pasta na qual os agentes podem salvar When PhotoCraft is closed Quando o PhotoCraft estiver fechado diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 49b37bd389..50af3a9c44 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -3116,7 +3116,7 @@ curves Smooth Сгладить Managed by the launch options (--control). Управляется параметрами запуска (--control). Agents can connect on 127.0.0.1:{port}. Агенты могут подключаться к 127.0.0.1:{port}. Off: agents can't connect. Выключено: агенты не могут подключаться. - 0 picks a free port 0 — выбрать свободный порт + 0 picks a free port; AI apps find it by themselves 0 — выбрать свободный порт; ИИ-приложения найдут его сами Folder agents can open from Папка, из которой агенты могут открывать Folder agents can save to Папка, в которую агенты могут сохранять When PhotoCraft is closed Когда PhotoCraft закрыт diff --git a/crates/ui-egui/src/i18n/sr.tsv b/crates/ui-egui/src/i18n/sr.tsv index 8885c9043a..99784cc31b 100644 --- a/crates/ui-egui/src/i18n/sr.tsv +++ b/crates/ui-egui/src/i18n/sr.tsv @@ -4225,7 +4225,7 @@ shape Appearance Izgled Managed by the launch options (--control). Upravljaju opcije pokretanja (--control). Agents can connect on 127.0.0.1:{port}. Agenti mogu da se povežu na 127.0.0.1:{port}. Off: agents can't connect. Isključeno: agenti ne mogu da se povežu. - 0 picks a free port 0 bira slobodan port + 0 picks a free port; AI apps find it by themselves 0 bira slobodan port; AI aplikacije ga same pronalaze Folder agents can open from Fascikla iz koje agenti mogu da otvaraju Folder agents can save to Fascikla u koju agenti mogu da čuvaju When PhotoCraft is closed Kada je PhotoCraft zatvoren diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 8f7f1e48ef..783919df01 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -3882,7 +3882,7 @@ cameraData Lens Lens Managed by the launch options (--control). Başlatma seçenekleri tarafından yönetiliyor (--control). Agents can connect on 127.0.0.1:{port}. Ajanlar 127.0.0.1:{port} üzerinden bağlanabilir. Off: agents can't connect. Kapalı: ajanlar bağlanamaz. - 0 picks a free port 0 boş bir bağlantı noktası seçer + 0 picks a free port; AI apps find it by themselves 0 boş bir bağlantı noktası seçer; yapay zekâ uygulamaları onu kendileri bulur Folder agents can open from Ajanların açabileceği klasör Folder agents can save to Ajanların kaydedebileceği klasör When PhotoCraft is closed PhotoCraft kapalıyken diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 1b175550fd..ad48474f48 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -3849,7 +3849,7 @@ curves Smooth Згладити Managed by the launch options (--control). Керується параметрами запуску (--control). Agents can connect on 127.0.0.1:{port}. Агенти можуть підключатися до 127.0.0.1:{port}. Off: agents can't connect. Вимкнено: агенти не можуть підключатися. - 0 picks a free port 0 — вибрати вільний порт + 0 picks a free port; AI apps find it by themselves 0 — вибрати вільний порт; ШІ-застосунки знайдуть його самі Folder agents can open from Тека, з якої агенти можуть відкривати Folder agents can save to Тека, до якої агенти можуть зберігати When PhotoCraft is closed Коли PhotoCraft закрито diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index bfd8f3e97d..df96e93c5e 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -3637,7 +3637,7 @@ curves Smooth Làm mượt Managed by the launch options (--control). Do tùy chọn khởi chạy quản lý (--control). Agents can connect on 127.0.0.1:{port}. Tác tử có thể kết nối tại 127.0.0.1:{port}. Off: agents can't connect. Tắt: tác tử không thể kết nối. - 0 picks a free port 0 chọn một cổng trống + 0 picks a free port; AI apps find it by themselves 0 chọn một cổng trống; ứng dụng AI tự tìm thấy cổng Folder agents can open from Thư mục tác tử có thể mở Folder agents can save to Thư mục tác tử có thể lưu vào When PhotoCraft is closed Khi PhotoCraft đang đóng diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 43215345d3..4953813f57 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -2760,7 +2760,7 @@ curves Smooth 平滑 Managed by the launch options (--control). 由启动选项管理 (--control)。 Agents can connect on 127.0.0.1:{port}. 代理可通过 127.0.0.1:{port} 连接。 Off: agents can't connect. 关闭:代理无法连接。 - 0 picks a free port 0 表示选择空闲端口 + 0 picks a free port; AI apps find it by themselves 0 表示选择空闲端口;AI 应用会自动找到它 Folder agents can open from 代理可打开的文件夹 Folder agents can save to 代理可保存到的文件夹 When PhotoCraft is closed PhotoCraft 关闭时 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index e5e231a3de..210953b5b2 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -2745,7 +2745,7 @@ curves Smooth 平滑 Managed by the launch options (--control). 由啟動選項管理 (--control)。 Agents can connect on 127.0.0.1:{port}. 代理程式可透過 127.0.0.1:{port} 連線。 Off: agents can't connect. 關閉:代理程式無法連線。 - 0 picks a free port 0 表示選擇閒置連接埠 + 0 picks a free port; AI apps find it by themselves 0 表示選擇閒置連接埠;AI 應用程式會自動找到它 Folder agents can open from 代理程式可開啟的資料夾 Folder agents can save to 代理程式可儲存的資料夾 When PhotoCraft is closed PhotoCraft 關閉時 diff --git a/crates/ui-egui/src/prefs_ui.rs b/crates/ui-egui/src/prefs_ui.rs index 298a0649cf..9a1fb4b893 100644 --- a/crates/ui-egui/src/prefs_ui.rs +++ b/crates/ui-egui/src/prefs_ui.rs @@ -1320,7 +1320,7 @@ fn integration_rows(ui: &mut egui::Ui, obj: &mut Map, f: &mut Map let mut p = obj.get("controlPort").and_then(Value::as_i64).unwrap_or(0); ui.add(egui::DragValue::new(&mut p).range(0..=65535).custom_parser(crate::widgets::parse_num)); obj.insert("controlPort".into(), json!(p)); - ui.label(RichText::new(tl!("0 picks a free port")).color(t.text_faint)); + ui.label(RichText::new(tl!("0 picks a free port; AI apps find it by themselves")).color(t.text_faint)); }); ui.end_row(); for (key, pick) in [("readFolder", "chooseRead"), ("writeFolder", "chooseWrite")] { @@ -1344,7 +1344,9 @@ fn integration_rows(ui: &mut egui::Ui, obj: &mut Map, f: &mut Map obj.insert("whenAppClosed".into(), json!(cur)); ui.end_row(); }); - if f.get("__agentClients").and_then(Value::as_bool) == Some(true) { + // The buttons configure an AI app to connect, which only works once agents may: offer them + // with the box ticked (launch options manage the connection otherwise). + if on && !launch_flags && f.get("__agentClients").and_then(Value::as_bool) == Some(true) { ui.add_space(10.0); ui.label(RichText::new(tl!("Connect an AI app")).font(crate::theme::semibold(12.5)).color(t.text)); ui.horizontal_wrapped(|ui| { @@ -3032,6 +3034,41 @@ mod tests { assert!(crate::control::inspect(&app, &ctx).get("agentLink").is_some()); } + /// The buttons that set up an AI app only show once agents may connect, and a click reaches + /// the service with the app's id and shows its answer. + #[test] + fn ai_integrations_offer_the_client_buttons_only_when_agents_may_connect() { + use egui_kittest::{Harness, kittest::Queryable}; + let (mut app, _) = app_with_store(); + let clicked: Arc>> = Arc::default(); + let seen = clicked.clone(); + app.services.agent_clients = Some(Box::new(move |id: &str| { + seen.lock().unwrap().push(id.to_string()); + Ok(format!("Added PhotoCraft to {id}.")) + })); + open_preferences(&mut app, "integrations"); + let mut h = Harness::builder().with_size(vec2(1280.0, 800.0)).build_eframe(move |cc| { + PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); + app + }); + h.run_steps(4); + assert!(h.query_by_label("Add to Claude Desktop").is_none(), "off: nothing to set up yet"); + assert!(h.query_by_label("Copy Configuration").is_none()); + h.get_by_label("Let AI agents connect (MCP)").click(); + h.run_steps(3); + for label in ["Add to Claude Desktop", "Add to Claude Code", "Add to Cursor", "Copy Configuration"] { + assert!(h.query_by_label(label).is_some(), "{label}"); + } + h.get_by_label("Add to Cursor").click(); + h.run_steps(3); + assert_eq!(*clicked.lock().unwrap(), ["cursor"]); + assert!(h.query_by_label("Added PhotoCraft to cursor.").is_some(), "the answer is shown"); + // Unticked again: the buttons go. + h.get_by_label("Let AI agents connect (MCP)").click(); + h.run_steps(3); + assert!(h.query_by_label("Add to Cursor").is_none()); + } + #[test] fn ai_integrations_choices_and_paths_validate_through_prefs_set() { let (mut app, _) = app_with_store(); diff --git a/docs/mcp.md b/docs/mcp.md index a76050e58b..4a4870470c 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -7,7 +7,8 @@ happens when an agent needs PhotoCraft while it is closed (open it, work without a window, or ask the user to open it). Click **Apply** or **OK**. 2. Click **Add to Claude Desktop**, **Add to Claude Code** or **Add to Cursor** (or **Copy - Configuration** for any other MCP client), then restart that client. + Configuration** for any other MCP client), then restart that client. The buttons show once + the box is ticked. The client then starts `photocraft-cli mcp --live`. The app listens on loopback (any free port by default) with a token it creates in its settings folder, and publishes both in @@ -23,12 +24,33 @@ app's choice. In a headless session started that way, the folders chosen in the session stays headless until the MCP client restarts it. The app is started only on a tool call, never when the MCP client starts, and only while **Let AI agents connect** is on. -Claude Desktop's configuration is rewritten with its keys sorted; the previous file is kept beside -it as `claude_desktop_config.json.photocraft-backup` (likewise Cursor's `mcp.json`). Claude Code -is configured with `claude mcp add-json --scope user`. In the Flatpak, the sandbox can't write -those files (use **Copy Configuration**), and the connection needs +Where each client is configured: + +| Client | macOS | Windows | Linux | +|---|---|---|---| +| Claude Desktop | `~/Library/Application Support/Claude/claude_desktop_config.json` | `%APPDATA%\Claude\claude_desktop_config.json`; the Microsoft Store app reads `%LOCALAPPDATA%\Packages\Claude_\LocalCache\Roaming\Claude\claude_desktop_config.json` instead | `$XDG_CONFIG_HOME` or `~/.config`, `Claude/claude_desktop_config.json` | +| Cursor | `~/.cursor/mcp.json` | `%USERPROFILE%\.cursor\mcp.json` | `~/.cursor/mcp.json` | +| Claude Code | `claude mcp add --scope user photocraft -- mcp --live` (stored in `~/.claude.json`) | same (`claude.exe`, or npm's `claude.cmd`) | same | + +A client is configured only where it has created its settings folder (it does when it first +starts); otherwise the button says to install it and open it once, rather than writing a file +nothing reads. On Windows both Claude Desktop files get the entry when both exist: the Store app +reads its package's copy, while its **Edit Config** opens the other one +([anthropics/claude-code#26073](https://github.com/anthropics/claude-code/issues/26073)). A JSON +configuration is rewritten with its keys sorted; the previous file is kept beside it as +`.photocraft-backup`. Claude Code is found on `PATH`, else where its installers put it +(`~/.local/bin`, `~/.claude/local`, Homebrew, `/usr/local/bin`, `%APPDATA%\npm`), and runs with +its own folder first on `PATH` (an npm install needs the Node beside it); if it can't be run, the +message gives the command to type. In the Flatpak, the sandbox can't write those files (use +**Copy Configuration**), and the connection needs `flatpak override --user --share=network ai.storyteller.photocraft`. +When `--live` starts the app, macOS goes through LaunchServices (`open -a`) and Windows through +Explorer, as a double-click would: the app is no child of the CLI, so it keeps running when the +MCP client ends the CLI's process tree (Claude Code does on Windows), and it stays out of a +Microsoft Store client's container, where new files under `%APPDATA%` would land in the client's +package instead of PhotoCraft's settings folder. Linux starts it in its own process group. + ## Headless sessions PhotoCraft follows the same conventions as FilmCraft #28. Start a headless session: