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.

release(v4.19.10): Better memory use on smaller Macs

mrbizarro39e3ec82ee3d
diff --git a/README.md b/README.md
index 39cbe7f..08ae4ad 100644
--- a/README.md
+++ b/README.md
@@ -10,7 +10,7 @@ AI video with sound, songs and images, made locally on your Mac.
[Website](https://phosphene.video) · [Docs](https://phosphene.video/docs/) · [Benchmarks](https://phosphene.video/benchmarks/) · [Changelog](https://phosphene.video/changelog/) · [@PhospheneAI](https://x.com/PhospheneAI)
-**Current release: v4.19.9.** See what's new in the [changelog](https://phosphene.video/changelog/).
+**Current release: v4.19.10.** See what's new in the [changelog](https://phosphene.video/changelog/).
Phosphene is a free, open-source app for Apple Silicon Macs, built on Apple's MLX by Mr Bizarro.
Renders run offline, and your prompts, pictures and videos stay on your Mac.
diff --git a/VERSION b/VERSION
index 8e95eb8..bf323df 100644
--- a/VERSION
+++ b/VERSION
@@ -1 +1 @@
-4.19.9
+4.19.10
diff --git a/docs/API.md b/docs/API.md
index 09bc4d8..7596362 100644
--- a/docs/API.md
+++ b/docs/API.md
@@ -272,6 +272,8 @@ Returns the full panel state.
Field semantics:
- `deferred_downloads` (4.20) — `{ active, state, key, message, pending: [{key, name, size_gb, left_gb}], left_gb, finished }`. The packs a fresh install queued for after Start (`state/install_deferred.json`, written by install.js; `required_files.json -> install.after_start`). `state` is `idle`, `starting`, `downloading`, `waiting` (another download holds the slot), `waiting_disk` (the panel keeps `install.background_floor_gb` free; `message` says how much to free), `retry_wait`, `failed` or `done`. Empty and `idle` on any install install.js never queued — an updated install downloads nothing. `download` carries `background: true` while the fetcher holds the slot.
- `current` — the job actively running (`null` when idle).
+- `gpu` (4.19.10) — `{ busy, holder, since, outside_queue }`: the panel's one GPU gate. `holder` is `"queue"` for the job in `current`, or what holds the GPU outside the queue: `"image"` (an Image Studio render), `"character_sheet"`, `"enhance"` (Prompt Enhance), `"lyrics"`, `"update"` (the post-update script). A client that must not interrupt work (stopping or updating the panel) waits for `current` to be `null`, the queue to be paused or empty, AND `gpu.busy` to be `false`.
+- `app_models` (Mac app only) — the app's own model download: `{ state, packs, active, locked, done_bytes, total_bytes }`. `locked` (4.19.10) is true while the app holds its download lock (`<Phosphene home>/.locks/models.lock`); the panel then offers no Download for those packs and refuses one with 409 `app_downloading`. A second `scripts/fetch_pack_release.py` on a pack folder that is already being written stops untouched with exit code 75.
- `queue` — jobs waiting, FIFO order.
- `history` — completed/failed jobs. Each entry has `status`, `elapsed_sec`, `output_path`, `raw_path` (native pre-upscale), `error`.
- `log` — rolling buffer of helper stdout lines (last ~50 jobs).
diff --git a/hostinfo.py b/hostinfo.py
index 9ffb735..3206751 100644
--- a/hostinfo.py
+++ b/hostinfo.py
@@ -94,6 +94,39 @@ def memory_usage() -> dict:
return info
+def available_bytes() -> int:
+ """Memory a new process can have without the system running out, in bytes;
+ 0 when unreadable.
+
+ macOS: the kernel's own answer, kern.memorystatus_level (the percentage
+ of memory available - what memory_pressure prints as "System-wide memory
+ free percentage" and what jetsam decides on). It counts the file cache
+ and purgeable memory the kernel hands back on demand, which the "used"
+ ratio in memory_usage() counts as taken: a 16 GB Mac with a browser open
+ reads ~4 GB "free" by that ratio while the kernel says ~9 GB is available.
+ Fallback: free + inactive + speculative + purgeable pages. Linux:
+ MemAvailable."""
+ total = total_ram_bytes()
+ if IS_MAC:
+ lvl = _sysctl("kern.memorystatus_level")
+ if lvl.isdigit() and total:
+ return total * min(100, int(lvl)) // 100
+ try:
+ vm = subprocess.run(["vm_stat"], capture_output=True, text=True, errors="replace", timeout=1).stdout
+ m = re.search(r"page size of (\d+)", vm)
+ page = int(m.group(1)) if m else 16384
+
+ def pages(name: str) -> int:
+ mm = re.search(rf"{re.escape(name)}:\s+(\d+)", vm)
+ return int(mm.group(1)) if mm else 0
+
+ return (pages("Pages free") + pages("Pages inactive") + pages("Pages speculative")
+ + pages("Pages purgeable")) * page
+ except Exception: # noqa: BLE001
+ return 0
+ return int(_meminfo().get("MemAvailable", 0))
+
+
def pressure_level() -> int:
"""macOS memorystatus scale: 1 normal, 2 warning, 3 critical.
diff --git a/mlx_ltx_panel.py b/mlx_ltx_panel.py
index 0f9e91e..131e907 100644
--- a/mlx_ltx_panel.py
+++ b/mlx_ltx_panel.py
@@ -881,6 +881,33 @@ HELPER_LOW_MEMORY = os.environ.get("LTX_HELPER_LOW_MEMORY", "true")
# `LTX_LOW_RAM_STREAM=1|0` in the environment forces it either way (testing
# on a big Mac, or opting out); otherwise it is decided by physical RAM.
LOW_RAM_STREAM_RAM_GB = 24
+# 4.19.10: the LTX video-decode memory budget follows the Mac's memory. The
+# engine tiles the VAE decode over time once its estimate of ONE activation
+# (the block-3 bf16 tensor) passes LTX2_VAE_DECODE_BUDGET_GB, and that was
+# 8 GB on every Mac. Measured on this Mac (MLX GPU, a 16 GB Mac's ceiling,
+# LTX-2.5 decoder, 768x416 x 481 frames): the real decode peak is ~14x that
+# estimate - 16.97 GiB untiled at budget 8 or 3 (no tiling at all), 11.29 at
+# 0.5, 7.78 at 0.25. So a budget only means something on a small Mac when it
+# is a fraction of a GB: vae_decode_budget_gb() gives Macs of 32 GB or less
+# 0.022 x RAM (16 GB -> 0.35, 24 -> 0.53, 32 -> 0.7; floor 0.125), which tiles
+# long clips (a 20 s clip on 16 GB: ~9 GiB instead of ~17) and leaves a 5 s
+# Quick or Balanced clip in one piece, exactly as before (estimate 0.27-0.33).
+# Macs over 32 GB keep the engine's 8 GB. A value in the environment wins.
+VAE_DECODE_BUDGET_MAX_GB = 8.0
+VAE_DECODE_BUDGET_MIN_GB = 0.125
+VAE_DECODE_BUDGET_RAM_FRACTION = 0.022
+VAE_DECODE_BUDGET_SMALL_MAC_GB = 32.5
+
+
+def vae_decode_budget_gb(ram_gb: float | None = None) -> float:
+ """LTX2_VAE_DECODE_BUDGET_GB for this Mac (see the block above)."""
+ try:
+ ram = float(SYSTEM_RAM_GB if ram_gb is None else ram_gb)
+ except (TypeError, ValueError, NameError):
+ ram = 0.0
+ if ram <= 0 or ram > VAE_DECODE_BUDGET_SMALL_MAC_GB:
+ return VAE_DECODE_BUDGET_MAX_GB
+ return round(max(VAE_DECODE_BUDGET_MIN_GB, ram * VAE_DECODE_BUDGET_RAM_FRACTION), 3)
# Enhance is an interactive HTTP request, unlike renders that may legitimately
# run for tens of minutes. Bound its helper wait below the UI/curl client's
# 120-second ceiling so a silent helper still produces a JSON error response.
@@ -1845,6 +1872,8 @@ def _validate_settings_patch(patch: dict) -> tuple[dict, str | None]:
else:
out["first_run_card_dismissed"] = str(v).strip().lower() in ("1", "true", "yes", "on")
+ if "spicy_mode" in patch and _dist.is_mac_app():
+ patch = {k: v for k, v in patch.items() if k != "spicy_mode"} # no Spicy mode in the Mac app
if "spicy_mode" in patch:
# Same urlencoded-bool coercion as models_card_dismissed.
v = patch["spicy_mode"]
@@ -2021,7 +2050,7 @@ def get_settings_public() -> dict:
"has_hf_token": bool(s.get("hf_token", "").strip()),
"models_card_dismissed": bool(s.get("models_card_dismissed", False)),
"first_run_card_dismissed": bool(s.get("first_run_card_dismissed", False)),
- "spicy_mode": bool(s.get("spicy_mode", False)),
+ "spicy_mode": bool(s.get("spicy_mode", False)) and not _dist.is_mac_app(),
"live_preview": str(s.get("live_preview", "on")),
"notify_done": bool(s.get("notify_done", True)),
"room_tone_auto": bool(s.get("room_tone_auto", True)),
@@ -5663,20 +5692,126 @@ APP_MODELS_ACTIVE = ("downloading", "paused")
#: A "downloading" file this much older than its last rewrite is a crashed
#: app, not a download: the panel's own buttons come back.
APP_MODELS_STALE_SEC = 120
+#: Exit code of scripts/fetch_pack_release.py when another fetcher holds the
+#: pack folder (its one-writer flock; EXIT_BUSY there).
+PACK_FETCH_BUSY_RC = 75
+#: The Mac app's model-download lock (bootstrap.sh `lock_acquire models`): a
+#: directory under <Phosphene home>/.locks holding the owner's PID.
+APP_MODELS_LOCK = Path(".locks") / "models.lock"
+
+
+def _app_home() -> Path:
+ """The Mac app's Phosphene home. The app puts LTX_STATE_DIR at
+ <home>/state; PHOSPHENE_HOME, when set, says it outright."""
+ explicit = (os.environ.get("PHOSPHENE_HOME") or "").strip()
+ return Path(explicit) if explicit else STATE_DIR.parent
+
+
+def app_models_lock_owner() -> int | None:
+ """PID of the live process holding the Mac app's model-download lock, or
+ None (no lock, unreadable, or its owner is gone - a stale lock the app
+ reaps itself). Mac app review #7: the studio respects this lock even when
+ app_models.json is missing or stale, because the lock, not the progress
+ file, is what says a download is writing right now."""
+ try:
+ pid = int((_app_home() / APP_MODELS_LOCK / "owner").read_text(encoding="utf-8").strip())
+ except (OSError, ValueError):
+ return None
+ if pid <= 1 or pid == os.getpid():
+ return None
+ try:
+ os.kill(pid, 0)
+ except ProcessLookupError:
+ return None
+ except PermissionError:
+ pass # alive, someone else's: still a holder
+ except OSError:
+ return None
+ # A PID the OS reused for something else is not the app's downloader: the
+ # owner must still be the app's setup script (its own lock_owner_ok rule).
+ return pid if _is_app_bootstrap(pid) else None
+
+
+_APP_OWNER_CACHE: dict[int, tuple[float, bool]] = {}
+
+
+def _is_app_bootstrap(pid: int) -> bool:
+ """Is `pid` running the Mac app's bootstrap.sh? Cached 10 s per PID
+ (/status asks on every poll)."""
+ now = time.time()
+ hit = _APP_OWNER_CACHE.get(pid)
+ if hit and now - hit[0] < 10.0:
+ return hit[1]
+ try:
+ cmd = subprocess.run(["ps", "-o", "command=", "-p", str(int(pid))],
+ capture_output=True, text=True, errors="replace",
+ timeout=2).stdout
+ except (OSError, subprocess.SubprocessError, ValueError):
+ cmd = ""
+ ok = "bootstrap.sh" in cmd
+ if len(_APP_OWNER_CACHE) > 32:
+ _APP_OWNER_CACHE.clear()
+ _APP_OWNER_CACHE[pid] = (now, ok)
+ return ok
+
+
+#: = scripts/fetch_pack_release.py PACK_LOCK_SUFFIX: every writer of a pack
+#: folder (that fetcher in any process, and Remove / Repair here) holds an
+#: exclusive flock on ".<folder>.fetchlock" beside the folder's real path.
+PACK_LOCK_SUFFIX = ".fetchlock"
+
+
+def pack_folder_lock(folder) -> int | None:
+ """Take the one-writer lock for a pack folder without waiting. Returns the
+ descriptor to close when done (-1: nothing to lock), or None when another
+ process is writing that folder right now."""
+ try:
+ import fcntl
+ except ImportError:
+ return -1
+ real = Path(os.path.realpath(str(folder)))
+ if not real.parent.is_dir():
+ return -1
+ try:
+ fd = os.open(str(real.parent / f".{real.name}{PACK_LOCK_SUFFIX}"),
+ os.O_RDWR | os.O_CREAT, 0o644)
+ except OSError:
+ return -1
+ try:
+ fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
+ except OSError:
+ os.close(fd)
+ return None
+ return fd
+
+
+def pack_folder_unlock(fds) -> None:
+ for fd in fds or ():
+ if fd is not None and fd >= 0:
+ try:
+ os.close(fd)
+ except OSError:
+ pass
def app_models_state() -> dict | None:
"""The app's download state, mac-app only; None when there is none."""
if not _dist.is_mac_app():
return None
+ lock_pid = app_models_lock_owner()
path = STATE_DIR / APP_MODELS_FILE
try:
raw = json.loads(path.read_text(encoding="utf-8"))
age = time.time() - path.stat().st_mtime
except (OSError, ValueError):
- return None
+ raw, age = None, 0.0
if not isinstance(raw, dict):
- return None
+ if lock_pid is None:
+ return None
+ # The app holds its download lock but wrote no (readable) progress
+ # file yet: a download is starting. Which packs is unknown, so it
+ # owns every pack until the file says otherwise (app_models_owns).
+ raw = {"state": "downloading"}
state = str(raw.get("state") or "idle")
packs = [str(x) for x in (raw.get("packs") or []) if isinstance(x, str)]
def _n(v):
@@ -5686,7 +5821,13 @@ def app_models_state() -> dict | None:
return 0
active = state in APP_MODELS_ACTIVE and not (
state == "downloading" and age > APP_MODELS_STALE_SEC)
+ if lock_pid is not None and state not in ("done", "failed"):
+ # A live lock holder is downloading whatever its file says - even a
+ # file the app has not rewritten for a while (it rewrites only on
+ # progress) or one that still says "idle" from before this run.
+ active = True
return {"state": state, "packs": packs, "active": active,
+ "locked": lock_pid is not None,
"done_bytes": _n(raw.get("done_bytes")),
"total_bytes": _n(raw.get("total_bytes"))}
@@ -5698,6 +5839,8 @@ def app_models_owns(repo: dict | None, st: dict | None = None) -> bool:
st = st if st is not None else app_models_state()
if not st or not st["active"]:
return False
+ if st.get("locked") and not st["packs"]:
+ return True # lock held, pack list not written yet
return repo_dir(repo).name in st["packs"] or Path(
str(repo.get("local_dir") or "")).name in st["packs"]
@@ -7560,7 +7703,8 @@ def _download_thread(repo: dict) -> str:
max_attempts = 3
backoff_sec = 5
# 4.20: what happened, for the background fetcher: "ok" | "cancelled" |
- # "failed". Thread callers ignore it, as before.
+ # "failed" | "busy" (4.19.10: another fetcher holds the pack folder).
+ # Thread callers ignore it, as before.
outcome = "failed"
try:
for attempt in range(1, max_attempts + 1):
@@ -7612,6 +7756,15 @@ def _download_thread(repo: dict) -> str:
push(f"[{dl_tag}] {dl_label} downloaded successfully.")
outcome = "ok"
break
+ if is_release_mirror and rc == PACK_FETCH_BUSY_RC:
+ # Mac app review #7: another fetcher (the Mac app's own model
+ # download, or a second studio) holds this pack folder. The
+ # fetcher stopped without writing; retrying would only bounce.
+ push(f"[{dl_tag}] {dl_label}: another download is already writing "
+ f"this pack, so this one stopped without touching it. It "
+ f"carries on when that one finishes.")
+ outcome = "busy"
+ break
with DOWNLOAD_LOCK:
cancelled = DOWNLOAD["cancelled"] or not DOWNLOAD["active"]
if cancelled:
@@ -7861,6 +8014,12 @@ def deferred_fetch_step() -> float | None:
_INTEGRITY_CACHE["ts"] = 0.0
push(f"[background] {repo.get('name') or key} is ready.")
return 1.0
+ if outcome == "busy":
+ # Another fetcher (the Mac app) is writing this pack: not a failure,
+ # nothing to back off from - wait for it like any busy slot.
+ _deferred_set(state="waiting", key=key,
+ message="Another download is writing this model; waiting for it.")
+ return DEFERRED_SLOT_WAIT_SEC
if outcome == "cancelled":
install_plan.drop_from_marker(STATE_DIR, key)
push(f"[background] {repo.get('name') or key} skipped - Settings -> Models "
@@ -8027,7 +8186,15 @@ from civitai_client import ( # noqa: F401 (re-exported on purpose)
def spicy_mode_enabled() -> bool:
- """Return the single server-side authorization predicate for NSFW UI/data."""
+ """Return the single server-side authorization predicate for NSFW UI/data.
+
+ Owner ruling 2026-10-22: the installed Mac app (PHOSPHENE_DISTRIBUTION=
+ mac-app, and Pro inside it) has no Spicy mode - always OFF there, whatever
+ panel_settings.json says (a persisted true from a copied Pinokio state is
+ ignored), so its CivitAI browser always runs the spicy-off path (nsfw=false
+ upstream + the flagged-item filter). The Pinokio edition is unchanged."""
+ if _dist.is_mac_app():
+ return False
return bool(get_settings().get("spicy_mode", False))
@@ -21587,6 +21754,10 @@ class WarmHelper:
env["LTX_IDLE_TIMEOUT"] = str(HELPER_IDLE_TIMEOUT)
env["LTX_LOW_MEMORY"] = HELPER_LOW_MEMORY
env["LTX_LOW_RAM_STREAM"] = "1" if low_ram_streaming_enabled() else "0"
+ # 4.19.10: the VAE decode budget follows this Mac's memory (the
+ # engine reads it at decode time). The user's own value wins.
+ if not (os.environ.get("LTX2_VAE_DECODE_BUDGET_GB") or "").strip():
+ env["LTX2_VAE_DECODE_BUDGET_GB"] = f"{vae_decode_budget_gb():g}"
env["LTX_ENABLE_MODEL_UPSCALE"] = "1" if MODEL_UPSCALE_ENABLED else "0"
# Output codec env vars sourced from panel settings. The patched
# ffmpeg call inside ltx_core_mlx reads these at job time, so
@@ -33169,7 +33340,11 @@ _PREFLIGHT_BASE_GB: dict[tuple[str, int], float] = {
("ideogram", 6): 24.0,
("ideogram", 8): 32.0,
# FLUX.2 — distilled 4B and base 4B/9B variants
- ("flux2", 4): 6.0,
+ # 4.19.10, measured: Klein 4B 4-bit at 1024x1024 peaks 11.5 GiB of MLX
+ # memory (mflux --low-ram changes nothing). 8 GB free is the admission
+ # line (what Auto has always been priced at): macOS compresses the rest,
+ # and 16 GB Macs complete these renders (fleet: 86 in 30 days).
+ ("flux2", 4): 8.0,
("flux2", 6): 8.0,
("flux2", 8): 12.0,
("flux2_edit", 4): 6.0, # klein-edit distilled 4B
@@ -33190,6 +33365,65 @@ _PREFLIGHT_BASE_GB: dict[tuple[str, int], float] = {
_PREFLIGHT_9B_GB = 36.0
+def _effective_image_quantize(cfg) -> int:
+ """The bit width mflux will really run at. A pre-quantized model
+ ("...-mflux-4bit") keeps its stored width whatever -q asks (mflux 0.18
+ QuantizationResolution: stored wins a conflict), so the default Klein
+ config, saved as -q 6, runs - and must be priced - at 4 bits."""
+ m = re.search(r"(?<![0-9])([3-8])-?bit", str(getattr(cfg, "mflux_model", "") or "").lower())
+ if m:
+ return int(m.group(1))
+ try:
+ return int(cfg.mflux_quantize or 6)
+ except (TypeError, ValueError):
+ return 6
+
+
+#: 4.19.10: Macs at or under this much memory render the "Auto" image engine
+#: on FLUX.2 [klein] 4B at 4-bit when the saved Auto engine cannot fit them
+#: (16 GB Macs report 16.0).
+LOW_RAM_IMAGE_GB = 16.5
+KLEIN_4B_Q4_MODEL = "Runpod/FLUX.2-klein-4B-mflux-4bit"
+
+
+def low_ram_auto_image_config(cfg, form: dict | None = None):
+ """"Auto" on a 16 GB (or smaller) Mac: FLUX.2 [klein] 4B at 4-bit.
+
+ Fleet (30 days to 2026-10-21): 170 image refusals on 26 installs with
+ 16 GB. Auto is the user's saved Settings engine, and on a small Mac that
+ can be one it can never hold (Reference Edit is 18-24 GB) - the refusal
+ then told them to "pick Auto", the engine it had just refused. Here an
+ Auto engine that does not fit this Mac is replaced, for this render only
+ (the saved setting is untouched), by the 4B Klein at 4 bits (~6 GB).
+ A Klein config already fits and only has its -q set to what it runs at.
+ Reference images need an edit engine Klein is not, so a render WITH
+ references keeps the saved engine and its honest refusal."""
+ if not (0 < float(SYSTEM_RAM_GB or 0) <= LOW_RAM_IMAGE_GB):
+ return cfg
+ if getattr(cfg, "kind", "") not in ("mflux", "hidream"):
+ return cfg # cloud (bfl) / mock: no local memory
+ fam = (agent_image_engine._resolve_mflux_family(cfg)
+ if cfg.kind == "mflux" else "hidream")
+ model = str(getattr(cfg, "mflux_model", "") or "").lower()
+ if fam == "flux2" and "klein" in model and "9b" not in model:
+ if int(cfg.mflux_quantize or 6) != 4:
+ cfg = agent_image_engine.ImageEngineConfig(**{**cfg.__dict__, "mflux_quantize": 4})
+ return cfg
+ if _image_engine_fit(_preflight_estimate_ram_gb(cfg))[0]:
+ return cfg # a small engine the user chose (Z-Image Turbo)
+ if (form or {}).get("refs"):
+ return cfg
+ push(f"[image] Auto on this {SYSTEM_RAM_GB:.0f} GB Mac: FLUX.2 [klein] 4B at 4-bit "
+ f"(the saved Auto engine needs a bigger Mac; Settings keeps it)")
+ return agent_image_engine.ImageEngineConfig(**{
+ **cfg.__dict__, "kind": "mflux", "mflux_model": KLEIN_4B_Q4_MODEL,
+ "mflux_family": "flux2", "mflux_base_model": "", "mflux_quantize": 4,
+ "mflux_steps": 4, "mflux_guidance": 1.0, "mflux_preset": None,
+ "mflux_lora_paths": [], "mflux_lora_scales": [],
+ # A saved CLI override names the OLD family's executable (review).
+ "mflux_python_path": ""})
+
+
def _preflight_estimate_ram_gb(cfg) -> float:
"""Return the best-effort RAM estimate (GB) for the given image cfg.
@@ -33212,8 +33446,11 @@ def _preflight_estimate_ram_gb(cfg) -> float:
if cfg.kind != "mflux":
# `mock` engine doesn't allocate; `bfl` is cloud-side.
return 1.0
- fam = (cfg.mflux_family or "auto").lower()
- q = int(cfg.mflux_quantize or 6)
+ # 4.19.10: the family the engine will actually run. A config saved with
+ # family "auto" (the default Klein config, i.e. what "Auto" renders on
+ # most Macs) matched no row here and fell back to the 8 GB guess.
+ fam = agent_image_engine._resolve_mflux_family(cfg)
+ q = _effective_image_quantize(cfg)
model = (getattr(cfg, "mflux_model", "") or "").lower()
if fam == "flux2" and "9b" in model:
return _PREFLIGHT_9B_GB
@@ -33293,6 +33530,26 @@ def _image_engine_fit(need_gb: float) -> tuple[bool, int]:
return (float(SYSTEM_RAM_GB or 0) >= floor), mac_gb
+def _image_free_gb(mem: dict) -> float:
+ """Memory an image engine can have now, in GB: the kernel's available
+ memory (hostinfo.available_bytes), never less than total - used.
+
+ 4.19.10 - THE WRONG "NOT ENOUGH FREE MEMORY" REFUSAL. This was
+ total - used, where "used" is active + wired + compressed pages. Active
+ pages include the file cache macOS gives back on demand, so an idle
+ 16 GB Mac with a browser open read ~4 GB "free" and was refused an
+ engine that runs fine there (fleet: 170 refusals, 26 installs, 30 days).
+ The kernel's own figure is what jetsam acts on; use it."""
+ total_gb = float(mem.get("total_gb") or 0.0)
+ used_gb = float(mem.get("used_gb") or 0.0)
+ ratio_free = max(0.0, total_gb - used_gb)
+ try:
+ avail = hostinfo.available_bytes() / 1024**3
+ except Exception: # noqa: BLE001
+ avail = 0.0
+ return max(ratio_free, min(avail, total_gb) if total_gb else avail)
+
+
def _preflight_image_job(cfg, *, engine_override: str = "auto") -> None:
"""Raise RuntimeError if the host can't safely run this image cfg.
@@ -33331,7 +33588,7 @@ def _preflight_image_job(cfg, *, engine_override: str = "auto") -> None:
mem = get_memory()
total_gb = float(mem.get("total_gb") or 0.0)
used_gb = float(mem.get("used_gb") or 0.0)
- free_gb = max(0.0, total_gb - used_gb)
+ free_gb = _image_free_gb(mem)
# Two different stories, both REFUSALS (deliberate guards, not faults —
# review 2026-09-02: 15 of the 16 "unclassified" failures on 4.9.0 were
# this branch, on 8 GB and 24 GB Macs that had been offered an engine
@@ -33342,12 +33599,18 @@ def _preflight_image_job(cfg, *, engine_override: str = "auto") -> None:
fits_mac, mac_gb = _image_engine_fit(need_gb)
label = _IMAGE_ENGINE_LABELS.get(engine_override, engine_override)
if not fits_mac:
+ # 4.19.10: "Pick Auto" was the advice even when Auto WAS this engine
+ # (the saved Settings engine). Auto now drops to Klein on a small Mac
+ # unless the render has references - say that instead.
+ way_out = ("Remove the reference images and Auto renders on FLUX.2 "
+ "[klein] 4B, which fits here, or pick a lighter engine in "
+ "Settings." if engine_override == "auto" else
+ "Pick Auto (the 4B FLUX engine, fits here) or a lighter preset.")
raise RenderRefused(
"image_ram",
f"Image pre-flight: {label} holds ~{need_gb:.0f} GB of weights in "
f"memory and needs a {mac_gb} GB Mac; this Mac has "
- f"{total_gb:.0f} GB. Pick Auto (the 4B FLUX engine, fits here) "
- f"or a lighter preset."
+ f"{SYSTEM_RAM_GB:.0f} GB. {way_out}"
)
if free_gb < need_gb and HELPER.is_alive():
# The video helper keeps its pipelines warm between jobs; on a 32 GB
@@ -33364,7 +33627,7 @@ def _preflight_image_job(cfg, *, engine_override: str = "auto") -> None:
mem = get_memory()
total_gb = float(mem.get("total_gb") or total_gb)
used_gb = float(mem.get("used_gb") or used_gb)
- free_gb = max(0.0, total_gb - used_gb)
+ free_gb = _image_free_gb(mem)
push(f"[preflight] {free_gb:.1f} GB free after releasing the helper")
if free_gb < need_gb:
raise RenderRefused(
@@ -40386,9 +40649,11 @@ def _post_update_thread() -> None:
# packages being replaced. Waiting for the gate waits them out; holding
# it refuses new ones ("busy") until the script is done.
_GPU_LOCK.acquire()
+ gpu_gate_mark("update")
try:
_post_update_run()
finally:
+ gpu_gate_unmark()
_GPU_LOCK.release()
@@ -40711,6 +40976,40 @@ _IMG_STUDIO_LOCK = threading.Lock()
# image is fine (the queue just waits); the inline path always releases in a
# finally, so the worker can't deadlock.
_GPU_LOCK = threading.Lock()
+# Mac app review #11: WHO holds _GPU_LOCK, for /status. The queue's job shows
+# in `current`; the users that take the gate OUTSIDE the queue (an inline
+# image render, a character sheet, Prompt Enhance, a lyrics request, the
+# post-update script) did not show anywhere, so the Mac app's update/restart
+# gate read "idle" while one of them was running and could stop it mid-render.
+# Each of them marks the gate right after acquiring it and clears the mark
+# right before releasing it; gpu_gate_status() is what /status reports.
+_GPU_HOLDER: dict = {}
+
+
+def gpu_gate_mark(kind: str) -> None:
+ """Record the out-of-queue holder of _GPU_LOCK (call right after acquire)."""
+ global _GPU_HOLDER
+ _GPU_HOLDER = {"kind": str(kind), "since": time.time()}
+
+
+def gpu_gate_unmark() -> None:
+ """Forget the holder (call right before release)."""
+ global _GPU_HOLDER
+ _GPU_HOLDER = {}
+
+
+def gpu_gate_status() -> dict:
+ """/status `gpu`: is the GPU gate held, by what, since when.
+
+ `busy` is the gate itself, so it is true for a queued job too (with
+ holder "queue"); `outside_queue` is the case `current` cannot show."""
+ busy = _GPU_LOCK.locked()
+ holder = dict(_GPU_HOLDER) if busy else {}
+ with LOCK:
+ queued = STATE.get("current") is not None
+ kind = holder.get("kind") or ("queue" if queued else ("other" if busy else None))
+ return {"busy": bool(busy), "holder": kind, "since": holder.get("since"),
+ "outside_queue": bool(busy and kind != "queue")}
def _video_render_active() -> bool:
@@ -40941,7 +41240,7 @@ def _build_image_engine_config(
engine_override = (engine_override or "auto").lower()
form = form or {}
if engine_override == "auto":
- return _load_agent_image_config()
+ return low_ram_auto_image_config(_load_agent_image_config(), form)
# ===== Ideogram 4 (fp8) — typography & layout, text-in-image ===========
# 9.3B fp8 DiT + an 8B Qwen3-VL text encoder (~28 GB on disk, gated).
# Text-to-image ONLY — NO reference images (mflux's ideogram4 CLI has no
@@ -41312,6 +41611,7 @@ def generate_character_sheet(character_id: str, *,
"the GPU is busy with a render or training job — character "
"sheet generation is paused until it finishes (they'd contend "
"for GPU memory). Try again once it completes.")
+ gpu_gate_mark("character_sheet")
t0 = time.time()
try:
# Preflight inside the gate: RAM/disk numbers measured while another
@@ -41368,6 +41668,7 @@ def generate_character_sheet(character_id: str, *,
"refs_ignored": bool(c.get("refs_ignored", False)),
})
finally:
+ gpu_gate_unmark()
_GPU_LOCK.release()
# Composite + atomic swap. sheet.png is served by URL and (below) named
@@ -45066,6 +45367,31 @@ def _resolve_cap_tier(version_id: str | None = None) -> str:
return quant
+#: index.html marks markup only the Pinokio edition serves (Spicy mode and the
+#: CivitAI browser's "Show NSFW" pill) with these comments; in the Mac app the
+#: page leaves out everything between them (owner ruling 2026-10-22).
+_PINOKIO_ONLY_RX = re.compile(r"<!--pinokio-only-->.*?<!--/pinokio-only-->", re.S)
+_DOC_DIRECTIVE_RX = re.compile(r"^\[\[(/?)(pinokio|mac-app)\]\]$")
+
+
+def _strip_pinokio_only(markup: str) -> str:
+ return _PINOKIO_ONLY_RX.sub("", markup) if _dist.is_mac_app() else markup
+
+
+def drop_pinokio_doc_blocks(md: str) -> str:
+ """A Docs page without its [[pinokio]] ... [[/pinokio]] passages (the line
+ directives webapp/js/docs.js reads); [[mac-app]] blocks stay for the page."""
+ out, skip = [], False
+ for line in md.split("\n"):
+ m = _DOC_DIRECTIVE_RX.match(line.strip())
+ if m and m.group(2) == "pinokio":
+ skip = not m.group(1)
+ continue
+ if not skip:
+ out.append(line)
+ return "\n".join(out)
+
+
def page(theme: str = "") -> str:
"""The served page. `theme` is the palette cookie the browser sent
("light" / "dark" / ""); "light" is stamped on <html> so the first paint
@@ -45189,7 +45515,7 @@ def page(theme: str = "") -> str:
'Its ' + SEQ_NOUN_PL + ' live in ' + html.escape(str(STATE_DIR)) + ', not in this '
'install — nothing you do here touches your own work.">TEST PANEL</span>'
+ profile_badge)
- return (HTML
+ return (_strip_pinokio_only(HTML)
.replace("__SEQCAP__", SEQ_NOUN_CAP)
.replace("__SEQS__", SEQ_NOUN_PL)
.replace("__SEQ__", SEQ_NOUN)
diff --git a/mlx_warm_helper.py b/mlx_warm_helper.py
index 951a39d..15df874 100644
--- a/mlx_warm_helper.py
+++ b/mlx_warm_helper.py
@@ -1338,6 +1338,83 @@ def _install_video_decoder_patch() -> None:
_VIDEO_DECODER_PATCH_INSTALLED = True
+_SPLIT_ENCODE_PATCH_INSTALLED = False
+
+
+def split_prompt_encode_wanted() -> bool:
+ """The low-memory prompt encode: on the streamed (low-RAM) path only.
+ Read at call time, so a helper's lanes and the tests see one answer."""
+ return bool(LOW_RAM_STREAM)
+
+
+def _install_split_prompt_encode_patch() -> None:
+ """4.19.10 - THE LOW-MEMORY PROMPT ENCODE (16 GB Macs).
+
+ The engine's PromptEncoder loads the text model AND the connector, then
+ encodes with both resident. On LTX-2.5 that is Gemma 4 (6.7 GB) plus the
+ connector (5.9 GB) at once - about 13 GiB, the whole render's peak once
+ the DiT streams from disk (the 2026-09-06 streaming measurement: 13.77 GiB
+ "denoise" peak with the DiT at ~0.6 GB was this phase). On a 16 GB Mac
+ that is past what is free, and the fleet's 16 GB memory failures sit in
+ exactly this phase ("encode": watchdog and jetsam, quick and balanced).
+
+ On the streamed path the encode runs in two halves instead: the text
+ model alone produces its hidden states, which are materialized, then the
+ text model is freed and the connector alone turns them into embeddings.
+ Same primitives on the same inputs in the same order, so the embeddings
+ are bit-identical (test + proof); the peak is the larger half, not the
+ sum. A second prompt (CFG lanes) loads the text model again - those lanes
+ are refused below 48 GB anyway. Off the streamed path nothing changes."""
+ global _SPLIT_ENCODE_PATCH_INSTALLED
+ if _SPLIT_ENCODE_PATCH_INSTALLED:
+ return
+ import ltx_pipelines_mlx.utils.blocks as _blocks
+ PE = _blocks.PromptEncoder
+ _orig_load, _orig_encode = PE.load, PE.encode
+
+ def _load_text_model(self):
+ if self._text_encoder is None:
+ self._text_encoder = _blocks.GemmaLanguageModel()
+ self._text_encoder.load(self.gemma_model_id)
+ _blocks.aggressive_cleanup()
+
+ def load(self):
+ if not split_prompt_encode_wanted():
+ return _orig_load(self)
+ # Text model only: the connector loads after it is gone (encode).
+ # Callers that read the tokenizer (Prompt Relay) still find it here.
+ _load_text_model(self)
+
+ def encode(self, prompt):
+ if not split_prompt_encode_wanted():
+ return _orig_encode(self, prompt)
+ import mlx.core as _mx
+ _materialize = getattr(_mx, "eval") # MLX graph evaluation, not Python eval
+ max_length = int(os.environ.get("LTX2_GEMMA_MAX_LENGTH", "1024"))
+ self._feature_extractor = None # never both resident
+ _load_text_model(self)
+ hidden, mask = self._text_encoder.encode_all_layers(prompt, max_length=max_length)
+ _materialize(hidden, mask)
+ self._text_encoder = None
+ _blocks.aggressive_cleanup()
+ fx = _blocks.GemmaFeaturesExtractorV2()
+ weights = _blocks.load_split_safetensors(self.model_dir / "connector.safetensors",
+ prefix="connector.")
+ fx.connector.load_weights(list(weights.items()))
+ del weights
+ _blocks.aggressive_cleanup()
+ self._feature_extractor = fx
+ video, audio = fx(hidden, attention_mask=mask)
+ _materialize(video, audio)
+ del hidden, mask
+ self._feature_extractor = None
+ _blocks.aggressive_cleanup()
+ return video, audio
+
+ PE.load, PE.encode = load, encode
+ _SPLIT_ENCODE_PATCH_INSTALLED = True
+
+
def _install_a2v_frame_rate_patch() -> None:
"""Make ``combined_image_conditionings`` tolerate the missing ``frame_rate``
kwarg that ``a2vid_two_stage.py`` neglects to pass.
@@ -1903,6 +1980,7 @@ def get_pipe(kind: str, loras: list[dict] | None = None,
# Repair the subclass-override-skips-fusion bug before any pipe is built.
_install_lora_fusion_patches()
_install_video_decoder_patch() # fps/frame_rate kwarg shim
+ _install_split_prompt_encode_patch() # 4.19.10 low-RAM encode
_install_a2v_frame_rate_patch() # A2V missing frame_rate= on combined_image_conditionings
fp = _lora_fingerprint(loras)
@@ -2185,6 +2263,7 @@ def get_hq_pipe(model_dir: str, loras: list[dict] | None = None,
# TI2VidTwoStagesHQPipeline.load() would still bypass _pending_loras.
_install_lora_fusion_patches()
_install_video_decoder_patch() # fps/frame_rate kwarg shim
+ _install_split_prompt_encode_patch() # 4.19.10 low-RAM encode
_install_a2v_frame_rate_patch() # A2V missing frame_rate= on combined_image_conditionings
fp = _lora_fingerprint(loras)
@@ -2269,6 +2348,7 @@ def get_kf_pipe(model_dir: str, dev_transformer: str | None = None,
# (reported by @oo2music in #9). The install funcs are all idempotent.
_install_lora_fusion_patches()
_install_video_decoder_patch()
+ _install_split_prompt_encode_patch() # 4.19.10 low-RAM encode
_install_a2v_frame_rate_patch()
dev_name = dev_transformer or "transformer-dev.safetensors"
@@ -2330,6 +2410,7 @@ def get_a2v_pipe(model_dir: str, loras: list[dict] | None = None,
_install_lora_fusion_patches()
_install_video_decoder_patch()
+ _install_split_prompt_encode_patch() # 4.19.10 low-RAM encode
_install_a2v_frame_rate_patch() # A2V missing frame_rate= on combined_image_conditionings
fp = _lora_fingerprint(loras)
@@ -3499,6 +3580,14 @@ for line in sys.__stdin__:
except Exception as _exc: # noqa: BLE001
emit({"event": "log",
"line": f"vae-decode int32 guard NOT installed: {_exc}"})
+ # 4.19.10: the low-memory prompt encode, for every lane (the IC-LoRA
+ # lanes build their pipelines without get_pipe). Inert off the
+ # streamed path.
+ try:
+ _install_split_prompt_encode_patch()
+ except Exception as _exc: # noqa: BLE001
+ emit({"event": "log",
+ "line": f"low-memory prompt encode NOT installed: {_exc}"})
if action == "generate":
job_id = msg.get("id", "?")
diff --git a/panel/routes_files.py b/panel/routes_files.py
index 04d23b7..bae9366 100644
--- a/panel/routes_files.py
+++ b/panel/routes_files.py
@@ -1047,6 +1047,12 @@ def get_webapp_file(h, parsed) -> None:
# registry stays single-source server-side.
body = body.replace(b"__ENGINE_RULES__",
P._engine_css().encode("utf-8"))
+ elif ext == ".md" and P._dist.is_mac_app():
+ # Mac app: a Docs page's [[pinokio]] passages (Spicy mode) never leave
+ # the server (owner ruling 2026-10-22).
+ body = P.drop_pinokio_doc_blocks(body.decode("utf-8", "replace")).encode("utf-8")
+ elif ext == ".html" and P._dist.is_mac_app():
+ body = P._strip_pinokio_only(body.decode("utf-8", "replace")).encode("utf-8")
elif ext in (".js", ".mjs"):
# The editor's user-facing strings carry the __SEQ__ noun
# seams. page() substitutes them in the page; module files
diff --git a/panel/routes_image.py b/panel/routes_image.py
index 88fae9d..f277f86 100644
--- a/panel/routes_image.py
+++ b/panel/routes_image.py
@@ -813,6 +813,7 @@ def post_image_generate(h, path, qs, ctype) -> None:
"image generation is paused until it finishes (they'd "
"contend for GPU memory). Try again once it completes.",
}, 429); return
+ P.gpu_gate_mark("image")
t0 = P.time.time()
try:
try:
@@ -837,6 +838,7 @@ def post_image_generate(h, path, qs, ctype) -> None:
except ValueError as e:
h._json({"error": str(e)}, 400); return
finally:
+ P.gpu_gate_unmark()
P._GPU_LOCK.release()
elapsed = round(P.time.time() - t0, 2)
diff --git a/panel/routes_models.py b/panel/routes_models.py
index a6d1288..3f3d845 100644
--- a/panel/routes_models.py
+++ b/panel/routes_models.py
@@ -138,6 +138,10 @@ def post_models_remove(h, path, qs, ctype) -> None:
if busy_key == key:
h._json({"error": "A download is using that folder — "
"cancel it first."}, 409); return
+ if P.app_models_owns(repo):
+ h._json({"error": "This model is downloading in the background — "
+ "try again when it finishes.",
+ "app_downloading": True}, 409); return
addon_key = P.model_version().get("hq_addon_repo_key")
if key == addon_key:
# The add-on has no directory of its own: delete exactly the
@@ -168,6 +172,31 @@ def post_models_remove(h, path, qs, ctype) -> None:
targets.append(p)
label = repo.get("name") or key
+ # 4.19.10 (review): another process may be WRITING one of these folders
+ # (the Mac app's own download, a second studio). Take each folder's
+ # one-writer lock (scripts/fetch_pack_release.py) before deleting, and
+ # hold it until done, so no fetcher can be mid-write in what goes.
+ locks = []
+ for folder in dict.fromkeys(t if t.is_dir() else t.parent for t in targets):
+ fd = P.pack_folder_lock(folder)
+ if fd is None:
+ P.pack_folder_unlock(locks)
+ h._json({"error": "This model is downloading right now — try again "
+ "when it finishes."}, 409); return
+ locks.append(fd)
+ try:
+ freed = _remove_targets(h, targets)
+ finally:
+ P.pack_folder_unlock(locks)
+ if freed is None:
+ return
+ P.push(f"[storage] removed {label} — {P._fmt_gb(freed)} freed")
+ h._json({"ok": True, "freed": freed, "freed_label": P._fmt_gb(freed),
+ "label": label}); return
+
+
+def _remove_targets(h, targets) -> int | None:
+ """Delete the resolved targets; None after answering a 500."""
freed = 0
for t in targets:
try:
@@ -179,10 +208,8 @@ def post_models_remove(h, path, qs, ctype) -> None:
t.unlink()
except OSError as exc:
P.push(f"[storage] could not remove {t}: {exc}")
- h._json({"error": f"could not remove {t.name}: {exc}"}, 500); return
- P.push(f"[storage] removed {label} — {P._fmt_gb(freed)} freed")
- h._json({"ok": True, "freed": freed, "freed_label": P._fmt_gb(freed),
- "label": label}); return
+ h._json({"error": f"could not remove {t.name}: {exc}"}, 500); return None
+ return freed
@post("/models/cancel")
@@ -274,6 +301,21 @@ def post_models_repair(h, path, qs, ctype) -> None:
P.DOWNLOAD["repo_id"] = repo["repo_id"]
P.DOWNLOAD["started_ts"] = P.time.time()
P.DOWNLOAD["last_line"] = "repairing…"
+ # 4.19.10 (review): never delete files another process is writing (the
+ # Mac app's own download): take the pack folder's one-writer lock for the
+ # deletion, and give the slot back when it is held.
+ target = P.Q8_LOCAL_PATH if key == "q8" else P.repo_dir(repo)
+ locks = []
+ for folder in dict.fromkeys([P.Path(target), P.repo_dir(repo)]):
+ fd = P.pack_folder_lock(folder)
+ if fd is None:
+ P.pack_folder_unlock(locks)
+ with P.DOWNLOAD_LOCK:
+ P.DOWNLOAD.update({"active": False, "key": None, "repo_id": None,
+ "started_ts": None})
+ h._json({"error": "This model is downloading right now — try again "
+ "when it finishes."}, 409); return
+ locks.append(fd)
# The deep-check findings for this repo are CONSUMED by this repair. They
# carry no file identity, so left in place a second Repair — after this
# one had fetched good copies — would delete the now-valid files again.
@@ -282,17 +324,20 @@ def post_models_repair(h, path, qs, ctype) -> None:
_dv = P._DEEP_VERIFY.get("result")
if isinstance(_dv, dict) and _dv.get("bad"):
_dv["bad"] = [b for b in _dv["bad"] if b.get("repo") != key]
- target = P.Q8_LOCAL_PATH if key == "q8" else P.repo_dir(repo)
deleted = []
- for fname in bad:
- for cand in {P.Path(target) / fname, P.repo_dir(repo) / fname}:
- try:
- if cand.exists():
- cand.unlink()
- if fname not in deleted:
- deleted.append(fname)
- except OSError:
- pass
+ try:
+ for fname in bad:
+ for cand in {P.Path(target) / fname, P.repo_dir(repo) / fname}:
+ try:
+ if cand.exists():
+ cand.unlink()
+ if fname not in deleted:
+ deleted.append(fname)
+ except OSError:
+ pass
+ finally:
+ # Released before the download starts: its fetcher takes the same lock.
+ P.pack_folder_unlock(locks)
with P._INTEGRITY_LOCK: # bust the cache so the next scan re-checks
P._INTEGRITY_CACHE["ts"] = 0.0
P.push(f"[repair] {key}: deleted {len(deleted)} corrupt/partial file(s) "
diff --git a/panel/routes_music.py b/panel/routes_music.py
index f3a36f7..973ecba 100644
--- a/panel/routes_music.py
+++ b/panel/routes_music.py
@@ -55,9 +55,11 @@ def _helper_run(spec: dict, timeout: float):
render when it is taken."""
if not P._GPU_LOCK.acquire(timeout=3.0):
raise RuntimeError("A render is using the GPU right now — try again when it finishes.")
+ P.gpu_gate_mark("lyrics")
try:
return P.HELPER.run(spec, timeout=timeout)
finally:
+ P.gpu_gate_unmark()
P._GPU_LOCK.release()
P = None # the running mlx_ltx_panel module; assigned at wiring time
diff --git a/panel/routes_queue.py b/panel/routes_queue.py
index e57a9e2..0f02845 100644
--- a/panel/routes_queue.py
+++ b/panel/routes_queue.py
@@ -298,6 +298,12 @@ def get_status(h, parsed) -> None:
# 4.20: what install.js left for after Start, and where the background
# fetcher is with it (empty and idle on every install it never queued).
payload["deferred_downloads"] = P.deferred_status()
+ # Mac app review #11: the process-wide GPU gate. `current` shows the queued
+ # job; an inline image render, a character sheet, Enhance, a lyrics request
+ # or the post-update script hold the GPU OUTSIDE the queue and showed
+ # nowhere, so a client deciding "is it safe to stop the studio" must read
+ # this too: {busy, holder, since, outside_queue}.
+ payload["gpu"] = P.gpu_gate_status()
# Mac app only: the app's own model download (app_models.json). The
# "Base models needed" card names it instead of offering a second fetch.
_app = P.app_models_state()
@@ -747,6 +753,7 @@ def post_prompt_enhance(h, path, qs, ctype) -> None:
reason = P.current_render_busy_reason()
P.push(f"[enhance] skipped: {reason}")
h._json({"error": f"{reason} Enhance works again when it finishes."}, 409); return
+ P.gpu_gate_mark("enhance")
try:
result = P.HELPER.run({
"action": "enhance_prompt",
@@ -759,6 +766,7 @@ def post_prompt_enhance(h, path, qs, ctype) -> None:
P.push(f"[enhance] failed: {exc}")
h._json({"error": str(exc)}, 500); return
finally:
+ P.gpu_gate_unmark()
P._GPU_LOCK.release()
# A malformed terminal helper event must still become JSON. Before
# this guard, None/non-string values raised after the only try/except
diff --git a/scripts/fetch_pack_release.py b/scripts/fetch_pack_release.py
index 8f7a586..a3d9969 100644
--- a/scripts/fetch_pack_release.py
+++ b/scripts/fetch_pack_release.py
@@ -51,7 +51,20 @@ USAGE
python scripts/fetch_pack_release.py --repo-key q4_25 --dest /tmp/from-zero/pack
python scripts/fetch_pack_release.py --repo-key q4_25 --check-only
-Exit code 0 means every declared file is present and hash-correct.
+Exit code 0 means every declared file is present and hash-correct. Exit code 75
+(EX_TEMPFAIL) means another download is writing the same pack folder right now
+and this one stopped without touching it.
+
+ONE WRITER PER PACK FOLDER
+--------------------------
+The studio's Models page, its background fetcher, ``install.js`` and the Mac
+app's own model download all run THIS script. Two copies writing one folder
+append into the same ``.phosphene_parts`` partials and corrupt both, so a
+download holds an exclusive ``flock`` on ``.<folder>.fetchlock`` beside the
+destination folder for as long as it writes (the kernel drops the lock when
+the process ends, however it ends; the panel's Remove and Repair take the
+same lock before they delete). A second download of the same folder refuses
+at once with exit 75; ``--check-only`` reads and takes no lock.
Stdlib only, on purpose: this runs from ``install.js`` before anything optional
is installed, and from the panel, which is stdlib-only by house rule.
@@ -60,6 +73,7 @@ is installed, and from the panel, which is stdlib-only by house rule.
from __future__ import annotations
import argparse
+import errno
import hashlib
import json
import os
@@ -77,6 +91,61 @@ USER_AGENT = "Phosphene"
CHUNK = 1 << 20
# Report at most this often, so a 6-shard 11 GB file does not spam the panel log.
PROGRESS_EVERY_SEC = 2.5
+#: Exit code when another download holds the destination folder (EX_TEMPFAIL).
+EXIT_BUSY = 75
+
+
+class PackBusy(Exception):
+ """Another download is writing this pack folder right now."""
+
+
+#: The one-writer lock lives BESIDE the pack folder, as ".<folder>.fetchlock",
+#: not on the folder itself: removing or repairing a pack deletes the folder,
+#: and a lock on a deleted folder's inode would let the next writer lock a
+#: fresh folder at the same path while the first one still writes there.
+PACK_LOCK_SUFFIX = ".fetchlock"
+
+
+def pack_lock_path(dest_dir: Path) -> Path:
+ """The lock file for a pack folder: its REAL path's sibling, so a
+ Pinokio-style symlink and the Mac app's own path meet on one lock."""
+ real = Path(os.path.realpath(str(dest_dir)))
+ return real.parent / f".{real.name}{PACK_LOCK_SUFFIX}"
+
+
+def lock_dest(dest_dir: Path) -> int:
+ """Take the one-writer lock for ``dest_dir`` (an exclusive, non-blocking
+ flock on its lock file) and return the descriptor; keep it open for as
+ long as the download writes. Raises PackBusy when another process holds
+ it. The kernel drops the lock when the process ends, however it ends."""
+ try:
+ import fcntl
+ except ImportError: # not a POSIX system: nothing to lock with
+ return -1
+ lock = pack_lock_path(dest_dir)
+ lock.parent.mkdir(parents=True, exist_ok=True)
+ fd = os.open(str(lock), os.O_RDWR | os.O_CREAT, 0o644)
+ try:
+ fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
+ except OSError as e:
+ os.close(fd)
+ if e.errno in (errno.EWOULDBLOCK, errno.EAGAIN, errno.EACCES):
+ raise PackBusy(str(dest_dir)) from None
+ raise
+ try: # who holds it, for a human reading the file
+ os.ftruncate(fd, 0)
+ os.write(fd, f"{os.getpid()}\n".encode())
+ except OSError:
+ pass
+ return fd
+
+
+def unlock_dest(fd: int) -> None:
+ if fd >= 0:
+ try:
+ os.close(fd) # closing the descriptor releases the flock
+ except OSError:
+ pass
def log(msg: str) -> None:
@@ -366,6 +435,25 @@ def fetch_pack(repo_key: str, root: Path, dest: Path | None,
log(f"[fetch] {repo_key}: complete, {len(files)} file(s) verified")
return 0
+ # ONE WRITER (Mac app review #7): the Mac app's download and the studio's
+ # Models page / background fetcher both run this script. Refuse, untouched,
+ # when another copy is writing this folder.
+ try:
+ lock_fd = lock_dest(dest_dir)
+ except PackBusy:
+ log(f"[fetch] {repo_key}: BUSY — another download is writing {dest_dir} right now; "
+ f"this one stopped without touching it, so the two never write the same files. "
+ f"It finishes on its own; download again after it if anything is still missing.")
+ return EXIT_BUSY
+ try:
+ return _fetch_locked(repo_key, files, dest_dir, mirror,
+ attempts=attempts, timeout=timeout)
+ finally:
+ unlock_dest(lock_fd)
+
+
+def _fetch_locked(repo_key: str, files: dict, dest_dir: Path, mirror: dict,
+ *, attempts: int, timeout: int) -> int:
total_gb = sum(int(s["bytes"]) for s in files.values()) / 1e9
log(f"[fetch] {len(files)} file(s), {total_gb:.2f} GB — resumable, sha256-verified")
@@ -411,17 +499,24 @@ def main(argv: list[str] | None = None) -> int:
ap.error("--dest applies to a single --repo-key")
rc = 0
+ busy = False
for key in args.repo_key:
try:
- rc |= fetch_pack(key, args.root, args.dest,
+ one = fetch_pack(key, args.root, args.dest,
attempts=args.attempts, timeout=args.timeout,
check_only=args.check_only)
except SystemExit:
raise
except Exception as e: # noqa: BLE001 — the installer needs a cause, not a traceback
log(f"[fetch] {key}: FAILED — {e}")
+ one = 1
+ if one == EXIT_BUSY:
+ busy = True
+ elif one:
rc = 1
- return rc
+ # A real failure wins over "busy": the caller must not mistake a broken
+ # download for one that is merely being served by someone else.
+ return rc if rc else (EXIT_BUSY if busy else 0)
if __name__ == "__main__":
diff --git a/webapp/docs/images.md b/webapp/docs/images.md
index 8221ba8..e1dbc35 100644
--- a/webapp/docs/images.md
+++ b/webapp/docs/images.md
@@ -14,6 +14,8 @@ The Images tab makes stills. Two kinds of engine live here: **Reference Edit**,
The pill next to the menu says whether that engine is downloaded. An engine that needs more memory than this Mac has is greyed out and labelled *needs a N GB Mac*.
+On Macs with 16 GB of memory or less, **Auto** uses FLUX.2 [klein] 4B at 4-bit for a render without references if the engine chosen in Settings needs a bigger Mac; your Settings stay the same. Renders with reference images keep the Settings engine because Klein does not use references. If that engine cannot fit, remove the references so Auto can use Klein, or choose a lighter engine in Settings.
+
## Reference images {#references}
Reference Edit needs at least one picture: drop it into **Primary**, and up to two more into the **Multi-ref** slots (or click one from *Recent uploads*). With two or more, name them in the prompt — *the jacket from reference 1 and the street from reference 2*.
diff --git a/webapp/docs/install.md b/webapp/docs/install.md
index 0410d99..01659f0 100644
--- a/webapp/docs/install.md
+++ b/webapp/docs/install.md
@@ -72,7 +72,7 @@ Your Mac's memory determines which quality settings and engines you can use. Pho
| Feature | Memory it needs |
|---|---|
-| LTX video and Images | Any Apple Silicon Mac. Below 48 GB, you get smaller video sizes. LTX's High quality, Start & end frame and Extend are hidden |
+| LTX video and Images | Any Apple Silicon Mac. Below 48 GB, you get smaller video sizes. LTX's High quality, Start & end frame and Extend are hidden. Macs with 24 GB or less automatically use a low-memory video path. |
| Music Studio | 24 GB or more |
| Training a character | 24 GB or more |
| Hailuo H3 | 36 GB or more for the compact engine. With 60 GB or more, you can also choose the full engine |
diff --git a/webapp/docs/settings.md b/webapp/docs/settings.md
index 7f41ec9..f5482f2 100644
--- a/webapp/docs/settings.md
+++ b/webapp/docs/settings.md
@@ -33,9 +33,11 @@ Saved on this Mac only, and sent nowhere except as sign-in to the site they belo
- **CivitAI API key** — needed to install LoRAs from CivitAI. **save & test** checks it.
- **Hugging Face token** — needed for gated models; read access is enough.
+[[pinokio]]
## Spicy mode (adult content) {#spicy}
Off by default: the CivitAI browser hides NSFW results and the **Show NSFW** switch. **Enable Spicy mode** asks for a second click, then lets you choose per search.
+[[/pinokio]]
## Appearance {#appearance}
diff --git a/webapp/docs/troubleshooting.md b/webapp/docs/troubleshooting.md
index 85275a8..98b2bf0 100644
--- a/webapp/docs/troubleshooting.md
+++ b/webapp/docs/troubleshooting.md
@@ -12,7 +12,7 @@ When Phosphene refuses a render, it says why and what to do. These are the messa
The health chip in the header shows memory at a glance; click it for the **Tier**, **Memory**, **Helper**, **Models**, **Queue** and **Render** rows. Click **Tier** to see what this Mac can run.
- *"Helper killed by the OS — out of memory"* — macOS stopped the render. Close memory-heavy apps (browsers, Slack, the iOS Simulator) and try again, or switch Quality to **Quick**, which uses about half the memory.
-- *"Image pre-flight: … needs a N GB Mac"* — that image engine does not fit this Mac. Pick **Auto** or a lighter preset. *"… needs ~N GB free"* means it fits, but other apps are holding the memory right now.
+- *"Image pre-flight: … needs a N GB Mac"* — that image engine does not fit this Mac. On Macs with 16 GB or less, **Auto** uses FLUX.2 [klein] 4B when the Settings engine needs a bigger Mac, without changing Settings. This requires a render without reference images; remove the references to let Auto use Klein, or choose a lighter engine in Settings. *"… needs ~N GB free"* means the engine fits, but memory is currently in use; this check now accounts for memory macOS can free up and Auto's actual memory needs.
- *"Training needs at least 24 GB of memory"* — character training cannot run on this Mac.
### Hailuo H3 on a 36–60 GB Mac {#h3-compact}
diff --git a/webapp/index.html b/webapp/index.html
index b173396..341002a 100644
--- a/webapp/index.html
+++ b/webapp/index.html
@@ -5940,11 +5940,13 @@ The last line"></textarea>
<button type="button" class="pill-btn" data-civitai-source="huggingface" onclick="civitaiSetSource('huggingface')" title="Search Hugging Face — a name, an author (author:someone) or an owner/repo">Hugging Face</button>
</div>
<div class="civitai-seg" id="civitaiFamilyRow" style="display:none" aria-label="Engine"></div>
+ <!--pinokio-only-->
<label class="toggle-pill" id="civitaiNsfwPill" data-spicy-only hidden>
<input type="checkbox" id="civitaiNsfw">
<span class="toggle-dot"></span>
<span>Show NSFW</span>
</label>
+ <!--/pinokio-only-->
</div>
<!-- WHAT KIND, for the Hugging Face source: read from each repo's name and
tags on the server; filtered here without another fetch. -->
@@ -6225,6 +6227,7 @@ The last line"></textarea>
</div>
</div>
+ <!--pinokio-only-->
<!-- Spicy mode — gates NSFW LoRA visibility in the CivitAI browser.
Default OFF. Turning ON requires an explicit confirm-click pattern
so a casual visitor / kid can't toggle it by a stray click. The
@@ -6249,6 +6252,8 @@ The last line"></textarea>
<div class="hint" id="spicyHint" style="margin-top:8px; display:none"></div>
</div>
+ <!--/pinokio-only-->
+
<!-- Anonymous usage analytics. Default ON, one click to turn off, and
the copy below is the whole truth about what leaves the machine —
if this list and docs/ANALYTICS.md ever disagree, the code is the
diff --git a/webapp/js/preview.js b/webapp/js/preview.js
index f42ffd2..68b32c7 100644
--- a/webapp/js/preview.js
+++ b/webapp/js/preview.js
@@ -1252,6 +1252,7 @@ function civitaiSetFamily(family) {
// One UI predicate serves both LTX and H3. The active engine only changes the
// LoRA family; it never changes whether NSFW controls/data are authorized.
function spicyModeEnabled() {
+ if (typeof isMacApp === 'function' && isMacApp()) return false; // no Spicy mode in the Mac app
return !!(_settingsCache && _settingsCache.settings &&
_settingsCache.settings.spicy_mode === true);
}
@@ -1505,7 +1506,7 @@ async function civitaiSearch() {
if (data.has_more) loadMore.style.display = '';
if ((data.items || []).length === 0) {
const meta = _civitaiContextMeta(_civitaiContext, _civitaiFamily);
- grid.innerHTML = `<div class="hint">${meta.empty} "${escapeHtml(q || '')}"${civitaiNsfwRequested() ? '' : ' (try Show NSFW for more)'}. Try one shorter word — CivitAI matches whole words in the title and tags — or switch the engine pill above.</div>`;
+ grid.innerHTML = `<div class="hint">${meta.empty} "${escapeHtml(q || '')}"${(civitaiNsfwRequested() || isMacApp()) ? '' : ' (try Show NSFW for more)'}. Try one shorter word — CivitAI matches whole words in the title and tags — or switch the engine pill above.</div>`;
}
} catch (e) {
status.textContent = 'Network error: ' + (e.message || e);
diff --git a/webapp/js/settings.js b/webapp/js/settings.js
index fcc45bf..634e4e3 100644
--- a/webapp/js/settings.js
+++ b/webapp/js/settings.js
@@ -1209,7 +1209,7 @@ function renderSpicyState(isOn) {
const badge = document.getElementById('spicyStateBadge');
const btn = document.getElementById('spicyToggleBtn');
const hint = document.getElementById('spicyHint');
- if (!badge || !btn) return;
+ if (!badge || !btn || !hint) return; // not served in the Mac app
badge.classList.remove('on', 'armed');
if (_spicyArmed) {
badge.textContent = 'ARMED';