From 11907ae14a5a9efa26037b125cabe48a00fb5777 Mon Sep 17 00:00:00 2001 From: Amit Ghadge Date: Sun, 15 Nov 2026 13:15:13 -0800 Subject: [PATCH] A checkout mid-rebase shows under the branch being rebased git detaches HEAD while it rebases, so the worktree list named no branch and an agent working on main mid-rebase showed under no branch (#230). The rebase names its branch in head-name: WorktreeInfo carries it, with the operation in progress (worktree.operation.v1), and the TUI and Conch.app say rebasing on the branch's row. The same blindness let worktree.stale suggest removing a worktree mid-rebase and branch.prune offer the branch being rebased; neither does now. Co-Authored-By: Claude Opus 5.5 --- cmd/conch/branch.go | 3 + cmd/conch/worktreestate_test.go | 26 ++++ internal/gitx/user.go | 66 +++++++--- internal/gitx/user_test.go | 113 ++++++++++++++++++ internal/proto/proto.go | 17 ++- internal/server/cleanup.go | 21 +++- internal/server/cleanup_test.go | 48 ++++++++ internal/server/projects.go | 13 +- internal/server/projects_test.go | 90 ++++++++++++++ internal/tui/rebasing_test.go | 40 +++++++ internal/tui/view.go | 9 +- macos/Sources/ConchKit/Model.swift | 15 ++- macos/Sources/ConchKit/Protocol.swift | 4 + macos/Tests/ConchKitTests/ConchKitTests.swift | 23 ++++ web/src/app/docs/cli/page.mdx | 2 +- web/src/app/docs/protocol/page.mdx | 2 +- 16 files changed, 466 insertions(+), 26 deletions(-) create mode 100644 cmd/conch/worktreestate_test.go create mode 100644 internal/tui/rebasing_test.go diff --git a/cmd/conch/branch.go b/cmd/conch/branch.go index 0df2f1bf..8bb4a225 100644 --- a/cmd/conch/branch.go +++ b/cmd/conch/branch.go @@ -12,6 +12,7 @@ import ( "github.com/Amitgb14/conch/internal/client" "github.com/Amitgb14/conch/internal/config" + "github.com/Amitgb14/conch/internal/gitx" "github.com/Amitgb14/conch/internal/proto" ) @@ -469,6 +470,8 @@ func worktreeLabel(w proto.StaleWorktree) string { // why it looks finished. func worktreeState(w proto.StaleWorktree) string { switch { + case w.Operation != "": + return gitx.OperationWord(w.Operation) case w.Panes: return "panes running" case w.Locked: diff --git a/cmd/conch/worktreestate_test.go b/cmd/conch/worktreestate_test.go new file mode 100644 index 00000000..f7f3cd67 --- /dev/null +++ b/cmd/conch/worktreestate_test.go @@ -0,0 +1,26 @@ +package main + +import ( + "testing" + + "github.com/Amitgb14/conch/internal/proto" +) + +// conch worktree ls says a worktree mid-rebase is rebasing, before +// anything else about it, and names the branch the rebase is rewriting. +func TestWorktreeStateSaysRebasing(t *testing.T) { + w := proto.StaleWorktree{Path: "/r/feat", Branch: "feat", Operation: "rebase", Panes: true} + if got := worktreeState(w); got != "rebasing" { + t.Fatalf("state: %q", got) + } + if got := worktreeLabel(w); got != "feat" { + t.Fatalf("label: %q", got) + } + w.Operation = "" + if got := worktreeState(w); got != "panes running" { + t.Fatalf("no operation: %q", got) + } + if got := worktreeLabel(proto.StaleWorktree{Path: "/r/x"}); got != "(detached)" { + t.Fatalf("detached: %q", got) + } +} diff --git a/internal/gitx/user.go b/internal/gitx/user.go index 5b1c8fd4..911e9996 100644 --- a/internal/gitx/user.go +++ b/internal/gitx/user.go @@ -105,16 +105,8 @@ func gitDir(ctx context.Context, dir string) (string, bool) { // rewriting, or "". git detaches HEAD while it works, so the worktree list // shows no branch there until the rebase ends. func RebasingBranch(ctx context.Context, dir string) string { - gd, ok := gitDir(ctx, dir) - if !ok { - return "" - } - for _, d := range []string{"rebase-merge", "rebase-apply"} { - if b, err := os.ReadFile(filepath.Join(gd, d, "head-name")); err == nil { - return strings.TrimPrefix(strings.TrimSpace(string(b)), "refs/heads/") - } - } - return "" + _, branch := Operation(ctx, dir) + return branch } // InProgress names the operation left unfinished in the checkout at dir — @@ -122,28 +114,66 @@ func RebasingBranch(ctx context.Context, dir string) string { // none. Each worktree has its own, so a conflict in one doesn't show in // the others. func InProgress(ctx context.Context, dir string) string { + op, _ := Operation(ctx, dir) + return op +} + +// OperationWord says what Operation found as a person reads it beside a +// branch: "rebasing" for "rebase". +func OperationWord(op string) string { + switch op { + case "rebase": + return "rebasing" + case "merge": + return "merging" + case "cherry-pick": + return "cherry-picking" + case "revert": + return "reverting" + case "am": + return "applying patches" + } + return op +} + +// Operation is InProgress and, for a rebase, the branch it is rewriting, +// read with one call to git. The branch is "" for anything but a rebase of +// a branch: an am also keeps rebase-apply, and a rebase of a detached HEAD +// writes "detached HEAD" where a branch's name would be. +func Operation(ctx context.Context, dir string) (op, branch string) { gd, ok := gitDir(ctx, dir) if !ok { - return "" + return "", "" } has := func(name string) bool { _, err := os.Stat(filepath.Join(gd, name)) return err == nil } + headName := func(d string) string { + b, err := os.ReadFile(filepath.Join(gd, d, "head-name")) + if err != nil { + return "" + } + name, ok := strings.CutPrefix(strings.TrimSpace(string(b)), "refs/heads/") + if !ok { + return "" + } + return name + } switch { case has("rebase-merge"): - return "rebase" + return "rebase", headName("rebase-merge") case has("rebase-apply"): if has("rebase-apply/applying") { - return "am" + return "am", "" } - return "rebase" + return "rebase", headName("rebase-apply") case has("MERGE_HEAD"): - return "merge" + return "merge", "" case has("CHERRY_PICK_HEAD"): - return "cherry-pick" + return "cherry-pick", "" case has("REVERT_HEAD"): - return "revert" + return "revert", "" } - return "" + return "", "" } diff --git a/internal/gitx/user_test.go b/internal/gitx/user_test.go index e3f1c30e..cc212c3d 100644 --- a/internal/gitx/user_test.go +++ b/internal/gitx/user_test.go @@ -3,6 +3,8 @@ package gitx import ( "context" "errors" + "os" + "path/filepath" "strings" "testing" "time" @@ -182,3 +184,114 @@ func TestInProgress(t *testing.T) { t.Fatalf("missing dir: %q", got) } } + +// stuckRebase leaves the checkout at dir mid-rebase onto onto, stopped on +// a conflict, with the extra arguments given to git rebase. +func stuckRebase(t *testing.T, dir, onto string, args ...string) { + t.Helper() + argv := append(append([]string{"rebase"}, args...), onto) + if _, code, _, _ := RunUser(ctx, dir, argv, 1<<16); code == 0 { + t.Fatalf("git %v didn't conflict", argv) + } +} + +func TestOperation(t *testing.T) { + t.Run("linked worktree, each backend", func(t *testing.T) { + for _, args := range [][]string{nil, {"-i"}, {"--apply"}} { + root, wt := taskRepo(t) + commit(t, root, "README.md", "hello\nfrom main\n", "main edit") + commit(t, wt, "README.md", "hello\nfrom feat\n", "feat edit") + if len(args) > 0 && args[0] == "-i" { + t.Setenv("GIT_SEQUENCE_EDITOR", "true") // take the todo list as it is + } + stuckRebase(t, wt, "main", args...) + if op, b := Operation(ctx, wt); op != "rebase" || b != "feat" { + t.Fatalf("rebase %v: %q %q", args, op, b) + } + // The main checkout is not the one rebasing. + if op, b := Operation(ctx, root); op != "" || b != "" { + t.Fatalf("main checkout during rebase %v: %q %q", args, op, b) + } + git(t, wt, "rebase", "--abort") + if op, b := Operation(ctx, wt); op != "" || b != "" { + t.Fatalf("after aborting %v: %q %q", args, op, b) + } + } + }) + + t.Run("main checkout", func(t *testing.T) { + root := newRepo(t) + git(t, root, "checkout", "-q", "-b", "side") + commit(t, root, "README.md", "hello\nfrom side\n", "side edit") + git(t, root, "checkout", "-q", "main") + commit(t, root, "README.md", "hello\nfrom main\n", "main edit") + stuckRebase(t, root, "side") + if op, b := Operation(ctx, root); op != "rebase" || b != "main" { + t.Fatalf("main checkout rebasing: %q %q", op, b) + } + }) + + t.Run("detached HEAD rebased", func(t *testing.T) { + root, wt := taskRepo(t) + commit(t, root, "README.md", "hello\nfrom main\n", "main edit") + commit(t, wt, "README.md", "hello\nfrom feat\n", "feat edit") + git(t, wt, "checkout", "-q", "--detach") + stuckRebase(t, wt, "main") + // git writes "detached HEAD" where a branch would be: no branch. + if op, b := Operation(ctx, wt); op != "rebase" || b != "" { + t.Fatalf("detached rebase: %q %q", op, b) + } + }) + + t.Run("head-name missing or empty", func(t *testing.T) { + root, wt := taskRepo(t) + commit(t, root, "README.md", "hello\nfrom main\n", "main edit") + commit(t, wt, "README.md", "hello\nfrom feat\n", "feat edit") + stuckRebase(t, wt, "main") + gd := git(t, wt, "rev-parse", "--absolute-git-dir") + name := filepath.Join(gd, "rebase-merge", "head-name") + if err := os.WriteFile(name, nil, 0o644); err != nil { + t.Fatal(err) + } + if op, b := Operation(ctx, wt); op != "rebase" || b != "" { + t.Fatalf("empty head-name: %q %q", op, b) + } + if err := os.Remove(name); err != nil { + t.Fatal(err) + } + if op, b := Operation(ctx, wt); op != "rebase" || b != "" { + t.Fatalf("no head-name: %q %q", op, b) + } + }) + + t.Run("am is not a rebase", func(t *testing.T) { + root, wt := taskRepo(t) + commit(t, root, "README.md", "hello\nfrom main\n", "main edit") + patch := filepath.Join(t.TempDir(), "p.patch") + write(t, filepath.Dir(patch), "p.patch", git(t, root, "format-patch", "-1", "--stdout")+"\n") + commit(t, wt, "README.md", "hello\nfrom feat\n", "feat edit") + if _, code, _, _ := RunUser(ctx, wt, []string{"am", patch}, 1<<16); code == 0 { + t.Fatal("am didn't conflict") + } + if op, b := Operation(ctx, wt); op != "am" || b != "" { + t.Fatalf("am: %q %q", op, b) + } + }) + + t.Run("not a repository", func(t *testing.T) { + if op, b := Operation(ctx, t.TempDir()); op != "" || b != "" { + t.Fatalf("plain folder: %q %q", op, b) + } + }) +} + +func TestOperationWord(t *testing.T) { + for op, want := range map[string]string{ + "rebase": "rebasing", "merge": "merging", "cherry-pick": "cherry-picking", + "revert": "reverting", "am": "applying patches", "bisect": "bisect", "": "", + } { + if got := OperationWord(op); got != want { + t.Errorf("%q: %q, want %q", op, got, want) + } + } +} diff --git a/internal/proto/proto.go b/internal/proto/proto.go index a5958a93..ddd88443 100644 --- a/internal/proto/proto.go +++ b/internal/proto/proto.go @@ -35,7 +35,7 @@ const ProtocolVersion = 1 var Capabilities = []string{ "pane.v1", "pane.frame.v1", "events.v1", "agent.v1", "project.v1", "pane.scroll.v1", "project.pr.v1", "pane.default_shell.v1", - "agent.install.v1", "fs.v1", "shell.omz.v1", "agent.setup.v1", "worktree.files.v1", "session.v1", "agent.limits.v1", "server.reload.v1", "session.delete.v1", "session.search.v1", "session.share.v1", "agent.broadcast.v1", "agent.broadcast.shells.v1", "pane.redraw.v1", "fs.upload.v1", "branch.harvest.v1", "worktree.cleanup.v1", "branch.hunks.v1", "project.resolve.v1", CapSessionHandoff, CapWorktreeWatch, CapPaneSearch, CapPaneMonitor, CapWorktreeMove, CapProjectBundle, CapFSFiles, CapFSRead, CapFSTransfer, CapFSSSH, CapPaneSSH, CapBranchRebase, CapAgentSync, CapAgentSyncUser, CapAgentLibrary, CapLibraryKeychain, CapLibraryPlain, CapCloudAgent, CapAgentPrompt, CapTaskName, CapPaneScope, CapScopeRemote, CapAgentSkill, CapAgentSkillPick, CapLibraryFetch, CapBranchGit, CapAgentTiers, CapWorktreeSetup, CapBranchCILog, CapAgentReply, CapSchedule, CapIssues, CapPermissionRules, CapTaskAfter, CapReviewComments, CapSessionStar, CapView, CapPRMerge, CapAutopilot, CapFrameCursor, CapPaneSizeLatest, CapFSFind, CapProjectLog, CapPaneRaw, CapPaneListening, CapUsageHistory, CapCommitShow, CapPRReview, CapReviewSendTo, CapBranchStage, CapReviewThread, CapFSWrite, CapProjectGroups, CapGroupTask, CapGroupTaskMerge, CapFSSearch, CapFSReplace, CapFSOps, CapFSLines, CapAgentChat, CapProjectGitInit, CapAccounts, CapAgentBackground, CapSystemStats, CapTickets, CapAgentInterrupt, CapAgentAttach, CapAutopilotIntake, CapTicketCheck, CapTicketOverview, CapAutopilotTriage, CapBranchPrune, + "agent.install.v1", "fs.v1", "shell.omz.v1", "agent.setup.v1", "worktree.files.v1", "session.v1", "agent.limits.v1", "server.reload.v1", "session.delete.v1", "session.search.v1", "session.share.v1", "agent.broadcast.v1", "agent.broadcast.shells.v1", "pane.redraw.v1", "fs.upload.v1", "branch.harvest.v1", "worktree.cleanup.v1", "branch.hunks.v1", "project.resolve.v1", CapSessionHandoff, CapWorktreeWatch, CapPaneSearch, CapPaneMonitor, CapWorktreeMove, CapProjectBundle, CapFSFiles, CapFSRead, CapFSTransfer, CapFSSSH, CapPaneSSH, CapBranchRebase, CapAgentSync, CapAgentSyncUser, CapAgentLibrary, CapLibraryKeychain, CapLibraryPlain, CapCloudAgent, CapAgentPrompt, CapTaskName, CapPaneScope, CapScopeRemote, CapAgentSkill, CapAgentSkillPick, CapLibraryFetch, CapBranchGit, CapAgentTiers, CapWorktreeSetup, CapBranchCILog, CapAgentReply, CapSchedule, CapIssues, CapPermissionRules, CapTaskAfter, CapReviewComments, CapSessionStar, CapView, CapPRMerge, CapAutopilot, CapFrameCursor, CapPaneSizeLatest, CapFSFind, CapProjectLog, CapPaneRaw, CapPaneListening, CapUsageHistory, CapCommitShow, CapPRReview, CapReviewSendTo, CapBranchStage, CapReviewThread, CapFSWrite, CapProjectGroups, CapGroupTask, CapGroupTaskMerge, CapFSSearch, CapFSReplace, CapFSOps, CapFSLines, CapAgentChat, CapProjectGitInit, CapAccounts, CapAgentBackground, CapSystemStats, CapTickets, CapAgentInterrupt, CapAgentAttach, CapAutopilotIntake, CapTicketCheck, CapTicketOverview, CapAutopilotTriage, CapBranchPrune, CapWorktreeOperation, } // The tiers an agent can be in, as agent.list reports them. They are in @@ -258,6 +258,11 @@ const CapAgentAttach = "agent.attach.v1" // or too-big, with a comment saying why. const CapAutopilotTriage = "autopilot.triage.v1" +// CapWorktreeOperation is WorktreeInfo.Operation, and a worktree mid-rebase +// carrying the branch being rebased as its Branch: git detaches HEAD until +// the rebase ends, and the agents in it showed under no branch. +const CapWorktreeOperation = "worktree.operation.v1" + // CapBranchPrune is branch.stale and branch.prune: local branches nobody // has committed to for a while, and deleting them. const CapBranchPrune = "branch.prune.v1" @@ -973,6 +978,12 @@ type WorktreeInfo struct { // servers, and Conflicts where git is older than 2.38. Overlaps []Overlap `json:"overlaps,omitempty"` Conflicts []string `json:"conflicts,omitempty"` + // Operation is what git left unfinished here: "rebase", "merge", + // "cherry-pick", "revert" or "am". Mid-rebase, Branch is the branch + // being rebased while Detached stays true, since HEAD is: a client + // shows the checkout under that branch. Absent from older servers + // (CapWorktreeOperation). + Operation string `json:"operation,omitempty"` } // Overlap is another branch's checkout touching the same files. @@ -1901,6 +1912,10 @@ type StaleWorktree struct { // Suggested means it can go without losing anything. Reasons []string `json:"reasons,omitempty"` Suggested bool `json:"suggested,omitempty"` + // Operation is what git left unfinished in it ("rebase", "merge"…), as + // in WorktreeInfo: such a worktree is never suggested, and mid-rebase + // Branch is the branch being rebased (CapWorktreeOperation). + Operation string `json:"operation,omitempty"` } // WorktreeCleanupParams removes linked worktrees, deleting their branches diff --git a/internal/server/cleanup.go b/internal/server/cleanup.go index b5897f09..45beec9b 100644 --- a/internal/server/cleanup.go +++ b/internal/server/cleanup.go @@ -44,6 +44,15 @@ func (pm *projectManager) staleWorktrees(id string) (proto.WorktreeStale, *proto if b, known := branches[wt.Branch]; known { sw.Gone, sw.Committed, sw.PR = b.Gone, b.Committed, b.PR } + if !sw.Missing { + // Mid-rebase, git has detached HEAD; the rebase still names + // the branch, and the worktree is anything but finished. + op, rebasing := gitx.Operation(ctx, wt.Path) + sw.Operation = op + if wt.Branch == "" && rebasing != "" { + sw.Branch = rebasing + } + } readable := true if !sw.Missing { sw.Panes = pm.s.panesIn(wt.Path) @@ -66,6 +75,7 @@ func (pm *projectManager) staleWorktrees(id string) (proto.WorktreeStale, *proto note("folder gone") } switch { + case sw.Operation != "": case wt.Branch == "": note("detached") case sw.Base: @@ -82,7 +92,7 @@ func (pm *projectManager) staleWorktrees(id string) (proto.WorktreeStale, *proto if sw.Gone { note("upstream deleted") } - sw.Suggested = finished && readable && !sw.Base && !sw.Locked && !sw.Panes && sw.Uncommitted == 0 && sw.Unmerged == 0 + sw.Suggested = finished && readable && sw.Operation == "" && !sw.Base && !sw.Locked && !sw.Panes && sw.Uncommitted == 0 && sw.Unmerged == 0 out.Worktrees = append(out.Worktrees, sw) } return out, nil @@ -136,6 +146,10 @@ func (pm *projectManager) cleanupWorktrees(cp proto.WorktreeCleanupParams) (prot fail(item.Path, "panes are still running in it") continue } + if op := gitx.InProgress(ctx, wt.Path); op != "" && !item.Force { + fail(item.Path, "a %s is in progress in it; finish or abort it first", op) + continue + } branch := wt.Branch if branch == base { branch = "" // the base branch stays @@ -262,6 +276,11 @@ func checkedOutBranches(ctx context.Context, root string) (map[string]string, *p for _, wt := range wts { if wt.Branch != "" { at[wt.Branch] = wt.Path + } else if wt.Detached && !wt.Prunable { + // A branch being rebased is as checked out as any other. + if b := gitx.RebasingBranch(ctx, wt.Path); b != "" { + at[b] = wt.Path + } } } return at, nil diff --git a/internal/server/cleanup_test.go b/internal/server/cleanup_test.go index f76c11b8..31000a57 100644 --- a/internal/server/cleanup_test.go +++ b/internal/server/cleanup_test.go @@ -176,3 +176,51 @@ func TestWorktreeCleanupKeepsTheBaseBranch(t *testing.T) { t.Fatal(err) } } + +// A worktree mid-rebase has HEAD detached by git, and once looked like any +// detached worktree: suggested for cleanup, its branch offered to prune. +// It is neither, and its branch is the one being rebased (#230). +func TestCleanupLeavesARebaseAlone(t *testing.T) { + c, proj, _, feat, _ := harvestFixture(t) + id := proj.ID + os.WriteFile(filepath.Join(feat, "f.txt"), []byte("f\n"), 0o644) + git(t, feat, "add", "f.txt") + git(t, feat, "commit", "-q", "-m", "feat work") + git(t, feat, "push", "-q", "-u", "origin", "feat") // so deleting it would lose nothing + // Stopped by a failing exec, with nothing uncommitted. + cmd := exec.Command("git", "-C", feat, "rebase", "--force-rebase", "-x", "false", "main") + cmd.Env = append(os.Environ(), "GIT_CONFIG_GLOBAL=/dev/null", "GIT_CONFIG_NOSYSTEM=1") + if out, err := cmd.CombinedOutput(); err == nil { + t.Fatalf("the rebase didn't stop:\n%s", out) + } + + var stale proto.WorktreeStale + if err := call(t, c, proto.MethodWorktreeStale, proto.ProjectRef{ID: id}, &stale); err != nil { + t.Fatal(err) + } + if len(stale.Worktrees) != 1 { + t.Fatalf("listed %+v", stale.Worktrees) + } + if w := stale.Worktrees[0]; w.Suggested || w.Operation != "rebase" || w.Branch != "feat" || len(w.Reasons) != 0 { + t.Fatalf("mid-rebase: %+v", w) + } + + var res proto.WorktreeCleanupResult + if err := call(t, c, proto.MethodWorktreeCleanup, proto.WorktreeCleanupParams{ProjectID: id, Remove: []proto.CleanupWorktree{{Path: feat}}}, &res); err != nil { + t.Fatal(err) + } + if len(res.Removed) != 0 || len(res.Failed) != 1 || !strings.Contains(res.Failed[0].Error, "a rebase is in progress") { + t.Fatalf("cleanup mid-rebase: %+v", res) + } + if _, err := os.Stat(feat); err != nil { + t.Fatalf("the worktree went: %v", err) + } + + var pruned proto.BranchPruneResult + if err := call(t, c, proto.MethodBranchPrune, proto.BranchPruneParams{ProjectID: id, Branches: []proto.PruneBranch{{Name: "feat"}}}, &pruned); err != nil { + t.Fatal(err) + } + if len(pruned.Deleted) != 0 || len(pruned.Failed) != 1 || !strings.Contains(pruned.Failed[0].Error, "checked out in") { + t.Fatalf("pruning the branch being rebased: %+v", pruned) + } +} diff --git a/internal/server/projects.go b/internal/server/projects.go index f171fabd..1d25105e 100644 --- a/internal/server/projects.go +++ b/internal/server/projects.go @@ -895,6 +895,15 @@ func (p *project) load() proto.ProjectInfo { checkedOut := map[string]string{} for _, wt := range wts { wi := proto.WorktreeInfo{Path: wt.Path, Branch: wt.Branch, Head: wt.Head, Detached: wt.Detached, Main: wt.Main} + if !wt.Prunable { + // git detaches HEAD while it rebases, so the list names no + // branch; the rebase itself still does. + op, rebasing := gitx.Operation(ctx, wt.Path) + wi.Operation = op + if wt.Detached && rebasing != "" { + wi.Branch = rebasing + } + } if st, err := gitx.WorktreeStatus(ctx, wt.Path); err == nil { wi.Status = &proto.GitStatus{ Staged: st.Staged, Unstaged: st.Unstaged, Untracked: st.Untracked, Conflicts: st.Conflicts, @@ -902,8 +911,8 @@ func (p *project) load() proto.ProjectInfo { } } info.Worktrees = append(info.Worktrees, wi) - if wt.Branch != "" { - checkedOut[wt.Branch] = wt.Path + if wi.Branch != "" { + checkedOut[wi.Branch] = wt.Path } } diff --git a/internal/server/projects_test.go b/internal/server/projects_test.go index deb628e1..e6b1ccc6 100644 --- a/internal/server/projects_test.go +++ b/internal/server/projects_test.go @@ -638,6 +638,96 @@ func TestPaneBranchFollowsCheckout(t *testing.T) { branchOf("main") } +// git detaches HEAD while it rebases, so the worktree list names no +// branch until the rebase ends — and an agent working on main mid-rebase +// showed under no branch at all (#230). The rebase names its branch; a +// HEAD detached on purpose still has none. +func TestPaneBranchFollowsARebase(t *testing.T) { + c, dir := startServer(t) + repo := filepath.Join(dir, "api") + os.MkdirAll(repo, 0o755) + git(t, repo, "init", "-q", "-b", "main") + git(t, repo, "config", "user.name", "t") + git(t, repo, "config", "user.email", "t@example.com") + commitFile := func(content, msg string) { + os.WriteFile(filepath.Join(repo, "a.txt"), []byte(content), 0o644) + git(t, repo, "commit", "-q", "-am", msg) + } + os.WriteFile(filepath.Join(repo, "a.txt"), []byte("one\n"), 0o644) + git(t, repo, "add", ".") + git(t, repo, "commit", "-q", "-m", "init") + git(t, repo, "checkout", "-q", "-b", "feature") + commitFile("from feature\n", "feature edit") + git(t, repo, "checkout", "-q", "main") + commitFile("from main\n", "main edit") + + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + var info proto.PaneInfo + if err := c.Call(ctx, proto.MethodPaneCreate, proto.PaneCreateParams{ + Command: []string{"/bin/sh", "-c", "sleep 60"}, Cwd: repo, + }, &info); err != nil { + t.Fatal(err) + } + waitProject(t, c, func(p proto.ProjectInfo) bool { return p.Path == repo }) + + paneBranch := func() string { + t.Helper() + var panes proto.PaneList + if err := c.Call(ctx, proto.MethodPaneList, nil, &panes); err != nil { + t.Fatal(err) + } + for _, p := range panes.Panes { + if p.ID == info.ID { + return p.Branch + } + } + t.Fatal("pane gone") + return "" + } + + cmd := exec.Command("git", "-C", repo, "rebase", "feature") + cmd.Env = append(os.Environ(), "GIT_CONFIG_GLOBAL=/dev/null", "GIT_CONFIG_NOSYSTEM=1") + if out, err := cmd.CombinedOutput(); err == nil { + t.Fatalf("the rebase didn't stop on a conflict:\n%s", out) + } + p := waitProject(t, c, func(p proto.ProjectInfo) bool { + return len(p.Worktrees) == 1 && p.Worktrees[0].Operation == "rebase" + }) + wt := p.Worktrees[0] + if wt.Branch != "main" || !wt.Detached || wt.Status == nil || wt.Status.Conflicts != 1 { + t.Fatalf("worktree mid-rebase: %+v (status %+v)", wt, wt.Status) + } + for _, b := range p.Branches { + if b.Name == "main" && b.Worktree != repo { + t.Fatalf("main's checkout mid-rebase: %q", b.Worktree) + } + } + if got := paneBranch(); got != "main" { + t.Fatalf("pane mid-rebase is on %q, want main", got) + } + + git(t, repo, "rebase", "--abort") + p = waitProject(t, c, func(p proto.ProjectInfo) bool { + return len(p.Worktrees) == 1 && p.Worktrees[0].Operation == "" && !p.Worktrees[0].Detached + }) + if wt := p.Worktrees[0]; wt.Branch != "main" { + t.Fatalf("after the rebase: %+v", wt) + } + + // Detached on purpose: no branch, and no operation. + git(t, repo, "checkout", "-q", "--detach") + p = waitProject(t, c, func(p proto.ProjectInfo) bool { + return len(p.Worktrees) == 1 && p.Worktrees[0].Detached + }) + if wt := p.Worktrees[0]; wt.Branch != "" || wt.Operation != "" { + t.Fatalf("plain detached HEAD: %+v", wt) + } + if got := paneBranch(); got != "" { + t.Fatalf("pane on a detached HEAD is on %q", got) + } +} + // pane.redraw clears the screen conch keeps and asks the program to draw // it again, without sending it a keystroke. func TestPaneRedraw(t *testing.T) { diff --git a/internal/tui/rebasing_test.go b/internal/tui/rebasing_test.go new file mode 100644 index 00000000..bb211107 --- /dev/null +++ b/internal/tui/rebasing_test.go @@ -0,0 +1,40 @@ +package tui + +import ( + "strings" + "testing" + + "github.com/Amitgb14/conch/internal/proto" + "github.com/charmbracelet/x/ansi" +) + +// A checkout mid-rebase is on its branch's row, which says so (#230); a +// HEAD detached on purpose is still "(detached …)" and on no row. +func TestBranchRowSaysRebasing(t *testing.T) { + m, _ := a1Fixture(t, false) + proj := &m.machines[0].projects[0] + proj.Worktrees[1].Detached = true + proj.Worktrees[1].Operation = "rebase" + proj.Worktrees[1].Status = &proto.GitStatus{Files: 1, Conflicts: 1} + m.rebuild() + + _, _, _, _, right := m.branchParts(row{kind: kindBranch, machine: localMachine, projectID: "r1", branch: "feat"}) + if got := ansi.Strip(right); !strings.Contains(got, "rebasing") || !strings.Contains(got, "⚠1") { + t.Fatalf("feat's row: %q", got) + } + _, _, _, _, right = m.branchParts(row{kind: kindBranch, machine: localMachine, projectID: "r1", branch: "main"}) + if strings.Contains(ansi.Strip(right), "rebasing") { + t.Fatalf("main's row: %q", ansi.Strip(right)) + } + out := a2Plain(m.projectLines(localMachine, *proj, 120)) + if !strings.Contains(out, "feat · rebasing") || strings.Contains(out, "(detached") { + t.Fatalf("worktrees:\n%s", out) + } + + // Detached on purpose, with nothing in progress. + proj.Worktrees[1].Branch, proj.Worktrees[1].Operation, proj.Worktrees[1].Head = "", "", "0123456789" + out = a2Plain(m.projectLines(localMachine, *proj, 120)) + if !strings.Contains(out, "(detached 0123456)") || strings.Contains(out, "rebasing") { + t.Fatalf("plain detached:\n%s", out) + } +} diff --git a/internal/tui/view.go b/internal/tui/view.go index 6f59c15b..a3bc491a 100644 --- a/internal/tui/view.go +++ b/internal/tui/view.go @@ -10,6 +10,7 @@ import ( "github.com/charmbracelet/lipgloss" "github.com/charmbracelet/x/ansi" + "github.com/Amitgb14/conch/internal/gitx" "github.com/Amitgb14/conch/internal/keymap" "github.com/Amitgb14/conch/internal/proto" "github.com/Amitgb14/conch/internal/remote" @@ -394,6 +395,9 @@ func (m Model) branchParts(r row) (string, lipgloss.Style, string, lipgloss.Styl if g, style, ok := m.branchAgentGlyph(r.machine, proj.ID, r.branch); ok { parts = append(parts, style.Render(g)) } + if wt != nil && wt.Operation != "" { + parts = append(parts, styleWarn.Render(gitx.OperationWord(wt.Operation))) + } if wt != nil && wt.Status != nil { switch { case wt.Status.Conflicts > 0: @@ -1003,9 +1007,12 @@ func (m Model) projectLines(mid string, proj proto.ProjectInfo, w int) []string lines = append(lines, "", styleBold.Render("Worktrees")+styleMuted.Render(fmt.Sprintf(" %d", len(proj.Worktrees)))) for _, wt := range proj.Worktrees { name := wt.Branch - if wt.Detached { + if wt.Detached && wt.Branch == "" { name = "(detached " + wt.Head[:min(7, len(wt.Head))] + ")" } + if wt.Operation != "" { + name += " · " + gitx.OperationWord(wt.Operation) + } state := styleMuted.Render("clean") if wt.Status != nil && !wt.Status.Clean() { state = fmt.Sprintf("%s %s", diffStat(wt.Status.Added, wt.Status.Deleted), styleMuted.Render(count(wt.Status.Files, "file"))) diff --git a/macos/Sources/ConchKit/Model.swift b/macos/Sources/ConchKit/Model.swift index 45432a4e..29acef33 100644 --- a/macos/Sources/ConchKit/Model.swift +++ b/macos/Sources/ConchKit/Model.swift @@ -1209,8 +1209,20 @@ public struct BadgePart: Equatable, Sendable { } } +/// What git left unfinished, in a word beside the branch (gitx.OperationWord). +public func operationWord(_ op: String) -> String { + switch op { + case "rebase": return "rebasing" + case "merge": return "merging" + case "cherry-pick": return "cherry-picking" + case "revert": return "reverting" + case "am": return "applying patches" + default: return op + } +} + /// A branch row's badge, as the TUI's (view.go branchParts): its agents' -/// state, worst first; conflicts or uncommitted changes; its pull request +/// state, worst first; a rebase or merge in progress; conflicts or uncommitted changes; its pull request /// (merged, closed, draft, its checks); gone, or how far it is ahead of /// and behind the base (the base itself against its upstream). public func branchBadgeParts(_ b: BranchInfo, worktree w: WorktreeInfo?, isBase: Bool, agents: [AgentState]) -> [BadgePart] { @@ -1218,6 +1230,7 @@ public func branchBadgeParts(_ b: BranchInfo, worktree w: WorktreeInfo?, isBase: if agents.contains(.blocked) { out.append(BadgePart("!", .warn)) } else if agents.contains(.working) { out.append(BadgePart("⠋", .work)) } else if agents.contains(.done) { out.append(BadgePart("✓", .ok)) } + if let op = w?.operation, !op.isEmpty { out.append(BadgePart(operationWord(op), .warn)) } if let st = w?.status { if let c = st.conflicts, c > 0 { out.append(BadgePart("⚠\(c)", .err)) diff --git a/macos/Sources/ConchKit/Protocol.swift b/macos/Sources/ConchKit/Protocol.swift index 11f026b9..ae31555c 100644 --- a/macos/Sources/ConchKit/Protocol.swift +++ b/macos/Sources/ConchKit/Protocol.swift @@ -197,6 +197,10 @@ public struct WorktreeInfo: Decodable, Equatable, Sendable { /// The files merging the branch into the base would conflict in, /// tried without merging (git 2.38 and later). public var conflicts: [String]? + /// What git left unfinished here: "rebase", "merge", "cherry-pick", + /// "revert" or "am". Mid-rebase, branch is the branch being rebased, + /// though git has detached HEAD (worktree.operation.v1). + public var operation: String? public init(path: String, branch: String?, main: Bool? = nil, port: Int? = nil) { self.path = path diff --git a/macos/Tests/ConchKitTests/ConchKitTests.swift b/macos/Tests/ConchKitTests/ConchKitTests.swift index be322505..6ada23ab 100644 --- a/macos/Tests/ConchKitTests/ConchKitTests.swift +++ b/macos/Tests/ConchKitTests/ConchKitTests.swift @@ -2117,6 +2117,29 @@ private func c(_ h: String, _ parents: String...) -> LogCommit { LogCommit(hash: #expect(texts(branchBadgeParts(b("f", pr: PRInfo(number: 6, state: "OPEN", checks: "pending")), worktree: nil, isBase: false, agents: [.working])) == ["⠋", "#6●"]) #expect(texts(branchBadgeParts(b("main", baseAhead: 5, ahead: 1, behind: 2), worktree: nil, isBase: true, agents: [])) == ["⇡1⇣2"]) #expect(branchBadgeParts(b("f"), worktree: w(GitStatus(files: 0)), isBase: false, agents: [.idle]).isEmpty) + // Mid-rebase (#230): said before its conflicts. + var rebasing = w(GitStatus(files: 1, conflicts: 1)) + rebasing.operation = "rebase" + let rebasingParts = branchBadgeParts(b("main"), worktree: rebasing, isBase: true, agents: [.working]) + #expect(texts(rebasingParts) == ["⠋", "rebasing", "⚠1"]) + #expect(rebasingParts[1].tone == .warn) + rebasing.operation = "" + #expect(texts(branchBadgeParts(b("main"), worktree: rebasing, isBase: true, agents: [])) == ["⚠1"]) +} + +@Test func operationWords() { + #expect(operationWord("rebase") == "rebasing") + #expect(operationWord("cherry-pick") == "cherry-picking") + #expect(operationWord("am") == "applying patches") + #expect(operationWord("bisect") == "bisect") +} + +// An older server sends no operation; a newer one's decodes. +@Test func worktreeOperationDecodes() throws { + let old = try JSONDecoder().decode(WorktreeInfo.self, from: Data(#"{"path":"/r","branch":"main"}"#.utf8)) + #expect(old.operation == nil) + let mid = try JSONDecoder().decode(WorktreeInfo.self, from: Data(#"{"path":"/r","branch":"main","detached":true,"operation":"rebase"}"#.utf8)) + #expect(mid.operation == "rebase" && mid.branch == "main") } // A pane row says how it ended — exited, or exit N and failed in red — or diff --git a/web/src/app/docs/cli/page.mdx b/web/src/app/docs/cli/page.mdx index f15be86f..cba3291d 100644 --- a/web/src/app/docs/cli/page.mdx +++ b/web/src/app/docs/cli/page.mdx @@ -273,7 +273,7 @@ An agent [kept to its own work](#when-an-agent-runs-these-commands) may comment | Command | Description | | --- | --- | -| `conch worktree ls` | list the project's worktrees besides the main checkout, with why each looks finished and what removing it would lose | +| `conch worktree ls` | list the project's worktrees besides the main checkout, with why each looks finished and what removing it would lose; one mid-rebase says `rebasing`, under the branch being rebased, and is removed only with `-force` | | `conch worktree clean [-y] [-force] [PATH\|BRANCH...]` | remove the worktrees that look finished and lose nothing, or the ones named, deleting their branches (never the base). Without `-y` it only prints what it would remove; `-force` allows losing work | Committing single hunks is a TUI-only step: see [Finishing a task](/docs/tasks#finishing-a-task). diff --git a/web/src/app/docs/protocol/page.mdx b/web/src/app/docs/protocol/page.mdx index e456ef12..b26113c1 100644 --- a/web/src/app/docs/protocol/page.mdx +++ b/web/src/app/docs/protocol/page.mdx @@ -36,7 +36,7 @@ Over SSH the same stream runs through `conch bridge`. `hello` returns the server | Panes | `pane.list`, `pane.create`, `pane.close`, `pane.resize`, `pane.send_text`, `pane.send_keys`, `pane.send_mouse`, `pane.scroll`, `pane.read`, `pane.rename`, `pane.subscribe`, `pane.unsubscribe`, `pane.mark_seen`; `pane.search` finds text in a pane's history (capability `pane.search.v1`); `pane.monitor` watches a pane for output or silence, reported as `monitor` and `alert` in its info (capability `pane.monitor.v1`) | | Agents | `agent.report`, `agent.explain`, `agent.status`, `agent.install`, `agent.setup`, `agent.setup.sync`, `agent.limits`, `agent.broadcast`; `agent.setup.sync` with `user` gives the other agents the setup in your home rather than a checkout's, and `undo` puts it back (capability `agent.setup.sync.user.v1`); `agent.library` and `agent.library.apply` keep MCP servers and skills in conch and write them where each agent looks for them (capability `agent.library.v1`); `agent.prompt` submits one message to an agent and answers with the `turn` that will reply, refusing an agent waiting for an answer with the code `agent_blocked` — `turn` in an agent's status counts its starts of work (capability `agent.prompt.v1`); `agent.skill` installs or removes conch's skill for the agents (capability `agent.skill.v1`); `account.list`, `account.add`, `account.remove`, `account.pin` and `account.failover` keep an agent's other accounts, and `pane.create`, `task.create`, `group.task` and `session.resume` take `account` while panes, plan limits and sessions say theirs (capability `agent.accounts.v1`) | | Scoping | a pane's `created_by` names the pane it was started from, and a change asked from inside an agent's pane to a pane or project that isn't its own comes back with the code `out_of_scope` (capability `pane.scope.v1`); `pane.caller` says which pane a connection comes from and, for an agent, the name it goes by elsewhere, and `scope.act_for` holds a connection to what that agent started on this machine (capability `scope.remote.v1`) | -| Projects | `project.list`, `project.add`, `project.remove`, `project.refresh`, `project.changes`, `project.diff`, `project.log` (a project's commits across its branches and tags, with parents and refs, for a commit graph, and the repository's remotes by which a remote's branch is told from a local one; capability `project.log.v1`), `project.create`, `project.set_files`, `project.resolve` (which project and branch a directory is in; capability `project.resolve.v1`) | +| Projects | `project.list`, `project.add`, `project.remove`, `project.refresh`, `project.changes`, `project.diff`, `project.log` (a project's commits across its branches and tags, with parents and refs, for a commit graph, and the repository's remotes by which a remote's branch is told from a local one; capability `project.log.v1`), `project.create`, `project.set_files`, `project.resolve` (which project and branch a directory is in; capability `project.resolve.v1`). A worktree's `operation` says what git left unfinished there (`rebase`, `merge`…), and mid-rebase its `branch` is the branch being rebased though `detached` is set (capability `worktree.operation.v1`) | | Worktrees and tasks | `worktree.add`, `worktree.remove`, `worktree.copy_files`, `task.create`; a task's `name` names its pane (capability `task.name.v1`) | | Branches | `branch.commit`, `branch.push`, `branch.pr`, `branch.merge`, `branch.discard` (capability `branch.harvest.v1`; a commit's `patch` field needs `branch.hunks.v1`, a push's `rebase` field `branch.push.rebase.v1`, and a push the remote is ahead of comes back with the code `push_rejected`, and a rebase undone by conflicts with `rebase_conflict`); `branch.git` runs the git panel's commands in the branch's worktree and reports an unfinished rebase or merge (capability `branch.git.v1`) | | Worktree cleanup | `worktree.stale`, `worktree.cleanup` (capability `worktree.cleanup.v1`) |