From f84bbb6fa5dc41bb000c1e7cb56390d7e1445feb Mon Sep 17 00:00:00 2001 From: Furoxfufu <111354128+Furoxfufu@users.noreply.github.com> Date: Wed, 14 Oct 2026 11:31:12 +0000 Subject: [PATCH 01/28] AI Integrations: connect MCP clients to the running app without a terminal MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Edit › Preferences › AI Integrations › Let AI agents connect (off by default) starts the loopback control server at runtime, with a fresh token on every start, and publishes agent-connection.json in the settings folder. Agent requests go through the automation policy with the read/write folders chosen in the panel. `photocraft-cli mcp --live` finds the app from that file before every tool call, so MCP clients survive app restarts and port changes. While the app is closed, `whenAppClosed` (or --when-closed) decides: start the app, serve a headless session with the same folders, or explain what to do. The panel's Add to Claude Desktop / Claude Code / Cursor buttons and `photocraft-cli mcp install --client` write the client configuration (merged, with a backup); Copy Configuration gives the JSON. `--control`, `mcp --bridge` and headless `mcp` behave as before; with --control the panel says the launch options manage the connection. - automation: agent_link (connection file, client install), live backend, app_dirs moved here so the app and the CLI agree. - prefs: connectAgents, readFolder, writeFolder, whenAppClosed; controlPort is now read (settings that do nothing 26 -> 25). - packaging: photocraft-cli inside PhotoCraft.app; AppImage `--cli`. - 18 new strings translated in all 20 catalogs; docs and book updated. Co-Authored-By: Claude Opus 5.5 --- README.md | 2 + apps/photocraft-cli/src/lib.rs | 67 ++- apps/photocraft-cli/tests/cli.rs | 82 +++ apps/photocraft/src/agent_link.rs | 224 ++++++++ apps/photocraft/src/app_dirs.rs | 88 +--- apps/photocraft/src/control_server.rs | 88 +++- apps/photocraft/src/main.rs | 10 + apps/photocraft/src/services.rs | 37 +- book/src/automation/mcp.md | 11 +- book/src/security/automation-security.md | 5 + crates/automation/src/agent_link.rs | 545 ++++++++++++++++++++ crates/automation/src/app_dirs.rs | 95 ++++ crates/automation/src/lib.rs | 5 + crates/automation/src/live.rs | 221 ++++++++ crates/automation/src/security.rs | 32 ++ crates/automation/src/server.rs | 47 +- crates/automation/src/server/conventions.rs | 8 +- crates/automation/tests/mcp_live.rs | 275 ++++++++++ crates/engine/src/prefs.rs | 30 +- crates/ui-egui/src/control.rs | 1 + crates/ui-egui/src/i18n/cs.tsv | 19 + crates/ui-egui/src/i18n/de.tsv | 19 + crates/ui-egui/src/i18n/el.tsv | 19 + crates/ui-egui/src/i18n/es.tsv | 19 + crates/ui-egui/src/i18n/fr.tsv | 19 + crates/ui-egui/src/i18n/hu.tsv | 19 + crates/ui-egui/src/i18n/id.tsv | 19 + crates/ui-egui/src/i18n/it.tsv | 19 + crates/ui-egui/src/i18n/ja.tsv | 19 + crates/ui-egui/src/i18n/ko.tsv | 19 + crates/ui-egui/src/i18n/nl.tsv | 19 + crates/ui-egui/src/i18n/pl.tsv | 19 + crates/ui-egui/src/i18n/pt-br.tsv | 19 + crates/ui-egui/src/i18n/ru.tsv | 19 + crates/ui-egui/src/i18n/sr.tsv | 19 + crates/ui-egui/src/i18n/tr.tsv | 19 + crates/ui-egui/src/i18n/uk.tsv | 19 + crates/ui-egui/src/i18n/vi.tsv | 19 + crates/ui-egui/src/i18n/zh-hans.tsv | 19 + crates/ui-egui/src/i18n/zh-hant.tsv | 19 + crates/ui-egui/src/lib.rs | 69 ++- crates/ui-egui/src/prefs_ui.rs | 227 +++++++- docs/control-protocol.md | 8 +- docs/development.md | 1 + docs/mcp.md | 31 ++ docs/scorecard.md | 9 +- packaging/linux/AppRun | 8 + packaging/linux/apprun-test.sh | 8 + packaging/macos/package.sh | 6 +- scorecard/automation.toml | 6 + 50 files changed, 2489 insertions(+), 137 deletions(-) create mode 100644 apps/photocraft/src/agent_link.rs create mode 100644 crates/automation/src/agent_link.rs create mode 100644 crates/automation/src/app_dirs.rs create mode 100644 crates/automation/src/live.rs create mode 100644 crates/automation/tests/mcp_live.rs diff --git a/README.md b/README.md index b272705e40..be9ee2defd 100644 --- a/README.md +++ b/README.md @@ -239,6 +239,8 @@ photocraft-cli batch --help photocraft-cli mcp ``` +To let Claude or another AI app drive the open PhotoCraft window without a terminal, turn on **Edit › Preferences › AI Integrations › Let AI agents connect**, then click **Add to Claude Desktop** (or Claude Code, or Cursor) in the same panel. See [`docs/mcp.md`](docs/mcp.md). + The desktop app also offers an authenticated, loopback-only control channel (`photocraft --control`) for inspecting UI state, driving tools with pointer events, and taking offscreen screenshots. Every image in this README was rendered that way. See [`docs/control-protocol.md`](docs/control-protocol.md). ## Under the hood diff --git a/apps/photocraft-cli/src/lib.rs b/apps/photocraft-cli/src/lib.rs index a81cce61ce..2107a2222b 100644 --- a/apps/photocraft-cli/src/lib.rs +++ b/apps/photocraft-cli/src/lib.rs @@ -43,6 +43,13 @@ USAGE: photocraft-cli mcp [--bridge <127.0.0.1:port>] [--control-token <64-hex> | --control-token-file ] [--automation-read-root ] [--automation-write-root ] Run the MCP server on stdio (headless engine, or bridge to a running `photocraft --control `). + photocraft-cli mcp --live [--when-closed ] [--automation-read-root ] [--automation-write-root ] + Run the MCP server on stdio for the desktop app with Edit › Preferences › AI Integrations › + Let AI agents connect on, found again on every call (no port or token to configure). While the + app is closed, --when-closed (default: the app's When PhotoCraft Is Closed setting) starts it, + serves a headless session with the app's agent folders (or the roots given here), or fails. + photocraft-cli mcp install --client + Add `photocraft-cli mcp --live` to an MCP client's configuration (json: print it to paste). photocraft-cli serve [--port ] [--control-token <64-hex> | --control-token-file ] [--automation-read-root ] [--automation-write-root ] Keep one headless session open and answer JSON lines ({\"id\",\"method\",\"params\"}) on stdio, @@ -87,9 +94,9 @@ const SUBCOMMANDS: &[Subcommand] = &[ Subcommand { name: "commands", values: &["--filter"], bare: &["--json"], run: |a, out, _| commands(a, out) }, Subcommand { name: "mcp", - values: &["--bridge", "--control-token", "--control-token-file", "--automation-read-root", "--automation-write-root"], - bare: &[], - run: |a, _, _| mcp(a), + values: &["--bridge", "--control-token", "--control-token-file", "--automation-read-root", "--automation-write-root", "--when-closed", "--client"], + bare: &["--live"], + run: mcp, }, Subcommand { name: "serve", @@ -581,8 +588,24 @@ fn serve(a: &Args, err: &mut dyn Write) -> R { } } -fn mcp(a: &Args) -> R { +fn mcp(a: &Args, out: &mut dyn Write, _err: &mut dyn Write) -> R { + match a.positional.as_slice() { + [] => {} + [cmd] if cmd == "install" => return mcp_install(a, out), + [cmd, ..] => return Err(format!("unknown mcp command `{cmd}` (expected `install` or none)")), + } + if let Some(flag) = ["--client"].into_iter().find(|f| a.has(f)) { + return Err(format!("{flag} goes with `mcp install`")); + } + let live = a.has("--live"); + if !live && let Some(flag) = ["--when-closed"].into_iter().find(|f| a.has(f)) { + return Err(format!("{flag} goes with --live")); + } + if live && let Some(flag) = ["--bridge", "--control-token", "--control-token-file"].into_iter().find(|f| a.has(f)) { + return Err(format!("--live finds the app by itself; {flag} is for --bridge")); + } let server = match a.get("--bridge") { + _ if live => PhotocraftMcp::live(live_config(a)?), Some(addr) => { let (supplied, token_file) = security::token_inputs(a.get("--control-token").map(str::to_owned), a.get("--control-token-file").map(PathBuf::from)); let token = security::client_token(supplied.as_deref(), token_file.as_deref()).map_err(|e| e.to_string())?; @@ -594,6 +617,42 @@ fn mcp(a: &Args) -> R { rt.block_on(server.serve_stdio()).map_err(|e| e.to_string()) } +/// `mcp --live`: the app's settings folder, the closed-app override and the app launcher. +fn live_config(a: &Args) -> Result { + let dir = photocraft_automation::app_dirs::from_env().dir.ok_or("can't find PhotoCraft's settings folder (no home folder; set PHOTOCRAFT_CONFIG_DIR)")?; + let mut config = photocraft_automation::live::LiveConfig::new(dir); + config.when_closed = match a.get("--when-closed") { + None => None, + Some(v) => { + Some(photocraft_engine::prefs::WhenAppClosed::parse(v).ok_or_else(|| format!("bad --when-closed `{v}`: expected launch, headless or error"))?) + } + }; + config.read_root = a.get("--automation-read-root").map(PathBuf::from); + config.write_root = a.get("--automation-write-root").map(PathBuf::from); + config.launch = std::env::current_exe().ok().and_then(|exe| photocraft_automation::live::launcher(&exe)); + Ok(config) +} + +/// `mcp install --client `: add this CLI (`mcp --live`) to an MCP client. +fn mcp_install(a: &Args, out: &mut dyn Write) -> R { + use photocraft_automation::agent_link::{Client, ClientEnv, McpLaunch, install}; + if let Some(flag) = a.flags.iter().map(|(f, _)| f.as_str()).find(|f| *f != "--client") { + return Err(format!("{flag} doesn't go with `mcp install`")); + } + let ids = Client::ALL.map(Client::id).join(", "); + let id = a.get("--client").ok_or_else(|| format!("mcp install needs --client <{ids}>"))?; + let client = Client::parse(id).ok_or_else(|| format!("unknown --client `{id}`: expected one of {ids}"))?; + let exe = std::env::current_exe().map_err(|e| format!("can't find this program's path: {e}"))?; + let launch = match std::env::var_os("APPIMAGE").filter(|v| !v.is_empty()) { + Some(image) => McpLaunch::beside(Path::new(""), Some(Path::new(&image))), + // Not canonicalized: Windows would turn it into a `\\?\` path some clients can't start. + None => McpLaunch::cli(&exe), + }; + let done = install(client, &launch, &ClientEnv::from_env()).map_err(|e| e.to_string())?; + let _ = writeln!(out, "{}", done.message(client)); + Ok(()) +} + #[cfg(test)] mod missing_font_warning_tests { use super::*; diff --git a/apps/photocraft-cli/tests/cli.rs b/apps/photocraft-cli/tests/cli.rs index 231eb2c321..a215e10a7a 100644 --- a/apps/photocraft-cli/tests/cli.rs +++ b/apps/photocraft-cli/tests/cli.rs @@ -748,3 +748,85 @@ fn batch_plays_a_photoshop_actions_file() { assert!(err.contains("Generative Fill"), "{err}"); assert!(!o.status.success()); } + +/// `mcp install --client json` prints the configuration MCP clients start `mcp --live` with; +/// Cursor's file gets the same entry, other servers kept (Preferences › AI Integrations). +#[test] +fn mcp_install_writes_the_live_entry() { + let home = tmp("mcp-install"); + let (out, _) = ok(bin().args(["mcp", "install", "--client", "json"]).env("HOME", &home)); + let v: Value = serde_json::from_str(&out).unwrap(); + let entry = &v["mcpServers"]["photocraft"]; + assert_eq!(entry["args"], json!(["mcp", "--live"]), "{out}"); + assert!(entry["command"].as_str().unwrap().contains("photocraft-cli"), "{out}"); + 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(); + let (out, _) = ok(bin().args(["mcp", "install", "--client", "cursor"]).env("HOME", &home).env("USERPROFILE", &home)); + assert!(out.contains("Cursor"), "{out}"); + let v: Value = serde_json::from_str(&std::fs::read_to_string(&cursor).unwrap()).unwrap(); + assert_eq!(v["mcpServers"]["other"]["command"], "x"); + assert_eq!(v["mcpServers"]["photocraft"], *entry); +} + +/// Flags that don't go together are refused before anything starts. +#[test] +fn mcp_live_and_install_reject_mismatched_flags() { + for (args, needle) in [ + (&["mcp", "install"][..], "--client"), + (&["mcp", "install", "--client", "vscode"], "unknown --client"), + (&["mcp", "install", "--client", "json", "--live"], "doesn't go with"), + (&["mcp", "frob"], "unknown mcp command"), + (&["mcp", "--client", "json"], "mcp install"), + (&["mcp", "--when-closed", "launch"], "--live"), + (&["mcp", "--live", "--bridge", "127.0.0.1:1"], "--bridge"), + (&["mcp", "--live", "--when-closed", "sometimes"], "bad --when-closed"), + ] { + let o = bin().args(args).stdin(Stdio::null()).output().unwrap(); + let err = String::from_utf8_lossy(&o.stderr); + assert!(!o.status.success(), "{args:?} succeeded"); + assert!(err.contains(needle), "{args:?}: {err}"); + } +} + +/// `mcp --live` serves MCP without the app; a tool call says how to connect it. +#[test] +fn mcp_live_without_the_app_explains_what_to_do() { + let dir = tmp("mcp-live"); + let mut child = bin() + .args(["mcp", "--live", "--when-closed", "error"]) + .env("PHOTOCRAFT_CONFIG_DIR", &dir) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::null()) + .spawn() + .unwrap(); + let mut stdin = child.stdin.take().unwrap(); + let mut stdout = BufReader::new(child.stdout.take().unwrap()); + let mut send = |v: Value| { + writeln!(stdin, "{v}").unwrap(); + stdin.flush().unwrap(); + }; + let mut recv = |id: u64| -> Value { + loop { + let mut line = String::new(); + assert!(stdout.read_line(&mut line).unwrap() > 0, "server closed"); + let v: Value = serde_json::from_str(&line).unwrap(); + if v["id"] == id { + return v; + } + } + }; + send(json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{ + "protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"test","version":"0"}}})); + recv(1); + send(json!({"jsonrpc":"2.0","method":"notifications/initialized"})); + send(json!({"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"ui_inspect","arguments":{}}})); + let r = recv(2); + assert_eq!(r["result"]["isError"], true, "{r}"); + assert!(r["result"]["content"][0]["text"].as_str().unwrap().contains("AI Integrations"), "{r}"); + drop(stdin); + let _ = child.kill(); + let _ = child.wait(); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/apps/photocraft/src/agent_link.rs b/apps/photocraft/src/agent_link.rs new file mode 100644 index 0000000000..dc6569007e --- /dev/null +++ b/apps/photocraft/src/agent_link.rs @@ -0,0 +1,224 @@ +//! Preferences › AI Integrations on the desktop: while *Let AI agents connect* is on, the app +//! serves the control protocol by itself (no `--control`), with a fresh token, and publishes the +//! connection file `photocraft-cli mcp --live` finds it by +//! ([`photocraft_automation::agent_link`]). Agent requests get the policy and the folders chosen +//! there, exactly as with `--control` and the automation roots. +//! +//! Launch flags win: started with `--control`, the app doesn't install this service and the +//! dialog says the launch options manage the connection. + +use std::path::{Path, PathBuf}; +use std::sync::mpsc::Receiver; + +use photocraft_automation::agent_link::{self, Client, ClientEnv, Connection, McpLaunch}; +use photocraft_automation::{AuthorizedWorkspace, security}; +use photocraft_engine::prefs::Integrations; +use photocraft_ui_egui::{AgentClientFn, AgentLink, AgentLinkFn, AgentLinkStatus, ControlRequest}; + +use crate::control_server; + +/// The connection while it runs; dropping it stops the server and removes the connection file. +struct Running { + server: control_server::Listening, + dir: PathBuf, + /// The `controlPort` preference it was started for (0 = any). + port_pref: u32, +} + +impl Drop for Running { + fn drop(&mut self) { + agent_link::remove_connection(&self.dir, std::process::id()); + log::info!("agent connection on 127.0.0.1:{} stopped", self.server.port); + } +} + +/// Start serving agents on `port` (0 = any free port): a new token, then the connection file. +/// Returns the connection and the channel its requests arrive on. +fn start(dir: &Path, port: u16, ctx: &egui::Context, port_pref: u32) -> Result<(Running, Receiver), String> { + let token_file = dir.join(agent_link::TOKEN_FILE); + let token = security::replace_token_file(&token_file).map_err(|e| format!("Couldn't create the agent key: {e}"))?; + let (requests, server) = control_server::listen(port, token, ctx.clone()).map_err(|e| format!("Couldn't listen on 127.0.0.1:{port}: {e}"))?; + let running = Running { server, dir: dir.to_path_buf(), port_pref }; + agent_link::write_connection(dir, &Connection::new(running.server.port, token_file)).map_err(|e| format!("Couldn't publish the agent connection: {e}"))?; + log::info!("agents can connect on 127.0.0.1:{}", running.server.port); + Ok((running, requests)) +} + +/// The agent connection service (`settings_dir`: where the connection file and token go). +pub fn service(settings_dir: Option, mcp: Option) -> AgentLinkFn { + let mut running: Option = None; + let mcp_command = mcp.map(|m| m.shell_line()); + Box::new(move |integrations: &Integrations, ctx: &egui::Context| apply(&mut running, settings_dir.as_deref(), integrations, ctx, mcp_command.clone())) +} + +/// Bring the connection in line with `integrations`: start, restart on another port, stop, or only +/// change the folders agents may use. +fn apply(running: &mut Option, dir: Option<&Path>, integrations: &Integrations, ctx: &egui::Context, mcp_command: Option) -> AgentLink { + let mut out = AgentLink { status: AgentLinkStatus { mcp_command, ..Default::default() }, ..Default::default() }; + if !integrations.connect_agents { + out.stopped = running.take().is_some(); + return out; + } + let Some(dir) = dir else { + out.stopped = running.take().is_some(); + out.status.error = Some("Agents can't connect: PhotoCraft has no settings folder (no home folder).".into()); + return out; + }; + if running.as_ref().is_none_or(|r| r.port_pref != integrations.control_port) { + out.stopped = running.take().is_some(); + // The preference's range is 0..=65535; anything else picks a free port. + let port = u16::try_from(integrations.control_port).unwrap_or(0); + match start(dir, port, ctx, integrations.control_port) { + Ok((r, requests)) => { + out.requests = Some(requests); + *running = Some(r); + } + Err(e) => { + log::warn!("{e}"); + out.status.error = Some(e); + return out; + } + } + } + out.status.port = running.as_ref().map(|r| r.server.port); + // Agent requests always go through the automation policy; without folders they get no file + // access at all (as `--control` without automation roots). + let read = agent_link::folder(&integrations.read_folder); + let write = agent_link::folder(&integrations.write_folder); + let workspace = AuthorizedWorkspace::new(read.as_deref(), write.as_deref()).unwrap_or_else(|e| { + out.status.error = Some(format!("Agents can connect, but without file access: {e}")); + AuthorizedWorkspace::default() + }); + out.automation = crate::services::automation(Some(workspace)); + out +} + +/// How MCP clients start this install's CLI (`photocraft-cli mcp --live`), or `None` when it +/// isn't installed beside the app (a development build of the app alone). +pub fn mcp_launch() -> Option { + if let Some(id) = std::env::var_os("FLATPAK_ID").filter(|v| !v.is_empty()) { + let args = ["run", "--command=photocraft-cli", &id.to_string_lossy(), "mcp", "--live"].map(str::to_string).to_vec(); + return Some(McpLaunch { command: "flatpak".into(), args }); + } + let exe = std::env::current_exe().ok()?; + let dir = exe.parent()?; + let appimage = std::env::var_os("APPIMAGE").filter(|v| !v.is_empty()).map(PathBuf::from); + let launch = McpLaunch::beside(dir, appimage.as_deref()); + (appimage.is_some() || dir.join(agent_link::cli_file_name()).is_file()).then_some(launch) +} + +/// The "Add to …" buttons: add `mcp` to a client, or return the configuration to paste. +pub fn clients(mcp: Option) -> AgentClientFn { + Box::new(move |id: &str| { + let client = Client::parse(id).ok_or_else(|| format!("unknown MCP client `{id}`"))?; + let launch = mcp.as_ref().ok_or_else(|| format!("photocraft-cli isn't installed beside PhotoCraft, so {} can't start it", client.name()))?; + agent_link::install(client, launch, &ClientEnv::from_env()).map(|done| done.message(client)).map_err(|e| e.to_string()) + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::atomic::{AtomicUsize, Ordering}; + + fn temp() -> PathBuf { + static N: AtomicUsize = AtomicUsize::new(0); + let d = std::env::temp_dir().join(format!("photocraft-agent-service-{}-{}", std::process::id(), N.fetch_add(1, Ordering::Relaxed))); + let _ = std::fs::remove_dir_all(&d); + std::fs::create_dir_all(&d).unwrap(); + d + } + + fn on(port: u32) -> Integrations { + Integrations { connect_agents: true, control_port: port, ..Default::default() } + } + + #[test] + fn turning_agents_on_publishes_a_reachable_connection_and_off_removes_it() { + let dir = temp(); + let ctx = egui::Context::default(); + let mut link = service(Some(dir.clone()), None); + // Off (the default): nothing listens, nothing is published. + let off = link(&Integrations::default(), &ctx); + assert!(off.requests.is_none() && !off.stopped && off.status.port.is_none()); + assert!(off.automation.command.is_none(), "no agent policy without a connection"); + assert_eq!(agent_link::read_connection(&dir).unwrap(), None); + + let started = link(&on(0), &ctx); + let port = started.status.port.unwrap(); + assert!(started.requests.is_some()); + assert!(started.automation.command.is_some() && started.automation.authorize.is_some(), "agent requests go through the policy"); + assert!(started.automation.read.is_some(), "the workspace answers (and refuses: no folder chosen)"); + let c = agent_link::read_connection(&dir).unwrap().unwrap(); + assert_eq!((c.port, c.pid), (port, std::process::id())); + assert!(agent_link::probe(port, agent_link::PROBE_TIMEOUT)); + let token = security::client_token(None, Some(&c.token_file)).unwrap(); + + // Folder changes keep the server and its token. + let folders = Integrations { read_folder: dir.to_string_lossy().into_owned(), ..on(0) }; + let changed = link(&folders, &ctx); + assert!(changed.requests.is_none() && !changed.stopped); + assert_eq!(changed.status.port, Some(port)); + assert!(changed.status.error.is_none(), "{:?}", changed.status.error); + assert_eq!(security::client_token(None, Some(&c.token_file)).unwrap(), token); + + // A missing folder still connects, without file access, and says why. + let missing = Integrations { write_folder: dir.join("nope").to_string_lossy().into_owned(), ..on(0) }; + let partial = link(&missing, &ctx); + assert_eq!(partial.status.port, Some(port)); + assert!(partial.status.error.as_deref().is_some_and(|e| e.contains("without file access")), "{:?}", partial.status.error); + assert!(partial.automation.command.is_some()); + + let stopped = link(&Integrations::default(), &ctx); + assert!(stopped.stopped && stopped.status.port.is_none()); + assert_eq!(agent_link::read_connection(&dir).unwrap(), None, "the connection file goes with the server"); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5); + while agent_link::probe(port, agent_link::PROBE_TIMEOUT) { + assert!(std::time::Instant::now() < deadline, "port {port} still open"); + std::thread::sleep(std::time::Duration::from_millis(20)); + } + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn a_new_port_restarts_with_a_new_token_and_a_taken_port_is_reported() { + let dir = temp(); + let ctx = egui::Context::default(); + let mut link = service(Some(dir.clone()), None); + let first = link(&on(0), &ctx); + let first_port = first.status.port.unwrap(); + let token_file = dir.join(agent_link::TOKEN_FILE); + let first_token = std::fs::read_to_string(&token_file).unwrap(); + // A taken port: the error names it and nothing is published for it. + let taken = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let taken_port = taken.local_addr().unwrap().port(); + let failed = link(&on(u32::from(taken_port)), &ctx); + assert!(failed.stopped && failed.requests.is_none() && failed.status.port.is_none()); + assert!(failed.status.error.as_deref().is_some_and(|e| e.contains(&taken_port.to_string())), "{:?}", failed.status.error); + assert_eq!(agent_link::read_connection(&dir).unwrap(), None); + drop(taken); + // Back to any port: a fresh token. + let again = link(&on(0), &ctx); + assert!(again.requests.is_some()); + assert!(again.status.port.is_some_and(|p| p != 0)); + assert_ne!(std::fs::read_to_string(&token_file).unwrap(), first_token); + let _ = first_port; + drop(link); + assert_eq!(agent_link::read_connection(&dir).unwrap(), None, "quitting removes the connection file"); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn no_settings_folder_is_an_error_not_a_panic() { + let mut link = service(None, None); + let r = link(&on(0), &egui::Context::default()); + assert!(r.requests.is_none() && r.status.error.is_some()); + } + + #[test] + fn clients_without_a_cli_say_so() { + let mut add = clients(None); + assert!(add("cursor").unwrap_err().contains("photocraft-cli")); + assert!(add("nope").unwrap_err().contains("unknown")); + } +} diff --git a/apps/photocraft/src/app_dirs.rs b/apps/photocraft/src/app_dirs.rs index 2897bebdb0..a063357e09 100644 --- a/apps/photocraft/src/app_dirs.rs +++ b/apps/photocraft/src/app_dirs.rs @@ -1,44 +1,14 @@ //! Where the desktop app keeps its per-user data: preferences, brush presets, crash-recovery //! autosaves and the GPU startup marker all live under the one directory [`config_dir`] returns. //! -//! In order: -//! 1. `PHOTOCRAFT_CONFIG_DIR`, when set (tests, agents, custom setups). -//! 2. **Portable mode** (#228): a marker file ([`PORTABLE_MARKERS`]) beside the executable puts -//! everything in `/PhotoCraftData`, so a portable copy on a USB stick leaves nothing in -//! `%APPDATA%`. The Windows portable zip ships with `portable.txt`; the MSI doesn't. If that -//! folder can't be written (read-only medium, Program Files), the app warns and falls back. -//! 3. The platform convention: macOS `~/Library/Application Support/Photocraft`, Windows -//! `%APPDATA%\Photocraft`, Linux `$XDG_CONFIG_HOME/photocraft` or `~/.config/photocraft`. +//! The rules (`PHOTOCRAFT_CONFIG_DIR`, portable mode, the platform convention) live in +//! [`photocraft_automation::app_dirs`], so `photocraft-cli` resolves the same folder; this module +//! resolves it once for the app and logs the outcome. -use std::ffi::OsString; use std::path::{Path, PathBuf}; use std::sync::OnceLock; -/// Files beside the executable that switch on portable mode (either one; contents are ignored). -pub const PORTABLE_MARKERS: [&str; 2] = ["portable.txt", "PhotoCraft.portable"]; -/// The data folder created beside the executable in portable mode. -pub const PORTABLE_DATA_DIR: &str = "PhotoCraftData"; - -/// How [`DataDir::dir`] was chosen. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum Mode { - /// `PHOTOCRAFT_CONFIG_DIR`. - Override, - /// `/PhotoCraftData`. - Portable, - /// The platform's per-user config directory. - Platform, -} - -/// The resolved data directory. -#[derive(Clone, Debug)] -pub struct DataDir { - /// `None` only when no platform directory is known either (no `HOME`/`APPDATA`). - pub dir: Option, - pub mode: Mode, - /// Set when a portable marker was found but its data folder isn't writable. - pub warning: Option, -} +pub use photocraft_automation::app_dirs::{DataDir, resolve}; /// The data directory for this process, resolved once (the portable check probes the disk). pub fn current() -> &'static DataDir { @@ -60,58 +30,12 @@ pub fn config_dir() -> Option { current().dir.clone() } -/// Resolve the data directory from the environment (`env`) and the executable's folder. -pub fn resolve(env: impl Fn(&str) -> Option, exe_dir: Option<&Path>) -> DataDir { - if let Some(d) = env("PHOTOCRAFT_CONFIG_DIR").filter(|d| !d.is_empty()) { - return DataDir { dir: Some(PathBuf::from(d)), mode: Mode::Override, warning: None }; - } - let platform = platform_dir(&env); - let Some((exe_dir, marker)) = exe_dir.and_then(|d| portable_marker(d).map(|m| (d, m))) else { - return DataDir { dir: platform, mode: Mode::Platform, warning: None }; - }; - let data = exe_dir.join(PORTABLE_DATA_DIR); - match ensure_writable(&data) { - Ok(()) => DataDir { dir: Some(data), mode: Mode::Portable, warning: None }, - Err(e) => { - let fallback = platform.as_ref().map_or_else(|| "nowhere (no user folder found)".to_string(), |p| p.display().to_string()); - let warning = - format!("portable mode ({} found) but {} isn't writable ({e}); settings are kept in {fallback} instead", marker.display(), data.display()); - DataDir { dir: platform, mode: Mode::Platform, warning: Some(warning) } - } - } -} - -/// The platform convention, from `env` (so tests can fake `HOME`/`APPDATA`/`XDG_CONFIG_HOME`). -pub fn platform_dir(env: &impl Fn(&str) -> Option) -> Option { - let home = env("HOME").filter(|h| !h.is_empty()).map(PathBuf::from); - if cfg!(target_os = "macos") { - return home.map(|h| h.join("Library/Application Support/Photocraft")); - } - if cfg!(windows) { - return env("APPDATA").filter(|a| !a.is_empty()).map(|a| PathBuf::from(a).join("Photocraft")); - } - env("XDG_CONFIG_HOME").filter(|x| !x.is_empty()).map(PathBuf::from).or_else(|| home.map(|h| h.join(".config"))).map(|c| c.join("photocraft")) -} - -/// The first portable marker file in `exe_dir`, if any. -pub fn portable_marker(exe_dir: &Path) -> Option { - PORTABLE_MARKERS.iter().map(|m| exe_dir.join(m)).find(|p| p.is_file()) -} - -/// Create `dir` and prove a file can be written in it (a folder can exist yet be read-only). -fn ensure_writable(dir: &Path) -> std::io::Result<()> { - std::fs::create_dir_all(dir)?; - let probe = dir.join(format!(".write-test-{}", std::process::id())); - std::fs::write(&probe, b"")?; - // A leftover probe is harmless; don't fail portable mode over it. - let _ = std::fs::remove_file(&probe); - Ok(()) -} - #[cfg(test)] mod tests { use super::*; + use photocraft_automation::app_dirs::{Mode, PORTABLE_DATA_DIR, PORTABLE_MARKERS, platform_dir}; use std::collections::HashMap; + use std::ffi::OsString; use std::sync::atomic::{AtomicUsize, Ordering}; fn temp(tag: &str) -> PathBuf { diff --git a/apps/photocraft/src/control_server.rs b/apps/photocraft/src/control_server.rs index 258d89e1ec..60889466fd 100644 --- a/apps/photocraft/src/control_server.rs +++ b/apps/photocraft/src/control_server.rs @@ -1,11 +1,15 @@ //! Localhost JSON-lines control server (one request per line, one reply per line). //! Loopback only. This is the transport the MCP server will wrap. +//! +//! `--control` starts it for the whole run ([`start`]); Preferences › AI Integrations starts and +//! stops it while the app runs ([`listen`], see `agent_link`). use std::io::{BufReader, Write}; use std::net::{TcpListener, TcpStream}; use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::mpsc::{Receiver, Sender, channel}; -use std::time::Instant; +use std::time::{Duration, Instant}; use photocraft_automation::budgets::write_reply; use photocraft_automation::security::{ @@ -16,19 +20,51 @@ use photocraft_ui_egui::control::REPLY_DEADLINE; use serde_json::{Value, json}; pub fn start(port: u16, token: String, ctx: egui::Context) -> Receiver { - let (tx, rx) = channel::(); - let listener = match TcpListener::bind(("127.0.0.1", port)) { - Ok(l) => l, + match listen(port, token, ctx) { + Ok((rx, server)) => { + eprintln!("photocraft: control server listening on 127.0.0.1:{}", server.port); + // Serves for the whole run. + std::mem::forget(server); + rx + } Err(e) => { eprintln!("photocraft: control server failed to bind 127.0.0.1:{port}: {e}"); - return rx; + channel::().1 } - }; - eprintln!("photocraft: control server listening on 127.0.0.1:{port}"); - std::thread::spawn(move || { + } +} + +/// A control server started by [`listen`]. Dropping it stops accepting connections; connections +/// already open end at their next request, once the app drops the request channel. +pub struct Listening { + /// The bound port (the one the system picked for port 0). + pub port: u16, + stop: Arc, +} + +impl Drop for Listening { + fn drop(&mut self) { + self.stop.store(true, Ordering::Release); + // Wake the accept loop so it sees the flag and closes the listener. + let _ = TcpStream::connect_timeout(&std::net::SocketAddr::from(([127, 0, 0, 1], self.port)), Duration::from_millis(500)); + } +} + +/// Serve the control protocol on `127.0.0.1:port` (0 = any free port) until the returned +/// [`Listening`] is dropped. +pub fn listen(port: u16, token: String, ctx: egui::Context) -> std::io::Result<(Receiver, Listening)> { + let (tx, rx) = channel::(); + let listener = TcpListener::bind(("127.0.0.1", port))?; + let port = listener.local_addr()?.port(); + let stop = Arc::new(AtomicBool::new(false)); + let stopped = stop.clone(); + std::thread::Builder::new().name("control server".into()).spawn(move || { let limiter = ConnectionLimiter::new(MAX_CONNECTIONS); let token = Arc::new(token); for mut stream in listener.incoming().flatten() { + if stopped.load(Ordering::Acquire) { + break; + } let Some(permit) = limiter.try_acquire() else { let _ = configure_stream(&stream); let _ = writeln!(stream, "{}", json!({"id": null, "ok": false, "error": "connection limit reached"})); @@ -42,8 +78,8 @@ pub fn start(port: u16, token: String, ctx: egui::Context) -> Receiver, ctx: egui::Context) { @@ -210,6 +246,38 @@ mod tests { server.join().unwrap(); } + #[test] + fn a_listening_server_picks_a_port_and_stops_when_dropped() { + const TOKEN: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"; + let (rx, server) = listen(0, TOKEN.into(), egui::Context::default()).unwrap(); + let port = server.port; + assert_ne!(port, 0); + let handler = std::thread::spawn(move || { + let req = rx.recv_timeout(Duration::from_secs(5)).unwrap(); + assert_eq!(req.method, "test.ping"); + req.reply.send(json!({"ok": true, "result": "pong"})).unwrap(); + }); + let mut stream = TcpStream::connect(("127.0.0.1", port)).unwrap(); + stream.set_read_timeout(Some(Duration::from_secs(5))).unwrap(); + let mut reader = BufReader::new(stream.try_clone().unwrap()); + let mut line = String::new(); + writeln!(stream, "{}", json!({"id": 1, "method": "auth", "params": {"token": TOKEN}})).unwrap(); + reader.read_line(&mut line).unwrap(); + assert_eq!(serde_json::from_str::(&line).unwrap()["ok"], true); + writeln!(stream, "{}", json!({"id": 2, "method": "test.ping"})).unwrap(); + line.clear(); + reader.read_line(&mut line).unwrap(); + assert_eq!(serde_json::from_str::(&line).unwrap()["result"], "pong"); + handler.join().unwrap(); + drop(server); + // The listener closes once the accept loop has seen the stop flag. + let deadline = Instant::now() + Duration::from_secs(5); + while TcpStream::connect_timeout(&std::net::SocketAddr::from(([127, 0, 0, 1], port)), Duration::from_millis(200)).is_ok() { + assert!(Instant::now() < deadline, "port {port} still accepts connections after stop"); + std::thread::sleep(Duration::from_millis(20)); + } + } + #[test] fn repeat_auth_reports_already_authenticated_without_dispatching() { const TOKEN: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"; diff --git a/apps/photocraft/src/main.rs b/apps/photocraft/src/main.rs index 1739568159..29966c4dbb 100644 --- a/apps/photocraft/src/main.rs +++ b/apps/photocraft/src/main.rs @@ -20,6 +20,7 @@ #![cfg_attr(all(windows, not(debug_assertions)), windows_subsystem = "windows")] #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +mod agent_link; mod app_dirs; mod app_icon; mod appearance; @@ -467,9 +468,18 @@ fn main() -> eframe::Result { log::warn!("couldn't remember GPU backend {}: {e}", b.name()); } }); + // Preferences › AI Integrations: agents connect without a terminal, unless the launch + // flags (`--control`) manage the connection. + let mcp = agent_link::mcp_launch(); + app.agent_link.mcp_command = mcp.as_ref().map(photocraft_automation::agent_link::McpLaunch::shell_line); + app.services.agent_clients = Some(agent_link::clients(mcp.clone())); if let Some((port, token, _)) = control { + app.agent_link.launch_flags = true; + app.agent_link.port = Some(port).filter(|p| *p != 0); let rx = control_server::start(port, token, cc.egui_ctx.clone()); app = app.with_control(rx); + } else { + app.services.agent_link = Some(agent_link::service(services::config_dir(), mcp)); } #[cfg(target_os = "macos")] { diff --git a/apps/photocraft/src/services.rs b/apps/photocraft/src/services.rs index d4a3869f31..00f1346607 100644 --- a/apps/photocraft/src/services.rs +++ b/apps/photocraft/src/services.rs @@ -404,37 +404,44 @@ fn shell_word(s: &str) -> String { if s.bytes().all(|b| b.is_ascii_alphanumeric() || b"/._-+:,@".contains(&b)) { s.to_string() } else { format!("'{}'", s.replace('\'', r"'\''")) } } -pub fn native(automation: Option) -> Services { - let clip: Rc>> = Rc::default(); - let automation_read = automation.clone().map(|workspace| { +/// What control and MCP requests may read, write and run, through `workspace` (`None`: no +/// automation, as without `--control` or an agent connection). +pub fn automation(workspace: Option) -> photocraft_ui_egui::AutomationServices { + let read = workspace.clone().map(|workspace| { Box::new(move |path: &str| { let bytes = workspace.read(path).map_err(|error| error.to_string())?; let name = Path::new(path).file_name().and_then(|name| name.to_str()).unwrap_or(path).to_string(); Ok((name, bytes)) }) as photocraft_ui_egui::AutomationReadFn }); - let automation_write = automation.clone().map(|workspace| { + let write = workspace.clone().map(|workspace| { Box::new(move |path: &str, bytes: &[u8]| workspace.write(path, bytes).map_err(|error| error.to_string())) as photocraft_ui_egui::AutomationWriteFn }); - let automation_open_pcraft = automation.clone().map(|workspace| { + let open_pcraft = workspace.clone().map(|workspace| { Box::new(move |path: &str| { let name = Path::new(path).file_name().and_then(|name| name.to_str()).unwrap_or(path).to_string(); let opened = crate::crash_guard::guard("Open", || workspace.open_pcraft(path).map_err(|e| e.to_string()))?; Ok(opened.map(|doc| (name, doc))) }) as photocraft_ui_egui::AutomationOpenPcraftFn }); - let automation_save = automation.clone().map(|workspace| { + let save = workspace.clone().map(|workspace| { std::sync::Arc::new(move |doc: &Document, path: &str, settings: &photocraft_ui_egui::ExportSettings, ctl: &photocraft_ui_egui::jobs_ui::SaveCtl| { save_through(doc, path, settings, ctl, |p, b, _| workspace.write(p, b).map_err(|e| e.to_string())) }) as photocraft_ui_egui::SaveFileFn }); - let step: fn(&str, &serde_json::Value) -> photocraft_engine::Result<()> = photocraft_automation::workspace::authorize_desktop_engine_step; - let automation_authorize = automation.is_some().then_some(step); - let automation_command = automation.map(|_| { + let step: photocraft_ui_egui::AutomationAuthorizeFn = photocraft_automation::workspace::authorize_desktop_engine_step; + let authorize = workspace.is_some().then_some(step); + let command = workspace.map(|_| { Box::new(|id: &str, params: &serde_json::Value| { photocraft_automation::workspace::authorize_desktop_engine_command(id, params).map_err(|error| error.to_string()) }) as photocraft_ui_egui::AutomationCommandFn }); + photocraft_ui_egui::AutomationServices { read, write, open_pcraft, save, command, authorize } +} + +pub fn native(automation: Option) -> Services { + let clip: Rc>> = Rc::default(); + let automation = self::automation(automation); Services { import: Some(Box::new(|name: &str, bytes: &[u8], max_svg_group_depth: usize| { crate::crash_guard::guard("Open", || { @@ -448,12 +455,12 @@ pub fn native(automation: Option) -> save_file: Some(Arc::new(save_file)), file_dialog: Some(Box::new(show_file_dialog)), write: Some(Box::new(|path: &str, bytes: &[u8]| write_atomic(Path::new(path), bytes))), - automation_read, - automation_write, - automation_open_pcraft, - automation_save, - automation_command, - automation_authorize, + automation_read: automation.read, + automation_write: automation.write, + automation_open_pcraft: automation.open_pcraft, + automation_save: automation.save, + automation_command: automation.command, + automation_authorize: automation.authorize, encode_png: Some(Box::new(|w, h, rgba| { let img = Image::from_u8(w, h, ChannelLayout::Rgba, rgba.to_vec()).map_err(|e| e.to_string())?; photocraft_codecs::encode(&img, photocraft_codecs::Format::Png, &EncodeOptions::default()).map_err(|e| e.to_string()) diff --git a/book/src/automation/mcp.md b/book/src/automation/mcp.md index 4f3d02496a..295191c796 100644 --- a/book/src/automation/mcp.md +++ b/book/src/automation/mcp.md @@ -1,9 +1,12 @@ # MCP -`photocraft-automation` implements an MCP server over stdio with two backends: +`photocraft-automation` implements an MCP server over stdio with three backends: - **Headless:** an in-process `Headless` session owns the engine and performs file I/O. - **Bridge:** `BridgeClient` forwards tools to a desktop application started with `photocraft --control `. +- **Live:** `photocraft-cli mcp --live` finds the desktop application through the connection file it publishes while Edit › Preferences › AI Integrations › *Let AI agents connect* is on, before every tool call; while the app is closed it starts it, serves a headless session, or reports an error, as chosen there. + +The simplest setup needs no terminal: turn on *Let AI agents connect* in PhotoCraft, then click *Add to Claude Desktop* (or Claude Code, or Cursor) in the same panel. See [`docs/mcp.md`](../../../docs/mcp.md#connecting-the-desktop-app-no-terminal). Start the headless server with: @@ -43,6 +46,12 @@ explicitly granted at launch; omitting a root omits that authority. Bridge mode loopback control connection with a bearer token before invoking any control method and uses the roots configured on the desktop process. +*Let AI agents connect* (off by default) opens the same loopback, token-authenticated control +listener as `--control`, with a token the app replaces every time the connection starts (in +`agent-control.token`, user-only on Unix, in the settings folder). The folders chosen in that panel +are the desktop process's roots, and the roots of a `mcp --live` headless session only when *When +PhotoCraft is closed* is set to work without a window. + The current server does not issue scoped sessions or distinguish trusted tools from high-impact tools. Authentication proves possession of the token; it does not restrict an authenticated client to document-only access. Do not expose either transport through an untrusted broker, shell, proxy, or remote service without adding an external policy boundary. Filesystem capabilities are implemented. General tool and method capabilities remain diff --git a/book/src/security/automation-security.md b/book/src/security/automation-security.md index 12a7679558..5698f77be7 100644 --- a/book/src/security/automation-security.md +++ b/book/src/security/automation-security.md @@ -29,6 +29,11 @@ Automation is a privilege boundary because requests can cause filesystem access, Screenshots are decoded under separate dimension, pixel, and allocation ceilings before downscaling; the 5 MiB PNG limit applies to the returned image. - MCP normally uses stdio and can optionally bridge to loopback control TCP. +- Preferences › AI Integrations › *Let AI agents connect* (off by default) opens that loopback + listener without launch flags. Its token is regenerated each time the connection starts and is + kept in a user-only file; the published `agent-connection.json` holds the port and the token + file's path, never the token. `photocraft-cli mcp --live` probes the port before sending the + token, and a file left by a crash fails that probe. - The bridge and UI request paths use timeouts. - Engine commands are expected to reject invalid parameters without panicking. - Remote filesystem methods use separately granted read and write directory capabilities. diff --git a/crates/automation/src/agent_link.rs b/crates/automation/src/agent_link.rs new file mode 100644 index 0000000000..ba2991f7df --- /dev/null +++ b/crates/automation/src/agent_link.rs @@ -0,0 +1,545 @@ +//! Connecting AI agents to the desktop app without a terminal (Edit › Preferences › AI +//! Integrations). +//! +//! While *Let AI agents connect* is on, the app serves the control protocol on loopback and +//! publishes where in its settings folder ([`CONNECTION_FILE`]): the port, its process id and the +//! bearer-token file ([`TOKEN_FILE`], created `0600` on Unix). `photocraft-cli mcp --live` +//! ([`crate::live`]) reads that file on every tool call, so MCP client configurations never hold a +//! port or a token, and keep working when the app restarts on another port. +//! +//! [`install`] adds that command to an MCP client's own configuration (Claude Desktop, Claude +//! Code, Cursor) or returns the JSON to paste into any other client; the app's buttons and +//! `photocraft-cli mcp install` share it. + +use std::net::{SocketAddr, TcpStream}; +use std::path::{Path, PathBuf}; +use std::time::Duration; + +use photocraft_engine::prefs::Integrations; +use serde::{Deserialize, Serialize}; +use serde_json::{Map, Value, json}; + +use crate::AutomationError; + +/// The connection file in the settings folder, present while the app accepts agents. +pub const CONNECTION_FILE: &str = "agent-connection.json"; +/// The bearer-token file the app creates (once) in its settings folder for agent connections. +pub const TOKEN_FILE: &str = "agent-control.token"; +/// The server name MCP clients list PhotoCraft under. +pub const SERVER_NAME: &str = "photocraft"; +/// How long [`probe`] waits for the app to accept a connection. +pub const PROBE_TIMEOUT: Duration = Duration::from_millis(500); +/// Version of the [`Connection`] file format. +const CONNECTION_VERSION: u32 = 1; +/// Largest connection or client configuration file read; anything bigger is not ours. +const MAX_CONFIG_BYTES: u64 = 16 << 20; + +/// What the app publishes in [`CONNECTION_FILE`]. Holds no secret: the token stays in its own +/// user-only file. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Connection { + pub version: u32, + /// The app's process id: only that process removes the file. + pub pid: u32, + /// Loopback port of the control server. + pub port: u16, + pub token_file: PathBuf, + /// The app's version, for diagnostics. + pub app: String, +} + +impl Connection { + pub fn new(port: u16, token_file: PathBuf) -> Self { + Connection { version: CONNECTION_VERSION, pid: std::process::id(), port, token_file, app: photocraft_engine::build_info::long_version() } + } + + /// `127.0.0.1:`. + pub fn addr(&self) -> String { + format!("127.0.0.1:{}", self.port) + } +} + +fn io_error(path: &Path, e: impl std::fmt::Display) -> AutomationError { + AutomationError::Io(format!("{}: {e}", path.display())) +} + +/// Read a small text file, refusing anything larger than [`MAX_CONFIG_BYTES`]. +fn read_small(path: &Path) -> Result, AutomationError> { + let meta = match std::fs::metadata(path) { + Ok(m) => m, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None), + Err(e) => return Err(io_error(path, e)), + }; + if meta.len() > MAX_CONFIG_BYTES { + return Err(io_error(path, format!("larger than {MAX_CONFIG_BYTES} bytes"))); + } + match std::fs::read_to_string(path) { + Ok(s) => Ok(Some(s)), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None), + Err(e) => Err(io_error(path, e)), + } +} + +/// Publish `c` in `dir` (written atomically, so a reader never sees half a file). +pub fn write_connection(dir: &Path, c: &Connection) -> Result<(), AutomationError> { + std::fs::create_dir_all(dir).map_err(|e| io_error(dir, e))?; + let path = dir.join(CONNECTION_FILE); + let text = serde_json::to_string_pretty(c).map_err(|e| AutomationError::Other(e.to_string()))?; + photocraft_format::atomic_write(&path, text.as_bytes()).map_err(|e| io_error(&path, e)) +} + +/// The connection published in `dir`, if any. A file from another version or one that doesn't +/// parse counts as none: the app rewrites it when it next starts listening. +pub fn read_connection(dir: &Path) -> Result, AutomationError> { + let Some(text) = read_small(&dir.join(CONNECTION_FILE))? else { return Ok(None) }; + Ok(serde_json::from_str::(&text).ok().filter(|c| c.version == CONNECTION_VERSION && c.port != 0)) +} + +/// Remove the connection file in `dir` if process `pid` wrote it (another instance may have +/// published its own since). Errors are ignored: a stale file only fails [`probe`]. +pub fn remove_connection(dir: &Path, pid: u32) { + if let Ok(Some(c)) = read_connection(dir) + && c.pid == pid + { + let _ = std::fs::remove_file(dir.join(CONNECTION_FILE)); + } +} + +/// Does something accept connections on loopback `port`? (A crashed app leaves its connection +/// file behind; nothing listens on its port any more.) +pub fn probe(port: u16, timeout: Duration) -> bool { + port != 0 && TcpStream::connect_timeout(&SocketAddr::from(([127, 0, 0, 1], port)), timeout).is_ok() +} + +/// The AI Integrations preferences saved in `dir/preferences.json` (defaults when the file or +/// the section is missing or unreadable: the CLI must not fail over the app's settings). +pub fn read_integrations(dir: &Path) -> Integrations { + read_small(&dir.join("preferences.json")) + .ok() + .flatten() + .and_then(|text| serde_json::from_str::(&text).ok()) + .and_then(|v| v.get("integrations").cloned()) + .and_then(|v| serde_json::from_value(v).ok()) + .unwrap_or_default() +} + +/// A folder preference as a path (`None` when empty). +pub fn folder(pref: &str) -> Option { + let pref = pref.trim(); + (!pref.is_empty()).then(|| PathBuf::from(pref)) +} + +// ---- MCP clients -------------------------------------------------------------------------------- + +/// How an MCP client starts PhotoCraft's MCP server. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct McpLaunch { + pub command: String, + pub args: Vec, +} + +impl McpLaunch { + /// ` mcp --live`. + pub fn cli(cli: &Path) -> Self { + McpLaunch { command: cli.to_string_lossy().into_owned(), args: vec!["mcp".into(), "--live".into()] } + } + + /// How to start the CLI that ships beside the executable in `exe_dir`. `appimage` is the + /// AppImage this process runs from (`$APPIMAGE`): its mount point disappears when the app + /// quits, so the AppImage itself starts the CLI (`--cli`, see `packaging/linux/AppRun`). + pub fn beside(exe_dir: &Path, appimage: Option<&Path>) -> Self { + match appimage { + Some(image) => McpLaunch { command: image.to_string_lossy().into_owned(), args: vec!["--cli".into(), "mcp".into(), "--live".into()] }, + None => Self::cli(&exe_dir.join(cli_file_name())), + } + } + + /// The `mcpServers` entry (`{"command", "args"}`). + pub fn entry(&self) -> Value { + json!({"command": self.command, "args": self.args}) + } + + /// A complete configuration to paste into an MCP client. + pub fn config_json(&self) -> String { + let v = json!({"mcpServers": {SERVER_NAME: self.entry()}}); + serde_json::to_string_pretty(&v).unwrap_or_default() + } + + /// The command line, quoted for a POSIX shell (Windows paths are double-quoted). + pub fn shell_line(&self) -> String { + std::iter::once(&self.command).chain(&self.args).map(|s| shell_quote(s)).collect::>().join(" ") + } +} + +fn shell_quote(s: &str) -> String { + if !s.is_empty() && s.bytes().all(|b| b.is_ascii_alphanumeric() || b"/._-+:,@=".contains(&b)) { + s.to_string() + } else if cfg!(windows) { + format!("\"{}\"", s.replace('"', "\\\"")) + } else { + format!("'{}'", s.replace('\'', r"'\''")) + } +} + +/// The CLI's file name on this platform. +pub fn cli_file_name() -> &'static str { + if cfg!(windows) { "photocraft-cli.exe" } else { "photocraft-cli" } +} + +/// MCP clients PhotoCraft can add itself to. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Client { + ClaudeDesktop, + ClaudeCode, + Cursor, + /// No client: the JSON to paste into any MCP client. + Json, +} + +impl Client { + pub const ALL: [Client; 4] = [Client::ClaudeDesktop, Client::ClaudeCode, Client::Cursor, Client::Json]; + + pub fn id(self) -> &'static str { + match self { + Client::ClaudeDesktop => "claude-desktop", + Client::ClaudeCode => "claude-code", + Client::Cursor => "cursor", + Client::Json => "json", + } + } + + pub fn parse(s: &str) -> Option { + Self::ALL.into_iter().find(|c| c.id() == s) + } + + pub fn name(self) -> &'static str { + match self { + Client::ClaudeDesktop => "Claude Desktop", + Client::ClaudeCode => "Claude Code", + Client::Cursor => "Cursor", + Client::Json => "MCP client", + } + } +} + +/// The environment [`install`] looks at, so tests can point it at a temporary home. +pub struct ClientEnv { + pub home: Option, + /// `%APPDATA%` (Windows). + pub appdata: Option, + /// `$XDG_CONFIG_HOME` (Linux). + pub xdg_config: Option, + /// `$PATH`, searched for the `claude` command. + pub path: Option, +} + +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), + appdata: var("APPDATA").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")) + } + 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::Cursor => self.home.as_ref().map(|h| h.join(".cursor").join("mcp.json")), + Client::ClaudeCode | Client::Json => None, + } + } + + /// 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()) + } +} + +/// 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`. + ClaudeCode, + /// The configuration to paste. + Json(String), +} + +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.", + _ => "", + }; + 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::ClaudeCode => "Added PhotoCraft to Claude Code (user scope). Start a new Claude Code session to connect.".into(), + Installed::Json(text) => text.clone(), + } + } +} + +/// 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 { + 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) + } + } +} + +/// Merge the `photocraft` entry into a JSON configuration with an `mcpServers` object. +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(), + Some(text) => match serde_json::from_str::(text) { + Ok(Value::Object(m)) => m, + Ok(_) => return Err(io_error(file, "is not a JSON object; fix or remove it, then try again")), + Err(e) => return Err(io_error(file, format!("is not valid JSON ({e}); fix or remove it, then try again"))), + }, + }; + let servers = root.entry("mcpServers").or_insert_with(|| Value::Object(Map::new())); + let Value::Object(servers) = servers else { + return Err(io_error(file, "`mcpServers` is not an object; fix it, then try again")); + }; + let entry = launch.entry(); + if servers.get(SERVER_NAME) == Some(&entry) { + return Ok(Installed::File { file: file.to_path_buf(), backup: None, unchanged: true }); + } + servers.insert(SERVER_NAME.into(), entry); + let text = serde_json::to_string_pretty(&Value::Object(root)).map_err(|e| AutomationError::Other(e.to_string()))?; + if let Some(parent) = file.parent() { + std::fs::create_dir_all(parent).map_err(|e| io_error(parent, e))?; + } + // Keys are rewritten in sorted order, so keep the user's file as it was. + let backup = match &existing { + Some(old) => { + let mut name = file.file_name().unwrap_or_default().to_os_string(); + name.push(".photocraft-backup"); + let backup = file.with_file_name(name); + photocraft_format::atomic_write(&backup, old.as_bytes()).map_err(|e| io_error(&backup, e))?; + Some(backup) + } + None => 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 }) +} + +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 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()))) + }; + // `add-json` 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}"))) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::atomic::{AtomicUsize, Ordering}; + + fn temp(tag: &str) -> PathBuf { + static N: AtomicUsize = AtomicUsize::new(0); + let d = std::env::temp_dir().join(format!("photocraft-agent-link-{tag}-{}-{}", std::process::id(), N.fetch_add(1, Ordering::Relaxed))); + let _ = std::fs::remove_dir_all(&d); + std::fs::create_dir_all(&d).unwrap(); + d + } + + fn env_at(home: &Path) -> ClientEnv { + ClientEnv { home: Some(home.to_path_buf()), appdata: Some(home.join("AppData")), xdg_config: None, path: None } + } + + #[test] + fn connection_round_trips_and_only_its_writer_removes_it() { + let dir = temp("conn"); + assert_eq!(read_connection(&dir).unwrap(), None); + let c = Connection::new(4242, dir.join(TOKEN_FILE)); + write_connection(&dir, &c).unwrap(); + assert_eq!(read_connection(&dir).unwrap(), Some(c.clone())); + assert_eq!(c.addr(), "127.0.0.1:4242"); + remove_connection(&dir, c.pid.wrapping_add(1)); + assert!(dir.join(CONNECTION_FILE).exists(), "another instance's file stays"); + remove_connection(&dir, c.pid); + assert!(!dir.join(CONNECTION_FILE).exists()); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn a_damaged_or_foreign_connection_file_counts_as_none() { + let dir = temp("bad-conn"); + for text in + ["", "{", "[]", r#"{"version":99,"pid":1,"port":1,"tokenFile":"t","app":"x"}"#, r#"{"version":1,"pid":1,"port":0,"tokenFile":"t","app":"x"}"#] + { + std::fs::write(dir.join(CONNECTION_FILE), text).unwrap(); + assert_eq!(read_connection(&dir).unwrap(), None, "{text}"); + } + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn probe_sees_a_listener_and_not_a_closed_port() { + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let port = listener.local_addr().unwrap().port(); + assert!(probe(port, PROBE_TIMEOUT)); + drop(listener); + assert!(!probe(port, PROBE_TIMEOUT)); + assert!(!probe(0, PROBE_TIMEOUT)); + } + + #[test] + fn integrations_come_from_the_saved_preferences_or_default() { + let dir = temp("prefs"); + assert_eq!(read_integrations(&dir), Integrations::default()); + std::fs::write(dir.join("preferences.json"), "not json").unwrap(); + assert_eq!(read_integrations(&dir), Integrations::default()); + // A section of the wrong type doesn't fail the CLI either. + std::fs::write(dir.join("preferences.json"), r#"{"integrations": {"connectAgents": "yes"}}"#).unwrap(); + assert_eq!(read_integrations(&dir), Integrations::default()); + std::fs::write( + dir.join("preferences.json"), + r#"{"general": {}, "integrations": {"connectAgents": true, "whenAppClosed": "headless", "readFolder": "/in"}}"#, + ) + .unwrap(); + let i = read_integrations(&dir); + assert!(i.connect_agents); + assert_eq!(i.when_app_closed, photocraft_engine::prefs::WhenAppClosed::Headless); + assert_eq!(folder(&i.read_folder), Some(PathBuf::from("/in"))); + assert_eq!(folder(&i.write_folder), None); + assert_eq!(folder(" "), None); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn launch_commands_and_config_json() { + let l = McpLaunch::cli(Path::new("/opt/PhotoCraft/photocraft-cli")); + assert_eq!(l.args, ["mcp", "--live"]); + let v: Value = serde_json::from_str(&l.config_json()).unwrap(); + assert_eq!(v["mcpServers"]["photocraft"]["command"], "/opt/PhotoCraft/photocraft-cli"); + assert_eq!(v["mcpServers"]["photocraft"]["args"], json!(["mcp", "--live"])); + let beside = McpLaunch::beside(Path::new("/opt/PhotoCraft"), None); + assert!(beside.command.ends_with(cli_file_name()), "{}", beside.command); + let image = McpLaunch::beside(Path::new("/tmp/.mount_x/usr/bin"), Some(Path::new("/home/u/PhotoCraft.AppImage"))); + assert_eq!(image.command, "/home/u/PhotoCraft.AppImage"); + assert_eq!(image.args, ["--cli", "mcp", "--live"]); + if !cfg!(windows) { + assert_eq!(McpLaunch::cli(Path::new("/a b/it's")).shell_line(), r"'/a b/it'\''s' mcp --live"); + } + for c in Client::ALL { + assert_eq!(Client::parse(c.id()), Some(c)); + } + assert_eq!(Client::parse("vscode"), None); + } + + #[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())); + } + let _ = std::fs::remove_dir_all(&home); + } + + #[test] + fn install_refuses_to_overwrite_a_file_it_cannot_read_as_json() { + 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(); + std::fs::create_dir_all(file.parent().unwrap()).unwrap(); + for text in ["{ broken", "[1, 2]", r#"{"mcpServers": []}"#] { + std::fs::write(&file, text).unwrap(); + let e = install(Client::Cursor, &launch, &env).unwrap_err().to_string(); + assert!(e.contains("try again"), "{e}"); + assert_eq!(std::fs::read_to_string(&file).unwrap(), text, "left untouched"); + } + let _ = std::fs::remove_dir_all(&home); + } + + #[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()) }; + if env.claude_command().is_some() { + return; // A system-wide `claude` (Homebrew, /usr/local) is installed here. + } + let e = install(Client::ClaudeCode, &McpLaunch::cli(Path::new("/x/photocraft-cli")), &env).unwrap_err().to_string(); + assert!(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 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/app_dirs.rs b/crates/automation/src/app_dirs.rs new file mode 100644 index 0000000000..32705958b0 --- /dev/null +++ b/crates/automation/src/app_dirs.rs @@ -0,0 +1,95 @@ +//! Where PhotoCraft keeps its per-user data, resolved the same way by the desktop app and +//! `photocraft-cli` (which finds the app's agent connection file there, see [`crate::agent_link`]). +//! +//! In order: +//! 1. `PHOTOCRAFT_CONFIG_DIR`, when set (tests, agents, custom setups). +//! 2. **Portable mode** (#228): a marker file ([`PORTABLE_MARKERS`]) beside the executable puts +//! everything in `/PhotoCraftData`, so a portable copy on a USB stick leaves nothing in +//! `%APPDATA%`. The Windows portable zip ships with `portable.txt`; the MSI doesn't. If that +//! folder can't be written (read-only medium, Program Files), the platform folder is used and +//! [`DataDir::warning`] says why. +//! 3. The platform convention: macOS `~/Library/Application Support/Photocraft`, Windows +//! `%APPDATA%\Photocraft`, Linux `$XDG_CONFIG_HOME/photocraft` or `~/.config/photocraft`. + +use std::ffi::OsString; +use std::path::{Path, PathBuf}; + +/// Files beside the executable that switch on portable mode (either one; contents are ignored). +pub const PORTABLE_MARKERS: [&str; 2] = ["portable.txt", "PhotoCraft.portable"]; +/// The data folder created beside the executable in portable mode. +pub const PORTABLE_DATA_DIR: &str = "PhotoCraftData"; + +/// How [`DataDir::dir`] was chosen. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Mode { + /// `PHOTOCRAFT_CONFIG_DIR`. + Override, + /// `/PhotoCraftData`. + Portable, + /// The platform's per-user config directory. + Platform, +} + +/// The resolved data directory. +#[derive(Clone, Debug)] +pub struct DataDir { + /// `None` only when no platform directory is known either (no `HOME`/`APPDATA`). + pub dir: Option, + pub mode: Mode, + /// Set when a portable marker was found but its data folder isn't writable. + pub warning: Option, +} + +/// Resolve the data directory from the environment (`env`) and the executable's folder. +pub fn resolve(env: impl Fn(&str) -> Option, exe_dir: Option<&Path>) -> DataDir { + if let Some(d) = env("PHOTOCRAFT_CONFIG_DIR").filter(|d| !d.is_empty()) { + return DataDir { dir: Some(PathBuf::from(d)), mode: Mode::Override, warning: None }; + } + let platform = platform_dir(&env); + let Some((exe_dir, marker)) = exe_dir.and_then(|d| portable_marker(d).map(|m| (d, m))) else { + return DataDir { dir: platform, mode: Mode::Platform, warning: None }; + }; + let data = exe_dir.join(PORTABLE_DATA_DIR); + match ensure_writable(&data) { + Ok(()) => DataDir { dir: Some(data), mode: Mode::Portable, warning: None }, + Err(e) => { + let fallback = platform.as_ref().map_or_else(|| "nowhere (no user folder found)".to_string(), |p| p.display().to_string()); + let warning = + format!("portable mode ({} found) but {} isn't writable ({e}); settings are kept in {fallback} instead", marker.display(), data.display()); + DataDir { dir: platform, mode: Mode::Platform, warning: Some(warning) } + } + } +} + +/// The platform convention, from `env` (so tests can fake `HOME`/`APPDATA`/`XDG_CONFIG_HOME`). +pub fn platform_dir(env: &impl Fn(&str) -> Option) -> Option { + let home = env("HOME").filter(|h| !h.is_empty()).map(PathBuf::from); + if cfg!(target_os = "macos") { + return home.map(|h| h.join("Library/Application Support/Photocraft")); + } + if cfg!(windows) { + return env("APPDATA").filter(|a| !a.is_empty()).map(|a| PathBuf::from(a).join("Photocraft")); + } + env("XDG_CONFIG_HOME").filter(|x| !x.is_empty()).map(PathBuf::from).or_else(|| home.map(|h| h.join(".config"))).map(|c| c.join("photocraft")) +} + +/// The first portable marker file in `exe_dir`, if any. +pub fn portable_marker(exe_dir: &Path) -> Option { + PORTABLE_MARKERS.iter().map(|m| exe_dir.join(m)).find(|p| p.is_file()) +} + +/// Create `dir` and prove a file can be written in it (a folder can exist yet be read-only). +fn ensure_writable(dir: &Path) -> std::io::Result<()> { + std::fs::create_dir_all(dir)?; + let probe = dir.join(format!(".write-test-{}", std::process::id())); + std::fs::write(&probe, b"")?; + // A leftover probe is harmless; don't fail portable mode over it. + let _ = std::fs::remove_file(&probe); + Ok(()) +} + +/// The data directory for this process's environment and executable (not cached). +pub fn from_env() -> DataDir { + let exe = std::env::current_exe().ok(); + resolve(|k| std::env::var_os(k), exe.as_deref().and_then(Path::parent)) +} diff --git a/crates/automation/src/lib.rs b/crates/automation/src/lib.rs index f1e7049d0d..ceca0937c6 100644 --- a/crates/automation/src/lib.rs +++ b/crates/automation/src/lib.rs @@ -11,15 +11,20 @@ //! * [`rpc`]: a headless JSON-lines server (stdio or loopback TCP) with the //! control protocol's envelope, used by `photocraft-cli serve`. //! * [`files`]: open/save any supported format, `.pcraft` natively. +//! * [`agent_link`] and [`live`]: connecting agents to the desktop app without a terminal +//! (Edit › Preferences › AI Integrations, `photocraft-cli mcp --live` and `mcp install`). //! //! L6, no UI-toolkit dependencies. #![forbid(unsafe_code)] #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +pub mod agent_link; +pub mod app_dirs; pub mod bridge; pub mod budgets; pub mod files; pub mod headless; +pub mod live; pub mod rpc; pub mod security; pub mod server; diff --git a/crates/automation/src/live.rs b/crates/automation/src/live.rs new file mode 100644 index 0000000000..092e86eb16 --- /dev/null +++ b/crates/automation/src/live.rs @@ -0,0 +1,221 @@ +//! `photocraft-cli mcp --live`: tools go to the desktop app found through its connection file +//! ([`crate::agent_link`]). The file is looked up again on every tool call, so the app may start, +//! quit or move to another port while the MCP client stays connected, and the MCP client's own +//! start never opens a window. +//! +//! While the app is closed, AI Integrations › When PhotoCraft Is Closed (or `--when-closed`) +//! decides: start the app and wait for it, serve a headless session with the folders chosen in +//! the app (then for the rest of the MCP session, so documents don't move under the agent), or +//! report an error that says what to do. + +use std::path::{Path, PathBuf}; +use std::sync::{Arc, Mutex, PoisonError}; +use std::time::{Duration, Instant}; + +use photocraft_engine::prefs::{Integrations, WhenAppClosed}; + +use crate::agent_link::{self, Connection, PROBE_TIMEOUT}; +use crate::bridge::BridgeClient; +use crate::headless::Headless; +use crate::{AuthorizedWorkspace, security}; + +/// Starts the desktop app (see [`launcher`]). +pub type LaunchFn = Box Result<(), String> + Send + Sync>; + +/// How long a started app gets to accept agents. A first start can take a while (GPU driver +/// shader caches, font scan), but MCP clients give a tool call about a minute. +pub const LAUNCH_TIMEOUT: Duration = Duration::from_secs(45); +const POLL: Duration = Duration::from_millis(250); + +pub struct LiveConfig { + /// The app's settings folder: connection file, token and preferences. + pub config_dir: PathBuf, + /// Overrides the app's preference (`--when-closed`). + pub when_closed: Option, + /// Override the app's folders for a headless session (`--automation-read-root`, + /// `--automation-write-root`). + pub read_root: Option, + pub write_root: Option, + /// Starts the app; `None` when this install can't (Flatpak sandbox, no app beside the CLI). + pub launch: Option, + pub launch_timeout: Duration, +} + +impl LiveConfig { + pub fn new(config_dir: PathBuf) -> Self { + LiveConfig { config_dir, when_closed: None, read_root: None, write_root: None, launch: None, launch_timeout: LAUNCH_TIMEOUT } + } +} + +/// Where a tool call goes once [`Live::resolve`] has run. +#[derive(Clone)] +pub(crate) enum Target { + Bridge(Arc), + Headless(Arc>), +} + +/// The port and token a bridge client was made for: when the app restarts, either changes. +type BridgeKey = (u16, String); + +pub struct Live { + cfg: LiveConfig, + /// Serialises lookups, so concurrent calls start the app once. + lookup: tokio::sync::Mutex<()>, + /// The current target, and for the bridge the port and token it was made for. + current: Mutex)>>, +} + +impl Live { + pub fn new(cfg: LiveConfig) -> Self { + Live { cfg, lookup: tokio::sync::Mutex::new(()), current: Mutex::new(None) } + } + + pub(crate) fn current(&self) -> Option { + self.current.lock().unwrap_or_else(PoisonError::into_inner).as_ref().map(|(t, _)| t.clone()) + } + + fn set(&self, target: Target, key: Option) { + *self.current.lock().unwrap_or_else(PoisonError::into_inner) = Some((target, key)); + } + + /// Find the app (or apply the closed-app choice) before a tool call. The error is the tool's + /// result: it tells the agent, and through it the user, what to do. + pub(crate) async fn resolve(&self) -> Result<(), String> { + let _one_at_a_time = self.lookup.lock().await; + if matches!(self.current(), Some(Target::Headless(_))) { + return Ok(()); + } + let dir = self.cfg.config_dir.clone(); + let (found, integrations) = blocking(move || (find_app(&dir), agent_link::read_integrations(&dir))).await?; + if let Some((c, token)) = found? { + self.use_app(&c, token)?; + return Ok(()); + } + match self.cfg.when_closed.unwrap_or(integrations.when_app_closed) { + WhenAppClosed::Error => Err(closed(&integrations)), + WhenAppClosed::Headless => { + let read = self.cfg.read_root.clone().or_else(|| agent_link::folder(&integrations.read_folder)); + let write = self.cfg.write_root.clone().or_else(|| agent_link::folder(&integrations.write_folder)); + let workspace = AuthorizedWorkspace::new(read.as_deref(), write.as_deref()) + .map_err(|e| format!("PhotoCraft isn't running and its agent folders can't be used: {e}"))?; + self.set(Target::Headless(Arc::new(Mutex::new(Headless::with_workspace(workspace)))), None); + Ok(()) + } + WhenAppClosed::Launch => self.launch_and_wait(&integrations).await, + } + } + + async fn launch_and_wait(&self, integrations: &Integrations) -> Result<(), String> { + if !integrations.connect_agents { + return Err(closed(integrations)); + } + let Some(launch) = &self.cfg.launch else { + return Err("PhotoCraft isn't running, and this install can't start it from here: open PhotoCraft, then try again.".into()); + }; + launch().map_err(|e| format!("couldn't start PhotoCraft: {e}"))?; + let deadline = Instant::now() + self.cfg.launch_timeout; + loop { + tokio::time::sleep(POLL).await; + let dir = self.cfg.config_dir.clone(); + if let Some((c, token)) = blocking(move || find_app(&dir)).await?? { + return self.use_app(&c, token); + } + if Instant::now() >= deadline { + return Err(format!( + "PhotoCraft didn't accept agents within {} s of starting. If it's still opening, try again in a moment; otherwise check Edit › Preferences › AI Integrations.", + self.cfg.launch_timeout.as_secs() + )); + } + } + } + + fn use_app(&self, c: &Connection, token: String) -> Result<(), String> { + let key: BridgeKey = (c.port, token); + let same = self.current.lock().unwrap_or_else(PoisonError::into_inner).as_ref().is_some_and(|(_, k)| k.as_ref() == Some(&key)); + if !same { + let client = BridgeClient::new(c.addr(), key.1.clone()).map_err(|e| e.to_string())?; + self.set(Target::Bridge(Arc::new(client)), Some(key)); + } + Ok(()) + } +} + +/// Run blocking file and socket work off the async runtime. +async fn blocking(f: impl FnOnce() -> T + Send + 'static) -> Result { + tokio::task::spawn_blocking(f).await.map_err(|e| format!("task failed: {e}")) +} + +/// The running app's connection and token: `None` when no app accepts agents (no connection +/// file, or one left by an app that crashed). +fn find_app(dir: &Path) -> Result, String> { + let Some(c) = agent_link::read_connection(dir).map_err(|e| e.to_string())? else { return Ok(None) }; + if !agent_link::probe(c.port, PROBE_TIMEOUT) { + return Ok(None); + } + let token = security::client_token(None, Some(&c.token_file)).map_err(|e| format!("PhotoCraft's agent token: {e}"))?; + Ok(Some((c, token))) +} + +fn closed(integrations: &Integrations) -> String { + if integrations.connect_agents { + "PhotoCraft isn't running: open it, then try again.".into() + } else { + "PhotoCraft doesn't accept AI agents: open it, turn on Edit › Preferences › AI Integrations › Let AI agents connect, then try again.".into() + } +} + +/// How to start the desktop app that ships with the CLI at `cli` (detached, with no standard +/// streams: the CLI's carry the MCP protocol, and the app must outlive the MCP client). +pub fn launcher(cli: &Path) -> Option { + use std::process::{Command, Stdio}; + if std::env::var_os("FLATPAK_ID").is_some() { + return None; + } + let command: Command = if let Some(image) = std::env::var_os("APPIMAGE").filter(|v| !v.is_empty()) { + // The AppImage's mount point goes away with the CLI; the image itself stays. + Command::new(image) + } else { + let dir = cli.parent()?; + let bundle = dir.parent().filter(|_| dir.ends_with("Contents/MacOS")).and_then(Path::parent); + match bundle { + // A macOS app bundle: LaunchServices starts (or brings forward) the app. + Some(app) if cfg!(target_os = "macos") => { + let mut c = Command::new("/usr/bin/open"); + c.arg("-a").arg(app); + c + } + _ => { + let app = dir.join(if cfg!(windows) { "photocraft.exe" } else { "photocraft" }); + if !app.is_file() { + return None; + } + Command::new(app) + } + } + }; + let command = Mutex::new(command); + Some(Box::new(move || { + let mut c = command.lock().unwrap_or_else(PoisonError::into_inner); + c.stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::null()); + detach(&mut c); + c.spawn().map(|_| ()).map_err(|e| e.to_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)] + { + use std::os::unix::process::CommandExt; + c.process_group(0); + } + #[cfg(windows)] + { + use std::os::windows::process::CommandExt; + const DETACHED_PROCESS: u32 = 0x0000_0008; + const CREATE_NEW_PROCESS_GROUP: u32 = 0x0000_0200; + c.creation_flags(DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP); + } + #[cfg(not(any(unix, windows)))] + let _ = c; +} diff --git a/crates/automation/src/security.rs b/crates/automation/src/security.rs index 4659a3ff17..d5cfa376ae 100644 --- a/crates/automation/src/security.rs +++ b/crates/automation/src/security.rs @@ -152,6 +152,20 @@ fn create_token_file(path: &Path, token: &str) -> Result<(), AutomationError> { writeln!(file, "{token}").map_err(|e| AutomationError::Io(format!("{}: {e}", path.display()))) } +/// Write a fresh token to `path`, replacing any earlier one (user-only on Unix), and return it. +/// The desktop app rotates the agent-connection token this way each time it starts listening, so +/// a token sent to a port another program took over after a crash stops working. +pub fn replace_token_file(path: &Path) -> Result { + let token = generate_token()?; + match std::fs::remove_file(path) { + Ok(()) => {} + Err(e) if e.kind() == std::io::ErrorKind::NotFound => {} + Err(e) => return Err(AutomationError::Io(format!("{}: {e}", path.display()))), + } + create_token_file(path, &token)?; + Ok(token) +} + /// Resolve a server token. With no supplied token or file, a fresh token is returned. /// A missing token file is created atomically; an existing one is read and validated. pub fn server_token(supplied: Option<&str>, token_file: Option<&Path>) -> Result { @@ -253,6 +267,24 @@ pub fn token_inputs(supplied: Option, token_file: Option) -> (O mod tests { use super::*; + #[test] + fn replaced_token_files_hold_a_new_valid_token() { + let dir = std::env::temp_dir().join(format!("photocraft-replace-token-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let path = dir.join("agent.token"); + let first = replace_token_file(&path).unwrap(); + assert_eq!(client_token(None, Some(&path)).unwrap(), first); + let second = replace_token_file(&path).unwrap(); + assert_ne!(first, second); + assert_eq!(client_token(None, Some(&path)).unwrap(), second); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + assert_eq!(std::fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o600); + } + let _ = std::fs::remove_dir_all(&dir); + } + #[test] fn generated_tokens_are_valid_and_distinct() { let a = generate_token().unwrap(); diff --git a/crates/automation/src/server.rs b/crates/automation/src/server.rs index b31507b005..ed902a87a4 100644 --- a/crates/automation/src/server.rs +++ b/crates/automation/src/server.rs @@ -16,6 +16,7 @@ use serde_json::{Value, json}; use crate::bridge::BridgeClient; use crate::budgets::{BatchReplyBudget, MAX_PREVIEW_SIDE, check_png, json_bytes}; use crate::headless::Headless; +use crate::live::{Live, LiveConfig, Target}; use crate::security::MAX_BATCH_STEPS; use crate::{AuthorizedWorkspace, AutomationError, files}; @@ -25,6 +26,9 @@ pub enum Backend { Headless(Arc>), /// A running desktop app reached over the control protocol. Bridge(Arc), + /// The desktop app found through its connection file before each call, or the closed-app + /// choice (`photocraft-cli mcp --live`, see [`crate::live`]). + Live(Arc), } #[derive(Clone)] @@ -465,6 +469,11 @@ impl PhotocraftMcp { Ok(Self::with_backend(Backend::Bridge(Arc::new(BridgeClient::new(addr, token)?)))) } + /// Serve the desktop app found through its connection file (`photocraft-cli mcp --live`). + pub fn live(config: LiveConfig) -> Self { + Self::with_backend(Backend::Live(Arc::new(Live::new(config)))) + } + pub fn with_backend(backend: Backend) -> Self { let mut tool_router = Self::tool_router(); for route in tool_router.map.values_mut() { @@ -485,10 +494,7 @@ impl PhotocraftMcp { &self, f: impl FnOnce(&mut Headless) -> Result + Send + 'static, ) -> Option> { - let Backend::Headless(h) = &*self.backend else { - return None; - }; - let h = h.clone(); + let h = self.headless_session()?; Some( tokio::task::spawn_blocking(move || { // A panicking command poisons the lock, but edits run on a copy @@ -503,13 +509,38 @@ impl PhotocraftMcp { ) } - fn bridge_client(&self) -> Option<&BridgeClient> { + /// The headless session tools run on, if this backend (or `--live`'s choice) is one. + fn headless_session(&self) -> Option>> { match &*self.backend { - Backend::Bridge(b) => Some(b), + Backend::Headless(h) => Some(h.clone()), + Backend::Live(live) => match live.current()? { + Target::Headless(h) => Some(h), + Target::Bridge(_) => None, + }, + Backend::Bridge(_) => None, + } + } + + fn bridge_client(&self) -> Option> { + match &*self.backend { + Backend::Bridge(b) => Some(b.clone()), + Backend::Live(live) => match live.current()? { + Target::Bridge(b) => Some(b), + Target::Headless(_) => None, + }, Backend::Headless(_) => None, } } + /// `--live`: find the app (or apply the closed-app choice) before a call; the error is the + /// call's result. Other backends are always ready. + async fn ready(&self) -> Result<(), String> { + match &*self.backend { + Backend::Live(live) => live.resolve().await, + Backend::Headless(_) | Backend::Bridge(_) => Ok(()), + } + } + async fn screenshot(&self, b: &BridgeClient, max_side: Option) -> Result { if max_side.is_some_and(|side| side > MAX_PREVIEW_SIDE) { return Ok(fail(format!("automation preview side exceeds {MAX_PREVIEW_SIDE} pixels"))); @@ -772,7 +803,7 @@ impl PhotocraftMcp { if p.index.is_some() { return Ok(fail("`index` is only supported in headless mode; bridge previews capture the app window")); } - self.screenshot(b, Some(max)).await + self.screenshot(&b, Some(max)).await } #[tool(description = "Render a bounded flattened PNG preview (bridge mode: app window screenshot).")] @@ -907,7 +938,7 @@ impl PhotocraftMcp { #[tool(description = "Bridge mode: screenshot of the live app window as PNG.")] async fn ui_screenshot(&self, Parameters(p): Parameters) -> Result { match self.bridge_client() { - Some(b) => self.screenshot(b, p.max_side).await, + Some(b) => self.screenshot(&b, p.max_side).await, None => bridge_only("ui_screenshot"), } } diff --git a/crates/automation/src/server/conventions.rs b/crates/automation/src/server/conventions.rs index 6e2740041d..c9e080d811 100644 --- a/crates/automation/src/server/conventions.rs +++ b/crates/automation/src/server/conventions.rs @@ -49,7 +49,10 @@ impl ServerHandler for PhotocraftMcp { let args = Value::Object(request.arguments.clone().unwrap_or_default()); let _: BatchParams = serde_json::from_value(args).map_err(|e| McpError::invalid_params(e.to_string(), None))?; } - if request.name == "command_run" && matches!(&*self.backend, Backend::Headless(_)) { + if let Err(error) = self.ready().await { + return Ok(fail(error).into()); + } + if request.name == "command_run" && self.headless_session().is_some() { let args = Value::Object(request.arguments.clone().unwrap_or_default()); let params: RunParams = serde_json::from_value(args).map_err(|e| McpError::invalid_params(e.to_string(), None))?; if params.id == "file.export.renderVideo" { @@ -68,6 +71,9 @@ impl ServerHandler for PhotocraftMcp { } async fn read_resource(&self, request: ReadResourceRequestParams, _: RequestContext) -> Result { + if let Err(error) = self.ready().await { + return Err(McpError::internal_error(error, None)); + } let result = match request.uri.as_str() { DOCUMENT => self.doc_inspect(Parameters(DocIndex::default())).await?, COMMANDS => self.command_list(Parameters(ListParams::default())).await?, diff --git a/crates/automation/tests/mcp_live.rs b/crates/automation/tests/mcp_live.rs new file mode 100644 index 0000000000..161335f586 --- /dev/null +++ b/crates/automation/tests/mcp_live.rs @@ -0,0 +1,275 @@ +//! `photocraft-cli mcp --live` (Preferences › AI Integrations): the MCP server finds the desktop +//! app through its connection file before every call, follows it to a new port and token, and +//! applies the closed-app choice (start it, headless, or an error) when no app answers. + +use std::io::{BufRead, BufReader, Write}; +use std::net::TcpListener; +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::time::Duration; + +use photocraft_automation::PhotocraftMcp; +use photocraft_automation::agent_link::{self, Connection}; +use photocraft_automation::live::LiveConfig; +use photocraft_engine::prefs::WhenAppClosed; +use rmcp::model::{CallToolRequestParams, CallToolResult, ClientConfig}; +use rmcp::service::RunningService; +use rmcp::{ClientHandler, RoleClient, ServiceExt}; +use serde_json::{Value, json}; + +#[derive(Clone, Default)] +struct Client; +impl ClientHandler for Client { + fn get_info(&self) -> ClientConfig { + ClientConfig::default() + } +} + +async fn connect(server: PhotocraftMcp) -> RunningService { + let (s, c) = tokio::io::duplex(1 << 20); + tokio::spawn(async move { + if let Ok(running) = server.serve(s).await { + let _ = running.waiting().await; + } + }); + Client.serve(c).await.expect("client init") +} + +async fn call(client: &RunningService, name: &str, args: Value) -> CallToolResult { + let mut p = CallToolRequestParams::new(name.to_owned()); + if let Value::Object(m) = args { + p = p.with_arguments(m); + } + client.call_tool(p).await.expect("call_tool transport") +} + +fn text(r: &CallToolResult) -> String { + r.content.iter().filter_map(|c| c.as_text()).map(|t| t.text.clone()).collect::>().join("\n") +} + +fn settings_dir(tag: &str) -> PathBuf { + static N: AtomicUsize = AtomicUsize::new(0); + let d = std::env::temp_dir().join(format!("pc-mcp-live-{tag}-{}-{}", std::process::id(), N.fetch_add(1, Ordering::Relaxed))); + let _ = std::fs::remove_dir_all(&d); + std::fs::create_dir_all(&d).unwrap(); + d +} + +fn prefs(dir: &Path, integrations: Value) { + std::fs::write(dir.join("preferences.json"), json!({"integrations": integrations}).to_string()).unwrap(); +} + +/// A desktop app as `--live` sees it: a control server on a free port with a fresh token, its +/// connection file published in `dir`. `ui.inspect` answers with `name`. [`quit`] stops it. +struct FakeApp { + port: u16, + stop: Arc, +} + +fn fake_app(dir: &Path, name: &'static str) -> FakeApp { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let port = listener.local_addr().unwrap().port(); + let token_file = dir.join(agent_link::TOKEN_FILE); + let token = photocraft_automation::security::replace_token_file(&token_file).unwrap(); + agent_link::write_connection(dir, &Connection::new(port, token_file)).unwrap(); + let stop = Arc::new(std::sync::atomic::AtomicBool::new(false)); + let stopped = stop.clone(); + std::thread::spawn(move || { + for stream in listener.incoming().flatten() { + if stopped.load(Ordering::SeqCst) { + break; + } + let token = token.clone(); + std::thread::spawn(move || { + let mut out = stream.try_clone().unwrap(); + let mut authenticated = false; + for line in BufReader::new(stream).lines() { + let Ok(line) = line else { break }; + let req: Value = serde_json::from_str(&line).unwrap(); + let id = req["id"].clone(); + let reply = match req["method"].as_str().unwrap_or("") { + "auth" if req["params"]["token"] == token.as_str() => { + authenticated = true; + json!({"id": id, "ok": true, "result": {"authenticated": true}}) + } + _ if !authenticated => json!({"id": id, "ok": false, "error": "authentication required"}), + "ui.inspect" => json!({"id": id, "ok": true, "result": {"app": name}}), + m => json!({"id": id, "ok": false, "error": format!("unexpected {m}")}), + }; + if writeln!(out, "{reply}").is_err() || !authenticated { + break; + } + } + }); + } + }); + FakeApp { port, stop } +} + +/// The fake app quits: its port stops accepting (connections already open end with the test). +fn quit(app: FakeApp) { + app.stop.store(true, Ordering::SeqCst); + let _ = std::net::TcpStream::connect(("127.0.0.1", app.port)); + while agent_link::probe(app.port, Duration::from_millis(200)) { + std::thread::sleep(Duration::from_millis(10)); + } +} + +fn live(dir: &Path, when_closed: Option) -> LiveConfig { + let mut c = LiveConfig::new(dir.to_path_buf()); + c.when_closed = when_closed; + c.launch_timeout = Duration::from_secs(10); + c +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_closed_app_is_a_tool_error_that_says_what_to_do() { + let dir = settings_dir("closed"); + let client = connect(PhotocraftMcp::live(live(&dir, Some(WhenAppClosed::Error)))).await; + // The tool list doesn't need the app. + assert!(client.list_all_tools().await.unwrap().iter().any(|t| t.name == "ui_inspect")); + let r = call(&client, "ui_inspect", json!({})).await; + assert_eq!(r.is_error, Some(true)); + assert!(text(&r).contains("Let AI agents connect"), "connection off: {}", text(&r)); + prefs(&dir, json!({"connectAgents": true})); + let r = call(&client, "command_list", json!({})).await; + assert_eq!(r.is_error, Some(true)); + assert!(text(&r).contains("isn't running"), "{}", text(&r)); + // A connection file left by a crashed app (nothing listens) counts as closed. + let gone = TcpListener::bind("127.0.0.1:0").unwrap(); + let port = gone.local_addr().unwrap().port(); + drop(gone); + agent_link::write_connection(&dir, &Connection::new(port, dir.join(agent_link::TOKEN_FILE))).unwrap(); + let r = call(&client, "ui_inspect", json!({})).await; + assert!(text(&r).contains("isn't running"), "{}", text(&r)); + client.cancel().await.unwrap(); + let _ = std::fs::remove_dir_all(&dir); +} + +#[tokio::test(flavor = "multi_thread")] +async fn follows_the_app_across_restarts_on_new_ports_and_tokens() { + let dir = settings_dir("follow"); + prefs(&dir, json!({"connectAgents": true, "whenAppClosed": "error"})); + let client = connect(PhotocraftMcp::live(live(&dir, None))).await; + let first = fake_app(&dir, "first"); + let r = call(&client, "ui_inspect", json!({})).await; + assert_eq!(r.is_error, Some(false), "{}", text(&r)); + assert!(text(&r).contains("first")); + // Restart: another port, a new token. + quit(first); + let second = fake_app(&dir, "second"); + let r = call(&client, "ui_inspect", json!({})).await; + assert_eq!(r.is_error, Some(false), "{}", text(&r)); + assert!(text(&r).contains("second"), "{}", text(&r)); + quit(second); + std::fs::remove_file(dir.join(agent_link::CONNECTION_FILE)).unwrap(); + let r = call(&client, "ui_inspect", json!({})).await; + assert_eq!(r.is_error, Some(true)); + client.cancel().await.unwrap(); + let _ = std::fs::remove_dir_all(&dir); +} + +#[tokio::test(flavor = "multi_thread")] +async fn launch_starts_the_app_once_and_only_when_agents_may_connect() { + let dir = settings_dir("launch"); + let launches = Arc::new(AtomicUsize::new(0)); + let apps = Arc::new(std::sync::Mutex::new(Vec::new())); + let config = |dir: &Path| { + let mut c = live(dir, Some(WhenAppClosed::Launch)); + let (launches, apps, dir) = (launches.clone(), apps.clone(), dir.to_path_buf()); + c.launch = Some(Box::new(move || { + launches.fetch_add(1, Ordering::SeqCst); + let (apps, dir) = (apps.clone(), dir.clone()); + // The app takes a moment to start listening. + std::thread::spawn(move || { + std::thread::sleep(Duration::from_millis(300)); + apps.lock().unwrap().push(fake_app(&dir, "launched")); + }); + Ok(()) + })); + c + }; + // Agent connections off in the app: it would never listen, so it isn't started. + let client = connect(PhotocraftMcp::live(config(&dir))).await; + let r = call(&client, "ui_inspect", json!({})).await; + assert!(text(&r).contains("Let AI agents connect"), "{}", text(&r)); + assert_eq!(launches.load(Ordering::SeqCst), 0); + client.cancel().await.unwrap(); + + prefs(&dir, json!({"connectAgents": true})); + let client = connect(PhotocraftMcp::live(config(&dir))).await; + // Two calls at once start one app. + let (a, b) = tokio::join!(call(&client, "ui_inspect", json!({})), call(&client, "ui_inspect", json!({}))); + for r in [a, b] { + assert_eq!(r.is_error, Some(false), "{}", text(&r)); + assert!(text(&r).contains("launched")); + } + assert_eq!(launches.load(Ordering::SeqCst), 1); + client.cancel().await.unwrap(); + for app in apps.lock().unwrap().drain(..) { + quit(app); + } + let _ = std::fs::remove_dir_all(&dir); +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_launch_that_never_listens_times_out_with_advice() { + let dir = settings_dir("timeout"); + prefs(&dir, json!({"connectAgents": true})); + let mut c = live(&dir, Some(WhenAppClosed::Launch)); + c.launch_timeout = Duration::from_millis(600); + c.launch = Some(Box::new(|| Ok(()))); + let client = connect(PhotocraftMcp::live(c)).await; + let r = call(&client, "ui_inspect", json!({})).await; + assert_eq!(r.is_error, Some(true)); + assert!(text(&r).contains("didn't accept agents"), "{}", text(&r)); + // A launcher that fails says so. + let mut c = live(&dir, Some(WhenAppClosed::Launch)); + c.launch = Some(Box::new(|| Err("no such file".into()))); + let client2 = connect(PhotocraftMcp::live(c)).await; + let r = call(&client2, "ui_inspect", json!({})).await; + assert!(text(&r).contains("couldn't start PhotoCraft: no such file"), "{}", text(&r)); + // No launcher (Flatpak, the app not installed beside the CLI): ask the user. + let client3 = connect(PhotocraftMcp::live(live(&dir, Some(WhenAppClosed::Launch)))).await; + let r = call(&client3, "ui_inspect", json!({})).await; + assert!(text(&r).contains("open PhotoCraft"), "{}", text(&r)); + for c in [client, client2, client3] { + c.cancel().await.unwrap(); + } + let _ = std::fs::remove_dir_all(&dir); +} + +#[tokio::test(flavor = "multi_thread")] +async fn headless_uses_the_app_folders_and_stays_headless() { + let dir = settings_dir("headless"); + let work = dir.join("work"); + std::fs::create_dir_all(&work).unwrap(); + prefs(&dir, json!({"whenAppClosed": "headless", "writeFolder": work.to_string_lossy()})); + let client = connect(PhotocraftMcp::live(live(&dir, None))).await; + let r = call(&client, "doc_new", json!({"width": 8, "height": 8})).await; + assert_eq!(r.is_error, Some(false), "{}", text(&r)); + let r = call(&client, "doc_save", json!({"path": "out.pcraft"})).await; + assert_eq!(r.is_error, Some(false), "{}", text(&r)); + assert!(work.join("out.pcraft").exists(), "saved into the app's write folder"); + // No read folder was chosen: reads are refused. + let r = call(&client, "doc_open", json!({"path": "out.pcraft"})).await; + assert_eq!(r.is_error, Some(true)); + // The app starting later doesn't move the documents away from the agent. + let app = fake_app(&dir, "late"); + let r = call(&client, "ui_inspect", json!({})).await; + assert!(text(&r).contains("bridge"), "UI tools stay unavailable in the headless session: {}", text(&r)); + let r = call(&client, "session_list", json!({})).await; + assert_eq!(r.is_error, Some(false), "{}", text(&r)); + client.cancel().await.unwrap(); + quit(app); + // A folder that doesn't exist is a clear error, not a crash. + prefs(&dir, json!({"whenAppClosed": "headless", "readFolder": dir.join("missing").to_string_lossy()})); + std::fs::remove_file(dir.join(agent_link::CONNECTION_FILE)).unwrap(); + let client = connect(PhotocraftMcp::live(live(&dir, None))).await; + let r = call(&client, "command_list", json!({})).await; + assert_eq!(r.is_error, Some(true)); + assert!(text(&r).contains("agent folders"), "{}", text(&r)); + client.cancel().await.unwrap(); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/engine/src/prefs.rs b/crates/engine/src/prefs.rs index b163d40d88..fa11bb32e2 100644 --- a/crates/engine/src/prefs.rs +++ b/crates/engine/src/prefs.rs @@ -108,6 +108,11 @@ choice!(FontPreview { Off = "off", Small = "small", Medium = "medium", Large = " choice!(RawColorSpace { Srgb = "srgb", AdobeRgb = "adobeRgb", ProPhoto = "proPhoto", DisplayP3 = "displayP3" } default AdobeRgb); choice!(RawDepth { Eight = "8", Sixteen = "16" } default Sixteen); choice!(RawSharpen { None = "none", Screen = "screen", Glossy = "glossy", Matte = "matte" } default None); +choice!( + /// AI Integrations › When PhotoCraft Is Closed: what `photocraft-cli mcp --live` does when an + /// agent calls a tool and the app isn't running. + WhenAppClosed { Launch = "launch", Headless = "headless", Error = "error" } default Launch +); impl Unit { /// Document pixels → this unit. `dpi` is the document resolution, `extent` the 100% length @@ -935,13 +940,29 @@ impl Default for RawDefaults { pub struct Integrations { /// Allow agents to drive the app over the loopback control channel / MCP bridge. pub allow_agent_control: bool, - /// Default control port (0 = only when `--control` is given). + /// Let AI agents connect: the desktop app listens on loopback for `photocraft-cli mcp --live` + /// without `--control` (off by default; launch flags still win). + pub connect_agents: bool, + /// Port agents connect to (0 = any free port, published in the connection file). pub control_port: u32, + /// Folder agents may open files from (empty = none). + pub read_folder: String, + /// Folder agents may save files to (empty = none). + pub write_folder: String, + /// What `photocraft-cli mcp --live` does while the app is closed. + pub when_app_closed: WhenAppClosed, } impl Default for Integrations { fn default() -> Self { - Self { allow_agent_control: true, control_port: 0 } + Self { + allow_agent_control: true, + connect_agents: false, + control_port: 0, + read_folder: String::new(), + write_folder: String::new(), + when_app_closed: WhenAppClosed::Launch, + } } } @@ -1077,10 +1098,8 @@ pub const HIDDEN_UNTIL_IMPLEMENTED: &[&str] = &[ "rawDefaults.sharpenFor", "rawDefaults.openAsSmartObject", "rawDefaults.applyAutoTone", - // Agent access is governed by the launch flags (`--control`, the automation roots), not - // by these yet. + // Agent access is governed by `integrations.connectAgents` and the launch flags. "integrations.allowAgentControl", - "integrations.controlPort", ]; /// Is the preference at `path` (`"section.key"`) hidden from the Preferences dialog? @@ -1128,6 +1147,7 @@ pub fn choices(path: &str) -> Option<&'static [&'static str]> { "performance.gpuBackend" => GpuBackend::NAMES, "performance.linuxDisplayServer" => LinuxDisplayServer::NAMES, "performance.renderingMode" => RenderingMode::NAMES, + "integrations.whenAppClosed" => WhenAppClosed::NAMES, _ => return None, }) } diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 209691b875..38270248f3 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -1319,6 +1319,7 @@ pub fn inspect(app: &PhotocraftApp, ctx: &egui::Context) -> Value { "brush": {"size": app.session.tools.brush.size, "hardness": app.session.tools.brush.hardness, "opacity": app.session.tools.brush.opacity}, "distort": app.distort.describe(), "jobs": crate::jobs_ui::inspect(app), + "agentLink": app.agent_link, "cameraRaw": app.camera_raw.as_ref().map(|d| d.describe(&app.ui.camera_raw_scope, &app.ui.camera_raw_preview)), }) } diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 01a8b9e4d9..ae6d69d5eb 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -3752,3 +3752,22 @@ navigator Zoom Zvětšení Sent to {printer} Odesláno do {printer} set in Print Settings… nastavuje se v nastavení tisku… ICO is limited to 256 × 256 pixels ICO je omezen na 256 × 256 pixelů +# Edit › Preferences › AI Integrations + Let AI agents connect (MCP) Povolit připojení agentů AI (MCP) + AI apps such as Claude can then open, edit and save documents here. Only programs on this computer can connect. Aplikace AI, jako je Claude, pak mohou zde otevírat, upravovat a ukládat dokumenty. Připojit se mohou jen programy na tomto počítači. + 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 + 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ý + Open PhotoCraft Otevřít PhotoCraft + Work without a window Pracovat bez okna + Ask to open PhotoCraft Požádat o otevření PhotoCraftu + Connect an AI app Připojit aplikaci AI + Add to Claude Desktop Přidat do Claude Desktop + Add to Claude Code Přidat do Claude Code + Add to Cursor Přidat do Cursoru + Copy Configuration Kopírovat konfiguraci + Configuration copied. Konfigurace zkopírována. diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 489647ed21..3f170a65a9 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -3142,3 +3142,22 @@ curves Smooth Glätten Sent to {printer} An {printer} gesendet set in Print Settings… in den Druckeinstellungen festlegen… ICO is limited to 256 × 256 pixels ICO ist auf 256 × 256 Pixel begrenzt +# Edit › Preferences › AI Integrations + Let AI agents connect (MCP) KI-Agenten verbinden lassen (MCP) + AI apps such as Claude can then open, edit and save documents here. Only programs on this computer can connect. KI-Apps wie Claude können dann hier Dokumente öffnen, bearbeiten und speichern. Nur Programme auf diesem Computer können sich verbinden. + 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 + 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 + Open PhotoCraft PhotoCraft öffnen + Work without a window Ohne Fenster arbeiten + Ask to open PhotoCraft Zum Öffnen von PhotoCraft auffordern + Connect an AI app KI-App verbinden + Add to Claude Desktop Zu Claude Desktop hinzufügen + Add to Claude Code Zu Claude Code hinzufügen + Add to Cursor Zu Cursor hinzufügen + Copy Configuration Konfiguration kopieren + Configuration copied. Konfiguration kopiert. diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 410da1a188..fafb9b6a7c 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -3842,3 +3842,22 @@ curves Smooth Εξομάλυνση Sent to {printer} Στάλθηκε στον {printer} set in Print Settings… ορίζεται στις ρυθμίσεις εκτύπωσης… ICO is limited to 256 × 256 pixels Το ICO περιορίζεται σε 256 × 256 εικονοστοιχεία +# Edit › Preferences › AI Integrations + Let AI agents connect (MCP) Να επιτρέπεται η σύνδεση πρακτόρων AI (MCP) + AI apps such as Claude can then open, edit and save documents here. Only programs on this computer can connect. Εφαρμογές AI όπως το Claude μπορούν τότε να ανοίγουν, να επεξεργάζονται και να αποθηκεύουν έγγραφα εδώ. Μόνο προγράμματα σε αυτόν τον υπολογιστή μπορούν να συνδεθούν. + 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 επιλέγει μια ελεύθερη θύρα + Folder agents can open from Φάκελος από τον οποίο ανοίγουν οι πράκτορες + Folder agents can save to Φάκελος όπου αποθηκεύουν οι πράκτορες + When PhotoCraft is closed Όταν το PhotoCraft είναι κλειστό + Open PhotoCraft Άνοιγμα του PhotoCraft + Work without a window Εργασία χωρίς παράθυρο + Ask to open PhotoCraft Αίτημα για άνοιγμα του PhotoCraft + Connect an AI app Σύνδεση εφαρμογής AI + Add to Claude Desktop Προσθήκη στο Claude Desktop + Add to Claude Code Προσθήκη στο Claude Code + Add to Cursor Προσθήκη στο Cursor + Copy Configuration Αντιγραφή ρυθμίσεων + Configuration copied. Οι ρυθμίσεις αντιγράφηκαν. diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index b5db4e9925..23e97328bc 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -2829,3 +2829,22 @@ curves Smooth Suavizar Sent to {printer} Enviado a {printer} set in Print Settings… se establece en Ajustes de impresión… ICO is limited to 256 × 256 pixels ICO está limitado a 256 × 256 píxeles +# Edit › Preferences › AI Integrations + Let AI agents connect (MCP) Permitir que se conecten agentes de IA (MCP) + AI apps such as Claude can then open, edit and save documents here. Only programs on this computer can connect. Las apps de IA como Claude podrán abrir, editar y guardar documentos aquí. Solo pueden conectarse programas de este equipo. + 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 + 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 + Open PhotoCraft Abrir PhotoCraft + Work without a window Trabajar sin ventana + Ask to open PhotoCraft Pedir que se abra PhotoCraft + Connect an AI app Conectar una app de IA + Add to Claude Desktop Añadir a Claude Desktop + Add to Claude Code Añadir a Claude Code + Add to Cursor Añadir a Cursor + Copy Configuration Copiar configuración + Configuration copied. Configuración copiada. diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index ab0cca6f40..56762f1a0e 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -3146,3 +3146,22 @@ curves Smooth Lisser Sent to {printer} Envoyé à {printer} set in Print Settings… défini dans les paramètres d’impression… ICO is limited to 256 × 256 pixels Le format ICO est limité à 256 × 256 pixels +# Edit › Preferences › AI Integrations + Let AI agents connect (MCP) Autoriser la connexion des agents IA (MCP) + AI apps such as Claude can then open, edit and save documents here. Only programs on this computer can connect. Les applications d’IA comme Claude peuvent alors ouvrir, modifier et enregistrer des documents ici. Seuls les programmes de cet ordinateur peuvent se connecter. + 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 + 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é + Open PhotoCraft Ouvrir PhotoCraft + Work without a window Travailler sans fenêtre + Ask to open PhotoCraft Demander d’ouvrir PhotoCraft + Connect an AI app Connecter une application d’IA + Add to Claude Desktop Ajouter à Claude Desktop + Add to Claude Code Ajouter à Claude Code + Add to Cursor Ajouter à Cursor + Copy Configuration Copier la configuration + Configuration copied. Configuration copiée. diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 9a7283a5a1..4f33903e2a 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -4065,3 +4065,22 @@ cameraRaw Yellow Sárga Ink Characteristics Festék jellemzői Solidity: Fedőképesség: Redrawing Újrarajzolás +# Edit › Preferences › AI Integrations + Let AI agents connect (MCP) AI-ügynökök csatlakozásának engedélyezése (MCP) + AI apps such as Claude can then open, edit and save documents here. Only programs on this computer can connect. Az AI-alkalmazások, például a Claude, ezután itt megnyithatnak, szerkeszthetnek és menthetnek dokumentumokat. Csak az ezen a számítógépen futó programok csatlakozhatnak. + 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 + 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 + Open PhotoCraft PhotoCraft megnyitása + Work without a window Munka ablak nélkül + Ask to open PhotoCraft Kérés a PhotoCraft megnyitására + Connect an AI app AI-alkalmazás csatlakoztatása + Add to Claude Desktop Hozzáadás a Claude Desktophoz + Add to Claude Code Hozzáadás a Claude Code-hoz + Add to Cursor Hozzáadás a Cursorhoz + Copy Configuration Konfiguráció másolása + Configuration copied. Konfiguráció másolva. diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 6924c45609..2190820cec 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -3133,3 +3133,22 @@ curves Smooth Haluskan Sent to {printer} Dikirim ke {printer} set in Print Settings… diatur di Pengaturan Cetak… ICO is limited to 256 × 256 pixels ICO dibatasi hingga 256 × 256 piksel +# Edit › Preferences › AI Integrations + Let AI agents connect (MCP) Izinkan agen AI terhubung (MCP) + AI apps such as Claude can then open, edit and save documents here. Only programs on this computer can connect. Aplikasi AI seperti Claude kemudian dapat membuka, mengedit, dan menyimpan dokumen di sini. Hanya program di komputer ini yang dapat terhubung. + 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 + 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 + Open PhotoCraft Buka PhotoCraft + Work without a window Bekerja tanpa jendela + Ask to open PhotoCraft Minta untuk membuka PhotoCraft + Connect an AI app Hubungkan aplikasi AI + Add to Claude Desktop Tambahkan ke Claude Desktop + Add to Claude Code Tambahkan ke Claude Code + Add to Cursor Tambahkan ke Cursor + Copy Configuration Salin Konfigurasi + Configuration copied. Konfigurasi disalin. diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 2d42c550cc..cc2c5b7f77 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -4107,3 +4107,22 @@ navigator Zoom Zoom Sent to {printer} Inviato a {printer} set in Print Settings… impostato nelle impostazioni di stampa… ICO is limited to 256 × 256 pixels ICO è limitato a 256 × 256 pixel +# Edit › Preferences › AI Integrations + Let AI agents connect (MCP) Consenti la connessione degli agenti IA (MCP) + AI apps such as Claude can then open, edit and save documents here. Only programs on this computer can connect. Le app di IA come Claude potranno aprire, modificare e salvare documenti qui. Possono connettersi solo i programmi di questo computer. + 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 + 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 + Open PhotoCraft Apri PhotoCraft + Work without a window Lavora senza finestra + Ask to open PhotoCraft Chiedi di aprire PhotoCraft + Connect an AI app Connetti un’app di IA + Add to Claude Desktop Aggiungi a Claude Desktop + Add to Claude Code Aggiungi a Claude Code + Add to Cursor Aggiungi a Cursor + Copy Configuration Copia configurazione + Configuration copied. Configurazione copiata. diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index e05f27d718..0a9e47be7b 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -3821,3 +3821,22 @@ curves Smooth スムーズ Reset All Locked Settings ロックされた設定をすべて初期化 Copy Texture to Other Tools テクスチャを他のツールにコピー ICO is limited to 256 × 256 pixels ICO は 256 × 256 ピクセルまでです +# Edit › Preferences › AI Integrations + Let AI agents connect (MCP) AI エージェントの接続を許可 (MCP) + AI apps such as Claude can then open, edit and save documents here. Only programs on this computer can connect. Claude などの AI アプリがここでドキュメントを開き、編集し、保存できるようになります。接続できるのはこのコンピューター上のプログラムだけです。 + 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 で空いているポートを選択 + Folder agents can open from エージェントが開けるフォルダー + Folder agents can save to エージェントが保存できるフォルダー + When PhotoCraft is closed PhotoCraft が閉じているとき + Open PhotoCraft PhotoCraft を開く + Work without a window ウィンドウなしで作業 + Ask to open PhotoCraft PhotoCraft を開くよう求める + Connect an AI app AI アプリを接続 + Add to Claude Desktop Claude Desktop に追加 + Add to Claude Code Claude Code に追加 + Add to Cursor Cursor に追加 + Copy Configuration 設定をコピー + Configuration copied. 設定をコピーしました。 diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 7de9f61f10..cf546fd520 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -3319,3 +3319,22 @@ curves Smooth 매끄럽게 Sent to {printer} {printer}(으)로 전송됨 set in Print Settings… 인쇄 설정에서 지정… ICO is limited to 256 × 256 pixels ICO는 256 × 256픽셀로 제한됩니다 +# Edit › Preferences › AI Integrations + Let AI agents connect (MCP) AI 에이전트 연결 허용 (MCP) + AI apps such as Claude can then open, edit and save documents here. Only programs on this computer can connect. Claude 같은 AI 앱이 여기에서 문서를 열고 편집하고 저장할 수 있습니다. 이 컴퓨터의 프로그램만 연결할 수 있습니다. + 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은 빈 포트를 선택 + Folder agents can open from 에이전트가 열 수 있는 폴더 + Folder agents can save to 에이전트가 저장할 수 있는 폴더 + When PhotoCraft is closed PhotoCraft가 닫혀 있을 때 + Open PhotoCraft PhotoCraft 열기 + Work without a window 창 없이 작업 + Ask to open PhotoCraft PhotoCraft 열기 요청 + Connect an AI app AI 앱 연결 + Add to Claude Desktop Claude Desktop에 추가 + Add to Claude Code Claude Code에 추가 + Add to Cursor Cursor에 추가 + Copy Configuration 구성 복사 + Configuration copied. 구성을 복사했습니다. diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 4ed7d8a744..412dedd8cd 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -3904,3 +3904,22 @@ curves Smooth Vloeiend maken Sent to {printer} Verzonden naar {printer} set in Print Settings… instellen in de afdrukinstellingen… ICO is limited to 256 × 256 pixels ICO is beperkt tot 256 × 256 pixels +# Edit › Preferences › AI Integrations + Let AI agents connect (MCP) AI-agents laten verbinden (MCP) + AI apps such as Claude can then open, edit and save documents here. Only programs on this computer can connect. AI-apps zoals Claude kunnen dan hier documenten openen, bewerken en opslaan. Alleen programma’s op deze computer kunnen verbinden. + 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 + 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 + Open PhotoCraft PhotoCraft openen + Work without a window Zonder venster werken + Ask to open PhotoCraft Vragen om PhotoCraft te openen + Connect an AI app Een AI-app verbinden + Add to Claude Desktop Toevoegen aan Claude Desktop + Add to Claude Code Toevoegen aan Claude Code + Add to Cursor Toevoegen aan Cursor + Copy Configuration Configuratie kopiëren + Configuration copied. Configuratie gekopieerd. diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index a27cb4af8d..c4896cd6c9 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -3742,3 +3742,22 @@ curves Smooth Wygładź Sent to {printer} Wysłano do {printer} set in Print Settings… ustawiane w ustawieniach druku… ICO is limited to 256 × 256 pixels ICO jest ograniczony do 256 × 256 pikseli +# Edit › Preferences › AI Integrations + Let AI agents connect (MCP) Zezwalaj na łączenie agentów AI (MCP) + AI apps such as Claude can then open, edit and save documents here. Only programs on this computer can connect. Aplikacje AI, takie jak Claude, będą mogły tu otwierać, edytować i zapisywać dokumenty. Połączyć się mogą tylko programy na tym komputerze. + 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 + 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 + Open PhotoCraft Otwórz PhotoCraft + Work without a window Pracuj bez okna + Ask to open PhotoCraft Poproś o otwarcie PhotoCraft + Connect an AI app Połącz aplikację AI + Add to Claude Desktop Dodaj do Claude Desktop + Add to Claude Code Dodaj do Claude Code + Add to Cursor Dodaj do Cursor + Copy Configuration Kopiuj konfigurację + Configuration copied. Skopiowano konfigurację. diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 0a64497704..23935471f4 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -3934,3 +3934,22 @@ layerLabel No Color Sem cor Sent to {printer} Enviado para {printer} set in Print Settings… definido nas configurações de impressão… ICO is limited to 256 × 256 pixels ICO é limitado a 256 × 256 pixels +# Edit › Preferences › AI Integrations + Let AI agents connect (MCP) Permitir que agentes de IA se conectem (MCP) + AI apps such as Claude can then open, edit and save documents here. Only programs on this computer can connect. Apps de IA como o Claude poderão abrir, editar e salvar documentos aqui. Só programas deste computador podem se conectar. + 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 + 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 + Open PhotoCraft Abrir o PhotoCraft + Work without a window Trabalhar sem janela + Ask to open PhotoCraft Pedir para abrir o PhotoCraft + Connect an AI app Conectar um app de IA + Add to Claude Desktop Adicionar ao Claude Desktop + Add to Claude Code Adicionar ao Claude Code + Add to Cursor Adicionar ao Cursor + Copy Configuration Copiar configuração + Configuration copied. Configuração copiada. diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 2dbbf4003c..49b37bd389 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -3110,3 +3110,22 @@ curves Smooth Сгладить Gray Value (Median) Уровень серого (медиана) Integrated Density Интегральная плотность Length Длина +# Edit › Preferences › AI Integrations + Let AI agents connect (MCP) Разрешить подключение ИИ-агентов (MCP) + AI apps such as Claude can then open, edit and save documents here. Only programs on this computer can connect. ИИ-приложения, такие как Claude, смогут открывать, редактировать и сохранять здесь документы. Подключаться могут только программы на этом компьютере. + 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 — выбрать свободный порт + Folder agents can open from Папка, из которой агенты могут открывать + Folder agents can save to Папка, в которую агенты могут сохранять + When PhotoCraft is closed Когда PhotoCraft закрыт + Open PhotoCraft Открыть PhotoCraft + Work without a window Работать без окна + Ask to open PhotoCraft Попросить открыть PhotoCraft + Connect an AI app Подключить ИИ-приложение + Add to Claude Desktop Добавить в Claude Desktop + Add to Claude Code Добавить в Claude Code + Add to Cursor Добавить в Cursor + Copy Configuration Копировать конфигурацию + Configuration copied. Конфигурация скопирована. diff --git a/crates/ui-egui/src/i18n/sr.tsv b/crates/ui-egui/src/i18n/sr.tsv index 4a5f7459df..8885c9043a 100644 --- a/crates/ui-egui/src/i18n/sr.tsv +++ b/crates/ui-egui/src/i18n/sr.tsv @@ -4219,3 +4219,22 @@ shape Appearance Izgled Ink Characteristics Karakteristike mastila Solidity: Punoća: Redrawing Ponovno iscrtavanje +# Edit › Preferences › AI Integrations + Let AI agents connect (MCP) Dozvoli povezivanje AI agenata (MCP) + AI apps such as Claude can then open, edit and save documents here. Only programs on this computer can connect. AI aplikacije kao što je Claude tada mogu ovde da otvaraju, uređuju i čuvaju dokumente. Mogu da se povežu samo programi na ovom računaru. + 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 + 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 + Open PhotoCraft Otvori PhotoCraft + Work without a window Radi bez prozora + Ask to open PhotoCraft Zatraži otvaranje PhotoCraft-a + Connect an AI app Poveži AI aplikaciju + Add to Claude Desktop Dodaj u Claude Desktop + Add to Claude Code Dodaj u Claude Code + Add to Cursor Dodaj u Cursor + Copy Configuration Kopiraj konfiguraciju + Configuration copied. Konfiguracija je kopirana. diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 01c37a18b2..8f7f1e48ef 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -3876,3 +3876,22 @@ cameraData Lens Lens Ink Characteristics Mürekkep Özellikleri Solidity: Doluluk: Redrawing Yeniden çiziliyor +# Edit › Preferences › AI Integrations + Let AI agents connect (MCP) Yapay zekâ ajanlarının bağlanmasına izin ver (MCP) + AI apps such as Claude can then open, edit and save documents here. Only programs on this computer can connect. Claude gibi yapay zekâ uygulamaları burada belge açabilir, düzenleyebilir ve kaydedebilir. Yalnızca bu bilgisayardaki programlar bağlanabilir. + 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 + 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 + Open PhotoCraft PhotoCraft’ı aç + Work without a window Pencere olmadan çalış + Ask to open PhotoCraft PhotoCraft’ı açmayı iste + Connect an AI app Bir yapay zekâ uygulaması bağla + Add to Claude Desktop Claude Desktop’a ekle + Add to Claude Code Claude Code’a ekle + Add to Cursor Cursor’a ekle + Copy Configuration Yapılandırmayı kopyala + Configuration copied. Yapılandırma kopyalandı. diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 79ebc8df36..1b175550fd 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -3843,3 +3843,22 @@ curves Smooth Згладити Sent to {printer} Надіслано на {printer} set in Print Settings… задається в параметрах друку… ICO is limited to 256 × 256 pixels ICO обмежено розміром 256 × 256 пікселів +# Edit › Preferences › AI Integrations + Let AI agents connect (MCP) Дозволити підключення ШІ-агентів (MCP) + AI apps such as Claude can then open, edit and save documents here. Only programs on this computer can connect. ШІ-застосунки, як-от Claude, зможуть відкривати, редагувати й зберігати тут документи. Підключатися можуть лише програми на цьому комп’ютері. + 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 — вибрати вільний порт + Folder agents can open from Тека, з якої агенти можуть відкривати + Folder agents can save to Тека, до якої агенти можуть зберігати + When PhotoCraft is closed Коли PhotoCraft закрито + Open PhotoCraft Відкрити PhotoCraft + Work without a window Працювати без вікна + Ask to open PhotoCraft Попросити відкрити PhotoCraft + Connect an AI app Підключити ШІ-застосунок + Add to Claude Desktop Додати до Claude Desktop + Add to Claude Code Додати до Claude Code + Add to Cursor Додати до Cursor + Copy Configuration Копіювати конфігурацію + Configuration copied. Конфігурацію скопійовано. diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 1fea5e6b38..bfd8f3e97d 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -3631,3 +3631,22 @@ curves Smooth Làm mượt Sent to {printer} Đã gửi tới {printer} set in Print Settings… đặt trong thiết lập in… ICO is limited to 256 × 256 pixels ICO giới hạn ở 256 × 256 pixel +# Edit › Preferences › AI Integrations + Let AI agents connect (MCP) Cho phép tác tử AI kết nối (MCP) + AI apps such as Claude can then open, edit and save documents here. Only programs on this computer can connect. Các ứng dụng AI như Claude khi đó có thể mở, chỉnh sửa và lưu tài liệu tại đây. Chỉ các chương trình trên máy tính này mới có thể kết nối. + 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 + 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 + Open PhotoCraft Mở PhotoCraft + Work without a window Làm việc không cần cửa sổ + Ask to open PhotoCraft Yêu cầu mở PhotoCraft + Connect an AI app Kết nối ứng dụng AI + Add to Claude Desktop Thêm vào Claude Desktop + Add to Claude Code Thêm vào Claude Code + Add to Cursor Thêm vào Cursor + Copy Configuration Sao chép cấu hình + Configuration copied. Đã sao chép cấu hình. diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 375b61c40b..43215345d3 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -2754,3 +2754,22 @@ curves Smooth 平滑 Sent to {printer} 已发送到 {printer} set in Print Settings… 在打印设置中设置… ICO is limited to 256 × 256 pixels ICO 最大为 256 × 256 像素 +# Edit › Preferences › AI Integrations + Let AI agents connect (MCP) 允许 AI 代理连接 (MCP) + AI apps such as Claude can then open, edit and save documents here. Only programs on this computer can connect. 之后,Claude 等 AI 应用可以在这里打开、编辑和保存文档。只有本机上的程序可以连接。 + 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 表示选择空闲端口 + Folder agents can open from 代理可打开的文件夹 + Folder agents can save to 代理可保存到的文件夹 + When PhotoCraft is closed PhotoCraft 关闭时 + Open PhotoCraft 打开 PhotoCraft + Work without a window 无窗口工作 + Ask to open PhotoCraft 请求打开 PhotoCraft + Connect an AI app 连接 AI 应用 + Add to Claude Desktop 添加到 Claude Desktop + Add to Claude Code 添加到 Claude Code + Add to Cursor 添加到 Cursor + Copy Configuration 复制配置 + Configuration copied. 已复制配置。 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index de931038db..e5e231a3de 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -2739,3 +2739,22 @@ curves Smooth 平滑 Sent to {printer} 已傳送至 {printer} set in Print Settings… 在列印設定中設定… ICO is limited to 256 × 256 pixels ICO 最大為 256 × 256 像素 +# Edit › Preferences › AI Integrations + Let AI agents connect (MCP) 允許 AI 代理程式連線 (MCP) + AI apps such as Claude can then open, edit and save documents here. Only programs on this computer can connect. 之後,Claude 等 AI 應用程式可以在這裡開啟、編輯和儲存文件。只有這台電腦上的程式可以連線。 + 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 表示選擇閒置連接埠 + Folder agents can open from 代理程式可開啟的資料夾 + Folder agents can save to 代理程式可儲存的資料夾 + When PhotoCraft is closed PhotoCraft 關閉時 + Open PhotoCraft 開啟 PhotoCraft + Work without a window 不開視窗工作 + Ask to open PhotoCraft 要求開啟 PhotoCraft + Connect an AI app 連線 AI 應用程式 + Add to Claude Desktop 加入 Claude Desktop + Add to Claude Code 加入 Claude Code + Add to Cursor 加入 Cursor + Copy Configuration 複製設定 + Configuration copied. 已複製設定。 diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 38118955c3..ed076286f5 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -336,6 +336,53 @@ pub type AutomationWriteFn = Box Result<(), String>>; pub type AutomationOpenPcraftFn = Box Result, String>>; /// Reject engine commands which still perform ambient filesystem I/O. pub type AutomationCommandFn = Box Result<(), String>>; +/// Same policy as [`AutomationCommandFn`] for each step a command runs (`actions.play`). +pub type AutomationAuthorizeFn = fn(&str, &Value) -> photocraft_engine::Result<()>; + +/// The automation half of [`Services`]: what control and MCP requests may read, write and run. +/// Replaced as a whole when Preferences › AI Integrations starts the agent connection or +/// changes its folders ([`Services::set_automation`]). +#[derive(Default)] +pub struct AutomationServices { + pub read: Option, + pub write: Option, + pub open_pcraft: Option, + pub save: Option, + pub command: Option, + pub authorize: Option, +} + +/// Preferences › AI Integrations: the agent connection as the dialog and `ui.inspect` show it. +#[derive(Clone, Debug, Default, PartialEq, Eq, serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct AgentLinkStatus { + /// Loopback port agents reach the app on, while it accepts them. + pub port: Option, + /// Started with `--control`: the launch flags manage the connection, not Preferences. + pub launch_flags: bool, + /// Why the connection, or one of its folders, couldn't be set up. + pub error: Option, + /// How an MCP client starts PhotoCraft's MCP server (`photocraft-cli mcp --live`). + pub mcp_command: Option, +} + +/// What [`Services::agent_link`] did after the AI Integrations settings changed. +#[derive(Default)] +pub struct AgentLink { + /// Requests from agents on a connection that just started (or moved to another port). + pub requests: Option>, + /// The connection stopped: drop the request channel. + pub stopped: bool, + /// What agent requests may read, write and run now. + pub automation: AutomationServices, + pub status: AgentLinkStatus, +} + +/// Starts, moves or stops the agent connection to match Preferences › AI Integrations. +pub type AgentLinkFn = Box AgentLink>; +/// Adds PhotoCraft to an MCP client (`claude-desktop`, `claude-code`, `cursor`), returning what +/// was done, or returns the configuration to paste into any client (`json`). +pub type AgentClientFn = Box Result>; /// Open a URL in the system browser (native) — reliable cross-platform, unlike `ctx.open_url`. pub type OpenUrlFn = Box Result<(), String>>; pub type EncodePngFn = Box Result, String>>; @@ -422,7 +469,12 @@ pub struct Services { /// Same policy as [`Self::automation_command`], as a function pointer the engine calls for /// each step of `actions.play`. Installed on the session only while a control request or /// an automation-driven [`PhotocraftApp::run`] runs, so a local play of a recorded `file.*` step still works. - pub automation_authorize: Option photocraft_engine::Result<()>>, + pub automation_authorize: Option, + /// Preferences › AI Integrations (desktop): starts, moves or stops the agent connection when + /// its settings change. `None` on the web, and when `--control` manages the connection. + pub agent_link: Option, + /// Preferences › AI Integrations' buttons that add PhotoCraft to MCP clients (desktop). + pub agent_clients: Option, /// Encode an RGBA8 image as PNG (used for screenshots and `ui.render`). pub encode_png: Option, /// Open a URL in the system browser (native). Falls back to `ctx.open_url` (web) when unset. @@ -488,6 +540,18 @@ pub struct Services { pub quit: Option, } +impl Services { + /// Install the automation services (see [`AutomationServices`]). + pub fn set_automation(&mut self, a: AutomationServices) { + self.automation_read = a.read; + self.automation_write = a.write; + self.automation_open_pcraft = a.open_pcraft; + self.automation_save = a.save; + self.automation_command = a.command; + self.automation_authorize = a.authorize; + } +} + /// A document histogram being computed off the UI thread: (document, revision, receiver of /// (document, compute ms, histograms)). pub(crate) type HistJob = (DocId, u64, std::sync::mpsc::Receiver<(DocId, f64, std::sync::Arc)>); @@ -578,6 +642,8 @@ pub struct PhotocraftApp { /// The first digit of a two-digit opacity typed on the number keys (`opacity_keys`, #352). pub(crate) opacity_keys: opacity_keys::Pending, control_rx: Option>, + /// Preferences › AI Integrations: the agent connection's state (see [`Services::agent_link`]). + pub agent_link: AgentLinkStatus, pending_screenshots: Vec<(u64, Option, Sender)>, /// Screenshots not yet requested from the viewport: (token, earliest time in ms, frames seen). queued_screenshots: Vec<(u64, f64, u32)>, @@ -805,6 +871,7 @@ impl PhotocraftApp { caps_lock: false, opacity_keys: None, control_rx: None, + agent_link: AgentLinkStatus::default(), pending_screenshots: Vec::new(), queued_screenshots: Vec::new(), input_waiters: Vec::new(), diff --git a/crates/ui-egui/src/prefs_ui.rs b/crates/ui-egui/src/prefs_ui.rs index db908ae23f..298a0649cf 100644 --- a/crates/ui-egui/src/prefs_ui.rs +++ b/crates/ui-egui/src/prefs_ui.rs @@ -52,6 +52,8 @@ pub struct Runtime { show_rulers: Option, /// Tool options as last remembered in the preferences (see `tool_memory`). pub(crate) tool_options: Option, + /// AI Integrations settings the agent connection was last set up for (`sync_agent_link`). + agent_link: Option, } /// The GPU canvas colours from Preferences › Transparency & Gamut. @@ -429,6 +431,7 @@ pub fn tick(app: &mut PhotocraftApp, ctx: &egui::Context) { sync_tooltips(app, ctx); sync_animations(app, ctx); app.sync_recent(); + sync_agent_link(app, ctx); if let Some(wait) = persist(app, ctx.input(|i| i.time)) { ctx.request_repaint_after(std::time::Duration::try_from_secs_f64(wait).unwrap_or_default()); } @@ -445,6 +448,26 @@ pub fn tick(app: &mut PhotocraftApp, ctx: &egui::Context) { history_log(app); } +/// Preferences › AI Integrations: start, move or stop the agent connection when its settings +/// change ([`crate::Services::agent_link`]); the first frame applies the saved settings. +fn sync_agent_link(app: &mut PhotocraftApp, ctx: &egui::Context) { + let Some(link) = app.services.agent_link.as_mut() else { return }; + let current = &app.session.prefs().integrations; + if app.prefs_rt.agent_link.as_ref() == Some(current) { + return; + } + let update = link(current, ctx); + app.prefs_rt.agent_link = Some(current.clone()); + if update.stopped { + app.control_rx = None; + } + if let Some(rx) = update.requests { + app.control_rx = Some(rx); + } + app.services.set_automation(update.automation); + app.agent_link = update.status; +} + /// First retry delay after a failed preferences write, in seconds; it doubles with every further /// failure up to [`SAVE_RETRY_MAX_S`]. A new change retries sooner, but no sooner than this. const SAVE_RETRY_S: f64 = 2.0; @@ -1010,8 +1033,13 @@ pub fn body(app: &mut PhotocraftApp, ui: &mut egui::Ui, f: &mut Map { f.insert("__gpuInfo".into(), json!(app.perf.gpu_info.lines())); + f.insert("__agentLink".into(), serde_json::to_value(&app.agent_link).unwrap_or(Value::Null)); + f.insert("__agentClients".into(), json!(app.services.agent_clients.is_some())); let system = system_theme(app, ui.ctx()); prefs_body(ui, f, system); + if let Some(action) = f.remove("__agentAction").and_then(|a| a.as_str().map(str::to_string)) { + agent_action(app, ui.ctx(), f, &action); + } } "shortcuts" => shortcuts_body(app, ui, f), "presets" => presets_body(app, ui, f), @@ -1042,6 +1070,14 @@ fn humanize(key: &str) -> String { if key == "notificationDurationSeconds" { return "Notification Duration (seconds)".into(); } + // AI Integrations: the labels its own rows show (`integration_rows`), also for search. + match key { + "connectAgents" => return "Let AI agents connect (MCP)".into(), + "readFolder" => return "Folder agents can open from".into(), + "writeFolder" => return "Folder agents can save to".into(), + "whenAppClosed" => return "When PhotoCraft is closed".into(), + _ => {} + } let mut s = String::new(); for (i, ch) in key.chars().enumerate() { if i == 0 { @@ -1070,6 +1106,10 @@ fn choice_label(v: &str) -> String { "metal" => "Metal".into(), "gl" => "OpenGL".into(), "cpu" => "CPU (no GPU acceleration)".into(), + // AI Integrations › When PhotoCraft is closed. + "launch" => "Open PhotoCraft".into(), + "headless" => "Work without a window".into(), + "error" => "Ask to open PhotoCraft".into(), v => humanize(v), } } @@ -1189,6 +1229,10 @@ fn prefs_body(ui: &mut egui::Ui, f: &mut Map, system: Option, obj: &mut Map, f: &mut Map) { + let t = Tokens::get(ui.ctx()); + let status = f.get("__agentLink").cloned().unwrap_or(Value::Null); + let launch_flags = status.get("launchFlags").and_then(Value::as_bool) == Some(true); + let mut on = obj.get("connectAgents").and_then(Value::as_bool).unwrap_or(false); + let label = humanize("connectAgents"); + ui.add_enabled_ui(!launch_flags, |ui| crate::widgets::checkbox(ui, &mut on, &label)); + obj.insert("connectAgents".into(), json!(on)); + ui.label( + RichText::new(tl!("AI apps such as Claude can then open, edit and save documents here. Only programs on this computer can connect.")).color(t.text_dim), + ); + ui.add_space(4.0); + let port = status.get("port").and_then(Value::as_u64); + let error = status.get("error").and_then(Value::as_str); + let (line, color) = match (launch_flags, port, error) { + (true, _, _) => (tl!("Managed by the launch options (--control).").to_string(), t.text_dim), + (false, _, Some(e)) => (e.to_string(), t.danger), + (false, Some(p), None) => (crate::i18n::fmt(tl!("Agents can connect on 127.0.0.1:{port}."), &[("port", &p.to_string())]), t.accent_text), + (false, None, None) => (tl!("Off: agents can't connect.").to_string(), t.text_faint), + }; + ui.label(RichText::new(line).color(color)); + ui.add_space(8.0); + egui::Grid::new("prefs-integrations").num_columns(2).spacing([14.0, 7.0]).show(ui, |ui| { + ui.label(RichText::new(tl!(&humanize("controlPort"))).color(t.text_dim)); + ui.horizontal(|ui| { + 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.end_row(); + for (key, pick) in [("readFolder", "chooseRead"), ("writeFolder", "chooseWrite")] { + ui.label(RichText::new(tl!(&humanize(key))).color(t.text_dim)); + ui.horizontal(|ui| { + let mut path = obj.get(key).and_then(Value::as_str).unwrap_or("").to_string(); + crate::widgets::text_field(ui, ui.id().with(key), &mut path, tl!("None"), 260.0, false); + obj.insert(key.into(), json!(path)); + if crate::widgets::secondary_button(ui, tl!("Browse…"), 70.0).clicked() { + f.insert("__agentAction".into(), json!(pick)); + } + }); + ui.end_row(); + } + ui.label(RichText::new(tl!(&humanize("whenAppClosed"))).color(t.text_dim)); + let mut cur = obj.get("whenAppClosed").and_then(Value::as_str).unwrap_or("launch").to_string(); + let options = prefs::choices("integrations.whenAppClosed").unwrap_or(&[]); + let labels: Vec = options.iter().map(|o| choice_label(o)).collect(); + let pairs: Vec<(String, &str)> = options.iter().map(|o| o.to_string()).zip(labels.iter().map(String::as_str)).collect(); + crate::widgets::dropdown(ui, "pref-integrations.whenAppClosed", &mut cur, &pairs, 220.0); + obj.insert("whenAppClosed".into(), json!(cur)); + ui.end_row(); + }); + if 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| { + for (id, label) in [ + ("claude-desktop", tl!("Add to Claude Desktop")), + ("claude-code", tl!("Add to Claude Code")), + ("cursor", tl!("Add to Cursor")), + ("json", tl!("Copy Configuration")), + ] { + if crate::widgets::secondary_button(ui, label, 120.0).clicked() { + f.insert("__agentAction".into(), json!(id)); + } + } + }); + } + if let Some(result) = f.get("__agentResult").and_then(Value::as_object) { + let ok = result.get("ok").and_then(Value::as_bool) == Some(true); + let text = result.get("message").and_then(Value::as_str).unwrap_or(""); + ui.label(RichText::new(text).color(if ok { t.text_dim } else { t.danger })); + } +} + +/// A button of [`integration_rows`]: choose a folder (into the dialog's working copy), or add +/// PhotoCraft to an MCP client through [`crate::Services::agent_clients`]. +fn agent_action(app: &mut PhotocraftApp, ctx: &egui::Context, f: &mut Map, action: &str) { + let key = match action { + "chooseRead" => Some("readFolder"), + "chooseWrite" => Some("writeFolder"), + _ => None, + }; + if let Some(key) = key { + let picked = app.ask_folder(move |app, path| { + if let Some(d) = app.ui.dialogs.iter_mut().find(|d| is_preferences(&d.fields)) + && let Some(obj) = d.fields.get_mut("values").and_then(|v| v.get_mut("integrations")).and_then(Value::as_object_mut) + { + obj.insert(key.into(), json!(path)); + } + Ok(Value::Null) + }); + if let Err(e) = picked { + f.insert("__agentResult".into(), json!({"ok": false, "message": e})); + } + return; + } + let Some(add) = app.services.agent_clients.as_mut() else { return }; + let result = match add(action) { + Ok(text) if action == "json" => { + ctx.copy_text(text); + json!({"ok": true, "message": tl!("Configuration copied.")}) + } + Ok(message) => json!({"ok": true, "message": message}), + Err(e) => json!({"ok": false, "message": e}), + }; + f.insert("__agentResult".into(), result); +} + /// One user-facing choice; legacy flags remain compatible with older settings. fn rendering_mode_row(ui: &mut egui::Ui, obj: &mut Map) { let mut current = rendering_mode_value(obj); @@ -2830,15 +2986,78 @@ mod tests { assert_eq!(both(&ctx2), [on, on]); } + #[test] + fn ai_integrations_start_and_stop_the_agent_connection_through_the_service() { + use std::sync::mpsc::channel; + let (mut app, _) = app_with_store(); + let ctx = egui::Context::default(); + let calls: Arc>> = Arc::default(); + let seen = calls.clone(); + let (tx, rx) = channel::(); + let mut rx = Some(rx); + app.services.agent_link = Some(Box::new(move |p: &prefs::Integrations, _: &egui::Context| { + seen.lock().unwrap().push(p.clone()); + let mut out = crate::AgentLink { stopped: !p.connect_agents, ..Default::default() }; + if p.connect_agents { + out.requests = rx.take(); + out.status.port = Some(4321); + out.automation.command = Some(Box::new(|_, _| Err("policy".into()))); + } + out + })); + // The first frame applies the saved settings (off), once. + tick(&mut app, &ctx); + tick(&mut app, &ctx); + assert_eq!(calls.lock().unwrap().len(), 1); + assert!(app.control_rx.is_none() && app.agent_link.port.is_none()); + // On: the request channel and the automation policy are installed. + app.run("prefs.set", json!({"values": {"integrations.connectAgents": true, "integrations.readFolder": "/work"}})).unwrap(); + tick(&mut app, &ctx); + assert_eq!(calls.lock().unwrap().last().map(|p| (p.connect_agents, p.read_folder.clone())), Some((true, "/work".into()))); + assert!(app.control_rx.is_some()); + assert!(app.services.automation_command.is_some()); + assert_eq!(app.agent_link.port, Some(4321)); + assert!(tx.send(crate::ControlRequest::new("ui.inspect", json!({})).0).is_ok(), "the app holds the receiver"); + // An unrelated preference doesn't touch the connection. + app.run("prefs.set", json!({"values": {"performance.historyStates": 12}})).unwrap(); + tick(&mut app, &ctx); + assert_eq!(calls.lock().unwrap().len(), 2); + // Off: the channel and the policy go. + app.run("prefs.set", json!({"values": {"integrations.connectAgents": false}})).unwrap(); + tick(&mut app, &ctx); + assert_eq!(calls.lock().unwrap().len(), 3); + assert!(app.control_rx.is_none() && app.services.automation_command.is_none()); + assert_eq!(app.agent_link.port, None); + // ui.inspect reports it. + assert!(crate::control::inspect(&app, &ctx).get("agentLink").is_some()); + } + + #[test] + fn ai_integrations_choices_and_paths_validate_through_prefs_set() { + let (mut app, _) = app_with_store(); + for v in ["launch", "headless", "error"] { + app.run("prefs.set", json!({"values": {"integrations.whenAppClosed": v}})).unwrap(); + assert_eq!(app.session.prefs().integrations.when_app_closed.name(), v); + } + assert!(app.run("prefs.set", json!({"values": {"integrations.whenAppClosed": "sometimes"}})).is_err()); + assert!( + app.run("prefs.set", json!({"values": {"integrations.controlPort": 70000}})).is_err() || app.session.prefs().integrations.control_port <= 65535 + ); + app.run("prefs.set", json!({"values": {"integrations.writeFolder": "/tmp/out"}})).unwrap(); + assert_eq!(app.session.prefs().integrations.write_folder, "/tmp/out"); + } + #[test] fn unimplemented_preferences_are_hidden_from_the_dialog() { let values = prefs::Preferences::default().to_json(); assert!(has_visible_fields(&values, "general")); assert!(has_visible_fields(&values, "fileHandling")); - // Every setting of these sections is still unimplemented. - for section in ["integrations", "scratchDisks"] { - assert!(!has_visible_fields(&values, section), "{section}"); - } + // Every setting of this section is still unimplemented. + assert!(!has_visible_fields(&values, "scratchDisks")); + // AI Integrations: the agent connection is live; the older Allow Agent Control isn't. + assert!(has_visible_fields(&values, "integrations")); + assert!(!prefs::is_hidden("integrations.connectAgents")); + assert!(prefs::is_hidden("integrations.allowAgentControl")); // "Fill new type layers with placeholder text" and "Use Escape to Commit" are live; other Type rows stay hidden. assert!(has_visible_fields(&values, "type")); assert!(!prefs::is_hidden("type.fillNewTypeLayersWithPlaceholder")); diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 771fec92e9..75311a8698 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -283,6 +283,10 @@ magenta alignment lines. `ui.pointer` drives the same code, so agents get identi - **Headless** (`photocraft-cli mcp`): an in-process `photocraft_engine::Session`. There is no window. - **Bridge** (`photocraft-cli mcp --bridge 127.0.0.1:7878 --control-token-file `): every tool is forwarded to a running `photocraft --control 7878 --control-token-file ` over this protocol, so agents see and drive the live app. +- **Live** (`photocraft-cli mcp --live`): the bridge, with the address and token read before every tool call from `agent-connection.json` in the app's settings folder. The app publishes that file while Edit › Preferences › AI Integrations › *Let AI agents connect* is on (not with `--control`), and removes it when the connection stops; a file left by a crash fails the connection probe and counts as no app. See [MCP conventions](mcp.md#connecting-the-desktop-app-no-terminal). + +`ui.inspect` reports the connection as `agentLink`: `port` while agents can connect, `launchFlags` when `--control` manages it, `error`, and `mcpCommand` (how MCP clients start the CLI). + The bridge keeps one authenticated TCP connection open, and drops and reconnects before a call once the connection has been idle long enough that the app (which closes idle connections after 30s) may have dropped it. A transport failure while sending a request or waiting for its reply, including a reply timeout, drops the connection and reports that the operation may have completed; inspect the document before retrying an edit. Edits are never automatically resent (#1007); a connection that could not be established is reported as "the request was not sent" instead. The MCP server opts its pure-read tools (`ui_inspect`, `doc_inspect`, `command_list`, `jobs_list`, `session_list`, `ui_screenshot`) into one automatic retry on a fresh connection, since a read applies nothing; clients driving `BridgeClient` directly opt in per call with `call_read`. The next separate call reconnects and authenticates, and reply lines whose `id` does not match the request are skipped. The client's call timeout is 55s, strictly below the server's 60s reply deadline, so the bridge's error is the one callers see; commands that can run longer should pass `"wait": false` and poll `jobs.list`. It only accepts loopback addresses, because the app only listens on loopback. Supply its bearer token with `--control-token-file`, `--control-token`, `PHOTOCRAFT_CONTROL_TOKEN_FILE`, or `PHOTOCRAFT_CONTROL_TOKEN`: ```sh @@ -329,7 +333,9 @@ Filesystem access fails closed unless launch-time read and/or write roots are gr (`PHOTOCRAFT_AUTOMATION_READ_ROOT` / `PHOTOCRAFT_AUTOMATION_WRITE_ROOT`) are supported by the desktop `photocraft` process, but not by headless `photocraft-cli mcp` or `serve`; for those CLI modes, supply the flags explicitly. In MCP bridge mode, configure roots on the -desktop process rather than on the bridging CLI. Request paths must be +desktop process rather than on the bridging CLI. With *Let AI agents connect*, the roots are the +folders chosen in Preferences › AI Integrations; `mcp --live` uses them for a headless session only +when the app's *When PhotoCraft is closed* choice (or `--when-closed headless`) asks for one. Request paths must be non-empty, forward-slash relative paths beneath the applicable root, or absolute paths that lie beneath it. An absolute path is compared with the root as text and the rest is checked like a relative path; nothing is resolved on the filesystem. Absolute paths outside the root, parent diff --git a/docs/development.md b/docs/development.md index 3c539f70bc..61d6460cb0 100644 --- a/docs/development.md +++ b/docs/development.md @@ -204,6 +204,7 @@ At startup the desktop lists recovery metadata, then decodes one document at a t - **Headless:** `photocraft-cli mcp --automation-read-root --automation-write-root `. It drives an in-process engine session and has no file authority when a root is omitted. - **Live app:** start `photocraft --control 7878 --control-token-file --automation-read-root --automation-write-root `, then run `photocraft-cli mcp --bridge 127.0.0.1:7878 --control-token-file `. The desktop process owns the roots. See `docs/control-protocol.md#mcp-bridge`. +- **Live app, no flags:** turn on Edit › Preferences › AI Integrations › Let AI agents connect, then point the MCP client at `photocraft-cli mcp --live` (the panel's buttons, or `photocraft-cli mcp install --client `, do it). The app publishes its port and token file in `agent-connection.json` in the settings folder; `--live` reads it on every call. See [MCP conventions](mcp.md#connecting-the-desktop-app-no-terminal). Test it against a scratch settings folder with `PHOTOCRAFT_CONFIG_DIR`, which both the app and the CLI honour. For headless MCP clients, pass absolute paths to deliberately chosen trusted workspace directories in the launch arguments. Desktop `PHOTOCRAFT_AUTOMATION_READ_ROOT` and `PHOTOCRAFT_AUTOMATION_WRITE_ROOT` environment variables do **not** grant headless CLI access. Omitting a root flag deliberately denies that direction of access. diff --git a/docs/mcp.md b/docs/mcp.md index 3046a669bc..a76050e58b 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1,5 +1,36 @@ # MCP conventions +## Connecting the desktop app (no terminal) + +1. In PhotoCraft, open **Edit › Preferences › AI Integrations** and turn on **Let AI agents + connect (MCP)**. Optionally choose the folders agents can open from and save to, and what + 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. + +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 +`agent-connection.json` there; `--live` reads that file before every tool call, so the client +configuration holds no port or token and keeps working when PhotoCraft restarts. The token is +replaced each time the connection starts. Started with `--control`, the app ignores these +settings and the launch flags manage the connection, as before. + +From a terminal, `photocraft-cli mcp install --client ` +does what the buttons do. `--when-closed ` on `mcp --live` overrides the +app's choice. In a headless session started that way, the folders chosen in the app (or +`--automation-read-root` / `--automation-write-root` given to `mcp --live`) are the roots, and 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 +`flatpak override --user --share=network ai.storyteller.photocraft`. + +## Headless sessions + PhotoCraft follows the same conventions as FilmCraft #28. Start a headless session: ```sh diff --git a/docs/scorecard.md b/docs/scorecard.md index 56a16654bd..cf16991a92 100644 --- a/docs/scorecard.md +++ b/docs/scorecard.md @@ -9,9 +9,9 @@ Generated by `cargo xtask scorecard` from `perf/budgets.toml`, `perf/baseline.js | [Performance](#performance) | 3 | 22 | 22 | 56 scenarios: 3 within budget, 22 over budget or failing, 9 tracked only, 17 not run, 5 not measurable yet (baseline 2026-10-05) | | [File compatibility](#file-compatibility) | 7 | 13 | 7 | io corpus: oracle ≥ 146/170, round trip ≥ 169/170; psd-tools corpus: oracle ≥ 236/309, round trip ≥ 308/309; photoshop oracles: oracle ≥ 145/256, round trip ≥ 258/256 | | [Tools](#tools) | 29 | 13 | 1 | | -| [Workspace and UI](#workspace-and-ui) | 13 | 6 | 4 | settings that do nothing: 26 of 157 (target 0) | +| [Workspace and UI](#workspace-and-ui) | 13 | 6 | 4 | settings that do nothing: 25 of 161 (target 0) | | [Type](#type) | 4 | 3 | 2 | | -| [Automation](#automation) | 5 | 2 | 4 | 631 of 631 menu items live (100.0%) | +| [Automation](#automation) | 6 | 2 | 4 | 631 of 631 menu items live (100.0%) | | [Reliability](#reliability) | 5 | 2 | 0 | never-crash lints on 28 of 28 crates; panic_hunt present | | [Distribution](#distribution) | 5 | 4 | 2 | | | [Open bugs](#open-bugs) | 29 | 2 | 1 | | @@ -176,9 +176,9 @@ Corpus floors (`crates/io/tests/corpus.rs`): the enforced minimums; the corpus t ## Workspace and UI -**Settings that do nothing: 26 of 157** (target 0, #204). Counted by the prefs audit (`xtask/src/scorecard.rs`): a `Preferences` field counts as read when code outside the prefs model (`prefs.rs` except its `impl Session` blocks; tests excluded; the schema-driven dialog never names a field) accesses `section.field`, or `.section` and `.field` in the same file, or calls a section method that reads `self.field`. It is a heuristic lower bound: a generic name can look read when it isn't. +**Settings that do nothing: 25 of 161** (target 0, #204). Counted by the prefs audit (`xtask/src/scorecard.rs`): a `Preferences` field counts as read when code outside the prefs model (`prefs.rs` except its `impl Session` blocks; tests excluded; the schema-driven dialog never names a field) accesses `section.field`, or `.section` and `.field` in the same file, or calls a section method that reads `self.field`. It is a heuristic lower bound: a generic name can look read when it isn't. -Unread: `general.color_picker`, `general.animated_zoom`, `general.zoom_resizes_windows`, `workspace.auto_show_hidden_panels`, `workspace.enable_floating_document_window_docking`, `file_handling.save_in_background`, `performance.cache_levels`, `performance.legacy_compositing`, `scratch_disks.disks`, `units_and_rulers.column_width`, `units_and_rulers.gutter`, `plug_ins.show_extension_panels`, `plug_ins.allow_scripts_to_connect`, `plug_ins.generator_enabled`, `type_.text_engine`, `type_.recent_fonts`, `enhanced_controls.scrubby_slider_acceleration`, `enhanced_controls.touch_gestures`, `raw_defaults.color_space`, `raw_defaults.bit_depth`, `raw_defaults.resolution`, `raw_defaults.sharpen_for`, `raw_defaults.open_as_smart_object`, `raw_defaults.apply_auto_tone`, `integrations.allow_agent_control`, `integrations.control_port`. +Unread: `general.color_picker`, `general.animated_zoom`, `general.zoom_resizes_windows`, `workspace.auto_show_hidden_panels`, `workspace.enable_floating_document_window_docking`, `file_handling.save_in_background`, `performance.cache_levels`, `performance.legacy_compositing`, `scratch_disks.disks`, `units_and_rulers.column_width`, `units_and_rulers.gutter`, `plug_ins.show_extension_panels`, `plug_ins.allow_scripts_to_connect`, `plug_ins.generator_enabled`, `type_.text_engine`, `type_.recent_fonts`, `enhanced_controls.scrubby_slider_acceleration`, `enhanced_controls.touch_gestures`, `raw_defaults.color_space`, `raw_defaults.bit_depth`, `raw_defaults.resolution`, `raw_defaults.sharpen_for`, `raw_defaults.open_as_smart_object`, `raw_defaults.apply_auto_tone`, `integrations.allow_agent_control`. | Id | Target | Status | Issue | Note | |---|---|---|---|---| @@ -237,6 +237,7 @@ Menu wiring (`docs/parity-checklist.md`): 631 of 631 menu items live (100.0%). T | AUTO-219-8 | xtask check that every panel button routes through a command id | missing | [#219](https://github.com/storytold/photocraft/issues/219) | No such xtask check | | AUTO-219-9 | Headless commands for in-canvas type editing, Liquify/Puppet strokes, transform handles | done | [#219](https://github.com/storytold/photocraft/issues/219) | type.hitTest, type.caret, type.navigate; filter.liquify strokes, edit.puppetWarp pins, type.edit, edit.transform | | AUTO-219-10 | Agent acceptance suite grown to 30-50 workflows | partial | [#219](https://github.com/storytold/photocraft/issues/219) | automation/tests/agent_tasks.rs runs 10 workflows over MCP | +| AUTO-MCP-LIVE | Connect an MCP client to the running app without a terminal (no flags, ports or tokens to copy) | done | | 2026-10-14: Preferences › AI Integrations › Let AI agents connect starts the loopback control server at runtime and publishes agent-connection.json; photocraft-cli mcp --live finds the app on every call (launch / headless / error while it is closed); Add to Claude Desktop / Claude Code / Cursor and mcp install --client. automation/tests/mcp_live.rs, apps/photocraft/src/agent_link.rs tests | ## Reliability diff --git a/packaging/linux/AppRun b/packaging/linux/AppRun index f04c5f4eab..0fded52a4d 100755 --- a/packaging/linux/AppRun +++ b/packaging/linux/AppRun @@ -92,5 +92,13 @@ integrate() { done } +# `PhotoCraft.AppImage --cli ` runs the bundled photocraft-cli: MCP clients start +# `--cli mcp --live` this way (Preferences › AI Integrations), since the mount point that holds +# the CLI changes with every run. +if [ "${1:-}" = "--cli" ]; then + shift + exec "$APPDIR/usr/bin/photocraft-cli" "$@" +fi + integrate exec "$APPDIR/usr/bin/photocraft" "$@" diff --git a/packaging/linux/apprun-test.sh b/packaging/linux/apprun-test.sh index 475fb5ee5e..c5e96e9ed9 100755 --- a/packaging/linux/apprun-test.sh +++ b/packaging/linux/apprun-test.sh @@ -22,6 +22,8 @@ mkdir -p "$APPDIR/usr/share/icons" cp -R "$ROOT/assets/app-icon/hicolor" "$APPDIR/usr/share/icons/" printf '#!/bin/sh\necho "stub: $*"\n' >"$APPDIR/usr/bin/photocraft" chmod +x "$APPDIR/usr/bin/photocraft" +printf '#!/bin/sh\necho "cli stub: $*"\n' >"$APPDIR/usr/bin/photocraft-cli" +chmod +x "$APPDIR/usr/bin/photocraft-cli" APPIMAGE="$TMP/photocraft test.AppImage" # spaces on purpose: Exec must stay quoted : >"$APPIMAGE" @@ -113,4 +115,10 @@ out="$(APPIMAGE="$odd" "$APPDIR/AppRun" x)" || fail "launch with an odd path exi [ "$out" = "stub: x" ] || fail "odd path: $out" [ ! -e "$XDG_DATA_HOME" ] || fail "integrated an AppImage path that needs escaping" +# 12. `--cli` runs the bundled CLI (MCP clients start `--cli mcp --live`), without integrating. +rm -rf "$XDG_DATA_HOME" +out="$("$APPDIR/AppRun" --cli mcp --live)" || fail "--cli exited non-zero" +[ "$out" = "cli stub: mcp --live" ] || fail "--cli output: $out" +[ ! -e "$XDG_DATA_HOME" ] || fail "--cli integrated the desktop entry" + echo "AppRun desktop integration ok" diff --git a/packaging/macos/package.sh b/packaging/macos/package.sh index 194b379293..0f7eec1ef2 100755 --- a/packaging/macos/package.sh +++ b/packaging/macos/package.sh @@ -102,6 +102,9 @@ echo "==> assembling $APP" mkdir -p "$APP/Contents/MacOS" "$APP/Contents/Resources" # Executable and icon carry the display name (CFBundleExecutable / CFBundleIconFile). cp "$WORK/bin/photocraft" "$APP/Contents/MacOS/PhotoCraft" +# The CLI too, beside the app: Preferences › AI Integrations points MCP clients at it +# (`photocraft-cli mcp --live`), and it starts the app when an agent needs it. +cp "$WORK/bin/photocraft-cli" "$APP/Contents/MacOS/photocraft-cli" cp "$ROOT/assets/app-icon/photocraft.icns" "$APP/Contents/Resources/PhotoCraft.icns" # Licences of the embedded craft-fonts fonts (only when built with CRAFT_FONTS_DIR). if [ -n "${CRAFT_FONTS_DIR:-}" ]; then @@ -115,7 +118,8 @@ plutil -lint "$APP/Contents/Info.plist" printf 'APPL????' >"$APP/Contents/PkgInfo" # Sign inside-out: nested code first, then the bundle itself (no --deep on the final signature). -# Today the only nested code is the main executable; frameworks/helpers would be signed here too. +# Today the nested code is the main executable and the CLI; frameworks/helpers would be signed here too. +sign --options runtime --identifier ai.storyteller.photocraft-cli "$APP/Contents/MacOS/photocraft-cli" sign --options runtime --entitlements "$HERE/entitlements.plist" "$APP/Contents/MacOS/PhotoCraft" sign --options runtime --entitlements "$HERE/entitlements.plist" "$APP" codesign --verify --strict --deep --verbose=2 "$APP" diff --git a/scorecard/automation.toml b/scorecard/automation.toml index 7bec4ab443..fe2213674c 100644 --- a/scorecard/automation.toml +++ b/scorecard/automation.toml @@ -80,3 +80,9 @@ target = "Agent acceptance suite grown to 30-50 workflows" status = "partial" issue = 219 note = "automation/tests/agent_tasks.rs runs 10 workflows over MCP" + +[[item]] +id = "AUTO-MCP-LIVE" +target = "Connect an MCP client to the running app without a terminal (no flags, ports or tokens to copy)" +status = "done" +note = "2026-10-14: Preferences › AI Integrations › Let AI agents connect starts the loopback control server at runtime and publishes agent-connection.json; photocraft-cli mcp --live finds the app on every call (launch / headless / error while it is closed); Add to Claude Desktop / Claude Code / Cursor and mcp install --client. automation/tests/mcp_live.rs, apps/photocraft/src/agent_link.rs tests" From d907ac7476b5faeb31683729fe748895dcd34cd7 Mon Sep 17 00:00:00 2001 From: Furoxfufu <111354128+Furoxfufu@users.noreply.github.com> Date: Wed, 14 Oct 2026 13:26:55 +0000 Subject: [PATCH 02/28] AI Integrations: set up each AI app where it really reads its configuration A Windows test showed "Add to Claude Desktop" writing a file Claude never read, and the buttons showing while agents couldn't connect. - Claude Desktop from the Microsoft Store reads its configuration inside its package (%LOCALAPPDATA%\Packages\Claude_\LocalCache\Roaming\ Claude); every install found now gets the entry (Store and classic). - An app is configured only where it has created its settings folder; otherwise the button says to install it and open it once instead of writing a file nothing reads. - Windows: the profile folder (USERPROFILE) comes before HOME (Cursor). - Claude Code: `claude mcp add --scope user photocraft -- mcp --live` (no JSON through cmd.exe), npm's claude.cmd on Windows, claude's own folder first on PATH (npm's Node), and the command to type when it can't run. - `mcp --live` starts the app through Explorer on Windows: the app leaves a Store client's container (whose AppData redirection would split PhotoCraft's settings) and isn't in the CLI's process tree, which Claude Code ends on Windows. - The panel offers the client buttons only with the box ticked; the port hint says AI apps find the port by themselves (20 languages). - docs/mcp.md: where each client is configured, per OS. Co-Authored-By: Claude Opus 5.5 --- apps/photocraft-cli/tests/cli.rs | 4 + crates/automation/src/agent_link.rs | 400 ++++++++++++++++++++++------ crates/automation/src/live.rs | 45 +++- crates/ui-egui/src/i18n/cs.tsv | 2 +- crates/ui-egui/src/i18n/de.tsv | 2 +- crates/ui-egui/src/i18n/el.tsv | 2 +- crates/ui-egui/src/i18n/es.tsv | 2 +- crates/ui-egui/src/i18n/fr.tsv | 2 +- crates/ui-egui/src/i18n/hu.tsv | 2 +- crates/ui-egui/src/i18n/id.tsv | 2 +- crates/ui-egui/src/i18n/it.tsv | 2 +- crates/ui-egui/src/i18n/ja.tsv | 2 +- crates/ui-egui/src/i18n/ko.tsv | 2 +- crates/ui-egui/src/i18n/nl.tsv | 2 +- crates/ui-egui/src/i18n/pl.tsv | 2 +- crates/ui-egui/src/i18n/pt-br.tsv | 2 +- crates/ui-egui/src/i18n/ru.tsv | 2 +- crates/ui-egui/src/i18n/sr.tsv | 2 +- crates/ui-egui/src/i18n/tr.tsv | 2 +- crates/ui-egui/src/i18n/uk.tsv | 2 +- crates/ui-egui/src/i18n/vi.tsv | 2 +- crates/ui-egui/src/i18n/zh-hans.tsv | 2 +- crates/ui-egui/src/i18n/zh-hant.tsv | 2 +- crates/ui-egui/src/prefs_ui.rs | 41 ++- docs/mcp.md | 32 ++- 25 files changed, 458 insertions(+), 104 deletions(-) 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: From 1b1c9d4ba5762abb5c28198c66eb45d5149c13a1 Mon Sep 17 00:00:00 2001 From: Furoxfufu <111354128+Furoxfufu@users.noreply.github.com> Date: Wed, 14 Oct 2026 14:05:59 +0000 Subject: [PATCH 03/28] Roadmap: M11 notes AI Integrations (MCP clients connect without a terminal) Co-Authored-By: Claude Opus 5.5 --- docs/roadmap.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/docs/roadmap.md b/docs/roadmap.md index bca91616c7..343def22ee 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -1,6 +1,6 @@ # Roadmap -> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-11 · **Change:** minor (adaptive Unsharp Mask performance evidence linked; Photomerge status correction retained; alpha gate, focus and estimates unchanged) · **Target:** Adobe Photoshop 2026 +> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-14 · **Change:** minor (M11: the desktop app connects to MCP clients from Preferences › AI Integrations, no terminal; alpha gate, focus and estimates unchanged) · **Target:** Adobe Photoshop 2026 - UI.5: Panels can detach, join other tab groups, split, resize and redock through shared docking transactions. Custom layouts persist with workspaces, respect workspace locking, and retain collapse flags for intact native groups. @@ -57,7 +57,7 @@ real work is ~45%, inside the alpha band (~40–75%), but close to its floor. | M8 PSD v2 | 🟡 | adjustments (incl. Selective Color, Color Lookup), fills, effects, patterns, text, shapes, smart objects, alpha channels; oracle floors 146/170 (io), 236/309 (psd-tools), 133/256 (Photoshop-authored) | | M9 Text, vector, styles | 🟡 | type engine + Warp Text, shapes / pen / paths, all 10 effects on CPU and GPU (parity ≤1/255, 30/31 corpus effect files on the GPU) | | M10 Smart features | 🟡 | classical Select Subject / Object, content-aware fill and scale, healing, auto-align / auto-blend; ML backend not started | -| M11 Automation + formats | 🟡 | MCP (headless + live bridge), batch, Image Processor, prefs over MCP; DoD test passes (10 agent tasks over MCP, `automation/tests/agent_tasks.rs`); since 2026-10-07 the CLI rejects unknown flags and answers ` --help`, batch runs report same-name outputs instead of overwriting them, MCP `command_batch` steps can start background jobs, and headless saves never flatten over the opened file; JP2 / DICOM / DPX / C2PA pending | +| M11 Automation + formats | 🟡 | MCP (headless + live bridge), batch, Image Processor, prefs over MCP; DoD test passes (10 agent tasks over MCP, `automation/tests/agent_tasks.rs`); since 2026-10-07 the CLI rejects unknown flags and answers ` --help`, batch runs report same-name outputs instead of overwriting them, MCP `command_batch` steps can start background jobs, and headless saves never flatten over the opened file; since 2026-10-14 Edit › Preferences › AI Integrations connects Claude Desktop, Claude Code and Cursor to the running app without a terminal (`photocraft-cli mcp --live`, `docs/mcp.md`); JP2 / DICOM / DPX / C2PA pending | | M12 Pro parity | 🟡 | CMYK / Lab / Indexed / Bitmap / Duotone, ICC + soft proofing, channels + Quick Mask, smart-object stack modes, artboards, layer comps; print, HDR, timeline pending; Photomerge is implemented, with real-world quality validation still open | Releases: 0.1.0 (2026-10-02), 0.2.0 (2026-10-05, first signed and notarized), 0.3.0 (10-07), @@ -116,6 +116,7 @@ Each milestone has a **definition of done (DoD)** and must leave `main` green on | Date | Change | Summary | |---|---|---| +| 2026-10-14 | minor | M11: AI Integrations connects MCP clients to the running app without a terminal; milestones, alpha gate and estimates unchanged | | 2026-10-11 | minor | Linked adaptive Unsharp Mask performance and quality evidence; milestones, alpha gate and estimates unchanged | | 2026-10-10 | minor | Photomerge is implemented; real-world quality validation remains open | | 2026-10-10 | minor | Alpha gate table (core-workflow gate from the progress-docs standard): passes, stage stays alpha | From e3e3da6f427ea4f34b4ffeade82768b2d96a01b5 Mon Sep 17 00:00:00 2001 From: Tom Ingling Date: Wed, 4 Nov 2026 22:13:25 -0500 Subject: [PATCH 04/28] Control from the Dock: publish the control connection, automation folders in Preferences MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit When Preferences › Integrations › Control Port starts the control server (no --control) and no token is given, keep the token in the settings folder as agent-control.token (same as --control-token-file) and publish agent-connection.json beside it ({version, pid, port, tokenFile, app}), in the shape #5525 proposes, so a client can find and authenticate to an app started from the Dock, Start menu or a file manager. Add integrations.readRoot / integrations.writeRoot, standing in for --automation-read-root / --automation-write-root; a flag wins over its preference direction by direction. A preference folder that can't be opened is left out (fails closed) with a notice instead of stopping the launch. prefs.set refuses both folders and the whole integrations section, so automation can't widen its own file access. A leftover connection file (crash, or any quit on macOS) is removed or replaced at the next launch. Co-Authored-By: Claude Opus 5.5 --- apps/photocraft/src/main.rs | 237 ++++++++++++++++-- crates/automation/src/agent_link.rs | 208 +++++++++++++++ crates/automation/src/lib.rs | 1 + crates/automation/src/workspace.rs | 6 +- crates/automation/src/workspace/tests.rs | 10 + crates/engine/src/prefs.rs | 8 +- crates/ui-egui/src/i18n/ar.tsv | 2 + crates/ui-egui/src/i18n/cs.tsv | 2 + crates/ui-egui/src/i18n/da.tsv | 2 + crates/ui-egui/src/i18n/de.tsv | 2 + crates/ui-egui/src/i18n/el.tsv | 2 + crates/ui-egui/src/i18n/es.tsv | 2 + crates/ui-egui/src/i18n/fi.tsv | 2 + crates/ui-egui/src/i18n/fr.tsv | 2 + crates/ui-egui/src/i18n/hi.tsv | 2 + crates/ui-egui/src/i18n/hu.tsv | 2 + crates/ui-egui/src/i18n/id.tsv | 2 + crates/ui-egui/src/i18n/it.tsv | 2 + crates/ui-egui/src/i18n/ja.tsv | 2 + crates/ui-egui/src/i18n/ko.tsv | 2 + crates/ui-egui/src/i18n/nb.tsv | 2 + crates/ui-egui/src/i18n/nl.tsv | 2 + crates/ui-egui/src/i18n/pl.tsv | 2 + crates/ui-egui/src/i18n/pt-br.tsv | 2 + crates/ui-egui/src/i18n/ru.tsv | 2 + crates/ui-egui/src/i18n/sr.tsv | 2 + crates/ui-egui/src/i18n/sv.tsv | 2 + crates/ui-egui/src/i18n/tr.tsv | 2 + crates/ui-egui/src/i18n/uk.tsv | 2 + crates/ui-egui/src/i18n/vi.tsv | 2 + crates/ui-egui/src/i18n/zh-hans.tsv | 2 + crates/ui-egui/src/i18n/zh-hant.tsv | 2 + crates/ui-egui/src/prefs/prefs_ui/fields.rs | 8 + crates/ui-egui/src/prefs/prefs_ui/graphics.rs | 4 +- crates/ui-egui/src/prefs/prefs_ui/tests.rs | 13 +- docs/control-protocol.md | 34 ++- docs/scorecard.md | 4 +- 37 files changed, 561 insertions(+), 24 deletions(-) create mode 100644 crates/automation/src/agent_link.rs diff --git a/apps/photocraft/src/main.rs b/apps/photocraft/src/main.rs index 75eb0ea83a..fd8919631e 100644 --- a/apps/photocraft/src/main.rs +++ b/apps/photocraft/src/main.rs @@ -95,8 +95,10 @@ fn custom_titlebar(prefs_file: Option<&std::path::Path>) -> bool { } /// Preferences › Integrations, read before the window opens the way [`custom_titlebar`] is: -/// whether agents may drive this launch at all, and the port to listen on when no `--control` -/// was given (0 = only with `--control`). A missing or unreadable file keeps the defaults. +/// whether agents may drive this launch at all, the port to listen on when no `--control` +/// was given (0 = only with `--control`) and the automation folders used when no +/// `--automation-read-root` / `--automation-write-root` was given. A missing or unreadable file +/// keeps the defaults. /// /// The section is read on its own, and when it doesn't read as a whole each value on its own, /// as the app's lenient load reads them (#6611): a wrong-typed value elsewhere in the file, or @@ -117,9 +119,80 @@ fn integrations(prefs_file: Option<&std::path::Path>) -> photocraft_engine::pref if let Some(port) = section.get("controlPort").and_then(Value::as_u64).and_then(|p| u32::try_from(p).ok()) { out.control_port = port; } + if let Some(root) = section.get("readRoot").and_then(Value::as_str) { + root.clone_into(&mut out.read_root); + } + if let Some(root) = section.get("writeRoot").and_then(Value::as_str) { + root.clone_into(&mut out.write_root); + } out } +/// The automation roots: `--automation-read-root` / `--automation-write-root` (or their +/// variables) win; a direction without one takes Preferences › Integrations' folder. A flag's +/// root that can't be opened stops the launch (exit status 2) as before. A preference's root that +/// can't be opened is left out, so that direction fails closed, and the warning says why: a +/// folder moved since it was chosen must not stop the app from starting. +fn automation_workspace( + flags: &photocraft_automation::args::AutomationArgs, + prefs: &photocraft_engine::prefs::Integrations, +) -> Result<(photocraft_automation::workspace::AuthorizedWorkspace, Option), photocraft_automation::AutomationError> { + use photocraft_automation::{agent_link::folder, workspace::AuthorizedWorkspace}; + let flagged = flags.workspace()?; + let mut warnings = Vec::new(); + let mut from_pref = |flag: &Option, pref: &str, read: bool| -> Option { + if flag.is_some() { + return flag.clone(); + } + let root = folder(pref)?; + let opened = if read { AuthorizedWorkspace::new(Some(&root), None) } else { AuthorizedWorkspace::new(None, Some(&root)) }; + match opened { + Ok(_) => Some(root), + Err(e) => { + let which = if read { "Automation Read Folder" } else { "Automation Write Folder" }; + warnings.push(format!("Preferences › Integrations › {which} is not used: {e}")); + None + } + } + }; + let read = from_pref(&flags.automation_read_root, &prefs.read_root, true); + let write = from_pref(&flags.automation_write_root, &prefs.write_root, false); + let warning = (!warnings.is_empty()).then(|| warnings.join("\n")); + if read == flags.automation_read_root && write == flags.automation_write_root { + return Ok((flagged, warning)); + } + Ok((AuthorizedWorkspace::new(read.as_deref(), write.as_deref())?, warning)) +} + +/// The connection file a launch published ([`photocraft_automation::agent_link`]); dropping it +/// removes the file. (Quitting through AppKit ends the process without returning from the event +/// loop, so on macOS the next launch, or a client's probe, finds a file left behind.) +struct Published(std::path::PathBuf); + +impl Drop for Published { + fn drop(&mut self) { + photocraft_automation::agent_link::remove_connection(&self.0, std::process::id()); + } +} + +/// Publish the control server started from the preferences in the settings folder `dir`, so a +/// local client finds its port and token file. Failing to write it is logged, not fatal: the +/// server still runs, as with `--control`. +fn publish_connection(dir: &std::path::Path, port: u16, token_file: &std::path::Path) -> Option { + use photocraft_automation::agent_link::{Connection, write_connection}; + match write_connection(dir, &Connection::new(port, token_file.to_path_buf())) { + Ok(()) => { + eprintln!("photocraft: control connection published in {}", dir.join(photocraft_automation::agent_link::CONNECTION_FILE).display()); + Some(Published(dir.to_path_buf())) + } + Err(e) => { + eprintln!("photocraft: couldn't publish the control connection: {e}"); + log::warn!("couldn't publish the control connection: {e}"); + None + } + } +} + /// The control port this launch listens on, and the warning to print when a request was refused. /// `--control` (or `PHOTOCRAFT_CONTROL_PORT`) wins over the preference; Allow Agent Control off /// refuses both, and says so rather than ignoring the flag silently. A preferred port outside @@ -282,17 +355,43 @@ fn linux_display_session() -> linux_libs::DisplaySession { session } +/// The control server: its listener, token and workspace. +type Control = (std::net::TcpListener, String, photocraft_automation::workspace::AuthorizedWorkspace); + +/// What [`control_setup`] set up: the control server when it is on, the connection file it +/// published, and a warning for the window (a preference's automation folder that wasn't used). +struct ControlSetup { + control: Option, + published: Option, + warning: Option, +} + /// The control server's port, token and workspace, when it is on (exits 2 on a bad configuration). +/// +/// Started from Preferences › Integrations (no `--control`) and given no token, it keeps its token +/// in the settings folder (`agent-control.token`, as with `--control-token-file`) and publishes +/// the connection there ([`photocraft_automation::agent_link`]), so a client can drive an app +/// started from the Dock. fn control_setup( cli_port: Option, auth: photocraft_automation::args::ControlArgs, automation: &photocraft_automation::args::AutomationArgs, -) -> Option<(std::net::TcpListener, String, photocraft_automation::workspace::AuthorizedWorkspace)> { - let (port, warning) = control_port_for(cli_port, &integrations(services::prefs_file().as_deref())); +) -> ControlSetup { + use photocraft_automation::agent_link; + let settings = services::config_dir(); + let prefs = integrations(services::prefs_file().as_deref()); + let (port, warning) = control_port_for(cli_port, &prefs); if let Some(warning) = &warning { eprint!("{warning}"); } - let port = port?; + // A file a crashed (or, on macOS, quit) launch left behind names a port nothing serves. Before + // binding, so this launch's own listener doesn't keep it. + if let Some(dir) = &settings { + agent_link::remove_stale_connection(dir); + } + let Some(port) = port else { + return ControlSetup { control: None, published: None, warning: None }; + }; let listener = match std::net::TcpListener::bind(("127.0.0.1", port)) { Ok(listener) => listener, Err(error) => { @@ -300,7 +399,13 @@ fn control_setup( std::process::exit(2); } }; + let from_prefs = cli_port.is_none(); let (supplied, token_file) = (auth.control_token, auth.control_token_file); + let token_file = match (token_file, &settings) { + (Some(file), _) => Some(file), + (None, Some(dir)) if from_prefs && supplied.is_none() => Some(dir.join(agent_link::TOKEN_FILE)), + (None, _) => None, + }; let token = match photocraft_automation::security::server_token(supplied.as_deref(), token_file.as_deref()) { Ok(token) => token, Err(e) => { @@ -308,21 +413,31 @@ fn control_setup( std::process::exit(2); } }; - if let Some(path) = token_file { + if let Some(path) = &token_file { eprintln!("photocraft: control token file: {}", path.display()); } else if supplied.is_none() { eprintln!("photocraft: control token: {token}"); } else { eprintln!("photocraft: using supplied control token"); } - let workspace = match automation.workspace() { + let (workspace, warning) = match automation_workspace(automation, &prefs) { Ok(workspace) => workspace, Err(error) => { eprintln!("photocraft: cannot configure automation workspace: {error}"); std::process::exit(2); } }; - Some((listener, token, workspace)) + if let Some(warning) = &warning { + eprintln!("photocraft: {warning}"); + log::warn!("{warning}"); + } + // Only a server the preferences started is published: a `--control` launch was told its port + // and token by whoever started it. A token given as a value has no file to point at. + let published = match (&settings, &token_file, listener.local_addr()) { + (Some(dir), Some(file), Ok(addr)) if from_prefs => publish_connection(dir, addr.port(), file), + _ => None, + }; + ControlSetup { control: Some((listener, token, workspace)), published, warning } } /// Record this start's backend in the GPU startup marker, if the marker is locked. @@ -398,7 +513,7 @@ fn main() -> eframe::Result { let _ = (new_instance, &launch_options); // Bind and authenticate the authorized control listener before display/GPU initialization. - let control = control_setup(control_port, auth, &automation); + let ControlSetup { control, published, warning: control_warning } = control_setup(control_port, auth, &automation); #[cfg(target_os = "linux")] let native_session = linux_libs::session_from_env(|name| std::env::var(name).ok()); @@ -684,9 +799,15 @@ fn main() -> eframe::Result { if let Some(w) = &app_dirs::current().warning { photocraft_ui_egui::notices::post(&mut app, "Portable mode is off", vec![w.clone()], false, None); } + // A preference's automation folder that couldn't be opened: a Dock launch has no console. + if let Some(w) = control_warning { + photocraft_ui_egui::notices::post(&mut app, "Automation folder not used", w.lines().map(str::to_owned).collect(), false, None); + } Ok(Box::new(app)) }), ); + // The window is gone: no client should find this launch any more. + drop(published); // The window is gone: refuse further files and free the lock, so a launch that is waiting (or // the CPU-compatibility relaunch below) becomes the primary instead of handing its files to a // process that is exiting. @@ -966,9 +1087,9 @@ mod tests { #[test] fn integrations_preferences_decide_the_control_port() { use photocraft_engine::prefs::Integrations; - let off = Integrations { allow_agent_control: false, control_port: 0 }; - let on = Integrations { allow_agent_control: true, control_port: 0 }; - let preferred = Integrations { allow_agent_control: true, control_port: 7878 }; + let off = Integrations { allow_agent_control: false, control_port: 0, ..Default::default() }; + let on = Integrations { allow_agent_control: true, control_port: 0, ..Default::default() }; + let preferred = Integrations { allow_agent_control: true, control_port: 7878, ..Default::default() }; // Nothing asked for, nothing listening. assert_eq!(super::control_port_for(None, &on), (None, None)); @@ -983,11 +1104,11 @@ mod tests { let (port, warning) = super::control_port_for(Some(9000), &off); assert_eq!(port, None); assert!(warning.is_some_and(|w| w.contains("Allow Agent Control") && w.contains("9000")), "the refusal names the port"); - let off_with_port = Integrations { allow_agent_control: false, control_port: 7878 }; + let off_with_port = Integrations { allow_agent_control: false, control_port: 7878, ..Default::default() }; assert_eq!(super::control_port_for(None, &off_with_port), (None, None), "off beats a preferred port"); // A port a hand-edited file could hold, outside 1..=65535, is refused and named. - let huge = Integrations { allow_agent_control: true, control_port: 70_000 }; + let huge = Integrations { allow_agent_control: true, control_port: 70_000, ..Default::default() }; let (port, warning) = super::control_port_for(None, &huge); assert_eq!(port, None); assert!(warning.is_some_and(|w| w.contains("70000")), "the refusal names the value"); @@ -1038,13 +1159,99 @@ mod tests { assert_eq!(r.control_port, 0, "the bad port alone takes its default"); // A bad Allow Agent Control alone takes its default. let r = read(r#"{"integrations":{"allowAgentControl":"no","controlPort":7878}}"#); - assert_eq!(r, photocraft_engine::prefs::Integrations { allow_agent_control: true, control_port: 7878 }); + assert_eq!(r, photocraft_engine::prefs::Integrations { allow_agent_control: true, control_port: 7878, ..Default::default() }); read(r#"{"integrations":{"allowAgentControl":false,"controlPort":-1}}"#); read(r#"{"integrations":{"allowAgentControl":false,"controlPort":4294967296}}"#); read(r#"{"integrations":"off"}"#); // serde reads a struct from a list too; the app does. assert!(!read(r#"{"integrations":[false]}"#).allow_agent_control, "a list"); assert_eq!(read(r#"{"integrations":[false,7878]}"#).control_port, 7878); + // The automation folders: a bad one takes its default alone, too. + let r = read(r#"{"integrations":{"allowAgentControl":false,"readRoot":5,"writeRoot":"/w"}}"#); + assert!(!r.allow_agent_control, "a bad folder"); + assert_eq!((r.read_root.as_str(), r.write_root.as_str()), ("", "/w")); + let _ = std::fs::remove_dir_all(&dir); + } + + fn temp_dir(name: &str) -> std::path::PathBuf { + let dir = std::env::temp_dir().join(format!("pc-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + dir + } + + fn flags(read: Option<&std::path::Path>, write: Option<&std::path::Path>) -> photocraft_automation::args::AutomationArgs { + photocraft_automation::args::AutomationArgs { automation_read_root: read.map(Into::into), automation_write_root: write.map(Into::into) } + } + + fn roots(read: &std::path::Path, write: &std::path::Path) -> photocraft_engine::prefs::Integrations { + photocraft_engine::prefs::Integrations { + read_root: read.to_string_lossy().into_owned(), + write_root: write.to_string_lossy().into_owned(), + ..Default::default() + } + } + + /// Preferences › Integrations' folders are the automation roots when no flag names one, and + /// a flag wins over its preference, direction by direction. + #[test] + fn automation_folders_come_from_the_preferences_unless_a_flag_names_one() { + let dir = temp_dir("automation-roots"); + let (pref, flag) = (dir.join("pref"), dir.join("flag")); + std::fs::create_dir_all(&pref).unwrap(); + std::fs::create_dir_all(&flag).unwrap(); + + // No flags: both directions from the preferences. + let (ws, warning) = super::automation_workspace(&flags(None, None), &roots(&pref, &pref)).unwrap(); + assert_eq!(warning, None); + ws.write("a.txt", b"pref").unwrap(); + assert_eq!(std::fs::read(pref.join("a.txt")).unwrap(), b"pref"); + assert_eq!(ws.read("a.txt").unwrap(), b"pref"); + + // A write flag wins over the write folder; reads still come from the preference. + let (ws, _) = super::automation_workspace(&flags(None, Some(&flag)), &roots(&pref, &pref)).unwrap(); + ws.write("b.txt", b"flag").unwrap(); + assert!(flag.join("b.txt").is_file() && !pref.join("b.txt").exists(), "the flag's folder takes the write"); + assert_eq!(ws.read("a.txt").unwrap(), b"pref"); + + // Empty preferences grant nothing, as no flags do. + let (ws, warning) = super::automation_workspace(&flags(None, None), &photocraft_engine::prefs::Integrations::default()).unwrap(); + assert_eq!(warning, None); + assert!(ws.read("a.txt").is_err() && ws.write("c.txt", b"x").is_err()); + let _ = std::fs::remove_dir_all(&dir); + } + + /// A preference's folder that can't be opened is left out (that direction fails closed) and + /// named in the warning; the app still starts. A flag's still stops the launch. + #[test] + fn a_missing_preference_folder_is_left_out_and_a_missing_flag_root_is_an_error() { + let dir = temp_dir("automation-roots-missing"); + let missing = dir.join("gone"); + let (ws, warning) = super::automation_workspace(&flags(None, None), &roots(&dir, &missing)).unwrap(); + let warning = warning.expect("the missing write folder is named"); + assert!(warning.contains("Automation Write Folder") && !warning.contains("Read Folder"), "{warning}"); + std::fs::write(dir.join("in.txt"), b"x").unwrap(); + assert_eq!(ws.read("in.txt").unwrap(), b"x", "the read folder still applies"); + assert!(ws.write("out.txt", b"x").is_err(), "no write access without its folder"); + + assert!(super::automation_workspace(&flags(Some(&missing), None), &roots(&dir, &dir)).is_err(), "a flag's root must open"); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn a_published_connection_goes_when_dropped() { + use photocraft_automation::agent_link; + let dir = temp_dir("published"); + let token = dir.join(agent_link::TOKEN_FILE); + let published = super::publish_connection(&dir, 7878, &token).expect("published"); + let c = agent_link::read_connection(&dir).unwrap().expect("a connection"); + assert_eq!((c.port, c.pid, c.token_file.as_path()), (7878, std::process::id(), token.as_path())); + drop(published); + assert_eq!(agent_link::read_connection(&dir).unwrap(), None); + // Nowhere to write (the settings folder's place is a file): no connection, no panic. + let blocker = dir.join("blocker"); + std::fs::write(&blocker, b"").unwrap(); + assert!(super::publish_connection(&blocker.join("settings"), 7878, &token).is_none()); let _ = std::fs::remove_dir_all(&dir); } diff --git a/crates/automation/src/agent_link.rs b/crates/automation/src/agent_link.rs new file mode 100644 index 0000000000..bc6c51627b --- /dev/null +++ b/crates/automation/src/agent_link.rs @@ -0,0 +1,208 @@ +//! Finding the desktop app's control server without being told (Preferences › Integrations). +//! +//! When the app starts its control server from the preferences (Allow Agent Control on and a +//! Control Port, no `--control`), it publishes where in its settings folder ([`CONNECTION_FILE`]): +//! the port, its process id and the bearer-token file ([`TOKEN_FILE`] unless a token file was +//! given at launch; created `0600` on Unix, see [`crate::security::server_token`]). A local +//! client reads that file, then the token from the file it names, so nothing has to pass a port +//! or a token to an app started from the Dock, the Start menu or a file manager. +//! +//! The file holds no secret. A crashed (or, on macOS, quit) app can leave it behind; nothing then +//! listens on its port ([`probe`]), and the app's next launch replaces it or removes it +//! ([`remove_stale_connection`]). + +use std::net::{SocketAddr, TcpStream}; +use std::path::{Path, PathBuf}; +use std::time::Duration; + +use serde::{Deserialize, Serialize}; + +use crate::AutomationError; + +/// The connection file in the settings folder, present while the app accepts agents. +pub const CONNECTION_FILE: &str = "agent-connection.json"; +/// The bearer-token file the app keeps in its settings folder for agent connections. +pub const TOKEN_FILE: &str = "agent-control.token"; +/// How long [`probe`] waits for the app to accept a connection. +pub const PROBE_TIMEOUT: Duration = Duration::from_millis(500); +/// Version of the [`Connection`] file format. +const CONNECTION_VERSION: u32 = 1; +/// Largest connection file read; anything bigger is not ours. +const MAX_CONNECTION_BYTES: u64 = 1 << 20; + +/// What the app publishes in [`CONNECTION_FILE`]. Holds no secret: the token stays in its own +/// user-only file. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Connection { + pub version: u32, + /// The app's process id: only that process removes the file. + pub pid: u32, + /// Loopback port of the control server. + pub port: u16, + pub token_file: PathBuf, + /// The app's version, for diagnostics. + pub app: String, +} + +impl Connection { + pub fn new(port: u16, token_file: PathBuf) -> Self { + Connection { version: CONNECTION_VERSION, pid: std::process::id(), port, token_file, app: photocraft_engine::build_info::long_version() } + } + + /// `127.0.0.1:`. + pub fn addr(&self) -> String { + format!("127.0.0.1:{}", self.port) + } +} + +fn io_error(path: &Path, e: impl std::fmt::Display) -> AutomationError { + AutomationError::Io(format!("{}: {e}", path.display())) +} + +/// Publish `c` in `dir` (written atomically, so a reader never sees half a file). +pub fn write_connection(dir: &Path, c: &Connection) -> Result<(), AutomationError> { + std::fs::create_dir_all(dir).map_err(|e| io_error(dir, e))?; + let path = dir.join(CONNECTION_FILE); + let text = serde_json::to_string_pretty(c).map_err(|e| AutomationError::Other(e.to_string()))?; + photocraft_format::atomic_write(&path, text.as_bytes()).map_err(|e| io_error(&path, e)) +} + +/// The connection published in `dir`, if any. A file from another version or one that doesn't +/// parse counts as none: the app rewrites it when it next starts listening. +pub fn read_connection(dir: &Path) -> Result, AutomationError> { + let path = dir.join(CONNECTION_FILE); + let meta = match std::fs::metadata(&path) { + Ok(m) => m, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None), + Err(e) => return Err(io_error(&path, e)), + }; + if meta.len() > MAX_CONNECTION_BYTES { + return Err(io_error(&path, format!("larger than {MAX_CONNECTION_BYTES} bytes"))); + } + let text = match std::fs::read_to_string(&path) { + Ok(s) => s, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None), + Err(e) => return Err(io_error(&path, e)), + }; + Ok(serde_json::from_str::(&text).ok().filter(|c| c.version == CONNECTION_VERSION && c.port != 0)) +} + +/// Remove the connection file in `dir` if process `pid` wrote it (another instance may have +/// published its own since). Errors are ignored: a stale file only fails [`probe`]. +pub fn remove_connection(dir: &Path, pid: u32) { + if let Ok(Some(c)) = read_connection(dir) + && c.pid == pid + { + let _ = std::fs::remove_file(dir.join(CONNECTION_FILE)); + } +} + +/// Remove the connection file in `dir` when nothing listens on its port any more (an app that +/// crashed or quit without removing it), or when it doesn't read as a connection. A live +/// instance's file is kept. Errors are ignored. +pub fn remove_stale_connection(dir: &Path) { + let path = dir.join(CONNECTION_FILE); + let stale = match read_connection(dir) { + Ok(Some(c)) => !probe(c.port, PROBE_TIMEOUT), + Ok(None) => path.is_file(), + Err(_) => false, + }; + if stale { + let _ = std::fs::remove_file(path); + } +} + +/// Does something accept connections on loopback `port`? (A crashed app leaves its connection +/// file behind; nothing listens on its port any more.) +pub fn probe(port: u16, timeout: Duration) -> bool { + port != 0 && TcpStream::connect_timeout(&SocketAddr::from(([127, 0, 0, 1], port)), timeout).is_ok() +} + +/// A folder preference as a path (`None` when empty or blank). +pub fn folder(pref: &str) -> Option { + let pref = pref.trim(); + (!pref.is_empty()).then(|| PathBuf::from(pref)) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::atomic::{AtomicUsize, Ordering}; + + fn temp() -> PathBuf { + static N: AtomicUsize = AtomicUsize::new(0); + let d = std::env::temp_dir().join(format!("photocraft-agent-link-{}-{}", std::process::id(), N.fetch_add(1, Ordering::Relaxed))); + let _ = std::fs::remove_dir_all(&d); + std::fs::create_dir_all(&d).unwrap(); + d + } + + #[test] + fn a_published_connection_reads_back_in_the_documented_shape() { + let dir = temp(); + let c = Connection::new(7878, dir.join(TOKEN_FILE)); + write_connection(&dir, &c).unwrap(); + assert_eq!(read_connection(&dir).unwrap(), Some(c.clone())); + let v: serde_json::Value = serde_json::from_str(&std::fs::read_to_string(dir.join(CONNECTION_FILE)).unwrap()).unwrap(); + let mut keys: Vec<_> = v.as_object().unwrap().keys().cloned().collect(); + keys.sort(); + assert_eq!(keys, ["app", "pid", "port", "tokenFile", "version"]); + assert_eq!((v["version"].as_u64(), v["port"].as_u64()), (Some(1), Some(7878))); + assert_eq!(c.addr(), "127.0.0.1:7878"); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn other_versions_garbage_and_port_zero_read_as_none() { + let dir = temp(); + assert_eq!(read_connection(&dir).unwrap(), None, "no file"); + for text in + ["{not json", r#"{"version":2,"pid":1,"port":7878,"tokenFile":"t","app":"x"}"#, r#"{"version":1,"pid":1,"port":0,"tokenFile":"t","app":"x"}"#] + { + std::fs::write(dir.join(CONNECTION_FILE), text).unwrap(); + assert_eq!(read_connection(&dir).unwrap(), None, "{text}"); + } + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn only_the_publishing_process_removes_its_file() { + let dir = temp(); + let c = Connection { pid: 1, ..Connection::new(7878, dir.join(TOKEN_FILE)) }; + write_connection(&dir, &c).unwrap(); + remove_connection(&dir, 2); + assert!(dir.join(CONNECTION_FILE).is_file(), "another process's file stays"); + remove_connection(&dir, 1); + assert!(!dir.join(CONNECTION_FILE).exists()); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn a_stale_file_is_removed_and_a_live_one_kept() { + let dir = temp(); + let live = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let live_port = live.local_addr().unwrap().port(); + write_connection(&dir, &Connection { pid: 1, ..Connection::new(live_port, dir.join(TOKEN_FILE)) }).unwrap(); + remove_stale_connection(&dir); + assert!(dir.join(CONNECTION_FILE).is_file(), "something listens on {live_port}"); + drop(live); + // A port nothing listens on: bind one, then close it. + let closed = std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port(); + write_connection(&dir, &Connection { pid: 1, ..Connection::new(closed, dir.join(TOKEN_FILE)) }).unwrap(); + remove_stale_connection(&dir); + assert!(!dir.join(CONNECTION_FILE).exists(), "nothing listens on {closed}"); + std::fs::write(dir.join(CONNECTION_FILE), "{not json").unwrap(); + remove_stale_connection(&dir); + assert!(!dir.join(CONNECTION_FILE).exists(), "an unreadable file is not a connection"); + remove_stale_connection(&dir); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn folder_preferences_are_trimmed_and_empty_means_none() { + assert_eq!(folder(""), None); + assert_eq!(folder(" "), None); + assert_eq!(folder(" /work/project "), Some(PathBuf::from("/work/project"))); + } +} diff --git a/crates/automation/src/lib.rs b/crates/automation/src/lib.rs index b4691723b9..53ce943ddd 100644 --- a/crates/automation/src/lib.rs +++ b/crates/automation/src/lib.rs @@ -16,6 +16,7 @@ #![forbid(unsafe_code)] #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +pub mod agent_link; pub mod args; pub mod bridge; pub mod budgets; diff --git a/crates/automation/src/workspace.rs b/crates/automation/src/workspace.rs index 3e068258fe..02510252a9 100644 --- a/crates/automation/src/workspace.rs +++ b/crates/automation/src/workspace.rs @@ -484,8 +484,12 @@ fn preference_uses_ambient_filesystem(path: &str) -> bool { let mut segments = path.split('.').filter(|segment| !segment.is_empty()); let Some(section) = segments.next() else { return true }; // File Handling's LUT folder (#6558) is listed from disk; the rest of that section is not. + // Integrations' automation roots are what this policy grants at the next launch: an agent must + // not widen its own file access. + let key = segments.next(); matches!(section, "colorSettings" | "scriptEvents" | "historyLog" | "plugIns" | "scratchDisks") - || (section == "fileHandling" && segments.next().is_none_or(|key| key == "lutFolder")) + || (section == "fileHandling" && key.is_none_or(|key| key == "lutFolder")) + || (section == "integrations" && key.is_none_or(|key| matches!(key, "readRoot" | "writeRoot"))) } fn command_uses_ambient_path(id: &str, params: &Value) -> bool { diff --git a/crates/automation/src/workspace/tests.rs b/crates/automation/src/workspace/tests.rs index 5ea4a5b3fe..7cd3a74691 100644 --- a/crates/automation/src/workspace/tests.rs +++ b/crates/automation/src/workspace/tests.rs @@ -533,6 +533,10 @@ fn automation_rejects_ambient_path_commands_and_preferences() { "fileHandling.lutFolder", "fileHandling", "scratchDisks.disks", + "integrations", + "integrations.readRoot", + "integrations.writeRoot", + ".integrations.writeRoot", ".", "..historyLog.filePath", ] { @@ -543,6 +547,12 @@ fn automation_rejects_ambient_path_commands_and_preferences() { ); assert!(authorize_engine_command("prefs.set", &serde_json::json!({"path": "interface.language", "value": "fr"})).is_ok()); assert!(authorize_engine_command("prefs.set", &serde_json::json!({"path": "fileHandling.autosave", "value": false})).is_ok()); + assert!( + authorize_engine_command("prefs.set", &serde_json::json!({"values": {"integrations.controlPort": 7878, "integrations.writeRoot": "/outside"}})) + .is_err(), + "a batch may not grant automation roots either" + ); + assert!(authorize_engine_command("prefs.set", &serde_json::json!({"path": "integrations.controlPort", "value": 7878})).is_ok()); } #[test] diff --git a/crates/engine/src/prefs.rs b/crates/engine/src/prefs.rs index e8d8126e2f..d3d64efc66 100644 --- a/crates/engine/src/prefs.rs +++ b/crates/engine/src/prefs.rs @@ -1077,11 +1077,17 @@ pub struct Integrations { pub allow_agent_control: bool, /// Default control port (0 = only when `--control` is given). pub control_port: u32, + /// The folder automation may read from when no `--automation-read-root` is given (empty = + /// none). Read at launch, like the flag. + pub read_root: String, + /// The folder automation may write to when no `--automation-write-root` is given (empty = + /// none). Read at launch, like the flag. + pub write_root: String, } impl Default for Integrations { fn default() -> Self { - Self { allow_agent_control: true, control_port: 0 } + Self { allow_agent_control: true, control_port: 0, read_root: String::new(), write_root: String::new() } } } diff --git a/crates/ui-egui/src/i18n/ar.tsv b/crates/ui-egui/src/i18n/ar.tsv index 0c67a91ec6..88a1e5cd4d 100644 --- a/crates/ui-egui/src/i18n/ar.tsv +++ b/crates/ui-egui/src/i18n/ar.tsv @@ -3549,3 +3549,5 @@ curves Smooth تنعيم The path was kept as the Work Path تم الاحتفاظ بالمسار كمسار عمل The path was discarded تم تجاهل المسار Edit Brush… تحرير الفرشاة… + Automation read folder مجلد القراءة للأتمتة + Automation write folder مجلد الكتابة للأتمتة diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 8cd95ed30d..c3254764fc 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -4266,3 +4266,5 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Stop Color Barva zarážky Shapes can't use patterns yet Tvary zatím nemohou používat vzorky Edit Brush… Upravit štětec… + Automation read folder Složka pro čtení automatizace + Automation write folder Složka pro zápis automatizace diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 46e71ed2cf..6308e77f56 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -4773,3 +4773,5 @@ cameraRaw White Balance: As Shot Hvidbalance: Som fotograferet The path was discarded Stien blev kasseret The path was kept as the Work Path Stien blev bevaret som arbejdssti Edit Brush… Rediger pensel… + Automation read folder Læsemappe til automatisering + Automation write folder Skrivemappe til automatisering diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 45fb326bea..c89cdf34f1 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -3551,3 +3551,5 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Solid Color Volltonfarbe Tint Color Tönungsfarbe Edit Brush… Pinsel bearbeiten… + Automation read folder Leseordner für Automatisierung + Automation write folder Schreibordner für Automatisierung diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 8f20dd6705..4ebe7f5900 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -4220,3 +4220,5 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Stop Color Χρώμα στάσης Shapes can't use patterns yet Τα σχήματα δεν μπορούν ακόμη να χρησιμοποιούν μοτίβα Edit Brush… Επεξεργασία πινέλου… + Automation read folder Φάκελος ανάγνωσης αυτοματισμού + Automation write folder Φάκελος εγγραφής αυτοματισμού diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 6b365ce2be..fe7744e657 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -4432,3 +4432,5 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Stop Color Color de la parada Shapes can't use patterns yet Las formas aún no pueden usar motivos Edit Brush… Editar pincel… + Automation read folder Carpeta de lectura de automatización + Automation write folder Carpeta de escritura de automatización diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index b08a224b27..79facb6aca 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -4774,3 +4774,5 @@ cameraRaw White Balance: As Shot Valkotasapaino: kuvauksen mukainen The path was discarded Polku hylättiin The path was kept as the Work Path Polku säilytettiin työpolkuna Edit Brush… Muokkaa sivellintä… + Automation read folder Automaation lukukansio + Automation write folder Automaation kirjoituskansio diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 89bdec45d4..85bcac7c4d 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -4556,3 +4556,5 @@ shape Appearance Apparence Stop Color Couleur du point Shapes can't use patterns yet Les formes ne peuvent pas encore utiliser de motifs Edit Brush… Modifier le pinceau… + Automation read folder Dossier de lecture de l'automatisation + Automation write folder Dossier d'écriture de l'automatisation diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 0acf7e4bf1..1cf091a5f2 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -597,3 +597,5 @@ cameraRaw Yellow पीला @plural {n} action file loaded|{n} action files loaded {n} एक्शन फ़ाइल लोड हुई|{n} एक्शन फ़ाइलें लोड हुईं {set} from {file} replaced the one from {earlier} {file} के सेट {set} ने {earlier} वाले सेट की जगह ले ली @plural {n} file could not be loaded: {errors}|{n} files could not be loaded: {errors} {n} फ़ाइल लोड नहीं हो सकी: {errors}|{n} फ़ाइलें लोड नहीं हो सकीं: {errors} + Automation read folder स्वचालन पठन फ़ोल्डर + Automation write folder स्वचालन लेखन फ़ोल्डर diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index c5a61baed8..2cb3938809 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -4440,3 +4440,5 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Stop Color Színpont színe Shapes can't use patterns yet Az alakzatok még nem használhatnak mintákat Edit Brush… Ecset szerkesztése… + Automation read folder Automatizálás olvasási mappája + Automation write folder Automatizálás írási mappája diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index e5058af2c9..a39a7d496c 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -3543,3 +3543,5 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Solid Color Warna Solid Tint Color Warna Tint Edit Brush… Edit Kuas… + Automation read folder Folder baca otomatisasi + Automation write folder Folder tulis otomatisasi diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 367c7267f5..fbc6bdc4b0 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -4632,3 +4632,5 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Stop Color Colore del punto Shapes can't use patterns yet Le forme non possono ancora usare pattern Edit Brush… Modifica pennello… + Automation read folder Cartella di lettura dell'automazione + Automation write folder Cartella di scrittura dell'automazione diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 2eee5145a2..b07e5e0857 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -4197,3 +4197,5 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Stop Color 分岐点のカラー Shapes can't use patterns yet シェイプではまだパターンを使用できません Edit Brush… ブラシを編集… + Automation read folder 自動化の読み取りフォルダー + Automation write folder 自動化の書き込みフォルダー diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 43f7dea83e..1de5745569 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -3740,3 +3740,5 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Stop Color 정지점 색상 Shapes can't use patterns yet 모양에는 아직 패턴을 사용할 수 없습니다 Edit Brush… 브러시 편집… + Automation read folder 자동화 읽기 폴더 + Automation write folder 자동화 쓰기 폴더 diff --git a/crates/ui-egui/src/i18n/nb.tsv b/crates/ui-egui/src/i18n/nb.tsv index d7232004b6..d4a5110440 100644 --- a/crates/ui-egui/src/i18n/nb.tsv +++ b/crates/ui-egui/src/i18n/nb.tsv @@ -4773,3 +4773,5 @@ cameraRaw White Balance: As Shot Hvitbalanse: som fotografert The path was discarded Banen ble forkastet The path was kept as the Work Path Banen ble beholdt som arbeidsbane Edit Brush… Rediger pensel… + Automation read folder Lesemappe for automatisering + Automation write folder Skrivemappe for automatisering diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 7ad2900a28..f07013251f 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -4277,3 +4277,5 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Stop Color Kleur van het punt Shapes can't use patterns yet Vormen kunnen nog geen patronen gebruiken Edit Brush… Penseel bewerken… + Automation read folder Leesmap voor automatisering + Automation write folder Schrijfmap voor automatisering diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index fe13d8f177..d559dce584 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -4139,3 +4139,5 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Stop Color Kolor punktu Shapes can't use patterns yet Kształty nie mogą jeszcze używać wzorków Edit Brush… Edytuj pędzel… + Automation read folder Folder odczytu automatyzacji + Automation write folder Folder zapisu automatyzacji diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index f12a596d1a..657f49bd92 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -4447,3 +4447,5 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Stop Color Cor da parada Shapes can't use patterns yet Formas ainda não podem usar padrões Edit Brush… Editar pincel… + Automation read folder Pasta de leitura da automação + Automation write folder Pasta de gravação da automação diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 60f3929e5f..6d1bf945b2 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -4717,3 +4717,5 @@ shape Appearance Оформление Stop Color Цвет контрольной точки Shapes can't use patterns yet Фигуры пока не могут использовать узоры Edit Brush… Изменить кисть… + Automation read folder Папка чтения для автоматизации + Automation write folder Папка записи для автоматизации diff --git a/crates/ui-egui/src/i18n/sr.tsv b/crates/ui-egui/src/i18n/sr.tsv index 2ebc6c2e70..62f21a3287 100644 --- a/crates/ui-egui/src/i18n/sr.tsv +++ b/crates/ui-egui/src/i18n/sr.tsv @@ -4599,3 +4599,5 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Stop Color Boja tačke Shapes can't use patterns yet Oblici još ne mogu da koriste šare Edit Brush… Uredi četkicu… + Automation read folder Fascikla za čitanje automatizacije + Automation write folder Fascikla za upis automatizacije diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index b9c3721765..9e5cde67a7 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -4771,3 +4771,5 @@ cameraRaw White Balance: As Shot Vitbalans: som tagen The path was discarded Banan kasserades The path was kept as the Work Path Banan behölls som arbetsbana Edit Brush… Redigera pensel… + Automation read folder Läsmapp för automatisering + Automation write folder Skrivmapp för automatisering diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 007d756f89..cfb52102b6 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -4254,3 +4254,5 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Stop Color Durak Rengi Shapes can't use patterns yet Şekiller henüz desen kullanamaz Edit Brush… Fırçayı Düzenle… + Automation read folder Otomasyon okuma klasörü + Automation write folder Otomasyon yazma klasörü diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 68128b8584..a7de3d9316 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -4231,3 +4231,5 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Stop Color Колір контрольної точки Shapes can't use patterns yet Фігури поки не можуть використовувати візерунки Edit Brush… Редагувати пензель… + Automation read folder Тека читання для автоматизації + Automation write folder Тека запису для автоматизації diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index d868ab099a..3582f74459 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -4027,3 +4027,5 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Stop Color Màu điểm dừng Shapes can't use patterns yet Hình chưa thể dùng mẫu tô Edit Brush… Chỉnh sửa cọ… + Automation read folder Thư mục đọc cho tự động hóa + Automation write folder Thư mục ghi cho tự động hóa diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index d9b554acfa..6b0a2158f4 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -3205,3 +3205,5 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Solid Color 纯色 Tint Color 色调颜色 Edit Brush… 编辑画笔… + Automation read folder 自动化读取文件夹 + Automation write folder 自动化写入文件夹 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 9379418b9e..b60d64c42b 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -3161,3 +3161,5 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Solid Color 純色 Tint Color 色調顏色 Edit Brush… 編輯筆刷… + Automation read folder 自動化讀取資料夾 + Automation write folder 自動化寫入資料夾 diff --git a/crates/ui-egui/src/prefs/prefs_ui/fields.rs b/crates/ui-egui/src/prefs/prefs_ui/fields.rs index 2accc50371..43cda59323 100644 --- a/crates/ui-egui/src/prefs/prefs_ui/fields.rs +++ b/crates/ui-egui/src/prefs/prefs_ui/fields.rs @@ -34,6 +34,9 @@ pub(super) fn humanize(key: &str) -> String { "darkTheme" => return "Dark Theme".into(), "lightTheme" => return "Light Theme".into(), "automaticallyCheckUpdates" => return "Automatically Check for Updates".into(), + // Integrations: the automation roots (`--automation-read-root` / `--automation-write-root`). + "readRoot" => return "Automation read folder".into(), + "writeRoot" => return "Automation write folder".into(), _ => {} } // These controls appear only for WebP, so reuse the existing translated labels. @@ -479,6 +482,11 @@ fn field_rows(ui: &mut egui::Ui, section: &str, obj: &mut Map, ke let mut s = s.clone(); ui.add(egui::TextEdit::singleline(&mut s).desired_width(260.0)).accessible_name(tl!(&label)); obj.insert(k, json!(s)); + if read_at_launch(&path) { + ui.end_row(); + ui.label(""); + ui.label(RichText::new(tl!("Applies at next launch.")).color(t.text_dim)); + } } Value::Number(n) => { let value_label = ui.label(RichText::new(tl!(&label)).color(t.text_dim)); diff --git a/crates/ui-egui/src/prefs/prefs_ui/graphics.rs b/crates/ui-egui/src/prefs/prefs_ui/graphics.rs index 166f5ed299..8de3a995c2 100644 --- a/crates/ui-egui/src/prefs/prefs_ui/graphics.rs +++ b/crates/ui-egui/src/prefs/prefs_ui/graphics.rs @@ -135,7 +135,9 @@ pub(super) fn read_at_launch(path: &str) -> bool { // Only Windows and Linux draw their own title bar. "interface.systemTitleBar" => cfg!(all(not(target_arch = "wasm32"), not(target_os = "macos"))), // The desktop app decides on the control server before its window opens. - "integrations.allowAgentControl" | "integrations.controlPort" => cfg!(not(target_arch = "wasm32")), + "integrations.allowAgentControl" | "integrations.controlPort" | "integrations.readRoot" | "integrations.writeRoot" => { + cfg!(not(target_arch = "wasm32")) + } _ => false, } } diff --git a/crates/ui-egui/src/prefs/prefs_ui/tests.rs b/crates/ui-egui/src/prefs/prefs_ui/tests.rs index 21994b7352..2e5db67eb2 100644 --- a/crates/ui-egui/src/prefs/prefs_ui/tests.rs +++ b/crates/ui-egui/src/prefs/prefs_ui/tests.rs @@ -1450,6 +1450,8 @@ fn unimplemented_preferences_are_hidden_from_the_dialog() { assert!(has_visible_fields(&values, "integrations")); assert!(!prefs::is_hidden("integrations.allowAgentControl")); assert!(!prefs::is_hidden("integrations.controlPort")); + assert!(!prefs::is_hidden("integrations.readRoot")); + assert!(!prefs::is_hidden("integrations.writeRoot")); // "Fill new type layers with placeholder text" and "Use Escape to Commit" are live; other Type rows stay hidden. assert!(has_visible_fields(&values, "type")); assert!(!prefs::is_hidden("type.fillNewTypeLayersWithPlaceholder")); @@ -1694,18 +1696,23 @@ fn rendering_mode_explains_next_launch() { assert!(h.query_by_label("Applies at next launch.").is_none()); } -/// #4097: Allow Agent Control and Control Port are read when the app starts, and say so. +/// #4097: Allow Agent Control, Control Port and the automation folders are read when the app +/// starts, and say so. #[test] fn integrations_explain_next_launch() { use egui_kittest::{Harness, kittest::Queryable}; - let obj = json!({"allowAgentControl": true, "controlPort": 0}).as_object().unwrap().clone(); + let obj = json!({"allowAgentControl": true, "controlPort": 0, "readRoot": "", "writeRoot": ""}).as_object().unwrap().clone(); let mut h = Harness::new_ui_state( |ui, obj: &mut Map| section_fields(ui, "integrations", obj, &[], crate::i18n::Lang::from_pref("en"), None, ""), obj, ); h.run_steps(4); h.get_by_label("Allow agent control"); - assert_eq!(h.query_all_by_label("Applies at next launch.").count(), 2, "one notice under each row"); + // The label and the text field it names. + for folder in ["Automation read folder", "Automation write folder"] { + assert!(h.query_all_by_label(folder).count() >= 1, "{folder}"); + } + assert_eq!(h.query_all_by_label("Applies at next launch.").count(), 4, "one notice under each row"); } #[test] diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 7e71f2233b..878b9ea58e 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -17,6 +17,35 @@ photocraft --control 7878 --control-token-file /private/path/photocraft-control. If the file does not exist, PhotoCraft creates it with a fresh 256-bit token. On Unix the new file is mode `0600`; on Windows, protect it with an appropriate user-only ACL. An existing file is reused. If neither a token nor token file is configured, PhotoCraft generates a token for that launch and writes it to standard error. `PHOTOCRAFT_CONTROL_TOKEN` and `PHOTOCRAFT_CONTROL_TOKEN_FILE` are the environment-variable equivalents. A flag wins over its variable and an empty variable counts as unset; with `--control` (or `PHOTOCRAFT_CONTROL_PORT`), a token together with a token file, from flags or variables, is a usage error (exit status 2). Without it no token is read, so the pair is ignored. +### Without `--control`: Preferences › Integrations + +An app started from the Dock, the Start menu or a file manager has no command line. Preferences › Integrations sets the same things for every launch (read when the app starts): + +| Preference | Launch option it stands in for | +|---|---| +| `integrations.allowAgentControl` (default on) | Off refuses the control server, `--control` included | +| `integrations.controlPort` (default 0) | `--control `; 0 = only with `--control` | +| `integrations.readRoot` (default empty) | `--automation-read-root` | +| `integrations.writeRoot` (default empty) | `--automation-write-root` | + +Each launch option, or its environment variable, wins over its preference; the two folders are decided separately. A folder named by a flag that can't be opened stops the launch (exit status 2), as before. A folder named only in the preferences that can't be opened is left out, so that direction of file access fails closed; the app still starts, prints the reason on standard error and shows it in a notice. Automation can't change the two folders (`prefs.set` refuses `integrations.readRoot`, `integrations.writeRoot` and the whole `integrations` section): an agent must not widen its own file access. + +When the control server is started by `controlPort` (no `--control`) and no token was given, the app keeps its token in its settings folder, in `agent-control.token`, exactly as `--control-token-file /agent-control.token` would (created mode `0600` with a fresh token when missing, reused otherwise; delete it to get a new token). It then publishes the connection beside it, in `agent-connection.json`: + +```json +{ + "version": 1, + "pid": 41234, + "port": 7878, + "tokenFile": "/Users/me/Library/Application Support/Photocraft/agent-control.token", + "app": "0.20.1 (8e9277e20, 2026-11-04)" +} +``` + +A local client reads that file, then the token from `tokenFile`, connects to `127.0.0.1:` and authenticates as above. The file holds no secret. With `--control-token-file` or `PHOTOCRAFT_CONTROL_TOKEN_FILE` (and `controlPort`), `tokenFile` names that file instead; with a token given as a value (`--control-token`, `PHOTOCRAFT_CONTROL_TOKEN`) nothing is published. A `--control` launch publishes nothing: whoever started it chose the port and token. + +On Windows and Linux the app removes the file when it quits. On macOS (quitting ends the process inside AppKit) and after a crash the file stays behind, naming a `port` nothing listens on: a client should treat a refused connection as "not running", and the next launch replaces or removes the file. `version` changes only with an incompatible format. The settings folder is the one that holds `preferences.json` (see [Preferences](#preferences); `PHOTOCRAFT_CONFIG_DIR` moves it). + The first request on every TCP connection must authenticate. No other method is dispatched before this succeeds: ```json @@ -261,6 +290,8 @@ the same commands work in the app, the CLI and headless MCP. Paths are dotted ca `unitsAndRulers`, `guidesGridAndSlices`, `plugIns`, `type`, `enhancedControls`, `rawDefaults`, `integrations`, plus `shortcuts.`, `menus` (`hidden`, `colors.`), `toolbar` (`hidden`, `order`) and `colorSettings` (Edit › Color Settings). +`integrations` (`allowAgentControl`, `controlPort`, `readRoot`, `writeRoot`) is read when the +desktop app starts; see [Without `--control`](#without---control-preferences--integrations). | Command | Params | |---|---| @@ -404,7 +435,8 @@ lines are visible. The protocol is unencrypted and must remain on loopback; do n it to an untrusted host. Filesystem access fails closed unless launch-time read and/or write roots are granted with -`--automation-read-root` and `--automation-write-root`. The environment-variable equivalents +`--automation-read-root` and `--automation-write-root` (or, for the desktop app, Preferences › +Integrations' `readRoot` / `writeRoot`, see [Without `--control`](#without---control-preferences--integrations)). The environment-variable equivalents (`PHOTOCRAFT_AUTOMATION_READ_ROOT` / `PHOTOCRAFT_AUTOMATION_WRITE_ROOT`) are supported by the desktop `photocraft` process, but not by headless `photocraft-cli mcp` or `serve`; for those CLI modes, supply the flags explicitly. In MCP bridge mode, configure roots on the diff --git a/docs/scorecard.md b/docs/scorecard.md index 713d5a3dc8..3af236810c 100644 --- a/docs/scorecard.md +++ b/docs/scorecard.md @@ -9,7 +9,7 @@ Generated by `cargo xtask scorecard` from `perf/budgets.toml`, `perf/baseline.js | [Performance](#performance) | 3 | 22 | 45 | 79 scenarios: 3 within budget, 22 over budget or failing, 9 tracked only, 41 not run, 4 not measurable yet (baseline 2026-10-05) | | [File compatibility](#file-compatibility) | 11 | 14 | 2 | io corpus: oracle ≥ 148/170, round trip ≥ 169/170; psd-tools corpus: oracle ≥ 249/309, round trip ≥ 308/309; photoshop oracles: oracle ≥ 190/258, round trip ≥ 258/258 | | [Tools](#tools) | 36 | 9 | 0 | | -| [Workspace and UI](#workspace-and-ui) | 15 | 6 | 2 | settings that do nothing: 10 of 187 (target 0) | +| [Workspace and UI](#workspace-and-ui) | 15 | 6 | 2 | settings that do nothing: 10 of 189 (target 0) | | [Type](#type) | 5 | 5 | 0 | | | [Automation](#automation) | 5 | 3 | 3 | 640 of 640 menu items live (100.0%) | | [Reliability](#reliability) | 5 | 2 | 0 | never-crash lints on 30 of 30 crates; panic_hunt present | @@ -203,7 +203,7 @@ Corpus floors (`crates/io/tests/it/corpus.rs`): the enforced minimums; the corpu ## Workspace and UI -**Settings that do nothing: 10 of 187** (target 0, #204). Counted by the prefs audit (`xtask/src/scorecard.rs`): a `Preferences` field counts as read when code outside the prefs model (`prefs.rs` except its `impl Session` blocks; tests excluded; the schema-driven dialog never names a field) accesses `section.field`, or `.section` and `.field` in the same file, or calls a section method that reads `self.field`. It is a heuristic lower bound: a generic name can look read when it isn't. +**Settings that do nothing: 10 of 189** (target 0, #204). Counted by the prefs audit (`xtask/src/scorecard.rs`): a `Preferences` field counts as read when code outside the prefs model (`prefs.rs` except its `impl Session` blocks; tests excluded; the schema-driven dialog never names a field) accesses `section.field`, or `.section` and `.field` in the same file, or calls a section method that reads `self.field`. It is a heuristic lower bound: a generic name can look read when it isn't. Unread: `general.color_picker`, `workspace.auto_show_hidden_panels`, `workspace.enable_floating_document_window_docking`, `performance.legacy_compositing`, `units_and_rulers.column_width`, `units_and_rulers.gutter`, `plug_ins.show_extension_panels`, `plug_ins.allow_scripts_to_connect`, `type_.text_engine`, `enhanced_controls.scrubby_slider_acceleration`. From a299480c78082500fa7c0bf5da2046df33e7ad03 Mon Sep 17 00:00:00 2001 From: Tom Ingling Date: Thu, 5 Nov 2026 12:56:49 -0500 Subject: [PATCH 05/28] Regenerate the scorecard after merging main Main's settings count plus this branch's two Automation folder preferences: 191. Co-Authored-By: Claude Opus 5.5 --- docs/scorecard.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/scorecard.md b/docs/scorecard.md index c540f7b060..2fbbee5103 100644 --- a/docs/scorecard.md +++ b/docs/scorecard.md @@ -9,7 +9,7 @@ Generated by `cargo xtask scorecard` from `perf/budgets.toml`, `perf/baseline.js | [Performance](#performance) | 3 | 22 | 49 | 83 scenarios: 3 within budget, 22 over budget or failing, 9 tracked only, 45 not run, 4 not measurable yet (baseline 2026-10-05) | | [File compatibility](#file-compatibility) | 11 | 14 | 2 | io corpus: oracle ≥ 148/170, round trip ≥ 169/170; psd-tools corpus: oracle ≥ 249/309, round trip ≥ 308/309; photoshop oracles: oracle ≥ 190/258, round trip ≥ 258/258 | | [Tools](#tools) | 36 | 9 | 0 | | -| [Workspace and UI](#workspace-and-ui) | 15 | 6 | 2 | settings that do nothing: 10 of 189 (target 0) | +| [Workspace and UI](#workspace-and-ui) | 15 | 6 | 2 | settings that do nothing: 10 of 191 (target 0) | | [Type](#type) | 5 | 5 | 0 | | | [Automation](#automation) | 5 | 3 | 3 | 660 of 660 menu items live (100.0%) | | [Reliability](#reliability) | 5 | 2 | 0 | never-crash lints on 30 of 30 crates; panic_hunt present | @@ -207,7 +207,7 @@ Corpus floors (`crates/io/tests/it/corpus.rs`): the enforced minimums; the corpu ## Workspace and UI -**Settings that do nothing: 10 of 189** (target 0, #204). Counted by the prefs audit (`xtask/src/scorecard.rs`): a `Preferences` field counts as read when code outside the prefs model (`prefs.rs` except its `impl Session` blocks; tests excluded; the schema-driven dialog never names a field) accesses `section.field`, or `.section` and `.field` in the same file, or calls a section method that reads `self.field`. It is a heuristic lower bound: a generic name can look read when it isn't. +**Settings that do nothing: 10 of 191** (target 0, #204). Counted by the prefs audit (`xtask/src/scorecard.rs`): a `Preferences` field counts as read when code outside the prefs model (`prefs.rs` except its `impl Session` blocks; tests excluded; the schema-driven dialog never names a field) accesses `section.field`, or `.section` and `.field` in the same file, or calls a section method that reads `self.field`. It is a heuristic lower bound: a generic name can look read when it isn't. Unread: `general.color_picker`, `workspace.auto_show_hidden_panels`, `workspace.enable_floating_document_window_docking`, `performance.legacy_compositing`, `units_and_rulers.column_width`, `units_and_rulers.gutter`, `plug_ins.show_extension_panels`, `plug_ins.allow_scripts_to_connect`, `type_.text_engine`, `enhanced_controls.scrubby_slider_acceleration`. From 1f83bc2556506e186c0dfeaa45030d259750c5fc Mon Sep 17 00:00:00 2001 From: Tom Ingling Date: Thu, 5 Nov 2026 22:09:22 -0500 Subject: [PATCH 06/28] Address review: fail closed on an unwritable token file, open each folder once - A token file the preferences need that can't be written or read leaves the control server off for that launch, with an "Agent control is off" notice and the reason on standard error, instead of exiting before the window opens. A file named by --control-token-file still exits 2. - Each preference folder is opened once and its capability combined with the flags' (AuthorizedWorkspace::with_read_from / with_write_from), so a folder that goes away mid-launch is left out instead of exiting 2. - A relative folder preference is left out with a warning; flags keep their behaviour. - tokenFile is published as an absolute path. - read_connection refuses anything but a regular file (a FIFO can't block startup) and reads invalid UTF-8 as no connection, so it is removed. - Docs: a client checks that the connection file's pid is running before sending the token; the token-file failure case. - Tests: a preference-started server publishes a connection whose token authenticates against the real control server; the unwritable token file; relative folders and token paths; non-regular and non-UTF-8 connection files; the Integrations UI test finds the text fields. Co-Authored-By: Claude Opus 5.5 --- apps/photocraft/src/main.rs | 181 +++++++++++++++++---- crates/automation/src/agent_link.rs | 42 +++-- crates/automation/src/workspace.rs | 12 ++ crates/ui-egui/src/prefs/prefs_ui/tests.rs | 2 +- docs/control-protocol.md | 6 +- 5 files changed, 197 insertions(+), 46 deletions(-) diff --git a/apps/photocraft/src/main.rs b/apps/photocraft/src/main.rs index de7a8f50f1..6cde640623 100644 --- a/apps/photocraft/src/main.rs +++ b/apps/photocraft/src/main.rs @@ -131,37 +131,43 @@ fn integrations(prefs_file: Option<&std::path::Path>) -> photocraft_engine::pref /// The automation roots: `--automation-read-root` / `--automation-write-root` (or their /// variables) win; a direction without one takes Preferences › Integrations' folder. A flag's /// root that can't be opened stops the launch (exit status 2) as before. A preference's root that -/// can't be opened is left out, so that direction fails closed, and the warning says why: a -/// folder moved since it was chosen must not stop the app from starting. +/// can't be opened, or isn't an absolute path (it would depend on the folder the app was started +/// from), is left out, so that direction fails closed, and the warning says why: a folder moved +/// since it was chosen must not stop the app from starting. Each folder is opened once, so one +/// that goes away during the launch can't turn into an error. fn automation_workspace( flags: &photocraft_automation::args::AutomationArgs, prefs: &photocraft_engine::prefs::Integrations, ) -> Result<(photocraft_automation::workspace::AuthorizedWorkspace, Option), photocraft_automation::AutomationError> { use photocraft_automation::{agent_link::folder, workspace::AuthorizedWorkspace}; - let flagged = flags.workspace()?; + let mut workspace = flags.workspace()?; let mut warnings = Vec::new(); - let mut from_pref = |flag: &Option, pref: &str, read: bool| -> Option { + let mut from_pref = |flag: &Option, pref: &str, read: bool| -> Option { if flag.is_some() { - return flag.clone(); + return None; } let root = folder(pref)?; - let opened = if read { AuthorizedWorkspace::new(Some(&root), None) } else { AuthorizedWorkspace::new(None, Some(&root)) }; - match opened { - Ok(_) => Some(root), - Err(e) => { + let opened = if !root.is_absolute() { + Err(format!("`{}` is not an absolute path", root.display())) + } else if read { + AuthorizedWorkspace::new(Some(&root), None).map_err(|e| e.to_string()) + } else { + AuthorizedWorkspace::new(None, Some(&root)).map_err(|e| e.to_string()) + }; + opened + .map_err(|e| { let which = if read { "Automation Read Folder" } else { "Automation Write Folder" }; warnings.push(format!("Preferences › Integrations › {which} is not used: {e}")); - None - } - } + }) + .ok() }; - let read = from_pref(&flags.automation_read_root, &prefs.read_root, true); - let write = from_pref(&flags.automation_write_root, &prefs.write_root, false); - let warning = (!warnings.is_empty()).then(|| warnings.join("\n")); - if read == flags.automation_read_root && write == flags.automation_write_root { - return Ok((flagged, warning)); + if let Some(read) = from_pref(&flags.automation_read_root, &prefs.read_root, true) { + workspace = workspace.with_read_from(read); } - Ok((AuthorizedWorkspace::new(read.as_deref(), write.as_deref())?, warning)) + if let Some(write) = from_pref(&flags.automation_write_root, &prefs.write_root, false) { + workspace = workspace.with_write_from(write); + } + Ok((workspace, (!warnings.is_empty()).then(|| warnings.join("\n")))) } /// The connection file a launch published ([`photocraft_automation::agent_link`]); dropping it @@ -180,7 +186,9 @@ impl Drop for Published { /// server still runs, as with `--control`. fn publish_connection(dir: &std::path::Path, port: u16, token_file: &std::path::Path) -> Option { use photocraft_automation::agent_link::{Connection, write_connection}; - match write_connection(dir, &Connection::new(port, token_file.to_path_buf())) { + // A relative `--control-token-file` is relative to this process's folder, not the client's. + let token_file = std::path::absolute(token_file).unwrap_or_else(|_| token_file.to_path_buf()); + match write_connection(dir, &Connection::new(port, token_file)) { Ok(()) => { eprintln!("photocraft: control connection published in {}", dir.join(photocraft_automation::agent_link::CONNECTION_FILE).display()); Some(Published(dir.to_path_buf())) @@ -359,11 +367,18 @@ fn linux_display_session() -> linux_libs::DisplaySession { type Control = (std::net::TcpListener, String, photocraft_automation::workspace::AuthorizedWorkspace); /// What [`control_setup`] set up: the control server when it is on, the connection file it -/// published, and a warning for the window (a preference's automation folder that wasn't used). +/// published, and a notice for the window (a preference's automation folder that wasn't used, or +/// a token file the preferences needed that couldn't be written). struct ControlSetup { control: Option, published: Option, - warning: Option, + warning: Option, +} + +/// A notice for the window about the control server: a Dock launch has no console. +struct ControlNotice { + title: &'static str, + lines: Vec, } /// The control server's port, token and workspace, when it is on (exits 2 on a bad configuration). @@ -371,16 +386,27 @@ struct ControlSetup { /// Started from Preferences › Integrations (no `--control`) and given no token, it keeps its token /// in the settings folder (`agent-control.token`, as with `--control-token-file`) and publishes /// the connection there ([`photocraft_automation::agent_link`]), so a client can drive an app -/// started from the Dock. +/// started from the Dock. When that token file can't be written (a read-only or full settings +/// folder), the app starts with the control server off and says why, as for a preference's +/// automation folder, instead of exiting before its window opens. fn control_setup( cli_port: Option, auth: photocraft_automation::args::ControlArgs, automation: &photocraft_automation::args::AutomationArgs, +) -> ControlSetup { + control_setup_in(services::config_dir(), &integrations(services::prefs_file().as_deref()), cli_port, auth, automation) +} + +/// [`control_setup`] with the settings folder and Preferences › Integrations given. +fn control_setup_in( + settings: Option, + prefs: &photocraft_engine::prefs::Integrations, + cli_port: Option, + auth: photocraft_automation::args::ControlArgs, + automation: &photocraft_automation::args::AutomationArgs, ) -> ControlSetup { use photocraft_automation::agent_link; - let settings = services::config_dir(); - let prefs = integrations(services::prefs_file().as_deref()); - let (port, warning) = control_port_for(cli_port, &prefs); + let (port, warning) = control_port_for(cli_port, prefs); if let Some(warning) = &warning { eprint!("{warning}"); } @@ -401,13 +427,22 @@ fn control_setup( }; let from_prefs = cli_port.is_none(); let (supplied, token_file) = (auth.control_token, auth.control_token_file); + let settings_token = token_file.is_none() && supplied.is_none() && from_prefs; let token_file = match (token_file, &settings) { (Some(file), _) => Some(file), - (None, Some(dir)) if from_prefs && supplied.is_none() => Some(dir.join(agent_link::TOKEN_FILE)), + (None, Some(dir)) if settings_token => Some(dir.join(agent_link::TOKEN_FILE)), (None, _) => None, }; let token = match photocraft_automation::security::server_token(supplied.as_deref(), token_file.as_deref()) { Ok(token) => token, + // The token file the preferences need, in the settings folder: fail closed (no server, so + // no token to leak) and say so in the window. + Err(e) if settings_token => { + let line = format!("Preferences › Integrations › Control Port is not used: the token file could not be written: {e}"); + eprintln!("photocraft: {line}"); + log::warn!("{line}"); + return ControlSetup { control: None, published: None, warning: Some(ControlNotice { title: "Agent control is off", lines: vec![line] }) }; + } Err(e) => { eprintln!("photocraft: cannot configure control authentication: {e}"); std::process::exit(2); @@ -420,7 +455,7 @@ fn control_setup( } else { eprintln!("photocraft: using supplied control token"); } - let (workspace, warning) = match automation_workspace(automation, &prefs) { + let (workspace, warning) = match automation_workspace(automation, prefs) { Ok(workspace) => workspace, Err(error) => { eprintln!("photocraft: cannot configure automation workspace: {error}"); @@ -437,6 +472,7 @@ fn control_setup( (Some(dir), Some(file), Ok(addr)) if from_prefs => publish_connection(dir, addr.port(), file), _ => None, }; + let warning = warning.map(|w| ControlNotice { title: "Automation folder not used", lines: w.lines().map(str::to_owned).collect() }); ControlSetup { control: Some((listener, token, workspace)), published, warning } } @@ -800,9 +836,10 @@ fn main() -> eframe::Result { if let Some(w) = &app_dirs::current().warning { photocraft_ui_egui::notices::post(&mut app, "Portable mode is off", vec![w.clone()], false, None); } - // A preference's automation folder that couldn't be opened: a Dock launch has no console. - if let Some(w) = control_warning { - photocraft_ui_egui::notices::post(&mut app, "Automation folder not used", w.lines().map(str::to_owned).collect(), false, None); + // A preference's automation folder that couldn't be opened, or a token file it couldn't + // write: a Dock launch has no console. + if let Some(ControlNotice { title, lines }) = control_warning { + photocraft_ui_egui::notices::post(&mut app, title, lines, false, None); } Ok(Box::new(app)) }), @@ -1253,6 +1290,90 @@ mod tests { let blocker = dir.join("blocker"); std::fs::write(&blocker, b"").unwrap(); assert!(super::publish_connection(&blocker.join("settings"), 7878, &token).is_none()); + // A relative token file is published as absolute: the client runs from another folder. + let published = super::publish_connection(&dir, 7878, std::path::Path::new("relative.token")).expect("published"); + let c = agent_link::read_connection(&dir).unwrap().expect("a connection"); + assert_eq!(c.token_file, std::env::current_dir().unwrap().join("relative.token")); + drop(published); + let _ = std::fs::remove_dir_all(&dir); + } + + /// A relative folder preference would depend on the folder the app was started from: left + /// out with a warning, like a missing one. + #[test] + fn a_relative_preference_folder_is_left_out() { + let dir = temp_dir("automation-roots-relative"); + let relative = photocraft_engine::prefs::Integrations { read_root: ".".into(), ..roots(&dir, &dir) }; + let (ws, warning) = super::automation_workspace(&flags(None, None), &relative).unwrap(); + let warning = warning.expect("the relative read folder is named"); + assert!(warning.contains("Automation Read Folder") && warning.contains("not an absolute path"), "{warning}"); + assert!(ws.read("anything").is_err(), "no read access from a relative folder"); + ws.write("out.txt", b"x").unwrap(); + assert!(dir.join("out.txt").is_file(), "the absolute write folder still applies"); + let _ = std::fs::remove_dir_all(&dir); + } + + /// A launch the preferences start (no `--control`, no token): the token goes in the settings + /// folder, the connection is published there, and the token in the file it names opens the + /// control server. + #[test] + fn a_preference_started_server_publishes_a_connection_that_authenticates() { + use photocraft_automation::{agent_link, security}; + use std::io::{BufRead, Write}; + let settings = temp_dir("preference-started"); + let port = std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port(); + let prefs = photocraft_engine::prefs::Integrations { allow_agent_control: true, control_port: u32::from(port), ..Default::default() }; + let auth = photocraft_automation::args::ControlArgs { control_token: None, control_token_file: None }; + let setup = super::control_setup_in(Some(settings.clone()), &prefs, None, auth, &flags(None, None)); + let (listener, token, _) = setup.control.expect("the preference starts the server"); + assert!(setup.published.is_some() && setup.warning.is_none()); + + let c = agent_link::read_connection(&settings).unwrap().expect("a published connection"); + assert_eq!((c.port, c.token_file.clone()), (port, settings.join(agent_link::TOKEN_FILE))); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + assert_eq!(std::fs::metadata(&c.token_file).unwrap().permissions().mode() & 0o777, 0o600); + } + let from_file = security::client_token(None, Some(&c.token_file)).unwrap(); + assert_eq!(from_file, token); + + let _requests = crate::control_server::start(listener, token, eframe::egui::Context::default()); + let mut stream = std::net::TcpStream::connect(c.addr()).unwrap(); + stream.set_read_timeout(Some(std::time::Duration::from_secs(5))).unwrap(); + let mut replies = std::io::BufReader::new(stream.try_clone().unwrap()); + writeln!(stream, "{}", serde_json::json!({"id": "auth", "method": "auth", "params": {"token": from_file}})).unwrap(); + let mut line = String::new(); + replies.read_line(&mut line).unwrap(); + assert_eq!(serde_json::from_str::(&line).unwrap()["result"]["authenticated"], true, "{line}"); + + // `--control` publishes nothing. + drop(setup.published); + let port = std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port(); + let auth = photocraft_automation::args::ControlArgs { control_token: None, control_token_file: Some(settings.join("cli.token")) }; + let setup = super::control_setup_in(Some(settings.clone()), &prefs, Some(port), auth, &flags(None, None)); + assert!(setup.control.is_some() && setup.published.is_none()); + assert_eq!(agent_link::read_connection(&settings).unwrap(), None); + let _ = std::fs::remove_dir_all(&settings); + } + + /// A token file the preferences need but can't write (here the "settings folder" is a file) + /// leaves the control server off with a notice, and its port free, instead of exiting before + /// the window opens. + #[test] + fn a_token_file_that_cannot_be_written_turns_preference_control_off() { + let dir = temp_dir("unwritable-token"); + let settings = dir.join("not-a-folder"); + std::fs::write(&settings, b"").unwrap(); + let port = std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port(); + let prefs = photocraft_engine::prefs::Integrations { allow_agent_control: true, control_port: u32::from(port), ..Default::default() }; + let auth = photocraft_automation::args::ControlArgs { control_token: None, control_token_file: None }; + let setup = super::control_setup_in(Some(settings.clone()), &prefs, None, auth, &flags(None, None)); + assert!(setup.control.is_none() && setup.published.is_none()); + let notice = setup.warning.expect("a notice says why"); + assert_eq!(notice.title, "Agent control is off"); + assert!(notice.lines.iter().any(|l| l.contains("token file")), "{:?}", notice.lines); + std::net::TcpListener::bind(("127.0.0.1", port)).expect("the port was let go"); let _ = std::fs::remove_dir_all(&dir); } diff --git a/crates/automation/src/agent_link.rs b/crates/automation/src/agent_link.rs index bc6c51627b..00da1c15a1 100644 --- a/crates/automation/src/agent_link.rs +++ b/crates/automation/src/agent_link.rs @@ -9,7 +9,8 @@ //! //! The file holds no secret. A crashed (or, on macOS, quit) app can leave it behind; nothing then //! listens on its port ([`probe`]), and the app's next launch replaces it or removes it -//! ([`remove_stale_connection`]). +//! ([`remove_stale_connection`]). Until then another program could take that port, so a client +//! checks that [`Connection::pid`] is still running before it sends the token. use std::net::{SocketAddr, TcpStream}; use std::path::{Path, PathBuf}; @@ -69,7 +70,9 @@ pub fn write_connection(dir: &Path, c: &Connection) -> Result<(), AutomationErro } /// The connection published in `dir`, if any. A file from another version or one that doesn't -/// parse counts as none: the app rewrites it when it next starts listening. +/// parse (invalid UTF-8 included) counts as none: the app rewrites it when it next starts +/// listening. Anything but a regular file (a FIFO would block the read) is an error, and left +/// alone. pub fn read_connection(dir: &Path) -> Result, AutomationError> { let path = dir.join(CONNECTION_FILE); let meta = match std::fs::metadata(&path) { @@ -77,15 +80,18 @@ pub fn read_connection(dir: &Path) -> Result, AutomationError Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None), Err(e) => return Err(io_error(&path, e)), }; + if !meta.is_file() { + return Err(io_error(&path, "not a regular file")); + } if meta.len() > MAX_CONNECTION_BYTES { return Err(io_error(&path, format!("larger than {MAX_CONNECTION_BYTES} bytes"))); } - let text = match std::fs::read_to_string(&path) { - Ok(s) => s, + let bytes = match std::fs::read(&path) { + Ok(b) => b, Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None), Err(e) => return Err(io_error(&path, e)), }; - Ok(serde_json::from_str::(&text).ok().filter(|c| c.version == CONNECTION_VERSION && c.port != 0)) + Ok(serde_json::from_slice::(&bytes).ok().filter(|c| c.version == CONNECTION_VERSION && c.port != 0)) } /// Remove the connection file in `dir` if process `pid` wrote it (another instance may have @@ -157,12 +163,22 @@ mod tests { fn other_versions_garbage_and_port_zero_read_as_none() { let dir = temp(); assert_eq!(read_connection(&dir).unwrap(), None, "no file"); - for text in - ["{not json", r#"{"version":2,"pid":1,"port":7878,"tokenFile":"t","app":"x"}"#, r#"{"version":1,"pid":1,"port":0,"tokenFile":"t","app":"x"}"#] - { + for text in [ + &b"{not json"[..], + br#"{"version":2,"pid":1,"port":7878,"tokenFile":"t","app":"x"}"#, + br#"{"version":1,"pid":1,"port":0,"tokenFile":"t","app":"x"}"#, + b"\xff\xfe not utf-8", + ] { std::fs::write(dir.join(CONNECTION_FILE), text).unwrap(); - assert_eq!(read_connection(&dir).unwrap(), None, "{text}"); + assert_eq!(read_connection(&dir).unwrap(), None, "{}", String::from_utf8_lossy(text)); } + std::fs::remove_file(dir.join(CONNECTION_FILE)).unwrap(); + // Not a regular file: an error (and `remove_stale_connection` leaves it), never a read + // that could block on a FIFO. + std::fs::create_dir(dir.join(CONNECTION_FILE)).unwrap(); + assert!(read_connection(&dir).is_err()); + remove_stale_connection(&dir); + assert!(dir.join(CONNECTION_FILE).is_dir()); let _ = std::fs::remove_dir_all(&dir); } @@ -192,9 +208,11 @@ mod tests { write_connection(&dir, &Connection { pid: 1, ..Connection::new(closed, dir.join(TOKEN_FILE)) }).unwrap(); remove_stale_connection(&dir); assert!(!dir.join(CONNECTION_FILE).exists(), "nothing listens on {closed}"); - std::fs::write(dir.join(CONNECTION_FILE), "{not json").unwrap(); - remove_stale_connection(&dir); - assert!(!dir.join(CONNECTION_FILE).exists(), "an unreadable file is not a connection"); + for text in [&b"{not json"[..], b"\xff\xfe not utf-8"] { + std::fs::write(dir.join(CONNECTION_FILE), text).unwrap(); + remove_stale_connection(&dir); + assert!(!dir.join(CONNECTION_FILE).exists(), "an unreadable file is not a connection"); + } remove_stale_connection(&dir); let _ = std::fs::remove_dir_all(&dir); } diff --git a/crates/automation/src/workspace.rs b/crates/automation/src/workspace.rs index 15c697c0c7..3b341dd3a9 100644 --- a/crates/automation/src/workspace.rs +++ b/crates/automation/src/workspace.rs @@ -44,6 +44,18 @@ impl AuthorizedWorkspace { Ok(Self { read: open_root(read_root, "read")?, write: open_root(write_root, "write")? }) } + /// This workspace with `other`'s read authority instead of its own (the write authority + /// stays). Combines roots opened separately without opening them again. + pub fn with_read_from(self, other: Self) -> Self { + Self { read: other.read, ..self } + } + + /// This workspace with `other`'s write authority instead of its own (the read authority + /// stays). + pub fn with_write_from(self, other: Self) -> Self { + Self { write: other.write, ..self } + } + /// Read one regular file below the configured read root. pub fn read(&self, path: &str) -> Result, AutomationError> { let relative = request_path(path, self.read.as_ref())?; diff --git a/crates/ui-egui/src/prefs/prefs_ui/tests.rs b/crates/ui-egui/src/prefs/prefs_ui/tests.rs index 2e5db67eb2..33126f0311 100644 --- a/crates/ui-egui/src/prefs/prefs_ui/tests.rs +++ b/crates/ui-egui/src/prefs/prefs_ui/tests.rs @@ -1710,7 +1710,7 @@ fn integrations_explain_next_launch() { h.get_by_label("Allow agent control"); // The label and the text field it names. for folder in ["Automation read folder", "Automation write folder"] { - assert!(h.query_all_by_label(folder).count() >= 1, "{folder}"); + h.get_by_role_and_label(egui::accesskit::Role::TextInput, folder); } assert_eq!(h.query_all_by_label("Applies at next launch.").count(), 4, "one notice under each row"); } diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 4675151294..b508c3a71c 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -28,9 +28,9 @@ An app started from the Dock, the Start menu or a file manager has no command li | `integrations.readRoot` (default empty) | `--automation-read-root` | | `integrations.writeRoot` (default empty) | `--automation-write-root` | -Each launch option, or its environment variable, wins over its preference; the two folders are decided separately. A folder named by a flag that can't be opened stops the launch (exit status 2), as before. A folder named only in the preferences that can't be opened is left out, so that direction of file access fails closed; the app still starts, prints the reason on standard error and shows it in a notice. Automation can't change the two folders (`prefs.set` refuses `integrations.readRoot`, `integrations.writeRoot` and the whole `integrations` section): an agent must not widen its own file access. +Each launch option, or its environment variable, wins over its preference; the two folders are decided separately. A folder named by a flag that can't be opened stops the launch (exit status 2), as before. A folder named only in the preferences that can't be opened, or isn't an absolute path, is left out, so that direction of file access fails closed; the app still starts, prints the reason on standard error and shows it in a notice. Automation can't change the two folders (`prefs.set` refuses `integrations.readRoot`, `integrations.writeRoot` and the whole `integrations` section): an agent must not widen its own file access. -When the control server is started by `controlPort` (no `--control`) and no token was given, the app keeps its token in its settings folder, in `agent-control.token`, exactly as `--control-token-file /agent-control.token` would (created mode `0600` with a fresh token when missing, reused otherwise; delete it to get a new token). It then publishes the connection beside it, in `agent-connection.json`: +When the control server is started by `controlPort` (no `--control`) and no token was given, the app keeps its token in its settings folder, in `agent-control.token`, exactly as `--control-token-file /agent-control.token` would (created mode `0600` with a fresh token when missing, reused otherwise; delete it to get a new token). If that file can't be written or read (a read-only or full settings folder), the control server stays off for that launch: the app still starts, prints the reason on standard error and shows it in a notice. A token file named by `--control-token-file` that can't be used still stops the launch (exit status 2). Otherwise the app publishes the connection beside it, in `agent-connection.json`: ```json { @@ -44,7 +44,7 @@ When the control server is started by `controlPort` (no `--control`) and no toke A local client reads that file, then the token from `tokenFile`, connects to `127.0.0.1:` and authenticates as above. The file holds no secret. With `--control-token-file` or `PHOTOCRAFT_CONTROL_TOKEN_FILE` (and `controlPort`), `tokenFile` names that file instead; with a token given as a value (`--control-token`, `PHOTOCRAFT_CONTROL_TOKEN`) nothing is published. A `--control` launch publishes nothing: whoever started it chose the port and token. -On Windows and Linux the app removes the file when it quits. On macOS (quitting ends the process inside AppKit) and after a crash the file stays behind, naming a `port` nothing listens on: a client should treat a refused connection as "not running", and the next launch replaces or removes the file. `version` changes only with an incompatible format. The settings folder is the one that holds `preferences.json` (see [Preferences](#preferences); `PHOTOCRAFT_CONFIG_DIR` moves it). +On Windows and Linux the app removes the file when it quits. On macOS (quitting ends the process inside AppKit) and after a crash the file stays behind, naming a `port` nothing listens on: a client should treat a refused connection as "not running", and the next launch replaces or removes the file. Until then, another local program could be listening on that port, so a client must check that the process `pid` names is still running before it sends the token, and treat the file as stale otherwise. (A challenge exchange that never sends the token to the listener, #9778, would make that check unnecessary.) `version` changes only with an incompatible format. The settings folder is the one that holds `preferences.json` (see [Preferences](#preferences); `PHOTOCRAFT_CONFIG_DIR` moves it). The first request on every TCP connection must authenticate. No other method is dispatched before this succeeds: From 820479f426d5f9fb20dfe41c151a913610af3810 Mon Sep 17 00:00:00 2001 From: Tom Ingling Date: Fri, 6 Nov 2026 15:43:01 -0500 Subject: [PATCH 07/28] Address review: never publish a relative token path; say what the pid check doesn't cover A token file path that can't be made absolute is no longer published (the launch logs why and runs unpublished). The docs say the pid check narrows but doesn't close the leftover-file gap, who it matters against, and that a client that must rule it out should use a challenge exchange (#9778) with no fallback. Co-Authored-By: Claude Opus 5.5 --- apps/photocraft/src/main.rs | 15 +++++++++++++-- crates/automation/src/agent_link.rs | 4 +++- docs/control-protocol.md | 2 +- 3 files changed, 17 insertions(+), 4 deletions(-) diff --git a/apps/photocraft/src/main.rs b/apps/photocraft/src/main.rs index 4ef23480c2..f3794f061c 100644 --- a/apps/photocraft/src/main.rs +++ b/apps/photocraft/src/main.rs @@ -186,8 +186,16 @@ impl Drop for Published { /// server still runs, as with `--control`. fn publish_connection(dir: &std::path::Path, port: u16, token_file: &std::path::Path) -> Option { use photocraft_automation::agent_link::{Connection, write_connection}; - // A relative `--control-token-file` is relative to this process's folder, not the client's. - let token_file = std::path::absolute(token_file).unwrap_or_else(|_| token_file.to_path_buf()); + // A relative `--control-token-file` is relative to this process's folder, not the client's: + // publish nothing rather than a path a client would resolve somewhere else. + let token_file = match std::path::absolute(token_file) { + Ok(path) => path, + Err(e) => { + eprintln!("photocraft: couldn't publish the control connection: {}: {e}", token_file.display()); + log::warn!("couldn't publish the control connection: {}: {e}", token_file.display()); + return None; + } + }; match write_connection(dir, &Connection::new(port, token_file)) { Ok(()) => { eprintln!("photocraft: control connection published in {}", dir.join(photocraft_automation::agent_link::CONNECTION_FILE).display()); @@ -1303,6 +1311,9 @@ mod tests { let c = agent_link::read_connection(&dir).unwrap().expect("a connection"); assert_eq!(c.token_file, std::env::current_dir().unwrap().join("relative.token")); drop(published); + // One that can't be made absolute (empty) is not published as given. + assert!(super::publish_connection(&dir, 7878, std::path::Path::new("")).is_none()); + assert_eq!(agent_link::read_connection(&dir).unwrap(), None); let _ = std::fs::remove_dir_all(&dir); } diff --git a/crates/automation/src/agent_link.rs b/crates/automation/src/agent_link.rs index 00da1c15a1..c4fafa4bcc 100644 --- a/crates/automation/src/agent_link.rs +++ b/crates/automation/src/agent_link.rs @@ -10,7 +10,9 @@ //! The file holds no secret. A crashed (or, on macOS, quit) app can leave it behind; nothing then //! listens on its port ([`probe`]), and the app's next launch replaces it or removes it //! ([`remove_stale_connection`]). Until then another program could take that port, so a client -//! checks that [`Connection::pid`] is still running before it sends the token. +//! checks that [`Connection::pid`] is still running before it sends the token. That narrows the +//! gap without closing it (a pid can be reused); `docs/control-protocol.md` says when a client +//! should not send the token on the strength of this file. use std::net::{SocketAddr, TcpStream}; use std::path::{Path, PathBuf}; diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 74ef4438f7..e59296315e 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -44,7 +44,7 @@ When the control server is started by `controlPort` (no `--control`) and no toke A local client reads that file, then the token from `tokenFile`, connects to `127.0.0.1:` and authenticates as above. The file holds no secret. With `--control-token-file` or `PHOTOCRAFT_CONTROL_TOKEN_FILE` (and `controlPort`), `tokenFile` names that file instead; with a token given as a value (`--control-token`, `PHOTOCRAFT_CONTROL_TOKEN`) nothing is published. A `--control` launch publishes nothing: whoever started it chose the port and token. -On Windows and Linux the app removes the file when it quits. On macOS (quitting ends the process inside AppKit) and after a crash the file stays behind, naming a `port` nothing listens on: a client should treat a refused connection as "not running", and the next launch replaces or removes the file. Until then, another local program could be listening on that port, so a client must check that the process `pid` names is still running before it sends the token, and treat the file as stale otherwise. (A challenge exchange that never sends the token to the listener, #9778, would make that check unnecessary.) `version` changes only with an incompatible format. The settings folder is the one that holds `preferences.json` (see [Preferences](#preferences); `PHOTOCRAFT_CONFIG_DIR` moves it). +On Windows and Linux the app removes the file when it quits. On macOS (quitting ends the process inside AppKit) and after a crash the file stays behind, naming a `port` nothing listens on: a client should treat a refused connection as "not running", and the next launch replaces or removes the file. Until then, another local program could be listening on that port. A program running as the same user can read the token file anyway, so this matters only against one that can listen on a loopback port but can't read that `0600` file (another user's, or a sandboxed app). A client must check that the process `pid` names is still running before it sends the token, and treat the file as stale otherwise. That check narrows the gap but doesn't close it: the pid can be reused, and the app can quit between the check and the connection. A client that must rule this out should not send the token on the strength of this file at all; it should use a challenge exchange that never sends the token to the listener (#9778) once that is available, with no fallback to sending the token. `version` changes only with an incompatible format. The settings folder is the one that holds `preferences.json` (see [Preferences](#preferences); `PHOTOCRAFT_CONFIG_DIR` moves it). The first request on every TCP connection must authenticate. No other method is dispatched before this succeeds: From cd41d633946e02f11bfa4308b8cee9a5844172ed Mon Sep 17 00:00:00 2001 From: David Mann Date: Thu, 12 Nov 2026 02:56:45 +0100 Subject: [PATCH 08/28] Batch: Preferences page is "MCP"; Copy Prompt for an Agent MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The page only holds the MCP connection, so Edit › Preferences › AI Integrations… is now Edit › Preferences › MCP… (command id and the `integrations` preference keys unchanged). Copy Prompt for an Agent puts a text on the clipboard that an agent with a terminal (Claude Code, Codex, Cursor's agent) pastes to register `photocraft-cli mcp --live` itself and check the connection; Claude Desktop has no terminal and keeps Add to Claude Desktop. Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- apps/photocraft-cli/src/args.rs | 4 +- apps/photocraft-cli/tests/it/cli.rs | 4 +- apps/photocraft/src/agent_link.rs | 12 +++++- apps/photocraft/src/control_server.rs | 2 +- apps/photocraft/src/main.rs | 16 ++++---- book/src/automation/mcp.md | 2 +- book/src/security/automation-security.md | 2 +- crates/automation/src/agent_link.rs | 40 ++++++++++++++++++- crates/automation/src/lib.rs | 2 +- crates/automation/src/live.rs | 6 +-- crates/automation/tests/mcp_live.rs | 2 +- crates/engine/src/prefs.rs | 2 +- crates/engine/src/prefs/cmds.rs | 2 +- crates/engine/src/prefs/validate.rs | 2 +- crates/ui-egui/src/lib.rs | 2 +- crates/ui-egui/src/menu_catalog.rs | 2 +- .../ui-egui/src/preferences_submenu_tests.rs | 2 +- crates/ui-egui/src/prefs/prefs_ui.rs | 2 +- crates/ui-egui/src/prefs/prefs_ui/agents.rs | 14 ++++++- .../src/prefs/prefs_ui/agents_tests.rs | 9 ++++- crates/ui-egui/src/prefs/prefs_ui/fields.rs | 4 +- crates/ui-egui/src/prefs/prefs_ui/tests.rs | 2 +- crates/ui-egui/src/services.rs | 12 +++--- docs/control-protocol.md | 8 ++-- docs/development.md | 2 +- docs/mcp.md | 2 +- docs/roadmap.md | 4 +- packaging/macos/package.sh | 2 +- scorecard/automation.toml | 2 +- 30 files changed, 115 insertions(+), 54 deletions(-) diff --git a/README.md b/README.md index eb6036d3a6..90a68c32ab 100644 --- a/README.md +++ b/README.md @@ -246,7 +246,7 @@ photocraft-cli batch --help photocraft-cli mcp ``` -To let Claude or another AI app drive the open PhotoCraft window without a terminal, turn on **Edit › Preferences › AI Integrations › Let AI agents connect**, then click **Add to Claude Desktop** (or Claude Code, or Cursor) in the same panel. See [`docs/mcp.md`](docs/mcp.md). +To let Claude or another AI app drive the open PhotoCraft window without a terminal, turn on **Edit › Preferences › MCP › Let AI agents connect**, then click **Add to Claude Desktop** (or Claude Code, or Cursor) in the same panel. See [`docs/mcp.md`](docs/mcp.md). The desktop app also offers an authenticated, loopback-only control channel (`photocraft --control`) for inspecting UI state, driving tools with pointer events, and taking offscreen screenshots. Every image in this README was rendered that way. See [`docs/control-protocol.md`](docs/control-protocol.md). diff --git a/apps/photocraft-cli/src/args.rs b/apps/photocraft-cli/src/args.rs index fb93c8a388..76905d2584 100644 --- a/apps/photocraft-cli/src/args.rs +++ b/apps/photocraft-cli/src/args.rs @@ -276,7 +276,7 @@ pub(crate) struct CommandsArgs { /// Headless: each automation root grants that direction of file access; an omitted root denies it. /// Prefer absolute root paths in MCP client configurations. Bridge: set the roots on the desktop /// app; root flags are refused. The token flags require --bridge (or PHOTOCRAFT_CONTROL_PORT). -/// Live: the desktop app with Edit › Preferences › AI Integrations › Let AI agents connect on, +/// Live: the desktop app with Edit › Preferences › MCP › Let AI agents connect on, /// found again on every call (no port or token to configure); the roots are for a headless session /// while the app is closed. #[derive(Args)] @@ -284,7 +284,7 @@ pub(crate) struct CommandsArgs { pub(crate) struct McpArgs { #[command(subcommand)] pub(crate) action: Option, - /// Find the desktop app by itself on every call (Edit › Preferences › AI Integrations › + /// Find the desktop app by itself on every call (Edit › Preferences › MCP › /// Let AI agents connect), with no port or token to configure #[arg(long)] pub(crate) live: bool, diff --git a/apps/photocraft-cli/tests/it/cli.rs b/apps/photocraft-cli/tests/it/cli.rs index 50db719d8f..1b8f4a29d4 100644 --- a/apps/photocraft-cli/tests/it/cli.rs +++ b/apps/photocraft-cli/tests/it/cli.rs @@ -2031,7 +2031,7 @@ fn info_detail_adds_text_runs_and_antialiasing() { } /// `mcp install --client json` prints the configuration MCP clients start `mcp --live` with; -/// Cursor's file gets the same entry, other servers kept (Preferences › AI Integrations). +/// Cursor's file gets the same entry, other servers kept (Preferences › MCP). #[test] fn mcp_install_writes_the_live_entry() { let home = tmp("mcp-install"); @@ -2110,7 +2110,7 @@ fn mcp_live_without_the_app_explains_what_to_do() { send(json!({"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"ui_inspect","arguments":{}}})); let r = recv(2); assert_eq!(r["result"]["isError"], true, "{r}"); - assert!(r["result"]["content"][0]["text"].as_str().unwrap().contains("AI Integrations"), "{r}"); + assert!(r["result"]["content"][0]["text"].as_str().unwrap().contains("MCP"), "{r}"); drop(stdin); let _ = child.kill(); let _ = child.wait(); diff --git a/apps/photocraft/src/agent_link.rs b/apps/photocraft/src/agent_link.rs index 2855d793cf..0ec73ed487 100644 --- a/apps/photocraft/src/agent_link.rs +++ b/apps/photocraft/src/agent_link.rs @@ -1,4 +1,4 @@ -//! Preferences › AI Integrations on the desktop: while *Let AI agents connect* is on, the app +//! Preferences › MCP on the desktop: while *Let AI agents connect* is on, the app //! serves the control protocol by itself (no `--control`) and publishes the connection file //! `photocraft-cli mcp --live` finds it by ([`photocraft_automation::agent_link`]). Turning it on //! or off, or changing the port or folders, applies at once. The token stays in the settings @@ -119,9 +119,14 @@ pub fn mcp_launch() -> Option { (appimage.is_some() || dir.join(agent_link::cli_file_name()).is_file()).then_some(launch) } -/// The "Add to …" buttons: add `mcp` to a client, or return the configuration to paste. +/// The "Add to …" buttons: add `mcp` to a client, or return the configuration to paste; and +/// "Copy Prompt for an Agent" (`prompt`): the text an agent with a terminal sets itself up from. pub fn clients(mcp: Option) -> AgentClientFn { Box::new(move |id: &str| { + if id == "prompt" { + let launch = mcp.as_ref().ok_or("photocraft-cli isn't installed beside PhotoCraft, so an agent can't start it")?; + return Ok(launch.agent_prompt()); + } let client = Client::parse(id).ok_or_else(|| format!("unknown MCP client `{id}`"))?; let launch = mcp.as_ref().ok_or_else(|| format!("photocraft-cli isn't installed beside PhotoCraft, so {} can't start it", client.name()))?; agent_link::install(client, launch, &ClientEnv::from_env()).map(|done| done.message(client)).map_err(|e| e.to_string()) @@ -261,5 +266,8 @@ mod tests { let mut add = clients(None); assert!(add("cursor").unwrap_err().contains("photocraft-cli")); assert!(add("nope").unwrap_err().contains("unknown")); + assert!(add("prompt").unwrap_err().contains("photocraft-cli")); + let mut add = clients(Some(McpLaunch::cli(Path::new("/x/photocraft-cli")))); + assert!(add("prompt").unwrap().contains("mcp --live")); } } diff --git a/apps/photocraft/src/control_server.rs b/apps/photocraft/src/control_server.rs index 678c57b358..b962b11ca6 100644 --- a/apps/photocraft/src/control_server.rs +++ b/apps/photocraft/src/control_server.rs @@ -1,7 +1,7 @@ //! Localhost JSON-lines control server (one request per line, one reply per line). //! Loopback only. This is the transport the MCP server will wrap. //! -//! `--control` starts it for the whole run ([`start`]); Preferences › AI Integrations starts and +//! `--control` starts it for the whole run ([`start`]); Preferences › MCP starts and //! stops it while the app runs ([`listen`], see `agent_link`). use std::io::{BufReader, Write}; diff --git a/apps/photocraft/src/main.rs b/apps/photocraft/src/main.rs index 420ce49051..1ad1c81bb2 100644 --- a/apps/photocraft/src/main.rs +++ b/apps/photocraft/src/main.rs @@ -95,7 +95,7 @@ fn custom_titlebar(prefs_file: Option<&std::path::Path>) -> bool { CUSTOM_TITLEBAR && !prefs.interface.system_title_bar } -/// Preferences › Integrations, read before the window opens the way [`custom_titlebar`] is: +/// Preferences › MCP, read before the window opens the way [`custom_titlebar`] is: /// whether agents may drive this launch at all, the port to listen on when no `--control` /// was given (0 = only with `--control`) and the automation folders used when no /// `--automation-read-root` / `--automation-write-root` was given. A missing or unreadable file @@ -147,7 +147,7 @@ fn integration_fields(section: &serde_json::Value, out: &mut photocraft_engine:: } /// The automation roots: `--automation-read-root` / `--automation-write-root` (or their -/// variables) win; a direction without one takes Preferences › Integrations' folder. A flag's +/// variables) win; a direction without one takes Preferences › MCP' folder. A flag's /// root that can't be opened stops the launch (exit status 2) as before. A preference's root that /// can't be opened, or isn't an absolute path (it would depend on the folder the app was started /// from), is left out, so that direction fails closed, and the warning says why: a folder moved @@ -177,7 +177,7 @@ fn automation_workspace( Ok(w) => workspace = w, Err(e) => { let which = if read { "Automation Read Folder" } else { "Automation Write Folder" }; - warnings.push(format!("Preferences › Integrations › {which} is not used: {e}")); + warnings.push(format!("Preferences › MCP › {which} is not used: {e}")); } } } @@ -192,7 +192,7 @@ fn control_port_for(cli: Option, prefs: &photocraft_engine::prefs::Integrat if !prefs.allow_agent_control { let warning = cli.map(|p| { format!( - "photocraft: Preferences › Integrations › Allow Agent Control is off: not listening on port {p} + "photocraft: Preferences › MCP › Allow Agent Control is off: not listening on port {p} " ) }); @@ -359,7 +359,7 @@ struct ControlNotice { } /// The `--control` server's port, token and workspace, when it is on (exits 2 on a bad -/// configuration). Preferences › Integrations' folders stand in for automation roots no flag +/// configuration). Preferences › MCP' folders stand in for automation roots no flag /// names. The server Preferences start (*Let AI agents connect*) is `agent_link`'s, not this. fn control_setup( cli_port: Option, @@ -369,7 +369,7 @@ fn control_setup( control_setup_in(services::config_dir(), &integrations(services::prefs_file().as_deref()), cli_port, auth, automation) } -/// [`control_setup`] with the settings folder and Preferences › Integrations given. +/// [`control_setup`] with the settings folder and Preferences › MCP given. fn control_setup_in( settings: Option, prefs: &photocraft_engine::prefs::Integrations, @@ -720,7 +720,7 @@ fn main() -> eframe::Result { log::warn!("couldn't remember GPU backend {}: {e}", b.name()); } }); - // Preferences › AI Integrations: agents connect without a terminal, unless the launch + // Preferences › MCP: agents connect without a terminal, unless the launch // flags (`--control`) manage the connection. let mcp = agent_link::mcp_launch(); app.agent_link.mcp_command = mcp.as_ref().map(photocraft_automation::agent_link::McpLaunch::shell_line); @@ -1197,7 +1197,7 @@ mod tests { } } - /// Preferences › Integrations' folders are the automation roots when no flag names one, and + /// Preferences › MCP' folders are the automation roots when no flag names one, and /// a flag wins over its preference, direction by direction. #[test] fn automation_folders_come_from_the_preferences_unless_a_flag_names_one() { diff --git a/book/src/automation/mcp.md b/book/src/automation/mcp.md index 4cfbb36310..9362d55376 100644 --- a/book/src/automation/mcp.md +++ b/book/src/automation/mcp.md @@ -4,7 +4,7 @@ - **Headless:** an in-process `Headless` session owns the engine and performs file I/O. - **Bridge:** `BridgeClient` forwards tools to a desktop application started with `photocraft --control `. -- **Live:** `photocraft-cli mcp --live` finds the desktop application through the connection file it publishes while Edit › Preferences › AI Integrations › *Let AI agents connect* is on, before every tool call; while the app is closed it starts it, serves a headless session, or reports an error, as chosen there. +- **Live:** `photocraft-cli mcp --live` finds the desktop application through the connection file it publishes while Edit › Preferences › MCP › *Let AI agents connect* is on, before every tool call; while the app is closed it starts it, serves a headless session, or reports an error, as chosen there. The simplest setup needs no terminal: turn on *Let AI agents connect* in PhotoCraft, then click *Add to Claude Desktop* (or Claude Code, or Cursor) in the same panel. See [`docs/mcp.md`](../../../docs/mcp.md#connecting-the-desktop-app-no-terminal). diff --git a/book/src/security/automation-security.md b/book/src/security/automation-security.md index 5698f77be7..c9157244ab 100644 --- a/book/src/security/automation-security.md +++ b/book/src/security/automation-security.md @@ -29,7 +29,7 @@ Automation is a privilege boundary because requests can cause filesystem access, Screenshots are decoded under separate dimension, pixel, and allocation ceilings before downscaling; the 5 MiB PNG limit applies to the returned image. - MCP normally uses stdio and can optionally bridge to loopback control TCP. -- Preferences › AI Integrations › *Let AI agents connect* (off by default) opens that loopback +- Preferences › MCP › *Let AI agents connect* (off by default) opens that loopback listener without launch flags. Its token is regenerated each time the connection starts and is kept in a user-only file; the published `agent-connection.json` holds the port and the token file's path, never the token. `photocraft-cli mcp --live` probes the port before sending the diff --git a/crates/automation/src/agent_link.rs b/crates/automation/src/agent_link.rs index dd6230e942..99a94e6f9c 100644 --- a/crates/automation/src/agent_link.rs +++ b/crates/automation/src/agent_link.rs @@ -170,7 +170,7 @@ fn read_small(path: &Path) -> Result, AutomationError> { } } -/// The AI Integrations preferences saved in `dir/preferences.json` (defaults when the file or +/// The MCP preferences saved in `dir/preferences.json` (defaults when the file or /// the section is missing or unreadable: the CLI must not fail over the app's settings). pub fn read_integrations(dir: &Path) -> Integrations { read_small(&dir.join("preferences.json")) @@ -218,6 +218,29 @@ impl McpLaunch { serde_json::to_string_pretty(&v).unwrap_or_default() } + /// A prompt to paste into an agent that has a terminal (Claude Code, Codex, Cursor's agent): + /// it registers PhotoCraft as its own MCP server, then checks the connection. Claude Desktop + /// has no terminal, so it is set up by [`install`] instead. Holds no port and no token. + pub fn agent_prompt(&self) -> String { + let line = self.shell_line(); + let config = self.config_json(); + format!( + "Please connect yourself to PhotoCraft, the image editor running on this computer, as an MCP server, then check that it works. + + 1. Register a stdio MCP server named \"{SERVER_NAME}\" that runs this command: + {line} + - Claude Code: claude mcp add --scope user {SERVER_NAME} -- {line} + - Codex: codex mcp add {SERVER_NAME} -- {line} + - Any other client: add this to its MCP configuration: + {config} + 2. Reload your MCP servers if your client needs that (or tell me to restart you). + 3. Call the {SERVER_NAME} tool `ui_inspect` and tell me which document is open. + + PhotoCraft must be running with Edit › Preferences › MCP › Let AI agents connect turned on. The command needs no port or token: it finds the app by itself on every call. +" + ) + } + /// The command line, quoted for a POSIX shell (Windows paths are double-quoted). pub fn shell_line(&self) -> String { std::iter::once(&self.command).chain(&self.args).map(|s| shell_quote(s)).collect::>().join(" ") @@ -767,6 +790,19 @@ mod tests { let _ = std::fs::remove_dir_all(&home); } + /// The prompt an agent pastes names the exact command, the Claude Code and Codex lines and a + /// configuration for any other client, and no token. + #[test] + fn the_agent_prompt_registers_the_live_command() { + let launch = McpLaunch::cli(Path::new("/x/photocraft-cli")); + let prompt = launch.agent_prompt(); + assert!(prompt.contains("claude mcp add --scope user photocraft -- /x/photocraft-cli mcp --live"), "{prompt}"); + assert!(prompt.contains("codex mcp add photocraft -- /x/photocraft-cli mcp --live"), "{prompt}"); + assert!(prompt.contains(&launch.config_json()), "{prompt}"); + assert!(prompt.contains("Edit › Preferences › MCP › Let AI agents connect"), "{prompt}"); + assert!(!prompt.contains(TOKEN_FILE) && !prompt.contains("token\":"), "{prompt}"); + } + #[test] fn claude_command_is_found_where_its_installers_put_it() { let home = temp("claude-find"); @@ -843,7 +879,7 @@ mod tests { assert!(install(Client::Cursor, &launch, &env).is_err(), "no home folder: an error, not a panic"); } - // ---- connection file (Preferences › Integrations) ---- + // ---- connection file (Preferences › MCP) ---- #[test] fn a_published_connection_reads_back_in_the_documented_shape() { diff --git a/crates/automation/src/lib.rs b/crates/automation/src/lib.rs index 47be6e0d8c..44e7d70ec0 100644 --- a/crates/automation/src/lib.rs +++ b/crates/automation/src/lib.rs @@ -12,7 +12,7 @@ //! control protocol's envelope, used by `photocraft-cli serve`. //! * [`files`]: open/save any supported format, `.pcraft` natively. //! * [`agent_link`] and [`live`]: connecting agents to the desktop app without a terminal -//! (Edit › Preferences › AI Integrations, `photocraft-cli mcp --live` and `mcp install`). +//! (Edit › Preferences › MCP, `photocraft-cli mcp --live` and `mcp install`). //! //! L6, no UI-toolkit dependencies. #![forbid(unsafe_code)] diff --git a/crates/automation/src/live.rs b/crates/automation/src/live.rs index 084c35719f..53501a97ba 100644 --- a/crates/automation/src/live.rs +++ b/crates/automation/src/live.rs @@ -3,7 +3,7 @@ //! quit or move to another port while the MCP client stays connected, and the MCP client's own //! start never opens a window. //! -//! While the app is closed, AI Integrations › When PhotoCraft Is Closed (or `--when-closed`) +//! While the app is closed, MCP › When PhotoCraft Is Closed (or `--when-closed`) //! decides: start the app and wait for it, serve a headless session with the folders chosen in //! the app (then for the rest of the MCP session, so documents don't move under the agent), or //! report an error that says what to do. @@ -122,7 +122,7 @@ impl Live { } if Instant::now() >= deadline { return Err(format!( - "PhotoCraft didn't accept agents within {} s of starting. If it's still opening, try again in a moment; otherwise check Edit › Preferences › AI Integrations.", + "PhotoCraft didn't accept agents within {} s of starting. If it's still opening, try again in a moment; otherwise check Edit › Preferences › MCP.", self.cfg.launch_timeout.as_secs() )); } @@ -160,7 +160,7 @@ fn closed(integrations: &Integrations) -> String { if integrations.connect_agents { "PhotoCraft isn't running: open it, then try again.".into() } else { - "PhotoCraft doesn't accept AI agents: open it, turn on Edit › Preferences › AI Integrations › Let AI agents connect, then try again.".into() + "PhotoCraft doesn't accept AI agents: open it, turn on Edit › Preferences › MCP › Let AI agents connect, then try again.".into() } } diff --git a/crates/automation/tests/mcp_live.rs b/crates/automation/tests/mcp_live.rs index 81909d783a..14daa48e1a 100644 --- a/crates/automation/tests/mcp_live.rs +++ b/crates/automation/tests/mcp_live.rs @@ -1,4 +1,4 @@ -//! `photocraft-cli mcp --live` (Preferences › AI Integrations): the MCP server finds the desktop +//! `photocraft-cli mcp --live` (Preferences › MCP): the MCP server finds the desktop //! app through its connection file before every call, follows it to a new port and token, and //! applies the closed-app choice (start it, headless, or an error) when no app answers. diff --git a/crates/engine/src/prefs.rs b/crates/engine/src/prefs.rs index ecc9c5c5e2..fb518a931a 100644 --- a/crates/engine/src/prefs.rs +++ b/crates/engine/src/prefs.rs @@ -121,7 +121,7 @@ choice!( RawDemosaic { Ahd = "ahd", Mhc = "mhc", Bilinear = "bilinear" } default Ahd ); choice!( - /// AI Integrations › When PhotoCraft Is Closed: what `photocraft-cli mcp --live` does when an + /// MCP › When PhotoCraft Is Closed: what `photocraft-cli mcp --live` does when an /// agent calls a tool and the app isn't running. WhenAppClosed { Launch = "launch", Headless = "headless", Error = "error" } default Launch ); diff --git a/crates/engine/src/prefs/cmds.rs b/crates/engine/src/prefs/cmds.rs index 564306ecf5..564566fb8c 100644 --- a/crates/engine/src/prefs/cmds.rs +++ b/crates/engine/src/prefs/cmds.rs @@ -189,7 +189,7 @@ pub fn specs() -> Vec { section!("edit.preferences.type", "Type…"), section!("edit.preferences.enhancedControls", "Enhanced Controls…"), section!("edit.preferences.rawDefaults", "RAW Defaults…"), - section!("edit.preferences.integrations", "Integrations…"), + section!("edit.preferences.integrations", "MCP…"), spec!( "edit.keyboardShortcuts", "Keyboard Shortcuts…", diff --git a/crates/engine/src/prefs/validate.rs b/crates/engine/src/prefs/validate.rs index 771382084c..d83a784720 100644 --- a/crates/engine/src/prefs/validate.rs +++ b/crates/engine/src/prefs/validate.rs @@ -25,7 +25,7 @@ pub const SECTIONS: [(&str, &str); 18] = [ ("type", "Type"), ("enhancedControls", "Enhanced Controls"), ("rawDefaults", "RAW Defaults"), - ("integrations", "Integrations"), + ("integrations", "MCP"), ]; /// Preferences that nothing reads yet, so Edit › Preferences doesn't show them: a control that diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index daa6caa8b2..220a4d6899 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -460,7 +460,7 @@ pub struct PhotocraftApp { /// The first digit of a two-digit opacity typed on the number keys (`opacity_keys`, #352). pub(crate) opacity_keys: opacity_keys::Pending, control_rx: Option>, - /// Preferences › AI Integrations: the agent connection's state (see [`Services::agent_link`]). + /// Preferences › MCP: the agent connection's state (see [`Services::agent_link`]). pub agent_link: AgentLinkStatus, /// `ui.screenshot` requests: bounded admission, a weak-slot callback per issuance, monotonic /// deadlines and a capture-time geometry epoch (see `screenshot.rs`). diff --git a/crates/ui-egui/src/menu_catalog.rs b/crates/ui-egui/src/menu_catalog.rs index d6db835eab..3e67428731 100644 --- a/crates/ui-egui/src/menu_catalog.rs +++ b/crates/ui-egui/src/menu_catalog.rs @@ -151,7 +151,7 @@ pub static CATALOG: &[(&[&str], &str, Option<&str>, &str)] = &[ (&["Edit"], "---", None, "---"), (&["Edit", "Preferences"], "General…", Some("Cmd+K"), "edit.preferences.general"), (&["Edit", "Preferences"], "---", None, "---"), - (&["Edit", "Preferences"], "AI Integrations…", None, "edit.preferences.integrations"), + (&["Edit", "Preferences"], "MCP…", None, "edit.preferences.integrations"), (&["Edit", "Preferences"], "Interface…", None, "edit.preferences.interface"), (&["Edit", "Preferences"], "Workspace…", None, "edit.preferences.workspace"), (&["Edit", "Preferences"], "Tools…", None, "edit.preferences.tools"), diff --git a/crates/ui-egui/src/preferences_submenu_tests.rs b/crates/ui-egui/src/preferences_submenu_tests.rs index 7050d385c0..7b8ef7b143 100644 --- a/crates/ui-egui/src/preferences_submenu_tests.rs +++ b/crates/ui-egui/src/preferences_submenu_tests.rs @@ -16,7 +16,7 @@ fn preferences_submenu_reads_in_the_reference_order_with_two_separators() { &labels[1..], [ "---", - "AI Integrations…", + "MCP…", "Interface…", "Workspace…", "Tools…", diff --git a/crates/ui-egui/src/prefs/prefs_ui.rs b/crates/ui-egui/src/prefs/prefs_ui.rs index 20d14e22d3..f7a567aa71 100644 --- a/crates/ui-egui/src/prefs/prefs_ui.rs +++ b/crates/ui-egui/src/prefs/prefs_ui.rs @@ -52,7 +52,7 @@ pub struct Runtime { show_rulers: Option, /// Tool options as last remembered in the preferences (see `tool_memory`). pub(crate) tool_options: Option, - /// AI Integrations settings the agent connection was last set up for (`agents::sync_agent_link`). + /// MCP settings the agent connection was last set up for (`agents::sync_agent_link`). agent_link: Option, pub(crate) selected_tool: Option, pub(crate) tool_colors: Option<[[[f32; 4]; 2]; 2]>, diff --git a/crates/ui-egui/src/prefs/prefs_ui/agents.rs b/crates/ui-egui/src/prefs/prefs_ui/agents.rs index 345cf63205..f998e7119b 100644 --- a/crates/ui-egui/src/prefs/prefs_ui/agents.rs +++ b/crates/ui-egui/src/prefs/prefs_ui/agents.rs @@ -1,4 +1,4 @@ -//! Preferences › AI Integrations: the agent connection (`integrations.connectAgents`), the folders +//! Preferences › MCP: the agent connection (`integrations.connectAgents`), the folders //! agents may use, what `photocraft-cli mcp --live` does while the app is closed, and the buttons //! that add PhotoCraft to MCP clients. Changes apply at once, without a restart. @@ -98,6 +98,14 @@ pub(super) fn integration_rows(ui: &mut egui::Ui, obj: &mut Map, } } }); + // Agents with a terminal (Claude Code, Codex, Cursor's agent) can set themselves up. + ui.add_space(4.0); + ui.horizontal_wrapped(|ui| { + if crate::widgets::secondary_button(ui, tl!("Copy Prompt for an Agent"), 120.0).clicked() { + f.insert("__agentAction".into(), json!("prompt")); + } + ui.label(RichText::new(tl!("Paste it into an agent with a terminal; it registers PhotoCraft by itself.")).color(t.text_faint)); + }); } if let Some(result) = f.get("__agentResult").and_then(Value::as_object) { let ok = result.get("ok").and_then(Value::as_bool) == Some(true); @@ -134,6 +142,10 @@ pub(super) fn agent_action(app: &mut PhotocraftApp, ctx: &egui::Context, f: &mut ctx.copy_text(text); json!({"ok": true, "message": tl!("Configuration copied.")}) } + Ok(text) if action == "prompt" => { + ctx.copy_text(text); + json!({"ok": true, "message": tl!("Prompt copied. Paste it into Claude Code, Codex or another agent with a terminal.")}) + } Ok(message) => json!({"ok": true, "message": message}), Err(e) => json!({"ok": false, "message": e}), }; diff --git a/crates/ui-egui/src/prefs/prefs_ui/agents_tests.rs b/crates/ui-egui/src/prefs/prefs_ui/agents_tests.rs index f618d8154a..9bf444a676 100644 --- a/crates/ui-egui/src/prefs/prefs_ui/agents_tests.rs +++ b/crates/ui-egui/src/prefs/prefs_ui/agents_tests.rs @@ -1,4 +1,4 @@ -//! Preferences › AI Integrations (`agents.rs`): the live agent connection and its buttons. +//! Preferences › MCP (`agents.rs`): the live agent connection and its buttons. use super::tests::app_with_store; use super::*; @@ -72,13 +72,18 @@ fn ai_integrations_offer_the_client_buttons_only_when_agents_may_connect() { 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"] { + for label in ["Add to Claude Desktop", "Add to Claude Code", "Add to Cursor", "Copy Configuration", "Copy Prompt for an Agent"] { 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"); + // The prompt for an agent with a terminal goes to the clipboard, with a note saying so. + h.get_by_label("Copy Prompt for an Agent").click(); + h.run_steps(3); + assert_eq!(*clicked.lock().unwrap(), ["cursor", "prompt"]); + assert!(h.query_by_label_contains("Prompt copied").is_some(), "the copy is confirmed"); // Unticked again: the buttons go. h.get_by_label("Let AI agents connect (MCP)").click(); h.run_steps(3); diff --git a/crates/ui-egui/src/prefs/prefs_ui/fields.rs b/crates/ui-egui/src/prefs/prefs_ui/fields.rs index f354115e40..6013b1f855 100644 --- a/crates/ui-egui/src/prefs/prefs_ui/fields.rs +++ b/crates/ui-egui/src/prefs/prefs_ui/fields.rs @@ -54,7 +54,7 @@ pub(super) fn humanize(key: &str) -> String { if key == "notificationAutoHide" { return "Auto Hide Notifications".into(); } - // AI Integrations: the labels its own rows show (`agents::integration_rows`), also for search. + // MCP: the labels its own rows show (`agents::integration_rows`), also for search. match key { "connectAgents" => return "Let AI agents connect (MCP)".into(), "readRoot" => return "Folder agents can open from".into(), @@ -136,7 +136,7 @@ pub(super) fn choice_label(v: &str) -> String { "ahd" => "AHD (adaptive homogeneity)".into(), "mhc" => "Malvar–He–Cutler".into(), "cpu" => "CPU (no GPU acceleration)".into(), - // AI Integrations › When PhotoCraft is closed. + // MCP › When PhotoCraft is closed. "launch" => "Open PhotoCraft".into(), "headless" => "Work without a window".into(), "error" => "Ask to open PhotoCraft".into(), diff --git a/crates/ui-egui/src/prefs/prefs_ui/tests.rs b/crates/ui-egui/src/prefs/prefs_ui/tests.rs index 215141ae39..4f0d1f1584 100644 --- a/crates/ui-egui/src/prefs/prefs_ui/tests.rs +++ b/crates/ui-egui/src/prefs/prefs_ui/tests.rs @@ -1582,7 +1582,7 @@ fn unimplemented_preferences_are_hidden_from_the_dialog() { assert!(has_visible_fields(&values, "fileHandling")); assert!(has_visible_fields(&values, "scratchDisks")); assert!(!prefs::is_hidden("scratchDisks.disks")); - // AI Integrations: the agent connection and its folders apply at once (`agents.rs`). + // MCP: the agent connection and its folders apply at once (`agents.rs`). assert!(has_visible_fields(&values, "integrations")); assert!(!prefs::is_hidden("integrations.allowAgentControl")); assert!(!prefs::is_hidden("integrations.controlPort")); diff --git a/crates/ui-egui/src/services.rs b/crates/ui-egui/src/services.rs index ca7cb7a47b..5ed287b336 100644 --- a/crates/ui-egui/src/services.rs +++ b/crates/ui-egui/src/services.rs @@ -344,7 +344,7 @@ pub type AutomationCommandFn = Box Result<(), String>>; pub type AutomationAuthorizeFn = fn(&str, &Value) -> photocraft_engine::Result<()>; /// The automation half of [`Services`]: what control and MCP requests may read, write and run. -/// Replaced as a whole when Preferences › AI Integrations starts the agent connection or +/// Replaced as a whole when Preferences › MCP starts the agent connection or /// changes its folders ([`Services::set_automation`]). #[derive(Default)] pub struct AutomationServices { @@ -356,7 +356,7 @@ pub struct AutomationServices { pub authorize: Option, } -/// Preferences › AI Integrations: the agent connection as the dialog and `ui.inspect` show it. +/// Preferences › MCP: the agent connection as the dialog and `ui.inspect` show it. #[derive(Clone, Debug, Default, PartialEq, Eq, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct AgentLinkStatus { @@ -370,7 +370,7 @@ pub struct AgentLinkStatus { pub mcp_command: Option, } -/// What [`Services::agent_link`] did after the AI Integrations settings changed. +/// What [`Services::agent_link`] did after the MCP settings changed. #[derive(Default)] pub struct AgentLink { /// Requests from agents on a connection that just started (or moved to another port). @@ -382,7 +382,7 @@ pub struct AgentLink { pub status: AgentLinkStatus, } -/// Starts, moves or stops the agent connection to match Preferences › AI Integrations. +/// Starts, moves or stops the agent connection to match Preferences › MCP. pub type AgentLinkFn = Box AgentLink>; /// Adds PhotoCraft to an MCP client (`claude-desktop`, `claude-code`, `cursor`), returning what /// was done, or returns the configuration to paste into any client (`json`). @@ -582,10 +582,10 @@ pub struct Services { /// each step of `actions.play`. Installed on the session only while a control request or /// an automation-driven [`PhotocraftApp::run`] runs, so a local play of a recorded `file.*` step still works. pub automation_authorize: Option, - /// Preferences › AI Integrations (desktop): starts, moves or stops the agent connection when + /// Preferences › MCP (desktop): starts, moves or stops the agent connection when /// its settings change. `None` on the web, and when `--control` manages the connection. pub agent_link: Option, - /// Preferences › AI Integrations' buttons that add PhotoCraft to MCP clients (desktop). + /// Preferences › MCP' buttons that add PhotoCraft to MCP clients (desktop). pub agent_clients: Option, /// Encode an RGBA8 image as PNG (used for screenshots and `ui.render`). pub encode_png: Option, diff --git a/docs/control-protocol.md b/docs/control-protocol.md index ea4c9236a2..c3ed0c2e4f 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -17,9 +17,9 @@ photocraft --control 7878 --control-token-file /private/path/photocraft-control. If the file does not exist, PhotoCraft creates it with a fresh 256-bit token. On Unix the new file is mode `0600`; on Windows, protect it with an appropriate user-only ACL. An existing file is reused. If neither a token nor token file is configured, PhotoCraft generates a token for that launch and writes it to standard error. `PHOTOCRAFT_CONTROL_TOKEN` and `PHOTOCRAFT_CONTROL_TOKEN_FILE` are the environment-variable equivalents. A flag wins over its variable and an empty variable counts as unset; with `--control` (or `PHOTOCRAFT_CONTROL_PORT`), a token together with a token file, from flags or variables, is a usage error (exit status 2). Without it no token is read, so the pair is ignored. -### Without `--control`: Preferences › Integrations +### Without `--control`: Preferences › MCP -An app started from the Dock, the Start menu or a file manager has no command line. Edit › Preferences › AI Integrations starts and stops the control server while the app runs: turning *Let AI agents connect* on or off, or changing its port or folders, applies at once, with no restart. +An app started from the Dock, the Start menu or a file manager has no command line. Edit › Preferences › MCP starts and stops the control server while the app runs: turning *Let AI agents connect* on or off, or changing its port or folders, applies at once, with no restart. | Preference | What it does | |---|---| @@ -418,7 +418,7 @@ magenta alignment lines. `ui.pointer` drives the same code, so agents get identi - **Headless** (`photocraft-cli mcp`): an in-process `photocraft_engine::Session`. There is no window. CPU composition is the default; `--gpu` or `PHOTOCRAFT_GPU=1` enables optional GPU rendering with automatic CPU fallback. - **Bridge** (`photocraft-cli mcp --bridge 127.0.0.1:7878 --control-token-file `): every tool is forwarded to a running `photocraft --control 7878 --control-token-file ` over this protocol, so agents see and drive the live app. Explicit `--gpu` / `--no-gpu` flags are rejected with a usage error because the desktop controls rendering; `PHOTOCRAFT_GPU` is ignored in bridge mode. `--bridge 7878` is short for `--bridge 127.0.0.1:7878`. With no `--bridge`, `PHOTOCRAFT_CONTROL_PORT` selects the bridge port (`127.0.0.1:`), and the CLI says so on standard error; with neither (or the variable empty), the MCP runs headless. A value that is not a port is a usage error naming the variable. `--automation-read-root` or `--automation-write-root` with the variable set is a usage error, since the bridge would drop the roots. -- **Live** (`photocraft-cli mcp --live`): the bridge, with the address and token read before every tool call from `agent-connection.json` in the app's settings folder. The app publishes that file while Edit › Preferences › AI Integrations › *Let AI agents connect* is on (not with `--control`), and removes it when the connection stops; a file left by a crash fails the connection probe and counts as no app. See [MCP conventions](mcp.md#connecting-the-desktop-app-no-terminal). +- **Live** (`photocraft-cli mcp --live`): the bridge, with the address and token read before every tool call from `agent-connection.json` in the app's settings folder. The app publishes that file while Edit › Preferences › MCP › *Let AI agents connect* is on (not with `--control`), and removes it when the connection stops; a file left by a crash fails the connection probe and counts as no app. See [MCP conventions](mcp.md#connecting-the-desktop-app-no-terminal). `ui.inspect` reports the connection as `agentLink`: `port` while agents can connect, `launchFlags` when `--control` manages it, `error`, and `mcpCommand` (how MCP clients start the CLI). @@ -488,7 +488,7 @@ One explicit write-root flag overrides `PHOTOCRAFT_AUTOMATION_WRITE_ROOT`. These variables are not supported by headless `photocraft-cli mcp` or `serve`; supply flags explicitly. In MCP bridge mode, configure roots on the desktop process. Supplying root flags to `photocraft-cli mcp --bridge` is a usage error; a bridge client cannot grant filesystem access. -With *Let AI agents connect*, the folders chosen in Preferences › AI Integrations (`readRoot` / +With *Let AI agents connect*, the folders chosen in Preferences › MCP (`readRoot` / `writeRoot`) are the agents' roots; `mcp --live` uses them for a headless session only when the app's *When PhotoCraft is closed* choice (or `--when-closed headless`) asks for one. diff --git a/docs/development.md b/docs/development.md index d091e49d98..cf1a1214ad 100644 --- a/docs/development.md +++ b/docs/development.md @@ -324,7 +324,7 @@ At startup the desktop lists recovery metadata, then decodes one document at a t - **Headless:** `photocraft-cli mcp --automation-read-root --automation-read-root --automation-write-root `. It drives an in-process engine session with ordered read directories and one write directory. - **Live app:** start `photocraft --control 7878 --control-token-file --automation-read-root --automation-read-root --automation-write-root `, then run `photocraft-cli mcp --bridge 127.0.0.1:7878 --control-token-file `. The desktop process owns the roots; root flags on the bridging CLI are a usage error. See `docs/control-protocol.md#mcp-bridge`. -- **Live app, no flags:** turn on Edit › Preferences › AI Integrations › Let AI agents connect, then point the MCP client at `photocraft-cli mcp --live` (the panel's buttons, or `photocraft-cli mcp install --client `, do it). The app publishes its port and token file in `agent-connection.json` in the settings folder; `--live` reads it on every call. See [MCP conventions](mcp.md#connecting-the-desktop-app-no-terminal). Test it against a scratch settings folder with `PHOTOCRAFT_CONFIG_DIR`, which both the app and the CLI honour. +- **Live app, no flags:** turn on Edit › Preferences › MCP › Let AI agents connect, then point the MCP client at `photocraft-cli mcp --live` (the panel's buttons, or `photocraft-cli mcp install --client `, do it). The app publishes its port and token file in `agent-connection.json` in the settings folder; `--live` reads it on every call. See [MCP conventions](mcp.md#connecting-the-desktop-app-no-terminal). Test it against a scratch settings folder with `PHOTOCRAFT_CONFIG_DIR`, which both the app and the CLI honour. For headless MCP clients, pass absolute paths to deliberately chosen trusted workspace directories in the launch arguments. Desktop `PHOTOCRAFT_AUTOMATION_READ_ROOT` and `PHOTOCRAFT_AUTOMATION_WRITE_ROOT` environment variables do **not** grant headless CLI access. Omitting a root flag deliberately denies that direction of access. diff --git a/docs/mcp.md b/docs/mcp.md index 8ba0de9057..b8ddbf6ebb 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2,7 +2,7 @@ ## Connecting the desktop app (no terminal) -1. In PhotoCraft, open **Edit › Preferences › AI Integrations** and turn on **Let AI agents +1. In PhotoCraft, open **Edit › Preferences › MCP** and turn on **Let AI agents connect (MCP)**. Optionally choose the folders agents can open from and save to, and what 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**. diff --git a/docs/roadmap.md b/docs/roadmap.md index e2c1d6bc0e..e0b6e3516a 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -1,6 +1,6 @@ # Roadmap -> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-14 · **Change:** minor (M11: the desktop app connects to MCP clients from Preferences › AI Integrations, no terminal; alpha gate, focus and estimates unchanged) · **Target:** Adobe Photoshop 2026 +> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-11-12 · **Change:** minor (M11: the desktop app connects to MCP clients from Edit › Preferences › MCP, no terminal, no restart; alpha gate, focus and estimates unchanged) · **Target:** Adobe Photoshop 2026 - UI.5: Panels can detach, join other tab groups, split, resize and redock through shared docking transactions. Custom layouts persist with workspaces, respect workspace locking, and retain collapse flags for intact native groups. @@ -116,7 +116,7 @@ Each milestone has a **definition of done (DoD)** and must leave `main` green on | Date | Change | Summary | |---|---|---| -| 2026-10-14 | minor | M11: AI Integrations connects MCP clients to the running app without a terminal; milestones, alpha gate and estimates unchanged | +| 2026-11-12 | minor | M11: Edit › Preferences › MCP connects MCP clients to the running app without a terminal or restart; milestones, alpha gate and estimates unchanged | | 2026-10-11 | minor | Linked adaptive Unsharp Mask performance and quality evidence; milestones, alpha gate and estimates unchanged | | 2026-10-10 | minor | Photomerge is implemented; real-world quality validation remains open | | 2026-10-10 | minor | Alpha gate table (core-workflow gate): passes, stage stays alpha | diff --git a/packaging/macos/package.sh b/packaging/macos/package.sh index ca64f30e82..b3e8a0a6f2 100755 --- a/packaging/macos/package.sh +++ b/packaging/macos/package.sh @@ -120,7 +120,7 @@ echo "==> assembling $APP" mkdir -p "$APP/Contents/MacOS" "$APP/Contents/Resources" # Executable and icon carry the display name (CFBundleExecutable / CFBundleIconFile). cp "$WORK/bin/photocraft" "$APP/Contents/MacOS/PhotoCraft" -# The CLI too, beside the app: Preferences › AI Integrations points MCP clients at it +# The CLI too, beside the app: Preferences › MCP points MCP clients at it # (`photocraft-cli mcp --live`), and it starts the app when an agent needs it. cp "$WORK/bin/photocraft-cli" "$APP/Contents/MacOS/photocraft-cli" cp "$ROOT/assets/app-icon/photocraft.icns" "$APP/Contents/Resources/PhotoCraft.icns" diff --git a/scorecard/automation.toml b/scorecard/automation.toml index e984199dbb..35c649717b 100644 --- a/scorecard/automation.toml +++ b/scorecard/automation.toml @@ -85,4 +85,4 @@ note = "automation/tests/it/agent_tasks.rs runs 10 workflows over MCP" id = "AUTO-MCP-LIVE" target = "Connect an MCP client to the running app without a terminal (no flags, ports or tokens to copy)" status = "done" -note = "2026-10-14: Preferences › AI Integrations › Let AI agents connect starts the loopback control server at runtime and publishes agent-connection.json; photocraft-cli mcp --live finds the app on every call (launch / headless / error while it is closed); Add to Claude Desktop / Claude Code / Cursor and mcp install --client. automation/tests/mcp_live.rs, apps/photocraft/src/agent_link.rs tests" +note = "2026-10-14: Preferences › MCP › Let AI agents connect starts the loopback control server at runtime and publishes agent-connection.json; photocraft-cli mcp --live finds the app on every call (launch / headless / error while it is closed); Add to Claude Desktop / Claude Code / Cursor and mcp install --client. automation/tests/mcp_live.rs, apps/photocraft/src/agent_link.rs tests" From 9dd0364db2275e55bc9f561f0b7f38d474162167 Mon Sep 17 00:00:00 2001 From: David Mann Date: Thu, 12 Nov 2026 02:59:23 +0100 Subject: [PATCH 09/28] Batch: regenerate docs/scorecard.md (AUTO-MCP-LIVE, Integrations prefs) Co-Authored-By: Claude Opus 5.5 --- docs/scorecard.md | 7 ++++--- scorecard/automation.toml | 2 +- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/docs/scorecard.md b/docs/scorecard.md index 89c462189d..b6d496c06d 100644 --- a/docs/scorecard.md +++ b/docs/scorecard.md @@ -9,9 +9,9 @@ Generated by `cargo xtask scorecard` from `perf/budgets.toml`, `perf/baseline.js | [Performance](#performance) | 3 | 22 | 54 | 88 scenarios: 3 within budget, 22 over budget or failing, 9 tracked only, 50 not run, 4 not measurable yet (baseline 2026-10-05) | | [File compatibility](#file-compatibility) | 11 | 14 | 2 | io corpus: oracle ≥ 148/170, round trip ≥ 169/170; psd-tools corpus: oracle ≥ 249/309, round trip ≥ 308/309; photoshop oracles: oracle ≥ 190/258, round trip ≥ 258/258 | | [Tools](#tools) | 36 | 9 | 0 | | -| [Workspace and UI](#workspace-and-ui) | 15 | 6 | 2 | settings that do nothing: 8 of 201 (target 0) | +| [Workspace and UI](#workspace-and-ui) | 15 | 6 | 2 | settings that do nothing: 8 of 203 (target 0) | | [Type](#type) | 5 | 5 | 0 | | -| [Automation](#automation) | 5 | 4 | 2 | 664 of 664 menu items live (100.0%) | +| [Automation](#automation) | 6 | 4 | 2 | 664 of 664 menu items live (100.0%) | | [Reliability](#reliability) | 5 | 2 | 0 | never-crash lints on 29 of 29 crates; panic_hunt present | | [Distribution](#distribution) | 5 | 5 | 1 | | | [Open bugs](#open-bugs) | 31 | 1 | 0 | | @@ -212,7 +212,7 @@ Corpus floors (`crates/io/tests/it/corpus.rs`): the enforced minimums; the corpu ## Workspace and UI -**Settings that do nothing: 8 of 201** (target 0, #204). Counted by the prefs audit (`xtask/src/scorecard.rs`): a `Preferences` field counts as read when code outside the prefs model (`prefs.rs` except its `impl Session` blocks; tests excluded; the schema-driven dialog never names a field) accesses `section.field`, or `.section` and `.field` in the same file, or calls a section method that reads `self.field`. It is a heuristic lower bound: a generic name can look read when it isn't. +**Settings that do nothing: 8 of 203** (target 0, #204). Counted by the prefs audit (`xtask/src/scorecard.rs`): a `Preferences` field counts as read when code outside the prefs model (`prefs.rs` except its `impl Session` blocks; tests excluded; the schema-driven dialog never names a field) accesses `section.field`, or `.section` and `.field` in the same file, or calls a section method that reads `self.field`. It is a heuristic lower bound: a generic name can look read when it isn't. Unread: `general.color_picker`, `workspace.auto_show_hidden_panels`, `workspace.enable_floating_document_window_docking`, `performance.legacy_compositing`, `plug_ins.show_extension_panels`, `plug_ins.allow_scripts_to_connect`, `type_.text_engine`, `enhanced_controls.scrubby_slider_acceleration`. @@ -274,6 +274,7 @@ Menu wiring (`docs/parity-checklist.md`): 664 of 664 menu items live (100.0%). T | AUTO-219-8 | xtask check that every panel button routes through a command id | partial | [#219](https://github.com/storytold/photocraft/issues/219) | cargo xtask panel-commands (run by xtask ci and CI) fails on a shell click handler that changes the document or session directly; 1 allowlisted function left (panels/color.rs color_field assigns the foreground/background colour instead of tools.setColors) | | AUTO-219-9 | Headless commands for in-canvas type editing, Liquify/Puppet strokes, transform handles | done | [#219](https://github.com/storytold/photocraft/issues/219) | type.hitTest, type.caret, type.navigate; filter.liquify strokes, edit.puppetWarp pins, type.edit, edit.transform | | AUTO-219-10 | Agent acceptance suite grown to 30-50 workflows | partial | [#219](https://github.com/storytold/photocraft/issues/219) | automation/tests/it/agent_tasks.rs runs 10 workflows over MCP | +| AUTO-MCP-LIVE | Connect an MCP client to the running app without a terminal (no flags, ports or tokens to copy) | done | | 2026-11-12 (#5525, #11363): Edit › Preferences › MCP › Let AI agents connect starts and stops the loopback control server while the app runs (no restart) and publishes agent-connection.json; photocraft-cli mcp --live finds the app on every call (launch / headless / error while it is closed); Add to Claude Desktop / Claude Code / Cursor, mcp install --client, and Copy Prompt for an Agent. automation/tests/mcp_live.rs, apps/photocraft/src/agent_link.rs tests | ## Reliability diff --git a/scorecard/automation.toml b/scorecard/automation.toml index 35c649717b..2816d95346 100644 --- a/scorecard/automation.toml +++ b/scorecard/automation.toml @@ -85,4 +85,4 @@ note = "automation/tests/it/agent_tasks.rs runs 10 workflows over MCP" id = "AUTO-MCP-LIVE" target = "Connect an MCP client to the running app without a terminal (no flags, ports or tokens to copy)" status = "done" -note = "2026-10-14: Preferences › MCP › Let AI agents connect starts the loopback control server at runtime and publishes agent-connection.json; photocraft-cli mcp --live finds the app on every call (launch / headless / error while it is closed); Add to Claude Desktop / Claude Code / Cursor and mcp install --client. automation/tests/mcp_live.rs, apps/photocraft/src/agent_link.rs tests" +note = "2026-11-12 (#5525, #11363): Edit › Preferences › MCP › Let AI agents connect starts and stops the loopback control server while the app runs (no restart) and publishes agent-connection.json; photocraft-cli mcp --live finds the app on every call (launch / headless / error while it is closed); Add to Claude Desktop / Claude Code / Cursor, mcp install --client, and Copy Prompt for an Agent. automation/tests/mcp_live.rs, apps/photocraft/src/agent_link.rs tests" From 9ac35b7e7672db9a14998e33eb498bdff88e4726 Mon Sep 17 00:00:00 2001 From: David Mann Date: Thu, 12 Nov 2026 03:23:22 +0100 Subject: [PATCH 10/28] Batch: CodeRabbit findings on the MCP connection - Allow Agent Control off refuses the Preferences connection too, as it refuses --control. - A connection that is on but failed to start (taken port) is tried again every 5 s. - Listening::drop waits for the accept loop, so the port is free when it returns. - The session's automation gate follows the live policy (actions agents record). - The folder picker answers the Preferences dialog that opened it. - One controlPort migration (engine::prefs::migrate_integrations) for the app, its launch read and photocraft-cli mcp --live. - --live: a batch stops when the app changes under it; a waited job is cancelled where it started; the bridge is keyed by pid too. - mcp --live ignores an exported PHOTOCRAFT_CONTROL_PORT and refuses --gpu/--no-gpu. - Claude Code: add first, replace an existing entry only when it exists, and stop a `claude` that hangs after 20 s. - Book: the token survives restarts; the challenge handshake, not the probe, protects it. Co-Authored-By: Claude Opus 5.5 --- apps/photocraft-cli/src/args.rs | 17 +++- apps/photocraft-cli/tests/it/cli.rs | 5 +- apps/photocraft/src/agent_link.rs | 18 ++++ apps/photocraft/src/control_server.rs | 22 +++-- apps/photocraft/src/main.rs | 17 ++-- book/src/security/automation-security.md | 13 ++- crates/automation/src/agent_link.rs | 94 +++++++++++++++++-- crates/automation/src/live.rs | 5 +- crates/automation/src/server.rs | 27 ++++++ crates/automation/src/server/progress.rs | 31 +++--- crates/engine/src/prefs.rs | 22 +++-- crates/ui-egui/src/dialogs.rs | 2 +- crates/ui-egui/src/prefs/prefs_ui.rs | 3 + crates/ui-egui/src/prefs/prefs_ui/agents.rs | 25 ++++- .../src/prefs/prefs_ui/agents_tests.rs | 41 ++++++++ crates/ui-egui/src/prefs/prefs_ui/fields.rs | 6 +- 16 files changed, 278 insertions(+), 70 deletions(-) diff --git a/apps/photocraft-cli/src/args.rs b/apps/photocraft-cli/src/args.rs index 76905d2584..8b850e2037 100644 --- a/apps/photocraft-cli/src/args.rs +++ b/apps/photocraft-cli/src/args.rs @@ -393,13 +393,16 @@ enum ServerOptionError { /// `--live` finds the app's port and token by itself. #[error("--live finds the app by itself; {0} is for --bridge")] LiveBridge(&'static str), + /// `--live` drives the app, which decides on rendering. + #[error("configure rendering on the desktop app; --gpu and --no-gpu require headless MCP mode, not --live")] + LiveGpu, } impl ServerOptionError { fn into_clap(self, cmd: &mut clap::Command) -> clap::Error { let kind = match self { Self::BridgeVar(_) | Self::GpuVar(_) => ErrorKind::ValueValidation, - Self::BridgeRoots | Self::BridgeGpu | Self::LiveBridge(_) => ErrorKind::ArgumentConflict, + Self::BridgeRoots | Self::BridgeGpu | Self::LiveBridge(_) | Self::LiveGpu => ErrorKind::ArgumentConflict, Self::NeedsTransport { .. } => ErrorKind::MissingRequiredArgument, }; cmd.error(kind, self) @@ -511,6 +514,11 @@ fn steps(m: &ArgMatches) -> Vec { /// stray.psd --help`): clap reports the mistake first. pub(crate) fn parse(args: &[OsString]) -> Result { let mut cmd = Cli::command().mut_subcommands(|sub| sub.mut_args(blank_env_is_unset)); + // `mcp --live` finds the app itself: a PHOTOCRAFT_CONTROL_PORT exported for another tool is + // not read, so a value it couldn't use anyway doesn't stop it. + if args.first().is_some_and(|a| a == "mcp") && args.iter().take_while(|a| *a != "--").any(|a| a == "--live") { + cmd = cmd.mut_subcommand("mcp", |sub| sub.mut_arg("bridge", |arg| arg.env(None::<&str>))); + } let argv = std::iter::once(OsString::from("photocraft-cli")).chain(args.iter().cloned()); let matches = match cmd.try_get_matches_from_mut(argv) { Err(e) if args.iter().take_while(|a| *a != "--").any(|a| *a == "--help" || *a == "-h") => { @@ -538,6 +546,13 @@ pub(crate) fn parse(args: &[OsString]) -> Result { return Err(ServerOptionError::LiveBridge(flag).into_clap(&mut cmd)); } } + // A headless session `--live` falls back to takes the app's rendering, not these. + if m.value_source("gpu") == Some(ValueSource::CommandLine) || m.value_source("no_gpu") == Some(ValueSource::CommandLine) { + if let Some(sub) = cmd.find_subcommand_mut(name) { + return Err(ServerOptionError::LiveGpu.into_clap(sub)); + } + return Err(ServerOptionError::LiveGpu.into_clap(&mut cmd)); + } a.bridge = None; return Ok(cli); } diff --git a/apps/photocraft-cli/tests/it/cli.rs b/apps/photocraft-cli/tests/it/cli.rs index 1b8f4a29d4..f48b7989c1 100644 --- a/apps/photocraft-cli/tests/it/cli.rs +++ b/apps/photocraft-cli/tests/it/cli.rs @@ -2067,6 +2067,7 @@ fn mcp_live_and_install_reject_mismatched_flags() { (&["mcp", "--live", "--bridge", "127.0.0.1:1"], "--bridge"), (&["mcp", "--live", "--control-token-file", "t"], "--control-token-file"), (&["mcp", "--live", "--when-closed", "sometimes"], "sometimes"), + (&["mcp", "--live", "--gpu"], "--gpu"), ] { let o = bin().args(args).stdin(Stdio::null()).output().unwrap(); let err = String::from_utf8_lossy(&o.stderr); @@ -2075,13 +2076,15 @@ fn mcp_live_and_install_reject_mismatched_flags() { } } -/// `mcp --live` serves MCP without the app; a tool call says how to connect it. +/// `mcp --live` serves MCP without the app; a tool call says how to connect it. A +/// PHOTOCRAFT_CONTROL_PORT exported for another tool (here not even a port) is not read. #[test] fn mcp_live_without_the_app_explains_what_to_do() { let dir = tmp("mcp-live"); let mut child = bin() .args(["mcp", "--live", "--when-closed", "error"]) .env("PHOTOCRAFT_CONFIG_DIR", &dir) + .env("PHOTOCRAFT_CONTROL_PORT", "not-a-port") .stdin(Stdio::piped()) .stdout(Stdio::piped()) .stderr(Stdio::null()) diff --git a/apps/photocraft/src/agent_link.rs b/apps/photocraft/src/agent_link.rs index 0ec73ed487..267b678e08 100644 --- a/apps/photocraft/src/agent_link.rs +++ b/apps/photocraft/src/agent_link.rs @@ -63,6 +63,12 @@ fn apply(running: &mut Option, dir: Option<&Path>, integrations: &Integ out.stopped = running.take().is_some(); return out; } + // Allow Agent Control off refuses every control server, this one as `--control`. + if !integrations.allow_agent_control { + out.stopped = running.take().is_some(); + out.status.error = Some("Agents can't connect: Allow Agent Control is off in the preferences file.".into()); + return out; + } let Some(dir) = dir else { out.stopped = running.take().is_some(); out.status.error = Some("Agents can't connect: PhotoCraft has no settings folder (no home folder).".into()); @@ -254,6 +260,18 @@ mod tests { let _ = std::fs::remove_dir_all(&dir); } + /// Allow Agent Control off (in the file; the dialog doesn't show it) refuses this server too. + #[test] + fn allow_agent_control_off_keeps_agents_out() { + let dir = temp(); + let mut link = service(Some(dir.clone()), None); + let r = link(&Integrations { allow_agent_control: false, ..on(0) }, &egui::Context::default()); + assert!(r.requests.is_none() && r.status.port.is_none() && r.automation.command.is_none()); + assert!(r.status.error.as_deref().is_some_and(|e| e.contains("Allow Agent Control")), "{:?}", r.status.error); + assert_eq!(agent_link::read_connection(&dir).unwrap(), None); + let _ = std::fs::remove_dir_all(&dir); + } + #[test] fn no_settings_folder_is_an_error_not_a_panic() { let mut link = service(None, None); diff --git a/apps/photocraft/src/control_server.rs b/apps/photocraft/src/control_server.rs index b962b11ca6..75bb02f480 100644 --- a/apps/photocraft/src/control_server.rs +++ b/apps/photocraft/src/control_server.rs @@ -36,13 +36,19 @@ pub struct Listening { /// The bound port (the one the system picked for port 0). pub port: u16, stop: Arc, + accept: Option>, } impl Drop for Listening { fn drop(&mut self) { self.stop.store(true, Ordering::Release); - // Wake the accept loop so it sees the flag and closes the listener. - let _ = TcpStream::connect_timeout(&std::net::SocketAddr::from(([127, 0, 0, 1], self.port)), Duration::from_millis(500)); + // Wake the accept loop so it sees the flag and closes the listener, and wait for that, so + // the port is free when this returns (a restart on the same port binds it again at once). + // Without a wake-up the loop would block in `accept`: then don't wait. + let woke = TcpStream::connect_timeout(&std::net::SocketAddr::from(([127, 0, 0, 1], self.port)), Duration::from_millis(500)).is_ok(); + if woke && let Some(accept) = self.accept.take() { + let _ = accept.join(); + } } } @@ -54,8 +60,8 @@ pub fn listen(port: u16, token: String, ctx: egui::Context) -> std::io::Result<( let port = listener.local_addr()?.port(); let stop = Arc::new(AtomicBool::new(false)); let stopped = stop.clone(); - std::thread::Builder::new().name("control server".into()).spawn(move || accept(listener, token, tx, ctx, Some(stopped)))?; - Ok((rx, Listening { port, stop })) + let accept = std::thread::Builder::new().name("control server".into()).spawn(move || accept(listener, token, tx, ctx, Some(stopped)))?; + Ok((rx, Listening { port, stop, accept: Some(accept) })) } /// Accept connections on `listener` and serve each on its own thread, until `stop` is set (never, @@ -203,12 +209,8 @@ mod tests { assert_eq!(serde_json::from_str::(&line).unwrap()["result"], "pong"); handler.join().unwrap(); drop(server); - // The listener closes once the accept loop has seen the stop flag. - let deadline = Instant::now() + Duration::from_secs(5); - while TcpStream::connect_timeout(&std::net::SocketAddr::from(([127, 0, 0, 1], port)), Duration::from_millis(200)).is_ok() { - assert!(Instant::now() < deadline, "port {port} still accepts connections after stop"); - std::thread::sleep(Duration::from_millis(20)); - } + // The listener is closed when the drop returns: the same port binds again at once. + TcpListener::bind(("127.0.0.1", port)).expect("the port is free after the drop"); } #[test] fn port_zero_logs_the_bound_port() { diff --git a/apps/photocraft/src/main.rs b/apps/photocraft/src/main.rs index 1ad1c81bb2..0315a40302 100644 --- a/apps/photocraft/src/main.rs +++ b/apps/photocraft/src/main.rs @@ -108,19 +108,18 @@ fn integrations(prefs_file: Option<&std::path::Path>) -> photocraft_engine::pref use serde_json::Value; let mut out = photocraft_engine::prefs::Preferences::default().integrations; let file: Option = prefs_file.and_then(|p| std::fs::read_to_string(p).ok()).and_then(|t| serde_json::from_str(&t).ok()); - let Some(section) = file.as_ref().and_then(|v| v.get("integrations")) else { + let Some(mut section) = file.as_ref().and_then(|v| v.get("integrations")).cloned() else { return out; }; - if let Ok(whole) = serde_json::from_value(section.clone()) { - out = whole; - } else { - integration_fields(section, &mut out); - } // As the engine's load does: a Control Port from before *Let AI agents connect* keeps it on. - if section.as_object().is_some_and(|o| !o.contains_key("connectAgents")) && (1..=65535).contains(&out.control_port) { - out.connect_agents = true; + photocraft_engine::prefs::migrate_integrations(&mut section); + match serde_json::from_value(section.clone()) { + Ok(whole) => whole, + Err(_) => { + integration_fields(§ion, &mut out); + out + } } - out } /// [`integrations`]' value-by-value read of a section that doesn't read as a whole. diff --git a/book/src/security/automation-security.md b/book/src/security/automation-security.md index c9157244ab..634b16d893 100644 --- a/book/src/security/automation-security.md +++ b/book/src/security/automation-security.md @@ -29,11 +29,14 @@ Automation is a privilege boundary because requests can cause filesystem access, Screenshots are decoded under separate dimension, pixel, and allocation ceilings before downscaling; the 5 MiB PNG limit applies to the returned image. - MCP normally uses stdio and can optionally bridge to loopback control TCP. -- Preferences › MCP › *Let AI agents connect* (off by default) opens that loopback - listener without launch flags. Its token is regenerated each time the connection starts and is - kept in a user-only file; the published `agent-connection.json` holds the port and the token - file's path, never the token. `photocraft-cli mcp --live` probes the port before sending the - token, and a file left by a crash fails that probe. +- Edit › Preferences › MCP › *Let AI agents connect* (off by default) opens that loopback + listener without launch flags. Its token is kept in a user-only file in the settings folder + (`agent-control.token`) and stays the same across restarts and port changes: restarting does + not revoke it. To revoke an exposed token, delete that file; the next start creates a new one. + The published `agent-connection.json` holds the port and the token file's path, never the + token. `photocraft-cli mcp --live` authenticates with the challenge handshake, so the token + itself is never sent: the listener must first prove it holds the token, and a stale file whose + port another program took fails that check before the client reveals anything. - The bridge and UI request paths use timeouts. - Engine commands are expected to reject invalid parameters without panicking. - Remote filesystem methods use separately granted read and write directory capabilities. diff --git a/crates/automation/src/agent_link.rs b/crates/automation/src/agent_link.rs index 99a94e6f9c..fb33b998aa 100644 --- a/crates/automation/src/agent_link.rs +++ b/crates/automation/src/agent_link.rs @@ -178,7 +178,11 @@ pub fn read_integrations(dir: &Path) -> Integrations { .flatten() .and_then(|text| serde_json::from_str::(&text).ok()) .and_then(|v| v.get("integrations").cloned()) - .and_then(|v| serde_json::from_value(v).ok()) + .and_then(|mut v| { + // As the app reads it: a Control Port from before *Let AI agents connect* keeps it on. + photocraft_engine::prefs::migrate_integrations(&mut v); + serde_json::from_value(v).ok() + }) .unwrap_or_default() } @@ -548,6 +552,26 @@ fn merge_into_file(file: &Path, launch: &McpLaunch) -> Result std::io::Result { + let mut child = c.spawn()?; + let deadline = std::time::Instant::now() + timeout; + loop { + if child.try_wait()?.is_some() { + return child.wait_with_output(); + } + if std::time::Instant::now() >= deadline { + let _ = child.kill(); + let _ = child.wait(); + return Err(std::io::Error::new(std::io::ErrorKind::TimedOut, format!("no answer within {} s", timeout.as_secs()))); + } + std::thread::sleep(Duration::from_millis(25)); + } +} + fn install_claude_code(launch: &McpLaunch, env: &ClientEnv) -> Result { let by_hand = format!("claude mcp add --scope user {SERVER_NAME} -- {}", launch.shell_line()); let claude = @@ -557,21 +581,34 @@ fn install_claude_code(launch: &McpLaunch, env: &ClientEnv) -> Result 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()), }; + if replaced { + return Err(AutomationError::Other(format!( + "adding PhotoCraft to Claude Code failed ({why}) after its older `{SERVER_NAME}` entry was removed; run this in a terminal to add it again: {by_hand}" + ))); + } Err(AutomationError::Other(format!("adding PhotoCraft to Claude Code failed ({why}); run this in a terminal instead: {by_hand}"))) } @@ -655,6 +692,11 @@ mod tests { assert_eq!(folder(&i.read_root), Some(PathBuf::from("/in"))); assert_eq!(folder(&i.write_root), None); assert_eq!(folder(" "), None); + // A Control Port saved before *Let AI agents connect* reads as on, as the app reads it. + std::fs::write(dir.join("preferences.json"), r#"{"integrations": {"controlPort": 7878}}"#).unwrap(); + assert!(read_integrations(&dir).connect_agents); + std::fs::write(dir.join("preferences.json"), r#"{"integrations": {"controlPort": 7878, "connectAgents": false}}"#).unwrap(); + assert!(!read_integrations(&dir).connect_agents); let _ = std::fs::remove_dir_all(&dir); } @@ -839,10 +881,19 @@ mod tests { std::fs::create_dir_all(&bin).unwrap(); let log = home.join("calls.txt"); let fail = home.join("fail"); + let exists = home.join("exists"); + // `add` fails while an entry exists (as claude's does) or while `fail` is there; `remove` + // removes the entry. 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", + "#!/bin/sh\nprintf 'PATH=%s\\n' \"$PATH\" >> '{log}'\nprintf '%s ' \"$@\" >> '{log}'\nprintf '\\n' >> '{log}'\n\ + if [ \"$2\" = remove ]; then rm -f '{exists}'; exit 0; fi\n\ + if [ \"$2\" = get ]; then [ -e '{exists}' ]; exit $?; fi\n\ + if [ \"$2\" = add ] && [ -e '{exists}' ]; then echo 'already exists' >&2; exit 1; fi\n\ + if [ \"$2\" = add ] && [ -e '{fail}' ]; then echo 'boom' >&2; exit 1; fi\n\ + if [ \"$2\" = add ]; then : > '{exists}'; fi\n", log = log.display(), - fail = fail.display() + fail = fail.display(), + exists = exists.display() ); let claude = bin.join("claude"); std::fs::write(&claude, script).unwrap(); @@ -859,17 +910,40 @@ mod tests { } install(Client::ClaudeCode, &launch, &env) }; + // No entry yet: added, nothing removed. 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 remove"), "{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}"); + // An entry exists: replaced. + assert_eq!(run().unwrap(), Installed::ClaudeCode); + assert!(std::fs::read_to_string(&log).unwrap().contains("mcp remove --scope user photocraft \n")); + assert!(exists.exists()); + // An entry exists and adding can't work: the error says the older entry went, and how to add it. 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}"); + assert!(e.contains("was removed") && e.contains("claude mcp add --scope user photocraft -- /x/photocraft-cli mcp --live"), "{e}"); + // No entry and adding can't work: nothing is removed. + std::fs::write(&log, "").unwrap(); + let e = run().unwrap_err().to_string(); + assert!(e.contains("boom") && !e.contains("was removed"), "{e}"); + assert!(!std::fs::read_to_string(&log).unwrap().contains("mcp remove")); let _ = std::fs::remove_dir_all(&home); } + /// A `claude` that never answers can't hang the Preferences button. + #[cfg(unix)] + #[test] + fn a_command_that_hangs_is_stopped_after_the_timeout() { + let mut c = std::process::Command::new("sleep"); + c.arg("30").stdout(std::process::Stdio::piped()).stderr(std::process::Stdio::piped()); + let t = std::time::Instant::now(); + let e = output_within(c, Duration::from_millis(200)).unwrap_err(); + assert_eq!(e.kind(), std::io::ErrorKind::TimedOut); + assert!(t.elapsed() < Duration::from_secs(5)); + } + #[test] fn json_client_returns_the_configuration() { let launch = McpLaunch::cli(Path::new("/x/photocraft-cli")); diff --git a/crates/automation/src/live.rs b/crates/automation/src/live.rs index 53501a97ba..67fddc43a8 100644 --- a/crates/automation/src/live.rs +++ b/crates/automation/src/live.rs @@ -55,7 +55,7 @@ pub(crate) enum Target { } /// The port and token a bridge client was made for: when the app restarts, either changes. -type BridgeKey = (u16, String); +type BridgeKey = (u16, String, u32); pub struct Live { cfg: LiveConfig, @@ -130,7 +130,8 @@ impl Live { } fn use_app(&self, c: &Connection, token: String) -> Result<(), String> { - let key: BridgeKey = (c.port, token); + // The pid too: a restarted app keeps its port and token, but the old socket is dead. + let key: BridgeKey = (c.port, token, c.pid); let same = self.current.lock().unwrap_or_else(PoisonError::into_inner).as_ref().is_some_and(|(_, k)| k.as_ref() == Some(&key)); if !same { let client = BridgeClient::new(c.addr(), key.1.clone()).map_err(|e| e.to_string())?; diff --git a/crates/automation/src/server.rs b/crates/automation/src/server.rs index d763c706f9..4ac27ea463 100644 --- a/crates/automation/src/server.rs +++ b/crates/automation/src/server.rs @@ -686,6 +686,15 @@ impl PhotocraftMcp { } } + /// Where calls go now: the backend's session or app, or `--live`'s last resolve. + fn target(&self) -> Option { + match &*self.backend { + Backend::Headless(h) => Some(Target::Headless(h.clone())), + Backend::Bridge(b) => Some(Target::Bridge(b.clone())), + Backend::Live(live) => live.current(), + } + } + /// `--live`: find the app (or apply the closed-app choice) before a call; the error is the /// call's result. Other backends are always ready. async fn ready(&self) -> Result<(), String> { @@ -1138,6 +1147,16 @@ impl PhotocraftMcp { } } +/// Whether two targets are the same session or the same app connection. +fn same_target(a: Option<&Target>, b: Option<&Target>) -> bool { + match (a, b) { + (Some(Target::Headless(a)), Some(Target::Headless(b))) => Arc::ptr_eq(a, b), + (Some(Target::Bridge(a)), Some(Target::Bridge(b))) => Arc::ptr_eq(a, b), + (None, None) => true, + _ => false, + } +} + fn bridge_only_headless(name: &str) -> Result { Ok(fail(format!("`{name}` is only available in headless mode (in the GUI use the window/tab UI or control_call)"))) } @@ -1170,11 +1189,19 @@ impl PhotocraftMcp { let mut failed = 0; // The reply travels as escaped JSON text, so steps are charged their escaped size. let mut reply_budget = BatchReplyBudget::escaped(); + // `--live` may find a restarted app (or go headless) while a batch runs: its steps must + // not end up split across two documents in two places. + let pinned = self.target(); for (i, s) in p.steps.into_iter().enumerate() { // A cancelled request runs no further steps; the client no longer reads the reply. if waiter.is_cancelled() { break; } + if !same_target(pinned.as_ref(), self.target().as_ref()) { + failed += 1; + results.push(json!({"ok": false, "error": "PhotoCraft restarted (or the session changed) during the batch; this step and the ones after it did not run"})); + break; + } let response = self.step(s.id, s.params.unwrap_or_else(|| json!({})), s.wait.unwrap_or(true), &mut waiter, (i, total)).await; let was_error = response.is_err(); let result = match response { diff --git a/crates/automation/src/server/progress.rs b/crates/automation/src/server/progress.rs index bdee54b4d4..be27ef8187 100644 --- a/crates/automation/src/server/progress.rs +++ b/crates/automation/src/server/progress.rs @@ -1,8 +1,9 @@ //! Progress and cancellation for calls that wait. Render Video runs on the existing blocking //! worker; other long commands run as engine jobs that the server polls ([`Waiter`]): the headless //! session's own, or the app's over the bridge. -use super::{Arc, AutomationError, Backend, BridgeClient, CallToolResult, PhotocraftMcp, PoisonError, Value, fail, json, no_backend, ok_json}; +use super::{Arc, AutomationError, BridgeClient, CallToolResult, PhotocraftMcp, PoisonError, Value, fail, json, no_backend, ok_json}; use crate::headless::JobPoll; +use crate::live::Target; use photocraft_engine::jobs::{JobId, Started}; use rmcp::RoleServer; use rmcp::model::ProgressNotificationParam; @@ -92,7 +93,9 @@ impl Waiter { /// Cancels a waited job when its waiter goes away without collecting it: rmcp may drop the /// request future on cancellation, and nothing else would stop the job. struct Abandon { - backend: Arc, + /// The session or app that started the job: under `--live` the current target can change + /// before the guard drops, and the job id means nothing elsewhere. + target: Target, job: Option, } @@ -100,15 +103,9 @@ impl Drop for Abandon { fn drop(&mut self) { let Some(job) = self.job.take() else { return }; let runtime = tokio::runtime::Handle::try_current(); - // `--live`: the session or app its last resolve pointed at. - let target = match &*self.backend { - Backend::Headless(session) => Some(crate::live::Target::Headless(session.clone())), - Backend::Bridge(client) => Some(crate::live::Target::Bridge(client.clone())), - Backend::Live(live) => live.current(), - }; - match target { - None => {} - Some(crate::live::Target::Headless(session)) => { + match &self.target { + Target::Headless(session) => { + let session = session.clone(); let abandon = move || drop(session.lock().unwrap_or_else(PoisonError::into_inner).job_abandon(job)); match runtime { // A synchronous command can hold the lock for a while: don't block a runtime thread. @@ -117,8 +114,9 @@ impl Drop for Abandon { } } // Without a runtime there is no way to reach the app; the job then runs to the end. - Some(crate::live::Target::Bridge(client)) => { + Target::Bridge(client) => { if let Ok(runtime) = runtime { + let client = client.clone(); drop(runtime.spawn(async move { client.call("jobs.cancel", json!({"job": job.0})).await })); } } @@ -132,8 +130,7 @@ impl PhotocraftMcp { /// `waiter` as `step.0 + fraction` of `step.1`, and cancelling the request cancels the job, /// leaving the document unchanged. `None` in bridge mode. pub(super) async fn headless_wait(&self, id: String, params: Value, waiter: &mut Waiter, step: (usize, usize)) -> Option> { - self.headless_session()?; - let backend = self.backend.clone(); + let target = Target::Headless(self.headless_session()?); let cancel = waiter.context.as_ref().map(|context| context.ct.clone()); // The guard is armed under the lock that starts the job: when the request is dropped while // the start still waits for the lock, the closure's output is dropped unread and cancels it. @@ -146,7 +143,7 @@ impl PhotocraftMcp { Started::Job(job) if cancel.as_ref().is_some_and(|token| token.is_cancelled()) => { return h.job_abandon(job).map(Err); } - Started::Job(job) => Ok(Abandon { backend, job: Some(job) }), + Started::Job(job) => Ok(Abandon { target, job: Some(job) }), Started::Done(value) => Err(value), }) }) @@ -190,7 +187,7 @@ impl PhotocraftMcp { /// (#1007); a failed poll reports the job instead of guessing its outcome. pub(super) async fn bridge_wait( &self, - client: &BridgeClient, + client: &Arc, id: String, params: Value, waiter: &mut Waiter, @@ -205,7 +202,7 @@ impl PhotocraftMcp { let Some(job) = started.get("job").and_then(Value::as_u64).filter(|_| pending) else { return Ok(started); }; - let mut guard = Abandon { backend: self.backend.clone(), job: Some(JobId(job)) }; + let mut guard = Abandon { target: Target::Bridge(client.clone()), job: Some(JobId(job)) }; let mut delay = Duration::from_millis(10); loop { // Race the poll against a cancel: an app slow to answer must not hold it until the call times out. diff --git a/crates/engine/src/prefs.rs b/crates/engine/src/prefs.rs index fb518a931a..d33d84d783 100644 --- a/crates/engine/src/prefs.rs +++ b/crates/engine/src/prefs.rs @@ -1174,6 +1174,19 @@ impl Default for RawDefaults { } } +/// Before *Let AI agents connect*, a Control Port other than 0 started the control server by itself. +/// A saved `integrations` section like that keeps its connection: the port now means "on, at this +/// port". Every reader of the saved section applies this (the app, its launch read, and +/// `photocraft-cli mcp --live`), so they agree. +pub fn migrate_integrations(section: &mut Value) { + if let Some(integrations) = section.as_object_mut() + && !integrations.contains_key("connectAgents") + && integrations.get("controlPort").and_then(Value::as_u64).is_some_and(|p| (1..=65535).contains(&p)) + { + integrations.insert("connectAgents".into(), json!(true)); + } +} + #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(default, rename_all = "camelCase")] pub struct Integrations { @@ -1678,13 +1691,8 @@ impl Session { { *language = json!("sr-latn"); } - // Before *Let AI agents connect*, a Control Port other than 0 started the control server by - // itself. Such a file keeps its connection: the port now means "on, at this port". - if let Some(integrations) = v.get_mut("integrations").and_then(Value::as_object_mut) - && !integrations.contains_key("connectAgents") - && integrations.get("controlPort").and_then(Value::as_u64).is_some_and(|p| (1..=65535).contains(&p)) - { - integrations.insert("connectAgents".into(), json!(true)); + if let Some(integrations) = v.get_mut("integrations") { + migrate_integrations(integrations); } let color = v.as_object_mut().and_then(|m| m.remove("colorSettings")); let presets = v.as_object_mut().and_then(|m| m.remove("presets")); diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 43a219cc0e..e137664fce 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -355,7 +355,7 @@ fn command_body_more(app: &mut PhotocraftApp, ui: &mut egui::Ui, d: &Dialog, fie } } _ if crate::color_range_ui::owns(fields) => crate::color_range_ui::body(app, ui, fields), - _ if crate::prefs_ui::owns(fields) => crate::prefs_ui::body(app, ui, fields), + _ if crate::prefs_ui::owns(fields) => crate::prefs_ui::body(app, ui, fields, d.id), _ if fields.contains_key("__export") => crate::export_dialog::body(app, ui, fields), // Image Size and Canvas Size open on Width, selected (#2329). _ if fields.contains_key("__sizing") => first_field_focused(ui, id, |ui| crate::sizing::body(ui, fields)), diff --git a/crates/ui-egui/src/prefs/prefs_ui.rs b/crates/ui-egui/src/prefs/prefs_ui.rs index f7a567aa71..f57a730544 100644 --- a/crates/ui-egui/src/prefs/prefs_ui.rs +++ b/crates/ui-egui/src/prefs/prefs_ui.rs @@ -54,6 +54,9 @@ pub struct Runtime { pub(crate) tool_options: Option, /// MCP settings the agent connection was last set up for (`agents::sync_agent_link`). agent_link: Option, + /// When to try again after the agent connection failed to start (a taken port), in seconds of + /// `gpu_canvas::now_ms`; `None` while it runs or is off. + agent_link_retry: Option, pub(crate) selected_tool: Option, pub(crate) tool_colors: Option<[[[f32; 4]; 2]; 2]>, pub(crate) tool_cmyk_picks: crate::tool_memory::CmykPicks, diff --git a/crates/ui-egui/src/prefs/prefs_ui/agents.rs b/crates/ui-egui/src/prefs/prefs_ui/agents.rs index f998e7119b..d7dbf92986 100644 --- a/crates/ui-egui/src/prefs/prefs_ui/agents.rs +++ b/crates/ui-egui/src/prefs/prefs_ui/agents.rs @@ -6,16 +6,28 @@ use super::dialogs::is_preferences; use super::fields::{choice_label, humanize}; use super::{Map, PhotocraftApp, RichText, Tokens, Value, json, prefs}; +/// Seconds between tries while the agent connection is on but couldn't start (its port taken). +pub(super) const AGENT_LINK_RETRY_S: f64 = 5.0; + /// Start, move or stop the agent connection when its settings change -/// ([`crate::Services::agent_link`]); the first frame applies the saved settings. +/// ([`crate::Services::agent_link`]); the first frame applies the saved settings. A connection +/// that is on but failed to start is tried again every [`AGENT_LINK_RETRY_S`], so freeing its +/// port is enough, without touching a setting. pub(super) fn sync_agent_link(app: &mut PhotocraftApp, ctx: &egui::Context) { let Some(link) = app.services.agent_link.as_mut() else { return }; let current = &app.session.prefs().integrations; - if app.prefs_rt.agent_link.as_ref() == Some(current) { + let now = crate::gpu_canvas::now_ms() / 1000.0; + let retry_due = app.prefs_rt.agent_link_retry.is_some_and(|at| now >= at); + if app.prefs_rt.agent_link.as_ref() == Some(current) && !retry_due { return; } let update = link(current, ctx); + let failed_start = current.connect_agents && current.allow_agent_control && update.status.port.is_none(); app.prefs_rt.agent_link = Some(current.clone()); + app.prefs_rt.agent_link_retry = failed_start.then_some(now + AGENT_LINK_RETRY_S); + if failed_start { + ctx.request_repaint_after(std::time::Duration::from_secs_f64(AGENT_LINK_RETRY_S)); + } if update.stopped { app.control_rx = None; } @@ -23,6 +35,9 @@ pub(super) fn sync_agent_link(app: &mut PhotocraftApp, ctx: &egui::Context) { app.control_rx = Some(rx); } app.services.set_automation(update.automation); + // Actions automation records keep the policy as their gate when the user plays them, as they + // do with `--control` (`PhotocraftApp::new`); the gate stays once agents have connected. + app.session.automation_gate = app.session.automation_gate.or(app.services.automation_authorize); app.agent_link = update.status; } @@ -116,15 +131,17 @@ pub(super) fn integration_rows(ui: &mut egui::Ui, obj: &mut Map, /// A button of [`integration_rows`]: choose a folder (into the dialog's working copy), or add /// PhotoCraft to an MCP client through [`crate::Services::agent_clients`]. -pub(super) fn agent_action(app: &mut PhotocraftApp, ctx: &egui::Context, f: &mut Map, action: &str) { +pub(super) fn agent_action(app: &mut PhotocraftApp, ctx: &egui::Context, f: &mut Map, action: &str, dialog: u64) { let key = match action { "chooseRead" => Some("readRoot"), "chooseWrite" => Some("writeRoot"), _ => None, }; if let Some(key) = key { + // Into the Preferences dialog that asked: closed meanwhile (or reopened as a new one), the + // answer is dropped rather than landing in another working copy. let picked = app.ask_folder(move |app, path| { - if let Some(d) = app.ui.dialogs.iter_mut().find(|d| is_preferences(&d.fields)) + if let Some(d) = app.ui.dialogs.iter_mut().find(|d| d.id == dialog && is_preferences(&d.fields)) && let Some(obj) = d.fields.get_mut("values").and_then(|v| v.get_mut("integrations")).and_then(Value::as_object_mut) { obj.insert(key.into(), json!(path)); diff --git a/crates/ui-egui/src/prefs/prefs_ui/agents_tests.rs b/crates/ui-egui/src/prefs/prefs_ui/agents_tests.rs index 9bf444a676..3e55459c0f 100644 --- a/crates/ui-egui/src/prefs/prefs_ui/agents_tests.rs +++ b/crates/ui-egui/src/prefs/prefs_ui/agents_tests.rs @@ -102,3 +102,44 @@ fn ai_integrations_choices_and_paths_validate_through_prefs_set() { app.run("prefs.set", json!({"values": {"integrations.writeRoot": "/tmp/out"}})).unwrap(); assert_eq!(app.session.prefs().integrations.write_root, "/tmp/out"); } + +/// A connection that is on but failed to start (its port taken) is tried again by itself, with the +/// same settings, and the automation gate follows the live policy. +#[test] +fn a_failed_start_is_retried_without_a_setting_change() { + let (mut app, _) = app_with_store(); + let ctx = egui::Context::default(); + let calls: Arc> = Arc::default(); + let seen = calls.clone(); + app.services.agent_link = Some(Box::new(move |p: &prefs::Integrations, _: &egui::Context| { + let mut n = seen.lock().unwrap(); + *n += 1; + let mut out = crate::AgentLink::default(); + if p.connect_agents && *n >= 3 { + out.status.port = Some(4321); + out.automation.authorize = Some(|_, _| Ok(())); + } else if p.connect_agents { + out.status.error = Some("Couldn't listen on 127.0.0.1:4321: in use".into()); + } + out + })); + app.run("prefs.set", json!({"values": {"integrations.connectAgents": true}})).unwrap(); + tick(&mut app, &ctx); + assert_eq!(*calls.lock().unwrap(), 1); + assert!(app.agent_link.port.is_none() && app.prefs_rt.agent_link_retry.is_some(), "a retry is scheduled"); + // Not yet due: nothing happens. + tick(&mut app, &ctx); + assert_eq!(*calls.lock().unwrap(), 1); + // Due: tried again with the same settings, still failing, then started. + app.prefs_rt.agent_link_retry = Some(0.0); + tick(&mut app, &ctx); + assert_eq!(*calls.lock().unwrap(), 2); + app.prefs_rt.agent_link_retry = Some(0.0); + tick(&mut app, &ctx); + assert_eq!(*calls.lock().unwrap(), 3); + assert_eq!(app.agent_link.port, Some(4321)); + assert!(app.prefs_rt.agent_link_retry.is_none(), "running: no more retries"); + assert!(app.session.automation_gate.is_some(), "actions agents record keep the policy"); + tick(&mut app, &ctx); + assert_eq!(*calls.lock().unwrap(), 3); +} diff --git a/crates/ui-egui/src/prefs/prefs_ui/fields.rs b/crates/ui-egui/src/prefs/prefs_ui/fields.rs index 6013b1f855..5b4574a1bd 100644 --- a/crates/ui-egui/src/prefs/prefs_ui/fields.rs +++ b/crates/ui-egui/src/prefs/prefs_ui/fields.rs @@ -6,8 +6,8 @@ use super::{Color32, Map, PhotocraftApp, RichText, SECTIONS, Sense, Tokens, Valu // ------------------------------------------------------------------ bodies -/// Render one of our dialogs' bodies. -pub fn body(app: &mut PhotocraftApp, ui: &mut egui::Ui, f: &mut Map) { +/// Render one of our dialogs' bodies (`id`: the dialog's, for answers that arrive later). +pub fn body(app: &mut PhotocraftApp, ui: &mut egui::Ui, f: &mut Map, id: u64) { match f.get("__prefsui").and_then(Value::as_str).unwrap_or("") { "prefs" => { let mut info = app.perf.gpu_info.lines(); @@ -19,7 +19,7 @@ pub fn body(app: &mut PhotocraftApp, ui: &mut egui::Ui, f: &mut Map shortcuts_body(app, ui, f), From 466f010a58a2676ec564f70856266eed1c0a5259 Mon Sep 17 00:00:00 2001 From: David Mann Date: Thu, 12 Nov 2026 13:58:43 +0100 Subject: [PATCH 11/28] fix(automation): Claude Code install says when the older entry could not be removed `install_claude_code` ignored the result of `claude mcp remove`, so a failed remove (on CI, a freshly written script briefly busy) led to a second "already exists" and an error claiming the entry had been removed. It now reports the failed remove with the command to run instead, and the test covers it. Also the CLI tests for the new `mcp install` subcommand: a stray word after `mcp` is an unrecognized subcommand, and it has its own man page. --- apps/photocraft-cli/tests/it/cli.rs | 4 ++- .../tests/it/man_and_completions.rs | 2 ++ crates/automation/src/agent_link.rs | 28 +++++++++++++++++-- 3 files changed, 30 insertions(+), 4 deletions(-) diff --git a/apps/photocraft-cli/tests/it/cli.rs b/apps/photocraft-cli/tests/it/cli.rs index 22a988baa5..f0d2ab4195 100644 --- a/apps/photocraft-cli/tests/it/cli.rs +++ b/apps/photocraft-cli/tests/it/cli.rs @@ -163,7 +163,9 @@ fn server_usage_error(args: &[&str], expected: &str) { #[test] fn server_modes_reject_ignored_or_conflicting_options() { for sub in ["mcp", "serve"] { - server_usage_error(&[sub, "stray.psd"], "unexpected argument 'stray.psd'"); + // `mcp` has a subcommand (`mcp install`), so clap reads a stray word there as one. + let stray = if sub == "mcp" { "unrecognized subcommand 'stray.psd'" } else { "unexpected argument 'stray.psd'" }; + server_usage_error(&[sub, "stray.psd"], stray); for flag in ["--control-token", "--control-token-file"] { server_usage_error(&[sub, flag, "unused"], if sub == "mcp" { "requires --bridge" } else { "requires --port" }); } diff --git a/apps/photocraft-cli/tests/it/man_and_completions.rs b/apps/photocraft-cli/tests/it/man_and_completions.rs index 9c1e2aabbf..d23e6f25a6 100644 --- a/apps/photocraft-cli/tests/it/man_and_completions.rs +++ b/apps/photocraft-cli/tests/it/man_and_completions.rs @@ -49,6 +49,8 @@ fn the_example_writes_the_files_the_packages_install() { let mut expected: Vec = completions.map(String::from).into(); expected.push("photocraft-cli.1".into()); expected.extend(subcommands.iter().map(|s| format!("photocraft-cli-{s}.1"))); + // Nested subcommands get their own page too (the packages install every `*.1`). + expected.push("photocraft-cli-mcp-install.1".into()); expected.sort(); assert_eq!(written, expected); std::fs::remove_dir_all(&dir).unwrap(); diff --git a/crates/automation/src/agent_link.rs b/crates/automation/src/agent_link.rs index fb33b998aa..4a0d4bd199 100644 --- a/crates/automation/src/agent_link.rs +++ b/crates/automation/src/agent_link.rs @@ -595,7 +595,18 @@ fn install_claude_code(launch: &McpLaunch, env: &ClientEnv) -> Result None, + Ok(out) => Some(String::from_utf8_lossy(if out.stderr.is_empty() { &out.stdout } else { &out.stderr }).trim().to_string()), + Err(e) => Some(format!("{}: {e}", claude.display())), + }; + if let Some(why) = why_not { + return Err(AutomationError::Other(format!( + "Claude Code already has a `{SERVER_NAME}` entry and removing it failed ({why}); run this in a terminal to replace it: claude mcp remove --scope user {SERVER_NAME} && {by_hand}" + ))); + } replaced = true; result = run(&add); } @@ -882,10 +893,12 @@ mod tests { let log = home.join("calls.txt"); let fail = home.join("fail"); let exists = home.join("exists"); + let keep = home.join("keep"); // `add` fails while an entry exists (as claude's does) or while `fail` is there; `remove` - // removes the entry. + // removes the entry, or fails while `keep` is there. let script = format!( "#!/bin/sh\nprintf 'PATH=%s\\n' \"$PATH\" >> '{log}'\nprintf '%s ' \"$@\" >> '{log}'\nprintf '\\n' >> '{log}'\n\ + if [ \"$2\" = remove ] && [ -e '{keep}' ]; then echo 'locked' >&2; exit 1; fi\n\ if [ \"$2\" = remove ]; then rm -f '{exists}'; exit 0; fi\n\ if [ \"$2\" = get ]; then [ -e '{exists}' ]; exit $?; fi\n\ if [ \"$2\" = add ] && [ -e '{exists}' ]; then echo 'already exists' >&2; exit 1; fi\n\ @@ -893,7 +906,8 @@ mod tests { if [ \"$2\" = add ]; then : > '{exists}'; fi\n", log = log.display(), fail = fail.display(), - exists = exists.display() + exists = exists.display(), + keep = keep.display() ); let claude = bin.join("claude"); std::fs::write(&claude, script).unwrap(); @@ -929,6 +943,14 @@ mod tests { let e = run().unwrap_err().to_string(); assert!(e.contains("boom") && !e.contains("was removed"), "{e}"); assert!(!std::fs::read_to_string(&log).unwrap().contains("mcp remove")); + // An entry exists and removing it fails: the error says so, and does not claim it went. + std::fs::remove_file(&fail).unwrap(); + std::fs::write(&exists, "").unwrap(); + std::fs::write(&keep, "").unwrap(); + let e = run().unwrap_err().to_string(); + assert!(e.contains("removing it failed (locked)") && !e.contains("was removed"), "{e}"); + assert!(e.contains("claude mcp remove --scope user photocraft && claude mcp add"), "{e}"); + assert!(exists.exists(), "the older entry is still there"); let _ = std::fs::remove_dir_all(&home); } From 1e3eae08cb250dcef624ba43f91170550d6ff59d Mon Sep 17 00:00:00 2001 From: David Mann Date: Thu, 12 Nov 2026 14:41:20 +0100 Subject: [PATCH 12/28] test(automation): the fake claude removes its entry with a full path to rm The test runs the fake `claude` with PATH set to its own folder and an empty one, so the script's external `rm` was not found: `mcp remove` exited 0 without removing anything, and the following `add` failed with "already exists". This, not a busy executable, is why the test failed on Linux. Builtins (printf, [, :) were unaffected. --- crates/automation/src/agent_link.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/crates/automation/src/agent_link.rs b/crates/automation/src/agent_link.rs index 4a0d4bd199..80aa7e1770 100644 --- a/crates/automation/src/agent_link.rs +++ b/crates/automation/src/agent_link.rs @@ -895,11 +895,12 @@ mod tests { let exists = home.join("exists"); let keep = home.join("keep"); // `add` fails while an entry exists (as claude's does) or while `fail` is there; `remove` - // removes the entry, or fails while `keep` is there. + // removes the entry, or fails while `keep` is there. `PATH` holds only claude's folder and + // an empty one, so anything that isn't a shell builtin needs its full path. let script = format!( "#!/bin/sh\nprintf 'PATH=%s\\n' \"$PATH\" >> '{log}'\nprintf '%s ' \"$@\" >> '{log}'\nprintf '\\n' >> '{log}'\n\ if [ \"$2\" = remove ] && [ -e '{keep}' ]; then echo 'locked' >&2; exit 1; fi\n\ - if [ \"$2\" = remove ]; then rm -f '{exists}'; exit 0; fi\n\ + if [ \"$2\" = remove ]; then /bin/rm -f '{exists}'; exit 0; fi\n\ if [ \"$2\" = get ]; then [ -e '{exists}' ]; exit $?; fi\n\ if [ \"$2\" = add ] && [ -e '{exists}' ]; then echo 'already exists' >&2; exit 1; fi\n\ if [ \"$2\" = add ] && [ -e '{fail}' ]; then echo 'boom' >&2; exit 1; fi\n\ From 09ad48fceea70bef3bd392eff267fd3783bf643c Mon Sep 17 00:00:00 2001 From: David Mann Date: Thu, 12 Nov 2026 15:38:51 +0100 Subject: [PATCH 13/28] Keep the page named AI Integrations, not MCP MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The Integrations page holds more than the agent connection: open PRs add the AI services for Generative Fill and other AI features to it (#10903, #12391, #7007). The menu item stays "AI Integrations…" and the page "Integrations", as on main; messages and docs say Edit › Preferences › AI Integrations. --- README.md | 2 +- apps/photocraft-cli/src/args.rs | 4 ++-- apps/photocraft-cli/tests/it/cli.rs | 4 ++-- apps/photocraft/src/agent_link.rs | 2 +- apps/photocraft/src/control_server.rs | 2 +- apps/photocraft/src/main.rs | 16 ++++++++-------- book/src/automation/mcp.md | 2 +- book/src/security/automation-security.md | 2 +- crates/automation/src/agent_link.rs | 6 +++--- crates/automation/src/lib.rs | 2 +- crates/automation/src/live.rs | 4 ++-- crates/automation/tests/mcp_live.rs | 2 +- crates/engine/src/prefs/cmds.rs | 2 +- crates/engine/src/prefs/validate.rs | 2 +- crates/ui-egui/src/lib.rs | 2 +- crates/ui-egui/src/menu_catalog.rs | 2 +- crates/ui-egui/src/preferences_submenu_tests.rs | 2 +- crates/ui-egui/src/prefs/prefs_ui/agents.rs | 2 +- .../ui-egui/src/prefs/prefs_ui/agents_tests.rs | 2 +- crates/ui-egui/src/services.rs | 10 +++++----- docs/control-protocol.md | 8 ++++---- docs/development.md | 2 +- docs/mcp.md | 2 +- docs/roadmap.md | 4 ++-- docs/scorecard.md | 2 +- packaging/macos/package.sh | 2 +- scorecard/automation.toml | 2 +- 27 files changed, 47 insertions(+), 47 deletions(-) diff --git a/README.md b/README.md index 83d1204ef5..eb577fded0 100644 --- a/README.md +++ b/README.md @@ -246,7 +246,7 @@ photocraft-cli batch --help photocraft-cli mcp ``` -To let Claude or another AI app drive the open PhotoCraft window without a terminal, turn on **Edit › Preferences › MCP › Let AI agents connect**, then click **Add to Claude Desktop** (or Claude Code, or Cursor) in the same panel. See [`docs/mcp.md`](docs/mcp.md). +To let Claude or another AI app drive the open PhotoCraft window without a terminal, turn on **Edit › Preferences › AI Integrations › Let AI agents connect**, then click **Add to Claude Desktop** (or Claude Code, or Cursor) in the same panel. See [`docs/mcp.md`](docs/mcp.md). The desktop app also offers an authenticated, loopback-only control channel (`photocraft --control`) for inspecting UI state, driving tools with pointer events, and taking offscreen screenshots. Every image in this README was rendered that way. See [`docs/control-protocol.md`](docs/control-protocol.md). diff --git a/apps/photocraft-cli/src/args.rs b/apps/photocraft-cli/src/args.rs index 8b850e2037..5934d6f94b 100644 --- a/apps/photocraft-cli/src/args.rs +++ b/apps/photocraft-cli/src/args.rs @@ -276,7 +276,7 @@ pub(crate) struct CommandsArgs { /// Headless: each automation root grants that direction of file access; an omitted root denies it. /// Prefer absolute root paths in MCP client configurations. Bridge: set the roots on the desktop /// app; root flags are refused. The token flags require --bridge (or PHOTOCRAFT_CONTROL_PORT). -/// Live: the desktop app with Edit › Preferences › MCP › Let AI agents connect on, +/// Live: the desktop app with Edit › Preferences › AI Integrations › Let AI agents connect on, /// found again on every call (no port or token to configure); the roots are for a headless session /// while the app is closed. #[derive(Args)] @@ -284,7 +284,7 @@ pub(crate) struct CommandsArgs { pub(crate) struct McpArgs { #[command(subcommand)] pub(crate) action: Option, - /// Find the desktop app by itself on every call (Edit › Preferences › MCP › + /// Find the desktop app by itself on every call (Edit › Preferences › AI Integrations › /// Let AI agents connect), with no port or token to configure #[arg(long)] pub(crate) live: bool, diff --git a/apps/photocraft-cli/tests/it/cli.rs b/apps/photocraft-cli/tests/it/cli.rs index f0d2ab4195..e4da07dc47 100644 --- a/apps/photocraft-cli/tests/it/cli.rs +++ b/apps/photocraft-cli/tests/it/cli.rs @@ -2033,7 +2033,7 @@ fn info_detail_adds_text_runs_and_antialiasing() { } /// `mcp install --client json` prints the configuration MCP clients start `mcp --live` with; -/// Cursor's file gets the same entry, other servers kept (Preferences › MCP). +/// Cursor's file gets the same entry, other servers kept (Preferences › AI Integrations). #[test] fn mcp_install_writes_the_live_entry() { let home = tmp("mcp-install"); @@ -2115,7 +2115,7 @@ fn mcp_live_without_the_app_explains_what_to_do() { send(json!({"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"ui_inspect","arguments":{}}})); let r = recv(2); assert_eq!(r["result"]["isError"], true, "{r}"); - assert!(r["result"]["content"][0]["text"].as_str().unwrap().contains("MCP"), "{r}"); + assert!(r["result"]["content"][0]["text"].as_str().unwrap().contains("Preferences › AI Integrations › Let AI agents connect"), "{r}"); drop(stdin); let _ = child.kill(); let _ = child.wait(); diff --git a/apps/photocraft/src/agent_link.rs b/apps/photocraft/src/agent_link.rs index 267b678e08..7cc2e563d3 100644 --- a/apps/photocraft/src/agent_link.rs +++ b/apps/photocraft/src/agent_link.rs @@ -1,4 +1,4 @@ -//! Preferences › MCP on the desktop: while *Let AI agents connect* is on, the app +//! Preferences › AI Integrations on the desktop: while *Let AI agents connect* is on, the app //! serves the control protocol by itself (no `--control`) and publishes the connection file //! `photocraft-cli mcp --live` finds it by ([`photocraft_automation::agent_link`]). Turning it on //! or off, or changing the port or folders, applies at once. The token stays in the settings diff --git a/apps/photocraft/src/control_server.rs b/apps/photocraft/src/control_server.rs index 75bb02f480..004a85463e 100644 --- a/apps/photocraft/src/control_server.rs +++ b/apps/photocraft/src/control_server.rs @@ -1,7 +1,7 @@ //! Localhost JSON-lines control server (one request per line, one reply per line). //! Loopback only. This is the transport the MCP server will wrap. //! -//! `--control` starts it for the whole run ([`start`]); Preferences › MCP starts and +//! `--control` starts it for the whole run ([`start`]); Preferences › AI Integrations starts and //! stops it while the app runs ([`listen`], see `agent_link`). use std::io::{BufReader, Write}; diff --git a/apps/photocraft/src/main.rs b/apps/photocraft/src/main.rs index 0315a40302..a8e17411eb 100644 --- a/apps/photocraft/src/main.rs +++ b/apps/photocraft/src/main.rs @@ -95,7 +95,7 @@ fn custom_titlebar(prefs_file: Option<&std::path::Path>) -> bool { CUSTOM_TITLEBAR && !prefs.interface.system_title_bar } -/// Preferences › MCP, read before the window opens the way [`custom_titlebar`] is: +/// Preferences › AI Integrations, read before the window opens the way [`custom_titlebar`] is: /// whether agents may drive this launch at all, the port to listen on when no `--control` /// was given (0 = only with `--control`) and the automation folders used when no /// `--automation-read-root` / `--automation-write-root` was given. A missing or unreadable file @@ -146,7 +146,7 @@ fn integration_fields(section: &serde_json::Value, out: &mut photocraft_engine:: } /// The automation roots: `--automation-read-root` / `--automation-write-root` (or their -/// variables) win; a direction without one takes Preferences › MCP' folder. A flag's +/// variables) win; a direction without one takes Preferences › AI Integrations' folder. A flag's /// root that can't be opened stops the launch (exit status 2) as before. A preference's root that /// can't be opened, or isn't an absolute path (it would depend on the folder the app was started /// from), is left out, so that direction fails closed, and the warning says why: a folder moved @@ -176,7 +176,7 @@ fn automation_workspace( Ok(w) => workspace = w, Err(e) => { let which = if read { "Automation Read Folder" } else { "Automation Write Folder" }; - warnings.push(format!("Preferences › MCP › {which} is not used: {e}")); + warnings.push(format!("Preferences › AI Integrations › {which} is not used: {e}")); } } } @@ -191,7 +191,7 @@ fn control_port_for(cli: Option, prefs: &photocraft_engine::prefs::Integrat if !prefs.allow_agent_control { let warning = cli.map(|p| { format!( - "photocraft: Preferences › MCP › Allow Agent Control is off: not listening on port {p} + "photocraft: Preferences › AI Integrations › Allow Agent Control is off: not listening on port {p} " ) }); @@ -358,7 +358,7 @@ struct ControlNotice { } /// The `--control` server's port, token and workspace, when it is on (exits 2 on a bad -/// configuration). Preferences › MCP' folders stand in for automation roots no flag +/// configuration). Preferences › AI Integrations' folders stand in for automation roots no flag /// names. The server Preferences start (*Let AI agents connect*) is `agent_link`'s, not this. fn control_setup( cli_port: Option, @@ -368,7 +368,7 @@ fn control_setup( control_setup_in(services::config_dir(), &integrations(services::prefs_file().as_deref()), cli_port, auth, automation) } -/// [`control_setup`] with the settings folder and Preferences › MCP given. +/// [`control_setup`] with the settings folder and Preferences › AI Integrations given. fn control_setup_in( settings: Option, prefs: &photocraft_engine::prefs::Integrations, @@ -719,7 +719,7 @@ fn main() -> eframe::Result { log::warn!("couldn't remember GPU backend {}: {e}", b.name()); } }); - // Preferences › MCP: agents connect without a terminal, unless the launch + // Preferences › AI Integrations: agents connect without a terminal, unless the launch // flags (`--control`) manage the connection. let mcp = agent_link::mcp_launch(); app.agent_link.mcp_command = mcp.as_ref().map(photocraft_automation::agent_link::McpLaunch::shell_line); @@ -1196,7 +1196,7 @@ mod tests { } } - /// Preferences › MCP' folders are the automation roots when no flag names one, and + /// Preferences › AI Integrations' folders are the automation roots when no flag names one, and /// a flag wins over its preference, direction by direction. #[test] fn automation_folders_come_from_the_preferences_unless_a_flag_names_one() { diff --git a/book/src/automation/mcp.md b/book/src/automation/mcp.md index 9362d55376..4cfbb36310 100644 --- a/book/src/automation/mcp.md +++ b/book/src/automation/mcp.md @@ -4,7 +4,7 @@ - **Headless:** an in-process `Headless` session owns the engine and performs file I/O. - **Bridge:** `BridgeClient` forwards tools to a desktop application started with `photocraft --control `. -- **Live:** `photocraft-cli mcp --live` finds the desktop application through the connection file it publishes while Edit › Preferences › MCP › *Let AI agents connect* is on, before every tool call; while the app is closed it starts it, serves a headless session, or reports an error, as chosen there. +- **Live:** `photocraft-cli mcp --live` finds the desktop application through the connection file it publishes while Edit › Preferences › AI Integrations › *Let AI agents connect* is on, before every tool call; while the app is closed it starts it, serves a headless session, or reports an error, as chosen there. The simplest setup needs no terminal: turn on *Let AI agents connect* in PhotoCraft, then click *Add to Claude Desktop* (or Claude Code, or Cursor) in the same panel. See [`docs/mcp.md`](../../../docs/mcp.md#connecting-the-desktop-app-no-terminal). diff --git a/book/src/security/automation-security.md b/book/src/security/automation-security.md index 634b16d893..000a091d75 100644 --- a/book/src/security/automation-security.md +++ b/book/src/security/automation-security.md @@ -29,7 +29,7 @@ Automation is a privilege boundary because requests can cause filesystem access, Screenshots are decoded under separate dimension, pixel, and allocation ceilings before downscaling; the 5 MiB PNG limit applies to the returned image. - MCP normally uses stdio and can optionally bridge to loopback control TCP. -- Edit › Preferences › MCP › *Let AI agents connect* (off by default) opens that loopback +- Edit › Preferences › AI Integrations › *Let AI agents connect* (off by default) opens that loopback listener without launch flags. Its token is kept in a user-only file in the settings folder (`agent-control.token`) and stays the same across restarts and port changes: restarting does not revoke it. To revoke an exposed token, delete that file; the next start creates a new one. diff --git a/crates/automation/src/agent_link.rs b/crates/automation/src/agent_link.rs index 80aa7e1770..9cfd4ae8d3 100644 --- a/crates/automation/src/agent_link.rs +++ b/crates/automation/src/agent_link.rs @@ -240,7 +240,7 @@ impl McpLaunch { 2. Reload your MCP servers if your client needs that (or tell me to restart you). 3. Call the {SERVER_NAME} tool `ui_inspect` and tell me which document is open. - PhotoCraft must be running with Edit › Preferences › MCP › Let AI agents connect turned on. The command needs no port or token: it finds the app by itself on every call. + PhotoCraft must be running with Edit › Preferences › AI Integrations › Let AI agents connect turned on. The command needs no port or token: it finds the app by itself on every call. " ) } @@ -852,7 +852,7 @@ mod tests { assert!(prompt.contains("claude mcp add --scope user photocraft -- /x/photocraft-cli mcp --live"), "{prompt}"); assert!(prompt.contains("codex mcp add photocraft -- /x/photocraft-cli mcp --live"), "{prompt}"); assert!(prompt.contains(&launch.config_json()), "{prompt}"); - assert!(prompt.contains("Edit › Preferences › MCP › Let AI agents connect"), "{prompt}"); + assert!(prompt.contains("Edit › Preferences › AI Integrations › Let AI agents connect"), "{prompt}"); assert!(!prompt.contains(TOKEN_FILE) && !prompt.contains("token\":"), "{prompt}"); } @@ -976,7 +976,7 @@ mod tests { assert!(install(Client::Cursor, &launch, &env).is_err(), "no home folder: an error, not a panic"); } - // ---- connection file (Preferences › MCP) ---- + // ---- connection file (Preferences › AI Integrations) ---- #[test] fn a_published_connection_reads_back_in_the_documented_shape() { diff --git a/crates/automation/src/lib.rs b/crates/automation/src/lib.rs index 44e7d70ec0..47be6e0d8c 100644 --- a/crates/automation/src/lib.rs +++ b/crates/automation/src/lib.rs @@ -12,7 +12,7 @@ //! control protocol's envelope, used by `photocraft-cli serve`. //! * [`files`]: open/save any supported format, `.pcraft` natively. //! * [`agent_link`] and [`live`]: connecting agents to the desktop app without a terminal -//! (Edit › Preferences › MCP, `photocraft-cli mcp --live` and `mcp install`). +//! (Edit › Preferences › AI Integrations, `photocraft-cli mcp --live` and `mcp install`). //! //! L6, no UI-toolkit dependencies. #![forbid(unsafe_code)] diff --git a/crates/automation/src/live.rs b/crates/automation/src/live.rs index 67fddc43a8..c55f0a91c1 100644 --- a/crates/automation/src/live.rs +++ b/crates/automation/src/live.rs @@ -122,7 +122,7 @@ impl Live { } if Instant::now() >= deadline { return Err(format!( - "PhotoCraft didn't accept agents within {} s of starting. If it's still opening, try again in a moment; otherwise check Edit › Preferences › MCP.", + "PhotoCraft didn't accept agents within {} s of starting. If it's still opening, try again in a moment; otherwise check Edit › Preferences › AI Integrations.", self.cfg.launch_timeout.as_secs() )); } @@ -161,7 +161,7 @@ fn closed(integrations: &Integrations) -> String { if integrations.connect_agents { "PhotoCraft isn't running: open it, then try again.".into() } else { - "PhotoCraft doesn't accept AI agents: open it, turn on Edit › Preferences › MCP › Let AI agents connect, then try again.".into() + "PhotoCraft doesn't accept AI agents: open it, turn on Edit › Preferences › AI Integrations › Let AI agents connect, then try again.".into() } } diff --git a/crates/automation/tests/mcp_live.rs b/crates/automation/tests/mcp_live.rs index 14daa48e1a..81909d783a 100644 --- a/crates/automation/tests/mcp_live.rs +++ b/crates/automation/tests/mcp_live.rs @@ -1,4 +1,4 @@ -//! `photocraft-cli mcp --live` (Preferences › MCP): the MCP server finds the desktop +//! `photocraft-cli mcp --live` (Preferences › AI Integrations): the MCP server finds the desktop //! app through its connection file before every call, follows it to a new port and token, and //! applies the closed-app choice (start it, headless, or an error) when no app answers. diff --git a/crates/engine/src/prefs/cmds.rs b/crates/engine/src/prefs/cmds.rs index 564566fb8c..564306ecf5 100644 --- a/crates/engine/src/prefs/cmds.rs +++ b/crates/engine/src/prefs/cmds.rs @@ -189,7 +189,7 @@ pub fn specs() -> Vec { section!("edit.preferences.type", "Type…"), section!("edit.preferences.enhancedControls", "Enhanced Controls…"), section!("edit.preferences.rawDefaults", "RAW Defaults…"), - section!("edit.preferences.integrations", "MCP…"), + section!("edit.preferences.integrations", "Integrations…"), spec!( "edit.keyboardShortcuts", "Keyboard Shortcuts…", diff --git a/crates/engine/src/prefs/validate.rs b/crates/engine/src/prefs/validate.rs index d83a784720..771382084c 100644 --- a/crates/engine/src/prefs/validate.rs +++ b/crates/engine/src/prefs/validate.rs @@ -25,7 +25,7 @@ pub const SECTIONS: [(&str, &str); 18] = [ ("type", "Type"), ("enhancedControls", "Enhanced Controls"), ("rawDefaults", "RAW Defaults"), - ("integrations", "MCP"), + ("integrations", "Integrations"), ]; /// Preferences that nothing reads yet, so Edit › Preferences doesn't show them: a control that diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 220a4d6899..daa6caa8b2 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -460,7 +460,7 @@ pub struct PhotocraftApp { /// The first digit of a two-digit opacity typed on the number keys (`opacity_keys`, #352). pub(crate) opacity_keys: opacity_keys::Pending, control_rx: Option>, - /// Preferences › MCP: the agent connection's state (see [`Services::agent_link`]). + /// Preferences › AI Integrations: the agent connection's state (see [`Services::agent_link`]). pub agent_link: AgentLinkStatus, /// `ui.screenshot` requests: bounded admission, a weak-slot callback per issuance, monotonic /// deadlines and a capture-time geometry epoch (see `screenshot.rs`). diff --git a/crates/ui-egui/src/menu_catalog.rs b/crates/ui-egui/src/menu_catalog.rs index 3e67428731..d6db835eab 100644 --- a/crates/ui-egui/src/menu_catalog.rs +++ b/crates/ui-egui/src/menu_catalog.rs @@ -151,7 +151,7 @@ pub static CATALOG: &[(&[&str], &str, Option<&str>, &str)] = &[ (&["Edit"], "---", None, "---"), (&["Edit", "Preferences"], "General…", Some("Cmd+K"), "edit.preferences.general"), (&["Edit", "Preferences"], "---", None, "---"), - (&["Edit", "Preferences"], "MCP…", None, "edit.preferences.integrations"), + (&["Edit", "Preferences"], "AI Integrations…", None, "edit.preferences.integrations"), (&["Edit", "Preferences"], "Interface…", None, "edit.preferences.interface"), (&["Edit", "Preferences"], "Workspace…", None, "edit.preferences.workspace"), (&["Edit", "Preferences"], "Tools…", None, "edit.preferences.tools"), diff --git a/crates/ui-egui/src/preferences_submenu_tests.rs b/crates/ui-egui/src/preferences_submenu_tests.rs index 7b8ef7b143..7050d385c0 100644 --- a/crates/ui-egui/src/preferences_submenu_tests.rs +++ b/crates/ui-egui/src/preferences_submenu_tests.rs @@ -16,7 +16,7 @@ fn preferences_submenu_reads_in_the_reference_order_with_two_separators() { &labels[1..], [ "---", - "MCP…", + "AI Integrations…", "Interface…", "Workspace…", "Tools…", diff --git a/crates/ui-egui/src/prefs/prefs_ui/agents.rs b/crates/ui-egui/src/prefs/prefs_ui/agents.rs index d7dbf92986..2dbaa69cfd 100644 --- a/crates/ui-egui/src/prefs/prefs_ui/agents.rs +++ b/crates/ui-egui/src/prefs/prefs_ui/agents.rs @@ -1,4 +1,4 @@ -//! Preferences › MCP: the agent connection (`integrations.connectAgents`), the folders +//! Preferences › AI Integrations: the agent connection (`integrations.connectAgents`), the folders //! agents may use, what `photocraft-cli mcp --live` does while the app is closed, and the buttons //! that add PhotoCraft to MCP clients. Changes apply at once, without a restart. diff --git a/crates/ui-egui/src/prefs/prefs_ui/agents_tests.rs b/crates/ui-egui/src/prefs/prefs_ui/agents_tests.rs index 3e55459c0f..312b6bf4e6 100644 --- a/crates/ui-egui/src/prefs/prefs_ui/agents_tests.rs +++ b/crates/ui-egui/src/prefs/prefs_ui/agents_tests.rs @@ -1,4 +1,4 @@ -//! Preferences › MCP (`agents.rs`): the live agent connection and its buttons. +//! Preferences › AI Integrations (`agents.rs`): the live agent connection and its buttons. use super::tests::app_with_store; use super::*; diff --git a/crates/ui-egui/src/services.rs b/crates/ui-egui/src/services.rs index 5ed287b336..1741dcfd85 100644 --- a/crates/ui-egui/src/services.rs +++ b/crates/ui-egui/src/services.rs @@ -344,7 +344,7 @@ pub type AutomationCommandFn = Box Result<(), String>>; pub type AutomationAuthorizeFn = fn(&str, &Value) -> photocraft_engine::Result<()>; /// The automation half of [`Services`]: what control and MCP requests may read, write and run. -/// Replaced as a whole when Preferences › MCP starts the agent connection or +/// Replaced as a whole when Preferences › AI Integrations starts the agent connection or /// changes its folders ([`Services::set_automation`]). #[derive(Default)] pub struct AutomationServices { @@ -356,7 +356,7 @@ pub struct AutomationServices { pub authorize: Option, } -/// Preferences › MCP: the agent connection as the dialog and `ui.inspect` show it. +/// Preferences › AI Integrations: the agent connection as the dialog and `ui.inspect` show it. #[derive(Clone, Debug, Default, PartialEq, Eq, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct AgentLinkStatus { @@ -382,7 +382,7 @@ pub struct AgentLink { pub status: AgentLinkStatus, } -/// Starts, moves or stops the agent connection to match Preferences › MCP. +/// Starts, moves or stops the agent connection to match Preferences › AI Integrations. pub type AgentLinkFn = Box AgentLink>; /// Adds PhotoCraft to an MCP client (`claude-desktop`, `claude-code`, `cursor`), returning what /// was done, or returns the configuration to paste into any client (`json`). @@ -582,10 +582,10 @@ pub struct Services { /// each step of `actions.play`. Installed on the session only while a control request or /// an automation-driven [`PhotocraftApp::run`] runs, so a local play of a recorded `file.*` step still works. pub automation_authorize: Option, - /// Preferences › MCP (desktop): starts, moves or stops the agent connection when + /// Preferences › AI Integrations (desktop): starts, moves or stops the agent connection when /// its settings change. `None` on the web, and when `--control` manages the connection. pub agent_link: Option, - /// Preferences › MCP' buttons that add PhotoCraft to MCP clients (desktop). + /// Preferences › AI Integrations' buttons that add PhotoCraft to MCP clients (desktop). pub agent_clients: Option, /// Encode an RGBA8 image as PNG (used for screenshots and `ui.render`). pub encode_png: Option, diff --git a/docs/control-protocol.md b/docs/control-protocol.md index c3ed0c2e4f..cbaf2c224c 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -17,9 +17,9 @@ photocraft --control 7878 --control-token-file /private/path/photocraft-control. If the file does not exist, PhotoCraft creates it with a fresh 256-bit token. On Unix the new file is mode `0600`; on Windows, protect it with an appropriate user-only ACL. An existing file is reused. If neither a token nor token file is configured, PhotoCraft generates a token for that launch and writes it to standard error. `PHOTOCRAFT_CONTROL_TOKEN` and `PHOTOCRAFT_CONTROL_TOKEN_FILE` are the environment-variable equivalents. A flag wins over its variable and an empty variable counts as unset; with `--control` (or `PHOTOCRAFT_CONTROL_PORT`), a token together with a token file, from flags or variables, is a usage error (exit status 2). Without it no token is read, so the pair is ignored. -### Without `--control`: Preferences › MCP +### Without `--control`: Preferences › AI Integrations -An app started from the Dock, the Start menu or a file manager has no command line. Edit › Preferences › MCP starts and stops the control server while the app runs: turning *Let AI agents connect* on or off, or changing its port or folders, applies at once, with no restart. +An app started from the Dock, the Start menu or a file manager has no command line. Edit › Preferences › AI Integrations starts and stops the control server while the app runs: turning *Let AI agents connect* on or off, or changing its port or folders, applies at once, with no restart. | Preference | What it does | |---|---| @@ -418,7 +418,7 @@ magenta alignment lines. `ui.pointer` drives the same code, so agents get identi - **Headless** (`photocraft-cli mcp`): an in-process `photocraft_engine::Session`. There is no window. CPU composition is the default; `--gpu` or `PHOTOCRAFT_GPU=1` enables optional GPU rendering with automatic CPU fallback. - **Bridge** (`photocraft-cli mcp --bridge 127.0.0.1:7878 --control-token-file `): every tool is forwarded to a running `photocraft --control 7878 --control-token-file ` over this protocol, so agents see and drive the live app. Explicit `--gpu` / `--no-gpu` flags are rejected with a usage error because the desktop controls rendering; `PHOTOCRAFT_GPU` is ignored in bridge mode. `--bridge 7878` is short for `--bridge 127.0.0.1:7878`. With no `--bridge`, `PHOTOCRAFT_CONTROL_PORT` selects the bridge port (`127.0.0.1:`), and the CLI says so on standard error; with neither (or the variable empty), the MCP runs headless. A value that is not a port is a usage error naming the variable. `--automation-read-root` or `--automation-write-root` with the variable set is a usage error, since the bridge would drop the roots. -- **Live** (`photocraft-cli mcp --live`): the bridge, with the address and token read before every tool call from `agent-connection.json` in the app's settings folder. The app publishes that file while Edit › Preferences › MCP › *Let AI agents connect* is on (not with `--control`), and removes it when the connection stops; a file left by a crash fails the connection probe and counts as no app. See [MCP conventions](mcp.md#connecting-the-desktop-app-no-terminal). +- **Live** (`photocraft-cli mcp --live`): the bridge, with the address and token read before every tool call from `agent-connection.json` in the app's settings folder. The app publishes that file while Edit › Preferences › AI Integrations › *Let AI agents connect* is on (not with `--control`), and removes it when the connection stops; a file left by a crash fails the connection probe and counts as no app. See [MCP conventions](mcp.md#connecting-the-desktop-app-no-terminal). `ui.inspect` reports the connection as `agentLink`: `port` while agents can connect, `launchFlags` when `--control` manages it, `error`, and `mcpCommand` (how MCP clients start the CLI). @@ -488,7 +488,7 @@ One explicit write-root flag overrides `PHOTOCRAFT_AUTOMATION_WRITE_ROOT`. These variables are not supported by headless `photocraft-cli mcp` or `serve`; supply flags explicitly. In MCP bridge mode, configure roots on the desktop process. Supplying root flags to `photocraft-cli mcp --bridge` is a usage error; a bridge client cannot grant filesystem access. -With *Let AI agents connect*, the folders chosen in Preferences › MCP (`readRoot` / +With *Let AI agents connect*, the folders chosen in Preferences › AI Integrations (`readRoot` / `writeRoot`) are the agents' roots; `mcp --live` uses them for a headless session only when the app's *When PhotoCraft is closed* choice (or `--when-closed headless`) asks for one. diff --git a/docs/development.md b/docs/development.md index fb13a03492..d37f01acbe 100644 --- a/docs/development.md +++ b/docs/development.md @@ -324,7 +324,7 @@ At startup the desktop lists recovery metadata, then decodes one document at a t - **Headless:** `photocraft-cli mcp --automation-read-root --automation-read-root --automation-write-root `. It drives an in-process engine session with ordered read directories and one write directory. - **Live app:** start `photocraft --control 7878 --control-token-file --automation-read-root --automation-read-root --automation-write-root `, then run `photocraft-cli mcp --bridge 127.0.0.1:7878 --control-token-file `. The desktop process owns the roots; root flags on the bridging CLI are a usage error. See `docs/control-protocol.md#mcp-bridge`. -- **Live app, no flags:** turn on Edit › Preferences › MCP › Let AI agents connect, then point the MCP client at `photocraft-cli mcp --live` (the panel's buttons, or `photocraft-cli mcp install --client `, do it). The app publishes its port and token file in `agent-connection.json` in the settings folder; `--live` reads it on every call. See [MCP conventions](mcp.md#connecting-the-desktop-app-no-terminal). Test it against a scratch settings folder with `PHOTOCRAFT_CONFIG_DIR`, which both the app and the CLI honour. +- **Live app, no flags:** turn on Edit › Preferences › AI Integrations › Let AI agents connect, then point the MCP client at `photocraft-cli mcp --live` (the panel's buttons, or `photocraft-cli mcp install --client `, do it). The app publishes its port and token file in `agent-connection.json` in the settings folder; `--live` reads it on every call. See [MCP conventions](mcp.md#connecting-the-desktop-app-no-terminal). Test it against a scratch settings folder with `PHOTOCRAFT_CONFIG_DIR`, which both the app and the CLI honour. For headless MCP clients, pass absolute paths to deliberately chosen trusted workspace directories in the launch arguments. Desktop `PHOTOCRAFT_AUTOMATION_READ_ROOT` and `PHOTOCRAFT_AUTOMATION_WRITE_ROOT` environment variables do **not** grant headless CLI access. Omitting a root flag deliberately denies that direction of access. diff --git a/docs/mcp.md b/docs/mcp.md index b8ddbf6ebb..8ba0de9057 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2,7 +2,7 @@ ## Connecting the desktop app (no terminal) -1. In PhotoCraft, open **Edit › Preferences › MCP** and turn on **Let AI agents +1. In PhotoCraft, open **Edit › Preferences › AI Integrations** and turn on **Let AI agents connect (MCP)**. Optionally choose the folders agents can open from and save to, and what 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**. diff --git a/docs/roadmap.md b/docs/roadmap.md index e0b6e3516a..6ffcdcfd09 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -1,6 +1,6 @@ # Roadmap -> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-11-12 · **Change:** minor (M11: the desktop app connects to MCP clients from Edit › Preferences › MCP, no terminal, no restart; alpha gate, focus and estimates unchanged) · **Target:** Adobe Photoshop 2026 +> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-11-12 · **Change:** minor (M11: the desktop app connects to MCP clients from Edit › Preferences › AI Integrations, no terminal, no restart; alpha gate, focus and estimates unchanged) · **Target:** Adobe Photoshop 2026 - UI.5: Panels can detach, join other tab groups, split, resize and redock through shared docking transactions. Custom layouts persist with workspaces, respect workspace locking, and retain collapse flags for intact native groups. @@ -116,7 +116,7 @@ Each milestone has a **definition of done (DoD)** and must leave `main` green on | Date | Change | Summary | |---|---|---| -| 2026-11-12 | minor | M11: Edit › Preferences › MCP connects MCP clients to the running app without a terminal or restart; milestones, alpha gate and estimates unchanged | +| 2026-11-12 | minor | M11: Edit › Preferences › AI Integrations connects MCP clients to the running app without a terminal or restart; milestones, alpha gate and estimates unchanged | | 2026-10-11 | minor | Linked adaptive Unsharp Mask performance and quality evidence; milestones, alpha gate and estimates unchanged | | 2026-10-10 | minor | Photomerge is implemented; real-world quality validation remains open | | 2026-10-10 | minor | Alpha gate table (core-workflow gate): passes, stage stays alpha | diff --git a/docs/scorecard.md b/docs/scorecard.md index 69df97bbe8..f0c051c86b 100644 --- a/docs/scorecard.md +++ b/docs/scorecard.md @@ -274,7 +274,7 @@ Menu wiring (`docs/parity-checklist.md`): 664 of 664 menu items live (100.0%). T | AUTO-219-8 | xtask check that every panel button routes through a command id | partial | [#219](https://github.com/storytold/photocraft/issues/219) | cargo xtask panel-commands (run by xtask ci and CI) fails on a shell click handler that changes the document or session directly; 1 allowlisted function left (panels/color.rs color_field assigns the foreground/background colour instead of tools.setColors) | | AUTO-219-9 | Headless commands for in-canvas type editing, Liquify/Puppet strokes, transform handles | done | [#219](https://github.com/storytold/photocraft/issues/219) | type.hitTest, type.caret, type.navigate; filter.liquify strokes, edit.puppetWarp pins, type.edit, edit.transform | | AUTO-219-10 | Agent acceptance suite grown to 30-50 workflows | partial | [#219](https://github.com/storytold/photocraft/issues/219) | automation/tests/it/agent_tasks.rs runs 10 workflows over MCP | -| AUTO-MCP-LIVE | Connect an MCP client to the running app without a terminal (no flags, ports or tokens to copy) | done | | 2026-11-12 (#5525, #11363): Edit › Preferences › MCP › Let AI agents connect starts and stops the loopback control server while the app runs (no restart) and publishes agent-connection.json; photocraft-cli mcp --live finds the app on every call (launch / headless / error while it is closed); Add to Claude Desktop / Claude Code / Cursor, mcp install --client, and Copy Prompt for an Agent. automation/tests/mcp_live.rs, apps/photocraft/src/agent_link.rs tests | +| AUTO-MCP-LIVE | Connect an MCP client to the running app without a terminal (no flags, ports or tokens to copy) | done | | 2026-11-12 (#5525, #11363): Edit › Preferences › AI Integrations › Let AI agents connect starts and stops the loopback control server while the app runs (no restart) and publishes agent-connection.json; photocraft-cli mcp --live finds the app on every call (launch / headless / error while it is closed); Add to Claude Desktop / Claude Code / Cursor, mcp install --client, and Copy Prompt for an Agent. automation/tests/mcp_live.rs, apps/photocraft/src/agent_link.rs tests | ## Reliability diff --git a/packaging/macos/package.sh b/packaging/macos/package.sh index b3e8a0a6f2..ca64f30e82 100755 --- a/packaging/macos/package.sh +++ b/packaging/macos/package.sh @@ -120,7 +120,7 @@ echo "==> assembling $APP" mkdir -p "$APP/Contents/MacOS" "$APP/Contents/Resources" # Executable and icon carry the display name (CFBundleExecutable / CFBundleIconFile). cp "$WORK/bin/photocraft" "$APP/Contents/MacOS/PhotoCraft" -# The CLI too, beside the app: Preferences › MCP points MCP clients at it +# The CLI too, beside the app: Preferences › AI Integrations points MCP clients at it # (`photocraft-cli mcp --live`), and it starts the app when an agent needs it. cp "$WORK/bin/photocraft-cli" "$APP/Contents/MacOS/photocraft-cli" cp "$ROOT/assets/app-icon/photocraft.icns" "$APP/Contents/Resources/PhotoCraft.icns" diff --git a/scorecard/automation.toml b/scorecard/automation.toml index 2816d95346..22a198f870 100644 --- a/scorecard/automation.toml +++ b/scorecard/automation.toml @@ -85,4 +85,4 @@ note = "automation/tests/it/agent_tasks.rs runs 10 workflows over MCP" id = "AUTO-MCP-LIVE" target = "Connect an MCP client to the running app without a terminal (no flags, ports or tokens to copy)" status = "done" -note = "2026-11-12 (#5525, #11363): Edit › Preferences › MCP › Let AI agents connect starts and stops the loopback control server while the app runs (no restart) and publishes agent-connection.json; photocraft-cli mcp --live finds the app on every call (launch / headless / error while it is closed); Add to Claude Desktop / Claude Code / Cursor, mcp install --client, and Copy Prompt for an Agent. automation/tests/mcp_live.rs, apps/photocraft/src/agent_link.rs tests" +note = "2026-11-12 (#5525, #11363): Edit › Preferences › AI Integrations › Let AI agents connect starts and stops the loopback control server while the app runs (no restart) and publishes agent-connection.json; photocraft-cli mcp --live finds the app on every call (launch / headless / error while it is closed); Add to Claude Desktop / Claude Code / Cursor, mcp install --client, and Copy Prompt for an Agent. automation/tests/mcp_live.rs, apps/photocraft/src/agent_link.rs tests" From 1a63521c8bf9b12a966dd1ea28feb5333b0ff6ef Mon Sep 17 00:00:00 2001 From: David Mann Date: Thu, 12 Nov 2026 16:02:23 +0100 Subject: [PATCH 14/28] The agent settings wait for the suite's AI-MCP feature flag MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Preferences › AI Integrations shows the new agent settings (Let AI agents connect, the agent folders, When PhotoCraft is closed, the buttons that add PhotoCraft to MCP clients) only while the Craft suite's AI-MCP feature flag is on (craft-flags, storytold/craft-libs#1118: ArtCraft/flags.toml, which the ArtCraft Launcher's Experimental features switch writes, or CRAFT_FLAGS). Without it the page shows Allow Agent Control and Control Port as before, and a Control Port already set keeps its connection. craft-flags is pinned to the head of storytold/craft-libs#1119 until it merges. --- Cargo.lock | 57 +++++++++++++++++++ Cargo.toml | 3 + README.md | 2 +- apps/photocraft/Cargo.toml | 1 + apps/photocraft/src/main.rs | 11 +++- .../src/prefs/prefs_ui/agents_tests.rs | 20 +++++++ crates/ui-egui/src/prefs/prefs_ui/fields.rs | 13 +++++ crates/ui-egui/src/services.rs | 3 + docs/mcp.md | 5 ++ 9 files changed, 113 insertions(+), 2 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index d83eea4686..020ccb0c3d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1426,6 +1426,14 @@ dependencies = [ "libc", ] +[[package]] +name = "craft-atomic" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=d6d6835dc888a270a96a575fba58ab01abf6c122#d6d6835dc888a270a96a575fba58ab01abf6c122" +dependencies = [ + "rustix 1.1.5", +] + [[package]] name = "craft-docpath" version = "0.1.0" @@ -1447,6 +1455,16 @@ dependencies = [ "serde_json", ] +[[package]] +name = "craft-flags" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=d6d6835dc888a270a96a575fba58ab01abf6c122#d6d6835dc888a270a96a575fba58ab01abf6c122" +dependencies = [ + "craft-atomic", + "dirs", + "toml_edit", +] + [[package]] name = "craft-fonts-build" version = "0.1.0" @@ -1841,6 +1859,27 @@ dependencies = [ "crypto-common 0.2.2", ] +[[package]] +name = "dirs" +version = "7.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8d57d423b3c82e89b9a24ca3091fee61f456a26edbd28d26c65906f4bc1dcd8f" +dependencies = [ + "dirs-sys", +] + +[[package]] +name = "dirs-sys" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e01a3366d27ee9890022452ee61b2b63a67e6f13f58900b651ff5665f0bb1fab" +dependencies = [ + "libc", + "option-ext", + "redox_users", + "windows-sys 0.59.0", +] + [[package]] name = "dispatch" version = "0.2.0" @@ -5166,6 +5205,12 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7e036b411754132fd6b74e94b74e9a13c5cf606fa93d1885c35860d3060820b1" +[[package]] +name = "option-ext" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d" + [[package]] name = "orbclient" version = "0.3.55" @@ -5440,6 +5485,7 @@ dependencies = [ "chrono", "clap", "core-graphics2", + "craft-flags", "craft-update", "dispatch2", "eframe", @@ -6641,6 +6687,16 @@ dependencies = [ "bitflags 2.13.2", ] +[[package]] +name = "redox_users" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60dc65c0ff1a7ae1294b0c67b9f14baf70b644404010370171787bfac1038fc0" +dependencies = [ + "libredox", + "thiserror 2.0.21", +] + [[package]] name = "ref-cast" version = "1.0.27" @@ -8223,6 +8279,7 @@ dependencies = [ "indexmap", "toml_datetime", "toml_parser", + "toml_writer", "winnow", ] diff --git a/Cargo.toml b/Cargo.toml index 5068387eec..7f2e5cb631 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -11,6 +11,9 @@ rust-version = "1.95" [workspace.dependencies] craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b", features = ["serde"] } +# Feature flags shared with the launcher and the other Craft apps (craft-libs#1118). Pinned to the +# pull request head craft-libs#1119 until it merges; re-pin then. +craft-flags = { git = "https://github.com/storytold/craft-libs", rev = "d6d6835dc888a270a96a575fba58ab01abf6c122" } # internal photocraft-geom = { path = "crates/geom" } photocraft-color = { path = "crates/color" } diff --git a/README.md b/README.md index eb577fded0..9bd0c6c101 100644 --- a/README.md +++ b/README.md @@ -246,7 +246,7 @@ photocraft-cli batch --help photocraft-cli mcp ``` -To let Claude or another AI app drive the open PhotoCraft window without a terminal, turn on **Edit › Preferences › AI Integrations › Let AI agents connect**, then click **Add to Claude Desktop** (or Claude Code, or Cursor) in the same panel. See [`docs/mcp.md`](docs/mcp.md). +To let Claude or another AI app drive the open PhotoCraft window without a terminal, turn on **Edit › Preferences › AI Integrations › Let AI agents connect**, then click **Add to Claude Desktop** (or Claude Code, or Cursor) in the same panel. See [`docs/mcp.md`](docs/mcp.md). These settings are behind the Craft suite's `AI-MCP` feature flag: turn it on in ArtCraft Launcher › Settings › Experimental features, or start PhotoCraft with `CRAFT_FLAGS=AI-MCP`. The desktop app also offers an authenticated, loopback-only control channel (`photocraft --control`) for inspecting UI state, driving tools with pointer events, and taking offscreen screenshots. Every image in this README was rendered that way. See [`docs/control-protocol.md`](docs/control-protocol.md). diff --git a/apps/photocraft/Cargo.toml b/apps/photocraft/Cargo.toml index 413002248a..a9a11046b9 100644 --- a/apps/photocraft/Cargo.toml +++ b/apps/photocraft/Cargo.toml @@ -27,6 +27,7 @@ photocraft-io = { workspace = true } photocraft-format = { workspace = true } photocraft-automation = { workspace = true } photocraft-ui-egui = { workspace = true } +craft-flags = { workspace = true } # Pen tablet pressure/tilt on macOS and X11 (the workspace's one isolated unsafe helper crate). photocraft-tablet = { workspace = true } eframe = { workspace = true, features = ["wgpu", "accesskit", "wayland", "x11", "persistence", "clipboard"] } diff --git a/apps/photocraft/src/main.rs b/apps/photocraft/src/main.rs index a8e17411eb..f259ad7d25 100644 --- a/apps/photocraft/src/main.rs +++ b/apps/photocraft/src/main.rs @@ -723,7 +723,16 @@ fn main() -> eframe::Result { // flags (`--control`) manage the connection. let mcp = agent_link::mcp_launch(); app.agent_link.mcp_command = mcp.as_ref().map(photocraft_automation::agent_link::McpLaunch::shell_line); - app.services.agent_clients = Some(agent_link::clients(mcp.clone())); + // The new agent settings and the buttons that add PhotoCraft to MCP clients are behind + // the suite's AI-MCP feature flag; the connection itself keeps working as before. + let flags = craft_flags::load(); + for problem in &flags.problems { + log::warn!("feature flags: {problem}"); + } + app.agent_link.mcp_flag = flags.enabled(&craft_flags::AI_MCP); + if app.agent_link.mcp_flag { + app.services.agent_clients = Some(agent_link::clients(mcp.clone())); + } if let Some((listener, token, _)) = control { app.agent_link.launch_flags = true; app.agent_link.port = listener.local_addr().ok().map(|a| a.port()); diff --git a/crates/ui-egui/src/prefs/prefs_ui/agents_tests.rs b/crates/ui-egui/src/prefs/prefs_ui/agents_tests.rs index 312b6bf4e6..cef92ee389 100644 --- a/crates/ui-egui/src/prefs/prefs_ui/agents_tests.rs +++ b/crates/ui-egui/src/prefs/prefs_ui/agents_tests.rs @@ -62,6 +62,7 @@ fn ai_integrations_offer_the_client_buttons_only_when_agents_may_connect() { seen.lock().unwrap().push(id.to_string()); Ok(format!("Added PhotoCraft to {id}.")) })); + app.agent_link.mcp_flag = true; 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()); @@ -90,6 +91,25 @@ fn ai_integrations_offer_the_client_buttons_only_when_agents_may_connect() { assert!(h.query_by_label("Add to Cursor").is_none()); } +/// Without the suite's AI-MCP feature flag the page shows only the settings it had before. +#[test] +fn ai_integrations_without_the_mcp_flag_show_only_the_earlier_settings() { + use egui_kittest::{Harness, kittest::Queryable}; + let (mut app, _) = app_with_store(); + app.services.agent_clients = Some(Box::new(|_: &str| Ok(String::new()))); + app.agent_link.mcp_flag = false; + 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("Let AI agents connect (MCP)").is_none(), "the new connection switch waits for the flag"); + assert!(h.query_by_label("Folder agents can open from").is_none()); + assert!(h.query_by_label("Add to Claude Desktop").is_none()); + assert!(h.query_by_label("Allow agent control").is_some(), "the earlier setting stays"); +} + #[test] fn ai_integrations_choices_and_paths_validate_through_prefs_set() { let (mut app, _) = app_with_store(); diff --git a/crates/ui-egui/src/prefs/prefs_ui/fields.rs b/crates/ui-egui/src/prefs/prefs_ui/fields.rs index 5b4574a1bd..5e2e925372 100644 --- a/crates/ui-egui/src/prefs/prefs_ui/fields.rs +++ b/crates/ui-egui/src/prefs/prefs_ui/fields.rs @@ -268,10 +268,19 @@ fn prefs_body(ui: &mut egui::Ui, f: &mut Map, system: Option = + obj.iter().filter(|(k, _)| LEGACY_INTEGRATIONS.contains(&k.as_str())).map(|(k, v)| (k.clone(), v.clone())).collect(); + section_fields(ui, §ion, &mut shown, &order, lang, system, filter); + obj.extend(shown); } else if let Some(obj) = values.get_mut(§ion).and_then(Value::as_object_mut) { section_fields(ui, §ion, obj, &order, lang, system, filter); if section == "fileHandling" { @@ -392,6 +401,10 @@ fn interface_groups(ui: &mut egui::Ui, obj: &mut Map, keys: &[Str /// Where a clicked colour swatch leaves its preference path and label for the dialog body, which /// holds the fields the Color Picker request goes in. +/// Preferences › AI Integrations without the AI-MCP feature flag: the settings PhotoCraft had +/// before the agent connection page. +const LEGACY_INTEGRATIONS: [&str; 2] = ["allowAgentControl", "controlPort"]; + const PICK_ID: &str = "prefs-pick-color"; /// The colour swatch clicked this frame, if any: (preference path, label). diff --git a/crates/ui-egui/src/services.rs b/crates/ui-egui/src/services.rs index 1741dcfd85..53aa83501c 100644 --- a/crates/ui-egui/src/services.rs +++ b/crates/ui-egui/src/services.rs @@ -368,6 +368,9 @@ pub struct AgentLinkStatus { pub error: Option, /// How an MCP client starts PhotoCraft's MCP server (`photocraft-cli mcp --live`). pub mcp_command: Option, + /// The suite's `AI-MCP` feature flag (`craft-flags`): without it the page shows only the + /// connection settings PhotoCraft had before (Allow Agent Control, Control Port). + pub mcp_flag: bool, } /// What [`Services::agent_link`] did after the MCP settings changed. diff --git a/docs/mcp.md b/docs/mcp.md index 8ba0de9057..cc440ba629 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2,6 +2,11 @@ ## Connecting the desktop app (no terminal) +These settings are behind the Craft suite's `AI-MCP` feature flag (`craft-flags`): turn it on in +ArtCraft Launcher › Settings › Experimental features, which writes `ArtCraft/flags.toml` for every +Craft app, or start PhotoCraft with `CRAFT_FLAGS=AI-MCP`. Without it the page shows only Allow +Agent Control and Control Port, as before; a Control Port already set keeps its connection. + 1. In PhotoCraft, open **Edit › Preferences › AI Integrations** and turn on **Let AI agents connect (MCP)**. Optionally choose the folders agents can open from and save to, and what happens when an agent needs PhotoCraft while it is closed (open it, work without a window, From 17337739fbd9ede910dcdcfc7cc633933add3796 Mon Sep 17 00:00:00 2001 From: David Mann Date: Thu, 12 Nov 2026 16:14:27 +0100 Subject: [PATCH 15/28] build: pin craft-flags to its merge in craft-libs (86d6e8c5) --- Cargo.lock | 4 ++-- Cargo.toml | 5 ++--- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 020ccb0c3d..5ea10652e8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1429,7 +1429,7 @@ dependencies = [ [[package]] name = "craft-atomic" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d6d6835dc888a270a96a575fba58ab01abf6c122#d6d6835dc888a270a96a575fba58ab01abf6c122" +source = "git+https://github.com/storytold/craft-libs?rev=86d6e8c5b05a4dadc35ff1c8e5d2f992c687ee97#86d6e8c5b05a4dadc35ff1c8e5d2f992c687ee97" dependencies = [ "rustix 1.1.5", ] @@ -1458,7 +1458,7 @@ dependencies = [ [[package]] name = "craft-flags" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d6d6835dc888a270a96a575fba58ab01abf6c122#d6d6835dc888a270a96a575fba58ab01abf6c122" +source = "git+https://github.com/storytold/craft-libs?rev=86d6e8c5b05a4dadc35ff1c8e5d2f992c687ee97#86d6e8c5b05a4dadc35ff1c8e5d2f992c687ee97" dependencies = [ "craft-atomic", "dirs", diff --git a/Cargo.toml b/Cargo.toml index 7f2e5cb631..476498d400 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -11,9 +11,8 @@ rust-version = "1.95" [workspace.dependencies] craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b", features = ["serde"] } -# Feature flags shared with the launcher and the other Craft apps (craft-libs#1118). Pinned to the -# pull request head craft-libs#1119 until it merges; re-pin then. -craft-flags = { git = "https://github.com/storytold/craft-libs", rev = "d6d6835dc888a270a96a575fba58ab01abf6c122" } +# Feature flags shared with the launcher and the other Craft apps (craft-libs#1118, #1119). +craft-flags = { git = "https://github.com/storytold/craft-libs", rev = "86d6e8c5b05a4dadc35ff1c8e5d2f992c687ee97" } # internal photocraft-geom = { path = "crates/geom" } photocraft-color = { path = "crates/color" } From d0f01a515ea7209bdee2ccf96004f20187a343af Mon Sep 17 00:00:00 2001 From: David Mann Date: Thu, 12 Nov 2026 20:02:54 +0100 Subject: [PATCH 16/28] The ArtCraft Launcher's agents switch lets agents in Turning on ArtCraft Launcher > Settings > AI agents is the person's consent for every Craft app (craft-ai-integrations#195). While the AI-MCP flag is on and the launcher's app list (ArtCraft/mcp/apps.json) names photocraft, PhotoCraft accepts agents as if Let AI agents connect were ticked: the desktop app watches those files every 2 s and starts or stops the connection, and `mcp --live` checks them before every call. The page shows the box ticked and says the launcher turned it on; PhotoCraft's own choice is kept. Allow Agent Control off still refuses agents. Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 2 + apps/photocraft/src/agent_link.rs | 28 +++++++ apps/photocraft/src/main.rs | 2 + book/src/security/automation-security.md | 2 +- crates/automation/Cargo.toml | 3 + crates/automation/src/agent_link.rs | 81 +++++++++++++++++++ crates/automation/src/live.rs | 37 ++++++--- crates/automation/tests/mcp_live.rs | 15 ++++ crates/ui-egui/src/prefs/prefs_ui/agents.rs | 20 ++++- .../src/prefs/prefs_ui/agents_tests.rs | 35 ++++++++ crates/ui-egui/src/services.rs | 7 ++ docs/control-protocol.md | 2 +- docs/mcp.md | 10 +++ 13 files changed, 228 insertions(+), 16 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 5ea10652e8..a725a21b88 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5562,7 +5562,9 @@ dependencies = [ "base64 0.23.1", "cap-std", "clap", + "craft-flags", "craft-psd", + "dirs", "getrandom 0.3.4", "hmac", "photocraft-codecs", diff --git a/apps/photocraft/src/agent_link.rs b/apps/photocraft/src/agent_link.rs index 7cc2e563d3..f9f447edf9 100644 --- a/apps/photocraft/src/agent_link.rs +++ b/apps/photocraft/src/agent_link.rs @@ -111,6 +111,34 @@ fn apply(running: &mut Option, dir: Option<&Path>, integrations: &Integ out } +/// How often [`launcher_watch`] looks at the ArtCraft Launcher's files. +const LAUNCHER_POLL: std::time::Duration = std::time::Duration::from_secs(2); + +/// Whether the ArtCraft Launcher turned agents on for every Craft app +/// ([`agent_link::launcher_allows_agents`]), watched on its own thread so the UI can ask every +/// frame without touching the disk. A change wakes the UI, which then starts or stops the +/// connection. Without a thread (one couldn't be started) the answer stays what it was at launch. +pub fn launcher_watch(ctx: &egui::Context) -> Box bool> { + use std::sync::Arc; + use std::sync::atomic::{AtomicBool, Ordering}; + let on = Arc::new(AtomicBool::new(agent_link::launcher_allows_agents())); + let (seen, ctx) = (on.clone(), ctx.clone()); + let started = std::thread::Builder::new().name("launcher-agents".into()).spawn(move || { + loop { + std::thread::sleep(LAUNCHER_POLL); + let now = agent_link::launcher_allows_agents(); + if seen.swap(now, Ordering::Relaxed) != now { + log::info!("ArtCraft Launcher: agents {}", if now { "on" } else { "off" }); + ctx.request_repaint(); + } + } + }); + if let Err(e) = started { + log::warn!("couldn't watch the ArtCraft Launcher's agents switch: {e}"); + } + Box::new(move || on.load(Ordering::Relaxed)) +} + /// How MCP clients start this install's CLI (`photocraft-cli mcp --live`), or `None` when it /// isn't installed beside the app (a development build of the app alone). pub fn mcp_launch() -> Option { diff --git a/apps/photocraft/src/main.rs b/apps/photocraft/src/main.rs index f259ad7d25..7ff5a50a8e 100644 --- a/apps/photocraft/src/main.rs +++ b/apps/photocraft/src/main.rs @@ -732,6 +732,8 @@ fn main() -> eframe::Result { app.agent_link.mcp_flag = flags.enabled(&craft_flags::AI_MCP); if app.agent_link.mcp_flag { app.services.agent_clients = Some(agent_link::clients(mcp.clone())); + // ArtCraft Launcher › Settings › AI agents turns agents on for every Craft app. + app.services.launcher_agents = Some(agent_link::launcher_watch(&cc.egui_ctx)); } if let Some((listener, token, _)) = control { app.agent_link.launch_flags = true; diff --git a/book/src/security/automation-security.md b/book/src/security/automation-security.md index 000a091d75..bf7549f614 100644 --- a/book/src/security/automation-security.md +++ b/book/src/security/automation-security.md @@ -29,7 +29,7 @@ Automation is a privilege boundary because requests can cause filesystem access, Screenshots are decoded under separate dimension, pixel, and allocation ceilings before downscaling; the 5 MiB PNG limit applies to the returned image. - MCP normally uses stdio and can optionally bridge to loopback control TCP. -- Edit › Preferences › AI Integrations › *Let AI agents connect* (off by default) opens that loopback +- Edit › Preferences › AI Integrations › *Let AI agents connect* (off by default), or ArtCraft Launcher › Settings › AI agents for every Craft app, opens that loopback listener without launch flags. Its token is kept in a user-only file in the settings folder (`agent-control.token`) and stays the same across restarts and port changes: restarting does not revoke it. To revoke an exposed token, delete that file; the next start creates a new one. diff --git a/crates/automation/Cargo.toml b/crates/automation/Cargo.toml index c03900b66e..af29a68b35 100644 --- a/crates/automation/Cargo.toml +++ b/crates/automation/Cargo.toml @@ -39,6 +39,9 @@ hmac = "0.12" sha2 = "0.10" cap-std = "4" clap = { workspace = true } +# The suite's AI-MCP flag and the ArtCraft Launcher's folder: the launcher's agents switch counts as consent. +craft-flags = { workspace = true } +dirs = "7" # Optional native GPU rendering backend photocraft-gpu = { workspace = true, optional = true } diff --git a/crates/automation/src/agent_link.rs b/crates/automation/src/agent_link.rs index 9cfd4ae8d3..d7ebbf7fe2 100644 --- a/crates/automation/src/agent_link.rs +++ b/crates/automation/src/agent_link.rs @@ -186,6 +186,51 @@ pub fn read_integrations(dir: &Path) -> Integrations { .unwrap_or_default() } +// ---- ArtCraft Launcher -------------------------------------------------------------------------- + +/// The id the ArtCraft Launcher lists PhotoCraft under in its app list. +pub const LAUNCHER_APP_ID: &str = "photocraft"; +/// The launcher's app list for the MCP gateway (storytold/craft-ai-integrations, +/// `docs/CRAFT-AI-MCP.md`). The launcher writes it when Settings › AI agents › *Let AI agents use +/// Craft apps* is turned on and removes it when that is turned off. +pub const LAUNCHER_APPS_FILE: &str = "apps.json"; +/// Moves the launcher's folder, as it does for the launcher and the gateway. +pub const LAUNCHER_DIR_ENV: &str = "CRAFT_MCP_DIR"; +/// Version of the launcher's app list this reads. +const LAUNCHER_APPS_VERSION: u64 = 1; + +/// The launcher's folder: [`LAUNCHER_DIR_ENV`], otherwise `ArtCraft/mcp` in the per-user local +/// configuration folder, where the launcher writes it and the gateway reads it. +pub fn launcher_dir(env: impl Fn(&str) -> Option) -> Option { + match env(LAUNCHER_DIR_ENV) { + Some(d) if !d.is_empty() => Some(PathBuf::from(d)), + _ => dirs::config_local_dir().map(|b| b.join("ArtCraft").join("mcp")), + } +} + +/// Whether the launcher's app list in `dir` names PhotoCraft. A list that is missing, too big, +/// not JSON or of another version counts as no. +pub fn launcher_lists_photocraft(dir: &Path) -> bool { + let Some(text) = read_small(&dir.join(LAUNCHER_APPS_FILE)).ok().flatten() else { return false }; + let Ok(list) = serde_json::from_str::(&text) else { return false }; + list.get("version").and_then(Value::as_u64) == Some(LAUNCHER_APPS_VERSION) + && list.get("apps").and_then(Value::as_array).is_some_and(|apps| apps.iter().any(|a| a.get("id").and_then(Value::as_str) == Some(LAUNCHER_APP_ID))) +} + +/// The person turned agents on for every Craft app in the ArtCraft Launcher: the suite's `AI-MCP` +/// flag is on and the launcher's app list names PhotoCraft. That switch is their consent, as +/// *Let AI agents connect* is (storytold/craft-ai-integrations#195), so PhotoCraft accepts agents +/// without its own box ticked. Reads two small files; call it from a timer, not every frame. +pub fn launcher_allows_agents() -> bool { + craft_flags::load().enabled(&craft_flags::AI_MCP) && launcher_dir(|k| std::env::var_os(k)).is_some_and(|d| launcher_lists_photocraft(&d)) +} + +/// Agents may connect: *Let AI agents connect* is on, or the launcher turned agents on +/// ([`launcher_allows_agents`]). Allow Agent Control off still refuses both. +pub fn agents_allowed(integrations: &Integrations, launcher: bool) -> bool { + integrations.connect_agents || launcher +} + // ---- MCP clients -------------------------------------------------------------------------------- /// How an MCP client starts PhotoCraft's MCP server. @@ -646,6 +691,42 @@ mod tests { } } + #[test] + fn the_launcher_list_counts_only_when_it_names_photocraft() { + let dir = temp("launcher"); + assert!(!launcher_lists_photocraft(&dir), "no list: the launcher's switch is off"); + let write = |text: &str| std::fs::write(dir.join(LAUNCHER_APPS_FILE), text).unwrap(); + write(r#"{"version":1,"apps":[{"id":"filmcraft","command":"/x","args":["mcp"]},{"id":"photocraft","command":"/y"}]}"#); + assert!(launcher_lists_photocraft(&dir)); + write(r#"{"version":1,"apps":[{"id":"filmcraft","command":"/x"}]}"#); + assert!(!launcher_lists_photocraft(&dir), "PhotoCraft isn't in the list"); + write(r#"{"version":2,"apps":[{"id":"photocraft","command":"/y"}]}"#); + assert!(!launcher_lists_photocraft(&dir), "another version"); + write(r#"{"version":1,"apps":{"id":"photocraft"}}"#); + assert!(!launcher_lists_photocraft(&dir), "apps not a list"); + write("not json"); + assert!(!launcher_lists_photocraft(&dir)); + std::fs::remove_file(dir.join(LAUNCHER_APPS_FILE)).unwrap(); + std::fs::create_dir(dir.join(LAUNCHER_APPS_FILE)).unwrap(); + assert!(!launcher_lists_photocraft(&dir), "a folder in its place"); + } + + #[test] + fn the_launcher_folder_follows_its_override() { + let at = |v: &str| launcher_dir(|k| (k == LAUNCHER_DIR_ENV).then(|| v.into())); + assert_eq!(at("/portable/mcp"), Some(PathBuf::from("/portable/mcp"))); + assert_eq!(at(""), dirs::config_local_dir().map(|b| b.join("ArtCraft").join("mcp")), "empty means unset"); + } + + #[test] + fn either_switch_lets_agents_in() { + let mut i = Integrations::default(); + assert!(!agents_allowed(&i, false)); + assert!(agents_allowed(&i, true), "the launcher's switch alone"); + i.connect_agents = true; + assert!(agents_allowed(&i, false), "PhotoCraft's box alone"); + } + #[test] fn connection_round_trips_and_only_its_writer_removes_it() { let dir = temp("conn"); diff --git a/crates/automation/src/live.rs b/crates/automation/src/live.rs index c55f0a91c1..894d82234f 100644 --- a/crates/automation/src/live.rs +++ b/crates/automation/src/live.rs @@ -12,7 +12,7 @@ use std::path::{Path, PathBuf}; use std::sync::{Arc, Mutex, PoisonError}; use std::time::{Duration, Instant}; -use photocraft_engine::prefs::{Integrations, WhenAppClosed}; +use photocraft_engine::prefs::WhenAppClosed; use crate::agent_link::{self, Connection, PROBE_TIMEOUT}; use crate::bridge::BridgeClient; @@ -39,11 +39,22 @@ pub struct LiveConfig { /// Starts the app; `None` when this install can't (Flatpak sandbox, no app beside the CLI). pub launch: Option, pub launch_timeout: Duration, + /// Whether the ArtCraft Launcher turned agents on for every Craft app + /// ([`agent_link::launcher_allows_agents`]); tests replace it. + pub launcher_allows: fn() -> bool, } impl LiveConfig { pub fn new(config_dir: PathBuf) -> Self { - LiveConfig { config_dir, when_closed: None, read_root: None, write_root: None, launch: None, launch_timeout: LAUNCH_TIMEOUT } + LiveConfig { + config_dir, + when_closed: None, + read_root: None, + write_root: None, + launch: None, + launch_timeout: LAUNCH_TIMEOUT, + launcher_allows: agent_link::launcher_allows_agents, + } } } @@ -86,13 +97,15 @@ impl Live { return Ok(()); } let dir = self.cfg.config_dir.clone(); - let (found, integrations) = blocking(move || (find_app(&dir), agent_link::read_integrations(&dir))).await?; + let launcher_allows = self.cfg.launcher_allows; + let (found, integrations, launcher) = blocking(move || (find_app(&dir), agent_link::read_integrations(&dir), launcher_allows())).await?; + let allowed = agent_link::agents_allowed(&integrations, launcher); if let Some((c, token)) = found? { self.use_app(&c, token)?; return Ok(()); } match self.cfg.when_closed.unwrap_or(integrations.when_app_closed) { - WhenAppClosed::Error => Err(closed(&integrations)), + WhenAppClosed::Error => Err(closed(allowed)), WhenAppClosed::Headless => { let read = self.cfg.read_root.clone().or_else(|| agent_link::folder(&integrations.read_root)); let write = self.cfg.write_root.clone().or_else(|| agent_link::folder(&integrations.write_root)); @@ -101,13 +114,15 @@ impl Live { self.set(Target::Headless(Arc::new(Mutex::new(Headless::with_workspace(workspace)))), None); Ok(()) } - WhenAppClosed::Launch => self.launch_and_wait(&integrations).await, + WhenAppClosed::Launch => self.launch_and_wait(allowed).await, } } - async fn launch_and_wait(&self, integrations: &Integrations) -> Result<(), String> { - if !integrations.connect_agents { - return Err(closed(integrations)); + /// `allowed`: agents may connect ([`agent_link::agents_allowed`]); otherwise the app would never + /// listen, so it isn't started. + async fn launch_and_wait(&self, allowed: bool) -> Result<(), String> { + if !allowed { + return Err(closed(false)); } let Some(launch) = &self.cfg.launch else { return Err("PhotoCraft isn't running, and this install can't start it from here: open PhotoCraft, then try again.".into()); @@ -157,11 +172,11 @@ fn find_app(dir: &Path) -> Result, String> { Ok(Some((c, token))) } -fn closed(integrations: &Integrations) -> String { - if integrations.connect_agents { +fn closed(allowed: bool) -> String { + if allowed { "PhotoCraft isn't running: open it, then try again.".into() } else { - "PhotoCraft doesn't accept AI agents: open it, turn on Edit › Preferences › AI Integrations › Let AI agents connect, then try again.".into() + "PhotoCraft doesn't accept AI agents: open it, turn on Edit › Preferences › AI Integrations › Let AI agents connect (or ArtCraft Launcher › Settings › AI agents), then try again.".into() } } diff --git a/crates/automation/tests/mcp_live.rs b/crates/automation/tests/mcp_live.rs index 81909d783a..f696db8e5b 100644 --- a/crates/automation/tests/mcp_live.rs +++ b/crates/automation/tests/mcp_live.rs @@ -125,6 +125,8 @@ fn live(dir: &Path, when_closed: Option) -> LiveConfig { let mut c = LiveConfig::new(dir.to_path_buf()); c.when_closed = when_closed; c.launch_timeout = Duration::from_secs(10); + // The machine's own ArtCraft Launcher settings stay out of the tests. + c.launcher_allows = || false; c } @@ -202,6 +204,19 @@ async fn launch_starts_the_app_once_and_only_when_agents_may_connect() { assert_eq!(launches.load(Ordering::SeqCst), 0); client.cancel().await.unwrap(); + // The ArtCraft Launcher's switch alone is consent: the app is started without its own box. + let mut c = config(&dir); + c.launcher_allows = || true; + let client = connect(PhotocraftMcp::live(c)).await; + let r = call(&client, "ui_inspect", json!({})).await; + assert_eq!(r.is_error, Some(false), "{}", text(&r)); + assert_eq!(launches.load(Ordering::SeqCst), 1); + client.cancel().await.unwrap(); + for app in apps.lock().unwrap().drain(..) { + quit(app); + } + launches.store(0, Ordering::SeqCst); + prefs(&dir, json!({"connectAgents": true})); let client = connect(PhotocraftMcp::live(config(&dir))).await; // Two calls at once start one app. diff --git a/crates/ui-egui/src/prefs/prefs_ui/agents.rs b/crates/ui-egui/src/prefs/prefs_ui/agents.rs index 2dbaa69cfd..60ea2d5aaa 100644 --- a/crates/ui-egui/src/prefs/prefs_ui/agents.rs +++ b/crates/ui-egui/src/prefs/prefs_ui/agents.rs @@ -12,10 +12,15 @@ pub(super) const AGENT_LINK_RETRY_S: f64 = 5.0; /// Start, move or stop the agent connection when its settings change /// ([`crate::Services::agent_link`]); the first frame applies the saved settings. A connection /// that is on but failed to start is tried again every [`AGENT_LINK_RETRY_S`], so freeing its -/// port is enough, without touching a setting. +/// port is enough, without touching a setting. The ArtCraft Launcher's agents switch +/// ([`crate::Services::launcher_agents`]) counts as the box ticked: the person turned agents on for +/// every Craft app there. pub(super) fn sync_agent_link(app: &mut PhotocraftApp, ctx: &egui::Context) { + let launcher = app.services.launcher_agents.as_ref().is_some_and(|on| on()); let Some(link) = app.services.agent_link.as_mut() else { return }; - let current = &app.session.prefs().integrations; + let mut effective = app.session.prefs().integrations.clone(); + effective.connect_agents |= launcher; + let current = &effective; let now = crate::gpu_canvas::now_ms() / 1000.0; let retry_due = app.prefs_rt.agent_link_retry.is_some_and(|at| now >= at); if app.prefs_rt.agent_link.as_ref() == Some(current) && !retry_due { @@ -39,6 +44,7 @@ pub(super) fn sync_agent_link(app: &mut PhotocraftApp, ctx: &egui::Context) { // do with `--control` (`PhotocraftApp::new`); the gate stays once agents have connected. app.session.automation_gate = app.session.automation_gate.or(app.services.automation_authorize); app.agent_link = update.status; + app.agent_link.launcher = launcher; } /// The rows of the section. A button click is left in `f["__agentAction"]` for [`agent_action`]. @@ -46,10 +52,18 @@ pub(super) fn integration_rows(ui: &mut egui::Ui, obj: &mut Map, let t = Tokens::get(ui.ctx()); let status = f.get("__agentLink").cloned().unwrap_or(Value::Null); let launch_flags = status.get("launchFlags").and_then(Value::as_bool) == Some(true); + let launcher = status.get("launcher").and_then(Value::as_bool) == Some(true); let mut on = obj.get("connectAgents").and_then(Value::as_bool).unwrap_or(false); let label = humanize("connectAgents"); - ui.add_enabled_ui(!launch_flags, |ui| crate::widgets::checkbox(ui, &mut on, tl!(&label))); + if launcher && !launch_flags { + // On for the whole suite: shown ticked, and PhotoCraft's own choice is kept as it was. + ui.add_enabled_ui(false, |ui| crate::widgets::checkbox(ui, &mut true, tl!(&label))); + ui.label(RichText::new(tl!("Turned on in ArtCraft Launcher › Settings › AI agents, for every Craft app.")).color(t.text_dim)); + } else { + ui.add_enabled_ui(!launch_flags, |ui| crate::widgets::checkbox(ui, &mut on, tl!(&label))); + } obj.insert("connectAgents".into(), json!(on)); + let on = on || launcher; ui.label( RichText::new(tl!("AI apps such as Claude can then open, edit and save documents here. Only programs on this computer can connect.")).color(t.text_dim), ); diff --git a/crates/ui-egui/src/prefs/prefs_ui/agents_tests.rs b/crates/ui-egui/src/prefs/prefs_ui/agents_tests.rs index cef92ee389..eea34c3d84 100644 --- a/crates/ui-egui/src/prefs/prefs_ui/agents_tests.rs +++ b/crates/ui-egui/src/prefs/prefs_ui/agents_tests.rs @@ -50,6 +50,41 @@ fn ai_integrations_start_and_stop_the_agent_connection_through_the_service() { assert!(crate::control::inspect(&app, &ctx).get("agentLink").is_some()); } +/// The ArtCraft Launcher's agents switch counts as the box ticked, and turning it off there stops +/// the connection again; PhotoCraft's own saved choice is never changed by it. +#[test] +fn the_launcher_switch_turns_the_agent_connection_on_without_the_box() { + use std::sync::atomic::{AtomicBool, Ordering}; + let (mut app, _) = app_with_store(); + let ctx = egui::Context::default(); + let calls: Arc>> = Arc::default(); + let seen = calls.clone(); + app.services.agent_link = Some(Box::new(move |p: &prefs::Integrations, _: &egui::Context| { + seen.lock().unwrap().push(p.connect_agents); + crate::AgentLink { + stopped: !p.connect_agents, + status: crate::AgentLinkStatus { port: p.connect_agents.then_some(4321), ..Default::default() }, + ..Default::default() + } + })); + let launcher = Arc::new(AtomicBool::new(false)); + let on = launcher.clone(); + app.services.launcher_agents = Some(Box::new(move || on.load(Ordering::Relaxed))); + tick(&mut app, &ctx); + assert_eq!(*calls.lock().unwrap(), [false]); + launcher.store(true, Ordering::Relaxed); + tick(&mut app, &ctx); + assert_eq!(*calls.lock().unwrap(), [false, true], "the launcher's switch alone starts it"); + assert!(app.agent_link.launcher && app.agent_link.port == Some(4321)); + assert!(!app.session.prefs().integrations.connect_agents, "the box's own value is kept"); + tick(&mut app, &ctx); + assert_eq!(calls.lock().unwrap().len(), 2, "no change, no restart"); + launcher.store(false, Ordering::Relaxed); + tick(&mut app, &ctx); + assert_eq!(*calls.lock().unwrap(), [false, true, false], "off in the launcher stops it"); + assert!(!app.agent_link.launcher && app.agent_link.port.is_none()); +} + /// 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] diff --git a/crates/ui-egui/src/services.rs b/crates/ui-egui/src/services.rs index 53aa83501c..295cf02806 100644 --- a/crates/ui-egui/src/services.rs +++ b/crates/ui-egui/src/services.rs @@ -371,6 +371,9 @@ pub struct AgentLinkStatus { /// The suite's `AI-MCP` feature flag (`craft-flags`): without it the page shows only the /// connection settings PhotoCraft had before (Allow Agent Control, Control Port). pub mcp_flag: bool, + /// The ArtCraft Launcher turned agents on for every Craft app (Settings › AI agents): that + /// counts as *Let AI agents connect*, whatever the box says. + pub launcher: bool, } /// What [`Services::agent_link`] did after the MCP settings changed. @@ -590,6 +593,10 @@ pub struct Services { pub agent_link: Option, /// Preferences › AI Integrations' buttons that add PhotoCraft to MCP clients (desktop). pub agent_clients: Option, + /// Whether the ArtCraft Launcher turned agents on for every Craft app, cheap enough to ask every + /// frame (the desktop app watches the launcher's files on its own thread). `None` without the + /// suite's `AI-MCP` flag, on the web, and in tests that don't set it. + pub launcher_agents: Option bool>>, /// Encode an RGBA8 image as PNG (used for screenshots and `ui.render`). pub encode_png: Option, /// Open a URL in the system browser (native). Falls back to `ctx.open_url` (web) when unset. diff --git a/docs/control-protocol.md b/docs/control-protocol.md index cbaf2c224c..5c2d2591b3 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -418,7 +418,7 @@ magenta alignment lines. `ui.pointer` drives the same code, so agents get identi - **Headless** (`photocraft-cli mcp`): an in-process `photocraft_engine::Session`. There is no window. CPU composition is the default; `--gpu` or `PHOTOCRAFT_GPU=1` enables optional GPU rendering with automatic CPU fallback. - **Bridge** (`photocraft-cli mcp --bridge 127.0.0.1:7878 --control-token-file `): every tool is forwarded to a running `photocraft --control 7878 --control-token-file ` over this protocol, so agents see and drive the live app. Explicit `--gpu` / `--no-gpu` flags are rejected with a usage error because the desktop controls rendering; `PHOTOCRAFT_GPU` is ignored in bridge mode. `--bridge 7878` is short for `--bridge 127.0.0.1:7878`. With no `--bridge`, `PHOTOCRAFT_CONTROL_PORT` selects the bridge port (`127.0.0.1:`), and the CLI says so on standard error; with neither (or the variable empty), the MCP runs headless. A value that is not a port is a usage error naming the variable. `--automation-read-root` or `--automation-write-root` with the variable set is a usage error, since the bridge would drop the roots. -- **Live** (`photocraft-cli mcp --live`): the bridge, with the address and token read before every tool call from `agent-connection.json` in the app's settings folder. The app publishes that file while Edit › Preferences › AI Integrations › *Let AI agents connect* is on (not with `--control`), and removes it when the connection stops; a file left by a crash fails the connection probe and counts as no app. See [MCP conventions](mcp.md#connecting-the-desktop-app-no-terminal). +- **Live** (`photocraft-cli mcp --live`): the bridge, with the address and token read before every tool call from `agent-connection.json` in the app's settings folder. The app publishes that file while Edit › Preferences › AI Integrations › *Let AI agents connect* is on, or the ArtCraft Launcher turned agents on for every Craft app ([MCP conventions](mcp.md#connecting-the-desktop-app-no-terminal)), not with `--control`, and removes it when the connection stops; a file left by a crash fails the connection probe and counts as no app. See [MCP conventions](mcp.md#connecting-the-desktop-app-no-terminal). `ui.inspect` reports the connection as `agentLink`: `port` while agents can connect, `launchFlags` when `--control` manages it, `error`, and `mcpCommand` (how MCP clients start the CLI). diff --git a/docs/mcp.md b/docs/mcp.md index cc440ba629..59c977b119 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -7,6 +7,16 @@ ArtCraft Launcher › Settings › Experimental features, which writes `ArtCraft Craft app, or start PhotoCraft with `CRAFT_FLAGS=AI-MCP`. Without it the page shows only Allow Agent Control and Control Port, as before; a Control Port already set keeps its connection. +**With the ArtCraft Launcher** there is nothing to do in PhotoCraft: turning on Settings › AI +agents › **Let AI agents use Craft apps** there is the person's consent for every Craft app. The +launcher then keeps its app list `ArtCraft/mcp/apps.json` (in the per-user local configuration +folder; `CRAFT_MCP_DIR` moves it), and while that list names `photocraft` and `AI-MCP` is on, +PhotoCraft accepts agents as if **Let AI agents connect** were ticked: the page shows the box ticked +and says the launcher turned it on, and PhotoCraft's own choice is kept for when the launcher's +switch goes off. The app looks at the launcher's files every 2 s, so switching there applies +without a restart; `photocraft-cli mcp --live` looks before every call. Allow Agent Control off +still refuses agents. Storytold/craft-ai-integrations#195 has the whole design. + 1. In PhotoCraft, open **Edit › Preferences › AI Integrations** and turn on **Let AI agents connect (MCP)**. Optionally choose the folders agents can open from and save to, and what happens when an agent needs PhotoCraft while it is closed (open it, work without a window, From d3a0166eebf8fab1fb8383065089dd519c0449ae Mon Sep 17 00:00:00 2001 From: David Mann Date: Thu, 12 Nov 2026 20:07:08 +0100 Subject: [PATCH 17/28] Client setup moves to the ArtCraft Launcher The launcher's Settings > AI agents adds one entry for every Craft app to Claude Desktop, Claude Code, Cursor and LM Studio (craft-launcher#1432), so PhotoCraft's page drops its Add to Claude Desktop / Claude Code / Cursor and Copy Prompt for an Agent buttons. Copy Configuration stays for people without the launcher, and so does `photocraft-cli mcp install --client`. Docs, README and the AUTO-MCP-LIVE scorecard row follow. Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- apps/photocraft/src/agent_link.rs | 12 +++---- book/src/automation/mcp.md | 2 +- crates/automation/src/agent_link.rs | 36 ------------------- crates/ui-egui/src/prefs/prefs_ui/agents.rs | 31 ++++------------ .../src/prefs/prefs_ui/agents_tests.rs | 30 +++++++--------- docs/mcp.md | 8 +++-- docs/scorecard.md | 2 +- scorecard/automation.toml | 2 +- 9 files changed, 32 insertions(+), 93 deletions(-) diff --git a/README.md b/README.md index 9bd0c6c101..a7413d6695 100644 --- a/README.md +++ b/README.md @@ -246,7 +246,7 @@ photocraft-cli batch --help photocraft-cli mcp ``` -To let Claude or another AI app drive the open PhotoCraft window without a terminal, turn on **Edit › Preferences › AI Integrations › Let AI agents connect**, then click **Add to Claude Desktop** (or Claude Code, or Cursor) in the same panel. See [`docs/mcp.md`](docs/mcp.md). These settings are behind the Craft suite's `AI-MCP` feature flag: turn it on in ArtCraft Launcher › Settings › Experimental features, or start PhotoCraft with `CRAFT_FLAGS=AI-MCP`. +To let Claude or another AI app drive the open PhotoCraft window without a terminal, turn on **ArtCraft Launcher › Settings › AI agents** and click **Add** next to the AI app (one entry for every Craft app), or, without the launcher, turn on **Edit › Preferences › AI Integrations › Let AI agents connect** and paste its **Copy Configuration** into the AI app. See [`docs/mcp.md`](docs/mcp.md). These settings are behind the Craft suite's `AI-MCP` feature flag: turn it on in ArtCraft Launcher › Settings › Experimental features, or start PhotoCraft with `CRAFT_FLAGS=AI-MCP`. The desktop app also offers an authenticated, loopback-only control channel (`photocraft --control`) for inspecting UI state, driving tools with pointer events, and taking offscreen screenshots. Every image in this README was rendered that way. See [`docs/control-protocol.md`](docs/control-protocol.md). diff --git a/apps/photocraft/src/agent_link.rs b/apps/photocraft/src/agent_link.rs index f9f447edf9..b3b2b52054 100644 --- a/apps/photocraft/src/agent_link.rs +++ b/apps/photocraft/src/agent_link.rs @@ -153,14 +153,10 @@ pub fn mcp_launch() -> Option { (appimage.is_some() || dir.join(agent_link::cli_file_name()).is_file()).then_some(launch) } -/// The "Add to …" buttons: add `mcp` to a client, or return the configuration to paste; and -/// "Copy Prompt for an Agent" (`prompt`): the text an agent with a terminal sets itself up from. +/// Copy Configuration (`json`): the configuration to paste into an MCP client. The same entry +/// point as `photocraft-cli mcp install --client`, which also adds to a client's own file. pub fn clients(mcp: Option) -> AgentClientFn { Box::new(move |id: &str| { - if id == "prompt" { - let launch = mcp.as_ref().ok_or("photocraft-cli isn't installed beside PhotoCraft, so an agent can't start it")?; - return Ok(launch.agent_prompt()); - } let client = Client::parse(id).ok_or_else(|| format!("unknown MCP client `{id}`"))?; let launch = mcp.as_ref().ok_or_else(|| format!("photocraft-cli isn't installed beside PhotoCraft, so {} can't start it", client.name()))?; agent_link::install(client, launch, &ClientEnv::from_env()).map(|done| done.message(client)).map_err(|e| e.to_string()) @@ -312,8 +308,8 @@ mod tests { let mut add = clients(None); assert!(add("cursor").unwrap_err().contains("photocraft-cli")); assert!(add("nope").unwrap_err().contains("unknown")); - assert!(add("prompt").unwrap_err().contains("photocraft-cli")); + assert!(add("json").unwrap_err().contains("photocraft-cli")); let mut add = clients(Some(McpLaunch::cli(Path::new("/x/photocraft-cli")))); - assert!(add("prompt").unwrap().contains("mcp --live")); + assert!(add("json").unwrap().contains("mcp")); } } diff --git a/book/src/automation/mcp.md b/book/src/automation/mcp.md index 4cfbb36310..e42e504a50 100644 --- a/book/src/automation/mcp.md +++ b/book/src/automation/mcp.md @@ -6,7 +6,7 @@ - **Bridge:** `BridgeClient` forwards tools to a desktop application started with `photocraft --control `. - **Live:** `photocraft-cli mcp --live` finds the desktop application through the connection file it publishes while Edit › Preferences › AI Integrations › *Let AI agents connect* is on, before every tool call; while the app is closed it starts it, serves a headless session, or reports an error, as chosen there. -The simplest setup needs no terminal: turn on *Let AI agents connect* in PhotoCraft, then click *Add to Claude Desktop* (or Claude Code, or Cursor) in the same panel. See [`docs/mcp.md`](../../../docs/mcp.md#connecting-the-desktop-app-no-terminal). +The simplest setup needs no terminal: turn on ArtCraft Launcher › Settings › AI agents and click *Add* next to the AI app; that reaches every Craft app. Without the launcher, turn on *Let AI agents connect* in PhotoCraft and paste its *Copy Configuration* into the AI app. See [`docs/mcp.md`](../../../docs/mcp.md#connecting-the-desktop-app-no-terminal). For a source checkout, first [install the CLI on PATH and register the server](../../../docs/mcp.md#install-and-register). The installed binary survives `cargo clean`; a symlink into `target/release` does not. diff --git a/crates/automation/src/agent_link.rs b/crates/automation/src/agent_link.rs index d7ebbf7fe2..8cd86f12eb 100644 --- a/crates/automation/src/agent_link.rs +++ b/crates/automation/src/agent_link.rs @@ -267,29 +267,6 @@ impl McpLaunch { serde_json::to_string_pretty(&v).unwrap_or_default() } - /// A prompt to paste into an agent that has a terminal (Claude Code, Codex, Cursor's agent): - /// it registers PhotoCraft as its own MCP server, then checks the connection. Claude Desktop - /// has no terminal, so it is set up by [`install`] instead. Holds no port and no token. - pub fn agent_prompt(&self) -> String { - let line = self.shell_line(); - let config = self.config_json(); - format!( - "Please connect yourself to PhotoCraft, the image editor running on this computer, as an MCP server, then check that it works. - - 1. Register a stdio MCP server named \"{SERVER_NAME}\" that runs this command: - {line} - - Claude Code: claude mcp add --scope user {SERVER_NAME} -- {line} - - Codex: codex mcp add {SERVER_NAME} -- {line} - - Any other client: add this to its MCP configuration: - {config} - 2. Reload your MCP servers if your client needs that (or tell me to restart you). - 3. Call the {SERVER_NAME} tool `ui_inspect` and tell me which document is open. - - PhotoCraft must be running with Edit › Preferences › AI Integrations › Let AI agents connect turned on. The command needs no port or token: it finds the app by itself on every call. -" - ) - } - /// The command line, quoted for a POSIX shell (Windows paths are double-quoted). pub fn shell_line(&self) -> String { std::iter::once(&self.command).chain(&self.args).map(|s| shell_quote(s)).collect::>().join(" ") @@ -924,19 +901,6 @@ mod tests { let _ = std::fs::remove_dir_all(&home); } - /// The prompt an agent pastes names the exact command, the Claude Code and Codex lines and a - /// configuration for any other client, and no token. - #[test] - fn the_agent_prompt_registers_the_live_command() { - let launch = McpLaunch::cli(Path::new("/x/photocraft-cli")); - let prompt = launch.agent_prompt(); - assert!(prompt.contains("claude mcp add --scope user photocraft -- /x/photocraft-cli mcp --live"), "{prompt}"); - assert!(prompt.contains("codex mcp add photocraft -- /x/photocraft-cli mcp --live"), "{prompt}"); - assert!(prompt.contains(&launch.config_json()), "{prompt}"); - assert!(prompt.contains("Edit › Preferences › AI Integrations › Let AI agents connect"), "{prompt}"); - assert!(!prompt.contains(TOKEN_FILE) && !prompt.contains("token\":"), "{prompt}"); - } - #[test] fn claude_command_is_found_where_its_installers_put_it() { let home = temp("claude-find"); diff --git a/crates/ui-egui/src/prefs/prefs_ui/agents.rs b/crates/ui-egui/src/prefs/prefs_ui/agents.rs index 60ea2d5aaa..be43bf1d28 100644 --- a/crates/ui-egui/src/prefs/prefs_ui/agents.rs +++ b/crates/ui-egui/src/prefs/prefs_ui/agents.rs @@ -1,6 +1,6 @@ //! Preferences › AI Integrations: the agent connection (`integrations.connectAgents`), the folders //! agents may use, what `photocraft-cli mcp --live` does while the app is closed, and the buttons -//! that add PhotoCraft to MCP clients. Changes apply at once, without a restart. +//! that copies the configuration for an MCP client. Changes apply at once, without a restart. use super::dialogs::is_preferences; use super::fields::{choice_label, humanize}; @@ -110,30 +110,17 @@ pub(super) fn integration_rows(ui: &mut egui::Ui, obj: &mut Map, obj.insert("whenAppClosed".into(), json!(cur)); ui.end_row(); }); - // 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). + // Adding the Craft apps to an MCP client is the ArtCraft Launcher's job (Settings › AI agents, + // one entry for every app, storytold/craft-ai-integrations#195). Without the launcher, the + // configuration to paste is here, once agents may connect (launch options manage it 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| { - for (id, label) in [ - ("claude-desktop", tl!("Add to Claude Desktop")), - ("claude-code", tl!("Add to Claude Code")), - ("cursor", tl!("Add to Cursor")), - ("json", tl!("Copy Configuration")), - ] { - if crate::widgets::secondary_button(ui, label, 120.0).clicked() { - f.insert("__agentAction".into(), json!(id)); - } + if crate::widgets::secondary_button(ui, tl!("Copy Configuration"), 120.0).clicked() { + f.insert("__agentAction".into(), json!("json")); } - }); - // Agents with a terminal (Claude Code, Codex, Cursor's agent) can set themselves up. - ui.add_space(4.0); - ui.horizontal_wrapped(|ui| { - if crate::widgets::secondary_button(ui, tl!("Copy Prompt for an Agent"), 120.0).clicked() { - f.insert("__agentAction".into(), json!("prompt")); - } - ui.label(RichText::new(tl!("Paste it into an agent with a terminal; it registers PhotoCraft by itself.")).color(t.text_faint)); + ui.label(RichText::new(tl!("Or add every Craft app at once in ArtCraft Launcher › Settings › AI agents.")).color(t.text_faint)); }); } if let Some(result) = f.get("__agentResult").and_then(Value::as_object) { @@ -173,10 +160,6 @@ pub(super) fn agent_action(app: &mut PhotocraftApp, ctx: &egui::Context, f: &mut ctx.copy_text(text); json!({"ok": true, "message": tl!("Configuration copied.")}) } - Ok(text) if action == "prompt" => { - ctx.copy_text(text); - json!({"ok": true, "message": tl!("Prompt copied. Paste it into Claude Code, Codex or another agent with a terminal.")}) - } Ok(message) => json!({"ok": true, "message": message}), Err(e) => json!({"ok": false, "message": e}), }; diff --git a/crates/ui-egui/src/prefs/prefs_ui/agents_tests.rs b/crates/ui-egui/src/prefs/prefs_ui/agents_tests.rs index eea34c3d84..108c55dbe0 100644 --- a/crates/ui-egui/src/prefs/prefs_ui/agents_tests.rs +++ b/crates/ui-egui/src/prefs/prefs_ui/agents_tests.rs @@ -85,10 +85,10 @@ fn the_launcher_switch_turns_the_agent_connection_on_without_the_box() { assert!(!app.agent_link.launcher && app.agent_link.port.is_none()); } -/// 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. +/// Copy Configuration only shows once agents may connect, and a click reaches the service. The +/// per-client buttons are the ArtCraft Launcher's (one entry for every Craft app). #[test] -fn ai_integrations_offer_the_client_buttons_only_when_agents_may_connect() { +fn ai_integrations_offer_the_configuration_only_when_agents_may_connect() { use egui_kittest::{Harness, kittest::Queryable}; let (mut app, _) = app_with_store(); let clicked: Arc>> = Arc::default(); @@ -104,26 +104,20 @@ fn ai_integrations_offer_the_client_buttons_only_when_agents_may_connect() { 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()); + assert!(h.query_by_label("Copy Configuration").is_none(), "off: nothing to set up yet"); 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", "Copy Prompt for an Agent"] { - assert!(h.query_by_label(label).is_some(), "{label}"); + for label in ["Add to Claude Desktop", "Add to Claude Code", "Add to Cursor", "Copy Prompt for an Agent"] { + assert!(h.query_by_label(label).is_none(), "{label} is the launcher's"); } - h.get_by_label("Add to Cursor").click(); + h.get_by_label("Copy Configuration").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"); - // The prompt for an agent with a terminal goes to the clipboard, with a note saying so. - h.get_by_label("Copy Prompt for an Agent").click(); - h.run_steps(3); - assert_eq!(*clicked.lock().unwrap(), ["cursor", "prompt"]); - assert!(h.query_by_label_contains("Prompt copied").is_some(), "the copy is confirmed"); - // Unticked again: the buttons go. + assert_eq!(*clicked.lock().unwrap(), ["json"]); + assert!(h.query_by_label("Configuration copied.").is_some(), "the copy is confirmed"); + // Unticked again: the button goes. h.get_by_label("Let AI agents connect (MCP)").click(); h.run_steps(3); - assert!(h.query_by_label("Add to Cursor").is_none()); + assert!(h.query_by_label("Copy Configuration").is_none()); } /// Without the suite's AI-MCP feature flag the page shows only the settings it had before. @@ -141,7 +135,7 @@ fn ai_integrations_without_the_mcp_flag_show_only_the_earlier_settings() { h.run_steps(4); assert!(h.query_by_label("Let AI agents connect (MCP)").is_none(), "the new connection switch waits for the flag"); assert!(h.query_by_label("Folder agents can open from").is_none()); - assert!(h.query_by_label("Add to Claude Desktop").is_none()); + assert!(h.query_by_label("Copy Configuration").is_none()); assert!(h.query_by_label("Allow agent control").is_some(), "the earlier setting stays"); } diff --git a/docs/mcp.md b/docs/mcp.md index 59c977b119..bbf3592533 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -21,9 +21,11 @@ still refuses agents. Storytold/craft-ai-integrations#195 has the whole design. connect (MCP)**. Optionally choose the folders agents can open from and save to, and what 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. The buttons show once - the box is ticked. +2. Add PhotoCraft to the MCP client: with the ArtCraft Launcher, Settings › AI agents › **Add** + adds one entry for every Craft app (the `craft-ai-mcp` gateway, which starts + `photocraft-cli mcp --live`). Without it, click **Copy Configuration** and paste it into the + client's MCP settings, or run `photocraft-cli mcp install --client ` (below). Then + restart that client. The button shows 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 diff --git a/docs/scorecard.md b/docs/scorecard.md index f0c051c86b..919b6754a0 100644 --- a/docs/scorecard.md +++ b/docs/scorecard.md @@ -274,7 +274,7 @@ Menu wiring (`docs/parity-checklist.md`): 664 of 664 menu items live (100.0%). T | AUTO-219-8 | xtask check that every panel button routes through a command id | partial | [#219](https://github.com/storytold/photocraft/issues/219) | cargo xtask panel-commands (run by xtask ci and CI) fails on a shell click handler that changes the document or session directly; 1 allowlisted function left (panels/color.rs color_field assigns the foreground/background colour instead of tools.setColors) | | AUTO-219-9 | Headless commands for in-canvas type editing, Liquify/Puppet strokes, transform handles | done | [#219](https://github.com/storytold/photocraft/issues/219) | type.hitTest, type.caret, type.navigate; filter.liquify strokes, edit.puppetWarp pins, type.edit, edit.transform | | AUTO-219-10 | Agent acceptance suite grown to 30-50 workflows | partial | [#219](https://github.com/storytold/photocraft/issues/219) | automation/tests/it/agent_tasks.rs runs 10 workflows over MCP | -| AUTO-MCP-LIVE | Connect an MCP client to the running app without a terminal (no flags, ports or tokens to copy) | done | | 2026-11-12 (#5525, #11363): Edit › Preferences › AI Integrations › Let AI agents connect starts and stops the loopback control server while the app runs (no restart) and publishes agent-connection.json; photocraft-cli mcp --live finds the app on every call (launch / headless / error while it is closed); Add to Claude Desktop / Claude Code / Cursor, mcp install --client, and Copy Prompt for an Agent. automation/tests/mcp_live.rs, apps/photocraft/src/agent_link.rs tests | +| AUTO-MCP-LIVE | Connect an MCP client to the running app without a terminal (no flags, ports or tokens to copy) | done | | 2026-11-12 (#5525, #11363): Edit › Preferences › AI Integrations › Let AI agents connect starts and stops the loopback control server while the app runs (no restart) and publishes agent-connection.json; photocraft-cli mcp --live finds the app on every call (launch / headless / error while it is closed); the ArtCraft Launcher's agents switch counts as consent (craft-ai-integrations#195) and its Add buttons register every Craft app; Copy Configuration and mcp install --client without the launcher. automation/tests/mcp_live.rs, apps/photocraft/src/agent_link.rs tests | ## Reliability diff --git a/scorecard/automation.toml b/scorecard/automation.toml index 22a198f870..2fd1660dce 100644 --- a/scorecard/automation.toml +++ b/scorecard/automation.toml @@ -85,4 +85,4 @@ note = "automation/tests/it/agent_tasks.rs runs 10 workflows over MCP" id = "AUTO-MCP-LIVE" target = "Connect an MCP client to the running app without a terminal (no flags, ports or tokens to copy)" status = "done" -note = "2026-11-12 (#5525, #11363): Edit › Preferences › AI Integrations › Let AI agents connect starts and stops the loopback control server while the app runs (no restart) and publishes agent-connection.json; photocraft-cli mcp --live finds the app on every call (launch / headless / error while it is closed); Add to Claude Desktop / Claude Code / Cursor, mcp install --client, and Copy Prompt for an Agent. automation/tests/mcp_live.rs, apps/photocraft/src/agent_link.rs tests" +note = "2026-11-12 (#5525, #11363): Edit › Preferences › AI Integrations › Let AI agents connect starts and stops the loopback control server while the app runs (no restart) and publishes agent-connection.json; photocraft-cli mcp --live finds the app on every call (launch / headless / error while it is closed); the ArtCraft Launcher's agents switch counts as consent (craft-ai-integrations#195) and its Add buttons register every Craft app; Copy Configuration and mcp install --client without the launcher. automation/tests/mcp_live.rs, apps/photocraft/src/agent_link.rs tests" From a1afd0b63923864329d8a714a0cc49645635d4df Mon Sep 17 00:00:00 2001 From: David Mann Date: Thu, 12 Nov 2026 20:39:22 +0100 Subject: [PATCH 18/28] The AI-MCP flag survives the connection's updates The page's status was replaced by the connection service's answer, which never carries the feature flag, so with AI-MCP on the page fell back to the settings it had before the flag after the first frame. The flag is the app's, set at launch; the update now keeps it. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/prefs/prefs_ui/agents.rs | 3 +++ crates/ui-egui/src/prefs/prefs_ui/agents_tests.rs | 15 +++++++++++++++ 2 files changed, 18 insertions(+) diff --git a/crates/ui-egui/src/prefs/prefs_ui/agents.rs b/crates/ui-egui/src/prefs/prefs_ui/agents.rs index be43bf1d28..18c5134db8 100644 --- a/crates/ui-egui/src/prefs/prefs_ui/agents.rs +++ b/crates/ui-egui/src/prefs/prefs_ui/agents.rs @@ -43,7 +43,10 @@ pub(super) fn sync_agent_link(app: &mut PhotocraftApp, ctx: &egui::Context) { // Actions automation records keep the policy as their gate when the user plays them, as they // do with `--control` (`PhotocraftApp::new`); the gate stays once agents have connected. app.session.automation_gate = app.session.automation_gate.or(app.services.automation_authorize); + // The service reports the connection; the feature flag is the app's, set once at launch. + let mcp_flag = app.agent_link.mcp_flag; app.agent_link = update.status; + app.agent_link.mcp_flag = mcp_flag; app.agent_link.launcher = launcher; } diff --git a/crates/ui-egui/src/prefs/prefs_ui/agents_tests.rs b/crates/ui-egui/src/prefs/prefs_ui/agents_tests.rs index 108c55dbe0..425bbac110 100644 --- a/crates/ui-egui/src/prefs/prefs_ui/agents_tests.rs +++ b/crates/ui-egui/src/prefs/prefs_ui/agents_tests.rs @@ -85,6 +85,21 @@ fn the_launcher_switch_turns_the_agent_connection_on_without_the_box() { assert!(!app.agent_link.launcher && app.agent_link.port.is_none()); } +/// The connection's updates keep the AI-MCP flag the app was started with: losing it would put the +/// page back to the settings it had before the flag after the first frame. +#[test] +fn connection_updates_keep_the_mcp_flag() { + let (mut app, _) = app_with_store(); + let ctx = egui::Context::default(); + app.services.agent_link = Some(Box::new(|_: &prefs::Integrations, _: &egui::Context| crate::AgentLink::default())); + app.agent_link.mcp_flag = true; + tick(&mut app, &ctx); + assert!(app.agent_link.mcp_flag, "first frame"); + app.run("prefs.set", json!({"values": {"integrations.connectAgents": true}})).unwrap(); + tick(&mut app, &ctx); + assert!(app.agent_link.mcp_flag, "after a change"); +} + /// Copy Configuration only shows once agents may connect, and a click reaches the service. The /// per-client buttons are the ArtCraft Launcher's (one entry for every Craft app). #[test] From ce1dd3a5946f65a285e3c153ed5c8e9db19df757 Mon Sep 17 00:00:00 2001 From: David Mann Date: Thu, 12 Nov 2026 21:07:58 +0100 Subject: [PATCH 19/28] docs: the AI-MCP flag is set in flags.toml or CRAFT_FLAGS only Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- docs/mcp.md | 7 ++++--- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index a7413d6695..01153abf54 100644 --- a/README.md +++ b/README.md @@ -246,7 +246,7 @@ photocraft-cli batch --help photocraft-cli mcp ``` -To let Claude or another AI app drive the open PhotoCraft window without a terminal, turn on **ArtCraft Launcher › Settings › AI agents** and click **Add** next to the AI app (one entry for every Craft app), or, without the launcher, turn on **Edit › Preferences › AI Integrations › Let AI agents connect** and paste its **Copy Configuration** into the AI app. See [`docs/mcp.md`](docs/mcp.md). These settings are behind the Craft suite's `AI-MCP` feature flag: turn it on in ArtCraft Launcher › Settings › Experimental features, or start PhotoCraft with `CRAFT_FLAGS=AI-MCP`. +To let Claude or another AI app drive the open PhotoCraft window without a terminal, turn on **ArtCraft Launcher › Settings › AI agents** and click **Add** next to the AI app (one entry for every Craft app), or, without the launcher, turn on **Edit › Preferences › AI Integrations › Let AI agents connect** and paste its **Copy Configuration** into the AI app. See [`docs/mcp.md`](docs/mcp.md). These settings are behind the Craft suite's `AI-MCP` feature flag: set `AI-MCP = true` in `ArtCraft/flags.toml`, or start PhotoCraft with `CRAFT_FLAGS=AI-MCP`. The desktop app also offers an authenticated, loopback-only control channel (`photocraft --control`) for inspecting UI state, driving tools with pointer events, and taking offscreen screenshots. Every image in this README was rendered that way. See [`docs/control-protocol.md`](docs/control-protocol.md). diff --git a/docs/mcp.md b/docs/mcp.md index bbf3592533..2596e73d5f 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2,9 +2,10 @@ ## Connecting the desktop app (no terminal) -These settings are behind the Craft suite's `AI-MCP` feature flag (`craft-flags`): turn it on in -ArtCraft Launcher › Settings › Experimental features, which writes `ArtCraft/flags.toml` for every -Craft app, or start PhotoCraft with `CRAFT_FLAGS=AI-MCP`. Without it the page shows only Allow +These settings are behind the Craft suite's `AI-MCP` feature flag (`craft-flags`). Flags are set +only in the per-user `ArtCraft/flags.toml` (`AI-MCP = true` under `[flags]`; on Windows in +`%LOCALAPPDATA%\ArtCraft`), which every Craft app and the launcher read, or for one run with +`CRAFT_FLAGS=AI-MCP`; no app or launcher setting switches them. Without it the page shows only Allow Agent Control and Control Port, as before; a Control Port already set keeps its connection. **With the ArtCraft Launcher** there is nothing to do in PhotoCraft: turning on Settings › AI From 113bec48cb882275e9f5d65bf11957e071c70a22 Mon Sep 17 00:00:00 2001 From: David Mann Date: Thu, 12 Nov 2026 22:20:13 +0100 Subject: [PATCH 20/28] test(cli): mcp --live test keeps the machine's launcher switch out The test expects agents off, but `mcp --live` now also accepts the ArtCraft Launcher's switch, read from the real per-user folder: on a machine with the launcher's agents on it failed. It points CRAFT_MCP_DIR at its own folder. Co-Authored-By: Claude Opus 5.5 --- apps/photocraft-cli/tests/it/cli.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/apps/photocraft-cli/tests/it/cli.rs b/apps/photocraft-cli/tests/it/cli.rs index e4da07dc47..3ab0234ab8 100644 --- a/apps/photocraft-cli/tests/it/cli.rs +++ b/apps/photocraft-cli/tests/it/cli.rs @@ -2086,6 +2086,8 @@ fn mcp_live_without_the_app_explains_what_to_do() { let mut child = bin() .args(["mcp", "--live", "--when-closed", "error"]) .env("PHOTOCRAFT_CONFIG_DIR", &dir) + // The machine's ArtCraft Launcher may have agents on; this test needs them off. + .env("CRAFT_MCP_DIR", &dir) .env("PHOTOCRAFT_CONTROL_PORT", "not-a-port") .stdin(Stdio::piped()) .stdout(Stdio::piped()) From fd626999fc92f7f685d571f8deb503a9b20c06b8 Mon Sep 17 00:00:00 2001 From: David Mann Date: Thu, 12 Nov 2026 23:41:14 +0100 Subject: [PATCH 21/28] One switch for agents, in the ArtCraft Launcher; plain `mcp` works in the open app As agreed in craft-ai-integrations#195: one switch for every Craft app, in the launcher; only the launcher writes MCP client configurations; plain `-cli mcp` works in the open app. - Consent: with the AI-MCP flag, the launcher's switch alone decides, read through `craft-ai-agents` (craft-ai-integrations#197), the crate the launcher writes the app list with and the gateway reads it with. The "Let AI agents connect" box is gone; without the flag everything is as on main (a saved Control Port keeps its connection). - `photocraft-cli mcp`: works in the open window while agents may use it (what `--live` did), and headless otherwise, exactly as before (only the roots given to it; the app is never started). `--headless` forces that; `--bridge` / PHOTOCRAFT_CONTROL_PORT as before. `--live` and `mcp install` are gone. Several read roots work again, invalid roots stop the start, and `--gpu` applies to the headless session. - Client setup is the launcher's: the client code (Claude Desktop, Claude Code, Cursor, JSON), Copy Configuration, its service and its docs are removed (about 740 lines net). - CLI tests run with their own settings, launcher and flags folders: plain `mcp` would otherwise find (or start) the developer's own PhotoCraft. - Docs, book, README, scorecard row, packaging comments follow. Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 12 +- Cargo.toml | 4 + README.md | 2 +- apps/photocraft-cli/src/args.rs | 86 +- apps/photocraft-cli/src/automation.rs | 50 +- apps/photocraft-cli/src/lib.rs | 2 +- apps/photocraft-cli/tests/it/cli.rs | 110 ++- apps/photocraft-cli/tests/it/gpu.rs | 2 +- apps/photocraft-cli/tests/it/main.rs | 16 + apps/photocraft-cli/tests/it/malloc_tuning.rs | 2 +- .../tests/it/man_and_completions.rs | 2 - apps/photocraft-cli/tests/it/orientation.rs | 2 +- apps/photocraft/src/agent_link.rs | 68 +- apps/photocraft/src/main.rs | 19 +- book/src/automation/mcp.md | 14 +- book/src/security/automation-security.md | 4 +- crates/automation/Cargo.toml | 4 +- crates/automation/src/agent_link.rs | 807 +----------------- crates/automation/src/lib.rs | 2 +- crates/automation/src/live.rs | 93 +- crates/automation/src/server.rs | 15 +- crates/automation/src/server/progress.rs | 2 +- crates/automation/tests/mcp_live.rs | 72 +- crates/engine/src/prefs.rs | 16 +- crates/engine/src/prefs/tests.rs | 2 +- crates/ui-egui/src/lib.rs | 2 +- crates/ui-egui/src/prefs/prefs_ui/agents.rs | 69 +- .../src/prefs/prefs_ui/agents_tests.rs | 63 +- crates/ui-egui/src/prefs/prefs_ui/fields.rs | 3 +- crates/ui-egui/src/services.rs | 11 +- docs/control-protocol.md | 23 +- docs/development.md | 2 +- docs/mcp.md | 96 +-- docs/scorecard.md | 2 +- packaging/linux/AppRun | 2 +- packaging/linux/apprun-test.sh | 6 +- packaging/macos/package.sh | 2 +- scorecard/automation.toml | 2 +- 38 files changed, 474 insertions(+), 1217 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index a725a21b88..50ee8419e8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1426,6 +1426,16 @@ dependencies = [ "libc", ] +[[package]] +name = "craft-ai-agents" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-ai-integrations?rev=35e0352666a117407d62230a6c6c2366f3e21a3b#35e0352666a117407d62230a6c6c2366f3e21a3b" +dependencies = [ + "dirs", + "serde", + "serde_json", +] + [[package]] name = "craft-atomic" version = "0.1.0" @@ -5562,9 +5572,9 @@ dependencies = [ "base64 0.23.1", "cap-std", "clap", + "craft-ai-agents", "craft-flags", "craft-psd", - "dirs", "getrandom 0.3.4", "hmac", "photocraft-codecs", diff --git a/Cargo.toml b/Cargo.toml index 476498d400..779273168c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -13,6 +13,10 @@ rust-version = "1.95" craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b", features = ["serde"] } # Feature flags shared with the launcher and the other Craft apps (craft-libs#1118, #1119). craft-flags = { git = "https://github.com/storytold/craft-libs", rev = "86d6e8c5b05a4dadc35ff1c8e5d2f992c687ee97" } +# The ArtCraft Launcher's agents switch and app list, shared with the launcher, the MCP gateway and +# every Craft app (storytold/craft-ai-integrations#195). Pinned to the head of +# storytold/craft-ai-integrations#197 until it merges. +craft-ai-agents = { git = "https://github.com/storytold/craft-ai-integrations", rev = "35e0352666a117407d62230a6c6c2366f3e21a3b" } # internal photocraft-geom = { path = "crates/geom" } photocraft-color = { path = "crates/color" } diff --git a/README.md b/README.md index 01153abf54..11880dda82 100644 --- a/README.md +++ b/README.md @@ -246,7 +246,7 @@ photocraft-cli batch --help photocraft-cli mcp ``` -To let Claude or another AI app drive the open PhotoCraft window without a terminal, turn on **ArtCraft Launcher › Settings › AI agents** and click **Add** next to the AI app (one entry for every Craft app), or, without the launcher, turn on **Edit › Preferences › AI Integrations › Let AI agents connect** and paste its **Copy Configuration** into the AI app. See [`docs/mcp.md`](docs/mcp.md). These settings are behind the Craft suite's `AI-MCP` feature flag: set `AI-MCP = true` in `ArtCraft/flags.toml`, or start PhotoCraft with `CRAFT_FLAGS=AI-MCP`. +To let Claude or another AI app drive the open PhotoCraft window without a terminal, turn on **ArtCraft Launcher › Settings › AI agents** and click **Add** next to the AI app (one entry for every Craft app). See [`docs/mcp.md`](docs/mcp.md). These settings are behind the Craft suite's `AI-MCP` feature flag: set `AI-MCP = true` in `ArtCraft/flags.toml`, or start PhotoCraft with `CRAFT_FLAGS=AI-MCP`. The desktop app also offers an authenticated, loopback-only control channel (`photocraft --control`) for inspecting UI state, driving tools with pointer events, and taking offscreen screenshots. Every image in this README was rendered that way. See [`docs/control-protocol.md`](docs/control-protocol.md). diff --git a/apps/photocraft-cli/src/args.rs b/apps/photocraft-cli/src/args.rs index 5934d6f94b..429fcb4547 100644 --- a/apps/photocraft-cli/src/args.rs +++ b/apps/photocraft-cli/src/args.rs @@ -270,27 +270,23 @@ pub(crate) struct CommandsArgs { pub(crate) filter: Option, } -/// Run the MCP server on stdio (headless engine, bridge to a running `photocraft --control `, -/// or --live) +/// Run the MCP server on stdio: in the open PhotoCraft window when the person lets agents use it +/// (ArtCraft Launcher › Settings › AI agents), otherwise headless /// -/// Headless: each automation root grants that direction of file access; an omitted root denies it. -/// Prefer absolute root paths in MCP client configurations. Bridge: set the roots on the desktop -/// app; root flags are refused. The token flags require --bridge (or PHOTOCRAFT_CONTROL_PORT). -/// Live: the desktop app with Edit › Preferences › AI Integrations › Let AI agents connect on, -/// found again on every call (no port or token to configure); the roots are for a headless session -/// while the app is closed. +/// The open window is found again on every call, with no port or token to configure. Without +/// the person's consent, or with --headless, it runs headless: each automation root grants that +/// direction of file access; an omitted root denies it. Prefer absolute root paths in MCP client +/// configurations. Bridge (--bridge or PHOTOCRAFT_CONTROL_PORT): a running `photocraft --control +/// `; set the roots on the desktop app, root flags are refused, and the token flags require +/// it. #[derive(Args)] -#[command(args_conflicts_with_subcommands = true)] pub(crate) struct McpArgs { - #[command(subcommand)] - pub(crate) action: Option, - /// Find the desktop app by itself on every call (Edit › Preferences › AI Integrations › - /// Let AI agents connect), with no port or token to configure - #[arg(long)] - pub(crate) live: bool, - /// With --live: while the app is closed, start it, serve a headless session, or fail - /// (default: the app's When PhotoCraft Is Closed setting) - #[arg(long, value_name = "launch|headless|error", requires = "live", value_parser = when_closed)] + /// Always work headless, without the open window + #[arg(long, conflicts_with = "when_closed")] + pub(crate) headless: bool, + /// While agents may use PhotoCraft but it is closed: start it, serve a headless session, or + /// fail (default: the app's When PhotoCraft Is Closed setting) + #[arg(long, value_name = "launch|headless|error", value_parser = when_closed)] pub(crate) when_closed: Option, /// Bridge to the PhotoCraft app listening here instead of a headless engine; a bare port means /// 127.0.0.1: @@ -307,19 +303,6 @@ pub(crate) struct McpArgs { pub(crate) automation: AutomationArgs, } -#[derive(Subcommand)] -pub(crate) enum McpCommand { - Install(McpInstallArgs), -} - -/// Add `photocraft-cli mcp --live` to an MCP client's configuration -#[derive(Args)] -pub(crate) struct McpInstallArgs { - /// The client to set up; json prints the configuration to paste into any other client - #[arg(long, value_parser = ["claude-desktop", "claude-code", "cursor", "json"])] - pub(crate) client: String, -} - /// Keep one headless session open and answer JSON lines on stdio, or on 127.0.0.1: /// /// Each request is a JSON line {"id", "method", "params"}. Methods: engine.execute, @@ -390,19 +373,19 @@ enum ServerOptionError { /// A token flag without the bridge or port that reads it would be ignored (#8035). #[error("{flag} requires {transport}")] NeedsTransport { flag: &'static str, transport: &'static str }, - /// `--live` finds the app's port and token by itself. - #[error("--live finds the app by itself; {0} is for --bridge")] - LiveBridge(&'static str), - /// `--live` drives the app, which decides on rendering. - #[error("configure rendering on the desktop app; --gpu and --no-gpu require headless MCP mode, not --live")] - LiveGpu, + /// `--headless` never reaches an app. + #[error("--headless works without the app; {0} is for --bridge")] + HeadlessBridge(&'static str), + /// `--when-closed` is about the open app, which a bridge names itself. + #[error("--when-closed is for the open window; --bridge names the app itself")] + BridgeWhenClosed, } impl ServerOptionError { fn into_clap(self, cmd: &mut clap::Command) -> clap::Error { let kind = match self { Self::BridgeVar(_) | Self::GpuVar(_) => ErrorKind::ValueValidation, - Self::BridgeRoots | Self::BridgeGpu | Self::LiveBridge(_) | Self::LiveGpu => ErrorKind::ArgumentConflict, + Self::BridgeRoots | Self::BridgeGpu | Self::HeadlessBridge(_) | Self::BridgeWhenClosed => ErrorKind::ArgumentConflict, Self::NeedsTransport { .. } => ErrorKind::MissingRequiredArgument, }; cmd.error(kind, self) @@ -514,9 +497,9 @@ fn steps(m: &ArgMatches) -> Vec { /// stray.psd --help`): clap reports the mistake first. pub(crate) fn parse(args: &[OsString]) -> Result { let mut cmd = Cli::command().mut_subcommands(|sub| sub.mut_args(blank_env_is_unset)); - // `mcp --live` finds the app itself: a PHOTOCRAFT_CONTROL_PORT exported for another tool is - // not read, so a value it couldn't use anyway doesn't stop it. - if args.first().is_some_and(|a| a == "mcp") && args.iter().take_while(|a| *a != "--").any(|a| a == "--live") { + // `mcp --headless` reaches no app: a PHOTOCRAFT_CONTROL_PORT exported for another tool is not + // read, so a value it couldn't use anyway doesn't stop it. + if args.first().is_some_and(|a| a == "mcp") && args.iter().take_while(|a| *a != "--").any(|a| a == "--headless") { cmd = cmd.mut_subcommand("mcp", |sub| sub.mut_arg("bridge", |arg| arg.env(None::<&str>))); } let argv = std::iter::once(OsString::from("photocraft-cli")).chain(args.iter().cloned()); @@ -535,25 +518,19 @@ pub(crate) fn parse(args: &[OsString]) -> Result { check_gpu_env(&mut cmd, m)?; } (Command::Mcp(a), Some((name, m))) => { - if a.live { - // `--live` reads the port and token the app publishes. Given on the command line, - // the bridge's flags conflict; exported for another tool, they are left alone. + if a.headless { + // `--headless` reaches no app. Given on the command line, the bridge's flags + // conflict; exported for another tool, they are left alone. for (id, flag) in [("bridge", "--bridge"), ("control_token", "--control-token"), ("control_token_file", "--control-token-file")] { if m.value_source(id) == Some(ValueSource::CommandLine) { if let Some(sub) = cmd.find_subcommand_mut(name) { - return Err(ServerOptionError::LiveBridge(flag).into_clap(sub)); + return Err(ServerOptionError::HeadlessBridge(flag).into_clap(sub)); } - return Err(ServerOptionError::LiveBridge(flag).into_clap(&mut cmd)); + return Err(ServerOptionError::HeadlessBridge(flag).into_clap(&mut cmd)); } } - // A headless session `--live` falls back to takes the app's rendering, not these. - if m.value_source("gpu") == Some(ValueSource::CommandLine) || m.value_source("no_gpu") == Some(ValueSource::CommandLine) { - if let Some(sub) = cmd.find_subcommand_mut(name) { - return Err(ServerOptionError::LiveGpu.into_clap(sub)); - } - return Err(ServerOptionError::LiveGpu.into_clap(&mut cmd)); - } a.bridge = None; + check_gpu_env(&mut cmd, m)?; return Ok(cli); } a.bridge_from_env = from_env(m, "bridge"); @@ -582,6 +559,9 @@ pub(crate) fn parse(args: &[OsString]) -> Result { return Err(ServerOptionError::BridgeGpu.into_clap(sub)); } check_server(sub, m, a.bridge.is_some(), "--bridge")?; + if a.bridge.is_some() && a.when_closed.is_some() { + return Err(ServerOptionError::BridgeWhenClosed.into_clap(sub)); + } } if a.bridge.is_none() { check_gpu_env(&mut cmd, m)?; diff --git a/apps/photocraft-cli/src/automation.rs b/apps/photocraft-cli/src/automation.rs index 340dabbc31..65c5f80be7 100644 --- a/apps/photocraft-cli/src/automation.rs +++ b/apps/photocraft-cli/src/automation.rs @@ -7,7 +7,7 @@ use photocraft_automation::{Headless, PhotocraftMcp, security}; use crate::{ Result, - args::{CommandsArgs, McpArgs, McpCommand, ServeArgs}, + args::{CommandsArgs, McpArgs, ServeArgs}, output::{JsonStyle, print_json}, }; @@ -68,12 +68,11 @@ pub(crate) fn serve(a: &ServeArgs, err: &mut dyn Write) -> Result { } } -pub(crate) fn mcp(a: &McpArgs, out: &mut dyn Write, err: &mut dyn Write) -> Result { - if let Some(McpCommand::Install(i)) = &a.action { - return mcp_install(&i.client, out); - } +/// `mcp`: the open window when agents may use it, otherwise headless (`mcp_live`); `--headless` +/// always headless; `--bridge` (or PHOTOCRAFT_CONTROL_PORT) a `photocraft --control` app. +pub(crate) fn mcp(a: &McpArgs, err: &mut dyn Write) -> Result { let server = match &a.bridge { - _ if a.live => PhotocraftMcp::live(live_config(a)?), + None if !a.headless => PhotocraftMcp::live(live_config(a)?), Some(addr) => { if a.bridge_from_env { // Name the mode switch, as `serve` does: the way back to headless is to unset it. @@ -99,7 +98,8 @@ pub(crate) fn mcp(a: &McpArgs, out: &mut dyn Write, err: &mut dyn Write) -> Resu Ok(rt.block_on(server.serve_stdio())?) } -/// `mcp --live`: the app's settings folder, the closed-app override and the app launcher. +/// `mcp`: the app's settings folder, the closed-app override, the app launcher, and the headless +/// session's roots and rendering for when it works without the window. fn live_config(a: &McpArgs) -> Result { let other = |m: &str| crate::CliError::Other(m.to_string()); let dir = photocraft_automation::app_dirs::from_env() @@ -107,30 +107,20 @@ fn live_config(a: &McpArgs) -> Result { .ok_or_else(|| other("can't find PhotoCraft's settings folder (no home folder; set PHOTOCRAFT_CONFIG_DIR)"))?; let mut config = photocraft_automation::live::LiveConfig::new(dir); config.when_closed = a.when_closed; - let reads = &a.automation.automation_read_root; - if reads.len() > 1 { - return Err(other("--live takes one --automation-read-root")); - } - config.read_root = reads.first().cloned(); + // As a headless `mcp` always did: folders that can't be opened stop the start, before the + // server answers anything, rather than at the first call that would fall back to them. + a.automation.workspace()?; + config.read_roots.clone_from(&a.automation.automation_read_root); config.write_root = a.automation.automation_write_root.clone(); config.launch = std::env::current_exe().ok().and_then(|exe| photocraft_automation::live::launcher(&exe)); + let policy = crate::gpu::GpuPolicy::from_args(&a.gpu).map_err(crate::CliError::Other)?; + config.prepare_headless = Some(Box::new(move |h| { + policy.apply_to_headless(h); + // stdout carries the protocol; the warnings a headless start has go to stderr. + let mut err = std::io::stderr(); + for d in h.drain_diagnostics() { + let _ = writeln!(err, "warning: {d}"); + } + })); Ok(config) } - -/// `mcp install --client `: add this CLI (`mcp --live`) to an MCP client. -fn mcp_install(id: &str, out: &mut dyn Write) -> Result { - use photocraft_automation::agent_link::{Client, ClientEnv, McpLaunch, install}; - use std::path::Path; - let other = |m: String| crate::CliError::Other(m); - let ids = Client::ALL.map(Client::id).join(", "); - let client = Client::parse(id).ok_or_else(|| other(format!("unknown --client `{id}`: expected one of {ids}")))?; - let exe = std::env::current_exe().map_err(|e| other(format!("can't find this program's path: {e}")))?; - let launch = match std::env::var_os("APPIMAGE").filter(|v| !v.is_empty()) { - Some(image) => McpLaunch::beside(Path::new(""), Some(Path::new(&image))), - // Not canonicalized: Windows would turn it into a `\\?\` path some clients can't start. - None => McpLaunch::cli(&exe), - }; - let done = install(client, &launch, &ClientEnv::from_env())?; - writeln!(out, "{}", done.message(client))?; - Ok(()) -} diff --git a/apps/photocraft-cli/src/lib.rs b/apps/photocraft-cli/src/lib.rs index 6d571ffb1e..7e815db5d2 100644 --- a/apps/photocraft-cli/src/lib.rs +++ b/apps/photocraft-cli/src/lib.rs @@ -57,7 +57,7 @@ where Command::Batch(a) => batch(a, out, err), Command::Droplet(a) => droplet(a, out, err), Command::Commands(a) => commands(a, out), - Command::Mcp(a) => mcp(a, out, err), + Command::Mcp(a) => mcp(a, err), Command::Serve(a) => serve(a, err), }; match result { diff --git a/apps/photocraft-cli/tests/it/cli.rs b/apps/photocraft-cli/tests/it/cli.rs index 3ab0234ab8..7585534a53 100644 --- a/apps/photocraft-cli/tests/it/cli.rs +++ b/apps/photocraft-cli/tests/it/cli.rs @@ -8,7 +8,7 @@ use serde_json::{Value, json}; /// The binary, without the variables `mcp` and `serve` fall back to: a test that wants one sets it. fn bin() -> Command { - let mut cmd = Command::new(crate::binary()); + let mut cmd = crate::command(); for var in ENV_VARS { cmd.env_remove(var); } @@ -163,9 +163,7 @@ fn server_usage_error(args: &[&str], expected: &str) { #[test] fn server_modes_reject_ignored_or_conflicting_options() { for sub in ["mcp", "serve"] { - // `mcp` has a subcommand (`mcp install`), so clap reads a stray word there as one. - let stray = if sub == "mcp" { "unrecognized subcommand 'stray.psd'" } else { "unexpected argument 'stray.psd'" }; - server_usage_error(&[sub, "stray.psd"], stray); + server_usage_error(&[sub, "stray.psd"], "unexpected argument 'stray.psd'"); for flag in ["--control-token", "--control-token-file"] { server_usage_error(&[sub, flag, "unused"], if sub == "mcp" { "requires --bridge" } else { "requires --port" }); } @@ -2032,44 +2030,20 @@ fn info_detail_adds_text_runs_and_antialiasing() { let _ = std::fs::remove_dir_all(&dir); } -/// `mcp install --client json` prints the configuration MCP clients start `mcp --live` with; -/// Cursor's file gets the same entry, other servers kept (Preferences › AI Integrations). +/// Flags that don't go together are usage errors before anything starts. Adding PhotoCraft to an +/// MCP client is the ArtCraft Launcher's job, so there is no `mcp install`, and plain `mcp` does +/// what `--live` did, so there is no `--live` either. #[test] -fn mcp_install_writes_the_live_entry() { - let home = tmp("mcp-install"); - let out = ok(bin().args(["mcp", "install", "--client", "json"]).env("HOME", &home)).stdout; - let v: Value = serde_json::from_str(&out).unwrap(); - 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(); - let out = ok(bin().args(["mcp", "install", "--client", "cursor"]).env("HOME", &home).env("USERPROFILE", &home)).stdout; - assert!(out.contains("Cursor"), "{out}"); - let v: Value = serde_json::from_str(&std::fs::read_to_string(&cursor).unwrap()).unwrap(); - assert_eq!(v["mcpServers"]["other"]["command"], "x"); - assert_eq!(v["mcpServers"]["photocraft"], *entry); -} - -/// Flags that don't go together are usage errors before anything starts. -#[test] -fn mcp_live_and_install_reject_mismatched_flags() { +fn mcp_rejects_mismatched_flags() { for (args, needle) in [ - (&["mcp", "install"][..], "--client"), - (&["mcp", "install", "--client", "vscode"], "vscode"), - (&["mcp", "install", "--client", "json", "--live"], "--live"), - (&["mcp", "frob"], "frob"), + (&["mcp", "install"][..], "install"), + (&["mcp", "--live"], "--live"), (&["mcp", "--client", "json"], "--client"), - (&["mcp", "--when-closed", "launch"], "--live"), - (&["mcp", "--live", "--bridge", "127.0.0.1:1"], "--bridge"), - (&["mcp", "--live", "--control-token-file", "t"], "--control-token-file"), - (&["mcp", "--live", "--when-closed", "sometimes"], "sometimes"), - (&["mcp", "--live", "--gpu"], "--gpu"), + (&["mcp", "--headless", "--bridge", "127.0.0.1:1"], "--bridge"), + (&["mcp", "--headless", "--control-token-file", "t"], "--control-token-file"), + (&["mcp", "--headless", "--when-closed", "launch"], "--when-closed"), + (&["mcp", "--when-closed", "sometimes"], "sometimes"), + (&["mcp", "--bridge", "127.0.0.1:1", "--when-closed", "error"], "--when-closed"), ] { let o = bin().args(args).stdin(Stdio::null()).output().unwrap(); let err = String::from_utf8_lossy(&o.stderr); @@ -2078,22 +2052,15 @@ fn mcp_live_and_install_reject_mismatched_flags() { } } -/// `mcp --live` serves MCP without the app; a tool call says how to connect it. A -/// PHOTOCRAFT_CONTROL_PORT exported for another tool (here not even a port) is not read. -#[test] -fn mcp_live_without_the_app_explains_what_to_do() { - let dir = tmp("mcp-live"); - let mut child = bin() - .args(["mcp", "--live", "--when-closed", "error"]) - .env("PHOTOCRAFT_CONFIG_DIR", &dir) - // The machine's ArtCraft Launcher may have agents on; this test needs them off. - .env("CRAFT_MCP_DIR", &dir) - .env("PHOTOCRAFT_CONTROL_PORT", "not-a-port") - .stdin(Stdio::piped()) - .stdout(Stdio::piped()) - .stderr(Stdio::null()) - .spawn() - .unwrap(); +/// One MCP exchange with `photocraft-cli mcp `: initialize, then each tool call; returns the +/// tool results. +fn mcp_session(args: &[&str], env: &[(&str, &std::ffi::OsStr)], calls: &[(&str, Value)]) -> Vec { + let mut cmd = bin(); + cmd.args(args).stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::null()); + for (k, v) in env { + cmd.env(k, v); + } + let mut child = cmd.spawn().unwrap(); let mut stdin = child.stdin.take().unwrap(); let mut stdout = BufReader::new(child.stdout.take().unwrap()); let mut send = |v: Value| { @@ -2114,12 +2081,37 @@ fn mcp_live_without_the_app_explains_what_to_do() { "protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"test","version":"0"}}})); recv(1); send(json!({"jsonrpc":"2.0","method":"notifications/initialized"})); - send(json!({"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"ui_inspect","arguments":{}}})); - let r = recv(2); - assert_eq!(r["result"]["isError"], true, "{r}"); - assert!(r["result"]["content"][0]["text"].as_str().unwrap().contains("Preferences › AI Integrations › Let AI agents connect"), "{r}"); + let mut out = Vec::new(); + for (i, (name, arguments)) in calls.iter().enumerate() { + let id = 2 + i as u64; + send(json!({"jsonrpc":"2.0","id":id,"method":"tools/call","params":{"name":name,"arguments":arguments}})); + out.push(recv(id)["result"].clone()); + } drop(stdin); let _ = child.kill(); let _ = child.wait(); + out +} + +/// Plain `mcp` without the person's consent works headless, as it always did: commands run, UI +/// tools say they need the open app. `--headless` too, and it doesn't read a PHOTOCRAFT_CONTROL_PORT +/// exported for another tool (here not even a port). +#[test] +fn mcp_without_consent_works_headless() { + let dir = tmp("mcp-plain"); + let empty = tmp("mcp-plain-launcher"); + // `crate::command()` keeps the machine's launcher and flags out already; this test names its + // own settings and an empty launcher folder as well, to say what it relies on. + let env = [("PHOTOCRAFT_CONFIG_DIR", dir.as_os_str()), ("CRAFT_MCP_DIR", empty.as_os_str())]; + let calls = [("command_list", json!({})), ("ui_inspect", json!({}))]; + let r = mcp_session(&["mcp", "--when-closed", "error"], &env, &calls); + assert_ne!(r[0]["isError"], true, "headless commands run: {}", r[0]); + assert_eq!(r[1]["isError"], true, "{}", r[1]); + assert!(r[1]["content"][0]["text"].as_str().unwrap().contains("bridge"), "{}", r[1]); + let mut env = env.to_vec(); + env.push(("PHOTOCRAFT_CONTROL_PORT", std::ffi::OsStr::new("not-a-port"))); + let r = mcp_session(&["mcp", "--headless"], &env, &calls[..1]); + assert_ne!(r[0]["isError"], true, "{}", r[0]); let _ = std::fs::remove_dir_all(&dir); + let _ = std::fs::remove_dir_all(&empty); } diff --git a/apps/photocraft-cli/tests/it/gpu.rs b/apps/photocraft-cli/tests/it/gpu.rs index eeb3faa8db..471e5a486f 100644 --- a/apps/photocraft-cli/tests/it/gpu.rs +++ b/apps/photocraft-cli/tests/it/gpu.rs @@ -6,7 +6,7 @@ use std::process::Command; use serde_json::Value; fn bin() -> Command { - let mut cmd = Command::new(crate::binary()); + let mut cmd = crate::command(); cmd.env_remove("PHOTOCRAFT_CONTROL_PORT"); cmd.env_remove("PHOTOCRAFT_CONTROL_TOKEN"); cmd.env_remove("PHOTOCRAFT_CONTROL_TOKEN_FILE"); diff --git a/apps/photocraft-cli/tests/it/main.rs b/apps/photocraft-cli/tests/it/main.rs index 411791d94c..280d98616d 100644 --- a/apps/photocraft-cli/tests/it/main.rs +++ b/apps/photocraft-cli/tests/it/main.rs @@ -13,3 +13,19 @@ mod psd_write_oracle; fn binary() -> std::ffi::OsString { std::env::var_os("NEXTEST_BIN_EXE_photocraft_cli").unwrap_or_else(|| env!("CARGO_BIN_EXE_photocraft-cli").into()) } + +/// The CLI, kept away from this machine's own PhotoCraft settings, ArtCraft Launcher and feature +/// flags: plain `mcp` works in the open app when the launcher's switch lets agents use it, and +/// would otherwise find (or start) the developer's own PhotoCraft. A test that needs a settings +/// folder of its own sets `PHOTOCRAFT_CONFIG_DIR` again; the last value wins. +fn command() -> std::process::Command { + let base = std::env::temp_dir().join(format!("pc-cli-it-isolated-{}", std::process::id())); + let settings = base.join("settings"); + let _ = std::fs::create_dir_all(&settings); + let mut cmd = std::process::Command::new(binary()); + cmd.env("PHOTOCRAFT_CONFIG_DIR", &settings) + .env("CRAFT_MCP_DIR", base.join("launcher")) + .env("CRAFT_FLAGS_FILE", base.join("flags.toml")) + .env_remove("CRAFT_FLAGS"); + cmd +} diff --git a/apps/photocraft-cli/tests/it/malloc_tuning.rs b/apps/photocraft-cli/tests/it/malloc_tuning.rs index a7513a714a..e19487c514 100644 --- a/apps/photocraft-cli/tests/it/malloc_tuning.rs +++ b/apps/photocraft-cli/tests/it/malloc_tuning.rs @@ -8,7 +8,7 @@ use photocraft_engine::malloc_tuning::{TRIM_THRESHOLD, TRIM_THRESHOLD_VAR}; /// The environment of a running `serve` once it answered a request, as `NAME=value` entries. fn serve_environ(set: Option<&str>) -> Vec { - let mut cmd = Command::new(crate::binary()); + let mut cmd = crate::command(); for var in [TRIM_THRESHOLD_VAR, "MALLOC_MMAP_THRESHOLD_", "MALLOC_TOP_PAD_", "MALLOC_MMAP_MAX_", "MALLOC_ARENA_MAX", "GLIBC_TUNABLES"] { cmd.env_remove(var); } diff --git a/apps/photocraft-cli/tests/it/man_and_completions.rs b/apps/photocraft-cli/tests/it/man_and_completions.rs index d23e6f25a6..9c1e2aabbf 100644 --- a/apps/photocraft-cli/tests/it/man_and_completions.rs +++ b/apps/photocraft-cli/tests/it/man_and_completions.rs @@ -49,8 +49,6 @@ fn the_example_writes_the_files_the_packages_install() { let mut expected: Vec = completions.map(String::from).into(); expected.push("photocraft-cli.1".into()); expected.extend(subcommands.iter().map(|s| format!("photocraft-cli-{s}.1"))); - // Nested subcommands get their own page too (the packages install every `*.1`). - expected.push("photocraft-cli-mcp-install.1".into()); expected.sort(); assert_eq!(written, expected); std::fs::remove_dir_all(&dir).unwrap(); diff --git a/apps/photocraft-cli/tests/it/orientation.rs b/apps/photocraft-cli/tests/it/orientation.rs index 8e8da558c7..e29549e3a7 100644 --- a/apps/photocraft-cli/tests/it/orientation.rs +++ b/apps/photocraft-cli/tests/it/orientation.rs @@ -10,7 +10,7 @@ use photocraft_codecs::{ChannelLayout, DecodeOptions, EncodeOptions, Format, Ima use serde_json::Value; fn bin() -> Command { - Command::new(crate::binary()) + crate::command() } fn tmp(name: &str) -> PathBuf { diff --git a/apps/photocraft/src/agent_link.rs b/apps/photocraft/src/agent_link.rs index b3b2b52054..26fc0756a3 100644 --- a/apps/photocraft/src/agent_link.rs +++ b/apps/photocraft/src/agent_link.rs @@ -1,7 +1,8 @@ -//! Preferences › AI Integrations on the desktop: while *Let AI agents connect* is on, the app -//! serves the control protocol by itself (no `--control`) and publishes the connection file -//! `photocraft-cli mcp --live` finds it by ([`photocraft_automation::agent_link`]). Turning it on -//! or off, or changing the port or folders, applies at once. The token stays in the settings +//! Agents in the open desktop app: while the person lets them in (ArtCraft Launcher › Settings › +//! AI agents; without the `AI-MCP` flag, a Control Port saved before), the app serves the control +//! protocol by itself (no `--control`) and publishes the connection file `photocraft-cli mcp` +//! finds it by ([`photocraft_automation::agent_link`]). Turning it on or off, or changing the +//! port or folders in Preferences › AI Integrations, applies at once. The token stays in the settings //! folder across launches (`agent-control.token`, as `--control-token-file` would keep it; delete //! it for a new one). Agent requests get the policy and the folders chosen there, exactly as with //! `--control` and the automation roots. @@ -12,10 +13,10 @@ use std::path::{Path, PathBuf}; use std::sync::mpsc::Receiver; -use photocraft_automation::agent_link::{self, Client, ClientEnv, Connection, McpLaunch}; +use photocraft_automation::agent_link::{self, Connection}; use photocraft_automation::security; use photocraft_engine::prefs::Integrations; -use photocraft_ui_egui::{AgentClientFn, AgentLink, AgentLinkFn, AgentLinkStatus, ControlRequest}; +use photocraft_ui_egui::{AgentLink, AgentLinkFn, ControlRequest}; use crate::control_server; @@ -49,16 +50,15 @@ fn start(dir: &Path, port: u16, ctx: &egui::Context, port_pref: u32) -> Result<( } /// The agent connection service (`settings_dir`: where the connection file and token go). -pub fn service(settings_dir: Option, mcp: Option) -> AgentLinkFn { +pub fn service(settings_dir: Option) -> AgentLinkFn { let mut running: Option = None; - let mcp_command = mcp.map(|m| m.shell_line()); - Box::new(move |integrations: &Integrations, ctx: &egui::Context| apply(&mut running, settings_dir.as_deref(), integrations, ctx, mcp_command.clone())) + Box::new(move |integrations: &Integrations, ctx: &egui::Context| apply(&mut running, settings_dir.as_deref(), integrations, ctx)) } /// Bring the connection in line with `integrations`: start, restart on another port, stop, or only /// change the folders agents may use. -fn apply(running: &mut Option, dir: Option<&Path>, integrations: &Integrations, ctx: &egui::Context, mcp_command: Option) -> AgentLink { - let mut out = AgentLink { status: AgentLinkStatus { mcp_command, ..Default::default() }, ..Default::default() }; +fn apply(running: &mut Option, dir: Option<&Path>, integrations: &Integrations, ctx: &egui::Context) -> AgentLink { + let mut out = AgentLink::default(); if !integrations.connect_agents { out.stopped = running.take().is_some(); return out; @@ -139,30 +139,6 @@ pub fn launcher_watch(ctx: &egui::Context) -> Box bool> { Box::new(move || on.load(Ordering::Relaxed)) } -/// How MCP clients start this install's CLI (`photocraft-cli mcp --live`), or `None` when it -/// isn't installed beside the app (a development build of the app alone). -pub fn mcp_launch() -> Option { - if let Some(id) = std::env::var_os("FLATPAK_ID").filter(|v| !v.is_empty()) { - let args = ["run", "--command=photocraft-cli", &id.to_string_lossy(), "mcp", "--live"].map(str::to_string).to_vec(); - return Some(McpLaunch { command: "flatpak".into(), args }); - } - let exe = std::env::current_exe().ok()?; - let dir = exe.parent()?; - let appimage = std::env::var_os("APPIMAGE").filter(|v| !v.is_empty()).map(PathBuf::from); - let launch = McpLaunch::beside(dir, appimage.as_deref()); - (appimage.is_some() || dir.join(agent_link::cli_file_name()).is_file()).then_some(launch) -} - -/// Copy Configuration (`json`): the configuration to paste into an MCP client. The same entry -/// point as `photocraft-cli mcp install --client`, which also adds to a client's own file. -pub fn clients(mcp: Option) -> AgentClientFn { - Box::new(move |id: &str| { - let client = Client::parse(id).ok_or_else(|| format!("unknown MCP client `{id}`"))?; - let launch = mcp.as_ref().ok_or_else(|| format!("photocraft-cli isn't installed beside PhotoCraft, so {} can't start it", client.name()))?; - agent_link::install(client, launch, &ClientEnv::from_env()).map(|done| done.message(client)).map_err(|e| e.to_string()) - }) -} - #[cfg(test)] mod tests { use super::*; @@ -184,7 +160,7 @@ mod tests { fn turning_agents_on_publishes_a_reachable_connection_and_off_removes_it() { let dir = temp(); let ctx = egui::Context::default(); - let mut link = service(Some(dir.clone()), None); + let mut link = service(Some(dir.clone())); // Off (the default): nothing listens, nothing is published. let off = link(&Integrations::default(), &ctx); assert!(off.requests.is_none() && !off.stopped && off.status.port.is_none()); @@ -231,7 +207,7 @@ mod tests { fn a_new_port_restarts_with_the_same_token_and_a_taken_port_is_reported() { let dir = temp(); let ctx = egui::Context::default(); - let mut link = service(Some(dir.clone()), None); + let mut link = service(Some(dir.clone())); let first = link(&on(0), &ctx); let first_port = first.status.port.unwrap(); let token_file = dir.join(agent_link::TOKEN_FILE); @@ -264,7 +240,7 @@ mod tests { let settings = dir.join("not-a-folder"); std::fs::write(&settings, b"").unwrap(); let port = std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port(); - let mut link = service(Some(settings), None); + let mut link = service(Some(settings)); let r = link(&on(u32::from(port)), &egui::Context::default()); assert!(r.requests.is_none() && r.status.port.is_none()); assert!(r.status.error.as_deref().is_some_and(|e| e.contains("token file")), "{:?}", r.status.error); @@ -276,7 +252,7 @@ mod tests { #[test] fn a_relative_folder_is_left_out_with_a_reason() { let dir = temp(); - let mut link = service(Some(dir.clone()), None); + let mut link = service(Some(dir.clone())); let r = link(&Integrations { read_root: ".".into(), ..on(0) }, &egui::Context::default()); assert!(r.status.port.is_some()); assert!(r.status.error.as_deref().is_some_and(|e| e.contains("not an absolute path")), "{:?}", r.status.error); @@ -288,7 +264,7 @@ mod tests { #[test] fn allow_agent_control_off_keeps_agents_out() { let dir = temp(); - let mut link = service(Some(dir.clone()), None); + let mut link = service(Some(dir.clone())); let r = link(&Integrations { allow_agent_control: false, ..on(0) }, &egui::Context::default()); assert!(r.requests.is_none() && r.status.port.is_none() && r.automation.command.is_none()); assert!(r.status.error.as_deref().is_some_and(|e| e.contains("Allow Agent Control")), "{:?}", r.status.error); @@ -298,18 +274,8 @@ mod tests { #[test] fn no_settings_folder_is_an_error_not_a_panic() { - let mut link = service(None, None); + let mut link = service(None); let r = link(&on(0), &egui::Context::default()); assert!(r.requests.is_none() && r.status.error.is_some()); } - - #[test] - fn clients_without_a_cli_say_so() { - let mut add = clients(None); - assert!(add("cursor").unwrap_err().contains("photocraft-cli")); - assert!(add("nope").unwrap_err().contains("unknown")); - assert!(add("json").unwrap_err().contains("photocraft-cli")); - let mut add = clients(Some(McpLaunch::cli(Path::new("/x/photocraft-cli")))); - assert!(add("json").unwrap().contains("mcp")); - } } diff --git a/apps/photocraft/src/main.rs b/apps/photocraft/src/main.rs index 7ff5a50a8e..98e4702044 100644 --- a/apps/photocraft/src/main.rs +++ b/apps/photocraft/src/main.rs @@ -111,7 +111,7 @@ fn integrations(prefs_file: Option<&std::path::Path>) -> photocraft_engine::pref let Some(mut section) = file.as_ref().and_then(|v| v.get("integrations")).cloned() else { return out; }; - // As the engine's load does: a Control Port from before *Let AI agents connect* keeps it on. + // As the engine's load does: a Control Port saved before the agents switch keeps it on. photocraft_engine::prefs::migrate_integrations(&mut section); match serde_json::from_value(section.clone()) { Ok(whole) => whole, @@ -359,7 +359,7 @@ struct ControlNotice { /// The `--control` server's port, token and workspace, when it is on (exits 2 on a bad /// configuration). Preferences › AI Integrations' folders stand in for automation roots no flag -/// names. The server Preferences start (*Let AI agents connect*) is `agent_link`'s, not this. +/// names. The server the agents switch starts is `agent_link`'s, not this. fn control_setup( cli_port: Option, auth: photocraft_automation::args::ControlArgs, @@ -719,20 +719,15 @@ fn main() -> eframe::Result { log::warn!("couldn't remember GPU backend {}: {e}", b.name()); } }); - // Preferences › AI Integrations: agents connect without a terminal, unless the launch - // flags (`--control`) manage the connection. - let mcp = agent_link::mcp_launch(); - app.agent_link.mcp_command = mcp.as_ref().map(photocraft_automation::agent_link::McpLaunch::shell_line); - // The new agent settings and the buttons that add PhotoCraft to MCP clients are behind - // the suite's AI-MCP feature flag; the connection itself keeps working as before. + // Agents in the open window, unless the launch flags (`--control`) manage the + // connection. Behind the suite's AI-MCP feature flag, the ArtCraft Launcher's switch + // (Settings › AI agents) is the one consent; without it, as before, a Control Port. let flags = craft_flags::load(); for problem in &flags.problems { log::warn!("feature flags: {problem}"); } app.agent_link.mcp_flag = flags.enabled(&craft_flags::AI_MCP); if app.agent_link.mcp_flag { - app.services.agent_clients = Some(agent_link::clients(mcp.clone())); - // ArtCraft Launcher › Settings › AI agents turns agents on for every Craft app. app.services.launcher_agents = Some(agent_link::launcher_watch(&cc.egui_ctx)); } if let Some((listener, token, _)) = control { @@ -741,7 +736,7 @@ fn main() -> eframe::Result { let rx = control_server::start(listener, token, cc.egui_ctx.clone()); app = app.with_control(rx); } else { - app.services.agent_link = Some(agent_link::service(services::config_dir(), mcp)); + app.services.agent_link = Some(agent_link::service(services::config_dir())); } #[cfg(target_os = "macos")] { @@ -1170,7 +1165,7 @@ mod tests { assert_eq!(r.control_port, 0, "the bad port alone takes its default"); // A bad Allow Agent Control alone takes its default. let r = read(r#"{"integrations":{"allowAgentControl":"no","controlPort":7878}}"#); - // (A saved port from before *Let AI agents connect* turns it on, in both reads.) + // (A saved port from before the agents switch turns it on, in both reads.) assert_eq!(r, photocraft_engine::prefs::Integrations { allow_agent_control: true, control_port: 7878, connect_agents: true, ..Default::default() }); read(r#"{"integrations":{"allowAgentControl":false,"controlPort":-1}}"#); read(r#"{"integrations":{"allowAgentControl":false,"controlPort":4294967296}}"#); diff --git a/book/src/automation/mcp.md b/book/src/automation/mcp.md index e42e504a50..91a75fb4e2 100644 --- a/book/src/automation/mcp.md +++ b/book/src/automation/mcp.md @@ -4,9 +4,9 @@ - **Headless:** an in-process `Headless` session owns the engine and performs file I/O. - **Bridge:** `BridgeClient` forwards tools to a desktop application started with `photocraft --control `. -- **Live:** `photocraft-cli mcp --live` finds the desktop application through the connection file it publishes while Edit › Preferences › AI Integrations › *Let AI agents connect* is on, before every tool call; while the app is closed it starts it, serves a headless session, or reports an error, as chosen there. +- **The open window:** plain `photocraft-cli mcp` finds the desktop application through the connection file it publishes while the person lets agents use it (ArtCraft Launcher › Settings › AI agents), before every tool call; while the app is closed it starts it, serves a headless session, or reports an error, as chosen in Preferences › AI Integrations. Without that consent, or with `--headless`, it is the headless session above. -The simplest setup needs no terminal: turn on ArtCraft Launcher › Settings › AI agents and click *Add* next to the AI app; that reaches every Craft app. Without the launcher, turn on *Let AI agents connect* in PhotoCraft and paste its *Copy Configuration* into the AI app. See [`docs/mcp.md`](../../../docs/mcp.md#connecting-the-desktop-app-no-terminal). +The simplest setup needs no terminal: turn on ArtCraft Launcher › Settings › AI agents and click *Add* next to the AI app; that one entry reaches every Craft app. See [`docs/mcp.md`](../../../docs/mcp.md#connecting-the-desktop-app-no-terminal). For a source checkout, first [install the CLI on PATH and register the server](../../../docs/mcp.md#install-and-register). The installed binary survives `cargo clean`; a symlink into `target/release` does not. @@ -59,11 +59,11 @@ explicitly granted at launch; omitting a root omits that authority. Bridge mode loopback control connection with a bearer token before invoking any control method and uses the roots configured on the desktop process. -*Let AI agents connect* (off by default) opens the same loopback, token-authenticated control -listener as `--control`, with a token the app replaces every time the connection starts (in -`agent-control.token`, user-only on Unix, in the settings folder). The folders chosen in that panel -are the desktop process's roots, and the roots of a `mcp --live` headless session only when *When -PhotoCraft is closed* is set to work without a window. +The launcher's switch (off by default) opens the same loopback, token-authenticated control +listener as `--control`, with a token the app keeps in its settings folder (`agent-control.token`, +user-only on Unix; delete it for a new one). The folders chosen in Preferences › AI Integrations +are the desktop process's roots, and the roots of a `mcp` headless session only when agents may +use the app and *When PhotoCraft is closed* is set to work without a window. The current server does not issue scoped sessions or distinguish trusted tools from high-impact tools. Authentication proves possession of the token; it does not restrict an authenticated client to document-only access. Do not expose either transport through an untrusted broker, shell, proxy, or remote service without adding an external policy boundary. diff --git a/book/src/security/automation-security.md b/book/src/security/automation-security.md index bf7549f614..cc65c7dc81 100644 --- a/book/src/security/automation-security.md +++ b/book/src/security/automation-security.md @@ -29,12 +29,12 @@ Automation is a privilege boundary because requests can cause filesystem access, Screenshots are decoded under separate dimension, pixel, and allocation ceilings before downscaling; the 5 MiB PNG limit applies to the returned image. - MCP normally uses stdio and can optionally bridge to loopback control TCP. -- Edit › Preferences › AI Integrations › *Let AI agents connect* (off by default), or ArtCraft Launcher › Settings › AI agents for every Craft app, opens that loopback +- ArtCraft Launcher › Settings › AI agents (off by default; one switch for every Craft app) opens that loopback listener without launch flags. Its token is kept in a user-only file in the settings folder (`agent-control.token`) and stays the same across restarts and port changes: restarting does not revoke it. To revoke an exposed token, delete that file; the next start creates a new one. The published `agent-connection.json` holds the port and the token file's path, never the - token. `photocraft-cli mcp --live` authenticates with the challenge handshake, so the token + token. `photocraft-cli mcp` authenticates with the challenge handshake, so the token itself is never sent: the listener must first prove it holds the token, and a stale file whose port another program took fails that check before the client reveals anything. - The bridge and UI request paths use timeouts. diff --git a/crates/automation/Cargo.toml b/crates/automation/Cargo.toml index af29a68b35..034bf01e70 100644 --- a/crates/automation/Cargo.toml +++ b/crates/automation/Cargo.toml @@ -39,9 +39,9 @@ hmac = "0.12" sha2 = "0.10" cap-std = "4" clap = { workspace = true } -# The suite's AI-MCP flag and the ArtCraft Launcher's folder: the launcher's agents switch counts as consent. +# The suite's AI-MCP flag and the ArtCraft Launcher's agents switch (the one consent for agents). craft-flags = { workspace = true } -dirs = "7" +craft-ai-agents = { workspace = true } # Optional native GPU rendering backend photocraft-gpu = { workspace = true, optional = true } diff --git a/crates/automation/src/agent_link.rs b/crates/automation/src/agent_link.rs index 8cd86f12eb..12b5620755 100644 --- a/crates/automation/src/agent_link.rs +++ b/crates/automation/src/agent_link.rs @@ -1,13 +1,14 @@ -//! Connecting AI agents to the desktop app without a terminal (Edit › Preferences › AI -//! Integrations): finding the app's control server without being told, and adding PhotoCraft -//! to MCP clients. +//! Connecting AI agents to the open desktop app: whether the person lets them (one switch, in +//! the ArtCraft Launcher, [`agents_allowed`]), and how a local client finds the app's control +//! server without being told. Adding PhotoCraft to MCP clients is the launcher's job (one entry +//! for every Craft app), so nothing here writes a client's configuration. //! -//! When the app starts its control server from the preferences (Allow Agent Control on and a -//! Control Port, no `--control`), it publishes where in its settings folder ([`CONNECTION_FILE`]): -//! the port, its process id and the bearer-token file ([`TOKEN_FILE`] unless a token file was -//! given at launch; created `0600` on Unix, see [`crate::security::server_token`]). A local -//! client reads that file, then the token from the file it names, so nothing has to pass a port -//! or a token to an app started from the Dock, the Start menu or a file manager. +//! While agents may connect (and no `--control` was given), the app serves its control protocol +//! on loopback and publishes where in its settings folder ([`CONNECTION_FILE`]): the port, its +//! process id and the bearer-token file ([`TOKEN_FILE`] unless a token file was given at launch; +//! created `0600` on Unix, see [`crate::security::server_token`]). A local client reads that +//! file, then the token from the file it names, so nothing has to pass a port or a token to an +//! app started from the Dock, the Start menu or a file manager. //! //! The file holds no secret. A crashed (or, on macOS, quit) app can leave it behind; nothing then //! listens on its port ([`probe`]), and the app's next launch replaces it or removes it @@ -16,12 +17,9 @@ //! gap without closing it (a pid can be reused); `docs/control-protocol.md` says when a client //! should not send the token on the strength of this file. //! -//! While *Let AI agents connect* is on, the app starts and stops that server at once when the -//! setting changes. `photocraft-cli mcp --live` ([`crate::live`]) reads the connection file on -//! every tool call, so MCP client configurations never hold a port or a token, and keep working -//! when the app restarts on another port. [`install`] adds that command to an MCP client's own -//! configuration (Claude Desktop, Claude Code, Cursor) or returns the JSON to paste into any -//! other client; the app's buttons and `photocraft-cli mcp install` share it. +//! The app starts and stops that server at once when the switch changes. `photocraft-cli mcp` +//! ([`crate::live`]) reads the connection file on every tool call, so MCP client configurations +//! never hold a port or a token, and keep working when the app restarts on another port. use std::net::{SocketAddr, TcpStream}; use std::path::{Path, PathBuf}; @@ -29,7 +27,7 @@ use std::time::Duration; use photocraft_engine::prefs::Integrations; use serde::{Deserialize, Serialize}; -use serde_json::{Map, Value, json}; +use serde_json::Value; use crate::AutomationError; @@ -179,470 +177,43 @@ pub fn read_integrations(dir: &Path) -> Integrations { .and_then(|text| serde_json::from_str::(&text).ok()) .and_then(|v| v.get("integrations").cloned()) .and_then(|mut v| { - // As the app reads it: a Control Port from before *Let AI agents connect* keeps it on. + // As the app reads it: a Control Port saved before the agents switch keeps it on. photocraft_engine::prefs::migrate_integrations(&mut v); serde_json::from_value(v).ok() }) .unwrap_or_default() } -// ---- ArtCraft Launcher -------------------------------------------------------------------------- +// ---- The agents switch ------------------------------------------------------------------------- -/// The id the ArtCraft Launcher lists PhotoCraft under in its app list. +/// The id the ArtCraft Launcher's app list names PhotoCraft by. pub const LAUNCHER_APP_ID: &str = "photocraft"; -/// The launcher's app list for the MCP gateway (storytold/craft-ai-integrations, -/// `docs/CRAFT-AI-MCP.md`). The launcher writes it when Settings › AI agents › *Let AI agents use -/// Craft apps* is turned on and removes it when that is turned off. -pub const LAUNCHER_APPS_FILE: &str = "apps.json"; -/// Moves the launcher's folder, as it does for the launcher and the gateway. -pub const LAUNCHER_DIR_ENV: &str = "CRAFT_MCP_DIR"; -/// Version of the launcher's app list this reads. -const LAUNCHER_APPS_VERSION: u64 = 1; -/// The launcher's folder: [`LAUNCHER_DIR_ENV`], otherwise `ArtCraft/mcp` in the per-user local -/// configuration folder, where the launcher writes it and the gateway reads it. -pub fn launcher_dir(env: impl Fn(&str) -> Option) -> Option { - match env(LAUNCHER_DIR_ENV) { - Some(d) if !d.is_empty() => Some(PathBuf::from(d)), - _ => dirs::config_local_dir().map(|b| b.join("ArtCraft").join("mcp")), - } +/// The suite's `AI-MCP` feature flag (`ArtCraft/flags.toml` or `CRAFT_FLAGS`). +pub fn mcp_flag() -> bool { + craft_flags::load().enabled(&craft_flags::AI_MCP) } -/// Whether the launcher's app list in `dir` names PhotoCraft. A list that is missing, too big, -/// not JSON or of another version counts as no. -pub fn launcher_lists_photocraft(dir: &Path) -> bool { - let Some(text) = read_small(&dir.join(LAUNCHER_APPS_FILE)).ok().flatten() else { return false }; - let Ok(list) = serde_json::from_str::(&text) else { return false }; - list.get("version").and_then(Value::as_u64) == Some(LAUNCHER_APPS_VERSION) - && list.get("apps").and_then(Value::as_array).is_some_and(|apps| apps.iter().any(|a| a.get("id").and_then(Value::as_str) == Some(LAUNCHER_APP_ID))) -} - -/// The person turned agents on for every Craft app in the ArtCraft Launcher: the suite's `AI-MCP` -/// flag is on and the launcher's app list names PhotoCraft. That switch is their consent, as -/// *Let AI agents connect* is (storytold/craft-ai-integrations#195), so PhotoCraft accepts agents -/// without its own box ticked. Reads two small files; call it from a timer, not every frame. +/// The ArtCraft Launcher's switch (Settings › AI agents › *Let AI agents use Craft apps*) lets +/// agents use PhotoCraft: the `AI-MCP` flag is on and the launcher's app list names PhotoCraft, +/// read through `craft-ai-agents` like the launcher, the MCP gateway and every Craft app do. Reads +/// two small files; ask from a timer, not every frame. pub fn launcher_allows_agents() -> bool { - craft_flags::load().enabled(&craft_flags::AI_MCP) && launcher_dir(|k| std::env::var_os(k)).is_some_and(|d| launcher_lists_photocraft(&d)) + mcp_flag() && craft_ai_agents::allowed(LAUNCHER_APP_ID) } -/// Agents may connect: *Let AI agents connect* is on, or the launcher turned agents on -/// ([`launcher_allows_agents`]). Allow Agent Control off still refuses both. -pub fn agents_allowed(integrations: &Integrations, launcher: bool) -> bool { - integrations.connect_agents || launcher +/// Whether agents may use the open window. With the `AI-MCP` flag only the launcher's switch +/// decides: there is one switch for every Craft app, and none in PhotoCraft. Without the flag it +/// is as on `main`: a Control Port saved in the preferences (`connect_agents`, set from it when +/// the preferences load). Allow Agent Control off still refuses agents either way. +pub fn agents_allowed(integrations: &Integrations, mcp_flag: bool, launcher: bool) -> bool { + if mcp_flag { launcher } else { integrations.connect_agents } } -// ---- MCP clients -------------------------------------------------------------------------------- - -/// How an MCP client starts PhotoCraft's MCP server. -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct McpLaunch { - pub command: String, - pub args: Vec, -} - -impl McpLaunch { - /// ` mcp --live`. - pub fn cli(cli: &Path) -> Self { - McpLaunch { command: cli.to_string_lossy().into_owned(), args: vec!["mcp".into(), "--live".into()] } - } - - /// How to start the CLI that ships beside the executable in `exe_dir`. `appimage` is the - /// AppImage this process runs from (`$APPIMAGE`): its mount point disappears when the app - /// quits, so the AppImage itself starts the CLI (`--cli`, see `packaging/linux/AppRun`). - pub fn beside(exe_dir: &Path, appimage: Option<&Path>) -> Self { - match appimage { - Some(image) => McpLaunch { command: image.to_string_lossy().into_owned(), args: vec!["--cli".into(), "mcp".into(), "--live".into()] }, - None => Self::cli(&exe_dir.join(cli_file_name())), - } - } - - /// The `mcpServers` entry (`{"command", "args"}`). - pub fn entry(&self) -> Value { - json!({"command": self.command, "args": self.args}) - } - - /// A complete configuration to paste into an MCP client. - pub fn config_json(&self) -> String { - let v = json!({"mcpServers": {SERVER_NAME: self.entry()}}); - serde_json::to_string_pretty(&v).unwrap_or_default() - } - - /// The command line, quoted for a POSIX shell (Windows paths are double-quoted). - pub fn shell_line(&self) -> String { - std::iter::once(&self.command).chain(&self.args).map(|s| shell_quote(s)).collect::>().join(" ") - } -} - -fn shell_quote(s: &str) -> String { - if !s.is_empty() && s.bytes().all(|b| b.is_ascii_alphanumeric() || b"/._-+:,@=".contains(&b)) { - s.to_string() - } else if cfg!(windows) { - format!("\"{}\"", s.replace('"', "\\\"")) - } else { - format!("'{}'", s.replace('\'', r"'\''")) - } -} - -/// The CLI's file name on this platform. -pub fn cli_file_name() -> &'static str { - if cfg!(windows) { "photocraft-cli.exe" } else { "photocraft-cli" } -} - -/// MCP clients PhotoCraft can add itself to. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum Client { - ClaudeDesktop, - ClaudeCode, - Cursor, - /// No client: the JSON to paste into any MCP client. - Json, -} - -impl Client { - pub const ALL: [Client; 4] = [Client::ClaudeDesktop, Client::ClaudeCode, Client::Cursor, Client::Json]; - - pub fn id(self) -> &'static str { - match self { - Client::ClaudeDesktop => "claude-desktop", - Client::ClaudeCode => "claude-code", - Client::Cursor => "cursor", - Client::Json => "json", - } - } - - pub fn parse(s: &str) -> Option { - Self::ALL.into_iter().find(|c| c.id() == s) - } - - pub fn name(self) -> &'static str { - match self { - Client::ClaudeDesktop => "Claude Desktop", - Client::ClaudeCode => "Claude Code", - Client::Cursor => "Cursor", - Client::Json => "MCP client", - } - } -} - -/// The environment [`install`] looks at, so tests can point it at a temporary home. -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 { - // 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"), - } - } - - /// 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, 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::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 { - 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 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 => " 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::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(), - } - } -} - -/// 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 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 { - let existing = read_small(file)?; - let mut root = match existing.as_deref().map(str::trim) { - None | Some("") => Map::new(), - Some(text) => match serde_json::from_str::(text) { - Ok(Value::Object(m)) => m, - Ok(_) => return Err(io_error(file, "is not a JSON object; fix or remove it, then try again")), - Err(e) => return Err(io_error(file, format!("is not valid JSON ({e}); fix or remove it, then try again"))), - }, - }; - let servers = root.entry("mcpServers").or_insert_with(|| Value::Object(Map::new())); - let Value::Object(servers) = servers else { - return Err(io_error(file, "`mcpServers` is not an object; fix it, then try again")); - }; - let entry = launch.entry(); - if servers.get(SERVER_NAME) == Some(&entry) { - return Ok(Written { file: file.to_path_buf(), backup: None, unchanged: true }); - } - servers.insert(SERVER_NAME.into(), entry); - let text = serde_json::to_string_pretty(&Value::Object(root)).map_err(|e| AutomationError::Other(e.to_string()))?; - if let Some(parent) = file.parent() { - std::fs::create_dir_all(parent).map_err(|e| io_error(parent, e))?; - } - // Keys are rewritten in sorted order, so keep the user's file as it was. - let backup = match &existing { - Some(old) => { - let mut name = file.file_name().unwrap_or_default().to_os_string(); - name.push(".photocraft-backup"); - let backup = file.with_file_name(name); - photocraft_format::atomic_write(&backup, old.as_bytes()).map_err(|e| io_error(&backup, e))?; - Some(backup) - } - None => None, - }; - photocraft_format::atomic_write(file, format!("{text}\n").as_bytes()).map_err(|e| io_error(file, e))?; - Ok(Written { file: file.to_path_buf(), backup, unchanged: false }) -} - -/// Longest wait for one `claude` command: the Preferences button waits on it. -const CLAUDE_TIMEOUT: Duration = Duration::from_secs(20); - -/// Run `c` and collect its output, killing it after `timeout` (an error then). -fn output_within(mut c: std::process::Command, timeout: Duration) -> std::io::Result { - let mut child = c.spawn()?; - let deadline = std::time::Instant::now() + timeout; - loop { - if child.try_wait()?.is_some() { - return child.wait_with_output(); - } - if std::time::Instant::now() >= deadline { - let _ = child.kill(); - let _ = child.wait(); - return Err(std::io::Error::new(std::io::ErrorKind::TimedOut, format!("no answer within {} s", timeout.as_secs()))); - } - std::thread::sleep(Duration::from_millis(25)); - } -} - -fn install_claude_code(launch: &McpLaunch, env: &ClientEnv) -> Result { - 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]| { - let mut c = std::process::Command::new(&claude); - c.args(args).stdin(std::process::Stdio::null()).stdout(std::process::Stdio::piped()).stderr(std::process::Stdio::piped()); - if let Some(p) = &path { - c.env("PATH", p); - } - output_within(c, CLAUDE_TIMEOUT) - }; - let mut add = vec!["mcp", "add", "--scope", "user", SERVER_NAME, "--", launch.command.as_str()]; - add.extend(launch.args.iter().map(String::as_str)); - // Add first, so an older entry stays when adding can't work at all (no Node, a broken - // install). `add` refuses a name that exists: only then replace that entry (ours, by name). - let mut result = run(&add); - let mut replaced = false; - let exists = || run(&["mcp", "get", SERVER_NAME]).is_ok_and(|out| out.status.success()); - if result.as_ref().is_ok_and(|out| !out.status.success()) && exists() { - // Say so when the older entry could not be removed: adding again would only fail with - // "already exists", and the message must not claim the entry is gone. - let why_not = match run(&["mcp", "remove", "--scope", "user", SERVER_NAME]) { - Ok(out) if out.status.success() => None, - Ok(out) => Some(String::from_utf8_lossy(if out.stderr.is_empty() { &out.stdout } else { &out.stderr }).trim().to_string()), - Err(e) => Some(format!("{}: {e}", claude.display())), - }; - if let Some(why) = why_not { - return Err(AutomationError::Other(format!( - "Claude Code already has a `{SERVER_NAME}` entry and removing it failed ({why}); run this in a terminal to replace it: claude mcp remove --scope user {SERVER_NAME} && {by_hand}" - ))); - } - replaced = true; - result = run(&add); - } - let why = match result { - 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()), - }; - if replaced { - return Err(AutomationError::Other(format!( - "adding PhotoCraft to Claude Code failed ({why}) after its older `{SERVER_NAME}` entry was removed; run this in a terminal to add it again: {by_hand}" - ))); - } - Err(AutomationError::Other(format!("adding PhotoCraft to Claude Code failed ({why}); run this in a terminal instead: {by_hand}"))) +/// [`agents_allowed`] for this run: the flag and the launcher's switch as they are now. +pub fn agents_allowed_now(integrations: &Integrations) -> bool { + let flag = mcp_flag(); + agents_allowed(integrations, flag, flag && craft_ai_agents::allowed(LAUNCHER_APP_ID)) } #[cfg(test)] @@ -658,50 +229,16 @@ mod tests { d } - fn env_at(home: &Path) -> ClientEnv { - 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] - fn the_launcher_list_counts_only_when_it_names_photocraft() { - let dir = temp("launcher"); - assert!(!launcher_lists_photocraft(&dir), "no list: the launcher's switch is off"); - let write = |text: &str| std::fs::write(dir.join(LAUNCHER_APPS_FILE), text).unwrap(); - write(r#"{"version":1,"apps":[{"id":"filmcraft","command":"/x","args":["mcp"]},{"id":"photocraft","command":"/y"}]}"#); - assert!(launcher_lists_photocraft(&dir)); - write(r#"{"version":1,"apps":[{"id":"filmcraft","command":"/x"}]}"#); - assert!(!launcher_lists_photocraft(&dir), "PhotoCraft isn't in the list"); - write(r#"{"version":2,"apps":[{"id":"photocraft","command":"/y"}]}"#); - assert!(!launcher_lists_photocraft(&dir), "another version"); - write(r#"{"version":1,"apps":{"id":"photocraft"}}"#); - assert!(!launcher_lists_photocraft(&dir), "apps not a list"); - write("not json"); - assert!(!launcher_lists_photocraft(&dir)); - std::fs::remove_file(dir.join(LAUNCHER_APPS_FILE)).unwrap(); - std::fs::create_dir(dir.join(LAUNCHER_APPS_FILE)).unwrap(); - assert!(!launcher_lists_photocraft(&dir), "a folder in its place"); - } - - #[test] - fn the_launcher_folder_follows_its_override() { - let at = |v: &str| launcher_dir(|k| (k == LAUNCHER_DIR_ENV).then(|| v.into())); - assert_eq!(at("/portable/mcp"), Some(PathBuf::from("/portable/mcp"))); - assert_eq!(at(""), dirs::config_local_dir().map(|b| b.join("ArtCraft").join("mcp")), "empty means unset"); - } - - #[test] - fn either_switch_lets_agents_in() { - let mut i = Integrations::default(); - assert!(!agents_allowed(&i, false)); - assert!(agents_allowed(&i, true), "the launcher's switch alone"); - i.connect_agents = true; - assert!(agents_allowed(&i, false), "PhotoCraft's box alone"); + fn with_the_flag_only_the_launchers_switch_lets_agents_in() { + let legacy = Integrations { connect_agents: true, ..Default::default() }; + let none = Integrations::default(); + // Without the AI-MCP flag: as on main, a Control Port saved before. + assert!(agents_allowed(&legacy, false, false)); + assert!(!agents_allowed(&none, false, true), "the launcher's list means nothing without the flag"); + // With the flag: the launcher's switch, and nothing else. + assert!(agents_allowed(&none, true, true)); + assert!(!agents_allowed(&legacy, true, false), "no second switch in PhotoCraft"); } #[test] @@ -761,7 +298,7 @@ mod tests { assert_eq!(folder(&i.read_root), Some(PathBuf::from("/in"))); assert_eq!(folder(&i.write_root), None); assert_eq!(folder(" "), None); - // A Control Port saved before *Let AI agents connect* reads as on, as the app reads it. + // A Control Port saved before the agents switch reads as on, as the app reads it. std::fs::write(dir.join("preferences.json"), r#"{"integrations": {"controlPort": 7878}}"#).unwrap(); assert!(read_integrations(&dir).connect_agents); std::fs::write(dir.join("preferences.json"), r#"{"integrations": {"controlPort": 7878, "connectAgents": false}}"#).unwrap(); @@ -769,260 +306,6 @@ mod tests { let _ = std::fs::remove_dir_all(&dir); } - #[test] - fn launch_commands_and_config_json() { - let l = McpLaunch::cli(Path::new("/opt/PhotoCraft/photocraft-cli")); - assert_eq!(l.args, ["mcp", "--live"]); - let v: Value = serde_json::from_str(&l.config_json()).unwrap(); - assert_eq!(v["mcpServers"]["photocraft"]["command"], "/opt/PhotoCraft/photocraft-cli"); - assert_eq!(v["mcpServers"]["photocraft"]["args"], json!(["mcp", "--live"])); - let beside = McpLaunch::beside(Path::new("/opt/PhotoCraft"), None); - assert!(beside.command.ends_with(cli_file_name()), "{}", beside.command); - let image = McpLaunch::beside(Path::new("/tmp/.mount_x/usr/bin"), Some(Path::new("/home/u/PhotoCraft.AppImage"))); - assert_eq!(image.command, "/home/u/PhotoCraft.AppImage"); - assert_eq!(image.args, ["--cli", "mcp", "--live"]); - if !cfg!(windows) { - assert_eq!(McpLaunch::cli(Path::new("/a b/it's")).shell_line(), r"'/a b/it'\''s' mcp --live"); - } - for c in Client::ALL { - assert_eq!(Client::parse(c.id()), Some(c)); - } - assert_eq!(Client::parse("vscode"), None); - } - - #[test] - fn install_adds_the_entry_and_keeps_other_servers_and_settings() { - let launch = McpLaunch::cli(Path::new("/opt/PhotoCraft/photocraft-cli")); - 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); - } - - #[test] - fn install_refuses_to_overwrite_a_file_it_cannot_read_as_json() { - let home = temp("install-bad"); - let env = env_at(&home); - let launch = McpLaunch::cli(Path::new("/x/photocraft-cli")); - 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(); - let e = install(Client::Cursor, &launch, &env).unwrap_err().to_string(); - assert!(e.contains("try again"), "{e}"); - assert_eq!(std::fs::read_to_string(&file).unwrap(), text, "left untouched"); - } - let _ = std::fs::remove_dir_all(&home); - } - - #[test] - fn claude_code_without_the_claude_command_names_the_command_to_run() { - let home = temp("claude-code"); - 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. - } - let e = install(Client::ClaudeCode, &McpLaunch::cli(Path::new("/x/photocraft-cli")), &env).unwrap_err().to_string(); - assert!(e.contains("claude mcp add --scope user photocraft -- /x/photocraft-cli mcp --live"), "{e}"); - 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 exists = home.join("exists"); - let keep = home.join("keep"); - // `add` fails while an entry exists (as claude's does) or while `fail` is there; `remove` - // removes the entry, or fails while `keep` is there. `PATH` holds only claude's folder and - // an empty one, so anything that isn't a shell builtin needs its full path. - let script = format!( - "#!/bin/sh\nprintf 'PATH=%s\\n' \"$PATH\" >> '{log}'\nprintf '%s ' \"$@\" >> '{log}'\nprintf '\\n' >> '{log}'\n\ - if [ \"$2\" = remove ] && [ -e '{keep}' ]; then echo 'locked' >&2; exit 1; fi\n\ - if [ \"$2\" = remove ]; then /bin/rm -f '{exists}'; exit 0; fi\n\ - if [ \"$2\" = get ]; then [ -e '{exists}' ]; exit $?; fi\n\ - if [ \"$2\" = add ] && [ -e '{exists}' ]; then echo 'already exists' >&2; exit 1; fi\n\ - if [ \"$2\" = add ] && [ -e '{fail}' ]; then echo 'boom' >&2; exit 1; fi\n\ - if [ \"$2\" = add ]; then : > '{exists}'; fi\n", - log = log.display(), - fail = fail.display(), - exists = exists.display(), - keep = keep.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) - }; - // No entry yet: added, nothing removed. - assert_eq!(run().unwrap(), Installed::ClaudeCode); - let calls = std::fs::read_to_string(&log).unwrap(); - assert!(!calls.contains("mcp remove"), "{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}"); - // An entry exists: replaced. - assert_eq!(run().unwrap(), Installed::ClaudeCode); - assert!(std::fs::read_to_string(&log).unwrap().contains("mcp remove --scope user photocraft \n")); - assert!(exists.exists()); - // An entry exists and adding can't work: the error says the older entry went, and how to add it. - std::fs::write(&fail, "").unwrap(); - let e = run().unwrap_err().to_string(); - assert!(e.contains("was removed") && e.contains("claude mcp add --scope user photocraft -- /x/photocraft-cli mcp --live"), "{e}"); - // No entry and adding can't work: nothing is removed. - std::fs::write(&log, "").unwrap(); - let e = run().unwrap_err().to_string(); - assert!(e.contains("boom") && !e.contains("was removed"), "{e}"); - assert!(!std::fs::read_to_string(&log).unwrap().contains("mcp remove")); - // An entry exists and removing it fails: the error says so, and does not claim it went. - std::fs::remove_file(&fail).unwrap(); - std::fs::write(&exists, "").unwrap(); - std::fs::write(&keep, "").unwrap(); - let e = run().unwrap_err().to_string(); - assert!(e.contains("removing it failed (locked)") && !e.contains("was removed"), "{e}"); - assert!(e.contains("claude mcp remove --scope user photocraft && claude mcp add"), "{e}"); - assert!(exists.exists(), "the older entry is still there"); - let _ = std::fs::remove_dir_all(&home); - } - - /// A `claude` that never answers can't hang the Preferences button. - #[cfg(unix)] - #[test] - fn a_command_that_hangs_is_stopped_after_the_timeout() { - let mut c = std::process::Command::new("sleep"); - c.arg("30").stdout(std::process::Stdio::piped()).stderr(std::process::Stdio::piped()); - let t = std::time::Instant::now(); - let e = output_within(c, Duration::from_millis(200)).unwrap_err(); - assert_eq!(e.kind(), std::io::ErrorKind::TimedOut); - assert!(t.elapsed() < Duration::from_secs(5)); - } - - #[test] - fn json_client_returns_the_configuration() { - let launch = McpLaunch::cli(Path::new("/x/photocraft-cli")); - 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"); - } - - // ---- connection file (Preferences › AI Integrations) ---- - #[test] fn a_published_connection_reads_back_in_the_documented_shape() { let dir = temp("conn"); diff --git a/crates/automation/src/lib.rs b/crates/automation/src/lib.rs index 47be6e0d8c..4b86a28e18 100644 --- a/crates/automation/src/lib.rs +++ b/crates/automation/src/lib.rs @@ -12,7 +12,7 @@ //! control protocol's envelope, used by `photocraft-cli serve`. //! * [`files`]: open/save any supported format, `.pcraft` natively. //! * [`agent_link`] and [`live`]: connecting agents to the desktop app without a terminal -//! (Edit › Preferences › AI Integrations, `photocraft-cli mcp --live` and `mcp install`). +//! (the ArtCraft Launcher's agents switch and plain `photocraft-cli mcp`). //! //! L6, no UI-toolkit dependencies. #![forbid(unsafe_code)] diff --git a/crates/automation/src/live.rs b/crates/automation/src/live.rs index 894d82234f..ba39eb729d 100644 --- a/crates/automation/src/live.rs +++ b/crates/automation/src/live.rs @@ -1,12 +1,13 @@ -//! `photocraft-cli mcp --live`: tools go to the desktop app found through its connection file -//! ([`crate::agent_link`]). The file is looked up again on every tool call, so the app may start, -//! quit or move to another port while the MCP client stays connected, and the MCP client's own -//! start never opens a window. +//! `photocraft-cli mcp`: tools go to the open desktop app when the person lets agents use it, +//! found through its connection file ([`crate::agent_link`]), and otherwise to a session without +//! a window, as `mcp` always did (`--headless` forces that). The file is looked up again on every +//! tool call, so the app may start, quit or move to another port while the MCP client stays +//! connected, and the MCP client's own start never opens a window. //! -//! While the app is closed, MCP › When PhotoCraft Is Closed (or `--when-closed`) +//! While agents may use the app but it is closed, When PhotoCraft Is Closed (or `--when-closed`) //! decides: start the app and wait for it, serve a headless session with the folders chosen in -//! the app (then for the rest of the MCP session, so documents don't move under the agent), or -//! report an error that says what to do. +//! the app, or report an error that says what to do. A session that went headless stays headless +//! for the rest of the MCP session, so documents don't move under the agent. use std::path::{Path, PathBuf}; use std::sync::{Arc, Mutex, PoisonError}; @@ -21,6 +22,8 @@ use crate::{AuthorizedWorkspace, security}; /// Starts the desktop app (see [`launcher`]). pub type LaunchFn = Box Result<(), String> + Send + Sync>; +/// Prepares a headless session before its first call (see [`LiveConfig::prepare_headless`]). +pub type PrepareFn = Box; /// How long a started app gets to accept agents. A first start can take a while (GPU driver /// shader caches, font scan), but MCP clients give a tool call about a minute. @@ -32,16 +35,18 @@ pub struct LiveConfig { pub config_dir: PathBuf, /// Overrides the app's preference (`--when-closed`). pub when_closed: Option, - /// Override the app's folders for a headless session (`--automation-read-root`, - /// `--automation-write-root`). - pub read_root: Option, + /// The folders a headless session may use (`--automation-read-root`, repeatable, and + /// `--automation-write-root`); while agents may use the app, they override its folders. + pub read_roots: Vec, pub write_root: Option, /// Starts the app; `None` when this install can't (Flatpak sandbox, no app beside the CLI). pub launch: Option, pub launch_timeout: Duration, - /// Whether the ArtCraft Launcher turned agents on for every Craft app - /// ([`agent_link::launcher_allows_agents`]); tests replace it. - pub launcher_allows: fn() -> bool, + /// Whether the person lets agents use the open app, given its saved preferences + /// ([`agent_link::agents_allowed_now`]: the ArtCraft Launcher's switch); tests replace it. + pub allowed: fn(&photocraft_engine::prefs::Integrations) -> bool, + /// Prepares a headless session before its first call (the CLI's `--gpu` / `--no-gpu`). + pub prepare_headless: Option, } impl LiveConfig { @@ -49,11 +54,12 @@ impl LiveConfig { LiveConfig { config_dir, when_closed: None, - read_root: None, + read_roots: Vec::new(), write_root: None, launch: None, launch_timeout: LAUNCH_TIMEOUT, - launcher_allows: agent_link::launcher_allows_agents, + allowed: agent_link::agents_allowed_now, + prepare_headless: None, } } } @@ -97,33 +103,50 @@ impl Live { return Ok(()); } let dir = self.cfg.config_dir.clone(); - let launcher_allows = self.cfg.launcher_allows; - let (found, integrations, launcher) = blocking(move || (find_app(&dir), agent_link::read_integrations(&dir), launcher_allows())).await?; - let allowed = agent_link::agents_allowed(&integrations, launcher); + let consent = self.cfg.allowed; + let (found, integrations, allowed) = blocking(move || { + let integrations = agent_link::read_integrations(&dir); + let allowed = consent(&integrations); + (find_app(&dir), integrations, allowed) + }) + .await?; if let Some((c, token)) = found? { self.use_app(&c, token)?; return Ok(()); } + if !allowed { + // As `mcp` always worked: a session without a window, with only the folders given to + // this command. The app's own folders are for agents the person let in. + return self.headless(&self.cfg.read_roots, self.cfg.write_root.clone(), "the automation roots can't be used"); + } match self.cfg.when_closed.unwrap_or(integrations.when_app_closed) { - WhenAppClosed::Error => Err(closed(allowed)), + WhenAppClosed::Error => Err("PhotoCraft isn't running: open it, then try again.".into()), WhenAppClosed::Headless => { - let read = self.cfg.read_root.clone().or_else(|| agent_link::folder(&integrations.read_root)); + let reads = if self.cfg.read_roots.is_empty() { + agent_link::folder(&integrations.read_root).into_iter().collect() + } else { + self.cfg.read_roots.clone() + }; let write = self.cfg.write_root.clone().or_else(|| agent_link::folder(&integrations.write_root)); - let workspace = AuthorizedWorkspace::new(read.as_deref(), write.as_deref()) - .map_err(|e| format!("PhotoCraft isn't running and its agent folders can't be used: {e}"))?; - self.set(Target::Headless(Arc::new(Mutex::new(Headless::with_workspace(workspace)))), None); - Ok(()) + self.headless(&reads, write, "PhotoCraft isn't running and its agent folders can't be used") } - WhenAppClosed::Launch => self.launch_and_wait(allowed).await, + WhenAppClosed::Launch => self.launch_and_wait().await, } } - /// `allowed`: agents may connect ([`agent_link::agents_allowed`]); otherwise the app would never - /// listen, so it isn't started. - async fn launch_and_wait(&self, allowed: bool) -> Result<(), String> { - if !allowed { - return Err(closed(false)); + /// Serve a headless session with these folders from now on. + fn headless(&self, reads: &[PathBuf], write: Option, why: &str) -> Result<(), String> { + let workspace = AuthorizedWorkspace::with_read_roots(reads.iter().map(PathBuf::as_path), write.as_deref()).map_err(|e| format!("{why}: {e}"))?; + let mut session = Headless::with_workspace(workspace); + if let Some(prepare) = &self.cfg.prepare_headless { + prepare(&mut session); } + self.set(Target::Headless(Arc::new(Mutex::new(session))), None); + Ok(()) + } + + /// Start the app (agents may use it) and wait until it accepts them. + async fn launch_and_wait(&self) -> Result<(), String> { let Some(launch) = &self.cfg.launch else { return Err("PhotoCraft isn't running, and this install can't start it from here: open PhotoCraft, then try again.".into()); }; @@ -137,7 +160,7 @@ impl Live { } if Instant::now() >= deadline { return Err(format!( - "PhotoCraft didn't accept agents within {} s of starting. If it's still opening, try again in a moment; otherwise check Edit › Preferences › AI Integrations.", + "PhotoCraft didn't accept agents within {} s of starting. If it's still opening, try again in a moment; otherwise check that AI agents are on in ArtCraft Launcher › Settings › AI agents.", self.cfg.launch_timeout.as_secs() )); } @@ -172,14 +195,6 @@ fn find_app(dir: &Path) -> Result, String> { Ok(Some((c, token))) } -fn closed(allowed: bool) -> String { - if allowed { - "PhotoCraft isn't running: open it, then try again.".into() - } else { - "PhotoCraft doesn't accept AI agents: open it, turn on Edit › Preferences › AI Integrations › Let AI agents connect (or ArtCraft Launcher › Settings › AI agents), then try again.".into() - } -} - /// How to start the desktop app that ships with the CLI at `cli` (detached, with no standard /// streams: the CLI's carry the MCP protocol, and the app must outlive the MCP client). pub fn launcher(cli: &Path) -> Option { diff --git a/crates/automation/src/server.rs b/crates/automation/src/server.rs index 4ac27ea463..1d2729c644 100644 --- a/crates/automation/src/server.rs +++ b/crates/automation/src/server.rs @@ -29,7 +29,7 @@ pub enum Backend { /// A running desktop app reached over the control protocol. Bridge(Arc), /// The desktop app found through its connection file before each call, or the closed-app - /// choice (`photocraft-cli mcp --live`, see [`crate::live`]). + /// choice (plain `photocraft-cli mcp`, see [`crate::live`]). Live(Arc), } @@ -623,7 +623,8 @@ impl PhotocraftMcp { Ok(Self::with_backend(Backend::Bridge(Arc::new(BridgeClient::new(addr, token)?)))) } - /// Serve the desktop app found through its connection file (`photocraft-cli mcp --live`). + /// Serve the desktop app found through its connection file, or headless without consent + /// (plain `photocraft-cli mcp`). pub fn live(config: LiveConfig) -> Self { Self::with_backend(Backend::Live(Arc::new(Live::new(config)))) } @@ -663,7 +664,7 @@ impl PhotocraftMcp { ) } - /// The headless session tools run on, if this backend (or `--live`'s choice) is one. + /// The headless session tools run on, if this backend (or the live choice) is one. fn headless_session(&self) -> Option>> { match &*self.backend { Backend::Headless(h) => Some(h.clone()), @@ -686,7 +687,7 @@ impl PhotocraftMcp { } } - /// Where calls go now: the backend's session or app, or `--live`'s last resolve. + /// Where calls go now: the backend's session or app, or the live mode's last resolve. fn target(&self) -> Option { match &*self.backend { Backend::Headless(h) => Some(Target::Headless(h.clone())), @@ -695,7 +696,7 @@ impl PhotocraftMcp { } } - /// `--live`: find the app (or apply the closed-app choice) before a call; the error is the + /// Live mode: find the app (or apply the closed-app choice) before a call; the error is the /// call's result. Other backends are always ready. async fn ready(&self) -> Result<(), String> { match &*self.backend { @@ -1169,7 +1170,7 @@ impl PhotocraftMcp { /// Run one command in either backend; `at` is its place in a batch, for progress. async fn step(&self, id: String, params: Value, wait: bool, waiter: &mut Waiter, at: (usize, usize)) -> Result { let none = || Err(AutomationError::Other("internal error: no headless session or app bridge".into())); - // `--live` goes wherever its last resolve pointed: the app, or a headless session. + // Live mode goes wherever its last resolve pointed: the app, or a headless session. match (self.headless_session(), self.bridge_client()) { (Some(_), _) if wait => self.headless_wait(id, params, waiter, at).await.unwrap_or_else(none), (Some(_), _) => self.headless_op(move |h| h.command_start(&id, params, false)).await.unwrap_or_else(none), @@ -1189,7 +1190,7 @@ impl PhotocraftMcp { let mut failed = 0; // The reply travels as escaped JSON text, so steps are charged their escaped size. let mut reply_budget = BatchReplyBudget::escaped(); - // `--live` may find a restarted app (or go headless) while a batch runs: its steps must + // Live mode may find a restarted app (or go headless) while a batch runs: its steps must // not end up split across two documents in two places. let pinned = self.target(); for (i, s) in p.steps.into_iter().enumerate() { diff --git a/crates/automation/src/server/progress.rs b/crates/automation/src/server/progress.rs index be27ef8187..9152157dfd 100644 --- a/crates/automation/src/server/progress.rs +++ b/crates/automation/src/server/progress.rs @@ -93,7 +93,7 @@ impl Waiter { /// Cancels a waited job when its waiter goes away without collecting it: rmcp may drop the /// request future on cancellation, and nothing else would stop the job. struct Abandon { - /// The session or app that started the job: under `--live` the current target can change + /// The session or app that started the job: in live mode the current target can change /// before the guard drops, and the job id means nothing elsewhere. target: Target, job: Option, diff --git a/crates/automation/tests/mcp_live.rs b/crates/automation/tests/mcp_live.rs index f696db8e5b..8100248f16 100644 --- a/crates/automation/tests/mcp_live.rs +++ b/crates/automation/tests/mcp_live.rs @@ -1,4 +1,4 @@ -//! `photocraft-cli mcp --live` (Preferences › AI Integrations): the MCP server finds the desktop +//! Plain `photocraft-cli mcp` with agents allowed (the ArtCraft Launcher's switch): the MCP server finds the desktop //! app through its connection file before every call, follows it to a new port and token, and //! applies the closed-app choice (start it, headless, or an error) when no app answers. @@ -60,7 +60,7 @@ fn prefs(dir: &Path, integrations: Value) { std::fs::write(dir.join("preferences.json"), json!({"integrations": integrations}).to_string()).unwrap(); } -/// A desktop app as `--live` sees it: a control server on a free port with a fresh token, its +/// A desktop app as `mcp` sees it: a control server on a free port with a fresh token, its /// connection file published in `dir`. `ui.inspect` answers with `name`. [`quit`] stops it. struct FakeApp { port: u16, @@ -125,21 +125,19 @@ fn live(dir: &Path, when_closed: Option) -> LiveConfig { let mut c = LiveConfig::new(dir.to_path_buf()); c.when_closed = when_closed; c.launch_timeout = Duration::from_secs(10); - // The machine's own ArtCraft Launcher settings stay out of the tests. - c.launcher_allows = || false; + // The machine's own ArtCraft Launcher and feature flags stay out of the tests: agents are + // allowed exactly when the test's preferences say so (as without the AI-MCP flag). + c.allowed = |i| i.connect_agents; c } #[tokio::test(flavor = "multi_thread")] async fn a_closed_app_is_a_tool_error_that_says_what_to_do() { let dir = settings_dir("closed"); + prefs(&dir, json!({"connectAgents": true})); let client = connect(PhotocraftMcp::live(live(&dir, Some(WhenAppClosed::Error)))).await; // The tool list doesn't need the app. assert!(client.list_all_tools().await.unwrap().iter().any(|t| t.name == "ui_inspect")); - let r = call(&client, "ui_inspect", json!({})).await; - assert_eq!(r.is_error, Some(true)); - assert!(text(&r).contains("Let AI agents connect"), "connection off: {}", text(&r)); - prefs(&dir, json!({"connectAgents": true})); let r = call(&client, "command_list", json!({})).await; assert_eq!(r.is_error, Some(true)); assert!(text(&r).contains("isn't running"), "{}", text(&r)); @@ -197,16 +195,19 @@ async fn launch_starts_the_app_once_and_only_when_agents_may_connect() { })); c }; - // Agent connections off in the app: it would never listen, so it isn't started. + // Agents not allowed: the app would never listen, so it isn't started; the session works + // without a window, as `mcp` always did. let client = connect(PhotocraftMcp::live(config(&dir))).await; let r = call(&client, "ui_inspect", json!({})).await; - assert!(text(&r).contains("Let AI agents connect"), "{}", text(&r)); + assert!(text(&r).contains("bridge"), "UI tools need the open app: {}", text(&r)); + let r = call(&client, "command_list", json!({})).await; + assert_eq!(r.is_error, Some(false), "{}", text(&r)); assert_eq!(launches.load(Ordering::SeqCst), 0); client.cancel().await.unwrap(); - // The ArtCraft Launcher's switch alone is consent: the app is started without its own box. + // The ArtCraft Launcher's switch is the consent: the app is started on it alone. let mut c = config(&dir); - c.launcher_allows = || true; + c.allowed = |_| true; let client = connect(PhotocraftMcp::live(c)).await; let r = call(&client, "ui_inspect", json!({})).await; assert_eq!(r.is_error, Some(false), "{}", text(&r)); @@ -265,7 +266,7 @@ async fn headless_uses_the_app_folders_and_stays_headless() { let dir = settings_dir("headless"); let work = dir.join("work"); std::fs::create_dir_all(&work).unwrap(); - prefs(&dir, json!({"whenAppClosed": "headless", "writeRoot": work.to_string_lossy()})); + prefs(&dir, json!({"connectAgents": true, "whenAppClosed": "headless", "writeRoot": work.to_string_lossy()})); let client = connect(PhotocraftMcp::live(live(&dir, None))).await; let r = call(&client, "doc_new", json!({"width": 8, "height": 8})).await; assert_eq!(r.is_error, Some(false), "{}", text(&r)); @@ -284,7 +285,7 @@ async fn headless_uses_the_app_folders_and_stays_headless() { client.cancel().await.unwrap(); quit(app); // A folder that doesn't exist is a clear error, not a crash. - prefs(&dir, json!({"whenAppClosed": "headless", "readRoot": dir.join("missing").to_string_lossy()})); + prefs(&dir, json!({"connectAgents": true, "whenAppClosed": "headless", "readRoot": dir.join("missing").to_string_lossy()})); std::fs::remove_file(dir.join(agent_link::CONNECTION_FILE)).unwrap(); let client = connect(PhotocraftMcp::live(live(&dir, None))).await; let r = call(&client, "command_list", json!({})).await; @@ -293,3 +294,46 @@ async fn headless_uses_the_app_folders_and_stays_headless() { client.cancel().await.unwrap(); let _ = std::fs::remove_dir_all(&dir); } + +/// Agents not allowed: `mcp` serves a session without a window as it always did, with only the +/// folders given to the command (the app's own folders are for agents the person let in), never +/// starts the app, and prepares the session as the command asked (`--gpu`). +#[tokio::test(flavor = "multi_thread")] +async fn without_consent_mcp_is_headless_with_its_own_folders() { + static PREPARED: AtomicUsize = AtomicUsize::new(0); + let dir = settings_dir("no-consent"); + let (app_folder, given) = (dir.join("app-folder"), dir.join("given")); + std::fs::create_dir_all(&app_folder).unwrap(); + std::fs::create_dir_all(&given).unwrap(); + prefs(&dir, json!({"whenAppClosed": "launch", "writeRoot": app_folder.to_string_lossy()})); + let launches = Arc::new(AtomicUsize::new(0)); + let config = |write_root: Option| { + let mut c = live(&dir, None); + c.write_root = write_root; + let launches = launches.clone(); + c.launch = Some(Box::new(move || { + launches.fetch_add(1, Ordering::SeqCst); + Ok(()) + })); + c.prepare_headless = Some(Box::new(|_| { + PREPARED.fetch_add(1, Ordering::SeqCst); + })); + c + }; + let client = connect(PhotocraftMcp::live(config(None))).await; + let r = call(&client, "doc_new", json!({"width": 8, "height": 8})).await; + assert_eq!(r.is_error, Some(false), "{}", text(&r)); + let r = call(&client, "doc_save", json!({"path": "out.pcraft"})).await; + assert_eq!(r.is_error, Some(true), "the app's folder isn't granted without consent"); + assert!(!app_folder.join("out.pcraft").exists()); + client.cancel().await.unwrap(); + let client = connect(PhotocraftMcp::live(config(Some(given.clone())))).await; + call(&client, "doc_new", json!({"width": 8, "height": 8})).await; + let r = call(&client, "doc_save", json!({"path": "out.pcraft"})).await; + assert_eq!(r.is_error, Some(false), "{}", text(&r)); + assert!(given.join("out.pcraft").exists(), "the command's own root is used"); + client.cancel().await.unwrap(); + assert_eq!(launches.load(Ordering::SeqCst), 0, "never started without consent"); + assert_eq!(PREPARED.load(Ordering::SeqCst), 2, "each headless session is prepared once"); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/engine/src/prefs.rs b/crates/engine/src/prefs.rs index d33d84d783..6543c9d311 100644 --- a/crates/engine/src/prefs.rs +++ b/crates/engine/src/prefs.rs @@ -121,7 +121,7 @@ choice!( RawDemosaic { Ahd = "ahd", Mhc = "mhc", Bilinear = "bilinear" } default Ahd ); choice!( - /// MCP › When PhotoCraft Is Closed: what `photocraft-cli mcp --live` does when an + /// MCP › When PhotoCraft Is Closed: what `photocraft-cli mcp` does when an /// agent calls a tool and the app isn't running. WhenAppClosed { Launch = "launch", Headless = "headless", Error = "error" } default Launch ); @@ -1174,10 +1174,10 @@ impl Default for RawDefaults { } } -/// Before *Let AI agents connect*, a Control Port other than 0 started the control server by itself. +/// Before the agents switch, a Control Port other than 0 started the control server by itself. /// A saved `integrations` section like that keeps its connection: the port now means "on, at this /// port". Every reader of the saved section applies this (the app, its launch read, and -/// `photocraft-cli mcp --live`), so they agree. +/// `photocraft-cli mcp`), so they agree. pub fn migrate_integrations(section: &mut Value) { if let Some(integrations) = section.as_object_mut() && !integrations.contains_key("connectAgents") @@ -1200,12 +1200,14 @@ pub struct Integrations { /// The folder automation may write to when no `--automation-write-root` is given (empty = /// none). Applied at once while agents are connected. pub write_root: String, - /// Let AI agents connect: while on, the desktop app serves the control protocol on loopback - /// for `photocraft-cli mcp --live` without `--control`, and starts or stops it at once when - /// this changes (off by default; launch flags still win). After the older fields, so a + /// Without the suite's `AI-MCP` flag, agents may connect: the desktop app serves the control + /// protocol on loopback for `photocraft-cli mcp` without `--control`, and starts or stops it at + /// once when this changes (off by default; launch flags still win). Set from a saved Control + /// Port ([`migrate_integrations`]); not in the dialog. With the flag the ArtCraft Launcher's + /// switch decides instead. After the older fields, so a /// section saved as a list still reads them where they were. pub connect_agents: bool, - /// What `photocraft-cli mcp --live` does while the app is closed. + /// What `photocraft-cli mcp` does while agents may use the app but it is closed. pub when_app_closed: WhenAppClosed, } diff --git a/crates/engine/src/prefs/tests.rs b/crates/engine/src/prefs/tests.rs index 20a015634e..aec791d96f 100644 --- a/crates/engine/src/prefs/tests.rs +++ b/crates/engine/src/prefs/tests.rs @@ -1218,7 +1218,7 @@ fn an_effect_cache_above_the_cap_loads_clamped_and_does_not_block_apply() { } } -/// A file from before *Let AI agents connect* whose Control Port started the control server keeps +/// A file from before the agents switch whose Control Port started the control server keeps /// it on; one without a port, or that already says, is left as it is. #[test] fn a_saved_control_port_turns_the_agent_connection_on() { diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 014c8d2b67..15fc6dfef0 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -261,7 +261,7 @@ pub(crate) use services::SAVE_OPTIONS_OPEN; #[cfg(test)] pub(crate) use services::saved_revision_after_write; pub use services::{ - AdoptAutosaveFn, AgentClientFn, AgentLink, AgentLinkFn, AgentLinkStatus, AppendTextFn, AutomationAuthorizeFn, AutomationCommandFn, AutomationOpenPcraftFn, + AdoptAutosaveFn, AgentLink, AgentLinkFn, AgentLinkStatus, AppendTextFn, AutomationAuthorizeFn, AutomationCommandFn, AutomationOpenPcraftFn, AutomationReadFn, AutomationServices, AutomationWriteFn, AutosaveFn, AutosaveResultsFn, CapsLockFn, CaptionStyleFn, ClipboardGetFn, ClipboardGetSvgFn, ClipboardSetFn, ClipboardUnreadableFn, CursorPosFn, DiscardAutosaveFn, EncodePngFn, ExportFn, ExportSettings, ExternalSvgEditor, ExternalSvgSession, ExternalVectorSave, ExternalVectorSource, FileStamp, FileStampFn, FormatChoices, ImportFn, Inbox, LastUpdateFn, LoadTextFn, OpenExternalSvgFn, OpenUrlFn, diff --git a/crates/ui-egui/src/prefs/prefs_ui/agents.rs b/crates/ui-egui/src/prefs/prefs_ui/agents.rs index 18c5134db8..0d6feb588e 100644 --- a/crates/ui-egui/src/prefs/prefs_ui/agents.rs +++ b/crates/ui-egui/src/prefs/prefs_ui/agents.rs @@ -1,6 +1,7 @@ -//! Preferences › AI Integrations: the agent connection (`integrations.connectAgents`), the folders -//! agents may use, what `photocraft-cli mcp --live` does while the app is closed, and the buttons -//! that copies the configuration for an MCP client. Changes apply at once, without a restart. +//! Preferences › AI Integrations: whether agents can use the open app (one switch for every Craft +//! app, in the ArtCraft Launcher), the port, the folders agents may use, and what +//! `photocraft-cli mcp` does while the app is closed. Changes apply at once, without a restart. +//! Adding PhotoCraft to an MCP client is the launcher's job too, so there is nothing for it here. use super::dialogs::is_preferences; use super::fields::{choice_label, humanize}; @@ -12,14 +13,18 @@ pub(super) const AGENT_LINK_RETRY_S: f64 = 5.0; /// Start, move or stop the agent connection when its settings change /// ([`crate::Services::agent_link`]); the first frame applies the saved settings. A connection /// that is on but failed to start is tried again every [`AGENT_LINK_RETRY_S`], so freeing its -/// port is enough, without touching a setting. The ArtCraft Launcher's agents switch -/// ([`crate::Services::launcher_agents`]) counts as the box ticked: the person turned agents on for -/// every Craft app there. +/// port is enough, without touching a setting. With the suite's `AI-MCP` flag, the ArtCraft +/// Launcher's switch ([`crate::Services::launcher_agents`]) alone decides whether agents may connect: +/// one switch for every Craft app. Without the flag, as before, a Control Port saved in the +/// preferences (`connectAgents`, set from it when they load). pub(super) fn sync_agent_link(app: &mut PhotocraftApp, ctx: &egui::Context) { let launcher = app.services.launcher_agents.as_ref().is_some_and(|on| on()); + let mcp_flag = app.agent_link.mcp_flag; let Some(link) = app.services.agent_link.as_mut() else { return }; let mut effective = app.session.prefs().integrations.clone(); - effective.connect_agents |= launcher; + if mcp_flag { + effective.connect_agents = launcher; + } let current = &effective; let now = crate::gpu_canvas::now_ms() / 1000.0; let retry_due = app.prefs_rt.agent_link_retry.is_some_and(|at| now >= at); @@ -44,7 +49,6 @@ pub(super) fn sync_agent_link(app: &mut PhotocraftApp, ctx: &egui::Context) { // do with `--control` (`PhotocraftApp::new`); the gate stays once agents have connected. app.session.automation_gate = app.session.automation_gate.or(app.services.automation_authorize); // The service reports the connection; the feature flag is the app's, set once at launch. - let mcp_flag = app.agent_link.mcp_flag; app.agent_link = update.status; app.agent_link.mcp_flag = mcp_flag; app.agent_link.launcher = launcher; @@ -55,20 +59,12 @@ pub(super) fn integration_rows(ui: &mut egui::Ui, obj: &mut Map, let t = Tokens::get(ui.ctx()); let status = f.get("__agentLink").cloned().unwrap_or(Value::Null); let launch_flags = status.get("launchFlags").and_then(Value::as_bool) == Some(true); - let launcher = status.get("launcher").and_then(Value::as_bool) == Some(true); - let mut on = obj.get("connectAgents").and_then(Value::as_bool).unwrap_or(false); - let label = humanize("connectAgents"); - if launcher && !launch_flags { - // On for the whole suite: shown ticked, and PhotoCraft's own choice is kept as it was. - ui.add_enabled_ui(false, |ui| crate::widgets::checkbox(ui, &mut true, tl!(&label))); - ui.label(RichText::new(tl!("Turned on in ArtCraft Launcher › Settings › AI agents, for every Craft app.")).color(t.text_dim)); - } else { - ui.add_enabled_ui(!launch_flags, |ui| crate::widgets::checkbox(ui, &mut on, tl!(&label))); - } - obj.insert("connectAgents".into(), json!(on)); - let on = on || launcher; + // One switch for every Craft app: ArtCraft Launcher › Settings › AI agents. There is none here. ui.label( - RichText::new(tl!("AI apps such as Claude can then open, edit and save documents here. Only programs on this computer can connect.")).color(t.text_dim), + RichText::new(tl!( + "AI apps such as Claude can open, edit and save documents in this window while ArtCraft Launcher › Settings › AI agents › Let AI agents use Craft apps is on. Only programs on this computer can connect." + )) + .color(t.text_dim), ); ui.add_space(4.0); let port = status.get("port").and_then(Value::as_u64); @@ -77,7 +73,7 @@ pub(super) fn integration_rows(ui: &mut egui::Ui, obj: &mut Map, (true, _, _) => (tl!("Managed by the launch options (--control).").to_string(), t.text_dim), (false, _, Some(e)) => (e.to_string(), t.danger), (false, Some(p), None) => (crate::i18n::fmt(tl!("Agents can connect on 127.0.0.1:{port}."), &[("port", &p.to_string())]), t.accent_text), - (false, None, None) => (tl!("Off: agents can't connect.").to_string(), t.text_faint), + (false, None, None) => (tl!("Off: turn on AI agents in ArtCraft Launcher › Settings › AI agents.").to_string(), t.text_faint), }; ui.label(RichText::new(line).color(color)); ui.add_space(8.0); @@ -113,19 +109,6 @@ pub(super) fn integration_rows(ui: &mut egui::Ui, obj: &mut Map, obj.insert("whenAppClosed".into(), json!(cur)); ui.end_row(); }); - // Adding the Craft apps to an MCP client is the ArtCraft Launcher's job (Settings › AI agents, - // one entry for every app, storytold/craft-ai-integrations#195). Without the launcher, the - // configuration to paste is here, once agents may connect (launch options manage it 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| { - if crate::widgets::secondary_button(ui, tl!("Copy Configuration"), 120.0).clicked() { - f.insert("__agentAction".into(), json!("json")); - } - ui.label(RichText::new(tl!("Or add every Craft app at once in ArtCraft Launcher › Settings › AI agents.")).color(t.text_faint)); - }); - } if let Some(result) = f.get("__agentResult").and_then(Value::as_object) { let ok = result.get("ok").and_then(Value::as_bool) == Some(true); let text = result.get("message").and_then(Value::as_str).unwrap_or(""); @@ -133,9 +116,8 @@ pub(super) fn integration_rows(ui: &mut egui::Ui, obj: &mut Map, } } -/// A button of [`integration_rows`]: choose a folder (into the dialog's working copy), or add -/// PhotoCraft to an MCP client through [`crate::Services::agent_clients`]. -pub(super) fn agent_action(app: &mut PhotocraftApp, ctx: &egui::Context, f: &mut Map, action: &str, dialog: u64) { +/// A button of [`integration_rows`]: choose a folder (into the dialog's working copy). +pub(super) fn agent_action(app: &mut PhotocraftApp, f: &mut Map, action: &str, dialog: u64) { let key = match action { "chooseRead" => Some("readRoot"), "chooseWrite" => Some("writeRoot"), @@ -155,16 +137,5 @@ pub(super) fn agent_action(app: &mut PhotocraftApp, ctx: &egui::Context, f: &mut if let Err(e) = picked { f.insert("__agentResult".into(), json!({"ok": false, "message": e})); } - return; } - let Some(add) = app.services.agent_clients.as_mut() else { return }; - let result = match add(action) { - Ok(text) if action == "json" => { - ctx.copy_text(text); - json!({"ok": true, "message": tl!("Configuration copied.")}) - } - Ok(message) => json!({"ok": true, "message": message}), - Err(e) => json!({"ok": false, "message": e}), - }; - f.insert("__agentResult".into(), result); } diff --git a/crates/ui-egui/src/prefs/prefs_ui/agents_tests.rs b/crates/ui-egui/src/prefs/prefs_ui/agents_tests.rs index 425bbac110..c5a2467663 100644 --- a/crates/ui-egui/src/prefs/prefs_ui/agents_tests.rs +++ b/crates/ui-egui/src/prefs/prefs_ui/agents_tests.rs @@ -50,12 +50,15 @@ fn ai_integrations_start_and_stop_the_agent_connection_through_the_service() { assert!(crate::control::inspect(&app, &ctx).get("agentLink").is_some()); } -/// The ArtCraft Launcher's agents switch counts as the box ticked, and turning it off there stops -/// the connection again; PhotoCraft's own saved choice is never changed by it. +/// With the AI-MCP flag the ArtCraft Launcher's switch is the one consent: it starts the +/// connection, turning it off there stops it again, and a Control Port saved before (the old, +/// flag-less way) doesn't keep it on. #[test] -fn the_launcher_switch_turns_the_agent_connection_on_without_the_box() { +fn with_the_flag_the_launcher_switch_alone_turns_the_agent_connection_on_and_off() { use std::sync::atomic::{AtomicBool, Ordering}; let (mut app, _) = app_with_store(); + app.agent_link.mcp_flag = true; + app.run("prefs.set", json!({"values": {"integrations.connectAgents": true}})).unwrap(); let ctx = egui::Context::default(); let calls: Arc>> = Arc::default(); let seen = calls.clone(); @@ -76,7 +79,6 @@ fn the_launcher_switch_turns_the_agent_connection_on_without_the_box() { tick(&mut app, &ctx); assert_eq!(*calls.lock().unwrap(), [false, true], "the launcher's switch alone starts it"); assert!(app.agent_link.launcher && app.agent_link.port == Some(4321)); - assert!(!app.session.prefs().integrations.connect_agents, "the box's own value is kept"); tick(&mut app, &ctx); assert_eq!(calls.lock().unwrap().len(), 2, "no change, no restart"); launcher.store(false, Ordering::Relaxed); @@ -85,6 +87,26 @@ fn the_launcher_switch_turns_the_agent_connection_on_without_the_box() { assert!(!app.agent_link.launcher && app.agent_link.port.is_none()); } +/// Without the AI-MCP flag nothing changes from before: the launcher's switch means nothing, and a +/// Control Port saved in the preferences keeps its connection. +#[test] +fn without_the_flag_the_launcher_switch_means_nothing() { + let (mut app, _) = app_with_store(); + let ctx = egui::Context::default(); + let calls: Arc>> = Arc::default(); + let seen = calls.clone(); + app.services.agent_link = Some(Box::new(move |p: &prefs::Integrations, _: &egui::Context| { + seen.lock().unwrap().push(p.connect_agents); + crate::AgentLink { stopped: !p.connect_agents, ..Default::default() } + })); + app.services.launcher_agents = Some(Box::new(|| true)); + tick(&mut app, &ctx); + assert_eq!(*calls.lock().unwrap(), [false], "the launcher's switch needs the flag"); + app.run("prefs.set", json!({"values": {"integrations.connectAgents": true}})).unwrap(); + tick(&mut app, &ctx); + assert_eq!(*calls.lock().unwrap(), [false, true], "a saved Control Port still counts"); +} + /// The connection's updates keep the AI-MCP flag the app was started with: losing it would put the /// page back to the settings it had before the flag after the first frame. #[test] @@ -100,18 +122,13 @@ fn connection_updates_keep_the_mcp_flag() { assert!(app.agent_link.mcp_flag, "after a change"); } -/// Copy Configuration only shows once agents may connect, and a click reaches the service. The -/// per-client buttons are the ArtCraft Launcher's (one entry for every Craft app). +/// With the flag the page has no switch of its own and nothing that sets up an MCP client: it says +/// where agents are turned on (the ArtCraft Launcher), and keeps the port, folders and closed-app +/// choice. #[test] -fn ai_integrations_offer_the_configuration_only_when_agents_may_connect() { +fn ai_integrations_point_to_the_launcher_and_have_no_switch_or_client_buttons() { 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}.")) - })); app.agent_link.mcp_flag = true; open_preferences(&mut app, "integrations"); let mut h = Harness::builder().with_size(vec2(1280.0, 800.0)).build_eframe(move |cc| { @@ -119,20 +136,12 @@ fn ai_integrations_offer_the_configuration_only_when_agents_may_connect() { app }); h.run_steps(4); - assert!(h.query_by_label("Copy Configuration").is_none(), "off: nothing to set up yet"); - 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 Prompt for an Agent"] { - assert!(h.query_by_label(label).is_none(), "{label} is the launcher's"); + for label in ["Let AI agents connect (MCP)", "Copy Configuration", "Add to Claude Desktop", "Copy Prompt for an Agent"] { + assert!(h.query_by_label(label).is_none(), "{label}"); } - h.get_by_label("Copy Configuration").click(); - h.run_steps(3); - assert_eq!(*clicked.lock().unwrap(), ["json"]); - assert!(h.query_by_label("Configuration copied.").is_some(), "the copy is confirmed"); - // Unticked again: the button goes. - h.get_by_label("Let AI agents connect (MCP)").click(); - h.run_steps(3); - assert!(h.query_by_label("Copy Configuration").is_none()); + h.get_by_label_contains("ArtCraft Launcher › Settings › AI agents › Let AI agents use Craft apps"); + h.get_by_label("Off: turn on AI agents in ArtCraft Launcher › Settings › AI agents."); + assert!(h.query_by_label("Folder agents can open from").is_some(), "the folders stay"); } /// Without the suite's AI-MCP feature flag the page shows only the settings it had before. @@ -140,7 +149,6 @@ fn ai_integrations_offer_the_configuration_only_when_agents_may_connect() { fn ai_integrations_without_the_mcp_flag_show_only_the_earlier_settings() { use egui_kittest::{Harness, kittest::Queryable}; let (mut app, _) = app_with_store(); - app.services.agent_clients = Some(Box::new(|_: &str| Ok(String::new()))); app.agent_link.mcp_flag = false; open_preferences(&mut app, "integrations"); let mut h = Harness::builder().with_size(vec2(1280.0, 800.0)).build_eframe(move |cc| { @@ -150,7 +158,6 @@ fn ai_integrations_without_the_mcp_flag_show_only_the_earlier_settings() { h.run_steps(4); assert!(h.query_by_label("Let AI agents connect (MCP)").is_none(), "the new connection switch waits for the flag"); assert!(h.query_by_label("Folder agents can open from").is_none()); - assert!(h.query_by_label("Copy Configuration").is_none()); assert!(h.query_by_label("Allow agent control").is_some(), "the earlier setting stays"); } diff --git a/crates/ui-egui/src/prefs/prefs_ui/fields.rs b/crates/ui-egui/src/prefs/prefs_ui/fields.rs index 5e2e925372..c07c304fae 100644 --- a/crates/ui-egui/src/prefs/prefs_ui/fields.rs +++ b/crates/ui-egui/src/prefs/prefs_ui/fields.rs @@ -15,11 +15,10 @@ pub fn body(app: &mut PhotocraftApp, ui: &mut egui::Ui, f: &mut Map shortcuts_body(app, ui, f), diff --git a/crates/ui-egui/src/services.rs b/crates/ui-egui/src/services.rs index 295cf02806..fc8a37bea1 100644 --- a/crates/ui-egui/src/services.rs +++ b/crates/ui-egui/src/services.rs @@ -366,13 +366,11 @@ pub struct AgentLinkStatus { pub launch_flags: bool, /// Why the connection, or one of its folders, couldn't be set up. pub error: Option, - /// How an MCP client starts PhotoCraft's MCP server (`photocraft-cli mcp --live`). - pub mcp_command: Option, /// The suite's `AI-MCP` feature flag (`craft-flags`): without it the page shows only the /// connection settings PhotoCraft had before (Allow Agent Control, Control Port). pub mcp_flag: bool, - /// The ArtCraft Launcher turned agents on for every Craft app (Settings › AI agents): that - /// counts as *Let AI agents connect*, whatever the box says. + /// The ArtCraft Launcher's switch (Settings › AI agents) lets agents use the Craft apps: with + /// the `AI-MCP` flag, the one consent for agents in this window. pub launcher: bool, } @@ -390,9 +388,6 @@ pub struct AgentLink { /// Starts, moves or stops the agent connection to match Preferences › AI Integrations. pub type AgentLinkFn = Box AgentLink>; -/// Adds PhotoCraft to an MCP client (`claude-desktop`, `claude-code`, `cursor`), returning what -/// was done, or returns the configuration to paste into any client (`json`). -pub type AgentClientFn = Box Result>; /// Open a URL in the system browser (native) — reliable cross-platform, unlike `ctx.open_url`. pub type OpenUrlFn = Box Result<(), String>>; @@ -591,8 +586,6 @@ pub struct Services { /// Preferences › AI Integrations (desktop): starts, moves or stops the agent connection when /// its settings change. `None` on the web, and when `--control` manages the connection. pub agent_link: Option, - /// Preferences › AI Integrations' buttons that add PhotoCraft to MCP clients (desktop). - pub agent_clients: Option, /// Whether the ArtCraft Launcher turned agents on for every Craft app, cheap enough to ask every /// frame (the desktop app watches the launcher's files on its own thread). `None` without the /// suite's `AI-MCP` flag, on the web, and in tests that don't set it. diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 5c2d2591b3..c4d2771fb9 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -17,24 +17,24 @@ photocraft --control 7878 --control-token-file /private/path/photocraft-control. If the file does not exist, PhotoCraft creates it with a fresh 256-bit token. On Unix the new file is mode `0600`; on Windows, protect it with an appropriate user-only ACL. An existing file is reused. If neither a token nor token file is configured, PhotoCraft generates a token for that launch and writes it to standard error. `PHOTOCRAFT_CONTROL_TOKEN` and `PHOTOCRAFT_CONTROL_TOKEN_FILE` are the environment-variable equivalents. A flag wins over its variable and an empty variable counts as unset; with `--control` (or `PHOTOCRAFT_CONTROL_PORT`), a token together with a token file, from flags or variables, is a usage error (exit status 2). Without it no token is read, so the pair is ignored. -### Without `--control`: Preferences › AI Integrations +### Without `--control`: the agents switch and Preferences › AI Integrations -An app started from the Dock, the Start menu or a file manager has no command line. Edit › Preferences › AI Integrations starts and stops the control server while the app runs: turning *Let AI agents connect* on or off, or changing its port or folders, applies at once, with no restart. +An app started from the Dock, the Start menu or a file manager has no command line. It starts and stops the control server while it runs. With the suite's `AI-MCP` flag, ArtCraft Launcher › Settings › AI agents › *Let AI agents use Craft apps* is the one switch (for every Craft app; PhotoCraft looks at it every 2 s); without the flag, as before, a saved Control Port. Turning it on or off, or changing the port or folders in Edit › Preferences › AI Integrations, applies at once, with no restart. | Preference | What it does | |---|---| -| `integrations.connectAgents` (default off) | Serve agents on loopback without `--control`, and publish the connection (below) | +| `integrations.connectAgents` (default off, not in the dialog) | Without the `AI-MCP` flag: serve agents on loopback without `--control`, and publish the connection (below). Set from a saved Control Port; with the flag only the launcher's switch counts | | `integrations.controlPort` (default 0) | The port for that; 0 = any free port (clients read it from the connection file) | | `integrations.readRoot` (default empty) | The agents' read folder; with `--control`, stands in for `--automation-read-root` | | `integrations.writeRoot` (default empty) | The agents' write folder; with `--control`, stands in for `--automation-write-root` | -| `integrations.whenAppClosed` (default `launch`) | What `photocraft-cli mcp --live` does while the app is closed: `launch`, `headless` or `error` | +| `integrations.whenAppClosed` (default `launch`) | What `photocraft-cli mcp` does while agents may use the app but it is closed: `launch`, `headless` or `error` | | `integrations.allowAgentControl` (default on, not in the dialog) | Off refuses `--control` too | -A file saved before *Let AI agents connect* existed, whose `controlPort` (1 to 65535) started the server at launch, loads with `connectAgents` on. Started with `--control`, the app leaves the connection to the launch flags and the dialog says so; only `--control` (or `PHOTOCRAFT_CONTROL_PORT`) opens a port at launch. +A file whose `controlPort` (1 to 65535) started the server at launch, as on `main` before the agents switch, loads with `connectAgents` on, so that keeps working without the flag. Started with `--control`, the app leaves the connection to the launch flags and the dialog says so; only `--control` (or `PHOTOCRAFT_CONTROL_PORT`) opens a port at launch. With `--control`, each launch option, or its environment variable, wins over its preference; the two folders are decided separately (any `--automation-read-root` replaces the read folder). The same folder for both reading and writing shares one capability, as it does when given by flags, so an implicit save works there too. A folder named by a flag that can't be opened stops the launch (exit status 2), as before. A folder named only in the preferences that can't be opened, or isn't an absolute path, is left out, so that direction of file access fails closed; the app still starts, prints the reason on standard error and shows it in a notice. Automation can't change the two folders (`prefs.set` refuses `integrations.readRoot`, `integrations.writeRoot` and the whole `integrations` section): an agent must not widen its own file access. -While *Let AI agents connect* is on, the app keeps its token in its settings folder, in `agent-control.token`, exactly as `--control-token-file /agent-control.token` would (created mode `0600` with a fresh token when missing, reused otherwise, also when the port changes; delete it to get a new token). If that file can't be written or read (a read-only or full settings folder), agents can't connect and the dialog shows why. Otherwise the app publishes the connection beside it, in `agent-connection.json`, and removes it when the connection stops: +While agents may connect, the app keeps its token in its settings folder, in `agent-control.token`, exactly as `--control-token-file /agent-control.token` would (created mode `0600` with a fresh token when missing, reused otherwise, also when the port changes; delete it to get a new token). If that file can't be written or read (a read-only or full settings folder), agents can't connect and the dialog shows why. Otherwise the app publishes the connection beside it, in `agent-connection.json`, and removes it when the connection stops: ```json { @@ -418,9 +418,9 @@ magenta alignment lines. `ui.pointer` drives the same code, so agents get identi - **Headless** (`photocraft-cli mcp`): an in-process `photocraft_engine::Session`. There is no window. CPU composition is the default; `--gpu` or `PHOTOCRAFT_GPU=1` enables optional GPU rendering with automatic CPU fallback. - **Bridge** (`photocraft-cli mcp --bridge 127.0.0.1:7878 --control-token-file `): every tool is forwarded to a running `photocraft --control 7878 --control-token-file ` over this protocol, so agents see and drive the live app. Explicit `--gpu` / `--no-gpu` flags are rejected with a usage error because the desktop controls rendering; `PHOTOCRAFT_GPU` is ignored in bridge mode. `--bridge 7878` is short for `--bridge 127.0.0.1:7878`. With no `--bridge`, `PHOTOCRAFT_CONTROL_PORT` selects the bridge port (`127.0.0.1:`), and the CLI says so on standard error; with neither (or the variable empty), the MCP runs headless. A value that is not a port is a usage error naming the variable. `--automation-read-root` or `--automation-write-root` with the variable set is a usage error, since the bridge would drop the roots. -- **Live** (`photocraft-cli mcp --live`): the bridge, with the address and token read before every tool call from `agent-connection.json` in the app's settings folder. The app publishes that file while Edit › Preferences › AI Integrations › *Let AI agents connect* is on, or the ArtCraft Launcher turned agents on for every Craft app ([MCP conventions](mcp.md#connecting-the-desktop-app-no-terminal)), not with `--control`, and removes it when the connection stops; a file left by a crash fails the connection probe and counts as no app. See [MCP conventions](mcp.md#connecting-the-desktop-app-no-terminal). +- **The open window** (plain `photocraft-cli mcp`): the bridge, with the address and token read before every tool call from `agent-connection.json` in the app's settings folder, while the person lets agents use the app; otherwise headless, as above (`--headless` forces that). The app publishes that file while agents may connect (the ArtCraft Launcher's switch; without the `AI-MCP` flag a saved Control Port), not with `--control`, and removes it when the connection stops; a file left by a crash fails the connection probe and counts as no app. See [MCP conventions](mcp.md#connecting-the-desktop-app-no-terminal). -`ui.inspect` reports the connection as `agentLink`: `port` while agents can connect, `launchFlags` when `--control` manages it, `error`, and `mcpCommand` (how MCP clients start the CLI). +`ui.inspect` reports the connection as `agentLink`: `port` while agents can connect, `launchFlags` when `--control` manages it, `error`, `mcpFlag` and `launcher` (the ArtCraft Launcher's switch is on). The bridge keeps one authenticated TCP connection open, and drops and reconnects before a call once the connection has been idle long enough that the app (which closes idle connections after 30s) may have dropped it. A transport failure while sending a request or waiting for its reply, including a reply timeout, drops the connection and reports that the operation may have completed (a call abandoned before its reply, such as a cancelled MCP wait, also drops it, so the next call never queues behind it); inspect the document before retrying an edit. Edits are never automatically resent (#1007); a connection that could not be established is reported as "the request was not sent" instead. The MCP server opts its pure-read tools (`ui_inspect`, `doc_inspect`, `command_list`, `jobs_list`, `session_list`, `ui_screenshot`) into one automatic retry on a fresh connection, since a read applies nothing; clients driving `BridgeClient` directly opt in per call with `call_read`. The next separate call reconnects and authenticates, and reply lines whose `id` does not match the request are skipped. The client's call timeout is 55s, strictly below the server's 60s reply deadline, so the bridge's error is the one callers see. A waited MCP `command_run` (or `command_batch` step) of an engine command is not bound by it (#8130): the bridge sends `engine.execute` once with `"wait": false` and, when the app starts a background job, polls `jobs.list` until the job ends and returns its result, forwarding progress and cancelling the job (`jobs.cancel`) when the request is cancelled, at once, even while a poll still waits on the app. Limits: a command that does not run as a job, a UI command (not an engine command; the app waits on it) and a lost reply to the start itself still fail at the timeout, the last with "operation may have completed" (look for the job in `jobs_list` before retrying); a failed poll of an uncancelled wait reports the job id and leaves the job running; and an unresponsive app still times out. Clients driving `BridgeClient` directly pass `"wait": false` and poll `jobs.list` themselves. It only accepts the literal loopback addresses `127.0.0.1:` and `[::1]:`, because the app only listens on loopback; `localhost:` means `127.0.0.1:` and is never looked up, since a lookup may return `[::1]` first and reach another process listening there. Every connection authenticates by challenge (see above), so the token is never sent, and a listener that cannot prove it holds the token is reported as such ("the control token was not sent"); an app too old for challenge authentication is refused the same way, so update the app with the CLI. Supply its bearer token with `--control-token-file`, `--control-token`, `PHOTOCRAFT_CONTROL_TOKEN_FILE`, or `PHOTOCRAFT_CONTROL_TOKEN`: @@ -488,9 +488,10 @@ One explicit write-root flag overrides `PHOTOCRAFT_AUTOMATION_WRITE_ROOT`. These variables are not supported by headless `photocraft-cli mcp` or `serve`; supply flags explicitly. In MCP bridge mode, configure roots on the desktop process. Supplying root flags to `photocraft-cli mcp --bridge` is a usage error; a bridge client cannot grant filesystem access. -With *Let AI agents connect*, the folders chosen in Preferences › AI Integrations (`readRoot` / -`writeRoot`) are the agents' roots; `mcp --live` uses them for a headless session only when the -app's *When PhotoCraft is closed* choice (or `--when-closed headless`) asks for one. +While agents may use the app, the folders chosen in Preferences › AI Integrations (`readRoot` / +`writeRoot`) are the agents' roots; `mcp` uses them for a headless session only when the app's +*When PhotoCraft is closed* choice (or `--when-closed headless`) asks for one. Without the +person's consent, `mcp` works headless with only the roots given to it, as before. Request paths must be non-empty, forward-slash relative paths beneath the applicable root, or absolute paths beneath a corresponding granted root. An absolute path is compared with the diff --git a/docs/development.md b/docs/development.md index d37f01acbe..af247f2845 100644 --- a/docs/development.md +++ b/docs/development.md @@ -324,7 +324,7 @@ At startup the desktop lists recovery metadata, then decodes one document at a t - **Headless:** `photocraft-cli mcp --automation-read-root --automation-read-root --automation-write-root `. It drives an in-process engine session with ordered read directories and one write directory. - **Live app:** start `photocraft --control 7878 --control-token-file --automation-read-root --automation-read-root --automation-write-root `, then run `photocraft-cli mcp --bridge 127.0.0.1:7878 --control-token-file `. The desktop process owns the roots; root flags on the bridging CLI are a usage error. See `docs/control-protocol.md#mcp-bridge`. -- **Live app, no flags:** turn on Edit › Preferences › AI Integrations › Let AI agents connect, then point the MCP client at `photocraft-cli mcp --live` (the panel's buttons, or `photocraft-cli mcp install --client `, do it). The app publishes its port and token file in `agent-connection.json` in the settings folder; `--live` reads it on every call. See [MCP conventions](mcp.md#connecting-the-desktop-app-no-terminal). Test it against a scratch settings folder with `PHOTOCRAFT_CONFIG_DIR`, which both the app and the CLI honour. +- **Live app, no flags:** with the `AI-MCP` flag, turn on ArtCraft Launcher › Settings › AI agents and add the MCP client there; plain `photocraft-cli mcp` then works in the open window. The app publishes its port and token file in `agent-connection.json` in the settings folder; `mcp` reads it on every call. Without a launcher, a scratch `CRAFT_MCP_DIR` with an `apps.json` naming `photocraft` (the format in storytold/craft-ai-integrations, crate `craft-ai-agents`) turns the switch on for a test. See [MCP conventions](mcp.md#connecting-the-desktop-app-no-terminal). Test it against a scratch settings folder with `PHOTOCRAFT_CONFIG_DIR`, which both the app and the CLI honour. For headless MCP clients, pass absolute paths to deliberately chosen trusted workspace directories in the launch arguments. Desktop `PHOTOCRAFT_AUTOMATION_READ_ROOT` and `PHOTOCRAFT_AUTOMATION_WRITE_ROOT` environment variables do **not** grant headless CLI access. Omitting a root flag deliberately denies that direction of access. diff --git a/docs/mcp.md b/docs/mcp.md index 2596e73d5f..debaf0d444 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2,68 +2,58 @@ ## Connecting the desktop app (no terminal) -These settings are behind the Craft suite's `AI-MCP` feature flag (`craft-flags`). Flags are set -only in the per-user `ArtCraft/flags.toml` (`AI-MCP = true` under `[flags]`; on Windows in +**One switch, in the ArtCraft Launcher.** Settings › AI agents › **Let AI agents use Craft apps** +is the person's consent for every Craft app, PhotoCraft included; PhotoCraft has no switch of its +own. **Add** next to an MCP client (Claude Desktop, Claude Code, Cursor, LM Studio) puts one entry +in it, `ArtCraft`, for every installed Craft app (the `craft-ai-mcp` gateway, which starts +`photocraft-cli mcp`); **Copy** gives the configuration for any other client. Then restart the +client. Adding to MCP clients is the launcher's job alone: PhotoCraft writes no client +configuration. The design is in storytold/craft-ai-integrations#195. + +This is behind the Craft suite's `AI-MCP` feature flag (`craft-flags`). Flags are set only in the +per-user `ArtCraft/flags.toml` (`AI-MCP = true` under `[flags]`; on Windows in `%LOCALAPPDATA%\ArtCraft`), which every Craft app and the launcher read, or for one run with -`CRAFT_FLAGS=AI-MCP`; no app or launcher setting switches them. Without it the page shows only Allow -Agent Control and Control Port, as before; a Control Port already set keeps its connection. +`CRAFT_FLAGS=AI-MCP`; no app or launcher setting switches them. Without the flag, everything is as +it was: Preferences › AI Integrations shows Allow Agent Control and Control Port, a Control Port +already set keeps its connection, and the launcher's switch means nothing to PhotoCraft. -**With the ArtCraft Launcher** there is nothing to do in PhotoCraft: turning on Settings › AI -agents › **Let AI agents use Craft apps** there is the person's consent for every Craft app. The -launcher then keeps its app list `ArtCraft/mcp/apps.json` (in the per-user local configuration -folder; `CRAFT_MCP_DIR` moves it), and while that list names `photocraft` and `AI-MCP` is on, -PhotoCraft accepts agents as if **Let AI agents connect** were ticked: the page shows the box ticked -and says the launcher turned it on, and PhotoCraft's own choice is kept for when the launcher's -switch goes off. The app looks at the launcher's files every 2 s, so switching there applies -without a restart; `photocraft-cli mcp --live` looks before every call. Allow Agent Control off -still refuses agents. Storytold/craft-ai-integrations#195 has the whole design. +While the launcher's switch is on, its app list `ArtCraft/mcp/apps.json` (in the per-user local +configuration folder; `CRAFT_MCP_DIR` moves it) names `photocraft`, read through +`craft-ai-agents`, the same crate the launcher writes it with and the gateway reads it with. +PhotoCraft then serves agents on loopback (any free port by default, or the Control Port) with a +token it keeps in its settings folder, and publishes both in `agent-connection.json` there. The +app looks at the launcher's files every 2 s, so switching there applies without a restart. Allow +Agent Control off still refuses agents. Started with `--control`, the app ignores all this and the +launch flags manage the connection, as before. -1. In PhotoCraft, open **Edit › Preferences › AI Integrations** and turn on **Let AI agents - connect (MCP)**. Optionally choose the folders agents can open from and save to, and what - 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. Add PhotoCraft to the MCP client: with the ArtCraft Launcher, Settings › AI agents › **Add** - adds one entry for every Craft app (the `craft-ai-mcp` gateway, which starts - `photocraft-cli mcp --live`). Without it, click **Copy Configuration** and paste it into the - client's MCP settings, or run `photocraft-cli mcp install --client ` (below). Then - restart that client. The button shows once the box is ticked. +**Edit › Preferences › AI Integrations** says whether agents can connect (and on which port), and +keeps what is PhotoCraft's own: the port, the folders agents can open from and save to, and what +happens when an agent needs PhotoCraft while it is closed (open it, work without a window, or ask +the user to open it). -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 -`agent-connection.json` there; `--live` reads that file before every tool call, so the client -configuration holds no port or token and keeps working when PhotoCraft restarts. The token stays in -the settings folder across restarts (`agent-control.token`; delete it to get a new one). Started with `--control`, the app ignores these -settings and the launch flags manage the connection, as before. +### `photocraft-cli mcp` -From a terminal, `photocraft-cli mcp install --client ` -does what the buttons do. `--when-closed ` on `mcp --live` overrides the -app's choice. In a headless session started that way, the folders chosen in the app (or -`--automation-read-root` / `--automation-write-root` given to `mcp --live`) are the roots, and 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. +Plain `photocraft-cli mcp` works in the open PhotoCraft window when the person lets agents use it, +and otherwise without a window, as it always did. It reads `agent-connection.json` before every +tool call, so the client configuration holds no port or token and keeps working when PhotoCraft +restarts or moves to another port. -Where each client is configured: +- **Agents allowed, PhotoCraft open:** tools work in the window. +- **Agents allowed, PhotoCraft closed:** When PhotoCraft Is Closed decides (`--when-closed + ` overrides it): start the app and wait for it, serve a headless + session with the folders chosen in the app (or the `--automation-read-root` / + `--automation-write-root` given to `mcp`), or say to open it. The app is started only on a tool + call, never when the MCP client starts. +- **Agents not allowed:** a headless session with only the roots given to `mcp`, exactly as + before; the app is never started and its folders aren't used. +- **`--headless`:** always headless, whatever the switch says. +- **`--bridge` (or `PHOTOCRAFT_CONTROL_PORT`):** a `photocraft --control` app, as before. -| 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 +A session that went headless stays headless until the MCP client restarts it, so documents don't +move under the agent. In the Flatpak 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 +When `mcp` 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 diff --git a/docs/scorecard.md b/docs/scorecard.md index 2e83f57a58..417b6e3651 100644 --- a/docs/scorecard.md +++ b/docs/scorecard.md @@ -274,7 +274,7 @@ Menu wiring (`docs/parity-checklist.md`): 664 of 664 menu items live (100.0%). T | AUTO-219-8 | xtask check that every panel button routes through a command id | partial | [#219](https://github.com/storytold/photocraft/issues/219) | cargo xtask panel-commands (run by xtask ci and CI) fails on a shell click handler that changes the document or session directly; 1 allowlisted function left (panels/color.rs color_field assigns the foreground/background colour instead of tools.setColors) | | AUTO-219-9 | Headless commands for in-canvas type editing, Liquify/Puppet strokes, transform handles | done | [#219](https://github.com/storytold/photocraft/issues/219) | type.hitTest, type.caret, type.navigate; filter.liquify strokes, edit.puppetWarp pins, type.edit, edit.transform | | AUTO-219-10 | Agent acceptance suite grown to 30-50 workflows | partial | [#219](https://github.com/storytold/photocraft/issues/219) | automation/tests/it/agent_tasks.rs runs 10 workflows over MCP | -| AUTO-MCP-LIVE | Connect an MCP client to the running app without a terminal (no flags, ports or tokens to copy) | done | | 2026-11-12 (#5525, #11363): Edit › Preferences › AI Integrations › Let AI agents connect starts and stops the loopback control server while the app runs (no restart) and publishes agent-connection.json; photocraft-cli mcp --live finds the app on every call (launch / headless / error while it is closed); the ArtCraft Launcher's agents switch counts as consent (craft-ai-integrations#195) and its Add buttons register every Craft app; Copy Configuration and mcp install --client without the launcher. automation/tests/mcp_live.rs, apps/photocraft/src/agent_link.rs tests | +| AUTO-MCP-LIVE | Connect an MCP client to the running app without a terminal (no flags, ports or tokens to copy) | done | | 2026-11-12 (#5525, #11363, craft-ai-integrations#195): the ArtCraft Launcher's agents switch (the one consent; read through craft-ai-agents) starts and stops the loopback control server while the app runs (no restart) and publishes agent-connection.json; plain photocraft-cli mcp works in the open app on every call while agents are allowed (launch / headless / error while it is closed) and headless otherwise (--headless forces it); the launcher's Add buttons register every Craft app, PhotoCraft writes no client configuration. automation/tests/mcp_live.rs, apps/photocraft/src/agent_link.rs tests | ## Reliability diff --git a/packaging/linux/AppRun b/packaging/linux/AppRun index b869b9499e..3414c5acc7 100755 --- a/packaging/linux/AppRun +++ b/packaging/linux/AppRun @@ -113,7 +113,7 @@ integrate() { } # `PhotoCraft.AppImage --cli ` runs the bundled photocraft-cli: MCP clients start -# `--cli mcp --live` this way (Preferences › AI Integrations), since the mount point that holds +# `--cli mcp` this way (the ArtCraft Launcher's app list), since the mount point that holds # the CLI changes with every run. if [ "${1:-}" = "--cli" ]; then shift diff --git a/packaging/linux/apprun-test.sh b/packaging/linux/apprun-test.sh index 9c52cc0127..473872ebfe 100755 --- a/packaging/linux/apprun-test.sh +++ b/packaging/linux/apprun-test.sh @@ -154,10 +154,10 @@ rm -f "$am_desktop" "$APPDIR/AppRun" >/dev/null || fail "launch after AM removal exited non-zero" [[ -f "$DESKTOP" ]] || fail "no desktop entry after the AM launcher was removed" -# 12. `--cli` runs the bundled CLI (MCP clients start `--cli mcp --live`), without integrating. +# 12. `--cli` runs the bundled CLI (MCP clients start `--cli mcp`), without integrating. rm -rf "$XDG_DATA_HOME" -out="$("$APPDIR/AppRun" --cli mcp --live)" || fail "--cli exited non-zero" -[ "$out" = "cli stub: mcp --live" ] || fail "--cli output: $out" +out="$("$APPDIR/AppRun" --cli mcp --headless)" || fail "--cli exited non-zero" +[ "$out" = "cli stub: mcp --headless" ] || fail "--cli output: $out" [ ! -e "$XDG_DATA_HOME" ] || fail "--cli integrated the desktop entry" echo "AppRun desktop integration ok" diff --git a/packaging/macos/package.sh b/packaging/macos/package.sh index ca64f30e82..8cb4d6db70 100755 --- a/packaging/macos/package.sh +++ b/packaging/macos/package.sh @@ -121,7 +121,7 @@ mkdir -p "$APP/Contents/MacOS" "$APP/Contents/Resources" # Executable and icon carry the display name (CFBundleExecutable / CFBundleIconFile). cp "$WORK/bin/photocraft" "$APP/Contents/MacOS/PhotoCraft" # The CLI too, beside the app: Preferences › AI Integrations points MCP clients at it -# (`photocraft-cli mcp --live`), and it starts the app when an agent needs it. +# (`photocraft-cli mcp`), and it starts the app when an agent needs it. cp "$WORK/bin/photocraft-cli" "$APP/Contents/MacOS/photocraft-cli" cp "$ROOT/assets/app-icon/photocraft.icns" "$APP/Contents/Resources/PhotoCraft.icns" # Notices for the bundled font fallback, included before the bundle is signed. diff --git a/scorecard/automation.toml b/scorecard/automation.toml index 2fd1660dce..641ab762d7 100644 --- a/scorecard/automation.toml +++ b/scorecard/automation.toml @@ -85,4 +85,4 @@ note = "automation/tests/it/agent_tasks.rs runs 10 workflows over MCP" id = "AUTO-MCP-LIVE" target = "Connect an MCP client to the running app without a terminal (no flags, ports or tokens to copy)" status = "done" -note = "2026-11-12 (#5525, #11363): Edit › Preferences › AI Integrations › Let AI agents connect starts and stops the loopback control server while the app runs (no restart) and publishes agent-connection.json; photocraft-cli mcp --live finds the app on every call (launch / headless / error while it is closed); the ArtCraft Launcher's agents switch counts as consent (craft-ai-integrations#195) and its Add buttons register every Craft app; Copy Configuration and mcp install --client without the launcher. automation/tests/mcp_live.rs, apps/photocraft/src/agent_link.rs tests" +note = "2026-11-12 (#5525, #11363, craft-ai-integrations#195): the ArtCraft Launcher's agents switch (the one consent; read through craft-ai-agents) starts and stops the loopback control server while the app runs (no restart) and publishes agent-connection.json; plain photocraft-cli mcp works in the open app on every call while agents are allowed (launch / headless / error while it is closed) and headless otherwise (--headless forces it); the launcher's Add buttons register every Craft app, PhotoCraft writes no client configuration. automation/tests/mcp_live.rs, apps/photocraft/src/agent_link.rs tests" From fcbc0a69f88509596c70cb6c2a3156376fde862c Mon Sep 17 00:00:00 2001 From: David Mann Date: Thu, 12 Nov 2026 23:55:27 +0100 Subject: [PATCH 22/28] docs: tests and agents run `mcp --headless` Plain `photocraft-cli mcp` now works in the open window while the ArtCraft Launcher's agents switch is on, and may start PhotoCraft, also on a developer's machine. AGENTS.md says scripts, tests and agent sessions pass `--headless` (and tests give the CLI their own settings, launcher and flags folders); the headless examples in docs/development.md, docs/mcp.md, docs/control-protocol.md, the book and the README use it. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 2 ++ README.md | 4 +++- book/src/automation/mcp.md | 5 +++-- docs/control-protocol.md | 2 +- docs/development.md | 2 +- docs/mcp.md | 6 ++++-- 6 files changed, 14 insertions(+), 7 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index fffe9b1daa..4c0acf5b54 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -161,6 +161,8 @@ cargo xtask test-corpus # if you touched psd, io, codecs, compose, gpu, text While iterating, run less and keep the full commands above as the final gate: `cargo test -p --lib --tests` skips the examples and doctests plain `cargo test` builds every time (ui-egui has 11 examples), and `cargo test -p --test ` runs one integration-test file. `cargo nextest run` runs tests in parallel across binaries; see `docs/development.md` › Faster test loops. +**MCP in tests and agent sessions: `photocraft-cli mcp --headless`.** Plain `photocraft-cli mcp` works in the open PhotoCraft window while the ArtCraft Launcher's agents switch is on, and then may start PhotoCraft on the developer's machine when it is closed. Scripts, tests and agents that want a session without a window pass `--headless` (or use `photocraft-cli serve`); a test that runs the CLI also gives it its own settings, launcher and flags folders (`PHOTOCRAFT_CONFIG_DIR`, `CRAFT_MCP_DIR`, `CRAFT_FLAGS_FILE`, as `crate::command()` in `apps/photocraft-cli/tests/it/main.rs` does). To drive the running app on purpose, use `--control` (`docs/development.md`). + **Test corpora.** Real-file corpora live in `corpus/` (gitignored, never committed), fetched at pinned commits and sha256-verified by `cargo xtask corpus --all`: our Photoshop- and GIMP-authored oracles from https://github.com/storytold/photocraft-corpus plus psd-tools, ag-psd and PngSuite from their upstreams. Pins: `xtask/src/corpus_pins.rs`. The corpus tests are opt-in (cargo feature `corpus`): plain `cargo test` skips them, and with the feature on a missing corpus fails ("run `cargo xtask corpus --all`"). `cargo xtask test-corpus` fetches and runs them all. CI always runs them (the `corpus` job, cached by pin). Never commit corpus files; new oracles go to photocraft-corpus (its `AGENTS.md`), then a pin bump here. Details: `docs/development.md` › Test corpora. Commands must **never panic** on bad input (Rule 9): every `run` closure and the code it calls returns `Err`, not a panic, for any params or document state. New commands come with a graceful-failure test (empty/out-of-range/wrong-type params → `Err`, not a crash). diff --git a/README.md b/README.md index 11880dda82..4e2b8ac8fb 100644 --- a/README.md +++ b/README.md @@ -242,8 +242,10 @@ photocraft-cli batch --actions grade.json --in ./raw --out ./graded # Every subcommand explains itself photocraft-cli batch --help -# Let an agent drive it over MCP (headless, or bridged to the running app) +# Let an agent drive it over MCP: the open window while agents are allowed, otherwise headless photocraft-cli mcp +# Always without a window (scripts, tests) +photocraft-cli mcp --headless ``` To let Claude or another AI app drive the open PhotoCraft window without a terminal, turn on **ArtCraft Launcher › Settings › AI agents** and click **Add** next to the AI app (one entry for every Craft app). See [`docs/mcp.md`](docs/mcp.md). These settings are behind the Craft suite's `AI-MCP` feature flag: set `AI-MCP = true` in `ArtCraft/flags.toml`, or start PhotoCraft with `CRAFT_FLAGS=AI-MCP`. diff --git a/book/src/automation/mcp.md b/book/src/automation/mcp.md index 91a75fb4e2..36d5e6be5e 100644 --- a/book/src/automation/mcp.md +++ b/book/src/automation/mcp.md @@ -11,10 +11,11 @@ The simplest setup needs no terminal: turn on ArtCraft Launcher › Settings › For a source checkout, first [install the CLI on PATH and register the server](../../../docs/mcp.md#install-and-register). The installed binary survives `cargo clean`; a symlink into `target/release` does not. -Start the headless server with: +Start the headless server with (without `--headless`, `mcp` works in the open PhotoCraft window +while the ArtCraft Launcher's agents switch is on): ```sh -photocraft-cli mcp --automation-read-root /work/project --automation-write-root /work/project +photocraft-cli mcp --headless --automation-read-root /work/project --automation-write-root /work/project ``` Bridge to a running desktop application with the same private token file used by the app: diff --git a/docs/control-protocol.md b/docs/control-protocol.md index c4d2771fb9..9f30cf8927 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -415,7 +415,7 @@ magenta alignment lines. `ui.pointer` drives the same code, so agents get identi `photocraft-automation` provides an MCP server built on the official Rust SDK (`rmcp`). It runs in one of two modes: -- **Headless** (`photocraft-cli mcp`): an in-process `photocraft_engine::Session`. There is no window. CPU composition is the default; `--gpu` or `PHOTOCRAFT_GPU=1` enables optional GPU rendering with automatic CPU fallback. +- **Headless** (`photocraft-cli mcp --headless`, or plain `mcp` while agents may not use the app): an in-process `photocraft_engine::Session`. There is no window. CPU composition is the default; `--gpu` or `PHOTOCRAFT_GPU=1` enables optional GPU rendering with automatic CPU fallback. - **Bridge** (`photocraft-cli mcp --bridge 127.0.0.1:7878 --control-token-file `): every tool is forwarded to a running `photocraft --control 7878 --control-token-file ` over this protocol, so agents see and drive the live app. Explicit `--gpu` / `--no-gpu` flags are rejected with a usage error because the desktop controls rendering; `PHOTOCRAFT_GPU` is ignored in bridge mode. `--bridge 7878` is short for `--bridge 127.0.0.1:7878`. With no `--bridge`, `PHOTOCRAFT_CONTROL_PORT` selects the bridge port (`127.0.0.1:`), and the CLI says so on standard error; with neither (or the variable empty), the MCP runs headless. A value that is not a port is a usage error naming the variable. `--automation-read-root` or `--automation-write-root` with the variable set is a usage error, since the bridge would drop the roots. - **The open window** (plain `photocraft-cli mcp`): the bridge, with the address and token read before every tool call from `agent-connection.json` in the app's settings folder, while the person lets agents use the app; otherwise headless, as above (`--headless` forces that). The app publishes that file while agents may connect (the ArtCraft Launcher's switch; without the `AI-MCP` flag a saved Control Port), not with `--control`, and removes it when the connection stops; a file left by a crash fails the connection probe and counts as no app. See [MCP conventions](mcp.md#connecting-the-desktop-app-no-terminal). diff --git a/docs/development.md b/docs/development.md index af247f2845..9988617aa4 100644 --- a/docs/development.md +++ b/docs/development.md @@ -322,7 +322,7 @@ At startup the desktop lists recovery metadata, then decodes one document at a t `photocraft-cli mcp` serves MCP on stdio using `crates/automation`, which is built on `rmcp`: -- **Headless:** `photocraft-cli mcp --automation-read-root --automation-read-root --automation-write-root `. It drives an in-process engine session with ordered read directories and one write directory. +- **Headless:** `photocraft-cli mcp --headless --automation-read-root --automation-read-root --automation-write-root `. Use `--headless` in scripts, tests and agent sessions: without it `mcp` works in the open window while the ArtCraft Launcher's agents switch is on, and may start PhotoCraft (When PhotoCraft Is Closed defaults to starting it). It drives an in-process engine session with ordered read directories and one write directory. - **Live app:** start `photocraft --control 7878 --control-token-file --automation-read-root --automation-read-root --automation-write-root `, then run `photocraft-cli mcp --bridge 127.0.0.1:7878 --control-token-file `. The desktop process owns the roots; root flags on the bridging CLI are a usage error. See `docs/control-protocol.md#mcp-bridge`. - **Live app, no flags:** with the `AI-MCP` flag, turn on ArtCraft Launcher › Settings › AI agents and add the MCP client there; plain `photocraft-cli mcp` then works in the open window. The app publishes its port and token file in `agent-connection.json` in the settings folder; `mcp` reads it on every call. Without a launcher, a scratch `CRAFT_MCP_DIR` with an `apps.json` naming `photocraft` (the format in storytold/craft-ai-integrations, crate `craft-ai-agents`) turns the switch on for a test. See [MCP conventions](mcp.md#connecting-the-desktop-app-no-terminal). Test it against a scratch settings folder with `PHOTOCRAFT_CONFIG_DIR`, which both the app and the CLI honour. diff --git a/docs/mcp.md b/docs/mcp.md index debaf0d444..6110c1f586 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -106,10 +106,12 @@ not put the CLI on `PATH`. ## Start a session -PhotoCraft follows the same conventions as FilmCraft #28. Start a headless session: +PhotoCraft follows the same conventions as FilmCraft #28. Start a headless session (`--headless`: +without it, `mcp` works in the open PhotoCraft window while the ArtCraft Launcher's agents switch is +on, and may start the app; scripts, tests and agents pass it): ```sh -photocraft-cli mcp \ +photocraft-cli mcp --headless \ --automation-read-root /work/project \ --automation-read-root /library/reference \ --automation-write-root /work/project From 6c53064e9bf906c76a59a1edbc3c943466c1e20f Mon Sep 17 00:00:00 2001 From: David Mann Date: Fri, 13 Nov 2026 02:04:48 +0100 Subject: [PATCH 23/28] Drop the unused Command import in the malloc tuning test Co-Authored-By: Claude Opus 5.5 --- apps/photocraft-cli/tests/it/malloc_tuning.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/photocraft-cli/tests/it/malloc_tuning.rs b/apps/photocraft-cli/tests/it/malloc_tuning.rs index e19487c514..068b4d2205 100644 --- a/apps/photocraft-cli/tests/it/malloc_tuning.rs +++ b/apps/photocraft-cli/tests/it/malloc_tuning.rs @@ -2,7 +2,7 @@ //! and a value the user set. use std::io::{BufRead, BufReader, Write}; -use std::process::{Command, Stdio}; +use std::process::Stdio; use photocraft_engine::malloc_tuning::{TRIM_THRESHOLD, TRIM_THRESHOLD_VAR}; From dbd2cd16282219e8841c22fa90b6a224d541fb36 Mon Sep 17 00:00:00 2001 From: David Mann Date: Fri, 13 Nov 2026 12:36:22 +0100 Subject: [PATCH 24/28] fix(mcp): plain mcp stays headless without the AI-MCP flag; integrations read leniently - Without the AI-MCP flag plain `photocraft-cli mcp` is headless as before: a Control Port saved before the agents switch no longer makes it look for the app, start it or apply When PhotoCraft Is Closed. Test in mcp_without_consent_works_headless (fails without the gate). - `prefs::read_integrations_section` (migrate + lenient read) is shared by the app's launch read and `photocraft-cli mcp`: one bad value resets only itself, so a saved "error" closed-app choice no longer falls back to Launch in the CLI. Replaces the app's hand-written per-field reader. Test in integrations_come_from_the_saved_preferences_or_default (fails without it). - docs/development.md: the headless client examples pass --headless. Co-Authored-By: Claude Opus 5.5 --- apps/photocraft-cli/src/automation.rs | 7 +++-- apps/photocraft-cli/tests/it/cli.rs | 6 ++++ apps/photocraft/src/main.rs | 44 ++++----------------------- crates/automation/src/agent_link.rs | 9 +++--- crates/engine/src/prefs.rs | 9 ++++++ docs/development.md | 4 +-- 6 files changed, 31 insertions(+), 48 deletions(-) diff --git a/apps/photocraft-cli/src/automation.rs b/apps/photocraft-cli/src/automation.rs index 65c5f80be7..39dd9ce374 100644 --- a/apps/photocraft-cli/src/automation.rs +++ b/apps/photocraft-cli/src/automation.rs @@ -68,11 +68,12 @@ pub(crate) fn serve(a: &ServeArgs, err: &mut dyn Write) -> Result { } } -/// `mcp`: the open window when agents may use it, otherwise headless (`mcp_live`); `--headless` -/// always headless; `--bridge` (or PHOTOCRAFT_CONTROL_PORT) a `photocraft --control` app. +/// `mcp`: with the suite's `AI-MCP` flag, the open window when agents may use it, otherwise +/// headless (`mcp_live`); without the flag headless, as before it; `--headless` always headless; +/// `--bridge` (or PHOTOCRAFT_CONTROL_PORT) a `photocraft --control` app. pub(crate) fn mcp(a: &McpArgs, err: &mut dyn Write) -> Result { let server = match &a.bridge { - None if !a.headless => PhotocraftMcp::live(live_config(a)?), + None if !a.headless && photocraft_automation::agent_link::mcp_flag() => PhotocraftMcp::live(live_config(a)?), Some(addr) => { if a.bridge_from_env { // Name the mode switch, as `serve` does: the way back to headless is to unset it. diff --git a/apps/photocraft-cli/tests/it/cli.rs b/apps/photocraft-cli/tests/it/cli.rs index 7585534a53..b14e2e61a3 100644 --- a/apps/photocraft-cli/tests/it/cli.rs +++ b/apps/photocraft-cli/tests/it/cli.rs @@ -2112,6 +2112,12 @@ fn mcp_without_consent_works_headless() { env.push(("PHOTOCRAFT_CONTROL_PORT", std::ffi::OsStr::new("not-a-port"))); let r = mcp_session(&["mcp", "--headless"], &env, &calls[..1]); assert_ne!(r[0]["isError"], true, "{}", r[0]); + // Without the `AI-MCP` flag a Control Port saved before the agents switch (which the app + // reads as "agents may connect") still leaves plain `mcp` headless: it neither looks for + // the app nor applies When PhotoCraft Is Closed ("error" would fail this call). + std::fs::write(dir.join("preferences.json"), r#"{"integrations": {"controlPort": 7878}}"#).unwrap(); + let r = mcp_session(&["mcp", "--when-closed", "error"], &env[..2], &calls[..1]); + assert_ne!(r[0]["isError"], true, "without the flag plain mcp stays headless: {}", r[0]); let _ = std::fs::remove_dir_all(&dir); let _ = std::fs::remove_dir_all(&empty); } diff --git a/apps/photocraft/src/main.rs b/apps/photocraft/src/main.rs index 98e4702044..dbde20d44a 100644 --- a/apps/photocraft/src/main.rs +++ b/apps/photocraft/src/main.rs @@ -105,44 +105,12 @@ fn custom_titlebar(prefs_file: Option<&std::path::Path>) -> bool { /// as the app's lenient load reads them (#6611): a wrong-typed value elsewhere in the file, or /// in the other field, must not turn Allow Agent Control back on while the dialog shows it off. fn integrations(prefs_file: Option<&std::path::Path>) -> photocraft_engine::prefs::Integrations { - use serde_json::Value; - let mut out = photocraft_engine::prefs::Preferences::default().integrations; - let file: Option = prefs_file.and_then(|p| std::fs::read_to_string(p).ok()).and_then(|t| serde_json::from_str(&t).ok()); - let Some(mut section) = file.as_ref().and_then(|v| v.get("integrations")).cloned() else { - return out; - }; - // As the engine's load does: a Control Port saved before the agents switch keeps it on. - photocraft_engine::prefs::migrate_integrations(&mut section); - match serde_json::from_value(section.clone()) { - Ok(whole) => whole, - Err(_) => { - integration_fields(§ion, &mut out); - out - } - } -} - -/// [`integrations`]' value-by-value read of a section that doesn't read as a whole. -fn integration_fields(section: &serde_json::Value, out: &mut photocraft_engine::prefs::Integrations) { - use serde_json::Value; - if let Some(allow) = section.get("allowAgentControl").and_then(Value::as_bool) { - out.allow_agent_control = allow; - } - if let Some(on) = section.get("connectAgents").and_then(Value::as_bool) { - out.connect_agents = on; - } - if let Some(when) = section.get("whenAppClosed").cloned().and_then(|v| serde_json::from_value(v).ok()) { - out.when_app_closed = when; - } - if let Some(port) = section.get("controlPort").and_then(Value::as_u64).and_then(|p| u32::try_from(p).ok()) { - out.control_port = port; - } - if let Some(root) = section.get("readRoot").and_then(Value::as_str) { - root.clone_into(&mut out.read_root); - } - if let Some(root) = section.get("writeRoot").and_then(Value::as_str) { - root.clone_into(&mut out.write_root); - } + let file: Option = prefs_file.and_then(|p| std::fs::read_to_string(p).ok()).and_then(|t| serde_json::from_str(&t).ok()); + file.as_ref() + .and_then(|v| v.get("integrations")) + .cloned() + .map(photocraft_engine::prefs::read_integrations_section) + .unwrap_or_else(|| photocraft_engine::prefs::Preferences::default().integrations) } /// The automation roots: `--automation-read-root` / `--automation-write-root` (or their diff --git a/crates/automation/src/agent_link.rs b/crates/automation/src/agent_link.rs index 12b5620755..c89a14246a 100644 --- a/crates/automation/src/agent_link.rs +++ b/crates/automation/src/agent_link.rs @@ -176,11 +176,7 @@ pub fn read_integrations(dir: &Path) -> Integrations { .flatten() .and_then(|text| serde_json::from_str::(&text).ok()) .and_then(|v| v.get("integrations").cloned()) - .and_then(|mut v| { - // As the app reads it: a Control Port saved before the agents switch keeps it on. - photocraft_engine::prefs::migrate_integrations(&mut v); - serde_json::from_value(v).ok() - }) + .map(photocraft_engine::prefs::read_integrations_section) .unwrap_or_default() } @@ -303,6 +299,9 @@ mod tests { assert!(read_integrations(&dir).connect_agents); std::fs::write(dir.join("preferences.json"), r#"{"integrations": {"controlPort": 7878, "connectAgents": false}}"#).unwrap(); assert!(!read_integrations(&dir).connect_agents); + // One bad value resets only itself, as in the app: the saved closed-app choice stays. + std::fs::write(dir.join("preferences.json"), r#"{"integrations": {"whenAppClosed": "error", "readRoot": 5}}"#).unwrap(); + assert_eq!(read_integrations(&dir).when_app_closed, photocraft_engine::prefs::WhenAppClosed::Error); let _ = std::fs::remove_dir_all(&dir); } diff --git a/crates/engine/src/prefs.rs b/crates/engine/src/prefs.rs index 6543c9d311..af7875acad 100644 --- a/crates/engine/src/prefs.rs +++ b/crates/engine/src/prefs.rs @@ -1187,6 +1187,15 @@ pub fn migrate_integrations(section: &mut Value) { } } +/// A saved `integrations` section read as the app's preference load reads it: migrated, and +/// leniently (a value of the wrong type keeps its default, the rest still loads). The desktop +/// app's launch read and `photocraft-cli mcp` use it, so a bad value can't reset, say, When +/// PhotoCraft Is Closed for them alone. +pub fn read_integrations_section(mut section: Value) -> Integrations { + migrate_integrations(&mut section); + read_section(section) +} + #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(default, rename_all = "camelCase")] pub struct Integrations { diff --git a/docs/development.md b/docs/development.md index 9988617aa4..f84208c8a1 100644 --- a/docs/development.md +++ b/docs/development.md @@ -368,7 +368,7 @@ Claude Code (`.mcp.json` in the repo root, or `claude mcp add`): "mcpServers": { "photocraft": { "command": "/path/to/photocraft/target/release/photocraft-cli", - "args": ["mcp", "--automation-read-root", "/absolute/path/to/trusted/workspace", "--automation-read-root", "/absolute/path/to/reference/library", "--automation-write-root", "/absolute/path/to/trusted/workspace"] + "args": ["mcp", "--headless", "--automation-read-root", "/absolute/path/to/trusted/workspace", "--automation-read-root", "/absolute/path/to/reference/library", "--automation-write-root", "/absolute/path/to/trusted/workspace"] }, "photocraft-live": { "command": "/path/to/photocraft/target/release/photocraft-cli", @@ -381,7 +381,7 @@ Claude Code (`.mcp.json` in the repo root, or `claude mcp add`): ```sh cargo build --release -p photocraft-cli mkdir -p "$PWD/photocraft-work" -claude mcp add photocraft -- "$PWD/target/release/photocraft-cli" mcp \ +claude mcp add photocraft -- "$PWD/target/release/photocraft-cli" mcp --headless \ --automation-read-root "$PWD/photocraft-work" \ --automation-write-root "$PWD/photocraft-work" ``` From 19f040a6ae235ab7a385edb7d7f988d33b64f75b Mon Sep 17 00:00:00 2001 From: David Mann Date: Fri, 13 Nov 2026 12:36:40 +0100 Subject: [PATCH 25/28] docs(mcp): plain mcp uses the open window only with the AI-MCP flag Co-Authored-By: Claude Opus 5.5 --- docs/control-protocol.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 9f30cf8927..4ad364efb1 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -418,7 +418,7 @@ magenta alignment lines. `ui.pointer` drives the same code, so agents get identi - **Headless** (`photocraft-cli mcp --headless`, or plain `mcp` while agents may not use the app): an in-process `photocraft_engine::Session`. There is no window. CPU composition is the default; `--gpu` or `PHOTOCRAFT_GPU=1` enables optional GPU rendering with automatic CPU fallback. - **Bridge** (`photocraft-cli mcp --bridge 127.0.0.1:7878 --control-token-file `): every tool is forwarded to a running `photocraft --control 7878 --control-token-file ` over this protocol, so agents see and drive the live app. Explicit `--gpu` / `--no-gpu` flags are rejected with a usage error because the desktop controls rendering; `PHOTOCRAFT_GPU` is ignored in bridge mode. `--bridge 7878` is short for `--bridge 127.0.0.1:7878`. With no `--bridge`, `PHOTOCRAFT_CONTROL_PORT` selects the bridge port (`127.0.0.1:`), and the CLI says so on standard error; with neither (or the variable empty), the MCP runs headless. A value that is not a port is a usage error naming the variable. `--automation-read-root` or `--automation-write-root` with the variable set is a usage error, since the bridge would drop the roots. -- **The open window** (plain `photocraft-cli mcp`): the bridge, with the address and token read before every tool call from `agent-connection.json` in the app's settings folder, while the person lets agents use the app; otherwise headless, as above (`--headless` forces that). The app publishes that file while agents may connect (the ArtCraft Launcher's switch; without the `AI-MCP` flag a saved Control Port), not with `--control`, and removes it when the connection stops; a file left by a crash fails the connection probe and counts as no app. See [MCP conventions](mcp.md#connecting-the-desktop-app-no-terminal). +- **The open window** (plain `photocraft-cli mcp`): the bridge, with the address and token read before every tool call from `agent-connection.json` in the app's settings folder, with the suite's `AI-MCP` flag and while the person lets agents use the app; otherwise headless, as above (`--headless` forces that). The app publishes that file while agents may connect (the ArtCraft Launcher's switch; without the `AI-MCP` flag a saved Control Port), not with `--control`, and removes it when the connection stops; a file left by a crash fails the connection probe and counts as no app. See [MCP conventions](mcp.md#connecting-the-desktop-app-no-terminal). `ui.inspect` reports the connection as `agentLink`: `port` while agents can connect, `launchFlags` when `--control` manages it, `error`, `mcpFlag` and `launcher` (the ArtCraft Launcher's switch is on). From 94082119f1ed2c71d5d53e839bb192fced95a749 Mon Sep 17 00:00:00 2001 From: David Mann Date: Fri, 13 Nov 2026 13:17:58 +0100 Subject: [PATCH 26/28] docs(mcp): say when plain mcp is headless and that --headless always is Co-Authored-By: Claude Opus 5.5 --- docs/control-protocol.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 4ad364efb1..5f5d7d949c 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -415,8 +415,8 @@ magenta alignment lines. `ui.pointer` drives the same code, so agents get identi `photocraft-automation` provides an MCP server built on the official Rust SDK (`rmcp`). It runs in one of two modes: -- **Headless** (`photocraft-cli mcp --headless`, or plain `mcp` while agents may not use the app): an in-process `photocraft_engine::Session`. There is no window. CPU composition is the default; `--gpu` or `PHOTOCRAFT_GPU=1` enables optional GPU rendering with automatic CPU fallback. -- **Bridge** (`photocraft-cli mcp --bridge 127.0.0.1:7878 --control-token-file `): every tool is forwarded to a running `photocraft --control 7878 --control-token-file ` over this protocol, so agents see and drive the live app. Explicit `--gpu` / `--no-gpu` flags are rejected with a usage error because the desktop controls rendering; `PHOTOCRAFT_GPU` is ignored in bridge mode. `--bridge 7878` is short for `--bridge 127.0.0.1:7878`. With no `--bridge`, `PHOTOCRAFT_CONTROL_PORT` selects the bridge port (`127.0.0.1:`), and the CLI says so on standard error; with neither (or the variable empty), the MCP runs headless. A value that is not a port is a usage error naming the variable. `--automation-read-root` or `--automation-write-root` with the variable set is a usage error, since the bridge would drop the roots. +- **Headless** (`photocraft-cli mcp --headless`, always an isolated session; or plain `mcp` without the suite's `AI-MCP` flag or while agents may not use the app): an in-process `photocraft_engine::Session`. There is no window. CPU composition is the default; `--gpu` or `PHOTOCRAFT_GPU=1` enables optional GPU rendering with automatic CPU fallback. +- **Bridge** (`photocraft-cli mcp --bridge 127.0.0.1:7878 --control-token-file `): every tool is forwarded to a running `photocraft --control 7878 --control-token-file ` over this protocol, so agents see and drive the live app. Explicit `--gpu` / `--no-gpu` flags are rejected with a usage error because the desktop controls rendering; `PHOTOCRAFT_GPU` is ignored in bridge mode. `--bridge 7878` is short for `--bridge 127.0.0.1:7878`. With no `--bridge`, `PHOTOCRAFT_CONTROL_PORT` selects the bridge port (`127.0.0.1:`), and the CLI says so on standard error; with neither (or the variable empty), plain `mcp` uses the open window (below) or runs headless. A value that is not a port is a usage error naming the variable. `--automation-read-root` or `--automation-write-root` with the variable set is a usage error, since the bridge would drop the roots. - **The open window** (plain `photocraft-cli mcp`): the bridge, with the address and token read before every tool call from `agent-connection.json` in the app's settings folder, with the suite's `AI-MCP` flag and while the person lets agents use the app; otherwise headless, as above (`--headless` forces that). The app publishes that file while agents may connect (the ArtCraft Launcher's switch; without the `AI-MCP` flag a saved Control Port), not with `--control`, and removes it when the connection stops; a file left by a crash fails the connection probe and counts as no app. See [MCP conventions](mcp.md#connecting-the-desktop-app-no-terminal). From 28c3a533676a34273197b7ffbf7f4bddc775c11c Mon Sep 17 00:00:00 2001 From: David Mann Date: Fri, 13 Nov 2026 13:29:57 +0100 Subject: [PATCH 27/28] docs(mcp): the open-window entry names the closed-app choice Co-Authored-By: Claude Opus 5.5 --- docs/control-protocol.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 5f5d7d949c..44606e113f 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -418,7 +418,7 @@ magenta alignment lines. `ui.pointer` drives the same code, so agents get identi - **Headless** (`photocraft-cli mcp --headless`, always an isolated session; or plain `mcp` without the suite's `AI-MCP` flag or while agents may not use the app): an in-process `photocraft_engine::Session`. There is no window. CPU composition is the default; `--gpu` or `PHOTOCRAFT_GPU=1` enables optional GPU rendering with automatic CPU fallback. - **Bridge** (`photocraft-cli mcp --bridge 127.0.0.1:7878 --control-token-file `): every tool is forwarded to a running `photocraft --control 7878 --control-token-file ` over this protocol, so agents see and drive the live app. Explicit `--gpu` / `--no-gpu` flags are rejected with a usage error because the desktop controls rendering; `PHOTOCRAFT_GPU` is ignored in bridge mode. `--bridge 7878` is short for `--bridge 127.0.0.1:7878`. With no `--bridge`, `PHOTOCRAFT_CONTROL_PORT` selects the bridge port (`127.0.0.1:`), and the CLI says so on standard error; with neither (or the variable empty), plain `mcp` uses the open window (below) or runs headless. A value that is not a port is a usage error naming the variable. `--automation-read-root` or `--automation-write-root` with the variable set is a usage error, since the bridge would drop the roots. -- **The open window** (plain `photocraft-cli mcp`): the bridge, with the address and token read before every tool call from `agent-connection.json` in the app's settings folder, with the suite's `AI-MCP` flag and while the person lets agents use the app; otherwise headless, as above (`--headless` forces that). The app publishes that file while agents may connect (the ArtCraft Launcher's switch; without the `AI-MCP` flag a saved Control Port), not with `--control`, and removes it when the connection stops; a file left by a crash fails the connection probe and counts as no app. See [MCP conventions](mcp.md#connecting-the-desktop-app-no-terminal). +- **The open window** (plain `photocraft-cli mcp`): the bridge, with the address and token read before every tool call from `agent-connection.json` in the app's settings folder, with the suite's `AI-MCP` flag and while the person lets agents use the app. With agents allowed and the app closed, `integrations.whenAppClosed` decides (`launch`, the default: start it and wait up to 45 s; `headless`: headless with the app's agent folders; `error`: fail with "PhotoCraft isn't running"), and `--when-closed` overrides it. Otherwise headless, as above (`--headless` forces that). The app publishes that file while agents may connect (the ArtCraft Launcher's switch; without the `AI-MCP` flag a saved Control Port), not with `--control`, and removes it when the connection stops; a file left by a crash fails the connection probe and counts as no app. See [MCP conventions](mcp.md#connecting-the-desktop-app-no-terminal). `ui.inspect` reports the connection as `agentLink`: `port` while agents can connect, `launchFlags` when `--control` manages it, `error`, `mcpFlag` and `launcher` (the ArtCraft Launcher's switch is on). From 309fdf1cde7ec3a7c827a0b0a34b2944fb16256e Mon Sep 17 00:00:00 2001 From: David Mann Date: Fri, 13 Nov 2026 14:19:38 +0100 Subject: [PATCH 28/28] Address CodeRabbit review: document per-direction root overrides In closed-app headless MCP mode, a given --automation-read-root or --automation-write-root replaces the app's agent folder for that direction only. Say so in control-protocol.md and mcp.md, and pin it with a test for each direction. Co-Authored-By: Claude Opus 5.5 --- crates/automation/tests/mcp_live.rs | 39 +++++++++++++++++++++++++++++ docs/control-protocol.md | 2 +- docs/mcp.md | 6 +++-- 3 files changed, 44 insertions(+), 3 deletions(-) diff --git a/crates/automation/tests/mcp_live.rs b/crates/automation/tests/mcp_live.rs index 8100248f16..dc106a639b 100644 --- a/crates/automation/tests/mcp_live.rs +++ b/crates/automation/tests/mcp_live.rs @@ -295,6 +295,45 @@ async fn headless_uses_the_app_folders_and_stays_headless() { let _ = std::fs::remove_dir_all(&dir); } +/// Agents allowed, app closed, headless: a root flag given to `mcp` replaces the app's folder for +/// its own direction only; the other direction still falls back to the app's folder. +#[tokio::test(flavor = "multi_thread")] +async fn headless_root_flags_override_each_direction_on_their_own() { + let dir = settings_dir("headless-override"); + let (app_read, app_write, given) = (dir.join("app-read"), dir.join("app-write"), dir.join("given")); + for d in [&app_read, &app_write, &given] { + std::fs::create_dir_all(d).unwrap(); + } + prefs(&dir, json!({"connectAgents": true, "whenAppClosed": "headless", "readRoot": app_read.to_string_lossy(), "writeRoot": app_write.to_string_lossy()})); + // Only the write root is given: saves go there, reads still come from the app's read folder. + let mut c = live(&dir, None); + c.write_root = Some(given.clone()); + let client = connect(PhotocraftMcp::live(c)).await; + let r = call(&client, "doc_new", json!({"width": 8, "height": 8})).await; + assert_eq!(r.is_error, Some(false), "{}", text(&r)); + let r = call(&client, "doc_save", json!({"path": "out.pcraft"})).await; + assert_eq!(r.is_error, Some(false), "{}", text(&r)); + assert!(given.join("out.pcraft").exists(), "saved into the given write root"); + assert!(!app_write.join("out.pcraft").exists(), "not into the app's write folder"); + std::fs::copy(given.join("out.pcraft"), app_read.join("in.pcraft")).unwrap(); + let r = call(&client, "doc_open", json!({"path": app_read.join("in.pcraft").to_string_lossy()})).await; + assert_eq!(r.is_error, Some(false), "the app's read folder still applies: {}", text(&r)); + client.cancel().await.unwrap(); + // Only a read root is given: it replaces the app's read folder; saves still go to the app's write folder. + let mut c = live(&dir, None); + c.read_roots = vec![given.clone()]; + let client = connect(PhotocraftMcp::live(c)).await; + let r = call(&client, "doc_open", json!({"path": app_read.join("in.pcraft").to_string_lossy()})).await; + assert_eq!(r.is_error, Some(true), "the app's read folder is replaced by the given one"); + let r = call(&client, "doc_open", json!({"path": given.join("out.pcraft").to_string_lossy()})).await; + assert_eq!(r.is_error, Some(false), "{}", text(&r)); + let r = call(&client, "doc_save", json!({"path": "again.pcraft"})).await; + assert_eq!(r.is_error, Some(false), "{}", text(&r)); + assert!(app_write.join("again.pcraft").exists(), "saved into the app's write folder"); + client.cancel().await.unwrap(); + let _ = std::fs::remove_dir_all(&dir); +} + /// Agents not allowed: `mcp` serves a session without a window as it always did, with only the /// folders given to the command (the app's own folders are for agents the person let in), never /// starts the app, and prepares the session as the command asked (`--gpu`). diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 44606e113f..01ea921148 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -418,7 +418,7 @@ magenta alignment lines. `ui.pointer` drives the same code, so agents get identi - **Headless** (`photocraft-cli mcp --headless`, always an isolated session; or plain `mcp` without the suite's `AI-MCP` flag or while agents may not use the app): an in-process `photocraft_engine::Session`. There is no window. CPU composition is the default; `--gpu` or `PHOTOCRAFT_GPU=1` enables optional GPU rendering with automatic CPU fallback. - **Bridge** (`photocraft-cli mcp --bridge 127.0.0.1:7878 --control-token-file `): every tool is forwarded to a running `photocraft --control 7878 --control-token-file ` over this protocol, so agents see and drive the live app. Explicit `--gpu` / `--no-gpu` flags are rejected with a usage error because the desktop controls rendering; `PHOTOCRAFT_GPU` is ignored in bridge mode. `--bridge 7878` is short for `--bridge 127.0.0.1:7878`. With no `--bridge`, `PHOTOCRAFT_CONTROL_PORT` selects the bridge port (`127.0.0.1:`), and the CLI says so on standard error; with neither (or the variable empty), plain `mcp` uses the open window (below) or runs headless. A value that is not a port is a usage error naming the variable. `--automation-read-root` or `--automation-write-root` with the variable set is a usage error, since the bridge would drop the roots. -- **The open window** (plain `photocraft-cli mcp`): the bridge, with the address and token read before every tool call from `agent-connection.json` in the app's settings folder, with the suite's `AI-MCP` flag and while the person lets agents use the app. With agents allowed and the app closed, `integrations.whenAppClosed` decides (`launch`, the default: start it and wait up to 45 s; `headless`: headless with the app's agent folders; `error`: fail with "PhotoCraft isn't running"), and `--when-closed` overrides it. Otherwise headless, as above (`--headless` forces that). The app publishes that file while agents may connect (the ArtCraft Launcher's switch; without the `AI-MCP` flag a saved Control Port), not with `--control`, and removes it when the connection stops; a file left by a crash fails the connection probe and counts as no app. See [MCP conventions](mcp.md#connecting-the-desktop-app-no-terminal). +- **The open window** (plain `photocraft-cli mcp`): the bridge, with the address and token read before every tool call from `agent-connection.json` in the app's settings folder, with the suite's `AI-MCP` flag and while the person lets agents use the app. With agents allowed and the app closed, `integrations.whenAppClosed` decides (`launch`, the default: start it and wait up to 45 s; `headless`: headless, with `--automation-read-root` / `--automation-write-root` where given and the app's agent folder for each direction without one; `error`: fail with "PhotoCraft isn't running"), and `--when-closed` overrides it. Otherwise headless, as above (`--headless` forces that). The app publishes that file while agents may connect (the ArtCraft Launcher's switch; without the `AI-MCP` flag a saved Control Port), not with `--control`, and removes it when the connection stops; a file left by a crash fails the connection probe and counts as no app. See [MCP conventions](mcp.md#connecting-the-desktop-app-no-terminal). `ui.inspect` reports the connection as `agentLink`: `port` while agents can connect, `launchFlags` when `--control` manages it, `error`, `mcpFlag` and `launcher` (the ArtCraft Launcher's switch is on). diff --git a/docs/mcp.md b/docs/mcp.md index 6110c1f586..64fd88baa5 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -41,8 +41,10 @@ restarts or moves to another port. - **Agents allowed, PhotoCraft open:** tools work in the window. - **Agents allowed, PhotoCraft closed:** When PhotoCraft Is Closed decides (`--when-closed ` overrides it): start the app and wait for it, serve a headless - session with the folders chosen in the app (or the `--automation-read-root` / - `--automation-write-root` given to `mcp`), or say to open it. The app is started only on a tool + session, or say to open it. The headless session takes `--automation-read-root` and + `--automation-write-root` when given to `mcp`, each on its own: a given read root replaces the + app's read folder, a given write root its write folder, and the app's folder is used for any + direction without a flag. The app is started only on a tool call, never when the MCP client starts. - **Agents not allowed:** a headless session with only the roots given to `mcp`, exactly as before; the app is never started and its folders aren't used.