Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
fix(demos): isolate theme recordings (#3864)
Maximilian Roos4cb2d4193b2b
diff --git a/docs/demos/CLAUDE.md b/docs/demos/CLAUDE.mdindex f424635ae..19bfc651f 100644--- a/docs/demos/CLAUDE.md+++ b/docs/demos/CLAUDE.md@@ -79,7 +79,7 @@ Checkpoints are defined in `docs/demos/shared/validation.py`. To add validation1. Identify key frame numbers by examining the GIF (30fps, so frame 90 = 3 seconds)2. Define checkpoint patterns in `validation.py` with frame numbers, expected patterns, and forbidden patterns-Currently `wt-zellij-omnibus` has checkpoints; other TUI demos are skipped until checkpoints are added.+`wt-switch`, `wt-statusline`, and `wt-zellij-omnibus` have checkpoints. Other TUI demos are skipped until checkpoints are added.**Prerequisites for TUI validation:** `ffmpeg` and `tesseract` must be installed.@@ -92,10 +92,11 @@ Currently `wt-zellij-omnibus` has checkpoints; other TUI demos are skipped until**Requires Go** — The VHS fork is built from source ([install Go](https://go.dev/dl/)).-**Requires ffmpeg with libass** — The keystroke overlay uses ASS subtitles. The build script checks for this and exits with install instructions if missing. Homebrew's API-sourced bottle omits `libass`; install from the tap formula instead:+**Requires ffmpeg with libass** — The keystroke overlay uses ASS subtitles. The build script checks for this and exits with install instructions if missing. Homebrew's regular `ffmpeg` formula omits `libass`; use the keg-only full build instead:```bash-HOMEBREW_NO_INSTALL_FROM_API=1 brew install --build-from-source ffmpeg+brew install ffmpeg-full+export PATH="$(brew --prefix ffmpeg-full)/bin:$PATH"```External dependencies are downloaded/built automatically on first run:@@ -103,13 +104,15 @@ External dependencies are downloaded/built automatically on first run:- **Claude Code binary** — Downloaded from Anthropic's release bucket- **Zellij plugin** — Downloaded from GitHub releases-Demos that launch Claude Code (wt-switch, wt-statusline, wt-zellij-omnibus) require `ANTHROPIC_API_KEY` in your environment:+Demos that launch Claude Code (`wt-switch`, `wt-statusline`, `wt-zellij-omnibus`) require authentication. On macOS, the recorder reuses the current `claude auth login` credential from the user's Keychain. Other environments can provide an OAuth token or API key:```bash-export ANTHROPIC_API_KEY=sk-ant-...+export CLAUDE_CODE_OAUTH_TOKEN=...+# or+export ANTHROPIC_API_KEY=...```-This uses a small amount of API credits per recording (Claude starts, renders its UI, then exits).+Recording uses the authenticated account's Claude usage.## Publishing demos@@ -199,6 +202,8 @@ The docs build generates both light and dark GIF variants in separate directorie- `docs/light/wt-merge.gif` / `docs/dark/wt-merge.gif`- `docs/light/wt-switch-picker.gif` / `docs/dark/wt-switch-picker.gif`+Each theme starts from a freshly prepared demo environment because recording a tape changes its repository and worktrees.+Social build generates light only (social media doesn't support theme-switching media queries).Theme definitions are in `docs/demos/shared/themes.py`, matching the CSS variables in `_variables.html`.@@ -220,6 +225,8 @@ wt switch --create foo # Create a worktreewt switch --execute claude --create bar # Test the demo command```+After fish exits, the debug environment remains at the path printed when the shell starts. Remove that directory manually when you no longer need it.+## Timing guidelinesDemo GIFs should feel natural—not rushed, but not lingering. The goal is to let viewers read and understand each step before moving on.@@ -264,6 +271,8 @@ Key fields in `.claude.json` for suppressing notifications:- `officialMarketplaceAutoInstalled: true` - should suppress marketplace auto-install- `numStartups: 100` - makes Claude think it's been run many times- `hasCompletedOnboarding: true` - skips onboarding+- `announcementImpressions` - suppresses launch promotions+- `passesUpsellSeenCount`, `passesLastSeenRemaining`, and `hasVisitedPasses` - suppress the guest-pass promotion, including after eligibility refresh## Viewing GIF resultsdiff --git a/docs/demos/build b/docs/demos/buildindex 49563ecdd..96eded34b 100755--- a/docs/demos/build+++ b/docs/demos/build@@ -20,6 +20,7 @@ import subprocessimport sysimport tempfileimport time+from contextlib import contextmanagerfrom concurrent.futures import ProcessPoolExecutor, as_completedfrom functools import partialfrom pathlib import Path@@ -35,13 +36,14 @@ from shared import ( # noqa: E402DemoSize,git,prepare_demo_repo,+ claude_auth_available,setup_claude_code_config,setup_zellij_config,setup_fish_config,check_dependencies,check_ffmpeg_libass,setup_demo_output,- record_all_themes,+ record_theme,SIZE_DOCS,SIZE_SOCIAL,record_text,@@ -61,6 +63,7 @@ SNAPSHOTS_DIR = SCRIPT_DIR / "snapshots"# Demos that use TUI or interactive input - not suitable for command snapshotsTUI_DEMOS = {"wt-switch-picker", "wt-switch", "wt-statusline", "wt-zellij-omnibus"}+CLAUDE_DEMOS = {"wt-switch", "wt-statusline", "wt-zellij-omnibus"}# =============================================================================@@ -68,6 +71,23 @@ TUI_DEMOS = {"wt-switch-picker", "wt-switch", "wt-statusline", "wt-zellij-omnibu# =============================================================================+@contextmanager+def prepared_demo_env(output_name: str, setup_func):+ """Create a prepared demo environment and remove it after use."""+ with tempfile.TemporaryDirectory(+ prefix="wt-demo-", ignore_cleanup_errors=True+ ) as demo_env_dir:+ yield _prepare_demo_env(Path(demo_env_dir), output_name, setup_func)+++def _prepare_demo_env(out_dir: Path, output_name: str, setup_func) -> DemoEnv:+ """Prepare a demo environment at an existing directory."""+ setup_demo_output(out_dir)+ env = DemoEnv(name=output_name, out_dir=out_dir, repo_name="acme")+ setup_func(env)+ return env++def _add_billing_branch(env: DemoEnv):"""Add a billing branch at same commit as main (merged state)."""branch = "billing"@@ -356,24 +376,19 @@ def record_demo(if not tape_path.exists():raise FileNotFoundError(f"{tape_file} not found")- # Create fresh environment in temp directory- demo_env_dir = Path(tempfile.mkdtemp(prefix="wt-demo-"))- setup_demo_output(demo_env_dir)- env = DemoEnv(name=output_name, out_dir=demo_env_dir, repo_name="acme")- setup_func(env)-- replacements = build_tape_replacements(env, REPO_ROOT)-if snapshot_mode:- output_snap = SNAPSHOTS_DIR / f"{output_name}.snap"- record_snapshot(env, tape_path, output_snap, REPO_ROOT)+ with prepared_demo_env(output_name, setup_func) as env:+ output_snap = SNAPSHOTS_DIR / f"{output_name}.snap"+ record_snapshot(env, tape_path, output_snap, REPO_ROOT)elapsed = time.monotonic() - t0print(f"✓ {output_name}: Snapshot saved ({elapsed:.0f}s)")return elapsedif text_mode:- output_txt = mode_out_dir / f"{output_name}.txt"- record_text(env, tape_path, output_txt, replacements, REPO_ROOT)+ with prepared_demo_env(output_name, setup_func) as env:+ replacements = build_tape_replacements(env, REPO_ROOT)+ output_txt = mode_out_dir / f"{output_name}.txt"+ record_text(env, tape_path, output_txt, replacements, REPO_ROOT)elapsed = time.monotonic() - t0print(f"✓ {output_name}: Text saved ({elapsed:.0f}s)")return elapsed@@ -384,30 +399,42 @@ def record_demo(theme_dir.mkdir(parents=True, exist_ok=True)output_gifs[theme] = theme_dir / f"{output_name}.gif"- record_all_themes(- env,- tape_path,- output_gifs,- REPO_ROOT,- vhs_binary=vhs_binary,- size=demo_size,- )+ for theme, output_gif in output_gifs.items():+ # Every tape mutates its repository. A fresh environment keeps one+ # theme's commands from changing the starting state of the next theme.+ with prepared_demo_env(output_name, setup_func) as env:+ record_theme(+ env,+ tape_path,+ theme,+ output_gif,+ REPO_ROOT,+ vhs_binary=vhs_binary,+ size=demo_size,+ )elapsed = time.monotonic() - t0# Validate TUI demos with OCR after recordingif output_name in TUI_CHECKPOINTS:- gif_path = output_gifs.get("light", list(output_gifs.values())[0])- success, output = validate_tui_demo_verbose(output_name, gif_path)- if success:- print(f"✓ {output_name}: GIFs saved + validation passed ({elapsed:.0f}s)")- else:+ validation_failures = {}+ for theme, gif_path in output_gifs.items():+ success, output = validate_tui_demo_verbose(output_name, gif_path)+ if not success:+ validation_failures[theme] = output++ if validation_failures:print(f"✓ {output_name}: GIFs saved ({elapsed:.0f}s)")- print(f"✗ {output_name}: Validation failed")- for line in output.split("\n"):- if line.startswith(" "):- print(line)+ for theme, output in validation_failures.items():+ print(f"✗ {output_name} ({theme}): Validation failed")+ for line in output.split("\n"):+ if line.startswith(" "):+ print(line)raise RuntimeError(f"TUI validation failed for {output_name}")+ print(+ f"✓ {output_name}: GIFs saved + validation passed: "+ f"{', '.join(themes)} ({elapsed:.0f}s)"+ )else:print(f"✓ {output_name}: GIFs saved: {', '.join(themes)} ({elapsed:.0f}s)")@@ -422,6 +449,7 @@ def record_demo(def spawn_debug_shell(env: DemoEnv, starship_config: Path):"""Spawn an interactive fish shell with the demo environment set up."""shell_env = os.environ.copy()+ shell_env.pop("CLAUDE_CONFIG_DIR", None)shell_env.update({"HOME": str(env.home),@@ -503,6 +531,38 @@ Examples:print("--only cannot be used with multiple targets")return+ selected_claude_demos = sorted(+ {+ name+ for target in args.target+ for _, name, _ in TARGETS[target]["demos"]+ if name in CLAUDE_DEMOS and (args.only is None or name == args.only)+ }+ )+ if (+ selected_claude_demos+ and not args.shell+ and not args.snapshot+ and not claude_auth_available()+ ):+ print(+ "✗ Claude Code authentication is required to record: "+ f"{', '.join(selected_claude_demos)}",+ file=sys.stderr,+ )+ if sys.platform == "darwin":+ print(+ "↳ Run claude auth login, or set CLAUDE_CODE_OAUTH_TOKEN "+ "or ANTHROPIC_API_KEY",+ file=sys.stderr,+ )+ else:+ print(+ "↳ Set CLAUDE_CODE_OAUTH_TOKEN or ANTHROPIC_API_KEY",+ file=sys.stderr,+ )+ sys.exit(1)+# Check dependencies (VHS is built from source, not required in PATH)deps = ["wt", "starship", "zellij"]check_dependencies(deps)@@ -577,10 +637,8 @@ def build_target(target: str, args, vhs_binary: str) -> list[str]:# Handle --shell mode (interactive, must be sequential)if args.shell:tape_file, output_name, setup_func = demos[0]- demo_env_dir = Path(tempfile.mkdtemp(prefix="wt-demo-"))- setup_demo_output(demo_env_dir)- env = DemoEnv(name=output_name, out_dir=demo_env_dir, repo_name="acme")- setup_func(env)+ debug_dir = Path(tempfile.mkdtemp(prefix="wt-demo-"))+ env = _prepare_demo_env(debug_dir, output_name, setup_func)print(f"Demo repo: {env.repo}")spawn_debug_shell(env, FIXTURES_DIR / "starship.toml")return []diff --git a/docs/demos/shared/__init__.py b/docs/demos/shared/__init__.pyindex eb2a8abcc..6bbe24425 100644--- a/docs/demos/shared/__init__.py+++ b/docs/demos/shared/__init__.py@@ -15,6 +15,7 @@ from .lib import (build_wt,commit_dated,prepare_base_repo,+ claude_auth_available,setup_claude_code_config,setup_zellij_config,setup_fish_config,@@ -24,7 +25,7 @@ from .lib import (check_dependencies,check_ffmpeg_libass,setup_demo_output,- record_all_themes,+ record_theme,# Text output recordingrecord_text,build_tape_replacements,@@ -51,6 +52,7 @@ __all__ = ["build_wt","commit_dated","prepare_base_repo",+ "claude_auth_available","setup_claude_code_config","setup_zellij_config","setup_fish_config",@@ -62,7 +64,7 @@ __all__ = ["check_dependencies","check_ffmpeg_libass","setup_demo_output",- "record_all_themes",+ "record_theme",# Text output recording"record_text","build_tape_replacements",diff --git a/docs/demos/shared/lib.py b/docs/demos/shared/lib.pyindex a6935dd27..6d86dfee7 100644--- a/docs/demos/shared/lib.py+++ b/docs/demos/shared/lib.py@@ -4,8 +4,10 @@ import jsonimport osimport platformimport re+import shleximport shutilimport subprocess+import tempfileimport urllib.requestfrom dataclasses import dataclassfrom datetime import datetime, timedelta@@ -106,6 +108,83 @@ def _ensure_claude_binary() -> Path:return claude_binary+def claude_auth_available() -> bool:+ """Return whether a Claude demo can authenticate without interactive login."""+ if os.environ.get("ANTHROPIC_API_KEY") or os.environ.get(+ "CLAUDE_CODE_OAUTH_TOKEN"+ ):+ return True+ if platform.system() != "Darwin":+ return False++ try:+ with tempfile.TemporaryDirectory(prefix="wt-claude-auth-") as auth_dir:+ auth_home = Path(auth_dir)+ _forward_macos_keychains(auth_home)+ result = subprocess.run(+ [str(_ensure_claude_binary()), "auth", "status", "--json"],+ env=_isolated_claude_env(auth_home),+ capture_output=True,+ text=True,+ check=False,+ timeout=10,+ )+ if result.returncode != 0:+ return False+ return bool(json.loads(result.stdout).get("loggedIn"))+ except (+ OSError,+ RuntimeError,+ subprocess.TimeoutExpired,+ json.JSONDecodeError,+ ):+ return False+++def _forward_macos_keychains(home: Path) -> None:+ """Make the user's Keychain search list visible from an isolated HOME."""+ if (+ platform.system() != "Darwin"+ or os.environ.get("ANTHROPIC_API_KEY")+ or os.environ.get("CLAUDE_CODE_OAUTH_TOKEN")+ ):+ return++ real_home_env = {**os.environ, "HOME": str(REAL_HOME)}+ result = subprocess.run(+ ["security", "list-keychains", "-d", "user"],+ env=real_home_env,+ capture_output=True,+ text=True,+ check=False,+ )+ if result.returncode != 0:+ raise RuntimeError(+ f"Failed to read the macOS Keychain search list: {result.stderr}"+ )++ # `security` has no structured output for the search list. Its output is a+ # shell-like sequence of quoted paths, one per line.+ keychains = [path for path in shlex.split(result.stdout) if Path(path).exists()]+ if not keychains:+ raise RuntimeError("The macOS user Keychain search list is empty")++ (home / "Library" / "Preferences").mkdir(parents=True, exist_ok=True)+ run(+ ["security", "list-keychains", "-d", "user", "-s", *keychains],+ env=_isolated_claude_env(home),+ )+++def _isolated_claude_env(home: Path) -> dict[str, str]:+ """Build an environment whose Claude state stays under an isolated HOME."""+ env = os.environ.copy()+ env.pop("CLAUDE_CONFIG_DIR", None)+ env["HOME"] = str(home)+ env["XDG_CONFIG_HOME"] = str(home / ".config")+ return env++def _ensure_zellij_plugin() -> Path:"""Ensure Zellij tab-name plugin is downloaded, return path."""plugin_path = DEPS_DIR / "zellij-tab-name.wasm"@@ -113,7 +192,7 @@ def _ensure_zellij_plugin() -> Path:return plugin_path_download_file(_ZELLIJ_PLUGIN_URL, plugin_path)- print(f"✓ Zellij plugin ready")+ print("✓ Zellij plugin ready")return plugin_path@@ -137,7 +216,7 @@ def ensure_vhs_binary() -> Path:# Clone if neededif not vhs_dir.exists():- print(f"Cloning VHS fork...")+ print("Cloning VHS fork...")DEPS_DIR.mkdir(parents=True, exist_ok=True)result = subprocess.run(["git", "clone", "-b", _VHS_FORK_BRANCH, "--depth=1", _VHS_FORK_REPO, str(vhs_dir)],@@ -148,7 +227,7 @@ def ensure_vhs_binary() -> Path:raise RuntimeError(f"Failed to clone VHS fork: {result.stderr}")# Build- print(f"Building VHS...")+ print("Building VHS...")result = subprocess.run(["go", "build", "-o", "vhs", "."],cwd=vhs_dir,@@ -168,7 +247,7 @@ def ensure_vhs_binary() -> Path:if result.returncode != 0:raise RuntimeError(f"VHS built but --version failed: {result.stderr}")- print(f"✓ VHS ready")+ print("✓ VHS ready")return vhs_binary@@ -275,7 +354,9 @@ def record_vhs(tape_path: Path, vhs_binary: str = "vhs", expected_output: Path = None):"""Record a demo GIF using VHS."""- run([vhs_binary, str(tape_path)], check=True)+ env = os.environ.copy()+ env.pop("CLAUDE_CONFIG_DIR", None)+ run([vhs_binary, str(tape_path)], check=True, env=env)if expected_output and not expected_output.exists():raise RuntimeError(@@ -492,9 +573,17 @@ def setup_claude_code_config("hasShownOpus46Notice": {},"opusProMigrationComplete": True,"opus46FeedSeenCount": 100,+ "unpinFable5LaunchEffort": True,"sonnet1m45MigrationComplete": True,"lastReleaseNotesSeen": "99.0.0","lastOnboardingVersion": "99.0.0",+ "announcementImpressions": {+ "fable-5-promo-2": 100,+ "fable-5-promo-2-2": 100,+ "fable-5-promo-2-3": 100,+ "fable-5-promo-2-4-max": 100,+ "opus-5-launch": 100,+ },"oauthAccount": {"displayName": "wt","emailAddress": "[email protected]",@@ -506,6 +595,9 @@ def setup_claude_code_config("officialMarketplaceAutoInstalled": True,"effortCalloutDismissed": True,"lspRecommendationDisabled": True,+ "passesUpsellSeenCount": 100,+ "passesLastSeenRemaining": 999,+ "hasVisitedPasses": True,"tipsHistory": {"new-user-warmup": 100,"terminal-setup": 100,@@ -522,6 +614,7 @@ def setup_claude_code_config("custom-agents": 100,"permissions": 100,"git-worktrees": 100,+ "guest-passes": 100,},"projects": projects_config,},@@ -548,6 +641,7 @@ def setup_claude_code_config(},}(claude_dir / "settings.json").write_text(json.dumps(settings, indent=2))+ _forward_macos_keychains(env.home)def setup_zellij_config(env: DemoEnv, default_cwd: str = None) -> None:@@ -679,6 +773,9 @@ def setup_fish_config(env: DemoEnv, wsl_create: bool = False) -> None:fish_config.write_text(f"""# Demo fish config# wsl abbreviation: switch to worktree and launch Claudeabbr --add wsl '{wsl_cmd}'+# New Zellij tabs start new fish processes, so disable suggestions here rather+# than only in the tape's initial shell.+set -g fish_autosuggestion_enabled 0starship init fish | source# Pre-load wt completions (VHS doesn't trigger lazy loading reliably)source ~/.config/fish/completions/wt.fish 2>/dev/null@@ -781,9 +878,15 @@ if echo "$input" | grep -qi "summary"; thenelse# Commit message generationsleep 0.5- echo "feat: add user settings module"- echo ""- echo "Add placeholder module for user profile settings."+ if echo "$input" | grep -q "test_add"; then+ echo "test: expand add coverage"+ echo ""+ echo "Add another test case for the add function."+ else+ echo "feat: add user settings module"+ echo ""+ echo "Add placeholder module for user profile settings."+ fifi""")llm_mock.chmod(0o755)@@ -983,7 +1086,8 @@ def check_ffmpeg_libass():if not shutil.which("ffmpeg"):raise SystemExit("Missing dependency: ffmpeg\n"- "Install with: HOMEBREW_NO_INSTALL_FROM_API=1 brew install --build-from-source ffmpeg"+ "Install with: brew install ffmpeg-full\n"+ 'Then add it to PATH: export PATH="$(brew --prefix ffmpeg-full)/bin:$PATH"')result = subprocess.run(["ffmpeg", "-filters"],@@ -993,7 +1097,8 @@ def check_ffmpeg_libass():if " ass " not in result.stdout:raise SystemExit("ffmpeg missing libass support (required for keystroke overlay).\n"- "Install with: HOMEBREW_NO_INSTALL_FROM_API=1 brew install --build-from-source ffmpeg"+ "Install with: brew install ffmpeg-full\n"+ 'Then add it to PATH: export PATH="$(brew --prefix ffmpeg-full)/bin:$PATH"')@@ -1055,7 +1160,11 @@ def record_text(tape_rendered = (demo_env.out_dir / ".text-rendered.tape").resolve()tape_rendered.write_text(rendered)try:- run([vhs_binary, str(tape_rendered)], check=True)+ run(+ [vhs_binary, str(tape_rendered)],+ check=True,+ env=_isolated_claude_env(demo_env.home),+ )finally:tape_rendered.unlink(missing_ok=True)@@ -1165,11 +1274,9 @@ def record_snapshot(raise RuntimeError(f"No snapshotable commands found in {tape_path.name}")# Build environment matching the GIF demos- env = os.environ.copy()+ env = _isolated_claude_env(demo_env.home)env.update({- "HOME": str(demo_env.home),- "XDG_CONFIG_HOME": str(demo_env.home / ".config"),"PATH": f"{repo_root / 'target' / 'debug'}:{demo_env.home / '.local' / 'bin'}:{os.environ.get('PATH', '')}","TERM": "xterm-256color","LANG": "en_US.UTF-8",@@ -1256,24 +1363,27 @@ def build_tape_replacements(demo_env: DemoEnv, repo_root: Path) -> dict:"STARSHIP_CONFIG": starship_config,"TARGET_DEBUG": (repo_root / "target" / "debug").resolve(),"ANTHROPIC_API_KEY": os.environ.get("ANTHROPIC_API_KEY", ""),- "GIT_PAGER": "", # Overridden per-theme in record_all_themes+ "CLAUDE_CODE_OAUTH_TOKEN": os.environ.get("CLAUDE_CODE_OAUTH_TOKEN", ""),+ "GIT_PAGER": "", # Overridden by record_theme}-def record_all_themes(+def record_theme(demo_env: "DemoEnv",tape_template: Path,- output_gifs: dict[str, Path],+ theme_name: str,+ output_gif: Path,repo_root: Path,vhs_binary: str = "vhs",size: DemoSize = None,):- """Record demo GIFs for all themes.+ """Record one demo GIF in a prepared environment.Args:demo_env: Demo environment with repo and home pathstape_template: Path to the .tape template file- output_gifs: Dict of theme_name -> output GIF path (e.g., {"light": path, "dark": path})+ theme_name: Name of the VHS theme to use+ output_gif: Output GIF pathrepo_root: Path to worktrunk repo root (for target/debug)vhs_binary: VHS binary to use (default "vhs", can be path to custom build)size: Canvas and font size (default SIZE_DOCS)@@ -1282,29 +1392,26 @@ def record_all_themes(size = SIZE_DOCStape_rendered = demo_env.out_dir / ".rendered.tape"- base_replacements = build_tape_replacements(demo_env, repo_root)-- for theme_name, output_gif in output_gifs.items():- theme = THEMES[theme_name]- delta_flags = "delta --paging=never"- if theme_name == "light":- delta_flags += " --light"- replacements = {- **base_replacements,- "OUTPUT_GIF": output_gif,- "THEME": format_theme_for_vhs(theme),- "WIDTH": size.width,- "HEIGHT": size.height,- "FONTSIZE": size.fontsize,- "GIT_PAGER": delta_flags,- }+ theme = THEMES[theme_name]+ delta_flags = "delta --paging=never"+ if theme_name == "light":+ delta_flags += " --light"+ replacements = {+ **build_tape_replacements(demo_env, repo_root),+ "OUTPUT_GIF": output_gif,+ "THEME": format_theme_for_vhs(theme),+ "WIDTH": size.width,+ "HEIGHT": size.height,+ "FONTSIZE": size.fontsize,+ "GIT_PAGER": delta_flags,+ }- rendered = render_tape(tape_template, replacements, repo_root)- if not rendered:- continue+ rendered = render_tape(tape_template, replacements, repo_root)+ if not rendered:+ return- tape_rendered.write_text(rendered)- print(f"\nRecording {theme_name} GIF...")- record_vhs(tape_rendered, vhs_binary, expected_output=output_gif)- tape_rendered.unlink(missing_ok=True)- print(f"GIF saved to {output_gif}")+ tape_rendered.write_text(rendered)+ print(f"\nRecording {theme_name} GIF...")+ record_vhs(tape_rendered, vhs_binary, expected_output=output_gif)+ tape_rendered.unlink(missing_ok=True)+ print(f"GIF saved to {output_gif}")diff --git a/docs/demos/shared/validation.py b/docs/demos/shared/validation.pyindex 5bcb56937..d9f49455d 100644--- a/docs/demos/shared/validation.py+++ b/docs/demos/shared/validation.py@@ -6,10 +6,10 @@ multiplexers. Instead, we extract frames from the GIF and use OCR to verifyexpected content appears.Checkpoints specify a frame range rather than a single frame. The validator-scans frames within the range (sampling every N frames) and passes the-checkpoint if ANY frame in the range matches all expected patterns while-containing none of the forbidden patterns. This makes validation resilient-to timing shifts from UI changes.+scans frames within the range (sampling every N frames). Expected patterns must+share at least one sampled frame, while forbidden patterns must be absent from+every sampled frame. This makes validation resilient to timing shifts from UI+changes without allowing transient errors.Usage:from shared.validation import validate_tui_demo, TUI_CHECKPOINTS@@ -42,9 +42,36 @@ class Checkpoint:# Checkpoint definitions per TUI demo.# Ranges are calibrated from actual GIF content at 30fps.# Expected patterns must ALL be present (case-insensitive) in at least one-# frame within the range. Forbidden patterns must ALL be absent.+# frame within the range. Every forbidden pattern must be absent from every+# sampled frame.TUI_CHECKPOINTS: dict[str, list[Checkpoint]] = {+ "wt-switch": [+ Checkpoint(+ start=360,+ end=455,+ expected=["Claude Code", "Opus", "acme.dashboard"],+ forbidden=[+ "Not logged in",+ "Unknown command",+ "Fable 5 is now",+ "Tackle your toughest",+ ],+ ),+ ],+ "wt-statusline": [+ Checkpoint(+ start=280,+ end=410,+ expected=["Claude Code", "Opus", "acme.alpha"],+ forbidden=[+ "Not logged in",+ "Unknown command",+ "Fable 5 is now",+ "Tackle your toughest",+ ],+ ),+ ],"wt-zellij-omnibus": [# Claude UI visible on TAB 1 (api) — shows model name and task.# Range covers the window where Claude's UI is rendered and stable.@@ -52,9 +79,43 @@ TUI_CHECKPOINTS: dict[str, list[Checkpoint]] = {# layout shifts across versions — task text may wrap or truncate.Checkpoint(start=150,- end=350,+ end=450,expected=["Opus", "acme"],- forbidden=["command not found", "Unknown command"],+ forbidden=[+ "command not found",+ "Unknown command",+ "Not logged in",+ "Fable 5 is now",+ "Tackle your toughest",+ ],+ ),+ # Claude UI visible on TAB 2 (billing), without referral or model ads.+ Checkpoint(+ start=550,+ end=700,+ expected=["Opus", "billing"],+ forbidden=[+ "Not logged in",+ "Share Claude Code",+ "Fable 5 is now",+ "Tackle your toughest",+ ],+ ),+ # The API agent adds a test. Commit generation should describe that+ # diff rather than replaying the feature-tab fixture's message.+ Checkpoint(+ start=1400,+ end=1750,+ expected=["expand", "coverage"],+ forbidden=["user settings module", "script -q"],+ ),+ # The feature push uses a local demo remote internally, but its+ # disposable filesystem path must never appear in the recording.+ Checkpoint(+ start=1000,+ end=1350,+ expected=["Removing feature"],+ forbidden=["/var/folders/", "wt-demo-"],),# Near end — wt list --full showing all worktrees.# "billing" omitted: depends on timing of when the branch appears@@ -63,7 +124,14 @@ TUI_CHECKPOINTS: dict[str, list[Checkpoint]] = {start=1650,end=1850,expected=["Branch", "main"],- forbidden=["CONFLICT", "error:", "failed"],+ forbidden=[+ "CONFLICT",+ "error:",+ "failed",+ "cargo test 2>&1",+ "cargo test -- --list",+ "script -q",+ ],),],}@@ -101,7 +169,7 @@ def extract_frames("-loglevel", "error","-i", str(gif_path),"-vf", f"select='{select_expr}'",- "-vsync", "vfr",+ "-fps_mode", "vfr",str(pattern),],capture_output=True,@@ -165,8 +233,9 @@ def validate_checkpoint() -> tuple[bool, str]:"""Validate a checkpoint by scanning its frame range.- Extracts all sampled frames in one ffmpeg call, then OCRs each- sequentially until one matches (early return on success).+ Extracts all sampled frames in one ffmpeg call, then OCRs each. Expected+ patterns must share a frame; forbidden patterns must be absent throughout+ the range.Returns (passed, detail_message)."""@@ -179,6 +248,7 @@ def validate_checkpoint(best_errors: list[str] = []frames_checked = 0+ matched_frame: int | None = Nonefor frame in frame_numbers:frame_path = frame_paths.get(frame)@@ -190,15 +260,22 @@ def validate_checkpoint(if not text:continue- passed, errors = _check_patterns(text, checkpoint.expected, checkpoint.forbidden)- if passed:- return True, f"matched at frame {frame} ({frames_checked} checked)"+ text_lower = text.lower()+ for pattern in checkpoint.forbidden:+ if pattern.lower() in text_lower:+ return False, f"forbidden '{pattern}' present at frame {frame}"++ passed, errors = _check_patterns(text, checkpoint.expected, [])+ if passed and matched_frame is None:+ matched_frame = frameif not best_errors or len(errors) < len(best_errors):best_errors = errorslabel = f"frames {checkpoint.start}-{checkpoint.end}"if not frames_checked:return False, f"no readable frames in {label}"+ if matched_frame is not None:+ return True, f"matched at frame {matched_frame} ({frames_checked} checked)"return False, f"no match in {label} ({frames_checked} checked): {'; '.join(best_errors)}"diff --git a/docs/demos/tapes/wt-statusline.tape b/docs/demos/tapes/wt-statusline.tapeindex c1267e3ab..d419f9c2e 100644--- a/docs/demos/tapes/wt-statusline.tape+++ b/docs/demos/tapes/wt-statusline.tape@@ -5,11 +5,8 @@ Output "{{OUTPUT_GIF}}"Source docs/demos/tapes/shared-commands.tapeEnv ANTHROPIC_API_KEY "{{ANTHROPIC_API_KEY}}"+Env CLAUDE_CODE_OAUTH_TOKEN "{{CLAUDE_CODE_OAUTH_TOKEN}}"-# Pre-install marketplace plugin before recording-Type "claude plugin marketplace add anthropics/claude-plugins-official"-Enter-Sleep 5sType "clear"EnterSleep 1sdiff --git a/docs/demos/tapes/wt-switch.tape b/docs/demos/tapes/wt-switch.tapeindex 07108aa60..ff3f60c7c 100644--- a/docs/demos/tapes/wt-switch.tape+++ b/docs/demos/tapes/wt-switch.tape@@ -5,11 +5,8 @@ Output "{{OUTPUT_GIF}}"Source docs/demos/tapes/shared-commands.tapeEnv ANTHROPIC_API_KEY "{{ANTHROPIC_API_KEY}}"+Env CLAUDE_CODE_OAUTH_TOKEN "{{CLAUDE_CODE_OAUTH_TOKEN}}"-# Pre-install marketplace plugin before recording-Type "claude plugin marketplace add anthropics/claude-plugins-official"-Enter-Sleep 5sType "clear"EnterSleep 1sdiff --git a/docs/demos/tapes/wt-zellij-omnibus.tape b/docs/demos/tapes/wt-zellij-omnibus.tapeindex 76951c324..cf4229a23 100644--- a/docs/demos/tapes/wt-zellij-omnibus.tape+++ b/docs/demos/tapes/wt-zellij-omnibus.tape@@ -33,11 +33,8 @@ Require zellijSource docs/demos/tapes/shared-commands.tapeEnv ANTHROPIC_API_KEY "{{ANTHROPIC_API_KEY}}"+Env CLAUDE_CODE_OAUTH_TOKEN "{{CLAUDE_CODE_OAUTH_TOKEN}}"-# Pre-install marketplace plugin before recording-Type "claude plugin marketplace add anthropics/claude-plugins-official"-Enter-Sleep 10s# Start Zellij before showingType "zellij"Enter@@ -69,9 +66,9 @@ Sleep 1sEnterSleep 1.5s-# Launch Claude agent on api (simple task that completes during demo)-# Note: lib.rs has an add() function, so this will definitely produce changes-Type "claude 'Add a test for the add function'"+# Launch Claude agent on api (one edit that completes during the demo).+# Skip test-running here; the merge's pre-merge hook demonstrates the tests.+Type "claude 'Add one test for the add function in src/lib.rs. Do not run commands or tests.'"EnterSleep 5.5s@@ -88,7 +85,7 @@ Sleep 2sType "ws"Type "l"Sleep 200ms-Type " billing -- 'Format billing amounts with currency symbols'"+Type " billing -- 'Make one small currency-formatting edit in src/lib.rs. Do not run commands or tests.'"Sleep 500msEnterSleep 6s@@ -118,8 +115,16 @@ Sleep 4s# Push to origin (feature branch is now ready)Type "git push -u origin feature"+Sleep 500ms+HideEnterSleep 2s+# The demo remote is a local bare repository. Clear its temporary filesystem+# path before resuming the visible recording.+Type "clear"+Enter+Sleep 300ms+Show# wt remove - done with feature, clean upType "wt remove"@@ -132,11 +137,16 @@ EnterSleep 3.5s# ==== Back to TAB 1: Merge Claude's completed work ====-# Agent finished - open new pane to show changes and merge+# Agent finished - open new pane to show changes and merge. Hide the tab+# transition while clearing the agent transcript so background tool output+# does not compete visually with the diff and merge.+HideCtrl+SpaceSleep 200msType "t1"Sleep 2s+Ctrl+l+Sleep 500ms# Open new pane for git diff and merge (like original zellij demo)# Use session manager (Ctrl+Space → pane mode → new) since Ctrl+n is@@ -145,6 +155,7 @@ Ctrl+SpaceSleep 200msType "on"Sleep 1.2s+Show# Show what Claude changedType "git diff"@@ -161,16 +172,23 @@ Sleep 11s# ==== Cycle through all tabs to show parallel work ====# TAB 2: billing agent working+HideCtrl+SpaceSleep 200msType "t2"+Sleep 1s+Ctrl+l+Sleep 500ms+ShowSleep 1.5s# TAB 3: show final state with wt list --full+HideCtrl+SpaceSleep 200msType "t3"Sleep 1s+Show# Show comprehensive list of all worktrees (post-merge state)Type "wt list --full"