Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 10 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ the arrows keep working inside `claude`.
| `n` | new session |
| `a` | add project |
| `e` | rename the focused project or session |
| `x` | end session — close and keep the worktree, or delete both |
| `x` | end session — close and keep the worktree, or delete both. In the session view, `x` on a running agent only stops it, and a second `x` ends the session |
| `c` | connect this session to one on another project |
| `t` | theme picker |
| `?` | help |
Expand Down Expand Up @@ -155,7 +155,7 @@ event. Any other agent gets `↑` and `↓`.
| `^g` and a number | jump straight to that session |
| `^g n` | new session |
| `^g e` | rename this session |
| `^g x` | stop the agent |
| `^g x` | stop the agent, or end a stopped session as `x` does |
| `^g esc` | detach from the pane |
| `^g ↵` | attach to the pane |
| `^g q` | quit |
Expand Down Expand Up @@ -224,6 +224,14 @@ the session stays, so you can open it again, commit, and delete it after. If the
tree is clean but its branch holds unmerged commits, the worktree goes and the
branch is kept — the notice names it.

A worktree deleted by hand leaves the session unable to start. While its branch
still exists, `x` on it offers a third row, **Recreate**, which checks the
branch out again at the same path so you continue from its last commit, and
links the project's ignored instruction files back in. Close and Delete still
work. Delete drops git's record of the missing tree, and the branch on the terms
above. It refuses when that record is the only reference to a commit, which
happens when the tree was on a detached HEAD.

A session that ran in the project directory has no worktree of its own, so it
skips the question and closes.

Expand Down
28 changes: 28 additions & 0 deletions docs/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -866,6 +866,34 @@ is the project's own checkout, so it skips the modal and closes outright.
`deleteSession` guards that itself rather than trusting its caller, because the
cost of reaching it with one is git aimed at the user's own tree.

**In the session view, `x` stops before it ends.** A live agent is stopped, and
`x` on a session with nothing running ends it as the dashboard's `x` does.
Stopping was once all it did, which left the sidebar no way to remove a row. A
session whose worktree was deleted by hand can never start, so it was stuck
there.

**A worktree deleted by hand gets a third row, Recreate** (`ui/missingdir.go`).
The branch still holds every commit, so checking it out again at the same path
continues the session, and the cursor starts there because it loses nothing.
The row needs the local branch to exist. Given a name with no branch, `worktree
add` falls back to a remote branch or a tag of that name and succeeds at
something that is not the session's work. The project's ignored instruction
files are linked back in, for the reason newSession links them.

git keeps a record of the missing tree and refuses to add over it, so
`gitx.RestoreWorktree` clears that record with `worktree remove`, which touches
the one path. It does not use `worktree prune`, which clears every missing tree
in the repository, or `add --force`, which would also check out a branch that
another tree already has. It retries only while the path is still empty,
because anything at that path now belongs to someone.

`worktree remove` on a missing tree drops the record and exits 0, and the
record's HEAD goes with it. That is harmless on a branch. On a detached HEAD
the record can be the only reference to a commit, so `gitx.RemoveWorktree`
refuses when no ref contains it. Delete goes through the same check. A missing
tree with no record at all — `git worktree prune` already ran — has nothing to
remove, so it succeeds rather than stranding the session.

The disk work comes first and `forget` comes last, so a worktree that refused to
go still has a row naming it. `forget` is not itself atomic: `RemoveSession`
runs before `Save`, so a failed save leaves the session gone from memory and
Expand Down
18 changes: 17 additions & 1 deletion internal/gitx/gitx.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@ package gitx

// Running git at all, and the questions asked of a repository before Deck
// commits to anything: where its root is, what it has checked out, whether it
// has a commit yet, and whether a directory is a project or a shelf of them.
// has a commit yet or a given branch, and whether a directory is a project or
// a shelf of them.
// The worktree a session gets is worktree.go.

import (
Expand All @@ -16,6 +17,7 @@ import (
"os"
"os/exec"
"path/filepath"
"slices"
"strings"
)

Expand Down Expand Up @@ -118,6 +120,20 @@ func HoldsRepos(dir string) bool {
return false
}

// HasBranch reports whether repo has a local branch of that name. Only
// refs/heads counts: a tag or a remote branch of the same name is what
// `worktree add` would otherwise guess at, and neither is the session's work.
func HasBranch(repo, branch string) (bool, error) {
// The pattern also matches refs below it ("a" matches "a/b"), so the output
// is compared whole rather than tested for being non-empty.
ref := "refs/heads/" + branch
out, err := run(repo, "for-each-ref", "--format=%(refname)", ref)
if err != nil {
return false, err
}
return slices.Contains(strings.Split(out, "\n"), ref), nil
}

// HeadCommit returns the commit dir's HEAD points at.
func HeadCommit(dir string) (string, error) {
return run(dir, "rev-parse", "HEAD")
Expand Down
17 changes: 17 additions & 0 deletions internal/gitx/gitx_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -217,3 +217,20 @@ func TestIgnores(t *testing.T) {
t.Error("a non-repository answered yes")
}
}

// TestHasBranchMatchesTheWholeName guards the for-each-ref pattern, which also
// matches the refs below it: "session" would match "session/x".
func TestHasBranchMatchesTheWholeName(t *testing.T) {
repo, _ := gittest.RepoWith(t, "a.txt", "one\n")
gittest.Run(t, repo, "branch", "session/x")

for branch, want := range map[string]bool{"session/x": true, "session": false, "nope": false} {
got, err := HasBranch(repo, branch)
if err != nil {
t.Fatalf("HasBranch(%q): %v", branch, err)
}
if got != want {
t.Errorf("HasBranch(%q) = %v, want %v", branch, got, want)
}
}
}
68 changes: 68 additions & 0 deletions internal/gitx/records.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
package gitx

// What git records about linked worktrees, read from `git worktree list
// --porcelain`, for the cases where the tree itself is no longer there to ask.

import (
"path/filepath"
"strings"
)

// worktreeRecord is git's record of one linked worktree.
type worktreeRecord struct {
head string
detached bool
}

// missingRecord returns git's record of the worktree at dest, or nil when git
// has none.
//
// git prints each path resolved through symlinks, so dest is resolved the same
// way before comparing. It cannot be resolved directly when it is gone, so the
// deepest ancestor that still exists is resolved and the rest rejoined.
func missingRecord(repo, dest string) (*worktreeRecord, error) {
out, err := run(repo, "worktree", "list", "--porcelain")
if err != nil {
return nil, err
}
want := resolveExisting(dest)
for block := range strings.SplitSeq(out, "\n\n") {
var rec worktreeRecord
path := ""
for line := range strings.SplitSeq(block, "\n") {
key, val, _ := strings.Cut(line, " ")
switch key {
case "worktree":
path = val
case "HEAD":
rec.head = val
case "detached":
rec.detached = true
}
}
if path == want {
return &rec, nil
}
}
return nil, nil
}

// resolveExisting resolves symlinks in the part of path that exists.
func resolveExisting(path string) string {
abs, err := filepath.Abs(path)
if err != nil {
return path
}
dir, rest := abs, ""
for {
if real, err := filepath.EvalSymlinks(dir); err == nil {
return filepath.Join(real, rest)
}
parent := filepath.Dir(dir)
if parent == dir {
return abs
}
rest = filepath.Join(filepath.Base(dir), rest)
dir = parent
}
}
79 changes: 74 additions & 5 deletions internal/gitx/worktree.go
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
package gitx

// The worktree an isolated session works in: creating one on a branch of its
// own, removing both when the session is deleted, and the refusals on either
// side that Deck reports rather than forces.
// own, restoring it when deleted by hand, removing both when the session is
// deleted, and the refusals on either side that Deck reports rather than forces.

import (
"errors"
"fmt"
"io/fs"
"os"
"path/filepath"
)
Expand Down Expand Up @@ -60,13 +61,74 @@ func AddWorktree(repo, dest, branch string) error {
// test. git's message names the path and says --force exists, so the user has
// the way out without Deck offering it as a button.
//
// A dest the user already deleted by hand is not an error. git drops the
// administrative entry and reports success.
// A dest the user already deleted by hand is not an error, with one exception.
// git would drop its record and report success, and the record's HEAD is then
// gone with it. On a branch that loses nothing, because the branch holds the
// commits. On a detached HEAD the record may be the only reference to them, so
// a commit no ref contains is refused rather than left for gc. With no record
// at all — the user also ran `git worktree prune` — there is nothing to remove.
func RemoveWorktree(repo, dest string) error {
if _, err := os.Lstat(dest); errors.Is(err, fs.ErrNotExist) {
rec, err := missingRecord(repo, dest)
if err != nil || rec == nil {
return err
}
if rec.detached {
held, err := run(repo, "for-each-ref", "--count=1", "--contains", rec.head, "refs/")
if err != nil {
return err
}
if held == "" {
return fmt.Errorf("%s is gone, and git's record of it is the only reference to commit %s — keep it with `git branch <name> %s` in %s first",
dest, rec.head, rec.head, repo)
}
}
}
_, err := run(repo, "worktree", "remove", dest)
return err
}

// RestoreWorktree checks an existing branch out again at dest, for a session
// whose tree was deleted by hand. The branch keeps every commit the tree had.
//
// The branch has to exist locally. Given a name it has no branch for, `worktree
// add` guesses: a remote branch of that name becomes a new local one tracking
// it, and a tag checks out detached. Either succeeds at something that is not
// the session's work.
//
// git usually still holds a record of the deleted tree and refuses to add over
// it ("missing but already registered"). The record goes through
// RemoveWorktree, which touches dest alone and keeps a detached HEAD's commits,
// rather than `worktree prune`, which clears every missing tree in the
// repository. It is not forced: --force would also check out a branch that
// another tree already has. Only a dest that is still missing is retried —
// anything that appeared there since belongs to someone, and removing it would
// take it.
func RestoreWorktree(repo, dest, branch string) error {
ok, err := HasBranch(repo, branch)
if err != nil {
return err
}
if !ok {
return fmt.Errorf("branch %s no longer exists, so there is nothing to check out again", branch)
}
if err := os.MkdirAll(filepath.Dir(dest), 0o755); err != nil {
return fmt.Errorf("create worktree parent: %w", err)
}
_, err = run(repo, "worktree", "add", dest, branch)
if err == nil {
return nil
}
if _, statErr := os.Lstat(dest); !errors.Is(statErr, fs.ErrNotExist) {
return err
}
if rmErr := RemoveWorktree(repo, dest); rmErr != nil {
return errors.Join(err, rmErr)
}
_, err = run(repo, "worktree", "add", dest, branch)
return err
}

// DeleteBranch deletes branch from repo. It never forces.
//
// Call it after RemoveWorktree, never before: git refuses to delete a branch
Expand All @@ -81,7 +143,14 @@ func RemoveWorktree(repo, dest string) error {
// That refusal is the case where the session goes and its work stays, so the
// caller keeps the branch and says so. A session that committed nothing sits on
// an ancestor of HEAD and deletes without complaint.
//
// A branch that is already gone is not an error: the outcome the caller asked
// for holds, and reporting it as a refusal would say the work was kept.
func DeleteBranch(repo, branch string) error {
_, err := run(repo, "branch", "-d", branch)
ok, err := HasBranch(repo, branch)
if err != nil || !ok {
return err
}
_, err = run(repo, "branch", "-d", branch)
return err
}
Loading
Loading