TypeScript
fix(server): changed files keep their real paths for renames and non-ASCII names (#20175)
Atharvsinh Jadav771fd93fc591
diff --git a/apps/server/src/vcs/GitVcsDriverCore.test.ts b/apps/server/src/vcs/GitVcsDriverCore.test.tsindex 7e65262e79c..f797cc7f145 100644--- a/apps/server/src/vcs/GitVcsDriverCore.test.ts+++ b/apps/server/src/vcs/GitVcsDriverCore.test.ts@@ -333,7 +333,7 @@ it.effect("uses stable diagnostics for every parsed non-repository command", ()assert.deepStrictEqual(commands, [{ args: ["rev-parse", "--git-path", "index"], lcAll: "C" },- { args: ["status", "--porcelain=2", "--branch"], lcAll: "C" },+ { args: ["status", "--porcelain=2", "--branch", "-z"], lcAll: "C" },{ args: ["rev-parse", "--abbrev-ref", "HEAD"], lcAll: "C" },{ args: ["rev-parse", "--git-common-dir"], lcAll: "C" },]);@@ -2643,6 +2643,97 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => {}),);+ it.effect("reports renamed and non-ASCII files by paths that can be committed", () =>+ Effect.gen(function* () {+ const cwd = yield* makeTmpDir();+ yield* initRepoWithCommit(cwd);+ yield* writeTextFile(cwd, "src/old.ts", "one\ntwo\nthree\n");+ yield* writeTextFile(cwd, "café notes.md", "draft\n");+ yield* git(cwd, ["add", "."]);+ yield* git(cwd, ["commit", "-m", "add files"]);+ yield* git(cwd, ["mv", "src/old.ts", "src/new.ts"]);+ yield* writeTextFile(cwd, "src/new.ts", "one\ntwo\nthree\nfour\n");+ yield* writeTextFile(cwd, "café notes.md", "draft\nedit\n");+ const driver = yield* GitVcsDriver.GitVcsDriver;++ const status = yield* driver.statusDetails(cwd);++ assert.deepEqual(status.workingTree.files, [+ { path: "café notes.md", insertions: 1, deletions: 0 },+ { path: "src/new.ts", insertions: 1, deletions: 0 },+ { path: "src/old.ts", insertions: 0, deletions: 0 },+ ]);+ yield* driver.commit(cwd, "Commit selection", "", {+ stage: { filePaths: status.workingTree.files.map((file) => file.path) },+ });+ assert.equal(yield* git(cwd, ["status", "--porcelain"]), "");+ }),+ );++ it.effect("commits selected files from a nested project directory", () =>+ Effect.gen(function* () {+ const path = yield* Path.Path;+ // A root basename ending in whitespace catches a root lookup that trims Git's output.+ const cwd = path.join(yield* makeTmpDir(), "repo ");+ yield* (yield* FileSystem.FileSystem).makeDirectory(cwd);+ yield* initRepoWithCommit(cwd);+ yield* writeTextFile(cwd, "nested/tracked.txt", "one\n");+ yield* git(cwd, ["add", "."]);+ yield* git(cwd, ["commit", "-m", "add nested file"]);+ yield* writeTextFile(cwd, "nested/tracked.txt", "one\ntwo\n");+ yield* writeTextFile(cwd, "nested/new.txt", "new\n");+ yield* writeTextFile(cwd, "README.md", "# test\nleft out\n");+ const nestedCwd = path.join(cwd, "nested");+ const driver = yield* GitVcsDriver.GitVcsDriver;++ const status = yield* driver.statusDetails(nestedCwd);++ assert.deepEqual(status.workingTree.files, [+ { path: "nested/new.txt", insertions: 0, deletions: 0 },+ { path: "nested/tracked.txt", insertions: 1, deletions: 0 },+ { path: "README.md", insertions: 1, deletions: 0 },+ ]);+ // The root is what the paths above are relative to, not the nested cwd, and it keeps+ // the trailing space so the resolved editor target is the file that exists.+ assert.equal(status.workingTree.rootPath, NodeFS.realpathSync.native(cwd));+ assert.equal(+ NodeFS.existsSync(path.join(status.workingTree.rootPath!, "nested", "new.txt")),+ true,+ );+ yield* driver.commit(nestedCwd, "Commit nested selection", "", {+ stage: { filePaths: ["nested/new.txt", "nested/tracked.txt"] },+ });+ assert.equal(yield* git(cwd, ["status", "--porcelain"]), "M README.md");+ }),+ );++ it.effect("reports the linked worktree as the root of a nested directory in it", () =>+ Effect.gen(function* () {+ const cwd = yield* makeTmpDir();+ const worktreePath = yield* makeTmpDir("git-vcs-driver-linked-");+ yield* initRepoWithCommit(cwd);+ yield* writeTextFile(cwd, "nested/tracked.txt", "one\n");+ yield* git(cwd, ["add", "."]);+ yield* git(cwd, ["commit", "-m", "add nested file"]);+ yield* git(cwd, ["worktree", "add", "-b", "feature/linked", worktreePath]);+ yield* writeTextFile(worktreePath, "nested/tracked.txt", "one\ntwo\n");+ yield* writeTextFile(worktreePath, "nested/new.txt", "new\n");+ const nestedCwd = (yield* Path.Path).join(worktreePath, "nested");+ const driver = yield* GitVcsDriver.GitVcsDriver;++ const status = yield* driver.statusDetails(nestedCwd);++ assert.deepEqual(status.workingTree.files, [+ { path: "nested/new.txt", insertions: 0, deletions: 0 },+ { path: "nested/tracked.txt", insertions: 1, deletions: 0 },+ ]);+ assert.equal(+ NodeFS.realpathSync.native(status.workingTree.rootPath!),+ NodeFS.realpathSync.native(worktreePath),+ );+ }),+ );+it.effect("reports default-branch delta separately from upstream delta", () =>Effect.gen(function* () {const cwd = yield* makeTmpDir();diff --git a/apps/server/src/vcs/GitVcsDriverCore.ts b/apps/server/src/vcs/GitVcsDriverCore.tsindex 3225a7fe455..f3120f5ebef 100644--- a/apps/server/src/vcs/GitVcsDriverCore.ts+++ b/apps/server/src/vcs/GitVcsDriverCore.ts@@ -185,30 +185,6 @@ function parseBranchAb(value: string): { ahead: number; behind: number } {};}-function parseNumstatEntries(- stdout: string,-): Array<{ path: string; insertions: number; deletions: number }> {- const entries: Array<{ path: string; insertions: number; deletions: number }> = [];- for (const line of stdout.split(/\r?\n/g)) {- if (line.trim().length === 0) continue;- const [addedRaw, deletedRaw, ...pathParts] = line.split("\t");- const rawPath =- pathParts.length > 1 ? (pathParts.at(-1) ?? "").trim() : pathParts.join("\t").trim();- if (rawPath.length === 0) continue;- const added = Number.parseInt(addedRaw ?? "0", 10);- const deleted = Number.parseInt(deletedRaw ?? "0", 10);- const renameArrowIndex = rawPath.indexOf(" => ");- const normalizedPath =- renameArrowIndex >= 0 ? rawPath.slice(renameArrowIndex + " => ".length).trim() : rawPath;- entries.push({- path: normalizedPath.length > 0 ? normalizedPath : rawPath,- insertions: Number.isFinite(added) ? added : 0,- deletions: Number.isFinite(deleted) ? deleted : 0,- });- }- return entries;-}-function parseReviewNumstat(stdout: string): ReviewDiffFileStat[] {const fields = stdout.split("\0");const files: ReviewDiffFileStat[] = [];@@ -228,25 +204,20 @@ function parseReviewNumstat(stdout: string): ReviewDiffFileStat[] {return files;}-function parsePorcelainPath(line: string): string | null {- if (line.startsWith("? ") || line.startsWith("! ")) {- const simple = line.slice(2).trim();- return simple.length > 0 ? simple : null;- }-- if (!(line.startsWith("1 ") || line.startsWith("2 ") || line.startsWith("u "))) {- return null;- }-- const tabIndex = line.indexOf("\t");- if (tabIndex >= 0) {- const fromTab = line.slice(tabIndex + 1);- const [filePath] = fromTab.split("\t");- return filePath?.trim().length ? filePath.trim() : null;- }+// Space-separated fields precede the path in each porcelain v2 record type. The path itself+// may contain spaces, so it is everything after them.+const PORCELAIN_V2_FIELDS_BEFORE_PATH: Record<string, number> = {+ "1": 8,+ "2": 9,+ u: 10,+ "?": 1,+ "!": 1,+};- const parts = line.trim().split(/\s+/g);- const filePath = parts.at(-1) ?? "";+function parsePorcelainPath(record: string): string | null {+ const fieldsBeforePath = PORCELAIN_V2_FIELDS_BEFORE_PATH[record[0] ?? ""];+ if (fieldsBeforePath === undefined) return null;+ const filePath = record.split(" ").slice(fieldsBeforePath).join(" ");return filePath.length > 0 ? filePath : null;}@@ -1347,7 +1318,12 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*],{ concurrency: 2 },);- const worktreeRootOutput = worktreeRootResult.stdout.trim();+ // Git terminates --show-toplevel with exactly one "\n" on every platform (stdout is+ // binary mode on Windows). Whitespace before it belongs to the path and must survive,+ // because this root becomes the editor target for every repository-relative status path.+ const worktreeRootOutput = worktreeRootResult.stdout.endsWith("\n")+ ? worktreeRootResult.stdout.slice(0, -1)+ : worktreeRootResult.stdout;const worktreeRoot =worktreeRootResult.exitCode === 0 && worktreeRootOutput.length > 0? path.normalize(@@ -1891,6 +1867,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*"status","--porcelain=2","--branch",+ "-z",...(includeDivergence ? [] : ["--no-ahead-behind"]),];const indexResult = yield* executeGitWithStableDiagnostics(@@ -1968,48 +1945,37 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*Effect.catchTags({ GitCommandError: () => Effect.succeed(null) }),);const statusCacheKey = repositoryPaths?.gitCommonDir;- const [numstatStdout, defaultBranch, hasPrimaryRemote] = yield* Effect.all(+ const [numstatEntries, defaultBranch, hasPrimaryRemote] = yield* Effect.all([// Plumbing, because porcelain `git diff` rewrites the index even with// GIT_OPTIONAL_LOCKS=0. -M keeps porcelain's rename detection.executeGitWithStableDiagnostics("GitVcsDriver.statusDetails.numstat",cwd,- ["diff-index", "-M", "--numstat", "HEAD", "--"],+ ["diff-index", "-M", "--numstat", "-z", "HEAD", "--"],{ allowNonZeroExit: true },).pipe(Effect.flatMap((result) => {- if (result.exitCode === 0) return Effect.succeed(result.stdout);+ if (result.exitCode === 0) return Effect.succeed(parseReviewNumstat(result.stdout));if (isUnbornHeadStderr(result.stderr)) {return Effect.map(Effect.all([runGitStdout("GitVcsDriver.statusDetails.numstat.unborn", cwd, ["diff-files","--numstat",+ "-z",]),runGitStdout("GitVcsDriver.statusDetails.numstat.unborn.staged", cwd, ["diff","--cached","--numstat",+ "-z",]),]),- ([unstagedStdout, stagedStdout]) => {- const staged = parseNumstatEntries(stagedStdout);- const unstaged = parseNumstatEntries(unstagedStdout);- const map = new Map<string, { insertions: number; deletions: number }>();- for (const entry of [...staged, ...unstaged]) {- const existing = map.get(entry.path) ?? {- insertions: 0,- deletions: 0,- };- existing.insertions += entry.insertions;- existing.deletions += entry.deletions;- map.set(entry.path, existing);- }- return Array.from(map.entries())- .map(([p, s]) => `${s.insertions}\t${s.deletions}\t${p}`)- .join("\n");- },+ ([unstagedStdout, stagedStdout]) => [+ ...parseReviewNumstat(stagedStdout),+ ...parseReviewNumstat(unstagedStdout),+ ],);}return Effect.fail(@@ -2017,7 +1983,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*...gitCommandContext({operation: "GitVcsDriver.statusDetails.numstat",cwd,- args: ["diff-index", "-M", "--numstat", "HEAD", "--"],+ args: ["diff-index", "-M", "--numstat", "-z", "HEAD", "--"],}),detail: "git diff-index HEAD --numstat failed.",exitCode: result.exitCode,@@ -2046,7 +2012,9 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*let hasWorkingTreeChanges = false;const changedFilesWithoutNumstat = new Set<string>();- for (const line of statusStdout.split(/\r?\n/g)) {+ const statusRecords = statusStdout.split("\0");+ for (let index = 0; index < statusRecords.length; index++) {+ const line = statusRecords[index]!;if (line.startsWith("# branch.head ")) {const value = line.slice("# branch.head ".length).trim();refName = value.startsWith("(") ? null : value;@@ -2064,10 +2032,16 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*behindCount = parsed.behind;continue;}- if (line.trim().length > 0 && !line.startsWith("#")) {+ if (line.length > 0 && !line.startsWith("#")) {hasWorkingTreeChanges = true;const pathValue = parsePorcelainPath(line);if (pathValue) changedFilesWithoutNumstat.add(pathValue);+ // A rename record is followed by its original path as a separate record. Listing it+ // keeps the deletion selectable when committing only some files.+ if (line.startsWith("2 ")) {+ const originalPath = statusRecords[++index];+ if (originalPath) changedFilesWithoutNumstat.add(originalPath);+ }}}@@ -2092,10 +2066,12 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*: yield* computeAheadCountAgainstBase(cwd, refName).pipe(Effect.orElseSucceed(() => 0));}- const numstatEntries = parseNumstatEntries(numstatStdout);const fileStatMap = new Map<string, { insertions: number; deletions: number }>();for (const entry of numstatEntries) {- fileStatMap.set(entry.path, { insertions: entry.insertions, deletions: entry.deletions });+ const stat = fileStatMap.get(entry.path) ?? { insertions: 0, deletions: 0 };+ stat.insertions += entry.additions;+ stat.deletions += entry.deletions;+ fileStatMap.set(entry.path, stat);}let insertions = 0;@@ -2128,6 +2104,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*upstreamRef,hasWorkingTreeChanges,workingTree: {+ ...(repositoryPaths?.worktreeRoot ? { rootPath: repositoryPaths.worktreeRoot } : {}),files,insertions,deletions,@@ -2221,7 +2198,8 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*yield* runGit("GitVcsDriver.commit.addSelected",cwd,- [...config, "--literal-pathspecs", "add", "-A", "--", ...filePaths],+ // Status paths are repository-relative, while cwd can be a subdirectory.+ [...config, "add", "-A", "--", ...filePaths.map((file) => `:(top,literal)${file}`)],env ? { env } : {},);} else {diff --git a/apps/web/src/components/GitActionsControl.browser.test.tsx b/apps/web/src/components/GitActionsControl.browser.test.tsxindex e4641b21700..5904d57f54d 100644--- a/apps/web/src/components/GitActionsControl.browser.test.tsx+++ b/apps/web/src/components/GitActionsControl.browser.test.tsx@@ -29,6 +29,9 @@ const state = vi.hoisted(() => ({metadataRequests: [] as { environmentId: string; branch: string }[],toasts: [] as Toast[],afterGitAction: undefined as (() => void) | undefined,+ workingTreeRoot: undefined as string | undefined,+ files: [{ path: "file.ts", insertions: 1, deletions: 0 }],+ editorOpens: [] as { environmentId: string; input: { cwd: string; editor: string } }[],}));vi.mock(import("~/state/session"), async (original) => {@@ -61,7 +64,8 @@ vi.mock(import("~/state/query"), async (original) => ({hasPrimaryRemote: true,hasWorkingTreeChanges: true,workingTree: {- files: [{ path: "file.ts", insertions: 1, deletions: 0 }],+ ...(state.workingTreeRoot === undefined ? {} : { rootPath: state.workingTreeRoot }),+ files: state.files,insertions: 1,deletions: 0,},@@ -73,21 +77,45 @@ vi.mock(import("~/state/query"), async (original) => ({error: null,})) as never,}));-vi.mock(import("~/state/use-atom-command"), async (original) => ({- ...(await original()),- // The only command whose result matters here is the thread's branch metadata update.- useAtomCommand: ((_command: unknown, options: unknown) =>- options === "thread branch metadata update"- ? async ({ environmentId, input }: { environmentId: string; input: { branch: string } }) => {- state.metadataRequests.push({ environmentId, branch: input.branch });- if (!state.scopes.has(AuthOrchestrationOperateScope))- return AsyncResult.failure(Cause.fail(new Error("Task denied")));- if (state.shell) state.shell = { branch: input.branch };- if (state.detail) state.detail = { branch: input.branch };- return AsyncResult.success(undefined);- }- : async () => AsyncResult.success(undefined)) as never,-}));+vi.mock(import("~/state/use-atom-command"), async (original) => {+ const { shellEnvironment } = await import("~/state/shell");+ return {+ ...(await original()),+ // Only the thread's branch metadata update and editor opens are observed here.+ useAtomCommand: ((command: unknown, options: unknown) =>+ options === "thread branch metadata update"+ ? async ({+ environmentId,+ input,+ }: {+ environmentId: string;+ input: { branch: string };+ }) => {+ state.metadataRequests.push({ environmentId, branch: input.branch });+ if (!state.scopes.has(AuthOrchestrationOperateScope))+ return AsyncResult.failure(Cause.fail(new Error("Task denied")));+ if (state.shell) state.shell = { branch: input.branch };+ if (state.detail) state.detail = { branch: input.branch };+ return AsyncResult.success(undefined);+ }+ : command === shellEnvironment.openInEditor+ ? async (request: (typeof state.editorOpens)[number]) => {+ state.editorOpens.push(request);+ return AsyncResult.success(undefined);+ }+ : async () => AsyncResult.success(undefined)) as never,+ };+});+// The preferred-editor flow needs one editor the environment reports as installed.+vi.mock(import("~/state/server"), async (original) => {+ const actual = await original();+ const { Atom } = await import("effect/reactivity");+ const config = Atom.make(() => ({ availableEditors: ["cursor"] }));+ return {+ ...actual,+ serverEnvironment: { ...actual.serverEnvironment, configValueAtom: (() => config) as never },+ };+});vi.mock(import("~/lib/sourceControlActions"), async (original) => ({...(await original()),useSourceControlActionRunning: () => false,@@ -180,6 +208,9 @@ beforeEach(() => {state.metadataRequests = [];state.toasts = [];state.afterGitAction = undefined;+ state.workingTreeRoot = undefined;+ state.files = [{ path: "file.ts", insertions: 1, deletions: 0 }];+ state.editorOpens = [];useComposerDraftStore.setState({getDraftSession: () => state.draft as never,getDraftThreadByRef: () => state.draft as never,@@ -312,6 +343,42 @@ describe("Git actions while thread details load", () => {});});+describe("Changed-file editor targets", () => {+ beforeEach(() => {+ state.scopes.add(AuthOrchestrationOperateScope);+ state.files = [+ { path: "nested/new.txt", insertions: 0, deletions: 0 },+ { path: "nested/tracked.txt", insertions: 1, deletions: 0 },+ ];+ });++ it("resolves repository-relative paths against the status root, not the project cwd", async () => {+ state.workingTreeRoot = "/repo";+ await render("thread", "/repo/nested");+ await openCommitDialog();++ await userEvent.click(button("Open nested/new.txt in editor"));+ await userEvent.click(button("Open nested/tracked.txt in editor"));++ await vi.waitFor(() => expect(state.editorOpens).toHaveLength(2));+ expect(state.editorOpens).toEqual([+ { environmentId: "environment", input: { cwd: "/repo/nested/new.txt", editor: "cursor" } },+ {+ environmentId: "environment",+ input: { cwd: "/repo/nested/tracked.txt", editor: "cursor" },+ },+ ]);+ });++ it("does not guess a file location when the server reports no root", async () => {+ await render("thread", "/repo/nested");+ await openCommitDialog();++ await expect.element(button("Open nested/new.txt in editor")).toBeDisabled();+ expect(state.editorOpens).toEqual([]);+ });+});+describe("Default branch prompt", () => {beforeEach(() => {state.isDefaultRef = true;diff --git a/apps/web/src/components/GitActionsControl.tsx b/apps/web/src/components/GitActionsControl.tsxindex f131bf1be98..1b60f7179d3 100644--- a/apps/web/src/components/GitActionsControl.tsx+++ b/apps/web/src/components/GitActionsControl.tsx@@ -1091,6 +1091,9 @@ export default function GitActionsControl({const changesTotals = gitStatusForActions?.branchChanges ?? gitStatusForActions?.workingTree;const allFiles = gitStatusForActions?.workingTree.files ?? [];+ // Changed-file paths are repository-relative, so they must resolve against+ // the worktree root from the same status snapshot, not the project cwd.+ const workingTreeRoot = gitStatusForActions?.workingTree.rootPath ?? null;const selectedFiles = allFiles.filter((f) => !excludedFiles.has(f.path));const allSelected = excludedFiles.size === 0;const noneSelected = selectedFiles.length === 0;@@ -1498,7 +1501,7 @@ export default function GitActionsControl({};const openChangedFileInEditor = (filePath: string) => {- if (!gitCwd) {+ if (workingTreeRoot === null) {toastManager.add({type: "error",title: "Editor opening is unavailable.",@@ -1506,7 +1509,7 @@ export default function GitActionsControl({});return;}- const target = resolvePathLinkTarget(filePath, gitCwd);+ const target = resolvePathLinkTarget(filePath, workingTreeRoot);void (async () => {const result = await openInPreferredEditor(target);if (result._tag === "Success" || isAtomCommandInterrupted(result)) {@@ -1944,7 +1947,7 @@ export default function GitActionsControl({<buttontype="button"className="flex min-w-0 flex-1 items-center justify-between gap-3 text-left"- disabled={!canOperateThread}+ disabled={!canOperateThread || workingTreeRoot === null}aria-label={`Open ${file.path} in editor`}onClick={() => openChangedFileInEditor(file.path)}>diff --git a/packages/contracts/src/git.ts b/packages/contracts/src/git.tsindex 382bad2f410..2e4c4ada0a5 100644--- a/packages/contracts/src/git.ts+++ b/packages/contracts/src/git.ts@@ -218,6 +218,9 @@ const VcsStatusLocalShape = {refName: Schema.NullOr(TrimmedNonEmptyStringSchema),hasWorkingTreeChanges: Schema.Boolean,workingTree: Schema.Struct({+ // Absolute worktree root on the environment that every files[].path is+ // relative to. Absent when the server could not resolve it.+ rootPath: Schema.optional(GitFilePath),files: Schema.Array(Schema.Struct({path: GitFilePath,