feat(projects): a project can track several repositories #35921
tanstack-source added labelsfeature
juliusmarminge added labelsagent-context-increase
github-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XXL
- @@ -0,0 +53,21 @@53+ readonly checked: ReadonlyArray<WorkspaceScannedFolder>;54+}): ReadonlyArray<ProjectTrackedFolder> {55+ const scannedKeys = new Set(56+ input.scanned.map((folder) => normalizeProjectPathForComparison(folder.path)),57+ );58+ const checkedKeys = new Set(59+ input.checked.map((folder) => normalizeProjectPathForComparison(folder.path)),60+ );61+ const seen = new Set<string>();62+ const merged: ProjectTrackedFolder[] = [];63+ for (const folder of input.tracked) {64+ const key = normalizeProjectPathForComparison(folder.path);65+ if (seen.has(key) || (scannedKeys.has(key) && !checkedKeys.has(key))) continue;66+ seen.add(key);67+ merged.push(folder);68+ }69+ for (const folder of input.checked) {70+ const key = normalizeProjectPathForComparison(folder.path);71+ if (seen.has(key)) continue;72+ seen.add(key);73+ merged.push({ path: folder.path, name: folder.name });@@ -0,0 +174,21 @@174+ const realRoot = yield* realPath(root);175+ const resolved = yield* Effect.forEach(176+ [177+ ...(listed ?? []).map((folder) => ({ ...folder, source: "code-workspace" as const })),178+ ...children.flat().map((folder) => ({ ...folder, source: "child" as const })),179+ ],180+ (folder) => realPath(folder.path).pipe(Effect.map((real) => ({ folder, real }))),181+ { concurrency: DETECTION_CONCURRENCY },182+ );183+ const seen = new Set<string>();184+ const candidates = resolved.flatMap(({ folder, real }) => {185+ // The scanned folder and its parents are never tracked, however a symlink names them.186+ if (seen.has(real) || isWithinRoot(path, realRoot, real)) return [];187+ seen.add(real);188+ // Submodules follow their parent repository.189+ return submodules.has(path.relative(root, folder.path).split(path.sep).join("/"))190+ ? []191+ : [folder];192+ });193+ const folders = yield* Effect.forEach(194+ candidates.slice(0, PROJECT_TRACKED_FOLDERS_MAX),@@ -1952,3 +1965,12 @@19521965 );19531966 return;19541967 }1968+ // A scan that fails or finds nothing adds the project as a single folder.1969+ const scanResult = await scanTrackedFolders({1970+ environmentId: input.environmentId,1971+ input: { workspaceRoot: cwd },1972+ });1973+ let trackedFolders: ReadonlyArray<ProjectTrackedFolder> = [];1974+ if (scanResult._tag === "Success" && scanResult.value.folders.length > 0) {1975+ const scan = scanResult.value;1976+ const choice = await new Promise<ReadonlyArray<ProjectTrackedFolder> | null>((resolve) =>@@ -410,3 +448,8 @@410448 projectId: input.projectId,411449 workspaceRoot: input.workspaceRoot,412450 });451+ // Moving the project's folder re-checks the folders it keeps tracking.452+ const trackedFolders =453+ input.trackedFolders === undefined && workspaceRoot === previousRoot454+ ? undefined455+ : yield* normalizeTrackedFolders(@@ -500,3 +512,11 @@500512 }501513502514 const title = yield* resolveProjectTitle(workspaceRoot, Option.getOrUndefined(flags.title));515+ const path = yield* Path.Path;516+ // Scanned here, not by a running server: this command runs on the server's machine.517+ const scanned = flags.trackRepos ? (yield* scanFolders({ workspaceRoot })).folders : [];518+ const named = flags.track.map((folder) => {519+ const resolved = path.resolve(folder);520+ return { path: resolved, name: path.basename(resolved) || resolved };521+ });522+ const trackedFolders = [...named, ...scanned]@@ -435,3 +435,7 @@435435 rule("shell", "ask"),436436 rule("edit", policy.runtimeMode === "auto-accept-edits" ? "allow" : "ask"),437437 rule("external_directory", "ask"),438+ // The thread's other folders count as workspace; `edit` still decides whether writes ask.439+ ...(policy.workspace?.extraRoots ?? []).map((root): Rule => ({440+ action: "external_directory",441+ resource: `${root.replace(/\/$/, "")}/*`,
- @@ -1334,7 +1373,16 @@133413731335- setIsSubmitting(true);1336- const result = await createProject(resolved.path);1337- if (result && AsyncResult.isFailure(result)) {1338- setError(errorMessage(Cause.squash(result.cause)));1374+ if (!findExisting(resolved.path)) {1375+ setIsSubmitting(true);1376+ // A scan that fails, or an environment too old to scan, adds the folder alone.1377+ const scan = await scanFolders({1378+ environmentId: environment.environmentId,1379+ input: { workspaceRoot: resolved.path },1380+ });1381+ if (AsyncResult.isSuccess(scan) && scan.value.folders.length > 0) {1382+ setDeselectedPaths(new Set());1383+ setFound({ workspaceRoot: resolved.path, folders: scan.value.folders });1384+ setIsSubmitting(false);1385+ return;1386+ }13391387 }1340- setIsSubmitting(false);1388+ await addProject(resolved.path, []);@@ -500,3 +512,15 @@500512 }501513502514 const title = yield* resolveProjectTitle(workspaceRoot, Option.getOrUndefined(flags.title));515+ const path = yield* Path.Path;516+ // Scanned here, not by a running server: this command runs on the server's machine.517+ const scanned = flags.trackRepos ? (yield* scanFolders({ workspaceRoot })).folders : [];518+ const named = flags.track.map((folder) => {519+ const resolved = path.resolve(folder);520+ return { path: resolved, name: path.basename(resolved) || resolved };521+ });522+ const trackedFolders = [...named, ...scanned]523+ .filter(524+ (folder, index, all) => all.findIndex((other) => other.path === folder.path) === index,525+ )526+ .slice(0, PROJECT_TRACKED_FOLDERS_MAX)@@ -0,0 +106,21 @@106+ return { ...folder, state: (yield* exists(folder.path)) ? "plain" : "missing" };107+ });108+109+ return { exists, realPath, classify };110+});111+112+const readCodeWorkspaceFolders = Effect.fn("WorkspaceFolders.readCodeWorkspaceFolders")(function* (113+ root: string,114+ fileName: string,115+) {116+ const fileSystem = yield* FileSystem.FileSystem;117+ const path = yield* Path.Path;118+ const document = yield* fileSystem119+ .readFileString(path.join(root, fileName))120+ .pipe(Effect.flatMap(decodeCodeWorkspace), Effect.option);121+ if (Option.isNone(document)) return null;122+ return (document.value.folders ?? []).flatMap((folder) => {123+ const folderPath = folder.path?.trim();124+ if (folderPath === undefined || folderPath === "") return [];125+ const resolved = path.resolve(root, folderPath);126+ return [{ path: resolved, name: folder.name?.trim() || path.basename(resolved) }];@@ -0,0 +131,21 @@131+ * Finds the folders worth tracking beside `workspaceRoot`. Exported for the CLI, which scans in132+ * its own process: it runs on the server's machine and may have no server to ask.133+ */134+export const scanFolders = Effect.fn("WorkspaceFolders.scan")(function* (135+ input: WorkspaceScanFoldersInput,136+): Effect.fn.Return<137+ WorkspaceScanFoldersResult,138+ WorkspaceFoldersError,139+ FileSystem.FileSystem | Path.Path140+> {141+ const fileSystem = yield* FileSystem.FileSystem;142+ const path = yield* Path.Path;143+ const { exists, realPath, classify } = yield* folderProbes;144+ const root = path.resolve(145+ expandHomePath(input.workspaceRoot.trim(), yield* HostProcess.HomeDirectory),146+ );147+ const names = (yield* fileSystem148+ .readDirectory(root)149+ .pipe(150+ Effect.mapError(151+ () => new WorkspaceFoldersError({ operation: "scan", detail: `Could not read ${root}.` }),@@ -0,0 +174,21 @@174+ const realRoot = yield* realPath(root);175+ const resolved = yield* Effect.forEach(176+ [177+ ...(listed ?? []).map((folder) => ({ ...folder, source: "code-workspace" as const })),178+ ...children.flat().map((folder) => ({ ...folder, source: "child" as const })),179+ ],180+ (folder) => realPath(folder.path).pipe(Effect.map((real) => ({ folder, real }))),181+ { concurrency: DETECTION_CONCURRENCY },182+ );183+ const seen = new Set<string>();184+ const candidates = resolved.flatMap(({ folder, real }) => {185+ // The scanned folder and its parents are never tracked, however a symlink names them.186+ if (seen.has(real) || isWithinRoot(path, realRoot, real)) return [];187+ seen.add(real);188+ // Submodules follow their parent repository.189+ return submodules.has(path.relative(root, folder.path).split(path.sep).join("/"))190+ ? []191+ : [folder];192+ });193+ const folders = yield* Effect.forEach(194+ candidates.slice(0, PROJECT_TRACKED_FOLDERS_MAX),@@ -1952,3 +1965,13 @@19521965 );19531966 return;19541967 }1968+ // A scan that fails or finds nothing adds the project as a single folder.1969+ const scanResult = await scanTrackedFolders({1970+ environmentId: input.environmentId,1971+ input: { workspaceRoot: cwd },1972+ });1973+ let trackedFolders: ReadonlyArray<ProjectTrackedFolder> = [];1974+ if (scanResult._tag === "Success" && scanResult.value.folders.length > 0) {1975+ const scan = scanResult.value;1976+ const choice = await new Promise<ReadonlyArray<ProjectTrackedFolder> | null>((resolve) =>1977+ setTrackedFoldersRequest({ scan, resolve }),@@ -0,0 +176,21 @@176+ disabled={disabled || isScanning || !access.canReadFiles}177+ onClick={() => void runRescan()}178+ >179+ {isScanning ? "Scanning…" : "Rescan"}180+ </Button>181+ <Button182+ size="xs"183+ variant="outline"184+ disabled={disabled || tracked.length >= PROJECT_TRACKED_FOLDERS_MAX}185+ onClick={() => setIsAddingFolder(true)}186+ >187+ <PlusIcon className="size-3.5" />188+ Add folder189+ </Button>190+ </div>191+ }192+ />193+ {tracked.length === 0 ? (194+ <p className="px-3 py-2 text-base text-muted-foreground sm:px-4 sm:text-sm">195+ Track a repository to give it its own changes and review, and to let agents work across it196+ and this folder.@@ -0,0 +53,21 @@53+ readonly checked: ReadonlyArray<WorkspaceScannedFolder>;54+}): ReadonlyArray<ProjectTrackedFolder> {55+ const scannedKeys = new Set(56+ input.scanned.map((folder) => normalizeProjectPathForComparison(folder.path)),57+ );58+ const checkedKeys = new Set(59+ input.checked.map((folder) => normalizeProjectPathForComparison(folder.path)),60+ );61+ const seen = new Set<string>();62+ const merged: ProjectTrackedFolder[] = [];63+ for (const folder of input.tracked) {64+ const key = normalizeProjectPathForComparison(folder.path);65+ if (seen.has(key) || (scannedKeys.has(key) && !checkedKeys.has(key))) continue;66+ seen.add(key);67+ merged.push(folder);68+ }69+ for (const folder of input.checked) {70+ const key = normalizeProjectPathForComparison(folder.path);71+ if (seen.has(key)) continue;72+ seen.add(key);73+ merged.push({ path: folder.path, name: folder.name });@@ -0,0 +76,21 @@76+ if (!next.delete(path)) next.add(path);77+ setCheckedPaths(next);78+ };79+80+ return (81+ <Dialog82+ open83+ onOpenChange={(open) => {84+ if (!open) props.onClose();85+ }}86+ >87+ <DialogPopup>88+ <DialogHeader>89+ <DialogTitle>Repositories in {folderName}</DialogTitle>90+ <DialogDescription>91+ Found {scan.folders.length} {noun}92+ {scan.codeWorkspaceFile93+ ? `, including the ones ${fileBasename(scan.codeWorkspaceFile)} lists`94+ : ""}95+ . Tracked repositories get their own changes and review, and agents can work across96+ them.@@ -2162,3 +2164,8 @@2162216421632165 const sessionSetupFields = (initializeResult: EffectAcpSchema.InitializeResponse) => {21642166 const meta = options.sessionMeta?.(initializeResult);2167+ const additionalDirectories = [2168+ ...(options.additionalDirectories ?? []),2169+ ...(initializeResult.agentCapabilities?.sessionCapabilities?.additionalDirectories == null2170+ ? []2171+ : (options.extraRoots ?? [])),@@ -2428,3 +2429,6 @@24282429 return {24292430 cwd: input.runtimePolicy.cwd ?? process.cwd(),24302431 runtimePolicy: input.runtimePolicy,2432+ ...(input.runtimePolicy.workspace === undefined2433+ ? {}2434+ : { extraRoots: input.runtimePolicy.workspace.extraRoots }),@@ -319,3 +319,6 @@319319 ...(input.apiKey === undefined ? {} : { apiKey: input.apiKey }),320320 local: {321321 ...(input.runtimePolicy.cwd === null ? {} : { cwd: input.runtimePolicy.cwd }),322+ ...(input.runtimePolicy.workspace === undefined323+ ? {}324+ : { dirs: [...input.runtimePolicy.workspace.extraRoots] }),@@ -683,3 +683,8 @@683683 }684684 }685685686+ // The thread's other folders count as workspace; `edit` still decides whether writes ask.687+ for (const root of runtimePolicy.workspace?.extraRoots ?? []) {688+ rules.push({689+ permission: "external_directory",690+ pattern: `${root.replace(/\/$/, "")}/*`,
- @@ -1367,8 +1385,18 @@13671385 AuthOrchestrationOperateScope,13681386 );13691387 const navigation = useNavigation();1370- const createProject = useCreateProject(environment);1388+ const { createProject, findExisting } = useCreateProject(environment);1389+ const scanFolders = useAtomQueryRunner(filesystemEnvironment.scanFolders, {1390+ reportFailure: false,1391+ reportDefect: false,1392+ refresh: true,1393+ });13711394 const { isBrowseNavigating, navigateToBrowsePath, pathInput, setPathInput, resolveHomePath } =13721395 useBrowsePathInput(environment);13731396 const [isSubmitting, setIsSubmitting] = useState(false);13741397 const [error, setError] = useState<string | null>(null);1398+ const [found, setFound] = useState<{1399+ readonly workspaceRoot: string;1400+ readonly lookupPath: string;1401+ readonly folders: ReadonlyArray<WorkspaceScannedFolder>;1402+ } | null>(null);@@ -259,3 +264,17 @@259264 detail: `${workspaceRoot} holds a repository's worktrees but is not a checkout itself. Add one of its worktrees as the project instead.`,260265 });261266 });267+ // A folder may be missing from disk: it shows as missing until it is restored or removed.268+ const normalizeTrackedFolders = (269+ projectId: ProjectId,270+ workspaceRoot: string,271+ folders: ReadonlyArray<ProjectTrackedFolder>,272+ ) => {273+ const invalid = (detail: string) => Effect.fail(new ProjectInvalidError({ projectId, detail }));274+ const normalized: Array<ProjectTrackedFolder> = [];275+ for (const folder of folders) {276+ if (!path.isAbsolute(folder.path)) {277+ return invalid(`Tracked folder '${folder.path}' must be an absolute path.`);278+ }279+ const folderPath = path.resolve(folder.path);280+ if (isWithinRoot(path, workspaceRoot, folderPath)) {@@ -430,3 +467,11 @@430467 if (workspaceRoot !== previousRoot) {431468 yield* rejectWorktreeContainer(input.projectId, workspaceRoot);432469 }470+ // Moving the project's folder re-checks the folders it keeps tracking.471+ const trackedFolders =472+ input.trackedFolders === undefined && workspaceRoot === previousRoot473+ ? undefined474+ : yield* normalizeTrackedFolders(475+ input.projectId,476+ workspaceRoot,477+ input.trackedFolders ?? existing.value.trackedFolders,@@ -440,3 +440,7 @@440440 rule("shell", "ask"),441441 rule("edit", policy.runtimeMode === "auto-accept-edits" ? "allow" : "ask"),442442 rule("external_directory", "ask"),443+ // The thread's other folders count as workspace; `edit` still decides whether writes ask.444+ ...(policy.workspace?.extraRoots ?? []).map((root): Rule => ({445+ action: "external_directory",446+ resource: `${root.replace(/\/$/, "")}/*`,
juliusmarminge closed this
Sign in to join this conversation.


This PR changes the test suite by +21 test cases (browser 0, unit +14, server +7).
Keep tests that would fail for a real reason, and test logic below the UI where it can be. See Testing.