From c4439497cbfa7dabb85cedfed5fbf030d2c33b9f Mon Sep 17 00:00:00 2001 From: Vuong Vu Date: Wed, 21 Oct 2026 11:14:13 +0200 Subject: [PATCH 1/6] feat: add worktree support for improved Git workflow management - Introduced a new design document outlining the goals and implementation details for worktree support. - Implemented functions to list worktrees, count changes, and determine which worktree holds a specific branch. - Added integration tests to ensure correct functionality of worktree-related features. - Created a WorktreeStrip component to visually represent worktrees in the UI, highlighting the current worktree and displaying change counts. - Enhanced the watcher to keep the UI updated with changes across all worktrees. --- README.md | 4 + docs/architecture.md | 4 + .../plans/2026-10-19-worktree-support.md | 241 ++++++++++++++++++ .../2026-10-19-worktree-support-design.md | 124 +++++++++ server/index.ts | 63 +++-- server/parse.test.ts | 34 ++- server/parse.ts | 27 ++ server/watch.test.ts | 65 ++++- server/watch.ts | 40 ++- server/worktrees.test.ts | 187 ++++++++++++++ server/worktrees.ts | 150 +++++++++++ src/App.tsx | 19 +- src/GraphView.tsx | 36 ++- src/RepoView.tsx | 72 +++++- src/TabBar.tsx | 14 +- src/WorktreeStrip.tsx | 26 ++ src/styles.css | 19 ++ 17 files changed, 1071 insertions(+), 54 deletions(-) create mode 100644 docs/superpowers/plans/2026-10-19-worktree-support.md create mode 100644 docs/superpowers/specs/2026-10-19-worktree-support-design.md create mode 100644 server/worktrees.test.ts create mode 100644 server/worktrees.ts create mode 100644 src/WorktreeStrip.tsx diff --git a/README.md b/README.md index 27dde1a..5d68700 100644 --- a/README.md +++ b/README.md @@ -53,6 +53,10 @@ A sticky WIP row sits at the top of the list whenever the worktree is dirty, con Stashes appear as their own rows, attached to the commit they were taken from with a dotted connector, and can be popped, deleted, or retitled in place. +### Worktrees + +A repository with linked worktrees gets a strip beside the graph listing each one with its branch and changed-file count. Click a row to open it in its own purple `⎇` tab; counts update live, and a branch checked out elsewhere is marked on its chip and offers to open that tab instead of failing the checkout. + ### Diffs Click a commit to see its changed files, then a file to see the diff. Syntax highlighting, word-level intra-line highlighting, collapsed context you can expand a hunk at a time, and a per-file "Viewed" checkbox. diff --git a/docs/architecture.md b/docs/architecture.md index 584843e..5f87db2 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -28,6 +28,10 @@ Graph queries use `--date-order`, deliberately not `--topo-order`: topological o **`watch.ts` drives auto-refresh.** One `fs.watch` per open repository, filtered by `isRelevant`, fed into a trailing debouncer with a max-wait cap (400 ms quiet flush, 2 s under sustained churn — a long install or a big rebase still updates twice a second rather than never). Changes are pushed to the browser over SSE at `/api/events`, with a 30 s `: ping` comment to keep intermediaries from closing an idle stream. +**Worktrees extend the watch set, not the protocol.** `worktrees.ts`'s `watchRepo` wraps `subscribe()` and sends two SSE message kinds: `data: changed` (the viewed repo, or — for a linked worktree — the common git dir, since a commit there lands in the common dir rather than in the worktree) and `data: worktrees` (a sibling worktree changed). Siblings are reconciled after each `changed` fire, because `git worktree add/remove` touches the common dir; a worktree nested inside a watched root (`.claude/worktrees/*` inside the repo, or the viewed worktree inside a sibling main checkout) is on that root's ignore list (`setIgnored`, re-applied on every reconcile, for the repo and each sibling alike) and is counted only by its own watcher — so an edit in it fires once, from the watcher that owns it. Filenames are normalised to `/` before the ignore and relevance checks, since Windows reports backslashes. A `worktrees` message refetches only `/api/worktrees`, never `/api/graph`, so editing a file in another worktree costs one `git status` per worktree and no graph re-layout. + +**`/api/worktrees` returns `{worktrees}`** — path, branch (or detached), head, `changed` count, `current`. A single-worktree repo costs one `git worktree list` and returns `[]`; the strip only renders when there is more than one. Paths are git's resolved paths, so compare with `current` (and realpath on the server), never against registered strings. `/api/config` also carries `linked`: the registered paths that are linked worktrees, so the tab bar can badge them without a request per tab. Checkout and branch delete consult `heldBy` first and refuse before stashing anything: checkout answers `{heldBy: path}` (the client offers to open that tab), delete answers 409. + **Only a manual refresh touches the network.** `/api/graph` and `/api/status` read local git, which cannot see upstream commits until something fetches — so Pull was once the only button that surfaced them. The ⟳ button and r now POST `{action:'fetch'}` to `/api/branch` and re-enter `refresh` for the local read; a failed fetch is swallowed so the read still lands. Everything else stays local-only on purpose: SSE refetches fire every 400 ms–2 s, and RepoView remounts per tab switch, so neither may cost a round-trip. **`/api/graph` pages.** 200 commits per request by default, clamped to 5000 — an uncapped limit turns one request into the entire history (4.2 MB / 380 ms on a 14.8k-commit repo), and 5000 rows is already far past where the DOM gives out. diff --git a/docs/superpowers/plans/2026-10-19-worktree-support.md b/docs/superpowers/plans/2026-10-19-worktree-support.md new file mode 100644 index 0000000..9f37f08 --- /dev/null +++ b/docs/superpowers/plans/2026-10-19-worktree-support.md @@ -0,0 +1,241 @@ +# Worktree Support Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** megit sees the git worktrees other tools create: live-refreshing worktree tabs, a strip listing every worktree with its changed-file count, `⎇` branch badges, and a checkout refusal that touches nothing. + +**Architecture:** One new server module, `server/worktrees.ts`, owns listing, counting, branch-holder lookup and the per-repo watch set. `/api/events` delegates to it and emits two message kinds: `changed` (this checkout) and `worktrees` (a sibling's folder). The client adds a `WorktreeStrip` component, and threads a `linked` path list and an `onOpen(path)` callback from `App` down. + +**Tech Stack:** Node 24 + TypeScript (type-stripped), `node:http` routes in `server/index.ts`, React 19, vitest. + +**Spec:** `docs/superpowers/specs/2026-10-19-worktree-support-design.md` + +## Global Constraints + +- **No commit steps.** CLAUDE.md forbids `git commit` and `git rm` for the agent, so each task ends with a check-in and the user commits. +- Work on branch `feat/worktree-support`. +- Prefix every Node/pnpm command with `export PATH="$HOME/.nvm/versions/node/v24.16.0/bin:$PATH"`. +- Don't add runtime dependencies. Client deps go in `devDependencies`. +- megit never runs `git worktree add|remove|prune|lock|move`. The only exception is test fixtures and verification scratch repos. +- **No per-worktree git work in a repo with a single worktree.** `/api/worktrees` returns `[]` without running `status`, and `/api/events` adds no sibling watchers. +- Keep fingerprint gating. A worktree refresh that yields the same list and counts calls no `setState`. +- Tab label is `⎇ ` (from `base(path)`), coloured purple. +- Strip-opened tabs skip `recent` and are inserted right after the tab they were opened from. +- When a worktree disappears, its tab stays open and shows `Worktree removed`. megit never closes a tab by itself. +- Don't touch the user's real `~/.config/megit/config.json`. For probes, run the server with `HOME=$(mktemp -d)`. +- `git worktree list --porcelain -z` needs git ≥ 2.36. The dev machine has 2.54. + +## Review Focus + +1. **Worktree folder paths with spaces or unicode.** Expected: they parse, count and open like any other path. Pinned by the `parseWorktrees` test that uses `/tmp/a b/ü`. +2. **A worktree folder deleted by hand** (`rm -rf`, not `git worktree remove`) while megit is showing it. Expected: git marks it `prunable`, it drops out of the strip, and its open tab shows `Worktree removed`. Pinned by the prunable parse test and Task 6, step 3. +3. **Nested worktrees** (`.claude/worktrees/x` inside the main checkout). Expected: edits there update that entry's count only, and never trigger the main tab's graph refetch. Pinned by the `watchRepo` nested test. +4. **A detached-HEAD worktree.** Expected: the strip shows `detached @ `, and the branch badge logic ignores it, since it holds no branch. Pinned by the `parseWorktrees` detached case and the `heldBy` test. +5. **Checkout of a held branch with a dirty tree.** Expected: no stash entry is created and the working tree is unchanged. Pinned by the `heldBy` integration test plus the curl probe in Task 3. + +--- + +### Task 1: Watcher relevance for git dirs, pluggable filter, ignore list + +**Files:** +- Modify: `server/watch.ts` +- Test: `server/watch.test.ts` + +**Interfaces:** +- Produces: + - `isGitDirRelevant(rel: string): boolean`. `rel` is relative to a git *common* dir. Returns true for `HEAD`, `index`, `packed-refs`, `refs/**`, `worktrees//HEAD`, `worktrees//index`. + - `isRelevant(rel)` keeps its signature. For paths under `.git/` it now returns `isGitDirRelevant(inner)`. + - `subscribe(path, onChange, onError, relevant: (rel: string) => boolean = isRelevant): () => void`. The first subscriber's filter wins for a path. Callers always pass the same filter for the same kind of path. + - `setIgnored(path: string, prefixes: string[]): void`. This sets the subscription's ignore list for `path` (live entry only; it does nothing when no entry exists). A `rel` that equals a prefix, or starts with `prefix + '/'`, is dropped before `relevant` runs. + +- [ ] **Step 1: Write the failing tests.** Extend the `isRelevant` table with: + +```ts +['.git/worktrees/feat/HEAD', true], +['.git/worktrees/feat/index', true], +['.git/worktrees/feat/index.lock', false], +['.git/worktrees/feat/logs/HEAD', false], +``` + +Add a `describe('isGitDirRelevant')` table: `['HEAD', true]`, `['refs/heads/x', true]`, `['packed-refs', true]`, `['worktrees/a/HEAD', true]`, `['worktrees/a/ORIG_HEAD', false]`, `['objects/ab/cd', false]`, `['worktrees/a/b/HEAD', false]`. + +Add integration tests in the existing `integration` describe: +- `'linked worktree: commit fires a subscription on the common git dir'`: `git worktree add ../wt -b wt` in the fixture, `subscribe(commonDir, spy, noop, isGitDirRelevant)`, commit inside `wt`, wait for `spy` (same polling helper as the existing test). +- `'setIgnored drops events under an ignored prefix'`: subscribe to the repo, `setIgnored(repo, ['nested'])`, write `nested/x.txt` and wait 2.5 s (past max-wait), then expect `spy` not called. Then write `top.txt` and expect `spy` called. + +- [ ] **Step 2: Run and see it fail.** +Run: `pnpm test -- watch` +Expected: FAIL. `isGitDirRelevant` and `setIgnored` are not exported. + +- [ ] **Step 3: Implement in `server/watch.ts`.** +`Entry` gets `ignored: string[]`. The watcher callback checks ignored prefixes, then the stored filter. + +- [ ] **Step 4: Run.** +Run: `pnpm test -- watch && npx tsc --noEmit` +Expected: PASS, no type errors. + +- [ ] **Step 5: Check in.** Hand back for the user to commit. + +--- + +### Task 2: Worktree listing, counts, branch holder, watch set + +**Files:** +- Modify: `server/parse.ts` (adds `parseWorktrees`) +- Create: `server/worktrees.ts` +- Test: `server/parse.test.ts`, `server/worktrees.test.ts` (new; the integration describe skips on win32, as in `watch.test.ts`) + +**Interfaces:** +- Consumes: `subscribe`, `setIgnored`, `isRelevant`, `isGitDirRelevant` from Task 1. `parseStatus` from `parse.ts`. +- Produces: + - `parse.ts`: `export type WorktreeEntry = { path: string; head: string; branch: string | null; prunable: boolean; bare: boolean }` and `export function parseWorktrees(raw: string): WorktreeEntry[]`. Input is `git worktree list --porcelain -z`: NUL-terminated `key value` fields, with records separated by an empty field. `branch` is stripped of `refs/heads/`. A `detached` line means `branch: null`. + - `worktrees.ts`: + - `export type Git = (repo: string, args: string[], okCodes?: number[]) => Promise`. This is index.ts's `git`, passed in the same way `resolveAvatar` takes it. + - `export type Worktree = { path: string; branch: string | null; head: string; changed: number; current: boolean }`. + - `isLinkedWorktree(dir: string): boolean`. Reads `/.git` synchronously. True only if it is a file whose `gitdir:` line contains `/worktrees/`. Submodules (`/modules/`) and missing paths return false. + - `listWorktrees(repo: string, git: Git): Promise`. Excludes prunable and bare entries. + - `worktreesWithCounts(repo: string, git: Git): Promise`. Returns `[]` when there is ≤ 1 entry, without running `status`. Otherwise it runs `status --porcelain=v2 -uall -z` in every entry in parallel, with `changed = parseStatus(raw).length`; a failing status gives `0`. `current` compares against `await realpath(repo)`. + - `heldBy(repo: string, branch: string, git: Git): Promise`. Returns the path of a *different* worktree whose `branch === branch`, else null. + - `watchRepo(repo: string, git: Git, send: (kind: 'changed' | 'worktrees') => void, onError: () => void): Promise<() => void>`. Subscribes as follows: + - `repo` with `isRelevant`, which sends `changed`. + - If `isLinkedWorktree(repo)`: also the common dir from `git rev-parse --path-format=absolute --git-common-dir` with `isGitDirRelevant`, which sends `changed`. + - Every *other* listed worktree path with `isRelevant`, which sends `worktrees`. + + After every `changed` fire, it re-runs `listWorktrees` and reconciles: adds and removes sibling subscriptions, and calls `setIgnored(repo, )`. Reconcile errors are swallowed. The returned function unsubscribes everything. + +- [ ] **Step 1: Write the failing parse tests** (`parse.test.ts`, `describe('parseWorktrees')`): + - Main plus a linked worktree, plus a detached one at `/tmp/a b/ü`: + + ```ts + const raw = 'worktree /r\0HEAD aaa\0branch refs/heads/main\0\0worktree /r-wt\0HEAD bbb\0branch refs/heads/feat/x\0\0worktree /tmp/a b/ü\0HEAD ccc\0detached\0\0' + expect(parseWorktrees(raw)).toEqual([ + { path: '/r', head: 'aaa', branch: 'main', prunable: false, bare: false }, + { path: '/r-wt', head: 'bbb', branch: 'feat/x', prunable: false, bare: false }, + { path: '/tmp/a b/ü', head: 'ccc', branch: null, prunable: false, bare: false }, + ]) + ``` + + - `'prunable gitdir file points to non-existent location'` on a record sets `prunable: true`. + - A `bare` record sets `bare: true`. + - `parseWorktrees('')` is `[]`. + +- [ ] **Step 2: Write the failing integration tests** (`worktrees.test.ts`). The fixture is a tmp repo with one commit, plus `git worktree add /wt -b feat`. + - `isLinkedWorktree(wt)` is true. `isLinkedWorktree(repo)` is false. `isLinkedWorktree(/nope)` is false. + - `worktreesWithCounts(repo, git)` returns two entries. After writing one file in `wt`, the `wt` entry has `changed: 1` and the `repo` entry has `current: true`. + - On a fresh single-worktree repo, `worktreesWithCounts` resolves to `[]`, and the spy `git` was called once (`worktree list` only). + - `heldBy(repo, 'feat', git)` is the `wt` path. `heldBy(repo, 'main', git)` is null (main is current). `heldBy(wt, 'main', git)` is the repo path. + - `watchRepo(wt, …)`: a commit made *inside wt* sends `changed`. This is goal 1, the auto-refresh fix. + - `watchRepo(repo, …)`: editing `wt/file` sends `worktrees` and not `changed`. + - Nested: `git worktree add /.claude/worktrees/n -b n`, then `watchRepo(repo, …)`. Editing `.claude/worktrees/n/f` sends `worktrees` only. + - After `git worktree remove wt` (run in the test), `listWorktrees(repo)` no longer contains `wt`. + + Here `git` is a minimal `execFile('git', ['-C', repo, ...args])` wrapper defined in the test file. + +- [ ] **Step 3: Run and see it fail.** +Run: `pnpm test -- worktrees parse` +Expected: FAIL. The module and function don't exist. + +- [ ] **Step 4: Implement `parseWorktrees` and `server/worktrees.ts` to the interfaces above.** Put a ponytail comment on `worktreesWithCounts` saying all worktrees are counted on every call, and that a per-path dirty cache is the upgrade if it ever shows up in a measurement. + +- [ ] **Step 5: Run.** +Run: `pnpm test && npx tsc --noEmit` +Expected: everything passes. + +- [ ] **Step 6: Check in.** + +--- + +### Task 3: Server wiring: routes, events, config, refusals + +**Files:** +- Modify: `server/index.ts`. The relevant spots are `withCaps` (~line 82), `POST /api/repos` (86), `/api/status` neighbourhood (new route), `/api/checkout` (308), `/api/branch` delete case (~485), and `/api/events` (699). + +**Interfaces:** +- Consumes: `worktreesWithCounts`, `heldBy`, `watchRepo`, `isLinkedWorktree` from Task 2. +- Produces (wire): + - `GET /api/worktrees?repo=` returns `{ worktrees: Worktree[] }` and goes through `repoGuard`. + - `GET /api/config` and every `withCaps` response gain `linked: string[]`, which is `cfg.repos.filter(isLinkedWorktree)`. + - `POST /api/repos` accepts an optional `after: string`. When it is present and is in `repos`, the new path is inserted right after it and `recent` is left alone. Without it, behaviour is unchanged. + - `POST /api/checkout`: before any `status` or stash, if `heldBy(repo, branch)` is set, respond `200 { heldBy: }`. This mirrors the `diverged` response shape. + - `POST /api/branch` delete: if the branch is held, throw `httpError(409, \`'${branch}' is checked out in ${path}\`)` before running `git branch -d`. + - `/api/events`: `data: changed` and `data: worktrees` messages. The handler awaits `watchRepo`. If the request closed before it resolved, it unsubscribes at once. + +- [ ] **Step 1: Implement the route and config changes listed above.** + +- [ ] **Step 2: Typecheck and test.** +Run: `npx tsc --noEmit && pnpm test` +Expected: clean. + +- [ ] **Step 3: Probe with curl** (isolated HOME, `PORT=4600 node server/index.ts &`, PID saved to a file; never `pkill`): + - Fixture: a tmp repo plus `git worktree add ../wt -b feat`, with a dirty file in the main checkout. Register the repo. + - `curl -s localhost:4600/api/worktrees?repo=…` shows 2 entries and the counts. + - `curl -s -X POST …/api/checkout?repo=
-d '{"branch":"feat"}'` returns `{"heldBy":"…/wt"}`, `git -C
stash list` is empty, and the dirty file is still dirty. + - Branch delete of `feat` returns 409 with the readable message. + - `POST /api/repos` with `{path: wt, after: main}`: `repos` has `wt` right after `main`, `recent` doesn't contain `wt`, and `linked` contains `wt`. + - Run `curl -w '%{time_total}'` on `/api/worktrees` against `~/WORKSPACE/BLS/bikeleasing-app` with 3 scratch worktrees, then remove the worktrees and the registration. Record the number in the check-in. + +- [ ] **Step 4: Check in.** + +--- + +### Task 4: Tabs: purple label, open-from-strip, "Worktree removed" + +**Files:** +- Modify: `src/App.tsx`, `src/TabBar.tsx`, `src/RepoView.tsx` (props and the `error.gone` render only), `src/index.css` (or wherever `.tab` is styled; find it with `grep -rn "\.tab\b" src/*.css`) + +**Interfaces:** +- Consumes: `linked`, `after` from Task 3. +- Produces: + - `Config` (client) gains `linked: string[]`. + - In `App`: `open(path: string): void`. If `cfg.repos` includes the path, it calls `select`. Otherwise it calls `POST /api/repos {path, after: cfg.activeRepo}` and then `setCfg`, with failures going to `toastErr`. + - `TabBar` gains the prop `linked: string[]`. A linked tab renders `⎇ {base(r)}` with class `tab wt`. + - `RepoView` gains the props `linked: boolean` and `onOpen: (path: string) => void`. When `error.gone && linked`, the message reads `Worktree removed` with the path below it (`tilde`), and the "Remove tab" button stays. + +- [ ] **Step 1: Implement the props and the purple `.tab.wt` style.** Colour `#a371f7` for the active state, `#c8a6ff` for inactive, matching the mockup. Add a light-theme variant if the stylesheet has theme blocks. +- [ ] **Step 2:** `npx tsc --noEmit && pnpm test`. Expected: clean. +- [ ] **Step 3: Check in.** + +--- + +### Task 5: Worktree strip, live events, branch badges, checkout refusal UI + +**Files:** +- Create: `src/WorktreeStrip.tsx` +- Modify: `src/RepoView.tsx`, `src/GraphView.tsx`, stylesheet + +**Interfaces:** +- Consumes: `Worktree` type (import from `../server/worktrees.ts`, the same way RepoView imports parse types), `onOpen` from Task 4, and the `heldBy` checkout response from Task 3. +- Produces: + - `WorktreeStrip({ worktrees, home, onOpen }: { worktrees: Worktree[]; home: string; onOpen: (path: string) => void })`. One row per worktree. The label is `branch ?? \`detached @ ${head.slice(0, 7)}\``, and the current row is highlighted. A count badge shows only when `changed > 0`. `title` is `tilde(path, home)`. Clicking calls `onOpen(path)` unless the row is current. The component renders nothing when `worktrees.length === 0`. + - In RepoView: + - `worktrees` state, behind a fingerprint (`fps.current.wt`, a `JSON.stringify` of the list). + - `loadWorktrees()`, which fetches `/api/worktrees` and swallows errors. + - Calls to it on mount, inside every `kick` (the `changed` message), and on a `worktrees` message, which does *not* call `refresh`. + - `es.onmessage = e => e.data === 'worktrees' ? loadWorktrees() : kick()`. + - Layout: the strip is the first child of a new flex row that wraps `.panes`, so the graph's existing column math is untouched. Width is fixed at `160px`, with no splitter. + - GraphView gains the prop `held: Map` (branch → path) for worktrees other than the current one. RepoView builds it with `useMemo`. A local chip whose name is in `held` gets a `⎇` button after its name, titled `open in `. Clicking it calls `onOpen(path)` and `stopPropagation`. + - GraphView's `checkout`: `CheckoutRes` gains `heldBy?: string`. When it is set, show `confirm(\`'${branch}' is open in another worktree:\n${path}\n\nOpen its tab?\`)`, and on OK call `onOpen(heldBy)`. GraphView therefore also takes `onOpen`. + + Ponytail note on the refusal: use native `confirm` as the Open button, the same pattern as the diverged prompt next to it. + +- [ ] **Step 1: Implement.** +- [ ] **Step 2:** `npx tsc --noEmit && pnpm test && pnpm build`. Record the main chunk size against `main` (the strip should add well under 2 kB gz). +- [ ] **Step 3: Check in.** + +--- + +### Task 6: End-to-end verification, perf, docs + +**Files:** +- Modify: `docs/architecture.md` (watcher section and routes list: two SSE message kinds, `/api/worktrees`, `linked`), and `README.md` feature list (one line). + +- [ ] **Step 1: Run the `verify` skill** with an isolated HOME, a scratch repo, and 2 linked worktrees, one of them nested under `.claude/worktrees/`. Check in Playwright: + - The strip shows 3 rows with counts. + - Editing a file in a worktree updates its badge within about 2.5 s, without a graph refetch. Check this in `performance.getEntriesByType('resource')`: no new `/api/graph` entry. + - Clicking a row opens a purple `⎇ ` tab right after the parent tab. + - A commit made in the worktree from a shell shows up in that worktree tab's graph without pressing `r` (goal 1). + - Double-clicking a held branch chip shows the "open in another worktree" prompt, and `git stash list` stays unchanged. +- [ ] **Step 2: Check the single-worktree repo:** no strip, and `/api/worktrees` is called but the server runs exactly one git process for it. Check with a temporary `console.count` or by timing; remove the instrumentation afterwards. +- [ ] **Step 3: Removal.** `git worktree remove` one worktree and `rm -rf` the other. Expected: both drop out of the strip, and an open tab for one shows `Worktree removed` and stays put. +- [ ] **Step 4: Update the docs.** Delete scratch repos with `node -e "fs.rmSync(p,{recursive:true,force:true})"`, and make sure no `.playwright-mcp/` artifacts are staged. +- [ ] **Step 5: Check in.** Report the measured `/api/worktrees` time on bikeleasing-app and the bundle delta. diff --git a/docs/superpowers/specs/2026-10-19-worktree-support-design.md b/docs/superpowers/specs/2026-10-19-worktree-support-design.md new file mode 100644 index 0000000..b444864 --- /dev/null +++ b/docs/superpowers/specs/2026-10-19-worktree-support-design.md @@ -0,0 +1,124 @@ +# Worktree support + +Date: 2026-10-19 + +## Why + +The user runs coding agents (T3 Code, Claude Code, plain terminal) that each work in their own +`git worktree`. megit should let them **watch that work**: which worktrees exist, which ones have +uncommitted changes right now, and what those changes are. Today megit has no idea worktrees exist. + +megit is a viewer here. Worktrees are created and deleted by other tools; megit never does either. + +## What exists today + +- A linked worktree folder can already be added as a tab. `gitDir()` (`server/index.ts:246`) resolves + the real git dir, and every git command works from inside the folder. +- **Auto-refresh is probably broken in such a tab** (from reading the code, not yet confirmed). + `watch.ts` watches `` recursively and treats `.git/HEAD`, `.git/index`, `.git/refs/` as + relevant. In a linked worktree, `.git` is a file; HEAD and index live in + `
/.git/worktrees//`, refs in `
/.git/refs/` + `packed-refs`. File edits refresh; + commits, checkouts, stashes made from a terminal or agent do not. +- Checking out a branch held by another worktree surfaces git's raw + `fatal: '' is already checked out at ''` (newer git: `is already used by worktree at`). +- Only the active tab's `RepoView` is mounted (`src/App.tsx:75`). A tab whose path is gone already gets + a 410 from `repoGuard` and RepoView's "gone" state. + +## Goals + +1. **Auto-refresh works in worktree tabs** — commits, checkouts, stashes, staging done by an agent show + up without a manual refresh. +2. **Worktree strip.** In any repo tab whose repo has more than one worktree, a narrow strip on the left + of the graph lists every worktree of that repo — the main checkout included, the current one + highlighted. Each entry shows its branch (or `detached @ `) and a **live count of changed + files**, hidden when clean. Full path in a tooltip. Clicking an entry opens that worktree as a tab + (registering it if needed) or focuses its tab if already open. +3. **Worktree tabs.** A tab whose folder is a linked worktree is labelled `⎇ ` in purple, and is + placed right after the tab it was opened from (the strip's own tab). Its contents are the normal + RepoView: graph, WIP row, diffs, commit panel — unchanged. +4. **Branch badges.** In the graph's ref pills, a branch checked out in a *different* worktree carries a + `⎇` marker; clicking it does what clicking that worktree in the strip does. +5. **Readable checkout refusal.** When git refuses a checkout because another worktree holds the branch, + show "`` is open in ``" with an **Open** button instead of the raw git message. +6. **Removed worktrees don't break anything.** When an agent deletes its worktree, the strip drops the + entry on the next refresh; an open tab for it falls into the 410 "gone" state, worded "worktree + removed", and stays until the user closes it. megit never closes a tab by itself. + +## Non-goals + +- Creating, removing, pruning, locking or moving worktrees. +- Showing other worktrees' WIP inside one graph (mockup option "B"). Rejected for cost and clutter; the + strip + tabs cover it. +- Live counts for repos in background tabs. Only the active tab is mounted, and that stays true. + +## Anti-goals + +- megit getting slower because agents are busy. Busy agents must cost debounced, bounded work. +- The strip appearing — or any per-worktree work happening — in a repo with no linked worktrees. +- megit touching a worktree's files or state in any way the user didn't click for. + +## Performance (measured 2026-10-19) + +| Command | megit (120 files) | bikeleasing-app (1.3k files) | +|---|---|---| +| `git status --porcelain=v2 -uall` | ~10 ms | ~10 ms | +| `git worktree list --porcelain` | <1 ms | <1 ms | + +Budget: one `git worktree list` per active-tab refresh, plus one `git status` per worktree per strip +refresh (run in parallel), through the existing debouncer (400 ms trailing, 2 s max-wait). Measured on +bikeleasing-app: a linked worktree's `status` settles at 11–14 ms; a freshly created one costs 75–98 ms +for its first ~8 calls (cold filesystem cache), then drops. A per-worktree count cache is the upgrade if +steady-state cost ever shows up. Re-measure on a large repo before shipping; if `status` gets expensive, counting with +`--untracked-files=normal` instead of `-uall` is the first lever (identical on the repos above). + +Keep the RepoView fingerprint pattern: a refresh that yields the same worktree list and counts must not +re-render. + +## Decided + +- Strip, always visible, left of the graph — chosen over a toolbar dropdown because the user wants to + watch counts change live without clicking. Absent entirely when the repo has one worktree. +- Live counts, with the cost above. +- Worktree tabs are ordinary registered repos (same config list, same `repoGuard`), so every existing + feature works in them for free. +- View-only: no worktree mutations. +- Removed worktree → its tab stays, showing "worktree removed", until the user closes it (user's call, + 2026-10-19). Worktree tabs persist across restarts like any other tab. + +## Calls made without the user (check these) + +- **Refusal is detected before any mutation.** `/api/checkout` stashes a dirty tree (`stashIfDirty`) + *before* running `git checkout`, so translating git's error afterwards would leave the user's WIP + stashed for a checkout that never happened. The route checks `git worktree list --porcelain` for the + target branch first and returns `{ heldBy: }` without touching anything. No fallback on git's message: the window + between the check and the checkout is milliseconds. +- **Readable refusal covers** checkout, the reset-to-remote checkout (`checkout -B`), and branch delete + ("used by worktree"). Rename, rebase and merge keep git's raw text. +- **Tab label is `⎇ `**, not the branch. The folder name never changes, so background tabs + need no git per refresh. "Is this a linked worktree" is read from the folder's `.git` file + (`gitdir: …/worktrees/`), no git process. This applies to any linked worktree tab, however it was + added. The live branch is visible in the strip and graph. +- **Worktree tabs opened from the strip don't enter `recent`.** Short-lived agent folders would push + real repos out of the 12-entry list. +- **Nested-worktree exclusion uses every path git knows** (`git worktree list`), not only the ones open + as tabs. That means the parent watcher's filter gets a per-repo exclusion list that changes over time. + +## Left to the builder + +- Wire shape: a new `/api/worktrees` route vs. folding the list into `/api/status`; how live counts reach + the client (a new SSE event type on the existing `/api/events` stream, or a separate stream). +- How the watcher covers a linked worktree's git dir and the shared refs (goal 1), and how worktree + folders are watched for counts — `subscribe()` already accepts any path and dedupes per path. +- **Nested worktrees.** Some tools put worktrees *inside* the repo (Claude Code uses `.claude/worktrees/`). + The main checkout's recursive watcher sees every agent edit there as its own working-tree change and + refetches. Check this; if so, exclude registered worktree paths from the parent's watcher — they are + counted by their own. +- How a tab knows it's a linked worktree (e.g. `--git-dir` ≠ `--git-common-dir`, cached like `gitDirs`) + and where its parent lives, for the label and tab placement. +- Strip width/collapse, colours, and behaviour for prunable entries (`git worktree list` marks + worktrees whose folder is gone `prunable`; hide them). +- Detecting the checkout refusal: match both git message variants, extract the path, return it + structured so the client doesn't parse English. +- Tests: pure parsing of `git worktree list --porcelain` in `parse.ts`; watcher relevance for worktree + git dirs in `watch.test.ts`; a real two-worktree fixture for the refresh path. `scripts/make-test-repo.sh` + could add one linked worktree so screenshots show the strip. diff --git a/server/index.ts b/server/index.ts index 21b997b..94a29cd 100644 --- a/server/index.ts +++ b/server/index.ts @@ -9,7 +9,7 @@ import { resolveAvatar, parseGithubRemote } from './avatars.ts' import { mergeMatches, parseBranchHeader, parseLog, parseMatches, parseMeta, parseNameStatus, parseStatus, stashIndex, LOG_FORMAT, META_FORMAT } from './parse.ts' import { pickOperation, STATE_FILES, type OpKind } from './operation.ts' import { checkoutPlan } from './checkout.ts' -import { subscribe } from './watch.ts' +import { heldBy, isLinkedWorktree, watchRepo, worktreesWithCounts } from './worktrees.ts' import { wireTerminal, hasPty } from './term.ts' // JSON bodies are capped at 10mb by createApp — a resolved conflicted file goes @@ -79,7 +79,8 @@ const repoGuard: Handler = (req, res, next) => { // capability can't be clobbered by a later /api/active or /api/repos response. // home rides along so the client can print ~/ instead of the full prefix; the // server is the only side that knows it. -const withCaps = (c: Config) => ({ ...c, hasTerminal: hasPty(), home: homedir() }) +// linked: registered paths that are linked worktrees, so the client can badge their tabs +const withCaps = (c: Config) => ({ ...c, hasTerminal: hasPty(), home: homedir(), linked: c.repos.filter(isLinkedWorktree) }) app.get('/api/config', (_req, res) => res.json(withCaps(loadConfig()))) @@ -92,9 +93,15 @@ app.post('/api/repos', async (req, res) => { return } const cfg = loadConfig() - if (!cfg.repos.includes(path)) cfg.repos.push(path) + // `after` (opening a worktree from its sibling's tab) seats the new tab next to + // that one and skips recent — a worktree isn't a repo the user browsed to + const after = typeof req.body.after === 'string' ? cfg.repos.indexOf(req.body.after) : -1 + if (!cfg.repos.includes(path)) { + if (after >= 0) cfg.repos.splice(after + 1, 0, path) + else cfg.repos.push(path) + } cfg.activeRepo = path - cfg.recent = touchRecent(cfg.recent, path) + if (after < 0) cfg.recent = touchRecent(cfg.recent, path) saveConfig(cfg) res.json(withCaps(cfg)) }) @@ -282,6 +289,14 @@ app.get('/api/status', repoGuard, async (req, res) => { } }) +app.get('/api/worktrees', repoGuard, async (req, res) => { + try { + res.json({ worktrees: await worktreesWithCounts(String(req.query.repo), git) }) + } catch (e) { + res.status(500).json({ error: (e as Error).message }) + } +}) + // resolves to a sha, or null when the ref doesn't exist (--quiet: exit 1, empty output) async function revParse(repo: string, ref: string): Promise { const out = await git(repo, ['rev-parse', '--verify', '--quiet', ref], [0, 1]) @@ -318,6 +333,12 @@ app.post('/api/checkout', repoGuard, async (req, res) => { return } try { + // before any status/stash: git would refuse the checkout anyway, after we'd stashed + const holder = await heldBy(repo, branch, git) + if (holder) { + res.json({ heldBy: holder }) + return + } const dirty = (await git(repo, ['status', '--porcelain'])).trim() !== '' const stash = (why: string) => stashIfDirty(repo, why) const remotes = (await git(repo, ['remote'])).split('\n').filter(Boolean) @@ -483,6 +504,8 @@ app.post('/api/branch', repoGuard, async (req, res) => { const branch = mustExist(await locals(), req.body.branch, 'branch') const current = (await git(repo, ['branch', '--show-current'])).trim() if (branch === current) throw httpError(409, 'cannot delete the checked-out branch') + const holder = await heldBy(repo, branch, git) + if (holder) throw httpError(409, `'${branch}' is checked out in ${holder}`) // -d refuses to drop unmerged work; the client re-asks and sends force await git(repo, ['branch', req.body.force === true ? '-D' : '-d', branch]) break @@ -706,26 +729,32 @@ app.get('/api/events', repoGuard, (req, res) => { res.write(': connected\n\n') const ping = setInterval(() => res.write(': ping\n\n'), 30_000) let unsub: (() => void) | null = null + let done = false + // idempotent: onError can fire per watcher, and before watchRepo has resolved const cleanup = () => { + if (done) return + done = true clearInterval(ping) unsub?.() unsub = null } - try { - unsub = subscribe( - repo, - () => res.write('data: changed\n\n'), - () => { - cleanup() - res.end() - }, - ) - } catch { - // watcher couldn't start (EMFILE, permissions) — client degrades to manual refresh + const send = (kind: string) => { + if (!done) res.write(`data: ${kind}\n\n`) + } + watchRepo(repo, git, send, () => { cleanup() res.end() - return - } + }).then( + u => { + if (done) u() // closed or errored while the initial reconcile ran + else unsub = u + }, + () => { + // watcher couldn't start (EMFILE, permissions) — client degrades to manual refresh + cleanup() + res.end() + }, + ) req.on('close', cleanup) }) diff --git a/server/parse.test.ts b/server/parse.test.ts index 1842425..6521d52 100644 --- a/server/parse.test.ts +++ b/server/parse.test.ts @@ -1,5 +1,5 @@ import { describe, it, expect } from 'vitest' -import { mergeMatches, parseBranchHeader, parseLog, parseMatches, parseMeta, parseNameStatus, parseStatus, stashIndex } from './parse.ts' +import { mergeMatches, parseBranchHeader, parseLog, parseMatches, parseMeta, parseNameStatus, parseStatus, parseWorktrees, stashIndex } from './parse.ts' const F = '\x1f' const R = '\x1e' @@ -190,3 +190,35 @@ describe('mergeMatches', () => { expect(mergeMatches([[], []])).toEqual({ matches: [], truncated: false }) }) }) + +describe('parseWorktrees', () => { + it('parses main, linked and detached records', () => { + const raw = 'worktree /r\nHEAD aaa\nbranch refs/heads/main\n\nworktree /r-wt\nHEAD bbb\nbranch refs/heads/feat/x\n\nworktree /tmp/a b/ü\nHEAD ccc\ndetached\n\n' + expect(parseWorktrees(raw)).toEqual([ + { path: '/r', head: 'aaa', branch: 'main', prunable: false, bare: false }, + { path: '/r-wt', head: 'bbb', branch: 'feat/x', prunable: false, bare: false }, + { path: '/tmp/a b/ü', head: 'ccc', branch: null, prunable: false, bare: false }, + ]) + }) + + it('tolerates a missing or doubled trailing blank line', () => { + const want = [{ path: '/r', head: 'aaa', branch: 'main', prunable: false, bare: false }] + expect(parseWorktrees('worktree /r\nHEAD aaa\nbranch refs/heads/main\n')).toEqual(want) + expect(parseWorktrees('worktree /r\nHEAD aaa\nbranch refs/heads/main\n\n\n')).toEqual(want) + }) + + it('flags prunable records', () => { + const raw = 'worktree /r\nHEAD aaa\nbranch refs/heads/main\n\nworktree /gone\nHEAD bbb\nbranch refs/heads/x\nprunable gitdir file points to non-existent location\n\n' + expect(parseWorktrees(raw)[1]).toEqual({ path: '/gone', head: 'bbb', branch: 'x', prunable: true, bare: false }) + }) + + it('flags bare records', () => { + expect(parseWorktrees('worktree /r.git\nbare\n\n')).toEqual([ + { path: '/r.git', head: '', branch: null, prunable: false, bare: true }, + ]) + }) + + it('empty input is empty', () => { + expect(parseWorktrees('')).toEqual([]) + }) +}) diff --git a/server/parse.ts b/server/parse.ts index 17a7ca2..6d5ead2 100644 --- a/server/parse.ts +++ b/server/parse.ts @@ -175,3 +175,30 @@ export function parseNameStatus(raw: string): { status: string; path: string }[] } return out } + +export type WorktreeEntry = { path: string; head: string; branch: string | null; prunable: boolean; bare: boolean } + +// `git worktree list --porcelain` (git ≥ 2.7): `key value` lines, records +// separated by a blank line. Unknown keys (locked, …) are ignored. +// ponytail: a path containing a newline mis-parses — unrealistic; `-z` (git ≥ 2.36) +// is the upgrade once older git no longer matters. +export function parseWorktrees(raw: string): WorktreeEntry[] { + const out: WorktreeEntry[] = [] + let cur: WorktreeEntry | null = null + for (const f of raw.split('\n')) { + if (!f) { + cur = null + continue + } + const sp = f.indexOf(' ') + const key = sp < 0 ? f : f.slice(0, sp) + const val = sp < 0 ? '' : f.slice(sp + 1) + if (key === 'worktree') out.push((cur = { path: val, head: '', branch: null, prunable: false, bare: false })) + else if (!cur) continue + else if (key === 'HEAD') cur.head = val + else if (key === 'branch') cur.branch = val.replace(/^refs\/heads\//, '') + else if (key === 'prunable') cur.prunable = true + else if (key === 'bare') cur.bare = true + } + return out +} diff --git a/server/watch.test.ts b/server/watch.test.ts index 521164f..4bab1bf 100644 --- a/server/watch.test.ts +++ b/server/watch.test.ts @@ -1,10 +1,10 @@ import { describe, it, expect, vi, afterEach } from 'vitest' -import { isRelevant, createDebouncer } from './watch.ts' -import { mkdtempSync, writeFileSync, rmSync } from 'node:fs' +import { isRelevant, isGitDirRelevant, createDebouncer } from './watch.ts' +import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { execFileSync } from 'node:child_process' -import { subscribe, activeWatcherCount } from './watch.ts' +import { subscribe, setIgnored, activeWatcherCount } from './watch.ts' describe('isRelevant', () => { it.each<[string, boolean]>([ @@ -31,11 +31,29 @@ describe('isRelevant', () => { ['.git/logs/HEAD', false], ['.git/FETCH_HEAD', false], ['.git/COMMIT_EDITMSG', false], + ['.git/worktrees/feat/HEAD', true], + ['.git/worktrees/feat/index', true], + ['.git/worktrees/feat/index.lock', false], + ['.git/worktrees/feat/logs/HEAD', false], ])('%s → %s', (path, expected) => { expect(isRelevant(path)).toBe(expected) }) }) +describe('isGitDirRelevant', () => { + it.each<[string, boolean]>([ + ['HEAD', true], + ['refs/heads/x', true], + ['packed-refs', true], + ['worktrees/a/HEAD', true], + ['worktrees/a/ORIG_HEAD', false], + ['objects/ab/cd', false], + ['worktrees/a/b/HEAD', false], + ])('%s → %s', (path, expected) => { + expect(isGitDirRelevant(path)).toBe(expected) + }) +}) + describe('createDebouncer', () => { it('coalesces a burst into one trailing flush', () => { vi.useFakeTimers() @@ -182,4 +200,45 @@ integration('subscribe (integration, real fs + timers)', () => { rmSync(dir, { recursive: true, force: true }) } }, 15000) + + it('linked worktree: commit fires a subscription on the common git dir', async () => { + const root = mkdtempSync(join(tmpdir(), 'megit-watch-')) + try { + const dir = join(root, 'main') + const wt = join(root, 'wt') + execFileSync('git', ['init', dir]) + const git = (cwd: string, ...a: string[]) => + execFileSync('git', ['-C', cwd, '-c', 'user.email=t@t', '-c', 'user.name=t', ...a]) + git(dir, 'commit', '--allow-empty', '-m', 'init') + git(dir, 'worktree', 'add', wt, '-b', 'wt') + let events = 0 + const unsub = subscribe(join(dir, '.git'), () => { events++ }, () => {}, isGitDirRelevant) + await sleep(300) // FSEvents warm-up + git(wt, 'commit', '--allow-empty', '-m', 'in wt') + await waitFor(() => events >= 1, 5000) + unsub() + } finally { + rmSync(root, { recursive: true, force: true }) + } + }, 15000) + + it('setIgnored drops events under an ignored prefix', async () => { + const dir = mkdtempSync(join(tmpdir(), 'megit-watch-')) + try { + execFileSync('git', ['-C', dir, 'init']) + mkdirSync(join(dir, 'nested')) + let events = 0 + const unsub = subscribe(dir, () => { events++ }, () => {}) + setIgnored(dir, ['nested']) + await sleep(300) // FSEvents warm-up + writeFileSync(join(dir, 'nested', 'x.txt'), 'x') + await sleep(2500) // past the debouncer's max-wait + expect(events).toBe(0) + writeFileSync(join(dir, 'top.txt'), 'x') + await waitFor(() => events >= 1, 5000) + unsub() + } finally { + rmSync(dir, { recursive: true, force: true }) + } + }, 15000) }) diff --git a/server/watch.ts b/server/watch.ts index 12dbb0a..a40837e 100644 --- a/server/watch.ts +++ b/server/watch.ts @@ -15,8 +15,16 @@ export function isRelevant(rel: string): boolean { if (rel === '.git') return false if (NOISE.test(rel)) return false if (!rel.startsWith('.git/')) return true - const inner = rel.slice('.git/'.length) - return inner === 'HEAD' || inner === 'index' || inner === 'packed-refs' || inner.startsWith('refs/') + return isGitDirRelevant(rel.slice('.git/'.length)) +} + +// rel is relative to a git *common* dir. A linked worktree keeps its own HEAD and +// index under worktrees//, so a commit there is visible from the common dir. +export function isGitDirRelevant(rel: string): boolean { + return ( + rel === 'HEAD' || rel === 'index' || rel === 'packed-refs' || rel.startsWith('refs/') || + /^worktrees\/[^/]+\/(HEAD|index)$/.test(rel) + ) } export type Debouncer = { hit: () => void; dispose: () => void } @@ -46,7 +54,7 @@ export function createDebouncer(fire: () => void, delay = 400, maxWait = 2000): } type Sub = { onChange: () => void; onError: () => void } -type Entry = { watcher: FSWatcher; debouncer: Debouncer; subs: Set } +type Entry = { watcher: FSWatcher; debouncer: Debouncer; subs: Set; ignored: string[] } const entries = new Map() @@ -55,8 +63,21 @@ export function activeWatcherCount(): number { return entries.size } -// One shared recursive watcher per repo, alive only while subscribed. -export function subscribe(repo: string, onChange: () => void, onError: () => void): () => void { +// Events under these rel prefixes (e.g. a nested worktree inside the repo) are +// dropped before the relevance filter. No-op when `repo` has no live entry. +export function setIgnored(repo: string, prefixes: string[]): void { + const entry = entries.get(repo) + if (entry) entry.ignored = prefixes +} + +// One shared recursive watcher per repo, alive only while subscribed. The first +// subscriber's `relevant` filter wins for a path; callers pass the same one per kind. +export function subscribe( + repo: string, + onChange: () => void, + onError: () => void, + relevant: (rel: string) => boolean = isRelevant, +): () => void { let entry = entries.get(repo) if (!entry) { // fs.watch does not agree across platforms about a path that isn't there: @@ -72,11 +93,16 @@ export function subscribe(repo: string, onChange: () => void, onError: () => voi const debouncer = createDebouncer(() => { for (const s of subs) s.onChange() }) + const fresh: Entry = { watcher: undefined as unknown as FSWatcher, debouncer, subs, ignored: [] } const watcher = watch(repo, { recursive: true }, (_event, filename) => { // null filename: platform couldn't tell — refresh conservatively - if (filename === null || isRelevant(filename.toString())) debouncer.hit() + if (filename === null) return debouncer.hit() + // Windows reports backslashes; the ignore prefixes and relevance rules are '/'-based + const rel = filename.toString().replaceAll('\\', '/') + if (fresh.ignored.some(p => rel === p || rel.startsWith(p + '/'))) return + if (relevant(rel)) debouncer.hit() }) - const fresh: Entry = { watcher, debouncer, subs } + fresh.watcher = watcher watcher.on('error', () => { entries.delete(repo) debouncer.dispose() diff --git a/server/worktrees.test.ts b/server/worktrees.test.ts new file mode 100644 index 0000000..3fac402 --- /dev/null +++ b/server/worktrees.test.ts @@ -0,0 +1,187 @@ +import { describe, it, expect, afterEach, vi } from 'vitest' +import { mkdtempSync, mkdirSync, writeFileSync, rmSync, realpathSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { execFile, execFileSync } from 'node:child_process' +import { isLinkedWorktree, isWorktreeGitdir, listWorktrees, worktreesWithCounts, heldBy, watchRepo } from './worktrees.ts' +import { activeWatcherCount } from './watch.ts' + +const git = (repo: string, args: string[], okCodes: number[] = [0]): Promise => + new Promise((res, rej) => { + execFile('git', ['-C', repo, ...args], (err, stdout, stderr) => { + if (err && !okCodes.includes(typeof err.code === 'number' ? err.code : 1)) rej(new Error(stderr.trim() || err.message)) + else res(stdout) + }) + }) + +const run = (cwd: string, ...a: string[]) => + execFileSync('git', ['-C', cwd, '-c', 'user.email=t@t', '-c', 'user.name=t', ...a]) + +const sleep = (ms: number) => new Promise(r => setTimeout(r, ms)) +async function waitFor(cond: () => boolean, timeoutMs: number): Promise { + const deadline = Date.now() + timeoutMs + while (!cond()) { + if (Date.now() > deadline) throw new Error('waitFor timed out') + await sleep(50) + } +} + +// root is deliberately NOT realpath'd: macOS tmpdir is a /var → /private/var +// symlink, and git lists resolved paths — the code under test must cope. +const roots: string[] = [] +function fixture() { + const root = mkdtempSync(join(tmpdir(), 'megit-wt-')) + roots.push(root) + const repo = join(root, 'main') + const wt = join(root, 'wt') + execFileSync('git', ['init', '-b', 'main', repo]) + run(repo, 'commit', '--allow-empty', '-m', 'init') + run(repo, 'worktree', 'add', wt, '-b', 'feat') + return { root, repo, wt } +} + +afterEach(() => { + for (const r of roots.splice(0)) rmSync(r, { recursive: true, force: true }) +}) + +describe('isWorktreeGitdir', () => { + it('matches only a gitdir that ends in worktrees/', () => { + expect(isWorktreeGitdir('/r/.git/worktrees/wt')).toBe(true) + expect(isWorktreeGitdir('/r/.git/worktrees/wt/')).toBe(true) + expect(isWorktreeGitdir('C:\\r\\.git\\worktrees\\wt')).toBe(true) + expect(isWorktreeGitdir('/r/.git/modules/sub')).toBe(false) + // a submodule inside a linked worktree is not itself a linked worktree + expect(isWorktreeGitdir('/r/.git/worktrees/wt/modules/sub')).toBe(false) + }) +}) + +describe('heldBy', () => { + it('fails open: a git error answers null so git\'s own refusal applies', async () => { + const broken = async () => { throw new Error('unknown option -z') } + expect(await heldBy(tmpdir(), 'main', broken)).toBeNull() + }) +}) + +// see watch.test.ts: real recursive fs.watch kills the vitest worker on Windows +const integration = process.platform === 'win32' ? describe.skip : describe + +integration('worktrees (integration)', () => { + it('isLinkedWorktree', () => { + const { root, repo, wt } = fixture() + expect(isLinkedWorktree(wt)).toBe(true) + expect(isLinkedWorktree(repo)).toBe(false) + expect(isLinkedWorktree(join(root, 'nope'))).toBe(false) + }) + + it('worktreesWithCounts counts changes and marks the current one', async () => { + const { repo, wt } = fixture() + writeFileSync(join(wt, 'file.txt'), 'x') + const list = await worktreesWithCounts(repo, git) + expect(list).toHaveLength(2) + const w = list.find(x => x.path === realpathSync(wt))! + const r = list.find(x => x.path === realpathSync(repo))! + expect(w).toMatchObject({ branch: 'feat', changed: 1, current: false }) + expect(r).toMatchObject({ branch: 'main', changed: 0, current: true }) + }) + + it('single worktree: [] without running status', async () => { + const root = mkdtempSync(join(tmpdir(), 'megit-wt-')) + roots.push(root) + execFileSync('git', ['init', '-b', 'main', root]) + run(root, 'commit', '--allow-empty', '-m', 'init') + const spy = vi.fn(git) + expect(await worktreesWithCounts(root, spy)).toEqual([]) + expect(spy).toHaveBeenCalledTimes(1) + expect(spy.mock.calls[0][1]).toEqual(['worktree', 'list', '--porcelain']) + }) + + it('heldBy names a different worktree holding the branch', async () => { + const { repo, wt } = fixture() + expect(await heldBy(repo, 'feat', git)).toBe(realpathSync(wt)) + expect(await heldBy(repo, 'main', git)).toBeNull() // main is current + expect(await heldBy(wt, 'main', git)).toBe(realpathSync(repo)) + }) + + it('listWorktrees drops a removed worktree', async () => { + const { repo, wt } = fixture() + run(repo, 'worktree', 'remove', wt) + const paths = (await listWorktrees(repo, git)).map(w => w.path) + expect(paths).toEqual([realpathSync(repo)]) + }) +}) + +integration('watchRepo (integration, real fs + timers)', () => { + afterEach(() => { + expect(activeWatcherCount(), 'test leaked a watcher into the shared registry').toBe(0) + }) + + // warm up FSEvents and let any events from fixture setup flush past the debounce + async function settle(events: string[]) { + await sleep(700) + events.length = 0 + } + + it('a commit inside a linked worktree sends changed', async () => { + const { wt } = fixture() + const events: string[] = [] + const unsub = await watchRepo(wt, git, k => events.push(k), () => {}) + try { + await settle(events) + run(wt, 'commit', '--allow-empty', '-m', 'in wt') + await waitFor(() => events.includes('changed'), 5000) + } finally { + unsub() + } + }, 15000) + + it('editing a sibling worktree sends worktrees, not changed', async () => { + const { repo, wt } = fixture() + const events: string[] = [] + const unsub = await watchRepo(repo, git, k => events.push(k), () => {}) + try { + await settle(events) + writeFileSync(join(wt, 'file.txt'), 'x') + await waitFor(() => events.includes('worktrees'), 5000) + await sleep(800) + expect(events).not.toContain('changed') + } finally { + unsub() + } + }, 15000) + + it('a worktree nested inside the repo sends worktrees only', async () => { + const { repo } = fixture() + const n = join(repo, '.claude', 'worktrees', 'n') + mkdirSync(join(repo, '.claude', 'worktrees'), { recursive: true }) + run(repo, 'worktree', 'add', n, '-b', 'n') + const events: string[] = [] + const unsub = await watchRepo(repo, git, k => events.push(k), () => {}) + try { + await settle(events) + writeFileSync(join(n, 'f'), 'x') + await waitFor(() => events.includes('worktrees'), 5000) + await sleep(2500) // past the debouncer's max-wait + expect(events).not.toContain('changed') + } finally { + unsub() + } + }, 15000) + + it('viewing a nested worktree: an edit inside it sends changed, not worktrees', async () => { + const { repo } = fixture() + const n = join(repo, '.claude', 'worktrees', 'n') + mkdirSync(join(repo, '.claude', 'worktrees'), { recursive: true }) + run(repo, 'worktree', 'add', n, '-b', 'n') + const events: string[] = [] + const unsub = await watchRepo(n, git, k => events.push(k), () => {}) + try { + await settle(events) + writeFileSync(join(n, 'f'), 'x') + await waitFor(() => events.includes('changed'), 5000) + await sleep(2500) // past the debouncer's max-wait + expect(events).not.toContain('worktrees') + } finally { + unsub() + } + }, 15000) +}) diff --git a/server/worktrees.ts b/server/worktrees.ts new file mode 100644 index 0000000..200653f --- /dev/null +++ b/server/worktrees.ts @@ -0,0 +1,150 @@ +// Linked worktrees: listing, per-worktree change counts, which worktree holds a +// branch, and the watch set that keeps a repo tab fresh across all of them. + +import { readFileSync } from 'node:fs' +import { realpath } from 'node:fs/promises' +import { isAbsolute, join, relative, resolve, sep } from 'node:path' +import { parseStatus, parseWorktrees } from './parse.ts' +import type { WorktreeEntry } from './parse.ts' +import { isGitDirRelevant, isRelevant, setIgnored, subscribe } from './watch.ts' + +export type Git = (repo: string, args: string[], okCodes?: number[]) => Promise + +export type Worktree = { path: string; branch: string | null; head: string; changed: number; current: boolean } + +// git lists resolved paths; the caller's may go through a symlink (macOS /var → +// /private/var), so every path comparison happens after realpath on both sides. +// A path that no longer exists compares as given. +const real = (p: string) => realpath(p).catch(() => p) + +// A linked worktree's .git is a file pointing into /worktrees/; +// a submodule's points into .../modules/ instead and is not one — including +// a submodule of a linked worktree (.../worktrees//modules/), hence the anchor. +export const isWorktreeGitdir = (gitdir: string) => /[\\/]worktrees[\\/][^\\/]+[\\/]?$/.test(gitdir.trim()) + +export function isLinkedWorktree(dir: string): boolean { + try { + const m = readFileSync(join(dir, '.git'), 'utf8').match(/^gitdir: (.*)$/m) + return !!m && isWorktreeGitdir(m[1]) + } catch { + return false // missing, or a directory (main worktree) + } +} + +export async function listWorktrees(repo: string, git: Git): Promise { + const raw = await git(repo, ['worktree', 'list', '--porcelain']) + return parseWorktrees(raw).filter(w => !w.prunable && !w.bare) +} + +// ponytail: every worktree's status is recomputed on every call — one process per +// worktree, in parallel. A per-path dirty cache (invalidated by the watch set) is +// the upgrade if this ever shows up in a measurement. +export async function worktreesWithCounts(repo: string, git: Git): Promise { + const list = await listWorktrees(repo, git) + if (list.length <= 1) return [] + const self = await real(repo) + return Promise.all( + list.map(async w => { + // --no-optional-locks: status must not refresh .git/worktrees//index, a watched path (changed → refetch → status echo) + const changed = await git(w.path, ['--no-optional-locks', 'status', '--porcelain=v2', '-uall', '-z']).then( + raw => parseStatus(raw).length, + () => 0, + ) + return { path: w.path, branch: w.branch, head: w.head, changed, current: (await real(w.path)) === self } + }), + ) +} + +// The path of a *different* worktree that has `branch` checked out — git refuses +// to check it out a second time. Fails open: on any error git's own refusal still +// applies, and nothing is stashed yet when it does (the stash comes after this). +export async function heldBy(repo: string, branch: string, git: Git): Promise { + try { + const self = await real(repo) + for (const w of await listWorktrees(repo, git)) { + if (w.branch === branch && (await real(w.path)) !== self) return w.path + } + } catch { /* fall through */ } + return null +} + +// Watches `repo` (sends 'changed'), its common git dir when it is a linked +// worktree (a commit there lands in the common dir, not the worktree), and every +// sibling worktree (sends 'worktrees', so only the counts refetch). The sibling set +// is reconciled after each 'changed' fire, since worktree add/remove touches the +// common dir. A worktree nested inside any watched root (`repo` or a sibling) is +// ignored by that root's watcher and counted by its own. +export async function watchRepo( + repo: string, + git: Git, + send: (kind: 'changed' | 'worktrees') => void, + onError: () => void, +): Promise<() => void> { + const self = await real(repo) + const common = isLinkedWorktree(repo) + // not --path-format=absolute (git ≥ 2.31): the bare form may print a relative path + ? resolve(repo, (await git(repo, ['rev-parse', '--git-common-dir'])).trim()) + : null + const siblings = new Map void>() // realpath → unsubscribe + let closed = false + let queue: Promise = Promise.resolve() + + // serialized so two overlapping runs can't both subscribe the same new sibling + const reconcile = () => + (queue = queue + .then(async () => { + if (closed) return + const paths = await Promise.all((await listWorktrees(repo, git)).map(w => real(w.path))) + if (closed) return + const others = new Set(paths.filter(p => p !== self)) + for (const [p, unsub] of siblings) { + if (!others.has(p)) { + unsub() + siblings.delete(p) + } + } + for (const p of others) { + if (siblings.has(p)) continue + try { + siblings.set(p, subscribe(p, () => send('worktrees'), () => siblings.delete(p), isRelevant)) + } catch { + // gone since listing — it is prunable or absent next time round + } + } + // Every watched root ignores the worktrees nested under it: each is counted + // by its own watcher, and a parent's count never includes them — so this is + // right for every subscriber sharing the entry. Without it, viewing nested N + // fires 'worktrees' from parent M's sibling watcher on every edit in N. + // Re-applied every run: the ignore list lives on the watcher entry and is + // lost if that watcher errors and is re-created. + const nestedUnder = (root: string) => + paths + .map(p => relative(root, p)) + .filter(rel => rel && !rel.startsWith('..') && !isAbsolute(rel)) + .map(rel => rel.split(sep).join('/')) + setIgnored(repo, nestedUnder(self)) + for (const p of siblings.keys()) setIgnored(p, nestedUnder(p)) + }) + .catch(() => {})) + + const changed = () => { + send('changed') + void reconcile() + } + const unsubs = [subscribe(repo, changed, onError, isRelevant)] + if (common) { + try { + unsubs.push(subscribe(common, changed, onError, isGitDirRelevant)) + } catch (e) { + unsubs[0]() + throw e + } + } + await reconcile() + return () => { + closed = true + for (const u of unsubs) u() + for (const u of siblings.values()) u() + siblings.clear() + } +} diff --git a/src/App.tsx b/src/App.tsx index 6e87698..a44233a 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -1,13 +1,13 @@ -import { Component, useEffect, useState, type ReactNode } from 'react' +import { Component, useEffect, useRef, useState, type ReactNode } from 'react' import { api, jsonInit } from './api' import TabBar from './TabBar' import DirBrowser from './DirBrowser' import RepoView from './RepoView' -import Toasts from './Toast' +import Toasts, { toastErr } from './Toast' import Settings from './SettingsDialog' // hasTerminal is server-reported: node-pty is optional and has no Linux prebuild -export type Config = { repos: string[]; activeRepo: string | null; recent: string[]; hasTerminal: boolean; home: string } +export type Config = { repos: string[]; activeRepo: string | null; recent: string[]; hasTerminal: boolean; home: string; linked: string[] } // Fetch failures already surface inside RepoView; a *render* throw is the one that // unmounts the tree and leaves a blank window with only the console to explain it. @@ -36,13 +36,22 @@ export default function App() { const [browsing, setBrowsing] = useState(false) const [settingsOpen, setSettingsOpen] = useState(false) + // Session union: the server stops reporting a worktree once its directory is gone, but the tab must stay marked. + const everLinked = useRef(new Set()) useEffect(() => { api('/api/config').then(setCfg) }, []) if (!cfg) return null + for (const p of cfg.linked) everLinked.current.add(p) + const linked = cfg.repos.filter(r => everLinked.current.has(r)) const select = (repo: string) => { setCfg({ ...cfg, activeRepo: repo }) api('/api/active', jsonInit('PUT', { repo })) } + // `after` seats a worktree opened from the strip beside the tab that opened it. + const open = (path: string) => { + if (cfg.repos.includes(path)) return select(path) + api('/api/repos', jsonInit('POST', { path, after: cfg.activeRepo })).then(setCfg).catch(e => toastErr(e.message)) + } const close = (repo: string) => api(`/api/repos?repo=${encodeURIComponent(repo)}`, { method: 'DELETE' }).then(setCfg) @@ -56,7 +65,7 @@ export default function App() { return (
- setBrowsing(true)} onClose={close} onReorder={reorder} onReorderEnd={reorderEnd} onSettings={() => setSettingsOpen(true)} /> + setBrowsing(true)} onClose={close} onReorder={reorder} onReorderEnd={reorderEnd} onSettings={() => setSettingsOpen(true)} /> {browsing && ( - close(cfg.activeRepo!)} hasTerminal={cfg.hasTerminal} /> + close(cfg.activeRepo!)} hasTerminal={cfg.hasTerminal} /> ) :
No repository open — add one with “+”
} diff --git a/src/GraphView.tsx b/src/GraphView.tsx index caa1dee..60786ee 100644 --- a/src/GraphView.tsx +++ b/src/GraphView.tsx @@ -9,6 +9,7 @@ import { rowOrder, sameRow, step } from './rowNav' import type { Selection } from './RepoView' import { toastErr } from './Toast' import { useAvatar, initials } from './avatar' +import { tilde } from './paths' const ROW = 28 const COL = 18 @@ -175,7 +176,7 @@ const fmtDate = (unix: number) => { return new Date(unix * 1000).toLocaleDateString(undefined, { year: '2-digit', month: 'short', day: 'numeric' }) } -function CommitRow({ repo, c, row, width, remotes, selected, onSelect, dashes, trail, onCheckout, onChipMenu, onRowMenu }: { +function CommitRow({ repo, c, row, width, remotes, selected, onSelect, dashes, trail, onCheckout, onChipMenu, onRowMenu, held, home, onOpen }: { repo: string c: Commit row: LaneRow @@ -188,6 +189,9 @@ function CommitRow({ repo, c, row, width, remotes, selected, onSelect, dashes, t onCheckout: (branch: string, fromRemote?: boolean) => void onChipMenu: (e: ReactMouseEvent, chip: RefChip, hash: string) => void onRowMenu: (e: ReactMouseEvent, hash: string) => void + held: Map + home: string + onOpen: (path: string) => void }) { const isMerge = c.parents.length > 1 const avatarUrl = useAvatar(repo, isMerge ? null : c.email) @@ -204,7 +208,8 @@ function CommitRow({ repo, c, row, width, remotes, selected, onSelect, dashes, t // icon count feeds the chip's flex-basis so every name gets the same // number of pixels (see .ref-chip); icons are unshrinkable, so a chip // that carries three of them would otherwise lose its whole name first - const nIcons = (chip.head ? 1 : 0) + (chip.tag ? 1 : 0) + (chip.local && !chip.tag ? 1 : 0) + (chip.remote ? 1 : 0) + const wt = chip.local && !chip.tag ? held.get(chip.name) : undefined + const nIcons = (chip.head ? 1 : 0) + (chip.tag ? 1 : 0) + (chip.local && !chip.tag ? 1 : 0) + (chip.remote ? 1 : 0) + (wt ? 1 : 0) return ( } {chip.local && !chip.tag && } {chip.remote && } + {/* checked out in another worktree: jump to its tab. Swallows dblclick and + contextmenu too, or the chip would also checkout / open its menu */} + {wt && ( + + )} ) })} @@ -294,7 +310,7 @@ function StashRow({ s, lane, passRow, width, dashes, trailLane, selected, onSele ) } -function GraphView({ repo, commits, status, remotes, stashes, githubUrl, selection, onSelect, onLoadMore, hasMore, onBusy }: { +function GraphView({ repo, commits, status, remotes, stashes, githubUrl, selection, onSelect, onLoadMore, hasMore, onBusy, held, home, onOpen }: { repo: string commits: Commit[] status: StatusEntry[] @@ -306,6 +322,9 @@ function GraphView({ repo, commits, status, remotes, stashes, githubUrl, selecti onLoadMore: () => void hasMore: boolean onBusy: (p: Promise) => void + held: Map // branch → path, for worktrees other than this one + home: string + onOpen: (path: string) => void }) { const headIdx = useMemo(() => commits.findIndex(c => c.refs.some(r => r === 'HEAD' || r.startsWith('HEAD -> '))), [commits]) const headHash = headIdx >= 0 ? commits[headIdx].hash : undefined @@ -348,11 +367,17 @@ function GraphView({ repo, commits, status, remotes, stashes, githubUrl, selecti const branchApi = (body: object, label: string) => onBusy(branchPost(body).catch(err => toastErr(`${label} failed:\n${(err as Error).message}`))) const checkout = (branch: string, fromRemote = false) => { - type CheckoutRes = { diverged?: boolean; remoteRef?: string; ahead?: number; behind?: number } + type CheckoutRes = { diverged?: boolean; remoteRef?: string; ahead?: number; behind?: number; heldBy?: string } const post = (body: object) => api(`/api/checkout?repo=${encodeURIComponent(repo)}`, jsonInit('POST', body)) onBusy(post({ branch, fromRemote }) .then(r => { + // git refuses a branch checked out in another worktree; offer that tab instead. + // ponytail: native confirm as the Open button, like the diverged prompt below + if (r.heldBy) { + if (confirm(`'${branch}' is open in another worktree:\n${r.heldBy}\n\nOpen its tab?`)) onOpen(r.heldBy) + return + } if (!r.diverged) return // ponytail: native confirm as the popup; custom modal when it grates const ok = confirm( @@ -576,6 +601,9 @@ function GraphView({ repo, commits, status, remotes, stashes, githubUrl, selecti onCheckout={checkout} onChipMenu={(e, chip, hash) => openMenu(e, chipItems(chip, hash))} onRowMenu={(e, hash) => openMenu(e, rowItems(hash))} + held={held} + home={home} + onOpen={onOpen} /> ) diff --git a/src/RepoView.tsx b/src/RepoView.tsx index fa1d6b7..2653da9 100644 --- a/src/RepoView.tsx +++ b/src/RepoView.tsx @@ -9,6 +9,8 @@ import ActionBar from './ActionBar' import ConflictBanner from './ConflictBanner' import SearchBar from './SearchBar' import type { OpKind } from '../server/operation.ts' +import type { Worktree } from '../server/worktrees.ts' +import WorktreeStrip from './WorktreeStrip' import { label, matchLocal, stepMatch } from './search' import { toastErr } from './Toast' import { useSetting } from './settingsStore' @@ -54,7 +56,7 @@ const NO_BRANCH: BranchHeader = { head: null, upstream: null, ahead: 0, behind: type Operation = { kind: OpKind; label: string } -export default function RepoView({ repo, home, onRemove, hasTerminal }: { repo: string; home: string; onRemove: () => void; hasTerminal: boolean }) { +export default function RepoView({ repo, home, linked, onOpen, onRemove, hasTerminal }: { repo: string; home: string; linked: boolean; onOpen: (path: string) => void; onRemove: () => void; hasTerminal: boolean }) { const [commits, setCommits] = useState([]) const [hasMore, setHasMore] = useState(false) const [remotes, setRemotes] = useState([]) @@ -103,13 +105,28 @@ export default function RepoView({ repo, home, onRemove, hasTerminal }: { repo: const page = useRef(pageSize) page.current = pageSize - const fps = useRef({ graph: '', status: '', head: '' }) + const [worktrees, setWorktrees] = useState([]) + const fps = useRef({ graph: '', status: '', head: '', wt: '' }) const loaded = useRef(0) loaded.current = commits.length const gen = useRef(0) const q = `repo=${encodeURIComponent(repo)}` + // own counter, not `gen`: a worktree poll must neither supersede nor be superseded by + // a graph refresh, only by a newer poll. Errors are swallowed — the strip is extra. + const wtGen = useRef(0) + const loadWorktrees = useCallback(() => { + const g = ++wtGen.current + api<{ worktrees: Worktree[] }>(`/api/worktrees?${q}`).then(r => { + if (g !== wtGen.current) return + const fp = JSON.stringify(r.worktrees) + if (fp === fps.current.wt) return + fps.current.wt = fp + setWorktrees(r.worktrees) + }).catch(() => {}) + }, [q]) + // `full` refetches every row currently loaded; a silent refresh instead probes the // first page and only pays for the rest once that page has actually moved. An fs // event fires every 400 ms–2 s, and the full refetch was 277 KB / 209 ms at 1000 @@ -128,9 +145,14 @@ export default function RepoView({ repo, home, onRemove, hasTerminal }: { repo: // remote) is swallowed so the local read still lands. Re-entering rather than // awaiting inline keeps `gen` claimed *after* the fetch, so an SSE refresh firing // during those seconds can't supersede this one and drop its results. - if (!silent && !fetched) return api(`/api/branch?${q}`, jsonInit('POST', { action: 'fetch' })) - .catch(() => {}) - .then(() => run(false, full, true)) + // Manual refreshes also re-poll the worktree strip: with SSE dead, they are the + // only thing that can still move its counts. (First paint has its own poll.) + if (!silent && !fetched) { + loadWorktrees() + return api(`/api/branch?${q}`, jsonInit('POST', { action: 'fetch' })) + .catch(() => {}) + .then(() => run(false, full, true)) + } const g = ++gen.current const probe = !full && loaded.current > page.current const limit = probe ? page.current : Math.max(loaded.current, page.current) @@ -181,7 +203,25 @@ export default function RepoView({ repo, home, onRemove, hasTerminal }: { repo: // background refreshes fail silently — except a gone repo, which must surface if (!silent || e.status === 410) setError({ msg: e.message, gone: e.status === 410 }) }) - }, [q]) + }, [q, loadWorktrees]) + + // cleanup bumps the counter so a poll still in flight at unmount can't setState + useEffect(() => { loadWorktrees(); return () => { wtGen.current++ } }, [loadWorktrees]) + // App's `open` is a fresh closure every render; GraphView is memo'd, so it gets a + // stable wrapper or every App render would re-render the whole graph + const openRef = useRef(onOpen) + openRef.current = onOpen + const openWt = useCallback((path: string) => openRef.current(path), []) + // branch → path for branches checked out elsewhere; GraphView badges those chips. + // Keyed on the pairs, not `worktrees`: a sibling's `changed`/`head` moving must not + // hand the memo'd GraphView a new Map and re-render every row. + const heldKey = worktrees.filter(w => !w.current && w.branch).map(w => `${w.branch}\0${w.path}`).join('\0') + const held = useMemo(() => { + const m = new Map() + const parts = heldKey ? heldKey.split('\0') : [] + for (let i = 0; i < parts.length; i += 2) m.set(parts[i], parts[i + 1]) + return m + }, [heldKey]) // `fetched` on the initial load: App keys RepoView by repo, so every tab switch // remounts and this would otherwise pay a network fetch per switch. Only an explicit @@ -226,10 +266,13 @@ export default function RepoView({ repo, home, onRemove, hasTerminal }: { repo: let firstOpen = true // mount already fetched — don't fetch again if the tab regains focus right after let lastVis = performance.now() + const visible = () => document.visibilityState !== 'hidden' const kick = () => { - if (document.visibilityState !== 'hidden') refresh(true) + if (visible()) { refresh(true); loadWorktrees() } } - es.onmessage = kick + // `worktrees`: a sibling's folder changed — only the strip's counts can have moved + const kickWt = () => { if (visible()) loadWorktrees() } + es.onmessage = e => e.data === 'worktrees' ? kickWt() : kick() es.onopen = () => { // initial open: mount effect already fetched; reconnect: catch up on missed events if (firstOpen) { firstOpen = false; return } @@ -243,11 +286,11 @@ export default function RepoView({ repo, home, onRemove, hasTerminal }: { repo: // ponytail: fixed 10 s window, not a real throttle — enough for hand-speed flipping if (performance.now() - lastVis < VIS_REFRESH_MS) return lastVis = performance.now() - refresh() + refresh() // also re-polls worktrees: `worktrees` events skipped while hidden land here } document.addEventListener('visibilitychange', onVis) return () => { es.close(); document.removeEventListener('visibilitychange', onVis) } - }, [q, refresh]) + }, [q, refresh, loadWorktrees]) // Listed in shortcuts.ts for the Settings dialog — change one, change both. useEffect(() => { @@ -380,7 +423,8 @@ export default function RepoView({ repo, home, onRemove, hasTerminal }: { repo: return (
-
{error.msg}
+
{error.gone && linked ? 'Worktree removed' : error.msg}
+ {error.gone && linked &&
{tilde(repo, home)}
} {error.gone ? : }
@@ -428,9 +472,12 @@ export default function RepoView({ repo, home, onRemove, hasTerminal }: { repo: {operation && ( conflictPost('continue')} /> )} + {/* own row around .panes so the graph's percentage widths stay relative to .panes */} +
+
- + {searchSeq > 0 && ( )}
+
{termOpen && }>}
) diff --git a/src/TabBar.tsx b/src/TabBar.tsx index 940931d..afe1957 100644 --- a/src/TabBar.tsx +++ b/src/TabBar.tsx @@ -1,9 +1,10 @@ import { useState } from 'react' import { base, tilde } from './paths' -export default function TabBar({ repos, home, active, onSelect, onAdd, onClose, onReorder, onReorderEnd, onSettings }: { +export default function TabBar({ repos, home, linked, active, onSelect, onAdd, onClose, onReorder, onReorderEnd, onSettings }: { repos: string[] home: string + linked: string[] active: string | null onSelect: (r: string) => void onAdd: () => void @@ -21,10 +22,12 @@ export default function TabBar({ repos, home, active, onSelect, onAdd, onClose, {import.meta.env.DEV ? '[DEV]' : `v${__VERSION__}`}
- {repos.map((r, i) => ( + {repos.map((r, i) => { + const wt = linked.includes(r) + return (
onSelect(r)} @@ -42,7 +45,7 @@ export default function TabBar({ repos, home, active, onSelect, onAdd, onClose, }} onDragEnd={() => { setDragIdx(null); onReorderEnd() }} > - {base(r)} + {wt ? `⎇ ${base(r)}` : base(r)}
- ))} + ) + })} + ))} + + ) +} diff --git a/src/styles.css b/src/styles.css index 697e1d8..f2fc1df 100644 --- a/src/styles.css +++ b/src/styles.css @@ -87,6 +87,11 @@ button:hover { background: var(--border); } .logo { width: 18px; height: 18px; display: block; pointer-events: none; } .tab { display: flex; align-items: center; gap: 6px; padding: 6px 10px; border-radius: 6px 6px 0 0; background: var(--bg-tab); cursor: pointer; } .tab.active { background: var(--bg-panel); } +.tab.wt { color: #c8a6ff; } +.tab.wt.active { color: #a371f7; } +:root[data-theme="light"] .tab.wt { color: #8250df; } +:root[data-theme="light"] .tab.wt.active { color: #6f42c1; } +.gone-path { color: var(--fg-dim); margin-bottom: 8px; } .tab.dragging { opacity: 0.5; } /* -2px margin lets an 18px hit target sit inside the tab's 6px vertical padding without growing the tab. */ .tab-close { border: none; background: none; padding: 0; margin: -2px -4px -2px 0; width: 18px; height: 18px; flex-shrink: 0; border-radius: 50%; display: flex; align-items: center; justify-content: center; color: var(--fg-dim); } @@ -262,6 +267,17 @@ button:hover { background: var(--border); } .theme-switch input:checked ~ .knob { left: 22px; } .theme-switch:has(input:focus-visible) { outline: 2px solid #5a80b0; outline-offset: 1px; } .panes { flex: 1; display: flex; min-height: 0; } +.panes-row { flex: 1; display: flex; min-height: 0; } +.panes-row > .panes { min-width: 0; } +/* worktree strip: fixed width, no splitter; purple matches the linked-worktree tab */ +.wt-strip { width: 160px; flex-shrink: 0; overflow-y: auto; display: flex; flex-direction: column; gap: 2px; padding: 6px; background: var(--bg-tab); border-right: 1px solid var(--border); } +.wt-row { display: flex; align-items: center; gap: 6px; padding: 4px 6px; border: none; border-radius: 4px; background: none; color: #c8a6ff; text-align: left; font-size: 12px; } +.wt-row:hover:not(:disabled) { background: var(--bg-hover); } +.wt-row.current { background: var(--bg-selected); color: #a371f7; font-weight: 600; cursor: default; } +:root[data-theme="light"] .wt-row { color: #8250df; } +:root[data-theme="light"] .wt-row.current { color: #6f42c1; } +.wt-name { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.wt-count { flex-shrink: 0; padding: 0 5px; border-radius: 8px; background: var(--border); color: var(--fg); font-size: 11px; font-weight: normal; } .graph-pane { position: relative; width: var(--graph-w, 55%); flex-shrink: 0; display: flex; flex-direction: column; min-width: 0; } .graphview { flex: 1; overflow: auto; padding-bottom: 8px; } @@ -335,6 +351,9 @@ button:hover { background: var(--border); } .ref-line.head, .ref-bridge.head { height: 2px; opacity: 1; } .ref-bridge.head { top: calc(50% - 1px); } .ref-icon { flex-shrink: 0; opacity: 0.8; } +.wt-badge { flex-shrink: 0; border: none; background: none; padding: 0 2px; line-height: 1; font-size: 12px; color: #c8a6ff; } +.wt-badge:hover { background: var(--border); } +:root[data-theme="light"] .wt-badge { color: #8250df; } .subject { flex: 1; overflow: hidden; text-overflow: ellipsis; } .date { color: var(--fg-dim); font-size: 12px; } .hash { color: var(--fg-faint); font-family: var(--font-stack); font-size: 12px; } From 6ab4d0a6c4be9c0babe5e0b808a87b6feedff622 Mon Sep 17 00:00:00 2001 From: Vuong Vu Date: Wed, 21 Oct 2026 11:26:09 +0200 Subject: [PATCH 2/6] feat: enhance worktree support with deletion and UI improvements --- README.md | 2 +- docs/architecture.md | 2 +- .../2026-10-19-worktree-support-design.md | 11 +- server/index.ts | 20 +++- src/RepoView.tsx | 2 +- src/WorktreeStrip.tsx | 104 +++++++++++++++--- src/styles.css | 17 ++- 7 files changed, 132 insertions(+), 26 deletions(-) diff --git a/README.md b/README.md index 5d68700..36d46b2 100644 --- a/README.md +++ b/README.md @@ -55,7 +55,7 @@ Stashes appear as their own rows, attached to the commit they were taken from wi ### Worktrees -A repository with linked worktrees gets a strip beside the graph listing each one with its branch and changed-file count. Click a row to open it in its own purple `⎇` tab; counts update live, and a branch checked out elsewhere is marked on its chip and offers to open that tab instead of failing the checkout. +A repository with linked worktrees gets a strip beside the graph listing each one with its branch and changed-file count. Click a row to open it in its own purple `⎇` tab; counts update live, and a branch checked out elsewhere is marked on its chip and offers to open that tab instead of failing the checkout. Drag the strip's edge to resize it, `«` to collapse it, and the trash icon on a row deletes that worktree (its branch stays). ### Diffs diff --git a/docs/architecture.md b/docs/architecture.md index 5f87db2..b0363d3 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -30,7 +30,7 @@ Graph queries use `--date-order`, deliberately not `--topo-order`: topological o **Worktrees extend the watch set, not the protocol.** `worktrees.ts`'s `watchRepo` wraps `subscribe()` and sends two SSE message kinds: `data: changed` (the viewed repo, or — for a linked worktree — the common git dir, since a commit there lands in the common dir rather than in the worktree) and `data: worktrees` (a sibling worktree changed). Siblings are reconciled after each `changed` fire, because `git worktree add/remove` touches the common dir; a worktree nested inside a watched root (`.claude/worktrees/*` inside the repo, or the viewed worktree inside a sibling main checkout) is on that root's ignore list (`setIgnored`, re-applied on every reconcile, for the repo and each sibling alike) and is counted only by its own watcher — so an edit in it fires once, from the watcher that owns it. Filenames are normalised to `/` before the ignore and relevance checks, since Windows reports backslashes. A `worktrees` message refetches only `/api/worktrees`, never `/api/graph`, so editing a file in another worktree costs one `git status` per worktree and no graph re-layout. -**`/api/worktrees` returns `{worktrees}`** — path, branch (or detached), head, `changed` count, `current`. A single-worktree repo costs one `git worktree list` and returns `[]`; the strip only renders when there is more than one. Paths are git's resolved paths, so compare with `current` (and realpath on the server), never against registered strings. `/api/config` also carries `linked`: the registered paths that are linked worktrees, so the tab bar can badge them without a request per tab. Checkout and branch delete consult `heldBy` first and refuse before stashing anything: checkout answers `{heldBy: path}` (the client offers to open that tab), delete answers 409. +**`/api/worktrees` returns `{worktrees}`** — path, branch (or detached), head, `changed` count, `current`. A single-worktree repo costs one `git worktree list` and returns `[]`; the strip only renders when there is more than one. Paths are git's resolved paths, so compare with `current` (and realpath on the server), never against registered strings. `/api/config` also carries `linked`: the registered paths that are linked worktrees, so the tab bar can badge them without a request per tab. Checkout and branch delete consult `heldBy` first and refuse before stashing anything: checkout answers `{heldBy: path}` (the client offers to open that tab), delete answers 409. `POST /api/worktrees {path, force}` runs `git worktree remove`, with `path` allow-listed against `git worktree list` minus the main worktree. **Only a manual refresh touches the network.** `/api/graph` and `/api/status` read local git, which cannot see upstream commits until something fetches — so Pull was once the only button that surfaced them. The ⟳ button and r now POST `{action:'fetch'}` to `/api/branch` and re-enter `refresh` for the local read; a failed fetch is swallowed so the read still lands. Everything else stays local-only on purpose: SSE refetches fire every 400 ms–2 s, and RepoView remounts per tab switch, so neither may cost a round-trip. diff --git a/docs/superpowers/specs/2026-10-19-worktree-support-design.md b/docs/superpowers/specs/2026-10-19-worktree-support-design.md index b444864..f498346 100644 --- a/docs/superpowers/specs/2026-10-19-worktree-support-design.md +++ b/docs/superpowers/specs/2026-10-19-worktree-support-design.md @@ -8,7 +8,8 @@ The user runs coding agents (T3 Code, Claude Code, plain terminal) that each wor `git worktree`. megit should let them **watch that work**: which worktrees exist, which ones have uncommitted changes right now, and what those changes are. Today megit has no idea worktrees exist. -megit is a viewer here. Worktrees are created and deleted by other tools; megit never does either. +megit is mostly a viewer here. Worktrees are created by other tools; megit can delete one from the strip +(added 2026-10-21 at the user's request — see Decided). ## What exists today @@ -46,7 +47,7 @@ megit is a viewer here. Worktrees are created and deleted by other tools; megit ## Non-goals -- Creating, removing, pruning, locking or moving worktrees. +- Creating, pruning, locking or moving worktrees. - Showing other worktrees' WIP inside one graph (mockup option "B"). Rejected for cost and clutter; the strip + tabs cover it. - Live counts for repos in background tabs. Only the active tab is mounted, and that stays true. @@ -81,7 +82,11 @@ re-render. - Live counts, with the cost above. - Worktree tabs are ordinary registered repos (same config list, same `repoGuard`), so every existing feature works in them for free. -- View-only: no worktree mutations. +- Delete from the strip (user's call, 2026-10-21): a trash icon on hover of each linked, non-current row, + behind a `confirm`. It names the branch that stays and the uncommitted file count that would be lost; + `--force` is sent only when that count was non-zero, so a stale zero count lets git refuse instead of + silently discarding work. The main worktree has no trash icon and the server allow-lists the path. +- Strip is resizable (splitter, 100–480 px) and collapsible to a 24 px rail; both persist globally. - Removed worktree → its tab stays, showing "worktree removed", until the user closes it (user's call, 2026-10-19). Worktree tabs persist across restarts like any other tab. diff --git a/server/index.ts b/server/index.ts index 94a29cd..8c8b461 100644 --- a/server/index.ts +++ b/server/index.ts @@ -9,7 +9,7 @@ import { resolveAvatar, parseGithubRemote } from './avatars.ts' import { mergeMatches, parseBranchHeader, parseLog, parseMatches, parseMeta, parseNameStatus, parseStatus, stashIndex, LOG_FORMAT, META_FORMAT } from './parse.ts' import { pickOperation, STATE_FILES, type OpKind } from './operation.ts' import { checkoutPlan } from './checkout.ts' -import { heldBy, isLinkedWorktree, watchRepo, worktreesWithCounts } from './worktrees.ts' +import { heldBy, isLinkedWorktree, listWorktrees, watchRepo, worktreesWithCounts } from './worktrees.ts' import { wireTerminal, hasPty } from './term.ts' // JSON bodies are capped at 10mb by createApp — a resolved conflicted file goes @@ -297,6 +297,24 @@ app.get('/api/worktrees', repoGuard, async (req, res) => { } }) +// Removes a linked worktree. The path is allow-listed against git's own list, minus +// [0] (the main worktree, which git can't remove). Without force, git refuses a +// worktree with uncommitted or untracked files — the client only sends force after +// the user confirmed losing them. Locked worktrees stay git's error. The branch stays. +app.post('/api/worktrees', repoGuard, async (req, res) => { + const repo = String(req.query.repo) + try { + const [, ...linked] = await listWorktrees(repo, git) + const target = linked.find(w => w.path === req.body.path) + if (!target) throw httpError(400, 'not a linked worktree of this repo') + await git(repo, ['worktree', 'remove', ...(req.body.force === true ? ['--force'] : []), target.path]) + res.json({ ok: true }) + } catch (e) { + const err = e as Error + res.status((err as { status?: number }).status ?? 409).json({ error: err.message }) + } +}) + // resolves to a sha, or null when the ref doesn't exist (--quiet: exit 1, empty output) async function revParse(repo: string, ref: string): Promise { const out = await git(repo, ['rev-parse', '--verify', '--quiet', ref], [0, 1]) diff --git a/src/RepoView.tsx b/src/RepoView.tsx index 2653da9..3986a7d 100644 --- a/src/RepoView.tsx +++ b/src/RepoView.tsx @@ -474,7 +474,7 @@ export default function RepoView({ repo, home, linked, onOpen, onRemove, hasTerm )} {/* own row around .panes so the graph's percentage widths stay relative to .panes */}
- +
diff --git a/src/WorktreeStrip.tsx b/src/WorktreeStrip.tsx index fe5d47e..307c797 100644 --- a/src/WorktreeStrip.tsx +++ b/src/WorktreeStrip.tsx @@ -1,26 +1,98 @@ +import { useRef, useState, type PointerEvent as ReactPointerEvent } from 'react' // type-only: server/worktrees.ts imports node:fs, which must not reach the bundle import type { Worktree } from '../server/worktrees.ts' +import { api, jsonInit } from './api' import { tilde } from './paths' +import { toastErr } from './Toast' + +const W_KEY = 'megit-wt-w' +const OPEN_KEY = 'megit-wt-open' + +type Props = { + repo: string + worktrees: Worktree[] + home: string + onOpen: (path: string) => void + onBusy: (p: Promise) => void + onRemoved: () => void +} // One row per worktree of this repo; the current one is highlighted and inert. // Empty list (a repo with a single worktree) → nothing rendered, no column taken. -export default function WorktreeStrip({ worktrees, home, onOpen }: { worktrees: Worktree[]; home: string; onOpen: (path: string) => void }) { +// Width and collapsed state are global (localStorage), like the other splitters. +export default function WorktreeStrip({ repo, worktrees, home, onOpen, onBusy, onRemoved }: Props) { + const [width, setWidth] = useState(() => Number(localStorage.getItem(W_KEY)) || 160) + const [open, setOpen] = useState(() => localStorage.getItem(OPEN_KEY) !== '0') + const strip = useRef(null) if (worktrees.length === 0) return null + + const toggle = () => { + localStorage.setItem(OPEN_KEY, open ? '0' : '1') + setOpen(!open) + } + // pointer capture keeps the drag on the splitter, same as RepoView's splitters + const onDown = (e: ReactPointerEvent) => { + e.preventDefault() + e.currentTarget.setPointerCapture(e.pointerId) + } + const onMove = (e: ReactPointerEvent) => { + if (!e.currentTarget.hasPointerCapture(e.pointerId)) return + const w = Math.round(Math.min(480, Math.max(100, e.clientX - strip.current!.getBoundingClientRect().left))) + setWidth(w) + localStorage.setItem(W_KEY, String(w)) + } + + // force only when the strip already counted changes and the user accepted losing + // them; a count that is stale-zero sends no force, and git refuses instead + const remove = (w: Worktree) => { + const lines = [`Delete worktree ${tilde(w.path, home)}?`] + lines.push(w.branch ? `Branch ${w.branch} stays.` : 'Detached HEAD — commits on no branch remain only in the reflog.') + if (w.changed > 0) lines.push(`${w.changed} uncommitted file${w.changed === 1 ? '' : 's'} will be lost.`) + if (!confirm(lines.join('\n\n'))) return + onBusy(api(`/api/worktrees?repo=${encodeURIComponent(repo)}`, jsonInit('POST', { path: w.path, force: w.changed > 0 })) + .then(onRemoved, (err: Error) => toastErr(`Delete worktree failed:\n${err.message}`))) + } + + if (!open) { + return ( +
+ +
+ ) + } return ( -
- {worktrees.map(w => ( - - ))} -
+ <> +
+
+ Worktrees + +
+ {worktrees.map((w, i) => ( +
+ + {/* [0] is the main worktree, which git can't remove; the current one is the tab you're in */} + {i > 0 && !w.current && ( + + )} +
+ ))} +
+
+ ) } diff --git a/src/styles.css b/src/styles.css index f2fc1df..929d88c 100644 --- a/src/styles.css +++ b/src/styles.css @@ -269,10 +269,21 @@ button:hover { background: var(--border); } .panes { flex: 1; display: flex; min-height: 0; } .panes-row { flex: 1; display: flex; min-height: 0; } .panes-row > .panes { min-width: 0; } -/* worktree strip: fixed width, no splitter; purple matches the linked-worktree tab */ -.wt-strip { width: 160px; flex-shrink: 0; overflow-y: auto; display: flex; flex-direction: column; gap: 2px; padding: 6px; background: var(--bg-tab); border-right: 1px solid var(--border); } +/* worktree strip: resizable via the .splitter after it, collapsible to a 24px rail; + purple matches the linked-worktree tab */ +.wt-strip { flex-shrink: 0; overflow-y: auto; display: flex; flex-direction: column; gap: 2px; padding: 6px; background: var(--bg-tab); } +.wt-strip.collapsed { width: 24px; padding: 6px 0; align-items: center; border-right: 1px solid var(--border); } +.wt-head { display: flex; align-items: center; justify-content: space-between; padding: 0 2px 4px 6px; font-size: 11px; color: var(--fg-dim); text-transform: uppercase; letter-spacing: .04em; } +.wt-toggle { border: none; background: none; padding: 0 4px; line-height: 1.4; font-size: 12px; color: #c8a6ff; border-radius: 3px; } +.wt-toggle:hover { background: var(--bg-hover); } +:root[data-theme="light"] .wt-toggle { color: #8250df; } +.wt-item { display: flex; align-items: center; border-radius: 4px; } +.wt-item:hover { background: var(--bg-hover); } +.wt-item > .wt-row { flex: 1; min-width: 0; } +.wt-del { opacity: 0; flex-shrink: 0; border: none; background: none; padding: 2px 4px; margin-right: 2px; color: var(--fg-dim); border-radius: 3px; } +.wt-item:hover .wt-del, .wt-del:focus-visible { opacity: 1; } +.wt-del:hover { color: #f85149; background: var(--border); } .wt-row { display: flex; align-items: center; gap: 6px; padding: 4px 6px; border: none; border-radius: 4px; background: none; color: #c8a6ff; text-align: left; font-size: 12px; } -.wt-row:hover:not(:disabled) { background: var(--bg-hover); } .wt-row.current { background: var(--bg-selected); color: #a371f7; font-weight: 600; cursor: default; } :root[data-theme="light"] .wt-row { color: #8250df; } :root[data-theme="light"] .wt-row.current { color: #6f42c1; } From 34604211026532cbb568ab9781a4368efdaa7c97 Mon Sep 17 00:00:00 2001 From: Vuong Vu Date: Wed, 21 Oct 2026 12:15:44 +0200 Subject: [PATCH 3/6] feat: improve worktree strip styling and button functionality --- src/WorktreeStrip.tsx | 11 +++++------ src/styles.css | 33 +++++++++++++++------------------ 2 files changed, 20 insertions(+), 24 deletions(-) diff --git a/src/WorktreeStrip.tsx b/src/WorktreeStrip.tsx index 307c797..23c8d20 100644 --- a/src/WorktreeStrip.tsx +++ b/src/WorktreeStrip.tsx @@ -21,7 +21,7 @@ type Props = { // Empty list (a repo with a single worktree) → nothing rendered, no column taken. // Width and collapsed state are global (localStorage), like the other splitters. export default function WorktreeStrip({ repo, worktrees, home, onOpen, onBusy, onRemoved }: Props) { - const [width, setWidth] = useState(() => Number(localStorage.getItem(W_KEY)) || 160) + const [width, setWidth] = useState(() => Number(localStorage.getItem(W_KEY)) || 200) const [open, setOpen] = useState(() => localStorage.getItem(OPEN_KEY) !== '0') const strip = useRef(null) if (worktrees.length === 0) return null @@ -81,11 +81,10 @@ export default function WorktreeStrip({ repo, worktrees, home, onOpen, onBusy, o {/* [0] is the main worktree, which git can't remove; the current one is the tab you're in */} {i > 0 && !w.current && ( - +
) } @@ -65,7 +67,12 @@ export default function WorktreeStrip({ repo, worktrees, home, onOpen, onBusy, o
Worktrees - +
{worktrees.map((w, i) => (
diff --git a/src/styles.css b/src/styles.css index db4f142..eb0313c 100644 --- a/src/styles.css +++ b/src/styles.css @@ -272,10 +272,12 @@ button:hover { background: var(--border); } /* worktree strip: resizable via the .splitter after it, collapsible to a 24px rail. Rows mirror the commit panel's .file-row: same font, hover, selected, trash button */ .wt-strip { flex-shrink: 0; overflow-y: auto; display: flex; flex-direction: column; gap: 1px; padding: 4px; background: var(--bg-tab); } -.wt-strip.collapsed { width: 28px; padding: 6px 0; align-items: center; border-right: 1px solid var(--border); } +.wt-strip.collapsed { width: 32px; padding: 6px 0; align-items: center; border-right: 1px solid var(--border); } .wt-head { display: flex; align-items: center; justify-content: space-between; padding: 2px 2px 6px 8px; font-size: var(--t1); color: var(--fg-dim); text-transform: uppercase; letter-spacing: .04em; } -.wt-toggle { border: none; background: none; padding: 0 5px; font: inherit; font-size: var(--t2); line-height: 1.4; color: var(--fg-dim); } +.wt-toggle { display: flex; align-items: center; justify-content: center; min-width: 24px; min-height: 24px; border: none; background: none; padding: 0; font: inherit; font-size: 18px; line-height: 1; color: var(--fg-dim); } .wt-toggle:hover { background: var(--bg-hover); color: var(--fg); } +.wt-strip.collapsed .wt-toggle { flex-direction: column; gap: 4px; padding: 4px 2px; } +.wt-total { padding: 0 5px; border-radius: 8px; background: var(--border); font-size: var(--t1); color: var(--fg); } .wt-item { display: flex; align-items: center; gap: 4px; padding-right: 4px; border-radius: 4px; } .wt-item:hover { background: var(--bg-hover); } .wt-item:has(.current) { background: var(--bg-selected); } From ff9a0f9c6880da93410921f4369ef63e73d9f75b Mon Sep 17 00:00:00 2001 From: Vuong Vu Date: Wed, 21 Oct 2026 12:33:08 +0200 Subject: [PATCH 5/6] feat: update changelog and README for worktree enhancements; bump version to 0.14.0 --- CHANGELOG.md | 18 ++++++++++++++++++ README.md | 2 +- package.json | 2 +- 3 files changed, 20 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e93372b..3725e0d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,24 @@ surface, and the HTTP API may change in any minor release. ## [Unreleased] +## [0.14.0] - 2026-10-21 + +### Added + +- **Worktrees.** A repo with linked worktrees gets a panel beside the graph listing each + one with its branch and a live count of changed files. Click a row to open it as its own + `⎇` tab. The panel resizes, collapses to a rail showing the count, and deletes a worktree + from the trash icon on hover, after confirming (its branch stays). +- A branch checked out in another worktree carries a `⎇` marker on its chip. Checking it + out offers to open that worktree's tab instead, before anything is stashed. + +### Fixed + +- Tabs for linked worktrees refresh on their own after commits, checkouts and stashes made + outside megit. Only file edits used to show up. +- A worktree tab whose folder was deleted shows "Worktree removed" and stays open until + you close it. + ## [0.13.0] - 2026-10-09 ### Added diff --git a/README.md b/README.md index 36d46b2..745dd9f 100644 --- a/README.md +++ b/README.md @@ -55,7 +55,7 @@ Stashes appear as their own rows, attached to the commit they were taken from wi ### Worktrees -A repository with linked worktrees gets a strip beside the graph listing each one with its branch and changed-file count. Click a row to open it in its own purple `⎇` tab; counts update live, and a branch checked out elsewhere is marked on its chip and offers to open that tab instead of failing the checkout. Drag the strip's edge to resize it, `«` to collapse it, and the trash icon on a row deletes that worktree (its branch stays). +A repository with linked worktrees gets a panel beside the graph listing each one with its branch and changed-file count. Click a row to open it in its own purple `⎇` tab; counts update live, and a branch checked out elsewhere is marked on its chip and offers to open that tab instead of failing the checkout. Drag the panel's edge to resize it, collapse it to a rail that keeps the worktree count, and the trash icon on a row deletes that worktree (its branch stays). ### Diffs diff --git a/package.json b/package.json index dbac604..2cbac3f 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "megit-app", - "version": "0.13.0", + "version": "0.14.0", "description": "Git repository viewer in the browser: commit graph with branch lanes, diffs, stashes and WIP", "license": "MIT", "author": "Hoang Vuong Vu", From 259d0f5752f22eb2e00b283c2a3ca689115148b0 Mon Sep 17 00:00:00 2001 From: Vuong Vu Date: Wed, 21 Oct 2026 12:40:58 +0200 Subject: [PATCH 6/6] feat: enhance integration test for subscribe function with improved event handling and cleanup --- server/watch.test.ts | 22 ++++++++++++++-------- 1 file changed, 14 insertions(+), 8 deletions(-) diff --git a/server/watch.test.ts b/server/watch.test.ts index 4bab1bf..d581448 100644 --- a/server/watch.test.ts +++ b/server/watch.test.ts @@ -229,14 +229,20 @@ integration('subscribe (integration, real fs + timers)', () => { mkdirSync(join(dir, 'nested')) let events = 0 const unsub = subscribe(dir, () => { events++ }, () => {}) - setIgnored(dir, ['nested']) - await sleep(300) // FSEvents warm-up - writeFileSync(join(dir, 'nested', 'x.txt'), 'x') - await sleep(2500) // past the debouncer's max-wait - expect(events).toBe(0) - writeFileSync(join(dir, 'top.txt'), 'x') - await waitFor(() => events >= 1, 5000) - unsub() + try { + setIgnored(dir, ['nested']) + // FSEvents can deliver `git init`'s own .git/HEAD writes after subscribe — + // a real, relevant event. Let it flush past the 400 ms trailing debounce, then count. + await sleep(1000) + events = 0 + writeFileSync(join(dir, 'nested', 'x.txt'), 'x') + await sleep(2500) // past the debouncer's max-wait + expect(events).toBe(0) + writeFileSync(join(dir, 'top.txt'), 'x') + await waitFor(() => events >= 1, 5000) + } finally { + unsub() // even on failure, so afterEach's leak check reports this test only once + } } finally { rmSync(dir, { recursive: true, force: true }) }