SLOPSHOPPER

wt

The worktree you are in, as wt sees it: how far behind trunk, its own remote, and wt up, undo and push from a small dialog. Optional: open it in gittree, and…

panebandguardcommandtoaststatus
v0.2.0no licenseupdated 2026-10-22anders-lindstrom/wt/mods/wt
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · wt
│ ┃ wt ✕ › fix the failing auth test and add an audit log call │ ┃ No wt worktree here: this folder is not in a │ ┃ repository wt knows, or wt is not installed. ⏺ Read(src/auth.ts) │ ┃ ⎿ Read 6 lines │ ┃ r: refresh ⏺ Update(src/auth.ts) │ ┃ ⎿ Added 2 lines, removed 1 line │ ┃ q: close click here, or ctrl+x then tab, fo ⏺ Bash(bun test) │ ⎿ 3 pass, 1 fail │ │ ● Done. refresh now rejects expired claims and logs an audit event. │ │ ✻ Worked for 42s · done 4:20 PM │ │ › /wt │ ⎿ wt: No wt worktree here. │ │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · wt
No wt worktree here: this folder is not in a repository wt knows, or wt is not installed. r: refresh q: close click here, or ctrl+x then tab, for the keys
README

wt

Git worktree tooling: one implementation, per-repo configuration.

Replaces the ~1,580-line copy of worktree scripts that seven repositories each carried privately — copies that had drifted into two to four variants of nearly every file, to the point where the same bug was found and fixed twice, in two repos, with two incompatible fixes, and neither reached the other five.

Install

A release, with mise:

mise use -g github:anders-lindstrom/wt   # the newest release, kept on the PATH

Or built from a checkout:

git clone git@github.com:anders-lindstrom/wt.git && cd wt
./install.sh                 # builds to ~/.local/bin, installs to ~/.local/share/wt

Then in your shell rc, either way:

eval "$(wt shell)"

Repositories whose bin/worktree_functions.sh shim sources ~/.local/share/wt/worktree_functions.sh need that file; install.sh writes it, and on a mise install wt shell --compat prints it.

A release is a v* tag pushed to GitHub: the release workflow builds darwin and linux binaries with GoReleaser and attaches them to the release. scripts/release.sh patch|minor|major tags the next version on a merged HEAD and pushes it; landing a branch runs it.

While GitHub Actions minutes are exhausted, run scripts/release.sh patch first, then scripts/release-local.sh <tag> for the tag it pushed. The local runner uses act, Docker, and gh auth token to run the same release workflow. Run from a clean checkout at that tag; the tag must be on freshly fetched origin/main. It builds in a temporary clone with full history and tags. --plan runs act -n on the publishing path; --dry-run builds all four snapshot archives without publishing and prints their directory under dist/. Dry-run refuses older tags without the snapshot gate. Run previews and publishing sequentially: act shares job containers and caches. The workflow only honors snapshot mode under act; GitHub tag pushes still publish normally. The current GoReleaser config needs only GITHUB_TOKEN (no Homebrew tap token). A real run verifies GitHub release creation and asset uploads, which neither local preview mode exercises.

Setting up a repository

cd your-repo
wt init          # writes bin/worktree/worktree.conf
wt doctor        # check it

wt init asks for the three keys a repository actually varies, offering detected values as the defaults:

trunk (MAIN_BRANCH) [main]:
branch prefix [feat_wt]:
build command (blank for none): make build

Every other key is written commented at its default, so the file is this repository's reference for what it may set — uncommenting a line as it stands changes nothing. An answer that would not validate is rejected at the prompt, not written and then discovered by the next command:

  ! WORKTREE_BRANCH_PREFIX="wip_wt" yields default type "wip", which is not in
    WORKTREE_TYPES; set WORKTREE_DEFAULT_TYPE to choose one of: feat fix docs …

With --yes, or with no terminal to answer from, the detected values are written without asking — so a script, a hook or an agent gets the same result without hanging on a prompt. --force replaces a configuration already there; without it, an existing file is an error rather than something to overwrite.

A repository with no configuration works too: every command runs on what wt init --yes would write — trunk from origin's HEAD, else the first of development, main and master that exists here or on origin, the default prefix, no build command — detected on each run and never written to the repository. That is what lets a harness make worktrees in a clone nobody set up (the Claude Code hooks, for one). wt new says so in one line on stderr, wt config shows the values as detected, and wt doctor notes it without counting it as a problem. Nothing that runs code is detected: only a bin/worktree/provision.sh the repository itself carries runs. When not even trunk can be detected — no origin HEAD, and none of those three branches — wt does not take the checked-out branch for it: commands stop with "cannot tell which branch is trunk", wt init --yes refuses, and wt init asks you to name it.

If the config lands somewhere git ignores — a repo ignoring bin/ for its build output also ignores bin/worktree/ — wt init says so, because that configuration would work for you and for nobody who clones the repo.

Commands

Grouped the way wt --help groups them. Every command carries worked examples: wt <command> --help.

Make a worktree

wt new <type>/<work>create a branch and worktree, then provision it (--base, --no-setup, --no-build, --no-cache, --no-superset, --dry-run)
wt checkout <branch> [<work>]put a worktree on a branch that already exists; <remote>/<branch>, or a bare name only one remote has, creates the local branch tracking it, from the refs as last fetched; also wt co (--dry-run)
wt pr checkout [<number>]put a worktree on a pull request; with no number, pick one from the open ones, your review queue first
wt pr listevery open pull request, its state and checks, and the worktree on it
wt pr open [<work>]open a worktree's pull request in the browser; with no argument, the one you are in

Get to your work

wt cd [<pattern>]cd to a worktree, in this shell; . is the one you are in, bare or / the main checkout
wt exec <pattern> <cmd>…run a command there, in a subshell; your shell stays put
wt attach [<pattern>] [<session>]open the Claude session in a worktree, in this terminal; asks which when there are several; --resume continues a conversation there instead
wt session list [<work>], wt session send <work> [<session>], wt session stop <work> [<session>]the Claude sessions in a worktree with their inboxes; one message from stdin to one running session's inbox (--from-name, --reply-to, --expect-session, --message-file, --dry-run, --json). A parked session is never sent to. stop runs claude stop on one background session (--expect-session, --dry-run, --json); a terminal or Codex session is refused
wt listevery worktree, in any layout; s marks Superset's, t T3 Code's, ! one nothing owns; a PR column when a worktree here has one, with ✓ ✗ ● for its checks, asked for by branch and cached for a few minutes (--no-pr, --refresh); a SESSION column when one has a Claude session in it and the terminal is wide enough for it (--wide whatever the width, --no-sessions); --all, --roots, --profile for many repositories
wt status [<work>]each worktree's branch, whether its checkout is clean, and how far behind and ahead of trunk it is; with a worktree named, that one in full with wt sync's verdict; wt list's PR column and cache (--no-pr, --refresh; --all, --roots, --profile for many repositories)
wt find <pattern>resolve a worktree by fuzzy name, across repositories (--candidates)
wt path <work> / wt branch <work>where a piece of work lives or would go, and its branch; exact, this repository only, for scripts
wt port [<work>]the port a worktree's dev server should use: a hash of the repository and the branch, in 10000–19999, stable per branch; provision.sh and the build get it as WT_PORT. Nothing is reserved: devports says whether it is free
wt reposevery repository wt manages under your roots, with its worktrees and whether wt sync is set up (--all, --roots, --profile, --paths)

Keep up with trunk

wt up [<work>]sync the worktree you are in with trunk by rebasing it, only if it goes through without you — conflict-free, or every stop resolved by .wt-sync.yaml; otherwise it touches nothing and says why. Also where trunk declares no .wt-sync.yaml, conflict-free only. The short form of wt sync rebase . --if-ready (--push, --no-push, --no-fetch, --yes/-y for yes to everything including the push, --force/-f to go ahead past an agent session in it)
wt status <work> --json / wt up --jsona worktree's plan for wt up, and a run's result, as one JSON object each for tools driving wt (--expect holds a run to its plan); wt schema prints their JSON Schemas, and docs/json.md explains them
wt sweep --dry-run --json / wt sweep --yes --jsona sweep's plan, every row with why it is merged or kept, and a sweep's result row by row, for tools driving wt (--expect holds the sweep to its plan); see docs/json.md
wt remove <work> --dry-run --json / wt remove <work> --yes --jsona removal's plan — where the branch stands, every reason it would refuse, what it would lose — and its result effect by effect, for tools driving wt (--expect holds the removal to its plan)
wt restore <dir> --dry-run --json / wt restore <dir> --jsonwhat putting back a worktree moved to a folder would do to its branch, and what it did; recovery.json in the folder is itself versioned (wt schema recovery)
wt purge <dir> --json / … --yes --jsonwhat deleting a removed worktree's folder for good would delete and leave unreachable, with a token, and what became of each pin and the folder (--expect holds the purge to its plan)
wt session list --json, wt session send --json, wt session stop --jsonthe sessions with their inboxes, and the outcome of a message or a stop; see docs/json.md
wt refs sweep, restore, purge --json; wt refs swept --jsoneach plan with a token and each result row by row, for the ref sweep; see docs/json.md
wt sync --json / `wt sync rebase\resume\undo --json`the sync overview of every worktree, and a verb's result, as JSON for tools (wt sync rebase --expect holds a run to the overview); wt schema sync and wt schema sync-run
wt new … --dry-run --json / wt new … --jsonthe same for creating a worktree, and for wt checkout: the plan with a token, and a result naming every side effect (--expect refuses a moved base or branch)
wt syncwhat rebasing each worktree onto trunk would do, simulated after fetching trunk; changes nothing of yours (--no-fetch)
wt sync rebase [<work>...]sync the named worktrees by rebasing them onto trunk, with the declared strategies (--no-fetch, --yes/-y, --push, --no-push, --if-ready); also spelled wt sync <work>... --rebase. With nothing named, every worktree the table calls ready except recipe?, asked first — and with no terminal, only with --yes. --if-ready rebases what is ready and fails if anything was not. The push question defaults to no; --yes answers yes to it, like every question, unless --no-push
wt sync resume <work>continue the rebase a run left at a conflict that was yours (--yes/-y, --push, --no-push); also spelled wt sync <work> --resume
wt sync undo <work>put back every ref the last wt sync rebase on this worktree moved, aborting a rebase a run handed over (--force/-f, --yes/-y); also spelled wt sync <work> --undo
wt sync doctorcheck what a run needs; --fix turns on rerere and removes expired locks, --prune deletes old safety refs; a keeper row says whether one is installed and how its last pass went
wt sync keep onceone unattended pass: fetch trunk and, when it moved, rebase every ready worktree nobody is in and push what finished (--no-push); keep run still works; logged to .git/wt-sync-keep.log; what the job runs, and what cron runs elsewhere
wt sync keep startinstall a launchd job (macOS) that runs wt sync keep once every 30 minutes (--every, --no-push), pushing the way this shell's git does; wt sync keep status for the last pass and the next, wt sync keep stop to remove it; --all, --roots or --profile on all three for many repositories

Put worktrees in their place

wt migrate <work> [<type>/<name>]move a worktree where it belongs, renaming or retyping it on the way (--dry-run, --force/-f); also wt move
wt adopt <path>provision a worktree another tool created (--relocate, --no-build, --no-cache)
wt setup [<from-dir>]provision the worktree you are in (--no-build, --no-cache, --source to name what ran it)
wt remove <work>remove a worktree; delete its branch when merged — on trunk, or as a pull request the cache says landed — keep it when not (--yes, --dry-run, . for the one you are in, --force/-f past a session, a held lock or hidden files, --force=<list> past only those named, --move-to <dir> to move it into a folder instead of deleting it, --keep-superset, --reap to stop the dev servers and watchers still running in it first (not ones started in a terminal), --json, --expect)
wt restore <dir>put back a worktree --move-to moved into <dir>, and its branch, from the recovery.json there (--dry-run, --json)
wt purge <dir>delete a worktree --move-to moved into <dir> for good: the refs pinning its commits, then the folder; refuses a folder no removal made or one a removal or restore left half-way, and finishes a purge that stopped (--yes, --dry-run, --json, --expect)
wt sweepdelete local branches already merged into trunk — or whose pull request GitHub merged — and remove the worktrees on such branches that nothing is using; from the main checkout only (--no-fetch, --yes, --dry-run, --json, --expect, --move-to <dir>, --keep-superset, --reap to stop what still runs in them instead of keeping them), or across repositories with --all, --roots, --profile
wt refs sweepmove backup branches and tags (backup/*, safe-* and the like) that another ref contains, or older than ref_sweep_age, to pins under refs/wt-swept/<run>/; wt refs swept lists runs, wt refs restore <run> puts one back, wt refs purge deletes pins for good (--remote, --only, --run-id, --yes, --dry-run, --json, --expect)

This repository, and this build

wt initcreate this repository's worktree.conf, pinning what wt otherwise detects on each run (--yes to skip the prompts, --force/-f to replace one)
wt config [--shell]the resolved configuration, typed or eval-able
wt config get/set/unset/pathyour own settings, per machine, from anywhere
wt doctorcheck config, required tools and worktree health, and your roots and profiles; --all, --roots, --profile check every repository, wt sync doctor included where it is set up
wt about / wt versionwhich build this is and what changed; the version alone, for scripts
wt completion zshshell completion, including live work names

A bare <work> takes the repository's default type, so wt new thing creates feat_wt/thing. <work> matches exactly, inside this repository, and is what every command that changes or deletes takes; <pattern> (cd, exec, find) is fuzzy and searches your other repositories too.

Many repositories

wt knows where your repositories live: your roots, set per machine.

# ~/.config/wt/config.toml
[roots]
work = "~/src/work"        # a folder: every repository one level down
oss = "~/src/oss"
dotfiles = "~/dotfiles"    # a repository: that one, searched no deeper

[profiles]
api = ["~/src/work/api", "~/src/work/billing"]

wt config set root.work ~/src/work and wt config set profile.api "<dir> <dir>" write them; WT_ROOTS overrides the table. Only repositories with a bin/worktree configuration count.

  • wt repos lists them, and wt cd <repo> goes to one.
  • wt sweep --all and wt sync --all --rebase work across every one, planned a few at a time and asked once; wt sync --all is the overview of each. --roots work or --profile api narrows the run.
  • wt list, wt status and wt doctor take the same flags.
  • wt doctor checks that every root is there and every profile entry is still a repository wt manages, inside a root.

Shell functions

A binary cannot change its caller's directory. These do:

wt_cd <pattern>the same as wt cd, if you prefer the underscore form
wt_exec <pattern> <cmd>…run a command there, in a subshell; your shell stays put
wt_attach [<pattern>] [<session>]the same as wt attach
wt_dir <pattern>print the path (stdout is path-only)
wt_ls [pattern]list worktrees, or show what a pattern matches
wt_rm_meremove the worktree you are standing in

wt cd, wt exec and wt attach are the same functions under a nicer name: wt is itself a shell function that handles those three and passes everything else to the binary. The first two are there because a process cannot change its caller's directory, and wt attach because your shell's claude may be a function of your own, which only your shell can call.

They are thin wrappers over wt find; the matching itself lives in the binary where it is tested. A pattern of . is the worktree you are standing in, and / the repository's main checkout.

Layout

<parent>/<repo>_wt/<type>_wt/<work>          branch: <type>_wt/<work>

code/
├─ myrepo/                                    ← the repo
└─ myrepo_wt/
   ├─ feat_wt/api-tidy/                       branch: feat_wt/api-tidy
   └─ fix_wt/login-crash/                     branch: fix_wt/login-crash

The path tail below <repo>_wt/ is character-for-character the branch name, so the two convert with no rules to remember. Why the layout is this shape, and the rules a tool building on it follows: docs/worktree-conventions.md.

Branches without the _wt

The _wt on a branch is one setting. A repository whose branches should read fix/login-crash says so in its own file:

WORKTREE_BRANCH_SUFFIX=""

and a person who wants that wherever the repository has not decided says so in theirs, once, for every repository they work in:

wt config set branch_suffix ""      # or "-wt", or whatever yours carry

The worktrees do not move for it. The folders are wt's layout, not a name anybody types, and they keep the suffix WORKTREE_TYPE_SUFFIX gives them:

code/
├─ myrepo/                                    ← the repo
└─ myrepo_wt/
   ├─ feat_wt/api-tidy/                       branch: feat/api-tidy
   └─ fix_wt/login-crash/                     branch: fix/login-crash

The repository outranks the person, but only where it said something: a committed file that never mentions the suffix is not a decision, so whoever clones it may still name their own branches. wt config and wt doctor both print which file decided.

What the suffix buys, and what dropping it costs: a suffixed branch says at a glance that wt made it, and wt remove renames an unmerged one out of the prefix to keep its commits (fix_wt/login-crash → login-crash). Without one, any <word>/<name> branch — dependabot/npm-x, an agent's own claude/… — reads as a worktree branch of type <word>. Nothing breaks: every lookup still goes through git worktree list, so only the names change.

What each type is called

feat or feature, docs or doc: the word is a preference, and the type underneath it is not. Name the ones you want called something else, in the repository's file or in your own:

WORKTREE_TYPE_NAMES=(feat=feature docs=doc)      # the repository's naming
wt config set type_names "feat=feature"          # or yours, everywhere
$ wt new feat/login-crash        # or feature/login-crash: the same work
  ~/src/myrepo_wt/feat_wt/login-crash        branch: feature/login-crash

The type is the identity — a fix is a fix whether its branches say fix, fix_wt or bugfix — so it is what the folders carry and what every command reasons in. Only the branch reads the word, which is why renaming one strands no checkout, and why a branch named before the change still resolves.

Everything takes both spellings: wt new, wt migrate, wt path, wt branch, the type read out of a bare name (wt new feature_dev-123), the type read off somebody else's pull request branch, and the completions, which offer the words you would type. The same two-file rule as the suffix applies — the repository where it named its types, you everywhere else — and a pair for a type a repository does not have is a name for somewhere else, so it quietly does not apply there.

Two names for one type, or a name that is already another type, would make a branch ambiguous; the repository's file is told so, and your own pairs are dropped where they would collide.

The type comes from the spec — wt new fix/login-crash — or, for a bare name, is read out of the name itself: wt new fix_dev-123 creates fix_wt/dev-123. A name whose first word is not a type is left whole, and an explicit <type>/<work> always wins. This is what lets the type survive a tool that has nowhere to enter one; Superset mints every branch from a single fixed prefix.

Worktrees in other layouts keep working. Every lookup goes through git worktree list, never the shape of a path, so worktrees made by Superset, by T3 Code, by plain git worktree add, or before a repo was migrated all resolve.

Superset's layout

Superset builds <parent>/<repo>_wt/<repo>/<type>_wt/<work> — the canonical path with the repository name repeated, because it joins its per-project worktree base directory with <repo>/<branch>. No setting on either side removes that segment.

wt treats it as a layout of its own rather than a fault. wt setup provisions a Superset workspace where it stands and never moves it, wt doctor passes it, and wt list marks it s. Only ! — a layout nothing owns, such as a pre-migration <repo>-<work> checkout — is a wt migrate candidate, because Superset stores the absolute path of every workspace and a move leaves that workspace pointing at nothing. wt migrate says so before it moves.

T3 Code's layout

T3 Code builds <worktrees directory>/<repo>/t3-<hex>, one directory for every repository, set by worktreesDirectory in ~/.t3/userdata/settings.json. wt list marks these t, wt doctor passes them and wt setup provisions them in place. See T3 Code's worktrees.

Worktrees wt makes show up in Superset

Off until you turn it on. Superset is a per-person choice, so nothing here happens until:

wt config set superset true

After that, wt new, wt checkout and wt pr checkout hand the worktree to Superset once it is provisioned, so one started from the shell appears in the app beside the ones started there. Superset adopts the checkout git already has — it creates nothing and moves nothing, and the workspace points at wt's canonical path.

This needs all three of: the superset CLI, on the PATH or at ~/.superset/bin/superset where the desktop app installs it; the host service running, which means the app is open; and this repository already one of Superset's projects. A machine with no Superset, and a repository Superset does not track, are ordinary states and pass in silence. A Superset that is there and would not answer is one line on stderr and nothing else — wt new still prints only the path on stdout and still exits the same way. wt never starts the app and never creates a project. wt doctor reports which of the three it found, whatever the mode.

Registering a branch that already has a workspace is Superset's own no-op, so running it twice changes nothing. A new workspace makes Superset run the project's setup step if it has one, which for these repos is wt setup --source superset: a

Source 2 files
hooks/register.tsx 1262 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register } from 'claude-code'
3
4import type { Busy, Input, Outcome, Plan, Review } from '../types'
5
6// The worktree the session stands in, as `wt status --json` reports it: one
7// line above the prompt in git's marks, the part of it that is wrong in the
8// warning colour, and a small dialog (`/wt`, or a click on that line) where
9// the keys act. Nothing is pinned under the prompt: the engine draws a mod's
10// notice there as a warning whatever it says. Every action is a wt command the person pressed or
11// typed; nothing here rebases, pushes or undoes by itself.
12//
13// Two knobs, off unless the person's settings turn them on, each a section of
14// its own that reads nothing of wt's but the worktree's path: `gittree` (open
15// the worktree in gittree) and `reviewStatus` (when this conversation last ran
16// a review skill, and when the person last typed: above the prompt once each
17// is old, and in the dialog).
18
19type Engine = EngineInterface
20type Loose = Record<string, any>
21type Ran = { exitCode: number; stdout: string; stderr: string }
22type Action = 'up' | 'upDiverged' | 'undo' | 'push' | 'resume' | 'fetch' | 'refresh' | 'details' | 'close' | 'dismiss' | 'gittree'
23type Tone = 'suggestion' | 'success' | 'warning' | 'error'
24// One part of the line above the prompt, in the colour that says how it is:
25// none when it is as it should be.
26type Part = { text: string; tone: Tone | 'dim' | undefined; isOwn?: true }
27type Note = Part
28// What the dialog shows for a worktree: what is not as it should be, and the
29// keys, the one that moves the branch on a row of its own.
30type Detail = { notes: Note[]; primary: Action | null; hint: string; follow: Action[]; other: Action[] }
31
32const PANE = 'wt'
33const TEN_MINUTES = 600_000
34const PULSE_MS = 10_000
35// Past this, what is shown about trunk says how old it is.
36const STALE_MS = 60 * 60_000
37
38const plan = atom({ plugin: 'wt', key: 'plan' } as const, null)
39const busy = atom({ plugin: 'wt', key: 'busy' } as const, 'idle')
40const outcome = atom({ plugin: 'wt', key: 'outcome' } as const, null)
41const inputs = atom({ plugin: 'wt', key: 'inputs' } as const, 0)
42const lastInput = atom({ plugin: 'wt', key: 'lastInput' } as const, null)
43const lastReview = atom({ plugin: 'wt', key: 'lastReview' } as const, null)
44const firstInput = atom({ plugin: 'wt', key: 'firstInput' } as const, null)
45
46// The knobs as the person's settings have them; `register` fills them in.
47// A skill that performs a review: "review" in its name, and not the one about
48// receiving one.
49const REVIEW_SKILLS = '^(?!.*receiving).*review'
50const knobs = {
51  hasGittree: false,
52  hasReview: false,
53  reviewSkills: new RegExp(REVIEW_SKILLS, 'i'),
54  // How old the last input and the last review are before the line above
55  // the prompt says them.
56  inputAfterMs: 5 * 60_000,
57  reviewAfterMs: 30 * 60_000,
58}
59
60const LABEL: Record<Action, string> = {
61  up: 'wt up',
62  upDiverged: 'wt up over the divergence',
63  undo: 'undo',
64  push: 'push…',
65  resume: 'resume',
66  fetch: 'fetch',
67  refresh: 'refresh',
68  details: '/wt',
69  close: 'close',
70  dismiss: 'dismiss',
71  gittree: 'gittree',
72}
73// On the line above the prompt gittree is a word to click: the arrow says it
74// opens somewhere else.
75const GITTREE_OUT = 'gittree ↗'
76// The dialog's keys are letters: it holds the keyboard while it is open.
77const HOTKEY: Partial<Record<Action, string>> = {
78  up: 'u',
79  upDiverged: 'v',
80  undo: 'z',
81  push: 'p',
82  resume: 'c',
83  fetch: 'f',
84  refresh: 'r',
85  gittree: 'g',
86  dismiss: 'd',
87  close: 'q',
88}
89// Said beside the dialog's close key: how it goes away while it holds the
90// keyboard, and how it gets the keyboard when it opened without it.
91const CLOSING = 'Esc closes too'
92const KEYLESS = 'click here, or ctrl+x then tab, for the keys'
93const RUNNING: Record<Busy, string> = {
94  idle: '',
95  up: 'wt up is running: fetch, fast-forward, rebase…',
96  undo: 'wt sync undo is running…',
97  resume: 'wt sync resume is running…',
98}
99
100const parse = (text: string): Loose | null => {
101  try {
102    const value: unknown = JSON.parse(text)
103
104    return value !== null && typeof value === 'object' ? (value as Loose) : null
105  } catch {
106    return null
107  }
108}
109
110const short = (sha: unknown): string => (typeof sha === 'string' && sha !== '' ? sha.slice(0, 7) : '?')
111const lastLine = (text: string): string => text.trim().split('\n').pop()?.trim() ?? ''
112
113// How long ago, in the fewest words that stay true.
114const ago = (now: number, at: number): string => {
115  const minutes = Math.max(0, Math.round((now - at) / 60_000))
116
117  if (minutes < 1) {
118    return 'just now'
119  }
120
121  return minutes < 90
122    ? `${minutes} min ago`
123    : minutes < 2_880
124      ? `${Math.round(minutes / 60)}h ago`
125      : `${Math.round(minutes / 1_440)} days ago`
126}
127
128const inputsSince = (count: number): string => (count === 0 ? 'no input since' : count === 1 ? '1 input since' : `${count} inputs since`)
129
130// What the review knob puts on the line above the prompt: the last input and
131// the last review, each only once it is older than its limit. A conversation
132// no review has run in is as old as its first input.
133const lingerOf = (typed: Input | null, review: Review | null, first: number | null, count: number, now: number): string => {
134  const parts: string[] = []
135
136  if (typed !== null && now - typed.at >= knobs.inputAfterMs) {
137    parts.push(`last input ${ago(now, typed.at)}: “${typed.head}”`)
138  }
139
140  if (review !== null) {
141    if (now - review.at >= knobs.reviewAfterMs) {
142      parts.push(`reviewed ${ago(now, review.at)}, ${inputsSince(count - review.inputs)}`)
143    }
144  } else if (first !== null && now - first >= knobs.reviewAfterMs) {
145    parts.push(`not reviewed yet, ${count === 1 ? '1 input' : `${count} inputs`}`)
146  }
147
148  return parts.join(' · ')
149}
150
151const planOf = (stdout: string): Plan | null => {
152  const s = parse(stdout)
153
154  if (s === null || s.command !== 'status' || s.worktree === null || typeof s.worktree !== 'object') {
155    return null
156  }
157
158  const w: Loose = s.worktree
159  const own: Loose | null = w.ownRemote ?? null
160  const stack: Loose[] = Array.isArray(s.stack) ? s.stack : []
161  const sessions: Loose[] = Array.isArray(s.sessions) ? s.sessions : []
162
163  return {
164    work: String(w.work),
165    branch: typeof w.branch === 'string' && w.branch !== '' ? w.branch : null,
166    path: String(w.path),
167    isMain: w.isMain === true,
168    trunk: String(s.trunk ?? ''),
169    trunkRef: String(s.trunkRef ?? s.trunk ?? ''),
170    trunkFetchedAt: s.trunkRefUpdatedAt ?? null,
171    gitDir: null,
172    fetchedAt: null,
173    trunkRemoteAhead: Number(s.trunkSync?.remoteAhead ?? 0),
174    behind: typeof w.behind === 'number' ? w.behind : null,
175    ahead: typeof w.ahead === 'number' ? w.ahead : null,
176    tree: String(w.state ?? 'clean'),
177    ownRemote:
178      own === null
179        ? null
180        : {
181            ref: own.ref ?? null,
182            state: String(own.state),
183            ahead: own.ahead ?? null,
184            behind: own.behind ?? null,
185            blocks: own.blocks ?? null,
186            noPushReason: typeof own.noPushReason === 'string' ? own.noPushReason : null,
187            fixCommand: Array.isArray(own.fixCommand) ? own.fixCommand.map(String) : null,
188          },
189    upEligible: s.upEligible === true,
190    upIneligibleCode: s.upIneligibleCode ?? null,
191    upIneligibleReason: s.upIneligibleReason ?? null,
192    token: s.token ?? null,
193    stack: stack.map(member => String(member.work)).filter(name => name !== String(w.work)),
194    sessions: sessions.map(one => ({ name: String(one.name), kind: String(one.kind), state: String(one.state) })),
195    sessionsError: typeof s.sessionsError === 'string' ? s.sessionsError : null,
196    schemaVersion: String(s.schemaVersion ?? ''),
197  }
198}
199
200// The remote a ref lives on: "origin" of "origin/feat/login".
201const remoteOf = (ref: string): string => ref.split('/')[0] ?? ref
202
203// The branch against trunk in marks: ↓ what trunk has that it lacks, ↑ its own
204// on top, ✓ when it lacks nothing, ? when wt could not count.
205const trunkMarks = (p: Plan): string =>
206  p.behind === null ? '?' : `${p.behind > 0 ? `↓${p.behind}` : '✓'}${p.ahead !== null && p.ahead > 0 ? `↑${p.ahead}` : ''}`
207
208// The branch against its own remote in the same marks, then the remote's
209// name; undefined when there is nothing to say (in sync, or no ref of its own).
210const ownMarks = (p: Plan): string | undefined => {
211  const own = p.ownRemote
212
213  if (own === null || own.ref === null) {
214    return undefined
215  }
216
217  const remote = remoteOf(own.ref)
218
219  switch (own.state) {
220    case 'rebased':
221      return `↑ ${remote} (rebased)`
222    case 'ahead':
223      return `↑${own.ahead ?? ''} ${remote}`
224    case 'behind':
225      return `↓${own.behind ?? ''} ${remote}`
226    case 'diverged':
227      return `↓${own.behind ?? ''}↑${own.ahead ?? ''} ${remote} diverged`
228    case 'gone':
229      return `✗ ${remote}`
230    default:
231      return undefined
232  }
233}
234
235// The same in words, for the dialog.
236const ownWords = (p: Plan): string | undefined => {
237  const own = p.ownRemote
238
239  if (own === null) {
240    return undefined
241  }
242
243  // wt's own sentence, and the command it names for it.
244  if (own.noPushReason !== null) {
245    return `nowhere to push: ${own.noPushReason}${own.fixCommand === null ? '' : `. ${own.fixCommand.map(quoted).join(' ')} records the first`}`
246  }
247
248  if (own.ref === null) {
249    return undefined
250  }
251
252  switch (own.state) {
253    case 'rebased':
254      return `rebased and not pushed to ${own.ref} yet`
255    case 'ahead':
256      return `${own.ahead} to push to ${own.ref}`
257    case 'behind':
258      return `${own.behind} behind ${own.ref}`
259    case 'diverged':
260      return `diverged from ${own.ref}: ${own.ahead} here, ${own.behind} there`
261    case 'gone':
262      return `${own.ref} is gone`
263    case 'unknown':
264      return `${own.ref} could not be checked`
265    default:
266      return undefined
267  }
268}
269
270// How old what is known about trunk is, once that is worth saying: nothing
271// here fetches, so a count against trunk is as of the last fetch anyone made.
272const staleWords = (p: Plan, now: number): string | undefined =>
273  p.fetchedAt !== null && now - p.fetchedAt > STALE_MS ? `fetched ${ago(now, p.fetchedAt)}` : undefined
274
275const ownBehind = (p: Plan): number => (p.ownRemote?.state === 'behind' ? (p.ownRemote.behind ?? 0) : 0)
276const behindTrunk = (p: Plan): number => p.behind ?? 0
277
278// Why `wt up` would not run on it as it stands, or undefined when it would.
279// Changes in the tree are not judged here: status counts untracked files and
280// the run refuses tracked changes only, so the run is the one to say.
281const obstacle = (p: Plan): string | undefined => {
282  if (!p.upEligible) {
283    return p.upIneligibleReason ?? p.upIneligibleCode ?? 'wt would refuse it'
284  }
285
286  const working = p.sessions.filter(one => one.state === 'busy').map(one => one.name)
287
288  return working.length > 0 ? `another session is working in it (${working.join(', ')})` : undefined
289}
290
291const hasWork = (p: Plan): boolean => behindTrunk(p) > 0 || ownBehind(p) > 0
292const canUp = (p: Plan): boolean => !p.isMain && p.token !== null && hasWork(p) && obstacle(p) === undefined
293
294// The worktree as the parts of one line: against trunk, against its own
295// remote, a rebase waiting, a run wt would refuse, how old the view of trunk
296// is. What wt up would do something about is in the accent colour, and only
297// while wt up would run; what is wrong is in the warning colour, and comes
298// before what is dim, so that a narrow terminal cuts the dim part first.
299const standing = (p: Plan, now: number): Part[] => {
300  const parts: Part[] = []
301
302  if (p.isMain) {
303    parts.push({ text: p.trunkRemoteAhead > 0 ? `main checkout ↓${p.trunkRemoteAhead} ${remoteOf(p.trunkRef)}` : 'main checkout', tone: undefined })
304  } else {
305    const own = ownMarks(p)
306    const state = p.ownRemote?.state
307    const isHandedOver = p.upIneligibleCode === 'handedOver'
308    const wouldRun = !isHandedOver && obstacle(p) === undefined
309    // Uncommitted changes, as a git prompt marks them, after the last mark.
310    const dirty = !isHandedOver && p.tree === 'dirty' ? ' *' : ''
311    parts.push({
312      text: `${p.work} ${trunkMarks(p)} ${p.trunk}${own === undefined ? dirty : ''}`,
313      tone: wouldRun && behindTrunk(p) > 0 ? 'suggestion' : undefined,
314    })
315
316    if (own !== undefined) {
317      parts.push({
318        text: `${own}${dirty}`,
319        tone: state === 'diverged' || state === 'gone' ? 'warning' : wouldRun && state === 'behind' ? 'suggestion' : undefined,
320        isOwn: true,
321      })
322    }
323
324    if (isHandedOver) {
325      parts.push({ text: 'REBASE STOPPED', tone: 'warning' })
326    } else if (!wouldRun && hasWork(p)) {
327      parts.push({ text: 'wt up would refuse', tone: 'warning' })
328    }
329  }
330
331  const stale = staleWords(p, now)
332
333  if (stale !== undefined) {
334    parts.push({ text: stale, tone: 'dim' })
335  }
336
337  return parts
338}
339
340// The same as text, for a command's answer.
341const statusText = (p: Plan | null, now: number): string | undefined =>
342  p === null
343    ? undefined
344    : standing(p, now)
345        .map(part => part.text)
346        .join(' · ')
347
348// The line above the prompt, or null outside a worktree of wt's: a run under
349// way, what the last run came to, or how the worktree stands.
350const lineOf = (p: Plan | null, last: Outcome | null, state: Busy, now: number): Part[] | null => {
351  if (state !== 'idle') {
352    return [{ text: RUNNING[state], tone: 'suggestion' }]
353  }
354
355  // An outcome is shown, and acted on, only for the worktree it was run on.
356  // It never hides what is wrong with the worktree as it stands now, and one
357  // that succeeded is followed by what is left to push.
358  if (last !== null && p !== null && last.path === p.path) {
359    return [
360      { text: last.brief, tone: last.isOk ? 'success' : 'error' },
361      ...standing(p, now).filter(part => part.tone === 'warning' || (last.isOk && part.isOwn === true)),
362    ]
363  }
364
365  if (p === null || p.isMain) {
366    return null
367  }
368
369  return standing(p, now)
370}
371
372// What the dialog shows for the worktree; `mine` is the last outcome when it
373// is this worktree's.
374const detailOf = (p: Plan, mine: Outcome | null): Detail => {
375  const notes: Note[] = []
376  const isHandedOver = p.upIneligibleCode === 'handedOver'
377  const own = ownWords(p)
378  const why = p.isMain || isHandedOver ? undefined : obstacle(p)
379
380  if (p.isMain && p.trunkRemoteAhead > 0) {
381    notes.push({ text: `local ${p.trunk} is ${p.trunkRemoteAhead} behind ${p.trunkRef}`, tone: 'warning' })
382  }
383
384  if (own !== undefined) {
385    const state = p.ownRemote?.state
386    const isUnpushed = p.ownRemote?.noPushReason != null
387    notes.push({ text: own, tone: state === 'diverged' || state === 'gone' ? 'error' : state === 'behind' || isUnpushed ? 'warning' : undefined })
388  }
389
390  if (!p.isMain && p.tree !== 'clean') {
391    notes.push({ text: p.tree === 'dirty' ? '* uncommitted changes (untracked files count)' : `the tree is ${p.tree}`, tone: 'warning' })
392  }
393
394  if (p.stack.length > 0) {
395    notes.push({ text: `moves with ${p.stack.join(', ')}`, tone: undefined })
396  }
397
398  if (p.sessionsError !== null) {
399    notes.push({ text: `sessions could not be listed: ${p.sessionsError}`, tone: 'warning' })
400  } else if (p.sessions.length > 0) {
401    notes.push({ text: `sessions: ${p.sessions.map(one => `${one.name} (${one.kind}, ${one.state})`).join(', ')}`, tone: undefined })
402  }
403
404  // Why there is no key for wt up, for someone who looked for it: said only
405  // when wt counted, and the count is none.
406  if (!p.isMain && !isHandedOver && p.behind === 0 && ownBehind(p) === 0 && mine === null && p.upIneligibleCode !== 'ownRemoteDiverged') {
407    notes.push({ text: 'not behind: wt up has nothing to do', tone: 'dim' })
408  }
409
410  if (isHandedOver) {
411    notes.push({ text: 'a rebase stopped at a conflict and is yours: resolve it in the worktree, then resume; or undo it', tone: 'warning' })
412  } else if (why !== undefined && (hasWork(p) || p.upIneligibleCode === 'ownRemoteDiverged')) {
413    notes.push({ text: `wt up would refuse: ${why}`, tone: 'warning' })
414  }
415
416  let primary: Action | null = null
417  let hint = ''
418  const follow: Action[] = []
419
420  if (isHandedOver) {
421    primary = 'resume'
422    hint = 'once the conflict is resolved'
423    follow.push('undo')
424  } else if (canUp(p)) {
425    primary = 'up'
426    hint = `fetches, then rebases onto ${p.trunkRef}; never pushes`
427  } else if (p.upIneligibleCode === 'ownRemoteDiverged' && p.token !== null) {
428    primary = 'upDiverged'
429    hint = 'rebases although the branch diverged from its own remote'
430  }
431
432  if (mine !== null) {
433    if (mine.pushCommand !== null) {
434      follow.push('push')
435    }
436
437    if (mine.canUndo && !follow.includes('undo')) {
438      follow.push('undo')
439    }
440
441    follow.push('dismiss')
442  }
443
444  return { notes, primary, hint, follow, other: knobs.hasGittree ? ['fetch', 'gittree', 'refresh'] : ['fetch', 'refresh'] }
445}
446
447const failed = (action: Outcome['action'], p: Plan, text: string, brief: string): Outcome => ({
448  action,
449  work: p.work,
450  path: p.path,
451  isOk: false,
452  text,
453  brief: `✗ ${brief}`,
454  pushCommand: null,
455  canUndo: false,
456})
457
458// The results that mean a participant is where the run meant to leave it.
459const SETTLED: readonly string[] = ['rebased', 'fastForwarded', 'skipped', 'undone']
460const RESULT_WORDS: Record<string, string> = {
461  handedOver: 'stopped at a conflict',
462  notRun: 'was not run',
463  refused: 'was refused',
464  restored: 'failed and was put back',
465  needsRecovery: 'needs recovery',
466  interrupted: 'was interrupted',
467  rebasedStepFailed: 'was rebased, but a step after it failed',
468}
469
470// One wt run's JSON (`wt up`, `wt sync resume`, `wt sync undo`) as the sentence
471// the dialog shows, the few words the line above the prompt shows, and what
472// can follow it. A run moves the whole stack, so another member that did not
473// settle makes the outcome a failure and takes the push away: the person
474// sorts the stack out first.
475const outcomeOf = (action: Outcome['action'], ran: Ran, p: Plan): Outcome => {
476  const result = parse(ran.stdout)
477
478  if (result === null) {
479    return failed(action, p, lastLine(ran.stderr) || `wt exited ${ran.exitCode} and printed no result`, `wt ${action} failed for ${p.work}`)
480  }
481
482  const list: Loose[] = Array.isArray(result.worktrees) ? result.worktrees : []
483  const mine = list.find(one => one.path === p.path) ?? list.find(one => one.work === p.work)
484  const error = typeof result.error === 'string' && result.error !== '' ? result.error : null
485  const reasonOf = (one: Loose): string => (typeof one.reason === 'string' && one.reason !== '' ? `: ${one.reason}` : '')
486
487  // A run wt refused before it touched anything lists its participants as
488  // not run and says why at the top.
489  if (mine === undefined || String(mine.result) === 'notRun') {
490    const why = error ?? (mine !== undefined && reasonOf(mine) !== '' ? reasonOf(mine).slice(2) : lastLine(ran.stderr))
491
492    return failed(action, p, `wt did not touch ${p.work}${why === '' ? '' : `: ${why}`}`, `wt did not touch ${p.work}`)
493  }
494
495  const unsettled = list.filter(one => one !== mine && !SETTLED.includes(String(one.result)))
496  const also =
497    unsettled.length === 0
498      ? ''
499      : ` But in its stack ${unsettled.map(one => `${one.work} ${RESULT_WORDS[String(one.result)] ?? one.result}${reasonOf(one)}`).join('; ')}.`
500  const range = `${short(mine.before)} → ${short(mine.after)}`
501  const sync: Loose | null = mine.ownRemoteSync ?? null
502  const forwarded = sync?.fastForwarded === true ? `, after a fast-forward to ${sync.ref}` : ''
503  const pushCommand = unsettled.length === 0 && Array.isArray(mine.pushCommand) ? mine.pushCommand.map(String) : null
504  const reason = reasonOf(mine)
505  const recovery = typeof mine.recovery === 'string' && mine.recovery !== '' ? ` ${mine.recovery}` : ''
506  const onto = String(result.trunkRef ?? p.trunkRef)
507  const done = (text: string, brief: string, canUndo: boolean): Outcome => ({
508    action,
509    work: p.work,
510    path: p.path,
511    isOk: unsettled.length === 0,
512    text: text + also,
513    brief: unsettled.length === 0 ? `✓ ${brief}` : `✗ ${brief}, but its stack did not settle`,
514    pushCommand,
515    canUndo,
516  })
517
518  switch (String(mine.result)) {
519    case 'rebased':
520      return done(`${p.work} rebased onto ${onto}${forwarded} (${range}). Undo puts it back.`, `${p.work} rebased onto ${onto}`, true)
521    case 'fastForwarded':
522      return done(
523        `${p.work} fast-forwarded to ${sync?.ref ?? 'its own remote'} (${range}); nothing was left to rebase.`,
524        `${p.work} fast-forwarded`,
525        true,
526      )
527    case 'undone':
528      return done(`${p.work} is back where it was (${range}).`, `${p.work} is back where it was`, false)
529    case 'skipped':
530      return done(`${p.work}: nothing to do${reason}`, `${p.work}: nothing to do`, false)
531    case 'handedOver':
532      return {
533        ...failed(
534          action,
535          p,
536          `${p.work}: the rebase stopped at a conflict and is yours now. Resolve it in the worktree, then resume; or undo it.${also}`,
537          `${p.work}: the rebase stopped at a conflict`,
538        ),
539        canUndo: true,
540      }
541    case 'refused':
542      return failed(action, p, `wt refused ${p.work}${reason}${also}`, `wt refused ${p.work}`)
543    case 'restored':
544      return failed(action, p, `${p.work}: the rebase failed and wt put the branch back${reason}.${also}`, `${p.work}: the rebase failed, the branch is back`)
545    case 'rebasedStepFailed':
546    case 'interrupted':
547      return {
548        ...failed(action, p, `${p.work} ${RESULT_WORDS[String(mine.result)]}${reason}.${recovery}${also}`, `${p.work} ${RESULT_WORDS[String(mine.result)]}`),
549        canUndo: true,
550      }
551    default:
552      return failed(action, p, `${p.work}: ${mine.result}${reason}.${recovery}${also}`, `${p.work}: ${mine.result}`)
553  }
554}
555
556let isChecking = false
557let wantsAnother = false
558// Whether a model turn runs: set by turn.start and turn.complete, and by the
559// band wherever it is drawn. wt moves nothing under one.
560let isTurnRunning = false
561// The move under way, if any: one at a time, and a prompt sent meanwhile
562// waits for it rather than start a turn on a branch in mid-rebase.
563let moving: Promise<void> | null = null
564// The fetch the person asked for, while it runs: a move waits for it.
565let fetching: Promise<void> | null = null
566
567// An argument as a shell reads it back unchanged.
568const quoted = (arg: string): string => (/^[A-Za-z0-9_/.:=@%+,-]+$/.test(arg) ? arg : `'${arg.replace(/'/g, `'\\''`)}'`)
569
570// When the repository last fetched anything: the age of FETCH_HEAD in its git
571// directory, which every worktree of it shares. Read, never caused.
572const fetched = async ($: Engine, path: string): Promise<Pick<Plan, 'gitDir' | 'fetchedAt'>> => {
573  try {
574    const ran = await $.process.run(['git', 'rev-parse', '--path-format=absolute', '--git-common-dir'], { cwd: path, timeoutMs: 5_000 })
575    const gitDir = ran.exitCode === 0 ? ran.stdout.trim() : ''
576
577    if (gitDir === '') {
578      return { gitDir: null, fetchedAt: null }
579    }
580
581    try {
582      return { gitDir, fetchedAt: (await $.fs.stat(`${gitDir}/FETCH_HEAD`)).mtimeMs }
583    } catch {
584      // Never fetched.
585      return { gitDir, fetchedAt: null }
586    }
587  } catch {
588    return { gitDir: null, fetchedAt: null }
589  }
590}
591
592// Reads the worktree again. One `wt status` at a time: a second ask while
593// one runs is served by one more run after it.
594const refresh = async ($: Engine): Promise<Plan | null> => {
595  if (isChecking) {
596    wantsAnother = true
597
598    return read($, plan)
599  }
600
601  isChecking = true
602
603  try {
604    // Read before the worktree is, so that what is read of the worktree is
605    // from after the run it came from.
606    const shown = await read($, outcome)
607    let found: Plan | null = null
608
609    try {
610      found = planOf((await $.process.run(['wt', 'status', '--json'], { timeoutMs: 20_000 })).stdout)
611    } catch {
612      // wt is not installed, or did not answer in time: nothing to show.
613    }
614
615    if (found !== null) {
616      found = { ...found, ...(await fetched($, found.path)) }
617    }
618
619    const held = await read($, plan)
620
621    if (JSON.stringify(held) !== JSON.stringify(found)) {
622      await update($, plan, () => found)
623    }
624
625    // A run that succeeded has nothing left to say once its branch is pushed.
626    if (
627      found !== null &&
628      shown !== null &&
629      shown.isOk &&
630      shown.pushCommand !== null &&
631      shown.path === found.path &&
632      found.ownRemote?.state === 'inSync' &&
633      JSON.stringify(await read($, outcome)) === JSON.stringify(shown)
634    ) {
635      await update($, outcome, () => null)
636    }
637
638    return found
639  } finally {
640    isChecking = false
641
642    if (wantsAnother) {
643      wantsAnother = false
644      refresh($).catch(() => undefined)
645    }
646  }
647}
648
649// The refs the worktree's standing rests on, as they stood at the last pulse.
650let pulse: string | null = null
651
652// Keeps what is shown current for someone coming back to this terminal from
653// another: every few seconds one cheap read of the branch, trunk and remote
654// refs, and a full `wt status` only when one of them has moved. A fetch, a
655// commit or a rebase made anywhere else shows here within one pulse.
656const beat = async ($: Engine): Promise<void> => {
657  const p = await read($, plan)
658
659  if (p === null || moving !== null || isChecking) {
660    return
661  }
662
663  const refs = [`refs/heads/${p.trunk}`, `refs/remotes/${p.trunkRef}`]
664
665  if (p.branch !== null) {
666    refs.push(`refs/heads/${p.branch}`)
667  }
668
669  if (p.ownRemote !== null && p.ownRemote.ref !== null) {
670    refs.push(`refs/remotes/${p.ownRemote.ref}`)
671  }
672
673  const ran = await $.process.run(['git', 'for-each-ref', '--format=%(refname) %(objectname)', ...refs], { cwd: p.path, timeoutMs: 5_000 })
674
675  if (ran.exitCode !== 0) {
676    return
677  }
678
679  // A fetch that moved no ref of ours still makes what is shown newer.
680  let fetchedAt = 0
681
682  if (p.gitDir !== null) {
683    try {
684      fetchedAt = (await $.fs.stat(`${p.gitDir}/FETCH_HEAD`)).mtimeMs
685    } catch {
686      // Never fetched.
687    }
688  }
689
690  const before = pulse
691  pulse = `${p.path}\n${fetchedAt}\n${ran.stdout}`
692
693  if (before !== null && before !== pulse) {
694    await refresh($)
695  }
696}
697
698// Tells the model what the person just did to the branch under it.
699const tell = async ($: Engine, text: string): Promise<void> => {
700  try {
701    await $.session.append({ message: { type: 'user', content: [{ type: 'text', text }] } })
702  } catch {
703    // A run no plugin may shape: the band still says it.
704  }
705}
706
707// The rows the dialog needs for what it has to show.
708const rowsOf = async ($: Engine): Promise<number> => {
709  const p = await read($, plan)
710  const last = await read($, outcome)
711
712  if (p === null) {
713    return 5
714  }
715
716  const mine = last !== null && last.path === p.path ? last : null
717  const detail = detailOf(p, mine)
718
719  return (
720    1 +
721    detail.notes.length +
722    (mine !== null ? 3 : 0) +
723    1 +
724    (detail.primary !== null ? 1 : 0) +
725    (detail.follow.length > 0 ? 1 : 0) +
726    1 +
727    (knobs.hasReview ? 3 : 0) +
728    2
729  )
730}
731
732// Opens the dialog with the keyboard in it, so its letter keys answer and Esc
733// closes it, as tall as what it has to show. With text in the prompt the keys
734// stay there; Esc closes it once the prompt is empty.
735const openPane = async ($: Engine): Promise<void> => {
736  await $.ui.open({ id: PANE, title: 'wt', focus: true, closeOnEscape: true, rows: await rowsOf($) })
737}
738
739// Whether the dialog is the pane on show. One open behind another pane, or
740// waiting undrawn, is not: asked for, that one is raised.
741const isOnShow = async ($: Engine): Promise<boolean> => (await $.ui.panes()).some(one => one.id === PANE && one.isShown && one.isPlaced)
742
743// Asks again for the rows an open dialog needs, now that a run has left a
744// result and its keys to show: the rows, and never the keyboard, so that a
745// letter typed at the prompt is not taken for one of its keys. Whether it is
746// still on show is asked last, so that one just closed stays closed.
747const resize = async ($: Engine): Promise<void> => {
748  try {
749    const rows = await rowsOf($)
750
751    if (await isOnShow($)) {
752      await $.ui.open({ id: PANE, title: 'wt', closeOnEscape: true, rows })
753    }
754  } catch {
755    // The dialog scrolls instead.
756  }
757}
758
759// Runs one action for the worktree. The moves leave an outcome to show.
760const act = async ($: Engine, action: Action): Promise<string> => {
761  if (action === 'details') {
762    // A click on the line toggles, as bare /wt does: on show, it closes.
763    if (await isOnShow($)) {
764      await $.ui.close({ id: PANE })
765
766      return 'wt pane closed.'
767    }
768
769    await openPane($)
770
771    return 'wt pane opened.'
772  }
773
774  if (action === 'close') {
775    await $.ui.close({ id: PANE })
776
777    return 'wt pane closed.'
778  }
779
780  const p = await read($, plan)
781  const last = await read($, outcome)
782
783  if (action === 'dismiss') {
784    // What the last run came to goes away; what is still to do comes back.
785    await update($, outcome, () => null)
786
787    return 'Dismissed.'
788  }
789
790  if (action === 'refresh') {
791    return statusText(await refresh($), await $.clock.now()) ?? 'No wt worktree here.'
792  }
793
794  if (action === 'gittree') {
795    // gittree shows the repository and worktree holding the path, launching
796    // the app or bringing it forward; outside a wt worktree, the session's own.
797    let text: string
798
799    try {
800      const ran = await $.process.run(['gittree', p?.path ?? '.'], { timeoutMs: 20_000 })
801      text = ran.exitCode === 0 ? `Opened ${p?.work ?? 'this folder'} in gittree.` : `gittree: ${lastLine(ran.stderr) || `exited ${ran.exitCode}`}`
802    } catch (error) {
803      text = `gittree did not start: ${error instanceof Error ? error.message : String(error)}`
804    }
805
806    $.ui.toast(text)
807
808    return text
809  }
810
811  if (p === null) {
812    return 'No wt worktree here.'
813  }
814
815  if (action === 'fetch') {
816    // wt up fetches too, and two fetches at once clash over a ref's lock.
817    if (moving !== null) {
818      return 'wt is already running here.'
819    }
820
821    if (fetching !== null) {
822      return 'A fetch is already running here.'
823    }
824
825    let text: string
826    let release = (): void => undefined
827
828    fetching = new Promise<void>(resolve => {
829      release = resolve
830    })
831
832    try {
833      const ran = await $.process.run(['git', 'fetch', '--quiet', 'origin', p.trunk], { cwd: p.path, timeoutMs: 120_000 })
834      text = ran.exitCode === 0 ? `Fetched ${p.trunkRef}.` : `The fetch failed: ${lastLine(ran.stderr) || `git exited ${ran.exitCode}`}`
835    } catch (error) {
836      text = `The fetch did not finish: ${error instanceof Error ? error.message : String(error)}`
837    } finally {
838      fetching = null
839      release()
840    }
841
842    await refresh($)
843    $.ui.toast(text)
844
845    return text
846  }
847
848  if (action === 'push') {
849    // The push is the person's to run: it goes in the prompt as a shell
850    // line, so they see it, press Enter, and the repository's git hooks run.
851    if (last === null || last.pushCommand === null || last.path !== p.path) {
852      return 'Nothing to push from here: run wt up first.'
853    }
854
855    const line = `! ${last.pushCommand.map(quoted).join(' ')}`
856    let isFilled = false
857
858    // The prompt takes nothing while a dialog holds the keys, and the push is
859    // run from the prompt: the dialog closes first.
860    try {
861      await $.ui.close({ id: PANE })
862      isFilled = (await $.prompt.fill({ text: line })).isFilled
863    } catch {
864      // Said below, with the command.
865    }
866
867    const text = isFilled ? 'The push is in the prompt: press Enter to run it.' : `The prompt did not take the push. Run it yourself: ${line}`
868    $.ui.toast(text)
869
870    return text
871  }
872
873  if (moving !== null) {
874    return 'wt is already running here.'
875  }
876
877  if (isTurnRunning) {
878    const text = `${LABEL[action]}: a turn is running in ${p.work}. wt can move it once the turn is done.`
879    $.ui.toast(text)
880
881    return text
882  }
883
884  let argv: string[]
885
886  switch (action) {
887    case 'up':
888    case 'upDiverged':
889      if (p.token === null) {
890        return `wt up would refuse ${p.work}: ${obstacle(p) ?? 'it has no plan'}`
891      }
892
893      argv = ['wt', 'up', '--yes', '--no-push', '--json', '--expect', p.token]
894
895      if (action === 'upDiverged') {
896        argv.push('--allow-diverged')
897      }
898
899      break
900    case 'undo':
901      // "." is the worktree the command runs in: a bare work name can be two.
902      argv = ['wt', 'sync', 'undo', '.', '--yes', '--json']
903      break
904    case 'resume':
905      argv = ['wt', 'sync', 'resume', '.', '--yes', '--no-push', '--json']
906      break
907  }
908
909  const kind: Outcome['action'] = action === 'upDiverged' ? 'up' : action
910  let release = (): void => undefined
911  let next: Outcome
912
913  // Taken before the first await, so a second press finds it.
914  moving = new Promise<void>(resolve => {
915    release = resolve
916  })
917
918  try {
919    await update($, busy, () => kind)
920
921    if (fetching !== null) {
922      await fetching
923    }
924
925    try {
926      next = outcomeOf(kind, await $.process.run(argv, { cwd: p.path, timeoutMs: TEN_MINUTES }), p)
927    } catch (error) {
928      next = failed(
929        kind,
930        p,
931        `${argv.slice(0, 3).join(' ')} did not finish: ${error instanceof Error ? error.message : String(error)}`,
932        `${argv.slice(0, 3).join(' ')} did not finish`,
933      )
934    }
935
936    await update($, outcome, () => next)
937  } finally {
938    await update($, busy, () => 'idle').catch(() => undefined)
939    moving = null
940    release()
941  }
942
943  await refresh($)
944  await resize($)
945  await tell(
946    $,
947    `[wt plugin] The person ran ${argv.slice(0, 3).join(' ')} on the worktree ${p.work} (${p.branch ?? 'detached'}). ${next.text}` +
948      (next.isOk ? ' Its files and commits may have changed: read again before editing.' : ''),
949  )
950
951  return next.text
952}
953
954export const register: Register = (on, options) => {
955  knobs.hasGittree = options.gittree === true
956  knobs.hasReview = options.reviewStatus === true
957  knobs.inputAfterMs = (typeof options.inputAfterMinutes === 'number' && options.inputAfterMinutes >= 0 ? options.inputAfterMinutes : 5) * 60_000
958  knobs.reviewAfterMs = (typeof options.reviewAfterMinutes === 'number' && options.reviewAfterMinutes >= 0 ? options.reviewAfterMinutes : 30) * 60_000
959
960  try {
961    knobs.reviewSkills = new RegExp(typeof options.reviewSkills === 'string' && options.reviewSkills !== '' ? options.reviewSkills : REVIEW_SKILLS, 'i')
962  } catch {
963    knobs.reviewSkills = new RegExp(REVIEW_SKILLS, 'i')
964  }
965
966  on('session.start', async ($, e, next) => {
967    await $.command.register({
968      name: 'wt',
969      description: 'The worktree you are in: its place against trunk, and wt up, undo, push from here',
970      argumentHint: knobs.hasGittree
971        ? '[up|undo|push|resume|fetch|refresh|dismiss|close|gittree]'
972        : '[up|undo|push|resume|fetch|refresh|dismiss|close]',
973    })
974    // A reload ends whatever this module was waiting on: nothing runs now.
975    await update($, busy, () => 'idle')
976    // Nothing of this mod's is pinned under the prompt; an older load's goes.
977    $.ui.status(undefined)
978    refresh($).catch(() => undefined)
979    // What is shown counts time: a minute later it says a minute more.
980    $.clock.every(60_000, () => {
981      $.ui.invalidate('ui.render')
982    })
983    $.clock.every(PULSE_MS, () => {
984      beat($).catch(() => undefined)
985    })
986    // What no ref shows (a file edited from outside, a session come or gone)
987    // is caught by the full read.
988    $.clock.every(180_000, () => {
989      refresh($).catch(() => undefined)
990    })
991
992    return next(e)
993  })
994
995  // Whatever a turn did to the checkout shows once it is done, and after each
996  // shell command that could have moved a branch.
997  on('tool.call', { tool: 'Bash' }, async ($, e, next) => {
998    const ran = await next(e)
999
1000    if (/\b(git|wt|gh)\b/.test(e.command)) {
1001      refresh($).catch(() => undefined)
1002    }
1003
1004    return ran
1005  }).catch(($, e, next) => next(e))
1006
1007  on('turn.start', ($, e, next) => {
1008    isTurnRunning = true
1009
1010    return next(e)
1011  })
1012
1013  on('turn.complete', ($, e, next) => {
1014    isTurnRunning = false
1015    refresh($).catch(() => undefined)
1016
1017    return next(e)
1018  })
1019
1020  // A new conversation starts with no review and no input behind it.
1021  on('session.end', async ($, e, next) => {
1022    if (e.reason === 'clear') {
1023      await update($, inputs, () => 0)
1024      await update($, lastInput, () => null)
1025      await update($, lastReview, () => null)
1026      await update($, firstInput, () => null)
1027    }
1028
1029    return next(e)
1030  })
1031
1032  // The review knob: the person's own inputs, counted and remembered by how
1033  // they began, and each review skill as it is expanded for the model, typed
1034  // as /name or called through the Skill tool alike.
1035  on('prompt.submit', async ($, e, next) => {
1036    // A prompt sent while wt moves the branch waits for the move to end.
1037    if (moving !== null) {
1038      await moving
1039    }
1040
1041    // The person's own: typed here, sent from a phone, or typed in an app
1042    // that hosts the session.
1043    const isOwn = e.origin.kind === 'composer' || e.origin.kind === 'bridge' || e.origin.kind === 'sdk'
1044
1045    // A run that succeeded and left nothing to push has been seen once the
1046    // person types on: the line goes back to how the worktree stands.
1047    if (isOwn && !e.text.trimStart().startsWith('/')) {
1048      const last = await read($, outcome)
1049
1050      if (last !== null && last.isOk && last.pushCommand === null) {
1051        await update($, outcome, () => null)
1052      }
1053    }
1054
1055    if (knobs.hasReview && isOwn) {
1056      const letters = Array.from(e.text.replace(/\s+/g, ' ').trim())
1057      const now = await $.clock.now()
1058      const typed: Input = { at: now, head: letters.length > 20 ? `${letters.slice(0, 20).join('')}…` : letters.join('') }
1059      const count = (await read($, inputs)) + 1
1060      await update($, inputs, () => count)
1061      await update($, lastInput, () => typed)
1062
1063      if ((await read($, firstInput)) === null) {
1064        await update($, firstInput, () => now)
1065      }
1066
1067      // A review skill expanded just before its own /name arrived here belongs
1068      // to this input, not to the one before it.
1069      const review = await read($, lastReview)
1070
1071      if (review !== null && now - review.at < 5_000 && e.text.trimStart().startsWith(`/${review.skill}`)) {
1072        await update($, lastReview, () => ({ ...review, inputs: count }))
1073      }
1074    }
1075
1076    return next(e)
1077  }).catch(($, e, next) => next(e))
1078
1079  on('skill.prompt', async ($, e, next) => {
1080    if (knobs.hasReview && knobs.reviewSkills.test(e.skill)) {
1081      const ran: Review = { skill: e.skill, at: await $.clock.now(), inputs: await read($, inputs) }
1082      await update($, lastReview, () => ran)
1083    }
1084
1085    return next(e)
1086  })
1087
1088  on('command.run', { command: 'wt' }, async ($, e) => {
1089    const word = e.args.trim().split(/\s+/)[0] ?? ''
1090    const known: readonly Action[] = knobs.hasGittree
1091      ? ['up', 'undo', 'push', 'resume', 'fetch', 'refresh', 'dismiss', 'close', 'gittree']
1092      : ['up', 'undo', 'push', 'resume', 'fetch', 'refresh', 'dismiss', 'close']
1093    const action = known.find(one => one === word)
1094
1095    if (action !== undefined) {
1096      return { text: await act($, action) }
1097    }
1098
1099    if (word !== '') {
1100      return { text: `/wt ${word}: not one of ${known.join(', ')}.` }
1101    }
1102
1103    // Bare, it toggles: the dialog on show is the dialog closed.
1104    if (await isOnShow($)) {
1105      return { text: await act($, 'close') }
1106    }
1107
1108    const p = await refresh($)
1109    await openPane($)
1110
1111    return { text: statusText(p, await $.clock.now()) ?? 'No wt worktree here.' }
1112  })
1113
1114  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
1115    isTurnRunning = e.props.isWorking
1116
1117    if (e.props.hasSurvey) {
1118      return next(e)
1119    }
1120
1121    const now = await $.clock.now()
1122    const line = lineOf(await read($, plan), await read($, outcome), await read($, busy), now)
1123    const linger = knobs.hasReview
1124      ? lingerOf(await read($, lastInput), await read($, lastReview), await read($, firstInput), await read($, inputs), now)
1125      : ''
1126
1127    // The line takes no keys: the only ones that would answer from the prompt
1128    // are digits, and a digit typed into an empty prompt is the person's to
1129    // type. It names the command instead, and a click on that toggles it.
1130    //
1131    // Outside a worktree of wt's, with nothing old to recall and no gittree,
1132    // nothing is drawn.
1133    if (line === null && linger === '' && !knobs.hasGittree) {
1134      return next(e)
1135    }
1136
1137    const { Box, Button, Text } = $.ui.resolve(e)
1138
1139    return (
1140      <Box gap={1}>
1141        {line !== null && <Button key="details" plain label={LABEL.details} onPress={() => act($, 'details')} />}
1142        <Text wrap="truncate-end">
1143          {line !== null &&
1144            line.map((part, at) => [
1145              at === 0 ? '· ' : ' · ',
1146              <Text color={part.tone === 'dim' ? undefined : part.tone} dimColor={part.tone === 'dim'}>
1147                {part.text}
1148              </Text>,
1149            ])}
1150          {linger !== '' && line !== null && ' · '}
1151          {linger !== '' && <Text dimColor>{linger}</Text>}
1152        </Text>
1153        <Box flexGrow={1} />
1154        {knobs.hasGittree && <Button key="gittree" plain label={GITTREE_OUT} onPress={() => act($, 'gittree')} />}
1155      </Box>
1156    )
1157  })
1158
1159  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
1160    const { Box, Button, Text } = $.ui.resolve(e)
1161    const p = await read($, plan)
1162    const last = await read($, outcome)
1163    const state = await read($, busy)
1164    const keyFor = (one: Action) => <Button key={one} plain label={LABEL[one]} hotkey={HOTKEY[one]} onPress={() => act($, one)} />
1165    const footer = (
1166      <Box gap={2} marginTop={1}>
1167        <Button key="close" plain dimColor role="dismiss" label={LABEL.close} hotkey={HOTKEY.close} onPress={() => act($, 'close')} />
1168        <Text dimColor>{e.props.isFocused ? CLOSING : KEYLESS}</Text>
1169      </Box>
1170    )
1171
1172    if (p === null) {
1173      return (
1174        <Box flexDirection="column">
1175          <Text dimColor wrap="wrap">
1176            No wt worktree here: this folder is not in a repository wt knows, or wt is not installed.
1177          </Text>
1178          <Box gap={3} marginTop={1}>
1179            {keyFor('refresh')}
1180            {knobs.hasGittree && keyFor('gittree')}
1181          </Box>
1182          {footer}
1183        </Box>
1184      )
1185    }
1186
1187    const now = await $.clock.now()
1188    // The last outcome, when it is this worktree's.
1189    const mine = last !== null && last.path === p.path ? last : null
1190    const detail = detailOf(p, mine)
1191    const review = knobs.hasReview ? await read($, lastReview) : null
1192    const typed = knobs.hasReview ? await read($, lastInput) : null
1193    const count = knobs.hasReview ? await read($, inputs) : 0
1194
1195    return (
1196      <Box flexDirection="column">
1197        <Box gap={2}>
1198          <Text bold>{p.work}</Text>
1199          {p.isMain ? (
1200            <Text dimColor>main checkout</Text>
types/index.d.ts 94 lines
1/** A branch against the ref a push of it would replace, as `wt status --json` reports it. */
2export type OwnRemote = {
3  ref: string | null
4  /** none | gone | unknown | inSync | ahead | behind | rebased | diverged */
5  state: string
6  ahead: number | null
7  behind: number | null
8  /** null | diverged | operation | dirty | session: why a run would refuse. */
9  blocks: string | null
10  /** Why wt would not push the branch, in wt's words; null when it would, and from a wt older than status 1.8.0. */
11  noPushReason: string | null
12  /** The command that settles it, as argv, when one does. */
13  fixCommand: string[] | null
14}
15
16export type WtSession = { name: string; kind: string; state: string }
17
18/** The worktree the session stands in, digested from `wt status --json`. */
19export type Plan = {
20  work: string
21  branch: string | null
22  path: string
23  isMain: boolean
24  trunk: string
25  trunkRef: string
26  /** When the trunk ref last moved here (ISO), or null: status does not fetch. */
27  trunkFetchedAt: string | null
28  /** The repository's git directory, absolute; null when it could not be read. */
29  gitDir: string | null
30  /** When the repository last fetched anything (ms since the epoch), or null. */
31  fetchedAt: number | null
32  /** Commits origin's trunk has that local trunk lacks. */
33  trunkRemoteAhead: number
34  /** null when wt could not count them. */
35  behind: number | null
36  ahead: number | null
37  /** clean | dirty | unreadable */
38  tree: string
39  /** null from a wt older than status 1.6.0. */
40  ownRemote: OwnRemote | null
41  upEligible: boolean
42  upIneligibleCode: string | null
43  upIneligibleReason: string | null
44  /** Passed to `wt up --expect`. */
45  token: string | null
46  /** The other worktrees a run on this one would move, parents first. */
47  stack: string[]
48  /** Other agent sessions in the worktree. */
49  sessions: WtSession[]
50  /** Why the sessions could not be listed, when they could not. */
51  sessionsError: string | null
52  schemaVersion: string
53}
54
55/** What the last action from the dialog or `/wt` came to. */
56export type Outcome = {
57  action: 'up' | 'undo' | 'resume'
58  /** The worktree it was run on: shown and acted on for that one only. */
59  work: string
60  path: string
61  isOk: boolean
62  /** The whole of it, for the dialog. */
63  text: string
64  /** A few words led by ✓ or ✗, for the line above the prompt. */
65  brief: string
66  /** The lease-protected push wt printed for the rebased branch, as argv. */
67  pushCommand: string[] | null
68  canUndo: boolean
69}
70
71export type Busy = 'idle' | 'up' | 'undo' | 'resume'
72
73/** The person's last own input: when, and how it began (cut with an ellipsis). */
74export type Input = { at: number; head: string }
75
76/** The last review skill this conversation ran, and the input count then. */
77export type Review = { skill: string; at: number; inputs: number }
78
79declare module 'claude-code' {
80  interface PluginState {
81    wt: {
82      plan: Plan | null
83      busy: Busy
84      outcome: Outcome | null
85      /** The person's own inputs so far in this conversation. */
86      inputs: number
87      lastInput: Input | null
88      lastReview: Review | null
89      /** When the person's first own input of this conversation was. */
90      firstInput: number | null
91    }
92  }
93}
94