mirror of
https://github.com/storytold/photocraft.git
synced 2026-11-16 15:14:38 +00:00
AI Integrations: connect MCP clients to the running app without a terminal
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 <noreply@anthropic.com>
This commit is contained in:
1 parent
706638b284
commit
f84bbb6fa5
50 files changed
+2489
-137
No files matched your search
@@ -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
|
||||
|
||||
@@ -43,6 +43,13 @@ USAGE:
|
||||
photocraft-cli mcp [--bridge <127.0.0.1:port>] [--control-token <64-hex> | --control-token-file <path>]
|
||||
[--automation-read-root <dir>] [--automation-write-root <dir>]
|
||||
Run the MCP server on stdio (headless engine, or bridge to a running `photocraft --control <port>`).
|
||||
photocraft-cli mcp --live [--when-closed <launch|headless|error>] [--automation-read-root <dir>] [--automation-write-root <dir>]
|
||||
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 <claude-desktop|claude-code|cursor|json>
|
||||
Add `photocraft-cli mcp --live` to an MCP client's configuration (json: print it to paste).
|
||||
photocraft-cli serve [--port <port>] [--control-token <64-hex> | --control-token-file <path>]
|
||||
[--automation-read-root <dir>] [--automation-write-root <dir>]
|
||||
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<photocraft_automation::live::LiveConfig, String> {
|
||||
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 <id>`: 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::*;
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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<ControlRequest>), 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<PathBuf>, mcp: Option<McpLaunch>) -> AgentLinkFn {
|
||||
let mut running: Option<Running> = 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<Running>, dir: Option<&Path>, integrations: &Integrations, ctx: &egui::Context, mcp_command: Option<String>) -> 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<McpLaunch> {
|
||||
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<McpLaunch>) -> 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"));
|
||||
}
|
||||
}
|
||||
@@ -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 `<exe dir>/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,
|
||||
/// `<exe dir>/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<PathBuf>,
|
||||
pub mode: Mode,
|
||||
/// Set when a portable marker was found but its data folder isn't writable.
|
||||
pub warning: Option<String>,
|
||||
}
|
||||
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<PathBuf> {
|
||||
current().dir.clone()
|
||||
}
|
||||
|
||||
/// Resolve the data directory from the environment (`env`) and the executable's folder.
|
||||
pub fn resolve(env: impl Fn(&str) -> Option<OsString>, 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<OsString>) -> Option<PathBuf> {
|
||||
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<PathBuf> {
|
||||
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 {
|
||||
|
||||
@@ -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<ControlRequest> {
|
||||
let (tx, rx) = channel::<ControlRequest>();
|
||||
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::<ControlRequest>().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<AtomicBool>,
|
||||
}
|
||||
|
||||
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<ControlRequest>, Listening)> {
|
||||
let (tx, rx) = channel::<ControlRequest>();
|
||||
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<ControlRe
|
||||
serve(stream, &token, tx, ctx);
|
||||
});
|
||||
}
|
||||
});
|
||||
rx
|
||||
})?;
|
||||
Ok((rx, Listening { port, stop }))
|
||||
}
|
||||
|
||||
fn serve(stream: TcpStream, token: &str, tx: Sender<ControlRequest>, 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::<Value>(&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::<Value>(&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";
|
||||
|
||||
@@ -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")]
|
||||
{
|
||||
|
||||
@@ -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<photocraft_automation::AuthorizedWorkspace>) -> Services {
|
||||
let clip: Rc<RefCell<Option<arboard::Clipboard>>> = 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_automation::AuthorizedWorkspace>) -> 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<photocraft_automation::AuthorizedWorkspace>) -> Services {
|
||||
let clip: Rc<RefCell<Option<arboard::Clipboard>>> = 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<photocraft_automation::AuthorizedWorkspace>) ->
|
||||
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())
|
||||
|
||||
@@ -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 <port>`.
|
||||
- **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
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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:<port>`.
|
||||
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<Option<String>, 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<Option<Connection>, AutomationError> {
|
||||
let Some(text) = read_small(&dir.join(CONNECTION_FILE))? else { return Ok(None) };
|
||||
Ok(serde_json::from_str::<Connection>(&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::<Value>(&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<PathBuf> {
|
||||
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<String>,
|
||||
}
|
||||
|
||||
impl McpLaunch {
|
||||
/// `<cli> 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::<Vec<_>>().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> {
|
||||
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<PathBuf>,
|
||||
/// `%APPDATA%` (Windows).
|
||||
pub appdata: Option<PathBuf>,
|
||||
/// `$XDG_CONFIG_HOME` (Linux).
|
||||
pub xdg_config: Option<PathBuf>,
|
||||
/// `$PATH`, searched for the `claude` command.
|
||||
pub path: Option<std::ffi::OsString>,
|
||||
}
|
||||
|
||||
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<PathBuf> {
|
||||
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<PathBuf> {
|
||||
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<PathBuf>, 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<Installed, AutomationError> {
|
||||
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<Installed, AutomationError> {
|
||||
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::<Value>(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<Installed, AutomationError> {
|
||||
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");
|
||||
}
|
||||
}
|
||||
@@ -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 `<exe dir>/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,
|
||||
/// `<exe dir>/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<PathBuf>,
|
||||
pub mode: Mode,
|
||||
/// Set when a portable marker was found but its data folder isn't writable.
|
||||
pub warning: Option<String>,
|
||||
}
|
||||
|
||||
/// Resolve the data directory from the environment (`env`) and the executable's folder.
|
||||
pub fn resolve(env: impl Fn(&str) -> Option<OsString>, 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<OsString>) -> Option<PathBuf> {
|
||||
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<PathBuf> {
|
||||
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))
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
@@ -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<dyn Fn() -> 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<WhenAppClosed>,
|
||||
/// Override the app's folders for a headless session (`--automation-read-root`,
|
||||
/// `--automation-write-root`).
|
||||
pub read_root: Option<PathBuf>,
|
||||
pub write_root: Option<PathBuf>,
|
||||
/// Starts the app; `None` when this install can't (Flatpak sandbox, no app beside the CLI).
|
||||
pub launch: Option<LaunchFn>,
|
||||
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<BridgeClient>),
|
||||
Headless(Arc<Mutex<Headless>>),
|
||||
}
|
||||
|
||||
/// 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<Option<(Target, Option<BridgeKey>)>>,
|
||||
}
|
||||
|
||||
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<Target> {
|
||||
self.current.lock().unwrap_or_else(PoisonError::into_inner).as_ref().map(|(t, _)| t.clone())
|
||||
}
|
||||
|
||||
fn set(&self, target: Target, key: Option<BridgeKey>) {
|
||||
*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<T: Send + 'static>(f: impl FnOnce() -> T + Send + 'static) -> Result<T, String> {
|
||||
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<Option<(Connection, String)>, 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<LaunchFn> {
|
||||
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;
|
||||
}
|
||||
@@ -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<String, AutomationError> {
|
||||
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<String, AutomationError> {
|
||||
@@ -253,6 +267,24 @@ pub fn token_inputs(supplied: Option<String>, token_file: Option<PathBuf>) -> (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();
|
||||
|
||||
@@ -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<Mutex<Headless>>),
|
||||
/// A running desktop app reached over the control protocol.
|
||||
Bridge(Arc<BridgeClient>),
|
||||
/// 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<Live>),
|
||||
}
|
||||
|
||||
#[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<T, AutomationError> + Send + 'static,
|
||||
) -> Option<Result<T, AutomationError>> {
|
||||
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<Arc<Mutex<Headless>>> {
|
||||
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<Arc<BridgeClient>> {
|
||||
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<u32>) -> Result<CallToolResult, McpError> {
|
||||
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<ScreenshotParams>) -> Result<CallToolResult, McpError> {
|
||||
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"),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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<RoleServer>) -> Result<ReadResourceResponse, McpError> {
|
||||
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?,
|
||||
|
||||
@@ -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<RoleClient, Client> {
|
||||
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<RoleClient, Client>, 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::<Vec<_>>().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<std::sync::atomic::AtomicBool>,
|
||||
}
|
||||
|
||||
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<WhenAppClosed>) -> 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);
|
||||
}
|
||||
@@ -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,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -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)),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -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.
|
||||
|
Can't render this file because it contains an unexpected character in line 6 and column 47.
|
@@ -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.
|
||||
|
Can't render this file because it contains an unexpected character in line 6 and column 47.
|
@@ -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. Οι ρυθμίσεις αντιγράφηκαν.
|
||||
|
Can't render this file because it contains an unexpected character in line 1029 and column 18.
|
@@ -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.
|
||||
|
Can't render this file because it contains an unexpected character in line 4 and column 47.
|
@@ -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.
|
||||
|
Can't render this file because it contains an unexpected character in line 6 and column 47.
|
@@ -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.
|
||||
|
Can't render this file because it contains an unexpected character in line 6 and column 47.
|
@@ -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.
|
||||
|
Can't render this file because it contains an unexpected character in line 4 and column 47.
|
@@ -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.
|
||||
|
Can't render this file because it contains an unexpected character in line 2647 and column 53.
|
@@ -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. 設定をコピーしました。
|
||||
|
Can't render this file because it contains an unexpected character in line 6 and column 47.
|
@@ -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. 구성을 복사했습니다.
|
||||
|
Can't render this file because it contains an unexpected character in line 3160 and column 53.
|
@@ -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.
|
||||
|
Can't render this file because it contains an unexpected character in line 8 and column 34.
|
@@ -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ę.
|
||||
|
Can't render this file because it contains an unexpected character in line 6 and column 47.
|
@@ -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.
|
||||
|
Can't render this file because it contains an unexpected character in line 6 and column 47.
|
@@ -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. Конфигурация скопирована.
|
||||
|
Can't render this file because it contains an unexpected character in line 6 and column 47.
|
@@ -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.
|
||||
|
Can't render this file because it contains an unexpected character in line 6 and column 47.
|
@@ -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ı.
|
||||
|
Can't render this file because it contains an unexpected character in line 8 and column 34.
|
@@ -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. Конфігурацію скопійовано.
|
||||
|
Can't render this file because it contains an unexpected character in line 1387 and column 18.
|
@@ -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.
|
||||
|
Can't render this file because it contains an unexpected character in line 6 and column 47.
|
@@ -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. 已复制配置。
|
||||
|
Can't render this file because it contains an unexpected character in line 2593 and column 53.
|
@@ -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. 已複製設定。
|
||||
|
Can't render this file because it contains an unexpected character in line 6 and column 47.
|
@@ -336,6 +336,53 @@ pub type AutomationWriteFn = Box<dyn FnMut(&str, &[u8]) -> Result<(), String>>;
|
||||
pub type AutomationOpenPcraftFn = Box<dyn FnMut(&str) -> Result<Option<(String, Document)>, String>>;
|
||||
/// Reject engine commands which still perform ambient filesystem I/O.
|
||||
pub type AutomationCommandFn = Box<dyn Fn(&str, &Value) -> 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<AutomationReadFn>,
|
||||
pub write: Option<AutomationWriteFn>,
|
||||
pub open_pcraft: Option<AutomationOpenPcraftFn>,
|
||||
pub save: Option<SaveFileFn>,
|
||||
pub command: Option<AutomationCommandFn>,
|
||||
pub authorize: Option<AutomationAuthorizeFn>,
|
||||
}
|
||||
|
||||
/// 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<u16>,
|
||||
/// 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<String>,
|
||||
/// How an MCP client starts PhotoCraft's MCP server (`photocraft-cli mcp --live`).
|
||||
pub mcp_command: Option<String>,
|
||||
}
|
||||
|
||||
/// 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<Receiver<ControlRequest>>,
|
||||
/// 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<dyn FnMut(&photocraft_engine::prefs::Integrations, &egui::Context) -> 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<dyn FnMut(&str) -> Result<String, String>>;
|
||||
/// Open a URL in the system browser (native) — reliable cross-platform, unlike `ctx.open_url`.
|
||||
pub type OpenUrlFn = Box<dyn Fn(&str) -> Result<(), String>>;
|
||||
pub type EncodePngFn = Box<dyn Fn(u32, u32, &[u8]) -> Result<Vec<u8>, 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<fn(&str, &serde_json::Value) -> photocraft_engine::Result<()>>,
|
||||
pub automation_authorize: Option<AutomationAuthorizeFn>,
|
||||
/// 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<AgentLinkFn>,
|
||||
/// Preferences › AI Integrations' buttons that add PhotoCraft to MCP clients (desktop).
|
||||
pub agent_clients: Option<AgentClientFn>,
|
||||
/// Encode an RGBA8 image as PNG (used for screenshots and `ui.render`).
|
||||
pub encode_png: Option<EncodePngFn>,
|
||||
/// 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<QuitFn>,
|
||||
}
|
||||
|
||||
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<tone::Histograms>)>);
|
||||
@@ -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<Receiver<ControlRequest>>,
|
||||
/// Preferences › AI Integrations: the agent connection's state (see [`Services::agent_link`]).
|
||||
pub agent_link: AgentLinkStatus,
|
||||
pending_screenshots: Vec<(u64, Option<String>, Sender<ControlResponse>)>,
|
||||
/// 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(),
|
||||
|
||||
@@ -52,6 +52,8 @@ pub struct Runtime {
|
||||
show_rulers: Option<bool>,
|
||||
/// Tool options as last remembered in the preferences (see `tool_memory`).
|
||||
pub(crate) tool_options: Option<crate::state::ToolOptions>,
|
||||
/// AI Integrations settings the agent connection was last set up for (`sync_agent_link`).
|
||||
agent_link: Option<prefs::Integrations>,
|
||||
}
|
||||
|
||||
/// 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<String, Valu
|
||||
match f.get("__prefsui").and_then(Value::as_str).unwrap_or("") {
|
||||
"prefs" => {
|
||||
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<String, Value>, system: Option<egui
|
||||
if !has_visible_fields(&values, §ion) {
|
||||
ui.add_space(4.0);
|
||||
ui.label(RichText::new(tl!("These settings aren't available in PhotoCraft yet.")).color(t.text_faint));
|
||||
} else if section == "integrations"
|
||||
&& let Some(obj) = values.get_mut(§ion).and_then(Value::as_object_mut)
|
||||
{
|
||||
integration_rows(ui, obj, f);
|
||||
} 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" {
|
||||
@@ -1245,6 +1289,118 @@ fn gpu_status_rows(ui: &mut egui::Ui, info: Option<&Value>, obj: &mut Map<String
|
||||
});
|
||||
}
|
||||
|
||||
/// Preferences › AI Integrations: whether agents may connect, the folders they may use, what
|
||||
/// `photocraft-cli mcp --live` does while the app is closed, and buttons that add PhotoCraft to
|
||||
/// MCP clients. A button click is left in `f["__agentAction"]` for [`agent_action`].
|
||||
fn integration_rows(ui: &mut egui::Ui, obj: &mut Map<String, Value>, f: &mut Map<String, Value>) {
|
||||
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<String> = 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<String, Value>, 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<String, Value>) {
|
||||
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<Mutex<Vec<prefs::Integrations>>> = Arc::default();
|
||||
let seen = calls.clone();
|
||||
let (tx, rx) = channel::<crate::ControlRequest>();
|
||||
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"));
|
||||
|
||||
@@ -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 <path>`): every tool is forwarded to a running `photocraft --control 7878 --control-token-file <path>` 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
|
||||
|
||||
@@ -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 <dir> --automation-write-root <dir>`. 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 <private-path> --automation-read-root <dir> --automation-write-root <dir>`, then run `photocraft-cli mcp --bridge 127.0.0.1:7878 --control-token-file <private-path>`. 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 <claude-desktop|claude-code|cursor|json>`, 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.
|
||||
|
||||
|
||||
+31
@@ -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 <claude-desktop|claude-code|cursor|json>`
|
||||
does what the buttons do. `--when-closed <launch|headless|error>` 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
|
||||
|
||||
+5
-4
@@ -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
|
||||
|
||||
|
||||
@@ -92,5 +92,13 @@ integrate() {
|
||||
done
|
||||
}
|
||||
|
||||
# `PhotoCraft.AppImage --cli <args>` 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" "$@"
|
||||
@@ -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"
|
||||
@@ -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"
|
||||
|
||||
@@ -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"
|
||||
Reference in new issue
Block a user