diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index 499c1e2acc0ca..f87ddd9c82bad 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -566,13 +566,15 @@ const layerWorkspaceFileSystem = WorkspaceFileSystem.layer.pipe( Layer.provide(layerKnownWorkspaces), ); +const layerWorkspaceFolders = WorkspaceFolders.layer.pipe( + Layer.provide(Layer.merge(ProjectStore.layer, TaskFolderStore.layer)), +); + const layerWorkspace = Layer.mergeAll( WorkspacePaths.layer, layerWorkspaceEntries, layerWorkspaceFileSystem, - WorkspaceFolders.layer.pipe( - Layer.provide(Layer.merge(ProjectStore.layer, TaskFolderStore.layer)), - ), + layerWorkspaceFolders, ); const layerProjectFaviconResolver = ProjectFaviconResolver.layer.pipe( @@ -873,8 +875,15 @@ const layerRuntimeDependencies = layerRuntimeCoreDependencies.pipe( Layer.provideMerge(DirectEndpoints.layer.pipe(Layer.provide(layerServerEnvironment))), Layer.provideMerge(ServerLifecycleEvents.layer), // GitVcsDriver.layer is memoized and some of its build sites live outside this file, so the - // fetch interval goes in context here, before the first build captures it. + // fetch interval and the nested repositories go in context here, before the first build + // captures them. Layer.provideMerge(VcsAutomaticFetchInterval.layer.pipe(Layer.provide(layerServerSettings))), + Layer.provideMerge( + WorkspaceFolders.layerVcsNestedRepositories.pipe( + Layer.provide(layerWorkspaceFolders), + Layer.provide(layerPersistence), + ), + ), Layer.provide(NetService.layer), ); diff --git a/apps/server/src/vcs/GitVcsDriverCore.test.ts b/apps/server/src/vcs/GitVcsDriverCore.test.ts index b7125614c0ef7..de4a8c6a7c8c0 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.test.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.test.ts @@ -55,6 +55,7 @@ import { import { autoPullProjects } from "../serverRuntimeStartup.ts"; import * as GitVcsDriver from "./GitVcsDriver.ts"; import { VcsAutomaticFetchInterval } from "./VcsAutomaticFetchInterval.ts"; +import { VcsNestedRepositories } from "./VcsNestedRepositories.ts"; import { gitConfigEnv } from "./VcsProcess.ts"; const encodeGitCommandError = Schema.encodeEffect(Schema.fromJsonString(GitCommandError)); @@ -3961,6 +3962,54 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { }), ); + it.effect("leaves the repositories a project covers out of its checkout's Git views", () => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + yield* initRepoWithCommit(cwd); + const fileSystem = yield* FileSystem.FileSystem; + const driver = yield* makeGitVcsDriverCore().pipe( + Effect.provideService(VcsNestedRepositories, (input) => + Effect.succeed(input.worktreeRoot === cwd ? ["api", "web"] : []), + ), + ); + // `web` is also listed in .gitignore: naming it in git add's pathspec would fail. + for (const nested of ["api", "web"]) { + yield* fileSystem.makeDirectory(`${cwd}/${nested}`); + yield* initRepoWithCommit(`${cwd}/${nested}`); + yield* writeTextFile(cwd, `${nested}/dirty.txt`, "nested change\n"); + } + yield* writeTextFile(cwd, ".gitignore", "web/\n"); + yield* git(cwd, ["add", ".gitignore"]); + yield* git(cwd, ["commit", "-m", "ignore web"]); + yield* writeTextFile(cwd, "notes.txt", "root change\n"); + + const status = yield* driver.statusDetailsLocal(cwd, { includeBranchChanges: true }); + assert.deepStrictEqual(status.workingTree.files, [ + { path: "notes.txt", insertions: 0, deletions: 0 }, + ]); + assert.deepStrictEqual(status.branchChanges, { + baseRef: null, + insertions: 1, + deletions: 0, + }); + const preview = yield* driver.getReviewDiffPreview({ cwd, ignoreWhitespace: false }); + const workingTree = preview.sources.find((source) => source.kind === "working-tree"); + assert.deepStrictEqual( + workingTree?.files?.map((file) => file.path), + ["notes.txt"], + ); + assert.notInclude(workingTree?.diff, "api"); + + yield* driver.commit(cwd, "Root change", "", { stage: {} }); + assert.deepStrictEqual((yield* git(cwd, ["ls-tree", "--name-only", "HEAD"])).split("\n"), [ + ".gitignore", + "README.md", + "notes.txt", + ]); + assert.isFalse((yield* driver.statusDetailsLocal(cwd)).hasWorkingTreeChanges); + }), + ); + it.effect("keeps untracked filenames with pathspec magic in the review", () => Effect.gen(function* () { const cwd = yield* makeTmpDir(); diff --git a/apps/server/src/vcs/GitVcsDriverCore.ts b/apps/server/src/vcs/GitVcsDriverCore.ts index 4981ece0979e4..0c75d33b680c4 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.ts @@ -48,6 +48,7 @@ import { gitCommandDuration, gitCommandsTotal, withMetrics } from "../observabil import * as GitVcsDriver from "./GitVcsDriver.ts"; import { removeEmptyDirectory, type RemoveEmptyDirectoryError } from "./removeEmptyDirectory.ts"; import { VcsAutomaticFetchInterval } from "./VcsAutomaticFetchInterval.ts"; +import { VcsNestedRepositories } from "./VcsNestedRepositories.ts"; import { gitConfigEnv, serverGitConfigEnv, unsetInheritedRepositoryEnv } from "./VcsProcess.ts"; import { makeWorktreeCheckoutCache } from "./worktreeCheckoutCache.ts"; import { removeLinkedWorktree } from "./worktreeRemoval.ts"; @@ -1046,6 +1047,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* const hostPlatform = yield* HostProcess.Platform; const serviceScope = yield* Effect.scope; const automaticFetchInterval = yield* VcsAutomaticFetchInterval; + const nestedRepositories = yield* VcsNestedRepositories; type StatusFetchState = { phase: "queued" | "running" | "claimed"; claimed: Deferred.Deferred; @@ -1316,6 +1318,38 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* }, }); + // Unexcluded, a repository the project covers inside this checkout shows as an untracked folder + // and `add -A` stages it as a gitlink. git add rejects a pathspec naming an ignored folder, and + // skips that folder anyway. + const nestedRepositoryExclusions = Effect.fn("GitVcsDriver.nestedRepositoryExclusions")( + function* (cwd: string, worktreeRoot: string) { + const nested = yield* nestedRepositories({ cwd, worktreeRoot }); + if (nested.length === 0) return []; + const args = ["check-ignore", "--no-index", "-z", "--stdin"]; + const checked = yield* executeGit( + "GitVcsDriver.nestedRepositoryExclusions", + worktreeRoot, + args, + { stdin: `${nested.join("\0")}\0`, allowNonZeroExit: true }, + ); + if (checked.exitCode !== 0 && checked.exitCode !== 1) { + return yield* new GitCommandError({ + ...gitCommandContext({ + operation: "GitVcsDriver.nestedRepositoryExclusions", + cwd: worktreeRoot, + args, + }), + detail: "Could not check which repositories inside the project Git ignores.", + ...(checked.exitCode === null ? {} : { exitCode: checked.exitCode }), + }); + } + const ignored = new Set(splitNullSeparatedGitStdoutPaths(checked)); + return nested + .filter((relativePath) => !ignored.has(relativePath)) + .map((relativePath) => `:(top,exclude,literal)${relativePath}`); + }, + ); + const runGit = ( operation: string, cwd: string, @@ -2829,10 +2863,13 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* const statusCacheKey = repositoryPaths?.gitCommonDir; const refsGeneration = statusCacheKey === undefined ? undefined : currentListRefsGeneration(statusCacheKey); + const exclusions = repositoryPaths?.worktreeRoot + ? yield* nestedRepositoryExclusions(cwd, repositoryPaths.worktreeRoot) + : []; const readStatus = executeGitWithStableDiagnostics( "GitVcsDriver.statusDetails.status", cwd, - statusArgs, + exclusions.length === 0 ? statusArgs : [...statusArgs, "--", ...exclusions], { allowNonZeroExit: true, maxOutputBytes: REVIEW_METADATA_MAX_OUTPUT_BYTES, @@ -2848,7 +2885,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* executeGitWithStableDiagnostics( "GitVcsDriver.statusDetails.numstat", cwd, - ["diff-index", "-M", "--numstat", "-z", ref, "--"], + ["diff-index", "-M", "--numstat", "-z", ref, "--", ...exclusions], { allowNonZeroExit: true, maxOutputBytes: REVIEW_METADATA_MAX_OUTPUT_BYTES }, ); // diff-index does not read status output, so both spawn together; a non-repository discards it. @@ -3020,6 +3057,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* options?.includeBranchChanges ? readBranchChangeTotals(repositoryPaths?.worktreeRoot ?? cwd, refName, { untrackedRoots, + exclusions, headOid, ...(index ? { indexPath: index } : {}), }).pipe(Effect.orElseSucceed(() => undefined)) @@ -3346,10 +3384,12 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* }); } } + const worktreeRoot = (yield* resolveRepositoryPaths(cwd))?.worktreeRoot; + const exclusions = worktreeRoot ? yield* nestedRepositoryExclusions(cwd, worktreeRoot) : []; yield* runGit( "GitVcsDriver.commit.addAll", cwd, - [...config, "add", "-A"], + [...config, "add", "-A", ...(exclusions.length === 0 ? [] : ["--", ...exclusions])], env ? { env } : {}, ); } @@ -4441,6 +4481,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* branch: string | null, options?: { readonly untrackedRoots: ReadonlyArray; + readonly exclusions?: ReadonlyArray; readonly headOid: string | null; readonly indexPath?: string; }, @@ -4467,11 +4508,15 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* }); } const roots = options?.untrackedRoots ?? []; + const exclusions = options?.exclusions ?? []; // Bound pathspec matching work and stay below Windows' command-line limit. - const pathspecs = - roots.length <= 128 && roots.reduce((length, root) => length + root.length + 16, 0) < 8_000 + const pathspecs = [ + ...(roots.length <= 128 && + roots.reduce((length, root) => length + root.length + 16, 0) < 8_000 ? roots.map((root) => `:(top,literal)${root}`) - : []; + : []), + ...exclusions, + ]; // Changed untracked roots skip the backoff and scan again. const rootsKey = roots.join("\0"); const remembered = untrackedTotalsFailures.get(cwd); @@ -4526,7 +4571,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* "GitVcsDriver.readBranchChangeTotals", cwd, // Plumbing: porcelain diff refreshes and rewrites the real index, taking index.lock. - ["diff-index", "-M", "--numstat", "-z", ref, "--"], + ["diff-index", "-M", "--numstat", "-z", ref, "--", ...exclusions], { allowNonZeroExit: true, maxOutputBytes: REVIEW_METADATA_MAX_OUTPUT_BYTES, @@ -4755,7 +4800,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* const getReviewDiffPreview = Effect.fn("getReviewDiffPreview")(function* ( input: ReviewDiffPreviewInput, ) { - const pathArgs = input.file + const filePathArgs = input.file ? [input.file.path, ...(input.file.previousPath ? [input.file.previousPath] : [])].map( (path) => `:(top,literal)${path}`, ) @@ -4829,7 +4874,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* const stat = yield* executeGit( "GitVcsDriver.getReviewDiffPreview.commitStat", cwd, - [...diffArgs, "--raw", "--numstat", "-z", commit.parent, commit.sha, "--", ...pathArgs], + [...diffArgs, "--raw", "--numstat", "-z", commit.parent, commit.sha, "--", ...filePathArgs], { maxOutputBytes: REVIEW_METADATA_MAX_OUTPUT_BYTES }, ); const files = parseReviewNumstat(stat.stdout); @@ -4839,7 +4884,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* : yield* executeGit( "GitVcsDriver.getReviewDiffPreview.commitPatch", cwd, - [...diffArgs, "--patch", commit.parent, commit.sha, "--", ...pathArgs], + [...diffArgs, "--patch", commit.parent, commit.sha, "--", ...filePathArgs], { maxOutputBytes: patchLimit, appendTruncationMarker: true }, ); const diffHash = yield* hashDiff(patch.stdout, files); @@ -4864,6 +4909,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* }; } + const pathArgs = input.file ? filePathArgs : yield* nestedRepositoryExclusions(input.cwd, cwd); const dirtyRef = sourceKind === "branch-range" ? null : "HEAD"; const review = tracked?.review ?? diff --git a/apps/server/src/vcs/VcsNestedRepositories.ts b/apps/server/src/vcs/VcsNestedRepositories.ts new file mode 100644 index 0000000000000..c3eb6a946351d --- /dev/null +++ b/apps/server/src/vcs/VcsNestedRepositories.ts @@ -0,0 +1,14 @@ +import * as Context from "effect/Context"; +import * as Effect from "effect/Effect"; + +/** + * The repositories a project covers inside a checkout of its folder, relative to `worktreeRoot` + * with `/` separators. Each has its own status, review and commits, so the checkout's own Git views + * leave them out. Empty where no project layer is provided. + */ +export class VcsNestedRepositories extends Context.Reference< + (input: { + readonly cwd: string; + readonly worktreeRoot: string; + }) => Effect.Effect> +>("t3/vcs/VcsNestedRepositories", { defaultValue: () => () => Effect.succeed([]) }) {} diff --git a/apps/server/src/workspace/WorkspaceFolders.test.ts b/apps/server/src/workspace/WorkspaceFolders.test.ts index 3a02d202be891..3f516fb44a16f 100644 --- a/apps/server/src/workspace/WorkspaceFolders.test.ts +++ b/apps/server/src/workspace/WorkspaceFolders.test.ts @@ -13,6 +13,27 @@ import * as WorkspaceFolders from "./WorkspaceFolders.ts"; const projectId = ProjectId.make("project:workspace-folders"); +const rowOf = (project: { + readonly workspaceRoot: string; + readonly trackedFolders: ReadonlyArray; +}) => ({ + projectId, + title: "Project", + hasCustomTitle: false, + defaultModelSelection: null, + defaultThreadEnvMode: null, + autoPull: false, + faviconPath: null, + projectIcon: null, + scripts: [], + pinnedAt: null, + archivedAt: null, + createdAt: "2026-06-21T00:00:00.000Z", + updatedAt: "2026-06-21T00:00:00.000Z", + deletedAt: null, + ...project, +}); + const layerFor = (project?: { readonly workspaceRoot: string; readonly trackedFolders: ReadonlyArray; @@ -21,25 +42,11 @@ const layerFor = (project?: { Layer.provide( Layer.mock(ProjectStore.ProjectStoreV2)({ get: () => - project === undefined - ? Effect.succeedNone - : Effect.succeedSome({ - projectId, - title: "Project", - hasCustomTitle: false, - defaultModelSelection: null, - defaultThreadEnvMode: null, - autoPull: false, - faviconPath: null, - projectIcon: null, - scripts: [], - pinnedAt: null, - archivedAt: null, - createdAt: "2026-06-21T00:00:00.000Z", - updatedAt: "2026-06-21T00:00:00.000Z", - deletedAt: null, - ...project, - }), + project === undefined ? Effect.succeedNone : Effect.succeedSome(rowOf(project)), + findActiveByWorkspaceRoot: (workspaceRoot) => + project?.workspaceRoot === workspaceRoot + ? Effect.succeedSome(rowOf(project)) + : Effect.succeedNone, }), ), Layer.provideMerge(TaskFolderStore.layer.pipe(Layer.provide(SqlitePersistence.layerMemory))), @@ -189,6 +196,21 @@ it.layer(NodeServices.layer)("WorkspaceFolders", (it) => { ["web", repository("web")], ["Outside", outside], ]); + // What the project folder's own Git views leave out: the repositories it covers inside. + assert.deepEqual( + yield* workspaceFolders.nestedRepositories({ + cwd: workspaceRoot, + worktreeRoot: workspaceRoot, + }), + ["docs", "src/web"], + ); + assert.deepEqual( + yield* workspaceFolders.nestedRepositories({ + cwd: path.join(workspaceRoot, "docs"), + worktreeRoot: path.join(workspaceRoot, "docs"), + }), + [], + ); }).pipe(Effect.provide(layerFor({ workspaceRoot, trackedFolders }))); }), ); @@ -459,6 +481,15 @@ it.layer(NodeServices.layer)("WorkspaceFolders", (it) => { }), { folders: [], extraRoots: [] }, ); + // The thread's checkout of the project folder leaves out the worktree inside it, which + // Git names by its resolved path. + assert.deepEqual( + yield* workspaceFolders.nestedRepositories({ + cwd: path.join(taskRoot, "ctx"), + worktreeRoot: path.join(realWorktrees, "x", "feature-0123", "ctx"), + }), + ["vendor/lib"], + ); }).pipe(Effect.provide(layerFor({ workspaceRoot: ctx, trackedFolders }))); }), ); diff --git a/apps/server/src/workspace/WorkspaceFolders.ts b/apps/server/src/workspace/WorkspaceFolders.ts index 0824c647ce360..c6da0a7a19b95 100644 --- a/apps/server/src/workspace/WorkspaceFolders.ts +++ b/apps/server/src/workspace/WorkspaceFolders.ts @@ -24,6 +24,7 @@ import * as Path from "effect/Path"; import * as Schema from "effect/Schema"; import * as ProjectStore from "../orchestration-v2/ProjectStore.ts"; +import { VcsNestedRepositories } from "../vcs/VcsNestedRepositories.ts"; import { isWithinRoot } from "./KnownWorkspaces.ts"; import * as TaskFolderStore from "./TaskFolderStore.ts"; @@ -67,6 +68,15 @@ export class WorkspaceFolders extends Context.Service< /** The thread's `forThread` folders; passed in so the project is walked once. */ readonly folders: ReadonlyArray; }) => Effect.Effect, WorkspaceFoldersError>; + /** + * The repositories a project covers inside `worktreeRoot`, the Git checkout of `cwd`: those of + * the project whose folder `cwd` is, or of the task folder it is in. Relative with `/` + * separators; a submodule stays with the repository that pins it. + */ + readonly nestedRepositories: (input: { + readonly cwd: string; + readonly worktreeRoot: string; + }) => Effect.Effect>; readonly list: ( input: WorkspaceListFoldersInput, ) => Effect.Effect; @@ -529,6 +539,49 @@ const make = Effect.gen(function* () { ]); }); + const nestedRepositories: WorkspaceFolders["Service"]["nestedRepositories"] = Effect.fn( + "WorkspaceFolders.nestedRepositories", + )(function* (input) { + const taskFolder = yield* taskFolders + .findContaining(input.cwd) + .pipe(Effect.orElseSucceed(() => null)); + const folders = + taskFolder !== null + ? taskFolder.repositories.map((repository) => repository.worktreePath) + : yield* projects.findActiveByWorkspaceRoot(input.cwd).pipe( + Effect.flatMap( + Option.match({ + onNone: () => Effect.succeed([]), + onSome: (project) => + Effect.map(foldersOf(project), (tracked) => tracked.map((folder) => folder.path)), + }), + ), + Effect.orElseSucceed((): ReadonlyArray => []), + ); + if (folders.length === 0) return []; + const root = yield* realPath(input.worktreeRoot); + const inside = yield* Effect.forEach( + folders, + (folder) => + realPath(folder).pipe( + Effect.map((real) => + real !== root && isWithinRoot(path, real, root) + ? [path.relative(root, real).split(path.sep).join("/")] + : [], + ), + ), + { concurrency: DETECTION_CONCURRENCY }, + ); + const submodules = new Set( + parseGitmodulesPaths( + yield* fileSystem + .readFileString(path.join(root, ".gitmodules")) + .pipe(Effect.orElseSucceed(() => "")), + ), + ); + return [...new Set(inside.flat())].filter((relative) => !submodules.has(relative)); + }); + const list: WorkspaceFolders["Service"]["list"] = Effect.fn("WorkspaceFolders.list")( function* (input) { const project = yield* readProject(input.projectId); @@ -542,7 +595,15 @@ const make = Effect.gen(function* () { Effect.provideService(Path.Path, path), ); - return WorkspaceFolders.of({ forThread, submodules, list, scan }); + return WorkspaceFolders.of({ forThread, submodules, nestedRepositories, list, scan }); }); export const layer = Layer.effect(WorkspaceFolders, make); + +/** Lets Git views of a project's checkout leave out the repositories the project covers in it. */ +export const layerVcsNestedRepositories = Layer.effect( + VcsNestedRepositories, + Effect.gen(function* () { + return (yield* WorkspaceFolders).nestedRepositories; + }), +); diff --git a/docs/user/multi-repo-projects.md b/docs/user/multi-repo-projects.md index 7962770417175..a08909a6b01c1 100644 --- a/docs/user/multi-repo-projects.md +++ b/docs/user/multi-repo-projects.md @@ -67,7 +67,8 @@ hand show up too. ## Commit, push, and open pull requests -Git actions run in one repository at a time. +Git actions run in one repository at a time. When the project folder is a repository itself, its +uncommitted changes, diff, and commits leave out the repositories the project covers inside it. - **Web and desktop:** the thread details panel lists the repositories the thread changed, most recent first, each with its branch and uncommitted changes. Expand one to commit, push, or open a