Skip to content

Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows

Refactor demo infrastructure: extract shared library and add wt select demo

Maximilian Roosdeac232f5526
diff --git a/demos/lib.py b/demos/lib.py
new file mode 100644
index 000000000..4a5b7a72f
--- /dev/null
+++ b/demos/lib.py
@@ -0,0 +1,85 @@
+"""Shared infrastructure for demo recording scripts."""
+
+import os
+import subprocess
+from dataclasses import dataclass
+from pathlib import Path
+
+REAL_HOME = Path.home()
+
+
+@dataclass
+class DemoEnv:
+ """Isolated demo environment with its own repo and home directory."""
+
+ name: str
+ out_dir: Path
+ repo_name: str = "worktrunk"
+
+ @property
+ def root(self) -> Path:
+ return self.out_dir / f".demo-{self.name}"
+
+ @property
+ def home(self) -> Path:
+ return self.root
+
+ @property
+ def work_base(self) -> Path:
+ return self.home / "w"
+
+ @property
+ def repo(self) -> Path:
+ return self.work_base / self.repo_name
+
+ @property
+ def bare_remote(self) -> Path:
+ return self.root / "remote.git"
+
+
+def run(cmd, cwd=None, env=None, check=True, capture=False):
+ """Run a command."""
+ result = subprocess.run(
+ cmd, cwd=cwd, env=env, check=check,
+ capture_output=capture, text=True
+ )
+ return result.stdout if capture else None
+
+
+def git(args, cwd=None, env=None):
+ """Run git command."""
+ run(["git"] + args, cwd=cwd, env=env)
+
+
+def render_tape(template_path: Path, output_path: Path, replacements: dict) -> bool:
+ """Render a VHS tape template with variable substitutions.
+
+ Args:
+ template_path: Path to the .tape template file
+ output_path: Path to write the rendered .tape file
+ replacements: Dict of {{VAR}} -> value replacements
+
+ Returns:
+ True if successful, False if template doesn't exist
+ """
+ if not template_path.exists():
+ print(f"Warning: {template_path} not found, skipping VHS recording")
+ return False
+
+ template = template_path.read_text()
+ rendered = template
+ for key, value in replacements.items():
+ rendered = rendered.replace(f"{{{{{key}}}}}", str(value))
+ output_path.write_text(rendered)
+ return True
+
+
+def record_vhs(tape_path: Path, vhs_binary: str = "vhs"):
+ """Record a demo GIF using VHS."""
+ run([vhs_binary, str(tape_path)], check=True)
+
+
+def build_wt(repo_root: Path):
+ """Build the wt binary."""
+ print("Building wt binary...")
+ run(["cargo", "build", "--quiet"], cwd=repo_root)
diff --git a/dev/wt-demo-build b/demos/wt-demo/build
similarity index 85%
rename from dev/wt-demo-build
rename to demos/wt-demo/build
index 9b6e69341..03d28583e 100755
--- a/dev/wt-demo-build
+++ b/demos/wt-demo/build
@@ -5,47 +5,24 @@ import os
import re
import shutil
import subprocess
+import sys
from datetime import datetime, timedelta
from pathlib import Path
+# Add demos/ to path for shared library
SCRIPT_DIR = Path(__file__).parent
-REPO_ROOT = SCRIPT_DIR.parent
-DEMO_DIR = SCRIPT_DIR / "wt-demo"
-FIXTURES_DIR = DEMO_DIR / "fixtures"
-OUT_DIR = DEMO_DIR / "out"
-TAPE_TEMPLATE = DEMO_DIR / "demo.tape"
+DEMOS_DIR = SCRIPT_DIR.parent
+sys.path.insert(0, str(DEMOS_DIR))
+
+from lib import DemoEnv, run, git, render_tape, record_vhs, build_wt, REAL_HOME
+
+REPO_ROOT = DEMOS_DIR.parent
+FIXTURES_DIR = SCRIPT_DIR / "fixtures"
+OUT_DIR = SCRIPT_DIR / "out"
+TAPE_TEMPLATE = SCRIPT_DIR / "demo.tape"
TAPE_RENDERED = OUT_DIR / ".rendered.tape"
STARSHIP_CONFIG = OUT_DIR / "starship.toml"
OUTPUT_GIF = OUT_DIR / "wt-demo.gif"
-LOG = OUT_DIR / "record.log"
-
-REAL_HOME = Path.home()
-
-
-class DemoEnv:
- """Isolated demo environment with its own repo and home directory."""
-
- def __init__(self, name: str):
- self.name = name
- self.root = OUT_DIR / f".demo-{name}"
- self.home = self.root
- self.work_base = self.home / "w"
- self.repo = self.work_base / "acme"
- self.bare_remote = self.root / "remote.git"
-
-
-def run(cmd, cwd=None, env=None, check=True, capture=False):
- """Run a command."""
- result = subprocess.run(
- cmd, cwd=cwd, env=env, check=check,
- capture_output=capture, text=True
- )
- return result.stdout if capture else None
-
-
-def git(args, cwd=None, env=None):
- """Run git command."""
- run(["git"] + args, cwd=cwd, env=env)
def commit_dated(repo, message, offset):
@@ -128,7 +105,7 @@ def prepare_repo(env: DemoEnv):
gh_mock.chmod(0o755)
# Build wt binary
- run(["cargo", "build", "--quiet"], cwd=REPO_ROOT)
+ build_wt(REPO_ROOT)
# User config
config_dir = env.home / ".config" / "worktrunk"
@@ -248,18 +225,6 @@ def create_branch_hooks(env: DemoEnv):
lib_rs.write_text(lib_rs.read_text() + "// TODO: add division\n")
-def render_tape(env: DemoEnv):
- """Render the VHS tape template with variables."""
- template = TAPE_TEMPLATE.read_text()
- rendered = template.replace("{{DEMO_REPO}}", str(env.repo))
- rendered = rendered.replace("{{DEMO_HOME}}", str(env.home))
- rendered = rendered.replace("{{REAL_HOME}}", str(REAL_HOME))
- rendered = rendered.replace("{{STARSHIP_CONFIG}}", str(STARSHIP_CONFIG))
- rendered = rendered.replace("{{OUTPUT_GIF}}", str(OUTPUT_GIF))
- rendered = rendered.replace("{{TARGET_DEBUG}}", str(REPO_ROOT / "target" / "debug"))
- TAPE_RENDERED.write_text(rendered)
-
-
def record_text(demo_env: DemoEnv):
"""Record text output by running demo commands."""
# Extract commands from tape
@@ -317,12 +282,6 @@ def record_text(demo_env: DemoEnv):
(OUT_DIR / "run.txt").write_text(clean)
-def record_vhs():
- """Record the demo GIF using VHS."""
- with open(LOG, "w") as f:
- run(["vhs", str(TAPE_RENDERED)], check=True)
-
-
def main():
# Check dependencies
for cmd in ["wt", "vhs", "starship"]:
@@ -336,15 +295,23 @@ def main():
# Create separate environments for text and VHS recording
# so they don't interfere with each other (different LLM-generated commits)
- text_env = DemoEnv("text")
- vhs_env = DemoEnv("vhs")
+ text_env = DemoEnv(name="text", out_dir=OUT_DIR, repo_name="acme")
+ vhs_env = DemoEnv(name="vhs", out_dir=OUT_DIR, repo_name="acme")
prepare_repo(text_env)
record_text(text_env)
prepare_repo(vhs_env)
- render_tape(vhs_env)
- record_vhs()
+ replacements = {
+ "DEMO_REPO": vhs_env.repo,
+ "DEMO_HOME": vhs_env.home,
+ "REAL_HOME": REAL_HOME,
+ "STARSHIP_CONFIG": STARSHIP_CONFIG,
+ "OUTPUT_GIF": OUTPUT_GIF,
+ "TARGET_DEBUG": REPO_ROOT / "target" / "debug",
+ }
+ render_tape(TAPE_TEMPLATE, TAPE_RENDERED, replacements)
+ record_vhs(TAPE_RENDERED)
# Cleanup
TAPE_RENDERED.unlink(missing_ok=True)
diff --git a/dev/wt-demo/demo.tape b/demos/wt-demo/demo.tape
similarity index 100%
rename from dev/wt-demo/demo.tape
rename to demos/wt-demo/demo.tape
diff --git a/dev/wt-demo/fixtures/alpha-readme.md b/demos/wt-demo/fixtures/alpha-readme.md
similarity index 100%
rename from dev/wt-demo/fixtures/alpha-readme.md
rename to demos/wt-demo/fixtures/alpha-readme.md
diff --git a/dev/wt-demo/fixtures/gh-mock.sh b/demos/wt-demo/fixtures/gh-mock.sh
similarity index 100%
rename from dev/wt-demo/fixtures/gh-mock.sh
rename to demos/wt-demo/fixtures/gh-mock.sh
diff --git a/dev/wt-demo/fixtures/lib-hooks.rs b/demos/wt-demo/fixtures/lib-hooks.rs
similarity index 100%
rename from dev/wt-demo/fixtures/lib-hooks.rs
rename to demos/wt-demo/fixtures/lib-hooks.rs
diff --git a/dev/wt-demo/fixtures/lib.rs b/demos/wt-demo/fixtures/lib.rs
similarity index 100%
rename from dev/wt-demo/fixtures/lib.rs
rename to demos/wt-demo/fixtures/lib.rs
diff --git a/dev/wt-demo/fixtures/starship.toml b/demos/wt-demo/fixtures/starship.toml
similarity index 100%
rename from dev/wt-demo/fixtures/starship.toml
rename to demos/wt-demo/fixtures/starship.toml
diff --git a/demos/wt-select/CLAUDE.md b/demos/wt-select/CLAUDE.md
new file mode 100644
index 000000000..b3b68b0c5
--- /dev/null
+++ b/demos/wt-select/CLAUDE.md
@@ -0,0 +1,139 @@
+# wt select Demo Recording
+
+## Running the Demo
+
+```bash
+./demos/wt-select/build
+```
+
+Creates:
+- `demos/wt-select/out/wt-select.gif` - Animated demo
+- Demo repo at `demos/wt-select/out/.demo-select/` (gitignored)
+
+## Demo Goals
+
+The demo showcases `wt select` with **realistic variety in all columns**:
+
+```
+Branch Status HEAD± main↕ main…± Remote⇅ CI Age
+@ main ^ ○ now
++ streaming + +54 -5 ● now
++ doctor ↕ ↑1 ↓1 +320 -14 ● 2d
++ llm-templates ! ↕ +8 ↑1 ↓1 +263 -192 3d
+```
+
+Key demonstration points:
+- **CI column**: hollow ○ (branch CI) vs filled ● (PR CI) vs none
+- **HEAD± column**: Large staged diff (+54), small unstaged (+8), none
+- **Status column**: Staged changes (+), unstaged (!), ahead/behind (↕)
+- **main↕ column**: Some branches ahead-only, some ahead-and-behind
+- **main…± column**: Meaningful commit diffs (small to 300+ lines)
+
+## How It Works
+
+**IMPORTANT: The setup is carefully orchestrated. The sequence in `prepare_repo()` matters!**
+
+Uses **actual commits from this repository** cherry-picked onto v0.1.11:
+
+- **Base**: v0.1.11 tag (005db9ad)
+- **Branches via cherry-pick** (simple names, no `/` to avoid path mismatch):
+ - `streaming` - cf667917 (Handle BrokenPipe)
+ - `doctor` - e286e847 (Add --doctor option, +320/-14)
+ - `llm-templates` - 74fe46ff (Enhance squash messages, +263/-192)
+
+Special setup tricks:
+1. **Soft reset** streaming to main creates large staged HEAD± diff
+2. **Manual code additions** add more staged/unstaged changes
+3. **Fake CI cache** with future timestamps prevents expiration during recording
+
+## CI Cache Trick
+
+CI status is cached in git config. To show CI without GitHub access:
+1. Write fake cache entries directly to git config
+2. Use **future timestamp** (1 hour ahead) so cache never expires
+3. VHS recording reads cached status
+
+Without the future timestamp, cache expires during recording → tries to fetch → fails → clears cache.
+
+## Viewing Results
+
+**Do NOT use `open` on the GIF** - that's for the user to do manually.
+
+Inline viewing options:
+- Quick Look: `qlmanage -p dev/wt-select-demo/out/wt-select-demo.gif`
+- iTerm2: `imgcat dev/wt-select-demo/out/wt-select-demo.gif`
+
+## Prerequisites
+
+- `wt` (worktrunk) installed and in PATH
+- Custom `vhs` fork with keystroke overlay (see below)
+- `starship` for prompt
+
+## VHS Fork with Keystroke Overlay
+
+This demo uses a **custom fork of VHS** with keystroke overlay support:
+
+**GitHub:** https://github.com/max-sixty/vhs/tree/keypress-overlay
+
+The fork adds a large keystroke overlay that appears in the center of the screen, showing what keys are being pressed. This is essential for demo GIFs where viewers need to see what's being typed.
+
+To build (from the `demos/wt-select/` directory):
+```bash
+git clone -b keypress-overlay https://github.com/max-sixty/vhs.git vhs-keystrokes
+cd vhs-keystrokes
+go build -o vhs-keystrokes .
+```
+
+The build script looks for the binary at `demos/wt-select/vhs-keystrokes/vhs-keystrokes` by default.
+Override with: `VHS_KEYSTROKES=/path/to/binary ./build`
+
+### Keystroke Timing Calibration
+
+The keystroke overlay timing is controlled by `keystrokeDelayMS` in `ffmpeg.go`:
+
+```go
+keystrokeDelayMS = 500.0 // Delay to sync with terminal rendering
+```
+
+**How this was calibrated:**
+1. The overlay must appear synchronized with when the terminal responds to the keystroke
+2. Initial value (600ms) showed keystrokes appearing ~240ms LATE (after terminal changed)
+3. Frame-by-frame GIF analysis (25fps = 40ms/frame) revealed the exact offset
+4. Reduced to 500ms achieves perfect sync - keystroke and terminal change on same frame
+
+**To recalibrate if needed:**
+```bash
+# Extract frames from GIF
+ffmpeg -i demo.gif -vsync 0 /tmp/gif-frames/frame_%04d.png
+
+# Compare frames to find when terminal changes vs when keystroke appears
+# Adjust keystrokeDelayMS: increase if keystroke appears too early, decrease if too late
+```
+
+## Files
+
+- `build` - Main build script
+- `demo.tape` - VHS tape file with recording script
+- `fixtures/` - Starship config and other fixtures
+- `out/` - Output directory (gitignored)
+
+## Updating Commits
+
+To update the cherry-picked commits, edit `CHERRY_PICKS` in `build`:
+
+```python
+CHERRY_PICKS = {
+ "branch-name": ("commit-hash", days_ago),
+ ...
+}
+```
+
+Test cherry-picks apply cleanly before updating:
+
+```bash
+cd /tmp && git clone --quiet /path/to/worktrunk test-repo
+cd test-repo && git checkout v0.1.11
+git cherry-pick --no-commit <new-commit-hash>
+```
+
+**Note:** Use simple branch names without `/` (e.g., `streaming` not `feature/streaming`) to avoid path mismatch issues in wt list.
diff --git a/demos/wt-select/build b/demos/wt-select/build
new file mode 100755
index 000000000..8faf98793
--- /dev/null
+++ b/demos/wt-select/build
@@ -0,0 +1,451 @@
+#!/usr/bin/env python3
+"""Build script for wt select demo GIF.
+
+Creates a demo environment using cherry-picked commits from this repo,
+records the GIF, and saves output to demos/wt-select/out/.
+
+DEMO GOALS
+==========
+The demo showcases `wt select` with realistic variety in the list columns.
+The target output looks like:
+
+ Branch Status HEAD± main↕ main…± Remote⇅ CI Age
+ @ main ^ ○ now
+ + streaming + +54 -5 ● now
+ + doctor ↕ ↑1 ↓1 +320 -14 ● 2d
+ + llm-templates ! ↕ +8 ↑1 ↓1 +263 -192 3d
+
+Key demonstration points:
+- **CI column variety**: hollow ○ (branch CI) vs filled ● (PR CI) vs none
+- **HEAD± column**: Large staged diff (+54), small unstaged (+8), none
+- **Status column**: Staged changes (+), unstaged (!), ahead/behind (↕)
+- **main↕ column**: Some branches ahead-only, some ahead-and-behind
+- **main…± column**: Meaningful commit diffs ranging from small to 300+ lines
+
+SETUP STRATEGY
+==============
+We start from v0.1.11 (BASE_COMMIT) because:
+1. It's a stable release point
+2. We can cherry-pick real commits for realistic diffs
+3. Many newer commits conflict with v0.1.11 files, so we use manual changes
+
+The setup process:
+1. Clone repo at BASE_COMMIT
+2. Create feature branches with cherry-picked commits (for main…± diffs)
+3. Advance main with MAIN_ADVANCE_COMMIT (so branches are "behind")
+4. Soft-reset streaming to main (creates large staged HEAD± diff)
+5. Add manual code changes (for additional HEAD± variety)
+6. Inject fake CI status cache (with future timestamp to prevent expiration)
+
+CI CACHE TRICK
+==============
+The CI status is cached in git config (`worktrunk.ci.{branch}`). To show CI
+status without actual GitHub/GitLab access, we:
+1. Write fake CI cache entries directly to git config
+2. Use a future timestamp (1 hour ahead) so the cache never expires during recording
+3. VHS recording runs `wt select` which reads the cached CI status
+
+Without the future timestamp, the cache would expire during VHS recording,
+causing `wt list` to try to fetch CI status (which fails without remote),
+and then clear the cache.
+"""
+
+import os
+import shutil
+import subprocess
+import sys
+from datetime import datetime, timedelta
+from pathlib import Path
+
+# Add demos/ to path for shared library
+SCRIPT_DIR = Path(__file__).parent
+DEMOS_DIR = SCRIPT_DIR.parent
+sys.path.insert(0, str(DEMOS_DIR))
+
+from lib import DemoEnv, run, git, render_tape, record_vhs, build_wt, REAL_HOME
+
+REPO_ROOT = DEMOS_DIR.parent
+FIXTURES_DIR = SCRIPT_DIR / "fixtures"
+OUT_DIR = SCRIPT_DIR / "out"
+TAPE_TEMPLATE = SCRIPT_DIR / "demo.tape"
+TAPE_RENDERED = OUT_DIR / ".rendered.tape"
+STARSHIP_CONFIG = OUT_DIR / "starship.toml"
+OUTPUT_GIF = OUT_DIR / "wt-select.gif"
+
+# Custom VHS binary with keystroke overlay
+# Clone and build from: https://github.com/max-sixty/vhs/tree/keypress-overlay
+# Set to "vhs" to use system VHS (no keystroke overlay), or path to custom build
+VHS_BINARY = os.environ.get("VHS_KEYSTROKES", str(SCRIPT_DIR / "vhs-keystrokes" / "vhs-keystrokes"))
+
+# Base point for demo - v0.1.11 release
+BASE_COMMIT = "005db9ad"
+
+# Commit to advance main (makes feature branches "behind" main)
+MAIN_ADVANCE_COMMIT = "50ffe925" # feat(tests): test env vars (+19/-20)
+
+# Branch configuration - real commits to cherry-pick onto branches
+# branch_name: (commit_hash, days_ago)
+# NOTE: Use simple branch names without / to avoid path mismatch issues
+CHERRY_PICKS = {
+ "streaming": ("cf667917", 1), # Handle BrokenPipe when LLM ignores stdin
+ "doctor": ("e286e847", 2), # Add wt config show --doctor option
+ "llm-templates": ("74fe46ff", 3), # Enhance squash message generation
+}
+
+# Working tree changes - applied manually to create material diffs in HEAD± column
+# (cherry-picking fails because many commits touch files that don't exist in v0.1.11)
+
+
+def commit_dated(repo, days_ago):
+ """Amend commit with a date offset in days."""
+ now = datetime.now()
+ delta = timedelta(days=days_ago)
+ date_str = (now - delta).strftime("%Y-%m-%dT%H:%M:%S")
+ env = os.environ.copy()
+ env["GIT_AUTHOR_DATE"] = date_str
+ env["GIT_COMMITTER_DATE"] = date_str
+ git(["-C", str(repo), "commit", "--amend", "--no-edit", "--date", date_str], env=env)
+
+
+def prepare_repo(env: DemoEnv):
+ """Set up the demo repository with variety in all columns.
+
+ This is carefully orchestrated to produce the target output. The sequence matters!
+
+ Step 1: Clone at BASE_COMMIT (v0.1.11)
+ - Stable base point where cherry-picks work
+ - Creates: main at BASE_COMMIT
+
+ Step 2: Create feature branches with cherry-picks (CHERRY_PICKS)
+ - Each branch gets one real commit cherry-picked
+ - Creates main…± diffs (doctor: +320, llm-templates: +263)
+ - Backdates commits for Age column variety
+
+ Step 3: Advance main with MAIN_ADVANCE_COMMIT
+ - Makes feature branches "behind" main (↓1 in main↕)
+ - doctor and llm-templates now show ↑1 ↓1
+
+ Step 4: Add MAIN_ADVANCE_COMMIT to streaming
+ - Makes streaming only "ahead" (not behind)
+ - Prepares for soft reset in next step
+
+ Step 5: Soft reset streaming to main
+ - Moves HEAD back to main, keeping cherry-picked changes as staged
+ - Creates large HEAD± diff (+54 -5) from staged changes
+
+ Step 6: Add manual uncommitted changes
+ - streaming: Additional staged code (+46 lines of error_handling.rs)
+ - llm-templates: Unstaged changes (+8 lines) for ! in Status column
+ - doctor: Left clean for variety
+
+ Step 7: Inject fake CI status cache
+ - main: green hollow ○ (branch CI, passed)
+ - streaming: green filled ● (PR CI, passed)
+ - doctor: blue filled ● (PR CI, running)
+ - Uses future timestamp to prevent expiration during VHS recording
+ """
+ # Clean previous
+ shutil.rmtree(env.root, ignore_errors=True)
+ env.root.mkdir(parents=True)
+ env.work_base.mkdir(parents=True)
+
+ # Clone with enough depth to have the commits we need
+ print(f"Cloning to {env.repo}...")
+ run(["git", "clone", "--quiet", "--depth", "200", str(REPO_ROOT), str(env.repo)])
+
+ # Configure repo
+ git(["-C", str(env.repo), "config", "user.name", "Demo User"])
+ git(["-C", str(env.repo), "config", "user.email", "[email protected]"])
+ git(["-C", str(env.repo), "config", "commit.gpgsign", "false"])
+
+ # Get current branch name and rename to main if needed
+ current_branch = run(["git", "-C", str(env.repo), "rev-parse", "--abbrev-ref", "HEAD"], capture=True).strip()
+ if current_branch != "main":
+ git(["-C", str(env.repo), "branch", "-m", current_branch, "main"])
+
+ # Reset main to base commit (v0.1.12)
+ git(["-C", str(env.repo), "reset", "--hard", BASE_COMMIT])
+
+ # Remove origin to avoid remote comparisons
+ git(["-C", str(env.repo), "remote", "remove", "origin"])
+
+ # User config for wt
+ config_dir = env.home / ".config" / "worktrunk"
+ config_dir.mkdir(parents=True)
+ (config_dir / "config.toml").write_text("""# Demo config
+[worktree]
+base-path = "~/w"
+""")
+
+ # Create feature branches with cherry-picked commits
+ for branch_name, (commit_hash, days_ago) in CHERRY_PICKS.items():
+ create_branch_with_cherry_pick(env, branch_name, commit_hash, days_ago)
+
+ # Advance main so some branches are "behind"
+ advance_main(env)
+
+ # Make streaming also have the advance commit (so it's only ahead, not behind)
+ add_commit_to_branch(env, "streaming", MAIN_ADVANCE_COMMIT)
+
+ # Soft reset streaming to main - all committed work becomes uncommitted
+ # This creates a large HEAD± diff showing real feature work
+ soft_reset_to_main(env, "streaming")
+
+ # Add smaller uncommitted working tree changes to other branches
+ add_uncommitted_changes(env)
+
+ # Add fake CI status for demo
+ add_ci_status(env)
+
+
+def create_branch_with_cherry_pick(env: DemoEnv, branch_name: str, commit_hash: str, days_ago: int):
+ """Create a branch with a cherry-picked commit and worktree."""
+ print(f"Creating branch {branch_name} (cherry-pick {commit_hash})...")
+
+ # Create branch from main (at BASE_COMMIT)
+ git(["-C", str(env.repo), "checkout", "-q", "main"])
+ git(["-C", str(env.repo), "checkout", "-q", "-b", branch_name])
+
+ # Cherry-pick the commit
+ git(["-C", str(env.repo), "cherry-pick", "--no-commit", commit_hash])
+
+ # Get original commit message
+ msg = run(["git", "-C", str(env.repo), "log", "-1", "--format=%s", commit_hash], capture=True).strip()
+ git(["-C", str(env.repo), "commit", "-m", msg])
+
+ # Adjust commit date for realistic history display
+ commit_dated(env.repo, days_ago)
+
+ # Create worktree
+ worktree_path = env.work_base / f"worktrunk.{branch_name}"
+ git(["-C", str(env.repo), "checkout", "-q", "main"])
+ git(["-C", str(env.repo), "worktree", "add", "-q", str(worktree_path), branch_name])
+
+
+def advance_main(env: DemoEnv):
+ """Advance main branch so feature branches are behind."""
+ print(f"Advancing main with {MAIN_ADVANCE_COMMIT}...")
+ git(["-C", str(env.repo), "checkout", "-q", "main"])
+ git(["-C", str(env.repo), "cherry-pick", "--no-commit", MAIN_ADVANCE_COMMIT])
+ msg = run(["git", "-C", str(env.repo), "log", "-1", "--format=%s", MAIN_ADVANCE_COMMIT], capture=True).strip()
+ git(["-C", str(env.repo), "commit", "-m", msg])
+
+
+def add_commit_to_branch(env: DemoEnv, branch_name: str, commit_hash: str):
+ """Add a commit to an existing branch (in its worktree)."""
+ print(f"Adding {commit_hash} to {branch_name}...")
+ worktree_path = env.work_base / f"worktrunk.{branch_name}"
+ git(["-C", str(worktree_path), "cherry-pick", "--no-commit", commit_hash])
+ msg = run(["git", "-C", str(worktree_path), "log", "-1", "--format=%s", commit_hash], capture=True).strip()
+ git(["-C", str(worktree_path), "commit", "-m", msg])
+
+
+def soft_reset_to_main(env: DemoEnv, branch_name: str):
+ """Soft reset a branch to main, keeping all changes as uncommitted.
+
+ This creates a large HEAD± diff showing the full feature work.
+ """
+ print(f"Soft resetting {branch_name} to main...")
+ worktree_path = env.work_base / f"worktrunk.{branch_name}"
+ git(["-C", str(worktree_path), "reset", "--soft", "main"])
+
+
+def add_uncommitted_changes(env: DemoEnv):
+ """Add uncommitted working tree changes manually.
+
+ Creates realistic WIP changes that look like in-progress work.
+ - streaming: Large staged diff (~+50 -30) from soft reset + manual additions
+ - llm-templates: Working on template validation (adds new function)
+ - doctor: Clean (no uncommitted changes) to show variety
+ """
+ # streaming: Add substantial changes to create ~+50 -30 diff
+ # The soft reset gives us +8 -5, so we add more to reach target
+ streaming_path = env.work_base / "worktrunk.streaming"
+
+ # Add new error handling module (~40 lines)
+ error_file = streaming_path / "src" / "error_handling.rs"
+ print("Adding staged changes to streaming...")
+ error_file.write_text('''//! Error handling utilities for pipe operations.
+//!
+//! This module provides robust error handling for cases where
+//! the LLM process ignores stdin or terminates unexpectedly.
+
+use std::io::{self, ErrorKind};
+
+/// Errors that can occur during pipe operations.
+#[derive(Debug)]
+pub enum PipeError {
+ /// The receiving end closed the pipe.
+ BrokenPipe,
+ /// The operation timed out.
+ Timeout { elapsed_ms: u64 },
+ /// An I/O error occurred.
+ Io(io::Error),
+}
+
+impl From<io::Error> for PipeError {
+ fn from(err: io::Error) -> Self {
+ match err.kind() {
+ ErrorKind::BrokenPipe => PipeError::BrokenPipe,
+ ErrorKind::TimedOut => PipeError::Timeout { elapsed_ms: 0 },
+ _ => PipeError::Io(err),
+ }
+ }
+}
+
+impl std::fmt::Display for PipeError {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ match self {
+ PipeError::BrokenPipe => write!(f, "pipe closed by receiver"),
+ PipeError::Timeout { elapsed_ms } => {
+ write!(f, "operation timed out after {}ms", elapsed_ms)
+ }
+ PipeError::Io(e) => write!(f, "I/O error: {}", e),
+ }
+ }
+}
+
+impl std::error::Error for PipeError {}
+
+/// Check if an error indicates the pipe was broken.
+pub fn is_broken_pipe(err: &io::Error) -> bool {
+ err.kind() == ErrorKind::BrokenPipe
+}
+''')
+ # Stage the new file
+ git(["-C", str(streaming_path), "add", "src/error_handling.rs"])
+
+ # llm-templates: Add template validation WIP (+12 lines)
+ templates_path = env.work_base / "worktrunk.llm-templates"
+ llm_file = templates_path / "src" / "llm.rs"
+ if llm_file.exists():
+ print("Adding uncommitted changes to llm-templates...")
+ content = llm_file.read_text()
+ content = content.replace(
+ "use std::io::Write;",
+ """use std::io::Write;
+
+// TODO(wip): Add template validation before rendering
+fn validate_template(template: &str) -> Result<(), String> {
+ if template.is_empty() {
+ return Err("Template cannot be empty".to_string());
+ }
+ Ok(())
+}""",
+ )
+ llm_file.write_text(content)
+
+ # doctor: No changes (leave clean to show variety in demo)
+
+
+def add_ci_status(env: DemoEnv):
+ """Add fake CI status to git config for demo.
+
+ CI status is cached in git config as worktrunk.ci.{branch} with JSON value.
+ The cache uses a future timestamp to prevent expiration during VHS recording.
+ """
+ import json
+ import time
+
+ # Use future timestamp to prevent cache expiration (TTL is 30-60 seconds)
+ # VHS recording can take several minutes, so we set checked_at to 1 hour ahead
+ future_time = int(time.time()) + 3600
+
+ # Get HEAD commits for each branch
+ def get_head(branch):
+ if branch == "main":
+ # main is in the repo directly, not a linked worktree
+ return run(["git", "-C", str(env.repo), "rev-parse", "HEAD"], capture=True).strip()
+ worktree = env.work_base / f"worktrunk.{branch}"
+ return run(["git", "-C", str(worktree), "rev-parse", "HEAD"], capture=True).strip()
+
+ # CI statuses to set:
+ # - main: passed (green ○ hollow - branch CI, not PR)
+ # - streaming: passed (green ● filled - PR CI)
+ # - doctor: running (blue ● filled - PR CI)
+ ci_configs = {
+ "main": {
+ "status": {
+ "ci_status": "passed",
+ "source": "branch", # hollow circle ○
+ "is_stale": False,
+ "url": None
+ },
+ "checked_at": future_time,
+ "head": get_head("main"),
+ },
+ "streaming": {
+ "status": {
+ "ci_status": "passed",
+ "source": "pullrequest", # filled circle ●
+ "is_stale": False,
+ "url": "https://github.com/example/worktrunk/pull/85"
+ },
+ "checked_at": future_time,
+ "head": get_head("streaming"),
+ },
+ "doctor": {
+ "status": {
+ "ci_status": "running",
+ "source": "pullrequest", # filled circle ●
+ "is_stale": False,
+ "url": "https://github.com/example/worktrunk/pull/92"
+ },
+ "checked_at": future_time,
+ "head": get_head("doctor"),
+ },
+ }
+
+ print("Adding CI status cache...")
+ for branch, config in ci_configs.items():
+ config_key = f"worktrunk.ci.{branch}"
+ config_json = json.dumps(config)
+ git(["-C", str(env.repo), "config", config_key, config_json])
+
+
+def main():
+ if not shutil.which("git"):
+ raise SystemExit("Missing dependency: git")
+
+ OUT_DIR.mkdir(parents=True, exist_ok=True)
+
+ # Copy starship config if exists
+ starship_fixture = FIXTURES_DIR / "starship.toml"
+ if starship_fixture.exists():
+ shutil.copy(starship_fixture, STARSHIP_CONFIG)
+
+ # Build wt binary
+ build_wt(REPO_ROOT)
+
+ # Create demo environment
+ demo_env = DemoEnv(name="select", out_dir=OUT_DIR)
+ prepare_repo(demo_env)
+
+ print(f"\nDemo repo created at: {demo_env.repo}")
+ print(f"Worktrees at: {demo_env.work_base}")
+
+ # Record if VHS is available and tape exists
+ vhs_available = Path(VHS_BINARY).exists() if "/" in VHS_BINARY else shutil.which(VHS_BINARY)
+ if vhs_available:
+ replacements = {
+ "DEMO_REPO": demo_env.repo,
+ "DEMO_HOME": demo_env.home,
+ "REAL_HOME": REAL_HOME,
+ "STARSHIP_CONFIG": STARSHIP_CONFIG,
+ "OUTPUT_GIF": OUTPUT_GIF,
+ "TARGET_DEBUG": REPO_ROOT / "target" / "debug",
+ }
+ if render_tape(TAPE_TEMPLATE, TAPE_RENDERED, replacements):
+ print(f"\nRecording GIF with {VHS_BINARY}...")
+ record_vhs(TAPE_RENDERED, VHS_BINARY)
+ TAPE_RENDERED.unlink(missing_ok=True)
+ print(f"GIF saved to {OUTPUT_GIF}")
+ else:
+ print(f"\nSkipping GIF recording ({VHS_BINARY} not available)")
+ print("\nTo test manually:")
+ print(f" cd {demo_env.repo}")
+ print(f" HOME={demo_env.home} wt select")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/demos/wt-select/demo.tape b/demos/wt-select/demo.tape
new file mode 100644
index 000000000..1c2357205
--- /dev/null
+++ b/demos/wt-select/demo.tape
@@ -0,0 +1,79 @@
+Output "{{OUTPUT_GIF}}"
+
+Require wt
+Require git
+
+Set Shell "fish"
+Set FontSize 19
+Set FontFamily "Geist Mono, Berkeley Mono, Fira Code, JetBrains Mono, Menlo, Apple Color Emoji"
+Set Width 1600
+Set Height 800
+Set Theme { "name": "GitHub Light Custom", "black": "#8c959f", "red": "#d73a49", "green": "#22863a", "yellow": "#d29922", "blue": "#0969da", "magenta": "#8250df", "cyan": "#1b7c83", "white": "#8c959f", "brightBlack": "#8c959f", "brightRed": "#cb2431", "brightGreen": "#2ea043", "brightYellow": "#f2cc60", "brightBlue": "#218bff", "brightMagenta": "#a475f9", "brightCyan": "#39c5cf", "brightWhite": "#8c959f", "background": "#f0f2f5", "foreground": "#1f2328", "cursor": "#0969da", "selection": "#ddf4ff" }
+Set Padding 18
+Set LineHeight 1.12
+Set TypingSpeed 28ms
+Set CursorBlink false
+Set Framerate 30
+
+Env DEMO_REPO "{{DEMO_REPO}}"
+Env RUSTUP_HOME "{{REAL_HOME}}/.rustup"
+Env CARGO_HOME "{{REAL_HOME}}/.cargo"
+Env HOME "{{DEMO_HOME}}"
+Env XDG_CONFIG_HOME "{{DEMO_HOME}}/.config"
+Env STARSHIP_CONFIG "{{STARSHIP_CONFIG}}"
+
+Hide
+Type "set -g fish_autosuggestion_enabled 0"
+Enter
+Type "set -gx LANG en_US.UTF-8; set -gx LC_ALL en_US.UTF-8"
+Enter
+Type "set -gx PATH {{TARGET_DEBUG}} $HOME/bin $PATH"
+Enter
+Type "starship init fish | source"
+Enter
+Type "wt config shell init fish | source"
+Enter
+Type "cd $DEMO_REPO"
+Enter
+Type "clear"
+Enter
+Sleep 500ms
+Show
+Set KeyStrokes Show
+Sleep 500ms
+
+# Launch wt select
+Type "wt select"
+Enter
+Sleep 2s
+
+# Navigate to doctor branch (has large main…± diff: +320 -14)
+Down
+Sleep 1s
+Down
+Sleep 1.5s
+
+# Switch to main…± tab (panel 3) to see committed diff from main
+Type "3"
+Sleep 1.5s
+
+# Browse the diff with Ctrl+D (shows scrolling through large diff)
+Ctrl+d
+Sleep 1s
+Ctrl+d
+Sleep 1s
+Ctrl+d
+Sleep 1.5s
+
+# Filter to narrow down and select
+Type "str"
+Sleep 1.5s
+Enter
+Sleep 2s
+
+# Show we're now in the worktree
+Sleep 500ms
+
+Type "exit"
+Enter
+Sleep 500ms
diff --git a/demos/wt-select/fixtures/starship.toml b/demos/wt-select/fixtures/starship.toml
new file mode 100644
index 000000000..312bf404c
--- /dev/null
+++ b/demos/wt-select/fixtures/starship.toml
@@ -0,0 +1,46 @@
+format = "$directory$character"
+palette = "gh_light"
+
+[palettes.gh_light]
+fg = "#1f2328"
+bg = "#ffffff"
+blue = "#0969da"
+yellow = "#d29922"
+green = "#2ea043"
+red = "#d73a49"
+muted = "#57606a"
+
+[directory]
+style = "bold fg:blue"
+truncation_length = 3
+truncate_to_repo = true
+home_symbol = "~"
+
+[git_branch]
+style = "fg:muted"
+symbol = " "
+format = " [$symbol$branch]($style)"
+
+[git_status]
+style = "fg:red"
+format = " [$all_status$ahead_behind]($style)"
+conflicted = "⇕"
+ahead = "⇡"
+behind = "⇣"
+staged = "+"
+modified = "!"
+untracked = "?"
+
+[cmd_duration]
+min_time = 500
+# Keep duration but drop the timer icon to reduce prompt noise.
+format = " [$duration]($style)"
+style = "fg:muted"
+
+[character]
+success_symbol = "[❯](fg:green)"
+error_symbol = "[❯](fg:red)"
+vicmd_symbol = "[❮](fg:blue)"
+
+[time]
+disabled = true
diff --git a/dev/wt-demo/CLAUDE.md b/dev/wt-demo/CLAUDE.md
deleted file mode 100644
index afda41f6d..000000000
--- a/dev/wt-demo/CLAUDE.md
+++ /dev/null
@@ -1,114 +0,0 @@
-# Demo Recording
-
-## Running the Demo
-
-```bash
-./dev/wt-demo-build
-```
-
-Creates:
-- `dev/wt-demo/out/wt-demo.gif` - Animated demo (~2 MB)
-- `dev/wt-demo/out/run.txt` - Text transcript
-- `dev/wt-demo/out/record.log` - Recording log
-
-The script creates a fresh temp repo under `dev/wt-demo/out/.demo-*/`, seeds 4 worktrees + 2 extra branches, shows `wt list`, creates a worktree, edits a file, merges with `wt merge`, then shows `wt list --branches --full`.
-
-## Publishing
-
-Demo GIFs are hosted in [worktrunk-assets](https://github.com/max-sixty/worktrunk-assets) to avoid bloating the main repo.
-
-**Build → Preview → Publish:**
-
-```bash
-# 1. Build the demo (auto-copies to docs/static/assets/ for local preview)
-./dev/wt-demo-build
-
-# 2. Preview inline (zola serve should be running)
-# View at http://127.0.0.1:1111/quickstart/
-
-# 3. Publish when satisfied
-./scripts/publish-assets
-```
-
-The script auto-clones the assets repo if needed.
-
-### How the Paths Connect
-
-**File locations:**
-```
-worktrunk/
-├── dev/wt-demo/out/wt-demo.gif # Build output (gitignored)
-├── docs/static/assets/wt-demo.gif # Local preview (gitignored)
-└── docs/content/quickstart.md # References: /assets/wt-demo.gif
-
-../worktrunk-assets/
-└── demos/wt-demo.gif # Published asset
-```
-
-**Path 1: Local Preview**
-```
-./dev/wt-demo-build
- → creates dev/wt-demo/out/wt-demo.gif
- → copies to docs/static/assets/wt-demo.gif
-
-zola serve (in docs/)
- → serves docs/static/assets/* at /assets/*
- → quickstart.md ![](/assets/wt-demo.gif) resolves to local file
-```
-
-**Path 2: Publish**
-```
-./scripts/publish-assets
- → copies dev/wt-demo/out/wt-demo.gif
- → to ../worktrunk-assets/demos/wt-demo.gif
- → pushes to GitHub
-```
-
-**Path 3: CI Build** (`.github/workflows/build-docs.yaml`)
-```
-curl https://raw.githubusercontent.com/max-sixty/worktrunk-assets/main/demos/wt-demo.gif
- → saves to docs/static/assets/wt-demo.gif
-
-zola build
- → copies docs/static/assets/* to docs/public/assets/*
- → quickstart.md ![](/assets/wt-demo.gif) resolves correctly
-```
-
-**Path 4: README on GitHub.com**
-```
-README.md references:
- https://cdn.jsdelivr.net/gh/max-sixty/worktrunk-assets@main/demos/wt-demo.gif
- → jsDelivr fetches from worktrunk-assets repo
- → GitHub renders the image inline
-```
-
-**Key invariant:** All paths end with the GIF at `/assets/wt-demo.gif` (local, CI) or CDN (README).
-
-## Viewing Results
-
-**Do NOT use `open` on the GIF** - that's for the user to do manually.
-
-Inline viewing options:
-- Quick Look: `qlmanage -p dev/wt-demo/out/wt-demo.gif`
-- iTerm2: `imgcat dev/wt-demo/out/wt-demo.gif`
-
-For Claude Code: read `dev/wt-demo/out/run.txt` to see text output (cannot view GIFs directly).
-
-## Prerequisites
-
-- `wt` (worktrunk) installed and in PATH
-- `vhs` for recording
-- `starship` for prompt
-- `llm` CLI with Claude model configured (for commit message generation)
-- `cargo-nextest` for running tests
-- Python 3
-
-## Files
-
-- `demo.tape` - VHS tape file with recording script
-- `fixtures/` - Extracted content files (README, lib.rs, etc.)
-- `out/` - Output directory (gitignored)
-
-## Defaults
-
-Light theme (GitHub-light-inspired palette), starship prompt, 1600x720 window.
diff --git a/docs/content/select.md b/docs/content/select.md
index 4bd94cba1..fe4b5edfe 100644
--- a/docs/content/select.md
+++ b/docs/content/select.md
@@ -10,6 +10,8 @@ group = "Commands"
Interactive worktree picker with live preview. Navigate worktrees with keyboard shortcuts and press Enter to switch.
+![wt select demo](/assets/wt-select.gif)
+
## Examples
Open the selector:
diff --git a/scripts/publish-assets b/scripts/publish-assets
index 3f8cde929..08150df63 100755
--- a/scripts/publish-assets
+++ b/scripts/publish-assets
@@ -4,9 +4,14 @@ set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(dirname "$SCRIPT_DIR")"
-DEMO_OUT="$REPO_ROOT/dev/wt-demo/out"
ASSETS_REPO="$REPO_ROOT/../worktrunk-assets"
+# Demo sources: name|source_path
+DEMOS=(
+ "wt-demo.gif|$REPO_ROOT/demos/wt-demo/out/wt-demo.gif"
+ "wt-select.gif|$REPO_ROOT/demos/wt-select/out/wt-select.gif"
+)
+
# Clone assets repo if needed
if [[ ! -d "$ASSETS_REPO/.git" ]]; then
if ! command -v gh &>/dev/null; then
@@ -20,13 +25,6 @@ if [[ ! -d "$ASSETS_REPO/.git" ]]; then
fi
fi
-# Check for demo output
-if [[ ! -f "$DEMO_OUT/wt-demo.gif" ]]; then
- echo "Demo GIF not found at $DEMO_OUT/wt-demo.gif"
- echo "Build it first: ./dev/wt-demo-build"
- exit 1
-fi
-
# Update assets repo
cd "$ASSETS_REPO"
if ! git pull --ff-only; then
@@ -34,9 +32,25 @@ if ! git pull --ff-only; then
exit 1
fi
-# Copy new assets
+# Copy available assets
echo "Copying assets..."
-cp "$DEMO_OUT/wt-demo.gif" "$ASSETS_REPO/demos/"
+copied=()
+for entry in "${DEMOS[@]}"; do
+ name="${entry%%|*}"
+ src="${entry#*|}"
+ if [[ -f "$src" ]]; then
+ cp "$src" "$ASSETS_REPO/demos/"
+ copied+=("$name")
+ echo " $name"
+ fi
+done
+
+if [[ ${#copied[@]} -eq 0 ]]; then
+ echo "No demo GIFs found. Build them first:"
+ echo " ./dev/wt-demo-build"
+ echo " ./demos/wt-select/build"
+ exit 1
+fi
# Check for changes
if git diff --quiet demos/; then
@@ -45,6 +59,7 @@ if git diff --quiet demos/; then
fi
# Show what changed
+echo ""
echo "Changes:"
git diff --stat demos/
@@ -54,5 +69,12 @@ git commit -m "Update demo assets"
git push
echo ""
-echo "Published: https://raw.githubusercontent.com/max-sixty/worktrunk-assets/main/demos/wt-demo.gif"
-echo "CDN (~1 min to update): https://cdn.jsdelivr.net/gh/max-sixty/worktrunk-assets@main/demos/wt-demo.gif"
+echo "Published:"
+for name in "${copied[@]}"; do
+ echo " https://raw.githubusercontent.com/max-sixty/worktrunk-assets/main/demos/$name"
+done
+echo ""
+echo "CDN (~1 min to update):"
+for name in "${copied[@]}"; do
+ echo " https://cdn.jsdelivr.net/gh/max-sixty/worktrunk-assets@main/demos/$name"
+done
diff --git a/src/cli.rs b/src/cli.rs
index e0c323224..a8abdd246 100644
--- a/src/cli.rs
+++ b/src/cli.rs
@@ -783,6 +783,8 @@ wt step push
#[command(
after_long_help = r#"Interactive worktree picker with live preview. Navigate worktrees with keyboard shortcuts and press Enter to switch.
+<!-- demo: wt-select.gif -->
+
## Examples
Open the selector:
diff --git a/src/main.rs b/src/main.rs
index fc49579cb..04a5f94d5 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -185,11 +185,12 @@ fn handle_help_page(args: &[String]) {
};
// Get the after_long_help content
- // Transform for web docs: console→bash, status colors
+ // Transform for web docs: console→bash, status colors, demo images
let after_help = sub
.get_after_long_help()
.map(|s| {
let text = s.to_string().replace("```console\n", "```bash\n");
+ let text = expand_demo_placeholders(&text);
colorize_ci_status_for_html(&text)
})
.unwrap_or_default();
@@ -297,6 +298,32 @@ fn colorize_ci_status_for_html(text: &str) -> String {
.replace("`●` gray", "<span style='color:#888'>●</span> gray")
}
+/// Expand demo GIF placeholders for web docs.
+///
+/// Transforms `<!-- demo: filename.gif -->` into `![wt command demo](/assets/filename.gif)`.
+/// The HTML comment is invisible in terminal --help output, but expands to a markdown image
+/// for web docs generated via --help-page.
+fn expand_demo_placeholders(text: &str) -> String {
+ const PREFIX: &str = "<!-- demo: ";
+ const SUFFIX: &str = " -->";
+
+ let mut result = text.to_string();
+ while let Some(start) = result.find(PREFIX) {
+ let after_prefix = start + PREFIX.len();
+ if let Some(end_offset) = result[after_prefix..].find(SUFFIX) {
+ let filename = &result[after_prefix..after_prefix + end_offset];
+ // Extract command name from filename (e.g., "wt-select.gif" -> "wt select")
+ let alt_text = filename.trim_end_matches(".gif").replace('-', " ");
+ let replacement = format!("![{alt_text} demo](/assets/{filename})");
+ let end = after_prefix + end_offset + SUFFIX.len();
+ result.replace_range(start..end, &replacement);
+ } else {
+ break;
+ }
+ }
+ result
+}
+
/// Enhance clap errors with command-specific hints, then exit.
///
/// For `wt switch` missing the branch argument, adds hints about shortcuts.