AI media harness for planning, generating, and editing locally
TypeScript
Bound Extend resolution and downscale its source
Bitti00e032e87934
diff --git a/RELEASE_NOTES.md b/RELEASE_NOTES.mdindex c91e4c9..a33d8ff 100644--- a/RELEASE_NOTES.md+++ b/RELEASE_NOTES.md@@ -10,7 +10,7 @@ This alpha update adds LAN generation workers, Linux support, expanded color gra- Renamed Colour correction to Basic Corrections and added temperature, tint, brightness, highlights, shadows, whites and blacks alongside exposure, contrast and saturation.- Added Creative with eight built-in procedural looks and intensity, faded film, sharpen and vibrance controls; RGB and hue/saturation/luma curve editors; and shadow, midtone and highlight Color Wheels with individual lightness controls.- Vignette now includes midpoint, roundness and feather, plus negative amounts for lighter edges. Grading settings are saved with the project and applied consistently in preview and export.-- Extend an image from the Image toolbar's Template menu. Draw, move or resize a bounding box to generate beyond any edge, with optional prompts and references, steps and seed controls. Original pixels inside the box stay unchanged, and the result is saved as a child image in lossless PNG format.+- Extend an image from the Image toolbar's Template menu. Draw, move or resize a bounding box to generate beyond any edge, with optional prompts and references, steps and seed controls. The original is downscaled to make room for the extension, and its scaled pixels are preserved in a child image saved as lossless PNG. Output stays within the source pixel count and selected generation resolution, with dimensions in multiples of 32.- Configure a character sheet from the Image toolbar's Template menu, with one reference-enabled prompt for clothing and other details, a resolution selection controlling sheet height (512–2048 px), and step count and seed controls, then select Execute. A square waist-up shot and three 9:16 full-body views are combined into one child image in the image bar. The front view provides a shared clothing reference for the other views; all four views share the selected step count and seed.- Continue scenes from a selected scene's saved latents, with adjustable overlap and a choice of beginning or end. This replaces Previous scene in First & last frame.- Share URL-based generator templates using Import and Export in Generator settings. Versioned `.slop` JSON bundles include GPU download variants, LoRAs and additional safetensors, preserve existing templates on import, and leave local paths out of shared files.@@ -34,7 +34,7 @@ This alpha update adds LAN generation workers, Linux support, expanded color gra- Continue preserves the full joined video and audio from Slopfab. Adjacent source and continuation scenes use that shared decode in preview and export, preserving context across the cut. Regenerate older Continue scenes to apply the fix.- The timeline playhead follows playback without waiting for editor updates.- Character sheets give side and back views explicit orientation instructions, keeping reference identity and clothing without copying the front-facing pose.-- Extend bounding box edges gently snap to nearby original image borders when drawing, moving or resizing.+- Extend bounding box edges gently snap to nearby original image borders when drawing, moving or resizing. Box dimensions use 32-pixel increments and stay within the maximum generation resolution.- Removing a reference from a scene's last prompt citation now removes it from generation inputs and “Used by.” References selected as frame or motion inputs remain active.- Copy and paste effect settings between matching effects from their **…** menus, including bypass state and LUT data.- Add voice reference chips directly in a shot's Speech field. Voice guidance stays separate from the words spoken.diff --git a/src-tauri/src/commands/extend_image.rs b/src-tauri/src/commands/extend_image.rsindex 7776ebd..6fa216b 100644--- a/src-tauri/src/commands/extend_image.rs+++ b/src-tauri/src/commands/extend_image.rs@@ -11,6 +11,79 @@ pub(crate) struct ExtendBounds {height: u32,}+#[derive(Clone, Copy, Deserialize, Serialize)]+pub(crate) struct ExtendSize {+ width: u32,+ height: u32,+}+// Keep aligned with the largest current preset in src/lib/export.ts (2048p).+const MAX_GENERATION_EDGE: u32 = 3648;+const MAX_GENERATION_PIXELS: u64 = 3648 * 2048;++fn source_dimensions(width: u32, height: u32) -> ExtendSize {+ let scale = 1.0f64+ .min(MAX_GENERATION_EDGE as f64 / (width as f64 * 1.5))+ .min(MAX_GENERATION_EDGE as f64 / (height as f64 * 1.5))+ .min((MAX_GENERATION_PIXELS as f64 / (width as f64 * height as f64)).sqrt() / 1.5);+ ExtendSize {+ width: ((width as f64 * scale).floor() as u32).max(1),+ height: ((height as f64 * scale).floor() as u32).max(1),+ }+}++fn scaled_layout(+ width: u32,+ height: u32,+ bounds: ExtendBounds,+ output: ExtendSize,+) -> Result<(ExtendSize, ExtendBounds), String> {+ if width == 0 || height == 0 || width > 8192 || height > 8192 {+ return Err("Invalid Extend source dimensions.".into());+ }+ let workspace = source_dimensions(width, height);+ bounds.validate(workspace.width, workspace.height)?;+ if bounds.width % 32 != 0+ || bounds.height % 32 != 0+ || bounds.width > MAX_GENERATION_EDGE+ || bounds.height > MAX_GENERATION_EDGE+ || u64::from(bounds.width) * u64::from(bounds.height) > MAX_GENERATION_PIXELS+ {+ return Err("Extend box dimensions must be multiples of 32 within the maximum generation resolution.".into());+ }+ if output.width == 0+ || output.height == 0+ || output.width % 32 != 0+ || output.height % 32 != 0+ || output.width > bounds.width+ || output.height > bounds.height+ || u64::from(output.width) * u64::from(output.height) > u64::from(width) * u64::from(height)+ {+ return Err(+ "Extend output must be aligned to 32 pixels and cannot increase the source resolution."+ .into(),+ );+ }+ let scale = (output.width as f64 / bounds.width as f64)+ .min(output.height as f64 / bounds.height as f64);+ let source = ExtendSize {+ width: ((workspace.width as f64 * scale).round() as u32).max(1),+ height: ((workspace.height as f64 * scale).round() as u32).max(1),+ };+ // Match JavaScript Math.round, including negative half-pixel positions.+ let mapped = ExtendBounds {+ x: (bounds.x as f64 * scale - (output.width as f64 - bounds.width as f64 * scale) / 2.0+ + 0.5)+ .floor() as i32,+ y: (bounds.y as f64 * scale - (output.height as f64 - bounds.height as f64 * scale) / 2.0+ + 0.5)+ .floor() as i32,+ width: output.width,+ height: output.height,+ };+ mapped.validate(source.width, source.height)?;+ Ok((source, mapped))+}+impl ExtendBounds {fn validate(self, width: u32, height: u32) -> Result<(), String> {if width == 0@@ -73,6 +146,7 @@ pub(crate) fn prepare_extend_image(job_id: String,source_id: String,bounds: ExtendBounds,+ output: ExtendSize,) -> Result<(), String> {let root = ProjectRoot::open(&folder_path)?;let project = read_project(root.path())?;@@ -90,17 +164,26 @@ pub(crate) fn prepare_extend_image(return Err("The Extend source has no saved file.".into());};let (width, height) = image::image_dimensions(&source_path).map_err(|e| e.to_string())?;- bounds.validate(width, height)?;+ let (scaled, bounds) = scaled_layout(width, height, bounds, output)?;if asset.width != Some(width) || asset.height != Some(height) {return Err("The source image dimensions changed. Reopen the image before extending it.".into(),);}- let source = image::open(source_path)+ let mut source = image::open(source_path).map_err(|e| e.to_string())?.to_rgba8();+ if source.dimensions() != (scaled.width, scaled.height) {+ source = image::imageops::resize(+ &source,+ scaled.width,+ scaled.height,+ image::imageops::FilterType::Lanczos3,+ );+ }let cache = root.directory(&directory(&job_id)?)?;- // Snapshot the original so file changes during generation cannot alter preservation.+ // Snapshot the downscaled original. Generation and final preservation use+ // exactly these pixels, with no second resampling or model changes to them.write_png(&cache.join("original.png"), &source)?;write_png(&cache.join("canvas.png"), &padded_source(&source, bounds))?;crate::storage::atomic::write_atomically(@@ -174,6 +257,73 @@ pub(crate) fn discard_extend_image(folder_path: String, job_id: String) -> Resulmod tests {use super::*;+ #[test]+ fn extend_layout_matches_the_scaled_generation_canvas_and_rejects_growth() {+ let bounds = ExtendBounds {+ x: -64,+ y: -32,+ width: 256,+ height: 160,+ };+ let output = ExtendSize {+ width: 128,+ height: 64,+ };+ let (source, mapped) = scaled_layout(128, 96, bounds, output).unwrap();+ assert_eq!(+ (+ source.width,+ source.height,+ mapped.x,+ mapped.y,+ mapped.width,+ mapped.height+ ),+ (51, 38, -38, -13, 128, 64)+ );+ assert!(scaled_layout(+ 128,+ 96,+ bounds,+ ExtendSize {+ width: 256,+ height: 160+ }+ )+ .is_err());+ assert!(scaled_layout(+ 128,+ 96,+ bounds,+ ExtendSize {+ width: 127,+ height: 64+ }+ )+ .is_err());+ assert!(scaled_layout(+ 128,+ 96,+ ExtendBounds {+ width: 257,+ ..bounds+ },+ output+ )+ .is_err());+ assert!(scaled_layout(+ 8192,+ 8192,+ ExtendBounds {+ width: 3648,+ height: 3648,+ ..bounds+ },+ output+ )+ .is_err());+ }+#[test]fn extend_preserves_original_pixels_including_alpha_and_cropped_intersections() {let source = RgbaImage::from_fn(7, 5, |x, y| {@@ -232,28 +382,33 @@ mod tests {let mut config = crate::tests::created_fixture();config.assets.push(serde_json::from_value(serde_json::json!({"id":"extend-source", "kind":"image", "name":"Source", "relativePath":"media/source.png", "mimeType":"image/png",- "width":7, "height":5, "createdAt":config.created_at+ "width":224, "height":160, "createdAt":config.created_at})).unwrap());crate::project::storage::write_project(folder.path(), &config).unwrap();let path = folder.path().to_string_lossy().into_owned();let root = ProjectRoot::open(&path).unwrap();- let source = RgbaImage::from_pixel(7, 5, image::Rgba([30, 60, 90, 123]));+ let source = RgbaImage::from_pixel(224, 160, image::Rgba([30, 60, 90, 123]));write_png(&root.directory("media").unwrap().join("source.png"),&source,).unwrap();let bounds = ExtendBounds {- x: -3,+ x: -96,y: 0,- width: 10,- height: 5,+ width: 320,+ height: 160,+ };+ let output = ExtendSize {+ width: 224,+ height: 96,};prepare_extend_image(path.clone(),"extend-test".into(),"extend-source".into(),bounds,+ output,).unwrap();prepare_extend_image(@@ -261,31 +416,34 @@ mod tests {"extend-other".into(),"extend-source".into(),bounds,+ output,).unwrap();let original_path = root.existing("cache/extend-images/extend-test/original.png").unwrap();- assert_eq!(image::open(&original_path).unwrap().to_rgba8(), source);+ let snapshot =+ image::imageops::resize(&source, 134, 96, image::imageops::FilterType::Lanczos3);+ assert_eq!(image::open(&original_path).unwrap().to_rgba8(), snapshot);assert_eq!(image::image_dimensions(root.existing("cache/extend-images/extend-test/canvas.png").unwrap()).unwrap(),- (10, 5)+ (224, 96));write_png(&root.existing("media/source.png").unwrap(),- &RgbaImage::new(7, 5),+ &RgbaImage::new(224, 160),).unwrap();- assert_eq!(image::open(original_path).unwrap().to_rgba8(), source);+ assert_eq!(image::open(original_path).unwrap().to_rgba8(), snapshot);for invalid in [- ExtendBounds { x: 7, ..bounds },+ ExtendBounds { x: 224, ..bounds },ExtendBounds {x: 0,- width: 7,+ width: 224,..bounds},ExtendBounds {@@ -301,7 +459,8 @@ mod tests {path.clone(),"invalid".into(),"extend-source".into(),- invalid+ invalid,+ output,).is_err());}@@ -309,7 +468,8 @@ mod tests {path.clone(),"../outside".into(),"extend-source".into(),- bounds+ bounds,+ output,).is_err());assert!(discard_extend_image(path.clone(), "../outside".into()).is_err());@@ -323,7 +483,7 @@ mod tests {}#[test]- fn extend_finalizer_writes_a_lossless_png_using_the_source_snapshot() {+ fn extend_finalizer_preserves_downscaled_source_pixels_in_a_bounded_png() {struct GeneratedPixels;impl crate::rendered::FrameSource for GeneratedPixels {fn frame_rgba(&self, _: u32, width: u32, height: u32) -> Result<Vec<u8>, String> {@@ -331,23 +491,44 @@ mod tests {}}let folder = tempfile::tempdir().unwrap();- crate::project::storage::write_project(folder.path(), &crate::tests::created_fixture())- .unwrap();+ let mut config = crate::tests::created_fixture();+ config.assets.push(serde_json::from_value(serde_json::json!({+ "id":"source", "kind":"image", "name":"Source", "relativePath":"media/source.png", "mimeType":"image/png",+ "width":128, "height":96, "createdAt":config.created_at+ })).unwrap());+ crate::project::storage::write_project(folder.path(), &config).unwrap();let path = folder.path().to_string_lossy().into_owned();let root = ProjectRoot::open(&path).unwrap();let job = "extend-finalizer-test";- let cache = root.directory(&directory(job).unwrap()).unwrap();let bounds = ExtendBounds {- x: -2,- y: 1,- width: 9,- height: 6,+ x: -64,+ y: -32,+ width: 256,+ height: 160,};- let source = RgbaImage::from_fn(7, 5, |x, y| image::Rgba([x as u8, y as u8, 80, 123]));- write_png(&cache.join("original.png"), &source).unwrap();- std::fs::write(- cache.join("bounds.json"),- serde_json::to_vec(&bounds).unwrap(),+ let source = RgbaImage::from_fn(128, 96, |x, y| image::Rgba([x as u8, y as u8, 80, 123]));+ write_png(+ &root.directory("media").unwrap().join("source.png"),+ &source,+ )+ .unwrap();+ prepare_extend_image(+ path.clone(),+ job.into(),+ "source".into(),+ bounds,+ ExtendSize {+ width: 128,+ height: 64,+ },+ )+ .unwrap();+ let scaled =+ image::imageops::resize(&source, 51, 38, image::imageops::FilterType::Lanczos3);+ // The original file may change while the job runs; its prepared snapshot wins.+ write_png(+ &root.existing("media/source.png").unwrap(),+ &RgbaImage::new(128, 96),).unwrap();crate::rendered::keep(@@ -356,10 +537,10 @@ mod tests {Box::new(GeneratedPixels),vec![],1,- 9,- 6,+ 128,+ 64,3,- 9 * 6 * 3,+ 128 * 64 * 3,24.0,0,0,@@ -370,12 +551,13 @@ mod tests {let image = image::open(root.existing(&saved.relative_path).unwrap()).unwrap().to_rgba8();- for y in 0..6 {- for x in 0..9 {+ assert_eq!(image.dimensions(), (128, 64));+ for y in 0..64 {+ for x in 0..128 {assert_eq!(image.get_pixel(x, y).0,- if x >= 2 && y < 4 {- source.get_pixel(x - 2, y + 1).0+ if (38..89).contains(&x) && (13..51).contains(&y) {+ scaled.get_pixel(x - 38, y - 13).0} else {[210, 180, 150, 255]}diff --git a/src/components/workspace/Extend.test.tsx b/src/components/workspace/Extend.test.tsxindex 54abf70..44e0ab1 100644--- a/src/components/workspace/Extend.test.tsx+++ b/src/components/workspace/Extend.test.tsx@@ -28,10 +28,17 @@ it("activates the box through Template, validates settings and executes withoutexpect(screen.getByLabelText("Extend bounding box tool")).toBeInTheDocument();expect(screen.queryByLabelText("Image placement canvas")).not.toBeInTheDocument();const panel = within(screen.getByRole("complementary", { name: "Extend settings" }));- expect(panel.getByLabelText("Extend x")).toHaveValue(-100);- expect(panel.getByLabelText("Extend width")).toHaveValue(600);+ expect(panel.getByLabelText("Extend x")).toHaveValue(-104);+ expect(panel.getByLabelText("Extend width")).toHaveValue(608);+ expect(panel.getByLabelText("Extend width")).toHaveAttribute("step", "32");+ expect(panel.getByLabelText("Extend width")).toHaveAttribute("max", "3648");+ fireEvent.change(panel.getByLabelText("Extend width"), { target: { value: "619" } });+ expect(panel.getByLabelText("Extend width")).toHaveValue(608);+ fireEvent.change(panel.getByLabelText("Extend width"), { target: { value: "9999" } });+ expect(panel.getByLabelText("Extend width")).toHaveValue(3648);+ fireEvent.click(panel.getByRole("button", { name: "Reset box" }));fireEvent.keyDown(screen.getByRole("button", { name: "Move Extend box" }), { key: "ArrowLeft", shiftKey: true });- expect(panel.getByLabelText("Extend x")).toHaveValue(-110);+ expect(panel.getByLabelText("Extend x")).toHaveValue(-114);fireEvent.change(panel.getByLabelText("Extend x"), { target: { value: "400" } });expect(panel.getByRole("button", { name: "Execute" })).toBeDisabled();expect(panel.getByText("The box must overlap the original image.")).toBeInTheDocument();@@ -41,8 +48,8 @@ it("activates the box through Template, validates settings and executes withouttypePrompt(panel.getByRole("textbox", { name: "Extend prompt" }), "A forest clearing");fireEvent.click(panel.getByRole("button", { name: "Execute" }));expect(generate).toHaveBeenCalledWith(expect.objectContaining({ id: template.id }), source.id,- { bounds: { x: -100, y: -75, width: 600, height: 450 }, steps: 31, seed: 0, prompt: "A forest clearing" });- expect(screen.getByRole("status")).toHaveTextContent("Extend: 600 × 450 px");+ { bounds: { x: -104, y: -74, width: 608, height: 448 }, steps: 31, seed: 0, prompt: "A forest clearing" });+ expect(screen.getByRole("status")).toHaveTextContent("Extend: 384 × 288 px");expect(change).not.toHaveBeenCalled();fireEvent.click(panel.getByRole("button", { name: "Close template settings" }));expect(screen.queryByLabelText("Extend bounding box tool")).not.toBeInTheDocument();@@ -55,7 +62,7 @@ it("activates the box through Template, validates settings and executes withoutit("moves, resizes, redraws and cancels box drags in original pixel coordinates", () => {vi.spyOn(persistence, "readMediaFileUrl").mockResolvedValue(null);- let latest: ExtendBounds = { x: -100, y: -75, width: 600, height: 450 };+ let latest: ExtendBounds = { x: -96, y: -64, width: 576, height: 448 };function Harness() {const [bounds, setBounds] = useState(latest); latest = bounds;return <ExtendCanvas source={source} folderPath="D:/Images" bounds={bounds} onChange={setBounds} disabled={false} />;@@ -71,29 +78,29 @@ it("moves, resizes, redraws and cancels box drags in original pixel coordinates"};pointer("pointerDown", screen.getByRole("button", { name: "Move Extend box" }), 0, 0);pointer("pointerMove", canvas, 20, 10); pointer("pointerUp", canvas, 20, 10);- expect(latest).toEqual({ x: -80, y: -65, width: 600, height: 450 });- pointer("pointerDown", canvas.querySelector('[data-handle="nw"]')!, -80, -65);- pointer("pointerMove", canvas, -110, -90); pointer("pointerUp", canvas, -110, -90);- expect(latest).toEqual({ x: -110, y: -90, width: 630, height: 475 });+ expect(latest).toEqual({ x: -76, y: -54, width: 576, height: 448 });+ pointer("pointerDown", canvas.querySelector('[data-handle="nw"]')!, -76, -54);+ pointer("pointerMove", canvas, -106, -79); pointer("pointerUp", canvas, -106, -79);+ expect(latest).toEqual({ x: -108, y: -86, width: 608, height: 480 });pointer("pointerDown", canvas, -130, -100);pointer("pointerMove", canvas, 200, 200); pointer("pointerUp", canvas, 200, 200);- expect(latest).toEqual({ x: -130, y: -100, width: 330, height: 300 });+ expect(latest).toEqual({ x: -130, y: -100, width: 320, height: 288 });pointer("pointerDown", canvas.querySelector('[data-handle="se"]')!, 200, 200);pointer("pointerMove", canvas, 300, 300); pointer("pointerCancel", canvas, 300, 300);- expect(latest).toEqual({ x: -130, y: -100, width: 330, height: 300 });+ expect(latest).toEqual({ x: -130, y: -100, width: 320, height: 288 });pointer("pointerDown", canvas.querySelector('[data-handle="e"]')!, 200, 0);pointer("pointerMove", canvas, 300, 0);fireEvent.keyDown(canvas, { key: "Escape" });- expect(latest).toEqual({ x: -130, y: -100, width: 330, height: 300 });+ expect(latest).toEqual({ x: -130, y: -100, width: 320, height: 288 });});it.each([0.5, 2])("snaps within six screen pixels at %sx scale without trapping the drag or resizing a moved box", (scale) => {vi.spyOn(persistence, "readMediaFileUrl").mockResolvedValue(null);- const original = { x: -100, y: -75, width: 600, height: 450 };+ const original = { x: -96, y: -64, width: 576, height: 448 };let latest: ExtendBounds = original;function Harness() {const [bounds, setBounds] = useState(original); latest = bounds;- return <ExtendCanvas source={source} folderPath="D:/Images" bounds={bounds} onChange={setBounds} disabled={false} />;+ return <ExtendCanvas source={{ ...source, width: 384, height: 288 }} folderPath="D:/Images" bounds={bounds} onChange={setBounds} disabled={false} />;}render(<Harness />);const canvas = screen.getByLabelText("Extend bounding box tool");@@ -105,34 +112,34 @@ it.each([0.5, 2])("snaps within six screen pixels at %sx scale without trappingfireEvent(target, event);};// Resize only the active edge, leaving its opposite edge and vertical bounds fixed.- pointer("pointerDown", canvas.querySelector('[data-handle="e"]')!, 500, 150);- pointer("pointerMove", canvas, 400 + 4 / scale, 150);- expect(latest).toEqual({ ...original, width: 500 });- pointer("pointerMove", canvas, 400 + 8 / scale, 150);- expect(latest).toEqual({ ...original, width: 500 + 8 / scale });- pointer("pointerMove", canvas, 400 - 4 / scale, 150);- expect(latest).toEqual({ ...original, width: 500 });- pointer("pointerCancel", canvas, 400, 150);+ pointer("pointerDown", canvas.querySelector('[data-handle="e"]')!, 480, 150);+ pointer("pointerMove", canvas, 384 + 4 / scale, 150);+ expect(latest).toEqual({ ...original, width: 480 });+ pointer("pointerMove", canvas, 416, 150);+ expect(latest).toEqual({ ...original, width: 512 });+ pointer("pointerMove", canvas, 384 - 4 / scale, 150);+ expect(latest).toEqual({ ...original, width: 480 });+ pointer("pointerCancel", canvas, 384, 150);expect(latest).toEqual(original);// A corner snaps to both original borders while preserving the opposite corner.- pointer("pointerDown", canvas.querySelector('[data-handle="nw"]')!, -100, -75);+ pointer("pointerDown", canvas.querySelector('[data-handle="nw"]')!, -96, -64);pointer("pointerMove", canvas, -4 / scale, 4 / scale);- expect(latest).toEqual({ x: 0, y: 0, width: 500, height: 375 });+ expect(latest).toEqual({ x: 0, y: 0, width: 480, height: 384 });fireEvent.keyDown(canvas, { key: "Escape" });expect(latest).toEqual(original);// Moving snaps by translation, never by stretching the box.pointer("pointerDown", screen.getByRole("button", { name: "Move Extend box" }), 0, 0);- pointer("pointerMove", canvas, 100 - 4 / scale, 75 + 4 / scale);+ pointer("pointerMove", canvas, 96 - 4 / scale, 64 + 4 / scale);expect(latest).toEqual({ ...original, x: 0, y: 0 });- pointer("pointerCancel", canvas, 100, 75);+ pointer("pointerCancel", canvas, 96, 64);// Both endpoints of a newly drawn box can align exactly with the source.pointer("pointerDown", canvas, -4 / scale, -4 / scale);- pointer("pointerMove", canvas, 400 + 4 / scale, 300 + 4 / scale);- expect(latest).toEqual({ x: 0, y: 0, width: 400, height: 300 });- pointer("pointerUp", canvas, 400, 300);+ pointer("pointerMove", canvas, 384 + 4 / scale, 288 + 4 / scale);+ expect(latest).toEqual({ x: 0, y: 0, width: 384, height: 288 });+ pointer("pointerUp", canvas, 384, 288);fireEvent.keyDown(screen.getByRole("button", { name: "Move Extend box" }), { key: "ArrowLeft" });- expect(latest).toEqual({ x: -1, y: 0, width: 400, height: 300 });+ expect(latest).toEqual({ x: -1, y: 0, width: 384, height: 288 });});diff --git a/src/components/workspace/ExtendCanvas.tsx b/src/components/workspace/ExtendCanvas.tsxindex 4242969..c3518cb 100644--- a/src/components/workspace/ExtendCanvas.tsx+++ b/src/components/workspace/ExtendCanvas.tsx@@ -1,5 +1,5 @@import { useEffect, useRef, useState, type CSSProperties, type PointerEvent } from "react";-import type { ExtendBounds } from "../../lib/extendImage";+import { alignExtendBounds, extendSourceDimensions, EXTEND_GRID, EXTEND_MAX_EDGE, EXTEND_MAX_PIXELS, type ExtendBounds } from "../../lib/extendImage";import type { ProjectAsset } from "../../lib/project";import { ReferenceImage } from "./ReferenceImage";@@ -13,7 +13,7 @@ function cameraFor(width: number, height: number, box: ExtendBounds) {const handles = ["nw", "n", "ne", "e", "se", "s", "sw", "w"] as const;const SNAP_DISTANCE = 6; // CSS pixels, independent of the image/canvas scale.-function snapAxis(start: number, size: number, sourceSize: number, tolerance: number, move: boolean, leading: boolean, trailing: boolean) {+function snapAxis(start: number, size: number, sourceSize: number, tolerance: number, move: boolean, leading: boolean, trailing: boolean, maxSize: number) {const nearest = (deltas: number[]) => deltas.filter((delta) => Math.abs(delta) <= tolerance).sort((a, b) => Math.abs(a) - Math.abs(b))[0] ?? 0;if (move) {@@ -24,16 +24,16 @@ function snapAxis(start: number, size: number, sourceSize: number, tolerance: nu}let end = start + size;if (leading) start += nearest([0, sourceSize].map((edge) => edge - start)- .filter((delta) => end - start - delta >= 1 && end - start - delta <= 8192));+ .filter((delta) => end - start - delta >= EXTEND_GRID && end - start - delta <= maxSize && (end - start - delta) % EXTEND_GRID === 0));if (trailing) end += nearest([0, sourceSize].map((edge) => edge - end)- .filter((delta) => end + delta - start >= 1 && end + delta - start <= 8192));+ .filter((delta) => end + delta - start >= EXTEND_GRID && end + delta - start <= maxSize && (end + delta - start) % EXTEND_GRID === 0));return [start, end - start];}export function ExtendCanvas({ source, folderPath, bounds, onChange, disabled }: {source: ProjectAsset; folderPath: string; bounds: ExtendBounds; onChange: (bounds: ExtendBounds) => void; disabled: boolean;}) {- const width = source.width!, height = source.height!;+ const { width, height } = extendSourceDimensions(source.width!, source.height!);const [camera, setCamera] = useState(() => cameraFor(width, height, bounds));const [dragging, setDragging] = useState(false);const drag = useRef<{ pointerId: number; x: number; y: number; box: ExtendBounds; mode: string } | null>(null);@@ -43,6 +43,12 @@ export function ExtendCanvas({ source, folderPath, bounds, onChange, disabled }:return { x: Math.round(camera.x + (event.clientX - rect.left) / rect.width * camera.width),y: Math.round(camera.y + (event.clientY - rect.top) / rect.height * camera.height) };};+ const snapPoint = (event: PointerEvent<SVGSVGElement>, at: { x: number; y: number }) => {+ const rect = event.currentTarget.getBoundingClientRect();+ const snap = (value: number, edge: number, tolerance: number) => [0, edge]+ .filter((border) => Math.abs(value - border) <= tolerance).sort((a, b) => Math.abs(a - value) - Math.abs(b - value))[0] ?? value;+ return { x: snap(at.x, width, SNAP_DISTANCE * camera.width / rect.width), y: snap(at.y, height, SNAP_DISTANCE * camera.height / rect.height) };+ };const finish = (event: PointerEvent<SVGSVGElement>, cancel = false) => {if (drag.current?.pointerId !== event.pointerId) return;if (cancel) onChange(drag.current.box);@@ -63,15 +69,16 @@ export function ExtendCanvas({ source, folderPath, bounds, onChange, disabled }:<svg className="extend-overlay" viewBox={`${camera.x} ${camera.y} ${camera.width} ${camera.height}`} aria-label="Extend bounding box tool" aria-disabled={disabled}onPointerDown={(event) => {if (disabled || event.button !== 0) return;- const at = point(event); if (!Number.isFinite(at.x + at.y)) return;+ let at = point(event); if (!Number.isFinite(at.x + at.y)) return;event.preventDefault();event.currentTarget.querySelector<SVGElement>('[data-handle="move"]')?.focus();const mode = (event.target as Element).getAttribute("data-handle") ?? "draw";+ if (mode === "draw") at = snapPoint(event, at);drag.current = { pointerId: event.pointerId, ...at, box: { ...box }, mode };setDragging(true); event.currentTarget.setPointerCapture?.(event.pointerId);}} onPointerMove={(event) => {const start = drag.current; if (!start || disabled || start.pointerId !== event.pointerId) return;- const at = point(event), dx = at.x - start.x, dy = at.y - start.y;+ const at = start.mode === "draw" ? snapPoint(event, point(event)) : point(event), dx = at.x - start.x, dy = at.y - start.y;if (!Number.isFinite(dx + dy)) return;let { x, y, width: w, height: h } = start.box;if (start.mode === "move") { x += dx; y += dy; }@@ -82,12 +89,14 @@ export function ExtendCanvas({ source, folderPath, bounds, onChange, disabled }:if (start.mode.includes("w")) { x = Math.min(x + dx, x + w - 1); w += start.box.x - x; }if (start.mode.includes("n")) { y = Math.min(y + dy, y + h - 1); h += start.box.y - y; }}+ const aligned = alignExtendBounds({ x, y, width: w, height: h }, start.mode);+ ({ x, y, width: w, height: h } = aligned);const rect = event.currentTarget.getBoundingClientRect();const move = start.mode === "move", draw = start.mode === "draw";- [x, w] = snapAxis(Math.max(-8192, Math.min(8192, x)), Math.min(8192, w), width,- SNAP_DISTANCE * camera.width / rect.width, move, draw || start.mode.includes("w"), draw || start.mode.includes("e"));- [y, h] = snapAxis(Math.max(-8192, Math.min(8192, y)), Math.min(8192, h), height,- SNAP_DISTANCE * camera.height / rect.height, move, draw || start.mode.includes("n"), draw || start.mode.includes("s"));+ [x, w] = snapAxis(Math.max(-8192, Math.min(8192, x)), w, width,+ SNAP_DISTANCE * camera.width / rect.width, move, draw || start.mode.includes("w"), draw || start.mode.includes("e"), Math.min(EXTEND_MAX_EDGE, EXTEND_MAX_PIXELS / h));+ [y, h] = snapAxis(Math.max(-8192, Math.min(8192, y)), h, height,+ SNAP_DISTANCE * camera.height / rect.height, move, draw || start.mode.includes("n"), draw || start.mode.includes("s"), Math.min(EXTEND_MAX_EDGE, EXTEND_MAX_PIXELS / w));onChange({ x, y, width: w, height: h });}} onPointerUp={(event) => finish(event)} onPointerCancel={(event) => finish(event, true)} onLostPointerCapture={(event) => finish(event)}onKeyDown={(event) => {diff --git a/src/components/workspace/ExtendSettings.tsx b/src/components/workspace/ExtendSettings.tsxindex 307b4fb..01b7d7e 100644--- a/src/components/workspace/ExtendSettings.tsx+++ b/src/components/workspace/ExtendSettings.tsx@@ -1,5 +1,5 @@import { useMemo } from "react";-import { compileExtendImage, initialExtendBounds, type ExtendOptions } from "../../lib/extendImage";+import { alignExtendBounds, compileExtendImage, initialExtendBounds, EXTEND_GRID, EXTEND_MAX_EDGE, type ExtendOptions } from "../../lib/extendImage";import type { ProjectAsset, ProjectConfig } from "../../lib/project";import { InfoBar, ItemHeader, PropRow } from "../ui";import { Dismiss16, Sparkle16 } from "../ui/icons";@@ -10,19 +10,24 @@ export function ExtendSettings({ config, source, options, onChange, references,references: PromptReference[]; missingLabel: (id: string) => string; busy: boolean; disabledReason: string | null;onExecute: () => void; onClose: () => void;}) {- const error = useMemo(() => {- try { compileExtendImage(config, source, "cache/extend-preview.png", options); return null; }- catch (reason) { return reason instanceof Error ? reason.message : String(reason); }+ const validation = useMemo(() => {+ try { return { output: compileExtendImage(config, source, "cache/extend-preview.png", options).layout.output, message: null }; }+ catch (reason) { return { output: null, message: reason instanceof Error ? reason.message : String(reason) }; }}, [config, source, options]);return <aside className="image-inspector image-template-settings" aria-label="Extend settings"><ItemHeader name="Extend" meta="Template" actions={<button type="button" className="icon-button" aria-label="Close template settings" data-tooltip="Back to image settings" onClick={onClose}><Dismiss16 aria-hidden="true" /></button>} />- <form className="image-template-settings__form" onSubmit={(event) => { event.preventDefault(); if (!busy && !disabledReason && !error) onExecute(); }}>+ <form className="image-template-settings__form" onSubmit={(event) => { event.preventDefault(); if (!busy && !disabledReason && !validation.message) onExecute(); }}><div className="image-inspector__fields image-template-settings__fields">- <p className="image-inspector__caption">Drag the box or its handles to set the final image bounds. Drag outside the box to draw a new one. Shaded areas will be generated; original pixels inside the box stay unchanged.</p>+ <p className="image-inspector__caption">Drag the box or its handles, or drag outside it to draw a new box. Sizes use 32-pixel increments. The original is downscaled to make room for generated areas; output stays within the source pixel count and selected generation resolution.</p>+ {validation.output && <p className="image-inspector__caption">Output: {validation.output.width} × {validation.output.height} px</p>}<p className="image-inspector__caption">Source: {source.name} · {source.width} × {source.height} px</p>{(["x", "y", "width", "height"] as const).map((field) => <PropRow key={field} label={field === "x" ? "X" : field === "y" ? "Y" : field === "width" ? "Width" : "Height"} htmlFor={`extend-${field}`}>- <input id={`extend-${field}`} aria-label={`Extend ${field}`} className="text-field" type="number" step="1" min={field === "x" || field === "y" ? -8192 : 1} max="8192" required disabled={busy}- value={Number.isNaN(options.bounds[field]) ? "" : options.bounds[field]} onChange={(event) => onChange({ ...options, bounds: { ...options.bounds, [field]: event.target.valueAsNumber } })} />+ <input id={`extend-${field}`} aria-label={`Extend ${field}`} className="text-field" type="number" step={field === "x" || field === "y" ? 1 : EXTEND_GRID} min={field === "x" || field === "y" ? -8192 : EXTEND_GRID} max={field === "x" || field === "y" ? 8192 : EXTEND_MAX_EDGE} required disabled={busy}+ value={options.bounds[field]} onChange={(event) => {+ const value = event.target.valueAsNumber; if (!Number.isFinite(value)) return;+ const bounds = { ...options.bounds, [field]: value };+ onChange({ ...options, bounds: field === "width" || field === "height" ? alignExtendBounds(bounds, field === "width" ? "e" : "s") : { ...bounds, [field]: Math.round(value) } });+ }} /></PropRow>)}<button type="button" className="secondary-button" disabled={busy} onClick={() => onChange({ ...options, bounds: initialExtendBounds(source.width!, source.height!) })}>Reset box</button><PropRow label="Steps" htmlFor="extend-steps"><input id="extend-steps" className="text-field" type="number" min="2" max="1000" step="1" required disabled={busy}@@ -32,11 +37,11 @@ export function ExtendSettings({ config, source, options, onChange, references,<p className="image-inspector__caption">Use -1 for a random seed.</p><div className="image-inspector__area"><span>Prompt</span><PromptTextField aria-label="Extend prompt" value={options.prompt} onChange={(prompt) => onChange({ ...options, prompt })}references={references} missingLabel={missingLabel} disabled={busy} placeholder="Describe what should appear beyond the image…" /></div>- {error && <InfoBar severity="error" title="Adjust the Extend settings" message={error} />}+ {validation.message && <InfoBar severity="error" title="Adjust the Extend settings" message={validation.message} />}</div><div className="image-template-settings__footer">{disabledReason && <p className="image-inspector__caption">{disabledReason}</p>}- <button type="submit" className="primary-button" disabled={busy || Boolean(disabledReason || error)}><Sparkle16 aria-hidden="true" />{busy ? "Executing…" : "Execute"}</button>+ <button type="submit" className="primary-button" disabled={busy || Boolean(disabledReason || validation.message)}><Sparkle16 aria-hidden="true" />{busy ? "Executing…" : "Execute"}</button></div></form></aside>;diff --git a/src/components/workspace/ImageEditor.tsx b/src/components/workspace/ImageEditor.tsxindex ef54193..5922124 100644--- a/src/components/workspace/ImageEditor.tsx+++ b/src/components/workspace/ImageEditor.tsx@@ -18,7 +18,7 @@ import { ImageBar } from "./ImageBar";import { CharacterSheetSettings } from "./CharacterSheetSettings";import { ExtendSettings } from "./ExtendSettings";import { ExtendCanvas } from "./ExtendCanvas";-import { initialExtendBounds, type ExtendOptions } from "../../lib/extendImage";+import { extendOutputDimensions, initialExtendBounds, type ExtendOptions } from "../../lib/extendImage";import type { CharacterSheetOptions } from "../../lib/characterSheet";import { referenceMediaTypes } from "../../lib/referenceSelection";import { DebugPromptDialog } from "./DebugPromptDialog";@@ -151,6 +151,11 @@ export function ImageEditor({ config, folderPath, onChange: changeConfig, onGeneconst work = workItems.filter((item) => item.imageAssetId === scene.outputAssetId).at(-1);const active = work && isWorkActive(work);const output = config.assets.find((asset) => asset.id === scene.outputAssetId);+ let extendSize: { width: number; height: number } | null = null;+ if (extendMode && extendOptions && output?.width && output.height) {+ try { extendSize = extendOutputDimensions(config, { width: output.width, height: output.height }, extendOptions.bounds); }+ catch { /* Invalid bounds are explained in Extend settings. */ }+ }const images = config.assets.filter((asset) => asset.kind === "image");const menuImage = images.find((asset) => asset.id === imageMenu?.id);const canUseMenuImage = Boolean(menuImage?.relativePath || menuImage?.sourcePath);@@ -656,7 +661,7 @@ export function ImageEditor({ config, folderPath, onChange: changeConfig, onGene{boxes && scene.nodes.filter((node) => node.box).map((node) => { const box = pointer.current?.id === node.id && draftBox ? draftBox : node.box!; return <span key={node.id} className="image-box-label" style={{ left: `${box.x / 10}%`, top: `${box.y / 10}%` }}>{node.name}</span>; })}</div></div>}{(error || work?.error) && <InfoBar className="image-error" severity="error" title="Couldn’t update the image" message={error ?? work?.error ?? ""} onClose={error ? () => setError(null) : undefined} />}- <div className="image-status" role="status">{active && <ProgressBar value={work.progress * 100} aria-label="Image generation progress" />}<span>{active ? work.detail : extendMode && extendOptions ? `Extend: ${extendOptions.bounds.width || "-"} \u00d7 ${extendOptions.bounds.height || "-"} px` : imageRoot ? editPlan?.error ?? `${width} × ${height} · ${editPlan?.edits.length} edits in hierarchy order` : !isTauri() ? "Image generation is available in the desktop app." : `${width} × ${height}${isMiniMaxH3 ? "" : " · Placement boxes guide the prompt"}`}</span></div>+ <div className="image-status" role="status">{active && <ProgressBar value={work.progress * 100} aria-label="Image generation progress" />}<span>{active ? work.detail : extendMode && extendOptions ? `Extend: ${extendSize?.width ?? "-"} \u00d7 ${extendSize?.height ?? "-"} px` : imageRoot ? editPlan?.error ?? `${width} × ${height} · ${editPlan?.edits.length} edits in hierarchy order` : !isTauri() ? "Image generation is available in the desktop app." : `${width} × ${height}${isMiniMaxH3 ? "" : " · Placement boxes guide the prompt"}`}</span></div><ImageBar ref={imageResults} images={images} selectedId={scene.outputAssetId} folderPath={folderPath} onSelect={selectImage}onMenu={(id, x, y, inFamily) => { setContextMenu(null); setImageMenu({ id, x, y, inFamily, source: "bar" }); }} /></section>diff --git a/src/lib/extendImage.test.ts b/src/lib/extendImage.test.tsindex 1c18652..704d00c 100644--- a/src/lib/extendImage.test.ts+++ b/src/lib/extendImage.test.ts@@ -1,5 +1,6 @@import { expect, it } from "vitest";-import { extendRegions, initialExtendBounds } from "./extendImage";+import { alignExtendBounds, compileExtendImage, extendLayout, extendRegions, extendSourceDimensions, EXTEND_MAX_EDGE, EXTEND_MAX_PIXELS, initialExtendBounds } from "./extendImage";+import { createProjectConfig } from "./project";it("partitions only new pixels for every combination of extension directions and crops", () => {for (const x of [-3, 0, 2]) for (const y of [-2, 0, 1]) for (const width of [5, 10]) for (const height of [4, 8]) {@@ -20,5 +21,54 @@ it("rejects boxes with no original context, no extension, fractional or excessiv{ x: 0, y: 0, width: 20, height: 20 }, { x: -1.5, y: 0, width: 20, height: 20 },{ x: -20, y: 0, width: 8193, height: 20 }, { x: NaN, y: 0, width: 20, height: 20 },]) expect(() => extendRegions({ width: 100, height: 100 }, bounds)).toThrow();- expect(initialExtendBounds(8192, 400)).toEqual({ x: -0, y: -100, width: 8192, height: 600 });+ const large = initialExtendBounds(8192, 400);+ expect(large.width).toBe(EXTEND_MAX_EDGE);+ expect(large.width % 32).toBe(0);+ expect(large.height % 32).toBe(0);+ expect(large.x).toBeLessThan(0);+});++it("keeps selection and output on the generation grid without increasing the source pixel count", () => {+ const config = createProjectConfig({ name: "Extend", prompt: "", aspectRatio: "16:9", resolution: "2048p", targetDurationSeconds: 15 });+ for (const source of [{ width: 400, height: 300 }, { width: 3648, height: 2048 }, { width: 2048, height: 3648 }, { width: 8192, height: 8192 }]) {+ const bounds = initialExtendBounds(source.width, source.height);+ const layout = extendLayout(config, source, bounds);+ for (const size of [bounds, layout.output]) {+ expect(size.width % 32).toBe(0); expect(size.height % 32).toBe(0);+ expect(Math.max(size.width, size.height)).toBeLessThanOrEqual(EXTEND_MAX_EDGE);+ expect(size.width * size.height).toBeLessThanOrEqual(EXTEND_MAX_PIXELS);+ }+ expect(layout.output.width * layout.output.height).toBeLessThanOrEqual(source.width * source.height);+ expect(layout.source.width).toBeLessThan(source.width);+ expect(layout.source.height).toBeLessThan(source.height);+ expect(Math.abs(layout.source.width / source.width - layout.source.height / source.height)).toBeLessThan(1 / Math.min(source.width, source.height));+ expect(layout.regions).toHaveLength(4);+ const workspace = extendSourceDimensions(source.width, source.height);+ expect(bounds.x + bounds.width).toBeGreaterThan(workspace.width);+ expect(bounds.y + bounds.height).toBeGreaterThan(workspace.height);+ }+});++it("uses the selected resolution budget and the same scaled geometry for preservation and inpainting", () => {+ const config = createProjectConfig({ name: "Extend", prompt: "", aspectRatio: "1:1", resolution: "416p", targetDurationSeconds: 15 });+ const source = { id: "source", name: "Source", kind: "image" as const, mimeType: "image/png", width: 128, height: 96, createdAt: config.createdAt };+ const options = { bounds: { x: -64, y: -32, width: 256, height: 160 }, prompt: "Forest", steps: 20, seed: 0 };+ const compiled = compileExtendImage(config, source, "cache/source.png", options);+ expect(compiled.layout).toMatchObject({ output: { width: 128, height: 64 }, source: { width: 51, height: 38 }, bounds: { x: -38, y: -13, width: 128, height: 64 }, preserved: { x: 38, y: 13, width: 51, height: 38 } });+ expect(compiled.scene.sourceImage).toMatchObject({ width: 128, height: 64 });+ for (const edit of compiled.edits) { expect(edit.x + edit.width).toBeLessThanOrEqual(128); expect(edit.y + edit.height).toBeLessThanOrEqual(64); }+ const large = { width: 2048, height: 2048 };+ const layout = extendLayout(config, large, initialExtendBounds(large.width, large.height));+ expect(layout.output.width * layout.output.height).toBeLessThanOrEqual(416 * 416);+ expect(() => compileExtendImage(config, source, "cache/source.png", { ...options, bounds: { ...options.bounds, width: 257 } })).toThrow("multiples of 32");+});++it("aligns resize dimensions while preserving the opposite corner and caps every sizing path", () => {+ expect(alignExtendBounds({ x: -10, y: -7, width: 610, height: 455 }, "nw")).toEqual({ x: -8, y: 0, width: 608, height: 448 });+ for (const mode of ["draw", "nw", "e", "s"]) {+ const bounds = alignExtendBounds({ x: 0, y: 0, width: 9999, height: 9999 }, mode);+ expect(bounds.width % 32).toBe(0); expect(bounds.height % 32).toBe(0);+ expect(bounds.width * bounds.height).toBeLessThanOrEqual(EXTEND_MAX_PIXELS);+ expect(Math.max(bounds.width,bounds.height)).toBeLessThanOrEqual(EXTEND_MAX_EDGE);+ }});diff --git a/src/lib/extendImage.ts b/src/lib/extendImage.tsindex 9a5b984..4dcfea3 100644--- a/src/lib/extendImage.ts+++ b/src/lib/extendImage.ts@@ -1,14 +1,65 @@import { createImageEditScene } from "./imageScene";import { compileImagePrompt } from "./imagePrompt";+import { outputDimensions } from "./export";import type { ProjectAsset, ProjectConfig } from "./project";-/** Output bounds in original image pixels; negative coordinates extend left/up. */+export const EXTEND_GRID = 32;+// Largest current generation preset (2048p landscape), also usable in portrait.+const MAX_GENERATION_SIZE = outputDimensions("2048p", "16:9");+export const EXTEND_MAX_EDGE = Math.max(MAX_GENERATION_SIZE.width, MAX_GENERATION_SIZE.height);+export const EXTEND_MAX_PIXELS = MAX_GENERATION_SIZE.width * MAX_GENERATION_SIZE.height;+/** Selection bounds in the Extend workspace; negative coordinates extend left/up. */export interface ExtendBounds { x: number; y: number; width: number; height: number }export interface ExtendOptions { bounds: ExtendBounds; prompt: string; steps: number; seed: number }+export function extendSourceDimensions(width: number, height: number) {+ // Reserve room to extend even when the source is already at the model limit.+ const scale = Math.min(1, EXTEND_MAX_EDGE / (width * 1.5), EXTEND_MAX_EDGE / (height * 1.5), Math.sqrt(EXTEND_MAX_PIXELS / (width * height)) / 1.5);+ return { width: Math.max(1, Math.floor(width * scale)), height: Math.max(1, Math.floor(height * scale)) };+}+export function alignExtendBounds(bounds: ExtendBounds, mode = "se"): ExtendBounds {+ const dimension = (size: number) => Math.max(EXTEND_GRID, Math.min(EXTEND_MAX_EDGE, Math.round(size / EXTEND_GRID) * EXTEND_GRID));+ let width = dimension(bounds.width), height = dimension(bounds.height);+ if (width * height > EXTEND_MAX_PIXELS) {+ if (mode === "e" || mode === "w") width = Math.floor(EXTEND_MAX_PIXELS / height / EXTEND_GRID) * EXTEND_GRID;+ else if (mode === "n" || mode === "s") height = Math.floor(EXTEND_MAX_PIXELS / width / EXTEND_GRID) * EXTEND_GRID;+ else {+ const scale = Math.sqrt(EXTEND_MAX_PIXELS / (width * height));+ width = Math.floor(width * scale / EXTEND_GRID) * EXTEND_GRID;+ height = Math.floor(height * scale / EXTEND_GRID) * EXTEND_GRID;+ }+ }+ return { x: Math.round(bounds.x + (mode.includes("w") && mode !== "draw" ? bounds.width - width : 0)),+ y: Math.round(bounds.y + (mode.includes("n") ? bounds.height - height : 0)), width, height };+}export function initialExtendBounds(width: number, height: number): ExtendBounds {- const dx = Math.min(Math.round(width / 4), Math.floor((8192 - width) / 2));- const dy = Math.min(Math.round(height / 4), Math.floor((8192 - height) / 2));- return { x: -dx, y: -dy, width: width + dx * 2, height: height + dy * 2 };+ const source = extendSourceDimensions(width, height);+ const box = alignExtendBounds({ x: 0, y: 0, width: source.width * 1.5, height: source.height * 1.5 });+ return { ...box, x: Math.round((source.width - box.width) / 2), y: Math.round((source.height - box.height) / 2) };+}++export function extendOutputDimensions(config: ProjectConfig, source: { width: number; height: number }, bounds: ExtendBounds) {+ const selected = outputDimensions(config.settings.resolution, config.settings.aspectRatio);+ const pixelBudget = Math.min(source.width * source.height, selected.width * selected.height, EXTEND_MAX_PIXELS);+ const scale = Math.min(1, Math.sqrt(pixelBudget / (bounds.width * bounds.height)), EXTEND_MAX_EDGE / bounds.width, EXTEND_MAX_EDGE / bounds.height);+ const width = Math.floor(bounds.width * scale / EXTEND_GRID) * EXTEND_GRID;+ const height = Math.floor(bounds.height * scale / EXTEND_GRID) * EXTEND_GRID;+ if (width < EXTEND_GRID || height < EXTEND_GRID) throw new Error("The Extend box is too narrow for a 32-pixel generation grid at this resolution.");+ return { width, height };+}++export function extendLayout(config: ProjectConfig, source: { width: number; height: number }, bounds: ExtendBounds) {+ const workspace = extendSourceDimensions(source.width, source.height);+ extendRegions(workspace, bounds);+ if (bounds.width % EXTEND_GRID || bounds.height % EXTEND_GRID || bounds.width > EXTEND_MAX_EDGE || bounds.height > EXTEND_MAX_EDGE+ || bounds.width * bounds.height > EXTEND_MAX_PIXELS) throw new Error("Use box dimensions in multiples of 32 within the maximum generation resolution.");+ const output = extendOutputDimensions(config, source, bounds);+ const scale = Math.min(output.width / bounds.width, output.height / bounds.height);+ // A uniform scale preserves the source aspect ratio. Grid rounding adds a+ // little generated space instead of stretching the original to fit.+ const scaledSource = { width: Math.max(1, Math.round(workspace.width * scale)), height: Math.max(1, Math.round(workspace.height * scale)) };+ const mappedBounds = { x: Math.round(bounds.x * scale - (output.width - bounds.width * scale) / 2),+ y: Math.round(bounds.y * scale - (output.height - bounds.height * scale) / 2), ...output };+ return { output, source: scaledSource, bounds: mappedBounds, ...extendRegions(scaledSource, mappedBounds) };}export function extendRegions(source: { width: number; height: number }, bounds: ExtendBounds) {@@ -33,20 +84,21 @@ export function extendRegions(source: { width: number; height: number }, bounds:export function compileExtendImage(config: ProjectConfig, source: ProjectAsset, sourceRelativePath: string, options: ExtendOptions) {if (!source.width || !source.height) throw new Error("Wait for the source image dimensions to load.");- const { regions } = extendRegions({ width: source.width, height: source.height }, options.bounds);+ const layout = extendLayout(config, { width: source.width, height: source.height }, options.bounds);+ const { regions, output } = layout;if (!Number.isInteger(options.steps) || options.steps < 2 || options.steps > 1000) throw new Error("Steps must be a whole number from 2 to 1000.");if (!Number.isSafeInteger(options.seed) || options.seed < -1) throw new Error("Seed must be -1 for random or a non-negative safe integer.");- const scene = createImageEditScene({ relativePath: sourceRelativePath, name: source.name, width: options.bounds.width, height: options.bounds.height });+ const scene = createImageEditScene({ relativePath: sourceRelativePath, name: source.name, ...output });scene.steps = options.steps; scene.seed = options.seed;scene.nodes[0].description = "Extend the scene naturally beyond its original framing. Continue the environment, objects, textures, perspective and lighting into the new space. Preserve the original scene and visual style. Replace the stretched edge placeholders with coherent new content. " + options.prompt.trim();const compiled = compileImagePrompt({ ...config, settings: { ...config.settings, defaultLook: null }, imageScene: scene });// The rectangular editor needs a little original context at each seam.- // The native finalizer restores all original pixels after every region is generated.+ // The native finalizer restores the downscaled source pixels after generation.const overlap = 32;const edits = regions.map((region) => {const x = Math.max(0, region.x - overlap), y = Math.max(0, region.y - overlap);- return { x, y, width: Math.min(options.bounds.width, region.x + region.width + overlap) - x,- height: Math.min(options.bounds.height, region.y + region.height + overlap) - y, prompt: compiled.prompt };+ return { x, y, width: Math.min(output.width, region.x + region.width + overlap) - x,+ height: Math.min(output.height, region.y + region.height + overlap) - y, prompt: compiled.prompt };});- return { ...compiled, scene, edits };+ return { ...compiled, scene, edits, layout };}diff --git a/src/lib/extendWork.test.ts b/src/lib/extendWork.test.tsindex fb7e387..6244872 100644--- a/src/lib/extendWork.test.ts+++ b/src/lib/extendWork.test.ts@@ -17,7 +17,7 @@ vi.mock("./runtime", () => ({ cancelSlopfabGeneration: vi.fn(), enqueueSlopfabGeconst handlers = new Map<string, (event: { payload: unknown }) => void>();const template: GeneratorTemplate = { id: "h3", name: "H3", modelType: "minimax-h3", defaultSteps: 20, attention: "sage2", paths: { ...EMPTY_ENGINE_SETTINGS, transformer: "C:/h3.safetensors" } };const options = (): ExtendOptions => ({ bounds: { x: -64, y: -32, width: 256, height: 160 }, prompt: "Continue the forest", steps: 25, seed: 0 });-const result = { relativePath: "media/generated/extended.png", width: 256, height: 160 };+const result = { relativePath: "media/generated/extended.png", width: 128, height: 64 };let stop: (() => void) | undefined;beforeEach(() => {localStorage.clear(); vi.resetAllMocks(); handlers.clear();@@ -54,12 +54,12 @@ it.each([false, true])("extends a frozen source and saves a child with a durableexpect(queue.getSnapshot()).toHaveLength(1);const request = await submitted();const { jobId } = request;- expect(request).toMatchObject({ stillImage: true, frames: 1, seed: 0, steps: 25, canvasWidth: 256, canvasHeight: 160,+ expect(request).toMatchObject({ stillImage: true, frames: 1, seed: 0, steps: 25, canvasWidth: 128, canvasHeight: 64,imageEdit: { sourceRelativePath: `cache/extend-images/${jobId}/canvas.png` }, referencePaths: [`C:/Extend/cache/extend-images/${jobId}/canvas.png`] });expect(request.imageEdit!.edits).toHaveLength(4);expect(request.prompt).toContain("Continue the forest");expect(request.prompt).not.toContain("Changed");- expect(invoke).toHaveBeenCalledWith("prepare_extend_image", { folderPath: "C:/Extend", jobId, sourceId: "source", bounds: options().bounds });+ expect(invoke).toHaveBeenCalledWith("prepare_extend_image", { folderPath: "C:/Extend", jobId, sourceId: "source", bounds: options().bounds, output: { width: 128, height: 64 } });if (changed) session.update((config) => ({ ...config, imageScene: { ...config.imageScene!, nodes: config.imageScene!.nodes.map((node) => ({ ...node, description: "New prompt" })) } }));emit("framesReady", jobId);await waitFor(() => expect(queue.getSnapshot()[0].status).toBe("completed"));diff --git a/src/lib/workQueue.ts b/src/lib/workQueue.tsindex 9907903..7867724 100644--- a/src/lib/workQueue.ts+++ b/src/lib/workQueue.ts@@ -281,7 +281,7 @@ export class WorkQueue {const referencePaths = [projectItemPath(session.record.folderPath, { relativePath: sourceRelativePath })!,...compiled.references.flatMap((reference) => referenceImages(reference).map((image) => projectItemPath(session.record.folderPath, image)!))];const request: SlopfabGenerationRequest = { jobId: id, stillImage: true, frames: 1, prompt: compiled.prompt,- canvasWidth: options.bounds.width, canvasHeight: options.bounds.height, steps: generationStepsWithLoras(options.steps, config), seed: imageGenerationSeed(options.seed),+ canvasWidth: compiled.layout.output.width, canvasHeight: compiled.layout.output.height, steps: generationStepsWithLoras(options.steps, config), seed: imageGenerationSeed(options.seed),referencePaths, refmods: referenceRefmodInputs(session.record.folderPath, compiled.references),imageEdit: { sourceRelativePath, edits: compiled.edits } };let finish!: () => void;@@ -384,7 +384,8 @@ export class WorkQueue {if (work.cancelled) continue;if (work.characterSheet) { await this.generateCharacterSheet(work); continue; }if (work.extend) {- await invoke("prepare_extend_image", { folderPath: next.folderPath, jobId: work.id, sourceId: work.extend.sourceId, bounds: work.extend.options.bounds });+ await invoke("prepare_extend_image", { folderPath: next.folderPath, jobId: work.id, sourceId: work.extend.sourceId, bounds: work.extend.options.bounds,+ output: { width: work.request.canvasWidth, height: work.request.canvasHeight } });if (work.cancelled) continue;}if (work.request.previousSceneId) {