Edit photos by describing the change, on your own GPU. A free, open-source alternative to Nano Banana and ChatGPT image editing: photos stay on your computer, no daily limit. One installer for Windows, Mac and Linux sets up the best open model (Qwen-Image 2.1). MCP server for AI agents.
TypeScript ai-photo-editorcomfyui-alternativegenerative-fillimage-editingimage-generationinpaintinglinuxlocal-aimacosmcpmcp-servernano-banana-alternativeofflinephoto-editorprivacyqwen-imageqwen-image-2-1stable-diffusion-cppvulkanwindows
Layers lab: progress and Stop for quick cut-outs, lab edits and model downloads
Gabriele Lozuponee5075fe1bf18
diff --git a/crates/qls-core/src/engine.rs b/crates/qls-core/src/engine.rsindex 4f7f681..41f73e7 100644--- a/crates/qls-core/src/engine.rs+++ b/crates/qls-core/src/engine.rs@@ -965,13 +965,13 @@ impl Engine {/// The fast-sticker matte of an image already in Kokon ("input:"/"gen:"), as a grey PNG at/// its size (white = the main thing in it; the layers lab combines it with the selection).- pub fn matte(&self, src: &str) -> AppResult<Vec<u8>> {+ pub fn matte(&self, src: &str, run: Option<&str>) -> AppResult<Vec<u8>> {if !src.starts_with("input:") && !src.starts_with("gen:") {return Err(AppError::invalid("Stickers are made from images already in Kokon."));}let (bytes, _, _) = self.read_source(src, None)?;let img = imaging::decode_image(&bytes)?;- let m = crate::matting::matte(&self.config().sdcpp_dir, &img.pixels)?;+ let m = crate::matting::matte(&self.config().sdcpp_dir, &img.pixels, run)?;let rgba = image::DynamicImage::ImageLuma8(m).to_rgba8();imaging::encode_png(&rgba, &[], None, true)}diff --git a/crates/qls-core/src/matting.rs b/crates/qls-core/src/matting.rsindex d3d9290..cadc0be 100644--- a/crates/qls-core/src/matting.rs+++ b/crates/qls-core/src/matting.rs@@ -5,11 +5,14 @@//! 16-thread CPU, no VRAM taken from the image engine. The webview could not run it (WebGPU kernels//! rejected, WASM out of memory), hence here. Also the MobileSAM files the lab's Select uses.+use std::collections::HashMap;use std::path::{Path, PathBuf};-use std::sync::Mutex;+use std::sync::atomic::{AtomicBool, Ordering};+use std::sync::{Arc, LazyLock, Mutex};+use std::time::{Duration, Instant};use image::{GrayImage, RgbaImage, imageops::FilterType};-use ort::session::Session;+use ort::session::{RunOptions, Session};use ort::value::Tensor;use crate::catalog::{Download, FileKind, join_rel};@@ -112,14 +115,139 @@ pub fn matte_image(logits: &[f32], w: u32, h: u32) -> GrayImage {image::imageops::resize(&m, w, h, FilterType::Triangle)}-/// The matte of `img` at its own size (white = the main thing in it).-pub fn matte(sdcpp_dir: &Path, img: &RgbaImage) -> AppResult<GrayImage> {+/// Something running that can be told to stop.+pub trait Stop {+ fn stop(&self);+}++/// One quick cut-out's model run: ONNX Runtime ends it at its next operator once `stop` is called+/// (also before it starts: a run whose flag is set exits at once).+pub struct Run {+ opts: RunOptions,+ stopped: AtomicBool,+}++impl Run {+ fn new() -> AppResult<Self> {+ Ok(Self { opts: RunOptions::new().map_err(ort_err)?, stopped: AtomicBool::new(false) })+ }+ fn is_stopped(&self) -> bool {+ self.stopped.load(Ordering::SeqCst)+ }+}++impl Stop for Run {+ fn stop(&self) {+ self.stopped.store(true, Ordering::SeqCst);+ let _ = self.opts.terminate();+ }+}++enum Slot<T> {+ Running(Arc<T>),+ /// Stop came before the run (the app stopped it while uploading): the run, if it comes, ends at once.+ Stopped(Instant),+}++/// The quick cut-outs being made, by the id the app gave each one, so Stop can end it in the+/// service (`POST /matte/cancel`) and not only stop waiting in the window.+pub struct Runs<T> {+ slots: Mutex<HashMap<String, Slot<T>>>,+}++/// How long a Stop that came first is remembered.+const STOPPED_KEPT: Duration = Duration::from_secs(120);++impl<T: Stop> Runs<T> {+ pub fn new() -> Self {+ Self { slots: Mutex::new(HashMap::new()) }+ }++ /// Registers `run` under `id`; false if `id` was stopped already (the caller gives up).+ pub fn start(&self, id: &str, run: Arc<T>) -> bool {+ let mut slots = self.slots.lock().unwrap_or_else(|p| p.into_inner());+ slots.retain(|_, s| !matches!(s, Slot::Stopped(at) if at.elapsed() > STOPPED_KEPT));+ if matches!(slots.get(id), Some(Slot::Stopped(_))) {+ slots.remove(id);+ return false;+ }+ slots.insert(id.to_string(), Slot::Running(run));+ true+ }++ /// The run of `id` is over (done, failed or stopped).+ pub fn finish(&self, id: &str) {+ let mut slots = self.slots.lock().unwrap_or_else(|p| p.into_inner());+ if matches!(slots.get(id), Some(Slot::Running(_))) {+ slots.remove(id);+ }+ }++ /// Stops `id`: true if it was running; otherwise it is remembered and ends as soon as it starts.+ pub fn cancel(&self, id: &str) -> bool {+ let mut slots = self.slots.lock().unwrap_or_else(|p| p.into_inner());+ match slots.get(id) {+ Some(Slot::Running(r)) => {+ r.stop();+ true+ }+ _ => {+ slots.insert(id.to_string(), Slot::Stopped(Instant::now()));+ false+ }+ }+ }++ pub fn running(&self) -> usize {+ self.slots.lock().unwrap_or_else(|p| p.into_inner()).values().filter(|s| matches!(s, Slot::Running(_))).count()+ }+}++impl<T: Stop> Default for Runs<T> {+ fn default() -> Self {+ Self::new()+ }+}++static RUNS: LazyLock<Runs<Run>> = LazyLock::new(Runs::new);++/// Stops the quick cut-out `id` (running, or about to start). True if it was running.+pub fn cancel(id: &str) -> bool {+ RUNS.cancel(id)+}++fn cancelled() -> AppError {+ AppError::new(ErrorCode::Cancelled, "The quick cut-out was stopped.")+}++/// The matte of `img` at its own size (white = the main thing in it). `run`: the id Stop uses+/// (`cancel`); a stopped run returns ErrorCode::Cancelled.+pub fn matte(sdcpp_dir: &Path, img: &RgbaImage, run: Option<&str>) -> AppResult<GrayImage> {let path = model_path(sdcpp_dir);if !path.is_file() {return Err(AppError::new(ErrorCode::MissingModel, "The fast sticker model is not downloaded yet."));}+ let this = Arc::new(Run::new()?);+ struct Finish<'a>(Option<&'a str>);+ impl Drop for Finish<'_> {+ fn drop(&mut self) {+ if let Some(id) = self.0 {+ RUNS.finish(id);+ }+ }+ }+ if let Some(id) = run+ && !RUNS.start(id, this.clone())+ {+ return Err(cancelled());+ }+ let _finish = Finish(run);let x = input_tensor(img);+ // Another cut-out may hold the model: a Stop while waiting for it is seen here.let mut guard = SESSION.lock().unwrap_or_else(|p| p.into_inner());+ if this.is_stopped() {+ return Err(cancelled());+ }if guard.as_ref().is_none_or(|(p, _, _)| p != &path) {let threads = std::thread::available_parallelism().map(|n| n.get()).unwrap_or(4);let env = crate::onnx::environment().map_err(ort_err)?;@@ -128,7 +256,11 @@ pub fn matte(sdcpp_dir: &Path, img: &RgbaImage) -> AppResult<GrayImage> {}let (_, _, session) = guard.as_mut().unwrap();let input = Tensor::from_array(([1usize, 3, SIDE as usize, SIDE as usize], x.into_boxed_slice())).map_err(ort_err)?;- let outputs = session.run(ort::inputs![input]).map_err(ort_err)?;+ let outputs = match session.run_with_options(ort::inputs![input], &this.opts) {+ Ok(o) => o,+ Err(_) if this.is_stopped() => return Err(cancelled()),+ Err(e) => return Err(ort_err(e)),+ };let (_, logits) = outputs[outputs.len() - 1].try_extract_tensor::<f32>().map_err(ort_err)?;if logits.len() != (SIDE * SIDE) as usize {return Err(AppError::new(ErrorCode::Internal, "The sticker model returned an unexpected size."));@@ -140,6 +272,42 @@ pub fn matte(sdcpp_dir: &Path, img: &RgbaImage) -> AppResult<GrayImage> {mod tests {use super::*;+ #[derive(Default)]+ struct Fake(AtomicBool);+ impl Stop for Fake {+ fn stop(&self) {+ self.0.store(true, Ordering::SeqCst);+ }+ }++ #[test]+ fn runs_stop_the_running_one_only() {+ let runs = Runs::new();+ let a = Arc::new(Fake::default());+ let b = Arc::new(Fake::default());+ assert!(runs.start("a", a.clone()));+ assert!(runs.start("b", b.clone()));+ assert!(runs.cancel("a"));+ assert!(a.0.load(Ordering::SeqCst));+ assert!(!b.0.load(Ordering::SeqCst));+ runs.finish("a");+ runs.finish("b");+ assert_eq!(runs.running(), 0);+ }++ #[test]+ fn a_stop_before_the_run_ends_it_when_it_comes() {+ let runs = Runs::new();+ assert!(!runs.cancel("x"));+ assert!(!runs.start("x", Arc::new(Fake::default())));+ // Remembered once: the next run with that id goes ahead.+ assert!(runs.start("x", Arc::new(Fake::default())));+ runs.finish("x");+ // A stop after the run finished does not stop a later run forever either.+ assert!(!runs.cancel("y"));+ assert_eq!(runs.running(), 0);+ }+#[test]fn only_the_sam_files_are_served() {let d = Path::new("/kokon");@@ -180,7 +348,7 @@ mod tests {#[test]fn missing_model_is_said() {let dir = tempfile::tempdir().unwrap();- let e = matte(dir.path(), &RgbaImage::new(4, 4)).unwrap_err();+ let e = matte(dir.path(), &RgbaImage::new(4, 4), None).unwrap_err();assert!(e.to_string().contains("not downloaded"));}}@@ -197,7 +365,7 @@ mod real_model {let img = image::open(std::env::var("KOKON_MATTE_IMAGE").unwrap()).unwrap().to_rgba8();for _ in 0..2 {let t = std::time::Instant::now();- let m = matte(&dir, &img).unwrap();+ let m = matte(&dir, &img, None).unwrap();eprintln!("matte {:?} in {:.2} s", m.dimensions(), t.elapsed().as_secs_f32());m.save(std::env::temp_dir().join("kokon-matte.png")).unwrap();}@@ -219,9 +387,37 @@ mod shared_runtime_tests {// On the CPU the first matte (session included) takes ~8 s on an M2 Pro; on the Neural// Engine (ort's default device policy, crate::onnx::cpu_session) it never came back.let started = std::time::Instant::now();- let m = super::matte(&dir, &marked).unwrap();+ let m = super::matte(&dir, &marked, None).unwrap();assert!(started.elapsed().as_secs() < 90, "first matte took {:?}", started.elapsed());assert_eq!(m.dimensions(), (400, 300));assert!(crate::watermark::detect(&dir, &marked).unwrap().unwrap().kokon);}++ /// Stop ends the model's run in the service: before it starts (stopped while uploading) at+ /// once, and during it well before a run would finish (~1 s vs 4-6 s per matte).+ #[test]+ fn stop_ends_the_run() {+ let Ok(dir) = std::env::var("KOKON_TEST_SDCPP") else { return };+ let dir = std::path::PathBuf::from(dir);+ let img = image::RgbaImage::from_pixel(640, 480, image::Rgba([90, 140, 200, 255]));+ // The session is loaded first, so the timings below are the run's alone.+ super::matte(&dir, &img, None).unwrap();+ assert!(!super::cancel("test-early"));+ let e = super::matte(&dir, &img, Some("test-early")).unwrap_err();+ assert_eq!(e.code, crate::error::ErrorCode::Cancelled);+ // The same id can be used again afterwards.+ let t = std::time::Instant::now();+ super::matte(&dir, &img, Some("test-early")).unwrap();+ let whole = t.elapsed();+ let stopper = std::thread::spawn(|| {+ std::thread::sleep(std::time::Duration::from_millis(300));+ assert!(super::cancel("test-during"));+ });+ let t = std::time::Instant::now();+ let e = super::matte(&dir, &img, Some("test-during")).unwrap_err();+ stopper.join().unwrap();+ assert_eq!(e.code, crate::error::ErrorCode::Cancelled);+ assert!(t.elapsed() < whole, "stopped after {:?}, a whole run {:?}", t.elapsed(), whole);+ assert_eq!(super::RUNS.running(), 0);+ }}diff --git a/crates/qls-core/src/remote.rs b/crates/qls-core/src/remote.rsindex c483021..bbfbf31 100644--- a/crates/qls-core/src/remote.rs+++ b/crates/qls-core/src/remote.rs@@ -270,7 +270,7 @@ pub fn browser_allowed(method: &str, path: &str) -> bool {("GET", ["gallery", _] | ["gallery", _, "image" | "thumb" | "preview" | "original"]) => true,("GET", ["projects", _, "records"]) => true,("GET", ["luts", _, "preview"]) => true,- ("GET" | "POST", ["matte"]) | ("POST", ["matte", "download"]) => true,+ ("GET" | "POST", ["matte"]) | ("POST", ["matte", "download" | "cancel"]) => true,("GET" | "PUT" | "DELETE", ["projects", _]) => true,("PUT", ["config"]) => true,("POST", ["setup", "install" | "gpu"] | ["setup", "install", "cancel"]) => true,diff --git a/crates/qls-service/src/api.rs b/crates/qls-service/src/api.rsindex 10b2e85..f077afe 100644--- a/crates/qls-service/src/api.rs+++ b/crates/qls-service/src/api.rs@@ -82,6 +82,7 @@ pub fn router(state: Arc<AppState>, lan: bool) -> Router {.route("/upscalers/{name}/download", post(download_upscaler)).route("/matte", get(matte_status).post(matte_image)).route("/matte/download", post(matte_download))+ .route("/matte/cancel", post(matte_cancel)).route("/segment", get(segment_status)).route("/segment/download", post(segment_download)).route("/segment/models/{file}", get(segment_model))@@ -520,22 +521,50 @@ async fn segment_model(State(s): St, AxPath(file): AxPath<String>) -> ApiResult<struct MatteBody {/// "input:<id>" / "gen:<id>".image: String,+ /// The app's id for this cut-out, for Stop (`/matte/cancel`).+ run: Option<String>,}/// The matte of an image (grey PNG at its size) for a fast sticker.async fn matte_image(State(s): St, Json(b): Json<MatteBody>) -> ApiResult<Response> {let engine = s.engine.clone();let image = b.image.clone();+ // Every run has an id: when the app drops the request (Stop, the lab closed), the guard below+ // stops the model too instead of letting it finish for no one.+ let run = b.run.clone().unwrap_or_else(|| format!("auto-{}", uuid::Uuid::new_v4()));+ struct StopIfDropped(String, bool);+ impl Drop for StopIfDropped {+ fn drop(&mut self) {+ if !self.1 {+ qls_core::matting::cancel(&self.0);+ }+ }+ }+ let mut guard = StopIfDropped(run.clone(), false);let started = std::time::Instant::now();- let res = tokio::task::spawn_blocking(move || engine.matte(&b.image)).await.map_err(AppError::internal)?;+ let res = tokio::task::spawn_blocking(move || engine.matte(&b.image, Some(&run))).await.map_err(AppError::internal)?;+ guard.1 = true;// Logged: a quick cut-out that fails or crawls is otherwise invisible (the lab runs it in the window).match &res {Ok(_) => tracing::info!("quick cut-out matte of {image} in {} ms", started.elapsed().as_millis()),+ Err(e) if e.code == ErrorCode::Cancelled => tracing::info!("quick cut-out matte of {image} stopped after {} ms", started.elapsed().as_millis()),Err(e) => tracing::warn!("quick cut-out matte of {image} failed after {} ms: {} {:?}", started.elapsed().as_millis(), e.message, e.detail),}Ok(([(header::CONTENT_TYPE, "image/png")], res?).into_response())}+#[derive(Deserialize)]+struct MatteCancelBody {+ run: String,+}++/// Stop for a quick cut-out: its model run ends at once (or as soon as it starts).+async fn matte_cancel(Json(b): Json<MatteCancelBody>) -> Json<Value> {+ let running = qls_core::matting::cancel(&b.run);+ tracing::info!("quick cut-out {} stopped ({})", b.run, if running { "while running" } else { "before it ran" });+ Json(json!({ "stopped": running }))+}+/// Upscaler models of earlier versions in the app's own folder (Settings offers to delete/// them; files elsewhere are never touched).#[derive(Deserialize)]diff --git a/crates/qls-service/src/security_tests.rs b/crates/qls-service/src/security_tests.rsindex d092935..0cce579 100644--- a/crates/qls-service/src/security_tests.rs+++ b/crates/qls-service/src/security_tests.rs@@ -368,4 +368,10 @@ async fn fast_stickers_take_only_images_already_in_kokon() {let r = send(&a, "POST", "/api/v1/matte", &[c, CSRF], Some(json!({ "image": image }))).await;assert_eq!((r.status, r.code()), (StatusCode::BAD_REQUEST, "invalid_input"), "{image}");}+ // Stop: signed in with the CSRF header only.+ let stop = json!({ "run": "r1" });+ let r = send(&a, "POST", "/api/v1/matte/cancel", &[c, CSRF], Some(stop.clone())).await;+ assert_eq!((r.status, r.body["stopped"].clone()), (StatusCode::OK, json!(false)));+ assert_ne!(send(&a, "POST", "/api/v1/matte/cancel", &[c], Some(stop.clone())).await.status, StatusCode::OK);+ assert_eq!(send(&a, "POST", "/api/v1/matte/cancel", &[CSRF], Some(stop)).await.status, StatusCode::UNAUTHORIZED);}diff --git a/src/components/LabStage.tsx b/src/components/LabStage.tsxindex 9279cb1..4f8e4ef 100644--- a/src/components/LabStage.tsx+++ b/src/components/LabStage.tsx@@ -2,10 +2,11 @@// (one frame per split image in the version strip, the composite on the Stage) instead of the lab's// own versions; clicking it opens that image's layers.-import { Layers, Loader2, X } from "lucide-react";+import { Layers, Loader2, Square, X } from "lucide-react";import { useEffect, useMemo, useState, useSyncExternalStore } from "react";import { docId, docsVersion, jobLayer, waitingMarks, labItems, leftovers, loadLab, saveLab, subscribeDocs, type LabStore, type LayerDoc } from "../lib/layerDoc";-import { editSource, itemOrigin, itemSource, removeSessionItem, setState, useStore, type SessionItem } from "../lib/store";+import { cancelJob, editSource, itemOrigin, itemSource, removeSessionItem, setState, useStore, type SessionItem } from "../lib/store";+import { jobStepText } from "../lib/logic";import type { JobView } from "../lib/types";import { urls } from "../lib/api";import { useJobPercent } from "./jobMotion";@@ -149,7 +150,12 @@ function JobPill({ j }: { j: LabJob }) {return (<span className="lab-progress"><Loader2 className="spin" size={13} />- {PHASE[j.job.status] ? `${PHASE[j.job.status]}${what ? ` · ${what}` : ""}` : `Generating${what ? ` ${what}` : ""}`} · <JobPct job={j.job} item={j.item} />+ {PHASE[j.job.status] ? `${PHASE[j.job.status]}${what ? ` · ${what}` : ""}` : `Generating${what ? ` ${what}` : ""}`}+ {jobStepText(j.job) ? ` · ${jobStepText(j.job)}` : ""} · <JobPct job={j.job} item={j.item} />+ {/* Stop: a queued edit leaves the queue, a running one stops in the engine; the layers stay as they are. */}+ <button className="lab-dismiss" title="Stop this edit (the layers stay as they are)" aria-label="Stop" onClick={() => cancelJob(j.job.id)}>+ <Square size={11} />+ </button></span>);}diff --git a/src/components/LayerDoc.tsx b/src/components/LayerDoc.tsxindex df86417..36a568d 100644--- a/src/components/LayerDoc.tsx+++ b/src/components/LayerDoc.tsx@@ -10,14 +10,14 @@// the flattened layers: "New objects" adds what the user drew with the coloured pencil as new// layers, "Edit together" gives the selected objects the edit's look. "Save as image" flattens the layers into a new version; "Export PSD" saves them for Photoshop (lib/psd.ts).-import { Brush, Eraser, Eye, EyeOff, FileDown, GripVertical, Group, Hand, History, ImageDown, Link2, Loader2, Lock, MousePointer2, Paintbrush, Pencil, Redo2, RotateCcw, Scissors, Sparkles, Sun, Trash2, Undo2, Ungroup, WandSparkles, X } from "lucide-react";+import { Brush, Eraser, Eye, EyeOff, FileDown, GripVertical, Group, Hand, History, ImageDown, Link2, Loader2, Lock, MousePointer2, Paintbrush, Pencil, Redo2, RotateCcw, Scissors, Sparkles, Square, Sun, Trash2, Undo2, Ungroup, WandSparkles, X } from "lucide-react";import { useEffect, useMemo, useRef, useState } from "react";-import { api, urls } from "../lib/api";-import { focusPixels, foreground, keptShare, MIN_KEPT, modelMatte, stickerAlpha } from "../lib/matte";+import { api, isStopped, Stopped, urls } from "../lib/api";+import { checkStop, cutControl, focusPixels, foreground, keptShare, MIN_KEPT, modelMatte, stickerAlpha, type CutControl } from "../lib/matte";import { blendPrompt, DEFAULT_READING } from "../lib/blend";import { dilate, erode, fileSafe } from "../lib/layers";-import { centre, copiedShare, CROP_MAX_RATIO, cropFor, docId, extOf, unionRect, type Rect, waitingMarks, shadowAlpha, strengthPixels, mapBox, reorder, unmapPoint, withGroup, xfOf, type Box, type DocLayer, type Effect, type Feed, type LayerDoc, type SceneEdit, type Sticker, type Xf } from "../lib/layerDoc";-import { buildRequest, refFromInput } from "../lib/logic";+import { centre, copiedShare, stoppedScenes, CROP_MAX_RATIO, cropFor, docId, extOf, unionRect, type Rect, waitingMarks, shadowAlpha, strengthPixels, mapBox, reorder, unmapPoint, withGroup, xfOf, type Box, type DocLayer, type Effect, type Feed, type LayerDoc, type SceneEdit, type Sticker, type Xf } from "../lib/layerDoc";+import { buildRequest, cutoutText, downloadIsFor, jobStepText, refFromInput, type CutStep } from "../lib/logic";import { native } from "../lib/native";import { aiMarkingXmp, writePsd } from "../lib/psd";import { MARK_COLOURS, marksPrompt, type MarkColour } from "../lib/sceneEdit";@@ -65,7 +65,37 @@ function ShadowPhase({ job, item }: { job: JobView; item: SessionItem }) {if (job.status === "queued") return <>Waiting for the edits before it</>;if (job.status === "starting_backend") return <>Starting the engine</>;if (job.status === "done") return <>Reading what the AI added</>;- return <>Blending into the scene · {Math.floor(pct)}%</>;+ const step = jobStepText(job);+ return (+ <>+ Blending into the scene{step ? ` · ${step}` : ""} · {Math.floor(pct)}%+ </>+ );+}++/** "waiting", "starting the engine", "step 3 of 8 · 38%": where a lab job is. */+function JobProgressText({ job, item }: { job: JobView; item?: SessionItem }) {+ const { pct } = useJobPercent(job, item?.request);+ if (job.status === "queued") return <>waiting for the edits before it</>;+ if (job.status === "starting_backend") return <>starting the engine</>;+ if (job.status === "enhancing_prompt") return <>writing the prompt</>;+ const step = jobStepText(job);+ return (+ <>+ {step ? `${step} · ` : ""}+ {Math.floor(pct)}%+ </>+ );+}++/** Re-renders every half second while `on` (seconds counting up in a status line). */+function useTick(on: boolean) {+ const [, setT] = useState(0);+ useEffect(() => {+ if (!on) return;+ const id = window.setInterval(() => setT((t) => t + 1), 500);+ return () => window.clearInterval(id);+ }, [on]);}/** What the canvas needs of a layer's version: its alpha (for clicks), where its content is, a thumbnail. */@@ -420,6 +450,8 @@ export function LayerDoc({ projectId, doc, onChange, onNewSplit }: { projectId:const zoomK = useRef(1);const [spacePressed, setSpacePressed] = useState(false);const [busy, setBusy] = useState(false);+ /** What a save or export is doing, for the header (null when nothing). */+ const [working, setWorking] = useState<string | null>(null);const [rowDrag, setRowDrag] = useState<{ from: number; over: number } | null>(null);// The layer being renamed (double-click), so a click on a row leaves the arrows to nudging.const [renaming, setRenaming] = useState<string | null>(null);@@ -699,7 +731,8 @@ export function LayerDoc({ projectId, doc, onChange, onNewSplit }: { projectId:/** A fast sticker, as the layer's next version: the object over the photo around it, matted by the* service (lib/matte.ts: the selection decides what, the matte only the edge; edge colours freed of* the background). Deterministic, a few seconds; Clean edges is the AI redraw. */- const fastSticker = async (l: DocLayer) => {+ const fastSticker = async (l: DocLayer, ctl?: CutControl) => {+ ctl?.phase("preparing");const e = extOf(liveRef.current, l.source);if (e.x < 0 || e.y < 0 || e.w > W || e.h > H) throw new Error(`${l.name} reaches past the photo: use Clean edges.`);const info = await sourceInfo(l.source, W, H);@@ -732,7 +765,11 @@ export function LayerDoc({ projectId, doc, onChange, onNewSplit }: { projectId:// The object in its scene (a new object drawn by the lab is over the photo too).const rgba = scene(w, h, true).getContext("2d")!.getImageData(0, 0, w, h).data;if (!sel.some((v) => v)) throw new Error(`${l.name} has no pixels to cut out.`);- const matte = await modelMatte(focusPixels(rgba, sel, w, h), w, h);+ checkStop(ctl);+ const matte = await modelMatte(focusPixels(rgba, sel, w, h), w, h, ctl);+ ctl?.phase("edges");+ // Lets the status line show the step before the edge work holds the page.+ await new Promise((r) => window.setTimeout(r, 0));const { alpha } = stickerAlpha(matte, sel, w, h);// Checked before anything changes: a cut-out that kept (almost) nothing leaves the layer as it was.const kept = keptShare(alpha, sel);@@ -753,25 +790,39 @@ export function LayerDoc({ projectId, doc, onChange, onNewSplit }: { projectId:for (let i = 0; i < cw * ch; i++) if (d.data[i * 4 + 3] > 250) for (let c = 0; c < 3; c++) d.data[i * 4 + c] = full[i * 4 + c];octx.putImageData(d, x0, y0);}- const rec = await api.upload(await toPng(out), `${fileSafe(l.name)} (sticker).png`);+ checkStop(ctl);+ ctl?.phase("saving");+ const rec = await api.upload(await toPng(out), `${fileSafe(l.name)} (sticker).png`, ctl?.signal);+ // Stopped up to here: the layer is as it was (the uploaded file stays out of sight).+ checkStop(ctl);addVersions([rec], 0);const src = `input:${rec.id}`;const now = liveRef.current;commitRef.current({ ...now, layers: now.layers.map((x) => (x.id === l.id ? { ...x, source: src, history: [...x.history, src] } : x)), known: [...now.known, src] });};- /** The fast sticker model is downloaded once (224 MB), the first time Fast is used; the % shows. */+ /** The fast sticker model is downloaded once (224 MB), the first time Fast is used; the % shows.+ * Aborting `signal` cancels the download (when it is this one) and throws Stopped. */const [matteDl, setMatteDl] = useState<number | null>(null);- const ensureMatteModel = async () => {+ const ensureMatteModel = async (signal?: AbortSignal) => {if ((await api.matteStatus()).installed) return;setMatteDl(0);+ const stop = () => {+ api+ .installStatus()+ .then((st) => (downloadIsFor(st, "matting") ? api.cancelInstall() : null))+ .catch(() => {});+ };+ signal?.addEventListener("abort", stop);try {await api.downloadMatte();for (;;) {await new Promise((r) => window.setTimeout(r, 1000));+ if (signal?.aborted) throw new Stopped();const st = await api.installStatus();const it = st.items.find((i) => i.id === "birefnet_lite");- if (it?.state === "failed" || it?.state === "cancelled") throw new Error(it.error ?? "The sticker model could not be downloaded.");+ if (it?.state === "cancelled") throw new Stopped();+ if (it?.state === "failed") throw new Error(it.error ?? "The sticker model could not be downloaded.");if (it?.state === "done" || it?.state === "present") return;if (!st.running) {if ((await api.matteStatus()).installed) return;@@ -780,18 +831,50 @@ export function LayerDoc({ projectId, doc, onChange, onNewSplit }: { projectId:if (it?.size) setMatteDl(Math.floor((100 * it.received) / it.size));}} finally {+ signal?.removeEventListener("abort", stop);setMatteDl(null);}};++ /** The quick cut-out being made (one at a time): which layer ("" while the model is fetched for+ * the automatic stickers), its step and since when. Stop ends it, in the service too. */+ const [cut, setCut] = useState<{ layer: string; name: string; step: CutStep; at: number } | null>(null);+ const cutRef = useRef<(CutControl & { abort: () => void; layer: string }) | null>(null);+ const startCut = (layer: string, name: string) => {+ const ctl: CutControl & { abort: () => void; layer: string } = Object.assign(+ cutControl((step) => {+ if (cutRef.current === ctl) setCut({ layer, name, step, at: Date.now() });+ }),+ { layer },+ );+ cutRef.current = ctl;+ setCut({ layer, name, step: "preparing", at: Date.now() });+ return ctl;+ };+ const endCut = (ctl: CutControl) => {+ if (cutRef.current !== ctl) return;+ cutRef.current = null;+ setCut(null);+ };+ const stopCut = () => cutRef.current?.abort();+ // Leaving the lab stops a cut-out still being made (its result would land nowhere).+ useEffect(() => () => cutRef.current?.abort(), []);+ useTick(!!cut);+ const cutLine = cut ? cutoutText(cut.name, cut.step, (Date.now() - cut.at) / 1000, matteDl) : "";+const quickClean = async (l: DocLayer) => {+ const ctl = startCut(l.id, l.name);setBusy(true);try {- await ensureMatteModel();- await fastSticker(l);+ ctl.phase("model");+ await ensureMatteModel(ctl.signal);+ await fastSticker(l, ctl);toastInfo(`${l.name}: quick cut-out done.`);} catch (e) {- toastError(e);+ if (isStopped(e)) toastInfo(`Quick cut-out stopped: ${l.name} is as it was.`);+ else toastError(e);} finally {+ endCut(ctl);setBusy(false);}};@@ -841,11 +924,15 @@ export function LayerDoc({ projectId, doc, onChange, onNewSplit }: { projectId:const sideBySide = !getState().status?.gpu?.unified;if (sideBySide) await sendFill();let ready = true;+ const dl = startCut("", "Stickers");try {- await ensureMatteModel();+ dl.phase("model");+ await ensureMatteModel(dl.signal);} catch (e) {- toastError(e);+ if (!isStopped(e)) toastError(e);ready = false;+ } finally {+ endCut(dl);}for (const l of objects) {if (liveRef.current.stickers?.find((s) => s.layer === l.id && !s.kind)?.skipped) continue;@@ -854,13 +941,20 @@ export function LayerDoc({ projectId, doc, onChange, onNewSplit }: { projectId:continue;}setSticker(l.id, { local: "making" });+ const ctl = startCut(l.id, l.name);try {- await fastSticker(liveRef.current.layers.find((x) => x.id === l.id) ?? l);+ await fastSticker(liveRef.current.layers.find((x) => x.id === l.id) ?? l, ctl);setSticker(l.id, { local: "done" });} catch (e) {- console.error(e);- setSticker(l.id, { failed: true, local: undefined });- toastError(e);+ // Skip (or Stop all) ended it: the object keeps its rough cut-out, nothing to report.+ if (isStopped(e)) setSticker(l.id, { skipped: true, local: undefined });+ else {+ console.error(e);+ setSticker(l.id, { failed: true, local: undefined });+ toastError(e);+ }+ } finally {+ endCut(ctl);}}if (!sideBySide) await sendFill();@@ -941,6 +1035,23 @@ export function LayerDoc({ projectId, doc, onChange, onNewSplit }: { projectId:// eslint-disable-next-line react-hooks/exhaustive-deps}, [jobs, session, live.stickers]);+ // A scene edit stopped before any result (Stop on its pill or on the Blend card): its entry goes,+ // so nothing waits for it, and what sending it took away comes back (the marks to the pencil).+ useEffect(() => {+ const edits = session.filter((i) => i.kind === "job" && i.jobId && jobs[i.jobId]).map((i) => ({ image: i.request?.images?.[0], status: jobs[i.jobId!].status }));+ const gone = stoppedScenes(liveRef.current, edits);+ if (!gone.length) return;+ const d = liveRef.current;+ const back = gone.map((e) => sentScene.current.get(e.source));+ const unhide = new Set(back.flatMap((b) => b?.hid ?? []));+ const marks = back.find((b) => b?.sketch)?.sketch;+ if (marks && !sketch.marks.length) setSketch(marks);+ for (const e of gone) sentScene.current.delete(e.source);+ commit({ ...d, layers: d.layers.map((l) => (unhide.has(l.id) ? { ...l, hidden: false } : l)), scenes: (d.scenes ?? []).filter((e) => !gone.includes(e)) });+ toastInfo("Stopped: the layers are as they were before that edit.");+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [jobs, session]);+// Blend into scene (or an older Automatic shadows edit) being made (sent, generated, or read back):// the layers stay where they are meanwhile (the result is made for this layout), and the stage says// how far it is. A failed edit does not hold them.@@ -964,6 +1075,8 @@ export function LayerDoc({ projectId, doc, onChange, onNewSplit }: { projectId:const skipSticker = (s: Sticker) => {if (s.job) void cancelJob(s.job);+ // Its quick cut-out stops, in the service too (the model's download is Stop all's to stop).+ if (cutRef.current?.layer === s.layer) cutRef.current.abort();setSticker(s.layer, { skipped: true });};const stickerRows = (live.stickers ?? []).filter((s) => live.layers.some((l) => l.id === s.layer));@@ -1461,6 +1574,9 @@ export function LayerDoc({ projectId, doc, onChange, onNewSplit }: { projectId:* what is sent, so Qwen makes them again); `look`: objects that take the edit's look. *//** `send`: made right away (a lab step, no Prompt+) instead of set up in the prompt; `one`: one* shadow layer for all the objects. */+ /** What sending a scene edit took away (its pencil marks, the old shadows a Blend hid), by the+ * edit's image: given back if the edit is stopped before a result (stoppedScenes). */+ const sentScene = useRef(new Map<string, { sketch?: typeof sketch; hid: string[] }>());const sendScene = async (o: { shadows: string[]; look: string[]; prompt: string; marks: boolean; hint: string; send?: boolean; one?: boolean; blend?: boolean }) => {setBusy(true);// Sent right away: the flattened layers become a version on the way; the prompt's image is put back.@@ -1510,6 +1626,10 @@ export function LayerDoc({ projectId, doc, onChange, onNewSplit }: { projectId:// would read this one's result first (11-01: per-object shadows instead of the one layer asked for).// Blend: the old Automatic shadows layer would double the shadows: hidden (its eye brings it back).const layers = o.blend ? live.layers.map((l) => (l.auto && l.effect && !l.blend ? { ...l, hidden: true } : l)) : live.layers;+ sentScene.current.set(target, {+ ...(marksId ? { sketch: { marks: sketch.marks, wants: sketch.wants } } : {}),+ hid: o.blend ? live.layers.filter((l) => l.auto && l.effect && !l.blend && !l.hidden).map((l) => l.id) : [],+ });commit({ ...live, layers, scenes: [...(live.scenes ?? []).filter((x) => x.source !== target), scene] });if (marksId) setSketch({ marks: [], wants: sketch.wants });setSels([]);@@ -1645,6 +1765,7 @@ export function LayerDoc({ projectId, doc, onChange, onNewSplit }: { projectId:const flatten = async () => {setBusy(true);+ setWorking("Saving the image…");try {// The one image of the lab that goes to the gallery (its steps are kept out of it).const rec = await api.upload(await toPng(await render(W, H)), "Layers flattened.png");@@ -1654,6 +1775,7 @@ export function LayerDoc({ projectId, doc, onChange, onNewSplit }: { projectId:} catch (e) {toastError(e);} finally {+ setWorking(null);setBusy(false);}};@@ -1663,7 +1785,10 @@ export function LayerDoc({ projectId, doc, onChange, onNewSplit }: { projectId:setBusy(true);try {const layers = [];- for (const l of live.layers) {+ for (const [k, l] of live.layers.entries()) {+ setWorking(`Writing the PSD · layer ${k + 1} of ${live.layers.length}`);+ // Lets the status show before the layer is drawn.+ await new Promise((r) => window.setTimeout(r, 0));const c = await render(W, H, undefined, [{ ...l, hidden: false }]);layers.push({ name: l.name, hidden: l.hidden, rgba: c.getContext("2d")!.getImageData(0, 0, W, H).data });}@@ -1675,11 +1800,13 @@ export function LayerDoc({ projectId, doc, onChange, onNewSplit }: { projectId:fx.fillRect(0, 0, W, H);fx.drawImage(await render(W, H), 0, 0);const xmp = aiMarkingXmp(getState().status?.service.version ?? "");+ setWorking("Writing the PSD · choose where to save it");const path = await native.savePsd(writePsd(W, H, layers, fx.getImageData(0, 0, W, H).data, xmp));if (path) toastInfo(`Saved ${path.split(/[\\/]/).pop()}: each layer is its own layer in Photoshop.`);} catch (e) {toastError(e);} finally {+ setWorking(null);setBusy(false);}};@@ -1760,7 +1887,15 @@ export function LayerDoc({ projectId, doc, onChange, onNewSplit }: { projectId:<div className="overlay"><div className="overlay-head"><h2>Layers (lab)</h2>- {labJobs.length && !stickering ? <LabJobs lab={lab} doc={doc} /> : <span className="layers-status">{stickering ? "Making stickers: each object is redrawn on its own; the background comes back when they are in" : status}</span>}+ {working ? (+ <span className="layers-status">+ <Loader2 size={13} className="spin" /> {working}+ </span>+ ) : labJobs.length && !stickering ? (+ <LabJobs lab={lab} doc={doc} />+ ) : (+ <span className="layers-status">{stickering ? "Making stickers: each object is redrawn on its own; the background comes back when they are in" : status}</span>+ )}<span className="spacer" /><button className="btn" onClick={onNewSplit} title="Split this image again (replaces these layers; other images keep theirs)"><Scissors size={14} /> New split@@ -1776,22 +1911,52 @@ export function LayerDoc({ projectId, doc, onChange, onNewSplit }: { projectId:<div className="sticker-strip"><Loader2 size={14} className="spin" /><span>- {matteDl !== null ? (- <>Getting the sticker model (once, 224 MB) · {matteDl}%</>+ {cut?.layer === "" ? (+ <>Getting the sticker model (once, 224 MB){matteDl !== null ? ` · ${matteDl}%` : ""}</>) : (<>Making stickers · {stickerRows.length - stickersLeft} of {stickerRows.length}- {stickerNow ? ` · ${stickerNow.kind ? "filling the background" : (live.layers.find((l) => l.id === stickerNow.layer)?.name ?? "")}` : ""}+ {cut && cut.layer === stickerNow?.layer ? (+ ` · ${cutLine}`+ ) : stickerNow ? (+ <>+ {` · ${stickerNow.kind ? "filling the background" : (live.layers.find((l) => l.id === stickerNow.layer)?.name ?? "")}`}+ {stickerNow.job && jobs[stickerNow.job] && (+ <>+ {" · "}+ <JobProgressText job={jobs[stickerNow.job]} item={session.find((i) => i.jobId === stickerNow.job)} />+ </>+ )}+ </>+ ) : (+ ""+ )}</>)}</span>- {stickerNow && (- <button className="btn" onClick={() => skipSticker(stickerNow)} title="Keep this object's rough cut-out">+ {stickerNow && cut?.layer !== "" && (+ <button className="btn" onClick={() => skipSticker(stickerNow)} title={stickerNow.kind ? "Stop the fill: the background keeps its holes" : "Stop this one: the object keeps its rough cut-out"}>Skip</button>)}- <button className="btn" onClick={() => stickerRows.forEach((s, i) => (stickerStates[i] === "waiting" || stickerStates[i] === "making") && skipSticker(s))} title="Keep the rough cut-outs of the objects not done yet">- Skip all+ <button+ className="btn"+ onClick={() => {+ if (cutRef.current?.layer === "") stopCut();+ stickerRows.forEach((s, i) => (stickerStates[i] === "waiting" || stickerStates[i] === "making") && skipSticker(s));+ }}+ title="Stop everything still to do: the objects keep their rough cut-outs, the background is not filled"+ >+ <Square size={12} /> Stop all+ </button>+ </div>+ )}+ {cut && !stickering && (+ <div className="sticker-strip">+ <Loader2 size={14} className="spin" />+ <span>Quick cut-out · {cutLine}</span>+ <button className="btn" onClick={stopCut} title="Stop the cut-out: the layer stays as it was">+ <Square size={12} /> Stop</button></div>)}@@ -1803,6 +1968,11 @@ export function LayerDoc({ projectId, doc, onChange, onNewSplit }: { projectId:{shadowJob ? <ShadowPhase job={shadowJob.job} item={shadowJob.item} /> : blendSending ? "Sending the scene" : "Reading what the AI added"}<small>The layers stay where they are until it is in</small></span>+ {shadowJob && !["done", "failed", "cancelled"].includes(shadowJob.job.status) && (+ <button className="btn" onClick={() => cancelJob(shadowJob.job.id)} title="Stop the blend: the layers stay as they are">+ <Square size={12} /> Stop+ </button>+ )}</div></div>)}diff --git a/src/components/LayerSplit.tsx b/src/components/LayerSplit.tsxindex b44cffd..0482d10 100644--- a/src/components/LayerSplit.tsx+++ b/src/components/LayerSplit.tsx@@ -5,12 +5,12 @@// (LayerDoc.tsx). Filling the holes or completing a cut object is done by hand with the usual// edits, to see what works before building the real feature.-import { Brush, ChevronDown, ChevronUp, Eraser, Eye, EyeOff, Hand, Layers, MousePointerClick, Plus, Redo2, Trash2, Undo2, X } from "lucide-react";+import { Brush, ChevronDown, ChevronUp, Eraser, Eye, EyeOff, Hand, Layers, Loader2, MousePointerClick, Plus, Redo2, Trash2, Undo2, X } from "lucide-react";import { useCallback, useEffect, useMemo, useRef, useState } from "react";import { api, urls } from "../lib/api";import { addTo, area, dilate, fileSafe, fromLogits, maskOrder, refineEdges, removeFrom, samSelection, union, type Mask } from "../lib/layers";import { shortcut } from "../lib/platform";-import { Segmenter, type SamResult } from "../lib/sam";+import { cancelSamDownload, Segmenter, type SamResult } from "../lib/sam";import type { DocLayer, LayerDoc } from "../lib/layerDoc";import { addVersions, setState, toastError, toastInfo, useStore } from "../lib/store";import type { InputRecord } from "../lib/types";@@ -130,6 +130,8 @@ export function LayerSplit({ onSplit, onBack }: { onSplit: (doc: LayerDoc) => voconst [sam, setSam] = useState<SamState>("loading");// The selection model being downloaded (the first time), in %.const [samPct, setSamPct] = useState<number | null>(null);+ /** The selection model's download was cancelled here (the brush still works). */+ const [samStopped, setSamStopped] = useState(false);const [busy, setBusy] = useState<string | null>(null);const [tick, setTick] = useState(0);const [areas, setAreas] = useState<Record<string, number>>({});@@ -444,7 +446,7 @@ export function LayerSplit({ onSplit, onBack }: { onSplit: (doc: LayerDoc) => vosetStickers(mode);const used = layers.filter((l) => area(maskOf(l.id)) > 0);if (!used.length) return;- setBusy("Splitting…");+ setBusy(`Splitting · the background (1 of ${used.length + 1})`);try {const img = await full.current!;const W = img.naturalWidth;@@ -483,7 +485,8 @@ export function LayerSplit({ onSplit, onBack }: { onSplit: (doc: LayerDoc) => voconst base = made[0];const docLayers: DocLayer[] = [];- for (const l of used) {+ for (const [k, l] of used.entries()) {+ setBusy(`Splitting · ${l.name} (${k + 2} of ${used.length + 1})`);cut(refined.get(l.id)!, "destination-in");const name = fileSafe(l.name);await save(out, `${name}.png`);@@ -559,7 +562,9 @@ export function LayerSplit({ onSplit, onBack }: { onSplit: (doc: LayerDoc) => voloading: samPct != null ? `Downloading the selection model (44 MB, once)… ${samPct}%` : "Loading the selection model…",encoding: "Reading the image…",ready: tool === "select" ? `Click an object to add it to “${activeName}” · again on the same spot: bigger part · right-click: take it out` : `Painting “${activeName}”`,- missing: "The selection model could not be downloaded: paint the layers with the brush (open the lab again to retry)",+ missing: samStopped+ ? "Download stopped: paint the layers with the brush (open the lab again to download the selection model)"+ : "The selection model could not be downloaded: paint the layers with the brush (open the lab again to retry)",error: "The selection model failed to start (see the console): paint the layers with the brush",}[sam];const brushCursor = tool === "brush" || tool === "eraser";@@ -568,7 +573,21 @@ export function LayerSplit({ onSplit, onBack }: { onSplit: (doc: LayerDoc) => vo<div className="overlay"><div className="overlay-head"><h2>Split into layers (lab)</h2>- <span className="layers-status">{status}</span>+ <span className="layers-status">+ {(busy || sam === "loading" || sam === "encoding") && <Loader2 size={13} className="spin" />} {status}+ </span>+ {samPct != null && (+ <button+ className="btn"+ onClick={() => {+ setSamStopped(true);+ cancelSamDownload().catch(toastError);+ }}+ title="Stop the download: the layers can still be painted with the brush"+ >+ Cancel download+ </button>+ )}<span className="spacer" />{onBack && (<button className="btn" onClick={onBack}>diff --git a/src/lib/api.ts b/src/lib/api.tsindex f1a9d9c..0d3597e 100644--- a/src/lib/api.ts+++ b/src/lib/api.ts@@ -17,6 +17,18 @@ export class ApiError extends Error {}}+/** Work the user stopped (Stop, Skip, Cancel): not an error to show. */+export class Stopped extends Error {+ constructor() {+ super("Stopped.");+ this.name = "Stopped";+ }+}++/** True for a Stop: ours, the browser's AbortError, or the service's "cancelled" answer. */+export const isStopped = (e: unknown) =>+ e instanceof Stopped || (e instanceof DOMException && e.name === "AbortError") || (e instanceof ApiError && e.body.code === "cancelled");+let base = "";let token = "";/** Private mode: uploads and imports go to the service's temporary store. */@@ -54,6 +66,7 @@ async function call<T>(path: string, init: RequestInit = {}): Promise<T> {headers: { ...authHeaders(init.method), ...(init.body && typeof init.body === "string" ? { "Content-Type": "application/json" } : {}), ...(init.headers || {}) },});} catch (e) {+ if (init.signal?.aborted) throw new Stopped();throw new ApiError({ code: "server_unavailable", message: inBrowser ? "Kokon is not reachable." : "The local service is not reachable.", detail: String(e) }, 0);}const text = await res.text();@@ -133,12 +146,14 @@ export const api = {matteStatus: () => call<{ installed: boolean; bytes: number }>("/matte"),/** Progress in `installStatus` (preset "matting"). */downloadMatte: () => call<InstallStatus>("/matte/download", { method: "POST" }),- /** The fast-sticker matte of an image in Kokon ("input:"/"gen:"): a grey PNG at its size. */- matte: async (image: string): Promise<Blob> => {+ /** The fast-sticker matte of an image in Kokon ("input:"/"gen:"): a grey PNG at its size. `run`:+ * the id `cancelMatte` stops; aborting `signal` drops the request (the service stops the model too). */+ matte: async (image: string, run?: string, signal?: AbortSignal): Promise<Blob> => {let res: Response;try {- res = await fetch(base + "/matte", { method: "POST", headers: { ...authHeaders("POST"), "Content-Type": "application/json" }, body: json({ image }) });+ res = await fetch(base + "/matte", { method: "POST", headers: { ...authHeaders("POST"), "Content-Type": "application/json" }, body: json({ image, run }), signal });} catch (e) {+ if (signal?.aborted) throw new Stopped();throw new ApiError({ code: "server_unavailable", message: inBrowser ? "Kokon is not reachable." : "The local service is not reachable.", detail: String(e) }, 0);}if (!res.ok) {@@ -147,6 +162,8 @@ export const api = {}return res.blob();},+ /** Stops the quick cut-out `run` in the service (running, or as soon as it starts). */+ cancelMatte: (run: string) => call<{ stopped: boolean }>("/matte/cancel", { method: "POST", body: json({ run }) }),/** ESRGAN models of earlier versions in the app's own folder. */legacyUpscalers: (keep: string) => call<{ files: string[]; bytes: number }>(`/setup/legacy-upscalers?keep=${encodeURIComponent(keep)}`),/** `keep`: the model chosen in Settings, even if not saved yet. */@@ -172,8 +189,8 @@ export const api = {job: (id: string) => call<JobView>(`/jobs/${id}`),jobs: () => call<JobView[]>("/jobs"),cancel: (id: string) => call<JobView>(`/jobs/${id}/cancel`, { method: "POST" }),- upload: (bytes: Blob | ArrayBuffer | Uint8Array, name?: string) =>- call<InputRecord>(`/inputs${privateQuery()}`, { method: "POST", body: bytes as BodyInit, headers: { "Content-Type": "application/octet-stream", ...(name ? { "x-filename": encodeURIComponent(name) } : {}) } }),+ upload: (bytes: Blob | ArrayBuffer | Uint8Array, name?: string, signal?: AbortSignal) =>+ call<InputRecord>(`/inputs${privateQuery()}`, { method: "POST", body: bytes as BodyInit, signal, headers: { "Content-Type": "application/octet-stream", ...(name ? { "x-filename": encodeURIComponent(name) } : {}) } }),/** What an image's AI markings say (metadata and Kokon's invisible watermark); nothing is kept. */checkImage: (bytes: Blob | ArrayBuffer | Uint8Array) =>call<AiCheckReport>("/provenance/check", { method: "POST", body: bytes as BodyInit, headers: { "Content-Type": "application/octet-stream" } }),diff --git a/src/lib/layerDoc.test.ts b/src/lib/layerDoc.test.tsindex 715e1e2..b243173 100644--- a/src/lib/layerDoc.test.ts+++ b/src/lib/layerDoc.test.ts@@ -1,5 +1,5 @@import { describe, expect, it } from "vitest";-import { copiedShare, cropFor, expandedRect, extOf, unionRect, docFor, keepLabsIn, labSources, loadLab, saveLab, waitingMarks, jobLayer, labItems, leftovers, putDoc, type LabStore, shadowAlpha, strengthPixels, mapPoint, placed, reconcile, reorder, toLayer, xfOf, type DocLayer, type LayerDoc } from "./layerDoc";+import { copiedShare, stoppedScenes, cropFor, expandedRect, extOf, unionRect, docFor, keepLabsIn, labSources, loadLab, saveLab, waitingMarks, jobLayer, labItems, leftovers, putDoc, type LabStore, shadowAlpha, strengthPixels, mapPoint, placed, reconcile, reorder, toLayer, xfOf, type DocLayer, type LayerDoc } from "./layerDoc";const layer = (id: string, source: string, base = false): DocLayer => ({ id, name: id, source, history: [source], hidden: false, base, dx: 0, dy: 0, s: 1 });const doc = (layers: DocLayer[]): LayerDoc => ({ width: 100, height: 100, layers, known: [] });@@ -258,3 +258,23 @@ describe("expanded objects", () => {expect(unionRect({ x: 0, y: 0, w: 800, h: 600 }, { x: 700, y: -50, w: 300, h: 100 })).toEqual({ x: 0, y: -50, w: 1000, h: 650 });});});++describe("stoppedScenes", () => {+ const scene = (source: string, made?: Record<string, string>) => ({ source, before: "b", shadows: [], look: [], places: {}, reach: 10, ...(made ? { made } : {}) });+ const doc = (scenes: ReturnType<typeof scene>[]): LayerDoc => ({ width: 10, height: 10, layers: [], known: [], scenes });+ it("lets go of an edit whose jobs were all stopped, and only that one", () => {+ const d = doc([scene("input:a"), scene("input:b"), scene("input:c"), scene("input:d", { red: "l1" })]);+ const edits = [+ { image: "input:a", status: "cancelled" },+ { image: "input:b", status: "cancelled" },+ { image: "input:b", status: "running" },+ { image: "input:c", status: "failed" },+ { image: "input:d", status: "cancelled" },+ { image: undefined, status: "cancelled" },+ ];+ expect(stoppedScenes(d, edits).map((e) => e.source)).toEqual(["input:a"]);+ });+ it("keeps edits not sent yet (in the prompt box)", () => {+ expect(stoppedScenes(doc([scene("input:a")]), [])).toEqual([]);+ });+});diff --git a/src/lib/layerDoc.ts b/src/lib/layerDoc.tsindex 288a2b0..1acc727 100644--- a/src/lib/layerDoc.ts+++ b/src/lib/layerDoc.ts@@ -542,3 +542,15 @@ export function copiedShare(rgba: ArrayLike<number>, mask: ArrayLike<number>, n:}return inside ? bad / inside : 0;}++/** The scene edits (Edit together, new objects, Blend) whose every job was stopped before a result+ * came: nothing will ever be made from them, so the lab lets them go (their marks come back to the+ * pencil). `edits`: the lab's jobs, by the image each was sent with. An edit with a job still+ * waiting, running, failed or done is kept. */+export function stoppedScenes(doc: LayerDoc, edits: { image: string | undefined; status: string }[]): SceneEdit[] {+ return (doc.scenes ?? []).filter((e) => {+ if (e.made) return false;+ const mine = edits.filter((j) => j.image === e.source);+ return mine.length > 0 && mine.every((j) => j.status === "cancelled");+ });+}diff --git a/src/lib/logic.test.ts b/src/lib/logic.test.tsindex 0dec330..94af112 100644--- a/src/lib/logic.test.ts+++ b/src/lib/logic.test.ts@@ -1,5 +1,8 @@import { describe, expect, it } from "vitest";import {+ cutoutText,+ downloadIsFor,+ jobStepText,macEngineOfferDue,modelChoiceUi,modelOfferDue,@@ -776,3 +779,26 @@ describe("expand: placing the image", () => {expect(placeInCanvas({ left: 0, right: 0, top: 30, bottom: 30 }, 20, 0).left).toBe(0);});});++describe("Layers lab status lines", () => {+ it("names the object and the cut-out's step", () => {+ expect(cutoutText("Vase", "model", 0, 42)).toBe("Vase · getting the sticker model (once, 224 MB) · 42%");+ expect(cutoutText("Vase", "model", 0, null)).toBe("Vase · getting the sticker model (once, 224 MB)");+ expect(cutoutText("Vase", "sending", 3, null)).toBe("Vase · sending to the model");+ expect(cutoutText("Vase", "matting", 0.4, null)).toBe("Vase · model at work");+ expect(cutoutText("Vase", "matting", 6.7, null)).toBe("Vase · model at work · 6 s");+ expect(cutoutText("Vase", "edges", 9, null)).toBe("Vase · refining the edge");+ });+ it("shows a job's step only while it runs and the engine has said how many", () => {+ expect(jobStepText({ status: "running", step: [3, 8] })).toBe("step 3 of 8");+ expect(jobStepText({ status: "running", step: [9, 8] })).toBe("step 8 of 8");+ expect(jobStepText({ status: "running", step: [0, 0] })).toBe("");+ expect(jobStepText({ status: "queued", step: null })).toBe("");+ });+ it("cancels a download only when it is the lab's own", () => {+ expect(downloadIsFor({ running: true, preset: "matting" }, "matting")).toBe(true);+ expect(downloadIsFor({ running: true, preset: "segment" }, "matting")).toBe(false);+ expect(downloadIsFor({ running: false, preset: "matting" }, "matting")).toBe(false);+ expect(downloadIsFor(null, "segment")).toBe(false);+ });+});diff --git a/src/lib/logic.ts b/src/lib/logic.tsindex 331efdd..1764404 100644--- a/src/lib/logic.ts+++ b/src/lib/logic.ts@@ -1,6 +1,6 @@// Pure UI logic (unit-tested in logic.test.ts).-import type { Advanced, GenerationRecord, GenerationRequest, InpaintAction, InputRecord, InstallItem, JobView, LoraItem, LutInfo, MacBenchState, Mode, ModelsStatus, StatusResponse, OutpaintSpec, Plan, Quality, ResolutionMode, Size } from "./types";+import type { Advanced, GenerationRecord, GenerationRequest, InpaintAction, InputRecord, InstallItem, InstallStatus, JobView, LoraItem, LutInfo, MacBenchState, Mode, ModelsStatus, StatusResponse, OutpaintSpec, Plan, Quality, ResolutionMode, Size } from "./types";export interface Ref {key: string;@@ -1032,3 +1032,38 @@ export function starPromptDue(made: number, busy: boolean): boolean {export function pageOutdated(pageVersion: string, serviceVersion: string | undefined, reloadedFor: string | null): boolean {return !!pageVersion && !!serviceVersion && pageVersion !== serviceVersion && reloadedFor !== serviceVersion;}++// ---- Layers lab: what is being done, for the status lines and their Stop buttons ----++/** A quick cut-out's step, for "Vase · model at work · 4 s". */+export type CutStep = "model" | "preparing" | "sending" | "matting" | "edges" | "saving";++/** The status line of a quick cut-out of `name`: its step, the download's % (`pct`) while the model+ * is fetched, and the seconds the model has worked so far (a run is ~4-8 s, 11-04). */+export function cutoutText(name: string, step: CutStep, seconds: number, pct: number | null): string {+ const what =+ step === "model"+ ? `getting the sticker model (once, 224 MB)${pct != null ? ` · ${pct}%` : ""}`+ : step === "preparing"+ ? "preparing"+ : step === "sending"+ ? "sending to the model"+ : step === "matting"+ ? `model at work${seconds >= 1 ? ` · ${Math.floor(seconds)} s` : ""}`+ : step === "edges"+ ? "refining the edge"+ : "saving";+ return `${name} · ${what}`;+}++/** "step 3 of 8" once the engine reports steps, else "". */+export function jobStepText(j: Pick<JobView, "status" | "step">): string {+ if (j.status !== "running" || !j.step || !j.step[1]) return "";+ return `step ${Math.min(j.step[0], j.step[1])} of ${j.step[1]}`;+}++/** The download running in the service is the one for `preset` (Cancel stops only that one: the+ * installer is shared with Settings and the first setup). */+export function downloadIsFor(st: Pick<InstallStatus, "running" | "preset"> | null | undefined, preset: string): boolean {+ return !!st?.running && st.preset === preset;+}diff --git a/src/lib/matte.ts b/src/lib/matte.tsindex 2243044..e7dc85c 100644--- a/src/lib/matte.ts+++ b/src/lib/matte.ts@@ -9,19 +9,58 @@// piece of the selection the selection's own edge band is used instead (`stickerAlpha`). The edge// colours are then freed of the background bleeding into them (`foreground`, Germer et al. 2020).-import { api } from "./api";+import { api, Stopped } from "./api";import { dilate, erode, type Mask } from "./layers";+import type { CutStep } from "./logic";++/** Where a quick cut-out is, for the lab to show (cutoutText in logic.ts). */+export type CutPhase = CutStep;++/** A quick cut-out's Stop and progress: `signal` aborts it, `phase` is told each step. */+export interface CutControl {+ signal: AbortSignal;+ /** The id the service knows the model's run by (Stop ends it there too). */+ run: string;+ phase: (p: CutPhase) => void;+}++/** Throws Stopped once the user stopped the cut-out. */+export function checkStop(c?: CutControl) {+ if (c?.signal.aborted) throw new Stopped();+}++/** A new cut-out's control (`abort` stops it, here and in the service). */+export function cutControl(phase: (p: CutPhase) => void): CutControl & { abort: () => void } {+ const ac = new AbortController();+ const run = `cut-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;+ return {+ signal: ac.signal,+ run,+ phase,+ abort: () => {+ if (ac.signal.aborted) return;+ ac.abort();+ // The dropped request stops the model as well; this also covers a Stop before it was sent.+ api.cancelMatte(run).catch(() => {});+ },+ };+}/** The model's matte (0-1) of RGBA pixels `w`×`h`, at that size (uploaded, matted by the service). */-export async function modelMatte(rgba: Uint8ClampedArray, w: number, h: number): Promise<Float32Array> {+export async function modelMatte(rgba: Uint8ClampedArray, w: number, h: number, ctl?: CutControl): Promise<Float32Array> {const c = document.createElement("canvas");c.width = w;c.height = h;const ctx = c.getContext("2d")!;ctx.putImageData(new ImageData(rgba as Uint8ClampedArray<ArrayBuffer>, w, h), 0, 0);const png = await new Promise<Blob>((res, rej) => c.toBlob((b) => (b ? res(b) : rej(new Error("export failed"))), "image/png"));- const rec = await api.upload(png, "sticker input.png");- const m = await createImageBitmap(await api.matte(`input:${rec.id}`));+ checkStop(ctl);+ ctl?.phase("sending");+ const rec = await api.upload(png, "sticker input.png", ctl?.signal);+ checkStop(ctl);+ ctl?.phase("matting");+ const m = await createImageBitmap(await api.matte(`input:${rec.id}`, ctl?.run, ctl?.signal));+ checkStop(ctl);ctx.clearRect(0, 0, w, h);ctx.drawImage(m, 0, 0, w, h);const px = ctx.getImageData(0, 0, w, h).data;diff --git a/src/lib/sam.ts b/src/lib/sam.tsindex 301eea1..5b3fa0f 100644--- a/src/lib/sam.ts+++ b/src/lib/sam.ts@@ -9,6 +9,7 @@import type * as Ort from "onnxruntime-web";import { api, urls } from "./api";+import { downloadIsFor } from "./logic";const DEV_DIR = "/lab-models/mobilesam/";const ENCODER = "mobile_sam_image_encoder.onnx";@@ -43,6 +44,12 @@ async function download() {}}+/** Cancel for the selection model's download (only when the running install is that one). The+ * waiting `load` then returns null, as for a failed download. */+export async function cancelSamDownload() {+ if (downloadIsFor(await api.installStatus().catch(() => null), "segment")) await api.cancelInstall();+}+/** Where the model files are: kokon-service's copy (downloaded now if it isn't there, `onProgress`* 0-100), else the dev server's. Null when neither has them. */async function modelUrls(onProgress?: (pct: number) => void): Promise<((file: string) => string) | null> {