Skip to content

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

demos: record the interactive picker, and fix the bugs it exposed (#4178)

Maximilian Roos75baa2cd375e
diff --git a/README.md b/README.md
index 4520253af..154b6901e 100644
--- a/README.md
+++ b/README.md
@@ -89,7 +89,7 @@ git branch -d feat</code></pre></td>
- **[Hooks](https://worktrunk.dev/hook/)** — run commands on create, pre-merge, post-merge, etc
- **[LLM commit messages](https://worktrunk.dev/llm-commits/)** — generate commit messages from diffs
- **[Merge workflow](https://worktrunk.dev/merge/)** — squash, rebase, merge, clean up in one command
-- **[Interactive picker](https://worktrunk.dev/switch/#interactive-picker)** — browse worktrees with live diff and log previews
+- **[Interactive picker](https://worktrunk.dev/switch/#interactive-picker)** — browse worktrees with streaming CI status and diff, log, PR and comment previews
- **[Share build caches](https://worktrunk.dev/step/#wt-step-copy-ignored)** — ten worktrees get `target/`, `node_modules/`, etc without building or copying them (on APFS, btrfs, and XFS)
- **[`wt list --full`](https://worktrunk.dev/list/#full-mode)** — [CI status](https://worktrunk.dev/list/#ci-status) and [AI-generated summaries](https://worktrunk.dev/list/#llm-summaries) per branch
- **[PR checkout](https://worktrunk.dev/switch/#pull-requests-and-merge-requests)** — `wt switch pr:123` to jump straight to a PR's branch
diff --git a/dev/config.example.toml b/dev/config.example.toml
index 8cd3eb504..d8a7c0a41 100644
--- a/dev/config.example.toml
+++ b/dev/config.example.toml
@@ -360,7 +360,7 @@
# <!-- DEFAULT_SQUASH_TEMPLATE_START -->
# [commit.generation]
# squash-template = """
-# <task>Write a commit message for the combined effect of these commits.</task>
+# <task>Write a commit message for the change in <diff>, which is everything the squash will record. <commits> lists what it folds in.</task>
#
# <format>
# - Subject line under 50 chars
diff --git a/docs/demos/CLAUDE.md b/docs/demos/CLAUDE.md
index 6d604e333..0af2c6fec 100644
--- a/docs/demos/CLAUDE.md
+++ b/docs/demos/CLAUDE.md
@@ -7,7 +7,8 @@ docs/demos/
build # Unified build script
tapes/ # All VHS tape files (templated)
shared/ # Python library, themes, fixtures
- vhs-keystrokes/ # Custom VHS binary (gitignored, built on demand)
+ tests/ # Tests for the build script and tape conventions
+ .deps/vhs/ # VHS fork clone and binary (gitignored, built on demand)
docs/public/assets/ # Output GIFs (gitignored, shared with fetch-assets)
docs/ # Doc site demos (1600x900; wt-core-mobile is 576x432)
@@ -80,7 +81,11 @@ Checkpoints are defined in `docs/demos/shared/validation.py`. To add validation
1. Identify key frame numbers by examining the GIF (25fps, so frame 75 = 3 seconds; a negative frame counts back from the last, for the state a recording ends in)
2. Define checkpoint patterns in `validation.py` with frame numbers, expected patterns, and forbidden patterns
-`wt-switch`, `wt-statusline`, and `wt-zellij-omnibus` have checkpoints. Other TUI demos are skipped until checkpoints are added.
+`wt-switch`, `wt-switch-picker`, `wt-statusline`, and `wt-zellij-omnibus` have checkpoints. Other TUI demos are skipped until checkpoints are added.
+
+**Measure the window; don't derive it.** A tape's Sleep directives don't fix where its content lands: command execution varies run to run, so the same tape gives GIFs whose frame counts differ by tens of frames. Anchor to the end (a negative `start`) where the content is near it, and prefer a window that stays generous under that drift. OCR each candidate range before committing to it — `extract_frames` plus `ocr_image` over `range(n-500, n, 20)` prints where a pattern actually lives.
+
+**A window is calibrated for one target's terminal size.** One tape records at each target's own size, so a line's on-screen lifetime differs between them: the docs terminal is ~33 rows and the social one ~24. `wt merge`'s generated commit message survives to the end of the docs recording and scrolls off the social one within a second. Set `targets=("docs",)` on a checkpoint that depends on that, rather than widening the window until it catches an 18-frame band in both.
**Prerequisites for TUI validation:** `ffmpeg` and `tesseract` must be installed.
@@ -93,11 +98,10 @@ Checkpoints are defined in `docs/demos/shared/validation.py`. To add validation
**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 regular `ffmpeg` formula omits `libass`; use the keg-only full build instead:
+**Requires ffmpeg with libass** — The keystroke overlay uses ASS subtitles, and Homebrew's regular `ffmpeg` formula is built without libass while holding the linked name, so installing or upgrading `ffmpeg` at any point takes the overlay away. `check_ffmpeg_libass` puts the full build in front of it on PATH for the run when it finds the linked one can't draw subtitles, and otherwise exits with:
```bash
brew install ffmpeg-full
-export PATH="$(brew --prefix ffmpeg-full)/bin:$PATH"
```
External dependencies are downloaded/built automatically on first run:
@@ -156,45 +160,119 @@ git push origin keypress-overlay
**CRITICAL**: Push changes to `origin keypress-overlay`. The directory is gitignored—changes only persist in the fork repo.
-### Keystroke timing calibration
+### Keystroke overlay timing
-The keystroke overlay timing is controlled by `keystrokeDelayMS` in `ffmpeg.go`:
+Each keystroke event is timed by the video's own clock: `Record` writes one
+frame per tick and only while recording, so `recordedMS` in `vhs.go` turns that
+frame count into the timeline the finished GIF plays on, and an event's time is
+where it lands in the output. A `Hide` stretch records no frames and so
+contributes nothing. Measured, a keypress and the frame that answers it are
+within one frame of each other (25fps = 40ms), so nothing is added on top.
-```go
-keystrokeDelayMS = 500.0 // Delay to sync with terminal rendering
-```
+**Keys pressed while the recording is hidden all land on the first visible
+frame**, since a hidden stretch records no frames to separate them. Every docs
+demo types its opening command before `Show` on purpose — the first frame
+carries the whole command, which
+`test_docs_demos_open_on_a_complete_command_before_execution` pins — so that
+command arrives in the overlay in one go, matching the prompt already on
+screen. Anything the overlay should track key by key happens after `Show`.
-**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 check the alignment of a recorded GIF, extract its frames and compare the
+frame where the overlay changes against the frame where the screen answers:
-**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
+ffmpeg -i demo.gif -fps_mode passthrough /tmp/gif-frames/frame_%04d.png
```
+## The mocked forge
+
+`fixtures/gh-mock.sh` answers every `gh` call from a file under
+`$HOME/.local/share/gh-mock` that `write_gh_mock_data` (in `shared/lib.py`)
+writes after the branches exist. Each file's first line is how long the mock
+waits before answering; the rest is the JSON body.
+
+Three things have to hold or the mock is never reached, and each one silently
+empties the CI column rather than failing:
+
+- **A parseable origin.** wt's CI detection parses the remote URL for an
+ owner/repo before it will call `gh` at all, and a bare filesystem path doesn't
+ parse. `prepare_base_repo` sets origin to `DEMO_ORIGIN_URL` and rewrites only
+ *push* to the local bare repo via `url.<bare>.pushInsteadOf` — plain
+ `git remote get-url` applies `insteadOf` but not `pushInsteadOf`, so rewriting
+ fetch too would hand wt the local path back.
+- **`gh --version` and `gh auth status` both exiting 0.** `CiToolsStatus::detect`
+ gates every forge call on them.
+- **`DEMO_PROJECT_ID` matching the URL.** It keys the approvals file, so a URL
+ change without it leaves every project command unapproved.
+
+The per-branch delays in `DEMO_PRS` are what make the CI column *stream*: wt
+runs one `gh pr list` per branch concurrently, so staggered delays land the cells
+one at a time behind a frame that already painted from local git. Keep the
+largest under the tape's post-command sleep — `wt list` renders progressively but
+still can't finish until every call returns.
+
+The PR bodies and comment threads also ride these responses. `detect_github`
+primes the picker's on-disk comments cache from the `gh pr list` payload, so the
+`comments` tab renders with no second call.
+
## wt-switch-picker demo goals (interactive picker)
-The wt-switch-picker demo showcases the interactive picker (`wt switch` without args) with **realistic variety in all columns**:
+The wt-switch-picker demo showcases the interactive picker (`wt switch` without
+args). The list itself is the subject here, so `prepare_picker` gives it sixteen
+worktrees — the shared set plus `PICKER_EXTRA_BRANCHES`, where every other demo
+keeps the shared four — and its table reads like a repo someone works in.
+
+It is also the one demo that records at its own size, `SIZE_DOCS_PICKER`: the
+same 1600x900 canvas as the rest in smaller text, which buys 139x34 instead of
+102x25. At the usual size the columns worth watching — CI status and the branch
+summary — fall off the right edge, and the preview pane is too short to page a
+diff through. `prepare_picker` is also the reason the Summary column renders at
+all: it writes the user config, and the column is gated on an LLM command being
+configured. `fixtures/llm-mock.sh` answers those calls, picking a summary from
+the paths in the diff, so each branch's row is its own sentence.
+
+Variety to preserve across all columns:
| Column | Demonstration |
|--------|---------------|
-| CI | PR/MR number (`#412`) vs bare `#` (branch CI) vs none |
-| HEAD± | Large staged diff (+54), small unstaged (+8), none |
-| Status | Staged changes (+), unstaged (!), ahead/behind (↕) |
+| CI | PR number colored by state (`#4` failing, `#5` changes-requested, `#2` running, `#1` stale head) vs bare `#` (branch CI, passing and failing) vs none |
+| HEAD± | Large unstaged diff (+106 -14), small (+1), none |
+| Status | Staged changes (+), unstaged (!), untracked (?), ahead/behind (↕) |
| main↕ | Some branches ahead-only, some ahead-and-behind |
| main…± | Meaningful merge-base diffstats (small to 300+ lines) |
-Branch setup (from shared infrastructure):
-- **alpha** — Large working tree changes, unpushed commits, PR CI
-- **beta** — Staged changes, behind main, branch CI
-- **hooks** — Staged+unstaged changes, no remote
+Branch setup:
+- **alpha** — Large working tree changes, unpushed commits (so its PR head reads
+ as stale), and the ten-comment thread the `comments` tab pages through
+- **beta** — Staged changes, behind main, PR with CI running
+- **hooks** — Staged+unstaged changes, no remote, so no CI at all
+- **`PICKER_EXTRA_BRANCHES`** — each carries one commit of its own; a branch left
+ on main's tip renders as an empty row *and* borrows main's branch CI, since
+ branch CI is keyed by commit
+
+Two keystroke hazards the tape works around, both of which pick the wrong
+worktree rather than failing:
+
+- **Narrowing the list keeps the cursor's row index**, not the row. A query
+ matching several rows leaves the cursor on whichever row now sits at that
+ index, and clearing the query restores the old index. Either type a query that
+ matches exactly one row, or type it before moving the cursor at all.
+- **The filter matches PR number, title and author too**, not just the branch
+ name and path. Adding a PR to a branch can make a previously unambiguous query
+ match several rows.
+
+## Alt keybindings in tapes
+
+`Alt+p`, `Alt+"8"` and the rest reach the program only because `buildTtyCmd` in
+the VHS fork passes `-t macOptionIsMeta=true` to ttyd. Without it xterm.js hands
+macOS Option to the browser's own composition and the program receives the
+unmodified character — so an `Alt+p` in a tape types a literal `p` into the
+picker's query, with no error anywhere. Verify a modifier reaches the program by
+recording a tape that runs `cat > file`, sending the key, and reading the bytes:
+alt-p is `1b70`, a bare `p` is `70`.
+
+VHS's parser takes a string, `Enter` or `Tab` after `Alt+`, so a digit needs
+quoting: `Alt+"8"`, not `Alt+8` (which fails to parse).
## Light/dark theme variants
diff --git a/docs/demos/build b/docs/demos/build
index f229b009f..1d2fc8b84 100755
--- a/docs/demos/build
+++ b/docs/demos/build
@@ -33,7 +33,10 @@ from shared import ( # noqa: E402
DemoEnv,
DemoSize,
git,
+ commit_dated,
prepare_demo_repo,
+ write_gh_mock_data,
+ DEMO_PROJECT_ID,
claude_auth_available,
setup_claude_code_config,
setup_zellij_config,
@@ -46,6 +49,7 @@ from shared import ( # noqa: E402
recorder_env,
SIZE_DOCS,
SIZE_DOCS_MOBILE,
+ SIZE_DOCS_PICKER,
SIZE_SOCIAL,
record_text,
record_snapshot,
@@ -113,7 +117,6 @@ def _write_user_config(
):
"""Write worktrunk user config and approvals."""
config_dir = env.home / ".config" / "worktrunk"
- project_id = str(env.bare_remote).removesuffix(".git")
# User config (portable settings only)
config_content = ""
@@ -129,7 +132,7 @@ summary = true
(config_dir / "config.toml").write_text(config_content)
# Approvals (machine-local trust state, separate from config)
- approvals_content = f'[projects."{project_id}"]\n'
+ approvals_content = f'[projects."{DEMO_PROJECT_ID}"]\n'
approvals_content += f"approved-commands = {approved_commands!r}\n"
(config_dir / "approvals.toml").write_text(approvals_content)
@@ -144,6 +147,65 @@ def prepare_basic(env: DemoEnv):
prepare_demo_repo(env, REPO_ROOT)
+# Worktrees the picker demo adds on top of the shared set, so its list reads
+# like a repo someone actually works in rather than a fixture — sixteen rows,
+# which is also what fills the taller terminal `SIZE_DOCS_PICKER` records in.
+#
+# Each carries a commit of its own: a branch sitting on main's tip renders as an
+# empty row and, because branch CI is keyed by commit, borrows main's checks —
+# seven of those in a row look like a fixture. `dirty` leaves an uncommitted
+# edit behind so the Status and HEAD± columns have something to say. api, auth
+# and billing are the branches DEMO_PRS gives PRs to.
+PICKER_EXTRA_BRANCHES = [
+ ("api", "src/api.rs", "feat: add the /health endpoint", False),
+ ("auth", "src/auth.rs", "feat: rotate tokens on role change", False),
+ ("billing", "src/billing.rs", "refactor: format currency by locale", False),
+ ("cache", "src/cache.rs", "perf: memoize the config parse", True),
+ ("deps", "Cargo.toml", "chore: bump tokio to 1.41", False),
+ ("docs/site", "docs/config.md", "docs: document every config key", False),
+ ("metrics", "src/metrics.rs", "feat: emit per-request timings", False),
+ ("perf/collect", "src/collect.rs", "perf: batch the rev-parse calls", True),
+ ("release", "CHANGELOG.md", "chore: start the 0.2.0 notes", False),
+ ("retry", "tests/retry.rs", "test: retry the network test", False),
+ ("search", "src/search.rs", "feat: rank results by recency", True),
+ ("ui/theme", "src/theme.rs", "style: soften the dark palette", False),
+]
+
+
+def prepare_picker(env: DemoEnv):
+ """Setup for wt-switch-picker — the shared repo plus a fuller worktree list.
+
+ The picker is the one demo whose subject is the list itself, so it wants
+ more rows than `wt list` output can show legibly. Keeping them here rather
+ than in `prepare_demo_repo` leaves every other demo's table unchanged.
+ """
+ prepare_demo_repo(env, REPO_ROOT)
+
+ # The Summary column renders only where an LLM command is configured, and
+ # `fixtures/llm-mock.sh` is what answers it. No project commands to approve:
+ # nothing in this tape runs a hook.
+ _write_user_config(env, [])
+
+ for branch, rel_path, message, dirty in PICKER_EXTRA_BRANCHES:
+ path = env.work_base / f"acme.{branch.replace('/', '-')}"
+ git(["-C", str(env.repo), "branch", branch, "main"])
+ git(["-C", str(env.repo), "worktree", "add", "-q", str(path), branch])
+
+ target = path / rel_path
+ target.parent.mkdir(parents=True, exist_ok=True)
+ target.write_text(f"// {message}\n")
+ git(["-C", str(path), "add", rel_path])
+ commit_dated(path, message, "1d")
+ git(["-C", str(path), "push", "-q", "-u", "origin", branch])
+
+ if dirty:
+ target.write_text(target.read_text() + "// still working on this\n")
+
+ # api, auth and billing have PRs in DEMO_PRS; rewrite the mock now that
+ # their upstreams exist, so each PR's headRefOid is its pushed tip.
+ write_gh_mock_data(env)
+
+
def prepare_with_hooks(env: DemoEnv, include_deps: bool = False):
"""Standard hooks demo: dev server + cleanup + billing branch."""
dev_cmd = "npm run dev -- --port {{ branch | hash_port }}"
@@ -232,6 +294,59 @@ fi
npm_mock.chmod(0o755)
+# The api branch's commit in the omnibus demo. Long enough that the picker's
+# preview pane pages rather than showing the whole diff at once, and matches the
+# PR title DEMO_PRS gives api.
+API_HEALTH_RS = '''//! The /health endpoint.
+
+use std::time::{Duration, Instant};
+
+/// What `/health` reports to a caller.
+pub struct Health {
+ /// The build this process was compiled from.
+ pub revision: &'static str,
+ /// How long the database took to answer a trivial query.
+ pub database_rtt: Duration,
+}
+
+impl Health {
+ /// Collect the report, timing the database round trip.
+ pub fn collect(revision: &'static str) -> Self {
+ let started = Instant::now();
+ probe_database();
+ Self {
+ revision,
+ database_rtt: started.elapsed(),
+ }
+ }
+
+ /// Whether the process should be taken out of the load balancer.
+ ///
+ /// A slow database is reported but not fatal: the endpoint exists to
+ /// distinguish "degraded" from "gone", and a restart fixes neither.
+ pub fn is_serving(&self) -> bool {
+ self.database_rtt < Duration::from_secs(2)
+ }
+}
+
+/// Issue the trivial query the round-trip time is measured against.
+fn probe_database() {
+ // The real implementation runs `SELECT 1`.
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn a_fast_database_is_serving() {
+ let health = Health::collect("abc1234");
+ assert!(health.is_serving());
+ }
+}
+'''
+
+
def prepare_zellij_omnibus(env: DemoEnv):
"""Setup for wt-zellij-omnibus demo - comprehensive showcase."""
hooks_config = """[post-create]
@@ -245,14 +360,6 @@ url = "http://localhost:{{ branch | hash_port }}"
"""
prepare_demo_repo(env, REPO_ROOT, hooks_config=hooks_config)
- # Clean up branches that might exist from previous runs (billing, feature created during demo)
- origin = env.home / "origin.git"
- for branch in ["billing", "feature"]:
- # Delete from origin if exists (ignore errors if not)
- subprocess.run(
- ["git", "-C", str(origin), "branch", "-D", branch], capture_output=True
- )
-
# Enable git colors for non-TTY environments (VHS)
git(["-C", str(env.repo), "config", "color.ui", "always"])
@@ -297,11 +404,22 @@ url = "http://localhost:{{ branch | hash_port }}"
raise RuntimeError(f"wt {' '.join(args)} failed: {result.stderr}")
run_wt(["switch", "--create", "api"], env.repo)
- git(["-C", str(env.work_base / "acme.api"), "push", "-u", "origin", "api", "-q"])
+ # Give api a commit of its own so the picker's diff pane has something to
+ # page through when TAB 1 filters to it. A freshly created branch sits on
+ # main's tip, and ctrl-d on an empty pane looks like a dropped keystroke.
+ api_path = env.work_base / "acme.api"
+ (api_path / "src" / "health.rs").write_text(API_HEALTH_RS)
+ git(["-C", str(api_path), "add", "src/health.rs"])
+ commit_dated(api_path, "feat: add the /health endpoint", "1d")
+ git(["-C", str(api_path), "push", "-u", "origin", "api", "-q"])
run_wt(["switch", "--create", "auth"], env.repo)
git(["-C", str(env.work_base / "acme.auth"), "push", "-u", "origin", "auth", "-q"])
+ # api and auth have PRs in DEMO_PRS; rewrite the mock now that their
+ # upstreams exist, so each PR's headRefOid is its pushed tip.
+ write_gh_mock_data(env)
+
# Return to main worktree for the demo to start
run_wt(["switch", "main"], env.work_base / "acme.api")
@@ -322,7 +440,7 @@ DOCS_DEMOS = [
("wt-commit.tape", "wt-commit", prepare_merge_demo),
("wt-statusline.tape", "wt-statusline", prepare_switch),
("wt-merge.tape", "wt-merge", prepare_merge_demo),
- ("wt-switch-picker.tape", "wt-switch-picker", prepare_basic),
+ ("wt-switch-picker.tape", "wt-switch-picker", prepare_picker),
("wt-zellij-omnibus.tape", "wt-zellij-omnibus", prepare_zellij_omnibus),
]
@@ -339,7 +457,7 @@ SOCIAL_DEMOS = [
"wt-merge",
partial(prepare_merge_demo, commit_generation=False, staged_changes=False),
),
- ("wt-switch-picker.tape", "wt-switch-picker", prepare_basic),
+ ("wt-switch-picker.tape", "wt-switch-picker", prepare_picker),
("wt-core.tape", "wt-core", prepare_with_hooks),
("wt-zellij-omnibus.tape", "wt-zellij-omnibus", prepare_zellij_omnibus),
]
@@ -348,7 +466,10 @@ TARGETS = {
"docs": {
"demos": DOCS_DEMOS,
"size": SIZE_DOCS,
- "sizes": {"wt-core-mobile": SIZE_DOCS_MOBILE},
+ "sizes": {
+ "wt-core-mobile": SIZE_DOCS_MOBILE,
+ "wt-switch-picker": SIZE_DOCS_PICKER,
+ },
"themes": ["light", "dark"],
},
"social": {
@@ -372,10 +493,16 @@ def record_demo(
themes: list[str],
demo_size: DemoSize,
vhs_binary: str,
+ target: str,
text_mode: bool = False,
snapshot_mode: bool = False,
) -> float:
- """Record a single demo. Returns elapsed seconds."""
+ """Record a single demo. Returns elapsed seconds.
+
+ `target` selects which checkpoints validate the result: a window calibrated
+ against one target's terminal size doesn't hold in the other (see
+ `Checkpoint.targets`).
+ """
t0 = time.monotonic()
tape_path = TAPES_DIR / tape_file
if not tape_path.exists():
@@ -424,7 +551,9 @@ def record_demo(
if output_name in TUI_CHECKPOINTS:
validation_failures = {}
for theme, gif_path in output_gifs.items():
- success, output = validate_tui_demo_verbose(output_name, gif_path)
+ success, output = validate_tui_demo_verbose(
+ output_name, gif_path, target
+ )
if not success:
validation_failures[theme] = output
@@ -665,6 +794,7 @@ def build_target(target: str, args, vhs_binary: str) -> list[str]:
themes,
demo_sizes.get(output_name, demo_size),
vhs_binary,
+ target,
args.text,
args.snapshot,
)
diff --git a/docs/demos/shared/__init__.py b/docs/demos/shared/__init__.py
index 6b423b63f..cdcdfc768 100644
--- a/docs/demos/shared/__init__.py
+++ b/docs/demos/shared/__init__.py
@@ -9,6 +9,7 @@ from .lib import (
SIZE_SOCIAL,
SIZE_DOCS,
SIZE_DOCS_MOBILE,
+ SIZE_DOCS_PICKER,
run,
git,
render_tape,
@@ -22,6 +23,8 @@ from .lib import (
setup_fish_config,
setup_mock_clis,
prepare_demo_repo,
+ write_gh_mock_data,
+ DEMO_PROJECT_ID,
# Demo recording infrastructure
check_dependencies,
check_ffmpeg_libass,
@@ -49,6 +52,7 @@ __all__ = [
"SIZE_SOCIAL",
"SIZE_DOCS",
"SIZE_DOCS_MOBILE",
+ "SIZE_DOCS_PICKER",
"run",
"git",
"render_tape",
@@ -62,6 +66,8 @@ __all__ = [
"setup_fish_config",
"setup_mock_clis",
"prepare_demo_repo",
+ "write_gh_mock_data",
+ "DEMO_PROJECT_ID",
"THEMES",
"format_theme_for_vhs",
# Demo recording infrastructure
diff --git a/docs/demos/shared/fixtures/gh-mock.sh b/docs/demos/shared/fixtures/gh-mock.sh
index 5b7ecdfad..763c7d629 100755
--- a/docs/demos/shared/fixtures/gh-mock.sh
+++ b/docs/demos/shared/fixtures/gh-mock.sh
@@ -1,49 +1,72 @@
#!/usr/bin/env bash
-# Mock gh CLI for demos - returns varied CI status per branch
+# Mock gh CLI for demos.
+#
+# Every answer is a file under $HOME/.local/share/gh-mock, written by
+# `write_gh_mock_data` in shared/lib.py: the first line is how long to wait
+# before answering, the rest is the JSON body. The wait is what makes the CI
+# column stream — each branch's `gh pr list` answers at a different moment, so
+# `wt list --full` and the switch picker fill their CI cells one at a time
+# instead of all at once.
+#
+# A request with no file answers with an empty array, which wt reads as "no PR"
+# for `pr list` and "no checks" for the check-runs API.
-if [[ "$1" == "auth" && "$2" == "status" ]]; then
- exit 0
-fi
+set -u
+MOCK_DIR="${HOME}/.local/share/gh-mock"
-if [[ "$1" == "pr" && "$2" == "list" ]]; then
- branch=""
- for arg in "$@"; do
- if [[ "$prev" == "--head" ]]; then
- branch="$arg"
+# Wait out the response file's first line, then emit the rest.
+respond() {
+ local file="$MOCK_DIR/$1"
+ if [[ ! -f "$file" ]]; then
+ echo '[]'
+ exit 0
fi
- prev="$arg"
- done
-
- case "$branch" in
- main)
- echo '[{"state":"MERGED","headRefOid":"main123","mergeStateStatus":"CLEAN","statusCheckRollup":[{"status":"COMPLETED","conclusion":"SUCCESS"}],"url":"https://github.com/acme/demo/pull/100"}]'
- ;;
- alpha)
- echo '[{"state":"OPEN","headRefOid":"abc123","mergeStateStatus":"CLEAN","statusCheckRollup":[{"status":"COMPLETED","conclusion":"SUCCESS"}],"url":"https://github.com/acme/demo/pull/1"}]'
- ;;
- beta)
- echo '[{"state":"OPEN","headRefOid":"def456","mergeStateStatus":"CLEAN","statusCheckRollup":[{"status":"IN_PROGRESS","conclusion":null}],"url":"https://github.com/acme/demo/pull/2"}]'
- ;;
- hooks)
- # hooks has no remote, so no PR
- echo '[]'
- ;;
- billing|api)
- echo '[{"state":"OPEN","headRefOid":"jkl012","mergeStateStatus":"CLEAN","statusCheckRollup":[{"status":"COMPLETED","conclusion":"SUCCESS"}],"url":"https://github.com/acme/demo/pull/4"}]'
- ;;
- *)
- echo '[]'
- ;;
- esac
- exit 0
+ {
+ read -r delay
+ sleep "$delay"
+ cat
+ } <"$file"
+ exit 0
+}
+
+# Branch names become filenames; `/` is the only character the demo's branches
+# use that can't appear in one. `write_gh_mock_data` names the files with the
+# same substitution — the two have to agree.
+sanitize() { printf '%s' "${1//\//_}"; }
+
+# wt gates every forge call on `gh --version` then `gh auth status`
+# (`CiToolsStatus::detect`), so both have to succeed before the responses below
+# are ever asked for.
+if [[ "${1:-}" == "--version" ]]; then
+ echo "gh version 2.63.2 (2024-12-05)"
+ exit 0
+fi
+
+if [[ "${1:-}" == "auth" && "${2:-}" == "status" ]]; then
+ exit 0
+fi
+
+if [[ "${1:-}" == "pr" && "${2:-}" == "list" ]]; then
+ branch=""
+ prev=""
+ for arg in "$@"; do
+ [[ "$prev" == "--head" ]] && branch="$arg"
+ prev="$arg"
+ done
+ respond "head/$(sanitize "$branch")"
+fi
+
+# `gh pr view <n> --json comments` — the picker's `comments` tab when the CI
+# call hasn't primed its cache yet.
+if [[ "${1:-}" == "pr" && "${2:-}" == "view" ]]; then
+ respond "view/${3:-}"
fi
-# gh api for check-runs (branches without PRs, like main)
-# wt calls: gh api repos/.../commits/.../check-runs --jq '.check_runs | map({status, conclusion})'
-# We return the post-jq result directly
-if [[ "$1" == "api" && "$2" == *"check-runs"* ]]; then
- echo '[{"status":"completed","conclusion":"success"}]'
- exit 0
+# `gh api repos/<owner>/<repo>/commits/<sha>/check-runs` — branch CI for a
+# commit with no PR. wt passes --jq, so the file holds the post-jq array.
+if [[ "${1:-}" == "api" && "${2:-}" == */check-runs ]]; then
+ sha="${2#*/commits/}"
+ respond "sha/${sha%/check-runs}"
fi
exit 1
diff --git a/docs/demos/shared/fixtures/llm-mock.sh b/docs/demos/shared/fixtures/llm-mock.sh
new file mode 100755
index 000000000..77128a7c3
--- /dev/null
+++ b/docs/demos/shared/fixtures/llm-mock.sh
@@ -0,0 +1,75 @@
+#!/usr/bin/env bash
+# Mock LLM CLI for demos — the `[commit.generation] command` every demo config
+# points at.
+#
+# wt calls the same command for two jobs and tells them apart only by the
+# prompt it pipes in, so this does the same: a summary prompt says "summary",
+# a commit-message prompt doesn't. Both answers are picked from the paths in
+# the diff, which is what makes each branch's row and each commit its own
+# sentence rather than one canned line repeated down the column.
+#
+# Summaries answer instantly. The forge mock's per-branch delays already carry
+# the "results stream in" story in the CI column, and `wt list` can't finish
+# until every task returns — a slow answer here would just make the demo wait.
+
+set -u
+input=$(cat)
+
+# Matches a path in the diff. The paths come from three places, all of which a
+# branch can be defined in: the shared fixtures in shared/lib.py,
+# `PICKER_EXTRA_BRANCHES`, and `prepare_zellij_omnibus` — which builds its own
+# `api` out of `src/health.rs` where the picker's writes `src/api.rs`. A branch
+# added to any of them wants a line here, or its row falls through to the
+# default and claims to be a README change.
+mentions() { echo "$input" | grep -q "$1"; }
+
+if echo "$input" | grep -qi "summary"; then
+ if mentions "utils\.rs"; then
+ echo "Add utility functions module with string and math helpers"
+ elif mentions "notes\.txt"; then
+ echo "Add TODO notes for caching improvements"
+ elif mentions "api\.rs\|health\.rs"; then
+ echo "Add /health for load-balancer polling"
+ elif mentions "auth\.rs"; then
+ echo "Reissue tokens when a role changes"
+ elif mentions "billing\.rs"; then
+ echo "Format invoice totals per locale"
+ elif mentions "cache\.rs"; then
+ echo "Cache the parsed config between runs"
+ elif mentions "collect\.rs"; then
+ echo "Collect revisions in one batched call"
+ elif mentions "docs/config\.md"; then
+ echo "Document every key in the config file"
+ elif mentions "CHANGELOG\.md"; then
+ echo "Open the 0.2.0 changelog section"
+ elif mentions "metrics\.rs"; then
+ echo "Emit timings for every request"
+ elif mentions "search\.rs"; then
+ echo "Rank search results by recency"
+ elif mentions "theme\.rs"; then
+ echo "Soften the dark palette"
+ elif mentions "tests/retry\.rs"; then
+ echo "Retry the flaky network test"
+ elif mentions "Cargo\.toml"; then
+ echo "Bump tokio to the current minor"
+ elif mentions "multiply\|subtract\|math"; then
+ echo "Add math operations and consolidate tests"
+ elif mentions "User settings"; then
+ echo "Add user settings module placeholder"
+ else
+ echo "Expand README with contributing and license sections"
+ fi
+else
+ # Commit message generation. The pause stands in for the model call the
+ # demo is showing off, so the spinner is on screen long enough to read.
+ sleep 0.5
+ if mentions "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."
+ fi
+fi
diff --git a/docs/demos/shared/lib.py b/docs/demos/shared/lib.py
index 263bc879c..50b310d56 100644
--- a/docs/demos/shared/lib.py
+++ b/docs/demos/shared/lib.py
@@ -10,7 +10,7 @@ import subprocess
import tempfile
import urllib.request
from dataclasses import dataclass
-from datetime import datetime, timedelta
+from datetime import datetime, timedelta, timezone
from pathlib import Path
from .themes import PALETTES, THEMES, format_theme_for_vhs
@@ -25,6 +25,23 @@ _ZELLIJ_PLUGIN_URL = "https://github.com/Cynary/zellij-tab-name/releases/downloa
_VHS_FORK_REPO = "https://github.com/max-sixty/vhs.git"
_VHS_FORK_BRANCH = "keypress-overlay"
+# The demo repo's origin claims a GitHub URL, and `url.<bare>.pushInsteadOf`
+# sends every push to the local bare repo beside it. `git remote get-url origin`
+# reports the URL below, which is what wt's CI detection parses for an
+# owner/repo before it will call `gh` at all — a bare filesystem path doesn't
+# parse, so a path remote leaves the CI column empty and the picker's `pr` and
+# `comments` tabs permanently unavailable. Only push is rewritten: plain
+# `get-url` applies `insteadOf` but not `pushInsteadOf`, so rewriting fetch too
+# would hand wt the local path again. Nothing in the demos fetches from origin
+# (only `wt switch pr:`/`mr:` do, and no tape uses them), and
+# `worktrunk.default-branch` is seeded so default-branch detection never falls
+# through to `git ls-remote` — so no demo command reaches the network.
+DEMO_ORIGIN_URL = "https://github.com/acme/demo.git"
+
+# What `Repository::project_identifier` derives from the URL above. Keys the
+# approvals file, so it must track `DEMO_ORIGIN_URL`.
+DEMO_PROJECT_ID = "github.com/acme/demo"
+
def _detect_platform() -> str:
"""Detect platform for Claude Code binary download."""
@@ -211,6 +228,37 @@ def _ensure_zellij_plugin() -> Path:
return plugin_path
+# A source marker for the newest fork commit the tapes depend on, as
+# (file, substring). Name the latest one: the branch is linear, so a clone that
+# has it has the ones before it too.
+#
+# `ensure_vhs_binary` reuses an existing clone and an existing binary without
+# pulling, so a clone made before that commit keeps building a VHS the tapes
+# have outgrown — one that drops the Alt modifier, turning a tape's `Alt+p`
+# into a literal "p" typed at whatever has focus; one that times the keystroke
+# overlay from the first keypress rather than from the video, which slides
+# every key a fixed distance away from what it did; or one that records a
+# modifier as a keystroke of its own, so `Alt+"8"` reads as a spent ⌥ followed
+# by an unrelated 8. Each records a wrong GIF with no error from VHS, the
+# build, or the recording, which is why this checks rather than trusting the
+# clone.
+_VHS_FORK_MARKER = ("keystroke.go", "heldModifiers")
+
+
+def _require_current_vhs_fork(vhs_dir: Path) -> None:
+ """Fail when the VHS clone predates the fork commit the tapes need."""
+ source_name, marker = _VHS_FORK_MARKER
+ source = vhs_dir / source_name
+ if source.exists() and marker in source.read_text():
+ return
+ raise RuntimeError(
+ f"The VHS fork clone at {vhs_dir} predates the {marker} fix, so a tape's "
+ f"keystroke overlay would not match what the screen does.\n"
+ f"Update and rebuild it:\n"
+ f" git -C {vhs_dir} pull && rm -f {vhs_dir / 'vhs'}"
+ )
+
+
def ensure_vhs_binary() -> Path:
"""Ensure VHS binary is cloned and built, return path.
@@ -221,6 +269,7 @@ def ensure_vhs_binary() -> Path:
vhs_binary = vhs_dir / "vhs"
if vhs_binary.exists():
+ _require_current_vhs_fork(vhs_dir)
return vhs_binary
# Check Go is available
@@ -262,6 +311,7 @@ def ensure_vhs_binary() -> Path:
if result.returncode != 0:
raise RuntimeError(f"VHS built but --version failed: {result.stderr}")
+ _require_current_vhs_fork(vhs_dir)
print("✓ VHS ready")
return vhs_binary
@@ -393,6 +443,285 @@ def build_wt(repo_root: Path):
run(["cargo", "build", "--quiet"], cwd=repo_root)
+# The demo's open PRs on the mocked forge, one row per branch.
+#
+# `delay` is how long that branch's `gh pr list` waits before answering. wt runs
+# one call per branch concurrently, so staggering the delays is what the picker
+# and `wt list --full` show as CI status streaming in: cells land one at a time
+# behind the frame that already painted from local git. Keep the largest under
+# the tape's post-command sleep — `wt list` can't finish until every call
+# returns, even though it renders progressively.
+#
+# `checks` is `statusCheckRollup`; `review` is `reviewDecision` (None for a PR
+# with no reviews). Comment ages are hours before the recording, so the pane's
+# relative times read naturally. A branch absent here has no PR; DEMO_BRANCH_CI
+# below covers branch CI without one.
+DEMO_PRS = [
+ {
+ "number": 1,
+ "branch": "alpha",
+ "title": "Add utility functions module",
+ "body": "Adds `src/utils.rs` with path normalization and project-root "
+ "discovery, plus the string helpers the config loader needs.",
+ "author": "dbenson",
+ "checks": [("COMPLETED", "SUCCESS")],
+ "review": "APPROVED",
+ "delay": 0.3,
+ # Bodies are written for the picker's preview pane, which is about half
+ # the terminal — roughly 65 columns at `SIZE_DOCS_PICKER`. Short
+ # sentences and short code lines keep the wrap from shredding them, and
+ # the thread runs a little past one screen so ctrl-d has somewhere to go.
+ "comments": [
+ (
+ "dbenson",
+ 28,
+ "Opening this for review. The path helpers are lifted out "
+ "of the config loader as-is — no behaviour change intended.",
+ ),
+ (
+ "rmurthy",
+ 26,
+ "`normalize_path` pops `..` without resolving "
+ "symlinks, so it can land somewhere the kernel "
+ "wouldn't. Worth saying so in the doc comment.",
+ ),
+ (
+ "dbenson",
+ 22,
+ "That's the documented difference from "
+ "`fs::canonicalize` — we never touch the "
+ "filesystem, so we can't know. Spelled it out:\n\n"
+ "```rust\n"
+ "/// Purely lexical: `..` pops the\n"
+ "/// previous component without\n"
+ "/// resolving symlinks.\n"
+ "```",
+ ),
+ (
+ "rmurthy",
+ 20,
+ "Reads well. One more: `find_project_root` walks "
+ "all the way to `/` when the path is outside any "
+ "project. That's a lot of `stat` for a miss.",
+ ),
+ (
+ "dbenson",
+ 18,
+ "Measured it: a miss from a nested path is about forty "
+ "`stat` calls here. Fine on a warm cache, less so on a "
+ "network mount.",
+ ),
+ (
+ "rmurthy",
+ 14,
+ "A network mount is exactly where I'd expect it to bite. "
+ "Worth a ceiling — the first directory we can't read is "
+ "as good a one as any.",
+ ),
+ (
+ "dbenson",
+ 6,
+ "Bounded it at the filesystem root, or the first "
+ "directory we can't read. There's a test that "
+ "runs it from `/tmp` now.",
+ ),
+ (
+ "rmurthy",
+ 4,
+ "Last thing and then I'm happy: `join_relative` "
+ "takes `&str` while everything around it takes "
+ "`impl AsRef<Path>`.",
+ ),
+ (
+ "dbenson",
+ 2,
+ "Fixed. Every helper in the module takes "
+ "`impl AsRef<Path>` now.",
+ ),
+ (
+ "rmurthy",
+ 1,
+ "Approving. Let's land this before the config "
+ "loader change, so that one can drop its own copy "
+ "of the helpers.",
+ ),
+ ],
+ },
+ {
+ "number": 2,
+ "branch": "beta",
+ "title": "Cache resolved config per project",
+ "body": "Keeps the parsed config behind a `OnceCell` so a command "
+ "that reads it twice doesn't parse twice.",
+ "author": "dbenson",
+ "checks": [("IN_PROGRESS", None)],
+ "review": "REVIEW_REQUIRED",
+ "delay": 0.8,
+ "comments": [
+ (
+ "rmurthy",
+ 3,
+ "Does this need invalidation? A long-lived process would "
+ "hold a stale config across an edit.",
+ ),
+ ],
+ },
+ {
+ "number": 4,
+ "branch": "api",
+ "title": "Add the /health endpoint",
+ "body": "Returns build metadata and the database's round-trip time.",
+ "author": "dbenson",
+ "checks": [("COMPLETED", "FAILURE")],
+ "review": None,
+ "delay": 1.2,
+ "comments": [
+ (
+ "ci-bot",
+ 1,
+ "`test (linux)` failed: `acme::tests::test_add_zeros` "
+ "panicked at `assert_eq!(add(0, 0), 0)`.",
+ ),
+ ],
+ },
+ {
+ "number": 5,
+ "branch": "auth",
+ "title": "Rotate session tokens on privilege change",
+ "body": "Issues a fresh token whenever a session's role changes, so a "
+ "downgraded session can't keep its old claims.",
+ "author": "rmurthy",
+ "checks": [("COMPLETED", "SUCCESS")],
+ "review": "CHANGES_REQUESTED",
+ "delay": 1.6,
+ "comments": [
+ (
+ "dbenson",
+ 5,
+ "The rotation drops the old token immediately, which logs "
+ "out every other tab. Can we keep it valid for a grace "
+ "period?",
+ ),
+ ],
+ },
+ {
+ "number": 6,
+ "branch": "billing",
+ "title": "Format currency by locale",
+ "body": "Replaces the hand-rolled formatter with the locale-aware one.",
+ "author": "dbenson",
+ "checks": [("COMPLETED", "SUCCESS")],
+ "review": None,
+ "delay": 1.0,
+ "comments": [],
+ },
+]
+
+# Branches whose CI comes from the check-runs API rather than a PR — the bare
+# `#` in the CI column. `main` has pushed commits and passing checks but no open
+# PR. Branches listed in neither this nor DEMO_PRS show no CI at all, which is
+# what `hooks` (no remote) demonstrates.
+DEMO_BRANCH_CI = {
+ "main": [("completed", "success")],
+ "cache": [("completed", "success")],
+ "release": [("completed", "failure")],
+ "search": [("completed", "success")],
+ "retry": [("completed", "failure")],
+}
+
+
+def _iso_hours_ago(now: datetime, hours: int) -> str:
+ """RFC 3339 timestamp `hours` before `now`, as the forge reports one.
+
+ `now` must be UTC-aware: the forge stamps comments in UTC, and the picker
+ renders them as an age against the clock. A naive local time with a `Z`
+ suffix would shift every age by the recorder's UTC offset.
+ """
+ return (now - timedelta(hours=hours)).strftime("%Y-%m-%dT%H:%M:%SZ")
+
+
+def _rev_parse(repo: Path, rev: str) -> str | None:
+ """Resolve `rev` in `repo`, or None when it doesn't exist."""
+ result = subprocess.run(
+ ["git", "-C", str(repo), "rev-parse", "--verify", "--quiet", rev],
+ capture_output=True,
+ text=True,
+ )
+ return result.stdout.strip() or None
+
+
+def write_gh_mock_data(env: DemoEnv) -> None:
+ """Write the mocked forge's responses for this demo environment.
+
+ Runs after the branches exist: the check-runs responses are keyed by commit
+ SHA, and a PR's `headRefOid` is its pushed tip, so a branch with unpushed
+ commits reports the stale-head marker a real PR would. `prepare_demo_repo`
+ calls it once the shared branches are in place; a setup that adds more
+ branches calls it again, which rewrites every file from the current state.
+
+ Each file's first line is the delay the mock waits before answering; see
+ DEMO_PRS and `fixtures/gh-mock.sh`.
+ """
+ mock_dir = env.home / ".local" / "share" / "gh-mock"
+ for sub in ("head", "view", "sha"):
+ (mock_dir / sub).mkdir(parents=True, exist_ok=True)
+
+ def write(rel: str, delay: float, payload) -> None:
+ (mock_dir / rel).write_text(f"{delay}\n{json.dumps(payload)}\n")
+
+ now = datetime.now(timezone.utc)
+
+ for pr in DEMO_PRS:
+ branch = pr["branch"]
+ # The pushed tip when there is one, so unpushed local commits read as a
+ # stale PR head; a branch created during the recording has neither yet.
+ head = _rev_parse(env.repo, f"origin/{branch}") or _rev_parse(
+ env.repo, branch
+ )
+ comments = [
+ {
+ "author": {"login": author},
+ "body": body,
+ "createdAt": _iso_hours_ago(now, hours),
+ }
+ for author, hours, body in pr["comments"]
+ ]
+ newest = min((hours for _, hours, _ in pr["comments"]), default=1)
+ entry = {
+ "number": pr["number"],
+ "title": pr["title"],
+ "body": pr["body"],
+ "author": {"login": pr["author"]},
+ "comments": comments,
+ "headRefOid": head,
+ "mergeStateStatus": "CLEAN",
+ "statusCheckRollup": [
+ {"status": status, "conclusion": conclusion}
+ for status, conclusion in pr["checks"]
+ ],
+ "url": f"https://github.com/acme/demo/pull/{pr['number']}",
+ "headRepositoryOwner": {"login": "acme"},
+ "reviewDecision": pr["review"],
+ "isDraft": False,
+ "updatedAt": _iso_hours_ago(now, newest),
+ }
+ # `/` -> `_` matches `sanitize` in fixtures/gh-mock.sh.
+ write(f"head/{branch.replace('/', '_')}", pr["delay"], [entry])
+ # The comments tab's own fetch, for a row whose CI call hasn't primed
+ # the cache yet — which the delays above make the common case.
+ write(f"view/{pr['number']}", pr["delay"], {"comments": comments})
+
+ for branch, checks in DEMO_BRANCH_CI.items():
+ sha = _rev_parse(env.repo, branch)
+ if sha is None:
+ continue
+ write(
+ f"sha/{sha}",
+ 0.5,
+ [{"status": status, "conclusion": conclusion} for status, conclusion in checks],
+ )
+
+
def commit_dated(repo: Path, message: str, offset: str, env_extra: dict = None):
"""Commit with a date offset like '7d' or '2H'."""
now = datetime.now()
@@ -453,8 +782,18 @@ def prepare_base_repo(env: DemoEnv, repo_root: Path):
git(["-C", str(env.repo), "add", "README.md"])
commit_dated(env.repo, "Initial commit", "7d")
git(["-C", str(env.repo), "branch", "-m", "main"])
- # Use local bare repo as remote (GitHub URLs cause VHS to hang waiting for SSH)
- git(["-C", str(env.repo), "remote", "add", "origin", str(env.bare_remote)])
+ # Claim a GitHub origin, push to the local bare repo (see DEMO_ORIGIN_URL).
+ git(["-C", str(env.repo), "remote", "add", "origin", DEMO_ORIGIN_URL])
+ git([
+ "-C",
+ str(env.repo),
+ "config",
+ f"url.{env.bare_remote}.pushInsteadOf",
+ DEMO_ORIGIN_URL,
+ ])
+ # Seed the default branch so detection never reaches `git ls-remote`, whose
+ # fetch URL is the unreachable github.com one.
+ git(["-C", str(env.repo), "config", "worktrunk.default-branch", "main"])
git(["-C", str(env.repo), "push", "-u", "origin", "main", "-q"])
# Rust project
@@ -880,41 +1219,9 @@ fi
""")
flyctl_mock.chmod(0o755)
- # llm mock - simulates both commit message and summary generation.
- # Reads stdin to detect prompt type: summary prompts contain "summary",
- # commit prompts don't. For summaries, returns branch-appropriate one-liners
- # based on filenames in the diff.
+ # llm mock — the command every demo's `[commit.generation]` points at.
llm_mock = bin_dir / "llm"
- llm_mock.write_text(r"""#!/bin/bash
-input=$(cat)
-
-if echo "$input" | grep -qi "summary"; then
- # Summary generation — return branch-appropriate one-liner
- if echo "$input" | grep -q "utils\.rs"; then
- echo "Add utility functions module with string and math helpers"
- elif echo "$input" | grep -q "notes\.txt"; then
- echo "Add TODO notes for caching improvements"
- elif echo "$input" | grep -q "multiply\|subtract\|math"; then
- echo "Add math operations and consolidate tests"
- elif echo "$input" | grep -q "User settings"; then
- echo "Add user settings module placeholder"
- else
- echo "Expand README with contributing and license sections"
- fi
-else
- # Commit message generation
- sleep 0.5
- 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."
- fi
-fi
-""")
+ shutil.copy(FIXTURES_DIR / "llm-mock.sh", llm_mock)
llm_mock.chmod(0o755)
# cargo mock - handles nextest run
@@ -971,7 +1278,8 @@ def prepare_demo_repo(env: DemoEnv, repo_root: Path, hooks_config: str = None):
commit_dated(env.repo, "Add project hooks", "5d")
git(["-C", str(env.repo), "push", "-q"])
- # Mock gh CLI with varied CI status per branch
+ # Mock gh CLI. Its responses are written by `write_gh_mock_data` at the end
+ # of this function, once the branches it keys off exist.
bin_dir = env.home / ".local" / "bin"
gh_mock = bin_dir / "gh"
shutil.copy(FIXTURES_DIR / "gh-mock.sh", gh_mock)
@@ -998,6 +1306,8 @@ def prepare_demo_repo(env: DemoEnv, repo_root: Path, hooks_config: str = None):
_create_branch_alpha(env)
_create_branch_hooks(env)
+ write_gh_mock_data(env)
+
def _create_branch_alpha(env: DemoEnv):
"""Create alpha branch with large diff and unpushed commits."""
@@ -1107,25 +1417,47 @@ def check_dependencies(commands: list[str]):
raise SystemExit(f"Missing dependency: {cmd}")
+def _ffmpeg_draws_subtitles(ffmpeg: str) -> bool:
+ """Whether this ffmpeg was built with libass, i.e. has the `ass` filter."""
+ result = subprocess.run([ffmpeg, "-filters"], capture_output=True, text=True)
+ return " ass " in result.stdout
+
+
def check_ffmpeg_libass():
- """Check that ffmpeg has libass support (required for keystroke overlay)."""
- if not shutil.which("ffmpeg"):
- raise SystemExit(
- "Missing dependency: ffmpeg\n"
- "Install with: brew install ffmpeg-full\n"
- 'Then add it to PATH: export PATH="$(brew --prefix ffmpeg-full)/bin:$PATH"'
+ """Put an ffmpeg that can draw subtitles on PATH, for the keystroke overlay.
+
+ Homebrew ships two builds: `ffmpeg` is the one linked onto PATH and is
+ built without libass, while `ffmpeg-full` carries it and stays unlinked —
+ so installing ffmpeg at any point silently takes the overlay away again.
+ VHS shells out to plain `ffmpeg`, so when the linked build can't draw
+ subtitles this puts the full one in front of it for the rest of the build.
+
+ Worth doing rather than telling the user to fix their PATH: the failure
+ lands at the very end of a recording, as an ffmpeg filter-graph parse
+ error naming the subtitle file, minutes after the work that produced it.
+ """
+ ffmpeg = shutil.which("ffmpeg")
+ if ffmpeg and _ffmpeg_draws_subtitles(ffmpeg):
+ return
+
+ # Ask brew only where there is one: `subprocess.run` on a missing program
+ # raises rather than returning non-zero, which would replace the message
+ # below with a traceback on any box without Homebrew.
+ if shutil.which("brew"):
+ full = subprocess.run(
+ ["brew", "--prefix", "ffmpeg-full"], capture_output=True, text=True
)
- result = subprocess.run(
- ["ffmpeg", "-filters"],
- capture_output=True,
- text=True,
- )
- if " ass " not in result.stdout:
- raise SystemExit(
- "ffmpeg missing libass support (required for keystroke overlay).\n"
- "Install with: brew install ffmpeg-full\n"
- 'Then add it to PATH: export PATH="$(brew --prefix ffmpeg-full)/bin:$PATH"'
+ candidate = (
+ Path(full.stdout.strip()) / "bin" / "ffmpeg" if full.returncode == 0 else None
)
+ if candidate and candidate.exists() and _ffmpeg_draws_subtitles(str(candidate)):
+ os.environ["PATH"] = f"{candidate.parent}{os.pathsep}{os.environ['PATH']}"
+ return
+
+ raise SystemExit(
+ "No ffmpeg with libass support (required for the keystroke overlay).\n"
+ "Install with: brew install ffmpeg-full"
+ )
def write_starship_config(path: Path, theme: str) -> None:
@@ -1318,8 +1650,16 @@ def record_snapshot(
"LANG": "en_US.UTF-8",
"LC_ALL": "en_US.UTF-8",
"GIT_PAGER": "", # Plain text output, no delta formatting
+ # Pin what the snapshot's shape depends on. The commands run without
+ # a terminal, so `wt` falls back to `COLUMNS` for width and drops
+ # color; both would otherwise come from whatever shell invoked the
+ # build, and a snapshot that reflows with the recorder's window
+ # can't show that a hint crept in.
+ "COLUMNS": "80",
+ "CLICOLOR_FORCE": "1",
}
)
+ env.pop("NO_COLOR", None)
# Generate a fish script that:
# 1. Initializes shell integration (like shared-commands.tape)
@@ -1380,6 +1720,13 @@ SIZE_SOCIAL = DemoSize(width=1200, height=700, fontsize=26) # Big text for mobi
SIZE_DOCS = DemoSize(width=1600, height=900, fontsize=24) # More content for docs
SIZE_DOCS_MOBILE = DemoSize(width=576, height=432, fontsize=20)
+# The picker demo trades text size for terminal size, on the same canvas as the
+# rest: 139x34 rather than 102x25. It is the one demo whose subject is a table
+# and a preview pane side by side, and the columns it loses first are the ones
+# worth watching — at 102 columns the CI status and the branch summary fall off
+# the right edge, and the preview pane is too short to page a diff through.
+SIZE_DOCS_PICKER = DemoSize(width=1600, height=900, fontsize=18)
+
def build_tape_replacements(demo_env: DemoEnv, repo_root: Path) -> dict:
"""Build template variable replacements for tape rendering.
diff --git a/docs/demos/shared/validation.py b/docs/demos/shared/validation.py
index 3d02bcc16..47537804e 100644
--- a/docs/demos/shared/validation.py
+++ b/docs/demos/shared/validation.py
@@ -12,12 +12,12 @@ 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
+ from shared.validation import validate_tui_demo_verbose
- # Validate after building
- errors = validate_tui_demo("wt-zellij-omnibus", gif_path)
- if errors:
- print("Validation failed:", errors)
+ # Validate after building, for the target the GIF was recorded at
+ passed, report = validate_tui_demo_verbose("wt-zellij-omnibus", gif_path, "docs")
+ if not passed:
+ print(report)
"""
from __future__ import annotations
@@ -36,6 +36,14 @@ class Checkpoint:
for checkpoints on the state a recording ends in. How many frames a tape
produces varies between runs with the recording machine's speed, so a
fixed frame number near the end can fall past a faster recording's end.
+
+ ``targets`` restricts a checkpoint to the build targets whose geometry it
+ was calibrated against. One tape records at each target's own size, so how
+ long a given line stays on screen differs between them: the docs terminal
+ is ~33 rows and the social one ~24, and output that persists to the end of
+ the docs recording can scroll away within a second in social. A checkpoint
+ on such a line holds only where it was measured. Leave it unset for a
+ checkpoint whose window is generous in every target.
"""
start: int
@@ -43,6 +51,7 @@ class Checkpoint:
expected: list[str] = field(default_factory=list)
forbidden: list[str] = field(default_factory=list)
step: int = 10
+ targets: tuple[str, ...] | None = None
# Checkpoint definitions per TUI demo.
@@ -68,6 +77,39 @@ TUI_CHECKPOINTS: dict[str, list[Checkpoint]] = {
],
),
],
+ "wt-switch-picker": [
+ # The alt-p beat. Both halves of it matter: the columns the preview was
+ # covering appear, and the preview's own tab bar goes with it — and that
+ # second half is the only evidence the Alt binding reached the picker at
+ # all. Where an Alt key degrades to a plain keypress (a recorder that
+ # doesn't send Option as Meta), the tape types a "p" into the query
+ # instead: the list filters, the preview stays open, and the recording
+ # is wrong without anything failing. Scoped to docs because the social
+ # terminal is too narrow for these columns.
+ Checkpoint(
+ start=45,
+ end=95,
+ expected=["Commit", "Summary", "Reissue tokens"],
+ forbidden=["ctrl-u/d"],
+ targets=("docs",),
+ ),
+ # The comment thread behind alt-8, every line of it from the mocked
+ # forge. `reopen the picker` is how a failed fetch reads, and a forge
+ # mock that isn't reachable fails exactly that way.
+ Checkpoint(
+ start=345,
+ end=470,
+ expected=["normalize_path", "rmurthy"],
+ forbidden=["reopen the picker"],
+ ),
+ # The PR itself behind alt-7.
+ Checkpoint(
+ start=495,
+ end=550,
+ expected=["utility functions", "BRANCH", "alpha"],
+ forbidden=["reopen the picker"],
+ ),
+ ],
"wt-statusline": [
Checkpoint(
start=-130,
@@ -119,13 +161,24 @@ TUI_CHECKPOINTS: dict[str, list[Checkpoint]] = {
"Transcript saving",
],
),
- # The API agent adds a test. Commit generation should describe that
- # diff rather than replaying the feature-tab fixture's message.
+ # The API agent adds a test, and `wt merge` squashes it together with
+ # api's own commit. The generated message must describe that combined
+ # diff rather than replaying the feature-tab fixture's message — the
+ # squash prompt once diffed only the commits and missed the staged work.
+ #
+ # docs only. The message is printed mid-way through `wt merge`'s output
+ # and then pushed up by the rest of it, so it survives to the end of the
+ # ~33-row docs recording but scrolls off the ~24-row social one inside a
+ # second — an 18-frame window there, too narrow to sample reliably.
Checkpoint(
- start=1400,
- end=1750,
+ start=-430,
+ end=-1,
expected=["expand", "coverage"],
+ # The fixture message belongs to TAB 3's own commit, which has
+ # scrolled away by here; the squash-prompt bug put it on the merge's
+ # commit instead, inside this window.
forbidden=["user settings module", "script -q"],
+ targets=("docs",),
),
# The feature push uses a local demo remote internally, but its
# disposable filesystem path must never appear in the recording.
@@ -386,36 +439,18 @@ def validate_checkpoint(
return False, f"no match in {label} ({frames_checked} checked): {'; '.join(best_errors)}"
-def validate_tui_demo(demo_name: str, gif_path: Path) -> list[str]:
- """Validate a TUI demo GIF against its checkpoints.
-
- Returns list of error messages. Empty list means validation passed.
- """
- if demo_name not in TUI_CHECKPOINTS:
- return [f"No checkpoints defined for demo: {demo_name}"]
-
- if not gif_path.exists():
- return [f"GIF not found: {gif_path}"]
-
- missing = check_dependencies()
- if missing:
- return [f"Missing required tools: {', '.join(missing)}"]
+def checkpoints_for(demo_name: str, target: str) -> list[Checkpoint]:
+ """The checkpoints that apply to this demo in this build target."""
+ return [
+ c
+ for c in TUI_CHECKPOINTS[demo_name]
+ if c.targets is None or target in c.targets
+ ]
- checkpoints = TUI_CHECKPOINTS[demo_name]
- all_errors = []
-
- with tempfile.TemporaryDirectory(prefix="wt-validate-") as work_dir:
- work_path = Path(work_dir)
- for checkpoint in checkpoints:
- passed, detail = validate_checkpoint(gif_path, checkpoint, work_path)
- if not passed:
- all_errors.append(detail)
-
- return all_errors
-
-
-def validate_tui_demo_verbose(demo_name: str, gif_path: Path) -> tuple[bool, str]:
+def validate_tui_demo_verbose(
+ demo_name: str, gif_path: Path, target: str
+) -> tuple[bool, str]:
"""Validate a TUI demo with verbose output.
Returns (success, output_message).
@@ -432,7 +467,7 @@ def validate_tui_demo_verbose(demo_name: str, gif_path: Path) -> tuple[bool, str
if missing:
return False, f"Missing required tools: {', '.join(missing)}"
- checkpoints = TUI_CHECKPOINTS[demo_name]
+ checkpoints = checkpoints_for(demo_name, target)
all_passed = True
with tempfile.TemporaryDirectory(prefix="wt-validate-") as work_dir:
diff --git a/docs/demos/snapshots/wt-commit.snap b/docs/demos/snapshots/wt-commit.snap
index 57163a6be..3d69c2a8f 100644
--- a/docs/demos/snapshots/wt-commit.snap
+++ b/docs/demos/snapshots/wt-commit.snap
@@ -1,5 +1,5 @@
$ wt switch hooks
-○ Switched to worktree for hooks @ <DEMO_DIR>/.demo-wt-commit/w/acme.hooks
+○ Switched to worktree for hooks @ ~/w/acme.hooks

$ git diff --staged --stat
src/lib.rs | 1 +
@@ -7,20 +7,18 @@ $ git diff --staged --stat
2 files changed, 24 insertions(+)
$ wt step commit
-◎ Generating commit message and committing changes... (2 files, +25)
- feat(validation): add input validation utilities
-
- Add validation module with is_positive and is_non_empty helpers
- for validating user input. Includes comprehensive test coverage.
-✓ Committed changes @ 08d6aa2
+◎ Generating commit message and committing changes... (2 files, +25)
+  feat: add user settings module
+ 
+  Add placeholder module for user profile settings.
+✓ Committed changes @ 9ba13e6

$ git log -1
-commit 08d6aa281ae15980b1dc485df79834735f9afaeb
+commit 9ba13e68a85c31d8e54949e2cc4a447209a08020
Author: Worktrunk Demo <[email protected]>
-Date: Tue Jan 27 19:36:26 2026 -0800
+Date: Thu Sep 17 13:08:15 2026 -0700
- feat(validation): add input validation utilities
+ feat: add user settings module
- Add validation module with is_positive and is_non_empty helpers
- for validating user input. Includes comprehensive test coverage.
+ Add placeholder module for user profile settings.

diff --git a/docs/demos/snapshots/wt-core-mobile.snap b/docs/demos/snapshots/wt-core-mobile.snap
new file mode 100644
index 000000000..4ddd98210
--- /dev/null
+++ b/docs/demos/snapshots/wt-core-mobile.snap
@@ -0,0 +1,35 @@
+$ wt list
+ Branch Status HEAD± main↕ main…± Remote⇅ Commit Age
+@ main ^| | 8dd23db 1d
++ hooks +! ↑ +2 ↑1 +12 -7 71fcfa0 2h
++ billing _| | 8dd23db 1d
++ alpha !? ↑⇡ +106 -14 ↑5 +264 -3 ⇡1 b1e7fc8 3d
++ beta + ↓| +2 ↓1 | 604a937 5d
+
+○ Showing 5 worktrees, 3 with changes, 2 ahead, hidden: Path, Message
+
+$ wt switch alpha
+○ Switched to worktree for alpha @ ~/w/acme.alpha
+
+$ wt switch --create api
+✓ Created branch api from main and worktree @ ~/w/acme.api
+◎ Running post-start: dev (project)
+
+$ wt list
+ Branch Status HEAD± main↕ main…± Remote⇅ Commit Age
+@ api _ 8dd23db 1d
+^ main ^| | 8dd23db 1d
++ hooks +! ↑ +2 ↑1 +12 -7 71fcfa0 2h
++ billing _| | 8dd23db 1d
++ alpha !? ↑⇡ +106 -14 ↑5 +264 -3 ⇡1 b1e7fc8 3d
++ beta + ↓| +2 ↓1 | 604a937 5d
+
+○ Showing 6 worktrees, 3 with changes, 2 ahead, hidden: Path, Message
+
+$ wt remove
+◎ Running pre-remove project:cleanup
+  flyctl scale count 0
+Scaling app to 0 machines
+◎ Removing api worktree & branch in background (same commit as main, _)
+○ Switched to worktree for main @ ~/w/acme
+
diff --git a/docs/demos/snapshots/wt-core.snap b/docs/demos/snapshots/wt-core.snap
index 6b8410665..b8f605bd1 100644
--- a/docs/demos/snapshots/wt-core.snap
+++ b/docs/demos/snapshots/wt-core.snap
@@ -1,35 +1,36 @@
$ wt list
- Branch Status HEAD± main↕ Remote⇅ Commit Age Message
-@ main ^| | 8dbd1794 1d docs: add developm…
-+ hooks +! ↑ +2 ↑1 27ef5da7 2h feat: add math ope…
-+ billing _| | 8dbd1794 1d docs: add developm…
-+ alpha !? ↑⇡ +105 -14 ↑5 ⇡1 c53676dd 3d docs: add FAQ sect…
-+ beta + ↓| +2 ↓1 | 6ed05ea1 5d Add project hooks
+ Branch Status HEAD± main↕ main…± Remote⇅ Commit Age
+@ main ^| | 8dd23db 1d
++ hooks +! ↑ +2 ↑1 +12 -7 71fcfa0 2h
++ billing _| | 8dd23db 1d
++ alpha !? ↑⇡ +106 -14 ↑5 +264 -3 ⇡1 b1e7fc8 3d
++ beta + ↓| +2 ↓1 | 604a937 5d
-○ Showing 5 worktrees, 3 with changes, 2 ahead, 1 column hidden
+○ Showing 5 worktrees, 3 with changes, 2 ahead, hidden: Path, Message

$ wt switch alpha
-○ Switched to worktree for alpha @ <DEMO_DIR>/.demo-wt-core/w/acme.alpha
+○ Switched to worktree for alpha @ ~/w/acme.alpha

$ wt switch --create api
-✓ Created branch api from main and worktree @ <DEMO_DIR>/.demo-wt-core/w/acme.api
-◎ Running post-start: project:dev
+✓ Created branch api from main and worktree @ ~/w/acme.api
+◎ Running post-start: dev (project)

$ wt list --full
- Branch Status HEAD± main↕ main…± Remote⇅ CI Commit Age
-@ api _ 8dbd1794 1d
-^ main ^| | 8dbd1794 1d
-+ hooks +! ↑ +2 ↑1 +12 -7 27ef5da7 2h
-+ billing _| | 8dbd1794 1d
-+ alpha !? ↑⇡ +105 -14 ↑5 +264 -3 ⇡1 c53676dd 3d
-+ beta + ↓| +2 ↓1 | 6ed05ea1 5d
+ Branch Status HEAD± main↕ main…± Summary Remote⇅ CI
+@ api _ #4
+^ main ^| | #
++ hooks +! ↑ +2 ↑1 +12 -7 Add math op…
++ billing _| | #6
++ alpha !? ↑⇡ +106 -14 ↑5 +264 -3 Add utility… ⇡1 #1
++ beta + ↓| +2 ↓1 Add TODO no… | #2
-○ Showing 6 worktrees, 3 with changes, 2 ahead, 2 columns hidden
+○ Showing 6 worktrees, 3 with changes, 2 ahead, hidden: Path, Commit, Age,
+ Message

$ wt remove
-◎ Running pre-remove project:cleanup:
- flyctl scale count 0
-Scaling app to 0 machines
-◎ Removing api worktree & branch in background (same commit as main, _)
-○ Switched to worktree for main @ <DEMO_DIR>/.demo-wt-core/w/acme
+◎ Running pre-remove project:cleanup
+  flyctl scale count 0
+Scaling app to 0 machines
+◎ Removing api worktree & branch in background (same commit as main, _)
+○ Switched to worktree for main @ ~/w/acme

diff --git a/docs/demos/snapshots/wt-list.snap b/docs/demos/snapshots/wt-list.snap
index 4a787f4e0..4c8b63f3a 100644
--- a/docs/demos/snapshots/wt-list.snap
+++ b/docs/demos/snapshots/wt-list.snap
@@ -1,32 +1,34 @@
$ wt list
- Branch Status HEAD± main↕ Remote⇅ Commit Age Message
-@ main ^| | 8dbd1794 1d docs: add developm…
-+ hooks +! ↑ +2 ↑1 27ef5da7 2h feat: add math ope…
-+ billing _| | 8dbd1794 1d docs: add developm…
-+ alpha !? ↑⇡ +105 -14 ↑5 ⇡1 c53676dd 3d docs: add FAQ sect…
-+ beta + ↓| +2 ↓1 | 6ed05ea1 5d Add project hooks
+ Branch Status HEAD± main↕ main…± Remote⇅ Commit Age
+@ main ^| | 8dd23db 1d
++ hooks +! ↑ +2 ↑1 +12 -7 71fcfa0 2h
++ billing _| | 8dd23db 1d
++ alpha !? ↑⇡ +106 -14 ↑5 +264 -3 ⇡1 b1e7fc8 3d
++ beta + ↓| +2 ↓1 | 604a937 5d
-○ Showing 5 worktrees, 3 with changes, 2 ahead, 1 column hidden
+○ Showing 5 worktrees, 3 with changes, 2 ahead, hidden: Path, Message

$ wt list --full
- Branch Status HEAD± main↕ main…± Remote⇅ CI Commit Age
-@ main ^| | 8dbd1794 1d
-+ hooks +! ↑ +2 ↑1 +12 -7 27ef5da7 2h
-+ billing _| | 8dbd1794 1d
-+ alpha !? ↑⇡ +105 -14 ↑5 +264 -3 ⇡1 c53676dd 3d
-+ beta + ↓| +2 ↓1 | 6ed05ea1 5d
+ Branch Status HEAD± main↕ main…± Summary Remote⇅ CI
+@ main ^| | #
++ hooks +! ↑ +2 ↑1 +12 -7 Add math op…
++ billing _| | #6
++ alpha !? ↑⇡ +106 -14 ↑5 +264 -3 Add utility… ⇡1 #1
++ beta + ↓| +2 ↓1 Add TODO no… | #2
-○ Showing 5 worktrees, 3 with changes, 2 ahead, 2 columns hidden
+○ Showing 5 worktrees, 3 with changes, 2 ahead, hidden: Path, Commit, Age,
+ Message

$ wt list --branches
- Branch Status HEAD± main↕ Remote⇅ Commit Age Message
-@ main ^| | 8dbd1794 1d docs: add dev…
-+ hooks +! ↑ +2 ↑1 27ef5da7 2h feat: add mat…
-+ billing _| | 8dbd1794 1d docs: add dev…
-+ alpha !? ↑⇡ +105 -14 ↑5 ⇡1 c53676dd 3d docs: add FAQ…
-+ beta + ↓| +2 ↓1 | 6ed05ea1 5d Add project h…
- docs/readme /⊂ ↓1 6ed05ea1 5d Add project h…
- spike/search /⊂ ↓1 6ed05ea1 5d Add project h…
+ Branch Status HEAD± main↕ main…± Remote⇅ Commit Age
+@ main ^| | 8dd23db 1d
++ hooks +! ↑ +2 ↑1 +12 -7 71fcfa0 2h
++ billing _| | 8dd23db 1d
++ alpha !? ↑⇡ +106 -14 ↑5 +264 -3 ⇡1 b1e7fc8 3d
++ beta + ↓| +2 ↓1 | 604a937 5d
+/ docs/readme /⊂ ↓1 604a937 5d
+/ spike/search /⊂ ↓1 604a937 5d
-○ Showing 5 worktrees, 2 remote branches, 3 with changes, 2 ahead, 1 column hidden
+○ Showing 5 worktrees, 2 branches, 3 with changes, 2 ahead, hidden: Path,
+ Message

diff --git a/docs/demos/snapshots/wt-merge.snap b/docs/demos/snapshots/wt-merge.snap
index 5dc455135..09d05156f 100644
--- a/docs/demos/snapshots/wt-merge.snap
+++ b/docs/demos/snapshots/wt-merge.snap
@@ -1,37 +1,37 @@
$ wt list
- Branch Status HEAD± main↕ Remote⇅ Commit Age Message
-@ main ^| | 98c9958a 1d docs: add developme…
-+ hooks +! ↑ +25 ↑1 a5a2f9d5 2h feat: add math oper…
-+ alpha !? ↑⇡ +105 -14 ↑5 ⇡1 f9dceea8 3d docs: add FAQ secti…
-+ beta + ↓| +2 ↓1 | b0853702 5d Add project hooks
+ Branch Status HEAD± main↕ main…± Remote⇅ Commit Age
+@ main ^| | 2bdcf67 1d
++ hooks +! ↑ +25 ↑1 +12 -7 411beae 2h
++ alpha !? ↑⇡ +106 -14 ↑5 +264 -3 ⇡1 94a16dc 3d
++ beta + ↓| +2 ↓1 | ad21d97 5d
-○ Showing 4 worktrees, 3 with changes, 2 ahead, 1 column hidden
+○ Showing 4 worktrees, 3 with changes, 2 ahead, hidden: Path, Message

$ wt switch --create notes
-✓ Created branch notes from main and worktree @ <DEMO_DIR>/.demo-wt-merge/w/acme.notes
+✓ Created branch notes from main and worktree @ ~/w/acme.notes

$ wt merge
-◎ Running pre-merge project:test:
- cargo nextest run
- Finished `test` profile [unoptimized + debuginfo] target(s) in 0.02s
+◎ Running pre-merge project:test
+  cargo nextest run
+ Finished `test` profile [unoptimized + debuginfo] target(s) in 0.02s
Starting 2 tests across 1 binary
PASS [ 0.001s] acme::tests::test_add
PASS [ 0.001s] acme::tests::test_add_zeros
------------
Summary [ 0.002s] 2 tests run: 2 passed, 0 skipped
-○ Already up to date with main (no new commits, no rebase needed)
-◎ Removing notes worktree & branch in background (same commit as main, _)
-○ Switched to worktree for main @ <DEMO_DIR>/.demo-wt-merge/w/acme
+○ Already up to date with main (no new commits, no rebase needed)
+◎ Removing notes worktree & branch in background (same commit as main, _)
+○ Switched to worktree for main @ ~/w/acme

$ wt list --branches --full
- Branch Status HEAD± main↕ main…± Remote⇅ CI Commit Age
-@ main ^| | 98c9958a 1d
-+ hooks +! ↑ +25 ↑1 +12 -7 a5a2f9d5 2h
-+ notes _ 98c9958a 1d
-+ alpha !? ↑⇡ +105 -14 ↑5 +264 -3 ⇡1 f9dceea8 3d
-+ beta + ↓| +2 ↓1 | b0853702 5d
- docs/readme /⊂ ↓1 b0853702 5d
- spike/search /⊂ ↓1 b0853702 5d
+ Branch Status HEAD± main↕ main…± Remote⇅ CI Commit
+@ main ^| | # 2bdcf67
++ hooks +! ↑ +25 ↑1 +12 -7 411beae
++ alpha !? ↑⇡ +106 -14 ↑5 +264 -3 ⇡1 #1 94a16dc
++ beta + ↓| +2 ↓1 | #2 ad21d97
+/ docs/readme /⊂ ↓1 ad21d97
+/ spike/search /⊂ ↓1 ad21d97
-○ Showing 5 worktrees, 2 remote branches, 3 with changes, 2 ahead, 2 columns hidden
+○ Showing 4 worktrees, 2 branches, 3 with changes, 2 ahead, hidden: Summary,
+ Path, Age, Message

diff --git a/docs/demos/tapes/wt-list.tape b/docs/demos/tapes/wt-list.tape
index 316dd4104..626c53f3c 100644
--- a/docs/demos/tapes/wt-list.tape
+++ b/docs/demos/tapes/wt-list.tape
@@ -15,10 +15,12 @@ Sleep 300ms
Enter
Sleep 2.5s
-# Full view with CI and diff stats
+# Full view with CI and diff stats. The CI cells arrive from the forge behind
+# the table, so this waits out the slowest mocked response (DEMO_PRS) and
+# still leaves the settled table on screen.
Type "wt list --full"
Enter
-Sleep 2.5s
+Sleep 3.5s
# Show all branches including remote-only
Type "wt list --branches"
diff --git a/docs/demos/tapes/wt-switch-picker.tape b/docs/demos/tapes/wt-switch-picker.tape
index 15a332e74..4613ddb37 100644
--- a/docs/demos/tapes/wt-switch-picker.tape
+++ b/docs/demos/tapes/wt-switch-picker.tape
@@ -2,6 +2,30 @@ Source docs/demos/tapes/shared-setup.tape
Output "{{OUTPUT_GIF}}"
+# PICKER DEMO: the interactive picker as its own subject
+#
+# The picker's two selling points are hard to show in a still: rows that paint
+# from local git before any network call, with per-row CI arriving behind them,
+# and a preview pane that pages through a diff or a PR thread without leaving
+# the list. The order below takes them in turn.
+#
+# 1. wt switch — rows land immediately, CI and summaries still in flight
+# 2. alt-p — preview off: the same rows reveal their right-hand
+# columns (summary, CI, commit) while both are arriving
+# 3. alt-p, ↓↓ — preview back on, following the cursor
+# 4. "alpha" — filter to the branch with the large diff
+# 5. ctrl-d ×3 — page through a 397-line diff
+# 6. alt-8, ctrl-d — the PR's comment thread, paged
+# 7. alt-7 — the PR itself: title, author, URL, description
+# 8. Enter — switch to it
+#
+# The environment is `prepare_picker` in docs/demos/build: sixteen worktrees,
+# varied CI (PR numbers, bare branch CI, none), a mocked LLM behind the Summary
+# column, and a mocked forge whose per-branch response delays are what make the
+# CI column stream. It records at `SIZE_DOCS_PICKER` — the same canvas as every
+# other demo, in smaller text, because at the usual size the CI status and the
+# summary fall off the right edge.
+
Source docs/demos/tapes/shared-commands.tape
Type "clear"
@@ -9,34 +33,61 @@ Enter
Sleep 1s
Set KeyStrokes Show
-# Launch interactive picker (wt switch without args)
+# Open the picker. Rows paint from local git right away. `Show` comes after the
+# command is typed, as in every docs demo — the first frame carries the whole
+# command rather than a character of it. Keystroke times are positions in the
+# recorded video and a hidden stretch records no frames, so those characters
+# all land on that first frame together, which is what it already shows.
Type "wt switch"
Show
Sleep 300ms
Enter
-Sleep 1.5s
+Sleep 500ms
+
+# alt-p hides the preview, and the same rows widen to full width to reveal the
+# columns the preview was covering. No reload, so no column moves — and the CI
+# cells are still landing one at a time behind the frame.
+Alt+p
+Sleep 3s
-# Quick browse - second down comes fast
+# Preview back on. It follows the cursor.
+Alt+p
+Sleep 1.2s
Down
-Sleep 0.1s
+Sleep 1.2s
Down
-Sleep 0.8s
+Sleep 1.2s
+
+# Filter to alpha, which carries the large diff. Spelled out rather than
+# "alp": narrowing the list keeps the cursor's row *index*, so a query that
+# still matches several rows would leave it on whichever one now sits at that
+# index (after the two Downs above, "alp" selects beta).
+Type "alpha"
+Sleep 1.5s
-# Scroll the diff panel with Ctrl+D
+# Page through it.
Ctrl+d
-Sleep 0.5s
+Sleep 700ms
Ctrl+d
-Sleep 0.5s
+Sleep 700ms
+Ctrl+d
+Sleep 2.5s
+
+# alt-8 is the PR's comment thread, which pages the same way. VHS needs the
+# digit quoted — `Alt+` takes a string, Enter or Tab, and a bare 8 lexes as a
+# number.
+Alt+"8"
+Sleep 3s
Ctrl+d
Sleep 3s
-# Filter to find alpha branch
-Type "alp"
-Sleep 1s
+# alt-7 is the PR itself.
+Alt+"7"
+Sleep 3s
-# Select it
+# Enter switches to the selected worktree.
Enter
-Sleep 1.5s
+Sleep 2.5s
Hide
Type "exit"
diff --git a/docs/demos/tapes/wt-zellij-omnibus.tape b/docs/demos/tapes/wt-zellij-omnibus.tape
index 54c562905..84f6866aa 100644
--- a/docs/demos/tapes/wt-zellij-omnibus.tape
+++ b/docs/demos/tapes/wt-zellij-omnibus.tape
@@ -13,14 +13,15 @@ Output "{{OUTPUT_GIF}}"
# 4. Each Zellij tab shows a distinct workflow
#
# Tab structure:
-# TAB 1: wt switch (picker → api) → claude (simple task)
+# TAB 1: wt switch (picker: CI streaming in, alt-p reveal, diff paging → api)
+# → claude (simple task)
# TAB 2: [NEW TAB] wsl abbreviation (wt switch -x claude --create) → claude
# TAB 3: [NEW TAB] wt switch --create → wt step commit → git push → wt remove → wt list --full
# Then back to TAB 1: [NEW PANE] git diff → wt merge (on Claude's completed work)
#
# Features demonstrated:
# - wt list / wt list --full (URLs, CI status, diff stats)
-# - wt switch (interactive picker)
+# - wt switch (interactive picker: streaming CI, alt-p column reveal, diff paging)
# - wsl abbreviation (wt switch --execute=claude --create)
# - wt switch --create (with post-start hooks)
# - wt step commit (LLM commit message, standalone)
@@ -51,16 +52,33 @@ Enter
Sleep 500ms
# ==== TAB 1: Interactive picker and Claude agent ====
-# wt switch (no args) - opens interactive picker
+# wt switch (no args) - opens interactive picker. The rows paint from local git
+# immediately; each row's CI status is still in flight behind them.
Type "wt switch"
Show
Sleep 300ms
Enter
-Sleep 1.5s
+Sleep 500ms
+
+# alt-p hides the preview, widening the same rows to full width so the CI
+# column is visible while it is still filling in. The picker demo
+# (wt-switch-picker) is the full tour; this is the glance at it.
+Alt+p
+Sleep 2.5s
+Alt+p
+Sleep 800ms
-# Filter to api branch
+# Filter to api. Typed before any cursor movement: narrowing the list keeps the
+# cursor's row *index*, so the exact branch-name match has to be the top row for
+# this to land on api — which it is from the cursor's opening position.
Type "api"
-Sleep 1s
+Sleep 1.2s
+
+# Page through api's diff without leaving the list.
+Ctrl+d
+Sleep 700ms
+Ctrl+d
+Sleep 1.8s
# Select it
Enter
diff --git a/docs/demos/tests/test_recording.py b/docs/demos/tests/test_recording.py
index 3b25f8008..fc3a804a5 100644
--- a/docs/demos/tests/test_recording.py
+++ b/docs/demos/tests/test_recording.py
@@ -60,6 +60,7 @@ Env HOME "{{DEMO_HOME}}"
list(output_gifs),
DemoSize(width=1600, height=900, fontsize=24),
vhs_binary=str(fake_vhs),
+ target="docs",
)
assert len(environments) == 2
diff --git a/docs/src/content/docs/config.md b/docs/src/content/docs/config.md
index 5cd46eab0..82972b5f9 100644
--- a/docs/src/content/docs/config.md
+++ b/docs/src/content/docs/config.md
@@ -482,7 +482,7 @@ Default template:
```toml
[commit.generation]
squash-template = """
-<task>Write a commit message for the combined effect of these commits.</task>
+<task>Write a commit message for the change in <diff>, which is everything the squash will record. <commits> lists what it folds in.</task>
<format>
- Subject line under 50 chars
diff --git a/docs/src/content/docs/switch.md b/docs/src/content/docs/switch.md
index aa384be08..f4d42dd85 100644
--- a/docs/src/content/docs/switch.md
+++ b/docs/src/content/docs/switch.md
@@ -86,9 +86,9 @@ The CI column shows each row's PR/MR CI and review status, the same as [`wt list
<figure class="demo">
<picture>
<source srcset="/assets/docs/dark/wt-switch-picker.gif" media="(prefers-color-scheme: dark)">
- <img src="/assets/docs/light/wt-switch-picker.gif" alt="wt switch picker demo" width="1600" height="800">
+ <img src="/assets/docs/light/wt-switch-picker.gif" alt="wt switch picker demo" width="1600" height="900">
</picture>
-<figcaption>Browsing the picker, scrolling a preview, filtering, and selecting</figcaption>
+<figcaption>Alt-p to reveal the CI and summary columns as they fill in, then paging a diff, a PR's comment thread, and the PR itself</figcaption>
</figure>
**Keybindings:**
diff --git a/docs/src/content/docs/worktrunk.md b/docs/src/content/docs/worktrunk.md
index d50b3ceb7..ff56fa7ed 100644
--- a/docs/src/content/docs/worktrunk.md
+++ b/docs/src/content/docs/worktrunk.md
@@ -99,7 +99,7 @@ git branch -d feat</code></pre></td>
- **[Hooks](/hook/)** — run commands on create, pre-merge, post-merge, etc
- **[LLM commit messages](/llm-commits/)** — generate commit messages from diffs
- **[Merge workflow](/merge/)** — squash, rebase, merge, clean up in one command
-- **[Interactive picker](/switch/#interactive-picker)** — browse worktrees with live diff and log previews
+- **[Interactive picker](/switch/#interactive-picker)** — browse worktrees with streaming CI status and diff, log, PR and comment previews
- **[Share build caches](/step/#wt-step-copy-ignored)** — ten worktrees get `target/`, `node_modules/`, etc without building or copying them (on APFS, btrfs, and XFS)
- **[`wt list --full`](/list/#full-mode)** — [CI status](/list/#ci-status) and [AI-generated summaries](/list/#llm-summaries) per branch
- **[PR checkout](/switch/#pull-requests-and-merge-requests)** — `wt switch pr:123` to jump straight to a PR's branch
diff --git a/plugins/worktrunk/skills/worktrunk/reference/config.md b/plugins/worktrunk/skills/worktrunk/reference/config.md
index 043b37b60..3cef4ef06 100644
--- a/plugins/worktrunk/skills/worktrunk/reference/config.md
+++ b/plugins/worktrunk/skills/worktrunk/reference/config.md
@@ -474,7 +474,7 @@ Default template:
```toml
[commit.generation]
squash-template = """
-<task>Write a commit message for the combined effect of these commits.</task>
+<task>Write a commit message for the change in <diff>, which is everything the squash will record. <commits> lists what it folds in.</task>
<format>
- Subject line under 50 chars
diff --git a/plugins/worktrunk/skills/worktrunk/reference/worktrunk.md b/plugins/worktrunk/skills/worktrunk/reference/worktrunk.md
index c23836451..033741302 100644
--- a/plugins/worktrunk/skills/worktrunk/reference/worktrunk.md
+++ b/plugins/worktrunk/skills/worktrunk/reference/worktrunk.md
@@ -71,7 +71,7 @@ git branch -d feat</code></pre></td>
- **[Hooks](https://worktrunk.dev/hook/)** — run commands on create, pre-merge, post-merge, etc
- **[LLM commit messages](https://worktrunk.dev/llm-commits/)** — generate commit messages from diffs
- **[Merge workflow](https://worktrunk.dev/merge/)** — squash, rebase, merge, clean up in one command
-- **[Interactive picker](https://worktrunk.dev/switch/#interactive-picker)** — browse worktrees with live diff and log previews
+- **[Interactive picker](https://worktrunk.dev/switch/#interactive-picker)** — browse worktrees with streaming CI status and diff, log, PR and comment previews
- **[Share build caches](https://worktrunk.dev/step/#wt-step-copy-ignored)** — ten worktrees get `target/`, `node_modules/`, etc without building or copying them (on APFS, btrfs, and XFS)
- **[`wt list --full`](https://worktrunk.dev/list/#full-mode)** — [CI status](https://worktrunk.dev/list/#ci-status) and [AI-generated summaries](https://worktrunk.dev/list/#llm-summaries) per branch
- **[PR checkout](https://worktrunk.dev/switch/#pull-requests-and-merge-requests)** — `wt switch pr:123` to jump straight to a PR's branch
diff --git a/skills/worktrunk/reference/config.md b/skills/worktrunk/reference/config.md
index 043b37b60..3cef4ef06 100644
--- a/skills/worktrunk/reference/config.md
+++ b/skills/worktrunk/reference/config.md
@@ -474,7 +474,7 @@ Default template:
```toml
[commit.generation]
squash-template = """
-<task>Write a commit message for the combined effect of these commits.</task>
+<task>Write a commit message for the change in <diff>, which is everything the squash will record. <commits> lists what it folds in.</task>
<format>
- Subject line under 50 chars
diff --git a/skills/worktrunk/reference/worktrunk.md b/skills/worktrunk/reference/worktrunk.md
index c23836451..033741302 100644
--- a/skills/worktrunk/reference/worktrunk.md
+++ b/skills/worktrunk/reference/worktrunk.md
@@ -71,7 +71,7 @@ git branch -d feat</code></pre></td>
- **[Hooks](https://worktrunk.dev/hook/)** — run commands on create, pre-merge, post-merge, etc
- **[LLM commit messages](https://worktrunk.dev/llm-commits/)** — generate commit messages from diffs
- **[Merge workflow](https://worktrunk.dev/merge/)** — squash, rebase, merge, clean up in one command
-- **[Interactive picker](https://worktrunk.dev/switch/#interactive-picker)** — browse worktrees with live diff and log previews
+- **[Interactive picker](https://worktrunk.dev/switch/#interactive-picker)** — browse worktrees with streaming CI status and diff, log, PR and comment previews
- **[Share build caches](https://worktrunk.dev/step/#wt-step-copy-ignored)** — ten worktrees get `target/`, `node_modules/`, etc without building or copying them (on APFS, btrfs, and XFS)
- **[`wt list --full`](https://worktrunk.dev/list/#full-mode)** — [CI status](https://worktrunk.dev/list/#ci-status) and [AI-generated summaries](https://worktrunk.dev/list/#llm-summaries) per branch
- **[PR checkout](https://worktrunk.dev/switch/#pull-requests-and-merge-requests)** — `wt switch pr:123` to jump straight to a PR's branch
diff --git a/src/cli/mod.rs b/src/cli/mod.rs
index d7cab06d4..32149995f 100644
--- a/src/cli/mod.rs
+++ b/src/cli/mod.rs
@@ -696,7 +696,7 @@ When called without arguments, `wt switch` opens an interactive picker to browse
The CI column shows each row's PR/MR CI and review status, the same as [`wt list --full`](/list/).
-<!-- demo: wt-switch-picker.gif 1600x800 | Browsing the picker, scrolling a preview, filtering, and selecting -->
+<!-- demo: wt-switch-picker.gif 1600x900 | Alt-p to reveal the CI and summary columns as they fill in, then paging a diff, a PR's comment thread, and the PR itself -->
**Keybindings:**
| Key | Action |
@@ -2420,7 +2420,7 @@ Default template:
```toml
[commit.generation]
squash-template = """
-<task>Write a commit message for the combined effect of these commits.</task>
+<task>Write a commit message for the change in <diff>, which is everything the squash will record. <commits> lists what it folds in.</task>
<format>
- Subject line under 50 chars
diff --git a/src/commands/picker/preview.rs b/src/commands/picker/preview.rs
index 8c12357f6..64fb23d97 100644
--- a/src/commands/picker/preview.rs
+++ b/src/commands/picker/preview.rs
@@ -109,6 +109,16 @@ pub(super) const MIN_VISIBLE_ITEMS: usize = 3;
/// Preview width as percentage of terminal width (for Right layout).
const PREVIEW_WIDTH_PERCENT: usize = 50;
+/// The column skim leaves unpainted at the right edge of a preview pane.
+///
+/// Measured in both layouts: a `right:N` window paints N-1 columns, and a
+/// `down:` pane paints one fewer than the terminal is wide. Render to the full
+/// width and the last column is dropped — silently, and only on the lines long
+/// enough to reach it, which for wrapped prose is whichever line happens to
+/// break flush against the edge, so the loss is a missing letter mid-sentence
+/// rather than anything that looks like clipping.
+const PREVIEW_RESERVED_COLS: usize = 1;
+
/// Minimum terminal columns for side-by-side (Right) layout.
///
/// Below this width, the list panel in Right layout is too narrow
@@ -201,7 +211,7 @@ impl PreviewLayout {
/// Right positions the preview by width, Down by height.
pub(super) fn spec_for(self, (width, height): (usize, usize)) -> String {
match self {
- Self::Right => format!("right:{width}"),
+ Self::Right => format!("right:{}", width + PREVIEW_RESERVED_COLS),
Self::Down => format!("down:{height}"),
}
}
@@ -212,6 +222,10 @@ impl PreviewLayout {
/// `spec_for`) and background pre-computation. Pure, so it's testable
/// without a live TTY.
///
+ /// The width is the pane's *text* width, which is what every renderer
+ /// wants; `spec_for` adds [`PREVIEW_RESERVED_COLS`] back when it asks skim
+ /// for the Right window, and Down's spec carries only a height.
+ ///
/// Right keeps a fixed 50%/90% split independent of `num_items`. Down lets
/// the list grow to `max_visible_items(available)` rows (half of skim's
/// area) and hands the rest to the preview, floored at `MIN_PREVIEW_LINES`
@@ -224,12 +238,13 @@ impl PreviewLayout {
) -> (usize, usize) {
match self {
Self::Right => {
- let width = term_width * PREVIEW_WIDTH_PERCENT / 100;
+ let width = (term_width * PREVIEW_WIDTH_PERCENT / 100)
+ .saturating_sub(PREVIEW_RESERVED_COLS);
let height = available_height(term_height);
(width, height)
}
Self::Down => {
- let width = term_width;
+ let width = term_width.saturating_sub(PREVIEW_RESERVED_COLS);
let available = available_height(term_height);
let list_lines = LIST_CHROME_LINES + num_items.min(max_visible_items(available));
let remaining = available.saturating_sub(list_lines);
@@ -352,11 +367,38 @@ mod tests {
#[test]
fn test_preview_layout_spec_for() {
- // Right positions by width, Down by height.
- assert_eq!(PreviewLayout::Right.spec_for((40, 21)), "right:40");
+ // Right positions by width, Down by height. The Right window is one
+ // column wider than the text it holds — see PREVIEW_RESERVED_COLS.
+ assert_eq!(PreviewLayout::Right.spec_for((40, 21)), "right:41");
assert_eq!(PreviewLayout::Down.spec_for((80, 15)), "down:15");
}
+ #[test]
+ fn test_preview_width_stops_short_of_the_column_skim_leaves_unpainted() {
+ // Both layouts hand renderers a text width one short of the pane, so a
+ // line that fills it survives; rendering to the full pane instead drops
+ // the last column, which reads as a wrapped sentence missing a letter.
+ // Right's window spec still names the whole pane — that is skim's, not
+ // the renderer's.
+ for term_width in [80usize, 120, 139, 200] {
+ let pane = term_width * PREVIEW_WIDTH_PERCENT / 100;
+ let (text_width, _) = PreviewLayout::Right.dimensions_for(term_width, 40, 10);
+ assert_eq!(text_width, pane - 1, "Right text width at {term_width}");
+ assert_eq!(
+ PreviewLayout::Right.spec_for((text_width, 0)),
+ format!("right:{pane}"),
+ "Right window spec at {term_width}"
+ );
+
+ let (down_width, _) = PreviewLayout::Down.dimensions_for(term_width, 40, 10);
+ assert_eq!(
+ down_width,
+ term_width - 1,
+ "Down text width at {term_width}"
+ );
+ }
+ }
+
#[test]
fn test_available_height_is_skim_height_percent() {
// The single home for skim's 90%-of-terminal conversion.
@@ -429,7 +471,10 @@ mod tests {
];
for (term_height, num_items, expected_preview) in cases {
let (width, preview) = PreviewLayout::Down.dimensions_for(80, term_height, num_items);
- assert_eq!(width, 80, "Down width is the full terminal width");
+ assert_eq!(
+ width, 79,
+ "Down width is the terminal less the column skim leaves unpainted"
+ );
assert_eq!(
preview, expected_preview,
"Down preview height for {term_height}h x {num_items} items"
diff --git a/src/commands/step/squash.rs b/src/commands/step/squash.rs
index 04575971e..bd9b81b31 100644
--- a/src/commands/step/squash.rs
+++ b/src/commands/step/squash.rs
@@ -280,15 +280,18 @@ pub fn handle_squash(
.and_then(|n| n.to_str())
.unwrap_or("repo");
- let commit_message = crate::llm::generate_squash_message(
- &span_target,
- &merge_base,
- &commit_details,
- &current_branch,
+ let commit_message = crate::llm::SquashInputs {
+ target_branch: &span_target,
+ merge_base: &merge_base,
+ commit_details: &commit_details,
+ current_branch: &current_branch,
repo_name,
- &resolved.commit_generation,
- project_append.as_deref(),
- )?;
+ config: &resolved.commit_generation,
+ project_append: project_append.as_deref(),
+ // `wt.stage` above already put everything in the real index.
+ staging_index: None,
+ }
+ .generate_message()?;
// Display the generated commit message
let formatted_message = generator.format_message_for_display(&commit_message);
@@ -345,24 +348,36 @@ pub fn handle_squash(
/// Handle `wt step squash --show-prompt`
///
/// Builds and outputs the squash prompt without running the LLM or squashing.
-pub fn step_show_squash_prompt(target: Option<&str>) -> anyhow::Result<()> {
+pub fn step_show_squash_prompt(
+ target: Option<&str>,
+ stage: Option<StageMode>,
+) -> anyhow::Result<()> {
// `--show-prompt` never invokes the LLM, so the `yes` flag is irrelevant
// — pass false; the guidance gate inside `preview_squash` is dry-run only.
- preview_squash(target, false, false)
+ preview_squash(target, stage, false, false)
}
/// Handle `wt step squash --dry-run`
///
/// Renders the squash prompt, prints the LLM command, generates the message, and prints
/// it without resetting, running hooks, or committing.
-pub fn step_dry_run_squash(target: Option<&str>, yes: bool) -> anyhow::Result<()> {
- preview_squash(target, true, yes)
+pub fn step_dry_run_squash(
+ target: Option<&str>,
+ stage: Option<StageMode>,
+ yes: bool,
+) -> anyhow::Result<()> {
+ preview_squash(target, stage, true, yes)
}
/// Shared implementation for `--show-prompt` and `--dry-run` on squash. `--show-prompt`
/// (`dry_run = false`) outputs only the rendered prompt; `--dry-run` additionally calls
/// the LLM and prints the command and the generated message.
-fn preview_squash(target: Option<&str>, dry_run: bool, yes: bool) -> anyhow::Result<()> {
+fn preview_squash(
+ target: Option<&str>,
+ stage: Option<StageMode>,
+ dry_run: bool,
+ yes: bool,
+) -> anyhow::Result<()> {
let repo = Repository::current()?;
let config = UserConfig::load().context("Failed to load config")?;
let project_id = repo.project_identifier().ok();
@@ -398,27 +413,37 @@ fn preview_squash(target: Option<&str>, dry_run: bool, yes: bool) -> anyhow::Res
let ctx = env.context(yes);
let project_append = resolve_template_for_preview(&ctx, &commit_config, dry_run)?;
- let prompt = crate::llm::build_squash_prompt(
- &span_target,
- &merge_base,
- &commit_details,
- &current_branch,
+ // `--dry-run` stages into a copy of the index so the previewed prompt spans
+ // what a real squash would commit: `handle_squash` stages before generating
+ // the message, and the prompt's diff is read from the index. `--show-prompt`
+ // skips it, the cheap "what's already staged" path — the same split
+ // `preview_commit` makes for `wt step commit`.
+ let stage_mode = stage.unwrap_or(env.resolved().commit.stage());
+ let temp_index = if dry_run && stage_mode != StageMode::None {
+ let temp = wt.temp_index()?;
+ temp.stage(stage_mode)?;
+ Some(temp)
+ } else {
+ None
+ };
+ let staging_index = temp_index.as_ref();
+
+ let inputs = crate::llm::SquashInputs {
+ target_branch: &span_target,
+ merge_base: &merge_base,
+ commit_details: &commit_details,
+ current_branch: &current_branch,
repo_name,
- &commit_config,
- project_append.as_deref(),
- )?;
+ config: &commit_config,
+ project_append: project_append.as_deref(),
+ staging_index,
+ };
+
+ let prompt = inputs.prompt()?;
if !dry_run {
println!("{}", prompt);
return Ok(());
}
- let message = crate::llm::generate_squash_message(
- &span_target,
- &merge_base,
- &commit_details,
- &current_branch,
- repo_name,
- &commit_config,
- project_append.as_deref(),
- )?;
+ let message = inputs.generate_message()?;
print_dry_run(&prompt, &commit_config, &message)
}
diff --git a/src/llm.rs b/src/llm.rs
index 63cf1ec5c..52fb1cf57 100644
--- a/src/llm.rs
+++ b/src/llm.rs
@@ -465,7 +465,7 @@ Branch: {{ branch }}
/// Default template for squash commit message prompts
///
/// Synced to dev/config.example.toml by `cargo test readme_sync`
-const DEFAULT_SQUASH_TEMPLATE: &str = r#"<task>Write a commit message for the combined effect of these commits.</task>
+const DEFAULT_SQUASH_TEMPLATE: &str = r#"<task>Write a commit message for the change in <diff>, which is everything the squash will record. <commits> lists what it folds in.</task>
<format>
- Subject line under 50 chars
@@ -722,7 +722,7 @@ pub(crate) fn generate_commit_message(
let command = commit_generation_config.command.as_ref().unwrap();
// Prompt-build failures (git plumbing) propagate as-is; only a
// failure of the LLM command itself gets the `LlmCommandFailed`
- // wrapper — mirroring `generate_squash_message`.
+ // wrapper — mirroring `SquashInputs::generate_message`.
let prompt =
build_commit_prompt(commit_generation_config, wt, staging_index, project_append)?;
// A slow or hung command is otherwise silent (stdout is captured); the
@@ -744,7 +744,8 @@ pub(crate) fn generate_commit_message(
}
// Fallback: generate a descriptive commit message based on changed files
- let file_list = staged_diff(wt, staging_index)?.capture(["--name-only", "-z"])?;
+ let file_list =
+ staged_diff(wt, staging_index, wt.index_base()?).capture(["--name-only", "-z"])?;
let staged_files = file_list
.split('\0')
.map(|s| s.trim())
@@ -771,17 +772,22 @@ pub(crate) fn generate_commit_message(
Ok(message)
}
-/// The changes a commit from `wt` would record, read from `staging_index`
-/// when given and from the real index otherwise.
+/// The changes a commit from `wt` would record against `base`, read from
+/// `staging_index` when given and from the real index otherwise.
+///
+/// `base` is the commit the resulting one sits on: `HEAD` for a plain commit,
+/// the merge base for a squash that rewrites everything since it. The caller
+/// supplies it because only the caller knows which, and reading `HEAD` is the
+/// only fallible part of naming either.
fn staged_diff<'a>(
wt: &WorkingTree<'a>,
staging_index: Option<&'a TempIndex>,
-) -> anyhow::Result<worktrunk::git::PreparedDiff<'a>> {
- let base = wt.index_base()?;
- Ok(match staging_index {
+ base: impl Into<String>,
+) -> worktrunk::git::PreparedDiff<'a> {
+ match staging_index {
Some(index) => index.prepare_staged_diff(base),
None => wt.prepare_staged_diff(base),
- })
+ }
}
/// Build the commit prompt from staged changes.
@@ -801,7 +807,7 @@ pub(crate) fn build_commit_prompt(
staging_index: Option<&TempIndex>,
project_append: Option<&str>,
) -> anyhow::Result<String> {
- let staged = staged_diff(wt, staging_index)?;
+ let staged = staged_diff(wt, staging_index, wt.index_base()?);
let diff_output = staged.capture(["--patch"])?;
let diff_stat = staged.capture(["--stat"])?;
@@ -831,92 +837,103 @@ pub(crate) fn build_commit_prompt(
build_prompt(config, TemplateType::Commit, &context)
}
-pub(crate) fn generate_squash_message(
- target_branch: &str,
- merge_base: &str,
- commit_details: &[CommitMessageDetail],
- current_branch: &str,
- repo_name: &str,
- commit_generation_config: &CommitGenerationConfig,
- project_append: Option<&str>,
-) -> anyhow::Result<String> {
- // Check if commit generation is configured (non-empty command)
- if commit_generation_config.is_configured() {
- let command = commit_generation_config.command.as_ref().unwrap();
-
- let prompt = build_squash_prompt(
- target_branch,
- merge_base,
- commit_details,
- current_branch,
- repo_name,
- commit_generation_config,
- project_append,
- )?;
-
- // See `generate_commit_message` — keep a slow squash-message generation
- // from being silent.
- let _watchdog = watch_llm_command(command);
- return execute_llm_command(command, &prompt).map_err(|e| {
- worktrunk::git::GitError::LlmCommandFailed {
- command: command.clone(),
- error: e.display_message(),
- reproduction_command: Some(format_reproduction_command(
- "wt step squash --show-prompt",
- command,
- )),
- }
- .into()
- });
- }
-
- // Fallback: deterministic commit message (only when not configured)
- let mut commit_message = format!("Squash commits from {}\n\n", current_branch);
- commit_message.push_str("Combined commits:\n");
- for detail in commit_details.iter().rev() {
- // Reverse so they're in chronological order
- commit_message.push_str(&format!("- {}\n", detail.subject));
- }
- Ok(commit_message)
-}
-
-/// Build the squash prompt from commits being squashed.
+/// Everything the squash's message is derived from.
///
-/// Gathers the combined diff, commit message details, branch names, and recent commits, then
-/// renders the prompt template. Used by both normal squash generation and `--show-prompt`.
-pub(crate) fn build_squash_prompt(
- target_branch: &str,
- merge_base: &str,
- commit_details: &[CommitMessageDetail],
- current_branch: &str,
- repo_name: &str,
- config: &CommitGenerationConfig,
- project_append: Option<&str>,
-) -> anyhow::Result<String> {
- let repo = Repository::current()?;
-
- // Get the combined diff and diffstat for all commits being squashed
- let squashed = repo.prepare_diff(merge_base, "HEAD");
- let diff_output = squashed.capture(["--patch"])?;
- let diff_stat = squashed.capture(["--stat"])?;
+/// One struct rather than eight positional arguments: `generate` forwards the
+/// whole set to `build`, and the three call sites pass the same values in the
+/// same order, which is exactly where a transposed pair goes unnoticed.
+pub(crate) struct SquashInputs<'a> {
+ pub target_branch: &'a str,
+ pub merge_base: &'a str,
+ pub commit_details: &'a [CommitMessageDetail],
+ pub current_branch: &'a str,
+ pub repo_name: &'a str,
+ pub config: &'a CommitGenerationConfig,
+ pub project_append: Option<&'a str>,
+ /// The temporary index `--dry-run` staged per the user's `--stage` mode,
+ /// read in place of the real one so the preview spans what a real run would
+ /// commit. A real run passes `None` — it has already staged the real index
+ /// — and so does `--show-prompt`, the cheap "what's already staged" path.
+ pub staging_index: Option<&'a TempIndex>,
+}
- // Prepare diff (may filter if too large)
- let prepared = prepare_diff(diff_output, diff_stat);
+impl SquashInputs<'_> {
+ /// The squash commit's message: generated by the configured LLM command, or
+ /// a deterministic list of the folded-in subjects when none is configured.
+ pub(crate) fn generate_message(&self) -> anyhow::Result<String> {
+ if self.config.is_configured() {
+ let command = self.config.command.as_ref().unwrap();
+ let prompt = self.prompt()?;
+
+ // See `generate_commit_message` — keep a slow squash-message
+ // generation from being silent.
+ let _watchdog = watch_llm_command(command);
+ return execute_llm_command(command, &prompt).map_err(|e| {
+ worktrunk::git::GitError::LlmCommandFailed {
+ command: command.clone(),
+ error: e.display_message(),
+ reproduction_command: Some(format_reproduction_command(
+ "wt step squash --show-prompt",
+ command,
+ )),
+ }
+ .into()
+ });
+ }
- let recent_commits = repo
- .current_worktree()
- .recent_commit_subjects(Some(merge_base), 5);
- let context = PromptContext {
- git_diff: &prepared.diff,
- git_diff_stat: &prepared.stat,
- branch: current_branch,
- recent_commits: recent_commits.as_ref(),
- repo_name,
- commit_details,
- target_branch: Some(target_branch),
- project_append,
- };
- build_prompt(config, TemplateType::Squash, &context)
+ let mut commit_message = format!("Squash commits from {}\n\n", self.current_branch);
+ commit_message.push_str("Combined commits:\n");
+ for detail in self.commit_details.iter().rev() {
+ // Reverse so they're in chronological order
+ commit_message.push_str(&format!("- {}\n", detail.subject));
+ }
+ Ok(commit_message)
+ }
+
+ /// Render the squash prompt from what the squash commit will record.
+ ///
+ /// Gathers the combined diff, commit message details, branch names, and
+ /// recent commits, then renders the prompt template. Used by normal squash
+ /// generation, `--show-prompt`, and `--dry-run`.
+ ///
+ /// The diff spans everything the one resulting commit records — the commits
+ /// since `merge_base` plus any working-tree changes folded in with them.
+ pub(crate) fn prompt(&self) -> anyhow::Result<String> {
+ let repo = Repository::current()?;
+ let wt = repo.current_worktree();
+
+ // Diff `merge_base` against the index, because the index is what the
+ // squash commits: `handle_squash` stages the working tree before
+ // generating this message and soft-resets to `merge_base` afterwards, so
+ // the index already holds everything the one resulting commit will
+ // record. `merge_base..HEAD` would name only the pre-existing commits
+ // and omit the working-tree changes folded into the same commit — and
+ // for `wt merge` on a dirty worktree those changes are the whole reason
+ // it ran, so the message came out describing the branch's older commits
+ // instead of the work just finished. With nothing staged the index
+ // matches `HEAD` and the two spans are the same diff, so this needs no
+ // second path. It also matches the stats `handle_squash` prints for the
+ // same commit.
+ let squashed = staged_diff(&wt, self.staging_index, self.merge_base);
+ let diff_output = squashed.capture(["--patch"])?;
+ let diff_stat = squashed.capture(["--stat"])?;
+
+ // Prepare diff (may filter if too large)
+ let prepared = prepare_diff(diff_output, diff_stat);
+
+ let recent_commits = wt.recent_commit_subjects(Some(self.merge_base), 5);
+ let context = PromptContext {
+ git_diff: &prepared.diff,
+ git_diff_stat: &prepared.stat,
+ branch: self.current_branch,
+ recent_commits: recent_commits.as_ref(),
+ repo_name: self.repo_name,
+ commit_details: self.commit_details,
+ target_branch: Some(self.target_branch),
+ project_append: self.project_append,
+ };
+ build_prompt(self.config, TemplateType::Squash, &context)
+ }
}
/// Synthetic diff for testing commit generation
@@ -1484,7 +1501,7 @@ mod tests {
context.project_append = Some("- Reference the related issue");
let prompt = build_prompt(&config, TemplateType::Squash, &context).unwrap();
assert_snapshot!(prompt, @r#"
- <task>Write a commit message for the combined effect of these commits.</task>
+ <task>Write a commit message for the change in <diff>, which is everything the squash will record. <commits> lists what it folds in.</task>
<format>
- Subject line under 50 chars
@@ -1540,7 +1557,7 @@ mod tests {
);
let prompt = build_prompt(&config, TemplateType::Squash, &context).unwrap();
assert_snapshot!(prompt, @r#"
- <task>Write a commit message for the combined effect of these commits.</task>
+ <task>Write a commit message for the change in <diff>, which is everything the squash will record. <commits> lists what it folds in.</task>
<format>
- Subject line under 50 chars
diff --git a/src/main.rs b/src/main.rs
index 8ec1c7d29..11458f565 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -237,9 +237,9 @@ fn handle_step_command(
}
// --show-prompt and --dry-run skip the squash and exit after preview output.
if args.show_prompt {
- commands::step_show_squash_prompt(args.target.as_deref())
+ commands::step_show_squash_prompt(args.target.as_deref(), args.stage)
} else if args.dry_run {
- commands::step_dry_run_squash(args.target.as_deref(), yes)
+ commands::step_dry_run_squash(args.target.as_deref(), args.stage, yes)
} else {
// Approval is handled inside handle_squash (like step_commit).
let repo = Repository::current()?;
diff --git a/tests/integration_tests/merge.rs b/tests/integration_tests/merge.rs
index cd5de3321..4c88c24c6 100644
--- a/tests/integration_tests/merge.rs
+++ b/tests/integration_tests/merge.rs
@@ -3120,6 +3120,59 @@ fn test_step_commit_first_commit_in_sha256_repo() {
);
}
+/// The squash commits the index, so its prompt must describe the working-tree
+/// changes folded in alongside the commits, and each preview must span what its
+/// own run would commit.
+///
+/// The prompt used to diff `merge_base..HEAD`, which named only the commits —
+/// so `wt merge` on a dirty worktree generated a message about the branch's
+/// older commits and said nothing about the work it had just staged into the
+/// same commit. `--dry-run` inherits that duty: it stages into a temp index the
+/// way a real run stages the real one, where `--show-prompt` deliberately shows
+/// only what is already staged.
+#[rstest]
+fn test_squash_prompt_covers_what_its_run_would_commit(repo_with_multi_commit_feature: TestRepo) {
+ let repo = repo_with_multi_commit_feature;
+ let feature_wt = repo.worktree_path("feature");
+ fs::write(feature_wt.join("staged.txt"), "staged content\n").unwrap();
+ repo.git_command()
+ .args(["add", "staged.txt"])
+ .current_dir(feature_wt)
+ .run()
+ .unwrap();
+ fs::write(feature_wt.join("unstaged.txt"), "unstaged content\n").unwrap();
+
+ let prompt_of = |args: &[&str]| {
+ let output = make_snapshot_cmd(&repo, "step", args, Some(feature_wt))
+ .output()
+ .unwrap();
+ assert!(output.status.success(), "{output:?}");
+ String::from_utf8(output.stdout).unwrap()
+ };
+
+ let shown = prompt_of(&["squash", "--show-prompt"]);
+ assert!(
+ shown.contains("staged.txt"),
+ "--show-prompt covers the staged change: {shown}"
+ );
+ for committed in ["file1.txt", "file2.txt"] {
+ assert!(
+ shown.contains(committed),
+ "--show-prompt still covers {committed}: {shown}"
+ );
+ }
+ assert!(
+ !shown.contains("unstaged.txt"),
+ "--show-prompt shows what is already staged, and nothing else: {shown}"
+ );
+
+ let dry = prompt_of(&["squash", "--dry-run"]);
+ assert!(
+ dry.contains("unstaged.txt") && dry.contains("staged.txt"),
+ "--dry-run covers everything a real squash would stage: {dry}"
+ );
+}
+
/// The commit and squash prompts split git's diff into per-file sections, so
/// the user's diff display settings must not change what the LLM receives.
#[rstest]
@@ -3595,7 +3648,7 @@ command = "cat >/dev/null && echo 'feat: missing-index'"
}
/// `wt step squash --show-prompt` propagates template errors from
-/// `build_squash_prompt`. A malformed jinja template must surface the failure
+/// `SquashInputs::prompt`. A malformed jinja template must surface the failure
/// rather than producing an empty prompt.
#[rstest]
fn test_step_squash_show_prompt_malformed_template(repo_with_multi_commit_feature: TestRepo) {
@@ -3625,7 +3678,7 @@ squash-template = "{% if commits"
}
/// `wt step squash --dry-run` propagates LLM-command failures from
-/// `generate_squash_message`. The prompt renders fine, but a non-zero exit
+/// `SquashInputs::generate_message`. The prompt renders fine, but a non-zero exit
/// from the configured command must be surfaced rather than swallowed.
#[rstest]
fn test_step_squash_dry_run_llm_failure(repo_with_multi_commit_feature: TestRepo) {
@@ -3633,7 +3686,7 @@ fn test_step_squash_dry_run_llm_failure(repo_with_multi_commit_feature: TestRepo
let feature_wt = repo.worktree_path("feature");
// `cat >/dev/null` consumes stdin first to avoid a broken-pipe race; the
- // command then exits non-zero so generate_squash_message bubbles the failure up.
+ // command then exits non-zero so `generate_message` bubbles the failure up.
let worktrunk_config = r#"
[commit.generation]
command = "cat >/dev/null; echo 'simulated LLM failure' >&2 && exit 1"
diff --git a/tests/snapshots/integration__integration_tests__help__help_config_create.snap b/tests/snapshots/integration__integration_tests__help__help_config_create.snap
index 59326ac4c..b8d2fd3a6 100644
--- a/tests/snapshots/integration__integration_tests__help__help_config_create.snap
+++ b/tests/snapshots/integration__integration_tests__help__help_config_create.snap
@@ -437,7 +437,7 @@ Creates ~/.config/worktrunk/config.toml with the following content:
  # <!-- DEFAULT_SQUASH_TEMPLATE_START -->
  # [commit.generation]
  # squash-template = """
-  # <task>Write a commit message for the combined effect of these commits.</task>
+  # <task>Write a commit message for the change in <diff>, which is everything the squash will record. <commits> lists what it folds in.</task>
  #
  # <format>
  # - Subject line under 50 chars
diff --git a/tests/snapshots/integration__integration_tests__help__help_config_long.snap b/tests/snapshots/integration__integration_tests__help__help_config_long.snap
index b93d1e51d..aa0789c1e 100644
--- a/tests/snapshots/integration__integration_tests__help__help_config_long.snap
+++ b/tests/snapshots/integration__integration_tests__help__help_config_long.snap
@@ -482,7 +482,7 @@ Default template:
  [commit.generation]
  squash-template = """
-  <task>Write a commit message for the combined effect of these commits.</task>
+  <task>Write a commit message for the change in <diff>, which is everything the squash will record. <commits> lists what it folds in.</task>
 
  <format>
  - Subject line under 50 chars
diff --git a/tests/snapshots/integration__integration_tests__merge__step_squash_dry_run.snap b/tests/snapshots/integration__integration_tests__merge__step_squash_dry_run.snap
index a171758dc..5ac04c6f5 100644
--- a/tests/snapshots/integration__integration_tests__merge__step_squash_dry_run.snap
+++ b/tests/snapshots/integration__integration_tests__merge__step_squash_dry_run.snap
@@ -59,7 +59,7 @@ success: true
exit_code: 0
----- stdout -----
PROMPT
-<task>Write a commit message for the combined effect of these commits.</task>
+<task>Write a commit message for the change in <diff>, which is everything the squash will record. <commits> lists what it folds in.</task>
<format>
- Subject line under 50 chars
diff --git a/tests/snapshots/integration__integration_tests__merge__step_squash_show_prompt.snap b/tests/snapshots/integration__integration_tests__merge__step_squash_show_prompt.snap
index 7759bc9a2..8d93889db 100644
--- a/tests/snapshots/integration__integration_tests__merge__step_squash_show_prompt.snap
+++ b/tests/snapshots/integration__integration_tests__merge__step_squash_show_prompt.snap
@@ -58,7 +58,7 @@ info:
success: true
exit_code: 0
----- stdout -----
-<task>Write a commit message for the combined effect of these commits.</task>
+<task>Write a commit message for the change in <diff>, which is everything the squash will record. <commits> lists what it folds in.</task>
<format>
- Subject line under 50 chars