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(v5.0.2): Pro that stays on, Remote that starts, an Editor that opens ready, Pinokio models without a second download

mrbizarro8089f9e56d7a
diff --git a/README.md b/README.md
index 6bf2b9d..bc25543 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 it still installs with one click through Pinokio. It 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: v5.0.1.** Made by Mr Bizarro.
+**Current release: v5.0.2.** Made by Mr Bizarro.
## Why Phosphene
diff --git a/VERSION b/VERSION
index 6b244dc..a1ef0ca 100644
--- a/VERSION
+++ b/VERSION
@@ -1 +1 @@
-5.0.1
+5.0.2
diff --git a/docs/CHANGELOG_5.0.2.md b/docs/CHANGELOG_5.0.2.md
new file mode 100644
index 0000000..02e3e4b
--- /dev/null
+++ b/docs/CHANGELOG_5.0.2.md
@@ -0,0 +1,32 @@
+# Phosphene 5.0.2
+
+**Pro that stays on, Remote that starts, and a clearer way back when something goes wrong.** Nothing that was free was taken away.
+
+## Pro (optional, paid) in the Pinokio install
+
+- **Pro stays on.** An unreadable saved licence is never treated as "no licence". Settings > Pro always shows your saved licence, also while Pro is off, and a paid renewal switches Pro back on by itself, also after a restart.
+- **One Mac, both installs.** The Mac app and Pinokio on the same Mac share one place on your key. Activating in one no longer switches off the other. "Deactivate this Mac" frees the whole Mac.
+- **Honest activation.** If the pass cannot be saved, activation is not reported as done, the key you typed stays in the box, and the server slot is given back.
+- **No late surprises.** A slow check that finishes after you deactivated or changed key can no longer turn Pro back on.
+- **Settings > Pro keeps the key box** when Pro comes from the Mac app's pass, so you can activate this install on its own.
+
+## iPhone Remote
+
+- **Remote setup shows what it is doing:** downloading, checking, a clear error with Try again, and "restart Phosphene" when new parts need it.
+- **Pro parts update safely.** The previous working part is kept and restored if the new one fails to import or start.
+
+## Editor
+
+- **The Editor opens on an empty timeline** you can drag clips into, with no start screen in the way. The header says "not saved yet" until a clip lands, then "saved". Nothing is written to disk before that.
+
+## Everywhere in the app
+
+- **One purple Pro tag** beside the wordmark, wherever Pro is shown. The Support button is easier to find.
+- **Volume in the play bar.** A speaker and slider sit next to the time in the viewer, also full screen. Press `M` to mute.
+- **Reuse from Pinokio.** If Pinokio already holds a model or adapter, Phosphene offers to use it first: it is cloned on your disk, so there is no download and no extra space. Settings > Models has a "Reuse from Pinokio" button on each model, and Upscale & Face Fix says "Use it from your Pinokio install" when its adapter is missing.
+- **Set up Remote** is a step you can follow: it shows the pairing code or QR once Remote is on.
+- **Free users see what Pro adds:** a small "Pro" mark on Remote Control, and Faster Flex Turbo is listed as a Pro option with a line saying what it does.
+
+## Free
+
+- Nothing was taken away from Free. The Editor start, the volume control and Reuse from Pinokio are for everyone.
diff --git a/mlx_ltx_panel.py b/mlx_ltx_panel.py
index 94ef25c..7c6963b 100644
--- a/mlx_ltx_panel.py
+++ b/mlx_ltx_panel.py
@@ -5726,6 +5726,44 @@ def _repos() -> list[dict]:
return list(_REQUIRED.get("repos", []))
+# ---- Reuse a Pinokio install's model (next update, owner test 6 Nov) -----------
+import pinokio_reuse as _pkr
+
+
+def pinokio_offer_for(key: str) -> dict | None:
+ """{bytes, same_volume} when a Pinokio install holds this pack whole and this studio does not."""
+ repo = next((r for r in _repos() if r.get("key") == key), None)
+ if not repo:
+ return None
+ try:
+ if _repo_complete(repo):
+ return None
+ src = _pkr.pack_source(repo, _pkr.model_roots(MODELS_DIR))
+ if not src:
+ return None
+ return {"bytes": src["bytes"], "same_volume": _pkr.same_volume(Path(src["dir"]), repo_dir(repo))}
+ except Exception:
+ return None
+
+
+def pinokio_reuse_pack(key: str) -> tuple[dict, int]:
+ repo = next((r for r in _repos() if r.get("key") == key), None)
+ if not repo:
+ return {"error": "unknown model"}, 400
+ reason = model_path_problem(repo, write=True)
+ if reason:
+ return {"error": reason}, 409
+ if app_models_owns(repo):
+ return {"error": "This model is already downloading in the background."}, 409
+ src = _pkr.pack_source(repo, _pkr.model_roots(MODELS_DIR))
+ if not src:
+ return {"error": "Pinokio does not hold this model (any more)."}, 404
+ ok, msg = _pkr.clone_pack(src, repo_dir(repo))
+ if not ok:
+ return {"error": msg}, 409
+ return {"ok": True, "key": key, "complete": _repo_complete(repo)}, 200
+
+
def repo_dir(repo: dict) -> Path:
"""Where one required_files.json repo lives on disk.
@@ -28530,9 +28568,25 @@ def _sb_board_summary(board: dict) -> dict:
# dropped it from the list entirely. A `Path.is_file()` stat, not a
# parse: this is read once per board on every list.
"has_timeline": _sb_has_timeline(board),
+ # What is ON the timeline, for the Editor's sequence menu (`clips`
+ # above only counts the storyboard's own shots).
+ **_sb_edit_facts(board),
}
+def _sb_edit_facts(board: dict) -> dict:
+ out = {"edit_clips": 0, "edit_duration": 0.0}
+ try:
+ ep = _sbe_import().edit_path(_sbe_board_dir(board.get("id")))
+ if ep.is_file():
+ doc = json.loads(ep.read_text(encoding="utf-8"))
+ out["edit_clips"] = len(doc.get("clips") or [])
+ out["edit_duration"] = float(doc.get("duration") or 0.0)
+ except Exception: # noqa: BLE001
+ pass
+ return out
+
+
def _sb_has_timeline(board: dict) -> bool:
"""Cheap and never fatal — a board summary must survive an editor
module that failed to import (see `_sbe_import`'s own rule: that is a
@@ -28546,6 +28600,24 @@ def _sb_has_timeline(board: dict) -> bool:
return False
+def _sb_is_blank(board: dict) -> bool:
+ """The Editor opens on an empty timeline (a board it made itself, flagged
+ `blank_sequence`). Until it holds a shot or a saved timeline it is not a
+ film: no list, tab count or picker shows it."""
+ if not board.get("blank_sequence") or (board.get("shots") or []):
+ return False
+ # Opening the Editor writes an edit.json with no clips in it. That is
+ # still blank; a clip on the track, or a second save, is not.
+ try:
+ ep = _sbe_import().edit_path(_sbe_board_dir(board.get("id")))
+ if not ep.is_file():
+ return True
+ doc = json.loads(ep.read_text(encoding="utf-8"))
+ return not (doc.get("clips") or []) and int(doc.get("revision") or 0) <= 1
+ except Exception: # noqa: BLE001
+ return False
+
+
def _sb_all_summaries() -> list:
"""The one-line-per-board payload /status carries.
@@ -28563,6 +28635,9 @@ def _sb_all_summaries() -> list:
board = storyboard.load_storyboard(STATE_DIR, r["id"])
except Exception:
continue
+ if _sb_is_blank(board):
+ # An Editor sequence nobody has put a clip on yet is not a film.
+ continue
out.append(_sb_board_summary(board))
return out
@@ -38994,6 +39069,20 @@ def _face_fix_offers(board_id: str, edit: dict) -> list[dict]:
return out
+def face_fix_pinokio_offer() -> dict | None:
+ """The upscaler adapter is not here but a Pinokio install holds it: {repo_key, bytes} to offer first."""
+ o = pinokio_offer_for("ic_upscale_x2")
+ return dict(o, repo_key="ic_upscale_x2", name="LTX-2.5 Pixel Spatial Upscaler adapter") if o else None
+
+
+def _face_fix_missing_sentence() -> str:
+ if face_fix_pinokio_offer():
+ return (f"{FACE_FIX_NAME} needs the LTX-2.5 Pixel Spatial Upscaler adapter (0.3 GB). It is already in "
+ "your Pinokio install: use it from there (no download), or download it in Settings → Models.")
+ return (f"{FACE_FIX_NAME} needs the LTX-2.5 Pixel Spatial Upscaler adapter (0.3 GB). "
+ "Open Settings → Models and download it.")
+
+
def face_fix_adapter_ready() -> bool:
"""Is the Pixel Spatial Upscaler adapter Upscale & Face Fix needs on disk?"""
adapter_path = CURATED_LORAS["upscale_x2"].get("local_path") or ""
@@ -39010,6 +39099,10 @@ def extend_face_fix_refusal(params: dict) -> str | None:
return None
if face_fix_adapter_ready():
return None
+ if face_fix_pinokio_offer():
+ return (f"“Also run {FACE_FIX_NAME} after” needs the LTX-2.5 Pixel Spatial Upscaler adapter, which is "
+ "already in your Pinokio install: use it from there (no download), download it in "
+ "Settings → Models, or uncheck the box to render the Extend alone.")
return (f"“Also run {FACE_FIX_NAME} after” needs the LTX-2.5 Pixel Spatial "
"Upscaler adapter (0.3 GB), which isn't on this Mac yet. Download it "
"in Settings → Models, or uncheck the box to render the Extend alone.")
@@ -39032,9 +39125,8 @@ def queue_face_fix(source_path: str, *, board_id: str = "",
if board_id and not (_sbe_board_dir(board_id) / "storyboard.json").is_file():
return {"ok": False, "error": "unknown film"}
if not face_fix_adapter_ready():
- return {"ok": False, "code": "pack_missing",
- "error": f"{FACE_FIX_NAME} needs the LTX-2.5 Pixel Spatial Upscaler "
- "adapter (0.3 GB). Open Settings → Models and download it."}
+ return {"ok": False, "code": "pack_missing", "error": _face_fix_missing_sentence(),
+ "pinokio": face_fix_pinokio_offer()}
sw, sh = _probe_video_dims(str(src))
src_frames = _probe_video_frames(str(src)) or 0
# VA-22: the target canvas, so the client's queued-toast can say what
@@ -42805,8 +42897,12 @@ def run_job_inner(job: dict) -> None:
raise RenderRefused(
"pack_missing",
f"{FACE_FIX_NAME} needs the LTX-2.5 Pixel Spatial Upscaler adapter, which "
- "isn't downloaded on this Mac yet. Open Settings → Models and "
- "download it, then render again.")
+ "isn't downloaded on this Mac yet. " + (
+ "It is already in your Pinokio install: open Settings → Models and choose "
+ "Reuse from Pinokio (no download), then render again."
+ if face_fix_pinokio_offer() else
+ "Open Settings → Models and download it, then render again.")
+ )
sw, sh = _probe_video_dims(src)
if not (sw and sh):
raise RuntimeError(f"could not read the size of {source.name}")
@@ -47519,6 +47615,32 @@ class Handler(BaseHTTPRequestHandler):
self._json({"ok": True})
return
+ if action == "new-sequence":
+ # The Editor opens straight into an empty timeline. Reuse the
+ # blank one if it is still there, so opening the Editor ten
+ # times leaves one board, not ten.
+ board = None
+ try:
+ for r in storyboard.list_storyboards(STATE_DIR):
+ cand = storyboard.load_storyboard(STATE_DIR, r["id"])
+ if _sb_is_blank(cand):
+ board = cand
+ break
+ except Exception:
+ board = None
+ if board is None:
+ title = (f("title", "") or "").strip() or \
+ "Sequence " + time.strftime("%-d %b")
+ board = storyboard.new_storyboard(_sb_new_id(title), title)
+ board["blank_sequence"] = True
+ board["policy"] = _sb_policy_for(
+ get_settings().get("storyboard_draft_quality", "quick"),
+ get_settings().get("storyboard_final_quality", "standard"))
+ storyboard.save_storyboard(STATE_DIR, board)
+ self._json({"ok": True, "id": board["id"],
+ "title": board.get("title") or ""})
+ return
+
if action == "duplicate":
# FILM-43: the board list had no way to branch off a plan —
# only rename (via the ordinary save route) and delete. A
@@ -49741,11 +49863,8 @@ def page(theme: str = "") -> str:
# different panel: a STATE_DIR outside the install root is by definition
# not the install's own films. Loud badge, and the tab title changes too —
# a background tab is a title and a favicon and nothing else.
- # The edition label (PHOSPHENE_EDITION=pro, set by the Mac app). A label
- # and a CSS hook (body[data-edition]) - no paid code rides on it.
- if _dist.is_pro():
- profile_badge += ('<span class="profile-badge edition-badge" '
- 'title="Phosphene Pro">Pro</span>')
+ # No edition badge (owner, 6 Nov 2026): Pro shows as the one gradient PRO pill beside the
+ # wordmark (#proMark, filled by proStatusRefresh); body[data-edition] stays as the CSS hook.
is_test = not _state_dir_is_native()
if is_test:
profile_badge = (
diff --git a/panel/routes_meta.py b/panel/routes_meta.py
index d72e11c..47cedae 100644
--- a/panel/routes_meta.py
+++ b/panel/routes_meta.py
@@ -290,6 +290,13 @@ def get_models(h, parsed) -> None:
)
# 4.20: packs a fresh install queued for the background (empty otherwise).
payload["deferred_pending"] = P.deferred_pending_keys()
+ # Next update: a pack this studio lacks but a Pinokio install of Phosphene holds whole.
+ for row in payload["repos"]:
+ if row.get("complete"):
+ continue
+ _pk = P.pinokio_offer_for(row.get("key"))
+ if _pk:
+ row["pinokio"] = _pk
# Mac app: the packs the app itself is fetching (absent under Pinokio).
_app = P.app_models_state()
if _app is not None:
diff --git a/panel/routes_models.py b/panel/routes_models.py
index 39ce0a3..8d72fb9 100644
--- a/panel/routes_models.py
+++ b/panel/routes_models.py
@@ -22,6 +22,16 @@ def post_models_video(h, path, qs, ctype) -> None:
h._json(payload, code)
+@post("/models/reuse-pinokio")
+def post_models_reuse_pinokio(h, path, qs, ctype) -> None:
+ _rb = h._read_form_body()
+ if _rb is None:
+ return
+ body, form = _rb
+ key = (form.get("repo_key", [""])[0] or "").strip()
+ h._json(*P.pinokio_reuse_pack(key))
+
+
@post("/models/download")
def post_models_download(h, path, qs, ctype) -> None:
_rb = h._read_form_body()
diff --git a/panel/routes_queue.py b/panel/routes_queue.py
index 54e8164..dbcd22d 100644
--- a/panel/routes_queue.py
+++ b/panel/routes_queue.py
@@ -878,7 +878,8 @@ def post_run(h, path, qs, ctype) -> None:
# not discovered in the log after a long Extend render.
refusal = P.extend_face_fix_refusal(job["params"])
if refusal:
- h._json({"error": refusal, "code": "pack_missing"}, 400); return
+ h._json({"error": refusal, "code": "pack_missing",
+ "pinokio": P.face_fix_pinokio_offer()}, 400); return
# Upscale ×2 above QHD exhausted 96 GB + swap: refused before it queues.
_up = job["params"]
if _up.get("mode") == "upscale" and _up.get("upscale_source_path"):
diff --git a/panel/routes_remote.py b/panel/routes_remote.py
index bede767..f8e5237 100644
--- a/panel/routes_remote.py
+++ b/panel/routes_remote.py
@@ -24,11 +24,52 @@ def _mod():
def get_remote_state(h, parsed) -> None:
m = _mod()
if m is None:
- h._json({"ok": True, "available": False, "pro": False, "requires_pro": True})
+ h._json(_unavailable_state())
return
h._json(m.page_state())
+def _unavailable_state() -> dict:
+ """No Remote module is loaded. Say WHY, with the real Pro status: a member sees the install
+ state (checking, downloading, error with next step, restart needed), never a dead page."""
+ try:
+ pro = bool((P.pro_status() or {}).get("active"))
+ except Exception: # noqa: BLE001
+ pro = False
+ doc = {"ok": True, "available": False, "pro": pro, "requires_pro": not pro}
+ if P._dist.is_mac_app():
+ doc["parts"] = {"managed_by": "mac_app"}
+ # Pro with no Remote module in a Mac-app studio = Pro was switched on after this engine
+ # started: the running engine is the Free one. The page offers "Set up Remote", which asks
+ # the app to start the Pro engine (no restart of Phosphene by hand).
+ doc["needs_engine_start"] = bool(pro)
+ return doc
+ try:
+ import pro_licence
+ import pro_parts
+ parts = pro_parts.status()
+ lic = pro_licence.status()
+ except Exception: # noqa: BLE001
+ return doc
+ doc["parts"] = parts
+ doc["licensed_here"] = bool(lic.get("licensed"))
+ if pro and not lic.get("licensed"):
+ doc["needs_licence"] = True
+ doc["next"] = "Paste your licence key in Settings > Pro of this Studio (it does not use another seat). Remote Control's components are fetched with your own key."
+ elif lic.get("storage_problem") or lic.get("note") and not pro:
+ doc["next"] = lic.get("note")
+ return doc
+
+
+@post("/remote/parts_retry")
+def post_parts_retry(h, path, qs, ctype) -> None:
+ if _mod() is not None:
+ h._json({"ok": True, "started": False, "message": "Remote Control is already installed."})
+ return
+ import pro_parts
+ h._json(pro_parts.retry_now())
+
+
def _do(action):
def handler(h, path, qs, ctype) -> None:
m = _mod()
diff --git a/pinokio_reuse.py b/pinokio_reuse.py
new file mode 100644
index 0000000..2aed747
--- /dev/null
+++ b/pinokio_reuse.py
@@ -0,0 +1,140 @@
+"""Reuse a model pack that a Pinokio install of Phosphene already holds (no download, no extra disk).
+
+Read-only on Pinokio: the files are cloned (APFS copy-on-write, same volume) into this studio's own
+models folder; Pinokio's copy is never touched. Stdlib only. Never runs inside Pinokio itself (its models
+folder IS the source, so nothing is "elsewhere").
+"""
+from __future__ import annotations
+
+import json
+import os
+import subprocess
+from pathlib import Path
+
+MIN_BYTES = 1 # a declared file must exist and not be empty
+
+
+def pinokio_homes(env=None, home=None) -> list[Path]:
+ env = os.environ if env is None else env
+ me = Path(home) if home else Path.home()
+ out: list[Path] = []
+ if env.get("PHOSPHENE_PINOKIO_HOME"):
+ out.append(Path(env["PHOSPHENE_PINOKIO_HOME"]))
+ for cfg in (me / ".pinokio/config.json", me / "Library/Application Support/pinokio/config.json"):
+ try:
+ h = json.loads(cfg.read_text()).get("home")
+ if h:
+ out.append(Path(h))
+ except (OSError, ValueError, AttributeError):
+ pass
+ out.append(me / "pinokio")
+ try:
+ out += sorted(Path("/Volumes").glob("*/pinokio"))
+ except OSError:
+ pass
+ seen, uniq = set(), []
+ for p in out:
+ try:
+ k = str(p.resolve())
+ except OSError:
+ continue
+ if k not in seen and p.is_dir():
+ seen.add(k)
+ uniq.append(Path(k))
+ return uniq
+
+
+def model_roots(own_models: Path, env=None, home=None) -> list[Path]:
+ """Every Pinokio `mlx_models` folder this Mac has, except this studio's own."""
+ own = None
+ try:
+ own = own_models.resolve()
+ except OSError:
+ pass
+ roots = []
+ for h in pinokio_homes(env, home):
+ api = h / "api"
+ try:
+ apps = sorted(api.glob("phosphene*.git"))
+ except OSError:
+ continue
+ for a in apps:
+ m = a / "mlx_models"
+ try:
+ r = m.resolve()
+ except OSError:
+ continue
+ if m.is_dir() and r != own and r not in roots:
+ roots.append(r)
+ return roots
+
+
+def _size(p: Path) -> int:
+ try:
+ return p.stat().st_size
+ except OSError:
+ return -1
+
+
+def pack_source(repo: dict, roots: list[Path]) -> dict | None:
+ """The first Pinokio folder that holds every declared file of `repo`, or None."""
+ parts = Path(str(repo.get("local_dir") or "")).parts
+ if not parts or parts[0] != "mlx_models":
+ return None
+ rel = Path(*parts[1:]) if len(parts) > 1 else Path(".")
+ files = list(repo.get("files") or [])
+ if not files:
+ return None
+ for root in roots:
+ d = root / rel
+ sizes = [_size(d / f) for f in files]
+ if all(s >= MIN_BYTES for s in sizes):
+ return {"dir": str(d), "bytes": sum(sizes), "files": files}
+ return None
+
+
+def _nearest_dev(p: Path) -> int | None:
+ q = p
+ while not q.exists():
+ if q.parent == q:
+ return None
+ q = q.parent
+ return q.stat().st_dev
+
+
+def same_volume(src: Path, dest: Path) -> bool:
+ try:
+ return src.stat().st_dev == _nearest_dev(dest)
+ except OSError:
+ return False
+
+
+def clone_pack(src: dict, dest: Path) -> tuple[bool, str]:
+ """Clone the declared files into `dest`. Files already there stay (an existing file is never replaced)."""
+ s = Path(src["dir"])
+ if not same_volume(s, dest):
+ return False, ("The copy in Pinokio is on another drive, so using it would take new disk space. "
+ "Download it instead, or move Pinokio's models onto this drive.")
+ dest.mkdir(parents=True, exist_ok=True)
+ done: list[Path] = []
+ for f in src["files"]:
+ to = dest / f
+ if to.exists() and _size(to) >= MIN_BYTES:
+ continue
+ to.parent.mkdir(parents=True, exist_ok=True)
+ tmp = to.with_name(to.name + ".reuse.partial")
+ try:
+ tmp.unlink()
+ except OSError:
+ pass
+ r = subprocess.run(["/bin/cp", "-c", str(s / f), str(tmp)], capture_output=True, text=True)
+ if r.returncode != 0:
+ for p in done + [tmp]:
+ try:
+ p.unlink()
+ except OSError:
+ pass
+ return False, "Could not reuse the file from Pinokio (" + (r.stderr.strip()[:120] or "copy failed") + ")."
+ os.replace(tmp, to)
+ done.append(to)
+ return True, ""
diff --git a/pro_licence.py b/pro_licence.py
index b71832c..b5e0060 100644
--- a/pro_licence.py
+++ b/pro_licence.py
@@ -10,9 +10,11 @@ thing the app does, against the same server, with the same rules:
POST https://phosphene.video/api/v1/licenses/deactivate license_key, instance_id
* One Mac per key: the server decides. The instance name ends with this Mac's device id (the same
- id as the app's), and the server gives the Mac's older slot back when the same Mac activates
- again. So a Mac that already has Pro through the Mac app is NOT activated a second time here
- (it would take the app's slot): the app's token file is read instead, see pro_token.py.
+ id as the app's). One Mac may hold two installations of the product, the Mac app and this Studio:
+ the server counts Macs, not installations, and each installation keeps its OWN place on the key,
+ so activating here never invalidates the Mac app (and the other way round). The Mac app's token
+ file is still read when this Studio has no licence of its own (Pro perks work), but only a licence
+ of its own can download Remote's components and renew by itself while the app is closed.
* The server answers every validate with a token (valid <= 14 days). It is written next to the
record and read by pro_token.py, which verifies the signature and the device on every call.
Nothing here grants Pro: a hand-written record or token file is checked like any other.
@@ -21,19 +23,24 @@ thing the app does, against the same server, with the same rules:
* Revoked / refunded / expired / deactivated elsewhere: an explicit answer, the token file is
removed at once and the Studio reads Free.
* Renewal: at start and every 6 hours the Studio validates again when the last good check is
- older than a day or the token has under 7 days left.
+ older than a day or the token has under 7 days left. A licence that was off (expired, refused)
+ is asked again with a bounded back-off, so a paid renewal turns Pro back on without any action.
+ Identity changes (activate, deactivate) are serialised; a server reply that arrives after the
+ identity changed is discarded, never written.
The licence key is kept in state/pro_licence.json (0600, replaced atomically), like the app keeps
its record (the app uses the Keychain). It is never logged and never sent anywhere but the server.
"""
from __future__ import annotations
+import calendar
import json
import os
import re
import socket
import threading
import time
+import uuid
import urllib.error
import urllib.parse
import urllib.request
@@ -51,12 +58,18 @@ RECORD_NAME = "pro_licence.json"
MESSAGES = {
"unreachable": "Could not reach the licence server. Check your internet connection and try again.",
"empty": "Paste your licence key first.",
- "via_app": "Phosphene Pro is already on through the Phosphene Mac app on this Mac, so there is nothing to activate here.",
+ "via_app_only": "Pro is on through the Phosphene Mac app on this Mac. To use Remote Control from this Studio too, paste your licence key here (it does not use another seat).",
"no_device": "This Mac could not be identified, so a licence cannot be activated here.",
"other_mac": "This licence was activated on another Mac. Deactivate it there, or use a key for this Mac.",
"revoked": "This licence has been disabled. Contact support for help.",
"expired": "This licence has expired. Renew it to keep Pro.",
- "grace_over": "The licence could not be checked for two weeks. Connect to the internet to renew it.",
+ "grace_over": "The licence could not be checked for two weeks. Your key is still saved: connect to the internet and press Check now.",
+ "clock": "This Mac's clock looks wrong (the Pro pass is dated in the future). Fix the date and time, then press Check now.",
+ "pass_unsaved": "Your licence is active, but this Mac could not save its Pro pass (is the disk full or the folder read-only?). Free some space, then press Check now. Your key is kept.",
+ "record_unsaved": "The licence could not be saved on this Mac (is the disk full or the folder read-only?). Nothing was changed. Fix that and try again.",
+ "unreadable": "The saved licence on this Mac cannot be read right now (permissions or a damaged file). Your key is not lost: fix the folder permissions or paste the key again.",
+ "superseded": "The licence changed while it was being checked, so that answer was ignored. Press Check now.",
+ "pass_invalid": "The licence server answered, but its Pro pass is not valid for this Mac. Press Check now; if it persists, contact support.",
}
@@ -84,13 +97,16 @@ def token_path() -> Path:
def _write_private(path: Path, text: str) -> bool:
- """Replace `path` atomically with `text`, readable by this user only."""
- tmp = path.with_name(".%s.%d.tmp" % (path.name, os.getpid()))
+ """Replace `path` atomically with `text`, readable by this user only. Every attempt has its own
+ temporary name, so two writers never share one."""
+ tmp = path.with_name(".%s.%d.%s.tmp" % (path.name, os.getpid(), uuid.uuid4().hex[:8]))
try:
path.parent.mkdir(parents=True, exist_ok=True)
- fd = os.open(str(tmp), os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
+ fd = os.open(str(tmp), os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
with os.fdopen(fd, "w", encoding="utf-8") as fh:
fh.write(text)
+ fh.flush()
+ os.fsync(fh.fileno())
os.replace(tmp, path)
return True
except OSError:
@@ -101,27 +117,53 @@ def _write_private(path: Path, text: str) -> bool:
return False
-def _remove(path: Path) -> None:
+def _remove(path: Path) -> bool:
try:
path.unlink()
except FileNotFoundError:
pass
except OSError:
- pass
+ return False
+ return True
-def load() -> dict | None:
+def read_record() -> tuple[dict | None, str | None]:
+ """(record, problem). problem: None = readable or genuinely absent; 'unreadable' = the file is
+ there but cannot be read; 'corrupt' = it is there but is not a licence record."""
try:
- d = json.loads(record_path().read_text(encoding="utf-8"))
- except (OSError, ValueError):
- return None
- return d if isinstance(d, dict) and d.get("key") and d.get("instance_id") else None
+ raw = record_path().read_text(encoding="utf-8")
+ except FileNotFoundError:
+ return None, None
+ except OSError:
+ return None, "unreadable"
+ try:
+ d = json.loads(raw)
+ except ValueError:
+ return None, "corrupt"
+ if isinstance(d, dict) and d.get("key") and d.get("instance_id"):
+ return d, None
+ return None, "corrupt"
+
+
+def load() -> dict | None:
+ return read_record()[0]
def _save(rec: dict) -> bool:
return _write_private(record_path(), json.dumps(rec, sort_keys=True, indent=1))
+# One lock serialises every identity change (activate, deactivate, committing an answer). `_gen`
+# counts identity changes: a server reply is only written when the identity it was asked about is
+# still the saved one.
+_op = threading.RLock()
+_gen = [0]
+
+
+def _same(a: dict | None, b: dict | None) -> bool:
+ return bool(a and b and a.get("key") == b.get("key") and a.get("instance_id") == b.get("instance_id"))
+
+
# ----------------------------------------------------------------------------- the server
class Offline(Exception):
@@ -179,8 +221,8 @@ def instance_name(device: str) -> str:
# ----------------------------------------------------------------------------- actions
def _app_token_valid() -> bool:
- """Is Pro already on this Mac through the Mac app's token (so a second activation would take
- the app's slot)?"""
+ """Is Pro on this Mac through the Mac app's token (a borrowed pass: it gives the perks that
+ check the pass, but it has no licence record here to renew or to fetch Remote's parts with)?"""
env = {"HOME": os.environ.get("HOME", ""), "PHOSPHENE_HOME": os.environ.get("PHOSPHENE_HOME", "")}
for t in pro_token.app_tokens(env):
v = pro_token.verify_signature(t)
@@ -189,39 +231,67 @@ def _app_token_valid() -> bool:
return False
+def _backup_corrupt() -> None:
+ """A damaged record is set aside, never silently overwritten."""
+ try:
+ os.replace(record_path(), record_path().with_name("%s.damaged-%d" % (RECORD_NAME, int(time.time()))))
+ except OSError:
+ pass
+
+
+def _deactivate_remote(key: str, iid: str, opener) -> bool:
+ """Give a server slot back. True only when the server confirmed (or said it never existed)."""
+ try:
+ # single=1: give back ONLY the instance this attempt just made. The Mac app on this Mac keeps its place.
+ r = _post("deactivate", {"license_key": key, "instance_id": iid, "single": "1"}, opener)
+ except Offline:
+ return False
+ return r.get("deactivated") is True or "not found" in str(r.get("error") or "").lower()
+
+
def activate(key: str, opener=None, now=None) -> dict:
- """Activate `key` on this Mac and fetch the first token. {ok, message, ...status()}."""
+ """Activate `key` on this Mac and fetch the first token. {ok, message, ...status()}.
+ ok is True only when the record AND the Pro pass are saved. On any failure the typed key is
+ kept by the caller (`keep_key`); the server slot is given back or, if that cannot be confirmed,
+ reused by the next attempt from this Mac (the server gives a Mac its own slot back)."""
key = (key or "").strip()
if not key or len(key) > 128:
- return {"ok": False, "message": MESSAGES["empty"], **status()}
+ return {"ok": False, "message": MESSAGES["empty"], "keep_key": True, **status()}
dev = pro_token.device_id()
if not dev:
- return {"ok": False, "message": MESSAGES["no_device"], **status()}
- if _app_token_valid() and not load():
- return {"ok": False, "message": MESSAGES["via_app"], **status()}
- old = load()
- try:
- r = _post("activate", {"license_key": key, "instance_name": instance_name(dev)}, opener)
- except Offline:
- return {"ok": False, "message": MESSAGES["unreachable"], **status()}
- inst = r.get("instance") or {}
- if not (r.get("activated") is True and inst.get("id") and r.get("meta")):
- return {"ok": False, "message": _human(r.get("error")), **status()}
- t = int(now if now is not None else time.time())
- rec = {"key": key, "instance_id": str(inst["id"]), "device": dev, "status": "active", "last_validated": t,
- "variant": str((r.get("meta") or {}).get("variant_name") or ""),
- "expires_at": (r.get("license_key") or {}).get("expires_at"), "token_error": None}
- if not _save(rec):
- # not durable: give the slot back rather than lose it at the next start
+ return {"ok": False, "message": MESSAGES["no_device"], "keep_key": True, **status()}
+ with _op:
+ rec0, prob = read_record()
+ if prob == "unreadable":
+ return {"ok": False, "message": MESSAGES["unreadable"], "keep_key": True, **status()}
+ if prob == "corrupt":
+ _backup_corrupt()
try:
- _post("deactivate", {"license_key": key, "instance_id": rec["instance_id"]}, opener)
+ r = _post("activate", {"license_key": key, "instance_name": instance_name(dev)}, opener)
except Offline:
- pass
- return {"ok": False, "message": "The licence could not be saved on this Mac (is the disk full?).", **status()}
- if old and old.get("key") == key and old.get("instance_id") != rec["instance_id"]:
- pass # the server already gave the old slot of this Mac back
- out = validate(opener=opener, now=t)
- return {**out, "message": out.get("message") or "Pro is active on this Mac."}
+ return {"ok": False, "message": MESSAGES["unreachable"], "keep_key": True, **status()}
+ inst = r.get("instance") or {}
+ if not (r.get("activated") is True and inst.get("id") and r.get("meta")):
+ return {"ok": False, "message": _human(r.get("error")), "keep_key": True, **status()}
+ t = int(now if now is not None else time.time())
+ rec = {"key": key, "instance_id": str(inst["id"]), "device": dev, "status": "active", "last_validated": t,
+ "last_checked": t, "variant": str((r.get("meta") or {}).get("variant_name") or ""),
+ "expires_at": (r.get("license_key") or {}).get("expires_at"), "token_error": None}
+ if not _save(rec):
+ gave_back = _deactivate_remote(key, rec["instance_id"], opener)
+ msg = MESSAGES["record_unsaved"] + ("" if gave_back else " (Your place on the key may still be held by this Mac; trying again here reuses it.)")
+ return {"ok": False, "message": msg, "keep_key": True, "slot_released": gave_back, **status()}
+ _gen[0] += 1
+ out = validate(opener=opener, now=t)
+ if out.get("ok"):
+ return {**out, "message": out.get("message") or "Pro is active on this Mac."}
+ out["keep_key"] = True
+ if out.get("storage_error") is None and not out.get("offline") and not out.get("superseded") and out.get("refused"):
+ # the server refused the fresh slot straight away: nothing to keep
+ _remove(record_path())
+ _gen[0] += 1
+ out = {**out, **status()}
+ return out
def _human(error) -> str:
@@ -240,14 +310,18 @@ def _human(error) -> str:
def validate(opener=None, now=None) -> dict:
- """Ask the server again and store the fresh token. An explicit 'no' removes the token."""
- rec = load()
+ """Ask the server again and store the fresh token. An explicit 'no' removes the token.
+ The answer is written only if the identity it was asked about is still the saved one."""
+ rec, prob = read_record()
+ if prob:
+ return {"ok": False, "message": MESSAGES["unreadable"], "storage_error": prob, **status()}
if not rec:
return {"ok": False, "message": None, **status()}
dev = pro_token.device_id()
if rec.get("device") != dev:
return {"ok": False, "message": MESSAGES["other_mac"], **status()}
t = int(now if now is not None else time.time())
+ snap, gen = dict(rec), _gen[0]
form = {"license_key": rec["key"], "instance_id": rec["instance_id"]}
bundle = current_bundle(opener)
if bundle and dev:
@@ -256,79 +330,154 @@ def validate(opener=None, now=None) -> dict:
try:
r = _post("validate", form, opener)
except Offline:
- return {"ok": False, "message": MESSAGES["unreachable"], **status()}
+ return {"ok": False, "offline": True, "message": MESSAGES["unreachable"], **status()}
lk = r.get("license_key") or {}
- if r.get("valid") is True and r.get("meta") and lk:
- rec.update(status=str(lk.get("status") or "active"), expires_at=lk.get("expires_at"), last_validated=t,
- variant=str((r.get("meta") or {}).get("variant_name") or rec.get("variant") or ""))
- tok = r.get("pro_token")
- if tok:
- if _write_private(token_path(), str(tok).strip() + "\n"):
- rec["token_error"] = None
+ granted = r.get("valid") is True and r.get("meta") and lk
+ if not granted and r.get("valid") is None and not r.get("error") and not lk:
+ return {"ok": False, "offline": True, "message": MESSAGES["unreachable"], **status()} # an empty answer is not a verdict
+ with _op:
+ cur, prob = read_record()
+ if gen != _gen[0] or prob or not _same(cur, snap):
+ # deactivated, replaced or re-activated while the server was thinking: this answer is about the past
+ return {"ok": False, "superseded": True, "message": MESSAGES["superseded"], **status()}
+ rec = dict(cur)
+ if granted:
+ rec.update(status=str(lk.get("status") or "active"), expires_at=lk.get("expires_at"), last_validated=t,
+ last_checked=t, variant=str((r.get("meta") or {}).get("variant_name") or rec.get("variant") or ""))
+ rec.pop("refused_since", None)
+ tok = r.get("pro_token")
+ failure = None
+ if tok:
+ text = str(tok).strip()
+ if not _write_private(token_path(), text + "\n"):
+ rec["token_error"], failure = "store_unavailable", ("pass_unsaved", MESSAGES["pass_unsaved"])
+ elif not pro_token.studio_token_valid():
+ rec["token_error"], failure = "pass_invalid", ("pass_invalid", MESSAGES["pass_invalid"])
+ else:
+ rec["token_error"] = None
else:
- rec["token_error"] = "store_unavailable"
- else:
- rec["token_error"] = str(r.get("pro_token_error") or "no_token")
- if rec["token_error"] in ("instance_bound_to_another_mac", "licence_expired"):
- _remove(token_path())
+ rec["token_error"] = str(r.get("pro_token_error") or "no_token")
+ if rec["token_error"] in ("instance_bound_to_another_mac", "licence_expired"):
+ _remove(token_path())
+ if not _save(rec):
+ return {"ok": False, "storage_error": "record", "message": MESSAGES["record_unsaved"], **status()}
+ if failure:
+ return {"ok": False, "storage_error": failure[0], "message": failure[1], **status()}
+ return {"ok": True, "message": None, **status()}
+ # the server said no: refunded, disabled, expired, or this slot was given up elsewhere
+ rec.update(status=str(lk.get("status") if lk.get("status") not in (None, "active") else "invalid"),
+ token_error="refused", last_checked=t)
+ rec.setdefault("refused_since", t)
+ gone = _remove(token_path())
_save(rec)
- return {"ok": True, "message": None, **status()}
- if r.get("valid") is None and not r.get("error") and not lk:
- return {"ok": False, "message": MESSAGES["unreachable"], **status()} # an empty answer is not a verdict
- # the server said no: refunded, disabled, expired, or this slot was given up elsewhere
- rec.update(status=str(lk.get("status") if lk.get("status") not in (None, "active") else "invalid"), token_error="refused")
- _remove(token_path())
- _save(rec)
- return {"ok": False, "message": _human(r.get("error")) if r.get("error") else MESSAGES["revoked"], **status()}
+ msg = _human(r.get("error")) if r.get("error") else MESSAGES["revoked"]
+ if not gone:
+ msg += " (The old Pro pass could not be removed from this Mac; it lapses by itself within two weeks.)"
+ return {"ok": False, "refused": True, "message": msg, **status()}
def deactivate(opener=None) -> dict:
"""Give this Mac's place on the key back. The record goes only once the server confirmed it."""
- rec = load()
- if not rec:
- return {"ok": True, "message": None, **status()}
- try:
- r = _post("deactivate", {"license_key": rec["key"], "instance_id": rec["instance_id"]}, opener)
- except Offline:
- return {"ok": False, "message": "Could not reach the licence server, so this Mac was not deactivated. Try again online.", **status()}
- gone = r.get("deactivated") is True or "not found" in str(r.get("error") or "").lower()
- if not gone:
- return {"ok": False, "message": _human(r.get("error")), **status()}
- _remove(record_path())
- _remove(token_path())
- return {"ok": True, "message": "This Mac is deactivated. Pro is off here.", **status()}
+ with _op:
+ rec, prob = read_record()
+ if prob == "unreadable":
+ return {"ok": False, "message": MESSAGES["unreadable"], **status()}
+ if not rec:
+ if prob == "corrupt":
+ _backup_corrupt()
+ return {"ok": True, "message": None, **status()}
+ try:
+ r = _post("deactivate", {"license_key": rec["key"], "instance_id": rec["instance_id"]}, opener)
+ except Offline:
+ return {"ok": False, "message": "Could not reach the licence server, so this Mac was not deactivated. Try again online.", **status()}
+ gone = r.get("deactivated") is True or "not found" in str(r.get("error") or "").lower()
+ if not gone:
+ return {"ok": False, "message": _human(r.get("error")), **status()}
+ _gen[0] += 1
+ ok_rec, ok_tok = _remove(record_path()), _remove(token_path())
+ if not (ok_rec and ok_tok):
+ return {"ok": False, "message": "This Mac was deactivated on the server, but its saved files could not be removed. Remove the Studio's state/pro_* files or restart the Studio.", **status()}
+ out = status()
+ msg = "This Mac is deactivated. Its place on the key is free; you can activate another Mac now."
+ if out.get("pro"):
+ # the Mac app's own pass is a separate file; it is released by the same deactivation on the server
+ # and lapses at its next check (open the Mac app while online), at the latest in 14 days
+ msg += " Pro can still show here for a short while from the Mac app's last pass; it ends at the app's next check."
+ return {"ok": True, "message": msg, **out}
def status() -> dict:
"""What Settings > Pro shows. `via`: 'app' (the Mac app's token), 'studio' (this module's record), or None."""
- rec = load()
+ rec, prob = read_record()
st = pro_token.status()
via = None
if st.get("ok"):
via = "studio" if (rec and pro_token.studio_token_valid()) else ("app" if _app_token_valid() else "studio")
out = {"licensed": bool(rec), "via": via, "pro": bool(st.get("ok")), "reason": st.get("reason"),
- "expires_at": st.get("expires_at"), "variant": (rec or {}).get("variant") or None}
- if rec and not st.get("ok"):
- out["note"] = _note(rec, st)
+ "expires_at": st.get("expires_at"), "variant": (rec or {}).get("variant") or None,
+ "storage_problem": prob, "remote_needs_licence": bool(via == "app" and not rec)}
+ note = _note(rec, st, prob)
+ if note:
+ out["note"] = note
return out
-def _note(rec: dict, st: dict) -> str | None:
+def _note(rec: dict | None, st: dict, prob: str | None = None) -> str | None:
+ if prob:
+ return MESSAGES["unreadable"]
+ if not rec:
+ return MESSAGES["via_app_only"] if st.get("ok") and _app_token_valid() else None
+ if rec.get("token_error") in ("store_unavailable",):
+ return MESSAGES["pass_unsaved"]
+ if rec.get("token_error") == "pass_invalid":
+ return MESSAGES["pass_invalid"]
+ if st.get("ok"):
+ return None
if rec.get("status") not in ("active",):
- return MESSAGES["revoked"] if rec.get("status") == "disabled" else MESSAGES["expired"] if rec.get("status") == "expired" \
- else "This licence is no longer active. Contact support if this is a mistake."
+ if rec.get("status") == "disabled":
+ return MESSAGES["revoked"]
+ if rec.get("status") == "expired":
+ return "Your paid period has ended. If you renewed, Pro turns back on by itself shortly (or press Check now). Your key is kept."
+ return "This licence is not active. Press Check now if that changed; contact support if this is a mistake."
if st.get("reason") == "expired":
return MESSAGES["grace_over"]
+ if st.get("reason") == "not_yet_valid":
+ return MESSAGES["clock"]
return None
# ----------------------------------------------------------------------------- renewal
+INACTIVE_EVERY = 6 * 3600 # a licence that is off is asked again this often ...
+INACTIVE_LONG = 24 * 3600 # ... daily once it has been refused for over three days
+INACTIVE_FINAL = 7 * 86400 # ... weekly once its paid period ended over 30 days ago
+BACKOFF = (60, 120, 300, 900, 3600) # after "no answer": retry soon, then back off
+
+
+def _epoch(iso) -> int | None:
+ try:
+ return calendar.timegm(time.strptime(str(iso)[:19], "%Y-%m-%dT%H:%M:%S")) if iso else None
+ except (ValueError, OverflowError):
+ return None
+
+
def due(now: int | None = None) -> bool:
rec = load()
- if not rec or rec.get("status") != "active":
+ if not rec:
return False
now = int(time.time()) if now is None else int(now)
+ if rec.get("status") != "active":
+ # A refusal is not forever: a paid renewal turns the licence on again on the server. Ask again,
+ # slowly. The server alone decides (a refund stays off until the server says otherwise).
+ last = int(rec.get("last_checked") or rec.get("last_validated") or 0)
+ every = INACTIVE_EVERY
+ since = int(rec.get("refused_since") or 0)
+ if since and now - since > 3 * 86400:
+ every = INACTIVE_LONG
+ ended = _epoch(rec.get("expires_at"))
+ if ended and now - ended > 30 * 86400:
+ every = INACTIVE_FINAL
+ return now - last >= every or now < last - 86400
if now - int(rec.get("last_validated") or 0) >= REVALIDATE_EVERY:
return True
st = pro_token.status()
@@ -336,22 +485,41 @@ def due(now: int | None = None) -> bool:
_loop_started = threading.Event()
+_fails = [0]
+
+
+def renew_step(now: int | None = None) -> int:
+ """One look: validate when due. Returns the seconds until the next look (a short back-off after
+ 'no answer', so a reconnect or a wake is noticed fast and a dead network is not hammered)."""
+ try:
+ if due(now):
+ r = validate(now=now)
+ if r.get("offline"):
+ n = _fails[0]
+ _fails[0] = n + 1
+ return BACKOFF[min(n, len(BACKOFF) - 1)]
+ _fails[0] = 0
+ except Exception: # noqa: BLE001 - a renewal problem must never reach a render
+ pass
+ return TICK
+
+
+SLICE = 30 # seconds: the loop watches the WALL clock, so a Mac that slept is looked at on waking
def start_renewal(sleep=time.sleep) -> bool:
- """A daemon thread: renew at start and every 6 hours. Pinokio only, once per process."""
+ """A daemon thread: renew at start, then when due. Pinokio only, once per process."""
if _loop_started.is_set():
return False
_loop_started.set()
def run():
+ nxt = 0.0
while True:
- try:
- if due():
- validate()
- except Exception: # noqa: BLE001 - a renewal problem must never reach a render
- pass
- sleep(TICK)
+ now = time.time()
+ if now >= nxt or nxt - now > 2 * TICK: # due, or the clock was set back
+ nxt = time.time() + renew_step()
+ sleep(SLICE)
threading.Thread(target=run, name="pro-licence-renewal", daemon=True).start()
return True
diff --git a/pro_parts.py b/pro_parts.py
index 8711175..6a62c44 100644
--- a/pro_parts.py
+++ b/pro_parts.py
@@ -45,7 +45,9 @@ MAX_PACK = 1 << 30
CHECK_EVERY = 24 * 3600
TIMEOUT = 30
_lock = threading.Lock()
-_state = {"busy": False, "error": None, "checked_at": None}
+_state = {"busy": False, "error": None, "checked_at": None, "restart_needed": False, "rolled_back": None,
+ "phase": None, "last_manual": 0.0}
+MANUAL_GAP = 20 # seconds between two manual retries
def _server() -> str:
@@ -83,26 +85,57 @@ def _sha(path: Path) -> str:
return h.hexdigest()
-def _record() -> dict | None:
+def _read_json(name: str) -> dict | None:
try:
- d = json.loads((root() / "current.json").read_text(encoding="utf-8"))
+ d = json.loads((root() / name).read_text(encoding="utf-8"))
except (OSError, ValueError):
return None
if not (isinstance(d, dict) and isinstance(d.get("version"), str) and isinstance(d.get("files"), dict)):
return None
if not re.fullmatch(r"[A-Za-z0-9._+-]{1,96}", d["version"]):
return None
+ if not re.fullmatch(r"[A-Za-z0-9._+-]{1,120}", str(d.get("dir", d["version"]))):
+ return None
return d
-def installed() -> str | None:
- """The verified parts folder, or None."""
- rec = _record()
+def _record() -> dict | None:
+ return _read_json("current.json")
+
+
+def _previous() -> dict | None:
+ return _read_json("previous.json")
+
+
+def _dir_of(rec: dict) -> Path:
+ return root() / str(rec.get("dir") or rec["version"])
+
+
+def _trusted_record(rec: dict) -> bool:
+ """A restored install is trusted only if the signed manifest saved with it still verifies against a
+ release key we know and names this version (the local file hashes alone prove nothing about who
+ signed them)."""
+ try:
+ offer = {"key_id": rec.get("key_id"), "manifest": rec.get("manifest"), "signature": rec.get("signature")}
+ import pro_token
+ pk = _trusted().get(str(offer["key_id"]))
+ if not pk:
+ return False
+ msg = _b64(str(offer["manifest"]))
+ if not pro_token.ed25519_verify(_b64(pk), msg, _b64(str(offer["signature"]))):
+ return False
+ m = json.loads(msg.decode("utf-8"))
+ return isinstance(m, dict) and m.get("version") == rec["version"] and m.get("component") == "panel"
+ except (ValueError, TypeError, KeyError):
+ return False
+
+
+def _verified(rec: dict | None) -> str | None:
if not rec:
return None
- d = root() / rec["version"]
+ d = _dir_of(rec)
want = {p + SO for p in PARTS}
- if set(rec["files"]) != want:
+ if set(rec["files"]) != want or not _trusted_record(rec):
return None
for name, sha in rec["files"].items():
p = d / name
@@ -111,12 +144,38 @@ def installed() -> str | None:
return str(d)
+def installed() -> str | None:
+ """The verified parts folder, or None."""
+ return _verified(_record())
+
+
+def rollback() -> str | None:
+ """The current install failed a check: switch back to the verified previous version (atomic
+ pointer swap). Returns the folder now current, or None when there is nothing to go back to."""
+ prev = _previous()
+ d = _verified(prev)
+ if not d:
+ return None
+ cur = root() / "current.json"
+ part = root() / (".current.%s.tmp" % os.urandom(4).hex())
+ try:
+ part.write_text(json.dumps(prev, indent=1, sort_keys=True), encoding="utf-8")
+ os.replace(part, cur)
+ except OSError:
+ return None
+ with _lock:
+ _state["rolled_back"] = prev["version"]
+ return d
+
+
def activate() -> str | None:
"""Called before `import pro_remote`. The Mac app's studio IS the Pro pack: nothing to do."""
if _dist.is_mac_app():
return None
try:
d = installed()
+ if not d and _record() is not None:
+ d = rollback() # the current one no longer verifies: use the last good one
except OSError:
return None
if d and d not in sys.path:
@@ -251,30 +310,41 @@ def fetch(opener=None) -> dict:
if rec and rec["version"] == m["version"] and installed():
return _done({"ok": True, "version": m["version"], "changed": False})
root().mkdir(parents=True, exist_ok=True)
- tmp = root() / (".fetch-%d" % os.getpid())
- shutil.rmtree(tmp, ignore_errors=True)
+ tmp = root() / (".fetch-%d-%s" % (os.getpid(), os.urandom(4).hex()))
tmp.mkdir()
+ _phase("downloading")
pack = tmp / "pack.tar.gz"
_download(str(offer.get("url", "")), pack, int(m["bytes"]), lic["key"], opener)
+ _phase("verifying")
if _sha(pack) != m["sha256"]:
raise ValueError("hash")
out = tmp / "parts"
out.mkdir()
files = _extract(pack, int(m["strip_components"]), out)
- dest = root() / m["version"]
- if dest.exists():
- shutil.rmtree(dest)
+ # A unique folder per install attempt: the version that is running is never touched.
+ dest_name = "%s.%s" % (m["version"], os.urandom(3).hex())
+ dest = root() / dest_name
+ if not _probe(out): # a correctly signed package that cannot load here is refused
+ raise ValueError("incompatible")
os.replace(out, dest)
- doc = {"version": m["version"], "files": files, "key_id": offer["key_id"],
+ doc = {"version": m["version"], "dir": dest_name, "files": files, "key_id": offer["key_id"],
"manifest": offer["manifest"], "signature": offer["signature"],
"installed_at": int(time.time())}
- cur = root() / "current.json"
- part = root() / ".current.json.tmp"
- part.write_text(json.dumps(doc, indent=1, sort_keys=True), encoding="utf-8")
old = _record()
- os.replace(part, cur)
- if old and old["version"] != m["version"]:
- shutil.rmtree(root() / old["version"], ignore_errors=True)
+ old_ok = _verified(old) if old else None
+ cur = root() / "current.json"
+ part = root() / (".current.%s.tmp" % os.urandom(4).hex())
+ try:
+ part.write_text(json.dumps(doc, indent=1, sort_keys=True), encoding="utf-8")
+ if old_ok: # keep one verified previous version to roll back to
+ pj = root() / (".previous.%s.tmp" % os.urandom(4).hex())
+ pj.write_text(json.dumps(old, indent=1, sort_keys=True), encoding="utf-8")
+ os.replace(pj, root() / "previous.json")
+ os.replace(part, cur) # the atomic switch
+ except OSError:
+ shutil.rmtree(dest, ignore_errors=True)
+ raise
+ _prune(keep={dest_name})
return _done({"ok": True, "version": m["version"], "changed": True})
except (ValueError, KeyError, TypeError, OSError, tarfile.TarError) as e:
return _done({"ok": False, "error": (e.args[0] if isinstance(e, ValueError) and e.args else type(e).__name__)[:60]})
@@ -285,23 +355,117 @@ def fetch(opener=None) -> dict:
_state["busy"] = False
+def _phase(name) -> None:
+ with _lock:
+ _state["phase"] = name
+
+
+def _probe(parts_dir: Path) -> bool:
+ """Would these modules import on this Studio? Tried in a throw-away interpreter with ONLY this
+ folder in front, so a bad build is refused before it replaces anything."""
+ import subprocess
+ if not PROBE:
+ return True
+ code = "import sys; sys.path[:0] = [sys.argv[1], sys.argv[2]]; import pro_remote_crypto, pro_remote, pro_relay_grant"
+ try:
+ r = subprocess.run([sys.executable, "-I", "-c", code, str(parts_dir), str(Path(__file__).resolve().parent)],
+ capture_output=True, timeout=60, cwd=str(parts_dir),
+ env={"PATH": "/usr/bin:/bin", "PHOSPHENE_PROBE": "1"})
+ except (OSError, subprocess.SubprocessError):
+ return False
+ return r.returncode == 0
+
+
+PROBE = True
+
+
+def _prune(keep: set) -> None:
+ """Remove install folders that are neither current nor the kept previous."""
+ prev = _previous()
+ if prev:
+ keep.add(str(prev.get("dir") or prev["version"]))
+ try:
+ for p in root().iterdir():
+ if p.is_dir() and not p.name.startswith(".") and p.name not in keep:
+ shutil.rmtree(p, ignore_errors=True)
+ except OSError:
+ pass
+
+
def _done(r: dict) -> dict:
with _lock:
_state["error"] = None if r.get("ok") else r.get("error")
_state["checked_at"] = int(time.time())
+ _state["phase"] = None
return r
+PLAIN = {
+ "no_licence": "Remote Control needs your Pro licence key in this Studio. Paste it in Settings > Pro.",
+ "unreachable": "The licence server could not be reached. Check the internet connection.",
+ "busy": "Already working on it.",
+ "bad_signature": "The downloaded Pro components did not pass the signature check, so they were not installed. Try again; if it repeats, contact support.",
+ "hash": "The download was damaged (its checksum did not match). Nothing was installed. Try again.",
+ "size": "The download was cut short or the wrong size. Nothing was installed. Try again.",
+ "incompatible": "These Pro components cannot run on this Studio yet. Your previous version stays in use. Update the Studio or try again later.",
+ "studio_too_old": "These Pro components need a newer Studio. Update Phosphene in Pinokio, then try again.",
+ "pack_without_remote": "The Pro download did not contain Remote Control. Contact support.",
+ "bad_url": "The download address was refused for safety. Contact support.",
+ "OSError": "The components could not be saved (is the disk full?). Free some space and try again.",
+ "TarError": "The download could not be unpacked. Try again.",
+ "licence_not_active": "Your licence is not active, so the components were not offered. Check Settings > Pro.",
+}
+
+
+def explain(code) -> str | None:
+ if not code:
+ return None
+ return PLAIN.get(str(code), "Remote Control components could not be installed (%s). Try again, or contact support." % str(code)[:40])
+
+
def status() -> dict:
rec = _record()
with _lock:
- return {"installed": rec["version"] if rec and installed() else None, "busy": _state["busy"],
- "error": _state["error"], "checked_at": _state["checked_at"]}
+ st = dict(_state)
+ ok = bool(rec and installed())
+ return {"installed": rec["version"] if ok else None, "busy": st["busy"], "phase": st["phase"],
+ "error": st["error"], "message": explain(st["error"]), "checked_at": st["checked_at"],
+ "restart_needed": st["restart_needed"], "rolled_back": st["rolled_back"]}
+
+
+def retry_now() -> dict:
+ """Settings > Remote 'Try again': one background attempt, rate limited, never stacks up."""
+ if _dist.is_mac_app():
+ return {"ok": False, "error": "mac_app"}
+ if not _licence():
+ return {"ok": False, "error": "no_licence", "message": explain("no_licence")}
+ with _lock:
+ if _state["busy"]:
+ return {"ok": True, "started": False, "message": "Already working on it."}
+ now = time.time()
+ if now - _state["last_manual"] < MANUAL_GAP:
+ return {"ok": True, "started": False, "message": "Just tried; give it a few seconds."}
+ _state["last_manual"] = now
+ _state["phase"] = "checking"
+ threading.Thread(target=_manual_run, name="pro-parts-retry", daemon=True).start()
+ return {"ok": True, "started": True}
+
+
+_P = [None]
+
+
+def _manual_run() -> None:
+ r = fetch()
+ if r.get("ok") and _P[0] is not None:
+ _bring_up(_P[0])
def _bring_up(P) -> None:
"""Newly installed parts start without a Studio restart (routes look P.pro_remote up live)."""
if getattr(P, "pro_remote", None) is not None:
+ with _lock:
+ if _state.get("changed_since_load"):
+ _state["restart_needed"] = True # new components are on disk; the running ones stay until restart
return
if activate() is None:
return
@@ -310,6 +474,10 @@ def _bring_up(P) -> None:
mod = importlib.import_module("pro_remote")
except Exception as exc: # noqa: BLE001
print(f"[remote] Pro parts did not load: {type(exc).__name__}", flush=True)
+ back = rollback() # the next start uses the last good version
+ with _lock:
+ _state["error"] = "incompatible"
+ _state["restart_needed"] = bool(back)
return
P.pro_remote = mod
mod.boot(P)
@@ -331,12 +499,17 @@ def start(P, sleep=time.sleep, rounds=None) -> bool:
if _dist.is_mac_app():
return False
+ _P[0] = P
+
def loop():
n = 0
while rounds is None or n < rounds:
n += 1
r = fetch() if _licence() else None
if r and r.get("ok"):
+ if r.get("changed") and getattr(P, "pro_remote", None) is not None:
+ with _lock:
+ _state["restart_needed"] = True
_bring_up(P)
sleep(_next_wait(r))
if rounds is not None:
diff --git a/webapp/index.html b/webapp/index.html
index 708f96b..eb2c1c3 100644
--- a/webapp/index.html
+++ b/webapp/index.html
@@ -168,7 +168,7 @@
</svg>
</span>
<img class="brand-word" src="/assets/phosphene_wordtext.png" alt="Phosphene">
- <span id="proMark" class="pro-mark" hidden title="Phosphene Pro is active on this Mac"><span class="pro-mark-dash" aria-hidden="true"></span>PRO</span>
+ <span id="proMark" class="pro-mark" hidden title="Phosphene Pro is active on this Mac">Pro</span>
</a>
<!-- The standalone version badge is gone: #versionPill already carries the
version in EVERY state it can be in — "Up to date · 4.2.0",
@@ -354,7 +354,7 @@
<button data-workflow="train" role="tab" aria-selected="false"><svg class="ph wf-icon" aria-hidden="true"><use href="#ph-user-plus"/></svg>Train Character</button>
<!-- Remote Control: drive this Mac from the iPhone app. The page is Studio UI; the
working parts are Pro-only and come from the Pro pack (see panel/routes_remote.py). -->
- <button data-workflow="remote" role="tab" aria-selected="false"><svg class="ph wf-icon" aria-hidden="true"><use href="#ph-remote"/></svg>Remote Control<span class="new-badge">NEW</span></button>
+ <button data-workflow="remote" role="tab" aria-selected="false"><svg class="ph wf-icon" aria-hidden="true"><use href="#ph-remote"/></svg>Remote Control<span class="new-badge">NEW</span><span class="rail-pro" title="Remote Control is part of Phosphene Pro">Pro</span></button>
</nav>
<div class="rail-foot">
<!-- DOCS. The manual gets a door of its own beside the gear, with a WORD on
@@ -419,8 +419,14 @@
<!-- A Pro member whose studio has no Remote module yet (the Pro pack is still installing,
or this is the free build on a Pro Mac): status, never the upsell above. -->
<div class="rm-card rm-pro-wait" id="rmProWait" hidden>
- <h3>Remote Control is not set up yet</h3>
- <p>Your Pro licence is active. Remote Control turns on once the Pro components finish installing; this page updates by itself.</p>
+ <h3 id="rmWaitTitle">Remote Control is not set up yet</h3>
+ <p id="rmWaitBody">Your Pro licence is active. Checking for the Remote Control components.</p>
+ <p class="rm-wait-err" id="rmWaitErr" hidden></p>
+ <div class="rm-wait-actions">
+ <button type="button" class="rm-btn primary" id="rmWaitStart" hidden onclick="rmStartInApp()">Set up Remote</button>
+ <button type="button" class="btn" id="rmWaitRetry" hidden onclick="rmPartsRetry()">Try again</button>
+ <button type="button" class="btn" id="rmWaitSettings" hidden onclick="openProModal()">Open Pro settings</button>
+ </div>
</div>
<div class="rm-grid" id="rmMain" hidden>
@@ -5488,11 +5494,13 @@ The last line"></textarea>
</div>
<div class="sbe-pop sbe-films" id="sbeFilmsMenu" role="menu" hidden>
+ <button type="button" class="ghost-btn" id="sbeFilmsNewBtn" onclick="sbeFilmsNew()"
+ title="Start an empty timeline. The one you are on is kept.">New __SEQ__</button>
+ <button type="button" class="ghost-btn" id="sbeFilmsRenameBtn" onclick="sbeRename()"
+ title="Change the name of this __SEQ__">Rename this __SEQ__</button>
+ <span class="sbe-pop-sep"></span>
<span class="sbe-pop-note" id="sbeFilmsNote">reading your __SEQS__…</span>
<div class="sbe-films-list" id="sbeFilmsList"></div>
- <span class="sbe-pop-sep"></span>
- <button type="button" class="ghost-btn" id="sbeFilmsAllBtn" onclick="sbeFilmsAll()"
- title="Close this timeline and show every __SEQ__. Nothing is deleted.">All __SEQS__…</button>
</div>
<div class="sbe-pop" id="sbeMoreMenu" hidden>
@@ -5762,7 +5770,7 @@ The last line"></textarea>
<div class="sbe-stage-empty sbe-src-empty" id="sbeSrcEmpty">
<svg class="sbe-cbar-i" aria-hidden="true"><use href="#ic-source"/></svg>
<b>Drop a clip here to preview</b>
- <span>Drag one from the media pool or the timeline — or click a clip in the pool.</span>
+ <span>Drag one from the media pool or the timeline, or click a clip in the pool.</span>
</div>
</div>
<div class="sbe-mon-bar">
diff --git a/webapp/js/editor.js b/webapp/js/editor.js
index 2e27b21..cfad841 100644
--- a/webapp/js/editor.js
+++ b/webapp/js/editor.js
@@ -4197,33 +4197,107 @@ function edInit() {
edShowPicker();
}
-// The empty state, painted from the board list. This is "pick a film / start
-// from clips": every film with something on disk, plus the pool on the left.
+// THE EDITOR NEVER OPENS ON A START SCREEN. With no document it opens an
+// empty timeline: a fresh sequence named by date, ready for a drag or a +.
+// The server keeps it out of every list until it holds a first clip, and
+// reuses it, so opening the Editor again does not pile up empty boards.
+// The old pick-a-sequence screen (#edEmpty) is only the fallback when the
+// panel does not answer.
async function edShowPicker() {
- edShow('empty');
- // With no document open "this film" has nothing in it, so the pool opens
- // on the generations — which is the source that always has something.
- if (ED.src === 'film') edPoolSrc('gallery'); else edPoolRefresh();
- const box = document.getElementById('edPick');
- if (box) box.innerHTML = '<span class="sbe-note">reading your __SEQS__…</span>';
- let boards = [];
- try {
- const r = await (await fetch('/storyboard/list')).json();
- boards = ((r && r.boards) || []).filter(b => (b.clips || 0) > 0);
- } catch (e) { boards = []; }
- if (!box) return;
- if (!boards.length) {
- box.innerHTML = '<span class="sbe-note">Nothing has been rendered yet. ' +
- 'Anything you generate — on any engine — shows up in the media pool ' +
- 'on the left, and one click puts it on the track.</span>';
+ if (ED.starting) return ED.starting;
+ ED.starting = (async () => {
+ let r = null;
+ try {
+ r = await (await fetch('/storyboard/new-sequence', { method: 'POST', body: new URLSearchParams() })).json();
+ } catch (e) { r = null; }
+ if (r && r.ok && r.id) {
+ // An empty sequence has no clips of its own: the pool opens on the
+ // generations, the source that always has something.
+ edPoolSrc('gallery');
+ edOpenBoard(r.id);
+ return;
+ }
+ edShow('empty');
+ const box = document.getElementById('edPick');
+ if (box) box.innerHTML = '<span class="sbe-note">The panel did not answer.</span>' +
+ '<button type="button" onclick="edShowPicker()">Try again</button>';
+ })();
+ try { await ED.starting; } finally { ED.starting = null; }
+}
+
+// A new sequence is real from its first clip: saved then, not left as
+// unsaved changes. From there on it is an ordinary sequence in every list.
+function edSaveOnFirstClip(wasEmpty) {
+ if (wasEmpty && (SBE.clips || []).length && SBE.open && SBE.id) {
+ try { sbeSave(true); } catch (_) {}
+ }
+}
+
+// A new empty sequence from the sequence menu. An already empty one is not
+// duplicated: there is nothing to start over.
+async function sbeFilmsNew() {
+ sbePopCloseAll('');
+ if (SBE.open && !(SBE.clips || []).length) {
+ phosToast('This sequence is already empty. Drag clips in.', { duration: 3000 });
return;
}
- box.innerHTML = boards.map(b =>
- '<button type="button" onclick="edOpenBoard(\'' + escapeHtml(b.id) + '\')">' +
- '<svg class="ph" aria-hidden="true"><use href="#ph-film-strip"/></svg>' +
- escapeHtml(b.title || b.id) +
- '<span class="sub">' + (b.clips || 0) + ' clip' + ((b.clips === 1) ? '' : 's') +
- '</span></button>').join('');
+ await edShowPicker();
+}
+
+// Rename in place: the name in the header turns into a field.
+function sbeRename() {
+ sbePopCloseAll('');
+ const ttl = sbeEl('sbeTitle');
+ if (!ttl || !SBE.id || ttl.querySelector('input')) return;
+ const id = SBE.id, current = SBE.title || ttl.textContent;
+ const input = document.createElement('input');
+ input.type = 'text'; input.value = current; input.className = 'sb-board-rename';
+ input.setAttribute('aria-label', 'Sequence name');
+ const done = (save) => {
+ const next = input.value.trim();
+ ttl.textContent = (save && next) || current;
+ if (save && next && next !== current) {
+ SBE.title = next;
+ fetch('/storyboard/save', { method: 'POST', headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ id: id, board: { id: id, title: next } }) })
+ .then(r => r.json()).then(r => {
+ if (!r || !r.ok) { phosToast((r && r.error) || 'Could not rename that sequence.', { kind: 'danger' }); }
+ }).catch(() => {});
+ }
+ };
+ input.addEventListener('keydown', (e) => {
+ e.stopPropagation();
+ if (e.key === 'Enter') { e.preventDefault(); input.blur(); }
+ else if (e.key === 'Escape') { input.value = current; input.blur(); }
+ });
+ input.addEventListener('blur', () => done(true), { once: true });
+ ttl.textContent = '';
+ ttl.appendChild(input);
+ input.focus(); input.select();
+}
+
+// The sentence on an empty track. Which one depends on the media pool, so it
+// is repainted whenever the pool is (edPoolPaint).
+function edTrackHintHtml() {
+ const rows = (ED.rows || []).filter(r => r.kind !== 'sound');
+ if (!rows.length) {
+ return 'Nothing to add yet. Make a clip in Video or One Shot and it shows up in the media pool.';
+ }
+ return 'Drag clips here, or press + on a clip.' +
+ '<button type="button" class="ghost-btn sbe-track-all" onclick="edPoolAddAll()">' +
+ (rows.length === 1 ? 'Add the clip' : 'Add these ' + rows.length + ' clips in order') + '</button>';
+}
+function edTrackHintRefresh() {
+ const el = document.querySelector('.sbe-track-empty:not(.sbe-ovlane-empty)');
+ if (el) el.innerHTML = edTrackHintHtml();
+}
+async function edPoolAddAll() {
+ const list = document.getElementById('edPoolList');
+ const rows = (list || {})._rows || [];
+ for (let i = 0; i < rows.length; i++) {
+ if (rows[i].kind === 'sound') continue;
+ await edPoolAdd(i);
+ }
}
// The one door, from anywhere: the rail's step 3, a board row, the picker.
@@ -4390,17 +4464,28 @@ async function sbeFilmsToggle() {
if (boards.length <= 1) note.textContent = 'No other __SEQ__ has clips yet.';
list.innerHTML = boards.map(b => {
const cur = b.id === SBE.id;
- const n = b.clips || 0;
+ const n = b.has_timeline ? (b.edit_clips || 0) : (b.clips || 0);
+ const len = (b.has_timeline && b.edit_duration)
+ ? ' · ' + sbeFmtTime(b.edit_duration).replace(/\.\d+$/, '') : '';
return '<button type="button" role="menuitem" class="ghost-btn' +
(cur ? ' is-current' : '') + '"' + (cur ? ' aria-current="true"' : '') +
' onclick="sbeFilmsPick(\'' + escapeHtml(b.id) + '\')"' +
' title="' + escapeHtml(b.title || b.id) + '">' +
'<span class="name">' + escapeHtml(b.title || b.id) + '</span>' +
'<span class="sub">' + (cur ? 'open · ' : '') + n + ' clip' + (n === 1 ? '' : 's') +
+ len + (b.updated_at ? ' · ' + edAgo(b.updated_at) : '') +
'</span></button>';
}).join('');
}
+function edAgo(ts) {
+ const d = new Date(ts * 1000), now = new Date();
+ if (d.toDateString() === now.toDateString()) {
+ return d.toLocaleTimeString([], { hour: 'numeric', minute: '2-digit' });
+ }
+ return d.toLocaleDateString([], { day: 'numeric', month: 'short' });
+}
+
function sbeFilmsPick(id) {
sbePopCloseAll('');
if (!id || id === SBE.id) return;
@@ -4554,8 +4639,8 @@ function sbeAdopt(r, quiet) {
// The saved mode wins over the control's default, or reopening a film would
// silently re-arm `replace` on a timeline that was mixed `under`.
sbeSetMusicMode((SBE.audio && SBE.audio.mode) || 'under');
- sbeSetState(r.generated ? 'cut by the auto-editor' : 'saved · revision ' + SBE.revision,
- 'saved');
+ sbeSetState((r.generated && (SBE.clips || []).length) ? 'cut by the auto-editor' : sbeSavedText(),
+ (r.generated && (SBE.clips || []).length) ? 'saved' : sbeSavedKind());
sbeSyncMusic();
sbePaintDraft();
sbePaintRecovery();
@@ -4592,7 +4677,7 @@ function sbeAdopt(r, quiet) {
// Land on a picture, not on black. A timeline that opens dark reads as
// broken for the second and a half before the first click.
if (!SBE.playing && !SBE.drag) sbeShowFrameAt(SBE.playhead);
- if (!quiet && r.generated) {
+ if (!quiet && r.generated && (SBE.clips || []).length) {
phosToast('No timeline existed, so the auto-editor cut one — every shot at its best window, on the beat.',
{ duration: 7000 });
}
@@ -4699,10 +4784,27 @@ function sbePaintProtected() {
if (pill) pill.title = text || '';
}
+// What the header says once the document is as saved as it can be. An empty
+// sequence the Editor made itself is not saved yet: nothing is written for it
+// until its first clip lands (edSaveOnFirstClip), so it must not claim a
+// revision.
+function sbeSavedKind() {
+ return (!(SBE.clips || []).length && SBE.revision <= 1) ? '' : 'saved';
+}
+function sbeSavedText() {
+ if (!(SBE.clips || []).length && SBE.revision <= 1) {
+ return 'not saved yet';
+ }
+ return 'saved \u00b7 revision ' + SBE.revision;
+}
+
function sbeSetState(text, kind) {
const el = sbeEl('sbeState');
if (!el) return;
sbeEl('sbeStateText').textContent = text;
+ const NOT_SAVED = 'Nothing is saved until the first clip lands on the timeline.';
+ if (text === 'not saved yet') el.title = NOT_SAVED;
+ else if (el.title === NOT_SAVED) el.title = '';
el.classList.toggle('is-dirty', kind === 'dirty');
el.classList.toggle('is-saved', kind === 'saved');
el.classList.toggle('is-alarm', kind === 'alarm');
@@ -4963,6 +5065,7 @@ function sbeSelectNone() {
// one member would make a multi-selection unusable the moment anything in it
// was pinned.
function sbeMutateEach(ids, fn) {
+ const wasEmpty = !(SBE.clips || []).length;
const list = (ids || []).slice();
if (!list.length) return false;
const before = sbeSnapshot();
@@ -4998,6 +5101,7 @@ function sbeMutateEach(ids, fn) {
}
sbePaint();
sbeQueueSave();
+ edSaveOnFirstClip(wasEmpty);
return true;
}
@@ -5257,6 +5361,7 @@ function sbeRestoreUndoIfFresh() {
}
function sbeMutate(fn) {
+ const wasEmpty = !(SBE.clips || []).length;
const before = sbeSnapshot();
const res = fn(SBE.clips);
if (!res || res.ok === false) {
@@ -5277,6 +5382,7 @@ function sbeMutate(fn) {
sbeSetState('unsaved changes', 'dirty');
sbePaint();
sbeQueueSave();
+ edSaveOnFirstClip(wasEmpty);
return true;
}
@@ -5630,7 +5736,7 @@ async function sbeSaveInner(quiet, force) {
sbeSetState('unsaved changes · revision ' + SBE.revision + ' is saved', 'dirty');
sbeQueueSave();
} else {
- sbeSetState('saved · revision ' + SBE.revision, 'saved');
+ sbeSetState(sbeSavedText(), sbeSavedKind());
}
sbePaint();
return true;
@@ -7230,8 +7336,7 @@ function sbePaintTrack() {
// for a gap to fill", starting mid-word, while the track itself, the thing
// that was empty, rendered nothing at all.
let html = SBE.clips.length ? '' :
- '<div class="sbe-track-empty">Nothing on the timeline yet — click a clip '
- + 'in the media pool to put it here, or Add black for a gap to fill.</div>';
+ '<div class="sbe-track-empty">' + edTrackHintHtml() + '</div>';
for (const g of holes) {
const w = sbePx(g.duration);
html += '<div class="sbe-gap" data-gap-start="' + g.film_start + '" ' +
@@ -7646,7 +7751,7 @@ function sbePaintTracks() {
+ 'data-track="new"><span class="sbe-tadd-t">'
+ escapeHtml(tracks.length
? 'Drop a sound here for a track of its own'
- : 'Audio tracks — drop a sound from the media pool here, or press + Add audio track')
+ : 'Audio tracks. Drop a sound from the media pool here, or press + Add audio track')
+ '</span></div>';
box.innerHTML = html;
const inner = sbeEl('sbeInner');
@@ -8740,7 +8845,7 @@ function sbePaintOverlays() {
// the four pool sources already follow. Without it the overlay lane is a
// strip of nothing that teaches nobody it exists.
lane.innerHTML = html || '<div class="sbe-track-empty sbe-ovlane-empty">'
- + 'Overlay lane — drop a still here, press \u25a3 on an image in the '
+ + 'Overlay lane. Drop a still here, press \u25a3 on an image in the '
+ 'media pool, or Add title for text over the picture at the playhead.</div>';
lane.style.width = sbeEl('sbeInner').style.width;
}
@@ -11272,7 +11377,7 @@ function sbePaintChrome() {
if (pe) {
if (SBE.clips.length) { pe.hidden = true; pe.textContent = ''; }
else {
- pe.textContent = 'Nothing on the timeline yet — drag a clip from the '
+ pe.textContent = 'Nothing on the timeline yet. Drag a clip from the '
+ 'media pool, or press + on one.';
pe.hidden = false;
}
@@ -12502,6 +12607,7 @@ function edPoolPaint() {
const list = document.getElementById('edPoolList');
const note = document.getElementById('edPoolNote');
if (!list) return;
+ edTrackHintRefresh();
const q = ((document.getElementById('edPoolSearch') || {}).value || '')
.trim().toLowerCase();
const rows = (ED.rows || []).filter(r =>
@@ -12667,8 +12773,9 @@ async function edPoolAdd(i, dropAt, overwriteId) {
// A SOUND HAS NO PICTURE to put on V1 — it goes on an audio track.
if (row.kind === 'sound') { await sbeTsAddSoundPath(row.path, '', SBE.playhead); return; }
if (!SBE.open || !SBE.id) {
- phosToast('Open a __SEQ__ first — the Editor holds one timeline at a time.', {});
- return;
+ // The Editor always has a timeline; if it was lost, make one and go on.
+ await edShowPicker();
+ if (!SBE.open || !SBE.id) return;
}
// The row's own word first, then the file's. The server checks the suffix
// too — this is the half that keeps the CLIENT from asking /file for a
@@ -15548,7 +15655,7 @@ Object.assign(globalThis, {
sbeSplitWhy, sbeCbarPlayhead,
sbeCtxOpen, sbeReorderSel, sbeSplitHere, sbeGenOpen,
// The header's film switcher (index.html onclicks + generated rows).
- sbeFilmsToggle, sbeFilmsPick, sbeFilmsAll,
+ sbeFilmsToggle, sbeFilmsPick, sbeFilmsAll, sbeFilmsNew, sbeRename, edPoolAddAll,
// THE AUDIO TRACKS — the model (for the harnesses) and every name the
// generated heads, strips, inspector and pool rows call back into.
sbeTrackLabel, sbeUnitGain, sbeTrackGain, sbeTsGain, sbeTsWindow, sbeTsGainPoints,
diff --git a/webapp/js/engines.js b/webapp/js/engines.js
index 5987f98..0cd58da 100644
--- a/webapp/js/engines.js
+++ b/webapp/js/engines.js
@@ -1702,11 +1702,14 @@ function h3FlexTurboPickerEntry() {
if (!h3e || !engineRenderable(h3e)) return null;
const ft = h3FlexTurboState();
const h3st = engineStatus(h3e);
- if (h3st.available && !ft.supported && !ft.downloaded) return null;
+ // A Pro member whose H3 runner cannot do it yet has nothing to pick; a Free user always sees
+ // it, marked Pro (owner, 6 Nov: the option was silently missing for Free, so nobody knew it
+ // existed). Clicking it as Free opens the Pro panel.
+ if (ft.pro_active && h3st.available && !ft.supported && !ft.downloaded) return null;
return Object.assign({}, h3e, {
- id: H3FLEXTURBO_ID, label: 'H3 Flex Turbo', generation: '', preview: true, pro: true, virtual: true,
- sublabel: 'H3 Flex Turbo · faster draft · Pro',
- tagline: 'Four-step H3 Flex: a faster draft, about 1.4× quicker than H3 Flex and a little softer. Pro.',
+ id: H3FLEXTURBO_ID, label: 'Faster Flex Turbo', generation: '', preview: true, pro: true, virtual: true,
+ sublabel: 'Faster Flex Turbo · quick drafts · Pro',
+ tagline: 'Quick drafts: try ideas fast, then render the keeper. Part of Phosphene Pro.',
});
}
function h3FlexTurboPickerStatus() {
@@ -1726,7 +1729,7 @@ function h3FlexTurboPickerStatus() {
}
function _h3FlexTurboTooltip(st) {
const credit = ' By akhaliq (Pika H3 Flex by Pika Labs + LightX2V Turbo), running on your Mac. Powered by MiniMax H3.';
- if (!st.pro_active) return 'H3 Flex Turbo is part of Phosphene Pro: a faster draft of H3 Flex, about 1.4× faster and a little softer.' + credit;
+ if (!st.pro_active) return 'Faster Flex Turbo is part of Phosphene Pro: quick drafts, so you can try ideas fast and render the keeper after. Click to see Pro.';
if (!st.h3_ready) return 'H3 Flex Turbo needs Hailuo H3 first. Click to get it.' + credit;
if (st.installing) return 'H3 Flex Turbo: downloading (' + st.progress + ').' + credit;
if (!st.available) return 'H3 Flex Turbo: click to download it (' + st.download_gb + ' GB).' + credit;
diff --git a/webapp/js/preview.js b/webapp/js/preview.js
index d9efc4c..f1e9b5e 100644
--- a/webapp/js/preview.js
+++ b/webapp/js/preview.js
@@ -1850,6 +1850,35 @@ document.addEventListener('DOMContentLoaded', () => {
// ◐ partial (amber) — some files there, some missing (e.g. interrupted)
// ⊘ missing (red) — nothing on disk
// ↻ downloading (blue, anim) — hf is currently fetching this repo
+// A refusal that names a file Pinokio already has (res.pinokio): the server's sentence, then two
+// actions - use it from Pinokio first, download second.
+function pinokioReuseToast(res, retry) {
+ const el = phosToast(`${res.pinokio.name || 'This file'} is already in your Pinokio install. Use it from there (no download).`, { kind: 'warning', duration: 0 });
+ if (!el) return true;
+ const mk = (label, fn) => {
+ const a = document.createElement('a'); a.href = '#'; a.className = 'phos-toast-action'; a.textContent = label;
+ a.onclick = (ev) => { ev.preventDefault(); el.remove(); fn(); }; el.appendChild(a);
+ };
+ mk('Use it from your Pinokio install', async () => {
+ await reuseFromPinokio(res.pinokio.repo_key);
+ if (typeof retry === 'function') retry();
+ });
+ mk('Download instead', () => openModelsModal());
+ return true;
+}
+async function reuseFromPinokio(key, btn) {
+ if (btn) { btn.disabled = true; btn.textContent = 'Reusing…'; }
+ try {
+ const res = await api('/models/reuse-pinokio', 'POST', `repo_key=${encodeURIComponent(key)}`);
+ if (res && res.error) throw new Error(res.error);
+ if (typeof phosToast === 'function') phosToast('Reusing your Pinokio copy: done, nothing downloaded.');
+ } catch (e) {
+ if (btn) { btn.disabled = false; btn.textContent = 'Reuse from Pinokio'; }
+ const m = (e && e.message) || 'Could not reuse the Pinokio copy.';
+ if (typeof phosToast === 'function') phosToast(m); else alert(m);
+ }
+ refreshModelsModal();
+}
function openModelsModal() {
// SYS-19: the health popover's Models row opens this modal too (the
// real #modelsPill element is relocated into the popover by
@@ -1964,6 +1993,17 @@ async function refreshModelsModal({ silent = false } = {}) {
? `<button onclick="startDownload('${escapeHtml(r.key)}')" ${slotBlocked || (active && !queuedKeys.has(r.key)) ? 'disabled' : ''}>${queuedKeys.has(r.key) && active ? 'Download next' : 'Download'}</button>`
: `<button disabled>Download</button>`;
}
+ // Next update: Pinokio already holds this pack whole - reuse it first (no download, no extra
+ // disk), download second. Shown only while the pack is missing here.
+ if (r.pinokio && !r.complete && !r.app_owned && !(active && active.key === r.key)) {
+ const pk = r.pinokio, gb = pk.bytes ? ` (${(pk.bytes / 1e9).toFixed(1)} GB)` : '';
+ statusText += `<div style="color:#c9b8ff;margin-top:2px">It is already in your Pinokio install${gb}. Reuse it: no download${pk.same_volume ? ', no extra disk' : ''}.</div>`;
+ const _dl = (hostMissing ? '' : btnHtml.replace(/>(Download|Resume)([^<]*)</, '>Download instead<').replace(/^<button onclick/, '<button class="ghost" onclick'));
+ btnHtml = '<span style="display:flex;flex-direction:column;gap:6px;align-items:stretch">' + (pk.same_volume
+ ? `<button onclick="reuseFromPinokio('${escapeHtml(r.key)}', this)">Reuse from Pinokio</button>`
+ : `<button disabled title="Pinokio is on another drive; reusing would copy the model here. Download it instead.">Reuse from Pinokio</button>`)
+ + _dl + '</span>';
+ }
// "required" means required BY THIS BUILD. A base pack from the retired
// generation is neither required nor optional — it is previous, and saying
// so is the difference between an inventory and a claim.
@@ -2142,7 +2182,7 @@ Object.assign(globalThis, {
spicyModeEnabled, renderSpicyAccess, civitaiNsfwRequested, renderCivitaiAuthBanner,
closeCivitaiModal, civitaiSearch, civitaiLoadMore, renderCivitaiGrid,
openModelsModal, closeModelsModal, refreshModelsModal, startDownload,
- cancelDownload, packNeededToast,
+ cancelDownload, packNeededToast, pinokioReuseToast, reuseFromPinokio,
// inline-handler targets: generated markup resolves these through the
// global scope (the v4.9.0 regression, PR #69)
_charactersManageDelete, _charactersManageSave, civitaiAuthSave, civitaiSetFamily,
diff --git a/webapp/js/queue.js b/webapp/js/queue.js
index 25dcd1e..66795d8 100644
--- a/webapp/js/queue.js
+++ b/webapp/js/queue.js
@@ -2693,13 +2693,14 @@ async function api(path, method = 'GET', body = null) {
// Prefer the SERVER'S sentence. /models/remove's three refusals are
// carefully written ("That's the model this build renders with.") and
// throwing a bare status turned every one of them into "…: 400".
- let msg = '', code = '';
- try { const b = (await r.json()) || {}; msg = b.error || ''; code = b.code || ''; } catch (e) {}
+ let msg = '', code = '', body = null;
+ try { const b = (await r.json()) || {}; body = b; msg = b.error || ''; code = b.code || ''; } catch (e) {}
const err = new Error(msg || `${path}: ${r.status}`);
// A refusal the SERVER wrote (EST-10) — callers tell it apart from an
// unreachable panel by these, and act on `code` (pack_missing -> Models).
err.status = r.status;
err.code = code;
+ err.body = body;
throw err;
}
return r.status === 409 ? { error: 'busy' } : r.json().catch(() => ({}));
@@ -5261,14 +5262,149 @@ const STAGE_MUTE_KEY = 'ph_stage_muted';
function _stageMutePreferred() {
try { return localStorage.getItem(STAGE_MUTE_KEY) === '1'; } catch (e) { return false; }
}
+const STAGE_VOLUME_KEY = 'ph_stage_volume';
+function _stageVolumePreferred() {
+ try {
+ const v = parseFloat(localStorage.getItem(STAGE_VOLUME_KEY));
+ return isFinite(v) ? Math.max(0, Math.min(1, v)) : 1;
+ } catch (e) { return 1; }
+}
function _wireStageMutePersistence(video) {
if (!video) return;
video.muted = _stageMutePreferred();
+ try { video.volume = _stageVolumePreferred(); } catch (e) {}
video.addEventListener('volumechange', () => {
- try { localStorage.setItem(STAGE_MUTE_KEY, video.muted ? '1' : '0'); } catch (e) {}
+ try {
+ localStorage.setItem(STAGE_MUTE_KEY, video.muted ? '1' : '0');
+ localStorage.setItem(STAGE_VOLUME_KEY, String(video.volume));
+ } catch (e) {}
});
}
+// ---- THE VIEWER'S OWN PLAY BAR ------------------------------------------------
+// Owner, 6 Nov (testing 5.0.1): the full-screen viewer's volume slider floated in
+// the video's top-right corner - "the most annoying place possible... it should
+// be in the bar". That slider was the browser's own control, which we cannot
+// move. The viewer (the stage player and the full-screen lightbox) now draws its
+// own bar under the picture: play, seek, time, and a speaker with a slider that
+// opens on hover or click. M mutes (shortcuts.js, `player.mute`).
+function _vbFmt(s) {
+ if (!isFinite(s) || s < 0) s = 0;
+ s = Math.floor(s);
+ return Math.floor(s / 60) + ':' + String(s % 60).padStart(2, '0');
+}
+const _VB_ICON_PLAY = '<svg class="ph" aria-hidden="true"><use href="#ph-play-fill"/></svg>';
+const _VB_ICON_PAUSE = '<svg class="ph" aria-hidden="true"><use href="#ph-pause-fill"/></svg>';
+const _VB_ICON_SPEAKER = '<svg class="ph" viewBox="0 0 256 256" aria-hidden="true"><path d="M144 48v160l-56-44H40V92h48z" fill="currentColor"/><path d="M176 96a40 40 0 0 1 0 64M200 72a72 72 0 0 1 0 112" fill="none" stroke="currentColor" stroke-width="14" stroke-linecap="round"/></svg>';
+const _VB_ICON_MUTED = '<svg class="ph" aria-hidden="true"><use href="#ph-speaker-slash"/></svg>';
+
+function viewerBarMute(video, force) {
+ if (!video) return false;
+ const want = (typeof force === 'boolean') ? force : !(video.muted || video.volume === 0);
+ video.muted = want;
+ if (!want && video.volume === 0) { try { video.volume = 0.6; } catch (e) {} }
+ return want;
+}
+
+// Returns the bar element; the caller puts it in the DOM next to the video.
+function buildViewerBar(video) {
+ const bar = document.createElement('div');
+ bar.className = 'vbar';
+ bar.setAttribute('role', 'toolbar');
+ bar.setAttribute('aria-label', 'Video controls');
+ bar.innerHTML =
+ '<button type="button" class="vb-btn vb-play" aria-label="Play" title="Play / pause (Space)"></button>'
+ + '<input type="range" class="vb-seek" min="0" max="1000" step="1" value="0" aria-label="Seek">'
+ + '<span class="vb-time" aria-live="off">0:00 / 0:00</span>'
+ + '<span class="vb-vol">'
+ + '<button type="button" class="vb-btn vb-mute" aria-label="Mute" title="Mute / unmute (M)"></button>'
+ + '<input type="range" class="vb-volume" min="0" max="100" step="1" value="100" aria-label="Volume">'
+ + '</span>';
+ const play = bar.querySelector('.vb-play');
+ const seek = bar.querySelector('.vb-seek');
+ const time = bar.querySelector('.vb-time');
+ const vol = bar.querySelector('.vb-vol');
+ const mute = bar.querySelector('.vb-mute');
+ const slider = bar.querySelector('.vb-volume');
+ let seeking = false, openTimer = null;
+ const paintPlay = () => {
+ play.innerHTML = video.paused ? _VB_ICON_PLAY : _VB_ICON_PAUSE;
+ play.setAttribute('aria-label', video.paused ? 'Play' : 'Pause');
+ bar.classList.toggle('is-paused', video.paused);
+ };
+ const paintTime = () => {
+ const d = video.duration;
+ if (!seeking && isFinite(d) && d > 0) seek.value = String(Math.round(video.currentTime / d * 1000));
+ time.textContent = _vbFmt(video.currentTime) + ' / ' + _vbFmt(d);
+ };
+ const paintVol = () => {
+ const silent = video.muted || video.volume === 0;
+ mute.innerHTML = silent ? _VB_ICON_MUTED : _VB_ICON_SPEAKER;
+ mute.setAttribute('aria-label', silent ? 'Unmute' : 'Mute');
+ vol.classList.toggle('is-muted', silent);
+ slider.value = String(silent ? 0 : Math.round(video.volume * 100));
+ };
+ play.addEventListener('click', () => {
+ window._stagePlaybackIntentAt = Date.now();
+ if (video.paused) { const p = video.play(); if (p && p.catch) p.catch(() => {}); } else video.pause();
+ });
+ seek.addEventListener('input', () => {
+ seeking = true;
+ const d = video.duration;
+ if (isFinite(d) && d > 0) video.currentTime = d * (parseFloat(seek.value) / 1000);
+ });
+ seek.addEventListener('change', () => { seeking = false; });
+ mute.addEventListener('click', () => {
+ viewerBarMute(video);
+ vol.classList.add('open');
+ clearTimeout(openTimer);
+ openTimer = setTimeout(() => vol.classList.remove('open'), 2500);
+ });
+ slider.addEventListener('input', () => {
+ const v = parseFloat(slider.value) / 100;
+ video.volume = v;
+ video.muted = v === 0;
+ });
+ video.addEventListener('play', paintPlay);
+ video.addEventListener('pause', paintPlay);
+ video.addEventListener('timeupdate', paintTime);
+ video.addEventListener('loadedmetadata', paintTime);
+ video.addEventListener('durationchange', paintTime);
+ video.addEventListener('volumechange', paintVol);
+ video.addEventListener('click', () => play.click());
+ paintPlay(); paintTime(); paintVol();
+ return bar;
+}
+
+// The stage player: the bar lies over the bottom of the picture (it fades in on
+// hover and stays while paused).
+function attachStageViewerBar(video) {
+ if (!video || !video.parentNode) return null;
+ video.removeAttribute('controls');
+ const bar = buildViewerBar(video);
+ bar.classList.add('vbar-stage');
+ video.insertAdjacentElement('afterend', bar);
+ return bar;
+}
+// The full-screen viewer: the picture and the bar are one column.
+function attachLightboxViewerBar(video) {
+ if (!video || !video.parentNode) return null;
+ video.removeAttribute('controls');
+ const box = document.createElement('div');
+ box.className = 'vbox-lb';
+ video.parentNode.insertBefore(box, video);
+ box.appendChild(video);
+ const bar = buildViewerBar(video);
+ bar.classList.add('vbar-lb');
+ box.appendChild(bar);
+ return bar;
+}
+function viewerVideo() {
+ const lb = document.getElementById('expandLightbox');
+ if (lb && lb.style.display === 'flex') return lb.querySelector('video');
+ return document.querySelector('#playerWrap video');
+}
+
function stageMayAutoSelectOutput() {
return !activePath && !window._liveStageOwnsPlayer;
}
@@ -5517,9 +5653,10 @@ function selectOutput(path, options) {
} else if (liveBackdrop) {
wrap.innerHTML =
`<img class="player-handoff-backdrop" src="${escapeHtml(liveBackdrop)}" alt="">` +
- `<video class="player-handoff-media" controls${autoplay ? ' autoplay' : ''} src="${escapeHtml(playerSrc)}"></video>`;
+ `<video class="player-handoff-media"${autoplay ? ' autoplay' : ''} src="${escapeHtml(playerSrc)}"></video>`;
const handoffVideo = wrap.querySelector('.player-handoff-media');
_wireStageMutePersistence(handoffVideo);
+ attachStageViewerBar(handoffVideo);
const revealFinished = () => {
if (!handoffVideo || !handoffVideo.isConnected) return;
handoffVideo.classList.add('is-ready');
@@ -5536,8 +5673,9 @@ function selectOutput(path, options) {
// settles; controls must never stay transparent forever.
setTimeout(revealFinished, 4000);
} else {
- wrap.innerHTML = `<video controls${autoplay ? ' autoplay' : ''} src="${escapeHtml(playerSrc)}"></video>`;
+ wrap.innerHTML = `<video${autoplay ? ' autoplay' : ''} src="${escapeHtml(playerSrc)}"></video>`;
_wireStageMutePersistence(wrap.querySelector('video'));
+ attachStageViewerBar(wrap.querySelector('video'));
}
// Surface aspect adapts to actual media dimensions so vertical clips
// render vertically (previous hardcoded 16:9 surface + object-fit:cover
@@ -6100,9 +6238,10 @@ function openExpandLightbox() {
? `<div class="expand-audio"><span class="expand-audio-note" aria-hidden="true">♪</span><audio class="train-voice-audio" src="${escapeHtml(o.url)}" controls autoplay></audio></div>`
: isPhoto
? `<img src="${o.url}" alt="${escapeHtml(o.name)}">`
- : `<video src="${o.url}" controls autoplay playsinline></video>`;
+ : `<video src="${o.url}" autoplay playsinline></video>`;
const media = stage.querySelector('video, audio');
_wireStageMutePersistence(stage.querySelector('video'));
+ if (!isAudio && !isPhoto) attachLightboxViewerBar(stage.querySelector('video'));
if (media) {
media.addEventListener('ended', () => { if (LB.playing && lbIsOpen() && media.isConnected) lbStep(1); });
media.addEventListener('error', () => {
@@ -6670,6 +6809,11 @@ async function faceFixClip(path, opts) {
try { r = await (await fetch('/queue/facefix', { method: 'POST', body: fd })).json(); }
catch (e) { r = { ok: false, error: String(e) }; }
const name = String(path).split('/').pop();
+ if (r && !r.ok && r.pinokio && typeof pinokioReuseToast === 'function') {
+ // Pinokio already has the adapter: offer to use it from there first, download second.
+ pinokioReuseToast(r, () => faceFixClip(path, opts));
+ return r;
+ }
if (!r || !r.ok) {
phosToast((r && r.error) || (FACE_FIX_NAME + ' could not be queued.'),
{ kind: 'danger', duration: 9000 });
@@ -8957,11 +9101,17 @@ document.getElementById('genForm').addEventListener('submit', async e => {
// not "offline" — show its sentence, and for a missing download offer
// the place to get it, before anything renders.
if (e && e.status) {
+ const _pk = e.body && e.body.pinokio;
const shown = (e.code === 'pack_missing' && typeof _phModalShow === 'function'
&& typeof openModelsModal === 'function')
- && _phModalShow({ kicker: 'Needs a download', title: 'Not queued',
- body: e.message, primaryLabel: 'Open Models',
- onPrimary: () => openModelsModal(), secondaryLabel: 'Not now' });
+ && (_pk
+ ? _phModalShow({ kicker: 'Already on this Mac', title: 'Not queued',
+ body: e.message, primaryLabel: 'Use it from your Pinokio install',
+ onPrimary: () => reuseFromPinokio(_pk.repo_key),
+ secondaryLabel: 'Download instead', onSecondary: () => openModelsModal() })
+ : _phModalShow({ kicker: 'Needs a download', title: 'Not queued',
+ body: e.message, primaryLabel: 'Open Models',
+ onPrimary: () => openModelsModal(), secondaryLabel: 'Not now' }));
if (!shown) phosToast(e.message, { kind: 'danger', duration: 0 });
return;
}
@@ -9300,4 +9450,4 @@ function studioMotionInit() {
});
}
-Object.assign(globalThis, {studioMotionInit, studioProgress});
+Object.assign(globalThis, {studioMotionInit, studioProgress, viewerVideo, viewerBarMute});
diff --git a/webapp/js/remote.js b/webapp/js/remote.js
index 8a6eee4..737866a 100644
--- a/webapp/js/remote.js
+++ b/webapp/js/remote.js
@@ -56,10 +56,93 @@ function rmIsMember(st) {
return !!(st && st.pro) || !!document.documentElement.dataset.pro;
}
+// The member's setup state while the Remote module is not loaded: what is happening, what went
+// wrong in plain words, and the one next action. Never a dead "not set up".
+function rmWaitView(st) {
+ const parts = st.parts || {};
+ let title = 'Remote Control is being set up';
+ let body = 'Your Pro licence is active. Checking for the Remote Control components.';
+ let err = '';
+ let retry = false, settings = false;
+ let start = false;
+ if (parts.managed_by === 'mac_app' && st.pro) {
+ // Pro was switched on after the engine started: the engine that is running is the Free one
+ // and Remote lives in the Pro one. The app starts it for you, no restart of Phosphene needed.
+ title = 'Set up Remote';
+ body = 'Pro is on. One step left: start Remote. Phosphene restarts its engine for a moment; your clips and queue are kept.';
+ start = true;
+ } else if (st.needs_licence) {
+ title = 'One more step: your key in this Studio';
+ body = st.next || 'Paste your licence key in Settings > Pro.';
+ settings = true;
+ } else if (parts.restart_needed) {
+ title = 'Restart the Studio to finish';
+ body = 'New Remote Control components are installed. Restart Phosphene in Pinokio to start using them.';
+ } else if (parts.busy) {
+ const ph = parts.phase;
+ title = ph === 'verifying' ? 'Checking the download' : ph === 'downloading' ? 'Downloading Remote Control' : 'Checking for Remote Control';
+ body = 'This takes a minute. This page updates by itself.';
+ } else if (parts.error) {
+ title = 'Remote Control could not be installed yet';
+ body = 'Your Pro licence is fine. The components did not install.';
+ err = parts.message || 'Try again in a moment.';
+ retry = true;
+ } else if (st.next) {
+ body = st.next;
+ settings = true;
+ }
+ return { title, body, err, retry, settings, start };
+}
+
+function rmRenderWait(st) {
+ const v = rmWaitView(st);
+ $('rmWaitTitle').textContent = v.title;
+ $('rmWaitBody').textContent = v.body;
+ const e = $('rmWaitErr'); e.hidden = !v.err; e.textContent = v.err;
+ $('rmWaitRetry').hidden = !v.retry;
+ $('rmWaitSettings').hidden = !v.settings;
+ const go = $('rmWaitStart'); if (go) go.hidden = !v.start;
+}
+
+// "Set up Remote" in the Mac app: ask the app (WKWebView bridge, NativeBridge.swift) to start the
+// engine that carries Remote. Anywhere else there is no bridge: say what to do by hand.
+function rmStartInApp() {
+ const h = window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.phosphene;
+ if (h) {
+ try {
+ h.postMessage({ type: 'startRemote' });
+ phosToast('Starting Remote. This takes a moment.');
+ return;
+ } catch (e) { /* fall through */ }
+ }
+ phosToast('Quit Phosphene and open it again to finish setting up Remote.', { kind: 'info' });
+}
+
+async function rmPartsRetry() {
+ const b = $('rmWaitRetry'); if (b) b.disabled = true;
+ try {
+ const r = await fetch('/remote/parts_retry', { method: 'POST' });
+ const d = await r.json();
+ if (d && d.message) phosToast(d.message);
+ } catch (e) { phosToast('Could not reach the Studio.', { kind: 'danger' }); }
+ if (b) setTimeout(() => { b.disabled = false; }, 3000);
+ rmRefresh();
+}
+
function rmConnection(st) {
// -> [class, text]
- if (!st.available || !st.pro) return ['off', rmIsMember(st) ? 'Not set up yet' : 'Pro feature'];
+ if (!st.available || !st.pro) {
+ if (!rmIsMember(st)) return ['off', 'Pro feature'];
+ const p = st.parts || {};
+ if (p.managed_by === 'mac_app' && st.pro) return ['warn', 'Not started yet'];
+ if (st.needs_licence) return ['warn', 'Needs your key here'];
+ if (p.restart_needed) return ['warn', 'Restart to finish'];
+ if (p.busy) return ['warn', 'Setting up\u2026'];
+ if (p.error) return ['bad', 'Setup failed \u00b7 try again'];
+ return ['off', 'Setting up\u2026'];
+ }
if (!st.enabled || !st.running) return ['off', 'Off'];
+ if (!(st.devices || []).some((d) => d.confirmed)) return ['warn', 'Not paired yet \u00b7 set up below'];
const anyPhone = (st.devices || []).some((d) => d.connected);
const lan = !!st.lan, relay = st.relay === 'connected';
if (anyPhone) return ['on', 'Phone connected' + (lan ? ' · same Wi-Fi' : ' · via relay')];
@@ -77,7 +160,7 @@ function rmRender() {
// A Pro member never sees the upsell: no Remote module yet = a status line instead.
const member = rmIsMember(st);
pro.hidden = !gated || member;
- if (wait) wait.hidden = !gated || !member;
+ if (wait) { wait.hidden = !gated || !member; if (!wait.hidden) rmRenderWait(st); }
main.hidden = gated;
const [cls, text] = rmConnection(st);
$('rmConnDot').className = 'rm-dot ' + cls;
@@ -101,6 +184,7 @@ function rmRender() {
if (!pairing.open) { offer = null; drawnUrl = ''; }
const devs = (st.devices || []).filter((d) => d.confirmed);
+ const pt = $('rmPairTitle'); if (pt) pt.textContent = devs.length ? 'Pair another iPhone' : 'Set up Remote';
$('rmPhonesCount').textContent = devs.length ? String(devs.length) : '';
$('rmPhonesEmpty').hidden = devs.length > 0;
const ul = $('rmPhones');
@@ -215,4 +299,4 @@ function remoteTabLeave() {
if (poll) { clearInterval(poll); poll = null; }
}
-Object.assign(globalThis, { remoteTabEnter, remoteTabLeave });
+Object.assign(globalThis, { remoteTabEnter, remoteTabLeave, rmPartsRetry, rmStartInApp });
diff --git a/webapp/js/settings.js b/webapp/js/settings.js
index fbfe3b8..47fdbf0 100644
--- a/webapp/js/settings.js
+++ b/webapp/js/settings.js
@@ -1589,8 +1589,10 @@ async function proStatusRefresh() {
// instead, and the Mac app has its own Pro chip in the top bar.
const btn = document.getElementById('proBtn');
// A member sees the door only to manage the licence this Studio holds (the modal hides the selling then).
- if (btn) { btn.hidden = isMacApp() || (active && !(st && st.own_licence)); btn.textContent = active ? 'Licence' : 'Pro'; }
- if (mark) { mark.hidden = !active; mark.textContent = ''; const d = document.createElement('span'); d.className = 'pro-mark-dash'; d.setAttribute('aria-hidden', 'true'); mark.append(d, active && st.label ? st.label.toUpperCase() : 'PRO'); }
+ // Pinokio: always reachable. A Pro Mac that only borrows the Mac app's pass must still be able to paste its own key
+ // (Remote's components and renewal while the app is closed need it).
+ if (btn) { btn.hidden = isMacApp(); btn.textContent = active ? 'Licence' : 'Pro'; }
+ if (mark) { mark.hidden = !active; mark.textContent = active && st.label ? st.label : 'Pro'; }
return st;
}
// Settings > Pro on Pinokio: the Studio takes the licence key itself (pro_licence.py).
@@ -1604,7 +1606,8 @@ function proLicenceShow(doc) {
st.textContent = msg;
st.dataset.on = pro ? '1' : '';
const own = !!lic.licensed;
- document.getElementById('proLicenceForm').hidden = pro;
+ // The key box is hidden only when this Studio already holds its own working licence; borrowed Pro (the Mac app's pass) keeps it.
+ document.getElementById('proLicenceForm').hidden = pro && own;
document.getElementById('proLicenceActions').hidden = !own;
}
async function proLicenceLoad() {
diff --git a/webapp/js/shortcuts.js b/webapp/js/shortcuts.js
index 2f7a69b..ac0ef7c 100644
--- a/webapp/js/shortcuts.js
+++ b/webapp/js/shortcuts.js
@@ -80,6 +80,9 @@ const SHORTCUTS = [
{ id: 'player.toggle', scope: 'outputs', combos: ['space'], owner: 'shortcuts.js',
label: 'Play / pause the selected output',
run: (ev) => shortcutTogglePlayer(ev) },
+ { id: 'player.mute', scope: 'outputs', combos: ['m'], owner: 'shortcuts.js',
+ label: 'Mute / unmute the player (works in the expanded player too)',
+ run: (ev) => shortcutMuteViewer(ev) },
{ id: 'outputs.step', scope: 'outputs', combos: ['arrowleft', 'arrowright'], owner: 'queue.js',
label: 'Previous / next output — wraps at the ends, works in the expanded player too' },
{ id: 'outputs.expand', scope: 'outputs', combos: ['f'], owner: 'queue.js',
@@ -484,6 +487,17 @@ function shortcutTogglePlayer(ev) {
else v.pause();
}
+function shortcutMuteViewer(ev) {
+ const t = ev.target;
+ if (t && t.closest && t.closest('input, textarea, select, [contenteditable]')) return false;
+ const lb = document.getElementById('expandLightbox');
+ const lbOpen = lb && lb.style.display === 'flex';
+ if (!lbOpen && (shortcutTopModal() || !_scOnOutputsTab())) return false;
+ const v = (typeof viewerVideo === 'function') ? viewerVideo() : null;
+ if (!v) return false;
+ viewerBarMute(v);
+}
+
function shortcutTrashOutput() {
if (shortcutTopModal() || !_scOnOutputsTab()) return false;
if (typeof activePath === 'undefined' || !activePath || typeof deleteOutput !== 'function') return false;
diff --git a/webapp/style/panel.css b/webapp/style/panel.css
index 366a6f7..c1a9b27 100644
--- a/webapp/style/panel.css
+++ b/webapp/style/panel.css
@@ -155,15 +155,6 @@
letter-spacing: 0.12em;
cursor: help;
}
- /* Edition label (PHOSPHENE_EDITION=pro, set by the Mac app): the brand
- violet, quieter than DEV/TEST - it states what this is, it does not
- warn. A label only; body[data-edition] is the hook for anything more. */
- .profile-badge.edition-badge {
- background: rgba(139,92,246,0.16);
- color: #b69cff;
- border-color: rgba(139,92,246,0.5);
- cursor: default;
- }
/* Phosphene 2.0 release badge — sits next to the wordmark logo so
users immediately know they're on the major version bump. Brand
violet vs the DEV badge's amber so they don't visually clash when
@@ -2572,6 +2563,9 @@
padding: 0 14px; color: var(--muted); font-size: var(--fs-sm);
pointer-events: none; max-width: 640px;
}
+ .sbe-track-empty .sbe-track-all {
+ pointer-events: auto; margin-left: 12px; white-space: nowrap;
+ }
/* ---- THE CLIP BAR -----------------------------------------------
The verbs, above the tracks, always on screen. See the block comment
@@ -14921,13 +14915,12 @@ body > header .star-link.is-calling svg { animation: star-twinkle 14s ease-in-ou
.star-ask #starAskGo, .star-ask .modal-actions .btn { white-space: nowrap; flex: 1 1 0; }
/* ---------- Pro: the mark beside the wordmark, the speed receipt chip, the Free-vs-Pro player ---------- */
-.pro-mark { display: inline-flex; align-items: center; gap: 6px; margin-left: 8px; padding: 2px 8px 2px 6px; border-radius: 6px; font: 700 11px/16px var(--mono, ui-monospace, monospace); letter-spacing: 0.14em;
- color: #0d0d0e; background: linear-gradient(90deg, #ff2e9f, #b14aff 52%, #5eeaff); box-shadow: 0 0 0 1px rgba(255,255,255,0.12) inset, 0 4px 14px -6px rgba(177,74,255,0.8); align-self: center; vertical-align: middle; }
+.pro-mark { display: inline-flex; align-items: center; margin-left: -4px; padding: 3px 9px; border-radius: var(--r-xs); font-size: 13px; font-weight: 700; letter-spacing: 0.12em; cursor: default;
+ color: #b69cff; background: rgba(139,92,246,0.16); border: 1px solid rgba(139,92,246,0.5); align-self: center; vertical-align: middle; } /* the one Pro tag (owner, 6 Nov): brand violet box, beside the wordmark */
.pro-mark[hidden] { display: none; }
-.pro-mark-dash { width: 10px; height: 3px; border-radius: 1px; background: #0d0d0e; opacity: 0.75; }
.pro-chip { display: inline-flex; align-items: center; gap: 6px; padding: 1px 7px; border-radius: 5px; font: 500 11px/16px var(--mono, ui-monospace, monospace); letter-spacing: 0.04em; color: var(--text, #f4f4f5);
- background: linear-gradient(90deg, rgba(255,46,159,0.18), rgba(177,74,255,0.18) 52%, rgba(94,234,255,0.18)); box-shadow: 0 0 0 1px rgba(177,74,255,0.45) inset; white-space: nowrap; margin-left: 6px; }
-.pro-chip::before { content: ''; width: 6px; height: 6px; border-radius: 50%; background: linear-gradient(90deg, #ff2e9f, #5eeaff); }
+ background: rgba(139,92,246,0.16); box-shadow: 0 0 0 1px rgba(139,92,246,0.5) inset; white-space: nowrap; margin-left: 6px; }
+.pro-chip::before { content: ''; width: 6px; height: 6px; border-radius: 50%; background: #b69cff; }
.card-chip-row .pro-chip { margin-left: 0; }
.pro-compare { margin: 18px 0 6px; padding: 16px 18px 18px; border: 1px solid #2a2a2f; border-radius: 12px; background: #0b0b0c; color: #f4f4f5; }
.pro-compare header h3 { margin: 4px 0 4px; font: 760 20px/1.1 Archivo, -apple-system, sans-serif; font-stretch: 86%; letter-spacing: -0.3px; }
@@ -14936,8 +14929,7 @@ body > header .star-link.is-calling svg { animation: star-twinkle 14s ease-in-ou
.pro-compare-player video { display: block; width: 100%; aspect-ratio: 2048 / 624; }
.pro-compare-labels { position: absolute; left: 0; right: 0; top: 8px; display: flex; justify-content: space-around; pointer-events: none; }
.pro-compare-labels span { padding: 2px 8px; border-radius: 5px; font: 700 11px/16px var(--mono, ui-monospace, monospace); letter-spacing: 0.12em; background: rgba(11, 11, 12,0.72); color: #f4f4f5; }
-.pro-compare-labels span:last-child { background: linear-gradient(90deg, #ff2e9f, #b14aff 52%, #5eeaff); color: #0d0d0e; }
-@media (prefers-reduced-motion: reduce) { .pro-mark { box-shadow: none; } }
+.pro-compare-labels span:last-child { background: rgba(139,92,246,0.16); color: #b69cff; box-shadow: 0 0 0 1px rgba(139,92,246,0.5) inset; }
/* In a gallery card the receipt is its own quiet mono line under the mode chip (the chip row is one ellipsised line otherwise). */
.card-chip-row:has(.pro-chip) { white-space: normal; overflow: visible; }
.card-chip-row .pro-chip { display: flex; width: fit-content; max-width: 100%; margin: 3px 0 0; padding: 0; background: none; box-shadow: none; color: #c99bff; font: inherit; letter-spacing: 0; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
@@ -15171,3 +15163,64 @@ html[data-pro]:not([data-pro=""]) #proModal .pro-prices,
html[data-pro]:not([data-pro=""]) #proModal .pro-compare,
html[data-pro]:not([data-pro=""]) #proModal .pro-benefits,
html[data-pro]:not([data-pro=""]) #proModal .pro-bottom { display: none; }
+
+/* ---- THE VIEWER'S OWN PLAY BAR (queue.js buildViewerBar) --------------------
+ Owner, 6 Nov: the volume slider sat in the video's top-right corner. The
+ viewer now draws its bar: play, seek, time, speaker + slider that opens on
+ hover / focus / click. Used by the stage player (over the picture's bottom
+ edge) and the full-screen viewer (a column under the picture). */
+.vbar {
+ display: flex; align-items: center; gap: 10px;
+ padding: 8px 12px; box-sizing: border-box;
+ background: rgba(10, 12, 18, .78);
+ color: #e8ecf5; font-size: 13px; font-variant-numeric: tabular-nums;
+}
+.vbar-stage {
+ position: absolute; left: 0; right: 0; bottom: 0; z-index: 3;
+ background: linear-gradient(to top, rgba(0,0,0,.78), rgba(0,0,0,0));
+ padding-top: 22px;
+ opacity: 0; transition: opacity 160ms ease;
+}
+.player-wrap:hover .vbar-stage, .vbar-stage:focus-within, .vbar-stage.is-paused { opacity: 1; }
+.vbox-lb {
+ display: flex; flex-direction: column; align-items: center;
+ max-width: 100%; min-height: 0;
+}
+/* the picture keeps its own shape: height capped by the viewport (the lightbox
+ chrome above and below is ~250 px), width follows from the ratio */
+.vbox-lb > video { flex: 0 1 auto; min-height: 0; max-height: calc(100vh - 250px); max-width: 100%; width: auto; height: auto; }
+.expand-lightbox:fullscreen .vbox-lb > video { max-height: calc(100vh - 210px); }
+.vbar-lb { width: min(100%, 900px); border-radius: 0 0 8px 8px; flex: 0 0 auto; }
+.expand-lightbox.is-idle .vbar-lb { opacity: .25; }
+.vb-btn {
+ appearance: none; border: 0; background: transparent; color: inherit;
+ width: 28px; height: 28px; border-radius: 6px; padding: 0; cursor: pointer;
+ display: inline-flex; align-items: center; justify-content: center; flex: 0 0 auto;
+}
+.vb-btn:hover, .vb-btn:focus-visible { background: rgba(255,255,255,.14); outline: none; }
+.vb-btn .ph { width: 18px; height: 18px; fill: currentColor; }
+.vb-seek { flex: 1 1 auto; min-width: 40px; accent-color: #8b7bff; cursor: pointer; }
+.vb-time { flex: 0 0 auto; color: #c3cadb; white-space: nowrap; }
+.vb-vol { display: inline-flex; align-items: center; flex: 0 0 auto; }
+.vb-volume {
+ width: 0; opacity: 0; margin: 0; accent-color: #8b7bff; cursor: pointer;
+ transition: width 160ms ease, opacity 160ms ease, margin 160ms ease;
+}
+.vb-vol:hover .vb-volume, .vb-vol:focus-within .vb-volume, .vb-vol.open .vb-volume {
+ width: 84px; opacity: 1; margin: 0 4px 0 2px;
+}
+.vb-vol.is-muted .vb-mute { color: #ff9a9a; }
+
+/* The small "Pro" mark on the Remote Control item for a Free Mac (owner, 6 Nov): it
+ shows once /pro/status has answered Free (data-pro="" ; absent until then, so a
+ Pro member never sees it flash), and takes the place of the NEW dot. */
+.workflow-tabs .rail-pro { display: none; }
+html[data-pro=""] .tool-rail .workflow-tabs .rail-pro {
+ display: inline-flex; align-items: center; position: absolute; top: 3px; right: 2px;
+ padding: 0 3px; font: 700 13px/15px var(--ph-font-mono, ui-monospace, monospace); letter-spacing: .06em;
+ color: #b69cff; background: rgba(139, 92, 246, .16); border: 1px solid rgba(139, 92, 246, .5);
+ border-radius: 4px; pointer-events: none;
+}
+html[data-pro=""] .tool-rail .workflow-tabs button[data-workflow="remote"] .new-badge { display: none; }
+.rm-pro-wait .rm-wait-actions { display: flex; flex-wrap: wrap; gap: 10px; margin-top: 16px; }
+.rm-pro-wait .rm-wait-actions .rm-btn { width: auto; }