diff --git a/apps/mobile/src/features/review/ReviewSheet.tsx b/apps/mobile/src/features/review/ReviewSheet.tsx index a953ca80901fa..e3690850b3fdd 100644 --- a/apps/mobile/src/features/review/ReviewSheet.tsx +++ b/apps/mobile/src/features/review/ReviewSheet.tsx @@ -1,6 +1,6 @@ import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime"; import { AsyncResult } from "effect/reactivity"; -import type { EnvironmentId, ThreadId } from "@t3tools/contracts"; +import type { ReviewRepositoriesResult, EnvironmentId, ThreadId } from "@t3tools/contracts"; import { formatDiffCount } from "@t3tools/client-runtime/diff-count"; import { useNavigation, type StaticScreenProps } from "@react-navigation/native"; import { AppActivityIndicator } from "../../components/ui/AppActivityIndicator"; @@ -63,6 +63,9 @@ import { useSelectWorkspaceDetail } from "../layout/workspace/useSelectWorkspace function ReviewHeader( props: Parameters[0] & { + readonly repositories: ReviewRepositoriesResult["repositories"]; + readonly selectedRepository: ReviewRepositoriesResult["repositories"][number] | undefined; + readonly onSelectRepository: (cwd: string) => void; readonly sectionMenu: ReturnType; readonly showSectionToolbar: boolean; readonly showChangedFilesToggle: boolean; @@ -104,6 +107,21 @@ function ReviewHeader( : undefined } menus={[ + ...(props.repositories.length > 1 + ? [ + { + title: "Select repository", + icon: "folder" as const, + items: props.repositories.map((repo) => ({ + id: repo.cwd, + title: repo.name + ": " + (repo.branch ?? "HEAD"), + subtitle: repo.path || "Workspace repository", + selected: repo.cwd === props.selectedRepository?.cwd, + onPress: () => props.onSelectRepository(repo.cwd), + })), + }, + ] + : []), ...(presentation.gitMenu ? [presentation.gitMenu] : []), ...(props.showSectionToolbar ? [ @@ -388,6 +406,11 @@ export function ReviewSheet(props: ReviewSheetProps) { refreshSelectedSection, selectSection, isSelectedSectionPending, + repositories, + selectedRepository, + selectRepository, + reviewCwd, + repositoryPath, } = useReviewSections({ enabled: isEnvironmentReady, environmentId, @@ -409,7 +432,8 @@ export function ReviewSheet(props: ReviewSheetProps) { } = useReviewDiffData({ threadKey: reviewCache.threadKey, environmentId, - cwd: selectedThreadCwd, + cwd: reviewCwd, + repositoryPath, selectedSection, draftMessage, draftContext, @@ -452,6 +476,7 @@ export function ReviewSheet(props: ReviewSheetProps) { environmentId, threadId, selectedSection, + repositoryPath, nativeReviewDiffData, }); const nativeBridge = useNativeReviewDiffBridge({ @@ -555,6 +580,9 @@ export function ReviewSheet(props: ReviewSheetProps) { }); }; const androidHeaderSubtitle = [ + repositories.length > 1 && selectedSection?.kind !== "turn" && selectedRepository + ? selectedRepository.name + ": " + (selectedRepository.branch ?? "HEAD") + : null, selectedSection?.title, headerDiffSummary.additions, headerDiffSummary.deletions, @@ -598,6 +626,9 @@ export function ReviewSheet(props: ReviewSheetProps) { return <>{children}; })(); const headerSubtitle = [ + repositories.length > 1 && selectedSection?.kind !== "turn" && selectedRepository + ? selectedRepository.name + ": " + (selectedRepository.branch ?? "HEAD") + : null, headerDiffSummary.additions, headerDiffSummary.deletions, pendingReviewCommentCount > 0 @@ -622,7 +653,10 @@ export function ReviewSheet(props: ReviewSheetProps) { title={headerTitleText} subtitle={headerSubtitle} androidSubtitle={androidHeaderSubtitle} - selectedThreadCwd={selectedThreadCwd} + selectedThreadCwd={repositoryPath ? null : selectedThreadCwd} + repositories={repositories} + selectedRepository={selectedRepository} + onSelectRepository={selectRepository} sectionMenu={sectionMenu} selectedSection={selectedSection} showSectionToolbar={showSectionToolbar} diff --git a/apps/mobile/src/features/review/reviewModel.test.ts b/apps/mobile/src/features/review/reviewModel.test.ts index ef366dc33d409..e238b8acf563f 100644 --- a/apps/mobile/src/features/review/reviewModel.test.ts +++ b/apps/mobile/src/features/review/reviewModel.test.ts @@ -24,6 +24,11 @@ describe("resolveReviewSelectedSectionId", () => { it("shows Changes before anything is picked, not the first section", () => { expect(resolveReviewSelectedSectionId([turn, changes], null)).toBe("git:branch-range"); + const childChanges = { ...changes, id: "git:branch-range:packages/auth" }; + expect(resolveReviewSelectedSectionId([turn, childChanges], null)).toBe(childChanges.id); + expect( + resolveReviewSelectedSectionId([turn, childChanges], "git:branch-range:packages/ui"), + ).toBe(childChanges.id); }); it("shows the default while the picked section loads and returns to the pick once it does", () => { diff --git a/apps/mobile/src/features/review/reviewModel.ts b/apps/mobile/src/features/review/reviewModel.ts index df3c7c51324b4..890be2116060a 100644 --- a/apps/mobile/src/features/review/reviewModel.ts +++ b/apps/mobile/src/features/review/reviewModel.ts @@ -515,6 +515,7 @@ export function reviewTurnDiffsBySectionId( } export function buildReviewSectionItems(input: { + readonly repositoryPath?: string; readonly checkpoints: ReadonlyArray; readonly gitSections: ReadonlyArray; readonly turnDiffById: Readonly>; @@ -534,13 +535,15 @@ export function buildReviewSectionItems(input: { }, ); + const repositorySectionId = (id: string) => + input.repositoryPath ? `${id}:${input.repositoryPath}` : id; const gitItems = input.gitSections .filter( (section): section is typeof section & { kind: ReviewSectionKind } => section.kind !== "commit", ) .map((section) => ({ - id: `git:${section.kind}`, + id: repositorySectionId(`git:${section.kind}`), kind: section.kind, title: section.title, subtitle: gitSubtitle(section), @@ -550,12 +553,12 @@ export function buildReviewSectionItems(input: { truncated: section.truncated, isLoading: false, })); - const hasChangesItem = gitItems.some((item) => item.id === CHANGES_SECTION_ID); + const hasChangesItem = gitItems.some((item) => item.kind === "branch-range"); const visibleGitItems = input.loadingGitSections && !hasChangesItem ? [ { - id: CHANGES_SECTION_ID, + id: repositorySectionId(CHANGES_SECTION_ID), kind: "branch-range", title: CHANGES_TITLE, subtitle: null, @@ -572,7 +575,7 @@ export function buildReviewSectionItems(input: { export function getDefaultReviewSectionId( sections: ReadonlyArray, ): string | null { - return (sections.find((section) => section.id === CHANGES_SECTION_ID) ?? sections[0])?.id ?? null; + return (sections.find((section) => section.kind === "branch-range") ?? sections[0])?.id ?? null; } /** diff --git a/apps/mobile/src/features/review/useReviewCommentSelectionController.ts b/apps/mobile/src/features/review/useReviewCommentSelectionController.ts index 4a68af28ca831..91f07c7f15009 100644 --- a/apps/mobile/src/features/review/useReviewCommentSelectionController.ts +++ b/apps/mobile/src/features/review/useReviewCommentSelectionController.ts @@ -26,6 +26,7 @@ export function useReviewCommentSelectionController(input: { readonly environmentId?: EnvironmentId; readonly threadId?: ThreadId; readonly selectedSection: ReviewSectionItem | null; + readonly repositoryPath?: string; readonly nativeReviewDiffData: NativeReviewDiffData; }) { const { environmentId, nativeReviewDiffData, selectedSection, threadId } = input; @@ -99,11 +100,14 @@ export function useReviewCommentSelectionController(input: { return; } + const filePath = input.repositoryPath + ? input.repositoryPath + "/" + target.filePath + : target.filePath; if (gesture === "longPress") { startReviewCommentRange(scope, { sectionId: selectedSection.id, sectionTitle: selectedSection.title, - filePath: target.filePath, + filePath, lines: target.lines, lineIndex: target.lineIndex, rowId, @@ -111,7 +115,7 @@ export function useReviewCommentSelectionController(input: { return; } - if (pendingRange && pendingRange.filePath === target.filePath) { + if (pendingRange && pendingRange.filePath === filePath) { completeReviewCommentRange( scope, buildReviewCommentTarget(pendingRange, pendingRange.lineIndex, target.lineIndex), @@ -122,7 +126,7 @@ export function useReviewCommentSelectionController(input: { setReviewCommentTarget(scope, { sectionTitle: selectedSection.title, sectionId: selectedSection.id, - filePath: target.filePath, + filePath, lines: target.lines, startIndex: target.lineIndex, endIndex: target.lineIndex, diff --git a/apps/mobile/src/features/review/useReviewDiffData.ts b/apps/mobile/src/features/review/useReviewDiffData.ts index d9ec656cbc773..8c44e0d1dee5e 100644 --- a/apps/mobile/src/features/review/useReviewDiffData.ts +++ b/apps/mobile/src/features/review/useReviewDiffData.ts @@ -125,6 +125,7 @@ export function useReviewDiffData(input: { readonly threadKey: string | null; readonly environmentId: EnvironmentId | undefined; readonly cwd: string | null; + readonly repositoryPath?: string; readonly selectedSection: ReviewSectionItem | null; readonly draftMessage: string; readonly draftContext: OrchestrationMessageContext | undefined; @@ -237,8 +238,15 @@ export function useReviewDiffData(input: { if (!selectedSectionId || inlineReviewComments.length === 0) { return EMPTY_INLINE_REVIEW_COMMENTS; } - return inlineReviewComments.filter((comment) => comment.sectionId === selectedSectionId); - }, [inlineReviewComments, selectedSectionId]); + const prefix = input.repositoryPath ? input.repositoryPath + "/" : ""; + return inlineReviewComments + .filter((comment) => comment.sectionId === selectedSectionId) + .map((comment) => + prefix && comment.filePath.startsWith(prefix) + ? { ...comment, filePath: comment.filePath.slice(prefix.length) } + : comment, + ); + }, [inlineReviewComments, selectedSectionId, input.repositoryPath]); const nativeReviewDiffData = getCachedNativeReviewDiffData({ parsedDiff, comments: selectedSectionInlineComments, diff --git a/apps/mobile/src/features/review/useReviewHeaderPresentation.tsx b/apps/mobile/src/features/review/useReviewHeaderPresentation.tsx index d0fda18cf60cd..ad580656c2ef9 100644 --- a/apps/mobile/src/features/review/useReviewHeaderPresentation.tsx +++ b/apps/mobile/src/features/review/useReviewHeaderPresentation.tsx @@ -40,7 +40,9 @@ export function useReviewHeaderPresentation(props: { ); // Selection-based git hooks apply only to reviews of the selected thread. const gitMenuAvailable = - selectedThread !== null && String(selectedThread.id) === String(props.threadId); + selectedThread !== null && + String(selectedThread.id) === String(props.threadId) && + props.selectedThreadCwd !== null; const gitMenu = useThreadGitMenuDefinition({ environmentId: props.environmentId, threadId: props.threadId, diff --git a/apps/mobile/src/features/review/useReviewSections.ts b/apps/mobile/src/features/review/useReviewSections.ts index 4fd506732e5d3..d85562d9bfd37 100644 --- a/apps/mobile/src/features/review/useReviewSections.ts +++ b/apps/mobile/src/features/review/useReviewSections.ts @@ -1,3 +1,5 @@ +import { useThreadSelection } from "../../state/use-thread-selection"; +import { useState } from "react"; import { useAtomValue } from "@effect/atom-react"; import { resolveFilesystemReadAccess } from "@t3tools/client-runtime/state/filesystem"; import { Atom } from "effect/reactivity"; @@ -53,17 +55,46 @@ export function useReviewSections(input: { const { canReadFiles } = fileAccess; const selectedThread = useSelectedThreadProjection(); const { selectedThreadCwd } = useSelectedThreadWorktree(); + const [repositoryChoice, setRepositoryChoice] = useState<{ + threadKey: string | null; + cwd: string; + } | null>(null); + const repositoriesQuery = useEnvironmentQuery( + canReadFiles && enabled && environmentId && selectedThreadCwd + ? reviewEnvironment.repositories({ environmentId, input: { cwd: selectedThreadCwd } }) + : null, + ); + const { selectedThreadProject } = useThreadSelection(); + const repositories = (repositoriesQuery.data?.repositories ?? []).map((repo) => + repo.path ? repo : { ...repo, name: selectedThreadProject?.title || repo.name }, + ); + const selectedRepository = + repositories.find( + (repo) => + repositoryChoice?.threadKey === reviewCache.threadKey && repo.cwd === repositoryChoice.cwd, + ) ?? repositories[0]; + // A chosen child stays unresolved while discovery has no answer, so its review never shows the parent. + const repositoryUnresolved = + repositoryChoice?.threadKey === reviewCache.threadKey && + repositoryChoice.cwd !== selectedThreadCwd && + !repositoriesQuery.data; + const reviewCwd = repositoryUnresolved + ? null + : selectedRepository?.path + ? selectedRepository.cwd + : selectedThreadCwd; + const repositoryPath = selectedRepository?.path ?? ""; const diffPreview = useEnvironmentQuery( - canReadFiles && enabled && environmentId !== undefined && selectedThreadCwd !== null + canReadFiles && enabled && environmentId !== undefined && reviewCwd !== null ? reviewEnvironment.diffPreview({ environmentId, - input: { cwd: selectedThreadCwd }, + input: { cwd: reviewCwd }, }) : null, ); const lastGitSections = useAtomValue( - environmentId !== undefined && selectedThreadCwd !== null - ? lastReviewGitSectionsAtom(environmentId, selectedThreadCwd) + environmentId !== undefined && reviewCwd !== null + ? lastReviewGitSectionsAtom(environmentId, reviewCwd) : NO_GIT_SECTIONS_ATOM, ); @@ -87,6 +118,7 @@ export function useReviewSections(input: { canReadFiles || fileAccess.isPending ? (diffPreview.data?.sources ?? lastGitSections) : [], turnDiffById: reviewTurnDiffsBySectionId(readyCheckpoints, lastTurnDiffs), loadingGitSections: fileAccess.isPending || diffPreview.isPending, + repositoryPath, }); const selectedSectionId = resolveReviewSelectedSectionId( cachedSections, @@ -124,15 +156,21 @@ export function useReviewSections(input: { const selectedSection = reviewSections.find((section) => section.id === selectedSectionId) ?? null; + // With a child unresolved there are no Git sections, so a turn can be selected only as a fallback. + const repositoryFailureVisible = + repositoryUnresolved && + !(selectedSection?.kind === "turn" && reviewCache.selectedSectionId === selectedSection.id); + const refreshSelectedSection = async () => { if (!enabled) { return; } if (selectedSection?.kind === "turn") { activeTurnDiff.refresh(); - return; + if (!repositoryFailureVisible) return; } diffPreview.refresh(); + repositoriesQuery.refresh(); }; const selectSection = (sectionId: string) => { @@ -141,8 +179,21 @@ export function useReviewSections(input: { } }; + const selectRepository = (cwd: string) => { + if (!repositories.some((repo) => repo.cwd === cwd)) return; + if (selectedRepository?.cwd === cwd) return; + setRepositoryChoice({ threadKey: reviewCache.threadKey, cwd }); + if (reviewCache.threadKey) setReviewSelectedSectionId(reviewCache.threadKey, null); + }; + return { + repositories, + selectedRepository, + selectRepository, + reviewCwd: selectedSection?.kind === "turn" ? selectedThreadCwd : reviewCwd, + repositoryPath: selectedSection?.kind === "turn" ? "" : repositoryPath, error: + (repositoryFailureVisible ? repositoriesQuery.error : null) ?? diffPreview.error ?? activeTurnDiff.error ?? (selectedSection === null && !fileAccess.isPending && !canReadFiles diff --git a/apps/server/src/auth/RpcAuthorization.ts b/apps/server/src/auth/RpcAuthorization.ts index 180f053f111f4..ebf7e8a8074dd 100644 --- a/apps/server/src/auth/RpcAuthorization.ts +++ b/apps/server/src/auth/RpcAuthorization.ts @@ -179,6 +179,7 @@ export const RPC_REQUIRED_SCOPES = { [WS_METHODS.vcsRefreshStatus]: AuthOrchestrationReadScope, [WS_METHODS.gitResolvePullRequest]: AuthOrchestrationReadScope, [WS_METHODS.vcsListRefs]: AuthOrchestrationReadScope, + [WS_METHODS.reviewGetRepositories]: AuthFilesystemReadScope, [WS_METHODS.reviewGetBranchCommits]: AuthFilesystemReadScope, [WS_METHODS.reviewGetDiffPreview]: AuthFilesystemReadScope, [WS_METHODS.reviewGetDiffFileContents]: AuthFilesystemReadScope, diff --git a/apps/server/src/observability/RpcInstrumentation.ts b/apps/server/src/observability/RpcInstrumentation.ts index f9a861cca23fb..9f513a158f853 100644 --- a/apps/server/src/observability/RpcInstrumentation.ts +++ b/apps/server/src/observability/RpcInstrumentation.ts @@ -193,6 +193,7 @@ const RPC_AGGREGATES = { [WS_METHODS.vcsCreateRef]: "vcs", [WS_METHODS.vcsSwitchRef]: "vcs", [WS_METHODS.vcsInit]: "vcs", + [WS_METHODS.reviewGetRepositories]: "review", [WS_METHODS.reviewGetBranchCommits]: "review", [WS_METHODS.reviewGetDiffPreview]: "review", [WS_METHODS.reviewGetDiffFileContents]: "review", diff --git a/apps/server/src/review/ReviewService.test.ts b/apps/server/src/review/ReviewService.test.ts index 4df56454cfc58..2bfd04843caf9 100644 --- a/apps/server/src/review/ReviewService.test.ts +++ b/apps/server/src/review/ReviewService.test.ts @@ -109,6 +109,12 @@ describe("ReviewService", () => { return yield* review.getDiffPreview({ cwd: outsideRoot }).pipe(Effect.flip); }).pipe(Effect.provide(layer({ workspaceRoot, baseDir, detectCalls }))); + const repositoryError = yield* Effect.gen(function* () { + const review = yield* ReviewService.ReviewService; + return yield* review.getRepositories({ cwd: outsideRoot }).pipe(Effect.flip); + }).pipe(Effect.provide(layer({ workspaceRoot, baseDir, detectCalls }))); + assert.strictEqual(repositoryError._tag, "VcsRepositoryDetectionError"); + assert.strictEqual(repositoryError.operation, "ReviewService.getRepositories"); assert.strictEqual(error._tag, "VcsRepositoryDetectionError"); assert.strictEqual(error.operation, "ReviewService.getDiffPreview"); assert.match( diff --git a/apps/server/src/review/ReviewService.ts b/apps/server/src/review/ReviewService.ts index 39ce1554cea61..2169224f3cb6f 100644 --- a/apps/server/src/review/ReviewService.ts +++ b/apps/server/src/review/ReviewService.ts @@ -8,6 +8,8 @@ import * as Path from "effect/Path"; import { VcsRepositoryDetectionError, VcsUnsupportedOperationError, + type ReviewRepositoriesInput, + type ReviewRepositoriesResult, type ReviewBranchCommitsInput, type ReviewBranchCommitsResult, type ReviewDiffFileContentsInput, @@ -23,6 +25,7 @@ import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts"; import * as KnownWorkspaces from "../workspace/KnownWorkspaces.ts"; const WORKSPACE_BOUND_SUBJECTS = { + "ReviewService.getRepositories": "repository list", "ReviewService.getBranchCommits": "commit list", "ReviewService.getDiffPreview": "diff preview", "ReviewService.getDiffFileContents": "diff file contents", @@ -31,6 +34,9 @@ const WORKSPACE_BOUND_SUBJECTS = { export class ReviewService extends Context.Service< ReviewService, { + readonly getRepositories: ( + input: ReviewRepositoriesInput, + ) => Effect.Effect; readonly getBranchCommits: ( input: ReviewBranchCommitsInput, ) => Effect.Effect; @@ -93,6 +99,15 @@ export const make = Effect.gen(function* () { }); }); + const getRepositories: ReviewService["Service"]["getRepositories"] = Effect.fn( + "ReviewService.getRepositories", + )(function* (input) { + yield* assertWorkspaceBoundCwd("ReviewService.getRepositories", input.cwd); + const handle = yield* vcsRegistry.detect({ cwd: input.cwd, requestedKind: "auto" }); + if (handle?.kind !== "git") return { repositories: [], truncated: false }; + return yield* git.getReviewRepositories(input); + }); + const getBranchCommits: ReviewService["Service"]["getBranchCommits"] = Effect.fn( "ReviewService.getBranchCommits", )(function* (input) { @@ -145,6 +160,7 @@ export const make = Effect.gen(function* () { }); return ReviewService.of({ + getRepositories, getBranchCommits, getDiffPreview, getDiffFileContents, diff --git a/apps/server/src/vcs/GitVcsDriver.ts b/apps/server/src/vcs/GitVcsDriver.ts index ff129690b7b24..97cb7ace9ce38 100644 --- a/apps/server/src/vcs/GitVcsDriver.ts +++ b/apps/server/src/vcs/GitVcsDriver.ts @@ -20,6 +20,8 @@ import { type VcsCreateRefResult, type VcsCreateWorktreeInput, type VcsCreateWorktreeResult, + type ReviewRepositoriesInput, + type ReviewRepositoriesResult, type ReviewBranchCommitsInput, type ReviewBranchCommitsResult, type ReviewDiffPreviewInput, @@ -353,6 +355,9 @@ export class GitVcsDriver extends Context.Service< cwd: string, baseRef: string, ) => Effect.Effect; + readonly getReviewRepositories: ( + input: ReviewRepositoriesInput, + ) => Effect.Effect; readonly getReviewBranchCommits: ( input: ReviewBranchCommitsInput, ) => Effect.Effect; diff --git a/apps/server/src/vcs/GitVcsDriverCore.test.ts b/apps/server/src/vcs/GitVcsDriverCore.test.ts index 70b2d50eda88e..53ae748a9de53 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.test.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.test.ts @@ -2219,6 +2219,132 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { }); describe("review diff previews", () => { + it.effect("lists initialized repositories and keeps each review inside its repository", () => + withGitFileProtocol( + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + const upstream = yield* makeTmpDir(); + const nested = yield* makeTmpDir(); + const { initialBranch } = yield* initRepoWithCommit(cwd); + yield* initRepoWithCommit(upstream); + yield* initRepoWithCommit(nested); + yield* git(upstream, ["submodule", "add", nested, "vendor/schema"]); + yield* git(upstream, ["commit", "-am", "Add schema"]); + yield* git(cwd, ["submodule", "add", upstream, "packages/auth service"]); + yield* git(cwd, ["submodule", "add", nested, "uninitialized"]); + yield* git(cwd, ["commit", "-am", "Add modules"]); + yield* git(cwd, ["submodule", "update", "--init", "--recursive"]); + yield* git(cwd, ["submodule", "deinit", "-f", "--", "uninitialized"]); + const child = NodePath.join(cwd, "packages/auth service"); + yield* git(child, ["config", "user.email", "test@test.com"]); + yield* git(child, ["config", "user.name", "Test"]); + yield* writeTextFile(child, "committed.txt", "child commit\n"); + yield* git(child, ["add", "committed.txt"]); + yield* git(child, ["commit", "-m", "Child change"]); + yield* git(child, ["checkout", "-b", "feature/auth"]); + yield* writeTextFile(child, "README.md", "# changed auth\n"); + yield* writeTextFile(cwd, "README.md", "# changed parent\n"); + const driver = yield* GitVcsDriver.GitVcsDriver; + const repos = yield* driver.getReviewRepositories({ cwd }); + assert.deepStrictEqual( + repos.repositories.map(({ path, branch }) => ({ path, branch })), + [ + { path: "", branch: initialBranch }, + { path: "packages/auth service", branch: "feature/auth" }, + { path: "packages/auth service/vendor/schema", branch: null }, + ], + ); + assert.isFalse(repos.truncated); + yield* git(cwd, [ + "config", + "-f", + ".gitmodules", + "submodule.duplicate.path", + "./packages/auth service", + ]); + yield* git(cwd, [ + "config", + "-f", + ".gitmodules", + "submodule.trailing.path", + "packages/auth service/", + ]); + assert.deepStrictEqual( + (yield* driver.getReviewRepositories({ cwd })).repositories, + repos.repositories, + ); + const subdirectory = NodePath.join(cwd, "packages"); + const scoped = yield* driver.getReviewRepositories({ cwd: subdirectory }); + assert.equal(scoped.repositories[0]!.cwd, subdirectory); + assert.deepStrictEqual( + scoped.repositories.map((repo) => repo.path), + ["", "auth service", "auth service/vendor/schema"], + ); + yield* git(cwd, ["config", "-f", ".gitmodules", "submodule.file.path", "README.md"]); + assert.deepStrictEqual( + (yield* driver.getReviewRepositories({ cwd })).repositories, + repos.repositories, + ); + const commits = yield* driver.getReviewBranchCommits({ cwd: child, baseRef: "HEAD~1" }); + assert.equal(commits.commits.length, 1); + assert.equal(commits.commits[0]!.subject, "Child change"); + const committed = (yield* driver.getReviewDiffPreview({ + cwd: child, + commitSha: commits.commits[0]!.sha, + })).sources[0]!; + assert.deepStrictEqual( + committed.files?.map((file) => file.path), + ["committed.txt"], + ); + assert.include(committed.diff, "+child commit"); + const parent = (yield* driver.getReviewDiffPreview({ cwd, sourceKind: "working-tree" })) + .sources[0]!; + assert.include(parent.diff, "Subproject commit"); + assert.notInclude(parent.diff, "changed auth"); + const auth = (yield* driver.getReviewDiffPreview({ + cwd: child, + sourceKind: "working-tree", + })).sources[0]!; + assert.include(auth.diff, "+# changed auth"); + assert.notInclude(auth.diff, "changed parent"); + assert.deepStrictEqual( + auth.files?.map((file) => file.path), + ["README.md"], + ); + const file = yield* driver.getReviewDiffFileContents( + makeReviewDiffFileContentsInput(child), + ); + assert.equal(file.newContents, "# changed auth\n"); + const fs = yield* FileSystem.FileSystem; + if ((yield* HostProcess.Platform) !== "win32") { + const locked = NodePath.join(cwd, "locked"); + yield* fs.makeDirectory(locked); + yield* git(cwd, ["config", "-f", ".gitmodules", "submodule.locked.path", "locked"]); + yield* fs.chmod(locked, 0); + const result = yield* driver + .getReviewRepositories({ cwd }) + .pipe(Effect.ensuring(fs.chmod(locked, 0o755).pipe(Effect.orDie))); + assert.deepStrictEqual(result.repositories, repos.repositories); + } + // A hostile manifest must not turn discovery into an arbitrary filesystem scan. + yield* git(cwd, ["config", "-f", ".gitmodules", "submodule.escape.path", upstream]); + yield* git(cwd, ["config", "-f", ".gitmodules", "submodule.parent.path", ".."]); + if (symlinksSupported) { + const alias = NodePath.join(yield* makeTmpDir(), "alias"); + yield* fs.symlink(subdirectory, alias); + const throughAlias = yield* driver.getReviewRepositories({ cwd: alias }); + assert.equal(throughAlias.repositories[0]!.cwd, alias); + assert.equal(throughAlias.repositories[1]!.cwd, NodePath.join(alias, "auth service")); + yield* fs.symlink(upstream, NodePath.join(cwd, "escape-link")); + yield* git(cwd, ["config", "-f", ".gitmodules", "submodule.link.path", "escape-link"]); + } + assert.deepStrictEqual( + (yield* driver.getReviewRepositories({ cwd })).repositories, + repos.repositories, + ); + }), + ), + ); it.effect("diffs a root commit against the empty tree but rejects a shallow boundary", () => Effect.gen(function* () { const upstream = yield* makeTmpDir(); diff --git a/apps/server/src/vcs/GitVcsDriverCore.ts b/apps/server/src/vcs/GitVcsDriverCore.ts index 3d8122f197971..0e20471555aed 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.ts @@ -26,6 +26,8 @@ import { type GitCommandFailureReason, T3_PROJECT_FILE_NAME, type ReviewBranchCommitsInput, + type ReviewRepositoriesInput, + type ReviewRepositoriesResult, type ReviewDiffFileContentsInput, type ReviewDiffPreviewInput, type ReviewDiffFileStat, @@ -3366,6 +3368,108 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* }; }); + const getReviewRepositories = Effect.fn("getReviewRepositories")(function* ( + input: ReviewRepositoriesInput, + ) { + const root = yield* resolveRepositoryPathsUncached(input.cwd); + if (!root?.worktreeRoot) return { repositories: [], truncated: false }; + const canonicalRoot = yield* fileSystem + .realPath(root.worktreeRoot) + .pipe(Effect.orElseSucceed(() => root.worktreeRoot!)); + const canonicalWorkspace = yield* fileSystem + .realPath(input.cwd) + .pipe(Effect.orElseSucceed(() => path.resolve(input.cwd))); + const withinRoot = (candidate: string) => { + const relative = path.relative(canonicalWorkspace, candidate); + return ( + relative === "" || + (relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative)) + ); + }; + const repositories: Array = []; + const seen = new Set(); + let pending = [canonicalRoot]; + let truncated = false; + // Discovery is separate from diff/status refreshes and bounded for large umbrellas. + while (pending.length > 0) { + const batch = pending.splice(0, 8); + const found = yield* Effect.forEach( + batch, + (candidate) => + Effect.gen(function* () { + const real = yield* fileSystem + .realPath(candidate) + .pipe(Effect.orElseSucceed(() => null)); + if (!real || (real !== canonicalRoot && !withinRoot(real)) || seen.has(real)) + return null; + seen.add(real); + const stat = yield* fileSystem.stat(real).pipe(Effect.orElseSucceed(() => null)); + if (stat?.type !== "Directory") return null; + const repo = yield* resolveRepositoryPathsUncached(real); + if (!repo?.worktreeRoot) return null; + const actualRoot = yield* fileSystem + .realPath(repo.worktreeRoot) + .pipe(Effect.orElseSucceed(() => null)); + // Git otherwise walks out of an uninitialized module into its parent repository. + if (actualRoot !== real) return null; + const manifest = yield* executeGit( + "GitVcsDriver.review.repositories", + real, + ["config", "-z", "--file=.gitmodules", "--get-regexp", "^submodule\\..*\\.path$"], + { allowNonZeroExit: true, maxOutputBytes: 1024 * 1024 }, + ); + const children = + manifest.exitCode === 0 + ? manifest.stdout.split("\0").flatMap((record) => { + const separator = record.indexOf("\n"); + if (separator < 0) return []; + const relative = record.slice(separator + 1); + if (!relative || path.isAbsolute(relative)) return []; + const child = path.resolve(real, relative); + const local = path.relative(real, child); + return local && + local !== ".." && + !local.startsWith(`..${path.sep}`) && + withinRoot(child) + ? [child] + : []; + }) + : []; + return { + repository: { + cwd: + real === canonicalRoot + ? input.cwd + : path.resolve(input.cwd, path.relative(canonicalWorkspace, real)), + path: + real === canonicalRoot + ? "" + : path.relative(canonicalWorkspace, real).split(path.sep).join("/"), + name: path.basename(real) || "Repository", + branch: repo.currentBranch, + }, + children, + }; + }).pipe( + Effect.catchCause((cause) => + candidate === canonicalRoot ? Effect.failCause(cause) : Effect.succeed(null), + ), + ), + { concurrency: 8 }, + ); + for (const item of found) { + if (!item) continue; + repositories.push(item.repository); + pending.push(...new Set(item.children.filter((child) => !seen.has(child)))); + } + if (seen.size + pending.length > 256) { + pending = pending.slice(0, Math.max(0, 256 - seen.size)); + truncated = true; + } + } + return { repositories: repositories.sort((a, b) => a.path.localeCompare(b.path)), truncated }; + }); + const getReviewBranchCommits = Effect.fn("getReviewBranchCommits")(function* ( input: ReviewBranchCommitsInput, ) { @@ -5196,6 +5300,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* return yield* withListRefsInvalidation(cwd, pullCurrentBranch(cwd)); }), readRangeContext, + getReviewRepositories, getReviewBranchCommits, getReviewDiffPreview, getReviewDiffFileContents, diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index 08a2756bfbe6c..6d6e0efa86482 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -3080,6 +3080,7 @@ export const layerWsRpc = ( gitWorkflow.switchRef(input).pipe(Effect.tap(() => refreshGitStatus(input.cwd))), [WS_METHODS.vcsInit]: (input) => vcsProvisioning.initRepository(input).pipe(Effect.tap(() => refreshGitStatus(input.cwd))), + [WS_METHODS.reviewGetRepositories]: (input) => review.getRepositories(input), [WS_METHODS.reviewGetBranchCommits]: (input) => review.getBranchCommits(input), [WS_METHODS.reviewGetDiffPreview]: (input) => review.getDiffPreview(input), [WS_METHODS.reviewGetDiffFileContents]: (input) => review.getDiffFileContents(input), diff --git a/apps/web/src/components/DiffPanel.browser.test.tsx b/apps/web/src/components/DiffPanel.browser.test.tsx index 5f789469af763..e1cd3e6845b51 100644 --- a/apps/web/src/components/DiffPanel.browser.test.tsx +++ b/apps/web/src/components/DiffPanel.browser.test.tsx @@ -7,6 +7,7 @@ import { ThreadId, type ClientSettings, type ReviewBranchCommitsResult, + type ReviewRepositoriesResult, type ReviewDiffPreviewResult, type ReviewDiffPreviewSource, type ScopedThreadRef, @@ -34,6 +35,7 @@ const state = vi.hoisted(() => ({ status: null as unknown as ResultAtom, localRefs: null as unknown as ResultAtom, remoteRefs: null as unknown as ResultAtom, + repositories: null as unknown as ResultAtom, commits: null as unknown as ResultAtom, })); @@ -44,6 +46,7 @@ vi.mock("~/state/review", () => ({ reviewEnvironment: { diffPreview: ({ input }: { input: { baseRef?: string } }) => state.previews.get(input.baseRef ?? null)!, + repositories: () => state.repositories, branchCommits: () => state.commits, diffFilePatch: () => state.patch, diffFileContents: {}, @@ -121,6 +124,7 @@ function setup(failedBaseRef: string | null) { useDiffPanelStore.setState({ byThreadKey: {}, branchBaseRefByThreadKey: {}, + repositoryCwdByThreadKey: {}, }); useDiffPanelSessionStore.setState({ collapsedFileKeysByScopeKey: {} }); }; @@ -145,6 +149,7 @@ function setup(failedBaseRef: string | null) { state.previews.set(null, Atom.make(AsyncResult.success(preview()))); state.previews.set("main", Atom.make(AsyncResult.success(preview()))); state.previews.set(failedBaseRef, Atom.make(AsyncResult.fail(new Error(errorMessage)))); + state.repositories = Atom.make(AsyncResult.success({ repositories: [], truncated: false })); state.config = Atom.make(null); state.status = Atom.make( AsyncResult.success({ @@ -267,3 +272,34 @@ it.each([false, true])( await expect.element(toggle).toHaveAttribute("aria-expanded", "false"); }, ); + +it("keeps the loading state while a saved repository is still being discovered", async () => { + using context = setup(null); + state.repositories = Atom.make(AsyncResult.initial(true)); + useDiffPanelStore.getState().selectRepository(context.threadRef, `${cwd}/packages/auth`); + await using screen = await render( + + + , + ); + await expect.element(screen.getByRole("status", { name: "Loading changes..." })).toBeVisible(); +}); + +it("shows a failed repository discovery instead of the workspace diff", async () => { + using context = setup(null); + state.repositories = Atom.make(AsyncResult.fail(new Error("discovery failed"))); + useDiffPanelStore.getState().selectRepository(context.threadRef, `${cwd}/packages/auth`); + await using screen = await render( + + + , + ); + await expect.element(screen.getByText("discovery failed", { exact: true })).toBeVisible(); + await userEvent.click(screen.getByRole("button", { name: "Review the thread's repository" })); + await expect + .element(screen.getByText("discovery failed", { exact: true })) + .not.toBeInTheDocument(); + expect( + useDiffPanelStore.getState().repositoryCwdByThreadKey[scopedThreadKey(context.threadRef)], + ).toBeUndefined(); +}); diff --git a/apps/web/src/components/DiffPanel.tsx b/apps/web/src/components/DiffPanel.tsx index 9767972d73d05..3ff5a73523ded 100644 --- a/apps/web/src/components/DiffPanel.tsx +++ b/apps/web/src/components/DiffPanel.tsx @@ -1,3 +1,4 @@ +import { scopedThreadKey } from "@t3tools/client-runtime/environment"; import { RefreshIcon } from "~/components/ui/refresh-icon"; import { useAtomValue } from "@effect/atom-react"; import type { FileDiffContentsLoader, FileDiffMetadata } from "@pierre/diffs"; @@ -259,10 +260,65 @@ export default function DiffPanel({ } : null, ); - const activeCwd = activeThread?.worktreePath ?? activeProject?.workspaceRoot; - const activeRepositoryRoot = activeThread?.worktreePath + const storedDiffSelection = useDiffPanelStore((state) => + selectThreadDiffPanelSelection(state.byThreadKey, routeThreadRef), + ); + const workspaceCwd = activeThread?.worktreePath ?? activeProject?.workspaceRoot; + const [repositoryQuery, setRepositoryQuery] = useState(""); + const requestedRepositoryCwd = useDiffPanelStore((state) => + routeThreadRef ? state.repositoryCwdByThreadKey[scopedThreadKey(routeThreadRef)] : undefined, + ); + const repositoriesQuery = useEnvironmentQuery( + visible && canReadFiles && activeThread && workspaceCwd + ? reviewEnvironment.repositories({ + environmentId: activeThread.environmentId, + input: { cwd: workspaceCwd }, + }) + : null, + ); + const repositories = (repositoriesQuery.data?.repositories ?? []).map((repo) => + repo.path ? repo : { ...repo, name: activeProject?.title || repo.name }, + ); + const selectedRepository = + repositories.find((repo) => repo.cwd === requestedRepositoryCwd) ?? repositories[0]; + const isRepositoryDiff = + storedDiffSelection.kind === "branch" || + storedDiffSelection.kind === "unstaged" || + storedDiffSelection.kind === "commit"; + const repositoryMissing = + !!requestedRepositoryCwd && + repositoriesQuery.data !== null && + !repositories.some((repo) => repo.cwd === requestedRepositoryCwd); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- clears a persisted child repository and its refs after that repository disappears + useEffect(() => { + if (repositoryMissing && routeThreadRef && repositories[0]) + useDiffPanelStore.getState().clearRepository(routeThreadRef); + }, [repositoryMissing, routeThreadRef, repositories]); + const diffSelection = + repositoryMissing && isRepositoryDiff + ? { kind: "branch" as const, baseRef: null } + : storedDiffSelection; + // A saved child stays unresolved until discovery answers; the thread's repository needs no answer. + const repositoryUnresolved = + !!requestedRepositoryCwd && requestedRepositoryCwd !== workspaceCwd && !repositoriesQuery.data; + const repositoryPending = repositoryUnresolved && repositoriesQuery.isPending; + const repositoryError = + repositoryUnresolved && !repositoriesQuery.isPending ? repositoriesQuery.error : null; + const repositoryCwd = repositoryUnresolved ? undefined - : activeProject?.repositoryIdentity?.rootPath; + : selectedRepository?.path + ? selectedRepository.cwd + : workspaceCwd; + const activeCwd = isRepositoryDiff ? repositoryCwd : workspaceCwd; + const isChildRepository = isRepositoryDiff && !!selectedRepository?.path; + const repositoryLabel = selectedRepository + ? selectedRepository.name + ": " + (selectedRepository.branch ?? "HEAD") + : "Repository"; + const activeRepositoryRoot = isChildRepository + ? activeCwd + : activeThread?.worktreePath + ? undefined + : activeProject?.repositoryIdentity?.rootPath; const serverConfig = useAtomValue( serverEnvironment.configValueAtom(activeThread?.environmentId ?? null), ); @@ -276,13 +332,11 @@ export default function DiffPanel({ activeThread !== null && activeThread !== undefined && activeCwd != null ? vcsEnvironment.status({ environmentId: activeThread.environmentId, - input: { cwd: activeCwd }, + input: { cwd: activeCwd, ...(isChildRepository ? { includeRemote: false } : {}) }, }) : null, ); - const diffSelection = useDiffPanelStore((state) => - selectThreadDiffPanelSelection(state.byThreadKey, routeThreadRef), - ); + const rememberedBaseRef = useDiffPanelStore((state) => selectThreadBranchBaseRef(state, routeThreadRef), ); @@ -347,7 +401,7 @@ export default function DiffPanel({ ? `commit:${selectedCommitSha}` : selectedGitScope; const collapseScopeKey = routeThreadRef - ? `${routeThreadRef.environmentId}:${routeThreadRef.threadId}:${reviewSectionId}` + ? `${routeThreadRef.environmentId}:${routeThreadRef.threadId}:${isRepositoryDiff ? activeCwd : ""}:${reviewSectionId}` : null; const codeViewMountKey = `${collapseScopeKey ?? reviewSectionId}:${codeViewRevision}`; const selectedCheckpointRange = @@ -402,12 +456,12 @@ export default function DiffPanel({ : null, ); const branchCommitsQuery = useEnvironmentQuery( - visible && isGitRepo && canReadFiles && activeThread && activeCwd + visible && isGitRepo && canReadFiles && activeThread && repositoryCwd ? reviewEnvironment.branchCommits({ environmentId: activeThread.environmentId, input: { - cwd: activeCwd, - ...(rememberedBaseRef ? { baseRef: rememberedBaseRef } : {}), + cwd: repositoryCwd, + ...(!repositoryMissing && rememberedBaseRef ? { baseRef: rememberedBaseRef } : {}), }, }) : null, @@ -455,7 +509,10 @@ export default function DiffPanel({ const headerCommitSha = selectedRunId === null ? selectedCommitSha : null; const selectedCommitUrl = headerCommitSha !== null - ? projectCommitUrl(activeProject?.repositoryIdentity, headerCommitSha) + ? projectCommitUrl( + isChildRepository ? null : activeProject?.repositoryIdentity, + headerCommitSha, + ) : null; const openLink = useOpenLink(routeThreadRef); // A SHA link goes to the code host; it must not route back into this pane's commit selection. @@ -467,7 +524,10 @@ export default function DiffPanel({ void openLink(url, { event }); }; const refreshPreviewQuery = branchDiffPreview.refresh; - const refreshDiffFromUserAction = refreshPreviewQuery; + const refreshDiffFromUserAction = () => { + repositoriesQuery.refresh(); + refreshPreviewQuery(); + }; const preview = branchDiffPreview.data; const gitDiff = selectedGitSource?.diff; @@ -488,14 +548,17 @@ export default function DiffPanel({ ? activeCheckpointDiff : branchDiffPreview; const isLoadingSelectedPatch = - selectedPatchQuery.isPending && - (selectedPatchQuery.data === null || - (isGitSelection && preview?.incomplete === true && selectedGitSource?.files?.length === 0)); + (isGitSelection && repositoryPending) || + (selectedPatchQuery.isPending && + (selectedPatchQuery.data === null || + (isGitSelection && + preview?.incomplete === true && + selectedGitSource?.files?.length === 0))); const selectedPatchError = toolCallSelection ? toolCallDetail.error : selectedTurn ? activeCheckpointDiff.error - : branchDiffPreview.error; + : (repositoryError ?? branchDiffPreview.error); const hasResolvedPatch = typeof selectedPatch === "string"; const hasNoNetChanges = hasResolvedPatch && @@ -729,8 +792,11 @@ export default function DiffPanel({ openDiffFilePrimaryAction({ threadRef: routeThreadRef, filePath, - activeCwd, - repositoryRoot: activeRepositoryRoot, + activeCwd: workspaceCwd, + fileCwd: isChildRepository ? selectedRepository?.cwd : undefined, + repositoryRoot: activeThread?.worktreePath + ? undefined + : activeProject?.repositoryIdentity?.rootPath, openInEditor: (targetPath) => { void (async () => { const result = await openInPreferredEditor(targetPath); @@ -819,7 +885,72 @@ export default function DiffPanel({ const headerRow = ( <> -
+
+ {repositories.length > 1 && ( + repo.cwd)} + filteredItems={repositories + .filter((repo) => + (repo.name + ": " + (repo.branch ?? "HEAD") + " " + repo.path) + .toLowerCase() + .includes(repositoryQuery.trim().toLowerCase()), + ) + .map((repo) => repo.cwd)} + value={selectedRepository?.cwd ?? null} + onOpenChange={(open) => { + if (open) repositoriesQuery.refresh(); + else setRepositoryQuery(""); + }} + onValueChange={(cwd) => { + if (!routeThreadRef || !cwd || !repositories.some((repo) => repo.cwd === cwd)) return; + useDiffPanelStore.getState().selectRepository(routeThreadRef, cwd); + setOpenCommitMenu(null); + setBaseRefQuery(""); + }} + > + } + aria-label={"Repository: " + repositoryLabel} + title="Repository for Changes, Uncommitted and Commits. Turn diffs use the thread checkpoints." + > + {repositoryLabel} + + + + setRepositoryQuery(event.target.value)} + /> + No matching repository. + + {(cwd) => { + const repo = repositories.find((repo) => repo.cwd === cwd)!; + return ( + + + + {repo.name}: {repo.branch ?? "HEAD"} + + + {repo.path || "Workspace repository"} + + + + ); + }} + + {repositoriesQuery.data?.truncated && ( +

+ Repository discovery reached its limit. +

+ )} + {repositoriesQuery.error && ( +

{repositoriesQuery.error}

+ )} +
+
+ )} } @@ -906,7 +1037,7 @@ export default function DiffPanel({ > {branchCommits?.commits.map((commit) => { const commitUrl = projectCommitUrl( - activeProject?.repositoryIdentity, + isChildRepository ? null : activeProject?.repositoryIdentity, commit.sha, ); return ( @@ -1329,6 +1460,20 @@ export default function DiffPanel({ {selectedPatchError && !renderablePatch && (

{selectedPatchError}

+ {isGitSelection && repositoryError && routeThreadRef && ( +
+ + +
+ )}
)} {!renderablePatch && toolCallPreview && toolCallPreview.content.length > 0 ? ( @@ -1437,7 +1582,12 @@ export default function DiffPanel({ files={codeViewFiles} pendingFiles={pendingFiles} renderCodeViewFooter={renderLoadingBoundary} - sectionId={reviewSectionId} + filePathPrefix={isChildRepository ? selectedRepository?.path : undefined} + sectionId={ + isChildRepository + ? selectedRepository?.path + ":" + reviewSectionId + : reviewSectionId + } sectionTitle={reviewSectionTitle} composerDraftTarget={composerDraftTarget} renderHeaderFilenameSuffix={(fileDiff) => { diff --git a/apps/web/src/components/DiffPanelShell.tsx b/apps/web/src/components/DiffPanelShell.tsx index 456f70516b23b..cc548f05cf8a9 100644 --- a/apps/web/src/components/DiffPanelShell.tsx +++ b/apps/web/src/components/DiffPanelShell.tsx @@ -10,7 +10,7 @@ export type DiffPanelMode = "inline" | "sheet" | "sidebar" | "embedded"; function getDiffPanelHeaderRowClassName(mode: DiffPanelMode) { const shouldUseDragRegion = isElectron && mode !== "sheet" && mode !== "embedded"; return cn( - "flex items-center justify-between gap-2", + "flex items-center justify-between gap-2 @max-[42rem]/diff-panel:flex-wrap @max-[42rem]/diff-panel:h-auto @max-[42rem]/diff-panel:py-1", mode === "embedded" ? "px-2" : "px-4", shouldUseDragRegion ? "drag-region h-[var(--workspace-topbar-height)] border-b border-border wco:pr-(--workspace-native-controls-inset)" @@ -28,7 +28,7 @@ export function DiffPanelShell(props: { return (
[], codeViewKey = "initial", pendingFiles: FileDiffMetadata[] = [], + filePathPrefix = "", ) { return ( { - it("keeps the text and selected line through refresh and a provisional lazy patch", async () => { - using _drafts = setup(); - const original = file("shared.ts", 1, "rename-pure", "old.ts"); - await using screen = await render(view([original]), { container }); - await click("Comment on shared.ts"); - await typeComment("Keep this draft"); - const refreshed = file("shared.ts", 2, "rename-pure", "old.ts"); - await screen.rerender(view([refreshed], "refreshed")); - expect(editor().value).toBe("Keep this draft"); - expect(container.querySelector("mark")?.textContent).toBe("Line 1"); + it.each(["", "packages/auth"])( + "keeps a comment through lazy refresh with repository prefix %j", + async (prefix) => { + using _drafts = setup(); + const original = file("shared.ts", 1, "rename-pure", "old.ts"); + await using screen = await render(view([original], "initial", [], prefix), { container }); + await click("Comment on shared.ts"); + await typeComment("Keep this draft"); + const refreshed = file("shared.ts", 2, "rename-pure", "old.ts"); + await screen.rerender(view([refreshed], "refreshed", [], prefix)); + expect(editor().value).toBe("Keep this draft"); + expect(container.querySelector("mark")?.textContent).toBe("Line 1"); - await screen.rerender( - view([], "loading", [ - { ...refreshed.fileDiff, type: "rename-changed", hunks: [], cacheKey: "shared:pending" }, - ]), - ); - expect(container.querySelector("textarea")).toBeNull(); - await screen.rerender(view([refreshed], "loaded")); - expect(editor().value).toBe("Keep this draft"); - expect(container.querySelector("mark")?.textContent).toBe("Line 1"); - await click("Comment"); - expect(useComposerDraftStore.getState().getComposerDraft(target)?.reviewComments).toEqual([ - expect.objectContaining({ - filePath: "shared.ts", - text: "Keep this draft", - selection: { ...range, endSide: "additions" }, - }), - ]); - expect(container.querySelector("p")?.textContent).toBe("Keep this draft"); - }); + await screen.rerender( + view( + [], + "loading", + [ + { + ...refreshed.fileDiff, + type: "rename-changed", + hunks: [], + cacheKey: "shared:pending", + }, + ], + prefix, + ), + ); + expect(container.querySelector("textarea")).toBeNull(); + await screen.rerender(view([refreshed], "loaded", [], prefix)); + expect(editor().value).toBe("Keep this draft"); + expect(container.querySelector("mark")?.textContent).toBe("Line 1"); + await click("Comment"); + expect(useComposerDraftStore.getState().getComposerDraft(target)?.reviewComments).toEqual([ + expect.objectContaining({ + filePath: prefix ? prefix + "/shared.ts" : "shared.ts", + text: "Keep this draft", + selection: { ...range, endSide: "additions" }, + }), + ]); + expect(container.querySelector("p")?.textContent).toBe("Keep this draft"); + }, + ); }); diff --git a/apps/web/src/components/diffs/AnnotatableCodeView.tsx b/apps/web/src/components/diffs/AnnotatableCodeView.tsx index b7965428478fb..896ae0c5f8e9d 100644 --- a/apps/web/src/components/diffs/AnnotatableCodeView.tsx +++ b/apps/web/src/components/diffs/AnnotatableCodeView.tsx @@ -83,6 +83,7 @@ interface AnnotatableCodeViewProps { collapsed: boolean; }>; pendingFiles: ReadonlyArray; + filePathPrefix?: string | undefined; sectionId: string; sectionTitle: string; composerDraftTarget: ScopedThreadRef | DraftId; @@ -109,6 +110,7 @@ export function AnnotatableCodeView({ environmentId, projectId, codeViewKey, + filePathPrefix, files, pendingFiles, sectionId, @@ -141,6 +143,8 @@ export function AnnotatableCodeView({ } | null>(null); const [draftText, setDraftText] = useState(""); + const commentPath = (filePath: string) => + filePathPrefix ? filePathPrefix + "/" + filePath : filePath; const filesByKey = new Map(files.map((file) => [file.fileKey, file])); if ( draft !== null && @@ -162,7 +166,7 @@ export function AnnotatableCodeView({ .filter( (comment) => comment.sectionId === sectionId && - comment.filePath === filePath && + comment.filePath === commentPath(filePath) && (comment.fenceLanguage ?? "diff") === "diff", ) .reduce((annotations, comment) => { @@ -214,7 +218,7 @@ export function AnnotatableCodeView({ id: entry.id, sectionId, sectionTitle, - filePath: file.filePath, + filePath: commentPath(file.filePath), fileDiff: file.fileDiff, range: entry.range, text, @@ -235,7 +239,7 @@ export function AnnotatableCodeView({ id, sectionId, sectionTitle, - filePath, + filePath: commentPath(filePath), fileDiff: item.fileDiff, range, text: "", diff --git a/apps/web/src/diffFileActions.test.ts b/apps/web/src/diffFileActions.test.ts index f7faf72ef8bd3..8aa447527faa2 100644 --- a/apps/web/src/diffFileActions.test.ts +++ b/apps/web/src/diffFileActions.test.ts @@ -15,25 +15,58 @@ describe("openDiffFilePrimaryAction", () => { useRightPanelStore.setState({ byThreadKey: {}, threadPanelVisibilityByThreadKey: {} }); }); - it("opens repository-relative diff files from a nested project", () => { - const openInEditor = vi.fn(); - - openDiffFilePrimaryAction({ - threadRef: THREAD_REF, + it.each([ + { filePath: "frontend/Dockerfile", activeCwd: "/repo/frontend", repositoryRoot: "/repo", - openInEditor, - }); + fileCwd: undefined, + expected: "Dockerfile", + }, + { + filePath: "src/policy.ts", + activeCwd: "/repo", + repositoryRoot: "/repo", + fileCwd: "/repo/packages/auth", + expected: "packages/auth/src/policy.ts", + }, + { + filePath: "src/policy.ts", + activeCwd: "/repo/packages", + repositoryRoot: "/repo", + fileCwd: "/repo/packages/auth", + expected: "auth/src/policy.ts", + }, + { + filePath: "notes:1-2", + activeCwd: "/repo", + repositoryRoot: "/repo", + fileCwd: "/repo/packages/auth", + expected: "packages/auth/notes:1-2", + }, + ])( + "opens a diff in its workspace at $expected", + ({ filePath, activeCwd, repositoryRoot, fileCwd, expected }) => { + const openInEditor = vi.fn(); - expect( - selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, THREAD_REF), - ).toMatchObject({ - isOpen: true, - activeSurfaceId: "file:Dockerfile", - }); - expect(openInEditor).not.toHaveBeenCalled(); - }); + openDiffFilePrimaryAction({ + threadRef: THREAD_REF, + filePath, + activeCwd, + repositoryRoot, + fileCwd, + openInEditor, + }); + + expect( + selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, THREAD_REF), + ).toMatchObject({ + isOpen: true, + activeSurfaceId: `file:${expected}`, + }); + expect(openInEditor).not.toHaveBeenCalled(); + }, + ); it("preserves repository-relative paths in a separate worktree", () => { expect( diff --git a/apps/web/src/diffFileActions.ts b/apps/web/src/diffFileActions.ts index c6a3fa3d436fc..06b96afe22df4 100644 --- a/apps/web/src/diffFileActions.ts +++ b/apps/web/src/diffFileActions.ts @@ -7,12 +7,13 @@ import { } from "@t3tools/shared/path"; import { useRightPanelStore } from "./rightPanelStore"; -import { resolvePathLinkTarget } from "@t3tools/shared/fileLinks"; +import { joinPath, resolvePathLinkTarget } from "@t3tools/shared/fileLinks"; interface OpenDiffFilePrimaryActionInput { readonly threadRef: ScopedThreadRef | null; readonly filePath: string; readonly activeCwd: string | undefined; + readonly fileCwd?: string | undefined; readonly repositoryRoot?: string | undefined; readonly openInEditor: (targetPath: string) => void; } @@ -93,11 +94,15 @@ export function openDiffFilePrimaryAction({ threadRef, filePath, activeCwd, + fileCwd, repositoryRoot, openInEditor, }: OpenDiffFilePrimaryActionInput): void { const workspaceFilePath = resolveDiffPathForWorkspace({ - filePath, + // Git paths are literal: a trailing ":12" is part of the name, not a line position. + filePath: fileCwd + ? joinPath(fileCwd, filePath, fileCwd.startsWith("/") ? "/" : "\\") + : filePath, workspaceRoot: activeCwd, repositoryRoot, }); diff --git a/apps/web/src/diffPanelStore.test.ts b/apps/web/src/diffPanelStore.test.ts index 82065c86fe3aa..8675910ffe9ff 100644 --- a/apps/web/src/diffPanelStore.test.ts +++ b/apps/web/src/diffPanelStore.test.ts @@ -1,4 +1,4 @@ -import { EnvironmentId, ThreadId, TurnItemId } from "@t3tools/contracts"; +import { EnvironmentId, ThreadId, TurnItemId, RunId } from "@t3tools/contracts"; import * as DateTime from "effect/DateTime"; import { scopedThreadKey } from "@t3tools/client-runtime/environment"; import { beforeEach, describe, expect, it } from "vite-plus/test"; @@ -10,10 +10,57 @@ import { } from "./diffPanelStore"; describe("diffPanelStore", () => { + it("resets repository-specific refs and commits when changing repositories", () => { + const ref = { environmentId: EnvironmentId.make("env"), threadId: ThreadId.make("thread") }; + const other = { ...ref, environmentId: EnvironmentId.make("remote") }; + const key = scopedThreadKey(ref); + const store = useDiffPanelStore.getState(); + store.selectBranchBaseRef(ref, "parent-only-branch"); + store.selectCommit(ref, "parent-commit"); + store.selectRepository(ref, "/project/auth"); + expect(useDiffPanelStore.getState().byThreadKey[key]).toEqual({ + kind: "branch", + baseRef: null, + }); + expect(useDiffPanelStore.getState().repositoryCwdByThreadKey[key]).toBe("/project/auth"); + expect( + useDiffPanelStore.getState().repositoryCwdByThreadKey[scopedThreadKey(other)], + ).toBeUndefined(); + store.selectGitScope(ref, "unstaged"); + store.selectRepository(ref, "/project/ui"); + expect(useDiffPanelStore.getState().byThreadKey[key]).toEqual({ kind: "unstaged" }); + store.selectBranchBaseRef(ref, "child-only-branch"); + store.clearRepository(ref); + store.selectCommit(ref, "linked-parent-commit"); + expect(useDiffPanelStore.getState().repositoryCwdByThreadKey[key]).toBeUndefined(); + expect(useDiffPanelStore.getState().byThreadKey[key]).toEqual({ + kind: "commit", + sha: "linked-parent-commit", + baseRef: null, + }); + store.selectRepository(ref, "/project/auth"); + store.selectTurn(ref, RunId.make("turn"), "file.ts"); + const turn = useDiffPanelStore.getState().byThreadKey[key]; + store.clearRepository(ref); + expect(useDiffPanelStore.getState().byThreadKey[key]).toEqual(turn); + store.selectRepository(ref, "/project/auth"); + store.selectToolCall(ref, { + threadId: ThreadId.make("child"), + itemId: TurnItemId.make("edit"), + revision: "1", + }); + const tool = useDiffPanelStore.getState().byThreadKey[key]; + store.clearRepository(ref); + expect(useDiffPanelStore.getState().byThreadKey[key]).toEqual(tool); + store.selectRepository(ref, "/project/auth"); + store.removeThread(ref); + expect(useDiffPanelStore.getState().repositoryCwdByThreadKey[key]).toBeUndefined(); + }); beforeEach(() => { useDiffPanelStore.setState({ byThreadKey: {}, branchBaseRefByThreadKey: {}, + repositoryCwdByThreadKey: {}, }); useDiffPanelSessionStore.setState({ collapsedFileKeysByScopeKey: {} }); }); diff --git a/apps/web/src/diffPanelStore.ts b/apps/web/src/diffPanelStore.ts index 2f685005c1e74..491c1d3dbacb1 100644 --- a/apps/web/src/diffPanelStore.ts +++ b/apps/web/src/diffPanelStore.ts @@ -25,6 +25,9 @@ const DEFAULT_SELECTION: DiffPanelSelection = { kind: "branch", baseRef: null }; interface DiffPanelStoreState { byThreadKey: Record; branchBaseRefByThreadKey: Record; + repositoryCwdByThreadKey: Record; + selectRepository: (ref: ScopedThreadRef, cwd: string) => void; + clearRepository: (ref: ScopedThreadRef) => void; selectGitScope: (ref: ScopedThreadRef, scope: "branch" | "unstaged") => void; selectBranchBaseRef: (ref: ScopedThreadRef, baseRef: string | null) => void; selectToolCall: (ref: ScopedThreadRef, target: ToolCallDiffTarget) => void; @@ -54,6 +57,42 @@ export const useDiffPanelStore = create()( (set) => ({ byThreadKey: {}, branchBaseRefByThreadKey: {}, + repositoryCwdByThreadKey: {}, + selectRepository: (ref, cwd) => + set((state) => { + const key = scopedThreadKey(ref); + return { + repositoryCwdByThreadKey: { ...state.repositoryCwdByThreadKey, [key]: cwd }, + byThreadKey: { + ...state.byThreadKey, + [key]: + state.byThreadKey[key]?.kind === "unstaged" + ? { kind: "unstaged" } + : { kind: "branch", baseRef: null }, + }, + branchBaseRefByThreadKey: { ...state.branchBaseRefByThreadKey, [key]: null }, + }; + }), + clearRepository: (ref) => + set((state) => { + const key = scopedThreadKey(ref); + const { [key]: _removedRepository, ...repositoryCwdByThreadKey } = + state.repositoryCwdByThreadKey; + const previous = state.byThreadKey[key]; + return { + repositoryCwdByThreadKey, + branchBaseRefByThreadKey: { ...state.branchBaseRefByThreadKey, [key]: null }, + byThreadKey: { + ...state.byThreadKey, + [key]: + previous?.kind === "turn" || + previous?.kind === "tool-call" || + previous?.kind === "unstaged" + ? previous + : { kind: "branch", baseRef: null }, + }, + }; + }), selectGitScope: (ref, scope) => set((state) => { const threadKey = scopedThreadKey(ref); @@ -145,13 +184,19 @@ export const useDiffPanelStore = create()( removeThread: (ref) => set((state) => { const threadKey = scopedThreadKey(ref); - if (!(threadKey in state.byThreadKey) && !(threadKey in state.branchBaseRefByThreadKey)) { + if ( + !(threadKey in state.byThreadKey) && + !(threadKey in state.branchBaseRefByThreadKey) && + !(threadKey in state.repositoryCwdByThreadKey) + ) { return state; } const { [threadKey]: _removed, ...byThreadKey } = state.byThreadKey; const { [threadKey]: _removedBaseRef, ...branchBaseRefByThreadKey } = state.branchBaseRefByThreadKey; - return { byThreadKey, branchBaseRefByThreadKey }; + const { [threadKey]: _removedRepository, ...repositoryCwdByThreadKey } = + state.repositoryCwdByThreadKey; + return { byThreadKey, branchBaseRefByThreadKey, repositoryCwdByThreadKey }; }), }), { @@ -163,6 +208,7 @@ export const useDiffPanelStore = create()( partialize: (state) => ({ byThreadKey: state.byThreadKey, branchBaseRefByThreadKey: state.branchBaseRefByThreadKey, + repositoryCwdByThreadKey: state.repositoryCwdByThreadKey, }), }, ), diff --git a/apps/web/src/lib/openPullRequestLink.browser.test.tsx b/apps/web/src/lib/openPullRequestLink.browser.test.tsx index 2d7aceeb304dc..3c123f62c3018 100644 --- a/apps/web/src/lib/openPullRequestLink.browser.test.tsx +++ b/apps/web/src/lib/openPullRequestLink.browser.test.tsx @@ -75,6 +75,7 @@ function setup() { }); useDiffPanelStore.setState({ byThreadKey: {}, + repositoryCwdByThreadKey: {}, branchBaseRefByThreadKey: {}, }); useRightPanelStore.setState({ byThreadKey: {}, userActionRevisionByThreadKey: {} }); @@ -139,21 +140,48 @@ it.each(["system", "app"] as const)( }, ); -it("opens an available commit in the closed Diff pane without the pane resetting it", async () => { - setup(); - const sha = "a".repeat(40); - state.preview.mockResolvedValue( - AsyncResult.success({ sources: [{ kind: "commit", headRef: sha }] }), - ); - await using screen = await render( - - - , - ); - await screen.getByRole("link", { name: "Commit" }).click(); - await vi.waitFor(() => - expect(useDiffPanelStore.getState().byThreadKey).toEqual({ - [scopedThreadKey(threadRef)]: { kind: "commit", sha, baseRef: null }, - }), - ); -}); +it.each( + [false, true].flatMap((diffOpen) => + ["child", "parent", "default"].map((repository) => ({ diffOpen, repository })), + ), +)( + "opens a linked parent commit with $repository selected and diffOpen=$diffOpen", + async ({ diffOpen, repository }) => { + setup(); + if (repository !== "default") + useDiffPanelStore + .getState() + .selectRepository(threadRef, repository === "child" ? "/repo/auth" : "/repo"); + const expectedBase = repository === "child" ? null : "origin/develop"; + useDiffPanelStore + .getState() + .selectBranchBaseRef( + threadRef, + repository === "child" ? "child-only-branch" : "origin/develop", + ); + if (diffOpen) useRightPanelStore.getState().open(threadRef, "diff"); + const sha = "a".repeat(40); + state.preview.mockResolvedValue( + AsyncResult.success({ sources: [{ kind: "commit", headRef: sha }] }), + ); + await using screen = await render( + + + , + ); + await screen.getByRole("link", { name: "Commit" }).click(); + await vi.waitFor(() => + expect(useDiffPanelStore.getState().byThreadKey).toEqual({ + [scopedThreadKey(threadRef)]: { kind: "commit", sha, baseRef: expectedBase }, + }), + ); + expect(useDiffPanelStore.getState().repositoryCwdByThreadKey[scopedThreadKey(threadRef)]).toBe( + repository === "parent" ? "/repo" : undefined, + ); + useDiffPanelStore.getState().selectGitScope(threadRef, "branch"); + expect(useDiffPanelStore.getState().byThreadKey[scopedThreadKey(threadRef)]).toEqual({ + kind: "branch", + baseRef: expectedBase, + }); + }, +); diff --git a/apps/web/src/lib/openPullRequestLink.ts b/apps/web/src/lib/openPullRequestLink.ts index 9b6591f34be0e..018f9ed42e425 100644 --- a/apps/web/src/lib/openPullRequestLink.ts +++ b/apps/web/src/lib/openPullRequestLink.ts @@ -1,3 +1,5 @@ +import { scopedThreadKey } from "@t3tools/client-runtime/environment"; +import { normalizeProjectPathForComparison } from "@t3tools/shared/path"; import { parsePullRequestAnchor } from "@t3tools/shared/pullRequestAnchor"; import type { EnvironmentId, ScopedThreadRef } from "@t3tools/contracts"; import { useAtomValue } from "@effect/atom-react"; @@ -199,6 +201,17 @@ export function useOpenChangeRequestLink( (source) => source.kind === "commit" && source.headRef === commit.sha, ) ) { + const selectedCwd = + useDiffPanelStore.getState().repositoryCwdByThreadKey[ + scopedThreadKey(resolvedThreadRef) + ]; + const workspaceCwd = commitThread.worktreePath ?? commitProject.workspaceRoot; + if ( + selectedCwd && + normalizeProjectPathForComparison(selectedCwd) !== + normalizeProjectPathForComparison(workspaceCwd) + ) + useDiffPanelStore.getState().clearRepository(resolvedThreadRef); useDiffPanelStore.getState().selectCommit(resolvedThreadRef, commit.sha); useRightPanelStore.getState().open(resolvedThreadRef, "diff"); return; diff --git a/docs/user/source-control.md b/docs/user/source-control.md index 8bbeb7e988cbe..b75dfef035d0b 100644 --- a/docs/user/source-control.md +++ b/docs/user/source-control.md @@ -20,6 +20,17 @@ commit links follow your **Open links in** setting; on web, when that opens a ne shows an **Open link** button. Command/Ctrl+Click always opens the link in your browser. Commit links follow the **Open pull requests in T3 Code** setting in **Settings → Diffs**. +## Review a submodule + +The Diff pane starts with the thread's repository. Its changes include submodule commit +pointers, as in Git. Use the repository picker to review an initialized submodule, including +nested submodules, without opening another project. Detached checkouts appear as HEAD. + +Changes, Uncommitted, commit lists and comparison branches use the selected repository. +Switching repositories resets the comparison branch to Automatic. File paths are relative to +the selected repository. Turn diffs still show the thread's checkpoints and do not capture +uncommitted contents inside submodules. Initialize a submodule with Git before selecting it. + ## Connect an account Install Git and configure authentication on the machine running your T3 Code server. For a remote diff --git a/packages/client-runtime/src/state/review.ts b/packages/client-runtime/src/state/review.ts index a374e51b1df89..baddcf6afc248 100644 --- a/packages/client-runtime/src/state/review.ts +++ b/packages/client-runtime/src/state/review.ts @@ -74,6 +74,11 @@ export function createReviewEnvironmentAtoms( }); }); return { + repositories: createEnvironmentRpcQueryAtomFamily(runtime, { + label: "environment-data:review:repositories", + tag: WS_METHODS.reviewGetRepositories, + staleTimeMs: 30_000, + }), branchCommits: createEnvironmentRpcQueryAtomFamily(runtime, { label: "environment-data:review:branch-commits", tag: WS_METHODS.reviewGetBranchCommits, diff --git a/packages/contracts/src/review.ts b/packages/contracts/src/review.ts index 2608e635ba906..dbb426e5793d1 100644 --- a/packages/contracts/src/review.ts +++ b/packages/contracts/src/review.ts @@ -3,6 +3,21 @@ import { TrimmedNonEmptyString } from "./baseSchemas.ts"; import { GitCommandError } from "./git.ts"; import { VcsError } from "./vcs.ts"; +export const ReviewRepositoriesInput = Schema.Struct({ cwd: TrimmedNonEmptyString }); +export type ReviewRepositoriesInput = typeof ReviewRepositoriesInput.Type; +export const ReviewRepositoriesResult = Schema.Struct({ + repositories: Schema.Array( + Schema.Struct({ + cwd: TrimmedNonEmptyString, + path: Schema.String, + name: Schema.NonEmptyString, + branch: Schema.NullOr(TrimmedNonEmptyString), + }), + ), + truncated: Schema.Boolean, +}); +export type ReviewRepositoriesResult = typeof ReviewRepositoriesResult.Type; + export const ReviewDiffPreviewInput = Schema.Struct({ cwd: TrimmedNonEmptyString, baseRef: Schema.optional(TrimmedNonEmptyString), diff --git a/packages/contracts/src/rpc.ts b/packages/contracts/src/rpc.ts index 0f6af19188e18..02e34b48ea74b 100644 --- a/packages/contracts/src/rpc.ts +++ b/packages/contracts/src/rpc.ts @@ -151,6 +151,8 @@ import { VcsStatusStreamEvent, } from "./git.ts"; import { + ReviewRepositoriesInput, + ReviewRepositoriesResult, ReviewBranchCommitsInput, ReviewBranchCommitsResult, ReviewDiffFileContentsInput, @@ -470,6 +472,7 @@ export const WS_METHODS = { gitResolvePullRequest: "git.resolvePullRequest", gitPreparePullRequestThread: "git.preparePullRequestThread", + reviewGetRepositories: "review.getRepositories", reviewGetBranchCommits: "review.getBranchCommits", reviewGetDiffPreview: "review.getDiffPreview", reviewGetDiffFileContents: "review.getDiffFileContents", @@ -1581,6 +1584,12 @@ const WsVcsInitRpc = Rpc.make(WS_METHODS.vcsInit, { error: Schema.Union([VcsError, EnvironmentAuthorizationError]), }); +const WsReviewGetRepositoriesRpc = Rpc.make(WS_METHODS.reviewGetRepositories, { + payload: ReviewRepositoriesInput, + success: ReviewRepositoriesResult, + error: Schema.Union([ReviewDiffPreviewError, EnvironmentAuthorizationError]), +}); + const WsReviewGetBranchCommitsRpc = Rpc.make(WS_METHODS.reviewGetBranchCommits, { payload: ReviewBranchCommitsInput, success: ReviewBranchCommitsResult, @@ -2223,6 +2232,7 @@ export const WsRpcGroup = RpcGroup.make( WsVcsCreateRefRpc, WsVcsSwitchRefRpc, WsVcsInitRpc, + WsReviewGetRepositoriesRpc, WsReviewGetBranchCommitsRpc, WsReviewGetDiffPreviewRpc, WsReviewGetDiffFileContentsRpc,