PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Actions: actions.record/stop/play/list commands for agents and the CLI (part of #219) (#622)
Matt Van Horn4a0a8d07948b
diff --git a/apps/photocraft/src/services.rs b/apps/photocraft/src/services.rsindex f16cf822e..9a18cc1bb 100644--- a/apps/photocraft/src/services.rs+++ b/apps/photocraft/src/services.rs@@ -139,6 +139,8 @@ pub fn native(automation: Option<photocraft_automation::AuthorizedWorkspace>) ->let automation_write = automation.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 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(|_| {Box::new(|id: &str, params: &serde_json::Value| {photocraft_automation::workspace::authorize_desktop_engine_command(id, params).map_err(|error| error.to_string())@@ -184,6 +186,7 @@ pub fn native(automation: Option<photocraft_automation::AuthorizedWorkspace>) ->automation_read,automation_write,automation_command,+ automation_authorize,encode_png: Some(Box::new(|w, h, rgba| {let img = Image::from_u8(w, h, ChannelLayout::Rgba, rgba.to_vec()).map_err(|e| e.to_string())?;photocraft_codecs::encode(&img, photocraft_codecs::Format::Png, &EncodeOptions::default()).map_err(|e| e.to_string())diff --git a/crates/automation/src/headless.rs b/crates/automation/src/headless.rsindex 0f944af4a..b685c3d3c 100644--- a/crates/automation/src/headless.rs+++ b/crates/automation/src/headless.rs@@ -9,9 +9,15 @@ use photocraft_format::PcraftWriter;use photocraft_io::ExportOptions;use serde_json::{Value, json};-use crate::workspace::authorize_engine_command;+use crate::workspace::{authorize_engine_command, authorize_engine_step};use crate::{AuthorizedWorkspace, AutomationError, files};+fn untrusted(filesystem: Filesystem) -> Headless {+ let mut session = Session::new();+ session.authorize = Some(authorize_engine_step);+ Headless { session, writers: HashMap::new(), filesystem }+}+enum Filesystem {Denied,TrustedLocal,@@ -28,7 +34,7 @@ pub struct Headless {impl Default for Headless {fn default() -> Self {- Self { session: Session::new(), writers: HashMap::new(), filesystem: Filesystem::Denied }+ untrusted(Filesystem::Denied)}}@@ -39,14 +45,16 @@ impl Headless {}/// Create a session for an explicit local CLI invocation. The CLI caller,- /// not a remote automation client, supplies these host paths.+ /// not a remote automation client, supplies these host paths. Nested+ /// `actions.play` steps are not re-checked: this caller is already trusted.pub fn trusted_local() -> Self {Self { session: Session::new(), writers: HashMap::new(), filesystem: Filesystem::TrustedLocal }}/// Create an automation session with capability-scoped file access.+ /// Each step of `actions.play` is checked with [`authorize_engine_step`].pub fn with_workspace(workspace: AuthorizedWorkspace) -> Self {- Self { session: Session::new(), writers: HashMap::new(), filesystem: Filesystem::Workspace(workspace) }+ untrusted(Filesystem::Workspace(workspace))}/// Apply background jobs that finished since the last request, so every request (save,diff --git a/crates/automation/src/workspace.rs b/crates/automation/src/workspace.rsindex 013919c1d..5b4c63be3 100644--- a/crates/automation/src/workspace.rs+++ b/crates/automation/src/workspace.rs@@ -201,6 +201,17 @@ pub fn authorize_desktop_engine_command(id: &str, params: &Value) -> Result<(),Ok(())}+/// [`authorize_engine_command`] as the function pointer [`photocraft_engine::Session::authorize`]+/// stores. `actions.play` calls it for every nested step.+pub fn authorize_engine_step(id: &str, params: &Value) -> photocraft_engine::Result<()> {+ authorize_engine_command(id, params).map_err(|e| photocraft_engine::EngineError::Other(e.to_string()))+}++/// [`authorize_desktop_engine_command`] as a [`photocraft_engine::Session::authorize`] hook.+pub fn authorize_desktop_engine_step(id: &str, params: &Value) -> photocraft_engine::Result<()> {+ authorize_desktop_engine_command(id, params).map_err(|e| photocraft_engine::EngineError::Other(e.to_string()))+}+fn params_contain_ambient_path(id: &str, params: &Value) -> bool {let keys: &[&str] = match id {"image.adjustments.colorLookup" | "layer.newAdjustmentLayer.colorLookup" | "layer.setAdjustment" => &["file"],@@ -432,5 +443,8 @@ mod tests {assert!(authorize_engine_command("filter.distort.displace", &serde_json::json!({"mapPath": "outside.png"})).is_err());assert!(authorize_engine_command("layer.setAdjustment", &serde_json::json!({"file": "outside.cube"})).is_err());assert!(authorize_engine_command("prefs.set", &serde_json::json!({"path": "colorSettings.workingRgb", "value": "outside.icc"})).is_err());+ assert!(authorize_engine_step("file.open", &serde_json::json!({})).is_err());+ assert!(authorize_engine_step("actions.play", &serde_json::json!({})).is_ok());+ assert!(authorize_desktop_engine_step("file.saveACopy", &serde_json::json!({})).is_err());}}diff --git a/crates/automation/tests/agent_tasks.rs b/crates/automation/tests/agent_tasks.rsindex f740f4fe0..979208506 100644--- a/crates/automation/tests/agent_tasks.rs+++ b/crates/automation/tests/agent_tasks.rs@@ -265,3 +265,68 @@ async fn agent_edits_text_by_position() {c.cancel().await.unwrap();std::fs::remove_dir_all(dir).unwrap();}++async fn connect_headless(headless: photocraft_automation::Headless) -> Conn {+ let (s, c) = tokio::io::duplex(1 << 20);+ tokio::spawn(async move {+ let backend = photocraft_automation::Backend::Headless(std::sync::Arc::new(std::sync::Mutex::new(headless)));+ if let Ok(running) = PhotocraftMcp::with_backend(backend).serve(s).await {+ let _ = running.waiting().await;+ }+ });+ Client.serve(c).await.expect("client init")+}++#[tokio::test(flavor = "multi_thread")]+async fn agent_records_and_replays_an_action() {+ let dir = tmp("actions");+ let c = connect(&dir).await;+ let listed = tool(&c, "command_list", json!({"filter": "actions."})).await;+ let ids: Vec<&str> = listed.as_array().unwrap().iter().filter_map(|item| item.get("id").and_then(Value::as_str)).collect();+ for id in ["actions.list", "actions.get", "actions.record", "actions.stop", "actions.play", "actions.delete"] {+ assert!(ids.contains(&id), "{id} missing from {ids:?}");+ }++ run(&c, "file.new", json!({"width": 32, "height": 32, "background": "white"})).await;+ run(&c, "actions.record", json!({"name": "Red"})).await;+ run(&c, "layer.new.layer", json!({})).await;+ run(&c, "select.rect", json!({"x": 0, "y": 0, "width": 8, "height": 8})).await;+ run(&c, "edit.fill", json!({"color": "#ff0000"})).await;+ let stopped = run(&c, "actions.stop", json!({})).await;+ assert_eq!(stopped["steps"], 3, "{stopped}");+ let got = run(&c, "actions.get", json!({"action": "Red"})).await;+ assert_eq!(got["steps"][0][0], "layer.new.layer");+ assert_eq!(got["steps"][1][0], "select.rect");+ assert_eq!(got["steps"][2][0], "edit.fill");++ run(&c, "file.new", json!({"width": 32, "height": 32, "background": "white"})).await;+ let played = run(&c, "actions.play", json!({"action": "Red"})).await;+ assert_eq!(played["ran"], 3, "{played}");+ assert!(played.get("failed").is_none(), "{played}");+ let px = pixel(&c, 2, 2).await;+ assert!(close(&px, &[1.0, 0.0, 0.0, 1.0], 1e-4), "{px:?}");++ c.cancel().await.unwrap();+ std::fs::remove_dir_all(dir).unwrap();+}++#[tokio::test(flavor = "multi_thread")]+async fn agent_play_refuses_a_recorded_file_open() {+ let dir = tmp("actions-auth");+ let workspace = AuthorizedWorkspace::new(Some(&dir), Some(&dir)).expect("test workspace");+ let mut headless = photocraft_automation::Headless::with_workspace(workspace);+ headless.session.actions.list.push(photocraft_engine::actions_cmds::Action {+ name: "Open".into(),+ steps: vec![("file.open".into(), json!({"path": "/etc/passwd"})), ("layer.new.layer".into(), json!({}))],+ });+ let c = connect_headless(headless).await;+ let played = run(&c, "actions.play", json!({"action": "Open"})).await;+ assert_eq!(played["ran"], 0, "{played}");+ assert_eq!(played["failed"]["step"], 0, "{played}");+ assert_eq!(played["failed"]["id"], "file.open", "{played}");+ assert!(played["failed"]["error"].as_str().unwrap_or("").contains("disabled"), "{played}");+ let session = tool(&c, "session_list", json!({})).await;+ assert!(session["documents"].as_array().is_some_and(|d| d.is_empty()), "{session}");+ c.cancel().await.unwrap();+ std::fs::remove_dir_all(dir).unwrap();+}diff --git a/crates/engine/src/actions_cmds.rs b/crates/engine/src/actions_cmds.rsnew file mode 100644index 000000000..90212f9b6--- /dev/null+++ b/crates/engine/src/actions_cmds.rs@@ -0,0 +1,470 @@+//! Window › Actions, as engine commands (`actions.record` / `stop` / `play` / `list` / `get` /+//! `delete`).+//!+//! The list lives on [`Session`] so the panel, the CLI, the control channel and MCP share one+//! copy. Recording copies replayable journal entries (commands whose [`CommandSpec::journal`] is+//! set, except `actions.*`) into an action. Playback runs those steps with [`Session::execute`]+//! and stops at the first error, leaving one history step per step that ran.+//!+//! An untrusted session installs [`Session::authorize`]. `actions.play` calls it for every nested+//! step, because the outer `actions.play` id would otherwise hide a recorded `file.*` command from+//! the top-level check.++use serde::{Deserialize, Serialize};+use serde_json::{Value, json};++use crate::commands::CommandSpec;+use crate::{EngineError, Result, Session};++fn bad(cmd: &str, msg: impl Into<String>) -> EngineError {+ EngineError::BadParams { cmd: cmd.into(), msg: msg.into() }+}++/// One recorded action. `steps` is the `[[id, params], …]` shape `file.automate.batch` and+/// droplets already accept.+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]+pub struct Action {+ pub name: String,+ #[serde(default)]+ pub steps: Vec<(String, Value)>,+}++/// On-disk form of [`ActionState::list`] (`actions.json` in the preset store).+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]+pub struct ActionsFile {+ pub version: u32,+ pub actions: Vec<Action>,+}++/// Actions list and the recording / playback flags. Only `list` is persisted.+#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]+#[serde(default)]+pub struct ActionState {+ pub list: Vec<Action>,+ /// Journal length when recording started, and the action index being recorded into.+ #[serde(skip)]+ pub recording: Option<(usize, usize)>,+ /// Nesting depth of `actions.play`. Greater than zero refuses another play.+ #[serde(skip)]+ pub playing: u8,+ /// Bumped whenever `list` changes, so the preset store can skip unchanged writes.+ #[serde(skip)]+ pub rev: u64,+}++impl ActionState {+ pub(crate) fn touch(&mut self) {+ self.rev = self.rev.saturating_add(1);+ }+}++/// A journal entry worth replaying: the command records itself, and it is not an `actions.*`+/// command (those would nest recording and playback).+pub fn replayable(id: &str) -> bool {+ !id.starts_with("actions.") && crate::commands::find(id).is_some_and(|c| c.journal)+}++fn always(_: &Session) -> std::result::Result<(), String> {+ Ok(())+}++fn num(v: &Value) -> Option<i64> {+ v.as_i64().or_else(|| v.as_f64().filter(|f| f.is_finite()).map(|f| f.round() as i64))+}++fn resolve(list: &[Action], p: &Value, cmd: &str) -> Result<usize> {+ let Some(v) = p.get("action") else {+ return Err(bad(cmd, "needs \"action\" (a name or an index)"));+ };+ if let Some(i) = num(v) {+ if i < 0 {+ return Err(bad(cmd, "action index is negative"));+ }+ let Some(i) = usize::try_from(i).ok() else {+ return Err(bad(cmd, "action index is out of range"));+ };+ if i >= list.len() {+ return Err(bad(cmd, format!("no action at index {i}")));+ }+ return Ok(i);+ }+ match v.as_str() {+ Some(name) if !name.is_empty() => list.iter().position(|a| a.name == name).ok_or_else(|| bad(cmd, format!("no action named `{name}`"))),+ Some(_) => Err(bad(cmd, "action name is empty")),+ None => Err(bad(cmd, "\"action\" must be a name or an index")),+ }+}++fn from_step(p: &Value, len: usize) -> Result<usize> {+ let Some(v) = p.get("from") else { return Ok(0) };+ if v.is_null() {+ return Ok(0);+ }+ let Some(i) = num(v) else {+ return Err(bad("actions.play", "\"from\" must be a step index"));+ };+ if i < 0 {+ return Err(bad("actions.play", "\"from\" is negative"));+ }+ let Some(i) = usize::try_from(i).ok() else {+ return Err(bad("actions.play", "\"from\" is out of range"));+ };+ if i > len {+ return Err(bad("actions.play", format!("\"from\" {i} is past the last step ({len})")));+ }+ Ok(i)+}++fn list(s: &mut Session, _p: &Value) -> Result<Value> {+ let actions: Vec<Value> = s.actions.list.iter().map(|a| json!({"name": a.name, "steps": a.steps.len()})).collect();+ let recording = s.actions.recording.and_then(|(_, i)| s.actions.list.get(i).map(|a| a.name.clone()));+ Ok(json!({"actions": actions, "recording": recording}))+}++fn get(s: &mut Session, p: &Value) -> Result<Value> {+ let idx = resolve(&s.actions.list, p, "actions.get")?;+ let action = &s.actions.list[idx];+ let steps: Vec<Value> = action.steps.iter().map(|(id, params)| json!([id, params])).collect();+ Ok(json!({"name": action.name, "steps": steps}))+}++fn record(s: &mut Session, p: &Value) -> Result<Value> {+ if s.actions.recording.is_some() {+ return Err(bad("actions.record", "already recording; stop first"));+ }+ let idx = if p.get("action").is_some() {+ resolve(&s.actions.list, p, "actions.record")?+ } else {+ let name = match p.get("name") {+ None | Some(Value::Null) => format!("Action {}", s.actions.list.len() + 1),+ Some(Value::String(n)) if !n.is_empty() => n.clone(),+ Some(Value::String(_)) => return Err(bad("actions.record", "\"name\" is empty")),+ Some(_) => return Err(bad("actions.record", "\"name\" must be a string")),+ };+ s.actions.list.push(Action { name, steps: Vec::new() });+ s.actions.touch();+ s.actions.list.len() - 1+ };+ s.actions.recording = Some((s.journal.len(), idx));+ let name = s.actions.list.get(idx).map(|a| a.name.clone()).unwrap_or_default();+ Ok(json!({"action": name, "index": idx}))+}++fn stop(s: &mut Session, _p: &Value) -> Result<Value> {+ let Some((from, idx)) = s.actions.recording else {+ return Err(bad("actions.stop", "not recording"));+ };+ if idx >= s.actions.list.len() {+ return Err(bad("actions.stop", "the action being recorded no longer exists"));+ }+ let steps: Vec<(String, Value)> = s.journal.iter().skip(from).filter(|(id, _)| replayable(id)).cloned().collect();+ s.actions.recording = None;+ let action = &mut s.actions.list[idx];+ action.steps.extend(steps);+ let name = action.name.clone();+ let n = action.steps.len();+ s.actions.touch();+ Ok(json!({"action": name, "steps": n}))+}++fn run_recorded(s: &mut Session, steps: &[(String, Value)], from: usize) -> (u64, Option<Value>) {+ let mut ran = 0u64;+ let mut failed = None;+ for (i, (id, params)) in steps.iter().enumerate().skip(from) {+ if let Some(auth) = s.authorize+ && let Err(e) = auth(id, params)+ {+ failed = Some(json!({"step": i, "id": id, "error": e.to_string()}));+ break;+ }+ match s.execute(id, params.clone()) {+ Ok(_) => ran += 1,+ Err(e) => {+ failed = Some(json!({"step": i, "id": id, "error": e.to_string()}));+ break;+ }+ }+ }+ (ran, failed)+}++fn play(s: &mut Session, p: &Value) -> Result<Value> {+ if s.actions.playing > 0 {+ return Err(bad("actions.play", "an action is already playing"));+ }+ let idx = resolve(&s.actions.list, p, "actions.play")?;+ let action = s.actions.list[idx].clone();+ let from = from_step(p, action.steps.len())?;+ s.actions.playing = s.actions.playing.saturating_add(1);+ let (ran, failed) = run_recorded(s, &action.steps, from);+ s.actions.playing = s.actions.playing.saturating_sub(1);+ Ok(match failed {+ Some(f) => json!({"action": action.name, "ran": ran, "failed": f}),+ None => json!({"action": action.name, "ran": ran}),+ })+}++fn delete(s: &mut Session, p: &Value) -> Result<Value> {+ if s.actions.recording.is_some() {+ return Err(bad("actions.delete", "stop recording first"));+ }+ let idx = resolve(&s.actions.list, p, "actions.delete")?;+ let name = s.actions.list.remove(idx).name;+ s.actions.touch();+ Ok(json!({"deleted": name}))+}++pub fn specs() -> Vec<CommandSpec> {+ vec![+ CommandSpec {+ id: "actions.list",+ label: "List Actions",+ menu: &[],+ shortcut: None,+ params: "{} → {actions:[{name, steps:count}], recording:name|null}",+ enabled: always,+ run: list,+ journal: false,+ },+ CommandSpec {+ id: "actions.get",+ label: "Get Action",+ menu: &[],+ shortcut: None,+ params: r##"{"action":name|index} → {name, steps:[[id, params]…]} (the shape file.automate.batch and droplets take)"##,+ enabled: always,+ run: get,+ journal: false,+ },+ CommandSpec {+ id: "actions.record",+ label: "Record Action",+ menu: &[],+ shortcut: None,+ params: r##"{"name":str? (new action, default "Action N")} or {"action":name|index} (append) → {action, index}"##,+ enabled: always,+ run: record,+ journal: false,+ },+ CommandSpec {+ id: "actions.stop",+ label: "Stop Recording",+ menu: &[],+ shortcut: None,+ params: "{} → {action, steps:count} (steps recorded since actions.record, queries and actions.* omitted)",+ enabled: always,+ run: stop,+ journal: false,+ },+ CommandSpec {+ id: "actions.play",+ label: "Play Action",+ menu: &[],+ shortcut: None,+ params: r##"{"action":name|index, "from":step?} → {action, ran, failed?:{step, id, error}}. step and from are 0-based. Stops at the first error (the command still returns ok, with failed set) and leaves one history step per step that ran. Refuses to play while a play is already running. Each step is checked with Session::authorize when one is installed."##,+ enabled: always,+ run: play,+ journal: false,+ },+ CommandSpec {+ id: "actions.delete",+ label: "Delete Action",+ menu: &[],+ shortcut: None,+ params: r##"{"action":name|index} → {deleted:name}. Refused while recording."##,+ enabled: always,+ run: delete,+ journal: false,+ },+ ]+}++#[cfg(test)]+mod tests {+ use super::*;+ use serde_json::json;++ fn pixel(s: &Session, layer: usize, x: i32, y: i32) -> Vec<f32> {+ s.active().unwrap().doc.layers[layer].surface().unwrap().pixel(x, y)+ }++ fn record_red(s: &mut Session, depth: u32) {+ s.execute("file.new", json!({"width": 40, "height": 40, "depth": depth})).unwrap();+ s.execute("actions.record", json!({"name": "Red"})).unwrap();+ s.execute("layer.new.layer", json!({})).unwrap();+ s.execute("select.rect", json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap();+ s.execute("edit.fill", json!({"color": "#ff0000"})).unwrap();+ let _ = s.execute("document.pixel", json!({"x": 1, "y": 1}));+ let _ = s.execute("actions.list", json!({}));+ s.execute("actions.stop", json!({})).unwrap();+ }++ #[test]+ fn record_keeps_only_replayable_steps() {+ let mut s = Session::new();+ record_red(&mut s, 8);+ let got = s.execute("actions.get", json!({"action": "Red"})).unwrap();+ let ids: Vec<&str> = got["steps"].as_array().unwrap().iter().map(|st| st[0].as_str().unwrap()).collect();+ assert_eq!(ids, ["layer.new.layer", "select.rect", "edit.fill"]);+ assert!(s.journal.iter().all(|(id, _)| !id.starts_with("actions.")));+ let listed = s.execute("actions.list", json!({})).unwrap();+ assert_eq!(listed["actions"][0]["steps"], 3);+ assert!(listed["recording"].is_null());+ }++ #[test]+ fn play_on_another_document_matches_pixels_at_each_depth() {+ for depth in [8, 16, 32] {+ let mut s = Session::new();+ record_red(&mut s, depth);+ s.execute("file.new", json!({"width": 40, "height": 40, "depth": depth})).unwrap();+ let before = s.active().unwrap().history.past_len();+ let r = s.execute("actions.play", json!({"action": 0})).unwrap();+ assert!(r.get("failed").is_none(), "depth {depth}: {r}");+ assert_eq!(r["ran"], 3, "depth {depth}");+ assert_eq!(s.active().unwrap().doc.layers.len(), 2, "depth {depth}");+ assert_eq!(s.active().unwrap().history.past_len(), before + 3, "depth {depth}: one history step per played step");+ let px = pixel(&s, 1, 5, 5);+ assert!(px.iter().zip([1.0, 0.0, 0.0, 1.0]).all(|(a, b)| (a - b).abs() < 1.0e-5), "depth {depth}: {px:?}");+ assert_eq!(s.actions.playing, 0);+ }+ }++ #[test]+ fn play_stops_at_the_failing_step_and_reports_it() {+ let mut s = Session::new();+ s.execute("file.new", json!({"width": 16, "height": 16})).unwrap();+ s.execute("actions.record", json!({})).unwrap();+ s.execute("layer.new.layer", json!({"name": "One"})).unwrap();+ s.execute("actions.stop", json!({})).unwrap();+ s.actions.list[0].steps.push(("not.a.command".into(), json!({})));+ s.execute("file.new", json!({"width": 16, "height": 16})).unwrap();+ let r = s.execute("actions.play", json!({"action": "Action 1"})).unwrap();+ assert_eq!(r["ran"], 1);+ assert_eq!(r["failed"]["step"], 1);+ assert_eq!(r["failed"]["id"], "not.a.command");+ assert!(r["failed"]["error"].as_str().unwrap().contains("unknown command"));+ assert_eq!(s.active().unwrap().doc.layers.len(), 2, "the step before the failure is kept");+ assert_eq!(s.actions.playing, 0);+ // A later play still runs.+ assert_eq!(s.execute("actions.play", json!({"action": 0, "from": 1})).unwrap()["ran"], 0);+ }++ #[test]+ fn play_refuses_recursion() {+ let mut s = Session::new();+ s.actions.list.push(Action { name: "Loop".into(), steps: vec![("actions.play".into(), json!({"action": "Loop"}))] });+ let r = s.execute("actions.play", json!({"action": "Loop"})).unwrap();+ assert_eq!(r["ran"], 0);+ assert_eq!(r["failed"]["id"], "actions.play");+ assert!(r["failed"]["error"].as_str().unwrap().contains("already playing"), "{r}");+ assert_eq!(s.actions.playing, 0);+ }++ #[test]+ fn play_checks_each_step_with_the_authorize_hook() {+ fn deny_file(id: &str, _: &Value) -> Result<()> {+ if id.starts_with("file.") { Err(EngineError::Other(format!("automation command `{id}` is disabled"))) } else { Ok(()) }+ }+ let mut s = Session::new();+ s.authorize = Some(deny_file);+ s.actions+ .list+ .push(Action { name: "Open".into(), steps: vec![("file.open".into(), json!({"path": "/etc/passwd"})), ("layer.new.layer".into(), json!({}))] });+ let r = s.execute("actions.play", json!({"action": "Open"})).unwrap();+ assert_eq!(r["ran"], 0);+ assert_eq!(r["failed"]["step"], 0);+ assert_eq!(r["failed"]["id"], "file.open");+ assert!(r["failed"]["error"].as_str().unwrap().contains("disabled"), "{r}");+ assert!(s.documents().is_empty(), "the refused step does not open a document");+ }++ #[test]+ fn append_delete_and_from_step() {+ let mut s = Session::new();+ s.execute("file.new", json!({"width": 8, "height": 8, "background": "white"})).unwrap();+ let started = s.execute("actions.record", json!({"name": "Grow"})).unwrap();+ assert_eq!(started["index"], 0);+ s.execute("layer.new.layer", json!({"name": "One"})).unwrap();+ assert!(s.execute("actions.record", json!({})).is_err(), "already recording");+ assert!(s.execute("actions.delete", json!({"action": 0})).is_err(), "delete while recording");+ let stopped = s.execute("actions.stop", json!({})).unwrap();+ assert_eq!(stopped["steps"], 1);+ s.execute("actions.record", json!({"action": "Grow"})).unwrap();+ s.execute("layer.new.layer", json!({"name": "Two"})).unwrap();+ assert_eq!(s.execute("actions.stop", json!({})).unwrap()["steps"], 2);+ assert!(s.execute("actions.stop", json!({})).is_err(), "not recording");+ let before = s.active().unwrap().doc.layers.len();+ let r = s.execute("actions.play", json!({"action": "Grow", "from": 1})).unwrap();+ assert_eq!(r["ran"], 1);+ assert_eq!(s.active().unwrap().doc.layers.len(), before + 1);+ assert_eq!(s.execute("actions.delete", json!({"action": "Grow"})).unwrap()["deleted"], "Grow");+ assert!(s.actions.list.is_empty());+ assert!(s.execute("actions.get", json!({"action": "Grow"})).is_err());+ }++ #[test]+ fn bad_params_do_not_panic() {+ let mut s = Session::new();+ let junk = [+ Value::Null,+ json!([]),+ json!("x"),+ json!(1),+ json!({"action": true}),+ json!({"action": -1}),+ json!({"action": 99}),+ json!({"action": ""}),+ json!({"name": 1}),+ json!({"name": ""}),+ json!({"from": "start"}),+ json!({"from": -3}),+ json!({"action": "missing", "from": 4}),+ ];+ for id in ["actions.list", "actions.get", "actions.record", "actions.stop", "actions.play", "actions.delete"] {+ for p in &junk {+ let _ = s.execute(id, p.clone());+ }+ }+ assert_eq!(s.actions.playing, 0);+ assert!(crate::commands::command_specs().iter().any(|c| c.id == "actions.play" && !c.journal && c.menu.is_empty()));+ }++ #[cfg(not(target_arch = "wasm32"))]+ #[test]+ fn actions_persist_with_the_preset_store() {+ let dir = std::env::temp_dir().join(format!("pc-actions-{}-persist", std::process::id()));+ let _ = std::fs::remove_dir_all(&dir);+ let mut s = Session::new();+ let warnings = s.attach_preset_store(crate::preset_store::open_dir(&dir));+ assert!(warnings.iter().all(|w| !w.contains("actions")), "{warnings:?}");+ s.execute("file.new", json!({"width": 4, "height": 4})).unwrap();+ s.execute("actions.record", json!({"name": "Kept"})).unwrap();+ s.execute("layer.new.layer", json!({})).unwrap();+ s.execute("actions.stop", json!({})).unwrap();+ drop(s);++ let mut t = Session::new();+ t.attach_preset_store(crate::preset_store::open_dir(&dir));+ let listed = t.execute("actions.list", json!({})).unwrap();+ assert_eq!(listed["actions"][0]["name"], "Kept");+ assert_eq!(listed["actions"][0]["steps"], 1);+ assert_eq!(t.execute("actions.get", json!({"action": "Kept"})).unwrap()["steps"][0][0], "layer.new.layer");++ // An action created before the store finishes loading is kept, and a different one on+ // disk is merged in.+ let mut early = Session::new();+ early.execute("actions.record", json!({"name": "Early"})).unwrap();+ early.execute("actions.stop", json!({})).unwrap();+ early.attach_preset_store(crate::preset_store::open_dir(&dir));+ let names: Vec<String> = early.actions.list.iter().map(|a| a.name.clone()).collect();+ assert!(names.contains(&"Early".into()) && names.contains(&"Kept".into()), "{names:?}");++ std::fs::write(dir.join("actions.json"), b"{").unwrap();+ let mut bad = Session::new();+ let warnings = bad.attach_preset_store(crate::preset_store::open_dir(&dir));+ assert!(warnings.iter().any(|w| w.contains("actions")), "{warnings:?}");+ assert!(bad.actions.list.is_empty());+ let _ = std::fs::remove_dir_all(&dir);+ }+}diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rsindex 8d7758ee1..1478f4a89 100644--- a/crates/engine/src/commands.rs+++ b/crates/engine/src/commands.rs@@ -1005,6 +1005,7 @@ fn build() -> Vec<CommandSpec> {v.extend(crate::group_view_cmds::specs());v.extend(crate::fx_view_cmds::specs());v.extend(crate::mask_view_cmds::specs());+ v.extend(crate::actions_cmds::specs());v}diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rsindex f5ec24cef..08db85647 100644--- a/crates/engine/src/lib.rs+++ b/crates/engine/src/lib.rs@@ -7,6 +7,7 @@#![forbid(unsafe_code)]#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]+pub mod actions_cmds;pub mod adjust_cmds;pub mod adjust_params;pub mod align_cmds;@@ -294,8 +295,14 @@ pub struct Session {/// event log (see `automate_cmds`).pub file_menu: automate_cmds::FileMenuState,/// Persistent brush preset store (desktop only; `None` keeps presets session-only, as in- /// headless and test sessions). See `preset_store`.+ /// headless and test sessions). See `preset_store`. The same store holds the Actions list.pub preset_store: Option<preset_store::PresetStore>,+ /// Window › Actions. The list persists with the preset store when one is attached.+ pub actions: actions_cmds::ActionState,+ /// Per-step gate for `actions.play`. Untrusted sessions (MCP, the control channel) install+ /// the same check a top-level command sees. `None` runs every step, which is what a local+ /// UI and `photocraft-cli run` do.+ pub authorize: Option<fn(&str, &serde_json::Value) -> Result<()>>,/// Background jobs (see [`jobs`]).jobs: jobs::Jobs,}diff --git a/crates/engine/src/preset_store.rs b/crates/engine/src/preset_store.rsindex d3bd3c020..b5c4b5980 100644--- a/crates/engine/src/preset_store.rs+++ b/crates/engine/src/preset_store.rs@@ -24,6 +24,10 @@//! app has no store (localStorage is too small for sampled tips): its brush presets are//! session-only. Gradient presets, including imported `.grd` groups, are small and persist with//! the preferences document (`presets.gradients`).+//!+//! The Actions list (`actions.json`, see [`crate::actions_cmds`]) lives in the same directory.+//! A missing file is an empty list. A corrupt or oversized file is skipped with a warning.+//! Headless and web sessions have no store, so their actions stay in memory.use std::collections::{HashMap, HashSet};use std::io::Read;@@ -47,6 +51,10 @@ pub const MAX_GROUP_BYTES: u64 = 16 << 20;pub const MAX_TIP_BYTES: u64 = 64 << 20;/// Largest index file read.pub const MAX_INDEX_BYTES: u64 = 4 << 20;+/// The Actions list (`actions.json`).+pub const ACTIONS_FILE: &str = "actions.json";+/// Largest Actions file read or written.+pub const MAX_ACTIONS_BYTES: u64 = 16 << 20;/// The whole store never grows beyond this; further groups are skipped with a warning.pub const MAX_STORE_BYTES: u64 = 2 << 30;/// Largest tip side accepted from disk.@@ -390,6 +398,8 @@ pub struct PresetStore {/// Tip hash → file size, for every tip file the store owns.tips: HashMap<String, u64>,index: Option<IndexFile>,+ /// [`crate::actions_cmds::ActionState::rev`] last written (or loaded).+ actions_rev: u64,warnings: Vec<String>,}@@ -404,6 +414,8 @@ pub struct Opened {pub order: Vec<String>,/// Files that were skipped (corrupt, oversized, missing tips).pub warnings: Vec<String>,+ /// Recorded actions (`actions.json`). Empty when the file is missing or unreadable.+ pub actions: Vec<crate::actions_cmds::Action>,}/// Load a store (any thread; the desktop app does this in the background at start).@@ -477,7 +489,8 @@ pub fn open(backend: Box<dyn PresetBackend>) -> Opened {}}- let mut store = PresetStore { backend, synced_rev: None, groups: HashMap::new(), tips: HashMap::new(), index: None, warnings: Vec::new() };+ let actions = load_actions(backend.as_ref(), &mut warnings);+ let mut store = PresetStore { backend, synced_rev: None, groups: HashMap::new(), tips: HashMap::new(), index: None, actions_rev: 0, warnings: Vec::new() };let mut presets = Vec::new();for (file, size, g) in parsed {let mut items = Vec::with_capacity(g.presets.len());@@ -516,7 +529,35 @@ pub fn open(backend: Box<dyn PresetBackend>) -> Opened {let hidden_builtins = index.as_ref().map(|i| i.hidden_builtins.clone()).unwrap_or_default();let order = index.as_ref().map(|i| i.order.clone()).unwrap_or_default();store.index = index;- Opened { store, presets, hidden_builtins, order, warnings }+ Opened { store, presets, hidden_builtins, order, warnings, actions }+}++/// `actions.json`: a missing file is an empty list. Anything else unreadable is a warning.+fn load_actions(backend: &dyn PresetBackend, warnings: &mut Vec<String>) -> Vec<crate::actions_cmds::Action> {+ let bytes = match backend.read(ACTIONS_FILE, MAX_ACTIONS_BYTES) {+ Ok(b) => b,+ Err(e) if missing_file(&e) => return Vec::new(),+ Err(e) => {+ warnings.push(format!("actions: {ACTIONS_FILE} skipped: {e}"));+ return Vec::new();+ }+ };+ match serde_json::from_slice::<crate::actions_cmds::ActionsFile>(&bytes) {+ Ok(file) if file.version == 1 => file.actions,+ Ok(file) => {+ warnings.push(format!("actions: {ACTIONS_FILE} skipped: unsupported version {}", file.version));+ Vec::new()+ }+ Err(e) => {+ warnings.push(format!("actions: {ACTIONS_FILE} skipped: {e}"));+ Vec::new()+ }+ }+}++fn missing_file(err: &str) -> bool {+ let lower = err.to_ascii_lowercase();+ lower.contains("not found") || lower.contains("no such file") || lower.contains("os error 2")}/// Read and decode tips, in parallel on native targets.@@ -689,6 +730,33 @@ impl PresetStore {self.groups.insert(file.to_string(), Synced { presets: items.iter().map(|p| (*p).clone()).collect(), tips: hashes, bytes: bytes.len() as u64 });Ok(())}++ /// Write the Actions list when `rev` differs from the last load or write.+ /// An oversized list is warned once and not retried. An I/O error is warned and retried+ /// on the next command.+ pub fn sync_actions(&mut self, list: &[crate::actions_cmds::Action], rev: u64) {+ if self.actions_rev == rev {+ return;+ }+ let file = crate::actions_cmds::ActionsFile { version: 1, actions: list.to_vec() };+ let bytes = match serde_json::to_vec_pretty(&file) {+ Ok(b) => b,+ Err(e) => {+ self.warnings.push(format!("Couldn't save actions: {e}"));+ self.actions_rev = rev;+ return;+ }+ };+ if bytes.len() as u64 > MAX_ACTIONS_BYTES {+ self.warnings.push(format!("actions: the action list is too large to save ({} MB limit)", MAX_ACTIONS_BYTES >> 20));+ self.actions_rev = rev;+ return;+ }+ match self.backend.write(ACTIONS_FILE, &bytes) {+ Ok(()) => self.actions_rev = rev,+ Err(e) => self.warnings.push(format!("Couldn't save actions: {e}")),+ }+ }}fn builtin_names() -> &'static [String] {@@ -707,7 +775,7 @@ impl Session {/// built-in of the same name; presets created before the store finished loading win), hide/// deleted built-ins, then sync. Returns the load warnings.pub fn attach_preset_store(&mut self, opened: Opened) -> Vec<String> {- let Opened { store, presets, hidden_builtins, order, mut warnings } = opened;+ let Opened { store, presets, hidden_builtins, order, mut warnings, actions: disk } = opened;let lib = &mut self.tools.presets;lib.retain(|p| !(p.builtin && hidden_builtins.iter().any(|h| h.eq_ignore_ascii_case(&p.name))));for p in presets {@@ -723,6 +791,22 @@ impl Session {lib.sort_by_key(|p| pos.get(&p.name.to_lowercase()).copied().unwrap_or(usize::MAX));}self.preset_store = Some(store);+ // In-memory actions (created before the store finished loading) win on name. Disk-only+ // names are appended. An empty session takes the disk list and does not rewrite it.+ if self.actions.list.is_empty() {+ self.actions.list = disk;+ self.actions.rev = 1;+ if let Some(st) = self.preset_store.as_mut() {+ st.actions_rev = 1;+ }+ } else {+ for action in disk {+ if !self.actions.list.iter().any(|have| have.name == action.name) {+ self.actions.list.push(action);+ }+ }+ self.actions.rev = self.actions.rev.saturating_add(1).max(1);+ }self.brush_presets_changed();self.sync_preset_store();if let Some(st) = self.preset_store.as_mut() {@@ -731,14 +815,16 @@ impl Session {warnings}- /// Write pending brush preset changes to the attached store (no-op without one).+ /// Write pending brush preset and Actions changes to the attached store (no-op without one).pub fn sync_preset_store(&mut self) {let rev = self.tools.presets_rev;- if let Some(st) = self.preset_store.as_mut()- && st.synced_rev != Some(rev)- {- st.sync(&self.tools.presets);- st.synced_rev = Some(rev);+ let actions_rev = self.actions.rev;+ if let Some(st) = self.preset_store.as_mut() {+ if st.synced_rev != Some(rev) {+ st.sync(&self.tools.presets);+ st.synced_rev = Some(rev);+ }+ st.sync_actions(&self.actions.list, actions_rev);}}}diff --git a/crates/ui-egui/src/actions.rs b/crates/ui-egui/src/actions.rsindex e883b4a04..63073f4a5 100644--- a/crates/ui-egui/src/actions.rs+++ b/crates/ui-egui/src/actions.rs@@ -1,80 +1,88 @@//! Actions panel: record and replay command sequences.//!-//! Every edit is an engine command appended to `Session::journal`, so recording is just remembering-//! where the journal was when ● was pressed, and ▶ replays those exact commands (strokes, transforms,-//! type edits included) on whatever document is active.+//! The list and the recording flag live on the engine session (`actions.record` / `stop` /+//! `play` / `list` / `get` / `delete`), so the panel, the CLI and MCP share them. This module+//! keeps only which row is selected and which rows are expanded.use egui::{Align2, Color32, Rect, Sense, Stroke, pos2, vec2};use serde::{Deserialize, Serialize};-use serde_json::Value;+use serde_json::{Value, json};++use photocraft_engine::actions_cmds::{self, Action};use crate::PhotocraftApp;use crate::theme::Tokens;-#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]-pub struct Action {- pub name: String,- pub steps: Vec<(String, Value)>,- #[serde(default)]- pub expanded: bool,-}--/// Actions and recording state (persisted with the UI state).+/// Which row is selected and which rows are expanded. The action list itself is+/// [`photocraft_engine::Session::actions`].#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]#[serde(default)]-pub struct Actions {- pub list: Vec<Action>,+pub struct ActionsUi {pub selected: Option<usize>,- /// Journal length when recording started, and the action being recorded into.- pub recording: Option<(usize, usize)>,+ pub expanded: Vec<bool>,}-/// Commands that are queries or UI plumbing, not worth replaying.-fn replayable(id: &str) -> bool {- !matches!(id, "document.pixel" | "document.inspect" | "session.inspect" | "command.list" | "type.info" | "type.fonts" | "edit.undo" | "edit.redo")+fn label_of(id: &str) -> String {+ photocraft_engine::commands::find(id).map(|c| c.label.trim_end_matches('…').to_string()).unwrap_or_else(|| id.to_string())}-pub fn start_recording(app: &mut PhotocraftApp) {- let n = app.ui.actions.list.len();- app.ui.actions.list.push(Action { name: format!("Action {}", n + 1), steps: Vec::new(), expanded: true });- app.ui.actions.selected = Some(n);- app.ui.actions.recording = Some((app.session.journal.len(), n));+/// The selected action, or the first one when nothing is selected.+pub fn selected_action(app: &PhotocraftApp) -> Option<&Action> {+ let list = &app.session.actions.list;+ let idx = app.ui.actions.selected.filter(|i| *i < list.len());+ idx.and_then(|i| list.get(i)).or_else(|| list.first())}-/// Stop recording: move the new journal entries into the action.-pub fn stop_recording(app: &mut PhotocraftApp) {- let Some((from, idx)) = app.ui.actions.recording.take() else { return };- let steps: Vec<(String, Value)> = app.session.journal.iter().skip(from).filter(|(id, _)| replayable(id)).cloned().collect();- if let Some(a) = app.ui.actions.list.get_mut(idx) {- a.steps.extend(steps);- }+/// Steps in the `[[id, params], …]` shape batch and droplets already accept.+pub fn action_steps(action: &Action) -> Vec<Value> {+ action.steps.iter().map(|(id, p)| json!([id, p])).collect()}-/// Replay an action; stops at the first failing step and reports it.-pub fn play(app: &mut PhotocraftApp, idx: usize) -> Result<usize, String> {- let steps = app.ui.actions.list.get(idx).map(|a| a.steps.clone()).ok_or("no such action")?;- for (i, (id, p)) in steps.iter().enumerate() {- app.run(id, p.clone()).map_err(|e| format!("Step {} ({id}) failed: {e}", i + 1))?;+fn begin_recording(app: &mut PhotocraftApp) {+ if app.session.actions.recording.is_some() {+ return;+ }+ let Ok(v) = app.run("actions.record", json!({})) else { return };+ let Some(i) = v.get("index").and_then(Value::as_u64).and_then(|n| usize::try_from(n).ok()) else { return };+ app.ui.actions.selected = Some(i);+ if app.ui.actions.expanded.len() <= i {+ app.ui.actions.expanded.resize(i + 1, false);}- Ok(steps.len())+ app.ui.actions.expanded[i] = true;}-fn label_of(id: &str) -> String {- photocraft_engine::commands::find(id).map(|c| c.label.trim_end_matches('…').to_string()).unwrap_or_else(|| id.to_string())+fn report_play(app: &mut PhotocraftApp, v: &Value) {+ let Some(failed) = v.get("failed").filter(|f| f.is_object()) else {+ let ran = v.get("ran").and_then(Value::as_u64).unwrap_or(0);+ app.ui.status = format!("Played {ran} steps");+ return;+ };+ let step = failed.get("step").and_then(Value::as_u64).unwrap_or(0);+ let id = failed.get("id").and_then(Value::as_str).unwrap_or("");+ let error = failed.get("error").and_then(Value::as_str).unwrap_or("");+ app.ui.status = format!("Step {} ({id}) failed: {error}", step + 1);+ app.ui.status_error = true;}pub fn panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) {let t = Tokens::get(ui.ctx());- let live = app.ui.actions.recording.map(|(from, _)| app.session.journal.len().saturating_sub(from)).unwrap_or(0);+ let recording = app.session.actions.recording;+ let live = recording.map(|(from, _)| app.session.journal.iter().skip(from).filter(|(id, _)| actions_cmds::replayable(id)).count()).unwrap_or(0);+ let rows: Vec<(String, Vec<String>)> =+ app.session.actions.list.iter().map(|a| (a.name.clone(), a.steps.iter().map(|(id, _)| id.clone()).collect())).collect();+ if app.ui.actions.selected.is_some_and(|i| i >= rows.len()) {+ app.ui.actions.selected = None;+ }+ if app.ui.actions.expanded.len() > rows.len() {+ app.ui.actions.expanded.truncate(rows.len());+ }let max_h = (ui.available_height() - 70.0).clamp(80.0, 320.0);let mut play_idx = None;egui::ScrollArea::vertical().id_salt("actions-rows").max_height(max_h).auto_shrink([false, true]).show(ui, |ui| {- if app.ui.actions.list.is_empty() {+ if rows.is_empty() {ui.label(egui::RichText::new(tl!("Record ● a sequence of edits, then play ▶ it on any document.")).color(t.text_faint).size(11.5));}- let n = app.ui.actions.list.len();- for i in 0..n {- let a = app.ui.actions.list[i].clone();+ for (i, (name, steps)) in rows.iter().enumerate() {let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 26.0), Sense::click());let sel = app.ui.actions.selected == Some(i);if sel {@@ -82,22 +90,19 @@ pub fn panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) {} else if resp.hovered() {ui.painter().rect_filled(rect, 0.0, t.hover.gamma_multiply(0.5));}- // Expander triangle.+ let expanded = app.ui.actions.expanded.get(i).copied().unwrap_or(false);let tri = Rect::from_center_size(pos2(rect.left() + 12.0, rect.center().y), vec2(8.0, 8.0));- let pts = if a.expanded {- vec![tri.left_top(), tri.right_top(), tri.center_bottom()]- } else {- vec![tri.left_top(), tri.right_center(), tri.left_bottom()]- };+ let pts =+ if expanded { vec![tri.left_top(), tri.right_top(), tri.center_bottom()] } else { vec![tri.left_top(), tri.right_center(), tri.left_bottom()] };ui.painter().add(egui::Shape::convex_polygon(pts, t.text_dim, Stroke::NONE));crate::icons::paint(ui, Rect::from_center_size(pos2(rect.left() + 30.0, rect.center().y), vec2(16.0, 16.0)), "play", 11.0, t.icon);- let recording_this = app.ui.actions.recording.is_some_and(|(_, r)| r == i);- let steps = a.steps.len() + if recording_this { live } else { 0 };- ui.painter().text(pos2(rect.left() + 44.0, rect.center().y), Align2::LEFT_CENTER, &a.name, egui::FontId::proportional(12.0), t.text);+ let recording_this = recording.is_some_and(|(_, r)| r == i);+ let nsteps = steps.len() + if recording_this { live } else { 0 };+ ui.painter().text(pos2(rect.left() + 44.0, rect.center().y), Align2::LEFT_CENTER, name, egui::FontId::proportional(12.0), t.text);ui.painter().text(pos2(rect.right() - 8.0, rect.center().y),Align2::RIGHT_CENTER,- format!("{steps} steps"),+ format!("{nsteps} steps"),egui::FontId::proportional(11.0),t.text_faint,);@@ -107,83 +112,84 @@ pub fn panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) {if resp.clicked() {app.ui.actions.selected = Some(i);if resp.interact_pointer_pos().is_some_and(|p| p.x < rect.left() + 20.0) {- app.ui.actions.list[i].expanded = !a.expanded;+ if app.ui.actions.expanded.len() <= i {+ app.ui.actions.expanded.resize(i + 1, false);+ }+ app.ui.actions.expanded[i] = !expanded;}}if resp.double_clicked() {play_idx = Some(i);}- if a.expanded {- for (id, _) in &a.steps {+ if expanded {+ for id in steps {let (r, _) = ui.allocate_exact_size(vec2(ui.available_width(), 20.0), Sense::hover());ui.painter().text(pos2(r.left() + 44.0, r.center().y), Align2::LEFT_CENTER, label_of(id), egui::FontId::proportional(11.5), t.text_dim);}}}});- // Footer: stop, record, play, new, delete (Photoshop's order).ui.add_space(4.0);ui.horizontal(|ui| {ui.spacing_mut().item_spacing.x = 2.0;- let recording = app.ui.actions.recording.is_some();- if crate::icons::button(ui, "square", 24.0, false, tl!("Stop playing/recording")).clicked() {- stop_recording(app);+ let recording_now = app.session.actions.recording.is_some();+ if crate::icons::button(ui, "square", 24.0, false, tl!("Stop playing/recording")).clicked() && recording_now {+ let _ = app.run("actions.stop", json!({}));}let (r, rec) = ui.allocate_exact_size(vec2(24.0, 24.0), Sense::click());if rec.hovered() {ui.painter().rect_filled(r, 3.0, t.hover);}- ui.painter().circle_filled(r.center(), 5.5, if recording { Color32::from_rgb(230, 60, 60) } else { t.icon });- if rec.on_hover_text(tl!("Begin recording")).clicked() && !recording {- start_recording(app);+ ui.painter().circle_filled(r.center(), 5.5, if recording_now { Color32::from_rgb(230, 60, 60) } else { t.icon });+ if rec.on_hover_text(tl!("Begin recording")).clicked() && !recording_now {+ begin_recording(app);}if crate::icons::button(ui, "play", 24.0, false, tl!("Play selection")).clicked() {play_idx = app.ui.actions.selected;}- if crate::icons::button(ui, "plus", 24.0, false, tl!("Create new action")).clicked() && !recording {- start_recording(app);+ if crate::icons::button(ui, "plus", 24.0, false, tl!("Create new action")).clicked() && !recording_now {+ begin_recording(app);}if crate::icons::button(ui, "trash", 24.0, false, tl!("Delete")).clicked()- && !recording- && let Some(i) = app.ui.actions.selected.take()- && i < app.ui.actions.list.len()+ && !recording_now+ && let Some(i) = app.ui.actions.selected+ && app.run("actions.delete", json!({"action": i})).is_ok(){- app.ui.actions.list.remove(i);- }- });- if let Some(i) = play_idx {- match play(app, i) {- Ok(n) => app.ui.status = format!("Played {n} steps"),- Err(e) => {- app.ui.status = e;- app.ui.status_error = true;+ if i < app.ui.actions.expanded.len() {+ app.ui.actions.expanded.remove(i);}+ app.ui.actions.selected = None;}+ });+ if let Some(i) = play_idx+ && let Ok(v) = app.run("actions.play", json!({"action": i}))+ {+ report_play(app, &v);}}#[cfg(test)]mod tests {use super::*;- use serde_json::json;#[test]fn record_and_replay_on_another_document() {let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());app.run("file.new", json!({"width": 40, "height": 40})).unwrap();app.sync_views();- start_recording(&mut app);+ app.run("actions.record", json!({})).unwrap();app.run("layer.new.layer", json!({})).unwrap();app.run("select.rect", json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap();app.run("edit.fill", json!({"color": "#ff0000"})).unwrap();let _ = app.run("document.pixel", json!({"x": 1, "y": 1}));- stop_recording(&mut app);- let a = &app.ui.actions.list[0];+ app.run("actions.stop", json!({})).unwrap();+ let a = &app.session.actions.list[0];assert_eq!(a.steps.iter().map(|s| s.0.as_str()).collect::<Vec<_>>(), ["layer.new.layer", "select.rect", "edit.fill"]);- // Replay on a second document.app.run("file.new", json!({"width": 40, "height": 40})).unwrap();app.sync_views();- assert_eq!(play(&mut app, 0).unwrap(), 3);+ let played = app.run("actions.play", json!({"action": 0})).unwrap();+ assert_eq!(played["ran"], 3);+ assert!(played.get("failed").is_none(), "{played}");let d = &app.session.active().unwrap().doc;assert_eq!(d.layers.len(), 2);assert_eq!(d.layers[1].surface().unwrap().pixel(5, 5), vec![1.0, 0.0, 0.0, 1.0]);diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rsindex 5f74cbb5e..56c6d9d84 100644--- a/crates/ui-egui/src/control.rs+++ b/crates/ui-egui/src/control.rs@@ -135,6 +135,16 @@ fn screen_point(app: &PhotocraftApp, x: f64, y: f64) -> [f32; 2] {}pub fn handle(app: &mut PhotocraftApp, ctx: &egui::Context, req: &ControlRequest) -> Outcome {+ let saved = app.session.authorize;+ if let Some(gate) = app.services.automation_authorize {+ app.session.authorize = Some(gate);+ }+ let outcome = dispatch(app, ctx, req);+ app.session.authorize = saved;+ outcome+}++fn dispatch(app: &mut PhotocraftApp, ctx: &egui::Context, req: &ControlRequest) -> Outcome {let p = &req.params;let s = |k: &str| p.get(k).and_then(Value::as_str);let u = |k: &str| p.get(k).and_then(Value::as_u64);@@ -943,4 +953,52 @@ mod tests {assert_eq!(r["result"]["path"], "in/layered.psd", "{r}");assert_eq!(written.borrow().last().map(String::as_str), Some("in/layered.psd"));}++ fn deny_ambient_file(id: &str, _: &serde_json::Value) -> photocraft_engine::Result<()> {+ if id.starts_with("file.") && id != "file.new" {+ Err(photocraft_engine::EngineError::Other(format!("automation command `{id}` is disabled")))+ } else {+ Ok(())+ }+ }++ #[test]+ fn actions_play_checks_each_step_over_control() {+ let services = crate::Services { automation_authorize: Some(deny_ambient_file), ..Default::default() };+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), services);+ app.session.actions.list.push(photocraft_engine::actions_cmds::Action {+ name: "Open".into(),+ steps: vec![("file.open".into(), json!({"path": "/etc/passwd"})), ("layer.new.layer".into(), json!({}))],+ });+ let ctx = egui::Context::default();+ let r = call(&mut app, &ctx, "engine.execute", json!({"command": "actions.play", "params": {"action": "Open"}}));+ assert_eq!(r["ok"], true, "{r}");+ assert_eq!(r["result"]["ran"], 0, "{r}");+ assert_eq!(r["result"]["failed"]["id"], "file.open", "{r}");+ assert!(r["result"]["failed"]["error"].as_str().unwrap_or("").contains("disabled"), "{r}");+ assert!(app.session.documents().is_empty());+ assert!(app.session.authorize.is_none(), "the per-step gate is only installed for the request");+ }++ #[test]+ fn actions_play_checks_each_step_for_synthetic_input() {+ let services = crate::Services { automation_authorize: Some(deny_ambient_file), ..Default::default() };+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), services);+ app.session.actions.list.push(photocraft_engine::actions_cmds::Action {+ name: "Open".into(),+ steps: vec![("file.open".into(), json!({"path": "/etc/passwd"})), ("layer.new.layer".into(), json!({}))],+ });+ app.automation_input = true;+ let r = app.run("actions.play", json!({"action": "Open"})).unwrap();+ assert_eq!(r["ran"], 0, "{r}");+ assert_eq!(r["failed"]["id"], "file.open", "{r}");+ assert!(app.session.authorize.is_none(), "the per-step gate is only installed for the command");++ // A local play (no automation input) still runs recorded steps.+ app.automation_input = false;+ app.session.actions.list[0].steps.remove(0);+ app.session.execute("file.new", json!({"width": 4, "height": 4})).unwrap();+ let r = app.run("actions.play", json!({"action": "Open"})).unwrap();+ assert_eq!(r["ran"], 1, "{r}");+ }}diff --git a/crates/ui-egui/src/file_ui.rs b/crates/ui-egui/src/file_ui.rsindex d00c65f2b..46b091e09 100644--- a/crates/ui-egui/src/file_ui.rs+++ b/crates/ui-egui/src/file_ui.rs@@ -68,12 +68,10 @@ pub fn invoke(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, params: &Vjson!({"units": ["inches", "cm", "pixels"], "mode": ["rgb", "gray", "cmyk", "lab"]}),),"file.automate.createDroplet" => {- let a = &app.ui.actions;- let action = a.selected.and_then(|i| a.list.get(i)).or(a.list.first());- let Some(action) = action else {+ let Some(action) = crate::actions::selected_action(app) else {return Some(Err("record an action in the Actions panel first".into()));};- let steps: Vec<Value> = action.steps.iter().map(|(id, p)| json!([id, p])).collect();+ let steps = crate::actions::action_steps(action);let name = action.name.clone();form(app,diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rsindex 22cb28250..b737c6777 100644--- a/crates/ui-egui/src/lib.rs+++ b/crates/ui-egui/src/lib.rs@@ -232,6 +232,10 @@ pub struct Services {pub automation_read: Option<AutomationReadFn>,pub automation_write: Option<AutomationWriteFn>,pub automation_command: Option<AutomationCommandFn>,+ /// 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<()>>,/// 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.@@ -552,6 +556,19 @@ impl PhotocraftApp {/// Run an engine command, reporting errors in the status bar.pub fn run(&mut self, id: &str, params: Value) -> Result<Value, String> {+ // Automation input also gates every step a command runs on its behalf (`actions.play`).+ let gate = if self.automation_input && self.session.authorize.is_none() { self.services.automation_authorize } else { None };+ if gate.is_some() {+ self.session.authorize = gate;+ }+ let result = self.run_command(id, params);+ if gate.is_some() {+ self.session.authorize = None;+ }+ result+ }++ fn run_command(&mut self, id: &str, params: Value) -> Result<Value, String> {let clip_read = std::mem::take(&mut self.clip_read_for_paste);if self.automation_input&& let Some(authorize) = self.services.automation_command.as_ref()diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rsindex 139a9bcd4..61a8dd8e7 100644--- a/crates/ui-egui/src/state.rs+++ b/crates/ui-egui/src/state.rs@@ -689,9 +689,9 @@ pub struct UiState {/// Layers panel kind filter ("pixel", "adjustment", "type", "shape", "smart"); empty = all.#[serde(default)]pub layer_filter: Vec<String>,- /// Recorded actions (Actions panel).+ /// Actions panel: which row is selected and which are expanded. The list lives on the session.#[serde(default)]- pub actions: crate::actions::Actions,+ pub actions: crate::actions::ActionsUi,/// Layer Comps panel: the selected comp (by comp id).#[serde(default)]pub layer_comp_selected: Option<u32>,diff --git a/crates/ui-egui/src/view_cmds.rs b/crates/ui-egui/src/view_cmds.rsindex b93b77add..e61387d4c 100644--- a/crates/ui-egui/src/view_cmds.rs+++ b/crates/ui-egui/src/view_cmds.rs@@ -918,12 +918,10 @@ fn front(app: &mut PhotocraftApp, id: &str, params: &Value) -> Option<Result<Valjson!({"format": ["jpg", "png", "psd", "tiff"]}),),"file.automate.batch" => {- let a = &app.ui.actions;- let action = a.selected.and_then(|i| a.list.get(i)).or(a.list.first());- let Some(action) = action else {+ let Some(action) = crate::actions::selected_action(app) else {return Some(Err("record an action in the Actions panel first".into()));};- let steps: Vec<Value> = action.steps.iter().map(|(id, p)| json!([id, p])).collect();+ let steps = crate::actions::action_steps(action);let name = action.name.clone();dialog(app,diff --git a/docs/control-protocol.md b/docs/control-protocol.mdindex 0ba58c4ed..2b219b80e 100644--- a/docs/control-protocol.md+++ b/docs/control-protocol.md@@ -80,6 +80,12 @@ store expose and persist the same setting; scripts keep using canonical command| `type.hitTest` | `{"layer":id?,"x":px,"y":px}`: character under a document point. No `layer` picks the topmost visible type layer there. Result `{"layer","index","line","inside"}` || `type.caret` | `{"layer":id?,"index":char}`: caret segment in document pixels, `{"index","line","segment":[[x,y],[x,y]]}` (rotated and vertical type included) || `type.navigate` | `{"layer":id?,"index":char,"move":"wordPrev\|wordNext\|linePrev\|lineNext\|lineStart\|lineEnd\|start\|end","x":px?}`: neighbouring caret. `x` keeps the column across line moves. Result `{"index"}` |+| `actions.list` | `{}` → `{actions:[{name, steps}], recording}` (the name being recorded, or null) |+| `actions.get` | `{"action": name or index}` → `{name, steps:[[id, params], …]}`, the shape `file.automate.batch` and droplets take |+| `actions.record` | `{"name":"Red"}` starts a new action (default name `Action N`). `{"action": name or index}` appends to one that exists |+| `actions.stop` | `{}` → `{action, steps}`. Copies replayable journal entries since `actions.record` (queries and `actions.*` omitted) |+| `actions.play` | `{"action": name or index, "from": step?}`. `from` and `failed.step` are 0-based. Returns `{action, ran, failed?:{step, id, error}}` and still returns ok when a step fails, so a partial run is reported. Leaves one history step per step that ran. Refuses to play while a play is already running. On an untrusted session each step is authorized the same way as a top-level command |+| `actions.delete` | `{"action": name or index}` → `{deleted}`. Refused while recording |UI-level commands (`view.zoomIn`, `window.theme.pro`, `edit.search`, …) are also accepted by `engine.execute` and `ui.menu.invoke`.@@ -138,8 +144,10 @@ User and imported (`.abr`) brush presets live in the config directory's `Presets`.pcbrushes` JSON file per preset group, content-addressed tip bitmaps under `tips/`, and an`index.json` with the group order and deleted built-ins (see `photocraft_engine::preset_store`).The store loads in the background at launch and syncs after every brush preset change; built-ins-are never written. Headless CLI/MCP sessions and the web build keep brush presets for the session-only. Gradient presets (including imported `.grd` groups) persist with the preferences.+are never written. The Actions list is `actions.json` in that same folder and survives a restart.+Headless CLI/MCP sessions and the web build keep brush presets and the action list for the session+only, unless a store is attached. Gradient presets (including imported `.grd` groups) persist with+the preferences.## Snappingdiff --git a/docs/scorecard.md b/docs/scorecard.mdindex 0f327560c..66b3efc3c 100644--- a/docs/scorecard.md+++ b/docs/scorecard.md@@ -11,7 +11,7 @@ Generated by `cargo xtask scorecard` from `perf/budgets.toml`, `perf/baseline.js| [Tools](#tools) | 6 | 13 | 11 | || [Workspace and UI](#workspace-and-ui) | 0 | 5 | 18 | settings that do nothing: 57 of 135 (target 0) || [Type](#type) | 0 | 3 | 6 | |-| [Automation](#automation) | 2 | 2 | 7 | 626 of 626 menu items live (100.0%) |+| [Automation](#automation) | 3 | 2 | 6 | 626 of 626 menu items live (100.0%) || [Reliability](#reliability) | 4 | 1 | 2 | never-crash lints on 27 of 27 crates; panic_hunt present || [Distribution](#distribution) | 4 | 4 | 3 | || [Open bugs](#open-bugs) | 12 | 4 | 16 | |@@ -207,7 +207,7 @@ Menu wiring (`docs/parity.md`): 626 of 626 menu items live (100.0%). This counts| AUTO-1 | Every menu item dispatches a command id (UI, CLI, control channel and MCP share them) | done | | docs/parity.md: all menu items live; menus.rs is_live || AUTO-219-1 | Record actions in a document-independent form (implicit layer, merged type keystrokes) | missing | [#219](https://github.com/storytold/photocraft/issues/219) | actions.rs:47 copies raw journal entries with explicit layer ids || AUTO-219-2 | Actions panel: step and dialog toggles, reorder, delete a step, Stop, sets, .atn import | missing | [#219](https://github.com/storytold/photocraft/issues/219) | Panel deletes whole actions only (actions.rs:146) |-| AUTO-219-3 | actions.record/stop/play/list commands for agents and the CLI | missing | [#219](https://github.com/storytold/photocraft/issues/219) | Recording is UI-only (actions.rs:37-60) |+| AUTO-219-3 | actions.record/stop/play/list commands for agents and the CLI | done | [#219](https://github.com/storytold/photocraft/issues/219) | actions.list/get/record/stop/play/delete in actions_cmds.rs; the panel, CLI and MCP share them. Nested steps pass the session authorize hook. || AUTO-219-4 | Replay tests for crop, filters, selections and styled text on a second document | missing | [#219](https://github.com/storytold/photocraft/issues/219) | One replay test (actions.rs:171: new layer, rect select, fill) || AUTO-219-5 | Batch: subfolders, open documents, naming template, progress/cancel, error log, stop | partial | [#219](https://github.com/storytold/photocraft/issues/219) | file_cmds.rs:590-631 folder/array input, per-file errors; no recursion, template or cancel || AUTO-219-6 | Plug-in ABI v2: panel kind, progress/cancel calls, read other layers, Last Filter repeats | missing | [#219](https://github.com/storytold/photocraft/issues/219) | runtime.rs:15 ABI_VERSION = 1; manifest.rs:18 Kind::Filter only |diff --git a/scorecard/automation.toml b/scorecard/automation.tomlindex 974492ff9..32c28b5b5 100644--- a/scorecard/automation.toml+++ b/scorecard/automation.toml@@ -28,9 +28,9 @@ note = "Panel deletes whole actions only (actions.rs:146)"[[item]]id = "AUTO-219-3"target = "actions.record/stop/play/list commands for agents and the CLI"-status = "missing"+status = "done"issue = 219-note = "Recording is UI-only (actions.rs:37-60)"+note = "actions.list/get/record/stop/play/delete in actions_cmds.rs; the panel, CLI and MCP share them. Nested steps pass the session authorize hook."[[item]]id = "AUTO-219-4"