feat(projects): a project covers several repositories #35925
Mergedjuliusmarmingemerged 35 commits into
main fromrefs/pull/35925/headmerged by juliusmarminge View on GitHubjuliusmarminge 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
- @@ -1168,0 +1275,21 @@1275+ if (1276+ (pathKey(cwd) === pathKey(guardedPath) || inside(guardedPath, cwd)) &&1277+ (yield* providerSessions.isLive(session.id))1278+ )1279+ return waitForStop("provider session is still open");1280+ }1281+ return null;1282+ });1283+ if (taskFolder !== null) {1284+ // Merged and unchanged compare one branch with one default branch; a task folder has1285+ // a repository per folder, so only age, settling and deletion remove it.1286+ if (!eligible) return keep(notDueReason);1287+ const blockedTaskFolder = yield* blockedSinceCheck();1288+ if (blockedTaskFolder !== null) return keep(blockedTaskFolder);1289+ return yield* withWorkspaceLease(1290+ worktreePath,1291+ Effect.gen(function* () {1292+ const blockedSinceLease = yield* blockedSinceCheck();1293+ if (blockedSinceLease !== null) return keep(blockedSinceLease);1294+ // Each checkout passes the checks a single worktree does, or it stays.1295+ const result = yield* taskFolders.remove({@@ -745,0 +757,21 @@757+ const preRewindRef = yield* scopeRef(target.scope.id, "pre-rewind").pipe(758+ Effect.provideService(Digest.Digest, crypto),759+ );760+ yield* checkpointStore.captureCheckpoint({761+ ...folder,762+ checkpointRef: preRewindRef,763+ });764+ snapshots.push({ ...folder, checkpointRef: preRewindRef });765+ // What this process knew of the folder no longer holds.766+ repositoryStates.delete(target.scope.id);767+ const restored = yield* checkpointStore.restoreCheckpoint({768+ ...folder,769+ checkpointRef: target.checkpoint.ref,770+ fallbackToHead: false,771+ });772+ if (!restored) return yield* Effect.fail("Checkpoint ref is unavailable.");773+ }),774+ ).pipe(Effect.catch((cause) => Effect.flip(failed(target, cause)))),775+ { discard: true },776+ ).pipe(777+ Effect.onError(() =>@@ -1168,0 +1283,21 @@1283+ if (taskFolder !== null) {1284+ // Merged and unchanged compare one branch with one default branch; a task folder has1285+ // a repository per folder, so only age, settling and deletion remove it.1286+ if (!eligible) return keep(notDueReason);1287+ const blockedTaskFolder = yield* blockedSinceCheck();1288+ if (blockedTaskFolder !== null) return keep(blockedTaskFolder);1289+ return yield* withWorkspaceLease(1290+ worktreePath,1291+ Effect.gen(function* () {1292+ const blockedSinceLease = yield* blockedSinceCheck();1293+ if (blockedSinceLease !== null) return keep(blockedSinceLease);1294+ // Each checkout passes the checks a single worktree does, or it stays.1295+ const result = yield* taskFolders.remove({1296+ root: taskFolder.root,1297+ force: false,1298+ forget: deleted,1299+ inspect: (checkout) =>1300+ inspectCheckout(checkout.worktreePath, thread.branch, settings),1301+ });1302+ for (const removedPath of result.removed)1303+ entries.push({@@ -228,4 +242,4 @@228242 let worktreeBaseRef = baseRef;229243 let baseRefName = baseRef;230244 let startedFromOrigin = false;231- if (startFromOrigin) {245+ if (startFromOrigin && projectIsRepository) {@@ -745,0 +740,21 @@740+ .hasCheckpointRef({ cwd: target.scope.cwd, checkpointRef: target.checkpoint.ref })741+ .pipe(Effect.catch((cause) => Effect.flip(failed(target, cause))));742+ if (!exists) return yield* Effect.flip(failed(target, "Checkpoint ref is unavailable."));743+ }744+ const nested = yield* resolveNestedScopePaths(input.scopes);745+ const snapshots: Array<Omit<CheckpointStore.RestoreCheckpointInput, "fallbackToHead">> = [];746+ yield* Effect.forEach(747+ input.targets,748+ (target) =>749+ withWorkspaceLock(750+ target.scope.cwd,751+ Effect.gen(function* () {752+ const excludePaths = nested.get(target.scope.id);753+ const folder = {754+ cwd: target.scope.cwd,755+ ...(excludePaths === undefined ? {} : { excludePaths }),756+ };757+ const preRewindRef = yield* scopeRef(target.scope.id, "pre-rewind").pipe(758+ Effect.provideService(Digest.Digest, crypto),759+ );760+ yield* checkpointStore.captureCheckpoint({@@ -0,0 +404,21 @@404+ detail:405+ "The worktree location must be an absolute folder on this machine, not a drive root. Change it in Settings → Worktrees.",406+ });407+ }408+ const hash = yield* digest.digest(409+ Digest.sha256,410+ new TextEncoder().encode(`${taskPlan.projectId}\0${taskPlan.anchor}\0${branch}`),411+ );412+ // UTF-8 bytes bound UTF-16 length too, leaving room for files on Windows.413+ let prefix = "";414+ for (const character of branch.replace(/\//g, "-")) {415+ if (Buffer.byteLength(prefix + character) > 23) break;416+ prefix += character;417+ }418+ const base = path.join(419+ parent,420+ path.basename(taskPlan.anchor) || "workspace",421+ `${prefix}-${Hex.encode(hash).slice(0, 16)}`,422+ );423+ let root = base;424+ for (let suffix = 2; yield* exists(root); suffix++) root = `${base}-${suffix}`;@@ -0,0 +639,21 @@639+ Effect.suspend(() => {640+ created.push(worktree);641+ return (642+ input.onRepository?.({643+ name: repository.name,644+ done: created.length,645+ total: taskPlan.repositories.length,646+ }) ?? Effect.void647+ );648+ }),649+ ),650+ Effect.mapError(fail("create", `Could not create the ${repository.name} worktree`)),651+ Effect.exit,652+ ),653+ { concurrency: REPOSITORY_CONCURRENCY },654+ ).pipe(Effect.uninterruptible);655+ const failed = exits.find(Exit.isFailure);656+ if (failed !== undefined) return yield* Effect.failCause(failed.cause);657+ }658+ const taskFolder = current();659+ yield* store.put(taskFolder);@@ -0,0 +887,21 @@887+ recreate,888+ }) {889+ const restoreFailed = fail("create", "Could not restore the worktrees");890+ const recreateMissing = Effect.fnUntraced(function* (checkout: TaskFolderCheckout) {891+ if (yield* isRepository(checkout.worktreePath)) return;892+ yield* fileSystem893+ .makeDirectory(path.dirname(checkout.worktreePath), { recursive: true })894+ .pipe(Effect.mapError(restoreFailed));895+ yield* recreate(checkout);896+ });897+ if (taskFolder.projectIsWorktree) {898+ yield* recreateMissing({899+ worktreePath: taskFolder.projectPath,900+ repositoryPath: taskFolder.projectRoot,901+ });902+ } else if (!(yield* exists(taskFolder.projectPath))) {903+ const project = yield* readProject("create", taskFolder.projectId);904+ const tracked = yield* Effect.filter(905+ project.trackedFolders.map((folder) => path.resolve(folder.path)),906+ isRepository,907+ );@@ -0,0 +177,21 @@177+ const digest = yield* Digest.Digest;178+ const config = yield* ServerConfig.ServerConfig;179+ const settings = yield* ServerSettings.ServerSettingsService;180+ const projects = yield* ProjectStore.ProjectStoreV2;181+ const git = yield* GitWorkflowService.GitWorkflowService;182+ const gitDriver = yield* GitVcsDriver.GitVcsDriver;183+ const store = yield* TaskFolderStore.TaskFolderStore;184+ const projections = yield* ProjectionStore.ProjectionStoreV2;185+186+ const exists = (target: string) =>187+ fileSystem.exists(target).pipe(Effect.orElseSucceed(() => false));188+ const isRepository = (folder: string) => exists(path.join(folder, ".git"));189+ const fail =190+ (operation: TaskFolderError["operation"], prefix: string) =>191+ (cause: unknown): TaskFolderError =>192+ new TaskFolderError({ operation, detail: `${prefix}: ${failureDetail(cause)}`, cause });193+194+ const commonAncestor = (folders: ReadonlyArray<string>) => {195+ let ancestor = folders[0]!;196+ for (const folder of folders.slice(1)) {197+ while (!isWithinRoot(path, folder, ancestor)) ancestor = path.dirname(ancestor);@@ -0,0 +882,21 @@882+ return { branch };883+ });884+885+ const restore: TaskFolders["Service"]["restore"] = Effect.fn("TaskFolders.restore")(function* ({886+ taskFolder,887+ recreate,888+ }) {889+ const restoreFailed = fail("create", "Could not restore the worktrees");890+ const recreateMissing = Effect.fnUntraced(function* (checkout: TaskFolderCheckout) {891+ if (yield* isRepository(checkout.worktreePath)) return;892+ yield* fileSystem893+ .makeDirectory(path.dirname(checkout.worktreePath), { recursive: true })894+ .pipe(Effect.mapError(restoreFailed));895+ yield* recreate(checkout);896+ });897+ if (taskFolder.projectIsWorktree) {898+ yield* recreateMissing({899+ worktreePath: taskFolder.projectPath,900+ repositoryPath: taskFolder.projectRoot,901+ });902+ } else if (!(yield* exists(taskFolder.projectPath))) {@@ -104,3 +106,7 @@104106 const activeThreadRef = { environmentId: props.environmentId, threadId: props.threadId };105107 const project = useProject(scopeProjectRef(props.environmentId, props.projectId));106108 const serverConfig = useServerConfigs().get(props.environmentId);109+ const tracksFolders = (project?.trackedFolders?.length ?? 0) > 0;110+ // A worktree thread reaches tracked repositories only through its own task folder.111+ const taskFolderQuery = useEnvironmentQuery(112+ props.isServerThread && props.worktreePath !== null && tracksFolders@@ -0,0 +24,21 @@24+ * no folders asks the server nothing.25+ */26+export function useWorktreeRepositoryChoices(27+ project: Pick<28+ EnvironmentProject,29+ "environmentId" | "id" | "workspaceRoot" | "trackedFolders"30+ > | null,31+): WorktreeRepositoryChoices {32+ const tracksFolders = (project?.trackedFolders?.length ?? 0) > 0;33+ const folders = useEnvironmentQuery(34+ project !== null && tracksFolders35+ ? filesystemEnvironment.listFolders({36+ environmentId: project.environmentId,37+ input: { projectId: project.id },38+ })39+ : null,40+ );41+ if (project === null || !tracksFolders) return NO_TRACKED_FOLDERS;42+ if (folders.data === null) {43+ // Until the folders arrive the tracked list stands in, as the checkout's Git state does.44+ return { choices: null, tracksGitRepositories: folders.error === null };@@ -1473,2 +1481,21 @@14731481 export type OrchestrationV2Checkpoint = typeof OrchestrationV2Checkpoint.Type;147414821483+/**1484+ * The checkpoint a file rewind to run `targetOrdinal` restores a tracked repository to, given that1485+ * repository scope's checkpoints. Its records are sparse: the first snapshot at or after the1486+ * target is the target's own, or the baseline taken before the first later run that changed the1487+ * repository. Null when no later run changed it, or when that state was never snapshotted.1488+ */1489+export function repositoryRewindCheckpoint<1490+ Checkpoint extends Pick<OrchestrationV2Checkpoint, "ordinalWithinScope" | "runId" | "status">,1491+>(checkpoints: ReadonlyArray<Checkpoint>, targetOrdinal: number): Checkpoint | null {1492+ let first: Checkpoint | undefined;1493+ for (const checkpoint of checkpoints) {1494+ if (checkpoint.status !== "ready" || checkpoint.ordinalWithinScope < targetOrdinal) continue;1495+ if (first === undefined || checkpoint.ordinalWithinScope < first.ordinalWithinScope)1496+ first = checkpoint;1497+ }1498+ // A later run's own checkpoint holds that run's changes, not the state before them.1499+ return first !== undefined && (first.ordinalWithinScope === targetOrdinal || first.runId === null)1500+ ? first1501+ : null;
- @@ -342,4 +409,5 @@342409 target: rollbackTarget,343410 providerThreadTurns,344411 });345- if (input.restoreFiles !== false) yield* checkpoints.restore({ scope, checkpoint });412+ if (restoreFiles) {413+ yield* checkpoints.restore({ targets: restoreTargets, scopes: [scope, ...repositories] });
- @@ -459,0 +561,21 @@561+ ? []562+ : [{ repositoryPath: folder.path, name: folder.name }],563+ );564+}565+566+/** A tracked Git repository a new worktree thread can get a worktree of. */567+export interface WorktreeRepositoryChoice {568+ /** The tracked folder's path; what `workspaceStrategy.repositories[].path` takes. */569+ readonly repositoryPath: string;570+ readonly name: string;571+ /** The folder from the project folder, `/`-separated, when it sits inside it. */572+ readonly relativePath?: string;573+}574+575+/** A project's tracked Git folders, in the project's order. */576+export function worktreeRepositoryChoices(input: {577+ readonly folders: ReadonlyArray<Pick<WorkspaceFolder, "path" | "name" | "state">>;578+ readonly projectRoot: string;579+}): ReadonlyArray<WorktreeRepositoryChoice> {580+ return input.folders.flatMap((folder) => {581+ if (folder.state !== "git") return [];@@ -0,0 +537,21 @@537+ worktreePath: projectPath,538+ repositoryPath: taskFolder.projectRoot,539+ });540+ }541+ } else {542+ projectGone = yield* removeLinks(projectPath).pipe(Effect.orElseSucceed(() => false));543+ if (!projectGone && !projectHoldsKept && input.force && input.inspect === undefined) {544+ // Forced: what is left are files the thread wrote beside the links.545+ projectGone = yield* fileSystem.remove(projectPath, { recursive: true, force: true }).pipe(546+ Effect.as(true),547+ Effect.orElseSucceed(() => false),548+ );549+ }550+ if (projectGone) removed.push(projectPath);551+ else if (!projectHoldsKept)552+ kept.push({ path: projectPath, reason: "has files that exist only in this folder" });553+ }554+ if (kept.length === 0) {555+ yield* removeLinks(taskFolder.root).pipe(Effect.ignore);556+ if (input.forget) yield* store.remove(taskFolder.root);557+ }
- @@ -431,8 +447,8 @@431447 : null,432448 );433449 const branchCommitsQuery = useEnvironmentQuery(434- visible && isGitRepo && canReadFiles && activeThread && activeCwd450+ visible && isGitRepo && canReadFiles && activeThread && gitCwd435451 ? reviewEnvironment.branchCommits({436452 environmentId: activeThread.environmentId,437453 input: {438- cwd: activeCwd,454+ cwd: gitCwd,@@ -93,4 +94,5 @@9394 // After every project folder: most tracked folders sit inside one and need no lookup.9495 for (const project of projects) {9596 for (const folder of project.trackedFolders ?? []) {96- if (within(yield* resolveRoot(folder.path))) return true;97+ if (isTrackedFolderRule(folder.path)) {98+ if (trackedFolderCovers(path.resolve(folder.path), realPath)) return true;@@ -152,5 +163,14 @@152163 const saveRescan = async (153164 scan: WorkspaceScanFoldersResult,154165 checked: ReadonlyArray<WorkspaceScannedFolder>,166+ follow: boolean,155167 ) => {156- const next = mergeScannedTrackedFolders({ tracked, scanned: scan.folders, checked });168+ // Following replaces the scanned folders' own entries with the rules that cover them.169+ const next = follow170+ ? [171+ ...mergeScannedTrackedFolders({ tracked, scanned: scan.folders, checked: [] }).filter(172+ (folder) => !isTrackedFolderRule(folder.path),173+ ),174+ ...followedTrackedFolders({ workspaceRoot: scan.workspaceRoot, scanned: checked }),175+ ]176+ : mergeScannedTrackedFolders({ tracked, scanned: scan.folders, checked });@@ -1085,3 +1109,18 @@10851109 )}10861110 </DropdownMenuContent>10871111 </DropdownMenu>1112+ {isGitSelection && gitRepositories.length > 0 && (1113+ <DropdownMenu>1114+ <DropdownMenuTrigger1115+ render={<Button size="xs" variant="ghost-muted" />}1116+ className="min-w-14 max-w-48 shrink"1117+ aria-label={`Repository: ${gitRepository?.name ?? threadFolderName}`}1118+ >1119+ <span className="truncate">{gitRepository?.name ?? threadFolderName}</span>1120+ <ChevronDownIcon className="size-3.5 shrink-0 opacity-70" />1121+ </DropdownMenuTrigger>1122+ <DropdownMenuContent align="start" className="max-h-80 max-w-72">1123+ <DropdownMenuRadioGroup1124+ value={gitRepository?.repositoryPath ?? THREAD_FOLDER}1125+ onValueChange={(value) =>1126+ setGitRepositoryPath(value === THREAD_FOLDER ? null : value)
- @@ -0,0 +1016,21 @@1016+ { discard: true },1017+ ),1018+ ),1019+ Effect.mapError(renameFailed),1020+ );1021+ return { branch };1022+ });1023+1024+ const restore: TaskFolders["Service"]["restore"] = Effect.fn("TaskFolders.restore")(function* ({1025+ taskFolder,1026+ recreate,1027+ }) {1028+ const restoreFailed = fail("create", "Could not restore the worktrees");1029+ const recreateMissing = Effect.fnUntraced(function* (checkout: TaskFolderCheckout) {1030+ if (yield* isRepository(checkout.worktreePath)) return;1031+ yield* fileSystem1032+ .makeDirectory(path.dirname(checkout.worktreePath), { recursive: true })1033+ .pipe(Effect.mapError(restoreFailed));1034+ yield* recreate(checkout);1035+ });1036+ if (taskFolder.projectIsWorktree) {@@ -0,0 +710,21 @@710+ return yield* Effect.gen(function* () {711+ yield* fileSystem.makeDirectory(root, { recursive: true });712+ // Recorded before any checkout, so an interrupted creation is still found and removed.713+ yield* store.put(empty);714+ if (input.onClaimed !== undefined) yield* input.onClaimed(empty, branch);715+ const layout = yield* worktreeLayout(taskPlan.projectRoot);716+ if (layout !== null) {717+ yield* runLayoutCommand("create", layout.create, empty, branch, input.baseBranch);718+ if (!(yield* exists(empty.projectPath))) {719+ return yield* new TaskFolderError({720+ operation: "create",721+ detail: `The project's worktree layout command left no folder at ${empty.projectPath}.`,722+ });723+ }724+ // Whatever the command checked out where a tracked repository belongs is the thread's.725+ for (const repositoryPath of taskPlan.trackedRepositories) {726+ const worktreePath = mapped(empty, repositoryPath);727+ if (yield* isRepository(worktreePath)) {728+ created.push({ repositoryPath, worktreePath, name: path.basename(repositoryPath) });729+ }730+ }@@ -392,0 +439,21 @@439+ readonly folders: ReadonlyArray<Pick<WorkspaceFolder, "path" | "name" | "state">> | null;440+ readonly threadCwd: string | null;441+}): ReadonlyArray<ThreadGitRepository> {442+ const reached: ReadonlyArray<ThreadGitRepository> =443+ input.taskFolder !== null444+ ? input.taskFolder.repositories.map((repository) => ({445+ repositoryPath: repository.repositoryPath,446+ name: repository.name,447+ cwd: repository.worktreePath,448+ }))449+ : (input.folders ?? []).flatMap((folder) =>450+ folder.state === "git" && folder.path !== input.threadCwd451+ ? [{ repositoryPath: folder.path, name: folder.name, cwd: folder.path }]452+ : [],453+ );454+ if (reached.length === 0) return input.changed;455+ const listed = new Set(input.changed.map((repository) => repository.repositoryPath));456+ return [457+ ...input.changed,458+ ...reached.filter((repository) => !listed.has(repository.repositoryPath)),459+ ];
- @@ -216,3 +221,13 @@216221 deletedAt: row.deletedAt,217222 });218223224+ // Clients read `trackedFolders` off the project, so the stored list is brought back in step225+ // with the disk when a project is read, at most this often. Server work reads the disk itself.226+ const folderSyncDue = new Map<ProjectId, number>();227+ const syncFolders = Effect.fn("ProjectService.syncFolders")(function* (228+ row: ProjectStore.ProjectRow,229+ ) {230+ const now = yield* Clock.currentTimeMillis;231+ if ((folderSyncDue.get(row.projectId) ?? 0) > now) return;232+ folderSyncDue.set(row.projectId, now + FOLDER_SYNC_INTERVAL_MS);233+ const trackedFolders = yield* withDiscovered(row.workspaceRoot, row.trackedFolders);@@ -225,0 +295,21 @@295+296+/**297+ * Every folder a project works in besides its own: the repositories found inside it now, then298+ * the folders someone added. Read from disk each time, so a clone or a removal shows at once.299+ */300+export const projectFolders = Effect.fn("WorkspaceFolders.projectFolders")(function* (project: {301+ readonly workspaceRoot: string;302+ readonly trackedFolders: ReadonlyArray<ProjectTrackedFolder>;303+}): Effect.fn.Return<304+ ReadonlyArray<ProjectTrackedFolder>,305+ never,306+ FileSystem.FileSystem | Path.Path307+> {308+ const discovered = yield* discoverFolders(project.workspaceRoot);309+ const found = new Set(discovered.map((folder) => folder.path));310+ return [311+ ...discovered,312+ ...project.trackedFolders.filter(313+ (folder) => folder.discovered !== true && !found.has(folder.path),314+ ),315+ ].slice(0, PROJECT_TRACKED_FOLDERS_MAX);
- @@ -0,0 +910,21 @@910+ (current) =>911+ resolveProjectSettings(current, projectId).settings.newWorktreesStartFromOrigin,912+ ),913+ );914+915+ const createForProjectFolder: TaskFolders["Service"]["createForProjectFolder"] = Effect.fn(916+ "TaskFolders.createForProjectFolder",917+ )(function* (input) {918+ if (input.path !== null || input.newRefName === undefined) return null;919+ const project = yield* projects920+ .findActiveByWorkspaceRoot(input.cwd)921+ .pipe(Effect.mapError(fail("plan", "Could not read the project")));922+ if (Option.isNone(project)) return null;923+ const { projectId } = project.value;924+ const taskPlan = yield* plan({ projectId });925+ if (taskPlan === null) return null;926+ const { taskFolder, branch } = yield* create({927+ plan: taskPlan,928+ branch: input.newRefName,929+ projectStart: { refName: input.refName, baseRefName: input.baseRefName ?? input.refName },930+ startFromOrigin: yield* startsFromOrigin("create", projectId),
Pushed9b45bdd
- @@ -4154,4 +4173,6 @@4154417341554174 <RevertConfirmHost41564175 threadKey={routeThreadKey}4157- checkpoints={serverProjection?.checkpoints}4176+ environmentId={environmentId}4177+ taskFolderPath={4178+ (activeProject?.trackedFolders?.length ?? 0) > 0 ? activeThreadWorktreePath : null
Pushed427c534
- @@ -0,0 +87,21 @@87+ if (!isAtomCommandInterrupted(result)) {88+ const error = squashAtomCommandFailure(result);89+ Dialog.alert(90+ gt("Failed to update repositories"),91+ error instanceof Error ? error.message : gt("An error occurred."),92+ );93+ }94+ return;95+ }96+ listQuery.refresh();97+ };98+99+ const remove = (folder: ProjectTrackedFolder) =>100+ Dialog.confirm({101+ title: gt("Remove folder"),102+ message: gt("Agents in this project stop working in {name}. Files on disk are not touched.", {103+ name: folder.name,104+ }),105+ confirmText: gt("Remove", { $context: "verb, removes a folder from the project" }),106+ destructive: true,107+ onConfirm: () => void save(added.filter((entry) => entry.path !== folder.path)),@@ -255,0 +266,21 @@266+ readonly taskFolder: string | null;267+ },268+ GitCommandError | TaskFolderError269+ > =>270+ taskPlan === null271+ ? gitWorkflow272+ .createWorktree({273+ cwd: projectCwd,274+ refName: worktreeBaseRef,275+ newRefName: input.branch,276+ baseRefName,277+ path: null,278+ })279+ .pipe(Effect.map((created) => ({ ...created.worktree, taskFolder: null })))280+ : taskFolders281+ .create({282+ plan: taskPlan,283+ branch: input.branch,284+ projectStart: { refName: worktreeBaseRef, baseRefName },285+ baseBranch: input.baseRef,286+ startFromOrigin,@@ -302,3 +333,12 @@302333303334 if (restoreFiles && !(yield* isolated)) return yield* sharedWorkspace();304335336+ // Before the provider conversation changes: a rewind with nothing to restore is refused.337+ const repositories =338+ restoreFiles && taskFolder !== null339+ ? yield* checkpoints.repositoryScopes({340+ rootScope: scope,341+ projectId: context.thread.projectId,342+ worktreePath,343+ })344+ : [];@@ -561,0 +800,21 @@800+ // A snapshot that could not be put back is the only copy of the folder's pre-rewind state.801+ const unrecovered = new Set<string>();802+ yield* Effect.forEach(803+ input.targets,804+ (target) =>805+ withWorkspaceLock(806+ target.scope.cwd,807+ Effect.gen(function* () {808+ const excludePaths = nested.get(target.scope.id);809+ const folder = {810+ cwd: target.scope.cwd,811+ ...(excludePaths === undefined ? {} : { excludePaths }),812+ };813+ const preRewindRef = yield* scopeRef(target.scope.id, "pre-rewind").pipe(814+ Effect.provideService(Digest.Digest, crypto),815+ );816+ // One an earlier failed rewind left is still the only copy of how the folder was.817+ const kept = yield* checkpointStore.hasCheckpointRef({818+ cwd: target.scope.cwd,819+ checkpointRef: preRewindRef,820+ });@@ -561,0 +824,21 @@824+ checkpointRef: preRewindRef,825+ });826+ }827+ snapshots.push({ ...folder, checkpointRef: preRewindRef });828+ // What this process knew of the folder no longer holds.829+ repositoryStates.delete(target.scope.id);830+ const restored = yield* checkpointStore.restoreCheckpoint({831+ ...folder,832+ checkpointRef: target.checkpoint.ref,833+ fallbackToHead: false,834+ });835+ if (!restored) return yield* Effect.fail("Checkpoint ref is unavailable.");836+ }),837+ ).pipe(Effect.catch((cause) => Effect.flip(failed(target, cause)))),838+ { discard: true },839+ ).pipe(840+ Effect.onError(() =>841+ Effect.forEach(842+ snapshots.toReversed(),843+ (snapshot) =>844+ withWorkspaceLock(snapshot.cwd, checkpointStore.restoreCheckpoint(snapshot)).pipe(@@ -570,4 +977,17 @@570- scopeId: input.scope.id,571- checkpointId: input.checkpoint.id,572- cause: "Checkpoint ref is unavailable.",573- });977+ const baselineExists = yield* checkpointStore978+ .hasCheckpointRef({ cwd, checkpointRef: baselineRef })979+ .pipe(Effect.orElseSucceed(() => false));980+ if (!baselineExists) {981+ // The turn started on a clean folder; its snapshot was left until one was needed.982+ if (known !== undefined && cleanAtStart !== null) {983+ yield* checkpointStore984+ .captureHeadCheckpoint({985+ cwd,986+ checkpointRef: baselineRef,987+ head: cleanAtStart,988+ seenAt: known.seenAt,989+ })990+ .pipe(Effect.ignore);991+ } else if (cleanHead !== null) {992+ // How the turn started is unknown and nothing is uncommitted: nothing to show.993+ return unchanged;@@ -1143,0 +1146,21 @@1146+ // The checks a single worktree passes before removal, for one checkout of a task folder.1147+ const inspectCheckout = Effect.fn("StorageCleanup.inspectCheckout")(1148+ function* (1149+ checkoutPath: string,1150+ branch: string | null,1151+ rules: WorktreeCleanupRules,1152+ settingsChanged: Effect.Effect<boolean, ServerSettingsError>,1153+ ) {1154+ const reason =1155+ (yield* worktreePathReason(checkoutPath)) ??1156+ ((yield* branchChanged(checkoutPath, branch)) ? "repository or branch changed" : null) ??1157+ (yield* localChangesReason(checkoutPath, rules));1158+ if (reason !== null) return { keep: reason, force: false, bytes: null };1159+ const { bytes, reason: measureReason } = yield* measureWorktree(checkoutPath, true);1160+ if (measureReason !== null) return { keep: measureReason, force: false, bytes };1161+ // Measuring takes time, and what follows deletes ignored files under these rules.1162+ if (yield* settingsChanged)1163+ return { keep: "settings changed since check", force: false, bytes };1164+ if (rules.worktreeKeepWhen === "tracked-changes")1165+ yield* cleanupGit(checkoutPath, ["clean", "-ffdx"], "git clean");1166+ const submodules = yield* submoduleRemoval(checkoutPath, rules);@@ -0,0 +370,21 @@370+ const projectRoot = path.resolve(project.workspaceRoot);371+ const classified = yield* Effect.forEach(372+ yield* trackedFolders(project),373+ (folder) => {374+ const folderPath = path.resolve(folder.path);375+ return Effect.all([isRepository(folderPath), isSubmodule(folderPath)]).pipe(376+ Effect.map(([git, submodule]) => ({377+ name: folder.name,378+ path: folderPath,379+ git,380+ submodule,381+ })),382+ );383+ },384+ { concurrency: 8 },385+ );386+ const tracked = classified.filter(387+ (folder) => folder.git && !folder.submodule && folder.path !== projectRoot,388+ );389+ // A project that lays its own thread folder out gets one even with nothing else to check out.390+ if (tracked.length === 0 && (yield* worktreeLayout(projectRoot)) === null) return null;@@ -0,0 +672,21 @@672+ ...taskFolder.repositories,673+ ...(taskFolder.projectIsWorktree674+ ? [{ worktreePath: taskFolder.projectPath, repositoryPath: taskFolder.projectRoot }]675+ : []),676+ ];677+ let allGo = true;678+ for (const checkout of checkouts) {679+ if (!(yield* exists(checkout.worktreePath))) continue;680+ if ((yield* verdict(checkout)).keep === null) continue;681+ allGo = false;682+ break;683+ }684+ if (allGo) {685+ yield* runLayoutCommand(686+ "remove",687+ layout.remove,688+ taskFolder,689+ input.deleteBranch ?? "",690+ undefined,691+ taskFolder.repositories.map((repository) => repository.repositoryPath),692+ ).pipe(Effect.ignoreCause({ log: true }));@@ -0,0 +733,21 @@733+ if (!(yield* removeOne(repository))) continue;734+ remaining = remaining.filter((entry) => entry.worktreePath !== repository.worktreePath);735+ // After each one, so a crash leaves a record that matches the disk.736+ if (input.forget) yield* store.put({ ...taskFolder, repositories: remaining });737+ }738+ const projectPath = taskFolder.projectPath;739+ const projectHoldsKept = kept.some((entry) => isWithinRoot(path, entry.path, projectPath));740+ let projectGone = false;741+ if (taskFolder.projectIsWorktree) {742+ if (projectHoldsKept) {743+ if (yield* exists(projectPath))744+ kept.push({ path: projectPath, reason: "holds a repository that was kept" });745+ } else {746+ projectGone = yield* removeOne({747+ worktreePath: projectPath,748+ repositoryPath: taskFolder.projectRoot,749+ });750+ }751+ } else if (!projectHoldsKept) {752+ // A folder that stays keeps its links: restoring relinks only a folder that is gone.753+ projectGone = yield* removeLinks(projectPath).pipe(Effect.orElseSucceed(() => false));@@ -0,0 +1039,21 @@1039+ return { worktree: { path: taskFolder.projectPath, refName: branch } };1040+ });1041+1042+ const addRepository: TaskFolders["Service"]["addRepository"] = Effect.fn(1043+ "TaskFolders.addRepository",1044+ )(function* (input) {1045+ const refuse = (detail: string) => new TaskFolderError({ operation: "add-repository", detail });1046+ const thread = yield* projections1047+ .getThreadShell(input.threadId)1048+ .pipe(Effect.mapError(fail("add-repository", "Could not read the thread")));1049+ if (thread === null || thread.worktreePath === null || thread.branch === null)1050+ return yield* refuse("This thread does not work in a worktree.");1051+ const branch = thread.branch;1052+ const startFromOrigin =1053+ input.startFromOrigin ?? (yield* startsFromOrigin("add-repository", thread.projectId));1054+ const found = yield* requireTaskFolder("add-repository", thread.worktreePath);1055+ return yield* locked(1056+ found,1057+ Effect.gen(function* () {1058+ // Read again under the lease: another add may have landed.1059+ const taskFolder = yield* requireTaskFolder("add-repository", found.root);@@ -0,0 +1067,21 @@1067+ if (!(yield* isRepository(repositoryPath)))1068+ return yield* refuse(`"${input.repositoryPath}" is not a Git repository.`);1069+ if (yield* isSubmodule(repositoryPath))1070+ return yield* refuse(`${folder.name} is a submodule, so it comes with its repository.`);1071+ if (taskFolder.repositories.some((entry) => entry.repositoryPath === repositoryPath))1072+ return yield* refuse(`${folder.name} already has a worktree in this thread.`);1073+ if (!isWithinRoot(path, repositoryPath, taskFolder.anchor))1074+ return yield* refuse(1075+ `${folder.name} lies outside the folders this thread's worktree was laid out for. Start a new worktree thread to include it.`,1076+ );1077+ const worktreePath = mapped(taskFolder, repositoryPath);1078+ const insideLinkedProject =1079+ !taskFolder.projectIsWorktree &&1080+ isWithinRoot(path, repositoryPath, taskFolder.projectRoot) &&1081+ repositoryPath !== taskFolder.projectRoot;1082+ const opened = insideLinkedProject1083+ ? yield* openLinkedPath(1084+ taskFolder.projectRoot,1085+ taskFolder.projectPath,1086+ path.relative(taskFolder.projectRoot, repositoryPath),1087+ ).pipe(Effect.mapError(fail("add-repository", "Could not prepare the folder")))@@ -0,0 +1222,21 @@1222+ }) {1223+ const restoreFailed = fail("create", "Could not restore the worktrees");1224+ // A project that lays its own folder out rebuilds it; whatever is still missing after that1225+ // comes back as a plain checkout below.1226+ const layout = yield* worktreeLayout(taskFolder.projectRoot);1227+ const present = yield* Effect.forEach(1228+ [taskFolder.projectPath, ...taskFolder.repositories.map((entry) => entry.worktreePath)],1229+ exists,1230+ );1231+ if (layout !== null && present.includes(false)) {1232+ yield* fileSystem1233+ .makeDirectory(taskFolder.root, { recursive: true })1234+ .pipe(Effect.mapError(restoreFailed));1235+ yield* runLayoutCommand(1236+ "create",1237+ layout.create,1238+ taskFolder,1239+ branch,1240+ undefined,1241+ taskFolder.repositories.map((repository) => repository.repositoryPath),1242+ ).pipe(Effect.ignoreCause({ log: true }));@@ -0,0 +1225,21 @@1225+ // comes back as a plain checkout below.1226+ const layout = yield* worktreeLayout(taskFolder.projectRoot);1227+ const present = yield* Effect.forEach(1228+ [taskFolder.projectPath, ...taskFolder.repositories.map((entry) => entry.worktreePath)],1229+ exists,1230+ );1231+ if (layout !== null && present.includes(false)) {1232+ yield* fileSystem1233+ .makeDirectory(taskFolder.root, { recursive: true })1234+ .pipe(Effect.mapError(restoreFailed));1235+ yield* runLayoutCommand(1236+ "create",1237+ layout.create,1238+ taskFolder,1239+ branch,1240+ undefined,1241+ taskFolder.repositories.map((repository) => repository.repositoryPath),1242+ ).pipe(Effect.ignoreCause({ log: true }));1243+ }1244+ const recreateMissing = Effect.fnUntraced(function* (checkout: TaskFolderCheckout) {1245+ if (yield* isRepository(checkout.worktreePath)) return;
Pushed486f3fa
- @@ -165,3 +169,10 @@165169 resolve: messages,166170 locale,167171 });172+ const repositoryFolder = input.repositoryFilter?.folder ?? null;173+ const repositoryFolders = input.repositoryFilter?.folders ?? "";174+ const previewDiff = useMemo(175+ () =>176+ repositoryFolder === null177+ ? sectionDiff178+ : filterReviewParsedDiffToFolder(@@ -522,3 +526,4 @@522526 // Only updates record model defaults; reject defaults that creation would silently drop.523527 if (524528 input.scripts !== undefined ||529+ input.trackedFolders !== undefined ||@@ -264,0 +348,21 @@348+ }349+ normalized.push({ path: folderPath, name: folder.name });350+ }351+ if (normalized.length > PROJECT_TRACKED_FOLDERS_MAX) {352+ return invalid(353+ `A project tracks at most ${PROJECT_TRACKED_FOLDERS_MAX} added folders; ${normalized.length} were given.`,354+ );355+ }356+ // Only a folder being added has to be there: one already tracked may have gone missing since.357+ return Effect.forEach(358+ normalized.filter((folder) => !known.some((existing) => existing.path === folder.path)),359+ (folder) =>360+ fileSystem.stat(folder.path).pipe(361+ Effect.map((info) => info.type === "Directory"),362+ Effect.orElseSucceed(() => false),363+ Effect.flatMap((isFolder) =>364+ isFolder ? Effect.void : invalid(`'${folder.path}' is not a folder on this machine.`),365+ ),366+ ),367+ { discard: true },368+ ).pipe(Effect.andThen(withDiscovered(workspaceRoot, normalized)));@@ -965,0 +1012,21 @@1012+ const root = taskFolder.root;1013+ // A nested worktree's uncommitted work must survive its thread's cleanup.1014+ yield* fs.writeFileString(`${root}/dist/api/tracked.txt`, "uncommitted\n");1015+ setTaskFolders(taskFolders);1016+ setThreads([shell({ branch: "task", worktreePath: root })]);1017+1018+ const report = yield* service.runNow;1019+1020+ expect(1021+ report.entries1022+ .filter((entry) => entry.path?.startsWith(root))1023+ .map(({ path, outcome, reason }) => ({ path, outcome, reason }))1024+ .toSorted((left, right) => left.path!.localeCompare(right.path!)),1025+ ).toEqual([1026+ { path: root, outcome: "kept", reason: "Holds a repository that was kept" },1027+ {1028+ path: `${root}/dist/api`,1029+ outcome: "kept",1030+ reason: "Has uncommitted changes (1 file)",1031+ },1032+ { path: `${root}/dist/web`, outcome: "removed", reason: expect.any(String) },@@ -0,0 +49,21 @@49+ yield* fileSystem.makeDirectory(folder, { recursive: true });50+ yield* run(folder, "init", "-b", "main");51+ yield* run(folder, "config", "user.email", "task-folders@example.test");52+ yield* run(folder, "config", "user.name", "Task folders");53+ yield* fileSystem.writeFileString(path.join(folder, "README.md"), `${relative}\n`);54+ yield* run(folder, "add", ".");55+ yield* run(folder, "commit", "-m", "initial");56+ return folder;57+ });58+ const isLink = (target: string) =>59+ fileSystem.readLink(target).pipe(Effect.option, Effect.map(Option.isSome));60+ const worktreeCount = (folder: string) =>61+ run(folder, "worktree", "list", "--porcelain").pipe(62+ Effect.map((listed) => listed.split("\n").filter((line) => line.startsWith("worktree "))),63+ Effect.map((worktrees) => worktrees.length),64+ );65+ return { fileSystem, path, tmp, run, repository, isLink, worktreeCount };66+});67+68+const tracked = (...folders: ReadonlyArray<string>): ReadonlyArray<ProjectTrackedFolder> =>69+ folders.map((folder) => ({ path: folder, name: folder.split("/").at(-1)! }));@@ -0,0 +367,21 @@367+ ),368+);369+370+it.live("adopts the checkouts a project's own layout command makes, and runs its teardown", () =>371+ withState((state) =>372+ Effect.gen(function* () {373+ const { fileSystem, path, tmp, run, repository, worktreeCount } = yield* fixture;374+ const shop = path.join(tmp, "shop");375+ const api = yield* repository("shop/api");376+ const web = yield* repository("shop/web");377+ // The project checks `api` out itself, copies its build cache and leaves `web` out.378+ yield* fileSystem.writeFileString(379+ path.join(shop, "t3.json"),380+ JSON.stringify({381+ worktreeLayout: {382+ // A plain project's folder is no worktree, even when the command leaves a `.git` there.383+ create:384+ 'mkdir -p "$T3_WORKTREE_PROJECT_PATH/cache" && git init -q "$T3_WORKTREE_PROJECT_PATH" && printf %s "$T3_WORKTREE_REPOSITORIES" > "$T3_WORKTREE_PROJECT_PATH/chosen" && git -C "$T3_PROJECT_ROOT/api" worktree add -q -b "$T3_WORKTREE_BRANCH" "$T3_WORKTREE_PROJECT_PATH/api" "$T3_WORKTREE_BASE"',385+ // Cleanup never deletes files that exist only here, so the teardown clears its own.386+ remove:387+ 'touch "$T3_PROJECT_ROOT/torn-down" && rm -rf "$T3_WORKTREE_PROJECT_PATH/cache" "$T3_WORKTREE_PROJECT_PATH/chosen" "$T3_WORKTREE_PROJECT_PATH/.git"',@@ -0,0 +274,21 @@274+ );275+ // One at a time per project: the commands share the project folder, and its workspace files.276+ const layoutLocks = yield* KeyedLock.make<string>();277+ const runLayoutCommand = (278+ operation: TaskFolderError["operation"],279+ command: string,280+ taskFolder: Pick<TaskFolder, "root" | "projectRoot" | "projectPath">,281+ branch: string,282+ baseBranch: string | undefined,283+ repositories: ReadonlyArray<string>,284+ ) =>285+ layoutLocks.withLock(286+ taskFolder.projectRoot,287+ processes288+ .run({289+ operation: "TaskFolders.worktreeLayout",290+ command: onWindows ? "cmd.exe" : "sh",291+ args: onWindows ? ["/d", "/s", "/c", command] : ["-c", command],292+ cwd: taskFolder.projectRoot,293+ env: {294+ ...hostEnvironment,@@ -0,0 +325,21 @@325+ // What a layout command leaves must be a checkout this service can later remove, restore and326+ // rename: a worktree linked to the repository, on the thread's branch. Null when it is.327+ const unadoptable = Effect.fnUntraced(function* (checkout: TaskFolderCheckout, branch: string) {328+ const real = (target: string) =>329+ fileSystem.realPath(target).pipe(Effect.orElseSucceed(() => target));330+ const resolved = yield* gitDirPointer(checkout.worktreePath);331+ const linked =332+ resolved !== null &&333+ isWithinRoot(334+ path,335+ yield* real(resolved),336+ path.join(yield* real(yield* commonGitDir(checkout.repositoryPath)), "worktrees"),337+ );338+ if (!linked)339+ return `${checkout.worktreePath} is not a Git worktree of ${checkout.repositoryPath}`;340+ const head = (yield* fileSystem341+ .readFileString(path.join(resolved, "HEAD"))342+ .pipe(Effect.orElseSucceed(() => ""))).trim();343+ return head === `ref: refs/heads/${branch}`344+ ? null345+ : `${checkout.worktreePath} is not on the branch ${branch}`;@@ -0,0 +689,21 @@689+ break;690+ }691+ if (allGo) {692+ yield* runLayoutCommand(693+ "remove",694+ layout.remove,695+ taskFolder,696+ input.deleteBranch ?? "",697+ undefined,698+ taskFolder.repositories.map((repository) => repository.repositoryPath),699+ ).pipe(Effect.ignoreCause({ log: true }));700+ }701+ }702+ const removeOne = Effect.fnUntraced(function* (checkout: TaskFolderCheckout) {703+ if (!(yield* exists(checkout.worktreePath))) {704+ yield* git705+ .pruneWorktrees({ cwd: checkout.repositoryPath })706+ .pipe(Effect.ignoreCause({ log: true }));707+ return true;708+ }709+ const { keep, force } = yield* verdict(checkout);@@ -0,0 +799,21 @@799+ // The same lease storage cleanup and file rewind take: the thread's worktree path.800+ const locked = <A, E>(taskFolder: Pick<TaskFolder, "projectPath">, effect: Effect.Effect<A, E>) =>801+ withWorkspaceLease(path.resolve(taskFolder.projectPath), effect);802+803+ const createRepositoryWorktree = Effect.fnUntraced(function* (804+ taskFolder: TaskFolder,805+ repository: ProjectTrackedFolder,806+ branch: string,807+ startFromOrigin: boolean,808+ baseBranch: string | undefined,809+ ) {810+ const worktreePath = mapped(taskFolder, repository.path);811+ yield* fileSystem.makeDirectory(path.dirname(worktreePath), { recursive: true });812+ const start = yield* repositoryStart(repository.path, startFromOrigin, baseBranch);813+ yield* git.createWorktree({814+ cwd: repository.path,815+ refName: start.refName,816+ newRefName: branch,817+ baseRefName: start.baseRefName,818+ path: worktreePath,819+ });@@ -0,0 +972,21 @@972+ );973+ }),974+ ),975+ Effect.mapError(fail("create", `Could not create the ${repository.name} worktree`)),976+ Effect.exit,977+ ),978+ { concurrency: REPOSITORY_CONCURRENCY },979+ ).pipe(Effect.uninterruptible);980+ const failed = exits.find(Exit.isFailure);981+ if (failed !== undefined) return yield* Effect.failCause(failed.cause);982+ }983+ const taskFolder = current();984+ yield* store.put(taskFolder);985+ return { taskFolder, branch };986+ }).pipe(987+ Effect.onError(() =>988+ removeLocked(989+ current(),990+ { force: true, forget: true, deleteBranch: branch },991+ hadBranch,992+ ).pipe(@@ -3242,4 +3263,18 @@32423263 .pipe(Effect.tap(() => refreshGitStatus(input.cwd))),32433264 [WS_METHODS.vcsListRefs]: (input) => gitWorkflow.listRefs(input),32443265 [WS_METHODS.vcsCreateWorktree]: (input) =>3245- gitWorkflow.createWorktree(input).pipe(Effect.tap(() => refreshGitStatus(input.cwd))),3266+ // A project that tracks repositories gets a task folder, as its new worktree threads do.3267+ taskFolders.createForProjectFolder(input).pipe(3268+ Effect.mapError(3269+ (cause) =>3270+ new GitCommandError({3271+ operation: "TaskFolders.create",3272+ command: "git worktree add",3273+ cwd: input.cwd,3274+ detail: cause.detail,3275+ }),3276+ ),3277+ Effect.filterOrElse(3278+ (created) => created !== null,3279+ () => gitWorkflow.createWorktree(input),3280+ ),@@ -0,0 +32,21 @@32+**Remove** takes an added folder out of the project. It never deletes files. Added folders are33+paths on one machine, so the same project on another machine has its own. A project can cover up to34+128 folders.35+36+### Leave a repository out37+38+To keep a repository inside the project folder out of the project, name it in the `t3.json` in the39+project folder, relative to that folder:40+41+```json42+{43+ "ignoreRepositories": ["vendor/big"]44+}45+```46+47+It is then not reviewed on its own and gets no worktree. Because the file is checked in, the choice48+applies on every machine.49+50+### Submodules51+52+Submodules need no setup. A thread that changes one shows it as its own repository, with its own
Sign in to join this conversation.
This PR changes the test suite by +105 test cases (browser +1, unit +47, server +57).
Keep tests that would fail for a real reason, and test logic below the UI where it can be. See Testing.