diff --git a/apps/backend/internal/agentctl/server/process/git_log.go b/apps/backend/internal/agentctl/server/process/git_log.go index ddd5d6de0b..b48007705e 100644 --- a/apps/backend/internal/agentctl/server/process/git_log.go +++ b/apps/backend/internal/agentctl/server/process/git_log.go @@ -299,15 +299,15 @@ func (g *GitOperator) parseCommitDiff(output string) map[string]interface{} { } header := lines[0] - // Extract path from "diff --git a/path b/path" - headerParts := strings.Split(header, " ") - if len(headerParts) < 4 { + // Extract path from "diff --git a/ b/". + // We cannot split by space because paths may contain spaces. + // Instead, strip the known prefix and find the " b/" separator. + pathsPart := strings.TrimPrefix(header, "diff --git ") + bIdx := strings.Index(pathsPart, " b/") + if bIdx == -1 { continue } - - // Get the b/path part and remove the "b/" prefix - bPath := headerParts[len(headerParts)-1] - filePath := strings.TrimPrefix(bPath, "b/") + filePath := pathsPart[bIdx+3:] // Determine file status from diff content status := fileStatusModified diff --git a/apps/backend/internal/agentctl/server/process/git_test.go b/apps/backend/internal/agentctl/server/process/git_test.go index d74eace592..66e889cc7e 100644 --- a/apps/backend/internal/agentctl/server/process/git_test.go +++ b/apps/backend/internal/agentctl/server/process/git_test.go @@ -2,6 +2,7 @@ package process import ( "context" + "os" "path/filepath" "strings" "testing" @@ -50,3 +51,39 @@ func TestGitOperatorPush_PreservesExistingUpstream(t *testing.T) { t.Fatalf("upstream after push = %q, want %q", after, "origin/feature/pr-branch") } } + +func TestParseCommitDiff_PathsWithSpaces(t *testing.T) { + repoDir, cleanup := setupTestRepo(t) + defer cleanup() + + log := newTestLogger(t) + + // Create a file with spaces in its path, commit it, then verify parseCommitDiff + // extracts the correct unquoted file path. + dir := filepath.Join(repoDir, "path with spaces") + if err := os.MkdirAll(dir, 0o755); err != nil { + t.Fatalf("failed to create dir: %v", err) + } + writeFile(t, dir, "file.md", "hello world\n") + runGit(t, repoDir, "add", ".") + runGit(t, repoDir, "commit", "-m", "add spaced path") + sha := strings.TrimSpace(runGit(t, repoDir, "rev-parse", "HEAD")) + + gitOp := NewGitOperator(repoDir, log, nil) + result, err := gitOp.ShowCommit(context.Background(), sha) + if err != nil { + t.Fatalf("ShowCommit error: %v", err) + } + if !result.Success { + t.Fatalf("ShowCommit failed: %+v", result) + } + + expectedPath := "path with spaces/file.md" + if _, exists := result.Files[expectedPath]; !exists { + keys := make([]string, 0, len(result.Files)) + for k := range result.Files { + keys = append(keys, k) + } + t.Errorf("expected Files to contain key %q, got keys: %v", expectedPath, keys) + } +} diff --git a/apps/backend/internal/agentctl/server/process/workspace_files_test.go b/apps/backend/internal/agentctl/server/process/workspace_files_test.go index f9012f6727..24c8611bcd 100644 --- a/apps/backend/internal/agentctl/server/process/workspace_files_test.go +++ b/apps/backend/internal/agentctl/server/process/workspace_files_test.go @@ -93,6 +93,9 @@ func TestResolveNonExistentPath(t *testing.T) { }) t.Run("permission error is propagated", func(t *testing.T) { + if os.Getuid() == 0 { + t.Skip("skipping permission test: root bypasses filesystem permission checks") + } // Create a directory, then make it unreadable restrictedDir := filepath.Join(tmpDir, "restricted") if err := os.Mkdir(restrictedDir, 0o755); err != nil { diff --git a/apps/backend/internal/agentctl/server/process/workspace_git_diff.go b/apps/backend/internal/agentctl/server/process/workspace_git_diff.go index 10f0af1aa6..d068ad17b0 100644 --- a/apps/backend/internal/agentctl/server/process/workspace_git_diff.go +++ b/apps/backend/internal/agentctl/server/process/workspace_git_diff.go @@ -37,7 +37,9 @@ func (wt *WorkspaceTracker) enrichWithUnstagedDiff(ctx context.Context, update * if line == "" { continue } - parts := strings.Fields(line) + // numstat uses tab-separated values: \t\t + // Split by tab (not whitespace) to preserve spaces in file paths. + parts := strings.SplitN(line, "\t", 3) if len(parts) < 3 { continue } @@ -85,7 +87,8 @@ func (wt *WorkspaceTracker) enrichWithStagedDiff(ctx context.Context, update *ty if line == "" { continue } - parts := strings.Fields(line) + // numstat uses tab-separated values: \t\t + parts := strings.SplitN(line, "\t", 3) if len(parts) < 3 { continue } diff --git a/apps/backend/internal/agentctl/server/process/workspace_git_status.go b/apps/backend/internal/agentctl/server/process/workspace_git_status.go index 37f1b4a162..85c2cb4e6e 100644 --- a/apps/backend/internal/agentctl/server/process/workspace_git_status.go +++ b/apps/backend/internal/agentctl/server/process/workspace_git_status.go @@ -180,11 +180,31 @@ func (wt *WorkspaceTracker) parseGitStatusOutput(ctx context.Context, update *ty return nil } +// unquoteGitPath strips git's C-style quoting from paths that contain spaces or +// special characters. Git wraps such paths in double quotes in porcelain output +// (e.g. "path with spaces/file.md"). Go's strconv.Unquote handles the same +// escaping rules (backslash sequences for tabs, newlines, quotes, etc.). +func unquoteGitPath(p string) string { + if len(p) >= 2 && p[0] == '"' && p[len(p)-1] == '"' { + if unquoted, err := strconv.Unquote(p); err == nil { + return unquoted + } + } + return p +} + // applyPorcelainLine parses a single git status --porcelain line and updates the status update. func (wt *WorkspaceTracker) applyPorcelainLine(line string, update *types.GitStatusUpdate) { indexStatus := line[0] // Staged status (X) workTreeStatus := line[1] // Unstaged status (Y) - filePath := strings.TrimSpace(line[3:]) + rawPath := strings.TrimSpace(line[3:]) + + // For renames the format is "old -> new" (each part may be independently + // quoted), so we must split first and unquote each part separately. + filePath := rawPath + if indexStatus != 'R' { + filePath = unquoteGitPath(rawPath) + } fileInfo := types.FileInfo{Path: filePath} @@ -223,10 +243,11 @@ func (wt *WorkspaceTracker) applyPorcelainLine(line string, update *types.GitSta case indexStatus == 'R': fileInfo.Status = "renamed" fileInfo.Staged = true - // Renamed files have format "old -> new" - if idx := strings.Index(filePath, " -> "); idx != -1 { - fileInfo.OldPath = filePath[:idx] - fileInfo.Path = filePath[idx+4:] + // Renamed files have format "old -> new"; each part may be quoted independently. + if idx := strings.Index(rawPath, " -> "); idx != -1 { + fileInfo.OldPath = unquoteGitPath(rawPath[:idx]) + filePath = unquoteGitPath(rawPath[idx+4:]) + fileInfo.Path = filePath } update.Renamed = append(update.Renamed, filePath) } diff --git a/apps/backend/internal/agentctl/server/process/workspace_git_status_test.go b/apps/backend/internal/agentctl/server/process/workspace_git_status_test.go new file mode 100644 index 0000000000..64eb1f0372 --- /dev/null +++ b/apps/backend/internal/agentctl/server/process/workspace_git_status_test.go @@ -0,0 +1,140 @@ +package process + +import ( + "context" + "os" + "path/filepath" + "testing" +) + +func TestUnquoteGitPath(t *testing.T) { + tests := []struct { + name string + in string + want string + }{ + {"plain path", "simple-path.txt", "simple-path.txt"}, + {"path with spaces", `"path with spaces/file.md"`, "path with spaces/file.md"}, + {"path with tab", `"path\twith\ttab"`, "path\twith\ttab"}, + {"path with backslash", `"path\\backslash"`, `path\backslash`}, + {"path with quotes", `"path \"quoted\""`, `path "quoted"`}, + {"empty quotes", `""`, ""}, + {"single char not quoted", "a", "a"}, + {"mismatched quote", `"not closed`, `"not closed`}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got := unquoteGitPath(tt.in) + if got != tt.want { + t.Errorf("unquoteGitPath(%q) = %q, want %q", tt.in, got, tt.want) + } + }) + } +} + +func TestGetGitStatus_PathsWithSpaces(t *testing.T) { + repoDir, cleanup := setupTestRepo(t) + defer cleanup() + + log := newTestLogger(t) + wt := NewWorkspaceTracker(repoDir, log) + ctx := context.Background() + + // Create a directory and file with spaces in the path. + dir := filepath.Join(repoDir, "path with spaces") + if err := os.MkdirAll(dir, 0o755); err != nil { + t.Fatalf("failed to create dir: %v", err) + } + writeFile(t, dir, "file.md", "initial content") + runGit(t, repoDir, "add", ".") + runGit(t, repoDir, "commit", "-m", "Add file with spaces in path") + + // Modify the file to create an unstaged change. + writeFile(t, dir, "file.md", "modified content") + + status, err := wt.getGitStatus(ctx) + if err != nil { + t.Fatalf("failed to get git status: %v", err) + } + + expectedPath := "path with spaces/file.md" + + // The file should appear in Modified with an unquoted path. + found := false + for _, p := range status.Modified { + if p == expectedPath { + found = true + break + } + } + if !found { + t.Errorf("expected %q in Modified list, got %v", expectedPath, status.Modified) + } + + // The Files map key should be the unquoted path. + fileInfo, exists := status.Files[expectedPath] + if !exists { + t.Fatalf("expected Files map to contain key %q, got keys: %v", + expectedPath, mapKeys(status.Files)) + } + if fileInfo.Status != "modified" { + t.Errorf("expected status=modified, got %q", fileInfo.Status) + } + + // Diff content should be populated (enrichWithDiffData uses the same key). + if fileInfo.Diff == "" { + t.Error("expected non-empty Diff for file with spaces in path") + } +} + +func TestGetGitStatus_UntrackedFileWithSpaces(t *testing.T) { + repoDir, cleanup := setupTestRepo(t) + defer cleanup() + + log := newTestLogger(t) + wt := NewWorkspaceTracker(repoDir, log) + ctx := context.Background() + + // Create an untracked file with spaces in the path. + dir := filepath.Join(repoDir, "dir with spaces") + if err := os.MkdirAll(dir, 0o755); err != nil { + t.Fatalf("failed to create dir: %v", err) + } + writeFile(t, dir, "new file.txt", "hello world") + + status, err := wt.getGitStatus(ctx) + if err != nil { + t.Fatalf("failed to get git status: %v", err) + } + + expectedPath := "dir with spaces/new file.txt" + + found := false + for _, p := range status.Untracked { + if p == expectedPath { + found = true + break + } + } + if !found { + t.Errorf("expected %q in Untracked list, got %v", expectedPath, status.Untracked) + } + + fileInfo, exists := status.Files[expectedPath] + if !exists { + t.Fatalf("expected Files map to contain key %q, got keys: %v", + expectedPath, mapKeys(status.Files)) + } + if fileInfo.Diff == "" { + t.Error("expected non-empty synthetic Diff for untracked file with spaces") + } +} + +// mapKeys returns the keys of a map for diagnostic output. +func mapKeys[V any](m map[string]V) []string { + keys := make([]string, 0, len(m)) + for k := range m { + keys = append(keys, k) + } + return keys +} diff --git a/apps/web/e2e/tests/git/git-changes-panel.spec.ts b/apps/web/e2e/tests/git/git-changes-panel.spec.ts index 5c16c72411..ba590cc0b3 100644 --- a/apps/web/e2e/tests/git/git-changes-panel.spec.ts +++ b/apps/web/e2e/tests/git/git-changes-panel.spec.ts @@ -213,6 +213,77 @@ test.describe("Git Changes Panel", () => { git.deleteFile("new-feature.ts"); }); + /** + * Verifies that files with spaces in their path are shown correctly in the + * Changes panel and that their diff content is visible (not "No changes"). + * Regression test for: git status --porcelain quotes paths with spaces, + * and the backend must unquote them so diff lookups succeed. + */ + test("shows modified files with spaces in path", async ({ + testPage, + apiClient, + seedData, + backend, + }) => { + const profile = await createStandardProfile(apiClient, "Git Spaces Profile"); + + await apiClient.createTaskWithAgent(seedData.workspaceId, "Git Spaces Test", profile.id, { + description: "Testing paths with spaces", + workflow_id: seedData.workflowId, + workflow_step_id: seedData.startStepId, + repository_ids: [seedData.repositoryId], + }); + + const session = await openTaskSession(testPage, "Git Spaces Test"); + + // Set up git helper + 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); + + // Create a file inside a directory with spaces + const dirWithSpaces = path.join(repoDir, "path with spaces"); + fs.mkdirSync(dirWithSpaces, { recursive: true }); + fs.writeFileSync(path.join(dirWithSpaces, "file.md"), "initial content"); + git.stageAll(); + git.commit("Add file with spaces in path"); + + // Modify the file to create an unstaged change + fs.writeFileSync(path.join(dirWithSpaces, "file.md"), "modified content"); + + // Click the Changes tab + await session.clickTab("Changes"); + await expect(session.changes).toBeVisible({ timeout: 10_000 }); + + // The file should appear in the unstaged section with its unquoted path + await expect(testPage.getByTestId("unstaged-files-section")).toBeVisible({ timeout: 15_000 }); + await expect(session.changes.getByText("file.md")).toBeVisible({ timeout: 15_000 }); + + // Click the file to open its diff and verify content is shown + await session.changes.getByText("file.md").click(); + + // Verify the diff viewer shows actual diff content (not empty / "No changes"). + // Pierre Diffs renders in a shadow DOM — check all diffs-container elements. + await testPage.waitForFunction( + (searchText: string) => { + for (const container of document.querySelectorAll("diffs-container")) { + const shadow = container.shadowRoot; + if (shadow?.textContent?.includes(searchText)) return true; + } + return false; + }, + "modified content", + { timeout: 30_000 }, + ); + }); + /** * Verifies that commits appear in the commits section after committing staged files. * This tests the full flow: create file → stage → commit → verify in UI.