diff --git a/crates/capri-computer/src/workflows.rs b/crates/capri-computer/src/workflows.rs new file mode 100644 index 0000000..cd2f792 --- /dev/null +++ b/crates/capri-computer/src/workflows.rs @@ -0,0 +1,218 @@ +//! Task workflows: owner-reviewed click/key/text sequences replayed under the +//! computer-control session rules (Escape, indicator, budget, fresh observations). An app is +//! identified by its `.desktop` path. `/workflows/workflows.json` (<= 30, <= 512 KiB). +//! TODO: recording is not implemented (Capri's recorder was a Windows input hook and Wayland +//! has no global hooks); X11 XRecord or an AT-SPI "teach" mode could fill the gap. +use std::collections::HashMap; +use std::path::PathBuf; +use std::sync::Arc; +use std::time::Duration; + +use anyhow::{bail, ensure, Result}; +use serde::{Deserialize, Serialize}; +use serde_json::{json, Value}; + +use crate::apps; +use crate::keys; +use crate::session::ComputerControl; + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct Selector { + pub label: String, + pub role: String, + pub automation_id: String, +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct Step { + pub action: String, + /// Absolute path of the app's `.desktop` entry. + pub executable: String, + pub delay_ms: u64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub selector: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub to: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub button: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub keys: Option>, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub amount: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub text: Option, +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] +pub struct Workflow { + pub id: String, + pub name: String, + pub steps: Vec, +} + +fn selector_ok(s: &Option) -> bool { + s.as_ref().is_some_and(|s| s.label.chars().count() <= 100 && s.role.chars().count() <= 80 && s.automation_id.chars().count() <= 100) +} + +pub fn validate(mut w: Workflow) -> Result { + w.name = w.name.trim().to_string(); + ensure!(!w.name.is_empty() && w.name.chars().count() <= 80 && (1..=120).contains(&w.steps.len()), "Use a workflow name and 1–120 steps."); + for s in &mut w.steps { + ensure!(["click", "drag", "keys", "scroll", "text"].contains(&s.action.as_str()) && s.executable.starts_with('/') && s.executable.ends_with(".desktop") && s.delay_ms <= 3000, "Invalid workflow step."); + if matches!(s.action.as_str(), "click" | "drag" | "text") { + ensure!(selector_ok(&s.selector), "Choose an accessible target for this step."); + } + match s.action.as_str() { + "drag" => ensure!(selector_ok(&s.to), "Choose an accessible drag destination."), + "click" => { + let b = s.button.get_or_insert_with(|| "left".into()); + ensure!(b == "left" || b == "right", "Invalid click button."); + } + "keys" => ensure!(s.keys.as_ref().is_some_and(|k| (1..=4).contains(&k.len()) && k.iter().all(|k| keys::agent_key(k) && k.to_uppercase() == *k)), "Invalid workflow shortcut."), + "scroll" => ensure!(s.amount.is_some_and(|a| a != 0 && a.abs() <= 10), "Invalid scroll step."), + "text" => ensure!(s.text.as_ref().is_some_and(|t| !t.trim().is_empty() && t.chars().count() <= 2000), "Enter text or a {{variable}} for the text step."), + _ => {} + } + } + if !(w.id.len() == 36 && w.id.chars().all(|c| c.is_ascii_hexdigit() || c == '-')) { + w.id = uuid::Uuid::new_v4().to_string(); + } + Ok(w) +} + +/// `{{name}}` substitution; a missing variable is an error. +pub fn substitute(text: &str, vars: &HashMap) -> Result { + let re = regex::Regex::new(r"\{\{(\w{1,40})\}\}").unwrap(); + let mut missing = None; + let out = re.replace_all(text, |c: ®ex::Captures| match vars.get(&c[1]) { + Some(v) => v.clone(), + None => { + missing = Some(c[1].to_string()); + String::new() + } + }); + if let Some(m) = missing { + bail!("The workflow variable {m} is missing."); + } + Ok(out.into_owned()) +} + +pub struct Workflows { + file: PathBuf, + playing: std::sync::atomic::AtomicBool, +} + +impl Workflows { + pub fn new(data_dir: &std::path::Path) -> Self { + Self { file: data_dir.join("workflows/workflows.json"), playing: false.into() } + } + + pub fn list(&self) -> Vec { + capri_core::fsutil::read_regular(&self.file, 512 << 10).ok().flatten().and_then(|b| serde_json::from_slice::>(&b).ok()).unwrap_or_default().into_iter().filter_map(|w| validate(w).ok()).take(30).collect() + } + + pub fn save(&self, w: Workflow) -> Result { + let w = validate(w)?; + let mut all = self.list(); + all.retain(|x| x.id != w.id); + ensure!(all.len() < 30, "Remove a workflow before saving another."); + all.push(w.clone()); + let bytes = serde_json::to_vec_pretty(&all)?; + ensure!(bytes.len() <= 512 << 10, "The workflows file is too large."); + if let Some(d) = self.file.parent() { + std::fs::create_dir_all(d)?; + } + capri_core::fsutil::write_atomic(&self.file, &bytes)?; + Ok(w) + } + + pub fn remove(&self, id: &str) -> Result<()> { + let all: Vec = self.list().into_iter().filter(|w| w.id != id).collect(); + capri_core::fsutil::write_json_atomic(&self.file, &all) + } + + /// `workflow_control list`. + pub fn summary(&self) -> Value { + json!({"ok": true, "workflows": self.list().iter().map(|w| json!({"id": w.id, "name": w.name, "steps": w.steps.len()})).collect::>()}) + } + + pub fn playing(&self) -> bool { + self.playing.load(std::sync::atomic::Ordering::SeqCst) + } + + /// Replays a saved workflow under a synthetic workflow turn. + pub async fn run(&self, control: &Arc, id: &str, vars: &HashMap) -> Result { + ensure!(vars.len() <= 40 && vars.iter().all(|(k, v)| k.len() <= 40 && k.chars().all(|c| c.is_alphanumeric() || c == '_') && v.chars().count() <= 2000), "Invalid workflow variables."); + let w = self.list().into_iter().find(|w| w.id == id).ok_or_else(|| anyhow::anyhow!("Unknown workflow ID. Call list and use an actual ID."))?; + ensure!(!control.active() && !self.playing.swap(true, std::sync::atomic::Ordering::SeqCst), "Wait for the current computer task or stop it with Escape."); + let turn = format!("workflow-{}", uuid::Uuid::new_v4()); + let budget = (3 * w.steps.len() as u32 + 5).min(400); + let result = async { + control.begin(&format!("Replay owner-reviewed workflow: {}", w.name), &turn, budget).await?; + let mut current_app = String::new(); + for step in &w.steps { + let entry = apps::entry_for(&step.executable)?; + if step.executable != current_app { + apps::launch_app(&entry, control.native.windows.as_ref(), None, None).await?; + current_app = step.executable.clone(); + } + tokio::time::sleep(Duration::from_millis(step.delay_ms)).await; + let view = control.observe(false).await?; + let identity = control.native.observe().await?; + ensure!(entry.owns(&identity.window), "A workflow target is missing or ambiguous. No input was sent. Re-record or edit the step."); + let find = |s: &Option| -> Result { + let s = s.as_ref().expect("validated"); + let matches: Vec<&Value> = view["targets"].as_array().into_iter().flatten().filter(|t| t["role"] == s.role && (s.automation_id.is_empty() || t["automationId"] == s.automation_id) && (s.label.is_empty() || t["untrustedLabel"] == s.label)).collect(); + ensure!(matches.len() == 1, "A workflow target is missing or ambiguous. No input was sent. Re-record or edit the step."); + Ok(matches[0]["targetId"].as_str().unwrap_or("").to_string()) + }; + let args = match step.action.as_str() { + "keys" => json!({"action": "press_keys", "keys": step.keys, "holdMs": 60, "observationId": view["observationId"]}), + "scroll" => json!({"action": "scroll", "amount": step.amount, "observationId": view["observationId"]}), + "click" => json!({"action": "click", "targetId": find(&step.selector)?, "button": step.button}), + "drag" => json!({"action": "drag", "targetId": find(&step.selector)?, "toTargetId": find(&step.to)?}), + _ => json!({"action": "enter_text", "targetId": find(&step.selector)?, "text": substitute(step.text.as_deref().unwrap_or(""), vars)?, "mode": "replace"}), + }; + control.input(&args).await?; + } + control.observe(false).await?; + anyhow::Ok(json!({"ok": true, "steps": w.steps.len(), "confirmation": "Executed the recorded steps. Check the final application result."})) + } + .await; + control.stop(false).await; + self.playing.store(false, std::sync::atomic::Ordering::SeqCst); + result + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn step(action: &str) -> Step { + Step { action: action.into(), executable: "/usr/share/applications/org.kde.kate.desktop".into(), delay_ms: 100, selector: Some(Selector { label: "Title".into(), role: "ControlType.Edit".into(), automation_id: String::new() }), to: None, button: None, keys: None, amount: None, text: Some("{{title}}".into()) } + } + + #[test] + fn validation_storage_and_variables() { + let w = validate(Workflow { id: "x".into(), name: " Rename ".into(), steps: vec![step("text"), step("click")] }).unwrap(); + assert_eq!((w.name.as_str(), w.id.len(), w.steps[1].button.as_deref()), ("Rename", 36, Some("left"))); + let mut bad = step("keys"); + bad.keys = Some(vec!["ESCAPE".into()]); + assert!(validate(Workflow { id: String::new(), name: "a".into(), steps: vec![bad] }).is_err(), "Escape is reserved"); + let mut exe = step("text"); + exe.executable = "C:\\notepad.exe".into(); + assert!(validate(Workflow { id: String::new(), name: "a".into(), steps: vec![exe] }).is_err()); + let vars = HashMap::from([("title".to_string(), "Draft".to_string())]); + assert_eq!(substitute("New {{title}}", &vars).unwrap(), "New Draft"); + assert!(substitute("{{missing}}", &vars).is_err()); + let dir = tempfile::tempdir().unwrap(); + let store = Workflows::new(dir.path()); + let saved = store.save(w).unwrap(); + assert_eq!(store.summary()["workflows"][0]["steps"], 2); + store.remove(&saved.id).unwrap(); + assert!(store.list().is_empty()); + } +}