Skip to content

FilmCraft: An open-source, nonlinear video editor written by scratch in pure Rust

control: preserve MCP pointer input defaults (#2784) (#3004)

Michael Butlere7f7775943a8
diff --git a/crates/automation/src/server.rs b/crates/automation/src/server.rs
index b2e313504..33f5dc653 100644
--- a/crates/automation/src/server.rs
+++ b/crates/automation/src/server.rs
@@ -108,7 +108,7 @@ pub struct ClickParams {
/// left | right | middle
#[serde(default)]
pub button: Option<String>,
- /// 2 for double-click.
+ /// Number of clicks (0–10; defaults to 1). Use 2 for double-click. Larger values are rejected.
#[serde(default)]
pub count: Option<u32>,
/// {"shift":bool,"alt":bool,"command":bool,"ctrl":bool}
@@ -122,6 +122,7 @@ pub struct DragParams {
pub from: Value,
/// End point, same forms.
pub to: Value,
+ /// Movement steps (0–1024; defaults to 12; 0 or 1 uses 2). Larger values are rejected.
#[serde(default)]
pub steps: Option<u32>,
#[serde(default)]
@@ -497,6 +498,7 @@ impl FilmcraftMcp {
self.ui("ui.elements", json!({"prefix": p.prefix.unwrap_or_default()})).await
}
+ /// Forward a click to the live editor; an omitted count is sent as null and uses its default.
#[tool(
title = "Live app: click",
description = "Live app: click an element by id or at x,y (points). Supports right/middle button, double-click (count=2) and modifiers.",
@@ -513,6 +515,7 @@ impl FilmcraftMcp {
self.ui("ui.click", v).await
}
+ /// Forward a drag to the live editor, which applies the step default and validates its bounds.
#[tool(
title = "Live app: drag",
description = "Live app: press-drag-release from one point/element to another (move clips, trim edges, scrub, resize panels, drop project items onto tracks).",
diff --git a/crates/ui-egui/README.md b/crates/ui-egui/README.md
index 75fbe94e1..81060d656 100644
--- a/crates/ui-egui/README.md
+++ b/crates/ui-egui/README.md
@@ -3,6 +3,16 @@
The egui frontend draws panels and dialogs, and dispatches project changes through the engine.
Interactive controls keep stable automation ids regardless of the interface language.
+## Control input limits
+
+The control channel bounds `ui.click` to 10 clicks and `ui.drag` to 1024 movement steps (#2784).
+The MCP bridge sends null for omitted counts/steps, so the validator treats null like an absent
+field: one click or 12 drag steps. Negative, fractional, non-numeric and over-limit values still
+return errors before queuing any input. Zero clicks emit no button events; 0–1 drag steps use 2.
+`control::input_bounds_tests` covers defaults, rejection, unchanged pending input and valid
+gestures; `keyboard_ui` verifies that rejected requests leave the UI usable. See the
+[control protocol](../../docs/control-protocol.md).
+
## Transition drop previews
Dragging a video or audio transition over a compatible clip shows its actual time span, the
diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs
index 960fa8915..0fe8fb6aa 100644
--- a/crates/ui-egui/src/control.rs
+++ b/crates/ui-egui/src/control.rs
@@ -28,8 +28,15 @@ use serde_json::{Value, json};
const MAX_CLICK_COUNT: u64 = 10;
const MAX_DRAG_STEPS: u64 = 1_024;
+/// Read a pointer repetition count, using `default` when `key` is absent or null.
+///
+/// Reject non-integer, negative and above-`maximum` values; raise accepted counts to `minimum`.
fn bounded_repetitions(params: &Value, key: &str, default: u64, minimum: u64, maximum: u64) -> Result<u64, String> {
- let value = params.get(key).map(|value| value.as_u64().ok_or_else(|| format!("`{key}` must be a non-negative integer"))).transpose()?.unwrap_or(default);
+ // The MCP bridge serializes omitted optional counts as null.
+ let value = match params.get(key) {
+ None | Some(Value::Null) => default,
+ Some(value) => value.as_u64().ok_or_else(|| format!("`{key}` must be a non-negative integer"))?,
+ };
if value > maximum {
return Err(format!("`{key}` must not exceed {maximum}"));
}
@@ -642,6 +649,113 @@ pub fn encode_png(rgba: &[u8], w: u32, h: u32) -> Result<Vec<u8>, String> {
Ok(out)
}
+#[cfg(test)]
+mod input_bounds_tests {
+ use super::*;
+
+ /// Create an empty editor session for inspecting queued synthetic input without a window.
+ fn app() -> FilmcraftApp {
+ FilmcraftApp::new(filmcraft_engine::Session::default())
+ }
+
+ /// Dispatch a control request and fail the test if hostile parameters cause a panic.
+ fn request(app: &mut FilmcraftApp, method: &str, params: Value) -> Outcome {
+ let (req, _) = ControlRequest::new(method, params);
+ std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| handle(app, &egui::Context::default(), &req)))
+ .expect("hostile control parameters must not panic")
+ }
+
+ /// Require an immediate error naming `field`, with all previously queued input unchanged.
+ fn assert_rejected(app: &mut FilmcraftApp, method: &str, params: Value, field: &str) {
+ let before = app.synthetic.clone();
+ let Outcome::Done(reply) = request(app, method, params) else { panic!("invalid input must return an error immediately") };
+ assert_eq!(reply["ok"], false);
+ assert!(reply["error"].as_str().unwrap().contains(field), "{reply}");
+ assert_eq!(app.synthetic, before, "rejection must not queue partial input or change existing input");
+ }
+
+ /// Check the first rejected click count without allocating an enormous event queue.
+ #[test]
+ fn click_count_above_limit_is_rejected() {
+ // A small boundary value reproduces the missing guard without exhausting memory.
+ assert_rejected(&mut app(), "ui.click", json!({"x": 10, "y": 20, "count": 11}), "count");
+ }
+
+ /// Check that one step above the drag limit returns an error before queuing input.
+ #[test]
+ fn drag_steps_above_limit_are_rejected() {
+ assert_rejected(&mut app(), "ui.drag", json!({"from": {"x": 0, "y": 0}, "to": {"x": 10, "y": 20}, "steps": 1025}), "steps");
+ }
+
+ /// Reject extreme counts and malformed types while preserving pending and subsequent input.
+ #[test]
+ fn hostile_counts_and_steps_leave_pending_input_unchanged() {
+ let mut app = app();
+ app.synthetic.push(egui::Event::PointerGone);
+ for value in [json!(u32::MAX), json!(u64::MAX), json!(-1), json!(1.5), json!("2"), json!(true), json!([]), json!({})] {
+ assert_rejected(&mut app, "ui.click", json!({"x": 10, "y": 20, "count": value}), "count");
+ assert_rejected(&mut app, "ui.drag", json!({"from": {"x": 0, "y": 0}, "to": {"x": 10, "y": 20}, "steps": value}), "steps");
+ }
+ // A rejected request must not prevent subsequent valid input.
+ assert!(matches!(request(&mut app, "ui.click", json!({"x": 10, "y": 20})), Outcome::AfterInput));
+ }
+
+ /// Verify missing/null defaults, accepted click bounds, button pairs and modifier resets.
+ #[test]
+ fn valid_click_counts_preserve_button_pairs_and_modifiers() {
+ let mut app = app();
+ let pos = egui::pos2(10.0, 20.0);
+ let modifiers = egui::Modifiers { shift: true, ..Default::default() };
+ for (value, count) in [(None, 1), (Some(Value::Null), 1), (Some(json!(0)), 0), (Some(json!(1)), 1), (Some(json!(2)), 2), (Some(json!(10)), 10)] {
+ app.synthetic.clear();
+ let mut params = json!({"x": 10, "y": 20, "button": "right", "modifiers": {"shift": true}});
+ if let Some(v) = value {
+ params["count"] = v;
+ }
+ assert!(matches!(request(&mut app, "ui.click", params), Outcome::AfterInput));
+ let mut expected = vec![egui::Event::ModifiersChanged(modifiers), egui::Event::PointerMoved(pos)];
+ for _ in 0..count {
+ for pressed in [true, false] {
+ expected.push(egui::Event::PointerButton { pos, button: egui::PointerButton::Secondary, pressed, modifiers });
+ }
+ }
+ expected.push(egui::Event::ModifiersChanged(egui::Modifiers::NONE));
+ assert_eq!(app.synthetic, expected);
+ }
+ app.synthetic.clear();
+ assert!(matches!(request(&mut app, "ui.move", json!({"x": 10, "y": 20, "count": u64::MAX})), Outcome::AfterInput));
+ assert_eq!(app.synthetic.len(), 3, "ui.move does not use count");
+ }
+
+ /// Verify missing/null defaults and accepted drag bounds retain endpoints and button release.
+ #[test]
+ fn valid_drag_steps_preserve_defaults_endpoints_and_release() {
+ let mut app = app();
+ for (value, steps) in [(None, 12), (Some(Value::Null), 12), (Some(json!(0)), 2), (Some(json!(1)), 2), (Some(json!(2)), 2), (Some(json!(1024)), 1024)] {
+ app.synthetic.clear();
+ let mut params = json!({"from": {"x": 0, "y": 0}, "to": {"x": 10, "y": 20}, "modifiers": {"shift": true}});
+ if let Some(v) = value {
+ params["steps"] = v;
+ }
+ assert!(matches!(request(&mut app, "ui.drag", params), Outcome::AfterInput));
+ assert_eq!(app.synthetic.len(), steps + 5);
+ let modifiers = egui::Modifiers { shift: true, ..Default::default() };
+ assert_eq!(app.synthetic[0], egui::Event::ModifiersChanged(modifiers));
+ assert_eq!(app.synthetic[1], egui::Event::PointerMoved(egui::pos2(0.0, 0.0)));
+ assert_eq!(
+ app.synthetic[2],
+ egui::Event::PointerButton { pos: egui::pos2(0.0, 0.0), button: egui::PointerButton::Primary, pressed: true, modifiers }
+ );
+ assert_eq!(app.synthetic[steps + 2], egui::Event::PointerMoved(egui::pos2(10.0, 20.0)));
+ assert_eq!(
+ app.synthetic[steps + 3],
+ egui::Event::PointerButton { pos: egui::pos2(10.0, 20.0), button: egui::PointerButton::Primary, pressed: false, modifiers }
+ );
+ assert_eq!(app.synthetic[steps + 4], egui::Event::ModifiersChanged(egui::Modifiers::NONE));
+ }
+ }
+}
+
#[cfg(test)]
mod base64_tests {
use serde_json::json;
diff --git a/crates/ui-egui/tests/it/keyboard_ui.rs b/crates/ui-egui/tests/it/keyboard_ui.rs
index b1ea139a2..e0147f1d1 100644
--- a/crates/ui-egui/tests/it/keyboard_ui.rs
+++ b/crates/ui-egui/tests/it/keyboard_ui.rs
@@ -71,6 +71,32 @@ impl Driver {
}
}
+/// Rejected pointer counts must preserve the editor and allow later MCP-default and double clicks.
+#[test]
+fn rejected_pointer_counts_leave_the_ui_usable() {
+ let mut d = Driver::new();
+ let project = d.app().session.project.clone();
+ for (method, params) in [
+ ("ui.click", json!({"id": "tools.Razor", "count": u64::MAX})),
+ ("ui.drag", json!({"from": {"id": "tools.Razor"}, "to": {"id": "tools.Selection"}, "steps": u64::MAX})),
+ ] {
+ let (req, reply) = ControlRequest::new(method, params);
+ d.tx.send(req).unwrap();
+ d.frames(3);
+ let response = reply.try_recv().expect("invalid counts must be answered without queuing input");
+ assert_eq!(response["ok"], false, "{response}");
+ assert_eq!(d.app().ui.tool, filmcraft_ui_egui::state::Tool::Selection);
+ assert_eq!(*d.app().session.project, *project);
+ }
+ d.ok("ui.click", json!({"id": "tools.Razor", "count": null}));
+ d.frames(3);
+ assert_eq!(d.app().ui.tool, filmcraft_ui_egui::state::Tool::Razor);
+ d.ok("ui.click", json!({"id": "tools.Selection", "count": 2}));
+ d.frames(3);
+ assert_eq!(d.app().ui.tool, filmcraft_ui_egui::state::Tool::Selection);
+ assert_eq!(*d.app().session.project, *project);
+}
+
/// Ids added for keyboard parity (engine + UI).
fn new_ids() -> Vec<String> {
let mut v: Vec<String> = filmcraft_engine::keyboard::commands().iter().map(|c| c.id.to_string()).collect();
diff --git a/docs/control-protocol.md b/docs/control-protocol.md
index 6093c4fbd..f5b32a1d9 100644
--- a/docs/control-protocol.md
+++ b/docs/control-protocol.md
@@ -52,8 +52,8 @@ Methods (handlers in `crates/ui-egui/src/control.rs`):
| `ui.elements` | `{prefix?}` | every on-screen interactive element: id, label, rect |
| `ui.set` | `{tool, workspace, mode, theme, focused, playbackRes, timeline:{pps,scroll,fit}, program:{…}, source:{…}, clipDialog:{param: value}, menuDialog:{param: value}, panels:{scopes, timecode, reference, events, progress}, export:{…}, keyframeSelection:[…]}` | `keyframeSelection` replaces the Effect Controls keyframe selection (`[{clip, effect, param, mask?, time}]`, `time` in media ticks; read back as `ui.inspect` → `ui.keyframe_selection`; a click on a lane keyframe selects just that one); `program` / `source` merge fields into the monitor view state (`res`, `paused_res`, `high_quality`, `display`, `zoom`, `pan`, `show_rulers`, `show_guides`, `lock_guides`, `snap`, `guides`, `compare_ref`, …; see [monitors.md](monitors.md)); `clipDialog` sets fields of the open Edit / Clip / File dialog (Paste Attributes, Make Subclip, Frame Hold Options, …); `menuDialog` those of the M3.11 dialogs (Find, Create Search Bin, Project Settings, Scene Edit Detection, Simplify Sequence, Automate to Sequence…; see `panels::menu_dialogs`); `panels` merges into the panel settings (`ui.inspect` → `ui.panels`; see `panels::panel_state`): Lumetri Scopes `{shown: ["vectorscopeYuv"|"vectorscopeHls"|"histogram"|"parade"|"waveform"], waveformType, paradeType, colorSpace, brightness, scale, clamp, targets}`, Timecode `{rows: [{source, mode, display}], showName}`, Reference Monitor `{ganged, time, display: "composite"|"scopes", scopes}`, Events `{level, selected}`, Progress `{showFinished}` `export` deep-merges into Export mode state (`preset` — applied first —, `settings` (ExportSettings JSON), `fileName`, `location`, `range`, `customStart`, `customEnd`, `openSections`, `manager` (Preset Manager: `query`, `favoritesOnly`, `selected`, `saveName`), `quickOpen`, `quickPath`, `quickPreset`); `program` / `source` merge fields into the monitor view state (`res`, `paused_res`, `high_quality`, `display`, `zoom`, `pan`, `show_rulers`, `show_guides`, `lock_guides`, `snap`, `guides`, `compare_ref`, …; see [monitors.md](monitors.md)); `clipDialog` sets fields of the open Edit / Clip / File dialog (Paste Attributes, Make Subclip, Frame Hold Options, …); `menuDialog` those of the M3.11 dialogs (Find, Create Search Bin, Project Settings, Scene Edit Detection, Simplify Sequence, Automate to Sequence…; see `panels::menu_dialogs`); `projectPanel` merges into the Project panel's view state (`bin` shown in place, `tabs` (bins in a tab or window: `{bin, floating, view, iconSize, nav}`), `activeTab`, `selectedBin`, `rename: {item|bin, text}`, `dialog` (`{"metadataDisplay": {columns, filter}}`, `{"savePresetAs": {name}}`, `{"managePresets": {selected, name}}`, `{"freeformOptions": {options}}`, `{"saveArrangement": {name, bin}}`)); `mediaBrowser` into the Media Browser's (`expanded`, `pathEdit`, `editColumns`, `treeWidth`). View settings, columns and presets are engine commands (`project.view.set`, `project.columns.set`, `project.viewPreset.*`, `mediaBrowser.settings`) |
| `ui.panel.show` / `ui.panel.close` | `{panel}` | |
-| `ui.click` / `ui.move` | `{id}` or `{x,y}`, `button`, `count`, `modifiers` | synthetic pointer input |
-| `ui.drag` | `{from, to, steps, modifiers}` | press–move–release |
+| `ui.click` / `ui.move` | `{id}` or `{x,y}`, `button`, `count`, `modifiers` | synthetic pointer input; click `count` is an integer 0–10 (default 1); `ui.move` ignores it |
+| `ui.drag` | `{from, to, steps, modifiers}` | press–move–release; `steps` is an integer 0–1024 (default 12; 0 or 1 uses 2 steps) |
| `ui.scroll` | `{id|x,y, dx, dy, modifiers}` | wheel / trackpad |
| `ui.key` / `ui.type` | `{key}` (`Cmd+K`, `Space`…; off macOS `Ctrl+K` is the same key) / `{text}` | keyboard |
| `ui.timeline.hit` / `ui.timeline.locate` | `{x,y,modifiers?}` / `{clip, edge?}` | timeline hit-testing. `hit` reports a clip's `edge` (`In`/`Out`) within 7 px of it (a third of a narrow clip); just left of a cut that is the left clip's Out, from the cut rightwards the right clip's In. `kind` is the trim a press of the current tool with `modifiers` starts there (`trim`, `ripple`, `roll`, `rateStretch`, `remix`), `volume` on an audio clip's Volume line (Selection and Pen tools), or null |
@@ -63,6 +63,10 @@ Methods (handlers in `crates/ui-egui/src/control.rs`):
| `ui.focus` | `{}` / `{id}` | empty parameters activate the native window; a widget ID requests egui focus without OS activation |
| `perf.stats` | – | performance counters (also the command `perf.stats`, so `engine.execute` and MCP `command_run` reach it; headless sessions return the engine part). `decode`: GOP-cache requests / hits / `cacheHitRate`, decoder seeks, samples decoded and skipped while catching up, `draftFrames` (decoded in draft mode), `h264Threads` (frame-threading workers per H.264 decoder), `liveDecoders` (sources holding a decoder now), `cacheMB` / `cacheBudgetMB` (decoded frames all sources hold, and the shared budget), `planePoolMB` / `planesReused` (idle buffers of the frame pool, the planes of evicted frames and the compositor's float images, which a standalone export frees when it ends; and buffers taken from it instead of allocated), decoder ms (total and per sample), `framesDecoded`, `hardware` (Settings ▸ Playback ▸ Hardware decoding: `enabled`, pictures from hardware decoders `frames` vs `softwareFrames`, `sessions`, `declined` streams, mid-stream `fallbacks`); `playback`: playing, shown / dropped frames and `dropRate` of the current or last play, resolution, `draftDecode` (Settings ▸ Playback ▸ Draft decoding), `audio` (desktop: sound is mixed 200 ms ahead of the device; device `callbacks`, `underruns` and `missingFrames` played as silence because the mixer fell behind, `minLeadMs` the least sound left buffered); `frames`: frame-worker jobs, cancelled, `requestHitRate`, `decodeMs` / `renderMs` (mean, p50, p95 of the last 256 jobs), queue, render-cost estimate, cache use; `monitor`: the `frame` and `revision` of the picture the Program monitor shows against `playheadFrame` and `projectRevision` (how far a drag or a scrub is ahead of the picture); `ui`: fps and frame ms; `process`: CPU seconds; `media`, `jobs`. Counters are cumulative: diff two readings to measure an interval ([performance.md](performance.md)) |
+For `ui.click` and `ui.drag`, omitted or null counts/steps use the defaults. Out-of-range or
+non-integer values return `{"ok": false, "error": "…"}` before queuing any pointer input.
+These limits also apply to the MCP bridge's `ui_click`, `ui_drag` and `ui_control` tools.
+
**Timeline thumbnails.** `ui.set {timeline: {thumbnails}}` sets the Timeline wrench menu's Show Video
Thumbnails: `off`, `head`, `headAndTail` or `continuous`.