Skip to content

Free, open-source AI video generator for Mac. Run LTX-2.5 and MiniMax H3 (Hailuo) locally on Apple Silicon: text-to-video and image-to-video with sound, lip-sync, character LoRA training, songs from lyrics (YuE2) and image editing (Qwen-Image-Edit). One-click install via Pinokio. Offline: no cloud, no API key, no NVIDIA GPU.

feat(agent): Qwen-Image-Edit-2509 multi-ref + image library tool

mrbizarroff8937b13c95
diff --git a/agent/image_engine.py b/agent/image_engine.py
index b38c508..9a85d1a 100644
--- a/agent/image_engine.py
+++ b/agent/image_engine.py
@@ -118,20 +118,54 @@ ASPECT_DIMS = {
def generate(*, prompt: str, n: int, output_dir: Path,
aspect: str = "16:9",
base_seed: int | None = None,
+ refs: list[str] | None = None,
config: ImageEngineConfig) -> list[dict]:
"""Generate `n` candidate images for one shot. Saves under `output_dir`.
- Returns a list of `{png_path, seed, engine, width, height}` dicts in
- submission order.
+ Args:
+ prompt: text prompt
+ n: number of candidates
+ output_dir: where PNGs land
+ aspect: aspect-ratio key from ASPECT_DIMS
+ base_seed: when given, candidate i uses base_seed + i (reproducible)
+ refs: optional list of reference image paths (1-3 supported by
+ Qwen-Image-Edit-2509 via mflux-generate-qwen-edit). Refs are
+ the way to lock character + place / character + product
+ composition without training a LoRA. The agent's path:
+ user uploads or library-picks 1-3 reference images, the
+ engine composes them per the prompt, the resulting still
+ becomes an LTX keyframe. Backends without multi-ref support
+ (mock, plain qwen, flux1/2, z_image, fibo, BFL) currently
+ ignore refs — they fall back to text-only generation. The
+ caller is responsible for picking a config.kind/family
+ that respects refs (today: qwen_edit). If refs are passed
+ to a non-supporting family, a warning shows in the result
+ dict but the call still succeeds with text-only output.
+ config: backend selection + per-backend params
+
+ Returns a list of `{png_path, seed, engine, width, height, ...}`
+ dicts in submission order.
"""
output_dir = Path(output_dir)
output_dir.mkdir(parents=True, exist_ok=True)
width, height = ASPECT_DIMS.get(aspect, ASPECT_DIMS["16:9"])
+ refs = list(refs or [])
+ # Validate ref paths up-front so we fail fast — Qwen-Edit-2509 supports
+ # 1-3 input images; more than 3 is unsupported by the model.
+ if refs:
+ if len(refs) > 3:
+ raise ValueError(
+ f"refs: Qwen-Image-Edit-2509 supports 1-3 input images, got {len(refs)}"
+ )
+ for r in refs:
+ if not Path(r).is_file():
+ raise FileNotFoundError(f"ref image not found: {r}")
+
if config.kind == "mock":
- return _generate_mock(prompt, n, width, height, output_dir, base_seed)
+ return _generate_mock(prompt, n, width, height, output_dir, base_seed, refs=refs)
if config.kind == "mflux":
- return _generate_mflux(prompt, n, width, height, output_dir, base_seed, config)
+ return _generate_mflux(prompt, n, width, height, output_dir, base_seed, config, refs=refs)
if config.kind == "bfl":
return _generate_bfl(prompt, n, width, height, output_dir, base_seed, config)
raise ValueError(f"unknown image engine kind: {config.kind!r}")
@@ -170,6 +204,12 @@ MFLUX_FAMILY_BIN = {
"z_image_turbo": "mflux-generate-z-image-turbo",
"fibo": "mflux-generate-fibo",
"qwen": "mflux-generate-qwen",
+ # Qwen-Image-Edit-2509 (multi-reference, 1-3 input images via --image-paths).
+ # Apache 2.0. Default model: Qwen/Qwen-Image-Edit-2509.
+ # Trained for "person + person", "person + product", "person + scene"
+ # combinations — exactly the place + character composition the agent
+ # needs for keyframe stills. mflux 0.11.1+.
+ "qwen_edit": "mflux-generate-qwen-edit",
"kontext": "mflux-generate-kontext",
}
@@ -185,6 +225,11 @@ MFLUX_FAMILY_DEFAULTS = {
"z_image_turbo": {"steps": 9, "guidance": 0.0, "base_model": ""},
"fibo": {"steps": 30, "guidance": 5.0, "base_model": ""},
"qwen": {"steps": 30, "guidance": 5.0, "base_model": ""},
+ # qwen_edit defaults match the Qwen team's recommended 40 steps + true_cfg
+ # at guidance 4.0 from the model card. 30/4.0 trades ~25% wall-time for
+ # only marginally lower quality on 1-3 ref jobs and is a better default
+ # for the agent's iterate-fast loop. Bump steps to 40 for final keyframes.
+ "qwen_edit": {"steps": 30, "guidance": 4.0, "base_model": ""},
"kontext": {"steps": 30, "guidance": 4.5, "base_model": ""},
}
@@ -216,6 +261,10 @@ def _infer_mflux_family(model: str) -> str:
return "kontext"
if "fibo" in s or "briaai/fibo" in s:
return "fibo"
+ # qwen_edit must be matched BEFORE plain qwen — "qwen-image-edit-2509"
+ # contains "qwen" + "image" so the plain qwen branch would steal it.
+ if "qwen" in s and ("image-edit" in s or "image_edit" in s or "qwen-edit" in s):
+ return "qwen_edit"
if "qwen" in s and "image" in s:
return "qwen"
# Default: flux1 (krea-dev / dev / schnell, plus filipstrand/FLUX.1-*)
@@ -271,7 +320,8 @@ def _resolve_mflux_bin(config: ImageEngineConfig) -> str | None:
# ---- Backends ---------------------------------------------------------------
def _generate_mock(prompt: str, n: int, width: int, height: int,
- output_dir: Path, base_seed: int | None) -> list[dict]:
+ output_dir: Path, base_seed: int | None,
+ refs: list[str] | None = None) -> list[dict]:
"""Draw `n` distinguishable colored PNGs locally. Each carries a label
with the candidate index + first ~60 chars of the prompt so the user
can verify the UX flow without confusing identical images.
@@ -343,7 +393,8 @@ def _generate_mock(prompt: str, n: int, width: int, height: int,
def _generate_mflux(prompt: str, n: int, width: int, height: int,
output_dir: Path, base_seed: int | None,
- config: ImageEngineConfig) -> list[dict]:
+ config: ImageEngineConfig,
+ refs: list[str] | None = None) -> list[dict]:
"""Subprocess the right `mflux-generate-*` binary once per candidate.
Family is inferred from `config.mflux_model` (or taken from
@@ -415,6 +466,15 @@ def _generate_mflux(prompt: str, n: int, width: int, height: int,
]
if seed is not None:
cmd.extend(["--seed", str(seed)])
+ # Multi-reference input — only the qwen_edit family consumes
+ # --image-paths today (mflux v0.11.1+). For other families we
+ # silently drop refs but tag the result so the caller can detect
+ # the no-op. This lets the agent pass refs unconditionally and
+ # the engine choice decides whether they're honored.
+ refs_used: list[str] = []
+ if refs and fam == "qwen_edit":
+ refs_used = [str(Path(r).resolve()) for r in refs]
+ cmd.extend(["--image-paths", *refs_used])
# When `--model` is a HuggingFace id or local path (contains a
# slash or starts with `~` or `/`), mflux needs `--base-model`
# to know which architecture to instantiate. Fall through to
@@ -464,6 +524,8 @@ def _generate_mflux(prompt: str, n: int, width: int, height: int,
"family": fam,
"model": config.mflux_model,
"width": width, "height": height,
+ "refs": refs_used,
+ "refs_ignored": (bool(refs) and fam != "qwen_edit"),
})
return results
diff --git a/agent/prompts.py b/agent/prompts.py
index 261f670..53e1e3e 100644
--- a/agent/prompts.py
+++ b/agent/prompts.py
@@ -366,49 +366,103 @@ target width × height.
(~16 min/+3s on Comfortable) and audio chains poorly across
extensions. Use only when explicitly asked.
-# Character lock via LoRA
+# Character lock via Qwen-Image-Edit-2509 references
The cleanest fix for "same prompt, different seed = different person"
-is a character-identity LoRA applied to **every shot** in the scene.
-The agent owns this lock across the whole session.
+is to **anchor identity at the still stage** by composing the
+character into every shot's keyframe via Qwen-Image-Edit-2509. No
+training step, no LoRA file — just 1-3 reference images per shot.
+
+The image engine's `qwen_edit` family wraps `mflux-generate-qwen-edit`
+(Apache 2.0, runs natively on Apple Silicon). Trained for "person +
+person", "person + place", "person + product" composition — exactly
+the agent's use case.
Workflow:
-1. **Discover what's installed.** First mention of a recurring named
- character → call `list_loras()`. If the user has a character LoRA
- for someone matching the description (named character, recognizable
- trigger words), suggest it. Don't try to install LoRAs — that
- requires the user (Settings → LoRAs → Browse).
-2. **Lock it in project notes.** When the user agrees to use a LoRA
- for a character, write the lock to durable memory:
+1. **Get one good reference image of the character.** Either the user
+ uploads a photo (it lands in `panel_uploads/`), or you ran
+ `generate_shot_images` for shot S1 and the user picked a candidate
+ (you can find that pick later via `list_library_images` filtered
+ by `shot_label`).
+2. **Lock the character ref in project notes.** First time the
+ character appears, write the path to durable memory:
+ ```
+ append_project_notes(content="Character ref — Emma: /abs/path/to/emma_S1_pick.png")
+ ```
+ Read project notes at session start to recover the lock across
+ panel restarts and tab reloads.
+3. **Pass the ref on every shot generation.** When generating new
+ anchor stills, include the locked ref:
```
- append_project_notes(content="Character LoRA — Emma: emma_v2.safetensors @ 0.85")
+ generate_shot_images(
+ shot_label="S2",
+ prompt="Emma sits at a kitchen table, soft morning light",
+ refs=["/abs/path/to/emma_S1_pick.png"],
+ n=4,
+ )
```
- Read project notes at the start of every session (or on every shot
- for paranoia) to recover the lock across helper restarts and tab
- reloads.
-3. **Apply on every render.** Pass the same LoRA on every
- `submit_shot` for that character:
+ The model composes Emma's identity into the new prompt + setting.
+ The candidates you get back have the same character at different
+ moments / framings.
+4. **Multi-character or character + place:** pass both refs (max 3):
```
- "loras": [{{"name": "emma_v2.safetensors", "strength": 0.85}}]
+ refs=["/abs/path/emma.png", "/abs/path/marcus.png", "/abs/path/kitchen.png"]
```
- AND on every `generate_shot_images` call where Emma is in frame
- (when the image engine supports it; today only some backends do —
- if not supported, the still is still useful as composition input
- but identity will lean on the video LoRA at render time).
-
-Two characters in one scene: pass BOTH LoRAs in the `loras` array,
-each at its own strength. Caveat — LoRA stacking quality drops above
-~2 stacked, and trigger-word collisions can blend identities. Surface
-the risk when the user asks for >2 character LoRAs at once.
-
-Strength tuning:
-- 0.85-1.0 — identity is locked, style of LoRA leaks slightly into
- costume / lighting. Default for character ID LoRAs.
-- 0.6-0.8 — identity present but model has more freedom on costume /
- framing. Good when the LoRA was trained on a narrow setting.
-- 0.5 or below — visible influence but easily overridden by the prompt.
- Mostly useful for style LoRAs, not identity.
+ Qwen-Edit-2509 will compose all three. Order doesn't strictly
+ matter but the prompt should mention each by descriptor matching
+ the ref order roughly ("a young woman, a man in his fifties, in a
+ sunlit kitchen") so the model knows which ref is which.
+5. **The video render does NOT need refs** — by the time you call
+ `submit_shot`, the locked character is already baked into the
+ keyframe still. Use `mode: "i2v"` with the chosen still as
+ `ref_image_path`, OR `mode: "keyframe"` with multiple stills (each
+ already character-locked) for cross-shot continuity.
+
+The image-engine's family must be `qwen_edit` for refs to take effect.
+Other families (flux1, flux2, z_image, fibo) silently drop refs and
+the candidate dict's `refs_ignored: true` flags the no-op.
+
+# Library workflow
+
+Every still the engine produces — agent-side via `generate_shot_images`
+and manually via the panel's Image tab — lives in the panel's image
+library. **`list_library_images()`** is your read access.
+
+Common uses:
+
+- **Find a previously-picked anchor.** "Use the Emma still we picked
+ earlier in S1" → `list_library_images(shot_label="S1", session_id="current")`
+ returns the candidate paths; pick the one with the user's selection.
+- **Find user-prepared refs.** The user might generate a few character
+ stills manually before starting the agent flow ("here's a few looks
+ for Emma, pick what works"). Those stills land in
+ `panel_uploads/library/manual/`. `list_library_images(include_agent=false, contains="Emma")`
+ surfaces them.
+- **Reuse a great still across sessions.** If the user wants to
+ "make another scene with the same character from yesterday's
+ project," `list_library_images(contains="emma", limit=8)` finds the
+ candidates with sidecar metadata so you can pass the picked path
+ as a `ref` on new shots.
+
+Library entries carry full metadata (prompt, refs used, engine,
+seed, dimensions, generated_at, session_id, shot_label) so you can
+match the user's intent precisely without guessing.
+
+# When LoRAs DO help (vs character-via-Qwen-refs)
+
+LoRAs are still the right tool for **style** and for trained
+character looks the user installed via the CivitAI browser. Pass
+them via the `loras` arg of `submit_shot`. Examples:
+
+- Style LoRAs (noir, sketch, painterly, anime): apply on every shot
+ for a coherent look.
+- Pre-trained character LoRAs (e.g., a CivitAI face LoRA the user
+ prefers over a Qwen-Edit ref): same submit_shot loras shape.
+
+For one-off characters, multi-character scenes, or place + character
+composition where no LoRA exists — **the Qwen-Edit references path is
+faster, more flexible, and requires no training**.
# Writing prompts FOR ANCHOR STILLS (Phase B)
diff --git a/agent/tools.py b/agent/tools.py
index 119591f..a8577c3 100644
--- a/agent/tools.py
+++ b/agent/tools.py
@@ -776,6 +776,18 @@ def _generate_shot_images(args: dict, ops: PanelOps, session: dict) -> dict:
says "give me 4 more variations of S3" — the
previous candidates stay clickable and the new
take stacks below.
+ refs: list[str] = [] — 1-3 absolute paths to reference images. Only
+ honored when the configured image engine is
+ Qwen-Image-Edit-2509 (mflux family `qwen_edit`).
+ With refs, the model COMPOSES the prompt onto
+ the references — character + place / character +
+ character / character + product. This is the
+ primary path for cross-shot character continuity:
+ pass the same character ref on every shot and
+ the identity is locked at the still stage. For
+ other engines, refs are silently dropped and
+ the candidate dict's `refs_ignored: true` flags
+ the no-op.
Returns: {shot_label, prompt, candidates: [{png_path, seed, ...}, ...],
takes: [{candidates, generated_at, prompt}, ...],
@@ -798,6 +810,26 @@ def _generate_shot_images(args: dict, ops: PanelOps, session: dict) -> dict:
seed_base = int(args.get("seed_base", -1))
append = bool(args.get("append", False))
+ # Reference images for multi-ref engines (Qwen-Image-Edit-2509). Each
+ # ref is resolved relative to ops.uploads_dir if not absolute, then
+ # validated. Engines that don't support refs ignore them; the result
+ # dict carries refs_ignored=True in that case.
+ refs_in = args.get("refs") or []
+ if not isinstance(refs_in, list):
+ raise _ToolValidationError("refs must be a list of image paths")
+ if len(refs_in) > 3:
+ raise _ToolValidationError(
+ f"refs supports at most 3 images (Qwen-Image-Edit-2509 limit), got {len(refs_in)}"
+ )
+ refs_resolved: list[str] = []
+ for r in refs_in:
+ if not isinstance(r, str) or not r.strip():
+ raise _ToolValidationError("each ref must be a non-empty string path")
+ rp = _resolve_path(r, ops.uploads_dir)
+ if not Path(rp).is_file():
+ raise _ToolValidationError(f"ref image not found: {rp}")
+ refs_resolved.append(rp)
+
# Image engine config travels in PanelOps.capabilities so tools.py
# stays free of panel imports.
cfg_dict = (ops.capabilities or {}).get("image_engine_config") or {}
@@ -835,10 +867,48 @@ def _generate_shot_images(args: dict, ops: PanelOps, session: dict) -> dict:
prompt=prompt, n=n, aspect=aspect,
output_dir=out_dir,
base_seed=(seed_base if seed_base >= 0 else None),
+ refs=refs_resolved or None,
config=cfg,
)
elapsed = round(time.time() - t0, 2)
+ # Write a sidecar JSON next to each candidate so the library reader
+ # (list_library_images) and the panel can recover full metadata
+ # without re-deriving from path. Idempotent — overwrites if the
+ # candidate is regenerated. Failure to write a sidecar isn't fatal:
+ # the agent still gets the candidates list back, list_library_images
+ # falls back to path inference for any sidecar-less PNG.
+ generated_at = time.time()
+ for c in candidates:
+ png = c.get("png_path")
+ if not png:
+ continue
+ sidecar_path = Path(png).with_suffix(Path(png).suffix + ".json")
+ sidecar = {
+ "schema": "phosphene/library/image@1",
+ "png_path": png,
+ "prompt": prompt,
+ "refs": list(refs_resolved),
+ "engine": c.get("engine"),
+ "family": c.get("family"),
+ "model": c.get("model"),
+ "seed": c.get("seed"),
+ "width": c.get("width"),
+ "height": c.get("height"),
+ "aspect": aspect,
+ "session_id": sid,
+ "shot_label": label,
+ "take_index": take_index,
+ "generated_at": generated_at,
+ "refs_ignored": c.get("refs_ignored", False),
+ "source": "agent.generate_shot_images",
+ }
+ try:
+ sidecar_path.write_text(json.dumps(sidecar, indent=2), encoding="utf-8")
+ except OSError:
+ # Sidecar is best-effort; library reader has a fallback.
+ pass
+
new_take = {
"candidates": candidates,
"prompt": prompt,
@@ -1213,6 +1283,154 @@ def _list_loras(args: dict, ops: PanelOps, session: dict) -> dict:
return {"count": len(out), "loras": out}
+@tool("list_library_images")
+def _list_library_images(args: dict, ops: PanelOps, session: dict) -> dict:
+ """List images previously generated by this Phosphene panel.
+
+ The library is the union of:
+ - Agent-generated stills under `panel_uploads/agentflow/<session>/<label>/[take_NN]/cand_*.png`
+ - Manually-generated stills under `panel_uploads/library/manual/*.png`
+ (produced from the panel's Image tab)
+
+ Each image's metadata comes from a sidecar `<png>.json` (written by
+ `generate_shot_images`). For older PNGs without sidecars, metadata
+ is reconstructed from the file path + mtime.
+
+ USE THIS for cross-shot character continuity:
+ 1. User uploaded photos of a character to anchor on
+ 2. Earlier this session you ran `generate_shot_images` for shot S1
+ and the user picked a candidate
+ 3. For shot S2, instead of regenerating from scratch, find the
+ picked candidate via list_library_images and pass it as a `ref`
+ to generate_shot_images for S2 (Qwen-Image-Edit-2509 will
+ compose the same character into the new prompt).
+
+ USE THIS to find references the user prepared earlier:
+ The user can manually generate stills via the panel's Image tab
+ and they all land in the library. Surfacing those stills via
+ list_library_images means the agent can use them on shots without
+ the user having to re-explain the character/place each time.
+
+ Args:
+ limit: int = 24 — max items to return (1-200), newest first
+ since: float = 0 — unix timestamp filter; only return images with
+ generated_at > since. Use 0 for "all time".
+ contains: str = None — case-insensitive substring filter on prompt
+ session_id: str = None — restrict to one agent session id; pass
+ the active session_id ('current') to filter
+ to the in-flight session
+ shot_label: str = None — restrict to one shot label
+ include_manual: bool = True — include manually-generated stills
+ include_agent: bool = True — include agent-generated stills
+
+ Returns: {
+ count, total_scanned, images: [{
+ png_path, prompt, refs, engine, family, model, seed,
+ width, height, aspect, session_id, shot_label, take_index,
+ generated_at, source ("agent.generate_shot_images"|"panel.image_tab"|"unknown")
+ }, ...]
+ }
+ Newest first by `generated_at` (or file mtime fallback).
+ """
+ limit = max(1, min(200, int(args.get("limit", 24))))
+ since = float(args.get("since") or 0)
+ contains = args.get("contains")
+ contains_norm = (contains or "").strip().lower()
+ sid_filter = args.get("session_id")
+ if sid_filter == "current":
+ sid_filter = session.get("session_id")
+ label_filter = args.get("shot_label")
+ include_manual = bool(args.get("include_manual", True))
+ include_agent = bool(args.get("include_agent", True))
+
+ roots: list[Path] = []
+ if include_agent:
+ roots.append(ops.uploads_dir / "agentflow")
+ if include_manual:
+ roots.append(ops.uploads_dir / "library" / "manual")
+
+ items: list[dict] = []
+ total_scanned = 0
+ for root in roots:
+ if not root.exists():
+ continue
+ # Walk for *.png. Limit recursion to a sane depth (4 levels —
+ # agentflow/<sid>/<label>/take_NN/cand.png is depth 4).
+ for png in root.rglob("*.png"):
+ total_scanned += 1
+ sidecar = png.with_suffix(png.suffix + ".json")
+ meta: dict = {}
+ if sidecar.is_file():
+ try:
+ meta = json.loads(sidecar.read_text(encoding="utf-8"))
+ except (OSError, json.JSONDecodeError):
+ meta = {}
+ # Backfill missing fields from path / stat for sidecar-less PNGs.
+ if "png_path" not in meta:
+ meta["png_path"] = str(png)
+ if "generated_at" not in meta:
+ try:
+ meta["generated_at"] = png.stat().st_mtime
+ except OSError:
+ meta["generated_at"] = 0
+ if "source" not in meta:
+ meta["source"] = (
+ "agent.generate_shot_images" if "agentflow" in png.parts
+ else "panel.image_tab" if "library" in png.parts
+ else "unknown"
+ )
+ # Path-based shot_label / session_id fallback for old PNGs:
+ # panel_uploads/agentflow/<sid>/<label>/[take_NN/]cand_*.png
+ if "session_id" not in meta and "agentflow" in png.parts:
+ try:
+ i = png.parts.index("agentflow")
+ if i + 1 < len(png.parts):
+ meta["session_id"] = png.parts[i + 1]
+ if i + 2 < len(png.parts):
+ meta["shot_label"] = png.parts[i + 2]
+ except (ValueError, IndexError):
+ pass
+
+ # Filters
+ if since and meta.get("generated_at", 0) <= since:
+ continue
+ if contains_norm:
+ p = (meta.get("prompt") or "").lower()
+ if contains_norm not in p:
+ continue
+ if sid_filter and meta.get("session_id") != sid_filter:
+ continue
+ if label_filter and meta.get("shot_label") != label_filter:
+ continue
+
+ items.append(meta)
+
+ items.sort(key=lambda m: m.get("generated_at", 0), reverse=True)
+ items = items[:limit]
+ # Slim each entry to the fields the agent actually consumes; drops
+ # noise like the full sidecar schema string.
+ out = []
+ for m in items:
+ out.append({
+ "png_path": m.get("png_path"),
+ "prompt": m.get("prompt"),
+ "refs": m.get("refs") or [],
+ "engine": m.get("engine"),
+ "family": m.get("family"),
+ "model": m.get("model"),
+ "seed": m.get("seed"),
+ "width": m.get("width"),
+ "height": m.get("height"),
+ "aspect": m.get("aspect"),
+ "session_id": m.get("session_id"),
+ "shot_label": m.get("shot_label"),
+ "take_index": m.get("take_index"),
+ "generated_at": m.get("generated_at"),
+ "source": m.get("source"),
+ })
+ return {"count": len(out), "total_scanned": total_scanned, "images": out}
+
+
@tool("read_project_notes")
def _read_project_notes(args: dict, ops: PanelOps, session: dict) -> dict:
"""Read the full project-notes file.