Skip to content

LightCraft: An open-source non-destructive photo editor written by scratch in pure Rust

LR-BEHAV-TEXTFIELD: agents cut, copy and paste in text fields

Nathaniel Ledford1029e63bdeec
diff --git a/crates/mcp/src/tests.rs b/crates/mcp/src/tests.rs
index 3393e5040..e09c9d4c9 100644
--- a/crates/mcp/src/tests.rs
+++ b/crates/mcp/src/tests.rs
@@ -371,3 +371,31 @@ fn modern_requests_receive_result_and_cache_fields() {
}
assert!(rpc(&mut s, 2, "tools/list", json!({}))["result"].get("resultType").is_none());
}
+
+/// A running app's control channel, as far as the MCP server can tell: it records each call.
+struct Recorder(Vec<(String, Value)>);
+
+impl Backend for Recorder {
+ fn call(&mut self, method: &str, params: Value) -> Result<Value, String> {
+ self.0.push((method.to_string(), params));
+ Ok(Value::Null)
+ }
+ fn has_ui(&self) -> bool {
+ true
+ }
+ fn describe(&self) -> String {
+ "recorder".into()
+ }
+}
+
+/// With the app attached, agents cut, copy and paste in its text fields (`clipboard`).
+#[test]
+fn the_clipboard_tool_cuts_copies_and_pastes_in_the_app() {
+ let names: Vec<String> = crate::tools::helper_tools(true).iter().filter_map(|t| t["name"].as_str().map(str::to_string)).collect();
+ assert!(names.iter().any(|n| n == "clipboard"), "{names:?}");
+ assert!(!crate::tools::helper_tools(false).iter().any(|t| t["name"] == "clipboard"), "not without the app");
+ let mut b = Recorder(vec![]);
+ let r = call_tool(&mut b, "clipboard", &json!({"action": "paste", "text": "travel"}));
+ assert!(!r.is_error, "{r:?}");
+ assert_eq!(b.0, vec![("ui.clipboard".to_string(), json!({"action": "paste", "text": "travel"}))]);
+}
diff --git a/crates/mcp/src/tools.rs b/crates/mcp/src/tools.rs
index 4a114f18c..86cf9ff0c 100644
--- a/crates/mcp/src/tools.rs
+++ b/crates/mcp/src/tools.rs
@@ -305,6 +305,13 @@ pub fn helper_tools(has_ui: bool) -> Vec<Value> {
&["key"],
),
tool("type_text", "Type text", "Type text into the focused field.", json!({"text": {"type": "string"}}), &["text"]),
+ tool(
+ "clipboard",
+ "Cut, copy or paste",
+ "Cut, copy or paste in the focused text field, as ⌘X / ⌘C / ⌘V do. `paste` pastes `text`, or what the system clipboard holds without it. inspect_ui → `copied` is the text the app last copied.",
+ json!({"action": {"type": "string", "enum": ["cut", "copy", "paste"]}, "text": {"type": "string"}}),
+ &["action"],
+ ),
tool(
"pointer_gesture",
"Pointer gesture",
@@ -757,6 +764,7 @@ pub fn call_tool(b: &mut dyn Backend, name: &str, args: &Value) -> ToolResult {
}
"press_key" => ToolResult::from(b.call("ui.key", obj(args, &["key", "cmd", "shift", "alt", "ctrl"]))),
"type_text" => ToolResult::from(b.call("ui.text", obj(args, &["text"]))),
+ "clipboard" => ToolResult::from(b.call("ui.clipboard", obj(args, &["action", "text"]))),
"pointer_gesture" => ToolResult::from(b.call("ui.pointer", obj(args, &["events", "alt", "shift", "cmd"]))),
other => ToolResult::error(format!("unknown tool `{other}` (see tools/list)")),
}
diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs
index dcd3d1f8b..e2d01f5ec 100644
--- a/crates/ui-egui/src/control.rs
+++ b/crates/ui-egui/src/control.rs
@@ -103,6 +103,7 @@ pub fn inspect(app: &LightcraftApp, ctx: &egui::Context) -> Value {
})),
"hoverPreview": app.hover_preview.as_ref().map(|h| h.label.clone()),
"status": app.ui.status,
+ "copied": app.copied,
"notices": app.notices,
"quitPrompt": app.quit_prompt,
// how hard the background face scan may work right now, and why it is judged so (see `panels::faces::scan_pace`)
@@ -273,6 +274,21 @@ pub fn handle(app: &mut LightcraftApp, ctx: &egui::Context, req: &ControlRequest
ctx.request_repaint();
ok(Value::Null)
}
+ // what the system does for ⌘X / ⌘C / ⌘V in a text field: paste `text`, or (without it)
+ // what the system clipboard holds
+ "ui.clipboard" => {
+ match s("action") {
+ Some("cut") => app.synthetic.push(egui::Event::Cut),
+ Some("copy") => app.synthetic.push(egui::Event::Copy),
+ Some("paste") => match s("text") {
+ Some(text) => app.synthetic.push(egui::Event::Paste(text.to_string())),
+ None => ctx.send_viewport_cmd(egui::ViewportCommand::RequestPaste),
+ },
+ _ => return err("ui.clipboard: `action` is cut, copy or paste"),
+ }
+ ctx.request_repaint();
+ ok(Value::Null)
+ }
"ui.scroll" => {
app.synthetic.push(egui::Event::MouseWheel {
unit: egui::MouseWheelUnit::Point,
diff --git a/crates/ui-egui/src/headless.rs b/crates/ui-egui/src/headless.rs
index c021291b1..8b5f4256b 100644
--- a/crates/ui-egui/src/headless.rs
+++ b/crates/ui-egui/src/headless.rs
@@ -635,6 +635,33 @@ mod tests {
Headless::new(app, size, 1.0)
}
+ /// Agents cut, copy and paste in a text field as the system does for ⌘X / ⌘C / ⌘V
+ /// (`ui.clipboard`), and `ui.inspect` → `copied` says what the UI last copied.
+ #[test]
+ fn agents_cut_copy_and_paste_in_text_fields() {
+ let mut h = demo([1200.0, 760.0]);
+ let t = Duration::from_secs(10);
+ let ask = |h: &mut Headless, method: &str, params: serde_json::Value| {
+ let r = h.request(method, params.clone(), t);
+ assert_eq!(r["ok"], true, "{method} {params}: {r}");
+ h.step();
+ h.step();
+ r
+ };
+ h.settle(SETTLE);
+ ask(&mut h, "ui.clickWidget", json!({"id": "field:search"}));
+ ask(&mut h, "ui.text", json!({"text": "wedding"}));
+ ask(&mut h, "ui.key", json!({"key": "a", "cmd": true}));
+ ask(&mut h, "ui.clipboard", json!({"action": "copy"}));
+ assert_eq!(ask(&mut h, "ui.inspect", json!({}))["result"]["copied"], "wedding");
+ ask(&mut h, "ui.clipboard", json!({"action": "cut"}));
+ assert_eq!(h.app.ui.search, "");
+ ask(&mut h, "ui.clipboard", json!({"action": "paste", "text": "travel"}));
+ assert_eq!(h.app.ui.search, "travel");
+ let r = h.request("ui.clipboard", json!({"action": "shred"}), t);
+ assert_eq!(r["ok"], false, "an unknown action is refused: {r}");
+ }
+
#[test]
fn demo_grid_snapshot_has_ui_pixels() {
let t0 = Instant::now();
diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs
index 4ad22a5d9..c9d0d27f6 100644
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@ -197,6 +197,8 @@ pub struct LightcraftApp {
shadow: Option<headless::HeadlessView>,
/// Synthetic input events (from the control channel) injected one step per frame.
pub synthetic: Vec<egui::Event>,
+ /// The text the UI last put on the clipboard (`ui.inspect` → `copied`).
+ pub copied: Option<String>,
/// Native file dialogs up for commands (`pick`): each command runs again when its closes.
pub(crate) pending_picks: Vec<pick::Pending>,
/// Modifiers announced for synthetic input (held from a button down to its release).
@@ -289,6 +291,7 @@ impl LightcraftApp {
screenshot_token: 0,
shadow: None,
synthetic: vec![],
+ copied: None,
pending_picks: vec![],
synthetic_mods: egui::Modifiers::NONE,
synthetic_mods_release: false,
@@ -883,7 +886,14 @@ impl LightcraftApp {
}
/// Frame timings once layout is done (`t0`: when layout started).
- fn end_frame(&mut self, t0: f64) {
+ fn end_frame(&mut self, ctx: &egui::Context, t0: f64) {
+ ctx.output(|o| {
+ for c in &o.commands {
+ if let egui::OutputCommand::CopyText(text) = c {
+ self.copied = Some(text.clone());
+ }
+ }
+ });
self.perf.frame_ms = now_ms() - t0;
self.perf.update_ms = self.perf.logic_ms + self.perf.frame_ms;
self.perf.max_update_ms = self.perf.max_update_ms.max(self.perf.update_ms);
@@ -913,7 +923,7 @@ impl LightcraftApp {
panels::library_problem::show(self, &ctx);
panels::toast(self, &ctx);
self.widgets = widgets::take_registry(&ctx);
- self.end_frame(t0);
+ self.end_frame(&ctx, t0);
return;
}
// Order matters: earlier panels take the full edge (top bar spans the window; the tool strip,
@@ -959,7 +969,7 @@ impl LightcraftApp {
panels::left::album_drag_feedback(self, &ctx);
panels::toast(self, &ctx);
self.widgets = widgets::take_registry(&ctx);
- self.end_frame(t0);
+ self.end_frame(&ctx, t0);
}
}
diff --git a/docs/control-protocol.md b/docs/control-protocol.md
index 4247b559e..b0b123faa 100644
--- a/docs/control-protocol.md
+++ b/docs/control-protocol.md
@@ -30,13 +30,14 @@ mode ([mcp.md](mcp.md)) is a thin layer over this channel. Implementation:
| `engine.commands` | — | Engine + UI commands: id, label, menu, shortcut, params doc, enabled |
| `ui.menu.list` | — | Menu entries (flat: id, label, menu path, shortcut, enabled) |
| `ui.menu.tree` | — | The menu bar as shown (File … Help): items `{id, params?, label, shortcut?, enabled, checked?}`, separators, submenus — the model behind the native macOS menu bar and the in-window menus |
-| `ui.inspect` | — | UI state, window, `loupe` (`source`, and `region: {full, window, pending}` when a zoomed view also renders the window on screen at no more than 100 % — `full` is the frame it is cut from, `window` its `[x, y, w, h]` — and `regionBefore` for the Before side of a Before/After view), canvas/image rects, `scroll: {grid, filmstrip}` (scroll offsets in points, `null` until drawn), active photo, selection, perf (`frameMs` = layout, `logicMs` = per-frame logic before it, `updateMs` = both, `maxUpdateMs`, `fps`, render queue …, `gpu` = adapter in use, `gpuReason` = why renders don't use the GPU, `gpuFallback` = latest render redone on the CPU and why — see `docs/gpu-pipeline.md`), status, memory (bytes per cache, see `library.memory`; plus stage caches — `budgetBytes`, `trimmed`, `sharedSourceBytes` (the one device copy of a big original) — and textures), `export: {running: {total, done, current} \| null, last}`, `notices` (warnings waiting to be shown, e.g. a damaged settings file; OK = `button:noticeOk`), `quitPrompt` (why quitting was stopped: unsaved changes; `button:quitRetry` / `button:quitAnyway` / `button:quitCancel`), `import: {done, total, imported, cancelled} \| null` (an import runs on a worker thread), `tasks` (other background work: `Find Missing Photos`, `Auto Import`), `fileDialogs` (commands waiting on a native file dialog, which runs off the UI thread; they run again with the answer when it closes) |
+| `ui.inspect` | — | UI state, window, `loupe` (`source`, and `region: {full, window, pending}` when a zoomed view also renders the window on screen at no more than 100 % — `full` is the frame it is cut from, `window` its `[x, y, w, h]` — and `regionBefore` for the Before side of a Before/After view), canvas/image rects, `scroll: {grid, filmstrip}` (scroll offsets in points, `null` until drawn), active photo, selection, perf (`frameMs` = layout, `logicMs` = per-frame logic before it, `updateMs` = both, `maxUpdateMs`, `fps`, render queue …, `gpu` = adapter in use, `gpuReason` = why renders don't use the GPU, `gpuFallback` = latest render redone on the CPU and why — see `docs/gpu-pipeline.md`), status, memory (bytes per cache, see `library.memory`; plus stage caches — `budgetBytes`, `trimmed`, `sharedSourceBytes` (the one device copy of a big original) — and textures), `export: {running: {total, done, current} \| null, last}`, `notices` (warnings waiting to be shown, e.g. a damaged settings file; OK = `button:noticeOk`), `quitPrompt` (why quitting was stopped: unsaved changes; `button:quitRetry` / `button:quitAnyway` / `button:quitCancel`), `import: {done, total, imported, cancelled} \| null` (an import runs on a worker thread), `tasks` (other background work: `Find Missing Photos`, `Auto Import`), `fileDialogs` (commands waiting on a native file dialog, which runs off the UI thread; they run again with the answer when it closes), `copied` (the text the UI last put on the clipboard, `null` until something is copied) |
| `ui.widgets` | `{filter?}` | On-screen widgets `{id, rect: [x, y, w, h]}` (screen points) |
| `ui.clickWidget` / `ui.dragWidget` / `ui.hoverWidget` | `{id, count?, fx?, fy?}` / `{id, toX?, toY?, dx?, dy?, steps?}` / `{id, fx?, fy?}` | Real egui input on a widget (hover: the pointer rests on it, e.g. for preset/profile previews) |
| `ui.move` / `ui.click` / `ui.drag` | `{x, y, count?, button?}` / `{x, y, toX, toY, steps?}` | Raw pointer input, screen points |
| `ui.pointer` | `{events: [{kind: down\|drag\|up, x, y}], alt?, shift?, cmd?}` | Gesture in normalized image coordinates (Detail view) |
| `ui.key` | `{key, cmd?, shift?, alt?, ctrl?}` | Key press |
| `ui.text` | `{text}` | Text input |
+| `ui.clipboard` | `{action: cut\|copy\|paste, text?}` | Cut, copy or paste in the focused text field, as the system does for ⌘X / ⌘C / ⌘V; `paste` pastes `text`, or the system clipboard without it. `ui.inspect` → `copied` is the text the UI last put on the clipboard |
| `ui.scroll` | `{dx, dy, cmd?, ctrl?, shift?, alt?}` | Wheel / two-finger scroll at the current pointer; pans over the image, modifier-scroll zooms |
| `ui.zoom` | `{factor}` | Pinch zoom at the current pointer (positive scale multiplier; 1 = unchanged). Position it first with `ui.move` or `ui.hoverWidget` |
| `ui.set` | partial UI state, e.g. `{"view": "detail"}` | Resulting UI state |
diff --git a/docs/mcp.md b/docs/mcp.md
index 3134468e3..2dfe59c10 100644
--- a/docs/mcp.md
+++ b/docs/mcp.md
@@ -134,6 +134,7 @@ Tools taking `id` make that photo active first; without it they act on the activ
| `set_ui {state}` | Merge UI state, e.g. `{"view": "detail"}` |
| `list_widgets {filter?}` / `click {widget \| x,y, count?}` | Widgets by automation id; real egui clicks |
| `press_key {key, cmd?, shift?, alt?}` / `type_text {text}` | Keyboard input (shortcuts) |
+| `clipboard {action, text?}` | Cut, copy or paste in the focused text field (⌘X / ⌘C / ⌘V); `inspect_ui` → `copied` is what was copied |
| `pointer_gesture {events}` | Gestures in normalized image coordinates (brush strokes, gradients, crop handles) |
In headless mode these return a tool error explaining how to start the app.