From 1cf726efe940d6eaf0385069d36eabde5d1f02b7 Mon Sep 17 00:00:00 2001 From: tdwd <111124579+tdwd@users.noreply.github.com> Date: Mon, 26 Oct 2026 13:17:10 +0100 Subject: [PATCH 1/3] Keep a detached commit when removing a missing worktree `git worktree remove` on a tree deleted by hand drops git's record of it and exits 0. On a detached HEAD that record can be the only reference to a commit, which gc then collects. RemoveWorktree now reads the record first and refuses when no ref contains its HEAD, naming the commit and the `git branch` command that keeps it. Two dead ends go with it. A missing tree whose record was already pruned made Delete fail with "is not a working tree"; there is nothing to remove, so it now succeeds. A branch already gone made DeleteBranch fail, and the UI reported that as an unmerged branch kept; it now succeeds, checked with the new HasBranch. --- docs/architecture.md | 7 ++++ internal/gitx/gitx.go | 18 ++++++++- internal/gitx/gitx_test.go | 17 +++++++++ internal/gitx/records.go | 68 ++++++++++++++++++++++++++++++++++ internal/gitx/worktree.go | 34 +++++++++++++++-- internal/gitx/worktree_test.go | 67 +++++++++++++++++++++++++++++++++ 6 files changed, 207 insertions(+), 4 deletions(-) create mode 100644 internal/gitx/records.go diff --git a/docs/architecture.md b/docs/architecture.md index e19da7d..b129b01 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -866,6 +866,13 @@ 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. +`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. A missing tree with no record at all — `git +worktree prune` already ran — has nothing to remove, so Delete 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 diff --git a/internal/gitx/gitx.go b/internal/gitx/gitx.go index 3433acb..4f6e5e3 100644 --- a/internal/gitx/gitx.go +++ b/internal/gitx/gitx.go @@ -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 ( @@ -16,6 +17,7 @@ import ( "os" "os/exec" "path/filepath" + "slices" "strings" ) @@ -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") diff --git a/internal/gitx/gitx_test.go b/internal/gitx/gitx_test.go index f171902..a651d3c 100644 --- a/internal/gitx/gitx_test.go +++ b/internal/gitx/gitx_test.go @@ -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) + } + } +} diff --git a/internal/gitx/records.go b/internal/gitx/records.go new file mode 100644 index 0000000..0399c8f --- /dev/null +++ b/internal/gitx/records.go @@ -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 + } +} diff --git a/internal/gitx/worktree.go b/internal/gitx/worktree.go index c246f8b..29302af 100644 --- a/internal/gitx/worktree.go +++ b/internal/gitx/worktree.go @@ -7,6 +7,7 @@ package gitx import ( "errors" "fmt" + "io/fs" "os" "path/filepath" ) @@ -60,9 +61,29 @@ 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 %s` in %s first", + dest, rec.head, rec.head, repo) + } + } + } _, err := run(repo, "worktree", "remove", dest) return err } @@ -81,7 +102,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 } diff --git a/internal/gitx/worktree_test.go b/internal/gitx/worktree_test.go index ad50c4d..2fb7e0f 100644 --- a/internal/gitx/worktree_test.go +++ b/internal/gitx/worktree_test.go @@ -223,3 +223,70 @@ func TestRemoveWorktreeAfterTheDirectoryIsGone(t *testing.T) { t.Errorf("git still lists the removed worktree:\n%s", list) } } + +// TestRemoveWorktreeKeepsADetachedCommit is the case where git's record is +// the only reference to the work. `worktree remove` would drop it and exit 0, +// leaving the commit for gc. +func TestRemoveWorktreeKeepsADetachedCommit(t *testing.T) { + repo, dest, _ := session(t) + gittest.Run(t, dest, "checkout", "-q", "--detach") + gittest.Run(t, dest, "commit", "-q", "--allow-empty", "-m", "detached work") + commit := gittest.Run(t, dest, "rev-parse", "HEAD") + if err := os.RemoveAll(dest); err != nil { + t.Fatal(err) + } + + err := RemoveWorktree(repo, dest) + if err == nil { + t.Fatal("RemoveWorktree dropped the only reference to a commit") + } + if !strings.Contains(err.Error(), commit) { + t.Errorf("err = %v, want it to name the commit to keep", err) + } + if rec, _ := missingRecord(repo, dest); rec == nil { + t.Error("the record holding the commit is gone") + } +} + +// TestRemoveWorktreeDropsADetachedHeadABranchHolds keeps the refusal narrow. +// A detached HEAD on a commit some branch contains loses nothing. +func TestRemoveWorktreeDropsADetachedHeadABranchHolds(t *testing.T) { + repo, dest, _ := session(t) + gittest.Run(t, dest, "checkout", "-q", "--detach") + if err := os.RemoveAll(dest); err != nil { + t.Fatal(err) + } + + if err := RemoveWorktree(repo, dest); err != nil { + t.Fatalf("RemoveWorktree refused a commit a branch holds: %v", err) + } +} + +// TestRemoveWorktreeAfterTheRecordIsPruned is a delete that would otherwise +// strand the session: no tree and no record, so git says "not a working tree" +// about the very thing the user wants gone. +func TestRemoveWorktreeAfterTheRecordIsPruned(t *testing.T) { + repo, dest, _ := session(t) + if err := os.RemoveAll(dest); err != nil { + t.Fatal(err) + } + gittest.Run(t, repo, "worktree", "prune") + + if err := RemoveWorktree(repo, dest); err != nil { + t.Fatalf("RemoveWorktree with nothing left to remove: %v", err) + } +} + +// TestDeleteBranchThatIsAlreadyGone is not a refusal. Reporting it as one +// would tell the user an unmerged branch was kept when there is no branch. +func TestDeleteBranchThatIsAlreadyGone(t *testing.T) { + repo, dest, branch := session(t) + if err := RemoveWorktree(repo, dest); err != nil { + t.Fatal(err) + } + gittest.Run(t, repo, "branch", "-D", branch) + + if err := DeleteBranch(repo, branch); err != nil { + t.Errorf("DeleteBranch on a branch already gone: %v", err) + } +} From 8fcdd4c953bc1936fb46fff12dcc2b8b34d4d566 Mon Sep 17 00:00:00 2001 From: tdwd <111124579+tdwd@users.noreply.github.com> Date: Mon, 26 Oct 2026 13:17:26 +0100 Subject: [PATCH 2/3] Take endSession out of endSelectedFromDashboard The choice between closing outright and asking moves into endSession, which takes the session rather than reading the dashboard's cursor, so a second caller can end a session it found another way. No behaviour changes. --- internal/ui/closing.go | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/internal/ui/closing.go b/internal/ui/closing.go index c8974fa..c43b4d6 100644 --- a/internal/ui/closing.go +++ b/internal/ui/closing.go @@ -11,12 +11,16 @@ import ( ) // endSelectedFromDashboard is x on the dashboard. +func (m Model) endSelectedFromDashboard() (tea.Model, tea.Cmd) { + return m.endSession(m.focusedSession()) +} + +// endSession closes sess, or asks how to end it. // // Only an isolated session is asked the question. One that ran in the project // directory has no worktree and no branch of its own, so there is nothing for // Delete to remove and a modal offering it would be offering nothing. -func (m Model) endSelectedFromDashboard() (tea.Model, tea.Cmd) { - sess := m.focusedSession() +func (m Model) endSession(sess *store.Session) (tea.Model, tea.Cmd) { if sess == nil { return m, nil } From d649e2140b061ad60749c00234896f4d7467e282 Mon Sep 17 00:00:00 2001 From: tdwd <111124579+tdwd@users.noreply.github.com> Date: Mon, 26 Oct 2026 13:17:40 +0100 Subject: [PATCH 3/3] End or recreate a stuck session from the sidebar MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit In the session view, x only stopped the agent and answered "session is not running" otherwise, so a row there could not be removed. A session whose worktree was deleted by hand never runs, which left it stuck. x and ^g x now stop a live agent as before, and on a session with nothing running they end it through endSession, as the dashboard does. When the worktree is gone and its branch still exists, the end modal offers Recreate first. gitx.RestoreWorktree checks the branch out again at the same path, and the project's ignored instruction files are linked back in. It needs the local branch, because `worktree add` would otherwise take a remote branch or tag of that name. It clears git's stale record through RemoveWorktree rather than prune or --force, and retries only while the path is still empty. Nothing claims a gone worktree is still on disk: the pane points at x instead of ↵, and the Close row and notice no longer say it was kept. Ending a session from the sidebar no longer moves the dashboard cursor of another project. --- README.md | 12 +- docs/architecture.md | 27 +++- internal/gitx/worktree.go | 45 +++++- internal/gitx/worktree_test.go | 152 +++++++++++++++++++++ internal/ui/app_test.go | 7 +- internal/ui/chrome.go | 4 +- internal/ui/closing.go | 42 +++++- internal/ui/input.go | 2 +- internal/ui/keyroutes.go | 2 +- internal/ui/keys.go | 2 +- internal/ui/missingdir.go | 68 ++++++++++ internal/ui/missingdir_test.go | 241 +++++++++++++++++++++++++++++++++ internal/ui/pane.go | 15 ++ internal/ui/pickerctl.go | 33 ++++- internal/ui/runner.go | 16 +-- 15 files changed, 629 insertions(+), 39 deletions(-) create mode 100644 internal/ui/missingdir.go create mode 100644 internal/ui/missingdir_test.go diff --git a/README.md b/README.md index 2ccde1f..9d73bbc 100644 --- a/README.md +++ b/README.md @@ -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 | @@ -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 | @@ -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. diff --git a/docs/architecture.md b/docs/architecture.md index b129b01..dd9ae2a 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -866,12 +866,33 @@ 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. A missing tree with no record at all — `git -worktree prune` already ran — has nothing to remove, so Delete succeeds rather -than stranding the session. +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` diff --git a/internal/gitx/worktree.go b/internal/gitx/worktree.go index 29302af..b293baf 100644 --- a/internal/gitx/worktree.go +++ b/internal/gitx/worktree.go @@ -1,8 +1,8 @@ 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" @@ -88,6 +88,47 @@ func RemoveWorktree(repo, dest string) error { 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 diff --git a/internal/gitx/worktree_test.go b/internal/gitx/worktree_test.go index 2fb7e0f..ea9a63f 100644 --- a/internal/gitx/worktree_test.go +++ b/internal/gitx/worktree_test.go @@ -224,6 +224,139 @@ func TestRemoveWorktreeAfterTheDirectoryIsGone(t *testing.T) { } } +// TestRestoreWorktreeAfterTheDirectoryIsGone is the case Recreate exists for: +// the tree was deleted by hand, git still holds its record, and the branch +// holds a commit the tree had. The commit is the point — a restore that came +// back on the base would look like success and lose the session's work. +func TestRestoreWorktreeAfterTheDirectoryIsGone(t *testing.T) { + repo, dest, branch := session(t) + gittest.Run(t, dest, "commit", "-q", "--allow-empty", "-m", "session work") + want := gittest.Run(t, dest, "rev-parse", "HEAD") + if err := os.RemoveAll(dest); err != nil { + t.Fatal(err) + } + + if err := RestoreWorktree(repo, dest, branch); err != nil { + t.Fatalf("RestoreWorktree: %v", err) + } + if got := gittest.Run(t, dest, "rev-parse", "HEAD"); got != want { + t.Errorf("restored HEAD = %s, want the session's commit %s", got, want) + } +} + +// TestRestoreWorktreeAfterTheRecordIsPruned covers a user who also ran +// `git worktree prune`. There is no record to clear, so the first add has to +// succeed on its own rather than depend on a removal that would now fail. +func TestRestoreWorktreeAfterTheRecordIsPruned(t *testing.T) { + repo, dest, branch := session(t) + if err := os.RemoveAll(dest); err != nil { + t.Fatal(err) + } + gittest.Run(t, repo, "worktree", "prune") + + if err := RestoreWorktree(repo, dest, branch); err != nil { + t.Fatalf("RestoreWorktree after prune: %v", err) + } + if _, err := os.Stat(filepath.Join(dest, "a.txt")); err != nil { + t.Errorf("the restored tree has no checkout: %v", err) + } +} + +// TestRestoreWorktreeNamesAMissingBranch is why the first add's error is the +// one returned. With no record and no branch, the removal fails too, and its +// "is not a working tree" would send the user after the wrong problem. +func TestRestoreWorktreeNamesAMissingBranch(t *testing.T) { + repo, dest, branch := session(t) + if err := os.RemoveAll(dest); err != nil { + t.Fatal(err) + } + gittest.Run(t, repo, "worktree", "prune") + gittest.Run(t, repo, "branch", "-D", branch) + + err := RestoreWorktree(repo, dest, branch) + if err == nil { + t.Fatal("RestoreWorktree succeeded on a branch that does not exist") + } + if strings.Contains(err.Error(), "not a working tree") { + t.Errorf("err = %v, want the add's error rather than the removal's", err) + } + if !strings.Contains(err.Error(), branch) { + t.Errorf("err = %v, want it to name the missing branch", err) + } +} + +// TestRestoreWorktreeLeavesATreeThatAppearedAtDest is the reason only a +// missing dest is retried. The session's record was pruned and another tree +// now sits at the path: removing "the record for dest" would take that tree. +func TestRestoreWorktreeLeavesATreeThatAppearedAtDest(t *testing.T) { + repo, dest, branch := session(t) + if err := os.RemoveAll(dest); err != nil { + t.Fatal(err) + } + gittest.Run(t, repo, "worktree", "prune") + gittest.Run(t, repo, "worktree", "add", "-q", "-b", "someone-else", dest, "HEAD") + + if err := RestoreWorktree(repo, dest, branch); err == nil { + t.Fatal("RestoreWorktree reported success over another tree") + } + if got := gittest.Run(t, dest, "branch", "--show-current"); got != "someone-else" { + t.Errorf("the tree at dest is on %q now, want it left on someone-else", got) + } +} + +// TestRestoreWorktreeRefusesATagOfTheSameName is why the branch is checked +// first. With the branch gone, `worktree add` takes the tag and succeeds on a +// detached HEAD that is not the session's work. +func TestRestoreWorktreeRefusesATagOfTheSameName(t *testing.T) { + repo, dest, branch := session(t) + if err := os.RemoveAll(dest); err != nil { + t.Fatal(err) + } + gittest.Run(t, repo, "worktree", "prune") + gittest.Run(t, repo, "branch", "-D", branch) + gittest.Run(t, repo, "tag", branch) + + if err := RestoreWorktree(repo, dest, branch); err == nil { + t.Fatal("RestoreWorktree checked out a tag in place of the branch") + } + if _, err := os.Lstat(dest); !os.IsNotExist(err) { + t.Errorf("a refused restore left something at dest: %v", err) + } +} + +// TestRestoreWorktreeKeepsOtherMissingRecords rules out `worktree prune`, +// which would clear every missing tree's record, not only this one. +func TestRestoreWorktreeKeepsOtherMissingRecords(t *testing.T) { + repo, dest, branch := session(t) + other := filepath.Join(t.TempDir(), "other") + gittest.Run(t, repo, "worktree", "add", "-q", "-b", "other", other, "HEAD") + for _, d := range []string{dest, other} { + if err := os.RemoveAll(d); err != nil { + t.Fatal(err) + } + } + + if err := RestoreWorktree(repo, dest, branch); err != nil { + t.Fatalf("RestoreWorktree: %v", err) + } + if rec, err := missingRecord(repo, other); err != nil || rec == nil { + t.Errorf("the other missing tree lost its record: rec=%v err=%v", rec, err) + } +} + +// TestRestoreWorktreeRecreatesAMissingParent covers the session directory's +// parent going too, which is what deleting the whole worktrees folder does. +func TestRestoreWorktreeRecreatesAMissingParent(t *testing.T) { + repo, dest, branch := session(t) + if err := os.RemoveAll(filepath.Dir(dest)); err != nil { + t.Fatal(err) + } + + if err := RestoreWorktree(repo, dest, branch); err != nil { + t.Fatalf("RestoreWorktree with the parent gone: %v", err) + } +} + // TestRemoveWorktreeKeepsADetachedCommit is the case where git's record is // the only reference to the work. `worktree remove` would drop it and exit 0, // leaving the commit for gc. @@ -290,3 +423,22 @@ func TestDeleteBranchThatIsAlreadyGone(t *testing.T) { t.Errorf("DeleteBranch on a branch already gone: %v", err) } } + +// TestRestoreWorktreeKeepsADetachedCommit is the restore side of the same +// rule, and what rules out --force: add -f succeeds straight over the record, +// and the record was the only reference to the detached commit. +func TestRestoreWorktreeKeepsADetachedCommit(t *testing.T) { + repo, dest, branch := session(t) + gittest.Run(t, dest, "checkout", "-q", "--detach") + gittest.Run(t, dest, "commit", "-q", "--allow-empty", "-m", "detached work") + if err := os.RemoveAll(dest); err != nil { + t.Fatal(err) + } + + if err := RestoreWorktree(repo, dest, branch); err == nil { + t.Fatal("RestoreWorktree dropped the only reference to a commit") + } + if rec, _ := missingRecord(repo, dest); rec == nil || !rec.detached { + t.Errorf("the record holding the commit is gone: %+v", rec) + } +} diff --git a/internal/ui/app_test.go b/internal/ui/app_test.go index 5f955f1..92a8c6c 100644 --- a/internal/ui/app_test.go +++ b/internal/ui/app_test.go @@ -205,6 +205,11 @@ func TestCloseIgnoresProjectsColumn(t *testing.T) { func TestEndModalClosesAndKeepsTheWorktree(t *testing.T) { t.Setenv("XDG_STATE_HOME", t.TempDir()) m := modelWith(2) + // A real directory: the notice names a worktree only while one is there. + dir := t.TempDir() + for i := range m.state.Sessions { + m.state.Sessions[i].Dir = dir + } m.focusContent() opened, _ := m.dashboardKey(typed("x")) @@ -224,7 +229,7 @@ func TestEndModalClosesAndKeepsTheWorktree(t *testing.T) { if n := len(done.state.Sessions); n != 1 { t.Errorf("sessions = %d after choosing Close, want 1", n) } - if !strings.Contains(done.notice, "/worktrees/sess") { + if !strings.Contains(done.notice, dir) { t.Errorf("notice = %q, want it to name where the worktree was kept", done.notice) } } diff --git a/internal/ui/chrome.go b/internal/ui/chrome.go index e6ca43d..b8b5570 100644 --- a/internal/ui/chrome.go +++ b/internal/ui/chrome.go @@ -94,7 +94,7 @@ func (m Model) commandHint() string { } pairs := [][2]string{ {"d", "dashboard"}, {"j/k", "switch"}, {"1…", "jump"}, {"n", "new"}, {"e", "rename"}, - {"x", "stop"}, {"↵", "attach"}, {"esc", "detach"}, {"?", "help"}, + {"x", "stop/end"}, {"↵", "attach"}, {"esc", "detach"}, {"?", "help"}, {"q", "quit"}, {"^g", "literal"}, } parts := make([]string, 0, len(pairs)) @@ -120,7 +120,7 @@ func (m Model) sessionFooter() string { if m.attached { return s.Footer.Render(" ^g for commands · ^g d dashboard · ^g j/k switch session · ^g n new · ^g ? help") } - return s.Footer.Render(" ↑/↓ session · ↵ attach · n new · e rename · x stop · d dashboard · ? help · q quit") + return s.Footer.Render(" ↑/↓ session · ↵ attach · n new · e rename · x stop/end · d dashboard · ? help · q quit") } // spread puts left and right on one line separated by padding, so the right diff --git a/internal/ui/closing.go b/internal/ui/closing.go index c43b4d6..088ec9b 100644 --- a/internal/ui/closing.go +++ b/internal/ui/closing.go @@ -2,10 +2,13 @@ package ui // Ending a session, which is two outcomes rather than one: closing forgets the // record and keeps the worktree, deleting removes the worktree and the branch -// behind it. The modal that asks which is pickerctl.go. +// behind it. A session whose worktree was deleted by hand gets a third, +// recreating it, which continues the session instead. The modal that asks which +// is pickerctl.go. import ( tea "github.com/charmbracelet/bubbletea" + "github.com/tripledownab/deck/internal/agent" "github.com/tripledownab/deck/internal/gitx" "github.com/tripledownab/deck/internal/store" ) @@ -15,6 +18,28 @@ func (m Model) endSelectedFromDashboard() (tea.Model, tea.Cmd) { return m.endSession(m.focusedSession()) } +// stopOrEnd is x in the session view: it stops a live agent, and ends a +// session that has none. +// +// Stopping alone left the sidebar with no way to remove a row. A session whose +// worktree was deleted by hand cannot start, so it never has a live agent, and +// x answered "not running" to the one session that most needed ending. A live +// agent is still only stopped, so ending one takes a second x and the modal. +func (m Model) stopOrEnd() (tea.Model, tea.Cmd) { + sess := m.currentSession() + if sess == nil { + return m, nil + } + if r, ok := m.runners[sess.ID]; ok && r.Status() != agent.Exited { + m.stopRunner(sess.ID) + m.attached = false + m.notice = "stopped " + sess.Name + return m, nil + } + m.attached = false + return m.endSession(sess) +} + // endSession closes sess, or asks how to end it. // // Only an isolated session is asked the question. One that ran in the project @@ -41,9 +66,12 @@ func (m Model) endPicked(choice string) (tea.Model, tea.Cmd) { if sess == nil { return m, nil } - if choice == endDelete { + switch choice { + case endRecreate: + m.recreateWorktree(*sess) + case endDelete: m.deleteSession(*sess) - } else { + default: m.closeSession(*sess) } return m, nil @@ -59,7 +87,7 @@ func (m *Model) closeSession(sess store.Session) { if !m.forget(sess) { return } - if sess.Isolated { + if sess.Isolated && !dirGone(sess.Dir) { m.notice = "closed " + sess.Name + " — worktree kept at " + sess.Dir } else { m.notice = "closed " + sess.Name @@ -136,6 +164,12 @@ func (m *Model) forget(sess store.Session) bool { } m.syncConnections() m.rebuildRows() + // The dashboard's cursor belongs to the project it shows. A session ended + // from the sidebar may be in another one, and clamping by that project's + // count would move a cursor the user left somewhere else. + if p := m.currentProject(); p == nil || p.ID != sess.ProjectID { + return true + } left := m.state.SessionsFor(sess.ProjectID) m.listIx = clamp(m.listIx, 0, max(len(left)-1, 0)) // Ending the last one leaves the cursor in a column with nothing in it — diff --git a/internal/ui/input.go b/internal/ui/input.go index 417943c..e410729 100644 --- a/internal/ui/input.go +++ b/internal/ui/input.go @@ -113,7 +113,7 @@ func (m Model) command(msg tea.KeyMsg) (tea.Model, tea.Cmd) { case "k", "up": m.moveRow(-1) case "x": - m.stopCurrent() + return m.stopOrEnd() case "esc", " ": m.attached = false case "enter", "i": diff --git a/internal/ui/keyroutes.go b/internal/ui/keyroutes.go index 8498ec1..638e91c 100644 --- a/internal/ui/keyroutes.go +++ b/internal/ui/keyroutes.go @@ -63,7 +63,7 @@ func (m Model) sessionKey(msg tea.KeyMsg) (tea.Model, tea.Cmd) { case key.Matches(msg, m.keys.Rename): return m.openSessionRename() case key.Matches(msg, m.keys.Delete): - m.stopCurrent() + return m.stopOrEnd() case key.Matches(msg, m.keys.Connect): return m.openConnectPicker(m.currentSession()) case key.Matches(msg, m.keys.Theme): diff --git a/internal/ui/keys.go b/internal/ui/keys.go index 2c33992..c117cf1 100644 --- a/internal/ui/keys.go +++ b/internal/ui/keys.go @@ -73,7 +73,7 @@ func defaultKeys() keyMap { Sessions: key.NewBinding(key.WithKeys("s"), key.WithHelp("^g s", "sessions")), NewSessCmd: key.NewBinding(key.WithKeys("n"), key.WithHelp("^g n", "new session")), RenameCmd: key.NewBinding(key.WithKeys("e"), key.WithHelp("^g e", "rename this session")), - StopSessCmd: key.NewBinding(key.WithKeys("x"), key.WithHelp("^g x", "stop the agent")), + StopSessCmd: key.NewBinding(key.WithKeys("x"), key.WithHelp("^g x", "stop the agent, or end a stopped session")), ThemeCmd: key.NewBinding(key.WithKeys("t"), key.WithHelp("^g t", "theme")), HelpCmd: key.NewBinding(key.WithKeys("?"), key.WithHelp("^g ?", "this help")), QuitCmd: key.NewBinding(key.WithKeys("q"), key.WithHelp("^g q", "quit")), diff --git a/internal/ui/missingdir.go b/internal/ui/missingdir.go new file mode 100644 index 0000000..a39b304 --- /dev/null +++ b/internal/ui/missingdir.go @@ -0,0 +1,68 @@ +package ui + +// A session whose worktree was deleted by hand: telling that apart from one +// still on disk, and checking its branch out again so the session continues. + +import ( + "errors" + "fmt" + "io/fs" + "os" + + "github.com/tripledownab/deck/internal/gitx" + "github.com/tripledownab/deck/internal/store" +) + +// dirGone reports whether dir no longer exists, which is how a worktree deleted +// by hand looks from here. Any other stat error is not taken as gone: the text +// that depends on it then says what it would say for a tree still on disk. +// Lstat, so a dangling link left at the path counts as something there: git +// refuses to add over it, and offering Recreate would only lead to that. +func dirGone(dir string) bool { + _, err := os.Lstat(dir) + return errors.Is(err, fs.ErrNotExist) +} + +// canRecreate reports whether a session's branch is still there to check out. +// A branch deleted since — merged and pruned, say — leaves nothing to recreate, +// and a row offering it would promise what RestoreWorktree then refuses. A +// failed look leaves the row out and is reported, so its absence has a reason +// on screen; Close and Delete are still offered. +func (m *Model) canRecreate(sess store.Session) bool { + p := m.state.Project(sess.ProjectID) + if p == nil || sess.Branch == "" { + return false + } + ok, err := gitx.HasBranch(p.Path, sess.Branch) + if err != nil { + m.fault = err + } + return ok +} + +// recreateWorktree checks a session's branch out again where its worktree was, +// so the session continues rather than ends. The record already names that +// directory and branch, and the agent starts with ↵ as it does for any session +// that is not running. +// +// The project's ignored instruction files are linked again, as newSession links +// them, because a tree without them gives an agent that behaves differently +// for a reason nothing on screen explains. A link that fails is reported and +// the tree stays: unlike newSession there is no record to roll back to, and +// the tree is the thing the user asked for. +func (m *Model) recreateWorktree(sess store.Session) { + p := m.state.Project(sess.ProjectID) + if p == nil { + m.notice = sess.Name + " has no project to recreate its worktree in" + return + } + if err := gitx.RestoreWorktree(p.Path, sess.Dir, sess.Branch); err != nil { + m.fault = err + return + } + if err := linkProjectFiles(p.Path, sess.Dir); err != nil { + m.fault = fmt.Errorf("recreated %s, but: %w", sess.Name, err) + return + } + m.notice = "recreated " + sess.Name + " at " + sess.Dir + " — ↵ starts the agent" +} diff --git a/internal/ui/missingdir_test.go b/internal/ui/missingdir_test.go new file mode 100644 index 0000000..76bff85 --- /dev/null +++ b/internal/ui/missingdir_test.go @@ -0,0 +1,241 @@ +package ui + +// Ending and recreating a session from the session view, including the one +// whose worktree was deleted by hand. That session cannot start, so x in the +// sidebar was the only way out of it and it used to answer "not running". + +import ( + "os" + "path/filepath" + "strings" + "testing" + + tea "github.com/charmbracelet/bubbletea" + "github.com/tripledownab/deck/internal/gittest" + "github.com/tripledownab/deck/internal/store" +) + +// inSessionView puts a deckWithWorktree model on its session's sidebar row. +func inSessionView(t *testing.T, m Model) Model { + t.Helper() + m.screen = screenSession + m.rebuildRows() + if m.currentSession() == nil { + t.Fatal("the sidebar has no session selected; the test proves nothing") + } + return m +} + +// TestXInTheSessionViewEndsAStoppedSession is the dead end this file fixes. +// Both routes to x are driven: the bare key and the one after the prefix. +func TestXInTheSessionViewEndsAStoppedSession(t *testing.T) { + m, _ := deckWithWorktree(t) + m = inSessionView(t, m) + + for name, press := range map[string]func(Model) (tea.Model, tea.Cmd){ + "x": func(m Model) (tea.Model, tea.Cmd) { return m.sessionKey(typed("x")) }, + "^g x": func(m Model) (tea.Model, tea.Cmd) { return m.command(typed("x")) }, + } { + got, _ := press(m) + if got.(Model).picker == nil { + t.Errorf("%s on a stopped session did not open the end-session modal", name) + } + } +} + +// TestXInTheSessionViewStopsALiveAgent keeps the first x what it was. Ending a +// live session takes a second press, so one key never takes a running agent +// and its session together. +func TestXInTheSessionViewStopsALiveAgent(t *testing.T) { + m, sess := deckWithWorktree(t) + m = inSessionView(t, m) + m.runners[sess.ID] = startAgent(t, sess.Dir, "") + + got, _ := m.sessionKey(typed("x")) + after := got.(Model) + + if _, ok := after.runners[sess.ID]; ok { + t.Error("x left the agent running") + } + if after.picker != nil { + t.Error("x on a live agent went straight to the end-session modal") + } +} + +// TestRecreateRestoresAGoneWorktree drives the whole path a user takes: x on +// the stuck session, the modal opening on Recreate, and enter. +func TestRecreateRestoresAGoneWorktree(t *testing.T) { + m, sess := deckWithWorktree(t) + if err := os.RemoveAll(sess.Dir); err != nil { + t.Fatal(err) + } + m = inSessionView(t, m) + + opened, _ := m.sessionKey(typed("x")) + asked := opened.(Model) + if asked.picker == nil { + t.Fatal("x did not open the end-session modal") + } + if got := asked.picker.selected(); got != endRecreate { + t.Fatalf("the modal opened on %q, want %q", got, endRecreate) + } + + picked, _ := asked.pickerKey(tea.KeyMsg{Type: tea.KeyEnter}) + done := picked.(Model) + + if done.fault != nil { + t.Fatalf("Recreate reported: %v", done.fault) + } + if _, err := os.Stat(sess.Dir); err != nil { + t.Errorf("the worktree is still missing: %v", err) + } + if n := len(done.state.Sessions); n != 1 { + t.Errorf("sessions = %d, want the session kept", n) + } +} + +// TestGoneWorktreeIsNotClaimedKept holds every place that would otherwise say +// the tree is still on disk: the pane's hint, the Close row, and the notice. +func TestGoneWorktreeIsNotClaimedKept(t *testing.T) { + m, sess := deckWithWorktree(t) + if err := os.RemoveAll(sess.Dir); err != nil { + t.Fatal(err) + } + m = inSessionView(t, m) + + if pane := m.renderPane(80, 10); !strings.Contains(pane, "Press x") { + t.Errorf("the pane does not point at x:\n%s", pane) + } + opened, _ := m.sessionKey(typed("x")) + for _, row := range opened.(Model).picker.rows { + if strings.Contains(row.desc, "keep the worktree") { + t.Errorf("row %q offers to keep a worktree that is gone", row.label) + } + } + m.closeSession(sess) + if strings.Contains(m.notice, "kept") { + t.Errorf("notice = %q, want no claim that the worktree was kept", m.notice) + } +} + +// TestGoneWorktreeUnderAnExitedAgent covers the tree deleted while its agent +// ran. The agent exits, the pane keeps its last screen, and the hint under it +// must not offer ↵, which can no longer start anything there. +func TestGoneWorktreeUnderAnExitedAgent(t *testing.T) { + m, sess := deckWithWorktree(t) + r := startAgent(t, sess.Dir, "exit 0") + waitExited(t, r) + m.runners[sess.ID] = r + if err := os.RemoveAll(sess.Dir); err != nil { + t.Fatal(err) + } + m = inSessionView(t, m) + + pane := m.renderPane(80, 10) + if !strings.Contains(pane, "Press x") || strings.Contains(pane, "Press ↵") { + t.Errorf("the hint does not point at x alone:\n%s", pane) + } +} + +// TestXEndsASessionWhoseAgentExited covers the other half of "nothing +// running". An exited runner stays in the map until it is replaced, and x on +// it must end the session rather than stop what has already stopped. +func TestXEndsASessionWhoseAgentExited(t *testing.T) { + m, sess := deckWithWorktree(t) + r := startAgent(t, sess.Dir, "exit 0") + waitExited(t, r) + m.runners[sess.ID] = r + m = inSessionView(t, m) + m.attached = true + + got, _ := m.command(typed("x")) + after := got.(Model) + + if after.picker == nil { + t.Error("x on an exited agent did not open the end-session modal") + } + if after.attached { + t.Error("the pane stayed attached under the modal") + } +} + +// TestNoRecreateWithoutTheBranch keeps the modal from offering what +// RestoreWorktree will refuse, and keeps the rows saying something. +func TestNoRecreateWithoutTheBranch(t *testing.T) { + m, sess := deckWithWorktree(t) + repo := m.state.Project(sess.ProjectID).Path + if err := os.RemoveAll(sess.Dir); err != nil { + t.Fatal(err) + } + gittest.Run(t, repo, "worktree", "prune") + gittest.Run(t, repo, "branch", "-D", sess.Branch) + m = inSessionView(t, m) + + opened, _ := m.sessionKey(typed("x")) + for _, row := range opened.(Model).picker.rows { + if row.id == endRecreate { + t.Error("Recreate is offered for a branch that no longer exists") + } + if row.desc == "" { + t.Errorf("row %q says nothing", row.label) + } + } +} + +// TestRecreateLinksTheProjectFiles is newSession's promise kept on the way +// back: an agent in a recreated tree gets the same ignored instructions. +func TestRecreateLinksTheProjectFiles(t *testing.T) { + m, sess := deckWithWorktree(t) + repo := m.state.Project(sess.ProjectID).Path + if err := os.WriteFile(filepath.Join(repo, ".gitignore"), []byte("CLAUDE.md\n"), 0o644); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(repo, "CLAUDE.md"), []byte("rules\n"), 0o644); err != nil { + t.Fatal(err) + } + if err := os.RemoveAll(sess.Dir); err != nil { + t.Fatal(err) + } + + m.recreateWorktree(sess) + + if m.fault != nil { + t.Fatalf("Recreate reported: %v", m.fault) + } + if _, err := os.Lstat(filepath.Join(sess.Dir, "CLAUDE.md")); err != nil { + t.Errorf("the recreated tree has no instructions: %v", err) + } +} + +// TestEndingFromTheSidebarLeavesTheDashboardCursor is forget's promise for a +// session the dashboard is not showing. Before the sidebar could end one, +// the ended session was always in the dashboard's project. +func TestEndingFromTheSidebarLeavesTheDashboardCursor(t *testing.T) { + m, sess := deckWithWorktree(t) + other := m.state.AddProject(store.Project{Name: "other", Path: t.TempDir()}) + for range 3 { + m.state.AddSession(store.Session{ProjectID: other.ID, Name: "o", Dir: other.Path}) + } + m.rebuildRows() + m.projectIx = 1 + m.listIx = 2 + m.focusContent() + + m.closeSession(sess) + + if m.listIx != 2 || m.focus != colContent { + t.Errorf("listIx = %d, focus = %v, want the cursor left on the other project", m.listIx, m.focus) + } +} + +// TestADanglingLinkIsNotAGoneWorktree keeps Recreate off a path git will +// refuse to add over. Stat follows the link and would call it gone. +func TestADanglingLinkIsNotAGoneWorktree(t *testing.T) { + path := filepath.Join(t.TempDir(), "wt") + if err := os.Symlink(filepath.Join(t.TempDir(), "nowhere"), path); err != nil { + t.Fatal(err) + } + if dirGone(path) { + t.Error("a dangling link at the path counts as gone") + } +} diff --git a/internal/ui/pane.go b/internal/ui/pane.go index dd729ca..59ecbb1 100644 --- a/internal/ui/pane.go +++ b/internal/ui/pane.go @@ -10,6 +10,11 @@ import ( "github.com/tripledownab/deck/internal/agent" ) +// goneHint is what the pane offers for a session whose worktree was deleted by +// hand. ↵ is the usual hint and it would fail there, so x is named instead. It +// does not promise Recreate, which needs the branch to be there still. +const goneHint = "Press x to choose what happens to the session" + func (m Model) renderPane(width, height int) string { s := m.styles border := s.Pane @@ -25,6 +30,13 @@ func (m Model) renderPane(width, height int) string { } r := m.runners[sess.ID] + // ↵ cannot start an agent in a directory that is not there, so both hints + // below would send the user into an error. x is the way out of this state. + gone := sess.Isolated && dirGone(sess.Dir) + if r == nil && gone { + return border.Render(m.placeholder(width, height, + "The worktree of “"+firstLine(sess.Title, sess.Name)+"” is gone.", goneHint)) + } if r == nil { return border.Render(m.placeholder(width, height, "“"+firstLine(sess.Title, sess.Name)+"” is closed.", @@ -42,6 +54,9 @@ func (m Model) renderPane(width, height int) string { if willResume(sess) { hint += ", resuming the conversation" } + if gone { + hint = "Its worktree is gone. " + goneHint + } // The emulator still holds the final screen, so show it under a // banner rather than clearing what the agent last said. lines := r.Render(false, nil, nil) diff --git a/internal/ui/pickerctl.go b/internal/ui/pickerctl.go index 3dd43ce..14c4568 100644 --- a/internal/ui/pickerctl.go +++ b/internal/ui/pickerctl.go @@ -12,12 +12,13 @@ import ( "github.com/tripledownab/deck/internal/store" ) -// The two rows of the end-session modal. They are ids rather than labels -// because the label is what the user reads and the id is what endPicked -// branches on, and a row renamed for clarity must not change what it does. +// The rows of the end-session modal. They are ids rather than labels because +// the label is what the user reads and the id is what endPicked branches on, +// and a row renamed for clarity must not change what it does. const ( - endClose = "close" - endDelete = "delete" + endRecreate = "recreate" + endClose = "close" + endDelete = "delete" ) // openThemePicker opens the theme list, positioned on the active theme. @@ -51,13 +52,31 @@ func (m Model) openFieldPicker() (tea.Model, tea.Cmd) { // The Delete row carries what that session changed rather than a warning about // what it is about to lose. A confirmation that states a fact can be answered; // one that states a warning can only be believed or dismissed. +// +// A worktree deleted by hand has nothing left to keep or measure, so the rows +// say that instead. Delete still has work to do: git drops its record of the +// tree, and the branch goes too unless `branch -d` refuses it. Recreate is +// offered first and the cursor starts on it, because the branch still holds +// the work and checking it out again is the outcome that loses nothing. func (m Model) openEndSessionPicker(sess *store.Session) (tea.Model, tea.Cmd) { rows := []pickerRow{ {id: endClose, label: "Close", desc: "keep the worktree at " + sess.Dir}, - {id: endDelete, label: "Delete", desc: "remove the worktree and branch — " + workSummary(*sess)}, + {id: endDelete, label: "Delete"}, + } + start := endClose + if !dirGone(sess.Dir) { + rows[1].desc = "remove the worktree and branch — " + workSummary(*sess) + } else { + rows[0].desc = "forget the session — its worktree is already gone" + rows[1].desc = "drop git's record of the worktree, and the branch unless unmerged" + if m.canRecreate(*sess) { + rows = append([]pickerRow{{id: endRecreate, label: "Recreate", + desc: "check " + sess.Branch + " out again at " + sess.Dir}}, rows...) + start = endRecreate + } } m.pickerSubject = sess.ID - m.picker = newPicker(pickEndSession, "End "+sessionLabel(*sess), rows, endClose) + m.picker = newPicker(pickEndSession, "End "+sessionLabel(*sess), rows, start) return m, nil } diff --git a/internal/ui/runner.go b/internal/ui/runner.go index a62d2f7..bda742a 100644 --- a/internal/ui/runner.go +++ b/internal/ui/runner.go @@ -52,20 +52,6 @@ func (m Model) attach() (tea.Model, tea.Cmd) { return m, nil } -func (m *Model) stopCurrent() { - sess := m.currentSession() - if sess == nil { - return - } - if _, ok := m.runners[sess.ID]; !ok { - m.notice = "session is not running" - return - } - m.stopRunner(sess.ID) - m.attached = false - m.notice = "stopped " + sess.Name -} - // stopRunner stops a session's agent and frees what it held in the // coordinator. // @@ -91,7 +77,7 @@ func (m *Model) releaseCoord(sessionID string) { // sweepExited releases sessions whose agent stopped without being told to. // -// stopCurrent and stopRunner cover the deliberate paths, but +// stopOrEnd and stopRunner cover the deliberate paths, but // an agent can also leave on its own — /exit, a crash, the process being // killed. Nothing calls back into the UI when that happens, so without this // sweep the coordinator keeps listing a dead session and holding its claims,