Open-source AI podcast clipper. Generate vertical clips with face tracking and burned-in captions. CLI, MCP server, web app.
Python ai-toolsauto-captionscaptionscliffmpegmcpmcp-serveropusclip-alternativepodcast-clipspodcastsshortform-videovertical-videowhisper
Asset library: logos, outros, intros, music across UI, MCP, and CLI (#62)
Nika Siradzeb1dc8ac134fe
diff --git a/.gitignore b/.gitignoreindex 6312001..09a8dd4 100644--- a/.gitignore+++ b/.gitignore@@ -58,6 +58,7 @@ cli/internal/backend/files/cli/internal/podstack/commands/cli/podclipodcli-clips/+reel_*/# generated by scripts/gen-docs-manifest.mjsdocs-manifest.jsondiff --git a/backend/cli.py b/backend/cli.pyindex 10eab60..a7b27df 100644--- a/backend/cli.py+++ b/backend/cli.py@@ -548,6 +548,21 @@ def cmd_process(args):auto_outro = default_outro()if auto_outro:config["outro_path"] = auto_outro+ if getattr(args, "intro", None):+ from services.asset_store import resolve as resolve_asset_intro+ resolved = resolve_asset_intro(args.intro)+ if resolved:+ config["intro_path"] = resolved+ else:+ print(f" Warning: Intro '{args.intro}' not found (checked assets and filesystem)", file=sys.stderr)+ config["intro_path"] = args.intro+ elif not config.get("intro_path"):+ from services.profiles import get_profile as _get_profile_intro+ if _get_profile_intro(config.get("profile")).candidate_source != "saliency":+ from services.asset_store import default_intro+ auto_intro = default_intro()+ if auto_intro:+ config["intro_path"] = auto_introif args.time_adjust is not None:config["time_adjust"] = args.time_adjustif args.no_energy:@@ -943,6 +958,7 @@ def cmd_process(args):output_dir=output_dir,logo_path=config.get("logo_path") or None,outro_path=config.get("outro_path") or None,+ intro_path=config.get("intro_path") or None,keep_segments=clip.get("segments"),face_map=face_map,allow_ass_fallback=config.get("allow_ass_fallback", False),@@ -1156,6 +1172,7 @@ def cmd_process(args):output_dir=output_dir,logo_path=config.get("logo_path") or None,outro_path=config.get("outro_path") or None,+ intro_path=config.get("intro_path") or None,keep_segments=clip.get("segments"),face_map=face_map,allow_ass_fallback=config.get("allow_ass_fallback", False),@@ -1480,6 +1497,7 @@ def _post_render_loop(output_dir=output_dir,logo_path=config.get("logo_path") or None,outro_path=config.get("outro_path") or None,+ intro_path=config.get("intro_path") or None,keep_segments=clip.get("segments"),face_map=face_map,allow_ass_fallback=config.get("allow_ass_fallback", False),@@ -1665,6 +1683,7 @@ def _post_render_loop(output_dir=output_dir,logo_path=config.get("logo_path") or None,outro_path=config.get("outro_path") or None,+ intro_path=config.get("intro_path") or None,keep_segments=f_clip.get("segments"),face_map=face_map,allow_ass_fallback=config.get("allow_ass_fallback", False),@@ -1720,6 +1739,7 @@ def _post_render_loop(output_dir=output_dir,logo_path=config.get("logo_path") or None,outro_path=config.get("outro_path") or None,+ intro_path=config.get("intro_path") or None,keep_segments=nc.get("segments"),face_map=face_map,allow_ass_fallback=config.get("allow_ass_fallback", False),@@ -2076,6 +2096,9 @@ def cmd_presets(args):if args.outro:from services.asset_store import resolve as _resolve_outroconfig["outro_path"] = _resolve_outro(args.outro) or args.outro+ if getattr(args, "intro", None):+ from services.asset_store import resolve as _resolve_intro+ config["intro_path"] = _resolve_intro(args.intro) or args.introif args.top:config["top_clips"] = args.topif args.time_adjust is not None:@@ -2134,8 +2157,11 @@ def cmd_presets(args):def cmd_assets(args):- """Manage named assets (logos, intros, outros)."""- from services.asset_store import register, unregister, list_assets, resolve+ """Manage named assets (logos, intros, outros, music)."""+ from services.asset_store import (+ register, import_file, import_url, unregister, list_assets,+ resolve, set_default, clear_default, rename as rename_asset,+ )accent = "\033[38;2;212;135;74m"gray = "\033[38;5;245m"@@ -2154,24 +2180,69 @@ def cmd_assets(args):for a in assets:exists = os.path.exists(a["path"])status = f"{green}✓{reset}" if exists else "\033[38;2;248;113;113m✗ missing\033[0m"- print(f" {accent}{a['name']}{reset} {gray}({a['type']}){reset} {status}")+ star = f" {accent}★ default{reset}" if a.get("default") else ""+ print(f" {accent}{a['name']}{reset} {gray}({a['type']}){reset} {status}{star}")print(f" {gray}{a['path']}{reset}")print()print(f" {gray}Use in commands:{reset} {accent}--logo mylogo{reset} {gray}or{reset} {accent}--outro myoutro{reset}")print()elif args.assets_action == "add":- name = args.name- file_path = args.path- asset_type = getattr(args, "type", "auto") or "auto"+ asset_type = getattr(args, "type", None) or "auto"try:- asset = register(name, file_path, asset_type)- print(f"\n {green}✓{reset} Registered {accent}{name}{reset} ({asset['type']})")+ fn = import_file if getattr(args, "copy", False) else register+ asset = fn(args.name, args.path, asset_type)+ print(f"\n {green}✓{reset} Registered {accent}{args.name}{reset} ({asset['type']})")print(f" {gray}{asset['path']}{reset}\n")except FileNotFoundError as e:print(f"\n ✗ {e}\n", file=sys.stderr)sys.exit(1)+ elif args.assets_action == "add-url":+ asset_type = getattr(args, "type", None) or "auto"+ try:+ print(f"\n Downloading {gray}{args.url}{reset} ...")+ asset = import_url(args.url, args.name, asset_type)+ print(f" {green}✓{reset} Imported {accent}{args.name}{reset} ({asset['type']})")+ print(f" {gray}{asset['path']}{reset}\n")+ except Exception as e:+ print(f"\n ✗ {e}\n", file=sys.stderr)+ sys.exit(1)++ elif args.assets_action == "default":+ asset = set_default(args.name)+ if asset:+ print(f"\n {green}✓{reset} {accent}{args.name}{reset} is now the default {asset['type']}\n")+ else:+ print(f"\n '{args.name}' not found\n", file=sys.stderr)+ sys.exit(1)++ elif args.assets_action == "undefault":+ if clear_default(args.name):+ print(f"\n {green}✓{reset} Cleared default on {accent}{args.name}{reset}\n")+ else:+ print(f"\n '{args.name}' is not a default\n")++ elif args.assets_action == "rename":+ try:+ asset = rename_asset(args.name, args.new_name)+ print(f"\n {green}✓{reset} Renamed to {accent}{asset['name']}{reset}\n")+ except (KeyError, ValueError) as e:+ print(f"\n ✗ {e}\n", file=sys.stderr)+ sys.exit(1)++ elif args.assets_action == "export":+ src = resolve(args.name)+ if not src:+ print(f"\n ✗ Not found: {args.name}\n", file=sys.stderr)+ sys.exit(1)+ dest = args.dest+ if os.path.isdir(dest):+ dest = os.path.join(dest, os.path.basename(src))+ import shutil+ shutil.copyfile(src, dest)+ print(f"\n {green}✓{reset} Exported {accent}{args.name}{reset} → {gray}{dest}{reset}\n")+elif args.assets_action == "remove":if unregister(args.name):print(f"\n ✓ Removed '{args.name}'\n")@@ -3465,6 +3536,7 @@ def main():proc.add_argument("--logo", help="Logo image (asset name or path)")proc.add_argument("--outro", help="Outro video (asset name or path)")proc.add_argument("--no-outro", action="store_true", help="Do not append an outro (default for highlight profiles)")+ proc.add_argument("--intro", help="Intro video (asset name or path)")proc.add_argument("--time-adjust", type=float, help="Timestamp offset in seconds")proc.add_argument("--no-energy", action="store_true", help="Skip audio energy analysis")proc.add_argument("--no-speakers", action="store_true", help="Skip speaker detection (faster, uses face detection only)")@@ -3545,6 +3617,7 @@ def main():pre_save.add_argument("--crop", choices=["center", "face", "speaker", "speaker-hardcut"])pre_save.add_argument("--logo", help="Logo (asset name or path)")pre_save.add_argument("--outro", help="Outro (asset name or path)")+ pre_save.add_argument("--intro", help="Intro (asset name or path)")pre_save.add_argument("--top", type=int, help="Default top clips count")pre_save.add_argument("--time-adjust", type=float)pre_save.add_argument("--quality", choices=["low", "medium", "high", "max"])@@ -3564,12 +3637,34 @@ def main():ast = sub.add_parser("assets", help="Manage named assets (logos, intros, outros)")ast_sub = ast.add_subparsers(dest="assets_action")+ _asset_types = ["logo", "outro", "intro", "music", "image", "audio", "other"]+ast_list = ast_sub.add_parser("list", help="List all registered assets")ast_add = ast_sub.add_parser("add", help="Register a file as a named asset")ast_add.add_argument("name", help="Short name (e.g., 'mylogo', 'outro')")ast_add.add_argument("path", help="Path to file")- ast_add.add_argument("--type", choices=["logo", "video", "image", "audio", "other"], help="Asset type (default: auto-detect)")+ ast_add.add_argument("--type", choices=_asset_types, help="Asset type (default: auto-detect)")+ ast_add.add_argument("--copy", action="store_true", help="Copy the file into .podcli/assets/ instead of referencing it in place")++ ast_url = ast_sub.add_parser("add-url", help="Download a URL into the asset library")+ ast_url.add_argument("name", help="Short name (e.g., 'outro')")+ ast_url.add_argument("url", help="Remote URL (direct file or video URL)")+ ast_url.add_argument("--type", choices=_asset_types, help="Asset type (default: auto-detect)")++ ast_default = ast_sub.add_parser("default", help="Mark an asset the default for its type")+ ast_default.add_argument("name")++ ast_undefault = ast_sub.add_parser("undefault", help="Clear an asset's default flag")+ ast_undefault.add_argument("name")++ ast_rename = ast_sub.add_parser("rename", help="Rename a registered asset")+ ast_rename.add_argument("name")+ ast_rename.add_argument("new_name")++ ast_export = ast_sub.add_parser("export", help="Copy an asset's file out to a destination")+ ast_export.add_argument("name")+ ast_export.add_argument("dest", help="Destination file or directory")ast_rm = ast_sub.add_parser("remove", help="Remove a named asset")ast_rm.add_argument("name")@@ -4305,7 +4400,7 @@ def _interactive_process():outro = Nonetry:from services.asset_store import list_assets as list_assets_o- outros = [a for a in list_assets_o() if a["type"] == "video" and os.path.exists(a["path"])]+ outros = [a for a in list_assets_o() if a["type"] in ("outro", "video") and os.path.exists(a["path"])]if outros:outro_choices = [questionary.Choice("None", value=None)]outro_choices += [questionary.Choice(f"{a['name']} ({os.path.basename(a['path'])})", value=a["path"]) for a in outros]@@ -4464,7 +4559,9 @@ def _interactive_assets():"""Interactive asset management using questionary."""import questionaryfrom questionary import Style- from services.asset_store import register, unregister, list_assets+ from services.asset_store import (+ register, import_url, unregister, list_assets, set_default,+ )green = "\033[38;2;74;222;128m"gray = "\033[38;5;245m"@@ -4488,11 +4585,16 @@ def _interactive_assets():for a in current:exists = os.path.exists(a["path"])icon = f"{green}✓{reset}" if exists else f"{red}✗{reset}"- print(f" {icon} {accent}{a['name']}{reset} {gray}({a['type']}) {os.path.basename(a['path'])}{reset}")+ star = f" {accent}★{reset}" if a.get("default") else ""+ print(f" {icon} {accent}{a['name']}{reset} {gray}({a['type']}) {os.path.basename(a['path'])}{reset}{star}")print()- actions = [questionary.Choice("Add asset", value="add")]+ actions = [+ questionary.Choice("Add asset from file", value="add"),+ questionary.Choice("Add asset from URL", value="add-url"),+ ]if current:+ actions.append(questionary.Choice("Set default", value="default"))actions.append(questionary.Choice("Remove asset", value="remove"))actions.append(questionary.Choice("← Back", value="_back"))@@ -4515,6 +4617,28 @@ def _interactive_assets():except FileNotFoundError as e:print(f"\n {red}✗{reset} {e}\n", file=sys.stderr)+ elif action == "add-url":+ name = questionary.text("Asset name (e.g. outro):", style=qstyle).ask()+ if not name:+ return+ url = questionary.text("URL:", style=qstyle).ask()+ if not url:+ return+ try:+ print(f"\n Downloading ...")+ asset = import_url(url, name)+ print(f" {green}✓{reset} Imported {accent}{name}{reset} ({asset['type']})")+ print(f" {gray}{asset['path']}{reset}\n")+ except Exception as e:+ print(f"\n {red}✗{reset} {e}\n", file=sys.stderr)++ elif action == "default":+ choices = [questionary.Choice(f"{a['name']} ({a['type']})", value=a["name"]) for a in current]+ pick = questionary.select("Default for its type:", choices=choices, style=qstyle).ask()+ if pick:+ asset = set_default(pick)+ print(f"\n {green}✓{reset} {accent}{pick}{reset} is now the default {asset['type']}\n")+elif action == "remove":choices = [questionary.Choice(f"{a['name']} ({a['type']})", value=a["name"]) for a in current]to_remove = questionary.select("Remove which?", choices=choices, style=qstyle).ask()@@ -4632,7 +4756,7 @@ def _interactive_presets():# Outro from assetstry:from services.asset_store import list_assets as list_assets_o- outros = [a for a in list_assets_o() if a["type"] == "video" and os.path.exists(a["path"])]+ outros = [a for a in list_assets_o() if a["type"] in ("outro", "video") and os.path.exists(a["path"])]if outros:outro_choices = [questionary.Choice("None", value="")]outro_choices += [questionary.Choice(f"{a['name']} ({os.path.basename(a['path'])})", value=a["path"]) for a in outros]diff --git a/backend/main.py b/backend/main.pyindex f73be5f..22744b2 100644--- a/backend/main.py+++ b/backend/main.py@@ -133,6 +133,7 @@ def handle_transcribe(task_id: str, params: dict):def handle_create_clip(task_id: str, params: dict):"""Create a single finished short-form clip."""from services.clip_generator import generate_clip+ from services import asset_storeemit_progress(task_id, "starting", 0, "Preparing clip...")result = generate_clip(@@ -146,8 +147,9 @@ def handle_create_clip(task_id: str, params: dict):transcript_words=params.get("transcript_words", []),title=params.get("title", "clip"),output_dir=params.get("output_dir"),- logo_path=params.get("logo_path"),- outro_path=params.get("outro_path"),+ logo_path=asset_store.resolve(params.get("logo_path")),+ outro_path=asset_store.resolve(params.get("outro_path")),+ intro_path=asset_store.resolve(params.get("intro_path")),clean_fillers=params.get("clean_fillers", True),face_map=params.get("face_map"),keep_segments=params.get("keep_segments"),@@ -162,6 +164,7 @@ def handle_create_clip(task_id: str, params: dict):def handle_batch_clips(task_id: str, params: dict):"""Create multiple clips in sequence."""from services.clip_generator import generate_clip+ from services import asset_storeclips = params["clips"]results = []@@ -185,8 +188,9 @@ def handle_batch_clips(task_id: str, params: dict):transcript_words=params.get("transcript_words", []),title=clip.get("title", f"clip_{i + 1}"),output_dir=params.get("output_dir"),- logo_path=clip.get("logo_path") or params.get("logo_path"),- outro_path=params.get("outro_path"),+ logo_path=asset_store.resolve(clip.get("logo_path") or params.get("logo_path")),+ outro_path=asset_store.resolve(params.get("outro_path")),+ intro_path=asset_store.resolve(clip.get("intro_path") or params.get("intro_path")),clean_fillers=params.get("clean_fillers", True),face_map=params.get("face_map"),keep_segments=clip.get("keep_segments"),@@ -401,13 +405,14 @@ def handle_manage_reel(task_id: str, params: dict):# Auto lets the saliency threshold decide how many moments clear the bar,# capped for sanity, with a wide length range so windows aren't constrained.auto = bool(params.get("auto"))+ from services import asset_storecommon = dict(profile=params.get("profile", "auto"),format=params.get("format", "horizontal"),top_n=50 if auto else int(params.get("top_n", 10)),min_dur=5.0 if auto else float(params.get("min_dur", 15.0)),max_dur=120.0 if auto else float(params.get("max_dur", 60.0)),- logo=params.get("logo") or "",+ logo=params.get("logo") or asset_store.default_logo() or "",progress_callback=lambda p, m: emit_progress(task_id, "detecting", p, m),)if video_paths:diff --git a/backend/presets.py b/backend/presets.pyindex 5aab62c..7431e23 100644--- a/backend/presets.py+++ b/backend/presets.py@@ -33,6 +33,7 @@ DEFAULT_PRESET = {"time_adjust": -1.0,"logo_path": "","outro_path": "",+ "intro_path": "","video_path": "","transcript_path": "","output_dir": "",diff --git a/backend/services/asset_store.py b/backend/services/asset_store.pyindex 61b2ef9..cf925dd 100644--- a/backend/services/asset_store.py+++ b/backend/services/asset_store.py@@ -1,11 +1,14 @@"""Shared asset registry — works from CLI, Web UI, and MCP.-Assets are named references to local files (logos, intros, outros, images).-Register once, use by name everywhere:+Assets are named references to local files (logos, intros, outros, music,+images). Register once, use by name everywhere:CLI: ./podcli process video.mp4 --logo deeptechMCP: create_clip(logo_path="deeptech")- Web UI: select from dropdown+ Web UI: pick from the Assets page++One of each defaultable type (logo/outro/intro/music) can be marked the+brand default, applied automatically when no explicit asset is passed.Registry stored at .podcli/assets/registry.json"""@@ -13,10 +16,22 @@ Registry stored at .podcli/assets/registry.jsonimport jsonimport osimport shutil+import subprocess+import sys+import urllib.requestfrom typing import Optionalfrom config.paths import paths+SCHEMA_VERSION = 2++# One default stacks per group; legacy "video" assets are outros.+DEFAULTABLE_TYPES = ("logo", "outro", "intro", "music")++_VIDEO_EXTS = {".mp4", ".mov", ".mkv", ".webm", ".m4v"}+_IMAGE_EXTS = {".png", ".jpg", ".jpeg", ".svg", ".webp", ".gif"}+_AUDIO_EXTS = {".mp3", ".wav", ".m4a", ".aac", ".flac", ".ogg"}+def _registry_path() -> str:"""Path to the asset registry JSON file."""@@ -25,6 +40,26 @@ def _registry_path() -> str:return os.path.join(base, "registry.json")+def _is_outro_type(asset_type: str) -> bool:+ return asset_type in ("outro", "video")+++def _same_default_group(a: str, b: str) -> bool:+ if _is_outro_type(a) and _is_outro_type(b):+ return True+ return a == b+++def _migrate(assets: list[dict]) -> tuple[list[dict], bool]:+ """Idempotent upgrade: normalize legacy 'video' type to 'outro'."""+ changed = False+ for a in assets:+ if a.get("type") == "video":+ a["type"] = "outro"+ changed = True+ return assets, changed++def _load() -> list[dict]:path = _registry_path()if not os.path.exists(path):@@ -32,15 +67,44 @@ def _load() -> list[dict]:try:with open(path, encoding="utf-8") as f:data = json.load(f)- return data.get("assets", []) if isinstance(data, dict) else data+ raw = data.get("assets", []) if isinstance(data, dict) else data+ stored_version = data.get("schemaVersion") if isinstance(data, dict) else None+ assets, changed = _migrate(raw)+ if changed or stored_version != SCHEMA_VERSION:+ try:+ _save(assets)+ except OSError:+ pass # Read-only FS or racing writer; serve the migrated view.+ return assetsexcept (json.JSONDecodeError, IOError):return []def _save(assets: list[dict]):path = _registry_path()- with open(path, "w", encoding="utf-8") as f:- json.dump({"assets": assets}, f, indent=2)+ tmp = f"{path}.{os.getpid()}.tmp"+ with open(tmp, "w", encoding="utf-8") as f:+ json.dump({"schemaVersion": SCHEMA_VERSION, "assets": assets}, f, indent=2)+ os.replace(tmp, path)+++def _safe_name(name: str) -> str:+ """Keep names URL-safe so they round-trip through the web /assets/:name routes."""+ slug = "".join(c if c.isalnum() or c in "._-" else "-" for c in (name or "").strip())+ return slug.strip("-") or "asset"+++def _infer_type(file_path: str) -> str:+ ext = os.path.splitext(file_path)[1].lower()+ if ext in (".png", ".svg"):+ return "logo"+ if ext in _IMAGE_EXTS:+ return "image"+ if ext in _VIDEO_EXTS:+ return "video"+ if ext in _AUDIO_EXTS:+ return "audio"+ return "other"def register(name: str, file_path: str, asset_type: str = "auto") -> dict:@@ -50,7 +114,8 @@ def register(name: str, file_path: str, asset_type: str = "auto") -> dict:Args:name: Short name to reference this asset (e.g., "deeptech", "outro")file_path: Absolute or relative path to the file- asset_type: "logo", "video", "image", "audio", or "auto" (detect from extension)+ asset_type: "logo", "outro", "intro", "music", "image", "audio", or+ "auto" (detect from extension)Returns:The registered asset dict@@ -60,23 +125,19 @@ def register(name: str, file_path: str, asset_type: str = "auto") -> dict:raise FileNotFoundError(f"File not found: {file_path}")if asset_type == "auto":- ext = os.path.splitext(file_path)[1].lower()- type_map = {- ".png": "logo", ".jpg": "image", ".jpeg": "image", ".svg": "logo",- ".mp4": "video", ".mov": "video", ".mkv": "video", ".webm": "video",- ".mp3": "audio", ".wav": "audio", ".m4a": "audio",- }- asset_type = type_map.get(ext, "other")+ asset_type = _infer_type(file_path)+ name = _safe_name(name)assets = _load()- # Update if name exists, otherwise addexisting = next((i for i, a in enumerate(assets) if a["name"] == name), None)asset = {"name": name,"type": asset_type,"path": file_path,}+ if existing is not None and assets[existing].get("default"):+ asset["default"] = Trueif existing is not None:assets[existing] = asset@@ -87,6 +148,31 @@ def register(name: str, file_path: str, asset_type: str = "auto") -> dict:return asset+def import_file(source_path: str, name: str, asset_type: str = "auto") -> dict:+ """Copy a file into .podcli/assets/ then register it (self-contained)."""+ source_path = os.path.abspath(source_path)+ if not os.path.exists(source_path):+ raise FileNotFoundError(f"File not found: {source_path}")+ base = paths["assets"]+ os.makedirs(base, exist_ok=True)+ dest = os.path.join(base, _safe_filename(name, source_path))+ shutil.copyfile(source_path, dest)+ return register(name, dest, asset_type)+++def import_url(url: str, name: str, asset_type: str = "auto") -> dict:+ """Download a remote URL into .podcli/assets/ then register it."""+ base = paths["assets"]+ os.makedirs(base, exist_ok=True)+ if _looks_like_direct_file(url):+ dest = os.path.join(base, _safe_filename(name, url))+ _download_direct(url, dest)+ else:+ dest = _download_yt_dlp(url, base, name)+ resolved_type = asset_type if asset_type != "auto" else _infer_type(dest)+ return register(name, dest, resolved_type)++def unregister(name: str) -> bool:"""Remove a named asset. Returns True if found and removed."""assets = _load()@@ -98,6 +184,46 @@ def unregister(name: str) -> bool:return False+def set_default(name: str) -> Optional[dict]:+ """Mark an asset the default for its type, clearing the flag on siblings."""+ assets = _load()+ target = next((a for a in assets if a["name"] == name), None)+ if target is None:+ return None+ for a in assets:+ if _same_default_group(a.get("type", ""), target.get("type", "")):+ a.pop("default", None)+ target["default"] = True+ _save(assets)+ return target+++def clear_default(name: str) -> bool:+ assets = _load()+ target = next((a for a in assets if a["name"] == name), None)+ if target is None or not target.get("default"):+ return False+ target.pop("default", None)+ _save(assets)+ return True+++def rename(name: str, new_name: str) -> dict:+ """Rename an asset, keeping its file, type, and default flag."""+ new_name = _safe_name(new_name)+ if not new_name:+ raise ValueError("New name is required")+ assets = _load()+ target = next((a for a in assets if a["name"] == name), None)+ if target is None:+ raise KeyError(f"Asset not found: {name}")+ if new_name != name and any(a["name"] == new_name for a in assets):+ raise ValueError(f'An asset named "{new_name}" already exists')+ target["name"] = new_name+ _save(assets)+ return target++def list_assets(asset_type: Optional[str] = None) -> list[dict]:"""List all registered assets, optionally filtered by type."""assets = _load()@@ -106,20 +232,35 @@ def list_assets(asset_type: Optional[str] = None) -> list[dict]:return assets-def default_logo() -> Optional[str]:- """First registered logo whose file still exists, else None."""- for a in list_assets("logo"):+def _default_of(*types: str) -> Optional[str]:+ """Default asset path for a group: flagged first, then first-existing."""+ assets = _load()+ group = [a for a in assets if any(_same_default_group(a.get("type", ""), t) for t in types)]+ for a in group:+ if a.get("default") and os.path.exists(a["path"]):+ return a["path"]+ for a in group:if os.path.exists(a["path"]):return a["path"]return None+def default_logo() -> Optional[str]:+ """The default logo path, else first existing logo, else None."""+ return _default_of("logo")++def default_outro() -> Optional[str]:- """First registered video asset whose file still exists, else None."""- for a in list_assets("video"):- if os.path.exists(a["path"]):- return a["path"]- return None+ """The default outro path (incl. legacy 'video'), else first existing, else None."""+ return _default_of("outro")+++def default_intro() -> Optional[str]:+ return _default_of("intro")+++def default_music() -> Optional[str]:+ return _default_of("music")def resolve_logo(explicit: Optional[str]) -> Optional[str]:@@ -136,6 +277,13 @@ def resolve_outro(explicit: Optional[str]) -> Optional[str]:return default_outro()+def resolve_intro(explicit: Optional[str]) -> Optional[str]:+ """Resolve an explicit intro name/path, falling back to the default intro."""+ if explicit:+ return resolve(explicit)+ return default_intro()++def resolve(name_or_path: str) -> Optional[str]:"""Resolve a name or path to an absolute file path.@@ -146,16 +294,67 @@ def resolve(name_or_path: str) -> Optional[str]:if not name_or_path:return None- # Check registered assetsassets = _load()for a in assets:if a["name"] == name_or_path:if os.path.exists(a["path"]):return a["path"]- # Treat as direct pathpath = os.path.abspath(name_or_path)if os.path.exists(path):return pathreturn None+++def _safe_filename(name: str, source: str) -> str:+ slug = "".join(c if c.isalnum() or c in "._-" else "_" for c in name) or "asset"+ ext = _url_ext(source) or os.path.splitext(source)[1].lower()+ return slug + ext+++def _url_ext(url: str) -> str:+ from urllib.parse import urlparse++ return os.path.splitext(urlparse(url).path)[1].lower()+++def _looks_like_direct_file(url: str) -> bool:+ ext = _url_ext(url)+ return ext in _IMAGE_EXTS or ext in _AUDIO_EXTS or ext in _VIDEO_EXTS+++def _download_direct(url: str, dest: str):+ req = urllib.request.Request(url, headers={"User-Agent": "podcli"})+ with urllib.request.urlopen(req, timeout=60) as resp, open(dest, "wb") as out:+ shutil.copyfileobj(resp, out)+++def _download_yt_dlp(url: str, dest_dir: str, name: str) -> str:+ slug = "".join(c if c.isalnum() or c in "._-" else "_" for c in name) or "asset"+ cmd = [+ sys.executable, "-m", "yt_dlp",+ "--no-playlist",+ "--format", "bv*[height<=1080]+ba/b[height<=1080]/bv*+ba/b",+ "--merge-output-format", "mp4",+ "--restrict-filenames", "--windows-filenames",+ "--paths", dest_dir,+ "--output", f"{slug}.%(ext)s",+ "--print", "after_move:podcli-filepath:%(filepath)s",+ ]+ # Hermetic installs bundle ffmpeg off-PATH; yt-dlp needs it to merge streams.+ ffmpeg = os.environ.get("PODCLI_FFMPEG")+ if ffmpeg and os.path.exists(ffmpeg):+ cmd += ["--ffmpeg-location", ffmpeg]+ cmd.append(url)+ proc = subprocess.run(cmd, capture_output=True, text=True)+ if proc.returncode != 0:+ raise RuntimeError(f"yt-dlp failed for {url}: {proc.stderr[-800:]}")+ file_path = ""+ for line in proc.stdout.splitlines():+ line = line.strip()+ if line.startswith("podcli-filepath:"):+ file_path = line[len("podcli-filepath:"):]+ if not file_path or not os.path.exists(file_path):+ raise RuntimeError(f"yt-dlp reported no output file for {url}")+ return file_pathdiff --git a/backend/services/clip_generator.py b/backend/services/clip_generator.pyindex f73076d..64b1138 100644--- a/backend/services/clip_generator.py+++ b/backend/services/clip_generator.py@@ -583,6 +583,7 @@ def generate_clip(face_map: dict = None,logo_path: Optional[str] = None,outro_path: Optional[str] = None,+ intro_path: Optional[str] = None,clean_fillers: bool = True,keep_segments: list[dict] = None,trim_opening: Optional[bool] = None,@@ -724,7 +725,9 @@ def generate_clip(caption_overlay_path = Nonetry:- total_steps = 4 + (1 if outro_path and os.path.exists(str(outro_path)) else 0)+ total_steps = 4 + (1 if outro_path and os.path.exists(str(outro_path)) else 0) + (+ 1 if intro_path and os.path.exists(str(intro_path)) else 0+ )# Step 1: Cut the segment(s) from the source videoif progress_callback:@@ -870,16 +873,30 @@ def generate_clip(normalized_path = os.path.join(work_dir, "normalized.mp4")normalize_audio(captioned_path, normalized_path)- # Step 5: Append outro (if provided)+ # Step 5: Prepend intro, then append outro (if provided).+ # concat_outro joins two clips head-to-tail, so passing the intro first+ # puts it in front of the clip.+ final_video_path = normalized_path+ if intro_path and os.path.exists(intro_path):+ if progress_callback:+ progress_callback(83, "Adding intro")+ # concat_outro outputs at its first arg's dimensions, so match the+ # intro to the clip's frame or a landscape intro reshapes the clip.+ from services.video_processor import get_dimensions, scale_to_frame+ cw, ch = get_dimensions(final_video_path)+ intro_scaled = os.path.join(work_dir, "intro_scaled.mp4")+ scale_to_frame(intro_path, intro_scaled, cw, ch)+ with_intro_path = os.path.join(work_dir, "with_intro.mp4")+ concat_outro(intro_scaled, final_video_path, with_intro_path)+ final_video_path = with_intro_path+if outro_path and os.path.exists(outro_path):if progress_callback:progress_callback(85, f"Adding outro ({total_steps}/{total_steps})")with_outro_path = os.path.join(work_dir, "with_outro.mp4")- concat_outro(normalized_path, outro_path, with_outro_path)+ concat_outro(final_video_path, outro_path, with_outro_path)final_video_path = with_outro_path- else:- final_video_path = normalized_path# Step 6: Move to outputif progress_callback:diff --git a/backend/services/video_processor.py b/backend/services/video_processor.pyindex 8787898..36256bd 100644--- a/backend/services/video_processor.py+++ b/backend/services/video_processor.py@@ -2515,6 +2515,25 @@ def _build_transition_keyframes(return x_keyframes, y_keyframes+def scale_to_frame(input_path: str, output_path: str, width: int, height: int) -> str:+ """Re-encode a video to exactly width×height (aspect preserved, padded)."""+ _run_ffmpeg_with_fallback(+ cmd_parts_before_enc=[+ "ffmpeg", "-y",+ "-i", input_path,+ "-vf", f"scale={width}:{height}:force_original_aspect_ratio=decrease,"+ f"pad={width}:{height}:(ow-iw)/2:(oh-ih)/2:black",+ ],+ cmd_parts_after_enc=[+ "-c:a", "aac", "-b:a", "192k", "-ar", "44100",+ "-movflags", "+faststart",+ ],+ output_path=output_path,+ label="scale_to_frame",+ )+ return output_path++def concat_outro(input_path: str,outro_path: str,diff --git a/src/handlers/batch-clips.handler.ts b/src/handlers/batch-clips.handler.tsindex 24ad80b..73462a3 100644--- a/src/handlers/batch-clips.handler.ts+++ b/src/handlers/batch-clips.handler.ts@@ -218,6 +218,7 @@ export async function handleBatchClips(input: BatchClipsInput): Promise<string>clean_fillers: input.clean_fillers !== false,logo_path: settings.logoPath || null,outro_path: settings.outroPath || null,+ intro_path: settings.introPath || null,keep_caption_overlay: input.keep_caption_overlay === true,}),});@@ -249,6 +250,8 @@ export async function handleBatchClips(input: BatchClipsInput): Promise<string>keep_caption_overlay: input.keep_caption_overlay === true,output_dir: paths.output,logo_path: settings.logoPath || null,+ outro_path: settings.outroPath || null,+ intro_path: settings.introPath || null,});if (!result.data) {diff --git a/src/handlers/create-clip.handler.ts b/src/handlers/create-clip.handler.tsindex 56bbd5f..c046627 100644--- a/src/handlers/create-clip.handler.ts+++ b/src/handlers/create-clip.handler.ts@@ -110,7 +110,11 @@ export const createClipToolDef = {},outro_path: {type: "string",- description: "Path to an outro video to append at the end of the clip",+ description: "Outro video (asset name or path) appended at the end of the clip. Uses the default outro asset if omitted.",+ },+ intro_path: {+ type: "string",+ description: "Intro video (asset name or path) prepended before the clip. Uses the default intro asset if omitted.",},keep_caption_overlay: {type: "boolean",@@ -157,6 +161,7 @@ export async function handleCreateClip(input: CreateClipInput): Promise<string>const format = input.format || settings.format || "vertical";const logoPath = input.logo_path || settings.logoPath || null;const outroPath = input.outro_path || settings.outroPath || null;+ const introPath = input.intro_path || settings.introPath || null;const transcriptWords = input.transcript_words ?? transcript?.words ?? [];// Pull multi-cut segments from suggestion (if available)@@ -187,6 +192,7 @@ export async function handleCreateClip(input: CreateClipInput): Promise<string>keep_caption_overlay: input.keep_caption_overlay === true,logo_path: logoPath,outro_path: outroPath,+ intro_path: introPath,...(keepSegments && { keep_segments: keepSegments }),});diff --git a/src/models/index.ts b/src/models/index.tsindex c6704e4..3fcc0b0 100644--- a/src/models/index.ts+++ b/src/models/index.ts@@ -122,6 +122,7 @@ export interface UIState {format?: Format;logoPath?: string;outroPath?: string;+ introPath?: string;};phase?: string;lastUpdated?: number;@@ -138,6 +139,7 @@ export interface CreateClipInput {format?: Format;logo_path?: string;outro_path?: string;+ intro_path?: string;transcript_words?: WordTimestamp[];clean_fillers?: boolean;allow_ass_fallback?: boolean;@@ -152,6 +154,7 @@ export interface BatchClipSpec {crop_strategy?: string;format?: Format;logo_path?: string | null;+ intro_path?: string | null;allow_ass_fallback?: boolean;keep_caption_overlay?: boolean;keep_segments?: Array<{ start: number; end: number }>;@@ -196,14 +199,28 @@ export interface BatchClipsResult {// === Asset Models ===+export type AssetType =+ | "logo"+ | "outro"+ | "intro"+ | "music"+ | "video"+ | "image"+ | "audio"+ | "other";+export interface Asset {name: string;- type: "logo" | "video" | "image" | "other";+ type: AssetType;path: string;addedAt: string;+ default?: boolean;}+export const ASSETS_SCHEMA_VERSION = 2;+export interface AssetRegistry {+ schemaVersion?: number;assets: Asset[];}@@ -238,6 +255,7 @@ export interface ClipHistoryEntry {format?: Format;logo_path?: string;outro_path?: string;+ intro_path?: string;title: string;output_path: string;file_size_mb: number;diff --git a/src/server.ts b/src/server.tsindex 9f730e1..e66c338 100644--- a/src/server.ts+++ b/src/server.ts@@ -25,7 +25,7 @@ import {import { registerIntegrationMcpTools } from "./handlers/integrations.handler.js";import { FileManager } from "./services/file-manager.js";import { KnowledgeBase } from "./services/knowledge-base.js";-import { AssetManager } from "./services/asset-manager.js";+import { AssetManager, inferType } from "./services/asset-manager.js";import { ClipsHistory } from "./services/clips-history.js";import { TranscriptCache } from "./services/transcript-cache.js";import { paths } from "./config/paths.js";@@ -1033,19 +1033,31 @@ export function createServer(): McpServer {// =============================================server.tool("manage_assets",- "Register and manage reusable assets (logos, videos). Registered assets can be referenced by name in create_clip instead of full paths.",+ "Register and manage reusable assets (logos, outros, intros, music, images). Reference them by name in create_clip/manage_reel instead of full paths. One logo/outro/intro/music can be the default, applied automatically when none is passed.",{action: z- .enum(["list", "register", "unregister", "resolve", "import"])+ .enum([+ "list",+ "register",+ "import",+ "import_url",+ "unregister",+ "resolve",+ "set_default",+ "clear_default",+ "rename",+ ]).describe("Action to perform"),name: z.string().optional().describe("Asset name (e.g. 'podcast-logo')"),- path: z.string().optional().describe("Absolute file path (for register)"),+ new_name: z.string().optional().describe("New asset name (for rename)"),+ path: z.string().optional().describe("Absolute file path (for register/import)"),+ url: z.string().optional().describe("Remote URL to download (for import_url)"),type: z- .enum(["logo", "video", "image", "other"])+ .enum(["logo", "outro", "intro", "music", "image", "audio", "other"]).optional()- .describe("Asset type (for register/list filter)"),+ .describe("Asset type (for register/import/list filter)"),},- async ({ action, name, path, type }) => {+ async ({ action, name, new_name, path, url, type }) => {try {if (action === "list") {const items = await assets.list(type || undefined);@@ -1056,12 +1068,12 @@ export function createServer(): McpServer {],};const text = items- .map((a) => `- ${a.name} (${a.type}): ${a.path}`)+ .map((a) => `- ${a.name} (${a.type})${a.default ? " [default]" : ""}: ${a.path}`).join("\n");return { content: [{ type: "text" as const, text }] };}if (action === "register" && name && path) {- const asset = await assets.register(name, path, type || "other");+ const asset = await assets.register(name, path, type || inferType(path));return {content: [{@@ -1071,6 +1083,28 @@ export function createServer(): McpServer {],};}+ if (action === "import" && path && name) {+ const asset = await assets.importFile(path, name, type || inferType(path));+ return {+ content: [+ {+ type: "text" as const,+ text: `Imported "${asset.name}" → ${asset.path}`,+ },+ ],+ };+ }+ if (action === "import_url" && url && name) {+ const asset = await assets.importUrl(url, name, type);+ return {+ content: [+ {+ type: "text" as const,+ text: `Imported "${asset.name}" from URL → ${asset.path}`,+ },+ ],+ };+ }if (action === "unregister" && name) {await assets.unregister(name);return {@@ -1090,17 +1124,33 @@ export function createServer(): McpServer {],};}- if (action === "import" && path && name) {- const asset = await assets.importFile(path, name, type || "other");+ if (action === "set_default" && name) {+ const asset = await assets.setDefault(name);return {content: [{type: "text" as const,- text: `Imported "${asset.name}" → ${asset.path}`,+ text: `"${asset.name}" is now the default ${asset.type}.`,},],};}+ if (action === "clear_default" && name) {+ await assets.clearDefault(name);+ return {+ content: [+ { type: "text" as const, text: `"${name}" is no longer a default.` },+ ],+ };+ }+ if (action === "rename" && name && new_name) {+ const asset = await assets.rename(name, new_name);+ return {+ content: [+ { type: "text" as const, text: `Renamed to "${asset.name}".` },+ ],+ };+ }return {content: [{@@ -1668,8 +1718,12 @@ export function createServer(): McpServer {.string().optional().describe("Path or registered asset name for outro video"),+ intro_path: z+ .string()+ .optional()+ .describe("Path or registered asset name for intro video"),},- async ({ caption_style, crop_strategy, logo_path, outro_path }) => {+ async ({ caption_style, crop_strategy, logo_path, outro_path, intro_path }) => {try {const settings: Record<string, string> = {};if (caption_style) settings.captionStyle = caption_style;@@ -1682,13 +1736,17 @@ export function createServer(): McpServer {const resolved = await assets.resolve(outro_path);settings.outroPath = resolved || outro_path;}+ if (intro_path) {+ const resolved = await assets.resolve(intro_path);+ settings.introPath = resolved || intro_path;+ }if (Object.keys(settings).length === 0) {return {content: [{type: "text" as const,- text: "No settings provided. Specify at least one of: caption_style, crop_strategy, logo_path, outro_path.",+ text: "No settings provided. Specify at least one of: caption_style, crop_strategy, logo_path, outro_path, intro_path.",},],};diff --git a/src/services/asset-manager.test.ts b/src/services/asset-manager.test.tsindex a55aa56..22b48f3 100644--- a/src/services/asset-manager.test.ts+++ b/src/services/asset-manager.test.ts@@ -51,9 +51,51 @@ describe("AssetManager", () => {it("filters list by type", async () => {await manager.register("logo1", makeFile("l1.png"), "logo");- await manager.register("vid1", makeFile("v1.mp4"), "video");+ await manager.register("out1", makeFile("o1.mp4"), "outro");expect(await manager.list("logo")).toHaveLength(1);- expect(await manager.list("video")).toHaveLength(1);+ expect(await manager.list("outro")).toHaveLength(1);+ });++ it("normalizes legacy 'video' type to 'outro' on load", async () => {+ await manager.register("legacy", makeFile("legacy.mp4"), "video");+ const list = await manager.list();+ expect(list[0].type).toBe("outro");+ expect(await manager.list("outro")).toHaveLength(1);+ expect(await manager.list("video")).toHaveLength(0);+ });++ it("marks one default per type and falls back to first-existing", async () => {+ const l1 = makeFile("d1.png");+ const l2 = makeFile("d2.png");+ await manager.register("d1", l1, "logo");+ await manager.register("d2", l2, "logo");+ expect(await manager.getDefault("logo")).toBe(l1);+ await manager.setDefault("d2");+ expect(await manager.getDefault("logo")).toBe(l2);+ const flagged = (await manager.list("logo")).filter((a) => a.default);+ expect(flagged).toHaveLength(1);+ expect(flagged[0].name).toBe("d2");+ });++ it("outro and legacy video share one default group", async () => {+ const o = makeFile("share.mp4");+ await manager.register("shared", o, "outro");+ await manager.setDefault("shared");+ expect(await manager.getDefault("outro")).toBe(o);+ expect(await manager.getDefault("video")).toBe(o);+ });++ it("sanitizes unsafe names so they round-trip through URL routes", async () => {+ const asset = await manager.register("my logo/v2", makeFile("s.png"), "logo");+ expect(asset.name).toBe("my-logo-v2");+ expect(await manager.resolve("my-logo-v2")).toBeTruthy();+ });++ it("importFile copies into the assets dir", async () => {+ const src = makeFile("src-logo.png");+ const asset = await manager.importFile(src, "copied", "logo");+ expect(asset.path).toContain(join(tmp, "assets"));+ expect(asset.path).not.toBe(src);});it("resolve returns path for registered name, direct path, or null", async () => {diff --git a/src/services/asset-manager.ts b/src/services/asset-manager.tsindex 3cc7b87..4905187 100644--- a/src/services/asset-manager.ts+++ b/src/services/asset-manager.ts@@ -1,8 +1,32 @@-import { readFile, writeFile, copyFile, mkdir } from "fs/promises";-import { existsSync } from "fs";-import { join, basename } from "path";+import { readFile, writeFile, copyFile, mkdir, rename } from "fs/promises";+import { existsSync, createWriteStream } from "fs";+import { join, extname } from "path";+import { spawn } from "child_process";+import { Readable } from "stream";+import { pipeline } from "stream/promises";import { paths } from "../config/paths.js";-import type { Asset, AssetRegistry } from "../models/index.js";+import { ASSETS_SCHEMA_VERSION } from "../models/index.js";+import type { Asset, AssetType, AssetRegistry } from "../models/index.js";++const VIDEO_EXTS = new Set([".mp4", ".mov", ".mkv", ".webm", ".m4v"]);+const IMAGE_EXTS = new Set([".png", ".jpg", ".jpeg", ".svg", ".webp", ".gif"]);+const AUDIO_EXTS = new Set([".mp3", ".wav", ".m4a", ".aac", ".flac", ".ogg"]);++export const DEFAULTABLE_TYPES: AssetType[] = ["logo", "outro", "intro", "music"];++export function inferType(filePath: string): AssetType {+ const ext = extname(filePath).toLowerCase();+ if (ext === ".png" || ext === ".svg") return "logo";+ if (IMAGE_EXTS.has(ext)) return "image";+ if (VIDEO_EXTS.has(ext)) return "video";+ if (AUDIO_EXTS.has(ext)) return "audio";+ return "other";+}++/** Outros were historically registered as "video"; treat both as outros. */+function isOutroType(type: string): boolean {+ return type === "outro" || type === "video";+}export class AssetManager {private registryPath = paths.assetsRegistry;@@ -15,28 +39,50 @@ export class AssetManager {}async load(): Promise<AssetRegistry> {+ let registry: AssetRegistry;try {- if (!existsSync(this.registryPath)) return { assets: [] };+ if (!existsSync(this.registryPath)) return { schemaVersion: ASSETS_SCHEMA_VERSION, assets: [] };const raw = await readFile(this.registryPath, "utf-8");- return JSON.parse(raw) as AssetRegistry;+ const parsed = JSON.parse(raw);+ const bag = Array.isArray(parsed) ? { assets: parsed } : (parsed ?? {});+ registry = { ...bag, assets: Array.isArray(bag.assets) ? bag.assets : [] } as AssetRegistry;} catch {- return { assets: [] };+ return { schemaVersion: ASSETS_SCHEMA_VERSION, assets: [] };+ }+ const { registry: migrated, changed } = migrate(registry);+ if (changed) {+ try {+ await this.save(migrated);+ } catch {+ // Read-only filesystem or a racing writer — serve the migrated view anyway.+ }}+ return migrated;}private async save(registry: AssetRegistry): Promise<void> {await this.ensureDir();- await writeFile(this.registryPath, JSON.stringify(registry, null, 2), "utf-8");+ registry.schemaVersion = ASSETS_SCHEMA_VERSION;+ const tmp = `${this.registryPath}.${process.pid}.tmp`;+ await writeFile(tmp, JSON.stringify(registry, null, 2), "utf-8");+ await rename(tmp, this.registryPath);}- async register(name: string, filePath: string, type: Asset["type"]): Promise<Asset> {+ async register(rawName: string, filePath: string, type: AssetType): Promise<Asset> {if (!existsSync(filePath)) {throw new Error(`File not found: ${filePath}`);}+ const name = safeName(rawName);const registry = await this.load();- // Update if name exists, otherwise addconst existing = registry.assets.findIndex((a) => a.name === name);- const asset: Asset = { name, type, path: filePath, addedAt: new Date().toISOString() };+ const prior = existing >= 0 ? registry.assets[existing] : undefined;+ const asset: Asset = {+ name,+ type,+ path: filePath,+ addedAt: prior?.addedAt ?? new Date().toISOString(),+ ...(prior?.default ? { default: true } : {}),+ };if (existing >= 0) {registry.assets[existing] = asset;} else {@@ -58,23 +104,205 @@ export class AssetManager {return registry.assets;}- /** Resolve a name or path to an absolute file path. */+ async setDefault(name: string): Promise<Asset> {+ const registry = await this.load();+ const target = registry.assets.find((a) => a.name === name);+ if (!target) throw new Error(`Asset not found: ${name}`);+ for (const a of registry.assets) {+ if (sameDefaultGroup(a.type, target.type)) delete a.default;+ }+ target.default = true;+ await this.save(registry);+ return target;+ }++ async clearDefault(name: string): Promise<void> {+ const registry = await this.load();+ const target = registry.assets.find((a) => a.name === name);+ if (target) {+ delete target.default;+ await this.save(registry);+ }+ }++ async rename(name: string, newName: string): Promise<Asset> {+ const trimmed = safeName(newName);+ if (!trimmed) throw new Error("New name is required");+ const registry = await this.load();+ const target = registry.assets.find((a) => a.name === name);+ if (!target) throw new Error(`Asset not found: ${name}`);+ if (trimmed !== name && registry.assets.some((a) => a.name === trimmed)) {+ throw new Error(`An asset named "${trimmed}" already exists`);+ }+ target.name = trimmed;+ await this.save(registry);+ return target;+ }++ async getDefault(type: AssetType): Promise<string | null> {+ const registry = await this.load();+ const group = registry.assets.filter((a) => sameDefaultGroup(a.type, type));+ const flagged = group.find((a) => a.default && existsSync(a.path));+ if (flagged) return flagged.path;+ const firstExisting = group.find((a) => existsSync(a.path));+ return firstExisting ? firstExisting.path : null;+ }+async resolve(nameOrPath: string): Promise<string | null> {if (!nameOrPath) return null;- // Check if it's a registered asset nameconst registry = await this.load();const asset = registry.assets.find((a) => a.name === nameOrPath);if (asset && existsSync(asset.path)) return asset.path;- // Otherwise treat as a direct pathif (existsSync(nameOrPath)) return nameOrPath;return null;}- /** Copy a file into .podcli/assets/ and register it. */- async importFile(sourcePath: string, name: string, type: Asset["type"]): Promise<Asset> {+ async importFile(sourcePath: string, name: string, type: AssetType): Promise<Asset> {await this.ensureDir();- const destPath = join(this.assetsDir, basename(sourcePath));+ const destPath = join(this.assetsDir, safeAssetFilename(name, sourcePath));await copyFile(sourcePath, destPath);return this.register(name, destPath, type);}++ async importUrl(url: string, name: string, type?: AssetType): Promise<Asset> {+ assertSafeUrl(url);+ await this.ensureDir();+ const destPath = looksLikeDirectFile(url)+ ? await downloadDirect(url, join(this.assetsDir, safeAssetFilename(name, url)))+ : await downloadWithYtDlp(url, this.assetsDir, name);+ // Infer from the downloaded file, not the URL (query strings break extname).+ return this.register(name, destPath, type ?? inferType(destPath));+ }}++/** Keep names URL-safe so they round-trip through /api/assets/:name routes. */+export function safeName(name: string): string {+ return (name || "").trim().replace(/[^a-zA-Z0-9._-]/g, "-").replace(/^-+|-+$/g, "") || "asset";+}++function sameDefaultGroup(a: string, b: string): boolean {+ if (isOutroType(a) && isOutroType(b)) return true;+ return a === b;+}++export function migrate(registry: AssetRegistry): { registry: AssetRegistry; changed: boolean } {+ let changed = false;+ if (registry.schemaVersion !== ASSETS_SCHEMA_VERSION) changed = true;+ const now = new Date().toISOString();+ for (const asset of registry.assets) {+ if (asset.type === "video") {+ asset.type = "outro";+ changed = true;+ }+ if (!asset.addedAt) {+ asset.addedAt = now;+ changed = true;+ }+ }+ registry.schemaVersion = ASSETS_SCHEMA_VERSION;+ return { registry, changed };+}++function safeAssetFilename(name: string, source: string): string {+ const slug = name.replace(/[^a-zA-Z0-9._-]/g, "_") || "asset";+ let ext = extname(new URL(source, "file://localhost/").pathname || source).toLowerCase();+ if (!ext) ext = extname(source).toLowerCase();+ return slug + ext;+}++function looksLikeDirectFile(url: string): boolean {+ try {+ const ext = extname(new URL(url).pathname).toLowerCase();+ return IMAGE_EXTS.has(ext) || AUDIO_EXTS.has(ext) || VIDEO_EXTS.has(ext);+ } catch {+ return false;+ }+}++const DOWNLOAD_TIMEOUT_MS = 120_000;++/** Basic SSRF guard: only http(s), and reject obvious localhost/private hosts. */+function assertSafeUrl(url: string): void {+ let parsed: URL;+ try {+ parsed = new URL(url);+ } catch {+ throw new Error(`Invalid URL: ${url}`);+ }+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {+ throw new Error(`Unsupported URL protocol: ${parsed.protocol}`);+ }+ const host = parsed.hostname.toLowerCase();+ if (+ host === "localhost" ||+ host === "0.0.0.0" ||+ host === "::1" ||+ host.endsWith(".localhost") ||+ /^127\./.test(host) ||+ /^10\./.test(host) ||+ /^192\.168\./.test(host) ||+ /^169\.254\./.test(host) ||+ /^172\.(1[6-9]|2\d|3[01])\./.test(host)+ ) {+ throw new Error(`Refusing to download from a private/loopback host: ${host}`);+ }+}++async function downloadDirect(url: string, destPath: string): Promise<string> {+ const ac = new AbortController();+ const timer = setTimeout(() => ac.abort(), DOWNLOAD_TIMEOUT_MS);+ try {+ const res = await fetch(url, { redirect: "follow", signal: ac.signal });+ if (!res.ok || !res.body) {+ throw new Error(`Download failed (${res.status}) for ${url}`);+ }+ // pipeline rejects on source errors too, so a dropped connection can't+ // throw an uncaught 'error' and crash the server.+ // @ts-expect-error - Web ReadableStream is accepted by Node's fromWeb.+ await pipeline(Readable.fromWeb(res.body), createWriteStream(destPath));+ return destPath;+ } finally {+ clearTimeout(timer);+ }+}++function downloadWithYtDlp(url: string, destDir: string, name: string): Promise<string> {+ const slug = name.replace(/[^a-zA-Z0-9._-]/g, "_") || "asset";+ const args = [+ "-m", "yt_dlp",+ "--js-runtimes", `node:${process.execPath}`,+ "--no-playlist",+ "--format", "bv*[height<=1080]+ba/b[height<=1080]/bv*+ba/b",+ "--merge-output-format", "mp4",+ "--ffmpeg-location", paths.ffmpegPath,+ "--restrict-filenames", "--windows-filenames",+ "--paths", destDir,+ "--output", `${slug}.%(ext)s`,+ "--print", "after_move:podcli-filepath:%(filepath)s",+ url,+ ];+ return new Promise((resolveP, rejectP) => {+ const proc = spawn(paths.pythonPath, args, { env: { ...process.env, PYTHONUNBUFFERED: "1" } });+ let stdout = "";+ let stderr = "";+ let filePath = "";+ proc.stdout.on("data", (c: Buffer) => {+ stdout += c.toString();+ for (const line of c.toString().split(/\r?\n/)) {+ const t = line.trim();+ if (t.startsWith("podcli-filepath:")) filePath = t.slice("podcli-filepath:".length);+ }+ });+ proc.stderr.on("data", (c: Buffer) => (stderr += c.toString()));+ proc.on("error", (err) => rejectP(err));+ proc.on("close", (code) => {+ if (code !== 0) return rejectP(new Error(`yt-dlp failed for ${url}: ${stderr.slice(-800)}`));+ if (!filePath || !existsSync(filePath)) {+ return rejectP(new Error(`yt-dlp reported no output file for ${url}. ${stdout.slice(-400)}`));+ }+ resolveP(filePath);+ });+ });+}++export const _test = { migrate, inferType, safeAssetFilename, looksLikeDirectFile };diff --git a/src/ui/client/AnalyticsPage.tsx b/src/ui/client/AnalyticsPage.tsxindex 1ca8efb..dbf4fd3 100644--- a/src/ui/client/AnalyticsPage.tsx+++ b/src/ui/client/AnalyticsPage.tsx@@ -1,6 +1,8 @@import React, { useEffect, useRef, useState } from "react";+import { PageHeader } from "./Page";import { Link } from "react-router-dom";-import { api, upload, fmt, labelStyle } from "./lib";+import { TrendingUp, Eye, Percent, MousePointerClick } from "lucide-react";+import { api, upload, fmt } from "./lib";interface Row { key: string; count: number; avgViews: number; avgRetention: number; avgCtr: number }interface Data {@@ -9,25 +11,47 @@ interface Data {top: Array<{ id: string; title: string; content_type?: string; caption_style: string; duration: number; metrics: any }>;}-const fmtViews = (n: number) => (n >= 1000 ? `${(n / 1000).toFixed(1)}k` : String(n));+const fmtViews = (n: number) => (n >= 1000 ? `${(n / 1000).toFixed(1)}k` : String(Math.round(n)));-function Group({ title, rows, metric }: { title: string; rows: Row[]; metric: "avgRetention" | "avgCtr" | "avgViews" }) {+function weighted(rows: Row[], metric: "avgRetention" | "avgCtr") {+ const total = rows.reduce((s, r) => s + r.count, 0);+ if (!total) return 0;+ return Math.round(rows.reduce((s, r) => s + r[metric] * r.count, 0) / total);+}+function totalViews(rows: Row[]) {+ return rows.reduce((s, r) => s + r.avgViews * r.count, 0);+}+function best(rows: Row[], metric: "avgRetention" | "avgCtr" | "avgViews") {+ return rows.length ? rows.reduce((a, b) => (b[metric] > a[metric] ? b : a)) : null;+}++function StatTile({ icon, label, value, sub }: { icon: React.ReactNode; label: string; value: string; sub?: string }) {+ return (+ <div className="stat-tile">+ <div className="stat-icon">{icon}</div>+ <div className="stat-label">{label}</div>+ <div className="stat-value">{value}</div>+ {sub && <div className="stat-sub">{sub}</div>}+ </div>+ );+}++function BarGroup({ title, hint, rows, metric }: { title: string; hint: string; rows: Row[]; metric: "avgRetention" | "avgCtr" | "avgViews" }) {const max = Math.max(1, ...rows.map((r) => r[metric]));const unit = metric === "avgViews" ? "" : "%";return (- <div className="section">- <div className="section-label">{title}</div>+ <div className="section card">+ <div className="section-label" style={{ marginBottom: 2 }}>{title}</div>+ <div className="hint" style={{ marginBottom: 14 }}>{hint}</div>{rows.length === 0 ? (- <div style={{ color: "var(--text3)", fontSize: 12 }}>No data yet</div>+ <div className="analytics-empty">No data yet</div>) : rows.map((r) => (- <div key={r.key} style={{ marginBottom: 10 }}>- <div style={{ display: "flex", justifyContent: "space-between", fontSize: 12, marginBottom: 4 }}>- <span style={{ color: "var(--text)" }}>{r.key} <span style={{ color: "var(--text3)" }}>· {r.count}</span></span>- <span style={{ color: "var(--text2)", fontVariantNumeric: "tabular-nums" }}>{metric === "avgViews" ? fmtViews(r[metric]) : r[metric] + unit}</span>- </div>- <div style={{ height: 6, borderRadius: 3, background: "var(--surface2)" }}>- <div style={{ width: `${(r[metric] / max) * 100}%`, height: "100%", borderRadius: 3, background: "var(--accent)" }} />+ <div key={r.key} className="bar-row">+ <div className="bar-head">+ <span className="bar-key">{r.key} <span className="bar-count">· {r.count}</span></span>+ <span className="bar-val">{metric === "avgViews" ? fmtViews(r[metric]) : r[metric] + unit}</span></div>+ <div className="bar-track"><div className="bar-fill" style={{ width: `${(r[metric] / max) * 100}%` }} /></div></div>))}</div>@@ -109,64 +133,73 @@ export default function AnalyticsPage() {} catch (e: any) { setMsg(`Import failed: ${e.message}`); setBusy(false); }};+ const hasData = !!data && data.published > 0;+ const bestRetention = data ? best(data.byContentType, "avgRetention") : null;+ const bestCtr = data ? best(data.byCaptionStyle, "avgCtr") : null;+ const bestLength = data ? best(data.byLength, "avgRetention") : null;+ const insights = [+ bestRetention && { label: "Holds viewers best", value: bestRetention.key, metric: `${bestRetention.avgRetention}% retention` },+ bestCtr && { label: "Best packaging", value: `${bestCtr.key} captions`, metric: `${bestCtr.avgCtr}% CTR` },+ bestLength && { label: "Ideal length", value: bestLength.key, metric: `${bestLength.avgRetention}% retention` },+ ].filter(Boolean) as { label: string; value: string; metric: string }[];+return (<div className="app">- <div className="header">- <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>- <h1 style={{ margin: 0 }}>Analytics</h1>- <div className="set-actions">- <input ref={fileRef} type="file" accept=".csv" style={{ display: "none" }} onChange={(e) => e.target.files?.[0] && importCsv(e.target.files[0])} />- <button className="btn btn-ghost btn-sm" onClick={() => setShowConnect((v) => !v)} disabled={busy}>Connect</button>- {status?.authorized && <button className="btn btn-ghost btn-sm" onClick={loadProposals} disabled={busy}>Link clips</button>}- <button className="btn btn-ghost btn-sm" onClick={() => fileRef.current?.click()} disabled={busy}>Import CSV</button>- <button className="btn btn-ghost btn-sm" onClick={analyze} disabled={busy}>Analyze patterns</button>- <button className="btn btn-primary btn-sm" onClick={() => sync()} disabled={busy}>{busy ? <div className="spinner sm" /> : "Sync YouTube"}</button>- </div>- </div>- {status && (- <div style={{ fontSize: 12, color: "var(--text3)", marginTop: 8 }}>- {status.authorized ? "YouTube connected" : "Not connected"} · {status.with_metrics}/{status.total} clips with metrics- </div>- )}- {msg && <div className="set-note ok" style={{ marginTop: 10, wordBreak: "break-all" }}>{msg}</div>}+ <PageHeader+ title="Analytics"+ actions={<>+ <input ref={fileRef} type="file" accept=".csv" style={{ display: "none" }} onChange={(e) => e.target.files?.[0] && importCsv(e.target.files[0])} />+ <button className="btn btn-ghost btn-sm" onClick={() => setShowConnect((v) => !v)} disabled={busy}>Connect</button>+ {status?.authorized && <button className="btn btn-ghost btn-sm" onClick={loadProposals} disabled={busy}>Link clips</button>}+ <button className="btn btn-ghost btn-sm" onClick={() => fileRef.current?.click()} disabled={busy}>Import CSV</button>+ <button className="btn btn-ghost btn-sm" onClick={analyze} disabled={busy || !hasData}>Teach Claude</button>+ <button className="btn btn-primary btn-sm" onClick={() => sync()} disabled={busy}>{busy ? <div className="spinner sm" /> : "Sync YouTube"}</button>+ </>}+ />++ <div className="analytics-status">+ <span className={`status-dot ${status?.authorized ? "on" : ""}`} />+ {status ? (status.authorized ? "YouTube connected" : "Not connected") : "…"}+ {status && <span className="analytics-status-sub">· {status.with_metrics}/{status.total} clips with metrics</span>}</div>+ {msg && <div className="set-note ok" style={{ marginTop: 10, wordBreak: "break-all" }}>{msg}</div>}{showConnect && (- <div className="section">+ <div className="section card"><div className="section-label">Connect YouTube (read-only)</div>- <ol style={{ fontSize: 12, color: "var(--text2)", lineHeight: 1.7, margin: "0 0 14px", paddingLeft: 18 }}>+ <ol className="analytics-steps"><li>In Google Cloud Console, enable the <strong>YouTube Data API v3</strong> + <strong>YouTube Analytics API</strong>.</li><li>Create an <strong>OAuth client ID</strong> (type: Desktop app) and paste its ID + secret below.</li><li>Save, then run <code>podcli youtube auth</code> in your terminal to authorize.</li></ol><div className="thumb-fields"><div>- <label style={labelStyle}>OAuth client ID</label>+ <label className="section-label">OAuth client ID</label><input type="text" value={clientId} onChange={(e) => setClientId(e.target.value)} style={{ width: "100%" }} /></div><div>- <label style={labelStyle}>OAuth client secret {hasSecret ? "(saved)" : ""}</label>+ <label className="section-label">OAuth client secret {hasSecret ? "(saved)" : ""}</label><input type="password" value={clientSecret} onChange={(e) => setClientSecret(e.target.value)} placeholder={hasSecret ? "••••••••" : ""} style={{ width: "100%" }} /></div></div>- <div style={{ marginTop: 12, display: "flex", gap: 10, alignItems: "center" }}>+ <div style={{ marginTop: 12, display: "flex", gap: 10, alignItems: "center", flexWrap: "wrap" }}><button className="btn btn-primary btn-sm" onClick={saveConfig} disabled={busy || !clientId}>Save credentials</button>- <span style={{ fontSize: 12, color: "var(--text3)" }}>then run <code>podcli youtube auth</code> to authorize · or use Import CSV (no auth)</span>+ <span className="hint">then run <code>podcli youtube auth</code> to authorize · or use Import CSV (no auth)</span></div></div>)}{proposals !== null && (- <div className="section">+ <div className="section card"><div className="section-label">Link clips to uploads</div>{proposals.length === 0 ? (- <div style={{ fontSize: 13, color: "var(--text2)" }}>No proposals. Every clip is linked, or no upload matched.</div>+ <div className="analytics-empty">No proposals. Every clip is linked, or no upload matched.</div>) : (proposals.map((p) => (- <div key={p.clip_id} style={{ display: "flex", alignItems: "center", gap: 12, padding: "9px 0", borderBottom: "1px solid var(--border)" }}>+ <div key={p.clip_id} className="analytics-row"><div style={{ flex: 1, minWidth: 0 }}>- <div style={{ fontSize: 13, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{p.clip_title}</div>- <div style={{ fontSize: 12, color: "var(--text3)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>+ <div className="analytics-row-title">{p.clip_title}</div>+ <div className="analytics-row-sub">→ {p.video_title} <span style={{ color: p.score >= 0.8 ? "var(--green)" : "var(--text3)" }}>(score {p.score})</span></div></div>@@ -179,34 +212,63 @@ export default function AnalyticsPage() {</div>)}- {!data || data.published === 0 ? (- <div className="drop-zone" style={{ textAlign: "center", padding: "48px 20px", color: "var(--text2)" }}>- <div className="label" style={{ marginTop: 8 }}>No performance data yet.</div>- <div style={{ fontSize: 12, color: "var(--text3)", marginTop: 6 }}>- Connect YouTube and sync, or import a YouTube Studio analytics CSV.+ {!hasData ? (+ <div className="analytics-hero">+ <TrendingUp size={32} strokeWidth={1.5} />+ <div className="analytics-hero-title">No performance data yet</div>+ <div className="analytics-hero-sub">+ Connect YouTube and sync, or import a YouTube Studio analytics CSV. Once clips have metrics,+ you'll see what holds viewers, what earns clicks, and which clips to make more of.+ </div>+ <div style={{ display: "flex", gap: 10, marginTop: 18, flexWrap: "wrap", justifyContent: "center" }}>+ <button className="btn btn-primary btn-sm" onClick={() => setShowConnect(true)}>Connect YouTube</button>+ <button className="btn btn-ghost btn-sm" onClick={() => fileRef.current?.click()}>Import CSV</button></div></div>) : (<>- <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(280px, 1fr))", gap: 16, marginBottom: 8 }}>- <Group title="Retention by content type: what holds viewers" rows={data.byContentType} metric="avgRetention" />- <Group title="CTR by caption style: packaging" rows={data.byCaptionStyle} metric="avgCtr" />- <Group title="Retention by length" rows={data.byLength} metric="avgRetention" />- <Group title="Views by content type: reach" rows={data.byContentType} metric="avgViews" />+ <div className="stat-row">+ <StatTile icon={<Eye size={16} />} label="Total views" value={fmtViews(totalViews(data!.byContentType))} sub="across published clips" />+ <StatTile icon={<Percent size={16} />} label="Avg retention" value={`${weighted(data!.byContentType, "avgRetention")}%`} sub="how much people watch" />+ <StatTile icon={<MousePointerClick size={16} />} label="Avg CTR" value={`${weighted(data!.byCaptionStyle, "avgCtr")}%`} sub="clicks per impression" />+ <StatTile icon={<TrendingUp size={16} />} label="Published" value={String(data!.published)} sub={`of ${data!.total} clips`} />+ </div>++ {insights.length > 0 && (+ <div className="section insights">+ <div className="section-label">What's working</div>+ <div className="insight-grid">+ {insights.map((i) => (+ <div key={i.label} className="insight">+ <div className="insight-label">{i.label}</div>+ <div className="insight-value">{i.value}</div>+ <div className="insight-metric">{i.metric}</div>+ </div>+ ))}+ </div>+ </div>+ )}++ <div className="analytics-charts">+ <BarGroup title="Retention by content type" hint="What holds viewers" rows={data!.byContentType} metric="avgRetention" />+ <BarGroup title="CTR by caption style" hint="How packaging drives clicks" rows={data!.byCaptionStyle} metric="avgCtr" />+ <BarGroup title="Retention by length" hint="The sweet spot for watch time" rows={data!.byLength} metric="avgRetention" />+ <BarGroup title="Views by content type" hint="What reaches the most people" rows={data!.byContentType} metric="avgViews" /></div>- <div className="section">+ <div className="section card"><div className="section-label">Top clips</div>- {data.top.map((c) => (- <Link key={c.id} to={`/clip/${c.id}`} style={{ display: "flex", alignItems: "center", gap: 12, padding: "9px 0", borderBottom: "1px solid var(--border)", textDecoration: "none", color: "inherit" }}>+ {data!.top.map((c, i) => (+ <Link key={c.id} to={`/clip/${c.id}`} className="top-clip">+ <span className="rank-badge">{i + 1}</span><div style={{ flex: 1, minWidth: 0 }}>- <div style={{ fontSize: 13, fontWeight: 600, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{c.title}</div>+ <div className="top-clip-title">{c.title}</div><div className="hint" style={{ marginTop: 2 }}>{fmt(c.duration)} · {c.caption_style}{c.content_type ? ` · ${c.content_type}` : ""}</div></div>- <div style={{ display: "flex", gap: 16, fontSize: 12, fontVariantNumeric: "tabular-nums" }}>- <span title="Views (reach)">{fmtViews(c.metrics?.views || 0)} views</span>- {c.metrics?.retention != null && <span style={{ color: "var(--text2)" }} title="Retention (content)">{c.metrics.retention}% ret</span>}- {c.metrics?.ctr != null && <span style={{ color: "var(--text2)" }} title="CTR (packaging)">{c.metrics.ctr}% ctr</span>}+ <div className="top-clip-metrics">+ <span className="metric-strong">{fmtViews(c.metrics?.views || 0)} views</span>+ {c.metrics?.retention != null && <span>{c.metrics.retention}% ret</span>}+ {c.metrics?.ctr != null && <span>{c.metrics.ctr}% ctr</span>}</div></Link>))}diff --git a/src/ui/client/AssetPicker.tsx b/src/ui/client/AssetPicker.tsxnew file mode 100644index 0000000..c1380d9--- /dev/null+++ b/src/ui/client/AssetPicker.tsx@@ -0,0 +1,117 @@+import React, { useEffect, useRef, useState } from "react";+import { Link } from "react-router-dom";+import { ChevronDown, Check, Upload } from "lucide-react";+import { basename } from "./lib";+import { useAssets, assetSrc, ASSET_GROUPS, type Asset, type AssetType } from "./useAssets";++function Thumb({ asset }: { asset: Asset }) {+ const src = assetSrc(asset.name);+ if (asset.type === "logo" || asset.type === "image") {+ return <img className="picker-thumb" src={src} alt="" />;+ }+ if (asset.type === "outro" || asset.type === "intro" || asset.type === "video") {+ return <video className="picker-thumb" src={src} muted preload="metadata" />;+ }+ return <div className="picker-thumb picker-thumb-file" />;+}++export default function AssetPicker({+ type,+ value,+ onChange,+ label,+ allowNone = true,+ disabled = false,+}: {+ type: AssetType;+ value: string;+ onChange: (path: string) => void;+ label?: string;+ allowNone?: boolean;+ disabled?: boolean;+}) {+ const { assets, uploadFile } = useAssets({ live: false });+ const [open, setOpen] = useState(false);+ const [uploading, setUploading] = useState(false);+ const ref = useRef<HTMLDivElement>(null);+ const fileRef = useRef<HTMLInputElement>(null);++ const options = assets.filter((a) => matchesGroup(a.type, type));+ const current = options.find((a) => a.path === value || a.name === value) || null;++ useEffect(() => {+ if (!open) return;+ const close = (e: MouseEvent) => {+ if (ref.current && !ref.current.contains(e.target as Node)) setOpen(false);+ };+ document.addEventListener("mousedown", close);+ return () => document.removeEventListener("mousedown", close);+ }, [open]);++ async function onUpload(f: File) {+ setUploading(true);+ try {+ const asset = await uploadFile(f, type);+ onChange(asset.path);+ setOpen(false);+ } finally {+ setUploading(false);+ }+ }++ return (+ <div className="asset-picker" ref={ref}>+ {label && <span className="asset-picker-label">{label}</span>}+ <button className="asset-picker-btn" disabled={disabled} onClick={() => setOpen((v) => !v)}>+ {current ? (+ <>+ <Thumb asset={current} />+ <span className="asset-picker-name">{current.name}</span>+ </>+ ) : (+ <span className="asset-picker-name muted">{value ? basename(value) : "None"}</span>+ )}+ <ChevronDown size={14} style={{ marginLeft: "auto", flexShrink: 0 }} />+ </button>++ {open && (+ <div className="asset-picker-menu">+ {allowNone && (+ <button className="asset-picker-opt" onClick={() => { onChange(""); setOpen(false); }}>+ <span className="asset-picker-name muted">None</span>+ {!value && <Check size={14} />}+ </button>+ )}+ {options.map((a) => (+ <button key={a.name} className="asset-picker-opt" onClick={() => { onChange(a.path); setOpen(false); }}>+ <Thumb asset={a} />+ <span className="asset-picker-name">{a.name}</span>+ {a.default && <span className="asset-default-tag">default</span>}+ {current?.name === a.name && <Check size={14} style={{ marginLeft: "auto" }} />}+ </button>+ ))}+ <input+ ref={fileRef}+ type="file"+ accept={ASSET_GROUPS.find((g) => g.type === type)?.accept ?? "*/*"}+ style={{ display: "none" }}+ onChange={(e) => { const f = e.target.files?.[0]; e.target.value = ""; if (f) onUpload(f); }}+ />+ <div className="asset-picker-foot">+ <button className="asset-picker-opt" disabled={uploading} onClick={() => fileRef.current?.click()}>+ {uploading ? <div className="spinner sm" /> : <Upload size={14} />}+ <span className="asset-picker-name">Upload new</span>+ </button>+ <Link to="/assets" className="asset-picker-link" onClick={() => setOpen(false)}>Manage</Link>+ </div>+ </div>+ )}+ </div>+ );+}++function matchesGroup(assetType: AssetType, groupType: AssetType): boolean {+ if (groupType === "outro") return assetType === "outro" || assetType === "video";+ if (groupType === "music") return assetType === "music" || assetType === "audio";+ return assetType === groupType;+}diff --git a/src/ui/client/AssetsPage.tsx b/src/ui/client/AssetsPage.tsxnew file mode 100644index 0000000..d51c106--- /dev/null+++ b/src/ui/client/AssetsPage.tsx@@ -0,0 +1,556 @@+import React, { useEffect, useRef, useState } from "react";+import { PageHeader } from "./Page";+import { createPortal } from "react-dom";+import { Star, Download, Trash2, Link2, Plus, MoreVertical, Play, Pause } from "lucide-react";+import { api, basename, fmt } from "./lib";+import { useJob } from "./useJob";+import Tooltip from "./Tooltip";+import ConfirmDialog from "./ConfirmDialog";+import {+ useAssets,+ assetSrc,+ ASSET_GROUPS,+ type Asset,+ type AssetType,+} from "./useAssets";++const DEFAULTABLE: AssetType[] = ["logo", "outro", "intro", "music"];++function AudioPlayer({ src }: { src: string }) {+ const ref = useRef<HTMLAudioElement>(null);+ const [playing, setPlaying] = useState(false);+ const [t, setT] = useState(0);+ const [dur, setDur] = useState(0);++ const toggle = () => {+ const a = ref.current;+ if (!a) return;+ a.paused ? a.play() : a.pause();+ };+ const seek = (clientX: number, el: HTMLDivElement) => {+ const a = ref.current;+ if (!a || !dur) return;+ const r = el.getBoundingClientRect();+ a.currentTime = Math.max(0, Math.min(1, (clientX - r.left) / r.width)) * dur;+ };+ const pct = dur ? (t / dur) * 100 : 0;++ return (+ <div className="asset-audio-player">+ <audio+ ref={ref}+ src={src}+ preload="metadata"+ onPlay={() => setPlaying(true)}+ onPause={() => setPlaying(false)}+ onTimeUpdate={(e) => setT(e.currentTarget.currentTime)}+ onLoadedMetadata={(e) => setDur(e.currentTarget.duration)}+ />+ <button className="asset-audio-btn" onClick={toggle} aria-label={playing ? "Pause" : "Play"}>+ {playing ? <Pause size={16} fill="currentColor" /> : <Play size={16} fill="currentColor" />}+ </button>+ <div+ className="asset-audio-track"+ onPointerDown={(e) => { e.currentTarget.setPointerCapture(e.pointerId); seek(e.clientX, e.currentTarget); }}+ onPointerMove={(e) => { if (e.buttons) seek(e.clientX, e.currentTarget); }}+ >+ <div className="asset-audio-fill" style={{ width: `${pct}%` }} />+ </div>+ <span className="asset-audio-time">{fmt(t || 0)}</span>+ </div>+ );+}++function Preview({ asset, onOpen }: { asset: Asset; onOpen: () => void }) {+ const src = assetSrc(asset.name);+ if (asset.type === "logo" || asset.type === "image") {+ return <img className="asset-thumb clickable" src={src} alt={asset.name} loading="lazy" onClick={onOpen} />;+ }+ if (asset.type === "outro" || asset.type === "intro" || asset.type === "video") {+ return <video className="asset-thumb clickable" src={src} muted preload="metadata" onClick={onOpen} />;+ }+ if (asset.type === "music" || asset.type === "audio") {+ return <div className="asset-thumb asset-thumb-audio"><AudioPlayer src={src} /></div>;+ }+ return <div className="asset-thumb asset-thumb-file clickable" onClick={onOpen}>{extLabel(asset.path)}</div>;+}++function AssetLightbox({ asset, onClose }: { asset: Asset; onClose: () => void }) {+ const src = assetSrc(asset.name);+ return createPortal(+ <div className="modal-overlay" onClick={onClose}>+ <div className="modal-body" onClick={(e) => e.stopPropagation()}>+ {(asset.type === "logo" || asset.type === "image") && (+ <img src={src} alt={asset.name} style={{ width: "100%", borderRadius: 16, background: "var(--bg2)" }} />+ )}+ {(asset.type === "outro" || asset.type === "intro" || asset.type === "video") && (+ <video src={src} controls autoPlay style={{ width: "100%", borderRadius: 16 }} />+ )}+ {(asset.type === "music" || asset.type === "audio") && (+ <div className="lightbox-audio"><AudioPlayer src={src} /></div>+ )}+ {asset.type === "other" && (+ <div className="lightbox-file">{basename(asset.path)}</div>+ )}+ <div className="lightbox-name">{asset.name}</div>+ </div>+ </div>,+ document.body,+ );+}++function extLabel(path: string): string {+ const ext = (path.split(".").pop() || "").toUpperCase();+ return ext.length <= 4 ? ext : "FILE";+}++const MENU_WIDTH = 150;++function OverflowMenu({ items }: { items: { label: string; onClick: () => void; danger?: boolean }[] }) {+ const [open, setOpen] = useState(false);+ const [pos, setPos] = useState<{ top: number; left: number } | null>(null);+ const btnRef = useRef<HTMLButtonElement>(null);++ useEffect(() => {+ if (!open) return;+ // Skip the trigger so its onClick can toggle closed, not reopen.+ const onDocMouseDown = (e: MouseEvent) => {+ if (btnRef.current?.contains(e.target as Node)) return;+ setOpen(false);+ };+ const dismiss = () => setOpen(false);+ document.addEventListener("mousedown", onDocMouseDown);+ window.addEventListener("scroll", dismiss, true);+ window.addEventListener("resize", dismiss);+ return () => {+ document.removeEventListener("mousedown", onDocMouseDown);+ window.removeEventListener("scroll", dismiss, true);+ window.removeEventListener("resize", dismiss);+ };+ }, [open]);++ function openMenu() {+ const r = btnRef.current?.getBoundingClientRect();+ if (r) {+ const menuHeight = items.length * 34 + 8;+ const left = Math.max(8, Math.min(r.right - MENU_WIDTH, window.innerWidth - MENU_WIDTH - 8));+ let top = r.bottom + 4;+ if (top + menuHeight > window.innerHeight - 8) top = Math.max(8, r.top - menuHeight - 4);+ setPos({ top, left });+ }+ setOpen((v) => !v);+ }++ return (+ <>+ <button ref={btnRef} className="icon-btn" onClick={openMenu}>+ <MoreVertical size={16} />+ </button>+ {open && pos && createPortal(+ <div+ className="overflow-menu"+ style={{ position: "fixed", top: pos.top, left: pos.left, right: "auto", width: MENU_WIDTH }}+ onMouseDown={(e) => e.stopPropagation()}+ >+ {items.map((it) => (+ <button+ key={it.label}+ className="overflow-menu-item"+ style={it.danger ? { color: "var(--red)" } : undefined}+ onClick={() => { setOpen(false); it.onClick(); }}+ >+ {it.label}+ </button>+ ))}+ </div>,+ document.body,+ )}+ </>+ );+}++function AssetCard({+ asset,+ selected,+ canDefault,+ onToggleSelect,+ onToggleDefault,+ onRename,+ onDelete,+ onOpen,+}: {+ asset: Asset;+ selected: boolean;+ canDefault: boolean;+ onToggleSelect: () => void;+ onToggleDefault: () => void;+ onRename: (newName: string) => void;+ onDelete: () => void;+ onOpen: () => void;+}) {+ const [renaming, setRenaming] = useState(false);+ const [draft, setDraft] = useState(asset.name);++ function commitRename() {+ // Guard against Enter + unmount-blur both firing on the same rename.+ if (!renaming) return;+ setRenaming(false);+ const next = draft.trim();+ if (next && next !== asset.name) onRename(next);+ else setDraft(asset.name);+ }++ return (+ <div className={`asset-card${selected ? " selected" : ""}`}>+ <label className="asset-check">+ <input type="checkbox" checked={selected} onChange={onToggleSelect} />+ </label>+ <Preview asset={asset} onOpen={onOpen} />+ <div className="asset-row">+ <div className="asset-meta">+ {renaming ? (+ <input+ className="asset-rename"+ value={draft}+ autoFocus+ onChange={(e) => setDraft(e.target.value)}+ onBlur={commitRename}+ onKeyDown={(e) => {+ if (e.key === "Enter") commitRename();+ if (e.key === "Escape") { setDraft(asset.name); setRenaming(false); }+ }}+ />+ ) : (+ <div className="asset-name" title={asset.path}>+ {asset.name}+ {asset.default && <span className="asset-default-tag">default</span>}+ </div>+ )}+ <div className="asset-sub">{basename(asset.path)}</div>+ </div>+ <div className="asset-actions">+ {canDefault && (+ <Tooltip label={asset.default ? "Remove default" : "Set as default"}>+ <button+ className={`icon-btn${asset.default ? " active" : ""}`}+ onClick={onToggleDefault}+ >+ <Star size={15} fill={asset.default ? "currentColor" : "none"} />+ </button>+ </Tooltip>+ )}+ <OverflowMenu+ items={[+ { label: "Rename", onClick: () => { setDraft(asset.name); setRenaming(true); } },+ { label: "Download", onClick: () => triggerDownload(asset.name) },+ { label: "Delete", onClick: onDelete, danger: true },+ ]}+ />+ </div>+ </div>+ </div>+ );+}++function triggerDownload(name: string) {+ const a = document.createElement("a");+ a.href = `${assetSrc(name)}?dl=1`;+ a.download = "";+ document.body.appendChild(a);+ a.click();+ a.remove();+}++export default function AssetsPage() {+ const { assets, loading, error, uploadFile, importUrl, setDefault, clearDefault, rename, remove } = useAssets();+ const [selected, setSelected] = useState<Set<string>>(new Set());+ const [busy, setBusy] = useState<string | null>(null);+ const [msg, setMsg] = useState<string | null>(null);+ const [preview, setPreview] = useState<Asset | null>(null);+ const [pendingDelete, setPendingDelete] = useState<{ title: string; message: string; run: () => void } | null>(null);++ const wrap = (p: Promise<unknown>) => p.catch((e) => setMsg(e instanceof Error ? e.message : String(e)));++ function toggleSelect(name: string) {+ setSelected((prev) => {+ const next = new Set(prev);+ next.has(name) ? next.delete(name) : next.add(name);+ return next;+ });+ }++ async function performDelete(name: string) {+ await wrap(remove(name));+ setSelected((p) => {+ const n = new Set(p);+ n.delete(name);+ return n;+ });+ }++ function requestDelete(name: string) {+ setPendingDelete({+ title: `Delete "${name}"?`,+ message: "This removes it from your asset library and cannot be undone.",+ run: () => performDelete(name),+ });+ }++ function requestBulkDelete() {+ const names = [...selected];+ setPendingDelete({+ title: `Delete ${names.length} asset${names.length > 1 ? "s" : ""}?`,+ message: "This removes them from your asset library and cannot be undone.",+ run: async () => { for (const name of names) await performDelete(name); },+ });+ }++ function bulkDownload() {+ // Stagger so browsers don't block rapid multiple downloads.+ [...selected].forEach((name, i) => setTimeout(() => triggerDownload(name), i * 300));+ }++ return (+ <div className="app">+ <PageHeader title="Assets" />++ {error && <div className="error-bar">{error}</div>}+ {msg && <div className="error-bar" onClick={() => setMsg(null)}>{msg}</div>}++ {selected.size > 0 && (+ <div className="asset-bulkbar">+ <span>{selected.size} selected</span>+ <button className="btn btn-ghost btn-sm" onClick={bulkDownload}>+ <Download size={14} /> Download+ </button>+ <button className="btn btn-ghost btn-sm" onClick={() => setSelected(new Set())}>Clear</button>+ <button className="btn btn-danger btn-sm" onClick={requestBulkDelete}>+ <Trash2 size={14} /> Delete+ </button>+ </div>+ )}++ <BrandDefaults onError={setMsg} />++ {loading ? (+ <div style={{ display: "flex", alignItems: "center", gap: 10, color: "var(--text2)" }}>+ <div className="spinner sm" /> Loading…+ </div>+ ) : (+ ASSET_GROUPS.map((group) => (+ <AssetSection+ key={group.type}+ group={group}+ assets={assets.filter((a) => matchesGroup(a.type, group.type))}+ selected={selected}+ canDefault={DEFAULTABLE.includes(group.type)}+ onToggleSelect={toggleSelect}+ onDelete={requestDelete}+ onOpen={setPreview}+ onRename={(name, next) => wrap(rename(name, next))}+ onToggleDefault={(a) => wrap(a.default ? clearDefault(a.name) : setDefault(a.name))}+ onUpload={async (file) => {+ setBusy(group.type);+ try {+ await uploadFile(file, group.type);+ } catch (e) {+ setMsg(e instanceof Error ? e.message : "Upload failed");+ } finally {+ setBusy(null);+ }+ }}+ onImportUrl={(url) => importUrl(url, group.type)}+ busy={busy === group.type}+ />+ ))+ )}++ <div className="asset-bottom-space" />++ {preview && <AssetLightbox asset={preview} onClose={() => setPreview(null)} />}+ <ConfirmDialog+ open={!!pendingDelete}+ title={pendingDelete?.title || ""}+ message={pendingDelete?.message}+ onConfirm={() => { pendingDelete?.run(); setPendingDelete(null); }}+ onCancel={() => setPendingDelete(null)}+ />+ </div>+ );+}++const CAPTION_STYLES: { id: string; label: string; className: string; sample: string }[] = [+ { id: "hormozi", label: "Hormozi", className: "cap-hormozi", sample: "THIS CHANGES EVERYTHING" },+ { id: "karaoke", label: "Karaoke", className: "cap-karaoke", sample: "word by word reveal" },+ { id: "subtle", label: "Subtle", className: "cap-subtle", sample: "clean and understated" },+ { id: "branded", label: "Branded", className: "cap-branded", sample: "PILL HIGHLIGHT" },+];++function BrandDefaults({ onError }: { onError: (m: string) => void }) {+ const [style, setStyle] = useState<string | null>(null);++ useEffect(() => {+ api<{ settings?: { captionStyle?: string } }>("/ui-state")+ .then((s) => setStyle(s.settings?.captionStyle || "branded"))+ .catch(() => setStyle("branded"));+ }, []);++ function pick(id: string) {+ setStyle(id);+ api("/ui-state", {+ method: "POST",+ body: JSON.stringify({ _source: "ui", settings: { captionStyle: id } }),+ }).catch((e) => onError(e instanceof Error ? e.message : "Failed to save default"));+ }++ return (+ <div className="section">+ <div className="section-label">Default caption style</div>+ <div className="cap-grid">+ {CAPTION_STYLES.map((s) => (+ <button+ key={s.id}+ className={`cap-card${style === s.id ? " selected" : ""}`}+ onClick={() => pick(s.id)}+ >+ <div className="cap-preview">+ <span className={s.className}>{s.sample}</span>+ </div>+ <div className="cap-label">+ {s.label}+ {style === s.id && <span className="asset-default-tag">default</span>}+ </div>+ </button>+ ))}+ </div>+ </div>+ );+}++function matchesGroup(assetType: AssetType, groupType: AssetType): boolean {+ if (groupType === "outro") return assetType === "outro" || assetType === "video";+ if (groupType === "music") return assetType === "music" || assetType === "audio";+ return assetType === groupType;+}++function AssetSection({+ group,+ assets,+ selected,+ canDefault,+ onToggleSelect,+ onDelete,+ onOpen,+ onRename,+ onToggleDefault,+ onUpload,+ onImportUrl,+ busy,+}: {+ group: { type: AssetType; label: string; accept: string };+ assets: Asset[];+ selected: Set<string>;+ canDefault: boolean;+ onToggleSelect: (name: string) => void;+ onDelete: (name: string) => void;+ onOpen: (asset: Asset) => void;+ onRename: (name: string, newName: string) => void;+ onToggleDefault: (asset: Asset) => void;+ onUpload: (file: File) => void;+ onImportUrl: (url: string) => Promise<string>;+ busy: boolean;+}) {+ const fileRef = useRef<HTMLInputElement>(null);+ const [urlOpen, setUrlOpen] = useState(false);+ const [urlDraft, setUrlDraft] = useState("");+ const [jobId, setJobId] = useState<string | null>(null);+ const [jobErr, setJobErr] = useState<string | null>(null);+ const job = useJob(jobId);++ useEffect(() => {+ if (job?.status === "done") setJobId(null);+ if (job?.status === "error") {+ setJobErr(job.error || "Download failed");+ setJobId(null);+ }+ }, [job?.status]);++ async function submitUrl() {+ const u = urlDraft.trim();+ if (!u) return;+ setUrlDraft("");+ setUrlOpen(false);+ setJobErr(null);+ try {+ setJobId(await onImportUrl(u));+ } catch (e) {+ setJobErr(e instanceof Error ? e.message : "Download failed");+ }+ }++ return (+ <div className="section">+ <div className="asset-section-head">+ <div className="section-label" style={{ margin: 0 }}>+ {group.label} <span className="asset-count">{assets.length}</span>+ </div>+ <button className="btn btn-ghost btn-sm asset-url-toggle" onClick={() => setUrlOpen((v) => !v)}>+ <Link2 size={14} /> Add from URL+ </button>+ </div>++ {urlOpen && (+ <div className="asset-url-row">+ <input+ type="text"+ placeholder="https://… (direct file or video URL)"+ value={urlDraft}+ autoFocus+ onChange={(e) => setUrlDraft(e.target.value)}+ onKeyDown={(e) => e.key === "Enter" && submitUrl()}+ />+ <button className="btn btn-primary btn-sm" onClick={submitUrl}>Add</button>+ </div>+ )}++ {jobErr && <div className="hint" style={{ color: "var(--red)" }}>{jobErr}</div>}+ {jobId && (+ <div className="file-badge">+ <div className="spinner sm" />+ <div className="name">Downloading{job?.progress ? ` · ${Math.round(job.progress)}%` : "…"}</div>+ </div>+ )}++ <div className="asset-grid">+ {assets.map((a) => (+ <AssetCard+ key={a.name}+ asset={a}+ selected={selected.has(a.name)}+ canDefault={canDefault}+ onToggleSelect={() => onToggleSelect(a.name)}+ onToggleDefault={() => onToggleDefault(a)}+ onRename={(next) => onRename(a.name, next)}+ onDelete={() => onDelete(a.name)}+ onOpen={() => onOpen(a)}+ />+ ))}+ <input+ ref={fileRef}+ type="file"+ accept={group.accept}+ style={{ display: "none" }}+ onChange={(e) => {+ const f = e.target.files?.[0];+ if (f) onUpload(f);+ e.target.value = "";+ }}+ />+ <button className="asset-add-tile" disabled={busy} onClick={() => fileRef.current?.click()}>+ {busy ? <div className="spinner sm" /> : <Plus size={20} />}+ <span>Upload {group.label.toLowerCase()}</span>+ </button>+ </div>+ </div>+ );+}diff --git a/src/ui/client/ClipDetail.tsx b/src/ui/client/ClipDetail.tsxindex c6cf0c7..39a7201 100644--- a/src/ui/client/ClipDetail.tsx+++ b/src/ui/client/ClipDetail.tsx@@ -1,4 +1,5 @@import React, { useEffect, useRef, useState } from "react";+import { PageHeader } from "./Page";import { Link, useParams, useNavigate } from "react-router-dom";import { api, upload, fmt, basename, labelStyle } from "./lib";import ClipPlayer from "./ClipPlayer";@@ -85,7 +86,7 @@ export default function ClipDetail() {}, []);if (loading) return <div className="app"><div style={{ display: "flex", alignItems: "center", gap: 10, color: "var(--text2)", padding: 40 }}><div className="spinner sm" /> Loading…</div></div>;- if (!clip) return <div className="app"><div className="header"><h1>Clip not found</h1></div><Link to="/" style={{ color: "var(--accent)", display: "inline-flex", alignItems: "center", gap: 4 }}><BackIcon /> Library</Link></div>;+ if (!clip) return <div className="app"><PageHeader title="Clip not found" /><Link to="/" style={{ color: "var(--accent)", display: "inline-flex", alignItems: "center", gap: 4 }}><BackIcon /> Library</Link></div>;const tc = clip.thumbnail_config || {};const dirty = title !== clip.title || captionStyle !== clip.caption_style;@@ -217,18 +218,16 @@ export default function ClipDetail() {return (<div className="app">- <div className="header">- <Link to="/" style={{ fontSize: 12, color: "var(--text3)", textDecoration: "none", display: "inline-flex", alignItems: "center", gap: 4 }}><BackIcon size={12} /> Library</Link>- <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-end", gap: 16, marginTop: 8, flexWrap: "wrap" }}>- <h1 style={{ margin: 0 }}>{clip.title}</h1>- <div className="set-actions">- <a className="btn btn-ghost btn-sm" href={`/api/clips/${clip.id}/download`} download style={{ textDecoration: "none" }}>Download</a>- <button className="btn btn-ghost btn-sm" onClick={reopen} disabled={busy !== null}>{busy === "reopen" ? <div className="spinner sm" /> : "Reopen in editor"}</button>- {davinciOn && <button className="btn btn-ghost btn-sm" onClick={exportDavinci} disabled={busy !== null}>{busy === "davinci" ? <div className="spinner sm" /> : "Export for DaVinci"}</button>}- <button className="btn btn-danger btn-sm" onClick={del} disabled={busy !== null}>{busy === "delete" ? <div className="spinner sm" /> : "Delete"}</button>- </div>- </div>- </div>+ <PageHeader+ back={<Link to="/" style={{ fontSize: 12, color: "var(--text3)", textDecoration: "none", display: "inline-flex", alignItems: "center", gap: 4 }}><BackIcon size={12} /> Library</Link>}+ title={clip.title}+ actions={<>+ <a className="btn btn-ghost btn-sm" href={`/api/clips/${clip.id}/download`} download style={{ textDecoration: "none" }}>Download</a>+ <button className="btn btn-ghost btn-sm" onClick={reopen} disabled={busy !== null}>{busy === "reopen" ? <div className="spinner sm" /> : "Reopen in editor"}</button>+ {davinciOn && <button className="btn btn-ghost btn-sm" onClick={exportDavinci} disabled={busy !== null}>{busy === "davinci" ? <div className="spinner sm" /> : "Export for DaVinci"}</button>}+ <button className="btn btn-danger btn-sm" onClick={del} disabled={busy !== null}>{busy === "delete" ? <div className="spinner sm" /> : "Delete"}</button>+ </>}+ /><div className="clip-detail"><div className="clip-detail-player">diff --git a/src/ui/client/ConfigPage.tsx b/src/ui/client/ConfigPage.tsxindex 0ea10b5..58c3e6d 100644--- a/src/ui/client/ConfigPage.tsx+++ b/src/ui/client/ConfigPage.tsx@@ -1,4 +1,5 @@import React, { useEffect, useRef, useState } from "react";+import { PageHeader } from "./Page";import { api, upload } from "./lib";type SettingRow = {@@ -149,7 +150,7 @@ export default function ConfigPage() {return (<div className="app" style={{ maxWidth: 760 }}>- <div className="header"><h1>Config</h1></div>+ <PageHeader title="Config" /><div className="section">{statusError ? (@@ -177,7 +178,7 @@ export default function ConfigPage() {<span className="v" style={{ color: aiCli.available ? "var(--green)" : "var(--yellow)" }}>{aiCli.available? `Found ${aiCli.candidates?.map((c) => c.engine).join(", ") || "CLI"}`- : "Not detected — set a path below or install Claude Code / Codex"}+ : "Not detected. Set a path below or install Claude Code / Codex"}</span></div>{(aiCli.candidates || []).map((c) => (@@ -246,7 +247,7 @@ export default function ConfigPage() {<div className="set-file"><inputtype="password"- placeholder={s.set ? "Replace token" : (s.placeholder || "token")}+ placeholder={s.set ? "Replace token" : (s.placeholder || "Token")}value={secretInputs[s.key] ?? ""}onChange={(e) => setSecretInputs((p) => ({ ...p, [s.key]: e.target.value }))}style={{ flex: 1 }}diff --git a/src/ui/client/ConfirmDialog.tsx b/src/ui/client/ConfirmDialog.tsxnew file mode 100644index 0000000..6d7b94d--- /dev/null+++ b/src/ui/client/ConfirmDialog.tsx@@ -0,0 +1,37 @@+import React from "react";+import { createPortal } from "react-dom";++export default function ConfirmDialog({+ open,+ title,+ message,+ confirmLabel = "Delete",+ danger = true,+ onConfirm,+ onCancel,+}: {+ open: boolean;+ title: string;+ message?: string;+ confirmLabel?: string;+ danger?: boolean;+ onConfirm: () => void;+ onCancel: () => void;+}) {+ if (!open) return null;+ return createPortal(+ <div className="modal-overlay" onClick={onCancel}>+ <div className="modal-body confirm-dialog" onClick={(e) => e.stopPropagation()}>+ <h3>{title}</h3>+ {message && <p>{message}</p>}+ <div className="confirm-actions">+ <button className="btn btn-ghost btn-sm" onClick={onCancel}>Cancel</button>+ <button className={`btn btn-sm ${danger ? "btn-danger" : "btn-primary"}`} autoFocus onClick={onConfirm}>+ {confirmLabel}+ </button>+ </div>+ </div>+ </div>,+ document.body,+ );+}diff --git a/src/ui/client/ContentStudio.tsx b/src/ui/client/ContentStudio.tsxindex 0edf566..aca73d0 100644--- a/src/ui/client/ContentStudio.tsx+++ b/src/ui/client/ContentStudio.tsx@@ -1,4 +1,5 @@import React, { useEffect, useState } from "react";+import { PageHeader } from "./Page";import { api, basename, labelStyle } from "./lib";import CopyButton from "./CopyButton";@@ -179,7 +180,7 @@ export default function ContentStudio() {<inputvalue={regenNote}onChange={(e) => setRegenNote(e.target.value)}- placeholder="optional: how to change it"+ placeholder="Optional: how to change it"style={{ flex: 1, fontSize: 12 }}onKeyDown={(e) => { if (e.key === "Enter") regenerate(field); }}autoFocus@@ -199,9 +200,7 @@ export default function ContentStudio() {return (<div className="app">- <div className="header">- <h1>Content studio</h1>- </div>+ <PageHeader title="Content studio" /><div style={{ display: "flex", gap: 24, alignItems: "flex-start", flexWrap: "wrap" }}><div style={{ flex: "1 1 380px", minWidth: 320 }}>@@ -218,8 +217,8 @@ export default function ContentStudio() {<div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", margin: "18px 0 0" }}><label style={{ ...labelStyle, marginBottom: 0 }}>Transcript</label>{sessionText && (- <button className="btn btn-ghost btn-sm" onClick={() => setTranscript(sessionText)} disabled={isBusy} title={sessionName}>- Use current episode{sessionName ? ` · ${sessionName}` : ""}+ <button className="btn btn-ghost btn-sm" onClick={() => setTranscript(sessionText)} disabled={isBusy} title={sessionName ? `Use transcript from ${sessionName}` : "Use the current episode transcript"}>+ Use current episode</button>)}</div>diff --git a/src/ui/client/EpisodeWorkspace.jsx b/src/ui/client/EpisodeWorkspace.jsxindex 401914e..af50159 100644--- a/src/ui/client/EpisodeWorkspace.jsx+++ b/src/ui/client/EpisodeWorkspace.jsx@@ -13,6 +13,7 @@ import {Users as UsersGlyph,Inbox,X,+ RotateCcw,Plus,Play,Pencil,@@ -24,6 +25,9 @@ import {ArrowRight,} from 'lucide-react';import CopyButton from './CopyButton';+import AssetPicker from './AssetPicker';+import RecentSources from './RecentSources';+import { PageHeader } from './Page';const fmt = (s) => `${Math.floor(s / 60)}:${String(Math.floor(s % 60)).padStart(2, '0')}`;const isHttpUrl = (value) => /^https?:\/\//i.test(value.trim());@@ -515,12 +519,10 @@ const isHttpUrl = (value) => /^https?:\/\//i.test(value.trim());const [format, setFormat] = useState('vertical');const [showTikTokFrame, setShowTikTokFrame] = useState(false);const [logoPath, setLogoPath] = useState('');- const logoRef = useRef();const [outroPath, setOutroPath] = useState('');+ const [introPath, setIntroPath] = useState('');const initializedRef = useRef(false);- const outroRef = useRef();const videoFileRef = useRef();- const [outroUploading, setOutroUploading] = useState(false);const [transcriptDragOver, setTranscriptDragOver] = useState(false);const [transcriptFileName, setTranscriptFileName] = useState('');@@ -541,8 +543,6 @@ const isHttpUrl = (value) => /^https?:\/\//i.test(value.trim());const [retryIdx, setRetryIdx] = useState(null);const [retryJobId, setRetryJobId] = useState(null);const retryStream = useJob(retryJobId);-- const [logoUploading, setLogoUploading] = useState(false);const [browsing, setBrowsing] = useState(false);const [downloadingVideo, setDownloadingVideo] = useState(false);const [downloadJobId, setDownloadJobId] = useState(null);@@ -607,6 +607,7 @@ const isHttpUrl = (value) => /^https?:\/\//i.test(value.trim());if (d.format) setFormat(d.format);if (d.logo_path !== undefined) setLogoPath(d.logo_path || '');if (d.outro_path !== undefined) setOutroPath(d.outro_path || '');+ if (d.intro_path !== undefined) setIntroPath(d.intro_path || '');if (d.video_path !== undefined) {const nextVideoPath = d.video_path || '';const changedVideo = nextVideoPath.trim() !== videoPath.trim();@@ -646,7 +647,7 @@ const isHttpUrl = (value) => /^https?:\/\//i.test(value.trim());try {await api('/presets', { method: 'POST', body: JSON.stringify({action: 'save', name: presetName.trim(),- config: { caption_style: captionStyle, crop_strategy: cropStrategy, format, logo_path: logoPath, outro_path: outroPath, video_path: videoPath.trim(), whisper_model: whisperModel, transcription_engine: transcriptionEngine, time_adjust: timeAdjust, clean_fillers: cleanFillers, quality, top_clips: topClips, min_clip_duration: minDuration, max_clip_duration: maxDuration, energy_boost: energyBoost }+ config: { caption_style: captionStyle, crop_strategy: cropStrategy, format, logo_path: logoPath, outro_path: outroPath, intro_path: introPath, video_path: videoPath.trim(), whisper_model: whisperModel, transcription_engine: transcriptionEngine, time_adjust: timeAdjust, clean_fillers: cleanFillers, quality, top_clips: topClips, min_clip_duration: minDuration, max_clip_duration: maxDuration, energy_boost: energyBoost }})});setActivePreset(presetName.trim());setPresetName(''); setShowPresetSave(false);@@ -797,7 +798,7 @@ const isHttpUrl = (value) => /^https?:\/\//i.test(value.trim());filePath: file?.file_path || '',suggestions,deselectedIndices: Array.from(deselected),- settings: { captionStyle, cropStrategy, format, logoPath, outroPath },+ settings: { captionStyle, cropStrategy, format, logoPath, outroPath, introPath },phase,results,energyData,@@ -806,7 +807,7 @@ const isHttpUrl = (value) => /^https?:\/\//i.test(value.trim());if (key === prevSyncRef.current) return;prevSyncRef.current = key;fetch('/api/ui-state', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: key }).catch(() => { });- }, [videoPath, file, suggestions, deselected, captionStyle, cropStrategy, format, logoPath, outroPath, phase, results, energyData]);+ }, [videoPath, file, suggestions, deselected, captionStyle, cropStrategy, format, logoPath, outroPath, introPath, phase, results, energyData]);// Sync transcript separately (large payload)const prevTranscriptRef = useRef(null);@@ -858,6 +859,7 @@ const isHttpUrl = (value) => /^https?:\/\//i.test(value.trim());if (d.settings.format) setFormat(d.settings.format);if (d.settings.logoPath !== undefined) setLogoPath(d.settings.logoPath);if (d.settings.outroPath !== undefined) setOutroPath(d.settings.outroPath);+ if (d.settings.introPath !== undefined) setIntroPath(d.settings.introPath);}// Mark initialized after first state restoration so sync useEffects don't overwrite with defaultsif (sseEvent.type === 'state') {@@ -1026,7 +1028,7 @@ const isHttpUrl = (value) => /^https?:\/\//i.test(value.trim());method: 'POST', body: JSON.stringify({video_path: vp,clips: sc.map(c => ({ start_second: c.start_second, end_second: c.end_second, title: c.title.slice(0, 40), caption_style: captionStyle, crop_strategy: cropStrategy, format })),- transcript_words: transcript?.words || [], logo_path: logoPath || undefined, outro_path: outroPath || undefined, clean_fillers: cleanFillers || undefined,+ transcript_words: transcript?.words || [], logo_path: logoPath || undefined, outro_path: outroPath || undefined, intro_path: introPath || undefined, clean_fillers: cleanFillers || undefined,})});setBatchJobId(data.job_id);@@ -1045,7 +1047,7 @@ const isHttpUrl = (value) => /^https?:\/\//i.test(value.trim());method: 'POST', body: JSON.stringify({video_path: vp, start_second: c.start_second, end_second: c.end_second,title: c.title.slice(0, 40), caption_style: captionStyle, crop_strategy: cropStrategy, format,- transcript_words: transcript?.words || [], logo_path: logoPath || undefined, outro_path: outroPath || undefined, clean_fillers: cleanFillers || undefined,+ transcript_words: transcript?.words || [], logo_path: logoPath || undefined, outro_path: outroPath || undefined, intro_path: introPath || undefined, clean_fillers: cleanFillers || undefined,})});setRetryJobId(data.job_id);@@ -1060,18 +1062,6 @@ const isHttpUrl = (value) => /^https?:\/\//i.test(value.trim());const toggleClip = (i) => setDeselected(prev => { const n = new Set(prev); n.has(i) ? n.delete(i) : n.add(i); return n; });const selectedCount = suggestions.length - deselected.size;- const handleLogoUpload = async (f) => {- setLogoUploading(true);- try { const d = await uploadFile(f, () => { }); if (d.file_path) setLogoPath(d.file_path); }- catch (e) { setError('Logo upload failed'); }- finally { setLogoUploading(false); }- };- const handleOutroUpload = async (f) => {- setOutroUploading(true);- try { const d = await uploadFile(f, () => { }); if (d.file_path) setOutroPath(d.file_path); }- catch (e) { setError('Outro upload failed'); }- finally { setOutroUploading(false); }- };const buildLocalPrompt = () => {const parts = [];const hasTranscriptReady = transcript || transcriptText.trim();@@ -1139,7 +1129,7 @@ const isHttpUrl = (value) => /^https?:\/\//i.test(value.trim());_source: 'ui',videoPath: videoPath.trim(),rawTranscriptText: transcriptText.trim() || undefined,- settings: { captionStyle, cropStrategy, format, logoPath, outroPath },+ settings: { captionStyle, cropStrategy, format, logoPath, outroPath, introPath },}),}).catch(() => { });}@@ -1225,35 +1215,33 @@ const isHttpUrl = (value) => /^https?:\/\//i.test(value.trim());return (<div className="app">- <div className="header">- <div style={{ display: 'flex', justifyContent: 'flex-end', alignItems: 'center' }}>- <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>- {mcpConnected && (- <span className="pill" style={{ fontSize: 10, letterSpacing: '0.5px', background: 'var(--green-subtle)', color: 'var(--green)', border: '1px solid var(--green-border)' }}>- MCP linked- </span>- )}- {encoderInfo && (- <span className="pill pill-blue" style={{ fontSize: 10, letterSpacing: '0.5px' }}>- {encoderInfo.best === 'libx264' ? 'CPU' : encoderInfo.best.replace('h264_', '').toUpperCase()}- </span>- )}- {speakerStatus && !speakerStatus.configured && (- <span className="pill" style={{ fontSize: 10, letterSpacing: '0.5px', background: 'rgba(250,204,21,0.08)', color: '#facc15', border: '1px solid rgba(250,204,21,0.2)', cursor: 'pointer' }}- title="Speaker detection not configured. Click to learn more"- onClick={() => window.open('https://huggingface.co/pyannote/speaker-diarization-3.1', '_blank')}>- <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4 }}>Speakers <X size={11} /></span>- </span>- )}- {speakerStatus && speakerStatus.configured && (- <span className="pill" style={{ fontSize: 10, letterSpacing: '0.5px', background: 'var(--green-subtle)', color: 'var(--green)', border: '1px solid var(--green-border)' }}>- <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4 }}>Speakers <Check size={11} /></span>- </span>- )}- </div>- </div>- <h1>Podcast content studio</h1>- </div>+ <PageHeader+ title="Podcast content studio"+ actions={<>+ {mcpConnected && (+ <span className="pill" style={{ fontSize: 10, letterSpacing: '0.5px', background: 'var(--green-subtle)', color: 'var(--green)', border: '1px solid var(--green-border)' }}>+ MCP linked+ </span>+ )}+ {encoderInfo && (+ <span className="pill pill-blue" style={{ fontSize: 10, letterSpacing: '0.5px' }}>+ {encoderInfo.best === 'libx264' ? 'CPU' : encoderInfo.best.replace('h264_', '').toUpperCase()}+ </span>+ )}+ {speakerStatus && !speakerStatus.configured && (+ <span className="pill" style={{ fontSize: 10, letterSpacing: '0.5px', background: 'rgba(250,204,21,0.08)', color: '#facc15', border: '1px solid rgba(250,204,21,0.2)', cursor: 'pointer' }}+ title="Speaker detection not configured. Click to learn more"+ onClick={() => window.open('https://huggingface.co/pyannote/speaker-diarization-3.1', '_blank')}>+ <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4 }}>Speakers <X size={11} /></span>+ </span>+ )}+ {speakerStatus && speakerStatus.configured && (+ <span className="pill" style={{ fontSize: 10, letterSpacing: '0.5px', background: 'var(--green-subtle)', color: 'var(--green)', border: '1px solid var(--green-border)' }}>+ <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4 }}>Speakers <Check size={11} /></span>+ </span>+ )}+ </>}+ />{speakerStatus && !speakerStatus.configured && !sessionStorage.getItem('dismiss-speaker') && (<div className="fade-in" style={{ margin: '0 0 16px', padding: '14px 16px', background: 'rgba(250,204,21,0.06)', border: '1px solid rgba(250,204,21,0.15)', borderRadius: 'var(--radius)', display: 'flex', alignItems: 'flex-start', gap: 12 }}>@@ -1269,8 +1257,7 @@ const isHttpUrl = (value) => /^https?:\/\//i.test(value.trim());<span style={{ color: 'var(--text3)' }}>3.</span> Add <code style={{ fontFamily: 'var(--font-mono)', fontSize: 11, padding: '1px 5px', background: 'rgba(250,204,21,0.1)', borderRadius: 4, color: '#facc15' }}>HF_TOKEN=hf_...</code> to your <code style={{ fontFamily: 'var(--font-mono)', fontSize: 11 }}>.env</code></div></div>- <button onClick={() => { sessionStorage.setItem('dismiss-speaker', '1'); setSpeakerStatus({...speakerStatus, _dismissed: true}); }}- style={{ background: 'none', border: 'none', color: 'var(--text3)', cursor: 'pointer', fontSize: 16, padding: 4, lineHeight: 1 }}+ <button className="icon-btn" onClick={() => { sessionStorage.setItem('dismiss-speaker', '1'); setSpeakerStatus({...speakerStatus, _dismissed: true}); }}title="Dismiss"><X size={12} /></button></div>)}@@ -1311,6 +1298,7 @@ const isHttpUrl = (value) => /^https?:\/\//i.test(value.trim());disabled={isProcessing || browsing}onKeyDown={e => { if (e.key === 'Enter' && sourceIsUrl) downloadVideo(); }}style={{ flex: 1, fontSize: 12, padding: '9px 13px', background: 'var(--bg)', borderColor: videoPath ? 'var(--green-border)' : 'var(--border)' }} />+ <RecentSources onPick={setVideoPath} exclude={videoPath ? [videoPath] : []} /><button className="btn btn-ghost btn-sm" onClick={downloadVideo} disabled={!sourceIsUrl || isProcessing || browsing}>{downloadingVideo ? <div className="spinner sm" /> : <><DownloadGlyph size={14} /> Download</>}</button>@@ -1491,38 +1479,12 @@ const isHttpUrl = (value) => /^https?:\/\//i.test(value.trim());</select></div></div>- <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>+ <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap' }}>{captionStyle === 'branded' && (- logoPath ? (- <div className="asset-pill fade-in">- <span className="asset-pill-icon">- <img src={`/api/stream-source?path=${encodeURIComponent(logoPath)}`}- style={{ width: 16, height: 16, objectFit: 'contain', borderRadius: 3 }} onError={e => { e.target.style.display = 'none' }} />- </span>- <span className="asset-pill-name">{logoPath.split('/').pop()}</span>- <button className="asset-pill-x" onClick={() => setLogoPath('')} disabled={isProcessing}><X size={12} /></button>- </div>- ) : (- <button className="asset-add fade-in" onClick={() => logoRef.current?.click()} disabled={isProcessing || logoUploading}>- {logoUploading ? <div className="spinner sm" /> : <Plus size={12} />} Logo- </button>- )+ <AssetPicker type="logo" label="Logo" value={logoPath} onChange={setLogoPath} disabled={isProcessing} />)}- {outroPath ? (- <div className="asset-pill">- <span className="asset-pill-icon" style={{ display: 'inline-flex' }}><Play size={11} /></span>- <span className="asset-pill-name">{outroPath.split('/').pop()}</span>- <button className="asset-pill-x" onClick={() => setOutroPath('')} disabled={isProcessing}><X size={12} /></button>- </div>- ) : (- <button className="asset-add" onClick={() => outroRef.current?.click()} disabled={isProcessing || outroUploading}>- {outroUploading ? <div className="spinner sm" /> : <Plus size={12} />} Outro- </button>- )}- <input ref={logoRef} type="file" accept=".png,.jpg,.jpeg,.svg" style={{ display: 'none' }}- onChange={e => e.target.files[0] && handleLogoUpload(e.target.files[0])} />- <input ref={outroRef} type="file" accept=".mp4,.mov,.mkv,.webm" style={{ display: 'none' }}- onChange={e => e.target.files[0] && handleOutroUpload(e.target.files[0])} />+ <AssetPicker type="intro" label="Intro" value={introPath} onChange={setIntroPath} disabled={isProcessing} />+ <AssetPicker type="outro" label="Outro" value={outroPath} onChange={setOutroPath} disabled={isProcessing} /></div>{/* Advanced Settings */}@@ -1781,7 +1743,7 @@ const isHttpUrl = (value) => /^https?:\/\//i.test(value.trim());<div className="clip-actions" onClick={e => e.stopPropagation()}><button className="btn btn-ghost btn-sm" onClick={() => onPlayRendered(outputFile)} title="Preview"><Play size={13} /></button><a href={`/api/download/${outputFile}`} className="btn btn-primary btn-sm" download title="Download"><Download size={14} /></a>- <button className="btn btn-ghost btn-sm" disabled={isRetryingThis} onClick={() => retryClip(resultIdx)} title="Retry">{'\u21BB'}</button>+ <button className="btn btn-ghost btn-sm" disabled={isRetryingThis} onClick={() => retryClip(resultIdx)} title="Retry"><RotateCcw size={13} /></button></div>)}{phase === 'done' && !off && r && failed && (@@ -1934,39 +1896,6 @@ const isHttpUrl = (value) => /^https?:\/\//i.test(value.trim());onToggleFrame={() => setShowTikTokFrame(v => !v)}/>)}- {/* Settings tags */}- <div className="preview-settings">- <div className={`preview-tag ${settingsFlash === 'caption' ? 'changed' : ''}`}- style={settingsFlash === 'caption' ? { animation: 'tagFlash 0.6s var(--ease)' } : {}}>- Caption {'\u00B7'} <strong>{captionStyle}</strong>- </div>- <div className={`preview-tag ${settingsFlash === 'crop' ? 'changed' : ''}`}- style={settingsFlash === 'crop' ? { animation: 'tagFlash 0.6s var(--ease)' } : {}}>- Crop {'\u00B7'} <strong>{cropStrategy}</strong>- </div>- {logoPath && (- <div className="preview-tag">- Logo {'\u00B7'} <strong>{logoPath.split('/').pop()}</strong>- </div>- )}- {outroPath && (- <div className="preview-tag">- Outro {'\u00B7'} <strong>{outroPath.split('/').pop()}</strong>- </div>- )}- {activePreset && (- <div className="preview-tag" style={{ background: 'var(--accent-subtle)', borderColor: 'rgba(219,139,72,0.2)' }}>- Preset {'\u00B7'} <strong>{activePreset}</strong>- </div>- )}- {cleanFillers && (- <div className="preview-tag">- Clean fillers {'\u00B7'} <strong>on</strong>- </div>- )}- </div>-- {/* Spec recap \u2014 form state as a reviewable summary card */}<SpecRecapcaptionStyle={captionStyle}cropStrategy={cropStrategy}diff --git a/src/ui/client/HighlightsPage.tsx b/src/ui/client/HighlightsPage.tsxindex 554cebd..a19142c 100644--- a/src/ui/client/HighlightsPage.tsx+++ b/src/ui/client/HighlightsPage.tsx@@ -1,5 +1,9 @@import React, { useEffect, useRef, useState } from "react";+import { PageHeader } from "./Page";import { api, basename } from "./lib";+import { useJob } from "./useJob";+import AssetPicker from "./AssetPicker";+import RecentSources from "./RecentSources";import { BackIcon, TrashIcon, PlayIcon, PauseIcon, DownloadIcon } from "./icons";interface Moment {@@ -183,7 +187,7 @@ function MomentTrim({/></div><span className="clip-player-time" style={{ minWidth: 118, textAlign: "right", fontVariantNumeric: "tabular-nums" }}>- {saving ? "saving…" : `${mmss(start)}–${mmss(end)} · ${Math.round(end - start)}s`}+ {saving ? "saving…" : `${mmss(start)}-${mmss(end)} · ${Math.round(end - start)}s`}</span></div></div>@@ -192,33 +196,6 @@ function MomentTrim({const round1 = (n: number) => Math.round(n * 10) / 10;-interface JobState {- status?: string;- progress?: number;- message?: string;- error?: string;- result?: { file_path?: string };-}--function useJob(jobId: string | null): JobState | null {- const [state, setState] = useState<JobState | null>(null);- useEffect(() => {- if (!jobId) {- setState(null);- return;- }- const es = new EventSource(`/api/job/${jobId}/stream`);- es.onmessage = (e) => {- const d = JSON.parse(e.data) as JobState;- setState(d);- if (d.status === "done" || d.status === "error") es.close();- };- es.onerror = () => es.close();- return () => es.close();- }, [jobId]);- return state;-}-function DownloadRow({jobId,url,@@ -266,9 +243,6 @@ export default function HighlightsPage() {const [minDur, setMinDur] = useState(15);const [maxDur, setMaxDur] = useState(60);const [logoPath, setLogoPath] = useState("");- const [logoUploading, setLogoUploading] = useState(false);- const createLogoRef = useRef<HTMLInputElement>(null);- const sessionLogoRef = useRef<HTMLInputElement>(null);const [session, setSession] = useState<HighlightsResp | null>(null);const [selected, setSelected] = useState(0);const [busy, setBusy] = useState(false);@@ -386,37 +360,19 @@ export default function HighlightsPage() {setPathDraft("");}- async function uploadImage(f: File): Promise<string | null> {- setLogoUploading(true);- try {- const fd = new FormData();- fd.append("file", f);- const res = await fetch("/api/upload", { method: "POST", body: fd });- const d = (await res.json()) as { file_path?: string; error?: string };- if (d.file_path) {- api("/ui-state", {- method: "POST",- body: JSON.stringify({ _source: "ui", settings: { logoPath: d.file_path } }),- }).catch(() => {});- return d.file_path;- }- setMsg(d.error || "Logo upload failed");- return null;- } catch {- setMsg("Logo upload failed");- return null;- } finally {- setLogoUploading(false);- }+ function chooseLogo(path: string) {+ setLogoPath(path);+ api("/ui-state", {+ method: "POST",+ body: JSON.stringify({ _source: "ui", settings: { logoPath: path } }),+ }).catch(() => {});}- async function applySessionLogo(f: File | null) {+ function applySessionLogoPath(path: string) {if (!session) return;- const logo = f ? await uploadImage(f) : "";- if (f && !logo) return;call(- { action: "build", session_id: session.session_id, logo },- f ? "Adding logo and rebuilding…" : "Removing logo…",+ { action: "build", session_id: session.session_id, logo: path },+ path ? "Applying logo and rebuilding…" : "Removing logo…",);}@@ -473,9 +429,7 @@ export default function HighlightsPage() {return (<div className="app">- <div className="header">- <h1 style={{ margin: 0 }}>Highlights</h1>- </div>+ <PageHeader title="Highlights" /><div className="section card"><div className="card-title" style={{ marginBottom: 14 }}>Find highlights</div>@@ -513,21 +467,24 @@ export default function HighlightsPage() {))}</div>)}- <input- type="text"- placeholder="…or paste a local path or YouTube/video URL, press Enter to add"- value={pathDraft}- onChange={(e) => setPathDraft(e.target.value)}- onKeyDown={(e) => { if (e.key === "Enter") { e.preventDefault(); commitDraft(); } }}- onBlur={commitDraft}- style={{ width: "100%", marginTop: 8, fontFamily: "var(--font-mono)", fontSize: 12 }}- />+ <div style={{ display: "flex", gap: 8, marginTop: 8, alignItems: "center" }}>+ <input+ type="text"+ placeholder="Or paste a local path or YouTube/video URL, press Enter to add"+ value={pathDraft}+ onChange={(e) => setPathDraft(e.target.value)}+ onKeyDown={(e) => { if (e.key === "Enter") { e.preventDefault(); commitDraft(); } }}+ onBlur={commitDraft}+ style={{ flex: 1, fontFamily: "var(--font-mono)", fontSize: 12 }}+ />+ <RecentSources onPick={addPath} exclude={videoPaths} />+ </div><div style={{ display: "flex", alignItems: "center", gap: 10, marginTop: 16 }}><span className="field-label" style={{ margin: 0 }}>Moments</span><div style={{ display: "inline-flex", gap: 4 }}>- <button className={`btn btn-sm ${auto ? "btn-primary" : "btn-ghost"}`} onClick={() => setAuto(true)}>Auto</button>- <button className={`btn btn-sm ${!auto ? "btn-primary" : "btn-ghost"}`} onClick={() => setAuto(false)}>Custom</button>+ <button className={`btn ${auto ? "btn-primary" : "btn-ghost"} btn-sm`} onClick={() => setAuto(true)}>Auto</button>+ <button className={`btn ${!auto ? "btn-primary" : "btn-ghost"} btn-sm`} onClick={() => setAuto(false)}>Custom</button></div>{auto && <span className="hint">Best moments and how many, picked for you</span>}</div>@@ -555,22 +512,9 @@ export default function HighlightsPage() {)}</div>- <div style={{ display: "flex", alignItems: "center", gap: 10, marginTop: 14 }}>- <span className="field-label" style={{ margin: 0 }}>Logo</span>- {logoPath ? (- <div className="file-badge">- <div className="dot" />- <div className="name">{basename(logoPath)}</div>- <button className="btn btn-ghost btn-sm" onClick={() => setLogoPath("")} style={{ padding: "4px 10px", fontSize: 11 }}>Remove</button>- </div>- ) : (- <button className="btn btn-ghost btn-sm" disabled={logoUploading} onClick={() => createLogoRef.current?.click()}>- {logoUploading ? "Uploading…" : "Add logo"}- </button>- )}- <span className="hint">Overlaid top-right on every clip</span>- <input ref={createLogoRef} type="file" accept=".png,.jpg,.jpeg,.svg,.webp" style={{ display: "none" }}- onChange={(e) => { const f = e.target.files?.[0]; e.target.value = ""; if (f) uploadImage(f).then((p) => p && setLogoPath(p)); }} />+ <div style={{ display: "flex", alignItems: "flex-end", gap: 12, marginTop: 14 }}>+ <AssetPicker type="logo" label="Logo" value={logoPath} onChange={chooseLogo} />+ <span className="hint" style={{ paddingBottom: 8 }}>Overlaid top-right on every clip</span></div><div style={{ display: "flex", justifyContent: "flex-end", marginTop: 16 }}>@@ -598,19 +542,12 @@ export default function HighlightsPage() {</button><div style={{ display: "flex", alignItems: "center", gap: 10 }}><span className="hint">{enabled}/{session.moments.length} in the cut</span>- <button className="btn btn-ghost btn-sm" disabled={busy || logoUploading} onClick={() => sessionLogoRef.current?.click()}>- {logoUploading ? "Uploading…" : session.logo ? "Change logo" : "Add logo"}- </button>- {session.logo && (- <button className="btn btn-ghost btn-sm" disabled={busy} onClick={() => applySessionLogo(null)}>Remove logo</button>- )}+ <AssetPicker type="logo" value={session.logo || ""} disabled={busy} onChange={applySessionLogoPath} />{session.reel_path && (<a className="btn btn-primary btn-sm" href={download(session.reel_path)} style={{ textDecoration: "none", display: "inline-flex", alignItems: "center", gap: 6 }}><DownloadIcon /> Download reel</a>)}- <input ref={sessionLogoRef} type="file" accept=".png,.jpg,.jpeg,.svg,.webp" style={{ display: "none" }}- onChange={(e) => { const f = e.target.files?.[0]; e.target.value = ""; if (f) applySessionLogo(f); }} /></div></div>@@ -660,7 +597,7 @@ export default function HighlightsPage() {}}><span className="hint" style={{ width: 20, textAlign: "right" }}>{idx + 1}</span>- <strong style={{ fontVariantNumeric: "tabular-nums", minWidth: 96 }}>{mmss(m.start)}–{mmss(m.end)}</strong>+ <strong style={{ fontVariantNumeric: "tabular-nums", minWidth: 96 }}>{mmss(m.start)}-{mmss(m.end)}</strong><span className="pill pill-blue">{m.why}</span>{(session.sources?.length ?? 1) > 1 && m.source && (<span className="hint" title={m.source} style={{ minWidth: 0, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>diff --git a/src/ui/client/IntegrationsPage.tsx b/src/ui/client/IntegrationsPage.tsxindex de2635d..e2ae281 100644--- a/src/ui/client/IntegrationsPage.tsx+++ b/src/ui/client/IntegrationsPage.tsx@@ -1,4 +1,5 @@import React, { useEffect, useState } from "react";+import { PageHeader } from "./Page";import { api } from "./lib";const CATEGORY: Record<string, string> = {@@ -46,7 +47,7 @@ export default function IntegrationsPage() {return (<div className="app" style={{ maxWidth: 820 }}>- <div className="header"><h1>Integrations</h1></div>+ <PageHeader title="Integrations" />{error ? (<div className="set-note err">{error}</div>diff --git a/src/ui/client/KnowledgePage.jsx b/src/ui/client/KnowledgePage.jsxindex bd091d0..f0b1f33 100644--- a/src/ui/client/KnowledgePage.jsx+++ b/src/ui/client/KnowledgePage.jsx@@ -1,4 +1,6 @@import React, { useState, useEffect, useCallback } from 'react';+import { PageHeader } from "./Page";+import { Trash2 } from 'lucide-react';import { api, upload } from './lib';export default function KnowledgePage() {@@ -95,10 +97,10 @@ export default function KnowledgePage() {return (<div className="app">- <div className="header">- <h1>Knowledge base</h1>- {kbDir && <div className="dir-path">{kbDir}</div>}- </div>+ <PageHeader+ title="Knowledge base"+ actions={kbDir ? <div className="dir-path">{kbDir}</div> : null}+ /><divclassName={`drop-zone knowledge-drop-zone ${dragOver ? 'drag-over' : ''}`}@@ -120,7 +122,7 @@ export default function KnowledgePage() {className={`file-card ${activeFile === f.filename ? 'active' : ''}`}onClick={() => openFile(f)}>- <button className="file-delete" onClick={(e) => deleteFile(f.filename, e)}>{'\u00D7'}</button>+ <button className="file-delete" onClick={(e) => deleteFile(f.filename, e)} title="Delete"><Trash2 size={13} /></button><div className="file-name">{f.filename}</div><div className="file-meta">{new Date(f.updatedAt).toLocaleDateString()}</div><div className="file-preview">{f.content.split('\n').filter(l => l.trim() && !l.startsWith('#')).slice(0, 2).join(' ')}</div>@@ -141,7 +143,7 @@ export default function KnowledgePage() {onChange={e => setNewName(e.target.value)}onKeyDown={e => e.key === 'Enter' && createFile()}/>- <button className="btn btn-primary" onClick={createFile}>Create</button>+ <button className="btn btn-primary btn-sm" onClick={createFile}>Create</button></div>{activeFile && (@@ -150,8 +152,8 @@ export default function KnowledgePage() {<span className="editor-filename">{activeFile}</span><div className="editor-actions">{dirty && <span style={{ fontSize: 11, color: 'var(--accent)', fontWeight: 600, padding: '4px 8px' }}>unsaved</span>}- <button className="btn btn-ghost" onClick={() => { setActiveFile(null); setEditorContent(''); setDirty(false); }}>Close</button>- <button className="btn btn-primary" onClick={saveFile}>Save</button>+ <button className="btn btn-ghost btn-sm" onClick={() => { setActiveFile(null); setEditorContent(''); setDirty(false); }}>Close</button>+ <button className="btn btn-primary btn-sm" onClick={saveFile}>Save</button></div></div><textareadiff --git a/src/ui/client/Layout.tsx b/src/ui/client/Layout.tsxindex afa5df9..82e5580 100644--- a/src/ui/client/Layout.tsx+++ b/src/ui/client/Layout.tsx@@ -11,6 +11,7 @@ import {Terminal,BarChart3,Scissors,+ Package,} from "lucide-react";const icons: Record<string, typeof LayoutGrid> = {@@ -24,6 +25,7 @@ const icons: Record<string, typeof LayoutGrid> = {mcp: Terminal,analytics: BarChart3,highlights: Scissors,+ assets: Package,};function Icon({ name }: { name: string }) {@@ -55,6 +57,7 @@ export default function Layout() {<NavLink to="/thumbnails" className="sidebar-link"><Icon name="thumbnail" /> Thumbnails</NavLink><div className="sidebar-section">Workspace</div>+ <NavLink to="/assets" className="sidebar-link"><Icon name="assets" /> Assets</NavLink><NavLink to="/knowledge" className="sidebar-link"><Icon name="knowledge" /> Knowledge</NavLink><NavLink to="/config" className="sidebar-link"><Icon name="config" /> Config</NavLink><NavLink to="/integrations" className="sidebar-link"><Icon name="integrations" /> Integrations</NavLink>diff --git a/src/ui/client/McpSetupPage.tsx b/src/ui/client/McpSetupPage.tsxindex 56c11f8..b96999e 100644--- a/src/ui/client/McpSetupPage.tsx+++ b/src/ui/client/McpSetupPage.tsx@@ -1,4 +1,5 @@import React, { useEffect, useRef, useState } from "react";+import { PageHeader } from "./Page";import { api } from "./lib";import CopyButton from "./CopyButton";@@ -51,9 +52,10 @@ export default function McpSetupPage() {return (<div className="app" style={{ maxWidth: 780 }}>- <div className="header"><h1>MCP setup</h1></div>-- <span className="pill" style={{ ...STATUS_STYLE[statusKind], fontSize: 11 }}>{statusText}</span>+ <PageHeader+ title="MCP setup"+ actions={<span className="pill" style={{ ...STATUS_STYLE[statusKind], fontSize: 11 }}>{statusText}</span>}+ /><div className="section" style={{ marginTop: 18 }}><div className="section-label">Claude Desktop</div>diff --git a/src/ui/client/Page.tsx b/src/ui/client/Page.tsxnew file mode 100644index 0000000..d2e1b1d--- /dev/null+++ b/src/ui/client/Page.tsx@@ -0,0 +1,21 @@+import React from "react";++export function PageHeader({+ title,+ actions,+ back,+}: {+ title: React.ReactNode;+ actions?: React.ReactNode;+ back?: React.ReactNode;+}) {+ return (+ <div className="header">+ {back && <div className="page-back">{back}</div>}+ <div className="page-head">+ <h1>{title}</h1>+ {actions && <div className="page-head-actions">{actions}</div>}+ </div>+ </div>+ );+}diff --git a/src/ui/client/RecentSources.tsx b/src/ui/client/RecentSources.tsxnew file mode 100644index 0000000..9c3c717--- /dev/null+++ b/src/ui/client/RecentSources.tsx@@ -0,0 +1,41 @@+import React, { useEffect, useState } from "react";+import { api } from "./lib";++interface Source {+ path: string;+ name: string;+ exists: boolean;+}++export default function RecentSources({+ onPick,+ exclude = [],+}: {+ onPick: (path: string) => void;+ exclude?: string[];+}) {+ const [items, setItems] = useState<Source[]>([]);++ useEffect(() => {+ api<Source[]>("/sources").then(setItems).catch(() => {});+ }, []);++ const options = items.filter((s) => !exclude.includes(s.path));+ if (options.length === 0) return null;++ return (+ <select+ className="recent-sources"+ value=""+ onChange={(e) => {+ if (e.target.value) onPick(e.target.value);+ e.target.value = "";+ }}+ >+ <option value="">Recent sources…</option>+ {options.map((s) => (+ <option key={s.path} value={s.path}>{s.name}</option>+ ))}+ </select>+ );+}diff --git a/src/ui/client/ReframeEditor.tsx b/src/ui/client/ReframeEditor.tsxindex f86e2ab..41bfa49 100644--- a/src/ui/client/ReframeEditor.tsx+++ b/src/ui/client/ReframeEditor.tsx@@ -176,7 +176,7 @@ export default function ReframeEditor({{keyframes.map((k) => (<span key={k.tAbs} className="pill" style={{ fontSize: 11, display: "inline-flex", gap: 6, alignItems: "center", cursor: "pointer" }} onClick={() => seek(k.tAbs)}>{fmtMs(k.tAbs)} · {Math.round(k.x_pct)}%- <button onClick={(e) => { e.stopPropagation(); setKeyframes((kf) => kf.filter((x) => x.tAbs !== k.tAbs)); }} style={{ background: "none", border: "none", color: "var(--text3)", cursor: "pointer", padding: 0 }}>×</button>+ <button className="asset-pill-x" onClick={(e) => { e.stopPropagation(); setKeyframes((kf) => kf.filter((x) => x.tAbs !== k.tAbs)); }}><CloseIcon /></button></span>))}</div>diff --git a/src/ui/client/StudioHome.tsx b/src/ui/client/StudioHome.tsxindex 27fb91e..526f0eb 100644--- a/src/ui/client/StudioHome.tsx+++ b/src/ui/client/StudioHome.tsx@@ -1,4 +1,5 @@import React, { useEffect, useState } from "react";+import { PageHeader } from "./Page";import { Link } from "react-router-dom";import { api, fmt, timeAgo, basename } from "./lib";import { TrashIcon, PlayIcon } from "./icons";@@ -81,12 +82,10 @@ export default function StudioHome() {return (<div className="app">- <div className="header">- <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>- <h1 style={{ margin: 0 }}>Library</h1>- <Link to="/episode" className="btn btn-primary btn-sm" style={{ textDecoration: "none" }}>+ New episode</Link>- </div>- </div>+ <PageHeader+ title="Library"+ actions={<Link to="/episode" className="btn btn-primary btn-sm" style={{ textDecoration: "none" }}>+ New episode</Link>}+ />{exporting > 0 && (<div className="set-note ok" style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 16 }}>diff --git a/src/ui/client/ThumbnailStudio.tsx b/src/ui/client/ThumbnailStudio.tsxindex 561058a..a4874c9 100644--- a/src/ui/client/ThumbnailStudio.tsx+++ b/src/ui/client/ThumbnailStudio.tsx@@ -1,4 +1,5 @@import React, { useRef, useState } from "react";+import { PageHeader } from "./Page";import { api, upload, basename, labelStyle } from "./lib";import ThumbnailTemplate from "./ThumbnailTemplate";@@ -136,12 +137,10 @@ export default function ThumbnailStudio() {return (<div className="app">- <div className="header">- <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-end", gap: 16, flexWrap: "wrap" }}>- <h1 style={{ margin: 0 }}>Thumbnail studio</h1>- <button className="btn btn-ghost btn-sm" onClick={() => setEditingTemplate(true)}>Edit template</button>- </div>- </div>+ <PageHeader+ title="Thumbnail studio"+ actions={<button className="btn btn-ghost btn-sm" onClick={() => setEditingTemplate(true)}>Edit template</button>}+ /><div className="section"><label style={labelStyle}>Source</label>diff --git a/src/ui/client/ThumbnailTemplate.tsx b/src/ui/client/ThumbnailTemplate.tsxindex 9fc8f43..e7266e5 100644--- a/src/ui/client/ThumbnailTemplate.tsx+++ b/src/ui/client/ThumbnailTemplate.tsx@@ -1,4 +1,5 @@import React, { useEffect, useRef, useState } from "react";+import { PageHeader } from "./Page";import { api, labelStyle } from "./lib";import { BackIcon } from "./icons";@@ -146,12 +147,10 @@ export default function ThumbnailTemplate({ onBack }: { onBack?: () => void }) {return (<div className="app">- <div className="header">- <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-end", gap: 16, flexWrap: "wrap" }}>- <h1 style={{ margin: 0 }}>Edit template</h1>- {onBack && <button className="btn btn-ghost btn-sm" onClick={onBack}><BackIcon /> Back to generator</button>}- </div>- </div>+ <PageHeader+ title="Edit template"+ actions={onBack && <button className="btn btn-ghost btn-sm" onClick={onBack}><BackIcon /> Back to generator</button>}+ /><div className="tmpl-layout"><div className="tmpl-preview">diff --git a/src/ui/client/Tooltip.tsx b/src/ui/client/Tooltip.tsxnew file mode 100644index 0000000..1cd3b77--- /dev/null+++ b/src/ui/client/Tooltip.tsx@@ -0,0 +1,47 @@+import React, { useRef, useState } from "react";+import { createPortal } from "react-dom";++export default function Tooltip({+ label,+ children,+ placement = "top",+}: {+ label: string;+ children: React.ReactNode;+ placement?: "top" | "bottom";+}) {+ const ref = useRef<HTMLSpanElement>(null);+ const [rect, setRect] = useState<DOMRect | null>(null);++ const show = () => setRect(ref.current?.getBoundingClientRect() ?? null);+ const hide = () => setRect(null);++ const style: React.CSSProperties = rect+ ? {+ position: "fixed",+ left: rect.left + rect.width / 2,+ top: placement === "top" ? rect.top - 8 : rect.bottom + 8,+ transform: placement === "top" ? "translate(-50%, -100%)" : "translate(-50%, 0)",+ }+ : {};++ return (+ <span+ ref={ref}+ className="tt-wrap"+ onMouseEnter={show}+ onMouseLeave={hide}+ onFocus={show}+ onBlur={hide}+ >+ {children}+ {rect && label &&+ createPortal(+ <span className={`tooltip tooltip-${placement}`} style={style} role="tooltip">+ {label}+ </span>,+ document.body,+ )}+ </span>+ );+}diff --git a/src/ui/client/main.tsx b/src/ui/client/main.tsxindex 95a451d..1e47a74 100644--- a/src/ui/client/main.tsx+++ b/src/ui/client/main.tsx@@ -8,6 +8,7 @@ import EpisodeWorkspace from "./EpisodeWorkspace";import ThumbnailStudio from "./ThumbnailStudio";import ContentStudio from "./ContentStudio";import HighlightsPage from "./HighlightsPage";+import AssetsPage from "./AssetsPage";import AnalyticsPage from "./AnalyticsPage";import KnowledgePage from "./KnowledgePage";import ConfigPage from "./ConfigPage";@@ -27,6 +28,7 @@ createRoot(document.getElementById("root")!).render(<Route path="/thumbnails" element={<ThumbnailStudio />} /><Route path="/thumbnail" element={<Navigate to="/thumbnails" replace />} /><Route path="/clip/:id" element={<ClipDetail />} />+ <Route path="/assets" element={<AssetsPage />} /><Route path="/knowledge" element={<KnowledgePage />} /><Route path="/config" element={<ConfigPage />} /><Route path="/integrations" element={<IntegrationsPage />} />diff --git a/src/ui/client/useAssets.ts b/src/ui/client/useAssets.tsnew file mode 100644index 0000000..da8226e--- /dev/null+++ b/src/ui/client/useAssets.ts@@ -0,0 +1,121 @@+import { useCallback, useEffect, useState } from "react";+import { api, upload } from "./lib";++export type AssetType =+ | "logo"+ | "outro"+ | "intro"+ | "music"+ | "video"+ | "image"+ | "audio"+ | "other";++export interface Asset {+ name: string;+ type: AssetType;+ path: string;+ addedAt: string;+ default?: boolean;+}++export const ASSET_GROUPS: { type: AssetType; label: string; accept: string }[] = [+ { type: "logo", label: "Logos", accept: "image/*" },+ { type: "outro", label: "Outros", accept: "video/*" },+ { type: "intro", label: "Intros", accept: "video/*" },+ { type: "music", label: "Music", accept: "audio/*" },+ { type: "image", label: "Images", accept: "image/*" },+ { type: "other", label: "Other", accept: "*/*" },+];++export function assetSrc(name: string): string {+ return `/api/assets/${encodeURIComponent(name)}/download`;+}++export function useAssets({ live = true }: { live?: boolean } = {}) {+ const [assets, setAssets] = useState<Asset[]>([]);+ const [loading, setLoading] = useState(true);+ const [error, setError] = useState<string | null>(null);++ const refresh = useCallback(async () => {+ try {+ const items = await api<Asset[]>("/assets");+ setAssets(items);+ setError(null);+ } catch (err) {+ setError(err instanceof Error ? err.message : "Failed to load assets");+ } finally {+ setLoading(false);+ }+ }, []);++ useEffect(() => {+ refresh();+ if (!live) return;+ const es = new EventSource("/api/events");+ const onChange = () => refresh();+ es.addEventListener("assets-updated", onChange);+ return () => es.close();+ }, [refresh, live]);++ const uploadFile = useCallback(+ async (file: File, type: AssetType, name?: string) => {+ const fd = new FormData();+ fd.append("file", file);+ fd.append("type", type);+ if (name) fd.append("name", name);+ const asset = await upload<Asset>("/assets/upload", fd);+ await refresh();+ return asset;+ },+ [refresh],+ );++ const importUrl = useCallback(+ async (url: string, type: AssetType, name?: string) => {+ const res = await api<{ job_id: string }>("/assets/url", {+ method: "POST",+ body: JSON.stringify({ url, type, name }),+ });+ return res.job_id;+ },+ [],+ );++ const setDefault = useCallback(+ async (name: string) => {+ await api(`/assets/${encodeURIComponent(name)}/default`, { method: "POST" });+ await refresh();+ },+ [refresh],+ );++ const clearDefault = useCallback(+ async (name: string) => {+ await api(`/assets/${encodeURIComponent(name)}/default`, { method: "DELETE" });+ await refresh();+ },+ [refresh],+ );++ const rename = useCallback(+ async (name: string, newName: string) => {+ await api(`/assets/${encodeURIComponent(name)}/rename`, {+ method: "POST",+ body: JSON.stringify({ new_name: newName }),+ });+ await refresh();+ },+ [refresh],+ );++ const remove = useCallback(+ async (name: string) => {+ await api(`/assets/${encodeURIComponent(name)}`, { method: "DELETE" });+ await refresh();+ },+ [refresh],+ );++ return { assets, loading, error, refresh, uploadFile, importUrl, setDefault, clearDefault, rename, remove };+}diff --git a/src/ui/client/useJob.ts b/src/ui/client/useJob.tsnew file mode 100644index 0000000..861b18c--- /dev/null+++ b/src/ui/client/useJob.ts@@ -0,0 +1,36 @@+import { useEffect, useState } from "react";++export interface JobState {+ status?: string;+ progress?: number;+ message?: string;+ error?: string;+ result?: { file_path?: string; [key: string]: unknown };+}++export function useJob(jobId: string | null): JobState | null {+ const [state, setState] = useState<JobState | null>(null);+ useEffect(() => {+ if (!jobId) {+ setState(null);+ return;+ }+ const es = new EventSource(`/api/job/${jobId}/stream`);+ es.onmessage = (e) => {+ const d = JSON.parse(e.data) as JobState;+ setState(d);+ if (d.status === "done" || d.status === "error") es.close();+ };+ es.onerror = () => {+ es.close();+ // Surface a dropped connection so consumers don't hang on the last status.+ setState((s) =>+ s && (s.status === "done" || s.status === "error")+ ? s+ : { ...s, status: "error", error: s?.error || "Lost connection to the job stream" },+ );+ };+ return () => es.close();+ }, [jobId]);+ return state;+}diff --git a/src/ui/public/css/styles.css b/src/ui/public/css/styles.cssindex cf62e7a..60a2bfc 100644--- a/src/ui/public/css/styles.css+++ b/src/ui/public/css/styles.css@@ -79,6 +79,10 @@ body {/* ─── Layout ─── */.app { max-width: 1080px; margin: 0 auto; padding: 48px 32px 96px; }.header { margin-bottom: 36px; }+.page-head { display: flex; justify-content: space-between; align-items: center; gap: 16px; flex-wrap: wrap; }+.page-head h1 { margin: 0; }+.page-head-actions { display: flex; align-items: center; gap: 8px; min-height: 24px; flex-wrap: wrap; }+.page-back { margin-bottom: 8px; }.logo { font-size: 13px; font-weight: 700; letter-spacing: 1.2px; color: var(--text3); margin-bottom: 10px; text-transform: uppercase; text-decoration: none; }.logo span { color: var(--accent); }h1 { font-size: 28px; font-weight: 700; letter-spacing: 0; line-height: 1.15; }@@ -1358,3 +1362,218 @@ p, li, figcaption, blockquote, .subtitle, .file-preview, .card-desc, .int-row .d@media (prefers-reduced-motion: reduce) {.stream-in { animation: none; }}++/* ── Assets page ── */+.asset-section-head { display: flex; align-items: center; justify-content: space-between; margin-bottom: 12px; }+.asset-count { color: var(--text3); font-weight: 500; margin-left: 4px; }+.asset-url-row { display: flex; gap: 8px; margin-bottom: 12px; }+.asset-url-row input { flex: 1; }+.asset-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); gap: 12px; }+.asset-card {+ position: relative; display: flex; flex-direction: column;+ background: var(--surface); border: 1px solid var(--border);+ border-radius: var(--radius); overflow: hidden;+ transition: border-color 0.15s var(--ease), box-shadow 0.15s var(--ease);+}+.asset-card:hover { border-color: var(--border-hover); }+.asset-card.selected { border-color: var(--accent); box-shadow: 0 0 0 1px var(--accent-edge); }+.asset-check {+ position: absolute; top: 8px; left: 8px; z-index: 2; display: flex;+ background: rgba(15, 14, 13, 0.6); border-radius: 5px; padding: 2px; backdrop-filter: blur(4px);+}+.asset-check input { width: 15px; height: 15px; cursor: pointer; accent-color: var(--accent); display: block; }+.asset-thumb { width: 100%; height: 120px; object-fit: contain; background: var(--bg2); display: block; }+.asset-thumb.clickable { cursor: zoom-in; transition: opacity 0.15s var(--ease); }+.asset-thumb.clickable:hover { opacity: 0.85; }+.asset-url-toggle { opacity: 0.55; transition: opacity 0.15s var(--ease); }+.asset-url-toggle:hover { opacity: 1; }+.asset-thumb-file { display: flex; align-items: center; justify-content: center; color: var(--text3); font-family: var(--font-mono); font-size: 15px; font-weight: 600; }+.asset-thumb-audio { display: flex; align-items: center; justify-content: center; height: 120px; }+.asset-row { display: flex; align-items: center; gap: 4px; padding: 8px 6px 8px 10px; }+.asset-meta { min-width: 0; flex: 1; }+.asset-name { display: flex; align-items: center; gap: 6px; font-size: 13px; font-weight: 600; color: var(--text); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }+.asset-rename { font-size: 13px; font-weight: 600; padding: 2px 6px !important; width: 100%; }+.asset-default-tag { font-size: 9px; font-weight: 700; letter-spacing: 0.5px; text-transform: uppercase; color: var(--accent); background: var(--accent-subtle); padding: 1px 5px; border-radius: 4px; flex-shrink: 0; }+.asset-sub { font-size: 11px; color: var(--text3); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; margin-top: 2px; }+.asset-actions { display: flex; gap: 2px; flex-shrink: 0; }+.asset-menu-wrap { position: relative; display: flex; }+.icon-btn {+ display: inline-flex; align-items: center; justify-content: center;+ width: 30px; height: 28px; border: none; background: transparent;+ color: var(--text3); cursor: pointer; border-radius: var(--radius-sm);+ transition: background 0.15s var(--ease), color 0.15s var(--ease);+}+.icon-btn:hover { background: var(--surface); color: var(--text); }+.icon-btn.active { color: var(--accent); }+.icon-btn.danger:hover { color: var(--red); }++.asset-add-tile {+ display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 8px;+ min-height: 168px; background: transparent; color: var(--text3);+ border: 1px dashed var(--border); border-radius: var(--radius);+ cursor: pointer; font-size: 12px; font-weight: 500; font-family: inherit;+ transition: border-color 0.15s var(--ease), color 0.15s var(--ease), background 0.15s var(--ease);+}+.asset-add-tile:hover:not(:disabled) { border-color: var(--accent); color: var(--accent); background: var(--accent-subtle); }+.asset-add-tile:disabled { cursor: default; opacity: 0.6; }++.asset-audio-player { display: flex; align-items: center; gap: 8px; width: 100%; padding: 0 12px; }+.asset-audio-btn {+ display: flex; align-items: center; justify-content: center; flex-shrink: 0;+ width: 34px; height: 34px; border-radius: 50%; border: none; cursor: pointer;+ background: var(--accent); color: #241803;+}+.asset-audio-track { flex: 1; height: 4px; border-radius: 2px; background: var(--surface); cursor: pointer; position: relative; }+.asset-audio-fill { position: absolute; left: 0; top: 0; bottom: 0; border-radius: 2px; background: var(--accent); }+.asset-audio-time { font-size: 11px; color: var(--text3); font-variant-numeric: tabular-nums; flex-shrink: 0; }+.asset-bulkbar {+ position: fixed; bottom: 24px; left: 50%; transform: translateX(-50%);+ display: flex; align-items: center; gap: 10px; z-index: 60;+ padding: 10px 12px 10px 18px; background: var(--surface3);+ border: 1px solid var(--border-hover); border-radius: 999px;+ font-size: 13px; color: var(--text2);+ box-shadow: 0 12px 32px rgba(0,0,0,0.5);+ animation: bulkbar-in 0.18s var(--ease-out) both;+}+.asset-bulkbar > span { font-weight: 600; color: var(--text); margin-right: 6px; }+@keyframes bulkbar-in { from { opacity: 0; transform: translate(-50%, 12px); } }+@media (prefers-reduced-motion: reduce) { .asset-bulkbar { animation: none; } }++.recent-sources { max-width: 190px; font-size: 12px; flex-shrink: 0; }++/* ── Analytics ── */+.analytics-status { display: flex; align-items: center; gap: 8px; margin-top: 10px; font-size: 13px; color: var(--text2); }+.analytics-status-sub { color: var(--text3); }+.status-dot { width: 8px; height: 8px; border-radius: 50%; background: var(--text3); flex-shrink: 0; }+.status-dot.on { background: var(--green); box-shadow: 0 0 0 3px var(--green-subtle); }+.analytics-steps { font-size: 12px; color: var(--text2); line-height: 1.7; margin: 8px 0 14px; padding-left: 18px; }+.analytics-empty { color: var(--text3); font-size: 13px; padding: 4px 0; }++.stat-row { display: grid; grid-template-columns: repeat(auto-fit, minmax(190px, 1fr)); gap: 12px; margin-bottom: 20px; }+.stat-tile { background: var(--surface); border: 1px solid var(--border); border-radius: var(--radius); padding: 16px 18px; }+.stat-icon { display: inline-flex; color: var(--accent); margin-bottom: 10px; }+.stat-label { font-size: 11px; font-weight: 600; letter-spacing: 0.4px; text-transform: uppercase; color: var(--text3); }+.stat-value { font-size: 26px; font-weight: 700; color: var(--text); font-variant-numeric: tabular-nums; margin-top: 4px; line-height: 1.1; }+.stat-sub { font-size: 12px; color: var(--text3); margin-top: 4px; }++.insights { background: var(--surface); border: 1px solid var(--border); border-radius: var(--radius); padding: 20px 22px; }+.insight-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 16px; margin-top: 4px; }+.insight { padding-left: 12px; border-left: 2px solid var(--accent); }+.insight-label { font-size: 11px; color: var(--text3); text-transform: uppercase; letter-spacing: 0.4px; font-weight: 600; }+.insight-value { font-size: 16px; font-weight: 700; color: var(--text); margin: 3px 0; text-transform: capitalize; }+.insight-metric { font-size: 12px; color: var(--accent); font-variant-numeric: tabular-nums; }++.analytics-charts { display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 16px; margin-bottom: 20px; }+.analytics-charts .section { margin-bottom: 0; }+.bar-row { margin-bottom: 12px; }+.bar-row:last-child { margin-bottom: 0; }+.bar-head { display: flex; justify-content: space-between; font-size: 12px; margin-bottom: 5px; }+.bar-key { color: var(--text); text-transform: capitalize; }+.bar-count { color: var(--text3); }+.bar-val { color: var(--text2); font-variant-numeric: tabular-nums; font-weight: 600; }+.bar-track { height: 7px; border-radius: 4px; background: var(--surface3); overflow: hidden; }+.bar-fill { height: 100%; border-radius: 4px; background: linear-gradient(90deg, var(--accent-edge), var(--accent)); transition: width 0.5s var(--ease-out); }++.analytics-row { display: flex; align-items: center; gap: 12px; padding: 10px 0; border-bottom: 1px solid var(--border); }+.analytics-row:last-child { border-bottom: 0; }+.analytics-row-title { font-size: 13px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }+.analytics-row-sub { font-size: 12px; color: var(--text3); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; margin-top: 2px; }++.top-clip { display: flex; align-items: center; gap: 12px; padding: 10px 0; border-bottom: 1px solid var(--border); text-decoration: none; color: inherit; }+.top-clip:last-child { border-bottom: 0; }+.top-clip:hover .top-clip-title { color: var(--accent); }+.rank-badge {+ flex-shrink: 0; width: 24px; height: 24px; border-radius: 6px;+ background: var(--surface3); color: var(--text2); font-size: 12px; font-weight: 700;+ display: flex; align-items: center; justify-content: center; font-variant-numeric: tabular-nums;+}+.top-clip:first-of-type .rank-badge { background: var(--accent-subtle); color: var(--accent); }+.top-clip-title { font-size: 13px; font-weight: 600; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; transition: color 0.15s var(--ease); }+.top-clip-metrics { display: flex; gap: 16px; font-size: 12px; color: var(--text3); font-variant-numeric: tabular-nums; flex-shrink: 0; }+.top-clip-metrics .metric-strong { color: var(--text); font-weight: 600; }++.analytics-hero {+ display: flex; flex-direction: column; align-items: center; text-align: center;+ padding: 56px 24px; margin-top: 8px; color: var(--text3);+ background: var(--surface); border: 1px solid var(--border); border-radius: var(--radius-lg);+}+.analytics-hero > svg { color: var(--accent); }+.analytics-hero-title { font-size: 17px; font-weight: 700; color: var(--text); margin-top: 14px; }+.analytics-hero-sub { font-size: 13px; color: var(--text2); line-height: 1.6; max-width: 440px; margin-top: 8px; }++/* ── Confirm dialog + lightbox ── */+.confirm-dialog {+ background: var(--surface); border: 1px solid var(--border-hover);+ border-radius: var(--radius); padding: 22px; box-shadow: 0 24px 64px rgba(0,0,0,0.5);+}+.confirm-dialog h3 { margin: 0 0 8px; font-size: 16px; color: var(--text); }+.confirm-dialog p { margin: 0 0 18px; font-size: 13px; color: var(--text2); line-height: 1.5; }+.confirm-actions { display: flex; justify-content: flex-end; gap: 8px; }+.lightbox-audio { background: var(--surface); border: 1px solid var(--border); border-radius: 16px; padding: 24px 16px; }+.lightbox-file { background: var(--surface); border: 1px solid var(--border); border-radius: 16px; padding: 32px; text-align: center; color: var(--text2); font-family: var(--font-mono); font-size: 14px; }+.lightbox-name { margin-top: 12px; text-align: center; font-size: 13px; font-weight: 600; color: var(--text); }+.asset-bottom-space { height: 72px; }++/* ── Tooltip (shared, portalled) ── */+.tt-wrap { display: inline-flex; }+.tooltip {+ z-index: 100; pointer-events: none; white-space: nowrap;+ background: var(--surface3); color: var(--text); border: 1px solid var(--border);+ font-size: 11px; font-weight: 500; padding: 4px 8px; border-radius: 6px;+ box-shadow: 0 6px 18px rgba(0,0,0,0.4);+ animation: tooltip-in 0.12s var(--ease-out) both;+}+@keyframes tooltip-in { from { opacity: 0; transform: translate(-50%, calc(-100% + 3px)); } }+.tooltip-bottom { animation: none; }+@media (prefers-reduced-motion: reduce) { .tooltip { animation: none; } }++/* ── Asset picker (reused across pages) ── */+.asset-picker { position: relative; display: inline-flex; flex-direction: column; gap: 6px; min-width: 200px; }+.asset-picker-label { font-size: 11px; font-weight: 600; color: var(--text2); }+.asset-picker-btn {+ display: flex; align-items: center; gap: 8px; width: 100%;+ padding: 6px 10px; background: var(--surface2); border: 1px solid var(--border);+ border-radius: var(--radius-sm); color: var(--text); cursor: pointer; font-family: inherit; font-size: 13px;+ transition: border-color 0.15s var(--ease);+}+.asset-picker-btn:hover:not(:disabled) { border-color: var(--border-hover); }+.asset-picker-btn:disabled { opacity: 0.5; cursor: not-allowed; }+.asset-picker-name { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }+.asset-picker-name.muted { color: var(--text3); }+.picker-thumb { width: 26px; height: 26px; border-radius: 4px; object-fit: cover; background: var(--bg2); flex-shrink: 0; }+.picker-thumb-file { display: block; }+.asset-picker-menu {+ position: absolute; top: calc(100% + 4px); left: 0; right: 0; z-index: 50;+ background: var(--surface); border: 1px solid var(--border); border-radius: var(--radius-sm);+ padding: 4px; box-shadow: 0 8px 24px rgba(0,0,0,0.4); max-height: 280px; overflow-y: auto;+}+.asset-picker-opt {+ display: flex; align-items: center; gap: 8px; width: 100%; text-align: left;+ padding: 6px 8px; background: none; border: none; color: var(--text2);+ font-family: inherit; font-size: 13px; cursor: pointer; border-radius: 6px;+}+.asset-picker-opt:hover:not(:disabled) { background: var(--surface2); color: var(--text); }+.asset-picker-foot { display: flex; align-items: center; gap: 4px; border-top: 1px solid var(--border); margin-top: 4px; padding-top: 4px; }+.asset-picker-foot .asset-picker-opt { flex: 1; }+.asset-picker-link { font-size: 12px; color: var(--accent); text-decoration: none; padding: 6px 10px; flex-shrink: 0; }+.asset-picker-link:hover { text-decoration: underline; }++.cap-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); gap: 12px; }+.cap-card {+ display: flex; flex-direction: column; padding: 0; overflow: hidden;+ background: var(--surface2); border: 1px solid var(--border);+ border-radius: var(--radius); cursor: pointer; text-align: left;+ transition: border-color 0.15s var(--ease), box-shadow 0.15s var(--ease);+}+.cap-card:hover { border-color: var(--border-hover); }+.cap-card.selected { border-color: var(--accent); box-shadow: 0 0 0 1px var(--accent-edge); }+.cap-preview {+ height: 84px; display: flex; align-items: center; justify-content: center;+ background: linear-gradient(135deg, #2a2f3a, #14171d); padding: 8px; text-align: center;+}+.cap-label { display: flex; align-items: center; gap: 6px; padding: 8px 10px; font-size: 13px; font-weight: 600; color: var(--text); }+.cap-hormozi { font-family: var(--font-sans); font-weight: 800; font-size: 15px; text-transform: uppercase; color: #fff; text-shadow: 0 2px 4px #000; }+.cap-karaoke { font-family: var(--font-sans); font-weight: 700; font-size: 14px; color: #fff; }+.cap-karaoke::first-letter { color: var(--yellow); }+.cap-subtle { font-family: var(--font-sans); font-weight: 500; font-size: 12px; color: #e5e7eb; }+.cap-branded { font-family: var(--font-sans); font-weight: 800; font-size: 14px; text-transform: uppercase; color: #fff; background: rgba(0,0,0,0.8); padding: 3px 8px; border-radius: 8px; }diff --git a/src/ui/web-server.ts b/src/ui/web-server.tsindex 7f18539..e350add 100644--- a/src/ui/web-server.ts+++ b/src/ui/web-server.ts@@ -33,7 +33,7 @@ import { v4 as uuidv4 } from "uuid";import { PythonExecutor } from "../services/python-executor.js";import { TranscriptCache } from "../services/transcript-cache.js";import { FileManager } from "../services/file-manager.js";-import { AssetManager } from "../services/asset-manager.js";+import { AssetManager, inferType, safeName } from "../services/asset-manager.js";import { ClipsHistory } from "../services/clips-history.js";import { KnowledgeBase } from "../services/knowledge-base.js";import { paths } from "../config/paths.js";@@ -43,6 +43,7 @@ import { childLogger } from "../utils/logger.js";import { sliceTranscript, sliceWords, findContentType } from "../utils/transcript.js";import { errMsg } from "../utils/errors.js";import type {+ AssetType,BatchClipsResult,ClipHistoryEntry,ClipResult,@@ -118,6 +119,7 @@ interface UIState {format: string;logoPath: string;outroPath: string;+ introPath: string;};phase: string;results: unknown[];@@ -151,6 +153,7 @@ function loadPersistedState(): UIState {format: saved.settings?.format || "vertical",logoPath: saved.settings?.logoPath || "",outroPath: saved.settings?.outroPath || "",+ introPath: saved.settings?.introPath || "",},// Never restore mid-export phasesphase: ["exporting", "parsing", "suggesting"].includes(saved.phase)@@ -182,6 +185,7 @@ function loadPersistedState(): UIState {format: "vertical",logoPath: "",outroPath: "",+ introPath: "",},phase: "idle",results: [],@@ -195,10 +199,36 @@ const uiState: UIState = loadPersistedState();// Files the server confirmed the user selected; /api/stream-source serves only// these, so a forged /api/ui-state can't grant reads of arbitrary files.const allowedSourcePaths = new Set<string>();++// Recent source videos, referenced in place (never copied) so they can be+// re-picked without re-uploading. Persisted as paths only — no GB bloat.+const sourcesFile = join(paths.home, "sources.json");+const VIDEO_SOURCE_EXTS = new Set([".mp4", ".mov", ".mkv", ".webm", ".m4v", ".avi"]);+let recentSources: string[] = loadRecentSources();++function loadRecentSources(): string[] {+ try {+ const raw = JSON.parse(readFileSync(sourcesFile, "utf-8"));+ return Array.isArray(raw) ? raw.filter((p) => typeof p === "string") : [];+ } catch {+ return [];+ }+}++function rememberSource(realPath: string): void {+ if (!VIDEO_SOURCE_EXTS.has(extname(realPath).toLowerCase())) return;+ recentSources = [realPath, ...recentSources.filter((p) => p !== realPath)].slice(0, 40);+ try {+ writeFileSync(sourcesFile, JSON.stringify(recentSources, null, 2), "utf-8");+ } catch {}+}+function registerSourcePath(p: string | undefined | null): void {if (!p) return;try {- allowedSourcePaths.add(realpathSync(path.resolve(p)));+ const real = realpathSync(path.resolve(p));+ allowedSourcePaths.add(real);+ rememberSource(real);} catch {}}registerSourcePath(uiState.videoPath);@@ -335,8 +365,9 @@ function createBatchHistoryRecorder({// --- Middleware ---app.use(express.json({ limit: "50mb" }));-// Serve static frontend-app.use(express.static(publicDir));+// Serve static frontend. redirect:false so the /assets page route isn't shadowed+// by a 301 to the Vite bundle's assets/ directory; it falls through to the SPA.+app.use(express.static(publicDir, { redirect: false }));// File upload configconst uploadDir = join(paths.working, "uploads");@@ -941,8 +972,6 @@ app.post("/api/create-clip", async (req, res) => {format = "vertical",transcript_words = [],title = "clip",- logo_path = null,- outro_path = null,clean_fillers = false,allow_ass_fallback = false,content_type = null,@@ -953,6 +982,22 @@ app.post("/api/create-clip", async (req, res) => {return;}+ // Resolve asset names (or paths) to real paths; reject only if provided-and-unresolvable.+ let logo_path: string | null = null;+ let outro_path: string | null = null;+ let intro_path: string | null = null;+ for (const [key, raw] of [["logo", req.body.logo_path], ["outro", req.body.outro_path], ["intro", req.body.intro_path]] as const) {+ if (!raw) continue;+ const resolved = await assetManager.resolve(raw);+ if (!resolved) {+ res.status(400).json({ error: `${key} not found: ${raw}` });+ return;+ }+ if (key === "logo") logo_path = resolved;+ else if (key === "outro") outro_path = resolved;+ else intro_path = resolved;+ }+// Validate clip params before spawning Pythonif (typeof start_second !== "number" || typeof end_second !== "number") {res@@ -974,14 +1019,6 @@ app.post("/api/create-clip", async (req, res) => {});return;}- if (logo_path && !existsSync(logo_path)) {- res.status(400).json({ error: `Logo file not found: ${logo_path}` });- return;- }- if (outro_path && !existsSync(outro_path)) {- res.status(400).json({ error: `Outro file not found: ${outro_path}` });- return;- }const validStyles = ["hormozi", "karaoke", "subtle", "branded"];if (!validStyles.includes(caption_style)) {res@@ -1034,6 +1071,7 @@ app.post("/api/create-clip", async (req, res) => {output_dir: paths.output,logo_path,outro_path,+ intro_path,clean_fillers,allow_ass_fallback,},@@ -1059,6 +1097,7 @@ app.post("/api/create-clip", async (req, res) => {format,logo_path: logo_path || undefined,outro_path: outro_path || undefined,+ intro_path: intro_path || undefined,title,output_path: d?.output_path || "",file_size_mb: d?.file_size_mb || 0,@@ -1070,7 +1109,7 @@ app.post("/api/create-clip", async (req, res) => {await clipsHistory.saveWords(rec.id, clipWords);await clipsHistory.saveRecipe(rec.id, {caption_style, crop_strategy, format, logo_path: logo_path || null, outro_path: outro_path || null,- clean_fillers, transcript_words: clipWords,+ intro_path: intro_path || null, clean_fillers, transcript_words: clipWords,});broadcastHistoryUpdated(jobId, [rec]);} catch (err) {@@ -1097,8 +1136,6 @@ app.post("/api/batch-clips", async (req, res) => {video_path,clips,transcript_words = [],- logo_path = null,- outro_path = null,clean_fillers = false,keep_caption_overlay = false,} = req.body;@@ -1111,6 +1148,21 @@ app.post("/api/batch-clips", async (req, res) => {res.status(400).json({ error: "No clips provided" });return;}++ let logo_path: string | null = null;+ let outro_path: string | null = null;+ let intro_path: string | null = null;+ for (const [key, raw] of [["logo", req.body.logo_path], ["outro", req.body.outro_path], ["intro", req.body.intro_path]] as const) {+ if (!raw) continue;+ const resolved = await assetManager.resolve(raw);+ if (!resolved) {+ res.status(400).json({ error: `${key} not found: ${raw}` });+ return;+ }+ if (key === "logo") logo_path = resolved;+ else if (key === "outro") outro_path = resolved;+ else intro_path = resolved;+ }// Validate each clip's timingfor (let i = 0; i < clips.length; i++) {const c = clips[i];@@ -1131,14 +1183,6 @@ app.post("/api/batch-clips", async (req, res) => {return;}}- if (logo_path && !existsSync(logo_path)) {- res.status(400).json({ error: `Logo file not found: ${logo_path}` });- return;- }- if (outro_path && !existsSync(outro_path)) {- res.status(400).json({ error: `Outro file not found: ${outro_path}` });- return;- }await fileManager.ensureDirectories();@@ -1175,6 +1219,7 @@ app.post("/api/batch-clips", async (req, res) => {output_dir: paths.output,logo_path,outro_path,+ intro_path,clean_fillers,keep_caption_overlay: keep_caption_overlay === true,face_map: uiState.transcript?.face_map,@@ -1669,34 +1714,171 @@ app.post("/api/presets", async (req, res) => {});// --- Assets ---+function uniqueAssetName(base: string, taken: Set<string>): string {+ const slug = (base || "asset").replace(/[^a-zA-Z0-9._-]/g, "-").replace(/^-+|-+$/g, "") || "asset";+ if (!taken.has(slug)) return slug;+ let i = 2;+ while (taken.has(`${slug}-${i}`)) i++;+ return `${slug}-${i}`;+}+app.get("/api/assets", async (req, res) => {try {const items = await assetManager.list(req.query.type as string | undefined);res.json(items);- } catch (err: any) {- res.status(500).json({ error: err.message });+ } catch (err: unknown) {+ res.status(500).json({ error: errMsg(err) });}});app.post("/api/assets/register", async (req, res) => {- const { name, path: filePath, type = "other" } = req.body;+ const { name, path: filePath, type } = req.body;try {- const asset = await assetManager.register(name, filePath, type);+ const asset = await assetManager.register(name, filePath, type || inferType(filePath));+ broadcastSSE("assets-updated", { name });res.json(asset);- } catch (err: any) {- res.status(400).json({ error: err.message });+ } catch (err: unknown) {+ res.status(400).json({ error: errMsg(err) });+ }+});++app.post("/api/assets/upload", upload.single("file"), async (req, res) => {+ if (!req.file) {+ res.status(400).json({ error: "No file uploaded" });+ return;+ }+ try {+ const existing = new Set((await assetManager.list()).map((a) => a.name));+ const wanted = safeName((req.body?.name as string) || basename(req.file.originalname, extname(req.file.originalname)));+ const name = existing.has(wanted) && !req.body?.overwrite ? uniqueAssetName(wanted, existing) : wanted;+ const type = (req.body?.type as AssetType) || inferType(req.file.originalname);+ const asset = await assetManager.importFile(req.file.path, name, type);+ broadcastSSE("assets-updated", { name });+ res.json(asset);+ } catch (err: unknown) {+ res.status(400).json({ error: errMsg(err) });+ } finally {+ await unlink(req.file.path).catch(() => {});+ }+});++app.post("/api/assets/url", async (req, res) => {+ let url: string;+ try {+ url = await validateDownloadUrl(req.body?.url);+ } catch (err: unknown) {+ res.status(400).json({ error: errMsg(err) });+ return;+ }+ const jobId = uuidv4();+ const job: JobState = {+ id: jobId,+ type: "download_video",+ status: "running",+ progress: 0,+ message: "Downloading asset",+ createdAt: Date.now(),+ };+ jobs.set(jobId, job);+ res.json({ job_id: jobId });++ (async () => {+ try {+ const existing = new Set((await assetManager.list()).map((a) => a.name));+ const wanted = safeName((req.body?.name as string) || basename(new URL(url).pathname) || "asset");+ const name = existing.has(wanted) ? uniqueAssetName(wanted, existing) : wanted;+ const type = req.body?.type as AssetType | undefined;+ const asset = await assetManager.importUrl(url, name, type);+ job.status = "done";+ job.progress = 100;+ job.result = asset;+ broadcastSSE("job-complete", { jobId, result: asset });+ broadcastSSE("assets-updated", { name });+ } catch (err: unknown) {+ job.status = "error";+ job.error = errMsg(err);+ broadcastSSE("job-error", { jobId, error: job.error });+ }+ })();+});++app.post("/api/assets/:name/default", async (req, res) => {+ try {+ const asset = await assetManager.setDefault(req.params.name);+ broadcastSSE("assets-updated", { name: asset.name });+ res.json(asset);+ } catch (err: unknown) {+ res.status(400).json({ error: errMsg(err) });+ }+});++app.delete("/api/assets/:name/default", async (req, res) => {+ try {+ await assetManager.clearDefault(req.params.name);+ broadcastSSE("assets-updated", { name: req.params.name });+ res.json({ ok: true });+ } catch (err: unknown) {+ res.status(400).json({ error: errMsg(err) });+ }+});++app.post("/api/assets/:name/rename", async (req, res) => {+ try {+ const asset = await assetManager.rename(req.params.name, req.body?.new_name);+ broadcastSSE("assets-updated", { name: asset.name });+ res.json(asset);+ } catch (err: unknown) {+ res.status(400).json({ error: errMsg(err) });+ }+});++app.get("/api/assets/:name/download", async (req, res) => {+ try {+ // Look up by registered name only — never fall through to treating the+ // param as a filesystem path (that would allow arbitrary file reads).+ const asset = (await assetManager.list()).find((a) => a.name === req.params.name);+ if (!asset || !existsSync(asset.path)) {+ res.status(404).json({ error: `Asset "${req.params.name}" not found` });+ return;+ }+ if (req.query.dl) {+ res.download(asset.path, basename(asset.path));+ } else {+ res.sendFile(asset.path);+ }+ } catch (err: unknown) {+ res.status(500).json({ error: errMsg(err) });+ }+});++app.delete("/api/assets/:name", async (req, res) => {+ try {+ await assetManager.unregister(req.params.name);+ broadcastSSE("assets-updated", { name: req.params.name });+ res.json({ ok: true });+ } catch (err: unknown) {+ res.status(400).json({ error: errMsg(err) });}});app.post("/api/assets/unregister", async (req, res) => {try {await assetManager.unregister(req.body.name);+ broadcastSSE("assets-updated", { name: req.body.name });res.json({ ok: true });- } catch (err: any) {- res.status(400).json({ error: err.message });+ } catch (err: unknown) {+ res.status(400).json({ error: errMsg(err) });}});+// Recent source videos (referenced in place, not copied).+app.get("/api/sources", (_req, res) => {+ const items = recentSources+ .map((p) => ({ path: p, name: basename(p), exists: existsSync(p) }))+ .filter((s) => s.exists);+ res.json(items);+});+// --- Clip History ---app.get("/api/history", async (req, res) => {try {@@ -2216,6 +2398,8 @@ app.post("/api/clips/:id/rerender", async (req, res) => {transcript_words: words,logo_path: (recipe.logo_path as string) ?? clip.logo_path ?? null,outro_path: (recipe.outro_path as string) ?? clip.outro_path ?? null,+ // Honor an explicit null in the recipe (intro removed), not the stale clip value.+ intro_path: "intro_path" in recipe ? (recipe.intro_path ?? null) : (clip.intro_path ?? null),clean_fillers: recipe.clean_fillers !== undefined ? recipe.clean_fillers : true,...(recipe.keep_segments ? { keep_segments: recipe.keep_segments } : {}),title: clip.title,@@ -3038,6 +3222,8 @@ app.post("/api/ui-state", (req, res) => {uiState.settings.logoPath = body.settings.logoPath;if (body.settings.outroPath !== undefined)uiState.settings.outroPath = body.settings.outroPath;+ if (body.settings.introPath !== undefined)+ uiState.settings.introPath = body.settings.introPath;}uiState.lastUpdated = Date.now();persistState();@@ -3079,6 +3265,7 @@ app.post("/api/mcp/export", async (req, res) => {: []);const logoPath = req.body.logo_path || uiState.settings.logoPath || null;const outroPath = req.body.outro_path || uiState.settings.outroPath || null;+ const introPath = req.body.intro_path || uiState.settings.introPath || null;const captionStyle =req.body.caption_style || uiState.settings.captionStyle || "branded";const cropStrategy =@@ -3149,6 +3336,7 @@ app.post("/api/mcp/export", async (req, res) => {output_dir: paths.output,logo_path: logoPath,outro_path: outroPath,+ intro_path: introPath,face_map: uiState.transcript?.face_map,},(event) => {diff --git a/tests/test_asset_store.py b/tests/test_asset_store.pyindex 9f9c239..19626db 100644--- a/tests/test_asset_store.py+++ b/tests/test_asset_store.py@@ -75,11 +75,67 @@ class AssetStoreTests(unittest.TestCase):def test_list_filters_by_type(self):asset_store.register("l1", self._make_file("l1.png"), "logo")- asset_store.register("v1", self._make_file("v1.mp4"), "video")+ asset_store.register("o1", self._make_file("o1.mp4"), "outro")self.assertEqual(len(asset_store.list_assets("logo")), 1)- self.assertEqual(len(asset_store.list_assets("video")), 1)+ self.assertEqual(len(asset_store.list_assets("outro")), 1)self.assertEqual(len(asset_store.list_assets()), 2)+ def test_legacy_video_type_migrates_to_outro(self):+ asset_store.register("legacy", self._make_file("legacy.mp4"), "video")+ loaded = asset_store.list_assets()+ self.assertEqual(loaded[0]["type"], "outro")+ self.assertEqual(len(asset_store.list_assets("outro")), 1)+ self.assertEqual(len(asset_store.list_assets("video")), 0)+ with open(self.registry_file) as f:+ self.assertEqual(json.load(f)["schemaVersion"], asset_store.SCHEMA_VERSION)++ def test_set_and_clear_default(self):+ a = self._make_file("d1.png")+ b = self._make_file("d2.png")+ asset_store.register("d1", a, "logo")+ asset_store.register("d2", b, "logo")+ self.assertEqual(asset_store.default_logo(), a) # first-existing fallback+ asset_store.set_default("d2")+ self.assertEqual(asset_store.default_logo(), b)+ flagged = [x for x in asset_store.list_assets("logo") if x.get("default")]+ self.assertEqual(len(flagged), 1)+ self.assertTrue(asset_store.clear_default("d2"))+ self.assertEqual(asset_store.default_logo(), a)++ def test_outro_and_video_share_default_group(self):+ vid = self._make_file("share.mp4")+ asset_store.register("shared", vid, "outro")+ asset_store.set_default("shared")+ self.assertEqual(asset_store.default_outro(), vid)++ def test_rename_keeps_file_and_default(self):+ p = self._make_file("r.png")+ asset_store.register("old", p, "logo")+ asset_store.set_default("old")+ renamed = asset_store.rename("old", "new")+ self.assertEqual(renamed["name"], "new")+ self.assertTrue(renamed["default"])+ self.assertEqual(asset_store.resolve("new"), p)+ self.assertIsNone(asset_store.resolve("old"))++ def test_rename_rejects_duplicate(self):+ asset_store.register("a", self._make_file("a.png"), "logo")+ asset_store.register("b", self._make_file("b.png"), "logo")+ with self.assertRaises(ValueError):+ asset_store.rename("a", "b")++ def test_register_sanitizes_unsafe_names(self):+ asset = asset_store.register("my logo/v2", self._make_file("s.png"), "logo")+ self.assertEqual(asset["name"], "my-logo-v2")+ self.assertTrue(asset_store.resolve("my-logo-v2"))++ def test_import_file_copies_into_assets_dir(self):+ src = self._make_file("orig.png")+ with mock.patch.dict(asset_store.paths, {"assets": self.tmpdir}):+ asset = asset_store.import_file(src, "copied", "logo")+ self.assertNotEqual(asset["path"], src)+ self.assertTrue(os.path.exists(asset["path"]))+def test_unregister_returns_true_when_removed(self):asset_store.register("tmp", self._make_file("t.png"), "logo")self.assertTrue(asset_store.unregister("tmp"))