AI media harness for planning, generating, and editing locally
TypeScript
Add lasso combine and subtract controls
Bitti5b1ce14e832f
diff --git a/RELEASE_NOTES.md b/RELEASE_NOTES.mdindex f731a01..ebc20e5 100644--- a/RELEASE_NOTES.md+++ b/RELEASE_NOTES.md@@ -24,6 +24,8 @@ This alpha update adds Prompt video scenes, agent image drafts, Sol attention an## Fixes and improvements+- Renamed Draw edit to Edit Box with a box icon. Hold Ctrl when releasing a lasso stroke to combine overlapping areas, or Alt to subtract. Cursor indicators show the active operation; holes and split areas persist in saved projects and generation masks.+- Lasso selections can be moved but not scaled. Image edits keep the source visible during generation and display the edited result when complete.- Generation effects reuse VAE fingerprints between jobs, removing repeated full-file calibration checks for unchanged VAEs. Changed or replaced VAEs are verified again; saved calibrations remain reusable after restarting.diff --git a/package-lock.json b/package-lock.jsonindex f01f5e7..6609772 100644--- a/package-lock.json+++ b/package-lock.json@@ -13,6 +13,7 @@"@tauri-apps/plugin-dialog": "^2.7.3","@tauri-apps/plugin-process": "^2.3.1","@tauri-apps/plugin-updater": "^2.11.0",+ "clipper-lib": "^6.4.2","mp4-muxer": "^5.2.2","mp4box": "^2.4.1","react": "^18.3.1",@@ -23,6 +24,7 @@"@tauri-apps/cli": "^2.8.4","@testing-library/jest-dom": "^6.6.3","@testing-library/react": "^16.1.0",+ "@types/clipper-lib": "^6.4.0","@types/react": "^18.3.18","@types/react-dom": "^18.3.5","@vitejs/plugin-react": "^4.3.4",@@ -1782,6 +1784,13 @@"assertion-error": "^2.0.1"}},+ "node_modules/@types/clipper-lib": {+ "version": "6.4.0",+ "resolved": "https://registry.npmjs.org/@types/clipper-lib/-/clipper-lib-6.4.0.tgz",+ "integrity": "sha512-y8WVQWLCIJobtcxk8SJj1f7OGVbQEL7RmfGtrWDkAKFxq2U6F0/7/hLYvDWlUnBayvnRYkq+QVZaUzm13mu+Ng==",+ "dev": true,+ "license": "MIT"+ },"node_modules/@types/deep-eql": {"version": "4.0.2","resolved": "https://registry.npmjs.org/@types/deep-eql/-/deep-eql-4.0.2.tgz",@@ -2160,6 +2169,12 @@"node": ">= 16"}},+ "node_modules/clipper-lib": {+ "version": "6.4.2",+ "resolved": "https://registry.npmjs.org/clipper-lib/-/clipper-lib-6.4.2.tgz",+ "integrity": "sha512-knglhjQX5ihNj/XCIs6zCHrTemdvHY3LPZP9XB2nq2/3igyYMFueFXtfp84baJvEE+f8pO1ZS4UVeEgmLnAprQ==",+ "license": "BSL"+ },"node_modules/combined-stream": {"version": "1.0.8","resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz",diff --git a/package.json b/package.jsonindex 6a10ea9..352ed4b 100644--- a/package.json+++ b/package.json@@ -20,6 +20,7 @@"@tauri-apps/plugin-dialog": "^2.7.3","@tauri-apps/plugin-process": "^2.3.1","@tauri-apps/plugin-updater": "^2.11.0",+ "clipper-lib": "^6.4.2","mp4-muxer": "^5.2.2","mp4box": "^2.4.1","react": "^18.3.1",@@ -30,6 +31,7 @@"@tauri-apps/cli": "^2.8.4","@testing-library/jest-dom": "^6.6.3","@testing-library/react": "^16.1.0",+ "@types/clipper-lib": "^6.4.0","@types/react": "^18.3.18","@types/react-dom": "^18.3.5","@vitejs/plugin-react": "^4.3.4",diff --git a/src-tauri/core/src/image_mask.rs b/src-tauri/core/src/image_mask.rsindex 66c655b..d15de7e 100644--- a/src-tauri/core/src/image_mask.rs+++ b/src-tauri/core/src/image_mask.rs@@ -17,22 +17,34 @@ pub fn validate_polygon(points: &[MaskPoint], width: i32, height: i32) -> ResultOk(())}+pub fn validate_contours(contours: &[Vec<MaskPoint>], width: i32, height: i32) -> Result<(), String> {+ if contours.is_empty() || contours.len() > 256 || contours.iter().map(Vec::len).sum::<usize>() > 8192 {+ return Err("Lasso masks require 1 to 256 contours and at most 8192 points.".into());+ }+ for points in contours { validate_polygon(points, width, height)?; }+ Ok(())+}+/// Even-odd fill, four vertical samples and exact horizontal coverage. Only/// the edge pixels blend; pixels outside the outline remain zero. Row storage/// stays bounded even for the largest supported canvas.pub fn rasterize_polygon(points: &[MaskPoint], width: i32, height: i32) -> Result<Vec<u8>, String> {- validate_polygon(points, width, height)?;+ rasterize_contours(&[points.to_vec()], width, height)+}++pub fn rasterize_contours(contours: &[Vec<MaskPoint>], width: i32, height: i32) -> Result<Vec<u8>, String> {+ validate_contours(contours, width, height)?;let mut mask = vec![0; width as usize * height as usize];- let mut intersections = Vec::with_capacity(points.len());+ let mut intersections = Vec::with_capacity(contours.iter().map(Vec::len).sum());let mut coverage = vec![0.0_f64; width as usize];- let top = points.iter().map(|p| p.y).fold(f64::INFINITY, f64::min).floor() as usize;- let bottom = points.iter().map(|p| p.y).fold(0.0_f64, f64::max).ceil() as usize;+ let top = contours.iter().flatten().map(|p| p.y).fold(f64::INFINITY, f64::min).floor() as usize;+ let bottom = contours.iter().flatten().map(|p| p.y).fold(0.0_f64, f64::max).ceil() as usize;for y in top..bottom.min(height as usize) {coverage.fill(0.0);for sample in 0..4 {let scan_y = y as f64 + (sample as f64 + 0.5) / 4.0;intersections.clear();- for (a, b) in points.iter().zip(points.iter().cycle().skip(1)) {+ for (a, b) in contours.iter().flat_map(|points| points.iter().zip(points.iter().cycle().skip(1))) {if (a.y > scan_y) != (b.y > scan_y) {intersections.push(a.x + (scan_y - a.y) * (b.x - a.x) / (b.y - a.y));}@@ -76,6 +88,19 @@ mod tests {assert!(rasterize_polygon(&points(&[(0.0, 0.0), (8.0, 8.0), (0.0, 8.0), (8.0, 0.0)]), 8, 8).is_ok());}#[test]+ fn compound_masks_preserve_holes_and_disconnected_pieces() {+ let outer = points(&[(1.0, 1.0), (6.0, 1.0), (6.0, 6.0), (1.0, 6.0)]);+ let hole = points(&[(2.0, 2.0), (4.0, 2.0), (4.0, 4.0), (2.0, 4.0)]);+ let island = points(&[(7.0, 0.0), (8.0, 0.0), (8.0, 8.0), (7.0, 8.0)]);+ let mask = rasterize_contours(&[outer.clone(), hole, island], 8, 8).unwrap();+ assert_eq!(mask[3 * 8 + 3], 0);+ assert_eq!(mask[4 * 8 + 4], 255);+ assert_eq!(mask[7 * 8 + 7], 255);+ assert_eq!(mask[7 * 8 + 6], 0);+ assert!(rasterize_contours(&[], 8, 8).is_err());+ assert!(rasterize_contours(&[outer.clone(), outer], 8, 8).is_err());+ }+ #[test]fn rejects_invalid_and_empty_polygons() {for polygon in [points(&[]), points(&[(1.0, 1.0), (2.0, 2.0), (3.0, 3.0)]), points(&[(-1.0, 0.0), (4.0, 0.0), (0.0, 4.0)]), points(&[(f64::NAN, 0.0), (4.0, 0.0), (0.0, 4.0)]), points(&[(0.0, 0.0), (9.0, 0.0), (0.0, 4.0)])] {assert!(rasterize_polygon(&polygon, 8, 8).is_err());diff --git a/src-tauri/core/src/slopfab/h3.rs b/src-tauri/core/src/slopfab/h3.rsindex 1c54d1d..1916d72 100644--- a/src-tauri/core/src/slopfab/h3.rs+++ b/src-tauri/core/src/slopfab/h3.rs@@ -95,6 +95,10 @@ pub(super) fn configure_request(} else {api.set_image_edit_path(handle, request.image_edit_path.as_deref().ok_or("Image edit source has not been resolved.")?, bounds, strength, feather)?;}+ if let Some(contours) = &step.mask_contours {+ let mask = crate::image_mask::rasterize_contours(contours, request.canvas_width, request.canvas_height)?;+ api.set_image_edit_mask(handle, &mask, request.canvas_width, request.canvas_height)?;+ }if let Some(points) = &step.mask_polygon {let mask = crate::image_mask::rasterize_polygon(points, request.canvas_width, request.canvas_height)?;api.set_image_edit_mask(handle, &mask, request.canvas_width, request.canvas_height)?;diff --git a/src-tauri/core/src/slopfab/planning.rs b/src-tauri/core/src/slopfab/planning.rsindex 7bebb64..81ae8f6 100644--- a/src-tauri/core/src/slopfab/planning.rs+++ b/src-tauri/core/src/slopfab/planning.rs@@ -86,6 +86,10 @@ pub(super) fn validate_generation_controls(request: &GenerationRequest) -> Resulreturn Err("Image edits require one source image and nonempty boxes inside its dimensions.".into());}for step in &edit.edits {+ if let Some(contours) = &step.mask_contours {+ if step.invert_mask || step.mask_polygon.is_some() { return Err("Compound lasso masks cannot be combined with another mask.".into()); }+ crate::image_mask::validate_contours(contours, request.canvas_width, request.canvas_height)?;+ }if let Some(points) = &step.mask_polygon {if step.invert_mask { return Err("Lasso masks cannot be combined with rectangular outpainting.".into()); }crate::image_mask::validate_polygon(points, request.canvas_width, request.canvas_height)?;diff --git a/src-tauri/core/src/slopfab/tests.rs b/src-tauri/core/src/slopfab/tests.rsindex 2816d8b..085a03c 100644--- a/src-tauri/core/src/slopfab/tests.rs+++ b/src-tauri/core/src/slopfab/tests.rs@@ -138,7 +138,7 @@ fn image_edit_recipe_disables_motion_cache_and_keeps_source_geometry() {canvas_width: 65, canvas_height: 41,image_edit_pixels: Some(std::sync::Arc::new(vec![100; 65 * 41 * 3])),image_edit: Some(types::ImageEditRequest { source_relative_path: "media/source.png".into(), edits: vec![- types::ImageEditStep { mask_polygon: None, prompt: "A red vase".into(), x: 30, y: 10, width: 35, height: 31, feather: None, strength: None, invert_mask: false, outpaint_blend_overlap: None, outpaint_langevin_steps: None, reference_paths: None, refmods: None }+ types::ImageEditStep { mask_contours: None, mask_polygon: None, prompt: "A red vase".into(), x: 30, y: 10, width: 35, height: 31, feather: None, strength: None, invert_mask: false, outpaint_blend_overlap: None, outpaint_langevin_steps: None, reference_paths: None, refmods: None }] }), ..Default::default()};validate_generation_controls(&request).unwrap();@@ -1556,31 +1556,41 @@ fn moss_cfg_reaches_planning_and_generation_and_h3_rejects_it() {#[test]fn lasso_masks_survive_worker_serialization_and_reach_native_requests() {- let mut request: GenerationRequest = serde_json::from_value(serde_json::json!({- "jobId":"lasso", "prompt":"A flower", "stillImage":true, "frames":1, "steps":4, "seed":1,- "canvasWidth":64, "canvasHeight":32,- "imageEdit":{"sourceRelativePath":"source.png", "edits":[{- "prompt":"A flower", "x":0, "y":0, "width":32, "height":32, "feather":0,- "maskPolygon":[{"x":0,"y":0},{"x":32,"y":0},{"x":0,"y":32}]- }]}- })).unwrap();- let serialized = serde_json::to_value(&request).unwrap();- request = serde_json::from_value(serialized.clone()).unwrap();- assert_eq!(serde_json::to_value(&request).unwrap(), serialized);- validate_generation_controls(&request).unwrap();- request.image_edit_pixels = Some(std::sync::Arc::new(vec![100; 64 * 32 * 3]));- let configuration = Configuration::from_settings(&BTreeMap::new());- let api = ffi::Api::load(&configuration.dll_path).unwrap();- for purpose in [RequestPurpose::Plan, RequestPurpose::Generate] {- let handle = RequestHandle::new(&api).unwrap();- configure_request(&api, &handle, &request, &configuration, ComputePlatform::Vulkan, purpose, &ReferenceVideos::default()).unwrap();- api.resolve(&handle).unwrap();- let description = api.describe(&handle).unwrap();- assert!(description.contains("mask"), "{description}");+ for compound in [false, true] {+ let mut request: GenerationRequest = serde_json::from_value(serde_json::json!({+ "jobId":"lasso", "prompt":"A flower", "stillImage":true, "frames":1, "steps":4, "seed":1,+ "canvasWidth":64, "canvasHeight":32,+ "imageEdit":{"sourceRelativePath":"source.png", "edits":[{+ "prompt":"A flower", "x":0, "y":0, "width":32, "height":32, "feather":0,+ "maskPolygon":[{"x":0,"y":0},{"x":32,"y":0},{"x":0,"y":32}]+ }]}+ })).unwrap();+ if compound {+ let step = &mut request.image_edit.as_mut().unwrap().edits[0];+ step.mask_contours = Some(vec![step.mask_polygon.take().unwrap(), vec![+ crate::image_mask::MaskPoint { x: 2.0, y: 2.0 }, crate::image_mask::MaskPoint { x: 6.0, y: 2.0 }, crate::image_mask::MaskPoint { x: 2.0, y: 6.0 }+ ]]);+ }+ let serialized = serde_json::to_value(&request).unwrap();+ request = serde_json::from_value(serialized.clone()).unwrap();+ assert_eq!(serde_json::to_value(&request).unwrap(), serialized);+ validate_generation_controls(&request).unwrap();+ request.image_edit_pixels = Some(std::sync::Arc::new(vec![100; 64 * 32 * 3]));+ let configuration = Configuration::from_settings(&BTreeMap::new());+ let api = ffi::Api::load(&configuration.dll_path).unwrap();+ for purpose in [RequestPurpose::Plan, RequestPurpose::Generate] {+ let handle = RequestHandle::new(&api).unwrap();+ configure_request(&api, &handle, &request, &configuration, ComputePlatform::Vulkan, purpose, &ReferenceVideos::default()).unwrap();+ api.resolve(&handle).unwrap();+ let description = api.describe(&handle).unwrap();+ assert!(description.contains("mask"), "{description}");+ }+ request.image_edit.as_mut().unwrap().edits[0].invert_mask = true;+ assert!(validate_generation_controls(&request).is_err());+ request.image_edit.as_mut().unwrap().edits[0].invert_mask = false;+ let step = &mut request.image_edit.as_mut().unwrap().edits[0];+ if compound { step.mask_contours.as_mut().unwrap()[0][0].x = -1.0; }+ else { step.mask_polygon.as_mut().unwrap()[0].x = -1.0; }+ assert!(validate_generation_controls(&request).is_err());}- request.image_edit.as_mut().unwrap().edits[0].invert_mask = true;- assert!(validate_generation_controls(&request).is_err());- request.image_edit.as_mut().unwrap().edits[0].invert_mask = false;- request.image_edit.as_mut().unwrap().edits[0].mask_polygon.as_mut().unwrap()[0].x = -1.0;- assert!(validate_generation_controls(&request).is_err());}diff --git a/src-tauri/core/src/slopfab/types.rs b/src-tauri/core/src/slopfab/types.rsindex 5371af4..d5765e5 100644--- a/src-tauri/core/src/slopfab/types.rs+++ b/src-tauri/core/src/slopfab/types.rs@@ -127,6 +127,8 @@ pub struct ImageEditRequest {pub struct ImageEditStep {#[serde(default, skip_serializing_if = "Option::is_none")]pub mask_polygon: Option<Vec<crate::image_mask::MaskPoint>>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub mask_contours: Option<Vec<Vec<crate::image_mask::MaskPoint>>>,pub prompt: String,pub x: i32,pub y: i32,diff --git a/src-tauri/core/src/worker/protocol.rs b/src-tauri/core/src/worker/protocol.rsindex a733539..94bd743 100644--- a/src-tauri/core/src/worker/protocol.rs+++ b/src-tauri/core/src/worker/protocol.rs@@ -9,6 +9,7 @@ use std::collections::BTreeMap;pub const SERVICE_TYPE: &str = "_slopus-worker._tcp.local.";/// Bumped on any incompatible change to the routes or bodies below.+// v13 carries compound lasso masks; older workers would discard holes and splits.// v12 carries lasso image masks; older workers would silently edit the box.// v11 carries image CFG; older workers would silently discard the scale.// v10 carries generation effects; older workers would silently discard them.@@ -18,7 +19,7 @@ pub const SERVICE_TYPE: &str = "_slopus-worker._tcp.local.";// v6 added custom upscale weights.// v5 added overlap locking.// v4 added SeedVR2 export streams. v3 added inverted image masks.-pub const PROTOCOL_VERSION: u32 = 12;+pub const PROTOCOL_VERSION: u32 = 13;/// Streaming SeedVR2 restoration; model paths are resolved on the worker.#[derive(Debug, Clone, Serialize, Deserialize)]diff --git a/src-tauri/src/project/commands/images.rs b/src-tauri/src/project/commands/images.rsindex 0caf855..f1ec319 100644--- a/src-tauri/src/project/commands/images.rs+++ b/src-tauri/src/project/commands/images.rs@@ -29,7 +29,7 @@ pub(super) fn new_scene(prompt: &str) -> ImageScene {source_image: None,output_size: None,nodes: vec![ImageNode {- lasso: None,+ lasso: None, lasso_contours: None,id: "image-root".into(),parent_id: None,kind: "root".into(),@@ -243,7 +243,7 @@ pub(super) fn apply(return Err("New image nodes must be objects, text, groups or backgrounds.".into());}let node = ImageNode {- lasso: None,+ lasso: None, lasso_contours: None,id: id.clone(),parent_id: Some(parent.clone()),kind: kind.clone(),diff --git a/src-tauri/src/project/image.rs b/src-tauri/src/project/image.rsindex 9827c12..3f1526e 100644--- a/src-tauri/src/project/image.rs+++ b/src-tauri/src/project/image.rs@@ -111,6 +111,8 @@ pub struct ImageNode {pub r#box: Option<ImageBox>,#[serde(default, skip_serializing_if = "Option::is_none")]pub lasso: Option<Vec<slopus_core::image_mask::MaskPoint>>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub lasso_contours: Option<Vec<Vec<slopus_core::image_mask::MaskPoint>>>,pub colors: Vec<String>,}#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]@@ -209,9 +211,15 @@ impl ImageScene {{return Err("Invalid image node.".into());}+ if node.lasso_contours.is_some() && node.lasso.is_none() { return Err("Lasso contours require an outline.".into()); }if let Some(points) = &node.lasso {if node.kind != "object" || node.r#box.is_none() { return Err("Lasso regions require an edit node and placement box.".into()); }- slopus_core::image_mask::validate_polygon(points, 1000, 1000)?;+ let mut contours = vec![points.clone()];+ if let Some(additional) = &node.lasso_contours {+ if additional.is_empty() { return Err("Additional lasso contours must not be empty.".into()); }+ contours.extend(additional.iter().cloned());+ }+ slopus_core::image_mask::validate_contours(&contours, 1000, 1000)?;}if let Some(b) = &node.r#box {if ![b.x, b.y, b.width, b.height].iter().all(|v| v.is_finite())diff --git a/src-tauri/src/tests/images.rs b/src-tauri/src/tests/images.rsindex 85df2e3..4796289 100644--- a/src-tauri/src/tests/images.rs+++ b/src-tauri/src/tests/images.rs@@ -33,7 +33,8 @@ fn image_editing_draft_survives_save_and_reopen() {snapshot["scene"]["outputSize"] = serde_json::json!({"width":128,"height":64});snapshot["scene"]["nodes"].as_array_mut().unwrap().push(serde_json::json!({"id":"lasso", "parentId":"image-root", "kind":"object", "name":"Lasso", "description":"A flower", "text":"", "colors":[],- "box":{"x":100,"y":200,"width":300,"height":400}, "lasso":[{"x":0,"y":0},{"x":1000,"y":0},{"x":0,"y":1000}]+ "box":{"x":100,"y":200,"width":300,"height":400}, "lasso":[{"x":0,"y":0},{"x":1000,"y":0},{"x":0,"y":1000}],+ "lassoContours":[[{"x":100,"y":100},{"x":200,"y":100},{"x":100,"y":200}]]}));config.assets.push(serde_json::from_value(serde_json::json!({"id":"draft", "kind":"image", "name":"Editing Source", "relativePath":"media/imported/source.png", "mimeType":"image/png",diff --git a/src/components/ui/icons.tsx b/src/components/ui/icons.tsxindex 5d0326f..feaeba5 100644--- a/src/components/ui/icons.tsx+++ b/src/components/ui/icons.tsx@@ -78,6 +78,7 @@ export { Save16Regular as Save16 } from "@fluentui/react-icons/headless/svg/saveexport { ScanDash16Regular as SafeArea16, ScanDash16Filled as SafeArea16Filled } from "@fluentui/react-icons/headless/svg/scan-dash";export { Search16Regular as Search16, Search32Regular as Search32 } from "@fluentui/react-icons/headless/svg/search";export { SelectObject16Regular as Boxes16, SelectObject16Filled as Boxes16Filled } from "@fluentui/react-icons/headless/svg/select-object";+export { Square16Regular as EditBox16 } from "@fluentui/react-icons/headless/svg/square";export { Send16Regular as Send16 } from "@fluentui/react-icons/headless/svg/send";export { Server16Regular as Worker16, Server16Filled as Worker16Filled, Server20Regular as Worker20 } from "@fluentui/react-icons/headless/svg/server";export { Settings16Regular as Settings16 } from "@fluentui/react-icons/headless/svg/settings";diff --git a/src/components/workspace/ImageEditor.test.tsx b/src/components/workspace/ImageEditor.test.tsxindex f00fc63..a32da21 100644--- a/src/components/workspace/ImageEditor.test.tsx+++ b/src/components/workspace/ImageEditor.test.tsx@@ -76,7 +76,7 @@ it("offers MOSS for new images and disables editing and reference templates", ()initial.imageScene = { ...createImageEditScene(source, initial.imageScene), outputAssetId: source.id };setup(initial);expect(screen.getByRole("button", { name: "Generate" })).toBeDisabled();- expect(screen.getByRole("radio", { name: "Draw edit" })).toBeDisabled();+ expect(screen.getByRole("radio", { name: "Edit Box" })).toBeDisabled();expect(screen.getByRole("status")).toHaveTextContent("MOSS Image does not support image editing");fireEvent.click(screen.getByRole("button", { name: "Template" }));expect(screen.getByRole("menuitem", { name: "Zoom" })).toBeDisabled();@@ -455,7 +455,7 @@ it("adds image files in edit mode and saves whole-image and drawn edits with sepfor (const key of ["o", "t", "g"]) fireEvent.keyDown(canvas, { key });expect(screen.getByRole("radio", { name: "Select" })).toHaveAttribute("aria-checked", "true");fireEvent.keyDown(canvas, { key: "e" });- expect(screen.getByRole("radio", { name: "Draw edit" })).toHaveAttribute("aria-checked", "true");+ expect(screen.getByRole("radio", { name: "Edit Box" })).toHaveAttribute("aria-checked", "true");pointer("pointerDown", 100, 80); pointer("pointerMove", 400, 320); pointer("pointerUp", 400, 320);expect(current().imageScene!.nodes[1]).toMatchObject({ name: "Edit", box: { x: 100, y: 100, width: 300, height: 300 } });expect(screen.queryByText("Placement (0–1000)")).not.toBeInTheDocument();@@ -492,7 +492,7 @@ it("starts an image root from the thumbnail Edit menu with edit tools and no typexpect(screen.queryByLabelText("Prompt (high-level description)")).not.toBeInTheDocument();expect(screen.queryByRole("combobox", { name: "Type" })).not.toBeInTheDocument();expect(promptValue(screen.getByLabelText("Edit prompt"))).toBe("");- expect(within(screen.getByRole("radiogroup", { name: "Canvas tool" })).getAllByRole("radio").map((tool) => tool.getAttribute("aria-label"))).toEqual(["Select", "Draw edit", "Lasso"]);+ expect(within(screen.getByRole("radiogroup", { name: "Canvas tool" })).getAllByRole("radio").map((tool) => tool.getAttribute("aria-label"))).toEqual(["Select", "Edit Box", "Lasso"]);const draft = screen.getByRole("button", { name: "View Editing Saved" });expect(draft).toHaveAttribute("aria-pressed", "true");fireEvent.contextMenu(screen.getByRole("button", { name: "Image" }));@@ -1173,7 +1173,7 @@ it("draws a lasso, edits its prompt, moves its outline, and saves it independentexpect(lasso).toMatchObject({ name: "Lasso", box: { x: 100, y: 100, width: 300, height: 300 }, lasso: [{ x: 0, y: 0 }, { x: 1000, y: 0 }, { x: 0, y: 1000 }] });typePrompt(screen.getByLabelText("Edit prompt"), "Add a red flower");fireEvent.click(screen.getByRole("button", { name: "Image" }));- const outline = canvas.querySelector("polygon[data-node]")!;+ const outline = canvas.querySelector("path[data-node]")!;pointer("pointerDown", 150, 120, outline); pointer("pointerMove", 250, 200); pointer("pointerUp", 250, 200);expect(current().imageScene!.nodes[1]).toMatchObject({ box: { x: 200, y: 200, width: 300, height: 300 }, lasso: lasso.lasso, description: "Add a red flower" });expect(promptValue(screen.getByLabelText("Edit prompt"))).toBe("Add a red flower");@@ -1211,3 +1211,50 @@ it.each(["queued", "generating", "encoding"] as const)("keeps the edit source viexpect(screen.queryByRole("progressbar", { name: "Image generation progress" })).not.toBeInTheDocument();expect(completed.assets[0]).toEqual(source);});++it("combines and subtracts lassos using release-time modifiers and shows matching cursors", () => {+ const initial = parseProjectConfig(fixture);+ initial.imageScene = createImageEditScene({ name: "Source", relativePath: "media/source.png", width: 1000, height: 1000 });+ const current = setup(initial);+ const canvas = screen.getByLabelText("Image placement canvas");+ Object.defineProperty(canvas, "setPointerCapture", { value: vi.fn() });+ Object.defineProperty(canvas, "getBoundingClientRect", { value: () => ({ left: 0, top: 0, width: 1000, height: 1000 }) });+ const pointer = (type: "pointerDown" | "pointerMove" | "pointerUp", x: number, y: number, ctrlKey = false, altKey = false) => {+ const event = createEvent[type](canvas);+ Object.defineProperties(event, { button: { value: 0 }, pointerId: { value: 1 }, clientX: { value: x }, clientY: { value: y }, ctrlKey: { value: ctrlKey }, altKey: { value: altKey } });+ fireEvent(canvas, event);+ };+ const rectangle = (x: number, y: number, width: number, height: number, modifier?: "Control" | "Alt") => {+ fireEvent.click(screen.getByRole("radio", { name: "Lasso" }));+ pointer("pointerDown", x, y); pointer("pointerMove", x + width, y); pointer("pointerMove", x + width, y + height);+ if (modifier) fireEvent.keyDown(window, { key: modifier, ctrlKey: modifier === "Control", altKey: modifier === "Alt" });+ pointer("pointerUp", x, y + height, modifier === "Control", modifier === "Alt");+ };+ rectangle(100, 100, 300, 300);+ const originalId = current().imageScene!.nodes[1].id;+ typePrompt(screen.getByLabelText("Edit prompt"), "Red flower");+ rectangle(300, 100, 300, 300, "Control");+ expect(current().imageScene!.nodes).toHaveLength(2);+ expect(current().imageScene!.nodes[1]).toMatchObject({ id: originalId, description: "Red flower", box: { x: 100, y: 100, width: 500, height: 300 } });+ expect(canvas).toHaveClass("lasso-add");+ fireEvent.keyUp(window, { key: "Control", ctrlKey: false });+ expect(canvas).not.toHaveClass("lasso-add");+ rectangle(200, 200, 100, 100, "Alt");+ expect(canvas).toHaveClass("lasso-subtract");+ expect(current().imageScene!.nodes[1].lassoContours).toHaveLength(1);+ expect(canvas.querySelector("path[data-node]")!.getAttribute("d")!.match(/M/g)).toHaveLength(2);+ const withHole = current().imageScene;+ fireEvent.keyUp(window, { key: "Alt", altKey: false });+ rectangle(800, 800, 100, 100, "Alt");+ expect(current().imageScene).toEqual(withHole);+ fireEvent.keyUp(window, { key: "Alt", altKey: false });+ undoImageEdit();+ expect(current().imageScene!.nodes[1].lassoContours).toBeUndefined();+ fireEvent.keyDown(screen.getByRole("tree", { name: "Image nodes" }), { key: "y", code: "KeyY", ctrlKey: true });+ expect(current().imageScene!.nodes[1].lassoContours).toHaveLength(1);+ rectangle(800, 800, 100, 100, "Control");+ expect(current().imageScene!.nodes).toHaveLength(3);+ fireEvent.blur(window);+ expect(canvas).not.toHaveClass("lasso-add");+ expect(parseProjectConfig(JSON.parse(JSON.stringify(current()))).imageScene).toEqual(current().imageScene);+});diff --git a/src/components/workspace/ImageEditor.tsx b/src/components/workspace/ImageEditor.tsxindex 69ccdbf..2f67e3d 100644--- a/src/components/workspace/ImageEditor.tsx+++ b/src/components/workspace/ImageEditor.tsx@@ -1,9 +1,11 @@import { activeGenerationEffects } from "../../lib/generationEffects";import { GenerationEffects } from "./GenerationEffects";+import { applyLassoStroke } from "../../lib/imageLasso";+import { EditBox16 } from "../ui/icons";import { useEffect, useId, useMemo, useRef, useState, useSyncExternalStore, type CSSProperties, type DragEvent, type KeyboardEvent as ReactKeyboardEvent, type PointerEvent } from "react";import { Add14, Add16, Boxes16, Boxes16Filled, ChevronDown14, ChevronRight14, Copy16, Cube16, Cube16Filled, Cursor16, Cursor16Filled, Delete14, Delete16, Edit16, Film16, FolderAdd16, FolderOpen16, Group16, Group16Filled, Image16, Image32, Lasso16, Paste16, References16, Rename16, Sparkle16, Stop14, Text16, Text16Filled } from "../ui/icons";import { invoke } from "@tauri-apps/api/core";-import { addImageNode, createImageEditScene, createImageScene, duplicateImageNode, imageDescendants, imageScenePrompt, imageLassoPoints, imageLassoSchema, simplifyImageLasso, removeImageNode, resizeImageNode, type ImageBox, type ImageNode, type ImageScene, type ImageSource, type ImagePoint } from "../../lib/imageScene";+import { addImageNode, createImageEditScene, createImageScene, duplicateImageNode, imageDescendants, imageScenePrompt, imageLassoPath, imageLassoSchema, simplifyImageLasso, removeImageNode, resizeImageNode, type ImageBox, type ImageNode, type ImageScene, type ImageSource, type ImagePoint } from "../../lib/imageScene";import { compileImageEdits, editGeneratedImage, imageEditDebugPrompt, imageEditOutputSize, imageEditSize } from "../../lib/imageEditing";import { imageSettings } from "../../lib/imageSettings";import { outputDimensions } from "../../lib/export";@@ -129,6 +131,14 @@ export function ImageEditor({ config, folderPath, onChange: changeConfig, onGeneconst [panning, setPanning] = useState(false);const [draftBox, setDraftBox] = useState<ImageBox | null>(null);const [draftLasso, setDraftLasso] = useState<ImagePoint[] | null>(null);+ const [lassoModifier, setLassoModifier] = useState<"" | "add" | "subtract">("");+ const updateLassoModifier = (event: { altKey: boolean; ctrlKey: boolean }) => setLassoModifier(event.altKey ? "subtract" : event.ctrlKey ? "add" : "");+ useEffect(() => {+ if (drawKind !== "lasso") { setLassoModifier(""); return; }+ const reset = () => setLassoModifier("");+ window.addEventListener("keydown", updateLassoModifier); window.addEventListener("keyup", updateLassoModifier); window.addEventListener("blur", reset);+ return () => { window.removeEventListener("keydown", updateLassoModifier); window.removeEventListener("keyup", updateLassoModifier); window.removeEventListener("blur", reset); };+ }, [drawKind]);const undo = useRef<ImageScene[]>([]);const redo = useRef<ImageScene[]>([]);const [, historyChanged] = useState(0);@@ -208,11 +218,11 @@ export function ImageEditor({ config, folderPath, onChange: changeConfig, onGene};const patchNode = (patch: Partial<ImageNode>) => commit({ ...scene, nodes: scene.nodes.map((node) => node.id === selected.id ? { ...node, ...patch } : node) });const insertParent = selected.kind === "object" || selected.kind === "text" ? selected.parentId ?? root.id : selected.id;- const add = (kind: Exclude<ImageNode["kind"], "root">, box?: ImageBox, lasso?: ImagePoint[]) => {+ const add = (kind: Exclude<ImageNode["kind"], "root">, box?: ImageBox) => {if (imageRoot && editingBlocked) return;const parent = imageRoot ? root.id : insertParent;const next = addImageNode(scene, parent, imageRoot ? "object" : kind, box);- if (imageRoot) Object.assign(next.nodes.at(-1)!, { name: lasso ? "Lasso" : "Edit", ...(lasso ? { lasso } : {}) });+ if (imageRoot) Object.assign(next.nodes.at(-1)!, { name: "Edit" });commit(next); setSelection(next.nodes.at(-1)!.id);setCollapsed((current) => { const next = new Set(current); next.delete(parent); return next; });};@@ -362,6 +372,7 @@ export function ImageEditor({ config, folderPath, onChange: changeConfig, onGeneevent.currentTarget.setPointerCapture(event.pointerId);};const pointerMove = (event: PointerEvent<SVGSVGElement>) => {+ if (drawKind === "lasso") updateLassoModifier(event);const start = pointer.current; if (!start) return;const at = point(event);if (!Number.isFinite(at.x) || !Number.isFinite(at.y)) return;@@ -388,8 +399,13 @@ export function ImageEditor({ config, folderPath, onChange: changeConfig, onGeneconst x = Math.min(...points.map((point) => point.x)), y = Math.min(...points.map((point) => point.y));const width = Math.max(...points.map((point) => point.x)) - x, height = Math.max(...points.map((point) => point.y)) - y;if (imageLassoSchema.safeParse(points).success && width >= 5 && height >= 5) {- add("object", { x, y, width, height }, points.map((point) => ({ x: Math.max(0, Math.min(1000, (point.x - x) / width * 1000)), y: Math.max(0, Math.min(1000, (point.y - y) / height * 1000)) })));- setDrawKind(null);+ attempt(() => {+ const mode = event.altKey ? "subtract" : event.ctrlKey ? "add" : "new";+ const result = applyLassoStroke(start.scene, points, mode, selected.id);+ commit(result.scene); setSelection(result.id);+ setCollapsed((current) => { const next = new Set(current); next.delete(root.id); return next; });+ if (mode === "new") setDrawKind(null);+ });}} else if (start?.box && start.box.width > 0 && start.box.height > 0) {if (start.id) commit(resizeImageNode(start.scene, start.id, start.box));@@ -467,7 +483,7 @@ export function ImageEditor({ config, folderPath, onChange: changeConfig, onGene/* Canvas tools: a radio group of icon toggles with one-letter keys. */const TOOLS = [{ id: null, label: "Select", key: "V", icon: <Cursor16 />, onIcon: <Cursor16Filled /> },- ...(imageRoot ? [{ id: "object", label: "Draw edit", key: "E", icon: <Edit16 />, onIcon: <Edit16 /> },+ ...(imageRoot ? [{ id: "object", label: "Edit Box", key: "E", icon: <EditBox16 />, onIcon: <EditBox16 /> },{ id: "lasso", label: "Lasso", key: "L", icon: <Lasso16 />, onIcon: <Lasso16 /> }] as const : [{ id: "object", label: "Draw object", key: "O", icon: <Cube16 />, onIcon: <Cube16Filled /> },{ id: "text", label: "Draw text", key: "T", icon: <Text16 />, onIcon: <Text16Filled /> },@@ -627,7 +643,7 @@ export function ImageEditor({ config, folderPath, onChange: changeConfig, onGenearia-keyshortcuts={tool.key}tabIndex={drawKind === tool.id ? 0 : -1}className={`image-tool${drawKind === tool.id ? " image-tool--on" : ""}`}- {...tooltipProps(tool.label, tool.key)}+ {...tooltipProps(tool.id === "lasso" ? "Lasso: Ctrl to combine, Alt to subtract" : tool.label, tool.key)}onClick={() => chooseTool(tool.id)}><span aria-hidden="true">{drawKind === tool.id ? tool.onIcon : tool.icon}</span></button>)}</div>@@ -735,10 +751,10 @@ export function ImageEditor({ config, folderPath, onChange: changeConfig, onGeneonAuxClick={(event) => { if (event.button === 1) event.preventDefault(); }}><div className="image-frame" style={{ "--image-ratio": width / height, "--image-zoom": view.zoom, "--image-pan-x": `${view.x}px`, "--image-pan-y": `${view.y}px` } as CSSProperties}>{active && output?.imageDraft && !(imageRoot && scene.sourceImage) ? <div className="image-empty" role="status"><Image32 aria-hidden="true" /><strong>{work.status === "queued" ? "Queued" : "Generating"}</strong><span>The generated image will appear here.</span></div> : showResult ? <ReferenceImage key={output!.id} folderPath={folderPath} relativePath={output!.relativePath} sourcePath={output!.sourcePath} alt={output!.name} /> : imageRoot && scene.sourceImage ? <ReferenceImage folderPath={folderPath} relativePath={scene.sourceImage.relativePath} alt={scene.sourceImage.name} /> : output && !imageRoot && (output.relativePath || output.sourcePath) ? <ReferenceImage key={output.id} folderPath={folderPath} relativePath={output.relativePath} sourcePath={output.sourcePath} alt={output.name} onMeasured={!output.imageGeneration ? (size) => measureImportedImage(output.id, size) : undefined} /> : <div className="image-empty"><Image32 aria-hidden="true" /><strong>{templateSnapshot ? output!.name : imageRoot ? "Add an image to edit" : "Compose your image"}</strong><span>{templateSnapshot ? active ? "The generated image will appear here." : "No generated image yet." : imageRoot ? "Choose Add image file in the image bar menu, then enter an edit prompt." : "Add objects, text and groups, then describe them in the inspector."}</span></div>}- <svg className={`image-overlay ${drawKind ? "drawing" : ""}`} viewBox="0 0 1000 1000" preserveAspectRatio="none" aria-label="Image placement canvas" onPointerDown={pointerDown} onPointerMove={pointerMove} onPointerUp={pointerUp} onPointerCancel={() => { pointer.current = null; setDraftBox(null); setDraftLasso(null); }}>+ <svg className={`image-overlay ${drawKind ? "drawing" : ""} ${drawKind === "lasso" && lassoModifier ? `lasso-${lassoModifier}` : ""}`} viewBox="0 0 1000 1000" preserveAspectRatio="none" aria-label="Image placement canvas" onPointerEnter={(event) => { if (drawKind === "lasso") updateLassoModifier(event); }} onPointerDown={pointerDown} onPointerMove={pointerMove} onPointerUp={pointerUp} onPointerCancel={() => { pointer.current = null; setDraftBox(null); setDraftLasso(null); }}>{boxes && scene.nodes.filter((node) => node.box).map((node) => {const box = pointer.current?.id === node.id && draftBox ? draftBox : node.box!;- return <g key={node.id} className={selected.id === node.id ? "selected" : ""}>{node.lasso ? <polygon data-node={node.id} points={imageLassoPoints(node, box).map(({ x, y }) => `${x},${y}`).join(" ")} fillRule="evenodd" vectorEffect="non-scaling-stroke" /> : <rect data-node={node.id} x={box.x} y={box.y} width={box.width} height={box.height} vectorEffect="non-scaling-stroke" />}{selected.id === node.id && !node.lasso && <rect className="image-box-handle" data-node={node.id} data-resize="true" x={box.x + box.width - 16} y={box.y + box.height - 16} width="16" height="16" />}</g>;+ return <g key={node.id} className={selected.id === node.id ? "selected" : ""}>{node.lasso ? <path data-node={node.id} d={imageLassoPath(node, box)} fillRule="evenodd" vectorEffect="non-scaling-stroke" /> : <rect data-node={node.id} x={box.x} y={box.y} width={box.width} height={box.height} vectorEffect="non-scaling-stroke" />}{selected.id === node.id && !node.lasso && <rect className="image-box-handle" data-node={node.id} data-resize="true" x={box.x + box.width - 16} y={box.y + box.height - 16} width="16" height="16" />}</g>;})}{draftLasso && <polygon className="image-box-draft" points={draftLasso.map(({ x, y }) => `${x},${y}`).join(" ")} fillRule="evenodd" vectorEffect="non-scaling-stroke" />}{draftBox && !pointer.current?.id && <rect className="image-box-draft" {...{ x: draftBox.x, y: draftBox.y, width: draftBox.width, height: draftBox.height }} />}diff --git a/src/lib/imageEditing.ts b/src/lib/imageEditing.tsindex c313505..54b5c85 100644--- a/src/lib/imageEditing.ts+++ b/src/lib/imageEditing.ts@@ -1,5 +1,5 @@import { imageSettings } from "./imageSettings";-import { createImageEditScene, createImageScene, imageLassoPoints, imageSourceSchema, type ImageNode, type ImageScene, type ImageSource, type ImagePoint } from "./imageScene";+import { createImageEditScene, createImageScene, imageLassoContours, imageSourceSchema, type ImageNode, type ImageScene, type ImageSource, type ImagePoint } from "./imageScene";import { compileImagePrompt } from "./imagePrompt";import type { ProjectConfig, ProjectReference } from "./project";@@ -8,6 +8,7 @@ export interface ImageEditStep {feather?: number;/** Pixel-space polygon, rasterized to a source-sized mask by the runtime. */maskPolygon?: ImagePoint[];+ maskContours?: ImagePoint[][];/** Denoising strength; lower values retain more of the source detail. */strength?: number;/** Preserve this box and generate its surround in a single outpainting pass. */@@ -51,8 +52,9 @@ export function compileImageEdits(config: ProjectConfig): { source: ImageSource;const compiled = compileImagePrompt({ ...config, imageSettings: { ...imageSettings(config), defaultLook: null }, imageScene: editScene });// A full-canvas edit has no surrounding source to blend into at its edges.const wholeImage = x === 0 && y === 0 && right === size.width && bottom === size.height;+ const contours = imageLassoContours(node).map((points) => points.map(({ x, y }) => ({ x: x * size.width / 1000, y: y * size.height / 1000 })));return { prompt: compiled.prompt, references: compiled.references, x, y, width: Math.max(1, right - x), height: Math.max(1, bottom - y),- ...(node.lasso ? { maskPolygon: imageLassoPoints(node).map(({ x, y }) => ({ x: x * size.width / 1000, y: y * size.height / 1000 })), feather: 0 } : wholeImage ? { feather: 0 } : {}) };+ ...(node.lasso ? { ...(contours.length > 1 ? { maskContours: contours } : { maskPolygon: contours[0] }), feather: 0 } : wholeImage ? { feather: 0 } : {}) };});if (!edits.length) throw new Error("Enter a whole-image edit prompt or add an Edit node before generating.");return { source, edits };diff --git a/src/lib/imageLasso.test.ts b/src/lib/imageLasso.test.tsnew file mode 100644index 0000000..50bb416--- /dev/null+++ b/src/lib/imageLasso.test.ts@@ -0,0 +1,72 @@+import { expect, it } from "vitest";+import { applyLassoStroke } from "./imageLasso";+import { createImageEditScene, imageLassoContours, imageSceneSchema, resizeImageNode, type ImageNode, type ImagePoint } from "./imageScene";+import { compileImageEdits } from "./imageEditing";+import { parseProjectConfig } from "./project";+import fixture from "../../fixtures/project-v1-image.json";++const rect = (x: number, y: number, width: number, height: number): ImagePoint[] => [{ x, y }, { x: x + width, y }, { x: x + width, y: y + height }, { x, y: y + height }];+const empty = () => createImageEditScene({ name: "Source", relativePath: "media/source.png", width: 1000, height: 1000 });+const contains = (node: ImageNode, x: number, y: number) => imageLassoContours(node).reduce((inside, ring) => ring.reduce((hit, a, index) => {+ const b = ring[(index + 1) % ring.length];+ return (a.y > y) !== (b.y > y) && x < a.x + (y - a.y) * (b.x - a.x) / (b.y - a.y) ? !hit : hit;+}, inside), false);++it("unions overlapping lassos, preserves prompts, and leaves a disjoint addition separate", () => {+ let result = applyLassoStroke(empty(), rect(100, 100, 300, 300), "new", "image-root");+ const firstId = result.id;+ result.scene.nodes[1].description = "Red flower";+ result = applyLassoStroke(result.scene, rect(500, 100, 200, 300), "add", firstId);+ expect(result.scene.nodes).toHaveLength(3);+ result.scene.nodes[2].description = "Green leaves";+ result = applyLassoStroke(result.scene, rect(300, 200, 300, 100), "add", firstId);+ expect(result.id).toBe(firstId);+ expect(result.scene.nodes).toHaveLength(2);+ expect(result.scene.nodes[1].description).toBe("Red flower\nGreen leaves");+ expect(contains(result.scene.nodes[1], 450, 250)).toBe(true);+ expect(contains(result.scene.nodes[1], 450, 150)).toBe(false);+});++it("subtracts holes, splits and full coverage, and ignores non-overlap including holes", () => {+ const original = applyLassoStroke(empty(), rect(100, 100, 600, 600), "new", "image-root");+ const hole = applyLassoStroke(original.scene, rect(200, 200, 100, 100), "subtract", original.id);+ expect(hole.scene.nodes[1].lassoContours).toHaveLength(1);+ expect(contains(hole.scene.nodes[1], 250, 250)).toBe(false);+ expect(contains(hole.scene.nodes[1], 150, 150)).toBe(true);+ const miss = applyLassoStroke(hole.scene, rect(220, 220, 10, 10), "subtract", hole.id);+ expect(miss.scene).toBe(hole.scene);+ const split = applyLassoStroke(hole.scene, rect(400, 0, 100, 800), "subtract", hole.id);+ expect(split.scene.nodes).toHaveLength(2);+ expect(contains(split.scene.nodes[1], 450, 150)).toBe(false);+ expect(contains(split.scene.nodes[1], 600, 150)).toBe(true);+ const gone = applyLassoStroke(split.scene, rect(0, 0, 1000, 1000), "subtract", split.id);+ expect(gone.scene.nodes).toHaveLength(1);+ expect(gone.id).toBe("image-root");+});++it("uses actual areas instead of bounding-box overlap and handles edge contact and self intersections", () => {+ const triangle = applyLassoStroke(empty(), [{ x: 100, y: 100 }, { x: 600, y: 100 }, { x: 100, y: 600 }], "new", "image-root");+ expect(applyLassoStroke(triangle.scene, rect(450, 450, 100, 100), "add", triangle.id).scene.nodes).toHaveLength(3);+ expect(applyLassoStroke(triangle.scene, rect(450, 450, 100, 100), "subtract", triangle.id).scene).toBe(triangle.scene);+ const box = applyLassoStroke(empty(), rect(100, 100, 100, 100), "new", "image-root");+ expect(applyLassoStroke(box.scene, rect(200, 100, 100, 100), "add", box.id).scene.nodes).toHaveLength(3);+ const crossed = applyLassoStroke(empty(), [{ x: 100, y: 100 }, { x: 500, y: 500 }, { x: 100, y: 500 }, { x: 500, y: 100 }], "new", "image-root");+ expect(applyLassoStroke(crossed.scene, rect(200, 80, 100, 80), "add", crossed.id).scene.nodes).toHaveLength(2);+});++it("moves, saves and compiles compound masks with their holes intact", () => {+ let result = applyLassoStroke(empty(), rect(100, 100, 400, 400), "new", "image-root");+ result = applyLassoStroke(result.scene, rect(200, 200, 100, 100), "subtract", result.id);+ result.scene.nodes[1].description = "Flower";+ const moved = resizeImageNode(result.scene, result.id, { x: 200, y: 300, width: 400, height: 400 });+ const restored = imageSceneSchema.parse(JSON.parse(JSON.stringify(moved)));+ expect(contains(restored.nodes[1], 350, 450)).toBe(false);+ expect(contains(restored.nodes[1], 250, 350)).toBe(true);+ const config = parseProjectConfig(fixture);+ config.imageScene = { ...restored, outputSize: { width: 512, height: 512 } };+ const edit = compileImageEdits(config).edits[0];+ expect(edit.maskContours).toHaveLength(2);+ expect(edit.maskPolygon).toBeUndefined();+ expect(edit.feather).toBe(0);+ expect(imageSceneSchema.safeParse({ ...moved, nodes: moved.nodes.map((node) => ({ ...node, lasso: undefined })) }).success).toBe(false);+});diff --git a/src/lib/imageLasso.ts b/src/lib/imageLasso.tsnew file mode 100644index 0000000..cc61f4d--- /dev/null+++ b/src/lib/imageLasso.ts@@ -0,0 +1,64 @@+import ClipperLib from "clipper-lib";+import { imageLassoContours, imageSceneSchema, type ImageNode, type ImagePoint, type ImageScene } from "./imageScene";++// Integer clipping retains subpixel accuracy even at the largest output size.+const SCALE = 10000;+function clip(subject: ImagePoint[][], operand: ImagePoint[][], operation: ClipperLib.ClipType): ImagePoint[][] {+ const paths = (contours: ImagePoint[][]) => contours.map((points) => points.map(({ x, y }) => ({ X: Math.round(x * SCALE), Y: Math.round(y * SCALE) })));+ const engine = new ClipperLib.Clipper();+ engine.StrictlySimple = true;+ engine.AddPaths(paths(subject), ClipperLib.PolyType.ptSubject, true);+ engine.AddPaths(paths(operand), ClipperLib.PolyType.ptClip, true);+ const result: ClipperLib.Paths = [];+ if (!engine.Execute(operation, result, ClipperLib.PolyFillType.pftEvenOdd, ClipperLib.PolyFillType.pftEvenOdd)) throw new Error("Could not combine these lasso areas.");+ return result.map((points) => points.map(({ X, Y }) => ({ x: X / SCALE, y: Y / SCALE })));+}++function shape(contours: ImagePoint[][]): Pick<ImageNode, "box" | "lasso" | "lassoContours"> {+ const points = contours.flat();+ const x = Math.min(...points.map((point) => point.x)), y = Math.min(...points.map((point) => point.y));+ const width = Math.max(...points.map((point) => point.x)) - x, height = Math.max(...points.map((point) => point.y)) - y;+ const normalized = contours.map((ring) => ring.map((point) => ({ x: Math.max(0, Math.min(1000, (point.x - x) / width * 1000)), y: Math.max(0, Math.min(1000, (point.y - y) / height * 1000)) })));+ return { box: { x, y, width, height }, lasso: normalized[0], lassoContours: normalized.length > 1 ? normalized.slice(1) : undefined };+}++/** One atomic scene edit, including holes/splits and preservation of authored prompts. */+export function applyLassoStroke(scene: ImageScene, points: ImagePoint[], mode: "new" | "add" | "subtract", selectedId: string): { scene: ImageScene; id: string } {+ const root = scene.nodes.find((node) => node.kind === "root")!;+ const stroke = clip([points], [], ClipperLib.ClipType.ctUnion);+ if (!stroke.length) return { scene, id: selectedId };+ const overlaps = mode === "new" ? [] : scene.nodes.filter((node) => node.lasso && clip(imageLassoContours(node), stroke, ClipperLib.ClipType.ctIntersection).length);+ if (!overlaps.length) {+ if (mode === "subtract") return { scene, id: selectedId };+ const node: ImageNode = { id: crypto.randomUUID(), parentId: root.id, kind: "object", name: "Lasso", description: "", text: "", colors: [], ...shape(mode === "new" ? [points] : stroke) };+ return { scene: imageSceneSchema.parse({ ...scene, nodes: [...scene.nodes, node] }), id: node.id };+ }+ const removed = new Map<string, string>();+ const replacements = new Map<string, ImageNode>();+ let id = selectedId;+ if (mode === "add") {+ const target = overlaps.find((node) => node.id === selectedId) ?? overlaps[0];+ let combined = stroke;+ for (const node of overlaps) combined = clip(combined, imageLassoContours(node), ClipperLib.ClipType.ctUnion);+ const ordered = [target, ...overlaps.filter((node) => node !== target)];+ replacements.set(target.id, { ...target, ...shape(combined), description: [...new Set(ordered.map((node) => node.description.trim()).filter(Boolean))].join("\n"),+ referenceIds: [...new Set(ordered.flatMap((node) => node.referenceIds ?? []))] });+ for (const node of overlaps) if (node !== target) removed.set(node.id, target.id);+ id = target.id;+ } else {+ for (const node of overlaps) {+ const remaining = clip(imageLassoContours(node), stroke, ClipperLib.ClipType.ctDifference);+ if (remaining.length) replacements.set(node.id, { ...node, ...shape(remaining) });+ else removed.set(node.id, node.parentId ?? root.id);+ }+ id = replacements.has(selectedId) ? selectedId : replacements.keys().next().value ?? root.id;+ }+ const nodes = scene.nodes.filter((node) => !removed.has(node.id)).map((node) => {+ const updated = replacements.get(node.id) ?? node;+ let parentId = updated.parentId;+ const visited = new Set<string>();+ while (parentId && removed.has(parentId) && !visited.has(parentId)) { visited.add(parentId); parentId = removed.get(parentId)!; }+ return parentId === updated.parentId ? updated : { ...updated, parentId };+ });+ return { scene: imageSceneSchema.parse({ ...scene, nodes }), id };+}diff --git a/src/lib/imageScene.ts b/src/lib/imageScene.tsindex 54cdc7d..f4fc1d8 100644--- a/src/lib/imageScene.ts+++ b/src/lib/imageScene.ts@@ -15,6 +15,8 @@ export const imageNodeSchema = z.object({name: z.string().min(1).max(120), description: z.string(), text: z.string(),referenceIds: z.array(z.string().min(1)).max(100).optional(),lasso: imageLassoSchema.optional(),+ /** Additional contours, including holes and disconnected pieces; filled even-odd. */+ lassoContours: z.array(imageLassoSchema).min(1).max(255).optional(),box: boxSchema.nullable(), colors: z.array(z.string().regex(/^#[0-9a-fA-F]{6}$/)).max(16),});export const imageSourceSchema = z.object({@@ -38,7 +40,8 @@ export const imageSceneSchema = z.object({const ids = new Map(scene.nodes.map((node) => [node.id, node]));const roots = scene.nodes.filter((node) => node.kind === "root");const invalid = ids.size !== scene.nodes.length || roots.length !== 1 || roots[0]?.parentId !== null || scene.nodes.some((node) => {- if (node.lasso && (!node.box || node.kind !== "object")) return true;+ if (node.lassoContours && !node.lasso) return true;+ if (node.lasso && (!node.box || node.kind !== "object" || node.lasso.length + (node.lassoContours ?? []).reduce((sum, contour) => sum + contour.length, 0) > 8192)) return true;if (node.kind === "root") return false;const seen = new Set([node.id]);let parent = node.parentId;@@ -88,6 +91,13 @@ export function imageLassoPoints(node: Pick<ImageNode, "box" | "lasso">, box = nreturn box && node.lasso ? node.lasso.map((point) => ({ x: box.x + point.x * box.width / 1000, y: box.y + point.y * box.height / 1000 })) : [];}+/** Contours share the same placement box so holes move with their outline. */+export function imageLassoContours(node: Pick<ImageNode, "box" | "lasso" | "lassoContours">, box = node.box): ImagePoint[][] {+ return node.lasso ? [node.lasso, ...(node.lassoContours ?? [])].map((lasso) => imageLassoPoints({ box, lasso })) : [];+}+export const imageLassoPath = (node: ImageNode, box = node.box) => imageLassoContours(node, box)+ .map((points) => `M${points.map(({ x, y }) => `${x},${y}`).join("L")}Z`).join(" ");+/** Keep the sampled outline bounded without changing corners of short strokes. */export function simplifyImageLasso(points: ImagePoint[], tolerance = 1): ImagePoint[] {if (points.length < 3) return points;diff --git a/src/lib/workQueue.test.ts b/src/lib/workQueue.test.tsindex a77c3f6..a98edc0 100644--- a/src/lib/workQueue.test.ts+++ b/src/lib/workQueue.test.ts@@ -585,13 +585,14 @@ describe("image generation work", () => {expect(session.getSnapshot().config.assets.find((asset) => asset.id === work.id)?.parentAssetId).toBe("chosen");});- it("submits whole-image and local edits with separate reference pictures and refmods", async () => {+ it.each([false, true])("submits whole-image and local edits with separate references (compound mask: %s)", async (compound) => {const { queue } = setup();const record = imageProject();let scene = createImageEditScene({ name: "Source", relativePath: "media/generated/source.jpg", width: 101, height: 77 });scene.nodes[0].description = "Make the light warmer like @[ref:Lighting]";scene = addImageNode(scene, "image-root", "object");Object.assign(scene.nodes[1], { name: "Lasso", description: "Add a red @[ref:Balloon]", lasso: [{ x: 0, y: 0 }, { x: 1000, y: 0 }, { x: 0, y: 1000 }] });+ if (compound) scene.nodes[1].lassoContours = [[{ x: 250, y: 250 }, { x: 500, y: 250 }, { x: 250, y: 500 }]];record.config.imageScene = scene;record.config.references = ["Lighting", "Balloon"].map((name) => ({ id: name, name, kind: "image", description: name,relativePath: `references/${name}.png`, intendedUse: [], createdAt: record.config.createdAt,@@ -604,7 +605,8 @@ describe("image generation work", () => {const steps = request.imageEdit!.edits;expect(steps).toHaveLength(2);expect(steps[0]).toMatchObject({ x: 0, y: 0, width: 96, height: 64, feather: 0 });- expect(steps[1]).toMatchObject({ feather: 0, maskPolygon: [{ x: 24, y: 16 }, { x: 72, y: 16 }, { x: 24, y: 48 }] });+ const outer = [{ x: 24, y: 16 }, { x: 72, y: 16 }, { x: 24, y: 48 }];+ expect(steps[1]).toMatchObject({ feather: 0, ...(compound ? { maskContours: [outer, [{ x: 36, y: 24 }, { x: 48, y: 24 }, { x: 36, y: 32 }]] } : { maskPolygon: outer }) });for (const [index, name] of ["Lighting", "Balloon"].entries()) {expect(steps[index].referencePaths).toEqual(["C:/Image/media/generated/source.jpg", `C:/Image/references/${name}.png`]);expect(steps[index].refmods).toEqual([{ path: `C:/Image/references/${name}.safetensors`, strength: 0.75, copies: 2 }]);diff --git a/src/styles/image-editor.css b/src/styles/image-editor.cssindex f10f009..3774295 100644--- a/src/styles/image-editor.css+++ b/src/styles/image-editor.css@@ -72,11 +72,13 @@.image-empty strong { color: var(--text-primary); font-size: var(--text-base); font-weight: var(--weight-semibold); }.image-empty span { max-width: 300px; font-size: var(--text-xs); }.image-overlay { position: absolute; inset: 0; width: 100%; height: 100%; touch-action: none; }-.image-overlay rect, .image-overlay polygon { fill: color-mix(in srgb, var(--accent) 8%, transparent); stroke: var(--accent); stroke-width: 1.5; cursor: move; }-.image-overlay .selected > rect, .image-overlay .selected > polygon { stroke-width: 3; }+.image-overlay rect, .image-overlay polygon, .image-overlay path { fill: color-mix(in srgb, var(--accent) 8%, transparent); stroke: var(--accent); stroke-width: 1.5; cursor: move; }+.image-overlay .selected > rect, .image-overlay .selected > polygon, .image-overlay .selected > path { stroke-width: 3; }.image-box-label { position: absolute; margin: var(--space-1); padding: 0 var(--space-1); border-radius: var(--radius-sm); color: var(--text-primary); background: var(--panel); font-size: var(--text-xs); pointer-events: none; }.image-overlay .image-box-handle { fill: var(--accent); cursor: nwse-resize; }-.image-overlay.drawing, .image-overlay.drawing rect, .image-overlay.drawing polygon { cursor: crosshair; }+.image-overlay.drawing, .image-overlay.drawing rect, .image-overlay.drawing polygon, .image-overlay.drawing path { cursor: crosshair; }+.image-overlay.lasso-add, .image-overlay.lasso-add * { cursor: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='36' height='36'%3E%3Cpath d='M16 6v7m0 6v7M6 16h7m6 0h7M25 21v8M21 25h8' fill='none' stroke='white' stroke-width='3'/%3E%3Cpath d='M16 6v7m0 6v7M6 16h7m6 0h7M25 21v8M21 25h8' fill='none' stroke='black'/%3E%3C/svg%3E") 16 16, crosshair; }+.image-overlay.lasso-subtract, .image-overlay.lasso-subtract * { cursor: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='36' height='36'%3E%3Cpath d='M16 6v7m0 6v7M6 16h7m6 0h7M21 25h8' fill='none' stroke='white' stroke-width='3'/%3E%3Cpath d='M16 6v7m0 6v7M6 16h7m6 0h7M21 25h8' fill='none' stroke='black'/%3E%3C/svg%3E") 16 16, crosshair; }.extend-frame { background: transparent; box-shadow: none; }.extend-source { position: absolute; }.extend-source img { width: 100%; height: 100%; object-fit: fill; }