diff --git a/apps/mobile/src/features/review/ReviewSheet.tsx b/apps/mobile/src/features/review/ReviewSheet.tsx index 7142394011e5e..6b9fa1b72e9fe 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 { LegendList } from "@legendapp/list/react-native"; import { useNavigation, type StaticScreenProps } from "@react-navigation/native"; @@ -63,6 +63,9 @@ import type { usePullRequestFileFilter } from "../pull-requests/usePullRequestFi function ReviewHeader( props: Parameters[0] & { + readonly repositories: ReviewRepositoriesResult["repositories"]; + readonly selectedGitRepository: ReviewRepositoriesResult["repositories"][number] | undefined; + readonly onSelectGitRepository: (cwd: string) => void; readonly sectionMenu: ReturnType; readonly showSectionToolbar: boolean; readonly showChangedFilesToggle: boolean; @@ -108,6 +111,21 @@ function ReviewHeader( : undefined } menus={[ + ...(props.repositories.length > 1 + ? [ + { + title: gt("Select Git repository"), + icon: "folder" as const, + items: props.repositories.map((repo) => ({ + id: repo.cwd, + title: repo.name + ": " + (repo.branch ?? "HEAD"), + subtitle: repo.path || gt("Workspace repository"), + selected: repo.cwd === props.selectedGitRepository?.cwd, + onPress: () => props.onSelectGitRepository(repo.cwd), + })), + }, + ] + : []), ...(presentation.gitMenu ? [presentation.gitMenu] : []), ...(props.showSectionToolbar ? [ @@ -421,6 +439,11 @@ export function ReviewSheet(props: ReviewSheetProps) { refreshSelectedSection, selectSection, isSelectedSectionPending, + repositories, + selectedRepository: selectedGitRepository, + selectRepository: selectGitRepository, + reviewCwd, + repositoryPath, } = useReviewSections({ enabled: isEnvironmentReady, environmentId, @@ -454,7 +477,8 @@ export function ReviewSheet(props: ReviewSheetProps) { } = useReviewDiffData({ threadKey: reviewCache.threadKey, environmentId, - cwd: selectedThreadCwd, + cwd: reviewCwd, + repositoryPath, selectedSection, draftMessage, draftContext, @@ -506,6 +530,7 @@ export function ReviewSheet(props: ReviewSheetProps) { environmentId, threadId, selectedSection, + repositoryPath, nativeReviewDiffData, }); const reviewContentKey = selectedSection @@ -617,7 +642,12 @@ export function ReviewSheet(props: ReviewSheetProps) { params: { environmentId: String(environmentId), threadId: String(threadId) }, }); }; + const gitRepositoryLabel = + repositories.length > 1 && selectedSection?.kind !== "turn" && selectedGitRepository + ? selectedGitRepository.name + ": " + (selectedGitRepository.branch ?? "HEAD") + : null; const androidHeaderSubtitle = [ + gitRepositoryLabel, selectedSection?.title, selectedRepository?.name, headerDiffSummary.additions, @@ -686,6 +716,7 @@ export function ReviewSheet(props: ReviewSheetProps) { return <>{children}; })(); const headerSubtitle = [ + gitRepositoryLabel, selectedRepository?.name, headerDiffSummary.additions, headerDiffSummary.deletions, @@ -713,7 +744,10 @@ export function ReviewSheet(props: ReviewSheetProps) { title={headerTitleText} subtitle={headerSubtitle} androidSubtitle={androidHeaderSubtitle} - selectedThreadCwd={selectedThreadCwd} + selectedThreadCwd={repositoryPath ? null : selectedThreadCwd} + repositories={repositories} + selectedGitRepository={selectedGitRepository} + onSelectGitRepository={selectGitRepository} 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 a1cedac294a5a..3725ab491d871 100644 --- a/apps/mobile/src/features/review/reviewModel.test.ts +++ b/apps/mobile/src/features/review/reviewModel.test.ts @@ -29,6 +29,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 c1ac48615e53e..5a7869fddb13d 100644 --- a/apps/mobile/src/features/review/reviewModel.ts +++ b/apps/mobile/src/features/review/reviewModel.ts @@ -15,7 +15,6 @@ export type ReviewSectionKind = "turn" | "working-tree" | "branch-range"; export type ReviewGitSectionKind = Exclude; type ReviewGitSource = ReviewDiffPreviewSource & { readonly kind: ReviewGitSectionKind }; -const CHANGES_SECTION_ID = "git:branch-range"; const GIT_SECTION_KINDS = ["working-tree", "branch-range"] as const; const GIT_PLACEHOLDER_TITLES = { "working-tree": msg("Uncommitted", { $context: "diff section: working tree" }), @@ -571,6 +570,7 @@ export function reviewTurnDiffsBySectionId( } export function buildReviewSectionItems(input: { + readonly repositoryPath?: string; readonly checkpoints: ReadonlyArray; readonly gitSections: ReadonlyArray; readonly turnDiffById: Readonly>; @@ -607,7 +607,7 @@ export function buildReviewSectionItems(input: { if (section) { return [ { - id: `git:${kind}`, + id: input.repositoryPath ? `git:${kind}:${input.repositoryPath}` : `git:${kind}`, kind, title: section.title, subtitle: gitSubtitle(section, resolve), @@ -624,7 +624,7 @@ export function buildReviewSectionItems(input: { ? [] : [ { - id: `git:${kind}`, + id: input.repositoryPath ? `git:${kind}:${input.repositoryPath}` : `git:${kind}`, kind, title: resolve(GIT_PLACEHOLDER_TITLES[kind]), subtitle: null, @@ -640,7 +640,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 beb9b25eaf836..00d8e6be8d27c 100644 --- a/apps/mobile/src/features/review/useReviewCommentSelectionController.ts +++ b/apps/mobile/src/features/review/useReviewCommentSelectionController.ts @@ -27,6 +27,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; @@ -103,11 +104,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, @@ -115,7 +119,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), @@ -126,7 +130,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 d530279f8ca25..a52f4bf834ca6 100644 --- a/apps/mobile/src/features/review/useReviewDiffData.ts +++ b/apps/mobile/src/features/review/useReviewDiffData.ts @@ -148,6 +148,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; @@ -183,7 +184,7 @@ export function useReviewDiffData(input: { [sectionDiff, repositoryFolder, repositoryFolders], ); const registry = useContext(RegistryContext); - const { environmentId, cwd } = input; + const { environmentId, cwd, repositoryPath } = input; const scope = JSON.stringify([environmentId, cwd, lazySource?.kind, source?.baseRef]); const hideTestFilesPreference = useHideTestFilesPreference(); const { hideTestFiles } = hideTestFilesPreference; @@ -211,9 +212,14 @@ export function useReviewDiffData(input: { input: { cacheKey: scope, // Newer preview revisions refresh patches read under an older one. - preview: { cwd, sourceKind: lazySource.kind }, + preview: { + cwd, + sourceKind: lazySource.kind, + ...(repositoryPath ? { requireRepositoryRoot: true } : {}), + }, request: { cwd, + ...(repositoryPath ? { requireRepositoryRoot: true } : {}), ...(lazySource.baseRef ? { baseRef: lazySource.baseRef } : {}), ...(lazySource.mergeBase ? { mergeBase: lazySource.mergeBase } : {}), file: { @@ -227,7 +233,7 @@ export function useReviewDiffData(input: { }) : null, ), - [environmentId, cwd, lazySource, indices, scope], + [environmentId, cwd, lazySource, indices, scope, repositoryPath], ); const parsedQuery = useMemo( () => @@ -288,8 +294,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 shownDiff = useMemo( () => filterPullRequestTestFiles(parsedDiff, hideTestFiles), [parsedDiff, hideTestFiles], diff --git a/apps/mobile/src/features/review/useReviewHeaderPresentation.tsx b/apps/mobile/src/features/review/useReviewHeaderPresentation.tsx index 30adccfff26dc..5ff41bcbe1d4b 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 8cb6929169771..b337ada1e618d 100644 --- a/apps/mobile/src/features/review/useReviewSections.ts +++ b/apps/mobile/src/features/review/useReviewSections.ts @@ -1,7 +1,7 @@ import { useAtomValue } from "@effect/atom-react"; import { resolveFilesystemReadAccess } from "@t3tools/client-runtime/state/filesystem"; import { Atom } from "effect/reactivity"; -import { useMemo } from "react"; +import { useMemo, useState } from "react"; import { msg, useMessages } from "gt-react-native"; import { deriveThreadCheckpointSummaries } from "@t3tools/client-runtime/state/thread-checkpoints"; @@ -61,19 +61,53 @@ 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 requestedCwd = + repositoryChoice?.threadKey === reviewCache.threadKey ? repositoryChoice.cwd : undefined; + const requestedRepository = repositories.find((repo) => repo.cwd === requestedCwd); + const selectedRepository = requestedRepository ?? repositories[0]; + const repositoryUnavailable = + requestedCwd !== undefined && requestedCwd !== selectedThreadCwd && !requestedRepository; + const repositoryMissing = + repositoryUnavailable && repositoriesQuery.isSuccess && !repositoriesQuery.isPending; + if (repositoryMissing) { + setRepositoryChoice(null); + } + const repositoryUnresolved = repositoryUnavailable && !repositoryMissing; + const reviewCwd = repositoryUnresolved + ? null + : selectedRepository?.path + ? selectedRepository.cwd + : selectedThreadCwd; + const repositoryPath = selectedRepository?.path ?? ""; const diffPreviewQuery = (sourceKind: ReviewGitSectionKind) => - canReadFiles && enabled && environmentId !== undefined && selectedThreadCwd !== null + canReadFiles && enabled && environmentId !== undefined && reviewCwd !== null ? reviewEnvironment.diffPreview({ environmentId, - input: { cwd: selectedThreadCwd, sourceKind }, + input: { + cwd: reviewCwd, + sourceKind, + ...(repositoryPath ? { requireRepositoryRoot: true } : {}), + }, }) : null; const workingTreePreview = useEnvironmentQuery(diffPreviewQuery("working-tree")); const branchPreview = useEnvironmentQuery(diffPreviewQuery("branch-range")); const lastGitSections = useAtomValue( - environmentId !== undefined && selectedThreadCwd !== null - ? lastReviewGitSectionsAtom(environmentId, selectedThreadCwd) + environmentId !== undefined && reviewCwd !== null + ? lastReviewGitSectionsAtom(environmentId, reviewCwd) : NO_GIT_SECTIONS_ATOM, ); @@ -107,6 +141,7 @@ export function useReviewSections(input: { checkpoints: readyCheckpoints, gitSections: canReadFiles || fileAccess.isPending ? gitSections : [], turnDiffById: reviewTurnDiffsBySectionId(readyCheckpoints, lastTurnDiffs), + repositoryPath, gitSectionStates: { "working-tree": gitSectionState(fileAccess.isPending, workingTreePreview), "branch-range": gitSectionState(fileAccess.isPending, branchPreview), @@ -155,6 +190,10 @@ 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 selectedGitPreview = selectedSection?.kind === "working-tree" ? workingTreePreview @@ -168,8 +207,9 @@ export function useReviewSections(input: { } if (selectedSection?.kind === "turn") { activeTurnDiff.refresh(); - return; + if (!repositoryFailureVisible) return; } + repositoriesQuery.refresh(); if (selectedGitPreview) { selectedGitPreview.refresh(); } else { @@ -184,8 +224,21 @@ export function useReviewSections(input: { } }; + const selectRepository = (cwd: string) => { + if (!repositories.some((repo) => repo.cwd === cwd)) return; + if ((requestedCwd ?? selectedThreadCwd) === 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) ?? (selectedSection?.kind === "turn" ? activeTurnDiff.error : (selectedGitPreview?.error ?? null)) ?? @@ -193,9 +246,10 @@ export function useReviewSections(input: { ? (fileAccess.error ?? messages(msg("This connection cannot read local diffs."))) : null), isSelectedSectionPending: - selectedSection?.kind === "turn" + (repositoryFailureVisible && repositoriesQuery.isPending) || + (selectedSection?.kind === "turn" ? activeTurnDiff.isPending - : (selectedGitPreview?.isPending ?? false), + : (selectedGitPreview?.isPending ?? false)), reviewSections, selectedSection, refreshSelectedSection, diff --git a/apps/mobile/src/i18n/translations/de.json b/apps/mobile/src/i18n/translations/de.json index e6fe9966910cb..a7531457e832e 100644 --- a/apps/mobile/src/i18n/translations/de.json +++ b/apps/mobile/src/i18n/translations/de.json @@ -5703,5 +5703,7 @@ "99451a5d2d40440f": "Zurückgezogen von {by}.", "3ee30a50b70fffab": "Zurückgezogen von {by}: {reason}", "201490988858b511": "zurückgezogen von {by}", - "46d614fa7b4bf1e5": "Workflow-Ausführungen" + "46d614fa7b4bf1e5": "Workflow-Ausführungen", + "f1b3ae2ae2319a51": "Git-Repository auswählen", + "18ed3e1af363c529": "Repository des Arbeitsbereichs" } diff --git a/apps/mobile/src/i18n/translations/en.json b/apps/mobile/src/i18n/translations/en.json index 13d1178a1eb5c..a43b1b727fb5e 100644 --- a/apps/mobile/src/i18n/translations/en.json +++ b/apps/mobile/src/i18n/translations/en.json @@ -5705,5 +5705,7 @@ "99451a5d2d40440f": "Withdrawn by {by}.", "3ee30a50b70fffab": "Withdrawn by {by}: {reason}", "201490988858b511": "withdrawn by {by}", - "46d614fa7b4bf1e5": "Workflow runs" + "46d614fa7b4bf1e5": "Workflow runs", + "f1b3ae2ae2319a51": "Select Git repository", + "18ed3e1af363c529": "Workspace repository" } diff --git a/apps/mobile/src/i18n/translations/es.json b/apps/mobile/src/i18n/translations/es.json index b839834f248e0..d40734b88d831 100644 --- a/apps/mobile/src/i18n/translations/es.json +++ b/apps/mobile/src/i18n/translations/es.json @@ -5697,5 +5697,7 @@ "99451a5d2d40440f": "Retirada por {by}.", "3ee30a50b70fffab": "Retirada por {by}: {reason}", "201490988858b511": "retirada por {by}", - "46d614fa7b4bf1e5": "Ejecuciones de flujos de trabajo" + "46d614fa7b4bf1e5": "Ejecuciones de flujos de trabajo", + "f1b3ae2ae2319a51": "Seleccionar repositorio Git", + "18ed3e1af363c529": "Repositorio del espacio de trabajo" } diff --git a/apps/mobile/src/i18n/translations/fr.json b/apps/mobile/src/i18n/translations/fr.json index 8a659455e3b59..2503b76a95604 100644 --- a/apps/mobile/src/i18n/translations/fr.json +++ b/apps/mobile/src/i18n/translations/fr.json @@ -5697,5 +5697,7 @@ "99451a5d2d40440f": "Retirée par {by}.", "3ee30a50b70fffab": "Retirée par {by} : {reason}", "201490988858b511": "retirée par {by}", - "46d614fa7b4bf1e5": "Exécutions de workflow" + "46d614fa7b4bf1e5": "Exécutions de workflow", + "f1b3ae2ae2319a51": "Choisir un dépôt Git", + "18ed3e1af363c529": "Dépôt de l’espace de travail" } diff --git a/apps/mobile/src/i18n/translations/ja.json b/apps/mobile/src/i18n/translations/ja.json index adb255de9dd11..c3dafec4d661d 100644 --- a/apps/mobile/src/i18n/translations/ja.json +++ b/apps/mobile/src/i18n/translations/ja.json @@ -5674,5 +5674,7 @@ "99451a5d2d40440f": "{by} が取り下げました。", "3ee30a50b70fffab": "{by} が取り下げました: {reason}", "201490988858b511": "{by} が取り下げ", - "46d614fa7b4bf1e5": "ワークフローの実行" + "46d614fa7b4bf1e5": "ワークフローの実行", + "f1b3ae2ae2319a51": "Git リポジトリを選択", + "18ed3e1af363c529": "ワークスペースのリポジトリ" } diff --git a/apps/mobile/src/i18n/translations/ko.json b/apps/mobile/src/i18n/translations/ko.json index 0ff760787a094..b4bd83c2bc7d5 100644 --- a/apps/mobile/src/i18n/translations/ko.json +++ b/apps/mobile/src/i18n/translations/ko.json @@ -5681,5 +5681,7 @@ "99451a5d2d40440f": "{by}에서 철회했습니다.", "3ee30a50b70fffab": "{by}에서 철회했습니다: {reason}", "201490988858b511": "{by}에서 철회함", - "46d614fa7b4bf1e5": "워크플로 실행" + "46d614fa7b4bf1e5": "워크플로 실행", + "f1b3ae2ae2319a51": "Git 리포지토리 선택", + "18ed3e1af363c529": "작업 공간 리포지토리" } diff --git a/apps/mobile/src/i18n/translations/pt-BR.json b/apps/mobile/src/i18n/translations/pt-BR.json index 66624b02182fc..ba38fe3597d08 100644 --- a/apps/mobile/src/i18n/translations/pt-BR.json +++ b/apps/mobile/src/i18n/translations/pt-BR.json @@ -5697,5 +5697,7 @@ "99451a5d2d40440f": "Retirada por {by}.", "3ee30a50b70fffab": "Retirada por {by}: {reason}", "201490988858b511": "retirada por {by}", - "46d614fa7b4bf1e5": "Execuções de workflow" + "46d614fa7b4bf1e5": "Execuções de workflow", + "f1b3ae2ae2319a51": "Selecionar repositório Git", + "18ed3e1af363c529": "Repositório do espaço de trabalho" } diff --git a/apps/mobile/src/i18n/translations/ru.json b/apps/mobile/src/i18n/translations/ru.json index f3f1fdd012ace..081953dd8ffb9 100644 --- a/apps/mobile/src/i18n/translations/ru.json +++ b/apps/mobile/src/i18n/translations/ru.json @@ -5777,5 +5777,7 @@ "99451a5d2d40440f": "Отозван: {by}.", "3ee30a50b70fffab": "Отозван ({by}): {reason}", "201490988858b511": "отозван: {by}", - "46d614fa7b4bf1e5": "Запуски воркфлоу" + "46d614fa7b4bf1e5": "Запуски воркфлоу", + "f1b3ae2ae2319a51": "Выбрать Git-репозиторий", + "18ed3e1af363c529": "Репозиторий рабочего пространства" } diff --git a/apps/mobile/src/i18n/translations/sv.json b/apps/mobile/src/i18n/translations/sv.json index 351210012940e..b467886dcce38 100644 --- a/apps/mobile/src/i18n/translations/sv.json +++ b/apps/mobile/src/i18n/translations/sv.json @@ -5703,5 +5703,7 @@ "99451a5d2d40440f": "Återkallad av {by}.", "3ee30a50b70fffab": "Återkallad av {by}: {reason}", "201490988858b511": "återkallad av {by}", - "46d614fa7b4bf1e5": "Arbetsflödeskörningar" + "46d614fa7b4bf1e5": "Arbetsflödeskörningar", + "f1b3ae2ae2319a51": "Välj Git-repo", + "18ed3e1af363c529": "Arbetsytans repo" } diff --git a/apps/mobile/src/i18n/translations/zh.json b/apps/mobile/src/i18n/translations/zh.json index 04afa392e5fe2..fcf212a966917 100644 --- a/apps/mobile/src/i18n/translations/zh.json +++ b/apps/mobile/src/i18n/translations/zh.json @@ -5684,5 +5684,7 @@ "99451a5d2d40440f": "已由 {by} 撤回。", "3ee30a50b70fffab": "已由 {by} 撤回:{reason}", "201490988858b511": "已由 {by} 撤回", - "46d614fa7b4bf1e5": "工作流运行" + "46d614fa7b4bf1e5": "工作流运行", + "f1b3ae2ae2319a51": "选择 Git 仓库", + "18ed3e1af363c529": "工作区仓库" } diff --git a/apps/server/src/auth/RpcAuthorization.ts b/apps/server/src/auth/RpcAuthorization.ts index 367ab10be6c0c..26fcbe35bdef3 100644 --- a/apps/server/src/auth/RpcAuthorization.ts +++ b/apps/server/src/auth/RpcAuthorization.ts @@ -214,6 +214,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 6e265f668ef87..3a05ae68ab3d2 100644 --- a/apps/server/src/observability/RpcInstrumentation.ts +++ b/apps/server/src/observability/RpcInstrumentation.ts @@ -236,6 +236,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 eff2100eb70cb..eacda847ae750 100644 --- a/apps/server/src/review/ReviewService.test.ts +++ b/apps/server/src/review/ReviewService.test.ts @@ -119,6 +119,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 7e97f29a821a9..bdabb4f0a62eb 100644 --- a/apps/server/src/vcs/GitVcsDriver.ts +++ b/apps/server/src/vcs/GitVcsDriver.ts @@ -25,6 +25,8 @@ import { type VcsError, type VcsCreateWorktreeInput, type VcsCreateWorktreeResult, + type ReviewRepositoriesInput, + type ReviewRepositoriesResult, type ReviewBranchCommitsInput, type ReviewBranchCommitsResult, type ReviewDiffPreviewInput, @@ -460,6 +462,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 a07cd0c0bafa1..331c4039d4211 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.test.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.test.ts @@ -3673,6 +3673,221 @@ 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); + const fs = yield* FileSystem.FileSystem; + yield* git(cwd, ["update-index", "--skip-worktree", ".gitmodules"]); + yield* fs.remove(NodePath.join(cwd, ".gitmodules")); + assert.deepStrictEqual( + (yield* driver.getReviewRepositories({ cwd })).repositories, + repos.repositories, + ); + yield* git(cwd, ["update-index", "--no-skip-worktree", ".gitmodules"]); + assert.deepStrictEqual( + (yield* driver.getReviewRepositories({ cwd })).repositories, + repos.repositories.slice(0, 1), + ); + yield* git(cwd, ["checkout", "--", ".gitmodules"]); + yield* git(cwd, ["submodule", "add", nested, "pending-child"]); + yield* git(cwd, ["update-index", "--skip-worktree", ".gitmodules"]); + yield* fs.remove(NodePath.join(cwd, ".gitmodules")); + assert.deepStrictEqual( + (yield* driver.getReviewRepositories({ cwd })).repositories.map((repo) => repo.path), + [...repos.repositories.map((repo) => repo.path), "pending-child"], + ); + yield* git(cwd, ["update-index", "--no-skip-worktree", ".gitmodules"]); + yield* git(cwd, ["checkout", "--", ".gitmodules"]); + yield* git(cwd, ["rm", "-f", "--", "pending-child"]); + yield* git(cwd, ["restore", "--staged", "--worktree", "--", ".gitmodules"]); + yield* fs.makeDirectory(NodePath.join(cwd, "independent")); + yield* initRepoWithCommit(NodePath.join(cwd, "independent")); + yield* git(cwd, [ + "config", + "-f", + ".gitmodules", + "submodule.independent.path", + "independent", + ]); + 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, + requireRepositoryRoot: true, + 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, { requireRepositoryRoot: true }), + ); + assert.equal(file.newContents, "# changed auth\n"); + 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, + ); + + const rootOnly = { cwd: child, requireRepositoryRoot: true } as const; + const tracked = yield* driver.getReviewDiffPreview({ + ...rootOnly, + sourceKind: "working-tree", + trackedOnly: true, + }); + assert.isDefined(tracked.completionToken); + yield* git(cwd, ["submodule", "deinit", "-f", "--", "packages/auth service"]); + const stale = yield* driver.getReviewDiffPreview({ + ...rootOnly, + sourceKind: "working-tree", + completionToken: tracked.completionToken!, + }); + assert.deepStrictEqual(stale.sources, []); + const patch = yield* driver.getReviewDiffPreview({ + ...rootOnly, + file: { path: "README.md", previousPath: null, sourceKind: "working-tree" }, + }); + assert.deepStrictEqual(patch.sources, []); + assert.deepStrictEqual((yield* driver.getReviewBranchCommits(rootOnly)).commits, []); + const contentsError = yield* driver + .getReviewDiffFileContents(makeReviewDiffFileContentsInput(child, rootOnly)) + .pipe(Effect.flip); + assert.include(contentsError.detail, "repository root"); + const nestedWorkspace = yield* driver.getReviewDiffPreview({ + cwd: child, + sourceKind: "working-tree", + }); + assert.include(nestedWorkspace.sources[0]?.diff, "changed parent"); + }), + ), + ); + it.effect("discards a tracked preview when another checkout replaces its directory", () => + Effect.gen(function* () { + const parent = yield* makeTmpDir(); + const fs = yield* FileSystem.FileSystem; + const cwd = NodePath.join(parent, "checkout"); + yield* fs.makeDirectory(cwd); + yield* initRepoWithCommit(cwd); + yield* writeTextFile(cwd, "README.md", "from the first checkout\n"); + const driver = yield* GitVcsDriver.GitVcsDriver; + const input = { cwd, requireRepositoryRoot: true, sourceKind: "working-tree" } as const; + const first = yield* driver.getReviewDiffPreview({ ...input, trackedOnly: true }); + assert.isDefined(first.completionToken); + assert.include(first.sources[0]?.diff, "+from the first checkout"); + + yield* fs.rename(cwd, NodePath.join(parent, "original-checkout")); + yield* fs.makeDirectory(cwd); + yield* initRepoWithCommit(cwd); + yield* writeTextFile(cwd, "README.md", "from the replacement checkout\n"); + const replacement = yield* driver.getReviewDiffPreview({ + ...input, + completionToken: first.completionToken!, + }); + assert.include(replacement.sources[0]?.diff, "+from the replacement checkout"); + assert.notInclude(replacement.sources[0]?.diff, "from the first checkout"); + }), + ); 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 20e31077f4644..ea63c26adfbe8 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.ts @@ -29,6 +29,8 @@ import { type GitCommandFailureReason, T3_PROJECT_FILE_NAME, type ReviewBranchCommitsInput, + type ReviewRepositoriesInput, + type ReviewRepositoriesResult, type ReviewDiffChangeType, type ReviewDiffFileContentsInput, type ReviewDiffPreviewInput, @@ -2202,6 +2204,8 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* const resolveReviewRepository = Effect.fn("resolveReviewRepository")(function* ( cwd: string, needsCurrentBranch: boolean, + requireRepositoryRoot = false, + refreshLayout = false, ) { // A cached layout outlives a removed cwd, which must still read as a missing cwd. if ( @@ -2210,8 +2214,14 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* ) { return null; } - const repository = yield* resolveRepositoryPaths(cwd); - if (repository?.worktreeRoot == null) return null; + const repository = yield* requireRepositoryRoot || refreshLayout + ? resolveRepositoryPathsUncached(cwd) + : resolveRepositoryPaths(cwd); + if ( + repository?.worktreeRoot == null || + (requireRepositoryRoot && repository.isAtRepositoryRoot !== true) + ) + return null; // The cached branch outlives a checkout made outside T3 Code, so it is read fresh. const currentBranch = needsCurrentBranch ? yield* readCurrentBranch("GitVcsDriver.review.currentBranch", cwd) @@ -5359,10 +5369,168 @@ 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 hasManifest = yield* fileSystem + .exists(path.join(real, ".gitmodules")) + .pipe(Effect.orElseSucceed(() => false)); + // A deleted manifest is authoritative. Only a skip-worktree entry means Git hid it. + const sparseManifest = + !hasManifest && + (yield* runGitStdout("GitVcsDriver.review.repositories.sparse", real, [ + "ls-files", + "-t", + "--", + ".gitmodules", + ])).startsWith("S "); + const manifest = + hasManifest || sparseManifest + ? yield* executeGit( + "GitVcsDriver.review.repositories", + real, + [ + "config", + "-z", + ...(sparseManifest ? ["--blob", ":.gitmodules"] : ["--file=.gitmodules"]), + "--get-regexp", + "^submodule\\..*\\.path$", + ], + { allowNonZeroExit: true, maxOutputBytes: 1024 * 1024 }, + ) + : null; + const declaredPaths = + 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) + ? [local.split(path.sep).join("/")] + : []; + }) + : []; + const children: string[] = []; + const batch: string[] = []; + let batchSize = 0; + const readGitlinks = Effect.fnUntraced(function* (paths: ReadonlyArray) { + const result = yield* executeGit( + "GitVcsDriver.review.repositories.index", + real, + ["--literal-pathspecs", "ls-files", "--stage", "-z", "--", ...paths], + { maxOutputBytes: REVIEW_METADATA_MAX_OUTPUT_BYTES, appendTruncationMarker: true }, + ); + const requested = new Set(paths); + for (const entry of result.stdout.split("\0")) { + const separator = entry.indexOf("\t"); + if (separator === -1 || !/^160000 [a-f0-9]+ 0$/.test(entry.slice(0, separator))) + continue; + const indexedPath = entry.slice(separator + 1); + if (requested.has(indexedPath)) children.push(path.join(real, indexedPath)); + } + return result.stdoutTruncated; + }); + let indexTruncated = false; + // Keep the argument list below Windows' command-line limit. + for (const local of new Set(declaredPaths)) { + const argSize = local.length * 2 + 3; + if (batch.length > 0 && batchSize + argSize > 16_000) { + indexTruncated = (yield* readGitlinks(batch)) || indexTruncated; + batch.length = 0; + batchSize = 0; + } + batch.push(local); + batchSize += argSize; + } + if (batch.length > 0) indexTruncated = (yield* readGitlinks(batch)) || indexTruncated; + 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: yield* readCurrentBranch("GitVcsDriver.review.repositories.branch", real), + }, + children, + truncated: indexTruncated, + }; + }).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); + truncated ||= item.truncated; + 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, ) { - const repository = yield* resolveReviewRepository(input.cwd, true); + const repository = yield* resolveReviewRepository(input.cwd, true, input.requireRepositoryRoot); if (!repository?.worktreeRoot) return { commits: [], truncated: false }; const cwd = repository.worktreeRoot; const head = yield* executeGit( @@ -5445,6 +5613,8 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* readonly key: string; readonly expiresAt: number; readonly repository: { readonly worktreeRoot: string; readonly currentBranch: string | null }; + readonly gitDir: string; + readonly checkoutIdentity: string; readonly review: { readonly baseRef: string | null; readonly mergeBase: string | null }; readonly dirty: ReviewTrackedDiff; readonly base: ReviewTrackedDiff; @@ -5453,11 +5623,46 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* const trackedReviewPreviewKey = (input: ReviewDiffPreviewInput) => JSON.stringify([ input.cwd, + input.requireRepositoryRoot === true, input.baseRef ?? null, input.sourceKind ?? null, input.ignoreWhitespace === true, input.metadataOnly === true, ]); + const readReviewCheckoutIdentity = Effect.fn("readReviewCheckoutIdentity")(function* ( + cwd: string, + worktreeRoot: string, + gitDir: string, + ) { + return yield* Effect.gen(function* () { + const physicalCwd = yield* fileSystem.realPath(cwd); + const worktree = yield* fileSystem.stat(worktreeRoot); + const dotGit = yield* fileSystem.lstat(path.join(worktreeRoot, ".git")); + const admin = yield* fileSystem.stat(gitDir); + const head = yield* fileSystem.readFileString(path.join(gitDir, "HEAD")); + const identity = (info: typeof worktree) => + [ + String(info.dev), + Option.map(info.ino, String).valueOrUndefined, + info.birthtime.valueOrUndefined?.getTime(), + ].join(":"); + if ( + [worktree, dotGit, admin].some( + (info) => Option.isNone(info.ino) && Option.isNone(info.birthtime), + ) + ) + return null; + return [ + physicalCwd, + identity(worktree), + identity(dotGit), + dotGit.type === "File" ? dotGit.mtime.valueOrUndefined?.getTime() : null, + identity(admin), + head, + ].join("\0"); + }).pipe(Effect.orElseSucceed(() => null)); + }); + const takeTrackedReviewPreview = Effect.fn("takeTrackedReviewPreview")(function* ( input: ReviewDiffPreviewInput, ) { @@ -5467,7 +5672,12 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* trackedReviewPreviews.delete(input.completionToken); if (entry.key !== trackedReviewPreviewKey(input)) return undefined; if ((yield* Clock.currentTimeMillis) > entry.expiresAt) return undefined; - return entry; + const identity = yield* readReviewCheckoutIdentity( + input.cwd, + entry.repository.worktreeRoot, + entry.gitDir, + ); + return identity === entry.checkoutIdentity ? entry : undefined; }); const getReviewDiffPreview = Effect.fn("getReviewDiffPreview")(function* ( @@ -5505,7 +5715,12 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* const tracked = reusesTracked ? yield* takeTrackedReviewPreview(input) : undefined; const repository = tracked?.repository ?? - (yield* resolveReviewRepository(input.cwd, needsCurrentBranch).pipe( + (yield* resolveReviewRepository( + input.cwd, + needsCurrentBranch, + input.requireRepositoryRoot, + input.completionToken !== undefined, + ).pipe( Effect.catchTags({ GitCommandError: (error) => isMissingGitCwdError(error) ? Effect.succeed(null) : Effect.fail(error), @@ -5520,6 +5735,17 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* } const cwd = repository.worktreeRoot; + const checkout = + input.trackedOnly && reusesTracked + ? yield* Effect.gen(function* () { + const gitDir = (yield* runGitStdout("GitVcsDriver.review.checkout.gitDir", cwd, [ + "rev-parse", + "--absolute-git-dir", + ])).replace(/\n$/, ""); + const checkoutIdentity = yield* readReviewCheckoutIdentity(input.cwd, cwd, gitDir); + return checkoutIdentity === null ? null : { gitDir, checkoutIdentity }; + }).pipe(Effect.orElseSucceed(() => null)) + : null; const hashDiff = (diff: string, files: ReadonlyArray) => digest.digest(Digest.sha256, new TextEncoder().encode(JSON.stringify([diff, files]))).pipe( Effect.map(Hex.encode), @@ -5690,12 +5916,13 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* return [incomplete(dirtyRef, dirty), incomplete(review.mergeBase, base)] as const; }).pipe(Effect.scoped); let completionToken: string | undefined; - if (input.trackedOnly && reusesTracked && dirtyTrackedResult.files && baseResult.files) { + if (checkout && dirtyTrackedResult.files && baseResult.files) { completionToken = yield* random.uuidV4(); trackedReviewPreviews.set(completionToken, { key: trackedReviewPreviewKey(input), expiresAt: (yield* Clock.currentTimeMillis) + REVIEW_TRACKED_PREVIEW_TTL_MS, repository, + ...checkout, review, dirty: { ...dirtyTrackedResult, files: dirtyTrackedResult.files }, base: { ...baseResult, files: baseResult.files }, @@ -5902,11 +6129,12 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* const getReviewDiffFileContents = Effect.fn("getReviewDiffFileContents")(function* ( input: ReviewDiffFileContentsInput, ) { - const repositoryRoot = yield* runGitStdout( - "GitVcsDriver.getReviewDiffFileContents.repositoryRoot", - input.cwd, - ["rev-parse", "--show-toplevel"], - ).pipe(Effect.map((value) => value.replace(/\n$/, ""))); + const repositoryRoot = input.requireRepositoryRoot + ? ((yield* resolveReviewRepository(input.cwd, false, true))?.worktreeRoot ?? "") + : yield* runGitStdout("GitVcsDriver.getReviewDiffFileContents.repositoryRoot", input.cwd, [ + "rev-parse", + "--show-toplevel", + ]).pipe(Effect.map((value) => value.replace(/\n$/, ""))); if (repositoryRoot.length === 0) { return yield* reviewDiffFileError(input, "Could not resolve the Git repository root."); } @@ -7824,6 +8052,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 c14a8fb943452..bd969207779cb 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -3441,6 +3441,7 @@ export const layerWsRpc = ( ), [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 2e1990b29b63e..48c3bb037f0ad 100644 --- a/apps/web/src/components/DiffPanel.browser.test.tsx +++ b/apps/web/src/components/DiffPanel.browser.test.tsx @@ -12,6 +12,7 @@ import { type ClientSettings, type OrchestrationGetTurnDiffResult, type ReviewBranchCommitsResult, + type ReviewRepositoriesResult, type ReviewDiffPreviewResult, type ReviewDiffPreviewSource, type ScopedThreadRef, @@ -33,10 +34,12 @@ const state = vi.hoisted(() => ({ thread: null as ReturnType | null, threadRef: null as ScopedThreadRef | null, previews: new Map>(), + repositoryPreviews: new Map>(), patch: null as unknown as ResultAtom, diffFilesCollapsed: false, project: { workspaceRoot: "/project", + trackedFolders: [] as string[], repositoryIdentity: null as { rootPath: string } | null, }, toolCallItem: null as unknown, @@ -44,7 +47,9 @@ 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, + taskFolder: null as unknown as ResultAtom, checkpoints: [] as unknown[], checkpointDiff: null as Partial | null, })); @@ -54,8 +59,9 @@ vi.mock("~/state/server", () => ({ })); vi.mock("~/state/review", () => ({ reviewEnvironment: { - diffPreview: ({ input }: { input: { baseRef?: string } }) => - state.previews.get(input.baseRef ?? null)!, + diffPreview: ({ input }: { input: { cwd: string; baseRef?: string } }) => + state.repositoryPreviews.get(input.cwd) ?? state.previews.get(input.baseRef ?? null)!, + repositories: () => state.repositories, branchCommits: () => state.commits, diffFilePatch: () => state.patch, diffFileContents: {}, @@ -77,7 +83,7 @@ vi.mock("~/state/entities", () => ({ })); vi.mock("~/state/filesystem", () => ({ useFilesystemReadAccess: () => ({ canReadFiles: true, isPending: false, error: null }), - filesystemEnvironment: {}, + filesystemEnvironment: { taskFolder: () => state.taskFolder }, })); vi.mock("~/hooks/useThreadRouteTarget", () => ({ useThreadRouteRef: () => state.threadRef })); vi.mock("~/hooks/useSettings", () => ({ @@ -140,14 +146,16 @@ function setup(failedBaseRef: string | null) { useDiffPanelStore.setState({ byThreadKey: {}, branchBaseRefByThreadKey: {}, + repositoryCwdByThreadKey: {}, }); useDiffPanelSessionStore.setState({ collapsedFileKeysByScopeKey: {} }); useRightPanelStore.setState({ byThreadKey: {}, threadPanelVisibilityByThreadKey: {} }); }; reset(); state.diffFilesCollapsed = false; - state.project = { workspaceRoot: "/project", repositoryIdentity: null }; + state.project = { workspaceRoot: "/project", trackedFolders: [], repositoryIdentity: null }; state.toolCallItem = null; + state.taskFolder = Atom.make(AsyncResult.initial()); state.checkpoints = []; state.checkpointDiff = null; const patch = Atom.make>( @@ -166,9 +174,11 @@ function setup(failedBaseRef: string | null) { worktreePath: cwd, }); state.previews.clear(); + state.repositoryPreviews.clear(); 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({ @@ -352,6 +362,94 @@ it.each([false, true])( }, ); +it("switches Changes between the workspace and an initialized submodule", async () => { + using context = setup("main"); + const childCwd = `${cwd}/packages/auth`; + state.repositories = Atom.make( + AsyncResult.success({ + repositories: [ + { cwd, name: "workspace", path: "", branch: "dev" }, + { cwd: childCwd, name: "auth", path: "packages/auth", branch: "fix-auth" }, + ], + truncated: false, + }), + ); + const childPreview = preview(); + state.repositoryPreviews.set( + childCwd, + Atom.make( + AsyncResult.success({ + ...childPreview, + cwd: childCwd, + sources: childPreview.sources.map((source) => ({ ...source, baseRef: "auth-base" })), + }), + ), + ); + await using screen = await render( + + + , + ); + await userEvent.click(screen.getByRole("combobox", { name: "Repository: Project folder: dev" })); + await userEvent.click(page.getByRole("option", { name: /auth: fix-auth/ })); + await expect + .element(screen.getByRole("combobox", { name: "Repository: auth: fix-auth" })) + .toBeVisible(); + await expect.element(screen.getByLabelText("Comparing dev against auth-base")).toBeVisible(); + expect( + useDiffPanelStore.getState().branchBaseRefByThreadKey[scopedThreadKey(context.threadRef)], + ).toBeNull(); +}); + +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(); +}); + +it("preserves a saved tracked repository when its folder list cannot load", async () => { + using context = setup(null); + state.project.trackedFolders = ["/tracked"]; + state.taskFolder = Atom.make(AsyncResult.fail(new Error("task folder query failed"))); + const key = scopedThreadKey(context.threadRef); + useDiffPanelStore.getState().selectRepository(context.threadRef, "/tracked/worktree"); + useDiffPanelStore.getState().selectBranchBaseRef(context.threadRef, "main"); + await using screen = await render( + + + , + ); + await expect.element(screen.getByText("task folder query failed", { exact: true })).toBeVisible(); + await expect.element(screen.getByRole("button", { name: "Retry", exact: true })).toBeVisible(); + expect(useDiffPanelStore.getState().repositoryCwdByThreadKey[key]).toBe("/tracked/worktree"); + expect(useDiffPanelStore.getState().branchBaseRefByThreadKey[key]).toBe("main"); +}); + it("says a turn diff cut off at the server's size limit is incomplete", async () => { using context = setup("origin/orphan"); state.checkpoints = [ @@ -497,7 +595,11 @@ it("opens a file from a tool call's diff by the path its agent recorded", async using context = setup("origin/orphan"); // A local thread in a project that is the repository's apps/web folder. state.thread = { ...state.thread!, worktreePath: null }; - state.project = { workspaceRoot: "/repo/apps/web", repositoryIdentity: { rootPath: "/repo" } }; + state.project = { + workspaceRoot: "/repo/apps/web", + trackedFolders: [], + repositoryIdentity: { rootPath: "/repo" }, + }; const status = AsyncResult.getOrThrow(context.registry.get(state.status)); state.status = Atom.make( AsyncResult.success({ ...status, workingTree: { ...status.workingTree, rootPath: "/repo" } }), diff --git a/apps/web/src/components/DiffPanel.tsx b/apps/web/src/components/DiffPanel.tsx index 29feac004971f..1a56cb02f1132 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 { T, useGT, useMessages, Var } from "gt-react"; import { RefreshIcon } from "~/components/ui/refresh-icon"; import { useAtomValue } from "@effect/atom-react"; @@ -134,7 +135,6 @@ import { useOpenLink } from "../browser/useOpenLink"; type DiffThemeType = "light" | "dark"; const AUTOMATIC_BASE_REF = "__automatic_base_ref__"; const ALL_REPOSITORIES = "__all_repositories__"; -const THREAD_FOLDER = "__thread_folder__"; const NO_GIT_REPOSITORIES: ReturnType = Object.freeze([]); const NO_TURN_DIFF_SECTIONS: ReadonlyArray = []; const DIFF_FILE_TREE_STORAGE_KEY = "t3code.diffFileTreeOpen"; @@ -306,8 +306,12 @@ export default function DiffPanel({ const tracksFolders = (activeProject?.trackedFolders?.length ?? 0) > 0; const threadWorktreePath = activeThread?.worktreePath ?? null; // Unchanged repositories are listed too: work done outside a turn only shows in these scopes. + const readsTaskFolder = + visible && tracksFolders && activeThread != null && threadWorktreePath !== null; + const readsProjectFolders = + visible && tracksFolders && activeThread != null && threadWorktreePath === null; const taskFolderQuery = useEnvironmentQuery( - visible && tracksFolders && activeThread != null && threadWorktreePath !== null + readsTaskFolder ? filesystemEnvironment.taskFolder({ environmentId: activeThread.environmentId, input: { worktreePath: threadWorktreePath }, @@ -315,14 +319,14 @@ export default function DiffPanel({ : null, ); const projectFoldersQuery = useEnvironmentQuery( - visible && tracksFolders && activeThread != null && threadWorktreePath === null + readsProjectFolders ? filesystemEnvironment.listFolders({ environmentId: activeThread.environmentId, input: { projectId: activeThread.projectId }, }) : null, ); - const gitRepositories = threadGitRepositories({ + const trackedRepositories = threadGitRepositories({ changed: repositoryStructure === null ? NO_GIT_REPOSITORIES @@ -331,11 +335,66 @@ export default function DiffPanel({ folders: projectFoldersQuery.data?.folders ?? null, threadCwd: activeCwd ?? null, }); - const [gitRepositoryPath, setGitRepositoryPath] = useState(null); + const [repositoryQuery, setRepositoryQuery] = useState(""); + const requestedRepositoryCwd = useDiffPanelStore((state) => + routeThreadRef ? state.repositoryCwdByThreadKey[scopedThreadKey(routeThreadRef)] : undefined, + ); + const repositoriesQuery = useEnvironmentQuery( + visible && canReadFiles && activeThread && activeCwd + ? reviewEnvironment.repositories({ + environmentId: activeThread.environmentId, + input: { cwd: activeCwd }, + }) + : null, + messages, + ); + const discoveredRepositories = repositoriesQuery.data?.repositories ?? []; + const submodules = discoveredRepositories.filter((repository) => repository.path !== ""); + const submoduleCwds = new Set(submodules.map((repository) => repository.cwd)); + const gitRepositories = [ + ...submodules.map((repository) => ({ + cwd: repository.cwd, + name: repository.name + ": " + (repository.branch ?? "HEAD"), + path: repository.path, + })), + ...trackedRepositories + .filter((repository) => repository.cwd !== activeCwd && !submoduleCwds.has(repository.cwd)) + .map((repository) => ({ cwd: repository.cwd, name: repository.name, path: "" })), + ]; const gitRepository = - gitRepositories.find((repository) => repository.repositoryPath === gitRepositoryPath) ?? + gitRepositories.find((repository) => repository.cwd === requestedRepositoryCwd) ?? (threadFolderIsRepo ? null : (gitRepositories[0] ?? null)); - const gitCwd = gitRepository?.cwd ?? activeCwd; + const repositoryUnavailable = + requestedRepositoryCwd !== undefined && + requestedRepositoryCwd !== activeCwd && + !gitRepositories.some((repository) => repository.cwd === requestedRepositoryCwd); + const repositoryMissing = + repositoryUnavailable && + repositoriesQuery.data !== null && + (!readsTaskFolder || taskFolderQuery.data !== null) && + (!readsProjectFolders || projectFoldersQuery.data !== null); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- clears a persisted checkout and refs after discovery confirms it is gone + useEffect(() => { + if (repositoryMissing && routeThreadRef) { + useDiffPanelStore.getState().clearRepository(routeThreadRef); + } + }, [repositoryMissing, routeThreadRef]); + + const repositoryUnresolved = repositoryUnavailable && !repositoryMissing; + const repositoryPending = + repositoryUnresolved && + (repositoriesQuery.isPending || taskFolderQuery.isPending || projectFoldersQuery.isPending); + const repositoryError = + repositoryUnresolved && !repositoryPending + ? (repositoriesQuery.error ?? taskFolderQuery.error ?? projectFoldersQuery.error) + : null; + const refreshRepositories = () => { + repositoriesQuery.refresh(); + taskFolderQuery.refresh(); + projectFoldersQuery.refresh(); + }; + const requireRepositoryRoot = gitRepository !== null; + const gitCwd = repositoryUnresolved ? undefined : (gitRepository?.cwd ?? activeCwd); const isGitRepo = threadFolderIsRepo || gitRepository !== null; const turnDiffSummaries = useThreadCheckpointSummaries(routeThreadRef); const orderedTurnDiffSummaries = turnDiffSummaries.toSorted((left, right) => { @@ -357,7 +416,10 @@ export default function DiffPanel({ storedDiffSelection.kind !== "turn" && storedDiffSelection.kind !== "tool-call" ? { kind: "turn", turnId: latestTurn.runId, filePath: null, revealRequestId: 0 } - : storedDiffSelection; + : repositoryMissing && + (storedDiffSelection.kind === "commit" || storedDiffSelection.kind === "branch") + ? { kind: "branch", baseRef: null } + : storedDiffSelection; const rememberedBaseRef = useDiffPanelStore((state) => selectThreadBranchBaseRef(state, routeThreadRef), ); @@ -416,7 +478,7 @@ export default function DiffPanel({ ? `commit:${selectedCommitSha}` : selectedGitScope; const collapseScopeKey = routeThreadRef - ? `${routeThreadRef.environmentId}:${routeThreadRef.threadId}:${reviewSectionId}` + ? `${routeThreadRef.environmentId}:${routeThreadRef.threadId}:${isGitSelection ? gitCwd : ""}:${reviewSectionId}` : null; const codeViewMountKey = collapseScopeKey ?? reviewSectionId; const selectedCheckpointRange = @@ -441,6 +503,7 @@ export default function DiffPanel({ canReadFiles && isGitSelection && activeThread && gitCwd ? { cwd: gitCwd, + ...(requireRepositoryRoot ? { requireRepositoryRoot: true } : {}), ...(selectedBaseRef ? { baseRef: selectedBaseRef } : {}), ...(selectedCommitSha !== null ? { commitSha: selectedCommitSha } : {}), ignoreWhitespace: diffIgnoreWhitespace, @@ -476,7 +539,8 @@ export default function DiffPanel({ environmentId: activeThread.environmentId, input: { cwd: gitCwd, - ...(rememberedBaseRef ? { baseRef: rememberedBaseRef } : {}), + ...(requireRepositoryRoot ? { requireRepositoryRoot: true } : {}), + ...(!repositoryMissing && rememberedBaseRef ? { baseRef: rememberedBaseRef } : {}), }, }) : null, @@ -544,9 +608,27 @@ export default function DiffPanel({ void openLink(url, { event }); }; const refreshPreviewQuery = branchDiffPreview.refresh; - const refreshDiffFromUserAction = refreshPreviewQuery; + const refreshDiffFromUserAction = () => { + refreshRepositories(); + refreshPreviewQuery(); + }; const threadFolderName = activeProject?.title ?? gt("Project folder"); + const parentRepository = discoveredRepositories.find((repository) => repository.path === ""); + const repositoryOptions = + threadFolderIsRepo && activeCwd + ? [ + { + cwd: activeCwd, + name: parentRepository + ? threadFolderName + ": " + (parentRepository.branch ?? "HEAD") + : threadFolderName, + path: "", + }, + ...gitRepositories, + ] + : gitRepositories; + const repositoryLabel = gitRepository?.name ?? repositoryOptions[0]?.name ?? threadFolderName; const preview = branchDiffPreview.data; const gitDiff = selectedGitSource?.diff; @@ -586,14 +668,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 && @@ -642,6 +727,7 @@ export default function DiffPanel({ ? createGitDiffFileContentsLoader(getDiffFileContents, { environmentId: activeThread.environmentId, cwd: preview.cwd, + ...(requireRepositoryRoot ? { requireRepositoryRoot: true } : {}), sourceKind: selectedGitSource.kind, baseRef: selectedGitSource.baseRef, headRef: selectedGitSource.headRef, @@ -849,7 +935,11 @@ export default function DiffPanel({ const repositoryFileTarget = (filePath: string) => { // A Git scope of a repository lists paths from that repository's folder. if (isGitSelection && gitRepository !== null) { - return { path: filePath, insideThreadFolder: false, cwd: gitRepository.cwd }; + return { + path: filePath, + insideThreadFolder: gitRepository.path !== "", + cwd: gitRepository.cwd, + }; } const match = repositorySectionForPath(repositorySections, filePath); if (match === null) return null; @@ -868,6 +958,7 @@ export default function DiffPanel({ threadRef: repositoryFile?.insideThreadFolder === false ? null : routeThreadRef, filePath: repositoryFile?.insideThreadFolder === false ? repositoryFile.path : filePath, activeCwd: repositoryFile?.insideThreadFolder === false ? repositoryFile.cwd : activeCwd, + fileCwd: isGitSelection && gitRepository?.path ? gitRepository.cwd : undefined, repositoryRoot: repositoryFile ? undefined : diffPathRepositoryRoot, openInEditor: (targetPath) => { void (async () => { @@ -929,14 +1020,13 @@ export default function DiffPanel({ if (!routeThreadRef) return; useDiffPanelStore.getState().selectBranchBaseRef(routeThreadRef, baseRef); }; - const selectGitRepository = (value: string) => { - const nextPath = value === THREAD_FOLDER ? null : value; - if (nextPath === (gitRepository?.repositoryPath ?? null)) return; - setGitRepositoryPath(nextPath); - // A commit or base ref of the repository being left means nothing in the next one. - if (selectedCommitSha === null && rememberedBaseRef === null) return; - selectBranchBaseRef(null); - if (selectedGitScope === "unstaged") selectGitScope("unstaged"); + const selectGitRepository = (cwd: string | null) => { + if (!routeThreadRef || !cwd || !repositoryOptions.some((repository) => repository.cwd === cwd)) + return; + if (cwd === gitCwd) return; + useDiffPanelStore.getState().selectRepository(routeThreadRef, cwd); + setOpenCommitMenu(null); + setBaseRefQuery(""); }; const selectedTurnValue = selectedTurn ? `turn:${selectedTurn.runId}` : ""; const selectedCommitValue = selectedCommitSha !== null ? `commit:${selectedCommitSha}` : ""; @@ -979,7 +1069,7 @@ export default function DiffPanel({ repositorySections.length > 0 ? "@max-[30rem]/diff-header:hidden" : undefined; const headerRow = ( <> -
+
} @@ -1172,39 +1262,62 @@ export default function DiffPanel({ {isGitSelection && gitRepositories.length > 0 && ( - - } - className="min-w-14 max-w-48 shrink" - aria-label={gt("Repository: {name}", { - name: gitRepository?.name ?? threadFolderName, - })} + repo.cwd)} + filteredItems={repositoryOptions + .filter((repo) => + (repo.name + " " + repo.path) + .toLowerCase() + .includes(repositoryQuery.trim().toLowerCase()), + ) + .map((repo) => repo.cwd)} + value={gitCwd ?? null} + onOpenChange={(open) => { + if (open) refreshRepositories(); + else setRepositoryQuery(""); + }} + onValueChange={selectGitRepository} + > + } + aria-label={gt("Repository: {name}", { name: repositoryLabel })} > - {gitRepository?.name ?? threadFolderName} + {repositoryLabel} - - - - {threadFolderIsRepo ? ( - - {threadFolderName} - - ) : null} - {gitRepositories.map((repository) => ( - - {repository.name} - - ))} - - - + + + setRepositoryQuery(event.target.value)} + /> + {gt("No matching repository.")} + + {(cwd) => { + const repo = repositoryOptions.find((repo) => repo.cwd === cwd)!; + return ( + + + {repo.name} + + {repo.path || + (repo.cwd === activeCwd ? gt("Workspace repository") : repo.cwd)} + + + + ); + }} + + {repositoriesQuery.data?.truncated && ( +

+ {gt("Repository discovery reached its limit.")} +

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

{repositoriesQuery.error}

+ )} +
+ )} {repositorySections.length > 0 && ( @@ -1600,6 +1713,20 @@ export default function DiffPanel({ {selectedPatchError && !renderablePatch && (

{selectedPatchError}

+ {isGitSelection && repositoryError && routeThreadRef && ( +
+ + +
+ )}
)} {!renderablePatch && toolCallPreview && toolCallPreview.content.length > 0 ? ( @@ -1704,7 +1831,12 @@ export default function DiffPanel({ files={codeViewFiles} pendingFiles={pendingFiles} renderCodeViewFooter={renderLoadingBoundary} - sectionId={reviewSectionId} + filePathPrefix={isGitSelection ? gitRepository?.path : undefined} + sectionId={ + isGitSelection && gitRepository?.path + ? gitRepository.path + ":" + reviewSectionId + : reviewSectionId + } sectionTitle={reviewSectionTitle} composerDraftTarget={composerDraftTarget} renderHeaderFilenameSuffix={(fileDiff) => { @@ -1713,7 +1845,7 @@ export default function DiffPanel({ 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 1fb8b99f7c4ca..f6a124bf6cfeb 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; @@ -110,6 +111,7 @@ export function AnnotatableCodeView({ environmentId, projectId, codeViewKey, + filePathPrefix, files, pendingFiles, sectionId, @@ -143,6 +145,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 && @@ -164,7 +168,7 @@ export function AnnotatableCodeView({ .filter( (comment) => comment.sectionId === sectionId && - comment.filePath === filePath && + comment.filePath === commentPath(filePath) && (comment.fenceLanguage ?? "diff") === "diff", ) .reduce((annotations, comment) => { @@ -216,7 +220,7 @@ export function AnnotatableCodeView({ id: entry.id, sectionId, sectionTitle, - filePath: file.filePath, + filePath: commentPath(file.filePath), fileDiff: file.fileDiff, range: entry.range, text, @@ -237,7 +241,7 @@ export function AnnotatableCodeView({ id, sectionId, sectionTitle, - filePath, + filePath: commentPath(filePath), fileDiff: item.fileDiff, range, text: "", diff --git a/apps/web/src/components/diffs/useReviewFilePatches.ts b/apps/web/src/components/diffs/useReviewFilePatches.ts index 0c889d501264d..d9573ce5df63a 100644 --- a/apps/web/src/components/diffs/useReviewFilePatches.ts +++ b/apps/web/src/components/diffs/useReviewFilePatches.ts @@ -199,6 +199,7 @@ function reviewFileQueries({ ...(previewInput ? { preview: previewInput } : {}), request: { cwd, + ...(previewInput?.requireRepositoryRoot ? { requireRepositoryRoot: true } : {}), ...(baseRef ? { baseRef } : {}), ...(source.kind === "commit" ? { commitSha: source.id } : {}), ...(source.mergeBase ? { mergeBase: source.mergeBase } : {}), diff --git a/apps/web/src/diffFileActions.test.ts b/apps/web/src/diffFileActions.test.ts index 8f7b2bc597b79..ee6900777de2a 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 046baa4ce5b64..bde33fb3d8e87 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; } @@ -100,11 +101,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 bb6d603d2bc56..a5d702d5415f5 100644 --- a/apps/web/src/diffPanelStore.test.ts +++ b/apps/web/src/diffPanelStore.test.ts @@ -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 207756445e91f..80c3304f9dcdd 100644 --- a/apps/web/src/diffPanelStore.ts +++ b/apps/web/src/diffPanelStore.ts @@ -33,6 +33,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; @@ -63,6 +66,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); @@ -179,13 +218,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 }; }), }), { @@ -197,6 +242,7 @@ export const useDiffPanelStore = create()( partialize: (state) => ({ byThreadKey: state.byThreadKey, branchBaseRefByThreadKey: state.branchBaseRefByThreadKey, + repositoryCwdByThreadKey: state.repositoryCwdByThreadKey, }), }, ), diff --git a/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json index bb4dbf0d19202..a8c4f9a6e3189 100644 --- a/apps/web/src/i18n/translations/de.json +++ b/apps/web/src/i18n/translations/de.json @@ -12986,5 +12986,10 @@ "99451a5d2d40440f": "Zurückgezogen von {by}.", "3ee30a50b70fffab": "Zurückgezogen von {by}: {reason}", "92e129bf413a1220": "zurückgezogen", - "800966eb58181745": "Prüfe, welche Sprachen das Modell unterstützt…" + "800966eb58181745": "Prüfe, welche Sprachen das Modell unterstützt…", + "e2e33c27c4a3af4c": "Repository suchen...", + "b781f558378592af": "Kein passendes Repository.", + "18ed3e1af363c529": "Repository des Arbeitsbereichs", + "332d417f22d1e83e": "Die Suche hat ihr Limit für Repositorys erreicht.", + "9bdaf65c667dedf2": "Repository des Threads prüfen" } diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json index 1a4cf83185001..1aee77cbfb521 100644 --- a/apps/web/src/i18n/translations/en.json +++ b/apps/web/src/i18n/translations/en.json @@ -12995,5 +12995,10 @@ "99451a5d2d40440f": "Withdrawn by {by}.", "3ee30a50b70fffab": "Withdrawn by {by}: {reason}", "92e129bf413a1220": "withdrawn", - "800966eb58181745": "Checking which languages the model supports…" + "800966eb58181745": "Checking which languages the model supports…", + "e2e33c27c4a3af4c": "Find repository...", + "b781f558378592af": "No matching repository.", + "18ed3e1af363c529": "Workspace repository", + "332d417f22d1e83e": "Repository discovery reached its limit.", + "9bdaf65c667dedf2": "Review the thread's repository" } diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json index 3741d30788810..488f51c2c751b 100644 --- a/apps/web/src/i18n/translations/es.json +++ b/apps/web/src/i18n/translations/es.json @@ -12981,5 +12981,10 @@ "99451a5d2d40440f": "Retirada por {by}.", "3ee30a50b70fffab": "Retirada por {by}: {reason}", "92e129bf413a1220": "retirada", - "800966eb58181745": "Comprobando qué idiomas admite el modelo…" + "800966eb58181745": "Comprobando qué idiomas admite el modelo…", + "e2e33c27c4a3af4c": "Buscar repositorio...", + "b781f558378592af": "No hay repositorios que coincidan.", + "18ed3e1af363c529": "Repositorio del espacio de trabajo", + "332d417f22d1e83e": "La detección alcanzó el límite de repositorios.", + "9bdaf65c667dedf2": "Revisar el repositorio del hilo" } diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json index 1c60b0470df31..504da437be337 100644 --- a/apps/web/src/i18n/translations/fr.json +++ b/apps/web/src/i18n/translations/fr.json @@ -12986,5 +12986,10 @@ "99451a5d2d40440f": "Retirée par {by}.", "3ee30a50b70fffab": "Retirée par {by} : {reason}", "92e129bf413a1220": "retirée", - "800966eb58181745": "Vérification des langues prises en charge par le modèle…" + "800966eb58181745": "Vérification des langues prises en charge par le modèle…", + "e2e33c27c4a3af4c": "Rechercher un dépôt...", + "b781f558378592af": "Aucun dépôt correspondant.", + "18ed3e1af363c529": "Dépôt de l’espace de travail", + "332d417f22d1e83e": "La détection a atteint la limite de dépôts.", + "9bdaf65c667dedf2": "Examiner le dépôt du fil" } diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json index f98ef7e93260f..269de33fd48a1 100644 --- a/apps/web/src/i18n/translations/ja.json +++ b/apps/web/src/i18n/translations/ja.json @@ -12922,5 +12922,10 @@ "99451a5d2d40440f": "{by} が取り下げました。", "3ee30a50b70fffab": "{by} が取り下げました: {reason}", "92e129bf413a1220": "取り下げ済み", - "800966eb58181745": "モデルが対応している言語を確認しています…" + "800966eb58181745": "モデルが対応している言語を確認しています…", + "e2e33c27c4a3af4c": "リポジトリを検索...", + "b781f558378592af": "一致するリポジトリがありません。", + "18ed3e1af363c529": "ワークスペースのリポジトリ", + "332d417f22d1e83e": "リポジトリの検出数が上限に達しました。", + "9bdaf65c667dedf2": "スレッドのリポジトリをレビュー" } diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json index 032042b111b7f..62d12442bdb4e 100644 --- a/apps/web/src/i18n/translations/ko.json +++ b/apps/web/src/i18n/translations/ko.json @@ -12919,5 +12919,10 @@ "99451a5d2d40440f": "{by}에서 철회했습니다.", "3ee30a50b70fffab": "{by}에서 철회했습니다: {reason}", "92e129bf413a1220": "철회됨", - "800966eb58181745": "모델이 지원하는 언어를 확인하는 중…" + "800966eb58181745": "모델이 지원하는 언어를 확인하는 중…", + "e2e33c27c4a3af4c": "리포지토리 검색...", + "b781f558378592af": "일치하는 리포지토리가 없습니다.", + "18ed3e1af363c529": "작업 공간 리포지토리", + "332d417f22d1e83e": "리포지토리 검색 한도에 도달했습니다.", + "9bdaf65c667dedf2": "스레드의 리포지토리 검토" } diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json index 307c29cf0ec4d..1672f48e9f4d7 100644 --- a/apps/web/src/i18n/translations/pt-BR.json +++ b/apps/web/src/i18n/translations/pt-BR.json @@ -12986,5 +12986,10 @@ "99451a5d2d40440f": "Retirada por {by}.", "3ee30a50b70fffab": "Retirada por {by}: {reason}", "92e129bf413a1220": "retirada", - "800966eb58181745": "Verificando quais idiomas o modelo suporta…" + "800966eb58181745": "Verificando quais idiomas o modelo suporta…", + "e2e33c27c4a3af4c": "Buscar repositório...", + "b781f558378592af": "Nenhum repositório correspondente.", + "18ed3e1af363c529": "Repositório do espaço de trabalho", + "332d417f22d1e83e": "A detecção atingiu o limite de repositórios.", + "9bdaf65c667dedf2": "Revisar o repositório da conversa" } diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json index 0f0d97eccea27..06fa59855ee53 100644 --- a/apps/web/src/i18n/translations/ru.json +++ b/apps/web/src/i18n/translations/ru.json @@ -12986,5 +12986,10 @@ "99451a5d2d40440f": "Отозван: {by}.", "3ee30a50b70fffab": "Отозван ({by}): {reason}", "92e129bf413a1220": "отозван", - "800966eb58181745": "Проверяем, какие языки поддерживает модель…" + "800966eb58181745": "Проверяем, какие языки поддерживает модель…", + "e2e33c27c4a3af4c": "Найти репозиторий...", + "b781f558378592af": "Нет подходящих репозиториев.", + "18ed3e1af363c529": "Репозиторий рабочего пространства", + "332d417f22d1e83e": "Достигнут лимит обнаружения репозиториев.", + "9bdaf65c667dedf2": "Просмотреть репозиторий ветки обсуждения" } diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json index f9e852760e4a0..70900c6c3dd6e 100644 --- a/apps/web/src/i18n/translations/sv.json +++ b/apps/web/src/i18n/translations/sv.json @@ -12993,5 +12993,10 @@ "99451a5d2d40440f": "Återkallad av {by}.", "3ee30a50b70fffab": "Återkallad av {by}: {reason}", "92e129bf413a1220": "återkallad", - "800966eb58181745": "Kontrollerar vilka språk modellen stöder…" + "800966eb58181745": "Kontrollerar vilka språk modellen stöder…", + "e2e33c27c4a3af4c": "Sök efter repo...", + "b781f558378592af": "Inget matchande repo.", + "18ed3e1af363c529": "Arbetsytans repo", + "332d417f22d1e83e": "Sökningen har nått gränsen för antal repon.", + "9bdaf65c667dedf2": "Granska trådens repo" } diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json index 86e48d8af0199..c5b944a80abda 100644 --- a/apps/web/src/i18n/translations/zh.json +++ b/apps/web/src/i18n/translations/zh.json @@ -13000,5 +13000,10 @@ "99451a5d2d40440f": "已由 {by} 撤回。", "3ee30a50b70fffab": "已由 {by} 撤回:{reason}", "92e129bf413a1220": "已撤回", - "800966eb58181745": "正在检查模型支持哪些语言…" + "800966eb58181745": "正在检查模型支持哪些语言…", + "e2e33c27c4a3af4c": "查找仓库...", + "b781f558378592af": "没有匹配的仓库。", + "18ed3e1af363c529": "工作区仓库", + "332d417f22d1e83e": "已达到仓库发现上限。", + "9bdaf65c667dedf2": "审查此线程的仓库" } diff --git a/apps/web/src/lib/diffFileContents.ts b/apps/web/src/lib/diffFileContents.ts index 7fcd821df7394..36dc2215d16a5 100644 --- a/apps/web/src/lib/diffFileContents.ts +++ b/apps/web/src/lib/diffFileContents.ts @@ -20,6 +20,7 @@ import { resolveFileDiffPath } from "./diffRendering"; interface GitDiffFileContentsSource { readonly environmentId: EnvironmentId; readonly cwd: string; + readonly requireRepositoryRoot?: boolean; readonly sourceKind: ReviewDiffPreviewSourceKind; readonly baseRef: string | null; readonly headRef: string | null; @@ -153,6 +154,7 @@ export function createGitDiffFileContentsLoader( environmentId: source.environmentId, input: { cwd: source.cwd, + ...(source.requireRepositoryRoot ? { requireRepositoryRoot: true } : {}), sourceKind: source.sourceKind, changeType, baseRef: source.baseRef, diff --git a/apps/web/src/lib/openPullRequestLink.browser.test.tsx b/apps/web/src/lib/openPullRequestLink.browser.test.tsx index 935cbd74a72b8..482b0cbeafa58 100644 --- a/apps/web/src/lib/openPullRequestLink.browser.test.tsx +++ b/apps/web/src/lib/openPullRequestLink.browser.test.tsx @@ -88,6 +88,7 @@ function setup() { }); useDiffPanelStore.setState({ byThreadKey: {}, + repositoryCwdByThreadKey: {}, branchBaseRefByThreadKey: {}, }); useRightPanelStore.setState({ byThreadKey: {}, userActionRevisionByThreadKey: {} }); @@ -152,6 +153,51 @@ it.each(["system", "app"] as const)( }, ); +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, + }); + }, +); it("opens an available commit in the closed Diff pane without the pane resetting it", async () => { setup(); const sha = "a".repeat(40); diff --git a/apps/web/src/lib/openPullRequestLink.ts b/apps/web/src/lib/openPullRequestLink.ts index 08d5996baa034..03e364055eccb 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 { thrownErrorMessage } from "@t3tools/client-runtime/errors"; import { parsePullRequestAnchor } from "@t3tools/shared/pullRequestAnchor"; import type { EnvironmentId, ScopedThreadRef } from "@t3tools/contracts"; @@ -218,6 +220,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 d436cd64eb144..7de181f7485cc 100644 --- a/docs/user/source-control.md +++ b/docs/user/source-control.md @@ -34,6 +34,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 use the repositories recorded in that turn's checkpoints. +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 fa93b3b81e7d5..6d24ae3fab775 100644 --- a/packages/client-runtime/src/state/review.ts +++ b/packages/client-runtime/src/state/review.ts @@ -111,6 +111,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, @@ -158,6 +163,7 @@ export function createReviewEnvironmentAtoms( JSON.stringify([ environmentId, input.cwd, + input.requireRepositoryRoot === true, input.sourceKind, input.baseRef, input.headRef, diff --git a/packages/contracts/src/review.ts b/packages/contracts/src/review.ts index 12292511c3a0a..2f80e0d573412 100644 --- a/packages/contracts/src/review.ts +++ b/packages/contracts/src/review.ts @@ -3,6 +3,20 @@ import { GitRefName, 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; // An object id or HEAD, never an option-looking ref, since it is passed to git as a revision. const ReviewMergeBase = Schema.String.check( Schema.isPattern(/^(?:[0-9a-f]{40}|[0-9a-f]{64}|HEAD)$/), @@ -19,6 +33,7 @@ export type ReviewDiffChangeType = typeof ReviewDiffChangeType.Type; export const ReviewDiffPreviewInput = Schema.Struct({ cwd: TrimmedNonEmptyString, + requireRepositoryRoot: Schema.optionalKey(Schema.Boolean), baseRef: Schema.optional(GitRefName), // A branch-range file read reuses its preview's merge base instead of resolving it again. mergeBase: Schema.optionalKey(ReviewMergeBase), @@ -43,6 +58,7 @@ export type ReviewDiffPreviewInput = typeof ReviewDiffPreviewInput.Type; export const ReviewBranchCommitsInput = Schema.Struct({ cwd: TrimmedNonEmptyString, + requireRepositoryRoot: Schema.optionalKey(Schema.Boolean), baseRef: Schema.optional(GitRefName), }); export type ReviewBranchCommitsInput = typeof ReviewBranchCommitsInput.Type; @@ -95,6 +111,7 @@ export type ReviewDiffPreviewSource = typeof ReviewDiffPreviewSource.Type; export const ReviewDiffFileContentsInput = Schema.Struct({ cwd: TrimmedNonEmptyString, + requireRepositoryRoot: Schema.optionalKey(Schema.Boolean), sourceKind: ReviewDiffPreviewSourceKind, changeType: ReviewDiffChangeType, baseRef: Schema.NullOr(GitRefName), diff --git a/packages/contracts/src/rpc.ts b/packages/contracts/src/rpc.ts index 29cea4095c2a1..ba73beebe0860 100644 --- a/packages/contracts/src/rpc.ts +++ b/packages/contracts/src/rpc.ts @@ -176,6 +176,8 @@ import { VcsStatusStreamEvent, } from "./git.ts"; import { + ReviewRepositoriesInput, + ReviewRepositoriesResult, ReviewBranchCommitsInput, ReviewBranchCommitsResult, ReviewDiffFileContentsInput, @@ -554,6 +556,7 @@ export const WS_METHODS = { gitResolvePullRequest: "git.resolvePullRequest", gitPreparePullRequestThread: "git.preparePullRequestThread", + reviewGetRepositories: "review.getRepositories", reviewGetBranchCommits: "review.getBranchCommits", reviewGetDiffPreview: "review.getDiffPreview", reviewGetDiffFileContents: "review.getDiffFileContents", @@ -1930,6 +1933,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, @@ -2685,6 +2694,7 @@ export const WsRpcGroup = RpcGroup.make( WsVcsCreateRefRpc, WsVcsSwitchRefRpc, WsVcsInitRpc, + WsReviewGetRepositoriesRpc, WsReviewGetBranchCommitsRpc, WsReviewGetDiffPreviewRpc, WsReviewGetDiffFileContentsRpc,