fix(git): contain rewritten contribution histories (#2509)

This commit is contained in:
Carlos Florêncio
2026-08-12 08:12:53 +01:00
committed by GitHub
parent b170d205fa
commit c4b4791de6
71 changed files with 3535 additions and 350 deletions
@@ -498,24 +498,27 @@ func (c *Client) GetCumulativeDiff(ctx context.Context, baseCommit, targetBranch
// GitStatusResult represents the result of a git status query.
type GitStatusResult struct {
Success bool `json:"success"`
IsSubmodule bool `json:"is_submodule,omitempty"`
Branch string `json:"branch"`
RemoteBranch string `json:"remote_branch"`
HeadCommit string `json:"head_commit"`
BaseCommit string `json:"base_commit"` // Merge-base with origin branch
Ahead int `json:"ahead"`
Behind int `json:"behind"`
Modified []string `json:"modified"`
Added []string `json:"added"`
Deleted []string `json:"deleted"`
Untracked []string `json:"untracked"`
Renamed []string `json:"renamed"`
Files map[string]interface{} `json:"files"`
Timestamp string `json:"timestamp"`
BranchAdditions int `json:"branch_additions,omitempty"`
BranchDeletions int `json:"branch_deletions,omitempty"`
Error string `json:"error,omitempty"`
Success bool `json:"success"`
IsSubmodule bool `json:"is_submodule,omitempty"`
Branch string `json:"branch"`
RemoteBranch string `json:"remote_branch"`
HeadCommit string `json:"head_commit"`
BaseCommit string `json:"base_commit"` // Merge-base with origin branch
Ahead int `json:"ahead"`
Behind int `json:"behind"`
RemoteAhead int `json:"remote_ahead"`
RemoteBehind int `json:"remote_behind"`
RemoteHeadCommit string `json:"remote_head_commit,omitempty"`
Modified []string `json:"modified"`
Added []string `json:"added"`
Deleted []string `json:"deleted"`
Untracked []string `json:"untracked"`
Renamed []string `json:"renamed"`
Files map[string]interface{} `json:"files"`
Timestamp string `json:"timestamp"`
BranchAdditions int `json:"branch_additions,omitempty"`
BranchDeletions int `json:"branch_deletions,omitempty"`
Error string `json:"error,omitempty"`
}
// fetchJSONResult performs a GET against `path` and decodes the response into
@@ -611,7 +611,8 @@ const gitStatusBody = `{
"success":true,"is_submodule":true,
"branch":"feature/x","remote_branch":"origin/feature/x",
"head_commit":"head1","base_commit":"base1",
"ahead":3,"behind":1,
"ahead":3,"behind":1,"remote_ahead":4,"remote_behind":2,
"remote_head_commit":"remote1",
"modified":["m.go"],"added":["a.go"],"deleted":["d.go"],
"untracked":["u.go"],"renamed":["r.go"],
"files":{"m.go":{"status":"M"}},
@@ -633,6 +634,10 @@ func assertFullGitStatus(t *testing.T, result *GitStatusResult) {
if result.Ahead != 3 || result.Behind != 1 {
t.Errorf("ahead/behind = %d / %d, want 3 / 1", result.Ahead, result.Behind)
}
if result.RemoteAhead != 4 || result.RemoteBehind != 2 || result.RemoteHeadCommit != "remote1" {
t.Errorf("remote ancestry = %d / %d / %q, want 4 / 2 / remote1",
result.RemoteAhead, result.RemoteBehind, result.RemoteHeadCommit)
}
for name, got := range map[string][]string{
"modified": result.Modified,
"added": result.Added,
@@ -291,11 +291,12 @@ type GitStatusData struct {
// (@{upstream}), unlike Ahead/Behind which are relative to the base
// branch and never reach zero just because the branch was pushed. Push
// detection (event_handlers_git.go) reads RemoteAhead, not Ahead.
RemoteAhead int `json:"remote_ahead"`
RemoteBehind int `json:"remote_behind"`
Files interface{} `json:"files,omitempty"`
BranchAdditions int `json:"branch_additions,omitempty"`
BranchDeletions int `json:"branch_deletions,omitempty"`
RemoteAhead int `json:"remote_ahead"`
RemoteBehind int `json:"remote_behind"`
RemoteHeadCommit string `json:"remote_head_commit,omitempty"`
Files interface{} `json:"files,omitempty"`
BranchAdditions int `json:"branch_additions,omitempty"`
BranchDeletions int `json:"branch_deletions,omitempty"`
// RepositoryName identifies which repository this status belongs to in
// multi-repo task workspaces. Empty for single-repo. Carried through to
// the frontend so the Changes panel can render per-repo group headers.
@@ -289,24 +289,25 @@ func (p *EventPublisher) PublishGitStatus(execution *AgentExecution, update *age
AgentID: execution.ID,
Timestamp: update.Timestamp.Format(time.RFC3339Nano),
Status: &GitStatusData{
Branch: update.Branch,
RemoteBranch: update.RemoteBranch,
HeadCommit: update.HeadCommit,
BaseCommit: update.BaseCommit,
Modified: update.Modified,
Added: update.Added,
Deleted: update.Deleted,
Untracked: update.Untracked,
Renamed: update.Renamed,
Ahead: update.Ahead,
Behind: update.Behind,
RemoteAhead: update.RemoteAhead,
RemoteBehind: update.RemoteBehind,
Files: update.Files,
BranchAdditions: update.BranchAdditions,
BranchDeletions: update.BranchDeletions,
RepositoryName: update.RepositoryName,
IsSubmodule: update.IsSubmodule,
Branch: update.Branch,
RemoteBranch: update.RemoteBranch,
HeadCommit: update.HeadCommit,
BaseCommit: update.BaseCommit,
Modified: update.Modified,
Added: update.Added,
Deleted: update.Deleted,
Untracked: update.Untracked,
Renamed: update.Renamed,
Ahead: update.Ahead,
Behind: update.Behind,
RemoteAhead: update.RemoteAhead,
RemoteBehind: update.RemoteBehind,
RemoteHeadCommit: update.RemoteHeadCommit,
Files: update.Files,
BranchAdditions: update.BranchAdditions,
BranchDeletions: update.BranchDeletions,
RepositoryName: update.RepositoryName,
IsSubmodule: update.IsSubmodule,
},
})
}
@@ -37,12 +37,18 @@ func TestPublishGitStatus_PropagatesRepositoryName(t *testing.T) {
SessionID: "sess-multi",
}
pub.PublishGitStatus(exec, &agentctl.GitStatusUpdate{
Timestamp: time.Now(),
RepositoryName: "frontend",
IsSubmodule: true,
Branch: "feature/x",
Modified: []string{"src/app.tsx"},
Files: map[string]agentctl.FileInfo{"src/app.tsx": {Path: "src/app.tsx"}},
Timestamp: time.Now(),
RepositoryName: "frontend",
IsSubmodule: true,
Branch: "feature/x",
HeadCommit: "local-head",
BaseCommit: "base-head",
RemoteBranch: "contributor/feature/x",
RemoteHeadCommit: "upstream-head",
RemoteAhead: 2,
RemoteBehind: 1,
Modified: []string{"src/app.tsx"},
Files: map[string]agentctl.FileInfo{"src/app.tsx": {Path: "src/app.tsx"}},
})
select {
@@ -60,6 +66,12 @@ func TestPublishGitStatus_PropagatesRepositoryName(t *testing.T) {
if !payload.Status.IsSubmodule {
t.Error("is_submodule was dropped")
}
if payload.Status.HeadCommit != "local-head" || payload.Status.BaseCommit != "base-head" {
t.Errorf("commit comparison SHAs were dropped: head=%q base=%q", payload.Status.HeadCommit, payload.Status.BaseCommit)
}
if payload.Status.RemoteHeadCommit != "upstream-head" || payload.Status.RemoteAhead != 2 || payload.Status.RemoteBehind != 1 {
t.Errorf("upstream evidence was dropped: head=%q ahead=%d behind=%d", payload.Status.RemoteHeadCommit, payload.Status.RemoteAhead, payload.Status.RemoteBehind)
}
case <-time.After(2 * time.Second):
t.Fatal("timed out waiting for git status event")
}
@@ -1246,24 +1246,27 @@ func mergeCumulativeFiles(dst, src map[string]interface{}, repo, baseRef string,
// GitStatusResult represents the result of a git status query.
type GitStatusResult struct {
Success bool `json:"success"`
IsSubmodule bool `json:"is_submodule,omitempty"`
Branch string `json:"branch"`
RemoteBranch string `json:"remote_branch"`
HeadCommit string `json:"head_commit"`
BaseCommit string `json:"base_commit"` // Merge-base with origin branch
Ahead int `json:"ahead"`
Behind int `json:"behind"`
Modified []string `json:"modified"`
Added []string `json:"added"`
Deleted []string `json:"deleted"`
Untracked []string `json:"untracked"`
Renamed []string `json:"renamed"`
Files map[string]interface{} `json:"files"`
Timestamp string `json:"timestamp"`
BranchAdditions int `json:"branch_additions,omitempty"`
BranchDeletions int `json:"branch_deletions,omitempty"`
Error string `json:"error,omitempty"`
Success bool `json:"success"`
IsSubmodule bool `json:"is_submodule,omitempty"`
Branch string `json:"branch"`
RemoteBranch string `json:"remote_branch"`
HeadCommit string `json:"head_commit"`
BaseCommit string `json:"base_commit"` // Merge-base with origin branch
Ahead int `json:"ahead"`
Behind int `json:"behind"`
RemoteAhead int `json:"remote_ahead"`
RemoteBehind int `json:"remote_behind"`
RemoteHeadCommit string `json:"remote_head_commit,omitempty"`
Modified []string `json:"modified"`
Added []string `json:"added"`
Deleted []string `json:"deleted"`
Untracked []string `json:"untracked"`
Renamed []string `json:"renamed"`
Files map[string]interface{} `json:"files"`
Timestamp string `json:"timestamp"`
BranchAdditions int `json:"branch_additions,omitempty"`
BranchDeletions int `json:"branch_deletions,omitempty"`
Error string `json:"error,omitempty"`
}
// PerRepoGitStatus pairs a repository_name with its current status. Used by
@@ -1357,23 +1360,26 @@ func (s *Server) collectStatusForRepo(ctx context.Context, sub string, fresh boo
return PerRepoGitStatus{
RepositoryName: sub,
Status: GitStatusResult{
Success: true,
IsSubmodule: status.IsSubmodule,
Branch: status.Branch,
RemoteBranch: status.RemoteBranch,
HeadCommit: status.HeadCommit,
BaseCommit: status.BaseCommit,
Ahead: status.Ahead,
Behind: status.Behind,
Modified: status.Modified,
Added: status.Added,
Deleted: status.Deleted,
Untracked: status.Untracked,
Renamed: status.Renamed,
Files: filesMap,
Timestamp: status.Timestamp.Format("2006-01-02T15:04:05.000Z07:00"),
BranchAdditions: status.BranchAdditions,
BranchDeletions: status.BranchDeletions,
Success: true,
IsSubmodule: status.IsSubmodule,
Branch: status.Branch,
RemoteBranch: status.RemoteBranch,
HeadCommit: status.HeadCommit,
BaseCommit: status.BaseCommit,
Ahead: status.Ahead,
Behind: status.Behind,
RemoteAhead: status.RemoteAhead,
RemoteBehind: status.RemoteBehind,
RemoteHeadCommit: status.RemoteHeadCommit,
Modified: status.Modified,
Added: status.Added,
Deleted: status.Deleted,
Untracked: status.Untracked,
Renamed: status.Renamed,
Files: filesMap,
Timestamp: status.Timestamp.Format("2006-01-02T15:04:05.000Z07:00"),
BranchAdditions: status.BranchAdditions,
BranchDeletions: status.BranchDeletions,
},
}
}
@@ -1416,23 +1422,26 @@ func (s *Server) handleGitStatus(c *gin.Context) {
}
c.JSON(http.StatusOK, GitStatusResult{
Success: true,
IsSubmodule: status.IsSubmodule,
Branch: status.Branch,
RemoteBranch: status.RemoteBranch,
HeadCommit: status.HeadCommit,
BaseCommit: status.BaseCommit,
Ahead: status.Ahead,
Behind: status.Behind,
Modified: status.Modified,
Added: status.Added,
Deleted: status.Deleted,
Untracked: status.Untracked,
Renamed: status.Renamed,
Files: filesMap,
Timestamp: status.Timestamp.Format("2006-01-02T15:04:05.000Z07:00"),
BranchAdditions: status.BranchAdditions,
BranchDeletions: status.BranchDeletions,
Success: true,
IsSubmodule: status.IsSubmodule,
Branch: status.Branch,
RemoteBranch: status.RemoteBranch,
HeadCommit: status.HeadCommit,
BaseCommit: status.BaseCommit,
Ahead: status.Ahead,
Behind: status.Behind,
RemoteAhead: status.RemoteAhead,
RemoteBehind: status.RemoteBehind,
RemoteHeadCommit: status.RemoteHeadCommit,
Modified: status.Modified,
Added: status.Added,
Deleted: status.Deleted,
Untracked: status.Untracked,
Renamed: status.Renamed,
Files: filesMap,
Timestamp: status.Timestamp.Format("2006-01-02T15:04:05.000Z07:00"),
BranchAdditions: status.BranchAdditions,
BranchDeletions: status.BranchDeletions,
})
}
@@ -467,21 +467,41 @@ func (wt *WorkspaceTracker) getAheadBehindCounts(ctx context.Context, update *ty
// (which would look like "just pushed" to a push-detection consumer).
func (wt *WorkspaceTracker) getRemoteAheadBehindCounts(ctx context.Context, update *types.GitStatusUpdate, prior types.GitStatusUpdate) {
if update.RemoteBranch == "" {
update.RemoteHeadCommit = ""
update.RemoteAhead = 0
update.RemoteBehind = 0
return
}
countOut, err := wt.runGitOutput(ctx, "rev-list", "--left-right", "--count", "HEAD..."+update.RemoteBranch)
// RemoteBranch came from Git, but keep the same inline ref boundary as the
// other status comparisons before using it in a command argument.
rest, hasOriginPrefix := strings.CutPrefix(update.RemoteBranch, "origin/")
check := update.RemoteBranch
if hasOriginPrefix {
check = rest
}
if !safeBranchRefPattern.MatchString(check) || strings.Contains(check, "..") || strings.HasSuffix(check, ".lock") {
carryRemoteSnapshot(update, prior)
return
}
remoteHeadOut, err := wt.runGitOutput(ctx, "rev-parse", "--verify", update.RemoteBranch+"^{commit}")
if err != nil {
wt.logger.Debug("getRemoteAheadBehindCounts: rev-parse failed, carrying forward", zap.Error(err))
carryRemoteSnapshot(update, prior)
return
}
remoteHead := strings.TrimSpace(string(remoteHeadOut))
countOut, err := wt.runGitOutput(ctx, "rev-list", "--left-right", "--count", "HEAD..."+remoteHead)
if err != nil {
wt.logger.Debug("getRemoteAheadBehindCounts: rev-list failed, carrying forward", zap.Error(err))
carryRemoteAheadBehind(update, prior)
carryRemoteSnapshot(update, prior)
return
}
parts := strings.Fields(string(countOut))
if len(parts) != 2 {
carryRemoteAheadBehind(update, prior)
carryRemoteSnapshot(update, prior)
return
}
update.RemoteHeadCommit = remoteHead
update.RemoteAhead, _ = strconv.Atoi(parts[0])
update.RemoteBehind, _ = strconv.Atoi(parts[1])
}
@@ -693,6 +713,25 @@ func carryRemoteAheadBehind(update *types.GitStatusUpdate, prior types.GitStatus
update.RemoteBehind = prior.RemoteBehind
}
// carryRemoteSnapshot keeps the upstream tip and divergence counts coherent
// when one of the secondary upstream observations fails. A changed local HEAD
// or tracking ref makes the previous snapshot unsafe, so the caller keeps the
// zero-value unknown state instead.
func carryRemoteSnapshot(update *types.GitStatusUpdate, prior types.GitStatusUpdate) {
update.RemoteHeadCommit = ""
update.RemoteAhead = 0
update.RemoteBehind = 0
if prior.HeadCommit == "" || prior.HeadCommit != update.HeadCommit {
return
}
if prior.RemoteBranch == "" || prior.RemoteBranch != update.RemoteBranch || prior.RemoteHeadCommit == "" {
return
}
update.RemoteHeadCommit = prior.RemoteHeadCommit
update.RemoteAhead = prior.RemoteAhead
update.RemoteBehind = prior.RemoteBehind
}
// parseGitStatusOutput runs git status --porcelain and populates the file lists and map.
func (wt *WorkspaceTracker) parseGitStatusOutput(ctx context.Context, update *types.GitStatusUpdate) error {
// --untracked-files=all shows all files in untracked directories, not just
@@ -480,3 +480,71 @@ func TestCarryRemoteAheadBehind(t *testing.T) {
})
}
}
func TestCarryRemoteSnapshot(t *testing.T) {
const (
localHead = "local-head"
remoteBranch = "origin/feature"
remoteHead = "remote-head"
)
tests := []struct {
name string
prior types.GitStatusUpdate
update types.GitStatusUpdate
wantRemoteHead string
wantRemoteAhead int
wantRemoteBehind int
}{
{
name: "same local and upstream identity preserves complete snapshot",
prior: types.GitStatusUpdate{
HeadCommit: localHead,
RemoteBranch: remoteBranch,
RemoteHeadCommit: remoteHead,
RemoteAhead: 2,
RemoteBehind: 1,
},
update: types.GitStatusUpdate{HeadCommit: localHead, RemoteBranch: remoteBranch},
wantRemoteHead: remoteHead,
wantRemoteAhead: 2,
wantRemoteBehind: 1,
},
{
name: "changed local head drops snapshot",
prior: types.GitStatusUpdate{
HeadCommit: localHead,
RemoteBranch: remoteBranch,
RemoteHeadCommit: remoteHead,
RemoteAhead: 2,
RemoteBehind: 1,
},
update: types.GitStatusUpdate{
HeadCommit: "new-local-head",
RemoteBranch: remoteBranch,
},
},
{
name: "changed upstream identity drops snapshot",
prior: types.GitStatusUpdate{
HeadCommit: localHead,
RemoteBranch: remoteBranch,
RemoteHeadCommit: remoteHead,
RemoteAhead: 2,
RemoteBehind: 1,
},
update: types.GitStatusUpdate{
HeadCommit: localHead,
RemoteBranch: "origin/other",
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
update := tt.update
carryRemoteSnapshot(&update, tt.prior)
if update.RemoteHeadCommit != tt.wantRemoteHead || update.RemoteAhead != tt.wantRemoteAhead || update.RemoteBehind != tt.wantRemoteBehind {
t.Fatalf("remote snapshot = %q/%d/%d, want %q/%d/%d", update.RemoteHeadCommit, update.RemoteAhead, update.RemoteBehind, tt.wantRemoteHead, tt.wantRemoteAhead, tt.wantRemoteBehind)
}
})
}
}
@@ -3,6 +3,7 @@ package process
import (
"context"
"encoding/base64"
"encoding/json"
"os"
"os/exec"
"path/filepath"
@@ -279,6 +280,94 @@ func TestGetGitStatus_AheadBehindWithoutUpstream(t *testing.T) {
}
}
func TestGetGitStatus_ReportsUpstreamHeadForHistoryStates(t *testing.T) {
repoDir, cleanup := setupTestRepo(t)
defer cleanup()
log := newTestLogger(t)
wt := NewWorkspaceTracker(repoDir, log)
ctx := context.Background()
runGit(t, repoDir, "checkout", "-b", "feature/pr")
runGit(t, repoDir, "push", "-u", "origin", "feature/pr")
pushedHead := strings.TrimSpace(runGit(t, repoDir, "rev-parse", "HEAD"))
status, err := wt.getGitStatus(ctx)
if err != nil {
t.Fatalf("getGitStatus (aligned): %v", err)
}
if got := remoteHeadFromWire(t, status); got != pushedHead {
t.Fatalf("remote_head_commit (aligned) = %q, want %q", got, pushedHead)
}
writeFile(t, repoDir, "local.txt", "local")
runGit(t, repoDir, "add", ".")
runGit(t, repoDir, "commit", "-m", "local contribution")
status, err = wt.getGitStatus(ctx)
if err != nil {
t.Fatalf("getGitStatus (local ahead): %v", err)
}
if got := remoteHeadFromWire(t, status); got != pushedHead {
t.Fatalf("remote_head_commit (local ahead) = %q, want %q", got, pushedHead)
}
remoteURL := strings.TrimSpace(runGit(t, repoDir, "remote", "get-url", "origin"))
providerRoot := t.TempDir()
runGit(t, providerRoot, "clone", remoteURL, "provider")
providerDir := filepath.Join(providerRoot, "provider")
runGit(t, providerDir, "config", "user.email", "provider@test.com")
runGit(t, providerDir, "config", "user.name", "Provider User")
runGit(t, providerDir, "checkout", "-b", "feature/pr", "origin/feature/pr")
writeFile(t, providerDir, "provider.txt", "provider")
runGit(t, providerDir, "add", ".")
runGit(t, providerDir, "commit", "-m", "provider contribution")
providerHead := strings.TrimSpace(runGit(t, providerDir, "rev-parse", "HEAD"))
runGit(t, providerDir, "push", "origin", "HEAD:feature/pr")
runGit(t, repoDir, "fetch", "origin")
status, err = wt.getGitStatus(ctx)
if err != nil {
t.Fatalf("getGitStatus (provider ahead): %v", err)
}
if got := remoteHeadFromWire(t, status); got != providerHead {
t.Fatalf("remote_head_commit (provider ahead) = %q, want %q", got, providerHead)
}
runGit(t, providerDir, "checkout", "--orphan", "rewritten")
runGit(t, providerDir, "rm", "-rf", ".")
writeFile(t, providerDir, "rewritten.txt", "rewritten")
runGit(t, providerDir, "add", ".")
runGit(t, providerDir, "commit", "-m", "rewritten contribution")
rewrittenHead := strings.TrimSpace(runGit(t, providerDir, "rev-parse", "HEAD"))
runGit(t, providerDir, "push", "--force", "origin", "HEAD:feature/pr")
runGit(t, repoDir, "fetch", "origin")
status, err = wt.getGitStatus(ctx)
if err != nil {
t.Fatalf("getGitStatus (diverged): %v", err)
}
if got := remoteHeadFromWire(t, status); got != rewrittenHead {
t.Fatalf("remote_head_commit (diverged) = %q, want %q", got, rewrittenHead)
}
}
func remoteHeadFromWire(t *testing.T, status types.GitStatusUpdate) string {
t.Helper()
wire, err := json.Marshal(status)
if err != nil {
t.Fatalf("marshal git status: %v", err)
}
var payload map[string]any
if err := json.Unmarshal(wire, &payload); err != nil {
t.Fatalf("unmarshal git status: %v", err)
}
value, ok := payload["remote_head_commit"].(string)
if !ok {
t.Fatalf("remote_head_commit missing from git status: %s", wire)
}
return value
}
// TestGetGitStatus_AheadBehindAfterRebase verifies that ahead/behind counts
// reflect divergence from the base branch (origin/main), not the remote tracking
// branch. After a rebase, the remote tracking branch has stale SHAs, so comparing
@@ -65,6 +65,11 @@ type GitStatusUpdate struct {
// empty.
RemoteBehind int `json:"remote_behind"`
// RemoteHeadCommit is the locally observed tip of RemoteBranch. It is
// captured with RemoteAhead and RemoteBehind so consumers can compare the
// checkout with an upstream snapshot without confusing it with the base.
RemoteHeadCommit string `json:"remote_head_commit,omitempty"`
// HeadCommit is the current HEAD commit SHA.
HeadCommit string `json:"head_commit,omitempty"`
+18 -13
View File
@@ -334,19 +334,24 @@ func tryGetLiveGitStatus(ctx context.Context, lifecycleMgr *lifecycle.Manager, s
// stores it under byEnvironmentRepo[envKey][repository_name].
func buildGitStatusNotification(sessionID, repositoryName string, status client.GitStatusResult) *ws.Message {
statusPayload := map[string]interface{}{
"branch": status.Branch,
"remote_branch": status.RemoteBranch,
"ahead": status.Ahead,
"behind": status.Behind,
"files": status.Files,
"modified": status.Modified,
"added": status.Added,
"deleted": status.Deleted,
"untracked": status.Untracked,
"renamed": status.Renamed,
"branch_additions": status.BranchAdditions,
"branch_deletions": status.BranchDeletions,
"is_submodule": status.IsSubmodule,
"branch": status.Branch,
"remote_branch": status.RemoteBranch,
"head_commit": status.HeadCommit,
"base_commit": status.BaseCommit,
"ahead": status.Ahead,
"behind": status.Behind,
"remote_ahead": status.RemoteAhead,
"remote_behind": status.RemoteBehind,
"remote_head_commit": status.RemoteHeadCommit,
"files": status.Files,
"modified": status.Modified,
"added": status.Added,
"deleted": status.Deleted,
"untracked": status.Untracked,
"renamed": status.Renamed,
"branch_additions": status.BranchAdditions,
"branch_deletions": status.BranchDeletions,
"is_submodule": status.IsSubmodule,
}
if repositoryName != "" {
statusPayload["repository_name"] = repositoryName
@@ -13,6 +13,7 @@ import (
"github.com/gin-gonic/gin"
"github.com/jmoiron/sqlx"
"github.com/kandev/kandev/internal/agent/executor"
client "github.com/kandev/kandev/internal/agent/runtime/agentctl"
"github.com/kandev/kandev/internal/agent/runtime/lifecycle"
"github.com/kandev/kandev/internal/agentctl/server/process"
"github.com/kandev/kandev/internal/agentctl/types/streams"
@@ -114,6 +115,39 @@ func decodePayload(t *testing.T, raw json.RawMessage) map[string]interface{} {
return payload
}
func TestBuildGitStatusNotificationIncludesAncestryEvidence(t *testing.T) {
msg := buildGitStatusNotification("session-1", "web", client.GitStatusResult{
Branch: "feature/rewrite",
RemoteBranch: "origin/feature/rewrite",
HeadCommit: "local-head",
BaseCommit: "base-head",
Ahead: 5,
Behind: 1,
RemoteAhead: 2,
RemoteBehind: 3,
RemoteHeadCommit: "remote-head",
})
if msg == nil {
t.Fatal("buildGitStatusNotification returned nil")
}
payload := decodePayload(t, msg.Payload)
status, ok := payload["status"].(map[string]interface{})
if !ok {
t.Fatalf("status payload = %#v, want an object", payload["status"])
}
for key, want := range map[string]interface{}{
"head_commit": "local-head",
"base_commit": "base-head",
"remote_ahead": float64(2),
"remote_behind": float64(3),
"remote_head_commit": "remote-head",
} {
if got := status[key]; got != want {
t.Errorf("status[%q] = %#v, want %#v", key, got, want)
}
}
}
// TestAppendSessionStateMessage_IncludesTaskEnvironmentID asserts the snapshot
// the WS hub sends on `session.subscribe` carries `task_environment_id`.
//
+1 -1
View File
@@ -461,7 +461,7 @@ func wsGetPRCommits(svc *Service, _ *logger.Logger) func(ctx context.Context, ms
if err != nil {
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeInternalError, err.Error(), nil)
}
return ws.NewResponse(msg.ID, msg.Action, map[string]interface{}{"commits": commits})
return ws.NewResponse(msg.ID, msg.Action, commits)
}
}
+9
View File
@@ -830,6 +830,15 @@ type PRCommitInfo struct {
StatsAvailable bool `json:"stats_available"`
}
// PRCommitsResult contains the current provider head and the ancestry data
// used to classify a contribution checkout. Complete is true only when the
// provider client finished loading the full PR commit list.
type PRCommitsResult struct {
Commits []PRCommitInfo `json:"commits"`
HeadSHA string `json:"head_sha"`
Complete bool `json:"complete"`
}
// PRCommitDetail represents the metadata and changed files for one GitHub
// commit. Unlike PRCommitInfo, its statistics come from GitHub's individual
// commit endpoint and are always measured.
+9 -3
View File
@@ -570,10 +570,16 @@ func (c *PATClient) ListPRFiles(ctx context.Context, owner, repo string, number
}
func (c *PATClient) ListPRCommits(ctx context.Context, owner, repo string, number int) ([]PRCommitInfo, error) {
var raw []ghPRCommit
endpoint := fmt.Sprintf("/repos/%s/%s/pulls/%d/commits?per_page=100", owner, repo, number)
if err := c.get(ctx, endpoint, &raw); err != nil {
return nil, fmt.Errorf("list PR commits: %w", err)
var raw []ghPRCommit
for endpoint != "" {
var page []ghPRCommit
next, err := c.getPaginated(ctx, endpoint, &page)
if err != nil {
return nil, fmt.Errorf("list PR commits: %w", err)
}
raw = append(raw, page...)
endpoint = next
}
return convertRawPRCommits(raw), nil
}
@@ -424,6 +424,32 @@ func TestPATClient_ListPRCommits(t *testing.T) {
}
}
func TestPATClient_ListPRCommits_FollowsLinkHeaderPages(t *testing.T) {
c, requests := newLinkPaginatedPATServer(t, "/repos/acme/widget/pulls/42/commits", []string{
`[
{"sha":"aaa","commit":{"message":"first","author":{"date":"2026-01-07T10:00:00Z"}}},
{"sha":"bbb","commit":{"message":"second","author":{"date":"2026-01-08T10:00:00Z"}}}
]`,
`[
{"sha":"ccc","commit":{"message":"provider head","author":{"date":"2026-01-09T10:00:00Z"}}}
]`,
})
commits, err := c.ListPRCommits(context.Background(), "acme", "widget", 42)
if err != nil {
t.Fatalf("ListPRCommits: %v", err)
}
if len(commits) != 3 {
t.Fatalf("commits = %d, want all pages (3)", len(commits))
}
if commits[2].SHA != "ccc" {
t.Errorf("last commit = %q, want the second-page provider head", commits[2].SHA)
}
if len(*requests) != 2 {
t.Fatalf("requests = %d, want 2 pages", len(*requests))
}
}
func TestPATClient_ListPRCommits_Error(t *testing.T) {
c, _ := newRecordingPATServer(t, nil)
if _, err := c.ListPRCommits(context.Background(), "acme", "widget", 42); err == nil ||
+37 -4
View File
@@ -546,17 +546,50 @@ func (s *Service) GetPRCommits(ctx context.Context, owner, repo string, number i
return s.client.ListPRCommits(ctx, owner, repo, number)
}
// GitHub's pull-request commit endpoint returns at most 250 commits, even
// when pagination has been requested. Treat a response at that limit as
// incomplete because the missing older ancestry can change a safe relation
// into an apparent divergence.
const githubPRCommitHistoryLimit = 250
func completePRCommitHistory(headSHA string, commits []PRCommitInfo) bool {
if headSHA == "" || len(commits) == 0 || len(commits) >= githubPRCommitHistoryLimit {
return false
}
for _, commit := range commits {
if commit.SHA == "" {
return false
}
}
return commits[len(commits)-1].SHA == headSHA
}
func (s *Service) GetPRCommitsForWorkspace(
ctx context.Context, workspaceID, userID, owner, repo string, number int,
) ([]PRCommitInfo, error) {
) (PRCommitsResult, error) {
if err := s.ensureRepositoryInWorkspaceScope(ctx, workspaceID, owner, repo); err != nil {
return nil, err
return PRCommitsResult{}, err
}
resolved, err := s.resolvePersonalReadClient(ctx, workspaceID, userID, owner, repo)
if err != nil {
return nil, err
return PRCommitsResult{}, err
}
return resolved.Client.ListPRCommits(ctx, owner, repo, number)
pr, err := resolved.Client.GetPR(ctx, owner, repo, number)
if err != nil {
return PRCommitsResult{}, fmt.Errorf("get PR #%d for commit history: %w", number, err)
}
if pr == nil {
return PRCommitsResult{}, fmt.Errorf("get PR #%d for commit history: empty response", number)
}
commits, err := resolved.Client.ListPRCommits(ctx, owner, repo, number)
if err != nil {
return PRCommitsResult{}, fmt.Errorf("list PR #%d commits: %w", number, err)
}
return PRCommitsResult{
Commits: commits,
HeadSHA: pr.HeadSHA,
Complete: completePRCommitHistory(pr.HeadSHA, commits),
}, nil
}
// GetPRCommitDetailForWorkspace fetches one commit through the workspace's
@@ -0,0 +1,42 @@
package github
import (
"fmt"
"testing"
)
func TestCompletePRCommitHistoryRequiresACompleteProviderSnapshot(t *testing.T) {
complete := make([]PRCommitInfo, githubPRCommitHistoryLimit-1)
for index := range complete {
complete[index] = PRCommitInfo{SHA: fmt.Sprintf("commit-%d", index)}
}
complete[len(complete)-1] = PRCommitInfo{SHA: "provider-head"}
truncated := make([]PRCommitInfo, githubPRCommitHistoryLimit)
for index := range truncated {
truncated[index] = PRCommitInfo{SHA: fmt.Sprintf("commit-%d", index)}
}
truncated[len(truncated)-1] = PRCommitInfo{SHA: "provider-head"}
tests := []struct {
name string
head string
commits []PRCommitInfo
want bool
}{
{name: "head terminates a paginated history", head: "provider-head", commits: complete, want: true},
{name: "head is missing from the returned history", head: "provider-head", commits: []PRCommitInfo{{SHA: "older"}}, want: false},
{name: "head does not terminate the returned history", head: "provider-head", commits: []PRCommitInfo{{SHA: "provider-head"}, {SHA: "newer"}}, want: false},
{name: "empty history is incomplete", head: "provider-head", commits: nil, want: false},
{name: "provider head is empty", head: "", commits: complete, want: false},
{name: "provider endpoint cap is incomplete", head: "provider-head", commits: truncated, want: false},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
if got := completePRCommitHistory(test.head, test.commits); got != test.want {
t.Fatalf("completePRCommitHistory() = %v, want %v", got, test.want)
}
})
}
}
+131 -19
View File
@@ -8,7 +8,11 @@ import {
ReviewProgressBar,
PRFilesSection,
} from "./changes-panel-timeline";
import { mergeCommits, firstVisibleSection } from "./changes-panel-helpers";
import {
firstVisibleSection,
mergeCommits,
separateCommitHistories,
} from "./changes-panel-helpers";
import type { ChangesPanelBodyProps } from "./changes-panel-data";
import { useTranslation } from "react-i18next";
@@ -51,6 +55,11 @@ type TimelineProps = Pick<
| "hasStaged"
| "hasCommits"
| "hasPRFiles"
| "relation"
| "providerCommitsLoading"
| "providerCommitsError"
| "pushDisabled"
| "pullDisabled"
| "canPush"
| "canCreatePR"
| "existingPrUrl"
@@ -165,18 +174,108 @@ function WorkingTreeSections(props: WorkingTreeProps) {
);
}
function ChangesPanelTimeline(props: TimelineProps) {
function CommitHistorySections({
props,
isDiverged,
defaultCollapsed,
mergedCommits,
separated,
}: {
props: TimelineProps;
isDiverged: boolean;
defaultCollapsed: boolean;
mergedCommits: ReturnType<typeof mergeCommits>;
separated: ReturnType<typeof separateCommitHistories>;
}) {
const { t } = useTranslation();
if (!props.hasAnything) {
if (isDiverged) {
return (
<div className="flex items-center justify-center h-full text-muted-foreground text-xs">
{t("task:yourChangedFilesWillAppearHere")}
</div>
<>
{separated.providerCommits.length > 0 && (
<CommitsSection
commits={separated.providerCommits}
label={t("task:currentPRCommits")}
testId="current-pr-commits-section"
defaultCollapsed={defaultCollapsed}
showActions={false}
onOpenCommitDetail={props.onOpenCommitDetail}
repoDisplayName={props.repoDisplayName}
perRepoStatus={props.perRepoStatus}
/>
)}
{separated.localCommits.length > 0 && (
<CommitsSection
commits={separated.localCommits}
label={t("task:localCheckoutCommits")}
testId="local-checkout-commits-section"
defaultCollapsed={defaultCollapsed}
pushDisabled={props.pushDisabled}
onOpenCommitDetail={props.onOpenCommitDetail}
onRevertCommit={props.onRevertCommit}
onAmendCommit={props.dialogs.handleOpenAmendDialog}
onResetToCommit={props.dialogs.handleOpenResetDialog}
onRepoPush={props.onRepoPush}
onRepoCreatePR={props.onRepoCreatePR}
repoDisplayName={props.repoDisplayName}
perRepoStatus={props.perRepoStatus}
prByRepo={props.prByRepo}
/>
)}
</>
);
}
const mergedCommits = mergeCommits(props.commits, props.prCommits);
const hasMergedCommits = mergedCommits.length > 0;
return (
<CommitsSection
commits={mergedCommits}
defaultCollapsed={defaultCollapsed}
onOpenCommitDetail={props.onOpenCommitDetail}
onRevertCommit={props.onRevertCommit}
onAmendCommit={props.dialogs.handleOpenAmendDialog}
onResetToCommit={props.dialogs.handleOpenResetDialog}
onRepoPush={props.onRepoPush}
onRepoCreatePR={props.onRepoCreatePR}
repoDisplayName={props.repoDisplayName}
perRepoStatus={props.perRepoStatus}
prByRepo={props.prByRepo}
pushDisabled={props.pushDisabled}
/>
);
}
function EmptyChangesPanel({ providerCommitsError }: { providerCommitsError: string | null }) {
const { t } = useTranslation();
if (providerCommitsError) {
return (
<div
className="flex items-center justify-center h-full px-3 text-center text-muted-foreground text-xs"
data-testid="provider-history-error"
>
{t("task:providerHistoryUnavailable")}
</div>
);
}
return (
<div className="flex items-center justify-center h-full text-muted-foreground text-xs">
{t("task:yourChangedFilesWillAppearHere")}
</div>
);
}
function ChangesPanelTimeline(props: TimelineProps) {
const { t } = useTranslation();
if (!props.hasAnything) {
return <EmptyChangesPanel providerCommitsError={props.providerCommitsError} />;
}
const isDiverged = props.relation.presentation === "separate";
const separated = isDiverged
? separateCommitHistories(props.commits, props.prCommits)
: { providerCommits: [], localCommits: [] };
const mergedCommits = isDiverged ? [] : mergeCommits(props.commits, props.prCommits);
const hasMergedCommits = isDiverged
? separated.providerCommits.length > 0 || separated.localCommits.length > 0
: mergedCommits.length > 0;
const hasLocalChanges = props.hasUnstaged || props.hasStaged;
const showCommitsList = props.hasStaged || hasMergedCommits;
// Auto-expand the first (topmost) visible section so the panel never opens
@@ -216,19 +315,32 @@ function ChangesPanelTimeline(props: TimelineProps) {
</div>
)}
{props.providerCommitsError && (
<div
className="mx-1 mb-2 rounded-md border border-yellow-500/30 bg-yellow-500/10 px-2 py-1.5 text-xs text-yellow-700 dark:text-yellow-300"
data-testid="provider-history-error"
>
{t("task:providerHistoryUnavailable")}
</div>
)}
{isDiverged && (
<div
className="mx-1 mb-2 rounded-md border border-yellow-500/40 bg-yellow-500/10 px-2 py-1.5 text-xs text-yellow-700 dark:text-yellow-300"
data-testid="remote-contribution-drift-warning"
role="status"
>
{t("task:remoteContributionHistoryChanged")}
</div>
)}
{showCommitsList && (
<CommitsSection
commits={mergedCommits}
<CommitHistorySections
props={props}
isDiverged={isDiverged}
defaultCollapsed={firstSection !== "commits"}
onOpenCommitDetail={props.onOpenCommitDetail}
onRevertCommit={props.onRevertCommit}
onAmendCommit={props.dialogs.handleOpenAmendDialog}
onResetToCommit={props.dialogs.handleOpenResetDialog}
onRepoPush={props.onRepoPush}
onRepoCreatePR={props.onRepoCreatePR}
repoDisplayName={props.repoDisplayName}
perRepoStatus={props.perRepoStatus}
prByRepo={props.prByRepo}
mergedCommits={mergedCommits}
separated={separated}
/>
)}
</div>
+34 -11
View File
@@ -11,12 +11,14 @@ import type { PRChangedFile } from "./changes-panel-timeline";
import { useChangesGitHandlers, useChangesDialogHandlers } from "./changes-panel-hooks";
import { useRepoDisplayName } from "@/hooks/domains/session/use-repo-display-name";
import { useBaseBranchByRepo } from "@/hooks/domains/session/use-base-branch-by-repo";
import { useReviewPRSelection } from "@/hooks/domains/github/use-review-pr-selection";
import {
useRemoteContributionRelation,
type RemoteContributionRelationState,
} from "@/hooks/domains/session/use-remote-contribution-relation";
import {
prFetchKey,
useActiveTaskPRsWithFiles,
} from "@/hooks/domains/github/use-active-task-pr-files";
import { usePRCommits } from "@/hooks/domains/github/use-pr-commits";
import { usePRReviewRepositoryIdentity } from "@/hooks/domains/github/use-pr-review-repository-identity";
import {
getCumulativeReviewRepositoryNames,
@@ -41,6 +43,8 @@ import {
import type { CommitDetailTarget, OpenDiffOptions } from "./changes-diff-target";
import type { PRDiffFile, TaskPR } from "@/lib/types/github";
import { getGitCredentialDisplay } from "./changes-git-credential-display";
import type { RemoteContributionRelation } from "@/hooks/domains/session/remote-contribution-relation";
import { remoteContributionActionPolicy } from "@/hooks/domains/session/remote-contribution-relation";
function useChangesPanelStoreData() {
const activeTaskId = useAppStore((state) => state.tasks.activeTaskId);
@@ -90,6 +94,11 @@ export type ChangesPanelBodyProps = {
hasCommits: boolean;
hasPRFiles: boolean;
hasPRCommits: boolean;
relation: RemoteContributionRelation;
providerCommitsLoading: boolean;
providerCommitsError: string | null;
pushDisabled: boolean;
pullDisabled: boolean;
canPush: boolean;
canCreatePR: boolean;
existingPrUrl: string | undefined;
@@ -135,7 +144,12 @@ export type ChangesPanelBodyProps = {
onRepoPush?: (repo: string) => void;
onRepoCreatePR?: (repo: string) => void;
repoDisplayName?: (repositoryName: string) => string | undefined;
perRepoStatus?: Array<{ repository_name: string; ahead: number }>;
perRepoStatus?: Array<{
repository_name: string;
ahead: number;
pushAhead: number;
pullBehind: number;
}>;
prByRepo?: Record<string, string | undefined>;
};
@@ -251,7 +265,8 @@ function useChangesPanelPRData(repositoryNames: string[], sessionId: string | nu
const { prs, filesByPRKey } = useActiveTaskPRsWithFiles();
const activeTaskId = useAppStore((state) => state.tasks.activeTaskId);
const workspaceId = useAppStore((state) => state.workspaces.activeId);
const { selectedPR: taskPR } = useReviewPRSelection(activeTaskId);
const relationState: RemoteContributionRelationState = useRemoteContributionRelation(sessionId);
const taskPR = relationState.selectedPR;
const reposByWorkspace = useAppStore((s) => s.repositories.itemsByWorkspaceId);
const repoNameById = useMemo(() => buildRepoNameById(reposByWorkspace), [reposByWorkspace]);
const taskRepositoryCount = useAppStore((s) => {
@@ -263,13 +278,7 @@ function useChangesPanelPRData(repositoryNames: string[], sessionId: string | nu
const taskHasMultipleRepos = taskRepositoryCount > 1;
const useRepositoryKeys = isReviewMultiRepo(taskRepositoryCount, repositoryNames);
const selectedPRRepositoryName = usePRReviewRepositoryIdentity(activeTaskId, sessionId, taskPR);
const refreshKey = taskPR?.last_synced_at ?? null;
const { commits: prCommitsList } = usePRCommits(
taskPR?.owner ?? null,
taskPR?.repo ?? null,
taskPR?.pr_number ?? null,
refreshKey,
);
const prCommitsList = relationState.commits;
const prCommits = useMemo<PRCommitForMerge[]>(() => {
if (!workspaceId?.trim() || !taskPR?.owner?.trim() || !taskPR.repo?.trim()) return [];
return prCommitsList.map((commit) => ({
@@ -310,6 +319,9 @@ function useChangesPanelPRData(repositoryNames: string[], sessionId: string | nu
hasPRCommits,
prFiles,
useRepositoryKeys,
relation: relationState.relation,
providerCommitsLoading: relationState.loading,
providerCommitsError: relationState.error,
};
}
@@ -329,6 +341,10 @@ export function useChangesPanelData() {
[git.repoNames, git.cumulativeDiff],
);
const prData = useChangesPanelPRData(reviewRepositoryNames, activeSessionId);
const remoteActionPolicy = useMemo(
() => remoteContributionActionPolicy(prData.relation),
[prData.relation],
);
const vcsDialogs = useVcsDialogs();
const baseBranchDisplay = useMemo(() => getBaseBranchDisplay(baseBranch), [baseBranch]);
const unstagedFiles = useMemo(() => mapToChangedFiles(git.unstagedFiles), [git.unstagedFiles]);
@@ -387,6 +403,8 @@ export function useChangesPanelData() {
existingPrUrl,
gitCredentialDisplay,
walkthroughRequestReady,
pushDisabled: remoteActionPolicy.pushDisabled,
pullDisabled: remoteActionPolicy.pullDisabled,
...prData,
};
}
@@ -410,6 +428,11 @@ export function buildChangesPanelBodyProps(
hasCommits: git.hasCommits,
hasPRFiles: data.hasPRFiles,
hasPRCommits: data.hasPRCommits,
relation: data.relation,
providerCommitsLoading: data.providerCommitsLoading,
providerCommitsError: data.providerCommitsError,
pushDisabled: data.pushDisabled,
pullDisabled: data.pullDisabled,
canPush: git.canPush,
canCreatePR: git.canCreatePR,
existingPrUrl: data.existingPrUrl,
@@ -0,0 +1,54 @@
import { cleanup, render, screen } from "@testing-library/react";
import { afterEach, describe, expect, it, vi } from "vitest";
import { PullDropdown } from "./changes-panel-header";
vi.mock("@kandev/ui/button", () => ({
Button: ({ children, ...props }: React.ButtonHTMLAttributes<HTMLButtonElement>) => (
<button {...props}>{children}</button>
),
}));
vi.mock("@kandev/ui/dropdown-menu", () => ({
DropdownMenu: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
DropdownMenuContent: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
DropdownMenuTrigger: ({ children }: { children: React.ReactNode }) => <>{children}</>,
}));
vi.mock("@kandev/ui/tooltip", () => ({
Tooltip: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
TooltipContent: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
TooltipTrigger: ({ children }: { children: React.ReactNode }) => <>{children}</>,
}));
vi.mock("./changes-panel-per-repo-menu", () => ({
PerRepoPullMenu: () => null,
}));
afterEach(cleanup);
describe("PullDropdown remote safety", () => {
it("keeps the history-change reason reachable while Pull is disabled", () => {
render(
<PullDropdown
behindCount={0}
pullDisabled
isLoading={false}
loadingOperation={null}
repoNames={[""]}
perRepoStatus={[]}
onRepoPull={vi.fn()}
onRepoRebase={vi.fn()}
onRepoMerge={vi.fn()}
/>,
);
const pullButton = screen.getByRole("button", { name: /Pull/ });
expect(pullButton).toHaveProperty("disabled", true);
expect(pullButton.parentElement?.getAttribute("tabindex")).toBe("0");
expect(
screen.getByText(
"Push, force-push, and Pull are disabled until the histories are reconciled.",
),
).toBeTruthy();
});
});
@@ -39,6 +39,7 @@ export type PerRepoStatus = {
branch: string | null;
ahead: number;
behind: number;
pullBehind?: number;
hasStaged: boolean;
hasUnstaged: boolean;
};
@@ -335,8 +336,9 @@ function PullTriggerContent({
);
}
function PullDropdown({
export function PullDropdown({
behindCount,
pullDisabled,
isLoading,
loadingOperation,
repoNames,
@@ -347,6 +349,7 @@ function PullDropdown({
repoDisplayName,
}: {
behindCount: number;
pullDisabled?: boolean;
isLoading: boolean;
loadingOperation: string | null;
/** Always non-empty (single-repo includes the empty-name entry). */
@@ -358,6 +361,7 @@ function PullDropdown({
/** Maps a repository_name to its display label. */
repoDisplayName?: (repositoryName: string) => string | undefined;
}) {
const { t } = useTranslation();
const isPulling = loadingOperation === "pull";
const isRebasing = loadingOperation === "rebase";
// For single-repo (empty repo entry), the trigger label uses the global
@@ -365,24 +369,37 @@ function PullDropdown({
// labels and the trigger summarises with the max.
const triggerBehind =
perRepoStatus.length > 0
? Math.max(behindCount, ...perRepoStatus.map((s) => s.behind))
? Math.max(behindCount, ...perRepoStatus.map((s) => s.pullBehind ?? 0))
: behindCount;
const pullButton = (
<Button
size="sm"
variant="ghost"
className="h-5 text-[11px] px-1.5 gap-1 cursor-pointer"
disabled={isLoading || pullDisabled}
>
<PullTriggerContent
behindCount={triggerBehind}
isPulling={isPulling}
isRebasing={isRebasing}
/>
</Button>
);
if (pullDisabled) {
return (
<Tooltip>
<TooltipTrigger asChild>
<span tabIndex={0} className="inline-flex">
{pullButton}
</span>
</TooltipTrigger>
<TooltipContent>{t("task:remoteActionsDisabledHistoryChanged")}</TooltipContent>
</Tooltip>
);
}
return (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
size="sm"
variant="ghost"
className="h-5 text-[11px] px-1.5 gap-1 cursor-pointer"
disabled={isLoading}
>
<PullTriggerContent
behindCount={triggerBehind}
isPulling={isPulling}
isRebasing={isRebasing}
/>
</Button>
</DropdownMenuTrigger>
<DropdownMenuTrigger asChild>{pullButton}</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-56">
<PerRepoPullMenu
repoNames={repoNames}
@@ -390,6 +407,7 @@ function PullDropdown({
onRepoPull={onRepoPull}
onRepoRebase={onRepoRebase}
onRepoMerge={onRepoMerge}
pullDisabled={pullDisabled}
repoDisplayName={repoDisplayName}
/>
</DropdownMenuContent>
@@ -484,6 +502,7 @@ export function ChangesPanelHeader({
baseBranchDisplay,
baseBranchByRepo,
behindCount,
pullDisabled,
isLoading,
loadingOperation,
onOpenDiffAll,
@@ -509,6 +528,7 @@ export function ChangesPanelHeader({
* back to baseBranchDisplay. Empty/missing for single-repo workspaces. */
baseBranchByRepo?: Record<string, string>;
behindCount: number;
pullDisabled?: boolean;
isLoading: boolean;
loadingOperation: string | null;
onOpenDiffAll?: () => void;
@@ -562,6 +582,7 @@ export function ChangesPanelHeader({
)}
<PullDropdown
behindCount={behindCount}
pullDisabled={pullDisabled}
isLoading={isLoading}
loadingOperation={loadingOperation}
repoNames={repoNames}
@@ -11,6 +11,7 @@ import type { PRDiffFile } from "@/lib/types/github";
import { normalizeFileChangeStatus, type FileChangeStatus } from "@/lib/utils/file-change-status";
import type { PRChangedFile } from "./changes-panel-timeline";
import type { CommitDetailTarget } from "./changes-diff-target";
import type { CommitPresentation } from "./commit-row";
export type ChangedFile = {
path: string;
@@ -279,6 +280,7 @@ export type MergedCommit = {
/** Multi-repo: name of the repo this commit was made in. Empty for single-repo. */
repository_name?: string;
committed_at?: string;
presentation?: CommitPresentation;
};
export type PRCommitForMerge = {
@@ -409,6 +411,64 @@ export function mergeCommits(
return [...unpushed, ...pushed];
}
function mapLocalCheckoutCommit(commit: {
commit_sha: string;
commit_message: string;
insertions: number;
deletions: number;
repository_name?: string;
committed_at?: string;
}): MergedCommit {
return {
...commit,
pushed: false,
statsAvailable: true,
detailTarget: localCommitTarget(commit),
presentation: "local_checkout",
};
}
function mapCurrentPRCommit(commit: PRCommitForMerge): MergedCommit | null {
const detailTarget = githubCommitTarget(commit);
if (!detailTarget) return null;
return {
commit_sha: commit.sha,
commit_message: commit.message,
insertions: commit.additions,
deletions: commit.deletions,
pushed: true,
statsAvailable: commit.stats_available === true,
detailTarget,
presentation: "current_pr",
...(commit.repository_name ? { repository_name: commit.repository_name } : {}),
committed_at: commit.author_date,
};
}
/**
* Keeps provider and checkout rows independent after a proven history drift.
* No SHA, message, or metadata matching occurs in this mode.
*/
export function separateCommitHistories(
localCommits: {
commit_sha: string;
commit_message: string;
insertions: number;
deletions: number;
repository_name?: string;
committed_at?: string;
}[],
prCommits: PRCommitForMerge[],
): { providerCommits: MergedCommit[]; localCommits: MergedCommit[] } {
return {
providerCommits: prCommits.flatMap((commit) => {
const mapped = mapCurrentPRCommit(commit);
return mapped ? [mapped] : [];
}),
localCommits: localCommits.map(mapLocalCheckoutCommit),
};
}
export function getBaseBranchDisplay(baseBranch: string | undefined): string {
return baseBranch ? baseBranch.replace(/^origin\//, "") : "main";
}
@@ -15,6 +15,7 @@ export function PerRepoPullMenu({
onRepoPull,
onRepoRebase,
onRepoMerge,
pullDisabled,
repoDisplayName,
}: {
repoNames: string[];
@@ -22,6 +23,7 @@ export function PerRepoPullMenu({
onRepoPull: (repo: string) => void;
onRepoRebase: (repo: string) => void;
onRepoMerge: (repo: string) => void;
pullDisabled?: boolean;
repoDisplayName?: (repositoryName: string) => string | undefined;
}) {
const { t } = useTranslation();
@@ -30,7 +32,7 @@ export function PerRepoPullMenu({
<>
{repoNames.map((repo, idx) => {
const s = statusByName.get(repo);
const behind = s?.behind ?? 0;
const behind = s?.pullBehind ?? 0;
const label = repoDisplayName?.(repo) || repo || t("task:repository2");
return (
<div key={repo || "__no_repo__"}>
@@ -46,6 +48,8 @@ export function PerRepoPullMenu({
<DropdownMenuItem
onClick={() => onRepoPull(repo)}
className="cursor-pointer text-xs gap-2"
disabled={pullDisabled}
title={pullDisabled ? t("task:remoteActionsDisabledHistoryChanged") : undefined}
>
<IconCloudDownload className="h-3.5 w-3.5 text-muted-foreground" />
{t("task:pull")}
@@ -1,5 +1,5 @@
import { describe, expect, it } from "vitest";
import { mergeCommits } from "./changes-panel";
import { mergeCommits, separateCommitHistories } from "./changes-panel";
const PR_DATE = "2026-03-29T00:00:00Z";
const SHARED_SHA = "ccc3333";
@@ -120,6 +120,43 @@ describe("mergeCommits source provenance", () => {
});
});
describe("separateCommitHistories", () => {
it("preserves rewritten provider and checkout rows without deduplication", () => {
const local = [makeLocal("old1111", "same message"), makeLocal("old2222", "local work")];
const provider = [
{
...makePR("new1111", "same message"),
stats_available: false,
workspace_id: WORKSPACE_ID,
owner: "acme",
repo: WIDGET_REPO,
},
{
...makePR("new3333", "provider work"),
stats_available: false,
workspace_id: WORKSPACE_ID,
owner: "acme",
repo: WIDGET_REPO,
},
];
const result = separateCommitHistories(local, provider);
expect(result.providerCommits.map((commit) => commit.commit_sha)).toEqual([
"new1111",
"new3333",
]);
expect(result.localCommits.map((commit) => commit.commit_sha)).toEqual(["old1111", "old2222"]);
expect(result.providerCommits.every((commit) => commit.presentation === "current_pr")).toBe(
true,
);
expect(result.localCommits.every((commit) => commit.presentation === "local_checkout")).toBe(
true,
);
expect(result.localCommits.every((commit) => commit.pushed === false)).toBe(true);
});
});
describe("mergeCommits repository identity", () => {
it("does not create a PR-only target without complete provenance", () => {
const pr = {
@@ -145,12 +145,16 @@ type CommitsSectionProps = {
repoDisplayName?: (repositoryName: string) => string | undefined;
/** The session's base branch — passed through to the per-repo PR dialog. */
repoBaseBranch?: string;
/** Per-repo branch / ahead / behind summary; used for the "ahead" indicator. */
perRepoStatus?: Array<{ repository_name: string; ahead: number }>;
/** Per-repo branch / upstream summary; used for the Push indicator. */
perRepoStatus?: Array<{ repository_name: string; pushAhead?: number; ahead?: number }>;
/** Existing PR URL keyed by repository_name; "" key for single-repo. */
prByRepo?: Record<string, string | undefined>;
/** Initial collapse state. Defaults to collapsed; the panel expands it when it is the first visible section. */
defaultCollapsed?: boolean;
label?: string;
testId?: string;
pushDisabled?: boolean;
showActions?: boolean;
};
// Commits grouping shares the helper above with files — see @/lib/group-by-repo.
@@ -168,10 +172,16 @@ export function CommitsSection({
perRepoStatus,
prByRepo,
defaultCollapsed = true,
label,
testId = "commits-section",
pushDisabled = false,
showActions = true,
}: CommitsSectionProps) {
const { t } = useTranslation();
const groups = groupByRepositoryName(commits, (c) => c.repository_name);
const aheadByRepo = new Map((perRepoStatus ?? []).map((s) => [s.repository_name, s.ahead]));
const aheadByRepo = new Map(
(perRepoStatus ?? []).map((s) => [s.repository_name, s.pushAhead ?? s.ahead ?? 0]),
);
// Single-repo: drop the per-repo sub-header (CommitsRepoGroup with
// showHeader=false renders flat) and lift the Push / PR buttons into the
// section header.
@@ -182,8 +192,8 @@ export function CommitsSection({
aheadCount={aheadByRepo.get("") ?? 0}
prExists={!!prByRepo?.[""]}
canCreatePR={!!onRepoCreatePR && !prByRepo?.[""]}
onRepoPush={onRepoPush}
onRepoCreatePR={onRepoCreatePR}
onRepoPush={showActions && !pushDisabled ? onRepoPush : undefined}
onRepoCreatePR={showActions ? onRepoCreatePR : undefined}
stop={(e) => e.stopPropagation()}
/>
) : undefined;
@@ -191,10 +201,10 @@ export function CommitsSection({
return (
<TimelineSection
dotColor={DOT_COLORS.commits}
label={t("task:commits")}
label={label ?? t("task:commits")}
count={commits.length}
defaultCollapsed={defaultCollapsed}
data-testid="commits-section"
data-testid={testId}
action={sectionAction}
>
<ul data-testid="commits-list" className="space-y-0.5">
@@ -212,8 +222,8 @@ export function CommitsSection({
onAmendCommit={onAmendCommit}
onRevertCommit={onRevertCommit}
onResetToCommit={onResetToCommit}
onRepoPush={onRepoPush}
onRepoCreatePR={onRepoCreatePR}
onRepoPush={showActions && !pushDisabled ? onRepoPush : undefined}
onRepoCreatePR={showActions ? onRepoCreatePR : undefined}
/>
))}
</ul>
+8 -3
View File
@@ -4,13 +4,17 @@ import { memo } from "react";
import { PanelRoot } from "./panel-primitives";
import { useIsTaskArchived, ArchivedPanelPlaceholder } from "./task-archived-context";
import { ChangesPanelHeader } from "./changes-panel-header";
import { filterUnpushedCommits, mergeCommits } from "./changes-panel-helpers";
import {
filterUnpushedCommits,
mergeCommits,
separateCommitHistories,
} from "./changes-panel-helpers";
import { useChangesPanelData, buildChangesPanelBodyProps } from "./changes-panel-data";
import { ChangesPanelBody } from "./changes-panel-body";
import type { CommitDetailTarget, OpenDiffOptions } from "./changes-diff-target";
import { useRequestChangesWalkthrough } from "@/hooks/domains/session/use-request-changes-walkthrough";
export { filterUnpushedCommits, mergeCommits };
export { filterUnpushedCommits, mergeCommits, separateCommitHistories };
type ChangesPanelProps = {
onOpenDiffFile: (path: string, options?: OpenDiffOptions) => void;
@@ -38,7 +42,8 @@ const ChangesPanel = memo(function ChangesPanel(props: ChangesPanelProps) {
displayBranch={data.git.branch}
baseBranchDisplay={data.baseBranchDisplay}
baseBranchByRepo={data.baseBranchByRepo}
behindCount={data.git.behind}
behindCount={data.git.pullBehind}
pullDisabled={data.pullDisabled}
isLoading={data.git.isLoading}
loadingOperation={data.git.loadingOperation}
onOpenDiffAll={props.onOpenDiffAll}
@@ -73,4 +73,21 @@ describe("CommitRow", () => {
fireEvent.click(screen.getByTestId("commit-row-remote1"));
expect(onOpenCommitDetail).toHaveBeenCalledWith(commit.detailTarget);
});
it("announces diverged row provenance without showing an unpushed marker", () => {
const localCheckoutCommit: CommitItem = {
...remoteCommit(),
commit_sha: "local123456",
commit_message: "Superseded checkout commit",
pushed: false,
presentation: "local_checkout",
detailTarget: { source: "local", sha: "local123456" },
};
render(<CommitRow commit={localCheckoutCommit} isLatest />);
expect(screen.getByTitle("Local checkout commit")).toBeTruthy();
expect(screen.getByText("Local checkout commit")).toBeTruthy();
expect(screen.queryByTitle("Local commit (not yet pushed)")).toBeNull();
});
});
+40 -16
View File
@@ -19,6 +19,8 @@ import { timeAgo } from "@/lib/utils/time";
import type { CommitDetailTarget } from "./changes-diff-target";
import { useTranslation } from "react-i18next";
export type CommitPresentation = "current_pr" | "local_checkout";
export type CommitItem = {
commit_sha: string;
commit_message: string;
@@ -30,6 +32,8 @@ export type CommitItem = {
/** Multi-repo: name of the repo this commit was made in. Empty for single-repo. */
repository_name?: string;
committed_at?: string;
/** Explicit provenance used when provider and checkout histories diverge. */
presentation?: CommitPresentation;
};
/** Context menu for commit items */
@@ -170,6 +174,41 @@ function CommitRowActions({
);
}
function CommitStatusMarker({ commit }: { commit: CommitItem }) {
const { t } = useTranslation();
let label: string;
let marker = <IconGitCommit aria-hidden="true" className="h-3.5 w-3.5 text-muted-foreground" />;
if (commit.presentation === "current_pr") {
label = t("task:currentPRCommit");
} else if (commit.presentation === "local_checkout") {
label = t("task:localCheckoutCommit");
} else if (commit.pushed === true) {
label = t("task:pushedToRemote");
} else {
label = t("task:localCommitNotYetPushed");
marker = <IconArrowUp aria-hidden="true" className="h-3.5 w-3.5 text-emerald-500" />;
}
let accessibleLabel: string;
if (commit.presentation === "current_pr") {
accessibleLabel = t("task:currentPRCommit");
} else if (commit.presentation === "local_checkout") {
accessibleLabel = t("task:localCheckoutCommit");
} else if (commit.pushed === true) {
accessibleLabel = t("task:pushedCommit");
} else {
accessibleLabel = t("task:unpushedCommit");
}
return (
<span className="shrink-0" title={label}>
<span className="sr-only">{accessibleLabel}</span>
{marker}
</span>
);
}
/** Individual commit row with hover actions */
export function CommitRow({
commit,
@@ -192,7 +231,6 @@ export function CommitRow({
onRevertCommit?: (sha: string, repo?: string) => void;
onResetToCommit?: (sha: string, repo?: string) => void;
}) {
const { t } = useTranslation();
const isLocalCommit = commit.detailTarget.source === "local";
const showActions =
isLocalCommit && (onResetToCommit || (isLatest && (onAmendCommit || onRevertCommit)));
@@ -218,21 +256,7 @@ export function CommitRow({
}
}}
>
<span
className="shrink-0"
title={
commit.pushed === true ? t("task:pushedToRemote") : t("task:localCommitNotYetPushed")
}
>
<span className="sr-only">
{commit.pushed === true ? t("task:pushedCommit") : t("task:unpushedCommit")}
</span>
{commit.pushed === true ? (
<IconGitCommit aria-hidden="true" className="h-3.5 w-3.5 text-muted-foreground" />
) : (
<IconArrowUp aria-hidden="true" className="h-3.5 w-3.5 text-emerald-500" />
)}
</span>
<CommitStatusMarker commit={commit} />
<code className="font-mono text-muted-foreground text-[11px]">
{commit.commit_sha.slice(0, 7)}
</code>
@@ -102,7 +102,8 @@ export const MobileChangesPanel = memo(function MobileChangesPanel({
displayBranch={data.git.branch}
baseBranchDisplay={data.baseBranchDisplay}
baseBranchByRepo={data.baseBranchByRepo}
behindCount={data.git.behind}
behindCount={data.git.pullBehind}
pullDisabled={data.pullDisabled}
isLoading={data.git.isLoading}
loadingOperation={data.git.loadingOperation}
onOpenDiffAll={handleOpenDiffAll}
@@ -0,0 +1,54 @@
"use client";
import { IconAlertTriangle, IconCloudUpload } from "@tabler/icons-react";
import {
DropdownMenuItem,
DropdownMenuSub,
DropdownMenuSubContent,
DropdownMenuSubTrigger,
} from "@kandev/ui/dropdown-menu";
import { useTranslation } from "react-i18next";
export function PushSubmenu({
disabled,
disabledReason,
onPush,
}: {
disabled: boolean;
disabledReason?: string;
onPush: (force: boolean) => void;
}) {
const { t } = useTranslation();
return (
<DropdownMenuSub>
<DropdownMenuSubTrigger
className="cursor-pointer gap-3"
disabled={disabled}
title={disabledReason}
>
<IconCloudUpload className="h-4 w-4 text-green-500" />
<span className="flex-1">{t("task:push")}</span>
</DropdownMenuSubTrigger>
<DropdownMenuSubContent>
<DropdownMenuItem
className="cursor-pointer gap-3"
onClick={() => onPush(false)}
disabled={disabled}
title={disabledReason}
>
<IconCloudUpload className="h-4 w-4 text-green-500" />
<span>{t("task:push")}</span>
</DropdownMenuItem>
<DropdownMenuItem
className="cursor-pointer gap-3"
onClick={() => onPush(true)}
disabled={disabled}
title={disabledReason}
>
<IconAlertTriangle className="h-4 w-4 text-orange-500" />
<span>{t("task:forcePush")}</span>
</DropdownMenuItem>
</DropdownMenuSubContent>
</DropdownMenuSub>
);
}
@@ -0,0 +1,70 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { cleanup, render, screen } from "@testing-library/react";
import { GitActionsDropdown } from "./session-mobile-top-bar-git-controls";
vi.mock("@/hooks/use-git-operations", () => ({
useChangeRequestTerminology: () => ({ shortName: "PR" }),
}));
vi.mock("@kandev/ui/button", () => ({
Button: ({ children, ...props }: React.ButtonHTMLAttributes<HTMLButtonElement>) => (
<button {...props}>{children}</button>
),
}));
vi.mock("@kandev/ui/dropdown-menu", () => ({
DropdownMenu: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
DropdownMenuContent: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
DropdownMenuItem: ({ children, ...props }: React.ButtonHTMLAttributes<HTMLButtonElement>) => (
<button {...props}>{children}</button>
),
DropdownMenuTrigger: ({ children }: { children: React.ReactNode }) => <>{children}</>,
DropdownMenuSeparator: () => null,
DropdownMenuSub: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
DropdownMenuSubTrigger: ({
children,
...props
}: React.ButtonHTMLAttributes<HTMLButtonElement>) => <button {...props}>{children}</button>,
DropdownMenuSubContent: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
}));
afterEach(cleanup);
const baseProps = {
sessionId: "session-1",
isGitLoading: false,
uncommittedCount: 2,
baseBranch: "main",
onCommitClick: vi.fn(),
onPRClick: vi.fn(),
onPull: vi.fn(),
onPush: vi.fn(),
onRebase: vi.fn(),
onMerge: vi.fn(),
};
describe("GitActionsDropdown remote safety", () => {
it("keeps Commit available while disabling Pull and both Push variants", () => {
render(<GitActionsDropdown {...baseProps} pushDisabled pullDisabled />);
expect(screen.getByRole("button", { name: /Commit/ })).not.toHaveProperty("disabled", true);
expect(screen.getByRole("button", { name: /Pull/ })).toHaveProperty("disabled", true);
expect(
screen
.getAllByRole("button", { name: /^Push$/i })
.every((button) => button.hasAttribute("disabled")),
).toBe(true);
expect(screen.getByRole("button", { name: /Force Push/ })).toHaveProperty("disabled", true);
});
it("keeps Pull available for a provider-ahead checkout when only Push is blocked", () => {
render(<GitActionsDropdown {...baseProps} pushDisabled />);
expect(screen.getByRole("button", { name: /Pull/ })).not.toHaveProperty("disabled", true);
expect(
screen
.getAllByRole("button", { name: /^Push$/i })
.every((button) => button.hasAttribute("disabled")),
).toBe(true);
});
});
@@ -7,13 +7,11 @@ import {
IconGitCommit,
IconGitPullRequest,
IconCloudDownload,
IconCloudUpload,
IconGitCherryPick,
IconGitMerge,
IconDots,
IconCheck,
IconLoader2,
IconAlertTriangle,
} from "@tabler/icons-react";
import { Button } from "@kandev/ui/button";
import {
@@ -30,9 +28,6 @@ import {
DropdownMenuItem,
DropdownMenuTrigger,
DropdownMenuSeparator,
DropdownMenuSub,
DropdownMenuSubTrigger,
DropdownMenuSubContent,
} from "@kandev/ui/dropdown-menu";
import { Input } from "@kandev/ui/input";
import { Textarea } from "@kandev/ui/textarea";
@@ -55,6 +50,7 @@ import {
PRSubmitButton,
} from "./session-mobile-top-bar-dialog-parts";
import { useTranslation } from "react-i18next";
import { PushSubmenu } from "./mobile-git-push-submenu";
// A Git branch name, not copy: shown when the task has no recorded base branch.
const DEFAULT_BASE_BRANCH = "main";
@@ -368,44 +364,10 @@ export type GitActionsDropdownProps = {
onPush: (force?: boolean) => void;
onRebase: () => void;
onMerge: () => void;
pushDisabled?: boolean;
pullDisabled?: boolean;
};
function PushSubmenu({
disabled,
onPush,
}: {
disabled: boolean;
onPush: (force: boolean) => void;
}) {
const { t } = useTranslation();
return (
<DropdownMenuSub>
<DropdownMenuSubTrigger className="cursor-pointer gap-3" disabled={disabled}>
<IconCloudUpload className="h-4 w-4 text-green-500" />
<span className="flex-1">{t("task:push")}</span>
</DropdownMenuSubTrigger>
<DropdownMenuSubContent>
<DropdownMenuItem
className="cursor-pointer gap-3"
onClick={() => onPush(false)}
disabled={disabled}
>
<IconCloudUpload className="h-4 w-4 text-green-500" />
<span>{t("task:push")}</span>
</DropdownMenuItem>
<DropdownMenuItem
className="cursor-pointer gap-3"
onClick={() => onPush(true)}
disabled={disabled}
>
<IconAlertTriangle className="h-4 w-4 text-orange-500" />
<span>{t("task:forcePush")}</span>
</DropdownMenuItem>
</DropdownMenuSubContent>
</DropdownMenuSub>
);
}
function RebaseMergeItems({
disabled,
baseBranch,
@@ -448,6 +410,8 @@ export function GitActionsDropdown({
onPush,
onRebase,
onMerge,
pushDisabled = false,
pullDisabled = false,
}: GitActionsDropdownProps) {
const { t } = useTranslation();
const disabled = isGitLoading || !sessionId;
@@ -490,11 +454,20 @@ export function GitActionsDropdown({
</span>
</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem className="cursor-pointer gap-3" onClick={onPull} disabled={disabled}>
<DropdownMenuItem
className="cursor-pointer gap-3"
onClick={onPull}
disabled={disabled || pullDisabled}
title={pullDisabled ? t("task:remoteActionsDisabledHistoryChanged") : undefined}
>
<IconCloudDownload className="h-4 w-4 text-blue-500" />
<span className="flex-1">{t("task:pull")}</span>
</DropdownMenuItem>
<PushSubmenu disabled={disabled} onPush={onPush} />
<PushSubmenu
disabled={disabled || pushDisabled}
disabledReason={pushDisabled ? t("task:remoteActionsDisabledHistoryChanged") : undefined}
onPush={onPush}
/>
<DropdownMenuSeparator />
<RebaseMergeItems
disabled={disabled}
@@ -8,6 +8,8 @@ import { RemoteCloudTooltip } from "@/components/task/remote-cloud-tooltip";
import { LineStat } from "@/components/diff-stat";
import { useSessionGitStatus } from "@/hooks/domains/session/use-session-git-status";
import { useSessionCommits } from "@/hooks/domains/session/use-session-commits";
import { useRemoteContributionRelation } from "@/hooks/domains/session/use-remote-contribution-relation";
import { remoteContributionActionPolicy } from "@/hooks/domains/session/remote-contribution-relation";
import {
CommitDialog,
PRDialog,
@@ -140,6 +142,11 @@ function useMobileGitMetrics(
};
}
function useMobileRemoteActionPolicy(sessionId: string | null | undefined) {
const { relation } = useRemoteContributionRelation(sessionId);
return remoteContributionActionPolicy(relation);
}
type MobileGitDialogsProps = {
commitDialogOpen: boolean;
setCommitDialogOpen: (open: boolean) => void;
@@ -239,6 +246,7 @@ function MobileTopBarActions({
onMenuClick,
}: MobileTopBarActionsProps) {
const { t } = useTranslation();
const remoteActionPolicy = useMobileRemoteActionPolicy(sessionId);
return (
<div className="flex items-center gap-1" data-testid="mobile-topbar-actions">
<MRTopbarButton compact mobile />
@@ -275,6 +283,8 @@ function MobileTopBarActions({
onPush={onPush}
onRebase={onRebase}
onMerge={onMerge}
pushDisabled={remoteActionPolicy.pushDisabled}
pullDisabled={remoteActionPolicy.pullDisabled}
/>
<Button
variant="ghost"
@@ -297,7 +307,6 @@ export const SessionMobileTopBar = memo(function SessionMobileTopBar(
const [commitDialogOpen, setCommitDialogOpen] = useState(false);
const [prDialogOpen, setPrDialogOpen] = useState(false);
const [prBranchPushed, setPrBranchPushed] = useState(false);
const {
commits,
displayBranch,
@@ -322,7 +331,6 @@ export const SessionMobileTopBar = memo(function SessionMobileTopBar(
setPrDialogOpen,
setPrBranchPushed,
);
return (
<header className="flex items-center justify-between px-2 py-2 bg-background">
<div className="flex items-center gap-2 min-w-0 flex-1">
@@ -0,0 +1,22 @@
import { describe, expect, it } from "vitest";
import { isRemoteActionBlockedForRepository } from "./vcs-multi-repo-menu";
describe("multi-repository remote action policy", () => {
it("blocks only the selected PR repository when its history diverged", () => {
expect(isRemoteActionBlockedForRepository("push", "frontend", "frontend", true, true)).toBe(
true,
);
expect(isRemoteActionBlockedForRepository("push", "backend", "frontend", true, true)).toBe(
false,
);
expect(isRemoteActionBlockedForRepository("pull", "backend", "frontend", true, true)).toBe(
false,
);
});
it("fails closed for every repository when the blocked repository is unknown", () => {
expect(isRemoteActionBlockedForRepository("pull", "frontend", undefined, false, true)).toBe(
true,
);
});
});
+57 -7
View File
@@ -32,6 +32,8 @@ export type PerRepoStatus = {
branch: string | null;
ahead: number;
behind: number;
pushAhead: number;
pullBehind: number;
hasStaged: boolean;
hasUnstaged: boolean;
};
@@ -70,10 +72,23 @@ const PICK_REPOSITORY_KEYS: Record<"commit" | "push" | "pr" | "rebase", string>
const ITEM_CLASS = "cursor-pointer gap-3";
const ICON_CLASS = "h-4 w-4 text-muted-foreground";
type ActionKey = "commit" | "push" | "pr" | "pull" | "rebase" | "merge" | "force-push";
export type VcsActionKey = "commit" | "push" | "pr" | "pull" | "rebase" | "merge" | "force-push";
export function isRemoteActionBlockedForRepository(
action: VcsActionKey,
repositoryName: string,
blockedRepositoryName: string | undefined,
pushDisabled: boolean,
pullDisabled: boolean,
): boolean {
const actionBlocked =
(action === "push" || action === "force-push" ? pushDisabled : false) ||
(action === "pull" ? pullDisabled : false);
return actionBlocked && (!blockedRepositoryName || repositoryName === blockedRepositoryName);
}
type ActionDef = {
key: ActionKey;
key: VcsActionKey;
/** Catalog key, resolved at render: `t()` here would freeze at the boot locale. */
labelKey: string;
icon: ReactNode;
@@ -94,7 +109,7 @@ const ACTION_DEFS: ActionDef[] = [
key: "push",
labelKey: "integrations:push",
icon: <IconCloudUpload className={ICON_CLASS} />,
disabledFor: (s) => (s?.ahead ?? 0) === 0,
disabledFor: (s) => (s?.pushAhead ?? 0) === 0,
invoke: (repo, cb) => cb.onPush(false, repo),
},
{
@@ -129,7 +144,7 @@ const ACTION_DEFS: ActionDef[] = [
key: "force-push",
labelKey: "integrations:forcePush",
icon: <IconAlertTriangle className={ICON_CLASS} />,
disabledFor: (s) => (s?.ahead ?? 0) === 0,
disabledFor: (s) => (s?.pushAhead ?? 0) === 0,
invoke: (repo, cb) => cb.onPush(true, repo),
},
];
@@ -143,6 +158,9 @@ const ACTION_DEFS: ActionDef[] = [
function PerRepoActionSub({
action,
disabled,
pushDisabled,
pullDisabled,
blockedRepositoryName,
repoNames,
perRepoStatus,
repoDisplayName,
@@ -150,6 +168,9 @@ function PerRepoActionSub({
}: {
action: ActionDef;
disabled: boolean;
pushDisabled: boolean;
pullDisabled: boolean;
blockedRepositoryName: string | undefined;
repoNames: string[];
perRepoStatus: PerRepoStatus[];
repoDisplayName: (repositoryName: string) => string | undefined;
@@ -166,15 +187,26 @@ function PerRepoActionSub({
<DropdownMenuSubContent className="w-52">
{repoNames.map((repo) => {
const status = statusByName.get(repo);
const ahead = status?.ahead ?? 0;
const behind = status?.behind ?? 0;
const ahead = status?.pushAhead ?? 0;
const behind = status?.pullBehind ?? 0;
const label = repoDisplayName(repo) || repo || t("integrations:repository");
const actionBlocked = isRemoteActionBlockedForRepository(
action.key,
repo,
blockedRepositoryName,
pushDisabled,
pullDisabled,
);
const blockedTitle = actionBlocked
? t("task:remoteActionsDisabledHistoryChanged")
: undefined;
return (
<DropdownMenuItem
key={repo || "__no_repo__"}
className={ITEM_CLASS}
onClick={() => action.invoke(repo, callbacks)}
disabled={disabled || action.disabledFor(status)}
disabled={disabled || actionBlocked || action.disabledFor(status)}
title={blockedTitle}
>
<span className="flex-1 truncate">{label}</span>
<span className="flex items-center gap-1.5 text-[10px] text-muted-foreground">
@@ -202,6 +234,9 @@ function MultiRepoVcsDropdown({
baseBranch,
repoNames,
perRepoStatus,
pushDisabled,
pullDisabled,
blockedRepositoryName,
repoDisplayName,
callbacks,
}: {
@@ -209,6 +244,9 @@ function MultiRepoVcsDropdown({
baseBranch: string;
repoNames: string[];
perRepoStatus: PerRepoStatus[];
pushDisabled: boolean;
pullDisabled: boolean;
blockedRepositoryName: string | undefined;
repoDisplayName: (repositoryName: string) => string | undefined;
callbacks: PerRepoCallbacks;
}) {
@@ -226,6 +264,9 @@ function MultiRepoVcsDropdown({
<PerRepoActionSub
action={action}
disabled={disabled}
pushDisabled={pushDisabled}
pullDisabled={pullDisabled}
blockedRepositoryName={blockedRepositoryName}
repoNames={repoNames}
perRepoStatus={perRepoStatus}
repoDisplayName={repoDisplayName}
@@ -268,6 +309,9 @@ export function MultiRepoVcsButton({
baseBranch,
repoNames,
perRepoStatus,
pushDisabled,
pullDisabled,
blockedRepositoryName,
repoDisplayName,
callbacks,
}: {
@@ -278,6 +322,9 @@ export function MultiRepoVcsButton({
baseBranch: string;
repoNames: string[];
perRepoStatus: PerRepoStatus[];
pushDisabled: boolean;
pullDisabled: boolean;
blockedRepositoryName?: string;
repoDisplayName: (repositoryName: string) => string | undefined;
callbacks: PerRepoCallbacks;
}) {
@@ -314,6 +361,9 @@ export function MultiRepoVcsButton({
baseBranch={baseBranch}
repoNames={repoNames}
perRepoStatus={perRepoStatus}
pushDisabled={pushDisabled}
pullDisabled={pullDisabled}
blockedRepositoryName={blockedRepositoryName}
repoDisplayName={repoDisplayName}
callbacks={callbacks}
/>
@@ -1,6 +1,7 @@
import { describe, expect, it } from "vitest";
import { t } from "@/lib/i18n";
import { determinePrimaryAction } from "./vcs-split-button";
/**
* The VCS tooltips used to build their plural by hand:
@@ -42,6 +43,16 @@ describe("vcs split-button count-bearing copy", () => {
});
});
describe("vcs split-button remote action semantics", () => {
it("uses the upstream-relative count for a linked PR push", () => {
expect(determinePrimaryAction(0, 1, 7, true)).toBe("push");
});
it("does not select Push when divergence policy removes unsafe push evidence", () => {
expect(determinePrimaryAction(0, 0, 7, true)).toBe("rebase");
});
});
/**
* The discard dialog used to concatenate a " in your local clone at X" tail
* onto a shared stem, which froze the tail's position in the sentence. Each
+48 -18
View File
@@ -28,6 +28,8 @@ import {
import { Tooltip, TooltipContent, TooltipTrigger } from "@kandev/ui/tooltip";
import { cn } from "@kandev/ui/lib/utils";
import { useSessionGit } from "@/hooks/domains/session/use-session-git";
import { useRemoteContributionRelation } from "@/hooks/domains/session/use-remote-contribution-relation";
import { remoteContributionActionPolicy } from "@/hooks/domains/session/remote-contribution-relation";
import { gitOperationLabel, useGitWithFeedback } from "@/hooks/use-git-with-feedback";
import { useVcsDialogs } from "@/components/vcs/vcs-dialogs";
import { useActiveTaskPR } from "@/hooks/domains/github/use-task-pr";
@@ -36,7 +38,7 @@ import { MultiRepoVcsButton } from "@/components/vcs-multi-repo-menu";
const DEFAULT_BASE_BRANCH = "origin/main";
function determinePrimaryAction(
export function determinePrimaryAction(
uncommittedFileCount: number,
aheadCount: number,
behindCount: number,
@@ -214,9 +216,11 @@ function GitDivergencePills({ ahead, behind }: { ahead: number; behind: number }
type VcsDropdownItemsProps = {
disabled: boolean;
baseBranch?: string;
hasMatchingUpstream: boolean | "" | null | undefined;
hasUpstream: boolean;
behindCount: number;
aheadCount: number;
pushDisabled: boolean;
pullDisabled: boolean;
onPR: () => void;
onPull: () => void;
onPush: (force: boolean) => void;
@@ -227,9 +231,11 @@ type VcsDropdownItemsProps = {
function VcsDropdownItems({
disabled,
baseBranch,
hasMatchingUpstream,
hasUpstream,
behindCount,
aheadCount,
pushDisabled,
pullDisabled,
onPR,
onPull,
onPush,
@@ -237,6 +243,7 @@ function VcsDropdownItems({
onMerge,
}: VcsDropdownItemsProps) {
const { t } = useTranslation();
const remoteActionsDisabledTitle = t("task:remoteActionsDisabledHistoryChanged");
return (
<DropdownMenuContent align="end" className="w-56">
<DropdownMenuItem className="cursor-pointer gap-3" onClick={onPR} disabled={disabled}>
@@ -244,20 +251,29 @@ function VcsDropdownItems({
<span className="flex-1">{t("integrations:createPr")}</span>
</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem className="cursor-pointer gap-3" onClick={onPull} disabled={disabled}>
<DropdownMenuItem
className="cursor-pointer gap-3"
onClick={onPull}
disabled={disabled || pullDisabled}
title={pullDisabled ? remoteActionsDisabledTitle : undefined}
>
<IconCloudDownload className="h-4 w-4 text-muted-foreground" />
<span className="flex-1">{t("integrations:pull")}</span>
{hasMatchingUpstream && behindCount > 0 && (
{hasUpstream && behindCount > 0 && (
<span className="rounded-full bg-muted px-2 py-0.5 text-xs font-medium text-muted-foreground">
↓{behindCount}
</span>
)}
</DropdownMenuItem>
<DropdownMenuSub>
<DropdownMenuSubTrigger className="cursor-pointer gap-3" disabled={disabled}>
<DropdownMenuSubTrigger
className="cursor-pointer gap-3"
disabled={disabled || pushDisabled}
title={pushDisabled ? remoteActionsDisabledTitle : undefined}
>
<IconCloudUpload className="h-4 w-4 text-muted-foreground" />
<span className="flex-1">{t("integrations:push")}</span>
{hasMatchingUpstream && aheadCount > 0 && (
{hasUpstream && aheadCount > 0 && (
<span className="rounded-full bg-muted px-2 py-0.5 text-xs font-medium text-muted-foreground">
↑{aheadCount}
</span>
@@ -267,7 +283,8 @@ function VcsDropdownItems({
<DropdownMenuItem
className="cursor-pointer gap-3"
onClick={() => onPush(false)}
disabled={disabled}
disabled={disabled || pushDisabled}
title={pushDisabled ? remoteActionsDisabledTitle : undefined}
>
<IconCloudUpload className="h-4 w-4 text-muted-foreground" />
<span>{t("integrations:push")}</span>
@@ -275,7 +292,8 @@ function VcsDropdownItems({
<DropdownMenuItem
className="cursor-pointer gap-3"
onClick={() => onPush(true)}
disabled={disabled}
disabled={disabled || pushDisabled}
title={pushDisabled ? remoteActionsDisabledTitle : undefined}
>
<IconAlertTriangle className="h-4 w-4 text-muted-foreground" />
<span>{t("integrations:forcePush")}</span>
@@ -364,17 +382,18 @@ const VcsSplitButton = memo(function VcsSplitButton({
const git = useSessionGit(sessionId);
const { openCommitDialog, openPRDialog } = useVcsDialogs();
const activePR = useActiveTaskPR();
const { relation, repositoryName } = useRemoteContributionRelation(sessionId);
const remoteActionPolicy = remoteContributionActionPolicy(relation);
const hasOpenPR = activePR?.state === "open";
const { handlePull, handlePush, handleRebase, handleMerge } = useGitActions(git, baseBranch);
const repoDisplayName = useRepoDisplayName(sessionId);
const currentBranch = git.branch;
const remoteBranch = git.remoteBranch;
const hasMatchingUpstream =
remoteBranch && currentBranch && remoteBranch === `origin/${currentBranch}`;
const hasUpstream = Boolean(remoteBranch);
const uncommittedFileCount = git.allFiles.length;
const aheadCount = git.ahead;
const aheadCount = remoteActionPolicy.pushDisabled ? 0 : git.pushAhead;
const behindCount = git.behind;
const pullCount = git.pullBehind;
const isDisabled = git.isLoading || !sessionId;
const isGitLoading = git.isLoading;
// Multi-repo when there's more than one named repo. Single-repo workspaces
@@ -411,6 +430,9 @@ const VcsSplitButton = memo(function VcsSplitButton({
baseBranch={baseBranch || DEFAULT_BASE_BRANCH}
repoNames={git.repoNames}
perRepoStatus={git.perRepoStatus}
pushDisabled={remoteActionPolicy.pushDisabled}
pullDisabled={remoteActionPolicy.pullDisabled}
blockedRepositoryName={repositoryName}
repoDisplayName={repoDisplayName}
callbacks={{
onCommit: (repo) => openCommitDialog(repo),
@@ -431,9 +453,11 @@ const VcsSplitButton = memo(function VcsSplitButton({
isDisabled={isDisabled}
isGitLoading={isGitLoading}
baseBranch={baseBranch}
hasMatchingUpstream={hasMatchingUpstream}
behindCount={behindCount}
hasUpstream={hasUpstream}
behindCount={pullCount}
aheadCount={aheadCount}
pushDisabled={remoteActionPolicy.pushDisabled}
pullDisabled={remoteActionPolicy.pullDisabled}
buttonSize={buttonSize}
className={className}
showDivergencePills={showDivergencePills}
@@ -452,9 +476,11 @@ function SingleRepoVcsButton({
isDisabled,
isGitLoading,
baseBranch,
hasMatchingUpstream,
hasUpstream,
behindCount,
aheadCount,
pushDisabled,
pullDisabled,
onPR,
onPull,
onPush,
@@ -469,9 +495,11 @@ function SingleRepoVcsButton({
isDisabled: boolean;
isGitLoading: boolean;
baseBranch?: string;
hasMatchingUpstream: boolean | "" | null | undefined;
hasUpstream: boolean;
behindCount: number;
aheadCount: number;
pushDisabled: boolean;
pullDisabled: boolean;
onPR: () => void;
onPull: () => void;
onPush: (force: boolean) => void;
@@ -525,9 +553,11 @@ function SingleRepoVcsButton({
<VcsDropdownItems
disabled={isDisabled}
baseBranch={baseBranch}
hasMatchingUpstream={hasMatchingUpstream}
hasUpstream={hasUpstream}
behindCount={behindCount}
aheadCount={aheadCount}
pushDisabled={pushDisabled}
pullDisabled={pullDisabled}
onPR={onPR}
onPull={onPull}
onPush={onPush}
@@ -1523,4 +1523,251 @@ test.describe("Git Changes Panel", () => {
await expect(pushedRow).toBeVisible({ timeout: 10_000 });
await expect(pushedRow.locator(".tabler-icon-git-commit")).toBeVisible({ timeout: 5_000 });
});
test("separates rewritten provider history from the local checkout", async ({
testPage,
apiClient,
seedData,
backend,
prCapture,
}) => {
test.setTimeout(120_000);
const repoDir = path.join(backend.tmpDir, "repos", "e2e-repo");
const gitEnv = {
...process.env,
HOME: backend.tmpDir,
GIT_AUTHOR_NAME: "E2E Test",
GIT_AUTHOR_EMAIL: "e2e@test.local",
GIT_COMMITTER_NAME: "E2E Test",
GIT_COMMITTER_EMAIL: "e2e@test.local",
};
const git = new GitHelper(repoDir, gitEnv);
// Build a deterministic stale checkout. The upstream stays at the fixture
// seed commit while the task checkout grows six local commits.
git.exec("git checkout -f main");
if (git.exec("git remote").split(/\r?\n/).includes("origin")) {
git.exec(`git remote set-url origin "${seedData.repositoryRemoteURL}"`);
} else {
git.exec(`git remote add origin "${seedData.repositoryRemoteURL}"`);
}
git.exec("git fetch origin main");
git.exec("git reset --hard origin/main");
git.exec("git clean -fd");
git.exec("git branch --set-upstream-to=origin/main main");
for (let index = 1; index <= 6; index += 1) {
git.createFile(`drift-local-${index}.txt`, `local checkout commit ${index}`);
git.stageFile(`drift-local-${index}.txt`);
git.commit(`Contribution commit ${index}`);
}
const localHead = git.getCurrentSha();
const task = await apiClient.createTaskWithAgent(
seedData.workspaceId,
"Git Rewritten Contribution History",
seedData.agentProfileId,
{
description: "/e2e:simple-message",
workflow_id: seedData.workflowId,
workflow_step_id: seedData.startStepId,
repository_ids: [seedData.repositoryId],
},
);
const providerCommits = Array.from({ length: 15 }, (_, index) => ({
// These are intentionally valid, unique provider SHAs that do not exist
// in the local checkout. Their absence proves graph drift, not metadata
// mismatch, and keeps the provider fixture independent of local Git.
sha: `${String(index + 1).padStart(2, "0")}${"a".repeat(38)}`,
message: `Rewritten provider commit ${index + 1}`,
author_login: "remote-contributor",
author_date: `2026-08-${String(index + 1).padStart(2, "0")}T12:00:00Z`,
stats_available: false,
}));
await apiClient.mockGitHubReset();
await apiClient.mockGitHubSetUser("remote-contributor");
await apiClient.mockGitHubAddPRs([
{
number: 901,
title: "Rewritten contribution",
state: "open",
head_branch: "feature/rewritten-contribution",
base_branch: "main",
author_login: "remote-contributor",
repo_owner: "testorg",
repo_name: "testrepo",
head_sha: providerCommits[providerCommits.length - 1].sha,
},
]);
await apiClient.mockGitHubAddPRCommits("testorg", "testrepo", 901, providerCommits);
await apiClient.mockGitHubAssociateTaskPR({
task_id: task.id,
owner: "testorg",
repo: "testrepo",
pr_number: 901,
pr_url: "https://github.com/testorg/testrepo/pull/901",
pr_title: "Rewritten contribution",
head_branch: "feature/rewritten-contribution",
base_branch: "main",
author_login: "remote-contributor",
});
await testPage.goto(`/t/${task.id}`);
const session = new SessionPage(testPage);
await session.waitForLoad();
await session.waitForChatIdle({ timeout: 45_000 });
await session.clickTab("Changes");
const changes = testPage.getByTestId("changes-panel");
await expect(changes.getByTestId("remote-contribution-drift-warning")).toBeVisible({
timeout: 30_000,
});
const providerSection = changes.getByTestId("current-pr-commits-section");
const localSection = changes.getByTestId("local-checkout-commits-section");
await expect(providerSection).toBeVisible({ timeout: 10_000 });
await expect(localSection).toBeVisible({ timeout: 10_000 });
await expect(
providerSection.getByTestId("current-pr-commits-section-collapse-toggle"),
).toContainText("Current PR commits");
await expect(
localSection.getByTestId("local-checkout-commits-section-collapse-toggle"),
).toContainText("Local checkout commits");
await expect(providerSection.locator('[data-testid^="commit-row-"]')).toHaveCount(15);
await expect(localSection.locator('[data-testid^="commit-row-"]')).toHaveCount(6);
// A rewritten provider history must not label the preserved checkout as
// six unpushed commits, and reading the panel must not mutate the checkout.
await expect(providerSection.locator(".tabler-icon-arrow-up")).toHaveCount(0);
await expect(localSection.locator(".tabler-icon-arrow-up")).toHaveCount(0);
expect(git.getCurrentSha()).toBe(localHead);
expect(git.exec("git status --porcelain").trim()).toBe("");
const changesPull = changes.getByRole("button", { name: /^Pull$/ });
await expect(changesPull).toBeDisabled();
await prCapture.screenshot("remote-contribution-drift-desktop", {
caption: "Rewritten provider history is separated from the preserved local checkout",
});
// The review dialog uses the desktop VCS split button. It must expose the
// same safety policy as the Changes panel.
await changes.getByRole("button", { name: "Review" }).click();
const reviewDialog = testPage.getByRole("dialog", { name: "Review Changes" });
await expect(reviewDialog).toBeVisible({ timeout: 15_000 });
await reviewDialog.getByRole("button", { name: "Open VCS options" }).click();
const openMenu = testPage.locator('[data-slot="dropdown-menu-content"][data-state="open"]');
await expect(openMenu).toHaveCount(1);
await expect(
openMenu.locator('[data-slot="dropdown-menu-item"]').filter({ hasText: /^Pull$/ }),
).toHaveAttribute("aria-disabled", "true");
await expect(
openMenu.locator('[data-slot="dropdown-menu-sub-trigger"]').filter({ hasText: /^Push/ }),
).toHaveAttribute("aria-disabled", "true");
});
test("keeps a one-commit local-ahead contribution pushable", async ({
testPage,
apiClient,
seedData,
backend,
}) => {
test.setTimeout(120_000);
const repoDir = path.join(backend.tmpDir, "repos", "e2e-repo");
const gitEnv = {
...process.env,
HOME: backend.tmpDir,
GIT_AUTHOR_NAME: "E2E Test",
GIT_AUTHOR_EMAIL: "e2e@test.local",
GIT_COMMITTER_NAME: "E2E Test",
GIT_COMMITTER_EMAIL: "e2e@test.local",
};
const git = new GitHelper(repoDir, gitEnv);
git.exec("git checkout -f main");
if (git.exec("git remote").split(/\r?\n/).includes("origin")) {
git.exec(`git remote set-url origin "${seedData.repositoryRemoteURL}"`);
} else {
git.exec(`git remote add origin "${seedData.repositoryRemoteURL}"`);
}
git.exec("git fetch origin main");
git.exec("git reset --hard origin/main");
git.exec("git clean -fd");
git.exec("git branch --set-upstream-to=origin/main main");
const providerHead = git.exec("git rev-parse origin/main").trim();
git.createFile("local-ahead-contribution.txt", "one local commit ahead");
git.stageFile("local-ahead-contribution.txt");
const localHead = git.commit("Local maintainer contribution");
const task = await apiClient.createTaskWithAgent(
seedData.workspaceId,
"Git Local Ahead Contribution",
seedData.agentProfileId,
{
description: "/e2e:simple-message",
workflow_id: seedData.workflowId,
workflow_step_id: seedData.startStepId,
repository_ids: [seedData.repositoryId],
},
);
await apiClient.mockGitHubReset();
await apiClient.mockGitHubSetUser("local-ahead-author");
await apiClient.mockGitHubAddPRs([
{
number: 903,
title: "Local ahead contribution",
state: "open",
head_branch: "feature/local-ahead",
base_branch: "main",
author_login: "local-ahead-author",
repo_owner: "testorg",
repo_name: "testrepo",
},
]);
await apiClient.mockGitHubAddPRCommits("testorg", "testrepo", 903, [
{
sha: providerHead,
message: "Current provider head",
author_login: "local-ahead-author",
author_date: "2026-08-10T12:00:00Z",
stats_available: false,
},
]);
await apiClient.mockGitHubAssociateTaskPR({
task_id: task.id,
owner: "testorg",
repo: "testrepo",
pr_number: 903,
pr_url: "https://github.com/testorg/testrepo/pull/903",
pr_title: "Local ahead contribution",
head_branch: "feature/local-ahead",
base_branch: "main",
author_login: "local-ahead-author",
});
await testPage.goto(`/t/${task.id}`);
const session = new SessionPage(testPage);
await session.waitForLoad();
await session.waitForChatIdle({ timeout: 45_000 });
await session.clickTab("Changes");
const changes = testPage.getByTestId("changes-panel");
await expect(changes.getByTestId("commits-section")).toBeVisible({ timeout: 30_000 });
await expect(changes.getByText("Local maintainer contribution")).toBeVisible({
timeout: 15_000,
});
await expect(changes.getByTestId("remote-contribution-drift-warning")).toHaveCount(0);
await changes.getByRole("button", { name: "Review" }).click();
const reviewDialog = testPage.getByRole("dialog", { name: "Review Changes" });
await expect(reviewDialog).toBeVisible({ timeout: 15_000 });
await expect(reviewDialog.getByTestId("vcs-primary-push")).toBeVisible({ timeout: 15_000 });
await reviewDialog.getByRole("button", { name: "Open VCS options" }).click();
const openMenu = testPage.locator('[data-slot="dropdown-menu-content"][data-state="open"]');
await expect(
openMenu.locator('[data-slot="dropdown-menu-sub-trigger"]').filter({ hasText: /^Push/ }),
).not.toHaveAttribute("aria-disabled", "true");
expect(git.getCurrentSha()).toBe(localHead);
expect(git.exec("git status --porcelain").trim()).toBe("");
});
});
@@ -0,0 +1,184 @@
import type { Locator, Page } from "@playwright/test";
import { test, expect } from "../../fixtures/test-base";
import { GitHelper, makeGitEnv } from "../../helpers/git-helper";
import { SessionPage } from "../../pages/session-page";
import path from "node:path";
function seedStaleCheckout(git: GitHelper, remoteUrl: string): string {
git.exec("git checkout -f main");
if (git.exec("git remote").split(/\r?\n/).includes("origin")) {
git.exec(`git remote set-url origin "${remoteUrl}"`);
} else {
git.exec(`git remote add origin "${remoteUrl}"`);
}
git.exec("git fetch origin main");
git.exec("git reset --hard origin/main");
git.exec("git clean -fd");
git.exec("git branch --set-upstream-to=origin/main main");
for (let index = 1; index <= 6; index += 1) {
git.createFile(`mobile-drift-local-${index}.txt`, `local checkout commit ${index}`);
git.stageFile(`mobile-drift-local-${index}.txt`);
git.commit(`Mobile contribution commit ${index}`);
}
return git.getCurrentSha();
}
function rewrittenProviderCommits() {
return Array.from({ length: 15 }, (_, index) => ({
sha: `${String(index + 1).padStart(2, "0")}${"b".repeat(38)}`,
message: `Mobile rewritten provider commit ${index + 1}`,
author_login: "mobile-remote-contributor",
author_date: `2026-08-${String(index + 1).padStart(2, "0")}T12:00:00Z`,
stats_available: false,
}));
}
async function swipeUpOnElement(page: Page, element: Locator): Promise<void> {
const box = await element.boundingBox();
if (!box) throw new Error("Changes scroll container has no bounding box");
const cdp = await page.context().newCDPSession(page);
const centerX = box.x + box.width / 2;
const startY = box.y + box.height - 20;
const endY = box.y + 20;
await cdp.send("Input.dispatchTouchEvent", {
type: "touchStart",
touchPoints: [{ x: centerX, y: startY }],
});
for (let step = 1; step <= 8; step += 1) {
await cdp.send("Input.dispatchTouchEvent", {
type: "touchMove",
touchPoints: [{ x: centerX, y: startY + ((endY - startY) * step) / 8 }],
});
}
await cdp.send("Input.dispatchTouchEvent", { type: "touchEnd", touchPoints: [] });
}
test.describe("Mobile rewritten contribution history", () => {
test.describe.configure({ retries: 1, timeout: 120_000 });
test.beforeEach(({ backend, seedData }) => {
const repoDir = path.join(backend.tmpDir, "repos", "e2e-repo");
const git = new GitHelper(repoDir, makeGitEnv(backend.tmpDir));
git.exec("git checkout -f main");
if (git.exec("git remote").split(/\r?\n/).includes("origin")) {
git.exec(`git remote set-url origin "${seedData.repositoryRemoteURL}"`);
} else {
git.exec(`git remote add origin "${seedData.repositoryRemoteURL}"`);
}
git.exec("git fetch origin main");
git.exec("git reset --hard origin/main");
git.exec("git clean -fd");
});
test("preserves local history and disables remote mutations after a rewrite", async ({
testPage,
apiClient,
seedData,
backend,
prCapture,
}) => {
const repoDir = path.join(backend.tmpDir, "repos", "e2e-repo");
const git = new GitHelper(repoDir, makeGitEnv(backend.tmpDir));
const localHead = seedStaleCheckout(git, seedData.repositoryRemoteURL);
const task = await apiClient.createTaskWithAgent(
seedData.workspaceId,
"Mobile Rewritten Contribution History",
seedData.agentProfileId,
{
description: "/e2e:simple-message",
workflow_id: seedData.workflowId,
workflow_step_id: seedData.startStepId,
repository_ids: [seedData.repositoryId],
},
);
const providerCommits = rewrittenProviderCommits();
await apiClient.mockGitHubReset();
await apiClient.mockGitHubSetUser("mobile-remote-contributor");
await apiClient.mockGitHubAddPRs([
{
number: 902,
title: "Mobile rewritten contribution",
state: "open",
head_branch: "feature/mobile-rewritten",
base_branch: "main",
author_login: "mobile-remote-contributor",
repo_owner: "testorg",
repo_name: "testrepo",
head_sha: providerCommits[providerCommits.length - 1].sha,
},
]);
await apiClient.mockGitHubAddPRCommits("testorg", "testrepo", 902, providerCommits);
await apiClient.mockGitHubAssociateTaskPR({
task_id: task.id,
owner: "testorg",
repo: "testrepo",
pr_number: 902,
pr_url: "https://github.com/testorg/testrepo/pull/902",
pr_title: "Mobile rewritten contribution",
head_branch: "feature/mobile-rewritten",
base_branch: "main",
author_login: "mobile-remote-contributor",
});
await testPage.goto(`/t/${task.id}`);
const session = new SessionPage(testPage);
await session.waitForLoad();
await session.waitForChatIdle({ timeout: 45_000 });
await testPage.getByRole("button", { name: "Changes" }).tap();
const changes = testPage.getByTestId("mobile-changes-panel");
await expect(changes.getByTestId("remote-contribution-drift-warning")).toBeVisible({
timeout: 30_000,
});
const providerSection = changes.getByTestId("current-pr-commits-section");
const localSection = changes.getByTestId("local-checkout-commits-section");
await expect(providerSection).toBeVisible({ timeout: 10_000 });
await expect(localSection).toBeVisible({ timeout: 10_000 });
await expect(providerSection.locator('[data-testid^="commit-row-"]')).toHaveCount(15);
await expect(localSection.locator('[data-testid^="commit-row-"]')).toHaveCount(6);
await expect(providerSection.locator(".tabler-icon-arrow-up")).toHaveCount(0);
await expect(localSection.locator(".tabler-icon-arrow-up")).toHaveCount(0);
const scrollOwners = changes.locator('[class*="overflow-y-auto"]');
await expect(scrollOwners).toHaveCount(1);
const scroller = scrollOwners.first();
await expect
.poll(() => scroller.evaluate((element) => element.scrollHeight > element.clientHeight))
.toBe(true);
await scroller.evaluate((element) => {
element.scrollTop = 0;
});
await swipeUpOnElement(testPage, scroller);
await expect.poll(() => scroller.evaluate((element) => element.scrollTop)).toBeGreaterThan(0);
const changesPull = changes.getByRole("button", { name: /^Pull$/ });
await expect(changesPull).toBeDisabled();
const gitActions = testPage.getByTestId("mobile-git-actions");
await gitActions.tap();
const openMenu = testPage.locator('[data-slot="dropdown-menu-content"][data-state="open"]');
await expect(openMenu).toHaveCount(1);
const menuItems = openMenu.locator('[data-slot="dropdown-menu-item"]');
await expect(menuItems.filter({ hasText: /^Commit/ })).not.toHaveAttribute(
"aria-disabled",
"true",
);
await expect(menuItems.filter({ hasText: /^Pull$/ })).toHaveAttribute("aria-disabled", "true");
await expect(
openMenu.locator('[data-slot="dropdown-menu-sub-trigger"]').filter({ hasText: /^Push/ }),
).toHaveAttribute("aria-disabled", "true");
expect(git.getCurrentSha()).toBe(localHead);
expect(git.exec("git status --porcelain").trim()).toBe("");
expect(
await testPage.evaluate(
() => document.documentElement.scrollWidth <= document.documentElement.clientWidth,
),
).toBe(true);
await prCapture.screenshot("remote-contribution-drift-mobile", {
caption: "Pixel 5 keeps the preserved checkout separate and blocks remote mutations",
});
});
});
@@ -50,12 +50,16 @@ describe("usePRCommits request ownership", () => {
const staleState: KeyedPRCommitsState = {
sourceKey: "workspace-1/acme/app/1/old-refresh",
commits: [commit("first-sha")],
providerHead: "first-sha",
providerCommitsComplete: true,
loading: false,
error: null,
};
expect(resolvePRCommitsView(staleState, "workspace-1/acme/other-app/2/new-refresh")).toEqual({
commits: [],
providerHead: null,
providerCommitsComplete: false,
loading: true,
error: null,
});
@@ -90,4 +94,17 @@ describe("usePRCommits request ownership", () => {
expect(result.current.commits[0]?.sha).toBe("second-sha");
});
it("exposes the provider head and commit-list completeness", async () => {
requestMock.mockResolvedValue({
commits: [commit("provider-head")],
head_sha: "provider-head",
complete: true,
});
const { result } = renderHook(() => usePRCommits("acme", "app", 1, "synced"), { wrapper });
await waitFor(() => expect(result.current.providerHead).toBe("provider-head"));
expect(result.current.providerCommitsComplete).toBe(true);
});
});
@@ -7,6 +7,8 @@ import type { PRCommitInfo } from "@/lib/types/github";
type PRCommitsState = {
commits: PRCommitInfo[];
providerHead: string | null;
providerCommitsComplete: boolean;
loading: boolean;
error: string | null;
};
@@ -15,6 +17,8 @@ export type KeyedPRCommitsState = PRCommitsState & { sourceKey: string };
const INITIAL_STATE: KeyedPRCommitsState = {
sourceKey: "",
commits: [],
providerHead: null,
providerCommitsComplete: false,
loading: false,
error: null,
};
@@ -24,9 +28,21 @@ export function resolvePRCommitsView(
requestedKey: string,
): PRCommitsState {
if (state.sourceKey === requestedKey) {
return { commits: state.commits, loading: state.loading, error: state.error };
return {
commits: state.commits,
providerHead: state.providerHead,
providerCommitsComplete: state.providerCommitsComplete,
loading: state.loading,
error: state.error,
};
}
return { commits: [], loading: requestedKey !== "", error: null };
return {
commits: [],
providerHead: null,
providerCommitsComplete: false,
loading: requestedKey !== "",
error: null,
};
}
type PRCommitsRequest = {
@@ -42,23 +58,50 @@ async function fetchPRCommits(
setState: (s: KeyedPRCommitsState) => void,
) {
const client = getWebSocketClient();
setState({ sourceKey, commits: [], loading: true, error: null });
setState({
sourceKey,
commits: [],
providerHead: null,
providerCommitsComplete: false,
loading: true,
error: null,
});
if (!client) {
setState({ sourceKey, commits: [], loading: false, error: null });
setState({
sourceKey,
commits: [],
providerHead: null,
providerCommitsComplete: false,
loading: false,
error: null,
});
return;
}
try {
const response = await client.request<{ commits?: PRCommitInfo[] }>("github.pr_commits.get", {
const response = await client.request<{
commits?: PRCommitInfo[];
head_sha?: string;
complete?: boolean;
}>("github.pr_commits.get", {
workspace_id: workspaceId,
owner,
repo,
number: prNumber,
});
setState({ sourceKey, commits: response?.commits ?? [], loading: false, error: null });
setState({
sourceKey,
commits: response?.commits ?? [],
providerHead: response?.head_sha ?? null,
providerCommitsComplete: response?.complete === true,
loading: false,
error: null,
});
} catch (err) {
setState({
sourceKey,
commits: [],
providerHead: null,
providerCommitsComplete: false,
loading: false,
error: err instanceof Error ? err.message : "Failed to fetch PR commits",
});
@@ -0,0 +1,215 @@
import { describe, expect, it } from "vitest";
import {
classifyRemoteContribution,
remoteContributionActionPolicy,
type RemoteContributionRelationInput,
} from "./remote-contribution-relation";
const LOCAL_HEAD = "local-head";
const PROVIDER_BASE = "provider-base";
const PROVIDER_HEAD = "provider-head";
const REWRITTEN_BASE = "rewritten-base";
const REWRITTEN_HEAD = "rewritten-head";
const baseInput: RemoteContributionRelationInput = {
hasSelectedPR: true,
providerCommits: [{ sha: PROVIDER_BASE }, { sha: PROVIDER_HEAD }],
providerHead: PROVIDER_HEAD,
providerCommitsComplete: true,
providerLoading: false,
providerError: null,
localHead: LOCAL_HEAD,
upstreamHead: PROVIDER_HEAD,
remoteAhead: 0,
remoteBehind: 0,
baseAhead: 4,
hasUpstream: true,
};
function input(overrides: Partial<RemoteContributionRelationInput> = {}) {
return { ...baseInput, ...overrides };
}
const classificationCases = [
{
name: "not applicable without a selected PR",
overrides: { hasSelectedPR: false, hasUpstream: false, baseAhead: 2 },
expected: { kind: "not_applicable", canPush: true, pushAhead: 2 },
},
{
name: "aligned heads",
overrides: { localHead: PROVIDER_HEAD },
expected: { kind: "aligned", canPush: false, canPull: false },
},
{
name: "local ahead of the current provider head",
overrides: { remoteAhead: 1 },
expected: { kind: "local_ahead", canPush: true, pushAhead: 1 },
},
{
name: "provider ahead while retaining local HEAD",
overrides: {
providerCommits: [{ sha: PROVIDER_BASE }, { sha: LOCAL_HEAD }, { sha: PROVIDER_HEAD }],
upstreamHead: PROVIDER_HEAD,
remoteBehind: 1,
},
expected: { kind: "provider_ahead", canPush: false, canPull: true },
},
{
name: "rewritten provider history",
overrides: {
providerCommits: [{ sha: REWRITTEN_BASE }, { sha: REWRITTEN_HEAD }],
upstreamHead: REWRITTEN_HEAD,
remoteAhead: 2,
remoteBehind: 2,
},
expected: {
kind: "diverged",
canPush: false,
canPull: false,
remoteMutationBlocked: true,
presentation: "separate",
},
},
];
const unknownCases = [
{ name: "provider commits are loading", providerLoading: true },
{ name: "provider commits failed", providerError: "provider unavailable" },
{ name: "provider commits are unexpectedly empty", providerCommits: [] },
{ name: "local HEAD is unavailable", localHead: null },
{ name: "upstream evidence is unavailable", upstreamHead: null, hasUpstream: true },
];
describe("classifyRemoteContribution", () => {
it.each(classificationCases)("classifies $name", ({ overrides, expected }) => {
expect(classifyRemoteContribution(input(overrides))).toMatchObject(expected);
});
it.each(unknownCases)("returns unknown when $name", (overrides) => {
expect(classifyRemoteContribution(input(overrides))).toMatchObject({
kind: "unknown",
presentation: "unified",
remoteMutationBlocked: false,
canPush: false,
canPull: false,
});
});
it("uses upstream counts instead of base-ahead for an existing upstream", () => {
expect(
classifyRemoteContribution(
input({
providerLoading: true,
baseAhead: 12,
hasUpstream: true,
remoteAhead: 0,
remoteBehind: 1,
}),
),
).toMatchObject({ canPush: false, canPull: true, pushAhead: 0, pullBehind: 1 });
});
it("uses the first-push base fallback only without an upstream", () => {
expect(
classifyRemoteContribution(
input({
providerLoading: true,
hasUpstream: false,
upstreamHead: null,
baseAhead: 3,
remoteAhead: 0,
}),
),
).toMatchObject({ canPush: true, pushAhead: 3, canPull: false, pullBehind: 0 });
});
it("does not equate equal metadata with equal commit identity", () => {
expect(
classifyRemoteContribution(
input({
providerCommits: [{ sha: "different-sha" }],
upstreamHead: "different-sha",
}),
),
).toMatchObject({ kind: "diverged", presentation: "separate" });
});
it("does not call an upstream mismatch local-ahead", () => {
expect(
classifyRemoteContribution(
input({ upstreamHead: "unrelated-upstream", remoteAhead: 3, remoteBehind: 0 }),
),
).toMatchObject({ kind: "diverged", canPush: false, remoteMutationBlocked: true });
});
it("uses the explicit provider head instead of the last listed commit", () => {
const providerHeadInput = {
...input({
providerCommits: [{ sha: PROVIDER_BASE }],
localHead: PROVIDER_HEAD,
upstreamHead: PROVIDER_HEAD,
}),
providerHead: PROVIDER_HEAD,
providerCommitsComplete: true,
};
expect(classifyRemoteContribution(providerHeadInput)).toMatchObject({
kind: "aligned",
providerHead: PROVIDER_HEAD,
});
});
it("returns unknown when provider ancestry data is incomplete", () => {
const incompleteInput = {
...input({
providerCommits: [{ sha: REWRITTEN_BASE }, { sha: REWRITTEN_HEAD }],
upstreamHead: REWRITTEN_HEAD,
remoteAhead: 2,
remoteBehind: 2,
}),
providerHead: REWRITTEN_HEAD,
providerCommitsComplete: false,
};
expect(classifyRemoteContribution(incompleteInput)).toMatchObject({
kind: "unknown",
providerHead: REWRITTEN_HEAD,
remoteMutationBlocked: false,
});
});
});
describe("remoteContributionActionPolicy", () => {
it("blocks both remote mutations only for diverged histories", () => {
const relation = classifyRemoteContribution(
input({
providerCommits: [{ sha: REWRITTEN_HEAD }],
upstreamHead: REWRITTEN_HEAD,
remoteAhead: 1,
remoteBehind: 1,
}),
);
expect(remoteContributionActionPolicy(relation)).toEqual({
pushDisabled: true,
pullDisabled: true,
disabledReason: "history_changed",
});
});
it("keeps Pull available for provider-ahead and blocks Push", () => {
const relation = classifyRemoteContribution(
input({
providerCommits: [{ sha: LOCAL_HEAD }, { sha: PROVIDER_HEAD }],
remoteBehind: 1,
}),
);
expect(remoteContributionActionPolicy(relation)).toEqual({
pushDisabled: true,
pullDisabled: false,
disabledReason: null,
});
});
});
@@ -0,0 +1,142 @@
export type RemoteContributionRelationKind =
| "not_applicable"
| "aligned"
| "local_ahead"
| "provider_ahead"
| "diverged"
| "unknown";
export type RemoteContributionPresentation = "unified" | "separate";
export type RemoteContributionRelationInput = {
hasSelectedPR: boolean;
providerCommits: ReadonlyArray<{ sha: string }>;
providerHead: string | null | undefined;
providerCommitsComplete: boolean;
providerLoading: boolean;
providerError: string | null;
localHead: string | null | undefined;
upstreamHead: string | null | undefined;
remoteAhead: number;
remoteBehind: number;
baseAhead: number;
hasUpstream: boolean;
};
export type RemoteContributionRelation = {
kind: RemoteContributionRelationKind;
presentation: RemoteContributionPresentation;
providerHead: string | null;
pushAhead: number;
pullBehind: number;
canPush: boolean;
canPull: boolean;
remoteMutationBlocked: boolean;
};
export type RemoteContributionActionPolicy = {
pushDisabled: boolean;
pullDisabled: boolean;
disabledReason: "history_changed" | null;
};
/**
* Safety gates shared by desktop and mobile Git controls. A provider-ahead
* checkout may pull, but must not push over the provider's newer history.
* Diverged histories require reconciliation outside these controls.
*/
export function remoteContributionActionPolicy(
relation: RemoteContributionRelation,
): RemoteContributionActionPolicy {
const historyChanged = relation.remoteMutationBlocked;
return {
pushDisabled: historyChanged || relation.kind === "provider_ahead",
pullDisabled: historyChanged,
disabledReason: historyChanged ? "history_changed" : null,
};
}
function nonNegative(value: number): number {
return Math.max(0, value);
}
function fallbackCapabilities(input: RemoteContributionRelationInput) {
const pushAhead = input.hasUpstream
? nonNegative(input.remoteAhead)
: nonNegative(input.baseAhead);
const pullBehind = input.hasUpstream ? nonNegative(input.remoteBehind) : 0;
return {
pushAhead,
pullBehind,
canPush: pushAhead > 0,
canPull: pullBehind > 0,
remoteMutationBlocked: false,
};
}
function result(
kind: RemoteContributionRelationKind,
providerHead: string | null,
capabilities: ReturnType<typeof fallbackCapabilities>,
): RemoteContributionRelation {
return {
kind,
presentation: kind === "diverged" ? "separate" : "unified",
providerHead,
...capabilities,
};
}
export function classifyRemoteContribution(
input: RemoteContributionRelationInput,
): RemoteContributionRelation {
const fallback = fallbackCapabilities(input);
if (!input.hasSelectedPR) {
return result("not_applicable", null, fallback);
}
// The provider API supplies the head separately because a commit page can
// be incomplete or ordered independently from the live branch head.
const providerHead = input.providerHead ?? null;
const evidenceUnavailable =
input.providerLoading ||
Boolean(input.providerError) ||
!input.providerCommitsComplete ||
input.providerCommits.length === 0 ||
!providerHead ||
!input.localHead ||
!input.upstreamHead;
if (evidenceUnavailable) {
return result("unknown", providerHead, fallback);
}
if (input.localHead === providerHead) {
return result("aligned", providerHead, fallback);
}
if (input.providerCommits.some((commit) => commit.sha === input.localHead)) {
return result("provider_ahead", providerHead, {
...fallback,
canPush: false,
canPull: true,
remoteMutationBlocked: false,
});
}
if (input.upstreamHead === providerHead && input.remoteAhead > 0 && input.remoteBehind === 0) {
return result("local_ahead", providerHead, {
...fallback,
pushAhead: input.remoteAhead,
canPush: true,
canPull: false,
remoteMutationBlocked: false,
});
}
return result("diverged", providerHead, {
...fallback,
canPush: false,
canPull: false,
remoteMutationBlocked: true,
});
}
@@ -0,0 +1,122 @@
import { renderHook } from "@testing-library/react";
import { beforeEach, describe, expect, it, vi } from "vitest";
import type { PRCommitInfo, TaskPR } from "@/lib/types/github";
import type { GitStatusEntry } from "@/lib/state/slices/session-runtime/types";
import { useRemoteContributionRelation } from "./use-remote-contribution-relation";
const mocks = vi.hoisted(() => ({
statuses: [] as Array<{ repository_name: string; status: GitStatusEntry }>,
selectedPR: null as TaskPR | null,
providerHead: "provider-head",
repositoryName: "frontend",
}));
vi.mock("@/components/state-provider", () => ({
useAppStore: (selector: (state: { tasks: { activeTaskId: string } }) => unknown) =>
selector({ tasks: { activeTaskId: "task-1" } }),
}));
vi.mock("@/hooks/domains/github/use-review-pr-selection", () => ({
useReviewPRSelection: () => ({ selectedPR: mocks.selectedPR }),
}));
vi.mock("@/hooks/domains/github/use-pr-commits", () => ({
usePRCommits: () => ({
commits: [{ sha: mocks.providerHead }] as PRCommitInfo[],
providerHead: mocks.providerHead,
providerCommitsComplete: true,
loading: false,
error: null,
}),
}));
vi.mock("@/hooks/domains/github/use-pr-review-repository-identity", () => ({
usePRReviewRepositoryIdentity: () => mocks.repositoryName,
}));
vi.mock("./use-session-git-status", () => ({
useSessionGitStatus: () => mocks.statuses.at(-1)?.status,
useSessionGitStatusByRepo: () => mocks.statuses,
}));
const baseStatus: Omit<GitStatusEntry, "repository_name" | "head_commit" | "remote_head_commit"> = {
branch: "feature",
remote_branch: "origin/feature",
modified: [],
added: [],
deleted: [],
untracked: [],
renamed: [],
ahead: 0,
behind: 0,
remote_ahead: 0,
remote_behind: 0,
files: {},
timestamp: null,
};
const selectedPR = { repository_id: "repo-frontend" } as TaskPR;
function status(
repository_name: string,
head_commit: string,
remote_head_commit: string,
overrides: Partial<GitStatusEntry> = {},
): { repository_name: string; status: GitStatusEntry } {
return {
repository_name,
status: {
...baseStatus,
repository_name,
head_commit,
remote_head_commit,
...overrides,
},
};
}
describe("useRemoteContributionRelation repository scoping", () => {
beforeEach(() => {
mocks.selectedPR = selectedPR;
mocks.statuses = [];
mocks.repositoryName = "frontend";
});
it.each([
["frontend then backend", ["frontend", "backend"]],
["backend then frontend", ["backend", "frontend"]],
])("uses the selected PR repository when statuses arrive %s", (_name, eventOrder) => {
const statuses = {
frontend: status("frontend", mocks.providerHead, mocks.providerHead),
backend: status("backend", "backend-local", "backend-provider", {
remote_ahead: 3,
remote_behind: 3,
}),
};
mocks.statuses = eventOrder.map(
(repositoryName) => statuses[repositoryName as keyof typeof statuses],
);
const { result } = renderHook(() => useRemoteContributionRelation("session-1"));
expect(result.current.relation).toMatchObject({
kind: "aligned",
canPush: false,
canPull: false,
remoteMutationBlocked: false,
});
});
it("uses the empty-key status for a single-repository session", () => {
mocks.statuses = [status("", mocks.providerHead, mocks.providerHead)];
const { result } = renderHook(() => useRemoteContributionRelation("session-1"));
expect(result.current.relation).toMatchObject({
kind: "aligned",
canPush: false,
canPull: false,
remoteMutationBlocked: false,
});
});
});
@@ -0,0 +1,88 @@
"use client";
import { useMemo } from "react";
import { useAppStore } from "@/components/state-provider";
import type { PRCommitInfo, TaskPR } from "@/lib/types/github";
import { usePRCommits } from "@/hooks/domains/github/use-pr-commits";
import { usePRReviewRepositoryIdentity } from "@/hooks/domains/github/use-pr-review-repository-identity";
import { useReviewPRSelection } from "@/hooks/domains/github/use-review-pr-selection";
import { useSessionGitStatusByRepo } from "./use-session-git-status";
import {
classifyRemoteContribution,
type RemoteContributionRelation,
} from "./remote-contribution-relation";
export type RemoteContributionRelationState = {
selectedPR: TaskPR | null;
repositoryName: string | undefined;
commits: PRCommitInfo[];
loading: boolean;
error: string | null;
relation: RemoteContributionRelation;
};
export function useRemoteContributionRelation(
sessionId: string | null | undefined,
): RemoteContributionRelationState {
const activeTaskId = useAppStore((state) => state.tasks.activeTaskId);
const { selectedPR } = useReviewPRSelection(activeTaskId);
const commitsState = usePRCommits(
selectedPR?.owner ?? null,
selectedPR?.repo ?? null,
selectedPR?.pr_number ?? null,
selectedPR?.last_synced_at ?? null,
);
const repositoryName = usePRReviewRepositoryIdentity(activeTaskId, sessionId, selectedPR);
const statusByRepo = useSessionGitStatusByRepo(sessionId ?? null);
const gitStatus = useMemo(() => {
const matchingStatus = repositoryName
? statusByRepo.find((entry) => entry.repository_name === repositoryName)?.status
: undefined;
if (matchingStatus) return matchingStatus;
// Single-repository sessions keep the legacy empty repository key even
// when the selected PR resolves to the workspace repository name. A lone
// empty-key entry is therefore the selected repository, while a lone
// named entry is only a safe fallback when no identity was resolved.
if (statusByRepo.length !== 1) return undefined;
const onlyStatus = statusByRepo[0];
if (onlyStatus.repository_name === "" || !repositoryName) return onlyStatus.status;
return undefined;
}, [repositoryName, statusByRepo]);
const relation = useMemo(
() =>
classifyRemoteContribution({
hasSelectedPR: Boolean(selectedPR),
providerCommits: commitsState.commits,
providerHead: commitsState.providerHead,
providerCommitsComplete: commitsState.providerCommitsComplete,
providerLoading: commitsState.loading,
providerError: commitsState.error,
localHead: gitStatus?.head_commit,
upstreamHead: gitStatus?.remote_head_commit,
remoteAhead: gitStatus?.remote_ahead ?? 0,
remoteBehind: gitStatus?.remote_behind ?? 0,
baseAhead: gitStatus?.ahead ?? 0,
hasUpstream: Boolean(gitStatus?.remote_branch),
}),
[
selectedPR,
commitsState.commits,
commitsState.providerHead,
commitsState.providerCommitsComplete,
commitsState.loading,
commitsState.error,
gitStatus,
],
);
return {
selectedPR,
repositoryName,
commits: commitsState.commits,
loading: commitsState.loading,
error: commitsState.error,
relation,
};
}
@@ -0,0 +1,51 @@
import { act, renderHook } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
import { useScopedStageOperations } from "./use-scoped-stage-operations";
const FILE_PATH = "src/app.ts";
function setup() {
const gitOps = {
stage: vi.fn(async (_paths?: string[], _repo?: string) => "repository-stage"),
unstage: vi.fn(async (_paths?: string[], _repo?: string) => "repository-unstage"),
};
const stageAll = vi.fn(async () => "stage-all");
const stageFile = vi.fn(async (_paths: string[], _repo?: string) => "stage-file");
const unstageAll = vi.fn(async () => "unstage-all");
const unstageFile = vi.fn(async (_paths: string[], _repo?: string) => "unstage-file");
const hook = renderHook(() =>
useScopedStageOperations(gitOps, stageAll, stageFile, unstageAll, unstageFile),
);
return { ...hook, gitOps, stageAll, stageFile, unstageAll, unstageFile };
}
describe("useScopedStageOperations", () => {
it("dispatches path, repository, and workspace stage scopes", async () => {
const { result, gitOps, stageAll, stageFile } = setup();
await act(async () => {
await result.current.stage([FILE_PATH], "frontend");
await result.current.stage(undefined, "backend");
await result.current.stage();
});
expect(stageFile).toHaveBeenCalledWith([FILE_PATH], "frontend");
expect(gitOps.stage).toHaveBeenCalledWith(undefined, "backend");
expect(stageAll).toHaveBeenCalledOnce();
});
it("dispatches path, repository, and workspace unstage scopes", async () => {
const { result, gitOps, unstageAll, unstageFile } = setup();
await act(async () => {
await result.current.unstage([FILE_PATH], "frontend");
await result.current.unstage(undefined, "backend");
await result.current.unstage();
});
expect(unstageFile).toHaveBeenCalledWith([FILE_PATH], "frontend");
expect(gitOps.unstage).toHaveBeenCalledWith(undefined, "backend");
expect(unstageAll).toHaveBeenCalledOnce();
});
});
@@ -0,0 +1,32 @@
import { useCallback } from "react";
type ScopedGitOperations<T> = {
stage: (paths?: string[], repo?: string) => Promise<T>;
unstage: (paths?: string[], repo?: string) => Promise<T>;
};
export function useScopedStageOperations<T>(
gitOps: ScopedGitOperations<T>,
stageAll: () => Promise<T>,
stageFile: (paths: string[], repo?: string) => Promise<T>,
unstageAll: () => Promise<T>,
unstageFile: (paths: string[], repo?: string) => Promise<T>,
) {
const stage = useCallback(
(paths?: string[], repo?: string) => {
if (paths && paths.length > 0) return stageFile(paths, repo);
if (repo !== undefined) return gitOps.stage(undefined, repo);
return stageAll();
},
[gitOps, stageAll, stageFile],
);
const unstage = useCallback(
(paths?: string[], repo?: string) => {
if (paths && paths.length > 0) return unstageFile(paths, repo);
if (repo !== undefined) return gitOps.unstage(undefined, repo);
return unstageAll();
},
[gitOps, unstageAll, unstageFile],
);
return { stage, unstage };
}
@@ -0,0 +1,72 @@
import { describe, expect, it } from "vitest";
import type { GitStatusEntry } from "@/lib/state/slices/session-runtime/types";
import { deriveSessionGitValues } from "./use-session-git-derived";
function status(overrides: Partial<GitStatusEntry> = {}): GitStatusEntry {
return {
branch: "feature/contribution",
remote_branch: "contributor/feature",
modified: [],
added: [],
deleted: [],
untracked: [],
renamed: [],
ahead: 0,
behind: 0,
files: {},
timestamp: null,
...overrides,
};
}
describe("deriveSessionGitValues", () => {
it("uses upstream-relative counts for remote actions", () => {
const result = deriveSessionGitValues(
status({
ahead: 7,
behind: 2,
remote_ahead: 1,
remote_behind: 3,
}),
false,
[],
[],
[],
);
expect(result).toMatchObject({
ahead: 7,
behind: 2,
remoteAhead: 1,
remoteBehind: 3,
pushAhead: 1,
pullBehind: 3,
canPush: true,
canPull: true,
});
});
it("falls back to base-ahead for a branch without an upstream", () => {
const result = deriveSessionGitValues(
status({
remote_branch: null,
ahead: 4,
remote_ahead: 8,
remote_behind: 2,
}),
false,
[],
[],
[],
);
expect(result).toMatchObject({
remoteAhead: 8,
remoteBehind: 2,
pushAhead: 4,
pullBehind: 0,
canPush: true,
canPull: false,
});
});
});
@@ -0,0 +1,65 @@
import type {
FileInfo,
GitStatusEntry,
SessionCommit,
} from "@/lib/state/slices/session-runtime/types";
function deriveBranchValues(gitStatus: GitStatusEntry | undefined) {
const ahead = gitStatus?.ahead ?? 0;
return {
branch: gitStatus?.branch ?? null,
remoteBranch: gitStatus?.remote_branch ?? null,
headCommit: gitStatus?.head_commit ?? null,
remoteHeadCommit: gitStatus?.remote_head_commit ?? null,
ahead,
behind: gitStatus?.behind ?? 0,
};
}
function deriveUpstreamValues(gitStatus: GitStatusEntry | undefined, ahead: number) {
const hasUpstream = Boolean(gitStatus?.remote_branch);
const remoteAhead = gitStatus?.remote_ahead ?? 0;
const remoteBehind = gitStatus?.remote_behind ?? 0;
return {
remoteAhead,
remoteBehind,
pushAhead: hasUpstream ? remoteAhead : ahead,
pullBehind: hasUpstream ? remoteBehind : 0,
};
}
function deriveChangeValues(
unstagedFiles: FileInfo[],
stagedFiles: FileInfo[],
commits: SessionCommit[],
) {
const hasUnstaged = unstagedFiles.length > 0;
const hasStaged = stagedFiles.length > 0;
const hasCommits = commits.length > 0;
return { hasUnstaged, hasStaged, hasCommits, hasChanges: hasUnstaged || hasStaged };
}
export function deriveSessionGitValues(
gitStatus: GitStatusEntry | undefined,
hasRepositoryStatuses: boolean,
unstagedFiles: FileInfo[],
stagedFiles: FileInfo[],
commits: SessionCommit[],
) {
const branch = deriveBranchValues(gitStatus);
const upstream = deriveUpstreamValues(gitStatus, branch.ahead);
const status = { ...branch, ...upstream };
const changes = deriveChangeValues(unstagedFiles, stagedFiles, commits);
const hasAnything = changes.hasChanges || changes.hasCommits;
return {
...status,
statusLoaded: Boolean(gitStatus || hasRepositoryStatuses),
...changes,
hasAnything,
canStageAll: changes.hasUnstaged,
canCommit: changes.hasStaged,
canPush: status.pushAhead > 0,
canPull: status.pullBehind > 0,
canCreatePR: changes.hasCommits,
};
}
@@ -6,6 +6,7 @@ type StatusByRepo = Parameters<typeof deriveMultiRepoSummary>[0];
const ROOT_SCOPE = "";
const OUTER_SCOPE = "vendor/outer";
const INNER_SCOPE = "vendor/outer/vendor/inner";
const NEW_BRANCH = "new-branch";
function status(overrides: Partial<GitStatusEntry> = {}): GitStatusEntry {
return {
@@ -77,4 +78,50 @@ describe("deriveMultiRepoSummary", () => {
expect.objectContaining({ repository_name: OUTER_SCOPE, hasUnstaged: true }),
]);
});
it("keeps base divergence separate from upstream push and pull counts", () => {
const result = deriveMultiRepoSummary(
[
repoStatus("contribution", {
ahead: 7,
behind: 2,
remote_branch: "contributor/feature",
remote_ahead: 1,
remote_behind: 0,
}),
],
[file("contribution")],
["contribution"],
);
expect(result.perRepoStatus).toEqual([
expect.objectContaining({
repository_name: "contribution",
ahead: 7,
behind: 2,
remoteAhead: 1,
remoteBehind: 0,
pushAhead: 1,
pullBehind: 0,
hasUpstream: true,
}),
]);
});
it("falls back to base-ahead only when no upstream exists", () => {
const result = deriveMultiRepoSummary(
[repoStatus(NEW_BRANCH, { ahead: 3, behind: 0, remote_branch: null })],
[file(NEW_BRANCH)],
[NEW_BRANCH],
);
expect(result.perRepoStatus).toEqual([
expect.objectContaining({
repository_name: NEW_BRANCH,
pushAhead: 3,
pullBehind: 0,
hasUpstream: false,
}),
]);
});
});
@@ -9,10 +9,47 @@ export type RepositoryStatusSummary = {
branch: string | null;
ahead: number;
behind: number;
remoteAhead: number;
remoteBehind: number;
pushAhead: number;
pullBehind: number;
hasUpstream: boolean;
hasStaged: boolean;
hasUnstaged: boolean;
};
function upstreamCounts(status: RepositoryStatus["status"], ahead: number) {
const hasUpstream = Boolean(status?.remote_branch);
const remoteAhead = status?.remote_ahead ?? 0;
const remoteBehind = status?.remote_behind ?? 0;
return {
hasUpstream,
remoteAhead,
remoteBehind,
pushAhead: hasUpstream ? remoteAhead : ahead,
pullBehind: hasUpstream ? remoteBehind : 0,
};
}
function summarizeRepositoryStatus(
{ repository_name, status }: RepositoryStatus,
stagedByRepo: Map<string, boolean>,
unstagedByRepo: Map<string, boolean>,
): RepositoryStatusSummary {
const ahead = status?.ahead ?? 0;
const behind = status?.behind ?? 0;
const remote = upstreamCounts(status, ahead);
return {
repository_name,
branch: status?.branch ?? null,
ahead,
behind,
...remote,
hasStaged: stagedByRepo.get(repository_name) ?? false,
hasUnstaged: unstagedByRepo.get(repository_name) ?? false,
};
}
export function deriveMultiRepoSummary(
statusByRepo: RepositoryStatus[],
allFiles: FileInfo[],
@@ -42,14 +79,9 @@ export function deriveMultiRepoSummary(
!hasRootStatus && hasNamed
? statusByRepo.filter((status) => status.repository_name !== "")
: statusByRepo;
const perRepoStatus = filtered.map(({ repository_name, status }) => ({
repository_name,
branch: status?.branch ?? null,
ahead: status?.ahead ?? 0,
behind: status?.behind ?? 0,
hasStaged: stagedByRepo.get(repository_name) ?? false,
hasUnstaged: unstagedByRepo.get(repository_name) ?? false,
}));
const perRepoStatus = filtered.map((entry) =>
summarizeRepositoryStatus(entry, stagedByRepo, unstagedByRepo),
);
return { repoNamesForControls, perRepoStatus };
}
@@ -21,6 +21,8 @@ import {
runRepositoryScopeWaves,
} from "./use-session-git-repository-order";
import { useMultiRepoSummary } from "./use-session-git-summary";
import { deriveSessionGitValues } from "./use-session-git-derived";
import { useScopedStageOperations } from "./use-scoped-stage-operations";
/**
* Per-repo result emitted by frontend-side fan-outs (commit, push, pull,
@@ -54,8 +56,14 @@ export type SessionGit = {
// Branch info
branch: string | null;
remoteBranch: string | null;
headCommit: string | null;
remoteHeadCommit: string | null;
ahead: number;
behind: number;
remoteAhead: number;
remoteBehind: number;
pushAhead: number;
pullBehind: number;
// Files (raw FileInfo from store)
allFiles: FileInfo[];
@@ -76,7 +84,8 @@ export type SessionGit = {
hasAnything: boolean; // hasChanges || hasCommits
canStageAll: boolean; // hasUnstaged
canCommit: boolean; // hasStaged
canPush: boolean; // ahead > 0
canPush: boolean; // pushAhead > 0
canPull: boolean; // pullBehind > 0
canCreatePR: boolean; // hasCommits
// Operation state
@@ -104,6 +113,11 @@ export type SessionGit = {
branch: string | null;
ahead: number;
behind: number;
remoteAhead: number;
remoteBehind: number;
pushAhead: number;
pullBehind: number;
hasUpstream: boolean;
hasStaged: boolean;
hasUnstaged: boolean;
}>;
@@ -497,7 +511,7 @@ function usePerRepoPendingClear(
type RemoteOpsArgs = {
gitOps: ReturnType<typeof useGitOperations>;
repoNamesForControls: string[];
perRepoStatus: Array<{ repository_name: string; ahead: number }>;
perRepoStatus: Array<{ repository_name: string; pushAhead: number }>;
};
/**
@@ -515,7 +529,7 @@ function useRemoteOpsFanOut({ gitOps, repoNamesForControls, perRepoStatus }: Rem
const isMultiRepo = repoNamesForControls.length > 1;
const aheadByRepo = useMemo(() => {
const m = new Map<string, number>();
for (const s of perRepoStatus) m.set(s.repository_name, s.ahead);
for (const s of perRepoStatus) m.set(s.repository_name, s.pushAhead);
return m;
}, [perRepoStatus]);
@@ -648,11 +662,6 @@ export function useSessionGit(sessionId: string | null | undefined): SessionGit
perRepoStatus,
} = useFileDerivations(statusByRepo, gitStatus);
usePerRepoPendingClear(statusByRepo, allFiles, setPendingStageFiles);
const ahead = gitStatus?.ahead ?? 0;
const statusLoaded = Boolean(gitStatus || statusByRepo.length > 0);
const hasUnstaged = unstagedFiles.length > 0;
const hasStaged = stagedFiles.length > 0;
const hasCommits = commits.length > 0;
const stageOps = useStageDispatch({
gitOps,
@@ -662,17 +671,28 @@ export function useSessionGit(sessionId: string | null | undefined): SessionGit
setPendingStageFiles,
});
const { stageAll, unstageAll, commit, stageFile, unstageFile, discard } = stageOps;
const derived = deriveSessionGitValues(
gitStatus,
statusByRepo.length > 0,
unstagedFiles,
stagedFiles,
commits,
);
const remoteOps = useRemoteOpsFanOut({
gitOps,
repoNamesForControls,
perRepoStatus,
});
const scopedStageOperations = useScopedStageOperations(
gitOps,
stageAll,
stageFile,
unstageAll,
unstageFile,
);
return {
branch: gitStatus?.branch ?? null,
remoteBranch: gitStatus?.remote_branch ?? null,
ahead,
behind: gitStatus?.behind ?? 0,
...derived,
repoNames: repoNamesForControls,
perRepoStatus,
@@ -684,17 +704,6 @@ export function useSessionGit(sessionId: string | null | undefined): SessionGit
cumulativeDiff,
commitsLoading: commitsLoading ?? false,
statusLoaded,
hasUnstaged,
hasStaged,
hasCommits,
hasChanges: hasUnstaged || hasStaged,
hasAnything: hasUnstaged || hasStaged || hasCommits,
canStageAll: hasUnstaged,
canCommit: hasStaged,
canPush: ahead > 0,
canCreatePR: hasCommits,
isLoading: gitOps.isLoading,
loadingOperation: gitOps.loadingOperation,
pendingStageFiles,
@@ -709,18 +718,10 @@ export function useSessionGit(sessionId: string | null | undefined): SessionGit
// for that single repo (one agentctl call). Without `repo`, we fan out
// across every repo with files (multi-repo) or hit the workspace root
// (single-repo). With paths, we route to the right repo per file.
stage: (paths?: string[], repo?: string) => {
if (paths && paths.length > 0) return stageFile(paths, repo);
if (repo !== undefined) return gitOps.stage(undefined, repo);
return stageAll();
},
stage: scopedStageOperations.stage,
stageFile,
stageAll,
unstage: (paths?: string[], repo?: string) => {
if (paths && paths.length > 0) return unstageFile(paths, repo);
if (repo !== undefined) return gitOps.unstage(undefined, repo);
return unstageAll();
},
unstage: scopedStageOperations.unstage,
unstageFile,
unstageAll,
discard,
@@ -31,6 +31,16 @@ function entry(overrides: { modified: string[]; repository_name?: string }): Git
};
}
function ancestryEntry(remoteHeadCommit?: string): GitStatusEntry {
const status = entry({ modified: [FRONTEND_FILE] });
status.remote_branch = "origin/main";
status.head_commit = "local-head";
status.remote_head_commit = remoteHeadCommit;
status.remote_ahead = 6;
status.remote_behind = 0;
return status;
}
const REPO_FRONTEND = "frontend";
const REPO_BACKEND = "backend";
const SESSION = "sess";
@@ -43,6 +53,10 @@ function makeStore() {
);
}
function setStatus(store: ReturnType<typeof makeStore>, status: GitStatusEntry): void {
store.getState().setGitStatus(SESSION, status);
}
describe("session-runtime gitStatus multi-repo routing", () => {
let useStore: ReturnType<typeof makeStore>;
@@ -60,12 +74,8 @@ describe("session-runtime gitStatus multi-repo routing", () => {
});
it("routes per-repo statuses into byEnvironmentRepo keyed by repository_name", () => {
useStore
.getState()
.setGitStatus(SESSION, entry({ modified: [FRONTEND_FILE], repository_name: REPO_FRONTEND }));
useStore
.getState()
.setGitStatus(SESSION, entry({ modified: [BACKEND_FILE], repository_name: REPO_BACKEND }));
setStatus(useStore, entry({ modified: [FRONTEND_FILE], repository_name: REPO_FRONTEND }));
setStatus(useStore, entry({ modified: [BACKEND_FILE], repository_name: REPO_BACKEND }));
const repoMap = useStore.getState().gitStatus.byEnvironmentRepo[SESSION];
expect(Object.keys(repoMap).sort()).toEqual([REPO_BACKEND, REPO_FRONTEND]);
@@ -74,28 +84,17 @@ describe("session-runtime gitStatus multi-repo routing", () => {
});
it("does NOT overwrite the per-repo map when a sibling repo updates", () => {
useStore
.getState()
.setGitStatus(SESSION, entry({ modified: [FRONTEND_FILE], repository_name: REPO_FRONTEND }));
useStore
.getState()
.setGitStatus(SESSION, entry({ modified: [BACKEND_FILE], repository_name: REPO_BACKEND }));
setStatus(useStore, entry({ modified: [FRONTEND_FILE], repository_name: REPO_FRONTEND }));
setStatus(useStore, entry({ modified: [BACKEND_FILE], repository_name: REPO_BACKEND }));
// Update frontend again — backend must still be there.
useStore
.getState()
.setGitStatus(
SESSION,
entry({ modified: ["frontend2.tsx"], repository_name: REPO_FRONTEND }),
);
setStatus(useStore, entry({ modified: ["frontend2.tsx"], repository_name: REPO_FRONTEND }));
const repoMap = useStore.getState().gitStatus.byEnvironmentRepo[SESSION];
expect(repoMap[REPO_FRONTEND].modified).toEqual(["frontend2.tsx"]);
expect(repoMap[REPO_BACKEND].modified).toEqual([BACKEND_FILE]);
});
it("clearGitStatus drops both maps", () => {
useStore
.getState()
.setGitStatus(SESSION, entry({ modified: ["x.ts"], repository_name: REPO_FRONTEND }));
setStatus(useStore, entry({ modified: ["x.ts"], repository_name: REPO_FRONTEND }));
useStore.getState().clearGitStatus(SESSION);
const state = useStore.getState();
expect(state.gitStatus.byEnvironmentId[SESSION]).toBeUndefined();
@@ -115,6 +114,21 @@ describe("session-runtime gitStatus multi-repo routing", () => {
expect(stateAfterSecond.gitStatus.byEnvironmentRepo[SESSION][""]).toBe(firstRepoStatus);
});
it("updates when commit ancestry evidence changes without file changes", () => {
const first = ancestryEntry();
const second = ancestryEntry("upstream-head");
useStore.getState().setGitStatus(SESSION, first);
useStore.getState().setGitStatus(SESSION, second);
expect(useStore.getState().gitStatus.byEnvironmentId[SESSION]).toMatchObject({
head_commit: "local-head",
remote_head_commit: "upstream-head",
remote_ahead: 6,
remote_behind: 0,
});
});
it("updates when file diff content changes with the same file stats", () => {
const first = entry({ modified: [FRONTEND_FILE] });
first.files[FRONTEND_FILE].additions = 1;
@@ -135,17 +149,11 @@ describe("session-runtime gitStatus multi-repo routing", () => {
});
it("does not overwrite byEnvironmentId for duplicate sibling-repo snapshots", () => {
useStore
.getState()
.setGitStatus(SESSION, entry({ modified: [FRONTEND_FILE], repository_name: REPO_FRONTEND }));
useStore
.getState()
.setGitStatus(SESSION, entry({ modified: [BACKEND_FILE], repository_name: REPO_BACKEND }));
setStatus(useStore, entry({ modified: [FRONTEND_FILE], repository_name: REPO_FRONTEND }));
setStatus(useStore, entry({ modified: [BACKEND_FILE], repository_name: REPO_BACKEND }));
const envAfterBackend = useStore.getState().gitStatus.byEnvironmentId[SESSION];
useStore
.getState()
.setGitStatus(SESSION, entry({ modified: [BACKEND_FILE], repository_name: REPO_BACKEND }));
setStatus(useStore, entry({ modified: [BACKEND_FILE], repository_name: REPO_BACKEND }));
const state = useStore.getState();
expect(state.gitStatus.byEnvironmentId[SESSION]).toBe(envAfterBackend);
@@ -95,8 +95,13 @@ function hasBranchSummaryChanged(existing: GitStatusEntry, incoming: GitStatusEn
return (
existing.branch !== incoming.branch ||
existing.remote_branch !== incoming.remote_branch ||
existing.head_commit !== incoming.head_commit ||
existing.base_commit !== incoming.base_commit ||
existing.ahead !== incoming.ahead ||
existing.behind !== incoming.behind ||
existing.remote_ahead !== incoming.remote_ahead ||
existing.remote_behind !== incoming.remote_behind ||
existing.remote_head_commit !== incoming.remote_head_commit ||
(existing.repository_name ?? "") !== (incoming.repository_name ?? "") ||
existing.is_submodule !== incoming.is_submodule ||
existing.branch_additions !== incoming.branch_additions ||
@@ -72,6 +72,11 @@ export type GitStatusEntry = {
renamed: string[];
ahead: number;
behind: number;
head_commit?: string;
base_commit?: string;
remote_ahead?: number;
remote_behind?: number;
remote_head_commit?: string;
files: Record<string, FileInfo>;
timestamp: string | null;
branch_additions?: number;
+3
View File
@@ -14,6 +14,7 @@ export type GitStatusData = {
remote_branch: string | null;
head_commit?: string;
base_commit?: string;
remote_head_commit?: string;
modified: string[];
added: string[];
deleted: string[];
@@ -21,6 +22,8 @@ export type GitStatusData = {
renamed: string[];
ahead: number;
behind: number;
remote_ahead: number;
remote_behind: number;
files: Record<string, FileInfo>;
branch_additions?: number;
branch_deletions?: number;
@@ -65,6 +65,8 @@ function statusUpdateEvent(timestamp: string, diff = "-old\n+new"): GitStatusUpd
renamed: [],
ahead: 0,
behind: 0,
remote_ahead: 0,
remote_behind: 0,
files: {
"a.ts": {
path: "a.ts",
@@ -98,6 +100,8 @@ function repoStatusUpdateEvent(
renamed: [],
ahead: 0,
behind: 0,
remote_ahead: 0,
remote_behind: 0,
repository_name: repositoryName,
files: {
[modifiedPath]: {
@@ -203,6 +207,29 @@ describe("git-status WS handler — stale-while-revalidate", () => {
expect(store.getState().gitStatus.byEnvironmentId[SESSION].is_submodule).toBe(true);
});
it("retains the commit and upstream evidence from a status event", () => {
const handler = gitStatusHandler(store);
const event = statusUpdateEvent(STATUS_TIME_1);
event.status = {
...event.status,
head_commit: "head-sha",
base_commit: "base-sha",
remote_head_commit: "remote-head-sha",
remote_ahead: 2,
remote_behind: 3,
} as typeof event.status;
handler(gitEvent(event));
expect(store.getState().gitStatus.byEnvironmentId[SESSION]).toMatchObject({
head_commit: "head-sha",
base_commit: "base-sha",
remote_head_commit: "remote-head-sha",
remote_ahead: 2,
remote_behind: 3,
});
});
it("invalidates cumulative diff when status diff content changes", () => {
const handler = gitStatusHandler(store);
+10
View File
@@ -38,6 +38,11 @@ function buildGitStatusEntry(event: GitStatusUpdateEvent): GitStatusEntry {
renamed: event.status.renamed,
ahead: event.status.ahead,
behind: event.status.behind,
head_commit: event.status.head_commit,
base_commit: event.status.base_commit,
remote_ahead: event.status.remote_ahead,
remote_behind: event.status.remote_behind,
remote_head_commit: event.status.remote_head_commit,
files: event.status.files,
timestamp: event.timestamp,
branch_additions: event.status.branch_additions,
@@ -68,6 +73,11 @@ const gitEventHandlers: GitEventHandlers = {
untracked: event.status.untracked?.length ?? 0,
ahead: event.status.ahead,
behind: event.status.behind,
remoteAhead: event.status.remote_ahead,
remoteBehind: event.status.remote_behind,
headCommit: event.status.head_commit,
baseCommit: event.status.base_commit,
remoteHeadCommit: event.status.remote_head_commit,
envKey: resolveEnvKey(store, event.session_id),
envMapped: event.session_id in store.getState().environmentIdBySessionId,
changed,
+7
View File
@@ -688,6 +688,8 @@
"loadingSessions": "Loading sessions…",
"loadingStatus": "Loading status...",
"localCommitNotYetPushed": "Local commit (not yet pushed)",
"localCheckoutCommit": "Local checkout commit",
"localCheckoutCommits": "Local checkout commits",
"localGitRepository": "Local Git repository",
"login": "Login",
"loginRequired": "Login required",
@@ -934,6 +936,7 @@
"promptFieldLabel": "prompt",
"providerPrivateContextThatKandevDid": "Provider-private context that Kandev did not record may not carry over. Open terminals, dev servers, and other workspace processes stop, including the task editor server.",
"providerUnavailable": "Provider unavailable",
"providerHistoryUnavailable": "Current PR history is unavailable. The checkout history is shown without assuming a rewrite.",
"proxy": "Proxy",
"publishARedactedSnapshotOfThis": "Publish a redacted snapshot of this completed task as a secret GitHub Gist on your account.",
"publishToGithubGist": "Publish to GitHub Gist",
@@ -984,12 +987,16 @@
"relatedTaskCount_other": "{{count}} related tasks",
"relatedTasks": "Related tasks",
"remote": "Remote",
"remoteActionsDisabledHistoryChanged": "Push, force-push, and Pull are disabled until the histories are reconciled.",
"remoteContributionHistoryChanged": "The linked contribution changed on the provider. Local checkout commits were preserved; reconcile the histories before using Push, force-push, or Pull.",
"remoteCreatedLine": "Created: {{createdAt}}",
"remoteExecutor": "Remote executor",
"remoteLastCheckLine": "Last check: {{checkedAt}}",
"remoteRepository": "Remote repository",
"remoteStateLine": "State: {{state}}",
"remoteStatusFailedLine": "Status failed: {{error}}",
"currentPRCommit": "Current PR commit",
"currentPRCommits": "Current PR commits",
"remoteUrlPressEnter": "<0>Remote URL</0>; press Enter to submit it.",
"remove": "Remove",
"remove2": "Remove {{name}}",
+7
View File
@@ -688,6 +688,8 @@
"loadingSessions": "Ĺōàďĩńĝ śēśśĩōńś…",
"loadingStatus": "Ĺōàďĩńĝ śţàţũś...",
"localCommitNotYetPushed": "Ĺōćàĺ ćōḿḿĩţ (ńōţ ŷēţ ƥũśĥēď)",
"localCheckoutCommit": "Ĺōćàĺ ćĥēćķōũţ ćōḿḿĩţ",
"localCheckoutCommits": "Ĺōćàĺ ćĥēćķōũţ ćōḿḿĩţś",
"localGitRepository": "Ĺōćàĺ Ĝĩţ ŕēƥōśĩţōŕŷ",
"login": "Ĺōĝĩń",
"loginRequired": "Ĺōĝĩń ŕēqũĩŕēď",
@@ -933,6 +935,7 @@
"prompt": "Ƥŕōḿƥţ",
"promptFieldLabel": "ƥŕōḿƥţ",
"providerPrivateContextThatKandevDid": "Ƥŕōvĩďēŕ-ƥŕĩvàţē ćōńţēxţ ţĥàţ Ķàńďēv ďĩď ńōţ ŕēćōŕď ḿàŷ ńōţ ćàŕŕŷ ōvēŕ. Ōƥēń ţēŕḿĩńàĺś, ďēv śēŕvēŕś, àńď ōţĥēŕ ŵōŕķśƥàćē ƥŕōćēśśēś śţōƥ, ĩńćĺũďĩńĝ ţĥē ţàśķ ēďĩţōŕ śēŕvēŕ.",
"providerHistoryUnavailable": "Ćũŕŕēńţ ƤŔ ĥĩśţōŕŷ ĩś ũńàṽàĩĺàƀĺē. Ťĥē ćĥēćķōũţ ĥĩśţōŕŷ ĩś śĥōŵń ŵĩţĥōũţ àśśũḿĩńĝ à ŕēŵŕĩţē.",
"providerUnavailable": "Ƥŕōvĩďēŕ ũńàvàĩĺàƀĺē",
"proxy": "Ƥŕōxŷ",
"publishARedactedSnapshotOfThis": "Ƥũƀĺĩśĥ à ŕēďàćţēď śńàƥśĥōţ ōƒ ţĥĩś ćōḿƥĺēţēď ţàśķ àś à śēćŕēţ ĜĩţĤũƀ Ĝĩśţ ōń ŷōũŕ àććōũńţ.",
@@ -984,12 +987,16 @@
"relatedTaskCount_other": "{{count}} ŕēĺàţēď ţàśķś",
"relatedTasks": "Ŕēĺàţēď ţàśķś",
"remote": "Ŕēḿōţē",
"remoteActionsDisabledHistoryChanged": "Ƥũśĥ, ƒōŕćē-ƥũśĥ, àńď Ƥũĺĺ àŕē ďĩśàƀĺēď ũńţĩĺ ţĥē ĥĩśţōŕĩēś àŕē ŕēćōńćĩĺēď.",
"remoteContributionHistoryChanged": "Ťĥē ĺĩńķēď ćōńţŕĩƀũţĩōń ćĥàńĝēď ōń ţĥē ƥŕōvĩďēŕ. Ĺōćàĺ ćĥēćķōũţ ćōḿḿĩţś ŵēŕē ƥŕēśēŕvēď; ŕēćōńćĩĺē ţĥē ĥĩśţōŕĩēś ƀēƒōŕē ũśĩńĝ Ƥũśĥ, ƒōŕćē-ƥũśĥ, ōŕ Ƥũĺĺ.",
"remoteCreatedLine": "Ćŕēàţēď: {{createdAt}}",
"remoteExecutor": "Ŕēḿōţē ēxēćũţōŕ",
"remoteLastCheckLine": "Ĺàśţ ćĥēćķ: {{checkedAt}}",
"remoteRepository": "Ŕēḿōţē ŕēƥōśĩţōŕŷ",
"remoteStateLine": "Śţàţē: {{state}}",
"remoteStatusFailedLine": "Śţàţũś ƒàĩĺēď: {{error}}",
"currentPRCommit": "Ćũŕŕēńţ ƤŔ ćōḿḿĩţ",
"currentPRCommits": "Ćũŕŕēńţ ƤŔ ćōḿḿĩţś",
"remoteUrlPressEnter": "<0>Ŕēḿōţē ŨŔĹ</0>; ƥŕēśś Ēńţēŕ ţō śũƀḿĩţ ĩţ.",
"remove": "Ŕēḿōvē",
"remove2": "Ŕēḿōvē {{name}}",
+7
View File
@@ -688,6 +688,8 @@
"loadingSessions": "A carregar as sessões…",
"loadingStatus": "A carregar o estado...",
"localCommitNotYetPushed": "Commit local (ainda sem push)",
"localCheckoutCommit": "Commit do checkout local",
"localCheckoutCommits": "Commits do checkout local",
"localGitRepository": "Repositório Git local",
"login": "Iniciar sessão",
"loginRequired": "É necessário iniciar sessão",
@@ -934,6 +936,7 @@
"promptFieldLabel": "prompt",
"providerPrivateContextThatKandevDid": "O contexto privado do fornecedor que o Kandev não registou pode não transitar. Os terminais abertos, os servidores de desenvolvimento e outros processos da área de trabalho param, incluindo o servidor do editor da tarefa.",
"providerUnavailable": "Fornecedor indisponível",
"providerHistoryUnavailable": "O histórico atual do PR está indisponível. O histórico do checkout é mostrado sem assumir uma reescrita.",
"proxy": "Proxy",
"publishARedactedSnapshotOfThis": "Publique um retrato censurado desta tarefa concluída como um GitHub Gist secreto na sua conta.",
"publishToGithubGist": "Publicar no GitHub Gist",
@@ -984,12 +987,16 @@
"relatedTaskCount_other": "{{count}} tarefas relacionadas",
"relatedTasks": "Tarefas relacionadas",
"remote": "Remoto",
"remoteActionsDisabledHistoryChanged": "Push, force-push e Pull estão desativados até os históricos serem reconciliados.",
"remoteContributionHistoryChanged": "A contribuição associada mudou no fornecedor. Os commits do checkout local foram preservados; reconcilie os históricos antes de usar Push, force-push ou Pull.",
"remoteCreatedLine": "Criado: {{createdAt}}",
"remoteExecutor": "Executor remoto",
"remoteLastCheckLine": "Última verificação: {{checkedAt}}",
"remoteRepository": "Repositório remoto",
"remoteStateLine": "Estado: {{state}}",
"remoteStatusFailedLine": "Falha ao obter o estado: {{error}}",
"currentPRCommit": "Commit atual do PR",
"currentPRCommits": "Commits atuais do PR",
"remoteUrlPressEnter": "<0>URL remoto</0>; prima Enter para o submeter.",
"remove": "Remover",
"remove2": "Remover {{name}}",
+7
View File
@@ -689,6 +689,8 @@
"loadingSessions": "正在加载会话…",
"loadingStatus": "正在加载状态…",
"localCommitNotYetPushed": "本地提交(尚未推送)",
"localCheckoutCommit": "本地检出提交",
"localCheckoutCommits": "本地检出提交",
"localGitRepository": "本地 Git 仓库",
"login": "登录",
"loginRequired": "需要登录",
@@ -935,6 +937,7 @@
"promptFieldLabel": "提示词",
"providerPrivateContextThatKandevDid": "Kandev 未记录的提供商私有上下文可能不会保留。已打开的终端、开发服务器及其他工作区进程会停止,包括任务编辑器服务器。",
"providerUnavailable": "提供商不可用",
"providerHistoryUnavailable": "当前 PR 历史不可用。显示检出历史,但不假定发生了重写。",
"proxy": "代理",
"publishARedactedSnapshotOfThis": "将此已完成任务的脱敏快照发布为你账户上的私密 GitHub Gist。",
"publishToGithubGist": "发布到 GitHub Gist",
@@ -985,12 +988,16 @@
"relatedTaskCount_other": "{{count}} 个相关任务",
"relatedTasks": "相关任务",
"remote": "远程",
"remoteActionsDisabledHistoryChanged": "在历史记录完成协调前,Push、force-push 和 Pull 均已禁用。",
"remoteContributionHistoryChanged": "关联的贡献已在提供商处发生变化。本地检出提交已保留;请先协调历史记录,再使用 Push、force-push 或 Pull。",
"remoteCreatedLine": "创建:{{createdAt}}",
"remoteExecutor": "远程执行器",
"remoteLastCheckLine": "上次检查:{{checkedAt}}",
"remoteRepository": "远程仓库",
"remoteStateLine": "状态:{{state}}",
"remoteStatusFailedLine": "状态失败:{{error}}",
"currentPRCommit": "当前 PR 提交",
"currentPRCommits": "当前 PR 提交",
"remoteUrlPressEnter": "<0>远程 URL</0>; 按 Enter 提交。",
"remove": "移除",
"remove2": "移除 {{name}}",
@@ -0,0 +1,101 @@
# ADR-2026-08-10-remote-contribution-head-drift: Separate Current Contribution and Local Checkout Histories
**Status:** accepted
**Date:** 2026-08-10
**Area:** backend, frontend, protocol, GitHub, GitLab
## Context
A remote-contribution task starts from the provider-reported head SHA and tracks the contributor's
source branch. After the task starts, the contributor can advance or rewrite that branch. The local
checkout, its remote-tracking ref, and the provider API can then describe different moments or different
commit graphs.
The Changes panel currently merges local commits with the provider's current PR commits by SHA and
labels every unmatched local commit as unpushed. This is correct for ordinary local-ahead work, but it
is false after a rewrite: the unmatched commits can be the contributor's superseded history, not work
created in Kandev. The green arrow expresses push state, not authorship, but the flat list makes those
meanings indistinguishable. The UI also uses base-branch `ahead` for Push even though the backend
already computes separate upstream-relative counts.
Automatically resetting to the provider head would make the display current by discarding local work.
Automatically merging or rebasing would create a new history without user intent. Matching rewritten
commits by message, author, file totals, or patch identity would hide real graph divergence and make
remote mutation decisions from heuristic evidence.
## Decision
Kandev treats provider history and local checkout history as separate authorities:
- The provider's current commit list is authoritative for what the pull request or merge request
currently contains.
- The checkout's Git graph is authoritative for local HEAD and local work.
- The configured upstream ref supplies push/pull divergence evidence. Base-branch divergence remains a
separate review/rebase concept.
- Commit identity and graph reachability are the only reconciliation evidence. Kandev does not collapse
different SHAs because their content or metadata appears equivalent.
Git status publishes local HEAD, upstream ref identity, upstream head SHA, base-relative counts, and
upstream-relative counts. The frontend combines that evidence with the provider's ordered current
commit list and classifies the selected contribution as:
- `aligned`: local HEAD and provider head are the same.
- `local_ahead`: the tracked upstream equals the provider head and local commits are strictly ahead.
- `provider_ahead`: the provider history contains local HEAD and can be fast-forwarded.
- `diverged`: local and current provider histories both have unique commits, including a force-pushed
provider history that no longer contains local HEAD.
- `unknown`: required Git or provider evidence is unavailable.
Aligned and local-ahead histories may retain the unified commit presentation. Provider-ahead history
may offer Pull. Diverged history is rendered as two explicitly titled lists: current provider commits
and local checkout commits. Commits in the local list are described as local-checkout history, not as
"unpushed" merely because their SHA is absent from the provider list.
Push availability and counts use `remote_ahead`; Pull availability and counts use `remote_behind` or a
proven provider-ahead relationship. Base-relative `ahead`/`behind` remains available for review scope,
change-request creation before an upstream exists, and base-branch rebase/merge context. When a linked
contribution is diverged, Push, force-push, and generic Pull are disabled on desktop and mobile. The
backend's existing prohibition on contribution force pushes remains the final enforcement boundary.
Kandev never changes the checkout merely because drift is detected. Local commit, amend, revert, reset,
and terminal workflows remain local operations; the warning must make clear that reconciliation is
required before remote mutation.
## Consequences
- A contributor rewrite no longer creates a misleading combined commit count or green arrows on
superseded contributor commits.
- Users can inspect and recover local work without Kandev silently deleting or transforming it.
- Desktop and mobile Git controls share the same remote-action safety decision.
- The Git status wire and frontend store gain upstream-head and upstream-divergence fields that the
backend already mostly computes.
- Provider commit loading becomes part of the confidence model. Loading and error states must not be
collapsed into an empty history.
- This change detects and contains drift but does not provide a one-click reconciliation workflow.
## Alternatives considered
### Reset every contribution checkout to the latest provider head
Rejected. It keeps the panel visually simple by destroying local commits and uncommitted work, and it
turns an observation into an unauthorized destructive operation.
### Fetch, merge, or rebase automatically
Rejected. Each operation creates a different history and conflict policy. Kandev cannot choose among
them without user intent, especially after a force push.
### Deduplicate rewritten commits by patch or metadata
Rejected. Patch equivalence is useful diagnostic evidence but not Git identity or ancestry. It can hide
meaningful changes and cannot justify a Push or Pull decision.
### Keep one flat list and change the arrow tooltip
Rejected. A tooltip does not communicate that the rows come from incompatible histories, and the
combined count still falsely describes the current PR.
### Rely on Git push rejection
Rejected. A non-fast-forward rejection protects the remote but leaves the UI misleading and makes a
predictable unsafe action fail only after the user invokes it.
+1
View File
@@ -145,4 +145,5 @@ Read individual ADRs for full context. Create new ones via `/record decision` or
| 2026-08-09-exclusive-runtime-state-ownership | [Lock Runtime State Before Backend Startup](2026-08-09-exclusive-runtime-state-ownership.md) | accepted | backend, infra | 2026-08-09 |
| 2026-08-10-duration-aware-e2e-sharding | [Duration-aware E2E sharding uses rolling `main` timings](2026-08-10-duration-aware-e2e-sharding.md) | accepted | infra, workflow | 2026-08-10 |
| 2026-08-10-debug-launcher-profile-selection | [Keep Debug Launches on the Production Profile](2026-08-10-debug-launcher-profile-selection.md) | accepted | backend, frontend, cli | 2026-08-10 |
| 2026-08-10-remote-contribution-head-drift | [Separate Current Contribution and Local Checkout Histories](2026-08-10-remote-contribution-head-drift.md) | accepted | backend, frontend, protocol, GitHub, GitLab | 2026-08-10 |
| 2026-08-11-user-owned-status-bar-visibility | [Make Status Bar Visibility a Portable User Preference](2026-08-11-user-owned-status-bar-visibility.md) | accepted | backend, frontend, protocol | 2026-08-11 |
@@ -0,0 +1,185 @@
---
spec: docs/specs/tasks/remote-contribution-tasks.md
created: 2026-08-10
status: approved
---
# Implementation Plan: Remote Contribution Head Drift
## Overview
Prevent a contribution branch update or force-push from making the Changes panel present two different
Git histories as one. The reported panel combined six commits from the task's original checkout with
fifteen commits from the PR's current provider history. Exact-SHA deduplication correctly found no
matches after the rewrite, but the fallback interpretation was wrong: every unmatched local SHA was
rendered as an unpushed commit with a green arrow. The rows were old contributor commits, not commits
authored by Kandev.
The fix preserves the checkout and classifies its relationship to the current provider history. Safe
aligned, local-ahead, and provider-ahead histories retain normal Push/Pull behavior. Diverged histories
show an inline warning and two separately titled commit lists. No observation automatically resets,
rebases, merges, or deletes local work.
This plan implements the amended
[Remote Contribution Tasks spec](../../specs/tasks/remote-contribution-tasks.md) and
[ADR-2026-08-10](../../decisions/2026-08-10-remote-contribution-head-drift.md).
## Implementation status
- [x] Task 01 — publish and retain complete upstream Git status evidence.
- [x] Task 02 — derive provider/local history relation and correct Push/Pull semantics.
- [x] Task 03 — render diverged histories and enforce the shared desktop/mobile action policy.
- [x] Task 04 — prove the force-push regression and responsive behavior end to end.
## Invariants
- Provider commits define the current PR contents; local Git defines the checkout contents.
- Different commit SHAs are not considered the same because their message, author, timestamps, file
totals, or patches look similar.
- `ahead`/`behind` remain base-branch-relative. Push and Pull use upstream-relative evidence.
- Drift detection never mutates the checkout.
- Diverged history disables Push, force-push, and generic Pull on desktop and mobile.
- Provider loading or failure is not silently treated as an empty provider history or a confirmed
rewrite.
- Ordinary repositories and tasks without a linked PR retain their current behavior.
## Data contract
### Git status evidence
Extend `GitStatusUpdate` with `remote_head_commit`, the commit resolved by
`@{upstream}^{commit}` during the same observation that computes `remote_ahead` and
`remote_behind`. Project `head_commit`, `base_commit`, `remote_head_commit`, and both remote counts
through lifecycle events, the WebSocket type, the handler, and `GitStatusEntry`. Carry the complete
upstream snapshot forward only when a transient secondary command fails and local HEAD is unchanged.
The existing meanings stay explicit:
- `ahead` / `behind`: checkout versus target base branch.
- `remote_ahead` / `remote_behind`: checkout versus its configured upstream.
- `head_commit`: checkout HEAD.
- `remote_head_commit`: locally observed upstream tip.
### Provider/local relation
Add a pure classifier with inputs for the selected linked PR, ordered provider commits and their
loading/error state, local HEAD, upstream HEAD, and upstream divergence counts. It returns one of:
- `not_applicable`: no selected linked PR.
- `aligned`: local and provider heads match.
- `local_ahead`: upstream head matches provider head and Git reports only local upstream-ahead commits.
- `provider_ahead`: the current provider commit list contains local HEAD.
- `diverged`: provider data is complete but neither safe ancestry relationship is proven.
- `unknown`: required provider or Git evidence is unavailable.
The classifier also returns explicit capabilities (`canPush`, `canPull`, `remoteMutationBlocked`) and
presentation mode (`unified` or `separate`). It does not compare commit patches or metadata. Keep it
provider-shaped so GitLab MR commit data can adopt the same classifier; the first Changes-panel wiring
uses the existing GitHub selected-PR commit source because that is the surface involved in this bug.
## Backend and protocol
- Add `RemoteHeadCommit` to `apps/backend/internal/agentctl/types/streams/git.go` and lifecycle Git
status data.
- In `workspace_git_status.go`, resolve the sanitized upstream commit and counts as one secondary
observation. Preserve the prior complete upstream snapshot on transient failure when local HEAD is
unchanged; clear it when no upstream exists.
- Extend existing status tests for no upstream, aligned upstream, local ahead, remote ahead, divergence,
and carry-forward. Extend lifecycle event projection tests to pin JSON field names.
- Do not fetch or mutate a remote as part of status polling. The provider comparison supplies current
remote-change evidence without adding network Git work to the polling loop.
## Frontend state and behavior
- Retain the existing `head_commit`, `base_commit`, `remote_ahead`, and `remote_behind` fields that the
WebSocket currently drops, and add `remote_head_commit`.
- Keep `SessionGit.ahead`/`behind` as base divergence for compatibility. Add clearly named upstream
values such as `pushAhead` and `pullBehind`; `canPush` uses `pushAhead`, with the existing base-ahead
fallback only when no upstream exists and a new change request still needs its first push.
- Update multi-repository summaries and fan-out gates to use each repository's upstream counts.
- Preserve the `loading` and `error` values from `usePRCommits`. A selected-PR relation hook combines
those provider facts with the active repository's Git status and exposes one policy to the Changes
panel, desktop VCS split button, and mobile Git menu.
## Changes panel
- Keep `mergeCommits` for `aligned`, `local_ahead`, `provider_ahead`, `unknown`, and non-PR flows. It
continues exact-SHA deduplication.
- For `diverged`, bypass the flat merge. Render an inline warning followed by “Current PR commits” and
“Local checkout commits”. Provider rows use provider details and no local mutation menu. Local rows
retain local detail/recovery actions, but use a neutral local-checkout marker and accessible label;
they are not described as unpushed solely because they are absent from the PR.
- The commit total and group headings must not imply that the union is the current PR history.
- Disable Changes-panel Push controls in diverged state and show the reason in accessible text.
- Surface provider commit loading failures without classifying the history as diverged.
- Add all copy to the `task` translation namespace in English, Portuguese, Simplified Chinese, and
pseudo-locale files.
## Desktop and mobile controls
- Update `VcsSplitButton` to use upstream Push/Pull counts. Any configured upstream is valid; do not
require `origin/<current-branch>`, because contribution tasks intentionally track a contribution
remote.
- Keep base divergence pills and rebase/merge context base-relative.
- In diverged state, disable Push, force-push, and generic Pull with the same reason used by the Changes
panel. Local Commit and explicit local recovery operations remain available.
- Apply the same relation and disabled state to `GitActionsDropdown` in the mobile top bar. The shared
Changes panel warning remains inside its existing vertical scroll owner; do not add a nested drawer or
horizontal scroller. The existing 44px mobile Git trigger remains unchanged.
## Testing strategy
Every implementation task follows red-green-refactor.
- Backend unit tests pin upstream head/count observation and carry-forward behavior.
- Frontend wire tests prove no status evidence is dropped.
- Pure classifier table tests cover aligned, local-ahead, provider-ahead, rewritten, loading, error,
absent PR, and missing-upstream inputs.
- Component tests prove base counts never masquerade as Push counts, contribution remotes qualify as
upstreams, diverged commit lists do not merge, and desktop/mobile remote actions are disabled.
- Desktop E2E recreates the bug with old local SHAs and a provider commit list containing rewritten
SHAs, then asserts separate headings, the warning, accurate counts, and no green unpushed arrows.
- Mobile E2E opens the same task's Changes panel and Git menu at Pixel 5 dimensions, verifies the same
warning/action policy, and checks viewport containment.
## Implementation waves
```text
Wave 1:
- [x] [Task 01: Upstream status contract](task-01-upstream-status-contract.md)
Wave 2:
- [x] [Task 02: Checkout relation and action semantics](task-02-checkout-relation-and-action-semantics.md)
Wave 3:
- [x] [Task 03: Diverged Changes UI and mobile parity](task-03-diverged-changes-ui-and-mobile-parity.md)
Wave 4:
- [x] [Task 04: Responsive force-push regression E2E](task-04-responsive-force-push-regression-e2e.md)
```
The tasks are sequential. Each consumes the contract established by the previous task, and Tasks 02–03
both touch shared Git UI state where parallel edits would conflict.
## Final verification
```bash
make -C apps/backend test
make -C apps/backend lint
cd apps && pnpm --filter @kandev/web test
cd apps/web && pnpm run typecheck
cd apps && pnpm run i18n:check && pnpm run i18n:ratchet
cd apps/web && pnpm e2e:raw --project=chromium tests/git/git-changes-panel.spec.ts
cd apps/web && pnpm e2e:raw --project=mobile-chrome tests/git/mobile-pr-checkout-drift.spec.ts
git diff --check
```
## Documentation impact
The behavioral spec and ADR are the durable documentation for this fix. No public CLI, configuration,
installation, executor, or API contract changes, so `docs/public/**` does not require an update.
## Open questions
None. A guided “reconcile checkout” action is intentionally out of scope; it requires a separate
product decision about reset, backup, rebase, and conflict handling.
@@ -0,0 +1,88 @@
---
id: "01-upstream-status-contract"
title: "Publish complete upstream status evidence"
status: done
wave: 1
depends_on: []
plan: "plan.md"
spec: "../../specs/tasks/remote-contribution-tasks.md"
---
# Task 01: Publish Complete Upstream Status Evidence
Expose the local HEAD, upstream tip, and upstream-relative counts as one coherent status contract. The
backend already computes most of this data, but the frontend currently drops it and substitutes
base-branch divergence for Push state.
## Context
- `apps/backend/internal/agentctl/types/streams/git.go` already distinguishes `Ahead`/`Behind` from
`RemoteAhead`/`RemoteBehind`.
- `apps/backend/internal/agentctl/server/process/workspace_git_status.go` computes upstream counts with
`HEAD...RemoteBranch` and carries them across transient failures.
- `apps/backend/internal/agent/runtime/lifecycle/events.go` publishes the remote counts.
- `apps/web/lib/types/git-events.ts` and `apps/web/lib/ws/handlers/git-status.ts` do not retain those
counts in `GitStatusEntry`; the handler also drops existing head/base SHAs.
## TDD sequence
1. Extend backend status tests first. Assert `remote_head_commit` for aligned, local-ahead,
remote-ahead, and diverged graphs. Assert no-upstream clears the head and counts. Assert a transient
`rev-list` or `rev-parse` failure carries forward the complete prior upstream snapshot only while
local HEAD is unchanged.
2. Add lifecycle projection and frontend WebSocket handler tests that fail because
`remote_head_commit`, `remote_ahead`, `remote_behind`, `head_commit`, or `base_commit` is absent.
3. Implement the smallest contract changes, then refactor the upstream observation into a helper if
needed to keep Go lint limits.
## Implementation
- Add `RemoteHeadCommit string \`json:"remote_head_commit,omitempty"\`` to agentctl and lifecycle Git
status types.
- Resolve `<RemoteBranch>^{commit}` with the same sanitized ref boundary used for upstream counts. Do
not run `git fetch` or contact the provider from the polling loop.
- Treat upstream head and counts as one carry-forward unit. Reuse the prior values only when the prior
and current local HEAD are equal; otherwise leave failed evidence unknown rather than stale.
- Project the field through `PublishGitStatus`.
- Add `head_commit`, `base_commit`, `remote_head_commit`, `remote_ahead`, and `remote_behind` to
`GitStatusEntry`; copy them in `buildGitStatusEntry` and include upstream values in debug evidence.
- Preserve optional/zero-value compatibility for older status payloads.
## Acceptance
- One Git status event gives the frontend enough evidence to distinguish base divergence from upstream
divergence and identify the observed upstream tip.
- An absent upstream produces no upstream head and zero upstream counts.
- A transient secondary Git failure does not flash false zero counts, but evidence is not carried across
a changed local HEAD.
- No remote fetch, checkout mutation, provider call, or database change is introduced.
## Files likely touched
- `apps/backend/internal/agentctl/types/streams/git.go`
- `apps/backend/internal/agentctl/server/process/workspace_git_status.go`
- `apps/backend/internal/agentctl/server/process/workspace_git_status_test.go`
- `apps/backend/internal/agent/runtime/lifecycle/event_types.go`
- `apps/backend/internal/agent/runtime/lifecycle/events.go`
- lifecycle Git event tests beside those files
- `apps/web/lib/types/git-events.ts`
- `apps/web/lib/state/slices/session-runtime/types.ts`
- `apps/web/lib/ws/handlers/git-status.ts`
- `apps/web/lib/ws/handlers/git-status.test.ts`
## Verification
```bash
cd apps/backend && go test ./internal/agentctl/server/process ./internal/agent/runtime/lifecycle -run 'Test.*(RemoteAhead|RemoteBehind|RemoteHead|GitStatus)'
cd apps && pnpm --filter @kandev/web test -- lib/ws/handlers/git-status.test.ts
```
## Dependencies and parallelism
No dependencies. Run sequentially because Task 02 consumes the final wire/store shape.
## Output contract
Record red/green test evidence, the exact carry-forward rule, affected JSON fields, verification output,
and blockers. Set this task to `in_progress` before code changes and `done` after verification; update
the matching checkbox in `plan.md`.
@@ -0,0 +1,110 @@
---
id: "02-checkout-relation-and-action-semantics"
title: "Classify checkout drift and Git actions"
status: done
wave: 2
depends_on: ["01-upstream-status-contract"]
plan: "plan.md"
spec: "../../specs/tasks/remote-contribution-tasks.md"
---
# Task 02: Classify Checkout Drift and Git Actions
Create one tested relation model for the selected PR, local checkout, and upstream, then replace
base-ahead Push semantics with upstream-relative semantics.
## Context
- `usePRCommits` already returns ordered provider commits plus `loading` and `error`, but
`useChangesPanelPRData` discards the latter two states.
- `useSessionGit` exposes only base-relative `ahead`/`behind`, sets `canPush = ahead > 0`, and gives the
same values to multi-repository Push controls.
- `VcsSplitButton` also requires an `origin/<current-branch>` upstream, which excludes the dedicated
contribution remote by design.
- Task 01 makes local/upstream SHA and count evidence available in the frontend store.
## TDD sequence
1. Add a table-driven pure-function test covering `not_applicable`, `aligned`, `local_ahead`,
`provider_ahead`, `diverged`, and `unknown`.
2. Include negative cases: same message/different SHA does not match; loading/error does not mean an
empty or rewritten PR; an upstream head that differs from provider head does not prove local-ahead;
base `ahead` alone never proves a Push is available when an upstream exists.
3. Add session summary/fan-out tests for upstream Push/Pull counts and no-upstream fallback.
4. Implement the classifier, selected-PR relation hook, and SessionGit semantics.
## Relation rules
Use full commit identity only:
- No selected linked PR: `not_applicable`.
- Provider request loading, failed, empty unexpectedly, or required Git SHA absent: `unknown`.
- `localHead === providerHead`: `aligned`.
- Provider commit list contains `localHead`: `provider_ahead`.
- `upstreamHead === providerHead && remoteAhead > 0 && remoteBehind === 0`: `local_ahead`.
- Complete provider data with none of the above: `diverged`.
For a provider-ahead relation, Pull is allowed and Push is not. For local-ahead, Push is allowed for
`remoteAhead` commits. For diverged, both remote mutations are blocked. For unknown/non-PR flows, use
upstream counts when an upstream exists and retain the existing first-push fallback when it does not.
## Implementation
- Add a pure module beside session Git domain code with explicit input/output types; do not couple it
to React or rendered commit types.
- Add a selected-PR hook that combines `useReviewPRSelection`, `usePRCommits`, repository identity, and
the active repository's Git status. Preserve provider `loading` and `error` in its result.
- Extend `SessionGit` with `headCommit`, `remoteHeadCommit`, `remoteAhead`, `remoteBehind`, `pushAhead`,
and `pullBehind`. Keep `ahead`/`behind` base-relative.
- Update `deriveMultiRepoSummary` and `useRemoteOpsFanOut` gates so per-repository Push uses upstream
evidence. A repository with a configured upstream must never use base `ahead` as its Push count.
- Keep change-request creation behavior for a branch without an upstream: base commits can still make
Create PR the primary action and the initial push can set an upstream.
- Feed the relation result into Changes-panel data. Task 03 owns rendering and control copy.
## Acceptance
- The six old SHAs plus fifteen rewritten provider SHAs classify as `diverged`, not twenty-one
unpushed/pushed commits.
- Patch-equivalent commits with different SHAs remain distinct.
- A normal maintainer commit on top of the current provider head classifies as `local_ahead` and Push
reports one upstream-relative commit even if the branch is many commits ahead of `main`.
- A provider fast-forward containing local HEAD classifies as `provider_ahead` and offers Pull.
- Loading and provider errors remain observable and never claim a rewrite.
## Files likely touched
- `apps/web/hooks/domains/session/remote-contribution-relation.ts` (new)
- `apps/web/hooks/domains/session/remote-contribution-relation.test.ts` (new)
- `apps/web/hooks/domains/session/use-remote-contribution-relation.ts` (new)
- `apps/web/hooks/domains/github/use-pr-commits.ts`
- `apps/web/hooks/domains/session/use-session-git.ts`
- `apps/web/hooks/domains/session/use-session-git-summary.ts`
- existing SessionGit and summary tests
- `apps/web/components/task/changes-panel-data.tsx`
## Verification
```bash
cd apps && pnpm --filter @kandev/web test -- hooks/domains/session/remote-contribution-relation.test.ts hooks/domains/session/use-session-git-summary.test.ts hooks/domains/session/use-session.test.ts
cd apps/web && pnpm run typecheck
```
## Dependencies and parallelism
Depends on Task 01. Run sequentially; Task 03 consumes the classifier and action policy.
## Output contract
Record classifier truth-table evidence, upstream/no-upstream action results, red/green commands, and
any compatibility choices. Update this task and the plan checkbox when complete.
## Completion evidence
- The pure classifier covers not-applicable, aligned, local-ahead, provider-ahead, diverged, and
unknown states, including rewritten SHAs, loading/error state, missing Git evidence, and upstream
versus base-count fallbacks.
- `SessionGit` now carries upstream-relative Push/Pull counts and observed heads without changing the
existing base-relative divergence fields. Fan-out Push gating uses the upstream count when one is
configured.
- Focused relation, summary, and session Git tests passed. Web typecheck and lint passed.
@@ -0,0 +1,124 @@
---
id: "03-diverged-changes-ui-and-mobile-parity"
title: "Separate diverged histories across responsive UI"
status: done
wave: 3
depends_on: ["02-checkout-relation-and-action-semantics"]
plan: "plan.md"
spec: "../../specs/tasks/remote-contribution-tasks.md"
---
# Task 03: Separate Diverged Histories Across Responsive UI
Replace the misleading flat commit list with explicit provider and checkout histories when the shared
relation model reports divergence. Apply the same remote-action policy to desktop and mobile controls.
## TDD sequence
1. Add Changes-panel component tests with old local SHAs and rewritten provider SHAs. Assert separate
headings, one warning, correct row provenance, no flat 21-commit interpretation, and no green
unpushed marker on superseded contributor commits.
2. Add `VcsSplitButton` tests proving Push/Pull counts use upstream values, a contribution remote is a
valid upstream, base divergence pills stay unchanged, and diverged remote actions are disabled.
3. Add focused mobile Git menu tests proving the same actions are disabled while Commit remains
available.
4. Implement the responsive presentation, accessible state, translations, and action wiring.
## Changes panel implementation
- Pass the relation from `changes-panel-data.tsx` into `ChangesPanelBody` and timeline props.
- Keep `mergeCommits` unchanged for non-diverged flows. In diverged mode, construct two lists instead:
provider commits in provider order and local checkout commits in local log order.
- Add an explicit commit provenance/presentation field rather than overloading `pushed: boolean` for
diverged local rows. `CommitRow` must announce “current PR commit” or “local checkout commit” through
translated accessible text.
- Render a compact inline warning above the two lists. It explains that the contributor changed the PR
history, local work was preserved, and reconciliation is required before remote mutation.
- Provider rows may open provider commit details but expose no local amend/revert/reset menu. Local rows
retain their current local recovery actions.
- Do not change the PR Files, staged, unstaged, review progress, or single-scroll-owner layout.
- If provider commits fail to load, show the error state and keep the non-diverged/unknown presentation;
never show the force-push warning from an empty array.
## Desktop and mobile controls
- Update `VcsSplitButton` primary action and dropdown to consume `pushAhead`, `pullBehind`, and the
relation capabilities. Do not equate “has upstream” with `origin/<current-branch>`.
- Keep base `ahead`/`behind` only in the existing divergence/rebase context.
- Disable remote actions in diverged state and provide a tooltip or adjacent accessible reason; do not
leave an inert-looking control without explanation.
- Thread the same capability into `GitActionsDropdown` and `useMobileGitActions`. Disable Pull and the
Push submenu in diverged state; keep the 44px trigger and local Commit action.
- Use the shared Changes panel on mobile. No mobile-only banner, drawer, nested scroll region, or
compressed desktop control is added.
## Internationalization
Add keys for the warning, current-provider heading, local-checkout heading, row provenance, provider
history failure, and disabled remote-action reason in:
- `apps/web/src/locales/en/task.json`
- `apps/web/src/locales/pt-pt/task.json`
- `apps/web/src/locales/zh-cn/task.json`
- `apps/web/src/locales/pseudo/task.json`
Use `count` with `_one`/`_other` for any count-bearing copy and never compare translated strings.
## Acceptance
- Rewritten provider and local histories are visually and accessibly separate on desktop and mobile.
- Old contributor commits are labeled as checkout history, not as Kandev-authored or waiting to push.
- Push, force-push, and generic Pull cannot be invoked from the Changes panel, desktop split button, or
mobile Git menu while diverged.
- Local work and local recovery operations remain intact.
- Aligned/local-ahead/provider-ahead/non-PR presentations remain unchanged except for corrected
upstream Push/Pull counts.
- The shared mobile panel has no horizontal overflow and preserves its existing vertical scroll owner.
## Files likely touched
- `apps/web/components/task/changes-panel-data.tsx`
- `apps/web/components/task/changes-panel-body.tsx`
- `apps/web/components/task/changes-panel-timeline.tsx`
- `apps/web/components/task/changes-panel-repo-groups.tsx`
- `apps/web/components/task/changes-panel-helpers.ts`
- `apps/web/components/task/commit-row.tsx`
- Changes-panel unit/component tests beside those files
- `apps/web/components/vcs-split-button.tsx`
- `apps/web/components/vcs-split-button.test.ts`
- `apps/web/components/task/mobile/session-mobile-top-bar-git-controls.tsx`
- `apps/web/components/task/mobile/session-mobile-top-bar-git-controls.test.tsx` (new)
- four `task.json` locale files
## Verification
```bash
cd apps && pnpm --filter @kandev/web test -- components/task/changes-panel.test.ts components/task/changes-panel-remote.test.ts components/task/changes-panel-timeline-grouping.test.tsx components/vcs-split-button.test.ts components/task/mobile/session-mobile-top-bar-git-controls.test.tsx
cd apps/web && pnpm run typecheck
cd apps && pnpm run i18n:check && pnpm run i18n:ratchet
```
## Mobile parity note
Nearest exemplars: the shared Changes panel in `task-layout.tsx` and the existing
`session-mobile-top-bar-git-controls.tsx`. The new warning is content, not a new navigation surface. It
must remain inside the panel's current scroll owner and use the mobile menu's existing touch target.
## Dependencies and parallelism
Depends on Task 02. Run sequentially because desktop/mobile control wiring and Changes-panel props share
the same relation API.
## Output contract
Record screenshots or component assertions for both layouts, action-policy assertions, translation
checks, typecheck output, and blockers. Update this task and the plan checkbox when complete.
## Completion evidence
- Diverged histories render as separate current-PR and local-checkout sections with provenance labels,
a translated warning, preserved local recovery actions, and no misleading unpushed arrow.
- Desktop and Pixel 5 controls consume the same action policy: remote mutations are disabled while
local Commit remains available; the existing mobile scroll owner and touch target are preserved.
- Focused Changes-panel, commit-row, VCS split-button, and mobile Git-control tests passed. Typecheck,
lint, i18n check, and i18n ratchet passed.
@@ -0,0 +1,96 @@
---
id: "04-responsive-force-push-regression-e2e"
title: "Prove rewritten PR behavior end to end"
status: done
wave: 4
depends_on: ["03-diverged-changes-ui-and-mobile-parity"]
plan: "plan.md"
spec: "../../specs/tasks/remote-contribution-tasks.md"
---
# Task 04: Prove Rewritten PR Behavior End to End
Recreate the reported stale-checkout/current-PR mismatch in browser tests and prove that the behavior is
correct on desktop and mobile.
## Desktop scenario
Extend `apps/web/e2e/tests/git/git-changes-panel.spec.ts` with a deterministic local Git graph and
mocked current GitHub PR commits:
1. Create a task checkout with several commits representing the original contributor history and record
its local/upstream head.
2. Associate a mocked open PR whose current commit list uses different SHAs, simulating a force-pushed
rewrite. At least one rewritten commit may intentionally reuse a message and file totals to prove
metadata is not used for deduplication.
3. Open Changes and assert:
- the drift warning is visible;
- “Current PR commits” and “Local checkout commits” are separate;
- each list contains only its own SHAs/messages;
- the old local rows have the neutral checkout marker, not the green unpushed arrow;
- Push and Pull are unavailable with the reconciliation reason;
- no action mutated local HEAD or the worktree.
4. Add a safe local-ahead control case: provider/upstream head match and one local commit exists. Assert
one Push commit even when base `ahead` is larger.
Reuse `mockGitHubAddPRs`, `mockGitHubAddPRCommits`, and `mockGitHubAssociateTaskPR`. Extend the E2E helper
only if the test cannot establish the required upstream ref with its real temporary repository.
## Mobile scenario
Add `apps/web/e2e/tests/git/mobile-pr-checkout-drift.spec.ts` under the `mobile-chrome` project:
- Open the same kind of linked task on Pixel 5 dimensions.
- Enter the shared Changes panel through the normal mobile navigation.
- Assert the warning and both histories are readable without horizontal overflow.
- Open the 44px Git actions trigger and assert Pull/Push are disabled while Commit remains available.
- Assert the panel keeps one vertical scroll owner and the warning/headings can be reached by ordinary
touch scrolling.
Use stable roles, translated accessible names, and `data-testid` only where no semantic locator exists.
Do not use fixed sleeps.
## Acceptance
- The original visual failure is reproduced by test data and fails before Tasks 01–03.
- Desktop and mobile tests pass after the fix.
- Tests prove both containment of a rewritten history and preservation of an ordinary local-ahead flow.
- The test does not depend on a live GitHub account or network timing.
## Files likely touched
- `apps/web/e2e/tests/git/git-changes-panel.spec.ts`
- `apps/web/e2e/tests/git/mobile-pr-checkout-drift.spec.ts` (new)
- `apps/web/e2e/helpers/api-client.ts` only if a narrow mock/status helper is required
- relevant Changes/Session page object only if semantic locators cannot express the new state
## Verification
Run the focused specs first, then the related browser project if time permits:
```bash
cd apps/web && pnpm e2e:raw --project=chromium tests/git/git-changes-panel.spec.ts --grep 'rewritten PR|upstream push count'
cd apps/web && pnpm e2e:raw --project=mobile-chrome tests/git/mobile-pr-checkout-drift.spec.ts
```
## Dependencies and parallelism
Depends on Task 03. Run after the UI contract is stable; this task may expose wiring defects that must
be fixed in the owning files rather than hidden in test helpers.
## Output contract
Record the red failure signature, green desktop/mobile command output, screenshots or traces for any
failure investigated, viewport/scroll assertions, and blockers. Update this task and the plan checkbox
when complete.
## Completion evidence
- The browser fixture initially exposed a missing local `origin/main` tracking ref. The regression
setup now restores the temporary remote URL, fetches the ref, and establishes the graph without
relying on fixture history.
- Desktop rewrite and local-ahead scenarios passed with Chromium; the rewritten-history scenario passed
on Pixel 5. Assertions cover separate histories, accurate provenance, disabled remote actions,
unchanged local HEAD/worktree, one scroll owner, and no horizontal overflow.
- Screenshot capture hooks are present for the desktop and mobile regression states; fresh PR assets
will be captured during final delivery verification.
+65 -2
View File
@@ -1,6 +1,7 @@
---
status: approved
created: 2026-08-04
updated: 2026-08-10
owner: product
---
@@ -14,6 +15,11 @@ review association before an agent can make a useful change. Kandev should accep
URL at task creation, prepare the contributor's exact branch, and push commits back to that branch
without making `create_task_kandev` materially larger.
The contributor can update or rewrite that branch after the task starts. Kandev must not present the
old checkout and the provider's current change as one continuous history, label old contributor
commits as maintainer-authored work waiting to be pushed, or offer a remote mutation whose safety has
not been established. It must preserve local work while making the drift explicit.
## What
- The existing `create_task_kandev.repositories[].repository_url` value accepts a canonical repository
@@ -41,8 +47,25 @@ without making `create_task_kandev` materially larger.
server-authored contribution identity and branch guidance.
- Ordinary repository URLs retain their current behavior, including default branch resolution,
normal `origin` pushes, and new-PR creation.
- Git status keeps two separate divergence concepts: `ahead`/`behind` compare the checkout with the
target base branch, while `remote_ahead`/`remote_behind` compare it with its configured upstream.
Push and pull affordances use the upstream-relative values; review scope and base-branch rebase
affordances continue to use the base-relative values.
- For an associated contribution, Kandev compares the local HEAD and upstream snapshot with the
provider's current commit history using commit identity and ancestry evidence. It never infers
equivalence from commit message, author, timestamp, file statistics, or patch similarity.
- When the provider history no longer contains the local HEAD and the histories cannot be proven to be
a safe local-ahead or provider-ahead relationship, the Changes panel shows the current remote change
and local checkout as separate histories. Local work remains intact. Push, force-push, and generic
pull actions are unavailable until the histories are reconciled outside this flow.
- A provider-ahead history that still contains local HEAD is a safe fast-forward case: the UI may offer
Pull, but must not label the existing local commits as unpushed work. A local-ahead history whose
tracked upstream equals the provider head may offer a normal Push for exactly `remote_ahead` commits.
Decision: [ADR-2026-08-04-remote-contribution-bindings](../../decisions/2026-08-04-remote-contribution-bindings.md).
Decisions:
[ADR-2026-08-04-remote-contribution-bindings](../../decisions/2026-08-04-remote-contribution-bindings.md)
and
[ADR-2026-08-10-remote-contribution-head-drift](../../decisions/2026-08-10-remote-contribution-head-drift.md).
## Data model
@@ -114,6 +137,9 @@ internal boundary.
| Fork does not allow maintainer collaboration | Task creation fails before persistence with provider-specific remediation guidance. |
| Task persists but the existing-change association fails | Kandev compensates the newly created task and returns failure; it does not launch an agent. |
| Checkout SHA no longer matches the source branch during preparation | Launch fails without checking out or pushing a different revision; retry resolves fresh provider state. |
| Provider branch advances after launch and still contains local HEAD | Kandev identifies a provider-ahead fast-forward, shows the current provider history, and offers Pull instead of Push. |
| Provider branch is rewritten after launch and no longer contains local HEAD | Kandev preserves the checkout, separates local and provider histories, explains the drift, and disables unsafe remote actions. |
| Current provider commits cannot be loaded | Kandev does not assert that a rewrite occurred. It shows the provider error and derives Push/Pull only from available upstream evidence. |
| Effective Git credentials cannot dry-run a push to the source branch | The task remains durable, but the session does not start and exposes an actionable credential/collaboration error. |
| Contribution binding is missing, malformed, or an unknown version | Runtime preparation and managed source-scope issuance fail closed. |
| Agent attempts a normal create-PR action | Kandev reuses the existing association and does not open a second remote change. |
@@ -126,6 +152,10 @@ from the binding. Credential leases and preflight results are ephemeral and are
launch or resume. A moved or deleted source branch causes a later launch to fail visibly rather than
silently falling back to the target repository.
The original contribution `head_sha` remains creation-time provenance. It is not mutated to pretend an
existing checkout follows a later provider rewrite. Live provider commits and Git status are observed
state. Neither observation automatically resets, rebases, merges, or deletes the task checkout.
## Scenarios
### Create from a same-repository GitHub pull request
@@ -162,6 +192,36 @@ GIVEN a contribution was resolved but its source branch moved before worktree pr
WHEN Kandev prepares the task
THEN preparation fails rather than checking out the new head or pushing from the stale SHA
### Show a provider fast-forward safely
GIVEN a running contribution task whose provider branch advances without rewriting local HEAD
WHEN Kandev loads the current provider commits
THEN the Changes panel treats the provider as ahead, does not mark the existing commits as local work
to push, and offers Pull rather than Push
### Separate a rewritten provider history
GIVEN a running contribution task whose provider branch is force-pushed and no longer contains local
HEAD
WHEN Kandev loads the current provider commits
THEN the Changes panel warns that the contribution changed, renders "Current PR commits" separately
from "Local checkout commits", preserves every local commit, and offers no Push, force-push, or generic
Pull action
### Keep ordinary local-ahead work pushable
GIVEN a contribution checkout whose upstream equals the provider's current head
AND the maintainer creates commits on top
WHEN Kandev computes Git status
THEN Push reports only the commits absent from the upstream and the provider commits are not duplicated
### Avoid guessing when provider history is unavailable
GIVEN Kandev cannot load the current provider commit list
WHEN the Changes panel renders the checkout
THEN it reports that provider history is unavailable, does not claim the branch was rewritten, and
does not compare commits by message or patch similarity
### Preserve ordinary repository creation
GIVEN an ordinary GitHub, GitLab, or provider-neutral repository URL
@@ -181,6 +241,9 @@ mentions pull and merge request URLs
- Creating tasks from issues, review comments, or arbitrary commit URLs.
- Azure DevOps or additional source-control providers.
- Multiple remote contributions in one create call.
- Force pushes, branch renames, retargeting, merging, or changing collaboration settings.
- Kandev performing force pushes, branch renames, retargeting, merging, or changing collaboration
settings.
- Automatically resetting, rebasing, merging, or replacing an existing checkout after provider drift.
- A guided history-reconciliation workflow; this iteration detects and contains the unsafe state.
- Copying remote titles, bodies, comments, or diffs into trusted prompts.
- Guaranteeing write access after credentials or provider permissions change during a running session.