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: Blend into scene replaces Automatic shadows
Gabriele Lozupone5ede6673ef28
diff --git a/crates/qls-core/src/engine.rs b/crates/qls-core/src/engine.rsindex cc856bc..64f1469 100644--- a/crates/qls-core/src/engine.rs+++ b/crates/qls-core/src/engine.rs@@ -84,6 +84,10 @@ pub struct JobView {/// The prompt enhancer's text: partial while `EnhancingPrompt`, then the prompt the image/// is made from (`prompt` stays the user's). None when the enhancer did not run or failed.pub enhanced_prompt: Option<String>,+ /// A scene reading's answer (`GenerationRequest::read_scene`): None while it runs, when it+ /// failed (noted) or for any other job.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub scene: Option<crate::scene::SceneReading>,pub client: Option<String>,pub plan: Option<Plan>,pub seed: Option<i64>,@@ -692,7 +696,7 @@ impl Engine {let upscale = request.mode == Mode::Upscale;// Removing a painted area needs no description (the planner writes the prompt).let removal = request.mask.is_some() && request.inpaint_action == planner::InpaintAction::Remove;- if request.prompt.trim().is_empty() && !upscale && !removal {+ if request.prompt.trim().is_empty() && !upscale && !removal && request.read_scene.is_none() {return Err(AppError::invalid("Describe what to generate or change."));}if upscale && request.images.is_empty() {@@ -724,8 +728,13 @@ impl Engine {created_at: now_rfc3339(),started_at: None,finished_at: None,- prompt: if upscale && request.prompt.trim().is_empty() { "Upscale".into() } else { request.prompt.clone() },+ prompt: match &request.read_scene {+ Some(name) => format!("Reading the scene around the {}", name.trim().to_lowercase()),+ None if upscale && request.prompt.trim().is_empty() => "Upscale".into(),+ None => request.prompt.clone(),+ },enhanced_prompt: None,+ scene: None,client: request.client.clone(),plan: None,seed: request.seed,@@ -1237,6 +1246,18 @@ impl Engine {.suggest("Turn it off in Settings → Performance to use the standard engine for this."));}+ // 4a. Blend into scene: only the reading of the place the object stands in.+ if let Some(name) = &request.read_scene {+ let reading = self.read_scene(id, &client, &caps, name, &sd_req.ref_images, seed).await?;+ self.update(id, |j| {+ j.view.scene = reading;+ j.view.status = JobStatus::Done;+ j.view.finished_at = Some(now_rfc3339());+ j.view.stage = None;+ });+ return Ok(());+ }+// 4b. Prompt enhancer: rewrites the user's prompt, looking at the references// exactly as the image model gets them.if request.enhance && enhancer::applies_to(plan.mode, plan.marks) {@@ -1449,6 +1470,42 @@ impl Engine {loras}+ /// Reads the place the object `name` stands in (`scene`), looking at the image as the edit+ /// model gets it. None when the engine cannot write text or the answer is not usable (noted+ /// on the job: the lab then offers the safe defaults to check). Errors only for a cancel.+ async fn read_scene(&self, id: &str, client: &SdcppClient, caps: &Capabilities, name: &str, images: &[String], seed: i64) -> AppResult<Option<crate::scene::SceneReading>> {+ if !caps.text_generation {+ self.update(id, |j| j.view.notes.push("This inference engine cannot read the scene (update it in Setup).".into()));+ return Ok(None);+ }+ let Some(image) = images.first() else { return Ok(None) };+ self.update(id, |j| {+ j.view.status = JobStatus::EnhancingPrompt;+ j.view.stage = None;+ });+ let started = Instant::now();+ let r = client.text_gen(&crate::scene::request(image.clone(), name, seed), Duration::from_secs(120), |_| {}, || self.is_cancelled(id)).await;+ let note = match r {+ Ok(done) => match crate::scene::parse(&done.text) {+ Some(reading) => {+ tracing::info!("scene reading for {name:?} in {:.1} s: {reading:?}", started.elapsed().as_secs_f32());+ return Ok(Some(reading));+ }+ None => {+ tracing::warn!("scene reading: no JSON in {:?}", done.text);+ "The scene could not be read (the answer was not usable).".to_string()+ }+ },+ Err(e) if e.code == ErrorCode::Cancelled => return Err(e),+ Err(e) => {+ tracing::warn!("scene reading failed: {} {:?}", e.message, e.detail);+ format!("The scene could not be read: {}", e.message)+ }+ };+ self.update(id, |j| j.view.notes.push(note));+ Ok(None)+ }+/// Runs the prompt enhancer for job `id` and streams its text into the job. Returns the/// new prompt, or None when the job keeps the user's prompt: the engine cannot write text,/// or the enhancer failed (both noted on the job). Errors only for a cancel or a crash.@@ -2267,6 +2324,46 @@ mod tests {assert_eq!(seen[2]["prompt"], "References:\n<image1>: person, female, long brown hair\n<image2>: cat, orange tabby\n\nRequest: lei sul divano con il gatto");}+ #[tokio::test]+ async fn scene_reading_parses_the_answer_or_notes_why_not() {+ let dir = tempfile::tempdir().unwrap();+ // SAFETY: test-only env override, single-threaded setup.+ unsafe { std::env::set_var("QLS_CONFIG_DIR", dir.path().join("cfg")) };+ let mut cfg = AppConfig { sdcpp_dir: dir.path().join("sdcpp"), ..AppConfig::default() };+ cfg.normalize();+ std::fs::create_dir_all(cfg.engine_dir()).unwrap();+ std::fs::write(cfg.server_exe(), b"").unwrap();+ for (_, p, _) in cfg.profile().files() {+ std::fs::create_dir_all(p.parent().unwrap()).unwrap();+ std::fs::write(p, b"").unwrap();+ }+ let e = Engine::new(cfg, dir.path()).unwrap();+ let caps = Capabilities { text_generation: true, ..Default::default() };+ let submit = || e.submit(GenerationRequest { read_scene: Some("Woman".into()), ..Default::default() }, None).unwrap().id;+ let images = vec!["PNG1".to_string()];+ let id = submit();+ assert_eq!(e.job(&id).unwrap().prompt, "Reading the scene around the woman");+ let (port, seen) = fake_text_server(vec![+ r#"{"surface": "wet ground", "light": "overcast daylight", "hard_shadows": false, "light_from": "above", "shadows_fall": "under the objects", "colour": "cool", "object_in": "shade"}"#,+ "It is a street.",+ ])+ .await;+ let r = e.read_scene(&id, &SdcppClient::new(port), &caps, "Woman", &images, 5).await.unwrap().unwrap();+ assert_eq!((r.surface.as_str(), r.light.as_str(), r.complete), ("wet", "overcast", true));+ {+ let seen = seen.lock().unwrap();+ assert_eq!((seen[0]["images"][0].as_str(), seen[0]["system_prompt"].as_str()), (Some("PNG1"), Some(crate::scene::SYSTEM_PROMPT)));+ }+ // An answer without JSON: none, with a note.+ let id = submit();+ assert_eq!(e.read_scene(&id, &SdcppClient::new(port), &caps, "Woman", &images, 5).await.unwrap(), None);+ assert!(e.job(&id).unwrap().notes.last().unwrap().contains("could not be read"));+ // An engine without text generation: none, with a note, no request.+ let id = submit();+ assert_eq!(e.read_scene(&id, &SdcppClient::new(1), &Capabilities::default(), "Woman", &images, 5).await.unwrap(), None);+ assert!(e.job(&id).unwrap().notes.last().unwrap().contains("cannot read the scene"));+ }+#[test]fn reviewed_prompts_keep_the_users_words() {let dir = tempfile::tempdir().unwrap();diff --git a/crates/qls-core/src/lib.rs b/crates/qls-core/src/lib.rsindex 6f4a918..38bd16b 100644--- a/crates/qls-core/src/lib.rs+++ b/crates/qls-core/src/lib.rs@@ -22,6 +22,7 @@ pub mod planner;pub mod process;pub mod projects;pub mod remote;+pub mod scene;pub mod sdcpp;pub mod speed;pub mod store;diff --git a/crates/qls-core/src/planner.rs b/crates/qls-core/src/planner.rsindex 9e3ccfc..4c1ee81 100644--- a/crates/qls-core/src/planner.rs+++ b/crates/qls-core/src/planner.rs@@ -285,6 +285,10 @@ pub struct GenerationRequest {/// `JobView::enhanced_prompt` and no image, so the user can read and change it first.#[serde(default, skip_serializing_if = "std::ops::Not::not")]pub enhance_only: bool,+ /// Layers lab "Blend into scene": only read the place the object with this name stands in+ /// (`scene`, the Prompt+ model). The job ends with the reading in `JobView::scene` and no image.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub read_scene: Option<String>,/// The user's own words when `prompt` was written by Prompt+ in a review (and maybe changed/// by the user since): kept as the record's original prompt.#[serde(default, skip_serializing_if = "Option::is_none")]@@ -921,8 +925,11 @@ pub fn plan(req: &GenerationRequest, inputs: &PlanInputs, rec: &RecommendedSetti}// Marks: the prompt names things by colour, never an action of its own (a Remove would blur the marks away).let inpaint_action = (mode == ResolvedMode::Inpaint).then(|| if marks { InpaintAction::Edit } else { req.inpaint_action.resolve(&req.prompt) });- // Upscales and removals need no description.- let prompt_optional = mode == ResolvedMode::Upscale || inpaint_action == Some(InpaintAction::Remove);+ if req.read_scene.is_some() && (mode != ResolvedMode::Edit || inputs.image_sizes.len() != 1) {+ return Err(AppError::invalid("The scene is read from one image, as an edit."));+ }+ // Upscales and removals need no description, nor a scene reading (the object's name is its own field).+ let prompt_optional = mode == ResolvedMode::Upscale || inpaint_action == Some(InpaintAction::Remove) || req.read_scene.is_some();if req.prompt.trim().is_empty() && !prompt_optional {return Err(AppError::invalid("Describe what to generate or change."));}@@ -1823,7 +1830,16 @@ mod tests {assert!(plan(&r, &inputs(&[(800, 800)]), &rec()).is_err(), "expansions wrap the prompt themselves");// The fields stay out of saved requests unless used.let v = serde_json::to_value(req("x")).unwrap();- assert!(v.get("enhance_only").is_none() && v.get("enhanced_from").is_none());+ assert!(v.get("enhance_only").is_none() && v.get("enhanced_from").is_none() && v.get("read_scene").is_none());+ }++ #[test]+ fn scene_reading_is_an_edit_of_one_image() {+ let mut r = req("");+ r.read_scene = Some("woman".into());+ assert_eq!(plan(&r, &inputs(&[(1324, 1176)]), &rec()).unwrap().mode, ResolvedMode::Edit, "no prompt needed");+ assert!(plan(&r, &inputs(&[]), &rec()).is_err(), "no image");+ assert!(plan(&r, &inputs(&[(800, 800), (800, 800)]), &rec()).is_err(), "two images");}#[test]diff --git a/crates/qls-core/src/scene.rs b/crates/qls-core/src/scene.rsnew file mode 100644index 0000000..374b3eb--- /dev/null+++ b/crates/qls-core/src/scene.rs@@ -0,0 +1,249 @@+//! Scene reading for the layers lab's "Blend into scene": the Prompt+ model (the Qwen3-VL text+//! encoder, `POST /sdcpp/v1/text_gen`) answers fixed questions about the place a pasted object+//! stands in (surface under it, light, shadows). The lab builds the edit's prompt from the answers,+//! so effects the surface does not have are never named: a prompt that names reflections or water+//! makes Qwen-Image add water on dry ground (bench 2026-11-02, `bench/20261102-200503-scene-integration`:+//! right on 4 of 4 scenes with both seeds, ~2 s on a 5070 Ti).++use serde::{Deserialize, Serialize};++use crate::sdcpp::{TextGenRequest, TextSampling};++/// The questions. The answers are fixed phrases the parser maps to ids.+pub const SYSTEM_PROMPT: &str = r#"You look at a photo where an object was pasted in, and describe the place it stands in, so it can be blended in.+Answer with JSON only, no other text, with these keys:+"surface": what is directly under and around the object's base, one of "dry hard ground", "wet ground", "puddle or standing water", "glossy or polished surface", "grass", "sand or soil", "snow", "carpet or fabric", "other".+"light": the scene's main light, one of "direct sunlight", "overcast daylight", "window light", "indoor lamps", "night".+"hard_shadows": true if the scene shows hard-edged shadows, else false.+"light_from": where the main light comes from, one of "left", "right", "front", "behind", "above".+"shadows_fall": the direction the scene's shadows fall on the ground, one of "left", "right", "towards the viewer", "away from the viewer", "under the objects".+"colour": the light's colour, one of "warm", "neutral", "cool".+"object_in": whether the object stands in "sun", "shade" or "both"."#;++/// Low temperature: the same scene reads the same way (both bench seeds gave identical answers).+const SAMPLING: TextSampling = TextSampling {+ temperature: 0.2,+ top_p: 0.8,+ top_k: 20,+ presence_penalty: 0.0,+ seed: -1,+};+/// The answer is ~60 tokens.+const MAX_TOKENS: u32 = 200;++/// What the scene does to the object, as ids (the lab shows them as words the user can change).+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+pub struct SceneReading {+ /// dry, wet, water, glossy, grass, soil, snow, fabric, other+ pub surface: String,+ /// sun, overcast, window, lamps, night+ pub light: String,+ pub hard_shadows: bool,+ /// left, right, front, behind, above+ pub light_from: String,+ /// left, right, front (towards the viewer), back (away), under+ pub shadows_fall: String,+ /// warm, neutral, cool+ pub colour: String,+ /// sun, shade, both+ pub object_in: String,+ /// Every answer was understood; false = some are the defaults (the lab says so).+ pub complete: bool,+}++impl Default for SceneReading {+ /// What is safe when nothing is known: dry ground, soft shadow under the object (no water, no+ /// reflection named).+ fn default() -> Self {+ Self {+ surface: "dry".into(),+ light: "overcast".into(),+ hard_shadows: false,+ light_from: "above".into(),+ shadows_fall: "under".into(),+ colour: "neutral".into(),+ object_in: "both".into(),+ complete: false,+ }+ }+}++/// The request for one object (`name`, as the lab names its layer) in `image` (base64, the image+/// as the edit model gets it).+pub fn request(image: String, name: &str, seed: i64) -> TextGenRequest {+ let name = name.trim().to_lowercase();+ TextGenRequest {+ prompt: format!("The pasted object is the {name}. Describe the place it stands in."),+ system_prompt: SYSTEM_PROMPT.into(),+ images: vec![image],+ max_tokens: MAX_TOKENS,+ sampling: TextSampling { seed, ..SAMPLING },+ stream: true,+ }+}++const SURFACES: &[(&str, &str)] = &[+ ("dry hard ground", "dry"),+ ("wet ground", "wet"),+ ("puddle or standing water", "water"),+ ("glossy or polished surface", "glossy"),+ ("grass", "grass"),+ ("sand or soil", "soil"),+ ("snow", "snow"),+ ("carpet or fabric", "fabric"),+ ("other", "other"),+];+const LIGHTS: &[(&str, &str)] = &[+ ("direct sunlight", "sun"),+ ("overcast daylight", "overcast"),+ ("window light", "window"),+ ("indoor lamps", "lamps"),+ ("night", "night"),+];+const FROM: &[(&str, &str)] = &[+ ("left", "left"),+ ("right", "right"),+ ("front", "front"),+ ("behind", "behind"),+ ("above", "above"),+];+const FALLS: &[(&str, &str)] = &[+ ("left", "left"),+ ("right", "right"),+ ("towards the viewer", "front"),+ ("away from the viewer", "back"),+ ("under the objects", "under"),+];+const COLOURS: &[(&str, &str)] = &[("warm", "warm"), ("neutral", "neutral"), ("cool", "cool")];+const PLACES: &[(&str, &str)] = &[("sun", "sun"), ("shade", "shade"), ("both", "both")];++/// The answer's phrase as an id: the exact phrase, else one the answer contains or that contains+/// it ("puddle" -> water), else None.+fn pick(v: Option<&serde_json::Value>, table: &[(&str, &str)]) -> Option<String> {+ let s = v?.as_str()?.trim().to_lowercase();+ if s.is_empty() {+ return None;+ }+ table+ .iter()+ .find(|(p, _)| *p == s)+ .or_else(|| {+ table+ .iter()+ .find(|(p, _)| s.contains(p) || p.contains(s.as_str()))+ })+ .map(|(_, id)| id.to_string())+}++/// The model's answer -> a reading. Each answer it did not give, or gave outside the list, is the+/// default (`complete` false); no JSON at all -> None.+pub fn parse(text: &str) -> Option<SceneReading> {+ let start = text.find('{')?;+ let end = text.rfind('}')?;+ let v: serde_json::Value = serde_json::from_str(text.get(start..=end)?).ok()?;+ let d = SceneReading::default();+ let mut complete = true;+ let mut get = |key: &str, table: &[(&str, &str)], fallback: &str| {+ pick(v.get(key), table).unwrap_or_else(|| {+ complete = false;+ fallback.to_string()+ })+ };+ let surface = get("surface", SURFACES, &d.surface);+ let light = get("light", LIGHTS, &d.light);+ let light_from = get("light_from", FROM, &d.light_from);+ let shadows_fall = get("shadows_fall", FALLS, &d.shadows_fall);+ let colour = get("colour", COLOURS, &d.colour);+ let object_in = get("object_in", PLACES, &d.object_in);+ let hard_shadows = match v.get("hard_shadows") {+ Some(serde_json::Value::Bool(b)) => *b,+ Some(serde_json::Value::String(s))+ if s.eq_ignore_ascii_case("true") || s.eq_ignore_ascii_case("false") =>+ {+ s.eq_ignore_ascii_case("true")+ }+ _ => {+ complete = false;+ d.hard_shadows+ }+ };+ Some(SceneReading {+ surface,+ light,+ hard_shadows,+ light_from,+ shadows_fall,+ colour,+ object_in,+ complete,+ })+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn reads_the_bench_answers() {+ // The street (bench 2026-11-02), as the model wrote it.+ let r = parse("{\n \"surface\": \"dry hard ground\",\n \"light\": \"direct sunlight\",\n \"hard_shadows\": true,\n \"light_from\": \"left\",\n \"shadows_fall\": \"right\",\n \"colour\": \"warm\",\n \"object_in\": \"sun\"\n}").unwrap();+ assert_eq!(+ r,+ SceneReading {+ surface: "dry".into(),+ light: "sun".into(),+ hard_shadows: true,+ light_from: "left".into(),+ shadows_fall: "right".into(),+ colour: "warm".into(),+ object_in: "sun".into(),+ complete: true+ }+ );+ // The puddle, with text around the JSON and a code fence.+ let r = parse("Here it is:\n```json\n{\"surface\": \"wet ground\", \"light\": \"overcast daylight\", \"hard_shadows\": false, \"light_from\": \"above\", \"shadows_fall\": \"under the objects\", \"colour\": \"cool\", \"object_in\": \"shade\"}\n```").unwrap();+ assert_eq!(+ (+ r.surface.as_str(),+ r.shadows_fall.as_str(),+ r.hard_shadows,+ r.complete+ ),+ ("wet", "under", false, true)+ );+ }++ #[test]+ fn near_answers_and_defaults() {+ // A shorter phrase than asked, a string boolean, a missing key, an answer outside the list.+ let r = parse(r#"{"surface": "puddle", "light": "sunlight", "hard_shadows": "true", "light_from": "upper left", "colour": "purple"}"#).unwrap();+ assert_eq!(+ (r.surface.as_str(), r.light.as_str(), r.hard_shadows),+ ("water", "sun", true)+ );+ assert_eq!(+ (+ r.light_from.as_str(),+ r.shadows_fall.as_str(),+ r.colour.as_str()+ ),+ ("left", "under", "neutral")+ );+ assert!(!r.complete);+ assert_eq!(parse("I can't tell."), None);+ assert_eq!(parse("{not json}"), None);+ // The safe default names no water.+ assert_eq!(SceneReading::default().surface, "dry");+ }++ #[test]+ fn request_names_the_object() {+ let r = request("AAA".into(), " Woman ", 7);+ assert!(+ r.prompt.contains("the woman.")+ && r.images == vec!["AAA".to_string()]+ && r.sampling.seed == 7+ && r.system_prompt == SYSTEM_PROMPT+ );+ }+}diff --git a/crates/qls-service/src/security_tests.rs b/crates/qls-service/src/security_tests.rsindex 894848a..d092935 100644--- a/crates/qls-service/src/security_tests.rs+++ b/crates/qls-service/src/security_tests.rs@@ -49,7 +49,9 @@ fn fixture(with_password: bool) -> Fixture {/// The service starting on `dir` (again, for a restart).fn start(dir: &std::path::Path) -> Arc<AppState> {- let engine = Engine::new(AppConfig::default(), dir).unwrap();+ // The engine folder inside the test's own: the default is the user's (a matting model installed+ // there made "installed" true).+ let engine = Engine::new(AppConfig { sdcpp_dir: dir.join("sdcpp"), ..AppConfig::default() }, dir).unwrap();Arc::new(AppState {engine,token: "t".repeat(64),diff --git a/src/components/BlendChoice.tsx b/src/components/BlendChoice.tsxnew file mode 100644index 0000000..7fc859a--- /dev/null+++ b/src/components/BlendChoice.tsx@@ -0,0 +1,139 @@+// "Blend into scene" (LayerDoc): what the AI read about where each object stands, shown before the+// edit so the user can correct it (Gabriele 11-02: "un pop up con possibilità di correggerlo"). The+// reading picks the effects the prompt names (lib/blend.ts): a wrong "wet" draws a reflection on dry+// ground, a wrong "dry" leaves a puddle without one.++import { Loader2, Sun, X } from "lucide-react";+import { useEffect, useRef } from "react";+import { blendEffects, FALLS, SURFACES } from "../lib/blend";+import type { SceneReading } from "../lib/types";+import { IconButton } from "./ui";++export interface BlendRow {+ id: string;+ name: string;+ /** Missing while it is being read. */+ reading?: SceneReading;+ /** Why the reading is the safe default. */+ failed?: string;+}++/** At the fast preset (11-02 bench, RTX 5070 Ti): ~2 s to read each object's place, then one edit of+ * the whole scene for all of them, 12-24 s. */+const READ_SECONDS = 2;+const EDIT_SECONDS = 20;++export function BlendChoice({ rows, onChange, onBlend, onCancel }: { rows: BlendRow[]; onChange: (id: string, r: SceneReading) => void; onBlend: () => void; onCancel: () => void }) {+ const reading = rows.some((r) => !r.reading);+ const go = useRef<HTMLButtonElement>(null);+ useEffect(() => {+ if (!reading) go.current?.focus();+ }, [reading]);+ useEffect(() => {+ const onKey = (e: KeyboardEvent) => {+ if (e.key !== "Escape") return;+ e.preventDefault();+ e.stopImmediatePropagation();+ onCancel();+ };+ window.addEventListener("keydown", onKey, true);+ return () => window.removeEventListener("keydown", onKey, true);+ }, [onCancel]);+ const s = EDIT_SECONDS + rows.length * READ_SECONDS;+ const time = s < 60 ? `about ${Math.max(5, Math.round(s / 5) * 5)} s` : `about ${Math.round(s / 60)} min`;++ return (+ <div className="modal-scrim" onPointerDown={(e) => e.target === e.currentTarget && onCancel()}>+ <div className="split-choice blend-choice" role="dialog" aria-modal="true" aria-labelledby="blend-choice-title">+ <span className="split-choice-close">+ <IconButton title="Cancel (Esc)" onClick={onCancel}>+ <X size={18} />+ </IconButton>+ </span>+ <h2 id="blend-choice-title">Blend into the scene</h2>+ <p className="split-choice-lead">+ The AI looked at where {rows.length === 1 ? "the object stands" : "each object stands"}. It redraws the scene with what that place does: the contact shadow, the+ shadow, a reflection on wet or shiny ground. Check what it read and change anything that is wrong.+ </p>+ <div className="blend-rows">+ {rows.map((row) => {+ const r = row.reading;+ return (+ <div key={row.id} className="blend-row">+ <div className="blend-row-head">+ <span className="blend-row-name">{row.name}</span>+ <span className={`blend-row-state ${row.failed ? "warn" : ""}`} title={row.failed}>+ {!r ? (+ <>+ <Loader2 size={13} className="spin" /> Reading the scene…+ </>+ ) : row.failed ? (+ "Could not read it: check these"+ ) : r.complete ? (+ "Read by the AI"+ ) : (+ "Partly read: check these"+ )}+ </span>+ </div>+ <div className={`blend-fields ${r ? "" : "waiting"}`}>+ <label>+ <span>Ground</span>+ <select className="select" value={r?.surface ?? ""} disabled={!r} onChange={(e) => r && onChange(row.id, { ...r, surface: e.target.value as SceneReading["surface"] })}>+ {!r && <option value="" />}+ {SURFACES.map((o) => (+ <option key={o.id} value={o.id}>+ {o.label}+ </option>+ ))}+ </select>+ </label>+ <label>+ <span>Shadows</span>+ <div className="seg">+ {([false, true] as const).map((hard) => (+ <button key={String(hard)} className={r && r.hard_shadows === hard ? "on" : ""} disabled={!r} onClick={() => r && onChange(row.id, { ...r, hard_shadows: hard })}>+ {hard ? "Hard (sun)" : "Soft"}+ </button>+ ))}+ </div>+ </label>+ <label>+ <span>They fall</span>+ <select className="select" value={r?.shadows_fall ?? ""} disabled={!r} onChange={(e) => r && onChange(row.id, { ...r, shadows_fall: e.target.value as SceneReading["shadows_fall"] })}>+ {!r && <option value="" />}+ {FALLS.map((o) => (+ <option key={o.id} value={o.id}>+ {o.label}+ </option>+ ))}+ </select>+ </label>+ </div>+ {r && (+ <details className="blend-prompt">+ <summary>What the AI is asked</summary>+ <p>{blendEffects(row.name, r)}</p>+ </details>+ )}+ </div>+ );+ })}+ </div>+ <div className="split-choice-foot">+ <span>+ {time} · the rest of the picture stays as it is · moved it later? Blend again+ </span>+ <span className="blend-buttons">+ <button className="btn ghost" onClick={onCancel}>+ Cancel+ </button>+ <button ref={go} className="btn primary" onClick={onBlend} disabled={reading}>+ <Sun size={15} /> Blend+ </button>+ </span>+ </div>+ </div>+ </div>+ );+}diff --git a/src/components/LabScene.ts b/src/components/LabScene.tsindex f486b9e..c492ec2 100644--- a/src/components/LabScene.ts+++ b/src/components/LabScene.ts@@ -8,6 +8,7 @@ import { api, urls } from "../lib/api";import { centre, type LayerDoc, type Place, type SceneEdit } from "../lib/layerDoc";import { dilate, fileSafe, fromLogits, refineEdges } from "../lib/layers";import { Segmenter } from "../lib/sam";+import { blendKeep } from "../lib/blend";import { alignEdit, attached, blur, changed, darkness, IDENTITY, invertAffine, luminance, MARK_COLOURS, objectAt, scaleAffine, splitShadows, toneCurve, type Affine, type MarkColour } from "../lib/sceneEdit";import type { InputRecord } from "../lib/types";import { loadImage, pixels, drawSource, sourceInfo, toPng } from "./LayerDoc";@@ -273,6 +274,31 @@ export async function readScene(doc: LayerDoc, e: SceneEdit, result: string): Pr// Shadows: only of the objects asked for. A new object comes alone (its shadow is made// afterwards with Automatic shadows), whatever shadow Qwen drew for it is left out.const targets = e.shadows.filter((id) => feet.has(id)).map((id) => ({ of: id, m: feet.get(id)! }));+ // Blend into scene: what Qwen's redrawn scene changed round the objects, in colour (lib/blend.ts).+ if (targets.length && e.blend) {+ const all = new Uint8Array(w * h);+ for (const t of targets) for (let i = 0; i < t.m.length; i++) if (t.m[i]) all[i] = 255;+ const r = blendKeep(p.before, p.after, p.valid, all, w, h);+ if (r.n < w * h * 0.0003) {+ out.notes.push("Nothing was added round the objects. Blend again, or check what the AI read.");+ return out;+ }+ // Qwen's image at full size, its overall tone brought back to the original's (colours kept).+ const full = warp(p.img, p.t, W, H, W, H);+ const fctx = full.getContext("2d")!;+ const px = fctx.getImageData(0, 0, W, H);+ const q = px.data;+ for (let i = 0; i < q.length; i += 4) {+ const l = 0.2126 * q[i] + 0.7152 * q[i + 1] + 0.0722 * q[i + 2];+ const k = (r.lut[Math.min(255, Math.round(l))] + 1) / (l + 1);+ q[i] = q[i] * k;+ q[i + 1] = q[i + 1] * k;+ q[i + 2] = q[i + 2] * k;+ }+ fctx.putImageData(px, 0, 0);+ out.shadows.push({ of: "all", src: `input:${(await upload(r.alpha, w, h, W, H, "Blend", full)).id}` });+ return out;+ }// One layer for all of them (Automatic shadows): the darkening within reach of the objects, taken// out only where an object is (it covers its own pixels). No band around the outlines to fill// back: a fill that fell short left a light ring round the spider's legs (11-01).diff --git a/src/components/LabStage.tsx b/src/components/LabStage.tsxindex 9ba790f..d2de586 100644--- a/src/components/LabStage.tsx+++ b/src/components/LabStage.tsx@@ -116,8 +116,8 @@ export function JobPct({ job, item }: { job: JobView; item: SessionItem }) {function JobPill({ j }: { j: LabJob }) {const layer = j.doc.layers.find((l) => l.id === j.layer);- const auto = j.layer === "scene" && j.doc.scenes?.some((e) => e.one && e.source === j.item.request?.images?.[0]);- const what = j.layer === "shadows" || auto ? "the shadows" : j.layer === "scene" ? "the scene" : layer ? (layer.base ? "the background" : layer.name) : "";+ const auto = j.layer === "scene" ? j.doc.scenes?.find((e) => e.one && e.source === j.item.request?.images?.[0]) : undefined;+ const what = auto?.blend ? "the blend" : j.layer === "shadows" || auto ? "the shadows" : j.layer === "scene" ? "the scene" : layer ? (layer.base ? "the background" : layer.name) : "";if (j.job.status === "failed")return (<span className="lab-progress failed" title={j.job.error?.detail ?? undefined}>diff --git a/src/components/LayerDoc.tsx b/src/components/LayerDoc.tsxindex 13321ca..dcfb034 100644--- a/src/components/LayerDoc.tsx+++ b/src/components/LayerDoc.tsx@@ -4,15 +4,17 @@// is the image the prompt below edits: the result shows on the layer, here (the background: "Fill// the holes" sets up a brushed Remove on the photo). On the canvas: click a layer to select it, drag// to move it, drag the corner to scale it; Shift/Ctrl+click selects more (moved and scaled-// together), Group keeps them together. Whole-image edits (LabScene.ts) give Qwen the flattened-// layers: "Shadows" reads back each object's shadow as its own layer (it moves with the object),-// "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).+// together), Group keeps them together. "Blend into scene" (lib/blend.ts, BlendChoice) has the AI+// read where each object stands, then a brushed edit round its base adds its shadow, reflection,+// grass at its feet, read back as layers that follow it. Whole-image edits (LabScene.ts) give Qwen+// 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 { useEffect, useMemo, useRef, useState } from "react";import { api, urls } from "../lib/api";import { focusPixels, foreground, modelMatte, stickerAlpha } 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, 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";@@ -22,7 +24,8 @@ import { MARK_COLOURS, marksPrompt, type MarkColour } from "../lib/sceneEdit";import { placesOf } from "./LabScene";import { shortcut } from "../lib/platform";import { addResult, addVersions, cancelJob, editSource, focusPrompt, getState, itemOrigin, itemSource, setState, submitRequest, toastError, toastInfo, updateComposer, useStore, type SessionItem } from "../lib/store";-import type { InputRecord, JobView } from "../lib/types";+import type { InputRecord, JobView, SceneReading } from "../lib/types";+import { BlendChoice, type BlendRow } from "./BlendChoice";import { useJobPercent } from "./jobMotion";import { JobPct, LabJobs, useLab, useLabJobs } from "./LabStage";import { IconButton } from "./ui";@@ -56,13 +59,13 @@ function StickerRing({ job, item }: { job: JobView; item: SessionItem }) {);}-/** Where Automatic shadows' edit is: "Making the shadows · 38%". */+/** Where the blend's edit is: "Blending into the scene · 38%". */function ShadowPhase({ 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 === "done") return <>Reading the shadows</>;- return <>Making the shadows · {Math.floor(pct)}%</>;+ if (job.status === "done") return <>Reading what the AI added</>;+ return <>Blending into the scene · {Math.floor(pct)}%</>;}/** What the canvas needs of a layer's version: its alpha (for clicks), where its content is, a thumbnail. */@@ -345,11 +348,6 @@ function dab(ctx: CanvasRenderingContext2D, x: number, y: number, r: number, mod/** How far a whole-image shadow edit's result is read around each object (% of the long side). */const SCENE_REACH = 12;-/** Automatic shadows: the whole scene edited, nothing painted. Generic on purpose (11-01 bench, Halloween and- * kitchen): the model put shadows where the light makes them and none on floating things (lettering, ghosts). */-const AUTO_SHADOWS_PROMPT =- "Add natural shadows for the objects that stand or rest on a surface: a soft contact shadow where each one touches it and the shadow each one casts, following the direction of the light in the scene. Floating things cast no shadow. Keep everything else in the image exactly unchanged.";-/** The selected layers per document (the last one is the one the panel shows), kept while the* view closes (Paint area, Expand, the Stage). */const lastSelected = new Map<string, string[]>();@@ -932,13 +930,26 @@ export function LayerDoc({ projectId, doc, onChange, onNewSplit }: { projectId:// eslint-disable-next-line react-hooks/exhaustive-deps}, [jobs, session, live.stickers]);- // Automatic shadows being made (sent, generated, or read back): the layers stay where they are- // meanwhile (the shadows are made for this layout), and the stage says how far it is.- const [shadowSending, setShadowSending] = useState(false);+ // 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.+ const [blendSending, setBlendSending] = useState(false);const autoScenes = (live.scenes ?? []).filter((e) => e.one);const shadowJob = labJobs.find((j) => j.job.status !== "failed" && autoScenes.some((e) => e.source === j.item.request?.images?.[0]));const shadowReading = autoScenes.some((e) => session.some((i) => i.gen && itemOrigin(i).from[0] === e.source && !live.known.includes(`gen:${i.gen.id}`)));- const shadowing = shadowSending || !!shadowJob || shadowReading;+ const shadowing = blendSending || !!shadowJob || shadowReading;+ // Something moved (or was scaled, shown, hidden) since the last blend: its layer no longer fits.+ const lastBlend = [...(live.scenes ?? [])].reverse().find((e) => e.blend);+ const blendStale =+ !!lastBlend &&+ live.layers.some((l) => l.blend === "paste" && !l.hidden) &&+ live.layers.some((o) => {+ if (o.base || o.effect) return false;+ const at = lastBlend.places[o.id];+ if (!at) return !o.hidden;+ if (o.hidden) return true;+ return o.source !== at.source || Math.hypot(o.dx - at.dx, o.dy - at.dy) > 0.02 * Math.max(W, H) || Math.abs(o.s / at.s - 1) > 0.05;+ });const skipSticker = (s: Sticker) => {if (s.job) void cancelJob(s.job);@@ -968,7 +979,8 @@ export function LayerDoc({ projectId, doc, onChange, onNewSplit }: { projectId:// Shadow strength: the Automatic shadows layer redrawn from the model's version, its alpha as k of// them stacked (1 - (1 - a)^k: darker stays a soft shadow, lighter fades evenly), as its next version.- const autoShadows = live.layers.find((l) => l.auto && l.effect);+ // The Blend (or older Shadows) layer shown, not the in-front piece.+ const autoShadows = live.layers.find((l) => l.auto && l.effect && l.blend !== "front" && !l.hidden) ?? live.layers.find((l) => l.auto && l.effect && l.blend !== "front");const [strengthShown, setStrengthShown] = useState(100);useEffect(() => setStrengthShown(Math.round((autoShadows?.strength ?? 1) * 100)), [autoShadows?.id, autoShadows?.strength]);useEffect(() => {@@ -1121,7 +1133,8 @@ export function LayerDoc({ projectId, doc, onChange, onNewSplit }: { projectId:commitRef.current({...d,...(e ? { ext: { ...d.ext, [src]: e } } : {}),- layers: d.layers.map((x) => (x.id === l.id ? { ...x, source: src, history: [...x.history, src] } : x)),+ // Strength starts from what was brushed (else its next change would bring back what was erased).+ layers: d.layers.map((x) => (x.id === l.id ? { ...x, source: src, history: [...x.history, src], ...(x.made ? { made: src, strength: 1 } : {}) } : x)),known: [...d.known, src],});} catch (e) {@@ -1422,7 +1435,7 @@ 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. */- const sendScene = async (o: { shadows: string[]; look: string[]; prompt: string; marks: boolean; hint: string; send?: boolean; one?: boolean }) => {+ 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.const keep = { selected: getState().selected, refs: getState().composer.refs };@@ -1463,10 +1476,13 @@ export function LayerDoc({ projectId, doc, onChange, onNewSplit }: { projectId:places: placesOf(live),reach: SCENE_REACH,...(o.one ? { one: true } : {}),+ ...(o.blend ? { blend: true } : {}),};// The same layers again upload as the same image (the service keeps one copy): an older edit of it// would read this one's result first (11-01: per-object shadows instead of the one layer asked for).- commit({ ...live, scenes: [...(live.scenes ?? []).filter((x) => x.source !== target), scene] });+ // 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;+ commit({ ...live, layers, scenes: [...(live.scenes ?? []).filter((x) => x.source !== target), scene] });if (marksId) setSketch({ marks: [], wants: sketch.wants });setSels([]);if (o.send) {@@ -1487,14 +1503,94 @@ export function LayerDoc({ projectId, doc, onChange, onNewSplit }: { projectId:};- const autoShadowsNow = async () => {- const objects = live.layers.filter((l) => !l.base && !l.effect && !l.hidden).map((l) => l.id);- if (!objects.length) return toastInfo("No visible objects to make shadows for.");- setShadowSending(true);+ // Blend into scene (11-02, replaces Automatic shadows): the AI reads where each object stands+ // (BlendChoice shows it, the user corrects it), then Qwen redraws the whole scene with what each+ // place does (lib/blend.ts blendPrompt) and only what changed round the objects is kept (LabScene+ // readScene, blendKeep): one Blend layer over the background and one in-front piece on top.+ const [blendRows, setBlendRows] = useState<BlendRow[] | null>(null);+ /** Bumped by Cancel and Blend: readings still running for an older dialog stop. */+ const blendRun = useRef(0);++ /** The scene read for one object by the Prompt+ model (a job that makes no image). */+ const readPlace = async (o: DocLayer, rec: InputRecord, run: number) => {+ let reading: SceneReading | undefined;+ let failed: string | undefined;try {- await sendScene({ shadows: objects, look: [], prompt: AUTO_SHADOWS_PROMPT, marks: false, send: true, one: true, hint: "Making the shadows: the model adds them to the whole scene where the light makes them, as one Shadows layer. Moved something? Make them again: the layer is replaced." });+ const ref = refFromInput(rec);+ const req = buildRequest({ ...getState().composer, prompt: "", refs: [ref], mask: null, outpaint: null, create: false, mode: "auto", enhance: false, enhancedFrom: null, seed: null });+ let job = await api.submit({ ...req, read_scene: o.name, hidden: true, ...(getState().privateMode ? { private: true } : {}) });+ while (job.status !== "done" && job.status !== "failed" && job.status !== "cancelled") {+ await new Promise((r) => window.setTimeout(r, 400));+ if (blendRun.current !== run) {+ void api.cancel(job.id).catch(() => {});+ return;+ }+ job = await api.job(job.id);+ }+ if (job.scene) reading = job.scene;+ else failed = job.error?.message ?? job.notes[job.notes.length - 1] ?? "no answer";+ } catch (e) {+ failed = e instanceof Error ? e.message : String(e);+ }+ if (blendRun.current !== run) return;+ setBlendRows((rows) => rows && rows.map((r) => (r.id === o.id ? { ...r, reading: reading ?? { ...DEFAULT_READING }, failed } : r)));+ };++ /** Opens the dialog: the selected objects, else every visible one; their scene is read meanwhile. */+ const startBlend = async () => {+ const all = live.layers.filter((l) => !l.base && !l.effect && !l.hidden);+ const chosen = sels.some((id) => all.some((l) => l.id === id)) ? all.filter((l) => sels.includes(l.id)) : all;+ if (!chosen.length) return toastInfo("No visible objects to blend in.");+ setBusy(true);+ try {+ // What the AI reads: the layers as they are, without the earlier Blend or Shadows layers, on grey+ // (holes would make the image transparent).+ const skip = new Set(live.layers.filter((l) => l.effect && l.auto).map((l) => l.id));+ const flat = document.createElement("canvas");+ flat.width = W;+ flat.height = H;+ const fctx = flat.getContext("2d")!;+ fctx.fillStyle = "#808080";+ fctx.fillRect(0, 0, W, H);+ fctx.drawImage(await render(W, H, skip), 0, 0);+ const rec = await api.upload(await toPng(flat), "Layers to blend in.png");+ const run = ++blendRun.current;+ setBlendRows(chosen.map((o) => ({ id: o.id, name: o.name })));+ for (const o of chosen) void readPlace(o, rec, run);+ } catch (e) {+ toastError(e);+ } finally {+ setBusy(false);+ }+ };++ const cancelBlend = () => {+ blendRun.current++;+ setBlendRows(null);+ };++ /** One edit of the whole scene for every object in the dialog, sent right away as a lab step. */+ const sendBlend = async () => {+ const rows = blendRows;+ blendRun.current++;+ setBlendRows(null);+ const items = (rows ?? []).flatMap((r) => (r.reading && live.layers.some((l) => l.id === r.id) ? [{ id: r.id, name: r.name, reading: r.reading }] : []));+ if (!items.length) return;+ setBlendSending(true);+ try {+ const hideAuto = live.layers.some((l) => l.auto && l.effect && !l.blend && !l.hidden);+ await sendScene({+ shadows: items.map((i) => i.id),+ look: [],+ prompt: blendPrompt(items),+ marks: false,+ send: true,+ one: true,+ blend: true,+ hint: `Blending ${items.length === 1 ? "it" : `the ${items.length} objects`} into the scene${hideAuto ? "; the old Shadows layer is hidden" : ""}. Moved something later? Blend again.`,+ });} finally {- setShadowSending(false);+ setBlendSending(false);}};@@ -1675,8 +1771,8 @@ export function LayerDoc({ projectId, doc, onChange, onNewSplit }: { projectId:<div className="doc-lock-card"><Loader2 size={18} className="spin" /><span>- {shadowJob ? <ShadowPhase job={shadowJob.job} item={shadowJob.item} /> : shadowSending ? "Sending the scene" : "Reading the shadows"}- <small>The layers stay where they are until the shadows are in</small>+ {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></div></div>@@ -1933,7 +2029,9 @@ export function LayerDoc({ projectId, doc, onChange, onNewSplit }: { projectId:: sel.effect? sel.follows? "Moves and scales with its object. Make it again after a big move."- : "Made where the objects are: make them again after moving objects."+ : sel.blend+ ? "The AI's redrawn scene round the objects (their shadows, reflections, where they touch the ground), on top of them. Something wrong? The Eraser (E) takes it out of this layer. Moved an object? Blend again."+ : "Made where the objects are: make them again after moving objects.": `The prompt edits this layer at its own size, e.g. “Complete the ${sel.name.toLowerCase()}, keep the transparent background”.`}</p><div className="doc-grid">@@ -1987,6 +2085,7 @@ export function LayerDoc({ projectId, doc, onChange, onNewSplit }: { projectId:</aside></div>+ {blendRows && <BlendChoice rows={blendRows} onChange={(id, r) => setBlendRows((rows) => rows && rows.map((x) => (x.id === id ? { ...x, reading: r } : x)))} onBlend={() => void sendBlend()} onCancel={cancelBlend} />}<div className={`editor-tools ${shadowing ? "locked" : ""}`}><div className="group"><IconButton title="Select and move (V)" active={tool === "move" && !spacePressed} onClick={() => setTool("move")}>@@ -2036,12 +2135,16 @@ export function LayerDoc({ projectId, doc, onChange, onNewSplit }: { projectId:{/* The whole document's commands (the panel on the right is for the selected layer). */}<div className="group"><button- className="pill doc-cmd"- onClick={autoShadowsNow}+ className={`pill doc-cmd ${blendStale ? "stale" : ""}`}+ onClick={startBlend}disabled={busy || shadowing}- title="Nothing to paint: the whole scene goes to the model, which adds the shadows where the light makes them, as one Shadows layer (made again after moving things: it is replaced)"+ title={+ blendStale+ ? "Something moved since the blend: its shadows and reflections no longer fit. Blend again (the selected objects, else all)"+ : "The AI reads where each object stands (you can correct it), then redraws the scene with their shadows, reflections on wet or shiny ground, grass round their feet; only that is kept, as the Blend layer (the selected objects, else all)"+ }>- <Sun size={15} /> Automatic shadows+ <Sun size={15} /> {blendStale ? "Blend again" : "Blend into scene"}</button>{autoShadows && (<label className="slider" title="How dark the Shadows layer is, without making it again (100 %: as the model made it)">diff --git a/src/components/LayersEditor.tsx b/src/components/LayersEditor.tsxindex a3edd74..c38f82c 100644--- a/src/components/LayersEditor.tsx+++ b/src/components/LayersEditor.tsx@@ -93,12 +93,24 @@ function LayersLab({ projectId }: { projectId: string }) {layers = [{ id, name: o.name, source: o.src, history: [o.src], hidden: false, base: false, dx: 0, dy: 0, s: 1 }, ...layers];}}+ // Blend: layers of earlier blend versions are hidden (in-front pieces put a light rim on the+ // boots; "under" layers stopped at the objects' outline, which Qwen had moved, 11-02).+ if (e.blend) layers = layers.map((l) => (l.blend === "front" || l.blend === "under" ? { ...l, hidden: true } : l));for (const s of r.shadows) {+ // Blend: the one layer on top of everything (it holds the objects' contact too); replaced by the next result.+ if (s.of === "all" && e.blend) {+ const have = layers.find((l) => l.auto && l.blend === "paste");+ const next: DocLayer = have+ ? { ...have, source: s.src, history: [...have.history, s.src], made: undefined, strength: undefined, hidden: false }+ : { id: `fx-${result}-all`, name: "Blend", source: s.src, history: [s.src], hidden: false, base: false, effect: true, auto: true, blend: "paste", dx: 0, dy: 0, s: 1 };+ layers = [next, ...layers.filter((l) => l.id !== next.id)];+ continue;+ }// Automatic shadows: the one layer, just above the background, replaced by the next result.if (s.of === "all") {- const have = layers.find((l) => l.auto);+ const have = layers.find((l) => l.auto && !l.blend);// A new result starts at its own strength again.- if (have) layers = layers.map((l) => (l.id === have.id ? { ...l, source: s.src, history: [...l.history, s.src], made: undefined, strength: undefined } : l));+ if (have) layers = layers.map((l) => (l.id === have.id ? { ...l, source: s.src, history: [...l.history, s.src], made: undefined, strength: undefined, hidden: false } : l));else {const layer: DocLayer = { id: `fx-${result}-all`, name: "Shadows", source: s.src, history: [s.src], hidden: false, base: false, effect: true, auto: true, dx: 0, dy: 0, s: 1 };const at = layers.findIndex((l) => l.base);diff --git a/src/lib/blend.test.ts b/src/lib/blend.test.tsnew file mode 100644index 0000000..34ea227--- /dev/null+++ b/src/lib/blend.test.ts@@ -0,0 +1,86 @@+import { describe, expect, it } from "vitest";+import { blendEffects, blendKeep, blendPrompt, DEFAULT_READING } from "./blend";+import type { SceneReading } from "./types";++const read = (o: Partial<SceneReading>): SceneReading => ({ ...DEFAULT_READING, complete: true, ...o });+const WATER = /water|puddle|ripple|reflection|wet|mirror/i;++describe("blend prompts", () => {+ it("names water and reflections only where the surface has them", () => {+ // The bench's four scenes as the reader saw them (2026-11-02).+ expect(blendEffects("Man", read({ surface: "dry", light: "sun", hard_shadows: true, shadows_fall: "right" }))).toBe(+ "Add the man's hard-edged shadow on the ground, starting at the bottom of the man and cast to the right with the same direction, angle and length as the other shadows in the scene, and a dark contact shadow where the man touches the ground. The ground is dry: no reflection.",+ );+ const puddle = blendEffects("Woman", read({ surface: "wet", light: "overcast", shadows_fall: "under" }));+ expect(puddle).toBe(+ "Add a faint soft darkening on the wet ground right where the woman touches it. Add the reflection of the lower part of the woman in the wet ground: mirrored upside down, starting exactly at the bottom of the woman, slightly darker, as clear as the other reflections in it.",+ );+ expect(blendEffects("Teapot", read({ surface: "glossy", light: "window", shadows_fall: "right" }))).toContain("a soft shadow on the polished surface under the teapot, falling slightly to the right");+ const grass = blendEffects("Dog", read({ surface: "grass", light: "sun", shadows_fall: "right" }));+ expect(grass).toContain("grass blades cover the bottom of the dog");+ expect(grass).not.toMatch(WATER);+ expect(blendEffects("Duck", read({ surface: "water" }))).toContain("small ripples around where it stands in the water");+ for (const surface of ["dry", "soil", "snow", "fabric", "other"] as const) expect(blendEffects("Box", read({ surface })).replace(/no reflection/i, "")).not.toMatch(WATER);+ });+ it("asks for every object in one edit, then what stays", () => {+ const one = blendPrompt([{ name: "Dog", reading: read({ surface: "grass" }) }]);+ expect(one.endsWith(" Do not change the dog. Keep everything else in the image unchanged.")).toBe(true);+ const three = blendPrompt(["Woman", "Dog", "Bench"].map((name) => ({ name, reading: read({}) })));+ expect(three).toContain("where the woman touches it. The ground is dry: no reflection. Add a faint soft darkening on the ground right where the dog");+ expect(three.endsWith("Do not change the woman, the dog and the bench. Keep everything else in the image unchanged.")).toBe(true);+ });+});++/** A w×h mask with the box [x0, x1] × [y0, y1] set. */+function rect(w: number, h: number, x0: number, y0: number, x1: number, y1: number): Uint8Array {+ const m = new Uint8Array(w * h);+ for (let y = y0; y <= y1; y++) for (let x = x0; x <= x1; x++) m[y * w + x] = 255;+ return m;+}++describe("blendKeep", () => {+ const w = 200;+ const h = 300;+ const obj = rect(w, h, 90, 60, 110, 120); // 61 px tall+ const valid = new Uint8Array(w * h).fill(1);+ /** A ground with a fine random texture (60-180; its blur is flat grey). */+ const texture = (seed: number) => {+ const px = new Uint8ClampedArray(w * h * 4);+ let s = seed;+ for (let i = 0; i < w * h; i++) {+ s = (s * 1103515245 + 12345) % 2147483648;+ const v = 60 + (s % 121);+ px.set([v, v, v, 255], i * 4);+ }+ return px;+ };+ const before = texture(1);+ const at = (m: Uint8Array, x: number, y: number) => m[y * w + x];++ it("pastes the changed area round the object with the object's part in it, nothing else", () => {+ const after = texture(2); // the whole ground redrawn: the same kind of texture, other grains+ const paint = (x0: number, y0: number, x1: number, y1: number, f: (v: number) => number) => {+ for (let y = y0; y <= y1; y++) for (let x = x0; x <= x1; x++) for (let c = 0; c < 3; c++) after[(y * w + x) * 4 + c] = f(after[(y * w + x) * 4 + c]);+ };+ paint(80, 105, 150, 140, (v) => v * 0.35); // its shadow, and its feet redrawn darker (Qwen moved them)+ paint(92, 65, 108, 85, () => 230); // its top recoloured: a change of the object itself+ paint(5, 5, 25, 25, (v) => v * 0.3); // a dark patch far away+ paint(0, 285, w - 1, 299, (v) => v * 0.35); // a dark band past twice its height...+ paint(140, 140, 144, 299, (v) => v * 0.35); // ...attached to the shadow by a thin strip+ const r = blendKeep(before, after, valid, obj, w, h);+ expect(at(r.alpha, 130, 130)).toBeGreaterThan(200); // the shadow+ expect(at(r.alpha, 100, 115)).toBeGreaterThan(200); // the object's feet, from the edit+ expect(at(r.alpha, 100, 75)).toBe(0); // its recoloured top stays the original+ expect(at(r.alpha, 60, 60)).toBe(0); // the redrawn texture+ expect(at(r.alpha, 15, 15)).toBe(0); // far away, not touching it+ expect(at(r.alpha, 5, 292)).toBe(0); // beyond twice its height+ expect(r.n).toBeGreaterThan(1500);+ });+ it("pastes nothing when only the tone changed, and the tone comes back", () => {+ const after = before.slice();+ for (let i = 0; i < after.length; i += 4) for (let c = 0; c < 3; c++) after[i + c] = Math.min(255, after[i + c] * 0.8);+ const r = blendKeep(before, after, valid, obj, w, h);+ expect(r.n).toBe(0);+ expect(Math.abs(r.lut[96] - 120)).toBeLessThan(4); // 0.8 darker -> brought back+ });+});diff --git a/src/lib/blend.ts b/src/lib/blend.tsnew file mode 100644index 0000000..964cb19--- /dev/null+++ b/src/lib/blend.ts@@ -0,0 +1,261 @@+// Layers lab "Blend into scene": moved objects made to belong where they stand. Bench 2026-11-02+// (`bench/20261102-200503-scene-integration`): a prompt that names reflections or water makes Qwen+// add water on dry ground, so the Prompt+ model first reads where each object stands (qls-core+// scene.rs; the user can correct it) and the prompt names only what that place does. Then Qwen+// redraws the whole scene (one plain edit of the flattened layers: it decides where and how), and the+// area that changed round the objects is pasted from it as it is, the objects' part in it included+// (Gabriele 11-02: Qwen moves the object a little, so its reflection only meets its own object). One+// "Blend" layer on top; the rest of the image stays the original.+//+// Everything here works on plain arrays (one byte per pixel, or RGBA).++import type { SceneReading } from "./types";+import { dilate, erode } from "./layers";+import { blur, fillHoles, luminance } from "./sceneEdit";++type Surface = SceneReading["surface"];+type Fall = SceneReading["shadows_fall"];++/** The choices the dialog offers, as the user reads them. */+export const SURFACES: { id: Surface; label: string }[] = [+ { id: "dry", label: "Dry ground" },+ { id: "wet", label: "Wet ground" },+ { id: "water", label: "Puddle or water" },+ { id: "glossy", label: "Glossy or polished" },+ { id: "grass", label: "Grass" },+ { id: "soil", label: "Sand or soil" },+ { id: "snow", label: "Snow" },+ { id: "fabric", label: "Carpet or fabric" },+ { id: "other", label: "Something else" },+];+export const FALLS: { id: Fall; label: string }[] = [+ { id: "under", label: "Under it" },+ { id: "left", label: "To the left" },+ { id: "right", label: "To the right" },+ { id: "front", label: "Towards the camera" },+ { id: "back", label: "Away from the camera" },+];++/** What is safe when the scene could not be read: dry ground, a soft shadow under it. */+export const DEFAULT_READING: SceneReading = {+ surface: "dry",+ light: "overcast",+ hard_shadows: false,+ light_from: "above",+ shadows_fall: "under",+ colour: "neutral",+ object_in: "both",+ complete: false,+};++const GROUND: Record<Surface, string> = {+ dry: "ground",+ wet: "wet ground",+ water: "water",+ glossy: "polished surface",+ grass: "grass",+ soil: "ground",+ snow: "snow",+ fabric: "surface",+ other: "surface",+};+const TOWARDS: Record<Fall, string> = { left: "to the left", right: "to the right", front: "towards the viewer", back: "away from the viewer", under: "" };++/** What Qwen is asked for one object (`name`, its layer name): only the effects this surface has.+ * Water words only on wet, water or glossy surfaces (bench rounds 1-2: named, they get drawn). */+export function blendEffects(name: string, r: SceneReading): string {+ const n = name.trim().toLowerCase() || "object";+ const g = GROUND[r.surface] ?? "surface";+ const fall = r.shadows_fall;+ let p: string;+ // A hard shadow as long and at the angle of the scene's own (a short stub looked pasted, 11-02); under+ // soft or overcast light only a faint darkening at the contact (a dark blob under the boots looked fake).+ if (r.hard_shadows && fall !== "under")+ p = `Add the ${n}'s hard-edged shadow on the ${g}, starting at the bottom of the ${n} and cast ${TOWARDS[fall]} with the same direction, angle and length as the other shadows in the scene, and a dark contact shadow where the ${n} touches the ${g}.`;+ else if (fall === "under" || r.light === "overcast") p = `Add a faint soft darkening on the ${g} right where the ${n} touches it.`;+ else p = `Add a soft shadow on the ${g} under the ${n}, falling slightly ${TOWARDS[fall]}, and a faint darkening right where it touches the ${g}.`;+ // A clear mirror image from the base (a "blurred" one came out as a smear), of the lower part (the whole+ // woman put her face upside down between her boots, round 4).+ if (r.surface === "wet" || r.surface === "water")+ p += ` Add the reflection of the lower part of the ${n} in the ${g}: mirrored upside down, starting exactly at the bottom of the ${n}, slightly darker, as clear as the other reflections in it${r.surface === "water" ? ", with small ripples around where it stands in the water." : "."}`;+ else if (r.surface === "glossy") p += ` Add the ${n}'s reflection on the ${g}: mirrored upside down, starting exactly at the bottom of the ${n}, slightly darker and fading out.`;+ else if (r.surface === "grass") p += ` Let a few grass blades cover the bottom of the ${n} where it touches the grass, so it sits in the grass, not on top of it. The grass is dry.`;+ else if (r.surface === "soil" || r.surface === "snow") p += ` Let the ${n}'s base sink slightly into the ${r.surface === "snow" ? "snow" : "ground"}. No reflection.`;+ else p += ` The ${g} is dry: no reflection.`;+ return p;+}++/** The one edit's prompt for every object blended: each one's effects, then what stays. */+export function blendPrompt(items: { name: string; reading: SceneReading }[]): string {+ const names = items.map((i) => `the ${i.name.trim().toLowerCase() || "object"}`);+ const list = names.length < 2 ? names[0] : `${names.slice(0, -1).join(", ")} and ${names[names.length - 1]}`;+ return `${items.map((i) => blendEffects(i.name, i.reading)).join(" ")} Do not change ${list}. Keep everything else in the image unchanged.`;+}++/** The pixels set in `m`, as a box (null when none). */+function boxOf(m: Uint8Array, w: number, h: number): { x0: number; y0: number; x1: number; y1: number } | null {+ let x0 = w;+ let y0 = h;+ let x1 = -1;+ let y1 = -1;+ for (let y = 0; y < h; y++)+ for (let x = 0; x < w; x++)+ if (m[y * w + x]) {+ if (x < x0) x0 = x;+ if (x > x1) x1 = x;+ if (y < y0) y0 = y;+ if (y > y1) y1 = y;+ }+ return x1 < 0 ? null : { x0, y0, x1, y1 };+}++/** Distance in px to the nearest set pixel of `m` (two-pass chamfer, 1 / 1.4). */+function distance(m: Uint8Array, w: number, h: number): Float32Array {+ const d = new Float32Array(w * h);+ for (let i = 0; i < d.length; i++) d[i] = m[i] ? 0 : 1e9;+ const D = Math.SQRT2;+ for (let y = 0; y < h; y++)+ for (let x = 0; x < w; x++) {+ const i = y * w + x;+ let v = d[i];+ if (x > 0) v = Math.min(v, d[i - 1] + 1);+ if (y > 0) {+ v = Math.min(v, d[i - w] + 1);+ if (x > 0) v = Math.min(v, d[i - w - 1] + D);+ if (x < w - 1) v = Math.min(v, d[i - w + 1] + D);+ }+ d[i] = v;+ }+ for (let y = h - 1; y >= 0; y--)+ for (let x = w - 1; x >= 0; x--) {+ const i = y * w + x;+ let v = d[i];+ if (x < w - 1) v = Math.min(v, d[i + 1] + 1);+ if (y < h - 1) {+ v = Math.min(v, d[i + w] + 1);+ if (x < w - 1) v = Math.min(v, d[i + w + 1] + D);+ if (x > 0) v = Math.min(v, d[i + w - 1] + D);+ }+ d[i] = v;+ }+ return d;+}++/** Qwen's change of tone, undone: original luminance = gain x Qwen's + offset, fitted on `far` pixels+ * (blurred: a redrawn texture matches the original only on average), refitted 3 times without the+ * pixels that do not follow it (a shadow or a reflection far from the objects). A line, not a free+ * curve: a curve learnt that the only dark pixels far away (a long shadow) were a tone change and+ * took the shadows out with it. As a lookup 0-255. */+export function toneLine(after: Float32Array, before: Float32Array, far: Uint8Array): Float32Array {+ let gain = 1;+ let offset = 0;+ let limit = Infinity;+ for (let round = 0; round < 4; round++) {+ let n = 0;+ let sx = 0;+ let sy = 0;+ let sxx = 0;+ let sxy = 0;+ const res: number[] = [];+ for (let i = 0; i < after.length; i++) {+ if (!far[i]) continue;+ const e = Math.abs(gain * after[i] + offset - before[i]);+ if (e > limit) continue;+ n++;+ sx += after[i];+ sy += before[i];+ sxx += after[i] * after[i];+ sxy += after[i] * before[i];+ if (i % 7 === 0) res.push(e);+ }+ if (n < 100) break;+ const den = n * sxx - sx * sx;+ if (Math.abs(den) < 1e-6) break;+ gain = Math.min(2, Math.max(0.5, (n * sxy - sx * sy) / den));+ offset = (sy - gain * sx) / n;+ res.sort((x, y) => x - y);+ limit = Math.max(4, 2.5 * (res[res.length >> 1] ?? 4));+ }+ return Float32Array.from({ length: 256 }, (_, v) => Math.min(255, Math.max(0, gain * v + offset)));+}++/** What to paste of Qwen's redrawn scene (`after`, already put back over `before`; RGBA w×h; `valid`+ * where it covers), as the Blend layer's alpha (0-255), and `lut`: Qwen's luminance -> the original's,+ * to apply to its pixels (ratio per pixel: its colours kept, its overall darkening or brightening+ * taken out; per-channel curves gave a lilac cast on the bright puddle, 11-02). `objects` = the blended+ * objects' pixels (0/255).+ * Gabriele 11-02: "take the area that changed the most and put it in exactly as it is". Qwen moves and+ * reshapes an object a little (the boots ~12 px), so its shadow or reflection never meets the original+ * object: the area is pasted object and all (its boots with its reflection), on top.+ * - Change is measured on blurred images: a redrawn texture (grass, cobbles) keeps its local mean, a+ * shadow, a reflection or a wet patch changes it.+ * - Pieces of change that touch the objects, within twice their height (a relit lawn stays out); a+ * piece mostly inside an object is a change of its colour, not of the scene round it: left out+ * (an orange patch on the coat, 11-02). Gaps closed, holes filled, edge soft. */+export function blendKeep(before: ArrayLike<number>, after: ArrayLike<number>, valid: Uint8Array, objects: Uint8Array, w: number, h: number) {+ const n = w * h;+ const L = Math.max(w, h);+ const alpha = new Uint8Array(n);+ const box = boxOf(objects, w, h);+ const lb = luminance(before, n);+ const la = luminance(after, n);+ const dist = distance(objects, w, h);+ const far = new Uint8Array(n);+ for (let i = 0; i < n; i++) far[i] = valid[i] && dist[i] > 0.12 * L ? 1 : 0;+ const r = Math.max(1, Math.round(0.006 * L));+ const lut = toneLine(blur(la, w, h, r), blur(lb, w, h, r), far);+ if (!box) return { alpha, n: 0, lut };+ const k = new Float32Array(n);+ for (let i = 0; i < n; i++) k[i] = (lut[Math.min(255, Math.max(0, Math.round(la[i])))] + 1) / (la[i] + 1);+ const d = new Float32Array(n);+ for (let c = 0; c < 3; c++) {+ const bc = new Float32Array(n);+ const tc = new Float32Array(n);+ for (let i = 0; i < n; i++) {+ bc[i] = before[i * 4 + c];+ tc[i] = Math.min(255, after[i * 4 + c] * k[i]);+ }+ const bb = blur(bc, w, h, r);+ const bt = blur(tc, w, h, r);+ for (let i = 0; i < n; i++) if (valid[i]) d[i] = Math.max(d[i], Math.abs(bt[i] - bb[i]));+ }+ const oh = box.y1 - box.y0 + 1;+ const cand = new Uint8Array(n);+ for (let i = 0; i < n; i++) cand[i] = d[i] > 12 && dist[i] < 2 * oh ? 1 : 0;+ const near = dilate(objects, w, h, Math.max(2, 0.03 * L));+ // Pieces of change (4-connected), each kept or not as a whole.+ const label = new Int32Array(n).fill(-1);+ const keep = new Uint8Array(n);+ const stack: number[] = [];+ const piece: number[] = [];+ for (let s0 = 0; s0 < n; s0++) {+ if (!cand[s0] || label[s0] >= 0) continue;+ piece.length = 0;+ let inside = 0;+ let touches = false;+ label[s0] = s0;+ stack.push(s0);+ while (stack.length) {+ const i = stack.pop()!;+ piece.push(i);+ if (objects[i]) inside++;+ if (near[i]) touches = true;+ const x = i % w;+ for (const j of [x > 0 ? i - 1 : -1, x < w - 1 ? i + 1 : -1, i - w, i + w])+ if (j >= 0 && j < n && cand[j] && label[j] < 0) {+ label[j] = s0;+ stack.push(j);+ }+ }+ if (touches && inside <= piece.length / 2) for (const i of piece) keep[i] = 255;+ }+ const c = Math.max(2, Math.round(0.005 * L));+ const closed = fillHoles(erode(dilate(keep, w, h, c), w, h, c), w, h);+ const soft = blur(Float32Array.from(closed, (v) => v / 255), w, h, Math.max(1, Math.round(0.002 * L)));+ let kept = 0;+ for (let i = 0; i < n; i++) {+ alpha[i] = Math.round(Math.min(1, soft[i]) * 255);+ if (alpha[i] > 25) kept++;+ }+ return { alpha, n: kept, lut };+}diff --git a/src/lib/layerDoc.ts b/src/lib/layerDoc.tsindex 3cf5cd2..f261c65 100644--- a/src/lib/layerDoc.ts+++ b/src/lib/layerDoc.ts@@ -113,6 +113,11 @@ export interface DocLayer {at?: Place;/** Layers with the same group are selected, moved and scaled together. */group?: string;+ /** Blend into scene (with `auto`): "paste" = the area of the redrawn scene round the objects (their+ * shadows, reflections, their own contact with the ground), on top of them. Earlier versions'+ * layers (11-02; hidden by the next blend): "under" (only round them, over the background), "front"+ * (a piece over their edges). */+ blend?: "paste" | "under" | "front";/** Offset in frame px, and scale around the centre of what the layer shows. */dx: number;dy: number;@@ -156,6 +161,9 @@ export interface SceneEdit {reach: number;/** One shadow layer for all the objects (Automatic shadows), not one per object. */one?: boolean;+ /** Blend into scene (with `one`): the area of the edit that changed round the `shadows` objects,+ * pasted as it is as the Blend layer (lib/blend.ts blendKeep), not only the darkening. */+ blend?: boolean;/** Layers its results made, so the next result becomes their next version: object id -> its* shadow layer, colour -> the new layer, "<colour>:shadow" -> the new layer's shadow. */made?: Record<string, string>;diff --git a/src/lib/types.ts b/src/lib/types.tsindex 5008e5b..24c48af 100644--- a/src/lib/types.ts+++ b/src/lib/types.ts@@ -64,6 +64,9 @@ export interface GenerationRequest {enhance?: boolean;/** Prompt+ review: only write the prompt (the job ends with `enhanced_prompt` and no image). */enhance_only?: boolean;+ /** Layers lab "Blend into scene": only read the place the object with this name stands in+ * (the job ends with `scene` and no image). */+ read_scene?: string;/** The user's own words when `prompt` was written by Prompt+ in a review. */enhanced_from?: string | null;/** LoRA ids to use (the app always sends its list; omitted = none, as for MCP). */@@ -194,6 +197,19 @@ export interface LutInfo { name: string; title?: string | null; intensity: numbeexport type JobStatus = "queued" | "starting_backend" | "preparing" | "enhancing_prompt" | "running" | "saving" | "done" | "failed" | "cancelled";export type BackendStage = "preparing" | "encoding_images" | "encoding_prompt" | "generating" | "upscaling" | "refining" | "decoding" | "finishing";+/** What the scene does to a pasted object, read by the Prompt+ model (qls-core scene.rs). */+export interface SceneReading {+ surface: "dry" | "wet" | "water" | "glossy" | "grass" | "soil" | "snow" | "fabric" | "other";+ light: "sun" | "overcast" | "window" | "lamps" | "night";+ hard_shadows: boolean;+ light_from: "left" | "right" | "front" | "behind" | "above";+ shadows_fall: "left" | "right" | "front" | "back" | "under";+ colour: "warm" | "neutral" | "cool";+ object_in: "sun" | "shade" | "both";+ /** Every answer understood; false = some are the defaults. */+ complete: boolean;+}+export interface JobView {id: string;status: JobStatus;@@ -208,6 +224,8 @@ export interface JobView {prompt: string;/** The prompt enhancer's text: growing while "enhancing_prompt", then the prompt in use. */enhanced_prompt?: string | null;+ /** A scene reading's answer (`read_scene`); missing when it failed (see `notes`). */+ scene?: SceneReading;plan: Plan | null;seed: number | null;results: GenerationRecord[];diff --git a/src/styles.css b/src/styles.cssindex 78678d6..7045f13 100644--- a/src/styles.css+++ b/src/styles.css@@ -629,6 +629,7 @@ pre.diag { font-family: ui-monospace, "Cascadia Mono", Consolas, monospace; font.doc-grid .btn { justify-content: center; height: 34px; min-width: 0; white-space: nowrap; }.doc-grid > :only-child { grid-column: 1 / -1; }.editor-tools .pill.doc-cmd { color: var(--text); font-weight: 500; }+.editor-tools .pill.doc-cmd.stale { box-shadow: inset 0 0 0 1.5px var(--okay); }.editor-tools .pill.doc-cmd.primary { background: var(--invert-bg); color: var(--invert-text); }.editor-tools .pill.doc-cmd.primary:hover:not(:disabled) { opacity: 0.88; background: var(--invert-bg); }.editor-tools .pill:disabled { opacity: 0.45; cursor: default; }@@ -1248,4 +1249,19 @@ kbd { min-width: 22px; height: 22px; padding: 0 6px; border-radius: 6px; display.split-card-time { margin-top: auto; padding-top: 8px; font-size: 12px; color: var(--text-3); font-variant-numeric: tabular-nums; }.split-choice-foot { display: flex; align-items: center; justify-content: space-between; gap: 12px; flex-wrap: wrap; margin-top: 6px; color: var(--text-3); font-size: 12.5px; }@media (max-width: 560px) { .split-cards { grid-template-columns: 1fr; } .split-choice { padding: 24px 18px 18px; } }+/* Blend into scene: what the AI read per object, to check (BlendChoice). */+.blend-rows { display: flex; flex-direction: column; gap: 10px; }+.blend-row { display: flex; flex-direction: column; gap: 10px; padding: 14px 16px; border-radius: 16px; background: var(--ground); }+.blend-row-head { display: flex; align-items: baseline; justify-content: space-between; gap: 12px; }+.blend-row-name { font-weight: 600; }+.blend-row-state { display: inline-flex; align-items: center; gap: 6px; font-size: 12px; color: var(--text-3); }+.blend-row-state.warn { color: var(--okay); }+.blend-fields { display: grid; grid-template-columns: 1.2fr 1fr 1.1fr; gap: 10px; }+.blend-fields.waiting { opacity: 0.5; }+.blend-fields label { display: flex; flex-direction: column; gap: 5px; font-size: 12px; color: var(--text-2); }+.blend-fields .select { width: 100%; }+.blend-prompt summary { cursor: pointer; font-size: 12px; color: var(--text-3); }+.blend-prompt p { margin: 6px 0 0; font-size: 12.5px; line-height: 1.45; color: var(--text-2); }+.blend-buttons { display: flex; gap: 8px; }+@media (max-width: 560px) { .blend-fields { grid-template-columns: 1fr; } }@media (prefers-reduced-motion: reduce) { .split-choice, .split-card { animation: none; transition: none; } }