diff --git a/apps/mobile/src/Stack.tsx b/apps/mobile/src/Stack.tsx index 696b01ce29692..42403edbb1e7d 100644 --- a/apps/mobile/src/Stack.tsx +++ b/apps/mobile/src/Stack.tsx @@ -88,6 +88,7 @@ import { AddProjectSourceRoute } from "./features/projects/AddProjectSourceRoute import { NewTaskBranchPickerRouteScreen, NewTaskEnvironmentPickerRouteScreen, + NewTaskRepositoriesPickerRouteScreen, } from "./features/threads/NewTaskContextPickerScreens"; import { ExistingThreadSettingsRouteScreen, @@ -206,6 +207,7 @@ const ROUTE_TITLES: Readonly> = { NewTaskProject: msg("Choose project"), NewTaskEnvironment: msg("Environment"), NewTaskBranch: msg("Branch"), + NewTaskRepositories: msg("Repositories"), AddProject: msg("Add project"), ThreadFiles: msg("Files"), SettingsLegal: msg("Legal"), @@ -669,6 +671,11 @@ const RootStackConfig = createWorkspaceStackNavigator({ screen: NewTaskBranchPickerRouteScreen, options: pageRoute(), }), + NewTaskRepositories: createNativeStackScreen({ + linking: "new/draft/repositories", + screen: NewTaskRepositoriesPickerRouteScreen, + options: pageRoute(), + }), AddProject: createNativeStackScreen({ linking: "new/add-project", screen: AddProjectSourceRoute, diff --git a/apps/mobile/src/components/ComposerToolbar.tsx b/apps/mobile/src/components/ComposerToolbar.tsx index ddce24be0b210..36ed505d27cd0 100644 --- a/apps/mobile/src/components/ComposerToolbar.tsx +++ b/apps/mobile/src/components/ComposerToolbar.tsx @@ -30,6 +30,8 @@ export function ComposerInlineControl(props: { readonly accessibilityLabel?: string; readonly disabled?: boolean; readonly emphasized?: boolean; + /** The control asks for a decision; it stays usable. */ + readonly tone?: "warning"; readonly icon?: ComponentProps["name"]; readonly renderIcon?: (size: number) => ReactNode; readonly label: string; @@ -81,7 +83,11 @@ export function ComposerInlineControl(props: { name={props.icon} size={iconSize} tintColorClassName={ - props.emphasized || props.selected ? "accent-icon" : "accent-icon-muted" + props.tone === "warning" + ? "accent-warning-foreground" + : props.emphasized || props.selected + ? "accent-icon" + : "accent-icon-muted" } type="monochrome" /> @@ -94,7 +100,11 @@ export function ComposerInlineControl(props: { = new Set([ "AddProjectNew", "NewTaskEnvironment", "NewTaskBranch", + "NewTaskRepositories", "SettingsLegal", "SettingsAuth", "SettingsWaitlist", diff --git a/apps/mobile/src/features/review/ReviewSheet.tsx b/apps/mobile/src/features/review/ReviewSheet.tsx index afbcb7407aef5..7142394011e5e 100644 --- a/apps/mobile/src/features/review/ReviewSheet.tsx +++ b/apps/mobile/src/features/review/ReviewSheet.tsx @@ -8,7 +8,7 @@ import { AppBar } from "../../components/ui/AppBar"; import type { AppBarMenuItem } from "../../components/ui/AppBar.types"; import type { ReviewSectionItem } from "./reviewModel"; import { useReviewHeaderPresentation } from "./useReviewHeaderPresentation"; -import { T, useGT } from "gt-react-native"; +import { T, useGT, Var } from "gt-react-native"; import { type Ref, type ReactElement, useImperativeHandle, useRef, useState } from "react"; import { Pressable, ScrollView, type NativeSyntheticEvent, StyleSheet, View } from "react-native"; import { RefreshControl } from "../../components/ui/RefreshControl"; @@ -66,6 +66,8 @@ function ReviewHeader( readonly sectionMenu: ReturnType; readonly showSectionToolbar: boolean; readonly showChangedFilesToggle: boolean; + readonly selectedRepositoryKey: string | null; + readonly onSelectRepository: (key: string | null) => void; readonly fileFilter: ReturnType; readonly onSelectSection: (sectionId: string) => void; readonly onReturnToThread: () => void; @@ -156,6 +158,29 @@ function ReviewHeader( }, ] : []), + ...(props.selectedSection?.repositoryGroups + ? [ + { + id: "repositories", + title: gt("Repository"), + items: [ + { + id: "repository:all", + title: gt("All repositories"), + selected: props.selectedRepositoryKey === null, + onPress: () => props.onSelectRepository(null), + }, + ...props.selectedSection.repositoryGroups.map((group) => ({ + id: `repository:${group.key}`, + title: group.name, + subtitle: group.relativePath || undefined, + selected: group.key === props.selectedRepositoryKey, + onPress: () => props.onSelectRepository(group.key), + })), + ], + }, + ] + : []), ...(presentation.refreshAction ? [presentation.refreshAction] : []), ], }, @@ -407,6 +432,15 @@ export function ReviewSheet(props: ReviewSheetProps) { sections: reviewSections, selectedSectionId: selectedSection?.id ?? null, }); + const [repositorySelection, setRepositorySelection] = useState<{ + readonly sectionId: string; + readonly key: string; + } | null>(null); + const repositoryGroups = selectedSection?.repositoryGroups; + const selectedRepository = + repositorySelection !== null && repositorySelection.sectionId === selectedSection?.id + ? (repositoryGroups?.find((group) => group.key === repositorySelection.key) ?? null) + : null; const { headerDiffSummary, nativeReviewDiffData, @@ -414,6 +448,7 @@ export function ReviewSheet(props: ReviewSheetProps) { allFiles, fileFilter, pendingReviewCommentCount, + sectionFiles, loadVisibleFile, isPending: areFilePatchesPending, } = useReviewDiffData({ @@ -423,6 +458,13 @@ export function ReviewSheet(props: ReviewSheetProps) { selectedSection, draftMessage, draftContext, + repositoryFilter: + selectedRepository === null || repositoryGroups === undefined + ? null + : { + folder: selectedRepository.relativePath, + folders: repositoryGroups.map((group) => group.relativePath).join("\0"), + }, }); // Expo may return null before registration or in older binaries; use the fallback. const NativeReviewDiffView = resolveNativeReviewDiffView(); @@ -451,6 +493,7 @@ export function ReviewSheet(props: ReviewSheetProps) { threadKey: reviewCache.threadKey, sectionId: selectedSection?.id ?? null, files: allFiles, + sectionFiles, cachedExpandedFileIds: selectedSection?.id ? reviewCache.expandedFileIdsBySection[selectedSection.id] : undefined, @@ -465,9 +508,12 @@ export function ReviewSheet(props: ReviewSheetProps) { selectedSection, nativeReviewDiffData, }); + const reviewContentKey = selectedSection + ? `${selectedSection.id}:${selectedRepository?.key ?? ""}` + : null; const nativeBridge = useNativeReviewDiffBridge({ threadKey: reviewCache.threadKey, - sectionId: selectedSection?.id ?? null, + sectionId: reviewContentKey, diff: selectedSection?.diff, data: nativeReviewDiffData, collapsedFileIds, @@ -492,6 +538,12 @@ export function ReviewSheet(props: ReviewSheetProps) { reportShowcaseSceneRendered({ scene: "review", themeId: nativeBridge.themeId }); }; + const handleSelectRepository = (key: string | null) => { + commentSelection.clearSelection(); + setRepositorySelection( + key === null || !selectedSection ? null : { sectionId: selectedSection.id, key }, + ); + }; const handleSelectFile = async (fileId: string | null) => { loadVisibleFile(fileId, true); commentSelection.clearSelection(); @@ -567,6 +619,7 @@ export function ReviewSheet(props: ReviewSheetProps) { }; const androidHeaderSubtitle = [ selectedSection?.title, + selectedRepository?.name, headerDiffSummary.additions, headerDiffSummary.deletions, ] @@ -599,6 +652,19 @@ export function ReviewSheet(props: ReviewSheetProps) { children.push(); } + if (selectedSection?.unlistedRepositories) { + children.push( + + + + This turn's changes in {selectedSection.unlistedRepositories.join(", ")}{" "} + cannot be listed. + + + , + ); + } + if (allFilesHidden) { children.push( {children}; })(); const headerSubtitle = [ + selectedRepository?.name, headerDiffSummary.additions, headerDiffSummary.deletions, pendingReviewCommentCount > 0 @@ -651,6 +718,8 @@ export function ReviewSheet(props: ReviewSheetProps) { selectedSection={selectedSection} showSectionToolbar={showSectionToolbar} showChangedFilesToggle={showChangedFilesToggle} + selectedRepositoryKey={selectedRepository?.key ?? null} + onSelectRepository={handleSelectRepository} fileFilter={fileFilter} onRefresh={handlePullToRefresh} onSelectSection={selectSection} @@ -705,7 +774,7 @@ export function ReviewSheet(props: ReviewSheetProps) { appearanceScheme={selectedTheme} collapsedFileIdsJson={nativeBridge.collapsedFileIdsJson} collapsedCommentIdsJson={nativeBridge.collapsedCommentIdsJson} - contentResetKey={`${reviewCache.threadKey}:${selectedSection.id}`} + contentResetKey={`${reviewCache.threadKey}:${reviewContentKey}`} contentWidth={NATIVE_REVIEW_DIFF_CONTENT_WIDTH} contentInsetTop={listHeader ? 0 : topContentInset} contentInsetBottom={bottomContentInset} diff --git a/apps/mobile/src/features/review/reviewFileVisibility.test.tsx b/apps/mobile/src/features/review/reviewFileVisibility.test.tsx index ac983a81ab1c9..0905eaa149756 100644 --- a/apps/mobile/src/features/review/reviewFileVisibility.test.tsx +++ b/apps/mobile/src/features/review/reviewFileVisibility.test.tsx @@ -4,7 +4,10 @@ import { expect, it, vi } from "vite-plus/test"; import { buildReviewParsedDiff, type ReviewRenderableFile } from "./reviewModel"; import { useReviewFileVisibility } from "./reviewFileVisibility"; -const stored = vi.hoisted(() => ({ expanded: undefined as ReadonlyArray | undefined })); +const stored = vi.hoisted(() => ({ + expanded: undefined as ReadonlyArray | undefined, + viewed: undefined as ReadonlyArray | undefined, +})); vi.mock("./reviewState", () => ({ updateReviewExpandedFileIds: ( _threadKey: string, @@ -13,7 +16,13 @@ vi.mock("./reviewState", () => ({ ) => { stored.expanded = update(stored.expanded); }, - updateReviewViewedFileIds: () => {}, + updateReviewViewedFileIds: ( + _threadKey: string, + _sectionId: string, + update: (current: ReadonlyArray | undefined) => ReadonlyArray | undefined, + ) => { + stored.viewed = update(stored.viewed); + }, })); function patch(path: string, line: string) { @@ -26,7 +35,10 @@ function files(diff: string): ReadonlyArray { return parsed.files; } -function visibility(current: ReadonlyArray) { +function visibility( + current: ReadonlyArray, + section: ReadonlyArray = current, +) { let result: ReturnType | undefined; function Probe({ report }: { report: (value: typeof result) => void }) { report( @@ -34,8 +46,9 @@ function visibility(current: ReadonlyArray) { threadKey: "thread", sectionId: "turn:3", files: current, + sectionFiles: section, cachedExpandedFileIds: stored.expanded, - cachedViewedFileIds: undefined, + cachedViewedFileIds: stored.viewed, }), ); return null; @@ -67,3 +80,30 @@ it("folds only the selected entry when a file becomes a symlink", () => { visibility(current).toggleExpandedFile(current[0]!.id); expect(visibility(current).collapsedFileIds).toEqual([current[0]!.id]); }); + +it("keeps the marks of files a repository filter hides", () => { + stored.expanded = undefined; + stored.viewed = undefined; + const all = files( + patch("web/a.ts", "one") + patch("api/b.ts", "two") + patch("api/c.ts", "three"), + ); + const [webFile, apiFile, otherApiFile] = all; + visibility(all).toggleViewedFile(webFile!.id); + + const apiOnly = all.slice(1); + visibility(apiOnly).toggleViewedFile(apiFile!.id); + visibility(apiOnly).toggleExpandedFile(otherApiFile!.id); + + expect(visibility(all).viewedFileIds).toEqual([webFile!.id, apiFile!.id]); + expect(visibility(all).collapsedFileIds).toEqual(all.map((file) => file.id)); + visibility(apiOnly).toggleViewedFile(apiFile!.id); + expect(visibility(all).viewedFileIds).toEqual([webFile!.id]); + + stored.expanded = undefined; + visibility(apiOnly, all).toggleExpandedFile(apiFile!.id); + expect(visibility(all).collapsedFileIds).toEqual([apiFile!.id]); + stored.expanded = undefined; + stored.viewed = undefined; + visibility(apiOnly, all).toggleViewedFile(otherApiFile!.id); + expect(visibility(all).collapsedFileIds).toEqual([otherApiFile!.id]); +}); diff --git a/apps/mobile/src/features/review/reviewFileVisibility.ts b/apps/mobile/src/features/review/reviewFileVisibility.ts index 7e1379d2b5ff5..6c53c1c60fba6 100644 --- a/apps/mobile/src/features/review/reviewFileVisibility.ts +++ b/apps/mobile/src/features/review/reviewFileVisibility.ts @@ -55,16 +55,36 @@ function removeReviewFileId(fileIds: ReadonlyArray, fileId: string): Rea return fileIds.includes(fileId) ? fileIds.filter((id) => id !== fileId) : fileIds; } +// A repository filter shows part of a section; what is stored for the rest of it stays. +function withStoredOutsideView( + inView: ReadonlyArray, + stored: ReadonlyArray | undefined, + next: ReadonlyArray, +): ReadonlyArray { + if (stored === undefined) return next; + const visible = new Set(inView); + const outside = stored.filter((entry) => !visible.has(entry)); + return outside.length === 0 ? next : [...outside, ...next]; +} + export function useReviewFileVisibility(input: { readonly threadKey: string | null; readonly sectionId: string | null; readonly files: ReadonlyArray; + /** Every file of the section; `files` is part of it under a repository filter. */ + readonly sectionFiles: ReadonlyArray; readonly cachedExpandedFileIds: ReadonlyArray | undefined; readonly cachedViewedFileIds: ReadonlyArray | undefined; }) { - const { cachedExpandedFileIds, cachedViewedFileIds, files, sectionId, threadKey } = input; + const { cachedExpandedFileIds, cachedViewedFileIds, files, sectionFiles, sectionId, threadKey } = + input; const expansionKeys = useMemo(() => getReviewFileExpansionKeys(files), [files]); + // Nothing stored means every file is expanded, which the first change has to write down. + const sectionExpansionKeys = useMemo( + () => getReviewFileExpansionKeys(sectionFiles), + [sectionFiles], + ); const expandedFileIds = useMemo(() => { const expandedKeys = new Set(getExpandedReviewFileKeys(expansionKeys, cachedExpandedFileIds)); return files @@ -95,11 +115,15 @@ export function useReviewFileVisibility(input: { if (key === undefined) { return; } - updateReviewExpandedFileIds(threadKey, sectionId, (existing) => - toggleReviewFileId(getExpandedReviewFileKeys(expansionKeys, existing), key), + updateReviewExpandedFileIds(threadKey, sectionId, (existing = sectionExpansionKeys) => + withStoredOutsideView( + expansionKeys, + existing, + toggleReviewFileId(getExpandedReviewFileKeys(expansionKeys, existing), key), + ), ); }, - [expansionKeys, files, sectionId, threadKey], + [expansionKeys, files, sectionExpansionKeys, sectionId, threadKey], ); const toggleViewedFile = useCallback( @@ -110,17 +134,25 @@ export function useReviewFileVisibility(input: { const shouldCollapse = !viewedFileIds.includes(fileId); updateReviewViewedFileIds(threadKey, sectionId, (existing) => - toggleReviewFileId(getValidExplicitReviewFileIds(files, existing), fileId), + withStoredOutsideView( + files.map((file) => file.id), + existing, + toggleReviewFileId(getValidExplicitReviewFileIds(files, existing), fileId), + ), ); const key = expansionKeys[files.findIndex((file) => file.id === fileId)]; if (shouldCollapse && key !== undefined) { - updateReviewExpandedFileIds(threadKey, sectionId, (existing) => - removeReviewFileId(getExpandedReviewFileKeys(expansionKeys, existing), key), + updateReviewExpandedFileIds(threadKey, sectionId, (existing = sectionExpansionKeys) => + withStoredOutsideView( + expansionKeys, + existing, + removeReviewFileId(getExpandedReviewFileKeys(expansionKeys, existing), key), + ), ); } }, - [expansionKeys, files, sectionId, threadKey, viewedFileIds], + [expansionKeys, files, sectionExpansionKeys, sectionId, threadKey, viewedFileIds], ); return { diff --git a/apps/mobile/src/features/review/reviewModel.test.ts b/apps/mobile/src/features/review/reviewModel.test.ts index 5213e64bb878b..a1cedac294a5a 100644 --- a/apps/mobile/src/features/review/reviewModel.test.ts +++ b/apps/mobile/src/features/review/reviewModel.test.ts @@ -1,10 +1,14 @@ +import type { ThreadCheckpointSummary } from "@t3tools/client-runtime/state/thread-checkpoints"; +import { CheckpointRef, CheckpointScopeId, RunId } from "@t3tools/contracts"; import { describe, expect, it } from "vite-plus/test"; import { applyReviewDiffMetadata, buildReviewParsedDiff, buildReviewSectionItems, + filterReviewParsedDiffToFolder, resolveReviewSelectedSectionId, + type ReviewRenderableFile, type ReviewSectionItem, } from "./reviewModel"; @@ -33,6 +37,83 @@ describe("resolveReviewSelectedSectionId", () => { }); }); +describe("buildReviewSectionItems", () => { + const checkpoint = (turn: number, repositories?: ThreadCheckpointSummary["repositories"]) => + ({ + runId: RunId.make(`run-${turn}`), + checkpointTurnCount: turn, + checkpointRef: CheckpointRef.make(`ref-${turn}`), + status: "missing", + files: [], + ...(repositories === undefined ? {} : { repositories }), + assistantMessageId: null, + completedAt: "2026-11-10T00:00:00.000Z", + }) satisfies ThreadCheckpointSummary; + const repository = (name: string, paths: ReadonlyArray) => ({ + scopeId: CheckpointScopeId.make(`scope-${name}`), + name, + repositoryPath: `/work/${name}`, + cwd: `/work/${name}`, + relativePath: name, + files: paths.map((path) => ({ path, kind: "modified", additions: 2, deletions: 1 })), + baselineMissing: paths.length === 0, + }); + + it("offers a plain folder's turns that changed its repositories", () => { + const sections = buildReviewSectionItems({ + checkpoints: [ + checkpoint(1), + checkpoint(2, [repository("api", ["a.ts", "b.ts"]), repository("web", ["a.ts"])]), + checkpoint(3, [repository("api", ["a.ts"]), repository("web", [])]), + ], + gitSections: [], + turnDiffById: {}, + gitSectionStates: { "working-tree": null, "branch-range": null }, + }); + + expect(sections).toMatchObject([ + { id: "turn:3", subtitle: "1 file changed · api, web", unlistedRepositories: ["web"] }, + { + id: "turn:2", + subtitle: "3 files changed · api, web", + repositoryGroups: [ + { key: "/work/api", name: "api", relativePath: "api" }, + { key: "/work/web", name: "web", relativePath: "web" }, + ], + }, + ]); + expect(sections[0]).not.toHaveProperty("repositoryGroups"); + }); +}); + +describe("filterReviewParsedDiffToFolder", () => { + it("keeps the files of one folder, giving a nested repository its own", () => { + const file = (path: string) => ({ path, additions: 2, deletions: 1 }) as ReviewRenderableFile; + const parsed = { + kind: "files" as const, + files: ["README.md", "api/src/a.ts", "api/vendor/lib/a.ts", "apiary/a.ts"].map(file), + fileCount: 4, + additions: 8, + deletions: 4, + notice: null, + }; + const folders = ["", "api", "api/vendor/lib"]; + const paths = (folder: string) => { + const filtered = filterReviewParsedDiffToFolder(parsed, folder, folders); + return filtered.kind === "files" ? filtered.files.map((entry) => entry.path) : null; + }; + + expect(paths("")).toEqual(["README.md", "apiary/a.ts"]); + expect(paths("api/vendor/lib")).toEqual(["api/vendor/lib/a.ts"]); + expect(filterReviewParsedDiffToFolder(parsed, "api", folders)).toMatchObject({ + files: [{ path: "api/src/a.ts" }], + fileCount: 1, + additions: 2, + deletions: 1, + }); + }); +}); + describe("buildReviewParsedDiff", () => { it("keeps UI identities compact, stable, and isolated from parser cache keys", () => { const patch = diff --git a/apps/mobile/src/features/review/reviewModel.ts b/apps/mobile/src/features/review/reviewModel.ts index a5d5a18cec341..c1ac48615e53e 100644 --- a/apps/mobile/src/features/review/reviewModel.ts +++ b/apps/mobile/src/features/review/reviewModel.ts @@ -1,9 +1,7 @@ import { parsePatchFiles } from "@pierre/diffs/utils/parsePatchFiles"; import type { ChangeTypes, FileDiffMetadata } from "@pierre/diffs/types"; -import { - checkpointFileTotals, - type ThreadCheckpointSummary, -} from "@t3tools/client-runtime/state/thread-checkpoints"; +import type { ThreadCheckpointSummary } from "@t3tools/client-runtime/state/thread-checkpoints"; +import { turnChanges, turnHasChanges } from "@t3tools/client-runtime/state/thread-repositories"; import type { ReviewDiffPreviewSource } from "@t3tools/contracts"; import { quoteGitPatchPath } from "@t3tools/shared/gitPatchPath"; import * as Arr from "effect/Array"; @@ -25,6 +23,13 @@ const GIT_PLACEHOLDER_TITLES = { } as const satisfies Record; const UNCOMMITTED_SUBTITLE = msg("Staged, unstaged, and untracked files"); +/** A folder of a turn's patch: the thread's own (`relativePath` empty) or a tracked repository. */ +export interface ReviewRepositoryGroup { + readonly key: string; + readonly name: string; + readonly relativePath: string; +} + export interface ReviewSectionItem { readonly id: string; readonly kind: ReviewSectionKind; @@ -35,6 +40,10 @@ export interface ReviewSectionItem { readonly files?: ReviewDiffPreviewSource["files"]; readonly truncated?: boolean; readonly source?: ReviewGitSource; + /** Set when a turn's patch spans more than one folder. */ + readonly repositoryGroups?: ReadonlyArray; + /** Repositories the turn changed that have nothing recorded before it to compare with. */ + readonly unlistedRepositories?: ReadonlyArray; } export interface ReviewRenderableHunkRow { @@ -124,15 +133,40 @@ function checkpointTitle(checkpoint: ThreadCheckpointSummary, resolve: MessageRe } function checkpointSubtitle(checkpoint: ThreadCheckpointSummary, resolve: MessageResolver): string { - const fileCount = checkpointFileTotals(checkpoint).count; - if (checkpoint.status !== "ready") { + if (checkpoint.status !== "ready" && !turnHasChanges(checkpoint)) { return resolve(msg("Diff {status}", { status: checkpoint.status })); } - return resolve( + const { repositories, totals } = turnChanges(checkpoint); + const files = resolve( msg("{count, plural, one {{count} file changed} other {{count} files changed}}", { - count: fileCount, + count: totals.count, }), ); + return repositories.length === 0 + ? files + : `${files} · ${repositories.map((repository) => repository.name).join(", ")}`; +} + +function checkpointRepositoryGroups( + checkpoint: ThreadCheckpointSummary, + rootName: string, +): ReadonlyArray { + const { repositories, rootFiles } = turnChanges(checkpoint); + const groups = [ + ...(rootFiles.length === 0 ? [] : [{ key: ".", name: rootName, relativePath: "" }]), + ...repositories.flatMap((repository) => + repository.files.length === 0 || !repository.relativePath || repository.relativePath === "." + ? [] + : [ + { + key: repository.repositoryPath, + name: repository.name, + relativePath: repository.relativePath, + }, + ], + ), + ]; + return groups.length > 1 ? groups : []; } function compareCheckpointTurnCountDescending( @@ -518,7 +552,8 @@ export function getReadyReviewCheckpoints( ): ReadonlyArray { return pipe( checkpoints, - Arr.filter((checkpoint) => checkpoint.status === "ready"), + // A plain folder holding repositories never has a ready checkpoint of its own. + Arr.filter((checkpoint) => checkpoint.status === "ready" || turnHasChanges(checkpoint)), Arr.sort(readyCheckpointOrder), ); } @@ -540,12 +575,18 @@ export function buildReviewSectionItems(input: { readonly gitSections: ReadonlyArray; readonly turnDiffById: Readonly>; readonly gitSectionStates: Readonly>; + /** Names the thread folder's own files beside its repositories. */ + readonly rootName?: string; readonly resolve?: MessageResolver; }): ReadonlyArray { const resolve = input.resolve ?? m; const turnItems = getReadyReviewCheckpoints(input.checkpoints).map( (checkpoint) => { const id = getReviewSectionIdForCheckpoint(checkpoint); + const repositoryGroups = checkpointRepositoryGroups(checkpoint, input.rootName ?? "Project"); + const unlistedRepositories = (checkpoint.repositories ?? []).flatMap((repository) => + repository.baselineMissing ? [repository.name] : [], + ); return { id, kind: "turn", @@ -553,6 +594,8 @@ export function buildReviewSectionItems(input: { subtitle: checkpointSubtitle(checkpoint, resolve), diff: input.turnDiffById[id] ?? null, isLoading: false, + ...(repositoryGroups.length === 0 ? {} : { repositoryGroups }), + ...(unlistedRepositories.length === 0 ? {} : { unlistedRepositories }), }; }, ); @@ -728,3 +771,31 @@ export function applyReviewDiffMetadata( }); return { ...previewDiff, ...totals, files, fileCount: selectedSection.files.length, notice }; } + +/** + * The files of one folder of a turn's patch. A file belongs to the deepest folder holding it, + * and to the thread's own (the empty folder) when no repository does. + */ +export function filterReviewParsedDiffToFolder( + parsedDiff: ReviewParsedDiff, + folder: string, + folders: ReadonlyArray, +): ReviewParsedDiff { + if (parsedDiff.kind !== "files") return parsedDiff; + const files = parsedDiff.files.filter((file) => { + let owner = ""; + for (const candidate of folders) { + if (candidate.length > owner.length && file.path.startsWith(`${candidate}/`)) { + owner = candidate; + } + } + return owner === folder; + }); + return { + ...parsedDiff, + files, + fileCount: files.length, + additions: files.reduce((total, file) => total + file.additions, 0), + deletions: files.reduce((total, file) => total + file.deletions, 0), + }; +} diff --git a/apps/mobile/src/features/review/useReviewDiffData.ts b/apps/mobile/src/features/review/useReviewDiffData.ts index 0b6e4e4ba1151..cf6574d87b26b 100644 --- a/apps/mobile/src/features/review/useReviewDiffData.ts +++ b/apps/mobile/src/features/review/useReviewDiffData.ts @@ -8,6 +8,7 @@ import { getCachedReviewParsedDiff } from "./reviewState"; import { applyReviewDiffMetadata, buildReviewParsedDiff, + filterReviewParsedDiffToFolder, type ReviewParsedDiff, type ReviewRenderableFile, type ReviewSectionItem, @@ -31,6 +32,7 @@ import { import { useHideTestFilesPreference } from "../pull-requests/usePullRequestFileFilter"; const EMPTY_INLINE_REVIEW_COMMENTS = Object.freeze([]); +const NO_REVIEW_FILES: ReadonlyArray = Object.freeze([]); type ParsedFilePatch = AsyncResult.AsyncResult< { source: ReviewDiffPreviewSource; parsed: ReviewParsedDiff }, unknown @@ -149,6 +151,8 @@ export function useReviewDiffData(input: { readonly selectedSection: ReviewSectionItem | null; readonly draftMessage: string; readonly draftContext: OrchestrationMessageContext | undefined; + /** Shows one folder of a turn's patch; `folders` lists every folder, NUL-separated. */ + readonly repositoryFilter: { readonly folder: string; readonly folders: string } | null; }) { const { draftMessage, draftContext, selectedSection, threadKey } = input; const messages = useMessages(); @@ -156,7 +160,7 @@ export function useReviewDiffData(input: { const selectedSectionId = selectedSection?.id ?? null; const source = selectedSection?.source; const lazySource = source?.truncated && source.files ? source : null; - const previewDiff: ReviewParsedDiff = lazySource + const sectionDiff: ReviewParsedDiff = lazySource ? { kind: "empty" } : getCachedReviewParsedDiff({ threadKey, @@ -165,6 +169,19 @@ export function useReviewDiffData(input: { resolve: messages, locale, }); + const repositoryFolder = input.repositoryFilter?.folder ?? null; + const repositoryFolders = input.repositoryFilter?.folders ?? ""; + const previewDiff = useMemo( + () => + repositoryFolder === null + ? sectionDiff + : filterReviewParsedDiffToFolder( + sectionDiff, + repositoryFolder, + repositoryFolders.split("\0"), + ), + [sectionDiff, repositoryFolder, repositoryFolders], + ); const registry = useContext(RegistryContext); const { environmentId, cwd } = input; const scope = JSON.stringify([environmentId, cwd, lazySource?.kind, source?.baseRef]); @@ -306,6 +323,13 @@ export function useReviewDiffData(input: { parsedDiff: fileFilter.parsed, allFiles: parsedDiff.kind === "files" ? parsedDiff.files : EMPTY_REVIEW_FILES, fileFilter, + /** The section's files before the repository filter. */ + sectionFiles: + sectionDiff.kind === "files" + ? sectionDiff.files + : parsedDiff.kind === "files" + ? parsedDiff.files + : NO_REVIEW_FILES, loadVisibleFile, isPending: patches.some((patch) => patch?._tag === "Initial" || patch?.waiting), headerDiffSummary, diff --git a/apps/mobile/src/features/review/useReviewHeaderPresentation.tsx b/apps/mobile/src/features/review/useReviewHeaderPresentation.tsx index d0fda18cf60cd..30adccfff26dc 100644 --- a/apps/mobile/src/features/review/useReviewHeaderPresentation.tsx +++ b/apps/mobile/src/features/review/useReviewHeaderPresentation.tsx @@ -27,7 +27,7 @@ export function useReviewHeaderPresentation(props: { readonly selectedSection: ReviewSectionItem | null; readonly onRefresh: () => Promise; }): ReviewHeaderPresentation { - const { selectedThread } = useThreadSelection(); + const { selectedThread, selectedThreadProject } = useThreadSelection(); const gitState = useSelectedThreadGitState(); const gitActions = useSelectedThreadGitActions(); const gitStatusQuery = useEnvironmentQuery( @@ -45,6 +45,7 @@ export function useReviewHeaderPresentation(props: { environmentId: props.environmentId, threadId: props.threadId, currentBranch: selectedThread?.branch ?? null, + tracksRepositories: (selectedThreadProject?.trackedFolders?.length ?? 0) > 0, gitStatus: gitStatusQuery.data, gitOperationLabel: gitState.gitOperationLabel, onPull: gitActions.onPullSelectedThreadBranch, diff --git a/apps/mobile/src/features/review/useReviewSections.ts b/apps/mobile/src/features/review/useReviewSections.ts index 49b0a8b44c6ac..8cb6929169771 100644 --- a/apps/mobile/src/features/review/useReviewSections.ts +++ b/apps/mobile/src/features/review/useReviewSections.ts @@ -1,6 +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 { msg, useMessages } from "gt-react-native"; import { deriveThreadCheckpointSummaries } from "@t3tools/client-runtime/state/thread-checkpoints"; @@ -10,10 +11,11 @@ import { useCheckpointDiff } from "../../state/queries"; import { useEnvironmentQuery } from "../../state/query"; import { useEnvironmentPresentation } from "../../state/presentation"; import { lastReviewGitSectionsAtom, reviewEnvironment } from "../../state/review"; -import { lastReviewTurnDiffsAtom } from "../../state/reviewTurnDiffs"; +import { lastReviewTurnDiffsAtom, reviewTurnDiffText } from "../../state/reviewTurnDiffs"; import { environmentSession } from "../../state/session"; import { useSelectedThreadProjection } from "../../state/use-thread-detail"; import { useSelectedThreadWorktree } from "../../state/use-selected-thread-worktree"; +import { useThreadSelection } from "../../state/use-thread-selection"; import { buildReviewSectionItems, getReadyReviewCheckpoints, @@ -59,6 +61,7 @@ export function useReviewSections(input: { const { canReadFiles } = fileAccess; const selectedThread = useSelectedThreadProjection(); const { selectedThreadCwd } = useSelectedThreadWorktree(); + const { selectedThreadProject } = useThreadSelection(); const diffPreviewQuery = (sourceKind: ReviewGitSectionKind) => canReadFiles && enabled && environmentId !== undefined && selectedThreadCwd !== null ? reviewEnvironment.diffPreview({ @@ -108,6 +111,7 @@ export function useReviewSections(input: { "working-tree": gitSectionState(fileAccess.isPending, workingTreePreview), "branch-range": gitSectionState(fileAccess.isPending, branchPreview), }, + ...(selectedThreadProject ? { rootName: selectedThreadProject.title } : {}), resolve: messages, }); const selectedSectionId = resolveReviewSelectedSectionId( @@ -129,13 +133,18 @@ export function useReviewSections(input: { toTurnCount: enabled ? (activeCheckpoint?.checkpointTurnCount ?? null) : null, ignoreWhitespace: false, }); + const activeTurnDiffData = activeTurnDiff.data; + const activeTurnDiffText = useMemo( + () => (activeTurnDiffData == null ? null : reviewTurnDiffText(activeTurnDiffData)), + [activeTurnDiffData], + ); const reviewSections = cachedSections.map((section): ReviewSectionItem => { if (section.kind === "turn") { return section.id === activeSectionId ? { ...section, - diff: activeTurnDiff.data?.diff ?? section.diff, + diff: activeTurnDiffText ?? section.diff, isLoading: activeTurnDiff.isPending, } : section; diff --git a/apps/mobile/src/features/settings/ProjectRepositoriesSection.tsx b/apps/mobile/src/features/settings/ProjectRepositoriesSection.tsx new file mode 100644 index 0000000000000..32a1c22a1e050 --- /dev/null +++ b/apps/mobile/src/features/settings/ProjectRepositoriesSection.tsx @@ -0,0 +1,191 @@ +import { + appendTrackedFolders, + suggestedTrackedFolders, +} from "@t3tools/client-runtime/state/projects"; +import { + isAtomCommandInterrupted, + squashAtomCommandFailure, +} from "@t3tools/client-runtime/state/runtime"; +import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell"; +import { + AuthFilesystemReadScope, + AuthOrchestrationOperateScope, + PROJECT_TRACKED_FOLDERS_MAX, + type ProjectTrackedFolder, + type WorkspaceFolderState, +} from "@t3tools/contracts"; +import { msg, T, useGT, useMessages } from "gt-react-native"; +import { useState } from "react"; +import { Pressable } from "react-native"; + +import { AppText as Text } from "../../components/ui/AppText"; +import * as Dialog from "../../components/ui/Dialog"; +import { ListActionRow } from "../../components/ui/ListActionRow"; +import { ListRowLayout } from "../../components/ui/ListRowLayout"; +import { filesystemEnvironment } from "../../state/filesystem"; +import { projectEnvironment } from "../../state/projects"; +import { useEnvironmentQuery } from "../../state/query"; +import { useEnvironmentScope } from "../../state/session"; +import { useAtomCommand } from "../../state/use-atom-command"; +import { SettingsSection } from "./components/SettingsSection"; + +const FOLDER_STATE_LABELS: Record = { + git: msg("Git repository"), + plain: msg("Folder", { $context: "a plain folder that is not a Git repository" }), + missing: msg("Missing", { $context: "folder state: not found on disk" }), +}; + +/** Tracked folders are paths on one environment, so each checkout gets its own section. */ +export function ProjectRepositoriesSection(props: { + readonly member: EnvironmentProject; + readonly title: string; +}) { + const { member } = props; + const gt = useGT(); + const m = useMessages(); + const tracked = member.trackedFolders ?? []; + const canEdit = useEnvironmentScope(member.environmentId, AuthOrchestrationOperateScope); + const canReadFiles = useEnvironmentScope(member.environmentId, AuthFilesystemReadScope); + // Read from disk: the project's own copy of the list can be a moment behind a clone. + const listQuery = useEnvironmentQuery( + canReadFiles + ? filesystemEnvironment.listFolders({ + environmentId: member.environmentId, + input: { projectId: member.id }, + }) + : null, + ); + const folders: ReadonlyArray = + listQuery.data?.folders ?? tracked; + // Only a workspace file's folders are offered: the rest is found without asking. + const scanQuery = useEnvironmentQuery( + canReadFiles + ? filesystemEnvironment.scanFolders({ + environmentId: member.environmentId, + input: { workspaceRoot: member.workspaceRoot }, + }) + : null, + ); + const suggested = suggestedTrackedFolders(folders, scanQuery.data?.folders ?? []); + const updateProject = useAtomCommand(projectEnvironment.update, { reportFailure: false }); + const [isSaving, setIsSaving] = useState(false); + // A save builds on the listed folders, so it waits for the list that follows the last one. + const isBusy = isSaving || listQuery.isPending; + const added = folders.filter((folder) => folder.discovered !== true); + + // One folder in or out: the server applies it to its own list, which another client may have + // changed while a confirmation was open here. + const save = async ( + change: { readonly track: ProjectTrackedFolder } | { readonly untrack: string }, + ) => { + setIsSaving(true); + const result = await updateProject({ + environmentId: member.environmentId, + input: { + projectId: member.id, + ...("track" in change + ? { trackFolders: [{ path: change.track.path, name: change.track.name }] } + : { untrackFolders: [change.untrack] }), + }, + }); + setIsSaving(false); + if (result._tag === "Failure") { + if (!isAtomCommandInterrupted(result)) { + const error = squashAtomCommandFailure(result); + Dialog.alert( + gt("Failed to update repositories"), + error instanceof Error ? error.message : gt("An error occurred."), + ); + } + return; + } + listQuery.refresh(); + }; + + const remove = (folder: ProjectTrackedFolder) => + Dialog.confirm({ + title: gt("Remove folder"), + message: gt("Agents in this project stop working in {name}. Files on disk are not touched.", { + name: folder.name, + }), + confirmText: gt("Remove", { $context: "verb, removes a folder from the project" }), + destructive: true, + onConfirm: () => void save({ untrack: folder.path }), + }); + + const add = (folder: ProjectTrackedFolder) => { + const next = appendTrackedFolders(added, [folder]); + if (next === null) { + Dialog.alert( + gt("Too many folders"), + gt("A project can cover up to {max} folders.", { max: PROJECT_TRACKED_FOLDERS_MAX }), + ); + return; + } + void save({ track: folder }); + }; + + if (folders.length === 0 && suggested.length === 0) { + return ( + + {null} + + ); + } + + return ( + + {folders.map((folder) => ( + + {m(FOLDER_STATE_LABELS[folder.state])} + + ) + } + accessory={ + // A repository inside the project folder is there for as long as it is on disk. + folder.discovered === true ? undefined : ( + remove(folder)} + className="rounded-full border border-border bg-card px-3 py-1.5 disabled:opacity-40" + > + + Remove + + + ) + } + /> + ))} + {suggested.map((folder) => ( + add(folder)} + /> + ))} + + ); +} diff --git a/apps/mobile/src/features/settings/SettingsProjectOverviewRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsProjectOverviewRouteScreen.tsx index de9203b37332c..ca9a8999e3ddc 100644 --- a/apps/mobile/src/features/settings/SettingsProjectOverviewRouteScreen.tsx +++ b/apps/mobile/src/features/settings/SettingsProjectOverviewRouteScreen.tsx @@ -40,6 +40,7 @@ import { SettingsScreen } from "./components/SettingsScreen"; import { SettingsSection } from "./components/SettingsSection"; import { ListActionRow as SettingsActionRow } from "../../components/ui/ListActionRow"; import { SettingsSwitchRow } from "./components/SettingsSwitchRow"; +import { ProjectRepositoriesSection } from "./ProjectRepositoriesSection"; import { useSettingsEnvironmentMenu } from "./components/SettingsEnvironmentFilterHeader"; import { useSettingsEnvironmentFilter, type SettingsTarget } from "./settings-environment-filter"; import { leaveSettingsPage } from "./settings-navigation"; @@ -439,6 +440,24 @@ function ProjectOverviewContent(props: { ); })} + {props.members.map((member) => { + const environment = props.environments.find( + (entry) => entry.environmentId === member.environmentId, + )?.label; + return ( + + ); + })} diff --git a/apps/mobile/src/features/threads/DraftThreadHeader.tsx b/apps/mobile/src/features/threads/DraftThreadHeader.tsx index 26e262e339af1..86422f948c151 100644 --- a/apps/mobile/src/features/threads/DraftThreadHeader.tsx +++ b/apps/mobile/src/features/threads/DraftThreadHeader.tsx @@ -59,6 +59,7 @@ export function DraftThreadHeader(props: { environmentId, threadId: props.thread.id, hasThread: false, + tracksRepositories: (props.project.trackedFolders?.length ?? 0) > 0, currentBranch: props.thread.branch, gitStatus: status.data, gitOperationLabel: vcsActionLabelText(progress, messages), diff --git a/apps/mobile/src/features/threads/NewTaskContextPickerScreens.tsx b/apps/mobile/src/features/threads/NewTaskContextPickerScreens.tsx index 21a16cbf7f232..97a3ce45fab3a 100644 --- a/apps/mobile/src/features/threads/NewTaskContextPickerScreens.tsx +++ b/apps/mobile/src/features/threads/NewTaskContextPickerScreens.tsx @@ -344,6 +344,104 @@ export function NewTaskBranchPickerRouteScreen() { ); } +export function NewTaskRepositoriesPickerRouteScreen() { + const gt = useGT(); + const flow = useNewTaskFlow(); + const navigation = useNavigation(); + const insets = useSafeAreaInsets(); + const choices = flow.worktreeRepositoryChoices; + const selection = flow.worktreeRepositorySelection; + const selected = new Set(selection.selected); + const toggle = (repositoryPath: string) => { + if (choices === null) return; + void Haptics.selectionAsync(); + flow.setWorktreeRepositories( + choices.flatMap((choice) => + (choice.repositoryPath === repositoryPath) !== selected.has(choice.repositoryPath) + ? [choice.repositoryPath] + : [], + ), + ); + }; + const header = + choices === null || choices.length === 0 ? null : ( + + + {selection.needsChoice + ? gt("Choose the repositories this thread works on.") + : gt("Each gets its own worktree on the thread's branch.")} + + + @@ -2109,3 +2048,148 @@ function CheckoutGitActionsControl({ ); } + +/** Git actions for a thread's own folder, whose branch the thread or its draft records. */ +export default function ThreadGitActionsControl({ + gitCwd, + name, + activeThreadRef, + draftId, + ...view +}: ThreadGitActionsControlProps) { + const updateThreadMetadata = useAtomCommand( + threadEnvironment.updateMetadata, + "thread branch metadata update", + ); + const activeEnvironmentId = activeThreadRef?.environmentId ?? null; + // Subscribed so a granted or revoked scope re-renders the control that reads it on demand. + useEnvironmentScope(activeEnvironmentId, AuthOrchestrationOperateScope); + const activeServerThreadShell = useQuietThreadShell(activeThreadRef); + const activeDraftThread = useComposerDraftStore((store) => + draftId + ? store.getDraftSession(draftId) + : activeThreadRef + ? store.getDraftThreadByRef(activeThreadRef) + : null, + ); + const activeServerThreadProjection = useQuietThreadProjection( + activeDraftThread !== null && activeServerThreadShell === null ? null : activeThreadRef, + ); + const activeServerThread = + activeServerThreadShell ?? activeServerThreadProjection?.projection.thread ?? null; + const isLocalDraftThread = activeDraftThread !== null && activeServerThread === null; + const setDraftThreadContext = useComposerDraftStore((store) => store.setDraftThreadContext); + const changesBaseRef = useDiffPanelStore((state) => + selectThreadBranchBaseRef(state, activeThreadRef), + ); + const sourceControlScope = { environmentId: activeEnvironmentId, cwd: gitCwd }; + // The same subscription the control below holds, so this adds no read of its own. + const { data: gitStatus } = useEnvironmentQuery( + activeEnvironmentId !== null && gitCwd !== null + ? vcsEnvironment.status({ environmentId: activeEnvironmentId, input: { cwd: gitCwd } }) + : null, + ); + const isGitActionRunning = useSourceControlActionRunning( + sourceControlScope, + RUNNING_SOURCE_CONTROL_ACTIONS, + ); + + const persistThreadBranchSync = (branch: string | null, manualSelection = false) => { + if (!activeThreadRef) { + return; + } + + if (activeServerThread) { + if ( + !readEnvironmentScope(activeThreadRef.environmentId, AuthOrchestrationOperateScope) || + activeServerThread.branch === branch + ) { + return; + } + + void updateThreadMetadata({ + environmentId: activeThreadRef.environmentId, + input: { + threadId: activeThreadRef.threadId, + ...resolveThreadBranchMetadataPatch(branch, activeServerThread.branch), + }, + }); + + return; + } + + if (!activeDraftThread || activeDraftThread.branch === branch) { + return; + } + + setDraftThreadContext(draftId ?? activeThreadRef, { + branch, + worktreePath: activeDraftThread.worktreePath, + environmentSelection: manualSelection + ? "manual" + : (activeDraftThread.environmentSelection ?? + (activeDraftThread.branch ? "manual" : "auto")), + }); + }; + const persistLiveThreadBranch = useEffectEvent((branch: string | null) => { + persistThreadBranchSync(branch); + }); + + const isSelectingWorktreeBase = + !activeServerThread && + activeDraftThread?.envMode === "worktree" && + activeDraftThread.worktreePath === null; + + // Until a clone finishes, the status names an unborn HEAD that the repository may never have. + const activeProjectClone = useProjectClone( + activeDraftThread + ? scopeProjectRef(activeDraftThread.environmentId, activeDraftThread.projectId) + : null, + ); + const isProjectCloning = activeProjectClone !== null && activeProjectClone.phase !== "done"; + + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- persists the draft thread branch when the live git status subscription reports a different branch + useEffect(() => { + if (isGitActionRunning || isSelectingWorktreeBase || activeServerThread || isProjectCloning) { + return; + } + + const branchUpdate = resolveLiveThreadBranchUpdate({ + threadBranch: activeDraftThread?.branch ?? null, + gitStatus, + }); + if (!branchUpdate) { + return; + } + + persistLiveThreadBranch(branchUpdate.branch); + }, [ + activeServerThread, + activeDraftThread?.branch, + gitStatus, + isGitActionRunning, + isProjectCloning, + isSelectingWorktreeBase, + ]); + + return ( + + isLocalDraftThread || + (activeEnvironmentId !== null && + readEnvironmentScope(activeEnvironmentId, AuthOrchestrationOperateScope)), + follow: (branch) => persistThreadBranchSync(branch, true), + }} + quietUntilWork={draftId !== undefined || activeServerThreadShell?.latestRun === null} + changesBaseRef={changesBaseRef} + /> + ); +} diff --git a/apps/web/src/components/Sidebar.logic.test.ts b/apps/web/src/components/Sidebar.logic.test.ts index 671897b2b819d..af006833c8134 100644 --- a/apps/web/src/components/Sidebar.logic.test.ts +++ b/apps/web/src/components/Sidebar.logic.test.ts @@ -37,6 +37,7 @@ import { groupSidebarThreadsByProject, resolveSidebarFolderDot, sidebarFolderExpansionKeys, + withoutRemovedCheckout, } from "./Sidebar.logic"; import { scopeThreadRef, scopedThreadKey } from "@t3tools/client-runtime/environment"; import { @@ -154,6 +155,48 @@ function makeLatestRun(overrides?: { }; } +describe("withoutRemovedCheckout", () => { + const worktree = { branch: "t3/task", worktreePath: "/worktrees/task" }; + const local = { branch: "main", worktreePath: null }; + const removed = { branch: null, worktreePath: null }; + const tracking = { trackedFolders: [{ path: "/work/wrapper/api" }] }; + + it.each([ + { + why: "status still loading", + thread: worktree, + isRepo: undefined, + project: null, + to: worktree, + }, + { why: "a live checkout", thread: worktree, isRepo: true, project: null, to: worktree }, + { why: "a removed worktree", thread: worktree, isRepo: false, project: null, to: removed }, + { + why: "a removed worktree of a project tracking nothing", + thread: worktree, + isRepo: false, + project: { trackedFolders: [] }, + to: removed, + }, + { + why: "a plain task folder of a project with tracked folders", + thread: worktree, + isRepo: false, + project: tracking, + to: worktree, + }, + { + why: "a local thread whose project folder is not a repository", + thread: local, + isRepo: false, + project: tracking, + to: removed, + }, + ])("$why", ({ thread, isRepo, project, to }) => { + expect(withoutRemovedCheckout(thread, { isRepo }, project)).toEqual(to); + }); +}); + describe("orderItemsByPreferredIds", () => { it("resolves legacy preference aliases without materializing project state", () => { const ordered = orderItemsByPreferredIds({ diff --git a/apps/web/src/components/Sidebar.logic.ts b/apps/web/src/components/Sidebar.logic.ts index 854137575136a..49109eb4ac2b0 100644 --- a/apps/web/src/components/Sidebar.logic.ts +++ b/apps/web/src/components/Sidebar.logic.ts @@ -166,11 +166,18 @@ export function useSnoozeWakeClock( return clockMs; } -// Live status that says the cwd is not a repository means the checkout was removed. +// Live status that says the cwd is not a repository means the checkout was removed. A worktree +// thread of a project with tracked folders may sit in a plain task folder, which never is one. export function withoutRemovedCheckout< T extends { readonly branch: string | null; readonly worktreePath: string | null }, ->(thread: T, gitStatus: { readonly isRepo?: boolean | undefined } | null): T { - return gitStatus?.isRepo === false ? { ...thread, branch: null, worktreePath: null } : thread; +>( + thread: T, + gitStatus: { readonly isRepo?: boolean | undefined } | null, + project: { readonly trackedFolders?: ReadonlyArray | undefined } | null, +): T { + if (gitStatus?.isRepo !== false) return thread; + if (thread.worktreePath !== null && (project?.trackedFolders?.length ?? 0) > 0) return thread; + return { ...thread, branch: null, worktreePath: null }; } export function useRetainedValue(key: string | null, value: T | null): T | null { diff --git a/apps/web/src/components/WorktreeRepositoriesControl.tsx b/apps/web/src/components/WorktreeRepositoriesControl.tsx new file mode 100644 index 0000000000000..350f64a2c06c1 --- /dev/null +++ b/apps/web/src/components/WorktreeRepositoriesControl.tsx @@ -0,0 +1,185 @@ +import { + resolveWorktreeRepositorySelection, + type WorktreeRepositoryChoice, +} from "@t3tools/client-runtime/state/thread-repositories"; +import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell"; +import { FolderGitIcon } from "lucide-react"; +import { T, useGT, useMessages } from "gt-react"; +import { memo, useState } from "react"; + +import { type ComposerThreadTarget, useComposerDraftStore } from "../composerDraftStore"; +import { useWorktreeRepositoryChoices } from "../hooks/useWorktreeRepositoryChoices"; +import { + rememberWorktreeRepositories, + setWorktreeBaseBranch, + useRememberedWorktreeRepositories, + useWorktreeBaseBranch, +} from "../worktreeRepositoryChoiceStore"; +import { cn } from "../lib/utils"; +import { ComposerContextLabel } from "./ComposerContextLabel"; +import { ComposerControl } from "./chat/ComposerControl"; +import { useComposerMenuProps } from "./chat/composerEventScope"; +import { + Menu, + MenuCheckboxItem, + MenuGroup, + MenuGroupLabel, + MenuItem, + MenuItemDetail, + MenuItemLabel, + MenuPopup, + MenuSearchInput, + MenuSeparator, + MenuTrigger, +} from "./ui/menu"; + +/** A checklist this long gets a filter. */ +const FILTER_ABOVE_CHOICES = 8; + +function matchesFilter(choice: WorktreeRepositoryChoice, filter: string): boolean { + return ( + choice.name.toLowerCase().includes(filter) || + (choice.relativePath ?? choice.repositoryPath).toLowerCase().includes(filter) + ); +} + +/** + * Which tracked repositories a new worktree thread gets a worktree of. The choice lives in the + * draft thread; until the user makes one, the server's default applies. + */ +export const WorktreeRepositoriesControl = memo(function WorktreeRepositoriesControl(props: { + project: EnvironmentProject; + draftTarget: ComposerThreadTarget; + /** A plain project folder has no branch picker of its own, so the base branch is named here. */ + offersBaseBranch: boolean; +}) { + const baseBranch = useWorktreeBaseBranch(props.project); + const composerFloatingLayerProps = useComposerMenuProps(); + const { choices } = useWorktreeRepositoryChoices(props.project); + const drafted = useComposerDraftStore( + (store) => store.getDraftThread(props.draftTarget)?.worktreeRepositories, + ); + // A new draft starts from the project's last choice. + const chosen = useRememberedWorktreeRepositories(props.project) ?? undefined; + const effective = drafted ?? chosen; + const setDraftThreadContext = useComposerDraftStore((store) => store.setDraftThreadContext); + const [filter, setFilter] = useState(""); + const gt = useGT(); + const messages = useMessages(); + + if (choices === null || choices.length === 0) return null; + + const selection = resolveWorktreeRepositorySelection({ choices, chosen: effective }, messages); + const selected = new Set(selection.selected); + const choose = (paths: ReadonlyArray) => { + setDraftThreadContext(props.draftTarget, { worktreeRepositories: paths }); + rememberWorktreeRepositories(props.project, paths); + }; + const normalizedFilter = filter.trim().toLowerCase(); + const visible = + normalizedFilter === "" + ? choices + : choices.filter((choice) => matchesFilter(choice, normalizedFilter)); + + return ( + (open ? undefined : setFilter(""))}> + } + className={cn( + "min-w-0 flex-initial justify-start", + selection.needsChoice && "text-warning-foreground dark:text-warning-foreground", + )} + aria-label={gt("Repositories in the new worktree: {selection}", { + selection: selection.label, + })} + data-composer-context-control + > + + {selection.label} + + + {choices.length > FILTER_ABOVE_CHOICES ? ( + setFilter(event.currentTarget.value)} + placeholder={gt("Filter repositories")} + aria-label={gt("Filter repositories")} + /> + ) : null} + + + {selection.needsChoice + ? gt("Choose the repositories this thread works on") + : gt("Each gets its own worktree on the thread's branch")} + + {visible.length === 0 ? ( + + No repositories match + + ) : null} + {visible.map((choice) => ( + + choose( + choices.flatMap((candidate) => + ( + candidate.repositoryPath === choice.repositoryPath + ? next + : selected.has(candidate.repositoryPath) + ) + ? [candidate.repositoryPath] + : [], + ), + ) + } + > + + {choice.name} + {choice.relativePath !== undefined && choice.relativePath !== choice.name ? ( + {choice.relativePath} + ) : null} + + + ))} + + {props.offersBaseBranch ? ( + <> + + + + Start from this branch where a repository has it + + + setWorktreeBaseBranch(props.project, event.currentTarget.value.trim()) + } + placeholder={gt("Each repository's default branch")} + aria-label={gt("Base branch")} + /> + + + ) : null} + + choose(choices.map((choice) => choice.repositoryPath))} + > + Select all + + choose([])} + > + Select none + + + + ); +}); diff --git a/apps/web/src/components/chat/ChangedFilesTree.tsx b/apps/web/src/components/chat/ChangedFilesTree.tsx index 6cacd2dba8f8b..387c3b3d51868 100644 --- a/apps/web/src/components/chat/ChangedFilesTree.tsx +++ b/apps/web/src/components/chat/ChangedFilesTree.tsx @@ -10,6 +10,7 @@ import { ChevronsDownUpIcon, ChevronsUpDownIcon, FolderClosedIcon, + FolderGit2Icon, FolderIcon, } from "lucide-react"; import { cn } from "~/lib/utils"; @@ -19,6 +20,7 @@ import { Button } from "../ui/button"; import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; import { MiddleTruncate } from "../ui/middle-truncate"; import { observeResize } from "~/lib/observeResize"; +import { repositoryFilePath } from "@t3tools/client-runtime/state/thread-repositories"; const EMPTY_DIRECTORY_OVERRIDES: Record = {}; const VIRTUALIZE_AFTER_ROWS = 250; @@ -29,13 +31,38 @@ interface ChangedFileRow { depth: number; } -type ChangedFileContextMenuHandler = (filePath: string, event: MouseEvent) => void; +/** One folder's share of a turn that changed several repositories. */ +export interface ChangedFilesGroup { + readonly key: string; + readonly name: string; + /** Paths relative to this group's folder. */ + readonly files: ReadonlyArray; + readonly totals: OrchestrationV2CheckpointFileTotals; + /** The folder from the thread's folder; undefined when the diff cannot be opened at a file. */ + readonly relativePath: string | undefined; + /** Shown in place of the files when they cannot be listed. */ + readonly note?: string | undefined; +} + +type ChangedFileContextMenuHandler = ( + filePath: string, + event: MouseEvent, + group?: ChangedFilesGroup, +) => void; + +function groupDiffPath(group: ChangedFilesGroup, filePath: string | undefined) { + return filePath === undefined || group.relativePath === undefined + ? undefined + : repositoryFilePath(group.relativePath, filePath); +} export const ChangedFilesCard = memo(function ChangedFilesCard(props: { runId: RunId; /** May be a prefix of the changed files; `totals` covers all of them. */ files: ReadonlyArray; totals: OrchestrationV2CheckpointFileTotals; + /** Set when the turn changed tracked repositories; replaces the single tree built from `files`. */ + groups?: ReadonlyArray | undefined; allDirectoriesExpanded: boolean; resolvedTheme: "light" | "dark"; onToggleAllDirectories: () => void; @@ -46,6 +73,7 @@ export const ChangedFilesCard = memo(function ChangedFilesCard(props: { runId, files, totals, + groups, allDirectoriesExpanded, resolvedTheme, onToggleAllDirectories, @@ -54,8 +82,13 @@ export const ChangedFilesCard = memo(function ChangedFilesCard(props: { } = props; const gt = useGT(); const syncTimelineLayout = useSyncLayout(); - const hiddenFileCount = totals.count - files.length; - const hasDirectories = files.some((file) => /[/\\]/.test(file.path)); + const listedFiles = groups ? groups.flatMap((group) => group.files) : files; + const hiddenFileCount = totals.count - listedFiles.length; + const hasDirectories = listedFiles.some((file) => /[/\\]/.test(file.path)); + const firstGroup = groups?.find((group) => group.files.length > 0); + const firstFilePath = groups + ? firstGroup && groupDiffPath(firstGroup, firstGroup.files[0]?.path) + : files[0]?.path; return (
onOpenTurnDiff(runId, files[0]?.path)} + onClick={() => onOpenTurnDiff(runId, firstFilePath)} /> } > @@ -136,22 +169,38 @@ export const ChangedFilesCard = memo(function ChangedFilesCard(props: {
- +
+ {groups ? ( + groups.map((group) => ( + + )) + ) : ( + + )} +
{hiddenFileCount > 0 && (
+ {collapsed ? null : group.note !== undefined ? ( +

{group.note}

+ ) : ( + onOpenTurnDiff(run, groupDiffPath(group, filePath))} + onFileContextMenu={ + onFileContextMenu + ? (filePath, event) => onFileContextMenu(filePath, event, group) + : undefined + } + /> + )} + + ); +} + const ChangedFilesTree = memo(function ChangedFilesTree(props: { runId: RunId; files: ReadonlyArray; + /** Rows start this deep, below the row of the folder the files belong to. */ + baseDepth?: number; allDirectoriesExpanded: boolean; resolvedTheme: "light" | "dark"; onOpenTurnDiff: (runId: RunId, filePath?: string) => void; onFileContextMenu?: ChangedFileContextMenuHandler | undefined; }) { + const baseDepth = props.baseDepth ?? 0; const { files, allDirectoriesExpanded, onOpenTurnDiff, resolvedTheme, runId, onFileContextMenu } = props; // Place state before tree derivation to preserve its compiler cache. @@ -208,7 +321,7 @@ const ChangedFilesTree = memo(function ChangedFilesTree(props: { const virtualized = rows.length > VIRTUALIZE_AFTER_ROWS; const renderRow = ({ node, depth }: ChangedFileRow) => { - const leftPadding = 8 + depth * 14; + const leftPadding = 8 + (baseDepth + depth) * 14; if (node.kind === "directory") { const isExpanded = expandedDirectories[node.path] ?? allDirectoriesExpanded; return ( @@ -261,7 +374,7 @@ const ChangedFilesTree = memo(function ChangedFilesTree(props: { : undefined } > - {hasDirectoryNodes || depth > 0 ? ( + {hasDirectoryNodes || baseDepth + depth > 0 ? (