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.

chore(panel): delete dead agent-runtime helpers + JS + CSS

mrbizarro783eb2c0c715
diff --git a/mlx_ltx_panel.py b/mlx_ltx_panel.py
index 221ebd6..45af8b2 100644
--- a/mlx_ltx_panel.py
+++ b/mlx_ltx_panel.py
@@ -4919,13 +4919,6 @@ def run_job_inner(job: dict) -> None:
# ---- worker thread -----------------------------------------------------------
def worker_loop() -> None:
- # Auto-pause bookkeeping. When the local agent engine is running and
- # the user has `auto_pause_during_renders=True` (default), we stop
- # mlx-lm.server before the LTX render starts and restart it after
- # the queue drains. The flag survives across multiple jobs in the
- # same batch so the engine isn't reload-thrashed between shots —
- # one stop at the start of a render burst, one start at the end.
- auto_paused = False
while True:
with QUEUE_COND:
while not STATE["queue"] or STATE["paused"]:
@@ -4942,27 +4935,6 @@ def worker_loop() -> None:
caffeinate_on()
persist_queue()
- # Auto-pause local engine before the render starts. Kept inside
- # the per-iteration body (NOT lifted to the top of the loop) so
- # the pause never fires when the queue has been empty all along
- # — only when there's actual work about to run. Idempotent:
- # subsequent iterations within the same batch see is_running()
- # return False and skip the stop.
- if not auto_paused:
- try:
- _agent_cfg = _load_agent_config()
- if (getattr(_agent_cfg, "auto_pause_during_renders", True)
- and getattr(_agent_cfg, "kind", "") == "phosphene_local"
- and agent_local_server.is_running()):
- agent_local_server.stop("auto-pause: LTX render starting")
- auto_paused = True
- push("[engine] paused for render — will resume when queue drains")
- except Exception as exc: # noqa: BLE001
- # Auto-pause is a nicety; if it errors, the render still
- # runs (the user just pays the swap tax). Surface the
- # reason in the job log for diagnosis without aborting.
- push(f"[engine] auto-pause check failed (continuing): {exc}")
-
try:
run_job_inner(job)
job["status"] = "done"
@@ -4987,43 +4959,21 @@ def worker_loop() -> None:
STATE["pgid"] = None
persist_queue()
- # Resume the local engine ONLY when the queue is fully drained
- # (no current job, nothing queued). If more jobs follow this
- # one we stay paused — restarting between every shot would
- # cost ~10 s × N reloads for nothing. The next iteration of
- # the outer loop will block on QUEUE_COND.wait until either
- # a new job arrives (still paused, fine) or… well, this
- # branch fires here on the way out.
- if auto_paused:
- with LOCK:
- queue_drained = (not STATE["queue"]) and (STATE["current"] is None)
- if queue_drained:
- try:
- _agent_local_start()
- push("[engine] resumed after render")
- auto_paused = False
- except Exception as exc: # noqa: BLE001
- push(f"[engine] resume failed (try Settings → Agent → Start): {exc}")
- auto_paused = False # don't keep retrying on every job
-
-# ---- Agentic Flows integration -----------------------------------------------
-#
-# Wires the `agent/` module into this panel. The agent runs *inside* the panel
-# process (no new microservice — see CLAUDE.md §9 hard constraints), submitting
-# jobs through the same FIFO queue + helper that the manual UI uses.
+# ---- Image Studio + characters integration ----------------------------------
#
-# State lives in two places:
-# - state/agent_config.json — engine config (which LLM, which URL, key)
-# - state/agent_sessions/ — one JSON per chat session (atomic-replaced)
+# The agentic chat surface was removed 2026-05-15 (tag
+# pre-agent-removal-2026-05-15). External agents drive Phosphene through the
+# HTTP API in docs/API.md. What survives here:
+# - state/agent_image_config.json — Image Studio engine config (pluggable
+# mflux / bfl / hidream / mock). Still served by GET/POST
+# /agent/image/config for Image Studio backward compat.
+# - The "agent_image_engine" alias is just `image_engine` (top-level module).
#
-# Both survive Pinokio Reset → Reinstall via the existing fs.link symlink on
-# state/ (see install.js / CLAUDE.md §7 "fs.link"). No extra plumbing needed.
+# State lives in state/ which Pinokio fs.link-preserves across Reset.
-AGENT_CONFIG_PATH = STATE_DIR / "agent_config.json"
AGENT_IMAGE_CONFIG_PATH = STATE_DIR / "agent_image_config.json"
AGENT_LOCK = threading.RLock()
-_AGENT_CONFIG_CACHE: agent_engine.EngineConfig | None = None
# Image-Studio generation lock — serializes /image/generate so two
# concurrent panel tabs (or a fast-double-clicking user) don't spawn
# two mflux subprocesses fighting for the GPU. The lock is acquired in
@@ -5032,170 +4982,9 @@ _AGENT_CONFIG_CACHE: agent_engine.EngineConfig | None = None
# this lock is the server-side safety net.
_IMG_STUDIO_LOCK = threading.Lock()
-# Per-session "turn in progress" locks. ThreadingHTTPServer means a
-# double-click on Send, a browser auto-retry, or a second tab can fire
-# two `/agent/sessions/<sid>/message` calls against the same JSON
-# session. save_session() is atomic but last-writer-wins, and both
-# turns can submit jobs into the queue. We hand out one Lock per
-# session_id and acquire it non-blocking — a concurrent turn returns
-# HTTP 409 instead of corrupting the session. _AGENT_SESSION_LOCKS_GUARD
-# only protects materialization of the dict entry; it is NOT held
-# while the agent loop runs.
-_AGENT_SESSION_LOCKS: dict[str, threading.Lock] = {}
-_AGENT_SESSION_LOCKS_GUARD = threading.Lock()
-
-
-def _agent_session_lock(sid: str) -> threading.Lock:
- """Return the per-session lock, materializing it on first use."""
- with _AGENT_SESSION_LOCKS_GUARD:
- lk = _AGENT_SESSION_LOCKS.get(sid)
- if lk is None:
- lk = threading.Lock()
- _AGENT_SESSION_LOCKS[sid] = lk
- return lk
-
-
_AGENT_IMAGE_CONFIG_CACHE: agent_image_engine.ImageEngineConfig | None = None
-def _default_agent_engine_config() -> agent_engine.EngineConfig:
- """Default engine config: bundled Gemma 3 12B IT via mlx-lm.server.
-
- The Gemma weights ship with Phosphene as the LTX text encoder. They're
- a perfectly capable instruction-tuned chat model — zero extra download
- required to use the agent on a fresh Phosphene install. Users who want
- a stronger agent can drop Qwen 3 Coder 30B-A3B (or similar MLX 4-bit
- chat model) into mlx_models/ and switch via the engine settings drawer.
- """
- return agent_engine.EngineConfig(
- kind="phosphene_local",
- base_url=f"http://127.0.0.1:{agent_local_server._PORT}/v1",
- model="gemma-3-12b-it-4bit",
- local_model_path=str(GEMMA),
- api_key="",
- temperature=0.4,
- max_tokens=8192,
- )
-
-
-def _load_agent_config() -> agent_engine.EngineConfig:
- """Read state/agent_config.json (creating defaults on first call).
-
- Cached after the first read; updates go through _save_agent_config()
- which atomically replaces the file and updates the cache.
- """
- global _AGENT_CONFIG_CACHE
- with AGENT_LOCK:
- if _AGENT_CONFIG_CACHE is not None:
- return _AGENT_CONFIG_CACHE
- if AGENT_CONFIG_PATH.is_file():
- try:
- data = json.loads(AGENT_CONFIG_PATH.read_text(encoding="utf-8"))
- cfg = agent_engine.EngineConfig(**data)
- except (OSError, json.JSONDecodeError, TypeError) as e:
- push(f"agent: invalid agent_config.json ({e}); using defaults")
- cfg = _default_agent_engine_config()
- else:
- cfg = _default_agent_engine_config()
- _AGENT_CONFIG_CACHE = cfg
- return cfg
-
-
-_ALLOWED_REMOTE_HOSTS = {
- # OpenAI-compatible providers we've intentionally tested. The kind="custom"
- # branch lets the user point at any HTTPS endpoint (their own gateway,
- # OpenRouter, etc.); the allow-list below is purely informational and not
- # used to block — see _validate_engine_base_url for the actual policy.
-}
-
-
-def _validate_engine_base_url(kind: str, base_url: str) -> tuple[bool, str]:
- """Block configs that would leak the user's API key to a hostile target.
-
- The agent posts the configured api_key as a Bearer token to whatever
- base_url we save. If the user is talked into pasting `http://evil.com/v1`
- the next message exfiltrates the key in plaintext. Two rules:
-
- * Any non-loopback URL must be HTTPS. Plain http:// outside loopback
- is rejected — even if the user "trusts" the host, an upstream MITM
- could still capture the bearer token.
- * The URL must parse to a real http/https scheme with a host.
- """
- from urllib.parse import urlparse as _u
- url = (base_url or "").strip()
- if not url:
- return False, "base_url is empty"
- try:
- p = _u(url)
- except Exception as e:
- return False, f"unparseable base_url: {e}"
- if p.scheme not in ("http", "https"):
- return False, "base_url must be http:// or https://"
- host = (p.hostname or "").lower()
- if not host:
- return False, "base_url has no host"
- is_loopback = host in {"127.0.0.1", "::1", "localhost"}
- if p.scheme == "http" and not is_loopback:
- return False, "remote base_url must use https:// (refusing to send API key over plaintext)"
- return True, ""
-
-
-def _save_agent_config(updates: dict) -> agent_engine.EngineConfig:
- """Merge `updates` into the current engine config and persist.
-
- Empty-string values are treated as 'leave as-is' for `api_key` so the
- masked /agent/config GET → echo POST round-trip doesn't accidentally
- erase the saved key (mirrors the panel_settings.json convention).
-
- Provider-kind normalization (post-merge): when the resulting `kind`
- changes provider (local ↔ cloud), the frontend can't be trusted to
- clear stale fields the new provider doesn't use — a switch to
- phosphene_local would otherwise inherit the previous Anthropic/
- custom base_url and api_key, and local-engine traffic would either
- leak prompts to a remote endpoint or fail the URL validator. Same
- in reverse: switching to a cloud kind shouldn't leave a local model
- path lying around in the persisted config. Normalize server-side
- so the saved file always reflects only fields the current kind
- actually consumes.
- """
- global _AGENT_CONFIG_CACHE
- with AGENT_LOCK:
- cur = _load_agent_config()
- merged = {**cur.__dict__}
- for k, v in (updates or {}).items():
- if k not in merged:
- continue # ignore unknown fields
- if k == "api_key" and v == "":
- continue # treat blank as no-change for secrets
- merged[k] = v
-
- kind = merged.get("kind", "phosphene_local")
- if kind == "phosphene_local":
- # Local engine always talks to the panel-spawned mlx-lm.server
- # on 127.0.0.1. Force the URL and wipe any cloud secret so a
- # subsequent kind switch back to a cloud provider re-prompts
- # for credentials rather than re-using a stale leak.
- local_port = int(os.environ.get("LTX_AGENT_LOCAL_PORT", "8200"))
- merged["base_url"] = f"http://127.0.0.1:{local_port}/v1"
- merged["api_key"] = ""
- else:
- # Cloud / external provider: drop the local-only model path so
- # the persisted config doesn't carry it forward into Settings
- # round-trips. Don't drop api_key here — the user just typed
- # it; the caller already handled the empty-string-means-keep
- # convention above.
- merged["local_model_path"] = ""
-
- cfg = agent_engine.EngineConfig(**merged)
- ok, why = _validate_engine_base_url(cfg.kind, cfg.base_url)
- if not ok:
- raise ValueError(why)
- STATE_DIR.mkdir(parents=True, exist_ok=True)
- atomic_write_text(AGENT_CONFIG_PATH, json.dumps(cfg.__dict__, indent=2))
- _AGENT_CONFIG_CACHE = cfg
- return cfg
-
-
def _load_agent_image_config() -> agent_image_engine.ImageEngineConfig:
"""Read state/agent_image_config.json (creating defaults on first call).
@@ -5506,38 +5295,6 @@ def _save_agent_image_config(updates: dict) -> agent_image_engine.ImageEngineCon
return cfg
-def _agent_capabilities(*, include_secrets: bool = False) -> dict:
- """Hardware-tier snapshot the agent uses to clamp its plan.
-
- Mirrors the SYSTEM_CAPS table in tier-friendly form so the system
- prompt can show the user what this Mac can actually render. Also
- carries the current image-engine config so the `generate_shot_images`
- tool can dispatch without circular imports.
-
- `include_secrets` controls whether the api_key fields (BFL key etc.)
- are returned. The HTTP-facing endpoint (`GET /agent/config`) calls
- this with the default (False) → masked dict. The PanelOps construction
- used by tools.py inside the agent loop calls with True so the actual
- BFL request can authenticate.
- """
- img_cfg = _load_agent_image_config()
- return {
- "tier": SYSTEM_TIER,
- "tier_label": SYSTEM_CAPS.get("label", SYSTEM_TIER),
- "max_dim_t2v": tier_max_dim("t2v"),
- "max_dim_i2v": tier_max_dim("i2v"),
- "max_dim_kf": tier_max_dim("keyframe"),
- "max_dim_extend": tier_max_dim("extend"),
- "allows_q8": SYSTEM_CAPS.get("allows_q8", False),
- "allows_keyframe": SYSTEM_CAPS.get("allows_keyframe", False),
- "allows_extend": SYSTEM_CAPS.get("allows_extend", False),
- "image_engine_config": (
- dict(img_cfg.__dict__) if include_secrets
- else img_cfg.to_public_dict()
- ),
- }
-
-
def _descriptive_filename(label: str, prompt: str, *, fallback: str) -> str:
"""Build a descriptive output stem from the user-set label or prompt.
@@ -5583,517 +5340,6 @@ def _unique_output_path(base: Path, stem: str, ext: str = ".mp4") -> Path:
i += 1
-def _agent_submit_job(form: dict) -> dict:
- """PanelOps.submit_job: build a job and append to the live FIFO queue.
-
- Goes through the exact same path /run / /queue/add use, so jobs
- submitted by the agent are indistinguishable from manual ones once
- queued (same params, same worker, same history bucket).
-
- Pre-flight: verify the helper subprocess can actually run before
- queueing. Catches the 'agent says success, render fails 30 s later
- with [Errno 2] No such file or directory' class of bug — the queue
- accepts anything, but the worker hits a missing helper python and
- the agent never knows.
- """
- if not HELPER_PYTHON.is_file():
- raise RuntimeError(
- f"helper python not found at {HELPER_PYTHON}. "
- f"Renders will fail. Set LTX_HELPER_PYTHON env var to a valid "
- f"interpreter or reinstall via Pinokio (which sets it for you). "
- f"Tried: {MLX}/.venv/bin/python3.11, {MLX}/env/bin/python3.11."
- )
- if not HELPER_SCRIPT.is_file():
- raise RuntimeError(
- f"helper script not found at {HELPER_SCRIPT}. "
- f"The mlx_warm_helper.py file is missing — reinstall the panel."
- )
- job = make_job(form)
- with QUEUE_COND:
- STATE["queue"].append(job)
- QUEUE_COND.notify_all()
- persist_queue()
- push(f"agent: queued job {job['id']} mode={job['params'].get('mode')} "
- f"label={job['params'].get('label') or '-'}")
- return job
-
-
-def _agent_queue_snapshot() -> dict:
- with LOCK:
- return {
- "running": STATE.get("running", False),
- "current": dict(STATE["current"]) if STATE.get("current") else None,
- "queue": [dict(j) for j in STATE.get("queue", [])],
- "history": [dict(j) for j in STATE.get("history", [])][:30],
- }
-
-
-def _agent_find_job(job_id: str) -> dict | None:
- with LOCK:
- cur = STATE.get("current")
- if cur and cur.get("id") == job_id:
- return dict(cur)
- for j in STATE.get("queue", []):
- if j.get("id") == job_id:
- return dict(j)
- for j in STATE.get("history", []):
- if j.get("id") == job_id:
- return dict(j)
- return None
-
-
-def _build_panel_ops() -> agent_tools.PanelOps:
- # The PanelOps surface is in-process only — passed to tool dispatch.
- # The capabilities dict here MUST include the bfl_api_key / etc. so
- # `generate_shot_images` can authenticate. The HTTP-facing
- # `/agent/config` endpoint calls _agent_capabilities() WITHOUT
- # include_secrets, masking the keys.
- return agent_tools.PanelOps(
- submit_job=_agent_submit_job,
- queue_snapshot=_agent_queue_snapshot,
- find_job=_agent_find_job,
- outputs_dir=OUTPUT,
- uploads_dir=UPLOADS,
- capabilities=_agent_capabilities(include_secrets=True),
- state_dir=STATE_DIR,
- # Wire the LoRA listing so the agent's `list_loras` tool can read
- # installed LoRAs. The agent can then recommend them on shots
- # via submit_shot's `loras` arg. INSTALL stays user-driven (the
- # CivitAI browser has a consent gate).
- list_loras_fn=list_user_loras,
- )
-
-
-def _agent_log_sink(line: str) -> None:
- """Forward mlx-lm.server stdout into the panel's Logs tab."""
- push(line)
-
-
-_ATTACHMENTS_RE = re.compile(
- r"^<attachments>\s*(.*?)\s*</attachments>\s*", re.DOTALL
-)
-
-
-def _split_user_attachments(content: str) -> tuple[str, list[dict]]:
- """Pull a leading `<attachments>JSON</attachments>` block off a user
- message, returning (visible_text, attachments_list).
-
- The block is the wire convention for image/PDF/text attachments — see
- the /message handler. Anything that fails to parse is left in place
- so the user can still read what they typed.
- """
- m = _ATTACHMENTS_RE.match(content or "")
- if not m:
- return content, []
- try:
- atts = json.loads(m.group(1))
- if not isinstance(atts, list):
- return content, []
- except (json.JSONDecodeError, ValueError):
- return content, []
- return content[m.end():], atts
-
-
-def _render_session_messages(sess: agent_runtime.Session) -> list[dict]:
- """Format session.messages for the chat UI.
-
- The raw message list contains:
- - the system prompt (skip in UI)
- - user messages (show as user bubbles, optionally with attachments)
- - assistant messages (may contain a fenced action block — strip it
- for display, surface the parsed tool name as a chip)
- - tool result wrapper user messages (parse, show as a tool-result
- chip rather than another user bubble)
-
- The UI renders each entry's `kind`: "user" | "assistant" | "tool_call"
- | "tool_result" | "system_note".
- """
- out = []
- for m in sess.messages:
- role = m.get("role", "")
- content = m.get("content", "") or ""
- if role == "system":
- continue # never shown to the user
- if role == "user" and content.startswith("<tool_result"):
- # Synthetic tool-result message inserted by run_turn
- try:
- inner = content.split(">", 1)[1].rsplit("</tool_result>", 1)[0].strip()
- parsed = json.loads(inner) if inner.startswith("{") else {"raw": inner}
- except Exception: # noqa: BLE001
- parsed = {"raw": content}
- out.append({"kind": "tool_result", "result": parsed})
- continue
- if role == "user":
- visible, atts = _split_user_attachments(content)
- entry: dict = {"kind": "user", "content": visible}
- if atts:
- entry["attachments"] = atts
- out.append(entry)
- continue
- if role == "assistant":
- action = agent_tools.parse_action_block(content)
- display = agent_tools.strip_action_block(content)
- entry = {"kind": "assistant", "content": display}
- if action:
- entry["tool_call"] = {
- "tool": action.get("tool"),
- "args": action.get("args", {}),
- }
- # Surface model reasoning to the UI as a separate field so
- # the renderer can show it as a collapsible "Thinking" block.
- # Reasoning is what makes the agent feel "stuck" when it
- # isn't — the user sees no content and assumes nothing's
- # happening, but the model is reasoning.
- if m.get("reasoning"):
- entry["reasoning"] = m["reasoning"]
- out.append(entry)
- continue
- out.append({"kind": role, "content": content})
- return out
-
-
-def _agent_ollama_status(timeout: float = 2.0) -> dict:
- """Probe a local Ollama server. Returns base_url + installed-model list.
-
- Ollama's native API:
- GET http://127.0.0.1:11434/api/tags -> {"models":[{"name", "size", ...}]}
- Its OpenAI-compat surface lives at /v1/* (chat/completions, models, ...)
- so the agent pointing at base_url + /v1 just works once Ollama is
- running.
- """
- base_url = os.environ.get("LTX_OLLAMA_URL", "http://127.0.0.1:11434")
- tags_url = base_url.rstrip("/") + "/api/tags"
- try:
- with urllib.request.urlopen(tags_url, timeout=timeout) as r:
- data = json.loads(r.read())
- except urllib.error.URLError as e:
- return {"running": False, "base_url": base_url,
- "openai_url": base_url.rstrip("/") + "/v1",
- "models": [], "error": f"unreachable: {getattr(e, 'reason', e)}"}
- except Exception as e: # noqa: BLE001
- return {"running": False, "base_url": base_url,
- "openai_url": base_url.rstrip("/") + "/v1",
- "models": [], "error": str(e)}
- models = []
- for m in (data.get("models") or []):
- size = int(m.get("size") or 0)
- details = m.get("details") or {}
- models.append({
- "name": m.get("name") or m.get("model"),
- "size_bytes": size,
- "size_gb": round(size / (1024 ** 3), 2) if size else None,
- "modified_at": m.get("modified_at"),
- "family": details.get("family"),
- "parameter_size": details.get("parameter_size"),
- "quantization": details.get("quantization_level"),
- })
- return {
- "running": True,
- "base_url": base_url,
- "openai_url": base_url.rstrip("/") + "/v1",
- "models": models,
- }
-
-
-# ---- Hugging Face model browser ------------------------------------------
-# `hf` CLI is already installed (used for LoRA + LTX downloads). We piggy-
-# back on the same binary for chat-model installs. Search talks directly
-# to https://huggingface.co/api which doesn't require auth for public
-# models. Install streams `hf download` to the panel log; cancellation
-# uses SIGTERM on the spawned process group.
-HF_MODEL_DOWNLOAD_LOCK = threading.Lock()
-HF_MODEL_DOWNLOAD: dict = {
- "active": False,
- "repo_id": None,
- "started_ts": None,
- "lines": [], # ring of recent lines for the UI to display
- "proc": None,
- "pgid": None,
- "error": None,
- "done": False,
- "target_dir": None,
-}
-_HF_MODEL_LINES_LIMIT = 200
-
-
-def _hf_model_search(query: str = "", *, abliterated: bool = False,
- limit: int = 30, library: str = "mlx",
- pipeline_tag: str = "text-generation") -> list[dict]:
- """Hit the public HF model search endpoint and return chat-capable
- MLX models matching `query`. When `abliterated` is True, swap the
- search term to 'abliterated' so the user gets uncensored variants
- (which are a substring convention in repo ids — `huihui-ai/...`,
- `mlx-community/...-abliterated-...`).
- """
- params = [
- ("library", library),
- ("pipeline_tag", pipeline_tag),
- ("sort", "downloads"),
- ("direction", "-1"),
- ("limit", str(limit)),
- ]
- if abliterated:
- # Combine the user's query with 'abliterated' so they can still
- # narrow ('qwen abliterated' -> qwen variants only).
- q = (query or "").strip()
- params.append(("search", (q + " abliterated").strip()))
- elif query:
- params.append(("search", query.strip()))
-
- url = "https://huggingface.co/api/models?" + urllib.parse.urlencode(params)
- headers = {"Accept": "application/json"}
- try:
- req = urllib.request.Request(url, headers=headers)
- with urllib.request.urlopen(req, timeout=10) as r:
- items = json.loads(r.read())
- except urllib.error.URLError as e:
- raise RuntimeError(f"HF search failed: {getattr(e, 'reason', e)}") from e
- out = []
- for it in (items or []):
- out.append({
- "repo_id": it.get("id") or it.get("modelId"),
- "author": it.get("author"),
- "downloads": it.get("downloads", 0),
- "likes": it.get("likes", 0),
- "last_modified": it.get("lastModified"),
- "tags": it.get("tags") or [],
- "library_name": it.get("library_name") or library,
- "pipeline_tag": it.get("pipeline_tag") or pipeline_tag,
- "gated": bool(it.get("gated")),
- "private": bool(it.get("private")),
- })
- return out
-
-
-def _hf_model_files(repo_id: str) -> dict:
- """Get the file list + total size for a repo. Used for 'this is a
- NN GB download' before clicking Install."""
- url = f"https://huggingface.co/api/models/{repo_id}/tree/main?recursive=true"
- try:
- with urllib.request.urlopen(url, timeout=10) as r:
- items = json.loads(r.read())
- except urllib.error.HTTPError as e:
- if e.code == 401 or e.code == 403:
- return {"repo_id": repo_id, "gated": True,
- "error": f"HTTP {e.code} — model is gated. Open the model card on HF and accept terms first."}
- raise RuntimeError(f"HF tree failed (HTTP {e.code})") from e
- except urllib.error.URLError as e:
- raise RuntimeError(f"HF tree failed: {getattr(e, 'reason', e)}") from e
- files = []
- total = 0
- for f in items:
- if f.get("type") != "file":
- continue
- size = int((f.get("lfs") or {}).get("size") or f.get("size") or 0)
- files.append({"path": f.get("path"), "size_bytes": size})
- total += size
- return {
- "repo_id": repo_id,
- "files": files,
- "total_size_bytes": total,
- "total_size_gb": round(total / (1024 ** 3), 2) if total else 0,
- "file_count": len(files),
- }
-
-
-def _hf_model_install_async(repo_id: str) -> dict:
- """Spawn `hf download {repo_id} --local-dir mlx_models/{name}` in a
- background thread. Status streams via /agent/models/install/status."""
- with HF_MODEL_DOWNLOAD_LOCK:
- if HF_MODEL_DOWNLOAD["active"]:
- return {"ok": False,
- "error": f"download already active for {HF_MODEL_DOWNLOAD['repo_id']}"}
- if not HF_BIN or not Path(HF_BIN).is_file():
- return {"ok": False, "error": "hf CLI not found in this venv"}
-
- # Pick a sensible local dir name — last segment of the repo id.
- # Avoid clobbering existing models by appending _N if needed.
- leaf = repo_id.split("/")[-1]
- target = MODELS_DIR / leaf
- if target.exists():
- i = 2
- while (MODELS_DIR / f"{leaf}_{i}").exists():
- i += 1
- target = MODELS_DIR / f"{leaf}_{i}"
- target.parent.mkdir(parents=True, exist_ok=True)
-
- HF_MODEL_DOWNLOAD["active"] = True
- HF_MODEL_DOWNLOAD["repo_id"] = repo_id
- HF_MODEL_DOWNLOAD["started_ts"] = time.time()
- HF_MODEL_DOWNLOAD["lines"] = []
- HF_MODEL_DOWNLOAD["error"] = None
- HF_MODEL_DOWNLOAD["done"] = False
- HF_MODEL_DOWNLOAD["target_dir"] = str(target)
-
- def _run():
- try:
- cmd = [str(HF_BIN), "download", repo_id, "--local-dir", str(target)]
- env = os.environ.copy()
- env.setdefault("HF_HUB_ENABLE_HF_TRANSFER", "1")
- tok = _active_hf_token() if "_active_hf_token" in globals() else None
- if tok:
- env["HF_TOKEN"] = tok
- proc = subprocess.Popen(
- cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
- env=env, start_new_session=True,
- )
- with HF_MODEL_DOWNLOAD_LOCK:
- HF_MODEL_DOWNLOAD["proc"] = proc
- HF_MODEL_DOWNLOAD["pgid"] = os.getpgid(proc.pid)
- assert proc.stdout is not None
- for raw in proc.stdout:
- line = raw.decode("utf-8", errors="replace").rstrip()
- if not line:
- continue
- with HF_MODEL_DOWNLOAD_LOCK:
- HF_MODEL_DOWNLOAD["lines"].append(line)
- HF_MODEL_DOWNLOAD["lines"] = HF_MODEL_DOWNLOAD["lines"][-_HF_MODEL_LINES_LIMIT:]
- push(f"hf download[{repo_id}]: {line}")
- rc = proc.wait()
- with HF_MODEL_DOWNLOAD_LOCK:
- HF_MODEL_DOWNLOAD["proc"] = None
- HF_MODEL_DOWNLOAD["pgid"] = None
- if rc != 0:
- HF_MODEL_DOWNLOAD["error"] = f"hf download exited {rc}"
- else:
- HF_MODEL_DOWNLOAD["done"] = True
- HF_MODEL_DOWNLOAD["active"] = False
- except Exception as e: # noqa: BLE001
- with HF_MODEL_DOWNLOAD_LOCK:
- HF_MODEL_DOWNLOAD["error"] = f"{type(e).__name__}: {e}"
- HF_MODEL_DOWNLOAD["active"] = False
- HF_MODEL_DOWNLOAD["proc"] = None
- HF_MODEL_DOWNLOAD["pgid"] = None
- push(f"hf download[{repo_id}] crashed: {e}")
-
- threading.Thread(target=_run, daemon=True, name=f"hf-dl-{leaf}").start()
- return {"ok": True, "repo_id": repo_id, "target_dir": str(target)}
-
-
-def _hf_model_install_status() -> dict:
- with HF_MODEL_DOWNLOAD_LOCK:
- return {
- "active": HF_MODEL_DOWNLOAD["active"],
- "repo_id": HF_MODEL_DOWNLOAD["repo_id"],
- "started_ts": HF_MODEL_DOWNLOAD["started_ts"],
- "elapsed_s": (time.time() - HF_MODEL_DOWNLOAD["started_ts"]) if HF_MODEL_DOWNLOAD["started_ts"] else None,
- "lines": list(HF_MODEL_DOWNLOAD["lines"][-30:]), # tail for display
- "last_line": HF_MODEL_DOWNLOAD["lines"][-1] if HF_MODEL_DOWNLOAD["lines"] else "",
- "error": HF_MODEL_DOWNLOAD["error"],
- "done": HF_MODEL_DOWNLOAD["done"],
- "target_dir": HF_MODEL_DOWNLOAD["target_dir"],
- }
-
-
-def _hf_model_install_cancel() -> dict:
- with HF_MODEL_DOWNLOAD_LOCK:
- proc = HF_MODEL_DOWNLOAD.get("proc")
- pgid = HF_MODEL_DOWNLOAD.get("pgid")
- if not proc:
- return {"ok": False, "error": "no active download"}
- try:
- os.killpg(pgid, signal.SIGTERM)
- except ProcessLookupError:
- pass
- return {"ok": True}
-
-
-# Allow-prefixes for HF repo ids passed to /agent/local/start. These are
-# the only owners we ever want mlx_lm.server to download with the user's
-# stored HF token. Anything else (including unknown private orgs) is
-# rejected at endpoint entry — see _validate_local_model_path.
-_LOCAL_MODEL_HF_ALLOWED_OWNERS = (
- "Qwen",
- "mlx-community",
- "lmstudio-community",
- "unsloth",
- "Lightricks",
- "Black-Forest-Labs",
- "lightx2v",
- "filipstrand",
- "huihui-ai",
- "google",
-)
-
-_LOCAL_MODEL_HF_REPO_RE = re.compile(r"^[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+$")
-
-
-def _validate_local_model_path(value: str) -> str:
- """Constrain `model_path` accepted by POST /agent/local/start.
-
- Without this gate, the field is a CSRF + token-burn sink: an attacker
- who beats the loopback/Origin check (or just a misclick on a hostile
- page that bypasses it via some future bug) could ask mlx_lm.server
- to download any HF repo with the user's stored token, or load
- weights from any directory the panel can read.
-
- Acceptable values:
- - HF repo id matching `<owner>/<name>` whose owner is in
- `_LOCAL_MODEL_HF_ALLOWED_OWNERS`.
- - Local path that resolves under `MODELS_DIR` (mlx_models/) or the
- HF cache root (`_hf_cache_root()`).
- Anything else: ValueError → caller maps to HTTP 400.
-
- Empty string is the saved-default case and is handled by the caller
- before reaching here.
- """
- s = (value or "").strip()
- if not s:
- raise ValueError("model_path must not be empty")
-
- # Local path: starts with /, ~, ./, or ../.
- looks_like_path = s.startswith(("/", "~", "./", "../"))
- if looks_like_path:
- try:
- p = Path(s).expanduser().resolve()
- except OSError as e:
- raise ValueError(f"model_path is not resolvable: {e}")
- roots: list[Path] = []
- for r in (MODELS_DIR, _hf_cache_root()):
- try:
- roots.append(r.resolve())
- except OSError:
- pass
- for r in roots:
- try:
- if p.is_relative_to(r):
- return str(p)
- except ValueError:
- continue
- raise ValueError(
- "model_path must resolve under mlx_models/ or the "
- "HuggingFace cache directory"
- )
-
- # HF repo id: <owner>/<name>.
- if not _LOCAL_MODEL_HF_REPO_RE.match(s):
- raise ValueError(
- "model_path must be a HuggingFace repo id "
- "(<owner>/<name>) or a path under mlx_models/"
- )
- owner = s.split("/", 1)[0]
- if owner not in _LOCAL_MODEL_HF_ALLOWED_OWNERS:
- raise ValueError(
- f"model_path owner {owner!r} is not on the allow-list "
- f"({', '.join(_LOCAL_MODEL_HF_ALLOWED_OWNERS)})"
- )
- return s
-
-
-def _agent_local_start(model_path: str | None = None) -> dict:
- """Spawn the bundled mlx-lm.server against the current config's model.
-
- `model_path` overrides the saved `local_model_path` for one-off boots
- (e.g. switching models without persisting the change). HTTP callers
- must pre-validate via `_validate_local_model_path`.
- """
- cfg = _load_agent_config()
- target = model_path or cfg.local_model_path or str(GEMMA)
- venv_py = str(MLX / "env/bin/python3.11")
- return agent_local_server.start(target, venv_python=venv_py,
- log_sink=_agent_log_sink)
-
-
# ---- HTTP --------------------------------------------------------------------
class Handler(BaseHTTPRequestHandler):
@@ -6878,140 +6124,6 @@ class Handler(BaseHTTPRequestHandler):
self._json({"error": "agentic flows removed; see docs/API.md"}, 410)
return
- if parsed.path == "/agent/capabilities":
- # Structured tool catalog — drives the in-app /help sheet so
- # users discover what the agent can actually do (Phase 0 #0.5).
- try:
- catalog = agent_runtime.list_tool_catalog()
- except Exception as e: # noqa: BLE001
- self._json({"error": str(e)}, 500); return
- self._json({
- "tools": catalog,
- "engine_kinds": [
- {"id": "phosphene_local", "label": "Phosphene Local", "cost": "free · on-device"},
- {"id": "anthropic", "label": "Claude (Anthropic)", "cost": "paid · per token"},
- {"id": "ollama", "label": "Ollama bridge", "cost": "free · on-device"},
- {"id": "custom", "label": "Custom (OpenAI-compat)", "cost": "depends"},
- ],
- "image_kinds": [
- {"id": "mock", "label": "Mock", "cost": "free · placeholders"},
- {"id": "mflux", "label": "Local Flux (mflux)", "cost": "free · uses RAM + disk"},
- {"id": "bfl", "label": "Black Forest Labs API", "cost": "paid · per image"},
- ],
- "modes": [
- {"id": "plan_sleep", "label": "Plan & sleep", "desc": "Auto-stop engine on finish; frees RAM for renders"},
- {"id": "interactive", "label": "Interactive", "desc": "Engine stays resident across finishes"},
- ],
- "shot_modes": ["t2v", "i2v", "keyframe", "extend"],
- "quality_tiers": ["quick", "balanced", "standard", "high"],
- })
- return
-
- if parsed.path == "/agent/engine/check":
- # Phase 0 #0.11 — engine readiness probe at session start.
- # Today users upload attachments + write a long prompt before the
- # first chat call surfaces an unreachable engine / 401 / wrong
- # base URL. This endpoint pings the configured engine with the
- # cheapest reachable call (`/v1/models` for OpenAI-compat, same
- # for Anthropic) and returns a structured verdict the UI surfaces
- # as a banner above the chat.
- cfg = _load_agent_config()
- try:
- import time as _time
- _t0 = _time.time()
- ok, message = agent_engine.health_check(cfg, timeout=5)
- latency_ms = int((_time.time() - _t0) * 1000)
- except Exception as e: # noqa: BLE001
- ok = False; message = f"probe error: {e}"; latency_ms = 0
- extra: dict = {}
- if cfg.kind == "phosphene_local":
- local = agent_local_server.status()
- extra["local_server_running"] = bool(local.get("running"))
- # For the bundled local engine: a 401-on-models response is
- # nonsense (no auth there) — surface the real cause, which is
- # almost always "helper not started yet".
- if not ok and not extra["local_server_running"]:
- message = ("Local engine not started. Click the engine "
- "pill in the top header, then 'Start' — or "
- "the agent will start it on first message.")
- # Treat as a soft warning, not a hard fail.
- ok = None # tri-state: True / False / None=warn
- self._json({
- "ok": ok,
- "message": message,
- "kind": cfg.kind,
- "model": cfg.model,
- "latency_ms": latency_ms,
- **extra,
- })
- return
-
- if parsed.path == "/agent/sessions":
- self._json({"sessions": agent_runtime.list_sessions(STATE_DIR)})
- return
-
- if parsed.path == "/agent/notes":
- try:
- from agent import project as _project
- content = _project.read_notes(STATE_DIR)
- except Exception as e: # noqa: BLE001
- self._json({"error": str(e)}, 500); return
- self._json({"content": content, "bytes": len(content.encode("utf-8"))})
- return
-
- if parsed.path.startswith("/agent/sessions/"):
- sid = parsed.path[len("/agent/sessions/"):]
- sid = sid.split("/", 1)[0]
- if not agent_runtime.is_valid_session_id(sid):
- self.send_error(404); return
- sess = agent_runtime.load_session(sid, STATE_DIR)
- if sess is None:
- self.send_error(404); return
- self._json({
- "session": sess.to_dict(),
- "rendered_messages": _render_session_messages(sess),
- })
- return
-
- if parsed.path == "/agent/local/status":
- self._json({
- "local_server": agent_local_server.status(),
- "available_models": agent_local_server.discover_local_models(ROOT),
- })
- return
-
- if parsed.path == "/agent/ollama/status":
- self._json(_agent_ollama_status())
- return
-
- if parsed.path == "/agent/models/search":
- qs = parse_qs(parsed.query)
- q = (qs.get("q", [""])[0] or "").strip()
- abliterated = qs.get("abliterated", ["0"])[0] in ("1", "true", "yes", "on")
- limit = int(qs.get("limit", ["30"])[0] or "30")
- try:
- results = _hf_model_search(q, abliterated=abliterated, limit=limit)
- except RuntimeError as e:
- self._json({"error": str(e)}, 502); return
- self._json({"results": results, "abliterated": abliterated, "query": q})
- return
-
- if parsed.path == "/agent/models/info":
- qs = parse_qs(parsed.query)
- repo_id = (qs.get("repo_id", [""])[0] or "").strip()
- if not repo_id:
- self._json({"error": "repo_id is required"}, 400); return
- try:
- info = _hf_model_files(repo_id)
- except RuntimeError as e:
- self._json({"error": str(e)}, 502); return
- self._json(info)
- return
-
- if parsed.path == "/agent/models/install/status":
- self._json(_hf_model_install_status())
- return
-
if parsed.path == "/agent/image/config":
cfg = _load_agent_image_config()
ok, msg = agent_image_engine.health_check(cfg)
@@ -8231,419 +7343,31 @@ class Handler(BaseHTTPRequestHandler):
self._json({"error": "agentic flows removed; see docs/API.md"}, 410)
return
- if path == "/agent/local/start":
- try:
- if ctype.startswith("application/json"):
- payload = json.loads(body or "{}")
- else:
- payload = {k: v[0] if v else "" for k, v in form.items()}
- except json.JSONDecodeError as e:
- self._json({"error": f"bad JSON: {e}"}, 400); return
- override = (payload.get("model_path") or "").strip() or None
- if override is not None:
- try:
- override = _validate_local_model_path(override)
- except ValueError as e:
- self._json({"error": str(e)}, 400); return
- status = _agent_local_start(override)
- self._json({"ok": status.get("running"), "local_server": status})
- return
-
- if path == "/agent/local/stop":
- status = agent_local_server.stop("manual stop via panel")
- self._json({"ok": True, "local_server": status})
- return
-
- if path == "/agent/sessions/new":
+ # Image-engine config (pluggable: mock | bfl).
+ if path == "/agent/image/config":
try:
payload = (json.loads(body or "{}")
if ctype.startswith("application/json")
else {k: v[0] if v else "" for k, v in form.items()})
except json.JSONDecodeError as e:
self._json({"error": f"bad JSON: {e}"}, 400); return
- title = (payload.get("title") or "").strip() or "Untitled"
- cfg = _load_agent_config()
- sess = agent_runtime.new_session(title=title, engine_config=cfg)
- agent_runtime.save_session(sess, STATE_DIR)
- push(f"agent: new session {sess.session_id} ({sess.title!r})")
- self._json({"ok": True, "session": sess.to_dict()})
- return
-
- if path.startswith("/agent/sessions/") and path.endswith("/message"):
- sid = path[len("/agent/sessions/"):-len("/message")]
- if not agent_runtime.is_valid_session_id(sid):
- self._json({"error": "session not found"}, 404); return
- # Per-session "turn in progress" guard. Try-acquire so a
- # concurrent send (double-click, retry, second tab) returns
- # 409 immediately instead of running a second agent loop
- # against the same JSON session and double-submitting jobs
- # into the queue. Released in the finally below, AFTER the
- # response has been sent on every code path.
- _sess_lock = _agent_session_lock(sid)
- if not _sess_lock.acquire(blocking=False):
- self._json({"error": "session busy"}, 409); return
try:
- sess = agent_runtime.load_session(sid, STATE_DIR)
- if sess is None:
- self._json({"error": "session not found"}, 404); return
- try:
- payload = (json.loads(body or "{}")
- if ctype.startswith("application/json")
- else {k: v[0] if v else "" for k, v in form.items()})
- except json.JSONDecodeError as e:
- self._json({"error": f"bad JSON: {e}"}, 400); return
- user_msg = payload.get("message") or payload.get("content") or ""
- user_msg = user_msg.strip()
-
- # Validate + normalize attachments. Each path must live under
- # UPLOADS — the client can lie about the path even though it
- # came from a /upload response. Without this check, a malicious
- # page could submit /etc/passwd as an attachment and the agent's
- # tools would happily inspect it.
- raw_atts = payload.get("attachments") or []
- attachments: list[dict] = []
- uploads_root = UPLOADS.resolve()
- for a in raw_atts:
- if not isinstance(a, dict):
- continue
- p_str = (a.get("path") or "").strip()
- if not p_str:
- continue
- try:
- p = Path(p_str).resolve()
- except Exception:
- continue
- if not p.is_relative_to(uploads_root) or not p.is_file():
- self._json({"error": f"attachment outside uploads dir or missing: {p_str}"}, 400)
- return
- attachments.append({
- "path": str(p),
- "name": (a.get("name") or p.name)[:200],
- "mime": (a.get("mime") or "")[:80],
- "size": int(a.get("size") or 0),
- })
- if not user_msg and not attachments:
- self._json({"error": "message or attachment is required"}, 400); return
-
- if attachments:
- # Embed an <attachments> JSON block in front of the user text
- # so the agent sees the file references inline. The renderer
- # strips this block back out for display and exposes the
- # parsed list as m.attachments.
- user_msg = (
- "<attachments>\n"
- + json.dumps(attachments)
- + "\n</attachments>\n"
- + user_msg
- )
- # Always re-load the engine config in case the user just changed
- # it via the settings drawer — the session keeps its own copy
- # for record-keeping but we honor the live config for actual calls.
- sess.engine_config = _load_agent_config()
-
- # Auto-start the local engine on first message so the user
- # doesn't dead-end on a connection-refused error. mlx_lm.server
- # boots in ~1-2s; weights load lazily on the first
- # /chat/completions call, which our run_turn timeout (300 s)
- # accommodates. Saves a trip to Settings → Start.
- if (sess.engine_config.kind == "phosphene_local"
- and not agent_local_server.is_running()):
- # Memory guard — refuse to spawn mlx-lm when the Mac is
- # already in swap or close to OOM. Loading a 22 GB Qwen
- # 35B on top of a 64 GB system that's at 90%+ pressure +
- # swap is what put Salo in a force-quit dialog last time.
- # Bail early with an actionable error rather than silently
- # making the system thrash.
- mem = get_memory()
- pressure = mem.get("pressure_pct") or 0
- swap_gb = mem.get("swap_gb") or 0.0
- if pressure >= 92 or swap_gb >= 8:
- push(f"agent: refusing to auto-start local engine "
- f"(memory pressure {pressure}%, swap {swap_gb:.1f} GB)")
- self._json({
- "error": (
- f"Memory too high to start the local engine "
- f"({mem.get('used_gb', 0):.1f}/"
- f"{mem.get('total_gb', 0):.0f} GB used, "
- f"swap {swap_gb:.1f} GB). "
- "Loading a 22 GB chat model on top of this "
- "would force the Mac into heavy swap. "
- "Either: (a) wait for current renders to "
- "finish, (b) switch to a smaller model in "
- "Settings (Gemma 12B is ~7.5 GB), or (c) "
- "quit other heavy apps (Claude.app, Chrome) "
- "and try again."
- ),
- }, 503)
- return
- push("agent: auto-starting local engine for first message")
- _agent_local_start()
- # Wait briefly for /v1/models to respond before we proceed —
- # avoids the very first chat call seeing a half-bound port.
- import urllib.error
- base = sess.engine_config.base_url.rstrip("/") + "/models"
- deadline = time.time() + 30
- ready = False
- while time.time() < deadline:
- try:
- with urllib.request.urlopen(base, timeout=2):
- ready = True
- break
- except (urllib.error.URLError, OSError):
- time.sleep(0.4)
- if not ready:
- push("agent: local engine spawn timed out; surfacing error")
- last = agent_local_server.status().get("last_error") or ""
- self._json({
- "error": (
- "Local engine spawned but isn't responding on "
- f"{base}. Check the Logs tab for mlx-lm output. "
- + (f" Last status: {last}" if last else "")
- ),
- }, 500)
- return
-
- ops = _build_panel_ops()
- tools_doc = agent_runtime.render_tools_doc()
- events: list[dict] = []
- # Pick legacy or smolagents runtime per-request based on env var.
- _runtime = _select_runtime()
- push(f"agent: using runtime={_runtime.__name__.split('.')[-1]}")
-
- # Persist after every event so a client polling
- # /agent/sessions/<id> mid-loop sees the agent's incremental
- # progress (plan, tool call, tool result, next message, ...)
- # rather than a 5-minute silence followed by a single batch.
- # mid-loop disk writes are atomic via runtime.save_session.
- def _on_event(ev: agent_runtime.TurnEvent) -> None:
- try:
- agent_runtime.save_session(sess, STATE_DIR)
- except Exception as e: # noqa: BLE001
- push(f"agent: mid-loop save failed: {e}")
+ cfg = _save_agent_image_config(payload)
+ except ValueError as e:
+ self._json({"error": str(e)}, 400); return
+ push(f"agent: image engine updated to {cfg.kind}"
+ + (f" ({cfg.bfl_model})" if cfg.kind == "bfl" else ""))
+ ok, msg = agent_image_engine.health_check(cfg)
+ self._json({"ok": True, "image_engine": cfg.to_public_dict(),
+ "health_ok": ok, "health_message": msg})
+ return
- try:
- for ev in _runtime.run_turn(
- sess, user_msg, ops, tools_doc=tools_doc,
- on_event=_on_event,
- ):
- events.append({"kind": ev.kind, "payload": ev.payload})
- except Exception as e: # noqa: BLE001
- push(f"agent: run_turn errored: {e}")
- self._json({"error": str(e), "events": events}, 500); return
- agent_runtime.save_session(sess, STATE_DIR)
-
- # Plan-and-sleep mode: the agent has just called `finish` which
- # means the plan is queued and the agent is done thinking for
- # this batch. Drop the local chat model's memory NOW so the
- # LTX renderer has the full RAM budget for the overnight run.
- # On a 64 GB Mac, leaving Qwen 35B (22 GB) resident alongside
- # active renders pushes the system into swap — exactly the
- # scenario the user wants to avoid.
- engine_stopped = False
- if (sess.finished
- and sess.engine_config.kind == "phosphene_local"
- and getattr(sess.engine_config, "mode", "plan_sleep") == "plan_sleep"
- and agent_local_server.is_running()):
- try:
- agent_local_server.stop("plan-and-sleep auto-stop after finish")
- engine_stopped = True
- push("agent: plan-and-sleep — stopped local engine to free RAM for renders")
- except Exception as e: # noqa: BLE001
- push(f"agent: failed to auto-stop local engine: {e}")
+ self.send_error(404)
- self._json({
- "ok": True,
- "events": events,
- "session": sess.to_dict(),
- "rendered_messages": _render_session_messages(sess),
- "engine_stopped": engine_stopped,
- })
- return
- finally:
- _sess_lock.release()
- if path.startswith("/agent/sessions/") and path.endswith("/delete"):
- sid = path[len("/agent/sessions/"):-len("/delete")]
- ok = agent_runtime.delete_session(sid, STATE_DIR)
- self._json({"ok": ok})
- return
-
- if path == "/agent/notes":
- # Manual edit from the Project Notes modal. We overwrite the
- # whole file, so the user gets full control. Empty content
- # collapses to a deletion (file persists with 0 bytes — the
- # excerpt helper handles that).
- try:
- payload = (json.loads(body or "{}")
- if ctype.startswith("application/json")
- else {k: v[0] if v else "" for k, v in form.items()})
- except json.JSONDecodeError as e:
- self._json({"error": f"bad JSON: {e}"}, 400); return
- content = payload.get("content")
- if content is None:
- self._json({"error": "content is required"}, 400); return
- if len(content.encode("utf-8")) > 4 * 1024 * 1024:
- self._json({"error": "notes file too large (max 4 MB)"}, 413); return
- from agent import project as _project
- STATE_DIR.mkdir(parents=True, exist_ok=True)
- atomic_write_text(_project.notes_path(STATE_DIR), content)
- self._json({"ok": True, "bytes": len(content.encode("utf-8"))})
- return
-
- if path.startswith("/agent/sessions/") and path.endswith("/rename"):
- sid = path[len("/agent/sessions/"):-len("/rename")]
- try:
- payload = (json.loads(body or "{}")
- if ctype.startswith("application/json")
- else {k: v[0] if v else "" for k, v in form.items()})
- except json.JSONDecodeError as e:
- self._json({"error": f"bad JSON: {e}"}, 400); return
- new_title = (payload.get("title") or "").strip()
- if not new_title:
- self._json({"error": "title is required"}, 400); return
- ok = agent_runtime.rename_session(sid, new_title, STATE_DIR)
- self._json({"ok": ok})
- return
-
- if path.startswith("/agent/sessions/") and path.endswith("/pin"):
- sid = path[len("/agent/sessions/"):-len("/pin")]
- try:
- payload = (json.loads(body or "{}")
- if ctype.startswith("application/json")
- else {k: v[0] if v else "" for k, v in form.items()})
- except json.JSONDecodeError as e:
- self._json({"error": f"bad JSON: {e}"}, 400); return
- pinned = bool(payload.get("pinned", True))
- ok = agent_runtime.set_pinned(sid, pinned, STATE_DIR)
- self._json({"ok": ok, "pinned": pinned})
- return
-
- # Image-engine config (pluggable: mock | bfl).
- if path == "/agent/image/config":
- try:
- payload = (json.loads(body or "{}")
- if ctype.startswith("application/json")
- else {k: v[0] if v else "" for k, v in form.items()})
- except json.JSONDecodeError as e:
- self._json({"error": f"bad JSON: {e}"}, 400); return
- try:
- cfg = _save_agent_image_config(payload)
- except ValueError as e:
- self._json({"error": str(e)}, 400); return
- push(f"agent: image engine updated to {cfg.kind}"
- + (f" ({cfg.bfl_model})" if cfg.kind == "bfl" else ""))
- ok, msg = agent_image_engine.health_check(cfg)
- self._json({"ok": True, "image_engine": cfg.to_public_dict(),
- "health_ok": ok, "health_message": msg})
- return
-
- # Anchor selection — user clicked a thumbnail in the chat.
- # Records {shot_label: candidate_dict} in the session's tool_state.
- if path == "/agent/models/install":
- try:
- payload = (json.loads(body or "{}")
- if ctype.startswith("application/json")
- else {k: v[0] if v else "" for k, v in form.items()})
- except json.JSONDecodeError as e:
- self._json({"error": f"bad JSON: {e}"}, 400); return
- repo_id = (payload.get("repo_id") or "").strip()
- if not repo_id:
- self._json({"error": "repo_id is required"}, 400); return
- # M2: same allowlist as /agent/local/start (H3, commit 947af34)
- # — endpoint downloads with the user's stored HF token, so an
- # attacker who beats the loopback/Origin check could fetch
- # any HF repo (gated, huge, malicious) without this gate.
- # Reuse `_LOCAL_MODEL_HF_REPO_RE` + `_LOCAL_MODEL_HF_ALLOWED_OWNERS`
- # rather than a parallel list. See security-review.md §M2.
- if not _LOCAL_MODEL_HF_REPO_RE.match(repo_id):
- self._json({"error": (
- "repo_id must look like <owner>/<name> using "
- "[A-Za-z0-9_.-]"
- )}, 400)
- return
- owner = repo_id.split("/", 1)[0]
- if owner not in _LOCAL_MODEL_HF_ALLOWED_OWNERS:
- self._json({"error": (
- f"repo_id owner {owner!r} is not on the allow-list "
- f"({', '.join(_LOCAL_MODEL_HF_ALLOWED_OWNERS)})"
- )}, 400)
- return
- res = _hf_model_install_async(repo_id)
- if not res.get("ok"):
- self._json(res, 409 if "already" in (res.get("error") or "") else 500)
- return
- self._json(res)
- return
-
- if path == "/agent/models/install/cancel":
- self._json(_hf_model_install_cancel())
- return
-
- if path.startswith("/agent/sessions/") and path.endswith("/anchors/select"):
- sid = path[len("/agent/sessions/"):-len("/anchors/select")]
- if not agent_runtime.is_valid_session_id(sid):
- self._json({"error": "session not found"}, 404); return
- sess = agent_runtime.load_session(sid, STATE_DIR)
- if sess is None:
- self._json({"error": "session not found"}, 404); return
- try:
- payload = (json.loads(body or "{}")
- if ctype.startswith("application/json")
- else {k: v[0] if v else "" for k, v in form.items()})
- except json.JSONDecodeError as e:
- self._json({"error": f"bad JSON: {e}"}, 400); return
- label = (payload.get("shot_label") or "").strip()
- png_path = (payload.get("png_path") or "").strip()
- if not label:
- self._json({"error": "shot_label is required"}, 400); return
- # Empty png_path → un-pick this label. Lets the chat UI implement
- # "click same anchor twice to deselect" without a separate endpoint.
- if not png_path:
- picks = sess.tool_state.setdefault("selected_anchors", {})
- if label in picks:
- picks.pop(label, None)
- agent_runtime.save_session(sess, STATE_DIR)
- push(f"agent: anchor un-picked for {label}")
- self._json({
- "ok": True,
- "shot_label": label,
- "selected": None,
- "all_selected": sess.tool_state.get("selected_anchors", {}),
- })
- return
- # Validate path is real and inside our uploads dir (no traversal).
- try:
- p = Path(png_path).resolve()
- _ = p.relative_to(UPLOADS.resolve())
- if not p.is_file():
- raise ValueError("not a file")
- except (ValueError, OSError) as e:
- self._json({"error": f"invalid png_path: {e}"}, 400); return
- # Find the matching candidate by path (so we keep seed/engine info)
- candidates = ((sess.tool_state.get("anchor_candidates") or {})
- .get(label, {}).get("candidates")) or []
- picked = next((c for c in candidates if c.get("png_path") == str(p)), None)
- if picked is None:
- # Path didn't match a known candidate — accept anyway with a
- # synthetic record. Useful when the user uploads their own.
- picked = {"png_path": str(p), "engine": "user", "seed": -1}
- sess.tool_state.setdefault("selected_anchors", {})[label] = picked
- agent_runtime.save_session(sess, STATE_DIR)
- push(f"agent: anchor picked for {label}: {p.name}")
- self._json({
- "ok": True,
- "shot_label": label,
- "selected": picked,
- "all_selected": sess.tool_state.get("selected_anchors", {}),
- })
- return
-
- self.send_error(404)
-
-
-def _avg_elapsed(kind: str | None = None) -> float | None:
- """Average elapsed time for recent completed jobs, optionally filtered
- to a single job kind (``"image"`` or ``"video"``).
+def _avg_elapsed(kind: str | None = None) -> float | None:
+ """Average elapsed time for recent completed jobs, optionally filtered
+ to a single job kind (``"image"`` or ``"video"``).
Why filter: image jobs are 30s–2min, video jobs are 5–30 min. Mixing
them when computing queue ETA means a session that's done a few
@@ -9376,32 +8100,7 @@ HTML = r"""<!doctype html>
.form-pane { padding: 16px; overflow-y: auto; }
.stage-pane { padding: 0; }
- /* Agentic Flows is a chat — it deserves more horizontal real estate
- than the manual form. When data-workflow="agent" is on the body,
- the form-pane grows to ~55% and the agent-stage-pane on the right
- takes over for showing live queue / renders / outputs. */
- body[data-workflow="agent"] .layout {
- grid-template-columns: minmax(560px, 1.2fr) minmax(440px, 1fr);
- }
- body[data-workflow="agent"] .form-pane { padding: 0; }
- body[data-workflow="agent"] .stage-pane { display: none; }
- body[data-workflow="agent"] .agent-stage-pane { display: flex; }
- /* Manual-only chrome that USED to live inside #genForm and was hidden
- implicitly when #genForm was hidden — but the redesign lifted the
- Mode picker (and the inline models card has always been a sibling)
- OUT of #genForm, so they leaked into the Agentic Flows view as a
- row of mode pills floating below the chat composer. Hide all
- manual-only sections explicitly when the user is in the agent
- workflow. (#genForm + #studioSection are belt-and-braces — JS
- already hides them on workflow switch but cover here so a missed
- toggle doesn't bleed manual chrome into the chat pane.) */
- body[data-workflow="agent"] #modelsInline,
- body[data-workflow="agent"] #modeGroup,
- body[data-workflow="agent"] aside.form-pane > h2,
- body[data-workflow="agent"] #genForm,
- body[data-workflow="agent"] #studioSection { display: none !important; }
-
- /* Train Character is its own workflow tier alongside Manual + Agent.
+ /* Train Character is its own workflow tier alongside Manual.
Hide the manual-only chrome (Mode pills, models card, genForm, studio)
so only #trainSection is visible inside form-pane. The stage-pane
stays visible — training surfaces progress through the existing Now /
@@ -10612,9 +9311,6 @@ HTML = r"""<!doctype html>
color: var(--accent-bright); font-weight: 600;
}
- /* When form-pane is in agent mode, drop the sticky footer padding. */
- body[data-workflow="agent"] .form-pane { padding-bottom: 0; }
-
/* ===== STAGE (PLAYER + CAROUSEL) — REDESIGN Y2.001 =====
Composer-grade right pane. The player is the hero (one elevated
surface with overlaid chrome instead of a black box + meta strip
@@ -12317,16143 +11013,7842 @@ HTML = r"""<!doctype html>
}
.models-foot { font-size: 11px; color: var(--muted); margin-top: 14px; line-height: 1.4; }
- /* ============== AGENTIC FLOWS — chat UI =====================
- Aim: feel like Claude.ai — generous typography, soft surfaces,
- avatars, expandable tool cards, markdown rendering. The form-pane
- gets a top strip switching between the manual form and the chat;
- the chat itself runs full-height with header / scroll / composer.
- */
- .workflow-tabs {
- display: flex; gap: 4px;
- padding: 5px; margin: 0 0 14px 0;
- background: var(--panel); border: 1px solid var(--border);
- border-radius: 12px;
- }
- .workflow-tabs button {
- flex: 1; padding: 9px 14px;
- background: rgba(255,255,255,0.02);
- color: var(--muted);
- border: 1px solid transparent; border-radius: var(--r-sm);
- font-size: 13px; font-weight: 600; cursor: pointer;
- letter-spacing: 0.2px;
- transition: background var(--t-base), color var(--t-base),
- border-color var(--t-base), transform var(--t-base);
- }
- .workflow-tabs button:hover { color: var(--text); background: rgba(255,255,255,0.05); }
- .workflow-tabs button.active {
- background: var(--accent-dim); color: var(--accent-bright);
- border-color: var(--accent);
- box-shadow: var(--shadow-1);
- }
- .workflow-tabs .new-badge {
- display: inline-block; margin-left: 6px;
- font-size: 9px; font-weight: 700; letter-spacing: 0.5px;
- padding: 2px 6px; border-radius: var(--r-pill);
- background: var(--accent-dim); color: var(--accent-bright);
- border: 1px solid var(--accent);
- vertical-align: middle;
- }
+ /* =========================================================
+ LINEAR DESIGN PASS — final layer
+ =========================================================
+ Direction picked by Salo on 2026-05-07. This block layers a
+ Linear-style refinement on top of the working panel: hairline
+ borders, dense type, monospaced numerics, very subtle
+ elevation, and a unified "chip" language across every header.
+ Lives at the END of the style block so it wins specificity.
+ NO class renames — every existing JS handler still finds its
+ targets.
- /* ---- Pane wrapper ---- */
- .agent-pane {
- position: relative; /* anchors agent-drop-overlay */
- display: flex; flex-direction: column;
- background: var(--panel);
- border: 1px solid var(--border);
- border-radius: 14px;
- overflow: hidden;
- --agent-text: 14px;
- --agent-line: 1.6;
- --agent-bubble-pad: 14px 16px;
- --agent-radius: 12px;
- --avatar: 28px;
- }
- /* The `display: flex` rule above wins over the UA stylesheet's
- `[hidden] { display: none }`, so toggling the `hidden` attribute
- on #agentPane (workflowSwitch's Manual branch) was a no-op — the
- agent header strip (Sessions chip, engine pill, RAM chip, fullscreen
- icon, etc.) and the engine readiness banner kept rendering above
- the manual form. Force the override so Manual really hides the
- Agentic Flows pane. Same shape as the line-8521 fix for the
- header's own [hidden] children. */
- .agent-pane[hidden] { display: none !important; }
-
- /* ---- Header ---- */
- .agent-header {
- display: flex; align-items: center; gap: 10px;
- padding: 12px 16px;
- border-bottom: 1px solid rgba(255,255,255,0.04);
- background: linear-gradient(180deg, var(--panel-2), var(--panel));
- }
- .agent-header .engine-pill {
- display: inline-flex; align-items: center; gap: 8px;
- padding: 5px 11px 5px 9px;
- background: var(--bg-2); color: var(--text);
- border: 1px solid var(--border); border-radius: 999px;
- font-size: 12px; font-weight: 500;
- cursor: pointer;
- transition: border-color var(--t-base), background var(--t-base);
- max-width: 320px;
- overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
- }
- .agent-header .engine-pill:hover { border-color: var(--accent); }
- .agent-header .engine-pill .dot {
- width: 7px; height: 7px; border-radius: 50%;
- background: var(--muted); flex-shrink: 0;
+ Per Salo's feedback: workflow tabs are repositioned to the
+ top-left of the form-pane (instead of full-width centered),
+ which keeps the existing user habit but reads cleaner. */
+
+ :root {
+ --ph-bg: #00061a;
+ --ph-elev-1: #0c1330;
+ --ph-elev-2: #141a3a;
+ --ph-border-soft: rgba(140, 160, 220, 0.08);
+ --ph-border-strong: rgba(140, 160, 220, 0.16);
+ --ph-text-faint: #5b6478;
+ /* Wordmark gradient — sampled from the SVG logo's three concentric
+ rings (#FF2E9F inner, #B14AFF middle, #5EEAFF outer). The middle
+ purple stop bridges pink → cyan; the old "magenta" was another
+ pink which made the gradient look muddy when scaled up. */
+ --ph-grad-pink: #FF2E9F;
+ --ph-grad-purple: #B14AFF;
+ --ph-grad-magenta: #B14AFF; /* alias for backward compat */
+ --ph-grad-cyan: #5EEAFF;
+ --ph-font-mono: "SF Mono", "JetBrains Mono", ui-monospace, Menlo, monospace;
}
- .agent-header .engine-pill .dot.live {
- background: #2ea043;
- box-shadow: 0 0 0 3px rgba(46,160,67,0.18);
+
+ /* Subtle radial wash above the void so the dark navy lifts at the
+ top — matches the Linear artboard. */
+ body {
+ background: var(--ph-bg);
+ background-image: radial-gradient(ellipse 1200px 600px at 50% -10%, rgba(47,129,247,0.06), transparent 60%);
+ font-size: 13px;
}
- .agent-header .engine-pill .dot.warn { background: #d29922; }
- .agent-header .engine-pill .dot.bad { background: #cf222e; }
- /* Mode pill — same shape as engine pill, neutral when plan_sleep,
- accent-tinted when interactive (visible reminder that the engine
- will stay resident). */
- .agent-header .agent-mode-pill {
- display: inline-flex; align-items: center; gap: 6px;
- padding: 5px 11px 5px 9px;
- background: var(--bg-2); color: var(--muted);
- border: 1px solid var(--border); border-radius: 999px;
- font-size: 11.5px; font-weight: 500;
- cursor: pointer;
- transition: border-color var(--t-base), background var(--t-base), color var(--t-base);
- white-space: nowrap;
- width: auto; /* form-reset rule sets buttons to 100% */
+ /* === TOP HEADER ============================================
+ 88px tall (was 62) — Salo flagged the chrome was reading too
+ small and the brand was getting lost. Logo bumped 48 → 64,
+ wordmark 22 → 28, plus a soft halo glow behind the mark so it
+ lifts off the void. Second-round bump (2026-05-12) to chrome
+ chips: pills 28 → 34, icon-btn 26 → 34, "by Bizarro" 24 → 34
+ — everything else needed to scale with the bigger brand. */
+ body > header {
+ height: 88px;
flex: 0 0 auto;
+ padding: 0 22px;
+ gap: 14px;
+ flex-wrap: nowrap;
+ align-items: center;
+ border-bottom: 1px solid var(--ph-border-soft);
+ background: rgba(0, 6, 26, 0.6);
+ backdrop-filter: blur(12px);
+ -webkit-backdrop-filter: blur(12px);
+ overflow: hidden;
}
- .agent-header .agent-mode-pill:hover { border-color: var(--accent); color: var(--text); }
- .agent-header .agent-mode-pill.is-interactive {
- color: var(--accent-bright);
- border-color: var(--accent);
- background: var(--accent-dim, rgba(47,129,247,0.12));
- }
- .agent-mode-icon {
+ body > header .brand {
display: inline-flex;
- align-items: center; justify-content: center;
- line-height: 0;
- flex-shrink: 0;
- }
- /* Stop-engine quick action — same height as the pills, danger color
- on hover so it reads as "this kills something". Only shown when
- the engine is running (toggled by JS). */
- .agent-header .agent-engine-stop {
- display: inline-flex; align-items: center; gap: 6px;
- padding: 5px 11px 5px 9px;
- background: transparent; color: var(--muted);
- border: 1px solid var(--border); border-radius: 999px;
- font-size: 11.5px; font-weight: 500;
- cursor: pointer;
- transition: color var(--t-base), border-color var(--t-base), background var(--t-base);
- white-space: nowrap;
- width: auto; /* form-reset rule sets buttons to 100% */
- flex: 0 0 auto;
- }
- .agent-header .agent-engine-stop:hover {
- color: var(--danger);
- border-color: rgba(248,81,73,0.5);
- background: rgba(248,81,73,0.08);
- }
- .agent-header .agent-engine-stop svg { flex-shrink: 0; }
- /* `display: inline-flex` on the pill rules above wins over the
- built-in `[hidden] { display:none }` cascade, so toggling the
- hidden attribute did nothing. Force the override here. */
- .agent-header [hidden] { display: none !important; }
-
- /* RAM headroom chip — reads whether you can comfortably run the
- configured chat model RIGHT NOW given current LTX renderer usage.
- Color-coded so a glance is enough; tooltip explains the breakdown.
- Lives in the agent header, where the action is. */
- .agent-header .agent-ram-chip {
- display: inline-flex; align-items: center; gap: 6px;
- padding: 5px 11px 5px 9px;
- background: var(--bg-2);
- border: 1px solid var(--border);
- border-radius: 999px;
- font-size: 11.5px; font-weight: 500;
- color: var(--muted);
- white-space: nowrap;
- cursor: help;
- transition: color var(--t-base), border-color var(--t-base), background var(--t-base);
- }
- .agent-header .agent-ram-chip .agent-ram-dot {
- width: 7px; height: 7px; border-radius: 50%;
+ align-items: center;
+ gap: 12px;
flex-shrink: 0;
- background: var(--muted);
- transition: background var(--t-base), box-shadow var(--t-base);
+ text-decoration: none;
}
- /* Roomy — chat model fits with comfortable margin. */
- .agent-header .agent-ram-chip.is-roomy { color: var(--success); border-color: rgba(63,185,80,0.4); }
- .agent-header .agent-ram-chip.is-roomy .agent-ram-dot {
- background: var(--success);
- box-shadow: 0 0 0 3px rgba(63,185,80,0.15);
+ body > header .brand img {
+ /* Phosphene brand mark — concentric radiating dashes that go
+ pink → magenta → cyan around a yellow core, on transparent
+ background. Provided by Salo (`phospene logo.png` 1254×1254
+ RGBA). Glow re-enabled 2026-05-12 — a soft brand-pink halo
+ that lifts the mark off the navy void without muddying the
+ dashes (uses drop-shadow filter so transparent regions stay
+ transparent). */
+ content: url('/assets/phosphene_brand.png');
+ height: 64px;
+ width: 64px;
+ display: block;
+ filter:
+ drop-shadow(0 0 14px rgba(255, 95, 168, 0.55))
+ drop-shadow(0 0 6px rgba(79, 214, 255, 0.35));
}
- /* Tight — fits but close to the edge; runs the risk of swap. */
- .agent-header .agent-ram-chip.is-tight { color: var(--warning); border-color: rgba(210,153,34,0.5); }
- .agent-header .agent-ram-chip.is-tight .agent-ram-dot {
- background: var(--warning);
- box-shadow: 0 0 0 3px rgba(210,153,34,0.15);
+ body > header .brand::after {
+ content: 'Phosphene';
+ /* Perceptual gradient: pink → cyan through OKLCh color space. RGB
+ interpolation produces muddy brown/grey mid-tones at large sizes;
+ OKLCh stays on the saturated hue ring (pink → magenta → purple →
+ blue-purple → cyan), which is what reads as a "real" gradient.
+ 5-stop fallback for older browsers; modern ones (Safari 16.4+,
+ Chrome 111+) use the in-oklch override below. */
+ background: linear-gradient(92deg,
+ #FF2E9F 0%,
+ #E135C2 25%,
+ #B14AFF 50%,
+ #7777FF 75%,
+ #5EEAFF 100%);
+ background: linear-gradient(in oklch 92deg, #FF2E9F, #5EEAFF);
+ -webkit-background-clip: text;
+ background-clip: text;
+ color: transparent;
+ font-weight: 700;
+ font-size: 44px;
+ letter-spacing: -0.02em;
+ /* Halo glow matching the gradient endpoints. */
+ text-shadow:
+ 0 0 24px rgba(255, 46, 159, 0.32),
+ 0 0 10px rgba(94, 234, 255, 0.22);
}
- /* Bad — wouldn't fit, would force swap immediately. */
- .agent-header .agent-ram-chip.is-bad { color: var(--danger); border-color: rgba(248,81,73,0.55); }
- .agent-header .agent-ram-chip.is-bad .agent-ram-dot {
- background: var(--danger);
- box-shadow: 0 0 0 3px rgba(248,81,73,0.18);
- animation: pulse 1.6s ease-in-out infinite;
+ /* Hide the existing version-badge styling and re-render it Linear-style
+ (mono "v2.0" in a chip). Keep the element so the JS doesn't break. */
+ body > header .version-badge {
+ margin: 0;
+ padding: 5px 10px;
+ font-size: 13px;
+ font-family: var(--ph-font-mono);
+ color: var(--muted);
+ background: rgba(140, 160, 220, 0.06);
+ border: 1px solid var(--ph-border-soft);
+ border-radius: 7px;
+ letter-spacing: 0.02em;
+ font-weight: 500;
+ text-transform: none;
}
- .agent-header .session-title {
- flex: 1; min-width: 0;
- font-size: 13px; font-weight: 500; color: var(--text);
- overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
+ body > header .profile-badge {
+ margin: 0 0 0 4px;
+ padding: 5px 10px;
+ font-size: 12px;
+ font-family: var(--ph-font-mono);
+ letter-spacing: 0.08em;
+ font-weight: 600;
+ border-radius: 7px;
}
- .agent-header .session-title .meta {
- font-size: 11px; color: var(--muted); margin-left: 8px;
- }
- .agent-header .icon-btn {
- width: 30px; height: 30px;
- background: transparent; color: var(--muted);
- border: 1px solid var(--border); border-radius: 8px;
- cursor: pointer;
- display: inline-flex; align-items: center; justify-content: center;
- font-size: 14px;
- transition: color var(--t-base), border-color var(--t-base);
- }
- .agent-header .icon-btn:hover {
- color: var(--accent-bright); border-color: var(--accent);
- }
-
- /* ---- Sessions sidebar (Cmd+K, slides in from left) ---- */
- /* Replaces the old absolute-positioned popover. Slides in from the
- left edge as an overlay (default) or pin-pushes the form-pane
- (when body.asp-pinned is set). Lives at z-index 60 so it covers
- the workflow tabs / engine pill / settings modal trigger but
- sits below the settings modal itself (z-200) and the model
- browser (z-220). */
- .agent-sessions-panel {
- position: fixed;
- top: 0; left: 0; bottom: 0;
- width: 290px;
- background: var(--panel);
- border-right: 1px solid var(--border-strong);
- box-shadow: 14px 0 40px rgba(0, 0, 0, 0.5);
- display: flex; flex-direction: column;
- transform: translateX(-100%);
- transition: transform var(--t-slow) cubic-bezier(0.2, 0.7, 0.2, 1);
- z-index: 60;
- will-change: transform;
- }
- .agent-sessions-panel[data-state="open"] { transform: translateX(0); }
- body.asp-pinned .agent-sessions-panel { box-shadow: none; }
- body.asp-pinned .form-pane { padding-left: 290px; transition: padding var(--t-slow); }
- body.asp-pinned .agent-stage-pane,
- body.asp-pinned .stage-pane { /* untouched in regular mode */ }
- body.agent-fullscreen.asp-pinned .layout {
- grid-template-columns: 290px 1fr minmax(420px, 480px);
- }
- body.agent-fullscreen.asp-pinned .agent-sessions-panel {
- position: fixed; /* still fixed, but column makes content reflow */
- }
- body.asp-pinned .asp-backdrop { display: none !important; }
-
- .asp-head {
- display: flex; align-items: center; gap: 8px;
- padding: 14px 14px 10px;
- border-bottom: 1px solid rgba(255, 255, 255, 0.04);
- }
- .asp-head .asp-title {
- flex: 1;
- font-size: 13px; font-weight: 600;
- letter-spacing: -0.1px; color: var(--text);
- text-transform: none; /* override the panel-wide h2/title rules */
- }
- .asp-head .asp-icon {
- width: 26px; height: 26px;
- background: transparent; color: var(--muted);
- border: 1px solid transparent;
- border-radius: var(--r-sm); cursor: pointer;
- display: inline-flex; align-items: center; justify-content: center;
- padding: 0;
- }
- .asp-head .asp-icon:hover {
- color: var(--text);
- background: var(--bg-2); border-color: var(--border);
- }
- body.asp-pinned #aspPinBtn { color: var(--accent-bright); border-color: var(--accent); background: var(--accent-dim); }
+ body > header .spacer { flex: 1 1 auto; }
- .asp-search {
- position: relative;
- padding: 10px 12px 12px;
- border-bottom: 1px solid rgba(255, 255, 255, 0.03);
- }
- .asp-search-icon {
- position: absolute; left: 22px; top: 18px;
+ /* Unified chip language for every header pill — Tier, RAM, Helper,
+ Models, Queue, current job, version, etc. */
+ body > header > .pill {
+ display: inline-flex;
+ align-items: center;
+ gap: 8px;
+ height: 34px;
+ padding: 0 14px;
+ border-radius: 8px;
+ background: rgba(140, 160, 220, 0.04);
+ border: 1px solid var(--ph-border-soft);
color: var(--muted);
+ font-size: 13.5px;
+ font-weight: 500;
+ font-variant-numeric: tabular-nums;
+ white-space: nowrap;
+ transition: border-color var(--t-base), color var(--t-base);
}
- .asp-search input {
- width: 100%;
- padding: 7px 36px 7px 32px;
- background: var(--bg-2);
+ body > header > .pill:hover {
+ border-color: var(--ph-border-strong);
color: var(--text);
- border: 1px solid var(--border);
- border-radius: 8px;
- font-size: 12px;
- box-sizing: border-box;
- transition: border-color var(--t-base), background var(--t-base);
}
- .asp-search input:focus {
- outline: none;
- border-color: var(--accent);
- background: var(--bg);
+ body > header > .pill .dot {
+ width: 7px; height: 7px;
+ border-radius: 999px;
+ margin-right: 0;
+ box-shadow: none;
}
- .asp-search input::placeholder { color: var(--muted); opacity: 0.7; }
- .asp-kbd {
- position: absolute; right: 20px; top: 16px;
- font-size: 10px; padding: 1px 6px;
- border: 1px solid var(--border); border-radius: 4px;
- color: var(--muted); background: var(--panel-2);
- font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
+ body > header > .pill-good { color: var(--success); border-color: rgba(63,185,80,0.30); }
+ body > header > .pill-good .dot { background: var(--success); box-shadow: 0 0 8px var(--success); }
+ body > header > .pill-warn { color: var(--warning); border-color: rgba(210,153,34,0.35); }
+ body > header > .pill-danger { color: var(--danger); border-color: rgba(248,81,73,0.35); }
+ body > header > .pill-running {
+ color: var(--accent-bright);
+ border-color: rgba(47,129,247,0.30);
+ background: rgba(47,129,247,0.06);
+ animation: pulse 1.6s ease-in-out infinite;
}
+ body > header > .pill-current { color: var(--success); border-color: rgba(63,185,80,0.25); }
+ body > header > .pill-update { color: var(--warning); border-color: rgba(240,185,64,0.40); background: rgba(240,185,64,0.06); }
+ body > header > .pill-restart { color: var(--accent-bright); border-color: rgba(126,152,255,0.40); background: rgba(126,152,255,0.06); }
- .asp-list {
- flex: 1 1 auto;
- overflow-y: auto;
- padding: 4px 8px 12px;
- min-height: 0;
- }
- .asp-list::-webkit-scrollbar { width: 8px; }
- .asp-list::-webkit-scrollbar-thumb { background: rgba(255, 255, 255, 0.06); border-radius: 4px; }
- .asp-list::-webkit-scrollbar-thumb:hover { background: rgba(255, 255, 255, 0.14); }
- .asp-section-label {
- padding: 10px 12px 4px;
- font-size: 9px; font-weight: 700;
- text-transform: uppercase; letter-spacing: 0.6px;
+ /* Settings cog — same height as chips, ghost styling. */
+ body > header #settingsBtn,
+ body > header .icon-btn {
+ width: 34px; height: 34px;
+ padding: 0;
+ border: none;
+ background: transparent;
color: var(--muted);
- }
- .asp-item {
- display: block; position: relative;
- padding: 9px 12px;
- margin: 2px 0;
- border-radius: 8px;
+ border-radius: 7px;
+ display: inline-flex;
+ align-items: center; justify-content: center;
cursor: pointer;
- border: 1px solid transparent;
- transition: background var(--t-fast), border-color var(--t-fast);
- }
- .asp-item:hover { background: var(--bg-2); }
- .asp-item.is-active {
- background: var(--accent-dim);
- border-color: var(--accent);
+ transition: color var(--t-base), background var(--t-base);
}
- .asp-item.is-active .asp-item-title { color: var(--accent-bright); }
- .asp-item.is-focused {
- background: var(--bg-2); border-color: var(--border-strong);
+ body > header #settingsBtn:hover,
+ body > header .icon-btn:hover {
+ color: var(--text);
+ background: rgba(140, 160, 220, 0.06);
}
- .asp-row {
- display: flex; gap: 8px; align-items: baseline;
+ /* Force the inline-sized SVGs (16×16) to scale up so the icons
+ look proportionate inside the larger 34×34 button. */
+ body > header #settingsBtn svg,
+ body > header .icon-btn svg {
+ width: 20px; height: 20px;
}
- .asp-item-title {
- flex: 1; font-size: 13px; font-weight: 500;
- color: var(--text);
- overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
+ /* Bug button — neon-pulsing accent so it reads as "interactive" and
+ discoverable. Uses an HSL accent (cyan-leaning) that's distinct from
+ the danger / warning / success colors already in use elsewhere. The
+ pulse is subtle enough to live in the header without being loud. */
+ body > header #bugBtn.bug-btn {
+ color: #5fc8ff;
+ animation: bug-neon 2.4s ease-in-out infinite;
+ filter: drop-shadow(0 0 4px rgba(95, 200, 255, 0.45));
}
- .asp-item-time {
- font-size: 10px; color: var(--muted); flex-shrink: 0;
+ body > header #bugBtn.bug-btn:hover {
+ color: #88dcff;
+ background: rgba(95, 200, 255, 0.10);
+ filter: drop-shadow(0 0 8px rgba(95, 200, 255, 0.85));
+ animation-duration: 1.2s;
}
- .asp-item-preview {
- font-size: 11px; color: var(--muted);
- margin-top: 2px;
- overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
- line-height: 1.4;
+ @keyframes bug-neon {
+ 0%, 100% {
+ filter: drop-shadow(0 0 3px rgba(95, 200, 255, 0.30));
+ opacity: 0.75;
+ }
+ 50% {
+ filter: drop-shadow(0 0 9px rgba(95, 200, 255, 0.85));
+ opacity: 1;
+ }
}
- /* Hover-revealed action row at the right edge of each session item.
- Kept hidden until hover so the list stays scannable; revealed always
- on the focused (keyboard-navigated) item too. */
- .asp-actions {
- position: absolute;
- top: 8px; right: 8px;
- display: none;
- gap: 2px;
- align-items: center;
+ @media (prefers-reduced-motion: reduce) {
+ body > header #bugBtn.bug-btn { animation: none; }
}
- .asp-item:hover .asp-actions,
- .asp-item.is-focused .asp-actions { display: inline-flex; }
- .asp-action-btn {
- width: 24px; height: 24px;
+ body > header #stopComfyBtn {
+ height: 24px; padding: 0 10px;
+ font-size: 11px; font-weight: 500;
border-radius: 6px;
- border: 1px solid transparent;
- background: rgba(255,255,255,0.05);
- color: var(--muted);
- cursor: pointer;
- display: inline-flex;
- align-items: center; justify-content: center;
- transition: background var(--t-base), color var(--t-base), border-color var(--t-base);
- padding: 0;
- }
- .asp-action-btn:hover {
- background: var(--bg-2);
- color: var(--text);
- border-color: var(--border);
+ width: auto; flex: 0 0 auto;
}
- .asp-action-btn.danger:hover { color: #f49a9e; border-color: rgba(244,154,158,0.5); }
- .asp-action-btn svg { width: 12px; height: 12px; }
- .asp-item.is-pinned .asp-pin-icon { color: var(--accent-bright); }
- .asp-item .asp-item-title-edit {
- flex: 1;
- background: var(--bg-2);
- color: var(--text);
- border: 1px solid var(--accent);
- border-radius: var(--r-xs);
- padding: 2px 6px;
+ /* Creator chip — square avatar, mono "by Bizarro" label, no underline. */
+ body > header .creator-link {
+ display: inline-flex;
+ align-items: center;
+ gap: 8px;
+ height: 34px;
+ padding: 0 12px 0 4px;
+ border-radius: 8px;
+ background: rgba(140, 160, 220, 0.04);
+ border: 1px solid var(--ph-border-soft);
+ color: var(--muted);
font-size: 13px;
font-weight: 500;
- width: 100%;
- box-sizing: border-box;
- outline: none;
- }
- .asp-item-preview {
- font-size: 11.5px;
- color: var(--muted);
- margin: 4px 0 0 0;
- white-space: nowrap;
- overflow: hidden;
- text-overflow: ellipsis;
- max-width: 100%;
- }
- /* Position items so action overlay can absolute. Already in .asp-item base. */
- .asp-item { position: relative; }
- .asp-item-meta {
- display: flex; gap: 6px; align-items: center;
- margin-top: 5px;
- justify-content: flex-end; /* pills hug the right edge of the card */
- }
- .asp-chip {
- font-size: 10px;
- padding: 1px 6px;
- background: var(--panel-2);
- border: 1px solid var(--border);
- border-radius: 999px;
- color: var(--muted);
- font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
+ text-decoration: none;
+ transition: border-color var(--t-base), color var(--t-base);
}
- .asp-chip-shots { color: var(--accent-bright); border-color: var(--accent); }
- .asp-status-running {
- width: 6px; height: 6px; border-radius: 50%;
- background: #3fb950;
- box-shadow: 0 0 0 3px rgba(63, 185, 80, 0.18);
- animation: stage-pulse 1.6s ease-in-out infinite;
+ body > header .creator-link:hover { color: var(--text); border-color: var(--ph-border-strong); }
+ body > header .creator-link .creator-avatar,
+ body > header .creator-link img {
+ width: 26px; height: 26px;
+ border-radius: 6px;
+ object-fit: cover;
+ flex-shrink: 0;
}
- .asp-empty {
- padding: 32px 18px;
- text-align: center;
- color: var(--muted);
+ body > header .creator-link .x-icon {
+ font-size: 11px;
+ color: var(--ph-text-faint);
+ letter-spacing: 0.04em;
}
- .asp-empty-title {
- font-size: 13px; font-weight: 600;
- color: var(--text);
- margin-bottom: 4px;
+ body > header .creator-link .x-icon svg {
+ width: 12px; height: 12px;
}
- .asp-empty-hint { font-size: 11px; }
- .asp-backdrop {
- position: fixed; inset: 0;
- background: rgba(0, 2, 12, 0.32);
- backdrop-filter: blur(2px);
- z-index: 55;
- opacity: 0;
- pointer-events: none;
- transition: opacity var(--t-slow);
+ /* === MAIN LAYOUT ===========================================
+ Hairline-bordered panes, no internal radius — Linear's edge
+ feel is "everything is one continuous surface".
+ The form-pane min width is bumped from 440 → 580 to match
+ the new composer-led redesign (which packs prompt + refs
+ + 4-up quality strip + 3-up dur/frames/seed + sticky
+ footer into the left pane). The stage cap on the right
+ still keeps the player from letterboxing into empty side
+ bars. Without this rule the two `main.layout` blocks
+ (this one + the one in the global section above) raced
+ and the more-specific selector here won, leaving the
+ form-pane stuck at 440 even after the redesign's wider
+ intent. */
+ main.layout {
+ gap: 0;
+ padding: 0;
+ grid-template-columns: minmax(580px, 1fr) minmax(0, calc((100vh - 220px) * 16 / 9));
}
- .asp-backdrop.is-shown {
- opacity: 1;
- pointer-events: auto;
+ .form-pane,
+ .stage-pane {
+ background: transparent;
+ border: none;
+ border-right: 1px solid var(--ph-border-soft);
+ border-radius: 0;
}
+ .stage-pane { border-right: none; }
+ /* No padding-bottom on form-pane: per CSS spec, sticky bottom:0
+ pins to the PADDING-BOX bottom of the scroll container, so
+ padding-bottom would lift the footer's pin position by exactly
+ that amount and leave content (LoRAs / Customize / Quality)
+ rendered BELOW the footer in viewport. The breathing room
+ above the sticky footer comes from the footer's own
+ margin-top:16px instead. */
+ .form-pane { padding: 0; }
- /* Sessions trigger pill in the agent header */
- .asp-trigger {
- display: inline-flex; align-items: center; gap: 7px;
- padding: 5px 10px 5px 9px;
- height: 30px;
- background: var(--bg-2); color: var(--muted);
- border: 1px solid var(--border);
- border-radius: 8px;
- font-size: 12px; font-weight: 500;
- cursor: pointer;
- transition: color var(--t-base), border-color var(--t-base), background var(--t-base);
- width: auto;
- }
- .asp-trigger:hover {
- color: var(--accent-bright);
- border-color: var(--accent);
- background: rgba(47, 129, 247, 0.06);
- }
- .asp-trigger svg { color: inherit; }
- .asp-trigger-count {
- font-size: 10px;
- padding: 1px 6px;
- background: var(--panel-2); color: var(--text);
- border-radius: 999px;
- font-weight: 600;
- }
-
- /* Fullscreen overrides — sidebar lives in front of the page,
- darker translucent panel for contrast against the gradient backdrop */
- body.agent-fullscreen .agent-sessions-panel {
- background: rgba(12, 19, 48, 0.96);
- backdrop-filter: blur(14px);
- -webkit-backdrop-filter: blur(14px);
- border-right-color: rgba(255, 255, 255, 0.06);
- }
-
- /* ---- Chat scroll area ---- */
- /* Wrapper carries the flex:1 + relative positioning so the
- "↓ new messages" pill can absolute-position over the chat. */
- .agent-chat-wrap {
- flex: 1;
- min-height: 360px; max-height: 60vh;
- position: relative;
- display: flex;
- flex-direction: column;
- }
- .agent-chat {
- flex: 1;
- overflow-y: auto; overflow-x: hidden;
- padding: 24px 20px 8px;
- scroll-behavior: smooth;
- }
- /* "↓ New messages" pill — sits at bottom-center of the chat surface,
- only visible when content has landed while the user is scrolled up.
- Clicking jumps to the bottom and re-arms autoscroll. */
- .agent-newmsgs-pill {
- position: absolute;
- left: 50%;
- bottom: 8px;
- transform: translateX(-50%);
+ /* === WORKFLOW TABS =========================================
+ Salo asked for these to be moved away from the centered top
+ slot. Now they live at the top-left of the form-pane as a
+ small segmented control — same place users have always seen
+ them, just visually re-tuned. */
+ .workflow-tabs {
display: inline-flex;
- align-items: center;
- gap: 6px;
- padding: 6px 12px;
- background: var(--accent);
- color: white;
- border: none;
- border-radius: 999px;
- font-size: 11.5px;
- font-weight: 600;
- cursor: pointer;
- box-shadow: 0 6px 18px rgba(47,129,247,0.45);
- animation: agent-fade-in 0.18s ease;
- z-index: 5;
+ gap: 0;
+ padding: 2px;
+ margin: 14px 0 18px 18px;
+ background: rgba(140, 160, 220, 0.04);
+ border: 1px solid var(--ph-border-soft);
+ border-radius: 7px;
width: auto;
- flex: 0 0 auto;
- }
- .agent-newmsgs-pill[hidden] { display: none; }
- .agent-newmsgs-pill:hover { filter: brightness(1.08); }
- .agent-chat::-webkit-scrollbar { width: 8px; }
- .agent-chat::-webkit-scrollbar-track { background: transparent; }
- .agent-chat::-webkit-scrollbar-thumb {
- background: var(--border-strong); border-radius: 4px;
- }
- .agent-chat::-webkit-scrollbar-thumb:hover { background: var(--accent); }
-
- /* ---- Empty state ---- */
- .agent-empty {
- max-width: 540px; margin: 24px auto 12px;
- text-align: center; color: var(--muted);
- animation: agent-fade-in 0.4s ease;
- }
- .agent-empty .badge {
- display: inline-flex; align-items: center; gap: 8px;
- padding: 6px 12px; border-radius: 999px;
- background: var(--accent-dim); color: var(--accent-bright);
- border: 1px solid var(--accent);
- font-size: 11px; font-weight: 600; letter-spacing: 0.5px;
- text-transform: uppercase;
- margin-bottom: 16px;
- }
- .agent-empty h3 {
- font-size: 18px; font-weight: 600; color: var(--text);
- margin: 0 0 10px;
- }
- .agent-empty p {
- font-size: 13px; line-height: 1.55; margin: 6px 0;
- }
- .agent-empty .examples {
- display: flex; flex-direction: column; gap: 8px;
- max-width: 420px; margin: 24px auto 0;
+ max-width: max-content;
}
- .agent-empty .example {
- text-align: left;
- padding: 12px 14px;
- background: var(--bg-2);
- border: 1px solid var(--border); border-radius: 10px;
- cursor: pointer;
- color: var(--text); font-size: 13px;
- transition: border-color var(--t-base), background var(--t-base);
- display: flex; align-items: center; gap: 10px;
+ .workflow-tabs button {
+ /* Override the global `button { width: 100% }` rule. Without
+ width:auto each tab stretches to fill the form-pane width, so
+ Manual + Agentic Flows + Train all rendered at ~306px each and
+ the latter two overflowed the visible nav pill off-screen —
+ that's why Salo saw Train as "hidden" unless he switched to
+ Agentic Flows. */
+ width: auto;
+ flex: 0 0 auto;
+ padding: 5px 14px;
+ font-size: 12px; font-weight: 500;
+ letter-spacing: 0;
+ background: transparent;
+ color: var(--muted);
+ border: none;
+ border-radius: 5px;
+ box-shadow: none;
+ transition: background var(--t-base), color var(--t-base);
}
- .agent-empty .example:hover {
- border-color: var(--accent);
- background: var(--panel);
+ .workflow-tabs button:hover {
+ background: rgba(140, 160, 220, 0.06);
+ color: var(--text);
}
- .agent-empty .example .arrow {
- color: var(--muted); flex-shrink: 0;
- transition: transform var(--t-base), color var(--t-base);
+ .workflow-tabs button.active {
+ background: rgba(47, 129, 247, 0.14);
+ color: var(--accent-bright);
+ box-shadow: inset 0 0 0 1px rgba(47, 129, 247, 0.22);
+ border: none;
}
- .agent-empty .example:hover .arrow {
+ .workflow-tabs .new-badge {
+ margin-left: 6px;
+ padding: 1px 5px;
+ font-size: 9px; font-weight: 600;
+ font-family: var(--ph-font-mono);
+ letter-spacing: 0.06em;
+ background: rgba(47, 129, 247, 0.12);
color: var(--accent-bright);
- transform: translateX(2px);
+ border: 1px solid rgba(47, 129, 247, 0.24);
+ border-radius: 3px;
+ vertical-align: baseline;
}
- /* ---- Message rows ---- */
- .agent-msg-row {
- display: flex; gap: 12px;
- align-items: flex-start;
- margin-bottom: 22px;
- animation: agent-fade-in 0.3s ease;
- }
- @keyframes agent-fade-in {
- from { opacity: 0; transform: translateY(6px); }
- to { opacity: 1; transform: translateY(0); }
- }
- .agent-avatar {
- width: var(--avatar); height: var(--avatar);
- border-radius: 50%;
- display: inline-flex; align-items: center; justify-content: center;
- font-size: 12px; font-weight: 700;
- flex-shrink: 0;
- letter-spacing: 0.3px;
- user-select: none;
- }
- /* Phosphene-branded avatar — circular logo on a dark background.
- Replaces the prior orange "C" placeholder so the agent reads as
- Phosphene, not a generic chat bot. The logo is the same circular
- glyph used as the favicon and in the offline banner. */
- .agent-avatar.claude {
- background: radial-gradient(circle at 50% 50%, #1a0e2e 0%, #0a0518 70%);
- color: transparent;
- padding: 2px;
- box-shadow: 0 0 0 1px rgba(187, 89, 233, 0.25);
- overflow: hidden;
+ /* === FORM PANE INNER ===
+ Contents inside the form (other than workflow tabs and the agent
+ pane) get padding, but the workflow tabs themselves now hug the
+ top-left corner, set by their own margin above. */
+ .form-pane > #genForm { padding: 0 18px; }
+ .form-pane > #modelsInline { margin: 0 18px 14px; }
+ /* h2 section labels — mono uppercase, Linear's signature. */
+ #genForm h2 {
+ font-size: 10.5px;
+ font-family: var(--ph-font-mono);
+ letter-spacing: 0.08em;
+ color: var(--ph-text-faint);
+ text-transform: uppercase;
+ margin: 22px 0 8px;
+ font-weight: 500;
}
- .agent-avatar.claude::before {
- content: '';
- display: block;
- width: 100%; height: 100%;
- background: url('/assets/favicon-64.png') center/contain no-repeat;
+ #genForm h2:first-of-type { margin-top: 0; }
+
+ /* Mode + Quality pickers as Linear's grouped panel: a subtle inset
+ container with hairline border, then 4 buttons inside. */
+ .pill-group.cols-2,
+ .pill-group.cols-4 {
+ gap: 6px;
+ padding: 3px;
+ background: rgba(140, 160, 220, 0.04);
+ border: 1px solid var(--ph-border-soft);
+ border-radius: 8px;
}
- .agent-avatar.user {
- background: var(--panel-2);
- color: var(--text);
- border: 1px solid var(--border-strong);
+ .pill-btn {
+ padding: 8px 10px;
+ background: transparent;
+ border: none;
+ color: var(--muted);
+ box-shadow: none;
+ border-radius: 6px;
+ transition: background var(--t-base), color var(--t-base);
}
- .agent-msg-body { flex: 1; min-width: 0; }
- .agent-msg-name {
- font-size: 12px; font-weight: 600;
+ .pill-btn:hover {
+ background: rgba(140, 160, 220, 0.05);
color: var(--text);
- margin-bottom: 4px;
- letter-spacing: 0.2px;
+ border: none;
}
- .agent-msg-content {
- font-size: var(--agent-text);
- line-height: var(--agent-line);
- color: var(--text);
- word-wrap: break-word; overflow-wrap: break-word;
- }
- /* Distinguish user vs assistant bubbles. Pre-this commit both sides
- rendered as naked text on the void, so the chat read like one
- wall of dev-tool output. User now gets a tinted bubble with the
- chat-app tail-truncated radius (Claude.ai style); assistant
- stays naked text on the void so longer planning replies don't
- feel boxed-in. */
- .agent-msg-row.user .agent-msg-content {
- background: var(--panel-2);
- border: 1px solid var(--border);
- border-radius: var(--r-lg) var(--r-lg) var(--r-xs) var(--r-lg);
- padding: 9px 14px;
+ .pill-btn.active {
+ background: rgba(47, 129, 247, 0.14);
+ color: var(--accent-bright);
+ box-shadow: inset 0 0 0 1px rgba(47, 129, 247, 0.22);
+ border: none;
}
- .agent-msg-row.user .agent-msg-attachments {
- margin-top: 2px;
+ .pill-btn .sub {
+ font-size: 10.5px;
+ font-family: var(--ph-font-mono);
+ color: var(--ph-text-faint);
+ letter-spacing: 0;
}
+ .pill-btn.active .sub { color: var(--accent-bright); opacity: 0.8; }
- /* ---- Markdown rendering inside .agent-md ---- */
- .agent-md > *:first-child { margin-top: 0; }
- .agent-md > *:last-child { margin-bottom: 0; }
- .agent-md p { margin: 8px 0; }
- .agent-md h1, .agent-md h2, .agent-md h3, .agent-md h4 {
- font-weight: 600; color: var(--text); margin: 16px 0 8px;
- line-height: 1.3;
+ /* Quality cards — 2x2 with looser padding + RECOMMENDED badge style.
+ Override the .pill-group inset bg so each card reads as standalone. */
+ .pill-group.cols-2.quality-row {
+ padding: 0;
+ background: transparent;
+ border: none;
+ gap: 8px;
}
- .agent-md h1 { font-size: 17px; }
- .agent-md h2 { font-size: 15px; }
- .agent-md h3 { font-size: 14px; color: var(--accent-bright); }
- .agent-md h4 { font-size: 13px; color: var(--muted); text-transform: uppercase; letter-spacing: 0.4px; }
- .agent-md ul, .agent-md ol { margin: 8px 0; padding-left: 22px; }
- .agent-md li { margin: 4px 0; }
- .agent-md li > p { margin: 2px 0; }
- .agent-md strong { font-weight: 600; color: var(--text); }
- .agent-md em { font-style: italic; color: var(--muted); }
- .agent-md a { color: var(--accent-bright); text-decoration: underline; }
- .agent-md code {
- font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
- font-size: 0.92em;
+ .pill-quality {
+ padding: 10px 12px !important;
+ align-items: flex-start !important;
+ text-align: left !important;
+ min-height: 76px;
+ background: rgba(20, 26, 58, 0.4) !important;
+ border: 1px solid var(--ph-border-soft) !important;
+ border-radius: 8px !important;
+ box-shadow: none !important;
+ position: relative;
+ }
+ .pill-quality:hover { background: rgba(20, 26, 58, 0.6) !important; border-color: var(--ph-border-strong) !important; }
+ .pill-quality.active {
+ background: rgba(47, 129, 247, 0.06) !important;
+ border-color: rgba(47, 129, 247, 0.45) !important;
+ box-shadow: inset 0 0 0 1px rgba(47, 129, 247, 0.18) !important;
+ }
+ .pill-quality.active::after {
+ content: 'RECOMMENDED';
+ position: absolute;
+ top: 9px; right: 10px;
+ font-size: 9px;
+ font-family: var(--ph-font-mono);
+ font-weight: 600;
padding: 2px 6px;
- background: rgba(255,255,255,0.05);
- border: 1px solid var(--border);
border-radius: 4px;
+ background: rgba(47, 129, 247, 0.16);
color: var(--accent-bright);
+ letter-spacing: 0.06em;
}
- .agent-md pre {
- background: var(--bg);
- border: 1px solid var(--border);
- border-radius: 8px;
- padding: 12px 14px;
- margin: 10px 0;
- overflow-x: auto;
- font-size: 12px;
- line-height: 1.5;
- }
- .agent-md pre code {
- background: transparent; border: none; padding: 0;
- color: var(--text);
- font-size: inherit;
- }
- .agent-md blockquote {
- margin: 10px 0;
- padding: 6px 14px;
- border-left: 3px solid var(--accent);
+ /* The RECOMMENDED badge above is sized for the legacy 4-up Quality
+ row that gave each chip plenty of headroom. The redesign's
+ compact `.quality-strip .q-chip` chips don't have room for an
+ inline badge — without this override the badge crams onto the
+ same line as the chip label, producing a "BalancedRECOMMENDED"
+ overlap that reads as a font glitch. Hide it inside the new
+ strip; the active state is already announced by background +
+ border + accent text. */
+ .quality-strip .pill-quality.active::after { content: none; }
+ .pill-quality .ql-name { font-size: 13px; font-weight: 600; color: var(--text); }
+ .pill-quality.active .ql-name { color: var(--text); }
+ .pill-quality .ql-spec {
+ font-size: 11px;
+ font-family: var(--ph-font-mono);
color: var(--muted);
- background: var(--accent-dim);
- border-radius: 0 6px 6px 0;
}
- .agent-md table {
- border-collapse: collapse;
- margin: 10px 0;
- font-size: 12px;
- width: 100%;
- }
- .agent-md th, .agent-md td {
- border: 1px solid var(--border);
- padding: 7px 10px;
- text-align: left;
- vertical-align: top;
+ .pill-quality .ql-tier {
+ font-size: 9.5px;
+ font-family: var(--ph-font-mono);
+ color: var(--ph-text-faint);
+ margin-top: 6px;
}
- .agent-md th {
- background: var(--bg-2);
- font-weight: 600;
- color: var(--text);
+
+ /* Prompt + Avoid textareas — denser, hairline border, monospaced
+ placeholder hint. */
+ #genForm textarea,
+ #genForm input[type="text"],
+ #genForm input[type="number"],
+ #genForm select {
+ background: rgba(12, 19, 48, 0.5);
+ border: 1px solid var(--ph-border-soft);
+ border-radius: 8px;
+ padding: 10px 12px;
+ font-size: 13px;
}
- .agent-md hr {
- border: none; border-top: 1px solid var(--border);
- margin: 14px 0;
+ #genForm textarea:focus,
+ #genForm input:focus,
+ #genForm select:focus {
+ border-color: var(--accent);
+ background: rgba(12, 19, 48, 0.7);
+ box-shadow: 0 0 0 3px rgba(47, 129, 247, 0.18);
}
- /* ---- Capabilities sheet (Phase 0 #0.5) ----
- Drives the /help slash-command output. Each tool is one row:
- monospaced name + first-line summary; click to expand the full
- docstring. Quiet typography — this is reference material. */
- .caps-section {
- margin: 14px 0;
- }
- .caps-section h3 {
- margin: 0 0 8px 0;
- font-size: 11px;
- letter-spacing: 0.5px;
- text-transform: uppercase;
- color: var(--muted);
- font-weight: 600;
- }
- .caps-row {
- display: flex;
- gap: 12px;
- padding: 10px 12px;
- border: 1px solid var(--border);
- border-radius: var(--r-sm);
- margin-bottom: 6px;
- background: rgba(255,255,255,0.025);
- }
- .caps-row .caps-name {
- font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
- font-size: 11.5px;
- color: var(--accent-bright);
- white-space: nowrap;
- flex-shrink: 0;
- align-self: flex-start;
- padding-top: 1px;
- }
- .caps-row .caps-text {
- flex: 1; min-width: 0;
- font-size: 12px;
- color: var(--text);
- line-height: 1.5;
- }
- .caps-row .caps-text .summary {
- color: var(--muted);
- font-size: 11.5px;
- }
- .caps-row details {
- margin-top: 4px;
- }
- .caps-row details summary {
- cursor: pointer;
- font-size: 11px;
- color: var(--accent-bright);
- list-style: none;
- user-select: none;
- }
- .caps-row details summary::-webkit-details-marker { display: none; }
- .caps-row details[open] summary { color: var(--muted); }
- .caps-row pre {
- margin: 6px 0 0 0;
- padding: 10px 12px;
- background: var(--bg);
- border: 1px solid var(--border);
- border-radius: var(--r-xs);
- font-size: 11px;
- line-height: 1.55;
- max-height: 280px;
- overflow: auto;
- white-space: pre-wrap;
- word-break: break-word;
- color: rgba(255,255,255,0.8);
- }
- .caps-grid {
- display: grid;
- grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
- gap: 8px;
- }
- .caps-grid .caps-cell {
- padding: 9px 12px;
- border: 1px solid var(--border);
- border-radius: var(--r-sm);
- background: rgba(255,255,255,0.025);
- }
- .caps-grid .caps-cell .label {
- font-weight: 600; font-size: 12px; color: var(--text);
- }
- .caps-grid .caps-cell .meta {
- color: var(--muted); font-size: 11px;
- font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
- letter-spacing: 0.2px;
- }
- .caps-grid .caps-cell .desc {
- color: var(--muted); font-size: 11.5px;
- margin-top: 2px;
- }
-
- /* ---- Reasoning disclosure (chain-of-thought) ----
- Shown above the assistant content as a collapsed details block.
- Quiet by default so the answer stays the focus; expanding reveals
- the model's thought process. Reasoning often runs 1–4k chars on
- a planning turn — scroll caps prevent runaway height. */
- .agent-reasoning {
- margin: 0 0 8px 0;
- border: 1px solid var(--border);
- border-radius: 8px;
- background: rgba(255,255,255,0.02);
- }
- .agent-reasoning > summary {
- list-style: none;
- cursor: pointer;
- padding: 7px 12px;
+ /* Inline buttons (Enhance / HDR / No-music) styled as Linear ghost pills */
+ .row-actions .ghost-btn,
+ .toggle-pill {
display: inline-flex;
align-items: center;
- gap: 7px;
- font-size: 11px;
+ gap: 6px;
+ padding: 6px 10px;
+ border-radius: 6px;
+ border: 1px solid var(--ph-border-soft);
+ background: transparent;
color: var(--muted);
- user-select: none;
- }
- .agent-reasoning > summary::-webkit-details-marker { display: none; }
- .agent-reasoning > summary svg {
- transition: transform var(--t-base) ease;
- flex-shrink: 0;
+ font-size: 12px;
+ width: auto;
+ cursor: pointer;
+ transition: border-color var(--t-base), color var(--t-base), background var(--t-base);
}
- .agent-reasoning[open] > summary svg { transform: rotate(90deg); }
- .agent-reasoning > summary .label {
- font-weight: 600;
+ .row-actions .ghost-btn:hover,
+ .toggle-pill:hover {
+ border-color: var(--ph-border-strong);
color: var(--text);
}
- .agent-reasoning > summary .meta {
- color: var(--muted);
- font-weight: 400;
- }
- .agent-reasoning .agent-reasoning-body {
- padding: 0 14px 12px 26px;
- font-size: 11.5px;
- line-height: 1.6;
- color: rgba(255,255,255,0.62);
- font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
- white-space: pre-wrap;
- word-break: break-word;
- max-height: 320px;
- overflow-y: auto;
+ .toggle-pill.is-on {
+ border-color: rgba(47, 129, 247, 0.28);
+ background: var(--accent-dim);
+ color: var(--accent-bright);
}
- /* ---- Tool cards (calls + results, expandable) ----
- Visually quieter than they used to be: 2px left accent (was 3px),
- subtle background, smaller font, less vertical padding. The point
- is to read as "side metadata" not "primary content" — the
- assistant's planning text is the protagonist. */
- .agent-tool-card {
- margin: 6px 0;
- background: rgba(255,255,255,0.025);
- border: 1px solid var(--border);
- border-left: 2px solid var(--border);
- border-radius: 8px;
- overflow: hidden;
- transition: border-color var(--t-base), background var(--t-base);
- animation: agent-fade-in 0.2s ease;
- }
- .agent-tool-card:hover { background: var(--bg-2); }
- .agent-tool-card.success { border-left-color: rgba(46,160,67,0.55); }
- .agent-tool-card.error { border-left-color: rgba(207,34,46,0.55); }
- .agent-tool-card.pending { border-left-color: var(--accent); }
- .agent-tool-card .head {
- padding: 7px 12px;
- display: flex; align-items: center; gap: 9px;
- cursor: pointer;
- user-select: none;
- font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
- font-size: 11.5px;
- }
- .agent-tool-card .head:hover { background: rgba(255,255,255,0.04); }
- .agent-tool-card .head .icon {
- font-size: 11px; flex-shrink: 0; line-height: 1;
- color: var(--muted);
- }
- .agent-tool-card .head .icon.success { color: #2ea043; }
- .agent-tool-card .head .icon.error { color: #cf222e; }
- .agent-tool-card .head .name {
- font-weight: 600; color: var(--muted);
- flex-shrink: 0;
- font-size: 11px;
- }
- .agent-tool-card.success .head .name { color: var(--text); }
- .agent-tool-card.error .head .name { color: #f49a9e; }
- .agent-tool-card .head .summary {
- color: var(--muted); flex: 1; min-width: 0;
- overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
- }
- .agent-tool-card .head .chevron {
- color: var(--muted); flex-shrink: 0;
- transition: transform var(--t-base) ease;
- font-size: 11px;
- }
- .agent-tool-card.open .head .chevron { transform: rotate(90deg); }
- .agent-tool-card .body {
- display: none;
- padding: 0 14px 12px;
- border-top: 1px solid var(--border);
- margin-top: 0;
- }
- .agent-tool-card.open .body {
- display: block;
- padding-top: 10px;
- }
- .agent-tool-card .body pre {
- margin: 0;
- padding: 10px 12px;
- background: var(--bg);
- border: 1px solid var(--border);
+ /* Generate / Stop primary action — Linear blue with subtle blue
+ glow. */
+ button.primary,
+ #genBtn,
+ button[type="submit"].primary {
+ padding: 10px 14px;
+ font-size: 13px; font-weight: 600;
border-radius: 6px;
- font-size: 11px;
- line-height: 1.45;
- max-height: 280px;
- overflow: auto;
- white-space: pre-wrap;
- word-break: break-word;
- color: var(--text);
+ background: var(--accent);
+ border-color: var(--accent);
+ box-shadow: 0 4px 14px rgba(47, 129, 247, 0.25);
}
+ button.primary:hover { background: var(--accent-bright); }
+ .actions { gap: 8px; margin-top: 18px; }
- /* ---- Anchor candidate grid (Phase B of the director workflow) ---- */
- .anchor-grid-wrap {
- padding: 12px 14px 14px;
- border-top: 1px solid var(--border);
- }
- .anchor-grid-meta {
- font-size: 11px; color: var(--muted);
- margin-bottom: 8px;
- display: flex; align-items: center; gap: 8px;
- }
- .anchor-grid-meta .label-pill {
- padding: 2px 8px; border-radius: 999px;
- background: var(--accent-dim); color: var(--accent-bright);
- font-weight: 600; font-size: 10px;
- letter-spacing: 0.4px; text-transform: uppercase;
- }
- .anchor-grid-meta .take-pill {
- padding: 2px 8px; border-radius: 999px;
- background: rgba(255,255,255,0.06);
- color: var(--text);
- font-weight: 500; font-size: 10px;
- border: 1px solid var(--border);
- letter-spacing: 0.2px;
- }
- /* Pick-state badge — right-aligned, neutral when nothing picked,
- success-tinted when there's a pick. Updated in-place by
- agentPickAnchor without re-rendering the grid. */
- .anchor-grid-meta .pick-state {
- font-size: 10px;
- padding: 2px 8px;
- border-radius: 999px;
- background: rgba(255,255,255,0.04);
- border: 1px solid var(--border);
- color: var(--muted);
- letter-spacing: 0.3px;
- }
- .anchor-grid-meta .pick-state.is-picked {
- background: rgba(63,185,80,0.12);
- border-color: rgba(63,185,80,0.5);
- color: var(--success, #3fb950);
- font-weight: 600;
+ /* === STAGE / PLAYER PANE (Manual mode) =====================
+ Y2.001 — the legacy Linear-style overrides that lived here are
+ removed; the redesigned stage block above (search "STAGE
+ (PLAYER + CAROUSEL) — REDESIGN Y2.001") is the source of truth
+ and uses the canonical token set instead of the older --ph-*
+ aliases. The selectors are intentionally left blank so any
+ future regression diff stays small. */
+
+ /* === BOTTOM PANEL ==========================================
+ Y2.001 — the legacy --ph-* override block is removed. The
+ redesigned bottom-pane block above (search "BOTTOM TABBED PANE
+ — REDESIGN Y2.001") is the source of truth and uses the
+ canonical token set. Selectors left blank to keep diffs clean. */
+
+ /* === MODELS-INLINE CARD =================================== */
+ .models-inline {
+ background: rgba(20, 26, 58, 0.4);
+ border: 1px solid var(--ph-border-soft);
+ border-radius: 10px;
}
- .anchor-grid {
- display: grid;
- grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));
- gap: 10px;
+
+ /* === LoRAs section + Customize disclosure ================== */
+ .form-divider {
+ border-top: 1px solid var(--ph-border-soft);
+ margin: 18px 0;
}
- .anchor-cell {
- position: relative;
- aspect-ratio: 16/9;
+ .loras-section, .customize-section {
+ border: 1px solid var(--ph-border-soft);
border-radius: 8px;
- overflow: hidden;
- cursor: pointer;
- border: 2px solid transparent;
- background: var(--bg);
- padding: 0;
- transition: border-color var(--t-base), transform var(--t-base);
- }
- .anchor-cell:hover {
- border-color: var(--accent);
- transform: scale(1.02);
- }
- .anchor-cell.selected {
- border-color: #2ea043;
- box-shadow: 0 0 0 3px rgba(46,160,67,0.25);
- }
- .anchor-cell img {
- width: 100%; height: 100%;
- object-fit: cover;
- display: block;
- }
- .anchor-cell .check {
- position: absolute; top: 6px; right: 6px;
- width: 22px; height: 22px;
- border-radius: 50%;
- background: var(--bg-2);
- color: var(--muted);
- display: flex; align-items: center; justify-content: center;
- font-size: 12px;
- font-weight: 800;
- border: 1px solid var(--border);
- transition: background var(--t-base), color var(--t-base);
- }
- .anchor-cell.selected .check {
- background: #2ea043;
- color: white;
- border-color: #2ea043;
- }
- .anchor-cell .seed {
- position: absolute; bottom: 4px; left: 4px;
- font-size: 9px;
- font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
- padding: 2px 6px;
- background: rgba(0,0,0,0.55);
- color: white;
- border-radius: 4px;
- letter-spacing: 0.3px;
- }
- .anchor-cell .engine-tag {
- position: absolute; bottom: 4px; right: 4px;
- font-size: 9px;
- padding: 2px 5px;
- background: rgba(0,0,0,0.55);
- color: white;
- border-radius: 4px;
- text-transform: uppercase;
- letter-spacing: 0.4px;
- }
- .anchor-prompt {
- font-size: 11px; color: var(--muted);
- line-height: 1.5;
- margin-bottom: 10px;
- padding: 8px 10px;
- background: var(--bg);
- border-radius: 6px;
- border: 1px solid var(--border);
- font-style: italic;
- max-height: 80px; overflow-y: auto;
+ background: rgba(20, 26, 58, 0.25);
}
- /* ============================================================
- AGENT STAGE PANE — the right-side "live canvas" / code-interpreter
- ============================================================
- Shows what the agent is actually doing with the renderer in real
- time: current job + progress, queue, generated anchors waiting on
- a pick, finished mp4s playing inline. Polls /status every ~1.5s.
-
- Hidden by default; appears when body[data-workflow="agent"] OR
- body.agent-fullscreen. Cards are layered (top: now, middle:
- activity feed, bottom: gallery of session outputs) and scroll
- independently. */
- .agent-stage-pane {
- display: none;
- flex-direction: column;
- background: var(--panel);
- border: 1px solid var(--border);
- border-radius: var(--radius);
- overflow: hidden;
- min-height: 0;
- }
- .agent-stage-head {
- padding: 12px 16px;
- border-bottom: 1px solid rgba(255,255,255,0.05);
- display: flex; align-items: center; gap: 10px;
- flex-shrink: 0;
- background: linear-gradient(180deg, rgba(255,255,255,0.02), transparent);
- }
- .agent-stage-head .label {
- font-size: 10px; font-weight: 700;
- text-transform: uppercase; letter-spacing: 0.5px;
- color: var(--muted);
- }
- .agent-stage-head .live-dot {
- width: 8px; height: 8px; border-radius: 50%;
- background: var(--muted);
- }
- .agent-stage-head .live-dot.live {
- background: #2ea043;
- box-shadow: 0 0 0 3px rgba(46,160,67,0.18);
- animation: stage-pulse 1.6s ease-in-out infinite;
- }
- @keyframes stage-pulse {
- 0%, 100% { box-shadow: 0 0 0 3px rgba(46,160,67,0.18); }
- 50% { box-shadow: 0 0 0 6px rgba(46,160,67,0.05); }
- }
- .agent-stage-head .session-pill {
- font-size: 10px; padding: 3px 8px;
- background: var(--bg-2); border: 1px solid var(--border);
- border-radius: 999px; color: var(--muted);
- font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
- flex: 0 0 auto;
- }
- .agent-stage-head .spacer { flex: 1; }
- .agent-stage-head .stage-tab {
- background: transparent; color: var(--muted);
- border: 1px solid transparent; border-radius: var(--r-sm);
- padding: 5px 10px; font-size: 11px; cursor: pointer;
- width: auto;
- }
- .agent-stage-head .stage-tab.active {
- background: var(--accent-dim); color: var(--accent-bright);
- border-color: var(--accent);
- }
- .agent-stage-head .stage-tab:hover:not(.active) {
- color: var(--text);
- }
- .agent-stage-body {
- flex: 1 1 auto;
- overflow-y: auto; overflow-x: hidden;
- padding: 14px 16px 18px;
- display: flex; flex-direction: column; gap: 14px;
- min-height: 0;
- }
- .agent-stage-body::-webkit-scrollbar { width: 8px; }
- .agent-stage-body::-webkit-scrollbar-thumb {
- background: rgba(255,255,255,0.06); border-radius: 4px;
- }
- .agent-stage-body::-webkit-scrollbar-thumb:hover {
- background: rgba(255,255,255,0.14);
- }
- .agent-stage-section {
- background: var(--bg-2);
- border: 1px solid var(--border);
- border-radius: 10px;
- padding: 12px 14px;
- }
- .agent-stage-section h4 {
- margin: 0 0 8px; font-size: 10px;
- text-transform: uppercase; letter-spacing: 0.5px;
- color: var(--muted); font-weight: 700;
- display: flex; align-items: center; gap: 8px;
- }
- .agent-stage-section h4 .count {
- padding: 1px 7px; border-radius: 999px;
- background: var(--accent-dim); color: var(--accent-bright);
- font-weight: 700;
- }
+ /* === Sub-header strip BELOW the workflow tabs (Manual mode)
+ — empty intentionally; the workflow tabs already act as the
+ leading row, the form sections start right under them. */
- /* "Now rendering" card */
- .stage-now-card {
- padding: 14px 14px 12px;
- }
- .stage-now-card.idle {
- text-align: center; color: var(--muted);
- font-size: 12px; padding: 24px 14px;
- font-style: italic;
- }
- .stage-now-label {
- font-size: 13px; font-weight: 600;
- color: var(--text); margin-bottom: 4px;
- overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
- }
- .stage-now-meta {
- font-size: 11px; color: var(--muted);
- font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
- margin-bottom: 10px;
- }
- .stage-progress-bar {
- height: 6px; border-radius: 3px;
- background: rgba(255,255,255,0.06);
- overflow: hidden;
- margin-bottom: 4px;
- }
- .stage-progress-fill {
- height: 100%;
- background: linear-gradient(90deg, var(--accent), var(--accent-bright));
- transition: width 600ms ease;
- box-shadow: 0 0 12px rgba(47,129,247,0.4);
- }
- .stage-progress-text {
- font-size: 10px; color: var(--muted);
- display: flex; justify-content: space-between;
- font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
- }
+ /* === FALLBACK: Hide unwanted inline icons in version pill === */
+ body > header > .pill svg { width: 12px; height: 12px; }
- /* Session outputs gallery */
- .stage-outputs {
- display: grid;
- grid-template-columns: repeat(auto-fill, minmax(140px, 1fr));
- gap: 8px;
- }
- /* Filter chips above the Session outputs grid — same shape as the
- Recent tab's row-list-filter (single row of pill buttons, the
- active one tinted with the accent border). Sits between the
- count badge and the grid. */
- .stage-outputs-filter {
- display: flex;
- gap: 6px;
- margin: 0 0 8px;
- }
- .stage-outputs-filter button {
- width: auto;
- padding: 3px 10px;
- font-size: 11px;
- font-weight: 500;
- color: var(--muted);
- background: transparent;
- border: 1px solid var(--border);
- border-radius: 999px;
- cursor: pointer;
- transition: color var(--t-base), border-color var(--t-base), background var(--t-base);
- }
- .stage-outputs-filter button:hover {
- color: var(--text);
- border-color: var(--accent);
- }
- .stage-outputs-filter button.active {
- color: var(--accent-bright);
- border-color: var(--accent);
- background: var(--accent-dim, rgba(47,129,247,0.12));
- }
- .stage-output-cell {
- position: relative;
- aspect-ratio: 16/9;
- background: var(--bg);
- border: 1px solid var(--border);
- border-radius: 8px;
- overflow: hidden;
- cursor: pointer;
- transition: border-color var(--t-base), transform var(--t-base);
- }
- .stage-output-cell:hover {
- border-color: var(--accent);
- transform: translateY(-1px);
- }
- .stage-output-cell.failed {
- border-color: rgba(207,34,46,0.5);
- background: rgba(207,34,46,0.04);
- }
- .stage-output-cell .vid {
- width: 100%; height: 100%; object-fit: cover; display: block;
- }
- .stage-output-cell .label {
- position: absolute; bottom: 0; left: 0; right: 0;
- padding: 4px 8px;
- background: linear-gradient(180deg, transparent, rgba(0,0,0,0.7));
- color: white;
- font-size: 10px;
- overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
- }
- .stage-output-cell .badge {
- position: absolute; top: 4px; left: 4px;
- font-size: 9px; padding: 2px 6px;
- background: rgba(0,0,0,0.6); color: white;
- border-radius: 4px;
- font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
- letter-spacing: 0.3px;
- }
- .stage-output-cell.failed .badge {
- background: rgba(207,34,46,0.85);
- }
- /* Refine button — small circular icon top-right of every output cell.
- Distinct from the main click area (which opens the lightbox to
- play the clip). Click → drops a reference into the chat composer
- so the user can ask the agent for a variation. */
- .stage-output-cell .refine-btn {
- position: absolute; top: 4px; right: 4px;
- width: 22px; height: 22px;
- border-radius: 50%;
- background: rgba(0,0,0,0.6);
- color: white;
- border: 1px solid rgba(255,255,255,0.15);
- font-size: 11px;
- display: flex; align-items: center; justify-content: center;
- cursor: pointer;
- opacity: 0;
- transition: opacity var(--t-base), background var(--t-base);
- z-index: 1;
- width: 22px;
- }
- .stage-output-cell:hover .refine-btn { opacity: 1; }
- .stage-output-cell .refine-btn:hover {
- background: var(--accent);
- border-color: var(--accent);
- }
- .stage-empty {
- text-align: center; color: var(--muted);
- font-size: 12px; padding: 16px;
- font-style: italic;
- }
- /* Activity feed (recent agent actions) */
- .stage-activity {
- display: flex; flex-direction: column; gap: 6px;
- max-height: 220px; overflow-y: auto;
- font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
- font-size: 11px;
- }
- .stage-activity-row {
- display: flex; align-items: baseline; gap: 8px;
- padding: 4px 0;
- border-bottom: 1px solid rgba(255,255,255,0.03);
- }
- .stage-activity-row:last-child { border-bottom: none; }
- .stage-activity-row .icon {
- width: 14px; flex-shrink: 0;
- font-size: 11px;
- }
- .stage-activity-row.ok .icon { color: #2ea043; }
- .stage-activity-row.fail .icon { color: #cf222e; }
- .stage-activity-row.run .icon { color: var(--accent-bright); }
- .stage-activity-row .text {
- flex: 1; color: var(--text);
- overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
- }
- .stage-activity-row .when {
- color: var(--muted); font-size: 10px;
- flex-shrink: 0;
- }
+ /* === PHOSPHOR ICONS (MIT) ===================================
+ Inline SVG symbol library used across the panel. Glyph art is
+ from phosphor-icons/core (MIT). `.ph` is the base size + color
+ hook; specific call sites can override width/height/color via
+ inline style or component CSS.
- /* ============== HF MODEL BROWSER MODAL ============== */
- .model-browser-modal {
- position: fixed; inset: 0;
- background: rgba(0,2,12,0.7); backdrop-filter: blur(6px);
- z-index: 220;
- display: none;
- align-items: center; justify-content: center;
- animation: agent-fade-in 0.2s ease;
- }
- .model-browser-modal.open { display: flex; }
- .model-browser-card {
- width: min(820px, 96vw); max-height: 88vh;
- display: flex; flex-direction: column;
- background: var(--panel);
- border: 1px solid var(--border-strong);
- border-radius: 14px;
- box-shadow: 0 24px 60px rgba(0,0,0,0.6);
- overflow: hidden;
- }
- .model-browser-head {
- padding: 18px 22px 14px;
- border-bottom: 1px solid var(--border);
- display: flex; align-items: center; gap: 10px;
- }
- .model-browser-head h2 {
- margin: 0; font-size: 17px; font-weight: 600;
- text-transform: none; letter-spacing: -0.1px;
- color: var(--text);
- flex: 1;
- }
- .model-browser-head .subtitle {
- font-size: 11px; color: var(--muted);
- letter-spacing: 0.3px; text-transform: uppercase;
- flex: 0 0 auto;
- }
- .model-browser-head .close-btn {
- width: auto; padding: 5px 12px;
- background: transparent; color: var(--muted);
- border: 1px solid var(--border);
- border-radius: 8px; font-size: 11px; font-weight: 600;
- cursor: pointer;
- }
- .model-browser-head .close-btn:hover {
- color: var(--text); border-color: var(--accent);
- }
- .model-browser-controls {
- padding: 14px 22px;
- display: flex; align-items: center; gap: 10px;
- border-bottom: 1px solid rgba(255,255,255,0.04);
- background: var(--bg-2);
- }
- .model-browser-controls input[type="text"] {
- flex: 1; padding: 9px 12px;
- background: var(--panel); color: var(--text);
- border: 1px solid var(--border);
- border-radius: 8px; font-size: 13px;
- width: auto;
- }
- .model-browser-controls input[type="text"]:focus {
- outline: none; border-color: var(--accent);
- box-shadow: 0 0 0 3px var(--accent-dim);
- }
- .model-browser-controls .checkbox-label {
- display: flex; align-items: center; gap: 6px;
- font-size: 12px; color: var(--muted);
- cursor: pointer; user-select: none;
- flex: 0 0 auto;
- }
- .model-browser-controls .checkbox-label input {
- width: auto; margin: 0;
- }
- .model-browser-controls button {
- padding: 9px 16px; border-radius: 8px;
- border: none; background: var(--accent); color: white;
- font-size: 12px; font-weight: 600; cursor: pointer;
- width: auto;
- }
- .model-browser-controls button:hover { background: var(--accent-bright); }
- .model-browser-controls button[disabled] { opacity: 0.5; cursor: not-allowed; }
- .model-browser-results {
- flex: 1; overflow-y: auto;
- padding: 8px 14px 18px;
- }
- .model-result {
- padding: 12px 14px; margin: 6px 0;
- background: var(--bg-2); border: 1px solid var(--border);
- border-radius: 10px;
- display: grid; grid-template-columns: 1fr auto;
- gap: 14px;
- transition: border-color var(--t-base);
- }
- .model-result:hover { border-color: var(--accent); }
- .model-result .info { min-width: 0; }
- .model-result .name {
- font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
- font-size: 13px; color: var(--text);
- font-weight: 600;
- overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
- }
- .model-result .meta {
- display: flex; flex-wrap: wrap; gap: 10px;
- margin-top: 4px;
- font-size: 11px; color: var(--muted);
- }
- .model-result .meta .tag {
- padding: 1px 7px; border-radius: 999px;
- background: rgba(255,255,255,0.04);
- color: var(--muted);
- font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
- font-size: 10px;
- }
- .model-result .meta .tag.gated {
- background: rgba(207,34,46,0.12); color: #f49a9e;
- border: 1px solid rgba(207,34,46,0.3);
- }
- .model-result .meta .tag.abliterated {
- background: rgba(204,122,58,0.12); color: #ffb37a;
- border: 1px solid rgba(204,122,58,0.3);
- }
- .model-result .actions {
- display: flex; align-items: center; gap: 8px;
- flex-shrink: 0;
- }
- .model-result .install-btn {
- padding: 7px 14px; border-radius: var(--r-sm);
- background: var(--accent-dim); color: var(--accent-bright);
- border: 1px solid var(--accent);
- font-size: 11px; font-weight: 600; cursor: pointer;
- width: auto;
- transition: background var(--t-base), color var(--t-base);
- }
- .model-result .install-btn:hover {
- background: var(--accent); color: white;
- }
- .model-result .install-btn[disabled] { opacity: 0.5; cursor: not-allowed; }
- .model-result .info-btn {
- padding: 7px 10px; border-radius: var(--r-sm);
- background: transparent; color: var(--muted);
- border: 1px solid var(--border);
- font-size: 11px; cursor: pointer; width: auto;
- }
- .model-result .info-btn:hover {
- color: var(--text); border-color: var(--accent);
- }
- .model-browser-status {
- padding: 12px 22px;
- border-top: 1px solid var(--border);
- background: var(--bg-2);
- font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
- font-size: 11px; color: var(--muted);
- display: none;
- }
- .model-browser-status.visible { display: block; }
- .model-browser-status .label {
- color: var(--accent-bright); font-weight: 700;
- margin-right: 8px;
- }
- .model-browser-status .last-line {
- max-height: 60px; overflow-y: auto;
- white-space: pre-wrap; word-break: break-all;
- margin-top: 6px;
- color: var(--text);
- }
- .model-browser-empty {
- text-align: center; padding: 60px 20px;
- color: var(--muted); font-size: 13px;
- }
+ Pattern: <svg class="ph"><use href="#ph-x"/></svg>
- /* Lightbox: clicking a stage-output-cell plays the video full-size */
- .stage-lightbox {
- position: fixed; inset: 0;
- background: rgba(0,2,12,0.85);
- backdrop-filter: blur(8px);
- z-index: 250;
- display: none;
- align-items: center; justify-content: center;
- padding: 40px;
- }
- .stage-lightbox.open { display: flex; }
- .stage-lightbox video {
- max-width: 90vw; max-height: 80vh;
- border-radius: 12px;
- box-shadow: 0 24px 80px rgba(0,0,0,0.6);
- }
- .stage-lightbox .close-btn {
- position: absolute;
- top: 16px; right: 20px;
- background: rgba(255,255,255,0.08);
- color: white;
- border: 1px solid rgba(255,255,255,0.1);
- border-radius: 8px;
- padding: 8px 14px;
- font-size: 12px;
- cursor: pointer;
- width: auto;
- }
- .stage-lightbox .close-btn:hover {
- background: rgba(255,255,255,0.14);
- }
- .stage-lightbox .refine-btn-large {
- position: absolute;
- top: 16px; right: 110px;
- background: var(--accent);
- color: white;
- border: 1px solid var(--accent);
- border-radius: 8px;
- padding: 8px 16px;
- font-size: 12px; font-weight: 600;
- cursor: pointer; width: auto;
- box-shadow: 0 4px 14px rgba(47,129,247,0.4);
- }
- .stage-lightbox .refine-btn-large:hover {
- background: var(--accent-bright);
+ `currentColor` ties stroke/fill to the parent's text color so
+ the existing `.danger`, `.muted`, `.accent-bright` classes carry
+ through. NEVER hardcode a color inside a <symbol> path. */
+ .ph {
+ width: 1em;
+ height: 1em;
+ flex-shrink: 0;
+ display: inline-block;
+ vertical-align: -0.125em;
+ color: currentColor;
}
+ .ph-sm { width: 12px; height: 12px; }
+ .ph-md { width: 14px; height: 14px; }
+ .ph-lg { width: 18px; height: 18px; }
+ .ph-xl { width: 24px; height: 24px; }
+ .ph-2xl { width: 32px; height: 32px; }
+ /* For buttons that previously held a single unicode glyph
+ (×, ↗, ↻, etc.). Make the SVG inherit the button's flex centering. */
+ button > .ph, a > .ph { display: block; }
+ /* Spinner keyframe for refresh icons used in "checking…" pills. */
+ @keyframes phSpin { from { transform: rotate(0deg); } to { transform: rotate(360deg); } }
+ </style>
+</head>
+<body>
- /* Expand lightbox: full-viewport image/video viewer triggered from
- the main player's Expand button. Backdrop click + Esc both close.
- Image scales to fit the viewport without zooming past native res. */
- .expand-lightbox {
- position: fixed; inset: 0;
- background: rgba(0,2,12,0.92);
- backdrop-filter: blur(10px);
- z-index: 300;
- display: flex;
- align-items: center; justify-content: center;
- flex-direction: column;
- padding: 40px 40px 24px;
- animation: expand-fade-in 0.15s ease;
- }
- @keyframes expand-fade-in { from { opacity: 0; } to { opacity: 1; } }
- .expand-lightbox .expand-stage {
- flex: 1 1 auto;
- display: flex; align-items: center; justify-content: center;
- width: 100%; min-height: 0;
- }
- .expand-lightbox .expand-stage img,
- .expand-lightbox .expand-stage video {
- max-width: 100%; max-height: 100%;
- width: auto; height: auto;
- object-fit: contain;
- border-radius: 10px;
- box-shadow: 0 30px 90px rgba(0,0,0,0.7);
- }
- .expand-lightbox .expand-meta {
- flex: 0 0 auto;
- margin-top: 16px;
- color: rgba(255,255,255,0.7);
- font-size: 12px;
- letter-spacing: 0.02em;
- text-align: center;
- max-width: 80vw;
- white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
- }
- .expand-lightbox .expand-close {
- position: absolute;
- top: 18px; right: 22px;
- width: 36px; height: 36px;
- display: inline-flex; align-items: center; justify-content: center;
- background: rgba(255,255,255,0.08);
- color: white;
- border: 1px solid rgba(255,255,255,0.12);
- border-radius: 10px;
- cursor: pointer;
- transition: background 0.12s ease;
- }
- .expand-lightbox .expand-close:hover { background: rgba(255,255,255,0.16); }
-
- /* ---- Composer reference chip ----
- When the user clicks Refine on a clip, a chip appears just above
- the textarea with the clip's label + a × to clear it. The chip's
- data is sent verbatim as a prefix to the user's next message so
- the agent picks up the reference and calls inspect_clip first. */
- .agent-ref-chip {
- display: none;
- align-items: center; gap: 8px;
- padding: 6px 10px 6px 12px;
- margin: 0 0 6px 0;
- background: var(--accent-dim);
- border: 1px solid var(--accent);
- border-radius: 999px;
- font-size: 12px;
- color: var(--accent-bright);
- max-width: fit-content;
- animation: agent-fade-in 0.2s ease;
- }
-
- /* Batch-now bar: appears above the composer when there are picked
- anchors not yet submitted. One-click trigger to queue them all. */
- .agent-batch-bar {
- display: flex;
- align-items: center;
- justify-content: space-between;
- gap: 12px;
- padding: 9px 14px 9px 16px;
- margin: 0 0 10px 0;
- background: linear-gradient(135deg, rgba(63,185,80,0.10) 0%, rgba(47,129,247,0.08) 100%);
- border: 1px solid rgba(63,185,80,0.35);
- border-radius: 12px;
- animation: agent-fade-in 0.22s ease;
- box-shadow: 0 4px 16px rgba(63,185,80,0.06);
- }
- .agent-batch-bar[hidden] { display: none; }
- .agent-batch-bar-text {
- display: inline-flex;
- align-items: center;
- gap: 10px;
- font-size: 12.5px;
- color: var(--text);
- }
- .agent-batch-bar-icon {
- color: var(--success, #3fb950);
- font-size: 14px;
- line-height: 1;
- }
- .agent-batch-bar-btn {
- display: inline-flex;
- align-items: center;
- gap: 6px;
- padding: 6px 12px;
- background: var(--success, #3fb950);
- color: #04130a;
- border: none;
- border-radius: 8px;
- font-size: 12px;
- font-weight: 600;
- cursor: pointer;
- transition: filter var(--t-base), transform var(--t-base);
- width: auto;
- flex: 0 0 auto;
- }
- .agent-batch-bar-btn:hover { filter: brightness(1.08); transform: translateY(-1px); }
- .agent-batch-bar-btn:active { transform: translateY(0); }
- .agent-batch-bar-btn svg { flex-shrink: 0; }
-
- /* Phase 0 #0.11 — Engine readiness banner.
- Sits between the agent header and the chat. Shows tri-state:
- success (green, auto-fades after 4s), warn (amber, sticky),
- error (red, sticky). Fires on session-surface init and after
- settings save so users discover 401 / unreachable BEFORE they
- invest in writing a long prompt. */
- .agent-engine-banner {
- display: flex;
- align-items: center;
- justify-content: space-between;
- gap: 12px;
- padding: 8px 12px 8px 14px;
- margin: 0 14px 8px 14px;
- border-radius: 10px;
- font-size: 12.5px;
- animation: agent-fade-in 0.22s ease;
- transition: opacity 0.4s ease;
- }
- .agent-engine-banner[hidden] { display: none; }
- .agent-engine-banner.dismissing { opacity: 0; }
- .agent-engine-banner.ok {
- background: rgba(63,185,80,0.10);
- border: 1px solid rgba(63,185,80,0.30);
- color: #b8e9c4;
- }
- .agent-engine-banner.warn {
- background: rgba(245,180,49,0.10);
- border: 1px solid rgba(245,180,49,0.30);
- color: #f3d28a;
- }
- .agent-engine-banner.err {
- background: rgba(248,81,73,0.10);
- border: 1px solid rgba(248,81,73,0.40);
- color: #f5b3ae;
- }
- .agent-engine-banner-text {
- display: inline-flex;
- align-items: center;
- gap: 8px;
- flex: 1 1 auto;
- min-width: 0;
- }
- .agent-engine-banner-icon {
- flex: 0 0 auto;
- width: 14px; height: 14px;
- display: inline-flex; align-items: center; justify-content: center;
- }
- .agent-engine-banner-title { font-weight: 600; }
- .agent-engine-banner-detail {
- opacity: 0.85;
- font-size: 11.5px;
- overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
- }
- .agent-engine-banner-actions {
- display: inline-flex;
- align-items: center;
- gap: 6px;
- flex: 0 0 auto;
- }
- .agent-engine-banner-btn {
- padding: 4px 9px;
- background: transparent;
- border: 1px solid currentColor;
- color: inherit;
- border-radius: 7px;
- font-size: 11.5px;
- font-weight: 600;
- cursor: pointer;
- opacity: 0.85;
- transition: opacity var(--t-base), background var(--t-base);
- }
- .agent-engine-banner-btn:hover { opacity: 1; background: rgba(255,255,255,0.06); }
- .agent-engine-banner-close {
- width: 22px; height: 22px;
- background: transparent;
- border: none;
- color: inherit;
- cursor: pointer;
- opacity: 0.6;
- border-radius: 6px;
- display: inline-flex;
- align-items: center;
- justify-content: center;
- }
- .agent-engine-banner-close:hover { opacity: 1; background: rgba(255,255,255,0.06); }
-
- /* Phase 0 #0.9 — turn summary chip.
- Sits below the LAST assistant message of a completed turn. Reads
- like "4 anchors · 2 shots queued · ✓ finished" — one-glance answer
- to "what just happened in this turn" without scrolling 30 cards. */
- .agent-turn-summary {
- display: flex;
- align-items: center;
- gap: 8px;
- margin: 6px 0 0 0;
- padding: 5px 10px;
- background: rgba(120, 140, 160, 0.06);
- border: 1px solid rgba(120, 140, 160, 0.18);
- border-radius: 8px;
- font-size: 11.5px;
- color: var(--muted);
- max-width: fit-content;
- animation: agent-fade-in 0.18s ease;
- }
- .agent-turn-summary-icon {
- width: 10px; height: 10px;
- flex: 0 0 auto;
- opacity: 0.6;
- }
- .agent-turn-summary-text {
- font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
- font-size: 11px;
- letter-spacing: 0.01em;
- }
- .agent-turn-summary-text .sep { opacity: 0.4; padding: 0 1px; }
- .agent-turn-summary-text .ok { color: var(--success, #3fb950); }
-
- .agent-ref-chip.visible { display: inline-flex; }
- .agent-ref-chip .ref-icon {
- font-size: 11px;
- }
- .agent-ref-chip .ref-label {
- font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
- font-size: 11px;
- max-width: 320px;
- overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
- }
- .agent-ref-chip .clear {
- background: transparent;
- color: var(--accent-bright);
- border: none;
- width: 18px; height: 18px;
- border-radius: 50%;
- cursor: pointer;
- font-size: 14px;
- line-height: 1;
- display: flex; align-items: center; justify-content: center;
- }
- .agent-ref-chip .clear:hover {
- background: rgba(255,255,255,0.1);
- }
-
- /* =========================================================
- FULLSCREEN / FOCUS MODE — pro-app polish
- =========================================================
- Toggle via .agent-fullscreen on <body>. Hides every chrome
- element, paints a soft radial-gradient backdrop, centers
- the conversation in a comfortable reading column, and
- floats the composer with a glass-blur effect so the chat
- fades under it.
- Esc exits — bound in JS. */
-
- /* Wipe all the regular panel chrome.
- NOTE: `body.agent-fullscreen > header` (direct child only) — without
- the > combinator the rule also matches the agent's own
- <header class="agent-header"> inside the chat, which is exactly
- what we DON'T want to hide.
- Stage pane (right column) STAYS visible — it becomes the agent's
- live canvas / code-interpreter view. */
- body.agent-fullscreen > header,
- body.agent-fullscreen .bottom-pane,
- /* Hide form-pane children EXCEPT .agent-pane (the chat itself) and
- .agent-sessions-panel (the left sidebar — fullscreen polish 2026-05-07
- per Salo: sessions stay visible always in fullscreen). */
- body.agent-fullscreen .form-pane > :not(.agent-pane):not(.agent-sessions-panel),
- body.agent-fullscreen .workflow-tabs,
- body.agent-fullscreen .stage-pane {
- display: none !important;
- }
- body.agent-fullscreen { overflow: hidden; }
- /* Fullscreen layout: chat on the left, stage pane on the right.
- Like Claude.ai with Artifacts open — conversation + live canvas. */
- body.agent-fullscreen .layout {
- max-width: none; padding: 0; margin: 0; gap: 0;
- height: 100vh;
- display: grid;
- grid-template-columns: 1fr minmax(420px, 480px);
- }
- body.agent-fullscreen .form-pane {
- max-width: none; padding: 0;
- width: 100%; height: 100vh;
- border: none; border-radius: 0;
- background: transparent;
- }
- body.agent-fullscreen .agent-stage-pane {
- display: flex !important;
- border: none; border-radius: 0;
- border-left: 1px solid rgba(255,255,255,0.05);
- background: rgba(0, 6, 26, 0.3);
- backdrop-filter: blur(8px);
- height: 100vh; width: 100%;
- }
-
- /* Soft body backdrop — subtle radial wash gives depth without
- fighting the conversation. */
- body.agent-fullscreen {
- background:
- radial-gradient(ellipse 80% 60% at 50% -10%, rgba(47,129,247,0.06), transparent 70%),
- radial-gradient(ellipse 70% 50% at 50% 110%, rgba(204,122,58,0.04), transparent 70%),
- var(--bg);
- background-attachment: fixed;
- }
-
- /* The pane fills the form-pane column (NOT 100vw — that ignores
- the parent grid layout and makes the chat overlap the stage at
- wider viewports). Salo's 1920px screen exposed this bug. */
- body.agent-fullscreen .agent-pane {
- width: 100%; height: 100vh; max-height: 100vh;
- border: none; border-radius: 0;
- background: transparent;
- overflow: hidden;
- display: flex; flex-direction: column;
- box-sizing: border-box;
- }
-
- /* Header in fullscreen: same chip language as the regular agent
- header (Linear pass — see ~line 10466). We only override the
- LAYOUT bits (centered, max-width, generous breathing room) and
- drop the bottom hairline so the chat below blends. The chip
- styles for engine-pill / mode-pill / RAM chip / icon-btn cascade
- from the Linear pass, so fullscreen and regular look identical
- except for the dimensions. */
- body.agent-fullscreen .agent-header {
- background: transparent;
- border-bottom: none;
- padding: 12px 28px;
- max-width: 1080px; width: 100%;
- margin: 0 auto;
- box-sizing: border-box;
- height: auto;
- }
- body.agent-fullscreen .agent-header .session-title {
- font-size: 13px;
- letter-spacing: -0.01em;
- }
- body.agent-fullscreen .agent-header .session-title .meta {
- font-size: 11px;
- opacity: 0.55;
- }
- /* Add the Phosphene wordmark + logo back into the fullscreen
- header so the brand stays visible even when the main top
- header is hidden. Inserted via ::before on .agent-header so we
- don't need to touch the HTML structure. */
- body.agent-fullscreen .agent-pane > .agent-header::before {
- content: '';
- flex: 0 0 auto;
- display: inline-block;
- width: 28px; height: 28px;
- background: url('/assets/favicon-64.png') center/contain no-repeat;
- filter: drop-shadow(0 0 3px rgba(79, 214, 255, 0.35));
- margin-right: 6px;
- }
-
- /* Chat: takes the rest, content column centered at reading width */
- body.agent-fullscreen .agent-chat {
- max-height: none;
- flex: 1;
- padding: 8px 28px 0;
- scroll-padding-bottom: 140px;
- }
- body.agent-fullscreen .agent-chat::-webkit-scrollbar { width: 10px; }
- body.agent-fullscreen .agent-chat::-webkit-scrollbar-thumb {
- background: rgba(255,255,255,0.06);
- border-radius: 4px;
- border: 2px solid transparent;
- background-clip: padding-box;
- }
- body.agent-fullscreen .agent-chat::-webkit-scrollbar-thumb:hover {
- background: rgba(255,255,255,0.14);
- background-clip: padding-box;
- }
-
- /* Center every direct child of the chat at reading width */
- body.agent-fullscreen .agent-chat > * {
- max-width: 720px;
- margin-left: auto; margin-right: auto;
- width: 100%;
- }
- body.agent-fullscreen .agent-empty {
- max-width: 580px; margin: 80px auto 24px;
- }
- body.agent-fullscreen .agent-msg-row {
- margin-bottom: 26px;
- }
- body.agent-fullscreen .agent-avatar {
- width: 30px; height: 30px;
- box-shadow: 0 0 0 1px rgba(255,255,255,0.04);
- }
- body.agent-fullscreen .agent-avatar.claude {
- box-shadow: 0 0 0 1px rgba(204,122,58,0.4),
- 0 4px 16px rgba(204,122,58,0.18);
- }
-
- /* Composer: floating glass card with soft shadow + fading
- gradient above so chat appears to dissolve under it.
- Width unified with chat reading column (800px) so the textarea
- aligns vertically with the chat above. */
- body.agent-fullscreen .agent-composer {
- background: transparent;
- border-top: none;
- padding: 0;
- position: relative;
- z-index: 5;
- }
- body.agent-fullscreen .agent-composer::before {
- content: '';
- position: absolute; inset: -56px 0 0 0;
- pointer-events: none;
- background: linear-gradient(
- 180deg,
- transparent 0%,
- rgba(0,6,26,0.5) 30%,
- rgba(0,6,26,0.85) 65%,
- var(--bg) 100%
- );
- }
- /* Composer chrome — Claude.ai / Gemini-grade glass card.
- The wrap is a relative container; textarea fills it and the
- attach (paperclip) + send buttons absolute-position over the
- bottom edge inside the same rounded box. Padding on the textarea
- reserves room for both buttons so typed text never collides with
- them. Attach button on the LEFT (40px reservation), send on the
- RIGHT (50px reservation). */
- body.agent-fullscreen .agent-composer-wrap {
- max-width: none; width: 100%;
- margin: 0;
- position: relative; z-index: 1;
- background: transparent; /* the textarea owns the glass look */
- border: none;
- padding: 0;
- }
- body.agent-fullscreen .agent-composer textarea {
- background: rgba(20, 26, 58, 0.92);
- backdrop-filter: blur(12px);
- -webkit-backdrop-filter: blur(12px);
- border: 1px solid rgba(120, 140, 220, 0.16);
- border-radius: 18px;
- /* top right bottom left — left 56 makes room for attach button (44+12),
- right 56 makes room for send button. Bottom 14 sits the textarea
- off the bottom edge so buttons don't collide with descenders. */
- padding: 16px 56px 16px 56px;
- box-shadow:
- 0 14px 40px rgba(0,0,0,0.55),
- 0 0 0 1px rgba(47,129,247,0.0);
- font-size: 15px;
- line-height: 1.5;
- min-height: 56px;
- transition: border-color var(--t-base), box-shadow var(--t-base), background var(--t-base);
- }
- body.agent-fullscreen .agent-composer textarea:focus {
- background: rgba(28, 36, 72, 0.95);
- border-color: rgba(47,129,247,0.55);
- box-shadow:
- 0 14px 40px rgba(0,0,0,0.55),
- 0 0 0 4px rgba(47,129,247,0.14);
- }
- body.agent-fullscreen .agent-composer .hint {
- bottom: -22px; left: 0;
- width: 100%; text-align: center;
- opacity: 0.5;
- }
-
- /* Attach (paperclip) button — visible by default, brighter on hover.
- Earlier was muted-on-dark and effectively invisible per Salo's
- screenshot ("we lost the ability to upload files and images"). */
- body.agent-fullscreen .agent-composer .attach-btn {
- width: 40px; height: 40px;
- left: 8px; bottom: 8px;
- border-radius: 12px;
- background: rgba(255,255,255,0.05);
- color: var(--text);
- border: 1px solid rgba(255,255,255,0.10);
- z-index: 2;
- transition: background var(--t-base), color var(--t-base),
- border-color var(--t-base), transform var(--t-base);
- }
- body.agent-fullscreen .agent-composer .attach-btn:hover {
- background: rgba(47,129,247,0.12);
- color: var(--accent-bright);
- border-color: rgba(47,129,247,0.35);
- transform: translateY(-1px);
- }
- body.agent-fullscreen .agent-composer .attach-btn svg {
- width: 18px; height: 18px;
- }
- body.agent-fullscreen .agent-composer .attach-btn.has-attach {
- background: rgba(47,129,247,0.18);
- color: var(--accent-bright);
- border-color: rgba(47,129,247,0.45);
- }
-
- /* Send button — accent fill, matched 40x40 with attach (so the
- composer reads as a balanced triplet). The Linear pass uses an
- ID selector (#agentSendBtn) for its 30x30 override; we match
- that specificity here so the fullscreen size wins.
- Also brightens the disabled state — earlier rgba(255,255,255,
- 0.3) on dark glass made the button effectively invisible per
- Salo's screenshot ("send button is not even centered" — it
- was, but barely visible at 30x30 with 0.3 opacity). */
- body.agent-fullscreen .agent-composer .send-btn,
- body.agent-fullscreen #agentSendBtn {
- width: 40px; height: 40px;
- right: 8px; bottom: 8px;
- border-radius: 12px;
- z-index: 2;
- box-shadow: 0 6px 20px rgba(47,129,247,0.45);
- }
- body.agent-fullscreen .agent-composer .send-btn:hover:not(:disabled),
- body.agent-fullscreen #agentSendBtn:hover:not(:disabled) {
- box-shadow: 0 8px 28px rgba(47,129,247,0.55);
- transform: translateY(-1px);
- }
- body.agent-fullscreen .agent-composer .send-btn:disabled,
- body.agent-fullscreen #agentSendBtn:disabled {
- background: rgba(120, 140, 200, 0.10);
- color: rgba(220, 230, 250, 0.55); /* visible "ready to send" affordance even when empty */
- box-shadow: none;
- }
- body.agent-fullscreen .agent-composer .send-btn svg,
- body.agent-fullscreen #agentSendBtn svg {
- width: 18px; height: 18px;
- }
-
- /* Tool cards: tighten + soften in fullscreen */
- body.agent-fullscreen .agent-tool-card {
- background: rgba(255,255,255,0.025);
- border-color: rgba(255,255,255,0.06);
- }
- body.agent-fullscreen .agent-tool-card:hover {
- border-color: rgba(47,129,247,0.4);
- }
- body.agent-fullscreen .agent-tool-card .head {
- padding: 9px 14px;
- font-size: 12px;
- }
- body.agent-fullscreen .agent-tool-card .body {
- padding: 0 14px 12px;
- }
-
- /* Anchor grid in fullscreen: roomier cells, no card border around them */
- body.agent-fullscreen .anchor-grid {
- grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
- gap: 12px;
- }
- body.agent-fullscreen .anchor-cell {
- border-width: 1px;
- border-color: rgba(255,255,255,0.06);
- box-shadow: 0 4px 14px rgba(0,0,0,0.25);
- }
- body.agent-fullscreen .anchor-cell:hover {
- transform: translateY(-2px) scale(1.01);
- box-shadow: 0 8px 24px rgba(0,0,0,0.35);
- }
-
- /* Empty state in fullscreen — magazine-feel layout */
- body.agent-fullscreen .agent-empty {
- padding: 40px 0 60px;
- }
- body.agent-fullscreen .agent-empty h3 {
- font-size: 26px; font-weight: 600;
- letter-spacing: -0.4px;
- margin: 14px 0 12px;
- }
- body.agent-fullscreen .agent-empty p {
- font-size: 14px; line-height: 1.65;
- max-width: 460px; margin: 8px auto;
- }
- body.agent-fullscreen .agent-empty .examples {
- gap: 10px; margin-top: 32px;
- }
- body.agent-fullscreen .agent-empty .example {
- padding: 14px 16px;
- background: rgba(255,255,255,0.025);
- border-color: rgba(255,255,255,0.06);
- border-radius: 12px;
- }
- body.agent-fullscreen .agent-empty .example:hover {
- background: rgba(47,129,247,0.06);
- border-color: rgba(47,129,247,0.4);
- }
-
- /* Sessions popover anchored to the header — keep it usable in fullscreen */
- /* (Old .agent-sessions-pop fullscreen override removed — sidebar
- handles its own fullscreen positioning now.) */
-
- /* Fullscreen entrance */
- body.agent-fullscreen .agent-pane {
- animation: agent-fullscreen-in 0.28s cubic-bezier(0.2, 0.7, 0.2, 1);
- }
- @keyframes agent-fullscreen-in {
- from { opacity: 0.6; transform: scale(0.99); }
- to { opacity: 1; transform: scale(1); }
- }
-
- /* =========================================================
- FULLSCREEN POLISH PASS — Salo 2026-05-07
- =========================================================
- Per Salo: "improve the design of the full page for the chat,
- it's not looking good. Put the history on the left to be
- steady there. Make the full screen button stand out so people
- know there is such an option."
-
- Three pieces:
- A. Sessions sidebar is ALWAYS pinned on the left in
- fullscreen — no toggle needed, no slide-in animation;
- it sits as a third grid column.
- B. Three-column layout: 268px sessions | flexible chat |
- 440px stage. The chat reads as a centered reading column.
- C. Fullscreen toggle button gets a brand-gradient accent in
- regular mode so users discover the affordance; in
- fullscreen it inverts to a subdued "exit" treatment. */
-
- /* ---- A. Sessions sidebar always visible in fullscreen ----------
- The panel is nested inside .form-pane in the DOM and uses
- position:fixed at left:0 so its slide-in transform doesn't
- reflow the chat. In fullscreen we keep that fixed positioning
- (taking it out of flow) but force transform:none so it's always
- visible at the screen's left edge. The form-pane and the layout
- grid then reserve 280px of left padding so the chat sits cleanly
- to the right of the sidebar. This matches how the regular-layout
- asp-pinned mode works (see line 7642), but applies UNCONDITIONALLY
- in fullscreen — no toggle needed. */
- body.agent-fullscreen .agent-sessions-panel {
- transform: none !important; /* always shown */
- box-shadow: none !important;
- border-right: 1px solid var(--ph-border-soft);
- background: rgba(8, 13, 36, 0.7);
- backdrop-filter: blur(10px);
- -webkit-backdrop-filter: blur(10px);
- width: 280px;
- z-index: 5; /* above chat scroll, below modals */
- }
- body.agent-fullscreen .asp-backdrop { display: none !important; }
- body.agent-fullscreen #aspPinBtn { display: none !important; } /* irrelevant — always pinned */
- /* Hide the in-panel close (X) button: in fullscreen the sidebar
- can't be closed without exiting fullscreen, so the X is dead. */
- body.agent-fullscreen .agent-sessions-panel .asp-head .asp-icon[onclick*="aspClose"] {
- display: none !important;
- }
- /* Sessions panel head/search inherit Linear chrome but lose the
- hairlines that made sense as an overlay; here they read as
- internal sections of the integrated sidebar. */
- body.agent-fullscreen .asp-head {
- border-bottom: 1px solid var(--ph-border-soft);
- padding: 14px 16px 12px;
- }
- body.agent-fullscreen .asp-head .asp-title {
- font-size: 12.5px;
- font-weight: 600;
- letter-spacing: 0.04em;
- text-transform: uppercase;
- color: var(--ph-text-faint);
- }
- body.agent-fullscreen .asp-search {
- border-bottom: none;
- padding: 10px 16px;
- }
- body.agent-fullscreen .asp-list {
- padding: 4px 10px 16px;
- }
-
- /* ---- B. Two-column grid + 280px form-pane padding ---------- */
- /* The layout grid has only 2 children (form-pane + stage-pane);
- sessions are nested INSIDE form-pane as a fixed overlay. So we
- use a 2-col grid (1fr + 480px) and pad form-pane left by 280px
- to make room for the fixed-positioned sidebar. */
- body.agent-fullscreen .layout {
- grid-template-columns: 1fr minmax(440px, 480px);
- }
- /* Form-pane in fullscreen: padding pattern `0 32px 0 312px`:
- 312 = 280 sidebar overlay + 32 gutter (chat starts right after
- the sidebar with breathing room)
- 32 = right gutter before stage column begins
- Per Salo's first-pass screenshot, max-width + margin:auto
- centered the chat 200px to the right of the sidebar with
- awkward empty space — switched to left-anchored chat below. */
- body.agent-fullscreen .form-pane {
- padding: 0 32px 0 312px;
- display: flex; flex-direction: column;
- align-items: stretch;
- box-sizing: border-box;
- }
- body.agent-fullscreen.asp-pinned .form-pane { padding: 0 32px 0 312px; }
- /* Chat reading column — centered within the form-pane content
- area. At 1600px viewport, content area = 796px; chat 800px is
- clamped to 796 with no centering slack (sits left-anchored to
- sidebar). At wider viewports (1920px+), chat stays at 800px and
- centers between sidebar and stage with comfortable gutters on
- both sides. Salo's screen is wider; this fixes "central window
- not properly centered". */
- body.agent-fullscreen .agent-chat {
- max-width: 800px;
- width: 100%;
- margin: 0 auto;
- padding: 12px 0 20px;
- }
- body.agent-fullscreen .agent-composer {
- max-width: 800px;
- width: 100%;
- margin: 0 auto 18px;
- padding: 0;
- }
- /* Header spans the full form-pane content width so the chips
- (Sessions / engine / mode / RAM / title / icons) all fit on one
- row regardless of how many chips light up. Salo's first-pass
- screenshot showed them wrapping to 2 rows under max-width:800.
- Top padding 22px gives the chips comfortable breathing room
- from the viewport / browser-chrome edge — earlier 14px was
- too tight; chips visually crammed against the URL bar. */
- body.agent-fullscreen .agent-pane > .agent-header {
- max-width: none;
- margin: 0;
- padding: 22px 0 14px;
- }
- /* Engine-readiness banner aligns with the chat column. */
- body.agent-fullscreen #agentEngineBanner {
- max-width: 800px;
- margin: 8px auto;
- }
-
- /* User bubble in fullscreen — a touch wider so dialogue beats
- don't wrap awkwardly at this reading width. */
- body.agent-fullscreen .agent-msg-row { max-width: 100%; }
- body.agent-fullscreen .agent-msg-row.user .agent-msg-body {
- max-width: 78%;
- }
-
- /* ---- C. Fullscreen toggle button stands out --------------- */
- /* In regular (non-fullscreen) mode: subtle brand-gradient accent
- so users SEE the affordance. The other icon-buttons are quiet
- greyscale; this one announces itself. */
- body:not(.agent-fullscreen) .agent-header #agentFullscreenBtn {
- background: linear-gradient(135deg,
- rgba(255, 61, 138, 0.10) 0%,
- rgba(79, 214, 255, 0.10) 100%);
- border: 1px solid rgba(79, 214, 255, 0.28);
- color: #c8e9ff;
- box-shadow: 0 0 0 0 rgba(79, 214, 255, 0);
- transition: box-shadow var(--t-base), background var(--t-base),
- border-color var(--t-base), color var(--t-base);
- }
- body:not(.agent-fullscreen) .agent-header #agentFullscreenBtn:hover {
- background: linear-gradient(135deg,
- rgba(255, 61, 138, 0.20) 0%,
- rgba(79, 214, 255, 0.20) 100%);
- border-color: rgba(79, 214, 255, 0.55);
- color: #fff;
- box-shadow: 0 0 14px rgba(79, 214, 255, 0.20);
- }
- /* In fullscreen: the button reverts to a quiet "exit" affordance
- so it doesn't fight the chat for attention. */
- body.agent-fullscreen .agent-header #agentFullscreenBtn {
- background: rgba(140, 160, 220, 0.06);
- border: 1px solid var(--ph-border-strong);
- color: var(--muted);
- }
- body.agent-fullscreen .agent-header #agentFullscreenBtn:hover {
- color: var(--text);
- border-color: var(--ph-border-strong);
- background: rgba(140, 160, 220, 0.10);
- }
-
- /* ---- Typing indicator ---- */
- .agent-typing-row {
- display: flex; gap: 12px;
- align-items: flex-start;
- margin-bottom: 22px;
- animation: agent-fade-in 0.2s ease;
- }
- .agent-typing-bubble {
- padding: 10px 14px;
- background: var(--bg-2);
- border: 1px solid var(--border);
- border-radius: 12px;
- font-size: 12px;
- color: var(--muted);
- display: flex; align-items: center; gap: 10px;
- }
- .agent-typing-abort {
- display: inline-flex;
- align-items: center; justify-content: center;
- width: 18px; height: 18px;
- margin-left: 4px;
- border-radius: 50%;
- background: transparent;
- border: 1px solid var(--border);
- color: var(--muted);
- cursor: pointer;
- transition: color var(--t-fast), border-color var(--t-fast), background var(--t-fast);
- padding: 0;
- width: auto;
- flex: 0 0 auto;
- }
- .agent-typing-abort:hover {
- color: var(--danger, #f85149);
- border-color: rgba(248,81,73,0.5);
- background: rgba(248,81,73,0.10);
- }
- .agent-typing-dots {
- display: inline-flex; gap: 4px;
- }
- .agent-typing-dot {
- width: 6px; height: 6px;
- border-radius: 50%;
- background: var(--accent-bright);
- animation: agent-typing-pulse 1.4s ease-in-out infinite;
- }
- .agent-typing-dot:nth-child(2) { animation-delay: 0.2s; }
- .agent-typing-dot:nth-child(3) { animation-delay: 0.4s; }
- @keyframes agent-typing-pulse {
- 0%, 60%, 100% { opacity: 0.25; transform: scale(0.85); }
- 30% { opacity: 1; transform: scale(1); }
- }
-
- /* ---- Composer ---- */
- /* Button sits INSIDE the textarea (absolute) so it feels like one
- integrated input — the modern chat-app convention. Textarea has
- padding-right to keep typed text clear of the button. */
- .agent-composer {
- border-top: 1px solid var(--border);
- padding: 14px 16px 18px;
- background: var(--bg-2);
- }
- .agent-composer-wrap {
- position: relative;
- }
- .agent-composer textarea {
- width: 100%;
- min-height: 48px; max-height: 220px;
- padding: 13px 56px 13px 50px;
- background: var(--panel);
- color: var(--text);
- border: 1px solid var(--border);
- border-radius: 14px;
- font-family: inherit;
- font-size: var(--agent-text);
- line-height: 1.55;
- resize: none;
- transition: border-color var(--t-base), box-shadow var(--t-base), background var(--t-base);
- box-sizing: border-box;
- }
- /* Paperclip — mirrors send-btn placement on the left edge of the
- composer. Same shape, ghost styling so it doesn't compete with Send. */
- .agent-composer .attach-btn {
- position: absolute;
- left: 7px; bottom: 7px;
- width: 34px; height: 34px;
- border-radius: 10px;
- background: transparent;
- color: var(--muted);
- border: 1px solid transparent;
- cursor: pointer;
- display: inline-flex;
- align-items: center; justify-content: center;
- transition: background var(--t-base), color var(--t-base), border-color var(--t-base);
- }
- .agent-composer .attach-btn:hover {
- background: rgba(255,255,255,0.06);
- color: var(--text);
- border-color: var(--border);
- }
- .agent-composer .attach-btn svg {
- width: 16px; height: 16px;
- }
- .agent-composer .attach-btn .count {
- position: absolute;
- top: -3px; right: -3px;
- min-width: 14px; height: 14px;
- padding: 0 3px;
- background: var(--accent);
- color: white;
- border-radius: var(--r-sm);
- font-size: 9px;
- font-weight: 700;
- display: none;
- align-items: center; justify-content: center;
- letter-spacing: 0;
- }
- .agent-composer .attach-btn.has-attach { color: var(--accent); }
- .agent-composer .attach-btn.has-attach .count { display: inline-flex; }
- /* Pending-attachment chip row above the textarea. */
- .agent-attach-row {
- display: flex;
- flex-wrap: wrap;
- gap: 6px;
- padding: 0 0 8px 0;
- max-width: 720px;
- margin-left: auto; margin-right: auto;
- }
- .agent-attach-chip {
- display: inline-flex;
- align-items: center;
- gap: 8px;
- padding: 5px 10px 5px 5px;
- background: var(--bg-3, rgba(255,255,255,0.04));
- border: 1px solid var(--border);
- border-radius: 10px;
- font-size: 12px;
- color: var(--text);
- max-width: 240px;
- }
- .agent-attach-chip .thumb {
- width: 28px; height: 28px;
- border-radius: 6px;
- object-fit: cover;
- background: rgba(255,255,255,0.08);
- flex-shrink: 0;
- display: inline-flex;
- align-items: center; justify-content: center;
- color: var(--muted);
- font-size: 10px;
- }
- .agent-attach-chip .name {
- max-width: 140px;
- white-space: nowrap;
- overflow: hidden;
- text-overflow: ellipsis;
- }
- .agent-attach-chip .meta {
- color: var(--muted);
- font-size: 10px;
- flex-shrink: 0;
- }
- .agent-attach-chip .remove {
- background: transparent;
- border: none;
- color: var(--muted);
- cursor: pointer;
- padding: 0 2px;
- font-size: 14px;
- line-height: 1;
- }
- .agent-attach-chip .remove:hover { color: #f49a9e; }
- .agent-attach-chip.pending { opacity: 0.6; }
- .agent-attach-chip.error { border-color: rgba(244,154,158,0.6); color: #f49a9e; }
-
- /* In-message attachment chips (rendered inside user bubbles). Slightly
- softer than the composer chips to read as past, not pending. */
- .agent-msg-attachments {
- display: flex;
- flex-wrap: wrap;
- gap: 6px;
- margin-bottom: 8px;
- }
- .agent-msg-attach {
- display: inline-flex;
- align-items: center;
- gap: 8px;
- padding: 5px 10px 5px 5px;
- background: rgba(255,255,255,0.04);
- border: 1px solid var(--border);
- border-radius: 10px;
- font-size: 11.5px;
- color: var(--text);
- text-decoration: none;
- }
- .agent-msg-attach:hover {
- background: rgba(255,255,255,0.08);
- border-color: var(--accent-dim);
- }
- .agent-msg-attach .thumb {
- width: 26px; height: 26px;
- border-radius: 6px;
- object-fit: cover;
- flex-shrink: 0;
- background: rgba(255,255,255,0.08);
- display: inline-flex;
- align-items: center; justify-content: center;
- color: var(--muted);
- font-size: 10px;
- }
- .agent-msg-attach .name {
- max-width: 200px;
- white-space: nowrap;
- overflow: hidden;
- text-overflow: ellipsis;
- }
-
- /* Drag-drop overlay — full-bleed inside the agent pane, visible only
- while a drag is over the chat surface. Subtle accent ring + dashed
- border so the user understands a drop is wanted. */
- .agent-drop-overlay {
- position: absolute;
- inset: 0;
- background: rgba(47,129,247,0.08);
- border: 2px dashed var(--accent);
- border-radius: 14px;
- display: none;
- align-items: center; justify-content: center;
- pointer-events: none;
- z-index: 50;
- backdrop-filter: blur(2px);
- }
- .agent-drop-overlay.visible { display: flex; }
- .agent-drop-overlay .drop-card {
- display: flex;
- flex-direction: column;
- align-items: center;
- gap: 6px;
- color: var(--accent);
- padding: 18px 28px;
- background: var(--panel);
- border: 1px solid var(--accent-dim);
- border-radius: 14px;
- box-shadow: 0 8px 32px rgba(0,0,0,0.4);
- }
- .agent-composer textarea:focus {
- outline: none;
- border-color: var(--accent);
- box-shadow: 0 0 0 3px var(--accent-dim);
- }
- .agent-composer textarea::placeholder {
- color: var(--muted);
- opacity: 0.7;
- }
- .agent-composer .hint {
- position: absolute;
- bottom: -16px; right: 4px;
- font-size: 10px;
- color: var(--muted);
- letter-spacing: 0.2px;
- pointer-events: none;
- opacity: 0.55;
- }
- .agent-composer .send-btn {
- position: absolute;
- right: 7px; bottom: 7px;
- width: 34px; height: 34px;
- border-radius: 10px;
- background: var(--accent);
- color: white;
- border: none;
- cursor: pointer;
- display: inline-flex;
- align-items: center; justify-content: center;
- transition: background var(--t-base), transform var(--t-base), box-shadow var(--t-base);
- box-shadow: 0 2px 8px rgba(47,129,247,0.3);
- }
- .agent-composer .send-btn:hover:not(:disabled) {
- background: var(--accent-bright);
- transform: translateY(-1px);
- box-shadow: 0 4px 14px rgba(47,129,247,0.45);
- }
- .agent-composer .send-btn:active:not(:disabled) {
- transform: translateY(0);
- }
- .agent-composer .send-btn:disabled {
- background: rgba(255,255,255,0.06);
- color: rgba(255,255,255,0.3);
- cursor: not-allowed;
- box-shadow: none;
- }
- .agent-composer .send-btn svg {
- width: 16px; height: 16px;
- }
-
- /* ---- Settings drawer ---- */
- .agent-settings-modal {
- position: fixed; inset: 0;
- background: rgba(0,2,12,0.7);
- backdrop-filter: blur(6px);
- z-index: 200;
- display: none;
- align-items: center; justify-content: center;
- animation: agent-fade-in 0.2s ease;
- }
- .agent-settings-modal.open { display: flex; }
- .agent-settings-card {
- width: min(580px, 96vw); max-height: 90vh;
- overflow-y: auto;
- padding: 24px;
- border-radius: 14px;
- background: var(--panel);
- border: 1px solid var(--border-strong);
- box-shadow: 0 24px 60px rgba(0,0,0,0.6);
- }
- .agent-settings-card h2 {
- margin: 0 0 6px;
- font-size: 17px; font-weight: 600;
- /* Override the panel-wide h2 rule (line ~5322) which sets uppercase
- + 0.1em letter-spacing. The settings-card titles are sentence-
- case, like a real settings sheet, not eyebrow labels. */
- text-transform: none;
- letter-spacing: -0.1px;
- color: var(--text);
- display: flex; align-items: center; justify-content: space-between;
- gap: 12px;
- }
- .agent-settings-card h2 button,
- .agent-settings-card h2 .close-btn {
- flex-shrink: 0; /* don't let the close button grow huge */
- }
- /* Inline 'Close' button next to the title. The button has no class,
- just sits inside h2 — keep it small and ghosty. */
- .agent-settings-card h2 > button {
- background: transparent;
- color: var(--muted);
- border: 1px solid var(--border);
- border-radius: 8px;
- padding: 5px 12px;
- font-size: 11px;
- font-weight: 600;
- letter-spacing: 0.2px;
- text-transform: none;
- cursor: pointer;
- transition: border-color var(--t-base), color var(--t-base);
- }
- .agent-settings-card h2 > button:hover {
- color: var(--text);
- border-color: var(--accent);
- }
-
- /* The panel has a global `input, textarea, select, button { width: 100% }`
- rule (see ~line 5331). It makes EVERY button full-width by default,
- which destroys the inline button layout in the modal: the Close
- button stretches across the whole card, the Start button next to
- the engine status pill takes 350px, etc. Override for the agent
- modal — buttons here are inline elements managed by their flex
- containers. */
- .agent-settings-card h2 > button,
- .agent-engine-row > button,
- .agent-settings-card .actions > button {
- width: auto;
- }
- .agent-settings-card .subtitle {
- font-size: 12px; color: var(--muted);
- margin-bottom: 18px;
- }
- .agent-settings-card .close-btn {
- background: transparent; color: var(--muted);
- border: 1px solid var(--border); border-radius: 8px;
- padding: 5px 11px; font-size: 11px; cursor: pointer;
- }
- .agent-settings-card .close-btn:hover {
- color: var(--text); border-color: var(--accent);
- }
- .agent-settings-card .field { margin-bottom: 14px; }
- .agent-settings-card label {
- display: block; margin-bottom: 6px;
- font-size: 11px;
- color: var(--muted); font-weight: 600;
- letter-spacing: 0.4px; text-transform: uppercase;
- }
- .agent-settings-card input,
- .agent-settings-card select,
- .agent-settings-card textarea {
- width: 100%;
- padding: 9px 12px;
- background: var(--bg-2); color: var(--text);
- border: 1px solid var(--border); border-radius: 8px;
- font-family: inherit; font-size: 13px;
- box-sizing: border-box;
- transition: border-color var(--t-base);
- }
- .agent-settings-card input:focus,
- .agent-settings-card select:focus,
- .agent-settings-card textarea:focus {
- outline: none; border-color: var(--accent);
- box-shadow: 0 0 0 3px var(--accent-dim);
- }
- .agent-settings-card .row { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; }
- .agent-settings-card .actions {
- display: flex; gap: 8px; margin-top: 18px;
- justify-content: flex-end;
- }
- .agent-settings-card .actions button {
- padding: 9px 18px; border-radius: 8px;
- border: none; cursor: pointer;
- font-size: 13px; font-weight: 600;
- transition: background var(--t-base);
- }
- .agent-settings-card .actions .save {
- background: var(--accent); color: white;
- }
- .agent-settings-card .actions .save:hover { background: var(--accent-bright); }
- .agent-settings-card .actions .ghost {
- background: transparent; color: var(--muted);
- border: 1px solid var(--border);
- }
- .agent-settings-card .actions .ghost:hover {
- color: var(--text); border-color: var(--accent);
- }
- .agent-settings-card .hint {
- font-size: 12px; color: var(--muted); line-height: 1.55;
- padding: 12px 14px; border-radius: 8px;
- background: var(--bg-2); border: 1px solid var(--border);
- margin-bottom: 16px;
- }
- .agent-settings-card .hint code {
- font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
- font-size: 11px;
- padding: 1px 5px;
- background: rgba(255,255,255,0.06);
- border-radius: 3px;
- color: var(--accent-bright);
- }
- .agent-engine-row {
- display: flex; align-items: center; gap: 12px;
- padding: 10px 14px; border-radius: 8px;
- background: var(--bg-2); border: 1px solid var(--border);
- margin-bottom: 12px;
- font-size: 12px;
- }
- .agent-engine-row .pill {
- font-size: 10px; padding: 3px 9px; border-radius: 999px;
- background: var(--panel-2); color: var(--muted);
- border: 1px solid var(--border);
- font-weight: 600; letter-spacing: 0.3px; text-transform: uppercase;
- }
- .agent-engine-row .pill.live {
- color: #9be7a4; border-color: rgba(46,160,67,0.5);
- background: rgba(46,160,67,0.08);
- }
- .agent-engine-row .pill.bad {
- color: #f49a9e; border-color: rgba(207,34,46,0.5);
- background: rgba(207,34,46,0.08);
- }
- .agent-engine-row .row-detail {
- flex: 1; color: var(--muted); min-width: 0;
- overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
- }
- .agent-engine-row button {
- padding: 6px 12px;
- border-radius: var(--r-sm);
- border: 1px solid var(--border);
- background: var(--panel);
- color: var(--text);
- font-size: 11px; font-weight: 600;
- cursor: pointer;
- transition: border-color var(--t-base);
- }
- .agent-engine-row button:hover {
- border-color: var(--accent);
- color: var(--accent-bright);
- }
-
- /* =========================================================
- LINEAR DESIGN PASS — final layer
- =========================================================
- Direction picked by Salo on 2026-05-07. This block layers a
- Linear-style refinement on top of the working panel: hairline
- borders, dense type, monospaced numerics, very subtle
- elevation, and a unified "chip" language across every header.
- Lives at the END of the style block so it wins specificity.
- NO class renames — every existing JS handler still finds its
- targets.
-
- Per Salo's feedback: workflow tabs are repositioned to the
- top-left of the form-pane (instead of full-width centered),
- which keeps the existing user habit but reads cleaner. */
-
- :root {
- --ph-bg: #00061a;
- --ph-elev-1: #0c1330;
- --ph-elev-2: #141a3a;
- --ph-border-soft: rgba(140, 160, 220, 0.08);
- --ph-border-strong: rgba(140, 160, 220, 0.16);
- --ph-text-faint: #5b6478;
- /* Wordmark gradient — sampled from the SVG logo's three concentric
- rings (#FF2E9F inner, #B14AFF middle, #5EEAFF outer). The middle
- purple stop bridges pink → cyan; the old "magenta" was another
- pink which made the gradient look muddy when scaled up. */
- --ph-grad-pink: #FF2E9F;
- --ph-grad-purple: #B14AFF;
- --ph-grad-magenta: #B14AFF; /* alias for backward compat */
- --ph-grad-cyan: #5EEAFF;
- --ph-font-mono: "SF Mono", "JetBrains Mono", ui-monospace, Menlo, monospace;
- }
-
- /* Subtle radial wash above the void so the dark navy lifts at the
- top — matches the Linear artboard. */
- body {
- background: var(--ph-bg);
- background-image: radial-gradient(ellipse 1200px 600px at 50% -10%, rgba(47,129,247,0.06), transparent 60%);
- font-size: 13px;
- }
-
- /* === TOP HEADER ============================================
- 88px tall (was 62) — Salo flagged the chrome was reading too
- small and the brand was getting lost. Logo bumped 48 → 64,
- wordmark 22 → 28, plus a soft halo glow behind the mark so it
- lifts off the void. Second-round bump (2026-05-12) to chrome
- chips: pills 28 → 34, icon-btn 26 → 34, "by Bizarro" 24 → 34
- — everything else needed to scale with the bigger brand. */
- body > header {
- height: 88px;
- flex: 0 0 auto;
- padding: 0 22px;
- gap: 14px;
- flex-wrap: nowrap;
- align-items: center;
- border-bottom: 1px solid var(--ph-border-soft);
- background: rgba(0, 6, 26, 0.6);
- backdrop-filter: blur(12px);
- -webkit-backdrop-filter: blur(12px);
- overflow: hidden;
- }
- body > header .brand {
- display: inline-flex;
- align-items: center;
- gap: 12px;
- flex-shrink: 0;
- text-decoration: none;
- }
- body > header .brand img {
- /* Phosphene brand mark — concentric radiating dashes that go
- pink → magenta → cyan around a yellow core, on transparent
- background. Provided by Salo (`phospene logo.png` 1254×1254
- RGBA). Glow re-enabled 2026-05-12 — a soft brand-pink halo
- that lifts the mark off the navy void without muddying the
- dashes (uses drop-shadow filter so transparent regions stay
- transparent). */
- content: url('/assets/phosphene_brand.png');
- height: 64px;
- width: 64px;
- display: block;
- filter:
- drop-shadow(0 0 14px rgba(255, 95, 168, 0.55))
- drop-shadow(0 0 6px rgba(79, 214, 255, 0.35));
- }
- body > header .brand::after {
- content: 'Phosphene';
- /* Perceptual gradient: pink → cyan through OKLCh color space. RGB
- interpolation produces muddy brown/grey mid-tones at large sizes;
- OKLCh stays on the saturated hue ring (pink → magenta → purple →
- blue-purple → cyan), which is what reads as a "real" gradient.
- 5-stop fallback for older browsers; modern ones (Safari 16.4+,
- Chrome 111+) use the in-oklch override below. */
- background: linear-gradient(92deg,
- #FF2E9F 0%,
- #E135C2 25%,
- #B14AFF 50%,
- #7777FF 75%,
- #5EEAFF 100%);
- background: linear-gradient(in oklch 92deg, #FF2E9F, #5EEAFF);
- -webkit-background-clip: text;
- background-clip: text;
- color: transparent;
- font-weight: 700;
- font-size: 44px;
- letter-spacing: -0.02em;
- /* Halo glow matching the gradient endpoints. */
- text-shadow:
- 0 0 24px rgba(255, 46, 159, 0.32),
- 0 0 10px rgba(94, 234, 255, 0.22);
- }
- /* Hide the existing version-badge styling and re-render it Linear-style
- (mono "v2.0" in a chip). Keep the element so the JS doesn't break. */
- body > header .version-badge {
- margin: 0;
- padding: 5px 10px;
- font-size: 13px;
- font-family: var(--ph-font-mono);
- color: var(--muted);
- background: rgba(140, 160, 220, 0.06);
- border: 1px solid var(--ph-border-soft);
- border-radius: 7px;
- letter-spacing: 0.02em;
- font-weight: 500;
- text-transform: none;
- }
- body > header .profile-badge {
- margin: 0 0 0 4px;
- padding: 5px 10px;
- font-size: 12px;
- font-family: var(--ph-font-mono);
- letter-spacing: 0.08em;
- font-weight: 600;
- border-radius: 7px;
- }
- body > header .spacer { flex: 1 1 auto; }
-
- /* Unified chip language for every header pill — Tier, RAM, Helper,
- Models, Queue, current job, version, etc. */
- body > header > .pill {
- display: inline-flex;
- align-items: center;
- gap: 8px;
- height: 34px;
- padding: 0 14px;
- border-radius: 8px;
- background: rgba(140, 160, 220, 0.04);
- border: 1px solid var(--ph-border-soft);
- color: var(--muted);
- font-size: 13.5px;
- font-weight: 500;
- font-variant-numeric: tabular-nums;
- white-space: nowrap;
- transition: border-color var(--t-base), color var(--t-base);
- }
- body > header > .pill:hover {
- border-color: var(--ph-border-strong);
- color: var(--text);
- }
- body > header > .pill .dot {
- width: 7px; height: 7px;
- border-radius: 999px;
- margin-right: 0;
- box-shadow: none;
- }
- body > header > .pill-good { color: var(--success); border-color: rgba(63,185,80,0.30); }
- body > header > .pill-good .dot { background: var(--success); box-shadow: 0 0 8px var(--success); }
- body > header > .pill-warn { color: var(--warning); border-color: rgba(210,153,34,0.35); }
- body > header > .pill-danger { color: var(--danger); border-color: rgba(248,81,73,0.35); }
- body > header > .pill-running {
- color: var(--accent-bright);
- border-color: rgba(47,129,247,0.30);
- background: rgba(47,129,247,0.06);
- animation: pulse 1.6s ease-in-out infinite;
- }
- body > header > .pill-current { color: var(--success); border-color: rgba(63,185,80,0.25); }
- body > header > .pill-update { color: var(--warning); border-color: rgba(240,185,64,0.40); background: rgba(240,185,64,0.06); }
- body > header > .pill-restart { color: var(--accent-bright); border-color: rgba(126,152,255,0.40); background: rgba(126,152,255,0.06); }
-
- /* Settings cog — same height as chips, ghost styling. */
- body > header #settingsBtn,
- body > header .icon-btn {
- width: 34px; height: 34px;
- padding: 0;
- border: none;
- background: transparent;
- color: var(--muted);
- border-radius: 7px;
- display: inline-flex;
- align-items: center; justify-content: center;
- cursor: pointer;
- transition: color var(--t-base), background var(--t-base);
- }
- body > header #settingsBtn:hover,
- body > header .icon-btn:hover {
- color: var(--text);
- background: rgba(140, 160, 220, 0.06);
- }
- /* Force the inline-sized SVGs (16×16) to scale up so the icons
- look proportionate inside the larger 34×34 button. */
- body > header #settingsBtn svg,
- body > header .icon-btn svg {
- width: 20px; height: 20px;
- }
- /* Bug button — neon-pulsing accent so it reads as "interactive" and
- discoverable. Uses an HSL accent (cyan-leaning) that's distinct from
- the danger / warning / success colors already in use elsewhere. The
- pulse is subtle enough to live in the header without being loud. */
- body > header #bugBtn.bug-btn {
- color: #5fc8ff;
- animation: bug-neon 2.4s ease-in-out infinite;
- filter: drop-shadow(0 0 4px rgba(95, 200, 255, 0.45));
- }
- body > header #bugBtn.bug-btn:hover {
- color: #88dcff;
- background: rgba(95, 200, 255, 0.10);
- filter: drop-shadow(0 0 8px rgba(95, 200, 255, 0.85));
- animation-duration: 1.2s;
- }
- @keyframes bug-neon {
- 0%, 100% {
- filter: drop-shadow(0 0 3px rgba(95, 200, 255, 0.30));
- opacity: 0.75;
- }
- 50% {
- filter: drop-shadow(0 0 9px rgba(95, 200, 255, 0.85));
- opacity: 1;
- }
- }
- @media (prefers-reduced-motion: reduce) {
- body > header #bugBtn.bug-btn { animation: none; }
- }
- body > header #stopComfyBtn {
- height: 24px; padding: 0 10px;
- font-size: 11px; font-weight: 500;
- border-radius: 6px;
- width: auto; flex: 0 0 auto;
- }
- /* Creator chip — square avatar, mono "by Bizarro" label, no underline. */
- body > header .creator-link {
- display: inline-flex;
- align-items: center;
- gap: 8px;
- height: 34px;
- padding: 0 12px 0 4px;
- border-radius: 8px;
- background: rgba(140, 160, 220, 0.04);
- border: 1px solid var(--ph-border-soft);
- color: var(--muted);
- font-size: 13px;
- font-weight: 500;
- text-decoration: none;
- transition: border-color var(--t-base), color var(--t-base);
- }
- body > header .creator-link:hover { color: var(--text); border-color: var(--ph-border-strong); }
- body > header .creator-link .creator-avatar,
- body > header .creator-link img {
- width: 26px; height: 26px;
- border-radius: 6px;
- object-fit: cover;
- flex-shrink: 0;
- }
- body > header .creator-link .x-icon {
- font-size: 11px;
- color: var(--ph-text-faint);
- letter-spacing: 0.04em;
- }
- body > header .creator-link .x-icon svg {
- width: 12px; height: 12px;
- }
-
- /* === MAIN LAYOUT ===========================================
- Hairline-bordered panes, no internal radius — Linear's edge
- feel is "everything is one continuous surface".
- The form-pane min width is bumped from 440 → 580 to match
- the new composer-led redesign (which packs prompt + refs
- + 4-up quality strip + 3-up dur/frames/seed + sticky
- footer into the left pane). The stage cap on the right
- still keeps the player from letterboxing into empty side
- bars. Without this rule the two `main.layout` blocks
- (this one + the one in the global section above) raced
- and the more-specific selector here won, leaving the
- form-pane stuck at 440 even after the redesign's wider
- intent. */
- main.layout {
- gap: 0;
- padding: 0;
- grid-template-columns: minmax(580px, 1fr) minmax(0, calc((100vh - 220px) * 16 / 9));
- }
- .form-pane,
- .stage-pane,
- .agent-stage-pane {
- background: transparent;
- border: none;
- border-right: 1px solid var(--ph-border-soft);
- border-radius: 0;
- }
- .stage-pane,
- .agent-stage-pane { border-right: none; }
- /* No padding-bottom on form-pane: per CSS spec, sticky bottom:0
- pins to the PADDING-BOX bottom of the scroll container, so
- padding-bottom would lift the footer's pin position by exactly
- that amount and leave content (LoRAs / Customize / Quality)
- rendered BELOW the footer in viewport. The breathing room
- above the sticky footer comes from the footer's own
- margin-top:16px instead. */
- .form-pane { padding: 0; }
- body[data-workflow="agent"] main.layout {
- grid-template-columns: minmax(560px, 1fr) minmax(420px, 460px);
- }
- /* Agent workflow doesn't have the sticky footer — drop the
- reserved space so the chat composer sits flush at the bottom. */
- body[data-workflow="agent"] .form-pane { padding-bottom: 0; }
-
- /* === WORKFLOW TABS =========================================
- Salo asked for these to be moved away from the centered top
- slot. Now they live at the top-left of the form-pane as a
- small segmented control — same place users have always seen
- them, just visually re-tuned. */
- .workflow-tabs {
- display: inline-flex;
- gap: 0;
- padding: 2px;
- margin: 14px 0 18px 18px;
- background: rgba(140, 160, 220, 0.04);
- border: 1px solid var(--ph-border-soft);
- border-radius: 7px;
- width: auto;
- max-width: max-content;
- }
- .workflow-tabs button {
- /* Override the global `button { width: 100% }` rule. Without
- width:auto each tab stretches to fill the form-pane width, so
- Manual + Agentic Flows + Train all rendered at ~306px each and
- the latter two overflowed the visible nav pill off-screen —
- that's why Salo saw Train as "hidden" unless he switched to
- Agentic Flows. */
- width: auto;
- flex: 0 0 auto;
- padding: 5px 14px;
- font-size: 12px; font-weight: 500;
- letter-spacing: 0;
- background: transparent;
- color: var(--muted);
- border: none;
- border-radius: 5px;
- box-shadow: none;
- transition: background var(--t-base), color var(--t-base);
- }
- .workflow-tabs button:hover {
- background: rgba(140, 160, 220, 0.06);
- color: var(--text);
- }
- .workflow-tabs button.active {
- background: rgba(47, 129, 247, 0.14);
- color: var(--accent-bright);
- box-shadow: inset 0 0 0 1px rgba(47, 129, 247, 0.22);
- border: none;
- }
- .workflow-tabs .new-badge {
- margin-left: 6px;
- padding: 1px 5px;
- font-size: 9px; font-weight: 600;
- font-family: var(--ph-font-mono);
- letter-spacing: 0.06em;
- background: rgba(47, 129, 247, 0.12);
- color: var(--accent-bright);
- border: 1px solid rgba(47, 129, 247, 0.24);
- border-radius: 3px;
- vertical-align: baseline;
- }
-
- /* === FORM PANE INNER ===
- Contents inside the form (other than workflow tabs and the agent
- pane) get padding, but the workflow tabs themselves now hug the
- top-left corner, set by their own margin above. */
- .form-pane > #genForm { padding: 0 18px; }
- .form-pane > #modelsInline { margin: 0 18px 14px; }
- /* h2 section labels — mono uppercase, Linear's signature. */
- #genForm h2 {
- font-size: 10.5px;
- font-family: var(--ph-font-mono);
- letter-spacing: 0.08em;
- color: var(--ph-text-faint);
- text-transform: uppercase;
- margin: 22px 0 8px;
- font-weight: 500;
- }
- #genForm h2:first-of-type { margin-top: 0; }
-
- /* Mode + Quality pickers as Linear's grouped panel: a subtle inset
- container with hairline border, then 4 buttons inside. */
- .pill-group.cols-2,
- .pill-group.cols-4 {
- gap: 6px;
- padding: 3px;
- background: rgba(140, 160, 220, 0.04);
- border: 1px solid var(--ph-border-soft);
- border-radius: 8px;
- }
- .pill-btn {
- padding: 8px 10px;
- background: transparent;
- border: none;
- color: var(--muted);
- box-shadow: none;
- border-radius: 6px;
- transition: background var(--t-base), color var(--t-base);
- }
- .pill-btn:hover {
- background: rgba(140, 160, 220, 0.05);
- color: var(--text);
- border: none;
- }
- .pill-btn.active {
- background: rgba(47, 129, 247, 0.14);
- color: var(--accent-bright);
- box-shadow: inset 0 0 0 1px rgba(47, 129, 247, 0.22);
- border: none;
- }
- .pill-btn .sub {
- font-size: 10.5px;
- font-family: var(--ph-font-mono);
- color: var(--ph-text-faint);
- letter-spacing: 0;
- }
- .pill-btn.active .sub { color: var(--accent-bright); opacity: 0.8; }
-
- /* Quality cards — 2x2 with looser padding + RECOMMENDED badge style.
- Override the .pill-group inset bg so each card reads as standalone. */
- .pill-group.cols-2.quality-row {
- padding: 0;
- background: transparent;
- border: none;
- gap: 8px;
- }
- .pill-quality {
- padding: 10px 12px !important;
- align-items: flex-start !important;
- text-align: left !important;
- min-height: 76px;
- background: rgba(20, 26, 58, 0.4) !important;
- border: 1px solid var(--ph-border-soft) !important;
- border-radius: 8px !important;
- box-shadow: none !important;
- position: relative;
- }
- .pill-quality:hover { background: rgba(20, 26, 58, 0.6) !important; border-color: var(--ph-border-strong) !important; }
- .pill-quality.active {
- background: rgba(47, 129, 247, 0.06) !important;
- border-color: rgba(47, 129, 247, 0.45) !important;
- box-shadow: inset 0 0 0 1px rgba(47, 129, 247, 0.18) !important;
- }
- .pill-quality.active::after {
- content: 'RECOMMENDED';
- position: absolute;
- top: 9px; right: 10px;
- font-size: 9px;
- font-family: var(--ph-font-mono);
- font-weight: 600;
- padding: 2px 6px;
- border-radius: 4px;
- background: rgba(47, 129, 247, 0.16);
- color: var(--accent-bright);
- letter-spacing: 0.06em;
- }
- /* The RECOMMENDED badge above is sized for the legacy 4-up Quality
- row that gave each chip plenty of headroom. The redesign's
- compact `.quality-strip .q-chip` chips don't have room for an
- inline badge — without this override the badge crams onto the
- same line as the chip label, producing a "BalancedRECOMMENDED"
- overlap that reads as a font glitch. Hide it inside the new
- strip; the active state is already announced by background +
- border + accent text. */
- .quality-strip .pill-quality.active::after { content: none; }
- .pill-quality .ql-name { font-size: 13px; font-weight: 600; color: var(--text); }
- .pill-quality.active .ql-name { color: var(--text); }
- .pill-quality .ql-spec {
- font-size: 11px;
- font-family: var(--ph-font-mono);
- color: var(--muted);
- }
- .pill-quality .ql-tier {
- font-size: 9.5px;
- font-family: var(--ph-font-mono);
- color: var(--ph-text-faint);
- margin-top: 6px;
- }
-
- /* Prompt + Avoid textareas — denser, hairline border, monospaced
- placeholder hint. */
- #genForm textarea,
- #genForm input[type="text"],
- #genForm input[type="number"],
- #genForm select {
- background: rgba(12, 19, 48, 0.5);
- border: 1px solid var(--ph-border-soft);
- border-radius: 8px;
- padding: 10px 12px;
- font-size: 13px;
- }
- #genForm textarea:focus,
- #genForm input:focus,
- #genForm select:focus {
- border-color: var(--accent);
- background: rgba(12, 19, 48, 0.7);
- box-shadow: 0 0 0 3px rgba(47, 129, 247, 0.18);
- }
-
- /* Inline buttons (Enhance / HDR / No-music) styled as Linear ghost pills */
- .row-actions .ghost-btn,
- .toggle-pill {
- display: inline-flex;
- align-items: center;
- gap: 6px;
- padding: 6px 10px;
- border-radius: 6px;
- border: 1px solid var(--ph-border-soft);
- background: transparent;
- color: var(--muted);
- font-size: 12px;
- width: auto;
- cursor: pointer;
- transition: border-color var(--t-base), color var(--t-base), background var(--t-base);
- }
- .row-actions .ghost-btn:hover,
- .toggle-pill:hover {
- border-color: var(--ph-border-strong);
- color: var(--text);
- }
- .toggle-pill.is-on {
- border-color: rgba(47, 129, 247, 0.28);
- background: var(--accent-dim);
- color: var(--accent-bright);
- }
-
- /* Generate / Stop primary action — Linear blue with subtle blue
- glow. */
- button.primary,
- #genBtn,
- button[type="submit"].primary {
- padding: 10px 14px;
- font-size: 13px; font-weight: 600;
- border-radius: 6px;
- background: var(--accent);
- border-color: var(--accent);
- box-shadow: 0 4px 14px rgba(47, 129, 247, 0.25);
- }
- button.primary:hover { background: var(--accent-bright); }
- .actions { gap: 8px; margin-top: 18px; }
-
- /* === STAGE / PLAYER PANE (Manual mode) =====================
- Y2.001 — the legacy Linear-style overrides that lived here are
- removed; the redesigned stage block above (search "STAGE
- (PLAYER + CAROUSEL) — REDESIGN Y2.001") is the source of truth
- and uses the canonical token set instead of the older --ph-*
- aliases. The selectors are intentionally left blank so any
- future regression diff stays small. */
-
- /* === AGENT PANE (Agentic Flows) ============================ */
- .agent-pane {
- background: transparent;
- border: none;
- border-radius: 0;
- }
- .agent-pane > .agent-header {
- /* Single-row chip strip — was collapsing/overlapping when the
- engine pill carried a long label ("Gemma 3 12B · 7.5 GB ·
- click to start") because flex-wrap defaulted to wrap and
- children had no min-width:0, so they bled into the next row
- underneath the banner. min-height (not height) lets the row
- honour the 40px target without clipping when a chip happens
- to be a hair taller; flex-wrap:nowrap + flex-shrink on the
- engine pill keeps everything on one line and lets the long
- engine label ellipsis instead of pushing siblings down. */
- min-height: 40px;
- padding: 0 14px;
- gap: 8px;
- background: transparent;
- border-bottom: 1px solid var(--ph-border-soft);
- flex-wrap: nowrap;
- overflow: hidden;
- }
- .agent-pane > .agent-header > * { flex-shrink: 0; }
- .agent-pane > .agent-header > .engine-pill {
- flex: 0 1 auto;
- min-width: 0;
- }
- .agent-pane > .agent-header > .engine-pill > #agentEngineLabel {
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
- min-width: 0;
- }
- .agent-pane > .agent-header > .session-title { flex-shrink: 1; }
- /* Sessions trigger — chip-style, mono "0" count */
- .agent-header .asp-trigger {
- display: inline-flex;
- align-items: center;
- gap: 6px;
- height: 24px;
- padding: 0 9px;
- background: rgba(140, 160, 220, 0.04);
- border: 1px solid var(--ph-border-soft);
- border-radius: 6px;
- color: var(--muted);
- font-size: 12px; font-weight: 500;
- width: auto; flex: 0 0 auto;
- cursor: pointer;
- transition: border-color var(--t-base), color var(--t-base);
- }
- .agent-header .asp-trigger:hover { border-color: var(--ph-border-strong); color: var(--text); }
- .agent-header .asp-trigger-count {
- font-family: var(--ph-font-mono);
- font-size: 10.5px;
- color: var(--ph-text-faint);
- }
- /* Engine pill / mode pill / RAM chip — all unified to chip language */
- .agent-header .engine-pill {
- height: 24px;
- padding: 0 9px;
- background: rgba(140, 160, 220, 0.04);
- border: 1px solid var(--ph-border-soft);
- border-radius: 6px;
- color: var(--text);
- font-size: 12px;
- font-family: var(--ph-font-mono);
- }
- .agent-header .engine-pill .dot {
- width: 6px; height: 6px;
- box-shadow: none;
- }
- .agent-header .engine-pill .dot.live {
- background: var(--success);
- box-shadow: 0 0 8px var(--success);
- }
- .agent-header .agent-mode-pill {
- height: 24px;
- padding: 0 9px;
- background: rgba(140, 160, 220, 0.04);
- border: 1px solid var(--ph-border-soft);
- border-radius: 6px;
- color: var(--muted);
- font-size: 12px;
- font-weight: 500;
- }
- .agent-header .agent-mode-pill.is-interactive {
- background: rgba(47, 129, 247, 0.10);
- border-color: rgba(47, 129, 247, 0.22);
- color: var(--accent-bright);
- }
- .agent-header .agent-engine-stop {
- height: 24px;
- padding: 0 9px;
- border: 1px solid var(--ph-border-soft);
- border-radius: 6px;
- font-size: 12px;
- background: transparent;
- color: var(--muted);
- }
- .agent-header .agent-engine-stop:hover {
- color: var(--danger);
- border-color: rgba(248, 81, 73, 0.30);
- background: rgba(248, 81, 73, 0.06);
- }
- .agent-header .agent-ram-chip {
- height: 24px;
- padding: 0 9px;
- background: rgba(140, 160, 220, 0.04);
- border: 1px solid var(--ph-border-soft);
- border-radius: 6px;
- font-size: 12px;
- font-family: var(--ph-font-mono);
- }
- .agent-header .agent-ram-chip .agent-ram-dot {
- width: 6px; height: 6px;
- box-shadow: none;
- }
- .agent-header .session-title {
- font-size: 13px;
- font-weight: 500;
- padding-left: 8px;
- text-align: right;
- }
- .agent-header .icon-btn {
- width: 26px; height: 26px;
- border: none;
- background: transparent;
- border-radius: 6px;
- color: var(--muted);
- }
- .agent-header .icon-btn:hover {
- color: var(--text);
- background: rgba(140, 160, 220, 0.06);
- border: none;
- }
-
- /* === CHAT THREAD ===========================================
- Tighter padding, smaller bubbles, the user bubble is a soft
- blue tint with hairline border — the assistant stays naked
- on the void. Flex-column on the chat so user rows can
- right-align with align-self. */
- .agent-chat {
- padding: 20px 24px 16px;
- display: flex;
- flex-direction: column;
- gap: 0;
- }
- .agent-msg-row { margin-bottom: 16px; gap: 10px; max-width: 92%; }
- .agent-msg-row.user {
- align-self: flex-end;
- flex-direction: row-reverse;
- max-width: 75%;
- }
- .agent-msg-row.user .agent-msg-body { flex: 0 1 auto; min-width: 0; }
- .agent-msg-row.user .agent-msg-name { display: none; }
- .agent-avatar {
- width: 22px; height: 22px;
- border-radius: 6px;
- font-size: 10px;
- border: 1px solid var(--ph-border-soft);
- background: var(--ph-elev-2);
- }
- .agent-avatar.user {
- background: linear-gradient(135deg, var(--ph-grad-magenta), var(--ph-grad-cyan));
- color: var(--ph-bg);
- border: none;
- }
- .agent-msg-row.user .agent-msg-content {
- background: rgba(47, 129, 247, 0.12);
- border: 1px solid rgba(47, 129, 247, 0.22);
- border-radius: 10px;
- padding: 8px 12px;
- font-size: 13px;
- }
- .agent-msg-content { font-size: 13px; line-height: 1.55; }
-
- /* Tool result inline cards — quieter than prose */
- .agent-tool-card {
- margin-top: 8px;
- border: 1px solid var(--ph-border-soft);
- border-radius: 8px;
- background: rgba(20, 26, 58, 0.4);
- font-size: 12px;
- border-left: 1px solid var(--ph-border-soft);
- }
- .agent-tool-card.success { border-left-color: rgba(63, 185, 80, 0.45); }
- .agent-tool-card.error { border-left-color: rgba(248, 81, 73, 0.45); }
- .agent-tool-card.pending { border-left-color: rgba(47, 129, 247, 0.45); }
- .agent-tool-card .head {
- font-family: var(--ph-font-mono);
- font-size: 11px;
- color: var(--muted);
- padding: 6px 10px;
- background: rgba(140, 160, 220, 0.025);
- border-bottom: 1px solid var(--ph-border-soft);
- }
-
- /* === COMPOSER ==============================================
- Hairline-bordered card with paperclip + textarea + send.
- Batch-now bar above it uses the accent-blue ghost styling
- per Linear (replaces the green gradient). */
- .agent-composer {
- background: transparent;
- border-top: 1px solid var(--ph-border-soft);
- padding: 0 24px 16px;
- }
- .agent-batch-bar {
- height: 30px;
- padding: 0 10px;
- margin: 12px 0 8px;
- background: rgba(47, 129, 247, 0.10);
- border: 1px solid rgba(47, 129, 247, 0.24);
- border-radius: 7px;
- box-shadow: none;
- font-size: 12px;
- color: var(--accent-bright);
- }
- .agent-batch-bar-icon { color: var(--accent-bright); }
- .agent-batch-bar-text { color: var(--accent-bright); }
- .agent-batch-bar-btn {
- padding: 4px 10px;
- font-size: 11.5px;
- font-weight: 500;
- border-radius: 5px;
- background: var(--accent);
- color: white;
- }
- .agent-composer-wrap {
- border: 1px solid var(--ph-border-soft);
- border-radius: 10px;
- background: rgba(12, 19, 48, 0.6);
- padding: 4px 4px 4px 4px;
- }
- .agent-composer textarea {
- background: transparent;
- border: none;
- border-radius: 0;
- padding: 10px 56px 10px 50px;
- font-size: 13px;
- min-height: 44px;
- }
- .agent-composer textarea:focus { box-shadow: none; border: none; background: transparent; }
- .agent-composer .attach-btn {
- bottom: 4px; left: 4px;
- width: 30px; height: 30px;
- border-radius: 7px;
- }
- .agent-composer .send-btn,
- #agentSendBtn {
- width: 30px; height: 30px;
- border-radius: 7px;
- bottom: 4px; right: 4px;
- }
-
- /* === AGENT STAGE PANE ====================================== */
- .agent-stage-pane {
- background: transparent;
- border: none;
- border-radius: 0;
- border-left: 1px solid var(--ph-border-soft);
- }
- .agent-stage-head {
- height: 40px;
- padding: 0 18px;
- background: transparent;
- border-bottom: 1px solid var(--ph-border-soft);
- gap: 8px;
- }
- .agent-stage-head .label {
- font-size: 10.5px;
- font-family: var(--ph-font-mono);
- letter-spacing: 0.08em;
- color: var(--ph-text-faint);
- text-transform: uppercase;
- font-weight: 500;
- }
- .agent-stage-head .session-pill {
- font-family: var(--ph-font-mono);
- font-size: 11px;
- padding: 2px 8px;
- background: rgba(140, 160, 220, 0.04);
- border: 1px solid var(--ph-border-soft);
- border-radius: 6px;
- color: var(--muted);
- }
- .agent-stage-body {
- padding: 0;
- gap: 0;
- }
- .agent-stage-section {
- padding: 14px 18px;
- background: transparent;
- border: none;
- border-bottom: 1px solid var(--ph-border-soft);
- border-radius: 0;
- }
- .agent-stage-section:last-child { border-bottom: none; }
- .agent-stage-section h4 {
- font-size: 10.5px;
- font-family: var(--ph-font-mono);
- letter-spacing: 0.08em;
- color: var(--ph-text-faint);
- text-transform: uppercase;
- font-weight: 500;
- margin-bottom: 10px;
- }
- .agent-stage-section h4 .count {
- font-family: var(--ph-font-mono);
- font-size: 10px;
- padding: 1px 6px;
- background: rgba(47, 129, 247, 0.10);
- color: var(--accent-bright);
- border-radius: 4px;
- font-weight: 500;
- }
- .stage-now-card {
- padding: 0;
- border: 1px solid var(--ph-border-soft);
- border-radius: 8px;
- background: linear-gradient(180deg, #0a1130 0%, #050920 100%);
- aspect-ratio: 16/9;
- position: relative;
- overflow: hidden;
- }
- .stage-now-card.idle {
- aspect-ratio: auto;
- padding: 24px 14px;
- background: rgba(20, 26, 58, 0.4);
- color: var(--ph-text-faint);
- font-style: normal;
- font-size: 12px;
- font-family: var(--ph-font-mono);
- }
- .stage-progress-fill {
- box-shadow: none;
- background: var(--accent-bright);
- }
- .stage-progress-text {
- font-size: 11px;
- font-family: var(--ph-font-mono);
- }
- .stage-outputs {
- grid-template-columns: repeat(2, 1fr);
- gap: 10px;
- }
- .stage-output-cell {
- border: 1px solid var(--ph-border-soft);
- border-radius: 8px;
- background: rgba(20, 26, 58, 0.4);
- }
- .stage-output-cell:hover {
- border-color: var(--ph-border-strong);
- transform: none;
- }
- .stage-output-cell .label {
- font-family: var(--ph-font-mono);
- font-size: 10.5px;
- padding: 4px 6px;
- background: rgba(0, 0, 0, 0.5);
- }
-
- /* === BOTTOM PANEL ==========================================
- Y2.001 — the legacy --ph-* override block is removed. The
- redesigned bottom-pane block above (search "BOTTOM TABBED PANE
- — REDESIGN Y2.001") is the source of truth and uses the
- canonical token set. Selectors left blank to keep diffs clean. */
-
- /* === MODELS-INLINE CARD =================================== */
- .models-inline {
- background: rgba(20, 26, 58, 0.4);
- border: 1px solid var(--ph-border-soft);
- border-radius: 10px;
- }
-
- /* === LoRAs section + Customize disclosure ================== */
- .form-divider {
- border-top: 1px solid var(--ph-border-soft);
- margin: 18px 0;
- }
- .loras-section, .customize-section {
- border: 1px solid var(--ph-border-soft);
- border-radius: 8px;
- background: rgba(20, 26, 58, 0.25);
- }
-
- /* === Sub-header strip BELOW the workflow tabs (Manual mode)
- — empty intentionally; the workflow tabs already act as the
- leading row, the form sections start right under them. */
-
- /* === FALLBACK: Hide unwanted inline icons in version pill === */
- body > header > .pill svg { width: 12px; height: 12px; }
-
- /* ============================================================
- AGENTIC FLOWS — CHAT REDESIGN Y2.002
- ============================================================
- Bold-pass overhaul of the agent chat surface to match the
- composer-led form-pane (Y1.0) and stage-pane (Y2.001) idiom.
- This block is the SOURCE OF TRUTH for chat chrome — it sits
- AFTER all earlier .agent-* rules, so it wins by cascade. The
- legacy rules above are intentionally left in place so we can
- diff-revert any specific surface if a regression appears.
-
- What changed:
- 1. Composer = elevated hero card, accent ring on focus,
- 38px circle send button, contextual hint strip below
- (no more negative-bottom absolute hint).
- 2. Header = single chip strip, condensed action cluster,
- engine pill carries inline state instead of a banner.
- 3. Empty state = centered hero with prompt suggestion grid.
- 4. Tool cards = polished, status badge, mono chips, hover
- tint, expand chevron rotation, duration meta.
- 5. Message rows = comfortable reading column, hover-revealed
- assistant meta (timestamp + copy).
- 6. Stage pane = elevated cards, refined activity feed,
- outputs gallery with hover lift.
- 7. Streaming indicator = inline 3-dot pulse for assistant.
- 8. Turn summary = polished mono chip with count badges.
- ============================================================ */
-
- /* ---- 1. Pane wrapper — make the chat dominate the form-pane.
- Drop the 60vh cap so the chat fills available height in regular
- mode (it's already the only content in the agent workflow). */
- body[data-workflow="agent"] .agent-pane {
- flex: 1 1 auto;
- min-height: 0;
- display: flex;
- flex-direction: column;
- background: transparent;
- border: none;
- border-radius: 0;
- padding-top: 0;
- }
- body[data-workflow="agent"] .agent-pane .agent-chat-wrap {
- flex: 1 1 auto;
- min-height: 0;
- max-height: none; /* override the legacy 60vh cap */
- }
- body[data-workflow="agent"] aside.form-pane {
- display: flex;
- flex-direction: column;
- min-height: 0;
- }
-
- /* ---- 2. Header — condense + polish.
- Elevated hairline strip, the engine pill is the primary
- state surface (no separate banner needed for "engine off"),
- action icons grouped into a polished cluster on the right. */
- .agent-pane > .agent-header {
- min-height: 48px;
- padding: 0 18px;
- gap: 8px;
- background: linear-gradient(180deg, rgba(140,160,220,0.025), transparent);
- border-bottom: 1px solid var(--ph-border-soft);
- }
- /* Sessions trigger — slightly more comfortable hit target */
- .agent-header .asp-trigger {
- height: 28px;
- padding: 0 11px;
- font-size: 12px;
- font-weight: 500;
- border-radius: var(--r-sm);
- background: rgba(140, 160, 220, 0.05);
- transition: var(--t-fast);
- }
- .agent-header .asp-trigger:hover {
- border-color: var(--accent);
- color: var(--accent-bright);
- background: rgba(47, 129, 247, 0.08);
- }
- .agent-header .asp-trigger svg { opacity: 0.85; }
- .agent-header .asp-trigger-count {
- padding: 1px 6px;
- background: rgba(47,129,247,0.15);
- color: var(--accent-bright);
- border-radius: var(--r-pill);
- font-size: 10px; font-weight: 600;
- font-family: var(--ph-font-mono);
- }
- /* Engine pill — primary state. When off, carries a contextual
- "Click to start" copy + warning glow. When live, shows model
- name with green glow. */
- .agent-header .engine-pill {
- height: 28px;
- padding: 0 11px;
- gap: 7px;
- font-family: inherit;
- font-size: 12px;
- font-weight: 500;
- background: rgba(140, 160, 220, 0.05);
- border: 1px solid var(--ph-border-soft);
- border-radius: var(--r-sm);
- color: var(--text);
- transition: var(--t-fast);
- max-width: 360px;
- }
- .agent-header .engine-pill:hover {
- border-color: var(--accent);
- background: rgba(47, 129, 247, 0.08);
- }
- .agent-header .engine-pill .dot {
- width: 7px; height: 7px;
- background: var(--muted);
- box-shadow: none;
- transition: var(--t-base);
- }
- .agent-header .engine-pill .dot.live {
- background: var(--success);
- box-shadow: 0 0 0 3px rgba(63,185,80,0.18),
- 0 0 8px rgba(63,185,80,0.45);
- animation: agent-engine-live 2.4s ease-in-out infinite;
- }
- @keyframes agent-engine-live {
- 0%, 100% { box-shadow: 0 0 0 3px rgba(63,185,80,0.18), 0 0 8px rgba(63,185,80,0.45); }
- 50% { box-shadow: 0 0 0 5px rgba(63,185,80,0.06), 0 0 14px rgba(63,185,80,0.65); }
- }
- .agent-header .engine-pill .dot.warn { background: var(--warning); }
- .agent-header .engine-pill .dot.bad { background: var(--danger); }
- /* Mode pill — same chip language */
- .agent-header .agent-mode-pill {
- height: 28px;
- padding: 0 11px;
- gap: 6px;
- font-size: 12px;
- font-weight: 500;
- background: rgba(140, 160, 220, 0.05);
- border-radius: var(--r-sm);
- transition: var(--t-fast);
- }
- .agent-header .agent-mode-pill:hover {
- border-color: var(--accent);
- color: var(--accent-bright);
- background: rgba(47, 129, 247, 0.08);
- }
- .agent-header .agent-mode-pill.is-interactive {
- background: rgba(47, 129, 247, 0.14);
- border-color: rgba(47, 129, 247, 0.32);
- color: var(--accent-bright);
- }
- /* Stop engine — quieter danger affordance */
- .agent-header .agent-engine-stop {
- height: 28px;
- padding: 0 11px;
- gap: 6px;
- font-size: 12px;
- font-weight: 500;
- border-radius: var(--r-sm);
- background: transparent;
- transition: var(--t-fast);
- }
- .agent-header .agent-engine-stop:hover {
- color: var(--danger);
- border-color: rgba(248, 81, 73, 0.40);
- background: rgba(248, 81, 73, 0.08);
- }
- /* RAM chip */
- .agent-header .agent-ram-chip {
- height: 28px;
- padding: 0 11px;
- gap: 6px;
- font-size: 12px;
- font-weight: 500;
- background: rgba(140, 160, 220, 0.05);
- border-radius: var(--r-sm);
- font-family: var(--ph-font-mono);
- }
- .agent-header .agent-ram-chip .agent-ram-dot {
- width: 7px; height: 7px;
- box-shadow: none;
- }
- .agent-header .agent-ram-chip.is-roomy .agent-ram-dot {
- background: var(--success);
- box-shadow: 0 0 0 2px rgba(63,185,80,0.20);
- }
- .agent-header .agent-ram-chip.is-tight .agent-ram-dot {
- background: var(--warning);
- box-shadow: 0 0 0 2px rgba(210,153,34,0.20);
- }
- .agent-header .agent-ram-chip.is-bad .agent-ram-dot {
- background: var(--danger);
- box-shadow: 0 0 0 2px rgba(248,81,73,0.22);
- animation: agent-engine-live 1.6s ease-in-out infinite;
- }
- /* Session title — quieter, stays centered */
- .agent-header .session-title {
- font-size: 12.5px;
- font-weight: 500;
- color: var(--muted);
- letter-spacing: -0.005em;
- text-align: right;
- padding-left: 12px;
- }
- .agent-header .session-title .meta {
- font-size: 10.5px;
- color: var(--ph-text-faint);
- font-family: var(--ph-font-mono);
- margin-left: 6px;
- }
- /* Action icon cluster — group into a polished surface */
- .agent-header .icon-btn {
- width: 28px; height: 28px;
- background: transparent;
- border: 1px solid transparent;
- border-radius: var(--r-sm);
- color: var(--muted);
- transition: var(--t-fast);
- }
- .agent-header .icon-btn:hover {
- color: var(--accent-bright);
- background: rgba(47, 129, 247, 0.08);
- border-color: transparent;
- }
- .agent-header .icon-btn:focus-visible {
- outline: 2px solid var(--accent);
- outline-offset: 1px;
- }
-
- /* ---- 3. Engine readiness banner — polished, action-led */
- body[data-workflow="agent"] #agentEngineBanner {
- margin: 10px 18px 0 18px;
- padding: 10px 12px 10px 14px;
- border-radius: var(--r-md);
- box-shadow: var(--shadow-1);
- background: var(--panel);
- }
- body[data-workflow="agent"] #agentEngineBanner.warn {
- background: linear-gradient(180deg, rgba(210,153,34,0.10), rgba(210,153,34,0.04));
- border-color: rgba(210, 153, 34, 0.40);
- }
- body[data-workflow="agent"] #agentEngineBanner.err {
- background: linear-gradient(180deg, rgba(248,81,73,0.10), rgba(248,81,73,0.04));
- border-color: rgba(248,81,73, 0.40);
- }
- body[data-workflow="agent"] #agentEngineBanner.ok {
- background: linear-gradient(180deg, rgba(63,185,80,0.10), rgba(63,185,80,0.04));
- border-color: rgba(63,185,80,0.32);
- }
- body[data-workflow="agent"] .agent-engine-banner-btn {
- padding: 5px 11px;
- border: 1px solid currentColor;
- border-radius: var(--r-sm);
- font-size: 11.5px;
- font-weight: 600;
- opacity: 0.95;
- transition: var(--t-fast);
- }
- body[data-workflow="agent"] .agent-engine-banner-btn:hover {
- opacity: 1;
- background: rgba(255,255,255,0.08);
- transform: translateY(-1px);
- }
-
- /* ---- 4. Chat scroll surface — comfortable reading column */
- body[data-workflow="agent"] .agent-chat {
- padding: 24px 18px 12px;
- gap: 4px;
- scroll-padding-bottom: 80px;
- }
- body[data-workflow="agent"] .agent-chat::-webkit-scrollbar { width: 10px; }
- body[data-workflow="agent"] .agent-chat::-webkit-scrollbar-thumb {
- background: rgba(140,160,220,0.14);
- border: 2px solid transparent;
- background-clip: padding-box;
- border-radius: 6px;
- }
- body[data-workflow="agent"] .agent-chat::-webkit-scrollbar-thumb:hover {
- background: var(--accent);
- background-clip: padding-box;
- border: 2px solid transparent;
- }
-
- /* ---- 5. Message rows — claude.ai-grade typography, hover meta */
- body[data-workflow="agent"] .agent-msg-row {
- gap: 12px;
- margin-bottom: 18px;
- max-width: 100%;
- align-items: flex-start;
- animation: agent-msg-in 0.28s cubic-bezier(0.2, 0.8, 0.2, 1);
- }
- @keyframes agent-msg-in {
- from { opacity: 0; transform: translateY(4px); }
- to { opacity: 1; transform: translateY(0); }
- }
- body[data-workflow="agent"] .agent-msg-row.user {
- align-self: flex-end;
- max-width: 82%;
- flex-direction: row-reverse;
- }
- body[data-workflow="agent"] .agent-msg-row.assistant {
- max-width: 100%;
- }
-
- /* Avatars — bigger, more refined */
- body[data-workflow="agent"] .agent-avatar {
- width: 28px; height: 28px;
- border-radius: var(--r-sm);
- font-size: 11px;
- font-weight: 700;
- letter-spacing: 0.02em;
- flex-shrink: 0;
- box-shadow: var(--shadow-1);
- }
- body[data-workflow="agent"] .agent-avatar.claude {
- background: radial-gradient(circle at 35% 30%, #2d1a4f 0%, #0a0518 80%);
- border: 1px solid rgba(187, 89, 233, 0.30);
- padding: 3px;
- position: relative;
- overflow: hidden;
- }
- body[data-workflow="agent"] .agent-avatar.claude::before {
- content: '';
- display: block;
- width: 100%; height: 100%;
- background: url('/assets/favicon-64.png') center/contain no-repeat;
- }
- /* Pulse the assistant avatar when its row is the LAST one and the
- message is being streamed (.streaming). Subtle accent halo so
- users see "still thinking" at a glance. */
- body[data-workflow="agent"] .agent-msg-row.streaming .agent-avatar.claude {
- box-shadow: 0 0 0 0 rgba(187, 89, 233, 0.5);
- animation: agent-avatar-pulse 1.6s ease-in-out infinite;
- }
- @keyframes agent-avatar-pulse {
- 0%, 100% { box-shadow: 0 0 0 0 rgba(187, 89, 233, 0.45); }
- 50% { box-shadow: 0 0 0 6px rgba(187, 89, 233, 0.0); }
- }
- body[data-workflow="agent"] .agent-avatar.user {
- background: linear-gradient(135deg, #3a4a8a, #1d2752);
- color: var(--text);
- border: 1px solid var(--border-strong);
- }
-
- body[data-workflow="agent"] .agent-msg-body {
- flex: 1;
- min-width: 0;
- }
- body[data-workflow="agent"] .agent-msg-row.user .agent-msg-body {
- flex: 0 1 auto;
- }
-
- /* Message header — name + hover-revealed timestamp + copy. */
- body[data-workflow="agent"] .agent-msg-name {
- display: inline-flex;
- align-items: baseline;
- gap: 8px;
- font-size: 12px;
- font-weight: 600;
- color: var(--text);
- margin-bottom: 5px;
- letter-spacing: 0.01em;
- }
- body[data-workflow="agent"] .agent-msg-row.user .agent-msg-name { display: none; }
- body[data-workflow="agent"] .agent-msg-time {
- font-size: 10.5px;
- font-weight: 400;
- color: var(--ph-text-faint);
- font-family: var(--ph-font-mono);
- letter-spacing: 0;
- opacity: 0;
- transition: opacity var(--t-base);
- }
- body[data-workflow="agent"] .agent-msg-row:hover .agent-msg-time { opacity: 1; }
- body[data-workflow="agent"] .agent-msg-actions {
- display: inline-flex;
- gap: 4px;
- margin-left: auto;
- opacity: 0;
- transition: opacity var(--t-base);
- }
- body[data-workflow="agent"] .agent-msg-row:hover .agent-msg-actions { opacity: 1; }
- body[data-workflow="agent"] .agent-msg-action {
- width: 22px; height: 22px;
- border-radius: var(--r-xs);
- background: transparent;
- border: 1px solid transparent;
- color: var(--muted);
- display: inline-flex;
- align-items: center; justify-content: center;
- cursor: pointer;
- transition: var(--t-fast);
- padding: 0;
- }
- body[data-workflow="agent"] .agent-msg-action:hover {
- color: var(--accent-bright);
- background: rgba(47,129,247,0.10);
- }
- body[data-workflow="agent"] .agent-msg-action.copied {
- color: var(--success);
- }
-
- /* Message content — assistant stays naked (claude.ai pattern);
- user gets a soft accent-tinted bubble with the chat-app radius. */
- body[data-workflow="agent"] .agent-msg-content {
- font-size: 14px;
- line-height: 1.62;
- color: var(--text);
- }
- body[data-workflow="agent"] .agent-msg-row.user .agent-msg-content {
- background: linear-gradient(135deg,
- rgba(47, 129, 247, 0.16),
- rgba(47, 129, 247, 0.10));
- border: 1px solid rgba(47, 129, 247, 0.30);
- border-radius: var(--r-lg) var(--r-lg) var(--r-xs) var(--r-lg);
- padding: 10px 14px;
- box-shadow: var(--shadow-1);
- color: var(--text);
- }
-
- /* Streaming dot indicator — appears inline at end of assistant
- content while content is being streamed. */
- body[data-workflow="agent"] .agent-streaming-dots {
- display: inline-flex;
- gap: 4px;
- vertical-align: middle;
- margin-left: 4px;
- }
- body[data-workflow="agent"] .agent-streaming-dots span {
- width: 6px; height: 6px;
- border-radius: 50%;
- background: var(--accent-bright);
- opacity: 0.4;
- animation: agent-dot-bounce 1.2s ease-in-out infinite;
- }
- body[data-workflow="agent"] .agent-streaming-dots span:nth-child(2) {
- animation-delay: 0.2s;
- }
- body[data-workflow="agent"] .agent-streaming-dots span:nth-child(3) {
- animation-delay: 0.4s;
- }
- @keyframes agent-dot-bounce {
- 0%, 60%, 100% { opacity: 0.4; transform: translateY(0); }
- 30% { opacity: 1; transform: translateY(-3px); }
- }
-
- /* ---- 6. Markdown — polished IDE-grade code blocks. */
- body[data-workflow="agent"] .agent-md p { margin: 9px 0; }
- body[data-workflow="agent"] .agent-md code {
- font-family: var(--ph-font-mono);
- font-size: 0.88em;
- padding: 1.5px 6px;
- background: rgba(47,129,247,0.10);
- border: 1px solid rgba(47,129,247,0.20);
- border-radius: var(--r-xs);
- color: var(--accent-bright);
- letter-spacing: 0;
- }
- body[data-workflow="agent"] .agent-md pre {
- position: relative;
- background: linear-gradient(180deg, #0a1130 0%, #050920 100%);
- border: 1px solid var(--ph-border-strong);
- border-radius: var(--r-md);
- padding: 12px 14px;
- margin: 12px 0;
- overflow-x: auto;
- font-size: 12px;
- line-height: 1.55;
- box-shadow: var(--shadow-1);
- }
- body[data-workflow="agent"] .agent-md pre code {
- background: transparent;
- border: none;
- padding: 0;
- color: var(--text);
- font-size: inherit;
- }
- /* Per-pre copy button — opt-in via JS hooking into renderMessage. */
- body[data-workflow="agent"] .agent-md pre .agent-copy-pre {
- position: absolute;
- top: 7px; right: 7px;
- width: 26px; height: 26px;
- border-radius: var(--r-xs);
- background: rgba(20, 26, 58, 0.7);
- border: 1px solid var(--ph-border-soft);
- color: var(--muted);
- cursor: pointer;
- opacity: 0;
- display: inline-flex;
- align-items: center; justify-content: center;
- transition: var(--t-fast);
- backdrop-filter: blur(6px);
- }
- body[data-workflow="agent"] .agent-md pre:hover .agent-copy-pre { opacity: 1; }
- body[data-workflow="agent"] .agent-md pre .agent-copy-pre:hover {
- color: var(--accent-bright);
- border-color: var(--accent);
- }
- body[data-workflow="agent"] .agent-md pre .agent-copy-pre.copied {
- color: var(--success);
- border-color: rgba(63,185,80,0.45);
- }
- body[data-workflow="agent"] .agent-md blockquote {
- margin: 12px 0;
- padding: 8px 14px;
- border-left: 3px solid var(--accent);
- color: var(--muted);
- background: rgba(47, 129, 247, 0.06);
- border-radius: 0 var(--r-sm) var(--r-sm) 0;
- }
- body[data-workflow="agent"] .agent-md table {
- border-collapse: separate;
- border-spacing: 0;
- margin: 12px 0;
- font-size: 12.5px;
- border: 1px solid var(--ph-border-strong);
- border-radius: var(--r-sm);
- overflow: hidden;
- }
- body[data-workflow="agent"] .agent-md th,
- body[data-workflow="agent"] .agent-md td {
- border-bottom: 1px solid var(--ph-border-soft);
- border-right: 1px solid var(--ph-border-soft);
- padding: 8px 12px;
- }
- body[data-workflow="agent"] .agent-md th:last-child,
- body[data-workflow="agent"] .agent-md td:last-child { border-right: none; }
- body[data-workflow="agent"] .agent-md tr:last-child td { border-bottom: none; }
- body[data-workflow="agent"] .agent-md th {
- background: rgba(47, 129, 247, 0.08);
- font-weight: 600;
- text-align: left;
- color: var(--accent-bright);
- letter-spacing: 0.02em;
- }
-
- /* ---- 7. Tool cards — claude.ai-grade. */
- body[data-workflow="agent"] .agent-tool-card {
- margin: 8px 0;
- background: linear-gradient(180deg,
- rgba(140, 160, 220, 0.04),
- rgba(140, 160, 220, 0.02));
- border: 1px solid var(--ph-border-soft);
- border-left-width: 2px;
- border-radius: var(--r-sm);
- box-shadow: var(--shadow-1);
- transition: var(--t-base);
- overflow: hidden;
- }
- body[data-workflow="agent"] .agent-tool-card:hover {
- border-color: var(--ph-border-strong);
- background: linear-gradient(180deg,
- rgba(140, 160, 220, 0.06),
- rgba(140, 160, 220, 0.03));
- }
- body[data-workflow="agent"] .agent-tool-card.pending {
- border-left-color: var(--accent);
- animation: agent-tool-running 2.2s ease-in-out infinite;
- }
- @keyframes agent-tool-running {
- 0%, 100% { box-shadow: var(--shadow-1), 0 0 0 0 rgba(47,129,247,0.0); }
- 50% { box-shadow: var(--shadow-1), 0 0 0 1px rgba(47,129,247,0.18); }
- }
- body[data-workflow="agent"] .agent-tool-card.success {
- border-left-color: rgba(63, 185, 80, 0.55);
- }
- body[data-workflow="agent"] .agent-tool-card.error {
- border-left-color: rgba(248, 81, 73, 0.55);
- background: linear-gradient(180deg,
- rgba(248, 81, 73, 0.05),
- rgba(248, 81, 73, 0.02));
- }
- body[data-workflow="agent"] .agent-tool-card .head {
- padding: 9px 11px 9px 12px;
- gap: 9px;
- font-family: inherit;
- font-size: 12px;
- transition: var(--t-fast);
- align-items: center;
- }
- body[data-workflow="agent"] .agent-tool-card .head:hover {
- background: rgba(255,255,255,0.025);
- }
- /* Status icon — circular badge */
- body[data-workflow="agent"] .agent-tool-card .head .icon {
- width: 18px; height: 18px;
- border-radius: 50%;
- display: inline-flex;
- align-items: center; justify-content: center;
- font-size: 11px;
- font-weight: 700;
- flex-shrink: 0;
- background: rgba(140,160,220,0.10);
- color: var(--muted);
- line-height: 1;
- }
- body[data-workflow="agent"] .agent-tool-card.pending .head .icon {
- background: rgba(47, 129, 247, 0.18);
- color: var(--accent-bright);
- }
- body[data-workflow="agent"] .agent-tool-card.pending .head .icon::before {
- content: '';
- width: 8px; height: 8px;
- border-radius: 50%;
- background: var(--accent-bright);
- animation: agent-tool-dot 1.2s ease-in-out infinite;
- }
- @keyframes agent-tool-dot {
- 0%, 100% { opacity: 0.4; transform: scale(0.85); }
- 50% { opacity: 1; transform: scale(1.1); }
- }
- body[data-workflow="agent"] .agent-tool-card.pending .head .icon-glyph { display: none; }
- body[data-workflow="agent"] .agent-tool-card.success .head .icon {
- background: rgba(63, 185, 80, 0.18);
- color: var(--success);
- }
- body[data-workflow="agent"] .agent-tool-card.error .head .icon {
- background: rgba(248, 81, 73, 0.18);
- color: var(--danger);
- }
- /* Tool name — mono chip */
- body[data-workflow="agent"] .agent-tool-card .head .name {
- font-family: var(--ph-font-mono);
- font-size: 11.5px;
- font-weight: 600;
- color: var(--text);
- letter-spacing: 0.01em;
- flex-shrink: 0;
- }
- body[data-workflow="agent"] .agent-tool-card.error .head .name { color: #f5b3ae; }
- body[data-workflow="agent"] .agent-tool-card .head .summary {
- color: var(--muted);
- flex: 1; min-width: 0;
- font-size: 11.5px;
- overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
- }
- /* Duration meta — mono, muted */
- body[data-workflow="agent"] .agent-tool-card .head .duration {
- font-family: var(--ph-font-mono);
- font-size: 10.5px;
- color: var(--ph-text-faint);
- flex-shrink: 0;
- letter-spacing: 0;
- }
- body[data-workflow="agent"] .agent-tool-card .head .chevron {
- color: var(--muted);
- flex-shrink: 0;
- transition: transform var(--t-base) ease;
- font-size: 13px;
- line-height: 1;
- width: 14px;
- text-align: center;
- }
- body[data-workflow="agent"] .agent-tool-card.open .head .chevron {
- transform: rotate(90deg);
- }
- body[data-workflow="agent"] .agent-tool-card .body {
- border-top: 1px solid var(--ph-border-soft);
- padding: 0 12px 12px;
- }
- body[data-workflow="agent"] .agent-tool-card.open .body {
- padding-top: 10px;
- }
- body[data-workflow="agent"] .agent-tool-card .body pre {
- margin: 0;
- padding: 11px 13px;
- background: linear-gradient(180deg, #0a1130 0%, #050920 100%);
- border: 1px solid var(--ph-border-soft);
- border-radius: var(--r-xs);
- font-size: 11.5px;
- line-height: 1.5;
- max-height: 320px;
- overflow: auto;
- white-space: pre-wrap;
- word-break: break-word;
- color: var(--text);
- font-family: var(--ph-font-mono);
- }
-
- /* ---- 8. Reasoning disclosure — quieter polish */
- body[data-workflow="agent"] .agent-reasoning {
- margin: 0 0 10px 0;
- border: 1px solid var(--ph-border-soft);
- border-radius: var(--r-sm);
- background: rgba(140, 160, 220, 0.025);
- transition: var(--t-base);
- }
- body[data-workflow="agent"] .agent-reasoning:hover {
- border-color: var(--ph-border-strong);
- }
- body[data-workflow="agent"] .agent-reasoning > summary {
- padding: 8px 12px;
- font-size: 11.5px;
- gap: 8px;
- }
- body[data-workflow="agent"] .agent-reasoning > summary .label {
- font-weight: 600;
- color: var(--text);
- }
- body[data-workflow="agent"] .agent-reasoning > summary .meta {
- color: var(--ph-text-faint);
- font-family: var(--ph-font-mono);
- font-size: 10.5px;
- }
- body[data-workflow="agent"] .agent-reasoning .agent-reasoning-body {
- padding: 4px 14px 12px 30px;
- max-height: 360px;
- }
-
- /* ---- 9. Turn summary chip — polished */
- body[data-workflow="agent"] .agent-turn-summary {
- margin-top: 10px;
- padding: 6px 11px;
- background: linear-gradient(180deg,
- rgba(140, 160, 220, 0.05),
- rgba(140, 160, 220, 0.02));
- border: 1px solid var(--ph-border-soft);
- border-radius: var(--r-pill);
- font-size: 11px;
- transition: var(--t-fast);
- }
- body[data-workflow="agent"] .agent-turn-summary:hover {
- border-color: var(--ph-border-strong);
- background: linear-gradient(180deg,
- rgba(140, 160, 220, 0.07),
- rgba(140, 160, 220, 0.03));
- }
- body[data-workflow="agent"] .agent-turn-summary-icon {
- color: var(--success);
- opacity: 0.85;
- }
- body[data-workflow="agent"] .agent-turn-summary-text {
- font-family: var(--ph-font-mono);
- font-size: 10.5px;
- color: var(--text);
- letter-spacing: 0.01em;
- }
- body[data-workflow="agent"] .agent-turn-summary-text .sep {
- color: var(--ph-text-faint);
- opacity: 0.7;
- }
-
- /* ---- 10. Empty state — inviting hero */
- body[data-workflow="agent"] .agent-empty {
- max-width: 600px;
- margin: 8vh auto 24px;
- text-align: center;
- padding: 0 18px;
- }
- body[data-workflow="agent"] .agent-empty-glyph {
- width: 64px; height: 64px;
- margin: 0 auto 18px;
- border-radius: var(--r-lg);
- background:
- radial-gradient(circle at 35% 30%, rgba(187, 89, 233, 0.22), transparent 60%),
- radial-gradient(circle at 70% 65%, rgba(47, 129, 247, 0.22), transparent 60%),
- linear-gradient(135deg, #0a1130, #050920);
- border: 1px solid rgba(187, 89, 233, 0.30);
- display: flex; align-items: center; justify-content: center;
- box-shadow: 0 12px 36px rgba(47,129,247,0.18),
- 0 0 0 1px rgba(187,89,233,0.10);
- position: relative;
- overflow: hidden;
- }
- body[data-workflow="agent"] .agent-empty-glyph::before {
- content: '';
- position: absolute;
- inset: 0;
- background: url('/assets/favicon-64.png') center/52% no-repeat;
- filter: drop-shadow(0 0 12px rgba(187,89,233,0.45));
- }
- body[data-workflow="agent"] .agent-empty .badge {
- display: inline-flex;
- align-items: center;
- gap: 6px;
- padding: 4px 11px;
- border-radius: var(--r-pill);
- background: rgba(47, 129, 247, 0.10);
- border: 1px solid rgba(47, 129, 247, 0.30);
- color: var(--accent-bright);
- font-size: 10.5px; font-weight: 600;
- letter-spacing: 0.06em;
- text-transform: uppercase;
- margin-bottom: 18px;
- font-family: var(--ph-font-mono);
- }
- body[data-workflow="agent"] .agent-empty h3 {
- font-size: 22px;
- font-weight: 600;
- letter-spacing: -0.01em;
- color: var(--text);
- margin: 0 0 10px;
- }
- body[data-workflow="agent"] .agent-empty p {
- font-size: 13.5px;
- line-height: 1.6;
- color: var(--muted);
- margin: 4px 0;
- }
- body[data-workflow="agent"] .agent-empty .examples {
- display: grid;
- grid-template-columns: 1fr;
- gap: 8px;
- max-width: 480px;
- margin: 28px auto 0;
- }
- body[data-workflow="agent"] .agent-empty .example {
- text-align: left;
- padding: 12px 14px;
- background: var(--panel);
- border: 1px solid var(--ph-border-soft);
- border-radius: var(--r-md);
- cursor: pointer;
- color: var(--text);
- font-size: 13px;
- transition: var(--t-base);
- display: flex; align-items: center; gap: 12px;
- box-shadow: var(--shadow-1);
- }
- body[data-workflow="agent"] .agent-empty .example:hover {
- border-color: var(--accent);
- background: rgba(47, 129, 247, 0.06);
- transform: translateY(-1px);
- box-shadow: 0 6px 18px rgba(47,129,247,0.15);
- }
- body[data-workflow="agent"] .agent-empty .example .ex-icon {
- width: 28px; height: 28px;
- flex-shrink: 0;
- border-radius: var(--r-sm);
- background: rgba(47, 129, 247, 0.14);
- color: var(--accent-bright);
- display: inline-flex;
- align-items: center; justify-content: center;
- }
- body[data-workflow="agent"] .agent-empty .example .ex-text {
- flex: 1; min-width: 0;
- font-weight: 500;
- }
- body[data-workflow="agent"] .agent-empty .example .arrow {
- color: var(--muted);
- flex-shrink: 0;
- transition: transform var(--t-base), color var(--t-base);
- }
- body[data-workflow="agent"] .agent-empty .example:hover .arrow {
- color: var(--accent-bright);
- transform: translateX(3px);
- }
-
- /* ---- 11. Composer — hero card. */
- body[data-workflow="agent"] .agent-composer {
- border-top: 1px solid var(--ph-border-soft);
- padding: 12px 18px 16px;
- background: linear-gradient(180deg,
- transparent,
- rgba(0, 6, 26, 0.4) 30%,
- rgba(0, 6, 26, 0.7));
- backdrop-filter: blur(8px);
- }
- body[data-workflow="agent"] .agent-composer-wrap {
- position: relative;
- background: var(--panel);
- border: 1px solid var(--border-strong);
- border-radius: var(--r-lg);
- padding: 0;
- box-shadow: var(--shadow-1);
- transition: border-color var(--t-base), box-shadow var(--t-base);
- }
- body[data-workflow="agent"] .agent-composer-wrap:focus-within {
- border-color: var(--accent);
- box-shadow: 0 0 0 3px var(--accent-dim), var(--shadow-1);
- }
- body[data-workflow="agent"] .agent-composer textarea {
- width: 100%;
- min-height: 56px;
- max-height: 240px;
- padding: 14px 60px 14px 56px;
- background: transparent;
- color: var(--text);
- border: none;
- border-radius: var(--r-lg);
- font-family: inherit;
- font-size: 14px;
- line-height: 1.55;
- resize: none;
- outline: none;
- box-shadow: none;
- }
- body[data-workflow="agent"] .agent-composer textarea:focus {
- outline: none;
- box-shadow: none;
- border: none;
- background: transparent;
- }
- body[data-workflow="agent"] .agent-composer textarea::placeholder {
- color: var(--muted);
- opacity: 0.7;
- }
- /* Attach button — left edge of the composer card */
- body[data-workflow="agent"] .agent-composer .attach-btn {
- position: absolute;
- left: 8px; bottom: 8px;
- width: 38px; height: 38px;
- border-radius: var(--r-md);
- background: transparent;
- color: var(--muted);
- border: 1px solid transparent;
- cursor: pointer;
- display: inline-flex;
- align-items: center; justify-content: center;
- transition: var(--t-fast);
- }
- body[data-workflow="agent"] .agent-composer .attach-btn:hover {
- background: rgba(140,160,220,0.08);
- color: var(--accent-bright);
- border-color: var(--ph-border-soft);
- }
- body[data-workflow="agent"] .agent-composer .attach-btn svg {
- width: 18px; height: 18px;
- }
- body[data-workflow="agent"] .agent-composer .attach-btn .count {
- position: absolute;
- top: 1px; right: 1px;
- min-width: 16px; height: 16px;
- padding: 0 4px;
- background: var(--accent);
- color: white;
- border-radius: var(--r-pill);
- font-size: 9.5px;
- font-weight: 700;
- display: none;
- align-items: center; justify-content: center;
- }
- body[data-workflow="agent"] .agent-composer .attach-btn.has-attach {
- color: var(--accent-bright);
- background: rgba(47,129,247,0.10);
- }
- body[data-workflow="agent"] .agent-composer .attach-btn.has-attach .count { display: inline-flex; }
-
- /* Send button — circular, accent-bright, plane icon */
- body[data-workflow="agent"] .agent-composer .send-btn,
- body[data-workflow="agent"] #agentSendBtn {
- position: absolute;
- right: 8px; bottom: 8px;
- width: 38px; height: 38px;
- border-radius: 50%;
- background: var(--accent);
- color: white;
- border: none;
- cursor: pointer;
- display: inline-flex;
- align-items: center; justify-content: center;
- transition: var(--t-fast);
- box-shadow: 0 4px 14px rgba(47,129,247,0.32),
- 0 0 0 1px rgba(255,255,255,0.05) inset;
- }
- body[data-workflow="agent"] .agent-composer .send-btn:hover:not(:disabled),
- body[data-workflow="agent"] #agentSendBtn:hover:not(:disabled) {
- background: var(--accent-bright);
- transform: translateY(-1px) scale(1.04);
- box-shadow: 0 8px 22px rgba(47,129,247,0.50),
- 0 0 0 1px rgba(255,255,255,0.08) inset;
- }
- body[data-workflow="agent"] .agent-composer .send-btn:active:not(:disabled),
- body[data-workflow="agent"] #agentSendBtn:active:not(:disabled) {
- transform: translateY(0) scale(1.0);
- }
- body[data-workflow="agent"] .agent-composer .send-btn:disabled,
- body[data-workflow="agent"] #agentSendBtn:disabled {
- background: rgba(140,160,220,0.10);
- color: rgba(255,255,255,0.30);
- cursor: not-allowed;
- box-shadow: none;
- }
- body[data-workflow="agent"] .agent-composer .send-btn svg,
- body[data-workflow="agent"] #agentSendBtn svg {
- width: 16px; height: 16px;
- }
- /* Busy state — spinner instead of plane (toggled via .is-busy by JS) */
- body[data-workflow="agent"] .agent-composer .send-btn.is-busy svg,
- body[data-workflow="agent"] #agentSendBtn.is-busy svg {
- animation: agent-send-spin 0.9s linear infinite;
- }
- @keyframes agent-send-spin {
- to { transform: rotate(360deg); }
- }
-
- /* Composer hint strip — sits BELOW the composer card, not absolute. */
- body[data-workflow="agent"] .agent-composer .hint {
- position: static;
- display: block;
- margin: 8px 4px 0;
- padding: 0;
- font-size: 11px;
- color: var(--muted);
- opacity: 0.7;
- letter-spacing: 0;
- pointer-events: auto;
- text-align: center;
- }
- body[data-workflow="agent"] .agent-composer .hint kbd {
- font-family: var(--ph-font-mono);
- font-size: 10px;
- padding: 1px 5px;
- margin: 0 1px;
- background: rgba(140,160,220,0.08);
- border: 1px solid var(--ph-border-soft);
- border-radius: var(--r-xs);
- color: var(--text);
- }
-
- /* Pending-attachment chip row — above the composer card */
- body[data-workflow="agent"] .agent-attach-row {
- max-width: 100%;
- margin: 0 0 8px 0;
- padding: 0;
- }
- body[data-workflow="agent"] .agent-attach-chip {
- padding: 5px 10px 5px 5px;
- background: var(--panel);
- border: 1px solid var(--ph-border-soft);
- border-radius: var(--r-md);
- box-shadow: var(--shadow-1);
- transition: var(--t-fast);
- }
- body[data-workflow="agent"] .agent-attach-chip:hover {
- border-color: var(--accent);
- }
-
- /* Reference chip (refine) — same shape as attach chip but
- accent-tinted to read as "this affects the next message". */
- body[data-workflow="agent"] .agent-ref-chip {
- max-width: 100%;
- margin: 0 0 8px 0;
- padding: 6px 10px 6px 12px;
- background: linear-gradient(135deg,
- rgba(47, 129, 247, 0.16),
- rgba(47, 129, 247, 0.10));
- border: 1px solid rgba(47, 129, 247, 0.32);
- border-radius: var(--r-md);
- box-shadow: 0 4px 12px rgba(47,129,247,0.15);
- }
- body[data-workflow="agent"] .agent-ref-chip .ref-icon {
- color: var(--accent-bright);
- font-size: 14px;
- }
-
- /* Batch bar — accent-tinted action strip, polished CTA */
- body[data-workflow="agent"] .agent-batch-bar {
- margin: 0 0 10px 0;
- padding: 9px 12px 9px 14px;
- background: linear-gradient(135deg,
- rgba(63, 185, 80, 0.14) 0%,
- rgba(47, 129, 247, 0.10) 100%);
- border: 1px solid rgba(63, 185, 80, 0.40);
- border-radius: var(--r-md);
- box-shadow: 0 4px 16px rgba(63,185,80,0.10);
- height: auto;
- }
- body[data-workflow="agent"] .agent-batch-bar-icon {
- font-size: 14px;
- color: var(--success);
- }
- body[data-workflow="agent"] .agent-batch-bar-text {
- color: var(--text);
- font-size: 12.5px;
- font-weight: 500;
- }
- body[data-workflow="agent"] .agent-batch-bar-btn {
- padding: 6px 12px;
- background: var(--success);
- color: #04130a;
- border-radius: var(--r-sm);
- font-size: 12px;
- font-weight: 600;
- border: none;
- }
-
- /* ---- 12. Sessions sidebar — richer item rows */
- body[data-workflow="agent"] .agent-sessions-panel {
- background: var(--panel);
- border-right: 1px solid var(--border-strong);
- box-shadow: 14px 0 40px rgba(0, 0, 0, 0.55);
- }
- body[data-workflow="agent"] .asp-head {
- padding: 16px 14px 12px;
- border-bottom: 1px solid var(--ph-border-soft);
- }
- body[data-workflow="agent"] .asp-head .asp-title {
- font-size: 13.5px;
- font-weight: 600;
- letter-spacing: -0.01em;
- }
- body[data-workflow="agent"] .asp-search {
- padding: 12px;
- border-bottom: 1px solid var(--ph-border-soft);
- }
- body[data-workflow="agent"] .asp-search input {
- padding: 8px 36px 8px 32px;
- background: var(--bg-2);
- border: 1px solid var(--ph-border-soft);
- border-radius: var(--r-sm);
- font-size: 12.5px;
- transition: var(--t-fast);
- }
- body[data-workflow="agent"] .asp-search input:focus {
- border-color: var(--accent);
- box-shadow: 0 0 0 3px var(--accent-dim);
- background: var(--bg);
- }
- body[data-workflow="agent"] .asp-search-icon { left: 24px; top: 20px; }
- body[data-workflow="agent"] .asp-kbd { right: 22px; top: 18px; }
- body[data-workflow="agent"] .asp-section-label {
- padding: 12px 12px 4px;
- font-size: 9.5px;
- font-weight: 700;
- font-family: var(--ph-font-mono);
- letter-spacing: 0.08em;
- }
- body[data-workflow="agent"] .asp-item {
- padding: 10px 12px;
- margin: 2px 0;
- border-radius: var(--r-sm);
- transition: var(--t-fast);
- }
- body[data-workflow="agent"] .asp-item:hover {
- background: rgba(140,160,220,0.06);
- }
- body[data-workflow="agent"] .asp-item.is-active {
- background: rgba(47, 129, 247, 0.10);
- border: 1px solid rgba(47, 129, 247, 0.32);
- }
- body[data-workflow="agent"] .asp-item-title {
- font-size: 13px;
- font-weight: 500;
- letter-spacing: -0.005em;
- }
- body[data-workflow="agent"] .asp-item-time {
- font-size: 10.5px;
- font-family: var(--ph-font-mono);
- color: var(--ph-text-faint);
- }
- body[data-workflow="agent"] .asp-item-preview {
- font-size: 11.5px;
- color: var(--muted);
- margin-top: 3px;
- line-height: 1.4;
- }
- body[data-workflow="agent"] .asp-chip {
- font-family: var(--ph-font-mono);
- font-size: 9.5px;
- padding: 1px 6px;
- background: rgba(140,160,220,0.06);
- border: 1px solid var(--ph-border-soft);
- border-radius: var(--r-pill);
- letter-spacing: 0.02em;
- }
- body[data-workflow="agent"] .asp-chip-shots {
- color: var(--accent-bright);
- border-color: rgba(47,129,247,0.32);
- background: rgba(47,129,247,0.10);
- }
-
- /* ---- 13. Agent stage pane (right side) — composer-grade.
- Same elevated-card visual language as the player + carousel
- in the manual stage pane. STAGE / NOW RENDERING / ACTIVITY /
- OUTPUTS read as one cohesive session dashboard. */
- body[data-workflow="agent"] .agent-stage-pane {
- background:
- radial-gradient(circle at 70% -10%, rgba(47,129,247,0.06) 0%, transparent 40%),
- linear-gradient(180deg, var(--bg) 0%, var(--bg-2) 100%);
- border: none;
- border-left: 1px solid var(--ph-border-soft);
- border-radius: 0;
- padding: 14px 14px 14px;
- gap: 12px;
- }
- body[data-workflow="agent"] .agent-stage-head {
- height: auto;
- min-height: 36px;
- padding: 4px 10px 6px;
- background: transparent;
- border-bottom: none;
- }
- body[data-workflow="agent"] .agent-stage-head .label {
- font-size: 10px;
- font-family: var(--ph-font-mono);
- font-weight: 600;
- letter-spacing: 0.10em;
- color: var(--accent-bright);
- text-transform: uppercase;
- }
- body[data-workflow="agent"] .agent-stage-head .live-dot {
- width: 7px; height: 7px;
- background: var(--muted);
- }
- body[data-workflow="agent"] .agent-stage-head .live-dot.live {
- background: var(--success);
- box-shadow: 0 0 0 3px rgba(63,185,80,0.18),
- 0 0 8px rgba(63,185,80,0.45);
- }
- body[data-workflow="agent"] .agent-stage-head .session-pill {
- font-family: var(--ph-font-mono);
- font-size: 10.5px;
- padding: 2px 8px;
- background: rgba(140, 160, 220, 0.05);
- border: 1px solid var(--ph-border-soft);
- border-radius: var(--r-pill);
- color: var(--muted);
- }
- /* Make body a vertical stack of elevated cards instead of bordered
- sections separated by hairlines — matches the carousel-wrap idiom. */
- body[data-workflow="agent"] .agent-stage-body {
- padding: 0;
- gap: 12px;
- display: flex;
- flex-direction: column;
- }
- body[data-workflow="agent"] .agent-stage-section {
- padding: 12px 14px;
- background: var(--panel);
- border: 1px solid var(--border-strong);
- border-radius: var(--r-lg);
- box-shadow: var(--shadow-1);
- transition: var(--t-base);
- }
- body[data-workflow="agent"] .agent-stage-section:hover {
- border-color: var(--ph-border-strong);
- }
- body[data-workflow="agent"] .agent-stage-section h4 {
- margin: 0 0 10px;
- font-size: 10px;
- font-family: var(--ph-font-mono);
- font-weight: 600;
- letter-spacing: 0.10em;
- color: var(--muted);
- text-transform: uppercase;
- display: flex; align-items: center; gap: 8px;
- }
- body[data-workflow="agent"] .agent-stage-section h4 .count {
- padding: 1px 7px;
- background: rgba(47, 129, 247, 0.14);
- color: var(--accent-bright);
- border-radius: var(--r-pill);
- font-size: 9.5px;
- font-weight: 700;
- }
- /* Now-rendering card — when active, becomes a 16:9 elevated frame */
- body[data-workflow="agent"] .stage-now-card {
- padding: 0;
- background: linear-gradient(180deg, #0a1130, #050920);
- border: 1px solid var(--ph-border-soft);
- border-radius: var(--r-md);
- aspect-ratio: 16/9;
- position: relative;
- overflow: hidden;
- }
- body[data-workflow="agent"] .stage-now-card.idle {
- aspect-ratio: auto;
- padding: 22px 14px;
- background: rgba(140, 160, 220, 0.025);
- border: 1px dashed var(--ph-border-soft);
- color: var(--muted);
- font-style: normal;
- font-size: 12px;
- font-family: var(--ph-font-mono);
- text-align: center;
- letter-spacing: 0.02em;
- }
- body[data-workflow="agent"] .stage-progress-fill {
- background: linear-gradient(90deg, var(--accent), var(--accent-bright));
- box-shadow: 0 0 12px rgba(47,129,247,0.45);
- }
- body[data-workflow="agent"] .stage-progress-text {
- font-family: var(--ph-font-mono);
- font-size: 10.5px;
- }
- /* Activity feed — icon avatars, smaller mono */
- body[data-workflow="agent"] .stage-activity {
- max-height: 220px;
- gap: 4px;
- }
- body[data-workflow="agent"] .stage-activity-row {
- padding: 5px 4px;
- border-bottom: 1px solid rgba(140,160,220,0.04);
- gap: 8px;
- font-size: 11px;
- align-items: center;
- }
- body[data-workflow="agent"] .stage-activity-row .icon {
- width: 16px; height: 16px;
- border-radius: 50%;
- display: inline-flex;
- align-items: center; justify-content: center;
- font-size: 9px;
- font-weight: 700;
- flex-shrink: 0;
- }
- body[data-workflow="agent"] .stage-activity-row.ok .icon {
- background: rgba(63,185,80,0.18);
- color: var(--success);
- }
- body[data-workflow="agent"] .stage-activity-row.fail .icon {
- background: rgba(248,81,73,0.18);
- color: var(--danger);
- }
- body[data-workflow="agent"] .stage-activity-row.run .icon {
- background: rgba(47,129,247,0.18);
- color: var(--accent-bright);
- }
- body[data-workflow="agent"] .stage-activity-row .text {
- font-family: inherit;
- color: var(--text);
- font-size: 11.5px;
- }
- body[data-workflow="agent"] .stage-activity-row .when {
- font-family: var(--ph-font-mono);
- font-size: 10px;
- color: var(--ph-text-faint);
- }
- /* Session outputs — accent hover lift */
- body[data-workflow="agent"] .stage-outputs {
- grid-template-columns: repeat(2, 1fr);
- gap: 10px;
- }
- body[data-workflow="agent"] .stage-output-cell {
- border: 1px solid var(--ph-border-soft);
- border-radius: var(--r-sm);
- background: var(--bg);
- transition: var(--t-base);
- box-shadow: var(--shadow-1);
- }
- body[data-workflow="agent"] .stage-output-cell:hover {
- border-color: var(--accent);
- transform: translateY(-2px);
- box-shadow: 0 8px 20px rgba(47,129,247,0.18);
- }
- body[data-workflow="agent"] .stage-output-cell .label {
- font-family: var(--ph-font-mono);
- font-size: 10px;
- padding: 3px 6px;
- background: linear-gradient(180deg, transparent, rgba(0,0,0,0.78));
- }
- body[data-workflow="agent"] .stage-outputs-filter button {
- padding: 4px 11px;
- font-size: 11px;
- font-weight: 500;
- border-radius: var(--r-pill);
- border: 1px solid var(--ph-border-soft);
- transition: var(--t-fast);
- }
- body[data-workflow="agent"] .stage-outputs-filter button:hover {
- color: var(--text);
- border-color: var(--accent);
- background: rgba(47,129,247,0.06);
- }
- body[data-workflow="agent"] .stage-outputs-filter button.active {
- background: rgba(47, 129, 247, 0.14);
- color: var(--accent-bright);
- border-color: var(--accent);
- }
-
- /* "↓ New messages" pill — match composer accent + a real shadow */
- body[data-workflow="agent"] .agent-newmsgs-pill {
- bottom: 12px;
- padding: 6px 12px;
- border-radius: var(--r-pill);
- background: var(--accent);
- color: white;
- font-size: 11.5px;
- font-weight: 600;
- box-shadow: 0 8px 22px rgba(47,129,247,0.55);
- transition: var(--t-fast);
- }
- body[data-workflow="agent"] .agent-newmsgs-pill:hover {
- background: var(--accent-bright);
- transform: translateX(-50%) translateY(-1px);
- }
-
- /* Drop overlay — accent-tinted with a soft glow */
- body[data-workflow="agent"] .agent-drop-overlay {
- background: rgba(47, 129, 247, 0.08);
- border: 2px dashed var(--accent);
- border-radius: var(--r-lg);
- }
- body[data-workflow="agent"] .agent-drop-overlay .drop-card {
- background: var(--panel);
- border: 1px solid var(--accent);
- border-radius: var(--r-lg);
- box-shadow: 0 12px 36px rgba(47,129,247,0.30);
- padding: 22px 32px;
- }
- /* === END CHAT REDESIGN Y2.002 ============================== */
-
- /* === PHOSPHOR ICONS (MIT) ===================================
- Inline SVG symbol library used across the panel. Glyph art is
- from phosphor-icons/core (MIT). `.ph` is the base size + color
- hook; specific call sites can override width/height/color via
- inline style or component CSS.
-
- Pattern: <svg class="ph"><use href="#ph-x"/></svg>
-
- `currentColor` ties stroke/fill to the parent's text color so
- the existing `.danger`, `.muted`, `.accent-bright` classes carry
- through. NEVER hardcode a color inside a <symbol> path. */
- .ph {
- width: 1em;
- height: 1em;
- flex-shrink: 0;
- display: inline-block;
- vertical-align: -0.125em;
- color: currentColor;
- }
- .ph-sm { width: 12px; height: 12px; }
- .ph-md { width: 14px; height: 14px; }
- .ph-lg { width: 18px; height: 18px; }
- .ph-xl { width: 24px; height: 24px; }
- .ph-2xl { width: 32px; height: 32px; }
- /* For buttons that previously held a single unicode glyph
- (×, ↗, ↻, etc.). Make the SVG inherit the button's flex centering. */
- button > .ph, a > .ph { display: block; }
- /* Spinner keyframe for refresh icons used in "checking…" pills. */
- @keyframes phSpin { from { transform: rotate(0deg); } to { transform: rotate(360deg); } }
- </style>
-</head>
-<body>
-
-<!-- Phosphor Icons (MIT, https://github.com/phosphor-icons/core) — inline symbol library.
- Referenced via <svg class="ph"><use href="#ph-NAME"/></svg>. The symbol set is
- curated, not the full Phosphor library — only icons we actually use. License notice
- lives at LICENSES/phosphor-icons.txt in the repo root. -->
-<svg width="0" height="0" style="position:absolute;width:0;height:0;overflow:hidden" aria-hidden="true">
-<defs>
-<symbol id="ph-arrow-clockwise" viewBox="0 0 256 256"><polyline points="184 104 232 104 232 56" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/><path d="M188.4,192a88,88,0,1,1,1.83-126.23L232,104" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/></symbol>
-<symbol id="ph-arrow-clockwise-bold" viewBox="0 0 256 256"><polyline points="184 104 232 104 232 56" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="24"/><path d="M188.4,192a88,88,0,1,1,1.83-126.23L232,104" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="24"/></symbol>
-<symbol id="ph-arrow-square-out" viewBox="0 0 256 256"><polyline points="216 104 215.99 40.01 152 40" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/><line x1="136" y1="120" x2="216" y2="40" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/><path d="M184,136v72a8,8,0,0,1-8,8H48a8,8,0,0,1-8-8V80a8,8,0,0,1,8-8h72" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/></symbol>
-<symbol id="ph-arrow-up" viewBox="0 0 256 256"><line x1="128" y1="216" x2="128" y2="40" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/><polyline points="56 112 128 40 200 112" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/></symbol>
-<symbol id="ph-caret-down-bold" viewBox="0 0 256 256"><polyline points="208 96 128 176 48 96" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="24"/></symbol>
-<symbol id="ph-check-bold" viewBox="0 0 256 256"><polyline points="40 144 96 200 224 72" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="24"/></symbol>
-<symbol id="ph-download-simple" viewBox="0 0 256 256"><line x1="128" y1="144" x2="128" y2="32" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/><polyline points="216 144 216 208 40 208 40 144" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/><polyline points="168 104 128 144 88 104" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/></symbol>
-<symbol id="ph-film-strip" viewBox="0 0 256 256"><rect x="32" y="48" width="192" height="160" rx="8" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/><line x1="128" y1="48" x2="128" y2="208" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/><line x1="32" y1="80" x2="224" y2="80" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/><line x1="32" y1="176" x2="224" y2="176" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/><line x1="80" y1="48" x2="80" y2="80" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/><line x1="176" y1="48" x2="176" y2="80" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/><line x1="80" y1="176" x2="80" y2="208" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/><line x1="176" y1="176" x2="176" y2="208" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/></symbol>
-<symbol id="ph-gear-six" viewBox="0 0 256 256"><circle cx="128" cy="128" r="40" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/><path d="M130.05,206.11c-1.34,0-2.69,0-4,0L94,224a104.61,104.61,0,0,1-34.11-19.2l-.12-36c-.71-1.12-1.38-2.25-2-3.41L25.9,147.24a99.15,99.15,0,0,1,0-38.46l31.84-18.1c.65-1.15,1.32-2.29,2-3.41l.16-36A104.58,104.58,0,0,1,94,32l32,17.89c1.34,0,2.69,0,4,0L162,32a104.61,104.61,0,0,1,34.11,19.2l.12,36c.71,1.12,1.38,2.25,2,3.41l31.85,18.14a99.15,99.15,0,0,1,0,38.46l-31.84,18.1c-.65,1.15-1.32,2.29-2,3.41l-.16,36A104.58,104.58,0,0,1,162,224Z" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/></symbol>
-<symbol id="ph-image" viewBox="0 0 256 256"><rect x="32" y="48" width="192" height="160" rx="8" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/><circle cx="156" cy="100" r="12"/><path d="M147.31,164,173,138.34a8,8,0,0,1,11.31,0L224,178.06" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/><path d="M32,168.69l54.34-54.35a8,8,0,0,1,11.32,0L191.31,208" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/></symbol>
-<symbol id="ph-info-fill" viewBox="0 0 256 256"><path d="M128,24A104,104,0,1,0,232,128,104.11,104.11,0,0,0,128,24Zm-4,48a12,12,0,1,1-12,12A12,12,0,0,1,124,72Zm12,112a16,16,0,0,1-16-16V128a8,8,0,0,1,0-16,16,16,0,0,1,16,16v40a8,8,0,0,1,0,16Z"/></symbol>
-<symbol id="ph-info" viewBox="0 0 256 256"><circle cx="128" cy="128" r="96" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/><polyline points="120 120 128 120 128 172 136 172" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/><circle cx="126" cy="84" r="10" fill="currentColor"/></symbol>
-<symbol id="ph-magnifying-glass" viewBox="0 0 256 256"><circle cx="112" cy="112" r="80" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/><line x1="168.57" y1="168.57" x2="224" y2="224" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/></symbol>
-<symbol id="ph-pause-fill" viewBox="0 0 256 256"><path d="M216,48V208a16,16,0,0,1-16,16H160a16,16,0,0,1-16-16V48a16,16,0,0,1,16-16h40A16,16,0,0,1,216,48ZM96,32H56A16,16,0,0,0,40,48V208a16,16,0,0,0,16,16H96a16,16,0,0,0,16-16V48A16,16,0,0,0,96,32Z"/></symbol>
-<symbol id="ph-pencil-simple" viewBox="0 0 256 256"><path d="M92.69,216H48a8,8,0,0,1-8-8V163.31a8,8,0,0,1,2.34-5.65L165.66,34.34a8,8,0,0,1,11.31,0L221.66,79a8,8,0,0,1,0,11.31L98.34,213.66A8,8,0,0,1,92.69,216Z" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/><line x1="136" y1="64" x2="192" y2="120" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/></symbol>
-<symbol id="ph-play-fill" viewBox="0 0 256 256"><path d="M240,128a15.74,15.74,0,0,1-7.6,13.51L88.32,229.65a16,16,0,0,1-16.2.3A15.86,15.86,0,0,1,64,216.13V39.87a15.86,15.86,0,0,1,8.12-13.82,16,16,0,0,1,16.2.3L232.4,114.49A15.74,15.74,0,0,1,240,128Z"/></symbol>
-<symbol id="ph-sparkle-fill" viewBox="0 0 256 256"><path d="M208,144a15.78,15.78,0,0,1-10.42,14.94L146,178l-19,51.62a15.92,15.92,0,0,1-29.88,0L78,178l-51.62-19a15.92,15.92,0,0,1,0-29.88L78,110l19-51.62a15.92,15.92,0,0,1,29.88,0L146,110l51.62,19A15.78,15.78,0,0,1,208,144ZM152,48h16V64a8,8,0,0,0,16,0V48h16a8,8,0,0,0,0-16H184V16a8,8,0,0,0-16,0V32H152a8,8,0,0,0,0,16Zm88,32h-8V72a8,8,0,0,0-16,0v8h-8a8,8,0,0,0,0,16h8v8a8,8,0,0,0,16,0V96h8a8,8,0,0,0,0-16Z"/></symbol>
-<symbol id="ph-target" viewBox="0 0 256 256"><line x1="128" y1="128" x2="224" y2="32" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/><path d="M195.88,60.12a95.88,95.88,0,1,0,18.77,26.49" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/><path d="M161.94,94.06a48,48,0,1,0,14,31.2" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/></symbol>
-<symbol id="ph-trash-simple" viewBox="0 0 256 256"><line x1="216" y1="56" x2="40" y2="56" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/><line x1="88" y1="24" x2="168" y2="24" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/><path d="M200,56V208a8,8,0,0,1-8,8H64a8,8,0,0,1-8-8V56" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/></symbol>
-<symbol id="ph-warning-fill" viewBox="0 0 256 256"><path d="M236.8,188.09,149.35,36.22h0a24.76,24.76,0,0,0-42.7,0L19.2,188.09a23.51,23.51,0,0,0,0,23.72A24.35,24.35,0,0,0,40.55,224h174.9a24.35,24.35,0,0,0,21.33-12.19A23.51,23.51,0,0,0,236.8,188.09ZM120,104a8,8,0,0,1,16,0v40a8,8,0,0,1-16,0Zm8,88a12,12,0,1,1,12-12A12,12,0,0,1,128,192Z"/></symbol>
-<symbol id="ph-x" viewBox="0 0 256 256"><line x1="200" y1="56" x2="56" y2="200" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/><line x1="200" y1="200" x2="56" y2="56" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/></symbol>
-<symbol id="ph-x-bold" viewBox="0 0 256 256"><line x1="200" y1="56" x2="56" y2="200" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="24"/><line x1="200" y1="200" x2="56" y2="56" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="24"/></symbol>
-<symbol id="ph-x-circle" viewBox="0 0 256 256"><line x1="160" y1="96" x2="96" y2="160" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/><line x1="96" y1="96" x2="160" y2="160" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/><circle cx="128" cy="128" r="96" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/></symbol>
-<symbol id="ph-x-circle-fill" viewBox="0 0 256 256"><path d="M128,24A104,104,0,1,0,232,128,104.11,104.11,0,0,0,128,24Zm37.66,130.34a8,8,0,0,1-11.32,11.32L128,139.31l-26.34,26.35a8,8,0,0,1-11.32-11.32L116.69,128,90.34,101.66a8,8,0,0,1,11.32-11.32L128,116.69l26.34-26.35a8,8,0,0,1,11.32,11.32L139.31,128Z"/></symbol>
-<!-- File-kind icons referenced dynamically by agentAttachIcon(); the
- tree-shake regex doesn't see runtime string concatenation. -->
-<symbol id="ph-paperclip" viewBox="0 0 256 256"><path d="M160,80,76.69,164.69a16,16,0,0,0,22.63,22.62L198.63,86.63a32,32,0,0,0-45.26-45.26L54.06,142.06a48,48,0,0,0,67.88,67.88L204,128" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/></symbol>
-<symbol id="ph-file-text" viewBox="0 0 256 256"><path d="M200,224H56a8,8,0,0,1-8-8V40a8,8,0,0,1,8-8h96l56,56V216A8,8,0,0,1,200,224Z" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/><polyline points="152 32 152 88 208 88" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/><line x1="96" y1="136" x2="160" y2="136" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/><line x1="96" y1="168" x2="160" y2="168" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/></symbol>
-<symbol id="ph-file-pdf" viewBox="0 0 256 256"><polyline points="216 152 184 152 184 208" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/><line x1="208" y1="184" x2="184" y2="184" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/><path d="M48,192H64a20,20,0,0,0,0-40H48v56" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/><path d="M112,152v56h16a28,28,0,0,0,0-56Z" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/><path d="M48,112V40a8,8,0,0,1,8-8h96l56,56v24" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/><polyline points="152 32 152 88 208 88" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/></symbol>
-<symbol id="ph-folder-simple" viewBox="0 0 256 256"><path d="M224,208H32V72a8,8,0,0,1,8-8H92.69a8,8,0,0,1,5.65,2.34L128,96h88a8,8,0,0,1,8,8V208Z" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/></symbol>
-</defs>
-</svg>
-
-<header>
- <a href="/" class="brand"><img src="/assets/phosphene_wordmark_compact_transparent.svg" alt="Phosphene"></a>
- <span class="version-badge" title="Phosphene 2.0">2.0</span>
- __PROFILE_BADGE__
- <span class="spacer"></span>
- <!-- Hardware tier badge — clickable, opens a dialog explaining what
- this Mac's RAM tier allows. Modes / qualities the tier doesn't
- support are visibly disabled in the form below. -->
- <span id="tierPill" class="pill" style="cursor:pointer" onclick="openTierModal()" title="Click to see what this Mac can do">click for system info</span>
- <span id="memPill" class="pill">memory…</span>
- <span id="comfyPill" class="pill" style="display:none">comfy…</span>
- <span id="helperPill" class="pill">helper…</span>
- <!-- Models pill: shows roll-up status (X / Y models ready) and click-opens
- a modal with per-repo download buttons. Color reflects readiness:
- pill-good = all models present, pill-warn = base ready but Q8 missing,
- pill-bad = base incomplete (panel can't render). -->
- <span id="modelsPill" class="pill" style="cursor:pointer" onclick="openModelsModal()" title="View / download model status">models…</span>
- <span id="queuePill" class="pill">queue 0</span>
- <span id="jobPill" class="pill">idle</span>
- <!-- Update-available pill. Hidden by default; renders only when the
- /version poller finds the install behind origin/main. Click → modal
- listing the unseen commits. We do this because users keep telling
- us "I clicked Update but I don't see anything" — by the time they
- do, we've usually pushed three more fixes. -->
- <!-- Version pill — the "magic button". Always visible so users learn
- where to look. Clicking does the right thing for the state:
- pill-current Y1.001 click → re-check GitHub now
- pill-update ↑ Y1.002 click → git pull (then restart)
- pill-restart ↻ restart click → just a reminder hint
- pill-dev Y1.001 ⚙ click → toast with reason
- pill-checking Y1.001 (idle, while first poll runs)
- No modal — confirm() + small toast for everything. -->
- <span id="versionPill" class="pill pill-checking" style="cursor:pointer"
- onclick="versionPillClick()" title="Phosphene version">phosphene · …</span>
- <!-- Bug-report button — neon-pulsing in the header pill row. Opens a
- modal that pre-fills environment info + log tail and finishes with a
- pre-filled GitHub issue (URL-built client-side, no auth). Sits before
- the settings cog so it's where the user looks first when something
- feels off. -->
- <button id="bugBtn" class="icon-btn bug-btn" onclick="openBugModal()" title="Report a bug — opens GitHub issue with environment pre-filled">
- <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
- <path d="M8 2l1.88 1.88"></path>
- <path d="M14.12 3.88L16 2"></path>
- <path d="M9 7.13v-1a3.003 3.003 0 0 1 6 0v1"></path>
- <path d="M12 20c-3.3 0-6-2.7-6-6v-3a4 4 0 0 1 4-4h4a4 4 0 0 1 4 4v3c0 3.3-2.7 6-6 6z"></path>
- <path d="M12 20v-9"></path>
- <path d="M6.53 9C4.6 8.8 3 7.1 3 5"></path>
- <path d="M6 13H2"></path>
- <path d="M3 21c0-2.1 1.7-3.8 3.8-4"></path>
- <path d="M20.97 5c0 2.1-1.6 3.8-3.5 4"></path>
- <path d="M22 13h-4"></path>
- <path d="M17.2 17c2.1.2 3.8 1.9 3.8 4"></path>
- </svg>
- </button>
- <!-- Settings cog: opens the modal that lets users pick output codec
- presets (Standard / Video production / Web / Custom). Sits between the
- runtime pills and Stop Comfy so it's findable but not loud. -->
- <button id="settingsBtn" class="icon-btn" onclick="openSettingsModal()" title="Output settings — codec, file size">
- <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
- <circle cx="12" cy="12" r="3"></circle>
- <path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"></path>
- </svg>
- </button>
- <button id="stopComfyBtn" class="ghost-btn" style="display:none" onclick="api('/stop_comfy', 'POST').then(poll)">Stop Comfy</button>
- <a class="creator-link" href="https://x.com/AIBizarrothe" target="_blank" rel="noopener" title="Follow Mr. Bizarro on X (the panel's creator)">
- <img src="/assets/bizarro-avatar.jpg" class="creator-avatar" alt="">
- <span>by Bizarro</span>
- <span class="x-icon"><svg class="ph" aria-hidden="true" style="margin-right:3px;vertical-align:-2px"><use href="#ph-arrow-square-out"/></svg>X</span>
- </a>
-</header>
-
-<main class="layout">
-
- <!-- ============== FORM PANE ============== -->
- <aside class="form-pane">
-
- <!-- Workflow tabs: switch the form-pane between the manual form and
- the chat-driven planner. Default = manual; toggling persists in
- localStorage so the user lands on the same tab next session. -->
- <nav class="workflow-tabs" id="workflowTabs">
- <button data-workflow="manual" class="active">Manual</button>
- <button data-workflow="train">Train<span class="new-badge">NEW</span></button>
- </nav>
- <!-- The original manual form is unchanged; it sits below in the DOM
- and is shown/hidden by JS as the workflow tab toggles. -->
- <!-- Inline models card. Sits ABOVE the mode picker because for many
- users the very first thing they need to do is download base
- weights — burying that in a header modal hides the whole point
- of the panel. Lives OUTSIDE #genForm so it persists across the
- video-form ↔ Image-Studio swap. -->
- <div id="modelsInline" class="models-inline" style="display:none">
- <button type="button" class="models-inline-dismiss" id="modelsInlineDismiss"
- title="Hide this card (won't show again until model state changes)"
- onclick="dismissModelsCard()"><svg class="ph" aria-hidden="true"><use href="#ph-x-bold"/></svg></button>
- <div class="models-inline-body">
- <div class="models-inline-icon" id="modelsInlineIcon"><svg class="ph" aria-hidden="true"><use href="#ph-download-simple"/></svg></div>
- <div class="models-inline-text">
- <div class="ttl" id="modelsInlineTitle">Download required</div>
- <div class="sub" id="modelsInlineSub">Click to start.</div>
- <div class="models-inline-progress" id="modelsInlineProgress" style="display:none">
- <div class="bar"><div class="fill" id="modelsInlineFill" style="width:0%"></div></div>
- <div class="last" id="modelsInlineLast"></div>
- </div>
- </div>
- <div class="models-inline-actions" id="modelsInlineActions"></div>
- </div>
- <a class="models-inline-link" onclick="openModelsModal()">Manage all models →</a>
- </div>
-
- <!-- Mode bar — segmented chip strip. Lifted OUT of #genForm so it
- stays visible when the user switches to Image Studio (which hides
- #genForm). Without this, once a user clicks Studio they had no
- way back to T2V/I2V short of refreshing. The hidden #mode input
- stays inside #genForm (further below) so the video form's
- FormData picks it up. The element keeps id=modeGroup and each
- chip keeps data-mode + .pill-btn (alongside .mode-chip) so the
- existing setMode() click wiring keeps working unchanged. -->
- <div class="mode-bar pill-group" id="modeGroup">
- <button type="button" class="mode-chip pill-btn" data-mode="t2v">Text<span class="mc-sub sub">prompt → video</span></button>
- <button type="button" class="mode-chip pill-btn" data-mode="i2v">Image<span class="mc-sub sub">image + prompt</span></button>
- <button type="button" class="mode-chip pill-btn" data-mode="keyframe">FFLF<span class="mc-sub sub">first + last</span></button>
- <button type="button" class="mode-chip pill-btn" data-mode="extend">Extend<span class="mc-sub sub">continue a clip</span></button>
- <button type="button" class="mode-chip pill-btn" data-mode="image" title="Open Image Studio — generate stills (Qwen-Image-Edit-2511 multi-ref + others)">Studio<span class="mc-sub sub">stills + library</span></button>
- <!-- "Train" used to live here as a mode chip; it's been promoted to a
- workflow tier (top tab strip, alongside Manual / Agentic Flows)
- because training is a different category than rendering. -->
- </div>
-
- <form id="genForm">
- <input type="hidden" name="preset_label" id="preset_label" value="">
- <input type="hidden" name="mode" id="mode" value="t2v">
- <input type="hidden" name="quality" id="quality" value="balanced">
- <input type="hidden" name="accel" id="accel" value="off">
- <input type="hidden" name="temporal_mode" id="temporal_mode" value="native">
- <input type="hidden" name="upscale" id="upscale" value="fit_720p">
-
- <div id="warnBanner" class="warn-banner"></div>
-
- <!-- ============== COMPOSER CARD ==============
- Hero element of the form. Carries the reference picker(s)
- (mode-conditional), the prompt textarea, and an inline tools
- strip (Enhance + HDR + No-music + Avoid disclosure). One
- elevated surface so the prompt reads as the primary input. -->
- <div class="composer-card">
- <!-- Slot for the mode-conditional reference pickers. Each
- .mode-only block is shown/hidden by setMode(); when none are
- active (T2V), the slot collapses (CSS :empty/:not(.show)). -->
- <div class="composer-refs">
- <!-- I2V — single image ref. -->
- <div class="mode-only" id="imageSection">
- <h2>Reference image</h2>
- <div class="picker" data-key="image">
- <div class="picker-drop" id="picker_drop_image">
- <div class="picker-empty">
- <div class="picker-icon"><svg class="ph"><use href="#ph-image"/></svg></div>
- <div class="picker-cta">Drop image here, or <strong>click to browse</strong></div>
- <div class="hint">PNG / JPG / WEBP — auto cover-crop to model size</div>
- </div>
- <img class="picker-preview" id="picker_preview_image" alt="" style="display:none">
- <button type="button" class="picker-clear" id="picker_clear_image" title="Clear" style="display:none"><svg class="ph" aria-hidden="true"><use href="#ph-x-bold"/></svg></button>
- </div>
- <input type="file" id="picker_file_image" accept="image/*" style="display:none">
- <input type="hidden" name="image" id="image" value="">
- <div class="picker-recent" id="picker_recent_image_wrap" style="display:none">
- <div class="picker-recent-label">Recent uploads · click to use</div>
- <div class="picker-recent-strip" id="picker_recent_image"></div>
- </div>
- </div>
- </div>
-
- <!-- FFLF — start + end pickers. -->
- <div class="mode-only" id="keyframeSection">
- <h2>Start frame (frame 0)</h2>
- <div class="picker" data-key="start_image">
- <div class="picker-drop" id="picker_drop_start_image">
- <div class="picker-empty">
- <div class="picker-icon"><svg class="ph"><use href="#ph-film-strip"/></svg></div>
- <div class="picker-cta">Drop the <strong>first frame</strong>, or <strong>click to browse</strong></div>
- <div class="hint">This image opens the clip — its aspect picks the output dimensions.</div>
- </div>
- <img class="picker-preview" id="picker_preview_start_image" alt="" style="display:none">
- <button type="button" class="picker-clear" id="picker_clear_start_image" title="Clear" style="display:none"><svg class="ph" aria-hidden="true"><use href="#ph-x-bold"/></svg></button>
- </div>
- <input type="file" id="picker_file_start_image" accept="image/*" style="display:none">
- <input type="hidden" name="start_image" id="start_image" value="">
- <div class="picker-recent" id="picker_recent_start_image_wrap" style="display:none">
- <div class="picker-recent-label">Recent uploads · click to use</div>
- <div class="picker-recent-strip" id="picker_recent_start_image"></div>
- </div>
- </div>
-
- <h2 style="margin-top:10px">End frame (last frame)</h2>
- <div class="picker" data-key="end_image">
- <div class="picker-drop" id="picker_drop_end_image">
- <div class="picker-empty">
- <div class="picker-icon"><svg class="ph"><use href="#ph-target"/></svg></div>
- <div class="picker-cta">Drop the <strong>last frame</strong>, or <strong>click to browse</strong></div>
- <div class="hint">A close-up here anchors face identity through the clip.</div>
- </div>
- <img class="picker-preview" id="picker_preview_end_image" alt="" style="display:none">
- <button type="button" class="picker-clear" id="picker_clear_end_image" title="Clear" style="display:none"><svg class="ph" aria-hidden="true"><use href="#ph-x-bold"/></svg></button>
- </div>
- <input type="file" id="picker_file_end_image" accept="image/*" style="display:none">
- <input type="hidden" name="end_image" id="end_image" value="">
- <div class="picker-recent" id="picker_recent_end_image_wrap" style="display:none">
- <div class="picker-recent-label">Recent uploads · click to use</div>
- <div class="picker-recent-strip" id="picker_recent_end_image"></div>
- </div>
- </div>
-
- <div class="hint" style="margin-top:8px">FFLF needs Q8 (auto-selects High quality). The model interpolates between the two frames you provide.</div>
- </div>
-
- <!-- Extend — source-video select + extend-by + direction +
- extend-mode preset. Lives inside the composer card so the
- prompt sits below the source picker, mirroring the I2V flow. -->
- <div class="mode-only" id="extendSection">
- <h2>Source video</h2>
- <select id="extendSrcSelect" onchange="document.getElementById('video_path').value=this.value"></select>
- <input name="video_path" id="video_path" placeholder="/path/to/source.mp4" style="margin-top:6px">
- <div class="row" style="margin-top:8px">
- <div>
- <label class="lbl">Extend by (seconds)</label>
- <!-- min must align to step from value=2: with min=0.4 step=0.5 the
- valid sequence is 0.4, 0.9, 1.4, 1.9, 2.4… — `2` is OFF the
- grid. Chrome blocks the entire form submission silently when
- ANY input fails validation, even hidden ones in inactive
- modes. Generate appeared dead until cocktailpeanut diagnosed
- it. With min=0.5 the sequence is 0.5, 1.0, 1.5, 2.0… and
- value=2 is valid. -->
- <input id="extend_seconds" type="number" value="2" min="0.5" max="10" step="0.5">
- <input type="hidden" name="extend_frames" id="extend_frames" value="6">
- <div class="hint" id="extendDurationHint" style="margin-top:4px">≈ 2.0 s of new content (6 latent frames × 8 video frames at 24 fps)</div>
- </div>
- <div>
- <label class="lbl">Direction</label>
- <select name="extend_direction" id="extend_direction">
- <option value="after" selected>After</option>
- <option value="before">Before</option>
- </select>
- </div>
- </div>
- <label class="lbl" style="margin-top:10px">Extend mode</label>
- <div class="pill-group cols-2" id="extendModeGroup">
- <button type="button" class="pill-btn active" data-extend-mode="fast"><span>Fast</span><span class="sub">~16 min · 12 steps · 64 GB safe</span></button>
- <button type="button" class="pill-btn" data-extend-mode="quality"><span>Quality</span><span class="sub">~38 min · 30 steps · 96+ GB</span></button>
- </div>
- <input type="hidden" name="extend_steps" id="extend_steps" value="12">
- <input type="hidden" name="extend_cfg" id="extend_cfg" value="1.0">
- <div class="hint">Each latent ≈ 8 frames (~0.33s). Quality mode runs the upstream defaults but pushes 1280×704 into swap on 64 GB Macs (~2 hr/render). Stick with Fast unless you've got more RAM.</div>
- </div>
- </div>
-
- <!-- Prompt — hero textarea. No h2 (the composer-card itself
- announces "this is where you compose"). Audio-cue placeholder
- is the only nudge users get to describe the soundscape;
- documented in the LTX 2.3 paper but unobvious. -->
- <textarea name="prompt" id="prompt" class="composer-prompt"
- placeholder="Describe the scene AND the sound — e.g. wizard in a forest clearing, fireflies spiraling up · low whispered chant, ember crackle, distant owl. Audio is generated jointly with video; without sound cues the model outputs near-silent ambient."></textarea>
-
- <!-- Tools strip — Enhance + HDR + No-music + Avoid disclosure.
- All inline so they read as part of composing the prompt.
- Avoid is now a toggle-disclosure (collapsed by default) — it's
- optional and most users won't touch it. -->
- <div class="composer-tools">
- <button type="button" class="ghost-btn" id="enhanceBtn" onclick="enhancePrompt()" title="Use Gemma to rewrite your prompt in the style LTX 2.3 was trained on"><svg class="ph" aria-hidden="true" style="margin-right:6px"><use href="#ph-sparkle-fill"/></svg>Enhance</button>
- <button type="button" class="ct-link" id="avoidToggleBtn" onclick="toggleAvoidRow()" title="Add 'avoid' / negative prompt — things the model should NOT generate">
- <span id="avoidToggleLabel">Avoid +</span>
- </button>
- <span class="ct-spacer"></span>
- <label class="toggle-pill" id="hdrPill"
- title="Boost dynamic range and color depth. Implemented as the official Lightricks HDR LoRA fused into the transformer. First HDR job spawns a one-time download (~120 MB) of the LoRA weights from Hugging Face, then renders share the cache.">
- <input type="checkbox" id="hdr" name="hdr">
- <span class="toggle-dot"></span>
- <span>HDR</span>
- </label>
- <label class="toggle-pill" id="noMusicPill"
- title="When on, the prompt is augmented with: 'Audio: voice and ambient sounds only, no music, no soundtrack, no score.' Useful for clips you'll score yourself in post — music can't be cleanly removed afterwards.">
- <input type="checkbox" id="noMusic" name="no_music">
- <span class="toggle-dot"></span>
- <span>No music</span>
- </label>
- </div>
- </div>
-
- <!-- Avoid (negative prompt) — collapsed by default; toggled by the
- Avoid + button inside the composer-tools strip. Lives outside
- the composer card so the textarea has its own framed surface
- and the composer card stays focused on the positive prompt. -->
- <div class="avoid-row" id="avoidRow">
- <label class="avoid-label" for="negative_prompt">
- <span>Avoid</span>
- <span class="avoid-hint">things the model should NOT generate</span>
- </label>
- <textarea class="avoid-textarea" name="negative_prompt" id="negative_prompt" placeholder="blurry hands, distorted fingers, extra fingers, smeared face, warped text"></textarea>
- </div>
-
- <!-- ============== QUICK SETTINGS ==============
- Quality picker (compact 4-up segmented strip) + Duration +
- Frames + Seed in one dense block. Everything more advanced
- (aspect, dims, speed, long-clips, export, audio source,
- open-when-done) is folded into the Customize disclosure below. -->
- <div class="quick-settings">
- <div>
- <div class="qs-label">
- <span class="qs-name">Quality</span>
- <span class="qs-meta" id="qualityMeta"></span>
- </div>
- <!-- Compact 4-col strip. Each chip carries name + a single spec
- line. Same data-quality wiring as before so setQuality()
- keeps working unchanged. The .pill-btn class is preserved
- for the click handler that filters by it. -->
- <div class="quality-strip pill-group" id="qualityGroup">
- <button type="button" class="q-chip pill-btn pill-quality" data-quality="quick">
- <span class="ql-name">Quick</span>
- <span class="q-spec ql-spec sub">640×480</span>
- <span class="ql-tier" hidden>Q4 · any Mac</span>
- </button>
- <button type="button" class="q-chip pill-btn pill-quality active" data-quality="balanced">
- <span class="ql-name">Balanced</span>
- <span class="q-spec ql-spec sub">1024×576</span>
- <span class="ql-tier" id="balancedSub">Q4 · 5 min</span>
- </button>
- <button type="button" class="q-chip pill-btn pill-quality" data-quality="standard">
- <span class="ql-name">Standard</span>
- <span class="q-spec ql-spec sub">1280×704</span>
- <span class="ql-tier" hidden>Q4 · standard tier+</span>
- </button>
- <button type="button" class="q-chip pill-btn pill-quality disabled" data-quality="high" id="qualityHigh">
- <span class="ql-name">High</span>
- <span class="q-spec ql-spec sub" id="highSpec">1024×576</span>
- <span class="ql-tier" id="highSub">Q8 not installed</span>
- </button>
- </div>
- </div>
-
- <div class="mode-only show" id="quickMetricsRow">
- <div class="mini-fields">
- <div class="mf-cell">
- <span class="mf-label">Duration (s)</span>
- <input id="duration" value="5" type="number" min="1" max="20" step="1">
- </div>
- <div class="mf-cell">
- <span class="mf-label">Frames <span class="mf-hint">8k+1</span></span>
- <input name="frames" id="frames" value="121" type="number" min="1" title="Must be 8k+1 (e.g., 121, 161, 201). Duration auto-syncs.">
- </div>
- <div class="mf-cell">
- <span class="mf-label">Seed <span class="mf-hint">-1 = random</span></span>
- <input name="seed" id="seed" value="-1" title="-1 picks a fresh random seed per render. Any integer locks the seed for repeatable output.">
- </div>
- </div>
- </div>
- </div>
-
- <!-- LoRA picker — UNIFIED across video form + Image Studio.
- Lives inside #genForm by default (so the video form's FormData
- picks up the hidden #lorasJson on submit), but on
- setMode('image') the JS portals the visible <details> over to
- #loraPickerStudioSlot so the SAME picker renders inside the
- Studio composer. One source of truth: _activeLoras + the same
- hidden #lorasJson field. The picker's library list is
- filtered by /loras?mode=<tag> based on the current (mode +
- engine) selection — see refreshLoras() in JS for the mapping.
-
- Collapsible because most users won't touch it on a given
- session, and inline because hiding it behind a modal makes
- it easy to forget. Default open so first-time users see what's
- inside without hunting for the disclosure triangle. -->
- <div class="form-divider"></div>
- <div id="loraPickerVideoSlot">
- <details id="lorasDetails" open class="loras-section">
- <summary class="loras-summary">
- <span class="loras-chevron" aria-hidden="true"><svg class="ph"><use href="#ph-caret-down-bold"/></svg></span>
- <span class="loras-title">LoRAs</span>
- <span class="loras-meta" id="lorasSummaryCount">none active</span>
- <!-- Action buttons live in the header so they're visible
- regardless of how far the user has scrolled inside the
- LoRA list. Rescan is icon-only (the ↻ glyph reads as
- refresh universally); Browse CivitAI is the primary CTA
- for adding new LoRAs so it's a coloured button.
- event.stopPropagation() keeps clicks from toggling the
- <details> open/closed state. -->
- <span class="loras-header-actions">
- <button type="button" class="loras-icon-btn"
- title="Rescan mlx_models/loras/ for new files"
- onclick="event.stopPropagation(); event.preventDefault(); refreshLoras()"><svg class="ph" aria-hidden="true"><use href="#ph-arrow-clockwise-bold"/></svg></button>
- <button type="button" class="loras-browse-btn"
- onclick="event.stopPropagation(); event.preventDefault(); openCivitaiModal()"><svg class="ph" aria-hidden="true" style="margin-right:6px;vertical-align:-2px"><use href="#ph-magnifying-glass"/></svg>Browse CivitAI</button>
- </span>
- </summary>
- <div class="loras-body" id="lorasBody">
- <!-- Mode/engine context banner — shows the active filter so
- the user understands why some library entries are
- hidden when they switch engine in Image Studio. -->
- <div class="lora-mode-banner hint" id="loraModeBanner"
- style="margin: 0 0 6px 0; font-size: 11px;"></div>
- <!-- Filter/search box. Shows up only when 5+ LoRAs are
- installed; below that it's just visual noise. Filters by
- name AND trigger words (case-insensitive substring). -->
- <div id="lorasFilterRow" style="display:none;">
- <input type="text" id="lorasFilter" class="lora-filter"
- placeholder="Filter LoRAs… (name or trigger word)"
- oninput="renderLorasList()">
- </div>
- <div class="hint" id="lorasEmpty">
- Drop <code>.safetensors</code> files into <code id="lorasDir">mlx_models/loras/</code>
- to use them, or click <strong>Browse CivitAI</strong> above.
- Each LoRA picks up an optional sidecar <code>.json</code> with
- name + trigger words + recommended strength.
- </div>
- <div class="loras-list" id="lorasList"></div>
- </div>
- </details>
- </div>
- <div class="form-divider"></div>
- <!-- Hidden field; updated by the LoRA picker JS to a JSON-encoded
- array of {path, strength} that make_job parses. STAYS inside
- #genForm even when the visible <details id="lorasDetails"> is
- portaled over to the Studio slot — the video form's FormData
- still needs to pick it up on submit. Image Studio submits go
- through imgStudioGenerate() which reads _activeLoras directly
- and attaches a `loras` field manually. -->
- <input type="hidden" id="lorasJson" name="loras" value="">
-
- <input type="hidden" name="steps" id="steps" value="8">
-
- <!-- ============== UNIFIED CUSTOMIZE DISCLOSURE ==============
- Folds together the old "Customize" (aspect, dims, speed,
- long-clips, export, method) and "Advanced" (audio source,
- open-when-done) into ONE collapsed disclosure. Power users
- open it; beginners ignore it. The summary line shows the
- effective state so power users can scan at a glance.
-
- Lives at form level (not mode-conditional) — its inner rows
- manage their own visibility (e.g. dimsRow hides in I2V flows;
- i2vAudioModeSection only shows for I2V; method only shows
- when an upscale is active). The wrapping #sizingSection
- class kept for the mode-only show/hide that still toggles
- it for Extend (Extend supplies its own duration/etc). -->
- <div class="mode-only" id="sizingSection">
- <details id="customizeDetails" class="customize-section">
- <summary class="cz-summary">
- <span class="cz-chevron" aria-hidden="true"><svg class="ph"><use href="#ph-caret-down-bold"/></svg></span>
- <span class="cz-title">Customize</span>
- <span class="cz-meta" id="customizeSummary">16:9 · default speed</span>
- </summary>
- <div class="cz-body">
- <!-- Aspect — only relevant when the active Quality preset has
- multiple aspects (Standard / High at 1280×704 vs 704×1280).
- Hidden when Quick is active (640×480 is 4:3 only). -->
- <div id="aspectRow" class="cz-control">
- <div class="cz-label">Aspect ratio</div>
- <div class="pill-group cols-2" id="aspectGroup">
- <button type="button" class="pill-btn active" data-aspect="landscape"><span>16 : 9</span><span class="sub">horizontal</span></button>
- <button type="button" class="pill-btn" data-aspect="vertical"><span>9 : 16</span><span class="sub">vertical</span></button>
- </div>
- <input type="hidden" id="aspect" value="landscape">
- </div>
-
- <!-- Width × height. Setting custom dimensions makes the form
- leave the active preset (the Quality pill stays highlighted
- but the Customize summary shows "custom" so the user knows
- they've deviated). -->
- <div id="dimsRow" class="cz-control">
- <div class="cz-label">Width × height</div>
- <div class="row">
- <div><input name="width" id="width" value="1024" type="number" min="32" step="32" aria-label="Width"></div>
- <div><input name="height" id="height" value="576" type="number" min="32" step="32" aria-label="Height"></div>
- </div>
- </div>
-
- <!-- Speed — experimental sampler acceleration. Boost/Turbo
- skip 2-3 stable middle denoise calls. Off at High quality
- (the two-stage HQ sampler doesn't support skipping). -->
- <div class="cz-control">
- <div class="cz-label">Speed
- <span class="cz-label-hint">experimental — skip stable denoise steps</span>
- </div>
- <div class="pill-group cols-3" id="accelGroup">
- <button type="button" class="pill-btn active" data-accel="off"><span>Exact</span><span class="sub">full sampler</span></button>
- <button type="button" class="pill-btn" data-accel="boost"><span>Boost</span><span class="sub">~10-15% faster</span></button>
- <button type="button" class="pill-btn" data-accel="turbo"><span>Turbo</span><span class="sub">~20-25% faster</span></button>
- </div>
- </div>
-
- <!-- Long Clip Boost — asks LTX 2.3 to generate fewer semantic
- frames at 12fps, then exports a normal 24fps file with
- motion interpolation. This is explicit because dialogue,
- lip-sync, and fast motion need user judgment. -->
- <div class="cz-control" id="temporalRow">
- <div class="cz-label">Long clips
- <span class="cz-label-hint">experimental temporal interpolation</span>
- </div>
- <div class="pill-group cols-2" id="temporalGroup">
- <button type="button" class="pill-btn active" data-temporal="native"><span>Native</span><span class="sub">24fps from LTX</span></button>
- <button type="button" class="pill-btn" data-temporal="fps12_interp24"><span>12 → 24fps</span><span class="sub">half frames · interpolated</span></button>
- </div>
- </div>
-
- <!-- Export upscale — target dims after render. "720p fit"
- preserves aspect ratio (no crop, no distortion). 2× doubles
- each side. Native skips the upscale entirely. The "Method"
- row below picks how the upscaling is done. -->
- <div class="cz-control">
- <div class="cz-label">Export
- <span class="cz-label-hint">post-render, no crop</span>
- </div>
- <div class="pill-group cols-3" id="upscaleGroup">
- <button type="button" class="pill-btn active" data-upscale="off"><span>Native</span><span class="sub">as generated</span></button>
- <button type="button" class="pill-btn" data-upscale="fit_720p"><span>720p fit</span><span class="sub">scale + pad</span></button>
- <button type="button" class="pill-btn" data-upscale="x2"><span>2×</span><span class="sub">same ratio</span></button>
- </div>
- </div>
-
- <!-- Upscale method. Hidden when Export = Native. Fast = ffmpeg
- Lanczos resize, no detail recovery, near-instant. Sharp =
- PiperSR/CoreML 2× post-upscale on Apple Neural Engine, then
- ffmpeg fit/export. The old LTX latent upscaler path remains
- hidden behind LTX_ENABLE_MODEL_UPSCALE for lab archaeology. -->
- <div class="cz-control" id="upscaleMethodRow" style="display:none;">
- <div class="cz-label">Method
- <span class="cz-label-hint">how the upscale is done</span>
- </div>
- <div class="pill-group cols-2" id="upscaleMethodGroup">
- <button type="button" class="pill-btn active" data-method="lanczos"><span>Fast</span><span class="sub">ffmpeg Lanczos · instant</span></button>
- <button type="button" class="pill-btn" data-method="pipersr"><span>Sharp</span><span class="sub">PiperSR ANE · +30-90 s</span></button>
- </div>
- <input type="hidden" name="upscale_method" id="upscale_method" value="lanczos">
- </div>
-
- <!-- Audio source (I2V only) — folded in from the old separate
- Advanced disclosure. Picker auto-hides when the current
- mode isn't I2V (see updateDerived's mode-aware visibility). -->
- <div class="cz-control mode-only" id="i2vAudioModeSection">
- <div class="cz-label">I2V audio source
- <span class="cz-label-hint">joint or external</span>
- </div>
- <select id="i2vMode">
- <option value="i2v" selected>Joint audio (LTX generates audio synced with the visual)</option>
- <option value="i2v_clean_audio">Use external audio file (mux it onto LTX video)</option>
- </select>
- <div class="mode-only" id="audioSection" style="margin-top:8px">
- <label class="lbl">Audio file path</label>
- <input name="audio" id="audio" placeholder="/path/to/your/track.wav">
- </div>
- </div>
-
- <!-- Open file when done — minor convenience. Was its own row
- in the old Advanced disclosure; now folded inline. -->
- <div class="cz-control">
- <label class="check" style="margin:0">
- <input type="checkbox" name="open_when_done" id="open_when_done"> Open file when done
- </label>
- </div>
- </div>
- </details>
-
- <div class="derived" id="derived"></div>
- </div>
-
- <!-- Comfy-kill toggle. Hidden in DOM by default; shown only when the
- panel detects ComfyUI actually running on this Mac (see updateUI
- in the poll handler). Default-off for public installs: killing a
- neighboring Pinokio app should be an explicit choice, even when it
- can free a lot of memory on 64 GB machines. -->
- <div id="comfyKillRow" class="comfy-row" style="display:none">
- <label class="lbl" style="display:flex; align-items:center; gap:8px; cursor:pointer">
- <input type="checkbox" name="stop_comfy" id="stop_comfy" value="on">
- <span>Stop ComfyUI before render <span style="color:var(--muted)">(optional · can free ~27 GB)</span></span>
- </label>
- </div>
-
- <!-- ============== STICKY ACTION FOOTER ==============
- Generate stays anchored at the bottom of the form-pane no
- matter how far the user scrolls. The queue chip strip sits
- above it (Batch / Pause / Clear) — compact pills, never the
- primary touch target. -->
- <div class="form-action-footer" id="formActionFooter">
- <div class="queue-strip">
- <button type="button" class="qchip" onclick="openBatch()" title="Paste many prompts at once and queue them">⊞ Batch</button>
- <button type="button" class="qchip" id="pauseBtn" onclick="togglePause()" title="Pause / resume the render queue"><svg class="ph" aria-hidden="true" style="margin-right:6px;vertical-align:-2px"><use href="#ph-pause-fill"/></svg>Pause queue</button>
- <button type="button" class="qchip" onclick="api('/queue/clear','POST').then(poll)" title="Clear all queued jobs (running job continues)"><svg class="ph" aria-hidden="true" style="margin-right:6px;vertical-align:-2px"><use href="#ph-x"/></svg>Clear</button>
- <span class="qchip-spacer"></span>
- <span class="qchip-derived" id="derivedFooter"></span>
- </div>
- <div class="actions">
- <button type="submit" class="primary" id="genBtn">Generate</button>
- <button type="button" class="danger" onclick="api('/stop', 'POST').then(poll)">Stop</button>
- </div>
- </div>
- </form>
-
- <!-- ============== IMAGE STUDIO (inline, mode='image') ============== -->
- <!-- Sibling of #genForm inside form-pane. Shown/hidden by setMode().
- Lives outside the form so its prompt textarea doesn't submit the
- video form on Enter. The right rail (queue · current · history)
- to the right of form-pane stays visible during image gen. -->
- <!-- Restyled to mirror the video form-pane: same h2 mono-uppercase
- section labels, same hairline-bordered input chrome, same picker
- idiom for ref slots, same dense 2-col field grid for engine /
- aspect / n / seed, and a Generate row with an inline wall-time
- estimate that updates as the user changes engine + n + aspect.
- An engine-status pill on the engine row tells the user whether
- the chosen engine's weights are cached locally or need a fresh
- download — driven by /image/engine_status (server-side cache
- probe via _repo_hf_cache_dir). -->
- <div class="mode-only studio-pane" id="studioSection">
- <!-- ============== STUDIO COMPOSER CARD ==============
- Same composer-card chrome as the video form. Refs (3 multi-ref
- slots) sit at the top, the prompt is the hero, and the engine /
- aspect / n / seed live in the Quick Settings strip below.
- Generate sticks at the bottom (sticky footer) so it's always
- one click away regardless of how far the user scrolls. -->
- <div class="composer-card">
- <div class="composer-refs">
- <div class="show">
- <h2>Reference images
- <span class="h2-hint">multi-ref · Qwen-Image-Edit-2511 / FLUX.2 Klein-Edit only</span>
- </h2>
- <div class="studio-ref-grid" id="imgStudioRefs">
- <div class="studio-ref-slot" data-slot="0">
- <span class="ref-tag">Primary</span>
- </div>
- <div class="studio-ref-slot" data-slot="1">
- <span class="ref-tag">Multi-ref</span>
- </div>
- <div class="studio-ref-slot" data-slot="2">
- <span class="ref-tag">Multi-ref</span>
- </div>
- </div>
- <!-- Mirrors the video I2V picker's "Recent uploads · click to use"
- strip. Click a thumb → fills the next empty ref slot. Hidden
- when /uploads is empty. -->
- <div class="studio-ref-recent" id="imgStudioRecentWrap" style="display:none">
- <div class="studio-ref-recent-label">Recent uploads · click to use</div>
- <div class="studio-ref-recent-strip" id="imgStudioRecentStrip"></div>
- </div>
- </div>
- </div>
-
- <textarea id="imgStudioPrompt" class="composer-prompt" rows="4"
- placeholder="A cinematic medium close-up of a woman in a sunlit kitchen, soft morning light through blinds, shallow depth of field, photorealistic"></textarea>
- </div>
-
- <!-- Validation / status messages (e.g. "pick a ref image"). Lives
- OUTSIDE the composer card so the card chrome stays focused on
- composing. Empty by default. -->
- <div class="studio-status-row" style="margin: 6px 0 -4px;">
- <span id="imgStudioStatus" class="hint"></span>
- </div>
-
- <!-- Quick settings — Engine on its own row (long labels), then a
- dense 3-up row for Aspect / Candidates / Seed. Wall-time
- estimate sits below the strip in the muted derived style. -->
- <div class="quick-settings">
- <div>
- <div class="qs-label">
- <span class="qs-name">Engine</span>
- <span class="qs-meta" id="imgStudioWallEstimate"></span>
- </div>
- <div class="studio-engine-row">
- <select id="imgStudioEngine" onchange="imgStudioUpdateValidity();imgStudioRefreshEngineStatus();imgStudioUpdateEstimate();if(typeof renderLorasList==='function')renderLorasList()">
- <option value="auto">Auto (use Settings)</option>
- <option value="qwen_edit_lightning_inline" selected>Qwen Fast (Lightning &middot; 4-step Q6 + FBCache, ~1:20 / image, multi-ref)</option>
- <option value="qwen_edit_inline">Qwen Medium (8-step Q6 + FBCache, ~2:05 / image, multi-ref)</option>
- <option value="qwen_edit_high_inline">Qwen Quality (40-step Q8 + CFG 4.0 + FBCache, ~3:50 / image, multi-ref)</option>
- <option value="hidream_fast_inline">HiDream Fast (3-step, ~3:45 / 4-img batch, slight bg softness)</option>
- <option value="hidream_inline">HiDream Medium (6-step + FBCache, ~6 min / 4-img batch, character-preserving)</option>
- <option value="hidream_quality_inline">HiDream Quality (12-step + light FBCache, ~9 min / 4-img batch, best detail)</option>
- <option value="mock_inline" id="imgStudioMockOption" hidden>Mock (testing — debug only)</option>
- </select>
- <span class="engine-status-pill" id="imgStudioEnginePill"
- data-state="unknown" title="Checking engine weights…"
- onclick="imgStudioOnPillClick()">…</span>
- </div>
- </div>
-
- <div>
- <div class="mini-fields">
- <div class="mf-cell">
- <span class="mf-label">Aspect</span>
- <select id="imgStudioAspect" onchange="imgStudioUpdateEstimate()" style="padding:7px 9px;font-size:13px;">
- <option value="16:9" selected>16:9 — 1280×720</option>
- <option value="4:3">4:3 — 1024×768</option>
- <option value="1:1">1:1 — 1024×1024</option>
- <option value="9:16">9:16 — 720×1280</option>
- <option value="3:4">3:4 — 768×1024</option>
- <option value="21:9">21:9 — 1280×544</option>
- </select>
- </div>
- <div class="mf-cell">
- <span class="mf-label">Candidates (n)</span>
- <input type="number" id="imgStudioN" min="1" max="8" value="4" oninput="imgStudioUpdateEstimate()">
- </div>
- <div class="mf-cell">
- <span class="mf-label">Seed</span>
- <input type="number" id="imgStudioSeed" value="-1" title="-1 = random">
- </div>
- </div>
- </div>
- </div>
-
- <!-- Slot for the unified LoRA picker. Empty by default; setMode('image')
- portals #lorasDetails into here so the SAME picker the video form
- uses appears tightly integrated under the Image Studio composer.
- When the user switches engine (e.g. Qwen-Edit → FLUX.2 Klein-Edit)
- the library auto-refilters via /loras?mode=image:flux2. Active
- chips that don't match the current engine get a warning badge. -->
- <div id="loraPickerStudioSlot"></div>
-
- <!-- Sticky action footer — same chrome as the video form's. Generate
- stays anchored at the bottom of the form-pane no matter how far
- the user has scrolled. Pause/Clear/Batch live above it as compact
- pills, never the primary touch target. -->
- <div class="form-action-footer" id="formActionFooterStudio">
- <div class="queue-strip">
- <button type="button" class="qchip" onclick="openBatch()" title="Paste many prompts at once and queue them">⊞ Batch</button>
- <button type="button" class="qchip" id="pauseBtnStudio" onclick="togglePause()" title="Pause / resume the render queue"><svg class="ph" aria-hidden="true" style="margin-right:6px;vertical-align:-2px"><use href="#ph-pause-fill"/></svg>Pause queue</button>
- <button type="button" class="qchip" onclick="api('/queue/clear','POST').then(poll)" title="Clear all queued jobs (running job continues)"><svg class="ph" aria-hidden="true" style="margin-right:6px;vertical-align:-2px"><use href="#ph-x"/></svg>Clear</button>
- <span class="qchip-spacer"></span>
- </div>
- <div class="actions">
- <button class="primary" id="imgStudioGenBtn" onclick="imgStudioGenerate()">
- <span id="imgStudioGenBtnLabel">Generate</span>
- </button>
- <button type="button" class="danger" onclick="api('/stop', 'POST').then(poll)">Stop</button>
- </div>
- </div>
-
- <!-- Submission status. Image jobs flow through the same queue as
- video jobs now, so the actual results show up in the right-rail
- Recent tab (with the Photos filter) along with everything else.
- This pane is just a thin "submitted" confirmation. -->
- <div id="imgStudioResults" class="studio-results"></div>
- </div>
-
- <!-- ============== TRAIN CHARACTER (inline, mode='train') ============== -->
- <!-- Sibling of #genForm and #studioSection inside form-pane. Shown by
- setMode('train'). Trains a character LoRA against 15-50 user
- stills. Pipeline lives in the sibling lora-lab repo; this panel
- shells out to it via /train/start. Job status surfaces through
- the existing Now / Queue / Recent / Logs panes (training is just
- another mode dispatch in run_job_inner). -->
- <div class="mode-only train-pane" id="trainSection">
-
- <!-- Preflight model check — hidden by default; populated by
- trainCheckPreflight() if any required model file is missing
- (today: transformer-dev.safetensors which isn't in default install). -->
- <div id="trainPreflight" style="display:none"></div>
-
- <!-- ============== DATASET CARD ============== -->
- <div class="composer-card train-card">
- <h2>Dataset
- <span class="h2-hint">15-50 stills · drop your character into the box</span>
- </h2>
- <div class="train-drop" id="trainDrop">
- <div class="train-drop-empty" id="trainDropEmpty">
- <div class="picker-icon"><svg class="ph"><use href="#ph-image"/></svg></div>
- <div class="picker-cta">Drop 15-50 images here, or <strong>click to browse</strong></div>
- <div class="hint">PNG / JPG / WEBP. Each preview shows the 1:1 center-crop the trainer will see.</div>
- </div>
- <div class="train-thumbs" id="trainThumbs" hidden></div>
- <input type="file" id="trainFileInput" accept="image/png,image/jpeg,image/webp" multiple style="display:none">
- </div>
- <div class="train-counter-row">
- <span class="train-counter" id="trainCounter">0 / 50 images</span>
- <span class="train-counter-hint" id="trainCounterHint">need at least 15 to train</span>
- <span class="qchip-spacer"></span>
- <button type="button" class="qchip" id="trainClearAllBtn" onclick="trainClearAll()" hidden><svg class="ph" aria-hidden="true" style="margin-right:6px;vertical-align:-2px"><use href="#ph-x"/></svg>Clear all</button>
- </div>
- </div>
-
- <!-- ============== TRIGGER + PRESET ============== -->
- <div class="composer-card train-card">
- <h2>Trigger word
- <span class="h2-hint">a rare token the model will associate with this character</span>
- </h2>
- <div class="train-trigger-row">
- <input type="text" id="trainTrigger" maxlength="32" placeholder="auto-generated rare token" autocomplete="off">
- <button type="button" class="qchip" onclick="trainSuggestTrigger()" title="Suggest a fresh rare token">↻ Suggest</button>
- </div>
- <div class="hint">Use the trigger word in your video prompts (e.g. <code><span id="trainTriggerExample">mrz07</span> man walking on the beach</code>).</div>
-
- <h2 style="margin-top:14px">Quality preset
- <span class="h2-hint">trade time for fidelity</span>
- </h2>
- <div class="pill-group cols-3" id="trainPresetGroup">
- <button type="button" class="pill-btn active" data-train-preset="quick"><span>Quick <span class="rec-badge">Recommended</span></span><span class="sub" id="trainPresetQuickSub">~30 min · rank 8 · 512px</span></button>
- <button type="button" class="pill-btn" data-train-preset="medium"><span>Medium</span><span class="sub" id="trainPresetMediumSub">~2 h · rank 16 · 576px</span></button>
- <button type="button" class="pill-btn" data-train-preset="high"><span>High</span><span class="sub" id="trainPresetHighSub">~4 h · rank 32 · 768px</span></button>
- </div>
-
- <details class="train-advanced">
- <summary>Advanced</summary>
- <div class="train-advanced-grid">
- <div class="mf-cell">
- <span class="mf-label">Rank</span>
- <select id="trainRank">
- <option value="">preset default</option>
- <option value="8">8</option>
- <option value="16">16</option>
- <option value="32">32</option>
- <option value="64">64</option>
- </select>
- </div>
- <div class="mf-cell">
- <span class="mf-label">Steps</span>
- <input type="number" id="trainSteps" min="100" max="10000" step="100" placeholder="preset default">
- </div>
- <div class="mf-cell">
- <span class="mf-label">Learning rate</span>
- <select id="trainLR">
- <option value="">preset default</option>
- <option value="0.00005">5e-5</option>
- <option value="0.0001">1e-4</option>
- <option value="0.0002">2e-4</option>
- <option value="0.0005">5e-4</option>
- </select>
- </div>
- <div class="mf-cell">
- <span class="mf-label">Resolution</span>
- <select id="trainResolution">
- <option value="">preset default</option>
- <option value="512">512²</option>
- <option value="576">576²</option>
- <option value="768">768²</option>
- </select>
- </div>
- <div class="mf-cell" style="grid-column: 1 / -1">
- <span class="mf-label">Caption strategy</span>
- <select id="trainCaptionStrategy">
- <option value="trigger_simple" selected>&lt;trigger&gt; man — dumbest-strongest default</option>
- <option value="trigger_only">trigger only — no role hint</option>
- <option value="qwen_vl" disabled>auto-caption via Qwen-VL — coming soon</option>
- </select>
- </div>
- </div>
- <div class="hint" style="margin-top:8px">Auto-captioning planned. For now, every image gets the same caption — the trigger does the heavy lifting.</div>
- </details>
- </div>
-
- <!-- Estimate strip — wall time + RAM peak update as inputs
- change. Hidden until at least one image is in the dataset:
- before that, the estimate row is misleading ("— · —" reads
- as "data missing" not "waiting on you"). Shown by
- trainRenderImagesGrid() the moment count > 0. -->
- <div class="train-estimate" id="trainEstimate" style="display:none">
- <span class="train-est-line">
- <span class="train-est-label">Estimated wall time</span>
- <span class="train-est-value" id="trainEstimateTime">—</span>
- </span>
- <span class="train-est-line">
- <span class="train-est-label">Peak RAM</span>
- <span class="train-est-value" id="trainEstimateRam">—</span>
- </span>
- <span class="train-est-line">
- <span class="train-est-label">Output</span>
- <span class="train-est-value" id="trainEstimateOut">—</span>
- </span>
- </div>
-
- <!-- Validation/status messages (e.g. "need 10 more images"). -->
- <div class="studio-status-row" style="margin: 4px 0 0;">
- <span id="trainStatus" class="hint"></span>
- </div>
-
- <!-- Sticky action footer — same chrome as the video/studio forms. -->
- <div class="form-action-footer" id="formActionFooterTrain">
- <div class="queue-strip">
- <button type="button" class="qchip" id="pauseBtnTrain" onclick="togglePause()" title="Pause / resume the queue"><svg class="ph" aria-hidden="true" style="margin-right:6px;vertical-align:-2px"><use href="#ph-pause-fill"/></svg>Pause queue</button>
- <button type="button" class="qchip" onclick="api('/queue/clear','POST').then(poll)" title="Clear all queued jobs"><svg class="ph" aria-hidden="true" style="margin-right:6px;vertical-align:-2px"><use href="#ph-x"/></svg>Clear</button>
- <span class="qchip-spacer"></span>
- </div>
- <div class="actions">
- <button type="button" class="primary" id="trainStartBtn" onclick="trainStart()" disabled>Start training</button>
- <button type="button" class="danger" onclick="api('/stop','POST').then(poll)">Stop</button>
- </div>
- </div>
-
- <!-- ============== TRAINED LORAs LIST ============== -->
- <div class="composer-card train-card">
- <h2>Trained character LoRAs
- <span class="h2-hint">your finished runs — click to use</span>
- </h2>
- <div class="train-lora-list" id="trainLoraList">
- <div class="hint" style="padding:12px 0">No trained LoRAs yet. Start your first run above.</div>
- </div>
- <div class="hint" style="margin-top:4px">Trained LoRAs land in <code id="trainLorasDir">mlx_models/loras/</code> alongside any LoRAs you've downloaded — they show up in the regular picker too.</div>
- </div>
-
- </div>
- </aside>
-
- <!-- ============== STAGE PANE: PLAYER + CAROUSEL ============== -->
- <!-- REDESIGN — Y2.001 stage-pane.
- Replaces the legacy "video → meta strip → header → two filter rows
- → carousel" stack with a composer-grade layout that mirrors the
- form-pane redesign: one elevated player surface with overlaid
- chrome, a single combined filter row, and richer carousel cards
- whose chrome lives on hover. All legacy IDs/handlers preserved
- (#playerWrap, #playerMeta, #playerName, #loadParamsBtn,
- #useAsExtendBtn, #animateBtn, #carousel, #carouselTitle,
- #mainOutputsFilter*) so the JS layer keeps working unchanged.
- (#filterAll/#filterHidden retired with the Visible/Hidden
- segmented control — orphan textContent/setFilter calls removed.) -->
- <section class="stage-pane">
- <!-- Player surface — the hero. Holds the <video>/<img>, the filename
- overlay (top), the action overlay (top-right), and an inline
- job-progress overlay (bottom) when something is rendering. The
- #playerMeta strip is preserved as a hidden a11y/data slot so
- legacy callers that read its IDs (selectOutput updates them)
- still find them — but it's never shown. -->
- <div class="player-surface">
- <div class="player-wrap empty" id="playerWrap">
- <div class="ps-empty">
- <div class="ps-empty-icon" aria-hidden="true">
- <svg width="56" height="56" viewBox="0 0 56 56" fill="none">
- <circle cx="28" cy="28" r="22" stroke="currentColor" stroke-width="1.5" stroke-opacity="0.35"/>
- <path d="M23 19 L37 28 L23 37 Z" fill="currentColor" fill-opacity="0.45"/>
- </svg>
- </div>
- <div class="ps-empty-title">No outputs yet</div>
- <div class="ps-empty-sub">Generate something on the left and the result lands here.</div>
- </div>
- </div>
- <!-- Top overlay: filename + relative time + size. Hidden until an
- output is selected; shown by selectOutput(). -->
- <div class="player-overlay-top" id="playerOverlayTop" style="display:none">
- <div class="po-name" id="playerOverlayName"></div>
- <div class="po-meta" id="playerOverlayMeta"></div>
- </div>
- <!-- Top-right action cluster. Icon buttons with tooltips replace
- the old text-button row. Each carries a data-action attribute
- that the old IDs alias to, so legacy code touching them keeps
- working (loadParamsBtn.disabled, animateBtn.style.display,
- useAsExtendBtn.style.display all still apply). -->
- <div class="player-overlay-actions" id="playerOverlayActions" style="display:none">
- <button id="loadParamsBtn" class="po-act" type="button"
- onclick="loadParams()" title="Load this clip's render params back into the form" disabled>
- <svg width="14" height="14" viewBox="0 0 16 16" fill="none" aria-hidden="true">
- <path d="M3 8 L8 13 L13 8 M8 3 L8 13" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
- </svg>
- <span class="po-act-label">Params</span>
- </button>
- <button id="useAsExtendBtn" class="po-act" type="button"
- onclick="useAsExtendSource()" title="Use this clip as the source for an Extend job">
- <svg width="14" height="14" viewBox="0 0 16 16" fill="none" aria-hidden="true">
- <path d="M3 8 L13 8 M9 4 L13 8 L9 12" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
- </svg>
- <span class="po-act-label">Extend</span>
- </button>
- <button id="animateBtn" class="po-act" type="button"
- onclick="animateActive()" style="display:none" title="Animate this still as an i2v render">
- <svg width="14" height="14" viewBox="0 0 16 16" fill="none" aria-hidden="true">
- <path d="M5 3 L13 8 L5 13 Z" stroke="currentColor" stroke-width="1.5" stroke-linejoin="round" fill="none"/>
- </svg>
- <span class="po-act-label">Animate</span>
- </button>
- <button id="expandBtn" class="po-act" type="button"
- onclick="openExpandLightbox()" title="Expand to fullscreen (Esc to close)">
- <svg width="14" height="14" viewBox="0 0 16 16" fill="none" aria-hidden="true">
- <path d="M3 6 V3 H6 M10 3 H13 V6 M13 10 V13 H10 M6 13 H3 V10"
- stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
- </svg>
- <span class="po-act-label">Expand</span>
- </button>
- <button class="po-act po-act-danger" type="button"
- onclick="hideActive()" title="Hide this output from the gallery">
- <svg width="14" height="14" viewBox="0 0 16 16" fill="none" aria-hidden="true">
- <path d="M2 8 C 4 4, 12 4, 14 8 C 12 12, 4 12, 2 8 Z M5 5 L11 11" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
- </svg>
- </button>
- </div>
- <!-- (Salo 2026-05-12: the in-player progress chip was redundant
- with the bottom Now strip, AND it covered the playing video.
- Removed entirely; bottom-pane Now card is the single source of
- truth for live + failed job state.) -->
- </div>
- <!-- Expand lightbox: full-viewport overlay shared by image + video.
- Opens via the Expand button on the player overlay actions, or by
- pressing F when an output is selected. Click outside the media or
- press Esc to close. -->
- <div class="expand-lightbox" id="expandLightbox" style="display:none"
- onclick="if(event.target===this)closeExpandLightbox()">
- <button class="expand-close" type="button" onclick="closeExpandLightbox()" title="Close (Esc)">
- <svg width="20" height="20" viewBox="0 0 20 20" fill="none" aria-hidden="true">
- <path d="M5 5 L15 15 M15 5 L5 15" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
- </svg>
- </button>
- <div class="expand-stage" id="expandStage"></div>
- <div class="expand-meta" id="expandMeta"></div>
- </div>
- <!-- Hidden compatibility slot. selectOutput() writes #playerName here
- and toggles display on #playerMeta — both kept so external code
- and tests don't break. The visible name lives in playerOverlayName. -->
- <div class="player-meta" id="playerMeta" style="display:none">
- <div class="name" id="playerName"></div>
- <div class="actions-bar"></div>
- </div>
- <!-- Combined filter + title row. One row, three regions: title +
- count, kind chips (All/Videos/Photos), visible/hidden segmented
- toggle on the right. Replaces the previous two-row stack. -->
- <div class="carousel-wrap">
- <div class="carousel-head">
- <h3 id="carouselTitle">Outputs</h3>
- <!-- Kind chips, ID + onclick names preserved. -->
- <div class="stage-outputs-filter" id="mainOutputsFilter">
- <button type="button" id="mainOutputsFilterAll" class="active"
- onclick="setMainOutputsFilter('all')">All</button>
- <button type="button" id="mainOutputsFilterVideos"
- onclick="setMainOutputsFilter('videos')">Videos</button>
- <button type="button" id="mainOutputsFilterPhotos"
- onclick="setMainOutputsFilter('photos')">Photos</button>
- </div>
- <span class="ch-spacer"></span>
- <button type="button" class="open-folder-btn" id="openOutputsFolderBtn"
- title="Reveal the outputs folder in Finder"
- aria-label="Reveal the outputs folder in Finder"
- onclick="openOutputsFolder()">
- <svg class="ph" aria-hidden="true"><use href="#ph-folder-simple"/></svg>
- </button>
- <!-- Visible/Hidden segmented control was removed: the Hide
- functionality was confusing in practice and we replaced it
- with a one-click per-card Delete + an in-place "Open folder"
- reveal here. The element is left out entirely so the seg-vh
- class loses its only consumer too (CSS still defines it for
- other segs). -->
- </div>
- <div class="carousel" id="carousel"></div>
- </div>
- </section>
-
-
- <!-- Lightbox for stage outputs — plays a finished mp4 full-size on click.
- Refine button references the playing clip in the composer so the
- user can ask the agent for a variation while watching. -->
-
-<!-- ============== CIVITAI MODAL ============== -->
-<!-- LoRA discovery + install modal. Hits /civitai/search to populate
- the grid and /civitai/download to fetch a selected LoRA into
- mlx_models/loras/ with a sidecar JSON capturing the metadata. -->
-<div id="civitaiModal" class="models-modal" style="display:none"
- role="dialog" aria-modal="true" aria-labelledby="civitaiModalTitle"
- onclick="if(event.target===this) closeCivitaiModal()">
- <div class="models-card" style="width: min(960px, 96vw)">
- <div class="models-head">
- <h2 id="civitaiModalTitle">Browse CivitAI for LTX 2.3 LoRAs</h2>
- <button class="ghost-btn" onclick="closeCivitaiModal()">Close</button>
- </div>
- <div class="models-hint">
- LoRAs land in <code id="civitaiTargetDir">mlx_models/loras/</code>
- with a sidecar JSON that carries the trigger words and recommended
- strength. The CivitAI page link stays in the sidecar for attribution.
- </div>
- <!-- Inline API-key banner. CivitAI requires a token to download LoRAs
- (even SFW ones). Three states, all rendered in the same slot by
- renderCivitaiAuthBanner():
- - missing: amber, has an input + Save button
- - set: green checkmark with a "change" link that re-shows the input
- - error: red, shown after a failed test, with re-input + retry
- The actual key is POSTed to /settings (same endpoint the cog
- menu uses) so there's a single source of truth on disk. -->
- <div id="civitaiAuthBanner" class="civitai-auth" style="display:none"></div>
- <div class="civitai-search-bar">
- <input type="text" id="civitaiQuery" placeholder="Search by name, style, creator…"
- oninput="if(this._t) clearTimeout(this._t); this._t = setTimeout(civitaiSearch, 350)"
- onkeydown="if(event.key==='Enter'){ event.preventDefault(); civitaiSearch(); }">
- <label class="toggle-pill" id="civitaiNsfwPill">
- <input type="checkbox" id="civitaiNsfw">
- <span class="toggle-dot"></span>
- <span>Show NSFW</span>
- </label>
- </div>
- <div class="civitai-grid" id="civitaiGrid">
- <div class="hint">Loading…</div>
- </div>
- <div class="civitai-status-line" id="civitaiStatus"></div>
- <div style="display:flex; justify-content:center; margin-top:14px">
- <button type="button" class="ghost-btn" id="civitaiLoadMore"
- style="display:none" onclick="civitaiLoadMore()">Load more</button>
- </div>
- </div>
-</div>
-
-<!-- ============== SETTINGS MODAL ============== -->
-<!-- Opened by the gear icon in the header. Lets users pick output codec
- presets (Standard / Video production / Web) or set custom pix_fmt + crf.
- Persisted to panel_settings.json; the helper subprocess restarts on
- codec change so the new ffmpeg args take effect on next job. -->
-<div id="settingsModal" class="models-modal" style="display:none"
- role="dialog" aria-modal="true" aria-labelledby="settingsModalTitle"
- onclick="if(event.target===this) closeSettingsModal()">
- <div class="models-card">
- <div class="models-head">
- <h2 id="settingsModalTitle">Settings</h2>
- <button class="ghost-btn" onclick="closeSettingsModal()">Close</button>
- </div>
- <div class="models-hint">
- Pick how rendered clips are encoded. Settings are saved to
- <code>panel_settings.json</code> and apply to every new render.
- Files already in the gallery are not re-encoded.
- </div>
-
- <div class="settings-section">
- <h3>Output format</h3>
- <div class="preset-grid" id="settingsPresets">
- <!-- populated by openSettingsModal() from /settings -->
- </div>
- </div>
-
- <div class="settings-section">
- <h3>Memory / speed</h3>
- <div class="hint" style="margin-bottom:8px">
- Controls the VAE decode path after denoising. Fast uses more unified
- memory on medium clips; Safe streams decode to reduce peak RAM.
- </div>
- <div class="settings-row">
- <label>Policy</label>
- <select id="settingsMemoryPolicy" style="flex:1"></select>
- </div>
- <div class="hint" id="settingsMemoryPolicyHint" style="margin-top:6px"></div>
- </div>
-
- <div class="settings-section">
- <h3>API tokens</h3>
- <div class="hint" style="margin-bottom:8px">
- Saved locally in <code>panel_settings.json</code>. Never sent
- anywhere except as auth headers to civitai.com / huggingface.co.
- Power users can override with <code>CIVITAI_API_KEY</code> /
- <code>HF_TOKEN</code> env vars; the saved value here wins when
- both are set.
- </div>
-
- <!-- CivitAI token row -->
- <div class="token-row">
- <div class="token-label">
- <span>CivitAI API key</span>
- <span class="token-status" id="civitaiKeyStatus">—</span>
- </div>
- <div class="token-row-input">
- <input type="password" id="civitaiKeyInput" autocomplete="off"
- placeholder="paste key here…"
- oninput="onTokenInput('civitai')">
- <button type="button" class="ghost-btn" id="civitaiKeyToggle"
- onclick="toggleTokenVisibility('civitaiKeyInput', this)">show</button>
- <button type="button" class="primary-btn token-savetest"
- onclick="testToken('civitai')" title="Save the pasted key and verify it with CivitAI">save & test</button>
- <button type="button" class="ghost-btn" id="civitaiKeyClear"
- onclick="clearToken('civitai')" style="display:none">clear</button>
- </div>
- <div class="hint" id="civitaiTestResult">
- Required for installing CivitAI LoRAs.
- Get one at <a href="https://civitai.com/user/account" target="_blank" rel="noopener">civitai.com/user/account</a>
- (Account → API Keys → Add).
- </div>
- </div>
-
- <!-- HF token row -->
- <div class="token-row">
- <div class="token-label">
- <span>Hugging Face token</span>
- <span class="token-status" id="hfTokenStatus">—</span>
- </div>
- <div class="token-row-input">
- <input type="password" id="hfTokenInput" autocomplete="off"
- placeholder="hf_…"
- oninput="onTokenInput('hf')">
- <button type="button" class="ghost-btn" id="hfTokenToggle"
- onclick="toggleTokenVisibility('hfTokenInput', this)">show</button>
- <button type="button" class="primary-btn token-savetest"
- onclick="testToken('hf')" title="Save the pasted token and verify it with Hugging Face">save & test</button>
- <button type="button" class="ghost-btn" id="hfTokenClear"
- onclick="clearToken('hf')" style="display:none">clear</button>
- </div>
- <div class="hint" id="hfTestResult">
- Required for gated LoRAs (Lightricks HDR + Control LoRAs).
- Get one at <a href="https://huggingface.co/settings/tokens" target="_blank" rel="noopener">huggingface.co/settings/tokens</a>
- — read access is enough.
- </div>
- </div>
- </div>
-
- <!-- Spicy mode — gates NSFW LoRA visibility in the CivitAI browser.
- Default OFF. Turning ON requires an explicit confirm-click pattern
- so a casual visitor / kid can't toggle it by a stray click. The
- server enforces the gate independently in _civitai_search, so a
- tampered client can't bypass this. -->
- <div class="settings-section">
- <h3>Spicy mode <span class="hint" style="font-weight:400">(adult content)</span></h3>
- <div class="hint" style="margin-bottom:10px">
- When OFF, the CivitAI LoRA browser hides NSFW models entirely —
- the "Show NSFW" toggle disappears and any NSFW result the API
- returns is filtered out. When ON, you can choose per-search whether
- to include NSFW results. The server enforces this gate even if the
- client is tampered with.
- </div>
- <div class="spicy-row">
- <span class="spicy-state" id="spicyStateBadge">OFF</span>
- <button type="button" class="ghost-btn" id="spicyToggleBtn"
- onclick="toggleSpicyMode()" style="margin-left:auto">
- Enable Spicy mode
- </button>
- </div>
- <div class="hint" id="spicyHint" style="margin-top:8px; display:none"></div>
- </div>
-
- <div class="settings-section" id="settingsCustomSection" style="display:none">
- <h3>Custom (advanced)</h3>
- <div class="settings-row" style="margin-bottom:10px">
- <label>pix_fmt</label>
- <select id="settingsPixFmt" style="flex:1">
- <option value="yuv420p">yuv420p — web standard, broad support</option>
- <option value="yuv422p">yuv422p — pro, more chroma than 420p</option>
- <option value="yuv444p">yuv444p — full chroma, no subsampling</option>
- <option value="yuv420p10le">yuv420p10le — 10-bit, HDR-ready</option>
- <option value="yuv422p10le">yuv422p10le — 10-bit pro</option>
- <option value="yuv444p10le">yuv444p10le — 10-bit, full chroma</option>
- </select>
- </div>
- <div class="settings-row">
- <label>CRF</label>
- <input type="range" id="settingsCrfRange" min="0" max="30" step="1"
- style="flex:1; width:auto" oninput="document.getElementById('settingsCrfNum').value = this.value">
- <input type="number" id="settingsCrfNum" min="0" max="30" step="1"
- style="width:60px"
- oninput="document.getElementById('settingsCrfRange').value = this.value">
- </div>
- <div class="hint" style="margin-top:6px">
- 0 = mathematically lossless · 18 = visually lossless ·
- 23 = web default · 28+ = lossy
- </div>
- </div>
-
- <div class="settings-foot">
- <span class="settings-status" id="settingsStatus"></span>
- <button class="ghost-btn" onclick="closeSettingsModal()">Cancel</button>
- <button class="primary-btn" id="settingsApplyBtn" onclick="applySettings()">Apply</button>
- </div>
- </div>
-</div>
-
-<!-- ============== TIER MODAL ============== -->
-<!-- Opened by the "tier" pill in the header. Renders the detected
- hardware tier + what it allows. Helps users understand WHY some
- options are disabled instead of just hitting a wall mid-flow. -->
-<div id="tierModal" class="models-modal" style="display:none"
- role="dialog" aria-modal="true" aria-labelledby="tierModalTitle"
- onclick="if(event.target===this) closeTierModal()">
- <div class="models-card">
- <div class="models-head">
- <h2 id="tierModalTitle">Hardware tier</h2>
- <button class="ghost-btn" onclick="closeTierModal()">Close</button>
- </div>
- <div class="models-hint" id="tierModalBlurb"></div>
- <ul class="models-list" id="tierCapsList"></ul>
- <div class="models-foot">
- Set <code>LTX_TIER_OVERRIDE=base|standard|high|pro</code> in the env to
- force a tier (useful for testing what other users see).
- </div>
- </div>
-</div>
-
-<!-- ============== MODELS MODAL ============== -->
-<!-- Opened by the "models" pill in the header. Shows per-repo download
- status from /models, with a Download button per row. Active downloads
- stream into the existing log at the bottom of the page. -->
-<div id="modelsModal" class="models-modal" style="display:none"
- role="dialog" aria-modal="true" aria-labelledby="modelsModalTitle"
- onclick="if(event.target===this) closeModelsModal()">
- <div class="models-card">
- <div class="models-head">
- <h2 id="modelsModalTitle">Models</h2>
- <button class="ghost-btn" onclick="closeModelsModal()">Close</button>
- </div>
- <div class="models-hint" id="modelsHint">Loading…</div>
- <ul class="models-list" id="modelsList"></ul>
- <div class="models-foot" id="modelsFoot"></div>
- </div>
-</div>
-
-<!-- (Version modal removed in the magic-button rewrite. Pill itself is the
- full UI now: click while behind → confirm + git pull; click while
- current → live re-check. See versionPillClick() in the JS section.) -->
-
-<!-- ============== OUTPUT INFO MODAL ============== -->
-<!-- Opened by the ⓘ button on each gallery card. Shows everything we
- wrote into the .mp4.json sidecar at render time: prompt, seed,
- mode/quality, frames + dimensions, LoRAs used (with name + strength),
- elapsed time, queue id, model. Plus copy-buttons for prompt + seed
- so users can easily re-use them. -->
-<div id="outputInfoModal" class="models-modal" style="display:none"
- role="dialog" aria-modal="true" aria-labelledby="outputInfoTitle"
- onclick="if(event.target===this) closeOutputInfoModal()">
- <div class="models-card" style="width: min(720px, 96vw)">
- <div class="models-head">
- <h2 id="outputInfoTitle">Generation info</h2>
- <button class="ghost-btn" onclick="closeOutputInfoModal()">Close</button>
- </div>
- <div id="outputInfoBody" class="output-info-body">
- <div class="hint">Loading…</div>
- </div>
- </div>
-</div>
-
-<!-- ============== BUG REPORT MODAL ============== -->
-<!-- Opened by the neon bug button in the header pill row. Pre-fills
- environment info + log tail server-side via /panel/bug-context, then
- opens a pre-filled GitHub issue when the user submits. NO server-side
- issue creation — the client builds the URL, opens it in a new tab,
- and we're done. Optional crash-report zip lives in /tmp for the user
- to drag onto the issue. -->
-<div id="bugModal" class="models-modal" style="display:none"
- role="dialog" aria-modal="true" aria-labelledby="bugModalTitle"
- onclick="if(event.target===this) closeBugModal()">
- <div class="models-card" style="width: min(720px, 96vw)">
- <div class="models-head">
- <h2 id="bugModalTitle">Report a bug</h2>
- <button class="ghost-btn" onclick="closeBugModal()">Close</button>
- </div>
- <div class="models-hint">
- Opens a pre-filled GitHub issue in a new tab. Environment info, version,
- and the last 50 log lines are filled in for you.
- </div>
- <div id="bugModalBody" style="padding: 12px 0; display:flex; flex-direction:column; gap:10px">
- <label style="display:flex; flex-direction:column; gap:4px; font-size:12px; color:var(--muted)">
- Title
- <input id="bugTitle" type="text" value="[bug] "
- style="padding:6px 9px; font-size:13px; background:rgba(140,160,220,0.04); border:1px solid var(--ph-border-soft); border-radius:6px; color:var(--text); font-family:inherit">
- </label>
- <label style="display:flex; flex-direction:column; gap:4px; font-size:12px; color:var(--muted)">
- Description
- <textarea id="bugBody" rows="14"
- style="padding:8px 10px; font-size:12px; background:rgba(140,160,220,0.04); border:1px solid var(--ph-border-soft); border-radius:6px; color:var(--text); font-family:ui-monospace,SFMono-Regular,Menlo,monospace; line-height:1.45; resize:vertical">Loading environment…</textarea>
- </label>
- <label id="bugCrashRow" style="display:none; align-items:center; gap:8px; font-size:12px; color:var(--muted)">
- <input id="bugCrashCheck" type="checkbox" checked>
- <span id="bugCrashLabel">Include latest crash reports (zips up to 5 .ips files)</span>
- </label>
- <div id="bugSubmitRow" style="display:flex; gap:8px; justify-content:flex-end; align-items:center">
- <span id="bugStatus" style="flex:1; font-size:12px; color:var(--muted)"></span>
- <button class="ghost-btn" onclick="closeBugModal()">Cancel</button>
- <button id="bugSubmitBtn" class="primary-btn" onclick="submitBugReport()">Open GitHub issue</button>
- </div>
- </div>
- </div>
-</div>
-
-<!-- ============== BOTTOM TABBED PANE ============== -->
-<aside class="bottom-pane" id="bottomPane">
- <!-- REDESIGN — Y2.001 bottom-pane. Tighter tab strip with leading
- activity dot, denser Now card matching the composer-card visual
- language, refined badges. All IDs preserved so poll() and the
- click handlers downstream keep working. -->
- <nav class="tabs">
- <span class="bp-live-dot" id="bpLiveDot" title="Idle"></span>
- <button data-tab="now" class="active">Now</button>
- <button data-tab="queue">Queue <span class="badge" id="queueBadge" style="display:none">0</span></button>
- <button data-tab="recent">Recent</button>
- <button data-tab="logs">Logs</button>
- <span class="spacer"></span>
- <a class="model-credit" id="modelTag" href="https://github.com/dgrauet/ltx-2-mlx" target="_blank" rel="noopener" title="MLX port by @dgrauet"></a>
- <!-- (Collapse-this-panel button removed 2026-05-12 — Salo flagged
- it hid important data (active job progress, queue) and the
- "down arrow that goes up" affordance read as confusing. The
- bottom pane is always visible at its natural height now.) -->
- </nav>
- <div class="bottom-body">
- <div class="tab-content show" id="tab-now">
- <div class="now-card idle" id="nowCard">
- <div class="ttl">Idle</div>
- <div class="progress-bar"><div class="fill" id="progressFill" style="width:0%"></div></div>
- <div class="meta" id="nowDetail">No job running</div>
- <!-- Action row populated on the failed state with Retry + Close.
- Lives outside .ttl so poll()'s innerHTML rewrites don't
- clobber the buttons mid-click. Hidden when empty. -->
- <div class="now-card-actions" id="nowCardActions"></div>
- </div>
- </div>
- <div class="tab-content" id="tab-queue">
- <ul class="row-list" id="queueList"></ul>
- </div>
- <div class="tab-content" id="tab-recent">
- <!-- Type filter — image jobs and video jobs share this list now
- that mode='image' goes through the same worker. -->
- <div class="row-list-filter">
- <button id="recentFilterAll" class="active" onclick="setRecentFilter('all')">All</button>
- <button id="recentFilterVideos" onclick="setRecentFilter('videos')">Videos</button>
- <button id="recentFilterPhotos" onclick="setRecentFilter('photos')">Photos</button>
- </div>
- <ul class="row-list" id="historyList"></ul>
- </div>
- <div class="tab-content" id="tab-logs">
- <pre class="log" id="log">No log yet.</pre>
- </div>
- </div>
-</aside>
-
-<!-- ============== HF MODEL BROWSER MODAL ============== -->
-<!-- Search + install MLX-format chat models from Hugging Face. Hits
- huggingface.co/api/models with library=mlx + pipeline_tag=text-generation
- filters. Click Install → backend spawns `hf download`, status streams
- in the bottom strip until done. Newly-installed models appear in the
- local-engine model picker on next refresh. -->
-<div class="model-browser-modal" id="modelBrowserModal" onclick="if(event.target===this)closeModelBrowser()">
- <div class="model-browser-card">
- <div class="model-browser-head">
- <h2>Browse + install models</h2>
- <span class="subtitle">Hugging Face · MLX</span>
- <button type="button" class="close-btn" onclick="closeModelBrowser()">Close</button>
- </div>
- <div class="model-browser-controls">
- <input type="text" id="modelBrowserQuery" placeholder="Search HF (e.g. qwen coder, devstral, llama 3.3, granite)" autocomplete="off" />
- <label class="checkbox-label" title="Filter to abliterated / uncensored variants — the huihui-ai conventions on HF.">
- <input type="checkbox" id="modelBrowserAbliterated">
- Abliterated only
- </label>
- <button type="button" id="modelBrowserSearchBtn" onclick="modelBrowserSearch()">Search</button>
- </div>
- <div class="model-browser-results" id="modelBrowserResults">
- <div class="model-browser-empty">Type a query and hit Search. Try "qwen3 coder", "devstral", "abliterated", "32b".</div>
- </div>
- <div class="model-browser-status" id="modelBrowserStatus">
- <div><span class="label" id="modelBrowserStatusLabel">…</span><span id="modelBrowserStatusSummary"></span></div>
- <div class="last-line" id="modelBrowserStatusLine"></div>
- </div>
- </div>
-</div>
-
-
-<!-- ============== BATCH MODAL ============== -->
-<div class="modal-bg" id="batchModal" onclick="if(event.target===this)closeBatch()">
- <div class="modal">
- <h3>Batch paste — split prompts with <code>---</code> on its own line</h3>
- <textarea class="batch" id="batchPrompts" placeholder="First prompt here.
-
----
-
-Second prompt.
-
----
-
-Third prompt."></textarea>
- <div class="hint" style="margin-top:6px">Each chunk between <code>---</code> lines becomes a queued job using the current form settings. Auto-open is forced off for batches.</div>
- <div class="modal-actions">
- <button class="small" onclick="closeBatch()">Cancel</button>
- <button class="small primary" style="padding:6px 14px" onclick="queueBatch().then(closeBatch)">Queue all</button>
- </div>
- </div>
-</div>
-
-<script>
-const BOOT = __BOOTSTRAP__;
-const ASPECTS = BOOT.aspects;
-const FPS = BOOT.fps;
-const MODEL_UPSCALE_ENABLED = !!BOOT.model_upscale_enabled;
-const PIPERSR_UPSCALE_ENABLED = !!BOOT.pipersr_upscale_enabled;
-
-// Apply tier-aware time estimates to the Quality pill subtitles. The HTML
-// ships with the Comfortable-tier (M4 Studio 64 GB) numbers as defaults;
-// users on Compact / Roomy / Studio tiers see realistic estimates instead
-// of the optimistic baseline. Runs once on boot, plus when the tier modal
-// reports new info (rare — tier is fixed for a given Mac).
-function applyTierTimes() {
- const qt = (BOOT.quality_times || {});
- document.querySelectorAll('#qualityGroup .pill-quality').forEach(btn => {
- const key = btn.dataset.quality;
- const time = qt[key];
- const spec = btn.querySelector('.ql-spec');
- if (!spec) return;
- const dimsMatch = spec.textContent.match(/^([0-9]+×[0-9]+(\s+→\s+[0-9p]+)?)/);
- const dims = dimsMatch ? dimsMatch[1] : '';
- if (time && dims) {
- spec.textContent = `${dims} · ${time}`;
- } else if (time) {
- spec.textContent = time;
- }
- });
-}
-
-let filterMode = 'visible';
-let activePath = null;
-let currentOutputs = [];
-let currentMode = 't2v';
-
-// Main right-pane gallery kind filter (All / Videos / Photos). Independent
-// of `filterMode` (which is visible/hidden) and independent of
-// `window.outputsFilter` (which is the agent-stage Session outputs filter
-// from commit ef7f114). The localStorage key is intentionally different:
-// the user can have "Photos" pinned on the main pane while Sessions sits
-// on "All". Default is 'all'; setMode('image') auto-flips to 'photos',
-// the video modes auto-flip to 'videos'. Manual user clicks always win.
-let mainOutputsFilter = 'all';
-try {
- const stored = localStorage.getItem('phos_main_outputs_filter');
- if (stored === 'all' || stored === 'videos' || stored === 'photos') {
- mainOutputsFilter = stored;
- }
-} catch (e) {}
-// Photo detection that matches commit af5c184's isPhotoOutput on the
-// agent-stage pane: explicit kind > params.mode > filename suffix. The
-// server now stamps a `kind` field, but the suffix fallback covers
-// outputs whose sidecar got lost (older entries) and any future caller
-// that forgets to set kind.
-function isPhotoOutputMain(o) {
- if (!o) return false;
- if (o.kind === 'image') return true;
- if (o.kind === 'video') return false;
- const path = (o.path || o.name || '').toLowerCase();
- if (/\.(png|jpg|jpeg|webp)$/.test(path)) return true;
- if (/\.mp4$/.test(path)) return false;
- return false;
-}
-// Apply the main filter on top of currentOutputs. Returns the filtered
-// array; callers also use this for the count badge so the filter and
-// the rendered cells agree.
-function filteredMainOutputs() {
- if (mainOutputsFilter === 'all') return currentOutputs;
- if (mainOutputsFilter === 'photos') return currentOutputs.filter(isPhotoOutputMain);
- return currentOutputs.filter(o => !isPhotoOutputMain(o));
-}
-function _updateMainFilterChips() {
- const a = document.getElementById('mainOutputsFilterAll');
- const v = document.getElementById('mainOutputsFilterVideos');
- const p = document.getElementById('mainOutputsFilterPhotos');
- if (a) a.classList.toggle('active', mainOutputsFilter === 'all');
- if (v) v.classList.toggle('active', mainOutputsFilter === 'videos');
- if (p) p.classList.toggle('active', mainOutputsFilter === 'photos');
-}
-function setMainOutputsFilter(mode) {
- if (mode !== 'all' && mode !== 'videos' && mode !== 'photos') mode = 'all';
- mainOutputsFilter = mode;
- try { localStorage.setItem('phos_main_outputs_filter', mode); } catch (e) {}
- _updateMainFilterChips();
- // If the active selection was filtered out, switch to the first match.
- const visible = filteredMainOutputs();
- if (visible.length && !visible.some(o => o.path === activePath)) {
- selectOutput(visible[0].path);
- }
- renderCarousel();
- // Reset scroll position on filter change so the user lands at the
- // top of the newly-filtered list, not mid-gallery from the previous
- // selection's position.
- const carEl = document.getElementById('carousel');
- if (carEl) carEl.scrollTop = 0;
- // Count badge mirrors the active filter (e.g. "Outputs · 23 photos").
- const titleEl = document.getElementById('carouselTitle');
- if (titleEl && filterMode !== 'hidden') {
- const label = mode === 'all' ? '' : ` ${mode}`;
- titleEl.textContent = `Outputs · ${visible.length}${label}`;
- }
-}
-// Auto-set helper called from setMode(). DOES NOT persist (writing to
-// localStorage would override the user's manual pick the next time they
-// switch modes), but DOES bump the active chip + re-render so the
-// gallery snaps to the new default. The user can override after, and
-// THAT click persists via setMainOutputsFilter().
-function _autoMainOutputsFilterForMode(mode) {
- // Auto-set NEVER lands on 'all' — that's user-only, per spec.
- let target = null;
- if (mode === 'image') target = 'photos';
- else if (mode === 't2v' || mode === 'i2v' || mode === 'keyframe' || mode === 'extend') target = 'videos';
- if (!target || target === mainOutputsFilter) return;
- mainOutputsFilter = target;
- // No localStorage write — see comment above.
- _updateMainFilterChips();
- if (typeof renderCarousel === 'function') renderCarousel();
- const titleEl = document.getElementById('carouselTitle');
- if (titleEl && filterMode !== 'hidden') {
- const visible = filteredMainOutputs();
- titleEl.textContent = `Outputs · ${visible.length} ${target}`;
- }
- // Swap the player to a matching entry if the current active is now
- // off-filter (e.g. mode=image but the viewer is showing a video).
- const visible = filteredMainOutputs();
- if (visible.length && !visible.some(o => o.path === activePath)) {
- selectOutput(visible[0].path);
- }
-}
-
-// Model tag in the bottom-pane nav links to dgrauet's repo. Strip an
-// absolute filesystem path back to the HF repo id form for display
-// (the panel sets LTX_MODEL to a local path in Pinokio installs).
-(function () {
- const m = String(BOOT.model || '');
- let label = m;
- const idx = m.indexOf('mlx_models/');
- if (idx >= 0) label = m.slice(idx + 'mlx_models/'.length);
- if (label.startsWith('/')) label = label.split('/').slice(-2).join('/');
- document.getElementById('modelTag').textContent = label;
-})();
-// `audio` is still a free-text input (advanced section); `image` is now a
-// picker — leave the picker empty by default and let the user pick or
-// drop. Pre-filling examples/reference.png surprised users into rendering
-// the demo image when they meant to leave it blank.
-document.getElementById('audio').value = BOOT.default_audio;
-
-// ====== Pill-button group helpers ======
-// Avoid (negative prompt) toggle — keeps the textarea collapsed by
-// default so the prompt-and-go flow stays tight. The button label flips
-// to "Avoid −" when open so the affordance is clear. Auto-opens once
-// the user types into it (so it stays visible) — shouldn't auto-close
-// from typing-then-deleting because that would yank the field out from
-// under their next keystroke.
-function toggleAvoidRow(forceOpen) {
- const row = document.getElementById('avoidRow');
- const btn = document.getElementById('avoidToggleBtn');
- const lbl = document.getElementById('avoidToggleLabel');
- const ta = document.getElementById('negative_prompt');
- if (!row) return;
- const wantOpen = (forceOpen === true) ? true : !row.classList.contains('show');
- row.classList.toggle('show', wantOpen);
- if (btn) btn.classList.toggle('active', wantOpen);
- if (lbl) lbl.textContent = wantOpen ? 'Avoid −' : 'Avoid +';
- if (wantOpen && ta) {
- try { ta.focus(); } catch (e) {}
- }
-}
-// Auto-open the Avoid row if it has content (e.g. loaded from a sidecar
-// via loadParams). Run once at boot AND after loadParams sets values.
-function syncAvoidRowFromValue() {
- const ta = document.getElementById('negative_prompt');
- if (!ta) return;
- if ((ta.value || '').trim() !== '') {
- const row = document.getElementById('avoidRow');
- if (row && !row.classList.contains('show')) toggleAvoidRow(true);
- }
-}
-
-function setMode(mode) {
- currentMode = mode;
- // The Studio pill swaps the form-pane in place: hide the video form
- // (genForm) and show the inline #studioSection. Right rail (queue,
- // current, history) stays visible regardless of mode. The mode dropdown
- // value is set to a non-form value when in studio so an accidental
- // form submit doesn't trigger a video render with stale fields.
- const studio = document.getElementById('studioSection');
- const train = document.getElementById('trainSection');
- const genForm = document.getElementById('genForm');
- // Train mode mirrors Studio: hide #genForm, show #trainSection. Same
- // chrome conventions, separate form (so an Enter inside the trigger
- // input doesn't submit a video render).
- if (mode === 'train') {
- if (studio) studio.classList.remove('show');
- if (train) train.classList.add('show');
- if (genForm) genForm.style.display = 'none';
- document.querySelectorAll('#modeGroup .pill-btn').forEach(b =>
- b.classList.toggle('active', b.dataset.mode === 'train'));
- // Lazy initialization on first entry — wires drop zone, generates
- // a starter trigger, refreshes the trained-LoRAs list, computes
- // an initial wall-time estimate.
- if (typeof trainInit === 'function') trainInit();
- return;
- }
- if (mode === 'image') {
- if (studio) studio.classList.add('show');
- if (genForm) genForm.style.display = 'none';
- document.querySelectorAll('#modeGroup .pill-btn').forEach(b =>
- b.classList.toggle('active', b.dataset.mode === 'image'));
- // Portal the unified LoRA picker into the Studio composer slot, so
- // the SAME UI (one chip strip, one library, one + LoRA button) is
- // visible under Image Studio. Re-renders with the engine-aware
- // filter automatically (renderLorasList reads _currentLoraModeFilter
- // every time, no separate config to thread). The hidden #lorasJson
- // input STAYS inside #genForm — imgStudioGenerate reads
- // _activeLoras directly when posting, so the studio submit doesn't
- // depend on the hidden field's location.
- _portalLoraPicker('studio');
- // Re-render the unified LoRA picker so its mode-aware filter
- // (which reads `currentMode` we just set above) actually applies.
- // Without this the picker stays on whatever filter it had under
- // the previous mode — the symptom the user hit: clicked Studio,
- // banner still read "LTX-Video LoRAs (active video mode)" until
- // they jiggled the engine dropdown to force a re-render.
- if (typeof renderLorasList === 'function') renderLorasList();
- // Wire ref drop-zones once + refresh library on every entry
- if (typeof imgStudioWireRefSlots === 'function') imgStudioWireRefSlots();
- if (typeof imgStudioRefreshLibrary === 'function') imgStudioRefreshLibrary();
- // Pull engine cache state + recent-uploads strip + estimate so the
- // composer is fully populated before the user reads it. These are
- // best-effort and silent on failure.
- if (typeof imgStudioRefreshEngineStatus === 'function') imgStudioRefreshEngineStatus();
- if (typeof imgStudioRefreshRecent === 'function') imgStudioRefreshRecent();
- if (typeof imgStudioUpdateEstimate === 'function') imgStudioUpdateEstimate();
- // Auto-set the right-pane outputs gallery to "Photos" — image mode
- // is composing photos, so a video gallery makes no sense as the
- // default. User can still flip back to All/Videos manually.
- if (typeof _autoMainOutputsFilterForMode === 'function') {
- _autoMainOutputsFilterForMode('image');
- }
- return;
- }
- if (studio) studio.classList.remove('show');
- if (train) train.classList.remove('show');
- if (genForm) genForm.style.display = '';
- // Portal the picker back to its video-form home so it's visible above
- // the Generate button when the user is composing a video shot.
- _portalLoraPicker('video');
- // Same re-render trigger as the image branch above — without it the
- // picker keeps the previous mode's filter when flipping back from
- // Studio to a video mode.
- if (typeof renderLorasList === 'function') renderLorasList();
- document.getElementById('mode').value = mode;
- document.querySelectorAll('#modeGroup .pill-btn').forEach(b => b.classList.toggle('active', b.dataset.mode === mode));
- // Mode → main-outputs filter auto-set (Videos for video modes).
- if (typeof _autoMainOutputsFilterForMode === 'function') {
- _autoMainOutputsFilterForMode(mode);
- }
- // For i2v, switch the actual mode based on the i2vMode select
- if (mode === 'i2v') {
- document.getElementById('mode').value = document.getElementById('i2vMode').value;
- }
- // Keyframe REQUIRES Q8 (uses dev transformer); force quality=high.
- // If Q8 isn't available the High pill stays disabled and the user gets the
- // same "Q8 not installed" hint as elsewhere.
- if (mode === 'keyframe') {
- setQuality('high');
- }
- updateAccelAvailability();
- updateTemporalAvailability();
- updateDerived();
- // Refresh the inline models card immediately — switching to FFLF when
- // Q8 is missing should surface the Download Q8 CTA without waiting for
- // the next 1.5s poll tick.
- if (LAST_STATUS) updateModelsCard(LAST_STATUS);
-}
-
-// Move the unified LoRA picker between its two homes (Option A portal).
-// "video" → goes inside #genForm (its declared position), "studio" →
-// goes inside #studioSection. Idempotent: a re-portal to the same
-// destination is a no-op. The hidden #lorasJson input is a SEPARATE
-// element that stays inside #genForm regardless, so the video form's
-// FormData(genForm) keeps picking it up. Image Studio's submit
-// (imgStudioGenerate) reads _activeLoras directly when posting.
-function _portalLoraPicker(dest) {
- const node = document.getElementById('lorasDetails');
- const videoSlot = document.getElementById('loraPickerVideoSlot');
- const studioSlot = document.getElementById('loraPickerStudioSlot');
- if (!node) return;
- const target = (dest === 'studio') ? studioSlot : videoSlot;
- if (!target || node.parentElement === target) {
- if (typeof renderLorasList === 'function') renderLorasList();
- return;
- }
- target.appendChild(node);
- // Re-render so the mode banner + library filter snap to the new
- // (mode + engine) context immediately.
- if (typeof renderLorasList === 'function') renderLorasList();
-}
-
-// ====== Image Studio (manual still gen) ======================================
-// State: 3 reference slots. Each slot holds {path, name} when populated.
-const IMG_STUDIO = {
- refs: [null, null, null],
- busy: false,
-};
+<!-- Phosphor Icons (MIT, https://github.com/phosphor-icons/core) — inline symbol library.
+ Referenced via <svg class="ph"><use href="#ph-NAME"/></svg>. The symbol set is
+ curated, not the full Phosphor library — only icons we actually use. License notice
+ lives at LICENSES/phosphor-icons.txt in the repo root. -->
+<svg width="0" height="0" style="position:absolute;width:0;height:0;overflow:hidden" aria-hidden="true">
+<defs>
+<symbol id="ph-arrow-clockwise" viewBox="0 0 256 256"><polyline points="184 104 232 104 232 56" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/><path d="M188.4,192a88,88,0,1,1,1.83-126.23L232,104" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/></symbol>
+<symbol id="ph-arrow-clockwise-bold" viewBox="0 0 256 256"><polyline points="184 104 232 104 232 56" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="24"/><path d="M188.4,192a88,88,0,1,1,1.83-126.23L232,104" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="24"/></symbol>
+<symbol id="ph-arrow-square-out" viewBox="0 0 256 256"><polyline points="216 104 215.99 40.01 152 40" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/><line x1="136" y1="120" x2="216" y2="40" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/><path d="M184,136v72a8,8,0,0,1-8,8H48a8,8,0,0,1-8-8V80a8,8,0,0,1,8-8h72" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/></symbol>
+<symbol id="ph-arrow-up" viewBox="0 0 256 256"><line x1="128" y1="216" x2="128" y2="40" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/><polyline points="56 112 128 40 200 112" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/></symbol>
+<symbol id="ph-caret-down-bold" viewBox="0 0 256 256"><polyline points="208 96 128 176 48 96" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="24"/></symbol>
+<symbol id="ph-check-bold" viewBox="0 0 256 256"><polyline points="40 144 96 200 224 72" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="24"/></symbol>
+<symbol id="ph-download-simple" viewBox="0 0 256 256"><line x1="128" y1="144" x2="128" y2="32" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/><polyline points="216 144 216 208 40 208 40 144" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/><polyline points="168 104 128 144 88 104" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/></symbol>
+<symbol id="ph-film-strip" viewBox="0 0 256 256"><rect x="32" y="48" width="192" height="160" rx="8" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/><line x1="128" y1="48" x2="128" y2="208" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/><line x1="32" y1="80" x2="224" y2="80" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/><line x1="32" y1="176" x2="224" y2="176" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/><line x1="80" y1="48" x2="80" y2="80" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/><line x1="176" y1="48" x2="176" y2="80" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/><line x1="80" y1="176" x2="80" y2="208" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/><line x1="176" y1="176" x2="176" y2="208" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/></symbol>
+<symbol id="ph-gear-six" viewBox="0 0 256 256"><circle cx="128" cy="128" r="40" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/><path d="M130.05,206.11c-1.34,0-2.69,0-4,0L94,224a104.61,104.61,0,0,1-34.11-19.2l-.12-36c-.71-1.12-1.38-2.25-2-3.41L25.9,147.24a99.15,99.15,0,0,1,0-38.46l31.84-18.1c.65-1.15,1.32-2.29,2-3.41l.16-36A104.58,104.58,0,0,1,94,32l32,17.89c1.34,0,2.69,0,4,0L162,32a104.61,104.61,0,0,1,34.11,19.2l.12,36c.71,1.12,1.38,2.25,2,3.41l31.85,18.14a99.15,99.15,0,0,1,0,38.46l-31.84,18.1c-.65,1.15-1.32,2.29-2,3.41l-.16,36A104.58,104.58,0,0,1,162,224Z" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/></symbol>
+<symbol id="ph-image" viewBox="0 0 256 256"><rect x="32" y="48" width="192" height="160" rx="8" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/><circle cx="156" cy="100" r="12"/><path d="M147.31,164,173,138.34a8,8,0,0,1,11.31,0L224,178.06" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/><path d="M32,168.69l54.34-54.35a8,8,0,0,1,11.32,0L191.31,208" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/></symbol>
+<symbol id="ph-info-fill" viewBox="0 0 256 256"><path d="M128,24A104,104,0,1,0,232,128,104.11,104.11,0,0,0,128,24Zm-4,48a12,12,0,1,1-12,12A12,12,0,0,1,124,72Zm12,112a16,16,0,0,1-16-16V128a8,8,0,0,1,0-16,16,16,0,0,1,16,16v40a8,8,0,0,1,0,16Z"/></symbol>
+<symbol id="ph-info" viewBox="0 0 256 256"><circle cx="128" cy="128" r="96" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/><polyline points="120 120 128 120 128 172 136 172" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/><circle cx="126" cy="84" r="10" fill="currentColor"/></symbol>
+<symbol id="ph-magnifying-glass" viewBox="0 0 256 256"><circle cx="112" cy="112" r="80" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/><line x1="168.57" y1="168.57" x2="224" y2="224" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/></symbol>
+<symbol id="ph-pause-fill" viewBox="0 0 256 256"><path d="M216,48V208a16,16,0,0,1-16,16H160a16,16,0,0,1-16-16V48a16,16,0,0,1,16-16h40A16,16,0,0,1,216,48ZM96,32H56A16,16,0,0,0,40,48V208a16,16,0,0,0,16,16H96a16,16,0,0,0,16-16V48A16,16,0,0,0,96,32Z"/></symbol>
+<symbol id="ph-pencil-simple" viewBox="0 0 256 256"><path d="M92.69,216H48a8,8,0,0,1-8-8V163.31a8,8,0,0,1,2.34-5.65L165.66,34.34a8,8,0,0,1,11.31,0L221.66,79a8,8,0,0,1,0,11.31L98.34,213.66A8,8,0,0,1,92.69,216Z" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/><line x1="136" y1="64" x2="192" y2="120" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/></symbol>
+<symbol id="ph-play-fill" viewBox="0 0 256 256"><path d="M240,128a15.74,15.74,0,0,1-7.6,13.51L88.32,229.65a16,16,0,0,1-16.2.3A15.86,15.86,0,0,1,64,216.13V39.87a15.86,15.86,0,0,1,8.12-13.82,16,16,0,0,1,16.2.3L232.4,114.49A15.74,15.74,0,0,1,240,128Z"/></symbol>
+<symbol id="ph-sparkle-fill" viewBox="0 0 256 256"><path d="M208,144a15.78,15.78,0,0,1-10.42,14.94L146,178l-19,51.62a15.92,15.92,0,0,1-29.88,0L78,178l-51.62-19a15.92,15.92,0,0,1,0-29.88L78,110l19-51.62a15.92,15.92,0,0,1,29.88,0L146,110l51.62,19A15.78,15.78,0,0,1,208,144ZM152,48h16V64a8,8,0,0,0,16,0V48h16a8,8,0,0,0,0-16H184V16a8,8,0,0,0-16,0V32H152a8,8,0,0,0,0,16Zm88,32h-8V72a8,8,0,0,0-16,0v8h-8a8,8,0,0,0,0,16h8v8a8,8,0,0,0,16,0V96h8a8,8,0,0,0,0-16Z"/></symbol>
+<symbol id="ph-target" viewBox="0 0 256 256"><line x1="128" y1="128" x2="224" y2="32" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/><path d="M195.88,60.12a95.88,95.88,0,1,0,18.77,26.49" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/><path d="M161.94,94.06a48,48,0,1,0,14,31.2" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/></symbol>
+<symbol id="ph-trash-simple" viewBox="0 0 256 256"><line x1="216" y1="56" x2="40" y2="56" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/><line x1="88" y1="24" x2="168" y2="24" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/><path d="M200,56V208a8,8,0,0,1-8,8H64a8,8,0,0,1-8-8V56" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/></symbol>
+<symbol id="ph-warning-fill" viewBox="0 0 256 256"><path d="M236.8,188.09,149.35,36.22h0a24.76,24.76,0,0,0-42.7,0L19.2,188.09a23.51,23.51,0,0,0,0,23.72A24.35,24.35,0,0,0,40.55,224h174.9a24.35,24.35,0,0,0,21.33-12.19A23.51,23.51,0,0,0,236.8,188.09ZM120,104a8,8,0,0,1,16,0v40a8,8,0,0,1-16,0Zm8,88a12,12,0,1,1,12-12A12,12,0,0,1,128,192Z"/></symbol>
+<symbol id="ph-x" viewBox="0 0 256 256"><line x1="200" y1="56" x2="56" y2="200" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/><line x1="200" y1="200" x2="56" y2="56" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/></symbol>
+<symbol id="ph-x-bold" viewBox="0 0 256 256"><line x1="200" y1="56" x2="56" y2="200" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="24"/><line x1="200" y1="200" x2="56" y2="56" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="24"/></symbol>
+<symbol id="ph-x-circle" viewBox="0 0 256 256"><line x1="160" y1="96" x2="96" y2="160" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/><line x1="96" y1="96" x2="160" y2="160" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/><circle cx="128" cy="128" r="96" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/></symbol>
+<symbol id="ph-x-circle-fill" viewBox="0 0 256 256"><path d="M128,24A104,104,0,1,0,232,128,104.11,104.11,0,0,0,128,24Zm37.66,130.34a8,8,0,0,1-11.32,11.32L128,139.31l-26.34,26.35a8,8,0,0,1-11.32-11.32L116.69,128,90.34,101.66a8,8,0,0,1,11.32-11.32L128,116.69l26.34-26.35a8,8,0,0,1,11.32,11.32L139.31,128Z"/></symbol>
+<!-- File-kind icons referenced dynamically by agentAttachIcon(); the
+ tree-shake regex doesn't see runtime string concatenation. -->
+<symbol id="ph-paperclip" viewBox="0 0 256 256"><path d="M160,80,76.69,164.69a16,16,0,0,0,22.63,22.62L198.63,86.63a32,32,0,0,0-45.26-45.26L54.06,142.06a48,48,0,0,0,67.88,67.88L204,128" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/></symbol>
+<symbol id="ph-file-text" viewBox="0 0 256 256"><path d="M200,224H56a8,8,0,0,1-8-8V40a8,8,0,0,1,8-8h96l56,56V216A8,8,0,0,1,200,224Z" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/><polyline points="152 32 152 88 208 88" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/><line x1="96" y1="136" x2="160" y2="136" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/><line x1="96" y1="168" x2="160" y2="168" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/></symbol>
+<symbol id="ph-file-pdf" viewBox="0 0 256 256"><polyline points="216 152 184 152 184 208" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/><line x1="208" y1="184" x2="184" y2="184" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/><path d="M48,192H64a20,20,0,0,0,0-40H48v56" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/><path d="M112,152v56h16a28,28,0,0,0,0-56Z" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/><path d="M48,112V40a8,8,0,0,1,8-8h96l56,56v24" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/><polyline points="152 32 152 88 208 88" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/></symbol>
+<symbol id="ph-folder-simple" viewBox="0 0 256 256"><path d="M224,208H32V72a8,8,0,0,1,8-8H92.69a8,8,0,0,1,5.65,2.34L128,96h88a8,8,0,0,1,8,8V208Z" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/></symbol>
+</defs>
+</svg>
-// Engine families that REQUIRE at least one reference image (mflux's
-// qwen-edit CLI marks --image-paths as required; calling it without
-// refs returns an argparse error after model load). The Studio engine
-// override values map 1:1 to these check predicates. Used by
-// imgStudioUpdateValidity() to gate the Generate button.
-function imgStudioRequiresRefs(engineOverride) {
- return engineOverride === 'qwen_edit_inline'
- || engineOverride === 'qwen_edit_lightning_inline'
- || engineOverride === 'qwen_edit_high_inline';
-}
+<header>
+ <a href="/" class="brand"><img src="/assets/phosphene_wordmark_compact_transparent.svg" alt="Phosphene"></a>
+ <span class="version-badge" title="Phosphene 2.0">2.0</span>
+ __PROFILE_BADGE__
+ <span class="spacer"></span>
+ <!-- Hardware tier badge — clickable, opens a dialog explaining what
+ this Mac's RAM tier allows. Modes / qualities the tier doesn't
+ support are visibly disabled in the form below. -->
+ <span id="tierPill" class="pill" style="cursor:pointer" onclick="openTierModal()" title="Click to see what this Mac can do">click for system info</span>
+ <span id="memPill" class="pill">memory…</span>
+ <span id="comfyPill" class="pill" style="display:none">comfy…</span>
+ <span id="helperPill" class="pill">helper…</span>
+ <!-- Models pill: shows roll-up status (X / Y models ready) and click-opens
+ a modal with per-repo download buttons. Color reflects readiness:
+ pill-good = all models present, pill-warn = base ready but Q8 missing,
+ pill-bad = base incomplete (panel can't render). -->
+ <span id="modelsPill" class="pill" style="cursor:pointer" onclick="openModelsModal()" title="View / download model status">models…</span>
+ <span id="queuePill" class="pill">queue 0</span>
+ <span id="jobPill" class="pill">idle</span>
+ <!-- Update-available pill. Hidden by default; renders only when the
+ /version poller finds the install behind origin/main. Click → modal
+ listing the unseen commits. We do this because users keep telling
+ us "I clicked Update but I don't see anything" — by the time they
+ do, we've usually pushed three more fixes. -->
+ <!-- Version pill — the "magic button". Always visible so users learn
+ where to look. Clicking does the right thing for the state:
+ pill-current Y1.001 click → re-check GitHub now
+ pill-update ↑ Y1.002 click → git pull (then restart)
+ pill-restart ↻ restart click → just a reminder hint
+ pill-dev Y1.001 ⚙ click → toast with reason
+ pill-checking Y1.001 (idle, while first poll runs)
+ No modal — confirm() + small toast for everything. -->
+ <span id="versionPill" class="pill pill-checking" style="cursor:pointer"
+ onclick="versionPillClick()" title="Phosphene version">phosphene · …</span>
+ <!-- Bug-report button — neon-pulsing in the header pill row. Opens a
+ modal that pre-fills environment info + log tail and finishes with a
+ pre-filled GitHub issue (URL-built client-side, no auth). Sits before
+ the settings cog so it's where the user looks first when something
+ feels off. -->
+ <button id="bugBtn" class="icon-btn bug-btn" onclick="openBugModal()" title="Report a bug — opens GitHub issue with environment pre-filled">
+ <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
+ <path d="M8 2l1.88 1.88"></path>
+ <path d="M14.12 3.88L16 2"></path>
+ <path d="M9 7.13v-1a3.003 3.003 0 0 1 6 0v1"></path>
+ <path d="M12 20c-3.3 0-6-2.7-6-6v-3a4 4 0 0 1 4-4h4a4 4 0 0 1 4 4v3c0 3.3-2.7 6-6 6z"></path>
+ <path d="M12 20v-9"></path>
+ <path d="M6.53 9C4.6 8.8 3 7.1 3 5"></path>
+ <path d="M6 13H2"></path>
+ <path d="M3 21c0-2.1 1.7-3.8 3.8-4"></path>
+ <path d="M20.97 5c0 2.1-1.6 3.8-3.5 4"></path>
+ <path d="M22 13h-4"></path>
+ <path d="M17.2 17c2.1.2 3.8 1.9 3.8 4"></path>
+ </svg>
+ </button>
+ <!-- Settings cog: opens the modal that lets users pick output codec
+ presets (Standard / Video production / Web / Custom). Sits between the
+ runtime pills and Stop Comfy so it's findable but not loud. -->
+ <button id="settingsBtn" class="icon-btn" onclick="openSettingsModal()" title="Output settings — codec, file size">
+ <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
+ <circle cx="12" cy="12" r="3"></circle>
+ <path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"></path>
+ </svg>
+ </button>
+ <button id="stopComfyBtn" class="ghost-btn" style="display:none" onclick="api('/stop_comfy', 'POST').then(poll)">Stop Comfy</button>
+ <a class="creator-link" href="https://x.com/AIBizarrothe" target="_blank" rel="noopener" title="Follow Mr. Bizarro on X (the panel's creator)">
+ <img src="/assets/bizarro-avatar.jpg" class="creator-avatar" alt="">
+ <span>by Bizarro</span>
+ <span class="x-icon"><svg class="ph" aria-hidden="true" style="margin-right:3px;vertical-align:-2px"><use href="#ph-arrow-square-out"/></svg>X</span>
+ </a>
+</header>
-function imgStudioUpdateValidity() {
- const btn = document.getElementById('imgStudioGenBtn');
- const eng = document.getElementById('imgStudioEngine');
- const status = document.getElementById('imgStudioStatus');
- if (!btn || !eng) return;
- const refsCount = IMG_STUDIO.refs.filter(r => r && r.path).length;
- const needsRefs = imgStudioRequiresRefs(eng.value);
- let invalidReason = '';
- if (needsRefs && refsCount === 0) {
- invalidReason = 'Pick at least 1 reference image (drop a file into one of the 3 slots above) — Qwen-Image-Edit composes against an image, it cannot run text-only. Use the Lightning preset only after picking a ref.';
- }
- // Don't override the busy state — imgStudioGenerate manages disabled
- // during in-flight gens.
- if (!IMG_STUDIO.busy) {
- btn.disabled = !!invalidReason;
- btn.title = invalidReason || 'Generate (Cmd/Ctrl+Enter)';
- if (status && !status.textContent.startsWith('Generating')) {
- if (invalidReason) {
- status.innerHTML = '<svg class="ph" aria-hidden="true" style="margin-right:4px;vertical-align:-2px"><use href="#ph-warning-fill"/></svg>' + escapeHtml(invalidReason);
- } else {
- status.textContent = '';
- }
- }
- }
-}
+<main class="layout">
-// Reveal the mock-engine option only when the URL has ?debug=1.
-// Mock paints flat colored rectangles — useful for testing the UX
-// without spending GPU time, but a casual user picks it and gets
-// confused output. Audit finding HIGH #14.
-(function() {
- try {
- const params = new URLSearchParams(window.location.search);
- if (params.get('debug') === '1') {
- const m = document.getElementById('imgStudioMockOption');
- if (m) m.removeAttribute('hidden');
- }
- } catch (e) {}
-})();
+ <!-- ============== FORM PANE ============== -->
+ <aside class="form-pane">
-// Phase 1: Image Studio is now an inline pane (#studioSection) shown by
-// setMode('image'). These two functions stay as no-arg shims so any
-// caller still doing openImageStudio()/closeImageStudio() works.
-// Switching to 'image' shows the pane; switching to any other video
-// mode hides it. The pill row drives both flows.
-function openImageStudio() {
- setMode('image');
- // Re-evaluate Generate button state (engine + ref count) every time the
- // user enters Studio so they don't see a stale "ready" button when the
- // engine selection makes refs mandatory.
- imgStudioUpdateValidity();
- setTimeout(() => {
- const t = document.getElementById('imgStudioPrompt');
- if (t) {
- t.focus();
- try { t.scrollIntoView({behavior:'smooth', block:'center'}); } catch (e) {}
- }
- }, 50);
-}
+ <!-- Workflow tabs: switch the form-pane between the manual form and
+ the chat-driven planner. Default = manual; toggling persists in
+ localStorage so the user lands on the same tab next session. -->
+ <nav class="workflow-tabs" id="workflowTabs">
+ <button data-workflow="manual" class="active">Manual</button>
+ <button data-workflow="train">Train<span class="new-badge">NEW</span></button>
+ </nav>
+ <!-- The original manual form is unchanged; it sits below in the DOM
+ and is shown/hidden by JS as the workflow tab toggles. -->
+ <!-- Inline models card. Sits ABOVE the mode picker because for many
+ users the very first thing they need to do is download base
+ weights — burying that in a header modal hides the whole point
+ of the panel. Lives OUTSIDE #genForm so it persists across the
+ video-form ↔ Image-Studio swap. -->
+ <div id="modelsInline" class="models-inline" style="display:none">
+ <button type="button" class="models-inline-dismiss" id="modelsInlineDismiss"
+ title="Hide this card (won't show again until model state changes)"
+ onclick="dismissModelsCard()"><svg class="ph" aria-hidden="true"><use href="#ph-x-bold"/></svg></button>
+ <div class="models-inline-body">
+ <div class="models-inline-icon" id="modelsInlineIcon"><svg class="ph" aria-hidden="true"><use href="#ph-download-simple"/></svg></div>
+ <div class="models-inline-text">
+ <div class="ttl" id="modelsInlineTitle">Download required</div>
+ <div class="sub" id="modelsInlineSub">Click to start.</div>
+ <div class="models-inline-progress" id="modelsInlineProgress" style="display:none">
+ <div class="bar"><div class="fill" id="modelsInlineFill" style="width:0%"></div></div>
+ <div class="last" id="modelsInlineLast"></div>
+ </div>
+ </div>
+ <div class="models-inline-actions" id="modelsInlineActions"></div>
+ </div>
+ <a class="models-inline-link" onclick="openModelsModal()">Manage all models →</a>
+ </div>
-function closeImageStudio() {
- // Return to the last sensible video mode. t2v is the safe default;
- // a future enhancement could remember the previous mode the user was
- // on before clicking Studio. For Phase 1, t2v is fine.
- setMode('t2v');
-}
+ <!-- Mode bar — segmented chip strip. Lifted OUT of #genForm so it
+ stays visible when the user switches to Image Studio (which hides
+ #genForm). Without this, once a user clicks Studio they had no
+ way back to T2V/I2V short of refreshing. The hidden #mode input
+ stays inside #genForm (further below) so the video form's
+ FormData picks it up. The element keeps id=modeGroup and each
+ chip keeps data-mode + .pill-btn (alongside .mode-chip) so the
+ existing setMode() click wiring keeps working unchanged. -->
+ <div class="mode-bar pill-group" id="modeGroup">
+ <button type="button" class="mode-chip pill-btn" data-mode="t2v">Text<span class="mc-sub sub">prompt → video</span></button>
+ <button type="button" class="mode-chip pill-btn" data-mode="i2v">Image<span class="mc-sub sub">image + prompt</span></button>
+ <button type="button" class="mode-chip pill-btn" data-mode="keyframe">FFLF<span class="mc-sub sub">first + last</span></button>
+ <button type="button" class="mode-chip pill-btn" data-mode="extend">Extend<span class="mc-sub sub">continue a clip</span></button>
+ <button type="button" class="mode-chip pill-btn" data-mode="image" title="Open Image Studio — generate stills (Qwen-Image-Edit-2511 multi-ref + others)">Studio<span class="mc-sub sub">stills + library</span></button>
+ <!-- "Train" used to live here as a mode chip; it's been promoted to a
+ workflow tier (top tab strip, alongside Manual / Agentic Flows)
+ because training is a different category than rendering. -->
+ </div>
-function imgStudioWireRefSlots() {
- // Backwards-compat: the legacy `.img-ref-slot` selector matched the old
- // 3-column flat grid. The new restyled composer uses `.studio-ref-slot`.
- // Wire both so any in-flight upgrade path keeps working.
- document.querySelectorAll('.studio-ref-slot, .img-ref-slot').forEach(slot => {
- if (slot.dataset.wired === '1') return;
- slot.dataset.wired = '1';
- const idx = parseInt(slot.dataset.slot, 10);
- // Click → file picker. Skip when the user clicked the close (×) button
- // — its handler manages the clear flow.
- slot.addEventListener('click', (e) => {
- if (e.target.classList && e.target.classList.contains('clear-x')) return;
- const input = document.createElement('input');
- input.type = 'file';
- input.accept = 'image/png,image/jpeg,image/webp';
- input.onchange = () => {
- if (input.files && input.files[0]) imgStudioUploadRef(idx, input.files[0]);
- };
- input.click();
- });
- // Drag + drop. .dragover class is style-driven (no inline style) so it
- // composes cleanly with .has-image / hover.
- slot.addEventListener('dragover', (e) => {
- e.preventDefault();
- slot.classList.add('dragover');
- });
- slot.addEventListener('dragleave', () => slot.classList.remove('dragover'));
- slot.addEventListener('drop', (e) => {
- e.preventDefault();
- slot.classList.remove('dragover');
- const f = e.dataTransfer && e.dataTransfer.files && e.dataTransfer.files[0];
- if (f) imgStudioUploadRef(idx, f);
- });
- imgStudioRenderSlot(idx);
- });
-}
+ <form id="genForm">
+ <input type="hidden" name="preset_label" id="preset_label" value="">
+ <input type="hidden" name="mode" id="mode" value="t2v">
+ <input type="hidden" name="quality" id="quality" value="balanced">
+ <input type="hidden" name="accel" id="accel" value="off">
+ <input type="hidden" name="temporal_mode" id="temporal_mode" value="native">
+ <input type="hidden" name="upscale" id="upscale" value="fit_720p">
-const _STUDIO_REF_TAGS = ['Primary', 'Multi-ref', 'Multi-ref'];
+ <div id="warnBanner" class="warn-banner"></div>
-function imgStudioRenderSlot(idx) {
- const slot = document.querySelector(
- `.studio-ref-slot[data-slot="${idx}"], .img-ref-slot[data-slot="${idx}"]`);
- if (!slot) return;
- const ref = IMG_STUDIO.refs[idx];
- const tag = _STUDIO_REF_TAGS[idx] || `Ref ${idx + 1}`;
- if (ref && ref.path) {
- slot.classList.add('has-image');
- slot.innerHTML = `
- <span class="ref-tag">${tag}</span>
- <img src="/image?path=${encodeURIComponent(ref.path)}" alt="">
- <button class="clear-x" type="button" onclick="imgStudioClearRef(${idx});event.stopPropagation()" title="Remove"><svg class="ph" aria-hidden="true"><use href="#ph-x-bold"/></svg></button>
- `;
- } else {
- slot.classList.remove('has-image');
- const cta = idx === 0
- ? 'Drop · click<br>character'
- : (idx === 1 ? 'Drop · click<br>place' : 'Drop · click<br>style');
- slot.innerHTML = `
- <span class="ref-tag">${tag}</span>
- <div class="ref-empty">
- <div class="ref-icon"><svg class="ph" aria-hidden="true"><use href="#ph-image"/></svg></div>
- <div class="ref-cta">${cta}</div>
- </div>
- `;
- }
- imgStudioUpdateValidity();
- // Recent strip's "in-use" highlight depends on which paths are bound to
- // slots — re-render the strip so freshly-cleared slots release their
- // selection ring.
- if (typeof imgStudioMarkRecentInUse === 'function') imgStudioMarkRecentInUse();
-}
+ <!-- ============== COMPOSER CARD ==============
+ Hero element of the form. Carries the reference picker(s)
+ (mode-conditional), the prompt textarea, and an inline tools
+ strip (Enhance + HDR + No-music + Avoid disclosure). One
+ elevated surface so the prompt reads as the primary input. -->
+ <div class="composer-card">
+ <!-- Slot for the mode-conditional reference pickers. Each
+ .mode-only block is shown/hidden by setMode(); when none are
+ active (T2V), the slot collapses (CSS :empty/:not(.show)). -->
+ <div class="composer-refs">
+ <!-- I2V — single image ref. -->
+ <div class="mode-only" id="imageSection">
+ <h2>Reference image</h2>
+ <div class="picker" data-key="image">
+ <div class="picker-drop" id="picker_drop_image">
+ <div class="picker-empty">
+ <div class="picker-icon"><svg class="ph"><use href="#ph-image"/></svg></div>
+ <div class="picker-cta">Drop image here, or <strong>click to browse</strong></div>
+ <div class="hint">PNG / JPG / WEBP — auto cover-crop to model size</div>
+ </div>
+ <img class="picker-preview" id="picker_preview_image" alt="" style="display:none">
+ <button type="button" class="picker-clear" id="picker_clear_image" title="Clear" style="display:none"><svg class="ph" aria-hidden="true"><use href="#ph-x-bold"/></svg></button>
+ </div>
+ <input type="file" id="picker_file_image" accept="image/*" style="display:none">
+ <input type="hidden" name="image" id="image" value="">
+ <div class="picker-recent" id="picker_recent_image_wrap" style="display:none">
+ <div class="picker-recent-label">Recent uploads · click to use</div>
+ <div class="picker-recent-strip" id="picker_recent_image"></div>
+ </div>
+ </div>
+ </div>
-// ---- Engine status pill + wall-time estimate ----
-// Cache of /image/engine_status results so onchange handlers don't refetch
-// on every keystroke. Refreshed when setMode('image') runs and after a
-// successful Generate (in case the worker just downloaded weights).
-let _IMG_ENGINE_STATUS = {}; // engine_override -> {cached, download_gb, sec_per_image}
+ <!-- FFLF — start + end pickers. -->
+ <div class="mode-only" id="keyframeSection">
+ <h2>Start frame (frame 0)</h2>
+ <div class="picker" data-key="start_image">
+ <div class="picker-drop" id="picker_drop_start_image">
+ <div class="picker-empty">
+ <div class="picker-icon"><svg class="ph"><use href="#ph-film-strip"/></svg></div>
+ <div class="picker-cta">Drop the <strong>first frame</strong>, or <strong>click to browse</strong></div>
+ <div class="hint">This image opens the clip — its aspect picks the output dimensions.</div>
+ </div>
+ <img class="picker-preview" id="picker_preview_start_image" alt="" style="display:none">
+ <button type="button" class="picker-clear" id="picker_clear_start_image" title="Clear" style="display:none"><svg class="ph" aria-hidden="true"><use href="#ph-x-bold"/></svg></button>
+ </div>
+ <input type="file" id="picker_file_start_image" accept="image/*" style="display:none">
+ <input type="hidden" name="start_image" id="start_image" value="">
+ <div class="picker-recent" id="picker_recent_start_image_wrap" style="display:none">
+ <div class="picker-recent-label">Recent uploads · click to use</div>
+ <div class="picker-recent-strip" id="picker_recent_start_image"></div>
+ </div>
+ </div>
-async function imgStudioRefreshEngineStatus() {
- try {
- const r = await fetch('/image/engine_status');
- if (!r.ok) throw new Error('HTTP ' + r.status);
- const j = await r.json();
- const map = {};
- (j.engines || []).forEach(e => { map[e.engine] = e; });
- _IMG_ENGINE_STATUS = map;
- } catch (e) {
- // Silent — pill falls back to "unknown" (dim ellipsis).
- _IMG_ENGINE_STATUS = {};
- }
- imgStudioRenderEnginePill();
- imgStudioUpdateEstimate();
-}
+ <h2 style="margin-top:10px">End frame (last frame)</h2>
+ <div class="picker" data-key="end_image">
+ <div class="picker-drop" id="picker_drop_end_image">
+ <div class="picker-empty">
+ <div class="picker-icon"><svg class="ph"><use href="#ph-target"/></svg></div>
+ <div class="picker-cta">Drop the <strong>last frame</strong>, or <strong>click to browse</strong></div>
+ <div class="hint">A close-up here anchors face identity through the clip.</div>
+ </div>
+ <img class="picker-preview" id="picker_preview_end_image" alt="" style="display:none">
+ <button type="button" class="picker-clear" id="picker_clear_end_image" title="Clear" style="display:none"><svg class="ph" aria-hidden="true"><use href="#ph-x-bold"/></svg></button>
+ </div>
+ <input type="file" id="picker_file_end_image" accept="image/*" style="display:none">
+ <input type="hidden" name="end_image" id="end_image" value="">
+ <div class="picker-recent" id="picker_recent_end_image_wrap" style="display:none">
+ <div class="picker-recent-label">Recent uploads · click to use</div>
+ <div class="picker-recent-strip" id="picker_recent_end_image"></div>
+ </div>
+ </div>
-function imgStudioRenderEnginePill() {
- const pill = document.getElementById('imgStudioEnginePill');
- const eng = document.getElementById('imgStudioEngine');
- if (!pill || !eng) return;
- const v = eng.value;
- // 'auto' resolves to whatever the user saved in Settings — we don't try
- // to second-guess that here, just show a neutral pill.
- if (v === 'auto') {
- pill.dataset.state = 'unknown';
- pill.textContent = 'auto';
- pill.title = 'Uses your saved Settings engine';
- return;
- }
- const info = _IMG_ENGINE_STATUS[v];
- if (!info) {
- pill.dataset.state = 'unknown';
- pill.textContent = '…';
- pill.title = 'Checking weights…';
- return;
- }
- if (info.cached) {
- pill.dataset.state = 'ready';
- pill.innerHTML = '<svg class="ph" aria-hidden="true" style="margin-right:4px;vertical-align:-2px"><use href="#ph-check-bold"/></svg>ready';
- pill.title = 'Weights are cached locally';
- } else {
- pill.dataset.state = 'missing';
- const gb = info.download_gb || 0;
- pill.innerHTML = '<svg class="ph" aria-hidden="true" style="margin-right:4px;vertical-align:-2px"><use href="#ph-download-simple"/></svg>' + (gb > 0 ? gb.toFixed(0) + ' GB' : 'fetch');
- pill.title = (gb > 0
- ? `Weights not cached — first run will download ~${gb.toFixed(0)} GB`
- : 'Weights not cached — first run will fetch');
- }
-}
+ <div class="hint" style="margin-top:8px">FFLF needs Q8 (auto-selects High quality). The model interpolates between the two frames you provide.</div>
+ </div>
-function imgStudioUpdateEstimate() {
- const out = document.getElementById('imgStudioWallEstimate');
- const btnLabel = document.getElementById('imgStudioGenBtnLabel');
- if (!out || !btnLabel) return;
- const eng = (document.getElementById('imgStudioEngine') || {}).value || 'auto';
- const n = parseInt((document.getElementById('imgStudioN') || {}).value || '4', 10);
- const safeN = Math.max(1, Math.min(8, isFinite(n) ? n : 4));
- // Wall-time = cold_start (paid once per batch) + n × per-image (denoise).
- // /image/engine_status returns both fields. The HiDream lab subprocess
- // pays ~45s cold load per batch (BF16 weights -> MLX); mflux engines
- // fold theirs into sec_per_image (cold_start_sec=0). The auto preset
- // doesn't know its target ahead of time so we hide.
- const info = _IMG_ENGINE_STATUS[eng];
- let label = 'Generate';
- if (info && !info.cached && (info.download_gb || 0) > 0) {
- label = `Generate · downloads ~${info.download_gb.toFixed(0)} GB first`;
- }
- btnLabel.textContent = label;
- if (eng === 'auto' || !info || !info.sec_per_image) {
- out.textContent = '';
- out.classList.add('dim');
- return;
- }
- const coldStart = info.cold_start_sec || 0;
- const total = coldStart + safeN * info.sec_per_image;
- out.textContent = '~' + _imgStudioFmtDuration(total) + (safeN > 1 ? ` · ${safeN} imgs` : '');
- out.classList.remove('dim');
-}
+ <!-- Extend — source-video select + extend-by + direction +
+ extend-mode preset. Lives inside the composer card so the
+ prompt sits below the source picker, mirroring the I2V flow. -->
+ <div class="mode-only" id="extendSection">
+ <h2>Source video</h2>
+ <select id="extendSrcSelect" onchange="document.getElementById('video_path').value=this.value"></select>
+ <input name="video_path" id="video_path" placeholder="/path/to/source.mp4" style="margin-top:6px">
+ <div class="row" style="margin-top:8px">
+ <div>
+ <label class="lbl">Extend by (seconds)</label>
+ <!-- min must align to step from value=2: with min=0.4 step=0.5 the
+ valid sequence is 0.4, 0.9, 1.4, 1.9, 2.4… — `2` is OFF the
+ grid. Chrome blocks the entire form submission silently when
+ ANY input fails validation, even hidden ones in inactive
+ modes. Generate appeared dead until cocktailpeanut diagnosed
+ it. With min=0.5 the sequence is 0.5, 1.0, 1.5, 2.0… and
+ value=2 is valid. -->
+ <input id="extend_seconds" type="number" value="2" min="0.5" max="10" step="0.5">
+ <input type="hidden" name="extend_frames" id="extend_frames" value="6">
+ <div class="hint" id="extendDurationHint" style="margin-top:4px">≈ 2.0 s of new content (6 latent frames × 8 video frames at 24 fps)</div>
+ </div>
+ <div>
+ <label class="lbl">Direction</label>
+ <select name="extend_direction" id="extend_direction">
+ <option value="after" selected>After</option>
+ <option value="before">Before</option>
+ </select>
+ </div>
+ </div>
+ <label class="lbl" style="margin-top:10px">Extend mode</label>
+ <div class="pill-group cols-2" id="extendModeGroup">
+ <button type="button" class="pill-btn active" data-extend-mode="fast"><span>Fast</span><span class="sub">~16 min · 12 steps · 64 GB safe</span></button>
+ <button type="button" class="pill-btn" data-extend-mode="quality"><span>Quality</span><span class="sub">~38 min · 30 steps · 96+ GB</span></button>
+ </div>
+ <input type="hidden" name="extend_steps" id="extend_steps" value="12">
+ <input type="hidden" name="extend_cfg" id="extend_cfg" value="1.0">
+ <div class="hint">Each latent ≈ 8 frames (~0.33s). Quality mode runs the upstream defaults but pushes 1280×704 into swap on 64 GB Macs (~2 hr/render). Stick with Fast unless you've got more RAM.</div>
+ </div>
+ </div>
-function _imgStudioFmtDuration(sec) {
- sec = Math.max(0, Math.round(sec));
- if (sec < 60) return sec + 's';
- const m = Math.floor(sec / 60);
- const s = sec % 60;
- return s ? `${m}m ${s}s` : `${m}m`;
-}
+ <!-- Prompt — hero textarea. No h2 (the composer-card itself
+ announces "this is where you compose"). Audio-cue placeholder
+ is the only nudge users get to describe the soundscape;
+ documented in the LTX 2.3 paper but unobvious. -->
+ <textarea name="prompt" id="prompt" class="composer-prompt"
+ placeholder="Describe the scene AND the sound — e.g. wizard in a forest clearing, fireflies spiraling up · low whispered chant, ember crackle, distant owl. Audio is generated jointly with video; without sound cues the model outputs near-silent ambient."></textarea>
-// ---- Recent uploads strip ----
-async function imgStudioRefreshRecent() {
- const strip = document.getElementById('imgStudioRecentStrip');
- const wrap = document.getElementById('imgStudioRecentWrap');
- if (!strip || !wrap) return;
- let data;
- try { data = await api('/uploads?limit=18'); }
- catch (e) { return; }
- const items = (data && data.uploads) || [];
- if (!items.length) {
- wrap.style.display = 'none';
- return;
- }
- wrap.style.display = '';
- strip.innerHTML = items.map(u => `
- <img class="studio-ref-recent-thumb"
- src="${escapeHtml(u.url)}"
- data-path="${escapeHtml(u.path)}"
- title="${escapeHtml(u.name)} · ${u.size_kb} KB · ${escapeHtml(u.mtime)}"
- alt="">
- `).join('');
- strip.querySelectorAll('img').forEach(img => {
- img.addEventListener('click', () => {
- // Find the next empty slot, or replace slot 0 if all are full.
- const path = img.dataset.path;
- let target = IMG_STUDIO.refs.findIndex(r => !r || !r.path);
- if (target < 0) target = 0;
- const fname = (path || '').split('/').pop() || 'recent';
- IMG_STUDIO.refs[target] = { path, name: fname };
- imgStudioRenderSlot(target);
- imgStudioMarkRecentInUse();
- });
- });
- imgStudioMarkRecentInUse();
-}
+ <!-- Tools strip — Enhance + HDR + No-music + Avoid disclosure.
+ All inline so they read as part of composing the prompt.
+ Avoid is now a toggle-disclosure (collapsed by default) — it's
+ optional and most users won't touch it. -->
+ <div class="composer-tools">
+ <button type="button" class="ghost-btn" id="enhanceBtn" onclick="enhancePrompt()" title="Use Gemma to rewrite your prompt in the style LTX 2.3 was trained on"><svg class="ph" aria-hidden="true" style="margin-right:6px"><use href="#ph-sparkle-fill"/></svg>Enhance</button>
+ <button type="button" class="ct-link" id="avoidToggleBtn" onclick="toggleAvoidRow()" title="Add 'avoid' / negative prompt — things the model should NOT generate">
+ <span id="avoidToggleLabel">Avoid +</span>
+ </button>
+ <span class="ct-spacer"></span>
+ <label class="toggle-pill" id="hdrPill"
+ title="Boost dynamic range and color depth. Implemented as the official Lightricks HDR LoRA fused into the transformer. First HDR job spawns a one-time download (~120 MB) of the LoRA weights from Hugging Face, then renders share the cache.">
+ <input type="checkbox" id="hdr" name="hdr">
+ <span class="toggle-dot"></span>
+ <span>HDR</span>
+ </label>
+ <label class="toggle-pill" id="noMusicPill"
+ title="When on, the prompt is augmented with: 'Audio: voice and ambient sounds only, no music, no soundtrack, no score.' Useful for clips you'll score yourself in post — music can't be cleanly removed afterwards.">
+ <input type="checkbox" id="noMusic" name="no_music">
+ <span class="toggle-dot"></span>
+ <span>No music</span>
+ </label>
+ </div>
+ </div>
-function imgStudioMarkRecentInUse() {
- const strip = document.getElementById('imgStudioRecentStrip');
- if (!strip) return;
- const usedPaths = new Set(IMG_STUDIO.refs.filter(r => r && r.path).map(r => r.path));
- strip.querySelectorAll('img.studio-ref-recent-thumb').forEach(img => {
- img.classList.toggle('in-use', usedPaths.has(img.dataset.path));
- });
-}
+ <!-- Avoid (negative prompt) — collapsed by default; toggled by the
+ Avoid + button inside the composer-tools strip. Lives outside
+ the composer card so the textarea has its own framed surface
+ and the composer card stays focused on the positive prompt. -->
+ <div class="avoid-row" id="avoidRow">
+ <label class="avoid-label" for="negative_prompt">
+ <span>Avoid</span>
+ <span class="avoid-hint">things the model should NOT generate</span>
+ </label>
+ <textarea class="avoid-textarea" name="negative_prompt" id="negative_prompt" placeholder="blurry hands, distorted fingers, extra fingers, smeared face, warped text"></textarea>
+ </div>
-// Click handler for the engine-status pill. Only meaningful when the pill
-// is in 'missing' state — focus the Generate button so the user can hit it
-// with the download-consent label already showing. (We don't kick off a
-// pre-emptive `hf download` here: the queue worker already triggers one
-// on first render, and a separate code path would risk drift between the
-// prefetch + render configs.)
-function imgStudioOnPillClick() {
- const pill = document.getElementById('imgStudioEnginePill');
- if (!pill || pill.dataset.state !== 'missing') return;
- const btn = document.getElementById('imgStudioGenBtn');
- if (!btn) return;
- btn.focus();
- try { btn.scrollIntoView({behavior:'smooth', block:'center'}); } catch (e) {}
- const s = document.getElementById('imgStudioStatus');
- if (s) s.textContent = 'Click Generate to start — first run will download the engine weights.';
-}
+ <!-- ============== QUICK SETTINGS ==============
+ Quality picker (compact 4-up segmented strip) + Duration +
+ Frames + Seed in one dense block. Everything more advanced
+ (aspect, dims, speed, long-clips, export, audio source,
+ open-when-done) is folded into the Customize disclosure below. -->
+ <div class="quick-settings">
+ <div>
+ <div class="qs-label">
+ <span class="qs-name">Quality</span>
+ <span class="qs-meta" id="qualityMeta"></span>
+ </div>
+ <!-- Compact 4-col strip. Each chip carries name + a single spec
+ line. Same data-quality wiring as before so setQuality()
+ keeps working unchanged. The .pill-btn class is preserved
+ for the click handler that filters by it. -->
+ <div class="quality-strip pill-group" id="qualityGroup">
+ <button type="button" class="q-chip pill-btn pill-quality" data-quality="quick">
+ <span class="ql-name">Quick</span>
+ <span class="q-spec ql-spec sub">640×480</span>
+ <span class="ql-tier" hidden>Q4 · any Mac</span>
+ </button>
+ <button type="button" class="q-chip pill-btn pill-quality active" data-quality="balanced">
+ <span class="ql-name">Balanced</span>
+ <span class="q-spec ql-spec sub">1024×576</span>
+ <span class="ql-tier" id="balancedSub">Q4 · 5 min</span>
+ </button>
+ <button type="button" class="q-chip pill-btn pill-quality" data-quality="standard">
+ <span class="ql-name">Standard</span>
+ <span class="q-spec ql-spec sub">1280×704</span>
+ <span class="ql-tier" hidden>Q4 · standard tier+</span>
+ </button>
+ <button type="button" class="q-chip pill-btn pill-quality disabled" data-quality="high" id="qualityHigh">
+ <span class="ql-name">High</span>
+ <span class="q-spec ql-spec sub" id="highSpec">1024×576</span>
+ <span class="ql-tier" id="highSub">Q8 not installed</span>
+ </button>
+ </div>
+ </div>
-function imgStudioClearRef(idx) {
- IMG_STUDIO.refs[idx] = null;
- imgStudioRenderSlot(idx);
-}
+ <div class="mode-only show" id="quickMetricsRow">
+ <div class="mini-fields">
+ <div class="mf-cell">
+ <span class="mf-label">Duration (s)</span>
+ <input id="duration" value="5" type="number" min="1" max="20" step="1">
+ </div>
+ <div class="mf-cell">
+ <span class="mf-label">Frames <span class="mf-hint">8k+1</span></span>
+ <input name="frames" id="frames" value="121" type="number" min="1" title="Must be 8k+1 (e.g., 121, 161, 201). Duration auto-syncs.">
+ </div>
+ <div class="mf-cell">
+ <span class="mf-label">Seed <span class="mf-hint">-1 = random</span></span>
+ <input name="seed" id="seed" value="-1" title="-1 picks a fresh random seed per render. Any integer locks the seed for repeatable output.">
+ </div>
+ </div>
+ </div>
+ </div>
-async function imgStudioUploadRef(idx, file) {
- const fd = new FormData();
- // The panel's /upload endpoint expects the multipart field to be named
- // "image" (cgi.FieldStorage lookup); using "file" silently 400s.
- fd.append('image', file);
- try {
- const r = await fetch('/upload', { method: 'POST', body: fd });
- if (!r.ok) throw new Error(`upload ${r.status}`);
- const j = await r.json();
- if (!j.path) throw new Error('upload returned no path');
- IMG_STUDIO.refs[idx] = { path: j.path, name: file.name };
- imgStudioRenderSlot(idx);
- } catch (e) {
- const s = document.getElementById('imgStudioStatus');
- if (s) s.textContent = 'Upload failed: ' + e.message;
- }
-}
+ <!-- LoRA picker — UNIFIED across video form + Image Studio.
+ Lives inside #genForm by default (so the video form's FormData
+ picks up the hidden #lorasJson on submit), but on
+ setMode('image') the JS portals the visible <details> over to
+ #loraPickerStudioSlot so the SAME picker renders inside the
+ Studio composer. One source of truth: _activeLoras + the same
+ hidden #lorasJson field. The picker's library list is
+ filtered by /loras?mode=<tag> based on the current (mode +
+ engine) selection — see refreshLoras() in JS for the mapping.
-async function imgStudioGenerate() {
- if (IMG_STUDIO.busy) return;
- const prompt = (document.getElementById('imgStudioPrompt').value || '').trim();
- if (!prompt) {
- document.getElementById('imgStudioStatus').textContent = 'Prompt is required.';
- return;
- }
- const refs = IMG_STUDIO.refs.filter(r => r && r.path).map(r => r.path);
- const body = {
- prompt,
- n: parseInt(document.getElementById('imgStudioN').value || '4', 10),
- aspect: document.getElementById('imgStudioAspect').value || '16:9',
- seed: parseInt(document.getElementById('imgStudioSeed').value || '-1', 10),
- engine_override: document.getElementById('imgStudioEngine').value,
- refs,
- };
- // Submit through the same /queue/add endpoint video jobs use, with
- // mode='image'. The worker thread routes mode==='image' to
- // run_image_job_inner (commit 1). Progress streams into the panel
- // log + the right-rail Now/Queue/Recent cards exactly the way video
- // jobs do — no need for the Studio's own elapsed-counter or in-pane
- // result grid. The Recent tab's Photos filter (commit 2) surfaces
- // the result with thumbnail + Animate.
- IMG_STUDIO.busy = true;
- document.getElementById('imgStudioGenBtn').disabled = true;
- document.getElementById('imgStudioResults').innerHTML =
- '<div class="hint">Submitted to queue. Watch the Now / Recent tabs on the right ' +
- '(Recent → Photos for just images).</div>';
- document.getElementById('imgStudioStatus').textContent = 'Queueing…';
- try {
- const fd = new URLSearchParams();
- fd.set('mode', 'image');
- fd.set('prompt', body.prompt);
- fd.set('engine_override', body.engine_override || 'auto');
- fd.set('aspect', body.aspect || '16:9');
- fd.set('n', String(body.n || 4));
- fd.set('seed', String(body.seed != null ? body.seed : -1));
- // refs is a list of paths — the existing /image/generate code
- // accepts a JSON-encoded list as a form field, and make_job()
- // mode='image' parses the same shape (commit 1).
- fd.set('refs', JSON.stringify(body.refs || []));
- // Carry user-picked LoRAs through the same `loras` form field the
- // video form uses (parse_loras_from_form on the server is shared).
- // imgStudioGenerate doesn't go through FormData(genForm), so we
- // attach it explicitly from _activeLoras here. Stacks on top of any
- // preset LoRA the chosen engine_override pinned (Lightning, etc.) —
- // run_image_job_inner does the merge.
- if (typeof _activeLoras !== 'undefined' && Array.isArray(_activeLoras) && _activeLoras.length) {
- const slim = _activeLoras.map(l => ({ path: l.path, strength: l.strength }));
- fd.set('loras', JSON.stringify(slim));
- }
- const r = await fetch('/queue/add', { method: 'POST', body: fd });
- if (!r.ok) throw new Error(`HTTP ${r.status}`);
- document.getElementById('imgStudioStatus').textContent =
- 'Submitted. Watch Now / Recent → Photos.';
- // Non-blocking toast — the user can stay focused on the form (e.g.
- // queue a second variant) without reading the inline status line.
- if (typeof phosToast === 'function') {
- const n = body.n || 1;
- phosToast(`Queued ${n} image${n === 1 ? '' : 's'} · watch Recent → Photos`,
- { kind: 'success' });
- }
- // Briefly flash the bottom-pane Now tab so the user's eye is drawn
- // to where the live progress will appear. CSS handles the pulse;
- // we just toggle a class for a second.
- const nowTab = document.querySelector('.tabs button[data-tab="now"]');
- if (nowTab) {
- nowTab.classList.add('flash');
- setTimeout(() => nowTab.classList.remove('flash'), 1200);
- }
- // Recent uploads may now include the refs the user just touched, and
- // the worker will start downloading weights for an uncached engine —
- // refresh both so the next user click sees the fresh state.
- if (typeof imgStudioRefreshRecent === 'function') imgStudioRefreshRecent();
- setTimeout(() => {
- if (typeof imgStudioRefreshEngineStatus === 'function') imgStudioRefreshEngineStatus();
- }, 2000);
- } catch (e) {
- document.getElementById('imgStudioStatus').textContent = 'Submit failed: ' + e.message;
- if (typeof phosToast === 'function') {
- phosToast('Image submit failed: ' + (e.message || 'unknown'),
- { kind: 'danger', duration: 5000 });
- }
- } finally {
- IMG_STUDIO.busy = false;
- document.getElementById('imgStudioGenBtn').disabled = false;
- }
-}
+ Collapsible because most users won't touch it on a given
+ session, and inline because hiding it behind a modal makes
+ it easy to forget. Default open so first-time users see what's
+ inside without hunting for the disclosure triangle. -->
+ <div class="form-divider"></div>
+ <div id="loraPickerVideoSlot">
+ <details id="lorasDetails" open class="loras-section">
+ <summary class="loras-summary">
+ <span class="loras-chevron" aria-hidden="true"><svg class="ph"><use href="#ph-caret-down-bold"/></svg></span>
+ <span class="loras-title">LoRAs</span>
+ <span class="loras-meta" id="lorasSummaryCount">none active</span>
+ <!-- Action buttons live in the header so they're visible
+ regardless of how far the user has scrolled inside the
+ LoRA list. Rescan is icon-only (the ↻ glyph reads as
+ refresh universally); Browse CivitAI is the primary CTA
+ for adding new LoRAs so it's a coloured button.
+ event.stopPropagation() keeps clicks from toggling the
+ <details> open/closed state. -->
+ <span class="loras-header-actions">
+ <button type="button" class="loras-icon-btn"
+ title="Rescan mlx_models/loras/ for new files"
+ onclick="event.stopPropagation(); event.preventDefault(); refreshLoras()"><svg class="ph" aria-hidden="true"><use href="#ph-arrow-clockwise-bold"/></svg></button>
+ <button type="button" class="loras-browse-btn"
+ onclick="event.stopPropagation(); event.preventDefault(); openCivitaiModal()"><svg class="ph" aria-hidden="true" style="margin-right:6px;vertical-align:-2px"><use href="#ph-magnifying-glass"/></svg>Browse CivitAI</button>
+ </span>
+ </summary>
+ <div class="loras-body" id="lorasBody">
+ <!-- Mode/engine context banner — shows the active filter so
+ the user understands why some library entries are
+ hidden when they switch engine in Image Studio. -->
+ <div class="lora-mode-banner hint" id="loraModeBanner"
+ style="margin: 0 0 6px 0; font-size: 11px;"></div>
+ <!-- Filter/search box. Shows up only when 5+ LoRAs are
+ installed; below that it's just visual noise. Filters by
+ name AND trigger words (case-insensitive substring). -->
+ <div id="lorasFilterRow" style="display:none;">
+ <input type="text" id="lorasFilter" class="lora-filter"
+ placeholder="Filter LoRAs… (name or trigger word)"
+ oninput="renderLorasList()">
+ </div>
+ <div class="hint" id="lorasEmpty">
+ Drop <code>.safetensors</code> files into <code id="lorasDir">mlx_models/loras/</code>
+ to use them, or click <strong>Browse CivitAI</strong> above.
+ Each LoRA picks up an optional sidecar <code>.json</code> with
+ name + trigger words + recommended strength.
+ </div>
+ <div class="loras-list" id="lorasList"></div>
+ </div>
+ </details>
+ </div>
+ <div class="form-divider"></div>
+ <!-- Hidden field; updated by the LoRA picker JS to a JSON-encoded
+ array of {path, strength} that make_job parses. STAYS inside
+ #genForm even when the visible <details id="lorasDetails"> is
+ portaled over to the Studio slot — the video form's FormData
+ still needs to pick it up on submit. Image Studio submits go
+ through imgStudioGenerate() which reads _activeLoras directly
+ and attaches a `loras` field manually. -->
+ <input type="hidden" id="lorasJson" name="loras" value="">
-// imgStudioRefreshLibrary used to populate the right-pane Studio
-// gallery. The unified Recent tab (commit 2) now covers that need —
-// the function is kept as a no-op so any setMode('image') call sites
-// that still reference it (defensive setMode plumbing) don't error.
-async function imgStudioRefreshLibrary() {
- // intentionally empty: replaced by the unified Recent tab.
- return;
-}
+ <input type="hidden" name="steps" id="steps" value="8">
-function imgStudioCopyPath(path) {
- if (!path) return;
- const s = document.getElementById('imgStudioStatus');
- const flash = (msg) => {
- if (!s) return;
- const prev = s.textContent;
- s.textContent = msg;
- setTimeout(() => { if (s.textContent === msg) s.textContent = prev; }, 1500);
- };
- // navigator.clipboard isn't available in non-secure contexts (HTTP origins
- // other than localhost) and may reject if the page lacks focus. Fall back
- // to the legacy execCommand path so the user still gets the path on their
- // clipboard.
- const legacy = () => {
- try {
- const ta = document.createElement('textarea');
- ta.value = path;
- ta.style.position = 'fixed';
- ta.style.opacity = '0';
- document.body.appendChild(ta);
- ta.select();
- const ok = document.execCommand('copy');
- document.body.removeChild(ta);
- flash(ok ? 'Path copied.' : 'Copy failed — select the path manually.');
- } catch (e) {
- flash('Copy failed: ' + (e.message || 'unknown'));
- }
- };
- if (!navigator.clipboard || !navigator.clipboard.writeText) { legacy(); return; }
- navigator.clipboard.writeText(path).then(() => flash('Path copied.')).catch(() => legacy());
-}
+ <!-- ============== UNIFIED CUSTOMIZE DISCLOSURE ==============
+ Folds together the old "Customize" (aspect, dims, speed,
+ long-clips, export, method) and "Advanced" (audio source,
+ open-when-done) into ONE collapsed disclosure. Power users
+ open it; beginners ignore it. The summary line shows the
+ effective state so power users can scan at a glance.
-// ====== Train Character pane ================================================
-// In-progress dataset state. The job_id is minted by the server on the FIRST
-// upload of a session and echoed back on every subsequent /train/upload so
-// the whole batch lands in one folder under state/train_character/<id>/.
-const TRAIN = {
- jobId: null,
- // Mirror of the server-side image list. Each: {filename, path, src}.
- images: [],
- preset: 'quick',
- // Local mirror of the preset table; server has the authoritative copy in
- // TRAIN_PRESETS but the JS-side estimator is instant — saves a /status
- // round-trip per keystroke. Keep these in sync with TRAIN_PRESETS in py.
- presets: {
- quick: { steps: 1500, rank: 8, resolution: 512, seconds_per_step: 1.5, ram_peak_gb: 12,
- label: 'Quick', subtitle: '~30 min · rank 8 · 512px' },
- medium: { steps: 3000, rank: 16, resolution: 576, seconds_per_step: 2.2, ram_peak_gb: 18,
- label: 'Medium', subtitle: '~2 h · rank 16 · 576px' },
- high: { steps: 5000, rank: 32, resolution: 768, seconds_per_step: 3.0, ram_peak_gb: 28,
- label: 'High', subtitle: '~4 h · rank 32 · 768px' },
- },
- initialised: false,
-};
+ Lives at form level (not mode-conditional) — its inner rows
+ manage their own visibility (e.g. dimsRow hides in I2V flows;
+ i2vAudioModeSection only shows for I2V; method only shows
+ when an upscale is active). The wrapping #sizingSection
+ class kept for the mode-only show/hide that still toggles
+ it for Extend (Extend supplies its own duration/etc). -->
+ <div class="mode-only" id="sizingSection">
+ <details id="customizeDetails" class="customize-section">
+ <summary class="cz-summary">
+ <span class="cz-chevron" aria-hidden="true"><svg class="ph"><use href="#ph-caret-down-bold"/></svg></span>
+ <span class="cz-title">Customize</span>
+ <span class="cz-meta" id="customizeSummary">16:9 · default speed</span>
+ </summary>
+ <div class="cz-body">
+ <!-- Aspect — only relevant when the active Quality preset has
+ multiple aspects (Standard / High at 1280×704 vs 704×1280).
+ Hidden when Quick is active (640×480 is 4:3 only). -->
+ <div id="aspectRow" class="cz-control">
+ <div class="cz-label">Aspect ratio</div>
+ <div class="pill-group cols-2" id="aspectGroup">
+ <button type="button" class="pill-btn active" data-aspect="landscape"><span>16 : 9</span><span class="sub">horizontal</span></button>
+ <button type="button" class="pill-btn" data-aspect="vertical"><span>9 : 16</span><span class="sub">vertical</span></button>
+ </div>
+ <input type="hidden" id="aspect" value="landscape">
+ </div>
-const TRAIN_MIN = 15;
-const TRAIN_MAX = 50;
+ <!-- Width × height. Setting custom dimensions makes the form
+ leave the active preset (the Quality pill stays highlighted
+ but the Customize summary shows "custom" so the user knows
+ they've deviated). -->
+ <div id="dimsRow" class="cz-control">
+ <div class="cz-label">Width × height</div>
+ <div class="row">
+ <div><input name="width" id="width" value="1024" type="number" min="32" step="32" aria-label="Width"></div>
+ <div><input name="height" id="height" value="576" type="number" min="32" step="32" aria-label="Height"></div>
+ </div>
+ </div>
-function trainInit() {
- // Idempotent — safe to call on every setMode('train') without re-binding
- // the drop zone. Triggers a list refresh too so the user sees the LoRAs
- // they trained in earlier sessions.
- if (!TRAIN.initialised) {
- TRAIN.initialised = true;
- trainWireDropZone();
- trainWirePresetButtons();
- trainWireAdvancedFields();
- // Initial trigger value — JS-side generator (instant); /train/suggest-trigger
- // exists for non-JS callers.
- const t = document.getElementById('trainTrigger');
- if (t && !t.value) t.value = trainGenerateTriggerJS();
- document.getElementById('trainTriggerExample').textContent =
- (document.getElementById('trainTrigger').value || 'mrz07');
- document.getElementById('trainTrigger').addEventListener('input', () => {
- document.getElementById('trainTriggerExample').textContent =
- (document.getElementById('trainTrigger').value || 'mrz07');
- trainUpdateButtonState();
- trainUpdateEstimate();
- });
- }
- trainRefreshLoraList();
- trainUpdateEstimate();
- trainUpdateButtonState();
- trainCheckPreflight();
-}
+ <!-- Speed — experimental sampler acceleration. Boost/Turbo
+ skip 2-3 stable middle denoise calls. Off at High quality
+ (the two-stage HQ sampler doesn't support skipping). -->
+ <div class="cz-control">
+ <div class="cz-label">Speed
+ <span class="cz-label-hint">experimental — skip stable denoise steps</span>
+ </div>
+ <div class="pill-group cols-3" id="accelGroup">
+ <button type="button" class="pill-btn active" data-accel="off"><span>Exact</span><span class="sub">full sampler</span></button>
+ <button type="button" class="pill-btn" data-accel="boost"><span>Boost</span><span class="sub">~10-15% faster</span></button>
+ <button type="button" class="pill-btn" data-accel="turbo"><span>Turbo</span><span class="sub">~20-25% faster</span></button>
+ </div>
+ </div>
-// Hits /train/preflight and surfaces a banner inside the Train form when a
-// required model is missing. Today the only on-demand download is the LTX-2.3
-// dev transformer (~11 GB) — Phosphene's default install ships the distilled
-// transformer only. Banner offers a one-click Download button that triggers
-// /train/install + redirects to /status for progress.
-async function trainCheckPreflight() {
- const box = document.getElementById('trainPreflight');
- if (!box) return;
- try {
- const r = await fetch('/train/preflight');
- const data = await r.json();
- if (!data || !data.ok) { box.style.display = 'none'; return; }
- const missing = (data.required || []).filter(m => !m.ready);
- if (missing.length === 0) {
- box.style.display = 'none';
- return;
- }
- box.style.display = 'block';
- box.innerHTML = `
- <div class="train-preflight-card">
- <div class="train-preflight-title">
- <svg class="ph" aria-hidden="true" style="margin-right:6px;vertical-align:-2px"><use href="#ph-warning-fill"/></svg>Required model${missing.length > 1 ? 's' : ''} not downloaded
- </div>
- <div class="train-preflight-list">
- ${missing.map(m => `
- <div class="train-preflight-row">
- <div class="train-preflight-label">${m.label}
- <span class="train-preflight-size">~${m.size_gb} GB</span></div>
- <div class="train-preflight-blurb">${m.blurb}</div>
- <button type="button" class="btn btn-primary"
- onclick="trainInstall('${m.key}')">Download</button>
+ <!-- Long Clip Boost — asks LTX 2.3 to generate fewer semantic
+ frames at 12fps, then exports a normal 24fps file with
+ motion interpolation. This is explicit because dialogue,
+ lip-sync, and fast motion need user judgment. -->
+ <div class="cz-control" id="temporalRow">
+ <div class="cz-label">Long clips
+ <span class="cz-label-hint">experimental temporal interpolation</span>
+ </div>
+ <div class="pill-group cols-2" id="temporalGroup">
+ <button type="button" class="pill-btn active" data-temporal="native"><span>Native</span><span class="sub">24fps from LTX</span></button>
+ <button type="button" class="pill-btn" data-temporal="fps12_interp24"><span>12 → 24fps</span><span class="sub">half frames · interpolated</span></button>
+ </div>
+ </div>
+
+ <!-- Export upscale — target dims after render. "720p fit"
+ preserves aspect ratio (no crop, no distortion). 2× doubles
+ each side. Native skips the upscale entirely. The "Method"
+ row below picks how the upscaling is done. -->
+ <div class="cz-control">
+ <div class="cz-label">Export
+ <span class="cz-label-hint">post-render, no crop</span>
+ </div>
+ <div class="pill-group cols-3" id="upscaleGroup">
+ <button type="button" class="pill-btn active" data-upscale="off"><span>Native</span><span class="sub">as generated</span></button>
+ <button type="button" class="pill-btn" data-upscale="fit_720p"><span>720p fit</span><span class="sub">scale + pad</span></button>
+ <button type="button" class="pill-btn" data-upscale="x2"><span>2×</span><span class="sub">same ratio</span></button>
+ </div>
+ </div>
+
+ <!-- Upscale method. Hidden when Export = Native. Fast = ffmpeg
+ Lanczos resize, no detail recovery, near-instant. Sharp =
+ PiperSR/CoreML 2× post-upscale on Apple Neural Engine, then
+ ffmpeg fit/export. The old LTX latent upscaler path remains
+ hidden behind LTX_ENABLE_MODEL_UPSCALE for lab archaeology. -->
+ <div class="cz-control" id="upscaleMethodRow" style="display:none;">
+ <div class="cz-label">Method
+ <span class="cz-label-hint">how the upscale is done</span>
+ </div>
+ <div class="pill-group cols-2" id="upscaleMethodGroup">
+ <button type="button" class="pill-btn active" data-method="lanczos"><span>Fast</span><span class="sub">ffmpeg Lanczos · instant</span></button>
+ <button type="button" class="pill-btn" data-method="pipersr"><span>Sharp</span><span class="sub">PiperSR ANE · +30-90 s</span></button>
+ </div>
+ <input type="hidden" name="upscale_method" id="upscale_method" value="lanczos">
+ </div>
+
+ <!-- Audio source (I2V only) — folded in from the old separate
+ Advanced disclosure. Picker auto-hides when the current
+ mode isn't I2V (see updateDerived's mode-aware visibility). -->
+ <div class="cz-control mode-only" id="i2vAudioModeSection">
+ <div class="cz-label">I2V audio source
+ <span class="cz-label-hint">joint or external</span>
+ </div>
+ <select id="i2vMode">
+ <option value="i2v" selected>Joint audio (LTX generates audio synced with the visual)</option>
+ <option value="i2v_clean_audio">Use external audio file (mux it onto LTX video)</option>
+ </select>
+ <div class="mode-only" id="audioSection" style="margin-top:8px">
+ <label class="lbl">Audio file path</label>
+ <input name="audio" id="audio" placeholder="/path/to/your/track.wav">
+ </div>
+ </div>
+
+ <!-- Open file when done — minor convenience. Was its own row
+ in the old Advanced disclosure; now folded inline. -->
+ <div class="cz-control">
+ <label class="check" style="margin:0">
+ <input type="checkbox" name="open_when_done" id="open_when_done"> Open file when done
+ </label>
</div>
- `).join('')}
+ </div>
+ </details>
+
+ <div class="derived" id="derived"></div>
+ </div>
+
+ <!-- Comfy-kill toggle. Hidden in DOM by default; shown only when the
+ panel detects ComfyUI actually running on this Mac (see updateUI
+ in the poll handler). Default-off for public installs: killing a
+ neighboring Pinokio app should be an explicit choice, even when it
+ can free a lot of memory on 64 GB machines. -->
+ <div id="comfyKillRow" class="comfy-row" style="display:none">
+ <label class="lbl" style="display:flex; align-items:center; gap:8px; cursor:pointer">
+ <input type="checkbox" name="stop_comfy" id="stop_comfy" value="on">
+ <span>Stop ComfyUI before render <span style="color:var(--muted)">(optional · can free ~27 GB)</span></span>
+ </label>
+ </div>
+
+ <!-- ============== STICKY ACTION FOOTER ==============
+ Generate stays anchored at the bottom of the form-pane no
+ matter how far the user scrolls. The queue chip strip sits
+ above it (Batch / Pause / Clear) — compact pills, never the
+ primary touch target. -->
+ <div class="form-action-footer" id="formActionFooter">
+ <div class="queue-strip">
+ <button type="button" class="qchip" onclick="openBatch()" title="Paste many prompts at once and queue them">⊞ Batch</button>
+ <button type="button" class="qchip" id="pauseBtn" onclick="togglePause()" title="Pause / resume the render queue"><svg class="ph" aria-hidden="true" style="margin-right:6px;vertical-align:-2px"><use href="#ph-pause-fill"/></svg>Pause queue</button>
+ <button type="button" class="qchip" onclick="api('/queue/clear','POST').then(poll)" title="Clear all queued jobs (running job continues)"><svg class="ph" aria-hidden="true" style="margin-right:6px;vertical-align:-2px"><use href="#ph-x"/></svg>Clear</button>
+ <span class="qchip-spacer"></span>
+ <span class="qchip-derived" id="derivedFooter"></span>
</div>
- <div class="train-preflight-foot">
- Phosphene's default install ships only the inference model. The dev
- transformer is needed for training and is downloaded on demand to
- keep the base install lean.
+ <div class="actions">
+ <button type="submit" class="primary" id="genBtn">Generate</button>
+ <button type="button" class="danger" onclick="api('/stop', 'POST').then(poll)">Stop</button>
</div>
</div>
- `;
- } catch (e) {
- box.style.display = 'none';
- }
-}
+ </form>
-async function trainInstall(key) {
- const fd = new FormData();
- fd.set('key', key);
- try {
- const r = await fetch('/train/install', { method: 'POST', body: fd });
- const data = await r.json();
- if (!data.ok) {
- alert('Download failed: ' + (data.error || r.status));
- return;
- }
- // Progress streams to STATUS log. Re-poll preflight every 5s; banner
- // self-hides when the file lands.
- const watch = setInterval(async () => {
- try {
- const r2 = await fetch('/train/preflight');
- const d2 = await r2.json();
- const stillMissing = (d2.required || []).filter(m => !m.ready).length;
- if (stillMissing === 0) {
- clearInterval(watch);
- trainCheckPreflight();
- }
- } catch (e) { /* ignore */ }
- }, 5000);
- } catch (e) {
- alert('Download request failed: ' + e.message);
- }
-}
+ <!-- ============== IMAGE STUDIO (inline, mode='image') ============== -->
+ <!-- Sibling of #genForm inside form-pane. Shown/hidden by setMode().
+ Lives outside the form so its prompt textarea doesn't submit the
+ video form on Enter. The right rail (queue · current · history)
+ to the right of form-pane stays visible during image gen. -->
+ <!-- Restyled to mirror the video form-pane: same h2 mono-uppercase
+ section labels, same hairline-bordered input chrome, same picker
+ idiom for ref slots, same dense 2-col field grid for engine /
+ aspect / n / seed, and a Generate row with an inline wall-time
+ estimate that updates as the user changes engine + n + aspect.
+ An engine-status pill on the engine row tells the user whether
+ the chosen engine's weights are cached locally or need a fresh
+ download — driven by /image/engine_status (server-side cache
+ probe via _repo_hf_cache_dir). -->
+ <div class="mode-only studio-pane" id="studioSection">
+ <!-- ============== STUDIO COMPOSER CARD ==============
+ Same composer-card chrome as the video form. Refs (3 multi-ref
+ slots) sit at the top, the prompt is the hero, and the engine /
+ aspect / n / seed live in the Quick Settings strip below.
+ Generate sticks at the bottom (sticky footer) so it's always
+ one click away regardless of how far the user scrolls. -->
+ <div class="composer-card">
+ <div class="composer-refs">
+ <div class="show">
+ <h2>Reference images
+ <span class="h2-hint">multi-ref · Qwen-Image-Edit-2511 / FLUX.2 Klein-Edit only</span>
+ </h2>
+ <div class="studio-ref-grid" id="imgStudioRefs">
+ <div class="studio-ref-slot" data-slot="0">
+ <span class="ref-tag">Primary</span>
+ </div>
+ <div class="studio-ref-slot" data-slot="1">
+ <span class="ref-tag">Multi-ref</span>
+ </div>
+ <div class="studio-ref-slot" data-slot="2">
+ <span class="ref-tag">Multi-ref</span>
+ </div>
+ </div>
+ <!-- Mirrors the video I2V picker's "Recent uploads · click to use"
+ strip. Click a thumb → fills the next empty ref slot. Hidden
+ when /uploads is empty. -->
+ <div class="studio-ref-recent" id="imgStudioRecentWrap" style="display:none">
+ <div class="studio-ref-recent-label">Recent uploads · click to use</div>
+ <div class="studio-ref-recent-strip" id="imgStudioRecentStrip"></div>
+ </div>
+ </div>
+ </div>
-// Trigger generator — `<3 consonants><2 digits>` for rare/uncommon tokens.
-// Skip vowels + ambiguous letters (l, i, o → 1, 0). Mirrors the Python
-// _suggest_trigger_token; not a security boundary so the algorithms can
-// drift slightly — server has its own generator for non-JS callers.
-function trainGenerateTriggerJS() {
- const cons = 'bcdfghjkmnpqrstvwxyz';
- let letters = '';
- for (let i = 0; i < 3; i++) letters += cons[Math.floor(Math.random() * cons.length)];
- const digits = String(Math.floor(Math.random() * 100)).padStart(2, '0');
- return letters + digits;
-}
+ <textarea id="imgStudioPrompt" class="composer-prompt" rows="4"
+ placeholder="A cinematic medium close-up of a woman in a sunlit kitchen, soft morning light through blinds, shallow depth of field, photorealistic"></textarea>
+ </div>
-function trainSuggestTrigger() {
- const t = document.getElementById('trainTrigger');
- t.value = trainGenerateTriggerJS();
- document.getElementById('trainTriggerExample').textContent = t.value;
-}
+ <!-- Validation / status messages (e.g. "pick a ref image"). Lives
+ OUTSIDE the composer card so the card chrome stays focused on
+ composing. Empty by default. -->
+ <div class="studio-status-row" style="margin: 6px 0 -4px;">
+ <span id="imgStudioStatus" class="hint"></span>
+ </div>
-function trainWireDropZone() {
- const drop = document.getElementById('trainDrop');
- const input = document.getElementById('trainFileInput');
- if (!drop || !input) return;
- drop.addEventListener('click', (e) => {
- // Avoid re-firing the picker when the user clicks an existing thumb's
- // controls (× / num pill).
- if (e.target.closest('.train-thumb')) return;
- input.click();
- });
- drop.addEventListener('dragover', (e) => {
- e.preventDefault();
- drop.classList.add('dragover');
- });
- drop.addEventListener('dragleave', () => drop.classList.remove('dragover'));
- drop.addEventListener('drop', (e) => {
- e.preventDefault();
- drop.classList.remove('dragover');
- const files = e.dataTransfer && e.dataTransfer.files;
- if (files && files.length) trainUploadFiles(files);
- });
- input.addEventListener('change', () => {
- if (input.files && input.files.length) trainUploadFiles(input.files);
- input.value = '';
- });
-}
+ <!-- Quick settings — Engine on its own row (long labels), then a
+ dense 3-up row for Aspect / Candidates / Seed. Wall-time
+ estimate sits below the strip in the muted derived style. -->
+ <div class="quick-settings">
+ <div>
+ <div class="qs-label">
+ <span class="qs-name">Engine</span>
+ <span class="qs-meta" id="imgStudioWallEstimate"></span>
+ </div>
+ <div class="studio-engine-row">
+ <select id="imgStudioEngine" onchange="imgStudioUpdateValidity();imgStudioRefreshEngineStatus();imgStudioUpdateEstimate();if(typeof renderLorasList==='function')renderLorasList()">
+ <option value="auto">Auto (use Settings)</option>
+ <option value="qwen_edit_lightning_inline" selected>Qwen Fast (Lightning &middot; 4-step Q6 + FBCache, ~1:20 / image, multi-ref)</option>
+ <option value="qwen_edit_inline">Qwen Medium (8-step Q6 + FBCache, ~2:05 / image, multi-ref)</option>
+ <option value="qwen_edit_high_inline">Qwen Quality (40-step Q8 + CFG 4.0 + FBCache, ~3:50 / image, multi-ref)</option>
+ <option value="hidream_fast_inline">HiDream Fast (3-step, ~3:45 / 4-img batch, slight bg softness)</option>
+ <option value="hidream_inline">HiDream Medium (6-step + FBCache, ~6 min / 4-img batch, character-preserving)</option>
+ <option value="hidream_quality_inline">HiDream Quality (12-step + light FBCache, ~9 min / 4-img batch, best detail)</option>
+ <option value="mock_inline" id="imgStudioMockOption" hidden>Mock (testing — debug only)</option>
+ </select>
+ <span class="engine-status-pill" id="imgStudioEnginePill"
+ data-state="unknown" title="Checking engine weights…"
+ onclick="imgStudioOnPillClick()">…</span>
+ </div>
+ </div>
-function trainWirePresetButtons() {
- document.querySelectorAll('#trainPresetGroup .pill-btn').forEach(b => {
- b.addEventListener('click', () => {
- TRAIN.preset = b.dataset.trainPreset;
- document.querySelectorAll('#trainPresetGroup .pill-btn').forEach(x =>
- x.classList.toggle('active', x === b));
- trainUpdateEstimate();
- });
- });
-}
+ <div>
+ <div class="mini-fields">
+ <div class="mf-cell">
+ <span class="mf-label">Aspect</span>
+ <select id="imgStudioAspect" onchange="imgStudioUpdateEstimate()" style="padding:7px 9px;font-size:13px;">
+ <option value="16:9" selected>16:9 — 1280×720</option>
+ <option value="4:3">4:3 — 1024×768</option>
+ <option value="1:1">1:1 — 1024×1024</option>
+ <option value="9:16">9:16 — 720×1280</option>
+ <option value="3:4">3:4 — 768×1024</option>
+ <option value="21:9">21:9 — 1280×544</option>
+ </select>
+ </div>
+ <div class="mf-cell">
+ <span class="mf-label">Candidates (n)</span>
+ <input type="number" id="imgStudioN" min="1" max="8" value="4" oninput="imgStudioUpdateEstimate()">
+ </div>
+ <div class="mf-cell">
+ <span class="mf-label">Seed</span>
+ <input type="number" id="imgStudioSeed" value="-1" title="-1 = random">
+ </div>
+ </div>
+ </div>
+ </div>
-function trainWireAdvancedFields() {
- ['trainRank', 'trainSteps', 'trainLR', 'trainResolution', 'trainCaptionStrategy']
- .forEach(id => {
- const el = document.getElementById(id);
- if (el) el.addEventListener('change', trainUpdateEstimate);
- if (el) el.addEventListener('input', trainUpdateEstimate);
- });
-}
+ <!-- Slot for the unified LoRA picker. Empty by default; setMode('image')
+ portals #lorasDetails into here so the SAME picker the video form
+ uses appears tightly integrated under the Image Studio composer.
+ When the user switches engine (e.g. Qwen-Edit → FLUX.2 Klein-Edit)
+ the library auto-refilters via /loras?mode=image:flux2. Active
+ chips that don't match the current engine get a warning badge. -->
+ <div id="loraPickerStudioSlot"></div>
-async function trainUploadFiles(fileList) {
- const status = document.getElementById('trainStatus');
- const files = Array.from(fileList).filter(f =>
- /^image\/(png|jpe?g|webp)$/.test(f.type) ||
- /\.(png|jpe?g|webp)$/i.test(f.name));
- if (!files.length) {
- if (status) status.textContent = 'No supported image files in that selection.';
- return;
- }
- if (status) status.textContent = `Uploading 0 / ${files.length}…`;
+ <!-- Sticky action footer — same chrome as the video form's. Generate
+ stays anchored at the bottom of the form-pane no matter how far
+ the user has scrolled. Pause/Clear/Batch live above it as compact
+ pills, never the primary touch target. -->
+ <div class="form-action-footer" id="formActionFooterStudio">
+ <div class="queue-strip">
+ <button type="button" class="qchip" onclick="openBatch()" title="Paste many prompts at once and queue them">⊞ Batch</button>
+ <button type="button" class="qchip" id="pauseBtnStudio" onclick="togglePause()" title="Pause / resume the render queue"><svg class="ph" aria-hidden="true" style="margin-right:6px;vertical-align:-2px"><use href="#ph-pause-fill"/></svg>Pause queue</button>
+ <button type="button" class="qchip" onclick="api('/queue/clear','POST').then(poll)" title="Clear all queued jobs (running job continues)"><svg class="ph" aria-hidden="true" style="margin-right:6px;vertical-align:-2px"><use href="#ph-x"/></svg>Clear</button>
+ <span class="qchip-spacer"></span>
+ </div>
+ <div class="actions">
+ <button class="primary" id="imgStudioGenBtn" onclick="imgStudioGenerate()">
+ <span id="imgStudioGenBtnLabel">Generate</span>
+ </button>
+ <button type="button" class="danger" onclick="api('/stop', 'POST').then(poll)">Stop</button>
+ </div>
+ </div>
- // Optimistic UI: render placeholders for the incoming batch using
- // FileReader to get a local data URL so the user sees the crop preview
- // immediately. Each placeholder is replaced with the server-saved path
- // once /train/upload returns.
- for (let i = 0; i < files.length; i++) {
- const f = files[i];
- if (TRAIN.images.length >= TRAIN_MAX) {
- if (status) status.textContent = `At max ${TRAIN_MAX} images. Stopping upload.`;
- break;
- }
- const localUrl = await trainFileToDataURL(f).catch(() => null);
- const placeholderIdx = TRAIN.images.length;
- TRAIN.images.push({
- filename: '__uploading__' + placeholderIdx,
- path: '',
- src: localUrl || '',
- uploading: true,
- });
- trainRenderThumbs();
+ <!-- Submission status. Image jobs flow through the same queue as
+ video jobs now, so the actual results show up in the right-rail
+ Recent tab (with the Photos filter) along with everything else.
+ This pane is just a thin "submitted" confirmation. -->
+ <div id="imgStudioResults" class="studio-results"></div>
+ </div>
- try {
- const fd = new FormData();
- fd.append('file', f, f.name);
- if (TRAIN.jobId) fd.append('job_id', TRAIN.jobId);
- const r = await fetch('/train/upload', { method: 'POST', body: fd });
- const j = await r.json();
- if (!r.ok || !j.ok) {
- // Remove the placeholder; surface the error.
- TRAIN.images.splice(placeholderIdx, 1);
- if (status) status.textContent = 'Upload error: ' + (j.error || r.status);
- trainRenderThumbs();
- continue;
- }
- TRAIN.jobId = j.job_id;
- TRAIN.images[placeholderIdx] = {
- filename: j.filename,
- path: j.path,
- src: '/train/file?job_id=' + encodeURIComponent(j.job_id) +
- '&filename=' + encodeURIComponent(j.filename) +
- '&v=' + Date.now(),
- uploading: false,
- };
- trainRenderThumbs();
- if (status) status.textContent = `Uploaded ${i + 1} / ${files.length}…`;
- } catch (e) {
- TRAIN.images.splice(placeholderIdx, 1);
- if (status) status.textContent = 'Upload failed: ' + (e.message || 'unknown');
- trainRenderThumbs();
- }
- }
- if (status) {
- const n = TRAIN.images.length;
- if (n < TRAIN_MIN) status.textContent = `${n} image${n === 1 ? '' : 's'} uploaded — need ${TRAIN_MIN - n} more to train.`;
- else status.textContent = `${n} images ready — pick a preset and start training.`;
- }
- trainUpdateEstimate();
- trainUpdateButtonState();
-}
+ <!-- ============== TRAIN CHARACTER (inline, mode='train') ============== -->
+ <!-- Sibling of #genForm and #studioSection inside form-pane. Shown by
+ setMode('train'). Trains a character LoRA against 15-50 user
+ stills. Pipeline lives in the sibling lora-lab repo; this panel
+ shells out to it via /train/start. Job status surfaces through
+ the existing Now / Queue / Recent / Logs panes (training is just
+ another mode dispatch in run_job_inner). -->
+ <div class="mode-only train-pane" id="trainSection">
-function trainFileToDataURL(file) {
- return new Promise((resolve, reject) => {
- const r = new FileReader();
- r.onload = () => resolve(r.result);
- r.onerror = reject;
- r.readAsDataURL(file);
- });
-}
+ <!-- Preflight model check — hidden by default; populated by
+ trainCheckPreflight() if any required model file is missing
+ (today: transformer-dev.safetensors which isn't in default install). -->
+ <div id="trainPreflight" style="display:none"></div>
-function trainRenderThumbs() {
- const wrap = document.getElementById('trainThumbs');
- const empty = document.getElementById('trainDropEmpty');
- const drop = document.getElementById('trainDrop');
- const clearAllBtn = document.getElementById('trainClearAllBtn');
- if (!wrap) return;
- if (TRAIN.images.length === 0) {
- wrap.hidden = true;
- if (empty) empty.style.display = '';
- if (drop) drop.classList.remove('has-images');
- if (clearAllBtn) clearAllBtn.hidden = true;
- trainUpdateCounter();
- return;
- }
- wrap.hidden = false;
- if (empty) empty.style.display = 'none';
- if (drop) drop.classList.add('has-images');
- if (clearAllBtn) clearAllBtn.hidden = false;
- wrap.innerHTML = TRAIN.images.map((img, idx) => {
- const cls = 'train-thumb' + (img.uploading ? ' uploading' : '');
- const removeAttr = img.uploading
- ? ''
- : `onclick="trainRemoveImage('${img.filename.replace(/'/g, "\\'")}')"`;
- return `<div class="${cls}" data-idx="${idx}">
- <img src="${img.src || ''}" alt="char ${idx + 1}" loading="lazy">
- <span class="train-thumb-num">${String(idx + 1).padStart(3, '0')}</span>
- <button type="button" class="train-thumb-x" ${removeAttr} title="Remove"><svg class="ph" aria-hidden="true"><use href="#ph-x-bold"/></svg></button>
- </div>`;
- }).join('');
- trainUpdateCounter();
-}
+ <!-- ============== DATASET CARD ============== -->
+ <div class="composer-card train-card">
+ <h2>Dataset
+ <span class="h2-hint">15-50 stills · drop your character into the box</span>
+ </h2>
+ <div class="train-drop" id="trainDrop">
+ <div class="train-drop-empty" id="trainDropEmpty">
+ <div class="picker-icon"><svg class="ph"><use href="#ph-image"/></svg></div>
+ <div class="picker-cta">Drop 15-50 images here, or <strong>click to browse</strong></div>
+ <div class="hint">PNG / JPG / WEBP. Each preview shows the 1:1 center-crop the trainer will see.</div>
+ </div>
+ <div class="train-thumbs" id="trainThumbs" hidden></div>
+ <input type="file" id="trainFileInput" accept="image/png,image/jpeg,image/webp" multiple style="display:none">
+ </div>
+ <div class="train-counter-row">
+ <span class="train-counter" id="trainCounter">0 / 50 images</span>
+ <span class="train-counter-hint" id="trainCounterHint">need at least 15 to train</span>
+ <span class="qchip-spacer"></span>
+ <button type="button" class="qchip" id="trainClearAllBtn" onclick="trainClearAll()" hidden><svg class="ph" aria-hidden="true" style="margin-right:6px;vertical-align:-2px"><use href="#ph-x"/></svg>Clear all</button>
+ </div>
+ </div>
-function trainUpdateCounter() {
- const counter = document.getElementById('trainCounter');
- const hint = document.getElementById('trainCounterHint');
- if (!counter) return;
- const n = TRAIN.images.length;
- counter.textContent = `${n} / ${TRAIN_MAX} images`;
- counter.classList.toggle('ok', n >= TRAIN_MIN);
- counter.classList.toggle('short', n > 0 && n < TRAIN_MIN);
- if (hint) {
- if (n === 0) hint.textContent = `need at least ${TRAIN_MIN} to train`;
- else if (n < TRAIN_MIN) hint.textContent = `need ${TRAIN_MIN - n} more`;
- else if (n < TRAIN_MAX) hint.textContent = `ready · up to ${TRAIN_MAX - n} more if you want variety`;
- else hint.textContent = `at the ${TRAIN_MAX}-image limit`;
- }
-}
+ <!-- ============== TRIGGER + PRESET ============== -->
+ <div class="composer-card train-card">
+ <h2>Trigger word
+ <span class="h2-hint">a rare token the model will associate with this character</span>
+ </h2>
+ <div class="train-trigger-row">
+ <input type="text" id="trainTrigger" maxlength="32" placeholder="auto-generated rare token" autocomplete="off">
+ <button type="button" class="qchip" onclick="trainSuggestTrigger()" title="Suggest a fresh rare token">↻ Suggest</button>
+ </div>
+ <div class="hint">Use the trigger word in your video prompts (e.g. <code><span id="trainTriggerExample">mrz07</span> man walking on the beach</code>).</div>
-async function trainRemoveImage(filename) {
- if (!TRAIN.jobId || !filename) return;
- try {
- const fd = new URLSearchParams();
- fd.set('train_job_id', TRAIN.jobId);
- fd.set('filename', filename);
- const r = await fetch('/train/remove-image', { method: 'POST', body: fd });
- const j = await r.json();
- if (!r.ok || !j.ok) {
- console.warn('remove-image failed', j);
- return;
- }
- // Server renumbers char_001…NN; re-pull the canonical list so our
- // src URLs match the new filenames on disk.
- await trainRefreshDataset();
- } catch (e) {
- console.warn('remove-image error', e);
- }
-}
+ <h2 style="margin-top:14px">Quality preset
+ <span class="h2-hint">trade time for fidelity</span>
+ </h2>
+ <div class="pill-group cols-3" id="trainPresetGroup">
+ <button type="button" class="pill-btn active" data-train-preset="quick"><span>Quick <span class="rec-badge">Recommended</span></span><span class="sub" id="trainPresetQuickSub">~30 min · rank 8 · 512px</span></button>
+ <button type="button" class="pill-btn" data-train-preset="medium"><span>Medium</span><span class="sub" id="trainPresetMediumSub">~2 h · rank 16 · 576px</span></button>
+ <button type="button" class="pill-btn" data-train-preset="high"><span>High</span><span class="sub" id="trainPresetHighSub">~4 h · rank 32 · 768px</span></button>
+ </div>
-async function trainClearAll() {
- if (!TRAIN.images.length) return;
- if (!confirm(`Remove all ${TRAIN.images.length} uploaded images?`)) return;
- const toRemove = TRAIN.images.filter(x => !x.uploading).map(x => x.filename);
- for (const f of toRemove) {
- await trainRemoveImage(f);
- }
- TRAIN.images = [];
- trainRenderThumbs();
- trainUpdateEstimate();
- trainUpdateButtonState();
-}
+ <details class="train-advanced">
+ <summary>Advanced</summary>
+ <div class="train-advanced-grid">
+ <div class="mf-cell">
+ <span class="mf-label">Rank</span>
+ <select id="trainRank">
+ <option value="">preset default</option>
+ <option value="8">8</option>
+ <option value="16">16</option>
+ <option value="32">32</option>
+ <option value="64">64</option>
+ </select>
+ </div>
+ <div class="mf-cell">
+ <span class="mf-label">Steps</span>
+ <input type="number" id="trainSteps" min="100" max="10000" step="100" placeholder="preset default">
+ </div>
+ <div class="mf-cell">
+ <span class="mf-label">Learning rate</span>
+ <select id="trainLR">
+ <option value="">preset default</option>
+ <option value="0.00005">5e-5</option>
+ <option value="0.0001">1e-4</option>
+ <option value="0.0002">2e-4</option>
+ <option value="0.0005">5e-4</option>
+ </select>
+ </div>
+ <div class="mf-cell">
+ <span class="mf-label">Resolution</span>
+ <select id="trainResolution">
+ <option value="">preset default</option>
+ <option value="512">512²</option>
+ <option value="576">576²</option>
+ <option value="768">768²</option>
+ </select>
+ </div>
+ <div class="mf-cell" style="grid-column: 1 / -1">
+ <span class="mf-label">Caption strategy</span>
+ <select id="trainCaptionStrategy">
+ <option value="trigger_simple" selected>&lt;trigger&gt; man — dumbest-strongest default</option>
+ <option value="trigger_only">trigger only — no role hint</option>
+ <option value="qwen_vl" disabled>auto-caption via Qwen-VL — coming soon</option>
+ </select>
+ </div>
+ </div>
+ <div class="hint" style="margin-top:8px">Auto-captioning planned. For now, every image gets the same caption — the trigger does the heavy lifting.</div>
+ </details>
+ </div>
-async function trainRefreshDataset() {
- if (!TRAIN.jobId) {
- TRAIN.images = [];
- trainRenderThumbs();
- return;
- }
- try {
- const r = await fetch('/train/dataset?job_id=' + encodeURIComponent(TRAIN.jobId));
- const j = await r.json();
- if (!j.ok) return;
- TRAIN.images = (j.images || []).map(im => ({
- filename: im.filename,
- path: im.path,
- src: '/train/file?job_id=' + encodeURIComponent(TRAIN.jobId) +
- '&filename=' + encodeURIComponent(im.filename) + '&v=' + Date.now(),
- uploading: false,
- }));
- trainRenderThumbs();
- trainUpdateEstimate();
- trainUpdateButtonState();
- } catch (e) { console.warn('train dataset refresh failed', e); }
-}
+ <!-- Estimate strip — wall time + RAM peak update as inputs
+ change. Hidden until at least one image is in the dataset:
+ before that, the estimate row is misleading ("— · —" reads
+ as "data missing" not "waiting on you"). Shown by
+ trainRenderImagesGrid() the moment count > 0. -->
+ <div class="train-estimate" id="trainEstimate" style="display:none">
+ <span class="train-est-line">
+ <span class="train-est-label">Estimated wall time</span>
+ <span class="train-est-value" id="trainEstimateTime">—</span>
+ </span>
+ <span class="train-est-line">
+ <span class="train-est-label">Peak RAM</span>
+ <span class="train-est-value" id="trainEstimateRam">—</span>
+ </span>
+ <span class="train-est-line">
+ <span class="train-est-label">Output</span>
+ <span class="train-est-value" id="trainEstimateOut">—</span>
+ </span>
+ </div>
-function trainEffectiveSteps() {
- const v = (document.getElementById('trainSteps').value || '').trim();
- if (!v) return null;
- const n = parseInt(v, 10);
- return Number.isFinite(n) && n > 0 ? n : null;
-}
+ <!-- Validation/status messages (e.g. "need 10 more images"). -->
+ <div class="studio-status-row" style="margin: 4px 0 0;">
+ <span id="trainStatus" class="hint"></span>
+ </div>
-function trainUpdateEstimate() {
- const preset = TRAIN.presets[TRAIN.preset] || TRAIN.presets.quick;
- const stepOverride = trainEffectiveSteps();
- const steps = stepOverride || preset.steps;
- const n = TRAIN.images.length;
- const sec = Math.round(3 * Math.max(0, n) + steps * preset.seconds_per_step + 30);
- // Estimate row is hidden until the user has dropped at least one
- // image. Before that, the row reads as missing data — not a useful
- // signal. Once there's data, reveal the row + populate it.
- const row = document.getElementById('trainEstimate');
- if (row) row.style.display = n === 0 ? 'none' : '';
- const ramRow = document.getElementById('trainEstimateRam');
- const timeRow = document.getElementById('trainEstimateTime');
- const outRow = document.getElementById('trainEstimateOut');
- if (timeRow && n > 0) timeRow.textContent = trainFmtDuration(sec) + ` · ${steps} steps`;
- if (ramRow) ramRow.textContent = `~${preset.ram_peak_gb} GB peak`;
- if (outRow) {
- const trig = (document.getElementById('trainTrigger').value || 'mrz07');
- outRow.textContent = `mlx_models/loras/${(TRAIN.jobId || 'trn-<new>')}.safetensors · trigger "${trig}"`;
- }
-}
+ <!-- Sticky action footer — same chrome as the video/studio forms. -->
+ <div class="form-action-footer" id="formActionFooterTrain">
+ <div class="queue-strip">
+ <button type="button" class="qchip" id="pauseBtnTrain" onclick="togglePause()" title="Pause / resume the queue"><svg class="ph" aria-hidden="true" style="margin-right:6px;vertical-align:-2px"><use href="#ph-pause-fill"/></svg>Pause queue</button>
+ <button type="button" class="qchip" onclick="api('/queue/clear','POST').then(poll)" title="Clear all queued jobs"><svg class="ph" aria-hidden="true" style="margin-right:6px;vertical-align:-2px"><use href="#ph-x"/></svg>Clear</button>
+ <span class="qchip-spacer"></span>
+ </div>
+ <div class="actions">
+ <button type="button" class="primary" id="trainStartBtn" onclick="trainStart()" disabled>Start training</button>
+ <button type="button" class="danger" onclick="api('/stop','POST').then(poll)">Stop</button>
+ </div>
+ </div>
-function trainFmtDuration(sec) {
- if (sec < 60) return `${sec} s`;
- const m = Math.round(sec / 60);
- if (m < 60) return `${m} min`;
- const h = Math.floor(m / 60);
- const rem = m % 60;
- return rem ? `${h} h ${rem} min` : `${h} h`;
-}
+ <!-- ============== TRAINED LORAs LIST ============== -->
+ <div class="composer-card train-card">
+ <h2>Trained character LoRAs
+ <span class="h2-hint">your finished runs — click to use</span>
+ </h2>
+ <div class="train-lora-list" id="trainLoraList">
+ <div class="hint" style="padding:12px 0">No trained LoRAs yet. Start your first run above.</div>
+ </div>
+ <div class="hint" style="margin-top:4px">Trained LoRAs land in <code id="trainLorasDir">mlx_models/loras/</code> alongside any LoRAs you've downloaded — they show up in the regular picker too.</div>
+ </div>
-function trainUpdateButtonState() {
- const btn = document.getElementById('trainStartBtn');
- if (!btn) return;
- const n = TRAIN.images.filter(x => !x.uploading).length;
- const trig = (document.getElementById('trainTrigger').value || '').trim();
- const ok = n >= TRAIN_MIN && trig.length >= 3 && trig.length <= 32;
- btn.disabled = !ok;
- if (!ok) {
- if (n < TRAIN_MIN) btn.title = `Need at least ${TRAIN_MIN} images (have ${n}).`;
- else if (trig.length < 3) btn.title = 'Trigger word must be 3+ characters.';
- else btn.title = 'Trigger word is too long (max 32).';
- } else {
- btn.title = 'Queue this training job.';
- }
-}
+ </div>
+ </aside>
+
+ <!-- ============== STAGE PANE: PLAYER + CAROUSEL ============== -->
+ <!-- REDESIGN — Y2.001 stage-pane.
+ Replaces the legacy "video → meta strip → header → two filter rows
+ → carousel" stack with a composer-grade layout that mirrors the
+ form-pane redesign: one elevated player surface with overlaid
+ chrome, a single combined filter row, and richer carousel cards
+ whose chrome lives on hover. All legacy IDs/handlers preserved
+ (#playerWrap, #playerMeta, #playerName, #loadParamsBtn,
+ #useAsExtendBtn, #animateBtn, #carousel, #carouselTitle,
+ #mainOutputsFilter*) so the JS layer keeps working unchanged.
+ (#filterAll/#filterHidden retired with the Visible/Hidden
+ segmented control — orphan textContent/setFilter calls removed.) -->
+ <section class="stage-pane">
+ <!-- Player surface — the hero. Holds the <video>/<img>, the filename
+ overlay (top), the action overlay (top-right), and an inline
+ job-progress overlay (bottom) when something is rendering. The
+ #playerMeta strip is preserved as a hidden a11y/data slot so
+ legacy callers that read its IDs (selectOutput updates them)
+ still find them — but it's never shown. -->
+ <div class="player-surface">
+ <div class="player-wrap empty" id="playerWrap">
+ <div class="ps-empty">
+ <div class="ps-empty-icon" aria-hidden="true">
+ <svg width="56" height="56" viewBox="0 0 56 56" fill="none">
+ <circle cx="28" cy="28" r="22" stroke="currentColor" stroke-width="1.5" stroke-opacity="0.35"/>
+ <path d="M23 19 L37 28 L23 37 Z" fill="currentColor" fill-opacity="0.45"/>
+ </svg>
+ </div>
+ <div class="ps-empty-title">No outputs yet</div>
+ <div class="ps-empty-sub">Generate something on the left and the result lands here.</div>
+ </div>
+ </div>
+ <!-- Top overlay: filename + relative time + size. Hidden until an
+ output is selected; shown by selectOutput(). -->
+ <div class="player-overlay-top" id="playerOverlayTop" style="display:none">
+ <div class="po-name" id="playerOverlayName"></div>
+ <div class="po-meta" id="playerOverlayMeta"></div>
+ </div>
+ <!-- Top-right action cluster. Icon buttons with tooltips replace
+ the old text-button row. Each carries a data-action attribute
+ that the old IDs alias to, so legacy code touching them keeps
+ working (loadParamsBtn.disabled, animateBtn.style.display,
+ useAsExtendBtn.style.display all still apply). -->
+ <div class="player-overlay-actions" id="playerOverlayActions" style="display:none">
+ <button id="loadParamsBtn" class="po-act" type="button"
+ onclick="loadParams()" title="Load this clip's render params back into the form" disabled>
+ <svg width="14" height="14" viewBox="0 0 16 16" fill="none" aria-hidden="true">
+ <path d="M3 8 L8 13 L13 8 M8 3 L8 13" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
+ </svg>
+ <span class="po-act-label">Params</span>
+ </button>
+ <button id="useAsExtendBtn" class="po-act" type="button"
+ onclick="useAsExtendSource()" title="Use this clip as the source for an Extend job">
+ <svg width="14" height="14" viewBox="0 0 16 16" fill="none" aria-hidden="true">
+ <path d="M3 8 L13 8 M9 4 L13 8 L9 12" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
+ </svg>
+ <span class="po-act-label">Extend</span>
+ </button>
+ <button id="animateBtn" class="po-act" type="button"
+ onclick="animateActive()" style="display:none" title="Animate this still as an i2v render">
+ <svg width="14" height="14" viewBox="0 0 16 16" fill="none" aria-hidden="true">
+ <path d="M5 3 L13 8 L5 13 Z" stroke="currentColor" stroke-width="1.5" stroke-linejoin="round" fill="none"/>
+ </svg>
+ <span class="po-act-label">Animate</span>
+ </button>
+ <button id="expandBtn" class="po-act" type="button"
+ onclick="openExpandLightbox()" title="Expand to fullscreen (Esc to close)">
+ <svg width="14" height="14" viewBox="0 0 16 16" fill="none" aria-hidden="true">
+ <path d="M3 6 V3 H6 M10 3 H13 V6 M13 10 V13 H10 M6 13 H3 V10"
+ stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
+ </svg>
+ <span class="po-act-label">Expand</span>
+ </button>
+ <button class="po-act po-act-danger" type="button"
+ onclick="hideActive()" title="Hide this output from the gallery">
+ <svg width="14" height="14" viewBox="0 0 16 16" fill="none" aria-hidden="true">
+ <path d="M2 8 C 4 4, 12 4, 14 8 C 12 12, 4 12, 2 8 Z M5 5 L11 11" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
+ </svg>
+ </button>
+ </div>
+ <!-- (Salo 2026-05-12: the in-player progress chip was redundant
+ with the bottom Now strip, AND it covered the playing video.
+ Removed entirely; bottom-pane Now card is the single source of
+ truth for live + failed job state.) -->
+ </div>
+ <!-- Expand lightbox: full-viewport overlay shared by image + video.
+ Opens via the Expand button on the player overlay actions, or by
+ pressing F when an output is selected. Click outside the media or
+ press Esc to close. -->
+ <div class="expand-lightbox" id="expandLightbox" style="display:none"
+ onclick="if(event.target===this)closeExpandLightbox()">
+ <button class="expand-close" type="button" onclick="closeExpandLightbox()" title="Close (Esc)">
+ <svg width="20" height="20" viewBox="0 0 20 20" fill="none" aria-hidden="true">
+ <path d="M5 5 L15 15 M15 5 L5 15" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
+ </svg>
+ </button>
+ <div class="expand-stage" id="expandStage"></div>
+ <div class="expand-meta" id="expandMeta"></div>
+ </div>
+ <!-- Hidden compatibility slot. selectOutput() writes #playerName here
+ and toggles display on #playerMeta — both kept so external code
+ and tests don't break. The visible name lives in playerOverlayName. -->
+ <div class="player-meta" id="playerMeta" style="display:none">
+ <div class="name" id="playerName"></div>
+ <div class="actions-bar"></div>
+ </div>
+ <!-- Combined filter + title row. One row, three regions: title +
+ count, kind chips (All/Videos/Photos), visible/hidden segmented
+ toggle on the right. Replaces the previous two-row stack. -->
+ <div class="carousel-wrap">
+ <div class="carousel-head">
+ <h3 id="carouselTitle">Outputs</h3>
+ <!-- Kind chips, ID + onclick names preserved. -->
+ <div class="stage-outputs-filter" id="mainOutputsFilter">
+ <button type="button" id="mainOutputsFilterAll" class="active"
+ onclick="setMainOutputsFilter('all')">All</button>
+ <button type="button" id="mainOutputsFilterVideos"
+ onclick="setMainOutputsFilter('videos')">Videos</button>
+ <button type="button" id="mainOutputsFilterPhotos"
+ onclick="setMainOutputsFilter('photos')">Photos</button>
+ </div>
+ <span class="ch-spacer"></span>
+ <button type="button" class="open-folder-btn" id="openOutputsFolderBtn"
+ title="Reveal the outputs folder in Finder"
+ aria-label="Reveal the outputs folder in Finder"
+ onclick="openOutputsFolder()">
+ <svg class="ph" aria-hidden="true"><use href="#ph-folder-simple"/></svg>
+ </button>
+ <!-- Visible/Hidden segmented control was removed: the Hide
+ functionality was confusing in practice and we replaced it
+ with a one-click per-card Delete + an in-place "Open folder"
+ reveal here. The element is left out entirely so the seg-vh
+ class loses its only consumer too (CSS still defines it for
+ other segs). -->
+ </div>
+ <div class="carousel" id="carousel"></div>
+ </div>
+ </section>
-async function trainStart() {
- const btn = document.getElementById('trainStartBtn');
- const status = document.getElementById('trainStatus');
- if (!TRAIN.jobId || TRAIN.images.length < TRAIN_MIN) {
- if (status) status.textContent = `Need at least ${TRAIN_MIN} images.`;
- return;
- }
- const trig = (document.getElementById('trainTrigger').value || '').trim();
- if (!trig) {
- if (status) status.textContent = 'Trigger word required.';
- return;
- }
- const fd = new URLSearchParams();
- fd.set('train_job_id', TRAIN.jobId);
- fd.set('trigger', trig);
- fd.set('preset', TRAIN.preset);
- fd.set('image_count', String(TRAIN.images.length));
- fd.set('caption_strategy', document.getElementById('trainCaptionStrategy').value || 'trigger_simple');
- const rank = document.getElementById('trainRank').value;
- if (rank) fd.set('rank', rank);
- const stepsVal = document.getElementById('trainSteps').value;
- if (stepsVal) fd.set('steps', stepsVal);
- const lrVal = document.getElementById('trainLR').value;
- if (lrVal) fd.set('lr', lrVal);
- const resVal = document.getElementById('trainResolution').value;
- if (resVal) fd.set('resolution', resVal);
- if (btn) { btn.disabled = true; btn.textContent = 'Submitting…'; }
- try {
- const r = await fetch('/train/start', { method: 'POST', body: fd });
- const j = await r.json();
- if (!r.ok || !j.ok) {
- if (status) status.textContent = 'Failed to enqueue: ' + (j.error || r.status);
- if (btn) { btn.disabled = false; btn.textContent = 'Start training'; }
- return;
- }
- if (status) status.textContent = `Queued · job ${j.queued_id}. Watch the Now / Queue pane for progress.`;
- // Reset the form so the user can stage another dataset. The current
- // job's files stay on disk — only our local mirror is cleared.
- TRAIN.jobId = null;
- TRAIN.images = [];
- trainRenderThumbs();
- trainUpdateEstimate();
- if (btn) btn.textContent = 'Start training';
- // Refresh queue poll immediately so the new job card appears without
- // waiting for the next 1.5s tick.
- if (typeof poll === 'function') poll();
- } catch (e) {
- if (status) status.textContent = 'Enqueue failed: ' + (e.message || 'unknown');
- if (btn) { btn.disabled = false; btn.textContent = 'Start training'; }
- }
-}
+ <!-- Lightbox for stage outputs — plays a finished mp4 full-size on click.
+ Refine button references the playing clip in the composer so the
+ user can ask the agent for a variation while watching. -->
-async function trainRefreshLoraList() {
- const list = document.getElementById('trainLoraList');
- if (!list) return;
- // Keep the global picker in sync. /loras scans the same directory but
- // also rebuilds _knownUserLoras + drops stale entries from _activeLoras.
- // Cheap (one fs scan) and harmless if it races with a render. Letting
- // it run unconditionally so a freshly-trained LoRA appears in T2V's
- // picker the moment the trained list updates — no manual refresh.
- try { if (typeof refreshLoras === 'function') refreshLoras(); } catch (e) {}
- try {
- const r = await fetch('/train/list');
- const j = await r.json();
- const items = (j.loras || []);
- if (!items.length) {
- list.innerHTML = '<div class="hint" style="padding:12px 0">No trained LoRAs yet. Start your first run above.</div>';
- return;
- }
- list.innerHTML = items.map(it => {
- const ageMs = Date.now() - (Number(it.created_at) || 0) * 1000;
- const ageStr = trainFmtAge(ageMs);
- const safeTrig = (it.trigger || '').replace(/[<>&"']/g, c =>
- ({'<':'&lt;','>':'&gt;','&':'&amp;','"':'&quot;',"'":'&#39;'})[c]);
- const safePath = (it.path || '').replace(/'/g, "\\'");
- return `<div class="train-lora-row">
- <span class="tl-name" title="${it.filename}">${it.name || it.filename}
- <span class="tl-trigger"> · "${safeTrig}"</span>
- <span class="tl-size"> · ${it.size_mb} MB · ${ageStr}</span>
- </span>
- <span class="tl-actions">
- <button type="button" class="qchip" onclick="trainUseInVideo('${safePath}','${safeTrig}','t2v')">Use in T2V</button>
- <button type="button" class="qchip" onclick="trainUseInVideo('${safePath}','${safeTrig}','i2v')">Use in I2V</button>
- <button type="button" class="qchip" onclick="trainCopyTriggerCmd('${safeTrig}')">Copy trigger</button>
- <button type="button" class="qchip" onclick="trainDeleteLora('${safePath}')" title="Delete .safetensors + sidecar"><svg class="ph" aria-hidden="true"><use href="#ph-trash-simple"/></svg></button>
- </span>
- </div>`;
- }).join('');
- } catch (e) {
- list.innerHTML = '<div class="hint">Load failed: ' + (e.message || 'unknown') + '</div>';
- }
-}
+<!-- ============== CIVITAI MODAL ============== -->
+<!-- LoRA discovery + install modal. Hits /civitai/search to populate
+ the grid and /civitai/download to fetch a selected LoRA into
+ mlx_models/loras/ with a sidecar JSON capturing the metadata. -->
+<div id="civitaiModal" class="models-modal" style="display:none"
+ role="dialog" aria-modal="true" aria-labelledby="civitaiModalTitle"
+ onclick="if(event.target===this) closeCivitaiModal()">
+ <div class="models-card" style="width: min(960px, 96vw)">
+ <div class="models-head">
+ <h2 id="civitaiModalTitle">Browse CivitAI for LTX 2.3 LoRAs</h2>
+ <button class="ghost-btn" onclick="closeCivitaiModal()">Close</button>
+ </div>
+ <div class="models-hint">
+ LoRAs land in <code id="civitaiTargetDir">mlx_models/loras/</code>
+ with a sidecar JSON that carries the trigger words and recommended
+ strength. The CivitAI page link stays in the sidecar for attribution.
+ </div>
+ <!-- Inline API-key banner. CivitAI requires a token to download LoRAs
+ (even SFW ones). Three states, all rendered in the same slot by
+ renderCivitaiAuthBanner():
+ - missing: amber, has an input + Save button
+ - set: green checkmark with a "change" link that re-shows the input
+ - error: red, shown after a failed test, with re-input + retry
+ The actual key is POSTed to /settings (same endpoint the cog
+ menu uses) so there's a single source of truth on disk. -->
+ <div id="civitaiAuthBanner" class="civitai-auth" style="display:none"></div>
+ <div class="civitai-search-bar">
+ <input type="text" id="civitaiQuery" placeholder="Search by name, style, creator…"
+ oninput="if(this._t) clearTimeout(this._t); this._t = setTimeout(civitaiSearch, 350)"
+ onkeydown="if(event.key==='Enter'){ event.preventDefault(); civitaiSearch(); }">
+ <label class="toggle-pill" id="civitaiNsfwPill">
+ <input type="checkbox" id="civitaiNsfw">
+ <span class="toggle-dot"></span>
+ <span>Show NSFW</span>
+ </label>
+ </div>
+ <div class="civitai-grid" id="civitaiGrid">
+ <div class="hint">Loading…</div>
+ </div>
+ <div class="civitai-status-line" id="civitaiStatus"></div>
+ <div style="display:flex; justify-content:center; margin-top:14px">
+ <button type="button" class="ghost-btn" id="civitaiLoadMore"
+ style="display:none" onclick="civitaiLoadMore()">Load more</button>
+ </div>
+ </div>
+</div>
-function trainFmtAge(ms) {
- if (!Number.isFinite(ms) || ms < 0) return 'just now';
- const s = Math.floor(ms / 1000);
- if (s < 60) return `${s}s ago`;
- const m = Math.floor(s / 60);
- if (m < 60) return `${m}m ago`;
- const h = Math.floor(m / 60);
- if (h < 24) return `${h}h ago`;
- const d = Math.floor(h / 24);
- return `${d}d ago`;
-}
+<!-- ============== SETTINGS MODAL ============== -->
+<!-- Opened by the gear icon in the header. Lets users pick output codec
+ presets (Standard / Video production / Web) or set custom pix_fmt + crf.
+ Persisted to panel_settings.json; the helper subprocess restarts on
+ codec change so the new ffmpeg args take effect on next job. -->
+<div id="settingsModal" class="models-modal" style="display:none"
+ role="dialog" aria-modal="true" aria-labelledby="settingsModalTitle"
+ onclick="if(event.target===this) closeSettingsModal()">
+ <div class="models-card">
+ <div class="models-head">
+ <h2 id="settingsModalTitle">Settings</h2>
+ <button class="ghost-btn" onclick="closeSettingsModal()">Close</button>
+ </div>
+ <div class="models-hint">
+ Pick how rendered clips are encoded. Settings are saved to
+ <code>panel_settings.json</code> and apply to every new render.
+ Files already in the gallery are not re-encoded.
+ </div>
-function trainUseInVideo(loraPath, trigger, targetMode) {
- // Switch the panel into the requested video mode + pre-fill the LoRA
- // picker by emitting an "add" against the unified picker's state. The
- // picker's _activeLoras list is what the form serialises into the
- // hidden #lorasJson input on submit. Falls back to copying the path
- // to clipboard if the picker hooks aren't present.
- try { setMode(targetMode); } catch (e) {}
- // Pre-fill the prompt textarea with the trigger word as a starter so
- // the user sees how it's used.
- const prompt = document.getElementById('prompt');
- if (prompt && !prompt.value) {
- prompt.value = `${trigger} man, cinematic medium shot, soft natural light`;
- }
- // Use the existing picker plumbing if available. _activeLoras and
- // renderLorasList come from the unified LoRA picker module.
- if (typeof window._activeLoras !== 'undefined' && Array.isArray(window._activeLoras)) {
- const already = window._activeLoras.some(x => x.path === loraPath);
- if (!already) {
- window._activeLoras.push({ path: loraPath, strength: 1.0, name: loraPath.split('/').pop() });
- if (typeof renderLorasList === 'function') renderLorasList();
- if (typeof _syncLorasJsonField === 'function') _syncLorasJsonField();
- }
- } else {
- // Fall back: copy the path so the user can paste it into the LoRA
- // picker manually.
- if (typeof imgStudioCopyPath === 'function') imgStudioCopyPath(loraPath);
- }
-}
+ <div class="settings-section">
+ <h3>Output format</h3>
+ <div class="preset-grid" id="settingsPresets">
+ <!-- populated by openSettingsModal() from /settings -->
+ </div>
+ </div>
-function trainCopyTriggerCmd(trigger) {
- if (!trigger) return;
- const text = `${trigger} man, cinematic medium shot, soft natural light`;
- if (typeof imgStudioCopyPath === 'function') imgStudioCopyPath(text);
-}
+ <div class="settings-section">
+ <h3>Memory / speed</h3>
+ <div class="hint" style="margin-bottom:8px">
+ Controls the VAE decode path after denoising. Fast uses more unified
+ memory on medium clips; Safe streams decode to reduce peak RAM.
+ </div>
+ <div class="settings-row">
+ <label>Policy</label>
+ <select id="settingsMemoryPolicy" style="flex:1"></select>
+ </div>
+ <div class="hint" id="settingsMemoryPolicyHint" style="margin-top:6px"></div>
+ </div>
+
+ <div class="settings-section">
+ <h3>API tokens</h3>
+ <div class="hint" style="margin-bottom:8px">
+ Saved locally in <code>panel_settings.json</code>. Never sent
+ anywhere except as auth headers to civitai.com / huggingface.co.
+ Power users can override with <code>CIVITAI_API_KEY</code> /
+ <code>HF_TOKEN</code> env vars; the saved value here wins when
+ both are set.
+ </div>
+
+ <!-- CivitAI token row -->
+ <div class="token-row">
+ <div class="token-label">
+ <span>CivitAI API key</span>
+ <span class="token-status" id="civitaiKeyStatus">—</span>
+ </div>
+ <div class="token-row-input">
+ <input type="password" id="civitaiKeyInput" autocomplete="off"
+ placeholder="paste key here…"
+ oninput="onTokenInput('civitai')">
+ <button type="button" class="ghost-btn" id="civitaiKeyToggle"
+ onclick="toggleTokenVisibility('civitaiKeyInput', this)">show</button>
+ <button type="button" class="primary-btn token-savetest"
+ onclick="testToken('civitai')" title="Save the pasted key and verify it with CivitAI">save & test</button>
+ <button type="button" class="ghost-btn" id="civitaiKeyClear"
+ onclick="clearToken('civitai')" style="display:none">clear</button>
+ </div>
+ <div class="hint" id="civitaiTestResult">
+ Required for installing CivitAI LoRAs.
+ Get one at <a href="https://civitai.com/user/account" target="_blank" rel="noopener">civitai.com/user/account</a>
+ (Account → API Keys → Add).
+ </div>
+ </div>
-async function trainDeleteLora(loraPath) {
- if (!loraPath) return;
- if (!confirm('Delete this LoRA?\n\n' + loraPath)) return;
- try {
- const fd = new URLSearchParams();
- fd.set('path', loraPath);
- const r = await fetch('/train/delete', { method: 'POST', body: fd });
- const j = await r.json();
- if (!r.ok || !j.ok) {
- alert('Delete failed: ' + (j.error || r.status));
- return;
- }
- trainRefreshLoraList();
- } catch (e) {
- alert('Delete error: ' + (e.message || 'unknown'));
- }
-}
+ <!-- HF token row -->
+ <div class="token-row">
+ <div class="token-label">
+ <span>Hugging Face token</span>
+ <span class="token-status" id="hfTokenStatus">—</span>
+ </div>
+ <div class="token-row-input">
+ <input type="password" id="hfTokenInput" autocomplete="off"
+ placeholder="hf_…"
+ oninput="onTokenInput('hf')">
+ <button type="button" class="ghost-btn" id="hfTokenToggle"
+ onclick="toggleTokenVisibility('hfTokenInput', this)">show</button>
+ <button type="button" class="primary-btn token-savetest"
+ onclick="testToken('hf')" title="Save the pasted token and verify it with Hugging Face">save & test</button>
+ <button type="button" class="ghost-btn" id="hfTokenClear"
+ onclick="clearToken('hf')" style="display:none">clear</button>
+ </div>
+ <div class="hint" id="hfTestResult">
+ Required for gated LoRAs (Lightricks HDR + Control LoRAs).
+ Get one at <a href="https://huggingface.co/settings/tokens" target="_blank" rel="noopener">huggingface.co/settings/tokens</a>
+ — read access is enough.
+ </div>
+ </div>
+ </div>
-// Quality presets (Y1.013) — each one bundles the backend quality value
-// (which selects the model + sampler) with the canonical dimensions.
-// Backend still routes only on `quality == 'high'` vs anything else, so
- // 'quick', 'balanced', and 'standard' all run Q4 distilled — they differ in
-// pixel count. The richer label is preserved in the sidecar so the
-// info modal can show "Quick" / "Standard" / "High" verbatim.
-const QUALITY_PRESETS = {
- quick: { w: 640, h: 480, upscale: 'off' }, // 4:3, fastest sanity check
- balanced: { w: 1024, h: 576, upscale: 'fit_720p' }, // exact 16:9 → 1280×720
- standard: { w: 1280, h: 704, upscale: 'off' }, // LTX-wide canonical render
- // High = Q8 quality at 1024×576. Lab finding 2026-05-09: at 1024×576
- // Q8 produces "outstanding" output at ~7:48 wall vs ~11:51 at
- // 1280×704 — Q8's quality differentiator is per-token detail
- // capacity, not raw pixels. User can still pick 1280×704 explicitly
- // via the resolution chip; this preset just sets the saner default.
- high: { w: 1024, h: 576, upscale: 'off' },
-};
+ <!-- Spicy mode — gates NSFW LoRA visibility in the CivitAI browser.
+ Default OFF. Turning ON requires an explicit confirm-click pattern
+ so a casual visitor / kid can't toggle it by a stray click. The
+ server enforces the gate independently in _civitai_search, so a
+ tampered client can't bypass this. -->
+ <div class="settings-section">
+ <h3>Spicy mode <span class="hint" style="font-weight:400">(adult content)</span></h3>
+ <div class="hint" style="margin-bottom:10px">
+ When OFF, the CivitAI LoRA browser hides NSFW models entirely —
+ the "Show NSFW" toggle disappears and any NSFW result the API
+ returns is filtered out. When ON, you can choose per-search whether
+ to include NSFW results. The server enforces this gate even if the
+ client is tampered with.
+ </div>
+ <div class="spicy-row">
+ <span class="spicy-state" id="spicyStateBadge">OFF</span>
+ <button type="button" class="ghost-btn" id="spicyToggleBtn"
+ onclick="toggleSpicyMode()" style="margin-left:auto">
+ Enable Spicy mode
+ </button>
+ </div>
+ <div class="hint" id="spicyHint" style="margin-top:8px; display:none"></div>
+ </div>
-function setQuality(q) {
- // Tolerate legacy values from old sidecars: 'draft' → 'standard'.
- if (q === 'draft' || !QUALITY_PRESETS[q]) q = 'standard';
- document.getElementById('quality').value = q;
- document.querySelectorAll('#qualityGroup .pill-btn').forEach(b => b.classList.toggle('active', b.dataset.quality === q));
- // Set canonical dimensions for the preset, respecting the current
- // aspect choice. Quick is 4:3 only — landscape orientation only.
- const preset = QUALITY_PRESETS[q];
- const aspect = document.getElementById('aspect').value || 'landscape';
- const vertical = (aspect === 'vertical' && q !== 'quick');
- document.getElementById('width').value = vertical ? preset.h : preset.w;
- document.getElementById('height').value = vertical ? preset.w : preset.h;
- setUpscale(preset.upscale || 'off');
- // Hide the Aspect row when Quick is active (only 4:3 supported); show
- // it for Standard/High where 16:9 vs 9:16 is a real choice.
- const aspectRow = document.getElementById('aspectRow');
- if (aspectRow) aspectRow.style.display = (q === 'quick') ? 'none' : '';
- applyQuality();
- updateAccelAvailability();
- updateTemporalAvailability();
- updateCustomizeSummary();
- if (LAST_STATUS) updateModelsCard(LAST_STATUS);
-}
-function setAccel(a) {
- const allowed = document.getElementById('quality').value !== 'high' && currentMode !== 'extend' && currentMode !== 'keyframe';
- const v = allowed ? a : 'off';
- document.getElementById('accel').value = v;
- document.querySelectorAll('#accelGroup .pill-btn').forEach(b => b.classList.toggle('active', b.dataset.accel === v));
- updateCustomizeSummary();
- updateDerived();
-}
-function temporalModeAllowed() {
- const q = document.getElementById('quality').value;
- const mode = document.getElementById('mode').value;
- return q !== 'high' && currentMode !== 'extend' && currentMode !== 'keyframe' && (mode === 't2v' || mode === 'i2v');
-}
-function setTemporalMode(t) {
- const allowed = temporalModeAllowed();
- const v = (allowed && t === 'fps12_interp24') ? 'fps12_interp24' : 'native';
- document.getElementById('temporal_mode').value = v;
- document.querySelectorAll('#temporalGroup .pill-btn').forEach(b => b.classList.toggle('active', b.dataset.temporal === v));
- updateCustomizeSummary();
- updateDerived();
-}
-function setUpscale(u) {
- const v = ['off', 'fit_720p', 'x2'].includes(u) ? u : 'off';
- document.getElementById('upscale').value = v;
- document.querySelectorAll('#upscaleGroup .pill-btn').forEach(b => b.classList.toggle('active', b.dataset.upscale === v));
- // Show / hide the Method pill row — only relevant when an upscale is
- // actually being applied. When toggled to "off", revert method to Fast
- // so a later toggle back to fit_720p starts from the safe default.
- const methodRow = document.getElementById('upscaleMethodRow');
- if (methodRow) methodRow.style.display = (v === 'off' || !PIPERSR_UPSCALE_ENABLED) ? 'none' : '';
- if (v === 'off' || !PIPERSR_UPSCALE_ENABLED) setUpscaleMethod('lanczos');
- updateCustomizeSummary();
- updateDerived();
-}
-function setUpscaleMethod(m) {
- if (m === 'model') m = 'pipersr'; // legacy sidecars from the retired LTX Sharp path
- const v = (PIPERSR_UPSCALE_ENABLED && m === 'pipersr') ? 'pipersr' : 'lanczos';
- document.getElementById('upscale_method').value = v;
- document.querySelectorAll('#upscaleMethodGroup .pill-btn').forEach(b => b.classList.toggle('active', b.dataset.method === v));
- updateCustomizeSummary();
- updateDerived();
-}
-function updateAccelAvailability() {
- const allowed = document.getElementById('quality').value !== 'high' && currentMode !== 'extend' && currentMode !== 'keyframe';
- document.querySelectorAll('#accelGroup .pill-btn').forEach(b => {
- const disabled = !allowed && b.dataset.accel !== 'off';
- b.classList.toggle('disabled', disabled);
- });
- if (!allowed && document.getElementById('accel').value !== 'off') setAccel('off');
-}
-function updateTemporalAvailability() {
- const allowed = temporalModeAllowed();
- document.querySelectorAll('#temporalGroup .pill-btn').forEach(b => {
- const disabled = !allowed && b.dataset.temporal !== 'native';
- b.classList.toggle('disabled', disabled);
- if (b.dataset.temporal === 'fps12_interp24') {
- b.title = allowed
- ? 'Generate at 12fps, then interpolate to a normal 24fps export.'
- : 'Available for Q4 Text/Image renders. Off for High, FFLF, Extend, and external-audio I2V.';
- }
- });
- if (!allowed && document.getElementById('temporal_mode').value !== 'native') setTemporalMode('native');
-}
-function setAspect(a) {
- if (!ASPECTS[a]) return;
- document.getElementById('aspect').value = a;
- document.querySelectorAll('#aspectGroup .pill-btn').forEach(b => b.classList.toggle('active', b.dataset.aspect === a));
- applyAspect(a);
-}
+ <div class="settings-section" id="settingsCustomSection" style="display:none">
+ <h3>Custom (advanced)</h3>
+ <div class="settings-row" style="margin-bottom:10px">
+ <label>pix_fmt</label>
+ <select id="settingsPixFmt" style="flex:1">
+ <option value="yuv420p">yuv420p — web standard, broad support</option>
+ <option value="yuv422p">yuv422p — pro, more chroma than 420p</option>
+ <option value="yuv444p">yuv444p — full chroma, no subsampling</option>
+ <option value="yuv420p10le">yuv420p10le — 10-bit, HDR-ready</option>
+ <option value="yuv422p10le">yuv422p10le — 10-bit pro</option>
+ <option value="yuv444p10le">yuv444p10le — 10-bit, full chroma</option>
+ </select>
+ </div>
+ <div class="settings-row">
+ <label>CRF</label>
+ <input type="range" id="settingsCrfRange" min="0" max="30" step="1"
+ style="flex:1; width:auto" oninput="document.getElementById('settingsCrfNum').value = this.value">
+ <input type="number" id="settingsCrfNum" min="0" max="30" step="1"
+ style="width:60px"
+ oninput="document.getElementById('settingsCrfRange').value = this.value">
+ </div>
+ <div class="hint" style="margin-top:6px">
+ 0 = mathematically lossless · 18 = visually lossless ·
+ 23 = web default · 28+ = lossy
+ </div>
+ </div>
-// Compose the right-aligned line in the Customize summary. Reflects the
-// current effective state: aspect, custom-dims callout, speed setting.
-function updateCustomizeSummary() {
- const el = document.getElementById('customizeSummary');
- if (!el) return;
- const q = document.getElementById('quality').value;
- const w = parseInt(document.getElementById('width').value || 0);
- const h = parseInt(document.getElementById('height').value || 0);
- const aspect = document.getElementById('aspect').value || 'landscape';
- const accel = document.getElementById('accel').value || 'off';
- const upscale = document.getElementById('upscale').value || 'off';
- const parts = [];
- // Aspect (Quick is fixed 4:3, no choice; Standard/High show landscape/vertical).
- if (q === 'quick') parts.push('4:3 · 640×480');
- else parts.push(aspect === 'vertical' ? '9:16' : '16:9');
- // Flag custom dims if they don't match the preset.
- const preset = QUALITY_PRESETS[q] || QUALITY_PRESETS['standard'];
- const vertical = (aspect === 'vertical' && q !== 'quick');
- const expectedW = vertical ? preset.h : preset.w;
- const expectedH = vertical ? preset.w : preset.h;
- if (q !== 'quick' && (w !== expectedW || h !== expectedH)) {
- parts.push(`${w}×${h} custom`);
- }
- // Speed
- parts.push(accel === 'off' ? 'exact speed' : (accel === 'boost' ? 'boost' : 'turbo'));
- if ((document.getElementById('temporal_mode')?.value || 'native') === 'fps12_interp24') {
- parts.push('12→24fps long clip');
- }
- const method = (document.getElementById('upscale_method')?.value || 'lanczos');
- const methodTag = method === 'pipersr' || method === 'model' ? ' sharp' : '';
- if (upscale === 'fit_720p') parts.push('720p export' + methodTag);
- else if (upscale === 'x2') parts.push('2× export' + methodTag);
- el.textContent = parts.join(' · ');
-}
-function setExtendMode(m) {
- // Fast = no-CFG path, fits in 64 GB at 1280×704. Quality = upstream
- // defaults, requires headroom. Both are exposed on the form via hidden
- // inputs; this just flips the values + active pill.
- const steps = m === 'quality' ? 30 : 12;
- const cfg = m === 'quality' ? 3.0 : 1.0;
- document.getElementById('extend_steps').value = String(steps);
- document.getElementById('extend_cfg').value = String(cfg);
- document.querySelectorAll('#extendModeGroup .pill-btn').forEach(b =>
- b.classList.toggle('active', b.dataset.extendMode === m));
-}
+ <div class="settings-foot">
+ <span class="settings-status" id="settingsStatus"></span>
+ <button class="ghost-btn" onclick="closeSettingsModal()">Cancel</button>
+ <button class="primary-btn" id="settingsApplyBtn" onclick="applySettings()">Apply</button>
+ </div>
+ </div>
+</div>
-document.querySelectorAll('#modeGroup .pill-btn').forEach(b => b.onclick = () => setMode(b.dataset.mode));
-document.querySelectorAll('#qualityGroup .pill-btn').forEach(b => b.onclick = () => {
- // Disabled-but-actionable: the High pill becomes a "click to install Q8"
- // CTA when Q8 is missing. Routes to the Models modal so the user lands
- // on the download button with full context (size, current state, etc.).
- if (b.classList.contains('disabled')) {
- if (b.classList.contains('needs-install') && typeof openModelsModal === 'function') {
- openModelsModal();
- }
- return;
- }
- setQuality(b.dataset.quality);
-});
-document.querySelectorAll('#accelGroup .pill-btn').forEach(b => b.onclick = () => { if (!b.classList.contains('disabled')) setAccel(b.dataset.accel); });
-document.querySelectorAll('#temporalGroup .pill-btn').forEach(b => b.onclick = () => { if (!b.classList.contains('disabled')) setTemporalMode(b.dataset.temporal); });
-document.querySelectorAll('#upscaleGroup .pill-btn').forEach(b => b.onclick = () => { if (!b.classList.contains('disabled')) setUpscale(b.dataset.upscale); });
-document.querySelectorAll('#upscaleMethodGroup .pill-btn').forEach(b => b.onclick = () => { if (!b.classList.contains('disabled')) setUpscaleMethod(b.dataset.method); });
-document.querySelectorAll('#aspectGroup .pill-btn').forEach(b => b.onclick = () => setAspect(b.dataset.aspect));
-document.querySelectorAll('#extendModeGroup .pill-btn').forEach(b => b.onclick = () => setExtendMode(b.dataset.extendMode));
+<!-- ============== TIER MODAL ============== -->
+<!-- Opened by the "tier" pill in the header. Renders the detected
+ hardware tier + what it allows. Helps users understand WHY some
+ options are disabled instead of just hitting a wall mid-flow. -->
+<div id="tierModal" class="models-modal" style="display:none"
+ role="dialog" aria-modal="true" aria-labelledby="tierModalTitle"
+ onclick="if(event.target===this) closeTierModal()">
+ <div class="models-card">
+ <div class="models-head">
+ <h2 id="tierModalTitle">Hardware tier</h2>
+ <button class="ghost-btn" onclick="closeTierModal()">Close</button>
+ </div>
+ <div class="models-hint" id="tierModalBlurb"></div>
+ <ul class="models-list" id="tierCapsList"></ul>
+ <div class="models-foot">
+ Set <code>LTX_TIER_OVERRIDE=base|standard|high|pro</code> in the env to
+ force a tier (useful for testing what other users see).
+ </div>
+ </div>
+</div>
-// Prompt enhancement via Gemma — wraps the upstream CLI's `enhance`
-// subcommand. Cold start ~12-15s (Gemma load), warm ~5s. Blocks the UI
-// during the request (just the button — rest of the form stays usable).
-async function enhancePrompt() {
- const ta = document.getElementById('prompt');
- const original = ta.value.trim();
- if (!original) { alert('Type a prompt before enhancing it.'); return; }
- const mode = (currentMode === 'i2v' || currentMode === 'keyframe' || currentMode === 'extend') ? 'i2v' : 't2v';
- const btn = document.getElementById('enhanceBtn');
- // Snapshot the FULL inner markup, not just text — the button carries
- // an inline ph-sparkle-fill SVG that textContent would strip.
- const originalLabel = btn.innerHTML;
- btn.disabled = true;
- btn.innerHTML = '<svg class="ph" aria-hidden="true" style="margin-right:6px;vertical-align:-2px"><use href="#ph-sparkle-fill"/></svg>Loading Gemma… (~15s on cold start)';
- let res;
- try {
- const fd = new URLSearchParams({ prompt: original, mode });
- const r = await fetch('/prompt/enhance', { method: 'POST', body: fd });
- res = await r.json();
- } catch (e) {
- alert('Enhance request failed: ' + (e.message || e));
- btn.disabled = false; btn.innerHTML = originalLabel;
- return;
- }
- btn.disabled = false; btn.innerHTML = originalLabel;
- if (res.error) { alert('Enhance failed: ' + res.error); return; }
- // Show diff in a confirm so the user can decide whether to accept.
- const accept = confirm(
- `Original:\n${res.original}\n\nEnhanced:\n${res.enhanced}\n\nReplace your prompt with the enhanced version?`
- );
- if (accept) {
- ta.value = res.enhanced;
- ta.dispatchEvent(new Event('input', { bubbles: true }));
- }
-}
+<!-- ============== MODELS MODAL ============== -->
+<!-- Opened by the "models" pill in the header. Shows per-repo download
+ status from /models, with a Download button per row. Active downloads
+ stream into the existing log at the bottom of the page. -->
+<div id="modelsModal" class="models-modal" style="display:none"
+ role="dialog" aria-modal="true" aria-labelledby="modelsModalTitle"
+ onclick="if(event.target===this) closeModelsModal()">
+ <div class="models-card">
+ <div class="models-head">
+ <h2 id="modelsModalTitle">Models</h2>
+ <button class="ghost-btn" onclick="closeModelsModal()">Close</button>
+ </div>
+ <div class="models-hint" id="modelsHint">Loading…</div>
+ <ul class="models-list" id="modelsList"></ul>
+ <div class="models-foot" id="modelsFoot"></div>
+ </div>
+</div>
-// Extend duration: user types seconds, we convert to latent frames behind
-// the scenes. Each latent = 8 video frames; at 24 fps that's 0.333 s.
-// Round-up so the user gets at least the seconds they asked for.
-// seconds → latents: ceil(seconds * 24 / 8)
-// latents → actual seconds: latents * 8 / 24
-// Hint line shows both numbers so the conversion isn't a black box.
-function syncExtendDuration() {
- const secInput = document.getElementById('extend_seconds');
- const hidden = document.getElementById('extend_frames');
- const hint = document.getElementById('extendDurationHint');
- if (!secInput || !hidden || !hint) return;
- const seconds = parseFloat(secInput.value) || 0;
- const latents = Math.max(1, Math.ceil(seconds * 24 / 8));
- const actualSec = (latents * 8 / 24);
- hidden.value = String(latents);
- hint.textContent = `≈ ${actualSec.toFixed(2)} s of new content (${latents} latent frames × 8 video frames at 24 fps)`;
-}
-document.getElementById('extend_seconds').addEventListener('input', syncExtendDuration);
-syncExtendDuration(); // initialize on load
-document.getElementById('i2vMode').addEventListener('change', () => {
- document.getElementById('audioSection').classList.toggle('show', document.getElementById('i2vMode').value === 'i2v_clean_audio');
- if (currentMode === 'i2v') document.getElementById('mode').value = document.getElementById('i2vMode').value;
- updateTemporalAvailability();
- updateCustomizeSummary();
- updateDerived();
-});
+<!-- (Version modal removed in the magic-button rewrite. Pill itself is the
+ full UI now: click while behind → confirm + git pull; click while
+ current → live re-check. See versionPillClick() in the JS section.) -->
-function applyAspect(key) {
- if (!ASPECTS[key]) return;
- document.getElementById('aspect').value = key;
- // Aspect controls dimensions only when the active preset has a choice
- // (Standard / High at 1280×704 vs 704×1280). Quick is fixed 4:3 and
- // ignores the aspect picker (the row is hidden in that state, so this
- // path normally won't fire — defensive in case of programmatic calls).
- const q = document.getElementById('quality').value;
- if (q === 'quick') return;
- const preset = QUALITY_PRESETS[q] || QUALITY_PRESETS['standard'];
- const vertical = (key === 'vertical');
- document.getElementById('width').value = vertical ? preset.h : preset.w;
- document.getElementById('height').value = vertical ? preset.w : preset.h;
- updateCustomizeSummary();
- updateDerived();
-}
+<!-- ============== OUTPUT INFO MODAL ============== -->
+<!-- Opened by the ⓘ button on each gallery card. Shows everything we
+ wrote into the .mp4.json sidecar at render time: prompt, seed,
+ mode/quality, frames + dimensions, LoRAs used (with name + strength),
+ elapsed time, queue id, model. Plus copy-buttons for prompt + seed
+ so users can easily re-use them. -->
+<div id="outputInfoModal" class="models-modal" style="display:none"
+ role="dialog" aria-modal="true" aria-labelledby="outputInfoTitle"
+ onclick="if(event.target===this) closeOutputInfoModal()">
+ <div class="models-card" style="width: min(720px, 96vw)">
+ <div class="models-head">
+ <h2 id="outputInfoTitle">Generation info</h2>
+ <button class="ghost-btn" onclick="closeOutputInfoModal()">Close</button>
+ </div>
+ <div id="outputInfoBody" class="output-info-body">
+ <div class="hint">Loading…</div>
+ </div>
+ </div>
+</div>
+
+<!-- ============== BUG REPORT MODAL ============== -->
+<!-- Opened by the neon bug button in the header pill row. Pre-fills
+ environment info + log tail server-side via /panel/bug-context, then
+ opens a pre-filled GitHub issue when the user submits. NO server-side
+ issue creation — the client builds the URL, opens it in a new tab,
+ and we're done. Optional crash-report zip lives in /tmp for the user
+ to drag onto the issue. -->
+<div id="bugModal" class="models-modal" style="display:none"
+ role="dialog" aria-modal="true" aria-labelledby="bugModalTitle"
+ onclick="if(event.target===this) closeBugModal()">
+ <div class="models-card" style="width: min(720px, 96vw)">
+ <div class="models-head">
+ <h2 id="bugModalTitle">Report a bug</h2>
+ <button class="ghost-btn" onclick="closeBugModal()">Close</button>
+ </div>
+ <div class="models-hint">
+ Opens a pre-filled GitHub issue in a new tab. Environment info, version,
+ and the last 50 log lines are filled in for you.
+ </div>
+ <div id="bugModalBody" style="padding: 12px 0; display:flex; flex-direction:column; gap:10px">
+ <label style="display:flex; flex-direction:column; gap:4px; font-size:12px; color:var(--muted)">
+ Title
+ <input id="bugTitle" type="text" value="[bug] "
+ style="padding:6px 9px; font-size:13px; background:rgba(140,160,220,0.04); border:1px solid var(--ph-border-soft); border-radius:6px; color:var(--text); font-family:inherit">
+ </label>
+ <label style="display:flex; flex-direction:column; gap:4px; font-size:12px; color:var(--muted)">
+ Description
+ <textarea id="bugBody" rows="14"
+ style="padding:8px 10px; font-size:12px; background:rgba(140,160,220,0.04); border:1px solid var(--ph-border-soft); border-radius:6px; color:var(--text); font-family:ui-monospace,SFMono-Regular,Menlo,monospace; line-height:1.45; resize:vertical">Loading environment…</textarea>
+ </label>
+ <label id="bugCrashRow" style="display:none; align-items:center; gap:8px; font-size:12px; color:var(--muted)">
+ <input id="bugCrashCheck" type="checkbox" checked>
+ <span id="bugCrashLabel">Include latest crash reports (zips up to 5 .ips files)</span>
+ </label>
+ <div id="bugSubmitRow" style="display:flex; gap:8px; justify-content:flex-end; align-items:center">
+ <span id="bugStatus" style="flex:1; font-size:12px; color:var(--muted)"></span>
+ <button class="ghost-btn" onclick="closeBugModal()">Cancel</button>
+ <button id="bugSubmitBtn" class="primary-btn" onclick="submitBugReport()">Open GitHub issue</button>
+ </div>
+ </div>
+ </div>
+</div>
+
+<!-- ============== BOTTOM TABBED PANE ============== -->
+<aside class="bottom-pane" id="bottomPane">
+ <!-- REDESIGN — Y2.001 bottom-pane. Tighter tab strip with leading
+ activity dot, denser Now card matching the composer-card visual
+ language, refined badges. All IDs preserved so poll() and the
+ click handlers downstream keep working. -->
+ <nav class="tabs">
+ <span class="bp-live-dot" id="bpLiveDot" title="Idle"></span>
+ <button data-tab="now" class="active">Now</button>
+ <button data-tab="queue">Queue <span class="badge" id="queueBadge" style="display:none">0</span></button>
+ <button data-tab="recent">Recent</button>
+ <button data-tab="logs">Logs</button>
+ <span class="spacer"></span>
+ <a class="model-credit" id="modelTag" href="https://github.com/dgrauet/ltx-2-mlx" target="_blank" rel="noopener" title="MLX port by @dgrauet"></a>
+ <!-- (Collapse-this-panel button removed 2026-05-12 — Salo flagged
+ it hid important data (active job progress, queue) and the
+ "down arrow that goes up" affordance read as confusing. The
+ bottom pane is always visible at its natural height now.) -->
+ </nav>
+ <div class="bottom-body">
+ <div class="tab-content show" id="tab-now">
+ <div class="now-card idle" id="nowCard">
+ <div class="ttl">Idle</div>
+ <div class="progress-bar"><div class="fill" id="progressFill" style="width:0%"></div></div>
+ <div class="meta" id="nowDetail">No job running</div>
+ <!-- Action row populated on the failed state with Retry + Close.
+ Lives outside .ttl so poll()'s innerHTML rewrites don't
+ clobber the buttons mid-click. Hidden when empty. -->
+ <div class="now-card-actions" id="nowCardActions"></div>
+ </div>
+ </div>
+ <div class="tab-content" id="tab-queue">
+ <ul class="row-list" id="queueList"></ul>
+ </div>
+ <div class="tab-content" id="tab-recent">
+ <!-- Type filter — image jobs and video jobs share this list now
+ that mode='image' goes through the same worker. -->
+ <div class="row-list-filter">
+ <button id="recentFilterAll" class="active" onclick="setRecentFilter('all')">All</button>
+ <button id="recentFilterVideos" onclick="setRecentFilter('videos')">Videos</button>
+ <button id="recentFilterPhotos" onclick="setRecentFilter('photos')">Photos</button>
+ </div>
+ <ul class="row-list" id="historyList"></ul>
+ </div>
+ <div class="tab-content" id="tab-logs">
+ <pre class="log" id="log">No log yet.</pre>
+ </div>
+ </div>
+</aside>
+
+<!-- ============== HF MODEL BROWSER MODAL ============== -->
+<!-- Search + install MLX-format chat models from Hugging Face. Hits
+ huggingface.co/api/models with library=mlx + pipeline_tag=text-generation
+ filters. Click Install → backend spawns `hf download`, status streams
+ in the bottom strip until done. Newly-installed models appear in the
+ local-engine model picker on next refresh. -->
+<!-- ============== BATCH MODAL ============== -->
+<div class="modal-bg" id="batchModal" onclick="if(event.target===this)closeBatch()">
+ <div class="modal">
+ <h3>Batch paste — split prompts with <code>---</code> on its own line</h3>
+ <textarea class="batch" id="batchPrompts" placeholder="First prompt here.
-// applyQuality is kept as a tiny shim — old call sites (mode switching,
-// etc.) call it expecting "set steps for the active quality." The
-// dimensions are now owned by setQuality / applyAspect.
-function applyQuality() {
- const q = document.getElementById('quality').value;
- if (q === 'high') {
- document.getElementById('steps').value = 18;
- } else {
- document.getElementById('steps').value = 8; // quick + balanced + standard
- }
- updateCustomizeSummary();
- updateDerived();
-}
+---
-function durationToFrames(s) {
- const k = Math.max(0, Math.round(s * FPS / 8));
- return k * 8 + 1;
-}
-function framesToDuration(f) { return ((f - 1) / FPS).toFixed(2); }
+Second prompt.
-// LTX 2.3 requires frame counts in the form 1 + 8k (one keyframe + N
-// VAE-temporal blocks of 8 frames each). Typing "100" or "240" wastes
-// compute on partially-filled trailing latents — the pipeline rounds
-// up internally but charges for the empty slots. Snap on blur to the
-// nearest valid value below + 1 (so we never silently render *more*
-// than the user asked for, only less or equal).
-function snapFramesTo8kPlus1() {
- const el = document.getElementById('frames');
- if (!el) return;
- const v = parseInt(el.value) || 0;
- if (v < 1) { el.value = 9; return; }
- // Nearest 8k+1: round (v-1)/8 to nearest int, multiply back, +1.
- const k = Math.max(1, Math.round((v - 1) / 8));
- const snapped = k * 8 + 1;
- if (snapped !== v) {
- el.value = snapped;
- // Reflect the change in duration too, since they're bound.
- document.getElementById('duration').value = framesToDuration(snapped);
- }
-}
+---
-function updateDerived() {
- const mode = document.getElementById('mode').value;
- const w = parseInt(document.getElementById('width').value || 0);
- const h = parseInt(document.getElementById('height').value || 0);
- const f = parseInt(document.getElementById('frames').value || 0);
- const dur = framesToDuration(f);
+Third prompt."></textarea>
+ <div class="hint" style="margin-top:6px">Each chunk between <code>---</code> lines becomes a queued job using the current form settings. Auto-open is forced off for batches.</div>
+ <div class="modal-actions">
+ <button class="small" onclick="closeBatch()">Cancel</button>
+ <button class="small primary" style="padding:6px 14px" onclick="queueBatch().then(closeBatch)">Queue all</button>
+ </div>
+ </div>
+</div>
- const upscale = document.getElementById('upscale')?.value || 'off';
- let finalRes = `<strong>${w}×${h}</strong>`;
- if (upscale === 'fit_720p') {
- const tw = w >= h ? 1280 : 720;
- const th = w >= h ? 720 : 1280;
- finalRes = `${w}×${h} → <strong>${tw}×${th}</strong> fit`;
- } else if (upscale === 'x2') {
- finalRes = `${w}×${h} → <strong>${w * 2}×${h * 2}</strong>`;
- } else {
- let pw = w, ph = h;
- if (w === 704 && h % 16 === 0) pw = 720;
- if (h === 704 && w % 16 === 0) ph = 720;
- const padded = (pw !== w || ph !== h) && mode === 'i2v_clean_audio';
- finalRes = padded ? `${w}×${h} → <strong>${pw}×${ph}</strong>` : `<strong>${w}×${h}</strong>`;
- }
- const accel = document.getElementById('accel')?.value || 'off';
- const accelText = accel === 'off' ? '' : ` · ${accel === 'turbo' ? 'Turbo' : 'Boost'}`;
- const temporal = document.getElementById('temporal_mode')?.value || 'native';
- let temporalText = '';
- if (temporal === 'fps12_interp24') {
- const intervalSec = Math.max(0, (f - 1) / FPS);
- const sourceFrames = Math.max(1, Math.round(intervalSec * 12 / 8)) * 8 + 1;
- temporalText = ` · LTX ${sourceFrames}f @ 12fps → ${FPS}fps`;
- }
+<script>
+const BOOT = __BOOTSTRAP__;
+const ASPECTS = BOOT.aspects;
+const FPS = BOOT.fps;
+const MODEL_UPSCALE_ENABLED = !!BOOT.model_upscale_enabled;
+const PIPERSR_UPSCALE_ENABLED = !!BOOT.pipersr_upscale_enabled;
- document.getElementById('derived').innerHTML = `Duration <strong>${dur}s</strong> @ ${FPS}fps${temporalText} · ${finalRes} · Steps ${document.getElementById('steps').value}${accelText}`;
+// Apply tier-aware time estimates to the Quality pill subtitles. The HTML
+// ships with the Comfortable-tier (M4 Studio 64 GB) numbers as defaults;
+// users on Compact / Roomy / Studio tiers see realistic estimates instead
+// of the optimistic baseline. Runs once on boot, plus when the tier modal
+// reports new info (rare — tier is fixed for a given Mac).
+function applyTierTimes() {
+ const qt = (BOOT.quality_times || {});
+ document.querySelectorAll('#qualityGroup .pill-quality').forEach(btn => {
+ const key = btn.dataset.quality;
+ const time = qt[key];
+ const spec = btn.querySelector('.ql-spec');
+ if (!spec) return;
+ const dimsMatch = spec.textContent.match(/^([0-9]+×[0-9]+(\s+→\s+[0-9p]+)?)/);
+ const dims = dimsMatch ? dimsMatch[1] : '';
+ if (time && dims) {
+ spec.textContent = `${dims} · ${time}`;
+ } else if (time) {
+ spec.textContent = time;
+ }
+ });
+}
- // Compact derived line in the sticky action footer — same info, tighter
- // typography. Lets the user see what they're about to render WITHOUT
- // scrolling back to the customize disclosure. Mirrors the Customize
- // summary style (just dimensions + duration; full details stay in the
- // expanded Customize body).
- const derivedFooter = document.getElementById('derivedFooter');
- if (derivedFooter) {
- derivedFooter.innerHTML = `<strong>${dur}s</strong> · ${finalRes}${temporalText}${accelText}`;
- }
- // Also update the Quality strip's right-side meta line (e.g. "5s · 1024×576")
- // so the Quality picker block reads as a self-contained summary.
- const qualityMeta = document.getElementById('qualityMeta');
- if (qualityMeta) {
- const qBare = `${w}×${h}`;
- qualityMeta.textContent = `${dur}s · ${qBare}`;
- }
+let filterMode = 'visible';
+let activePath = null;
+let currentOutputs = [];
+let currentMode = 't2v';
- const warns = [];
- if (w % 32 !== 0) warns.push(`Width ${w} isn't a multiple of 32 (closest ${Math.round(w/32)*32})`);
- if (h % 32 !== 0) warns.push(`Height ${h} isn't a multiple of 32 (closest ${Math.round(h/32)*32})`);
- if (f > 1 && (f - 1) % 8 !== 0) {
- const closest = Math.max(1, Math.round((f - 1) / 8) * 8 + 1);
- warns.push(`Frames work best as 8k+1 (closest ${closest})`);
+// Main right-pane gallery kind filter (All / Videos / Photos). Independent
+// of `filterMode` (which is visible/hidden) and independent of
+// `window.outputsFilter` (which is the agent-stage Session outputs filter
+// from commit ef7f114). The localStorage key is intentionally different:
+// the user can have "Photos" pinned on the main pane while Sessions sits
+// on "All". Default is 'all'; setMode('image') auto-flips to 'photos',
+// the video modes auto-flip to 'videos'. Manual user clicks always win.
+let mainOutputsFilter = 'all';
+try {
+ const stored = localStorage.getItem('phos_main_outputs_filter');
+ if (stored === 'all' || stored === 'videos' || stored === 'photos') {
+ mainOutputsFilter = stored;
}
- if (temporal === 'fps12_interp24') {
- warns.push('12→24fps is experimental; check dialogue lip-sync and fast motion');
+} catch (e) {}
+// Photo detection that matches commit af5c184's isPhotoOutput on the
+// agent-stage pane: explicit kind > params.mode > filename suffix. The
+// server now stamps a `kind` field, but the suffix fallback covers
+// outputs whose sidecar got lost (older entries) and any future caller
+// that forgets to set kind.
+function isPhotoOutputMain(o) {
+ if (!o) return false;
+ if (o.kind === 'image') return true;
+ if (o.kind === 'video') return false;
+ const path = (o.path || o.name || '').toLowerCase();
+ if (/\.(png|jpg|jpeg|webp)$/.test(path)) return true;
+ if (/\.mp4$/.test(path)) return false;
+ return false;
+}
+// Apply the main filter on top of currentOutputs. Returns the filtered
+// array; callers also use this for the count badge so the filter and
+// the rendered cells agree.
+function filteredMainOutputs() {
+ if (mainOutputsFilter === 'all') return currentOutputs;
+ if (mainOutputsFilter === 'photos') return currentOutputs.filter(isPhotoOutputMain);
+ return currentOutputs.filter(o => !isPhotoOutputMain(o));
+}
+function _updateMainFilterChips() {
+ const a = document.getElementById('mainOutputsFilterAll');
+ const v = document.getElementById('mainOutputsFilterVideos');
+ const p = document.getElementById('mainOutputsFilterPhotos');
+ if (a) a.classList.toggle('active', mainOutputsFilter === 'all');
+ if (v) v.classList.toggle('active', mainOutputsFilter === 'videos');
+ if (p) p.classList.toggle('active', mainOutputsFilter === 'photos');
+}
+function setMainOutputsFilter(mode) {
+ if (mode !== 'all' && mode !== 'videos' && mode !== 'photos') mode = 'all';
+ mainOutputsFilter = mode;
+ try { localStorage.setItem('phos_main_outputs_filter', mode); } catch (e) {}
+ _updateMainFilterChips();
+ // If the active selection was filtered out, switch to the first match.
+ const visible = filteredMainOutputs();
+ if (visible.length && !visible.some(o => o.path === activePath)) {
+ selectOutput(visible[0].path);
+ }
+ renderCarousel();
+ // Reset scroll position on filter change so the user lands at the
+ // top of the newly-filtered list, not mid-gallery from the previous
+ // selection's position.
+ const carEl = document.getElementById('carousel');
+ if (carEl) carEl.scrollTop = 0;
+ // Count badge mirrors the active filter (e.g. "Outputs · 23 photos").
+ const titleEl = document.getElementById('carouselTitle');
+ if (titleEl && filterMode !== 'hidden') {
+ const label = mode === 'all' ? '' : ` ${mode}`;
+ titleEl.textContent = `Outputs · ${visible.length}${label}`;
}
- const banner = document.getElementById('warnBanner');
- if (warns.length) { banner.innerHTML = '<svg class="ph" aria-hidden="true" style="margin-right:6px;vertical-align:-2px"><use href="#ph-warning-fill"/></svg>' + warns.join(' · '); banner.classList.add('show'); }
- else banner.classList.remove('show');
-
- // Mode-aware visibility
- const inI2V = mode === 'i2v' || mode === 'i2v_clean_audio';
- const inImageFlow = inI2V || currentMode === 'keyframe';
- document.getElementById('imageSection').classList.toggle('show', inI2V && currentMode !== 'keyframe');
- document.getElementById('extendSection').classList.toggle('show', currentMode === 'extend');
- document.getElementById('keyframeSection').classList.toggle('show', currentMode === 'keyframe');
- document.getElementById('sizingSection').classList.toggle('show', currentMode !== 'extend');
- // quickMetricsRow (Duration / Frames / Seed) doesn't apply to Extend
- // (extend_seconds drives the new content; the source video provides
- // the rest). Hide it in extend, show otherwise.
- const qmr = document.getElementById('quickMetricsRow');
- if (qmr) qmr.classList.toggle('show', currentMode !== 'extend');
- document.getElementById('audioSection').classList.toggle('show', mode === 'i2v_clean_audio');
- // I2V audio source picker (Advanced) — only relevant in I2V flow.
- // In T2V/Extend/FFLF the model generates audio jointly; there's nothing
- // to swap out, so the dropdown is just noise.
- const i2vAudioSec = document.getElementById('i2vAudioModeSection');
- if (i2vAudioSec) i2vAudioSec.classList.toggle('show', inI2V);
- // In image flows the aspect picker is the only sizing control. Width/height
- // auto-derive from aspect+quality so the source image drives the framing
- // and we don't accidentally cover-crop a 16:9 photo into 9:16.
- const dimsRow = document.getElementById('dimsRow');
- if (dimsRow) dimsRow.style.display = inImageFlow ? 'none' : '';
-
- // Image previews are now part of the picker component itself — the
- // preview <img> + clear button live inside .picker-drop and are toggled
- // by pickerSetImage(). No per-mode preview management here anymore;
- // the old imagePreview / startImagePreview / endImagePreview elements
- // are gone.
}
-
-['width','height','frames','duration'].forEach(id => {
- const el = document.getElementById(id);
- if (id === 'duration') {
- el.addEventListener('input', e => { document.getElementById('frames').value = durationToFrames(parseFloat(e.target.value) || 0); updateDerived(); });
- } else if (id === 'frames') {
- el.addEventListener('input', e => { document.getElementById('duration').value = framesToDuration(parseInt(e.target.value) || 0); updateDerived(); });
- el.addEventListener('blur', () => { snapFramesTo8kPlus1(); updateDerived(); });
- } else {
- // width / height: also refresh the Customize summary so "custom" flags
- // appear/disappear as the user types away from the preset values.
- el.addEventListener('input', () => { updateCustomizeSummary(); updateDerived(); });
+// Auto-set helper called from setMode(). DOES NOT persist (writing to
+// localStorage would override the user's manual pick the next time they
+// switch modes), but DOES bump the active chip + re-render so the
+// gallery snaps to the new default. The user can override after, and
+// THAT click persists via setMainOutputsFilter().
+function _autoMainOutputsFilterForMode(mode) {
+ // Auto-set NEVER lands on 'all' — that's user-only, per spec.
+ let target = null;
+ if (mode === 'image') target = 'photos';
+ else if (mode === 't2v' || mode === 'i2v' || mode === 'keyframe' || mode === 'extend') target = 'videos';
+ if (!target || target === mainOutputsFilter) return;
+ mainOutputsFilter = target;
+ // No localStorage write — see comment above.
+ _updateMainFilterChips();
+ if (typeof renderCarousel === 'function') renderCarousel();
+ const titleEl = document.getElementById('carouselTitle');
+ if (titleEl && filterMode !== 'hidden') {
+ const visible = filteredMainOutputs();
+ titleEl.textContent = `Outputs · ${visible.length} ${target}`;
+ }
+ // Swap the player to a matching entry if the current active is now
+ // off-filter (e.g. mode=image but the viewer is showing a video).
+ const visible = filteredMainOutputs();
+ if (visible.length && !visible.some(o => o.path === activePath)) {
+ selectOutput(visible[0].path);
}
-});
-// Picker hidden inputs no longer take user input — their value changes
-// via pickerSetImage(), which already calls updateDerived(). No per-input
-// listeners needed.
-
-// Auto-snap the aspect picker based on an image's actual dimensions.
-// Avoids the 16:9-source-cropped-to-9:16-strip footgun.
-function snapAspectToImage(path) {
- const probe = new Image();
- probe.onload = () => {
- const r = probe.naturalWidth / probe.naturalHeight;
- const target = r >= 1 ? 'landscape' : 'vertical';
- if (document.getElementById('aspect').value !== target) setAspect(target);
- };
- probe.src = '/image?path=' + encodeURIComponent(path);
}
-// uploadImage() / uploadKeyframe() were replaced by the unified picker
-// component (pickerUploadFile + refreshUploadsStrip). The /upload endpoint
-// still drives the actual transfer; the only change is which JS calls it.
-
-// ====== Image picker component ======
-// One implementation, three call sites: I2V image, FFLF start_image,
-// FFLF end_image. Each picker carries a `key` (the hidden field's name);
-// every DOM element it owns is suffixed with `_<key>` so we can wire
-// listeners by lookup instead of a per-instance closure.
-const PICKERS = ['image', 'start_image', 'end_image'];
+// Model tag in the bottom-pane nav links to dgrauet's repo. Strip an
+// absolute filesystem path back to the HF repo id form for display
+// (the panel sets LTX_MODEL to a local path in Pinokio installs).
+(function () {
+ const m = String(BOOT.model || '');
+ let label = m;
+ const idx = m.indexOf('mlx_models/');
+ if (idx >= 0) label = m.slice(idx + 'mlx_models/'.length);
+ if (label.startsWith('/')) label = label.split('/').slice(-2).join('/');
+ document.getElementById('modelTag').textContent = label;
+})();
+// `audio` is still a free-text input (advanced section); `image` is now a
+// picker — leave the picker empty by default and let the user pick or
+// drop. Pre-filling examples/reference.png surprised users into rendering
+// the demo image when they meant to leave it blank.
+document.getElementById('audio').value = BOOT.default_audio;
-function pickerEls(key) {
- return {
- drop: document.getElementById(`picker_drop_${key}`),
- file: document.getElementById(`picker_file_${key}`),
- hidden: document.getElementById(key),
- preview: document.getElementById(`picker_preview_${key}`),
- clear: document.getElementById(`picker_clear_${key}`),
- empty: document.querySelector(`#picker_drop_${key} .picker-empty`),
- recentWrap: document.getElementById(`picker_recent_${key}_wrap`),
- recentStrip: document.getElementById(`picker_recent_${key}`),
- };
+// ====== Pill-button group helpers ======
+// Avoid (negative prompt) toggle — keeps the textarea collapsed by
+// default so the prompt-and-go flow stays tight. The button label flips
+// to "Avoid −" when open so the affordance is clear. Auto-opens once
+// the user types into it (so it stays visible) — shouldn't auto-close
+// from typing-then-deleting because that would yank the field out from
+// under their next keystroke.
+function toggleAvoidRow(forceOpen) {
+ const row = document.getElementById('avoidRow');
+ const btn = document.getElementById('avoidToggleBtn');
+ const lbl = document.getElementById('avoidToggleLabel');
+ const ta = document.getElementById('negative_prompt');
+ if (!row) return;
+ const wantOpen = (forceOpen === true) ? true : !row.classList.contains('show');
+ row.classList.toggle('show', wantOpen);
+ if (btn) btn.classList.toggle('active', wantOpen);
+ if (lbl) lbl.textContent = wantOpen ? 'Avoid −' : 'Avoid +';
+ if (wantOpen && ta) {
+ try { ta.focus(); } catch (e) {}
+ }
+}
+// Auto-open the Avoid row if it has content (e.g. loaded from a sidecar
+// via loadParams). Run once at boot AND after loadParams sets values.
+function syncAvoidRowFromValue() {
+ const ta = document.getElementById('negative_prompt');
+ if (!ta) return;
+ if ((ta.value || '').trim() !== '') {
+ const row = document.getElementById('avoidRow');
+ if (row && !row.classList.contains('show')) toggleAvoidRow(true);
+ }
}
-function pickerSetImage(key, path, opts = {}) {
- const els = pickerEls(key);
- if (!els.hidden) return;
- els.hidden.value = path;
- if (path) {
- els.preview.src = `/image?path=${encodeURIComponent(path)}`;
- els.preview.style.display = 'block';
- els.empty.style.display = 'none';
- els.clear.style.display = 'flex';
- els.drop.classList.add('has-image');
- // Highlight the matching thumbnail in the recent strip if visible.
- if (els.recentStrip) {
- els.recentStrip.querySelectorAll('img').forEach(img => {
- img.classList.toggle('selected', img.dataset.path === path);
- });
- }
- // FFLF anchors framing on the start frame; I2V anchors on its single
- // image. End frame doesn't drive aspect (would override the start frame).
- if (key !== 'end_image' && opts.snapAspect !== false) {
- snapAspectToImage(path);
- }
- } else {
- els.preview.removeAttribute('src');
- els.preview.style.display = 'none';
- els.empty.style.display = '';
- els.clear.style.display = 'none';
- els.drop.classList.remove('has-image');
- if (els.recentStrip) {
- els.recentStrip.querySelectorAll('img').forEach(img => img.classList.remove('selected'));
+function setMode(mode) {
+ currentMode = mode;
+ // The Studio pill swaps the form-pane in place: hide the video form
+ // (genForm) and show the inline #studioSection. Right rail (queue,
+ // current, history) stays visible regardless of mode. The mode dropdown
+ // value is set to a non-form value when in studio so an accidental
+ // form submit doesn't trigger a video render with stale fields.
+ const studio = document.getElementById('studioSection');
+ const train = document.getElementById('trainSection');
+ const genForm = document.getElementById('genForm');
+ // Train mode mirrors Studio: hide #genForm, show #trainSection. Same
+ // chrome conventions, separate form (so an Enter inside the trigger
+ // input doesn't submit a video render).
+ if (mode === 'train') {
+ if (studio) studio.classList.remove('show');
+ if (train) train.classList.add('show');
+ if (genForm) genForm.style.display = 'none';
+ document.querySelectorAll('#modeGroup .pill-btn').forEach(b =>
+ b.classList.toggle('active', b.dataset.mode === 'train'));
+ // Lazy initialization on first entry — wires drop zone, generates
+ // a starter trigger, refreshes the trained-LoRAs list, computes
+ // an initial wall-time estimate.
+ if (typeof trainInit === 'function') trainInit();
+ return;
+ }
+ if (mode === 'image') {
+ if (studio) studio.classList.add('show');
+ if (genForm) genForm.style.display = 'none';
+ document.querySelectorAll('#modeGroup .pill-btn').forEach(b =>
+ b.classList.toggle('active', b.dataset.mode === 'image'));
+ // Portal the unified LoRA picker into the Studio composer slot, so
+ // the SAME UI (one chip strip, one library, one + LoRA button) is
+ // visible under Image Studio. Re-renders with the engine-aware
+ // filter automatically (renderLorasList reads _currentLoraModeFilter
+ // every time, no separate config to thread). The hidden #lorasJson
+ // input STAYS inside #genForm — imgStudioGenerate reads
+ // _activeLoras directly when posting, so the studio submit doesn't
+ // depend on the hidden field's location.
+ _portalLoraPicker('studio');
+ // Re-render the unified LoRA picker so its mode-aware filter
+ // (which reads `currentMode` we just set above) actually applies.
+ // Without this the picker stays on whatever filter it had under
+ // the previous mode — the symptom the user hit: clicked Studio,
+ // banner still read "LTX-Video LoRAs (active video mode)" until
+ // they jiggled the engine dropdown to force a re-render.
+ if (typeof renderLorasList === 'function') renderLorasList();
+ // Wire ref drop-zones once + refresh library on every entry
+ if (typeof imgStudioWireRefSlots === 'function') imgStudioWireRefSlots();
+ if (typeof imgStudioRefreshLibrary === 'function') imgStudioRefreshLibrary();
+ // Pull engine cache state + recent-uploads strip + estimate so the
+ // composer is fully populated before the user reads it. These are
+ // best-effort and silent on failure.
+ if (typeof imgStudioRefreshEngineStatus === 'function') imgStudioRefreshEngineStatus();
+ if (typeof imgStudioRefreshRecent === 'function') imgStudioRefreshRecent();
+ if (typeof imgStudioUpdateEstimate === 'function') imgStudioUpdateEstimate();
+ // Auto-set the right-pane outputs gallery to "Photos" — image mode
+ // is composing photos, so a video gallery makes no sense as the
+ // default. User can still flip back to All/Videos manually.
+ if (typeof _autoMainOutputsFilterForMode === 'function') {
+ _autoMainOutputsFilterForMode('image');
}
+ return;
}
+ if (studio) studio.classList.remove('show');
+ if (train) train.classList.remove('show');
+ if (genForm) genForm.style.display = '';
+ // Portal the picker back to its video-form home so it's visible above
+ // the Generate button when the user is composing a video shot.
+ _portalLoraPicker('video');
+ // Same re-render trigger as the image branch above — without it the
+ // picker keeps the previous mode's filter when flipping back from
+ // Studio to a video mode.
+ if (typeof renderLorasList === 'function') renderLorasList();
+ document.getElementById('mode').value = mode;
+ document.querySelectorAll('#modeGroup .pill-btn').forEach(b => b.classList.toggle('active', b.dataset.mode === mode));
+ // Mode → main-outputs filter auto-set (Videos for video modes).
+ if (typeof _autoMainOutputsFilterForMode === 'function') {
+ _autoMainOutputsFilterForMode(mode);
+ }
+ // For i2v, switch the actual mode based on the i2vMode select
+ if (mode === 'i2v') {
+ document.getElementById('mode').value = document.getElementById('i2vMode').value;
+ }
+ // Keyframe REQUIRES Q8 (uses dev transformer); force quality=high.
+ // If Q8 isn't available the High pill stays disabled and the user gets the
+ // same "Q8 not installed" hint as elsewhere.
+ if (mode === 'keyframe') {
+ setQuality('high');
+ }
+ updateAccelAvailability();
+ updateTemporalAvailability();
updateDerived();
+ // Refresh the inline models card immediately — switching to FFLF when
+ // Q8 is missing should surface the Download Q8 CTA without waiting for
+ // the next 1.5s poll tick.
+ if (LAST_STATUS) updateModelsCard(LAST_STATUS);
}
-async function pickerUploadFile(key, file) {
- const els = pickerEls(key);
- if (!file || !els.drop) return;
- // Inline progress overlay on the drop tile while the upload runs.
- let busy = els.drop.querySelector('.picker-uploading');
- if (!busy) {
- busy = document.createElement('div');
- busy.className = 'picker-uploading';
- busy.textContent = `Uploading ${file.name}…`;
- els.drop.appendChild(busy);
- }
- try {
- const fd = new FormData(); fd.append('image', file);
- const r = await fetch('/upload', { method: 'POST', body: fd });
- const data = await r.json();
- if (!data.ok) throw new Error(data.error || 'upload failed');
- pickerSetImage(key, data.path);
- // Refresh the "Recent uploads" strip so the just-uploaded file shows
- // up immediately for the other slots too.
- refreshUploadsStrip();
- } catch (e) {
- alert(`Upload failed: ${e.message || e}`);
- } finally {
- busy.remove();
+// Move the unified LoRA picker between its two homes (Option A portal).
+// "video" → goes inside #genForm (its declared position), "studio" →
+// goes inside #studioSection. Idempotent: a re-portal to the same
+// destination is a no-op. The hidden #lorasJson input is a SEPARATE
+// element that stays inside #genForm regardless, so the video form's
+// FormData(genForm) keeps picking it up. Image Studio's submit
+// (imgStudioGenerate) reads _activeLoras directly when posting.
+function _portalLoraPicker(dest) {
+ const node = document.getElementById('lorasDetails');
+ const videoSlot = document.getElementById('loraPickerVideoSlot');
+ const studioSlot = document.getElementById('loraPickerStudioSlot');
+ if (!node) return;
+ const target = (dest === 'studio') ? studioSlot : videoSlot;
+ if (!target || node.parentElement === target) {
+ if (typeof renderLorasList === 'function') renderLorasList();
+ return;
}
+ target.appendChild(node);
+ // Re-render so the mode banner + library filter snap to the new
+ // (mode + engine) context immediately.
+ if (typeof renderLorasList === 'function') renderLorasList();
}
-function pickerWire(key) {
- const els = pickerEls(key);
- if (!els.drop) return;
- // Click → file dialog. Skip when the click came from the clear button.
- els.drop.addEventListener('click', (e) => {
- if (e.target.closest('.picker-clear')) return;
- els.file.click();
- });
- els.file.addEventListener('change', () => {
- if (els.file.files[0]) pickerUploadFile(key, els.file.files[0]);
- els.file.value = ''; // allow re-uploading the same file
- });
- els.clear.addEventListener('click', (e) => { e.stopPropagation(); pickerSetImage(key, ''); });
- // Drag-drop. preventDefault on dragover is what enables drop.
- els.drop.addEventListener('dragover', (e) => {
- e.preventDefault();
- els.drop.classList.add('dragover');
- });
- els.drop.addEventListener('dragleave', () => els.drop.classList.remove('dragover'));
- els.drop.addEventListener('drop', (e) => {
- e.preventDefault();
- els.drop.classList.remove('dragover');
- const f = e.dataTransfer.files && e.dataTransfer.files[0];
- if (f) pickerUploadFile(key, f);
- });
-}
+// ====== Image Studio (manual still gen) ======================================
+// State: 3 reference slots. Each slot holds {path, name} when populated.
+const IMG_STUDIO = {
+ refs: [null, null, null],
+ busy: false,
+};
-let _uploadsCache = []; // last fetched list, kept module-level so all
- // three pickers render the same source data.
-async function refreshUploadsStrip() {
- let data;
- try { data = await api('/uploads?limit=24'); }
- catch (e) { return; }
- _uploadsCache = data.uploads || [];
- PICKERS.forEach(key => {
- const els = pickerEls(key);
- if (!els.recentStrip) return;
- if (!_uploadsCache.length) {
- els.recentWrap.style.display = 'none';
- return;
- }
- els.recentWrap.style.display = '';
- const currentPath = els.hidden.value;
- els.recentStrip.innerHTML = _uploadsCache.map(u => `
- <img class="picker-recent-thumb${u.path === currentPath ? ' selected' : ''}"
- src="${escapeHtml(u.url)}"
- data-path="${escapeHtml(u.path)}"
- title="${escapeHtml(u.name)} · ${u.size_kb} KB · ${escapeHtml(u.mtime)}"
- alt="">
- `).join('');
- els.recentStrip.querySelectorAll('img').forEach(img => {
- img.addEventListener('click', () => pickerSetImage(key, img.dataset.path));
- });
- });
+// Engine families that REQUIRE at least one reference image (mflux's
+// qwen-edit CLI marks --image-paths as required; calling it without
+// refs returns an argparse error after model load). The Studio engine
+// override values map 1:1 to these check predicates. Used by
+// imgStudioUpdateValidity() to gate the Generate button.
+function imgStudioRequiresRefs(engineOverride) {
+ return engineOverride === 'qwen_edit_inline'
+ || engineOverride === 'qwen_edit_lightning_inline'
+ || engineOverride === 'qwen_edit_high_inline';
}
-// ====== Format helpers ======
-function fmtMem(m) { return `${m.used_gb.toFixed(1)} / ${m.total_gb.toFixed(0)} GB · swap ${m.swap_gb.toFixed(1)}`; }
-function fmtMin(s) { if (!s || s < 0) return '—'; const m = Math.floor(s/60); const sec = Math.round(s%60); return m > 0 ? `${m}m ${sec}s` : `${sec}s`; }
-function snippet(s, n = 70) { if (!s) return ''; s = s.replace(/\s+/g,' ').trim(); return s.length > n ? s.slice(0, n-1)+'…' : s; }
-function escapeHtml(s) { if (!s) return ''; return s.replace(/[&<>"']/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c])); }
-
-async function api(path, method = 'GET', body = null) {
- const opts = { method };
- if (body) {
- opts.body = body instanceof FormData ? new URLSearchParams(body) : body;
- opts.headers = { 'Content-Type': 'application/x-www-form-urlencoded' };
+function imgStudioUpdateValidity() {
+ const btn = document.getElementById('imgStudioGenBtn');
+ const eng = document.getElementById('imgStudioEngine');
+ const status = document.getElementById('imgStudioStatus');
+ if (!btn || !eng) return;
+ const refsCount = IMG_STUDIO.refs.filter(r => r && r.path).length;
+ const needsRefs = imgStudioRequiresRefs(eng.value);
+ let invalidReason = '';
+ if (needsRefs && refsCount === 0) {
+ invalidReason = 'Pick at least 1 reference image (drop a file into one of the 3 slots above) — Qwen-Image-Edit composes against an image, it cannot run text-only. Use the Lightning preset only after picking a ref.';
+ }
+ // Don't override the busy state — imgStudioGenerate manages disabled
+ // during in-flight gens.
+ if (!IMG_STUDIO.busy) {
+ btn.disabled = !!invalidReason;
+ btn.title = invalidReason || 'Generate (Cmd/Ctrl+Enter)';
+ if (status && !status.textContent.startsWith('Generating')) {
+ if (invalidReason) {
+ status.innerHTML = '<svg class="ph" aria-hidden="true" style="margin-right:4px;vertical-align:-2px"><use href="#ph-warning-fill"/></svg>' + escapeHtml(invalidReason);
+ } else {
+ status.textContent = '';
+ }
+ }
}
- const r = await fetch(path, opts);
- if (!r.ok && r.status !== 409) throw new Error(`${path}: ${r.status}`);
- return r.status === 409 ? { error: 'busy' } : r.json().catch(() => ({}));
}
-// ====== Poll ======
-// Cache of the latest /status response so non-poll callers (setMode,
-// setQuality) can refresh tier-gated UI without waiting for the next tick.
-let LAST_STATUS = null;
-
-// Tracks consecutive /status failures so we can surface a panel-offline
-// banner instead of silently freezing the UI. Two-strike threshold so a
-// single transient hiccup (network blip, panel reload) doesn't flash.
-let _POLL_FAILS = 0;
-
-// Last 8 banner messages stay accessible from devtools at
-// `window._panelBannerLog` so a user who saw a flash but couldn't
-// read it can recover the message after the fact. Cheap insurance.
-window._panelBannerLog = window._panelBannerLog || [];
+// Reveal the mock-engine option only when the URL has ?debug=1.
+// Mock paints flat colored rectangles — useful for testing the UX
+// without spending GPU time, but a casual user picks it and gets
+// confused output. Audit finding HIGH #14.
+(function() {
+ try {
+ const params = new URLSearchParams(window.location.search);
+ if (params.get('debug') === '1') {
+ const m = document.getElementById('imgStudioMockOption');
+ if (m) m.removeAttribute('hidden');
+ }
+ } catch (e) {}
+})();
-function _setOfflineBanner(visible, msg) {
- let bar = document.getElementById('panelOfflineBanner');
- if (visible) {
- const text = msg || "uploads, chat & renders are paused";
- if (!bar) {
- bar = document.createElement('div');
- bar.id = 'panelOfflineBanner';
- bar.className = 'panel-offline-banner';
- bar.innerHTML =
- '<span class="icon"><img src="/assets/favicon-64.png" alt=""></span>' +
- '<span class="label">Phosphene offline</span>' +
- '<span class="text"></span>' +
- '<span class="hint">restart from Pinokio</span>';
- document.body.appendChild(bar);
+// Phase 1: Image Studio is now an inline pane (#studioSection) shown by
+// setMode('image'). These two functions stay as no-arg shims so any
+// caller still doing openImageStudio()/closeImageStudio() works.
+// Switching to 'image' shows the pane; switching to any other video
+// mode hides it. The pill row drives both flows.
+function openImageStudio() {
+ setMode('image');
+ // Re-evaluate Generate button state (engine + ref count) every time the
+ // user enters Studio so they don't see a stale "ready" button when the
+ // engine selection makes refs mandatory.
+ imgStudioUpdateValidity();
+ setTimeout(() => {
+ const t = document.getElementById('imgStudioPrompt');
+ if (t) {
+ t.focus();
+ try { t.scrollIntoView({behavior:'smooth', block:'center'}); } catch (e) {}
}
- bar.classList.remove('reconnected');
- bar.querySelector('.label').textContent = 'Phosphene offline';
- bar.querySelector('.text').textContent = text;
- bar.querySelector('.hint').textContent = 'restart from Pinokio';
- const entry = `${new Date().toLocaleTimeString()} offline · ${text}`;
- window._panelBannerLog.push(entry);
- if (window._panelBannerLog.length > 8) window._panelBannerLog.shift();
- console.warn('[phosphene] offline banner:', text);
- } else if (bar && !bar.classList.contains('reconnected')) {
- // Linger for 3s in a "back online" state instead of removing
- // instantly. Salo flagged that he saw a banner flash during a
- // restart but couldn't read it before it disappeared — this gives
- // the eye time to register and gives the user a chance to scroll
- // back in window._panelBannerLog if they want details.
- bar.classList.add('reconnected');
- bar.querySelector('.label').textContent = 'Phosphene reconnected';
- bar.querySelector('.text').textContent = 'queue + renders resumed';
- bar.querySelector('.hint').textContent = '';
- const entry = `${new Date().toLocaleTimeString()} online · reconnected`;
- window._panelBannerLog.push(entry);
- if (window._panelBannerLog.length > 8) window._panelBannerLog.shift();
- console.info('[phosphene] panel reconnected');
- setTimeout(() => {
- const b = document.getElementById('panelOfflineBanner');
- if (b && b.classList.contains('reconnected')) b.remove();
- }, 3000);
- }
+ }, 50);
}
-async function poll() {
- let s;
- const url = '/status' + (filterMode === 'hidden' ? '?include_hidden=1' : '');
- try {
- s = await (await fetch(url)).json();
- _POLL_FAILS = 0;
- _setOfflineBanner(false);
- } catch (e) {
- _POLL_FAILS += 1;
- // Suppress the offline banner while a known long-running endpoint is
- // in flight (e.g. /version/pull which blocks the server for ~30s on
- // git fetch + git pull). Without this suppression the banner flashes
- // "Phosphene offline → reconnected" at the tail of every successful
- // Update click — looks like an error to the user when nothing is
- // actually wrong.
- if (_POLL_FAILS >= 2 && !window._suppressOfflineBanner) _setOfflineBanner(true);
- return;
- }
- LAST_STATUS = s;
+function closeImageStudio() {
+ // Return to the last sensible video mode. t2v is the safe default;
+ // a future enhancement could remember the previous mode the user was
+ // on before clicking Studio. For Phase 1, t2v is fine.
+ setMode('t2v');
+}
+
+function imgStudioWireRefSlots() {
+ // Backwards-compat: the legacy `.img-ref-slot` selector matched the old
+ // 3-column flat grid. The new restyled composer uses `.studio-ref-slot`.
+ // Wire both so any in-flight upgrade path keeps working.
+ document.querySelectorAll('.studio-ref-slot, .img-ref-slot').forEach(slot => {
+ if (slot.dataset.wired === '1') return;
+ slot.dataset.wired = '1';
+ const idx = parseInt(slot.dataset.slot, 10);
+ // Click → file picker. Skip when the user clicked the close (×) button
+ // — its handler manages the clear flow.
+ slot.addEventListener('click', (e) => {
+ if (e.target.classList && e.target.classList.contains('clear-x')) return;
+ const input = document.createElement('input');
+ input.type = 'file';
+ input.accept = 'image/png,image/jpeg,image/webp';
+ input.onchange = () => {
+ if (input.files && input.files[0]) imgStudioUploadRef(idx, input.files[0]);
+ };
+ input.click();
+ });
+ // Drag + drop. .dragover class is style-driven (no inline style) so it
+ // composes cleanly with .has-image / hover.
+ slot.addEventListener('dragover', (e) => {
+ e.preventDefault();
+ slot.classList.add('dragover');
+ });
+ slot.addEventListener('dragleave', () => slot.classList.remove('dragover'));
+ slot.addEventListener('drop', (e) => {
+ e.preventDefault();
+ slot.classList.remove('dragover');
+ const f = e.dataTransfer && e.dataTransfer.files && e.dataTransfer.files[0];
+ if (f) imgStudioUploadRef(idx, f);
+ });
+ imgStudioRenderSlot(idx);
+ });
+}
- // Memory
- const m = s.memory;
- const memPill = document.getElementById('memPill');
- memPill.innerHTML = `<span class="dot"></span>${fmtMem(m)}`;
- let memCls = 'pill-good';
- if (m.swap_gb > 8 || m.pressure_pct > 90) memCls = 'pill-danger';
- else if (m.swap_gb > 4 || m.pressure_pct > 75) memCls = 'pill-warn';
- memPill.className = 'pill ' + memCls;
+const _STUDIO_REF_TAGS = ['Primary', 'Multi-ref', 'Multi-ref'];
- // Comfy (hidden when not running). Drives three things in lockstep —
- // the status pill, the global Stop Comfy button, and the per-render
- // "Stop ComfyUI before render" checkbox in the form. The checkbox row
- // stays hidden when Comfy isn't running so users who don't have Comfy
- // installed never see a cryptic toggle.
- const cp = document.getElementById('comfyPill');
- const stopBtn = document.getElementById('stopComfyBtn');
- const comfyRow = document.getElementById('comfyKillRow');
- const comfyToggle = document.getElementById('stop_comfy');
- if (s.comfy_pids.length) {
- cp.innerHTML = `<span class="dot"></span>Comfy ${s.comfy_pids.join(', ')}`;
- cp.className = 'pill pill-warn'; cp.style.display = '';
- stopBtn.style.display = '';
- if (comfyRow) comfyRow.style.display = '';
+function imgStudioRenderSlot(idx) {
+ const slot = document.querySelector(
+ `.studio-ref-slot[data-slot="${idx}"], .img-ref-slot[data-slot="${idx}"]`);
+ if (!slot) return;
+ const ref = IMG_STUDIO.refs[idx];
+ const tag = _STUDIO_REF_TAGS[idx] || `Ref ${idx + 1}`;
+ if (ref && ref.path) {
+ slot.classList.add('has-image');
+ slot.innerHTML = `
+ <span class="ref-tag">${tag}</span>
+ <img src="/image?path=${encodeURIComponent(ref.path)}" alt="">
+ <button class="clear-x" type="button" onclick="imgStudioClearRef(${idx});event.stopPropagation()" title="Remove"><svg class="ph" aria-hidden="true"><use href="#ph-x-bold"/></svg></button>
+ `;
} else {
- cp.style.display = 'none';
- stopBtn.style.display = 'none';
- if (comfyRow) comfyRow.style.display = 'none';
- // When Comfy isn't running, also force the form value off so the
- // submission doesn't carry a meaningless `stop_comfy=on` server-side.
- if (comfyToggle) comfyToggle.checked = false;
+ slot.classList.remove('has-image');
+ const cta = idx === 0
+ ? 'Drop · click<br>character'
+ : (idx === 1 ? 'Drop · click<br>place' : 'Drop · click<br>style');
+ slot.innerHTML = `
+ <span class="ref-tag">${tag}</span>
+ <div class="ref-empty">
+ <div class="ref-icon"><svg class="ph" aria-hidden="true"><use href="#ph-image"/></svg></div>
+ <div class="ref-cta">${cta}</div>
+ </div>
+ `;
}
+ imgStudioUpdateValidity();
+ // Recent strip's "in-use" highlight depends on which paths are bound to
+ // slots — re-render the strip so freshly-cleared slots release their
+ // selection ring.
+ if (typeof imgStudioMarkRecentInUse === 'function') imgStudioMarkRecentInUse();
+}
- // Helper
- const hp = document.getElementById('helperPill');
- if (s.helper && s.helper.alive) {
- hp.innerHTML = `<span class="dot"></span>helper warm`;
- hp.className = 'pill pill-good';
- hp.title = 'Helper subprocess is loaded with pipelines and ready.';
- } else {
- // Helper auto-respawns on the next job (see WarmHelper._ensure). "Cold"
- // is normal after the idle timeout, not an error — first job after a
- // cold start eats a ~30s pipeline-load cost.
- hp.innerHTML = `<span class="dot"></span>helper idle`;
- hp.className = 'pill';
- hp.title = 'Helper is idle (auto-exited after the idle timeout). The next queued job will respawn it; expect a one-time ~30s pipeline-load delay.';
- }
+// ---- Engine status pill + wall-time estimate ----
+// Cache of /image/engine_status results so onchange handlers don't refetch
+// on every keystroke. Refreshed when setMode('image') runs and after a
+// successful Generate (in case the worker just downloaded weights).
+let _IMG_ENGINE_STATUS = {}; // engine_override -> {cached, download_gb, sec_per_image}
- // Tier pill — what this Mac's RAM tier allows. Click to open the
- // explanation modal. Color is informational, not warning: the tier is
- // what it is, not "wrong".
- const tp = document.getElementById('tierPill');
- if (s.tier) {
- const t = s.tier;
- const cls = t.key === 'base' ? 'pill-warn'
- : (t.key === 'pro' ? 'pill-good' : '');
- // Show the friendly label ("Compact" / "Comfortable" / "Roomy" /
- // "Studio") not the internal key. Click opens the explanation modal.
- tp.innerHTML = `<span class="dot"></span>${escapeHtml(t.label || t.key)}`;
- tp.className = 'pill ' + cls;
- tp.title = `${t.label} (${t.ram_label}) · ${t.tagline} · click for details`;
- // Apply tier-driven enabled/disabled state to mode + quality pills.
- // Done here in poll() so a tier override (env var) flips state on
- // panel restart without needing to also change a separate setMode call.
- applyTierGates(t);
+async function imgStudioRefreshEngineStatus() {
+ try {
+ const r = await fetch('/image/engine_status');
+ if (!r.ok) throw new Error('HTTP ' + r.status);
+ const j = await r.json();
+ const map = {};
+ (j.engines || []).forEach(e => { map[e.engine] = e; });
+ _IMG_ENGINE_STATUS = map;
+ } catch (e) {
+ // Silent — pill falls back to "unknown" (dim ellipsis).
+ _IMG_ENGINE_STATUS = {};
}
+ imgStudioRenderEnginePill();
+ imgStudioUpdateEstimate();
+}
- // Models pill — roll-up status: base ready / Q8 ready, plus active download.
- // Renders as one of:
- // "models ↓ Q4 12%" while a download streams (live progress, last hf line)
- // "models 3/3" all on disk
- // "models 2/3" base ready, Q8 missing → warn color
- // "models 0/3" base incomplete → bad color
- const mp = document.getElementById('modelsPill');
- const dl = s.download && s.download.active ? s.download : null;
- if (dl) {
- const elapsed = Math.max(0, Math.round(s.server_now - (dl.started_ts || s.server_now)));
- mp.innerHTML = `<span class="dot"></span>↓ ${dl.key} · ${elapsed}s`;
- mp.className = 'pill pill-running';
- mp.title = `Downloading ${dl.repo_id} — ${dl.last_line || 'starting…'}`;
- } else {
- // Per-repo ready/total counts, matches what the modal shows (3 rows by
- // default: Q4 + Gemma + Q8). base_available is a roll-up bool that
- // honors the HF-id env-var short-circuit; we use it for the color
- // hint, not the count itself.
- const baseOk = s.base_available;
- const q8Ok = s.q8_available;
- const ready = s.repos_ready ?? 0;
- const total = s.repos_total ?? 0;
- mp.innerHTML = `<span class="dot"></span>models ${ready}/${total}`;
- mp.className = 'pill ' + (!baseOk ? 'pill-warn' : (q8Ok ? 'pill-good' : ''));
- mp.title = !baseOk
- ? 'Base models incomplete — click to download'
- : (q8Ok ? 'All models on disk' : 'Q8 not installed (optional — needed for High quality + FFLF)');
- }
- // If the modal is open, refresh its rows on each poll so progress updates.
- if (document.getElementById('modelsModal').style.display !== 'none') {
- refreshModelsModal({ silent: true });
+function imgStudioRenderEnginePill() {
+ const pill = document.getElementById('imgStudioEnginePill');
+ const eng = document.getElementById('imgStudioEngine');
+ if (!pill || !eng) return;
+ const v = eng.value;
+ // 'auto' resolves to whatever the user saved in Settings — we don't try
+ // to second-guess that here, just show a neutral pill.
+ if (v === 'auto') {
+ pill.dataset.state = 'unknown';
+ pill.textContent = 'auto';
+ pill.title = 'Uses your saved Settings engine';
+ return;
}
- // Inline models card — top-of-form, big, can't miss it. State logic
- // lives in updateModelsCard so we don't bloat poll() further.
- updateModelsCard(s);
-
- // Queue pill + tab badge. Animate the bottom-pane Queue badge with
- // a brief scale-up "pop" when the count goes up — draws the eye to
- // the badge so the user notices that a new job got queued without
- // having to watch the strip. CSS .badge.bump handles the keyframes;
- // we just toggle the class for ~280 ms.
- const qp = document.getElementById('queuePill');
- qp.innerHTML = `<span class="dot"></span>queue ${s.queue.length}${s.paused ? ' · paused' : ''}`;
- qp.className = 'pill ' + (s.paused ? 'pill-warn' : (s.queue.length ? 'pill-running' : ''));
- const qb = document.getElementById('queueBadge');
- const prevQueueLen = window._lastQueueLen ?? 0;
- if (s.queue.length) {
- qb.textContent = s.queue.length;
- qb.style.display = '';
- if (s.queue.length > prevQueueLen) {
- qb.classList.remove('bump');
- // Re-trigger the CSS animation by toggling the class after a
- // reflow. Without the rAF the second add doesn't re-fire.
- requestAnimationFrame(() => {
- qb.classList.add('bump');
- setTimeout(() => qb.classList.remove('bump'), 320);
- });
- }
- } else {
- qb.style.display = 'none';
+ const info = _IMG_ENGINE_STATUS[v];
+ if (!info) {
+ pill.dataset.state = 'unknown';
+ pill.textContent = '…';
+ pill.title = 'Checking weights…';
+ return;
}
- window._lastQueueLen = s.queue.length;
-
- // Job pill
- const jp = document.getElementById('jobPill');
- if (s.running && s.current) {
- const elapsed = Math.max(0, Math.round(s.server_now - s.current.started_ts));
- jp.innerHTML = `<span class="dot"></span>${s.current.params.label || s.current.params.mode} · ${elapsed}s`;
- jp.className = 'pill pill-running';
+ if (info.cached) {
+ pill.dataset.state = 'ready';
+ pill.innerHTML = '<svg class="ph" aria-hidden="true" style="margin-right:4px;vertical-align:-2px"><use href="#ph-check-bold"/></svg>ready';
+ pill.title = 'Weights are cached locally';
} else {
- jp.innerHTML = `<span class="dot"></span>idle`;
- jp.className = 'pill';
+ pill.dataset.state = 'missing';
+ const gb = info.download_gb || 0;
+ pill.innerHTML = '<svg class="ph" aria-hidden="true" style="margin-right:4px;vertical-align:-2px"><use href="#ph-download-simple"/></svg>' + (gb > 0 ? gb.toFixed(0) + ' GB' : 'fetch');
+ pill.title = (gb > 0
+ ? `Weights not cached — first run will download ~${gb.toFixed(0)} GB`
+ : 'Weights not cached — first run will fetch');
}
+}
- document.getElementById('pauseBtn').textContent = s.paused ? 'Resume queue' : 'Pause queue';
-
- // Q8 / High enable. Subtitle shows what pipeline this chip uses; goes
- // visible permanently (no more `hidden` attribute on the span) so users
- // can see at a glance which engine drives each tier.
- const highBtn = document.getElementById('qualityHigh');
- const highSub = document.getElementById('highSub');
- if (s.q8_available) {
- highBtn.classList.remove('disabled', 'needs-install');
- highSub.textContent = 'Q8 Pro · 7 min';
- } else {
- // Disabled-but-actionable: a click on the High pill now opens the
- // Models modal so the user can install Q8 in one move instead of
- // hunting for the download. CSS .needs-install gives the pill an
- // accent-tinted look + download arrow in the subtitle so it reads
- // as a CTA, not a dead button.
- highBtn.classList.add('disabled', 'needs-install');
- const missing = (s.q8_missing || []).length;
- if (missing > 0 && missing < 6) {
- highSub.textContent = `Q8 downloading · ${missing} left`;
- highBtn.classList.remove('needs-install'); // mid-download, no need for the CTA hint
- } else {
- highSub.textContent = 'Install Q8 (37 GB)';
- }
- if (document.getElementById('quality').value === 'high') setQuality('standard');
+function imgStudioUpdateEstimate() {
+ const out = document.getElementById('imgStudioWallEstimate');
+ const btnLabel = document.getElementById('imgStudioGenBtnLabel');
+ if (!out || !btnLabel) return;
+ const eng = (document.getElementById('imgStudioEngine') || {}).value || 'auto';
+ const n = parseInt((document.getElementById('imgStudioN') || {}).value || '4', 10);
+ const safeN = Math.max(1, Math.min(8, isFinite(n) ? n : 4));
+ // Wall-time = cold_start (paid once per batch) + n × per-image (denoise).
+ // /image/engine_status returns both fields. The HiDream lab subprocess
+ // pays ~45s cold load per batch (BF16 weights -> MLX); mflux engines
+ // fold theirs into sec_per_image (cold_start_sec=0). The auto preset
+ // doesn't know its target ahead of time so we hide.
+ const info = _IMG_ENGINE_STATUS[eng];
+ let label = 'Generate';
+ if (info && !info.cached && (info.download_gb || 0) > 0) {
+ label = `Generate · downloads ~${info.download_gb.toFixed(0)} GB first`;
}
-
- // Balanced subtitle: on the "standard" (48–79 GB) tier with Q8 installed,
- // the Balanced chip auto-routes to Q8 Fast (safe_a config) — but ONLY for
- // mode ∈ {t2v, a2v} and frames ≤ 121, which is what the 64 GB memory
- // budget actually fits. Other combos fall back to Q4 Balanced. The
- // subtitle reflects the user's current selection so they see what they
- // will actually get when they hit Generate. Re-evaluated on every poll
- // and on mode/frames change (see the listener wired at DOMContentLoaded
- // below this function).
- window.__phosLastStatus = s;
- if (typeof window.refreshBalancedSubtitle === 'function') {
- window.refreshBalancedSubtitle(s);
+ btnLabel.textContent = label;
+ if (eng === 'auto' || !info || !info.sec_per_image) {
+ out.textContent = '';
+ out.classList.add('dim');
+ return;
}
+ const coldStart = info.cold_start_sec || 0;
+ const total = coldStart + safeN * info.sec_per_image;
+ out.textContent = '~' + _imgStudioFmtDuration(total) + (safeN > 1 ? ` · ${safeN} imgs` : '');
+ out.classList.remove('dim');
+}
- // Keyframe (FFLF) and Extend both require Q8 — server enforces it (see
- // run_job_inner). The UI was previously silently downgrading the user to
- // Standard when they picked keyframe with Q8 missing, then the server
- // would 500 on submit. Disable Generate + show a clear reason while in
- // that state. Y1.036 added Extend to the same gate after the Y1.024
- // download trim exposed that Extend is structurally Q8-class.
- const genBtn = document.getElementById('genBtn');
- const q8GatedMode = (currentMode === 'keyframe' || currentMode === 'extend');
- if (q8GatedMode && !s.q8_available) {
- genBtn.disabled = true;
- const modeName = currentMode === 'keyframe' ? 'Keyframe (FFLF)' : 'Extend';
- const left = (s.q8_missing || []).length;
- genBtn.title = left > 0 && left < 6
- ? `${modeName} needs Q8 — ${left} file(s) still downloading.`
- : `${modeName} needs the Q8 model. Click "Download Q8 (~37 GB)" in Pinokio.`;
- genBtn.textContent = 'Generate · Q8 required';
- } else if (genBtn.disabled && genBtn.textContent.startsWith('Generate · Q8')) {
- // Restore — only do so if WE were the ones who disabled it, otherwise
- // some future code path that disables Generate for a different reason
- // would get clobbered here.
- genBtn.disabled = false;
- genBtn.title = '';
- genBtn.textContent = 'Generate';
- }
+function _imgStudioFmtDuration(sec) {
+ sec = Math.max(0, Math.round(sec));
+ if (sec < 60) return sec + 's';
+ const m = Math.floor(sec / 60);
+ const s = sec % 60;
+ return s ? `${m}m ${s}s` : `${m}m`;
+}
- // Now card
- // Y1.039 — bar + meta line driven by server-computed progress (phase-aware,
- // config-bucketed ETA, denoise per-step extrapolation). Falls back to the
- // old elapsed/global-avg behavior if the server didn't ship a progress
- // block (e.g. mid-deploy where the server is older than the JS).
- const nowCard = document.getElementById('nowCard');
- const fill = document.getElementById('progressFill');
- // The Now-card Stop button is gone — both the video form's Stop and
- // the Image Studio's Stop now live in the form-pane and stay
- // visible across mode switches, so a Now-card duplicate is no
- // longer needed.
- if (s.running && s.current) {
- nowCard.classList.remove('idle', 'failed');
- const prog = s.current.progress || null;
- const elapsedFallback = Math.max(0, s.server_now - s.current.started_ts);
- let pct, elapsed, phaseLabel, timing;
- if (prog) {
- pct = Math.min(99, Math.max(0, prog.pct ?? 0));
- elapsed = prog.elapsed_sec ?? elapsedFallback;
- phaseLabel = prog.phase_label || 'Working';
- if (prog.remaining_sec != null && prog.remaining_sec > 0) {
- timing = `<strong>${fmtMin(elapsed)}</strong> in · ~${fmtMin(prog.remaining_sec)} left`;
- } else if (prog.eta_sec) {
- timing = `<strong>${fmtMin(elapsed)}</strong> / ~${fmtMin(prog.eta_sec)}`;
- } else {
- timing = `<strong>${fmtMin(elapsed)}</strong> elapsed`;
- }
- } else {
- // Legacy fallback path
- const avg = s.avg_elapsed_sec || 420;
- pct = Math.min(99, Math.round(elapsedFallback / avg * 100));
- elapsed = elapsedFallback;
- phaseLabel = '';
- timing = `<strong>${fmtMin(elapsed)}</strong> elapsed${avg ? ' / ~'+fmtMin(avg)+' avg' : ''}`;
- }
- fill.style.width = pct + '%';
- nowCard.querySelector('.ttl').textContent = snippet(s.current.params.label || s.current.params.prompt, 80);
- // Image jobs don't have width/height/frames; show n × aspect instead.
- // Falls through to the video shape when those fields ARE present.
- const cur = s.current.params;
- const baseMeta = (cur.mode === 'image')
- ? `image · ${cur.aspect || '?'} · n=${cur.n || '?'} · ${cur.engine_override || 'auto'} · ${timing}`
- : `${cur.mode} · ${cur.width}×${cur.height} · ${cur.frames}f · ${timing}`;
- nowCard.querySelector('.meta').innerHTML = phaseLabel
- ? `${baseMeta}<br><span style="color:var(--muted)">${escapeHtml(phaseLabel)}</span>`
- : baseMeta;
- } else {
- // Idle state. If the LAST history entry was a failure (helper crash,
- // OOM, etc.) surface it loud-and-clear here — otherwise users like
- // cocktailpeanut just see "Idle" and assume "the panel did nothing."
- // We hold the failure visible until the user starts a new job.
- fill.style.width = '0%';
- const last = (s.history || [])[0];
- // Salo flagged that a stuck "Job failed" card with no close button
- // is disruptive — once a render fails, the surface holds the message
- // visible until the next job runs, with no way to acknowledge it.
- // _dismissedFailureId remembers which job id the user chose to
- // dismiss so we don't keep nagging. Clears on next job (id changes).
- const showFailure = last && last.status === 'failed' && !s.queue.length
- && last.id !== window._dismissedFailureId;
- const actionsEl = document.getElementById('nowCardActions');
- if (showFailure) {
- nowCard.classList.remove('idle');
- nowCard.classList.add('failed');
- // Translate cryptic engine errors into actionable user guidance.
- // "helper died mid-job (no event)" is the SIGKILL-by-jetsam
- // signature on memory-pressured Macs — the helper subprocess gets
- // killed by the OS for using too much RAM and we never get an
- // event back. Tell the user how to recover instead of leaving them
- // with the engine wording.
- const raw = (last.error || 'unknown error');
- const rawLower = raw.toLowerCase();
- let friendly, hint;
- if (rawLower.includes('sigkill')) {
- friendly = 'Helper killed by the OS — out of memory (jetsam).';
- hint = 'Close memory-heavy apps (Chrome, Slack, iOS Simulator) and try again, ' +
- 'or switch Quality to Quick (about half the RAM).';
- } else if (rawLower.includes('sigsegv') || rawLower.includes('sigbus')) {
- friendly = 'Helper crashed at the native level (MLX/Metal fault).';
- hint = 'Share the crashlog at ~/Library/Logs/DiagnosticReports/python3.11_*.crash ' +
- 'on github.com/mrbizarro/phosphene/issues so we can fix it.';
- } else if (rawLower.includes('sigabrt')) {
- friendly = 'Helper hit a C-level assertion and aborted.';
- hint = 'Share the crashlog at ~/Library/Logs/DiagnosticReports/python3.11_*.crash ' +
- 'on github.com/mrbizarro/phosphene/issues.';
- } else if (rawLower.includes('helper exited from') || rawLower.includes('helper pipe closed') ||
- rawLower.includes('helper died') || rawLower.includes('helper exited')) {
- friendly = 'Helper exited unexpectedly.';
- hint = 'Check the log for the last "step:*" breadcrumb (tells us which ' +
- 'phase died). If memory-pressured, close other apps and retry.';
- } else if (rawLower.includes('q8') || rawLower.includes('keyframe')) {
- friendly = 'This mode needs the Q8 model.';
- hint = raw;
- } else {
- friendly = 'Job failed.';
- hint = raw;
- }
- nowCard.querySelector('.ttl').innerHTML =
- `<span style="color: var(--danger, #f85149)"><svg class="ph" aria-hidden="true" style="margin-right:4px;vertical-align:-2px"><use href="#ph-warning-fill"/></svg>${escapeHtml(friendly)}</span>`;
- nowCard.querySelector('.meta').innerHTML =
- `<span style="color: var(--muted)">${escapeHtml(snippet(last.params.label || last.params.prompt, 80))}</span>` +
- ` <span style="color: var(--muted)">· ${escapeHtml(last.params.mode)} · ${last.params.width}×${last.params.height}</span>` +
- `<br><span style="color: var(--text)">${escapeHtml(hint)}</span>`;
- // Action row: Retry (re-submit same params via /queue/retry) +
- // Dismiss (mark this id as handled so the next idle poll clears
- // the card). Both buttons live in a stable sibling element of
- // .ttl so the click handlers survive every poll-driven rewrite.
- // A single delegated listener on document (installed once at
- // boot) catches the clicks via data-action so we never lose them
- // to an inline-handler race.
- if (actionsEl) {
- actionsEl.dataset.jobId = String(last.id);
- actionsEl.innerHTML =
- `<button type="button" class="now-card-retry" data-action="retry" ` +
- `title="Re-submit this job with the same params">` +
- `<svg class="ph" aria-hidden="true"><use href="#ph-arrow-clockwise"/></svg>` +
- `<span>Retry</span></button>` +
- `<button type="button" class="now-card-dismiss" data-action="dismiss" ` +
- `title="Dismiss this failure" aria-label="Dismiss this failure">` +
- `<svg class="ph" aria-hidden="true"><use href="#ph-x-bold"/></svg></button>`;
- }
- } else {
- nowCard.classList.add('idle');
- nowCard.classList.remove('failed');
- nowCard.querySelector('.ttl').textContent = s.paused ? 'Paused' : 'Idle';
- nowCard.querySelector('.meta').textContent = s.paused
- ? 'Worker paused — current job (if any) finishes, queue waits for resume.'
- : (s.queue.length ? 'Worker about to pick up next queued job.' : 'No jobs queued. Generate something on the left.');
- if (actionsEl) { actionsEl.innerHTML = ''; actionsEl.dataset.jobId = ''; }
- }
+// ---- Recent uploads strip ----
+async function imgStudioRefreshRecent() {
+ const strip = document.getElementById('imgStudioRecentStrip');
+ const wrap = document.getElementById('imgStudioRecentWrap');
+ if (!strip || !wrap) return;
+ let data;
+ try { data = await api('/uploads?limit=18'); }
+ catch (e) { return; }
+ const items = (data && data.uploads) || [];
+ if (!items.length) {
+ wrap.style.display = 'none';
+ return;
}
+ wrap.style.display = '';
+ strip.innerHTML = items.map(u => `
+ <img class="studio-ref-recent-thumb"
+ src="${escapeHtml(u.url)}"
+ data-path="${escapeHtml(u.path)}"
+ title="${escapeHtml(u.name)} · ${u.size_kb} KB · ${escapeHtml(u.mtime)}"
+ alt="">
+ `).join('');
+ strip.querySelectorAll('img').forEach(img => {
+ img.addEventListener('click', () => {
+ // Find the next empty slot, or replace slot 0 if all are full.
+ const path = img.dataset.path;
+ let target = IMG_STUDIO.refs.findIndex(r => !r || !r.path);
+ if (target < 0) target = 0;
+ const fname = (path || '').split('/').pop() || 'recent';
+ IMG_STUDIO.refs[target] = { path, name: fname };
+ imgStudioRenderSlot(target);
+ imgStudioMarkRecentInUse();
+ });
+ });
+ imgStudioMarkRecentInUse();
+}
- // Y2.001 — bottom-pane live dot mirrors worker state. Tooltip sets
- // a one-line status for accessibility / hover. The dot animates
- // when running, switches red on the failed state.
- const liveDot = document.getElementById('bpLiveDot');
- if (liveDot) {
- liveDot.classList.remove('live', 'failed');
- if (s.running && s.current) {
- liveDot.classList.add('live');
- liveDot.title = 'Rendering';
- } else {
- const last = (s.history || [])[0];
- const showFailure = last && last.status === 'failed' && !s.queue.length;
- if (showFailure) { liveDot.classList.add('failed'); liveDot.title = 'Last job failed'; }
- else if (s.paused) liveDot.title = 'Paused';
- else if (s.queue.length) liveDot.title = `${s.queue.length} queued`;
- else liveDot.title = 'Idle';
- }
- }
+function imgStudioMarkRecentInUse() {
+ const strip = document.getElementById('imgStudioRecentStrip');
+ if (!strip) return;
+ const usedPaths = new Set(IMG_STUDIO.refs.filter(r => r && r.path).map(r => r.path));
+ strip.querySelectorAll('img.studio-ref-recent-thumb').forEach(img => {
+ img.classList.toggle('in-use', usedPaths.has(img.dataset.path));
+ });
+}
- // (The in-player progress overlay used to be wired here; it was
- // removed 2026-05-12 because it duplicated the bottom Now strip and
- // covered the playing video. Bottom strip is the single source.)
+// Click handler for the engine-status pill. Only meaningful when the pill
+// is in 'missing' state — focus the Generate button so the user can hit it
+// with the download-consent label already showing. (We don't kick off a
+// pre-emptive `hf download` here: the queue worker already triggers one
+// on first render, and a separate code path would risk drift between the
+// prefetch + render configs.)
+function imgStudioOnPillClick() {
+ const pill = document.getElementById('imgStudioEnginePill');
+ if (!pill || pill.dataset.state !== 'missing') return;
+ const btn = document.getElementById('imgStudioGenBtn');
+ if (!btn) return;
+ btn.focus();
+ try { btn.scrollIntoView({behavior:'smooth', block:'center'}); } catch (e) {}
+ const s = document.getElementById('imgStudioStatus');
+ if (s) s.textContent = 'Click Generate to start — first run will download the engine weights.';
+}
- // Logs
- const log = document.getElementById('log');
- const wasNearBottom = log.scrollHeight - log.scrollTop - log.clientHeight < 60;
- log.textContent = s.log.length ? s.log.join('\n') : 'No log yet.';
- if (wasNearBottom) log.scrollTop = log.scrollHeight;
+function imgStudioClearRef(idx) {
+ IMG_STUDIO.refs[idx] = null;
+ imgStudioRenderSlot(idx);
+}
- // Queue list — memoized on a signature of the IDs + ordinals so
- // identical queue data doesn't trigger a full innerHTML replacement
- // every 1.5 s. Pre-fix every poll() rebuilt all <li> nodes which
- // caused a perceptible flicker on the Queue tab during long batches.
- const ql = document.getElementById('queueList');
- const qSig = !s.queue.length ? '__empty__'
- : s.queue.map(j => j.id).join('|');
- if (qSig !== window._lastQueueSig) {
- if (!s.queue.length) ql.innerHTML = '<li class="empty-state"><span></span><span>Queue empty</span><span></span><span></span></li>';
- else ql.innerHTML = s.queue.map((j, i) => {
- // Image jobs don't have width/height/frames; show n × aspect instead.
- const params = (j.params.mode === 'image')
- ? `image · ${j.params.aspect || '?'} · n=${j.params.n || '?'}`
- : `${j.params.mode} · ${j.params.width}×${j.params.height} · ${j.params.frames}f`;
- return `
- <li>
- <span class="pos">#${i+1}</span>
- <span class="ttl" title="${escapeHtml(j.params.prompt)}">${escapeHtml(j.params.label || snippet(j.params.prompt, 60))}</span>
- <span class="params">${params}</span>
- <button title="Remove" onclick="removeJob('${j.id}')"><svg class="ph" aria-hidden="true"><use href="#ph-x-bold"/></svg></button>
- </li>`;
- }).join('');
- window._lastQueueSig = qSig;
+async function imgStudioUploadRef(idx, file) {
+ const fd = new FormData();
+ // The panel's /upload endpoint expects the multipart field to be named
+ // "image" (cgi.FieldStorage lookup); using "file" silently 400s.
+ fd.append('image', file);
+ try {
+ const r = await fetch('/upload', { method: 'POST', body: fd });
+ if (!r.ok) throw new Error(`upload ${r.status}`);
+ const j = await r.json();
+ if (!j.path) throw new Error('upload returned no path');
+ IMG_STUDIO.refs[idx] = { path: j.path, name: file.name };
+ imgStudioRenderSlot(idx);
+ } catch (e) {
+ const s = document.getElementById('imgStudioStatus');
+ if (s) s.textContent = 'Upload failed: ' + e.message;
}
+}
- // History — failed jobs show the error inline in the title slot, so
- // users can see WHY without having to scroll the log to find it.
- // mode='image' jobs render with a thumbnail of the first candidate
- // and an Animate button that pre-fills the i2v form (does NOT
- // auto-submit — user keeps the chance to tweak prompt/seed).
- const hl = document.getElementById('historyList');
- // Apply the All / Videos / Photos filter (set by setRecentFilter).
- const filterPhotos = (window.recentFilter || 'all');
- const filtered = s.history.filter(j => {
- if (filterPhotos === 'all') return true;
- const isPhoto = (j.params && j.params.mode === 'image');
- return filterPhotos === 'photos' ? isPhoto : !isPhoto;
- });
- if (!filtered.length) {
- const empty = filterPhotos === 'photos' ? 'No photo renders yet'
- : filterPhotos === 'videos' ? 'No video renders yet'
- : 'No history yet';
- hl.innerHTML = `<li class="empty-state"><span></span><span>${empty}</span><span></span><span></span></li>`;
+async function imgStudioGenerate() {
+ if (IMG_STUDIO.busy) return;
+ const prompt = (document.getElementById('imgStudioPrompt').value || '').trim();
+ if (!prompt) {
+ document.getElementById('imgStudioStatus').textContent = 'Prompt is required.';
+ return;
}
- else hl.innerHTML = filtered.slice(0, 20).map(j => {
- const titleText = escapeHtml(j.params.label || snippet(j.params.prompt, 60));
- const titleAttr = escapeHtml(j.params.prompt || '');
- let titleHtml;
- if (j.status === 'failed' && j.error) {
- titleHtml = `${titleText} ` +
- `<span class="err-inline" title="${escapeHtml(j.error)}">— ${escapeHtml(snippet(j.error, 70))}</span>`;
- } else {
- titleHtml = titleText;
+ const refs = IMG_STUDIO.refs.filter(r => r && r.path).map(r => r.path);
+ const body = {
+ prompt,
+ n: parseInt(document.getElementById('imgStudioN').value || '4', 10),
+ aspect: document.getElementById('imgStudioAspect').value || '16:9',
+ seed: parseInt(document.getElementById('imgStudioSeed').value || '-1', 10),
+ engine_override: document.getElementById('imgStudioEngine').value,
+ refs,
+ };
+ // Submit through the same /queue/add endpoint video jobs use, with
+ // mode='image'. The worker thread routes mode==='image' to
+ // run_image_job_inner (commit 1). Progress streams into the panel
+ // log + the right-rail Now/Queue/Recent cards exactly the way video
+ // jobs do — no need for the Studio's own elapsed-counter or in-pane
+ // result grid. The Recent tab's Photos filter (commit 2) surfaces
+ // the result with thumbnail + Animate.
+ IMG_STUDIO.busy = true;
+ document.getElementById('imgStudioGenBtn').disabled = true;
+ document.getElementById('imgStudioResults').innerHTML =
+ '<div class="hint">Submitted to queue. Watch the Now / Recent tabs on the right ' +
+ '(Recent → Photos for just images).</div>';
+ document.getElementById('imgStudioStatus').textContent = 'Queueing…';
+ try {
+ const fd = new URLSearchParams();
+ fd.set('mode', 'image');
+ fd.set('prompt', body.prompt);
+ fd.set('engine_override', body.engine_override || 'auto');
+ fd.set('aspect', body.aspect || '16:9');
+ fd.set('n', String(body.n || 4));
+ fd.set('seed', String(body.seed != null ? body.seed : -1));
+ // refs is a list of paths — the existing /image/generate code
+ // accepts a JSON-encoded list as a form field, and make_job()
+ // mode='image' parses the same shape (commit 1).
+ fd.set('refs', JSON.stringify(body.refs || []));
+ // Carry user-picked LoRAs through the same `loras` form field the
+ // video form uses (parse_loras_from_form on the server is shared).
+ // imgStudioGenerate doesn't go through FormData(genForm), so we
+ // attach it explicitly from _activeLoras here. Stacks on top of any
+ // preset LoRA the chosen engine_override pinned (Lightning, etc.) —
+ // run_image_job_inner does the merge.
+ if (typeof _activeLoras !== 'undefined' && Array.isArray(_activeLoras) && _activeLoras.length) {
+ const slim = _activeLoras.map(l => ({ path: l.path, strength: l.strength }));
+ fd.set('loras', JSON.stringify(slim));
}
- // Image rows get a thumbnail + Animate button; video rows keep
- // the existing 4-column shape so the layout doesn't shift.
- const isPhoto = (j.params && j.params.mode === 'image');
- if (isPhoto && j.status === 'done' && j.output_path) {
- const cands = (j.params.candidate_paths && j.params.candidate_paths.length)
- ? j.params.candidate_paths.length : 1;
- const engineLabel = escapeHtml(j.params.engine || 'image');
- // Reuse the server-built mtime-versioned URL when available
- // (currentOutputs has each entry's `&v=<mtime>` cache-bust),
- // falling back to a plain URL otherwise. Each job's output_path
- // is immutable post-completion, so no Date.now() bust is needed
- // — and it WAS the source of the carousel hot-loop: this list
- // re-renders every ~1s poll tick, so a `&t=${Date.now()}` on
- // every photo row caused ~16 thumbnail re-fetches per tick
- // (~50-60 req/s steady-state idle) that defeated the cache.
- const matchedOutput = (currentOutputs || []).find(x => x.path === j.output_path);
- const thumbSrc = matchedOutput
- ? matchedOutput.url
- : `/image?path=${encodeURIComponent(j.output_path)}`;
- const animateArgs = JSON.stringify({
- path: j.output_path, prompt: j.params.prompt || ''
- }).replace(/"/g, '&quot;');
- return `
- <li class="${j.status}" data-photo="1">
- <span class="badge">photo</span>
- <span class="ttl photo-ttl" title="${titleAttr}">
- <img class="photo-thumb" src="${thumbSrc}" alt=""
- style="width:36px;height:36px;object-fit:cover;border-radius:4px;vertical-align:middle;margin-right:6px">
- ${titleHtml}
- <span class="photo-meta hint" style="margin-left:6px;font-size:11px;opacity:0.7">${cands}× · ${engineLabel}</span>
- </span>
- <span class="params">${fmtMin(j.elapsed_sec)} · ${j.finished_at ? j.finished_at.slice(11) : ''}</span>
- <span><button class="animate-btn" type="button"
- onclick='animateFromPhoto(${animateArgs})' title="Pre-fill i2v with this image (does not auto-submit)">Animate</button></span>
- </li>`;
+ const r = await fetch('/queue/add', { method: 'POST', body: fd });
+ if (!r.ok) throw new Error(`HTTP ${r.status}`);
+ document.getElementById('imgStudioStatus').textContent =
+ 'Submitted. Watch Now / Recent → Photos.';
+ // Non-blocking toast — the user can stay focused on the form (e.g.
+ // queue a second variant) without reading the inline status line.
+ if (typeof phosToast === 'function') {
+ const n = body.n || 1;
+ phosToast(`Queued ${n} image${n === 1 ? '' : 's'} · watch Recent → Photos`,
+ { kind: 'success' });
}
- // Failed jobs get a Retry button in the action column. Clicking it
- // re-submits the same params via /queue/add so the user doesn't have
- // to rebuild the form. Cancelled jobs get the same treatment — a
- // cancellation often means "wrong intent, try again with edits" but
- // sometimes "ran out of RAM, want to retry as-is."
- const isRetryable = j.status === 'failed' || j.status === 'cancelled';
- const actionHtml = isRetryable
- ? `<button class="retry-btn" type="button"
- title="Re-submit this job with the same params"
- onclick='retryJob(${JSON.stringify(j.id)})'>Retry</button>`
- : '';
- return `
- <li class="${j.status}">
- <span class="badge">${j.status}</span>
- <span class="ttl" title="${titleAttr}">${titleHtml}</span>
- <span class="params">${fmtMin(j.elapsed_sec)} · ${j.finished_at ? j.finished_at.slice(11) : ''}</span>
- <span>${actionHtml}</span>
- </li>`;
- }).join('');
-
- // Outputs / carousel
- if (JSON.stringify(currentOutputs) !== JSON.stringify(s.outputs)) {
- currentOutputs = s.outputs;
- renderCarousel();
- // Pick the first FILTERED entry as the default selection so the
- // viewer agrees with what the gallery is showing — without this,
- // landing on Photos with no active selection would auto-pick a
- // video and fight the filter.
- if (!activePath) {
- const visible = filteredMainOutputs();
- if (visible.length) selectOutput(visible[0].path);
+ // Briefly flash the bottom-pane Now tab so the user's eye is drawn
+ // to where the live progress will appear. CSS handles the pulse;
+ // we just toggle a class for a second.
+ const nowTab = document.querySelector('.tabs button[data-tab="now"]');
+ if (nowTab) {
+ nowTab.classList.add('flash');
+ setTimeout(() => nowTab.classList.remove('flash'), 1200);
}
- // The Extend source dropdown is video-only — Extend mode operates on
- // mp4 input. Filter to videos so the user can't accidentally pick a
- // .png as an Extend source (which would 400 server-side).
- const sel = document.getElementById('extendSrcSelect');
- const videoOutputs = currentOutputs.filter(o => !isPhotoOutputMain(o));
- sel.innerHTML = '<option value="">— pick an output below or paste a path —</option>' +
- videoOutputs.slice(0, 40).map(o => `<option value="${escapeHtml(o.path)}">${escapeHtml(o.name)}</option>`).join('');
- }
- // (The old "Hidden (N)" pill that lived here was retired with the
- // Visible/Hidden segmented control — the carousel-head comment above
- // documents the removal. Setting textContent on the missing element
- // was firing a TypeError every poll cycle.)
- // Title: count is post-filter so the badge agrees with the rendered
- // cells. "Outputs · 23 photos" when Photos is active, plain "Outputs · N"
- // when All. Hidden override stays unchanged.
- const _visible = filteredMainOutputs();
- const _kindLabel = mainOutputsFilter === 'all' ? '' : ` ${mainOutputsFilter}`;
- document.getElementById('carouselTitle').textContent =
- filterMode === 'hidden' ? 'Hidden outputs'
- : `Outputs · ${_visible.length}${_kindLabel}`;
-
- // Train Character integration: detect newly-completed train jobs and
- // refresh both the trained-LoRA list AND the global LoRA picker so a
- // freshly-trained character appears in T2V/I2V's picker without a manual
- // reload. We watch history for entries with mode === 'train' that
- // weren't there last poll; cheap and survives the user being on any
- // tab/mode at the time training finishes.
- if (Array.isArray(s.history)) {
- const trainDoneCount = s.history.filter(h =>
- h && h.params && h.params.mode === 'train' && h.status === 'done'
- ).length;
- if (typeof window._lastTrainDoneCount === 'undefined') {
- window._lastTrainDoneCount = trainDoneCount;
- } else if (trainDoneCount > window._lastTrainDoneCount) {
- window._lastTrainDoneCount = trainDoneCount;
- // New train job(s) completed since last poll — re-sync everything.
- if (typeof refreshLoras === 'function') {
- try { refreshLoras(); } catch (e) {}
- }
- if (typeof trainRefreshLoraList === 'function') {
- try { trainRefreshLoraList(); } catch (e) {}
- }
+ // Recent uploads may now include the refs the user just touched, and
+ // the worker will start downloading weights for an uncached engine —
+ // refresh both so the next user click sees the fresh state.
+ if (typeof imgStudioRefreshRecent === 'function') imgStudioRefreshRecent();
+ setTimeout(() => {
+ if (typeof imgStudioRefreshEngineStatus === 'function') imgStudioRefreshEngineStatus();
+ }, 2000);
+ } catch (e) {
+ document.getElementById('imgStudioStatus').textContent = 'Submit failed: ' + e.message;
+ if (typeof phosToast === 'function') {
+ phosToast('Image submit failed: ' + (e.message || 'unknown'),
+ { kind: 'danger', duration: 5000 });
}
+ } finally {
+ IMG_STUDIO.busy = false;
+ document.getElementById('imgStudioGenBtn').disabled = false;
}
}
-// Balanced chip subtitle — kept in sync with current mode + frames so the
-// label tells the truth about which pipeline a click on Balanced will run.
-// Mirrors the server-side `balanced_q8_fast` rule in run_job_inner: Q8 Fast
-// only on standard tier with Q8 installed, mode ∈ {t2v, a2v}, frames ≤ 121.
-window.refreshBalancedSubtitle = function(state) {
- const sub = document.getElementById('balancedSub');
- if (!sub) return;
- const s = state || (window.__phosLastStatus || {});
- const tierKey = (s.tier && (s.tier.key || s.tier.tier)) || '';
- const q8Capable = !!s.q8_available && tierKey === 'standard';
- if (!q8Capable) {
- sub.textContent = 'Q4 · 5 min';
- return;
- }
- const framesEl = document.getElementById('frames');
- const frames = parseInt((framesEl && framesEl.value) || '121', 10);
- const mode = (typeof currentMode !== 'undefined') ? currentMode : 't2v';
- // T2V only — see Q8_FAST_OK_MODES on the server side.
- // I2V/a2v Q8 Fast caused identity drift on real content; reverted until
- // plan C (upscaled half-ref) or low_ram block streaming lands.
- const eligible = mode === 't2v' && frames <= 121;
- sub.textContent = eligible
- ? 'Q8 Fast · 6 min'
- : 'Q4 fallback';
-};
-document.addEventListener('DOMContentLoaded', function() {
- const framesEl = document.getElementById('frames');
- if (framesEl && !framesEl.__balancedSubWired) {
- framesEl.addEventListener('input', () => window.refreshBalancedSubtitle());
- framesEl.__balancedSubWired = true;
- }
- // Wrap setMode() if it exists, so mode flips also re-evaluate the label.
- if (typeof setMode === 'function' && !setMode.__balancedSubWired) {
- const _orig = setMode;
- window.setMode = function(m) {
- _orig(m);
- window.refreshBalancedSubtitle();
- };
- window.setMode.__balancedSubWired = true;
- }
-});
+// imgStudioRefreshLibrary used to populate the right-pane Studio
+// gallery. The unified Recent tab (commit 2) now covers that need —
+// the function is kept as a no-op so any setMode('image') call sites
+// that still reference it (defensive setMode plumbing) don't error.
+async function imgStudioRefreshLibrary() {
+ // intentionally empty: replaced by the unified Recent tab.
+ return;
+}
-// Recent-tab type filter (All / Videos / Photos). Stored on window so
-// the value survives across renders without polluting the existing
-// `filterMode` global (which is for the hidden/visible carousel filter,
-// a different concept). Defaults to 'all'.
-window.recentFilter = window.recentFilter || 'all';
-function setRecentFilter(mode) {
- window.recentFilter = mode;
- document.getElementById('recentFilterAll').classList.toggle('active', mode === 'all');
- document.getElementById('recentFilterVideos').classList.toggle('active', mode === 'videos');
- document.getElementById('recentFilterPhotos').classList.toggle('active', mode === 'photos');
- // Re-poll so the filter's effect is visible immediately. /status is
- // a localhost no-op, so the user perceives no latency.
- poll();
+function imgStudioCopyPath(path) {
+ if (!path) return;
+ const s = document.getElementById('imgStudioStatus');
+ const flash = (msg) => {
+ if (!s) return;
+ const prev = s.textContent;
+ s.textContent = msg;
+ setTimeout(() => { if (s.textContent === msg) s.textContent = prev; }, 1500);
+ };
+ // navigator.clipboard isn't available in non-secure contexts (HTTP origins
+ // other than localhost) and may reject if the page lacks focus. Fall back
+ // to the legacy execCommand path so the user still gets the path on their
+ // clipboard.
+ const legacy = () => {
+ try {
+ const ta = document.createElement('textarea');
+ ta.value = path;
+ ta.style.position = 'fixed';
+ ta.style.opacity = '0';
+ document.body.appendChild(ta);
+ ta.select();
+ const ok = document.execCommand('copy');
+ document.body.removeChild(ta);
+ flash(ok ? 'Path copied.' : 'Copy failed — select the path manually.');
+ } catch (e) {
+ flash('Copy failed: ' + (e.message || 'unknown'));
+ }
+ };
+ if (!navigator.clipboard || !navigator.clipboard.writeText) { legacy(); return; }
+ navigator.clipboard.writeText(path).then(() => flash('Path copied.')).catch(() => legacy());
}
-// Session-outputs (right-pane Agentic Flows gallery) filter — same
-// All / Videos / Photos chip language as the Recent tab, but persisted
-// across panel reloads via localStorage so picking "Photos" once
-// sticks. Photo discrimination uses params.mode === 'image' first, then
-// falls back to filename suffix for older sidecar-less entries.
-try {
- const stored = localStorage.getItem('phos_outputs_filter');
- if (stored === 'all' || stored === 'videos' || stored === 'photos') {
- window.outputsFilter = stored;
- }
-} catch (e) {}
-window.outputsFilter = window.outputsFilter || 'all';
-function setOutputsFilter(mode) {
- if (mode !== 'all' && mode !== 'videos' && mode !== 'photos') mode = 'all';
- window.outputsFilter = mode;
- try { localStorage.setItem('phos_outputs_filter', mode); } catch (e) {}
- const a = document.getElementById('outputsFilterAll');
- const v = document.getElementById('outputsFilterVideos');
- const p = document.getElementById('outputsFilterPhotos');
- if (a) a.classList.toggle('active', mode === 'all');
- if (v) v.classList.toggle('active', mode === 'videos');
- if (p) p.classList.toggle('active', mode === 'photos');
- // Re-render the stage outputs immediately so the gallery reflects
- // the new filter without waiting for the next status poll. The
- // status + session caches are kept on window so we can reuse them.
- if (typeof agentStageRender === 'function'
- && window.AGENT && window.AGENT.lastStatus) {
- agentStageRender(window.AGENT.lastStatus, window.AGENT.lastSession);
+// ====== Train Character pane ================================================
+// In-progress dataset state. The job_id is minted by the server on the FIRST
+// upload of a session and echoed back on every subsequent /train/upload so
+// the whole batch lands in one folder under state/train_character/<id>/.
+const TRAIN = {
+ jobId: null,
+ // Mirror of the server-side image list. Each: {filename, path, src}.
+ images: [],
+ preset: 'quick',
+ // Local mirror of the preset table; server has the authoritative copy in
+ // TRAIN_PRESETS but the JS-side estimator is instant — saves a /status
+ // round-trip per keystroke. Keep these in sync with TRAIN_PRESETS in py.
+ presets: {
+ quick: { steps: 1500, rank: 8, resolution: 512, seconds_per_step: 1.5, ram_peak_gb: 12,
+ label: 'Quick', subtitle: '~30 min · rank 8 · 512px' },
+ medium: { steps: 3000, rank: 16, resolution: 576, seconds_per_step: 2.2, ram_peak_gb: 18,
+ label: 'Medium', subtitle: '~2 h · rank 16 · 576px' },
+ high: { steps: 5000, rank: 32, resolution: 768, seconds_per_step: 3.0, ram_peak_gb: 28,
+ label: 'High', subtitle: '~4 h · rank 32 · 768px' },
+ },
+ initialised: false,
+};
+
+const TRAIN_MIN = 15;
+const TRAIN_MAX = 50;
+
+function trainInit() {
+ // Idempotent — safe to call on every setMode('train') without re-binding
+ // the drop zone. Triggers a list refresh too so the user sees the LoRAs
+ // they trained in earlier sessions.
+ if (!TRAIN.initialised) {
+ TRAIN.initialised = true;
+ trainWireDropZone();
+ trainWirePresetButtons();
+ trainWireAdvancedFields();
+ // Initial trigger value — JS-side generator (instant); /train/suggest-trigger
+ // exists for non-JS callers.
+ const t = document.getElementById('trainTrigger');
+ if (t && !t.value) t.value = trainGenerateTriggerJS();
+ document.getElementById('trainTriggerExample').textContent =
+ (document.getElementById('trainTrigger').value || 'mrz07');
+ document.getElementById('trainTrigger').addEventListener('input', () => {
+ document.getElementById('trainTriggerExample').textContent =
+ (document.getElementById('trainTrigger').value || 'mrz07');
+ trainUpdateButtonState();
+ trainUpdateEstimate();
+ });
}
+ trainRefreshLoraList();
+ trainUpdateEstimate();
+ trainUpdateButtonState();
+ trainCheckPreflight();
}
-// Apply the persisted filter on first paint so the chip styling
-// matches the live `window.outputsFilter` before the user clicks.
-document.addEventListener('DOMContentLoaded', () => {
- if (document.getElementById('outputsFilterAll')) {
- setOutputsFilter(window.outputsFilter || 'all');
- }
- // Same first-paint sync for the main right-pane chip strip — the
- // localStorage value was loaded into `mainOutputsFilter` at script
- // top, but the chip DOM hadn't been built yet, so the .active class
- // is still on All. Re-apply now that the strip exists.
- if (document.getElementById('mainOutputsFilterAll')) {
- _updateMainFilterChips();
+
+// Hits /train/preflight and surfaces a banner inside the Train form when a
+// required model is missing. Today the only on-demand download is the LTX-2.3
+// dev transformer (~11 GB) — Phosphene's default install ships the distilled
+// transformer only. Banner offers a one-click Download button that triggers
+// /train/install + redirects to /status for progress.
+async function trainCheckPreflight() {
+ const box = document.getElementById('trainPreflight');
+ if (!box) return;
+ try {
+ const r = await fetch('/train/preflight');
+ const data = await r.json();
+ if (!data || !data.ok) { box.style.display = 'none'; return; }
+ const missing = (data.required || []).filter(m => !m.ready);
+ if (missing.length === 0) {
+ box.style.display = 'none';
+ return;
+ }
+ box.style.display = 'block';
+ box.innerHTML = `
+ <div class="train-preflight-card">
+ <div class="train-preflight-title">
+ <svg class="ph" aria-hidden="true" style="margin-right:6px;vertical-align:-2px"><use href="#ph-warning-fill"/></svg>Required model${missing.length > 1 ? 's' : ''} not downloaded
+ </div>
+ <div class="train-preflight-list">
+ ${missing.map(m => `
+ <div class="train-preflight-row">
+ <div class="train-preflight-label">${m.label}
+ <span class="train-preflight-size">~${m.size_gb} GB</span></div>
+ <div class="train-preflight-blurb">${m.blurb}</div>
+ <button type="button" class="btn btn-primary"
+ onclick="trainInstall('${m.key}')">Download</button>
+ </div>
+ `).join('')}
+ </div>
+ <div class="train-preflight-foot">
+ Phosphene's default install ships only the inference model. The dev
+ transformer is needed for training and is downloaded on demand to
+ keep the base install lean.
+ </div>
+ </div>
+ `;
+ } catch (e) {
+ box.style.display = 'none';
}
-});
+}
-// Animate button — pre-fills the i2v form with the given still as the
-// reference image and the same prompt. Does NOT auto-submit; the user
-// keeps the chance to tweak prompt/seed/quality before clicking
-// Generate. Reversible (changing the image picker resets it).
-async function retryJob(jobId) {
- // Re-submit a failed/cancelled job by its id. Server side endpoint
- // /queue/retry takes the original job's id, copies its params verbatim
- // into a fresh queue entry, and returns the new id. Toast on success
- // (the Now/Queue pane will pick the new entry up on the next poll).
- if (!jobId) return;
+async function trainInstall(key) {
+ const fd = new FormData();
+ fd.set('key', key);
try {
- const fd = new URLSearchParams();
- fd.set('id', jobId);
- const r = await fetch('/queue/retry', { method: 'POST', body: fd });
- let data = {};
- try { data = await r.json(); } catch (e) { /* keep empty */ }
- if (!r.ok || !data.ok) {
- alert('Retry failed: ' + (data.error || ('HTTP ' + r.status)));
+ const r = await fetch('/train/install', { method: 'POST', body: fd });
+ const data = await r.json();
+ if (!data.ok) {
+ alert('Download failed: ' + (data.error || r.status));
return;
}
- // Force one immediate poll so the queue badge updates without the
- // 1.5s wait. poll() is idempotent.
- if (typeof poll === 'function') poll();
+ // Progress streams to STATUS log. Re-poll preflight every 5s; banner
+ // self-hides when the file lands.
+ const watch = setInterval(async () => {
+ try {
+ const r2 = await fetch('/train/preflight');
+ const d2 = await r2.json();
+ const stillMissing = (d2.required || []).filter(m => !m.ready).length;
+ if (stillMissing === 0) {
+ clearInterval(watch);
+ trainCheckPreflight();
+ }
+ } catch (e) { /* ignore */ }
+ }, 5000);
} catch (e) {
- alert('Retry error: ' + (e.message || 'unknown'));
+ alert('Download request failed: ' + e.message);
}
}
-// Re-run a previously-generated still through HiDream Quality (the
-// 12-step + light FBCache recipe). Reads the source's sidecar to pull
-// the original prompt + seed + refs, then drives the Image Studio form
-// (engine swapped to hidream_quality_inline, n=1) and submits to the
-// queue. Used from the photo card hover button.
-//
-// Why no manual confirmation step: Salo's intent is "pick best of 4
-// Fast/Medium previews → bake one at Quality" — adding a dialog would
-// burn a click for no information. The Image Studio form is left
-// pre-filled so the user can tweak + resubmit if they want.
-async function remakeInQuality(payload) {
- if (!payload || !payload.path) {
- if (typeof phosToast === 'function') {
- phosToast('Remake: missing path', { kind: 'danger' });
- }
- return;
- }
- // Pull the source's generation params from its sidecar JSON.
- let sidecar;
- try {
- const r = await fetch('/sidecar?path=' + encodeURIComponent(payload.path));
- if (!r.ok) throw new Error('no sidecar (older output?)');
- sidecar = await r.json();
- } catch (e) {
- if (typeof phosToast === 'function') {
- phosToast('Remake: ' + (e.message || 'failed to read sidecar'),
- { kind: 'danger' });
- }
+// Trigger generator — `<3 consonants><2 digits>` for rare/uncommon tokens.
+// Skip vowels + ambiguous letters (l, i, o → 1, 0). Mirrors the Python
+// _suggest_trigger_token; not a security boundary so the algorithms can
+// drift slightly — server has its own generator for non-JS callers.
+function trainGenerateTriggerJS() {
+ const cons = 'bcdfghjkmnpqrstvwxyz';
+ let letters = '';
+ for (let i = 0; i < 3; i++) letters += cons[Math.floor(Math.random() * cons.length)];
+ const digits = String(Math.floor(Math.random() * 100)).padStart(2, '0');
+ return letters + digits;
+}
+
+function trainSuggestTrigger() {
+ const t = document.getElementById('trainTrigger');
+ t.value = trainGenerateTriggerJS();
+ document.getElementById('trainTriggerExample').textContent = t.value;
+}
+
+function trainWireDropZone() {
+ const drop = document.getElementById('trainDrop');
+ const input = document.getElementById('trainFileInput');
+ if (!drop || !input) return;
+ drop.addEventListener('click', (e) => {
+ // Avoid re-firing the picker when the user clicks an existing thumb's
+ // controls (× / num pill).
+ if (e.target.closest('.train-thumb')) return;
+ input.click();
+ });
+ drop.addEventListener('dragover', (e) => {
+ e.preventDefault();
+ drop.classList.add('dragover');
+ });
+ drop.addEventListener('dragleave', () => drop.classList.remove('dragover'));
+ drop.addEventListener('drop', (e) => {
+ e.preventDefault();
+ drop.classList.remove('dragover');
+ const files = e.dataTransfer && e.dataTransfer.files;
+ if (files && files.length) trainUploadFiles(files);
+ });
+ input.addEventListener('change', () => {
+ if (input.files && input.files.length) trainUploadFiles(input.files);
+ input.value = '';
+ });
+}
+
+function trainWirePresetButtons() {
+ document.querySelectorAll('#trainPresetGroup .pill-btn').forEach(b => {
+ b.addEventListener('click', () => {
+ TRAIN.preset = b.dataset.trainPreset;
+ document.querySelectorAll('#trainPresetGroup .pill-btn').forEach(x =>
+ x.classList.toggle('active', x === b));
+ trainUpdateEstimate();
+ });
+ });
+}
+
+function trainWireAdvancedFields() {
+ ['trainRank', 'trainSteps', 'trainLR', 'trainResolution', 'trainCaptionStrategy']
+ .forEach(id => {
+ const el = document.getElementById(id);
+ if (el) el.addEventListener('change', trainUpdateEstimate);
+ if (el) el.addEventListener('input', trainUpdateEstimate);
+ });
+}
+
+async function trainUploadFiles(fileList) {
+ const status = document.getElementById('trainStatus');
+ const files = Array.from(fileList).filter(f =>
+ /^image\/(png|jpe?g|webp)$/.test(f.type) ||
+ /\.(png|jpe?g|webp)$/i.test(f.name));
+ if (!files.length) {
+ if (status) status.textContent = 'No supported image files in that selection.';
return;
}
- // Switch to Image Studio mode so the form is visible.
- if (typeof setMode === 'function') setMode('image');
-
- // Pre-fill the form. Prompt + seed + aspect carry over verbatim.
- // Refs go into the studio's 3-slot model.
- const promptEl = document.getElementById('imgStudioPrompt');
- if (promptEl) promptEl.value = sidecar.prompt || '';
- const seedEl = document.getElementById('imgStudioSeed');
- if (seedEl && sidecar.seed != null) seedEl.value = String(sidecar.seed);
- const nEl = document.getElementById('imgStudioN');
- if (nEl) nEl.value = '1'; // remake just the picked one
- const engineEl = document.getElementById('imgStudioEngine');
- if (engineEl) engineEl.value = 'hidream_quality_inline';
- const aspectEl = document.getElementById('imgStudioAspect');
- if (aspectEl && sidecar.aspect) aspectEl.value = sidecar.aspect;
+ if (status) status.textContent = `Uploading 0 / ${files.length}…`;
- // Refs — clear the 3 slots, then re-populate from sidecar.refs.
- if (typeof IMG_STUDIO !== 'undefined' && IMG_STUDIO.refs) {
- for (let i = 0; i < IMG_STUDIO.refs.length; i++) {
- IMG_STUDIO.refs[i] = null;
- if (typeof imgStudioRenderSlot === 'function') imgStudioRenderSlot(i);
+ // Optimistic UI: render placeholders for the incoming batch using
+ // FileReader to get a local data URL so the user sees the crop preview
+ // immediately. Each placeholder is replaced with the server-saved path
+ // once /train/upload returns.
+ for (let i = 0; i < files.length; i++) {
+ const f = files[i];
+ if (TRAIN.images.length >= TRAIN_MAX) {
+ if (status) status.textContent = `At max ${TRAIN_MAX} images. Stopping upload.`;
+ break;
}
- const refs = Array.isArray(sidecar.refs) ? sidecar.refs : [];
- refs.slice(0, IMG_STUDIO.refs.length).forEach((path, i) => {
- const fname = String(path).split('/').pop();
- IMG_STUDIO.refs[i] = { path, name: fname };
- if (typeof imgStudioRenderSlot === 'function') imgStudioRenderSlot(i);
+ const localUrl = await trainFileToDataURL(f).catch(() => null);
+ const placeholderIdx = TRAIN.images.length;
+ TRAIN.images.push({
+ filename: '__uploading__' + placeholderIdx,
+ path: '',
+ src: localUrl || '',
+ uploading: true,
});
+ trainRenderThumbs();
+
+ try {
+ const fd = new FormData();
+ fd.append('file', f, f.name);
+ if (TRAIN.jobId) fd.append('job_id', TRAIN.jobId);
+ const r = await fetch('/train/upload', { method: 'POST', body: fd });
+ const j = await r.json();
+ if (!r.ok || !j.ok) {
+ // Remove the placeholder; surface the error.
+ TRAIN.images.splice(placeholderIdx, 1);
+ if (status) status.textContent = 'Upload error: ' + (j.error || r.status);
+ trainRenderThumbs();
+ continue;
+ }
+ TRAIN.jobId = j.job_id;
+ TRAIN.images[placeholderIdx] = {
+ filename: j.filename,
+ path: j.path,
+ src: '/train/file?job_id=' + encodeURIComponent(j.job_id) +
+ '&filename=' + encodeURIComponent(j.filename) +
+ '&v=' + Date.now(),
+ uploading: false,
+ };
+ trainRenderThumbs();
+ if (status) status.textContent = `Uploaded ${i + 1} / ${files.length}…`;
+ } catch (e) {
+ TRAIN.images.splice(placeholderIdx, 1);
+ if (status) status.textContent = 'Upload failed: ' + (e.message || 'unknown');
+ trainRenderThumbs();
+ }
+ }
+ if (status) {
+ const n = TRAIN.images.length;
+ if (n < TRAIN_MIN) status.textContent = `${n} image${n === 1 ? '' : 's'} uploaded — need ${TRAIN_MIN - n} more to train.`;
+ else status.textContent = `${n} images ready — pick a preset and start training.`;
}
+ trainUpdateEstimate();
+ trainUpdateButtonState();
+}
- // Refresh validity + estimate UI so the Generate button enables.
- if (typeof imgStudioUpdateValidity === 'function') imgStudioUpdateValidity();
- if (typeof imgStudioUpdateEstimate === 'function') imgStudioUpdateEstimate();
- if (typeof imgStudioRefreshEngineStatus === 'function') imgStudioRefreshEngineStatus();
+function trainFileToDataURL(file) {
+ return new Promise((resolve, reject) => {
+ const r = new FileReader();
+ r.onload = () => resolve(r.result);
+ r.onerror = reject;
+ r.readAsDataURL(file);
+ });
+}
- // Auto-submit. imgStudioGenerate reads the now-prefilled fields.
- if (typeof imgStudioGenerate === 'function') {
- if (typeof phosToast === 'function') {
- phosToast('Remaking in Quality (12-step) · watch Recent → Photos',
- { kind: 'success' });
- }
- imgStudioGenerate();
+function trainRenderThumbs() {
+ const wrap = document.getElementById('trainThumbs');
+ const empty = document.getElementById('trainDropEmpty');
+ const drop = document.getElementById('trainDrop');
+ const clearAllBtn = document.getElementById('trainClearAllBtn');
+ if (!wrap) return;
+ if (TRAIN.images.length === 0) {
+ wrap.hidden = true;
+ if (empty) empty.style.display = '';
+ if (drop) drop.classList.remove('has-images');
+ if (clearAllBtn) clearAllBtn.hidden = true;
+ trainUpdateCounter();
+ return;
+ }
+ wrap.hidden = false;
+ if (empty) empty.style.display = 'none';
+ if (drop) drop.classList.add('has-images');
+ if (clearAllBtn) clearAllBtn.hidden = false;
+ wrap.innerHTML = TRAIN.images.map((img, idx) => {
+ const cls = 'train-thumb' + (img.uploading ? ' uploading' : '');
+ const removeAttr = img.uploading
+ ? ''
+ : `onclick="trainRemoveImage('${img.filename.replace(/'/g, "\\'")}')"`;
+ return `<div class="${cls}" data-idx="${idx}">
+ <img src="${img.src || ''}" alt="char ${idx + 1}" loading="lazy">
+ <span class="train-thumb-num">${String(idx + 1).padStart(3, '0')}</span>
+ <button type="button" class="train-thumb-x" ${removeAttr} title="Remove"><svg class="ph" aria-hidden="true"><use href="#ph-x-bold"/></svg></button>
+ </div>`;
+ }).join('');
+ trainUpdateCounter();
+}
+
+function trainUpdateCounter() {
+ const counter = document.getElementById('trainCounter');
+ const hint = document.getElementById('trainCounterHint');
+ if (!counter) return;
+ const n = TRAIN.images.length;
+ counter.textContent = `${n} / ${TRAIN_MAX} images`;
+ counter.classList.toggle('ok', n >= TRAIN_MIN);
+ counter.classList.toggle('short', n > 0 && n < TRAIN_MIN);
+ if (hint) {
+ if (n === 0) hint.textContent = `need at least ${TRAIN_MIN} to train`;
+ else if (n < TRAIN_MIN) hint.textContent = `need ${TRAIN_MIN - n} more`;
+ else if (n < TRAIN_MAX) hint.textContent = `ready · up to ${TRAIN_MAX - n} more if you want variety`;
+ else hint.textContent = `at the ${TRAIN_MAX}-image limit`;
}
}
-function animateFromPhoto(payload) {
- if (!payload || !payload.path) return;
- // Switch to i2v mode (pill + form fields). setMode('i2v') hides the
- // Studio pane, shows the video form, and applies the i2v-specific
- // dropdown selection.
- setMode('i2v');
- // Use the existing image picker helper so the preview tile updates
- // alongside the hidden form field. Pass snapAspect:false to keep
- // whatever aspect the user already had selected (matches loadParams).
- if (typeof pickerSetImage === 'function') {
- pickerSetImage('image', payload.path, { snapAspect: false });
- } else {
- document.getElementById('image').value = payload.path;
- }
- if (payload.prompt) {
- document.getElementById('prompt').value = payload.prompt;
+async function trainRemoveImage(filename) {
+ if (!TRAIN.jobId || !filename) return;
+ try {
+ const fd = new URLSearchParams();
+ fd.set('train_job_id', TRAIN.jobId);
+ fd.set('filename', filename);
+ const r = await fetch('/train/remove-image', { method: 'POST', body: fd });
+ const j = await r.json();
+ if (!r.ok || !j.ok) {
+ console.warn('remove-image failed', j);
+ return;
+ }
+ // Server renumbers char_001…NN; re-pull the canonical list so our
+ // src URLs match the new filenames on disk.
+ await trainRefreshDataset();
+ } catch (e) {
+ console.warn('remove-image error', e);
}
- // Scroll the form pane to the top so the image picker + prompt are
- // immediately visible.
- const formPane = document.querySelector('aside.form-pane');
- if (formPane) formPane.scrollTop = 0;
- if (typeof updateDerived === 'function') updateDerived();
- if (typeof updateCustomizeSummary === 'function') updateCustomizeSummary();
}
-// Format render duration for the gallery card sub-line. Falls back to
-// the time-of-day when the sidecar is missing (older outputs that
-// pre-date the elapsed_sec field, or outputs whose sidecar got
-// deleted) so the slot is never empty.
-function _outputDurationLabel(o) {
- const s = (o && typeof o.elapsed_sec === 'number') ? o.elapsed_sec : null;
- if (s == null) {
- // Fallback: show time-of-day from mtime so empty cards aren't worse.
- return o.mtime ? o.mtime.slice(11, 16) : '—';
+async function trainClearAll() {
+ if (!TRAIN.images.length) return;
+ if (!confirm(`Remove all ${TRAIN.images.length} uploaded images?`)) return;
+ const toRemove = TRAIN.images.filter(x => !x.uploading).map(x => x.filename);
+ for (const f of toRemove) {
+ await trainRemoveImage(f);
}
- if (s < 60) return `${Math.round(s)} s`;
- if (s < 3600) return `${Math.floor(s / 60)} m ${Math.round(s % 60)} s`;
- return `${Math.floor(s / 3600)} h ${Math.round((s % 3600) / 60)} m`;
+ TRAIN.images = [];
+ trainRenderThumbs();
+ trainUpdateEstimate();
+ trainUpdateButtonState();
}
-function renderCarousel() {
- const el = document.getElementById('carousel');
- const visible = filteredMainOutputs();
- if (!visible.length) {
- const msg = mainOutputsFilter === 'photos' ? 'No photo outputs yet.'
- : mainOutputsFilter === 'videos' ? 'No video outputs yet.'
- : 'No outputs in this view yet.';
- el.innerHTML = `<div class="empty-msg">${msg}</div>`;
+async function trainRefreshDataset() {
+ if (!TRAIN.jobId) {
+ TRAIN.images = [];
+ trainRenderThumbs();
return;
}
- el.innerHTML = visible.map(o => {
- const pathAttr = JSON.stringify(o.path).replace(/"/g, '&quot;');
- const isPhoto = isPhotoOutputMain(o);
- // Thumbnail markup branches on kind. Videos use <video> with a
- // mid-clip seek (2.5s — LTX clips are 5s at 24fps and the first
- // half-second is often a dark fade-in, so seeking to the middle
- // gets a representative frame). Photos use <img> directly with
- // the same /image?path=… cache-bust URL the server stamped.
- const thumbHtml = isPhoto
- ? `<img class="car-thumb" src="${o.url}" alt="${escapeHtml(o.name)}" loading="lazy">`
- // Hover-scrub: on enter, jump to 0 and play silently at 0.6×;
- // on leave, pause + snap back to the static 2.5s preview frame.
- // The play() promise can reject during a fast scrub (browser
- // says "play interrupted by pause") — swallow it.
- : `<video src="${o.url}#t=2.5" preload="metadata" muted playsinline
- onmouseenter="this.currentTime=0; this.playbackRate=0.6; this.play().catch(()=>{})"
- onmouseleave="this.pause(); this.currentTime=2.5; this.playbackRate=1"></video>`;
- // Per-card actions (revealed on hover) — kept deliberately minimal:
- // * Photos get a small "Animate" chip (turns the still into i2v).
- // * Everything gets a delete (×) chip.
- // The previous Hide + Extend buttons were dropped per Salo:
- // - Hide was useless (clutter, never used in practice).
- // - Extend wasn't practical on Mac.
- // Folder-reveal moved to a global button in the carousel header.
- const animateArgs = JSON.stringify({path: o.path, prompt: ''}).replace(/"/g, '&quot;');
- const animateChip = isPhoto
- ? `<button class="card-action card-action-photo" type="button"
- title="Pre-fill i2v with this image (does not auto-submit)"
- onclick="event.stopPropagation(); animateFromPhoto(${animateArgs})">Animate</button>`
- : '';
- // Remake-in-Quality chip — only on photos that have a sidecar (we need the
- // original prompt + seed + refs to re-run). Pre-fills the Image Studio
- // form with the source's exact params, swaps the engine to
- // hidream_quality_inline, sets n=1, and auto-submits. Useful flow:
- // generate 4 candidates in Fast/Medium, pick the best, hit ✦ to bake the
- // same composition at Quality fidelity.
- const remakeArgs = JSON.stringify({path: o.path}).replace(/"/g, '&quot;');
- const remakeChip = (isPhoto && o.has_sidecar)
- ? `<button class="card-action card-action-photo" type="button"
- title="Re-run this prompt + seed + refs through HiDream Quality (auto-submits)"
- onclick="event.stopPropagation(); remakeInQuality(${remakeArgs})">✦ Quality</button>`
- : '';
- return `
- <div class="car-card${o.path === activePath ? ' active' : ''}"
- data-path="${escapeHtml(o.path)}" onclick="selectOutput(${pathAttr})">
- <div class="car-thumb-wrap">
- ${thumbHtml}
- ${o.has_sidecar
- ? `<button class="car-info-btn" type="button" title="Show generation info"
- onclick="event.stopPropagation(); openOutputInfoModal(${pathAttr})"><svg class="ph" aria-hidden="true"><use href="#ph-info"/></svg></button>`
- : ''}
- <div class="card-chrome">
- ${remakeChip}
- ${animateChip}
- <button class="card-action card-action-danger" type="button" title="Delete this file from disk"
- onclick="event.stopPropagation(); deleteOutput(${pathAttr})"><svg class="ph" aria-hidden="true"><use href="#ph-trash-simple"/></svg></button>
- </div>
- </div>
- <div class="info">
- <div class="name" title="${escapeHtml(o.name)}">${escapeHtml(o.name)}</div>
- <div class="sub" title="Render time · file size">
- ${_outputDurationLabel(o)} · ${o.size_mb.toFixed(1)} MB
- </div>
- </div>
- </div>`;
- }).join('');
+ try {
+ const r = await fetch('/train/dataset?job_id=' + encodeURIComponent(TRAIN.jobId));
+ const j = await r.json();
+ if (!j.ok) return;
+ TRAIN.images = (j.images || []).map(im => ({
+ filename: im.filename,
+ path: im.path,
+ src: '/train/file?job_id=' + encodeURIComponent(TRAIN.jobId) +
+ '&filename=' + encodeURIComponent(im.filename) + '&v=' + Date.now(),
+ uploading: false,
+ }));
+ trainRenderThumbs();
+ trainUpdateEstimate();
+ trainUpdateButtonState();
+ } catch (e) { console.warn('train dataset refresh failed', e); }
}
-// Relative-time helper for the player overlay meta line. Takes the
-// server's "YYYY-MM-DD HH:MM:SS" mtime string and returns a humanlike
-// "2 min ago" / "3 h ago" / "yesterday" so the meta strip carries
-// recency info without forcing the user to do date math.
-function _relTimeFromMtime(mtime) {
- if (!mtime) return '';
- // Treat the server timestamp as local time (it's the panel host's
- // wall clock). Date parses "YYYY-MM-DD HH:MM:SS" inconsistently
- // across browsers, so re-format to ISO-with-T which all engines
- // accept as local.
- const iso = String(mtime).replace(' ', 'T');
- const t = new Date(iso).getTime();
- if (!isFinite(t)) return mtime;
- const sec = Math.max(0, Math.round((Date.now() - t) / 1000));
- if (sec < 45) return 'just now';
- if (sec < 90) return '1 min ago';
- if (sec < 3600) return Math.round(sec / 60) + ' min ago';
- if (sec < 5400) return '1 h ago';
- if (sec < 86400) return Math.round(sec / 3600) + ' h ago';
- if (sec < 172800) return 'yesterday';
- return Math.round(sec / 86400) + ' d ago';
+function trainEffectiveSteps() {
+ const v = (document.getElementById('trainSteps').value || '').trim();
+ if (!v) return null;
+ const n = parseInt(v, 10);
+ return Number.isFinite(n) && n > 0 ? n : null;
}
-function selectOutput(path) {
- activePath = path;
- document.querySelectorAll('.car-card').forEach(el => el.classList.toggle('active', el.dataset.path === path));
- const wrap = document.getElementById('playerWrap');
- wrap.classList.remove('empty');
- // Y1.039 — use the server-provided URL (which includes the mtime
- // cache-bust v=N param) instead of reconstructing from path. Otherwise
- // the player ends up on the cached stale-bytes URL and re-shows black
- // until the browser cache expires.
- const o = currentOutputs.find(x => x.path === path);
- const isPhoto = isPhotoOutputMain(o);
- // Photo entries don't go through /file (which is OUTPUT-bound and
- // serves video with Range headers). Use /image which supports both
- // OUTPUT and UPLOADS roots, with the right MIME headers. Server-side
- // list_outputs() already builds the right URL per kind, so o.url
- // is correct for both — the fallback path below only runs when an
- // unknown path is requested (e.g. clicked from a stale modal link).
- let playerSrc;
- if (o) {
- playerSrc = o.url;
- } else if (isPhoto) {
- playerSrc = `/image?path=${encodeURIComponent(path)}`;
- } else {
- playerSrc = `/file?path=${encodeURIComponent(path)}`;
- }
- // Photo viewer is a static <img> — no controls, no autoplay (would
- // be a no-op on an image element anyway). Video viewer keeps the
- // existing controls + autoplay behaviour.
- wrap.innerHTML = isPhoto
- ? `<img src="${playerSrc}" alt="${o ? escapeHtml(o.name) : ''}">`
- : `<video controls autoplay src="${playerSrc}"></video>`;
-
- // Y2.001 — populate the new overlays. The legacy #playerName / #playerMeta
- // are kept hidden but the writes still happen so any test/external code
- // reading them gets the same data.
- document.getElementById('playerMeta').style.display = '';
- const legacyMetaText = o
- ? `${o.name} · ${o.mtime} · ${o.size_mb.toFixed(1)} MB`
- : '';
- document.getElementById('playerName').textContent = legacyMetaText;
- // Visible top overlay — title + meta line with relative time.
- const overlayTop = document.getElementById('playerOverlayTop');
- const overlayActions = document.getElementById('playerOverlayActions');
- if (overlayTop) {
- overlayTop.style.display = '';
- document.getElementById('playerOverlayName').textContent = o ? o.name : '';
- const rel = o ? _relTimeFromMtime(o.mtime) : '';
- const sizeLbl = o ? `${o.size_mb.toFixed(1)} MB` : '';
- const kindLbl = isPhoto ? 'Photo' : 'Video';
- document.getElementById('playerOverlayMeta').innerHTML = o
- ? `<span>${kindLbl}</span><span class="po-dot"></span>` +
- `<span>${escapeHtml(rel)}</span><span class="po-dot"></span>` +
- `<span>${sizeLbl}</span>`
- : '';
+function trainUpdateEstimate() {
+ const preset = TRAIN.presets[TRAIN.preset] || TRAIN.presets.quick;
+ const stepOverride = trainEffectiveSteps();
+ const steps = stepOverride || preset.steps;
+ const n = TRAIN.images.length;
+ const sec = Math.round(3 * Math.max(0, n) + steps * preset.seconds_per_step + 30);
+ // Estimate row is hidden until the user has dropped at least one
+ // image. Before that, the row reads as missing data — not a useful
+ // signal. Once there's data, reveal the row + populate it.
+ const row = document.getElementById('trainEstimate');
+ if (row) row.style.display = n === 0 ? 'none' : '';
+ const ramRow = document.getElementById('trainEstimateRam');
+ const timeRow = document.getElementById('trainEstimateTime');
+ const outRow = document.getElementById('trainEstimateOut');
+ if (timeRow && n > 0) timeRow.textContent = trainFmtDuration(sec) + ` · ${steps} steps`;
+ if (ramRow) ramRow.textContent = `~${preset.ram_peak_gb} GB peak`;
+ if (outRow) {
+ const trig = (document.getElementById('trainTrigger').value || 'mrz07');
+ outRow.textContent = `mlx_models/loras/${(TRAIN.jobId || 'trn-<new>')}.safetensors · trigger "${trig}"`;
}
- if (overlayActions) overlayActions.style.display = '';
+}
- // Load params is video-only — image sidecars use the library@1 schema
- // which doesn't carry the i2v/t2v form fields the loader expects.
- document.getElementById('loadParamsBtn').disabled = !(o && o.has_sidecar) || isPhoto;
- // Action button row: swap "Use as Extend" for "Animate" on photo
- // entries (Extend is video-only, but the still can be the seed for
- // an i2v render).
- const useExtBtn = document.getElementById('useAsExtendBtn');
- const animBtn = document.getElementById('animateBtn');
- if (useExtBtn) useExtBtn.style.display = isPhoto ? 'none' : '';
- if (animBtn) animBtn.style.display = isPhoto ? '' : 'none';
+function trainFmtDuration(sec) {
+ if (sec < 60) return `${sec} s`;
+ const m = Math.round(sec / 60);
+ if (m < 60) return `${m} min`;
+ const h = Math.floor(m / 60);
+ const rem = m % 60;
+ return rem ? `${h} h ${rem} min` : `${h} h`;
}
-// Expand lightbox — full-viewport viewer for the active output. Reuses
-// the active entry's URL / kind detection so a single button works for
-// both image and video. Closed by Esc, backdrop click, or the × button.
-function openExpandLightbox() {
- if (!activePath) return;
- const o = currentOutputs.find(x => x.path === activePath);
- if (!o) return;
- const lb = document.getElementById('expandLightbox');
- const stage = document.getElementById('expandStage');
- const meta = document.getElementById('expandMeta');
- if (!lb || !stage) return;
- const isPhoto = isPhotoOutputMain(o);
- // Build the media element fresh each time so the previous selection's
- // <video> stops decoding immediately.
- stage.innerHTML = isPhoto
- ? `<img src="${o.url}" alt="${escapeHtml(o.name)}">`
- : `<video src="${o.url}" controls autoplay></video>`;
- if (meta) {
- const sizeLbl = `${o.size_mb.toFixed(1)} MB`;
- meta.textContent = `${o.name} · ${sizeLbl}`;
+function trainUpdateButtonState() {
+ const btn = document.getElementById('trainStartBtn');
+ if (!btn) return;
+ const n = TRAIN.images.filter(x => !x.uploading).length;
+ const trig = (document.getElementById('trainTrigger').value || '').trim();
+ const ok = n >= TRAIN_MIN && trig.length >= 3 && trig.length <= 32;
+ btn.disabled = !ok;
+ if (!ok) {
+ if (n < TRAIN_MIN) btn.title = `Need at least ${TRAIN_MIN} images (have ${n}).`;
+ else if (trig.length < 3) btn.title = 'Trigger word must be 3+ characters.';
+ else btn.title = 'Trigger word is too long (max 32).';
+ } else {
+ btn.title = 'Queue this training job.';
}
- lb.style.display = 'flex';
}
-function closeExpandLightbox() {
- const lb = document.getElementById('expandLightbox');
- const stage = document.getElementById('expandStage');
- if (!lb) return;
- if (stage) stage.innerHTML = ''; // stops video playback
- lb.style.display = 'none';
-}
+async function trainStart() {
+ const btn = document.getElementById('trainStartBtn');
+ const status = document.getElementById('trainStatus');
+ if (!TRAIN.jobId || TRAIN.images.length < TRAIN_MIN) {
+ if (status) status.textContent = `Need at least ${TRAIN_MIN} images.`;
+ return;
+ }
+ const trig = (document.getElementById('trainTrigger').value || '').trim();
+ if (!trig) {
+ if (status) status.textContent = 'Trigger word required.';
+ return;
+ }
+ const fd = new URLSearchParams();
+ fd.set('train_job_id', TRAIN.jobId);
+ fd.set('trigger', trig);
+ fd.set('preset', TRAIN.preset);
+ fd.set('image_count', String(TRAIN.images.length));
+ fd.set('caption_strategy', document.getElementById('trainCaptionStrategy').value || 'trigger_simple');
+ const rank = document.getElementById('trainRank').value;
+ if (rank) fd.set('rank', rank);
+ const stepsVal = document.getElementById('trainSteps').value;
+ if (stepsVal) fd.set('steps', stepsVal);
+ const lrVal = document.getElementById('trainLR').value;
+ if (lrVal) fd.set('lr', lrVal);
+ const resVal = document.getElementById('trainResolution').value;
+ if (resVal) fd.set('resolution', resVal);
-// Esc + F shortcuts for the expand lightbox. Bound once at module init.
-(function _wireExpandLightboxKeys() {
- document.addEventListener('keydown', (e) => {
- const lb = document.getElementById('expandLightbox');
- if (!lb) return;
- const isOpen = lb.style.display === 'flex';
- // Don't steal keystrokes from inputs/textareas.
- const tag = (e.target && e.target.tagName) || '';
- const inField = tag === 'INPUT' || tag === 'TEXTAREA' || (e.target && e.target.isContentEditable);
- if (e.key === 'Escape' && isOpen) {
- closeExpandLightbox();
- e.preventDefault();
- } else if ((e.key === 'f' || e.key === 'F') && !isOpen && !inField && activePath) {
- openExpandLightbox();
- e.preventDefault();
- } else if ((e.key === 'ArrowLeft' || e.key === 'ArrowRight') && !inField && activePath
- && typeof filteredMainOutputs === 'function') {
- // Carousel keyboard nav. Wraps at the edges so power users can
- // scrub through the whole gallery without lifting hands off the
- // keyboard. Works whether the lightbox is open or not — if it
- // IS open, the lightbox content updates with the new selection.
- const list = filteredMainOutputs();
- if (!list.length) return;
- const idx = list.findIndex(o => o.path === activePath);
- const nextIdx = e.key === 'ArrowLeft'
- ? (idx <= 0 ? list.length - 1 : idx - 1)
- : (idx < 0 || idx >= list.length - 1 ? 0 : idx + 1);
- const next = list[nextIdx];
- if (next && typeof selectOutput === 'function') {
- selectOutput(next.path);
- if (isOpen) openExpandLightbox(); // re-bind media to new pick
- }
- e.preventDefault();
+ if (btn) { btn.disabled = true; btn.textContent = 'Submitting…'; }
+ try {
+ const r = await fetch('/train/start', { method: 'POST', body: fd });
+ const j = await r.json();
+ if (!r.ok || !j.ok) {
+ if (status) status.textContent = 'Failed to enqueue: ' + (j.error || r.status);
+ if (btn) { btn.disabled = false; btn.textContent = 'Start training'; }
+ return;
}
- });
-})();
-
-// Toast helper — non-blocking confirmation pattern, stacks at the
-// bottom-center of the viewport. Use for delete confirmation, "moved
-// to Trash" feedback, save success, etc. Auto-dismisses after
-// `duration` ms (default 3 s). Pass `kind: "success" | "danger"` to
-// tint the border + icon.
-function phosToast(message, opts) {
- opts = opts || {};
- const c = document.getElementById('phosToast');
- if (!c) return null;
- const el = document.createElement('div');
- el.className = 'phos-toast';
- if (opts.kind === 'success' || opts.kind === 'danger') {
- el.classList.add('phos-toast-' + opts.kind);
+ if (status) status.textContent = `Queued · job ${j.queued_id}. Watch the Now / Queue pane for progress.`;
+ // Reset the form so the user can stage another dataset. The current
+ // job's files stay on disk — only our local mirror is cleared.
+ TRAIN.jobId = null;
+ TRAIN.images = [];
+ trainRenderThumbs();
+ trainUpdateEstimate();
+ if (btn) btn.textContent = 'Start training';
+ // Refresh queue poll immediately so the new job card appears without
+ // waiting for the next 1.5s tick.
+ if (typeof poll === 'function') poll();
+ } catch (e) {
+ if (status) status.textContent = 'Enqueue failed: ' + (e.message || 'unknown');
+ if (btn) { btn.disabled = false; btn.textContent = 'Start training'; }
}
- const icon = opts.icon
- || (opts.kind === 'success' ? 'ph-check-bold'
- : opts.kind === 'danger' ? 'ph-x-circle'
- : 'ph-info');
- el.innerHTML =
- `<svg class="ph" aria-hidden="true"><use href="#${icon}"/></svg>` +
- `<span class="phos-toast-msg"></span>`;
- el.querySelector('.phos-toast-msg').textContent = String(message);
- c.appendChild(el);
- const duration = (opts.duration === 0) ? 0 : (opts.duration || 3000);
- if (duration > 0) {
- setTimeout(() => {
- if (!el.isConnected) return;
- el.classList.add('is-leaving');
- el.addEventListener('animationend', () => el.remove(), { once: true });
- }, duration);
+}
+
+async function trainRefreshLoraList() {
+ const list = document.getElementById('trainLoraList');
+ if (!list) return;
+ // Keep the global picker in sync. /loras scans the same directory but
+ // also rebuilds _knownUserLoras + drops stale entries from _activeLoras.
+ // Cheap (one fs scan) and harmless if it races with a render. Letting
+ // it run unconditionally so a freshly-trained LoRA appears in T2V's
+ // picker the moment the trained list updates — no manual refresh.
+ try { if (typeof refreshLoras === 'function') refreshLoras(); } catch (e) {}
+ try {
+ const r = await fetch('/train/list');
+ const j = await r.json();
+ const items = (j.loras || []);
+ if (!items.length) {
+ list.innerHTML = '<div class="hint" style="padding:12px 0">No trained LoRAs yet. Start your first run above.</div>';
+ return;
+ }
+ list.innerHTML = items.map(it => {
+ const ageMs = Date.now() - (Number(it.created_at) || 0) * 1000;
+ const ageStr = trainFmtAge(ageMs);
+ const safeTrig = (it.trigger || '').replace(/[<>&"']/g, c =>
+ ({'<':'&lt;','>':'&gt;','&':'&amp;','"':'&quot;',"'":'&#39;'})[c]);
+ const safePath = (it.path || '').replace(/'/g, "\\'");
+ return `<div class="train-lora-row">
+ <span class="tl-name" title="${it.filename}">${it.name || it.filename}
+ <span class="tl-trigger"> · "${safeTrig}"</span>
+ <span class="tl-size"> · ${it.size_mb} MB · ${ageStr}</span>
+ </span>
+ <span class="tl-actions">
+ <button type="button" class="qchip" onclick="trainUseInVideo('${safePath}','${safeTrig}','t2v')">Use in T2V</button>
+ <button type="button" class="qchip" onclick="trainUseInVideo('${safePath}','${safeTrig}','i2v')">Use in I2V</button>
+ <button type="button" class="qchip" onclick="trainCopyTriggerCmd('${safeTrig}')">Copy trigger</button>
+ <button type="button" class="qchip" onclick="trainDeleteLora('${safePath}')" title="Delete .safetensors + sidecar"><svg class="ph" aria-hidden="true"><use href="#ph-trash-simple"/></svg></button>
+ </span>
+ </div>`;
+ }).join('');
+ } catch (e) {
+ list.innerHTML = '<div class="hint">Load failed: ' + (e.message || 'unknown') + '</div>';
}
- return el;
}
-// Animate the active output (photo only). Mirrors animateFromPhoto's
-// shape — pre-fills the i2v form from the active entry's path and the
-// sidecar's prompt if there is one. Sidecar fetch is best-effort; if it
-// fails (or there isn't one), we still animate with an empty prompt so
-// the user can type their own.
-async function animateActive() {
- if (!activePath) return;
- const o = currentOutputs.find(x => x.path === activePath);
- let prompt = '';
- if (o && o.has_sidecar) {
- try {
- const r = await fetch('/sidecar?path=' + encodeURIComponent(activePath));
- if (r.ok) {
- const data = await r.json();
- // Image sidecars use schema "phosphene/library/image@1" with
- // a top-level `prompt`; video sidecars nest it under `params`.
- // Cover both shapes so the UI works regardless of source.
- prompt = (data && (data.prompt || (data.params && data.params.prompt))) || '';
- }
- } catch (e) {}
+function trainFmtAge(ms) {
+ if (!Number.isFinite(ms) || ms < 0) return 'just now';
+ const s = Math.floor(ms / 1000);
+ if (s < 60) return `${s}s ago`;
+ const m = Math.floor(s / 60);
+ if (m < 60) return `${m}m ago`;
+ const h = Math.floor(m / 60);
+ if (h < 24) return `${h}h ago`;
+ const d = Math.floor(h / 24);
+ return `${d}d ago`;
+}
+
+function trainUseInVideo(loraPath, trigger, targetMode) {
+ // Switch the panel into the requested video mode + pre-fill the LoRA
+ // picker by emitting an "add" against the unified picker's state. The
+ // picker's _activeLoras list is what the form serialises into the
+ // hidden #lorasJson input on submit. Falls back to copying the path
+ // to clipboard if the picker hooks aren't present.
+ try { setMode(targetMode); } catch (e) {}
+ // Pre-fill the prompt textarea with the trigger word as a starter so
+ // the user sees how it's used.
+ const prompt = document.getElementById('prompt');
+ if (prompt && !prompt.value) {
+ prompt.value = `${trigger} man, cinematic medium shot, soft natural light`;
}
- if (typeof animateFromPhoto === 'function') {
- animateFromPhoto({path: activePath, prompt: prompt});
+ // Use the existing picker plumbing if available. _activeLoras and
+ // renderLorasList come from the unified LoRA picker module.
+ if (typeof window._activeLoras !== 'undefined' && Array.isArray(window._activeLoras)) {
+ const already = window._activeLoras.some(x => x.path === loraPath);
+ if (!already) {
+ window._activeLoras.push({ path: loraPath, strength: 1.0, name: loraPath.split('/').pop() });
+ if (typeof renderLorasList === 'function') renderLorasList();
+ if (typeof _syncLorasJsonField === 'function') _syncLorasJsonField();
+ }
+ } else {
+ // Fall back: copy the path so the user can paste it into the LoRA
+ // picker manually.
+ if (typeof imgStudioCopyPath === 'function') imgStudioCopyPath(loraPath);
}
}
-async function hide(path) { await fetch('/output/hide?path='+encodeURIComponent(path),{method:'POST'}); currentOutputs = []; poll(); }
-async function unhide(path) { await fetch('/output/show?path='+encodeURIComponent(path),{method:'POST'}); currentOutputs = []; poll(); }
+function trainCopyTriggerCmd(trigger) {
+ if (!trigger) return;
+ const text = `${trigger} man, cinematic medium shot, soft natural light`;
+ if (typeof imgStudioCopyPath === 'function') imgStudioCopyPath(text);
+}
-async function deleteOutput(path) {
- // Per-card × button. Moves the media (and any sibling sidecar JSON)
- // to the macOS Trash via /output/delete — files are recoverable
- // from Finder Trash via Cmd-Z right after, or by dragging them out
- // of the Trash bin later. Toast confirms the move; if the user was
- // viewing this clip in the expand lightbox, that closes too.
- if (!path) return;
- const base = path.split('/').pop();
- if (!confirm('Move to Trash?\n\n' + base + '\n\nRestore from Finder if needed.')) return;
+async function trainDeleteLora(loraPath) {
+ if (!loraPath) return;
+ if (!confirm('Delete this LoRA?\n\n' + loraPath)) return;
try {
const fd = new URLSearchParams();
- fd.set('path', path);
- const r = await fetch('/output/delete', { method: 'POST', body: fd });
- const data = await r.json().catch(() => ({}));
- if (!r.ok || !data.ok) {
- phosToast('Delete failed: ' + (data.error || ('HTTP ' + r.status)),
- { kind: 'danger', duration: 5000 });
+ fd.set('path', loraPath);
+ const r = await fetch('/train/delete', { method: 'POST', body: fd });
+ const j = await r.json();
+ if (!r.ok || !j.ok) {
+ alert('Delete failed: ' + (j.error || r.status));
return;
}
- // If the deleted clip was open in the expand lightbox, close it —
- // otherwise the lightbox sits there pointing at a 404 URL.
- if (activePath === path) {
- activePath = null;
- const lb = document.getElementById('expandLightbox');
- if (lb && lb.style.display === 'flex' && typeof closeExpandLightbox === 'function') {
- closeExpandLightbox();
- }
- }
- currentOutputs = [];
- poll();
- phosToast('Moved to Trash · ' + base, { kind: 'success' });
+ trainRefreshLoraList();
} catch (e) {
- phosToast('Delete error: ' + (e.message || 'unknown'),
- { kind: 'danger', duration: 5000 });
+ alert('Delete error: ' + (e.message || 'unknown'));
}
}
-async function openOutputsFolder() {
- // One-click Reveal in Finder. Global, lives in the Outputs header so
- // it isn't duplicated per-card. macOS `open <dir>` — Phosphene is
- // Apple Silicon-only, no cross-platform branch.
- try {
- const r = await fetch('/output/open_folder', { method: 'POST' });
- const data = await r.json().catch(() => ({}));
- if (!r.ok || !data.ok) {
- alert('Open folder failed: ' + (data.error || ('HTTP ' + r.status)));
- }
- } catch (e) {
- alert('Open folder error: ' + (e.message || 'unknown'));
- }
-}
-function hideActive() { if (activePath) hide(activePath); }
+// Quality presets (Y1.013) — each one bundles the backend quality value
+// (which selects the model + sampler) with the canonical dimensions.
+// Backend still routes only on `quality == 'high'` vs anything else, so
+ // 'quick', 'balanced', and 'standard' all run Q4 distilled — they differ in
+// pixel count. The richer label is preserved in the sidecar so the
+// info modal can show "Quick" / "Standard" / "High" verbatim.
+const QUALITY_PRESETS = {
+ quick: { w: 640, h: 480, upscale: 'off' }, // 4:3, fastest sanity check
+ balanced: { w: 1024, h: 576, upscale: 'fit_720p' }, // exact 16:9 → 1280×720
+ standard: { w: 1280, h: 704, upscale: 'off' }, // LTX-wide canonical render
+ // High = Q8 quality at 1024×576. Lab finding 2026-05-09: at 1024×576
+ // Q8 produces "outstanding" output at ~7:48 wall vs ~11:51 at
+ // 1280×704 — Q8's quality differentiator is per-token detail
+ // capacity, not raw pixels. User can still pick 1280×704 explicitly
+ // via the resolution chip; this preset just sets the saner default.
+ high: { w: 1024, h: 576, upscale: 'off' },
+};
-function useAsExtendSourcePath(path) {
- setMode('extend');
- document.getElementById('video_path').value = path;
- document.getElementById('extendSrcSelect').value = path;
+function setQuality(q) {
+ // Tolerate legacy values from old sidecars: 'draft' → 'standard'.
+ if (q === 'draft' || !QUALITY_PRESETS[q]) q = 'standard';
+ document.getElementById('quality').value = q;
+ document.querySelectorAll('#qualityGroup .pill-btn').forEach(b => b.classList.toggle('active', b.dataset.quality === q));
+ // Set canonical dimensions for the preset, respecting the current
+ // aspect choice. Quick is 4:3 only — landscape orientation only.
+ const preset = QUALITY_PRESETS[q];
+ const aspect = document.getElementById('aspect').value || 'landscape';
+ const vertical = (aspect === 'vertical' && q !== 'quick');
+ document.getElementById('width').value = vertical ? preset.h : preset.w;
+ document.getElementById('height').value = vertical ? preset.w : preset.h;
+ setUpscale(preset.upscale || 'off');
+ // Hide the Aspect row when Quick is active (only 4:3 supported); show
+ // it for Standard/High where 16:9 vs 9:16 is a real choice.
+ const aspectRow = document.getElementById('aspectRow');
+ if (aspectRow) aspectRow.style.display = (q === 'quick') ? 'none' : '';
+ applyQuality();
+ updateAccelAvailability();
+ updateTemporalAvailability();
+ updateCustomizeSummary();
+ if (LAST_STATUS) updateModelsCard(LAST_STATUS);
+}
+function setAccel(a) {
+ const allowed = document.getElementById('quality').value !== 'high' && currentMode !== 'extend' && currentMode !== 'keyframe';
+ const v = allowed ? a : 'off';
+ document.getElementById('accel').value = v;
+ document.querySelectorAll('#accelGroup .pill-btn').forEach(b => b.classList.toggle('active', b.dataset.accel === v));
+ updateCustomizeSummary();
updateDerived();
- document.querySelector('aside.form-pane').scrollTop = 0;
}
-function useAsExtendSource() { if (!activePath) return alert('Pick an output first.'); useAsExtendSourcePath(activePath); }
-
-async function loadParams() {
- if (!activePath) return;
- const r = await fetch('/sidecar?path='+encodeURIComponent(activePath));
- if (!r.ok) return;
- const data = await r.json();
- const p = data.params;
- if (p.mode === 'extend') setMode('extend');
- else if (p.mode === 'keyframe') setMode('keyframe');
- else if (p.mode === 'i2v_clean_audio' || p.mode === 'i2v') { setMode('i2v'); document.getElementById('i2vMode').value = p.mode; document.getElementById('mode').value = p.mode; }
- else setMode('t2v');
- // Apply quality + aspect FIRST (these stomp on width/height), then
- // override with explicit sidecar values so any custom dims survive.
- if (p.quality) setQuality(p.quality);
- // Snap aspect from the sidecar's recorded dims; only call when quality
- // isn't 'quick' (Quick has no aspect choice and the row is hidden).
- if (p.quality !== 'quick' && p.width && p.height) {
- for (const [k, a] of Object.entries(ASPECTS)) {
- if ((a.w === p.width && a.h === p.height) ||
- (a.h === p.width && a.w === p.height)) { setAspect(k); break; }
- }
- }
- // Now load explicit dims — overrides whatever the preset/aspect set.
- if (p.width) document.getElementById('width').value = p.width;
- if (p.height) document.getElementById('height').value = p.height;
- if (p.accel) setAccel(p.accel);
- if (p.temporal_mode) setTemporalMode(p.temporal_mode);
- if (p.upscale) setUpscale(p.upscale);
- if (p.upscale_method) setUpscaleMethod(p.upscale_method);
- document.getElementById('prompt').value = p.prompt || '';
- document.getElementById('negative_prompt').value = p.negative_prompt || '';
- // If the loaded sidecar carried an Avoid value, surface the row so the
- // user can see it without having to click the toggle.
- syncAvoidRowFromValue();
- if (p.frames) { document.getElementById('frames').value = p.frames; document.getElementById('duration').value = framesToDuration(p.frames); }
- if (p.steps) document.getElementById('steps').value = p.steps;
- if (p.seed != null) document.getElementById('seed').value = p.seed;
- // Image / start / end go through pickerSetImage so the preview tile
- // and recent-strip selection state update along with the hidden input.
- if (p.image) pickerSetImage('image', p.image, { snapAspect: false });
- if (p.start_image) pickerSetImage('start_image', p.start_image, { snapAspect: false });
- if (p.end_image) pickerSetImage('end_image', p.end_image, { snapAspect: false });
- if (p.audio) document.getElementById('audio').value = p.audio;
- // Extend-specific: restore source video path
- if (p.video_path) document.getElementById('video_path').value = p.video_path;
- if (p.label) document.getElementById('preset_label').value = p.label;
-
- // Restore the LoRA picker state. Without this, Load Params would silently
- // drop every LoRA the prior render used — prompt + seed + dims all match
- // but `loras=0` would go on the wire and the model would re-render
- // without fusion (no face/style transfer). Wire shape on the sidecar is
- // a list of {path, strength}; we re-decorate with `name` + `trigger_words`
- // from _knownUserLoras when available so the chip renders nicely.
- if (Array.isArray(p.loras)) {
- _activeLoras = p.loras.map(l => {
- const path = l.path;
- const strength = (typeof l.strength === 'number') ? l.strength : 1.0;
- const meta = (Array.isArray(_knownUserLoras)
- ? _knownUserLoras.find(u => u.path === path)
- : null) || {};
- return {
- path,
- strength,
- name: meta.name || (path ? path.split('/').pop() : 'LoRA'),
- trigger_words: meta.trigger_words || [],
- compatible_modes: meta.compatible_modes || ['unknown'],
- };
- }).filter(x => x.path);
- if (typeof renderLorasList === 'function') {
- try { renderLorasList(); } catch (_) {}
- }
- if (typeof _serializeLoras === 'function') {
- try { _serializeLoras(); } catch (_) {}
+function temporalModeAllowed() {
+ const q = document.getElementById('quality').value;
+ const mode = document.getElementById('mode').value;
+ return q !== 'high' && currentMode !== 'extend' && currentMode !== 'keyframe' && (mode === 't2v' || mode === 'i2v');
+}
+function setTemporalMode(t) {
+ const allowed = temporalModeAllowed();
+ const v = (allowed && t === 'fps12_interp24') ? 'fps12_interp24' : 'native';
+ document.getElementById('temporal_mode').value = v;
+ document.querySelectorAll('#temporalGroup .pill-btn').forEach(b => b.classList.toggle('active', b.dataset.temporal === v));
+ updateCustomizeSummary();
+ updateDerived();
+}
+function setUpscale(u) {
+ const v = ['off', 'fit_720p', 'x2'].includes(u) ? u : 'off';
+ document.getElementById('upscale').value = v;
+ document.querySelectorAll('#upscaleGroup .pill-btn').forEach(b => b.classList.toggle('active', b.dataset.upscale === v));
+ // Show / hide the Method pill row — only relevant when an upscale is
+ // actually being applied. When toggled to "off", revert method to Fast
+ // so a later toggle back to fit_720p starts from the safe default.
+ const methodRow = document.getElementById('upscaleMethodRow');
+ if (methodRow) methodRow.style.display = (v === 'off' || !PIPERSR_UPSCALE_ENABLED) ? 'none' : '';
+ if (v === 'off' || !PIPERSR_UPSCALE_ENABLED) setUpscaleMethod('lanczos');
+ updateCustomizeSummary();
+ updateDerived();
+}
+function setUpscaleMethod(m) {
+ if (m === 'model') m = 'pipersr'; // legacy sidecars from the retired LTX Sharp path
+ const v = (PIPERSR_UPSCALE_ENABLED && m === 'pipersr') ? 'pipersr' : 'lanczos';
+ document.getElementById('upscale_method').value = v;
+ document.querySelectorAll('#upscaleMethodGroup .pill-btn').forEach(b => b.classList.toggle('active', b.dataset.method === v));
+ updateCustomizeSummary();
+ updateDerived();
+}
+function updateAccelAvailability() {
+ const allowed = document.getElementById('quality').value !== 'high' && currentMode !== 'extend' && currentMode !== 'keyframe';
+ document.querySelectorAll('#accelGroup .pill-btn').forEach(b => {
+ const disabled = !allowed && b.dataset.accel !== 'off';
+ b.classList.toggle('disabled', disabled);
+ });
+ if (!allowed && document.getElementById('accel').value !== 'off') setAccel('off');
+}
+function updateTemporalAvailability() {
+ const allowed = temporalModeAllowed();
+ document.querySelectorAll('#temporalGroup .pill-btn').forEach(b => {
+ const disabled = !allowed && b.dataset.temporal !== 'native';
+ b.classList.toggle('disabled', disabled);
+ if (b.dataset.temporal === 'fps12_interp24') {
+ b.title = allowed
+ ? 'Generate at 12fps, then interpolate to a normal 24fps export.'
+ : 'Available for Q4 Text/Image renders. Off for High, FFLF, Extend, and external-audio I2V.';
}
- }
-
- updateCustomizeSummary();
- updateDerived();
+ });
+ if (!allowed && document.getElementById('temporal_mode').value !== 'native') setTemporalMode('native');
+}
+function setAspect(a) {
+ if (!ASPECTS[a]) return;
+ document.getElementById('aspect').value = a;
+ document.querySelectorAll('#aspectGroup .pill-btn').forEach(b => b.classList.toggle('active', b.dataset.aspect === a));
+ applyAspect(a);
}
-// ====== Output info modal ======
-//
-// Opened by the ⓘ button on each gallery card. Shows the full sidecar
-// (.mp4.json) we wrote at render time: prompt, seed, mode, dimensions,
-// frames, steps, LoRAs used (with display names + strengths), elapsed
-// time, queue id, model. Plus per-field copy buttons for the things
-// users actually want to reuse (prompt + seed).
-//
-// Why a modal and not inline detail-on-hover: the prompt alone can be
-// 1000+ chars; trying to render it inline next to the thumbnail would
-// blow up the gallery layout. Modal lets us scroll comfortably.
-
-let _outputInfoLastPath = null;
+// Compose the right-aligned line in the Customize summary. Reflects the
+// current effective state: aspect, custom-dims callout, speed setting.
+function updateCustomizeSummary() {
+ const el = document.getElementById('customizeSummary');
+ if (!el) return;
+ const q = document.getElementById('quality').value;
+ const w = parseInt(document.getElementById('width').value || 0);
+ const h = parseInt(document.getElementById('height').value || 0);
+ const aspect = document.getElementById('aspect').value || 'landscape';
+ const accel = document.getElementById('accel').value || 'off';
+ const upscale = document.getElementById('upscale').value || 'off';
+ const parts = [];
+ // Aspect (Quick is fixed 4:3, no choice; Standard/High show landscape/vertical).
+ if (q === 'quick') parts.push('4:3 · 640×480');
+ else parts.push(aspect === 'vertical' ? '9:16' : '16:9');
+ // Flag custom dims if they don't match the preset.
+ const preset = QUALITY_PRESETS[q] || QUALITY_PRESETS['standard'];
+ const vertical = (aspect === 'vertical' && q !== 'quick');
+ const expectedW = vertical ? preset.h : preset.w;
+ const expectedH = vertical ? preset.w : preset.h;
+ if (q !== 'quick' && (w !== expectedW || h !== expectedH)) {
+ parts.push(`${w}×${h} custom`);
+ }
+ // Speed
+ parts.push(accel === 'off' ? 'exact speed' : (accel === 'boost' ? 'boost' : 'turbo'));
+ if ((document.getElementById('temporal_mode')?.value || 'native') === 'fps12_interp24') {
+ parts.push('12→24fps long clip');
+ }
+ const method = (document.getElementById('upscale_method')?.value || 'lanczos');
+ const methodTag = method === 'pipersr' || method === 'model' ? ' sharp' : '';
+ if (upscale === 'fit_720p') parts.push('720p export' + methodTag);
+ else if (upscale === 'x2') parts.push('2× export' + methodTag);
+ el.textContent = parts.join(' · ');
+}
+function setExtendMode(m) {
+ // Fast = no-CFG path, fits in 64 GB at 1280×704. Quality = upstream
+ // defaults, requires headroom. Both are exposed on the form via hidden
+ // inputs; this just flips the values + active pill.
+ const steps = m === 'quality' ? 30 : 12;
+ const cfg = m === 'quality' ? 3.0 : 1.0;
+ document.getElementById('extend_steps').value = String(steps);
+ document.getElementById('extend_cfg').value = String(cfg);
+ document.querySelectorAll('#extendModeGroup .pill-btn').forEach(b =>
+ b.classList.toggle('active', b.dataset.extendMode === m));
+}
-async function openOutputInfoModal(path) {
- _outputInfoLastPath = path;
- const modal = document.getElementById('outputInfoModal');
- const body = document.getElementById('outputInfoBody');
- const title = document.getElementById('outputInfoTitle');
- modal.style.display = 'flex';
- body.innerHTML = '<div class="hint">Loading…</div>';
- // Display the filename in the modal title for quick orientation.
- const fname = path.split('/').pop();
- if (title) title.textContent = `Generation info · ${fname}`;
- let data;
- try {
- const r = await fetch('/sidecar?path=' + encodeURIComponent(path));
- if (!r.ok) {
- body.innerHTML = `<div class="hint">No sidecar metadata for this output (older generation, or sidecar was deleted).</div>`;
- return;
+document.querySelectorAll('#modeGroup .pill-btn').forEach(b => b.onclick = () => setMode(b.dataset.mode));
+document.querySelectorAll('#qualityGroup .pill-btn').forEach(b => b.onclick = () => {
+ // Disabled-but-actionable: the High pill becomes a "click to install Q8"
+ // CTA when Q8 is missing. Routes to the Models modal so the user lands
+ // on the download button with full context (size, current state, etc.).
+ if (b.classList.contains('disabled')) {
+ if (b.classList.contains('needs-install') && typeof openModelsModal === 'function') {
+ openModelsModal();
}
- data = await r.json();
- } catch (e) {
- body.innerHTML = `<div class="hint">Couldn't load info: ${escapeHtml(e.message || String(e))}</div>`;
return;
}
- body.innerHTML = renderOutputInfoBody(path, data);
-}
-
-function closeOutputInfoModal() {
- document.getElementById('outputInfoModal').style.display = 'none';
-}
+ setQuality(b.dataset.quality);
+});
+document.querySelectorAll('#accelGroup .pill-btn').forEach(b => b.onclick = () => { if (!b.classList.contains('disabled')) setAccel(b.dataset.accel); });
+document.querySelectorAll('#temporalGroup .pill-btn').forEach(b => b.onclick = () => { if (!b.classList.contains('disabled')) setTemporalMode(b.dataset.temporal); });
+document.querySelectorAll('#upscaleGroup .pill-btn').forEach(b => b.onclick = () => { if (!b.classList.contains('disabled')) setUpscale(b.dataset.upscale); });
+document.querySelectorAll('#upscaleMethodGroup .pill-btn').forEach(b => b.onclick = () => { if (!b.classList.contains('disabled')) setUpscaleMethod(b.dataset.method); });
+document.querySelectorAll('#aspectGroup .pill-btn').forEach(b => b.onclick = () => setAspect(b.dataset.aspect));
+document.querySelectorAll('#extendModeGroup .pill-btn').forEach(b => b.onclick = () => setExtendMode(b.dataset.extendMode));
-function _copyToClipboard(text, btn) {
- // Best-effort copy with visual feedback. Falls back silently when the
- // clipboard API is blocked (e.g. iframe sandboxes without permissions).
+// Prompt enhancement via Gemma — wraps the upstream CLI's `enhance`
+// subcommand. Cold start ~12-15s (Gemma load), warm ~5s. Blocks the UI
+// during the request (just the button — rest of the form stays usable).
+async function enhancePrompt() {
+ const ta = document.getElementById('prompt');
+ const original = ta.value.trim();
+ if (!original) { alert('Type a prompt before enhancing it.'); return; }
+ const mode = (currentMode === 'i2v' || currentMode === 'keyframe' || currentMode === 'extend') ? 'i2v' : 't2v';
+ const btn = document.getElementById('enhanceBtn');
+ // Snapshot the FULL inner markup, not just text — the button carries
+ // an inline ph-sparkle-fill SVG that textContent would strip.
+ const originalLabel = btn.innerHTML;
+ btn.disabled = true;
+ btn.innerHTML = '<svg class="ph" aria-hidden="true" style="margin-right:6px;vertical-align:-2px"><use href="#ph-sparkle-fill"/></svg>Loading Gemma… (~15s on cold start)';
+ let res;
try {
- navigator.clipboard.writeText(text);
- if (btn) {
- const orig = btn.textContent;
- btn.textContent = 'Copied!';
- setTimeout(() => { btn.textContent = orig; }, 1200);
- }
- } catch (e) { /* swallow */ }
+ const fd = new URLSearchParams({ prompt: original, mode });
+ const r = await fetch('/prompt/enhance', { method: 'POST', body: fd });
+ res = await r.json();
+ } catch (e) {
+ alert('Enhance request failed: ' + (e.message || e));
+ btn.disabled = false; btn.innerHTML = originalLabel;
+ return;
+ }
+ btn.disabled = false; btn.innerHTML = originalLabel;
+ if (res.error) { alert('Enhance failed: ' + res.error); return; }
+ // Show diff in a confirm so the user can decide whether to accept.
+ const accept = confirm(
+ `Original:\n${res.original}\n\nEnhanced:\n${res.enhanced}\n\nReplace your prompt with the enhanced version?`
+ );
+ if (accept) {
+ ta.value = res.enhanced;
+ ta.dispatchEvent(new Event('input', { bubbles: true }));
+ }
}
-function _humanSize(b) {
- if (b == null) return '';
- if (b < 1024) return `${b} B`;
- if (b < 1024*1024) return `${(b/1024).toFixed(1)} KB`;
- if (b < 1024*1024*1024) return `${(b/1024/1024).toFixed(1)} MB`;
- return `${(b/1024/1024/1024).toFixed(2)} GB`;
+// Extend duration: user types seconds, we convert to latent frames behind
+// the scenes. Each latent = 8 video frames; at 24 fps that's 0.333 s.
+// Round-up so the user gets at least the seconds they asked for.
+// seconds → latents: ceil(seconds * 24 / 8)
+// latents → actual seconds: latents * 8 / 24
+// Hint line shows both numbers so the conversion isn't a black box.
+function syncExtendDuration() {
+ const secInput = document.getElementById('extend_seconds');
+ const hidden = document.getElementById('extend_frames');
+ const hint = document.getElementById('extendDurationHint');
+ if (!secInput || !hidden || !hint) return;
+ const seconds = parseFloat(secInput.value) || 0;
+ const latents = Math.max(1, Math.ceil(seconds * 24 / 8));
+ const actualSec = (latents * 8 / 24);
+ hidden.value = String(latents);
+ hint.textContent = `≈ ${actualSec.toFixed(2)} s of new content (${latents} latent frames × 8 video frames at 24 fps)`;
}
+document.getElementById('extend_seconds').addEventListener('input', syncExtendDuration);
+syncExtendDuration(); // initialize on load
+document.getElementById('i2vMode').addEventListener('change', () => {
+ document.getElementById('audioSection').classList.toggle('show', document.getElementById('i2vMode').value === 'i2v_clean_audio');
+ if (currentMode === 'i2v') document.getElementById('mode').value = document.getElementById('i2vMode').value;
+ updateTemporalAvailability();
+ updateCustomizeSummary();
+ updateDerived();
+});
-function _humanDuration(s) {
- if (s == null) return '';
- if (s < 60) return `${s.toFixed(1)} s`;
- const m = Math.floor(s / 60); const r = (s - m*60).toFixed(0);
- return `${m} min ${r} s`;
+function applyAspect(key) {
+ if (!ASPECTS[key]) return;
+ document.getElementById('aspect').value = key;
+ // Aspect controls dimensions only when the active preset has a choice
+ // (Standard / High at 1280×704 vs 704×1280). Quick is fixed 4:3 and
+ // ignores the aspect picker (the row is hidden in that state, so this
+ // path normally won't fire — defensive in case of programmatic calls).
+ const q = document.getElementById('quality').value;
+ if (q === 'quick') return;
+ const preset = QUALITY_PRESETS[q] || QUALITY_PRESETS['standard'];
+ const vertical = (key === 'vertical');
+ document.getElementById('width').value = vertical ? preset.h : preset.w;
+ document.getElementById('height').value = vertical ? preset.w : preset.h;
+ updateCustomizeSummary();
+ updateDerived();
}
-function renderOutputInfoBody(path, data) {
- const p = (data && data.params) || {};
- const loras = Array.isArray(p.loras) ? p.loras : [];
-
- // Look up each LoRA's display name from the installed-LoRAs cache so
- // the modal shows "Claymation Style" instead of the raw safetensors
- // path. Falls back gracefully when a LoRA was deleted or is an HF id.
- const lookupLoraName = (loraPath) => {
- if (!loraPath) return '?';
- const known = (_knownUserLoras || []).find(l => l.path === loraPath);
- if (known) return known.name;
- if (loraPath.includes('/') && !loraPath.endsWith('.safetensors')) return loraPath;
- return loraPath.split('/').pop().replace(/\.safetensors$/, '');
- };
-
- const promptText = p.prompt || '';
- const promptAttr = JSON.stringify(promptText).replace(/"/g, '&quot;');
- const seedVal = String(p.seed_used != null ? p.seed_used : p.seed || '');
- const seedAttr = JSON.stringify(seedVal).replace(/"/g, '&quot;');
- const pathAttr = JSON.stringify(path).replace(/"/g, '&quot;');
- const accelMetrics = (data && data.accel_metrics) || null;
- const modeLabel = ({
- t2v: 'Text → Video',
- i2v: 'Image → Video',
- i2v_clean_audio: 'Image → Video (clean audio)',
- keyframe: 'FFLF (first + last frame)',
- extend: 'Extend',
- })[p.mode] || (p.mode || '—');
-
- // Compose the dimensions + duration into a single "Format" line — fewer
- // grid rows, easier to scan. We separate technical metadata (Format,
- // Frames) from generation parameters (Mode, Quality, Seed, Steps).
- const formatBits = [];
- if (p.width && p.height) formatBits.push(`${p.width} × ${p.height}`);
- if (data.video_duration_sec != null) formatBits.push(`${data.video_duration_sec.toFixed(2)} s @ ${data.fps || 24} fps`);
-
- let html = '';
+// applyQuality is kept as a tiny shim — old call sites (mode switching,
+// etc.) call it expecting "set steps for the active quality." The
+// dimensions are now owned by setQuality / applyAspect.
+function applyQuality() {
+ const q = document.getElementById('quality').value;
+ if (q === 'high') {
+ document.getElementById('steps').value = 18;
+ } else {
+ document.getElementById('steps').value = 8; // quick + balanced + standard
+ }
+ updateCustomizeSummary();
+ updateDerived();
+}
- // ---- Output (technical) ----
- html += `<div class="oi-section">
- <div class="oi-section-title"><span>Output</span></div>
- <dl class="oi-grid">
- ${formatBits.length ? `<dt>Format</dt><dd>${formatBits.join(' · ')}</dd>` : ''}
- ${p.frames != null ? `<dt>Frames</dt><dd>${p.frames}</dd>` : ''}
- </dl>
- </div>`;
+function durationToFrames(s) {
+ const k = Math.max(0, Math.round(s * FPS / 8));
+ return k * 8 + 1;
+}
+function framesToDuration(f) { return ((f - 1) / FPS).toFixed(2); }
- // ---- Generation parameters ----
- const genRows = [];
- genRows.push(`<dt>Mode</dt><dd>${escapeHtml(modeLabel)}</dd>`);
- genRows.push(`<dt>Quality</dt><dd>${escapeHtml((p.quality || 'standard').replace(/^./, c => c.toUpperCase()))}</dd>`);
- if (p.accel && p.accel !== 'off') {
- genRows.push(`<dt>Speed</dt><dd>${escapeHtml(p.accel.replace(/^./, c => c.toUpperCase()))}</dd>`);
- }
- if (accelMetrics && p.accel && p.accel !== 'off') {
- const cachedCount = accelMetrics.cached_steps_count || 0;
- const totalSteps = accelMetrics.total_steps || p.steps || 0;
- const savings = accelMetrics.estimated_denoise_call_savings_pct;
- const cachedList = Array.isArray(accelMetrics.cached_steps) && accelMetrics.cached_steps.length
- ? ` · cached steps ${escapeHtml(accelMetrics.cached_steps.join(', '))}`
- : '';
- const savingsText = savings != null ? ` · ~${escapeHtml(String(savings))}% denoise calls saved` : '';
- genRows.push(`<dt>Accel metrics</dt><dd>${cachedCount}/${totalSteps} cached${savingsText}${cachedList}</dd>`);
+// LTX 2.3 requires frame counts in the form 1 + 8k (one keyframe + N
+// VAE-temporal blocks of 8 frames each). Typing "100" or "240" wastes
+// compute on partially-filled trailing latents — the pipeline rounds
+// up internally but charges for the empty slots. Snap on blur to the
+// nearest valid value below + 1 (so we never silently render *more*
+// than the user asked for, only less or equal).
+function snapFramesTo8kPlus1() {
+ const el = document.getElementById('frames');
+ if (!el) return;
+ const v = parseInt(el.value) || 0;
+ if (v < 1) { el.value = 9; return; }
+ // Nearest 8k+1: round (v-1)/8 to nearest int, multiply back, +1.
+ const k = Math.max(1, Math.round((v - 1) / 8));
+ const snapped = k * 8 + 1;
+ if (snapped !== v) {
+ el.value = snapped;
+ // Reflect the change in duration too, since they're bound.
+ document.getElementById('duration').value = framesToDuration(snapped);
}
- if (data.memory_policy) {
- const mp = data.memory_policy;
- const req = mp.requested || p.memory_policy || 'auto';
- const eff = mp.effective || req;
- const decode = mp.vae_decode || (mp.helper && mp.helper.vae_decode) || '';
- const fullMax = mp.full_decode_max_frames != null ? ` · full≤${escapeHtml(String(mp.full_decode_max_frames))}f` : '';
- const reason = mp.reason ? ` · ${escapeHtml(mp.reason)}` : '';
- genRows.push(`<dt>Memory</dt><dd>${escapeHtml(req)}${eff !== req ? ` → ${escapeHtml(eff)}` : ''}${decode ? ` · VAE ${escapeHtml(decode)}` : ''}${fullMax}${reason}</dd>`);
+}
+
+function updateDerived() {
+ const mode = document.getElementById('mode').value;
+ const w = parseInt(document.getElementById('width').value || 0);
+ const h = parseInt(document.getElementById('height').value || 0);
+ const f = parseInt(document.getElementById('frames').value || 0);
+ const dur = framesToDuration(f);
+
+ const upscale = document.getElementById('upscale')?.value || 'off';
+ let finalRes = `<strong>${w}×${h}</strong>`;
+ if (upscale === 'fit_720p') {
+ const tw = w >= h ? 1280 : 720;
+ const th = w >= h ? 720 : 1280;
+ finalRes = `${w}×${h} → <strong>${tw}×${th}</strong> fit`;
+ } else if (upscale === 'x2') {
+ finalRes = `${w}×${h} → <strong>${w * 2}×${h * 2}</strong>`;
+ } else {
+ let pw = w, ph = h;
+ if (w === 704 && h % 16 === 0) pw = 720;
+ if (h === 704 && w % 16 === 0) ph = 720;
+ const padded = (pw !== w || ph !== h) && mode === 'i2v_clean_audio';
+ finalRes = padded ? `${w}×${h} → <strong>${pw}×${ph}</strong>` : `<strong>${w}×${h}</strong>`;
}
- if (p.temporal_mode === 'fps12_interp24' || data.temporal) {
- const t = data.temporal || {};
- const sourceFrames = t.source_frames || p.model_frames || '—';
- const deliveryFrames = t.delivery_frames || p.frames || '—';
- const sourceFps = t.model_fps || p.model_fps || 12;
- const deliveryFps = t.delivery_fps || p.delivery_fps || 24;
- genRows.push(`<dt>Long clips</dt><dd>12 → 24fps · LTX ${escapeHtml(String(sourceFrames))}f @ ${escapeHtml(String(sourceFps))}fps → ${escapeHtml(String(deliveryFrames))}f @ ${escapeHtml(String(deliveryFps))}fps</dd>`);
+ const accel = document.getElementById('accel')?.value || 'off';
+ const accelText = accel === 'off' ? '' : ` · ${accel === 'turbo' ? 'Turbo' : 'Boost'}`;
+ const temporal = document.getElementById('temporal_mode')?.value || 'native';
+ let temporalText = '';
+ if (temporal === 'fps12_interp24') {
+ const intervalSec = Math.max(0, (f - 1) / FPS);
+ const sourceFrames = Math.max(1, Math.round(intervalSec * 12 / 8)) * 8 + 1;
+ temporalText = ` · LTX ${sourceFrames}f @ 12fps → ${FPS}fps`;
}
- if (p.upscale && p.upscale !== 'off') {
- const up = data.upscale || {};
- const target = up.target_w && up.target_h ? ` → ${up.target_w} × ${up.target_h}` : '';
- const isSharp = p.upscale_method === 'pipersr' || p.upscale_method === 'model' || (data.upscale && (data.upscale.method === 'pipersr_coreml' || data.upscale.pre_pass === 'pipersr_x2' || data.upscale.method === 'ltx_latent_x2' || data.upscale.pre_pass === 'ltx_latent_x2'));
- const baseLabel = p.upscale === 'fit_720p' ? '720p fit (no crop)' : (p.upscale === 'x2' ? '2×' : p.upscale);
- const label = isSharp ? `${baseLabel} · Sharp (PiperSR)` : `${baseLabel} · Fast (Lanczos)`;
- genRows.push(`<dt>Upscale</dt><dd>${escapeHtml(label + target)}</dd>`);
+
+ document.getElementById('derived').innerHTML = `Duration <strong>${dur}s</strong> @ ${FPS}fps${temporalText} · ${finalRes} · Steps ${document.getElementById('steps').value}${accelText}`;
+
+ // Compact derived line in the sticky action footer — same info, tighter
+ // typography. Lets the user see what they're about to render WITHOUT
+ // scrolling back to the customize disclosure. Mirrors the Customize
+ // summary style (just dimensions + duration; full details stay in the
+ // expanded Customize body).
+ const derivedFooter = document.getElementById('derivedFooter');
+ if (derivedFooter) {
+ derivedFooter.innerHTML = `<strong>${dur}s</strong> · ${finalRes}${temporalText}${accelText}`;
}
- const codec = data.output_codec || (data.upscale && data.upscale.codec);
- if (codec && codec.pix_fmt && codec.crf != null) {
- const preset = codec.preset ? ` · ${codec.preset}` : '';
- genRows.push(`<dt>Output codec</dt><dd>${escapeHtml(codec.pix_fmt)} · CRF ${escapeHtml(String(codec.crf))}${escapeHtml(preset)}</dd>`);
+ // Also update the Quality strip's right-side meta line (e.g. "5s · 1024×576")
+ // so the Quality picker block reads as a self-contained summary.
+ const qualityMeta = document.getElementById('qualityMeta');
+ if (qualityMeta) {
+ const qBare = `${w}×${h}`;
+ qualityMeta.textContent = `${dur}s · ${qBare}`;
}
- if (p.negative_prompt) {
- genRows.push(`<dt>Avoid</dt><dd>${escapeHtml(snippet(p.negative_prompt, 90))}</dd>`);
+
+ const warns = [];
+ if (w % 32 !== 0) warns.push(`Width ${w} isn't a multiple of 32 (closest ${Math.round(w/32)*32})`);
+ if (h % 32 !== 0) warns.push(`Height ${h} isn't a multiple of 32 (closest ${Math.round(h/32)*32})`);
+ if (f > 1 && (f - 1) % 8 !== 0) {
+ const closest = Math.max(1, Math.round((f - 1) / 8) * 8 + 1);
+ warns.push(`Frames work best as 8k+1 (closest ${closest})`);
}
- if (seedVal) {
- genRows.push(`<dt>Seed</dt><dd>
- <code>${escapeHtml(seedVal)}</code>
- <button class="oi-copy" type="button" onclick="_copyToClipboard(${seedAttr}, this)">Copy</button>
- </dd>`);
+ if (temporal === 'fps12_interp24') {
+ warns.push('12→24fps is experimental; check dialogue lip-sync and fast motion');
}
- if (p.steps != null) genRows.push(`<dt>Steps</dt><dd>${p.steps}</dd>`);
- if (p.hdr) genRows.push(`<dt>HDR</dt><dd>On</dd>`);
- if (p.label) genRows.push(`<dt>Label</dt><dd>${escapeHtml(p.label)}</dd>`);
+ const banner = document.getElementById('warnBanner');
+ if (warns.length) { banner.innerHTML = '<svg class="ph" aria-hidden="true" style="margin-right:6px;vertical-align:-2px"><use href="#ph-warning-fill"/></svg>' + warns.join(' · '); banner.classList.add('show'); }
+ else banner.classList.remove('show');
- html += `<div class="oi-section">
- <div class="oi-section-title"><span>Generation</span></div>
- <dl class="oi-grid">${genRows.join('')}</dl>
- </div>`;
+ // Mode-aware visibility
+ const inI2V = mode === 'i2v' || mode === 'i2v_clean_audio';
+ const inImageFlow = inI2V || currentMode === 'keyframe';
+ document.getElementById('imageSection').classList.toggle('show', inI2V && currentMode !== 'keyframe');
+ document.getElementById('extendSection').classList.toggle('show', currentMode === 'extend');
+ document.getElementById('keyframeSection').classList.toggle('show', currentMode === 'keyframe');
+ document.getElementById('sizingSection').classList.toggle('show', currentMode !== 'extend');
+ // quickMetricsRow (Duration / Frames / Seed) doesn't apply to Extend
+ // (extend_seconds drives the new content; the source video provides
+ // the rest). Hide it in extend, show otherwise.
+ const qmr = document.getElementById('quickMetricsRow');
+ if (qmr) qmr.classList.toggle('show', currentMode !== 'extend');
+ document.getElementById('audioSection').classList.toggle('show', mode === 'i2v_clean_audio');
+ // I2V audio source picker (Advanced) — only relevant in I2V flow.
+ // In T2V/Extend/FFLF the model generates audio jointly; there's nothing
+ // to swap out, so the dropdown is just noise.
+ const i2vAudioSec = document.getElementById('i2vAudioModeSection');
+ if (i2vAudioSec) i2vAudioSec.classList.toggle('show', inI2V);
+ // In image flows the aspect picker is the only sizing control. Width/height
+ // auto-derive from aspect+quality so the source image drives the framing
+ // and we don't accidentally cover-crop a 16:9 photo into 9:16.
+ const dimsRow = document.getElementById('dimsRow');
+ if (dimsRow) dimsRow.style.display = inImageFlow ? 'none' : '';
- // ---- Prompt ----
- if (promptText) {
- html += `<div class="oi-section">
- <div class="oi-section-title">
- <span>Prompt</span>
- <button class="oi-copy" type="button" onclick="_copyToClipboard(${promptAttr}, this)">Copy</button>
- </div>
- <div class="oi-prompt">${escapeHtml(promptText)}</div>
- </div>`;
- }
+ // Image previews are now part of the picker component itself — the
+ // preview <img> + clear button live inside .picker-drop and are toggled
+ // by pickerSetImage(). No per-mode preview management here anymore;
+ // the old imagePreview / startImagePreview / endImagePreview elements
+ // are gone.
+}
- // ---- LoRAs (flat list, hairline-separated) ----
- if (loras.length) {
- const rows = loras.map(l => {
- const name = lookupLoraName(l.path);
- const strength = (l.strength != null ? l.strength : 1).toFixed(2);
- return `<div class="oi-lora-row">
- <span class="oi-lora-name" title="${escapeHtml(l.path || '')}">${escapeHtml(name)}</span>
- <span class="oi-lora-strength">strength ${strength}</span>
- </div>`;
- }).join('');
- html += `<div class="oi-section">
- <div class="oi-section-title">
- <span>LoRAs used</span>
- <span class="oi-count">${loras.length}</span>
- </div>
- <div class="oi-lora-list">${rows}</div>
- </div>`;
+['width','height','frames','duration'].forEach(id => {
+ const el = document.getElementById(id);
+ if (id === 'duration') {
+ el.addEventListener('input', e => { document.getElementById('frames').value = durationToFrames(parseFloat(e.target.value) || 0); updateDerived(); });
+ } else if (id === 'frames') {
+ el.addEventListener('input', e => { document.getElementById('duration').value = framesToDuration(parseInt(e.target.value) || 0); updateDerived(); });
+ el.addEventListener('blur', () => { snapFramesTo8kPlus1(); updateDerived(); });
+ } else {
+ // width / height: also refresh the Customize summary so "custom" flags
+ // appear/disappear as the user types away from the preset values.
+ el.addEventListener('input', () => { updateCustomizeSummary(); updateDerived(); });
}
+});
+// Picker hidden inputs no longer take user input — their value changes
+// via pickerSetImage(), which already calls updateDerived(). No per-input
+// listeners needed.
- // ---- Timing + provenance ----
- const timingRows = [];
- if (data.started) timingRows.push(`<dt>Started</dt><dd>${escapeHtml(data.started)}</dd>`);
- if (data.elapsed_sec != null) timingRows.push(`<dt>Elapsed</dt><dd>${_humanDuration(data.elapsed_sec)}</dd>`);
- if (data.queue_id) timingRows.push(`<dt>Queue ID</dt><dd><code>${escapeHtml(data.queue_id)}</code></dd>`);
- if (data.model) timingRows.push(`<dt>Model</dt><dd><code>${escapeHtml(data.model.split('/').pop())}</code></dd>`);
- if (timingRows.length) {
- html += `<div class="oi-section">
- <div class="oi-section-title"><span>Timing</span></div>
- <dl class="oi-grid">${timingRows.join('')}</dl>
- </div>`;
- }
+// Auto-snap the aspect picker based on an image's actual dimensions.
+// Avoids the 16:9-source-cropped-to-9:16-strip footgun.
+function snapAspectToImage(path) {
+ const probe = new Image();
+ probe.onload = () => {
+ const r = probe.naturalWidth / probe.naturalHeight;
+ const target = r >= 1 ? 'landscape' : 'vertical';
+ if (document.getElementById('aspect').value !== target) setAspect(target);
+ };
+ probe.src = '/image?path=' + encodeURIComponent(path);
+}
- // ---- Action row ----
- html += `<div class="oi-actions">
- <button class="ghost-btn" type="button" onclick="closeOutputInfoModal()">Close</button>
- <button class="oi-primary" type="button"
- onclick="closeOutputInfoModal(); selectOutput(${pathAttr}); loadParams()">
- Load params into form
- </button>
- </div>`;
+// uploadImage() / uploadKeyframe() were replaced by the unified picker
+// component (pickerUploadFile + refreshUploadsStrip). The /upload endpoint
+// still drives the actual transfer; the only change is which JS calls it.
+
+// ====== Image picker component ======
+// One implementation, three call sites: I2V image, FFLF start_image,
+// FFLF end_image. Each picker carries a `key` (the hidden field's name);
+// every DOM element it owns is suffixed with `_<key>` so we can wire
+// listeners by lookup instead of a per-instance closure.
+const PICKERS = ['image', 'start_image', 'end_image'];
- return html;
+function pickerEls(key) {
+ return {
+ drop: document.getElementById(`picker_drop_${key}`),
+ file: document.getElementById(`picker_file_${key}`),
+ hidden: document.getElementById(key),
+ preview: document.getElementById(`picker_preview_${key}`),
+ clear: document.getElementById(`picker_clear_${key}`),
+ empty: document.querySelector(`#picker_drop_${key} .picker-empty`),
+ recentWrap: document.getElementById(`picker_recent_${key}_wrap`),
+ recentStrip: document.getElementById(`picker_recent_${key}`),
+ };
}
-async function removeJob(id) { await fetch('/queue/remove?id='+encodeURIComponent(id),{method:'POST'}); poll(); }
-async function togglePause() {
- const s = await (await fetch('/status')).json();
- await api(s.paused ? '/queue/resume' : '/queue/pause', 'POST');
- poll();
+function pickerSetImage(key, path, opts = {}) {
+ const els = pickerEls(key);
+ if (!els.hidden) return;
+ els.hidden.value = path;
+ if (path) {
+ els.preview.src = `/image?path=${encodeURIComponent(path)}`;
+ els.preview.style.display = 'block';
+ els.empty.style.display = 'none';
+ els.clear.style.display = 'flex';
+ els.drop.classList.add('has-image');
+ // Highlight the matching thumbnail in the recent strip if visible.
+ if (els.recentStrip) {
+ els.recentStrip.querySelectorAll('img').forEach(img => {
+ img.classList.toggle('selected', img.dataset.path === path);
+ });
+ }
+ // FFLF anchors framing on the start frame; I2V anchors on its single
+ // image. End frame doesn't drive aspect (would override the start frame).
+ if (key !== 'end_image' && opts.snapAspect !== false) {
+ snapAspectToImage(path);
+ }
+ } else {
+ els.preview.removeAttribute('src');
+ els.preview.style.display = 'none';
+ els.empty.style.display = '';
+ els.clear.style.display = 'none';
+ els.drop.classList.remove('has-image');
+ if (els.recentStrip) {
+ els.recentStrip.querySelectorAll('img').forEach(img => img.classList.remove('selected'));
+ }
+ }
+ updateDerived();
}
-// ====== Tabs ======
-document.querySelectorAll('.tabs button[data-tab]').forEach(b => b.onclick = () => {
- document.querySelectorAll('.tabs button[data-tab]').forEach(x => x.classList.toggle('active', x === b));
- document.querySelectorAll('.tab-content').forEach(t => t.classList.toggle('show', t.id === 'tab-'+b.dataset.tab));
-});
+async function pickerUploadFile(key, file) {
+ const els = pickerEls(key);
+ if (!file || !els.drop) return;
+ // Inline progress overlay on the drop tile while the upload runs.
+ let busy = els.drop.querySelector('.picker-uploading');
+ if (!busy) {
+ busy = document.createElement('div');
+ busy.className = 'picker-uploading';
+ busy.textContent = `Uploading ${file.name}…`;
+ els.drop.appendChild(busy);
+ }
+ try {
+ const fd = new FormData(); fd.append('image', file);
+ const r = await fetch('/upload', { method: 'POST', body: fd });
+ const data = await r.json();
+ if (!data.ok) throw new Error(data.error || 'upload failed');
+ pickerSetImage(key, data.path);
+ // Refresh the "Recent uploads" strip so the just-uploaded file shows
+ // up immediately for the other slots too.
+ refreshUploadsStrip();
+ } catch (e) {
+ alert(`Upload failed: ${e.message || e}`);
+ } finally {
+ busy.remove();
+ }
+}
-// ====== Batch modal ======
-function openBatch() { document.getElementById('batchModal').classList.add('show'); }
-function closeBatch() { document.getElementById('batchModal').classList.remove('show'); }
-async function queueBatch() {
- const fd = new FormData(document.getElementById('genForm'));
- fd.set('prompts', document.getElementById('batchPrompts').value);
- const r = await api('/queue/batch','POST',fd);
- if (r && r.error) { alert('Batch error: '+r.error); return; }
- if (r && r.added) { document.getElementById('batchPrompts').value = ''; poll(); }
+function pickerWire(key) {
+ const els = pickerEls(key);
+ if (!els.drop) return;
+ // Click → file dialog. Skip when the click came from the clear button.
+ els.drop.addEventListener('click', (e) => {
+ if (e.target.closest('.picker-clear')) return;
+ els.file.click();
+ });
+ els.file.addEventListener('change', () => {
+ if (els.file.files[0]) pickerUploadFile(key, els.file.files[0]);
+ els.file.value = ''; // allow re-uploading the same file
+ });
+ els.clear.addEventListener('click', (e) => { e.stopPropagation(); pickerSetImage(key, ''); });
+ // Drag-drop. preventDefault on dragover is what enables drop.
+ els.drop.addEventListener('dragover', (e) => {
+ e.preventDefault();
+ els.drop.classList.add('dragover');
+ });
+ els.drop.addEventListener('dragleave', () => els.drop.classList.remove('dragover'));
+ els.drop.addEventListener('drop', (e) => {
+ e.preventDefault();
+ els.drop.classList.remove('dragover');
+ const f = e.dataTransfer.files && e.dataTransfer.files[0];
+ if (f) pickerUploadFile(key, f);
+ });
}
-// ====== "No music" toggle pill ======
-//
-// Custom pill replacing the default checkbox. Click anywhere on the pill
-// to flip the hidden checkbox + reflect state in the UI (.on class drives
-// the accent fill from the toggle-pill CSS). Backed by a real <input
-// type=checkbox> inside the label, so FormData still picks it up the
-// normal way and screen readers / keyboard nav still work.
-(function () {
- const pill = document.getElementById('noMusicPill');
- const cb = document.getElementById('noMusic');
- if (!pill || !cb) return;
- const sync = () => pill.classList.toggle('on', cb.checked);
- cb.addEventListener('change', sync);
- pill.addEventListener('click', e => {
- // <label> already toggles the checkbox; we just need to refresh the
- // visual state on the next tick AFTER the native toggle has fired.
- setTimeout(sync, 0);
+let _uploadsCache = []; // last fetched list, kept module-level so all
+ // three pickers render the same source data.
+async function refreshUploadsStrip() {
+ let data;
+ try { data = await api('/uploads?limit=24'); }
+ catch (e) { return; }
+ _uploadsCache = data.uploads || [];
+ PICKERS.forEach(key => {
+ const els = pickerEls(key);
+ if (!els.recentStrip) return;
+ if (!_uploadsCache.length) {
+ els.recentWrap.style.display = 'none';
+ return;
+ }
+ els.recentWrap.style.display = '';
+ const currentPath = els.hidden.value;
+ els.recentStrip.innerHTML = _uploadsCache.map(u => `
+ <img class="picker-recent-thumb${u.path === currentPath ? ' selected' : ''}"
+ src="${escapeHtml(u.url)}"
+ data-path="${escapeHtml(u.path)}"
+ title="${escapeHtml(u.name)} · ${u.size_kb} KB · ${escapeHtml(u.mtime)}"
+ alt="">
+ `).join('');
+ els.recentStrip.querySelectorAll('img').forEach(img => {
+ img.addEventListener('click', () => pickerSetImage(key, img.dataset.path));
+ });
});
- sync();
-})();
+}
-// ====== Form submit ======
-//
-// "No music" toggle: appends a clear audio constraint to the prompt
-// before submission so the LTX 2.3 vocoder skips the soundtrack/score it
-// otherwise tends to add. Music is hard to remove cleanly from a stem
-// after the fact (it shares spectral space with dialogue), so users who
-// plan to score the clip themselves want voice + ambient only.
-//
-// We modify the FormData copy, not the textarea value — so the user's
-// original prompt stays untouched in the UI.
-document.getElementById('genForm').addEventListener('submit', async e => {
- e.preventDefault();
- const fd = new FormData(e.target);
+// ====== Format helpers ======
+function fmtMem(m) { return `${m.used_gb.toFixed(1)} / ${m.total_gb.toFixed(0)} GB · swap ${m.swap_gb.toFixed(1)}`; }
+function fmtMin(s) { if (!s || s < 0) return '—'; const m = Math.floor(s/60); const sec = Math.round(s%60); return m > 0 ? `${m}m ${sec}s` : `${sec}s`; }
+function snippet(s, n = 70) { if (!s) return ''; s = s.replace(/\s+/g,' ').trim(); return s.length > n ? s.slice(0, n-1)+'…' : s; }
+function escapeHtml(s) { if (!s) return ''; return s.replace(/[&<>"']/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c])); }
- // Disable the Generate button while we POST to /queue/add so a fast
- // double-click doesn't queue the same job twice. The button is
- // re-enabled after poll() returns (or on error). Keep this ABOVE the
- // LoRA-orphan confirm() so a user who cancels the confirm doesn't
- // leave the button stuck disabled.
- const genBtn = document.getElementById('genBtn');
- const reenable = () => { if (genBtn) genBtn.disabled = false; };
+async function api(path, method = 'GET', body = null) {
+ const opts = { method };
+ if (body) {
+ opts.body = body instanceof FormData ? new URLSearchParams(body) : body;
+ opts.headers = { 'Content-Type': 'application/x-www-form-urlencoded' };
+ }
+ const r = await fetch(path, opts);
+ if (!r.ok && r.status !== 409) throw new Error(`${path}: ${r.status}`);
+ return r.status === 409 ? { error: 'busy' } : r.json().catch(() => ({}));
+}
- // Safety net: if the prompt mentions a trigger word from a LoRA the user
- // has installed but NOT toggled active for this render, ask before
- // submitting. The #1 silent-failure mode is "I typed 'salotrn' but
- // forgot to switch on the picker chip" — the render then runs without
- // fusion, and the face/style doesn't reproduce. Compare prompt vs.
- // (_knownUserLoras minus _activeLoras) and surface a confirm() so the
- // mismatch isn't invisible.
- try {
- const promptRaw = (fd.get('prompt') || '').toString();
- const promptLower = promptRaw.toLowerCase();
- if (promptLower.trim() &&
- Array.isArray(_knownUserLoras) &&
- Array.isArray(_activeLoras)) {
- const activePaths = new Set(_activeLoras.map(l => l.path));
- const orphans = []; // [{name, trigger}]
- const wordRe = /[a-z0-9]+/g;
- const promptTokens = new Set(promptLower.match(wordRe) || []);
- for (const ul of _knownUserLoras) {
- if (activePaths.has(ul.path)) continue;
- for (const w of (ul.trigger_words || [])) {
- if (!w) continue;
- const wLower = String(w).toLowerCase().trim();
- if (!wLower || wLower.length < 4) continue; // skip 1-3 char tokens, too common
- if (promptTokens.has(wLower)) {
- orphans.push({ name: ul.name || ul.filename || ul.path.split('/').pop(), trigger: w });
- break; // one match per LoRA is enough
- }
- }
- }
- if (orphans.length) {
- const lines = orphans.map(o => ` • "${o.trigger}" → ${o.name}`).join('\n');
- const ok = window.confirm(
- 'Your prompt mentions trigger word(s) from LoRA(s) that are NOT attached:\n\n' +
- lines + '\n\n' +
- 'The model will NOT reproduce these characters/styles. Toggle the LoRA on in the picker, then Generate.\n\n' +
- 'Generate without the LoRA anyway?'
- );
- if (!ok) { reenable(); return; }
- }
- }
- } catch (_) { /* never block submit on this check */ }
+// ====== Poll ======
+// Cache of the latest /status response so non-poll callers (setMode,
+// setQuality) can refresh tier-gated UI without waiting for the next tick.
+let LAST_STATUS = null;
- if (genBtn) genBtn.disabled = true;
+// Tracks consecutive /status failures so we can surface a panel-offline
+// banner instead of silently freezing the UI. Two-strike threshold so a
+// single transient hiccup (network blip, panel reload) doesn't flash.
+let _POLL_FAILS = 0;
- const noMusic = document.getElementById('noMusic');
- if (noMusic && noMusic.checked) {
- const original = fd.get('prompt') || '';
- const constraint = ' Audio: voice and ambient sounds only, no music, no soundtrack, no score, no melody.';
- if (!original.toLowerCase().includes('no music')) {
- fd.set('prompt', original.trim() + constraint);
+// Last 8 banner messages stay accessible from devtools at
+// `window._panelBannerLog` so a user who saw a flash but couldn't
+// read it can recover the message after the fact. Cheap insurance.
+window._panelBannerLog = window._panelBannerLog || [];
+
+function _setOfflineBanner(visible, msg) {
+ let bar = document.getElementById('panelOfflineBanner');
+ if (visible) {
+ const text = msg || "uploads, chat & renders are paused";
+ if (!bar) {
+ bar = document.createElement('div');
+ bar.id = 'panelOfflineBanner';
+ bar.className = 'panel-offline-banner';
+ bar.innerHTML =
+ '<span class="icon"><img src="/assets/favicon-64.png" alt=""></span>' +
+ '<span class="label">Phosphene offline</span>' +
+ '<span class="text"></span>' +
+ '<span class="hint">restart from Pinokio</span>';
+ document.body.appendChild(bar);
}
+ bar.classList.remove('reconnected');
+ bar.querySelector('.label').textContent = 'Phosphene offline';
+ bar.querySelector('.text').textContent = text;
+ bar.querySelector('.hint').textContent = 'restart from Pinokio';
+ const entry = `${new Date().toLocaleTimeString()} offline · ${text}`;
+ window._panelBannerLog.push(entry);
+ if (window._panelBannerLog.length > 8) window._panelBannerLog.shift();
+ console.warn('[phosphene] offline banner:', text);
+ } else if (bar && !bar.classList.contains('reconnected')) {
+ // Linger for 3s in a "back online" state instead of removing
+ // instantly. Salo flagged that he saw a banner flash during a
+ // restart but couldn't read it before it disappeared — this gives
+ // the eye time to register and gives the user a chance to scroll
+ // back in window._panelBannerLog if they want details.
+ bar.classList.add('reconnected');
+ bar.querySelector('.label').textContent = 'Phosphene reconnected';
+ bar.querySelector('.text').textContent = 'queue + renders resumed';
+ bar.querySelector('.hint').textContent = '';
+ const entry = `${new Date().toLocaleTimeString()} online · reconnected`;
+ window._panelBannerLog.push(entry);
+ if (window._panelBannerLog.length > 8) window._panelBannerLog.shift();
+ console.info('[phosphene] panel reconnected');
+ setTimeout(() => {
+ const b = document.getElementById('panelOfflineBanner');
+ if (b && b.classList.contains('reconnected')) b.remove();
+ }, 3000);
}
+}
+
+async function poll() {
+ let s;
+ const url = '/status' + (filterMode === 'hidden' ? '?include_hidden=1' : '');
try {
- await api('/queue/add','POST',fd);
- } finally {
- // Re-enable on the next event-loop tick so the button visibly
- // bounces rather than feeling "stuck on click". poll() refreshes
- // the queue right after, picking up the new job in the next ~1.5s.
- setTimeout(reenable, 200);
+ s = await (await fetch(url)).json();
+ _POLL_FAILS = 0;
+ _setOfflineBanner(false);
+ } catch (e) {
+ _POLL_FAILS += 1;
+ // Suppress the offline banner while a known long-running endpoint is
+ // in flight (e.g. /version/pull which blocks the server for ~30s on
+ // git fetch + git pull). Without this suppression the banner flashes
+ // "Phosphene offline → reconnected" at the tail of every successful
+ // Update click — looks like an error to the user when nothing is
+ // actually wrong.
+ if (_POLL_FAILS >= 2 && !window._suppressOfflineBanner) _setOfflineBanner(true);
+ return;
}
- poll();
-});
+ LAST_STATUS = s;
-// ====== Inline models card (top of form) ======
-// Displays what the current install needs RIGHT WHERE the user is about
-// to act. Beats burying the download CTA in a header modal. State picked
-// from /status: base missing → red blocker, current-mode-needs-Q8 →
-// amber prompt, downloading → animated progress, all-good → hidden.
-function updateModelsCard(s) {
- const card = document.getElementById('modelsInline');
- const icon = document.getElementById('modelsInlineIcon');
- const title = document.getElementById('modelsInlineTitle');
- const sub = document.getElementById('modelsInlineSub');
- const progress = document.getElementById('modelsInlineProgress');
- const fill = document.getElementById('modelsInlineFill');
- const last = document.getElementById('modelsInlineLast');
- const actions = document.getElementById('modelsInlineActions');
- if (!card) return;
+ // Memory
+ const m = s.memory;
+ const memPill = document.getElementById('memPill');
+ memPill.innerHTML = `<span class="dot"></span>${fmtMem(m)}`;
+ let memCls = 'pill-good';
+ if (m.swap_gb > 8 || m.pressure_pct > 90) memCls = 'pill-danger';
+ else if (m.swap_gb > 4 || m.pressure_pct > 75) memCls = 'pill-warn';
+ memPill.className = 'pill ' + memCls;
- const baseOk = !!s.base_available;
- const q8Ok = !!s.q8_available;
- const dl = s.download && s.download.active ? s.download : null;
- const tier = s.tier || {};
- const dismissed = !!(s.settings && s.settings.models_card_dismissed);
+ // Comfy (hidden when not running). Drives three things in lockstep —
+ // the status pill, the global Stop Comfy button, and the per-render
+ // "Stop ComfyUI before render" checkbox in the form. The checkbox row
+ // stays hidden when Comfy isn't running so users who don't have Comfy
+ // installed never see a cryptic toggle.
+ const cp = document.getElementById('comfyPill');
+ const stopBtn = document.getElementById('stopComfyBtn');
+ const comfyRow = document.getElementById('comfyKillRow');
+ const comfyToggle = document.getElementById('stop_comfy');
+ if (s.comfy_pids.length) {
+ cp.innerHTML = `<span class="dot"></span>Comfy ${s.comfy_pids.join(', ')}`;
+ cp.className = 'pill pill-warn'; cp.style.display = '';
+ stopBtn.style.display = '';
+ if (comfyRow) comfyRow.style.display = '';
+ } else {
+ cp.style.display = 'none';
+ stopBtn.style.display = 'none';
+ if (comfyRow) comfyRow.style.display = 'none';
+ // When Comfy isn't running, also force the form value off so the
+ // submission doesn't carry a meaningless `stop_comfy=on` server-side.
+ if (comfyToggle) comfyToggle.checked = false;
+ }
- // Reset state classes — we set the right one below.
- card.classList.remove('state-missing', 'state-warn', 'state-downloading', 'dismissible');
- progress.style.display = 'none';
+ // Helper
+ const hp = document.getElementById('helperPill');
+ if (s.helper && s.helper.alive) {
+ hp.innerHTML = `<span class="dot"></span>helper warm`;
+ hp.className = 'pill pill-good';
+ hp.title = 'Helper subprocess is loaded with pipelines and ready.';
+ } else {
+ // Helper auto-respawns on the next job (see WarmHelper._ensure). "Cold"
+ // is normal after the idle timeout, not an error — first job after a
+ // cold start eats a ~30s pipeline-load cost.
+ hp.innerHTML = `<span class="dot"></span>helper idle`;
+ hp.className = 'pill';
+ hp.title = 'Helper is idle (auto-exited after the idle timeout). The next queued job will respawn it; expect a one-time ~30s pipeline-load delay.';
+ }
- // ----- Active download takes precedence over everything ------------------
+ // Tier pill — what this Mac's RAM tier allows. Click to open the
+ // explanation modal. Color is informational, not warning: the tier is
+ // what it is, not "wrong".
+ const tp = document.getElementById('tierPill');
+ if (s.tier) {
+ const t = s.tier;
+ const cls = t.key === 'base' ? 'pill-warn'
+ : (t.key === 'pro' ? 'pill-good' : '');
+ // Show the friendly label ("Compact" / "Comfortable" / "Roomy" /
+ // "Studio") not the internal key. Click opens the explanation modal.
+ tp.innerHTML = `<span class="dot"></span>${escapeHtml(t.label || t.key)}`;
+ tp.className = 'pill ' + cls;
+ tp.title = `${t.label} (${t.ram_label}) · ${t.tagline} · click for details`;
+ // Apply tier-driven enabled/disabled state to mode + quality pills.
+ // Done here in poll() so a tier override (env var) flips state on
+ // panel restart without needing to also change a separate setMode call.
+ applyTierGates(t);
+ }
+
+ // Models pill — roll-up status: base ready / Q8 ready, plus active download.
+ // Renders as one of:
+ // "models ↓ Q4 12%" while a download streams (live progress, last hf line)
+ // "models 3/3" all on disk
+ // "models 2/3" base ready, Q8 missing → warn color
+ // "models 0/3" base incomplete → bad color
+ const mp = document.getElementById('modelsPill');
+ const dl = s.download && s.download.active ? s.download : null;
if (dl) {
- card.style.display = '';
- card.classList.add('state-downloading');
- icon.textContent = '↓';
- const labelByKey = { q4: 'Q4 base model', gemma: 'Gemma text encoder', q8: 'Q8 high-quality model' };
- title.textContent = `Downloading ${labelByKey[dl.key] || dl.repo_id}`;
- const elapsed = Math.max(0, Math.round((Date.now()/1000) - (dl.started_ts || 0)));
- sub.textContent = `${elapsed}s elapsed · resumable if interrupted`;
- progress.style.display = '';
- // Try to extract a percent from the last hf line (tqdm format).
- const m = (dl.last_line || '').match(/\b(\d{1,3})%/);
- fill.style.width = m ? `${Math.min(100, parseInt(m[1]))}%` : '15%';
- last.textContent = dl.last_line || 'starting…';
- actions.innerHTML = `<button class="danger" onclick="cancelDownload()">Cancel</button>`;
- return;
+ const elapsed = Math.max(0, Math.round(s.server_now - (dl.started_ts || s.server_now)));
+ mp.innerHTML = `<span class="dot"></span>↓ ${dl.key} · ${elapsed}s`;
+ mp.className = 'pill pill-running';
+ mp.title = `Downloading ${dl.repo_id} — ${dl.last_line || 'starting…'}`;
+ } else {
+ // Per-repo ready/total counts, matches what the modal shows (3 rows by
+ // default: Q4 + Gemma + Q8). base_available is a roll-up bool that
+ // honors the HF-id env-var short-circuit; we use it for the color
+ // hint, not the count itself.
+ const baseOk = s.base_available;
+ const q8Ok = s.q8_available;
+ const ready = s.repos_ready ?? 0;
+ const total = s.repos_total ?? 0;
+ mp.innerHTML = `<span class="dot"></span>models ${ready}/${total}`;
+ mp.className = 'pill ' + (!baseOk ? 'pill-warn' : (q8Ok ? 'pill-good' : ''));
+ mp.title = !baseOk
+ ? 'Base models incomplete — click to download'
+ : (q8Ok ? 'All models on disk' : 'Q8 not installed (optional — needed for High quality + FFLF)');
+ }
+ // If the modal is open, refresh its rows on each poll so progress updates.
+ if (document.getElementById('modelsModal').style.display !== 'none') {
+ refreshModelsModal({ silent: true });
}
+ // Inline models card — top-of-form, big, can't miss it. State logic
+ // lives in updateModelsCard so we don't bloat poll() further.
+ updateModelsCard(s);
- // ----- Base missing — hard block, the panel can't render anything --------
- if (!baseOk) {
- card.style.display = '';
- card.classList.add('state-missing');
- icon.innerHTML = '<svg class="ph" aria-hidden="true"><use href="#ph-warning-fill"/></svg>';
- title.textContent = 'Base models needed before you can render';
- const missing = (s.base_missing || []).length;
- sub.innerHTML = `Q4 (~20 GB) and Gemma (~6 GB) are required. Click below — downloads resume if interrupted.${
- missing ? ` <span style="color:var(--muted)">(${missing} files left)</span>` : ''
- }`;
- actions.innerHTML = (s.hf_available ?? true)
- ? `<button onclick="startDownload('q4')">Download Q4 (20 GB)</button>`
- : `<button disabled title="hf binary not found — reinstall via Pinokio">hf missing</button>`;
- return;
+ // Queue pill + tab badge. Animate the bottom-pane Queue badge with
+ // a brief scale-up "pop" when the count goes up — draws the eye to
+ // the badge so the user notices that a new job got queued without
+ // having to watch the strip. CSS .badge.bump handles the keyframes;
+ // we just toggle the class for ~280 ms.
+ const qp = document.getElementById('queuePill');
+ qp.innerHTML = `<span class="dot"></span>queue ${s.queue.length}${s.paused ? ' · paused' : ''}`;
+ qp.className = 'pill ' + (s.paused ? 'pill-warn' : (s.queue.length ? 'pill-running' : ''));
+ const qb = document.getElementById('queueBadge');
+ const prevQueueLen = window._lastQueueLen ?? 0;
+ if (s.queue.length) {
+ qb.textContent = s.queue.length;
+ qb.style.display = '';
+ if (s.queue.length > prevQueueLen) {
+ qb.classList.remove('bump');
+ // Re-trigger the CSS animation by toggling the class after a
+ // reflow. Without the rAF the second add doesn't re-fire.
+ requestAnimationFrame(() => {
+ qb.classList.add('bump');
+ setTimeout(() => qb.classList.remove('bump'), 320);
+ });
+ }
+ } else {
+ qb.style.display = 'none';
+ }
+ window._lastQueueLen = s.queue.length;
+
+ // Job pill
+ const jp = document.getElementById('jobPill');
+ if (s.running && s.current) {
+ const elapsed = Math.max(0, Math.round(s.server_now - s.current.started_ts));
+ jp.innerHTML = `<span class="dot"></span>${s.current.params.label || s.current.params.mode} · ${elapsed}s`;
+ jp.className = 'pill pill-running';
+ } else {
+ jp.innerHTML = `<span class="dot"></span>idle`;
+ jp.className = 'pill';
}
- // ----- User picked a mode that needs Q8, but Q8 isn't there --------------
- // FFLF + Extend + High quality all need Q8. Surface the CTA *only* when
- // the user is about to do one of those — no point nagging a T2V user
- // about Q8 if they'll never use it.
- // Dismissible: a user who deliberately doesn't want Q8 (storage budget,
- // they only do T2V Quick/Standard) can × this away and we'll respect it
- // until either model state changes or they re-summon the modal.
- // Y1.036 — Extend joins FFLF and High in needing Q8. The Extend pipeline
- // loads `transformer-dev.safetensors` for CFG-guided denoise; Q4 doesn't
- // ship it after the Y1.024 download trim, so surface the same CTA here.
- const needsQ8 = (currentMode === 'keyframe')
- || (currentMode === 'extend')
- || (document.getElementById('quality').value === 'high');
- if (needsQ8 && !q8Ok && tier.allows_q8 !== false) {
- if (dismissed) { card.style.display = 'none'; return; }
- card.style.display = '';
- card.classList.add('state-warn', 'dismissible');
- icon.innerHTML = '<svg class="ph" aria-hidden="true"><use href="#ph-download-simple"/></svg>';
- const reason = currentMode === 'keyframe' ? 'FFLF needs the Q8 model'
- : currentMode === 'extend' ? 'Extend needs the Q8 model'
- : 'High quality needs the Q8 model';
- title.textContent = reason;
+ document.getElementById('pauseBtn').textContent = s.paused ? 'Resume queue' : 'Pause queue';
+
+ // Q8 / High enable. Subtitle shows what pipeline this chip uses; goes
+ // visible permanently (no more `hidden` attribute on the span) so users
+ // can see at a glance which engine drives each tier.
+ const highBtn = document.getElementById('qualityHigh');
+ const highSub = document.getElementById('highSub');
+ if (s.q8_available) {
+ highBtn.classList.remove('disabled', 'needs-install');
+ highSub.textContent = 'Q8 Pro · 7 min';
+ } else {
+ // Disabled-but-actionable: a click on the High pill now opens the
+ // Models modal so the user can install Q8 in one move instead of
+ // hunting for the download. CSS .needs-install gives the pill an
+ // accent-tinted look + download arrow in the subtitle so it reads
+ // as a CTA, not a dead button.
+ highBtn.classList.add('disabled', 'needs-install');
const missing = (s.q8_missing || []).length;
- sub.innerHTML = `Q8 (~37 GB) is a separate one-time download. Resumable.${
- missing && missing < 8 ? ` <span style="color:var(--muted)">(${missing} files left — partial install detected)</span>` : ''
- }`;
- actions.innerHTML = (s.hf_available ?? true)
- ? `<button onclick="startDownload('q8')">Download Q8 (37 GB)</button>`
- : `<button disabled>hf missing</button>`;
- return;
+ if (missing > 0 && missing < 6) {
+ highSub.textContent = `Q8 downloading · ${missing} left`;
+ highBtn.classList.remove('needs-install'); // mid-download, no need for the CTA hint
+ } else {
+ highSub.textContent = 'Install Q8 (37 GB)';
+ }
+ if (document.getElementById('quality').value === 'high') setQuality('standard');
}
- // ----- All good — hide the card completely -------------------------------
- // Per user feedback: the "Models ready · 3/3" status was visual noise once
- // everything was downloaded. Hide the card on full readiness; the header
- // models pill still gives a way to reopen the modal if the user wants to
- // manage repos. If state regresses (a file gets deleted, partial download
- // appears), one of the branches above re-shows it automatically.
- const allReady = baseOk && q8Ok;
- if (allReady) {
- card.style.display = 'none';
- actions.innerHTML = '';
- return;
+ // Balanced subtitle: on the "standard" (48–79 GB) tier with Q8 installed,
+ // the Balanced chip auto-routes to Q8 Fast (safe_a config) — but ONLY for
+ // mode ∈ {t2v, a2v} and frames ≤ 121, which is what the 64 GB memory
+ // budget actually fits. Other combos fall back to Q4 Balanced. The
+ // subtitle reflects the user's current selection so they see what they
+ // will actually get when they hit Generate. Re-evaluated on every poll
+ // and on mode/frames change (see the listener wired at DOMContentLoaded
+ // below this function).
+ window.__phosLastStatus = s;
+ if (typeof window.refreshBalancedSubtitle === 'function') {
+ window.refreshBalancedSubtitle(s);
}
- // ----- Partial-OK quiet state ---------------------------------------------
- // Base OK but Q8 missing on a tier that supports it AND the user hasn't
- // picked a Q8-needing mode — gentle nudge in neutral colours, dismissible.
- if (dismissed) { card.style.display = 'none'; return; }
- card.style.display = '';
- card.classList.add('dismissible');
- icon.innerHTML = '<svg class="ph" aria-hidden="true"><use href="#ph-check-bold"/></svg>';
- const ready = s.repos_ready ?? 0;
- const total = s.repos_total ?? 0;
- title.textContent = `Models ready · ${ready}/${total}`;
- const partialNote = (q8Ok && baseOk) ? '' : ` · ${total - ready} optional missing`;
- sub.innerHTML =
- `All installed weights detected${partialNote}. ` +
- `<a style="color:var(--accent-bright,#7e98ff); cursor:pointer; text-decoration:underline" onclick="openModelsModal()">Manage models →</a>`;
- actions.innerHTML = '';
-}
-// Persist the "user dismissed the models card" flag. POSTs to /settings
-// and re-runs updateModelsCard with the latest status so the card hides
-// immediately (not after the next /status poll cycle, ~5s away).
-async function dismissModelsCard() {
- try {
- const fd = new URLSearchParams();
- fd.set('models_card_dismissed', 'true');
- await fetch('/settings', {
- method: 'POST',
- headers: {'Content-Type': 'application/x-www-form-urlencoded'},
- body: fd,
- });
- } catch (e) { /* best effort — UI still hides locally on next poll */ }
- // Optimistically hide right now without waiting for the poll round-trip.
- const card = document.getElementById('modelsInline');
- if (card) card.style.display = 'none';
- // Patch LAST_STATUS so subsequent updateModelsCard calls before the next
- // /status fetch agree with the on-disk state.
- if (LAST_STATUS && LAST_STATUS.settings) {
- LAST_STATUS.settings.models_card_dismissed = true;
+ // Keyframe (FFLF) and Extend both require Q8 — server enforces it (see
+ // run_job_inner). The UI was previously silently downgrading the user to
+ // Standard when they picked keyframe with Q8 missing, then the server
+ // would 500 on submit. Disable Generate + show a clear reason while in
+ // that state. Y1.036 added Extend to the same gate after the Y1.024
+ // download trim exposed that Extend is structurally Q8-class.
+ const genBtn = document.getElementById('genBtn');
+ const q8GatedMode = (currentMode === 'keyframe' || currentMode === 'extend');
+ if (q8GatedMode && !s.q8_available) {
+ genBtn.disabled = true;
+ const modeName = currentMode === 'keyframe' ? 'Keyframe (FFLF)' : 'Extend';
+ const left = (s.q8_missing || []).length;
+ genBtn.title = left > 0 && left < 6
+ ? `${modeName} needs Q8 — ${left} file(s) still downloading.`
+ : `${modeName} needs the Q8 model. Click "Download Q8 (~37 GB)" in Pinokio.`;
+ genBtn.textContent = 'Generate · Q8 required';
+ } else if (genBtn.disabled && genBtn.textContent.startsWith('Generate · Q8')) {
+ // Restore — only do so if WE were the ones who disabled it, otherwise
+ // some future code path that disables Generate for a different reason
+ // would get clobbered here.
+ genBtn.disabled = false;
+ genBtn.title = '';
+ genBtn.textContent = 'Generate';
}
-}
-// ====== Tier gating ======
-// Disables the FFLF / Extend mode pills and the High quality pill when
-// the detected hardware tier doesn't support them. Visual state +
-// tooltip + intercepted clicks. Run from the poll handler so an env
-// override flips state on restart.
-function applyTierGates(tier) {
- // Mode pills
- document.querySelectorAll('#modeGroup .pill-btn').forEach(b => {
- const m = b.dataset.mode;
- const allowed = (m === 'keyframe') ? tier.allows_keyframe
- : (m === 'extend') ? tier.allows_extend
- : true;
- b.classList.toggle('disabled', !allowed);
- if (!allowed) {
- const need = m === 'keyframe'
- ? 'first/last-frame interpolation needs more memory than this Mac has — try Image → Video instead'
- : 'extending an existing clip needs more memory than this Mac has — try Image → Video instead';
- b.title = `Off on the ${tier.label} tier · ${need}`;
+ // Now card
+ // Y1.039 — bar + meta line driven by server-computed progress (phase-aware,
+ // config-bucketed ETA, denoise per-step extrapolation). Falls back to the
+ // old elapsed/global-avg behavior if the server didn't ship a progress
+ // block (e.g. mid-deploy where the server is older than the JS).
+ const nowCard = document.getElementById('nowCard');
+ const fill = document.getElementById('progressFill');
+ // The Now-card Stop button is gone — both the video form's Stop and
+ // the Image Studio's Stop now live in the form-pane and stay
+ // visible across mode switches, so a Now-card duplicate is no
+ // longer needed.
+ if (s.running && s.current) {
+ nowCard.classList.remove('idle', 'failed');
+ const prog = s.current.progress || null;
+ const elapsedFallback = Math.max(0, s.server_now - s.current.started_ts);
+ let pct, elapsed, phaseLabel, timing;
+ if (prog) {
+ pct = Math.min(99, Math.max(0, prog.pct ?? 0));
+ elapsed = prog.elapsed_sec ?? elapsedFallback;
+ phaseLabel = prog.phase_label || 'Working';
+ if (prog.remaining_sec != null && prog.remaining_sec > 0) {
+ timing = `<strong>${fmtMin(elapsed)}</strong> in · ~${fmtMin(prog.remaining_sec)} left`;
+ } else if (prog.eta_sec) {
+ timing = `<strong>${fmtMin(elapsed)}</strong> / ~${fmtMin(prog.eta_sec)}`;
+ } else {
+ timing = `<strong>${fmtMin(elapsed)}</strong> elapsed`;
+ }
+ } else {
+ // Legacy fallback path
+ const avg = s.avg_elapsed_sec || 420;
+ pct = Math.min(99, Math.round(elapsedFallback / avg * 100));
+ elapsed = elapsedFallback;
+ phaseLabel = '';
+ timing = `<strong>${fmtMin(elapsed)}</strong> elapsed${avg ? ' / ~'+fmtMin(avg)+' avg' : ''}`;
+ }
+ fill.style.width = pct + '%';
+ nowCard.querySelector('.ttl').textContent = snippet(s.current.params.label || s.current.params.prompt, 80);
+ // Image jobs don't have width/height/frames; show n × aspect instead.
+ // Falls through to the video shape when those fields ARE present.
+ const cur = s.current.params;
+ const baseMeta = (cur.mode === 'image')
+ ? `image · ${cur.aspect || '?'} · n=${cur.n || '?'} · ${cur.engine_override || 'auto'} · ${timing}`
+ : `${cur.mode} · ${cur.width}×${cur.height} · ${cur.frames}f · ${timing}`;
+ nowCard.querySelector('.meta').innerHTML = phaseLabel
+ ? `${baseMeta}<br><span style="color:var(--muted)">${escapeHtml(phaseLabel)}</span>`
+ : baseMeta;
+ } else {
+ // Idle state. If the LAST history entry was a failure (helper crash,
+ // OOM, etc.) surface it loud-and-clear here — otherwise users like
+ // cocktailpeanut just see "Idle" and assume "the panel did nothing."
+ // We hold the failure visible until the user starts a new job.
+ fill.style.width = '0%';
+ const last = (s.history || [])[0];
+ // Salo flagged that a stuck "Job failed" card with no close button
+ // is disruptive — once a render fails, the surface holds the message
+ // visible until the next job runs, with no way to acknowledge it.
+ // _dismissedFailureId remembers which job id the user chose to
+ // dismiss so we don't keep nagging. Clears on next job (id changes).
+ const showFailure = last && last.status === 'failed' && !s.queue.length
+ && last.id !== window._dismissedFailureId;
+ const actionsEl = document.getElementById('nowCardActions');
+ if (showFailure) {
+ nowCard.classList.remove('idle');
+ nowCard.classList.add('failed');
+ // Translate cryptic engine errors into actionable user guidance.
+ // "helper died mid-job (no event)" is the SIGKILL-by-jetsam
+ // signature on memory-pressured Macs — the helper subprocess gets
+ // killed by the OS for using too much RAM and we never get an
+ // event back. Tell the user how to recover instead of leaving them
+ // with the engine wording.
+ const raw = (last.error || 'unknown error');
+ const rawLower = raw.toLowerCase();
+ let friendly, hint;
+ if (rawLower.includes('sigkill')) {
+ friendly = 'Helper killed by the OS — out of memory (jetsam).';
+ hint = 'Close memory-heavy apps (Chrome, Slack, iOS Simulator) and try again, ' +
+ 'or switch Quality to Quick (about half the RAM).';
+ } else if (rawLower.includes('sigsegv') || rawLower.includes('sigbus')) {
+ friendly = 'Helper crashed at the native level (MLX/Metal fault).';
+ hint = 'Share the crashlog at ~/Library/Logs/DiagnosticReports/python3.11_*.crash ' +
+ 'on github.com/mrbizarro/phosphene/issues so we can fix it.';
+ } else if (rawLower.includes('sigabrt')) {
+ friendly = 'Helper hit a C-level assertion and aborted.';
+ hint = 'Share the crashlog at ~/Library/Logs/DiagnosticReports/python3.11_*.crash ' +
+ 'on github.com/mrbizarro/phosphene/issues.';
+ } else if (rawLower.includes('helper exited from') || rawLower.includes('helper pipe closed') ||
+ rawLower.includes('helper died') || rawLower.includes('helper exited')) {
+ friendly = 'Helper exited unexpectedly.';
+ hint = 'Check the log for the last "step:*" breadcrumb (tells us which ' +
+ 'phase died). If memory-pressured, close other apps and retry.';
+ } else if (rawLower.includes('q8') || rawLower.includes('keyframe')) {
+ friendly = 'This mode needs the Q8 model.';
+ hint = raw;
+ } else {
+ friendly = 'Job failed.';
+ hint = raw;
+ }
+ nowCard.querySelector('.ttl').innerHTML =
+ `<span style="color: var(--danger, #f85149)"><svg class="ph" aria-hidden="true" style="margin-right:4px;vertical-align:-2px"><use href="#ph-warning-fill"/></svg>${escapeHtml(friendly)}</span>`;
+ nowCard.querySelector('.meta').innerHTML =
+ `<span style="color: var(--muted)">${escapeHtml(snippet(last.params.label || last.params.prompt, 80))}</span>` +
+ ` <span style="color: var(--muted)">· ${escapeHtml(last.params.mode)} · ${last.params.width}×${last.params.height}</span>` +
+ `<br><span style="color: var(--text)">${escapeHtml(hint)}</span>`;
+ // Action row: Retry (re-submit same params via /queue/retry) +
+ // Dismiss (mark this id as handled so the next idle poll clears
+ // the card). Both buttons live in a stable sibling element of
+ // .ttl so the click handlers survive every poll-driven rewrite.
+ // A single delegated listener on document (installed once at
+ // boot) catches the clicks via data-action so we never lose them
+ // to an inline-handler race.
+ if (actionsEl) {
+ actionsEl.dataset.jobId = String(last.id);
+ actionsEl.innerHTML =
+ `<button type="button" class="now-card-retry" data-action="retry" ` +
+ `title="Re-submit this job with the same params">` +
+ `<svg class="ph" aria-hidden="true"><use href="#ph-arrow-clockwise"/></svg>` +
+ `<span>Retry</span></button>` +
+ `<button type="button" class="now-card-dismiss" data-action="dismiss" ` +
+ `title="Dismiss this failure" aria-label="Dismiss this failure">` +
+ `<svg class="ph" aria-hidden="true"><use href="#ph-x-bold"/></svg></button>`;
+ }
} else {
- b.title = '';
+ nowCard.classList.add('idle');
+ nowCard.classList.remove('failed');
+ nowCard.querySelector('.ttl').textContent = s.paused ? 'Paused' : 'Idle';
+ nowCard.querySelector('.meta').textContent = s.paused
+ ? 'Worker paused — current job (if any) finishes, queue waits for resume.'
+ : (s.queue.length ? 'Worker about to pick up next queued job.' : 'No jobs queued. Generate something on the left.');
+ if (actionsEl) { actionsEl.innerHTML = ''; actionsEl.dataset.jobId = ''; }
}
- });
- // Quality: High requires Q8. We already disable based on q8_available
- // for the no-download case; this layer enforces the RAM tier on top.
- // Both layers can disable — we OR them together via a class.
- const highBtn = document.getElementById('qualityHigh');
- if (highBtn) {
- if (!tier.allows_q8) {
- highBtn.classList.add('disabled');
- highBtn.title = `Off on the ${tier.label} tier · the high-quality model needs more memory than this Mac has`;
+ }
+
+ // Y2.001 — bottom-pane live dot mirrors worker state. Tooltip sets
+ // a one-line status for accessibility / hover. The dot animates
+ // when running, switches red on the failed state.
+ const liveDot = document.getElementById('bpLiveDot');
+ if (liveDot) {
+ liveDot.classList.remove('live', 'failed');
+ if (s.running && s.current) {
+ liveDot.classList.add('live');
+ liveDot.title = 'Rendering';
} else {
- // Don't unconditionally clear .disabled — the Q8-not-installed code
- // path also sets it. Only clear if the tier is the only reason.
- // The poll() code that checks q8_available re-applies that state
- // every cycle, so this branch is safe to unset.
- highBtn.title = '';
+ const last = (s.history || [])[0];
+ const showFailure = last && last.status === 'failed' && !s.queue.length;
+ if (showFailure) { liveDot.classList.add('failed'); liveDot.title = 'Last job failed'; }
+ else if (s.paused) liveDot.title = 'Paused';
+ else if (s.queue.length) liveDot.title = `${s.queue.length} queued`;
+ else liveDot.title = 'Idle';
}
}
-}
-// Intercept clicks on disabled mode pills so users get a helpful message
-// instead of a broken-feeling no-op.
-document.addEventListener('click', (e) => {
- const btn = e.target.closest('#modeGroup .pill-btn.disabled');
- if (btn) {
- e.stopPropagation();
- e.preventDefault();
- alert(btn.title || 'This mode is not supported on this hardware tier.');
+
+ // (The in-player progress overlay used to be wired here; it was
+ // removed 2026-05-12 because it duplicated the bottom Now strip and
+ // covered the playing video. Bottom strip is the single source.)
+
+ // Logs
+ const log = document.getElementById('log');
+ const wasNearBottom = log.scrollHeight - log.scrollTop - log.clientHeight < 60;
+ log.textContent = s.log.length ? s.log.join('\n') : 'No log yet.';
+ if (wasNearBottom) log.scrollTop = log.scrollHeight;
+
+ // Queue list — memoized on a signature of the IDs + ordinals so
+ // identical queue data doesn't trigger a full innerHTML replacement
+ // every 1.5 s. Pre-fix every poll() rebuilt all <li> nodes which
+ // caused a perceptible flicker on the Queue tab during long batches.
+ const ql = document.getElementById('queueList');
+ const qSig = !s.queue.length ? '__empty__'
+ : s.queue.map(j => j.id).join('|');
+ if (qSig !== window._lastQueueSig) {
+ if (!s.queue.length) ql.innerHTML = '<li class="empty-state"><span></span><span>Queue empty</span><span></span><span></span></li>';
+ else ql.innerHTML = s.queue.map((j, i) => {
+ // Image jobs don't have width/height/frames; show n × aspect instead.
+ const params = (j.params.mode === 'image')
+ ? `image · ${j.params.aspect || '?'} · n=${j.params.n || '?'}`
+ : `${j.params.mode} · ${j.params.width}×${j.params.height} · ${j.params.frames}f`;
+ return `
+ <li>
+ <span class="pos">#${i+1}</span>
+ <span class="ttl" title="${escapeHtml(j.params.prompt)}">${escapeHtml(j.params.label || snippet(j.params.prompt, 60))}</span>
+ <span class="params">${params}</span>
+ <button title="Remove" onclick="removeJob('${j.id}')"><svg class="ph" aria-hidden="true"><use href="#ph-x-bold"/></svg></button>
+ </li>`;
+ }).join('');
+ window._lastQueueSig = qSig;
}
-}, true);
-// ====== Tier modal ======
-function openTierModal() {
- const modal = document.getElementById('tierModal');
- modal.style.display = 'flex';
- // Defensive: show "loading" state immediately so the modal never appears
- // with the body completely blank (which is what happens if the panel
- // process is dead and fetch fails — looked like a "buggy bug" to a user
- // who was just kicked off a stale browser view).
- document.getElementById('tierModalTitle').textContent = 'Hardware tier';
- document.getElementById('tierModalBlurb').innerHTML = '<em>Loading…</em>';
- document.getElementById('tierCapsList').innerHTML = '';
- // Tier doesn't change at runtime — RAM is fixed at boot — so a single
- // fetch on open is plenty. No need for live polling here.
- fetch('/status').then(r => r.json()).then(s => {
- const t = s.tier || {};
- const tt = t.times || {};
- // Helper: a row is "available" if it's allowed; "max" is the friendly
- // size limit (or "Any size" / "—" when there is no limit / disabled).
- const sizeLine = (on, maxDim, fallback) => {
- if (!on) return fallback || 'Not available on this Mac';
- if (!maxDim) return 'Any size';
- return `Up to ${maxDim} pixels on the longer side`;
- };
- document.getElementById('tierModalTitle').textContent = `What this Mac can do · ${t.label || 'unknown'}`;
- document.getElementById('tierModalBlurb').innerHTML = `
- <div style="margin-bottom: 6px"><strong>${escapeHtml(t.label || '')}</strong> · ${escapeHtml(t.ram_label || '')} of memory</div>
- <div>${escapeHtml(t.blurb || '')}</div>`;
- // One row per mode/option, with three pieces of info each:
- // - is it available? (✓ / ✗)
- // - what's the size limit? (plain English)
- // - how long does a typical 5-second render take? (rough estimate)
- const items = [
- {
- title: 'Text → video',
- desc: 'Type a prompt, get a clip. The default mode.',
- on: true,
- size: sizeLine(true, t.t2v_max_dim),
- time: tt.t2v_standard,
- },
- {
- title: 'Image → video',
- desc: 'Drop in a still, get it animated. Same speed as text → video.',
- on: true,
- size: sizeLine(true, t.i2v_max_dim),
- time: tt.i2v_standard,
- },
- {
- title: 'Quick (640×480)',
- desc: 'Smaller preview to scout prompts and seeds before a full-size render.',
- on: true,
- size: 'Always smaller than Standard',
- time: tt.t2v_draft,
- },
- {
- title: 'High quality',
- desc: 'Bigger model, two-stage denoising, sharper faces. Needs the optional Q8 download.',
- on: !!t.allows_q8,
- size: sizeLine(!!t.allows_q8, 0, 'Needs more memory than this Mac has'),
- time: tt.high,
- },
- {
- title: 'First / last frame (FFLF)',
- desc: 'Pick a start image and an end image, the model fills the motion between.',
- on: !!t.allows_keyframe,
- size: sizeLine(!!t.allows_keyframe, t.keyframe_max_dim, 'Needs more memory than this Mac has'),
- time: tt.keyframe,
- },
- {
- title: 'Extend an existing clip',
- desc: 'Pick a video you already rendered, the model adds more time onto either end.',
- on: !!t.allows_extend,
- size: sizeLine(!!t.allows_extend, t.extend_max_dim, 'Needs more memory than this Mac has'),
- time: tt.extend,
- },
- ];
- document.getElementById('tierCapsList').innerHTML = items.map(it => `
- <li class="${it.on ? 'ready' : 'missing'}">
- <span class="icon"><svg class="ph" aria-hidden="true"><use href="${it.on ? '#ph-check-bold' : '#ph-x-circle-fill'}"/></svg></span>
- <div class="meta">
- <span class="ttl">${escapeHtml(it.title)}</span>
- <span class="sub">${escapeHtml(it.desc)}</span>
- <span class="sub" style="margin-top:2px">
- <span style="color:var(--fg,#d8e0ee)">${escapeHtml(it.size)}</span>${
- it.time ? ` · <span style="color:var(--accent-bright,#7e98ff)">~ ${escapeHtml(it.time)} for a 5-second clip</span>` : ''
- }
- </span>
- </div>
- <span></span>
- </li>`).join('');
- }).catch(err => {
- // Panel might be dead, status endpoint unreachable, or response not JSON.
- // Replace the loading state with a visible error so the modal doesn't
- // look "broken" with empty content.
- document.getElementById('tierModalBlurb').innerHTML =
- '<div style="color: var(--danger, #f85149)">Could not load tier info — the panel server may have stopped responding. Check the Pinokio terminal and restart the panel if needed.</div>';
- document.getElementById('tierCapsList').innerHTML = '';
- console.error('tier modal fetch failed:', err);
+ // History — failed jobs show the error inline in the title slot, so
+ // users can see WHY without having to scroll the log to find it.
+ // mode='image' jobs render with a thumbnail of the first candidate
+ // and an Animate button that pre-fills the i2v form (does NOT
+ // auto-submit — user keeps the chance to tweak prompt/seed).
+ const hl = document.getElementById('historyList');
+ // Apply the All / Videos / Photos filter (set by setRecentFilter).
+ const filterPhotos = (window.recentFilter || 'all');
+ const filtered = s.history.filter(j => {
+ if (filterPhotos === 'all') return true;
+ const isPhoto = (j.params && j.params.mode === 'image');
+ return filterPhotos === 'photos' ? isPhoto : !isPhoto;
});
-}
-function closeTierModal() { document.getElementById('tierModal').style.display = 'none'; }
+ if (!filtered.length) {
+ const empty = filterPhotos === 'photos' ? 'No photo renders yet'
+ : filterPhotos === 'videos' ? 'No video renders yet'
+ : 'No history yet';
+ hl.innerHTML = `<li class="empty-state"><span></span><span>${empty}</span><span></span><span></span></li>`;
+ }
+ else hl.innerHTML = filtered.slice(0, 20).map(j => {
+ const titleText = escapeHtml(j.params.label || snippet(j.params.prompt, 60));
+ const titleAttr = escapeHtml(j.params.prompt || '');
+ let titleHtml;
+ if (j.status === 'failed' && j.error) {
+ titleHtml = `${titleText} ` +
+ `<span class="err-inline" title="${escapeHtml(j.error)}">— ${escapeHtml(snippet(j.error, 70))}</span>`;
+ } else {
+ titleHtml = titleText;
+ }
+ // Image rows get a thumbnail + Animate button; video rows keep
+ // the existing 4-column shape so the layout doesn't shift.
+ const isPhoto = (j.params && j.params.mode === 'image');
+ if (isPhoto && j.status === 'done' && j.output_path) {
+ const cands = (j.params.candidate_paths && j.params.candidate_paths.length)
+ ? j.params.candidate_paths.length : 1;
+ const engineLabel = escapeHtml(j.params.engine || 'image');
+ // Reuse the server-built mtime-versioned URL when available
+ // (currentOutputs has each entry's `&v=<mtime>` cache-bust),
+ // falling back to a plain URL otherwise. Each job's output_path
+ // is immutable post-completion, so no Date.now() bust is needed
+ // — and it WAS the source of the carousel hot-loop: this list
+ // re-renders every ~1s poll tick, so a `&t=${Date.now()}` on
+ // every photo row caused ~16 thumbnail re-fetches per tick
+ // (~50-60 req/s steady-state idle) that defeated the cache.
+ const matchedOutput = (currentOutputs || []).find(x => x.path === j.output_path);
+ const thumbSrc = matchedOutput
+ ? matchedOutput.url
+ : `/image?path=${encodeURIComponent(j.output_path)}`;
+ const animateArgs = JSON.stringify({
+ path: j.output_path, prompt: j.params.prompt || ''
+ }).replace(/"/g, '&quot;');
+ return `
+ <li class="${j.status}" data-photo="1">
+ <span class="badge">photo</span>
+ <span class="ttl photo-ttl" title="${titleAttr}">
+ <img class="photo-thumb" src="${thumbSrc}" alt=""
+ style="width:36px;height:36px;object-fit:cover;border-radius:4px;vertical-align:middle;margin-right:6px">
+ ${titleHtml}
+ <span class="photo-meta hint" style="margin-left:6px;font-size:11px;opacity:0.7">${cands}× · ${engineLabel}</span>
+ </span>
+ <span class="params">${fmtMin(j.elapsed_sec)} · ${j.finished_at ? j.finished_at.slice(11) : ''}</span>
+ <span><button class="animate-btn" type="button"
+ onclick='animateFromPhoto(${animateArgs})' title="Pre-fill i2v with this image (does not auto-submit)">Animate</button></span>
+ </li>`;
+ }
+ // Failed jobs get a Retry button in the action column. Clicking it
+ // re-submits the same params via /queue/add so the user doesn't have
+ // to rebuild the form. Cancelled jobs get the same treatment — a
+ // cancellation often means "wrong intent, try again with edits" but
+ // sometimes "ran out of RAM, want to retry as-is."
+ const isRetryable = j.status === 'failed' || j.status === 'cancelled';
+ const actionHtml = isRetryable
+ ? `<button class="retry-btn" type="button"
+ title="Re-submit this job with the same params"
+ onclick='retryJob(${JSON.stringify(j.id)})'>Retry</button>`
+ : '';
+ return `
+ <li class="${j.status}">
+ <span class="badge">${j.status}</span>
+ <span class="ttl" title="${titleAttr}">${titleHtml}</span>
+ <span class="params">${fmtMin(j.elapsed_sec)} · ${j.finished_at ? j.finished_at.slice(11) : ''}</span>
+ <span>${actionHtml}</span>
+ </li>`;
+ }).join('');
-// ====== Bug report modal ======
-// Fetches env + log tail from /panel/bug-context on open, lets the user
-// type into pre-marked sections, then on submit POSTs the title+body to
-// /panel/bug-report (which builds the GitHub URL + optional crash zip)
-// and opens the URL in a new tab. Stays purely in the panel — no auth,
-// no API hit, the user reviews the issue body in GitHub before posting.
-let _bugCtxCache = null;
-async function openBugModal() {
- const modal = document.getElementById('bugModal');
- modal.style.display = 'flex';
- const titleEl = document.getElementById('bugTitle');
- const bodyEl = document.getElementById('bugBody');
- const crashRow = document.getElementById('bugCrashRow');
- const crashLabel = document.getElementById('bugCrashLabel');
- const statusEl = document.getElementById('bugStatus');
- const submitBtn = document.getElementById('bugSubmitBtn');
- // Clear stale state in case the user opens twice in a row.
- titleEl.value = '[bug] ';
- bodyEl.value = 'Loading environment…';
- statusEl.textContent = '';
- submitBtn.disabled = false;
- submitBtn.textContent = 'Open GitHub issue';
- try {
- const r = await fetch('/panel/bug-context');
- if (!r.ok) throw new Error('bug-context: ' + r.status);
- _bugCtxCache = await r.json();
- } catch (err) {
- bodyEl.value = '## Environment\n- (server context unavailable: ' + err + ')\n\n'
- + '## What I was doing\n\n\n## What happened\n\n\n## Expected\n\n';
- crashRow.style.display = 'none';
- return;
+ // Outputs / carousel
+ if (JSON.stringify(currentOutputs) !== JSON.stringify(s.outputs)) {
+ currentOutputs = s.outputs;
+ renderCarousel();
+ // Pick the first FILTERED entry as the default selection so the
+ // viewer agrees with what the gallery is showing — without this,
+ // landing on Photos with no active selection would auto-pick a
+ // video and fight the filter.
+ if (!activePath) {
+ const visible = filteredMainOutputs();
+ if (visible.length) selectOutput(visible[0].path);
+ }
+ // The Extend source dropdown is video-only — Extend mode operates on
+ // mp4 input. Filter to videos so the user can't accidentally pick a
+ // .png as an Extend source (which would 400 server-side).
+ const sel = document.getElementById('extendSrcSelect');
+ const videoOutputs = currentOutputs.filter(o => !isPhotoOutputMain(o));
+ sel.innerHTML = '<option value="">— pick an output below or paste a path —</option>' +
+ videoOutputs.slice(0, 40).map(o => `<option value="${escapeHtml(o.path)}">${escapeHtml(o.name)}</option>`).join('');
}
- const c = _bugCtxCache;
- const tail = (c.logTail || []).join('\n') || '(no recent log lines)';
- bodyEl.value =
-`## Environment
-- Phosphene version: ${c.version}${c.commit ? ' (' + c.commit + ')' : ''}
-- Branch: ${c.branch}
-- macOS: ${c.macOS || 'unknown'}
-- Mac: ${c.hwModel || 'unknown'} · ${c.ramGB || '?'} GB RAM
-
-## What I was doing
-
-
-## What happened
+ // (The old "Hidden (N)" pill that lived here was retired with the
+ // Visible/Hidden segmented control — the carousel-head comment above
+ // documents the removal. Setting textContent on the missing element
+ // was firing a TypeError every poll cycle.)
+ // Title: count is post-filter so the badge agrees with the rendered
+ // cells. "Outputs · 23 photos" when Photos is active, plain "Outputs · N"
+ // when All. Hidden override stays unchanged.
+ const _visible = filteredMainOutputs();
+ const _kindLabel = mainOutputsFilter === 'all' ? '' : ` ${mainOutputsFilter}`;
+ document.getElementById('carouselTitle').textContent =
+ filterMode === 'hidden' ? 'Hidden outputs'
+ : `Outputs · ${_visible.length}${_kindLabel}`;
+ // Train Character integration: detect newly-completed train jobs and
+ // refresh both the trained-LoRA list AND the global LoRA picker so a
+ // freshly-trained character appears in T2V/I2V's picker without a manual
+ // reload. We watch history for entries with mode === 'train' that
+ // weren't there last poll; cheap and survives the user being on any
+ // tab/mode at the time training finishes.
+ if (Array.isArray(s.history)) {
+ const trainDoneCount = s.history.filter(h =>
+ h && h.params && h.params.mode === 'train' && h.status === 'done'
+ ).length;
+ if (typeof window._lastTrainDoneCount === 'undefined') {
+ window._lastTrainDoneCount = trainDoneCount;
+ } else if (trainDoneCount > window._lastTrainDoneCount) {
+ window._lastTrainDoneCount = trainDoneCount;
+ // New train job(s) completed since last poll — re-sync everything.
+ if (typeof refreshLoras === 'function') {
+ try { refreshLoras(); } catch (e) {}
+ }
+ if (typeof trainRefreshLoraList === 'function') {
+ try { trainRefreshLoraList(); } catch (e) {}
+ }
+ }
+ }
+}
-## Expected
+// Balanced chip subtitle — kept in sync with current mode + frames so the
+// label tells the truth about which pipeline a click on Balanced will run.
+// Mirrors the server-side `balanced_q8_fast` rule in run_job_inner: Q8 Fast
+// only on standard tier with Q8 installed, mode ∈ {t2v, a2v}, frames ≤ 121.
+window.refreshBalancedSubtitle = function(state) {
+ const sub = document.getElementById('balancedSub');
+ if (!sub) return;
+ const s = state || (window.__phosLastStatus || {});
+ const tierKey = (s.tier && (s.tier.key || s.tier.tier)) || '';
+ const q8Capable = !!s.q8_available && tierKey === 'standard';
+ if (!q8Capable) {
+ sub.textContent = 'Q4 · 5 min';
+ return;
+ }
+ const framesEl = document.getElementById('frames');
+ const frames = parseInt((framesEl && framesEl.value) || '121', 10);
+ const mode = (typeof currentMode !== 'undefined') ? currentMode : 't2v';
+ // T2V only — see Q8_FAST_OK_MODES on the server side.
+ // I2V/a2v Q8 Fast caused identity drift on real content; reverted until
+ // plan C (upscaled half-ref) or low_ram block streaming lands.
+ const eligible = mode === 't2v' && frames <= 121;
+ sub.textContent = eligible
+ ? 'Q8 Fast · 6 min'
+ : 'Q4 fallback';
+};
+document.addEventListener('DOMContentLoaded', function() {
+ const framesEl = document.getElementById('frames');
+ if (framesEl && !framesEl.__balancedSubWired) {
+ framesEl.addEventListener('input', () => window.refreshBalancedSubtitle());
+ framesEl.__balancedSubWired = true;
+ }
+ // Wrap setMode() if it exists, so mode flips also re-evaluate the label.
+ if (typeof setMode === 'function' && !setMode.__balancedSubWired) {
+ const _orig = setMode;
+ window.setMode = function(m) {
+ _orig(m);
+ window.refreshBalancedSubtitle();
+ };
+ window.setMode.__balancedSubWired = true;
+ }
+});
+// Recent-tab type filter (All / Videos / Photos). Stored on window so
+// the value survives across renders without polluting the existing
+// `filterMode` global (which is for the hidden/visible carousel filter,
+// a different concept). Defaults to 'all'.
+window.recentFilter = window.recentFilter || 'all';
+function setRecentFilter(mode) {
+ window.recentFilter = mode;
+ document.getElementById('recentFilterAll').classList.toggle('active', mode === 'all');
+ document.getElementById('recentFilterVideos').classList.toggle('active', mode === 'videos');
+ document.getElementById('recentFilterPhotos').classList.toggle('active', mode === 'photos');
+ // Re-poll so the filter's effect is visible immediately. /status is
+ // a localhost no-op, so the user perceives no latency.
+ poll();
+}
-## Logs / repro
-\`\`\`
-${tail}
-\`\`\`
-`;
- // Crash-report checkbox only when there's something to bundle.
- if ((c.crashCount || 0) > 0) {
- crashRow.style.display = 'flex';
- crashLabel.textContent =
- `Include latest crash reports (zips up to 5 of ${c.crashCount} .ips files)`;
- document.getElementById('bugCrashCheck').checked = true;
- } else {
- crashRow.style.display = 'none';
+// Right-pane gallery filter — All / Videos / Photos, persisted via
+// localStorage so picking "Photos" once sticks across reloads. Photo
+// discrimination uses params.mode === 'image' first, then falls back
+// to filename suffix for older sidecar-less entries.
+try {
+ const stored = localStorage.getItem('phos_outputs_filter');
+ if (stored === 'all' || stored === 'videos' || stored === 'photos') {
+ window.outputsFilter = stored;
}
- // Focus the "What I was doing" line for the user to start typing.
- // Place caret right after the heading.
- setTimeout(() => {
- bodyEl.focus();
- const marker = '## What I was doing\n';
- const idx = bodyEl.value.indexOf(marker);
- if (idx >= 0) {
- const pos = idx + marker.length;
- bodyEl.setSelectionRange(pos, pos);
- }
- }, 50);
-}
-function closeBugModal() {
- document.getElementById('bugModal').style.display = 'none';
+} catch (e) {}
+window.outputsFilter = window.outputsFilter || 'all';
+function setOutputsFilter(mode) {
+ if (mode !== 'all' && mode !== 'videos' && mode !== 'photos') mode = 'all';
+ window.outputsFilter = mode;
+ try { localStorage.setItem('phos_outputs_filter', mode); } catch (e) {}
+ const a = document.getElementById('outputsFilterAll');
+ const v = document.getElementById('outputsFilterVideos');
+ const p = document.getElementById('outputsFilterPhotos');
+ if (a) a.classList.toggle('active', mode === 'all');
+ if (v) v.classList.toggle('active', mode === 'videos');
+ if (p) p.classList.toggle('active', mode === 'photos');
}
-async function submitBugReport() {
- const submitBtn = document.getElementById('bugSubmitBtn');
- const statusEl = document.getElementById('bugStatus');
- const title = document.getElementById('bugTitle').value.trim() || '[bug] (untitled)';
- const body = document.getElementById('bugBody').value;
- const includeCrashEl = document.getElementById('bugCrashCheck');
- const includeCrash = includeCrashEl && document.getElementById('bugCrashRow').style.display !== 'none'
- ? !!includeCrashEl.checked : false;
- submitBtn.disabled = true;
- submitBtn.textContent = 'Working…';
- statusEl.textContent = 'Building issue…';
+// Apply the persisted filter on first paint so the chip styling
+// matches the live `window.outputsFilter` before the user clicks.
+document.addEventListener('DOMContentLoaded', () => {
+ if (document.getElementById('outputsFilterAll')) {
+ setOutputsFilter(window.outputsFilter || 'all');
+ }
+ // Same first-paint sync for the main right-pane chip strip — the
+ // localStorage value was loaded into `mainOutputsFilter` at script
+ // top, but the chip DOM hadn't been built yet, so the .active class
+ // is still on All. Re-apply now that the strip exists.
+ if (document.getElementById('mainOutputsFilterAll')) {
+ _updateMainFilterChips();
+ }
+});
+
+// Animate button — pre-fills the i2v form with the given still as the
+// reference image and the same prompt. Does NOT auto-submit; the user
+// keeps the chance to tweak prompt/seed/quality before clicking
+// Generate. Reversible (changing the image picker resets it).
+async function retryJob(jobId) {
+ // Re-submit a failed/cancelled job by its id. Server side endpoint
+ // /queue/retry takes the original job's id, copies its params verbatim
+ // into a fresh queue entry, and returns the new id. Toast on success
+ // (the Now/Queue pane will pick the new entry up on the next poll).
+ if (!jobId) return;
try {
- const r = await fetch('/panel/bug-report', {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ title, body, includeCrashReports: includeCrash }),
- });
- const data = await r.json();
- if (!r.ok || !data.issueUrl) throw new Error(data.error || ('HTTP ' + r.status));
- // Open the issue in a new tab. noopener for safety.
- window.open(data.issueUrl, '_blank', 'noopener');
- if (data.zipPath) {
- // Try to copy the path to clipboard so the user can paste-find it
- // in Finder, OR drag the file from /tmp directly onto the GitHub
- // issue. Best-effort — clipboard write requires a user gesture
- // context, which a click handler counts as.
- try { await navigator.clipboard.writeText(data.zipPath); } catch (e) { /* ignore */ }
- statusEl.innerHTML =
- 'Crash report bundled. Drag this file into the GitHub issue:<br>' +
- '<code style="font-size:11px">' + data.zipPath + '</code><br>' +
- '<span style="color:var(--success,#3fb950)">(path copied to clipboard)</span>';
- submitBtn.textContent = 'Done — close';
- submitBtn.disabled = false;
- submitBtn.onclick = closeBugModal;
- } else {
- statusEl.textContent = 'GitHub issue opened in a new tab.';
- submitBtn.textContent = 'Done — close';
- submitBtn.disabled = false;
- submitBtn.onclick = closeBugModal;
- // Auto-close after a short delay if the user doesn't click Close.
- setTimeout(() => {
- const m = document.getElementById('bugModal');
- if (m && m.style.display !== 'none') closeBugModal();
- }, 4000);
+ const fd = new URLSearchParams();
+ fd.set('id', jobId);
+ const r = await fetch('/queue/retry', { method: 'POST', body: fd });
+ let data = {};
+ try { data = await r.json(); } catch (e) { /* keep empty */ }
+ if (!r.ok || !data.ok) {
+ alert('Retry failed: ' + (data.error || ('HTTP ' + r.status)));
+ return;
}
- } catch (err) {
- statusEl.innerHTML = '<span style="color:var(--danger,#f85149)">Failed: ' + err + '</span>';
- submitBtn.disabled = false;
- submitBtn.textContent = 'Try again';
+ // Force one immediate poll so the queue badge updates without the
+ // 1.5s wait. poll() is idempotent.
+ if (typeof poll === 'function') poll();
+ } catch (e) {
+ alert('Retry error: ' + (e.message || 'unknown'));
}
}
-// ====== Settings modal ======
-// Single-shot fetch on open (settings change rarely). The modal hydrates
-// preset cards from the /settings response so the labels and blurbs
-// match the server-side OUTPUT_PRESETS table — no preset content
-// duplicated in JS.
-let _settingsCache = null;
-
-async function openSettingsModal() {
- const modal = document.getElementById('settingsModal');
- modal.style.display = 'flex';
- document.getElementById('settingsStatus').textContent = '';
- document.getElementById('settingsStatus').className = 'settings-status';
+// Re-run a previously-generated still through HiDream Quality (the
+// 12-step + light FBCache recipe). Reads the source's sidecar to pull
+// the original prompt + seed + refs, then drives the Image Studio form
+// (engine swapped to hidream_quality_inline, n=1) and submits to the
+// queue. Used from the photo card hover button.
+//
+// Why no manual confirmation step: Salo's intent is "pick best of 4
+// Fast/Medium previews → bake one at Quality" — adding a dialog would
+// burn a click for no information. The Image Studio form is left
+// pre-filled so the user can tweak + resubmit if they want.
+async function remakeInQuality(payload) {
+ if (!payload || !payload.path) {
+ if (typeof phosToast === 'function') {
+ phosToast('Remake: missing path', { kind: 'danger' });
+ }
+ return;
+ }
+ // Pull the source's generation params from its sidecar JSON.
+ let sidecar;
try {
- const r = await fetch('/settings');
- _settingsCache = await r.json();
+ const r = await fetch('/sidecar?path=' + encodeURIComponent(payload.path));
+ if (!r.ok) throw new Error('no sidecar (older output?)');
+ sidecar = await r.json();
} catch (e) {
- document.getElementById('settingsStatus').textContent = 'Could not load settings.';
- document.getElementById('settingsStatus').className = 'settings-status err';
+ if (typeof phosToast === 'function') {
+ phosToast('Remake: ' + (e.message || 'failed to read sidecar'),
+ { kind: 'danger' });
+ }
return;
}
- const cur = _settingsCache.settings;
- const presets = _settingsCache.presets;
- // Render preset cards (Standard, Video production, Web, Custom).
- // Display order matches the typical user journey: most users want
- // Standard, video pros pick Video production, web preview folks pick Web.
- const order = ['standard', 'archival', 'web'];
- const grid = document.getElementById('settingsPresets');
- grid.innerHTML = '';
- for (const key of order) {
- const p = presets[key];
- const active = cur.output_preset === key ? 'active' : '';
- const card = document.createElement('label');
- card.className = `preset-card ${active}`;
- card.dataset.preset = key;
- card.innerHTML = `
- <input type="radio" name="settingsPreset" value="${key}" ${cur.output_preset === key ? 'checked' : ''}>
- <div class="preset-text">
- <div class="preset-label">${escapeHtml(p.label)}</div>
- <div class="preset-blurb">${escapeHtml(p.blurb)}</div>
- <div class="preset-spec">pix_fmt=${p.pix_fmt} · crf=${p.crf}</div>
- </div>`;
- card.addEventListener('click', () => selectPreset(key));
- grid.appendChild(card);
- }
- // Custom row.
- const customActive = cur.output_preset === 'custom' ? 'active' : '';
- const custom = document.createElement('label');
- custom.className = `preset-card ${customActive}`;
- custom.dataset.preset = 'custom';
- custom.innerHTML = `
- <input type="radio" name="settingsPreset" value="custom" ${cur.output_preset === 'custom' ? 'checked' : ''}>
- <div class="preset-text">
- <div class="preset-label">Custom</div>
- <div class="preset-blurb">Set pix_fmt and CRF manually. For unusual workflows: 10-bit HDR, format-specific delivery, or non-standard CRF for video production work.</div>
- <div class="preset-spec">pix_fmt=${cur.output_pix_fmt} · crf=${cur.output_crf}</div>
- </div>`;
- custom.addEventListener('click', () => selectPreset('custom'));
- grid.appendChild(custom);
- // Pre-fill custom inputs with current values
- document.getElementById('settingsPixFmt').value = cur.output_pix_fmt;
- document.getElementById('settingsCrfRange').value = cur.output_crf;
- document.getElementById('settingsCrfNum').value = cur.output_crf;
- document.getElementById('settingsCustomSection').style.display =
- cur.output_preset === 'custom' ? 'block' : 'none';
+ // Switch to Image Studio mode so the form is visible.
+ if (typeof setMode === 'function') setMode('image');
- // Memory policy — populated from the server so labels/blurbs stay aligned
- // with backend behavior.
- const memSelect = document.getElementById('settingsMemoryPolicy');
- const memPolicies = _settingsCache.memory_policies || {};
- if (memSelect) {
- memSelect.innerHTML = '';
- for (const key of ['auto', 'fast', 'safe']) {
- const mp = memPolicies[key];
- if (!mp) continue;
- const opt = document.createElement('option');
- opt.value = key;
- opt.textContent = mp.label || key;
- memSelect.appendChild(opt);
+ // Pre-fill the form. Prompt + seed + aspect carry over verbatim.
+ // Refs go into the studio's 3-slot model.
+ const promptEl = document.getElementById('imgStudioPrompt');
+ if (promptEl) promptEl.value = sidecar.prompt || '';
+ const seedEl = document.getElementById('imgStudioSeed');
+ if (seedEl && sidecar.seed != null) seedEl.value = String(sidecar.seed);
+ const nEl = document.getElementById('imgStudioN');
+ if (nEl) nEl.value = '1'; // remake just the picked one
+ const engineEl = document.getElementById('imgStudioEngine');
+ if (engineEl) engineEl.value = 'hidream_quality_inline';
+ const aspectEl = document.getElementById('imgStudioAspect');
+ if (aspectEl && sidecar.aspect) aspectEl.value = sidecar.aspect;
+
+ // Refs — clear the 3 slots, then re-populate from sidecar.refs.
+ if (typeof IMG_STUDIO !== 'undefined' && IMG_STUDIO.refs) {
+ for (let i = 0; i < IMG_STUDIO.refs.length; i++) {
+ IMG_STUDIO.refs[i] = null;
+ if (typeof imgStudioRenderSlot === 'function') imgStudioRenderSlot(i);
}
- memSelect.value = cur.memory_policy || 'auto';
- memSelect.onchange = renderMemoryPolicyHint;
- renderMemoryPolicyHint();
+ const refs = Array.isArray(sidecar.refs) ? sidecar.refs : [];
+ refs.slice(0, IMG_STUDIO.refs.length).forEach((path, i) => {
+ const fname = String(path).split('/').pop();
+ IMG_STUDIO.refs[i] = { path, name: fname };
+ if (typeof imgStudioRenderSlot === 'function') imgStudioRenderSlot(i);
+ });
}
- // Token rows. We never receive the actual key from the server (the
- // /settings GET returns has_X booleans only), so we display either
- // "set" with an empty placeholder input, or "—" with the placeholder.
- // Inputs start empty on every modal open; user pastes when they want
- // to change.
- setTokenStatus('civitaiKey', cur.has_civitai_key);
- setTokenStatus('hfToken', cur.has_hf_token);
- // Placeholders reflect the saved state so an empty input doesn't read
- // as "no token here" when there is one. The asterisks make it clear
- // something's persisted; the hint reminds users they paste to replace.
- const civInput = document.getElementById('civitaiKeyInput');
- const hfInput = document.getElementById('hfTokenInput');
- civInput.value = '';
- hfInput.value = '';
- civInput.placeholder = cur.has_civitai_key
- ? '•••••••••• saved — paste new to replace'
- : '32-char API key';
- hfInput.placeholder = cur.has_hf_token
- ? '•••••••••• saved — paste new to replace'
- : 'hf_…';
- document.getElementById('civitaiKeyClear').style.display = cur.has_civitai_key ? '' : 'none';
- document.getElementById('hfTokenClear').style.display = cur.has_hf_token ? '' : 'none';
-
- // Spicy mode — render current state. _spicyArmed is the mid-confirm
- // state (clicked once, waiting for the second click). It lives only
- // on the JS side; only ON/OFF gets persisted.
- _spicyArmed = false;
- renderSpicyState(!!cur.spicy_mode);
-}
+ // Refresh validity + estimate UI so the Generate button enables.
+ if (typeof imgStudioUpdateValidity === 'function') imgStudioUpdateValidity();
+ if (typeof imgStudioUpdateEstimate === 'function') imgStudioUpdateEstimate();
+ if (typeof imgStudioRefreshEngineStatus === 'function') imgStudioRefreshEngineStatus();
-function renderMemoryPolicyHint() {
- const sel = document.getElementById('settingsMemoryPolicy');
- const hint = document.getElementById('settingsMemoryPolicyHint');
- if (!sel || !hint) return;
- const policies = (_settingsCache && _settingsCache.memory_policies) || {};
- const p = policies[sel.value] || {};
- hint.textContent = p.blurb || '';
+ // Auto-submit. imgStudioGenerate reads the now-prefilled fields.
+ if (typeof imgStudioGenerate === 'function') {
+ if (typeof phosToast === 'function') {
+ phosToast('Remaking in Quality (12-step) · watch Recent → Photos',
+ { kind: 'success' });
+ }
+ imgStudioGenerate();
+ }
}
-let _spicyArmed = false;
-
-function renderSpicyState(isOn) {
- const badge = document.getElementById('spicyStateBadge');
- const btn = document.getElementById('spicyToggleBtn');
- const hint = document.getElementById('spicyHint');
- if (!badge || !btn) return;
- badge.classList.remove('on', 'armed');
- if (_spicyArmed) {
- badge.textContent = 'ARMED';
- badge.classList.add('armed');
- btn.textContent = 'Click again to confirm';
- btn.classList.remove('ghost-btn');
- btn.classList.add('primary-btn');
- hint.style.display = '';
- hint.textContent = 'Confirms turning Spicy mode ON. NSFW LoRAs will be available in the CivitAI browser. Cancel by closing the modal.';
- } else if (isOn) {
- badge.textContent = 'ON';
- badge.classList.add('on');
- btn.textContent = 'Disable';
- btn.classList.remove('primary-btn');
- btn.classList.add('ghost-btn');
- hint.style.display = '';
- hint.textContent = 'Spicy mode is ON. NSFW LoRAs are visible in the CivitAI browser when you tick "Show NSFW".';
+function animateFromPhoto(payload) {
+ if (!payload || !payload.path) return;
+ // Switch to i2v mode (pill + form fields). setMode('i2v') hides the
+ // Studio pane, shows the video form, and applies the i2v-specific
+ // dropdown selection.
+ setMode('i2v');
+ // Use the existing image picker helper so the preview tile updates
+ // alongside the hidden form field. Pass snapAspect:false to keep
+ // whatever aspect the user already had selected (matches loadParams).
+ if (typeof pickerSetImage === 'function') {
+ pickerSetImage('image', payload.path, { snapAspect: false });
} else {
- badge.textContent = 'OFF';
- btn.textContent = 'Enable Spicy mode';
- btn.classList.remove('primary-btn');
- btn.classList.add('ghost-btn');
- hint.style.display = 'none';
- hint.textContent = '';
+ document.getElementById('image').value = payload.path;
+ }
+ if (payload.prompt) {
+ document.getElementById('prompt').value = payload.prompt;
}
+ // Scroll the form pane to the top so the image picker + prompt are
+ // immediately visible.
+ const formPane = document.querySelector('aside.form-pane');
+ if (formPane) formPane.scrollTop = 0;
+ if (typeof updateDerived === 'function') updateDerived();
+ if (typeof updateCustomizeSummary === 'function') updateCustomizeSummary();
}
-async function toggleSpicyMode() {
- // Two-click confirm to turn ON, single-click to turn OFF.
- // Easy to disable, deliberate to enable — matches the user spec
- // ("don't want people to turn it on by mistake, or kids").
- const cur = (_settingsCache && _settingsCache.settings) || {};
- const isOn = !!cur.spicy_mode;
- if (isOn) {
- // Single-click off, no confirm.
- await _persistSpicyMode(false);
- return;
+// Format render duration for the gallery card sub-line. Falls back to
+// the time-of-day when the sidecar is missing (older outputs that
+// pre-date the elapsed_sec field, or outputs whose sidecar got
+// deleted) so the slot is never empty.
+function _outputDurationLabel(o) {
+ const s = (o && typeof o.elapsed_sec === 'number') ? o.elapsed_sec : null;
+ if (s == null) {
+ // Fallback: show time-of-day from mtime so empty cards aren't worse.
+ return o.mtime ? o.mtime.slice(11, 16) : '—';
}
- if (!_spicyArmed) {
- _spicyArmed = true;
- renderSpicyState(false);
- // Auto-disarm after 6 s if the user doesn't confirm — prevents
- // the "click again" state lingering across an unrelated tab return.
- setTimeout(() => {
- if (_spicyArmed) {
- _spicyArmed = false;
- renderSpicyState(!!(_settingsCache?.settings?.spicy_mode));
- }
- }, 6000);
+ if (s < 60) return `${Math.round(s)} s`;
+ if (s < 3600) return `${Math.floor(s / 60)} m ${Math.round(s % 60)} s`;
+ return `${Math.floor(s / 3600)} h ${Math.round((s % 3600) / 60)} m`;
+}
+
+function renderCarousel() {
+ const el = document.getElementById('carousel');
+ const visible = filteredMainOutputs();
+ if (!visible.length) {
+ const msg = mainOutputsFilter === 'photos' ? 'No photo outputs yet.'
+ : mainOutputsFilter === 'videos' ? 'No video outputs yet.'
+ : 'No outputs in this view yet.';
+ el.innerHTML = `<div class="empty-msg">${msg}</div>`;
return;
}
- // Second click — actually persist.
- _spicyArmed = false;
- await _persistSpicyMode(true);
+ el.innerHTML = visible.map(o => {
+ const pathAttr = JSON.stringify(o.path).replace(/"/g, '&quot;');
+ const isPhoto = isPhotoOutputMain(o);
+ // Thumbnail markup branches on kind. Videos use <video> with a
+ // mid-clip seek (2.5s — LTX clips are 5s at 24fps and the first
+ // half-second is often a dark fade-in, so seeking to the middle
+ // gets a representative frame). Photos use <img> directly with
+ // the same /image?path=… cache-bust URL the server stamped.
+ const thumbHtml = isPhoto
+ ? `<img class="car-thumb" src="${o.url}" alt="${escapeHtml(o.name)}" loading="lazy">`
+ // Hover-scrub: on enter, jump to 0 and play silently at 0.6×;
+ // on leave, pause + snap back to the static 2.5s preview frame.
+ // The play() promise can reject during a fast scrub (browser
+ // says "play interrupted by pause") — swallow it.
+ : `<video src="${o.url}#t=2.5" preload="metadata" muted playsinline
+ onmouseenter="this.currentTime=0; this.playbackRate=0.6; this.play().catch(()=>{})"
+ onmouseleave="this.pause(); this.currentTime=2.5; this.playbackRate=1"></video>`;
+ // Per-card actions (revealed on hover) — kept deliberately minimal:
+ // * Photos get a small "Animate" chip (turns the still into i2v).
+ // * Everything gets a delete (×) chip.
+ // The previous Hide + Extend buttons were dropped per Salo:
+ // - Hide was useless (clutter, never used in practice).
+ // - Extend wasn't practical on Mac.
+ // Folder-reveal moved to a global button in the carousel header.
+ const animateArgs = JSON.stringify({path: o.path, prompt: ''}).replace(/"/g, '&quot;');
+ const animateChip = isPhoto
+ ? `<button class="card-action card-action-photo" type="button"
+ title="Pre-fill i2v with this image (does not auto-submit)"
+ onclick="event.stopPropagation(); animateFromPhoto(${animateArgs})">Animate</button>`
+ : '';
+ // Remake-in-Quality chip — only on photos that have a sidecar (we need the
+ // original prompt + seed + refs to re-run). Pre-fills the Image Studio
+ // form with the source's exact params, swaps the engine to
+ // hidream_quality_inline, sets n=1, and auto-submits. Useful flow:
+ // generate 4 candidates in Fast/Medium, pick the best, hit ✦ to bake the
+ // same composition at Quality fidelity.
+ const remakeArgs = JSON.stringify({path: o.path}).replace(/"/g, '&quot;');
+ const remakeChip = (isPhoto && o.has_sidecar)
+ ? `<button class="card-action card-action-photo" type="button"
+ title="Re-run this prompt + seed + refs through HiDream Quality (auto-submits)"
+ onclick="event.stopPropagation(); remakeInQuality(${remakeArgs})">✦ Quality</button>`
+ : '';
+ return `
+ <div class="car-card${o.path === activePath ? ' active' : ''}"
+ data-path="${escapeHtml(o.path)}" onclick="selectOutput(${pathAttr})">
+ <div class="car-thumb-wrap">
+ ${thumbHtml}
+ ${o.has_sidecar
+ ? `<button class="car-info-btn" type="button" title="Show generation info"
+ onclick="event.stopPropagation(); openOutputInfoModal(${pathAttr})"><svg class="ph" aria-hidden="true"><use href="#ph-info"/></svg></button>`
+ : ''}
+ <div class="card-chrome">
+ ${remakeChip}
+ ${animateChip}
+ <button class="card-action card-action-danger" type="button" title="Delete this file from disk"
+ onclick="event.stopPropagation(); deleteOutput(${pathAttr})"><svg class="ph" aria-hidden="true"><use href="#ph-trash-simple"/></svg></button>
+ </div>
+ </div>
+ <div class="info">
+ <div class="name" title="${escapeHtml(o.name)}">${escapeHtml(o.name)}</div>
+ <div class="sub" title="Render time · file size">
+ ${_outputDurationLabel(o)} · ${o.size_mb.toFixed(1)} MB
+ </div>
+ </div>
+ </div>`;
+ }).join('');
}
-async function _persistSpicyMode(target) {
- const status = document.getElementById('settingsStatus');
- try {
- const fd = new URLSearchParams();
- fd.set('spicy_mode', target ? 'true' : 'false');
- const r = await fetch('/settings', { method: 'POST', body: fd });
- const j = await r.json();
- if (j.error) throw new Error(j.error);
- if (_settingsCache && _settingsCache.settings) {
- _settingsCache.settings.spicy_mode = !!target;
- }
- renderSpicyState(!!target);
- if (status) {
- status.textContent = target ? 'Spicy mode ON · NSFW LoRAs unlocked' : 'Spicy mode OFF · NSFW LoRAs hidden';
- status.className = 'settings-status ok';
- }
- // Refresh the CivitAI panel so the "Show NSFW" toggle appears /
- // disappears immediately without a full page reload.
- if (typeof refreshCivitaiAccessUI === 'function') refreshCivitaiAccessUI();
- } catch (e) {
- if (status) {
- status.textContent = 'Could not change Spicy mode: ' + (e.message || e);
- status.className = 'settings-status err';
- }
- }
+// Relative-time helper for the player overlay meta line. Takes the
+// server's "YYYY-MM-DD HH:MM:SS" mtime string and returns a humanlike
+// "2 min ago" / "3 h ago" / "yesterday" so the meta strip carries
+// recency info without forcing the user to do date math.
+function _relTimeFromMtime(mtime) {
+ if (!mtime) return '';
+ // Treat the server timestamp as local time (it's the panel host's
+ // wall clock). Date parses "YYYY-MM-DD HH:MM:SS" inconsistently
+ // across browsers, so re-format to ISO-with-T which all engines
+ // accept as local.
+ const iso = String(mtime).replace(' ', 'T');
+ const t = new Date(iso).getTime();
+ if (!isFinite(t)) return mtime;
+ const sec = Math.max(0, Math.round((Date.now() - t) / 1000));
+ if (sec < 45) return 'just now';
+ if (sec < 90) return '1 min ago';
+ if (sec < 3600) return Math.round(sec / 60) + ' min ago';
+ if (sec < 5400) return '1 h ago';
+ if (sec < 86400) return Math.round(sec / 3600) + ' h ago';
+ if (sec < 172800) return 'yesterday';
+ return Math.round(sec / 86400) + ' d ago';
}
-function setTokenStatus(prefix, isSet, dirty) {
- const el = document.getElementById(prefix + 'Status');
- if (!el) return;
- el.classList.remove('set', 'dirty');
- if (dirty) {
- el.innerHTML = '<svg class="ph" aria-hidden="true" style="margin-right:4px;vertical-align:-2px"><use href="#ph-pencil-simple"/></svg>unsaved';
- el.classList.add('dirty');
- } else if (isSet) {
- el.innerHTML = '<svg class="ph" aria-hidden="true" style="margin-right:4px;vertical-align:-2px"><use href="#ph-check-bold"/></svg>saved';
- el.classList.add('set');
+function selectOutput(path) {
+ activePath = path;
+ document.querySelectorAll('.car-card').forEach(el => el.classList.toggle('active', el.dataset.path === path));
+ const wrap = document.getElementById('playerWrap');
+ wrap.classList.remove('empty');
+ // Y1.039 — use the server-provided URL (which includes the mtime
+ // cache-bust v=N param) instead of reconstructing from path. Otherwise
+ // the player ends up on the cached stale-bytes URL and re-shows black
+ // until the browser cache expires.
+ const o = currentOutputs.find(x => x.path === path);
+ const isPhoto = isPhotoOutputMain(o);
+ // Photo entries don't go through /file (which is OUTPUT-bound and
+ // serves video with Range headers). Use /image which supports both
+ // OUTPUT and UPLOADS roots, with the right MIME headers. Server-side
+ // list_outputs() already builds the right URL per kind, so o.url
+ // is correct for both — the fallback path below only runs when an
+ // unknown path is requested (e.g. clicked from a stale modal link).
+ let playerSrc;
+ if (o) {
+ playerSrc = o.url;
+ } else if (isPhoto) {
+ playerSrc = `/image?path=${encodeURIComponent(path)}`;
} else {
- el.textContent = 'not set';
+ playerSrc = `/file?path=${encodeURIComponent(path)}`;
}
-}
+ // Photo viewer is a static <img> — no controls, no autoplay (would
+ // be a no-op on an image element anyway). Video viewer keeps the
+ // existing controls + autoplay behaviour.
+ wrap.innerHTML = isPhoto
+ ? `<img src="${playerSrc}" alt="${o ? escapeHtml(o.name) : ''}">`
+ : `<video controls autoplay src="${playerSrc}"></video>`;
-function onTokenInput(which) {
- const prefix = which === 'civitai' ? 'civitaiKey' : 'hfToken';
- const inp = document.getElementById(prefix + 'Input');
- setTokenStatus(prefix, false, !!inp.value);
+ // Y2.001 — populate the new overlays. The legacy #playerName / #playerMeta
+ // are kept hidden but the writes still happen so any test/external code
+ // reading them gets the same data.
+ document.getElementById('playerMeta').style.display = '';
+ const legacyMetaText = o
+ ? `${o.name} · ${o.mtime} · ${o.size_mb.toFixed(1)} MB`
+ : '';
+ document.getElementById('playerName').textContent = legacyMetaText;
+ // Visible top overlay — title + meta line with relative time.
+ const overlayTop = document.getElementById('playerOverlayTop');
+ const overlayActions = document.getElementById('playerOverlayActions');
+ if (overlayTop) {
+ overlayTop.style.display = '';
+ document.getElementById('playerOverlayName').textContent = o ? o.name : '';
+ const rel = o ? _relTimeFromMtime(o.mtime) : '';
+ const sizeLbl = o ? `${o.size_mb.toFixed(1)} MB` : '';
+ const kindLbl = isPhoto ? 'Photo' : 'Video';
+ document.getElementById('playerOverlayMeta').innerHTML = o
+ ? `<span>${kindLbl}</span><span class="po-dot"></span>` +
+ `<span>${escapeHtml(rel)}</span><span class="po-dot"></span>` +
+ `<span>${sizeLbl}</span>`
+ : '';
+ }
+ if (overlayActions) overlayActions.style.display = '';
+
+ // Load params is video-only — image sidecars use the library@1 schema
+ // which doesn't carry the i2v/t2v form fields the loader expects.
+ document.getElementById('loadParamsBtn').disabled = !(o && o.has_sidecar) || isPhoto;
+ // Action button row: swap "Use as Extend" for "Animate" on photo
+ // entries (Extend is video-only, but the still can be the seed for
+ // an i2v render).
+ const useExtBtn = document.getElementById('useAsExtendBtn');
+ const animBtn = document.getElementById('animateBtn');
+ if (useExtBtn) useExtBtn.style.display = isPhoto ? 'none' : '';
+ if (animBtn) animBtn.style.display = isPhoto ? '' : 'none';
}
-function toggleTokenVisibility(inputId, btn) {
- const inp = document.getElementById(inputId);
- if (!inp) return;
- if (inp.type === 'password') {
- inp.type = 'text';
- btn.textContent = 'hide';
- } else {
- inp.type = 'password';
- btn.textContent = 'show';
+// Expand lightbox — full-viewport viewer for the active output. Reuses
+// the active entry's URL / kind detection so a single button works for
+// both image and video. Closed by Esc, backdrop click, or the × button.
+function openExpandLightbox() {
+ if (!activePath) return;
+ const o = currentOutputs.find(x => x.path === activePath);
+ if (!o) return;
+ const lb = document.getElementById('expandLightbox');
+ const stage = document.getElementById('expandStage');
+ const meta = document.getElementById('expandMeta');
+ if (!lb || !stage) return;
+ const isPhoto = isPhotoOutputMain(o);
+ // Build the media element fresh each time so the previous selection's
+ // <video> stops decoding immediately.
+ stage.innerHTML = isPhoto
+ ? `<img src="${o.url}" alt="${escapeHtml(o.name)}">`
+ : `<video src="${o.url}" controls autoplay></video>`;
+ if (meta) {
+ const sizeLbl = `${o.size_mb.toFixed(1)} MB`;
+ meta.textContent = `${o.name} · ${sizeLbl}`;
}
+ lb.style.display = 'flex';
}
-// Save-then-test in one click. The /civitai/test and /hf/test endpoints
-// use the saved key, not the current input field. Pre-Y1.023 the user
-// had to: paste → click Apply → click Test. That left a footgun: users
-// pasted, clicked Test, saw it fail (because nothing was saved yet),
-// closed the modal thinking the panel was broken. The token never
-// landed in panel_settings.json, gated downloads kept failing.
-//
-// Now Test does Save first when the input has a value, so a single
-// click works. If the save fails (validator rejects malformed token),
-// we surface the error inline next to the field instead of just at
-// the bottom of the modal.
-async function testToken(which) {
- const path = which === 'civitai' ? '/civitai/test' : '/hf/test';
- const resultId = which === 'civitai' ? 'civitaiTestResult' : 'hfTestResult';
- const inputId = which === 'civitai' ? 'civitaiKeyInput' : 'hfTokenInput';
- const fieldName = which === 'civitai' ? 'civitai_api_key' : 'hf_token';
- const statusPrefix = which === 'civitai' ? 'civitaiKey' : 'hfToken';
- const clearBtnId = which === 'civitai' ? 'civitaiKeyClear' : 'hfTokenClear';
- const result = document.getElementById(resultId);
- if (!result) return;
- result.textContent = 'Testing…';
- result.style.color = 'var(--muted)';
+function closeExpandLightbox() {
+ const lb = document.getElementById('expandLightbox');
+ const stage = document.getElementById('expandStage');
+ if (!lb) return;
+ if (stage) stage.innerHTML = ''; // stops video playback
+ lb.style.display = 'none';
+}
- // If the input has content, save it first. Empty input means "test
- // the already-saved token" — the legitimate use after the panel is
- // configured.
- const inputEl = document.getElementById(inputId);
- const inputValue = inputEl ? inputEl.value.trim() : '';
- if (inputValue) {
- try {
- const fd = new URLSearchParams();
- fd.set(fieldName, inputValue);
- const saveResp = await fetch('/settings', {
- method: 'POST',
- headers: {'Content-Type': 'application/x-www-form-urlencoded'},
- body: fd,
- });
- const saveData = await saveResp.json();
- if (!saveResp.ok || saveData.error) {
- result.innerHTML = `<svg class="ph" aria-hidden="true" style="color:var(--danger,#f85149);margin-right:4px;vertical-align:-2px"><use href="#ph-x-circle-fill"/></svg>${escapeHtml(saveData.error || `HTTP ${saveResp.status}`)}`;
- return;
+// Esc + F shortcuts for the expand lightbox. Bound once at module init.
+(function _wireExpandLightboxKeys() {
+ document.addEventListener('keydown', (e) => {
+ const lb = document.getElementById('expandLightbox');
+ if (!lb) return;
+ const isOpen = lb.style.display === 'flex';
+ // Don't steal keystrokes from inputs/textareas.
+ const tag = (e.target && e.target.tagName) || '';
+ const inField = tag === 'INPUT' || tag === 'TEXTAREA' || (e.target && e.target.isContentEditable);
+ if (e.key === 'Escape' && isOpen) {
+ closeExpandLightbox();
+ e.preventDefault();
+ } else if ((e.key === 'f' || e.key === 'F') && !isOpen && !inField && activePath) {
+ openExpandLightbox();
+ e.preventDefault();
+ } else if ((e.key === 'ArrowLeft' || e.key === 'ArrowRight') && !inField && activePath
+ && typeof filteredMainOutputs === 'function') {
+ // Carousel keyboard nav. Wraps at the edges so power users can
+ // scrub through the whole gallery without lifting hands off the
+ // keyboard. Works whether the lightbox is open or not — if it
+ // IS open, the lightbox content updates with the new selection.
+ const list = filteredMainOutputs();
+ if (!list.length) return;
+ const idx = list.findIndex(o => o.path === activePath);
+ const nextIdx = e.key === 'ArrowLeft'
+ ? (idx <= 0 ? list.length - 1 : idx - 1)
+ : (idx < 0 || idx >= list.length - 1 ? 0 : idx + 1);
+ const next = list[nextIdx];
+ if (next && typeof selectOutput === 'function') {
+ selectOutput(next.path);
+ if (isOpen) openExpandLightbox(); // re-bind media to new pick
}
- // Save succeeded — reflect the persisted state in the UI.
- inputEl.value = '';
- _settingsCache = { ...(_settingsCache || {}), settings: saveData.settings };
- setTokenStatus(statusPrefix, true);
- const clearBtn = document.getElementById(clearBtnId);
- if (clearBtn) clearBtn.style.display = '';
- } catch (e) {
- result.innerHTML = `<svg class="ph" aria-hidden="true" style="color:var(--danger,#f85149);margin-right:4px;vertical-align:-2px"><use href="#ph-x-circle-fill"/></svg>Save failed: ${escapeHtml(e.message || String(e))}`;
- return;
+ e.preventDefault();
}
- }
+ });
+})();
- // Now hit the test endpoint, which reads the freshly-saved token.
- try {
- const r = await fetch(path);
- const data = await r.json();
- if (data.ok) {
- result.innerHTML = `<svg class="ph" aria-hidden="true" style="color:var(--success,#3fb950);margin-right:4px;vertical-align:-2px"><use href="#ph-check-bold"/></svg>${escapeHtml(data.message)}`;
- } else {
- result.innerHTML = `<svg class="ph" aria-hidden="true" style="color:var(--danger,#f85149);margin-right:4px;vertical-align:-2px"><use href="#ph-x-circle-fill"/></svg>${escapeHtml(data.error)}`;
- }
- } catch (e) {
- result.innerHTML = `<svg class="ph" aria-hidden="true" style="color:var(--danger,#f85149);margin-right:4px;vertical-align:-2px"><use href="#ph-x-circle-fill"/></svg>Network error: ${escapeHtml(e.message || String(e))}`;
+// Toast helper — non-blocking confirmation pattern, stacks at the
+// bottom-center of the viewport. Use for delete confirmation, "moved
+// to Trash" feedback, save success, etc. Auto-dismisses after
+// `duration` ms (default 3 s). Pass `kind: "success" | "danger"` to
+// tint the border + icon.
+function phosToast(message, opts) {
+ opts = opts || {};
+ const c = document.getElementById('phosToast');
+ if (!c) return null;
+ const el = document.createElement('div');
+ el.className = 'phos-toast';
+ if (opts.kind === 'success' || opts.kind === 'danger') {
+ el.classList.add('phos-toast-' + opts.kind);
}
-}
-
-async function clearToken(which) {
- const fd = new FormData();
- if (which === 'civitai') fd.set('civitai_api_key', '');
- if (which === 'hf') fd.set('hf_token', '');
- try {
- // urlencoded body — see applySettings for why.
- const r = await fetch('/settings', {
- method: 'POST',
- headers: {'Content-Type': 'application/x-www-form-urlencoded'},
- body: new URLSearchParams(fd),
- });
- const data = await r.json();
- if (!r.ok || data.error) {
- alert('Could not clear: ' + (data.error || `HTTP ${r.status}`));
- return;
- }
- // Refresh the modal so the status flips back to "not set".
- openSettingsModal();
- } catch (e) {
- alert('Network error: ' + (e.message || e));
+ const icon = opts.icon
+ || (opts.kind === 'success' ? 'ph-check-bold'
+ : opts.kind === 'danger' ? 'ph-x-circle'
+ : 'ph-info');
+ el.innerHTML =
+ `<svg class="ph" aria-hidden="true"><use href="#${icon}"/></svg>` +
+ `<span class="phos-toast-msg"></span>`;
+ el.querySelector('.phos-toast-msg').textContent = String(message);
+ c.appendChild(el);
+ const duration = (opts.duration === 0) ? 0 : (opts.duration || 3000);
+ if (duration > 0) {
+ setTimeout(() => {
+ if (!el.isConnected) return;
+ el.classList.add('is-leaving');
+ el.addEventListener('animationend', () => el.remove(), { once: true });
+ }, duration);
}
+ return el;
}
-function closeSettingsModal() {
- document.getElementById('settingsModal').style.display = 'none';
+// Animate the active output (photo only). Mirrors animateFromPhoto's
+// shape — pre-fills the i2v form from the active entry's path and the
+// sidecar's prompt if there is one. Sidecar fetch is best-effort; if it
+// fails (or there isn't one), we still animate with an empty prompt so
+// the user can type their own.
+async function animateActive() {
+ if (!activePath) return;
+ const o = currentOutputs.find(x => x.path === activePath);
+ let prompt = '';
+ if (o && o.has_sidecar) {
+ try {
+ const r = await fetch('/sidecar?path=' + encodeURIComponent(activePath));
+ if (r.ok) {
+ const data = await r.json();
+ // Image sidecars use schema "phosphene/library/image@1" with
+ // a top-level `prompt`; video sidecars nest it under `params`.
+ // Cover both shapes so the UI works regardless of source.
+ prompt = (data && (data.prompt || (data.params && data.params.prompt))) || '';
+ }
+ } catch (e) {}
+ }
+ if (typeof animateFromPhoto === 'function') {
+ animateFromPhoto({path: activePath, prompt: prompt});
+ }
}
-function selectPreset(key) {
- document.querySelectorAll('#settingsPresets .preset-card').forEach(c => {
- c.classList.toggle('active', c.dataset.preset === key);
- const r = c.querySelector('input[type="radio"]');
- if (r) r.checked = (c.dataset.preset === key);
- });
- document.getElementById('settingsCustomSection').style.display =
- key === 'custom' ? 'block' : 'none';
- // Clear status so it doesn't claim "saved" after a fresh selection.
- document.getElementById('settingsStatus').textContent = '';
- document.getElementById('settingsStatus').className = 'settings-status';
-}
+async function hide(path) { await fetch('/output/hide?path='+encodeURIComponent(path),{method:'POST'}); currentOutputs = []; poll(); }
+async function unhide(path) { await fetch('/output/show?path='+encodeURIComponent(path),{method:'POST'}); currentOutputs = []; poll(); }
-async function applySettings() {
- const status = document.getElementById('settingsStatus');
- const btn = document.getElementById('settingsApplyBtn');
- status.textContent = 'Saving…';
- status.className = 'settings-status';
- btn.disabled = true;
- // Read which preset is selected. Custom path also sends pix_fmt + crf.
- const checked = document.querySelector('#settingsPresets input[type="radio"]:checked');
- const preset = checked ? checked.value : 'standard';
- const fd = new FormData();
- fd.set('output_preset', preset);
- if (preset === 'custom') {
- fd.set('output_pix_fmt', document.getElementById('settingsPixFmt').value);
- fd.set('output_crf', document.getElementById('settingsCrfNum').value);
- }
- fd.set('memory_policy', document.getElementById('settingsMemoryPolicy')?.value || 'auto');
- // Tokens — only send a key when the input has a value. Empty input
- // means "leave as-is" (clearing is explicit via the Clear button).
- // This protects against accidentally wiping a saved key by clicking
- // Apply on an unchanged form.
- const civInput = document.getElementById('civitaiKeyInput').value.trim();
- if (civInput) fd.set('civitai_api_key', civInput);
- const hfInput = document.getElementById('hfTokenInput').value.trim();
- if (hfInput) fd.set('hf_token', hfInput);
+async function deleteOutput(path) {
+ // Per-card × button. Moves the media (and any sibling sidecar JSON)
+ // to the macOS Trash via /output/delete — files are recoverable
+ // from Finder Trash via Cmd-Z right after, or by dragging them out
+ // of the Trash bin later. Toast confirms the move; if the user was
+ // viewing this clip in the expand lightbox, that closes too.
+ if (!path) return;
+ const base = path.split('/').pop();
+ if (!confirm('Move to Trash?\n\n' + base + '\n\nRestore from Finder if needed.')) return;
try {
- // Convert FormData → URLSearchParams so the body is sent as
- // x-www-form-urlencoded — the panel's parse_qs only understands
- // that wire format, NOT the multipart/form-data fetch sends by
- // default with FormData. This bug silently turned every settings
- // save into a no-op (server saw empty payload) until caught.
- const r = await fetch('/settings', {
- method: 'POST',
- headers: {'Content-Type': 'application/x-www-form-urlencoded'},
- body: new URLSearchParams(fd),
- });
- const data = await r.json();
- if (!r.ok || data.error) {
- status.textContent = data.error || `HTTP ${r.status}`;
- status.className = 'settings-status err';
- btn.disabled = false;
+ const fd = new URLSearchParams();
+ fd.set('path', path);
+ const r = await fetch('/output/delete', { method: 'POST', body: fd });
+ const data = await r.json().catch(() => ({}));
+ if (!r.ok || !data.ok) {
+ phosToast('Delete failed: ' + (data.error || ('HTTP ' + r.status)),
+ { kind: 'danger', duration: 5000 });
return;
}
- status.textContent = data.helper_restarted
- ? 'Saved. Helper restarted — takes effect on the next render.'
- : 'Saved.';
- status.className = 'settings-status ok';
- btn.disabled = false;
- // Refresh cache so a re-open shows the new values without a stale flash.
- _settingsCache = { ...(_settingsCache || {}), settings: data.settings };
+ // If the deleted clip was open in the expand lightbox, close it —
+ // otherwise the lightbox sits there pointing at a 404 URL.
+ if (activePath === path) {
+ activePath = null;
+ const lb = document.getElementById('expandLightbox');
+ if (lb && lb.style.display === 'flex' && typeof closeExpandLightbox === 'function') {
+ closeExpandLightbox();
+ }
+ }
+ currentOutputs = [];
+ poll();
+ phosToast('Moved to Trash · ' + base, { kind: 'success' });
} catch (e) {
- status.textContent = 'Network error: ' + (e.message || e);
- status.className = 'settings-status err';
- btn.disabled = false;
+ phosToast('Delete error: ' + (e.message || 'unknown'),
+ { kind: 'danger', duration: 5000 });
}
}
-// ====== HDR toggle pill (header pill behavior, same as No-music) ======
-(function () {
- const pill = document.getElementById('hdrPill');
- const cb = document.getElementById('hdr');
- if (!pill || !cb) return;
- const sync = () => pill.classList.toggle('on', cb.checked);
- cb.addEventListener('change', sync);
- pill.addEventListener('click', () => setTimeout(sync, 0));
- sync();
-})();
-
-// ====== CivitAI NSFW toggle pill (mirrors HDR toggle UX) ======
-(function () {
- const pill = document.getElementById('civitaiNsfwPill');
- const cb = document.getElementById('civitaiNsfw');
- if (!pill || !cb) return;
- const sync = () => pill.classList.toggle('on', cb.checked);
- cb.addEventListener('change', sync);
- pill.addEventListener('click', () => setTimeout(sync, 0));
- sync();
-})();
-
-// ====== LoRA picker ======
-//
-// State model: an in-memory list of LoRA entries the user has added.
-// Adding can come from "Use" on a CivitAI install or from clicking a
-// row in the local list. Each entry:
-// { path, name, strength, trigger_words, civitai_url }
-// On every change we mirror the list into the hidden #lorasJson field
-// so make_job's parse_loras_from_form picks them up at submit time.
-
-let _activeLoras = []; // [{path, name, strength, trigger_words, compatible_modes, ...}]
-let _knownUserLoras = []; // last list_user_loras() snapshot, for the picker
-
-// Resolve the compat tag the picker should filter by, based on the
-// CURRENT (mode + engine) selection. The unified picker lives in ONE
-// place but its library list re-filters when the user switches mode
-// (Manual T2V/I2V/keyframe/extend → "video") or when they pick a
-// different engine in Image Studio (Qwen-Edit → "image:qwen", FLUX.2
-// Klein-Edit → "image:flux2", etc.). Returns "" to mean "no filter,
-// show everything" — the back-compat path when we can't determine
-// the active engine.
-function _currentLoraModeFilter() {
- // `currentMode` is a `let` at the top of this <script> block (line ~15016),
- // sharing the same IIFE scope as setMode() and renderLorasList(). It is
- // NOT a property of `window` — `let`/`const` at the script's top level
- // are not auto-attached to globalThis in modern browsers. Reading
- // `window.currentMode` was always undefined, falling through to the
- // hidden #mode input which the image branch of setMode deliberately
- // doesn't update (to avoid an accidental form submit firing a video
- // render with stale fields). Net effect: the picker filter always
- // saw 't2v' even after the user clicked Studio. Read currentMode
- // directly via lexical capture so the mode-aware filter actually
- // works.
- const mode = (currentMode || document.getElementById('mode')?.value || 't2v');
- if (mode !== 'image') {
- // All video modes share the LTX lane.
- return 'video';
+async function openOutputsFolder() {
+ // One-click Reveal in Finder. Global, lives in the Outputs header so
+ // it isn't duplicated per-card. macOS `open <dir>` — Phosphene is
+ // Apple Silicon-only, no cross-platform branch.
+ try {
+ const r = await fetch('/output/open_folder', { method: 'POST' });
+ const data = await r.json().catch(() => ({}));
+ if (!r.ok || !data.ok) {
+ alert('Open folder failed: ' + (data.error || ('HTTP ' + r.status)));
+ }
+ } catch (e) {
+ alert('Open folder error: ' + (e.message || 'unknown'));
}
- // Image Studio: read the engine override + map to compat tag.
- const eng = (document.getElementById('imgStudioEngine')?.value || 'auto').toLowerCase();
- if (eng.startsWith('qwen_edit')) return 'image:qwen';
- if (eng.startsWith('flux2_edit') || eng.startsWith('flux2')) return 'image:flux2';
- if (eng.startsWith('flux1') || eng === 'flux1_inline') return 'image:flux1';
- if (eng.startsWith('kontext')) return 'image:kontext';
- if (eng.startsWith('z_image')) return 'image:z_image';
- if (eng.startsWith('hidream')) return 'image:hidream';
- // Mock engine is image-lane — narrow off LTX video LoRAs the same way
- // 'auto' does. Returning '' here skipped the filter entirely (same bug
- // ab50f12 fixed for 'auto'); video LTX LoRAs would re-appear in the
- // Image Studio picker when the user picked Mock for testing.
- if (eng.startsWith('mock')) return 'image';
- // 'auto' → fall back to the user's saved engine. Without a server
- // round-trip to /agent/config we don't know exactly which family
- // they saved; show ALL image-lane LoRAs (image:* + unknown) but
- // STILL hide LTX video LoRAs which can never run on mflux. Returning
- // 'image' as a meta-tag — the row filter below treats it as a
- // wildcard matching anything starting with `image:` plus `unknown`,
- // so we narrow off the LTX side without false-hiding the rest.
- // Returning '' here would (and did) skip the filter entirely
- // because `if (modeTag)` is falsy on empty string — that's the
- // bug the user hit when Studio + auto showed all 5 of their LTX
- // LoRAs in the picker.
- return 'image';
}
+function hideActive() { if (activePath) hide(activePath); }
-// Friendly label for the active filter, surfaced in the picker banner
-// so the user understands "why don't I see all my LoRAs". Mirrors the
-// _currentLoraModeFilter return values.
-function _loraFilterLabel(tag) {
- switch (tag) {
- case 'video': return 'LTX-Video LoRAs (active video mode)';
- case 'image': return 'image LoRAs (any mflux family — auto engine)';
- case 'image:qwen': return 'Qwen-Image / Qwen-Image-Edit LoRAs';
- case 'image:flux2': return 'FLUX.2 LoRAs';
- case 'image:flux1': return 'FLUX.1 LoRAs';
- case 'image:kontext': return 'FLUX.1 Kontext LoRAs';
- case 'image:z_image': return 'Z-Image LoRAs (none expected — most LoRAs trained for other families)';
- case 'image:sdxl': return 'SDXL LoRAs';
- case 'image:hidream': return 'HiDream LoRAs (LoRA support not yet implemented — picked LoRAs are ignored)';
- default: return 'all installed LoRAs';
- }
+function useAsExtendSourcePath(path) {
+ setMode('extend');
+ document.getElementById('video_path').value = path;
+ document.getElementById('extendSrcSelect').value = path;
+ updateDerived();
+ document.querySelector('aside.form-pane').scrollTop = 0;
}
+function useAsExtendSource() { if (!activePath) return alert('Pick an output first.'); useAsExtendSourcePath(activePath); }
-function _serializeLoras() {
- // What the helper actually needs is path + strength. Keep the rest in
- // the in-memory list for UI rendering, drop it on the wire. Summary
- // count is updated by renderLorasList() which has fuller state — we
- // don't touch it here to avoid two functions stomping each other.
- const slim = _activeLoras.map(l => ({ path: l.path, strength: l.strength }));
- document.getElementById('lorasJson').value = JSON.stringify(slim);
- // Train-Character LoRAs are trained against the dev transformer (HQ
- // path) — Quick/Standard run the distilled model at 8 steps, which is
- // a different fine-tune of the same architecture. Fusion succeeds
- // numerically but deltas don't transfer cleanly; the user sees muddy
- // output. Disable those chips when any trained LoRA is attached so
- // the wrong-path landing becomes visible.
- try { updateQualityChipsForLora(); } catch (_) {}
-}
+async function loadParams() {
+ if (!activePath) return;
+ const r = await fetch('/sidecar?path='+encodeURIComponent(activePath));
+ if (!r.ok) return;
+ const data = await r.json();
+ const p = data.params;
+ if (p.mode === 'extend') setMode('extend');
+ else if (p.mode === 'keyframe') setMode('keyframe');
+ else if (p.mode === 'i2v_clean_audio' || p.mode === 'i2v') { setMode('i2v'); document.getElementById('i2vMode').value = p.mode; document.getElementById('mode').value = p.mode; }
+ else setMode('t2v');
+ // Apply quality + aspect FIRST (these stomp on width/height), then
+ // override with explicit sidecar values so any custom dims survive.
+ if (p.quality) setQuality(p.quality);
+ // Snap aspect from the sidecar's recorded dims; only call when quality
+ // isn't 'quick' (Quick has no aspect choice and the row is hidden).
+ if (p.quality !== 'quick' && p.width && p.height) {
+ for (const [k, a] of Object.entries(ASPECTS)) {
+ if ((a.w === p.width && a.h === p.height) ||
+ (a.h === p.width && a.w === p.height)) { setAspect(k); break; }
+ }
+ }
+ // Now load explicit dims — overrides whatever the preset/aspect set.
+ if (p.width) document.getElementById('width').value = p.width;
+ if (p.height) document.getElementById('height').value = p.height;
+ if (p.accel) setAccel(p.accel);
+ if (p.temporal_mode) setTemporalMode(p.temporal_mode);
+ if (p.upscale) setUpscale(p.upscale);
+ if (p.upscale_method) setUpscaleMethod(p.upscale_method);
+ document.getElementById('prompt').value = p.prompt || '';
+ document.getElementById('negative_prompt').value = p.negative_prompt || '';
+ // If the loaded sidecar carried an Avoid value, surface the row so the
+ // user can see it without having to click the toggle.
+ syncAvoidRowFromValue();
+ if (p.frames) { document.getElementById('frames').value = p.frames; document.getElementById('duration').value = framesToDuration(p.frames); }
+ if (p.steps) document.getElementById('steps').value = p.steps;
+ if (p.seed != null) document.getElementById('seed').value = p.seed;
+ // Image / start / end go through pickerSetImage so the preview tile
+ // and recent-strip selection state update along with the hidden input.
+ if (p.image) pickerSetImage('image', p.image, { snapAspect: false });
+ if (p.start_image) pickerSetImage('start_image', p.start_image, { snapAspect: false });
+ if (p.end_image) pickerSetImage('end_image', p.end_image, { snapAspect: false });
+ if (p.audio) document.getElementById('audio').value = p.audio;
+ // Extend-specific: restore source video path
+ if (p.video_path) document.getElementById('video_path').value = p.video_path;
+ if (p.label) document.getElementById('preset_label').value = p.label;
-function updateQualityChipsForLora() {
- const trained = Array.isArray(_activeLoras) && _activeLoras.some(a => {
- const meta = Array.isArray(_knownUserLoras)
- ? _knownUserLoras.find(u => u.path === a.path)
- : null;
- // _knownUserLoras carries the raw sidecar kind ('train_character');
- // 'trained' is only a display-side alias built inside renderLorasList.
- // Match the raw value so the chip disable actually fires.
- return meta && meta.kind === 'train_character';
- });
- document.querySelectorAll('#qualityGroup .pill-btn').forEach(b => {
- const q = b.dataset.quality;
- const incompat = trained && (q === 'quick' || q === 'standard');
- b.classList.toggle('disabled', incompat);
- if (incompat) {
- b.title = 'Trained character LoRA needs the dev transformer (High quality). Quick/Standard run the distilled model — different fine-tune, so the LoRA can\'t reproduce the character faithfully.';
- } else if (b.dataset.tooltipDefault) {
- b.title = b.dataset.tooltipDefault;
- } else {
- b.removeAttribute('title');
+ // Restore the LoRA picker state. Without this, Load Params would silently
+ // drop every LoRA the prior render used — prompt + seed + dims all match
+ // but `loras=0` would go on the wire and the model would re-render
+ // without fusion (no face/style transfer). Wire shape on the sidecar is
+ // a list of {path, strength}; we re-decorate with `name` + `trigger_words`
+ // from _knownUserLoras when available so the chip renders nicely.
+ if (Array.isArray(p.loras)) {
+ _activeLoras = p.loras.map(l => {
+ const path = l.path;
+ const strength = (typeof l.strength === 'number') ? l.strength : 1.0;
+ const meta = (Array.isArray(_knownUserLoras)
+ ? _knownUserLoras.find(u => u.path === path)
+ : null) || {};
+ return {
+ path,
+ strength,
+ name: meta.name || (path ? path.split('/').pop() : 'LoRA'),
+ trigger_words: meta.trigger_words || [],
+ compatible_modes: meta.compatible_modes || ['unknown'],
+ };
+ }).filter(x => x.path);
+ if (typeof renderLorasList === 'function') {
+ try { renderLorasList(); } catch (_) {}
+ }
+ if (typeof _serializeLoras === 'function') {
+ try { _serializeLoras(); } catch (_) {}
}
- });
- // If the currently-selected preset just became incompatible, bump to High.
- const cur = document.getElementById('quality').value;
- if (trained && (cur === 'quick' || cur === 'standard')) {
- setQuality('high');
}
-}
-function addLoraToActive(entry) {
- // Idempotent: same path twice = update strength only.
- const existing = _activeLoras.find(l => l.path === entry.path);
- if (existing) {
- existing.strength = entry.strength;
- } else {
- _activeLoras.push(entry);
- }
- renderLorasList();
- _serializeLoras();
+ updateCustomizeSummary();
+ updateDerived();
}
-function removeLoraFromActive(path) {
- _activeLoras = _activeLoras.filter(l => l.path !== path);
- renderLorasList();
- _serializeLoras();
-}
+// ====== Output info modal ======
+//
+// Opened by the ⓘ button on each gallery card. Shows the full sidecar
+// (.mp4.json) we wrote at render time: prompt, seed, mode, dimensions,
+// frames, steps, LoRAs used (with display names + strengths), elapsed
+// time, queue id, model. Plus per-field copy buttons for the things
+// users actually want to reuse (prompt + seed).
+//
+// Why a modal and not inline detail-on-hover: the prompt alone can be
+// 1000+ chars; trying to render it inline next to the thumbnail would
+// blow up the gallery layout. Modal lets us scroll comfortably.
-function setLoraStrength(path, strength) {
- const e = _activeLoras.find(l => l.path === path);
- if (!e) return;
- e.strength = Math.max(-2, Math.min(2, parseFloat(strength) || 0));
- _serializeLoras();
-}
+let _outputInfoLastPath = null;
-async function refreshLoras() {
- // Pull the FULL library (no mode filter) so _knownUserLoras keeps every
- // entry — that lets refreshLoras() also serve as the "deleted on disk"
- // garbage collector below. The visible filter is applied client-side
- // in renderLorasList() via _currentLoraModeFilter(), which keeps the
- // round-trip count to one and avoids re-fetching every time the
- // user flips mode/engine.
+async function openOutputInfoModal(path) {
+ _outputInfoLastPath = path;
+ const modal = document.getElementById('outputInfoModal');
+ const body = document.getElementById('outputInfoBody');
+ const title = document.getElementById('outputInfoTitle');
+ modal.style.display = 'flex';
+ body.innerHTML = '<div class="hint">Loading…</div>';
+ // Display the filename in the modal title for quick orientation.
+ const fname = path.split('/').pop();
+ if (title) title.textContent = `Generation info · ${fname}`;
let data;
try {
- data = await (await fetch('/loras')).json();
+ const r = await fetch('/sidecar?path=' + encodeURIComponent(path));
+ if (!r.ok) {
+ body.innerHTML = `<div class="hint">No sidecar metadata for this output (older generation, or sidecar was deleted).</div>`;
+ return;
+ }
+ data = await r.json();
} catch (e) {
+ body.innerHTML = `<div class="hint">Couldn't load info: ${escapeHtml(e.message || String(e))}</div>`;
return;
}
- _knownUserLoras = data.user || [];
- // Update displayed loras dir
- if (data.loras_dir) {
- const dirEl = document.getElementById('lorasDir');
- if (dirEl) dirEl.textContent = data.loras_dir;
- }
- // Backfill compatible_modes on any active LoRA whose entry we now
- // have full metadata for — addLoraToActive() may have stored a sparse
- // {path, strength, name} from a CivitAI install before /loras was
- // refreshed.
- for (const a of _activeLoras) {
- if (!a.compatible_modes) {
- const ul = _knownUserLoras.find(u => u.path === a.path);
- if (ul) a.compatible_modes = ul.compatible_modes || ['unknown'];
- }
- }
- // If a row was previously active but the file is gone (deleted on
- // disk), drop it from the active set so we don't submit a stale path.
- const knownPaths = new Set(_knownUserLoras.map(l => l.path));
- _activeLoras = _activeLoras.filter(l =>
- knownPaths.has(l.path) || l.path.includes('/')); // keep HF ids (no dir slash)
- renderLorasList();
- _serializeLoras();
+ body.innerHTML = renderOutputInfoBody(path, data);
}
-function renderLorasList() {
- const wrap = document.getElementById('lorasList');
- const empty = document.getElementById('lorasEmpty');
- const filterRow = document.getElementById('lorasFilterRow');
- const filterInput = document.getElementById('lorasFilter');
- const banner = document.getElementById('loraModeBanner');
- if (!wrap) return;
-
- // Resolve current (mode + engine) → compat tag. Drives both the
- // library filter AND the per-active-chip "wrong family" warning.
- const modeTag = _currentLoraModeFilter();
-
- // Combine: user-installed LoRAs (from /loras) plus any active LoRAs
- // that aren't user-installed (HF repo paths, e.g. from the HDR toggle).
- const allRows = [];
- const seen = new Set();
- for (const ul of _knownUserLoras) {
- const active = _activeLoras.find(a => a.path === ul.path);
- seen.add(ul.path);
- allRows.push({
- path: ul.path,
- name: ul.name,
- trigger_words: ul.trigger_words || [],
- recommended_strength: ul.recommended_strength || 1.0,
- filename: ul.filename,
- civitai_url: ul.civitai_url,
- compatible_modes: ul.compatible_modes || ['unknown'],
- active: !!active,
- strength: active ? active.strength : (ul.recommended_strength || 1.0),
- // 'user' = downloaded/installed (CivitAI or manual);
- // 'trained' = produced by Phosphene's in-app Train Character pipeline
- // ('kind' on the sidecar is 'train_character'). The picker badges
- // these separately so the user finds their own characters fast.
- kind: ul.kind === 'train_character' ? 'trained' : 'user',
- });
- }
- for (const a of _activeLoras) {
- if (seen.has(a.path)) continue;
- allRows.push({
- path: a.path,
- name: a.name || a.path,
- trigger_words: a.trigger_words || [],
- recommended_strength: 1.0,
- filename: null,
- civitai_url: null,
- compatible_modes: a.compatible_modes || ['unknown'],
- active: true,
- strength: a.strength,
- kind: 'remote',
- });
- }
-
- // Empty state — collapse the filter box too.
- if (allRows.length === 0) {
- wrap.innerHTML = '';
- if (empty) empty.style.display = '';
- if (filterRow) filterRow.style.display = 'none';
- if (banner) banner.textContent = '';
- return;
- }
- if (empty) empty.style.display = 'none';
-
- // Apply mode-aware filter FIRST. Hard-filter EVERY row (active OR not)
- // whose compatible_modes don't intersect the active engine. This is the
- // tight-integration version the user explicitly asked for — the prior
- // behavior of "keep mismatched active rows visible with ⚠" was
- // confusing ("now I see the LoRA, but there is no filtering by selected
- // model"). Mismatched-active rows aren't deleted from `_activeLoras` —
- // they're just hidden from this list while the engine is set this way,
- // so flipping back to a compatible engine restores them. The "+ N from
- // other modes" pill at the bottom of the banner is the escape hatch
- // for the rare user who wants to manage a hidden chip without
- // switching engines first.
- //
- // "unknown" compatible_modes still pass every filter — sidecar-less
- // LoRAs need to be reachable, the picker indicator is the user's cue
- // that the family wasn't auto-detected.
- let rows = allRows;
- let hiddenCount = 0;
- const showOtherModes = !!window._loraShowOtherModes;
- if (modeTag) {
- rows = allRows.filter(r => {
- const tags = r.compatible_modes || ['unknown'];
- let matches;
- if (modeTag === 'image') {
- // Meta-tag: image-engine UNKNOWN (auto preset). Match any
- // specific `image:*` tag plus `unknown`. Hides `video` so LTX
- // LoRAs don't pollute the image picker even when we can't tell
- // exactly which mflux family the user has saved as default.
- matches = tags.some(t => t === 'unknown' || (typeof t === 'string' && t.startsWith('image:')));
- } else {
- matches = tags.includes(modeTag) || tags.includes('unknown');
- }
- if (!matches && !showOtherModes) hiddenCount++;
- return matches || showOtherModes;
- });
- }
- // Surface the filter input only when 5+ LoRAs (post-mode-filter)
- // remain; below that it's just visual noise.
- if (filterRow) filterRow.style.display = (rows.length >= 5) ? '' : 'none';
-
- // Then text filter (case-insensitive substring on name + trigger words).
- const q = (filterInput && filterInput.value || '').trim().toLowerCase();
- if (q) {
- rows = rows.filter(r => {
- if (r.name && r.name.toLowerCase().includes(q)) return true;
- for (const t of (r.trigger_words || [])) {
- if (String(t).toLowerCase().includes(q)) return true;
- }
- return false;
- });
- }
- // Sort: active rows first (so the user's selection floats to the top),
- // then alphabetical by name. Stable enough for a UI list.
- rows.sort((a, b) => {
- if (a.active !== b.active) return a.active ? -1 : 1;
- return (a.name || '').localeCompare(b.name || '');
- });
+function closeOutputInfoModal() {
+ document.getElementById('outputInfoModal').style.display = 'none';
+}
- // Mode banner — explains the active filter so users grok "why don't
- // I see all my LoRAs". When mismatched LoRAs exist (active OR not),
- // exposes a "Show N from other modes" toggle so the user has an
- // escape hatch to manage them without switching engines first.
- if (banner) {
- let bannerHtml = `Library filter: <strong>${escapeHtml(_loraFilterLabel(modeTag))}</strong>`;
- if (hiddenCount > 0) {
- bannerHtml += ` · <a href="#" style="color:var(--muted)" onclick="event.preventDefault(); window._loraShowOtherModes = true; renderLorasList()">Show ${hiddenCount} from other modes</a>`;
- } else if (showOtherModes) {
- bannerHtml += ` · <a href="#" style="color:var(--muted)" onclick="event.preventDefault(); window._loraShowOtherModes = false; renderLorasList()">Hide other modes</a>`;
- }
- // Empty image-mode case — when the library has zero compatible
- // LoRAs, point users at the install path so they don't think the
- // picker's broken.
- if (modeTag && modeTag.startsWith('image:') && rows.length === 0 && _knownUserLoras.length > 0) {
- bannerHtml += ` · <span style="color:var(--muted)">No image LoRAs in your library — install one via the CivitAI browser, filter by Flux / Qwen Image base models.</span>`;
+function _copyToClipboard(text, btn) {
+ // Best-effort copy with visual feedback. Falls back silently when the
+ // clipboard API is blocked (e.g. iframe sandboxes without permissions).
+ try {
+ navigator.clipboard.writeText(text);
+ if (btn) {
+ const orig = btn.textContent;
+ btn.textContent = 'Copied!';
+ setTimeout(() => { btn.textContent = orig; }, 1200);
}
- banner.innerHTML = bannerHtml;
- }
+ } catch (e) { /* swallow */ }
+}
- // Update header summary.
- const summary = document.getElementById('lorasSummaryCount');
- if (summary) {
- const total = allRows.length;
- const active = allRows.filter(r => r.active).length;
- summary.textContent = `${total} installed · ${active} active${q ? ` · ${rows.length} match` : ''}`;
- }
+function _humanSize(b) {
+ if (b == null) return '';
+ if (b < 1024) return `${b} B`;
+ if (b < 1024*1024) return `${(b/1024).toFixed(1)} KB`;
+ if (b < 1024*1024*1024) return `${(b/1024/1024).toFixed(1)} MB`;
+ return `${(b/1024/1024/1024).toFixed(2)} GB`;
+}
- if (rows.length === 0) {
- wrap.innerHTML = `<div class="hint" style="padding:8px 0;">No LoRAs match "${escapeHtml(q)}".</div>`;
- return;
- }
- wrap.innerHTML = rows.map(r => loraRowHtml(r, modeTag)).join('');
+function _humanDuration(s) {
+ if (s == null) return '';
+ if (s < 60) return `${s.toFixed(1)} s`;
+ const m = Math.floor(s / 60); const r = (s - m*60).toFixed(0);
+ return `${m} min ${r} s`;
}
-// Build a single compact LoRA row. Inactive rows are ~36px tall (just
-// name + meta + corner actions). Active rows expand inline with the
-// strength slider and trigger chips. Click anywhere on the main row to
-// toggle activation.
-//
-// modeTag is the active engine compat tag (e.g. "image:qwen") — used to
-// render the per-chip warning when an ACTIVE LoRA doesn't fit the
-// current engine, and a `?` indicator for unclassified LoRAs.
-function loraRowHtml(r, modeTag) {
- const pathHtml = escapeHtml(r.path);
- const pathAttr = JSON.stringify(r.path).replace(/"/g, '&quot;');
- const nameHtml = escapeHtml(r.name);
- const nameAttr = JSON.stringify(r.name).replace(/"/g, '&quot;');
- // Per-row family badges. `?` for unknown family (unclassified
- // base_model), `⚠` for an ACTIVE LoRA whose compat tags don't match
- // the current engine — clear visible signal that "this chip stays
- // selected but won't actually fire on the engine you've chosen".
- const tags = r.compatible_modes || ['unknown'];
- const isUnknown = tags.length === 1 && tags[0] === 'unknown';
- const familyMismatch = !!(modeTag && r.active
- && !tags.includes(modeTag) && !tags.includes('unknown'));
- const familyBadges = [];
- if (isUnknown) {
- familyBadges.push(`<span class="badge" title="Unknown LoRA family — sidecar didn't list a base_model. May or may not fire on this engine.">?</span>`);
+function renderOutputInfoBody(path, data) {
+ const p = (data && data.params) || {};
+ const loras = Array.isArray(p.loras) ? p.loras : [];
+
+ // Look up each LoRA's display name from the installed-LoRAs cache so
+ // the modal shows "Claymation Style" instead of the raw safetensors
+ // path. Falls back gracefully when a LoRA was deleted or is an HF id.
+ const lookupLoraName = (loraPath) => {
+ if (!loraPath) return '?';
+ const known = (_knownUserLoras || []).find(l => l.path === loraPath);
+ if (known) return known.name;
+ if (loraPath.includes('/') && !loraPath.endsWith('.safetensors')) return loraPath;
+ return loraPath.split('/').pop().replace(/\.safetensors$/, '');
+ };
+
+ const promptText = p.prompt || '';
+ const promptAttr = JSON.stringify(promptText).replace(/"/g, '&quot;');
+ const seedVal = String(p.seed_used != null ? p.seed_used : p.seed || '');
+ const seedAttr = JSON.stringify(seedVal).replace(/"/g, '&quot;');
+ const pathAttr = JSON.stringify(path).replace(/"/g, '&quot;');
+ const accelMetrics = (data && data.accel_metrics) || null;
+ const modeLabel = ({
+ t2v: 'Text → Video',
+ i2v: 'Image → Video',
+ i2v_clean_audio: 'Image → Video (clean audio)',
+ keyframe: 'FFLF (first + last frame)',
+ extend: 'Extend',
+ })[p.mode] || (p.mode || '—');
+
+ // Compose the dimensions + duration into a single "Format" line — fewer
+ // grid rows, easier to scan. We separate technical metadata (Format,
+ // Frames) from generation parameters (Mode, Quality, Seed, Steps).
+ const formatBits = [];
+ if (p.width && p.height) formatBits.push(`${p.width} × ${p.height}`);
+ if (data.video_duration_sec != null) formatBits.push(`${data.video_duration_sec.toFixed(2)} s @ ${data.fps || 24} fps`);
+
+ let html = '';
+
+ // ---- Output (technical) ----
+ html += `<div class="oi-section">
+ <div class="oi-section-title"><span>Output</span></div>
+ <dl class="oi-grid">
+ ${formatBits.length ? `<dt>Format</dt><dd>${formatBits.join(' · ')}</dd>` : ''}
+ ${p.frames != null ? `<dt>Frames</dt><dd>${p.frames}</dd>` : ''}
+ </dl>
+ </div>`;
+
+ // ---- Generation parameters ----
+ const genRows = [];
+ genRows.push(`<dt>Mode</dt><dd>${escapeHtml(modeLabel)}</dd>`);
+ genRows.push(`<dt>Quality</dt><dd>${escapeHtml((p.quality || 'standard').replace(/^./, c => c.toUpperCase()))}</dd>`);
+ if (p.accel && p.accel !== 'off') {
+ genRows.push(`<dt>Speed</dt><dd>${escapeHtml(p.accel.replace(/^./, c => c.toUpperCase()))}</dd>`);
}
- if (familyMismatch) {
- familyBadges.push(`<span class="badge" style="background:rgba(232,179,65,0.15);color:var(--warn,#e8b341)" title="This LoRA was trained for a different family (${tags.join(', ')}) — it will be passed to mflux but probably won't influence the output. Switch the Engine dropdown to a matching family, or remove this LoRA."><svg class="ph" aria-hidden="true"><use href="#ph-warning-fill"/></svg></span>`);
+ if (accelMetrics && p.accel && p.accel !== 'off') {
+ const cachedCount = accelMetrics.cached_steps_count || 0;
+ const totalSteps = accelMetrics.total_steps || p.steps || 0;
+ const savings = accelMetrics.estimated_denoise_call_savings_pct;
+ const cachedList = Array.isArray(accelMetrics.cached_steps) && accelMetrics.cached_steps.length
+ ? ` · cached steps ${escapeHtml(accelMetrics.cached_steps.join(', '))}`
+ : '';
+ const savingsText = savings != null ? ` · ~${escapeHtml(String(savings))}% denoise calls saved` : '';
+ genRows.push(`<dt>Accel metrics</dt><dd>${cachedCount}/${totalSteps} cached${savingsText}${cachedList}</dd>`);
}
- // Trigger summary line under the name (when not expanded). Truncated.
- const trigs = r.trigger_words || [];
- const trigSummary = trigs.length
- ? trigs.slice(0, 4).join(' · ') + (trigs.length > 4 ? ` +${trigs.length - 4}` : '')
- : 'no trigger word';
- // Corner actions — link to civitai page + delete (or remove for HF/remote).
- const corner = [];
- if (r.civitai_url) {
- corner.push(`<a class="lora-icon-btn" href="${escapeHtml(r.civitai_url)}" target="_blank" rel="noopener" title="Open on CivitAI" onclick="event.stopPropagation()"><svg class="ph" aria-hidden="true"><use href="#ph-arrow-square-out"/></svg></a>`);
+ if (data.memory_policy) {
+ const mp = data.memory_policy;
+ const req = mp.requested || p.memory_policy || 'auto';
+ const eff = mp.effective || req;
+ const decode = mp.vae_decode || (mp.helper && mp.helper.vae_decode) || '';
+ const fullMax = mp.full_decode_max_frames != null ? ` · full≤${escapeHtml(String(mp.full_decode_max_frames))}f` : '';
+ const reason = mp.reason ? ` · ${escapeHtml(mp.reason)}` : '';
+ genRows.push(`<dt>Memory</dt><dd>${escapeHtml(req)}${eff !== req ? ` → ${escapeHtml(eff)}` : ''}${decode ? ` · VAE ${escapeHtml(decode)}` : ''}${fullMax}${reason}</dd>`);
}
- if (r.kind === 'user' || r.kind === 'trained') {
- corner.push(`<button class="lora-icon-btn danger" type="button" title="Delete from disk"
- onclick="event.stopPropagation(); deleteLora(${pathAttr}, ${nameAttr})"><svg class="ph" aria-hidden="true"><use href="#ph-x-bold"/></svg></button>`);
- } else {
- corner.push(`<button class="lora-icon-btn" type="button" title="Remove from active set"
- onclick="event.stopPropagation(); removeLoraFromActive(${pathAttr})"><svg class="ph" aria-hidden="true"><use href="#ph-x-bold"/></svg></button>`);
+ if (p.temporal_mode === 'fps12_interp24' || data.temporal) {
+ const t = data.temporal || {};
+ const sourceFrames = t.source_frames || p.model_frames || '—';
+ const deliveryFrames = t.delivery_frames || p.frames || '—';
+ const sourceFps = t.model_fps || p.model_fps || 12;
+ const deliveryFps = t.delivery_fps || p.delivery_fps || 24;
+ genRows.push(`<dt>Long clips</dt><dd>12 → 24fps · LTX ${escapeHtml(String(sourceFrames))}f @ ${escapeHtml(String(sourceFps))}fps → ${escapeHtml(String(deliveryFrames))}f @ ${escapeHtml(String(deliveryFps))}fps</dd>`);
}
- // Trigger chips for the expanded section. Same click-to-append behavior
- // as before — chips prepend the trigger to the prompt textarea.
- const chipsHtml = trigs.length
- ? trigs.slice(0, 12).map(w => {
- const wAttr = JSON.stringify(w).replace(/"/g, '&quot;');
- return `<span class="trigger-chip" title="Click to add to prompt"
- onclick="event.stopPropagation(); appendTriggerToPrompt(${wAttr})">${escapeHtml(w)}</span>`;
- }).join('')
- : `<span class="trigger-chip empty">style-only LoRA — no trigger word needed</span>`;
-
- return `
- <div class="lora-row ${r.active ? 'active' : ''}" data-path="${pathHtml}">
- <div class="lora-row-main"
- onclick="toggleLora(${pathAttr}, ${!r.active}, ${r.recommended_strength}, ${nameAttr})">
- <div class="lora-toggle-dot"></div>
- <div class="lora-text">
- <div class="lora-name" title="${pathHtml}">
- ${nameHtml}${r.kind === 'remote' ? '<span class="badge">HF</span>' : ''}${r.kind === 'trained' ? '<span class="badge badge-trained" title="Trained in Phosphene’s Train Character workflow">Trained</span>' : ''}${familyBadges.join('')}
- </div>
- <div class="lora-name-meta" title="${escapeHtml(trigs.join(', '))}">${escapeHtml(trigSummary)}</div>
- </div>
- <div class="lora-row-actions">${corner.join('')}</div>
- </div>
- <div class="lora-row-extra">
- <div class="lora-strength-row">
- <label>strength</label>
- <input type="range" min="-2" max="2" step="0.05" value="${r.strength}"
- onclick="event.stopPropagation()"
- oninput="this.nextElementSibling.value = this.value; setLoraStrength(${pathAttr}, this.value)">
- <input type="number" min="-2" max="2" step="0.05" value="${r.strength}"
- onclick="event.stopPropagation()"
- oninput="this.previousElementSibling.value = this.value; setLoraStrength(${pathAttr}, this.value)">
- </div>
- <div class="trigger-chips">${chipsHtml}</div>
- </div>
- </div>`;
-}
-
-function toggleLora(path, on, recommended, name) {
- if (on) {
- addLoraToActive({ path, strength: recommended, name });
- // Auto-insert the LoRA's first trigger word into the prompt so the
- // user doesn't have to remember + retype it. The biggest source of
- // "I activated the LoRA but it didn't fire" reports is the trigger
- // missing from the prompt entirely. appendTriggerToPrompt is
- // idempotent — duplicate clicks are no-ops. Skips silently if the
- // LoRA has no trigger_words (style-only LoRAs).
- try {
- const meta = _knownUserLoras.find(u => u.path === path);
- const triggers = (meta && meta.trigger_words) || [];
- if (triggers.length) {
- appendTriggerToPrompt(triggers[0]);
- }
- } catch (e) { /* picker race during boot — ignore */ }
- } else {
- removeLoraFromActive(path);
+ if (p.upscale && p.upscale !== 'off') {
+ const up = data.upscale || {};
+ const target = up.target_w && up.target_h ? ` → ${up.target_w} × ${up.target_h}` : '';
+ const isSharp = p.upscale_method === 'pipersr' || p.upscale_method === 'model' || (data.upscale && (data.upscale.method === 'pipersr_coreml' || data.upscale.pre_pass === 'pipersr_x2' || data.upscale.method === 'ltx_latent_x2' || data.upscale.pre_pass === 'ltx_latent_x2'));
+ const baseLabel = p.upscale === 'fit_720p' ? '720p fit (no crop)' : (p.upscale === 'x2' ? '2×' : p.upscale);
+ const label = isSharp ? `${baseLabel} · Sharp (PiperSR)` : `${baseLabel} · Fast (Lanczos)`;
+ genRows.push(`<dt>Upscale</dt><dd>${escapeHtml(label + target)}</dd>`);
}
-}
-
-// Append a LoRA's trigger word to the prompt textarea. Most LTX LoRAs
-// only fully activate when their trigger word is somewhere in the prompt,
-// and asking users to remember + type a string like "DISPSTYLE" exactly
-// is friction. Click the chip → it goes in. Idempotent: if the word is
-// already present (case-insensitive substring), do nothing so users can
-// click freely without piling duplicates.
-function appendTriggerToPrompt(word) {
- const ta = document.getElementById('prompt');
- if (!ta) return;
- const cur = ta.value || '';
- if (cur.toLowerCase().includes(String(word).toLowerCase())) {
- // Brief visual ping so the click feels acknowledged even though we
- // didn't change anything — otherwise users repeat-click thinking
- // it's broken.
- ta.classList.add('flash-ok');
- setTimeout(() => ta.classList.remove('flash-ok'), 250);
- return;
+ const codec = data.output_codec || (data.upscale && data.upscale.codec);
+ if (codec && codec.pix_fmt && codec.crf != null) {
+ const preset = codec.preset ? ` · ${codec.preset}` : '';
+ genRows.push(`<dt>Output codec</dt><dd>${escapeHtml(codec.pix_fmt)} · CRF ${escapeHtml(String(codec.crf))}${escapeHtml(preset)}</dd>`);
}
- // If the user has typed nothing, drop the trigger in alone. Otherwise
- // prepend to the existing prompt: many LoRA authors put the trigger
- // FIRST in their examples, and quality often degrades when the trigger
- // is buried at the end past 20+ tokens of unrelated context.
- if (cur.trim() === '') {
- ta.value = String(word);
- } else {
- ta.value = String(word) + ', ' + cur;
+ if (p.negative_prompt) {
+ genRows.push(`<dt>Avoid</dt><dd>${escapeHtml(snippet(p.negative_prompt, 90))}</dd>`);
+ }
+ if (seedVal) {
+ genRows.push(`<dt>Seed</dt><dd>
+ <code>${escapeHtml(seedVal)}</code>
+ <button class="oi-copy" type="button" onclick="_copyToClipboard(${seedAttr}, this)">Copy</button>
+ </dd>`);
+ }
+ if (p.steps != null) genRows.push(`<dt>Steps</dt><dd>${p.steps}</dd>`);
+ if (p.hdr) genRows.push(`<dt>HDR</dt><dd>On</dd>`);
+ if (p.label) genRows.push(`<dt>Label</dt><dd>${escapeHtml(p.label)}</dd>`);
+
+ html += `<div class="oi-section">
+ <div class="oi-section-title"><span>Generation</span></div>
+ <dl class="oi-grid">${genRows.join('')}</dl>
+ </div>`;
+
+ // ---- Prompt ----
+ if (promptText) {
+ html += `<div class="oi-section">
+ <div class="oi-section-title">
+ <span>Prompt</span>
+ <button class="oi-copy" type="button" onclick="_copyToClipboard(${promptAttr}, this)">Copy</button>
+ </div>
+ <div class="oi-prompt">${escapeHtml(promptText)}</div>
+ </div>`;
}
- ta.focus();
- ta.dispatchEvent(new Event('input', { bubbles: true }));
-}
-async function deleteLora(path, name) {
- if (!confirm(`Delete the LoRA file for "${name}" from disk? This is permanent.`)) {
- return;
+ // ---- LoRAs (flat list, hairline-separated) ----
+ if (loras.length) {
+ const rows = loras.map(l => {
+ const name = lookupLoraName(l.path);
+ const strength = (l.strength != null ? l.strength : 1).toFixed(2);
+ return `<div class="oi-lora-row">
+ <span class="oi-lora-name" title="${escapeHtml(l.path || '')}">${escapeHtml(name)}</span>
+ <span class="oi-lora-strength">strength ${strength}</span>
+ </div>`;
+ }).join('');
+ html += `<div class="oi-section">
+ <div class="oi-section-title">
+ <span>LoRAs used</span>
+ <span class="oi-count">${loras.length}</span>
+ </div>
+ <div class="oi-lora-list">${rows}</div>
+ </div>`;
}
- const fd = new FormData();
- fd.set('path', path);
- try {
- const r = await fetch('/loras/delete', {
- method: 'POST',
- headers: {'Content-Type': 'application/x-www-form-urlencoded'},
- body: new URLSearchParams(fd),
- });
- const data = await r.json();
- if (!r.ok || !data.ok) {
- alert('Delete failed: ' + (data.error || `HTTP ${r.status}`));
- return;
- }
- removeLoraFromActive(path);
- refreshLoras();
- } catch (e) {
- alert('Delete failed: ' + (e.message || e));
+
+ // ---- Timing + provenance ----
+ const timingRows = [];
+ if (data.started) timingRows.push(`<dt>Started</dt><dd>${escapeHtml(data.started)}</dd>`);
+ if (data.elapsed_sec != null) timingRows.push(`<dt>Elapsed</dt><dd>${_humanDuration(data.elapsed_sec)}</dd>`);
+ if (data.queue_id) timingRows.push(`<dt>Queue ID</dt><dd><code>${escapeHtml(data.queue_id)}</code></dd>`);
+ if (data.model) timingRows.push(`<dt>Model</dt><dd><code>${escapeHtml(data.model.split('/').pop())}</code></dd>`);
+ if (timingRows.length) {
+ html += `<div class="oi-section">
+ <div class="oi-section-title"><span>Timing</span></div>
+ <dl class="oi-grid">${timingRows.join('')}</dl>
+ </div>`;
}
-}
-// ====== CivitAI modal ======
+ // ---- Action row ----
+ html += `<div class="oi-actions">
+ <button class="ghost-btn" type="button" onclick="closeOutputInfoModal()">Close</button>
+ <button class="oi-primary" type="button"
+ onclick="closeOutputInfoModal(); selectOutput(${pathAttr}); loadParams()">
+ Load params into form
+ </button>
+ </div>`;
-let _civitaiCursor = '';
-let _civitaiSearching = false;
+ return html;
+}
-function openCivitaiModal() {
- document.getElementById('civitaiModal').style.display = 'flex';
- // Pull /loras to populate the dir text and the auth-banner state.
- fetch('/loras').then(r => r.json()).then(d => {
- const dirEl = document.getElementById('civitaiTargetDir');
- if (dirEl && d.loras_dir) dirEl.textContent = d.loras_dir;
- renderCivitaiAuthBanner(!!d.civitai_auth);
- }).catch(() => { renderCivitaiAuthBanner(false); });
- document.getElementById('civitaiQuery').value = '';
- _civitaiCursor = '';
- // Pull current Spicy mode state so the "Show NSFW" toggle hides when off.
- refreshCivitaiAccessUI();
- civitaiSearch();
+async function removeJob(id) { await fetch('/queue/remove?id='+encodeURIComponent(id),{method:'POST'}); poll(); }
+async function togglePause() {
+ const s = await (await fetch('/status')).json();
+ await api(s.paused ? '/queue/resume' : '/queue/pause', 'POST');
+ poll();
}
-// Hide / show the "Show NSFW" toggle in the CivitAI browser based on the
-// Spicy mode setting. Called on modal open and after toggleSpicyMode flips
-// the value, so the UI tracks the gate without a page reload.
-async function refreshCivitaiAccessUI() {
- let spicy = false;
- try {
- const r = await fetch('/settings');
- const j = await r.json();
- spicy = !!(j && j.settings && j.settings.spicy_mode);
- } catch (_) { /* default off */ }
- const pill = document.getElementById('civitaiNsfwPill');
- const cb = document.getElementById('civitaiNsfw');
- if (pill) pill.style.display = spicy ? '' : 'none';
- if (!spicy && cb) cb.checked = false; // force off when spicy mode is off
+// ====== Tabs ======
+document.querySelectorAll('.tabs button[data-tab]').forEach(b => b.onclick = () => {
+ document.querySelectorAll('.tabs button[data-tab]').forEach(x => x.classList.toggle('active', x === b));
+ document.querySelectorAll('.tab-content').forEach(t => t.classList.toggle('show', t.id === 'tab-'+b.dataset.tab));
+});
+
+// ====== Batch modal ======
+function openBatch() { document.getElementById('batchModal').classList.add('show'); }
+function closeBatch() { document.getElementById('batchModal').classList.remove('show'); }
+async function queueBatch() {
+ const fd = new FormData(document.getElementById('genForm'));
+ fd.set('prompts', document.getElementById('batchPrompts').value);
+ const r = await api('/queue/batch','POST',fd);
+ if (r && r.error) { alert('Batch error: '+r.error); return; }
+ if (r && r.added) { document.getElementById('batchPrompts').value = ''; poll(); }
}
-// Render the inline API-key banner at the top of the CivitAI browser.
-// Three states: set (✓ small green), missing (amber, prompts for key),
-// editing (input visible while user is changing/setting the key). The
-// banner is the primary surface for the key now — Settings still has
-// the field but most users won't need to dig there.
-function renderCivitaiAuthBanner(haveKey, mode) {
- const box = document.getElementById('civitaiAuthBanner');
- if (!box) return;
- // Three visual modes: 'view' (default), 'edit' (showing input), 'err' (last save failed).
- const m = mode || (haveKey ? 'view' : 'edit');
- box.style.display = '';
- box.classList.remove('missing','set','err');
- if (m === 'view' && haveKey) {
- box.classList.add('set');
- box.innerHTML = `
- <span><svg class="ph" aria-hidden="true" style="color:var(--success,#3fb950);margin-right:4px;vertical-align:-2px"><use href="#ph-check-bold"/></svg><strong style="color:var(--success,#3fb950)"></strong> CivitAI API key set —
- LoRA downloads will work.</span>
- <span class="grow"></span>
- <a class="changekey" onclick="renderCivitaiAuthBanner(true,'edit')">change key</a>`;
- return;
- }
- // edit / missing mode — render input + Save.
- box.classList.add(m === 'err' ? 'err' : 'missing');
- const intro = m === 'err'
- ? `<strong>That key didn't work.</strong> Double-check it from <a href="https://civitai.com/user/account" target="_blank" rel="noopener">civitai.com/user/account</a> and try again.`
- : haveKey
- ? `Replace your CivitAI API key. The current one stays active until you save a new one.`
- : `<strong>CivitAI requires an API key</strong> to download LoRAs. Get one at <a href="https://civitai.com/user/account" target="_blank" rel="noopener">civitai.com/user/account</a> and paste it here:`;
- box.innerHTML = `
- <div class="grow" style="flex-basis:100%; margin-bottom:6px;">${intro}</div>
- <input type="password" id="civitaiAuthInput" placeholder="paste API key — usually 32 hex chars"
- autocomplete="off" spellcheck="false">
- <button type="button" id="civitaiAuthSave" onclick="civitaiAuthSave()">Save & test</button>
- ${haveKey ? '<a class="changekey" onclick="renderCivitaiAuthBanner(true,\'view\')">cancel</a>' : ''}`;
- // Pressing Enter inside the input triggers save.
- const inp = document.getElementById('civitaiAuthInput');
- if (inp) inp.addEventListener('keydown', (e) => {
- if (e.key === 'Enter') { e.preventDefault(); civitaiAuthSave(); }
+// ====== "No music" toggle pill ======
+//
+// Custom pill replacing the default checkbox. Click anywhere on the pill
+// to flip the hidden checkbox + reflect state in the UI (.on class drives
+// the accent fill from the toggle-pill CSS). Backed by a real <input
+// type=checkbox> inside the label, so FormData still picks it up the
+// normal way and screen readers / keyboard nav still work.
+(function () {
+ const pill = document.getElementById('noMusicPill');
+ const cb = document.getElementById('noMusic');
+ if (!pill || !cb) return;
+ const sync = () => pill.classList.toggle('on', cb.checked);
+ cb.addEventListener('change', sync);
+ pill.addEventListener('click', e => {
+ // <label> already toggles the checkbox; we just need to refresh the
+ // visual state on the next tick AFTER the native toggle has fired.
+ setTimeout(sync, 0);
});
-}
+ sync();
+})();
-async function civitaiAuthSave() {
- const inp = document.getElementById('civitaiAuthInput');
- const btn = document.getElementById('civitaiAuthSave');
- if (!inp) return;
- const key = (inp.value || '').trim();
- if (!key) { inp.focus(); return; }
- if (btn) { btn.disabled = true; btn.textContent = 'Saving…'; }
- // Save via /settings (single source of truth for tokens). After save
- // we hit /civitai/test to verify before flipping the banner to "set" —
- // that catches the most common error (typo'd key) right at the moment
- // the user pasted it, instead of failing later on the first download.
+// ====== Form submit ======
+//
+// "No music" toggle: appends a clear audio constraint to the prompt
+// before submission so the LTX 2.3 vocoder skips the soundtrack/score it
+// otherwise tends to add. Music is hard to remove cleanly from a stem
+// after the fact (it shares spectral space with dialogue), so users who
+// plan to score the clip themselves want voice + ambient only.
+//
+// We modify the FormData copy, not the textarea value — so the user's
+// original prompt stays untouched in the UI.
+document.getElementById('genForm').addEventListener('submit', async e => {
+ e.preventDefault();
+ const fd = new FormData(e.target);
+
+ // Disable the Generate button while we POST to /queue/add so a fast
+ // double-click doesn't queue the same job twice. The button is
+ // re-enabled after poll() returns (or on error). Keep this ABOVE the
+ // LoRA-orphan confirm() so a user who cancels the confirm doesn't
+ // leave the button stuck disabled.
+ const genBtn = document.getElementById('genBtn');
+ const reenable = () => { if (genBtn) genBtn.disabled = false; };
+
+ // Safety net: if the prompt mentions a trigger word from a LoRA the user
+ // has installed but NOT toggled active for this render, ask before
+ // submitting. The #1 silent-failure mode is "I typed 'salotrn' but
+ // forgot to switch on the picker chip" — the render then runs without
+ // fusion, and the face/style doesn't reproduce. Compare prompt vs.
+ // (_knownUserLoras minus _activeLoras) and surface a confirm() so the
+ // mismatch isn't invisible.
try {
- const fd = new URLSearchParams();
- fd.set('civitai_api_key', key);
- const r = await fetch('/settings', { method: 'POST',
- headers: {'Content-Type':'application/x-www-form-urlencoded'}, body: fd });
- const data = await r.json();
- if (!r.ok || !data.ok) throw new Error(data.error || `HTTP ${r.status}`);
- // Verify
- if (btn) btn.textContent = 'Testing…';
- const t = await fetch('/civitai/test');
- const td = await t.json();
- if (!td.ok) {
- renderCivitaiAuthBanner(false, 'err');
- return;
+ const promptRaw = (fd.get('prompt') || '').toString();
+ const promptLower = promptRaw.toLowerCase();
+ if (promptLower.trim() &&
+ Array.isArray(_knownUserLoras) &&
+ Array.isArray(_activeLoras)) {
+ const activePaths = new Set(_activeLoras.map(l => l.path));
+ const orphans = []; // [{name, trigger}]
+ const wordRe = /[a-z0-9]+/g;
+ const promptTokens = new Set(promptLower.match(wordRe) || []);
+ for (const ul of _knownUserLoras) {
+ if (activePaths.has(ul.path)) continue;
+ for (const w of (ul.trigger_words || [])) {
+ if (!w) continue;
+ const wLower = String(w).toLowerCase().trim();
+ if (!wLower || wLower.length < 4) continue; // skip 1-3 char tokens, too common
+ if (promptTokens.has(wLower)) {
+ orphans.push({ name: ul.name || ul.filename || ul.path.split('/').pop(), trigger: w });
+ break; // one match per LoRA is enough
+ }
+ }
+ }
+ if (orphans.length) {
+ const lines = orphans.map(o => ` • "${o.trigger}" → ${o.name}`).join('\n');
+ const ok = window.confirm(
+ 'Your prompt mentions trigger word(s) from LoRA(s) that are NOT attached:\n\n' +
+ lines + '\n\n' +
+ 'The model will NOT reproduce these characters/styles. Toggle the LoRA on in the picker, then Generate.\n\n' +
+ 'Generate without the LoRA anyway?'
+ );
+ if (!ok) { reenable(); return; }
+ }
}
- renderCivitaiAuthBanner(true, 'view');
- // Re-run the search so any 401-blocked thumbnails reload as authed.
- civitaiSearch();
- } catch (e) {
- if (btn) { btn.disabled = false; btn.textContent = 'Save & test'; }
- renderCivitaiAuthBanner(false, 'err');
- }
-}
+ } catch (_) { /* never block submit on this check */ }
-function closeCivitaiModal() {
- document.getElementById('civitaiModal').style.display = 'none';
-}
+ if (genBtn) genBtn.disabled = true;
-async function civitaiSearch() {
- if (_civitaiSearching) return;
- _civitaiSearching = true;
- const grid = document.getElementById('civitaiGrid');
- const status = document.getElementById('civitaiStatus');
- const loadMore = document.getElementById('civitaiLoadMore');
- status.textContent = '';
- status.className = 'civitai-status-line';
- grid.innerHTML = '<div class="hint">Loading…</div>';
- loadMore.style.display = 'none';
- _civitaiCursor = '';
- try {
- const params = new URLSearchParams();
- const q = document.getElementById('civitaiQuery').value.trim();
- if (q) params.set('query', q);
- if (document.getElementById('civitaiNsfw').checked) params.set('nsfw', 'true');
- params.set('limit', '24');
- const r = await fetch('/civitai/search?' + params.toString());
- const data = await r.json();
- if (data.error) {
- grid.innerHTML = '';
- status.textContent = data.error;
- status.className = 'civitai-status-line err';
- return;
- }
- renderCivitaiGrid(data.items, /* append */ false);
- _civitaiCursor = data.next_cursor || '';
- if (data.has_more) loadMore.style.display = '';
- if ((data.items || []).length === 0) {
- grid.innerHTML = `<div class="hint">No LTX 2.3 LoRAs match "${escapeHtml(q || '')}"${document.getElementById('civitaiNsfw').checked ? '' : ' (try Show NSFW for more)'}.</div>`;
+ const noMusic = document.getElementById('noMusic');
+ if (noMusic && noMusic.checked) {
+ const original = fd.get('prompt') || '';
+ const constraint = ' Audio: voice and ambient sounds only, no music, no soundtrack, no score, no melody.';
+ if (!original.toLowerCase().includes('no music')) {
+ fd.set('prompt', original.trim() + constraint);
}
- } catch (e) {
- status.textContent = 'Network error: ' + (e.message || e);
- status.className = 'civitai-status-line err';
- } finally {
- _civitaiSearching = false;
}
-}
-
-async function civitaiLoadMore() {
- if (_civitaiSearching || !_civitaiCursor) return;
- _civitaiSearching = true;
- const loadMore = document.getElementById('civitaiLoadMore');
- loadMore.disabled = true;
- loadMore.textContent = 'Loading…';
try {
- const params = new URLSearchParams();
- const q = document.getElementById('civitaiQuery').value.trim();
- if (q) params.set('query', q);
- if (document.getElementById('civitaiNsfw').checked) params.set('nsfw', 'true');
- params.set('limit', '24');
- params.set('cursor', _civitaiCursor);
- const r = await fetch('/civitai/search?' + params.toString());
- const data = await r.json();
- if (data.error) {
- document.getElementById('civitaiStatus').textContent = data.error;
- document.getElementById('civitaiStatus').className = 'civitai-status-line err';
- return;
- }
- renderCivitaiGrid(data.items, /* append */ true);
- _civitaiCursor = data.next_cursor || '';
- loadMore.style.display = data.has_more ? '' : 'none';
- } catch (e) {
- document.getElementById('civitaiStatus').textContent = 'Network error: ' + (e.message || e);
- document.getElementById('civitaiStatus').className = 'civitai-status-line err';
+ await api('/queue/add','POST',fd);
} finally {
- _civitaiSearching = false;
- loadMore.disabled = false;
- loadMore.textContent = 'Load more';
+ // Re-enable on the next event-loop tick so the button visibly
+ // bounces rather than feeling "stuck on click". poll() refreshes
+ // the queue right after, picking up the new job in the next ~1.5s.
+ setTimeout(reenable, 200);
}
-}
+ poll();
+});
-function renderCivitaiGrid(items, append) {
- const grid = document.getElementById('civitaiGrid');
- if (!append) grid.innerHTML = '';
- if (!items || items.length === 0) return;
- const frag = document.createDocumentFragment();
- for (const it of items) {
- const card = document.createElement('div');
- card.className = 'civitai-card';
- const sizeMb = it.size_kb ? (it.size_kb / 1024).toFixed(1) : '?';
- const dl = it.downloads ? new Intl.NumberFormat().format(it.downloads) : '?';
- const triggers = (it.trigger_words || []).slice(0, 3).join(', ');
- // LTX is a video model so most LoRAs ship animated previews. Render
- // <video> for videos (autoplay muted loop = looks like an animated
- // GIF, no user interaction needed) and <img> for stills. Both share
- // the .preview class so the card height is stable while images
- // load. CivitAI's CDN sets `Access-Control-Allow-Origin: *` so
- // cross-origin loads work without a panel-side proxy.
- let previewHtml;
- if (!it.preview_url) {
- previewHtml = `<div class="preview-empty">no preview</div>`;
- } else if (it.preview_type === 'video' || /\.mp4($|\?)/i.test(it.preview_url)) {
- previewHtml = `<video class="preview" src="${escapeHtml(it.preview_url)}"
- autoplay muted loop playsinline preload="metadata"></video>`;
- } else {
- previewHtml = `<img class="preview" src="${escapeHtml(it.preview_url)}" alt="" loading="lazy">`;
- }
- card.innerHTML = `
- ${previewHtml}
- <div class="body">
- <div class="ttl" title="${escapeHtml(it.name)}">${escapeHtml(it.name)}</div>
- <div class="meta">
- <span>by ${escapeHtml(it.creator)}</span>
- <span>↓ ${dl}</span>
- <span>${sizeMb} MB</span>
- ${it.nsfw ? '<span class="nsfw-badge">NSFW</span>' : ''}
- </div>
- ${triggers ? `<div class="meta"><span title="trigger words">trigger: ${escapeHtml(triggers)}</span></div>` : ''}
- ${it.civitai_url
- ? `<div class="meta"><a class="civitai-source-link" href="${escapeHtml(it.civitai_url)}" target="_blank" rel="noopener" title="Open the original CivitAI page — usage notes, examples, comments">Read instructions on CivitAI <svg class="ph" aria-hidden="true" style="margin-left:3px;vertical-align:-2px"><use href="#ph-arrow-square-out"/></svg></a></div>`
- : ''}
- </div>
- <div class="actions">
- <button type="button" class="primary-btn" data-id="${it.id}">Install</button>
- </div>`;
- const btn = card.querySelector('button[data-id]');
- btn.addEventListener('click', () => civitaiInstall(btn, it));
- frag.appendChild(card);
+// ====== Inline models card (top of form) ======
+// Displays what the current install needs RIGHT WHERE the user is about
+// to act. Beats burying the download CTA in a header modal. State picked
+// from /status: base missing → red blocker, current-mode-needs-Q8 →
+// amber prompt, downloading → animated progress, all-good → hidden.
+function updateModelsCard(s) {
+ const card = document.getElementById('modelsInline');
+ const icon = document.getElementById('modelsInlineIcon');
+ const title = document.getElementById('modelsInlineTitle');
+ const sub = document.getElementById('modelsInlineSub');
+ const progress = document.getElementById('modelsInlineProgress');
+ const fill = document.getElementById('modelsInlineFill');
+ const last = document.getElementById('modelsInlineLast');
+ const actions = document.getElementById('modelsInlineActions');
+ if (!card) return;
+
+ const baseOk = !!s.base_available;
+ const q8Ok = !!s.q8_available;
+ const dl = s.download && s.download.active ? s.download : null;
+ const tier = s.tier || {};
+ const dismissed = !!(s.settings && s.settings.models_card_dismissed);
+
+ // Reset state classes — we set the right one below.
+ card.classList.remove('state-missing', 'state-warn', 'state-downloading', 'dismissible');
+ progress.style.display = 'none';
+
+ // ----- Active download takes precedence over everything ------------------
+ if (dl) {
+ card.style.display = '';
+ card.classList.add('state-downloading');
+ icon.textContent = '↓';
+ const labelByKey = { q4: 'Q4 base model', gemma: 'Gemma text encoder', q8: 'Q8 high-quality model' };
+ title.textContent = `Downloading ${labelByKey[dl.key] || dl.repo_id}`;
+ const elapsed = Math.max(0, Math.round((Date.now()/1000) - (dl.started_ts || 0)));
+ sub.textContent = `${elapsed}s elapsed · resumable if interrupted`;
+ progress.style.display = '';
+ // Try to extract a percent from the last hf line (tqdm format).
+ const m = (dl.last_line || '').match(/\b(\d{1,3})%/);
+ fill.style.width = m ? `${Math.min(100, parseInt(m[1]))}%` : '15%';
+ last.textContent = dl.last_line || 'starting…';
+ actions.innerHTML = `<button class="danger" onclick="cancelDownload()">Cancel</button>`;
+ return;
}
- grid.appendChild(frag);
+
+ // ----- Base missing — hard block, the panel can't render anything --------
+ if (!baseOk) {
+ card.style.display = '';
+ card.classList.add('state-missing');
+ icon.innerHTML = '<svg class="ph" aria-hidden="true"><use href="#ph-warning-fill"/></svg>';
+ title.textContent = 'Base models needed before you can render';
+ const missing = (s.base_missing || []).length;
+ sub.innerHTML = `Q4 (~20 GB) and Gemma (~6 GB) are required. Click below — downloads resume if interrupted.${
+ missing ? ` <span style="color:var(--muted)">(${missing} files left)</span>` : ''
+ }`;
+ actions.innerHTML = (s.hf_available ?? true)
+ ? `<button onclick="startDownload('q4')">Download Q4 (20 GB)</button>`
+ : `<button disabled title="hf binary not found — reinstall via Pinokio">hf missing</button>`;
+ return;
+ }
+
+ // ----- User picked a mode that needs Q8, but Q8 isn't there --------------
+ // FFLF + Extend + High quality all need Q8. Surface the CTA *only* when
+ // the user is about to do one of those — no point nagging a T2V user
+ // about Q8 if they'll never use it.
+ // Dismissible: a user who deliberately doesn't want Q8 (storage budget,
+ // they only do T2V Quick/Standard) can × this away and we'll respect it
+ // until either model state changes or they re-summon the modal.
+ // Y1.036 — Extend joins FFLF and High in needing Q8. The Extend pipeline
+ // loads `transformer-dev.safetensors` for CFG-guided denoise; Q4 doesn't
+ // ship it after the Y1.024 download trim, so surface the same CTA here.
+ const needsQ8 = (currentMode === 'keyframe')
+ || (currentMode === 'extend')
+ || (document.getElementById('quality').value === 'high');
+ if (needsQ8 && !q8Ok && tier.allows_q8 !== false) {
+ if (dismissed) { card.style.display = 'none'; return; }
+ card.style.display = '';
+ card.classList.add('state-warn', 'dismissible');
+ icon.innerHTML = '<svg class="ph" aria-hidden="true"><use href="#ph-download-simple"/></svg>';
+ const reason = currentMode === 'keyframe' ? 'FFLF needs the Q8 model'
+ : currentMode === 'extend' ? 'Extend needs the Q8 model'
+ : 'High quality needs the Q8 model';
+ title.textContent = reason;
+ const missing = (s.q8_missing || []).length;
+ sub.innerHTML = `Q8 (~37 GB) is a separate one-time download. Resumable.${
+ missing && missing < 8 ? ` <span style="color:var(--muted)">(${missing} files left — partial install detected)</span>` : ''
+ }`;
+ actions.innerHTML = (s.hf_available ?? true)
+ ? `<button onclick="startDownload('q8')">Download Q8 (37 GB)</button>`
+ : `<button disabled>hf missing</button>`;
+ return;
+ }
+
+ // ----- All good — hide the card completely -------------------------------
+ // Per user feedback: the "Models ready · 3/3" status was visual noise once
+ // everything was downloaded. Hide the card on full readiness; the header
+ // models pill still gives a way to reopen the modal if the user wants to
+ // manage repos. If state regresses (a file gets deleted, partial download
+ // appears), one of the branches above re-shows it automatically.
+ const allReady = baseOk && q8Ok;
+ if (allReady) {
+ card.style.display = 'none';
+ actions.innerHTML = '';
+ return;
+ }
+ // ----- Partial-OK quiet state ---------------------------------------------
+ // Base OK but Q8 missing on a tier that supports it AND the user hasn't
+ // picked a Q8-needing mode — gentle nudge in neutral colours, dismissible.
+ if (dismissed) { card.style.display = 'none'; return; }
+ card.style.display = '';
+ card.classList.add('dismissible');
+ icon.innerHTML = '<svg class="ph" aria-hidden="true"><use href="#ph-check-bold"/></svg>';
+ const ready = s.repos_ready ?? 0;
+ const total = s.repos_total ?? 0;
+ title.textContent = `Models ready · ${ready}/${total}`;
+ const partialNote = (q8Ok && baseOk) ? '' : ` · ${total - ready} optional missing`;
+ sub.innerHTML =
+ `All installed weights detected${partialNote}. ` +
+ `<a style="color:var(--accent-bright,#7e98ff); cursor:pointer; text-decoration:underline" onclick="openModelsModal()">Manage models →</a>`;
+ actions.innerHTML = '';
}
-async function civitaiInstall(btn, item) {
- btn.disabled = true;
- const origLabel = btn.textContent;
- btn.textContent = 'Downloading…';
- const fd = new FormData();
- fd.set('download_url', item.download_url);
- fd.set('meta', JSON.stringify(item));
+// Persist the "user dismissed the models card" flag. POSTs to /settings
+// and re-runs updateModelsCard with the latest status so the card hides
+// immediately (not after the next /status poll cycle, ~5s away).
+async function dismissModelsCard() {
try {
- const r = await fetch('/civitai/download', {
+ const fd = new URLSearchParams();
+ fd.set('models_card_dismissed', 'true');
+ await fetch('/settings', {
method: 'POST',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
- body: new URLSearchParams(fd),
- });
- const data = await r.json();
- if (!r.ok || !data.ok) {
- const status = document.getElementById('civitaiStatus');
- status.textContent = `Download failed: ${data.error || 'HTTP ' + r.status}`;
- status.className = 'civitai-status-line err';
- btn.disabled = false;
- btn.textContent = origLabel;
- return;
- }
- btn.textContent = data.skipped ? 'Already installed ✓' : 'Installed ✓';
- const status = document.getElementById('civitaiStatus');
- status.textContent = data.skipped
- ? `Already in ${data.path} — auto-enabled below.`
- : `Saved to ${data.path}. Auto-enabled below.`;
- status.className = 'civitai-status-line ok';
- // Refresh the local picker so the new LoRA appears, then auto-enable.
- // Auto-enable applies on BOTH the fresh-download AND the
- // already-installed paths — clicking Install on a CivitAI card
- // should always result in "this LoRA is now usable in the next
- // render," regardless of whether it was already on disk. Earlier
- // build only auto-enabled fresh downloads, leaving repeat clicks
- // looking like a no-op even though the file was sitting right
- // there in the picker.
- await refreshLoras();
- addLoraToActive({
- path: data.path,
- name: data.name || item.name,
- strength: item.recommended_strength || 1.0,
- trigger_words: item.trigger_words || [],
+ body: fd,
});
- // Open the LoRAs disclosure so the user sees the entry without
- // hunting for it after the modal closes.
- const det = document.getElementById('lorasDetails');
- if (det) det.open = true;
- } catch (e) {
- document.getElementById('civitaiStatus').textContent = 'Network error: ' + (e.message || e);
- document.getElementById('civitaiStatus').className = 'civitai-status-line err';
- btn.disabled = false;
- btn.textContent = origLabel;
+ } catch (e) { /* best effort — UI still hides locally on next poll */ }
+ // Optimistically hide right now without waiting for the poll round-trip.
+ const card = document.getElementById('modelsInline');
+ if (card) card.style.display = 'none';
+ // Patch LAST_STATUS so subsequent updateModelsCard calls before the next
+ // /status fetch agree with the on-disk state.
+ if (LAST_STATUS && LAST_STATUS.settings) {
+ LAST_STATUS.settings.models_card_dismissed = true;
}
}
-// Boot: load the local LoRA list on page load so the picker isn't empty
-// when the user expands it for the first time.
-document.addEventListener('DOMContentLoaded', () => { refreshLoras(); });
-
-// ====== Models modal ======
-// Opens to /models snapshot. While open, the main poll() refreshes the
-// list every cycle so download progress appears live. Each row shows:
-// ✓ ready (green) — all repo files present
-// ◐ partial (amber) — some files there, some missing (e.g. interrupted)
-// ⊘ missing (red) — nothing on disk
-// ↻ downloading (blue, anim) — hf is currently fetching this repo
-function openModelsModal() {
- document.getElementById('modelsModal').style.display = 'flex';
- refreshModelsModal();
-}
-function closeModelsModal() {
- document.getElementById('modelsModal').style.display = 'none';
-}
-async function refreshModelsModal({ silent = false } = {}) {
- const list = document.getElementById('modelsList');
- const hint = document.getElementById('modelsHint');
- const foot = document.getElementById('modelsFoot');
- let data;
- try { data = await api('/models'); }
- catch (e) {
- if (!silent) hint.textContent = 'Failed to load models. Panel might be restarting — try again.';
- return;
- }
- const repos = data.repos || [];
- const active = data.active_download;
- hint.innerHTML = data.hf_available
- ? `Each row shows what's on disk. Click <b>Download</b> to fetch missing files via <code>hf download</code>; progress streams to the log at the bottom of the page.`
- : `<span style="color:var(--warning,#d29922)"><svg class="ph" aria-hidden="true" style="margin-right:4px;vertical-align:-2px"><use href="#ph-warning-fill"/></svg><code>hf</code> not found</span> — this Pinokio install doesn't have <code>huggingface_hub&gt;=1.0</code> in the venv. Run Update from Pinokio, then come back.`;
- const rows = repos.map(r => {
- let cls, icon, statusText, btnHtml;
- if (active && active.key === r.key) {
- cls = 'downloading';
- icon = '<svg class="ph" aria-hidden="true"><use href="#ph-arrow-clockwise-bold"/></svg>';
- const elapsed = Math.max(0, Math.round((Date.now()/1000) - (active.started_ts || 0)));
- const last = active.last_line ? `<div class="progress">${escapeHtml(active.last_line)}</div>` : '';
- statusText = `Downloading · ${elapsed}s${last}`;
- btnHtml = `<button class="ghost" onclick="cancelDownload()">Cancel</button>`;
- } else if (r.complete) {
- cls = 'ready'; icon = '<svg class="ph" aria-hidden="true"><use href="#ph-check-bold"/></svg>';
- // `where: 'hf_cache'` means the files were resolved from
- // ~/.cache/huggingface/ rather than the canonical mlx_models/
- // dir. Common on manual / dev installs that pre-existed Pinokio
- // and pulled the model via `huggingface-cli` or first-run helper.
- const tag = r.where === 'hf_cache' ? 'HF cache' : 'local';
- statusText = `Ready · ${r.total_files} files · ~${r.size_gb || '?'} GB · ${tag}`;
- btnHtml = `<button class="ghost" disabled>Installed</button>`;
- } else if (r.present_files > 0) {
- cls = 'partial'; icon = '<svg class="ph" aria-hidden="true"><use href="#ph-download-simple"/></svg>';
- const left = r.total_files - r.present_files;
- statusText = `Partial · ${r.present_files}/${r.total_files} files · ${left} missing — resume to finish`;
- btnHtml = data.hf_available
- ? `<button onclick="startDownload('${escapeHtml(r.key)}')" ${active ? 'disabled' : ''}>Resume</button>`
- : `<button disabled>Resume</button>`;
+// ====== Tier gating ======
+// Disables the FFLF / Extend mode pills and the High quality pill when
+// the detected hardware tier doesn't support them. Visual state +
+// tooltip + intercepted clicks. Run from the poll handler so an env
+// override flips state on restart.
+function applyTierGates(tier) {
+ // Mode pills
+ document.querySelectorAll('#modeGroup .pill-btn').forEach(b => {
+ const m = b.dataset.mode;
+ const allowed = (m === 'keyframe') ? tier.allows_keyframe
+ : (m === 'extend') ? tier.allows_extend
+ : true;
+ b.classList.toggle('disabled', !allowed);
+ if (!allowed) {
+ const need = m === 'keyframe'
+ ? 'first/last-frame interpolation needs more memory than this Mac has — try Image → Video instead'
+ : 'extending an existing clip needs more memory than this Mac has — try Image → Video instead';
+ b.title = `Off on the ${tier.label} tier · ${need}`;
} else {
- cls = 'missing'; icon = '<svg class="ph" aria-hidden="true"><use href="#ph-x-circle"/></svg>';
- statusText = `Not installed · ~${r.size_gb || '?'} GB`;
- btnHtml = data.hf_available
- ? `<button onclick="startDownload('${escapeHtml(r.key)}')" ${active ? 'disabled' : ''}>Download</button>`
- : `<button disabled>Download</button>`;
+ b.title = '';
}
- const kindBadge = r.kind === 'optional'
- ? `<span style="color:var(--muted)">optional</span>`
- : `<span style="color:var(--success,#3fb950)">required</span>`;
- return `
- <li class="${cls}">
- <span class="icon">${icon}</span>
+ });
+ // Quality: High requires Q8. We already disable based on q8_available
+ // for the no-download case; this layer enforces the RAM tier on top.
+ // Both layers can disable — we OR them together via a class.
+ const highBtn = document.getElementById('qualityHigh');
+ if (highBtn) {
+ if (!tier.allows_q8) {
+ highBtn.classList.add('disabled');
+ highBtn.title = `Off on the ${tier.label} tier · the high-quality model needs more memory than this Mac has`;
+ } else {
+ // Don't unconditionally clear .disabled — the Q8-not-installed code
+ // path also sets it. Only clear if the tier is the only reason.
+ // The poll() code that checks q8_available re-applies that state
+ // every cycle, so this branch is safe to unset.
+ highBtn.title = '';
+ }
+ }
+}
+// Intercept clicks on disabled mode pills so users get a helpful message
+// instead of a broken-feeling no-op.
+document.addEventListener('click', (e) => {
+ const btn = e.target.closest('#modeGroup .pill-btn.disabled');
+ if (btn) {
+ e.stopPropagation();
+ e.preventDefault();
+ alert(btn.title || 'This mode is not supported on this hardware tier.');
+ }
+}, true);
+
+// ====== Tier modal ======
+function openTierModal() {
+ const modal = document.getElementById('tierModal');
+ modal.style.display = 'flex';
+ // Defensive: show "loading" state immediately so the modal never appears
+ // with the body completely blank (which is what happens if the panel
+ // process is dead and fetch fails — looked like a "buggy bug" to a user
+ // who was just kicked off a stale browser view).
+ document.getElementById('tierModalTitle').textContent = 'Hardware tier';
+ document.getElementById('tierModalBlurb').innerHTML = '<em>Loading…</em>';
+ document.getElementById('tierCapsList').innerHTML = '';
+ // Tier doesn't change at runtime — RAM is fixed at boot — so a single
+ // fetch on open is plenty. No need for live polling here.
+ fetch('/status').then(r => r.json()).then(s => {
+ const t = s.tier || {};
+ const tt = t.times || {};
+ // Helper: a row is "available" if it's allowed; "max" is the friendly
+ // size limit (or "Any size" / "—" when there is no limit / disabled).
+ const sizeLine = (on, maxDim, fallback) => {
+ if (!on) return fallback || 'Not available on this Mac';
+ if (!maxDim) return 'Any size';
+ return `Up to ${maxDim} pixels on the longer side`;
+ };
+ document.getElementById('tierModalTitle').textContent = `What this Mac can do · ${t.label || 'unknown'}`;
+ document.getElementById('tierModalBlurb').innerHTML = `
+ <div style="margin-bottom: 6px"><strong>${escapeHtml(t.label || '')}</strong> · ${escapeHtml(t.ram_label || '')} of memory</div>
+ <div>${escapeHtml(t.blurb || '')}</div>`;
+ // One row per mode/option, with three pieces of info each:
+ // - is it available? (✓ / ✗)
+ // - what's the size limit? (plain English)
+ // - how long does a typical 5-second render take? (rough estimate)
+ const items = [
+ {
+ title: 'Text → video',
+ desc: 'Type a prompt, get a clip. The default mode.',
+ on: true,
+ size: sizeLine(true, t.t2v_max_dim),
+ time: tt.t2v_standard,
+ },
+ {
+ title: 'Image → video',
+ desc: 'Drop in a still, get it animated. Same speed as text → video.',
+ on: true,
+ size: sizeLine(true, t.i2v_max_dim),
+ time: tt.i2v_standard,
+ },
+ {
+ title: 'Quick (640×480)',
+ desc: 'Smaller preview to scout prompts and seeds before a full-size render.',
+ on: true,
+ size: 'Always smaller than Standard',
+ time: tt.t2v_draft,
+ },
+ {
+ title: 'High quality',
+ desc: 'Bigger model, two-stage denoising, sharper faces. Needs the optional Q8 download.',
+ on: !!t.allows_q8,
+ size: sizeLine(!!t.allows_q8, 0, 'Needs more memory than this Mac has'),
+ time: tt.high,
+ },
+ {
+ title: 'First / last frame (FFLF)',
+ desc: 'Pick a start image and an end image, the model fills the motion between.',
+ on: !!t.allows_keyframe,
+ size: sizeLine(!!t.allows_keyframe, t.keyframe_max_dim, 'Needs more memory than this Mac has'),
+ time: tt.keyframe,
+ },
+ {
+ title: 'Extend an existing clip',
+ desc: 'Pick a video you already rendered, the model adds more time onto either end.',
+ on: !!t.allows_extend,
+ size: sizeLine(!!t.allows_extend, t.extend_max_dim, 'Needs more memory than this Mac has'),
+ time: tt.extend,
+ },
+ ];
+ document.getElementById('tierCapsList').innerHTML = items.map(it => `
+ <li class="${it.on ? 'ready' : 'missing'}">
+ <span class="icon"><svg class="ph" aria-hidden="true"><use href="${it.on ? '#ph-check-bold' : '#ph-x-circle-fill'}"/></svg></span>
<div class="meta">
- <span class="ttl">${escapeHtml(r.name)} · ${kindBadge}</span>
- <span class="sub">${escapeHtml(r.repo_id)} → ${escapeHtml(r.local_dir)}</span>
- <span class="sub">${statusText}${r.blurb ? ' · ' + escapeHtml(r.blurb) : ''}</span>
+ <span class="ttl">${escapeHtml(it.title)}</span>
+ <span class="sub">${escapeHtml(it.desc)}</span>
+ <span class="sub" style="margin-top:2px">
+ <span style="color:var(--fg,#d8e0ee)">${escapeHtml(it.size)}</span>${
+ it.time ? ` · <span style="color:var(--accent-bright,#7e98ff)">~ ${escapeHtml(it.time)} for a 5-second clip</span>` : ''
+ }
+ </span>
</div>
- ${btnHtml}
- </li>`;
- }).join('');
- list.innerHTML = rows || `<li class="empty-state">No model manifest found — required_files.json is missing or unreadable.</li>`;
- // Footer summarises required vs optional counts.
- const reqRepos = repos.filter(r => r.kind !== 'optional');
- const optRepos = repos.filter(r => r.kind === 'optional');
- const reqReady = reqRepos.filter(r => r.complete).length;
- const optReady = optRepos.filter(r => r.complete).length;
- foot.innerHTML = `
- <div>Required: ${reqReady}/${reqRepos.length} ready &nbsp;·&nbsp; Optional: ${optReady}/${optRepos.length} ready</div>
- <div style="margin-top:4px">Tip: downloads resume on retry — closing this dialog mid-download keeps it running in the background.</div>`;
+ <span></span>
+ </li>`).join('');
+ }).catch(err => {
+ // Panel might be dead, status endpoint unreachable, or response not JSON.
+ // Replace the loading state with a visible error so the modal doesn't
+ // look "broken" with empty content.
+ document.getElementById('tierModalBlurb').innerHTML =
+ '<div style="color: var(--danger, #f85149)">Could not load tier info — the panel server may have stopped responding. Check the Pinokio terminal and restart the panel if needed.</div>';
+ document.getElementById('tierCapsList').innerHTML = '';
+ console.error('tier modal fetch failed:', err);
+ });
}
-async function startDownload(key) {
- let res;
+function closeTierModal() { document.getElementById('tierModal').style.display = 'none'; }
+
+// ====== Bug report modal ======
+// Fetches env + log tail from /panel/bug-context on open, lets the user
+// type into pre-marked sections, then on submit POSTs the title+body to
+// /panel/bug-report (which builds the GitHub URL + optional crash zip)
+// and opens the URL in a new tab. Stays purely in the panel — no auth,
+// no API hit, the user reviews the issue body in GitHub before posting.
+let _bugCtxCache = null;
+async function openBugModal() {
+ const modal = document.getElementById('bugModal');
+ modal.style.display = 'flex';
+ const titleEl = document.getElementById('bugTitle');
+ const bodyEl = document.getElementById('bugBody');
+ const crashRow = document.getElementById('bugCrashRow');
+ const crashLabel = document.getElementById('bugCrashLabel');
+ const statusEl = document.getElementById('bugStatus');
+ const submitBtn = document.getElementById('bugSubmitBtn');
+ // Clear stale state in case the user opens twice in a row.
+ titleEl.value = '[bug] ';
+ bodyEl.value = 'Loading environment…';
+ statusEl.textContent = '';
+ submitBtn.disabled = false;
+ submitBtn.textContent = 'Open GitHub issue';
try {
- res = await api('/models/download', 'POST', `repo_key=${encodeURIComponent(key)}`);
- } catch (e) {
- alert('Download failed to start: ' + (e?.message || e));
+ const r = await fetch('/panel/bug-context');
+ if (!r.ok) throw new Error('bug-context: ' + r.status);
+ _bugCtxCache = await r.json();
+ } catch (err) {
+ bodyEl.value = '## Environment\n- (server context unavailable: ' + err + ')\n\n'
+ + '## What I was doing\n\n\n## What happened\n\n\n## Expected\n\n';
+ crashRow.style.display = 'none';
return;
}
- // The api() helper coerces 409 (busy) to { error: 'busy' } — surface that
- // to the user instead of silently no-op'ing the click.
- if (res && res.error) {
- alert(`Can't start download: ${res.error}`);
- }
- refreshModelsModal();
- poll();
-}
-async function cancelDownload() {
- if (!confirm('Cancel the active download? Partial files stay on disk; clicking Download/Resume later picks up where you left off.')) return;
- try { await api('/models/cancel', 'POST'); } catch (e) {}
- refreshModelsModal();
-}
-
-// ====== Version pill (the "magic button") ======
-//
-// One always-visible pill in the header that changes content + colour
-// based on /version state. Clicking it does the right thing for the
-// current state — no modal, no nested click flows.
-//
-// Backend: a daemon thread polls GitHub every 30 minutes (commits API
-// for the SHA + raw VERSION file for the human-friendly Y1.NNN label)
-// and exposes the result at /version. The JS polls /version every 5
-// minutes (cheap; pre-computed dict read). When the user clicks while
-// behind, /version/pull does the actual `git pull` server-side; the
-// user still has to Stop+Start phosphene in Pinokio to apply.
-//
-// Rationale: users keep telling us "I clicked Update but I don't see
-// the new features" — by the time the feedback reaches us we've usually
-// pushed three more commits. The pill turns the loop from
-// "hope-they-noticed" into a literal one-click action.
+ const c = _bugCtxCache;
+ const tail = (c.logTail || []).join('\n') || '(no recent log lines)';
+ bodyEl.value =
+`## Environment
+- Phosphene version: ${c.version}${c.commit ? ' (' + c.commit + ')' : ''}
+- Branch: ${c.branch}
+- macOS: ${c.macOS || 'unknown'}
+- Mac: ${c.hwModel || 'unknown'} · ${c.ramGB || '?'} GB RAM
-let _versionState = null;
-let _versionRestartPending = false; // set after a successful /version/pull;
- // pill turns into a "restart" reminder.
+## What I was doing
-async function refreshVersionPill() {
- try {
- const r = await fetch('/version');
- _versionState = await r.json();
- } catch (e) {
- return; // network blip; don't blow away last good state
- }
- renderVersionPill();
-}
-function _versionDisplayLabel(s) {
- // Prefer the human Y1.NNN VERSION file label. Fall back to the short
- // SHA for older checkouts that predate the VERSION file. Last-resort
- // ellipsis when nothing's known yet.
- return s.local_version || s.local_short || '…';
-}
+## What happened
-function _versionRemoteLabel(s) {
- return s.remote_version || s.remote_short || 'latest';
-}
-function renderVersionPill() {
- const pill = document.getElementById('versionPill');
- if (!pill) return;
- const s = _versionState || {};
- const local = _versionDisplayLabel(s);
- const remote = _versionRemoteLabel(s);
- // Reset every state class; exactly one is added below.
- pill.classList.remove('pill-update','pill-current','pill-dev','pill-checking','pill-restart','pill-busy');
- pill.style.display = '';
+## Expected
- // Pill text leads with the MEANING of the state, not the version code.
- // Earlier build showed bare "Y1.005" which read as a label rather than
- // a status — users didn't realize they could click it. Now every state
- // uses plain English so a user glancing at the header understands at
- // a glance whether they're current, behind, or need to restart.
- // Highest-priority state: a pull just happened and the panel needs a
- // restart to load the new code.
- if (_versionRestartPending) {
- pill.classList.add('pill-restart');
- pill.innerHTML = '<svg class="ph" aria-hidden="true" style="margin-right:4px;vertical-align:-2px"><use href="#ph-arrow-clockwise-bold"/></svg>Restart Phosphene';
- const v = s.pull_pulled_to_version || s.pull_pulled_to_short || 'the new code';
- pill.title = s.pull_requires_full_update
- ? `Pulled ${v}. This update touched dependencies — use Pinokio's Update button (not just Stop+Start).`
- : `Pulled ${v}. Click Stop → Start in Pinokio to apply.`;
- return;
- }
- // Suppressed (dev branch / dirty tree / no git).
- if (s.suppress_reason) {
- pill.classList.add('pill-dev');
- pill.textContent = `${local} · dev`;
- pill.title = `Update check paused: ${s.suppress_reason}.`;
- return;
- }
- // Behind origin/main — eye-catching action prompt.
- if (!s.error && s.checked_ts && (s.behind_by | 0) > 0) {
- pill.classList.add('pill-update');
- pill.innerHTML = `<svg class="ph" aria-hidden="true" style="margin-right:4px;vertical-align:-2px"><use href="#ph-arrow-up"/></svg>Update to ${remote}`;
- pill.title = `You're on ${local}; latest is ${remote}. Click to pull the update.`;
- return;
- }
- // Last check errored (offline).
- if (s.error) {
- pill.classList.add('pill-dev');
- pill.textContent = `${local} · offline`;
- pill.title = `Couldn't reach github.com (${s.error}). Click to retry.`;
- return;
- }
- // Current with origin/main.
- if (s.checked_ts && (s.behind_by | 0) === 0) {
- pill.classList.add('pill-current');
- pill.innerHTML = `<svg class="ph" aria-hidden="true" style="margin-right:4px;vertical-align:-2px"><use href="#ph-check-bold"/></svg>Up to date · ${local}`;
- pill.title = `You're on ${local}, the latest version. Click to re-check now.`;
- return;
+## Logs / repro
+\`\`\`
+${tail}
+\`\`\`
+`;
+ // Crash-report checkbox only when there's something to bundle.
+ if ((c.crashCount || 0) > 0) {
+ crashRow.style.display = 'flex';
+ crashLabel.textContent =
+ `Include latest crash reports (zips up to 5 of ${c.crashCount} .ips files)`;
+ document.getElementById('bugCrashCheck').checked = true;
+ } else {
+ crashRow.style.display = 'none';
}
- // First poll hasn't landed yet.
- pill.classList.add('pill-checking');
- pill.textContent = `Checking · ${local}`;
- pill.title = 'Checking for updates…';
+ // Focus the "What I was doing" line for the user to start typing.
+ // Place caret right after the heading.
+ setTimeout(() => {
+ bodyEl.focus();
+ const marker = '## What I was doing\n';
+ const idx = bodyEl.value.indexOf(marker);
+ if (idx >= 0) {
+ const pos = idx + marker.length;
+ bodyEl.setSelectionRange(pos, pos);
+ }
+ }, 50);
}
-
-// One click — does the right thing for the current state. Magic button.
-async function versionPillClick() {
- if (_versionRestartPending) {
- // Educational click: tell the user what's needed.
- const s = _versionState || {};
- const tip = s.pull_requires_full_update
- ? "Pulled. Because this update touched Python deps / patches, use Pinokio's Update button (it reinstalls + reapplies patches). After that click Start."
- : "Pulled. Click Stop, then Start in Pinokio to apply (your queue and settings are preserved).";
- alert(tip);
- return;
- }
- const s = _versionState || {};
- if (s.suppress_reason) {
- alert(`Update check is paused: ${s.suppress_reason}.\n\n` +
- `Phosphene only checks GitHub when you're on a clean main branch. ` +
- `Commit your local changes (or switch back to main) to re-enable updates.`);
- return;
- }
- // Behind: pull the update.
- if (!s.error && s.checked_ts && (s.behind_by | 0) > 0) {
- await versionDoPull();
- return;
- }
- // Current OR error OR pre-first-poll: re-check now.
- await versionDoRefresh();
+function closeBugModal() {
+ document.getElementById('bugModal').style.display = 'none';
}
-
-async function versionDoRefresh() {
- const pill = document.getElementById('versionPill');
- pill.classList.add('pill-busy');
- pill.innerHTML = '<svg class="ph" aria-hidden="true" style="margin-right:4px;vertical-align:-2px;animation:phSpin 1.2s linear infinite"><use href="#ph-arrow-clockwise-bold"/></svg>checking…';
+async function submitBugReport() {
+ const submitBtn = document.getElementById('bugSubmitBtn');
+ const statusEl = document.getElementById('bugStatus');
+ const title = document.getElementById('bugTitle').value.trim() || '[bug] (untitled)';
+ const body = document.getElementById('bugBody').value;
+ const includeCrashEl = document.getElementById('bugCrashCheck');
+ const includeCrash = includeCrashEl && document.getElementById('bugCrashRow').style.display !== 'none'
+ ? !!includeCrashEl.checked : false;
+ submitBtn.disabled = true;
+ submitBtn.textContent = 'Working…';
+ statusEl.textContent = 'Building issue…';
try {
- const r = await fetch('/version/check', { method: 'POST' });
+ const r = await fetch('/panel/bug-report', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ title, body, includeCrashReports: includeCrash }),
+ });
const data = await r.json();
- if (data && data.state) _versionState = data.state;
- } catch (e) {
- // Leave _versionState as-is so the pill returns to the prior render
- // instead of flashing to "unknown".
+ if (!r.ok || !data.issueUrl) throw new Error(data.error || ('HTTP ' + r.status));
+ // Open the issue in a new tab. noopener for safety.
+ window.open(data.issueUrl, '_blank', 'noopener');
+ if (data.zipPath) {
+ // Try to copy the path to clipboard so the user can paste-find it
+ // in Finder, OR drag the file from /tmp directly onto the GitHub
+ // issue. Best-effort — clipboard write requires a user gesture
+ // context, which a click handler counts as.
+ try { await navigator.clipboard.writeText(data.zipPath); } catch (e) { /* ignore */ }
+ statusEl.innerHTML =
+ 'Crash report bundled. Drag this file into the GitHub issue:<br>' +
+ '<code style="font-size:11px">' + data.zipPath + '</code><br>' +
+ '<span style="color:var(--success,#3fb950)">(path copied to clipboard)</span>';
+ submitBtn.textContent = 'Done — close';
+ submitBtn.disabled = false;
+ submitBtn.onclick = closeBugModal;
+ } else {
+ statusEl.textContent = 'GitHub issue opened in a new tab.';
+ submitBtn.textContent = 'Done — close';
+ submitBtn.disabled = false;
+ submitBtn.onclick = closeBugModal;
+ // Auto-close after a short delay if the user doesn't click Close.
+ setTimeout(() => {
+ const m = document.getElementById('bugModal');
+ if (m && m.style.display !== 'none') closeBugModal();
+ }, 4000);
+ }
+ } catch (err) {
+ statusEl.innerHTML = '<span style="color:var(--danger,#f85149)">Failed: ' + err + '</span>';
+ submitBtn.disabled = false;
+ submitBtn.textContent = 'Try again';
}
- pill.classList.remove('pill-busy');
- renderVersionPill();
}
-async function versionDoPull() {
- const s = _versionState || {};
- const target = _versionRemoteLabel(s);
- const local = _versionDisplayLabel(s);
- const ok = confirm(
- `Pull update from ${local} → ${target}?\n\n` +
- `This runs git pull on your phosphene install. After it succeeds, ` +
- `you'll need to click Stop, then Start in Pinokio to load the new code. ` +
- `Your queue and settings are preserved across restarts.`
- );
- if (!ok) return;
- const pill = document.getElementById('versionPill');
- pill.classList.add('pill-busy');
- pill.innerHTML = '<svg class="ph" aria-hidden="true" style="margin-right:4px;vertical-align:-2px;animation:phSpin 1.2s linear infinite"><use href="#ph-arrow-clockwise-bold"/></svg>pulling…';
- // Tell poll() not to flash the offline banner during this call —
- // /version/pull is single-threaded server-side and blocks /status for
- // ~30s while git fetch + git pull + remote-check run. Without this
- // suppression the user sees an "offline → reconnected" flash at the
- // tail of every successful Update click.
- window._suppressOfflineBanner = true;
+// ====== Settings modal ======
+// Single-shot fetch on open (settings change rarely). The modal hydrates
+// preset cards from the /settings response so the labels and blurbs
+// match the server-side OUTPUT_PRESETS table — no preset content
+// duplicated in JS.
+let _settingsCache = null;
+
+async function openSettingsModal() {
+ const modal = document.getElementById('settingsModal');
+ modal.style.display = 'flex';
+ document.getElementById('settingsStatus').textContent = '';
+ document.getElementById('settingsStatus').className = 'settings-status';
try {
- const r = await fetch('/version/pull', { method: 'POST' });
- const data = await r.json();
- if (data && data.state) _versionState = data.state;
- if (!r.ok || !data.ok) {
- pill.classList.remove('pill-busy');
- renderVersionPill();
- alert(`Pull failed:\n\n${(data && data.error) || 'unknown error'}\n\n` +
- `Tip: try the full Pinokio Update button instead — it also handles ` +
- `cases where you have local changes that block a fast-forward.`);
- return;
- }
- _versionRestartPending = true;
- pill.classList.remove('pill-busy');
- renderVersionPill();
- const newVersion = (data.state && (data.state.pull_pulled_to_version || data.state.pull_pulled_to_short)) || 'new version';
- const fullUpdateNote = data.state && data.state.pull_requires_full_update
- ? `\n\n⚠ This update touched Python dependencies / patches. Use ` +
- `Pinokio's Update button (not just Stop+Start) so deps reinstall.`
- : '';
- alert(`Pulled to ${newVersion}.\n\nClick Stop, then Start in Pinokio to apply.${fullUpdateNote}`);
+ const r = await fetch('/settings');
+ _settingsCache = await r.json();
} catch (e) {
- pill.classList.remove('pill-busy');
- renderVersionPill();
- alert(`Pull failed: ${e.message || e}`);
- } finally {
- // Reset the suppression flag so future genuine outages still surface
- // the banner. Also clear the failure counter so we don't fire on the
- // very next legit poll because of stale state from the pull window.
- window._suppressOfflineBanner = false;
- _POLL_FAILS = 0;
- // Force one immediate clean poll — also clears any latent banner
- // that snuck through (e.g. if the page was on a slow tab and missed
- // a couple seconds of state).
- _setOfflineBanner(false);
- if (typeof poll === 'function') poll();
+ document.getElementById('settingsStatus').textContent = 'Could not load settings.';
+ document.getElementById('settingsStatus').className = 'settings-status err';
+ return;
}
-}
-
-// Boot: first /version read happens 2 seconds after DOM ready (gives the
-// panel's startup-delay thread time to complete its first remote check),
-// then every 5 minutes thereafter.
-setTimeout(refreshVersionPill, 2000);
-setInterval(refreshVersionPill, 5 * 60 * 1000);
-
-// ====== Modal reliability scaffold ======
-// One global scaffold for all 8 modals on the panel (.models-modal,
-// .model-browser-modal, .expand-lightbox). Covers three things the
-// individual open/close functions didn't:
-// 1. Esc closes the topmost-visible modal.
-// 2. Tab/Shift-Tab cycles focus inside the modal (no escape into
-// the form behind it).
-// 3. body.modal-open is toggled whenever any modal is visible so
-// CSS can lock background scroll.
-// No need to patch each open/close fn — a MutationObserver watches
-// inline style changes on the modals themselves; whoever toggles
-// display gets the side-effects for free.
-(function _phosModalScaffold() {
- const MODAL_SEL = '.models-modal, .model-browser-modal, .expand-lightbox';
- const isVisible = el => {
- const d = el.style.display;
- // Some modals open by adding an .open class (.model-browser-modal);
- // others toggle the inline style. Cover both.
- if (el.classList.contains('open')) return true;
- return d === 'flex' || d === 'block';
- };
- const visibleModals = () =>
- Array.from(document.querySelectorAll(MODAL_SEL)).filter(isVisible);
- const topVisible = () => {
- const v = visibleModals();
- return v.length ? v[v.length - 1] : null;
- };
- const FOCUSABLE = 'button:not([disabled]), [href], input:not([disabled]):not([type="hidden"]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])';
- const refreshScrollLock = () => {
- document.body.classList.toggle('modal-open', visibleModals().length > 0);
- };
- // Wire a single MutationObserver per modal element. Cheaper than a
- // global subtree observer and avoids the cost of body-wide attribute
- // tracking. Lazy — modals added later (none today, but defensive)
- // need to re-register.
- document.querySelectorAll(MODAL_SEL).forEach(el => {
- new MutationObserver(refreshScrollLock).observe(el, {
- attributes: true,
- attributeFilter: ['style', 'class'],
- });
- });
- refreshScrollLock();
-
- // Esc closes the topmost modal. We find the close button inside it
- // and click it (preserves any per-modal cleanup logic — settings
- // save, civitai abort, etc.). Fall back to hiding the element if no
- // close button is found.
- document.addEventListener('keydown', e => {
- if (e.key !== 'Escape') return;
- const top = topVisible();
- if (!top) return;
- e.preventDefault();
- e.stopPropagation();
- const closeBtn =
- top.querySelector('button[onclick*="close"]') ||
- top.querySelector('.close-btn') ||
- top.querySelector('.expand-close');
- if (closeBtn) closeBtn.click();
- else { top.style.display = 'none'; top.classList.remove('open'); }
- });
-
- // Focus trap — when a modal is visible, Tab cycles inside it.
- document.addEventListener('keydown', e => {
- if (e.key !== 'Tab') return;
- const top = topVisible();
- if (!top) return;
- const focusables = Array.from(top.querySelectorAll(FOCUSABLE))
- .filter(el => el.offsetWidth > 0 || el.offsetHeight > 0);
- if (!focusables.length) return;
- const first = focusables[0];
- const last = focusables[focusables.length - 1];
- const active = document.activeElement;
- if (e.shiftKey && (active === first || !top.contains(active))) {
- e.preventDefault();
- last.focus();
- } else if (!e.shiftKey && (active === last || !top.contains(active))) {
- e.preventDefault();
- first.focus();
- }
- });
-})();
-
-// ====== Init ======
-// Skip poll when the tab is backgrounded — at 1.5s cadence with a fan-
-// spinning render in the background, every saved request matters. Pinokio
-// users park the panel in a tab and switch to other apps for the 5–20 min
-// a render takes; nothing in the UI needs updating until they come back.
-// `visibilitychange` fires immediately when the user returns so the chrome
-// catches up on the first frame.
-setInterval(() => { if (!document.hidden) poll(); }, 1500);
-document.addEventListener('visibilitychange', () => { if (!document.hidden) poll(); });
-
-// Delegated click handler for the failed Now-card action buttons.
-// Inline `onclick` attributes on these buttons were fragile — the
-// failed branch of poll() rewrites .ttl's innerHTML every 1.5s, and a
-// click that landed mid-rewrite could be lost. A single delegated
-// listener on document survives every rewrite + costs nothing.
-document.addEventListener('click', (e) => {
- const btn = e.target.closest('[data-action="retry"], [data-action="dismiss"]');
- if (!btn) return;
- e.stopPropagation();
- e.preventDefault();
- const actions = btn.closest('.now-card-actions');
- const id = actions ? actions.dataset.jobId : '';
- if (!id) return;
- if (btn.dataset.action === 'retry') {
- if (typeof retryJob === 'function') retryJob(id);
- } else {
- window._dismissedFailureId = id;
- if (typeof poll === 'function') poll();
+ const cur = _settingsCache.settings;
+ const presets = _settingsCache.presets;
+ // Render preset cards (Standard, Video production, Web, Custom).
+ // Display order matches the typical user journey: most users want
+ // Standard, video pros pick Video production, web preview folks pick Web.
+ const order = ['standard', 'archival', 'web'];
+ const grid = document.getElementById('settingsPresets');
+ grid.innerHTML = '';
+ for (const key of order) {
+ const p = presets[key];
+ const active = cur.output_preset === key ? 'active' : '';
+ const card = document.createElement('label');
+ card.className = `preset-card ${active}`;
+ card.dataset.preset = key;
+ card.innerHTML = `
+ <input type="radio" name="settingsPreset" value="${key}" ${cur.output_preset === key ? 'checked' : ''}>
+ <div class="preset-text">
+ <div class="preset-label">${escapeHtml(p.label)}</div>
+ <div class="preset-blurb">${escapeHtml(p.blurb)}</div>
+ <div class="preset-spec">pix_fmt=${p.pix_fmt} · crf=${p.crf}</div>
+ </div>`;
+ card.addEventListener('click', () => selectPreset(key));
+ grid.appendChild(card);
}
-});
+ // Custom row.
+ const customActive = cur.output_preset === 'custom' ? 'active' : '';
+ const custom = document.createElement('label');
+ custom.className = `preset-card ${customActive}`;
+ custom.dataset.preset = 'custom';
+ custom.innerHTML = `
+ <input type="radio" name="settingsPreset" value="custom" ${cur.output_preset === 'custom' ? 'checked' : ''}>
+ <div class="preset-text">
+ <div class="preset-label">Custom</div>
+ <div class="preset-blurb">Set pix_fmt and CRF manually. For unusual workflows: 10-bit HDR, format-specific delivery, or non-standard CRF for video production work.</div>
+ <div class="preset-spec">pix_fmt=${cur.output_pix_fmt} · crf=${cur.output_crf}</div>
+ </div>`;
+ custom.addEventListener('click', () => selectPreset('custom'));
+ grid.appendChild(custom);
+ // Pre-fill custom inputs with current values
+ document.getElementById('settingsPixFmt').value = cur.output_pix_fmt;
+ document.getElementById('settingsCrfRange').value = cur.output_crf;
+ document.getElementById('settingsCrfNum').value = cur.output_crf;
+ document.getElementById('settingsCustomSection').style.display =
+ cur.output_preset === 'custom' ? 'block' : 'none';
-poll();
-setMode('t2v');
-setAspect('landscape'); // sets aspect first so the default preset orients correctly
-setQuality('balanced'); // bundles quality + dims; respects current aspect
-applyTierTimes(); // rewrite Quality pill subtitles to match this Mac
-updateCustomizeSummary();
-updateDerived();
+ // Memory policy — populated from the server so labels/blurbs stay aligned
+ // with backend behavior.
+ const memSelect = document.getElementById('settingsMemoryPolicy');
+ const memPolicies = _settingsCache.memory_policies || {};
+ if (memSelect) {
+ memSelect.innerHTML = '';
+ for (const key of ['auto', 'fast', 'safe']) {
+ const mp = memPolicies[key];
+ if (!mp) continue;
+ const opt = document.createElement('option');
+ opt.value = key;
+ opt.textContent = mp.label || key;
+ memSelect.appendChild(opt);
+ }
+ memSelect.value = cur.memory_policy || 'auto';
+ memSelect.onchange = renderMemoryPolicyHint;
+ renderMemoryPolicyHint();
+ }
-// Wire the picker components (I2V image + FFLF start/end) and seed the
-// "Recent uploads" strip. The strip is shared across all three pickers,
-// so dropping a new image in one slot makes it instantly clickable in
-// the other two.
-PICKERS.forEach(pickerWire);
-refreshUploadsStrip();
-// Refresh the strip whenever a render finishes (queue/history changes
-// don't fire here), and whenever the user opens FFLF — covers the case
-// where they uploaded something via I2V, then switched to FFLF.
-document.querySelectorAll('#modeGroup .pill-btn').forEach(b => b.addEventListener('click', refreshUploadsStrip));
+ // Token rows. We never receive the actual key from the server (the
+ // /settings GET returns has_X booleans only), so we display either
+ // "set" with an empty placeholder input, or "—" with the placeholder.
+ // Inputs start empty on every modal open; user pastes when they want
+ // to change.
+ setTokenStatus('civitaiKey', cur.has_civitai_key);
+ setTokenStatus('hfToken', cur.has_hf_token);
+ // Placeholders reflect the saved state so an empty input doesn't read
+ // as "no token here" when there is one. The asterisks make it clear
+ // something's persisted; the hint reminds users they paste to replace.
+ const civInput = document.getElementById('civitaiKeyInput');
+ const hfInput = document.getElementById('hfTokenInput');
+ civInput.value = '';
+ hfInput.value = '';
+ civInput.placeholder = cur.has_civitai_key
+ ? '•••••••••• saved — paste new to replace'
+ : '32-char API key';
+ hfInput.placeholder = cur.has_hf_token
+ ? '•••••••••• saved — paste new to replace'
+ : 'hf_…';
+ document.getElementById('civitaiKeyClear').style.display = cur.has_civitai_key ? '' : 'none';
+ document.getElementById('hfTokenClear').style.display = cur.has_hf_token ? '' : 'none';
+ // Spicy mode — render current state. _spicyArmed is the mid-confirm
+ // state (clicked once, waiting for the second click). It lives only
+ // on the JS side; only ON/OFF gets persisted.
+ _spicyArmed = false;
+ renderSpicyState(!!cur.spicy_mode);
+}
-// ============================================================================
-// AGENTIC FLOWS — chat UI (rich version)
-// ============================================================================
-//
-// Pieces:
-// - Workflow tab switch (Manual / Agentic Flows).
-// - Chat with avatar bubbles, markdown rendering, expandable tool cards.
-// - Composer with auto-resize textarea + circular send button (disabled
-// when empty, Cmd/Ctrl+Enter to fire).
-// - Sessions dropdown (from the header session-title click).
-// - Engine settings drawer (modal).
-//
-// Server-authoritative: after every user message we re-render the whole
-// thread from /agent/sessions/<id>'s `rendered_messages` payload. The
-// optimistic user bubble + typing row are inserted immediately for snap.
+function renderMemoryPolicyHint() {
+ const sel = document.getElementById('settingsMemoryPolicy');
+ const hint = document.getElementById('settingsMemoryPolicyHint');
+ if (!sel || !hint) return;
+ const policies = (_settingsCache && _settingsCache.memory_policies) || {};
+ const p = policies[sel.value] || {};
+ hint.textContent = p.blurb || '';
+}
-window.AGENT = {
- sessionId: null,
- config: null,
- busy: false,
- models: [],
- sessions: [], // cached list for the dropdown
- selectedAnchors: {}, // {shot_label: candidate_obj} — synced from session.tool_state
- imageConfig: null, // {kind, has_bfl_api_key, ...}
-};
+let _spicyArmed = false;
-function workflowSwitch(name) {
- document.querySelectorAll('#workflowTabs button[data-workflow]')
- .forEach(b => b.classList.toggle('active', b.dataset.workflow === name));
- const manual = document.getElementById('genForm');
- const agent = document.getElementById('agentPane');
- const studio = document.getElementById('studioSection');
- const train = document.getElementById('trainSection');
- // Set body data attribute so CSS can switch the layout (wider form-pane,
- // show agent-stage-pane on the right).
- document.body.setAttribute('data-workflow', name);
- // Studio is an inline pane inside form-pane — when leaving Manual it
- // must hide too, otherwise the user lands on Agentic Flows with the
- // Studio form overlapping the chat. Also reset currentMode to t2v so
- // a future Manual click returns to a sane default. Bug fix from the
- // browser-driven audit: switching tabs while Studio was active left
- // the chat inaccessible.
- if (studio) studio.classList.remove('show');
- if (train) train.classList.remove('show');
- if (name === 'agent') {
- if (manual) manual.style.display = 'none';
- if (agent) agent.hidden = false;
- agentRefreshConfig();
- if (!window.AGENT.sessionId) {
- const stored = localStorage.getItem('phos_agent_session');
- if (stored) agentLoadSession(stored);
- else agentLoadMostRecent();
- } else {
- agentLoadSession(window.AGENT.sessionId);
- }
- agentStageStart();
- setTimeout(() => {
- const ta = document.getElementById('agentInput');
- if (ta) { agentAutoResize(ta); ta.focus(); }
- }, 50);
- } else if (name === 'train') {
- // Train Character is its own workflow tier (alongside Manual and
- // Agentic Flows). Hide the manual render form + agent chat, show
- // the train section, run its init.
- if (manual) manual.style.display = 'none';
- if (agent) agent.hidden = true;
- agentStageStop();
- if (train) train.classList.add('show');
- if (typeof trainInit === 'function') trainInit();
+function renderSpicyState(isOn) {
+ const badge = document.getElementById('spicyStateBadge');
+ const btn = document.getElementById('spicyToggleBtn');
+ const hint = document.getElementById('spicyHint');
+ if (!badge || !btn) return;
+ badge.classList.remove('on', 'armed');
+ if (_spicyArmed) {
+ badge.textContent = 'ARMED';
+ badge.classList.add('armed');
+ btn.textContent = 'Click again to confirm';
+ btn.classList.remove('ghost-btn');
+ btn.classList.add('primary-btn');
+ hint.style.display = '';
+ hint.textContent = 'Confirms turning Spicy mode ON. NSFW LoRAs will be available in the CivitAI browser. Cancel by closing the modal.';
+ } else if (isOn) {
+ badge.textContent = 'ON';
+ badge.classList.add('on');
+ btn.textContent = 'Disable';
+ btn.classList.remove('primary-btn');
+ btn.classList.add('ghost-btn');
+ hint.style.display = '';
+ hint.textContent = 'Spicy mode is ON. NSFW LoRAs are visible in the CivitAI browser when you tick "Show NSFW".';
} else {
- if (manual) manual.style.display = '';
- if (agent) agent.hidden = true;
- agentStageStop();
+ badge.textContent = 'OFF';
+ btn.textContent = 'Enable Spicy mode';
+ btn.classList.remove('primary-btn');
+ btn.classList.add('ghost-btn');
+ hint.style.display = 'none';
+ hint.textContent = '';
}
- try { localStorage.setItem('phos_workflow', name); } catch(e) {}
}
-document.querySelectorAll('#workflowTabs button[data-workflow]').forEach(b => {
- b.addEventListener('click', () => workflowSwitch(b.dataset.workflow));
-});
-
-// ---- Engine status (in the header pill) -----------------------------------
-// Human-readable model name. mlx-community ships ugly slugs like
-// "Qwen3.6-35B-A3B-Abliterated-Heretic-MLX-4Bit" or
-// "gemma-3-12b-it-4bit" that fill the pill. Keep the "family · size"
-// signal and drop the rest.
-function formatModelName(raw) {
- if (!raw) return '';
- let s = String(raw);
- // Strip common quantization / format suffixes anywhere in the slug.
- s = s.replace(/-(MLX|mlx|GGUF|gguf|AWQ|GPTQ)\b.*$/, '');
- s = s.replace(/-(it|chat|instruct|inst)\b/i, '');
- s = s.replace(/-?(4bit|8bit|q4|q8|bf16|fp16|int4|int8)$/i, '');
- // If it still has flavor tags like "-Abliterated-Heretic", drop those
- // tail tokens unless they're size-bearing.
- // First collapse the family + size if we can detect them.
- const fam = (s.match(/^([A-Za-z][A-Za-z0-9.]*)/) || [])[1] || '';
- const size = (s.match(/(\d+(?:\.\d+)?)[Bb]\b/) || [])[1] || '';
- if (fam && size) {
- // Special-case Gemma's "gemma-3-12b" → "Gemma 3 12B".
- if (/^gemma$/i.test(fam)) {
- const ver = (s.match(/^gemma-(\d)/i) || [])[1];
- return ver ? `Gemma ${ver} ${size}B` : `Gemma ${size}B`;
- }
- // Default: "Qwen3.6 35B"
- return `${fam} ${size}B`;
+async function toggleSpicyMode() {
+ // Two-click confirm to turn ON, single-click to turn OFF.
+ // Easy to disable, deliberate to enable — matches the user spec
+ // ("don't want people to turn it on by mistake, or kids").
+ const cur = (_settingsCache && _settingsCache.settings) || {};
+ const isOn = !!cur.spicy_mode;
+ if (isOn) {
+ // Single-click off, no confirm.
+ await _persistSpicyMode(false);
+ return;
+ }
+ if (!_spicyArmed) {
+ _spicyArmed = true;
+ renderSpicyState(false);
+ // Auto-disarm after 6 s if the user doesn't confirm — prevents
+ // the "click again" state lingering across an unrelated tab return.
+ setTimeout(() => {
+ if (_spicyArmed) {
+ _spicyArmed = false;
+ renderSpicyState(!!(_settingsCache?.settings?.spicy_mode));
+ }
+ }, 6000);
+ return;
}
- // Fallback — truncate the raw slug.
- return s.length > 22 ? s.slice(0, 20) + '…' : s;
+ // Second click — actually persist.
+ _spicyArmed = false;
+ await _persistSpicyMode(true);
}
-// ---- Phase 0 #0.11 — Engine readiness banner ------------------------------
-//
-// `agentCheckEngine` hits /agent/engine/check (which calls
-// engine.health_check on the configured engine) and routes the verdict
-// into a banner above the chat. Banner is tri-state:
-// ok (200 + auth fine) → green, auto-dismiss after 4s unless `forceShow`
-// warn (local helper not started; recoverable) → amber, sticky
-// err (401 / unreachable / probe error) → red, sticky
-//
-// Called from aspInit (so it runs once on page load) and from the tail
-// of agentSaveSettings (so the user gets immediate confirmation that a
-// new API key works).
-window.AGENT_ENGINE_BANNER = {
- hideTimer: null,
- // session-scoped dismiss memory: if the user X'd a green/warn banner,
- // don't pop it back up on the next refresh. Errors always re-show
- // because they really are blocking.
- dismissed: false,
-};
-
-function agentEngineBannerHide(userClick) {
- const el = document.getElementById('agentEngineBanner');
- if (!el) return;
- if (window.AGENT_ENGINE_BANNER.hideTimer) {
- clearTimeout(window.AGENT_ENGINE_BANNER.hideTimer);
- window.AGENT_ENGINE_BANNER.hideTimer = null;
+async function _persistSpicyMode(target) {
+ const status = document.getElementById('settingsStatus');
+ try {
+ const fd = new URLSearchParams();
+ fd.set('spicy_mode', target ? 'true' : 'false');
+ const r = await fetch('/settings', { method: 'POST', body: fd });
+ const j = await r.json();
+ if (j.error) throw new Error(j.error);
+ if (_settingsCache && _settingsCache.settings) {
+ _settingsCache.settings.spicy_mode = !!target;
+ }
+ renderSpicyState(!!target);
+ if (status) {
+ status.textContent = target ? 'Spicy mode ON · NSFW LoRAs unlocked' : 'Spicy mode OFF · NSFW LoRAs hidden';
+ status.className = 'settings-status ok';
+ }
+ // Refresh the CivitAI panel so the "Show NSFW" toggle appears /
+ // disappears immediately without a full page reload.
+ if (typeof refreshCivitaiAccessUI === 'function') refreshCivitaiAccessUI();
+ } catch (e) {
+ if (status) {
+ status.textContent = 'Could not change Spicy mode: ' + (e.message || e);
+ status.className = 'settings-status err';
+ }
}
- el.classList.add('dismissing');
- setTimeout(() => {
- el.hidden = true;
- el.classList.remove('dismissing');
- }, 380);
- if (userClick) window.AGENT_ENGINE_BANNER.dismissed = true;
}
-function agentEngineBannerShow(j, opts) {
- opts = opts || {};
- const el = document.getElementById('agentEngineBanner');
+function setTokenStatus(prefix, isSet, dirty) {
+ const el = document.getElementById(prefix + 'Status');
if (!el) return;
- const titleEl = document.getElementById('agentEngineBannerTitle');
- const detailEl = document.getElementById('agentEngineBannerDetail');
- const iconEl = document.getElementById('agentEngineBannerIcon');
- const actionEl = document.getElementById('agentEngineBannerAction');
-
- // Map engine kind to a friendly label.
- const kindLabel = ({
- phosphene_local: 'Phosphene Local',
- anthropic: 'Claude',
- ollama: 'Ollama',
- custom: 'Custom OpenAI-compat',
- }[j.kind] || j.kind || 'Engine');
-
- // Tri-state: true = ok, null = warn, false = err.
- let state = 'err';
- if (j.ok === true) state = 'ok';
- else if (j.ok === null || j.ok === undefined) state = 'warn';
-
- // Don't re-pop a green banner the user already dismissed unless
- // explicitly forceShow'd (e.g., right after settings save).
- if (state === 'ok' && window.AGENT_ENGINE_BANNER.dismissed && !opts.forceShow) return;
-
- el.classList.remove('ok', 'warn', 'err', 'dismissing');
- el.classList.add(state);
-
- let title, detail, actionLabel = 'Open Settings', showAction = true;
- if (state === 'ok') {
- title = `${kindLabel} ready`;
- const lat = (j.latency_ms != null) ? ` · ${j.latency_ms} ms` : '';
- const model = j.model ? ` · ${j.model}` : '';
- detail = `${model.replace(/^\s·\s/, '')}${lat}`;
- showAction = false;
- } else if (state === 'warn') {
- title = `${kindLabel} not started`;
- detail = j.message || 'Will auto-start on first message.';
- actionLabel = 'Start engine';
- actionEl && (actionEl.onclick = function() {
- // Reuse the existing one-click engine-start path. After the
- // POST returns we poll agentRefreshConfig + agentCheckEngine
- // every 2 s for up to 45 s — Gemma 12B 4-bit binds the port
- // ~10-15 s after spawn, longer if weights need to come off
- // disk. Without the poll, the pill stays "starting…" forever
- // because nothing triggers a refresh once port is bound.
- fetch('/agent/local/start', {method: 'POST'}).then(() => {
- let tries = 0;
- const maxTries = 22; // ~45 s budget
- const tick = () => {
- agentRefreshConfig().then(() => {
- const local = (window.AGENT.config || {}).local_server || {};
- const reachable = (typeof local.reachable === 'boolean')
- ? local.reachable : !!local.running;
- if (reachable || tries >= maxTries) {
- agentCheckEngine({forceShow: true});
- return;
- }
- tries += 1;
- setTimeout(tick, 2000);
- }).catch(() => {
- tries += 1;
- if (tries < maxTries) setTimeout(tick, 2000);
- });
- };
- // First tick immediately so the pill flips out of "click to start"
- // the moment the spawn reports running=true.
- setTimeout(tick, 500);
- });
- });
+ el.classList.remove('set', 'dirty');
+ if (dirty) {
+ el.innerHTML = '<svg class="ph" aria-hidden="true" style="margin-right:4px;vertical-align:-2px"><use href="#ph-pencil-simple"/></svg>unsaved';
+ el.classList.add('dirty');
+ } else if (isSet) {
+ el.innerHTML = '<svg class="ph" aria-hidden="true" style="margin-right:4px;vertical-align:-2px"><use href="#ph-check-bold"/></svg>saved';
+ el.classList.add('set');
} else {
- title = `${kindLabel} unreachable`;
- detail = j.message || 'Probe failed.';
- actionLabel = 'Restart engine';
- actionEl && (actionEl.onclick = function() {
- // Restart-engine action — for the most common cause of unreachable
- // (orphaned process holding the port). The local_server.start path
- // now reaps orphans before spawning, so this is a clean recovery.
- fetch('/agent/local/stop', {method: 'POST'}).then(() =>
- fetch('/agent/local/start', {method: 'POST'})
- ).then(() => {
- let tries = 0;
- const tick = () => {
- agentRefreshConfig().then(() => {
- const local = (window.AGENT.config || {}).local_server || {};
- const reachable = (typeof local.reachable === 'boolean')
- ? local.reachable : !!local.running;
- if (reachable || tries >= 22) {
- agentCheckEngine({forceShow: true});
- return;
- }
- tries += 1;
- setTimeout(tick, 2000);
- });
- };
- setTimeout(tick, 500);
- });
- });
+ el.textContent = 'not set';
}
+}
- if (titleEl) titleEl.textContent = title;
- if (detailEl) detailEl.textContent = detail;
- if (iconEl) {
- const ref = state === 'ok' ? '#ph-check-bold'
- : state === 'warn' ? '#ph-warning-fill'
- : '#ph-x-circle-fill';
- iconEl.innerHTML = '<svg class="ph" aria-hidden="true"><use href="' + ref + '"/></svg>';
- }
- if (actionEl) {
- actionEl.textContent = actionLabel;
- actionEl.style.display = showAction ? '' : 'none';
- }
- el.hidden = false;
+function onTokenInput(which) {
+ const prefix = which === 'civitai' ? 'civitaiKey' : 'hfToken';
+ const inp = document.getElementById(prefix + 'Input');
+ setTokenStatus(prefix, false, !!inp.value);
+}
- // Auto-fade green after 4s unless forceShow.
- if (window.AGENT_ENGINE_BANNER.hideTimer) {
- clearTimeout(window.AGENT_ENGINE_BANNER.hideTimer);
- window.AGENT_ENGINE_BANNER.hideTimer = null;
- }
- if (state === 'ok' && !opts.persist) {
- window.AGENT_ENGINE_BANNER.hideTimer = setTimeout(
- () => agentEngineBannerHide(false),
- opts.forceShow ? 4500 : 3500
- );
+function toggleTokenVisibility(inputId, btn) {
+ const inp = document.getElementById(inputId);
+ if (!inp) return;
+ if (inp.type === 'password') {
+ inp.type = 'text';
+ btn.textContent = 'hide';
+ } else {
+ inp.type = 'password';
+ btn.textContent = 'show';
}
}
-async function agentCheckEngine(opts) {
- opts = opts || {};
- try {
- const r = await fetch('/agent/engine/check');
- if (!r.ok) throw new Error('HTTP ' + r.status);
- const j = await r.json();
- agentEngineBannerShow(j, opts);
- } catch (e) {
- agentEngineBannerShow({
- ok: false,
- message: 'Could not reach panel: ' + (e.message || e),
- kind: '?', model: '',
- }, {persist: true, ...opts});
+// Save-then-test in one click. The /civitai/test and /hf/test endpoints
+// use the saved key, not the current input field. Pre-Y1.023 the user
+// had to: paste → click Apply → click Test. That left a footgun: users
+// pasted, clicked Test, saw it fail (because nothing was saved yet),
+// closed the modal thinking the panel was broken. The token never
+// landed in panel_settings.json, gated downloads kept failing.
+//
+// Now Test does Save first when the input has a value, so a single
+// click works. If the save fails (validator rejects malformed token),
+// we surface the error inline next to the field instead of just at
+// the bottom of the modal.
+async function testToken(which) {
+ const path = which === 'civitai' ? '/civitai/test' : '/hf/test';
+ const resultId = which === 'civitai' ? 'civitaiTestResult' : 'hfTestResult';
+ const inputId = which === 'civitai' ? 'civitaiKeyInput' : 'hfTokenInput';
+ const fieldName = which === 'civitai' ? 'civitai_api_key' : 'hf_token';
+ const statusPrefix = which === 'civitai' ? 'civitaiKey' : 'hfToken';
+ const clearBtnId = which === 'civitai' ? 'civitaiKeyClear' : 'hfTokenClear';
+ const result = document.getElementById(resultId);
+ if (!result) return;
+ result.textContent = 'Testing…';
+ result.style.color = 'var(--muted)';
+
+ // If the input has content, save it first. Empty input means "test
+ // the already-saved token" — the legitimate use after the panel is
+ // configured.
+ const inputEl = document.getElementById(inputId);
+ const inputValue = inputEl ? inputEl.value.trim() : '';
+ if (inputValue) {
+ try {
+ const fd = new URLSearchParams();
+ fd.set(fieldName, inputValue);
+ const saveResp = await fetch('/settings', {
+ method: 'POST',
+ headers: {'Content-Type': 'application/x-www-form-urlencoded'},
+ body: fd,
+ });
+ const saveData = await saveResp.json();
+ if (!saveResp.ok || saveData.error) {
+ result.innerHTML = `<svg class="ph" aria-hidden="true" style="color:var(--danger,#f85149);margin-right:4px;vertical-align:-2px"><use href="#ph-x-circle-fill"/></svg>${escapeHtml(saveData.error || `HTTP ${saveResp.status}`)}`;
+ return;
+ }
+ // Save succeeded — reflect the persisted state in the UI.
+ inputEl.value = '';
+ _settingsCache = { ...(_settingsCache || {}), settings: saveData.settings };
+ setTokenStatus(statusPrefix, true);
+ const clearBtn = document.getElementById(clearBtnId);
+ if (clearBtn) clearBtn.style.display = '';
+ } catch (e) {
+ result.innerHTML = `<svg class="ph" aria-hidden="true" style="color:var(--danger,#f85149);margin-right:4px;vertical-align:-2px"><use href="#ph-x-circle-fill"/></svg>Save failed: ${escapeHtml(e.message || String(e))}`;
+ return;
+ }
}
-}
-async function agentRefreshConfig() {
+ // Now hit the test endpoint, which reads the freshly-saved token.
try {
- const r = await fetch('/agent/config');
- const j = await r.json();
- window.AGENT.config = j;
- window.AGENT.models = j.available_models || [];
- const eng = j.engine || {};
- const local = j.local_server || {};
- const dot = document.getElementById('agentEngineDot');
- const label = document.getElementById('agentEngineLabel');
- let live = false;
- let summary = '';
- if (eng.kind === 'phosphene_local') {
- // The pill is green only when BOTH process is alive AND port
- // accepts connections. Without the reachable check, a freshly
- // crashed engine (bind error after orphan collision) still
- // shows green for ~1 s and the user submits a chat that 500s
- // with "Remote end closed connection without response".
- // `local.reachable` is `true | false`; older panels that don't
- // expose it default to !!local.running for backward compat.
- const reachableOk = (typeof local.reachable === 'boolean')
- ? local.reachable
- : !!local.running;
- live = !!local.running && reachableOk;
- const modelName = formatModelName(eng.model || '');
- // Look up the resident size from the discovered models so the user
- // sees "22 GB" inline next to the name — no surprise loads.
- let sizeBit = '';
- try {
- const path = eng.local_model_path || '';
- const list = j.available_models || [];
- const hit = list.find(m => m.path === path);
- if (hit && hit.size_gb) sizeBit = ` · ${hit.size_gb.toFixed(1)} GB`;
- } catch (e) {}
- // Three-state summary: live / starting / click-to-start. The
- // "starting" state appears the moment a spawn begins until the
- // port is bound (typically 5-15 s for Gemma 12B, longer on first
- // run if weights need to come off disk).
- if (local.running && !reachableOk) {
- summary = `${modelName || 'Local'}${sizeBit} · starting…`;
- } else if (live) {
- summary = `${modelName || 'Local'}${sizeBit} · live`;
- } else {
- summary = `${modelName || 'Local'}${sizeBit} · click to start`;
- }
+ const r = await fetch(path);
+ const data = await r.json();
+ if (data.ok) {
+ result.innerHTML = `<svg class="ph" aria-hidden="true" style="color:var(--success,#3fb950);margin-right:4px;vertical-align:-2px"><use href="#ph-check-bold"/></svg>${escapeHtml(data.message)}`;
} else {
- const u = (eng.base_url || '').replace(/^https?:\/\//, '').replace(/\/v1$/, '');
- summary = `${eng.model || 'remote'} · ${u}`;
- live = !!eng.has_api_key;
- }
- if (dot) {
- dot.classList.remove('live', 'warn', 'bad');
- dot.classList.add(live ? 'live' : 'warn');
- }
- if (label) label.textContent = summary;
- agentRenderModePill();
- // Stop-engine quick action: only meaningful when a local engine is
- // actually running. Hide it for remote engines and when nothing is
- // resident (clicking would no-op).
- const stopBtn = document.getElementById('agentEngineStopBtn');
- if (stopBtn) {
- const isLocal = eng.kind === 'phosphene_local';
- stopBtn.hidden = !(isLocal && local && local.running);
+ result.innerHTML = `<svg class="ph" aria-hidden="true" style="color:var(--danger,#f85149);margin-right:4px;vertical-align:-2px"><use href="#ph-x-circle-fill"/></svg>${escapeHtml(data.error)}`;
}
} catch (e) {
- const label = document.getElementById('agentEngineLabel');
- if (label) label.textContent = 'engine unavailable';
- }
-}
-
-function agentRenderModePill() {
- const pill = document.getElementById('agentModePill');
- const icon = document.getElementById('agentModeIcon');
- const label = document.getElementById('agentModeLabel');
- if (!pill) return;
- const mode = ((window.AGENT.config && window.AGENT.config.engine
- && window.AGENT.config.engine.mode) || 'plan_sleep');
- // Monochrome stroked SVGs — pro-app feel. Color emoji glyphs read
- // as Pythonic in chrome that's otherwise stroke-icon based.
- const ICON_INTERACTIVE =
- '<svg viewBox="0 0 24 24" width="13" height="13" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">' +
- '<path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/>' +
- '</svg>';
- const ICON_PLAN_SLEEP =
- '<svg viewBox="0 0 24 24" width="13" height="13" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">' +
- '<path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"/>' +
- '</svg>';
- if (mode === 'interactive') {
- pill.classList.add('is-interactive');
- if (icon) icon.innerHTML = ICON_INTERACTIVE;
- if (label) label.textContent = 'Interactive';
- pill.title = 'Interactive: chat model stays resident across finishes (uses ~22 GB for Qwen 35B).\nClick to switch to Plan & sleep mode.';
- } else {
- pill.classList.remove('is-interactive');
- if (icon) icon.innerHTML = ICON_PLAN_SLEEP;
- if (label) label.textContent = 'Plan & sleep';
- pill.title = 'Plan & sleep: auto-stop the chat model after the agent finishes (frees RAM for renders).\nClick to switch to Interactive mode.';
+ result.innerHTML = `<svg class="ph" aria-hidden="true" style="color:var(--danger,#f85149);margin-right:4px;vertical-align:-2px"><use href="#ph-x-circle-fill"/></svg>Network error: ${escapeHtml(e.message || String(e))}`;
}
}
-async function agentToggleMode() {
- const cur = ((window.AGENT.config && window.AGENT.config.engine
- && window.AGENT.config.engine.mode) || 'plan_sleep');
- const next = cur === 'interactive' ? 'plan_sleep' : 'interactive';
+async function clearToken(which) {
+ const fd = new FormData();
+ if (which === 'civitai') fd.set('civitai_api_key', '');
+ if (which === 'hf') fd.set('hf_token', '');
try {
- const r = await fetch('/agent/config', {
+ // urlencoded body — see applySettings for why.
+ const r = await fetch('/settings', {
method: 'POST',
- headers: {'Content-Type': 'application/json'},
- body: JSON.stringify({mode: next}),
+ headers: {'Content-Type': 'application/x-www-form-urlencoded'},
+ body: new URLSearchParams(fd),
});
- const j = await r.json();
- if (!r.ok || j.error) throw new Error(j.error || ('HTTP ' + r.status));
- await agentRefreshConfig();
+ const data = await r.json();
+ if (!r.ok || data.error) {
+ alert('Could not clear: ' + (data.error || `HTTP ${r.status}`));
+ return;
+ }
+ // Refresh the modal so the status flips back to "not set".
+ openSettingsModal();
} catch (e) {
- alert('Could not switch mode: ' + e.message);
+ alert('Network error: ' + (e.message || e));
}
}
-async function agentEngineStopNow() {
- const btn = document.getElementById('agentEngineStopBtn');
- if (btn) btn.disabled = true;
- try {
- const r = await fetch('/agent/local/stop', {method: 'POST'});
- if (!r.ok) throw new Error('HTTP ' + r.status);
- // Reflect the new state in the header without waiting for the next
- // /status poll.
- await agentRefreshConfig();
- } catch (e) {
- alert('Stop failed: ' + e.message);
- } finally {
- if (btn) btn.disabled = false;
- }
+function closeSettingsModal() {
+ document.getElementById('settingsModal').style.display = 'none';
}
-// ---- Sessions -------------------------------------------------------------
-async function agentNewSession(initialMessage) {
- const title = (initialMessage || '').slice(0, 60) || 'New chat';
- const r = await fetch('/agent/sessions/new', {
- method: 'POST',
- headers: {'Content-Type': 'application/json'},
- body: JSON.stringify({title}),
+function selectPreset(key) {
+ document.querySelectorAll('#settingsPresets .preset-card').forEach(c => {
+ c.classList.toggle('active', c.dataset.preset === key);
+ const r = c.querySelector('input[type="radio"]');
+ if (r) r.checked = (c.dataset.preset === key);
});
- const j = await r.json();
- if (!j.ok) {
- alert('Could not create session: ' + (j.error || 'unknown'));
- return null;
- }
- window.AGENT.sessionId = j.session.session_id;
- try { localStorage.setItem('phos_agent_session', j.session.session_id); } catch(e) {}
- agentSetSessionTitle(j.session.title || 'New chat', j.session.session_id);
- agentRender([]);
- return j.session;
-}
-
-async function agentLoadMostRecent() {
- try {
- const r = await fetch('/agent/sessions');
- const j = await r.json();
- const sessions = j.sessions || [];
- window.AGENT.sessions = sessions;
- if (sessions.length === 0) {
- agentRender([]);
- return;
- }
- const mostRecent = sessions[0];
- await agentLoadSession(mostRecent.session_id);
- try { localStorage.setItem('phos_agent_session', mostRecent.session_id); } catch(e) {}
- } catch (e) { console.warn('agentLoadMostRecent', e); }
+ document.getElementById('settingsCustomSection').style.display =
+ key === 'custom' ? 'block' : 'none';
+ // Clear status so it doesn't claim "saved" after a fresh selection.
+ document.getElementById('settingsStatus').textContent = '';
+ document.getElementById('settingsStatus').className = 'settings-status';
}
-async function agentLoadSession(sid) {
+async function applySettings() {
+ const status = document.getElementById('settingsStatus');
+ const btn = document.getElementById('settingsApplyBtn');
+ status.textContent = 'Saving…';
+ status.className = 'settings-status';
+ btn.disabled = true;
+ // Read which preset is selected. Custom path also sends pix_fmt + crf.
+ const checked = document.querySelector('#settingsPresets input[type="radio"]:checked');
+ const preset = checked ? checked.value : 'standard';
+ const fd = new FormData();
+ fd.set('output_preset', preset);
+ if (preset === 'custom') {
+ fd.set('output_pix_fmt', document.getElementById('settingsPixFmt').value);
+ fd.set('output_crf', document.getElementById('settingsCrfNum').value);
+ }
+ fd.set('memory_policy', document.getElementById('settingsMemoryPolicy')?.value || 'auto');
+ // Tokens — only send a key when the input has a value. Empty input
+ // means "leave as-is" (clearing is explicit via the Clear button).
+ // This protects against accidentally wiping a saved key by clicking
+ // Apply on an unchanged form.
+ const civInput = document.getElementById('civitaiKeyInput').value.trim();
+ if (civInput) fd.set('civitai_api_key', civInput);
+ const hfInput = document.getElementById('hfTokenInput').value.trim();
+ if (hfInput) fd.set('hf_token', hfInput);
try {
- const r = await fetch('/agent/sessions/' + encodeURIComponent(sid));
- if (!r.ok) {
- try { localStorage.removeItem('phos_agent_session'); } catch(e) {}
- window.AGENT.sessionId = null;
- window.AGENT.selectedAnchors = {};
- agentSetSessionTitle('New chat', null);
- agentRender([]);
+ // Convert FormData → URLSearchParams so the body is sent as
+ // x-www-form-urlencoded — the panel's parse_qs only understands
+ // that wire format, NOT the multipart/form-data fetch sends by
+ // default with FormData. This bug silently turned every settings
+ // save into a no-op (server saw empty payload) until caught.
+ const r = await fetch('/settings', {
+ method: 'POST',
+ headers: {'Content-Type': 'application/x-www-form-urlencoded'},
+ body: new URLSearchParams(fd),
+ });
+ const data = await r.json();
+ if (!r.ok || data.error) {
+ status.textContent = data.error || `HTTP ${r.status}`;
+ status.className = 'settings-status err';
+ btn.disabled = false;
return;
}
- const j = await r.json();
- window.AGENT.sessionId = sid;
- const sess = j.session || {};
- window.AGENT.selectedAnchors = (sess.tool_state || {}).selected_anchors || {};
- window.AGENT.submittedShots = (sess.tool_state || {}).submitted_shots || [];
- agentSetSessionTitle(sess.title || 'Untitled', sid);
- agentRender(j.rendered_messages || []);
- agentRenderBatchBar();
- } catch (e) { console.error('agentLoadSession', e); }
-}
-
-function agentSetSessionTitle(title, sid) {
- const el = document.getElementById('agentSessionTitle');
- if (!el) return;
- el.innerHTML = '';
- const t = document.createElement('span');
- t.textContent = title;
- el.appendChild(t);
- if (sid) {
- const m = document.createElement('span');
- m.className = 'meta';
- m.textContent = '· ' + sid.slice(0, 8);
- el.appendChild(m);
+ status.textContent = data.helper_restarted
+ ? 'Saved. Helper restarted — takes effect on the next render.'
+ : 'Saved.';
+ status.className = 'settings-status ok';
+ btn.disabled = false;
+ // Refresh cache so a re-open shows the new values without a stale flash.
+ _settingsCache = { ...(_settingsCache || {}), settings: data.settings };
+ } catch (e) {
+ status.textContent = 'Network error: ' + (e.message || e);
+ status.className = 'settings-status err';
+ btn.disabled = false;
}
}
-// ============================================================================
-// AGENT SESSIONS SIDEBAR (Cmd+K)
-// ============================================================================
-// Replaces the old absolute-positioned popover with a slide-in sidebar.
-// Searchable, keyboard-navigable, time-bucketed. Pinning persists in
-// localStorage and reflows the form-pane when active.
-window.ASP = {
- open: false,
- pinned: false,
- query: '',
- all: [], // raw /agent/sessions response
- filtered: [], // bucketed for render
- focusIndex: -1, // arrow-key cursor
-};
+// ====== HDR toggle pill (header pill behavior, same as No-music) ======
+(function () {
+ const pill = document.getElementById('hdrPill');
+ const cb = document.getElementById('hdr');
+ if (!pill || !cb) return;
+ const sync = () => pill.classList.toggle('on', cb.checked);
+ cb.addEventListener('change', sync);
+ pill.addEventListener('click', () => setTimeout(sync, 0));
+ sync();
+})();
-function aspInit() {
- // Restore pinned state.
- try {
- if (localStorage.getItem('phos_asp_pinned') === '1') {
- document.body.classList.add('asp-pinned');
- window.ASP.pinned = true;
- }
- } catch (e) {}
- // Phase 0 #0.11 — engine readiness probe. Run once at session start so
- // 401 / unreachable / wrong-base-URL surfaces BEFORE the user invests
- // in attaching a script + writing a long prompt. Delay 600ms so the
- // initial config fetch has settled and the user isn't blinded by a
- // fresh-page banner.
- setTimeout(() => { try { agentCheckEngine(); } catch (e) {} }, 600);
- // Update the trigger count badge from any cached list.
- aspUpdateTriggerCount();
- // Search input.
- const inp = document.getElementById('aspSearchInput');
- if (inp) {
- let to = null;
- inp.addEventListener('input', () => {
- window.ASP.query = inp.value;
- window.ASP.focusIndex = -1;
- clearTimeout(to);
- to = setTimeout(aspRefilterAndRender, 80);
- });
- }
- // Global keyboard shortcuts.
- document.addEventListener('keydown', (e) => {
- // Cmd/Ctrl+K toggles the sidebar.
- if ((e.metaKey || e.ctrlKey) && (e.key === 'k' || e.key === 'K')) {
- e.preventDefault();
- aspToggle();
- return;
- }
- if (window.ASP.open) {
- // "/" focuses the search input.
- if (e.key === '/' && document.activeElement !== inp) {
- e.preventDefault();
- inp && inp.focus();
- return;
- }
- // Esc closes (only when not pinned).
- if (e.key === 'Escape' && !window.ASP.pinned) {
- const modal = document.getElementById('agentSettingsModal');
- const browser = document.getElementById('modelBrowserModal');
- const lb = document.getElementById('agentStageLightbox');
- // Don't steal Esc from layered modals.
- if ((modal && modal.classList.contains('open')) ||
- (browser && browser.classList.contains('open')) ||
- (lb && lb.classList.contains('open'))) return;
- aspClose();
- return;
- }
- // Arrow nav + Enter on the list.
- if (e.key === 'ArrowDown') {
- e.preventDefault();
- aspMoveFocus(1);
- } else if (e.key === 'ArrowUp') {
- e.preventDefault();
- aspMoveFocus(-1);
- } else if (e.key === 'Enter') {
- const items = window.ASP.filtered;
- if (window.ASP.focusIndex >= 0 && window.ASP.focusIndex < items.length) {
- e.preventDefault();
- aspLoad(items[window.ASP.focusIndex].session_id);
- }
- }
- }
- });
-}
+// ====== CivitAI NSFW toggle pill (mirrors HDR toggle UX) ======
+(function () {
+ const pill = document.getElementById('civitaiNsfwPill');
+ const cb = document.getElementById('civitaiNsfw');
+ if (!pill || !cb) return;
+ const sync = () => pill.classList.toggle('on', cb.checked);
+ cb.addEventListener('change', sync);
+ pill.addEventListener('click', () => setTimeout(sync, 0));
+ sync();
+})();
-async function aspToggle() {
- if (window.ASP.open) aspClose();
- else await aspOpen();
-}
+// ====== LoRA picker ======
+//
+// State model: an in-memory list of LoRA entries the user has added.
+// Adding can come from "Use" on a CivitAI install or from clicking a
+// row in the local list. Each entry:
+// { path, name, strength, trigger_words, civitai_url }
+// On every change we mirror the list into the hidden #lorasJson field
+// so make_job's parse_loras_from_form picks them up at submit time.
-async function aspOpen() {
- const panel = document.getElementById('agentSessionsPanel');
- const backdrop = document.getElementById('aspBackdrop');
- if (!panel) return;
- // Refresh list before opening.
- try {
- const r = await fetch('/agent/sessions');
- const j = await r.json();
- window.ASP.all = j.sessions || [];
- window.AGENT.sessions = window.ASP.all; // keep legacy var in sync
- } catch (e) { /* swallow — show whatever's cached */ }
- aspRefilterAndRender();
- panel.dataset.state = 'open';
- panel.setAttribute('aria-hidden', 'false');
- if (backdrop && !window.ASP.pinned) backdrop.classList.add('is-shown');
- if (backdrop) backdrop.hidden = false;
- window.ASP.open = true;
- aspUpdateTriggerCount();
- // Focus search after slide-in animation.
- setTimeout(() => {
- const inp = document.getElementById('aspSearchInput');
- if (inp) inp.focus();
- }, 120);
-}
+let _activeLoras = []; // [{path, name, strength, trigger_words, compatible_modes, ...}]
+let _knownUserLoras = []; // last list_user_loras() snapshot, for the picker
-function aspClose() {
- if (window.ASP.pinned) return; // pin overrides close
- const panel = document.getElementById('agentSessionsPanel');
- const backdrop = document.getElementById('aspBackdrop');
- if (!panel) return;
- panel.dataset.state = 'closed';
- panel.setAttribute('aria-hidden', 'true');
- if (backdrop) backdrop.classList.remove('is-shown');
- window.ASP.open = false;
- window.ASP.focusIndex = -1;
+// Resolve the compat tag the picker should filter by, based on the
+// CURRENT (mode + engine) selection. The unified picker lives in ONE
+// place but its library list re-filters when the user switches mode
+// (Manual T2V/I2V/keyframe/extend → "video") or when they pick a
+// different engine in Image Studio (Qwen-Edit → "image:qwen", FLUX.2
+// Klein-Edit → "image:flux2", etc.). Returns "" to mean "no filter,
+// show everything" — the back-compat path when we can't determine
+// the active engine.
+function _currentLoraModeFilter() {
+ // `currentMode` is a `let` at the top of this <script> block (line ~15016),
+ // sharing the same IIFE scope as setMode() and renderLorasList(). It is
+ // NOT a property of `window` — `let`/`const` at the script's top level
+ // are not auto-attached to globalThis in modern browsers. Reading
+ // `window.currentMode` was always undefined, falling through to the
+ // hidden #mode input which the image branch of setMode deliberately
+ // doesn't update (to avoid an accidental form submit firing a video
+ // render with stale fields). Net effect: the picker filter always
+ // saw 't2v' even after the user clicked Studio. Read currentMode
+ // directly via lexical capture so the mode-aware filter actually
+ // works.
+ const mode = (currentMode || document.getElementById('mode')?.value || 't2v');
+ if (mode !== 'image') {
+ // All video modes share the LTX lane.
+ return 'video';
+ }
+ // Image Studio: read the engine override + map to compat tag.
+ const eng = (document.getElementById('imgStudioEngine')?.value || 'auto').toLowerCase();
+ if (eng.startsWith('qwen_edit')) return 'image:qwen';
+ if (eng.startsWith('flux2_edit') || eng.startsWith('flux2')) return 'image:flux2';
+ if (eng.startsWith('flux1') || eng === 'flux1_inline') return 'image:flux1';
+ if (eng.startsWith('kontext')) return 'image:kontext';
+ if (eng.startsWith('z_image')) return 'image:z_image';
+ if (eng.startsWith('hidream')) return 'image:hidream';
+ // Mock engine is image-lane — narrow off LTX video LoRAs the same way
+ // 'auto' does. Returning '' here skipped the filter entirely (same bug
+ // ab50f12 fixed for 'auto'); video LTX LoRAs would re-appear in the
+ // Image Studio picker when the user picked Mock for testing.
+ if (eng.startsWith('mock')) return 'image';
+ // 'auto' → fall back to the user's saved engine. Without a server
+ // round-trip to /agent/config we don't know exactly which family
+ // they saved; show ALL image-lane LoRAs (image:* + unknown) but
+ // STILL hide LTX video LoRAs which can never run on mflux. Returning
+ // 'image' as a meta-tag — the row filter below treats it as a
+ // wildcard matching anything starting with `image:` plus `unknown`,
+ // so we narrow off the LTX side without false-hiding the rest.
+ // Returning '' here would (and did) skip the filter entirely
+ // because `if (modeTag)` is falsy on empty string — that's the
+ // bug the user hit when Studio + auto showed all 5 of their LTX
+ // LoRAs in the picker.
+ return 'image';
}
-function aspTogglePin() {
- const next = !window.ASP.pinned;
- window.ASP.pinned = next;
- document.body.classList.toggle('asp-pinned', next);
- const backdrop = document.getElementById('aspBackdrop');
- if (backdrop) {
- if (next) backdrop.classList.remove('is-shown');
- else if (window.ASP.open) backdrop.classList.add('is-shown');
+// Friendly label for the active filter, surfaced in the picker banner
+// so the user understands "why don't I see all my LoRAs". Mirrors the
+// _currentLoraModeFilter return values.
+function _loraFilterLabel(tag) {
+ switch (tag) {
+ case 'video': return 'LTX-Video LoRAs (active video mode)';
+ case 'image': return 'image LoRAs (any mflux family — auto engine)';
+ case 'image:qwen': return 'Qwen-Image / Qwen-Image-Edit LoRAs';
+ case 'image:flux2': return 'FLUX.2 LoRAs';
+ case 'image:flux1': return 'FLUX.1 LoRAs';
+ case 'image:kontext': return 'FLUX.1 Kontext LoRAs';
+ case 'image:z_image': return 'Z-Image LoRAs (none expected — most LoRAs trained for other families)';
+ case 'image:sdxl': return 'SDXL LoRAs';
+ case 'image:hidream': return 'HiDream LoRAs (LoRA support not yet implemented — picked LoRAs are ignored)';
+ default: return 'all installed LoRAs';
}
- try { localStorage.setItem('phos_asp_pinned', next ? '1' : ''); } catch (e) {}
- // When pinning, ensure the panel is open (otherwise pinning a closed
- // panel does nothing visible).
- if (next && !window.ASP.open) aspOpen();
-}
-
-function aspRelTime(ts) {
- if (!ts) return '';
- const now = Date.now() / 1000;
- const d = now - ts;
- if (d < 60) return 'just now';
- if (d < 3600) return Math.floor(d / 60) + 'm ago';
- if (d < 86400) return Math.floor(d / 3600) + 'h ago';
- if (d < 86400 * 2) return 'Yesterday';
- if (d < 86400 * 7) return Math.floor(d / 86400) + 'd ago';
- const dt = new Date(ts * 1000);
- return dt.toLocaleString(undefined, {month: 'short', day: 'numeric'});
-}
-
-function aspBucket(ts) {
- if (!ts) return 'Earlier';
- const now = Date.now() / 1000;
- const d = now - ts;
- if (d < 86400) return 'Today';
- if (d < 86400 * 2) return 'Yesterday';
- if (d < 86400 * 7) return 'This week';
- return 'Earlier';
-}
-
-function aspRefilterAndRender() {
- const q = (window.ASP.query || '').toLowerCase().trim();
- const all = (window.ASP.all || []).slice();
- // Sort newest first.
- all.sort((a, b) => (b.updated_at || 0) - (a.updated_at || 0));
- // Filter on title + session id prefix (preview from messages would
- // require a full session fetch per row — defer to v2).
- const filtered = q
- ? all.filter(s => (s.title || '').toLowerCase().includes(q) ||
- (s.session_id || '').toLowerCase().includes(q))
- : all;
- window.ASP.filtered = filtered;
- aspRender();
- aspUpdateTriggerCount();
}
-function aspRender() {
- const list = document.getElementById('aspList');
- const empty = document.getElementById('aspEmpty');
- if (!list || !empty) return;
- list.innerHTML = '';
- const items = window.ASP.filtered || [];
- if (items.length === 0) {
- empty.hidden = false;
- if (window.ASP.query) {
- empty.querySelector('.asp-empty-title').textContent = 'No matches';
- empty.querySelector('.asp-empty-hint').textContent = 'Try a different query, or clear the search.';
- } else {
- empty.querySelector('.asp-empty-title').textContent = 'No sessions yet';
- empty.querySelector('.asp-empty-hint').textContent = 'Type a prompt to start your first one.';
- }
- return;
- }
- empty.hidden = true;
-
- // Pinned sessions surface at the top regardless of recency. Then the
- // standard time buckets in order. All rows still share one keyboard
- // focus index so arrow nav flows naturally across sections.
- const pinnedItems = items.filter(s => s.pinned);
- const restItems = items.filter(s => !s.pinned);
- const buckets = {Today: [], Yesterday: [], 'This week': [], Earlier: []};
- for (const s of restItems) {
- const b = aspBucket(s.updated_at);
- if (!buckets[b]) buckets[b] = [];
- buckets[b].push(s);
- }
- let flatIdx = 0;
- if (pinnedItems.length) {
- const head = document.createElement('div');
- head.className = 'asp-section-label';
- head.textContent = 'Pinned';
- list.appendChild(head);
- for (const s of pinnedItems) { list.appendChild(aspMakeItem(s, flatIdx)); flatIdx++; }
- }
- for (const label of ['Today', 'Yesterday', 'This week', 'Earlier']) {
- const bucket = buckets[label];
- if (!bucket || bucket.length === 0) continue;
- const head = document.createElement('div');
- head.className = 'asp-section-label';
- head.textContent = label;
- list.appendChild(head);
- for (const s of bucket) {
- list.appendChild(aspMakeItem(s, flatIdx));
- flatIdx++;
- }
- }
+function _serializeLoras() {
+ // What the helper actually needs is path + strength. Keep the rest in
+ // the in-memory list for UI rendering, drop it on the wire. Summary
+ // count is updated by renderLorasList() which has fuller state — we
+ // don't touch it here to avoid two functions stomping each other.
+ const slim = _activeLoras.map(l => ({ path: l.path, strength: l.strength }));
+ document.getElementById('lorasJson').value = JSON.stringify(slim);
+ // Train-Character LoRAs are trained against the dev transformer (HQ
+ // path) — Quick/Standard run the distilled model at 8 steps, which is
+ // a different fine-tune of the same architecture. Fusion succeeds
+ // numerically but deltas don't transfer cleanly; the user sees muddy
+ // output. Disable those chips when any trained LoRA is attached so
+ // the wrong-path landing becomes visible.
+ try { updateQualityChipsForLora(); } catch (_) {}
}
-function aspMakeItem(s, flatIdx) {
- const item = document.createElement('div');
- item.className = 'asp-item';
- if (s.session_id === window.AGENT.sessionId) item.classList.add('is-active');
- if (window.ASP.focusIndex === flatIdx) item.classList.add('is-focused');
- if (s.pinned) item.classList.add('is-pinned');
- item.dataset.sid = s.session_id;
- // Cross-reference live queue: if any of this session's submitted shots
- // are currently in the panel queue or running, show a live dot.
- const queueIds = (window.AGENT && window.AGENT.lastStatus
- ? (((window.AGENT.lastStatus.queue || [])
- .concat(window.AGENT.lastStatus.current ? [window.AGENT.lastStatus.current] : [])).map(j => j.id))
- : []);
- const sessionShotIds = (s.submitted_shot_ids || []); // optional field
- const isRunning = sessionShotIds.some(id => queueIds.includes(id));
- const time = aspRelTime(s.updated_at);
- const preview = (s.preview || '').trim();
- item.innerHTML = `
- <div class="asp-row">
- <div class="asp-item-title">${escapeHtml(s.title || 'Untitled')}</div>
- <div class="asp-item-time">${escapeHtml(time)}</div>
- </div>
- ${preview ? `<div class="asp-item-preview">${escapeHtml(preview)}</div>` : ''}
- <div class="asp-item-meta">
- <span class="asp-chip">${s.messages || 0} msg</span>
- <span class="asp-chip asp-chip-shots">${s.shots_submitted || 0} shots</span>
- ${isRunning ? '<span class="asp-status-running" title="Active in queue"></span>' : ''}
- </div>
- <div class="asp-actions">
- <button type="button" class="asp-action-btn" data-action="pin" title="${s.pinned ? 'Unpin' : 'Pin'}">
- <svg class="asp-pin-icon" viewBox="0 0 24 24" fill="${s.pinned ? 'currentColor' : 'none'}" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
- <line x1="12" y1="17" x2="12" y2="22"/>
- <path d="M5 17h14l-2-7V4H7v6z"/>
- </svg>
- </button>
- <button type="button" class="asp-action-btn" data-action="rename" title="Rename">
- <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
- <path d="M11 4H4a2 2 0 00-2 2v14a2 2 0 002 2h14a2 2 0 002-2v-7"/>
- <path d="M18.5 2.5a2.121 2.121 0 013 3L12 15l-4 1 1-4 9.5-9.5z"/>
- </svg>
- </button>
- <button type="button" class="asp-action-btn danger" data-action="delete" title="Delete">
- <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
- <polyline points="3 6 5 6 21 6"/>
- <path d="M19 6l-1 14a2 2 0 01-2 2H8a2 2 0 01-2-2L5 6"/>
- <path d="M10 11v6M14 11v6"/>
- </svg>
- </button>
- </div>
- `;
- item.addEventListener('click', (e) => {
- // If user clicked one of the action buttons, dispatch the action
- // instead of loading the session.
- const btn = e.target.closest('[data-action]');
- if (btn) {
- e.stopPropagation();
- const action = btn.dataset.action;
- if (action === 'delete') aspDeleteRow(s, item);
- else if (action === 'rename') aspBeginRename(s, item);
- else if (action === 'pin') aspTogglePinRow(s);
- return;
- }
- aspLoad(s.session_id);
+function updateQualityChipsForLora() {
+ const trained = Array.isArray(_activeLoras) && _activeLoras.some(a => {
+ const meta = Array.isArray(_knownUserLoras)
+ ? _knownUserLoras.find(u => u.path === a.path)
+ : null;
+ // _knownUserLoras carries the raw sidecar kind ('train_character');
+ // 'trained' is only a display-side alias built inside renderLorasList.
+ // Match the raw value so the chip disable actually fires.
+ return meta && meta.kind === 'train_character';
});
- return item;
-}
-
-async function aspDeleteRow(s, itemEl) {
- if (!confirm(`Delete "${s.title || 'Untitled'}"? This can't be undone.`)) return;
- try {
- const r = await fetch('/agent/sessions/' + encodeURIComponent(s.session_id) + '/delete', {method: 'POST'});
- if (!r.ok) throw new Error('HTTP ' + r.status);
- } catch (e) { alert('Delete failed: ' + e.message); return; }
- // Remove from in-memory list and re-render. If the deleted session
- // was the active one, fall back to the most-recent remaining.
- window.ASP.all = (window.ASP.all || []).filter(x => x.session_id !== s.session_id);
- if (s.session_id === window.AGENT.sessionId) {
- window.AGENT.sessionId = null;
- try { localStorage.removeItem('phos_agent_session'); } catch (e) {}
- const remaining = (window.ASP.all || []).slice().sort((a,b) => (b.updated_at||0) - (a.updated_at||0));
- if (remaining.length) await agentLoadSession(remaining[0].session_id);
- else {
- // Empty UI — clear the chat surface.
- const chat = document.getElementById('agentChat');
- if (chat) chat.innerHTML = '';
- agentSetSessionTitle('New chat', null);
+ document.querySelectorAll('#qualityGroup .pill-btn').forEach(b => {
+ const q = b.dataset.quality;
+ const incompat = trained && (q === 'quick' || q === 'standard');
+ b.classList.toggle('disabled', incompat);
+ if (incompat) {
+ b.title = 'Trained character LoRA needs the dev transformer (High quality). Quick/Standard run the distilled model — different fine-tune, so the LoRA can\'t reproduce the character faithfully.';
+ } else if (b.dataset.tooltipDefault) {
+ b.title = b.dataset.tooltipDefault;
+ } else {
+ b.removeAttribute('title');
}
- }
- aspRefilterAndRender();
-}
-
-function aspBeginRename(s, itemEl) {
- const titleEl = itemEl.querySelector('.asp-item-title');
- if (!titleEl) return;
- const original = s.title || '';
- const input = document.createElement('input');
- input.type = 'text';
- input.className = 'asp-item-title-edit';
- input.value = original;
- titleEl.replaceWith(input);
- input.focus();
- input.select();
- const finish = async (commit) => {
- if (!input.parentNode) return;
- const next = (input.value || '').trim();
- const wrap = document.createElement('div');
- wrap.className = 'asp-item-title';
- wrap.textContent = (commit && next) ? next : original;
- input.replaceWith(wrap);
- if (!commit || !next || next === original) return;
- try {
- const r = await fetch('/agent/sessions/' + encodeURIComponent(s.session_id) + '/rename', {
- method: 'POST',
- headers: {'Content-Type': 'application/json'},
- body: JSON.stringify({title: next}),
- });
- if (!r.ok) throw new Error('HTTP ' + r.status);
- s.title = next;
- // Update the in-memory cache + active-session header if relevant.
- const cached = (window.ASP.all || []).find(x => x.session_id === s.session_id);
- if (cached) cached.title = next;
- if (window.AGENT.sessionId === s.session_id) {
- agentSetSessionTitle(next, s.session_id);
- }
- } catch (e) { alert('Rename failed: ' + e.message); }
- };
- input.addEventListener('blur', () => finish(true));
- input.addEventListener('keydown', (e) => {
- if (e.key === 'Enter') { e.preventDefault(); finish(true); }
- else if (e.key === 'Escape') { e.preventDefault(); finish(false); }
- e.stopPropagation(); // don't bubble to global asp shortcuts
});
-}
-
-async function aspTogglePinRow(s) {
- const next = !s.pinned;
- try {
- const r = await fetch('/agent/sessions/' + encodeURIComponent(s.session_id) + '/pin', {
- method: 'POST',
- headers: {'Content-Type': 'application/json'},
- body: JSON.stringify({pinned: next}),
- });
- if (!r.ok) throw new Error('HTTP ' + r.status);
- s.pinned = next;
- const cached = (window.ASP.all || []).find(x => x.session_id === s.session_id);
- if (cached) cached.pinned = next;
- aspRefilterAndRender();
- } catch (e) { alert('Pin failed: ' + e.message); }
-}
-
-function aspMoveFocus(delta) {
- const items = window.ASP.filtered || [];
- if (items.length === 0) return;
- const next = Math.max(0, Math.min(items.length - 1, window.ASP.focusIndex + delta));
- window.ASP.focusIndex = next;
- aspRender();
- // Scroll into view.
- const list = document.getElementById('aspList');
- if (list) {
- const focused = list.querySelector('.asp-item.is-focused');
- if (focused) focused.scrollIntoView({block: 'nearest'});
+ // If the currently-selected preset just became incompatible, bump to High.
+ const cur = document.getElementById('quality').value;
+ if (trained && (cur === 'quick' || cur === 'standard')) {
+ setQuality('high');
}
}
-async function aspLoad(sid) {
- if (!window.ASP.pinned) aspClose();
- await agentLoadSession(sid);
- // Re-render to update the active state styling.
- aspRender();
-}
-
-function aspUpdateTriggerCount() {
- const el = document.getElementById('aspTriggerCount');
- if (!el) return;
- const n = (window.ASP.all || []).length;
- if (n > 0) {
- el.textContent = String(n);
- el.hidden = false;
+function addLoraToActive(entry) {
+ // Idempotent: same path twice = update strength only.
+ const existing = _activeLoras.find(l => l.path === entry.path);
+ if (existing) {
+ existing.strength = entry.strength;
} else {
- el.hidden = true;
+ _activeLoras.push(entry);
}
+ renderLorasList();
+ _serializeLoras();
}
-// Refresh the cached list periodically while the agent tab is active —
-// keeps the trigger count and "running" dots honest without forcing
-// re-fetches on every keystroke.
-setInterval(() => {
- if (document.body.getAttribute('data-workflow') !== 'agent') return;
- fetch('/agent/sessions').then(r => r.json()).then(j => {
- window.ASP.all = j.sessions || [];
- aspUpdateTriggerCount();
- if (window.ASP.open) aspRefilterAndRender();
- }).catch(() => {});
-}, 10000);
-
-// Boot.
-document.addEventListener('DOMContentLoaded', aspInit);
-if (document.readyState !== 'loading') aspInit();
-
-// ---- Markdown rendering ---------------------------------------------------
-// Tight subset: headers, bold, italic, inline code, code blocks, lists,
-// tables, blockquotes, hr, paragraphs. Escapes HTML first; processes
-// markdown on already-safe text. Code blocks are pulled out of the way
-// before other regexes run, then restored.
-function mdToHtml(src) {
- if (!src) return '';
- let s = String(src);
- // Strip the fenced ```action ...``` blocks we use for tool calls — they're
- // already represented as tool-call cards, no need to show the JSON twice.
- s = s.replace(/```(?:action|tool|json action|action_json)\s*\n[\s\S]*?\n```/gi, '').trim();
- // Pull out code blocks first
- const blocks = [];
- s = s.replace(/```(\w*)\n([\s\S]*?)```/g, (_, lang, code) => {
- blocks.push(`<pre><code>${escapeHtml(code)}</code></pre>`);
- return `CB${blocks.length - 1}`;
- });
- // Escape rest
- s = escapeHtml(s);
- // Inline code (must come before bold/italic so backticks don't get eaten)
- s = s.replace(/`([^`\n]+)`/g, (_, c) => `<code>${c}</code>`);
- // Headers (longest first)
- s = s.replace(/^#### (.+)$/gm, '<h4>$1</h4>');
- s = s.replace(/^### (.+)$/gm, '<h3>$1</h3>');
- s = s.replace(/^## (.+)$/gm, '<h2>$1</h2>');
- s = s.replace(/^# (.+)$/gm, '<h1>$1</h1>');
- // Horizontal rule
- s = s.replace(/^---+$/gm, '<hr>');
- // Bold then italic
- s = s.replace(/\*\*([^\n*]+)\*\*/g, '<strong>$1</strong>');
- s = s.replace(/(^|[^*])\*([^\n*]+)\*(?!\*)/g, '$1<em>$2</em>');
- // Tables — block of lines starting with | ... |
- s = s.replace(/((?:^\|[^\n]*\|\n?)+)/gm, (block) => {
- const rows = block.trim().split('\n').filter(l => !/^\s*\|[\s\-:|]+\|\s*$/.test(l));
- if (rows.length < 1) return block;
- const html = rows.map((row, i) => {
- const cells = row.replace(/^\|/, '').replace(/\|$/, '').split('|').map(c => c.trim());
- const tag = i === 0 ? 'th' : 'td';
- return '<tr>' + cells.map(c => `<${tag}>${c}</${tag}>`).join('') + '</tr>';
- }).join('');
- return `<table>${html}</table>`;
- });
- // Blockquotes
- s = s.replace(/((?:^&gt; .+\n?)+)/gm, (block) => {
- const inner = block.split('\n').map(l => l.replace(/^&gt; ?/, '')).join(' ').trim();
- return `<blockquote>${inner}</blockquote>`;
- });
- // Unordered lists
- s = s.replace(/((?:^[-*] .+\n?)+)/gm, (block) => {
- const items = block.trim().split('\n').map(l => l.replace(/^[-*] /, ''));
- return '<ul>' + items.map(i => `<li>${i}</li>`).join('') + '</ul>';
- });
- // Ordered lists
- s = s.replace(/((?:^\d+\. .+\n?)+)/gm, (block) => {
- const items = block.trim().split('\n').map(l => l.replace(/^\d+\. /, ''));
- return '<ol>' + items.map(i => `<li>${i}</li>`).join('') + '</ol>';
- });
- // Wrap remaining text into paragraphs (split on blank lines)
- s = s.split(/\n\n+/).map(p => {
- p = p.trim();
- if (!p) return '';
- if (/^<(h[1-6]|ul|ol|table|pre|blockquote|hr)/.test(p)) return p;
- return `<p>${p.replace(/\n/g, '<br>')}</p>`;
- }).join('\n');
- // Restore code blocks
- s = s.replace(/CB(\d+)/g, (_, i) => blocks[parseInt(i, 10)] || '');
- return s;
-}
-
-function escapeHtml(s) {
- return String(s).replace(/[&<>"']/g, c => ({
- '&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'
- }[c]));
-}
-
-// ---- Chat rendering -------------------------------------------------------
-
-// Phase 0 #0.9 — turn summaries.
-//
-// A "turn" is the run of messages from one user message up to (but not
-// including) the next. The interesting span for the user reading back
-// is "what tools did the agent invoke + what came of them", so we aggregate
-// tool_result counts per turn and attach a one-line chip to the LAST
-// assistant message in that turn. Empty for turns with no tool actions
-// (pure conversation).
-const _AGENT_TOOL_LABELS = {
- generate_shot_images: 'anchors',
- submit_shot: 'shots queued',
- estimate_shot: 'shots estimated',
- inspect_clip: 'clips inspected',
- read_document: 'docs read',
- list_loras: 'LoRA scans',
- get_master_style: 'style fetched',
- extract_frame: 'frames pulled',
- upload_image: 'uploads',
- wait_for_shot: 'shots awaited',
- get_queue_status: 'queue checks',
- write_session_manifest: 'manifest writes',
- append_project_notes: 'notes added',
- read_project_notes: 'notes read',
- get_selected_anchors: 'pick reads',
- finish: 'finished',
-};
-
-function _turnSummaryByIdx(messages) {
- // Walk the array. Each user message starts a turn. The LAST assistant
- // message before the next user (or end of array) is where the summary
- // attaches. Counts come from tool_result entries within the turn.
- const out = {}; // {idx: {counts, lastAssistantIdx}}
- let turnStart = -1; // -1 = no user msg yet
- let counts = {};
- let lastAssistantIdx = -1;
- const flush = () => {
- if (turnStart < 0 || lastAssistantIdx < 0) return;
- const has = Object.keys(counts).length > 0;
- if (!has) return;
- out[lastAssistantIdx] = {counts: counts};
- };
- for (let i = 0; i < messages.length; i++) {
- const m = messages[i];
- if (m.kind === 'user') {
- flush();
- turnStart = i;
- counts = {};
- lastAssistantIdx = -1;
- } else if (m.kind === 'tool_result') {
- // Tool name lives on the PRECEDING assistant message's tool_call —
- // see Stage activity-feed code which uses the same pairing pattern.
- // This is a quirk of the rendered_messages shape: tool_result has
- // {ok, result, error} but not the tool name.
- const prev = messages[i - 1];
- const tool = prev && prev.tool_call && prev.tool_call.tool;
- if (tool) counts[tool] = (counts[tool] || 0) + 1;
- } else if (m.kind === 'assistant' || !m.kind) {
- lastAssistantIdx = i;
- }
- }
- flush();
- return out;
+function removeLoraFromActive(path) {
+ _activeLoras = _activeLoras.filter(l => l.path !== path);
+ renderLorasList();
+ _serializeLoras();
}
-function _renderTurnSummaryChip(info) {
- const c = info.counts || {};
- const wrap = document.createElement('div');
- wrap.className = 'agent-turn-summary';
- wrap.title = 'What this turn accomplished';
- // Sparkle icon. SVG so it looks crisp.
- wrap.innerHTML =
- '<svg class="agent-turn-summary-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round">' +
- '<polygon points="12 2 14.5 9.5 22 12 14.5 14.5 12 22 9.5 14.5 2 12 9.5 9.5"/></svg>' +
- '<span class="agent-turn-summary-text"></span>';
- const txt = wrap.querySelector('.agent-turn-summary-text');
- // Stable order: queued shots and anchors come first so glance-readers
- // see the high-leverage actions (rendering work) before diagnostics.
- const order = [
- 'submit_shot', 'generate_shot_images', 'estimate_shot', 'inspect_clip',
- 'read_document', 'extract_frame', 'upload_image', 'wait_for_shot',
- 'get_queue_status', 'list_loras', 'get_master_style',
- 'write_session_manifest', 'append_project_notes', 'read_project_notes',
- 'get_selected_anchors', 'finish',
- ];
- const parts = [];
- for (const tool of order) {
- if (!c[tool]) continue;
- const lbl = _AGENT_TOOL_LABELS[tool] || tool;
- if (tool === 'finish') {
- parts.push(`<span class="ok">✓ finished</span>`);
- } else if (tool === 'generate_shot_images') {
- // each call generates ≥1 anchor; the count IS calls, not anchors.
- // Still meaningful enough for a one-liner.
- parts.push(`${c[tool]} ${lbl}`);
- } else {
- parts.push(`${c[tool]} ${lbl}`);
- }
- }
- // Any tool we didn't know about — still show its raw name.
- for (const tool in c) {
- if (order.includes(tool)) continue;
- parts.push(`${c[tool]} ${tool}`);
- }
- txt.innerHTML = parts.join('<span class="sep"> · </span>');
- return wrap;
+function setLoraStrength(path, strength) {
+ const e = _activeLoras.find(l => l.path === path);
+ if (!e) return;
+ e.strength = Math.max(-2, Math.min(2, parseFloat(strength) || 0));
+ _serializeLoras();
}
-function agentRender(messages) {
- const chat = document.getElementById('agentChat');
- if (!chat) return;
- chat.innerHTML = '';
- if (!messages || messages.length === 0) {
- chat.appendChild(renderEmpty());
+async function refreshLoras() {
+ // Pull the FULL library (no mode filter) so _knownUserLoras keeps every
+ // entry — that lets refreshLoras() also serve as the "deleted on disk"
+ // garbage collector below. The visible filter is applied client-side
+ // in renderLorasList() via _currentLoraModeFilter(), which keeps the
+ // round-trip count to one and avoids re-fetching every time the
+ // user flips mode/engine.
+ let data;
+ try {
+ data = await (await fetch('/loras')).json();
+ } catch (e) {
return;
}
- // Pre-compute per-turn summaries so renderMessage can attach the chip
- // to the LAST assistant message of each turn without a second pass.
- const summaryByIdx = _turnSummaryByIdx(messages);
- for (let i = 0; i < messages.length; i++) {
- const node = renderMessage(messages[i]);
- chat.appendChild(node);
- if (summaryByIdx[i]) {
- // Attach inside the assistant message body so it visually lives
- // with that message rather than floating below it.
- const body = node.querySelector('.agent-msg-body');
- if (body) body.appendChild(_renderTurnSummaryChip(summaryByIdx[i]));
- }
+ _knownUserLoras = data.user || [];
+ // Update displayed loras dir
+ if (data.loras_dir) {
+ const dirEl = document.getElementById('lorasDir');
+ if (dirEl) dirEl.textContent = data.loras_dir;
}
- // Hand-off the scroll on next animation frame so freshly-inserted nodes
- // have measured heights.
- requestAnimationFrame(() => agentChatScrollIfPinned(chat));
-}
-
-// Scroll-pinning: only auto-scroll when the user is already at (or near)
-// the bottom. If they've scrolled up to read something, leave them alone
-// and surface a "↓ New messages" pill they can click to catch up. The
-// pill goes away once they're back at the bottom (any scroll restores
-// the pin).
-const _AGENT_CHAT_NEAR_BOTTOM_PX = 80;
-function _isChatNearBottom(chat) {
- if (!chat) return true;
- return (chat.scrollHeight - chat.scrollTop - chat.clientHeight)
- <= _AGENT_CHAT_NEAR_BOTTOM_PX;
-}
-function _setNewMsgsPill(visible) {
- const p = document.getElementById('agentNewMsgsPill');
- if (!p) return;
- p.hidden = !visible;
-}
-function agentChatScrollIfPinned(chat) {
- if (!chat) chat = document.getElementById('agentChat');
- if (!chat) return;
- if (_isChatNearBottom(chat)) {
- chat.scrollTop = chat.scrollHeight;
- _setNewMsgsPill(false);
- } else {
- _setNewMsgsPill(true);
+ // Backfill compatible_modes on any active LoRA whose entry we now
+ // have full metadata for — addLoraToActive() may have stored a sparse
+ // {path, strength, name} from a CivitAI install before /loras was
+ // refreshed.
+ for (const a of _activeLoras) {
+ if (!a.compatible_modes) {
+ const ul = _knownUserLoras.find(u => u.path === a.path);
+ if (ul) a.compatible_modes = ul.compatible_modes || ['unknown'];
+ }
}
-}
-// Force-scroll for explicit user actions (Send pressed, pill clicked).
-function agentScrollChatToBottom() {
- const chat = document.getElementById('agentChat');
- if (!chat) return;
- chat.scrollTop = chat.scrollHeight;
- _setNewMsgsPill(false);
-}
-// Wire scroll listener once at boot to clear the pill when the user
-// catches up to the bottom on their own.
-document.addEventListener('DOMContentLoaded', () => {
- const chat = document.getElementById('agentChat');
- if (!chat) return;
- chat.addEventListener('scroll', () => {
- if (_isChatNearBottom(chat)) _setNewMsgsPill(false);
- }, {passive: true});
-});
-
-function renderEmpty() {
- const wrap = document.createElement('div');
- wrap.className = 'agent-empty';
- // Y2.002 redesign: hero glyph + polished suggestion grid with icons.
- // Each example carries an inline icon so the row reads like a card,
- // not a text-only list. Suggestions chosen to mirror the three most
- // common entry points (script → shorts, planning a long-form piece,
- // continuing an existing project).
- wrap.innerHTML = `
- <div class="agent-empty-glyph" aria-hidden="true"></div>
- <div class="badge">Phosphene · Agentic Flows</div>
- <h3>Plan a film overnight</h3>
- <p>Paste a script or describe a piece. I'll plan the shots, estimate the wall time, and queue the renders.</p>
- <p style="opacity:0.75">You wake up to mp4s and a manifest.json.</p>
- <div class="examples">
- <div class="example" data-prompt="I want to make a short movie. Help me plan it shot by shot, then we'll generate it together.">
- <span class="ex-icon" aria-hidden="true">
- <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
- <polygon points="23 7 16 12 23 17 23 7"></polygon>
- <rect x="1" y="5" width="15" height="14" rx="2" ry="2"></rect>
- </svg>
- </span>
- <span class="ex-text">Plan a short film, shot by shot</span>
- <span class="arrow">→</span>
- </div>
- <div class="example" data-prompt="I want to make a 30-minute video. Walk me through how to break it into renderable shots given LTX 2.3's per-clip limits.">
- <span class="ex-icon" aria-hidden="true">
- <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
- <circle cx="12" cy="12" r="10"></circle>
- <polyline points="12 6 12 12 16 14"></polyline>
- </svg>
- </span>
- <span class="ex-text">Break a 30-minute piece into renderable shots</span>
- <span class="arrow">→</span>
- </div>
- <div class="example" data-prompt="I want to make clips for my existing project. Ask me about the project first, then we'll plan the next batch of shots together.">
- <span class="ex-icon" aria-hidden="true">
- <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
- <path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"></path>
- </svg>
- </span>
- <span class="ex-text">Continue an existing project</span>
- <span class="arrow">→</span>
- </div>
- </div>
- `;
- wrap.querySelectorAll('.example').forEach(b => {
- b.addEventListener('click', () => {
- const ta = document.getElementById('agentInput');
- if (!ta) return;
- ta.value = b.dataset.prompt;
- agentAutoResize(ta);
- agentUpdateSendState();
- ta.focus();
- });
- });
- return wrap;
+ // If a row was previously active but the file is gone (deleted on
+ // disk), drop it from the active set so we don't submit a stale path.
+ const knownPaths = new Set(_knownUserLoras.map(l => l.path));
+ _activeLoras = _activeLoras.filter(l =>
+ knownPaths.has(l.path) || l.path.includes('/')); // keep HF ids (no dir slash)
+ renderLorasList();
+ _serializeLoras();
}
-// Y2.002 — relative timestamp helper for the chat. Accepts unix-seconds,
-// unix-ms, or an ISO string. Returns "just now" / "3 min ago" / "2 h ago"
-// / "5 d ago" / "Apr 24" — whatever's most readable for the gap.
-function _agentRelTime(ts) {
- if (ts === null || ts === undefined) return '';
- let t;
- if (typeof ts === 'number') {
- t = ts > 1e12 ? ts : ts * 1000;
- } else {
- const p = Date.parse(ts);
- if (Number.isNaN(p)) return '';
- t = p;
- }
- const diff = Math.max(0, Date.now() - t) / 1000;
- if (diff < 30) return 'just now';
- if (diff < 90) return '1 min ago';
- if (diff < 3600) return Math.round(diff / 60) + ' min ago';
- if (diff < 7200) return '1 h ago';
- if (diff < 86400) return Math.round(diff / 3600) + ' h ago';
- if (diff < 7 * 86400) return Math.round(diff / 86400) + ' d ago';
- try {
- return new Date(t).toLocaleDateString(undefined, {month: 'short', day: 'numeric'});
- } catch (e) { return ''; }
-}
+function renderLorasList() {
+ const wrap = document.getElementById('lorasList');
+ const empty = document.getElementById('lorasEmpty');
+ const filterRow = document.getElementById('lorasFilterRow');
+ const filterInput = document.getElementById('lorasFilter');
+ const banner = document.getElementById('loraModeBanner');
+ if (!wrap) return;
-// Y2.002 — install per-pre copy buttons on the rendered markdown body.
-// Called after the message content is set so we can decorate every <pre>
-// in the assistant message without touching the markdown renderer itself.
-function _installPreCopyButtons(rootEl) {
- if (!rootEl) return;
- const pres = rootEl.querySelectorAll('pre');
- pres.forEach((pre) => {
- if (pre.querySelector('.agent-copy-pre')) return; // already decorated
- const btn = document.createElement('button');
- btn.type = 'button';
- btn.className = 'agent-copy-pre';
- btn.title = 'Copy code';
- btn.setAttribute('aria-label', 'Copy code');
- btn.innerHTML = '<svg viewBox="0 0 24 24" width="12" height="12" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="9" y="9" width="13" height="13" rx="2" ry="2"></rect><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"></path></svg>';
- btn.addEventListener('click', (ev) => {
- ev.stopPropagation();
- const code = pre.querySelector('code') || pre;
- try {
- navigator.clipboard.writeText(code.textContent || '');
- btn.classList.add('copied');
- btn.title = 'Copied';
- setTimeout(() => { btn.classList.remove('copied'); btn.title = 'Copy code'; }, 1400);
- } catch (e) { /* best-effort */ }
- });
- pre.appendChild(btn);
- });
-}
+ // Resolve current (mode + engine) → compat tag. Drives both the
+ // library filter AND the per-active-chip "wrong family" warning.
+ const modeTag = _currentLoraModeFilter();
-function renderMessage(m) {
- if (m.kind === 'tool_result') return renderToolResultCard(m.result || {});
- if (m.kind === 'system_note') return renderSystemNote(m.content || '');
-
- const row = document.createElement('div');
- row.className = 'agent-msg-row ' + (m.kind === 'user' ? 'user' : 'assistant');
- // Y2.002: tag streaming rows so the avatar gets the pulse halo while
- // the model is mid-stream. The runtime sets m.streaming on the latest
- // assistant turn until the response settles.
- if (m.kind !== 'user' && m.streaming) row.classList.add('streaming');
-
- const av = document.createElement('div');
- av.className = `agent-avatar ${m.kind === 'user' ? 'user' : 'claude'}`;
- // User shows initial "U"; assistant shows the circular Phosphene logo
- // via CSS background — leave textContent empty for assistant so the
- // ::before sprite is visible.
- av.textContent = m.kind === 'user' ? 'U' : '';
-
- const body = document.createElement('div');
- body.className = 'agent-msg-body';
-
- const name = document.createElement('div');
- name.className = 'agent-msg-name';
- // Header row — name + hover-revealed timestamp + copy button. The
- // timestamp is only shown on assistant rows (user bubbles are right-
- // aligned and don't carry a name). Relative ("3 min ago") instead of
- // absolute clock time so the chat reads like a conversation.
- if (m.kind === 'user') {
- name.textContent = 'You';
- } else {
- const nameSpan = document.createElement('span');
- nameSpan.textContent = 'Phosphene';
- name.appendChild(nameSpan);
- if (m.timestamp || m.created_at || m.ts) {
- const t = document.createElement('span');
- t.className = 'agent-msg-time';
- t.textContent = _agentRelTime(m.timestamp || m.created_at || m.ts);
- name.appendChild(t);
- }
- // Copy button — appears on hover, copies the rendered message text.
- const acts = document.createElement('span');
- acts.className = 'agent-msg-actions';
- const copyBtn = document.createElement('button');
- copyBtn.type = 'button';
- copyBtn.className = 'agent-msg-action';
- copyBtn.title = 'Copy message';
- copyBtn.innerHTML = '<svg viewBox="0 0 24 24" width="12" height="12" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="9" y="9" width="13" height="13" rx="2" ry="2"></rect><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"></path></svg>';
- copyBtn.addEventListener('click', (ev) => {
- ev.stopPropagation();
- const txt = m.content || '';
- try {
- navigator.clipboard.writeText(txt);
- copyBtn.classList.add('copied');
- copyBtn.title = 'Copied';
- setTimeout(() => { copyBtn.classList.remove('copied'); copyBtn.title = 'Copy message'; }, 1400);
- } catch (e) { /* best-effort */ }
+ // Combine: user-installed LoRAs (from /loras) plus any active LoRAs
+ // that aren't user-installed (HF repo paths, e.g. from the HDR toggle).
+ const allRows = [];
+ const seen = new Set();
+ for (const ul of _knownUserLoras) {
+ const active = _activeLoras.find(a => a.path === ul.path);
+ seen.add(ul.path);
+ allRows.push({
+ path: ul.path,
+ name: ul.name,
+ trigger_words: ul.trigger_words || [],
+ recommended_strength: ul.recommended_strength || 1.0,
+ filename: ul.filename,
+ civitai_url: ul.civitai_url,
+ compatible_modes: ul.compatible_modes || ['unknown'],
+ active: !!active,
+ strength: active ? active.strength : (ul.recommended_strength || 1.0),
+ // 'user' = downloaded/installed (CivitAI or manual);
+ // 'trained' = produced by Phosphene's in-app Train Character pipeline
+ // ('kind' on the sidecar is 'train_character'). The picker badges
+ // these separately so the user finds their own characters fast.
+ kind: ul.kind === 'train_character' ? 'trained' : 'user',
});
- acts.appendChild(copyBtn);
- name.appendChild(acts);
}
-
- body.appendChild(name);
-
- if (m.attachments && m.attachments.length) {
- body.appendChild(renderAttachmentChips(m.attachments));
- }
-
- // Reasoning disclosure — surfaces the model's chain-of-thought as a
- // collapsible "Thinking" block above the content. Closed by default
- // so the chat reads as the answer; expand to see the model's work.
- // The #1 fix for "agent appears stuck" — reasoning models spend most
- // of their time here and the user couldn't see it.
- if (m.reasoning) body.appendChild(renderReasoningBlock(m.reasoning));
-
- const content = document.createElement('div');
- content.className = 'agent-msg-content agent-md';
- content.innerHTML = mdToHtml(m.content || '');
- // Y2.002 — decorate every <pre> with a hover-revealed copy button.
- _installPreCopyButtons(content);
- // Inline streaming dots — appended only while the message is mid-stream.
- // Sits at the end of the content so it reads as "more is coming".
- if (m.kind !== 'user' && m.streaming) {
- const dots = document.createElement('span');
- dots.className = 'agent-streaming-dots';
- dots.innerHTML = '<span></span><span></span><span></span>';
- content.appendChild(dots);
+ for (const a of _activeLoras) {
+ if (seen.has(a.path)) continue;
+ allRows.push({
+ path: a.path,
+ name: a.name || a.path,
+ trigger_words: a.trigger_words || [],
+ recommended_strength: 1.0,
+ filename: null,
+ civitai_url: null,
+ compatible_modes: a.compatible_modes || ['unknown'],
+ active: true,
+ strength: a.strength,
+ kind: 'remote',
+ });
}
- body.appendChild(content);
-
- if (m.tool_call) body.appendChild(renderToolCallCard(m.tool_call));
-
- row.appendChild(av);
- row.appendChild(body);
- return row;
-}
-
-// Reasoning block — shows the model's chain-of-thought (Qwen 3.6 / R1 /
-// any mlx-lm reasoning model). Collapsed by default; click to expand.
-// Reads as a quiet bracket of italic text above the answer so users
-// see SOMETHING happened during the long inference even if the final
-// content was short. Crucial for reasoning models where the model
-// spends 80% of its tokens here.
-function renderReasoningBlock(text) {
- const wrap = document.createElement('details');
- wrap.className = 'agent-reasoning';
- const sum = document.createElement('summary');
- const len = (text || '').length;
- sum.innerHTML =
- '<svg viewBox="0 0 24 24" width="11" height="11" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><path d="M9 5l7 7-7 7"/></svg>' +
- '<span class="label">Thinking</span>' +
- `<span class="meta">${len.toLocaleString()} chars</span>`;
- wrap.appendChild(sum);
- const body = document.createElement('div');
- body.className = 'agent-reasoning-body';
- body.textContent = text;
- wrap.appendChild(body);
- return wrap;
-}
-function renderAttachmentChips(attachments) {
- const wrap = document.createElement('div');
- wrap.className = 'agent-msg-attachments';
- for (const a of attachments) {
- const kind = AGENT_ATTACH_KIND(a.mime, a.name);
- const link = document.createElement('a');
- link.className = 'agent-msg-attach';
- link.href = '/image?path=' + encodeURIComponent(a.path);
- link.target = '_blank';
- link.rel = 'noopener';
- link.title = a.path;
-
- const thumb = document.createElement(kind === 'image' ? 'img' : 'div');
- thumb.className = 'thumb';
- if (kind === 'image') {
- thumb.src = '/image?path=' + encodeURIComponent(a.path);
- thumb.alt = a.name;
- } else {
- thumb.innerHTML = agentAttachIcon(kind);
- }
- const nameEl = document.createElement('span');
- nameEl.className = 'name';
- nameEl.textContent = a.name;
- link.appendChild(thumb);
- link.appendChild(nameEl);
- wrap.appendChild(link);
+ // Empty state — collapse the filter box too.
+ if (allRows.length === 0) {
+ wrap.innerHTML = '';
+ if (empty) empty.style.display = '';
+ if (filterRow) filterRow.style.display = 'none';
+ if (banner) banner.textContent = '';
+ return;
}
- return wrap;
-}
-
-function renderSystemNote(text) {
- const div = document.createElement('div');
- div.style.cssText = 'text-align:center; padding:8px; font-size:11px; color:var(--muted); font-style:italic;';
- div.textContent = text;
- return div;
-}
-
-function renderToolCallCard(call) {
- const card = document.createElement('div');
- card.className = 'agent-tool-card pending';
- const head = document.createElement('div');
- head.className = 'head';
- const summary = summarizeToolCall(call);
- // Y2.002: empty .icon for pending (the CSS ::before paints a pulsing
- // dot); .icon-glyph holds the legacy gear so the older non-pending
- // states still have something to fall back to.
- head.innerHTML = `
- <span class="icon"><svg class="ph" aria-hidden="true"><use href="#ph-gear-six"/></svg></span>
- <span class="name">${escapeHtml(call.tool || '?')}</span>
- <span class="summary">${escapeHtml(summary)}</span>
- <span class="duration">running…</span>
- <span class="chevron">›</span>
- `;
- const body = document.createElement('div');
- body.className = 'body';
- const pre = document.createElement('pre');
- try { pre.textContent = JSON.stringify(call.args || {}, null, 2); }
- catch(e) { pre.textContent = String(call.args); }
- body.appendChild(pre);
- card.appendChild(head);
- card.appendChild(body);
- head.addEventListener('click', () => card.classList.toggle('open'));
- return card;
-}
+ if (empty) empty.style.display = 'none';
-function renderToolResultCard(result) {
- const card = document.createElement('div');
- const ok = result.ok !== false && !result.error;
- card.className = 'agent-tool-card ' + (ok ? 'success' : 'error');
- const head = document.createElement('div');
- head.className = 'head';
- const inner = result.result;
- const summary = ok ? summarizeToolResult(inner) : (result.error || 'failed');
- // Y2.002: surface duration when the runtime gives us one. Backends
- // may stash it on result.duration_sec / .duration_ms / .elapsed_sec
- // — be defensive and fall back to nothing when absent.
- let dur = '';
- const ds = (result.duration_sec ?? result.elapsed_sec
- ?? (result.duration_ms != null ? result.duration_ms / 1000 : null));
- if (typeof ds === 'number' && Number.isFinite(ds) && ds >= 0) {
- if (ds < 1) dur = Math.round(ds * 1000) + ' ms';
- else if (ds < 60) dur = ds.toFixed(ds < 10 ? 1 : 0) + ' s';
- else dur = Math.floor(ds / 60) + 'm ' + Math.round(ds % 60) + 's';
- }
- head.innerHTML = `
- <span class="icon ${ok ? 'success' : 'error'}"><svg class="ph" aria-hidden="true"><use href="${ok ? '#ph-check-bold' : '#ph-x-circle-fill'}"/></svg></span>
- <span class="name">${ok ? 'result' : 'error'}</span>
- <span class="summary">${escapeHtml(summary)}</span>
- ${dur ? `<span class="duration">${escapeHtml(dur)}</span>` : ''}
- <span class="chevron">›</span>
- `;
-
- const body = document.createElement('div');
- body.className = 'body';
- const pre = document.createElement('pre');
- try { pre.textContent = JSON.stringify(ok ? inner : result, null, 2); }
- catch(e) { pre.textContent = String(result); }
- body.appendChild(pre);
-
- card.appendChild(head);
- card.appendChild(body);
- head.addEventListener('click', () => card.classList.toggle('open'));
-
- // Error cards auto-expand on render so users don't have to click
- // through every collapsed card hunting for "which submit_shot
- // failed?". Success cards stay collapsed (the head's one-line
- // summary is enough for a quick scan).
- if (!ok) card.classList.add('open');
-
- // Phase B of the director workflow: when the result carries
- // `candidates`, render an interactive thumbnail grid below the head.
- // The card stays expanded by default so the user can immediately pick.
- // Multi-take support: if `takes` is present, render every take stacked
- // (take 1 / take 2 / take N) so the user can choose from any prior batch.
- if (ok && inner) {
- const takes = Array.isArray(inner.takes) && inner.takes.length > 1
- ? inner.takes
- : (Array.isArray(inner.candidates) && inner.candidates.length > 0
- ? [{candidates: inner.candidates, prompt: inner.prompt, take_index: 0}]
- : []);
- if (takes.length > 0) {
- card.classList.add('open'); // open by default
- for (const take of takes) {
- const grid = renderAnchorGrid({
- shot_label: inner.shot_label,
- prompt: take.prompt || inner.prompt,
- engine: inner.engine,
- candidates: take.candidates || [],
- take_index: take.take_index,
- take_count: takes.length,
- });
- card.appendChild(grid);
+ // Apply mode-aware filter FIRST. Hard-filter EVERY row (active OR not)
+ // whose compatible_modes don't intersect the active engine. This is the
+ // tight-integration version the user explicitly asked for — the prior
+ // behavior of "keep mismatched active rows visible with ⚠" was
+ // confusing ("now I see the LoRA, but there is no filtering by selected
+ // model"). Mismatched-active rows aren't deleted from `_activeLoras` —
+ // they're just hidden from this list while the engine is set this way,
+ // so flipping back to a compatible engine restores them. The "+ N from
+ // other modes" pill at the bottom of the banner is the escape hatch
+ // for the rare user who wants to manage a hidden chip without
+ // switching engines first.
+ //
+ // "unknown" compatible_modes still pass every filter — sidecar-less
+ // LoRAs need to be reachable, the picker indicator is the user's cue
+ // that the family wasn't auto-detected.
+ let rows = allRows;
+ let hiddenCount = 0;
+ const showOtherModes = !!window._loraShowOtherModes;
+ if (modeTag) {
+ rows = allRows.filter(r => {
+ const tags = r.compatible_modes || ['unknown'];
+ let matches;
+ if (modeTag === 'image') {
+ // Meta-tag: image-engine UNKNOWN (auto preset). Match any
+ // specific `image:*` tag plus `unknown`. Hides `video` so LTX
+ // LoRAs don't pollute the image picker even when we can't tell
+ // exactly which mflux family the user has saved as default.
+ matches = tags.some(t => t === 'unknown' || (typeof t === 'string' && t.startsWith('image:')));
+ } else {
+ matches = tags.includes(modeTag) || tags.includes('unknown');
}
- }
+ if (!matches && !showOtherModes) hiddenCount++;
+ return matches || showOtherModes;
+ });
}
- return card;
-}
+ // Surface the filter input only when 5+ LoRAs (post-mode-filter)
+ // remain; below that it's just visual noise.
+ if (filterRow) filterRow.style.display = (rows.length >= 5) ? '' : 'none';
-function renderAnchorGrid(payload) {
- const wrap = document.createElement('div');
- wrap.className = 'anchor-grid-wrap';
- const label = payload.shot_label || 'shot';
- const prompt = payload.prompt || '';
- const engine = payload.engine || '';
-
- const selected = window.AGENT.selectedAnchors || {};
- const isPicked = !!((selected[label] || {}).png_path);
- // Multi-take label: when the same shot has multiple takes generated,
- // tag each grid as "Take 1 of 3" so the user knows where the candidates
- // came from and can compare across takes.
- const takeChip = (typeof payload.take_index === 'number'
- && (payload.take_count || 1) > 1)
- ? `<span class="take-pill">Take ${payload.take_index + 1} / ${payload.take_count}</span>`
- : '';
- const meta = document.createElement('div');
- meta.className = 'anchor-grid-meta';
- meta.dataset.shot = label;
- meta.innerHTML = `
- <span class="label-pill">${escapeHtml(label)}</span>
- ${takeChip}
- <span>${payload.candidates.length} candidates · ${escapeHtml(engine)}</span>
- <span style="flex:1"></span>
- <span class="pick-state${isPicked ? ' is-picked' : ''}">${isPicked ? '✓ picked' : 'click to pick'}</span>
- `;
- wrap.appendChild(meta);
-
- if (prompt) {
- const p = document.createElement('div');
- p.className = 'anchor-prompt';
- p.textContent = prompt;
- wrap.appendChild(p);
+ // Then text filter (case-insensitive substring on name + trigger words).
+ const q = (filterInput && filterInput.value || '').trim().toLowerCase();
+ if (q) {
+ rows = rows.filter(r => {
+ if (r.name && r.name.toLowerCase().includes(q)) return true;
+ for (const t of (r.trigger_words || [])) {
+ if (String(t).toLowerCase().includes(q)) return true;
+ }
+ return false;
+ });
}
+ // Sort: active rows first (so the user's selection floats to the top),
+ // then alphabetical by name. Stable enough for a UI list.
+ rows.sort((a, b) => {
+ if (a.active !== b.active) return a.active ? -1 : 1;
+ return (a.name || '').localeCompare(b.name || '');
+ });
- const grid = document.createElement('div');
- grid.className = 'anchor-grid';
-
- const currentPick = (selected[label] || {}).png_path;
-
- for (const cand of payload.candidates) {
- const cell = document.createElement('button');
- cell.type = 'button';
- cell.className = 'anchor-cell' + (cand.png_path === currentPick ? ' selected' : '');
- cell.dataset.shotLabel = label;
- cell.dataset.pngPath = cand.png_path;
-
- const img = document.createElement('img');
- img.src = '/image?path=' + encodeURIComponent(cand.png_path);
- img.alt = label + ' candidate';
- img.loading = 'lazy';
- cell.appendChild(img);
-
- const check = document.createElement('span');
- check.className = 'check';
- check.innerHTML = '<svg class="ph" aria-hidden="true"><use href="#ph-check-bold"/></svg>';
- cell.appendChild(check);
-
- if (typeof cand.seed === 'number' && cand.seed >= 0) {
- const s = document.createElement('span');
- s.className = 'seed';
- s.textContent = 'seed ' + cand.seed;
- cell.appendChild(s);
- }
- if (cand.engine) {
- const e = document.createElement('span');
- e.className = 'engine-tag';
- e.textContent = cand.engine;
- cell.appendChild(e);
+ // Mode banner — explains the active filter so users grok "why don't
+ // I see all my LoRAs". When mismatched LoRAs exist (active OR not),
+ // exposes a "Show N from other modes" toggle so the user has an
+ // escape hatch to manage them without switching engines first.
+ if (banner) {
+ let bannerHtml = `Library filter: <strong>${escapeHtml(_loraFilterLabel(modeTag))}</strong>`;
+ if (hiddenCount > 0) {
+ bannerHtml += ` · <a href="#" style="color:var(--muted)" onclick="event.preventDefault(); window._loraShowOtherModes = true; renderLorasList()">Show ${hiddenCount} from other modes</a>`;
+ } else if (showOtherModes) {
+ bannerHtml += ` · <a href="#" style="color:var(--muted)" onclick="event.preventDefault(); window._loraShowOtherModes = false; renderLorasList()">Hide other modes</a>`;
}
-
- cell.addEventListener('click', () => agentPickAnchor(label, cand, grid));
- grid.appendChild(cell);
- }
-
- wrap.appendChild(grid);
- return wrap;
-}
-
-async function agentPickAnchor(label, cand, gridEl) {
- if (!window.AGENT.sessionId) return;
- // Toggle behavior: clicking the already-selected anchor un-picks it.
- // The backend treats empty png_path as "remove this label's pick".
- const cur = (window.AGENT.selectedAnchors || {})[label];
- const isUnpick = cur && cur.png_path === cand.png_path;
- // Optimistic UI: mark this cell selected, deselect siblings (or clear).
- if (gridEl) {
- gridEl.querySelectorAll('.anchor-cell').forEach(c => c.classList.remove('selected'));
- if (!isUnpick) {
- const me = gridEl.querySelector(`[data-png-path="${CSS.escape(cand.png_path)}"]`);
- if (me) me.classList.add('selected');
+ // Empty image-mode case — when the library has zero compatible
+ // LoRAs, point users at the install path so they don't think the
+ // picker's broken.
+ if (modeTag && modeTag.startsWith('image:') && rows.length === 0 && _knownUserLoras.length > 0) {
+ bannerHtml += ` · <span style="color:var(--muted)">No image LoRAs in your library — install one via the CivitAI browser, filter by Flux / Qwen Image base models.</span>`;
}
- }
- if (isUnpick) {
- delete window.AGENT.selectedAnchors[label];
- } else {
- window.AGENT.selectedAnchors[label] = cand;
+ banner.innerHTML = bannerHtml;
}
- try {
- const r = await fetch(
- '/agent/sessions/' + encodeURIComponent(window.AGENT.sessionId) + '/anchors/select',
- {
- method: 'POST',
- headers: {'Content-Type': 'application/json'},
- body: JSON.stringify({
- shot_label: label,
- png_path: isUnpick ? '' : cand.png_path,
- }),
- }
- );
- const j = await r.json();
- if (!r.ok || j.error) {
- alert('Could not save selection: ' + (j.error || ('HTTP ' + r.status)));
- return;
- }
- window.AGENT.selectedAnchors = j.all_selected || window.AGENT.selectedAnchors;
- } catch (e) {
- console.error('agentPickAnchor', e);
+ // Update header summary.
+ const summary = document.getElementById('lorasSummaryCount');
+ if (summary) {
+ const total = allRows.length;
+ const active = allRows.filter(r => r.active).length;
+ summary.textContent = `${total} installed · ${active} active${q ? ` · ${rows.length} match` : ''}`;
}
- // Also refresh per-grid summary lines on screen.
- document.querySelectorAll('.anchor-grid-meta[data-shot]').forEach(m => {
- const lbl = m.dataset.shot;
- const has = !!((window.AGENT.selectedAnchors || {})[lbl] || {}).png_path;
- const pickEl = m.querySelector('.pick-state');
- if (pickEl) {
- pickEl.textContent = has ? '✓ picked' : 'click to pick';
- pickEl.className = 'pick-state' + (has ? ' is-picked' : '');
- }
- });
- agentRenderBatchBar();
-}
-// Sticky bar above the composer that surfaces "you've picked anchors;
-// click here to queue them all". Drives the user's promised "Ok now batch
-// everything" workflow. Counts picked shots vs already-submitted shots
-// (matched by `label`); shows when picks > submitted.
-function agentRenderBatchBar() {
- const bar = document.getElementById('agentBatchBar');
- const text = document.getElementById('agentBatchBarSummary');
- if (!bar || !text) return;
- const picks = window.AGENT.selectedAnchors || {};
- const pickLabels = Object.keys(picks).filter(k => (picks[k] || {}).png_path);
- // submitted_shots lives on the loaded session; we cache it on AGENT.
- const submitted = (window.AGENT.submittedShots || []);
- const submittedLabels = new Set(submitted.map(s => (s.label || '').trim()).filter(Boolean));
- const pendingLabels = pickLabels.filter(l => !submittedLabels.has(l));
- if (pendingLabels.length === 0 || window.AGENT.busy) {
- bar.hidden = true;
+ if (rows.length === 0) {
+ wrap.innerHTML = `<div class="hint" style="padding:8px 0;">No LoRAs match "${escapeHtml(q)}".</div>`;
return;
}
- const total = pickLabels.length;
-
- // Phase 0 #0.10 — estimated wall total across PENDING picks. Each pick
- // carries its candidate's duration / mode / quality / accel — sum the
- // wall estimate so the user knows what they're committing to before
- // clicking "Queue them". For a 12-shot overnight batch this is the
- // difference between "looks easy" and "that's 2 hours."
- let walls = 0;
- let computed = 0;
- for (const lbl of pendingLabels) {
- const c = picks[lbl] || {};
- const dur = Number(c.duration_seconds);
- if (!(dur > 0)) continue;
- try {
- walls += _agentEstimateWallSeconds({
- duration: dur,
- quality: c.quality || 'balanced',
- accel: c.accel || 'turbo',
- // Picks are i2v in the canonical batch flow (the agent
- // animates a chosen anchor); fallback to t2v if the candidate
- // explicitly carries a non-i2v mode.
- mode: c.mode || 'i2v',
- sharp: (c.sharp !== false),
- });
- computed += 1;
- } catch (e) {}
- }
- const totalEta = (computed > 0) ? ` · ~${_agentFmtDur(walls)} total` : '';
-
- text.textContent = pendingLabels.length === total
- ? `${total} anchor${total === 1 ? '' : 's'} picked · ready to render${totalEta}`
- : `${pendingLabels.length} of ${total} picks not yet queued${totalEta}`;
- bar.hidden = false;
-}
-
-// User clicked "Queue them" — inject a structured message that prompts
-// the agent to submit each picked anchor as i2v, using durations from the
-// plan it already produced. Mirrors how the user would say it themselves
-// ("ok let's batch everything") — we just save them the typing.
-function agentBatchQueue() {
- const input = document.getElementById('agentInput');
- if (!input) return;
- const picks = window.AGENT.selectedAnchors || {};
- const pickLabels = Object.keys(picks).filter(k => (picks[k] || {}).png_path);
- const submitted = (window.AGENT.submittedShots || []);
- const submittedLabels = new Set(submitted.map(s => (s.label || '').trim()).filter(Boolean));
- const pending = pickLabels.filter(l => !submittedLabels.has(l));
- if (pending.length === 0) return;
- const list = pending.map(l => `- ${l}`).join('\n');
- input.value =
- `Queue every picked anchor as an i2v shot now using the durations and prompts from your plan. ` +
- `Use balanced quality + Sharp 720p unless I overrode that earlier. ` +
- `Pending picks:\n${list}\n` +
- `Submit them in plan order, then call finish. Don't ask for confirmation — go.`;
- agentAutoResize(input);
- agentUpdateSendState();
- // Auto-fire — the user clicked the button, so they consented.
- agentSend();
+ wrap.innerHTML = rows.map(r => loraRowHtml(r, modeTag)).join('');
}
-// Phase 0 #0.10 — inline wall-time predictor.
-//
-// Mirror of agent/tools.py::_estimate_wall_seconds. Feeds the
-// submit_shot / estimate_shot call summaries below so users see the
-// expected wall-time AT THE MOMENT THE TOOL CALL LANDS — not after the
-// queue confirms. On a 12-shot overnight batch this lets you see
-// instant feedback per shot and the running rough total without
-// expanding cards.
+// Build a single compact LoRA row. Inactive rows are ~36px tall (just
+// name + meta + corner actions). Active rows expand inline with the
+// strength slider and trigger chips. Click anywhere on the main row to
+// toggle activation.
//
-// Numbers anchor to STATE.md §3 + CLAUDE.md §0; same source of truth as
-// the server. If the table drifts, update both.
-const _AGENT_WALL_BASE_5S = {
- 't2v|quick': 134, 't2v|balanced': 210, 't2v|standard': 460, 't2v|high': 711,
- 'i2v|quick': 150, 'i2v|balanced': 217, 'i2v|standard': 471, 'i2v|high': 750,
- 'keyframe|balanced': 329, 'keyframe|standard': 329, 'keyframe|high': 390,
- 'extend|balanced': 950, 'extend|standard': 950, 'extend|high': 1100,
-};
-function _agentEstimateWallSeconds(opts) {
- const duration = (opts.duration != null) ? Number(opts.duration) : 5;
- const quality = opts.quality || 'balanced';
- const accel = opts.accel || 'turbo';
- const mode = opts.mode || 't2v';
- const sharp = (opts.sharp !== false);
- const key = `${mode}|${quality}`;
- let base = _AGENT_WALL_BASE_5S[key];
- if (base == null) base = _AGENT_WALL_BASE_5S['t2v|standard'];
- if ((mode === 't2v' || mode === 'i2v') && quality === 'standard') {
- if (accel === 'boost') base *= 0.83;
- else if (accel === 'turbo') base *= 0.71;
- }
- if (duration > 0 && duration !== 5) {
- base *= Math.pow(duration / 5.0, 1.5);
- }
- if (sharp && (mode === 't2v' || mode === 'i2v') && (quality === 'balanced' || quality === 'quick')) {
- if (quality !== 'balanced') base += 26;
- }
- return Math.round(base);
-}
-function _agentFmtDur(seconds) {
- const s = Math.round(seconds);
- const h = Math.floor(s / 3600);
- const m = Math.floor((s % 3600) / 60);
- const sec = s % 60;
- if (h) return `${h}h ${String(m).padStart(2,'0')}m`;
- if (m) return `${m}m ${String(sec).padStart(2,'0')}s`;
- return `${sec}s`;
-}
-
-function summarizeToolCall(call) {
- const t = call.tool || '';
- const a = call.args || {};
- if (t === 'submit_shot') {
- // Inline wall predictor — shows ETA BEFORE the queue confirms.
- let eta = '';
- try {
- const sec = _agentEstimateWallSeconds({
- duration: a.duration_seconds || 5,
- quality: a.quality || 'balanced',
- accel: a.accel || 'turbo',
- mode: a.mode || 't2v',
- sharp: (a.sharp !== false),
- });
- eta = ` · ~${_agentFmtDur(sec)}`;
- } catch (e) {}
- return `${a.label || a.preset_label || 'unnamed'} — ${a.duration_seconds || '?'}s ${a.mode || 't2v'} ${a.quality || 'balanced'}${eta}`;
- }
- if (t === 'estimate_shot') {
- let eta = '';
- try {
- const sec = _agentEstimateWallSeconds({
- duration: a.duration_seconds || 5,
- quality: a.quality || 'balanced',
- accel: a.accel || 'turbo',
- mode: a.mode || 't2v',
- sharp: (a.sharp !== false),
- });
- eta = ` · ~${_agentFmtDur(sec)}`;
- } catch (e) {}
- return `${a.duration_seconds || '?'}s ${a.mode || 't2v'} ${a.quality || 'balanced'} ${a.accel || ''}${eta}`;
- }
- if (t === 'extract_frame') {
- return `${a.which || 'last'} of ${(a.job_id || '').slice(0, 12)}…`;
- }
- if (t === 'wait_for_shot') {
- return (a.job_id || '').slice(0, 14) + '…';
- }
- if (t === 'get_queue_status') return 'queue snapshot';
- if (t === 'write_session_manifest') {
- return a.title || 'manifest';
- }
- if (t === 'finish') return a.summary ? a.summary.slice(0, 80) : 'done';
- if (t === 'upload_image') return (a.attachment_id || '').split('/').pop() || '';
- return Object.keys(a).slice(0, 3).join(', ');
-}
-
-function summarizeToolResult(inner) {
- if (typeof inner !== 'object' || inner === null) return String(inner ?? '').slice(0, 100);
- if ('job_id' in inner && 'estimated_wall_human' in inner) {
- return `queued ${inner.job_id} · ETA ${inner.estimated_wall_human}`;
- }
- if ('manifest_path' in inner) {
- return `manifest written · ${inner.shot_count || '?'} shots`;
- }
- if ('estimate_wall_human' in inner) return `ETA ${inner.estimate_wall_human}`;
- if ('png_path' in inner) {
- return `frame ${inner.frame_index} → ${(inner.png_path || '').split('/').pop()}`;
- }
- if ('summary' in inner) return inner.summary.slice(0, 100);
- if ('queue_depth' in inner) {
- return `queue ${inner.queue_depth}, total ${inner.total_estimated_wall_human || '?'}`;
- }
- if ('status' in inner && 'output_path' in inner) {
- return `${inner.status} · ${(inner.output_path || '').split('/').pop() || '-'}`;
- }
- if ('absolute_path' in inner) {
- return (inner.name || inner.absolute_path);
- }
- // Fallback: show top 2 keys
- return Object.entries(inner).slice(0, 2)
- .map(([k, v]) => `${k}=${typeof v === 'object' ? '...' : String(v).slice(0, 40)}`).join(', ');
-}
-
-function renderTypingRow(msg) {
- const row = document.createElement('div');
- row.className = 'agent-typing-row';
- row.id = 'agentTypingRow';
- const av = document.createElement('div');
- av.className = 'agent-avatar claude';
- av.textContent = ''; // CSS ::before paints the Phosphene logo
- const bubble = document.createElement('div');
- bubble.className = 'agent-typing-bubble';
- bubble.innerHTML = `
- <span class="agent-typing-dots">
- <span class="agent-typing-dot"></span>
- <span class="agent-typing-dot"></span>
- <span class="agent-typing-dot"></span>
- </span>
- <span id="agentTypingText">${escapeHtml(msg || 'Thinking')}</span>
- <button type="button" class="agent-typing-abort" id="agentTypingAbort"
- onclick="agentAbortTurn()" title="Stop this turn">
- <svg viewBox="0 0 24 24" width="11" height="11" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round">
- <line x1="18" y1="6" x2="6" y2="18"/>
- <line x1="6" y1="6" x2="18" y2="18"/>
- </svg>
- </button>
- `;
- row.appendChild(av);
- row.appendChild(bubble);
- return row;
-}
-
-// ---- Send -----------------------------------------------------------------
-async function agentSend() {
- if (window.AGENT.busy) return;
- const input = document.getElementById('agentInput');
- const btn = document.getElementById('agentSendBtn');
- const text = (input.value || '').trim();
-
- // Slash commands handled client-side BEFORE engaging the engine.
- // /help opens the capabilities sheet; /notes opens project notes;
- // /queue triggers the batch; /clear starts a new session; etc.
- if (text && text.startsWith('/') &&
- typeof agentMaybeHandleSlashCommand === 'function' &&
- agentMaybeHandleSlashCommand(text)) {
- input.value = '';
- if (typeof agentAutoResize === 'function') agentAutoResize(input);
- if (typeof agentUpdateSendState === 'function') agentUpdateSendState();
- return;
+// modeTag is the active engine compat tag (e.g. "image:qwen") — used to
+// render the per-chip warning when an ACTIVE LoRA doesn't fit the
+// current engine, and a `?` indicator for unclassified LoRAs.
+function loraRowHtml(r, modeTag) {
+ const pathHtml = escapeHtml(r.path);
+ const pathAttr = JSON.stringify(r.path).replace(/"/g, '&quot;');
+ const nameHtml = escapeHtml(r.name);
+ const nameAttr = JSON.stringify(r.name).replace(/"/g, '&quot;');
+ // Per-row family badges. `?` for unknown family (unclassified
+ // base_model), `⚠` for an ACTIVE LoRA whose compat tags don't match
+ // the current engine — clear visible signal that "this chip stays
+ // selected but won't actually fire on the engine you've chosen".
+ const tags = r.compatible_modes || ['unknown'];
+ const isUnknown = tags.length === 1 && tags[0] === 'unknown';
+ const familyMismatch = !!(modeTag && r.active
+ && !tags.includes(modeTag) && !tags.includes('unknown'));
+ const familyBadges = [];
+ if (isUnknown) {
+ familyBadges.push(`<span class="badge" title="Unknown LoRA family — sidecar didn't list a base_model. May or may not fire on this engine.">?</span>`);
}
-
- // Wait for any in-flight uploads so the message arrives WITH its
- // attachments. UX: don't block the user — if uploads error we surface
- // them in the chip row and the user can remove/retry.
- const stillUploading = (window.AGENT.pendingAttachments || []).some(a => a.status === 'uploading');
- if (stillUploading) {
- btn.disabled = true;
- let waited = 0;
- while ((window.AGENT.pendingAttachments || []).some(a => a.status === 'uploading')) {
- await new Promise(r => setTimeout(r, 120));
- waited += 120;
- if (waited > 60000) break; // 60 s safety bail
- }
+ if (familyMismatch) {
+ familyBadges.push(`<span class="badge" style="background:rgba(232,179,65,0.15);color:var(--warn,#e8b341)" title="This LoRA was trained for a different family (${tags.join(', ')}) — it will be passed to mflux but probably won't influence the output. Switch the Engine dropdown to a matching family, or remove this LoRA."><svg class="ph" aria-hidden="true"><use href="#ph-warning-fill"/></svg></span>`);
}
- const ready = agentReadyAttachments();
- if (!text && !ready.length) return;
-
- if (!window.AGENT.sessionId) {
- const sess = await agentNewSession(text || ready[0].name);
- if (!sess) return;
+ // Trigger summary line under the name (when not expanded). Truncated.
+ const trigs = r.trigger_words || [];
+ const trigSummary = trigs.length
+ ? trigs.slice(0, 4).join(' · ') + (trigs.length > 4 ? ` +${trigs.length - 4}` : '')
+ : 'no trigger word';
+ // Corner actions — link to civitai page + delete (or remove for HF/remote).
+ const corner = [];
+ if (r.civitai_url) {
+ corner.push(`<a class="lora-icon-btn" href="${escapeHtml(r.civitai_url)}" target="_blank" rel="noopener" title="Open on CivitAI" onclick="event.stopPropagation()"><svg class="ph" aria-hidden="true"><use href="#ph-arrow-square-out"/></svg></a>`);
}
-
- // If a Refine reference is set, prepend "Refine <jobid> (<label>): " to
- // the user's message so the agent picks it up as a variation request.
- // Clear the chip after so the next message is a normal one.
- let outgoing = text;
- if (window.AGENT_REFINE) {
- const r = window.AGENT_REFINE;
- const ref = r.jobId || r.clipPath;
- const lbl = r.label ? ` (${r.label})` : '';
- outgoing = `Refine ${ref}${lbl}: ${text}`;
- agentClearRefine();
+ if (r.kind === 'user' || r.kind === 'trained') {
+ corner.push(`<button class="lora-icon-btn danger" type="button" title="Delete from disk"
+ onclick="event.stopPropagation(); deleteLora(${pathAttr}, ${nameAttr})"><svg class="ph" aria-hidden="true"><use href="#ph-x-bold"/></svg></button>`);
+ } else {
+ corner.push(`<button class="lora-icon-btn" type="button" title="Remove from active set"
+ onclick="event.stopPropagation(); removeLoraFromActive(${pathAttr})"><svg class="ph" aria-hidden="true"><use href="#ph-x-bold"/></svg></button>`);
}
+ // Trigger chips for the expanded section. Same click-to-append behavior
+ // as before — chips prepend the trigger to the prompt textarea.
+ const chipsHtml = trigs.length
+ ? trigs.slice(0, 12).map(w => {
+ const wAttr = JSON.stringify(w).replace(/"/g, '&quot;');
+ return `<span class="trigger-chip" title="Click to add to prompt"
+ onclick="event.stopPropagation(); appendTriggerToPrompt(${wAttr})">${escapeHtml(w)}</span>`;
+ }).join('')
+ : `<span class="trigger-chip empty">style-only LoRA — no trigger word needed</span>`;
- const chat = document.getElementById('agentChat');
- // Clear empty-state if present, then append user bubble + typing
- const empty = chat.querySelector('.agent-empty');
- if (empty) empty.remove();
- chat.appendChild(renderMessage({
- kind: 'user',
- content: outgoing,
- attachments: ready.map(a => ({path: a.path, name: a.name, mime: a.mime, size: a.size})),
- }));
- chat.appendChild(renderTypingRow('Thinking'));
- // User just hit Send — explicit action, force-scroll to bottom.
- agentScrollChatToBottom();
-
- input.value = '';
- agentAutoResize(input);
- // Snapshot then clear before send — if the round-trip succeeds we don't
- // want stale chips. If it fails the user can re-attach.
- const sentAttachments = ready.map(a => ({path: a.path, name: a.name, mime: a.mime, size: a.size}));
- agentClearAttachments();
- agentUpdateSendState();
- window.AGENT.busy = true;
- btn.disabled = true;
+ return `
+ <div class="lora-row ${r.active ? 'active' : ''}" data-path="${pathHtml}">
+ <div class="lora-row-main"
+ onclick="toggleLora(${pathAttr}, ${!r.active}, ${r.recommended_strength}, ${nameAttr})">
+ <div class="lora-toggle-dot"></div>
+ <div class="lora-text">
+ <div class="lora-name" title="${pathHtml}">
+ ${nameHtml}${r.kind === 'remote' ? '<span class="badge">HF</span>' : ''}${r.kind === 'trained' ? '<span class="badge badge-trained" title="Trained in Phosphene’s Train Character workflow">Trained</span>' : ''}${familyBadges.join('')}
+ </div>
+ <div class="lora-name-meta" title="${escapeHtml(trigs.join(', '))}">${escapeHtml(trigSummary)}</div>
+ </div>
+ <div class="lora-row-actions">${corner.join('')}</div>
+ </div>
+ <div class="lora-row-extra">
+ <div class="lora-strength-row">
+ <label>strength</label>
+ <input type="range" min="-2" max="2" step="0.05" value="${r.strength}"
+ onclick="event.stopPropagation()"
+ oninput="this.nextElementSibling.value = this.value; setLoraStrength(${pathAttr}, this.value)">
+ <input type="number" min="-2" max="2" step="0.05" value="${r.strength}"
+ onclick="event.stopPropagation()"
+ oninput="this.previousElementSibling.value = this.value; setLoraStrength(${pathAttr}, this.value)">
+ </div>
+ <div class="trigger-chips">${chipsHtml}</div>
+ </div>
+ </div>`;
+}
- // Streaming-feel: while the message round-trip is in flight (which can
- // take minutes when the agent makes many tool calls on a local model),
- // poll the server-side session every 2 s and re-render as new messages
- // land. The typing indicator stays visible until the round-trip
- // completes (since `busy` doesn't flip until then).
- const sid = window.AGENT.sessionId;
- // Track when we started the current LLM "thinking" wait so the typing
- // indicator can surface "Thinking · 18s" rather than a static phrase
- // during long Qwen 35B inferences. Reset every time a new message lands.
- let lastMsgLen = 0;
- let waitingSince = Date.now();
- let poller = setInterval(async () => {
- if (!window.AGENT.busy) return;
+function toggleLora(path, on, recommended, name) {
+ if (on) {
+ addLoraToActive({ path, strength: recommended, name });
+ // Auto-insert the LoRA's first trigger word into the prompt so the
+ // user doesn't have to remember + retype it. The biggest source of
+ // "I activated the LoRA but it didn't fire" reports is the trigger
+ // missing from the prompt entirely. appendTriggerToPrompt is
+ // idempotent — duplicate clicks are no-ops. Skips silently if the
+ // LoRA has no trigger_words (style-only LoRAs).
try {
- const sr = await fetch('/agent/sessions/' + encodeURIComponent(sid));
- if (!sr.ok) return;
- const sj = await sr.json();
- const msgs = sj.rendered_messages || [];
- const cur = chat.querySelectorAll('.agent-msg-row, .agent-tool-card').length;
- if (msgs.length > cur) {
- // Re-render only when the message count actually grew — avoids
- // flickery rebuilds during lulls.
- const typingTextEl = document.getElementById('agentTypingText');
- const phase = typingTextEl ? typingTextEl.textContent : 'Working';
- agentRender(msgs);
- chat.appendChild(renderTypingRow(_phaseFor(msgs, phase, 0)));
- // Async content (poller) — only auto-scroll if user is following.
- agentChatScrollIfPinned(chat);
- lastMsgLen = msgs.length;
- waitingSince = Date.now();
- } else {
- // No growth — still refresh the typing label so the user sees
- // "Thinking · 12s" instead of a frozen "Drafting plan". Rewriting
- // just the text node avoids re-rendering the whole chat.
- const typingTextEl = document.getElementById('agentTypingText');
- if (typingTextEl) {
- const elapsed = Math.round((Date.now() - waitingSince) / 1000);
- typingTextEl.textContent = _phaseFor(msgs, 'Thinking', elapsed);
- }
- }
- } catch(e) {}
- }, 1500);
-
- // AbortController so the user can cancel a runaway turn from the
- // typing-row × button. Cancels the in-flight fetch + clears the poller.
- // The server-side run_turn keeps going until it exits (no kill-switch
- // in the runtime today), but the user is unstuck immediately and the
- // state will reconcile on the next session load.
- window.AGENT.abortController = new AbortController();
-
- try {
- const r = await fetch(
- '/agent/sessions/' + encodeURIComponent(sid) + '/message',
- {
- method: 'POST',
- headers: {'Content-Type': 'application/json'},
- body: JSON.stringify({message: outgoing, attachments: sentAttachments}),
- signal: window.AGENT.abortController.signal,
- }
- );
- const j = await r.json();
- if (!r.ok || j.error) {
- const typing = document.getElementById('agentTypingRow');
- if (typing) {
- typing.querySelector('.agent-typing-bubble').innerHTML =
- `<span style="color:#f49a9e"><svg class="ph" aria-hidden="true" style="margin-right:4px;vertical-align:-2px"><use href="#ph-warning-fill"/></svg>Error: ${escapeHtml(j.error || ('HTTP ' + r.status))}</span>`;
+ const meta = _knownUserLoras.find(u => u.path === path);
+ const triggers = (meta && meta.trigger_words) || [];
+ if (triggers.length) {
+ appendTriggerToPrompt(triggers[0]);
}
- } else {
- agentRender(j.rendered_messages || []);
- }
- } catch (e) {
- const typing = document.getElementById('agentTypingRow');
- if (typing) {
- typing.querySelector('.agent-typing-bubble').innerHTML =
- `<span style="color:#f49a9e"><svg class="ph" aria-hidden="true" style="margin-right:4px;vertical-align:-2px"><use href="#ph-warning-fill"/></svg>Network error: ${escapeHtml(String(e))}</span>`;
- }
- } finally {
- clearInterval(poller);
- window.AGENT.busy = false;
- btn.disabled = false;
- // The auto-start backend logic may have just spawned the local
- // engine — the engine pill in the header was 'click to start'
- // when the user hit Send. Now it should read 'live'. Refresh
- // the config view so the pill catches up.
- agentRefreshConfig();
- requestAnimationFrame(() => agentChatScrollIfPinned(chat));
- }
-}
-
-// Stop the current turn — clicked from the × on the typing row.
-// Aborts the in-flight fetch (the catch block in agentSend treats the
-// AbortError as a network error and surfaces it). The server-side
-// run_turn loop is NOT killed (no kill-switch in the runtime today);
-// it'll continue until it finishes and the next session-load will pull
-// the final state. This is purely a "unstick the UI" affordance.
-function agentAbortTurn() {
- if (window.AGENT && window.AGENT.abortController) {
- try { window.AGENT.abortController.abort(); } catch(e) {}
- }
- const typing = document.getElementById('agentTypingRow');
- if (typing) {
- typing.querySelector('.agent-typing-bubble').innerHTML =
- '<span style="color:var(--muted)">Aborted — server may still be finishing the current turn.</span>';
+ } catch (e) { /* picker race during boot — ignore */ }
+ } else {
+ removeLoraFromActive(path);
}
}
-// Pick a contextual typing-indicator phrase based on what just happened.
-// `elapsedSec` is how long we've been waiting since the last message landed
-// — surface it once the wait runs long enough that a frozen label feels
-// stuck (Qwen 35B easily takes 30s for a complex turn).
-function _phaseFor(messages, fallback, elapsedSec) {
- const tail = (s) => (elapsedSec && elapsedSec >= 6) ? `${s} · ${elapsedSec}s` : s;
- if (!messages || messages.length === 0) return tail(fallback || 'Thinking');
- const last = messages[messages.length - 1];
- if (last.kind === 'user') {
- // We just sent the user's message; the model is composing its reply.
- return tail('Thinking');
- }
- if (last.kind === 'tool_result') {
- const r = last.result || {};
- const inner = r.result || {};
- if (typeof inner === 'object' && inner && 'job_id' in inner) {
- return tail(`Queued ${String(inner.job_id || '').slice(-3) || ''}, planning next`);
- }
- return tail('Reading result, drafting next step');
+// Append a LoRA's trigger word to the prompt textarea. Most LTX LoRAs
+// only fully activate when their trigger word is somewhere in the prompt,
+// and asking users to remember + type a string like "DISPSTYLE" exactly
+// is friction. Click the chip → it goes in. Idempotent: if the word is
+// already present (case-insensitive substring), do nothing so users can
+// click freely without piling duplicates.
+function appendTriggerToPrompt(word) {
+ const ta = document.getElementById('prompt');
+ if (!ta) return;
+ const cur = ta.value || '';
+ if (cur.toLowerCase().includes(String(word).toLowerCase())) {
+ // Brief visual ping so the click feels acknowledged even though we
+ // didn't change anything — otherwise users repeat-click thinking
+ // it's broken.
+ ta.classList.add('flash-ok');
+ setTimeout(() => ta.classList.remove('flash-ok'), 250);
+ return;
}
- if (last.kind === 'assistant') {
- if (last.tool_call) return tail(`Calling ${last.tool_call.tool}`);
- return tail('Drafting next step');
+ // If the user has typed nothing, drop the trigger in alone. Otherwise
+ // prepend to the existing prompt: many LoRA authors put the trigger
+ // FIRST in their examples, and quality often degrades when the trigger
+ // is buried at the end past 20+ tokens of unrelated context.
+ if (cur.trim() === '') {
+ ta.value = String(word);
+ } else {
+ ta.value = String(word) + ', ' + cur;
}
- return tail(fallback || 'Working');
-}
-
-// ---- Composer plumbing ----------------------------------------------------
-function agentAutoResize(ta) {
- if (!ta) return;
- ta.style.height = 'auto';
- ta.style.height = Math.min(220, Math.max(48, ta.scrollHeight)) + 'px';
-}
-
-function agentUpdateSendState() {
- const input = document.getElementById('agentInput');
- const btn = document.getElementById('agentSendBtn');
- if (!input || !btn) return;
- // Allow send when there's text OR at least one ready attachment — the
- // agent can act on attachments alone (e.g. "use this image as the lead").
- const hasText = !!input.value.trim();
- const hasAttach = (window.AGENT.pendingAttachments || []).some(a => a.path);
- btn.disabled = (!hasText && !hasAttach) || window.AGENT.busy;
-}
-
-// ---- Attachments ----------------------------------------------------------
-// `pendingAttachments` is the staged list before send. Each entry:
-// { id, name, size, mime, path, status: 'uploading'|'ready'|'error', error }
-// `path` is filled in once /upload returns. Send is allowed when at least
-// one attachment is `ready` (or there is text).
-window.AGENT.pendingAttachments = window.AGENT.pendingAttachments || [];
-
-const AGENT_ATTACH_KIND = (mime, name) => {
- const m = (mime || '').toLowerCase();
- const n = (name || '').toLowerCase();
- if (m.startsWith('image/')) return 'image';
- if (m === 'application/pdf' || n.endsWith('.pdf')) return 'pdf';
- if (m.startsWith('text/') || n.endsWith('.md') || n.endsWith('.txt')) return 'text';
- return 'file';
-};
-
-const AGENT_ATTACH_MAX_BYTES = 64 * 1024 * 1024; // mirrors backend cap
-
-function agentFmtBytes(n) {
- if (!n && n !== 0) return '';
- if (n < 1024) return n + ' B';
- if (n < 1024*1024) return (n/1024).toFixed(0) + ' KB';
- return (n/(1024*1024)).toFixed(1) + ' MB';
-}
-
-function agentAttachIcon(kind) {
- // Returns inline SVG markup (Phosphor) for attachment-chip thumbs.
- // Callers should use .innerHTML, not .textContent.
- const id = (kind === 'image') ? 'ph-image'
- : (kind === 'pdf') ? 'ph-file-pdf'
- : (kind === 'text') ? 'ph-file-text'
- : 'ph-paperclip';
- return '<svg class="ph" aria-hidden="true"><use href="#' + id + '"/></svg>';
+ ta.focus();
+ ta.dispatchEvent(new Event('input', { bubbles: true }));
}
-function agentRenderAttachRow() {
- const row = document.getElementById('agentAttachRow');
- const btn = document.getElementById('agentAttachBtn');
- const cnt = document.getElementById('agentAttachCount');
- if (!row) return;
- const list = window.AGENT.pendingAttachments;
- if (btn) btn.classList.toggle('has-attach', list.length > 0);
- if (cnt) cnt.textContent = String(list.length);
- if (!list.length) { row.style.display = 'none'; row.innerHTML = ''; return; }
- row.style.display = 'flex';
- row.innerHTML = '';
- for (const a of list) {
- const chip = document.createElement('div');
- chip.className = 'agent-attach-chip';
- if (a.status === 'uploading') chip.classList.add('pending');
- if (a.status === 'error') chip.classList.add('error');
- const kind = AGENT_ATTACH_KIND(a.mime, a.name);
- const thumb = document.createElement(kind === 'image' && a.path ? 'img' : 'div');
- thumb.className = 'thumb';
- if (kind === 'image' && a.path) {
- thumb.src = '/image?path=' + encodeURIComponent(a.path);
- thumb.alt = a.name;
- } else {
- thumb.innerHTML = agentAttachIcon(kind);
- }
- const name = document.createElement('span');
- name.className = 'name';
- name.title = a.name;
- name.textContent = a.name;
- const meta = document.createElement('span');
- meta.className = 'meta';
- meta.textContent = a.status === 'uploading' ? 'uploading…'
- : a.status === 'error' ? (a.error || 'failed')
- : agentFmtBytes(a.size);
- const x = document.createElement('button');
- x.type = 'button';
- x.className = 'remove';
- x.title = 'Remove';
- x.innerHTML = '<svg class="ph" aria-hidden="true"><use href="#ph-x-bold"/></svg>';
- x.addEventListener('click', () => agentRemoveAttachment(a.id));
- chip.appendChild(thumb); chip.appendChild(name); chip.appendChild(meta); chip.appendChild(x);
- row.appendChild(chip);
+async function deleteLora(path, name) {
+ if (!confirm(`Delete the LoRA file for "${name}" from disk? This is permanent.`)) {
+ return;
}
-}
-
-function agentRemoveAttachment(id) {
- window.AGENT.pendingAttachments =
- window.AGENT.pendingAttachments.filter(a => a.id !== id);
- agentRenderAttachRow();
- agentUpdateSendState();
-}
-
-function agentClearAttachments() {
- window.AGENT.pendingAttachments = [];
- agentRenderAttachRow();
- agentUpdateSendState();
-}
-
-async function agentUploadFile(att) {
- // POST one file to /upload. The backend already exists for the legacy
- // gallery picker; we reuse it. Returns { ok, path } on success.
const fd = new FormData();
- fd.append('image', att._file, att.name);
+ fd.set('path', path);
try {
- const r = await fetch('/upload', { method: 'POST', body: fd });
- const j = await r.json();
- if (!r.ok || j.error) throw new Error(j.error || ('HTTP ' + r.status));
- att.path = j.path;
- att.status = 'ready';
+ const r = await fetch('/loras/delete', {
+ method: 'POST',
+ headers: {'Content-Type': 'application/x-www-form-urlencoded'},
+ body: new URLSearchParams(fd),
+ });
+ const data = await r.json();
+ if (!r.ok || !data.ok) {
+ alert('Delete failed: ' + (data.error || `HTTP ${r.status}`));
+ return;
+ }
+ removeLoraFromActive(path);
+ refreshLoras();
} catch (e) {
- att.status = 'error';
- att.error = String(e.message || e);
- } finally {
- delete att._file; // free the File reference
- agentRenderAttachRow();
- agentUpdateSendState();
- }
-}
-
-function agentAddFiles(fileList) {
- if (!fileList || !fileList.length) return;
- for (const f of Array.from(fileList)) {
- if (f.size > AGENT_ATTACH_MAX_BYTES) {
- alert(`"${f.name}" is too large (max ${(AGENT_ATTACH_MAX_BYTES/1024/1024).toFixed(0)} MB)`);
- continue;
- }
- const att = {
- id: 'att_' + Math.random().toString(36).slice(2, 10),
- name: f.name,
- size: f.size,
- mime: f.type || '',
- path: '',
- status: 'uploading',
- _file: f,
- };
- window.AGENT.pendingAttachments.push(att);
- agentUploadFile(att); // fires async; UI updates on settle
+ alert('Delete failed: ' + (e.message || e));
}
- agentRenderAttachRow();
- agentUpdateSendState();
-}
-
-function agentOnFilesPicked(ev) {
- agentAddFiles(ev.target.files);
- ev.target.value = ''; // allow picking the same file again
}
-function agentReadyAttachments() {
- return (window.AGENT.pendingAttachments || []).filter(a => a.status === 'ready' && a.path);
-}
+// ====== CivitAI modal ======
-// ---- Drag-drop on the chat surface ---------------------------------------
-function agentInstallDragDrop() {
- const pane = document.getElementById('agentPane');
- const overlay = document.getElementById('agentDropOverlay');
- if (!pane || !overlay) return;
- let dragDepth = 0;
- pane.addEventListener('dragenter', e => {
- if (!e.dataTransfer || !Array.from(e.dataTransfer.types || []).includes('Files')) return;
- e.preventDefault();
- dragDepth += 1;
- overlay.classList.add('visible');
- });
- pane.addEventListener('dragover', e => {
- if (!e.dataTransfer || !Array.from(e.dataTransfer.types || []).includes('Files')) return;
- e.preventDefault();
- e.dataTransfer.dropEffect = 'copy';
- });
- pane.addEventListener('dragleave', () => {
- dragDepth = Math.max(0, dragDepth - 1);
- if (dragDepth === 0) overlay.classList.remove('visible');
- });
- pane.addEventListener('drop', e => {
- if (!e.dataTransfer || !e.dataTransfer.files || !e.dataTransfer.files.length) return;
- e.preventDefault();
- dragDepth = 0;
- overlay.classList.remove('visible');
- agentAddFiles(e.dataTransfer.files);
- });
-}
+let _civitaiCursor = '';
+let _civitaiSearching = false;
-// ---- Paste-from-clipboard on the textarea --------------------------------
-function agentInstallPasteHandler() {
- const ta = document.getElementById('agentInput');
- if (!ta) return;
- ta.addEventListener('paste', e => {
- if (!e.clipboardData) return;
- const items = e.clipboardData.items || [];
- const files = [];
- for (const it of Array.from(items)) {
- if (it.kind === 'file') {
- const f = it.getAsFile();
- if (f) files.push(f);
- }
- }
- if (files.length) {
- e.preventDefault();
- agentAddFiles(files);
- }
- });
+function openCivitaiModal() {
+ document.getElementById('civitaiModal').style.display = 'flex';
+ // Pull /loras to populate the dir text and the auth-banner state.
+ fetch('/loras').then(r => r.json()).then(d => {
+ const dirEl = document.getElementById('civitaiTargetDir');
+ if (dirEl && d.loras_dir) dirEl.textContent = d.loras_dir;
+ renderCivitaiAuthBanner(!!d.civitai_auth);
+ }).catch(() => { renderCivitaiAuthBanner(false); });
+ document.getElementById('civitaiQuery').value = '';
+ _civitaiCursor = '';
+ // Pull current Spicy mode state so the "Show NSFW" toggle hides when off.
+ refreshCivitaiAccessUI();
+ civitaiSearch();
}
-document.addEventListener('DOMContentLoaded', () => {
- const ta = document.getElementById('agentInput');
- if (ta) {
- ta.addEventListener('input', () => {
- agentAutoResize(ta);
- agentUpdateSendState();
- });
- ta.addEventListener('keydown', e => {
- if ((e.metaKey || e.ctrlKey) && e.key === 'Enter') {
- e.preventDefault();
- agentSend();
- }
- });
- agentAutoResize(ta);
- agentUpdateSendState();
- }
- agentInstallDragDrop();
- agentInstallPasteHandler();
-});
-
-// ---- Engine settings drawer -----------------------------------------------
-async function agentRefreshImageConfig() {
+// Hide / show the "Show NSFW" toggle in the CivitAI browser based on the
+// Spicy mode setting. Called on modal open and after toggleSpicyMode flips
+// the value, so the UI tracks the gate without a page reload.
+async function refreshCivitaiAccessUI() {
+ let spicy = false;
try {
- const r = await fetch('/agent/image/config');
+ const r = await fetch('/settings');
const j = await r.json();
- window.AGENT.imageConfig = j;
- return j;
- } catch (e) {
- return null;
- }
+ spicy = !!(j && j.settings && j.settings.spicy_mode);
+ } catch (_) { /* default off */ }
+ const pill = document.getElementById('civitaiNsfwPill');
+ const cb = document.getElementById('civitaiNsfw');
+ if (pill) pill.style.display = spicy ? '' : 'none';
+ if (!spicy && cb) cb.checked = false; // force off when spicy mode is off
}
-function openAgentSettings() {
- Promise.all([agentRefreshConfig(), agentRefreshImageConfig()]).then(() => {
- const modal = document.getElementById('agentSettingsModal');
- if (!modal) return;
- const cfg = (window.AGENT.config && window.AGENT.config.engine) || {};
- const local = (window.AGENT.config && window.AGENT.config.local_server) || {};
- const imgCfg = (window.AGENT.imageConfig && window.AGENT.imageConfig.image_engine) || {};
- document.getElementById('agentKind').value = cfg.kind || 'phosphene_local';
- document.getElementById('agentBaseUrl').value = cfg.base_url || '';
- document.getElementById('agentRemoteModel').value = cfg.kind === 'custom' ? (cfg.model || '') : '';
- if ((cfg.kind || 'phosphene_local') === 'ollama') agentOllamaRefresh();
- document.getElementById('agentApiKey').value = '';
- document.getElementById('agentApiKey').placeholder =
- cfg.has_api_key ? '(saved key — leave blank to keep)' : 'Paste API key';
- // Anthropic: pick the curated dropdown if cfg.model matches, else fall
- // through to the custom-id input so power users can pick e.g. a
- // dated alias Anthropic shipped after this UI was last edited.
- const anthropicModels = ['claude-sonnet-4-5', 'claude-opus-4-5', 'claude-haiku-4-5'];
- if (cfg.kind === 'anthropic') {
- if (anthropicModels.includes(cfg.model || '')) {
- document.getElementById('agentAnthropicModel').value = cfg.model;
- document.getElementById('agentAnthropicCustomModel').value = '';
- document.getElementById('agentAnthropicCustomModel').style.display = 'none';
- } else {
- document.getElementById('agentAnthropicModel').value = '__custom__';
- document.getElementById('agentAnthropicCustomModel').value = cfg.model || '';
- document.getElementById('agentAnthropicCustomModel').style.display = '';
- }
- } else {
- document.getElementById('agentAnthropicModel').value = 'claude-sonnet-4-5';
- document.getElementById('agentAnthropicCustomModel').value = '';
- document.getElementById('agentAnthropicCustomModel').style.display = 'none';
- }
- document.getElementById('agentTemp').value = cfg.temperature ?? 0.4;
- document.getElementById('agentMaxTokens').value = cfg.max_tokens ?? 8192;
-
- // Image-engine fields
- document.getElementById('agentImageKind').value = imgCfg.kind || 'mock';
- // mflux. The dropdown now includes named shorthands (krea-dev, dev,
- // schnell) AND HF repo ids (Runpod/FLUX.2-klein-4B-mflux-4bit,
- // filipstrand/Z-Image-Turbo-mflux-4bit). To know which path to take
- // (built-in option vs __custom__), we check if the saved value is
- // present as a real <option> in the select rather than maintaining
- // a parallel list.
- const mfSelect = document.getElementById('agentMfluxModel');
- const mfModel = imgCfg.mflux_model || 'Runpod/FLUX.2-klein-4B-mflux-4bit';
- const mfHasOption = Array.from(mfSelect.options || []).some(o => o.value === mfModel);
- if (mfHasOption) {
- mfSelect.value = mfModel;
- document.getElementById('agentMfluxCustomPath').value = '';
- } else {
- mfSelect.value = '__custom__';
- document.getElementById('agentMfluxCustomPath').value = mfModel;
- }
- document.getElementById('agentMfluxBaseModel').value = imgCfg.mflux_base_model || 'flux2-klein-4b';
- // Steps: 0 means "use family default". Fill in the right per-family
- // value for display so the user sees what will actually be used,
- // mirroring agent/image_engine.py MFLUX_FAMILY_DEFAULTS.
- // Family-default step count when the user hasn't explicitly set one.
- // Must mirror agent/image_engine.py:MFLUX_FAMILY_DEFAULTS — flagged at
- // the source. Out-of-sync defaults are how Settings was showing 25/30
- // for qwen_edit when image_engine was already running 8.
- let stepsForDisplay = imgCfg.mflux_steps;
- if (!stepsForDisplay) {
- if (/qwen-image-edit|qwen_image_edit|qwen-edit/i.test(mfModel)) stepsForDisplay = 8;
- else if (/flux\.?2|flux2-klein/i.test(mfModel)) stepsForDisplay = 4;
- else if (/z-image-turbo|z_image_turbo/i.test(mfModel)) stepsForDisplay = 9;
- else if (/schnell/i.test(mfModel)) stepsForDisplay = 4;
- else if (/fibo/i.test(mfModel)) stepsForDisplay = 30;
- else if (/qwen/i.test(mfModel)) stepsForDisplay = 30; // plain Qwen-Image (T2I)
- else stepsForDisplay = 25; // flux1-dev/krea, z-image base
- }
- document.getElementById('agentMfluxSteps').value = stepsForDisplay;
- document.getElementById('agentMfluxQuantize').value = String(imgCfg.mflux_quantize || 6);
- // BFL
- document.getElementById('agentBflModel').value = imgCfg.bfl_model || 'flux-dev';
- document.getElementById('agentBflKey').value = '';
- document.getElementById('agentBflKey').placeholder =
- imgCfg.has_bfl_api_key ? '(saved key — leave blank to keep)' : 'Paste BFL API key';
- const imgPill = document.getElementById('agentImagePill');
- if (imgPill) {
- const okMsg = window.AGENT.imageConfig || {};
- imgPill.textContent = okMsg.ok === false ? 'needs config' : (imgCfg.kind || 'mock');
- imgPill.style.color = okMsg.ok === false ? '#f49a9e' : '#9be7a4';
- imgPill.style.borderColor = okMsg.ok === false ? 'rgba(207,34,46,0.5)' : 'rgba(46,160,67,0.5)';
- imgPill.title = okMsg.message || '';
- }
- agentImageKindChanged();
-
- const sel = document.getElementById('agentLocalModel');
- sel.innerHTML = '';
- const models = (window.AGENT.config && window.AGENT.config.available_models) || [];
- // Compute current RAM headroom so we can flag models that won't
- // fit. Auto-spawn already refuses to start when system is in
- // swap, but the picker was happy to let users select e.g. a
- // 22 GB model on a Mac with 6 GB free. Now those entries are
- // visibly tagged "won't fit" so the user picks a smaller one.
- let freeGb = 0;
- try {
- const m = (window.AGENT.lastStatus && window.AGENT.lastStatus.memory) || {};
- freeGb = Math.max(0, (Number(m.total_gb) || 0) - (Number(m.used_gb) || 0));
- } catch (e) {}
- if (models.length === 0) {
- const opt = document.createElement('option');
- opt.value = '';
- opt.textContent = 'No chat-capable models found in mlx_models/';
- sel.appendChild(opt);
- } else {
- for (const m of models) {
- const opt = document.createElement('option');
- opt.value = m.path;
- // 2 GB safety margin — the renderer needs some headroom too.
- const wontFit = freeGb > 0 && Number(m.size_gb) > 0 && m.size_gb + 2 > freeGb;
- opt.textContent = wontFit
- ? `${m.name} · ${m.size_gb} GB · won't fit (${freeGb.toFixed(0)} GB free)`
- : `${m.name} · ${m.size_gb} GB`;
- if (wontFit) {
- opt.disabled = true;
- opt.title = `Needs ~${m.size_gb} GB; only ${freeGb.toFixed(1)} GB free. Close apps or pick a smaller model.`;
- }
- if ((cfg.local_model_path || '') === m.path) opt.selected = true;
- sel.appendChild(opt);
- }
- }
- agentKindChanged();
- agentLocalRefreshRow(local);
- modal.classList.add('open');
+// Render the inline API-key banner at the top of the CivitAI browser.
+// Three states: set (✓ small green), missing (amber, prompts for key),
+// editing (input visible while user is changing/setting the key). The
+// banner is the primary surface for the key now — Settings still has
+// the field but most users won't need to dig there.
+function renderCivitaiAuthBanner(haveKey, mode) {
+ const box = document.getElementById('civitaiAuthBanner');
+ if (!box) return;
+ // Three visual modes: 'view' (default), 'edit' (showing input), 'err' (last save failed).
+ const m = mode || (haveKey ? 'view' : 'edit');
+ box.style.display = '';
+ box.classList.remove('missing','set','err');
+ if (m === 'view' && haveKey) {
+ box.classList.add('set');
+ box.innerHTML = `
+ <span><svg class="ph" aria-hidden="true" style="color:var(--success,#3fb950);margin-right:4px;vertical-align:-2px"><use href="#ph-check-bold"/></svg><strong style="color:var(--success,#3fb950)"></strong> CivitAI API key set —
+ LoRA downloads will work.</span>
+ <span class="grow"></span>
+ <a class="changekey" onclick="renderCivitaiAuthBanner(true,'edit')">change key</a>`;
+ return;
+ }
+ // edit / missing mode — render input + Save.
+ box.classList.add(m === 'err' ? 'err' : 'missing');
+ const intro = m === 'err'
+ ? `<strong>That key didn't work.</strong> Double-check it from <a href="https://civitai.com/user/account" target="_blank" rel="noopener">civitai.com/user/account</a> and try again.`
+ : haveKey
+ ? `Replace your CivitAI API key. The current one stays active until you save a new one.`
+ : `<strong>CivitAI requires an API key</strong> to download LoRAs. Get one at <a href="https://civitai.com/user/account" target="_blank" rel="noopener">civitai.com/user/account</a> and paste it here:`;
+ box.innerHTML = `
+ <div class="grow" style="flex-basis:100%; margin-bottom:6px;">${intro}</div>
+ <input type="password" id="civitaiAuthInput" placeholder="paste API key — usually 32 hex chars"
+ autocomplete="off" spellcheck="false">
+ <button type="button" id="civitaiAuthSave" onclick="civitaiAuthSave()">Save & test</button>
+ ${haveKey ? '<a class="changekey" onclick="renderCivitaiAuthBanner(true,\'view\')">cancel</a>' : ''}`;
+ // Pressing Enter inside the input triggers save.
+ const inp = document.getElementById('civitaiAuthInput');
+ if (inp) inp.addEventListener('keydown', (e) => {
+ if (e.key === 'Enter') { e.preventDefault(); civitaiAuthSave(); }
});
}
-function closeAgentSettings() {
- document.getElementById('agentSettingsModal').classList.remove('open');
-}
-
-// ---- Project notes modal --------------------------------------------------
-// Capabilities sheet — driven by /agent/capabilities. Surfaces every
-// tool the agent has, plus engine/image/mode options, so users
-// discover what they can ask for. (Phase 0 #0.5)
-async function openAgentCaps() {
- const modal = document.getElementById('agentCapsModal');
- const body = document.getElementById('agentCapsBody');
- if (!modal || !body) return;
- body.innerHTML = '<div style="padding:24px; color:var(--muted); text-align:center">Loading…</div>';
- modal.classList.add('open');
+async function civitaiAuthSave() {
+ const inp = document.getElementById('civitaiAuthInput');
+ const btn = document.getElementById('civitaiAuthSave');
+ if (!inp) return;
+ const key = (inp.value || '').trim();
+ if (!key) { inp.focus(); return; }
+ if (btn) { btn.disabled = true; btn.textContent = 'Saving…'; }
+ // Save via /settings (single source of truth for tokens). After save
+ // we hit /civitai/test to verify before flipping the banner to "set" —
+ // that catches the most common error (typo'd key) right at the moment
+ // the user pasted it, instead of failing later on the first download.
try {
- const r = await fetch('/agent/capabilities');
- const j = await r.json();
- body.innerHTML = '';
- // Tools
- if (Array.isArray(j.tools) && j.tools.length) {
- const sec = document.createElement('div');
- sec.className = 'caps-section';
- const h = document.createElement('h3');
- h.textContent = `Tools the agent can call · ${j.tools.length}`;
- sec.appendChild(h);
- for (const t of j.tools) {
- const row = document.createElement('div');
- row.className = 'caps-row';
- const name = document.createElement('div');
- name.className = 'caps-name';
- name.textContent = t.name;
- const txt = document.createElement('div');
- txt.className = 'caps-text';
- const sum = document.createElement('div');
- sum.className = 'summary';
- sum.textContent = t.summary || '(no summary)';
- txt.appendChild(sum);
- if (t.body) {
- const det = document.createElement('details');
- const dsum = document.createElement('summary');
- dsum.textContent = 'Show full doc';
- det.appendChild(dsum);
- const pre = document.createElement('pre');
- pre.textContent = t.body;
- det.appendChild(pre);
- txt.appendChild(det);
- }
- row.appendChild(name); row.appendChild(txt);
- sec.appendChild(row);
- }
- body.appendChild(sec);
- }
- // Engine kinds
- const _gridSection = (title, items, render) => {
- if (!Array.isArray(items) || !items.length) return;
- const sec = document.createElement('div');
- sec.className = 'caps-section';
- const h = document.createElement('h3'); h.textContent = title;
- sec.appendChild(h);
- const grid = document.createElement('div');
- grid.className = 'caps-grid';
- for (const it of items) grid.appendChild(render(it));
- sec.appendChild(grid);
- body.appendChild(sec);
- };
- _gridSection('Chat engine kinds', j.engine_kinds || [], (e) => {
- const c = document.createElement('div'); c.className = 'caps-cell';
- c.innerHTML = `<div class="label">${escapeHtml(e.label)}</div>` +
- `<div class="meta">${escapeHtml(e.id)}</div>` +
- `<div class="desc">${escapeHtml(e.cost)}</div>`;
- return c;
- });
- _gridSection('Image-engine backends', j.image_kinds || [], (e) => {
- const c = document.createElement('div'); c.className = 'caps-cell';
- c.innerHTML = `<div class="label">${escapeHtml(e.label)}</div>` +
- `<div class="meta">${escapeHtml(e.id)}</div>` +
- `<div class="desc">${escapeHtml(e.cost)}</div>`;
- return c;
- });
- _gridSection('Operating modes', j.modes || [], (e) => {
- const c = document.createElement('div'); c.className = 'caps-cell';
- c.innerHTML = `<div class="label">${escapeHtml(e.label)}</div>` +
- `<div class="meta">${escapeHtml(e.id)}</div>` +
- `<div class="desc">${escapeHtml(e.desc)}</div>`;
- return c;
- });
+ const fd = new URLSearchParams();
+ fd.set('civitai_api_key', key);
+ const r = await fetch('/settings', { method: 'POST',
+ headers: {'Content-Type':'application/x-www-form-urlencoded'}, body: fd });
+ const data = await r.json();
+ if (!r.ok || !data.ok) throw new Error(data.error || `HTTP ${r.status}`);
+ // Verify
+ if (btn) btn.textContent = 'Testing…';
+ const t = await fetch('/civitai/test');
+ const td = await t.json();
+ if (!td.ok) {
+ renderCivitaiAuthBanner(false, 'err');
+ return;
+ }
+ renderCivitaiAuthBanner(true, 'view');
+ // Re-run the search so any 401-blocked thumbnails reload as authed.
+ civitaiSearch();
} catch (e) {
- body.innerHTML = `<div style="padding:18px;color:#f49a9e">Couldn't load capabilities: ${escapeHtml(String(e))}</div>`;
+ if (btn) { btn.disabled = false; btn.textContent = 'Save & test'; }
+ renderCivitaiAuthBanner(false, 'err');
}
}
-function closeAgentCaps() {
- const m = document.getElementById('agentCapsModal');
- if (m) m.classList.remove('open');
+function closeCivitaiModal() {
+ document.getElementById('civitaiModal').style.display = 'none';
}
-// Slash-command pre-handler. Called from agentSend BEFORE the send fires.
-// Returns true if the slash command was handled (don't continue with
-// the normal send), false otherwise.
-function agentMaybeHandleSlashCommand(text) {
- const t = (text || '').trim();
- if (!t.startsWith('/')) return false;
- const cmd = t.split(/\s+/)[0].toLowerCase();
- switch (cmd) {
- case '/help':
- case '/?':
- openAgentCaps();
- return true;
- case '/notes':
- openProjectNotes();
- return true;
- case '/queue':
- case '/picks':
- // If anchor picks are pending, fire the existing batch flow.
- if (typeof agentBatchQueue === 'function') {
- agentBatchQueue();
- } else {
- alert('No anchors picked yet — generate some first.');
- }
- return true;
- case '/clear':
- case '/new':
- if (typeof agentNewSession === 'function') agentNewSession();
- return true;
- case '/settings':
- case '/engine':
- if (typeof openAgentSettings === 'function') openAgentSettings();
- return true;
- default:
- return false; // unknown slash — let it through
+async function civitaiSearch() {
+ if (_civitaiSearching) return;
+ _civitaiSearching = true;
+ const grid = document.getElementById('civitaiGrid');
+ const status = document.getElementById('civitaiStatus');
+ const loadMore = document.getElementById('civitaiLoadMore');
+ status.textContent = '';
+ status.className = 'civitai-status-line';
+ grid.innerHTML = '<div class="hint">Loading…</div>';
+ loadMore.style.display = 'none';
+ _civitaiCursor = '';
+ try {
+ const params = new URLSearchParams();
+ const q = document.getElementById('civitaiQuery').value.trim();
+ if (q) params.set('query', q);
+ if (document.getElementById('civitaiNsfw').checked) params.set('nsfw', 'true');
+ params.set('limit', '24');
+ const r = await fetch('/civitai/search?' + params.toString());
+ const data = await r.json();
+ if (data.error) {
+ grid.innerHTML = '';
+ status.textContent = data.error;
+ status.className = 'civitai-status-line err';
+ return;
+ }
+ renderCivitaiGrid(data.items, /* append */ false);
+ _civitaiCursor = data.next_cursor || '';
+ if (data.has_more) loadMore.style.display = '';
+ if ((data.items || []).length === 0) {
+ grid.innerHTML = `<div class="hint">No LTX 2.3 LoRAs match "${escapeHtml(q || '')}"${document.getElementById('civitaiNsfw').checked ? '' : ' (try Show NSFW for more)'}.</div>`;
+ }
+ } catch (e) {
+ status.textContent = 'Network error: ' + (e.message || e);
+ status.className = 'civitai-status-line err';
+ } finally {
+ _civitaiSearching = false;
}
}
-async function openProjectNotes() {
- const modal = document.getElementById('agentNotesModal');
- const ta = document.getElementById('agentNotesTextarea');
- const st = document.getElementById('agentNotesStatus');
- if (!modal || !ta) return;
- st.textContent = 'Loading…';
- ta.value = '';
- modal.classList.add('open');
+async function civitaiLoadMore() {
+ if (_civitaiSearching || !_civitaiCursor) return;
+ _civitaiSearching = true;
+ const loadMore = document.getElementById('civitaiLoadMore');
+ loadMore.disabled = true;
+ loadMore.textContent = 'Loading…';
try {
- const r = await fetch('/agent/notes');
- const j = await r.json();
- if (!r.ok) throw new Error(j.error || ('HTTP ' + r.status));
- ta.value = j.content || '';
- const n = (j.content || '').length;
- st.textContent = n ? `${n.toLocaleString()} chars` : 'Empty — type to start.';
+ const params = new URLSearchParams();
+ const q = document.getElementById('civitaiQuery').value.trim();
+ if (q) params.set('query', q);
+ if (document.getElementById('civitaiNsfw').checked) params.set('nsfw', 'true');
+ params.set('limit', '24');
+ params.set('cursor', _civitaiCursor);
+ const r = await fetch('/civitai/search?' + params.toString());
+ const data = await r.json();
+ if (data.error) {
+ document.getElementById('civitaiStatus').textContent = data.error;
+ document.getElementById('civitaiStatus').className = 'civitai-status-line err';
+ return;
+ }
+ renderCivitaiGrid(data.items, /* append */ true);
+ _civitaiCursor = data.next_cursor || '';
+ loadMore.style.display = data.has_more ? '' : 'none';
} catch (e) {
- st.textContent = 'Load failed: ' + e.message;
+ document.getElementById('civitaiStatus').textContent = 'Network error: ' + (e.message || e);
+ document.getElementById('civitaiStatus').className = 'civitai-status-line err';
+ } finally {
+ _civitaiSearching = false;
+ loadMore.disabled = false;
+ loadMore.textContent = 'Load more';
}
- ta.focus();
}
-function closeProjectNotes() {
- document.getElementById('agentNotesModal').classList.remove('open');
+function renderCivitaiGrid(items, append) {
+ const grid = document.getElementById('civitaiGrid');
+ if (!append) grid.innerHTML = '';
+ if (!items || items.length === 0) return;
+ const frag = document.createDocumentFragment();
+ for (const it of items) {
+ const card = document.createElement('div');
+ card.className = 'civitai-card';
+ const sizeMb = it.size_kb ? (it.size_kb / 1024).toFixed(1) : '?';
+ const dl = it.downloads ? new Intl.NumberFormat().format(it.downloads) : '?';
+ const triggers = (it.trigger_words || []).slice(0, 3).join(', ');
+ // LTX is a video model so most LoRAs ship animated previews. Render
+ // <video> for videos (autoplay muted loop = looks like an animated
+ // GIF, no user interaction needed) and <img> for stills. Both share
+ // the .preview class so the card height is stable while images
+ // load. CivitAI's CDN sets `Access-Control-Allow-Origin: *` so
+ // cross-origin loads work without a panel-side proxy.
+ let previewHtml;
+ if (!it.preview_url) {
+ previewHtml = `<div class="preview-empty">no preview</div>`;
+ } else if (it.preview_type === 'video' || /\.mp4($|\?)/i.test(it.preview_url)) {
+ previewHtml = `<video class="preview" src="${escapeHtml(it.preview_url)}"
+ autoplay muted loop playsinline preload="metadata"></video>`;
+ } else {
+ previewHtml = `<img class="preview" src="${escapeHtml(it.preview_url)}" alt="" loading="lazy">`;
+ }
+ card.innerHTML = `
+ ${previewHtml}
+ <div class="body">
+ <div class="ttl" title="${escapeHtml(it.name)}">${escapeHtml(it.name)}</div>
+ <div class="meta">
+ <span>by ${escapeHtml(it.creator)}</span>
+ <span>↓ ${dl}</span>
+ <span>${sizeMb} MB</span>
+ ${it.nsfw ? '<span class="nsfw-badge">NSFW</span>' : ''}
+ </div>
+ ${triggers ? `<div class="meta"><span title="trigger words">trigger: ${escapeHtml(triggers)}</span></div>` : ''}
+ ${it.civitai_url
+ ? `<div class="meta"><a class="civitai-source-link" href="${escapeHtml(it.civitai_url)}" target="_blank" rel="noopener" title="Open the original CivitAI page — usage notes, examples, comments">Read instructions on CivitAI <svg class="ph" aria-hidden="true" style="margin-left:3px;vertical-align:-2px"><use href="#ph-arrow-square-out"/></svg></a></div>`
+ : ''}
+ </div>
+ <div class="actions">
+ <button type="button" class="primary-btn" data-id="${it.id}">Install</button>
+ </div>`;
+ const btn = card.querySelector('button[data-id]');
+ btn.addEventListener('click', () => civitaiInstall(btn, it));
+ frag.appendChild(card);
+ }
+ grid.appendChild(frag);
}
-async function saveProjectNotes() {
- const ta = document.getElementById('agentNotesTextarea');
- const st = document.getElementById('agentNotesStatus');
- if (!ta) return;
- st.textContent = 'Saving…';
+async function civitaiInstall(btn, item) {
+ btn.disabled = true;
+ const origLabel = btn.textContent;
+ btn.textContent = 'Downloading…';
+ const fd = new FormData();
+ fd.set('download_url', item.download_url);
+ fd.set('meta', JSON.stringify(item));
try {
- const r = await fetch('/agent/notes', {
+ const r = await fetch('/civitai/download', {
method: 'POST',
- headers: {'Content-Type': 'application/json'},
- body: JSON.stringify({content: ta.value}),
+ headers: {'Content-Type': 'application/x-www-form-urlencoded'},
+ body: new URLSearchParams(fd),
});
- const j = await r.json();
- if (!r.ok) throw new Error(j.error || ('HTTP ' + r.status));
- st.textContent = `Saved · ${(j.bytes || 0).toLocaleString()} bytes`;
- setTimeout(closeProjectNotes, 350);
+ const data = await r.json();
+ if (!r.ok || !data.ok) {
+ const status = document.getElementById('civitaiStatus');
+ status.textContent = `Download failed: ${data.error || 'HTTP ' + r.status}`;
+ status.className = 'civitai-status-line err';
+ btn.disabled = false;
+ btn.textContent = origLabel;
+ return;
+ }
+ btn.textContent = data.skipped ? 'Already installed ✓' : 'Installed ✓';
+ const status = document.getElementById('civitaiStatus');
+ status.textContent = data.skipped
+ ? `Already in ${data.path} — auto-enabled below.`
+ : `Saved to ${data.path}. Auto-enabled below.`;
+ status.className = 'civitai-status-line ok';
+ // Refresh the local picker so the new LoRA appears, then auto-enable.
+ // Auto-enable applies on BOTH the fresh-download AND the
+ // already-installed paths — clicking Install on a CivitAI card
+ // should always result in "this LoRA is now usable in the next
+ // render," regardless of whether it was already on disk. Earlier
+ // build only auto-enabled fresh downloads, leaving repeat clicks
+ // looking like a no-op even though the file was sitting right
+ // there in the picker.
+ await refreshLoras();
+ addLoraToActive({
+ path: data.path,
+ name: data.name || item.name,
+ strength: item.recommended_strength || 1.0,
+ trigger_words: item.trigger_words || [],
+ });
+ // Open the LoRAs disclosure so the user sees the entry without
+ // hunting for it after the modal closes.
+ const det = document.getElementById('lorasDetails');
+ if (det) det.open = true;
} catch (e) {
- st.textContent = 'Save failed: ' + e.message;
+ document.getElementById('civitaiStatus').textContent = 'Network error: ' + (e.message || e);
+ document.getElementById('civitaiStatus').className = 'civitai-status-line err';
+ btn.disabled = false;
+ btn.textContent = origLabel;
}
}
-function agentKindChanged() {
- const kind = document.getElementById('agentKind').value;
- document.getElementById('agentLocalModelField').style.display = kind === 'phosphene_local' ? '' : 'none';
- document.getElementById('agentLocalRow').style.display = kind === 'phosphene_local' ? '' : 'none';
- document.getElementById('agentOllamaField').style.display = kind === 'ollama' ? '' : 'none';
- document.getElementById('agentAnthropicModelField').style.display = kind === 'anthropic' ? '' : 'none';
- // Base URL is implicit for Anthropic — hide the field.
- document.getElementById('agentBaseUrlField').style.display = kind === 'custom' ? '' : 'none';
- // API key field is shared between Anthropic + custom (transport differs:
- // Anthropic uses x-api-key, custom uses Authorization Bearer — that's
- // engine.chat()'s problem, not the UI's).
- document.getElementById('agentApiKeyField').style.display =
- (kind === 'custom' || kind === 'anthropic') ? '' : 'none';
- document.getElementById('agentRemoteModelField').style.display = kind === 'custom' ? '' : 'none';
- if (kind === 'ollama') agentOllamaRefresh();
-}
+// Boot: load the local LoRA list on page load so the picker isn't empty
+// when the user expands it for the first time.
+document.addEventListener('DOMContentLoaded', () => { refreshLoras(); });
-function agentAnthropicModelChanged() {
- const sel = document.getElementById('agentAnthropicModel');
- const custom = document.getElementById('agentAnthropicCustomModel');
- if (!sel || !custom) return;
- if (sel.value === '__custom__') {
- custom.style.display = '';
- custom.focus();
- } else {
- custom.style.display = 'none';
+// ====== Models modal ======
+// Opens to /models snapshot. While open, the main poll() refreshes the
+// list every cycle so download progress appears live. Each row shows:
+// ✓ ready (green) — all repo files present
+// ◐ partial (amber) — some files there, some missing (e.g. interrupted)
+// ⊘ missing (red) — nothing on disk
+// ↻ downloading (blue, anim) — hf is currently fetching this repo
+function openModelsModal() {
+ document.getElementById('modelsModal').style.display = 'flex';
+ refreshModelsModal();
+}
+function closeModelsModal() {
+ document.getElementById('modelsModal').style.display = 'none';
+}
+async function refreshModelsModal({ silent = false } = {}) {
+ const list = document.getElementById('modelsList');
+ const hint = document.getElementById('modelsHint');
+ const foot = document.getElementById('modelsFoot');
+ let data;
+ try { data = await api('/models'); }
+ catch (e) {
+ if (!silent) hint.textContent = 'Failed to load models. Panel might be restarting — try again.';
+ return;
}
+ const repos = data.repos || [];
+ const active = data.active_download;
+ hint.innerHTML = data.hf_available
+ ? `Each row shows what's on disk. Click <b>Download</b> to fetch missing files via <code>hf download</code>; progress streams to the log at the bottom of the page.`
+ : `<span style="color:var(--warning,#d29922)"><svg class="ph" aria-hidden="true" style="margin-right:4px;vertical-align:-2px"><use href="#ph-warning-fill"/></svg><code>hf</code> not found</span> — this Pinokio install doesn't have <code>huggingface_hub&gt;=1.0</code> in the venv. Run Update from Pinokio, then come back.`;
+ const rows = repos.map(r => {
+ let cls, icon, statusText, btnHtml;
+ if (active && active.key === r.key) {
+ cls = 'downloading';
+ icon = '<svg class="ph" aria-hidden="true"><use href="#ph-arrow-clockwise-bold"/></svg>';
+ const elapsed = Math.max(0, Math.round((Date.now()/1000) - (active.started_ts || 0)));
+ const last = active.last_line ? `<div class="progress">${escapeHtml(active.last_line)}</div>` : '';
+ statusText = `Downloading · ${elapsed}s${last}`;
+ btnHtml = `<button class="ghost" onclick="cancelDownload()">Cancel</button>`;
+ } else if (r.complete) {
+ cls = 'ready'; icon = '<svg class="ph" aria-hidden="true"><use href="#ph-check-bold"/></svg>';
+ // `where: 'hf_cache'` means the files were resolved from
+ // ~/.cache/huggingface/ rather than the canonical mlx_models/
+ // dir. Common on manual / dev installs that pre-existed Pinokio
+ // and pulled the model via `huggingface-cli` or first-run helper.
+ const tag = r.where === 'hf_cache' ? 'HF cache' : 'local';
+ statusText = `Ready · ${r.total_files} files · ~${r.size_gb || '?'} GB · ${tag}`;
+ btnHtml = `<button class="ghost" disabled>Installed</button>`;
+ } else if (r.present_files > 0) {
+ cls = 'partial'; icon = '<svg class="ph" aria-hidden="true"><use href="#ph-download-simple"/></svg>';
+ const left = r.total_files - r.present_files;
+ statusText = `Partial · ${r.present_files}/${r.total_files} files · ${left} missing — resume to finish`;
+ btnHtml = data.hf_available
+ ? `<button onclick="startDownload('${escapeHtml(r.key)}')" ${active ? 'disabled' : ''}>Resume</button>`
+ : `<button disabled>Resume</button>`;
+ } else {
+ cls = 'missing'; icon = '<svg class="ph" aria-hidden="true"><use href="#ph-x-circle"/></svg>';
+ statusText = `Not installed · ~${r.size_gb || '?'} GB`;
+ btnHtml = data.hf_available
+ ? `<button onclick="startDownload('${escapeHtml(r.key)}')" ${active ? 'disabled' : ''}>Download</button>`
+ : `<button disabled>Download</button>`;
+ }
+ const kindBadge = r.kind === 'optional'
+ ? `<span style="color:var(--muted)">optional</span>`
+ : `<span style="color:var(--success,#3fb950)">required</span>`;
+ return `
+ <li class="${cls}">
+ <span class="icon">${icon}</span>
+ <div class="meta">
+ <span class="ttl">${escapeHtml(r.name)} · ${kindBadge}</span>
+ <span class="sub">${escapeHtml(r.repo_id)} → ${escapeHtml(r.local_dir)}</span>
+ <span class="sub">${statusText}${r.blurb ? ' · ' + escapeHtml(r.blurb) : ''}</span>
+ </div>
+ ${btnHtml}
+ </li>`;
+ }).join('');
+ list.innerHTML = rows || `<li class="empty-state">No model manifest found — required_files.json is missing or unreadable.</li>`;
+ // Footer summarises required vs optional counts.
+ const reqRepos = repos.filter(r => r.kind !== 'optional');
+ const optRepos = repos.filter(r => r.kind === 'optional');
+ const reqReady = reqRepos.filter(r => r.complete).length;
+ const optReady = optRepos.filter(r => r.complete).length;
+ foot.innerHTML = `
+ <div>Required: ${reqReady}/${reqRepos.length} ready &nbsp;·&nbsp; Optional: ${optReady}/${optRepos.length} ready</div>
+ <div style="margin-top:4px">Tip: downloads resume on retry — closing this dialog mid-download keeps it running in the background.</div>`;
}
-
-async function agentOllamaRefresh() {
- const sel = document.getElementById('agentOllamaModel');
- const hint = document.getElementById('agentOllamaHint');
- if (!sel) return;
- sel.innerHTML = '<option>Probing Ollama at 127.0.0.1:11434…</option>';
+async function startDownload(key) {
+ let res;
try {
- const r = await fetch('/agent/ollama/status');
- const j = await r.json();
- sel.innerHTML = '';
- if (!j.running) {
- const opt = document.createElement('option');
- opt.value = '';
- opt.textContent = 'Ollama not running on 127.0.0.1:11434';
- sel.appendChild(opt);
- if (hint) hint.innerHTML = `<strong>Ollama is not running.</strong> Start it with <code>ollama serve</code>, then click Refresh. Install models with <code>ollama pull qwen2.5-coder:32b</code>.`;
- return;
- }
- const cfg = (window.AGENT.config && window.AGENT.config.engine) || {};
- if ((j.models || []).length === 0) {
- const opt = document.createElement('option');
- opt.value = '';
- opt.textContent = 'No Ollama models installed';
- sel.appendChild(opt);
- }
- for (const m of (j.models || [])) {
- const opt = document.createElement('option');
- opt.value = m.name;
- opt.textContent = `${m.name}${m.size_gb ? ' · ' + m.size_gb + ' GB' : ''}${m.parameter_size ? ' · ' + m.parameter_size : ''}${m.quantization ? ' · ' + m.quantization : ''}`;
- if (cfg.kind === 'ollama' && cfg.model === m.name) opt.selected = true;
- sel.appendChild(opt);
- }
- if (hint) hint.innerHTML = `Talks to <code>${escapeHtml(j.openai_url || j.base_url + '/v1')}/chat/completions</code>. Tool calling works on models whose Modelfile declares it (Qwen3 Coder, Llama 3.x, Devstral, Mistral, Granite). Run <code>ollama show &lt;model&gt;</code> to verify.`;
- } catch(e) {
- sel.innerHTML = '<option>Failed to probe — see console</option>';
- }
-}
-
-function agentImageKindChanged() {
- const kind = document.getElementById('agentImageKind').value;
- // mflux fields
- const isMflux = kind === 'mflux';
- document.getElementById('agentMfluxModelField').style.display = isMflux ? '' : 'none';
- document.getElementById('agentMfluxParamsField').style.display = isMflux ? '' : 'none';
- document.getElementById('agentMfluxInstallHint').style.display = isMflux ? '' : 'none';
- if (isMflux) agentMfluxModelChanged();
- else {
- document.getElementById('agentMfluxCustomField').style.display = 'none';
- document.getElementById('agentMfluxBaseField').style.display = 'none';
- }
- // BFL fields
- document.getElementById('agentBflModelField').style.display = kind === 'bfl' ? '' : 'none';
- document.getElementById('agentBflKeyField').style.display = kind === 'bfl' ? '' : 'none';
-}
-
-function agentMfluxModelChanged() {
- const v = document.getElementById('agentMfluxModel').value;
- const isCustom = v === '__custom__';
- document.getElementById('agentMfluxCustomField').style.display = isCustom ? '' : 'none';
- document.getElementById('agentMfluxBaseField').style.display = isCustom ? '' : 'none';
-
- // Show the Qwen install hint when the user picks a Qwen-Edit option
- // AND `mflux-generate-qwen-edit` isn't on PATH yet. family_status comes
- // from /agent/image/config (cached in window.AGENT.imageConfig). The
- // hint is silent for installed families and for non-Qwen picks.
- const hint = document.getElementById('agentQwenInstallHint');
- if (hint) {
- const isQwenEdit = /qwen-image-edit|qwen_image_edit|qwen-edit/i.test(v);
- const fs = (window.AGENT.imageConfig || {}).family_status || {};
- const installed = fs.qwen_edit === true;
- hint.style.display = (isQwenEdit && !installed) ? '' : 'none';
+ res = await api('/models/download', 'POST', `repo_key=${encodeURIComponent(key)}`);
+ } catch (e) {
+ alert('Download failed to start: ' + (e?.message || e));
+ return;
}
-
- // Per-family default step count — mirrors agent/image_engine.py
- // MFLUX_FAMILY_DEFAULTS. The user can override; we only auto-fill
- // when they haven't manually edited the field this session
- // (dataset.userTouched is set when the input fires `input`).
- const stepsInput = document.getElementById('agentMfluxSteps');
- if (stepsInput && !stepsInput.dataset.userTouched) {
- // Family-aware step picks (must stay in sync with image_engine.py
- // MFLUX_FAMILY_DEFAULTS — flagged at the source). Qwen-Edit default
- // is 8 (matches MFLUX_FAMILY_DEFAULTS["qwen_edit"]["steps"] and the
- // `qwen_edit_inline` preset's standard tier — was 30, which is the
- // final-quality count and slowed every fresh user's first run by
- // ~4x). Bump to 30/40 manually when committing a final render.
- // (Code-review P2-3.)
- let steps = null;
- if (/qwen-image-edit|qwen_image_edit|qwen-edit/i.test(v)) steps = 8;
- else if (/flux\.?2.*klein/i.test(v) || /flux2-klein/i.test(v)) steps = 4;
- else if (/z-image-turbo|z_image_turbo/i.test(v)) steps = 9;
- else if (/^schnell$/i.test(v)) steps = 4;
- else if (/^(krea-dev|dev)$/i.test(v)) steps = 25;
- else if (/z-image$|z_image$/i.test(v)) steps = 25;
- else if (/fibo/i.test(v)) steps = 30;
- if (steps !== null) stepsInput.value = steps;
+ // The api() helper coerces 409 (busy) to { error: 'busy' } — surface that
+ // to the user instead of silently no-op'ing the click.
+ if (res && res.error) {
+ alert(`Can't start download: ${res.error}`);
}
+ refreshModelsModal();
+ poll();
}
-
-function agentLocalRefreshRow(local) {
- const pill = document.getElementById('agentLocalPill');
- const detail = document.getElementById('agentLocalDetail');
- const btn = document.getElementById('agentLocalToggleBtn');
- if (!pill || !detail || !btn) return;
- if (local.running) {
- pill.textContent = 'live';
- pill.classList.add('live'); pill.classList.remove('bad');
- detail.textContent = `mlx-lm.server pid ${local.pid} on :${local.port}`;
- btn.textContent = 'Stop';
- } else {
- pill.textContent = 'stopped';
- pill.classList.remove('live');
- if (local.last_error) pill.classList.add('bad');
- detail.textContent = local.last_error || 'mlx-lm.server (will spawn on Start)';
- btn.textContent = 'Start';
- }
+async function cancelDownload() {
+ if (!confirm('Cancel the active download? Partial files stay on disk; clicking Download/Resume later picks up where you left off.')) return;
+ try { await api('/models/cancel', 'POST'); } catch (e) {}
+ refreshModelsModal();
}
-async function agentLocalToggle() {
- const local = (window.AGENT.config && window.AGENT.config.local_server) || {};
- if (local.running) {
- await fetch('/agent/local/stop', {method: 'POST'});
- } else {
- const sel = document.getElementById('agentLocalModel');
- const modelPath = sel ? sel.value : '';
- await fetch('/agent/local/start', {
- method: 'POST',
- headers: {'Content-Type': 'application/json'},
- body: JSON.stringify({model_path: modelPath || undefined}),
- });
- }
- await new Promise(r => setTimeout(r, 300));
- await agentRefreshConfig();
- const local2 = (window.AGENT.config && window.AGENT.config.local_server) || {};
- agentLocalRefreshRow(local2);
-}
+// ====== Version pill (the "magic button") ======
+//
+// One always-visible pill in the header that changes content + colour
+// based on /version state. Clicking it does the right thing for the
+// current state — no modal, no nested click flows.
+//
+// Backend: a daemon thread polls GitHub every 30 minutes (commits API
+// for the SHA + raw VERSION file for the human-friendly Y1.NNN label)
+// and exposes the result at /version. The JS polls /version every 5
+// minutes (cheap; pre-computed dict read). When the user clicks while
+// behind, /version/pull does the actual `git pull` server-side; the
+// user still has to Stop+Start phosphene in Pinokio to apply.
+//
+// Rationale: users keep telling us "I clicked Update but I don't see
+// the new features" — by the time the feedback reaches us we've usually
+// pushed three more commits. The pill turns the loop from
+// "hope-they-noticed" into a literal one-click action.
-async function agentSaveSettings() {
- const kind = document.getElementById('agentKind').value;
- const payload = {
- kind,
- temperature: parseFloat(document.getElementById('agentTemp').value || '0.4'),
- max_tokens: parseInt(document.getElementById('agentMaxTokens').value || '8192', 10),
- };
- if (kind === 'phosphene_local') {
- const sel = document.getElementById('agentLocalModel');
- if (sel && sel.value) {
- payload.local_model_path = sel.value;
- const parts = sel.value.split('/');
- payload.model = parts[parts.length - 1] || sel.value;
- }
- } else if (kind === 'ollama') {
- // Ollama bridge: same OpenAI-compat shape, just talks to 127.0.0.1:11434/v1.
- // No api_key. The model field is the Ollama tag (e.g. "qwen2.5-coder:32b").
- const sel = document.getElementById('agentOllamaModel');
- payload.base_url = 'http://127.0.0.1:11434/v1';
- payload.model = sel ? sel.value : '';
- payload.local_model_path = '';
- } else if (kind === 'anthropic') {
- // Anthropic Messages API: implicit base URL + x-api-key auth (handled
- // inside engine.chat). Model is either the curated select or a custom
- // dated id.
- payload.base_url = 'https://api.anthropic.com/v1';
- const sel = document.getElementById('agentAnthropicModel');
- const custom = (document.getElementById('agentAnthropicCustomModel').value || '').trim();
- payload.model = (sel && sel.value === '__custom__')
- ? (custom || 'claude-sonnet-4-5')
- : (sel ? sel.value : 'claude-sonnet-4-5');
- payload.local_model_path = '';
- const ak = (document.getElementById('agentApiKey').value || '').trim();
- if (ak) payload.api_key = ak;
- } else {
- payload.base_url = (document.getElementById('agentBaseUrl').value || '').trim();
- payload.model = (document.getElementById('agentRemoteModel').value || '').trim();
- const ak = (document.getElementById('agentApiKey').value || '').trim();
- if (ak) payload.api_key = ak;
- }
- const r = await fetch('/agent/config', {
- method: 'POST',
- headers: {'Content-Type': 'application/json'},
- body: JSON.stringify(payload),
- });
- const j = await r.json();
- if (!r.ok || j.error) {
- alert('Could not save: ' + (j.error || ('HTTP ' + r.status)));
- return;
- }
+let _versionState = null;
+let _versionRestartPending = false; // set after a successful /version/pull;
+ // pill turns into a "restart" reminder.
- // Save image-engine config too (separate file).
- const imgKind = document.getElementById('agentImageKind').value;
- const imgPayload = {
- kind: imgKind,
- bfl_model: document.getElementById('agentBflModel').value,
- };
- const bk = (document.getElementById('agentBflKey').value || '').trim();
- if (bk) imgPayload.bfl_api_key = bk;
- // mflux fields (only meaningful when kind === 'mflux', but we save them
- // either way so the form retains the user's previous setup when they
- // toggle backends back and forth).
- const mfSel = document.getElementById('agentMfluxModel').value;
- if (mfSel === '__custom__') {
- const cp = (document.getElementById('agentMfluxCustomPath').value || '').trim();
- if (cp) {
- imgPayload.mflux_model = cp;
- imgPayload.mflux_base_model = document.getElementById('agentMfluxBaseModel').value;
- }
- } else {
- imgPayload.mflux_model = mfSel;
- imgPayload.mflux_base_model = '';
- }
- imgPayload.mflux_steps = parseInt(document.getElementById('agentMfluxSteps').value || '25', 10);
- imgPayload.mflux_quantize = parseInt(document.getElementById('agentMfluxQuantize').value || '6', 10);
+async function refreshVersionPill() {
try {
- const ir = await fetch('/agent/image/config', {
- method: 'POST',
- headers: {'Content-Type': 'application/json'},
- body: JSON.stringify(imgPayload),
- });
- const ij = await ir.json();
- if (!ir.ok || ij.error) {
- alert('Image config could not be saved: ' + (ij.error || ('HTTP ' + ir.status)));
- }
- } catch(e) {
- alert('Image config save failed: ' + e);
+ const r = await fetch('/version');
+ _versionState = await r.json();
+ } catch (e) {
+ return; // network blip; don't blow away last good state
}
-
- closeAgentSettings();
- await agentRefreshConfig();
- await agentRefreshImageConfig();
- // Phase 0 #0.11 — re-probe so the user sees instant confirmation that
- // the new key / base URL / model actually works. Reset the dismiss flag
- // so a green banner pops even if they X'd a previous one.
- window.AGENT_ENGINE_BANNER.dismissed = false;
- setTimeout(() => { try { agentCheckEngine({forceShow: true, persist: false}); } catch (e) {} }, 200);
+ renderVersionPill();
}
-// ============================================================================
-// HF MODEL BROWSER — search + install MLX chat models
-// ============================================================================
-window.MODEL_BROWSER = {
- pollerId: null,
- lastResults: [],
-};
-
-function openModelBrowser() {
- const m = document.getElementById('modelBrowserModal');
- if (!m) return;
- m.classList.add('open');
- // Auto-focus the query input on open.
- setTimeout(() => {
- const q = document.getElementById('modelBrowserQuery');
- if (q) q.focus();
- }, 50);
- // If we already have results from a previous search, leave them; else
- // run a default search ("qwen") so the user sees something useful.
- if (!window.MODEL_BROWSER.lastResults.length) {
- document.getElementById('modelBrowserQuery').value = 'qwen';
- modelBrowserSearch();
- }
- // Start polling install status in case a download is already in flight.
- modelBrowserStartPolling();
+function _versionDisplayLabel(s) {
+ // Prefer the human Y1.NNN VERSION file label. Fall back to the short
+ // SHA for older checkouts that predate the VERSION file. Last-resort
+ // ellipsis when nothing's known yet.
+ return s.local_version || s.local_short || '…';
}
-function closeModelBrowser() {
- document.getElementById('modelBrowserModal').classList.remove('open');
- modelBrowserStopPolling();
+function _versionRemoteLabel(s) {
+ return s.remote_version || s.remote_short || 'latest';
}
-async function modelBrowserSearch() {
- const q = (document.getElementById('modelBrowserQuery').value || '').trim();
- const abliterated = document.getElementById('modelBrowserAbliterated').checked;
- const results = document.getElementById('modelBrowserResults');
- const btn = document.getElementById('modelBrowserSearchBtn');
- results.innerHTML = '<div class="model-browser-empty">Searching…</div>';
- btn.disabled = true;
- try {
- const url = '/agent/models/search?q=' + encodeURIComponent(q)
- + '&abliterated=' + (abliterated ? '1' : '0')
- + '&limit=40';
- const r = await fetch(url);
- const j = await r.json();
- if (!r.ok || j.error) {
- results.innerHTML = '<div class="model-browser-empty" style="color:#f49a9e">Error: ' + escapeHtml(j.error || ('HTTP ' + r.status)) + '</div>';
- return;
- }
- window.MODEL_BROWSER.lastResults = j.results || [];
- modelBrowserRender(j.results || []);
- } catch(e) {
- results.innerHTML = '<div class="model-browser-empty" style="color:#f49a9e">Error: ' + escapeHtml(String(e)) + '</div>';
- } finally {
- btn.disabled = false;
- }
-}
+function renderVersionPill() {
+ const pill = document.getElementById('versionPill');
+ if (!pill) return;
+ const s = _versionState || {};
+ const local = _versionDisplayLabel(s);
+ const remote = _versionRemoteLabel(s);
+ // Reset every state class; exactly one is added below.
+ pill.classList.remove('pill-update','pill-current','pill-dev','pill-checking','pill-restart','pill-busy');
+ pill.style.display = '';
-function modelBrowserRender(results) {
- const wrap = document.getElementById('modelBrowserResults');
- if (!results.length) {
- wrap.innerHTML = '<div class="model-browser-empty">No matches. Try a different query.</div>';
- return;
- }
- wrap.innerHTML = '';
- for (const m of results) {
- const row = document.createElement('div');
- row.className = 'model-result';
- const isAbliterated = (m.repo_id || '').toLowerCase().includes('abliterated')
- || (m.repo_id || '').toLowerCase().startsWith('huihui-ai/');
- const dl = (m.downloads || 0).toLocaleString();
- const lk = (m.likes || 0).toLocaleString();
- const tags = [];
- if (m.gated) tags.push('<span class="tag gated">gated</span>');
- if (isAbliterated) tags.push('<span class="tag abliterated">abliterated</span>');
- if (m.library_name) tags.push(`<span class="tag">${escapeHtml(m.library_name)}</span>`);
- if (m.pipeline_tag) tags.push(`<span class="tag">${escapeHtml(m.pipeline_tag)}</span>`);
- row.innerHTML = `
- <div class="info">
- <div class="name">${escapeHtml(m.repo_id)}</div>
- <div class="meta">
- <span>↓ ${dl}</span>
- <span>♥ ${lk}</span>
- ${tags.join('')}
- </div>
- </div>
- <div class="actions">
- <button class="info-btn" onclick="modelBrowserInfo('${escapeHtml(m.repo_id)}')">Info</button>
- <button class="install-btn" onclick="modelBrowserInstall('${escapeHtml(m.repo_id)}', this)">Install</button>
- </div>
- `;
- wrap.appendChild(row);
- }
-}
+ // Pill text leads with the MEANING of the state, not the version code.
+ // Earlier build showed bare "Y1.005" which read as a label rather than
+ // a status — users didn't realize they could click it. Now every state
+ // uses plain English so a user glancing at the header understands at
+ // a glance whether they're current, behind, or need to restart.
-async function modelBrowserInfo(repoId) {
- // Lightweight inline info — pop a confirm with size + file count + gated state.
- try {
- const r = await fetch('/agent/models/info?repo_id=' + encodeURIComponent(repoId));
- const j = await r.json();
- if (j.gated || j.error) {
- alert('Repo info:\n' + (j.error || ('Gated. Open https://huggingface.co/' + repoId + ' and accept the terms first.')));
- return;
- }
- alert(`${repoId}\n\nFiles: ${j.file_count}\nTotal: ${j.total_size_gb} GB\n\nClick Install to download into mlx_models/.`);
- } catch(e) {
- alert('Could not fetch info: ' + e);
+ // Highest-priority state: a pull just happened and the panel needs a
+ // restart to load the new code.
+ if (_versionRestartPending) {
+ pill.classList.add('pill-restart');
+ pill.innerHTML = '<svg class="ph" aria-hidden="true" style="margin-right:4px;vertical-align:-2px"><use href="#ph-arrow-clockwise-bold"/></svg>Restart Phosphene';
+ const v = s.pull_pulled_to_version || s.pull_pulled_to_short || 'the new code';
+ pill.title = s.pull_requires_full_update
+ ? `Pulled ${v}. This update touched dependencies — use Pinokio's Update button (not just Stop+Start).`
+ : `Pulled ${v}. Click Stop → Start in Pinokio to apply.`;
+ return;
}
-}
-
-async function modelBrowserInstall(repoId, btn) {
- if (!confirm(`Install ${repoId}?\n\nDownloads to mlx_models/. Files are large — first run can take 5-30 min depending on size and network.`)) {
+ // Suppressed (dev branch / dirty tree / no git).
+ if (s.suppress_reason) {
+ pill.classList.add('pill-dev');
+ pill.textContent = `${local} · dev`;
+ pill.title = `Update check paused: ${s.suppress_reason}.`;
return;
}
- btn.disabled = true;
- btn.textContent = 'Queuing…';
- try {
- const r = await fetch('/agent/models/install', {
- method: 'POST',
- headers: {'Content-Type': 'application/json'},
- body: JSON.stringify({repo_id: repoId}),
- });
- const j = await r.json();
- if (!r.ok || j.error) {
- alert('Install failed to start: ' + (j.error || ('HTTP ' + r.status)));
- btn.disabled = false;
- btn.textContent = 'Install';
- return;
- }
- btn.textContent = 'Downloading…';
- modelBrowserStartPolling();
- } catch(e) {
- alert('Install error: ' + e);
- btn.disabled = false;
- btn.textContent = 'Install';
+ // Behind origin/main — eye-catching action prompt.
+ if (!s.error && s.checked_ts && (s.behind_by | 0) > 0) {
+ pill.classList.add('pill-update');
+ pill.innerHTML = `<svg class="ph" aria-hidden="true" style="margin-right:4px;vertical-align:-2px"><use href="#ph-arrow-up"/></svg>Update to ${remote}`;
+ pill.title = `You're on ${local}; latest is ${remote}. Click to pull the update.`;
+ return;
}
-}
-
-function modelBrowserStartPolling() {
- modelBrowserStopPolling();
- modelBrowserPollOnce();
- window.MODEL_BROWSER.pollerId = setInterval(modelBrowserPollOnce, 1500);
-}
-
-function modelBrowserStopPolling() {
- if (window.MODEL_BROWSER.pollerId) {
- clearInterval(window.MODEL_BROWSER.pollerId);
- window.MODEL_BROWSER.pollerId = null;
+ // Last check errored (offline).
+ if (s.error) {
+ pill.classList.add('pill-dev');
+ pill.textContent = `${local} · offline`;
+ pill.title = `Couldn't reach github.com (${s.error}). Click to retry.`;
+ return;
}
-}
-
-async function modelBrowserPollOnce() {
- try {
- const r = await fetch('/agent/models/install/status');
- const j = await r.json();
- const status = document.getElementById('modelBrowserStatus');
- const lbl = document.getElementById('modelBrowserStatusLabel');
- const summ = document.getElementById('modelBrowserStatusSummary');
- const line = document.getElementById('modelBrowserStatusLine');
- if (!status || !lbl) return;
- if (j.active) {
- status.classList.add('visible');
- lbl.textContent = 'Downloading';
- lbl.style.color = '';
- const elapsed = j.elapsed_s ? ` · ${Math.round(j.elapsed_s)}s` : '';
- summ.textContent = `${j.repo_id || ''}${elapsed}`;
- line.textContent = j.last_line || '';
- } else if (j.done) {
- status.classList.add('visible');
- lbl.textContent = 'Installed';
- lbl.style.color = '#9be7a4';
- summ.textContent = `${j.repo_id || ''} → ${j.target_dir || ''}`;
- line.textContent = '';
- modelBrowserStopPolling();
- // Refresh the local-model picker in the background so the user
- // sees the new model on next settings-modal open.
- try { agentRefreshConfig(); } catch(e) {}
- } else if (j.error) {
- status.classList.add('visible');
- lbl.textContent = 'Failed';
- lbl.style.color = '#f49a9e';
- summ.textContent = j.repo_id || '';
- line.textContent = j.error;
- modelBrowserStopPolling();
- } else {
- status.classList.remove('visible');
- modelBrowserStopPolling();
- }
- } catch(e) {
- /* swallow */
+ // Current with origin/main.
+ if (s.checked_ts && (s.behind_by | 0) === 0) {
+ pill.classList.add('pill-current');
+ pill.innerHTML = `<svg class="ph" aria-hidden="true" style="margin-right:4px;vertical-align:-2px"><use href="#ph-check-bold"/></svg>Up to date · ${local}`;
+ pill.title = `You're on ${local}, the latest version. Click to re-check now.`;
+ return;
}
+ // First poll hasn't landed yet.
+ pill.classList.add('pill-checking');
+ pill.textContent = `Checking · ${local}`;
+ pill.title = 'Checking for updates…';
}
-// Esc closes the model browser, before falling through to settings/fullscreen.
-document.addEventListener('keydown', (e) => {
- if (e.key === 'Escape') {
- const m = document.getElementById('modelBrowserModal');
- if (m && m.classList.contains('open')) {
- closeModelBrowser();
- e.stopPropagation();
- }
+// One click — does the right thing for the current state. Magic button.
+async function versionPillClick() {
+ if (_versionRestartPending) {
+ // Educational click: tell the user what's needed.
+ const s = _versionState || {};
+ const tip = s.pull_requires_full_update
+ ? "Pulled. Because this update touched Python deps / patches, use Pinokio's Update button (it reinstalls + reapplies patches). After that click Start."
+ : "Pulled. Click Stop, then Start in Pinokio to apply (your queue and settings are preserved).";
+ alert(tip);
+ return;
}
-}, true);
-
-// Cmd/Ctrl+Enter in the search box runs the search.
-document.addEventListener('DOMContentLoaded', () => {
- const q = document.getElementById('modelBrowserQuery');
- if (q) {
- q.addEventListener('keydown', (e) => {
- if (e.key === 'Enter') { e.preventDefault(); modelBrowserSearch(); }
- });
+ const s = _versionState || {};
+ if (s.suppress_reason) {
+ alert(`Update check is paused: ${s.suppress_reason}.\n\n` +
+ `Phosphene only checks GitHub when you're on a clean main branch. ` +
+ `Commit your local changes (or switch back to main) to re-enable updates.`);
+ return;
}
-});
-
-// ============================================================================
-// AGENT STAGE PANE — live canvas on the right side
-// ============================================================================
-// Shows the agent's video work as it happens: currently rendering job,
-// session outputs (with click-to-play lightbox), and a recent-activity
-// feed of tool calls. Polls /status + the active session every ~1.5 s
-// while the agent workflow is selected.
-
-window.AGENT_STAGE = {
- pollerId: null,
- lastSessionShotIds: [], // submitted_shots from session.tool_state, ordered
- lastEventCount: 0, // for animating new entries in the activity feed
-};
-
-function agentStageStart() {
- agentStageStop();
- // Tick once immediately, then every 1500 ms.
- agentStageTick();
- window.AGENT_STAGE.pollerId = setInterval(agentStageTick, 1500);
-}
-
-function agentStageStop() {
- if (window.AGENT_STAGE.pollerId) {
- clearInterval(window.AGENT_STAGE.pollerId);
- window.AGENT_STAGE.pollerId = null;
+ // Behind: pull the update.
+ if (!s.error && s.checked_ts && (s.behind_by | 0) > 0) {
+ await versionDoPull();
+ return;
}
+ // Current OR error OR pre-first-poll: re-check now.
+ await versionDoRefresh();
}
-async function agentStageTick() {
- const pane = document.querySelector('.agent-stage-pane');
- // Don't bother polling when the pane is hidden.
- if (!pane || getComputedStyle(pane).display === 'none') return;
+async function versionDoRefresh() {
+ const pill = document.getElementById('versionPill');
+ pill.classList.add('pill-busy');
+ pill.innerHTML = '<svg class="ph" aria-hidden="true" style="margin-right:4px;vertical-align:-2px;animation:phSpin 1.2s linear infinite"><use href="#ph-arrow-clockwise-bold"/></svg>checking…';
try {
- const [statusResp, sessResp] = await Promise.all([
- fetch('/status').then(r => r.ok ? r.json() : null).catch(() => null),
- window.AGENT.sessionId
- ? fetch('/agent/sessions/' + encodeURIComponent(window.AGENT.sessionId))
- .then(r => r.ok ? r.json() : null).catch(() => null)
- : null,
- ]);
- agentStageRender(statusResp, sessResp);
- agentRenderRamChip(statusResp);
- // Keep submittedShots cache + batch bar in sync with the live session.
- if (sessResp && sessResp.session && sessResp.session.tool_state) {
- const ts = sessResp.session.tool_state;
- window.AGENT.submittedShots = ts.submitted_shots || [];
- window.AGENT.selectedAnchors = ts.selected_anchors || window.AGENT.selectedAnchors || {};
- agentRenderBatchBar();
- }
- } catch(e) {
- /* swallow — next tick retries */
+ const r = await fetch('/version/check', { method: 'POST' });
+ const data = await r.json();
+ if (data && data.state) _versionState = data.state;
+ } catch (e) {
+ // Leave _versionState as-is so the pill returns to the prior render
+ // instead of flashing to "unknown".
}
+ pill.classList.remove('pill-busy');
+ renderVersionPill();
}
-// RAM headroom chip in the agent header. The single answer to
-// "can I send a message right now without putting the Mac in swap?"
-// — colored green when comfortable, amber when tight, red when not.
-function agentRenderRamChip(status) {
- const chip = document.getElementById('agentRamChip');
- const label = document.getElementById('agentRamLabel');
- if (!chip || !label || !status) return;
- const m = status.memory || {};
- const total = Number(m.total_gb) || 0;
- const used = Number(m.used_gb) || 0;
- const free = Math.max(0, total - used);
- // Pull the configured chat model's resident size if we know it. The
- // /agent/config response carries `available_models[*].size_gb`; match
- // by `path` for local engines.
- let modelGb = null;
- let modelName = '';
- let isLocal = false;
- let isLoaded = false;
+async function versionDoPull() {
+ const s = _versionState || {};
+ const target = _versionRemoteLabel(s);
+ const local = _versionDisplayLabel(s);
+ const ok = confirm(
+ `Pull update from ${local} → ${target}?\n\n` +
+ `This runs git pull on your phosphene install. After it succeeds, ` +
+ `you'll need to click Stop, then Start in Pinokio to load the new code. ` +
+ `Your queue and settings are preserved across restarts.`
+ );
+ if (!ok) return;
+ const pill = document.getElementById('versionPill');
+ pill.classList.add('pill-busy');
+ pill.innerHTML = '<svg class="ph" aria-hidden="true" style="margin-right:4px;vertical-align:-2px;animation:phSpin 1.2s linear infinite"><use href="#ph-arrow-clockwise-bold"/></svg>pulling…';
+ // Tell poll() not to flash the offline banner during this call —
+ // /version/pull is single-threaded server-side and blocks /status for
+ // ~30s while git fetch + git pull + remote-check run. Without this
+ // suppression the user sees an "offline → reconnected" flash at the
+ // tail of every successful Update click.
+ window._suppressOfflineBanner = true;
try {
- const cfg = window.AGENT && window.AGENT.config;
- const eng = cfg && cfg.engine;
- if (eng && eng.kind === 'phosphene_local') {
- isLocal = true;
- isLoaded = !!(cfg.local_server && cfg.local_server.running);
- const path = eng.local_model_path || '';
- const list = cfg.available_models || [];
- const hit = list.find(m => m.path === path);
- if (hit && hit.size_gb) {
- modelGb = Number(hit.size_gb);
- modelName = hit.name || '';
- }
+ const r = await fetch('/version/pull', { method: 'POST' });
+ const data = await r.json();
+ if (data && data.state) _versionState = data.state;
+ if (!r.ok || !data.ok) {
+ pill.classList.remove('pill-busy');
+ renderVersionPill();
+ alert(`Pull failed:\n\n${(data && data.error) || 'unknown error'}\n\n` +
+ `Tip: try the full Pinokio Update button instead — it also handles ` +
+ `cases where you have local changes that block a fast-forward.`);
+ return;
}
- } catch (e) {}
-
- // If the chat model is already resident, its weights are already in
- // `used` — the question is simply "is there room left to keep going?"
- // If it's NOT loaded yet, we need to subtract its expected size from
- // `free` to predict whether spawning would push us into swap.
- const swapGb = Number(m.swap_gb) || 0;
- let cls = 'is-roomy';
- let text = `${free.toFixed(0)} GB free`;
- let tip = `Total ${total.toFixed(0)} GB · Used ${used.toFixed(1)} GB · Free ${free.toFixed(1)} GB`;
- if (swapGb >= 1) tip += ` · Swap ${swapGb.toFixed(1)} GB`;
-
- if (isLocal && modelGb && !isLoaded) {
- const after = free - modelGb;
- tip += `\n${modelName || 'Selected model'}: ~${modelGb.toFixed(1)} GB`;
- tip += `\nIf started: ${after.toFixed(1)} GB would remain for renders`;
- if (after < 2 || swapGb >= 8) {
- cls = 'is-bad';
- text = `Tight · ${free.toFixed(0)} GB free`;
- } else if (after < 8) {
- cls = 'is-tight';
- text = `${free.toFixed(0)} GB free · model fits`;
- } else {
- cls = 'is-roomy';
- text = `${free.toFixed(0)} GB free · plenty`;
- }
- } else if (isLocal && isLoaded) {
- tip += `\nChat model loaded${modelName ? ' (' + modelName + ', ~' + (modelGb||0).toFixed(1) + ' GB)' : ''}`;
- if (free < 4 || swapGb >= 8) { cls = 'is-bad'; text = `Tight · ${free.toFixed(0)} GB free`; }
- else if (free < 12) { cls = 'is-tight'; text = `${free.toFixed(0)} GB free`; }
- else { cls = 'is-roomy'; text = `${free.toFixed(0)} GB free`; }
- } else {
- // Remote engine — the chat model isn't on this Mac. Just report
- // raw headroom for the renderer's benefit.
- if (free < 4 || swapGb >= 8) { cls = 'is-bad'; text = `Tight · ${free.toFixed(0)} GB free`; }
- else if (free < 12) { cls = 'is-tight'; text = `${free.toFixed(0)} GB free`; }
- else { cls = 'is-roomy'; text = `${free.toFixed(0)} GB free`; }
- }
- // Append a one-line "what to do about it" hint for amber/red states.
- // Pre-fix the chip went amber with no actionable copy; Salo flagged
- // that "Tight" tells you the symptom but not the move.
- if (cls === 'is-tight') {
- tip += '\n\nTip: switch Engine to plan-and-sleep mode, or pick a smaller chat model.';
- } else if (cls === 'is-bad') {
- tip += '\n\nAction: stop the chat engine (Settings → Stop engine) ' +
- 'or close memory-heavy apps before queuing another render.';
+ _versionRestartPending = true;
+ pill.classList.remove('pill-busy');
+ renderVersionPill();
+ const newVersion = (data.state && (data.state.pull_pulled_to_version || data.state.pull_pulled_to_short)) || 'new version';
+ const fullUpdateNote = data.state && data.state.pull_requires_full_update
+ ? `\n\n⚠ This update touched Python dependencies / patches. Use ` +
+ `Pinokio's Update button (not just Stop+Start) so deps reinstall.`
+ : '';
+ alert(`Pulled to ${newVersion}.\n\nClick Stop, then Start in Pinokio to apply.${fullUpdateNote}`);
+ } catch (e) {
+ pill.classList.remove('pill-busy');
+ renderVersionPill();
+ alert(`Pull failed: ${e.message || e}`);
+ } finally {
+ // Reset the suppression flag so future genuine outages still surface
+ // the banner. Also clear the failure counter so we don't fire on the
+ // very next legit poll because of stale state from the pull window.
+ window._suppressOfflineBanner = false;
+ _POLL_FAILS = 0;
+ // Force one immediate clean poll — also clears any latent banner
+ // that snuck through (e.g. if the page was on a slow tab and missed
+ // a couple seconds of state).
+ _setOfflineBanner(false);
+ if (typeof poll === 'function') poll();
}
- chip.className = 'agent-ram-chip ' + cls;
- chip.title = tip;
- label.textContent = text;
}
-function agentStageRender(status, sess) {
- // Cache the most recent payloads so setOutputsFilter (and other UI
- // toggles) can re-render without a network round-trip.
- if (window.AGENT) {
- window.AGENT.lastStatus = status;
- window.AGENT.lastSession = sess;
- }
- const dot = document.getElementById('agentStageDot');
- const sessionPill = document.getElementById('agentStageSession');
- const nowEl = document.getElementById('agentStageNow');
- const outputsEl = document.getElementById('agentStageOutputs');
- const outputsCountEl = document.getElementById('agentStageOutputsCount');
- const activityEl = document.getElementById('agentStageActivity');
- const activityCountEl = document.getElementById('agentStageActivityCount');
- if (!dot || !nowEl || !outputsEl || !activityEl) return;
-
- const running = !!(status && status.running);
- dot.classList.toggle('live', running);
- if (sessionPill) {
- if (window.AGENT.sessionId) {
- sessionPill.textContent = window.AGENT.sessionId.slice(0, 10);
- } else {
- sessionPill.textContent = 'no session';
- }
- }
-
- // Now rendering. /status returns `current.progress` as an object now:
- // { phase, phase_label, pct (0-100), elapsed_sec, eta_sec, denoise_step, ... }
- // The legacy code path here was calling Number(progressObject) which yields
- // NaN, so the bar always read 0% with phase "rendering" — making the user
- // think nothing was happening even mid-batch. Read the structured fields
- // and fall back gracefully if a future status format ships flat numbers.
- const cur = status && status.current;
- if (running && cur) {
- const p = cur.params || {};
- const label = p.label || (p.preset_label || cur.id || 'render');
- const prog = cur.progress;
- let pct = 0;
- let phase = (cur.status === 'running' ? 'rendering' : '');
- let eta = cur.eta_seconds || cur.eta || null;
- let elapsed = null;
- let denoiseStep = null, denoiseTotal = null;
- if (prog && typeof prog === 'object') {
- pct = Math.max(0, Math.min(100, Number(prog.pct) || 0));
- phase = prog.phase_label || prog.phase || phase;
- eta = prog.eta_sec || prog.remaining_sec || eta;
- elapsed = prog.elapsed_sec || null;
- denoiseStep = prog.denoise_step;
- denoiseTotal = prog.denoise_total;
- } else {
- pct = Math.max(0, Math.min(1, Number(prog) || 0)) * 100;
- }
- // Append step counter when in the denoise phase so progress feels
- // alive even when pct ticks slowly.
- let phaseDetail = phase || 'rendering';
- if (denoiseStep && denoiseTotal) {
- phaseDetail += ` · step ${denoiseStep}/${denoiseTotal}`;
- } else if (elapsed && elapsed >= 5) {
- phaseDetail += ` · ${agentFmtDur(elapsed)} in`;
- }
- nowEl.classList.remove('idle');
- nowEl.innerHTML = `
- <div class="stage-now-label">${escapeHtml(label)}</div>
- <div class="stage-now-meta">${escapeHtml(p.mode || 't2v')} · ${escapeHtml(p.quality || 'balanced')} · ${escapeHtml(p.frames || '?')}f</div>
- <div class="stage-progress-bar">
- <div class="stage-progress-fill" style="width:${pct.toFixed(1)}%"></div>
- </div>
- <div class="stage-progress-text">
- <span>${escapeHtml(phaseDetail)}</span>
- <span>${pct.toFixed(0)}%${eta ? ' · ETA ' + agentFmtDur(eta) : ''}</span>
- </div>
- `;
- } else {
- nowEl.className = 'stage-now-card idle';
- nowEl.innerHTML = `<div>Idle. Ask the agent to plan a shot to see it render here.</div>`;
- }
+// Boot: first /version read happens 2 seconds after DOM ready (gives the
+// panel's startup-delay thread time to complete its first remote check),
+// then every 5 minutes thereafter.
+setTimeout(refreshVersionPill, 2000);
+setInterval(refreshVersionPill, 5 * 60 * 1000);
- // Session outputs — pull from session.tool_state.submitted_shots (ordered)
- // and look up each in /status.history for current state + output_path.
- const tool = (sess && sess.session && sess.session.tool_state) || {};
- const submitted = tool.submitted_shots || [];
- const allJobs = []
- .concat(status && status.queue ? status.queue : [])
- .concat(cur ? [cur] : [])
- .concat(status && status.history ? status.history : []);
- const byId = new Map(allJobs.map(j => [j.id, j]));
- let outputs = submitted.map(s => {
- const j = byId.get(s.job_id) || s;
- const p = (j.params || {});
- return {
- id: s.job_id,
- label: s.label || p.label || s.job_id,
- status: j.status || 'unknown',
- output_path: j.output_path || null,
- mode: p.mode || s.mode || 't2v',
- duration: s.duration_seconds || null,
- };
- });
- // Filter out failed / cancelled / error renders entirely — they were
- // appearing as red "fail" cards alongside real outputs and polluting
- // the gallery. The user explicitly asked to not see them.
- outputs = outputs.filter(o =>
- o.status !== 'failed' && o.status !== 'cancelled' && o.status !== 'error');
- // Deduplicate by label — when the same shot was submitted multiple
- // times (retry, refine, append-take), only the most recent attempt
- // should surface. Prefer entries with status === 'done' over
- // queued/running (the user wants to see WORKING renders, not three
- // copies of the same label in different states). Walk in submission
- // order; keep the LAST seen entry per label, but bias toward 'done'
- // if any entry for that label is done.
- const byLabel = new Map();
- for (const o of outputs) {
- const cur = byLabel.get(o.label);
- if (!cur) { byLabel.set(o.label, o); continue; }
- // Prefer done > running > queued > unknown
- const rank = (s) => s === 'done' ? 3 : s === 'running' ? 2 : s === 'queued' ? 1 : 0;
- if (rank(o.status) >= rank(cur.status)) byLabel.set(o.label, o);
- }
- outputs = Array.from(byLabel.values());
- // Newest-first display — the agent appends to submitted_shots in
- // submission order, so the END of the array is the most recent.
- // Reverse so the top-left of the grid holds the newest clip the
- // user just got, with older flowing right and down. Matches the
- // main gallery's "newest first" convention.
- outputs.reverse();
- // Apply All / Videos / Photos filter (set by setOutputsFilter; persisted
- // to localStorage as 'phos_outputs_filter'). Video modes: t2v / i2v /
- // keyframe / extend (or anything that's not 'image'); photo mode is
- // 'image'. Falls back to filename suffix when mode is missing — older
- // sessions don't always record one.
- const outputsFilter = (window.outputsFilter || 'all');
- const isPhotoOutput = (o) => {
- if (o.mode === 'image') return true;
- if (o.mode === 't2v' || o.mode === 'i2v' || o.mode === 'keyframe' || o.mode === 'extend') return false;
- const path = (o.output_path || '').toLowerCase();
- if (/\.(png|jpg|jpeg|webp)$/.test(path)) return true;
- if (/\.mp4$/.test(path)) return false;
- return false;
+// ====== Modal reliability scaffold ======
+// One global scaffold for all 8 modals on the panel (.models-modal,
+// .model-browser-modal, .expand-lightbox). Covers three things the
+// individual open/close functions didn't:
+// 1. Esc closes the topmost-visible modal.
+// 2. Tab/Shift-Tab cycles focus inside the modal (no escape into
+// the form behind it).
+// 3. body.modal-open is toggled whenever any modal is visible so
+// CSS can lock background scroll.
+// No need to patch each open/close fn — a MutationObserver watches
+// inline style changes on the modals themselves; whoever toggles
+// display gets the side-effects for free.
+(function _phosModalScaffold() {
+ const MODAL_SEL = '.models-modal, .model-browser-modal, .expand-lightbox';
+ const isVisible = el => {
+ const d = el.style.display;
+ // Some modals open by adding an .open class (.model-browser-modal);
+ // others toggle the inline style. Cover both.
+ if (el.classList.contains('open')) return true;
+ return d === 'flex' || d === 'block';
+ };
+ const visibleModals = () =>
+ Array.from(document.querySelectorAll(MODAL_SEL)).filter(isVisible);
+ const topVisible = () => {
+ const v = visibleModals();
+ return v.length ? v[v.length - 1] : null;
+ };
+ const FOCUSABLE = 'button:not([disabled]), [href], input:not([disabled]):not([type="hidden"]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])';
+ const refreshScrollLock = () => {
+ document.body.classList.toggle('modal-open', visibleModals().length > 0);
};
- const filteredOutputs = outputs.filter(o => {
- if (outputsFilter === 'all') return true;
- return outputsFilter === 'photos' ? isPhotoOutput(o) : !isPhotoOutput(o);
+ // Wire a single MutationObserver per modal element. Cheaper than a
+ // global subtree observer and avoids the cost of body-wide attribute
+ // tracking. Lazy — modals added later (none today, but defensive)
+ // need to re-register.
+ document.querySelectorAll(MODAL_SEL).forEach(el => {
+ new MutationObserver(refreshScrollLock).observe(el, {
+ attributes: true,
+ attributeFilter: ['style', 'class'],
+ });
});
- // Count badge mirrors the active filter so users see e.g.
- // "Session outputs · 23 photos" while Photos is selected.
- if (outputsFilter === 'all') {
- outputsCountEl.textContent = filteredOutputs.length;
- } else {
- outputsCountEl.textContent = `${filteredOutputs.length} ${outputsFilter}`;
- }
- if (filteredOutputs.length === 0) {
- const emptyMsg = outputsFilter === 'photos' ? 'No photo renders yet.'
- : outputsFilter === 'videos' ? 'No video renders yet.'
- : 'No mp4s rendered yet. Submit a shot from the chat.';
- outputsEl.innerHTML = `<div class="stage-empty">${emptyMsg}</div>`;
- } else {
- outputs = filteredOutputs;
- outputsEl.innerHTML = '';
- // No display cap — the count and the rendered cells must agree.
- // The grid is auto-fill so it wraps; the parent stage pane scrolls.
- // Earlier code sliced at 24 "for performance" but the user (rightly)
- // saw count=45 with 25 cards visible and asked where the rest went.
- for (const o of outputs) {
- const cell = document.createElement('div');
- const failed = o.status === 'error' || o.status === 'failed' || o.status === 'cancelled';
- cell.className = 'stage-output-cell' + (failed ? ' failed' : '');
- cell.title = o.label + ' · ' + o.status;
- // If we have a finished output_path, show the media as a thumbnail.
- // Use <img> for photo outputs and <video> for video outputs — without
- // this branch, .png paths stuffed into a <video> tag rendered as
- // empty cells when the user picked the Photos filter.
- if (o.output_path && o.status === 'done') {
- if (isPhotoOutput(o)) {
- const im = document.createElement('img');
- im.className = 'vid';
- im.src = '/file?path=' + encodeURIComponent(o.output_path);
- im.loading = 'lazy';
- im.alt = o.label || 'photo output';
- cell.appendChild(im);
- // Click on photo: open full-size in a new tab (lightbox is
- // video-only). Cheapest viewer that works with /file?path=…
- // and the cache-bust headers already set on that endpoint.
- cell.addEventListener('click', () => {
- window.open('/file?path=' + encodeURIComponent(o.output_path), '_blank', 'noopener');
- });
- // Animate button (overlay top-right): pre-fill the i2v form
- // with this still as the reference. Mirrors the Recent tab's
- // Animate flow from commit 0d9c6eb so users have one button
- // to "animate this picture" no matter where they click from.
- const anim = document.createElement('button');
- anim.type = 'button';
- anim.className = 'refine-btn';
- anim.title = 'Animate this still — pre-fill the i2v form';
- anim.innerHTML = '<svg class="ph" aria-hidden="true"><use href="#ph-play-fill"/></svg>';
- anim.addEventListener('click', (e) => {
- e.stopPropagation();
- if (typeof animateFromPhoto === 'function') {
- animateFromPhoto({path: o.output_path, prompt: ''});
- }
- });
- cell.appendChild(anim);
- } else {
- const v = document.createElement('video');
- v.className = 'vid';
- v.src = '/file?path=' + encodeURIComponent(o.output_path);
- v.preload = 'metadata';
- v.muted = true;
- cell.appendChild(v);
- cell.addEventListener('click', () => agentStageLightboxOpen(o.output_path, o.label, o.id));
- // Refine button (overlay top-right): "give me a variation of this clip"
- const refine = document.createElement('button');
- refine.type = 'button';
- refine.className = 'refine-btn';
- refine.title = 'Refine this clip — start a variation in the chat';
- refine.innerHTML = '<svg class="ph" aria-hidden="true"><use href="#ph-arrow-clockwise-bold"/></svg>';
- refine.addEventListener('click', (e) => {
- e.stopPropagation();
- agentSetRefine({jobId: o.id, label: o.label, clipPath: o.output_path});
- });
- cell.appendChild(refine);
- }
- } else {
- cell.style.display = 'flex';
- cell.style.alignItems = 'center';
- cell.style.justifyContent = 'center';
- const span = document.createElement('span');
- span.style.cssText = 'color:var(--muted); font-size:11px; font-style:italic;';
- span.textContent = failed ? 'failed' : (o.status === 'running' ? 'rendering…' : 'queued');
- cell.appendChild(span);
- }
- const badge = document.createElement('span');
- badge.className = 'badge';
- if (failed) {
- badge.textContent = 'fail';
- } else if (o.status === 'done') {
- badge.innerHTML = '<svg class="ph" aria-hidden="true"><use href="#ph-check-bold"/></svg>';
- } else {
- badge.textContent = o.status.slice(0, 4);
- }
- cell.appendChild(badge);
- const lbl = document.createElement('span');
- lbl.className = 'label';
- lbl.textContent = o.label;
- cell.appendChild(lbl);
- outputsEl.appendChild(cell);
- }
- }
-
- // Activity feed — derive from rendered_messages: each tool_call/tool_result
- // becomes one row with an icon. Newest at the top.
- const rendered = (sess && sess.rendered_messages) || [];
- const events = [];
- for (let i = rendered.length - 1; i >= 0 && events.length < 40; i--) {
- const m = rendered[i];
- if (m.kind === 'tool_result') {
- const r = m.result || {};
- const ok = r.ok !== false && !r.error;
- const inner = r.result || {};
- let txt;
- if (typeof inner === 'object' && 'job_id' in inner) {
- txt = `→ queued ${inner.job_id} · ${inner.estimated_wall_human || '?'}`;
- } else if (typeof inner === 'object' && 'manifest_path' in inner) {
- txt = `→ manifest written (${inner.shot_count} shots)`;
- } else if (typeof inner === 'object' && 'png_path' in inner) {
- txt = `→ frame extracted (${inner.frame_index})`;
- } else if (typeof inner === 'object' && 'candidates' in inner) {
- txt = `→ ${inner.candidates.length} candidates ready`;
- } else if (!ok) {
- txt = (r.error || 'failed').slice(0, 80);
- } else {
- txt = '→ result';
- }
- events.push({ kind: ok ? 'ok' : 'fail', text: txt });
- } else if (m.kind === 'assistant' && m.tool_call) {
- events.push({ kind: 'run', text: m.tool_call.tool });
- }
- }
- activityCountEl.textContent = events.length;
- if (events.length === 0) {
- activityEl.innerHTML = `<div class="stage-empty">No tool calls yet.</div>`;
- } else {
- activityEl.innerHTML = '';
- for (const ev of events) {
- const row = document.createElement('div');
- row.className = 'stage-activity-row ' + ev.kind;
- const iconRef = (ev.kind === 'ok') ? '#ph-check-bold' : (ev.kind === 'fail') ? '#ph-x-circle-fill' : '#ph-gear-six';
- row.innerHTML = `
- <span class="icon"><svg class="ph" aria-hidden="true"><use href="${iconRef}"/></svg></span>
- <span class="text">${escapeHtml(ev.text)}</span>
- `;
- activityEl.appendChild(row);
- }
- }
-}
-
-function agentFmtDur(seconds) {
- const s = Math.max(0, Math.round(Number(seconds) || 0));
- if (s < 60) return s + 's';
- const m = Math.floor(s / 60), rem = s % 60;
- if (m < 60) return m + 'm ' + (rem < 10 ? '0' : '') + rem + 's';
- const h = Math.floor(m / 60), mr = m % 60;
- return h + 'h ' + (mr < 10 ? '0' : '') + mr + 'm';
-}
+ refreshScrollLock();
-// Track which clip is currently in the lightbox so the Refine button
-// has something to reference when clicked.
-window.AGENT_STAGE.lightboxCurrent = null;
-
-function agentStageLightboxOpen(path, label, jobId) {
- const lb = document.getElementById('agentStageLightbox');
- const v = document.getElementById('agentStageLightboxVideo');
- if (!lb || !v) return;
- v.src = '/file?path=' + encodeURIComponent(path);
- v.title = label || '';
- window.AGENT_STAGE.lightboxCurrent = {jobId: jobId || null, label: label || '', clipPath: path};
- lb.classList.add('open');
- v.play().catch(() => {});
-}
+ // Esc closes the topmost modal. We find the close button inside it
+ // and click it (preserves any per-modal cleanup logic — settings
+ // save, civitai abort, etc.). Fall back to hiding the element if no
+ // close button is found.
+ document.addEventListener('keydown', e => {
+ if (e.key !== 'Escape') return;
+ const top = topVisible();
+ if (!top) return;
+ e.preventDefault();
+ e.stopPropagation();
+ const closeBtn =
+ top.querySelector('button[onclick*="close"]') ||
+ top.querySelector('.close-btn') ||
+ top.querySelector('.expand-close');
+ if (closeBtn) closeBtn.click();
+ else { top.style.display = 'none'; top.classList.remove('open'); }
+ });
-function agentStageLightboxClose() {
- const lb = document.getElementById('agentStageLightbox');
- const v = document.getElementById('agentStageLightboxVideo');
- if (!lb || !v) return;
- v.pause();
- v.src = '';
- window.AGENT_STAGE.lightboxCurrent = null;
- lb.classList.remove('open');
-}
+ // Focus trap — when a modal is visible, Tab cycles inside it.
+ document.addEventListener('keydown', e => {
+ if (e.key !== 'Tab') return;
+ const top = topVisible();
+ if (!top) return;
+ const focusables = Array.from(top.querySelectorAll(FOCUSABLE))
+ .filter(el => el.offsetWidth > 0 || el.offsetHeight > 0);
+ if (!focusables.length) return;
+ const first = focusables[0];
+ const last = focusables[focusables.length - 1];
+ const active = document.activeElement;
+ if (e.shiftKey && (active === first || !top.contains(active))) {
+ e.preventDefault();
+ last.focus();
+ } else if (!e.shiftKey && (active === last || !top.contains(active))) {
+ e.preventDefault();
+ first.focus();
+ }
+ });
+})();
-function agentStageLightboxRefine() {
- const cur = window.AGENT_STAGE.lightboxCurrent;
- if (!cur) return;
- agentStageLightboxClose();
- agentSetRefine(cur);
-}
+// ====== Init ======
+// Skip poll when the tab is backgrounded — at 1.5s cadence with a fan-
+// spinning render in the background, every saved request matters. Pinokio
+// users park the panel in a tab and switch to other apps for the 5–20 min
+// a render takes; nothing in the UI needs updating until they come back.
+// `visibilitychange` fires immediately when the user returns so the chrome
+// catches up on the first frame.
+setInterval(() => { if (!document.hidden) poll(); }, 1500);
+document.addEventListener('visibilitychange', () => { if (!document.hidden) poll(); });
-// ---- Composer reference chip — "Refine this clip" -----------------------
-// When the user clicks ↻ on a stage output (or the Refine button in the
-// lightbox), we set a refine reference. The chip shows above the textarea;
-// on next Send, the user's message is prepended with "Refine <job_id>: "
-// so the agent calls inspect_clip and treats the rest as the requested
-// modification. Clear with × on the chip.
-window.AGENT_REFINE = null; // {jobId, label, clipPath}
-
-function agentSetRefine(ref) {
- window.AGENT_REFINE = ref;
- const chip = document.getElementById('agentRefChip');
- const lbl = document.getElementById('agentRefChipLabel');
- if (!chip || !lbl) return;
- lbl.textContent = ref.label || ref.jobId || ref.clipPath || 'clip';
- lbl.title = ref.jobId ? `${ref.label || ''} · ${ref.jobId}` : ref.clipPath;
- chip.classList.add('visible');
- // Bring focus to the composer so the user can type their refinement.
- const ta = document.getElementById('agentInput');
- if (ta) {
- ta.placeholder = 'How should this clip be different? (e.g. "more pause", "warmer light", "longer take")';
- setTimeout(() => ta.focus(), 50);
+// Delegated click handler for the failed Now-card action buttons.
+// Inline `onclick` attributes on these buttons were fragile — the
+// failed branch of poll() rewrites .ttl's innerHTML every 1.5s, and a
+// click that landed mid-rewrite could be lost. A single delegated
+// listener on document survives every rewrite + costs nothing.
+document.addEventListener('click', (e) => {
+ const btn = e.target.closest('[data-action="retry"], [data-action="dismiss"]');
+ if (!btn) return;
+ e.stopPropagation();
+ e.preventDefault();
+ const actions = btn.closest('.now-card-actions');
+ const id = actions ? actions.dataset.jobId : '';
+ if (!id) return;
+ if (btn.dataset.action === 'retry') {
+ if (typeof retryJob === 'function') retryJob(id);
+ } else {
+ window._dismissedFailureId = id;
+ if (typeof poll === 'function') poll();
}
-}
+});
-function agentClearRefine() {
- window.AGENT_REFINE = null;
- const chip = document.getElementById('agentRefChip');
- if (chip) chip.classList.remove('visible');
- const ta = document.getElementById('agentInput');
- if (ta) ta.placeholder = 'Paste a script, or describe a piece. The agent will plan, estimate the wall time, and queue overnight.';
-}
+poll();
+setMode('t2v');
+setAspect('landscape'); // sets aspect first so the default preset orients correctly
+setQuality('balanced'); // bundles quality + dims; respects current aspect
+applyTierTimes(); // rewrite Quality pill subtitles to match this Mac
+updateCustomizeSummary();
+updateDerived();
-// Esc closes the stage lightbox first (before falling through to the
-// settings modal / fullscreen exit handlers).
-document.addEventListener('keydown', (e) => {
- if (e.key === 'Escape') {
- const lb = document.getElementById('agentStageLightbox');
- if (lb && lb.classList.contains('open')) {
- agentStageLightboxClose();
- e.stopPropagation();
- }
- }
-}, true);
+// Wire the picker components (I2V image + FFLF start/end) and seed the
+// "Recent uploads" strip. The strip is shared across all three pickers,
+// so dropping a new image in one slot makes it instantly clickable in
+// the other two.
+PICKERS.forEach(pickerWire);
+refreshUploadsStrip();
+// Refresh the strip whenever a render finishes (queue/history changes
+// don't fire here), and whenever the user opens FFLF — covers the case
+// where they uploaded something via I2V, then switched to FFLF.
+document.querySelectorAll('#modeGroup .pill-btn').forEach(b => b.addEventListener('click', refreshUploadsStrip));
-// ---- Pop out to system browser -------------------------------------------
-// The pop-out is a real <a target="_blank"> link (set up during boot via
-// agentInitPopOut). The browser handles the actual navigation as a user
-// gesture so popup-blockers don't kick in. This handler just sets the
-// localStorage flags so the new tab boots straight into Agentic Flows +
-// fullscreen.
-function agentPopOutFlagsBeforeNavigate() {
- try {
- localStorage.setItem('phos_workflow', 'agent');
- localStorage.setItem('phos_agent_fullscreen', '1');
- } catch(e) {}
- // The <a href> handles navigation. Don't preventDefault.
-}
-function agentInitPopOut() {
- const a = document.getElementById('agentPopOutBtn');
- if (!a) return;
- a.href = window.location.origin || ('http://127.0.0.1:' + window.location.port);
-}
-// Run on every page load; cheap and idempotent.
-if (document.readyState === 'loading') {
- document.addEventListener('DOMContentLoaded', agentInitPopOut);
-} else {
- agentInitPopOut();
-}
+// ============================================================================
+// Workflow tabs — Manual / Characters / Train
+// ============================================================================
+// The in-panel agentic chat surface was removed 2026-05-15 (tag
+// pre-agent-removal-2026-05-15). External agents drive Phosphene via the
+// HTTP API in docs/API.md. The tab switcher now flips between three
+// surfaces: the manual generate form, the Characters tab (LoRA pair +
+// prompt + ship), and Train (character LoRA training).
-// ---- Fullscreen / focus mode ---------------------------------------------
-function agentToggleFullscreen(force) {
- // `force === true` to enter, `false` to exit, undefined to toggle
- const cur = document.body.classList.contains('agent-fullscreen');
- const next = (typeof force === 'boolean') ? force : !cur;
- document.body.classList.toggle('agent-fullscreen', next);
- const btn = document.getElementById('agentFullscreenBtn');
- if (btn) btn.title = next ? 'Exit fullscreen (Esc)' : 'Expand to fullscreen';
- const ix = document.getElementById('agentFullscreenIconExpand');
- const iy = document.getElementById('agentFullscreenIconCollapse');
- if (ix) ix.style.display = next ? 'none' : '';
- if (iy) iy.style.display = next ? '' : 'none';
- try { localStorage.setItem('phos_agent_fullscreen', next ? '1' : ''); } catch(e) {}
- // When ENTERING fullscreen, populate the sessions sidebar — it's
- // always visible in fullscreen, but the list renders empty until
- // aspOpen() fetches /agent/sessions. Fixed 2026-05-07 per Salo's
- // screenshot showing a blank sidebar with just a search box.
- if (next && typeof aspOpen === 'function') {
- aspOpen();
+function workflowSwitch(name) {
+ document.querySelectorAll('#workflowTabs button[data-workflow]')
+ .forEach(b => b.classList.toggle('active', b.dataset.workflow === name));
+ const manual = document.getElementById('genForm');
+ const studio = document.getElementById('studioSection');
+ const train = document.getElementById('trainSection');
+ const characters = document.getElementById('charactersSection');
+ // Set body data attribute so CSS can switch the layout per workflow.
+ document.body.setAttribute('data-workflow', name);
+ // Studio is an inline pane inside form-pane — when leaving Manual it
+ // must hide too. Train and Characters are full-pane workflows that
+ // own their own section.
+ if (studio) studio.classList.remove('show');
+ if (train) train.classList.remove('show');
+ if (characters) characters.classList.remove('show');
+ if (name === 'characters') {
+ if (manual) manual.style.display = 'none';
+ if (characters) characters.classList.add('show');
+ if (typeof charactersInit === 'function') charactersInit();
+ } else if (name === 'train') {
+ // Train Character is its own workflow tier. Hide the manual render
+ // form, show the train section, run its init.
+ if (manual) manual.style.display = 'none';
+ if (train) train.classList.add('show');
+ if (typeof trainInit === 'function') trainInit();
+ } else {
+ if (manual) manual.style.display = '';
}
- // After collapse animation settles, scroll chat to bottom so the
- // user keeps their place.
- requestAnimationFrame(() => {
- const chat = document.getElementById('agentChat');
- if (chat) chat.scrollTop = chat.scrollHeight;
- });
+ try { localStorage.setItem('phos_workflow', name); } catch(e) {}
}
-// Esc handler: priority is modal-close > fullscreen-exit. So Esc to
-// dismiss the settings drawer doesn't drop the user out of fullscreen
-// at the same time.
-document.addEventListener('keydown', (e) => {
- if (e.key !== 'Escape') return;
- const modal = document.getElementById('agentSettingsModal');
- if (modal && modal.classList.contains('open')) {
- closeAgentSettings();
- return;
- }
- if (document.body.classList.contains('agent-fullscreen')) {
- agentToggleFullscreen(false);
- }
+document.querySelectorAll('#workflowTabs button[data-workflow]').forEach(b => {
+ b.addEventListener('click', () => workflowSwitch(b.dataset.workflow));
});
+
// Initial workflow tab restore from localStorage.
try {
const saved = localStorage.getItem('phos_workflow');
- if (saved === 'agent') workflowSwitch('agent');
- // NOTE: fullscreen is NOT auto-restored from localStorage. The
- // earlier behaviour ("remember it across reloads") was confusing —
- // users opening the panel from Pinokio saw an unexpected
- // chat-only layout with the regular chrome hidden, and didn't know
- // why or how to get back to the split view (Manual + Agentic Flows
- // tabs are hidden in fullscreen, so the toggle is hard to find).
- // Fullscreen is now strictly opt-in per session via the icon button
- // in the agent header. We DO clear any stale flag so users who
- // toggled it on once before this change get a clean slate.
+ if (saved === 'characters' || saved === 'train') {
+ workflowSwitch(saved);
+ }
+ // Clear any stale agent-fullscreen flag from the removed chat surface.
try { localStorage.removeItem('phos_agent_fullscreen'); } catch(e) {}
} catch(e) {}
</script>