Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

feat(automation): add cap-automation crate with rule engine

Richie McIlroy3a67c782664d
diff --git a/crates/automation/Cargo.toml b/crates/automation/Cargo.toml
new file mode 100644
index 000000000..98b9500ce
--- /dev/null
+++ b/crates/automation/Cargo.toml
@@ -0,0 +1,21 @@
+[package]
+name = "cap-automation"
+version = "0.1.0"
+edition = "2024"
+
+[dependencies]
+cap-project = { path = "../project" }
+
+serde = { workspace = true }
+serde_json.workspace = true
+specta.workspace = true
+uuid = { version = "1.18.1", features = ["v4"] }
+tracing.workspace = true
+thiserror.workspace = true
+tokio.workspace = true
+
+[dev-dependencies]
+tokio = { workspace = true, features = ["test-util"] }
+
+[lints]
+workspace = true
diff --git a/crates/automation/src/lib.rs b/crates/automation/src/lib.rs
new file mode 100644
index 000000000..763ec0b99
--- /dev/null
+++ b/crates/automation/src/lib.rs
@@ -0,0 +1,456 @@
+mod types;
+
+pub use types::*;
+
+use std::path::PathBuf;
+use tracing::{info, warn};
+
+#[derive(Debug)]
+pub struct TriggerContext {
+ pub project_path: Option<PathBuf>,
+ pub image_path: Option<PathBuf>,
+ pub output_path: Option<PathBuf>,
+ pub capture_target: Option<CaptureTargetKind>,
+ pub recording_mode: Option<AutomationRecordingMode>,
+ pub duration_secs: Option<f64>,
+ pub share_link: Option<String>,
+ pub share_id: Option<String>,
+ pub organization_id: Option<String>,
+ pub window_title: Option<String>,
+}
+
+impl TriggerContext {
+ pub fn new() -> Self {
+ Self {
+ project_path: None,
+ image_path: None,
+ output_path: None,
+ capture_target: None,
+ recording_mode: None,
+ duration_secs: None,
+ share_link: None,
+ share_id: None,
+ organization_id: None,
+ window_title: None,
+ }
+ }
+
+ pub fn with_project_path(mut self, path: PathBuf) -> Self {
+ self.project_path = Some(path);
+ self
+ }
+
+ pub fn with_image_path(mut self, path: PathBuf) -> Self {
+ self.image_path = Some(path);
+ self
+ }
+
+ pub fn with_output_path(mut self, path: PathBuf) -> Self {
+ self.output_path = Some(path);
+ self
+ }
+
+ pub fn with_capture_target(mut self, target: CaptureTargetKind) -> Self {
+ self.capture_target = Some(target);
+ self
+ }
+
+ pub fn with_recording_mode(mut self, mode: AutomationRecordingMode) -> Self {
+ self.recording_mode = Some(mode);
+ self
+ }
+
+ pub fn with_duration(mut self, secs: f64) -> Self {
+ self.duration_secs = Some(secs);
+ self
+ }
+
+ pub fn with_share_link(mut self, link: String) -> Self {
+ self.share_link = Some(link);
+ self
+ }
+
+ pub fn with_share_id(mut self, id: String) -> Self {
+ self.share_id = Some(id);
+ self
+ }
+
+ pub fn with_organization_id(mut self, id: String) -> Self {
+ self.organization_id = Some(id);
+ self
+ }
+
+ pub fn with_window_title(mut self, title: String) -> Self {
+ self.window_title = Some(title);
+ self
+ }
+}
+
+impl Default for TriggerContext {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
+pub enum Capability {
+ CopyToClipboard,
+ SaveToLocation,
+ Export,
+ Upload,
+ RevealInFileManager,
+ OpenFile,
+ RunCommand,
+ Webhook,
+ RecognizeText,
+ Notify,
+ OpenEditor,
+ ApplyPreset,
+ DeleteLocalFiles,
+}
+
+impl Action {
+ /// The host capability an action needs to run, or `None` for control-only actions that are
+ /// always a no-op in the engine (`SkipEditor`). Returning `None` keeps such actions from being
+ /// reported as "unsupported" on hosts that lack an editor (e.g. the CLI).
+ pub fn required_capability(&self) -> Option<Capability> {
+ Some(match self {
+ Action::CopyToClipboard { .. } => Capability::CopyToClipboard,
+ Action::SaveToLocation { .. } => Capability::SaveToLocation,
+ Action::Export { .. } => Capability::Export,
+ Action::Upload { .. } => Capability::Upload,
+ Action::RevealInFileManager => Capability::RevealInFileManager,
+ Action::OpenFile => Capability::OpenFile,
+ Action::RunCommand { .. } => Capability::RunCommand,
+ Action::Webhook { .. } => Capability::Webhook,
+ Action::RecognizeTextToClipboard => Capability::RecognizeText,
+ Action::Notify { .. } => Capability::Notify,
+ Action::OpenEditor => Capability::OpenEditor,
+ Action::SkipEditor => return None,
+ Action::ApplyPreset { .. } => Capability::ApplyPreset,
+ Action::DeleteLocalFiles => Capability::DeleteLocalFiles,
+ })
+ }
+}
+
+pub fn evaluate(
+ store: &AutomationsStore,
+ trigger: &Trigger,
+ ctx: &TriggerContext,
+) -> Vec<(String, Vec<Action>)> {
+ let mut matched = Vec::new();
+ for rule in &store.rules {
+ if !rule.enabled {
+ continue;
+ }
+ if rule.trigger != *trigger {
+ continue;
+ }
+ if rule.conditions.is_empty() || check_conditions(&rule.conditions, rule.match_mode, ctx) {
+ matched.push((rule.id.clone(), rule.actions.clone()));
+ }
+ }
+ matched
+}
+
+fn check_conditions(conditions: &[Condition], mode: MatchMode, ctx: &TriggerContext) -> bool {
+ match mode {
+ MatchMode::All => conditions.iter().all(|c| evaluate_condition(c, ctx)),
+ MatchMode::Any => conditions.iter().any(|c| evaluate_condition(c, ctx)),
+ }
+}
+
+fn evaluate_condition(condition: &Condition, ctx: &TriggerContext) -> bool {
+ match condition {
+ Condition::CaptureTargetIs { target } => ctx.capture_target.as_ref() == Some(target),
+ Condition::RecordingModeIs { mode } => ctx.recording_mode.as_ref() == Some(mode),
+ Condition::DurationAtLeast { secs } => ctx.duration_secs.is_some_and(|d| d >= *secs),
+ Condition::DurationAtMost { secs } => ctx.duration_secs.is_some_and(|d| d <= *secs),
+ Condition::WindowTitleContains { pattern } => ctx
+ .window_title
+ .as_ref()
+ .is_some_and(|t| t.to_lowercase().contains(&pattern.to_lowercase())),
+ Condition::OrganizationIs { id } => ctx.organization_id.as_ref() == Some(id),
+ }
+}
+
+pub trait AutomationHost: Send + Sync {
+ fn capabilities(&self) -> &[Capability];
+
+ fn copy_to_clipboard(
+ &self,
+ ctx: &TriggerContext,
+ source: &ClipboardSource,
+ ) -> impl std::future::Future<Output = Result<(), String>> + Send;
+
+ fn save_to_location(
+ &self,
+ ctx: &TriggerContext,
+ dir: &str,
+ filename_template: Option<&str>,
+ ) -> impl std::future::Future<Output = Result<(), String>> + Send;
+
+ fn export(
+ &self,
+ ctx: &TriggerContext,
+ profile: &ExportProfile,
+ destination: &ExportDestination,
+ ) -> impl std::future::Future<Output = Result<(), String>> + Send;
+
+ fn upload(
+ &self,
+ ctx: &TriggerContext,
+ organization_id: Option<&str>,
+ copy_link: bool,
+ open_in_browser: bool,
+ ) -> impl std::future::Future<Output = Result<(), String>> + Send;
+
+ fn reveal_in_file_manager(
+ &self,
+ ctx: &TriggerContext,
+ ) -> impl std::future::Future<Output = Result<(), String>> + Send;
+
+ fn open_file(
+ &self,
+ ctx: &TriggerContext,
+ ) -> impl std::future::Future<Output = Result<(), String>> + Send;
+
+ fn run_command(
+ &self,
+ ctx: &TriggerContext,
+ program: &str,
+ args: &[String],
+ cwd: Option<&str>,
+ env: &std::collections::HashMap<String, String>,
+ use_shell: bool,
+ ) -> impl std::future::Future<Output = Result<(), String>> + Send;
+
+ fn webhook(
+ &self,
+ ctx: &TriggerContext,
+ url: &str,
+ method: &str,
+ headers: &std::collections::HashMap<String, String>,
+ body_template: Option<&str>,
+ ) -> impl std::future::Future<Output = Result<(), String>> + Send;
+
+ fn recognize_text_to_clipboard(
+ &self,
+ ctx: &TriggerContext,
+ ) -> impl std::future::Future<Output = Result<(), String>> + Send;
+
+ fn notify(
+ &self,
+ ctx: &TriggerContext,
+ title_template: &str,
+ body_template: &str,
+ ) -> impl std::future::Future<Output = Result<(), String>> + Send;
+
+ fn open_editor(
+ &self,
+ ctx: &TriggerContext,
+ ) -> impl std::future::Future<Output = Result<(), String>> + Send;
+
+ fn apply_preset(
+ &self,
+ ctx: &TriggerContext,
+ name: &str,
+ ) -> impl std::future::Future<Output = Result<(), String>> + Send;
+
+ fn delete_local_files(
+ &self,
+ ctx: &TriggerContext,
+ ) -> impl std::future::Future<Output = Result<(), String>> + Send;
+}
+
+pub struct RunResult {
+ pub rule_id: String,
+ pub action_results: Vec<ActionResult>,
+}
+
+pub struct ActionResult {
+ pub action: Action,
+ pub success: bool,
+ pub error: Option<String>,
+}
+
+pub fn has_skip_editor(store: &AutomationsStore, trigger: &Trigger, ctx: &TriggerContext) -> bool {
+ let matched = evaluate(store, trigger, ctx);
+ matched
+ .iter()
+ .any(|(_, actions)| actions.iter().any(|a| matches!(a, Action::SkipEditor)))
+}
+
+pub fn has_open_editor(store: &AutomationsStore, trigger: &Trigger, ctx: &TriggerContext) -> bool {
+ let matched = evaluate(store, trigger, ctx);
+ matched
+ .iter()
+ .any(|(_, actions)| actions.iter().any(|a| matches!(a, Action::OpenEditor)))
+}
+
+pub async fn run<H: AutomationHost>(
+ host: &H,
+ store: &AutomationsStore,
+ trigger: &Trigger,
+ ctx: &TriggerContext,
+) -> Vec<RunResult> {
+ let matched = evaluate(store, trigger, ctx);
+ let caps = host.capabilities();
+ let mut results = Vec::new();
+
+ for (rule_id, actions) in matched {
+ info!(rule_id = %rule_id, trigger = ?trigger, "Running automation rule");
+ let mut action_results = Vec::new();
+
+ for action in &actions {
+ if let Some(cap) = action.required_capability()
+ && !caps.contains(&cap)
+ {
+ warn!(
+ rule_id = %rule_id,
+ action = ?action,
+ capability = ?cap,
+ "Skipping action: host does not support required capability"
+ );
+ action_results.push(ActionResult {
+ action: action.clone(),
+ success: false,
+ error: Some(format!("Unsupported capability: {cap:?}")),
+ });
+ continue;
+ }
+
+ let result = execute_action(host, action, ctx).await;
+ let (success, error) = match result {
+ Ok(()) => (true, None),
+ Err(e) => {
+ warn!(
+ rule_id = %rule_id,
+ action = ?action,
+ error = %e,
+ "Automation action failed"
+ );
+ (false, Some(e))
+ }
+ };
+ action_results.push(ActionResult {
+ action: action.clone(),
+ success,
+ error,
+ });
+ }
+
+ results.push(RunResult {
+ rule_id,
+ action_results,
+ });
+ }
+
+ results
+}
+
+async fn execute_action<H: AutomationHost>(
+ host: &H,
+ action: &Action,
+ ctx: &TriggerContext,
+) -> Result<(), String> {
+ match action {
+ Action::CopyToClipboard { source } => host.copy_to_clipboard(ctx, source).await,
+ Action::SaveToLocation {
+ dir,
+ filename_template,
+ } => {
+ host.save_to_location(ctx, dir, filename_template.as_deref())
+ .await
+ }
+ Action::Export {
+ profile,
+ destination,
+ } => host.export(ctx, profile, destination).await,
+ Action::Upload {
+ organization_id,
+ copy_link,
+ open_in_browser,
+ } => {
+ host.upload(
+ ctx,
+ organization_id.as_deref(),
+ *copy_link,
+ *open_in_browser,
+ )
+ .await
+ }
+ Action::RevealInFileManager => host.reveal_in_file_manager(ctx).await,
+ Action::OpenFile => host.open_file(ctx).await,
+ Action::RunCommand {
+ program,
+ args,
+ cwd,
+ env,
+ use_shell,
+ } => {
+ host.run_command(ctx, program, args, cwd.as_deref(), env, *use_shell)
+ .await
+ }
+ Action::Webhook {
+ url,
+ method,
+ headers,
+ body_template,
+ } => {
+ host.webhook(ctx, url, method, headers, body_template.as_deref())
+ .await
+ }
+ Action::RecognizeTextToClipboard => host.recognize_text_to_clipboard(ctx).await,
+ Action::Notify {
+ title_template,
+ body_template,
+ } => host.notify(ctx, title_template, body_template).await,
+ Action::OpenEditor => host.open_editor(ctx).await,
+ Action::SkipEditor => Ok(()),
+ Action::ApplyPreset { name } => host.apply_preset(ctx, name).await,
+ Action::DeleteLocalFiles => host.delete_local_files(ctx).await,
+ }
+}
+
+pub fn load_store_from_json(value: &serde_json::Value) -> Option<AutomationsStore> {
+ value
+ .get("automations")
+ .and_then(|v| serde_json::from_value(v.clone()).ok())
+}
+
+/// Build a single shell command line from a program and its arguments, quoting each token so that
+/// arguments containing spaces or shell metacharacters survive as written instead of being re-split
+/// by the shell. Used by hosts running `RunCommand { use_shell: true }`.
+pub fn shell_command_line(program: &str, args: &[String]) -> String {
+ std::iter::once(program)
+ .chain(args.iter().map(String::as_str))
+ .map(quote_shell_arg)
+ .collect::<Vec<_>>()
+ .join(" ")
+}
+
+fn is_shell_safe_byte(b: u8) -> bool {
+ b.is_ascii_alphanumeric() || b"-_./:=@%+,".contains(&b)
+}
+
+#[cfg(not(target_os = "windows"))]
+fn quote_shell_arg(arg: &str) -> String {
+ if !arg.is_empty() && arg.bytes().all(is_shell_safe_byte) {
+ arg.to_string()
+ } else {
+ format!("'{}'", arg.replace('\'', "'\\''"))
+ }
+}
+
+#[cfg(target_os = "windows")]
+fn quote_shell_arg(arg: &str) -> String {
+ if !arg.is_empty() && arg.bytes().all(is_shell_safe_byte) {
+ arg.to_string()
+ } else {
+ format!("\"{}\"", arg.replace('"', "\"\""))
+ }
+}
+
+#[cfg(test)]
+mod tests;
diff --git a/crates/automation/src/tests.rs b/crates/automation/src/tests.rs
new file mode 100644
index 000000000..95f8e2d8e
--- /dev/null
+++ b/crates/automation/src/tests.rs
@@ -0,0 +1,798 @@
+use super::*;
+use std::collections::HashMap;
+use std::sync::Mutex;
+
+struct MockHost {
+ caps: Vec<Capability>,
+ actions_run: Mutex<Vec<String>>,
+}
+
+impl MockHost {
+ fn new(caps: Vec<Capability>) -> Self {
+ Self {
+ caps,
+ actions_run: Mutex::new(Vec::new()),
+ }
+ }
+
+ fn actions_run(&self) -> Vec<String> {
+ self.actions_run.lock().unwrap().clone()
+ }
+
+ fn record(&self, name: &str) {
+ self.actions_run.lock().unwrap().push(name.to_string());
+ }
+}
+
+impl AutomationHost for MockHost {
+ fn capabilities(&self) -> &[Capability] {
+ &self.caps
+ }
+
+ async fn copy_to_clipboard(
+ &self,
+ _ctx: &TriggerContext,
+ source: &ClipboardSource,
+ ) -> Result<(), String> {
+ self.record(&format!("copy_to_clipboard:{source:?}"));
+ Ok(())
+ }
+
+ async fn save_to_location(
+ &self,
+ _ctx: &TriggerContext,
+ dir: &str,
+ tmpl: Option<&str>,
+ ) -> Result<(), String> {
+ self.record(&format!("save_to_location:{dir}:{tmpl:?}"));
+ Ok(())
+ }
+
+ async fn export(
+ &self,
+ _ctx: &TriggerContext,
+ _profile: &ExportProfile,
+ _dest: &ExportDestination,
+ ) -> Result<(), String> {
+ self.record("export");
+ Ok(())
+ }
+
+ async fn upload(
+ &self,
+ _ctx: &TriggerContext,
+ _org: Option<&str>,
+ _copy: bool,
+ _open: bool,
+ ) -> Result<(), String> {
+ self.record("upload");
+ Ok(())
+ }
+
+ async fn reveal_in_file_manager(&self, _ctx: &TriggerContext) -> Result<(), String> {
+ self.record("reveal");
+ Ok(())
+ }
+
+ async fn open_file(&self, _ctx: &TriggerContext) -> Result<(), String> {
+ self.record("open_file");
+ Ok(())
+ }
+
+ async fn run_command(
+ &self,
+ _ctx: &TriggerContext,
+ prog: &str,
+ _args: &[String],
+ _cwd: Option<&str>,
+ _env: &HashMap<String, String>,
+ _shell: bool,
+ ) -> Result<(), String> {
+ self.record(&format!("run_command:{prog}"));
+ Ok(())
+ }
+
+ async fn webhook(
+ &self,
+ _ctx: &TriggerContext,
+ url: &str,
+ _method: &str,
+ _headers: &HashMap<String, String>,
+ _body: Option<&str>,
+ ) -> Result<(), String> {
+ self.record(&format!("webhook:{url}"));
+ Ok(())
+ }
+
+ async fn recognize_text_to_clipboard(&self, _ctx: &TriggerContext) -> Result<(), String> {
+ self.record("ocr");
+ Ok(())
+ }
+
+ async fn notify(&self, _ctx: &TriggerContext, title: &str, body: &str) -> Result<(), String> {
+ self.record(&format!("notify:{title}:{body}"));
+ Ok(())
+ }
+
+ async fn open_editor(&self, _ctx: &TriggerContext) -> Result<(), String> {
+ self.record("open_editor");
+ Ok(())
+ }
+
+ async fn apply_preset(&self, _ctx: &TriggerContext, name: &str) -> Result<(), String> {
+ self.record(&format!("apply_preset:{name}"));
+ Ok(())
+ }
+
+ async fn delete_local_files(&self, _ctx: &TriggerContext) -> Result<(), String> {
+ self.record("delete_local_files");
+ Ok(())
+ }
+}
+
+fn screenshot_copy_rule() -> AutomationRule {
+ AutomationRule {
+ id: "rule-1".to_string(),
+ name: "Auto-copy screenshot".to_string(),
+ enabled: true,
+ trigger: Trigger::ScreenshotTaken,
+ match_mode: MatchMode::All,
+ conditions: vec![],
+ actions: vec![
+ Action::CopyToClipboard {
+ source: ClipboardSource::Raw,
+ },
+ Action::Notify {
+ title_template: "Screenshot".to_string(),
+ body_template: "Copied to clipboard".to_string(),
+ },
+ ],
+ }
+}
+
+fn studio_export_rule() -> AutomationRule {
+ AutomationRule {
+ id: "rule-2".to_string(),
+ name: "Auto-export studio".to_string(),
+ enabled: true,
+ trigger: Trigger::StudioRecordingFinished,
+ match_mode: MatchMode::All,
+ conditions: vec![Condition::DurationAtLeast { secs: 5.0 }],
+ actions: vec![Action::Export {
+ profile: ExportProfile {
+ format: ExportFormat::Mp4,
+ fps: 60,
+ resolution_base: cap_project::XY { x: 1920, y: 1080 },
+ compression: Some(AutomationExportCompression::Web),
+ preset_name: None,
+ },
+ destination: ExportDestination::ProjectFolder,
+ }],
+ }
+}
+
+#[test]
+fn evaluate_matches_trigger_and_returns_actions() {
+ let store = AutomationsStore {
+ version: 1,
+ rules: vec![screenshot_copy_rule(), studio_export_rule()],
+ };
+
+ let matched = evaluate(&store, &Trigger::ScreenshotTaken, &TriggerContext::new());
+ assert_eq!(matched.len(), 1);
+ assert_eq!(matched[0].0, "rule-1");
+ assert_eq!(matched[0].1.len(), 2);
+}
+
+#[test]
+fn evaluate_skips_disabled_rules() {
+ let mut rule = screenshot_copy_rule();
+ rule.enabled = false;
+ let store = AutomationsStore {
+ version: 1,
+ rules: vec![rule],
+ };
+
+ let matched = evaluate(&store, &Trigger::ScreenshotTaken, &TriggerContext::new());
+ assert!(matched.is_empty());
+}
+
+#[test]
+fn evaluate_skips_wrong_trigger() {
+ let store = AutomationsStore {
+ version: 1,
+ rules: vec![screenshot_copy_rule()],
+ };
+
+ let matched = evaluate(
+ &store,
+ &Trigger::StudioRecordingFinished,
+ &TriggerContext::new(),
+ );
+ assert!(matched.is_empty());
+}
+
+#[test]
+fn condition_duration_at_least() {
+ let store = AutomationsStore {
+ version: 1,
+ rules: vec![studio_export_rule()],
+ };
+
+ let short_ctx = TriggerContext::new().with_duration(3.0);
+ let long_ctx = TriggerContext::new().with_duration(10.0);
+
+ let matched_short = evaluate(&store, &Trigger::StudioRecordingFinished, &short_ctx);
+ assert!(matched_short.is_empty());
+
+ let matched_long = evaluate(&store, &Trigger::StudioRecordingFinished, &long_ctx);
+ assert_eq!(matched_long.len(), 1);
+}
+
+#[test]
+fn condition_capture_target() {
+ let rule = AutomationRule {
+ id: "rule-target".to_string(),
+ name: "Window only".to_string(),
+ enabled: true,
+ trigger: Trigger::ScreenshotTaken,
+ match_mode: MatchMode::All,
+ conditions: vec![Condition::CaptureTargetIs {
+ target: CaptureTargetKind::Window,
+ }],
+ actions: vec![Action::CopyToClipboard {
+ source: ClipboardSource::Raw,
+ }],
+ };
+
+ let store = AutomationsStore {
+ version: 1,
+ rules: vec![rule],
+ };
+
+ let display_ctx = TriggerContext::new().with_capture_target(CaptureTargetKind::Display);
+ let window_ctx = TriggerContext::new().with_capture_target(CaptureTargetKind::Window);
+
+ assert!(evaluate(&store, &Trigger::ScreenshotTaken, &display_ctx).is_empty());
+ assert_eq!(
+ evaluate(&store, &Trigger::ScreenshotTaken, &window_ctx).len(),
+ 1
+ );
+}
+
+#[test]
+fn condition_window_title_contains() {
+ let rule = AutomationRule {
+ id: "rule-title".to_string(),
+ name: "Slack screenshots".to_string(),
+ enabled: true,
+ trigger: Trigger::ScreenshotTaken,
+ match_mode: MatchMode::All,
+ conditions: vec![Condition::WindowTitleContains {
+ pattern: "slack".to_string(),
+ }],
+ actions: vec![Action::CopyToClipboard {
+ source: ClipboardSource::Raw,
+ }],
+ };
+
+ let store = AutomationsStore {
+ version: 1,
+ rules: vec![rule],
+ };
+
+ let no_title = TriggerContext::new();
+ let slack_ctx = TriggerContext::new().with_window_title("Slack - #general".to_string());
+ let vscode_ctx = TriggerContext::new().with_window_title("VS Code".to_string());
+
+ assert!(evaluate(&store, &Trigger::ScreenshotTaken, &no_title).is_empty());
+ assert_eq!(
+ evaluate(&store, &Trigger::ScreenshotTaken, &slack_ctx).len(),
+ 1
+ );
+ assert!(evaluate(&store, &Trigger::ScreenshotTaken, &vscode_ctx).is_empty());
+}
+
+#[test]
+fn match_mode_any_matches_on_first_true() {
+ let rule = AutomationRule {
+ id: "rule-any".to_string(),
+ name: "Display or window".to_string(),
+ enabled: true,
+ trigger: Trigger::ScreenshotTaken,
+ match_mode: MatchMode::Any,
+ conditions: vec![
+ Condition::CaptureTargetIs {
+ target: CaptureTargetKind::Display,
+ },
+ Condition::CaptureTargetIs {
+ target: CaptureTargetKind::Window,
+ },
+ ],
+ actions: vec![Action::CopyToClipboard {
+ source: ClipboardSource::Raw,
+ }],
+ };
+
+ let store = AutomationsStore {
+ version: 1,
+ rules: vec![rule],
+ };
+
+ let area_ctx = TriggerContext::new().with_capture_target(CaptureTargetKind::Area);
+ let display_ctx = TriggerContext::new().with_capture_target(CaptureTargetKind::Display);
+
+ assert!(evaluate(&store, &Trigger::ScreenshotTaken, &area_ctx).is_empty());
+ assert_eq!(
+ evaluate(&store, &Trigger::ScreenshotTaken, &display_ctx).len(),
+ 1
+ );
+}
+
+#[test]
+fn has_skip_editor_detects_skip_action() {
+ let rule = AutomationRule {
+ id: "headless".to_string(),
+ name: "Headless screenshot".to_string(),
+ enabled: true,
+ trigger: Trigger::ScreenshotTaken,
+ match_mode: MatchMode::All,
+ conditions: vec![],
+ actions: vec![
+ Action::CopyToClipboard {
+ source: ClipboardSource::Raw,
+ },
+ Action::SkipEditor,
+ ],
+ };
+
+ let store = AutomationsStore {
+ version: 1,
+ rules: vec![rule],
+ };
+
+ assert!(has_skip_editor(
+ &store,
+ &Trigger::ScreenshotTaken,
+ &TriggerContext::new()
+ ));
+ assert!(!has_skip_editor(
+ &store,
+ &Trigger::StudioRecordingFinished,
+ &TriggerContext::new()
+ ));
+}
+
+#[tokio::test]
+async fn run_executes_actions_in_order() {
+ let host = MockHost::new(vec![Capability::CopyToClipboard, Capability::Notify]);
+
+ let store = AutomationsStore {
+ version: 1,
+ rules: vec![screenshot_copy_rule()],
+ };
+
+ let results = run(
+ &host,
+ &store,
+ &Trigger::ScreenshotTaken,
+ &TriggerContext::new(),
+ )
+ .await;
+
+ assert_eq!(results.len(), 1);
+ assert_eq!(results[0].action_results.len(), 2);
+ assert!(results[0].action_results.iter().all(|r| r.success));
+
+ let actions = host.actions_run();
+ assert_eq!(actions[0], "copy_to_clipboard:Raw");
+ assert_eq!(actions[1], "notify:Screenshot:Copied to clipboard");
+}
+
+#[tokio::test]
+async fn run_skips_unsupported_capabilities() {
+ let host = MockHost::new(vec![Capability::CopyToClipboard]);
+
+ let store = AutomationsStore {
+ version: 1,
+ rules: vec![screenshot_copy_rule()],
+ };
+
+ let results = run(
+ &host,
+ &store,
+ &Trigger::ScreenshotTaken,
+ &TriggerContext::new(),
+ )
+ .await;
+
+ assert_eq!(results[0].action_results.len(), 2);
+ assert!(results[0].action_results[0].success);
+ assert!(!results[0].action_results[1].success);
+
+ let actions = host.actions_run();
+ assert_eq!(actions.len(), 1);
+ assert_eq!(actions[0], "copy_to_clipboard:Raw");
+}
+
+#[tokio::test]
+async fn skip_editor_action_is_noop_and_never_opens_editor() {
+ let rule = AutomationRule {
+ id: "headless".to_string(),
+ name: "Headless screenshot".to_string(),
+ enabled: true,
+ trigger: Trigger::ScreenshotTaken,
+ match_mode: MatchMode::All,
+ conditions: vec![],
+ actions: vec![
+ Action::CopyToClipboard {
+ source: ClipboardSource::Raw,
+ },
+ Action::SkipEditor,
+ ],
+ };
+
+ let store = AutomationsStore {
+ version: 1,
+ rules: vec![rule],
+ };
+
+ let host = MockHost::new(vec![Capability::CopyToClipboard, Capability::OpenEditor]);
+ let results = run(
+ &host,
+ &store,
+ &Trigger::ScreenshotTaken,
+ &TriggerContext::new(),
+ )
+ .await;
+
+ assert!(results[0].action_results.iter().all(|r| r.success));
+ let actions = host.actions_run();
+ assert_eq!(actions, vec!["copy_to_clipboard:Raw".to_string()]);
+ assert!(!actions.iter().any(|a| a == "open_editor"));
+}
+
+#[test]
+fn serialize_roundtrip() {
+ let store = AutomationsStore {
+ version: 1,
+ rules: vec![screenshot_copy_rule(), studio_export_rule()],
+ };
+
+ let json = serde_json::to_string_pretty(&store).unwrap();
+ let parsed: AutomationsStore = serde_json::from_str(&json).unwrap();
+ assert_eq!(parsed.rules.len(), 2);
+ assert_eq!(parsed.version, 1);
+}
+
+#[test]
+fn serialize_all_condition_and_action_shapes_roundtrip() {
+ use std::collections::HashMap;
+
+ let rule = AutomationRule {
+ id: "everything".to_string(),
+ name: "All shapes".to_string(),
+ enabled: true,
+ trigger: Trigger::StudioRecordingFinished,
+ match_mode: MatchMode::Any,
+ conditions: vec![
+ Condition::CaptureTargetIs {
+ target: CaptureTargetKind::Window,
+ },
+ Condition::RecordingModeIs {
+ mode: AutomationRecordingMode::Studio,
+ },
+ Condition::DurationAtLeast { secs: 5.0 },
+ Condition::DurationAtMost { secs: 600.0 },
+ Condition::WindowTitleContains {
+ pattern: "slack".to_string(),
+ },
+ Condition::OrganizationIs {
+ id: "org_1".to_string(),
+ },
+ ],
+ actions: vec![
+ Action::CopyToClipboard {
+ source: ClipboardSource::Rendered,
+ },
+ Action::SaveToLocation {
+ dir: "/tmp/cap".to_string(),
+ filename_template: Some("{date}-{window}".to_string()),
+ },
+ Action::Export {
+ profile: ExportProfile {
+ format: ExportFormat::Mp4,
+ fps: 60,
+ resolution_base: cap_project::XY { x: 1920, y: 1080 },
+ compression: Some(AutomationExportCompression::Web),
+ preset_name: Some("My Preset".to_string()),
+ },
+ destination: ExportDestination::CustomPath {
+ dir: "/tmp/out".to_string(),
+ },
+ },
+ Action::Upload {
+ organization_id: Some("org_1".to_string()),
+ copy_link: true,
+ open_in_browser: false,
+ },
+ Action::RevealInFileManager,
+ Action::OpenFile,
+ Action::RunCommand {
+ program: "echo".to_string(),
+ args: vec!["hi".to_string()],
+ cwd: None,
+ env: HashMap::new(),
+ use_shell: false,
+ },
+ Action::Webhook {
+ url: "https://example.com/hook".to_string(),
+ method: "POST".to_string(),
+ headers: HashMap::new(),
+ body_template: Some("{share_link}".to_string()),
+ },
+ Action::RecognizeTextToClipboard,
+ Action::Notify {
+ title_template: "Done".to_string(),
+ body_template: "Recording finished".to_string(),
+ },
+ Action::OpenEditor,
+ Action::SkipEditor,
+ Action::ApplyPreset {
+ name: "My Preset".to_string(),
+ },
+ Action::DeleteLocalFiles,
+ ],
+ };
+
+ let store = AutomationsStore {
+ version: 1,
+ rules: vec![rule],
+ };
+
+ let json = serde_json::to_value(&store).unwrap();
+ let conditions = &json["rules"][0]["conditions"];
+ assert_eq!(conditions[0]["type"], "captureTargetIs");
+ assert_eq!(conditions[0]["target"], "window");
+ assert_eq!(conditions[1]["type"], "recordingModeIs");
+ assert_eq!(conditions[1]["mode"], "studio");
+
+ let actions = &json["rules"][0]["actions"];
+ assert_eq!(actions[0]["type"], "copyToClipboard");
+ assert_eq!(actions[0]["source"], "rendered");
+ assert_eq!(actions[4]["type"], "revealInFileManager");
+
+ // Struct-variant fields must serialize camelCase to match the desktop+CLI frontends; serde's
+ // enum-level rename_all does not cover variant fields, so each multi-word variant carries its own.
+ assert_eq!(actions[1]["type"], "saveToLocation");
+ assert!(actions[1].get("filenameTemplate").is_some());
+ assert!(actions[1].get("filename_template").is_none());
+ assert!(actions[3].get("organizationId").is_some());
+ assert!(actions[3].get("copyLink").is_some());
+ assert!(actions[3].get("openInBrowser").is_some());
+ assert!(actions[6].get("useShell").is_some());
+ assert!(actions[7].get("bodyTemplate").is_some());
+ assert!(actions[9].get("titleTemplate").is_some());
+
+ let parsed: AutomationsStore = serde_json::from_value(json).unwrap();
+ assert_eq!(parsed.rules.len(), 1);
+ assert_eq!(parsed.rules[0].conditions.len(), 6);
+ assert_eq!(parsed.rules[0].actions.len(), 14);
+}
+
+#[test]
+fn load_store_from_json_extracts_automations_key() {
+ let store = AutomationsStore {
+ version: 1,
+ rules: vec![screenshot_copy_rule()],
+ };
+
+ let wrapper = serde_json::json!({
+ "general_settings": {},
+ "automations": store,
+ });
+
+ let loaded = load_store_from_json(&wrapper).unwrap();
+ assert_eq!(loaded.rules.len(), 1);
+ assert_eq!(loaded.rules[0].id, "rule-1");
+}
+
+#[test]
+fn load_store_from_json_returns_none_on_missing_key() {
+ let wrapper = serde_json::json!({
+ "general_settings": {},
+ });
+ assert!(load_store_from_json(&wrapper).is_none());
+}
+
+fn desktop_capabilities() -> Vec<Capability> {
+ vec![
+ Capability::CopyToClipboard,
+ Capability::SaveToLocation,
+ Capability::Export,
+ Capability::Upload,
+ Capability::RevealInFileManager,
+ Capability::OpenFile,
+ Capability::RunCommand,
+ Capability::Webhook,
+ Capability::RecognizeText,
+ Capability::Notify,
+ Capability::OpenEditor,
+ Capability::ApplyPreset,
+ Capability::DeleteLocalFiles,
+ ]
+}
+
+fn cli_capabilities() -> Vec<Capability> {
+ vec![
+ Capability::SaveToLocation,
+ Capability::Export,
+ Capability::Upload,
+ Capability::RevealInFileManager,
+ Capability::OpenFile,
+ Capability::RunCommand,
+ Capability::Webhook,
+ Capability::ApplyPreset,
+ Capability::DeleteLocalFiles,
+ ]
+}
+
+// Both surfaces share the same engine + store, so they must match the same rules and run the same
+// actions in the same order — the only difference being that surface-specific actions (clipboard on the
+// CLI) are skipped, never silently reordered or dropped.
+#[tokio::test]
+async fn desktop_and_cli_parity_on_screenshot_rule() {
+ let rule = AutomationRule {
+ id: "parity".to_string(),
+ name: "Auto-handle screenshot".to_string(),
+ enabled: true,
+ trigger: Trigger::ScreenshotTaken,
+ match_mode: MatchMode::All,
+ conditions: vec![Condition::CaptureTargetIs {
+ target: CaptureTargetKind::Window,
+ }],
+ actions: vec![
+ Action::SaveToLocation {
+ dir: "/tmp/shots".to_string(),
+ filename_template: None,
+ },
+ Action::CopyToClipboard {
+ source: ClipboardSource::Raw,
+ },
+ Action::RunCommand {
+ program: "true".to_string(),
+ args: vec![],
+ cwd: None,
+ env: HashMap::new(),
+ use_shell: false,
+ },
+ ],
+ };
+
+ let store = AutomationsStore {
+ version: 1,
+ rules: vec![rule],
+ };
+ let ctx = TriggerContext::new().with_capture_target(CaptureTargetKind::Window);
+
+ // Both surfaces evaluate to the same matched rule + ordered actions (engine is host-independent).
+ let matched = evaluate(&store, &Trigger::ScreenshotTaken, &ctx);
+ assert_eq!(matched.len(), 1);
+ assert_eq!(matched[0].1.len(), 3);
+
+ let desktop = MockHost::new(desktop_capabilities());
+ let desktop_results = run(&desktop, &store, &Trigger::ScreenshotTaken, &ctx).await;
+ assert!(desktop_results[0].action_results.iter().all(|r| r.success));
+ assert_eq!(
+ desktop.actions_run(),
+ vec![
+ "save_to_location:/tmp/shots:None".to_string(),
+ "copy_to_clipboard:Raw".to_string(),
+ "run_command:true".to_string(),
+ ]
+ );
+
+ let cli = MockHost::new(cli_capabilities());
+ let cli_results = run(&cli, &store, &Trigger::ScreenshotTaken, &ctx).await;
+ // Same three action slots reported, in order; the clipboard one is marked unsupported, not dropped.
+ assert_eq!(cli_results[0].action_results.len(), 3);
+ assert!(cli_results[0].action_results[0].success);
+ assert!(!cli_results[0].action_results[1].success);
+ assert!(cli_results[0].action_results[2].success);
+ assert_eq!(
+ cli.actions_run(),
+ vec![
+ "save_to_location:/tmp/shots:None".to_string(),
+ "run_command:true".to_string(),
+ ]
+ );
+}
+
+#[tokio::test]
+async fn skip_editor_runs_without_open_editor_capability() {
+ let rule = AutomationRule {
+ id: "cli-skip".to_string(),
+ name: "Headless".to_string(),
+ enabled: true,
+ trigger: Trigger::ScreenshotTaken,
+ match_mode: MatchMode::All,
+ conditions: vec![],
+ actions: vec![Action::SkipEditor],
+ };
+ let store = AutomationsStore {
+ version: 1,
+ rules: vec![rule],
+ };
+
+ // Host without `OpenEditor` capability, mirroring the CLI. `SkipEditor` must still succeed as a
+ // no-op rather than being reported unsupported.
+ let host = MockHost::new(vec![Capability::SaveToLocation]);
+ let results = run(
+ &host,
+ &store,
+ &Trigger::ScreenshotTaken,
+ &TriggerContext::new(),
+ )
+ .await;
+
+ assert_eq!(results[0].action_results.len(), 1);
+ assert!(results[0].action_results[0].success);
+ assert!(results[0].action_results[0].error.is_none());
+ assert!(host.actions_run().is_empty());
+}
+
+#[test]
+fn shell_command_line_quotes_args_with_spaces() {
+ let line = shell_command_line("echo", &["hello world".to_string(), "plain".to_string()]);
+ #[cfg(not(target_os = "windows"))]
+ assert_eq!(line, "echo 'hello world' plain");
+ #[cfg(target_os = "windows")]
+ assert_eq!(line, "echo \"hello world\" plain");
+}
+
+#[test]
+fn shell_command_line_escapes_embedded_quotes() {
+ #[cfg(not(target_os = "windows"))]
+ {
+ let line = shell_command_line("printf", &["it's".to_string()]);
+ assert_eq!(line, "printf 'it'\\''s'");
+ assert_eq!(shell_command_line("x", &[String::new()]), "x ''");
+ }
+ #[cfg(target_os = "windows")]
+ {
+ let line = shell_command_line("echo", &["a\"b".to_string()]);
+ assert_eq!(line, "echo \"a\"\"b\"");
+ }
+}
+
+#[test]
+fn multiple_rules_same_trigger() {
+ let rule1 = AutomationRule {
+ id: "a".to_string(),
+ name: "Rule A".to_string(),
+ enabled: true,
+ trigger: Trigger::ScreenshotTaken,
+ match_mode: MatchMode::All,
+ conditions: vec![],
+ actions: vec![Action::CopyToClipboard {
+ source: ClipboardSource::Raw,
+ }],
+ };
+ let rule2 = AutomationRule {
+ id: "b".to_string(),
+ name: "Rule B".to_string(),
+ enabled: true,
+ trigger: Trigger::ScreenshotTaken,
+ match_mode: MatchMode::All,
+ conditions: vec![],
+ actions: vec![Action::RevealInFileManager],
+ };
+
+ let store = AutomationsStore {
+ version: 1,
+ rules: vec![rule1, rule2],
+ };
+
+ let matched = evaluate(&store, &Trigger::ScreenshotTaken, &TriggerContext::new());
+ assert_eq!(matched.len(), 2);
+}
diff --git a/crates/automation/src/types.rs b/crates/automation/src/types.rs
new file mode 100644
index 000000000..6193b0292
--- /dev/null
+++ b/crates/automation/src/types.rs
@@ -0,0 +1,212 @@
+use serde::{Deserialize, Serialize};
+use specta::Type;
+use std::collections::HashMap;
+
+use cap_project::XY;
+
+#[derive(Serialize, Deserialize, Type, Debug, Clone, Default)]
+#[serde(rename_all = "camelCase")]
+pub struct AutomationsStore {
+ #[serde(default)]
+ pub version: u32,
+ #[serde(default)]
+ pub rules: Vec<AutomationRule>,
+}
+
+#[derive(Serialize, Deserialize, Type, Debug, Clone)]
+#[serde(rename_all = "camelCase")]
+pub struct AutomationRule {
+ pub id: String,
+ pub name: String,
+ #[serde(default = "default_true")]
+ pub enabled: bool,
+ pub trigger: Trigger,
+ #[serde(default)]
+ pub match_mode: MatchMode,
+ #[serde(default)]
+ pub conditions: Vec<Condition>,
+ #[serde(default)]
+ pub actions: Vec<Action>,
+}
+
+fn default_true() -> bool {
+ true
+}
+
+#[derive(Serialize, Deserialize, Type, Debug, Clone, Copy, PartialEq, Eq, Default)]
+#[serde(rename_all = "camelCase")]
+pub enum MatchMode {
+ #[default]
+ All,
+ Any,
+}
+
+#[derive(Serialize, Deserialize, Type, Debug, Clone, Copy, PartialEq, Eq, Hash)]
+#[serde(rename_all = "camelCase")]
+pub enum Trigger {
+ ScreenshotTaken,
+ StudioRecordingFinished,
+ InstantRecordingFinished,
+ RecordingStarted,
+ UploadCompleted,
+ VideoImported,
+ RecordingDeleted,
+}
+
+#[derive(Serialize, Deserialize, Type, Debug, Clone, PartialEq)]
+#[serde(rename_all = "camelCase", tag = "type")]
+pub enum Condition {
+ CaptureTargetIs { target: CaptureTargetKind },
+ RecordingModeIs { mode: AutomationRecordingMode },
+ DurationAtLeast { secs: f64 },
+ DurationAtMost { secs: f64 },
+ WindowTitleContains { pattern: String },
+ OrganizationIs { id: String },
+}
+
+#[derive(Serialize, Deserialize, Type, Debug, Clone, Copy, PartialEq, Eq)]
+#[serde(rename_all = "camelCase")]
+pub enum CaptureTargetKind {
+ Display,
+ Window,
+ Area,
+}
+
+#[derive(Serialize, Deserialize, Type, Debug, Clone, Copy, PartialEq, Eq)]
+#[serde(rename_all = "camelCase")]
+pub enum AutomationRecordingMode {
+ Studio,
+ Instant,
+}
+
+#[derive(Serialize, Deserialize, Type, Debug, Clone)]
+#[serde(rename_all = "camelCase", tag = "type")]
+pub enum Action {
+ CopyToClipboard {
+ #[serde(default)]
+ source: ClipboardSource,
+ },
+ #[serde(rename_all = "camelCase")]
+ SaveToLocation {
+ dir: String,
+ #[serde(default)]
+ filename_template: Option<String>,
+ },
+ Export {
+ profile: ExportProfile,
+ #[serde(default)]
+ destination: ExportDestination,
+ },
+ #[serde(rename_all = "camelCase")]
+ Upload {
+ #[serde(default)]
+ organization_id: Option<String>,
+ #[serde(default = "default_true")]
+ copy_link: bool,
+ #[serde(default)]
+ open_in_browser: bool,
+ },
+ RevealInFileManager,
+ OpenFile,
+ #[serde(rename_all = "camelCase")]
+ RunCommand {
+ program: String,
+ #[serde(default)]
+ args: Vec<String>,
+ #[serde(default)]
+ cwd: Option<String>,
+ #[serde(default)]
+ env: HashMap<String, String>,
+ #[serde(default)]
+ use_shell: bool,
+ },
+ #[serde(rename_all = "camelCase")]
+ Webhook {
+ url: String,
+ #[serde(default = "default_post")]
+ method: String,
+ #[serde(default)]
+ headers: HashMap<String, String>,
+ #[serde(default)]
+ body_template: Option<String>,
+ },
+ RecognizeTextToClipboard,
+ #[serde(rename_all = "camelCase")]
+ Notify {
+ #[serde(default = "default_notify_title")]
+ title_template: String,
+ #[serde(default)]
+ body_template: String,
+ },
+ OpenEditor,
+ SkipEditor,
+ ApplyPreset {
+ name: String,
+ },
+ DeleteLocalFiles,
+}
+
+fn default_post() -> String {
+ "POST".to_string()
+}
+
+fn default_notify_title() -> String {
+ "Cap Automation".to_string()
+}
+
+#[derive(Serialize, Deserialize, Type, Debug, Clone, Copy, PartialEq, Eq, Default)]
+#[serde(rename_all = "camelCase")]
+pub enum ClipboardSource {
+ #[default]
+ Raw,
+ Rendered,
+}
+
+#[derive(Serialize, Deserialize, Type, Debug, Clone)]
+#[serde(rename_all = "camelCase")]
+pub struct ExportProfile {
+ pub format: ExportFormat,
+ #[serde(default = "default_fps")]
+ pub fps: u32,
+ #[serde(default = "default_resolution")]
+ pub resolution_base: XY<u32>,
+ #[serde(default)]
+ pub compression: Option<AutomationExportCompression>,
+ #[serde(default)]
+ pub preset_name: Option<String>,
+}
+
+fn default_fps() -> u32 {
+ 30
+}
+
+fn default_resolution() -> XY<u32> {
+ XY { x: 1920, y: 1080 }
+}
+
+#[derive(Serialize, Deserialize, Type, Debug, Clone, Copy, PartialEq, Eq)]
+#[serde(rename_all = "camelCase")]
+pub enum ExportFormat {
+ Mp4,
+ Gif,
+ Mov,
+}
+
+#[derive(Serialize, Deserialize, Type, Debug, Clone, Copy, PartialEq, Eq)]
+#[serde(rename_all = "camelCase")]
+pub enum AutomationExportCompression {
+ Maximum,
+ Social,
+ Web,
+ Potato,
+}
+
+#[derive(Serialize, Deserialize, Type, Debug, Clone, Default, PartialEq, Eq)]
+#[serde(rename_all = "camelCase")]
+pub enum ExportDestination {
+ #[default]
+ ProjectFolder,
+ CustomPath {
+ dir: String,
+ },
+}