From a5dec21e9733aec48dbd5d0e2f65332bf50aba53 Mon Sep 17 00:00:00 2001 From: Brandon Thomas Date: Sun, 4 Oct 2026 11:59:51 -0400 Subject: [PATCH] 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 --- apps/photocraft-cli/src/lib.rs | 2 ++ apps/photocraft-cli/src/main.rs | 2 ++ crates/automation/src/bridge.rs | 4 ++- crates/automation/src/lib.rs | 1 + crates/automation/src/rpc.rs | 29 ++++++++++++++++++---- crates/automation/src/server.rs | 43 ++++++++++++++++++++++++--------- 6 files changed, 64 insertions(+), 17 deletions(-) diff --git a/apps/photocraft-cli/src/lib.rs b/apps/photocraft-cli/src/lib.rs index a01aaee3d6..43a1295e07 100644 --- a/apps/photocraft-cli/src/lib.rs +++ b/apps/photocraft-cli/src/lib.rs @@ -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}; diff --git a/apps/photocraft-cli/src/main.rs b/apps/photocraft-cli/src/main.rs index 5585399e6c..ec851e925a 100644 --- a/apps/photocraft-cli/src/main.rs +++ b/apps/photocraft-cli/src/main.rs @@ -1,3 +1,5 @@ +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] + fn main() { let args: Vec = std::env::args().skip(1).collect(); let code = photocraft_cli::run(&args, &mut std::io::stdout(), &mut std::io::stderr()); diff --git a/crates/automation/src/bridge.rs b/crates/automation/src/bridge.rs index e6904ea1d7..43f6ee9222 100644 --- a/crates/automation/src/bridge.rs +++ b/crates/automation/src/bridge.rs @@ -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 => { diff --git a/crates/automation/src/lib.rs b/crates/automation/src/lib.rs index 8787257960..d3c115ef27 100644 --- a/crates/automation/src/lib.rs +++ b/crates/automation/src/lib.rs @@ -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; diff --git a/crates/automation/src/rpc.rs b/crates/automation/src/rpc.rs index 66a86db842..cb99ba9159 100644 --- a/crates/automation/src/rpc.rs +++ b/crates/automation/src/rpc.rs @@ -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, 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(); diff --git a/crates/automation/src/server.rs b/crates/automation/src/server.rs index ab0f721ed6..5b0a633ce9 100644 --- a/crates/automation/src/server.rs +++ b/crates/automation/src/server.rs @@ -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 { - 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) } }