mirror of
https://github.com/storytold/photocraft.git
synced 2026-12-02 06:20:48 +01:00
Never crash: automation (MCP/RPC) and photocraft-cli are panic-free
- rpc::respond (the JSON-lines server behind `photocraft-cli run`/TCP)
catches a panicking request and answers it with an error, and keeps
using a poisoned session lock (as the MCP server already does) instead
of failing every later call with "session lock poisoned". Regression
test poisoned_session_keeps_serving.
- MCP server: the eight bridge_client().expect("bridge") and the
headless_op(..).expect("headless") calls return a tool error instead.
- bridge: the connection is taken with let-else, not expect.
- automation and photocraft-cli deny unwrap/expect/panic/unimplemented/
todo/unreachable.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
1 parent
296ced38d6
commit
a5dec21e97
6 files changed
+64
-17
No files matched your search
@@ -1,6 +1,8 @@
|
||||
//! Headless Photocraft command line. `run` is the whole program, so it can be
|
||||
//! tested in-process as well as through the binary.
|
||||
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
|
||||
use std::io::Write;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
|
||||
fn main() {
|
||||
let args: Vec<String> = std::env::args().skip(1).collect();
|
||||
let code = photocraft_cli::run(&args, &mut std::io::stdout(), &mut std::io::stderr());
|
||||
|
||||
@@ -56,7 +56,9 @@ impl BridgeClient {
|
||||
*guard = Some((BufReader::new(r), w));
|
||||
}
|
||||
let id = self.next_id.fetch_add(1, Ordering::Relaxed);
|
||||
let conn = guard.as_mut().expect("connected");
|
||||
let Some(conn) = guard.as_mut() else {
|
||||
return Err(AutomationError::Bridge(format!("not connected to {}", self.addr)));
|
||||
};
|
||||
match tokio::time::timeout(self.timeout, exchange(conn, id, method, ¶ms)).await {
|
||||
Ok(Ok(v)) => return v,
|
||||
Ok(Err(e)) if attempt == 0 => {
|
||||
|
||||
@@ -14,6 +14,7 @@
|
||||
//!
|
||||
//! 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 bridge;
|
||||
pub mod files;
|
||||
|
||||
@@ -16,7 +16,7 @@
|
||||
use std::io::{BufRead, Write};
|
||||
use std::net::TcpListener;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::sync::{Arc, Mutex, PoisonError};
|
||||
|
||||
use base64::Engine as _;
|
||||
use serde_json::{Value, json};
|
||||
@@ -160,10 +160,12 @@ pub fn respond(h: &Mutex<Headless>, line: &str) -> Value {
|
||||
return json!({"id": id, "ok": false, "error": "missing `method`"});
|
||||
};
|
||||
let params = req.get("params").cloned().unwrap_or(Value::Null);
|
||||
let r = match h.lock() {
|
||||
Ok(mut g) => g.handle(method, params),
|
||||
Err(_) => Err(AutomationError::Other("session lock poisoned".into())),
|
||||
};
|
||||
// Last-resort guard (AGENTS.md, Never crash): a command that panics answers this request
|
||||
// with an error instead of taking down the connection (or the whole stdio server). Edits
|
||||
// run on a copy of the document (`Session::edit`), so the session stays consistent and a
|
||||
// poisoned lock is safe to keep using, the same as the MCP server does.
|
||||
let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| h.lock().unwrap_or_else(PoisonError::into_inner).handle(method, params)))
|
||||
.unwrap_or_else(|_| Err(AutomationError::Other(format!("internal error: `{method}` panicked"))));
|
||||
match r {
|
||||
Ok(v) => json!({"id": id, "ok": true, "result": v}),
|
||||
Err(e) => json!({"id": id, "ok": false, "error": e.to_string()}),
|
||||
@@ -239,6 +241,23 @@ mod tests {
|
||||
assert_eq!(replies[4]["id"], Value::Null);
|
||||
}
|
||||
|
||||
/// Regression: after a panic while the session lock was held, every later request
|
||||
/// failed with "session lock poisoned"; the server now keeps serving.
|
||||
#[test]
|
||||
fn poisoned_session_keeps_serving() {
|
||||
let h = session();
|
||||
let _ = std::thread::scope(|sc| {
|
||||
sc.spawn(|| {
|
||||
let _g = h.lock().unwrap();
|
||||
panic!("poison the session lock");
|
||||
})
|
||||
.join()
|
||||
});
|
||||
assert!(h.is_poisoned());
|
||||
let r = respond(&h, r#"{"id":1,"method":"doc.new","params":{"width":8,"height":8}}"#);
|
||||
assert_eq!(r["ok"], true, "{r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn batch_stops_on_error_unless_told_not_to() {
|
||||
let h = session();
|
||||
|
||||
@@ -165,6 +165,12 @@ fn fail(e: impl std::fmt::Display) -> CallToolResult {
|
||||
CallToolResult::error(vec![Content::text(e.to_string())])
|
||||
}
|
||||
|
||||
/// Neither backend took the call. The backend is always headless or a bridge, so this only
|
||||
/// guards against a future backend kind.
|
||||
fn no_backend() -> CallToolResult {
|
||||
fail("internal error: no headless session or app bridge")
|
||||
}
|
||||
|
||||
fn png_result(png: &[u8], note: String) -> CallToolResult {
|
||||
let b64 = base64::engine::general_purpose::STANDARD.encode(png);
|
||||
CallToolResult::success(vec![Content::image(b64, "image/png"), Content::text(note)])
|
||||
@@ -285,7 +291,9 @@ impl PhotocraftMcp {
|
||||
if let Some(r) = self.headless_op(|h| Ok(h.session_list())).await {
|
||||
return to_result(r);
|
||||
}
|
||||
let b = self.bridge_client().expect("bridge");
|
||||
let Some(b) = self.bridge_client() else {
|
||||
return Ok(no_backend());
|
||||
};
|
||||
to_result(b.call("ui.inspect", json!({})).await)
|
||||
}
|
||||
|
||||
@@ -295,7 +303,9 @@ impl PhotocraftMcp {
|
||||
if let Some(r) = self.headless_op(move |h| h.open(&path)).await {
|
||||
return to_result(r);
|
||||
}
|
||||
let b = self.bridge_client().expect("bridge");
|
||||
let Some(b) = self.bridge_client() else {
|
||||
return Ok(no_backend());
|
||||
};
|
||||
to_result(b.call("app.open", json!({"path": p.path})).await)
|
||||
}
|
||||
|
||||
@@ -342,7 +352,9 @@ impl PhotocraftMcp {
|
||||
if let Some(r) = self.headless_op(move |h| h.inspect(p.index)).await {
|
||||
return to_result(r);
|
||||
}
|
||||
let b = self.bridge_client().expect("bridge");
|
||||
let Some(b) = self.bridge_client() else {
|
||||
return Ok(no_backend());
|
||||
};
|
||||
to_result(b.call("engine.execute", json!({"command": "document.inspect", "params": {}})).await)
|
||||
}
|
||||
|
||||
@@ -355,7 +367,9 @@ impl PhotocraftMcp {
|
||||
Err(e) => fail(e),
|
||||
});
|
||||
}
|
||||
let b = self.bridge_client().expect("bridge");
|
||||
let Some(b) = self.bridge_client() else {
|
||||
return Ok(no_backend());
|
||||
};
|
||||
self.screenshot(b, Some(max)).await
|
||||
}
|
||||
|
||||
@@ -380,7 +394,9 @@ impl PhotocraftMcp {
|
||||
let all = if let Some(r) = self.headless_op(|h| Ok(h.command_list())).await {
|
||||
r
|
||||
} else {
|
||||
let b = self.bridge_client().expect("bridge");
|
||||
let Some(b) = self.bridge_client() else {
|
||||
return Ok(no_backend());
|
||||
};
|
||||
b.call("engine.commands", json!({})).await
|
||||
};
|
||||
let all = match all {
|
||||
@@ -417,7 +433,9 @@ impl PhotocraftMcp {
|
||||
if let Some(r) = self.headless_op(move |h| h.batch(&args)).await {
|
||||
return to_result(r);
|
||||
}
|
||||
let b = self.bridge_client().expect("bridge");
|
||||
let Some(b) = self.bridge_client() else {
|
||||
return Ok(no_backend());
|
||||
};
|
||||
let mut results = Vec::new();
|
||||
let mut failed = 0;
|
||||
for s in &steps {
|
||||
@@ -502,19 +520,20 @@ impl PhotocraftMcp {
|
||||
if let Some(r) = self.headless_op(move |h| h.command_run(&id2, params2)).await {
|
||||
return to_result(r);
|
||||
}
|
||||
let b = self.bridge_client().expect("bridge");
|
||||
let Some(b) = self.bridge_client() else {
|
||||
return Ok(no_backend());
|
||||
};
|
||||
to_result(b.call("engine.execute", json!({"command": id, "params": params})).await)
|
||||
}
|
||||
|
||||
async fn save_impl(&self, p: SaveParams) -> Result<CallToolResult, McpError> {
|
||||
if self.bridge_client().is_some() {
|
||||
let b = self.bridge_client().expect("bridge");
|
||||
if let Some(b) = self.bridge_client() {
|
||||
let Some(path) = p.path else {
|
||||
return Ok(fail("bridge mode needs `path`"));
|
||||
};
|
||||
return to_result(b.call("app.save", json!({"path": path})).await);
|
||||
}
|
||||
let r = self
|
||||
let Some(r) = self
|
||||
.headless_op(move |h| {
|
||||
let mut opts = photocraft_io::ExportOptions::default();
|
||||
if let Some(q) = p.quality {
|
||||
@@ -524,7 +543,9 @@ impl PhotocraftMcp {
|
||||
h.save(p.index, path.as_deref(), p.format.as_deref(), &opts)
|
||||
})
|
||||
.await
|
||||
.expect("headless");
|
||||
else {
|
||||
return Ok(no_backend());
|
||||
};
|
||||
to_result(r)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user