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.18): lip-sync keeps time with the voice, a friendlier thank-you card with one-click starring, a stopped image download carries on

mrbizarro9f6d1629b22c
diff --git a/README.md b/README.md
index 981f617..7d27193 100644
--- a/README.md
+++ b/README.md
@@ -18,7 +18,7 @@ It runs **LTX-2.5** and **MiniMax H3 (Hailuo H3)** for text-to-video and image-t
and is built on Apple's MLX: no CUDA, no cloud GPU, no API key, no credits and no watermark.
Your prompts, pictures and videos never leave your Mac.
-**Current release: v4.19.17.** Made by Mr Bizarro.
+**Current release: v4.19.18.** Made by Mr Bizarro.
## Why Phosphene
diff --git a/VERSION b/VERSION
index 7693a42..6fa8004 100644
--- a/VERSION
+++ b/VERSION
@@ -1 +1 @@
-4.19.17
+4.19.18
diff --git a/docs/ANALYTICS.md b/docs/ANALYTICS.md
index d3ab70f..1872569 100644
--- a/docs/ANALYTICS.md
+++ b/docs/ANALYTICS.md
@@ -524,7 +524,7 @@ ignored or dismissed.
| Field | Type | Example |
|---|---|---|
-| `via` | string | `"link"` — one of `link` (opened the repo) or `already` (said they had already starred) from the update banner and the header star; or, from the one-time card after the fifth finished render (2 Nov 2026), `card_shown`, `card_star`, `card_waitlist` (the quiet Pro waitlist link, 5.0 line only) or `card_not_now` (Not now, the close button or Escape) |
+| `via` | string | `"link"` — one of `link` (opened the repo) or `already` (said they had already starred) from the update banner and the header star; or, from the one-time card after the fifth finished render (2 Nov 2026), `card_shown`, `card_star` (opened GitHub), `card_star_inapp` (starred in place with one click, through the Mac's own signed-in GitHub CLI; 4 Nov 2026), `card_waitlist` (the quiet Pro waitlist link, 5.0 line only) or `card_not_now` (the close button or Escape). A card retired unseen because GitHub says that account already starred sends nothing |
The banner's two values are coerced in their handler: anything else becomes
`link`. The card's values come from `POST /star-prompt`, which refuses
diff --git a/docs/CHANGELOG_4.19.18.md b/docs/CHANGELOG_4.19.18.md
new file mode 100644
index 0000000..26b1280
--- /dev/null
+++ b/docs/CHANGELOG_4.19.18.md
@@ -0,0 +1,12 @@
+# Phosphene 4.19.18
+
+**Lip-sync that keeps time, a friendlier thank-you card, and a stopped image download that carries on.** Free for everyone.
+
+- **Lip-sync: the mouth now moves with the voice, not a few frames ahead.** Both video engines' lip-sync clips moved the mouth up to a quarter of a second before the voice. Phosphene now checks each lip-sync clip after it is made and holds the picture back by exactly those frames; the sound, the length and where the clip sits on your song stay the same. A clip it cannot read clearly (no clear face, singing that blurs the timing) is left as it was made.
+- **A friendlier one-time thank-you card, and one-click starring if your Mac is signed in to GitHub.** After your fifth video, once you have stepped away for half a minute, a small card asks for a GitHub star. One button, a close button, and it never comes back. If your Mac is already signed in to GitHub (the `gh` command), the button stars Phosphene right there and says thank you; otherwise it opens GitHub. If you already starred, you never see it.
+- **Fixed: "The download for ... is stuck" on every Generate.** If the first download of an image model (Ideogram 4, FLUX.2, Reference Edit, Z-Image Turbo) was stopped partway, every later Generate with that model could fail at once with that message until you restarted Phosphene. Now every Generate carries the download on from where it is.
+- **Clearer messages:** an image model download that breaks off says which model, how far it got and what went wrong; a LoRA that does not fit the image model is named; the progress line says when a file has to start again from the beginning.
+
+All of this is free for everyone, and it is also in Phosphene 5.0.
+
+In Pinokio, press Update, then restart Phosphene.
diff --git a/image_engine.py b/image_engine.py
index c0b96bd..99c6ae3 100644
--- a/image_engine.py
+++ b/image_engine.py
@@ -177,6 +177,76 @@ def hf_repo_partial_download(repo_id: str, env: "dict | None" = None) -> "dict |
"repo_dir": repo_dir}
+def clear_download_litter(repo_id: str, env: "dict | None", before: float) -> int:
+ """Delete `.incomplete` blobs untouched since `before`; returns how many.
+
+ Call ONLY after an engine run on this repo exited 0: the model loaded, so
+ every file this revision needs is complete, and a leftover the run never
+ touched belongs to no file it wants (an older revision, a renamed file).
+ Left alone, it keeps hf_repo_partial_download() reporting the model as
+ unfinished forever (fleet: "stuck at 4.6 GB" about a 4.6 GB model). The
+ mtime guard keeps a download another process is running right now."""
+ blobs = _hf_hub_root(env) / ("models--" + str(repo_id).replace("/", "--")) / "blobs"
+ n = 0
+ try:
+ entries = list(blobs.iterdir())
+ except OSError:
+ return 0
+ for p in entries:
+ if not p.name.endswith(".incomplete"):
+ continue
+ try:
+ if p.stat().st_mtime < before:
+ p.unlink()
+ n += 1
+ except OSError:
+ pass
+ if n:
+ _REPAIR_MEMO.pop(str(repo_id), None)
+ return n
+
+
+def download_progress_step(prev_gb: float, now_gb: float) -> "tuple[bool, str | None]":
+ """One 15-second sample of a model download folder: (moved, log line).
+
+ `moved` is any change of more than 1 MB either way - a download that
+ restarts an unfinished file is alive. huggingface_hub's Xet downloader
+ (hf_xet, which every repo uploaded since 2025 uses) cannot resume: it
+ truncates the file's `.incomplete` to 0 and fetches it again, so the
+ folder SHRINKS when a retry starts. -1 means the folder does not exist."""
+ if now_gb < 0.0:
+ return False, None
+ if prev_gb < 0.0:
+ return now_gb > 0.001, None # the folder appeared: alive, nothing to compare
+ if now_gb > prev_gb + 0.001:
+ return True, f"[download] model weights: {now_gb:.1f} GB"
+ if now_gb < prev_gb - 0.001:
+ return True, (f"[download] an unfinished file is being fetched again from "
+ f"its start (the Hugging Face downloader cannot resume it), "
+ f"so the model folder dropped to {now_gb:.1f} GB")
+ return False, None
+
+
+def _download_stopped_note(repo_id, env, cause: str = "") -> "str | None":
+ """The first line of an engine failure whose model download is unfinished,
+ or None. Names the model, how far it got and the engine's own last line,
+ and says the next Generate continues it (it does - the repair is never
+ refused, see repair_partial_hf_download)."""
+ if not _is_hf_repo_id(repo_id):
+ return None
+ try:
+ info = hf_repo_partial_download(str(repo_id), env)
+ except Exception: # noqa: BLE001
+ info = None
+ if not info:
+ return None
+ why = f" The engine's last line: {cause[:220]}." if cause else ""
+ return (f"The model download for {repo_id} stopped at "
+ f"{float(info.get('on_disk_gb') or 0.0):.1f} GB before it finished "
+ f"({info.get('incomplete')} file(s) unfinished).{why} Generate again to "
+ f"continue it; if it stops again, check the network and free disk space.")
+
+
_REPAIR_MEMO: dict = {} # repo_id -> on_disk_gb at the last repair attempt
@@ -198,46 +268,36 @@ def repair_partial_hf_download(repo_id: str, env: "dict | None" = None) -> "dict
if not info:
_REPAIR_MEMO.pop(str(repo_id), None)
return None
- # Bounded (review 2026-09-02): if the previous attempt in this process
- # left the download exactly where it was, wiping and re-fetching again
- # on every render just burns time — say what's stuck instead.
+ # 4.19.18 (fleet, incident fw-20261102-1838): this used to REFUSE the
+ # render when the size had not moved since the previous repair ("The
+ # download for X is stuck at N GB - it did not grow on the last try") and
+ # it never forgot that verdict, so every later Generate in the same panel
+ # session failed in under a second without trying the download at all,
+ # while the message told the user to "Generate again to resume it". One
+ # M2 Max hit it 16 times on Ideogram 4 (16.7 -> 23.3 -> 30.1 GB): the
+ # download only moved after a panel restart cleared the memo. Two facts
+ # made the verdict wrong in the first place:
+ # - a pass that was Stopped (or killed) before the downloader wrote a
+ # byte is not a stalled download; cancelled jobs are not even reported;
+ # - the Hub's Xet downloader (hf_xet, every repo uploaded since 2025)
+ # cannot resume: it truncates an unfinished `.incomplete` to 0 and
+ # fetches that file again, so the folder's size is not a progress
+ # meter (measured on cocktailpeanut/ideogram-4-fp8: 58.7 MB -> 0 ->
+ # the whole file).
+ # So a repair is never refused before it runs. The run itself says what
+ # went wrong: a network or disk error from the engine, and, when it
+ # exits with the download unfinished, `_download_stopped_note` names the
+ # download on the error's first line.
+ # Leftover `.incomplete` files that belong to no file this revision
+ # needs used to be deleted here when the previous pass had re-linked
+ # `snapshots/`. That proves only that the pass reached the Hub and
+ # finished ONE file: a Stop after the first small file, or a blocked Xet
+ # server, deleted partials the model still needed, the cache then read
+ # complete, and mflux crashed in its weight loader on every render (#73).
+ # Only a render that SUCCEEDED proves the download is whole; the litter
+ # is cleared there (clear_download_litter, called by _generate_mflux).
on_disk = round(float(info.get("on_disk_gb") or 0.0), 2)
import time as _time
- prev = _REPAIR_MEMO.get(str(repo_id))
- if prev is not None and prev[0] == on_disk:
- # A whole download pass ran since the last repair. huggingface_hub
- # resumes a blob it needs by APPENDING to its `.incomplete`, so a
- # leftover older than that pass belongs to no file this revision wants
- # (an older revision, a renamed file) — IF the pass actually reached
- # the Hub, which is what a re-linked `snapshots/` proves. Then the
- # download is complete and the leftovers are litter. Without that proof
- # (offline, Hub down) nothing is deleted and the stall is reported.
- try:
- leftovers = [p for p in (info["repo_dir"] / "blobs").iterdir()
- if p.name.endswith(".incomplete")]
- except OSError:
- leftovers = []
-
- def _mtime(p):
- try:
- return p.stat().st_mtime
- except OSError:
- return None
- untouched = [p for p in leftovers if (_mtime(p) or 0.0) < prev[1]]
- if (leftovers and len(untouched) == len(leftovers)
- and (info["repo_dir"] / "snapshots").is_dir()):
- for p in untouched:
- try:
- p.unlink()
- except OSError:
- pass
- _REPAIR_MEMO.pop(str(repo_id), None)
- return None
- raise RuntimeError(
- f"The download for {repo_id} is stuck at {on_disk:.1f} GB — it did "
- f"not grow on the last try. Check free disk space and the network, "
- f"then Generate again to resume it."
- )
_REPAIR_MEMO[str(repo_id)] = (on_disk, _time.time())
snaps = info["repo_dir"] / "snapshots"
if snaps.is_dir():
@@ -971,6 +1031,38 @@ def lora_input_width(path) -> int | None:
return width if hits * 5 >= sum(counts.values()) * 2 else None # >= 40 %
+_SHAPE_ERROR_MARKS = ("[broadcast_shapes]", "[matmul]", "[addmm]", "Shapes (")
+
+
+def _lora_shape_note(config: ImageEngineConfig, lora_paths, cause: str) -> "str | None":
+ """The first line of an engine failure that a picked LoRA caused, or None.
+
+ mflux attaches LoRAs by key name and never compares shapes, so a LoRA made
+ for another model dies mid-denoise with an MLX shape error. The pre-launch
+ check (mflux_lora_problem) reads the width of plain lora_A/lora_down
+ adapters; LoKr/LoHa and full-delta files have none and pass it. Fleet
+ 4.19.16: "ValueError: [broadcast_shapes] Shapes (1,1024,18432) ..." five
+ times on one Mac, every time with a style LoRA picked on Auto (18432 is
+ [klein] 4B's feed-forward width, 3072 x 3 x 2). The card said only
+ "mflux-generate-flux2 failed (exit 1)"; it now names the LoRA."""
+ # The engine presets' own step-distillation adapters (Lightning) are made
+ # for their model and are never the user's pick: they are not blamed.
+ picked = [lp for lp in (lora_paths or [])
+ if not any(k in str(lp).lower() for k in ("lightning", "lightx2v"))]
+ if not picked or not cause or not any(m in cause for m in _SHAPE_ERROR_MARKS):
+ return None
+ names = [Path(str(lp)).name or str(lp) for lp in picked]
+ want = flux2_transformer_width(config)
+ model = FLUX2_WIDTH_NAMES.get(want) if want else None
+ model = model or str(getattr(config, "mflux_model", "") or "this model")
+ which = (f"the LoRA {names[0]}" if len(names) == 1 else
+ "one of the LoRAs you picked (" + ", ".join(names) + ")")
+ return (f"The render stopped on a layer-size mismatch, most likely because {which} "
+ f"does not fit {model} (the engine said: {cause[:160]}). Un-pick it"
+ f"{'' if len(names) == 1 else ', one at a time to find which'}, or pick a "
+ f"LoRA made for {model}.")
+
+
def mflux_lora_problem(config: ImageEngineConfig) -> tuple[str, str] | None:
"""Why the LoRAs on this config would make mflux fail, or None.
@@ -1545,8 +1637,9 @@ def _generate_mflux(prompt: str, n: int, width: int, height: int,
try:
on_log(f"[download] {config.mflux_model} was interrupted at "
f"{_partial['on_disk_gb']} GB ({_partial['incomplete']} files "
- f"unfinished) — resuming it before this render; nothing "
- f"already downloaded is fetched again.")
+ f"unfinished) — continuing it before this render. "
+ f"Finished files are kept; an unfinished one may start "
+ f"again from its beginning.")
except Exception: # noqa: BLE001
pass
@@ -1555,6 +1648,7 @@ def _generate_mflux(prompt: str, n: int, width: int, height: int,
last_lines: collections.deque[str] = collections.deque(maxlen=64)
stderr_tail = ""
timed_out = False
+ _spawned_at = time.time()
proc = subprocess.Popen(
cmd,
stdout=subprocess.PIPE,
@@ -1590,8 +1684,9 @@ def _generate_mflux(prompt: str, n: int, width: int, height: int,
# read loop stamps `_alive` on each render line (render alive). It kills
# the subprocess only on a GENUINE stall — neither disk nor stdout for
# stall_budget — and emits a GB readout. (HiDream uses the same idea.)
- _hf_home = env.get("HF_HOME") or os.path.expanduser("~/.cache/huggingface")
- dl_dir = ((Path(_hf_home) / "hub"
+ # Same hub root as the repair (HF_HUB_CACHE, then HF_HOME, then the
+ # default): it used to read HF_HOME only.
+ dl_dir = ((_hf_hub_root(env)
/ ("models--" + config.mflux_model.replace("/", "--")))
if getattr(config, "mflux_model", None) else None)
def _dl_gb() -> float:
@@ -1617,13 +1712,19 @@ def _generate_mflux(prompt: str, n: int, width: int, height: int,
_last = _dl_gb()
while not _wd_stop.wait(15.0):
_sz = _dl_gb()
- if _sz > _last + 0.001: # >1 MB on disk → download alive
+ # Compared with the LAST SAMPLE, not the largest one seen
+ # (4.19.18): the Xet downloader restarts an unfinished file
+ # from 0, the folder shrinks by gigabytes, and a max-so-far
+ # test showed no progress (and stamped no liveness) until
+ # the file had grown back past its old size.
+ _moved, _line = download_progress_step(_last, _sz)
+ if _moved:
_alive[0] = time.time()
- if _last >= 0.0 and on_log is not None:
- try: on_log(f"[download] model weights: {_sz:.1f} GB")
+ if _line and on_log is not None:
+ try: on_log(_line)
except Exception: # noqa: BLE001
pass
- _last = max(_last, _sz)
+ _last = _sz
if (time.time() - _alive[0] > stall_budget) or (time.time() > hard_cap):
_wd_killed[0] = True
try: os.killpg(os.getpgid(proc.pid), 15) # SIGTERM tree → readline EOFs
@@ -1786,6 +1887,18 @@ def _generate_mflux(prompt: str, n: int, width: int, height: int,
f"for a Python .ips crash report and attach it to your bug report.\n\n"
f"Tail of stdout/stderr:\n{stderr_tail[-800:]}"
)
+ # The engine exited with its model download unfinished (4.19.18):
+ # say THAT on the first line - the line the user reads and the
+ # fleet keeps - not only whatever mflux printed last.
+ _dl_note = _download_stopped_note(getattr(config, "mflux_model", None),
+ env, cause)
+ if _dl_note:
+ raise RuntimeError(
+ f"{_dl_note}\n\nTail of stdout/stderr:\n{stderr_tail[-1200:]}")
+ _shape_note = _lora_shape_note(config, _lora_paths_in, cause)
+ if _shape_note:
+ raise RuntimeError(
+ f"{_shape_note}\n\nTail of stdout/stderr:\n{stderr_tail[-1200:]}")
# Generic non-zero exit — pass through the tail so the user sees
# whatever mflux printed last. Keep the END of the tail: a Python
# traceback puts the exception on its last line, and the head-slice
@@ -1795,6 +1908,13 @@ def _generate_mflux(prompt: str, n: int, width: int, height: int,
f"Tail of stdout/stderr:\n{stderr_tail[-1200:]}"
)
+ # The run loaded the model, so its download is whole: clear leftovers.
+ if _is_hf_repo_id(getattr(config, "mflux_model", None)):
+ try:
+ clear_download_litter(config.mflux_model, env, _spawned_at)
+ except Exception: # noqa: BLE001
+ pass
+
# Build results from whatever files actually landed. If the
# subprocess errored partway through (e.g. one seed's generation
# raised), some seeds may not have produced an output — return the
diff --git a/lipsync_align.py b/lipsync_align.py
new file mode 100644
index 0000000..5da73f4
--- /dev/null
+++ b/lipsync_align.py
@@ -0,0 +1,264 @@
+"""Lip-sync alignment: the mouth moves a few frames BEFORE the voice in lip-sync (a2v) clips.
+
+Measured 4 Nov 2026 on H3 and LTX lip-sync renders (research note
+a2v_lipsync_lead_2026-11-04): the picture leads the soundtrack it was conditioned on by
+0-6 frames, typically 2, and the amount changes from clip to clip. The conditioning path
+itself is exact (the audio VAE round trip is 0 samples, the drive slice starts on the
+frame clock, the mux is 0 samples off), and the models' own text-to-video talking clips
+lead by a similar, equally variable amount, so the lead is the models' habit, not a
+rounding in our code. A fixed correction would leave the 0- and 6-frame clips wrong, so
+every lip-sync clip is MEASURED after it renders and its picture is held back by the
+measured lead:
+
+ * measure - motion inside the mouth box (frame differences) against the voice's
+ speech-band envelope, cross-correlated over the whole clip; the lag of the
+ peak is the lead (negative = the mouth moves first, the convention of the
+ measuring tool the film edit was cut with);
+ * correct - the first frame is held for N frames and the last N frames are dropped:
+ the soundtrack is untouched, the clip keeps its exact length and its place
+ on the song's clock (Editor, Storyboard and Continue-the-song read the
+ audio window, which does not move);
+ * refuse - no face, no speech, a weak or flat correlation, or a lead outside the
+ plausible range: the clip is delivered exactly as rendered.
+
+The pure parts (lag search, plan, filter) are unit-tested; the I/O parts need ffmpeg and
+OpenCV and return None rather than raise, so a measurement failure never fails a render.
+"""
+
+from __future__ import annotations
+
+import subprocess
+from pathlib import Path
+
+# Search range for the lag, in frames, each way. Wider than any lead seen (6) so a real
+# 6-frame lead is a peak inside the range, not a value pinned to its edge.
+SEARCH_FRAMES = 12
+# The largest correction ever applied. A measured lead past this is treated as a bad
+# measurement (a hand, a head turn, music in the voice band), not as a lead.
+MAX_SHIFT_FRAMES = 8
+# The measurement must be clearly better at the lag than at zero, and correlate at all.
+# Validation, 4 Nov 2026: a sung take (SUNDAY MASS s25) and a plateau (s15) scored only
+# 5 % / 3 % better at their "lead" than at zero; shifting s25 by its measured 5 frames
+# left it 3 frames LATE against the owner-approved 2. Clips with a real, clear lead
+# (kitchen line, s08, s09) score 12-68 % better. Sound arriving early is easier to
+# notice than a mouth a little ahead, so an unclear clip is delivered as rendered.
+MIN_PEAK = 0.25
+MIN_GAIN = 0.02 # absolute: peak - score at zero
+MIN_REL_GAIN = 0.09 # relative: (peak - score at zero) / peak
+# Fewer speaking frames than this cannot be measured (one short word).
+MIN_FRAMES = 36
+
+
+def best_lag(motion, envelope, search: int = SEARCH_FRAMES):
+ """PURE. `(lag, sub_frame_lag, peak, at_zero)` or None.
+
+ `motion[i]` is how much the mouth moved INTO frame i, `envelope[i]` the voice's
+ loudness during frame i. A NEGATIVE lag means the motion series matches the voice
+ LATER in time - the mouth moves first - by that many frames. `sub_frame_lag` refines
+ the integer peak with a parabola through its two neighbours.
+ """
+ import numpy as np
+
+ e = np.asarray(envelope, dtype=float)
+ m = np.asarray(motion, dtype=float)
+ n = min(len(e), len(m))
+ if n < MIN_FRAMES:
+ return None
+ e, m = e[:n], m[:n]
+ if e.std() < 1e-9 or m.std() < 1e-9:
+ return None
+ e = (e - e.mean()) / e.std()
+ m = (m - m.mean()) / m.std()
+ search = max(1, min(int(search), n // 3))
+ score = {}
+ for lag in range(-search, search + 1):
+ a = e[max(0, -lag):n - max(0, lag)]
+ b = m[max(0, lag):n - max(0, -lag)]
+ score[lag] = float(np.mean(a * b))
+ lag = max(score, key=score.get)
+ sub = float(lag)
+ if -search < lag < search:
+ lo, mid, hi = score[lag - 1], score[lag], score[lag + 1]
+ den = lo - 2.0 * mid + hi
+ if den < 0:
+ sub = lag + 0.5 * (lo - hi) / den
+ return lag, round(sub, 2), round(score[lag], 3), round(score[0], 3)
+
+
+def plan_shift(measure, *, max_shift: int = MAX_SHIFT_FRAMES, min_peak: float = MIN_PEAK,
+ min_gain: float = MIN_GAIN) -> tuple[int, str]:
+ """PURE. `(frames to hold the picture back, why)`; 0 = deliver as rendered.
+
+ Only a mouth-FIRST lead is corrected (the direction the models drift); a clip whose
+ mouth trails the voice is left alone - holding the voice back would move the clip
+ off the song's clock, and no render measured that way.
+ """
+ if measure is None:
+ return 0, "not measured (no face or no speech found)"
+ lag, sub, peak, at0 = measure
+ if peak < min_peak:
+ return 0, f"too weak to trust (peak {peak:+.2f})"
+ if lag >= 0:
+ return 0, "already in sync" if lag == 0 else f"mouth after the voice ({lag} f), left alone"
+ if peak - at0 < min_gain or (peak - at0) < MIN_REL_GAIN * peak:
+ return 0, f"no clear lead (peak {peak:+.2f} vs {at0:+.2f} at 0)"
+ lead = int(round(-float(sub)))
+ if lead > max_shift:
+ return 0, f"implausible lead ({lead} f), left alone"
+ if lead <= 0:
+ return 0, "already in sync"
+ return lead, f"mouth led the voice by {lead} frame{'s' if lead != 1 else ''}"
+
+
+def delay_filter(shift: int, frames: int) -> str:
+ """PURE. ffmpeg video filter: hold frame 0 for `shift` frames, keep `frames` in all."""
+ shift, frames = int(shift), int(frames)
+ if shift <= 0:
+ return f"trim=end_frame={frames},setpts=PTS-STARTPTS"
+ return (f"tpad=start={shift}:start_mode=clone,trim=end_frame={frames},"
+ "setpts=PTS-STARTPTS")
+
+
+# ----------------------------------------------------------------- I/O (ffmpeg + OpenCV)
+# The panel sets this to its own resolved ffprobe (mlx_ltx_panel.FFPROBE): some installs
+# keep ffprobe in another folder than ffmpeg, and Pinokio's PATH may not have it.
+FFPROBE: str | None = None
+
+
+def _probe(ffmpeg: str, video: Path) -> tuple[int, int, float, int] | None:
+ ffprobe = FFPROBE or str(Path(ffmpeg).with_name("ffprobe"))
+ if not Path(ffprobe).exists():
+ ffprobe = "ffprobe"
+ out = subprocess.run(
+ [ffprobe, "-v", "error", "-select_streams", "v:0", "-count_packets",
+ "-show_entries", "stream=width,height,r_frame_rate,nb_read_packets",
+ "-of", "csv=p=0", str(video)],
+ capture_output=True, text=True, errors="replace", timeout=60).stdout.strip().split(",")
+ try:
+ w, h = int(out[0]), int(out[1])
+ num, den = out[2].split("/")
+ return w, h, float(num) / float(den or 1), int(out[3])
+ except (IndexError, ValueError, ZeroDivisionError):
+ return None
+
+
+def mouth_box(ffmpeg: str, video: Path, size: tuple[int, int], fps: float, frames: int):
+ """(x0, y0, x1, y1) of the mouth area - the lower part of the biggest frontal face,
+ the median over five frames - or None when no face is found."""
+ try:
+ import cv2
+ import numpy as np
+ except Exception: # noqa: BLE001
+ return None
+ w, h = size
+ casc = cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalface_default.xml")
+ boxes = []
+ for frac in (0.15, 0.32, 0.5, 0.68, 0.85):
+ t = frac * frames / fps
+ raw = subprocess.run([ffmpeg, "-v", "error", "-ss", f"{t:.3f}", "-i", str(video),
+ "-frames:v", "1", "-f", "rawvideo", "-pix_fmt", "gray", "-"],
+ capture_output=True, timeout=60).stdout
+ if len(raw) < w * h:
+ continue
+ g = np.frombuffer(raw[:w * h], np.uint8).reshape(h, w)
+ faces = casc.detectMultiScale(g, 1.1, 5, minSize=(max(40, w // 20), max(40, w // 20)))
+ if len(faces):
+ fx, fy, fw, fh = max(faces, key=lambda b: b[2] * b[3])
+ boxes.append((fx + 0.22 * fw, fy + 0.62 * fh, fx + 0.78 * fw, fy + 1.05 * fh))
+ if len(boxes) < 2:
+ return None
+ x0, y0, x1, y1 = (int(v) for v in np.median(np.array(boxes), 0))
+ x0, y0 = max(0, x0), max(0, y0)
+ x1, y1 = min(w, x1), min(h, y1)
+ if x1 - x0 < 8 or y1 - y0 < 8:
+ return None
+ return x0 - x0 % 2, y0 - y0 % 2, x1 - x1 % 2, y1 - y1 % 2
+
+
+def mouth_motion(ffmpeg: str, video: Path, box, fps: float):
+ import numpy as np
+ x0, y0, x1, y1 = box
+ raw = subprocess.run([ffmpeg, "-v", "error", "-i", str(video), "-vf",
+ f"crop={x1 - x0}:{y1 - y0}:{x0}:{y0},scale=48:24,format=gray",
+ "-f", "rawvideo", "-"], capture_output=True, timeout=300).stdout
+ f = np.frombuffer(raw[:len(raw) // 1152 * 1152], np.uint8).reshape(-1, 24, 48).astype(float)
+ if len(f) < 2:
+ return None
+ return np.r_[0.0, np.abs(np.diff(f, axis=0)).mean((1, 2))]
+
+
+def voice_envelope(ffmpeg: str, audio: Path, fps: float, *, start: float = 0.0,
+ duration: float | None = None):
+ """Speech-band (250-3500 Hz) loudness per picture frame."""
+ import numpy as np
+ rate = 24000
+ cmd = [ffmpeg, "-v", "error"]
+ if start > 0:
+ cmd += ["-ss", f"{start:.4f}"]
+ cmd += ["-i", str(audio)]
+ if duration:
+ cmd += ["-t", f"{duration:.4f}"]
+ cmd += ["-vn", "-af", "highpass=f=250,lowpass=f=3500", "-ac", "1", "-ar", str(rate),
+ "-f", "s16le", "-"]
+ a = np.frombuffer(subprocess.run(cmd, capture_output=True, timeout=300).stdout,
+ np.int16).astype(float)
+ hop = rate / float(fps)
+ n = int(len(a) // hop)
+ if n < 2:
+ return None
+ return np.array([np.sqrt(np.mean(a[int(i * hop):int((i + 1) * hop)] ** 2) + 1e-9)
+ for i in range(n)])
+
+
+def measure(ffmpeg: str, video, audio=None, *, audio_start: float = 0.0):
+ """Measure one clip: `{lag, sub, peak, at0, box, fps, frames}` or None.
+
+ `audio` is the soundtrack the picture was conditioned on (a vocal stem when one was
+ used - the cleanest voice there is); None = the clip's own sound."""
+ try:
+ video = Path(video)
+ info = _probe(ffmpeg, video)
+ if info is None:
+ return None
+ w, h, fps, frames = info
+ box = mouth_box(ffmpeg, video, (w, h), fps, frames)
+ if box is None:
+ return None
+ motion = mouth_motion(ffmpeg, video, box, fps)
+ env = voice_envelope(ffmpeg, Path(audio) if audio else video, fps,
+ start=float(audio_start) if audio else 0.0,
+ duration=frames / fps)
+ if motion is None or env is None:
+ return None
+ got = best_lag(motion, env)
+ if got is None:
+ return None
+ lag, sub, peak, at0 = got
+ return {"lag": lag, "sub": sub, "peak": peak, "at0": at0, "box": list(box),
+ "fps": round(fps, 3), "frames": frames}
+ except Exception: # noqa: BLE001
+ return None
+
+
+def hold_picture(ffmpeg: str, video, shift: int, frames: int, *, crf: str = "18",
+ pix_fmt: str = "yuv420p") -> bool:
+ """Re-encode `video` in place with its picture held back by `shift` frames; the sound
+ is copied untouched. False (file unchanged) on any failure."""
+ video = Path(video)
+ # Not *.mp4: the gallery lists every .mp4 in the output folder.
+ tmp = video.with_name(video.name + ".lipsync-tmp")
+ cmd = [ffmpeg, "-y", "-v", "error", "-i", str(video), "-map", "0:v:0", "-map", "0:a?",
+ "-vf", delay_filter(shift, frames), "-c:v", "libx264", "-preset", "medium",
+ "-crf", str(crf), "-pix_fmt", str(pix_fmt), "-c:a", "copy",
+ "-movflags", "+faststart", "-f", "mp4", str(tmp)]
+ try:
+ subprocess.run(cmd, check=True, capture_output=True, timeout=1800)
+ got = _probe(ffmpeg, tmp)
+ if got is None or got[3] != int(frames):
+ tmp.unlink(missing_ok=True)
+ return False
+ tmp.replace(video)
+ return True
+ except Exception: # noqa: BLE001
+ tmp.unlink(missing_ok=True)
+ return False
diff --git a/mlx_ltx_panel.py b/mlx_ltx_panel.py
index 31e5049..2f0f061 100644
--- a/mlx_ltx_panel.py
+++ b/mlx_ltx_panel.py
@@ -20067,7 +20067,12 @@ def _analytics_feature(feature: str, detail: str = "") -> None:
# (star_prompt_done) never sees the card.
STAR_PROMPT_THRESHOLD = 5
STAR_PROMPT_URL = "https://github.com/mrbizarro/Phosphene"
-STAR_PROMPT_ACTIONS = ("shown", "star", "waitlist", "not_now")
+# star_inapp: starred in place through the Mac's own GitHub CLI (v2, 4 Nov).
+# already: the gh check says this GitHub account starred us; closes it with
+# no count (the owner: no analytics change except card_star_inapp).
+STAR_PROMPT_ACTIONS = ("shown", "star", "star_inapp", "waitlist", "not_now",
+ "already")
+STAR_PROMPT_REPO = "mrbizarro/Phosphene"
_STAR_PROMPT_LOCK = threading.Lock()
@@ -20121,12 +20126,99 @@ def star_prompt_due() -> bool:
return False
+# The live star count on the card's button (owner, 4 Nov 2026: "Star on
+# GitHub | 294"). A real number or nothing: the page hides the count whenever
+# this returns None, so a stranger never sees a made-up figure. Two sources,
+# in order: the daily GitHub snapshot the owner's own stats dashboard already
+# keeps (state/stats-data.jsonl, no network), then one anonymous GET of the
+# public repo, the same github.com the update check already talks to and off
+# under the same PHOSPHENE_DISABLE_VERSION_CHECK. Asked only while the card is
+# up (once per Mac), cached for an hour, a failure cached for ten minutes.
+STAR_COUNT_TTL_OK = 3600.0
+STAR_COUNT_TTL_FAIL = 600.0
+STAR_COUNT_SNAPSHOT_MAX_DAYS = 3
+_STAR_COUNT_CACHE: dict = {"at": 0.0, "stars": None, "checked": False}
+_STAR_COUNT_LOCK = threading.Lock()
+
+
+def _star_count_valid(v) -> int | None:
+ """A star count is a non-negative int (bools and floats are not)."""
+ if isinstance(v, bool) or not isinstance(v, int) or v < 0:
+ return None
+ return v
+
+
+def _star_count_from_snapshot(path: Path, today=None) -> int | None:
+ """The newest row of the stats archive, if it is recent. Rows are one
+ JSON object per UTC day, oldest first; a stale archive says nothing."""
+ import datetime as _dt
+ try:
+ if not path.is_file():
+ return None
+ with path.open("rb") as fh:
+ fh.seek(0, 2)
+ size = fh.tell()
+ fh.seek(max(0, size - 256 * 1024))
+ tail = fh.read().decode("utf-8", "replace")
+ except OSError:
+ return None
+ today = today or _dt.datetime.now(_dt.timezone.utc).date()
+ for line in reversed(tail.splitlines()):
+ line = line.strip()
+ if not line:
+ continue
+ try:
+ row = json.loads(line)
+ day = _dt.date.fromisoformat(str(row.get("date") or ""))
+ except (ValueError, TypeError, AttributeError):
+ continue
+ if (today - day).days > STAR_COUNT_SNAPSHOT_MAX_DAYS:
+ return None
+ return _star_count_valid(row.get("stars"))
+ return None
+
+
+def _star_count_from_github(timeout: float = 5.0) -> int | None:
+ """stargazers_count of the public repo, or None on any failure."""
+ import urllib.request as _urlreq
+ url = (f"https://api.github.com/repos/{_VERSION_REPO_OWNER}/"
+ f"{_VERSION_REPO_NAME}")
+ req = _urlreq.Request(url, headers={
+ "Accept": "application/vnd.github+json",
+ "User-Agent": "phosphene-panel-version-check",
+ })
+ try:
+ with _urlreq.urlopen(req, timeout=timeout) as resp:
+ data = json.loads(resp.read(512 * 1024).decode("utf-8", "replace"))
+ except Exception:
+ return None
+ if not isinstance(data, dict):
+ return None
+ return _star_count_valid(data.get("stargazers_count"))
+
+
+def star_prompt_stars(now: float | None = None) -> int | None:
+ """The repo's star count for the card, or None when it is not known."""
+ now = time.time() if now is None else now
+ with _STAR_COUNT_LOCK:
+ c = _STAR_COUNT_CACHE
+ if c["checked"]:
+ ttl = STAR_COUNT_TTL_OK if c["stars"] is not None else STAR_COUNT_TTL_FAIL
+ if now - c["at"] < ttl:
+ return c["stars"]
+ stars = _star_count_from_snapshot(STATS_DATA_FILE)
+ if stars is None and VERSION_CHECK_ENABLED:
+ stars = _star_count_from_github()
+ c.update(at=now, stars=stars, checked=True)
+ return stars
+
+
def _star_prompt_transition(state: str, action: str) -> str | None:
"""Pure: the new state for an action, or None when it changes nothing
(a second answer, or `shown` once it was already shown)."""
if action == "shown":
return "shown" if state == "due" else None
- if action in ("star", "waitlist", "not_now"):
+ if action in ("star", "star_inapp", "waitlist", "not_now", "already"):
return "done" if state in ("due", "shown") else None
return None
@@ -20149,11 +20241,120 @@ def star_prompt_answer(action: str) -> bool:
delta["star_prompt_done"] = True
_settings_set_internal(**delta)
# The same anonymous `star_prompt` event as the banner and the header
- # icon (via link / already), with the card's own closed values.
- _analytics_capture("star_prompt", {"via": "card_" + action})
+ # icon (via link / already), with the card's own closed values. A card
+ # retired because GitHub says they already starred is not counted.
+ if action != "already":
+ _analytics_capture("star_prompt", {"via": "card_" + action})
return True
+# ---- Star card v2: one click, only where the Mac is signed in to GitHub ----
+# (owner, 4 Nov 2026; the method learned from T3 Code's star prompt, our own
+# code.) If the GitHub CLI `gh` is installed and signed in to github.com, the
+# card can star in place: the person's click runs
+# gh api -X PUT /user/starred/mrbizarro/Phosphene
+# from this server. gh keeps its own login; we never read, store or send a
+# token, and we never look at `gh auth status` output, only its exit code.
+# Nothing here runs unless the card is due or up, and the PUT only on the
+# explicit click (post_star_prompt_star, which also refuses other websites).
+# No gh, not signed in, or any failure: the page opens GitHub as before.
+_STAR_GH_TIMEOUT = 8
+_STAR_GH_CACHE: dict = {"at": 0.0, "value": None}
+
+
+def _star_gh_bin() -> str | None:
+ """`gh` on PATH, or in the two Homebrew places a hand-started or
+ Pinokio-started panel may not have on PATH."""
+ found = shutil.which("gh")
+ if found:
+ return found
+ home = os.path.expanduser("~")
+ for cand in ("/opt/homebrew/bin/gh", "/usr/local/bin/gh", "/opt/local/bin/gh",
+ os.path.join(home, "bin", "gh"), os.path.join(home, ".local", "bin", "gh")):
+ if os.path.isfile(cand) and os.access(cand, os.X_OK):
+ return cand
+ return None
+
+
+def _star_gh_env() -> dict:
+ env = {k: v for k, v in os.environ.items()
+ if k not in ("PYTHONPATH", "PYTHONHOME", "VIRTUAL_ENV")}
+ env["GH_PROMPT_DISABLED"] = "1"
+ env["GH_NO_UPDATE_NOTIFIER"] = "1"
+ env["GH_SPINNER_DISABLED"] = "1"
+ env["NO_COLOR"] = "1"
+ env.pop("GH_HOST", None) # always github.com
+ return env
+
+
+def _star_gh_run(args: list, capture: bool = False):
+ """Run gh with `args`; (returncode, stdout, stderr) or None when gh is
+ missing or did not answer. stdout/stderr are only read when asked."""
+ gh = _star_gh_bin()
+ if not gh:
+ return None
+ try:
+ r = subprocess.run(
+ [gh, *args], env=_star_gh_env(), stdin=subprocess.DEVNULL,
+ stdout=subprocess.PIPE if capture else subprocess.DEVNULL,
+ stderr=subprocess.PIPE if capture else subprocess.DEVNULL,
+ text=True, errors="replace", timeout=_STAR_GH_TIMEOUT, check=False)
+ except (OSError, subprocess.SubprocessError, ValueError):
+ return None
+ return r.returncode, (r.stdout or ""), (r.stderr or "")
+
+
+def _star_gh_signed_in() -> bool:
+ r = _star_gh_run(["auth", "status", "--hostname", "github.com"])
+ return bool(r) and r[0] == 0
+
+
+def _star_gh_starred() -> bool | None:
+ """True = this GitHub account starred us (204), False = it has not
+ (404), None = unknown."""
+ r = _star_gh_run(["api", f"/user/starred/{STAR_PROMPT_REPO}"], capture=True)
+ if not r:
+ return None
+ if r[0] == 0:
+ return True
+ return False if "404" in r[2] else None
+
+
+def star_github_check(force: bool = False) -> dict:
+ """What the card needs before it goes up: whether gh can star in place,
+ whether they already starred, and the live star count (None = unknown,
+ the button then shows no number). Cached for ten minutes."""
+ now = time.time()
+ cached = _STAR_GH_CACHE.get("value")
+ if cached is not None and not force and now - _STAR_GH_CACHE["at"] < 600:
+ return dict(cached)
+ signed_in = _star_gh_signed_in()
+ starred = _star_gh_starred() if signed_in else None
+ try:
+ stars = star_prompt_stars()
+ except Exception:
+ stars = None
+ out = {"gh": bool(signed_in), "starred": starred, "stars": stars}
+ _STAR_GH_CACHE.update(at=now, value=dict(out))
+ return out
+
+
+def star_github_star() -> bool:
+ """Star the repo in place for the GitHub account `gh` is signed in as.
+ Only ever called from the person's click on the card."""
+ if not _star_gh_signed_in():
+ return False
+ r = _star_gh_run(["api", "-X", "PUT", f"/user/starred/{STAR_PROMPT_REPO}"])
+ ok = bool(r) and r[0] == 0
+ if ok:
+ cached = _STAR_GH_CACHE.get("value") or {}
+ stars = cached.get("stars")
+ _STAR_GH_CACHE.update(at=time.time(), value={
+ "gh": True, "starred": True,
+ "stars": (stars + 1) if isinstance(stars, int) and not cached.get("starred") else stars})
+ return ok
+
+
def _analytics_canvas_class(width: int, height: int) -> str:
"""Coarse canvas grouping by megapixels — the percentile dimension."""
@@ -33029,6 +33230,44 @@ def a2v_mux_original_audio(video: Path, audio_src: str, *,
os.replace(str(tmp), str(video))
+LIPSYNC_ALIGN_ENV = "PHOSPHENE_LIPSYNC_ALIGN" # "0" = deliver lip-sync clips as rendered
+
+
+def a2v_align_lipsync(video: Path, audio, start: float, *, crf="18",
+ pix_fmt="yuv420p") -> dict:
+ """Hold a lip-sync clip's picture back by the lead its mouth has on the voice.
+
+ Both engines' lip-sync renders move the mouth 0-6 frames BEFORE the voice
+ they were conditioned on (measured 4 Nov 2026; typical 2, different on
+ every clip, the same habit their own talking clips have, so it is the
+ models' and not a rounding in the conditioning path - see lipsync_align).
+ Each clip is measured against the voice it followed (`audio` from `start`,
+ the vocal stem when one was used) and, when the measurement is clear, its
+ first frame is held for that many frames and as many are cut from the end:
+ the sound, the length and the clip's place on the song's clock do not
+ move. Never raises; returns the sidecar's `lipsync_align` record.
+ """
+ rec = {"shift_frames": 0}
+ if os.environ.get(LIPSYNC_ALIGN_ENV, "1").strip() == "0":
+ rec["reason"] = f"off ({LIPSYNC_ALIGN_ENV}=0)"
+ return rec
+ try:
+ import lipsync_align as _la # noqa: PLC0415
+ _la.FFPROBE = str(FFPROBE) if FFPROBE else None
+ m = _la.measure(str(FFMPEG), video, audio, audio_start=float(start or 0.0))
+ shift, why = _la.plan_shift(
+ None if m is None else (m["lag"], m["sub"], m["peak"], m["at0"]))
+ rec.update(reason=why, measured=m)
+ if shift and _la.hold_picture(str(FFMPEG), video, shift, m["frames"],
+ crf=str(crf), pix_fmt=str(pix_fmt)):
+ rec["shift_frames"] = shift
+ elif shift:
+ rec["reason"] = why + " - the re-encode failed, delivered as rendered"
+ except Exception as exc: # noqa: BLE001
+ rec["reason"] = f"skipped ({exc})"
+ return rec
+
+
def a2v_audio_scale(raw, *, q8: bool) -> float:
"""The audio-guidance value for this lane: `raw` when it names one, else
the lane's engine default.
@@ -35382,6 +35621,12 @@ def run_image_job_inner(job: dict) -> None:
# (_resolve_model_path / snapshot_download / PathResolution) survive in
# the tail and only appear when the weights can't be fetched (gate /
# token / network), all of which the setup message addresses.
+ # 4.19.18: an engine failure that already names its unfinished
+ # download (image_engine._download_stopped_note: the model, how far it
+ # got, the engine's own last line) passes through; the generic text
+ # below hid it, and its traceback words matched every time.
+ if _m.startswith("The model download for"):
+ raise
if engine_override == "ideogram4_inline" and any(
k in _m for k in ("GatedRepo", "Access denied", "requires approval",
"awaiting", "403", "401", "Forbidden", "gated",
@@ -37160,6 +37405,7 @@ def h3_media_plan(job: dict, p: dict, mode: str, tier: dict, width: int,
out["notes"].append(note)
out["argv"] += ["--audio-drive", str(drive),
"--audio-drive-offset", f"{start_t:.3f}"]
+ out["drive_audio"], out["drive_start"] = str(drive), start_t
if str(drive) != audio:
out["argv"] += ["--audio-mux", audio]
image = str(p.get("image") or "").strip()
@@ -38487,6 +38733,15 @@ def run_h3_job_inner(job: dict) -> None:
if mode == "extend":
_h3_drop_runner_wavs(out_path, t0)
+ h3_lipsync_align = None
+ if mode == "a2v":
+ h3_lipsync_align = a2v_align_lipsync(
+ out_path, plan.get("drive_audio"), plan.get("drive_start") or 0.0,
+ crf=native_codec["crf"], pix_fmt=native_codec["pix_fmt"])
+ push(f"[h3] lip-sync timing: {h3_lipsync_align.get('reason')}"
+ + (f" - picture held back {h3_lipsync_align['shift_frames']} frame(s)"
+ if h3_lipsync_align.get("shift_frames") else ""))
+
if mode == "v2a":
# The delivery is the source's own stream: record ITS size, not the
# canvas the picture was read at for conditioning.
@@ -38578,6 +38833,9 @@ def run_h3_job_inner(job: dict) -> None:
"extend_audio_master": h3_splice_report.get("audio_master"),
"extend_source": plan.get("extend_source")}
if h3_splice_report else {}),
+ # Lip-sync: how far the mouth led the voice and how many frames the
+ # picture was held back for it (a2v_align_lipsync).
+ **({"lipsync_align": h3_lipsync_align} if h3_lipsync_align else {}),
"params": {
**p,
"engine": "h3",
@@ -41329,6 +41587,16 @@ def run_job_inner(job: dict) -> None:
except Exception as exc: # noqa: BLE001
push(f"[a2v] could not mux the original song back ({exc}) — "
f"this clip plays the vocal stem")
+ # The mouth leads the voice by a few frames on this engine too: hold
+ # the picture back by the measured lead, against the voice the model
+ # followed (the stem when one was used), before the verdict below.
+ ltx_lipsync_align = a2v_align_lipsync(
+ out_path, cond_audio, a2v_params["audio_start_time"],
+ crf=output_codec_settings().get("crf", "18"),
+ pix_fmt=output_codec_settings().get("pix_fmt", "yuv420p"))
+ push(f"[a2v] lip-sync timing: {ltx_lipsync_align.get('reason')}"
+ + (f" - picture held back {ltx_lipsync_align['shift_frames']} frame(s)"
+ if ltx_lipsync_align.get("shift_frames") else ""))
# VA-14: the lip-sync verdict. Scores the FINAL delivered file (the
# audience's own audio — the original song when a stem was muxed
# back, the conditioning file otherwise), not the stage-1 conditioning
@@ -41350,6 +41618,7 @@ def run_job_inner(job: dict) -> None:
sidecar = {
"output": str(out_path), "raw_output": str(out_path),
"lipsync_score": a2v_lipsync_score,
+ "lipsync_align": ltx_lipsync_align,
"params": {**p, "command": action, "audio": audio_src,
"audio_conditioning": cond_audio,
"audio_stem_used": cond_audio != audio_src,
diff --git a/panel/routes_meta.py b/panel/routes_meta.py
index 785854e..e55ab61 100644
--- a/panel/routes_meta.py
+++ b/panel/routes_meta.py
@@ -604,6 +604,52 @@ def post_star_prompt(h, path, qs, ctype) -> None:
h._json({"ok": True, "changed": changed, "due": P.star_prompt_due()})
+def _star_state_open() -> bool:
+ """The card is due or up: the only time the GitHub routes do anything."""
+ try:
+ return (P.get_settings().get("star_prompt_state") or "") in ("due", "shown")
+ except Exception:
+ return False
+
+
+@get("/star-prompt/github")
+def get_star_prompt_github(h, parsed) -> None:
+ """Star card v2 (owner, 4 Nov 2026): before the card goes up, the page
+ asks whether this Mac's GitHub CLI can star in place, whether that
+ account already starred, and the live star count. Does nothing (no gh,
+ no network) unless the card is due or up."""
+ if not _star_state_open():
+ h._json({"ok": True, "open": False, "gh": False, "starred": None,
+ "stars": None}); return
+ out = P.star_github_check()
+ h._json({"ok": True, "open": True, **out})
+
+
+@post("/star-prompt/star")
+def post_star_prompt_star(h, path, qs, ctype) -> None:
+ """The card's Star click, one click where gh is signed in. Runs only on
+ the person's click: the page sends JSON (another website cannot without
+ a preflight this server never answers) and same-origin fetch metadata,
+ and only while the card is due or up. On any failure the page opens
+ GitHub instead and records `star` as before."""
+ site = (h.headers.get("Sec-Fetch-Site") or "").strip().lower()
+ if site and site not in ("same-origin", "none"):
+ h._json({"ok": False, "error": "refused"}, 403); return
+ _ct = (ctype or h.headers.get("Content-Type") or "").split(";", 1)[0].strip().lower()
+ if _ct != "application/json":
+ h._json({"ok": False, "error": "refused"}, 415); return
+ _rb = h._read_form_body()
+ if _rb is None:
+ return
+ if not _star_state_open():
+ h._json({"ok": False, "fallback": True, "error": "card not up"}, 409); return
+ if not P.star_github_star():
+ h._json({"ok": False, "fallback": True}); return
+ P.star_prompt_answer("star_inapp")
+ h._json({"ok": True, "starred": True,
+ "stars": (P.star_github_check().get("stars"))})
+
+
@post("/version/pull")
def post_version_pull(h, path, qs, ctype) -> None:
# The "magic button" path — when the pill is in the behind
diff --git a/webapp/docs/getting-started.md b/webapp/docs/getting-started.md
index 52e1b31..c14842e 100644
--- a/webapp/docs/getting-started.md
+++ b/webapp/docs/getting-started.md
@@ -101,4 +101,12 @@ Updating an existing install downloads and removes nothing.
- To repair the music engine, open **Audio → Compose** and click **Repair music engine**. Hailuo H3 is not available in the Mac app yet.
[[/mac-app]]
+## The thank-you card {#star}
+
+After your fifth finished render, once you have left Phosphene alone for 30 seconds, a small card in the corner asks for a star on GitHub. It never covers your clip and never comes back once you close it (the **×** or Escape).
+
+- **One-click GitHub star:** if this Mac is signed in to GitHub with the `gh` command, **Star on GitHub** stars Phosphene right there and the card says thank you. Phosphene only asks `gh` to do it when you click; it never reads or keeps your GitHub login.
+- Otherwise the button opens Phosphene's GitHub page in your browser.
+- If you already starred (from the star in the header, the update banner, or GitHub itself as `gh` sees it), you never see the card.
+
> **Tip** Press [[sc:docs.open]] anywhere to open these docs on the shortcuts page, and use the search box on the left to find any button by the word written on it.
diff --git a/webapp/index.html b/webapp/index.html
index 387a6ac..35e820e 100644
--- a/webapp/index.html
+++ b/webapp/index.html
@@ -6514,11 +6514,14 @@ The last line"></textarea>
GET /licences; opened when the server answers 451 licence_required, from
the H3 install card, and from the H3 credit line. -->
<!-- STAR_CARD_START: the one-time "star us on GitHub" card (owner, 2 Nov
- 2026). A sibling of the Pro lamp card ("Help us keep the lights on"): the
- same lamp, header and palette. Not modal and never over the clip: it sits
- in the corner beside the result after the fifth finished render, once per
- Mac, and any answer ends it for good. Driven by starCardPoll (health.js). -->
-<aside id="starCard" class="star-card" role="dialog" aria-modal="false" aria-labelledby="starCardTitle" hidden>
+ 2026; v2 4 Nov 2026). A sibling of the Pro lamp card: the same lamp,
+ header and palette. Not modal and never over the clip: it sits in the
+ corner after the fifth finished render, once the person has been idle
+ 30 s with the page in front of them, once per Mac. One button; the quiet
+ close X (and Escape) is the only other way out. Where the Mac's GitHub
+ CLI is signed in, the button stars in place and the card says thank you;
+ otherwise it opens GitHub. Driven by starCardPoll (health.js). -->
+<aside id="starCard" class="star-card" role="dialog" aria-modal="false" aria-labelledby="starCardTitle" aria-describedby="starCardBody" hidden>
<button type="button" class="star-card-close" aria-label="Close" title="Close" onclick="starCardAnswer('not_now')">&times;</button>
<section class="lights-on-header star-card-head">
<div class="lights-on-wash" aria-hidden="true"></div>
@@ -6541,16 +6544,19 @@ The last line"></textarea>
<circle class="lamp-chain" cx="111" cy="81" r="2.5" fill="#b4b4bb"/>
</g>
</svg>
- <div class="lights-on-copy">
- <p class="lights-on-eyebrow">FREE AND OPEN SOURCE</p>
+ <div class="lights-on-copy star-card-ask">
<h2 id="starCardTitle">Help keep<br>the lights on</h2>
- <p class="lights-on-lead">I'm Mr Bizarro, the one person behind Phosphene. A star on GitHub costs nothing and helps the next person find it.</p>
+ <p id="starCardBody" class="lights-on-lead">Enjoying Phosphene? A star on GitHub would mean the world to us, and it helps other Mac users find us.</p>
+ </div>
+ <div class="lights-on-copy star-card-thanks" id="starCardThanks" role="status" aria-live="polite" hidden>
+ <h2>Thank you!</h2>
+ <p class="lights-on-lead">You just helped the next Mac user find Phosphene.</p>
</div>
</section>
<div class="star-card-actions">
- <button type="button" class="star-card-primary" onclick="starCardAnswer('star')"><svg viewBox="0 0 16 16" width="15" height="15" aria-hidden="true"><path d="M8 1.2l2.1 4.3 4.7.7-3.4 3.3.8 4.7L8 12l-4.2 2.2.8-4.7L1.2 6.2l4.7-.7z" fill="currentColor"/></svg>Star Phosphene on GitHub</button>
- <button type="button" class="star-card-later" onclick="starCardAnswer('not_now')">Not now</button>
+ <button type="button" id="starCardStar" class="star-card-primary" onclick="starCardStar()"><svg viewBox="0 0 16 16" width="15" height="15" aria-hidden="true"><path d="M8 1.2l2.1 4.3 4.7.7-3.4 3.3.8 4.7L8 12l-4.2 2.2.8-4.7L1.2 6.2l4.7-.7z" fill="currentColor"/></svg><span class="star-card-label">Star on GitHub</span><span class="star-card-count" id="starCardCount" hidden></span></button>
</div>
+ <canvas class="star-card-burst" id="starCardBurst" aria-hidden="true"></canvas>
</aside>
<!-- STAR_CARD_END -->
diff --git a/webapp/js/health.js b/webapp/js/health.js
index ad19992..9a8d257 100644
--- a/webapp/js/health.js
+++ b/webapp/js/health.js
@@ -1022,35 +1022,105 @@ Object.assign(globalThis, {
_phModalShow, _phModalClose,
});
-// ---- The one-time "star us on GitHub" card (owner, 2 Nov 2026) -------------
+// ---- The one-time "star us on GitHub" card (owner, 2 Nov 2026; v2 4 Nov) --
// After the fifth finished render the server sets `star_prompt_due` on
-// /status (see _star_prompt_after_job). The card goes up once, only while
-// the page is actually visible, and tells the server `shown` so it is never
-// put up again on this Mac. Any answer (star, waitlist, Not now, the close
-// button or Escape) ends it for good. No counters on screen; the only
-// network call is opening the link the person chose.
+// /status (see _star_prompt_after_job). v2, learned from how T3 Code asks
+// (our own code):
+// 1. Ask the server first (/star-prompt/github): if this Mac's GitHub CLI
+// says the account already starred us, the card is retired unseen.
+// 2. Wait until the person has been idle 30 s with the page visible and
+// focused. Any pointer, key, wheel or typing restarts the wait, so it
+// never lands mid-typing or mid-drag.
+// 3. One button, "Star on GitHub | <live count>" (no number when unknown).
+// Where gh is signed in it stars in place and the card says thank you
+// with a short burst, then closes; otherwise it opens GitHub.
+// The quiet close X and Escape record `not_now`. The card says `shown` when
+// it really goes up, so it is never put up again on this Mac.
const STAR_CARD_URL = 'https://github.com/mrbizarro/Phosphene';
-let _starCardUp = false;
+const STAR_CARD_IDLE_MS = 30000;
+const STAR_CARD_THANKS_MS = 5000;
+const STAR_CARD_ACTIVITY = ['pointerdown', 'pointermove', 'keydown', 'wheel',
+ 'touchstart', 'input', 'compositionstart', 'focus'];
+let _starCardUp = false; // on screen
+let _starCardArmed = false; // due seen this session: checking or waiting
+let _starCardDone = false; // answered; the card only closes now
+let _starCardInfo = null; // {gh, starred, stars} from the server
function _starCardPost(action) {
try {
return fetch('/star-prompt', {method: 'POST', body: new URLSearchParams({action}),
keepalive: true}).catch(() => {});
} catch (_) { return Promise.resolve(); }
}
-function starCardPoll(s) {
- if (_starCardUp || !s || !s.star_prompt_due) return;
- if (document.hidden) return; // wait until someone can see it
+function _starCardCheck() {
+ try {
+ return fetch('/star-prompt/github', {cache: 'no-store'})
+ .then((r) => (r && r.ok ? r.json() : null)).catch(() => null);
+ } catch (_) { return Promise.resolve(null); }
+}
+function _starCardCount(n) {
+ if (typeof n !== 'number' || !isFinite(n) || n < 0) return '';
+ if (n < 1000) return String(Math.round(n));
+ const k = n / 1000;
+ return (k < 10 ? k.toFixed(1).replace(/\.0$/, '') : String(Math.round(k))) + 'k';
+}
+function _starCardSetCount(n) {
+ const c = document.getElementById('starCardCount');
+ if (!c) return;
+ const t = _starCardCount(n);
+ c.textContent = t;
+ c.hidden = !t;
+}
+// Resolves once the page has been idle STAR_CARD_IDLE_MS while visible and
+// focused. A timer that ends while the page is hidden or unfocused waits for
+// the next focus / visibility change and starts over.
+function _starCardWaitIdle() {
+ return new Promise((resolve) => {
+ let timer = null;
+ const restart = () => {
+ clearTimeout(timer);
+ timer = setTimeout(() => {
+ if (document.hidden || (typeof document.hasFocus === 'function' && !document.hasFocus())) return;
+ for (const t of STAR_CARD_ACTIVITY) window.removeEventListener(t, restart, true);
+ document.removeEventListener('visibilitychange', restart, true);
+ resolve();
+ }, STAR_CARD_IDLE_MS);
+ };
+ for (const t of STAR_CARD_ACTIVITY) window.addEventListener(t, restart, {capture: true, passive: true});
+ document.addEventListener('visibilitychange', restart, true);
+ restart();
+ });
+}
+function _starCardShow() {
const el = document.getElementById('starCard');
- if (!el) return;
+ if (!el || _starCardUp || _starCardDone) return;
+ _starCardSetCount(_starCardInfo && _starCardInfo.stars);
_starCardUp = true;
el.hidden = false;
_starCardPost('shown');
}
-function starCardAnswer(action) {
+function starCardPoll(s) {
+ if (_starCardArmed || _starCardUp || !s || !s.star_prompt_due) return;
+ if (!document.getElementById('starCard')) return;
+ _starCardArmed = true;
+ return _starCardCheck().then((info) => {
+ _starCardInfo = info || null;
+ if (info && info.starred === true) { // they already starred
+ _starCardDone = true;
+ return _starCardPost('already');
+ }
+ return _starCardWaitIdle().then(_starCardShow);
+ });
+}
+function _starCardClose() {
const el = document.getElementById('starCard');
- if (el) el.hidden = true;
- if (!_starCardUp) return;
+ if (el) { el.hidden = true; el.classList.remove('is-thanks'); }
_starCardUp = false;
+}
+function starCardAnswer(action) {
+ if (!_starCardUp) { _starCardClose(); return; }
+ if (_starCardDone) { _starCardClose(); return; } // the thank-you, closed early
+ _starCardDone = true;
+ _starCardClose();
if (action === 'star') {
document.getElementById('starLink')?.classList.remove('is-calling');
if (typeof openExternal === 'function') openExternal(STAR_CARD_URL);
@@ -1064,9 +1134,96 @@ function starCardAnswer(action) {
}
_starCardPost(action);
}
+// The one button. In place where gh is signed in, GitHub otherwise (and on
+// any failure). Only ever on the person's click.
+async function starCardStar() {
+ if (!_starCardUp || _starCardDone) return;
+ const btn = document.getElementById('starCardStar');
+ if (_starCardInfo && _starCardInfo.gh) {
+ const label = btn && btn.querySelector('.star-card-label');
+ if (btn) btn.disabled = true;
+ if (label) label.textContent = 'Starring…';
+ let r = null;
+ try {
+ r = await fetch('/star-prompt/star', {method: 'POST',
+ headers: {'Content-Type': 'application/json'}, body: '{}'})
+ .then((x) => x.json()).catch(() => null);
+ } catch (_) { r = null; }
+ if (btn) btn.disabled = false;
+ if (label) label.textContent = 'Star on GitHub';
+ if (r && r.ok) { _starCardThank(r.stars); return; }
+ }
+ starCardAnswer('star');
+}
+function _starCardThank(stars) {
+ _starCardDone = true; // the server recorded star_inapp
+ const el = document.getElementById('starCard');
+ if (!el) return;
+ _starCardSetCount(stars);
+ el.classList.add('is-thanks');
+ const ask = el.querySelector('.star-card-ask');
+ if (ask) ask.hidden = true;
+ const ty = document.getElementById('starCardThanks');
+ if (ty) ty.hidden = false;
+ _starCardBurst(el);
+ setTimeout(_starCardClose, STAR_CARD_THANKS_MS);
+}
+// A short burst of little stars and sparks out of the lamp's bulb (the lamp
+// lights up as the card says thank you), drawn on the card's own canvas, no
+// library. Skipped under prefers-reduced-motion.
+function _starCardBurst(card) {
+ const reduce = typeof matchMedia === 'function'
+ && matchMedia('(prefers-reduced-motion: reduce)').matches;
+ const cv = document.getElementById('starCardBurst');
+ if (reduce || !cv || !cv.getContext) return false;
+ const rect = card.getBoundingClientRect();
+ const bulb = card.querySelector && card.querySelector('.lamp-bulb');
+ const bb = bulb && bulb.getBoundingClientRect ? bulb.getBoundingClientRect() : null;
+ const b = bb && bb.width ? bb : {left: rect.left + rect.width / 2 - 1, top: rect.top + rect.height / 2 - 1, width: 2, height: 2};
+ const dpr = Math.min(2, window.devicePixelRatio || 1);
+ cv.width = Math.round(rect.width * dpr); cv.height = Math.round(rect.height * dpr);
+ const ctx = cv.getContext('2d');
+ if (!ctx) return false;
+ ctx.scale(dpr, dpr);
+ const ox = b.left - rect.left + b.width / 2, oy = b.top - rect.top + b.height / 2;
+ const colors = ['#ffd391', '#ffe5b4', '#5eeaff', '#b14aff', '#f4f4f5'];
+ const parts = [];
+ for (let i = 0; i < 44; i++) {
+ const a = (Math.PI * 2 * i) / 44 + Math.random() * 0.3;
+ const v = 1.8 + Math.random() * 3.6;
+ parts.push({x: ox, y: oy, vx: Math.cos(a) * v * 1.25, vy: Math.sin(a) * v - 1.6,
+ r: 1.2 + Math.random() * 2, c: colors[i % colors.length],
+ star: i % 3 === 0, spin: Math.random() * 6});
+ }
+ const t0 = performance.now(), life = 1400;
+ const star = (x, y, r, rot) => {
+ ctx.beginPath();
+ for (let k = 0; k < 10; k++) {
+ const rr = k % 2 ? r * 0.45 : r, an = rot + (Math.PI * k) / 5;
+ ctx.lineTo(x + Math.cos(an) * rr, y + Math.sin(an) * rr);
+ }
+ ctx.closePath(); ctx.fill();
+ };
+ const frame = (now) => {
+ const t = (now - t0) / life;
+ ctx.clearRect(0, 0, rect.width, rect.height);
+ if (t >= 1) return;
+ ctx.globalAlpha = 1 - t * t;
+ for (const p of parts) {
+ p.vy += 0.16; p.vx *= 0.985; p.vy *= 0.985;
+ p.x += p.vx; p.y += p.vy;
+ ctx.fillStyle = p.c;
+ if (p.star) star(p.x, p.y, p.r * 1.9, p.spin + t * 6);
+ else { ctx.beginPath(); ctx.arc(p.x, p.y, p.r, 0, Math.PI * 2); ctx.fill(); }
+ }
+ requestAnimationFrame(frame);
+ };
+ requestAnimationFrame(frame);
+ return true;
+}
document.addEventListener('keydown', (e) => {
if (e.key !== 'Escape' || !_starCardUp) return;
const el = document.getElementById('starCard');
if (el && el.contains(document.activeElement)) starCardAnswer('not_now');
});
-Object.assign(globalThis, { starCardPoll, starCardAnswer });
+Object.assign(globalThis, { starCardPoll, starCardAnswer, starCardStar });
diff --git a/webapp/style/panel.css b/webapp/style/panel.css
index 60a5c6a..9fc485d 100644
--- a/webapp/style/panel.css
+++ b/webapp/style/panel.css
@@ -13019,26 +13019,31 @@ body[data-engine="h3"][data-vmode="v2a"] #h3LengthLabel { display: none !importa
/* LIGHTS_ON_CSS_END */
/* STAR_CARD_CSS_START: the one-time "star us on GitHub" card (owner, 2 Nov
- 2026). The Pro lamp header at card size; nothing new in the palette. */
+ 2026; v2 4 Nov). The Pro lamp header at card size; nothing new in the
+ palette. Always the dark lamp card, in both appearances. */
.star-card { position: fixed; right: 20px; bottom: 20px; z-index: 900; width: min(400px, calc(100vw - 32px)); border: 1px solid #2a2a2f; border-radius: 14px; background: #0b0b0c; color: #f4f4f5; box-shadow: 0 24px 60px rgba(0,0,0,.55), 0 0 0 1px rgba(255,211,145,.04); overflow: hidden; animation: star-card-in .42s cubic-bezier(.2,.8,.2,1) both; }
+html[data-theme="light"] .star-card { box-shadow: 0 18px 44px rgba(20,26,46,.28), 0 0 0 1px rgba(20,26,46,.06); }
.star-card[hidden] { display: none; }
-.star-card .star-card-head { border: 0; border-radius: 0; background: transparent; gap: 14px; padding: 24px 22px 8px 18px; }
+.star-card .star-card-head { border: 0; border-radius: 0; background: transparent; gap: 14px; padding: 24px 30px 8px 18px; }
.star-card .star-card-lamp { width: 76px; height: 85px; flex-basis: 76px; }
.star-card .star-card-head h2 { font-size: 27px; letter-spacing: -.4px; }
-.star-card .lights-on-eyebrow { margin-bottom: 9px; font-size: 11px; letter-spacing: 1.6px; }
.star-card .lights-on-lead { margin-top: 10px; font-size: 13px; line-height: 1.5; }
-.star-card-actions { display: flex; align-items: center; gap: 6px; padding: 12px 22px 18px; }
+.star-card .lights-on-copy[hidden] { display: none; }
+.star-card-actions { display: flex; align-items: center; gap: 6px; padding: 12px 22px 20px; }
.star-card-primary { display: inline-flex; align-items: center; gap: 8px; border: 0; border-radius: 4px; padding: 11px 15px; background: #f4f4f5; color: #0b0b0c; font: inherit; font-size: 13px; font-weight: 650; white-space: nowrap; cursor: pointer; }
.star-card-primary svg { color: #c98a2b; flex: 0 0 auto; }
.star-card-primary:hover { background: #fff0d8; }
-.star-card-later { border: 0; background: transparent; color: #b4b4bb; font: inherit; font-size: 13px; padding: 11px 8px; cursor: pointer; }
-.star-card-later:hover { color: #f4f4f5; }
-.star-card-quiet { display: block; padding: 0 22px 18px; margin-top: -6px; color: #8e8e96; font-size: 12px; text-decoration: none; }
-.star-card-quiet:hover { color: #b4b4bb; text-decoration: underline; }
-.star-card-close { position: absolute; top: 8px; right: 10px; z-index: 2; width: 28px; height: 28px; border: 0; border-radius: 4px; background: transparent; color: #8e8e96; font-size: 20px; line-height: 1; cursor: pointer; }
+.star-card-primary:disabled { cursor: progress; opacity: .8; }
+.star-card-count { margin-left: 3px; padding-left: 11px; border-left: 1px solid rgba(11,11,12,.22); font-variant-numeric: tabular-nums; font-weight: 600; color: #3a3a40; }
+.star-card-count[hidden] { display: none; }
+.star-card.is-thanks .star-card-actions { display: none; }
+.star-card.is-thanks .star-card-head { padding-bottom: 24px; }
+.star-card.is-thanks .lamp-beam, .star-card.is-thanks .lamp-pool { opacity: .55; }
+.star-card-burst { position: absolute; inset: 0; width: 100%; height: 100%; pointer-events: none; z-index: 3; }
+.star-card-close { position: absolute; top: 10px; right: 10px; z-index: 4; display: grid; place-items: center; width: 24px; height: 24px; padding: 0; border: 0; border-radius: 4px; background: transparent; color: #8e8e96; font-size: 18px; line-height: 1; cursor: pointer; }
.star-card-close:hover { color: #f4f4f5; background: #19191c; }
.star-card button:focus-visible, .star-card a:focus-visible { outline: 2px solid #ffd391; outline-offset: 2px; }
@keyframes star-card-in { from { opacity: 0; transform: translateY(12px); } to { opacity: 1; transform: none; } }
-@media (prefers-reduced-motion: reduce) { .star-card { animation: none; } }
+@media (prefers-reduced-motion: reduce) { .star-card { animation: none; } .star-card-burst { display: none; } }
@media (max-width: 560px) { .star-card { right: 16px; bottom: 16px; } .star-card .star-card-head h2 { font-size: 24px; } }
/* STAR_CARD_CSS_END */