diff --git a/apps/mobile/src/features/home/HomeScreen.tsx b/apps/mobile/src/features/home/HomeScreen.tsx index c2946c59ed065..19f079b27a25f 100644 --- a/apps/mobile/src/features/home/HomeScreen.tsx +++ b/apps/mobile/src/features/home/HomeScreen.tsx @@ -14,6 +14,7 @@ import { } from "@t3tools/client-runtime/state/shell"; import { pickableProjectGroups } from "@t3tools/client-runtime/state/project-grouping"; import { threadSearchMatchKey } from "@t3tools/client-runtime/state/thread-search"; +import { umbrellaMemberLabelsByProjectKey } from "@t3tools/client-runtime/state/umbrella"; import { type EnvironmentId, type SidebarProjectGroupingMode } from "@t3tools/contracts"; import { useAtomValue } from "@effect/atom-react"; import { @@ -327,6 +328,9 @@ export function HomeScreen(props: HomeScreenProps) { }), [projects, selectedEnvironmentId, projectGroupingMode], ); + const umbrellaMemberLabelByProjectKey = umbrellaMemberLabelsByProjectKey( + projectScopes.map((scope) => scope.umbrellaMembers), + ); const hasSearchQuery = props.searchQuery.trim().length > 0; const projectByKey = (() => { const map = new Map(); @@ -538,6 +542,11 @@ export function HomeScreen(props: HomeScreenProps) { timeLabel={item.timeLabel} showTrailingDivider={item.showTrailingDivider} project={projectByKey.get(scopedProjectKey(thread.environmentId, thread.projectId)) ?? null} + umbrellaMemberLabel={ + umbrellaMemberLabelByProjectKey.get( + scopedProjectKey(thread.environmentId, thread.projectId), + ) ?? null + } providerInstance={resolveProviderInstance(thread)} providers={providersByEnvironmentId.get(thread.environmentId)} environmentLabel={ @@ -598,6 +607,7 @@ export function HomeScreen(props: HomeScreenProps) { activeNewTask, projectByKey, projectTitleByProjectKey: v2ProjectTitleByProjectKey, + umbrellaMemberLabelByProjectKey, listEnvironments, savedConnectionsById: props.savedConnectionsById, searchQuery: props.searchQuery, diff --git a/apps/mobile/src/features/home/homeThreadList.ts b/apps/mobile/src/features/home/homeThreadList.ts index 7c0392497645b..fa7c893313d70 100644 --- a/apps/mobile/src/features/home/homeThreadList.ts +++ b/apps/mobile/src/features/home/homeThreadList.ts @@ -16,6 +16,7 @@ import type { ScopedProjectRef, SidebarProjectGroupingMode, SidebarProjectSortOrder, + UmbrellaMember, } from "@t3tools/contracts"; import * as Arr from "effect/Array"; import * as Order from "effect/Order"; @@ -31,6 +32,8 @@ export interface HomeProjectScope { readonly representative: EnvironmentProject; readonly projects: ReadonlyArray; readonly projectRefs: ReadonlyArray; + /** Projects folded in as umbrella members, by scoped project key. */ + readonly umbrellaMembers: ReadonlyMap; readonly pinned: boolean; readonly archived: boolean; } @@ -68,6 +71,7 @@ export function buildHomeProjectScopes(input: { representative: group.representative, projects: group.members.map((member) => member.project), projectRefs: group.memberProjectRefs, + umbrellaMembers: group.umbrellaMembers, pinned: group.pinned, archived: group.archived, }; diff --git a/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx b/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx index 6de4c54d6d430..f37cef513a3c2 100644 --- a/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx +++ b/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx @@ -11,6 +11,7 @@ import type { EnvironmentThreadShell, } from "@t3tools/client-runtime/state/shell"; import { threadSearchMatchKey } from "@t3tools/client-runtime/state/thread-search"; +import { umbrellaMemberLabelsByProjectKey } from "@t3tools/client-runtime/state/umbrella"; import { AnimatedLegendList } from "@legendapp/list/reanimated"; import { THREAD_LIST_ROW_LAYOUT } from "./threadListAnimations"; import { useAtomValue } from "@effect/atom-react"; @@ -208,6 +209,9 @@ function ThreadNavigationSidebarPane(props: ThreadNavigationSidebarProps) { ), [projectScopes], ); + const umbrellaMemberLabelByProjectKey = umbrellaMemberLabelsByProjectKey( + projectScopes.map((scope) => scope.umbrellaMembers), + ); const selectedProjectScope = resolveHomeProjectFilterScope(projectScopes, projects, options); const threadSearch = useThreadSearch( searchEnvironmentIds, @@ -356,6 +360,7 @@ function ThreadNavigationSidebarPane(props: ThreadNavigationSidebarProps) { selectedThreadKey: selectedThreadKey ?? "", projectByKey, projectTitleByProjectKey, + umbrellaMemberLabelByProjectKey, savedConnectionsById, listEnvironments, threadSearchMatchByKey, @@ -423,6 +428,7 @@ function ThreadNavigationSidebarPane(props: ThreadNavigationSidebarProps) { snoozeWakeLabelText={item.snoozeWakeLabelText} timeLabel={item.timeLabel} project={projectByKey.get(scopeKey) ?? null} + umbrellaMemberLabel={umbrellaMemberLabelByProjectKey.get(scopeKey) ?? null} providerInstance={resolveProviderInstance(thread)} providers={providersByEnvironmentId.get(thread.environmentId)} environmentLabel={ diff --git a/apps/mobile/src/features/threads/new-task-project-selection.test.ts b/apps/mobile/src/features/threads/new-task-project-selection.test.ts index 82533a3c91e74..ef5f88927da70 100644 --- a/apps/mobile/src/features/threads/new-task-project-selection.test.ts +++ b/apps/mobile/src/features/threads/new-task-project-selection.test.ts @@ -54,6 +54,7 @@ function makeScope(projects: ReadonlyArray): HomeProjectScop environmentId: project.environmentId, projectId: project.id, })), + umbrellaMembers: new Map(), pinned: false, archived: false, }; diff --git a/apps/mobile/src/features/threads/thread-list-v2-items.tsx b/apps/mobile/src/features/threads/thread-list-v2-items.tsx index d304bc87ed451..901e56cb79e71 100644 --- a/apps/mobile/src/features/threads/thread-list-v2-items.tsx +++ b/apps/mobile/src/features/threads/thread-list-v2-items.tsx @@ -661,6 +661,8 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: { readonly timeLabel: string; readonly snoozePresetMinute: string; readonly project: EnvironmentProject | null; + /** The umbrella member a folded project's thread works in. */ + readonly umbrellaMemberLabel?: string | null; readonly providers: ReadonlyArray | undefined; readonly providerInstance: ThreadRowProviderInstance | null; readonly environmentLabel: string | null; @@ -1335,9 +1337,22 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: { > {thread.runtime.lastError} - ) : props.environmentLabel ? ( + ) : props.environmentLabel || props.umbrellaMemberLabel ? ( - {props.environmentMachine ? ( + {props.umbrellaMemberLabel ? ( + + {props.umbrellaMemberLabel} + + ) : null} + {props.environmentLabel && props.environmentMachine ? ( ) : null} - - {props.environmentLabel} - + {props.environmentLabel ? ( + + {props.environmentLabel} + + ) : null} ) : ( diff --git a/apps/server/src/checkpointing/CheckpointStore.test.ts b/apps/server/src/checkpointing/CheckpointStore.test.ts index 15fa9205dee21..c165c345cde45 100644 --- a/apps/server/src/checkpointing/CheckpointStore.test.ts +++ b/apps/server/src/checkpointing/CheckpointStore.test.ts @@ -1,10 +1,11 @@ // @effect-diagnostics nodeBuiltinImport:off +import * as NodeFS from "node:fs"; import * as NodePath from "node:path"; import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { it } from "@effect/vitest"; -import { CheckpointRef, ThreadId, type VcsError } from "@t3tools/contracts"; +import { CheckpointRef, ThreadId, type VcsError, VcsProcessExitError } from "@t3tools/contracts"; import * as HostProcess from "@t3tools/shared/HostProcess"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; @@ -18,6 +19,7 @@ import { parseTurnDiffFilesFromNumstat } from "./Diffs.ts"; import * as CheckpointStore from "./CheckpointStore.ts"; import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts"; import * as VcsProcess from "../vcs/VcsProcess.ts"; +import * as UmbrellaMemberIndex from "../vcs/UmbrellaMemberIndex.ts"; import * as ServerConfig from "../config.ts"; function checkpointRefForThreadTurn(threadId: ThreadId, turnCount: number): CheckpointRef { @@ -698,4 +700,344 @@ it.layer(layerTest)("CheckpointStore.layer", (it) => { }), ); }); + describe("umbrella members", () => { + const umbrellaStore = (root: string, members: ReadonlyArray) => + Effect.gen(function* () { + const index = UmbrellaMemberIndex.makeIndex(); + yield* index.replace( + new Map([ + [ + root, + members.map((relativePath) => ({ + path: NodePath.join(root, relativePath), + relativePath, + })), + ], + ]), + ); + return yield* CheckpointStore.make.pipe( + // The shared registry memoized the git driver with an empty index. + Effect.provide(Layer.fresh(layerVcsDriverTest)), + Effect.provideService(UmbrellaMemberIndex.UmbrellaMemberIndex, index), + ); + }); + + it.effect("checkpoints, diffs, and restores members under their own prefixes", () => + Effect.gen(function* () { + const root = NodeFS.realpathSync.native(yield* makeTmpDir()); + yield* initRepoWithCommit(root); + const fileSystem = yield* FileSystem.FileSystem; + const member = NodePath.join(root, "apps", "api"); + yield* fileSystem.makeDirectory(member, { recursive: true }); + yield* initRepoWithCommit(member); + yield* writeTextFile(NodePath.join(member, "notes.md"), buildLargeText(20)); + const checkpointStore = yield* umbrellaStore(root, ["apps/api"]); + const threadId = ThreadId.make("thread-checkpoint-store-umbrella"); + const refs = { + cwd: root, + fromCheckpointRef: checkpointRefForThreadTurn(threadId, 0), + toCheckpointRef: checkpointRefForThreadTurn(threadId, 1), + }; + + yield* checkpointStore.captureCheckpoint({ + cwd: root, + checkpointRef: refs.fromCheckpointRef, + }); + yield* writeTextFile(NodePath.join(root, "README.md"), "# outer\n"); + yield* writeTextFile(NodePath.join(member, "README.md"), "# member\n"); + yield* writeTextFile(NodePath.join(member, "new.txt"), "new\n"); + yield* fileSystem.rename( + NodePath.join(member, "notes.md"), + NodePath.join(member, "renamed.md"), + ); + yield* checkpointStore.captureCheckpoint({ + cwd: root, + checkpointRef: refs.toCheckpointRef, + }); + + const numstat = yield* checkpointStore.diffCheckpoints({ + ...refs, + ignoreWhitespace: false, + format: "numstat", + }); + expect( + parseTurnDiffFilesFromNumstat(numstat).map((file) => [file.path, file.previousPath]), + ).toEqual([ + ["apps/api/new.txt", undefined], + ["apps/api/README.md", undefined], + ["apps/api/renamed.md", "apps/api/notes.md"], + ["README.md", undefined], + ]); + const renamePatch = yield* checkpointStore.diffCheckpoints({ + ...refs, + ignoreWhitespace: false, + filePaths: ["apps/api/renamed.md", "apps/api/notes.md"], + }); + expect(renamePatch).toContain("rename from apps/api/notes.md\n"); + expect(renamePatch).toContain("rename to apps/api/renamed.md\n"); + const memberPatch = yield* checkpointStore.diffCheckpoints({ + ...refs, + ignoreWhitespace: false, + filePaths: ["apps/api/README.md"], + }); + expect(memberPatch).toContain("diff --git a/apps/api/README.md b/apps/api/README.md"); + expect(memberPatch).not.toContain("new.txt"); + expect(yield* git(root, ["ls-tree", "-r", "--name-only", refs.toCheckpointRef])).toBe( + "README.md", + ); + + expect( + yield* checkpointStore.restoreCheckpoint({ + cwd: root, + checkpointRef: refs.fromCheckpointRef, + }), + ).toBe(true); + expect(yield* fileSystem.readFileString(NodePath.join(member, "README.md"))).toBe( + "# test\n", + ); + expect(yield* fileSystem.exists(NodePath.join(member, "new.txt"))).toBe(false); + expect(yield* fileSystem.readFileString(NodePath.join(root, "README.md"))).toBe("# test\n"); + }), + ); + + it.effect("checkpoints a repository umbrella whose members it ignores", () => + Effect.gen(function* () { + const root = NodeFS.realpathSync.native(yield* makeTmpDir()); + yield* initRepoWithCommit(root); + yield* writeTextFile(NodePath.join(root, ".gitignore"), "/api/\n"); + const fileSystem = yield* FileSystem.FileSystem; + const member = NodePath.join(root, "api"); + yield* fileSystem.makeDirectory(member); + yield* initRepoWithCommit(member); + const checkpointStore = yield* umbrellaStore(root, ["api"]); + const threadId = ThreadId.make("thread-umbrella-ignored-member"); + const refs = { + cwd: root, + fromCheckpointRef: checkpointRefForThreadTurn(threadId, 0), + toCheckpointRef: checkpointRefForThreadTurn(threadId, 1), + }; + + yield* checkpointStore.captureCheckpoint({ + cwd: root, + checkpointRef: refs.fromCheckpointRef, + }); + yield* writeTextFile(NodePath.join(root, "README.md"), "# outer\n"); + yield* writeTextFile(NodePath.join(member, "README.md"), "# member\n"); + yield* checkpointStore.captureCheckpoint({ + cwd: root, + checkpointRef: refs.toCheckpointRef, + }); + + const numstat = yield* checkpointStore.diffCheckpoints({ + ...refs, + ignoreWhitespace: false, + format: "numstat", + }); + expect(parseTurnDiffFilesFromNumstat(numstat).map((file) => file.path)).toEqual([ + "api/README.md", + "README.md", + ]); + expect( + yield* checkpointStore.restoreCheckpoint({ + cwd: root, + checkpointRef: refs.fromCheckpointRef, + }), + ).toBe(true); + expect(yield* fileSystem.readFileString(NodePath.join(root, "README.md"))).toBe("# test\n"); + expect(yield* fileSystem.readFileString(NodePath.join(member, "README.md"))).toBe( + "# test\n", + ); + }), + ); + + it.effect("restores only members that changed and reports one that fails", () => + Effect.gen(function* () { + const root = NodeFS.realpathSync.native(yield* makeTmpDir()); + const fileSystem = yield* FileSystem.FileSystem; + for (const name of ["a-locked", "b-changed", "c-unchanged"]) { + yield* fileSystem.makeDirectory(NodePath.join(root, name)); + yield* initRepoWithCommit(NodePath.join(root, name)); + } + const unchanged = NodePath.join(root, "c-unchanged"); + yield* writeTextFile(NodePath.join(unchanged, "staged.txt"), "staged\n"); + yield* git(unchanged, ["add", "staged.txt"]); + const checkpointStore = yield* umbrellaStore(root, [ + "a-locked", + "b-changed", + "c-unchanged", + ]); + const checkpointRef = checkpointRefForThreadTurn( + ThreadId.make("thread-umbrella-restore"), + 0, + ); + yield* checkpointStore.captureCheckpoint({ cwd: root, checkpointRef }); + + for (const name of ["a-locked", "b-changed"]) { + yield* writeTextFile(NodePath.join(root, name, "README.md"), "# edited\n"); + } + yield* writeTextFile(NodePath.join(root, "a-locked", ".git", "index.lock"), ""); + + const error = yield* Effect.flip( + checkpointStore.restoreCheckpoint({ cwd: root, checkpointRef }), + ); + expect(error.message).toContain("Could not restore a-locked:"); + expect(error.message).not.toContain("b-changed"); + expect( + yield* fileSystem.readFileString(NodePath.join(root, "b-changed", "README.md")), + ).toBe("# test\n"); + // A member already matching the checkpoint is left alone, staged changes included. + expect(yield* git(unchanged, ["diff", "--cached", "--name-only"])).toBe("staged.txt"); + }), + ); + + it.effect("fails the checkpoint when the umbrella's own repository cannot be captured", () => + Effect.gen(function* () { + const root = "/clients/acme"; + const member = `${root}/api`; + const captured: Array = []; + const outerFailure = new VcsProcessExitError({ + operation: "test.capture", + command: "git add", + cwd: root, + exitCode: 1, + detail: "outer capture failed", + }); + const checkpointsFor = (cwd: string) => + ({ + captureCheckpoint: () => + cwd === root + ? Effect.fail(outerFailure) + : Effect.sync(() => { + captured.push(cwd); + }), + // The umbrella's own ref is missing, as after a failed capture. + hasCheckpointRef: () => Effect.succeed(cwd !== root), + diffCheckpoints: () => Effect.succeed(cwd === root ? "outer-diff" : "member-diff"), + }) as unknown as VcsDriverRegistry.VcsDriverHandle["driver"]["checkpoints"]; + const index = UmbrellaMemberIndex.makeIndex(); + yield* index.replace(new Map([[root, [{ path: member, relativePath: "api" }]]])); + const checkpointStore = yield* CheckpointStore.make.pipe( + Effect.provide( + Layer.merge( + Layer.mock(VcsDriverRegistry.VcsDriverRegistry)({ + detect: ({ cwd }) => + Effect.succeed(cwd === root ? ({} as VcsDriverRegistry.VcsDriverHandle) : null), + resolve: ({ cwd }) => + Effect.succeed({ + driver: { checkpoints: checkpointsFor(cwd) }, + } as unknown as VcsDriverRegistry.VcsDriverHandle), + }), + FileSystem.layerNoop({ realPath: (value) => Effect.succeed(value) }), + ), + ), + Effect.provideService(UmbrellaMemberIndex.UmbrellaMemberIndex, index), + ); + const checkpointRef = checkpointRefForThreadTurn(ThreadId.make("thread-outer-fail"), 1); + + const error = yield* Effect.flip( + checkpointStore.captureCheckpoint({ cwd: root, checkpointRef }), + ); + expect(error).toBe(outerFailure); + expect(captured).toEqual([]); + expect( + yield* checkpointStore.diffCheckpoints({ + cwd: root, + fromCheckpointRef: checkpointRefForThreadTurn(ThreadId.make("thread-outer-fail"), 0), + toCheckpointRef: checkpointRef, + ignoreWhitespace: false, + }), + ).toBe("member-diff"); + }), + ); + + it.effect("gives a plain umbrella folder checkpoints without making it a repository", () => + Effect.gen(function* () { + const root = NodeFS.realpathSync.native(yield* makeTmpDir()); + const member = NodePath.join(root, "site"); + yield* (yield* FileSystem.FileSystem).makeDirectory(member); + yield* initRepoWithCommit(member); + const checkpointStore = yield* umbrellaStore(root, ["site"]); + + expect(yield* checkpointStore.isGitRepository(root)).toBe(false); + expect(yield* checkpointStore.hasCheckpointWorkspace(root)).toBe(true); + }), + ); + + it.effect("checkpoints and restores a worktree-mode thread's member worktrees", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const umbrella = NodeFS.realpathSync.native(yield* makeTmpDir()); + const worktrees = NodeFS.realpathSync.native(yield* makeTmpDir()); + yield* initRepoWithCommit(umbrella); + for (const name of ["api", "site"]) { + yield* fileSystem.makeDirectory(NodePath.join(umbrella, name)); + yield* initRepoWithCommit(NodePath.join(umbrella, name)); + } + // The thread's folder: the root's own worktree with each member's worktree inside it. + const folder = NodePath.join(worktrees, "thread"); + yield* git(umbrella, ["worktree", "add", "-b", "thread", folder]); + for (const name of ["api", "site"]) { + yield* git(NodePath.join(umbrella, name), [ + "worktree", + "add", + "-b", + "thread", + NodePath.join(folder, name), + ]); + } + yield* writeTextFile( + `${folder}.t3-umbrella.json`, + JSON.stringify({ + version: 1, + umbrellaRoot: umbrella, + members: ["api", "site"].map((name) => ({ + source: NodePath.join(umbrella, name), + path: name, + })), + }), + ); + // Nothing registered the folder yet, as after a restart. + const checkpointStore = yield* umbrellaStore( + NodeFS.realpathSync.native(yield* makeTmpDir()), + [], + ); + const threadId = ThreadId.make("thread-umbrella-worktree"); + const baseline = checkpointRefForThreadTurn(threadId, 0); + const turn = checkpointRefForThreadTurn(threadId, 1); + yield* checkpointStore.captureCheckpoint({ cwd: folder, checkpointRef: baseline }); + for (const name of ["api", "site"]) { + yield* writeTextFile(NodePath.join(folder, name, "README.md"), `# ${name} edited\n`); + } + yield* writeTextFile(NodePath.join(folder, "site", "new.md"), "new\n"); + yield* checkpointStore.captureCheckpoint({ cwd: folder, checkpointRef: turn }); + + const numstat = yield* checkpointStore.diffCheckpoints({ + cwd: folder, + fromCheckpointRef: baseline, + toCheckpointRef: turn, + ignoreWhitespace: false, + format: "numstat", + }); + expect(parseTurnDiffFilesFromNumstat(numstat).map((file) => file.path)).toEqual([ + "api/README.md", + "site/new.md", + "site/README.md", + ]); + // The root's checkpoint leaves the members' worktrees out. + expect(yield* git(folder, ["ls-tree", "-r", "--name-only", turn])).toBe("README.md"); + + expect( + yield* checkpointStore.restoreCheckpoint({ cwd: folder, checkpointRef: baseline }), + ).toBe(true); + for (const name of ["api", "site"]) { + expect(yield* fileSystem.readFileString(NodePath.join(folder, name, "README.md"))).toBe( + "# test\n", + ); + // The members' own checkouts are untouched. + expect(yield* git(NodePath.join(umbrella, name), ["status", "--porcelain"])).toBe(""); + } + expect(yield* fileSystem.exists(NodePath.join(folder, "site", "new.md"))).toBe(false); + }), + ); + }); }); diff --git a/apps/server/src/checkpointing/CheckpointStore.ts b/apps/server/src/checkpointing/CheckpointStore.ts index 8eadf2b5342af..edb5f90e06ab7 100644 --- a/apps/server/src/checkpointing/CheckpointStore.ts +++ b/apps/server/src/checkpointing/CheckpointStore.ts @@ -1,11 +1,17 @@ -import { type CheckpointRef } from "@t3tools/contracts"; +import { CheckpointRef, VcsProcessExitError } from "@t3tools/contracts"; import * as Context from "effect/Context"; import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; +import * as Path from "effect/Path"; +import * as Result from "effect/Result"; +import { parseTurnDiffFilesFromNumstat } from "./Diffs.ts"; import type { CheckpointStoreError } from "./Errors.ts"; import type { VcsCheckpointOps } from "../vcs/VcsDriver.ts"; import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts"; +import { UmbrellaMemberIndex } from "../vcs/UmbrellaMemberIndex.ts"; +import { loadUmbrellaWorktree } from "../project/umbrellaWorktreeLayout.ts"; export interface CaptureCheckpointInput { readonly cwd: string; @@ -49,6 +55,9 @@ export class CheckpointStore extends Context.Service< { readonly isGitRepository: (cwd: string) => Effect.Effect; + /** A repository, or an umbrella whose member checkouts take checkpoints even when it is a plain folder. */ + readonly hasCheckpointWorkspace: (cwd: string) => Effect.Effect; + readonly captureCheckpoint: ( input: CaptureCheckpointInput, ) => Effect.Effect; @@ -76,9 +85,47 @@ export class CheckpointStore extends Context.Service< } >()("t3/checkpointing/CheckpointStore") {} +/** One repository behind a checkpoint: the workspace itself, or an umbrella member under `prefix`. */ +interface CheckpointComponent { + readonly cwd: string; + readonly prefix: string; +} + +/** Splits workspace-relative paths between the umbrella's own repository and its members. */ +function routeComponentPaths( + components: ReadonlyArray, + filePaths: ReadonlyArray, +): ReadonlyMap> { + const members = components + .filter((component) => component.prefix !== "") + .toSorted((left, right) => right.prefix.length - left.prefix.length); + const routed = new Map(components.map((c) => [c, []])); + for (const filePath of filePaths) { + const member = members.find((candidate) => filePath.startsWith(candidate.prefix)); + const owner = member ?? components.find((component) => component.prefix === ""); + if (owner === undefined) continue; + routed.get(owner)!.push(member ? filePath.slice(member.prefix.length) : filePath); + } + return routed; +} + +function partitionComponents( + components: ReadonlyArray, +): readonly [CheckpointComponent | undefined, ReadonlyArray] { + return [ + components.find((component) => component.prefix === ""), + components.filter((component) => component.prefix !== ""), + ]; +} + +const componentLabel = (component: CheckpointComponent) => + component.prefix === "" ? "the umbrella folder" : component.prefix.slice(0, -1); + /** @public */ export const make = Effect.gen(function* () { const vcsRegistry = yield* VcsDriverRegistry.VcsDriverRegistry; + const fileSystem = yield* FileSystem.FileSystem; + const umbrellaMembers = yield* UmbrellaMemberIndex; const resolveCheckpoints = Effect.fn("CheckpointStore.resolveCheckpoints")(function* ( cwd: string, @@ -96,50 +143,327 @@ export const make = Effect.gen(function* () { return (yield* git.detectRepository(cwd)) !== null; }); + const registeredMembersOf = (cwd: string) => + umbrellaMembers.hasMembers() + ? fileSystem.realPath(cwd).pipe( + Effect.map((resolved) => umbrellaMembers.membersOf(resolved)), + Effect.orElseSucceed(() => umbrellaMembers.membersOf(cwd)), + ) + : Effect.succeed([]); + // A worktree-mode umbrella thread's folder registers on first use after a restart, before + // its root repository's checkpoint could take in the members. + const membersOf = (cwd: string) => + registeredMembersOf(cwd).pipe( + Effect.filterOrElse( + (members) => members.length > 0, + (members) => + loadUmbrellaWorktree(cwd).pipe( + Effect.provideService(FileSystem.FileSystem, fileSystem), + Effect.provideService(UmbrellaMemberIndex, umbrellaMembers), + Effect.provide(Path.layer), + Effect.flatMap((layout) => + layout === null ? Effect.succeed(members) : registeredMembersOf(cwd), + ), + ), + ), + ); + + // Only an umbrella pays for the extra lookups; a plain workspace is its own single component. + const componentsOf = Effect.fn("CheckpointStore.components")(function* (cwd: string) { + const members = yield* membersOf(cwd); + if (members.length === 0) return null; + const own = yield* isGitRepository(cwd).pipe(Effect.orElseSucceed(() => false)); + return [ + ...(own ? [{ cwd, prefix: "" }] : []), + ...members.map((member) => ({ cwd: member.path, prefix: `${member.relativePath}/` })), + ] satisfies ReadonlyArray; + }); + + const hasRef = (cwd: string, checkpointRef: CheckpointRef) => + resolveCheckpoints(cwd).pipe( + Effect.flatMap((checkpoints) => checkpoints.hasCheckpointRef({ cwd, checkpointRef })), + Effect.orElseSucceed(() => false), + ); + + const hasBothRefs = ( + cwd: string, + input: { readonly fromCheckpointRef: CheckpointRef; readonly toCheckpointRef: CheckpointRef }, + ) => + hasRef(cwd, input.fromCheckpointRef).pipe( + Effect.flatMap((found) => + found ? hasRef(cwd, input.toCheckpointRef) : Effect.succeed(false), + ), + ); + + const hasCheckpointWorkspace: CheckpointStore["Service"]["hasCheckpointWorkspace"] = Effect.fn( + "CheckpointStore.hasCheckpointWorkspace", + )(function* (cwd) { + if ((yield* membersOf(cwd)).length > 0) return true; + return yield* isGitRepository(cwd); + }); + const captureCheckpoint: CheckpointStore["Service"]["captureCheckpoint"] = Effect.fn( "captureCheckpoint", )(function* (input) { - const checkpoints = yield* resolveCheckpoints(input.cwd); - return yield* checkpoints.captureCheckpoint(input); + const components = yield* componentsOf(input.cwd); + if (components === null) { + const checkpoints = yield* resolveCheckpoints(input.cwd); + return yield* checkpoints.captureCheckpoint(input); + } + // The umbrella's own repository fails the checkpoint as a plain workspace would. A member that + // cannot be captured drops its ref instead, so diffs and restores leave it alone. + const [own, members] = partitionComponents(components); + if (own !== undefined) { + const checkpoints = yield* resolveCheckpoints(own.cwd); + yield* checkpoints.captureCheckpoint({ ...input, cwd: own.cwd }); + } + yield* Effect.forEach( + members, + (component) => + resolveCheckpoints(component.cwd).pipe( + Effect.flatMap((checkpoints) => + checkpoints.captureCheckpoint({ ...input, cwd: component.cwd }), + ), + Effect.catch((cause) => + Effect.logWarning("umbrella checkpoint capture failed", { + cwd: component.cwd, + cause, + }).pipe( + Effect.andThen( + resolveCheckpoints(component.cwd).pipe( + Effect.flatMap((checkpoints) => + checkpoints.deleteCheckpointRefs({ + cwd: component.cwd, + checkpointRefs: [input.checkpointRef], + }), + ), + Effect.ignore, + ), + ), + ), + ), + ), + { concurrency: 4, discard: true }, + ); }); const hasCheckpointRef: CheckpointStore["Service"]["hasCheckpointRef"] = Effect.fn( "hasCheckpointRef", )(function* (input) { - const checkpoints = yield* resolveCheckpoints(input.cwd); - return yield* checkpoints.hasCheckpointRef(input); + const components = yield* componentsOf(input.cwd); + if (components === null) { + const checkpoints = yield* resolveCheckpoints(input.cwd); + return yield* checkpoints.hasCheckpointRef(input); + } + for (const component of components) { + if (yield* hasRef(component.cwd, input.checkpointRef)) return true; + } + return false; + }); + + // A capture of the member as it is now, diffed against the target, tells whether restoring it + // would change anything; one that already matches keeps any unrelated state untouched. + const matchesCheckpoint = Effect.fn("CheckpointStore.matchesCheckpoint")(function* ( + component: CheckpointComponent, + checkpointRef: CheckpointRef, + ) { + const checkpoints = yield* resolveCheckpoints(component.cwd); + const probeRef = CheckpointRef.make(checkpointRef.replace("/checkpoints/", "/restore-probes/")); + return yield* checkpoints + .captureCheckpoint({ cwd: component.cwd, checkpointRef: probeRef }) + .pipe( + Effect.andThen( + checkpoints.diffCheckpoints({ + cwd: component.cwd, + fromCheckpointRef: checkpointRef, + toCheckpointRef: probeRef, + ignoreWhitespace: false, + format: "numstat", + }), + ), + Effect.map((numstat) => numstat.length === 0), + Effect.ensuring( + checkpoints + .deleteCheckpointRefs({ cwd: component.cwd, checkpointRefs: [probeRef] }) + .pipe(Effect.ignore), + ), + ); }); const restoreCheckpoint: CheckpointStore["Service"]["restoreCheckpoint"] = Effect.fn( "restoreCheckpoint", )(function* (input) { - const checkpoints = yield* resolveCheckpoints(input.cwd); - return yield* checkpoints.restoreCheckpoint(input); + const components = yield* componentsOf(input.cwd); + if (components === null) { + const checkpoints = yield* resolveCheckpoints(input.cwd); + return yield* checkpoints.restoreCheckpoint(input); + } + // Every ref is checked before anything is written. The umbrella's own repository must have + // it, as a plain workspace must; a member added after the checkpoint has none and is skipped. + const [own, members] = partitionComponents(components); + if (own !== undefined && !(yield* hasRef(own.cwd, input.checkpointRef))) { + if (input.fallbackToHead !== true) return false; + } + const captured = yield* Effect.filter(members, (member) => + hasRef(member.cwd, input.checkpointRef), + ); + if (own === undefined && captured.length === 0) return false; + const targets = [ + ...(own === undefined ? [] : [own]), + ...(yield* Effect.filter(captured, (member) => + matchesCheckpoint(member, input.checkpointRef).pipe( + Effect.map((matches) => !matches), + Effect.orElseSucceed(() => true), + ), + )), + ]; + const failures: Array = []; + for (const component of targets) { + const result = yield* resolveCheckpoints(component.cwd).pipe( + // Falling back to HEAD would discard a member's edits it never checkpointed. + Effect.flatMap((checkpoints) => + checkpoints.restoreCheckpoint({ + cwd: component.cwd, + checkpointRef: input.checkpointRef, + fallbackToHead: component.prefix === "" && input.fallbackToHead === true, + }), + ), + Effect.result, + ); + if (Result.isFailure(result)) { + failures.push(`${componentLabel(component)}: ${result.failure.message}`); + } else if (!result.success && component.prefix === "") { + failures.push(`${componentLabel(component)}: the checkpoint is unavailable`); + } + } + if (failures.length > 0) { + return yield* new VcsProcessExitError({ + operation: "CheckpointStore.restoreCheckpoint", + command: "git restore", + cwd: input.cwd, + exitCode: 0, + detail: `Could not restore ${failures.join("; ")}.`, + }); + } + return true; + }); + + const diffComponent = Effect.fn("CheckpointStore.diffComponent")(function* ( + component: CheckpointComponent, + input: DiffCheckpointsInput, + ) { + if (!(yield* hasBothRefs(component.cwd, input))) return ""; + const checkpoints = yield* resolveCheckpoints(component.cwd); + return yield* checkpoints.diffCheckpoints({ + ...input, + cwd: component.cwd, + ...(component.prefix === "" ? {} : { pathPrefix: component.prefix }), + }); }); const diffCheckpoints: CheckpointStore["Service"]["diffCheckpoints"] = Effect.fn( "diffCheckpoints", )(function* (input) { - const checkpoints = yield* resolveCheckpoints(input.cwd); - return yield* checkpoints.diffCheckpoints(input); + const components = yield* componentsOf(input.cwd); + if (components === null) { + const checkpoints = yield* resolveCheckpoints(input.cwd); + return yield* checkpoints.diffCheckpoints(input); + } + if (input.filePaths?.length === 0) return ""; + const routed = + input.filePaths === undefined ? null : routeComponentPaths(components, input.filePaths); + let output = ""; + for (const component of components) { + const filePaths = routed?.get(component); + if (filePaths !== undefined && filePaths.length === 0) continue; + const remaining = + input.maxOutputBytes === undefined + ? undefined + : input.maxOutputBytes - Buffer.byteLength(output); + if (remaining !== undefined && remaining <= 0) break; + output += yield* diffComponent(component, { + ...input, + ...(filePaths === undefined ? {} : { filePaths }), + ...(remaining === undefined ? {} : { maxOutputBytes: remaining }), + }); + } + return output; }); const listAuthoredPaths: CheckpointStore["Service"]["listAuthoredPaths"] = Effect.fn( "listAuthoredPaths", )(function* (input) { - const checkpoints = yield* resolveCheckpoints(input.cwd); - return yield* checkpoints.listAuthoredPaths(input); + const components = yield* componentsOf(input.cwd); + if (components === null) { + const checkpoints = yield* resolveCheckpoints(input.cwd); + return yield* checkpoints.listAuthoredPaths(input); + } + const perComponent = yield* Effect.forEach(components, (component) => + Effect.gen(function* () { + if (!(yield* hasBothRefs(component.cwd, input))) { + return { component, authored: new Set() }; + } + const checkpoints = yield* resolveCheckpoints(component.cwd); + const authored = yield* checkpoints.listAuthoredPaths({ ...input, cwd: component.cwd }); + return { component, authored }; + }), + ); + if (perComponent.every((entry) => entry.authored === null)) return null; + const union = new Set(); + for (const { component, authored } of perComponent) { + if (authored !== null) { + for (const authoredPath of authored) union.add(`${component.prefix}${authoredPath}`); + continue; + } + // An unchanged HEAD means every path this member changed is the turn's. + const numstat = yield* diffComponent(component, { + ...input, + ignoreWhitespace: false, + format: "numstat", + }); + for (const file of parseTurnDiffFilesFromNumstat(numstat)) { + union.add(file.path); + if (file.previousPath !== undefined) union.add(file.previousPath); + } + } + return union; }); const deleteCheckpointRefs: CheckpointStore["Service"]["deleteCheckpointRefs"] = Effect.fn( "deleteCheckpointRefs", )(function* (input) { - const checkpoints = yield* resolveCheckpoints(input.cwd); - return yield* checkpoints.deleteCheckpointRefs(input); + const components = yield* componentsOf(input.cwd); + if (components === null) { + const checkpoints = yield* resolveCheckpoints(input.cwd); + return yield* checkpoints.deleteCheckpointRefs(input); + } + // One repository failing must not leave the others' refs behind. + const failures: Array = []; + for (const component of components) { + const result = yield* resolveCheckpoints(component.cwd).pipe( + Effect.flatMap((checkpoints) => + checkpoints.deleteCheckpointRefs({ ...input, cwd: component.cwd }), + ), + Effect.result, + ); + if (Result.isFailure(result)) { + failures.push(`${componentLabel(component)}: ${result.failure.message}`); + } + } + if (failures.length > 0) { + return yield* new VcsProcessExitError({ + operation: "CheckpointStore.deleteCheckpointRefs", + command: "git update-ref", + cwd: input.cwd, + exitCode: 0, + detail: `Could not delete checkpoint refs in ${failures.join("; ")}.`, + }); + } }); return CheckpointStore.of({ isGitRepository, + hasCheckpointWorkspace, captureCheckpoint, hasCheckpointRef, restoreCheckpoint, diff --git a/apps/server/src/git/linkCreatedPullRequest.ts b/apps/server/src/git/linkCreatedPullRequest.ts index 50708d4ff7bc2..1530a02a891d6 100644 --- a/apps/server/src/git/linkCreatedPullRequest.ts +++ b/apps/server/src/git/linkCreatedPullRequest.ts @@ -2,6 +2,7 @@ import { type CommandId, type GitRunStackedActionResult, type OrchestrationProjectShell, + type RepositoryIdentity, type ThreadId, } from "@t3tools/contracts"; import * as Cause from "effect/Cause"; @@ -27,11 +28,19 @@ export function createdPullRequestKey( if ((status !== "created" && status !== "opened_existing") || number === undefined || !url) { return null; } + return pullRequestKeyOf({ number, url }, project?.repositoryIdentity); +} + +/** The thread link key for a pull request, from its URL or else the repository it was opened in. */ +export function pullRequestKeyOf( + pullRequest: { readonly number: number; readonly url: string }, + identity: RepositoryIdentity | null | undefined, +): CreatedPullRequestKey | null { + const { number, url } = pullRequest; const parsed = sourceControlDefinitions.parseChangeRequestUrl(url)?.link; if (parsed !== undefined) { return { host: parsed.host, repository: parsed.repository, number: parsed.number, url }; } - const identity = project?.repositoryIdentity; const kind = identity?.provider; const repository = sourceControlDefinitions.repositorySelector(identity); if (!identity || kind === undefined || repository === null) return null; diff --git a/apps/server/src/mcp/OrchestratorMcpService.ts b/apps/server/src/mcp/OrchestratorMcpService.ts index 5c5c9636406e1..954c8c96e4772 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.ts @@ -111,6 +111,7 @@ import { import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts"; import { placeholderThreadTitle } from "../orchestration-v2/placeholderThreadTitle.ts"; import * as ThreadLaunchService from "../orchestration-v2/ThreadLaunchService.ts"; +import * as UmbrellaMembership from "../project/UmbrellaMembership.ts"; import * as GitVcsDriver from "../vcs/GitVcsDriver.ts"; import { isSnoozed } from "../orchestration-v2/ThreadSettlementService.ts"; import { userFacingDispatchErrorMessage } from "../orchestration-v2/UserFacingErrors.ts"; @@ -1265,6 +1266,7 @@ const make = Effect.gen(function* () { const projects = yield* ProjectService.ProjectService; const threadLaunch = yield* ThreadLaunchService.ThreadLaunchService; const gitDriver = yield* GitVcsDriver.GitVcsDriver; + const umbrellaMembersOf = yield* UmbrellaMembership.makeUmbrellaMembersOf; const serverSettings = yield* ServerSettings.ServerSettingsService; const remoteDelegation = yield* RemoteDelegation.RemoteDelegation; @@ -2699,7 +2701,26 @@ const make = Effect.gen(function* () { input.interactionMode, ); let workspaceStrategy: OrchestrationV2ThreadLaunchWorkspaceStrategy | undefined; - if (input.isolation === "worktree" && !isRetryOfAcceptedDelegation) { + const umbrellaMembers = + input.isolation === "worktree" + ? yield* umbrellaMembersOf(yield* requireProject(parent.thread.projectId)) + : []; + if ( + input.isolation === "worktree" && + !isRetryOfAcceptedDelegation && + umbrellaMembers.length > 0 + ) { + // An umbrella child starts each repository from the parent's branch, which every + // repository in the parent's umbrella worktree has, or else from its own checkout. + workspaceStrategy = { + type: "worktree", + baseRef: + parent.thread.worktreePath !== null && parent.thread.branch !== null + ? parent.thread.branch + : "HEAD", + startFromOrigin: false, + }; + } else if (input.isolation === "worktree" && !isRetryOfAcceptedDelegation) { const project = yield* requireProject(parent.thread.projectId); const base = yield* gitDriver .resolveCommit({ diff --git a/apps/server/src/mcp/WorktreeMcpService.test.ts b/apps/server/src/mcp/WorktreeMcpService.test.ts index 3dc7cc2bcc77a..4c8ffb36da2c0 100644 --- a/apps/server/src/mcp/WorktreeMcpService.test.ts +++ b/apps/server/src/mcp/WorktreeMcpService.test.ts @@ -9,6 +9,7 @@ import { ProjectId, ProviderInstanceId, ThreadId, + type UmbrellaMember, WorktreeMcpHandoffInput, } from "@t3tools/contracts"; import * as Cause from "effect/Cause"; @@ -32,6 +33,7 @@ import { import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts"; import * as ProjectService from "../project/ProjectService.ts"; import * as ProjectSetupScriptRunner from "../project/ProjectSetupScriptRunner.ts"; +import * as UmbrellaMembership from "../project/UmbrellaMembership.ts"; import * as ServerSettings from "../serverSettings.ts"; import * as VcsStatusBroadcaster from "../vcs/VcsStatusBroadcaster.ts"; import type * as McpInvocationContext from "./McpInvocationContext.ts"; @@ -116,6 +118,8 @@ interface HarnessOptions { readonly deleteLocalBranchFails?: boolean; readonly createWorktreeGate?: Effect.Effect; readonly existsFails?: boolean; + readonly umbrellaMembers?: ReadonlyArray; + readonly worktreesDir?: string; } const makeHarness = (options: HarnessOptions = {}) => { @@ -212,7 +216,9 @@ const makeHarness = (options: HarnessOptions = {}) => { Effect.andThen( Effect.succeed({ worktree: { - path: input.path ?? `/worktrees/project/${input.newRefName}`, + path: + input.path ?? + `${options.worktreesDir ?? "/worktrees"}/project/${input.newRefName}`, refName: input.newRefName ?? "detached", }, }), @@ -315,6 +321,16 @@ const makeHarness = (options: HarnessOptions = {}) => { } satisfies Partial), NodeServices.layer, NodeCrypto.layer, + options.umbrellaMembers === undefined + ? Layer.empty + : Layer.mock(UmbrellaMembership.UmbrellaMembership)({ + stateOf: () => + Effect.succeed({ + members: options.umbrellaMembers!, + suggestions: [], + enclosingRepository: null, + }), + }), options.existsFails ? FileSystem.layerNoop({ exists: (path) => @@ -399,6 +415,44 @@ describe("t3_worktree_handoff", () => { }); }); + it.effect("hands an umbrella thread off to one folder holding every member", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const worktreesDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "handoff-umbrella-", + }); + yield* fileSystem.makeDirectory(`${worktreesDir}/project/feature`, { recursive: true }); + const harness = makeHarness({ + worktreesDir, + umbrellaMembers: [ + { path: "/project/api", relativePath: "api", repositoryIdentity: null, source: "nested" }, + ], + git: { + repositoryRoot: (cwd) => Effect.succeed(cwd), + currentBranch: () => Effect.succeed("main"), + }, + }); + const result = yield* runHandoff(harness, { branch: "feature/umbrella" }); + expect(result.baseRef).toBe("HEAD"); + expect(harness.localStatus).not.toHaveBeenCalled(); + expect(harness.createWorktree).toHaveBeenCalledWith( + expect.objectContaining({ + cwd: "/project/api", + newRefName: "feature/umbrella", + path: `${result.worktreePath}/api`, + }), + expect.anything(), + ); + expect(harness.dispatch).toHaveBeenCalledWith( + expect.objectContaining({ + type: "thread.metadata.update", + worktreePath: result.worktreePath, + branch: "feature/umbrella", + }), + ); + }).pipe(Effect.provide(NodeServices.layer)), + ); + it.effect("uses the fetched commit and remote PR base for an explicit local alias", () => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; diff --git a/apps/server/src/mcp/WorktreeMcpService.ts b/apps/server/src/mcp/WorktreeMcpService.ts index 5d73b864d356b..92490c5689db0 100644 --- a/apps/server/src/mcp/WorktreeMcpService.ts +++ b/apps/server/src/mcp/WorktreeMcpService.ts @@ -3,6 +3,7 @@ import { type GitCommandError, MessageId, type ProjectId, + type ProjectScript, WorktreeMcpFailure, type WorktreeMcpContinuationStatus, type WorktreeMcpHandoffInput, @@ -20,12 +21,16 @@ import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; +import type * as Path from "effect/Path"; import type * as PlatformError from "effect/PlatformError"; import * as GitWorkflowService from "../git/GitWorkflowService.ts"; import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts"; import * as ProjectService from "../project/ProjectService.ts"; import * as ProjectSetupScriptRunner from "../project/ProjectSetupScriptRunner.ts"; +import * as UmbrellaMembership from "../project/UmbrellaMembership.ts"; +import { makeUmbrellaWorktrees } from "../project/UmbrellaWorktree.ts"; +import type { UmbrellaWorktreeError } from "../project/umbrellaWorktreeLayout.ts"; import * as ServerSettings from "../serverSettings.ts"; import * as VcsStatusBroadcaster from "../vcs/VcsStatusBroadcaster.ts"; import type { McpInvocationScope, McpThreadInvocationScope } from "./McpInvocationContext.ts"; @@ -75,6 +80,8 @@ const make = Effect.gen(function* () { const gitWorkflow = yield* GitWorkflowService.GitWorkflowService; const setupScriptRunner = yield* ProjectSetupScriptRunner.ProjectSetupScriptRunner; const vcsStatusBroadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster; + const umbrellaWorktrees = yield* makeUmbrellaWorktrees; + const umbrellaMembersOf = yield* UmbrellaMembership.makeUmbrellaMembersOf; // Serialize handoffs per thread to avoid creating two worktrees and orphaning one. const handoffThreadsInFlight = new Set(); @@ -176,6 +183,42 @@ const make = Effect.gen(function* () { const project = yield* loadProject(scope, projection.thread.projectId); const projectCwd = project.workspaceRoot; + const umbrellaMembers = yield* umbrellaMembersOf(project); + if (umbrellaMembers.length > 0) { + const baseRef = input.baseRef ?? "HEAD"; + return yield* bindWorktree(scope, input, project, { + baseRef, + startedFromOrigin: false, + create: Effect.gen(function* () { + const startFromOrigin = + input.startFromOrigin ?? (yield* readDefaultStartFromOrigin(project.id)); + const submodules = yield* serverSettings.getSettings.pipe( + Effect.map( + (settings) => + resolveProjectSettings(settings, project.id).settings.worktreeSubmodules, + ), + Effect.orElseSucceed(() => null), + ); + return yield* umbrellaWorktrees + .create({ + umbrellaRoot: projectCwd, + members: umbrellaMembers, + baseRef, + startFromOrigin, + branch: input.branch, + flattenOnConflict: false, + submodules, + }) + .pipe(asOperationFailed("Unable to create the umbrella worktree")); + }), + remove: (created) => + umbrellaWorktrees.remove({ + worktreePath: created.path, + force: true, + deleteBranch: created.branch, + }), + }); + } const localStatus = yield* gitWorkflow .localStatus({ cwd: projectCwd }) @@ -238,23 +281,71 @@ const make = Effect.gen(function* () { } } + return yield* bindWorktree(scope, input, project, { + baseRef, + startedFromOrigin, + create: gitWorkflow + .createWorktree({ + cwd: projectCwd, + refName: worktreeBaseRef, + newRefName: input.branch, + baseRefName, + path: null, + }) + .pipe( + Effect.map(({ worktree }) => ({ path: worktree.path, branch: worktree.refName })), + asOperationFailed("Unable to create the worktree"), + ), + remove: (created) => + gitWorkflow.removeWorktree({ cwd: projectCwd, path: created.path, force: true }).pipe( + Effect.andThen( + Effect.suspend(() => + gitWorkflow.deleteLocalBranch({ + cwd: projectCwd, + refName: created.branch, + force: true, + }), + ), + ), + ), + }); + }); + + const bindWorktree = Effect.fn("WorktreeMcpService.bindWorktree")(function* ( + scope: McpThreadInvocationScope, + input: WorktreeMcpHandoffInput, + project: { + readonly id: ProjectId; + readonly workspaceRoot: string; + readonly scripts: ReadonlyArray; + }, + worktreeSource: { + readonly baseRef: string; + readonly startedFromOrigin: boolean; + readonly create: Effect.Effect< + { readonly path: string; readonly branch: string }, + WorktreeMcpFailure + >; + readonly remove: (created: { + readonly path: string; + readonly branch: string; + }) => Effect.Effect; + }, + ) { + const { baseRef, startedFromOrigin } = worktreeSource; + const projectCwd = project.workspaceRoot; + const alreadyInWorktree = (worktreePath: string) => + failure( + "already_in_worktree", + `Thread '${scope.thread.threadId}' is already attached to worktree '${worktreePath}'.`, + ); const ids = yield* handoffIds(scope); // Mask interruption after worktree creation through setup; binding can detach and interrupt the caller. return yield* Effect.uninterruptibleMask((restore) => Effect.gen(function* () { - const worktree = yield* restore( - gitWorkflow - .createWorktree({ - cwd: projectCwd, - refName: worktreeBaseRef, - newRefName: input.branch, - baseRefName, - path: null, - }) - .pipe(asOperationFailed("Unable to create the worktree")), - ); - const worktreePath = worktree.worktree.path; + const worktree = yield* restore(worktreeSource.create); + const worktreePath = worktree.path; const reportFailed = (logMessage: string) => Effect.catchCause((cause: Cause.Cause) => { @@ -266,19 +357,9 @@ const make = Effect.gen(function* () { }).pipe(Effect.as({ status: "failed", detail } as const)); }); - const removeCreatedWorktree = Effect.suspend(() => - gitWorkflow.removeWorktree({ cwd: projectCwd, path: worktreePath, force: true }).pipe( - Effect.andThen( - Effect.suspend(() => - gitWorkflow.deleteLocalBranch({ - cwd: projectCwd, - refName: worktree.worktree.refName, - force: true, - }), - ), - ), - ), - ).pipe(Effect.ignoreCause({ log: true })); + const removeCreatedWorktree = Effect.suspend(() => worktreeSource.remove(worktree)).pipe( + Effect.ignoreCause({ log: true }), + ); const recheckAndBind = Effect.gen(function* () { // A concurrent UI binding may have landed during git work; do not orphan a second worktree. @@ -297,7 +378,7 @@ const make = Effect.gen(function* () { type: "thread.metadata.update", commandId: ids.commandId, threadId: scope.thread.threadId, - branch: worktree.worktree.refName, + branch: worktree.branch, worktreePath, expectedWorktreePath: null, // Binding detaches the session and ends the caller; a later send could lose the race. @@ -351,7 +432,7 @@ const make = Effect.gen(function* () { setupScript = yield* setupScriptRunner .runForThread({ threadId: scope.thread.threadId, - projectId: projection.thread.projectId, + projectId: project.id, projectCwd, worktreePath, project: { @@ -378,7 +459,7 @@ const make = Effect.gen(function* () { const result: WorktreeMcpHandoffResult = { worktreePath, - branch: worktree.worktree.refName, + branch: worktree.branch, baseRef, startedFromOrigin, setupScript, @@ -464,4 +545,5 @@ export const layer: Layer.Layer< | GitWorkflowService.GitWorkflowService | ProjectSetupScriptRunner.ProjectSetupScriptRunner | VcsStatusBroadcaster.VcsStatusBroadcaster + | Path.Path > = Layer.effect(WorktreeMcpService, make); diff --git a/apps/server/src/mcp/toolkits/project/handlers.test.ts b/apps/server/src/mcp/toolkits/project/handlers.test.ts index c95fadd9096e2..5c5b7621a5bfb 100644 --- a/apps/server/src/mcp/toolkits/project/handlers.test.ts +++ b/apps/server/src/mcp/toolkits/project/handlers.test.ts @@ -613,6 +613,63 @@ it.effect("a launch into a new worktree creates nothing when its base ref has no }), ); +it.effect("a worktree launch in a plain umbrella folder points at a member's own project", () => + Effect.gen(function* () { + const launched: Array = []; + const appProjectId = ProjectId.make("project-app"); + const { projectId, dependencies } = clientLaunchHarness({ + runtimeModeCeiling: "auto", + launched, + checkWorktreeBase: ({ projectId, workspaceStrategy }) => + Effect.fail( + new ThreadLaunch.ThreadLaunchNotRepositoryError({ + projectId, + projectTitle: "Client folder", + workspaceRoot: "/projects/client", + ...(workspaceStrategy.type === "worktree" + ? { baseRef: workspaceStrategy.baseRef } + : {}), + nestedRepositories: [ + { + relativePath: "app", + projectId: appProjectId, + projectTitle: "app", + hasBaseRef: true, + }, + { + relativePath: "site", + projectId: ProjectId.make("project-site"), + hasBaseRef: false, + }, + { relativePath: "dev-setup", hasBaseRef: false }, + ], + umbrella: true, + }), + ), + }); + const toolkit = yield* ProjectToolkit.pipe( + Effect.provide( + McpToolAccess.HandlersLayer.layer(ProjectHandlers.layer).pipe(Layer.provide(dependencies)), + ), + ); + const refused = (yield* toolkit + .handle("t3_thread_launch", { + title: "Fix CI", + projectId, + workspaceStrategy: { type: "worktree", baseRef: "origin/develop", startFromOrigin: true }, + }) + .pipe(Stream.unwrap, Stream.runCollect, Effect.provide(dependencies))).at(-1)?.result; + expect(refused).toMatchObject({ code: "invalid_request" }); + const message = (refused as { message: string }).message; + expect(message).toContain('"origin/develop" is in app (project "app").'); + expect(message).toContain( + `pass the projectId of the checkout's own project: "${appProjectId}" (app).`, + ); + expect(message).toContain("Umbrella worktrees need the umbrella folder to be a Git repository"); + expect(launched).toHaveLength(0); + }), +); + it.effect("a worktree launch that omits startFromOrigin follows the new-worktree setting", () => Effect.gen(function* () { const cases = [ diff --git a/apps/server/src/mcp/toolkits/project/handlers.ts b/apps/server/src/mcp/toolkits/project/handlers.ts index 7a2fb5381227e..19fc8b378d594 100644 --- a/apps/server/src/mcp/toolkits/project/handlers.ts +++ b/apps/server/src/mcp/toolkits/project/handlers.ts @@ -55,8 +55,19 @@ function worktreeCheckHint( | ThreadLaunch.ThreadLaunchNotRepositoryError, strategy: { readonly startFromOrigin?: boolean | undefined }, ) { - if (error._tag === "ThreadLaunchNotRepositoryError") - return `Use workspaceStrategy: {type: "root"}, or pass the projectId of a Git repository.`; + if (error._tag === "ThreadLaunchNotRepositoryError") { + const nested = error.nestedRepositories ?? []; + const projects = nested.filter((repository) => repository.projectId !== undefined); + const holders = projects.filter((repository) => repository.hasBaseRef); + const candidates = holders.length > 0 ? holders : projects; + const suggestion = + candidates.length === 0 + ? "pass the projectId of a Git repository" + : `pass the projectId of the checkout's own project: ${candidates + .map((repository) => `"${repository.projectId}" (${repository.relativePath})`) + .join(", ")}`; + return `Use workspaceStrategy: {type: "root"}, or ${suggestion}.`; + } if (error._tag === "ThreadLaunchBranchConflictError") { const sibling = error.branch.replaceAll("/", "-"); return `Use a name that does not nest under or contain an existing branch${ diff --git a/apps/server/src/orchestration-v2/CheckpointCaptureService.test.ts b/apps/server/src/orchestration-v2/CheckpointCaptureService.test.ts index 828d438646cdf..3ab81c7f45355 100644 --- a/apps/server/src/orchestration-v2/CheckpointCaptureService.test.ts +++ b/apps/server/src/orchestration-v2/CheckpointCaptureService.test.ts @@ -277,7 +277,7 @@ it.layer(layerProjectionStoreTest)("CheckpointCaptureServiceV2", (it) => { NodeCrypto.layer, Layer.mock(CheckpointStore.CheckpointStore)({ listAuthoredPaths: () => Effect.succeed(null), - isGitRepository: () => Effect.succeed(true), + hasCheckpointWorkspace: () => Effect.succeed(true), captureCheckpoint: () => Effect.void, hasCheckpointRef: () => Effect.fail( @@ -640,7 +640,7 @@ it.layer(layerProjectionStoreTest)("CheckpointCaptureServiceV2", (it) => { IdAllocator.layer, NodeCrypto.layer, Layer.mock(CheckpointStore.CheckpointStore)({ - isGitRepository: () => Effect.succeed(true), + hasCheckpointWorkspace: () => Effect.succeed(true), hasCheckpointRef: () => Effect.succeed(true), captureCheckpoint: () => Effect.void, diffCheckpoints: () => Effect.succeed(""), @@ -1085,7 +1085,7 @@ it.layer(layerProjectionStoreTest)("CheckpointCaptureServiceV2", (it) => { IdAllocator.layer, NodeCrypto.layer, Layer.mock(CheckpointStore.CheckpointStore)({ - isGitRepository: gitUnavailable, + hasCheckpointWorkspace: gitUnavailable, captureCheckpoint: gitUnavailable, hasCheckpointRef: gitUnavailable, }), diff --git a/apps/server/src/orchestration-v2/CheckpointRollbackService.ts b/apps/server/src/orchestration-v2/CheckpointRollbackService.ts index 8924a3eb9a78b..09b6c26ecf643 100644 --- a/apps/server/src/orchestration-v2/CheckpointRollbackService.ts +++ b/apps/server/src/orchestration-v2/CheckpointRollbackService.ts @@ -21,6 +21,7 @@ import * as GitWorkflowService from "../git/GitWorkflowService.ts"; import type * as ServerConfig from "../config.ts"; import type * as ServerSettings from "../serverSettings.ts"; import { makeIsManagedWorktreePath } from "../worktreesDirectory.ts"; +import { makeUmbrellaWorktrees } from "../project/UmbrellaWorktree.ts"; import { withCheckpointRestoreReservation, withWorkspaceLease, @@ -139,6 +140,7 @@ export const layer: Layer.Layer< const path = yield* Path.Path; const threadCommands = yield* ThreadCommandExecutor.ThreadCommandExecutor; const isManagedWorktreePath = yield* makeIsManagedWorktreePath; + const umbrellaWorktrees = yield* makeUmbrellaWorktrees; const execute = Effect.fn("orchestrationV2.checkpointRollback.execute")(function* (input: { readonly threadId: ThreadId; @@ -238,7 +240,15 @@ export const layer: Layer.Layer< const { worktreePath, branch } = context.thread; // Recreated only where the server would have made it, as turn start does. - if (worktreePath != null && branch != null) { + if ( + worktreePath != null && + branch != null && + (yield* umbrellaWorktrees.read(worktreePath)) !== null && + (yield* isManagedWorktreePath(worktreePath)) + ) { + // Each missing repository comes back on its own; a folder with files in it is left alone. + yield* umbrellaWorktrees.restoreMissing({ worktreePath, branch }); + } else if (worktreePath != null && branch != null) { // A failed removal can leave the folder without its checkout; only a file restore replaces it. const leftover = restoreFiles && diff --git a/apps/server/src/orchestration-v2/CheckpointService.test.ts b/apps/server/src/orchestration-v2/CheckpointService.test.ts index 62fa68c4c53af..69bb0ecc07344 100644 --- a/apps/server/src/orchestration-v2/CheckpointService.test.ts +++ b/apps/server/src/orchestration-v2/CheckpointService.test.ts @@ -58,7 +58,7 @@ it.effect( Layer.mergeAll( IdAllocator.layer, Layer.mock(CheckpointStore.CheckpointStore)({ - isGitRepository: () => Effect.succeed(true), + hasCheckpointWorkspace: () => Effect.succeed(true), hasCheckpointRef: () => Effect.succeed(false), captureCheckpoint: () => Effect.fail(captureError), }), @@ -127,7 +127,7 @@ it.effect( Layer.mergeAll( IdAllocator.layer, Layer.mock(CheckpointStore.CheckpointStore)({ - isGitRepository: () => Effect.succeed(true), + hasCheckpointWorkspace: () => Effect.succeed(true), hasCheckpointRef: ({ checkpointRef }) => Ref.get(refs).pipe(Effect.map((current) => current.has(checkpointRef))), captureCheckpoint: ({ checkpointRef }) => @@ -195,7 +195,7 @@ it.effect("records a repository probe failure as an error checkpoint, not a miss Layer.mergeAll( IdAllocator.layer, Layer.mock(CheckpointStore.CheckpointStore)({ - isGitRepository: () => + hasCheckpointWorkspace: () => Effect.fail( new VcsProcessExitError({ operation: "GitVcsDriver.detectRepository", diff --git a/apps/server/src/orchestration-v2/CheckpointService.ts b/apps/server/src/orchestration-v2/CheckpointService.ts index 3e0fbe95e8aa4..b53e3cae39209 100644 --- a/apps/server/src/orchestration-v2/CheckpointService.ts +++ b/apps/server/src/orchestration-v2/CheckpointService.ts @@ -252,7 +252,7 @@ export const layer: Layer.Layer< // A failed probe is an operational error, not proof that the workspace has no repository. const probeRepository = (scope: OrchestrationV2CheckpointScope) => - checkpointStore.isGitRepository(scope.cwd).pipe( + checkpointStore.hasCheckpointWorkspace(scope.cwd).pipe( Effect.map((isRepository) => isRepository ? ("repository" as const) : ("missing" as const), ), @@ -268,7 +268,7 @@ export const layer: Layer.Layer< withWorkspaceLock( input.scope.cwd, Effect.gen(function* () { - if (!(yield* checkpointStore.isGitRepository(input.scope.cwd))) { + if (!(yield* checkpointStore.hasCheckpointWorkspace(input.scope.cwd))) { return; } diff --git a/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts b/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts index e6e29a1b34a76..6a4e2982d3198 100644 --- a/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts +++ b/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts @@ -143,6 +143,8 @@ const layerTest = Layer.mergeAll( }), request: () => Effect.void, readRepositoryIdentity: () => Effect.succeed(null), + peekNestedRepositories: () => Effect.succeed([]), + readNestedRepositories: () => Effect.succeed([]), getAvailable: () => Effect.succeed({ repositoryIdentity: null, diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 2805935d38890..d48ec5df802e6 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -4917,9 +4917,13 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio command.source !== "stack" && command.source !== "stack-dismissed"; if (existing && !undismisses) return thread; - const link = existing + // A relinked pull request starts fresh: notices owed to the unlinked one's watch lapse. + const relinked = existing + ? (({ endedWatch: _endedWatch, ...kept }) => kept)(existing) + : undefined; + const link = relinked ? { - ...existing, + ...relinked, source: command.source, url: canonicalizeGitCafePullRequestUrl(command.url), ...(command.repositoryWebUrl !== undefined && { @@ -4962,7 +4966,10 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ]; } else if (command.type === "thread.pull-request.unlink") { if (!existing) return thread; - const belongsToStack = + // Agent links can come back on their own (umbrella member discovery), so an unlinked + // one is kept dismissed rather than dropped. + const keepDismissed = + existing.source === "agent" || existing.source === "stack" || existing.stack !== null || links.some( @@ -4971,7 +4978,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio link.repository.toLowerCase() === key.repository && link.stack?.layers.some((layer) => layer.number === key.number), ); - pullRequests = belongsToStack + pullRequests = keepDismissed ? links.map((link) => link === existing ? { diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts index 7b0759ae99b0b..51e7ccfd06261 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts @@ -84,6 +84,17 @@ const isDomainEvent = Schema.is(OrchestrationV2DomainEvent); const managedWorktreesDir = "/tmp/provider-turn-start-worktrees"; // fs.realpath applies `..` and `.` before following symlinks. +// No folder here is an umbrella worktree. +const noUmbrellaManifest = (target: string) => + Effect.fail( + PlatformError.systemError({ + _tag: "NotFound", + module: "FileSystem", + method: "readFileString", + pathOrDescriptor: target, + }), + ); + const normalize = (target: string) => { const parts: Array = []; for (const part of target.split("/")) { @@ -165,6 +176,7 @@ function startWithMissingWorktree( Layer.mock(TurnItemPositionStore.TurnItemPositionStoreV2)({}), Layer.succeed(FileSystem.FileSystem, { exists: () => Effect.succeed(false), + readFileString: noUmbrellaManifest, realPath: (target: string) => normalize(target) in realPaths ? Effect.succeed(realPaths[normalize(target)]) @@ -301,6 +313,7 @@ const layerRestoreLeaseTest = layerThreadWorktreeRestore.pipe( Layer.succeed(FileSystem.FileSystem, { exists: restoreLeaseExists, realPath: (target: string) => Effect.succeed(normalize(target)), + readFileString: noUmbrellaManifest, } as never), layerWorktreeLocation(), Layer.mock(GitWorkflow.GitWorkflowService)({ @@ -365,6 +378,7 @@ it.each([ exists: () => Effect.succeed(false), realPath: (target: string) => Effect.succeed(target), makeDirectory, + readFileString: noUmbrellaManifest, } as never), Path.layer, Layer.mock(ServerConfig.ServerConfig)({ diff --git a/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts b/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts index c9316bd231fc1..8679e9ab2166f 100644 --- a/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts +++ b/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts @@ -29,6 +29,7 @@ import { ThreadId, TextGenerationError, ServerSettingsError, + type UmbrellaMember, VcsProcessExitError, } from "@t3tools/contracts"; import * as Cause from "effect/Cause"; @@ -52,6 +53,8 @@ import * as ProjectStore from "./ProjectStore.ts"; import * as ProjectService from "../project/ProjectService.ts"; import * as ProjectSetupScriptRunner from "../project/ProjectSetupScriptRunner.ts"; import * as ManagedProjectFolders from "../project/ManagedProjectFolders.ts"; +import * as UmbrellaMembership from "../project/UmbrellaMembership.ts"; +import { readUmbrellaWorktree } from "../project/umbrellaWorktreeLayout.ts"; import * as ProviderRegistryMock from "../provider/testUtils/providerRegistryMock.ts"; import * as ServerSettings from "../serverSettings.ts"; import * as ScheduledTasks from "../scheduledTasks/ScheduledTaskService.ts"; @@ -139,6 +142,10 @@ interface HarnessOptions { readonly providers?: ReadonlyArray; readonly git?: Partial; readonly isGitRepository?: CheckpointStore.CheckpointStore["Service"]["isGitRepository"]; + readonly umbrellaMembers?: ReadonlyArray; + /** Checkouts a plain folder holds before its umbrella is turned on. */ + readonly umbrellaSuggestions?: ReadonlyArray; + readonly getByWorkspaceRoot?: ProjectService.ProjectService["Service"]["getByWorkspaceRoot"]; } function makeHarness(options: HarnessOptions = {}) { @@ -206,7 +213,7 @@ function makeHarness(options: HarnessOptions = {}) { ? Option.some(otherProject) : Option.none(), ), - getByWorkspaceRoot: () => Effect.succeedSome(project), + getByWorkspaceRoot: options.getByWorkspaceRoot ?? (() => Effect.succeedSome(project)), workspaceScanDirectory: () => Effect.die("unused"), snapshot: Effect.die("unused"), getShell: () => Effect.die("unused"), @@ -255,6 +262,20 @@ function makeHarness(options: HarnessOptions = {}) { layerReceipts, layerOrchestrator, IdAllocator.layer, + NodeServices.layer, + ServerConfig.layerTest(process.cwd(), { prefix: "t3-thread-launch-" }).pipe( + Layer.provide(NodeServices.layer), + ), + options.umbrellaMembers === undefined && options.umbrellaSuggestions === undefined + ? Layer.empty + : Layer.mock(UmbrellaMembership.UmbrellaMembership)({ + stateOf: () => + Effect.succeed({ + members: options.umbrellaMembers ?? [], + suggestions: options.umbrellaSuggestions ?? [], + enclosingRepository: null, + }), + }), options.getLaunchSettings === undefined ? Layer.empty : Layer.mock(ServerSettings.ServerSettingsService)({ @@ -3146,6 +3167,259 @@ it.effect.each(["origin/master", ":/initial"])( }), ); +it.effect("checks out every member of an umbrella inside the root's own worktree", () => + Effect.gen(function* () { + const folder = yield* (yield* FileSystem.FileSystem).makeTempDirectoryScoped({ + prefix: "t3-umbrella-thread-", + }); + const members: ReadonlyArray = [ + { path: "/repo/api", relativePath: "api", repositoryIdentity: null, source: "nested" }, + { + path: "/elsewhere/site", + relativePath: "../elsewhere/site", + repositoryIdentity: null, + source: "adopted", + }, + ]; + const setupStarted = yield* Deferred.make(); + const harness = makeHarness({ + umbrellaMembers: members, + hasCommit: () => Effect.succeed(true), + git: { currentBranch: () => Effect.succeed("main") }, + createWorktree: (input) => + Effect.succeed({ + worktree: { path: input.path ?? folder, refName: input.newRefName!, headSha: "abc" }, + } as never), + runSetup: () => + Deferred.succeed(setupStarted, undefined).pipe(Effect.as({ status: "no-script" as const })), + }); + yield* Effect.gen(function* () { + const launches = yield* ThreadLaunch.ThreadLaunchService; + const threads = yield* ThreadManagement.ThreadManagementService; + const workspace = { type: "worktree" as const, baseRef: "HEAD", branch: "feature" }; + yield* launches.checkWorktreeBase({ projectId, workspaceStrategy: workspace }); + const launched = yield* launches.launch( + launchInput({ + command: "command:launch:umbrella", + thread: "thread:launch:umbrella", + workspace, + }), + ); + yield* Deferred.await(setupStarted); + const { thread } = yield* threads.getThreadProjection(launched.threadId); + assert.equal(thread.branch, "feature"); + assert.equal(thread.worktreePath, folder); + const layout = yield* readUmbrellaWorktree(thread.worktreePath!).pipe( + Effect.provide(NodeServices.layer), + ); + assert.deepEqual(layout?.members, [ + { source: "/repo/api", path: "api" }, + { source: "/elsewhere/site", path: "_external/site" }, + ]); + // Members are checked out concurrently, so the call order is not fixed. + assert.deepEqual( + harness.createWorktree.mock.calls + .map(([input]) => [input.cwd, input.path, input.newRefName]) + .toSorted(([a], [b]) => String(a).localeCompare(String(b))), + [ + ["/elsewhere/site", `${folder}/_external/site`, "feature"], + [project.workspaceRoot, null, "feature"], + ["/repo/api", `${folder}/api`, "feature"], + ], + ); + }).pipe(Effect.provide(harness.layer)); + }).pipe(Effect.provide(NodeServices.layer)), +); + +const plainFolderCheckouts: ReadonlyArray = [ + { path: "/repo/app", relativePath: "app", repositoryIdentity: null, source: "nested" }, + { + path: "/repo/dev-setup", + relativePath: "dev-setup", + repositoryIdentity: null, + source: "nested", + }, +]; +const appProjectId = ProjectId.make("project-app"); +// Only `/repo/app` has the base branch, and only it is registered as its own project. +const plainFolderHarness = (options: HarnessOptions = {}) => + makeHarness({ + umbrellaSuggestions: plainFolderCheckouts, + getByWorkspaceRoot: (root) => + Effect.succeed( + root === "/repo/app" + ? Option.some({ ...project, id: appProjectId, title: "app" }) + : Option.none(), + ), + hasCommit: (input) => + Effect.succeed(input.cwd === "/repo/app" && input.refName === "origin/develop"), + ...options, + git: { + repositoryRoot: (cwd) => Effect.succeed(cwd === project.workspaceRoot ? null : cwd), + hasRefNamed: () => Effect.succeed(false), + ...options.git, + }, + }); + +it.effect( + "names a plain folder's checkouts, and which has the base, when refusing its worktree", + () => + Effect.gen(function* () { + const harness = plainFolderHarness(); + yield* Effect.gen(function* () { + const launches = yield* ThreadLaunch.ThreadLaunchService; + const result = yield* launches + .checkWorktreeBase({ + projectId, + workspaceStrategy: { + type: "worktree", + baseRef: "origin/develop", + startFromOrigin: true, + }, + }) + .pipe(Effect.result); + assert.isTrue(Result.isFailure(result)); + if (Result.isFailure(result)) { + const failure = result.failure; + assert.instanceOf(failure, ThreadLaunch.ThreadLaunchNotRepositoryError); + if (failure._tag !== "ThreadLaunchNotRepositoryError") return; + assert.deepEqual(failure.nestedRepositories, [ + { relativePath: "app", projectId: appProjectId, projectTitle: "app", hasBaseRef: true }, + { relativePath: "dev-setup", hasBaseRef: false }, + ]); + assert.include(failure.message, "It holds Git repositories: app, dev-setup."); + assert.include(failure.message, '"origin/develop" is in app (project "app").'); + } + }).pipe(Effect.provide(harness.layer)); + }), +); + +it.effect( + "refuses a plain folder's worktree with its checkouts when preparation skipped the check", + () => + Effect.gen(function* () { + const harness = plainFolderHarness(); + yield* Effect.gen(function* () { + const launches = yield* ThreadLaunch.ThreadLaunchService; + const threads = yield* ThreadManagement.ThreadManagementService; + // launch() alone does not run checkWorktreeBase, as a retried or replayed launch does not. + const launched = yield* launches.launch( + launchInput({ + command: "command:launch:plain-folder", + thread: "thread:launch:plain-folder", + message: "Fix CI", + workspace: { type: "worktree", baseRef: "origin/develop", startFromOrigin: true }, + }), + ); + yield* threads.streamStoredEventsFrom({ threadId: launched.threadId }).pipe( + Stream.filter( + (stored) => + stored.event.type === "run.updated" && stored.event.payload.status === "failed", + ), + Stream.runHead, + ); + const projection = yield* threads.getThreadProjection(launched.threadId); + const message = + projection.turnItems.find((item) => item.type === "error")?.failure.message ?? ""; + assert.include( + message, + "is not a Git repository. It holds Git repositories: app, dev-setup.", + ); + assert.notInclude(message, "VCS driver"); + assert.equal(harness.createWorktree.mock.calls.length, 0); + }).pipe(Effect.provide(harness.layer)); + }), +); + +it.effect("refuses a plain umbrella folder's worktree, naming its members' projects", () => + Effect.gen(function* () { + const harness = plainFolderHarness({ + umbrellaMembers: plainFolderCheckouts, + umbrellaSuggestions: [], + }); + yield* Effect.gen(function* () { + const launches = yield* ThreadLaunch.ThreadLaunchService; + const failure = yield* launches + .checkWorktreeBase({ + projectId, + workspaceStrategy: { type: "worktree", baseRef: "origin/develop" }, + }) + .pipe(Effect.flip); + assert.instanceOf(failure, ThreadLaunch.ThreadLaunchNotRepositoryError); + if (failure._tag !== "ThreadLaunchNotRepositoryError") return; + assert.isTrue(failure.umbrella); + assert.include( + failure.message, + "Umbrella worktrees need the umbrella folder to be a Git repository", + ); + assert.include(failure.message, 'Its member checkouts are app (project "app"), dev-setup.'); + }).pipe(Effect.provide(harness.layer)); + }), +); + +// The umbrella root is a repository with only its own HEAD; members are as above. +const gitRootUmbrella: HarnessOptions = { + umbrellaMembers: plainFolderCheckouts, + umbrellaSuggestions: [], + hasCommit: (input) => + Effect.succeed( + input.cwd === project.workspaceRoot + ? input.refName === "HEAD" + : input.cwd === "/repo/app" && input.refName === "origin/develop", + ), + git: { repositoryRoot: (cwd) => Effect.succeed(cwd) }, +}; + +it.effect("accepts an umbrella base ref that only one of its checkouts has", () => + Effect.gen(function* () { + const harness = plainFolderHarness(gitRootUmbrella); + yield* ThreadLaunch.ThreadLaunchService.pipe( + Effect.flatMap((launches) => + launches.checkWorktreeBase({ + projectId, + workspaceStrategy: { type: "worktree", baseRef: "origin/develop" }, + }), + ), + Effect.provide(harness.layer), + ); + }), +); + +it.effect("refuses an umbrella base ref that none of its checkouts has", () => + Effect.gen(function* () { + const harness = plainFolderHarness({ + ...gitRootUmbrella, + fetchWorktreeBaseCommit: () => Effect.succeed(null), + }); + yield* Effect.gen(function* () { + const launches = yield* ThreadLaunch.ThreadLaunchService; + const result = yield* launches + .checkWorktreeBase({ + projectId, + workspaceStrategy: { type: "worktree", baseRef: "release/9", startFromOrigin: true }, + }) + .pipe(Effect.result); + assert.isTrue(Result.isFailure(result)); + if (Result.isFailure(result)) { + assert.instanceOf(result.failure, ThreadLaunch.ThreadLaunchBaseRefError); + assert.include( + result.failure.message, + 'Base ref "release/9" does not resolve to a commit in project', + ); + assert.include( + result.failure.message, + "or in any of its umbrella checkouts (app, dev-setup).", + ); + } + // HEAD means each checkout's own branch, which every checkout has. + yield* launches.checkWorktreeBase({ + projectId, + workspaceStrategy: { type: "worktree", baseRef: "HEAD" }, + }); + }).pipe(Effect.provide(harness.layer)); + }), +); + it.effect("leaves uncertain Git detection failures to workspace preparation", () => Effect.gen(function* () { const harness = makeHarness({ diff --git a/apps/server/src/orchestration-v2/ThreadLaunchService.ts b/apps/server/src/orchestration-v2/ThreadLaunchService.ts index eb452b883d761..c131346f4db9c 100644 --- a/apps/server/src/orchestration-v2/ThreadLaunchService.ts +++ b/apps/server/src/orchestration-v2/ThreadLaunchService.ts @@ -11,6 +11,7 @@ import { type OrchestrationV2CreationSource, type OrchestrationV2DelegatedFrom, type OrchestrationV2LinkOrigin, + type GitCommandError, type OrchestrationV2ProviderThreadNativeMetadata, type OrchestrationV2ThreadProjection, type ProviderDriverKind, @@ -48,6 +49,10 @@ import { parseGitCloneProgressLine } from "../project/gitCloneProgress.ts"; import * as ProjectService from "../project/ProjectService.ts"; import * as ProjectSetupScriptRunner from "../project/ProjectSetupScriptRunner.ts"; import * as ManagedProjectFolders from "../project/ManagedProjectFolders.ts"; +import * as UmbrellaMembership from "../project/UmbrellaMembership.ts"; +import { makeUmbrellaWorktrees } from "../project/UmbrellaWorktree.ts"; +import { discoverNestedRepositories } from "../project/umbrellaDiscovery.ts"; +import type { UmbrellaWorktreeError } from "../project/umbrellaWorktreeLayout.ts"; import * as ProviderRegistry from "../provider/ProviderRegistry.ts"; import * as ServerSettings from "../serverSettings.ts"; import * as TextGeneration from "../textGeneration/TextGeneration.ts"; @@ -168,11 +173,17 @@ export class ThreadLaunchBaseRefError extends Schema.TaggedError()( "ThreadLaunchNotRepositoryError", { projectId: ProjectId, projectTitle: Schema.String, workspaceRoot: Schema.String, + baseRef: Schema.optional(Schema.String), + nestedRepositories: Schema.optional(Schema.Array(NestedRepository)), + /** The folder is an umbrella, so `nestedRepositories` are its members. */ + umbrella: Schema.optional(Schema.Boolean), }, ) { override get message(): string { - return `Project "${this.projectTitle}" (${this.workspaceRoot}) is not a Git repository.`; + const project = `"${this.projectTitle}" (${this.workspaceRoot})`; + const nested = this.nestedRepositories ?? []; + const named = nested.map(({ relativePath, projectTitle }) => + projectTitle === undefined ? relativePath : `${relativePath} (project "${projectTitle}")`, + ); + const holders = named.filter((_, index) => nested[index]!.hasBaseRef); + const located = holders.length > 0 ? ` "${this.baseRef}" is in ${holders.join(", ")}.` : ""; + if (this.umbrella === true) { + return `Umbrella worktrees need the umbrella folder to be a Git repository, and project ${project} is not one. Its member checkouts are ${named.join(", ")}.${located} To work in a member in a worktree, start the thread in its project.`; + } + const base = `Project ${project} is not a Git repository.`; + if (nested.length === 0) return base; + return `${base} It holds Git repositories: ${nested.map((repository) => repository.relativePath).join(", ")}.${located} To work in one of them, start the thread in its project.`; } } +// Enough to point at the right checkout without listing a whole projects folder. +const MAX_REPORTED_NESTED_REPOSITORIES = 12; + export class ThreadLaunchService extends Context.Service< ThreadLaunchService, { @@ -262,6 +303,93 @@ const make = Effect.gen(function* () { const threads = yield* ThreadManagement.ThreadManagementService; const eventSink = yield* EventSink.EventSinkV2; const managedFolders = yield* ManagedProjectFolders.ManagedProjectFolders; + const umbrellaWorktrees = yield* makeUmbrellaWorktrees; + const umbrellaMembership = yield* Effect.serviceOption(UmbrellaMembership.UmbrellaMembership); + // An umbrella's worktree mode checks out every member inside the root's own worktree. + const umbrellaMembersOf = yield* UmbrellaMembership.makeUmbrellaMembersOf; + /** Whether `refName` names a commit in the checkout at `cwd`, without asking a remote. */ + const refResolvesLocally = (cwd: string, refName: string) => + // `:/text` is a commit search, which cannot be asked for a commit type. + refName.startsWith(":") + ? Effect.succeed(true) + : git.hasCommit({ cwd, refName: refName === "-" ? "@{-1}" : refName }).pipe( + Effect.filterOrElse( + (found) => found, + () => git.hasRefNamed({ cwd, refName }), + ), + Effect.orElseSucceed(() => false), + ); + /** As refResolvesLocally, then asks the checkout's remote when the launch starts from origin. */ + const refResolvesInCheckout = (cwd: string, refName: string, startFromOrigin: boolean) => + refResolvesLocally(cwd, refName).pipe( + Effect.filterOrElse( + (found) => found || !startFromOrigin, + () => + git.resolveWorktreeBaseRemote({ cwd, refName }).pipe( + Effect.flatMap((remote) => + remote === null + ? Effect.succeed(false) + : git + .fetchWorktreeBaseCommit({ cwd, refName, remote }) + .pipe(Effect.map((fetched) => fetched !== null)), + ), + Effect.orElseSucceed(() => false), + ), + ), + ); + // A plain folder's checkouts or umbrella members, so a refused worktree launch can say where + // to start instead. + const notRepository = Effect.fn("ThreadLaunchService.notRepository")(function* ( + project: { readonly id: ProjectId; readonly title: string; readonly workspaceRoot: string }, + baseRef: string, + ) { + const state = Option.isNone(umbrellaMembership) + ? undefined + : yield* umbrellaMembership.value.stateOf(project); + const root = project.workspaceRoot.replaceAll("\\", "/").replace(/\/+$/, ""); + const checkouts = + state !== undefined + ? [...state.members, ...state.suggestions] + : (yield* discoverNestedRepositories(project.workspaceRoot)).map((checkoutPath) => { + const normalized = checkoutPath.replaceAll("\\", "/"); + return { + path: checkoutPath, + relativePath: normalized.startsWith(`${root}/`) + ? normalized.slice(root.length + 1) + : normalized, + }; + }); + const nestedRepositories = yield* Effect.forEach( + checkouts.slice(0, MAX_REPORTED_NESTED_REPOSITORIES), + (checkout) => + Effect.all( + [ + projects + .getByWorkspaceRoot(checkout.path) + .pipe(Effect.orElseSucceed(() => Option.none())), + refResolvesLocally(checkout.path, baseRef), + ], + { concurrency: "unbounded" }, + ).pipe( + Effect.map(([owner, hasBaseRef]) => ({ + relativePath: checkout.relativePath, + ...(Option.isSome(owner) + ? { projectId: owner.value.id, projectTitle: owner.value.title } + : {}), + hasBaseRef, + })), + ), + { concurrency: 4 }, + ); + return yield* new ThreadLaunchNotRepositoryError({ + projectId: project.id, + projectTitle: project.title, + workspaceRoot: project.workspaceRoot, + baseRef, + nestedRepositories, + ...(state !== undefined && state.members.length > 0 ? { umbrella: true } : {}), + }); + }); // A project-folder launch that names no branch records the folder's checkout, as the composer does. const launchBranch = (strategy: ThreadLaunchWorkspaceStrategy, workspaceRoot: string) => strategy.type === "root" && strategy.branch === undefined @@ -394,13 +522,9 @@ const make = Effect.gen(function* () { ], { concurrency: "unbounded" }, ); - if (repositoryRoot === null) - return yield* new ThreadLaunchNotRepositoryError({ - projectId: project.id, - projectTitle: project.title, - workspaceRoot: cwd, - }); - const baseResolves = + if (repositoryRoot === null) return yield* notRepository(project, baseRef); + const umbrellaMembers = yield* umbrellaMembersOf(project); + const rootResolves = hasBaseCommit || (yield* Effect.gen(function* () { if (strategy.startFromOrigin === true) { @@ -416,12 +540,25 @@ const make = Effect.gen(function* () { if (yield* git.hasRefNamed({ cwd, refName: baseRef })) return true; return !(yield* git.hasCommit({ cwd, refName: "HEAD" })); }).pipe(Effect.orElseSucceed(() => true))); + // An umbrella checkout without the base ref starts from its own checkout, so one with it is enough. + const umbrellaResolves = Effect.gen(function* () { + if (baseRef === "HEAD") return true; + for (const member of umbrellaMembers) { + if (yield* refResolvesInCheckout(member.path, baseRef, strategy.startFromOrigin === true)) + return true; + } + return false; + }); + const baseResolves = rootResolves || (umbrellaMembers.length > 0 && (yield* umbrellaResolves)); if (!baseResolves) return yield* new ThreadLaunchBaseRefError({ projectId: project.id, projectTitle: project.title, workspaceRoot: project.workspaceRoot, baseRef, + ...(umbrellaMembers.length === 0 + ? {} + : { umbrellaCheckouts: umbrellaMembers.map((member) => member.relativePath) }), }); // Provisioning flattens temporary names that collide, so only explicit names are refused. if (!checksBranch) return; @@ -616,18 +753,70 @@ const make = Effect.gen(function* () { input.workspaceStrategy.type === "existing_worktree" ? input.workspaceStrategy.worktreePath : null; - if (input.workspaceStrategy.type === "worktree") { - if (runId !== null) { - yield* threads - .dispatch({ - type: "prepared-run.progress", - commandId: CommandId.make(`${input.commandId}:progress:worktree`), - threadId, - runId, - phase: "worktree", - }) - .pipe(Effect.mapError(mapError(input, "update-thread", threadId))); - } + const umbrellaMembers = + input.workspaceStrategy.type === "worktree" ? yield* umbrellaMembersOf(project) : []; + // A retried or replayed launch skips checkWorktreeBase; refuse a plain folder the same way + // rather than with Git's driver error, and say which checkouts it holds. + if ( + input.workspaceStrategy.type === "worktree" && + (yield* git + .repositoryRoot(project.workspaceRoot) + .pipe(Effect.orElseSucceed(() => undefined))) === null + ) { + return yield* notRepository(project, input.workspaceStrategy.baseRef).pipe( + Effect.mapError(mapError(input, "provision-worktree", threadId)), + ); + } + if (input.workspaceStrategy.type === "worktree" && runId !== null) { + yield* threads + .dispatch({ + type: "prepared-run.progress", + commandId: CommandId.make(`${input.commandId}:progress:worktree`), + threadId, + runId, + phase: "worktree", + }) + .pipe(Effect.mapError(mapError(input, "update-thread", threadId))); + } + if (input.workspaceStrategy.type === "worktree" && umbrellaMembers.length > 0) { + const startFromOrigin = input.workspaceStrategy.startFromOrigin === true; + yield* setupTracker.stageStatus(threadId, "fetch", startFromOrigin ? "running" : "skipped"); + yield* setupTracker.stageStatus(threadId, "checkout", "running"); + const submodules = yield* serverSettings.getSettings.pipe( + Effect.map( + (settings) => + resolveProjectSettings(settings, input.projectId).settings.worktreeSubmodules, + ), + Effect.orElseSucceed(() => null), + ); + const created = yield* umbrellaWorktrees + .create({ + umbrellaRoot: project.workspaceRoot, + members: umbrellaMembers, + baseRef: input.workspaceStrategy.baseRef, + startFromOrigin, + branch: branch!, + flattenOnConflict: generatedTemporaryBranch || isTemporaryWorktreeBranch(branch!), + submodules, + }) + .pipe(Effect.mapError(mapError(input, "provision-worktree", threadId))); + worktreePath = created.path; + branch = created.branch; + createdWorktreePath = worktreePath; + createdBranch = branch; + if (startFromOrigin) yield* setupTracker.stageStatus(threadId, "fetch", "done"); + yield* setupTracker.update(threadId, (snapshot) => ({ + ...snapshot, + worktreePath, + branch, + stages: snapshot.stages.map((stage) => + stage.id === "submodules" && stage.status === "pending" + ? { ...stage, status: "skipped", detail: "none" } + : stage, + ), + })); + yield* setupTracker.stageStatus(threadId, "checkout", "done"); + } else if (input.workspaceStrategy.type === "worktree") { const requestedBaseRef = input.workspaceStrategy.baseRef; let startRef = requestedBaseRef; let baseRefName = requestedBaseRef; @@ -823,7 +1012,7 @@ const make = Effect.gen(function* () { const worktreeCwd = worktreePath; branchRename = yield* generateBranchNameFor(worktreeCwd, initialMessage).pipe( Effect.flatMap(({ branch: newBranch, exactName }) => - git + umbrellaWorktrees .renameBranch({ cwd: worktreeCwd, oldBranch, @@ -1042,41 +1231,54 @@ const make = Effect.gen(function* () { if (branchRename !== null) yield* Fiber.interrupt(branchRename); const removedPath = createdWorktreePath; const removedBranch = createdBranch; + const umbrellaWorktree = (yield* umbrellaWorktrees.read(removedPath)) !== null; // Forget worktrees only after removal succeeds; failed removals must not reuse partially written checkouts. - yield* git - .removeWorktree({ cwd: project.workspaceRoot, path: removedPath, force: true }) - .pipe( - Effect.andThen( - removedBranch === null - ? Effect.void - : git - .deleteLocalBranch({ - cwd: project.workspaceRoot, - refName: removedBranch, - force: true, - }) - .pipe(Effect.ignoreCause({ log: true })), - ), - Effect.andThen( - threads - .dispatch({ - type: "thread.metadata.update", - commandId: CommandId.make(`${input.commandId}:cancel-workspace`), - threadId, - worktreePath: null, - branch: null, + const removal: Effect.Effect = + umbrellaWorktree + ? umbrellaWorktrees + .remove({ + worktreePath: removedPath, + force: true, + ...(removedBranch === null ? {} : { deleteBranch: removedBranch }), }) - .pipe(Effect.ignore), - ), - Effect.catchCause((removeCause) => - Effect.logWarning("Failed to remove an abandoned thread worktree", { - commandId: input.commandId, - threadId, + .pipe(Effect.asVoid) + : git.removeWorktree({ + cwd: project.workspaceRoot, path: removedPath, - cause: removeCause, - }), - ), - ); + force: true, + }); + yield* removal.pipe( + Effect.andThen( + umbrellaWorktree || removedBranch === null + ? Effect.void + : git + .deleteLocalBranch({ + cwd: project.workspaceRoot, + refName: removedBranch, + force: true, + }) + .pipe(Effect.ignoreCause({ log: true })), + ), + Effect.andThen( + threads + .dispatch({ + type: "thread.metadata.update", + commandId: CommandId.make(`${input.commandId}:cancel-workspace`), + threadId, + worktreePath: null, + branch: null, + }) + .pipe(Effect.ignore), + ), + Effect.catchCause((removeCause) => + Effect.logWarning("Failed to remove an abandoned thread worktree", { + commandId: input.commandId, + threadId, + path: removedPath, + cause: removeCause, + }), + ), + ); } }), ), diff --git a/apps/server/src/orchestration-v2/ThreadPullRequestService.test.ts b/apps/server/src/orchestration-v2/ThreadPullRequestService.test.ts index bd7154dae96ae..f14d8daa2c6a4 100644 --- a/apps/server/src/orchestration-v2/ThreadPullRequestService.test.ts +++ b/apps/server/src/orchestration-v2/ThreadPullRequestService.test.ts @@ -26,6 +26,7 @@ import * as BackgroundPolicy from "../background/BackgroundPolicy.ts"; import * as GitManager from "../git/GitManager.ts"; import * as ProjectStore from "./ProjectStore.ts"; import * as RepositoryIdentityResolver from "../project/RepositoryIdentityResolver.ts"; +import * as UmbrellaMembership from "../project/UmbrellaMembership.ts"; import * as PullRequestService from "../pullRequest/PullRequestService.ts"; import * as ServerActivation from "../serverActivation.ts"; import * as ProjectionStore from "./ProjectionStore.ts"; @@ -181,6 +182,179 @@ describe("ThreadPullRequestServiceV2 reads", () => { }), ); + it.effect.each([ + { worktreePath: null, checkout: "/clients/acme/apps/api" }, + // A worktree-mode thread looks its members up in their worktrees inside its folder. + { worktreePath: "/worktrees/acme/feature-1", checkout: "/worktrees/acme/feature-1/apps/api" }, + ])( + "links the branch pull request of each umbrella member a turn edited in $checkout", + ({ worktreePath, checkout }) => + Effect.gen(function* () { + // The user unlinked this member's pull request earlier; it stays unlinked and is not looked up. + const thread: OrchestrationV2ThreadShell = { + ...threadShell("umbrella-thread"), + worktreePath, + pullRequests: [ + { + host: "github.com", + repository: "acme/linked", + number: 3, + url: "https://github.com/acme/linked/pull/3", + source: "stack-dismissed", + linkedAt: "2026-09-01T00:00:00.000Z", + snapshot: null, + stack: null, + }, + ], + }; + const project: OrchestrationProjectShell = { + id: thread.projectId, + title: "Client", + workspaceRoot: "/clients/acme", + defaultModelSelection: null, + scripts: [], + createdAt: "2026-08-01T00:00:00.000Z", + updatedAt: "2026-08-01T00:00:00.000Z", + }; + const member = (relativePath: string) => ({ + path: `/clients/acme/${relativePath}`, + relativePath, + repositoryIdentity: + relativePath === "apps/linked" + ? { + canonicalKey: "github.com/acme/linked", + locator: { source: "git-remote" as const, remoteName: "origin", remoteUrl: "x" }, + owner: "acme", + name: "linked", + } + : null, + source: "nested" as const, + }); + const domainEvents = yield* Queue.unbounded(); + const lookups: Array = []; + const dispatched: Array = []; + const linked = yield* Deferred.make(); + const dependencies = Layer.mergeAll( + Layer.mock(Orchestrator.OrchestratorV2)({ + streamDomainEvents: Stream.fromQueue(domainEvents), + getPullRequestSnapshot: () => + Effect.succeed({ + schemaVersion: 2, + snapshotSequence: 1, + threads: [], + archivedThreads: [], + }), + getThreadShell: () => Effect.succeed(thread), + dispatch: (command) => + Effect.sync(() => { + dispatched.push(command as OrchestrationV2ServerCommand); + }).pipe(Effect.andThen(Deferred.succeed(linked, undefined))) as never, + }), + Layer.mock(ProjectStore.ProjectStoreV2)({ + listShells: () => Effect.succeed([project]), + getShell: () => Effect.succeedSome(project), + }), + Layer.mock(GitManager.GitManager)({ + localStatus: ({ cwd }) => + Effect.succeed({ + isRepo: true, + hasPrimaryRemote: true, + isDefaultRef: false, + refName: `feature/${cwd.split("/").at(-1)}`, + hasWorkingTreeChanges: false, + workingTree: { files: [], insertions: 0, deletions: 0 }, + }), + branchPullRequest: ({ cwd, branch }) => + Effect.sync(() => { + lookups.push(`${cwd}@${branch}`); + return { + number: 12, + title: "API change", + url: "https://github.com/acme/api/pull/12", + baseRef: "main", + headRef: branch, + state: "open" as const, + repositoryKey: "github.com/acme/api", + updatedAt: null, + }; + }), + }), + Layer.mock(PullRequestService.PullRequestService)({ + notifyLinkedThreadsChanged: Effect.void, + }), + Layer.mock(RepositoryIdentityResolver.RepositoryIdentityResolver)({}), + Layer.mock(BackgroundPolicy.BackgroundPolicy)({ + shouldRunScopeWork: () => Effect.succeed(false), + shouldRunOpportunisticWork: Effect.succeed(false), + }), + Layer.mock(UmbrellaMembership.UmbrellaMembership)({ + stateOf: () => + Effect.succeed({ + members: [member("apps/api"), member("apps/web"), member("apps/linked")], + suggestions: [], + enclosingRepository: null, + }), + }), + Layer.succeed( + SecureRandom.SecureRandom, + SecureRandom.make((size) => new Uint8Array(size).fill(1)), + ), + FileSystem.layerNoop({ + readFileString: (file) => + file === `${worktreePath}.t3-umbrella.json` + ? Effect.succeed( + JSON.stringify({ + version: 1, + umbrellaRoot: "/clients/acme", + members: ["apps/api", "apps/web", "apps/linked"].map((relativePath) => ({ + source: `/clients/acme/${relativePath}`, + path: relativePath, + })), + }), + ) + : Effect.fail( + PlatformError.systemError({ + _tag: "NotFound", + module: "FileSystem", + method: "readFileString", + pathOrDescriptor: file, + }), + ), + }), + Path.layer, + ); + yield* Effect.gen(function* () { + const service = yield* ThreadPullRequestService.make; + yield* service.start(); + yield* Queue.offer(domainEvents, { + type: "checkpoint.captured", + threadId: thread.id, + payload: { + files: [ + { path: "apps/api/src/server.ts" }, + { path: "apps/linked/index.ts" }, + { path: "README.md" }, + ], + }, + } as unknown as OrchestrationV2DomainEvent); + yield* Deferred.await(linked); + yield* service.drain; + + expect(lookups).toEqual([`${checkout}@feature/api`]); + expect(dispatched).toMatchObject([ + { + type: "thread.pull-request.link", + threadId: thread.id, + host: "github.com", + repository: "acme/api", + number: 12, + source: "agent", + }, + ]); + }).pipe(Effect.provide(dependencies)); + }), + ); + it.effect("refreshes linked-thread readers at most every 10s while activity reorders them", () => Effect.gen(function* () { const link = { diff --git a/apps/server/src/orchestration-v2/ThreadPullRequestService.ts b/apps/server/src/orchestration-v2/ThreadPullRequestService.ts index 559ea7677aac0..6be1e6fe27510 100644 --- a/apps/server/src/orchestration-v2/ThreadPullRequestService.ts +++ b/apps/server/src/orchestration-v2/ThreadPullRequestService.ts @@ -23,13 +23,20 @@ import * as Stream from "effect/Stream"; import * as BackgroundPolicy from "../background/BackgroundPolicy.ts"; import * as GitManager from "../git/GitManager.ts"; +import { pullRequestKeyOf } from "../git/linkCreatedPullRequest.ts"; import * as GitVcsDriver from "../vcs/GitVcsDriver.ts"; import * as ProjectStore from "./ProjectStore.ts"; import * as PullRequestService from "../pullRequest/PullRequestService.ts"; import { makeLinkedThreadsChangeDetector } from "../pullRequest/linkedThreads.ts"; import * as RepositoryIdentityResolver from "../project/RepositoryIdentityResolver.ts"; +import * as UmbrellaMembership from "../project/UmbrellaMembership.ts"; +import { makeReadUmbrellaWorktree } from "../project/umbrellaWorktreeLayout.ts"; import { forkParked } from "../serverActivation.ts"; import { sourceControlDefinitions } from "../sourceControl/sourceControlDefinitions.ts"; +import { + threadPullRequestKeysEqual, + threadPullRequestsOf, +} from "../sourceControl/threadPullRequests.ts"; import { makeNoPullRequestRechecks } from "./noPullRequestRechecks.ts"; import * as Orchestrator from "./Orchestrator.ts"; @@ -122,7 +129,9 @@ export const make = Effect.gen(function* () { const random = yield* SecureRandom.SecureRandom; const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; + const readUmbrellaWorktree = yield* makeReadUmbrellaWorktree; const backgroundPolicy = yield* BackgroundPolicy.BackgroundPolicy; + const umbrellaMembership = yield* Effect.serviceOption(UmbrellaMembership.UmbrellaMembership); const pendingBackfill = new Map(); const noPullRequestRechecks = makeNoPullRequestRechecks(); @@ -423,6 +432,105 @@ export const make = Effect.gen(function* () { ), ); + // A checkpoint lists the umbrella members a turn edited; each one's branch pull request joins + // the thread. A pull request already on the thread, linked or unlinked by the user, is left as + // it is, and a member whose branch already has one is not looked up again. + const linkMemberPullRequests = Effect.fn("ThreadPullRequestServiceV2.linkMemberPullRequests")( + function* (threadId: ThreadId, files: ReadonlyArray<{ readonly path: string }>) { + if (Option.isNone(umbrellaMembership) || files.length === 0) return; + const thread = yield* orchestrator.getThreadShell(threadId); + if (thread === null) return; + const project = yield* projectStore.getShell(thread.projectId); + if (Option.isNone(project)) return; + const members = (yield* umbrellaMembership.value.stateOf(project.value))?.members ?? []; + // A worktree-mode thread works in member worktrees inside its own folder, on its branch. + const layout = + thread.worktreePath === null ? null : yield* readUmbrellaWorktree(thread.worktreePath); + const checkouts = + layout === null + ? members.map((member) => ({ ...member, cwd: member.path, prefix: member.relativePath })) + : layout.members.flatMap((checkout) => { + const member = members.find( + (candidate) => path.resolve(candidate.path) === checkout.source, + ); + return member === undefined + ? [] + : [ + { + ...member, + cwd: path.join(layout.path, checkout.path), + prefix: checkout.path, + }, + ]; + }); + const touched = checkouts.filter((member) => + files.some((file) => file.path.startsWith(`${member.prefix}/`)), + ); + const links = threadPullRequestsOf(thread); + yield* Effect.forEach( + touched, + (member) => + Effect.gen(function* () { + const status = yield* git.localStatus({ cwd: member.cwd }); + if (status.refName === null || status.isDefaultRef) return; + const repository = sourceControlDefinitions + .repositorySelector(member.repositoryIdentity) + ?.toLowerCase(); + if ( + repository !== undefined && + links.some( + (link) => + link.repository.toLowerCase() === repository && + (link.snapshot === null || link.snapshot.headBranch === status.refName), + ) + ) { + return; + } + const detected = yield* git.branchPullRequest( + { cwd: member.cwd, branch: status.refName }, + { refresh: true, confirmTerminal: false }, + ); + if (detected === null || pullRequestPredatesThread(detected, thread.createdAt)) return; + const key = pullRequestKeyOf(detected, member.repositoryIdentity); + if (key === null || links.some((link) => threadPullRequestKeysEqual(link, key))) return; + const uuid = yield* random.uuidV4(); + yield* orchestrator.dispatch({ + type: "thread.pull-request.link", + commandId: CommandId.make(`server:umbrella-pull-request:${thread.id}:${uuid}`), + threadId: thread.id, + ...key, + source: "agent", + }); + }).pipe( + Effect.catchCauseIf( + (cause) => !Cause.hasInterruptsOnly(cause), + (cause) => + Effect.logWarning("umbrella member pull request discovery failed", { + threadId, + member: member.relativePath, + cause: Cause.pretty(cause), + }), + ), + ), + { concurrency: 4, discard: true }, + ); + }, + ); + + const memberWorker = yield* makeDrainableWorker( + (request: { readonly threadId: ThreadId; readonly files: ReadonlyArray<{ path: string }> }) => + linkMemberPullRequests(request.threadId, request.files).pipe( + Effect.provideService(GitVcsDriver.BackgroundGitWork, true), + Effect.catchCauseIf( + (cause) => !Cause.hasInterruptsOnly(cause), + (cause) => + Effect.logWarning("umbrella member pull request refresh failed", { + cause: Cause.pretty(cause), + }), + ), + ), + ); + const enqueueThread = (threadId: ThreadId, refresh: boolean) => Effect.suspend(() => { const queued = queuedThreadRequests.get(threadId); @@ -452,7 +560,15 @@ export const make = Effect.gen(function* () { }; const processEvent = (event: OrchestrationV2DomainEvent) => - Effect.andThen(notifyLinkedThreads(event), refreshForEvent(event)); + Effect.andThen( + notifyLinkedThreads(event), + Effect.andThen( + refreshForEvent(event), + event.type === "checkpoint.captured" && Option.isSome(umbrellaMembership) + ? memberWorker.enqueue({ threadId: event.threadId, files: event.payload.files }) + : Effect.void, + ), + ); const refreshForEvent = (event: OrchestrationV2DomainEvent) => { switch (event.type) { @@ -503,5 +619,8 @@ export const make = Effect.gen(function* () { ); }); - return { start, drain: worker.drain } satisfies ThreadPullRequestServiceV2["Service"]; + return { + start, + drain: Effect.andThen(worker.drain, memberWorker.drain), + } satisfies ThreadPullRequestServiceV2["Service"]; }); diff --git a/apps/server/src/orchestration-v2/http.ts b/apps/server/src/orchestration-v2/http.ts index b58ce1b143119..d2da11fee6b67 100644 --- a/apps/server/src/orchestration-v2/http.ts +++ b/apps/server/src/orchestration-v2/http.ts @@ -21,6 +21,7 @@ import * as ServerEnvironment from "../environment/ServerEnvironment.ts"; import { traceLocalHandlerWork } from "../cloud/traceRelayRequest.ts"; import * as OrchestrationEventStore from "../persistence/OrchestrationEventStore.ts"; import * as ProjectEnrichmentService from "../project/ProjectEnrichmentService.ts"; +import { attachUmbrellaMembers } from "../project/UmbrellaMembership.ts"; import { buildBoundedThreadProjection, decodeThreadHistoryCursor, @@ -77,7 +78,7 @@ export const layer = HttpApiBuilder.group( })), ), { concurrency: 16 }, - ), + ).pipe(Effect.flatMap(attachUmbrellaMembers)), ); const loadShellSnapshot = Effect.fn("http.orchestration.loadShellSnapshot")( diff --git a/apps/server/src/orchestration-v2/runtimeLayer.test.ts b/apps/server/src/orchestration-v2/runtimeLayer.test.ts index b2d12935aa2f8..8d964b2f768b7 100644 --- a/apps/server/src/orchestration-v2/runtimeLayer.test.ts +++ b/apps/server/src/orchestration-v2/runtimeLayer.test.ts @@ -1361,6 +1361,8 @@ const layerSharedApplicationDataPlaneTest = Layer.mergeAll( }), request: () => Effect.void, readRepositoryIdentity: () => Effect.succeed(null), + peekNestedRepositories: () => Effect.succeed([]), + readNestedRepositories: () => Effect.succeed([]), getAvailable: () => Effect.succeed({ repositoryIdentity: null, @@ -4100,6 +4102,30 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => { (yield* orchestrator.getThreadShell(threadId))?.pullRequests?.[0]?.source, "manual", ); + + // A pull request found for an umbrella member stays unlinked once the user unlinks it. + const memberKey = { host: "github.com", repository: "acme/api", number: 12 }; + yield* orchestrator.dispatch({ + type: "thread.pull-request.link", + commandId: CommandId.make("multi-pr-member-link"), + threadId, + ...memberKey, + url: "https://github.com/acme/api/pull/12", + source: "agent", + }); + yield* orchestrator.dispatch({ + type: "thread.pull-request.unlink", + commandId: CommandId.make("multi-pr-member-unlink"), + threadId, + ...memberKey, + }); + assert.isTrue((yield* maintenance.rebuild).valid); + assert.deepEqual( + (yield* orchestrator.getThreadShell(threadId))?.pullRequests + ?.filter((link) => link.repository === "acme/api") + .map(({ number, source }) => ({ number, source })), + [{ number: 12, source: "stack-dismissed" }], + ); }), ); diff --git a/apps/server/src/project/ProjectEnrichmentService.ts b/apps/server/src/project/ProjectEnrichmentService.ts index c08bba24bcceb..96f2920ebe1bc 100644 --- a/apps/server/src/project/ProjectEnrichmentService.ts +++ b/apps/server/src/project/ProjectEnrichmentService.ts @@ -1,6 +1,7 @@ import type { RepositoryIdentity } from "@t3tools/contracts"; import * as Cache from "effect/Cache"; import * as Cause from "effect/Cause"; +import * as Clock from "effect/Clock"; import * as Context from "effect/Context"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; @@ -14,6 +15,7 @@ import type * as Scope from "effect/Scope"; import * as ProjectFaviconResolver from "./ProjectFaviconResolver.ts"; import * as RepositoryIdentityResolver from "./RepositoryIdentityResolver.ts"; +import { discoverNestedRepositories } from "./umbrellaDiscovery.ts"; const DEFAULT_CACHE_CAPACITY = 512; const DEFAULT_MAX_PENDING = 512; @@ -22,6 +24,8 @@ const DEFAULT_SUCCESS_TTL = Duration.minutes(1); // Frequent shell reads scan ~20 files per project; icons change rarely, so cache longer than identities. const DEFAULT_FAVICON_TTL = Duration.minutes(15); const DEFAULT_FAILURE_TTL = Duration.seconds(5); +// Discovery walks folders, so only enabled umbrellas rescan; other roots are scanned once. +const NESTED_REPOSITORIES_RESCAN_AFTER = Duration.minutes(5); export interface ProjectEnrichment { readonly repositoryIdentity: RepositoryIdentity | null; @@ -33,6 +37,8 @@ export interface ProjectEnrichmentChange { readonly workspaceRoot: string; readonly enrichment: ProjectEnrichment; readonly repositoryIdentityResolved: boolean; + /** Set when the change is a new list of checkouts discovered under the root. */ + readonly nestedRepositoriesResolved?: boolean; } export interface ProjectEnrichmentServiceOptions { @@ -50,6 +56,14 @@ export class ProjectEnrichmentService extends Context.Service< readonly readRepositoryIdentity: ( workspaceRoot: string, ) => Effect.Effect; + /** Checkouts found under the root so far, or null before the first scan, which this schedules. */ + readonly peekNestedRepositories: ( + workspaceRoot: string, + options?: { readonly rescanWhenStale?: boolean }, + ) => Effect.Effect | null>; + readonly readNestedRepositories: ( + workspaceRoot: string, + ) => Effect.Effect>; readonly invalidate: (workspaceRoots: Iterable) => Effect.Effect; /** Re-resolves past both identity caches and publishes a found identity, leaving the favicon alone. */ readonly refreshRepositoryIdentity: (workspaceRoot: string) => Effect.Effect; @@ -149,6 +163,27 @@ export const make = Effect.fn("ProjectEnrichmentService.make")(function* ( }), }, ); + // What subscribers last heard per root; direct reads fill the cache without publishing. + const publishedNestedRepositories = new Map>(); + const nestedScannedAt = new Map(); + const nestedRepositoriesCache = yield* Cache.makeWith( + (workspaceRoot: string) => + discoverNestedRepositories(workspaceRoot).pipe( + Effect.tap(() => + Effect.flatMap(Clock.currentTimeMillis, (now) => + Effect.sync(() => nestedScannedAt.set(workspaceRoot, now)), + ), + ), + ), + { capacity: cacheCapacity, timeToLive: () => Duration.infinity }, + ); + const nestedScanIsStale = (workspaceRoot: string) => + Effect.map( + Clock.currentTimeMillis, + (now) => + now - (nestedScannedAt.get(workspaceRoot) ?? 0) >= + Duration.toMillis(NESTED_REPOSITORIES_RESCAN_AFTER), + ); const makeWorkLane = Effect.gen(function* () { const pendingRoots = yield* Ref.make>(new Set()); const queue = yield* Effect.acquireRelease(Queue.dropping(maxPending), (queue) => @@ -158,6 +193,7 @@ export const make = Effect.fn("ProjectEnrichmentService.make")(function* ( }); const repositoryIdentityLane = yield* makeWorkLane; const faviconLane = yield* makeWorkLane; + const nestedRepositoriesLane = yield* makeWorkLane; const changes = yield* Effect.acquireRelease( PubSub.sliding(256), (pubsub) => PubSub.shutdown(pubsub), @@ -183,7 +219,7 @@ export const make = Effect.fn("ProjectEnrichmentService.make")(function* ( const logFailure = ( workspaceRoot: string, - field: "repositoryIdentity" | "faviconPath", + field: "repositoryIdentity" | "faviconPath" | "nestedRepositories", result: Exit.Exit, ) => Exit.isFailure(result) @@ -226,6 +262,30 @@ export const make = Effect.fn("ProjectEnrichmentService.make")(function* ( yield* logFailure(workspaceRoot, "faviconPath", faviconPath); }); + const sameList = (left: ReadonlyArray | undefined, right: ReadonlyArray) => + left !== undefined && + left.length === right.length && + left.every((value, index) => value === right[index]); + + const resolveNestedRepositories = Effect.fn("ProjectEnrichmentService.resolveNestedRepositories")( + function* (workspaceRoot: string) { + const nested = (yield* Cache.has(nestedRepositoriesCache, workspaceRoot)) + ? yield* Cache.refresh(nestedRepositoriesCache, workspaceRoot) + : yield* Cache.get(nestedRepositoriesCache, workspaceRoot); + const published = publishedNestedRepositories.get(workspaceRoot); + publishedNestedRepositories.set(workspaceRoot, nested); + // Rescans of an unchanged folder, or a folder without checkouts, would otherwise push a + // shell frame to every subscriber. + if (sameList(published, nested) || (nested.length === 0 && !published?.length)) return; + yield* PubSub.publish(changes, { + workspaceRoot, + repositoryIdentityResolved: false, + nestedRepositoriesResolved: true, + enrichment: yield* peek(workspaceRoot), + }); + }, + ); + const startWorkers = ( lane: EnrichmentWorkLane, resolve: (workspaceRoot: string) => Effect.Effect, @@ -244,6 +304,7 @@ export const make = Effect.fn("ProjectEnrichmentService.make")(function* ( [ startWorkers(repositoryIdentityLane, resolveRepositoryIdentity), startWorkers(faviconLane, resolveFavicon), + startWorkers(nestedRepositoriesLane, resolveNestedRepositories), ], { concurrency: "unbounded", discard: true }, ); @@ -252,7 +313,7 @@ export const make = Effect.fn("ProjectEnrichmentService.make")(function* ( const requestLane = Effect.fnUntraced(function* ( lane: EnrichmentWorkLane, workspaceRoot: string, - field: "repositoryIdentity" | "faviconPath", + field: "repositoryIdentity" | "faviconPath" | "nestedRepositories", ) { if (!(yield* reservePending(lane, workspaceRoot))) return; yield* Effect.gen(function* () { @@ -319,6 +380,23 @@ export const make = Effect.fn("ProjectEnrichmentService.make")(function* ( return Exit.isSuccess(resolved) ? resolved.value : null; }); + const peekNestedRepositories: ProjectEnrichmentService["Service"]["peekNestedRepositories"] = + Effect.fnUntraced(function* (workspaceRoot, options) { + const cached = yield* Cache.getSuccess(nestedRepositoriesCache, workspaceRoot); + if ( + Option.isNone(cached) || + (options?.rescanWhenStale === true && (yield* nestedScanIsStale(workspaceRoot))) + ) { + yield* requestLane(nestedRepositoriesLane, workspaceRoot, "nestedRepositories"); + } + return Option.getOrNull(cached); + }); + + const readNestedRepositories: ProjectEnrichmentService["Service"]["readNestedRepositories"] = + Effect.fn("ProjectEnrichmentService.readNestedRepositories")((workspaceRoot) => + Cache.get(nestedRepositoriesCache, workspaceRoot), + ); + const invalidate: ProjectEnrichmentService["Service"]["invalidate"] = Effect.fn( "ProjectEnrichmentService.invalidate", )(function* (workspaceRoots) { @@ -331,8 +409,11 @@ export const make = Effect.fn("ProjectEnrichmentService.make")(function* ( Effect.sync(() => { lookupsInFlight.delete(workspaceRoot); lastRepositoryIdentities.delete(workspaceRoot); + publishedNestedRepositories.delete(workspaceRoot); + nestedScannedAt.delete(workspaceRoot); }), Cache.invalidate(faviconCache, workspaceRoot), + Cache.invalidate(nestedRepositoriesCache, workspaceRoot), // The resolver keeps its own misses, which would outlive a clone filling the folder. faviconResolver.invalidate(workspaceRoot), ], @@ -358,6 +439,8 @@ export const make = Effect.fn("ProjectEnrichmentService.make")(function* ( request, getAvailable, readRepositoryIdentity, + peekNestedRepositories, + readNestedRepositories, invalidate, refreshRepositoryIdentity, subscribeChanges: PubSub.subscribe(changes), diff --git a/apps/server/src/project/ProjectService.ts b/apps/server/src/project/ProjectService.ts index 1db031456f2d7..428f2444fbd21 100644 --- a/apps/server/src/project/ProjectService.ts +++ b/apps/server/src/project/ProjectService.ts @@ -37,6 +37,7 @@ import { deletedProjectOverridePatch } from "../provider/ProjectSettingsOverride import { makeIsManagedWorktreePath } from "../worktreesDirectory.ts"; import * as ProcessRunner from "../processRunner.ts"; import * as ProjectEnrichmentService from "./ProjectEnrichmentService.ts"; +import { attachUmbrellaMembers, refreshUmbrellaIndex } from "./UmbrellaMembership.ts"; import { makeIsWorktreeContainer } from "./worktreeContainer.ts"; import * as WorkspacePaths from "../workspace/WorkspacePaths.ts"; @@ -452,6 +453,7 @@ export const make = Effect.gen(function* () { }); if (workspaceRoot !== previousRoot || input.faviconPath !== undefined) { yield* projectEnrichment.invalidate([previousRoot, workspaceRoot]); + yield* refreshUmbrellaIndex; } return yield* readCommitted(input.projectId); }, @@ -586,6 +588,7 @@ export const make = Effect.gen(function* () { yield* clearProjectSettingsOverrides(projectId); } yield* projectEnrichment.invalidate([existing.value.workspaceRoot]); + yield* refreshUmbrellaIndex; return yield* readCommitted(projectId); }, ); @@ -596,6 +599,8 @@ export const make = Effect.gen(function* () { ...shell, repositoryIdentity: enrichment.repositoryIdentity, })), + Effect.flatMap((enriched) => attachUmbrellaMembers([enriched])), + Effect.map(([enriched]) => enriched!), ); const getShell: ProjectService["Service"]["getShell"] = Effect.fn("ProjectService.getShell")( diff --git a/apps/server/src/project/UmbrellaMembership.test.ts b/apps/server/src/project/UmbrellaMembership.test.ts new file mode 100644 index 0000000000000..4b63ea0b28902 --- /dev/null +++ b/apps/server/src/project/UmbrellaMembership.test.ts @@ -0,0 +1,223 @@ +import { it } from "@effect/vitest"; +import { ProjectId, type ServerSettings } from "@t3tools/contracts"; +import * as Deferred from "effect/Deferred"; +import * as Duration from "effect/Duration"; +import * as Effect from "effect/Effect"; +import * as Fiber from "effect/Fiber"; +import * as FileSystem from "effect/FileSystem"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as Path from "effect/Path"; +import * as PubSub from "effect/PubSub"; +import * as Ref from "effect/Ref"; +import * as Stream from "effect/Stream"; +import { describe, expect } from "vite-plus/test"; + +import * as ProjectStore from "../orchestration-v2/ProjectStore.ts"; +import * as ServerActivation from "../serverActivation.ts"; +import * as ServerSettingsService from "../serverSettings.ts"; +import * as UmbrellaMemberIndex from "../vcs/UmbrellaMemberIndex.ts"; +import * as ProjectEnrichmentService from "./ProjectEnrichmentService.ts"; +import * as UmbrellaMembership from "./UmbrellaMembership.ts"; + +describe("umbrellaStateOf", () => { + it.effect("offers discovered checkouts until the user turns the umbrella on", () => + Effect.gen(function* () { + const path = yield* Path.Path; + const state = (settings: { + readonly enabled: boolean; + readonly adopted?: ReadonlyArray; + readonly excluded?: ReadonlyArray; + readonly enclosingRepository?: string; + }) => { + const { members, suggestions, enclosingRepository } = UmbrellaMembership.umbrellaStateOf({ + path, + workspaceRoot: "/clients/acme", + nested: ["/clients/acme/api", "/clients/acme/sites/web", "/clients/acme/legacy"], + settings: { + enabled: settings.enabled, + adopted: settings.adopted ?? [], + excluded: settings.excluded ?? [], + }, + enclosingRepository: settings.enclosingRepository ?? null, + }); + return { + members: members.map((member) => `${member.relativePath}:${member.source}`), + suggestions: suggestions.map((member) => member.relativePath), + enclosingRepository, + }; + }; + + expect(state({ enabled: false })).toEqual({ + members: [], + suggestions: ["api", "legacy", "sites/web"], + enclosingRepository: null, + }); + expect( + state({ enabled: true, adopted: ["/work/acme-mobile", "api"], excluded: ["legacy"] }), + ).toEqual({ + members: ["../../work/acme-mobile:adopted", "api:nested", "sites/web:nested"], + suggestions: [], + enclosingRepository: null, + }); + expect(state({ enabled: true, enclosingRepository: "/clients" })).toEqual({ + members: [], + suggestions: [], + enclosingRepository: "/clients", + }); + }).pipe(Effect.provide(Path.layer)), + ); +}); + +describe("UmbrellaMembership index", () => { + it.effect("applies the newest settings when rebuilds overlap", () => + Effect.gen(function* () { + const projectId = ProjectId.make("acme"); + const root = "/clients/acme"; + const settingsFor = (excluded: ReadonlyArray) => + ({ + projectSettingsOverrides: { + [projectId]: { umbrellaEnabled: true, umbrellaExcludedPaths: [...excluded] }, + }, + }) as unknown as ServerSettings; + const settings = yield* Ref.make(settingsFor([])); + const peeks = yield* Ref.make(0); + const firstPeekEntered = yield* Deferred.make(); + const releaseFirstPeek = yield* Deferred.make(); + const nested = [`${root}/api`, `${root}/web`]; + const index = UmbrellaMemberIndex.makeIndex(); + const changes = yield* PubSub.unbounded(); + // Startup work stays parked, so only the two rebuilds below touch the index. + const neverActivated = yield* Deferred.make(); + + const membership = yield* UmbrellaMembership.make.pipe( + Effect.provide( + Layer.mergeAll( + Layer.succeed(ServerActivation.ServerActivation, Deferred.await(neverActivated)), + FileSystem.layerNoop({ + exists: () => Effect.succeed(false), + realPath: (value) => Effect.succeed(value), + }), + Path.layer, + Layer.mock(ProjectEnrichmentService.ProjectEnrichmentService)({ + readNestedRepositories: () => Effect.succeed(nested), + peekNestedRepositories: () => + Effect.gen(function* () { + if ((yield* Ref.getAndUpdate(peeks, (count) => count + 1)) === 0) { + yield* Deferred.succeed(firstPeekEntered, undefined); + yield* Deferred.await(releaseFirstPeek); + } + return nested; + }), + subscribeChanges: PubSub.subscribe(changes), + }), + Layer.mock(ServerSettingsService.ServerSettingsService)({ + getSettings: Ref.get(settings), + subscribeChanges: Effect.succeed(Stream.never), + }), + Layer.mock(ProjectStore.ProjectStoreV2)({ + listShells: () => + Effect.succeed([ + { + id: projectId, + title: "Acme", + workspaceRoot: root, + defaultModelSelection: null, + scripts: [], + createdAt: "2026-01-01T00:00:00.000Z", + updatedAt: "2026-01-01T00:00:00.000Z", + }, + ]), + }), + ), + ), + Effect.provideService(UmbrellaMemberIndex.UmbrellaMemberIndex, index), + ); + + // Started immediately, an unserialized rebuild would finish before the stale one resumes. + const stale = yield* Effect.forkChild(membership.refreshIndex, { startImmediately: true }); + yield* Deferred.await(firstPeekEntered); + yield* Ref.set(settings, settingsFor([`${root}/web`])); + const fresh = yield* Effect.forkChild(membership.refreshIndex, { startImmediately: true }); + yield* Deferred.succeed(releaseFirstPeek, undefined); + yield* Fiber.join(stale); + yield* Fiber.join(fresh); + + expect(index.membersOf(root).map((member) => member.relativePath)).toEqual(["api"]); + }).pipe(Effect.scoped), + ); +}); + +describe("UmbrellaMembership changes", () => { + it.live("names the umbrellas a root rescan or a member identity changes", () => + Effect.gen(function* () { + const root = "/clients/acme"; + const shell = (id: string, workspaceRoot: string) => ({ + id: ProjectId.make(id), + title: id, + workspaceRoot, + defaultModelSelection: null, + scripts: [], + createdAt: "2026-01-01T00:00:00.000Z", + updatedAt: "2026-01-01T00:00:00.000Z", + }); + const enrichmentChanges = + yield* PubSub.unbounded(); + const change = ( + workspaceRoot: string, + kind: "identity" | "rescan", + ): ProjectEnrichmentService.ProjectEnrichmentChange => ({ + workspaceRoot, + enrichment: { + repositoryIdentity: null, + faviconPath: null, + repositoryIdentityResolved: true, + }, + repositoryIdentityResolved: kind === "identity", + ...(kind === "rescan" ? { nestedRepositoriesResolved: true } : {}), + }); + + const membership = yield* UmbrellaMembership.make.pipe( + Effect.provide( + Layer.mergeAll( + FileSystem.layerNoop({ + exists: () => Effect.succeed(false), + realPath: (value) => Effect.succeed(value), + }), + Path.layer, + Layer.mock(ProjectEnrichmentService.ProjectEnrichmentService)({ + readNestedRepositories: () => Effect.succeed([`${root}/api`]), + peekNestedRepositories: () => Effect.succeed([`${root}/api`]), + subscribeChanges: PubSub.subscribe(enrichmentChanges), + }), + Layer.mock(ServerSettingsService.ServerSettingsService)({ + getSettings: Effect.succeed({ + projectSettingsOverrides: { acme: { umbrellaEnabled: true } }, + } as unknown as ServerSettings), + subscribeChanges: Effect.succeed(Stream.never), + }), + Layer.mock(ProjectStore.ProjectStoreV2)({ + listShells: () => Effect.succeed([shell("acme", root), shell("other", "/other")]), + }), + ), + ), + Effect.provideService( + UmbrellaMemberIndex.UmbrellaMemberIndex, + UmbrellaMemberIndex.makeIndex(), + ), + ); + const changes = yield* membership.subscribeChanges; + const next = Stream.fromSubscription(changes).pipe( + Stream.runHead, + Effect.timeout(Duration.seconds(2)), + ); + + yield* PubSub.publish(enrichmentChanges, change("/other", "identity")); + yield* PubSub.publish(enrichmentChanges, change(`${root}/api`, "identity")); + expect(yield* next).toEqual(Option.some(["acme"])); + + yield* PubSub.publish(enrichmentChanges, change(root, "rescan")); + expect(yield* next).toEqual(Option.some(["acme"])); + }).pipe(Effect.scoped), + ); +}); diff --git a/apps/server/src/project/UmbrellaMembership.ts b/apps/server/src/project/UmbrellaMembership.ts new file mode 100644 index 0000000000000..859405b03d935 --- /dev/null +++ b/apps/server/src/project/UmbrellaMembership.ts @@ -0,0 +1,395 @@ +import type { + ProjectId, + ProjectSettingsOverrides, + ServerSettings as ServerSettingsSchema, + UmbrellaMember, +} from "@t3tools/contracts"; +import * as HostProcess from "@t3tools/shared/HostProcess"; +import * as Context from "effect/Context"; +import * as Duration from "effect/Duration"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as Path from "effect/Path"; +import * as PubSub from "effect/PubSub"; +import * as Schedule from "effect/Schedule"; +import * as Semaphore from "effect/Semaphore"; +import type * as Scope from "effect/Scope"; +import * as Stream from "effect/Stream"; + +import * as ServerConfig from "../config.ts"; +import * as ProjectStore from "../orchestration-v2/ProjectStore.ts"; +import { forkParked } from "../serverActivation.ts"; +import * as ServerSettings from "../serverSettings.ts"; +import { UmbrellaMemberIndex, type UmbrellaMemberCheckout } from "../vcs/UmbrellaMemberIndex.ts"; +import { managedWorktreesDirectories } from "../worktreesDirectory.ts"; +import * as ProjectEnrichmentService from "./ProjectEnrichmentService.ts"; +import { registerUmbrellaWorktreesIn } from "./umbrellaWorktreeLayout.ts"; + +interface UmbrellaProject { + readonly id: ProjectId; + readonly workspaceRoot: string; +} + +interface UmbrellaState { + readonly members: ReadonlyArray; + readonly suggestions: ReadonlyArray; + readonly enclosingRepository: string | null; +} + +const EMPTY_PATHS: ReadonlyArray = []; +const EMPTY_STATE: UmbrellaState = { members: [], suggestions: [], enclosingRepository: null }; + +/** Adopting a checkout turns the umbrella on, so only discovery waits for the user's confirmation. */ +function umbrellaSettingsOf( + overrides: + | Pick< + ProjectSettingsOverrides, + "umbrellaEnabled" | "umbrellaAdoptedPaths" | "umbrellaExcludedPaths" + > + | undefined, +) { + return { + enabled: overrides?.umbrellaEnabled === true, + adopted: overrides?.umbrellaAdoptedPaths ?? EMPTY_PATHS, + excluded: overrides?.umbrellaExcludedPaths ?? EMPTY_PATHS, + }; +} +type UmbrellaSettings = ReturnType; + +/** + * Discovered checkouts plus adopted ones, minus exclusions; a checkout found both ways is nested. + * They are suggestions until the user turns the umbrella on. A root inside another repository's + * work tree cannot be one: that repository's paths are relative to its own top level. + */ +export function umbrellaStateOf(input: { + readonly path: Path.Path; + readonly workspaceRoot: string; + readonly nested: ReadonlyArray; + readonly settings: UmbrellaSettings; + readonly enclosingRepository: string | null; +}): UmbrellaState { + if (input.enclosingRepository !== null) { + return { ...EMPTY_STATE, enclosingRepository: input.enclosingRepository }; + } + const { path, settings } = input; + const root = path.resolve(input.workspaceRoot); + const resolve = (value: string) => path.resolve(root, value); + const excluded = new Set(settings.excluded.map(resolve)); + const sources = new Map(); + for (const nested of input.nested) sources.set(resolve(nested), "nested"); + for (const adopted of settings.adopted) { + const memberPath = resolve(adopted); + if (!sources.has(memberPath)) sources.set(memberPath, "adopted"); + } + const candidates = Array.from(sources, ([memberPath, source]) => ({ + path: memberPath, + relativePath: path.relative(root, memberPath).split(path.sep).join("/"), + repositoryIdentity: null, + source, + })) + .filter((member) => member.path !== root && !excluded.has(member.path)) + .toSorted((left, right) => left.relativePath.localeCompare(right.relativePath)); + if (candidates.length === 0) return EMPTY_STATE; + return settings.enabled + ? { ...EMPTY_STATE, members: candidates } + : { ...EMPTY_STATE, suggestions: candidates }; +} + +const sameSettings = (left: UmbrellaSettings, right: UmbrellaSettings) => + left.enabled === right.enabled && + left.adopted.join("\0") === right.adopted.join("\0") && + left.excluded.join("\0") === right.excluded.join("\0"); + +export class UmbrellaMembership extends Context.Service< + UmbrellaMembership, + { + /** From cached scans and identities, never scanning inline; undefined before the root's first scan. */ + readonly stateOf: (project: UmbrellaProject) => Effect.Effect; + /** Recomputes which checkouts git leaves out, after projects move or go away. */ + readonly refreshIndex: Effect.Effect; + /** Projects whose members may have changed: settings edits, root rescans, member identities. */ + readonly subscribeChanges: Effect.Effect< + PubSub.Subscription>, + never, + Scope.Scope + >; + } +>()("t3/project/UmbrellaMembership") {} + +/** @public */ +export const make = Effect.gen(function* () { + const path = yield* Path.Path; + const fileSystem = yield* FileSystem.FileSystem; + const enrichment = yield* ProjectEnrichmentService.ProjectEnrichmentService; + const settingsService = yield* ServerSettings.ServerSettingsService; + const projectStore = yield* ProjectStore.ProjectStoreV2; + const index = yield* UmbrellaMemberIndex; + const changes = yield* Effect.acquireRelease( + PubSub.sliding>(64), + (pubsub) => PubSub.shutdown(pubsub), + ); + + const readSettings = settingsService.getSettings.pipe( + Effect.map((settings) => settings.projectSettingsOverrides), + Effect.orElseSucceed((): ServerSettingsSchema["projectSettingsOverrides"] => ({})), + ); + + // A folder rarely moves into or out of a repository, so the answer is kept per root. + const enclosingRepositories = new Map(); + const enclosingRepositoryOf = Effect.fnUntraced(function* (workspaceRoot: string) { + const cached = enclosingRepositories.get(workspaceRoot); + if (cached !== undefined) return cached; + const hasGit = (directory: string) => + fileSystem.exists(path.join(directory, ".git")).pipe(Effect.orElseSucceed(() => false)); + let enclosing: string | null = null; + if (!(yield* hasGit(workspaceRoot))) { + let directory = path.dirname(path.resolve(workspaceRoot)); + while (enclosing === null) { + if (yield* hasGit(directory)) enclosing = directory; + const parent = path.dirname(directory); + if (parent === directory) break; + directory = parent; + } + } + enclosingRepositories.set(workspaceRoot, enclosing); + return enclosing; + }); + + const stateFor = Effect.fnUntraced(function* ( + project: UmbrellaProject, + overrides: ServerSettingsSchema["projectSettingsOverrides"], + scan: "peek" | "read", + ) { + const settings = umbrellaSettingsOf(overrides[project.id]); + const nested = + scan === "read" + ? yield* enrichment.readNestedRepositories(project.workspaceRoot) + : yield* enrichment.peekNestedRepositories(project.workspaceRoot, { + rescanWhenStale: settings.enabled, + }); + if (nested === null) return undefined; + return umbrellaStateOf({ + path, + workspaceRoot: project.workspaceRoot, + nested, + settings, + enclosingRepository: yield* enclosingRepositoryOf(project.workspaceRoot), + }); + }); + + const stateOf: UmbrellaMembership["Service"]["stateOf"] = Effect.fnUntraced(function* (project) { + const state = yield* stateFor(project, yield* readSettings, "peek"); + if (state === undefined || state.members.length === 0) return state; + const members = yield* Effect.forEach(state.members, (member) => + enrichment + .getAvailable(member.path) + .pipe(Effect.map(({ repositoryIdentity }) => ({ ...member, repositoryIdentity }))), + ); + return { ...state, members }; + }); + + const realPath = (value: string) => + fileSystem.realPath(value).pipe(Effect.orElseSucceed(() => path.resolve(value))); + + let umbrellasByMemberPath = new Map>(); + // Serialized, with settings read inside, so a slow rebuild cannot restore what a later one dropped. + const rebuildLock = yield* Semaphore.make(1); + const rebuildIndex = Effect.fn("UmbrellaMembership.rebuildIndex")( + function* (scan: "peek" | "read") { + const projects = yield* projectStore.listShells().pipe(Effect.orElseSucceed(() => [])); + const overrides = yield* readSettings; + const umbrellas = new Map>(); + const byMemberPath = new Map(); + yield* Effect.forEach( + projects, + (project) => + Effect.gen(function* () { + // Git only leaves out the members of umbrellas the user turned on. + if (!umbrellaSettingsOf(overrides[project.id]).enabled) return; + const state = yield* stateFor(project, overrides, scan); + if (state === undefined || state.members.length === 0) return; + for (const member of state.members) { + byMemberPath.set(member.path, [...(byMemberPath.get(member.path) ?? []), project.id]); + } + const root = yield* realPath(project.workspaceRoot); + const checkouts = yield* Effect.forEach(state.members, (member) => + realPath(member.path).pipe( + Effect.map((resolved) => ({ path: resolved, relativePath: member.relativePath })), + ), + ); + umbrellas.set(root, [...(umbrellas.get(root) ?? []), ...checkouts]); + }), + { concurrency: 2, discard: true }, + ); + yield* index.replace(umbrellas); + umbrellasByMemberPath = byMemberPath; + }, + (effect) => rebuildLock.withPermits(1)(effect), + ); + + const settingsChanges = yield* settingsService.subscribeChanges; + const enrichmentChanges = yield* enrichment.subscribeChanges; + let lastSettings = new Map( + Object.entries(yield* readSettings).map(([projectId, entry]) => [ + projectId, + umbrellaSettingsOf(entry), + ]), + ); + const onSettings = Effect.fn("UmbrellaMembership.onSettings")(function* ( + settings: ServerSettingsSchema, + ) { + const next = new Map( + Object.entries(settings.projectSettingsOverrides).map(([projectId, entry]) => [ + projectId, + umbrellaSettingsOf(entry), + ]), + ); + const changed = [...new Set([...lastSettings.keys(), ...next.keys()])].filter( + (projectId) => + !sameSettings( + lastSettings.get(projectId) ?? umbrellaSettingsOf(undefined), + next.get(projectId) ?? umbrellaSettingsOf(undefined), + ), + ) as ProjectId[]; + lastSettings = next; + if (changed.length === 0) return; + yield* rebuildIndex("peek"); + yield* PubSub.publish(changes, changed); + }); + + // A rescan changes its root's members; a resolved identity changes the umbrellas holding it. + const onEnrichment = Effect.fn("UmbrellaMembership.onEnrichment")(function* ( + batch: ReadonlyArray, + ) { + const rescanned = new Set( + batch.flatMap((change) => + change.nestedRepositoriesResolved === true ? [change.workspaceRoot] : [], + ), + ); + if (rescanned.size > 0) yield* rebuildIndex("peek"); + const changed = new Set( + batch.flatMap((change) => + change.repositoryIdentityResolved + ? (umbrellasByMemberPath.get(change.workspaceRoot) ?? []) + : [], + ), + ); + if (rescanned.size > 0) { + for (const project of yield* projectStore.listShells().pipe(Effect.orElseSucceed(() => []))) { + if (rescanned.has(project.workspaceRoot)) changed.add(project.id); + } + } + if (changed.size > 0) yield* PubSub.publish(changes, [...changed]); + }); + + const serverConfig = yield* Effect.serviceOption(ServerConfig.ServerConfig); + // Worktree-mode threads' folders, so their status and checkpoints leave members out after a restart. + const registerWorktrees = Effect.gen(function* () { + if (Option.isNone(serverConfig)) return; + const settings = yield* settingsService.getSettings.pipe( + Effect.orElseSucceed(() => ({ worktreesDirectory: "", previousWorktreesDirectories: [] })), + ); + yield* registerUmbrellaWorktreesIn( + managedWorktreesDirectories( + settings, + serverConfig.value.worktreesDir, + path, + yield* HostProcess.HomeDirectory, + ), + ).pipe( + Effect.provideService(FileSystem.FileSystem, fileSystem), + Effect.provideService(Path.Path, path), + Effect.provideService(UmbrellaMemberIndex, index), + ); + }); + + yield* forkParked( + Effect.gen(function* () { + yield* registerWorktrees; + yield* rebuildIndex("read"); + yield* Effect.all( + [ + Stream.runForEach(settingsChanges, onSettings), + Stream.fromSubscription(enrichmentChanges).pipe( + Stream.groupedWithin(64, Duration.millis(250)), + Stream.runForEach(onEnrichment), + ), + // Rescans enabled umbrellas and drops projects removed or moved since. + rebuildIndex("peek").pipe( + Effect.repeat(Schedule.spaced(Duration.minutes(5))), + Effect.delay(Duration.minutes(5)), + ), + ], + { concurrency: "unbounded", discard: true }, + ); + }).pipe( + Effect.catchCause((cause) => + Effect.logWarning("Umbrella membership sync stopped", { cause }), + ), + ), + ); + + return UmbrellaMembership.of({ + stateOf, + refreshIndex: rebuildIndex("peek"), + subscribeChanges: PubSub.subscribe(changes), + }); +}); + +export const layer = Layer.effect(UmbrellaMembership, make); + +/** Adds umbrella members or suggestions once the root has been scanned. Runtimes without the umbrella layer keep plain shells. */ +export const attachUmbrellaMembers = Effect.fnUntraced(function*

( + projects: ReadonlyArray

, +) { + const membership = yield* Effect.serviceOption(UmbrellaMembership); + if (Option.isNone(membership)) return projects; + return yield* Effect.forEach( + projects, + (project) => + membership.value.stateOf(project).pipe( + Effect.map((state) => + state === undefined + ? project + : { + ...project, + umbrellaMembers: state.members, + ...(state.suggestions.length > 0 ? { umbrellaSuggestions: state.suggestions } : {}), + ...(state.enclosingRepository === null + ? {} + : { umbrellaEnclosingRepository: state.enclosingRepository }), + }, + ), + ), + { concurrency: 16 }, + ); +}); + +/** Looks the umbrella layer up once: a project's enabled members, or none without the layer. */ +export const makeUmbrellaMembersOf = Effect.map( + Effect.serviceOption(UmbrellaMembership), + (membership) => + (project: UmbrellaProject): Effect.Effect> => + Option.isNone(membership) + ? Effect.succeed([]) + : membership.value.stateOf(project).pipe(Effect.map((state) => state?.members ?? [])), +); + +/** Projects whose members may have changed; nothing without the umbrella layer. */ +export const subscribeUmbrellaChanges = Effect.serviceOption(UmbrellaMembership).pipe( + Effect.flatMap( + Option.match({ + onNone: () => Effect.succeed(Stream.empty), + onSome: (membership) => Effect.map(membership.subscribeChanges, Stream.fromSubscription), + }), + ), +); + +/** A moved or deleted project stops git leaving out its members right away. */ +export const refreshUmbrellaIndex = Effect.serviceOption(UmbrellaMembership).pipe( + Effect.flatMap( + Option.match({ onNone: () => Effect.void, onSome: (membership) => membership.refreshIndex }), + ), +); diff --git a/apps/server/src/project/UmbrellaWorktree.test.ts b/apps/server/src/project/UmbrellaWorktree.test.ts new file mode 100644 index 0000000000000..83f99cb3b2d86 --- /dev/null +++ b/apps/server/src/project/UmbrellaWorktree.test.ts @@ -0,0 +1,328 @@ +// @effect-diagnostics nodeBuiltinImport:off +import * as NodeFS from "node:fs"; +import * as NodePath from "node:path"; + +import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { assert, it } from "@effect/vitest"; +import type { VcsStatusLocalResult } from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Layer from "effect/Layer"; + +import * as ServerConfig from "../config.ts"; +import * as GitWorkflowService from "../git/GitWorkflowService.ts"; +import * as GitVcsDriver from "../vcs/GitVcsDriver.ts"; +import * as UmbrellaMemberIndex from "../vcs/UmbrellaMemberIndex.ts"; +import * as VcsProcess from "../vcs/VcsProcess.ts"; +import { makeUmbrellaWorktrees } from "./UmbrellaWorktree.ts"; +import { + readUmbrellaWorktree, + UMBRELLA_WORKTREE_MANIFEST_SUFFIX, +} from "./umbrellaWorktreeLayout.ts"; + +// The workflow service's Git calls, answered by the real driver. +const layerGitWorkflow = Layer.unwrap( + Effect.gen(function* () { + const driver = yield* GitVcsDriver.GitVcsDriver; + const run = (cwd: string, args: ReadonlyArray) => + driver.execute({ operation: "UmbrellaWorktree.test", cwd, args, allowNonZeroExit: true }); + const currentBranch = (cwd: string) => + run(cwd, ["symbolic-ref", "--quiet", "--short", "HEAD"]).pipe( + Effect.map((result) => (result.exitCode === 0 ? result.stdout.trim() : null)), + ); + return Layer.mock(GitWorkflowService.GitWorkflowService)({ + repositoryRoot: (cwd) => + run(cwd, ["rev-parse", "--show-toplevel"]).pipe( + Effect.map((result) => (result.exitCode === 0 ? result.stdout.trim() : null)), + ), + hasCommit: ({ cwd, refName }) => + run(cwd, ["rev-parse", "--verify", "--quiet", `${refName}^{commit}`]).pipe( + Effect.map((result) => result.exitCode === 0), + ), + currentBranch, + localStatus: ({ cwd }) => + currentBranch(cwd).pipe( + Effect.map((refName) => ({ isRepo: true, refName }) as VcsStatusLocalResult), + ), + invalidateLocalStatus: () => Effect.void, + createWorktree: driver.createWorktree, + removeWorktree: driver.removeWorktree, + pruneWorktrees: driver.pruneWorktrees, + deleteLocalBranch: driver.deleteLocalBranch, + renameBranch: driver.renameBranch, + listLocalBranchNames: driver.listLocalBranchNames, + resolvePrimaryRemoteName: driver.resolvePrimaryRemoteName, + resolveRemoteTrackingCommit: driver.resolveRemoteTrackingCommit, + resolveWorktreeBaseRemote: driver.resolveWorktreeBaseRemote, + fetchWorktreeBaseCommit: driver.fetchWorktreeBaseCommit, + }); + }), +); + +const layerTest = layerGitWorkflow.pipe( + Layer.provideMerge(GitVcsDriver.layer), + Layer.provideMerge(ServerConfig.layerTest(process.cwd(), { prefix: "t3-umbrella-worktree-" })), + Layer.provideMerge(VcsProcess.layer), + Layer.provideMerge(UmbrellaMemberIndex.layer), + Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), +); + +const git = (cwd: string, args: ReadonlyArray) => + Effect.gen(function* () { + const result = yield* (yield* VcsProcess.VcsProcess).run({ + operation: "UmbrellaWorktree.test.git", + command: "git", + cwd, + args, + timeoutMs: 10_000, + }); + return result.stdout.trim(); + }); + +const initRepo = (cwd: string) => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + yield* fileSystem.makeDirectory(cwd, { recursive: true }); + yield* git(cwd, ["init", "--initial-branch=main"]); + yield* git(cwd, ["config", "user.email", "test@test.com"]); + yield* git(cwd, ["config", "user.name", "Test"]); + yield* fileSystem.writeFileString( + NodePath.join(cwd, "README.md"), + `# ${NodePath.basename(cwd)}\n`, + ); + yield* git(cwd, ["add", "."]); + yield* git(cwd, ["commit", "-m", "initial"]); + }); + +/** An umbrella repository holding two member repositories and an untracked notes folder. */ +const makeUmbrella = Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const root = NodeFS.realpathSync.native( + yield* fileSystem.makeTempDirectoryScoped({ prefix: "umbrella-root-" }), + ); + const outside = NodeFS.realpathSync.native( + yield* fileSystem.makeTempDirectoryScoped({ prefix: "umbrella-outside-" }), + ); + yield* initRepo(root); + yield* fileSystem.writeFileString(NodePath.join(root, ".gitignore"), "api/\nclients/\n"); + yield* git(root, ["add", ".gitignore"]); + yield* git(root, ["commit", "-m", "ignore members"]); + yield* initRepo(NodePath.join(root, "api")); + yield* initRepo(NodePath.join(root, "clients", "web")); + yield* fileSystem.makeDirectory(NodePath.join(root, "copy"), { recursive: true }); + yield* fileSystem.writeFileString(NodePath.join(root, "copy", "brief.md"), "brief\n"); + const adopted = NodePath.join(outside, "design"); + yield* initRepo(adopted); + return { + root, + members: [ + { path: NodePath.join(root, "api"), relativePath: "api" }, + { path: NodePath.join(root, "clients", "web"), relativePath: "clients/web" }, + { path: adopted, relativePath: NodePath.relative(root, adopted) }, + ], + }; +}); + +it.layer(layerTest)("UmbrellaWorktree", (it) => { + it.effect("mirrors the umbrella in the root's own worktree", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const umbrella = yield* makeUmbrella; + const worktrees = yield* makeUmbrellaWorktrees; + const created = yield* worktrees.create({ + umbrellaRoot: umbrella.root, + members: umbrella.members, + baseRef: "main", + startFromOrigin: false, + branch: "feature/umbrella", + flattenOnConflict: false, + submodules: null, + }); + const folder = created.path; + const config = yield* ServerConfig.ServerConfig; + assert.strictEqual(NodePath.dirname(NodePath.dirname(folder)), config.worktreesDir); + + // Every repository is a worktree on the thread branch; the originals stay put. + for (const [repository, relativePath] of [ + [NodePath.join(umbrella.root, "api"), "api"], + [NodePath.join(umbrella.root, "clients", "web"), "clients/web"], + [umbrella.members[2]!.path, "_external/design"], + [umbrella.root, ""], + ] as const) { + const checkout = relativePath === "" ? folder : NodePath.join(folder, relativePath); + assert.strictEqual( + yield* git(checkout, ["symbolic-ref", "--short", "HEAD"]), + "feature/umbrella", + ); + assert.strictEqual(yield* git(repository, ["symbolic-ref", "--short", "HEAD"]), "main"); + } + + // The root's own checkout supplies its files; untracked ones stay behind. + assert.isFalse(yield* fileSystem.exists(NodePath.join(folder, "copy"))); + assert.isTrue(yield* fileSystem.exists(NodePath.join(folder, ".gitignore"))); + + const layout = yield* readUmbrellaWorktree(folder); + assert.deepStrictEqual( + layout?.members.map((member) => member.path), + ["api", "clients/web", "_external/design"], + ); + const index = yield* UmbrellaMemberIndex.UmbrellaMemberIndex; + assert.deepStrictEqual(index.memberPathsWithin(NodeFS.realpathSync.native(folder)), [ + "api", + "clients/web", + "_external/design", + ]); + + // Removal takes every worktree, keeps the originals and branches, and forgets the folder. + yield* fileSystem.writeFileString(NodePath.join(folder, "api", "draft.md"), "draft\n"); + assert.isTrue(yield* worktrees.remove({ worktreePath: folder, force: true })); + assert.isFalse(yield* fileSystem.exists(folder)); + assert.isFalse(yield* fileSystem.exists(`${folder}${UMBRELLA_WORKTREE_MANIFEST_SUFFIX}`)); + assert.deepStrictEqual(index.memberPathsWithin(folder), []); + assert.strictEqual( + yield* fileSystem.readFileString(NodePath.join(umbrella.root, "copy", "brief.md")), + "brief\n", + ); + for (const repository of [umbrella.root, ...umbrella.members.map((member) => member.path)]) { + const listed = yield* git(repository, ["worktree", "list", "--porcelain"]); + assert.notInclude(listed, folder); + assert.strictEqual( + yield* git(repository, ["branch", "--list", "feature/umbrella"]), + "feature/umbrella", + ); + } + }), + ); + + it.effect("recreates the missing parts of an umbrella worktree from its branch", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const umbrella = yield* makeUmbrella; + const worktrees = yield* makeUmbrellaWorktrees; + const created = yield* worktrees.create({ + umbrellaRoot: umbrella.root, + members: umbrella.members, + baseRef: "HEAD", + startFromOrigin: false, + branch: "t3code/abc12345", + flattenOnConflict: true, + submodules: null, + }); + const folder = created.path; + yield* fileSystem.writeFileString(NodePath.join(folder, "api", "work.md"), "work\n"); + yield* git(NodePath.join(folder, "api"), ["add", "work.md"]); + yield* git(NodePath.join(folder, "api"), ["commit", "-m", "work"]); + + // Storage cleanup keeps the manifest, so the next turn rebuilds the same layout. + yield* worktrees.remove({ worktreePath: folder, force: false, keepManifest: true }); + assert.isFalse(yield* fileSystem.exists(folder)); + assert.isTrue( + yield* worktrees.restoreMissing({ worktreePath: folder, branch: created.branch }), + ); + assert.strictEqual( + yield* fileSystem.readFileString(NodePath.join(folder, "api", "work.md")), + "work\n", + ); + assert.isTrue(yield* fileSystem.exists(NodePath.join(folder, "_external", "design", ".git"))); + + // One member removed by hand comes back alone. + yield* git(umbrella.members[1]!.path, [ + "worktree", + "remove", + "--force", + NodePath.join(folder, "clients", "web"), + ]); + assert.isTrue( + yield* worktrees.restoreMissing({ worktreePath: folder, branch: created.branch }), + ); + assert.strictEqual( + yield* git(NodePath.join(folder, "clients", "web"), ["symbolic-ref", "--short", "HEAD"]), + created.branch, + ); + + assert.isFalse( + yield* worktrees.restoreMissing({ worktreePath: umbrella.root, branch: created.branch }), + ); + }), + ); + + it.effect("renames the thread branch in every repository and rolls back a failed creation", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const umbrella = yield* makeUmbrella; + const worktrees = yield* makeUmbrellaWorktrees; + const created = yield* worktrees.create({ + umbrellaRoot: umbrella.root, + members: umbrella.members, + baseRef: "main", + startFromOrigin: false, + branch: "t3code/0011aabb", + flattenOnConflict: true, + submodules: null, + }); + const renamed = yield* worktrees.renameBranch({ + cwd: created.path, + oldBranch: created.branch, + newBranch: "feature/renamed", + exactName: true, + }); + assert.strictEqual(renamed.branch, "feature/renamed"); + for (const relativePath of ["", "api", "clients/web", "_external/design"]) { + assert.strictEqual( + yield* git(NodePath.join(created.path, relativePath), [ + "symbolic-ref", + "--short", + "HEAD", + ]), + "feature/renamed", + ); + } + yield* worktrees.remove({ + worktreePath: created.path, + force: true, + deleteBranch: "feature/renamed", + }); + assert.strictEqual( + yield* git(umbrella.members[0]!.path, ["branch", "--list", "feature/renamed"]), + "", + ); + + // A plain umbrella folder has no worktree of its own to hold the members. + const plain = yield* Effect.flip( + worktrees.create({ + umbrellaRoot: NodePath.dirname(umbrella.members[2]!.path), + members: [{ path: umbrella.members[2]!.path, relativePath: "design" }], + baseRef: "HEAD", + startFromOrigin: false, + branch: "plain", + flattenOnConflict: false, + submodules: null, + }), + ); + assert.include(plain.message, "to be a Git repository"); + + // A member that cannot take the branch undoes the worktrees made before it. + yield* git(umbrella.members[2]!.path, ["branch", "taken"]); + const failure = yield* Effect.flip( + worktrees.create({ + umbrellaRoot: umbrella.root, + members: umbrella.members, + baseRef: "main", + startFromOrigin: false, + branch: "taken", + flattenOnConflict: false, + submodules: null, + }), + ); + assert.strictEqual(failure._tag, "UmbrellaWorktreeError"); + assert.strictEqual(yield* git(umbrella.root, ["branch", "--list", "taken"]), ""); + assert.strictEqual(yield* git(umbrella.members[0]!.path, ["branch", "--list", "taken"]), ""); + const config = yield* ServerConfig.ServerConfig; + const leftovers = yield* fileSystem + .readDirectory(NodePath.join(config.worktreesDir, NodePath.basename(umbrella.root))) + .pipe(Effect.orElseSucceed((): string[] => [])); + assert.deepStrictEqual(leftovers, []); + }), + ); +}); diff --git a/apps/server/src/project/UmbrellaWorktree.ts b/apps/server/src/project/UmbrellaWorktree.ts new file mode 100644 index 0000000000000..25f85c2d4e17a --- /dev/null +++ b/apps/server/src/project/UmbrellaWorktree.ts @@ -0,0 +1,402 @@ +import type { UmbrellaMember, WorktreeSubmodules } from "@t3tools/contracts"; +import { umbrellaWorktreeMemberPaths } from "@t3tools/shared/umbrellaWorktree"; +import * as Cause from "effect/Cause"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Path from "effect/Path"; + +import * as GitWorkflowService from "../git/GitWorkflowService.ts"; +import { UmbrellaMemberIndex } from "../vcs/UmbrellaMemberIndex.ts"; +import { recreateBranchWorktree } from "../workspace/recreateBranchWorktree.ts"; +import { + encodeUmbrellaWorktreeManifest, + joinUmbrellaRelative, + readUmbrellaWorktree, + registerUmbrellaWorktree, + UmbrellaWorktreeError, + type UmbrellaWorktreeLayout, + type UmbrellaWorktreeRepository, + umbrellaWorktreeManifestPath, + umbrellaWorktreeRepositories, +} from "./umbrellaWorktreeLayout.ts"; + +interface CreateUmbrellaWorktreeInput { + readonly umbrellaRoot: string; + /** The umbrella's enabled members. */ + readonly members: ReadonlyArray>; + /** "HEAD" starts each repository from its own checkout. */ + readonly baseRef: string; + readonly startFromOrigin: boolean; + readonly branch: string; + /** A temporary name that collides with an existing branch folder gets flattened, as plain worktrees do. */ + readonly flattenOnConflict: boolean; + readonly submodules: WorktreeSubmodules | null; +} + +/** @public */ +export const makeUmbrellaWorktrees = Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const git = yield* GitWorkflowService.GitWorkflowService; + const index = yield* UmbrellaMemberIndex; + const local = (effect: Effect.Effect) => + effect.pipe( + Effect.provideService(FileSystem.FileSystem, fileSystem), + Effect.provideService(Path.Path, path), + Effect.provideService(GitWorkflowService.GitWorkflowService, git), + Effect.provideService(UmbrellaMemberIndex, index), + ); + + const fail = (operation: string, detail: string, cause?: unknown) => + new UmbrellaWorktreeError({ + operation, + detail, + ...(cause === undefined ? {} : { cause }), + }); + const errorDetail = (cause: unknown) => + cause instanceof Error ? cause.message : typeof cause === "string" ? cause : String(cause); + const exists = (target: string) => + fileSystem.exists(target).pipe(Effect.orElseSucceed(() => false)); + + /** Where a repository starts: the requested base when it has one, else its own checkout. */ + const resolveBase = Effect.fn("UmbrellaWorktree.resolveBase")(function* ( + cwd: string, + baseRef: string, + startFromOrigin: boolean, + ) { + // Untraced: resolveBase's span covers it. + const fromOrigin = Effect.fnUntraced(function* (refName: string) { + if (!startFromOrigin) return null; + const remote = yield* git.resolveWorktreeBaseRemote({ cwd, refName }); + if (remote === null) return null; + const fetched = yield* git.fetchWorktreeBaseCommit({ cwd, refName, remote }); + return fetched === null + ? null + : { startRef: fetched.commitSha, baseRefName: `refs/remotes/${fetched.remoteRefName}` }; + }); + if (baseRef !== "HEAD") { + const remote = yield* fromOrigin(baseRef); + if (remote !== null) return remote; + if (yield* git.hasCommit({ cwd, refName: baseRef })) { + return { startRef: baseRef, baseRefName: baseRef }; + } + } + const current = yield* git.currentBranch(cwd); + if (current !== null) { + return (yield* fromOrigin(current)) ?? { startRef: current, baseRefName: current }; + } + if (yield* git.hasCommit({ cwd, refName: "HEAD" })) { + return { startRef: "HEAD", baseRefName: undefined }; + } + return yield* fail( + "UmbrellaWorktree.resolveBase", + `${cwd} has no commit to start a worktree from.`, + ); + }); + + const writeManifest = Effect.fn("UmbrellaWorktree.writeManifest")(function* ( + layout: UmbrellaWorktreeLayout, + ) { + const { path: worktreePath, ...manifest } = layout; + yield* fileSystem.writeFileString( + umbrellaWorktreeManifestPath(path, worktreePath), + yield* encodeUmbrellaWorktreeManifest({ version: 1, ...manifest }), + ); + }); + + const create = Effect.fn("UmbrellaWorktree.create")(function* ( + input: CreateUmbrellaWorktreeInput, + ) { + const umbrellaRoot = path.resolve(input.umbrellaRoot); + if ((yield* git.repositoryRoot(umbrellaRoot).pipe(Effect.orElseSucceed(() => null))) === null) { + return yield* fail( + "UmbrellaWorktree.create", + `Umbrella worktrees need the umbrella folder ${umbrellaRoot} to be a Git repository.`, + ); + } + const memberPaths = umbrellaWorktreeMemberPaths( + input.members.map((member) => member.relativePath), + ); + const sources = [umbrellaRoot, ...input.members.map((member) => member.path)]; + let branch = input.branch; + if (input.flattenOnConflict) { + const parts = branch.split("/"); + const prefixes = parts.slice(1).map((_, depth) => parts.slice(0, depth + 1).join("/")); + for (const cwd of sources) { + const names = yield* git + .listLocalBranchNames(cwd) + .pipe(Effect.orElseSucceed((): string[] => [])); + if (names.some((name) => prefixes.includes(name))) { + branch = branch.replaceAll("/", "-"); + break; + } + } + } + + // Created pieces, removed again if a later step fails or the launch is cancelled. + const created: Array<{ readonly cwd: string; readonly path: string }> = []; + let folder: string | null = null; + let manifestWritten = false; + const rollback = Effect.gen(function* () { + for (const piece of created.toReversed()) { + yield* git + .removeWorktree({ cwd: piece.cwd, path: piece.path, force: true }) + .pipe( + Effect.andThen(git.deleteLocalBranch({ cwd: piece.cwd, refName: branch, force: true })), + Effect.ignoreCause({ log: true }), + ); + } + if (folder !== null && manifestWritten) { + yield* fileSystem.remove(umbrellaWorktreeManifestPath(path, folder)).pipe(Effect.ignore); + yield* fileSystem.realPath(folder).pipe( + Effect.orElseSucceed(() => folder!), + Effect.flatMap(index.forgetWorktree), + ); + } + }); + + const build = Effect.gen(function* () { + const base = yield* resolveBase(umbrellaRoot, input.baseRef, input.startFromOrigin); + const worktree = yield* git.createWorktree( + { + cwd: umbrellaRoot, + refName: base.startRef, + newRefName: branch, + ...(base.baseRefName === undefined ? {} : { baseRefName: base.baseRefName }), + path: null, + }, + { + submodules: input.submodules, + progress: { + onWorktreeClaimed: (claimed) => + Effect.sync(() => { + folder = claimed; + created.push({ cwd: umbrellaRoot, path: claimed }); + }), + }, + }, + ); + const threadFolder = worktree.worktree.path; + folder = threadFolder; + if (!created.some((piece) => piece.path === threadFolder)) { + created.push({ cwd: umbrellaRoot, path: threadFolder }); + } + const layout: UmbrellaWorktreeLayout = { + path: threadFolder, + umbrellaRoot, + members: input.members.map((member, index) => ({ + source: path.resolve(member.path), + path: memberPaths[index]!, + })), + }; + // Written first, so status and checkpoints of the root worktree leave members out from the start. + yield* writeManifest(layout); + manifestWritten = true; + yield* local(registerUmbrellaWorktree(layout)); + yield* Effect.forEach( + layout.members, + (member) => + Effect.gen(function* () { + const target = joinUmbrellaRelative(path, threadFolder, member.path); + yield* fileSystem.makeDirectory(path.dirname(target), { recursive: true }); + const base = yield* resolveBase(member.source, input.baseRef, input.startFromOrigin); + yield* git.createWorktree( + { + cwd: member.source, + refName: base.startRef, + newRefName: branch, + ...(base.baseRefName === undefined ? {} : { baseRefName: base.baseRefName }), + path: target, + }, + { + submodules: input.submodules, + progress: { + onWorktreeClaimed: (claimed) => + Effect.sync(() => { + created.push({ cwd: member.source, path: claimed }); + }), + }, + }, + ); + if (!created.some((piece) => piece.path === target)) { + created.push({ cwd: member.source, path: target }); + } + }).pipe( + Effect.mapError((cause) => + cause._tag === "UmbrellaWorktreeError" + ? cause + : fail( + "UmbrellaWorktree.create", + `Could not create the worktree of ${member.path}: ${errorDetail(cause)}`, + cause, + ), + ), + ), + { concurrency: 4, discard: true }, + ); + // Members' worktrees exist now, so their real paths register. + yield* local(registerUmbrellaWorktree(layout)); + return { path: threadFolder, branch }; + }); + + return yield* build.pipe( + Effect.mapError((cause) => + cause._tag === "UmbrellaWorktreeError" + ? cause + : fail("UmbrellaWorktree.create", errorDetail(cause), cause), + ), + Effect.onError(() => Effect.uninterruptible(rollback)), + ); + }); + + /** + * Removes every repository's worktree and the folder. Each branch named by `deleteBranch` goes + * too. Storage cleanup keeps the manifest, so the next turn can recreate the same layout. + */ + const remove = Effect.fn("UmbrellaWorktree.remove")(function* (input: { + readonly worktreePath: string; + readonly force: boolean; + readonly deleteBranch?: string; + readonly keepManifest?: boolean; + }) { + const layout = yield* local(readUmbrellaWorktree(input.worktreePath)); + if (layout === null) return false; + const registeredPath = yield* fileSystem + .realPath(layout.path) + .pipe(Effect.orElseSucceed(() => layout.path)); + const failures: Array = []; + const [root, ...members] = umbrellaWorktreeRepositories(path, layout); + // Untraced: the removal's span covers each repository. + const removeRepository = Effect.fnUntraced( + function* (repository: UmbrellaWorktreeRepository) { + if (yield* exists(repository.cwd)) { + yield* git.removeWorktree({ + cwd: repository.source, + path: repository.cwd, + force: input.force, + }); + } else { + yield* git.pruneWorktrees({ cwd: repository.source }); + } + if (input.deleteBranch !== undefined) { + yield* git + .deleteLocalBranch({ + cwd: repository.source, + refName: input.deleteBranch, + force: true, + }) + .pipe(Effect.ignoreCause({ log: true })); + } + }, + (effect, repository) => + effect.pipe( + Effect.catchCause((cause) => + Effect.sync(() => { + failures.push( + `${repository.relativePath || "the umbrella folder"}: ${errorDetail(Cause.squash(cause))}`, + ); + }), + ), + ), + ); + // Members first: removing the root's worktree would delete the members inside it. + for (const member of members.toSorted( + (left, right) => right.relativePath.length - left.relativePath.length, + )) { + yield* removeRepository(member); + } + if (failures.length === 0) yield* removeRepository(root!); + if (failures.length > 0) { + return yield* fail( + "UmbrellaWorktree.remove", + `Could not remove the worktree of ${failures.join("; ")}.`, + ); + } + if (input.keepManifest !== true) { + yield* fileSystem.remove(umbrellaWorktreeManifestPath(path, layout.path)).pipe(Effect.ignore); + yield* index.forgetWorktree(registeredPath); + } + return true; + }); + + /** + * Recreates whatever part of an umbrella worktree is missing, from `branch` in each + * repository. Returns false when the folder is not an umbrella worktree. + */ + const restoreMissing = Effect.fn("UmbrellaWorktree.restoreMissing")(function* (input: { + readonly worktreePath: string; + readonly branch: string; + }) { + const layout = yield* local(readUmbrellaWorktree(input.worktreePath)); + if (layout === null) return false; + const hasCheckout = (cwd: string) => + fileSystem.exists(path.join(cwd, ".git")).pipe(Effect.orElseSucceed(() => false)); + const isEmptyOrMissing = (cwd: string) => + fileSystem.readDirectory(cwd).pipe( + Effect.map((entries) => entries.length === 0), + Effect.orElseSucceed(() => true), + ); + for (const repository of umbrellaWorktreeRepositories(path, layout)) { + if (yield* hasCheckout(repository.cwd)) continue; + if (!(yield* isEmptyOrMissing(repository.cwd))) { + return yield* fail( + "UmbrellaWorktree.restoreMissing", + `${repository.cwd} is no longer a checkout but still holds files, so it was left alone.`, + ); + } + yield* fileSystem.remove(repository.cwd, { recursive: true }).pipe(Effect.ignore); + yield* fileSystem.makeDirectory(path.dirname(repository.cwd), { recursive: true }); + yield* Effect.logWarning("recreating a missing umbrella worktree checkout", { + worktreePath: layout.path, + repository: repository.relativePath || ".", + branch: input.branch, + }); + yield* local( + recreateBranchWorktree({ + cwd: repository.source, + worktreePath: repository.cwd, + branch: input.branch, + }), + ); + } + yield* local(registerUmbrellaWorktree(layout)); + return true; + }); + + /** Renames the thread branch in the folder and, in an umbrella worktree, every member to the same name. */ + const renameBranch = Effect.fn("UmbrellaWorktree.renameBranch")(function* ( + input: Parameters[0], + ) { + const renamed = yield* git.renameBranch(input); + const layout = yield* local(readUmbrellaWorktree(input.cwd)); + const members = layout === null ? [] : umbrellaWorktreeRepositories(path, layout).slice(1); + for (const repository of members) { + yield* git + .renameBranch({ + cwd: repository.cwd, + oldBranch: input.oldBranch, + newBranch: renamed.branch, + exactName: true, + }) + .pipe( + Effect.catchCause((cause) => + Effect.logWarning("umbrella member kept its temporary branch name", { + repository: repository.relativePath, + branch: input.oldBranch, + cause, + }), + ), + ); + } + return renamed; + }); + + return { + /** The umbrella worktree at this folder, or null when it is not one. */ + read: (worktreePath: string) => local(readUmbrellaWorktree(worktreePath)), + create, + remove, + restoreMissing, + renameBranch, + }; +}); diff --git a/apps/server/src/project/umbrellaDiscovery.test.ts b/apps/server/src/project/umbrellaDiscovery.test.ts new file mode 100644 index 0000000000000..9a8bd10fba61f --- /dev/null +++ b/apps/server/src/project/umbrellaDiscovery.test.ts @@ -0,0 +1,52 @@ +// @effect-diagnostics nodeBuiltinImport:off +import * as NodeFS from "node:fs"; +import * as NodeOS from "node:os"; +import * as NodePath from "node:path"; + +import { it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import { expect } from "vite-plus/test"; + +import { discoverNestedRepositories } from "./umbrellaDiscovery.ts"; + +const makeTree = (entries: ReadonlyArray) => { + const root = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "umbrella-discovery-")); + for (const entry of entries) { + const target = NodePath.join(root, entry); + if (entry.endsWith("/.git-file")) { + NodeFS.mkdirSync(NodePath.dirname(target), { recursive: true }); + NodeFS.writeFileSync(NodePath.join(NodePath.dirname(target), ".git"), "gitdir: elsewhere\n"); + } else { + NodeFS.mkdirSync(target, { recursive: true }); + } + } + return root; +}; + +it.effect("finds checkouts under the root without entering skipped folders", () => + Effect.gen(function* () { + const root = makeTree([ + "api/.git", + "api/vendor/inner/.git", + "sites/marketing/.git", + "copy/drafts", + ".hidden/repo/.git", + "node_modules/pkg/.git", + "worktree/.git-file", + "worktree/nested/.git", + "one/two/three/.git", + "one/two/three/four/.git", + "deep/a/b/c/.git", + ]); + try { + const found = yield* discoverNestedRepositories(root); + expect(found.map((path) => NodePath.relative(root, path))).toEqual([ + "api", + NodePath.join("one", "two", "three"), + NodePath.join("sites", "marketing"), + ]); + } finally { + NodeFS.rmSync(root, { recursive: true, force: true }); + } + }), +); diff --git a/apps/server/src/project/umbrellaDiscovery.ts b/apps/server/src/project/umbrellaDiscovery.ts new file mode 100644 index 0000000000000..40c87e2bcbddc --- /dev/null +++ b/apps/server/src/project/umbrellaDiscovery.ts @@ -0,0 +1,58 @@ +// @effect-diagnostics nodeBuiltinImport:off +import * as NodeFSP from "node:fs/promises"; +import * as NodePath from "node:path"; + +import * as Effect from "effect/Effect"; + +const MAX_DEPTH = 3; +// Bounds a scan of a huge non-umbrella folder; a client folder holds far fewer directories. +const MAX_DIRECTORIES = 1_000; +// Package managers and vendored trees hold checkouts that are dependencies, not the user's work. +const SKIPPED_DIRECTORY_NAMES = new Set([ + "node_modules", + "venv", + "vendor", + "site-packages", + "third_party", + "Pods", +]); + +const readDirectoryEntries = (directory: string) => + Effect.promise(() => NodeFSP.readdir(directory, { withFileTypes: true }).catch(() => [])); + +/** + * Git checkouts under `root`, at most three levels down. A checkout's own folders are not + * searched, and linked worktrees and submodules (a `.git` file) are skipped: they belong to + * another repository. Hidden, dependency, and vendored folders and symlinks are never entered. + */ +export const discoverNestedRepositories = Effect.fn("umbrellaDiscovery.discoverNestedRepositories")( + function* (root: string) { + let budget = MAX_DIRECTORIES; + const found: string[] = []; + let frontier = [{ directory: root, entries: yield* readDirectoryEntries(root) }]; + for (let depth = 1; depth <= MAX_DEPTH && frontier.length > 0; depth++) { + const next: typeof frontier = []; + for (const { directory, entries } of frontier) { + for (const entry of entries) { + if ( + !entry.isDirectory() || + entry.name.startsWith(".") || + SKIPPED_DIRECTORY_NAMES.has(entry.name) + ) { + continue; + } + if (budget-- <= 0) return found.toSorted(); + const child = NodePath.join(directory, entry.name); + const childEntries = yield* readDirectoryEntries(child); + const gitEntry = childEntries.find((candidate) => candidate.name === ".git"); + if (gitEntry?.isDirectory()) found.push(child); + else if (gitEntry === undefined && depth < MAX_DEPTH) { + next.push({ directory: child, entries: childEntries }); + } + } + } + frontier = next; + } + return found.toSorted(); + }, +); diff --git a/apps/server/src/project/umbrellaWorktreeLayout.ts b/apps/server/src/project/umbrellaWorktreeLayout.ts new file mode 100644 index 0000000000000..897a2c20ccc99 --- /dev/null +++ b/apps/server/src/project/umbrellaWorktreeLayout.ts @@ -0,0 +1,136 @@ +// A worktree-mode umbrella thread works in one folder that mirrors the umbrella: the root's own +// worktree with a worktree of every member at its path. A manifest beside the folder records +// which repositories it holds. +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Option from "effect/Option"; +import * as Path from "effect/Path"; +import * as Schema from "effect/Schema"; + +import { UmbrellaMemberIndex } from "../vcs/UmbrellaMemberIndex.ts"; + +export const UMBRELLA_WORKTREE_MANIFEST_SUFFIX = ".t3-umbrella.json"; + +const UmbrellaWorktreeManifest = Schema.Struct({ + version: Schema.Literal(1), + umbrellaRoot: Schema.String, + /** `path` is relative to the thread's folder, with `/` separators; `source` is the member's own checkout. */ + members: Schema.Array(Schema.Struct({ source: Schema.String, path: Schema.String })), +}); +const decodeManifest = Schema.decodeUnknownEffect(Schema.fromJsonString(UmbrellaWorktreeManifest)); +export const encodeUmbrellaWorktreeManifest = Schema.encodeEffect( + Schema.fromJsonString(UmbrellaWorktreeManifest), +); + +export interface UmbrellaWorktreeLayout extends Omit< + typeof UmbrellaWorktreeManifest.Type, + "version" +> { + /** The thread's folder. */ + readonly path: string; +} + +/** One repository checked out in an umbrella worktree. `relativePath` is "" for the root's own. */ +export interface UmbrellaWorktreeRepository { + readonly cwd: string; + readonly source: string; + readonly relativePath: string; +} + +export class UmbrellaWorktreeError extends Schema.TaggedError()( + "UmbrellaWorktreeError", + { + operation: Schema.String, + detail: Schema.String, + cause: Schema.optional(Schema.Defect()), + }, +) { + override get message(): string { + return this.detail; + } +} + +export const umbrellaWorktreeManifestPath = (path: Path.Path, worktreePath: string) => + `${path.resolve(worktreePath)}${UMBRELLA_WORKTREE_MANIFEST_SUFFIX}`; + +export const joinUmbrellaRelative = (path: Path.Path, root: string, relativePath: string) => + relativePath === "" ? root : path.join(root, ...relativePath.split("/")); + +/** The repositories in an umbrella worktree: the root's own first. */ +export const umbrellaWorktreeRepositories = ( + path: Path.Path, + layout: UmbrellaWorktreeLayout, +): ReadonlyArray => [ + { cwd: layout.path, source: layout.umbrellaRoot, relativePath: "" }, + ...layout.members.map((member) => ({ + cwd: joinUmbrellaRelative(path, layout.path, member.path), + source: member.source, + relativePath: member.path, + })), +]; + +/** The umbrella worktree at this folder, or null when it is not one. */ +export const readUmbrellaWorktree = Effect.fn("UmbrellaWorktree.read")( + function* (worktreePath: string) { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const contents = yield* fileSystem + .readFileString(umbrellaWorktreeManifestPath(path, worktreePath)) + .pipe(Effect.option); + if (Option.isNone(contents)) return null; + const { version: _version, ...manifest } = yield* decodeManifest(contents.value); + return { ...manifest, path: path.resolve(worktreePath) } satisfies UmbrellaWorktreeLayout; + }, + Effect.orElseSucceed(() => null), +); + +/** `readUmbrellaWorktree` bound to the caller's file system and paths, for services built with them. */ +export const makeReadUmbrellaWorktree = Effect.map( + Effect.context(), + (context) => (worktreePath: string) => + readUmbrellaWorktree(worktreePath).pipe(Effect.provideContext(context)), +); + +/** Lets checkpoints and Git status of the folder treat its members as the umbrella's do. */ +export const registerUmbrellaWorktree = Effect.fn("UmbrellaWorktree.register")(function* ( + layout: UmbrellaWorktreeLayout, +) { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const index = yield* UmbrellaMemberIndex; + const realPath = (target: string) => + fileSystem.realPath(target).pipe(Effect.orElseSucceed(() => path.resolve(target))); + const members = yield* Effect.forEach(layout.members, (member) => + realPath(joinUmbrellaRelative(path, layout.path, member.path)).pipe( + Effect.map((memberPath) => ({ path: memberPath, relativePath: member.path })), + ), + ); + yield* index.registerWorktree(yield* realPath(layout.path), members); +}); + +/** Reads and registers the umbrella worktree at `cwd`, for callers that may run before the startup scan. */ +export const loadUmbrellaWorktree = Effect.fn("UmbrellaWorktree.load")(function* (cwd: string) { + const layout = yield* readUmbrellaWorktree(cwd); + if (layout !== null) yield* registerUmbrellaWorktree(layout); + return layout; +}); + +/** Registers every umbrella worktree whose manifest sits in these worktree folders. */ +export const registerUmbrellaWorktreesIn = Effect.fn("UmbrellaWorktree.registerIn")(function* ( + directories: ReadonlyArray, +) { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const list = (directory: string) => + fileSystem.readDirectory(directory).pipe(Effect.orElseSucceed((): string[] => [])); + for (const directory of directories) { + for (const group of yield* list(directory)) { + for (const name of yield* list(path.join(directory, group))) { + if (!name.endsWith(UMBRELLA_WORKTREE_MANIFEST_SUFFIX)) continue; + yield* loadUmbrellaWorktree( + path.join(directory, group, name.slice(0, -UMBRELLA_WORKTREE_MANIFEST_SUFFIX.length)), + ); + } + } + } +}); diff --git a/apps/server/src/review/ReviewService.test.ts b/apps/server/src/review/ReviewService.test.ts index 4df56454cfc58..51db626fe04c8 100644 --- a/apps/server/src/review/ReviewService.test.ts +++ b/apps/server/src/review/ReviewService.test.ts @@ -24,6 +24,7 @@ function layer(input: { readonly projectRoots?: ReadonlyArray | "unavailable"; readonly threadWorktrees?: ReadonlyArray<{ worktreePath: string; deleted?: boolean }>; readonly gitWorktrees?: ReadonlyArray; + readonly adoptedPaths?: ReadonlyArray; }) { const projectRoots = input.projectRoots ?? []; return ReviewService.layer.pipe( @@ -88,6 +89,16 @@ function layer(input: { ServerSettings.ServerSettingsService.layerTest({ worktreesDirectory: input.worktreesDirectory ?? "", previousWorktreesDirectories: [...(input.previousWorktreesDirectories ?? [])], + ...(input.adoptedPaths === undefined + ? {} + : { + projectSettingsOverrides: { + [ProjectId.make("project-0")]: { + umbrellaEnabled: true, + umbrellaAdoptedPaths: [...input.adoptedPaths], + }, + }, + }), }), ), Layer.provide(ServerConfig.layerTest(input.workspaceRoot, input.baseDir)), @@ -166,17 +177,32 @@ describe("ReviewService", () => { yield* fs.makeDirectory(sibling); yield* Effect.addFinalizer(() => fs.remove(sibling, { recursive: true }).pipe(Effect.ignore)); - const review = (cwd: string, projectRoots: ReadonlyArray | "unavailable") => + const review = ( + cwd: string, + projectRoots: ReadonlyArray | "unavailable", + adoptedPaths?: ReadonlyArray, + ) => Effect.gen(function* () { const service = yield* ReviewService.ReviewService; return yield* service.getDiffPreview({ cwd }); - }).pipe(Effect.provide(layer({ workspaceRoot, baseDir, projectRoots }))); + }).pipe( + Effect.provide( + layer({ + workspaceRoot, + baseDir, + projectRoots, + ...(adoptedPaths === undefined ? {} : { adoptedPaths }), + }), + ), + ); assert.strictEqual((yield* review(projectRoot, [projectRoot])).cwd, projectRoot); assert.strictEqual((yield* review(projectChild, [projectRoot])).cwd, projectChild); const dottedChild = `${projectRoot}/..feature`; yield* fs.makeDirectory(dottedChild); assert.strictEqual((yield* review(dottedChild, [projectRoot])).cwd, dottedChild); + // An umbrella project's adopted checkout counts, wherever it lives. + assert.strictEqual((yield* review(sibling, [projectRoot], [sibling])).cwd, sibling); for (const [cwd, projectRoots] of [ [sibling, [projectRoot]], [projectRoot, []], diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index 47c4a4c9a20ec..e77269a4fe598 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -113,6 +113,7 @@ import * as ServerSettings from "./serverSettings.ts"; import * as ManagedLimits from "./policy/managedLimits.ts"; import * as ManagedPolicy from "./policy/ManagedPolicy.ts"; import * as ProjectEnrichmentService from "./project/ProjectEnrichmentService.ts"; +import * as UmbrellaMembership from "./project/UmbrellaMembership.ts"; import * as NativeAppIconResolver from "./assets/NativeAppIconResolver.ts"; import * as AntigravityInstallation from "./provider/AntigravityInstallation.ts"; import * as ProviderInstallation from "./provider/providerInstallation.ts"; @@ -132,6 +133,7 @@ import * as WorkspaceFileSystem from "./workspace/WorkspaceFileSystem.ts"; import * as WorkspacePaths from "./workspace/WorkspacePaths.ts"; import * as GitVcsDriver from "./vcs/GitVcsDriver.ts"; import * as VcsAutomaticFetchInterval from "./vcs/VcsAutomaticFetchInterval.ts"; +import * as UmbrellaMemberIndex from "./vcs/UmbrellaMemberIndex.ts"; import * as VcsDriverRegistry from "./vcs/VcsDriverRegistry.ts"; import * as VcsProjectConfig from "./vcs/VcsProjectConfig.ts"; import * as VcsProcess from "./vcs/VcsProcess.ts"; @@ -778,6 +780,12 @@ const layerRuntimeCoreDependencies = layerRuntimeCoreDependenciesBase.pipe( ), ), Layer.provideMerge(layerWorkspace), + Layer.provideMerge( + UmbrellaMembership.layer.pipe( + Layer.provide(ProjectStore.layer), + Layer.provide(layerServerSettings), + ), + ), Layer.provideMerge(ProjectEnrichmentService.layer), Layer.provideMerge(Layer.mergeAll(NativeAppIconResolver.layer, layerProjectFaviconResolver)), Layer.provideMerge(layerRepositoryIdentityResolver), @@ -812,6 +820,7 @@ const layerRuntimeDependencies = layerRuntimeCoreDependencies.pipe( // GitVcsDriver.layer is memoized and some of its build sites live outside this file, so the // fetch interval goes in context here, before the first build captures it. Layer.provideMerge(VcsAutomaticFetchInterval.layer.pipe(Layer.provide(layerServerSettings))), + Layer.provideMerge(UmbrellaMemberIndex.layer), Layer.provide(NetService.layer), ); diff --git a/apps/server/src/storageCleanup.test.ts b/apps/server/src/storageCleanup.test.ts index cf56bde07f214..e70b468ace994 100644 --- a/apps/server/src/storageCleanup.test.ts +++ b/apps/server/src/storageCleanup.test.ts @@ -460,6 +460,8 @@ const cleanupFixture = ( command(cwd, ["branch", "--show-current"]).pipe( Effect.map((result) => result.stdout.trim() || null), ), + removeWorktree: git.removeWorktree, + pruneWorktrees: git.pruneWorktrees, } as unknown as GitWorkflowService.GitWorkflowService["Service"]), Effect.provideService(ProviderSessionManager.ProviderSessionManagerV2, { isLive: () => @@ -3010,6 +3012,70 @@ describe("storage cleanup reports and local file policies", () => { }), ), ); + it.effect( + "removes every member worktree of an umbrella thread's folder and keeps its layout", + () => + runCleanupTest( + Effect.gen(function* () { + yield* TestClock.setTime(NOW_MS); + const fixture = yield* cleanupFixture(); + const { fs, command, config } = fixture; + // An umbrella repository holding one member repository. + const umbrella = yield* fs.realPath( + yield* fs.makeTempDirectoryScoped({ prefix: "cleanup-umbrella-" }), + ); + const member = `${umbrella}/api`; + yield* fs.makeDirectory(member); + yield* fs.writeFileString(`${umbrella}/.gitignore`, "api/\n"); + yield* fs.writeFileString(`${member}/tracked.txt`, "original\n"); + for (const repository of [umbrella, member]) { + yield* command(repository, ["init", "-b", "main"]); + yield* command(repository, ["config", "user.email", "cleanup@example.test"]); + yield* command(repository, ["config", "user.name", "Cleanup test"]); + yield* command(repository, ["add", "."]); + yield* command(repository, ["commit", "-m", "initial"]); + } + const folder = `${config.worktreesDir}/umbrella/feature`; + yield* command(umbrella, ["worktree", "add", "-b", "feature", folder]); + yield* command(member, ["worktree", "add", "-b", "feature", `${folder}/api`]); + const manifest = `${folder}.t3-umbrella.json`; + yield* fs.writeFileString( + manifest, + JSON.stringify({ + version: 1, + umbrellaRoot: umbrella, + members: [{ source: member, path: "api" }], + }), + ); + fixture.setThreads([shell({ branch: "feature", worktreePath: folder })]); + + // An uncommitted edit in a member keeps the whole folder. + yield* fs.writeFileString(`${folder}/api/tracked.txt`, "edited\n"); + let report = yield* fixture.service.runNow; + expect(report.entries.find((entry) => entry.path === folder)).toMatchObject({ + outcome: "kept", + reason: "Has uncommitted changes (1 file) in api", + }); + yield* command(`${folder}/api`, ["checkout", "--", "tracked.txt"]); + + report = yield* fixture.service.runNow; + expect(report.entries.find((entry) => entry.path === folder)).toMatchObject({ + outcome: "removed", + }); + expect(yield* fs.exists(folder)).toBe(false); + for (const repository of [umbrella, member]) { + expect( + (yield* command(repository, ["worktree", "list", "--porcelain"])).stdout, + ).not.toContain(folder); + expect( + (yield* command(repository, ["branch", "--list", "feature"])).stdout.trim(), + ).toBe("feature"); + } + // The next turn rebuilds the same layout from the manifest. + expect(yield* fs.exists(manifest)).toBe(true); + }), + ), + ); it.effect("removes a worktree owned by a repository other than the project root", () => runCleanupTest( Effect.gen(function* () { diff --git a/apps/server/src/storageCleanup.ts b/apps/server/src/storageCleanup.ts index 43ff8254daa6d..1e9c2b1a1251d 100644 --- a/apps/server/src/storageCleanup.ts +++ b/apps/server/src/storageCleanup.ts @@ -52,12 +52,15 @@ import { checkpointRefForScopeOrdinal } from "./orchestration-v2/CheckpointServi import { threadHasQueuedTurnStart } from "./orchestration-v2/ThreadSettlementService.ts"; import { MAX_OVERDUE_ARM_MS } from "./orchestration-v2/UsageLimitRecoveryWorker.ts"; import * as WorktreeBranchSync from "./orchestration-v2/WorktreeBranchSync.ts"; +import { makeUmbrellaWorktrees } from "./project/UmbrellaWorktree.ts"; +import { umbrellaWorktreeRepositories } from "./project/umbrellaWorktreeLayout.ts"; import { forkParked } from "./serverActivation.ts"; import * as Settings from "./serverSettings.ts"; import * as TerminalManager from "./terminal/Manager.ts"; import { isFilesystemRoot, managedWorktreesDirectories } from "./worktreesDirectory.ts"; import * as GitVcsDriver from "./vcs/GitVcsDriver.ts"; import { isNonRepositoryGitStderr } from "./vcs/GitVcsDriverCore.ts"; +import { excludePathspecs } from "./vcs/UmbrellaMemberIndex.ts"; import { isLinkedWorktree, removeLinkedWorktree } from "./vcs/worktreeRemoval.ts"; import { withWorkspaceLease } from "./workspace/workspaceLease.ts"; import * as HostProcess from "@t3tools/shared/HostProcess"; @@ -328,6 +331,7 @@ const make = Effect.gen(function* () { const gitManager = yield* GitManager.GitManager; const gitWorkflow = yield* GitWorkflowService.GitWorkflowService; const reconcileBranch = yield* WorktreeBranchSync.makeReconcile; + const umbrellaWorktrees = yield* makeUmbrellaWorktrees; const terminals = yield* TerminalManager.TerminalManager; const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; @@ -840,7 +844,11 @@ const make = Effect.gen(function* () { const localChangesReason = Effect.fn("StorageCleanup.localChangesReason")(function* ( cwd: string, rules: WorktreeCleanupRules, + // An umbrella worktree's root leaves out the member worktrees inside it. + excludedPaths: ReadonlyArray = [], ) { + const pathspec = + excludedPaths.length === 0 ? [] : ["--", ".", ...excludePathspecs(excludedPaths)]; const status = yield* git.execute({ operation: "StorageCleanup.localChanges", cwd, @@ -852,6 +860,7 @@ const make = Effect.gen(function* () { rules.worktreeKeepWhen === "tracked-changes" ? "--untracked-files=no" : "--untracked-files=all", + ...pathspec, ], maxOutputBytes: 64 * 1024, appendTruncationMarker: true, @@ -870,7 +879,15 @@ const make = Effect.gen(function* () { const ignored = yield* git.execute({ operation: "StorageCleanup.ignoredFiles", cwd, - args: ["ls-files", "--others", "--ignored", "--exclude-standard", "--directory", "-z"], + args: [ + "ls-files", + "--others", + "--ignored", + "--exclude-standard", + "--directory", + "-z", + ...pathspec, + ], maxOutputBytes: 64 * 1024, appendTruncationMarker: true, }); @@ -1423,6 +1440,64 @@ const make = Effect.gen(function* () { }), ); } + const umbrella = yield* umbrellaWorktrees.read(worktreePath); + if (umbrella !== null) { + // Only the time and deletion rules apply: merge and unchanged rules read one branch. + if (!eligible) + return keep( + settings.worktreeAfterDays !== null || settings.worktreeSettledAfterDays !== null + ? notDueReason + : "umbrella worktrees follow only the age, settled and deletion rules", + ); + const repositories = umbrellaWorktreeRepositories(path, umbrella); + const memberPaths = repositories + .map((repository) => repository.relativePath) + .filter((relativePath) => relativePath !== ""); + const umbrellaChanges = Effect.fnUntraced(function* () { + for (const repository of repositories) { + if (yield* branchChanged(repository.cwd, thread.branch)) + return `branch changed in ${repository.relativePath || "the umbrella folder"}`; + const changes = yield* localChangesReason( + repository.cwd, + settings, + repository.relativePath === "" ? memberPaths : [], + ); + if (changes !== null) + return `${changes} in ${repository.relativePath || "the umbrella folder"}`; + } + return null; + }); + const folderReason = yield* worktreePathReason(worktreePath); + if (folderReason !== null) return keep(folderReason); + const changes = yield* umbrellaChanges(); + if (changes !== null) return keep(changes); + const blocked = yield* blockedSinceCheck(); + if (blocked !== null) return keep(blocked); + return yield* withWorkspaceLease( + worktreePath, + Effect.gen(function* () { + const blockedWhileChecking = yield* blockedSinceCheck(); + if (blockedWhileChecking !== null) return keep(blockedWhileChecking); + const finalChanges = yield* umbrellaChanges(); + if (finalChanges !== null) return keep(finalChanges); + if (yield* settingsChangedSinceCheck) return keep("settings changed since check"); + // Forced only to drop untracked files the checks above allow. + yield* umbrellaWorktrees.remove({ + worktreePath, + force: settings.worktreeKeepWhen === "tracked-changes", + keepManifest: true, + }); + entries.push({ ...entry, outcome: "removed", reason: sentence(removalReason) }); + for (const repository of repositories) { + yield* gitManager.invalidateStatus(repository.source); + } + // The manifest, branch and path stay so the next turn recreates the same layout. + yield* Effect.logInfo("storage cleanup removed umbrella worktree", { + threadId: thread.id, + }); + }), + ); + } const pathReason = yield* worktreePathReason(worktreePath); if (pathReason !== null) return keep(pathReason); if (yield* containsProjectRoot(worktreePaths, [project, ...snapshot.projects])) @@ -1694,8 +1769,12 @@ const make = Effect.gen(function* () { })).slice(0, -1), ); } + // An umbrella worktree's members keep their refs in each member's own repository. + const umbrella = + row.worktreePath === null ? null : yield* umbrellaWorktrees.read(row.worktreePath); + const memberSources = umbrella?.members.map((member) => member.source) ?? []; // A worktree may already be gone; its refs live in the shared repository. - for (const cwd of [row.cwd, row.worktreePath, row.workspaceRoot]) { + for (const cwd of [row.cwd, row.worktreePath, row.workspaceRoot, ...memberSources]) { if (cwd === null) continue; const key = path.resolve(cwd); const owned = targets.get(key) ?? new Set(); diff --git a/apps/server/src/vcs/GitVcsDriver.ts b/apps/server/src/vcs/GitVcsDriver.ts index d0da1b3d09b3d..8b10970428540 100644 --- a/apps/server/src/vcs/GitVcsDriver.ts +++ b/apps/server/src/vcs/GitVcsDriver.ts @@ -47,6 +47,7 @@ import { splitNullSeparatedGitStdoutPaths, } from "./GitVcsDriverCore.ts"; import * as CheckoutCloner from "./CheckoutCloner.ts"; +import { excludePathspecs, UmbrellaMemberIndex } from "./UmbrellaMemberIndex.ts"; import * as CheckpointUntrackedBlobs from "./checkpointUntrackedBlobs.ts"; import * as VcsDriver from "./VcsDriver.ts"; import * as VcsProcess from "./VcsProcess.ts"; @@ -611,12 +612,53 @@ const HEAD_MOVES_SCAN_LIMIT = 512; const HEAD_MARK_TRAILER = "T3-Head-Moved-At"; const HEAD_MARK_TRAILER_PATTERN = new RegExp(`^${HEAD_MARK_TRAILER}: (\\d+) (\\d+)$`, "m"); +/** Prefixes each path in `git diff --numstat -z` output, whose renames carry two paths. */ +function prefixNumstatPaths(numstat: string, prefix: string): string { + const records = numstat.split("\0"); + for (let index = 0; index < records.length; index += 1) { + const counts = /^(?:\d+|-)\t(?:\d+|-)\t/.exec(records[index]!); + if (!counts) continue; + const path = records[index]!.slice(counts[0].length); + if (path.length > 0) { + records[index] = `${counts[0]}${prefix}${path}`; + continue; + } + for (const renamed of [index + 1, index + 2]) { + if (records[renamed] !== undefined) records[renamed] = `${prefix}${records[renamed]}`; + } + index += 2; + } + return records.join("\0"); +} + +/** `--src-prefix`/`--dst-prefix` leave rename and copy headers bare; Git quotes unusual paths. */ +function prefixPatchHeaderPaths(patch: string, prefix: string): string { + return patch.replace( + /^((?:rename|copy) (?:from|to) )("?)/gm, + (_match, header: string, quote: string) => `${header}${quote}${prefix}`, + ); +} + export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* () { const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; const vcsProcess = yield* VcsProcess.VcsProcess; const random = yield* SecureRandom.SecureRandom; const hostPlatform = yield* HostProcess.Platform; + const umbrellaMembers = yield* UmbrellaMemberIndex; + // Umbrella members keep their own checkpoints; the enclosing repository's must not stage or restore them. + // Git skips ignored members by itself, and git add fails on a pathspec naming one, excluding or not. + const memberExclusionsUnder = (cwd: string) => + umbrellaMembers.hasMembers() + ? fileSystem.realPath(cwd).pipe( + Effect.map((resolved) => umbrellaMembers.memberPathsWithin(resolved)), + Effect.flatMap((paths) => + filterIgnoredPaths(cwd, paths).pipe(Effect.orElseSucceed(() => paths)), + ), + Effect.map(excludePathspecs), + Effect.orElseSucceed((): ReadonlyArray => []), + ) + : Effect.succeed>([]); // Returns stdout, or null when there is no work tree. A non-repository exits 128 like a broken // one, so only Git's message (pinned to the C locale) or a missing cwd tells them apart. const probeWorkTree = Effect.fn("GitVcsDriver.probeWorkTree")(function* ( @@ -1394,6 +1436,7 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( ? CheckpointUntrackedBlobs.NOTHING : yield* untrackedBlobs.reuse({ ...untracked, indexConfig }); + const memberExclusions = yield* memberExclusionsUnder(input.cwd); const stageFiles = (exclusions: ReadonlyArray) => execute({ operation, @@ -1411,6 +1454,7 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( workspaceIgnored ? "-u" : "-A", "--", ".", + ...memberExclusions, ...exclusions, ], env: commitEnv, @@ -1851,6 +1895,7 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( yield* Effect.addFinalizer((exit) => mutationStarted && Exit.hasInterrupts(exit) ? resetIndex.pipe(Effect.ignore) : Effect.void, ); + const memberExclusions = yield* memberExclusionsUnder(input.cwd); // An empty index and checkpoint have nothing for git restore's pathspec to match. if (tracked.stdout.length > 0) { const restore = [...longPaths, "restore", "--source", commitOid, "--worktree", "--staged"]; @@ -1859,7 +1904,13 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( yield* execute({ operation, cwd: input.cwd, - args: [...restore, ...(sparseCheckout ? [] : ["--ignore-skip-worktree-bits"]), "--", "."], + args: [ + ...restore, + ...(sparseCheckout ? [] : ["--ignore-skip-worktree-bits"]), + "--", + ".", + ...memberExclusions, + ], onSpawn, }); if (sparseCheckout) { @@ -1936,7 +1987,7 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( const clean = execute({ operation, cwd: input.cwd, - args: [...longPaths, "clean", "-fd", "--", "."], + args: [...longPaths, "clean", "-fd", "--", ".", ...memberExclusions], env: { LC_ALL: "C" }, allowNonZeroExit: true, onSpawn, @@ -1956,7 +2007,7 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( const remaining = yield* execute({ operation, cwd: input.cwd, - args: [...longPaths, "clean", "-dn", "--", "."], + args: [...longPaths, "clean", "-dn", "--", ".", ...memberExclusions], env: { LC_ALL: "C" }, }); if (/^Would remove /m.test(remaining.stdout)) { @@ -2069,7 +2120,9 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( "--no-ext-diff", "--no-textconv", "--submodule=short", - ...PATCH_RENDER_PREFIX_ARGS, + ...(input.pathPrefix + ? [`--src-prefix=a/${input.pathPrefix}`, `--dst-prefix=b/${input.pathPrefix}`] + : PATCH_RENDER_PREFIX_ARGS), ...(input.ignoreWhitespace ? ["--ignore-all-space"] : []), `${fromRevision}^{commit}`, `${input.toCheckpointRef}^{commit}`, @@ -2093,7 +2146,10 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( }); } - return result.stdout; + if (!input.pathPrefix) return result.stdout; + return input.format === "numstat" + ? prefixNumstatPaths(result.stdout, input.pathPrefix) + : prefixPatchHeaderPaths(result.stdout, input.pathPrefix); }), listAuthoredPaths: Effect.fn("GitVcsDriver.checkpoints.listAuthoredPaths")(function* (input) { diff --git a/apps/server/src/vcs/GitVcsDriverCore.test.ts b/apps/server/src/vcs/GitVcsDriverCore.test.ts index efaf9826408cd..e947365f6fa90 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.test.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.test.ts @@ -52,6 +52,7 @@ import { } from "./GitVcsDriverCore.ts"; import * as GitVcsDriver from "./GitVcsDriver.ts"; import { VcsAutomaticFetchInterval } from "./VcsAutomaticFetchInterval.ts"; +import * as UmbrellaMemberIndex from "./UmbrellaMemberIndex.ts"; import { gitConfigEnv } from "./VcsProcess.ts"; const encodeGitCommandError = Schema.encodeEffect(Schema.fromJsonString(GitCommandError)); @@ -3447,6 +3448,62 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { }), ); + it.effect("leaves umbrella members out of the enclosing repository", () => + Effect.gen(function* () { + const cwd = NodeFS.realpathSync.native(yield* makeTmpDir()); + yield* initRepoWithCommit(cwd); + const member = `${cwd}/apps/api`; + yield* (yield* FileSystem.FileSystem).makeDirectory(member, { recursive: true }); + yield* initRepoWithCommit(member); + yield* writeTextFile(member, "README.md", "# member change\n"); + yield* writeTextFile(cwd, "README.md", "# tracked change\n"); + const index = UmbrellaMemberIndex.makeIndex(); + yield* index.replace(new Map([[cwd, [{ path: member, relativePath: "apps/api" }]]])); + const driver = yield* makeGitVcsDriverCore().pipe( + Effect.provideService(UmbrellaMemberIndex.UmbrellaMemberIndex, index), + Effect.provide(layerServerConfig), + ); + + const status = yield* driver.statusDetailsLocal(cwd, { includeBranchChanges: true }); + assert.deepStrictEqual( + status.workingTree.files.map((file) => file.path), + ["README.md"], + ); + assert.deepStrictEqual(status.branchChanges, { + baseRef: null, + insertions: 1, + deletions: 1, + }); + const preview = yield* driver.getReviewDiffPreview({ cwd, ignoreWhitespace: false }); + const diff = preview.sources.find((source) => source.kind === "working-tree")?.diff ?? ""; + assert.include(diff, "+# tracked change"); + assert.notInclude(diff, "apps/api"); + + yield* driver.commit(cwd, "outer change", "", { stage: {} }); + assert.equal(yield* git(cwd, ["ls-files", "apps"]), ""); + }), + ); + + it.effect("commits an umbrella repository that ignores its members", () => + Effect.gen(function* () { + const cwd = NodeFS.realpathSync.native(yield* makeTmpDir()); + yield* initRepoWithCommit(cwd); + yield* writeTextFile(cwd, ".gitignore", "/api/\n"); + const member = `${cwd}/api`; + yield* (yield* FileSystem.FileSystem).makeDirectory(member); + yield* initRepoWithCommit(member); + const index = UmbrellaMemberIndex.makeIndex(); + yield* index.replace(new Map([[cwd, [{ path: member, relativePath: "api" }]]])); + const driver = yield* makeGitVcsDriverCore().pipe( + Effect.provideService(UmbrellaMemberIndex.UmbrellaMemberIndex, index), + Effect.provide(layerServerConfig), + ); + + yield* driver.commit(cwd, "ignore members", "", { stage: {} }); + assert.equal(yield* git(cwd, ["ls-files"]), ".gitignore\nREADME.md"); + }), + ); + it.effect("keeps untracked filenames with pathspec magic in the review", () => Effect.gen(function* () { const cwd = yield* makeTmpDir(); diff --git a/apps/server/src/vcs/GitVcsDriverCore.ts b/apps/server/src/vcs/GitVcsDriverCore.ts index 89bb1fa039ddd..4c4ba4d9d2439 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.ts @@ -47,6 +47,7 @@ import { gitCommandDuration, gitCommandsTotal, withMetrics } from "../observabil import * as GitVcsDriver from "./GitVcsDriver.ts"; import { removeEmptyDirectory, type RemoveEmptyDirectoryError } from "./removeEmptyDirectory.ts"; import { VcsAutomaticFetchInterval } from "./VcsAutomaticFetchInterval.ts"; +import { excludePathspecs, UmbrellaMemberIndex } from "./UmbrellaMemberIndex.ts"; import { explicitBareRepositoryEnv, gitConfigEnv, @@ -1024,6 +1025,10 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* const hostPlatform = yield* HostProcess.Platform; const serviceScope = yield* Effect.scope; const automaticFetchInterval = yield* VcsAutomaticFetchInterval; + const umbrellaMembers = yield* UmbrellaMemberIndex; + // Umbrella members checked out inside a work tree are separate projects' files, not this repository's. + const memberExclusions = (worktreeRoot: string | null | undefined): ReadonlyArray => + worktreeRoot ? excludePathspecs(umbrellaMembers.memberPathsWithin(worktreeRoot)) : []; type StatusFetchState = { phase: "queued" | "running" | "claimed"; claimed: Deferred.Deferred; @@ -2401,10 +2406,11 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* Effect.catchTags({ GitCommandError: () => Effect.succeed(null) }), ); const statusCacheKey = repositoryPaths?.gitCommonDir; + const exclusions = memberExclusions(repositoryPaths?.worktreeRoot); const readStatus = executeGitWithStableDiagnostics( "GitVcsDriver.statusDetails.status", cwd, - statusArgs, + exclusions.length === 0 ? statusArgs : [...statusArgs, "--", ...exclusions], { allowNonZeroExit: true, maxOutputBytes: REVIEW_METADATA_MAX_OUTPUT_BYTES, @@ -2420,7 +2426,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* executeGitWithStableDiagnostics( "GitVcsDriver.statusDetails.numstat", cwd, - ["diff-index", "-M", "--numstat", "-z", ref, "--"], + ["diff-index", "-M", "--numstat", "-z", ref, "--", ...exclusions], { allowNonZeroExit: true, maxOutputBytes: REVIEW_METADATA_MAX_OUTPUT_BYTES }, ); // diff-index does not read status output, so both spawn together; a non-repository discards it. @@ -2895,10 +2901,27 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* }); } } + const worktreeRoot = umbrellaMembers.hasMembers() + ? (yield* resolveRepositoryPaths(cwd).pipe(Effect.orElseSucceed(() => null)))?.worktreeRoot + : undefined; + const members = worktreeRoot ? umbrellaMembers.memberPathsWithin(worktreeRoot) : []; + // git add fails on a pathspec naming an ignored member, excluding or not; it skips those anyway. + const ignored = + worktreeRoot && members.length > 0 + ? splitNullSeparatedGitStdoutPaths( + yield* executeGit( + "GitVcsDriver.commit.ignoredMembers", + worktreeRoot, + ["check-ignore", "--no-index", "-z", "--stdin"], + { allowNonZeroExit: true, stdin: `${members.join("\0")}\0` }, + ), + ) + : []; + const exclusions = excludePathspecs(members.filter((member) => !ignored.includes(member))); yield* runGit( "GitVcsDriver.commit.addAll", cwd, - [...config, "add", "-A"], + [...config, "add", "-A", ...(exclusions.length === 0 ? [] : ["--", ...exclusions])], env ? { env } : {}, ); } @@ -3894,10 +3917,14 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* } const roots = options?.untrackedRoots ?? []; // Bound pathspec matching work and stay below Windows' command-line limit. - const pathspecs = - roots.length <= 128 && roots.reduce((length, root) => length + root.length + 16, 0) < 8_000 + const exclusions = memberExclusions(cwd); + const pathspecs = [ + ...(roots.length <= 128 && + roots.reduce((length, root) => length + root.length + 16, 0) < 8_000 ? roots.map((root) => `:(top,literal)${root}`) - : []; + : []), + ...exclusions, + ]; // Changed untracked roots skip the backoff and scan again. const rootsKey = roots.join("\0"); const remembered = untrackedTotalsFailures.get(cwd); @@ -3946,7 +3973,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* "GitVcsDriver.readBranchChangeTotals", cwd, // Plumbing: porcelain diff refreshes and rewrites the real index, taking index.lock. - ["diff-index", "-M", "--numstat", "-z", ref, "--"], + ["diff-index", "-M", "--numstat", "-z", ref, "--", ...exclusions], { allowNonZeroExit: true, maxOutputBytes: REVIEW_METADATA_MAX_OUTPUT_BYTES, @@ -4137,7 +4164,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* const getReviewDiffPreview = Effect.fn("getReviewDiffPreview")(function* ( input: ReviewDiffPreviewInput, ) { - const pathArgs = input.file + const filePathArgs = input.file ? [input.file.path, ...(input.file.previousPath ? [input.file.previousPath] : [])].map( (path) => `:(top,literal)${path}`, ) @@ -4169,6 +4196,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* } const cwd = repository.worktreeRoot; + const pathArgs = [...filePathArgs, ...memberExclusions(cwd)]; const hashDiff = (diff: string, files: ReadonlyArray) => digest.digest(Digest.sha256, new TextEncoder().encode(JSON.stringify([diff, files]))).pipe( Effect.map(Hex.encode), diff --git a/apps/server/src/vcs/UmbrellaMemberIndex.test.ts b/apps/server/src/vcs/UmbrellaMemberIndex.test.ts new file mode 100644 index 0000000000000..fdecc102947a7 --- /dev/null +++ b/apps/server/src/vcs/UmbrellaMemberIndex.test.ts @@ -0,0 +1,24 @@ +import { it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import { expect } from "vite-plus/test"; + +import { makeIndex } from "./UmbrellaMemberIndex.ts"; + +it.effect("leaves out only the members of the umbrella rooted at the work tree", () => + Effect.gen(function* () { + const index = makeIndex(); + yield* index.replace( + new Map([ + ["/clients/acme", [{ path: "/clients/acme/api", relativePath: "api" }]], + ["/clients/beta", [{ path: "/work/beta-site", relativePath: "../../work/beta-site" }]], + ]), + ); + + expect(index.memberPathsWithin("/clients/acme")).toEqual(["api"]); + // A repository that merely encloses an umbrella, or holds another umbrella's adopted + // checkout, keeps its own view. + expect(index.memberPathsWithin("/clients")).toEqual([]); + expect(index.memberPathsWithin("/work")).toEqual([]); + expect(index.memberPathsWithin("/clients/beta")).toEqual([]); + }), +); diff --git a/apps/server/src/vcs/UmbrellaMemberIndex.ts b/apps/server/src/vcs/UmbrellaMemberIndex.ts new file mode 100644 index 0000000000000..b2ba92c211db9 --- /dev/null +++ b/apps/server/src/vcs/UmbrellaMemberIndex.ts @@ -0,0 +1,97 @@ +// @effect-diagnostics nodeBuiltinImport:off +// Git reads consult this synchronously, so a repository's own status, diffs, and checkpoints +// leave out the umbrella members checked out inside it. +import * as NodePath from "node:path"; + +import * as Context from "effect/Context"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; + +export interface UmbrellaMemberCheckout { + /** Symlink-resolved absolute path. */ + readonly path: string; + /** Relative to the umbrella root, with `/` separators. */ + readonly relativePath: string; +} + +interface UmbrellaMemberIndexShape { + /** Replaces every umbrella, keyed by symlink-resolved root. */ + readonly replace: ( + umbrellas: ReadonlyMap>, + ) => Effect.Effect; + /** Adds or replaces one worktree-mode thread's folder, which `replace` leaves alone. */ + readonly registerWorktree: ( + resolvedRoot: string, + members: ReadonlyArray, + ) => Effect.Effect; + readonly forgetWorktree: (resolvedRoot: string) => Effect.Effect; + readonly membersOf: (resolvedRoot: string) => ReadonlyArray; + readonly hasMembers: () => boolean; + /** Members of the umbrella rooted at this work tree that sit inside it, relative with `/` separators. */ + readonly memberPathsWithin: (resolvedWorktreeRoot: string) => ReadonlyArray; +} + +const EMPTY: ReadonlyArray = []; + +/** Pathspecs that leave these paths, relative to the work tree's top, out of a Git command. */ +export const excludePathspecs = (paths: ReadonlyArray) => + paths.map((path) => `:(top,exclude,literal)${path}`); + +const isStrictlyWithin = (root: string, candidate: string) => { + const relative = NodePath.relative(root, candidate); + return ( + relative !== "" && + relative !== ".." && + !relative.startsWith(`..${NodePath.sep}`) && + !NodePath.isAbsolute(relative) + ); +}; + +export const makeIndex = (): UmbrellaMemberIndexShape => { + let umbrellas = new Map>(); + const worktrees = new Map>(); + const lookup = (root: string) => umbrellas.get(root) ?? worktrees.get(root) ?? EMPTY; + return { + replace: (next) => + Effect.sync(() => { + umbrellas = new Map( + Array.from(next, ([root, members]) => [NodePath.resolve(root), members] as const), + ); + }), + registerWorktree: (resolvedRoot, members) => + Effect.sync(() => { + worktrees.set(NodePath.resolve(resolvedRoot), members); + }), + forgetWorktree: (resolvedRoot) => + Effect.sync(() => { + worktrees.delete(NodePath.resolve(resolvedRoot)); + }), + membersOf: (resolvedRoot) => lookup(NodePath.resolve(resolvedRoot)), + hasMembers: () => umbrellas.size > 0 || worktrees.size > 0, + memberPathsWithin: (resolvedWorktreeRoot) => { + if (umbrellas.size === 0 && worktrees.size === 0) return EMPTY; + const root = NodePath.resolve(resolvedWorktreeRoot); + return lookup(root) + .map((member) => NodePath.resolve(member.path)) + .filter((member) => isStrictlyWithin(root, member)) + .map((member) => NodePath.relative(root, member).split(NodePath.sep).join("/")); + }, + }; +}; + +/** Defaults to an empty index, so git keeps its plain behavior wherever no umbrella layer is provided. */ +export class UmbrellaMemberIndex extends Context.Reference( + "t3/vcs/UmbrellaMemberIndex", + { + defaultValue: () => ({ + replace: () => Effect.void, + registerWorktree: () => Effect.void, + forgetWorktree: () => Effect.void, + membersOf: () => EMPTY, + hasMembers: () => false, + memberPathsWithin: () => EMPTY, + }), + }, +) {} + +export const layer = Layer.sync(UmbrellaMemberIndex, makeIndex); diff --git a/apps/server/src/vcs/VcsDriver.ts b/apps/server/src/vcs/VcsDriver.ts index 383db4302543f..f85246db77683 100644 --- a/apps/server/src/vcs/VcsDriver.ts +++ b/apps/server/src/vcs/VcsDriver.ts @@ -37,6 +37,8 @@ export interface VcsDiffCheckpointsInput { readonly maxOutputBytes?: number; /** An empty list yields an empty diff. */ readonly filePaths?: ReadonlyArray; + /** Prepended to every reported path, e.g. `apps/api/` for a member diffed inside its umbrella. */ + readonly pathPrefix?: string; } export interface VcsListAuthoredPathsInput { diff --git a/apps/server/src/workspace/KnownWorkspaces.ts b/apps/server/src/workspace/KnownWorkspaces.ts index f442e4cedbb61..7881db214b4da 100644 --- a/apps/server/src/workspace/KnownWorkspaces.ts +++ b/apps/server/src/workspace/KnownWorkspaces.ts @@ -1,4 +1,5 @@ // Client-supplied worktrees count only under managed folders or when Git lists them for the project. +import type { ServerSettings as ServerSettingsSchema } from "@t3tools/contracts"; import * as HostProcess from "@t3tools/shared/HostProcess"; import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient"; import * as Context from "effect/Context"; @@ -72,7 +73,11 @@ export const make = Effect.gen(function* () { function* (realPath) { const within = (root: string | null) => root !== null && isWithinRoot(path, realPath, root); const worktreeSettings = yield* settings.getSettings.pipe( - Effect.orElseSucceed(() => ({ worktreesDirectory: "", previousWorktreesDirectories: [] })), + Effect.orElseSucceed(() => ({ + worktreesDirectory: "", + previousWorktreesDirectories: [], + projectSettingsOverrides: {} as ServerSettingsSchema["projectSettingsOverrides"], + })), ); const home = yield* HostProcess.HomeDirectory; const managedDirectories = managedWorktreesDirectories( @@ -90,6 +95,15 @@ export const make = Effect.gen(function* () { for (const project of projects) { if (within(yield* resolveRoot(project.workspaceRoot))) return true; } + // Members a turned-on umbrella adopted from outside the project's folder. + for (const project of projects) { + const overrides = worktreeSettings.projectSettingsOverrides[project.id]; + const adopted = + overrides?.umbrellaEnabled === true ? (overrides.umbrellaAdoptedPaths ?? []) : []; + for (const member of adopted) { + if (within(yield* resolveRoot(path.resolve(project.workspaceRoot, member)))) return true; + } + } const threads = yield* sql<{ readonly worktreePath: string; readonly projectId: string }>` SELECT DISTINCT diff --git a/apps/server/src/workspace/recreateBranchWorktree.ts b/apps/server/src/workspace/recreateBranchWorktree.ts new file mode 100644 index 0000000000000..c7d8da9b6d691 --- /dev/null +++ b/apps/server/src/workspace/recreateBranchWorktree.ts @@ -0,0 +1,82 @@ +import * as Effect from "effect/Effect"; +import * as Schema from "effect/Schema"; + +import * as GitWorkflowService from "../git/GitWorkflowService.ts"; + +export class WorktreeRecreateNoBaseError extends Schema.TaggedError()( + "WorktreeRecreateNoBaseError", + { worktreePath: Schema.String, branch: Schema.String }, +) { + override get message(): string { + return `Could not recreate branch '${this.branch}' at ${this.worktreePath}: the project workspace has no commit to start it from.`; + } +} + +const resolveRecreateBase = Effect.fn("recreateBranchWorktree.resolveRecreateBase")(function* ( + cwd: string, + remoteName: string | null, +) { + const gitWorkflow = yield* GitWorkflowService.GitWorkflowService; + // Recovery can follow an external checkout, before the status cache expires. + yield* gitWorkflow.invalidateLocalStatus(cwd); + const { refName: currentBranch } = yield* gitWorkflow.localStatus({ cwd }); + if (currentBranch !== null) { + const refName = `refs/heads/${currentBranch}`; + return { refName, baseRefName: refName }; + } + const remoteHead = `refs/remotes/${remoteName}/HEAD`; + if (remoteName !== null && (yield* gitWorkflow.hasCommit({ cwd, refName: remoteHead }))) { + const { commitSha } = yield* gitWorkflow.resolveRemoteTrackingCommit({ + cwd, + refName: "HEAD", + fallbackRemoteName: remoteName, + }); + // Start from the commit so the thread branch does not track the default branch. + return { refName: commitSha, baseRefName: remoteHead }; + } + if (yield* gitWorkflow.hasCommit({ cwd, refName: "HEAD" })) { + return { refName: "HEAD", baseRefName: undefined }; + } + return null; +}); + +/** Checks `branch` out at `worktreePath` again: the local branch, else its pushed copy, else a new branch from the checkout. */ +export const recreateBranchWorktree = Effect.fn("recreateBranchWorktree")(function* (input: { + readonly cwd: string; + readonly worktreePath: string; + readonly branch: string; +}) { + const gitWorkflow = yield* GitWorkflowService.GitWorkflowService; + const { cwd, worktreePath, branch } = input; + yield* gitWorkflow.pruneWorktrees({ cwd }); + const localBranchNames = yield* gitWorkflow.listLocalBranchNames(cwd); + if (localBranchNames.includes(branch)) { + yield* gitWorkflow.createWorktree({ cwd, refName: branch, path: worktreePath }); + return; + } + const remoteName = yield* gitWorkflow + .resolvePrimaryRemoteName(cwd) + .pipe(Effect.orElseSucceed(() => null)); + // Push keeps the tracking ref current, so recovery reads it without fetching. + const pushedRef = remoteName === null ? null : `refs/remotes/${remoteName}/${branch}`; + if (pushedRef !== null && (yield* gitWorkflow.hasCommit({ cwd, refName: pushedRef }))) { + yield* gitWorkflow.createWorktree({ + cwd, + refName: pushedRef, + newRefName: branch, + path: worktreePath, + }); + return; + } + const base = yield* resolveRecreateBase(cwd, remoteName); + if (base === null) { + return yield* new WorktreeRecreateNoBaseError({ worktreePath, branch }); + } + yield* gitWorkflow.createWorktree({ + cwd, + refName: base.refName, + newRefName: branch, + ...(base.baseRefName === undefined ? {} : { baseRefName: base.baseRefName }), + path: worktreePath, + }); +}); diff --git a/apps/server/src/workspace/restoreMissingWorktree.ts b/apps/server/src/workspace/restoreMissingWorktree.ts index dee23025dbf41..484a3c3d05182 100644 --- a/apps/server/src/workspace/restoreMissingWorktree.ts +++ b/apps/server/src/workspace/restoreMissingWorktree.ts @@ -10,9 +10,11 @@ import * as Schema from "effect/Schema"; import * as ServerConfig from "../config.ts"; import * as GitWorkflowService from "../git/GitWorkflowService.ts"; import { scratchFolderRoot } from "../project/ManagedProjectFolders.ts"; +import { makeUmbrellaWorktrees } from "../project/UmbrellaWorktree.ts"; import * as ProjectService from "../project/ProjectService.ts"; import { makeIsManagedWorktreePath } from "../worktreesDirectory.ts"; import { isWithinRoot } from "./KnownWorkspaces.ts"; +import { recreateBranchWorktree, WorktreeRecreateNoBaseError } from "./recreateBranchWorktree.ts"; import { withWorkspaceLease } from "./workspaceLease.ts"; import { TerminalCwdRecovery } from "../terminal/Manager.ts"; @@ -29,15 +31,6 @@ export class WorktreeRecreateError extends Schema.TaggedError()( - "WorktreeRecreateNoBaseError", - { worktreePath: Schema.String, branch: Schema.String }, -) { - override get message(): string { - return `Could not recreate branch '${this.branch}' at ${this.worktreePath}: the project workspace has no commit to start it from.`; - } -} - // `git worktree remove` skips pnpm junctions on Windows, leaving these behind without a checkout. const LEFTOVER_WORKTREE_ENTRIES = new Set(["node_modules", ".next"]); @@ -55,6 +48,7 @@ export const makeRestoreMissingWorktree = Effect.gen(function* () { const projects = yield* ProjectService.ProjectService; const isManagedWorktreePath = yield* makeIsManagedWorktreePath; const serverConfig = yield* ServerConfig.ServerConfig; + const umbrellaWorktrees = yield* makeUmbrellaWorktrees; // Storage cleanup prunes idle No project folders, which have no branch to restore from. // An empty folder, only directly inside the No project's own root, lets the thread run again. @@ -99,76 +93,26 @@ export const makeRestoreMissingWorktree = Effect.gen(function* () { Effect.orElseSucceed(() => false), ); - const resolveRecreateBase = Effect.fn("restoreMissingWorktree.resolveRecreateBase")(function* ( - cwd: string, - remoteName: string | null, - ) { - // Recovery can follow an external checkout, before the status cache expires. - yield* gitWorkflow.invalidateLocalStatus(cwd); - const { refName: currentBranch } = yield* gitWorkflow.localStatus({ cwd }); - if (currentBranch !== null) { - const refName = `refs/heads/${currentBranch}`; - return { refName, baseRefName: refName }; - } - const remoteHead = `refs/remotes/${remoteName}/HEAD`; - if (remoteName !== null && (yield* gitWorkflow.hasCommit({ cwd, refName: remoteHead }))) { - const { commitSha } = yield* gitWorkflow.resolveRemoteTrackingCommit({ - cwd, - refName: "HEAD", - fallbackRemoteName: remoteName, - }); - // Start from the commit so the thread branch does not track the default branch. - return { refName: commitSha, baseRefName: remoteHead }; - } - if (yield* gitWorkflow.hasCommit({ cwd, refName: "HEAD" })) { - return { refName: "HEAD", baseRefName: undefined }; - } - return null; - }); - - const recreateMissingWorktree = Effect.fn("restoreMissingWorktree.recreate")(function* (input: { - readonly cwd: string; - readonly worktreePath: string; - readonly branch: string; - }) { - const { cwd, worktreePath, branch } = input; - yield* gitWorkflow.pruneWorktrees({ cwd }); - const localBranchNames = yield* gitWorkflow.listLocalBranchNames(cwd); - if (localBranchNames.includes(branch)) { - yield* gitWorkflow.createWorktree({ cwd, refName: branch, path: worktreePath }); - return; - } - const remoteName = yield* gitWorkflow - .resolvePrimaryRemoteName(cwd) - .pipe(Effect.orElseSucceed(() => null)); - // Push keeps the tracking ref current, so recovery reads it without fetching. - const pushedRef = remoteName === null ? null : `refs/remotes/${remoteName}/${branch}`; - if (pushedRef !== null && (yield* gitWorkflow.hasCommit({ cwd, refName: pushedRef }))) { - yield* gitWorkflow.createWorktree({ - cwd, - refName: pushedRef, - newRefName: branch, - path: worktreePath, - }); - return; - } - const base = yield* resolveRecreateBase(cwd, remoteName); - if (base === null) { - return yield* new WorktreeRecreateNoBaseError({ worktreePath, branch }); - } - yield* gitWorkflow.createWorktree({ - cwd, - refName: base.refName, - newRefName: branch, - ...(base.baseRefName === undefined ? {} : { baseRefName: base.baseRefName }), - path: worktreePath, - }); - }); - return Effect.fn("restoreMissingWorktree")(function* (thread: WorktreeThread) { const { worktreePath, branch } = thread; if (worktreePath === null) return; if (branch === null) return yield* recreateScratchFolder(thread, worktreePath); + // An umbrella worktree recreates each missing repository on its own. + if ( + (yield* umbrellaWorktrees.read(worktreePath)) !== null && + (yield* isManagedWorktreePath(worktreePath)) + ) { + yield* umbrellaWorktrees + .restoreMissing({ worktreePath, branch }) + .pipe( + Effect.mapError((cause) => + cause._tag === "WorktreeRecreateNoBaseError" + ? cause + : new WorktreeRecreateError({ worktreePath, branch, cause }), + ), + ); + return; + } const exists = yield* fileSystem.exists(worktreePath).pipe(Effect.orElseSucceed(() => true)); const leftover = exists && (yield* isLeftoverFolder(worktreePath)); if ((exists && !leftover) || !(yield* isManagedWorktreePath(worktreePath))) return; @@ -184,7 +128,11 @@ export const makeRestoreMissingWorktree = Effect.gen(function* () { }); // `git worktree add` refuses a non-empty target. yield* (leftover ? fileSystem.remove(worktreePath, { recursive: true }) : Effect.void).pipe( - Effect.andThen(recreateMissingWorktree({ cwd: project.workspaceRoot, worktreePath, branch })), + Effect.andThen( + recreateBranchWorktree({ cwd: project.workspaceRoot, worktreePath, branch }).pipe( + Effect.provideService(GitWorkflowService.GitWorkflowService, gitWorkflow), + ), + ), Effect.mapError((cause) => cause._tag === "WorktreeRecreateNoBaseError" ? cause diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index 6defac543eaac..14dababeb5f2e 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -27,6 +27,7 @@ import { subscribeChatGptHandoff } from "./provider/CodexChatGptHandoff.ts"; import { AcpRegistryOperationError, CommandId, + GitCommandError, authScopeResponse, AuthAccessStreamError, type AuthAccessStreamEvent, @@ -194,6 +195,7 @@ import * as DatabaseStorage from "./persistence/DatabaseStorage.ts"; import * as StorageCleanup from "./storageCleanup.ts"; import * as TerminalManager from "./terminal/Manager.ts"; import { makePrepareTerminalLaunch } from "./workspace/restoreMissingWorktree.ts"; +import { makeUmbrellaWorktrees } from "./project/UmbrellaWorktree.ts"; import { terminalOutputStream, withOutputWindow } from "./terminal/OutputProtocol.ts"; import * as ServerBrowser from "./preview/ServerBrowser.ts"; import * as DeviceService from "./device/DeviceService.ts"; @@ -221,6 +223,7 @@ import { linkCreatedPullRequest } from "./git/linkCreatedPullRequest.ts"; import * as ReviewService from "./review/ReviewService.ts"; import * as ProjectEnrichmentService from "./project/ProjectEnrichmentService.ts"; import * as ProjectService from "./project/ProjectService.ts"; +import * as UmbrellaMembership from "./project/UmbrellaMembership.ts"; import { threadWorkspaceRoot } from "./project/threadWorkspaceRoot.ts"; import * as ManagedProjectFolders from "./project/ManagedProjectFolders.ts"; import * as ScratchThreadPromotion from "./project/ScratchThreadPromotion.ts"; @@ -884,8 +887,13 @@ const enrichProjectShells = Effect.fn("ws.orchestrationV2.enrichProjectShells")( ), { concurrency: 16 }, ).pipe( - Effect.map((enriched) => ({ - projects: enriched.map((entry) => entry.project), + Effect.flatMap((enriched) => + UmbrellaMembership.attachUmbrellaMembers(enriched.map((entry) => entry.project)).pipe( + Effect.map((projects) => ({ enriched, projects })), + ), + ), + Effect.map(({ enriched, projects }) => ({ + projects, resolvedRepositoryIdentityRoots: enriched .filter((entry) => entry.repositoryIdentityResolved) .map((entry) => entry.project.workspaceRoot), @@ -1147,6 +1155,7 @@ export const subscribeOrchestrationV2Shell = Effect.fn("ws.orchestrationV2.subsc shouldPublishShellApplicationEvent(stored, subagentThreadIds); const enrichmentChanges = yield* projectEnrichment.subscribeChanges; + const umbrellaChanges = yield* UmbrellaMembership.subscribeUmbrellaChanges; const loadProjectMetadataSnapshot = Effect.fn("ws.orchestrationV2.loadProjectMetadataSnapshot")( function* (snapshotSequence: number) { const enriched = yield* enrichProjectShells(yield* projects.listShells()); @@ -1303,6 +1312,42 @@ export const subscribeOrchestrationV2Shell = Effect.fn("ws.orchestrationV2.subsc ), ); + // Members are refreshed as metadata: roots stay out of the identity list, so identities are + // not overwritten. + const umbrellaRefreshes = umbrellaChanges.pipe( + Stream.mapEffect((projectIds) => + Effect.gen(function* () { + const changed = new Set(projectIds); + const affected = (yield* projects.listShells()).filter((project) => + changed.has(project.id), + ); + if (affected.length === 0) return []; + const changedProjects = yield* Effect.forEach( + yield* UmbrellaMembership.attachUmbrellaMembers(affected), + (project) => + projectEnrichment + .peek(project.workspaceRoot) + .pipe(Effect.map(({ repositoryIdentity }) => ({ ...project, repositoryIdentity }))), + ); + return [ + { + kind: "snapshot" as const, + snapshot: { + schemaVersion: ORCHESTRATION_V2_PROJECTION_SCHEMA_VERSION, + snapshotSequence: yield* applicationEvents.latestApplicationSequence, + projects: changedProjects, + threads: [], + archivedThreads: [], + } as OrchestrationV2ShellSnapshot, + resolvedRepositoryIdentityRoots: [] as ReadonlyArray, + }, + ]; + }), + ), + Stream.flatMap(Stream.fromIterable), + ); + const metadataRefreshes = Stream.merge(enrichmentRefreshes, umbrellaRefreshes); + // Subscribe before loading for racing enrichments; initial refresh covers pre-subscription completions and cold HTTP snapshots. const completionMarker = input.requestCompletionMarker === true @@ -1338,7 +1383,7 @@ export const subscribeOrchestrationV2Shell = Effect.fn("ws.orchestrationV2.subsc return composeShellStreamWithEnrichment({ initial: initialSnapshotItems(loaded), tail: completionThenLive(loaded.snapshot.snapshotSequence), - enrichment: enrichmentRefreshes, + enrichment: metadataRefreshes, }); } @@ -1353,7 +1398,7 @@ export const subscribeOrchestrationV2Shell = Effect.fn("ws.orchestrationV2.subsc return composeShellStreamWithEnrichment({ initial: initialSnapshotItems(loaded), tail: completionThenLive(loaded.snapshot.snapshotSequence), - enrichment: enrichmentRefreshes, + enrichment: metadataRefreshes, }); }); const highWater = yield* applicationEvents.latestApplicationSequence; @@ -1393,7 +1438,7 @@ export const subscribeOrchestrationV2Shell = Effect.fn("ws.orchestrationV2.subsc }), }), tail: Stream.concat(Stream.concat(replay, completionMarker), liveFrom(highWater)), - enrichment: enrichmentRefreshes, + enrichment: metadataRefreshes, }); }).pipe( Effect.mapError( @@ -1516,6 +1561,8 @@ export const layerWsRpc = ( const remoteOpenTargets = yield* RemoteOpenTargets.RemoteOpenTargets; const directEndpoints = yield* DirectEndpoints.DirectEndpoints; const gitWorkflow = yield* GitWorkflowService.GitWorkflowService; + const umbrellaWorktrees = yield* makeUmbrellaWorktrees; + const workspacePath = yield* Path.Path; const review = yield* ReviewService.ReviewService; const vcsProvisioning = yield* VcsProvisioningService.VcsProvisioningService; const vcsStatusBroadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster; @@ -3178,7 +3225,24 @@ export const layerWsRpc = ( [WS_METHODS.vcsCreateWorktree]: (input) => gitWorkflow.createWorktree(input).pipe(Effect.tap(() => refreshGitStatus(input.cwd))), [WS_METHODS.vcsRemoveWorktree]: (input) => - gitWorkflow.removeWorktree(input).pipe( + // An umbrella thread's folder holds a worktree of each member, removed together. + (workspacePath.isAbsolute(input.path) + ? umbrellaWorktrees.remove({ worktreePath: input.path, force: input.force === true }) + : Effect.succeed(false) + ).pipe( + Effect.mapError( + (cause) => + new GitCommandError({ + operation: "vcs.removeWorktree", + command: "git worktree remove", + cwd: input.cwd, + detail: cause.message, + cause, + }), + ), + Effect.flatMap((removed) => + removed ? Effect.void : gitWorkflow.removeWorktree(input), + ), Effect.tap(() => refreshGitStatus(input.cwd)), // Subscribers of the removed checkout learn it is no longer a repository. Effect.tap(() => diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index fbec56205975c..407e3c8d06b2e 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -1764,6 +1764,12 @@ export default function ChatView(props: ChatViewProps) { } }, [environmentId, gitStatusCwd, liveIsGitRepo]); const isGitRepo = liveIsGitRepo ?? recallCheckoutIsRepo(environmentId, gitStatusCwd) ?? true; + // A plain folder holding git checkouts still has member diffs, or the umbrella prompt, to show. + const hasUmbrellaCheckouts = + activeThreadWorktreePath === null && + ((activeProject?.umbrellaMembers?.length ?? 0) > 0 || + (activeProject?.umbrellaSuggestions?.length ?? 0) > 0); + const diffAvailable = isServerThread && (isGitRepo || hasUmbrellaCheckouts); // Provider-native subagents cannot take messages; approvals and questions go to the top-level parent. const showProviderSubagentBar = isProviderSubagent; const composerMounted = !showProviderSubagentBar; @@ -2418,7 +2424,7 @@ export default function ChatView(props: ChatViewProps) { threadPanelPresentation, isServerThread, embedded, - isGitRepo, + diffAvailable, browserAvailable, canOperatePreview, diffOpen, @@ -4040,7 +4046,7 @@ export default function ChatView(props: ChatViewProps) { onAddSideChat={sideChatsOffered ? openSideChatStable : undefined} browserAvailable={canOperatePreview && browserAvailable} terminalAvailable={activeProject !== null && canOperateTerminal} - diffAvailable={isServerThread && isGitRepo} + diffAvailable={diffAvailable} filesAvailable={activeProject !== null} pullRequestAvailable={pullRequestSurfaceAvailable} pullRequestsAvailable={pullRequestsSurfaceAvailable} diff --git a/apps/web/src/components/CommandPalette.logic.test.ts b/apps/web/src/components/CommandPalette.logic.test.ts index 8ba78e2639fdc..b089d8b0fc319 100644 --- a/apps/web/src/components/CommandPalette.logic.test.ts +++ b/apps/web/src/components/CommandPalette.logic.test.ts @@ -471,6 +471,39 @@ describe("buildThreadActionItems", () => { expect(labels("lake")).toEqual(["Threads", "Projects"]); }); + it("lists an umbrella above its matching members, and keeps it only while one matches", () => { + const row = (value: string, title: string, parentValue?: string) => ({ + kind: "action" as const, + value, + searchTerms: [title], + title, + icon: null, + run: async () => undefined, + ...(parentValue ? { parentValue } : {}), + }); + const projectSearchItems = [ + row("project:fleet", "fleet"), + row("project:northwind", "northwind"), + row("member:api", "api", "project:northwind"), + row("member:dev-setup", "dev-setup", "project:northwind"), + row("member:storefront", "storefront", "project:northwind"), + ]; + const rows = (query: string) => + filterCommandPaletteGroups({ + activeGroups: [], + query, + isInSubmenu: false, + projectSearchItems, + threadSearchItems: [], + }).flatMap((group) => group.items.map((item) => item.title)); + expect(rows("s")).toEqual(["northwind", "dev-setup", "storefront"]); + expect(rows("st")).toEqual(["northwind", "storefront"]); + expect(rows("stq")).toEqual([]); + expect(rows("f")).toEqual(["fleet"]); + // The umbrella's own name keeps it with no member matching. + expect(rows("north")).toEqual(["northwind"]); + }); + it("keeps a command first over a thread in daily use that matches as well", () => { const now = Date.parse("2026-10-23T00:00:00.000Z"); const threadSearchItems = buildThreadActionItems({ diff --git a/apps/web/src/components/CommandPalette.logic.ts b/apps/web/src/components/CommandPalette.logic.ts index 2456ca357e178..68295146e48cc 100644 --- a/apps/web/src/components/CommandPalette.logic.ts +++ b/apps/web/src/components/CommandPalette.logic.ts @@ -206,6 +206,8 @@ export interface CommandPaletteItem { readonly titleTrailingContent?: ReactNode; readonly shortcutCommand?: KeybindingCommand; readonly secondary?: boolean; + /** Lists the row indented under the row with this value, which a search keeps while this one matches. */ + readonly parentValue?: string; } export interface CommandPaletteActionItem extends CommandPaletteItem { @@ -553,6 +555,40 @@ function scorePaletteItem( return match && (item.title === terms[0] ? match : { ...match, ranges: [] }); } +/** + * Lists each matching child under its parent, at the place of whichever ranks first. A parent + * that does not match stays while any of its children does, so it carries no match. + */ +function nestUnderParents, TMatch>( + ranked: ReadonlyArray<{ readonly item: TItem; readonly match: TMatch }>, + items: ReadonlyArray, +): Array<{ readonly item: TItem; readonly match: TMatch | undefined }> { + const itemByValue = new Map(items.map((item) => [item.value, item] as const)); + const parentOf = (item: TItem) => + item.parentValue !== undefined && itemByValue.has(item.parentValue) + ? item.parentValue + : undefined; + const rankedByValue = new Map(ranked.map((entry) => [entry.item.value, entry] as const)); + const childrenOf = new Map>(); + for (const entry of ranked) { + const parent = parentOf(entry.item); + if (parent === undefined) continue; + const children = childrenOf.get(parent); + if (children) children.push(entry); + else childrenOf.set(parent, [entry]); + } + const nested: Array<{ readonly item: TItem; readonly match: TMatch | undefined }> = []; + const placed = new Set(); + for (const entry of ranked) { + const head = parentOf(entry.item) ?? entry.item.value; + if (placed.has(head)) continue; + placed.add(head); + nested.push(rankedByValue.get(head) ?? { item: itemByValue.get(head)!, match: undefined }); + nested.push(...(childrenOf.get(head) ?? [])); + } + return nested; +} + /** * Equal match classes put commands before threads, so "new" runs "New thread". * Server message matches stay in a final group so late results cannot move earlier rows. @@ -650,16 +686,18 @@ export function filterCommandPaletteGroups(input: { ? PALETTE_THREAD_LIMIT : group.value === "nested-search" || (searchesEverything && threadsMatch) ? PALETTE_SECONDARY_LIMIT - : ranked.length; + : Number.POSITIVE_INFINITY; // Hints are built only for the rows shown. - const items = ranked - .toSorted( + const items = nestUnderParents( + ranked.toSorted( (left, right) => Number(left.item.secondary ?? false) - Number(right.item.secondary ?? false), - ) + ), + group.items, + ) .slice(0, limit) .map(({ item, match }) => { - if (match.ranges.length > 0) return item; + if (match === undefined || match.ranges.length > 0) return item; // Built only for the rows shown. const matchHint = match.explain?.(); return matchHint ? { ...item, matchHint } : item; diff --git a/apps/web/src/components/CommandPalette.tsx b/apps/web/src/components/CommandPalette.tsx index cd32eeb4a6468..b3447e68e0eff 100644 --- a/apps/web/src/components/CommandPalette.tsx +++ b/apps/web/src/components/CommandPalette.tsx @@ -79,6 +79,8 @@ import { PlugIcon, SquarePenIcon, TextSearchIcon, + UmbrellaIcon, + UmbrellaOffIcon, UserPlusIcon, } from "lucide-react"; import { openThreadFind } from "./chat/threadFindStore"; @@ -276,6 +278,9 @@ import { ComposerHandleContext, useComposerHandleContext } from "../composerHand import type { ChatComposerHandle } from "./chat/ChatComposer"; import { pickableProjectGroups } from "@t3tools/client-runtime/state/project-grouping"; import { buildSidebarProjectPickerEntries } from "../sidebarProjectGrouping"; +import { umbrellaMemberLabel } from "@t3tools/client-runtime/state/umbrella"; +import { umbrellaMembershipActions } from "../umbrellaMembership.logic"; +import { useUmbrellaMembershipEdits } from "../hooks/useUmbrellaMembershipEdits"; import { PullRequestGlyph } from "~/components/pullRequest/pullRequestIcons"; import { readPullRequestListPreferences } from "~/components/pullRequest/pullRequestListPreferences"; import { useThreadRouteTarget } from "../hooks/useThreadRouteTarget"; @@ -576,6 +581,7 @@ function OpenCommandPaletteDialog(props: { ]), ); const { canPinProjectGroup, toggleProjectGroupPin } = useProjectPin(); + const umbrellaEdits = useUmbrellaMembershipEdits(); // A row's target record can change when another machine's copy loads, so the kept // order follows the project group instead. const rowOrderKey = (prefix: string) => (item: CommandPaletteActionItem) => @@ -803,8 +809,15 @@ function OpenCommandPaletteDialog(props: { [browseNavigation], ); - const openProjectFromSearch = async (project: (typeof projects)[number]) => { - const group = projectGroupByTargetKey.get(`${project.environmentId}:${project.id}`); + // A member row opens its own project, not the umbrella group it folds into. + const openProjectFromSearch = async ( + project: (typeof projects)[number], + options?: { readonly wholeGroup: boolean }, + ) => { + const group = + options?.wholeGroup === false + ? undefined + : projectGroupByTargetKey.get(`${project.environmentId}:${project.id}`); const groupedProjectKeys = group ? new Set( group.memberProjectRefs.map( @@ -849,6 +862,7 @@ function OpenCommandPaletteDialog(props: { projectGroupByTargetKey, locationByEnvironmentId: projectEnvironmentLocationById, runProject: openProjectFromSearch, + openMemberProject: (project) => openProjectFromSearch(project, { wholeGroup: false }), pin: projectPin, }), rowOrderKey("project"), @@ -1746,6 +1760,37 @@ function OpenCommandPaletteDialog(props: { run: async () => toggleProjectGroupPin(currentProjectGroup), }); } + const contextualProject = contextualProjectRef + ? projectByKey.get(`${contextualProjectRef.environmentId}:${contextualProjectRef.projectId}`) + : undefined; + const umbrellaActions = umbrellaMembershipActions( + contextualProject ? [contextualProject] : [], + projects, + clientSettings, + ); + for (const { umbrella, path } of umbrellaActions.adoptions) { + actionItems.push({ + kind: "action", + value: `action:umbrella-adopt:${umbrella.environmentId}:${umbrella.id}`, + searchTerms: ["umbrella", "add", "join", "member", "project", umbrella.title], + title: "Add project to umbrella", + description: umbrella.title, + icon: , + run: async () => umbrellaEdits.adopt(umbrella, path), + }); + } + for (const removal of umbrellaActions.removals) { + const { umbrella, member } = removal; + actionItems.push({ + kind: "action", + value: `action:umbrella-remove:${umbrella.environmentId}:${umbrella.id}`, + searchTerms: ["umbrella", "remove", "leave", "member", "project", umbrella.title], + title: `Remove ${umbrellaMemberLabel(member)} from umbrella`, + description: umbrella.title, + icon: , + run: async () => umbrellaEdits.leave(removal), + }); + } const contextualProjectGroup = currentProjectGroup ?? projectGroups[0] ?? null; if (contextualProjectGroup) { actionItems.push({ diff --git a/apps/web/src/components/CommandPaletteProjectItems.tsx b/apps/web/src/components/CommandPaletteProjectItems.tsx index 3039ac9e6f261..a56f813399c14 100644 --- a/apps/web/src/components/CommandPaletteProjectItems.tsx +++ b/apps/web/src/components/CommandPaletteProjectItems.tsx @@ -1,10 +1,13 @@ import type { EnvironmentId, EnvironmentMachineKind } from "@t3tools/contracts"; +import { isUmbrellaProject } from "@t3tools/client-runtime/state/project-grouping"; +import { umbrellaMemberLabel } from "@t3tools/client-runtime/state/umbrella"; import type { SidebarProjectSnapshot } from "../sidebarProjectGrouping"; import type { Project } from "../types"; import { buildCommandPaletteProjectMetadata, buildProjectActionItems, + type CommandPaletteActionItem, type CommandPaletteItemPin, type CommandPaletteProject, ITEM_ICON_CLASS, @@ -37,13 +40,20 @@ function projectFaviconIcon(project: Project) { return ; } -/** Projects as root search results; a grouped project matches on every member. */ -export function buildProjectSearchItems(input: ProjectItemsInput) { +/** + * Projects as root search results; a grouped project matches on every member. An umbrella is one + * line with its members' rows indented under it, and both match by name only. + */ +export function buildProjectSearchItems( + input: ProjectItemsInput & { + readonly openMemberProject: (project: CommandPaletteProject) => Promise; + }, +) { const membersOf = (project: CommandPaletteProject) => input.projectGroupByTargetKey.get(`${project.environmentId}:${project.id}`)?.memberProjects ?? [ project, ]; - return buildProjectActionItems({ + const items = buildProjectActionItems({ projects: input.projects, valuePrefix: "project", searchTerms: (project) => @@ -70,6 +80,55 @@ export function buildProjectSearchItems(input: ProjectItemsInput) { runProject: input.runProject, ...(input.pin ? { pin: input.pin } : {}), }); + return items.flatMap((item, index): CommandPaletteActionItem[] => { + const target = input.projects[index]!; + const group = input.projectGroupByTargetKey.get(`${target.environmentId}:${target.id}`); + const umbrellas = group?.memberProjects.filter(isUmbrellaProject) ?? []; + const umbrella = + umbrellas.find((project) => project.environmentId === target.environmentId) ?? umbrellas[0]; + if (group === undefined || umbrella === undefined) return [item]; + const projectByMemberPath = new Map( + group.memberProjects.flatMap((project) => { + const member = group.foldedUmbrellaMembers.get(`${project.environmentId}:${project.id}`); + return member ? [[member.path, project] as const] : []; + }), + ); + const { description: _description, ...umbrellaRow } = item; + return [ + { + ...umbrellaRow, + searchTerms: [group.displayName, umbrella.title], + icon: projectFaviconIcon(umbrella), + }, + ...(umbrella.umbrellaMembers ?? []).map((member) => { + const label = umbrellaMemberLabel(member); + const project = projectByMemberPath.get(member.path); + return { + kind: "action" as const, + value: `project-member:${umbrella.environmentId}:${umbrella.id}:${member.path}`, + parentValue: item.value, + searchTerms: project ? [label, project.title] : [label], + title: label, + icon: ( + + ), + // A checkout with no project of its own opens in the umbrella. + run: project + ? () => input.openMemberProject({ ...project, displayName: project.title }) + : item.run, + }; + }), + ]; + }); } /** Projects as targets of the "New thread in..." submenu. */ diff --git a/apps/web/src/components/CommandPaletteResults.tsx b/apps/web/src/components/CommandPaletteResults.tsx index 8c52ad294fb42..eccf36423da21 100644 --- a/apps/web/src/components/CommandPaletteResults.tsx +++ b/apps/web/src/components/CommandPaletteResults.tsx @@ -270,6 +270,8 @@ function CommandPaletteResultRow(props: { props.onExecuteItem(props.item); }} > + {/* With the row's gap, 12px: the sidebar's indent for an umbrella's threads. */} + {props.item.parentValue === undefined ? null : } {props.item.icon} {props.item.description || props.item.threadContentMatch ? ( diff --git a/apps/web/src/components/DiffPanel.browser.test.tsx b/apps/web/src/components/DiffPanel.browser.test.tsx index e10bd823889cc..34500b29d866c 100644 --- a/apps/web/src/components/DiffPanel.browser.test.tsx +++ b/apps/web/src/components/DiffPanel.browser.test.tsx @@ -58,13 +58,20 @@ vi.mock("~/state/review", () => ({ diffFileContents: {}, }, })); -vi.mock("~/state/vcs", () => ({ - vcsEnvironment: { - status: () => state.status, - listRefs: ({ input }: { input: { refKind: "local" | "remote" } }) => - input.refKind === "local" ? state.localRefs : state.remoteRefs, - }, -})); +vi.mock("~/state/vcs", async () => { + const { Atom: MockAtom } = await import("effect/reactivity"); + const noStatuses = MockAtom.make((): ReadonlyArray => []); + return { + vcsEnvironment: { + status: () => state.status, + listRefs: ({ input }: { input: { refKind: "local" | "remote" } }) => + input.refKind === "local" ? state.localRefs : state.remoteRefs, + }, + NO_UMBRELLA_MEMBER_STATUSES_ATOM: noStatuses, + umbrellaMemberStatusesAtom: () => noStatuses, + umbrellaMemberStatusesKey: () => "", + }; +}); vi.mock("~/state/entities", () => ({ useQuietThreadShell: () => state.thread, useProject: () => state.project, @@ -75,6 +82,9 @@ vi.mock("~/state/filesystem", () => ({ useFilesystemReadAccess: () => ({ canReadFiles: true, isPending: false, error: null }), })); vi.mock("~/hooks/useThreadRouteTarget", () => ({ useThreadRouteRef: () => state.threadRef })); +vi.mock("~/hooks/useUmbrellaMembershipEdits", () => ({ + useUmbrellaMembershipEdits: () => ({ confirmEnable: async () => {} }), +})); vi.mock("~/hooks/useSettings", () => ({ useClientSettings: (select: (settings: ClientSettings) => unknown) => select({ ...DEFAULT_CLIENT_SETTINGS, diffFilesCollapsed: state.diffFilesCollapsed }), @@ -101,6 +111,7 @@ vi.mock("~/browser/useOpenLink", () => ({ useOpenLink: () => async () => {} })); vi.mock("./diffs/DiffCommentAnnotation", () => ({ DiffCommentAnnotation: () => null })); vi.mock("./diffs/DiffFileTree", () => ({ DiffFileTree: () => null })); vi.mock("./DiffFilePathCopyButton", () => ({ DiffFilePathCopyButton: () => null })); +vi.mock("./ProjectFavicon", () => ({ ProjectFavicon: () => null })); import DiffPanel from "./DiffPanel"; import { useDiffPanelSessionStore, useDiffPanelStore } from "~/diffPanelStore"; diff --git a/apps/web/src/components/DiffPanel.tsx b/apps/web/src/components/DiffPanel.tsx index 38e3151eb7978..c2ca1508276b6 100644 --- a/apps/web/src/components/DiffPanel.tsx +++ b/apps/web/src/components/DiffPanel.tsx @@ -11,7 +11,13 @@ import { type ReviewBranchCommitsResult, type ScopedThreadRef, type RunId, + type UmbrellaMember, } from "@t3tools/contracts"; +import { scopedThreadKey } from "@t3tools/client-runtime/environment"; +import { + umbrellaMemberLabel, + umbrellaMembersForThread, +} from "@t3tools/client-runtime/state/umbrella"; import { ArrowRightIcon, CheckIcon, @@ -25,6 +31,7 @@ import { ChevronRightIcon, ChevronsDownUpIcon, ChevronsUpDownIcon, + UmbrellaIcon, } from "lucide-react"; import * as Schema from "effect/Schema"; import { type MouseEvent, useEffect, useRef, useState } from "react"; @@ -39,6 +46,7 @@ import { toolCallDiff } from "../lib/toolCallDiff"; import { useCheckpointDiff, useTurnItemDetail } from "~/state/queries"; import { revisionedQuery } from "~/state/revisionedQuery"; import { cn } from "~/lib/utils"; +import { ProjectFavicon } from "./ProjectFavicon"; import { resolveToolCallDiffTarget, selectThreadBranchBaseRef, @@ -105,7 +113,14 @@ import { useEnvironmentQuery } from "../state/query"; import { useAtomCommand } from "../state/use-atom-command"; import { serverEnvironment } from "../state/server"; import { reviewEnvironment } from "../state/review"; -import { vcsEnvironment } from "../state/vcs"; +import { + NO_UMBRELLA_MEMBER_STATUSES_ATOM, + umbrellaMemberStatusesAtom, + umbrellaMemberStatusesKey, + vcsEnvironment, +} from "../state/vcs"; +import { umbrellaDiffSections } from "./diffs/umbrellaDiffSections.logic"; +import { useUmbrellaMembershipEdits } from "../hooks/useUmbrellaMembershipEdits"; import { buildBaseRefChoices, filterBaseRefChoices } from "../lib/baseRefChoices"; import { createGitDiffFileContentsLoader } from "../lib/diffFileContents"; @@ -122,6 +137,7 @@ const AUTOMATIC_BASE_REF = "__automatic_base_ref__"; const DIFF_FILE_TREE_STORAGE_KEY = "t3code.diffFileTreeOpen"; const EMPTY_COLLAPSED_DIFF_FILE_KEYS: ReadonlySet = new Set(); +const NO_UMBRELLA_MEMBERS: ReadonlyArray = []; function DiffFileCollapseToggle({ filePath, @@ -252,7 +268,7 @@ export default function DiffPanel({ } : null, ); - const activeCwd = activeThread?.worktreePath ?? activeProject?.workspaceRoot; + const rootCwd = activeThread?.worktreePath ?? activeProject?.workspaceRoot; const serverConfig = useAtomValue( serverEnvironment.configValueAtom(activeThread?.environmentId ?? null), ); @@ -262,20 +278,82 @@ export default function DiffPanel({ serverConfig?.availableEditors ?? [], ); const getDiffFileContents = useAtomCommand(reviewEnvironment.diffFileContents); - const gitStatusQuery = useEnvironmentQuery( - activeThread !== null && activeThread !== undefined && activeCwd != null + const rootStatusQuery = useEnvironmentQuery( + activeThread !== null && activeThread !== undefined && rootCwd != null ? vcsEnvironment.status({ environmentId: activeThread.environmentId, - input: { cwd: activeCwd }, + input: { cwd: rootCwd }, }) : null, ); - const activeRepositoryRoot = - gitStatusQuery.data?.workingTree.rootPath ?? - (activeThread?.worktreePath ? undefined : activeProject?.repositoryIdentity?.rootPath); const diffSelection = useDiffPanelStore((state) => selectThreadDiffPanelSelection(state.byThreadKey, routeThreadRef), ); + const isGitSelection = + diffSelection.kind === "branch" || + diffSelection.kind === "unstaged" || + diffSelection.kind === "commit"; + // A worktree-mode thread works in each member's worktree inside its own folder. + const umbrellaMembers = activeThread + ? umbrellaMembersForThread( + activeProject?.umbrellaMembers ?? NO_UMBRELLA_MEMBERS, + activeThread.worktreePath, + ) + : NO_UMBRELLA_MEMBERS; + // Repositories found under a project that is not an umbrella yet wait for the user to confirm. + const umbrellaSuggestions = + activeThread && !activeThread.worktreePath && umbrellaMembers.length === 0 + ? (activeProject?.umbrellaSuggestions ?? NO_UMBRELLA_MEMBERS) + : NO_UMBRELLA_MEMBERS; + const umbrellaSuggestionNames = umbrellaSuggestions.map(umbrellaMemberLabel).join(", "); + const umbrellaEdits = useUmbrellaMembershipEdits(); + const umbrellaMemberStatuses = useAtomValue( + visible && activeThread && umbrellaMembers.length > 0 + ? umbrellaMemberStatusesAtom( + umbrellaMemberStatusesKey( + activeThread.environmentId, + umbrellaMembers.map((member) => member.path), + ), + ) + : NO_UMBRELLA_MEMBER_STATUSES_ATOM, + ); + const routeThreadKey = routeThreadRef ? scopedThreadKey(routeThreadRef) : null; + const [umbrellaPick, setUmbrellaPick] = useState<{ + readonly threadKey: string; + readonly memberPath: string | null; + } | null>(null); + const umbrella = + umbrellaMembers.length > 0 && rootCwd + ? umbrellaDiffSections({ + rootCwd, + rootLabel: activeProject?.title ?? "Project", + rootIsRepo: rootStatusQuery.data?.isRepo ?? true, + members: umbrellaMembers, + statuses: umbrellaMemberStatuses, + selectedMemberPath: + umbrellaPick !== null && umbrellaPick.threadKey === routeThreadKey + ? umbrellaPick.memberPath + : null, + }) + : null; + const umbrellaSection = isGitSelection ? (umbrella?.selected ?? null) : null; + const umbrellaSectionIndex = + umbrellaSection?.memberPath != null + ? umbrellaMembers.findIndex((member) => member.path === umbrellaSection.memberPath) + : -1; + const umbrellaSectionMember = umbrellaMembers[umbrellaSectionIndex] ?? null; + const activeCwd = umbrellaSection?.cwd ?? rootCwd; + const activeGitStatus = umbrellaSectionMember + ? (umbrellaMemberStatuses[umbrellaSectionIndex] ?? null) + : rootStatusQuery.data; + const activeRepositoryIdentity = umbrellaSectionMember + ? umbrellaSectionMember.repositoryIdentity + : activeProject?.repositoryIdentity; + const activeRepositoryRoot = + activeGitStatus?.workingTree.rootPath ?? + (activeThread?.worktreePath || umbrellaSectionMember + ? undefined + : activeProject?.repositoryIdentity?.rootPath); const rememberedBaseRef = useDiffPanelStore((state) => selectThreadBranchBaseRef(state, routeThreadRef), ); @@ -283,10 +361,6 @@ export default function DiffPanel({ // Turn and git diffs name files from the repository root; a tool call's diff names them as // its provider recorded them, absolute or relative to the workspace. const diffPathRepositoryRoot = toolCallSelection ? undefined : activeRepositoryRoot; - const isGitSelection = - diffSelection.kind === "branch" || - diffSelection.kind === "unstaged" || - diffSelection.kind === "commit"; const toolCallItems = useQuietThreadVisibleTurnItems(toolCallSelection ? routeThreadRef : null); const toolCallDetail = useTurnItemDetail( toolCallSelection && routeThreadRef @@ -297,7 +371,10 @@ export default function DiffPanel({ : null, ); const toolCallItem = toolCallDetail.data?.item; - const isGitRepo = gitStatusQuery.data?.isRepo ?? true; + // An umbrella checkpoints its members even when its root is not a repository. + const isGitRepo = umbrellaSectionMember + ? (activeGitStatus?.isRepo ?? true) + : (rootStatusQuery.data?.isRepo ?? true) || (!isGitSelection && umbrellaMembers.length > 0); const turnDiffSummaries = useThreadCheckpointSummaries(routeThreadRef); const orderedTurnDiffSummaries = turnDiffSummaries.toSorted((left, right) => { if (left.checkpointTurnCount !== right.checkpointTurnCount) { @@ -341,9 +418,9 @@ export default function DiffPanel({ ? `tool-call:${toolCallSelection.threadId}:${toolCallSelection.itemId}` : selectedTurn ? `turn:${selectedTurn.runId}` - : selectedCommitSha !== null - ? `commit:${selectedCommitSha}` - : selectedGitScope; + : `${selectedCommitSha !== null ? `commit:${selectedCommitSha}` : selectedGitScope}${ + umbrellaSectionMember ? `:${umbrellaSectionMember.path}` : "" + }`; const collapseScopeKey = routeThreadRef ? `${routeThreadRef.environmentId}:${routeThreadRef.threadId}:${reviewSectionId}` : null; @@ -424,7 +501,7 @@ export default function DiffPanel({ ? "commit" : "branch-range"), ); - const comparisonHeadRef = selectedGitSource?.headRef ?? gitStatusQuery.data?.refName ?? "HEAD"; + const comparisonHeadRef = selectedGitSource?.headRef ?? activeGitStatus?.refName ?? "HEAD"; const comparisonBaseRef = selectedGitSource?.baseRef ?? selectedBaseRef ?? "Automatic"; const selectedCommitSubject = selectedCommitSha !== null && selectedGitSource?.headRef === selectedCommitSha @@ -449,12 +526,12 @@ export default function DiffPanel({ ? "Tool call" : selectedTurn ? `Turn ${selectedCheckpointTurnCount ?? "?"}` - : selectedGitScopeLabel; + : umbrellaSectionMember && umbrellaSection + ? `${selectedGitScopeLabel} · ${umbrellaSection.label}` + : selectedGitScopeLabel; const headerCommitSha = selectedRunId === null ? selectedCommitSha : null; const selectedCommitUrl = - headerCommitSha !== null - ? projectCommitUrl(activeProject?.repositoryIdentity, headerCommitSha) - : null; + headerCommitSha !== null ? projectCommitUrl(activeRepositoryIdentity, headerCommitSha) : null; const openLink = useOpenLink(routeThreadRef); // A SHA link goes to the code host; it must not route back into this pane's commit selection. const openCommitUrl = (event: MouseEvent, url: string) => { @@ -807,6 +884,12 @@ export default function DiffPanel({ if (!routeThreadRef) return; useDiffPanelStore.getState().selectBranchBaseRef(routeThreadRef, baseRef); }; + // A base ref or commit belongs to one repository, so another section starts from its default. + const selectUmbrellaSection = (memberPath: string | null) => { + if (!routeThreadKey || memberPath === (umbrellaSection?.memberPath ?? null)) return; + setUmbrellaPick({ threadKey: routeThreadKey, memberPath }); + if (selectedGitScope !== "unstaged") selectBranchBaseRef(null); + }; const selectedTurnValue = selectedTurn ? `turn:${selectedTurn.runId}` : ""; const selectedCommitValue = selectedCommitSha !== null ? `commit:${selectedCommitSha}` : ""; const selectedScopeValue = toolCallSelection @@ -921,10 +1004,7 @@ export default function DiffPanel({ onValueChange={selectScopeValue} > {branchCommits?.commits.map((commit) => { - const commitUrl = projectCommitUrl( - activeProject?.repositoryIdentity, - commit.sha, - ); + const commitUrl = projectCommitUrl(activeRepositoryIdentity, commit.sha); return (

+ {activeProject && umbrellaSuggestions.length > 0 ? ( +
+ + + {umbrellaSuggestions.length === 1 + ? `Found a repository in this folder: ${umbrellaSuggestionNames}.` + : `Found ${umbrellaSuggestions.length} repositories in this folder: ${umbrellaSuggestionNames}.`} + + +
+ ) : null} {!activeThread ? (
Select a thread to inspect turn diffs.
) : !isGitRepo && !toolCallSelection ? (
- Turn diffs are unavailable because this project is not a git repository. + {umbrellaSuggestions.length > 0 + ? "This folder is not a git repository. Use it as an umbrella to see each of its repositories' changes here." + : "Turn diffs are unavailable because this project is not a git repository."}
) : selectedRunId !== null && orderedTurnDiffSummaries.length === 0 ? (
@@ -1321,6 +1421,48 @@ export default function DiffPanel({ ) : ( <>
+ {umbrella && + isGitSelection && + (umbrella.sections.length > 1 || umbrella.sections[0]?.memberPath != null) ? ( +
+ {umbrella.sections.map((section) => { + const selected = section.memberPath === (umbrellaSection?.memberPath ?? null); + return ( + + ); + })} +
+ ) : null} {preview?.incomplete && (

{selectedPatchError diff --git a/apps/web/src/components/Sidebar.logic.test.ts b/apps/web/src/components/Sidebar.logic.test.ts index 2fa0d608b1f1d..4e0dd1f8d31f8 100644 --- a/apps/web/src/components/Sidebar.logic.test.ts +++ b/apps/web/src/components/Sidebar.logic.test.ts @@ -15,6 +15,7 @@ import { pinOrderKeyBetween, resolveSidebarSweepKeys, resolveSidebarRowStatus, + sidebarRowShowsStatus, resolveSidebarThreadStatus, resolveThreadStatusPill, resolveWindowTitleThreadStatus, @@ -33,6 +34,7 @@ import { type SidebarListMarker, type SidebarSection, resolveSidebarDropVerb, + gatherUmbrellaThreads, groupSidebarThreadsByProject, resolveSidebarFolderDot, sidebarFolderExpansionKeys, @@ -330,6 +332,29 @@ describe("resolveSidebarRowStatus", () => { expect(resolveThreadStatusPill({ thread: stopped })).toBeNull(); } }); + + it("says whether a row shows a status, Done and Woke included", () => { + const visited = { + ...failed, + runtime: null, + latestRun: makeLatestRun(), + settledOverride: null, + lastVisitedAt: "2026-03-09T10:06:00.000Z", + }; + expect(sidebarRowShowsStatus(visited, null)).toBe(false); + // Done: the run completed after the last visit. + expect( + sidebarRowShowsStatus({ ...visited, lastVisitedAt: "2026-03-09T10:01:00.000Z" }, null), + ).toBe(true); + expect( + sidebarRowShowsStatus({ ...visited, runtime: failedRuntime, latestRun: null }, null), + ).toBe(true); + expect(sidebarRowShowsStatus(visited, "2026-03-09T10:07:00.000Z")).toBe(true); + expect(sidebarRowShowsStatus(visited, "2026-03-09T10:05:00.000Z")).toBe(false); + expect( + sidebarRowShowsStatus({ ...visited, settledOverride: "settled" }, "2026-03-09T10:07:00.000Z"), + ).toBe(false); + }); }); describe("searchSidebarThreads", () => { @@ -1636,6 +1661,78 @@ describe("groupSidebarThreadsByProject", () => { }); }); +describe("gatherUmbrellaThreads", () => { + const northwind = ProjectId.make("northwind"); + const api = ProjectId.make("api"); + const acme = ProjectId.make("acme"); + const umbrellas = [ + { + projectKey: "northwind", + memberProjectRefs: [ + { environmentId: localEnvironmentId, projectId: northwind }, + { environmentId: localEnvironmentId, projectId: api }, + ], + }, + { + projectKey: "acme", + memberProjectRefs: [{ environmentId: localEnvironmentId, projectId: acme }], + }, + ]; + const thread = (id: string, projectId: ProjectId) => ({ + id, + environmentId: localEnvironmentId, + projectId, + }); + const summarize = ( + threads: ReadonlyArray>, + flagged: ReadonlySet = new Set(), + ) => + gatherUmbrellaThreads(umbrellas, threads, (entry) => !flagged.has(entry.id)).map((run) => ({ + umbrella: run.umbrella?.projectKey ?? null, + threads: run.threads.map((entry) => entry.id), + })); + + it("gathers each umbrella's own and member threads where its first thread is", () => { + expect( + summarize([ + thread("other-1", ProjectId.make("fleet")), + thread("api-1", api), + thread("other-2", ProjectId.make("fleet")), + thread("acme-1", acme), + thread("northwind-1", northwind), + thread("other-3", ProjectId.make("notes")), + thread("api-2", api), + ]), + ).toEqual([ + { umbrella: null, threads: ["other-1"] }, + { umbrella: "northwind", threads: ["api-1", "northwind-1", "api-2"] }, + { umbrella: null, threads: ["other-2"] }, + { umbrella: "acme", threads: ["acme-1"] }, + { umbrella: null, threads: ["other-3"] }, + ]); + }); + + it("puts threads showing a status first, ahead of every umbrella", () => { + expect( + summarize( + [ + thread("api-done", api), + thread("other-1", ProjectId.make("fleet")), + thread("api-1", api), + thread("northwind-working", northwind), + thread("northwind-1", northwind), + ], + new Set(["api-done", "northwind-working"]), + ), + ).toEqual([ + { umbrella: null, threads: ["api-done"] }, + { umbrella: null, threads: ["northwind-working"] }, + { umbrella: null, threads: ["other-1"] }, + { umbrella: "northwind", threads: ["api-1", "northwind-1"] }, + ]); + }); +}); + describe("resolveSidebarFolderDot", () => { it("flags the most urgent hidden thread and stays quiet otherwise", () => { const idle = { diff --git a/apps/web/src/components/Sidebar.logic.ts b/apps/web/src/components/Sidebar.logic.ts index 351505c4c666c..f17dda1158dc9 100644 --- a/apps/web/src/components/Sidebar.logic.ts +++ b/apps/web/src/components/Sidebar.logic.ts @@ -38,6 +38,7 @@ import { type ThreadSortInput, } from "@t3tools/client-runtime/state/thread-sort"; import type { SidebarThreadSummary, Thread } from "../types"; +import { parseTimestampDate } from "../timestampFormat"; import { normalizeSearchText } from "../lib/utils"; import { isLatestRunSettled } from "../session-logic"; import { THREAD_STATUS_TEXT } from "@t3tools/client-runtime/state/thread-activity-announcement"; @@ -970,6 +971,36 @@ export function resolveSidebarRowStatus( return hasUnseenRunFailure(thread) ? status : "ready"; } +/** Woke shows from the wake until the user visits, unless the thread was settled since. */ +export function isSidebarThreadWoke( + thread: Pick & { + readonly lastVisitedAt?: string | null | undefined; + }, + wokeAt: string | null, +): boolean { + const wokeAtDate = wokeAt === null ? null : parseTimestampDate(wokeAt); + const visitedDate = thread.lastVisitedAt ? parseTimestampDate(thread.lastVisitedAt) : null; + return ( + wokeAtDate !== null && + (visitedDate === null || visitedDate < wokeAtDate) && + thread.settledOverride !== "settled" + ); +} + +/** Whether a row shows a status such as Working, Waiting, Input, Done or Woke. */ +export function sidebarRowShowsStatus( + thread: ThreadStatusInput & + SidebarThreadStatusInput & + Pick, + wokeAt: string | null, +): boolean { + return ( + resolveSidebarRowStatus(thread) !== "ready" || + hasUnseenCompletion(thread) || + isSidebarThreadWoke(thread, wokeAt) + ); +} + /** What the window title says the open thread is doing, in the words its announcer uses. */ export function resolveWindowTitleThreadStatus(thread: SidebarThreadStatusInput): string | null { // A guest waiting doesn't hide that the agent is still working. @@ -1065,6 +1096,55 @@ export function groupSidebarThreadsByProject< return folders.filter((folder) => folder.threads.length > 0 || keepEmpty(folder.group)); } +/** + * The default sidebar's rows in runs: each umbrella's threads, its own and its members', gather + * at the place of its first thread, and every other thread is a run of one with no umbrella. + * Threads `gathers` rejects, the ones showing a status, lead in their own order as runs of one. + */ +export function gatherUmbrellaThreads< + TGroup extends { + readonly memberProjectRefs: ReadonlyArray<{ + readonly environmentId: EnvironmentId; + readonly projectId: string; + }>; + }, + TThread extends Pick, +>( + umbrellas: readonly TGroup[], + threads: readonly TThread[], + gathers: (thread: TThread) => boolean, +): Array<{ readonly umbrella: TGroup | null; readonly threads: TThread[] }> { + const umbrellaByProject = new Map(); + for (const umbrella of umbrellas) { + for (const ref of umbrella.memberProjectRefs) { + umbrellaByProject.set(`${ref.environmentId}:${ref.projectId}`, umbrella); + } + } + const leading: Array<{ readonly umbrella: TGroup | null; readonly threads: TThread[] }> = []; + const runs: typeof leading = []; + const runByUmbrella = new Map(); + for (const thread of threads) { + if (!gathers(thread)) { + leading.push({ umbrella: null, threads: [thread] }); + continue; + } + const umbrella = umbrellaByProject.get(`${thread.environmentId}:${thread.projectId}`); + if (umbrella === undefined) { + runs.push({ umbrella: null, threads: [thread] }); + continue; + } + const run = runByUmbrella.get(umbrella); + if (run) { + run.threads.push(thread); + continue; + } + const created = { umbrella, threads: [thread] }; + runByUmbrella.set(umbrella, created); + runs.push(created); + } + return [...leading, ...runs]; +} + export type SidebarV2TopStatusKind = | "approval" | "done" diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index e6cdb90d5c86d..73545c384e2b5 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -107,6 +107,7 @@ import { configuredHostedAppUrl } from "../hostedPairing"; import { useSidebarPendingFileDropStore } from "../sidebarPendingFileDropStore"; import { SidebarFolderDrop } from "./sidebar/SidebarFolderDrop"; import { + isUmbrellaProject, pickableProjectGroups, selectProjectGroupingSettings, } from "@t3tools/client-runtime/state/project-grouping"; @@ -180,7 +181,10 @@ import { import { applySidebarThreadDrop, filterSidebarV2VisibleThreads, + gatherUmbrellaThreads, groupSidebarThreadsByProject, + resolveThreadLastVisitedAt, + sidebarRowShowsStatus, sidebarFolderExpansionKeys, buildBulkTitleRegenerationContextMenuItem, buildBulkUnpinContextMenuItem, @@ -269,8 +273,16 @@ import { type SidebarSweepAction, } from "./sidebar/SidebarThreadRow"; import { SidebarDraftBlock } from "./sidebar/SidebarDraftBlock"; +import { umbrellaMemberLabelsByProjectKey } from "@t3tools/client-runtime/state/umbrella"; +import { useUmbrellaMembershipEdits } from "../hooks/useUmbrellaMembershipEdits"; +import { + resolveUmbrellaMenuAction, + umbrellaMembershipActions, + umbrellaMenuItems, +} from "../umbrellaMembership.logic"; import { SidebarProjectFolderHeader, + SidebarUmbrellaHeader, sidebarFolderRowId, } from "./sidebar/SidebarProjectFolderHeader"; import { @@ -430,6 +442,8 @@ function useSidebarThreads(input: { readonly folderGroups: readonly SidebarProjectSnapshot[] | null; // Keeps folders with no active threads, so a project the user filtered to or pinned can start one. readonly keepEmptyFolders: (group: SidebarProjectSnapshot) => boolean; + // Outside boring mode, each gathers its Active threads that show no status in one place. + readonly umbrellaGroups: readonly SidebarProjectSnapshot[]; }) { const { projectScopeKey, @@ -442,6 +456,7 @@ function useSidebarThreads(input: { routeRowThreadKey, folderGroups, keepEmptyFolders: keepEmpty, + umbrellaGroups, } = input; // Folders already separate the work, so boring mode has no Working shelf. const workingShelfEnabled = @@ -470,6 +485,7 @@ function useSidebarThreads(input: { ); // Shared with the old per-project sidebar, so folders keep their open state. const projectExpandedById = useUiStateStore((store) => store.projectExpandedById); + const localLastVisitedAtById = useUiStateStore((store) => store.threadLastVisitedAtById); const setProjectExpanded = useUiStateStore((store) => store.setProjectExpanded); const [settledTail, setSettledTail] = useState({ scopeKey: projectScopeKey, @@ -493,8 +509,43 @@ function useSidebarThreads(input: { clockKey: `${nowMinute}:${snoozeWakeClock}:${inboxReturnsVersion}`, }); - const { pinnedThreads, activeThreads, workingThreads, snoozedThreads, settledThreads } = - partition; + const { pinnedThreads, workingThreads, snoozedThreads, settledThreads } = partition; + // Rows showing a status need the user, so they lead, ahead of the umbrellas. + const umbrellaRuns = + folderGroups === null && umbrellaGroups.length > 0 + ? gatherUmbrellaThreads( + umbrellaGroups, + partition.activeThreads, + (thread) => + !sidebarRowShowsStatus( + { + ...thread, + lastVisitedAt: resolveThreadLastVisitedAt( + thread.lastVisitedAt, + localLastVisitedAtById[threadShellKey(thread)], + ), + }, + threadWokeAt(thread, { now: partition.snoozeNow }), + ), + ) + : null; + const activeThreads = umbrellaRuns + ? umbrellaRuns.flatMap((run) => run.threads) + : partition.activeThreads; + const activeUmbrellaByThreadKey = new Map< + string, + { readonly group: SidebarProjectSnapshot; readonly first: boolean; readonly last: boolean } + >(); + for (const run of umbrellaRuns ?? []) { + if (run.umbrella === null) continue; + for (const [index, thread] of run.threads.entries()) { + activeUmbrellaByThreadKey.set(threadShellKey(thread), { + group: run.umbrella, + first: index === 0, + last: index === run.threads.length - 1, + }); + } + } // Older settled threads load in pages; the shelf lists them only as far as they are loaded. const olderSettledShelf = useOlderSettledShelf({ scopes: olderSettledScopes([...serverConfigs.keys()], scopedProjectKeys), @@ -568,6 +619,8 @@ function useSidebarThreads(input: { } return { ...partition, + activeThreads, + activeUmbrellaByThreadKey, threads, workingShelfEnabled, searchableThreads: [ @@ -826,6 +879,9 @@ function useSidebarLookups() { ), ), ); + const umbrellaMemberLabelByKey = umbrellaMemberLabelsByProjectKey( + projectGroups.map((group) => group.foldedUmbrellaMembers), + ); const projectGroupByScopeKey = new Map( projectGroups.map((project) => [project.projectKey, project] as const), ); @@ -844,6 +900,7 @@ function useSidebarLookups() { providerEntriesByEnvironment, projectByKey, projectDisplayNameByKey, + umbrellaMemberLabelByKey, projectGroupByScopeKey, projectScopeItems, }; @@ -911,9 +968,11 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve providerEntriesByEnvironment, projectByKey, projectDisplayNameByKey, + umbrellaMemberLabelByKey, projectGroupByScopeKey, projectScopeItems: lookupProjectScopeItems, } = useSidebarLookups(); + const umbrellaEdits = useUmbrellaMembershipEdits(); const delegatedUnderParent = useDelegatedUnderParent(); const router = useRouter(); const { isMobile, setOpenMobile } = useSidebar(); @@ -1258,6 +1317,11 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve ) => { const api = readLocalApi(); if (!api) return; + const umbrellaActions = umbrellaMembershipActions( + group.memberProjects, + projects, + projectGroupingSettings, + ); void (async () => { const clicked = await settlePromise(() => api.contextMenu.show( @@ -1271,6 +1335,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve : { id: "pin", label: "Pin project", icon: "pin" }, ] : []), + ...umbrellaMenuItems(umbrellaActions), { id: "project-settings", label: "Project settings", icon: "settings" }, ], position, @@ -1278,6 +1343,15 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve ), ); if (clicked._tag === "Failure") return; + const umbrellaAction = resolveUmbrellaMenuAction(umbrellaActions, clicked.value); + if (umbrellaAction?.kind === "adopt") { + umbrellaEdits.adopt(umbrellaAction.umbrella, umbrellaAction.path); + return; + } + if (umbrellaAction?.kind === "remove") { + umbrellaEdits.leave(umbrellaAction); + return; + } switch (clicked.value) { case "new-thread": startThreadInProjectFolder(group); @@ -1303,6 +1377,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve draggableThreadKeys, activeReorderableThreadKeys, activeThreads, + activeUmbrellaByThreadKey, workingThreads, snoozedThreads, settledThreads, @@ -1350,6 +1425,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve : null, keepEmptyFolders: (group) => scopedProjectGroups.length > 0 || (group.pinned && !group.archived), + umbrellaGroups: projectGroups.filter((group) => group.memberProjects.some(isUmbrellaProject)), }); // Ranked across environments as the palette ranks them, so one @@ -2005,6 +2081,8 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve projectFolders ?.map((folder) => `${folder.group.projectKey}:${folder.threads.length}`) .join("\n") ?? "", + // Umbrella names come and go without moving any thread row. + [...activeUmbrellaByThreadKey].flatMap(([key, { first }]) => (first ? [key] : [])).join("\n"), visibleDraftSessionCount, routeDraftIdForRows ?? "", ].join("\0"); @@ -3361,6 +3439,8 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve section: SidebarSection, // The tree row of the project folder this row sits in. folderRow?: string, + // Sits among its umbrella's threads in the Active list. + umbrella?: { group: SidebarProjectSnapshot; first: boolean; last: boolean }, ) => { const threadKey = scopedThreadKey( scopeThreadRef(thread.environmentId, thread.id), @@ -3386,6 +3466,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve } thread={thread} variant={rowVariant} + umbrella={umbrella && (umbrella.last ? "last" : "member")} navigationParent={ folderRow ?? (section === "working" || @@ -3450,6 +3531,11 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve `${thread.environmentId}:${thread.projectId}`, ) ?? null } + umbrellaMemberLabel={ + umbrellaMemberLabelByKey.get( + `${thread.environmentId}:${thread.projectId}`, + ) ?? null + } providerEntryByInstanceId={ providerEntriesByEnvironment.get(thread.environmentId) ?? EMPTY_PROVIDER_ENTRIES @@ -3491,7 +3577,27 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve if (item.kind === "thread") { // Folders draw active rows in their own place below. if (projectFolders !== null && item.section === "active") continue; - items.push(renderThreadRow(threadByKey.get(item.key)!, item.section)); + const umbrella = + item.section === "active" + ? activeUmbrellaByThreadKey.get(item.key) + : undefined; + if (umbrella?.first) { + items.push( + , + ); + } + items.push( + renderThreadRow( + threadByKey.get(item.key)!, + item.section, + undefined, + umbrella, + ), + ); continue; } if (projectFolders !== null && item.marker === "active-placeholder") { diff --git a/apps/web/src/components/chat/ChangedFilesTree.tsx b/apps/web/src/components/chat/ChangedFilesTree.tsx index 5023da3a7823f..a5735b78eb669 100644 --- a/apps/web/src/components/chat/ChangedFilesTree.tsx +++ b/apps/web/src/components/chat/ChangedFilesTree.tsx @@ -30,6 +30,13 @@ interface ChangedFileRow { type ChangedFileContextMenuHandler = (filePath: string, event: MouseEvent) => void; +/** An umbrella project the files are in, named on the row of its folder ("" for its own files). */ +interface ChangedFilesProject { + readonly folder: string; + readonly label: string; + readonly icon: ReactNode; +} + export const ChangedFilesCard = memo(function ChangedFilesCard(props: { runId: RunId; /** May be a prefix of the changed files; `totals` covers all of them. */ @@ -40,6 +47,8 @@ export const ChangedFilesCard = memo(function ChangedFilesCard(props: { onToggleAllDirectories: () => void; onOpenTurnDiff: (runId: RunId, filePath?: string) => void; onFileContextMenu?: ChangedFileContextMenuHandler | undefined; + /** The umbrella's projects the files are in, counted beside the totals. */ + projects?: ReadonlyArray | undefined; }) { const { runId, @@ -76,6 +85,11 @@ export const ChangedFilesCard = memo(function ChangedFilesCard(props: { className="text-xs leading-4" /> )} + {props.projects && props.projects.length > 0 ? ( + + in {props.projects.length === 1 ? "1 project" : `${props.projects.length} projects`} + + ) : null}

{hasDirectories && ( @@ -135,6 +149,7 @@ export const ChangedFilesCard = memo(function ChangedFilesCard(props: { resolvedTheme={resolvedTheme} onOpenTurnDiff={onOpenTurnDiff} onFileContextMenu={onFileContextMenu} + projects={props.projects} /> {hiddenFileCount > 0 && (
@@ -160,6 +175,7 @@ const ChangedFilesTree = memo(function ChangedFilesTree(props: { resolvedTheme: "light" | "dark"; onOpenTurnDiff: (runId: RunId, filePath?: string) => void; onFileContextMenu?: ChangedFileContextMenuHandler | undefined; + projects?: ReadonlyArray | undefined; }) { const { files, allDirectoriesExpanded, onOpenTurnDiff, resolvedTheme, runId, onFileContextMenu } = props; @@ -200,6 +216,12 @@ const ChangedFilesTree = memo(function ChangedFilesTree(props: { const leftPadding = 8 + depth * 14; if (node.kind === "directory") { const isExpanded = expandedDirectories[node.path] ?? allDirectoriesExpanded; + // A compacted row such as "api/src" still names the project folder it passes through. + const rowStart = node.path.slice(0, node.path.length - node.name.length); + const project = props.projects?.find( + ({ folder }) => + folder !== "" && folder.startsWith(rowStart) && `${node.path}/`.startsWith(`${folder}/`), + ); return ( + + ); +} + +/** Each project in the group that can hold checkouts, with its umbrella state and writability. */ +function useUmbrellaProjects(group: SidebarProjectSnapshot) { + const { environments } = useEnvironments(); + const pendingWrites = useAtomValue(pendingScopedWritesAtom); + const shownEnvironments = applyPendingScopedWrites(environments, pendingWrites); + const umbrellas = group.memberProjects.filter( + (project) => + !project.isScratch && + !group.foldedUmbrellaMembers.has(`${project.environmentId}:${project.id}`), + ); + const writableIds = useEnvironmentsWithScope(umbrellas, AuthSettingsWriteScope); + return umbrellas.map((project) => { + const environment = shownEnvironments.find( + (candidate) => candidate.environmentId === project.environmentId, + ); + const overrides = environment?.serverConfig?.settings.projectSettingsOverrides[project.id]; + return { + project, + environmentLabel: project.environmentLabel ?? environment?.label ?? "this environment", + enabled: overrides?.umbrellaEnabled === true, + excluded: overrides?.umbrellaExcludedPaths ?? [], + suggestions: project.umbrellaSuggestions ?? [], + disabled: + !writableIds.has(project.environmentId) || + environment?.connection.phase !== "connected" || + !environment.serverConfig, + }; + }); +} + +/** Offers the umbrella at the top of a project's settings when its folder holds checkouts. */ +export function ProjectUmbrellaPrompt({ group }: { group: SidebarProjectSnapshot }) { + const edits = useUmbrellaMembershipEdits(); + const candidate = useUmbrellaProjects(group).find( + (entry) => + !entry.enabled && + !entry.disabled && + entry.suggestions.length > 0 && + entry.project.umbrellaEnclosingRepository === undefined, + ); + if (candidate === undefined) return null; + const { project, suggestions } = candidate; + return ( + + + + {suggestions.length === 1 ? "1 project" : `${suggestions.length} projects`} detected within + this folder: {suggestions.map(umbrellaMemberLabel).join(", ")}. + + Use {group.displayName} as umbrella project? + + + + + ); +} + +/** Members, exclusions, and adoption for each project in the group that can hold checkouts. */ +export function ProjectUmbrellaSettings({ group }: { group: SidebarProjectSnapshot }) { + const edits = useUmbrellaMembershipEdits(); + const umbrellas = useUmbrellaProjects(group); + if (umbrellas.length === 0) return null; + + const rowsFor = ({ + project, + environmentLabel, + enabled, + excluded, + suggestions, + disabled, + }: (typeof umbrellas)[number]) => { + const prefix = umbrellas.length > 1 ? `${environmentLabel} · ` : ""; + if (project.umbrellaEnclosingRepository !== undefined) { + return ( + + ); + } + return ( + + 0 + ? `Found ${suggestions.length === 1 ? "1 checkout" : `${suggestions.length} checkouts`} in this folder, listed below. Turning this on lets turns checkpoint and restore them.` + : "No checkouts found in this folder. Add one below to start an umbrella." + } + control={ + { + if (checked) void edits.confirmEnable(project); + else edits.setEnabled(project, false); + }} + /> + } + /> + {!enabled + ? suggestions.map((suggestion) => ( + + )) + : null} + {project.umbrellaMembers === undefined ? ( + + ) : null} + {project.umbrellaMembers?.map((member) => { + const repository = member.repositoryIdentity + ? (repositoryGroupingDisplayNameOf(member.repositoryIdentity) ?? + member.repositoryIdentity.name) + : null; + return ( + + {`${prefix}${member.relativePath}`} + + {member.source === "nested" ? "Found in folder" : "Added"} + + + } + description={repository ?? member.path} + control={ + + } + /> + ); + })} + {excluded.map((path) => ( + edits.restore(project, path)} + > + Restore + + } + /> + ))} + edits.adopt(project, path)} + /> + } + /> + + ); + }; + + return ( + +

+ Git checkouts this project spans once it is an umbrella. Their projects' threads group under + it, and the diff panel shows each checkout's changes. +

+ {umbrellas.map(rowsFor)} +
+ ); +} diff --git a/apps/web/src/components/settings/scheduledTasksSettings.logic.test.ts b/apps/web/src/components/settings/scheduledTasksSettings.logic.test.ts index 295ce0aae0bd6..5b374996b9330 100644 --- a/apps/web/src/components/settings/scheduledTasksSettings.logic.test.ts +++ b/apps/web/src/components/settings/scheduledTasksSettings.logic.test.ts @@ -73,6 +73,8 @@ function group( environmentPresence: "mixed", allRemoteMembersAreDesktopLocal: false, allRemoteMembersAreWsl: false, + foldedUmbrellaMembers: new Map(), + foldedProjectKeys: [], remoteEnvironmentLabels: [], pinned: false, archived: false, diff --git a/apps/web/src/components/settings/scopedSettings.test.ts b/apps/web/src/components/settings/scopedSettings.test.ts index 1748f37690ebb..897ef1293cca6 100644 --- a/apps/web/src/components/settings/scopedSettings.test.ts +++ b/apps/web/src/components/settings/scopedSettings.test.ts @@ -17,6 +17,7 @@ import { applyPendingScopedWrites, createScopedSettingsWriter, persistScopedSettingsPatch, + planProjectOverrideEdit, planProjectOverridesClear, planScopedSettingsClear, planScopedSettingsPatch, @@ -95,6 +96,8 @@ const group: SidebarProjectSnapshot = { environmentPresence: "remote-only", allRemoteMembersAreDesktopLocal: false, allRemoteMembersAreWsl: false, + foldedUmbrellaMembers: new Map(), + foldedProjectKeys: [], remoteEnvironmentLabels: [server.label, laptop.label], pinned: false, archived: false, @@ -537,6 +540,39 @@ describe("scoped settings writes", () => { ).toEqual({ projectSettingsOverrides: { [projectId]: null } }); }); + it("rewrites one project's entry from its environment's copy, and only while connected", () => { + const withOverrides = environment("Server", { + settings: { + projectSettingsOverrides: { + [projectId]: { defaultAutoPull: true }, + [laptopProjectId]: { defaultAutoPull: false }, + }, + }, + }); + const edit = (current: { readonly defaultAutoPull?: boolean } | undefined) => ({ + ...current, + umbrellaAdoptedPaths: ["/work/api"], + }); + const target = { environmentId: server.environmentId, projectId }; + expect(planProjectOverrideEdit([laptop, withOverrides], target, edit).serverWrites).toEqual([ + { + environmentId: server.environmentId, + label: server.label, + previous: expect.anything(), + patch: { + projectSettingsOverrides: { + [projectId]: { defaultAutoPull: true, umbrellaAdoptedPaths: ["/work/api"] }, + }, + }, + }, + ]); + const disconnected = environment("Server", { connected: false }); + expect(planProjectOverrideEdit([disconnected], target, edit)).toMatchObject({ + serverWrites: [], + unavailableReason: "Connect Server to change this project.", + }); + }); + it("never substitutes an environment-default write for an invalid scope", () => { const scope = resolveSettingsScope({ machine: "removed" }, [group], environments); const plan = planScopedSettingsPatch(scope, environments, { enableAgentBrowserAccess: false }); diff --git a/apps/web/src/components/settings/scopedSettings.ts b/apps/web/src/components/settings/scopedSettings.ts index d0654f8902d8c..cf24ce126e225 100644 --- a/apps/web/src/components/settings/scopedSettings.ts +++ b/apps/web/src/components/settings/scopedSettings.ts @@ -486,6 +486,43 @@ export function planProjectOverridesClear( }; } +/** Rewrites one project's whole override entry from its environment's current copy. */ +export function planProjectOverrideEdit( + environments: readonly ScopedSettingsEnvironment[], + target: ProjectOverrideEntry, + edit: (current: ProjectSettingsOverrides | undefined) => ProjectSettingsOverrides, +) { + const environment = environments.find( + (candidate) => candidate.environmentId === target.environmentId, + ); + const previous = + environment?.connection.phase === "connected" ? environment.serverConfig?.settings : undefined; + const serverWrites: ScopedServerWrite[] = + environment && previous + ? [ + { + environmentId: target.environmentId, + label: environment.label, + previous, + patch: { + projectSettingsOverrides: { + [target.projectId]: edit(previous.projectSettingsOverrides[target.projectId]), + }, + }, + }, + ] + : []; + return { + clientPatch: {} as ClientSettingsPatch, + hasClientWrite: false, + serverWrites, + unavailableReason: + serverWrites.length > 0 + ? null + : `Connect ${environment?.label ?? "the project's environment"} to change this project.`, + }; +} + function writeWasDropped(value: unknown, before: unknown, saved: unknown): boolean { if (value === null) return before != null && Equal.equals(saved, before); if (isPlainObject(value) && !Array.isArray(before) && !Array.isArray(saved)) { diff --git a/apps/web/src/components/settings/settingsScope.test.ts b/apps/web/src/components/settings/settingsScope.test.ts index 60e69b7714f11..4411f4a8d8b65 100644 --- a/apps/web/src/components/settings/settingsScope.test.ts +++ b/apps/web/src/components/settings/settingsScope.test.ts @@ -53,6 +53,8 @@ function group( environmentPresence: "mixed", allRemoteMembersAreDesktopLocal: false, allRemoteMembersAreWsl: false, + foldedUmbrellaMembers: new Map(), + foldedProjectKeys: [], remoteEnvironmentLabels: [], pinned: false, archived: false, diff --git a/apps/web/src/components/settings/settingsSearch.ts b/apps/web/src/components/settings/settingsSearch.ts index 937e37dd8ec38..1c2df714449c5 100644 --- a/apps/web/src/components/settings/settingsSearch.ts +++ b/apps/web/src/components/settings/settingsSearch.ts @@ -1235,6 +1235,14 @@ export const SETTINGS_SEARCH_ITEMS = [ to: "/settings/projects", searchTerms: ["commands scripts setup run dev server checkout worktree t3.json import"], }, + { + id: "project-umbrella", + title: "Umbrella checkouts", + to: "/settings/projects", + searchTerms: [ + "umbrella repositories repos nested checkout member adopt exclude monorepo folder", + ], + }, { id: "environment-icon", title: "Environment icon", diff --git a/apps/web/src/components/settings/useScopedSettings.ts b/apps/web/src/components/settings/useScopedSettings.ts index d67e2d3124282..7c0f2781689ce 100644 --- a/apps/web/src/components/settings/useScopedSettings.ts +++ b/apps/web/src/components/settings/useScopedSettings.ts @@ -25,6 +25,7 @@ import { useOptionalSettingsScope, useSettingsScope } from "./SettingsScopeConte import { createScopedSettingsWriter, pendingScopedWritesAtom, + planProjectOverrideEdit, planProjectOverridesClear, planScopedSettingsClear, planScopedSettingsPatch, @@ -164,6 +165,17 @@ export function useClearProjectOverrides() { }; } +/** Rewrites one project's override entry; works outside a settings page. */ +export function useEditProjectOverrides() { + const run = useRunScopedPlan(); + return (target: ProjectOverrideEntry, edit: Parameters[2]) => { + const environment = readEnvironment(target.environmentId); + run(environment ? [environment] : [], (current) => + planProjectOverrideEdit(current, target, edit), + ); + }; +} + export function useScopedSettingsWriteAllowed() { const { connectedEnvironments } = useSettingsScope(); const writable = useEnvironmentsWithScope(connectedEnvironments, AuthSettingsWriteScope); diff --git a/apps/web/src/components/sidebar/SidebarProjectFolderHeader.tsx b/apps/web/src/components/sidebar/SidebarProjectFolderHeader.tsx index b438db4e6a111..f4d68a0946d69 100644 --- a/apps/web/src/components/sidebar/SidebarProjectFolderHeader.tsx +++ b/apps/web/src/components/sidebar/SidebarProjectFolderHeader.tsx @@ -1,7 +1,7 @@ import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/models"; import { scopedThreadKey, scopeThreadRef } from "@t3tools/client-runtime/environment"; import type { ContextMenuSource } from "@t3tools/contracts"; -import { ChevronDownIcon, SquarePenIcon } from "lucide-react"; +import { ChevronDownIcon, SquarePenIcon, UmbrellaIcon } from "lucide-react"; import { memo } from "react"; import { cn } from "~/lib/utils"; @@ -129,3 +129,38 @@ export const SidebarProjectFolderHeader = memo(function SidebarProjectFolderHead ); }); + +/** An umbrella's name above its threads in the default sidebar's Active list. */ +export const SidebarUmbrellaHeader = memo(function SidebarUmbrellaHeader(props: { + group: SidebarProjectSnapshot; + onContextMenu: ( + group: SidebarProjectSnapshot, + position: { x: number; y: number }, + source: ContextMenuSource, + ) => void; +}) { + const { group } = props; + return ( +
  • { + event.preventDefault(); + props.onContextMenu( + group, + { x: event.clientX, y: event.clientY }, + contextMenuSourceOf(event), + ); + }} + > + + + {group.displayName} + + +
  • + ); +}); diff --git a/apps/web/src/components/sidebar/SidebarThreadRow.tsx b/apps/web/src/components/sidebar/SidebarThreadRow.tsx index d901418db85a5..d2bde2c040e3c 100644 --- a/apps/web/src/components/sidebar/SidebarThreadRow.tsx +++ b/apps/web/src/components/sidebar/SidebarThreadRow.tsx @@ -77,7 +77,7 @@ import { useNowSecond } from "../../hooks/useNowSecond"; import { vcsEnvironment, vcsBranchRevalidation } from "../../state/vcs"; import { useEnvironmentQuery } from "../../state/query"; import { readEnvironmentScope, useEnvironmentScope } from "../../state/session"; -import { formatRelativeTimeLabel, parseTimestampDate } from "../../timestampFormat"; +import { formatRelativeTimeLabel } from "../../timestampFormat"; import type { SidebarThreadSummary } from "../../types"; import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell"; import { cn } from "~/lib/utils"; @@ -86,6 +86,7 @@ import { EnvironmentMachineIcon } from "../EnvironmentMachineIcon"; import { animateSidebarLayoutChanges, hasUnseenCompletion, + isSidebarThreadWoke, resolveSidebarRowAccessibility, type SidebarDropVerb, resolveSidebarRowStatus, @@ -552,6 +553,8 @@ type SidebarThreadRowProps = { // "folder" is a one-line row inside a boring sidebar project folder; // "folder-multiline" adds the card's branch and PR line under it. variant: "card" | "slim" | "folder" | "folder-multiline"; + // Indents the row under its umbrella's name, beside a line that ends at the umbrella's last row. + umbrella?: "member" | "last" | undefined; navigationParent?: string | undefined; variantAction: SidebarSweepAction; settlementSupported: boolean; @@ -579,6 +582,8 @@ type SidebarThreadRowProps = { scratchMachineLabel: string | null; project: EnvironmentProject | null; projectDisplayName: string | null; + // The umbrella member a folded project's thread works in. + umbrellaMemberLabel: string | null; providerEntryByInstanceId: ReadonlyMap; timestampFormat: TimestampFormat; onThreadClick: (event: ReactMouseEvent, threadRef: ScopedThreadRef) => void; @@ -739,12 +744,7 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP const isUnread = hasUnseenCompletion({ ...thread, lastVisitedAt }); const status = resolveSidebarRowStatus({ ...thread, lastVisitedAt }); - const lastVisitedDate = lastVisitedAt === undefined ? null : parseTimestampDate(lastVisitedAt); - const wokeAtDate = props.wokeAt === null ? null : parseTimestampDate(props.wokeAt); - const isWoke = - wokeAtDate !== null && - (lastVisitedDate === null || lastVisitedDate < wokeAtDate) && - thread.settledOverride !== "settled"; + const isWoke = isSidebarThreadWoke({ ...thread, lastVisitedAt }, props.wokeAt); const shouldRecede = shouldRecedeSidebarThread({ status, isUnread, @@ -1079,6 +1079,12 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP ); + const umbrellaMemberTag = props.umbrellaMemberLabel ? ( + + {props.umbrellaMemberLabel} + + ) : null; + const prBadgeShape = supportsMultiplePullRequests ? resolveThreadPullRequestBadge(thread.pullRequests) : null; @@ -1282,6 +1288,7 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP )} {draftIndicator} {title} + {umbrellaMemberTag} {multiline ? titleLineIcons : null} {pinIndicator} {multiline ? null : terminalStatusIcon} @@ -1431,9 +1438,19 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP className={cn( "list-none py-0.5 [content-visibility:auto] [contain-intrinsic-size:auto_78px]", metaLineEmpty && "[contain-intrinsic-size:auto_60px]", + props.umbrella && "relative ps-3", sortable?.isDragging && "relative z-20", )} > + {props.umbrella ? ( + + ) : null} - {props.projectDisplayName} + {props.umbrellaMemberLabel ? ( + <> + {props.umbrellaMemberLabel} + · {props.projectDisplayName} + + ) : ( + props.projectDisplayName + )} ) : ( diff --git a/apps/web/src/environmentGrouping.test.ts b/apps/web/src/environmentGrouping.test.ts index b2081b4b8fe9a..02f553ae6d77a 100644 --- a/apps/web/src/environmentGrouping.test.ts +++ b/apps/web/src/environmentGrouping.test.ts @@ -9,6 +9,7 @@ import { buildSidebarProjectPickerEntries, buildSidebarProjectSnapshots, resolveSidebarProjectScopeKey, + resolveSidebarProjectScopeKeys, getSidebarProjectSettingsKey, } from "./sidebarProjectGrouping"; import type { Project } from "./types"; @@ -125,6 +126,36 @@ describe("environment grouping", () => { expect(resolveSidebarProjectScopeKey({ groups, key, canClearMissingScope: true })).toBe(key); }); + it("moves a saved project scope into the umbrella its project folds into", () => { + const api = makeProject({ id: ProjectId.make("api"), workspaceRoot: "/clients/acme/api" }); + const acme = makeProject({ + id: ProjectId.make("acme"), + title: "acme", + workspaceRoot: "/clients/acme", + umbrellaMembers: [ + { + path: api.workspaceRoot, + relativePath: "api", + repositoryIdentity: null, + source: "nested", + }, + ], + }); + const groupsOf = (projects: Project[]) => + buildSidebarProjectSnapshots({ + projects, + settings: defaultGroupingSettings, + primaryEnvironmentId, + resolveEnvironmentLabel: () => null, + }); + const saved = groupsOf([api]).map((group) => group.projectKey); + const groups = groupsOf([acme, api]); + expect(groups).toHaveLength(1); + expect( + resolveSidebarProjectScopeKeys({ groups, keys: saved, canClearMissingScope: true }), + ).toEqual([groups[0]!.projectKey]); + }); + it("dedupes stale project rows with the same environment and workspace path", () => { const duplicate = makeProject({ id: ProjectId.make("project-duplicate"), diff --git a/apps/web/src/hooks/useUmbrellaMembershipEdits.ts b/apps/web/src/hooks/useUmbrellaMembershipEdits.ts new file mode 100644 index 0000000000000..d387282070e2a --- /dev/null +++ b/apps/web/src/hooks/useUmbrellaMembershipEdits.ts @@ -0,0 +1,78 @@ +import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell"; +import { derivePhysicalProjectKey } from "@t3tools/client-runtime/state/project-grouping"; +import { + adoptUmbrellaMember, + removeUmbrellaMember, + restoreUmbrellaMember, + umbrellaMemberLabel, +} from "@t3tools/client-runtime/state/umbrella"; +import type { ProjectSettingsOverrides, UmbrellaMember } from "@t3tools/contracts"; + +import { useEditProjectOverrides } from "../components/settings/useScopedSettings"; +import { toastManager } from "../components/ui/toast"; +import { withProjectGroupingOverride } from "../sidebarProjectGrouping"; +import { requestConfirmDialog } from "../confirmDialog"; +import { umbrellaConfirmationMessage, type UmbrellaRemoval } from "../umbrellaMembership.logic"; +import { persistClientSettingsUpdate } from "./useSettings"; + +type Umbrella = Pick; + +/** Adopt, remove, and restore umbrella members through the umbrella's own project overrides. */ +export function useUmbrellaMembershipEdits() { + const editOverrides = useEditProjectOverrides(); + const edit = ( + umbrella: Umbrella, + change: (current: ProjectSettingsOverrides | undefined) => Partial, + ) => + editOverrides({ environmentId: umbrella.environmentId, projectId: umbrella.id }, (current) => ({ + ...current, + ...change(current), + })); + const remove = (umbrella: Umbrella, member: Pick) => + edit(umbrella, (current) => removeUmbrellaMember(umbrella, current, member)); + return { + setEnabled: (umbrella: Umbrella, enabled: boolean) => + edit(umbrella, () => ({ umbrellaEnabled: enabled })), + /** Lists the checkouts that will join, then turns the umbrella on once the user confirms. */ + confirmEnable: async ( + umbrella: Umbrella & Pick, + ) => { + const confirmed = await requestConfirmDialog( + umbrellaConfirmationMessage(umbrella.title, umbrella.umbrellaSuggestions ?? []), + { initialFocus: "confirm" }, + ); + if (confirmed !== true) return; + edit(umbrella, () => ({ umbrellaEnabled: true })); + const names = (umbrella.umbrellaSuggestions ?? []).map(umbrellaMemberLabel).join(", "); + toastManager.add({ + type: "success", + title: `${umbrella.title} is now an umbrella`, + description: `Its threads checkpoint ${names}, and the diff panel shows their changes.`, + }); + }, + adopt: (umbrella: Umbrella, path: string) => + edit(umbrella, (current) => adoptUmbrellaMember(umbrella, current, path)), + remove, + restore: (umbrella: Umbrella, path: string) => + edit(umbrella, (current) => restoreUmbrellaMember(umbrella, current, path)), + /** The umbrella's own checkout leaves it; another clone only stops grouping under it. */ + leave: (removal: UmbrellaRemoval) => { + if (removal.match === "folder") return remove(removal.umbrella, removal.member); + const overrideKey = derivePhysicalProjectKey(removal.project); + void persistClientSettingsUpdate((current) => ({ + ...current, + sidebarProjectGroupingOverrides: withProjectGroupingOverride( + current.sidebarProjectGroupingOverrides, + overrideKey, + "separate", + ), + })).catch((error: unknown) => { + toastManager.add({ + type: "error", + title: "Could not ungroup the project", + description: error instanceof Error ? error.message : "An error occurred.", + }); + }); + }, + }; +} diff --git a/apps/web/src/sidebarProjectGrouping.ts b/apps/web/src/sidebarProjectGrouping.ts index 8fb8c4a5a1c6c..60c258f9231ea 100644 --- a/apps/web/src/sidebarProjectGrouping.ts +++ b/apps/web/src/sidebarProjectGrouping.ts @@ -2,6 +2,7 @@ import type { EnvironmentId, ScopedProjectRef, SidebarProjectGroupingMode, + UmbrellaMember, } from "@t3tools/contracts"; import { buildProjectGroups, @@ -44,6 +45,9 @@ export interface SidebarProjectSnapshot extends Project { allRemoteMembersAreWsl: boolean; memberProjects: readonly SidebarProjectGroupMember[]; memberProjectRefs: readonly ScopedProjectRef[]; + /** Projects folded in as umbrella members, by `environmentId:projectId`. */ + foldedUmbrellaMembers: ReadonlyMap; + foldedProjectKeys: ReadonlyArray; remoteEnvironmentLabels: readonly string[]; pinned: boolean; archived: boolean; @@ -95,16 +99,19 @@ export function resolveSidebarProjectScopeKey(input: { readonly settings?: ProjectGroupingSettings; readonly canClearMissingScope?: boolean; }): string | null { - if (input.key === null) return null; + const { key } = input; + if (key === null) return null; const group = - input.groups.find((candidate) => candidate.projectKey === input.key) ?? + input.groups.find((candidate) => candidate.projectKey === key) ?? + // A project folded into an umbrella takes the scopes saved for its own group along. + input.groups.find((candidate) => candidate.foldedProjectKeys.includes(key)) ?? input.groups.find( (candidate) => candidate.isScratch && - resolveScratchProjectScopeKey(input.key, candidate.memberProjects, input.settings) === + resolveScratchProjectScopeKey(key, candidate.memberProjects, input.settings) === candidate.projectKey, ); - return group?.projectKey ?? (input.canClearMissingScope ? null : input.key); + return group?.projectKey ?? (input.canClearMissingScope ? null : key); } export function resolveSidebarProjectScopeKeys(input: { @@ -199,6 +206,8 @@ export function buildSidebarProjectSnapshots(input: { allRemoteMembersAreWsl, memberProjects: members, memberProjectRefs: group.memberProjectRefs, + foldedUmbrellaMembers: group.umbrellaMembers, + foldedProjectKeys: group.foldedProjectKeys, remoteEnvironmentLabels, pinned: group.pinned, archived: group.archived, diff --git a/apps/web/src/state/vcs.ts b/apps/web/src/state/vcs.ts index dafacf53c27f3..be74637bbcb30 100644 --- a/apps/web/src/state/vcs.ts +++ b/apps/web/src/state/vcs.ts @@ -3,6 +3,7 @@ import { createVcsEnvironmentAtoms, createVcsStatusRevalidationAtomFamily, } from "@t3tools/client-runtime/state/vcs"; +import type { EnvironmentId, VcsStatusResult } from "@t3tools/contracts"; import * as Equal from "effect/Equal"; import { AsyncResult, Atom } from "effect/reactivity"; @@ -23,6 +24,29 @@ export const chatGitStatusAtom = Atom.family((status: ReturnType = Atom.make(null); +/** Live status of each umbrella member checkout, keyed by `umbrellaMemberStatusesKey`. */ +export const umbrellaMemberStatusesAtom = Atom.family((key: string) => { + const { environmentId, paths } = JSON.parse(key) as { + environmentId: EnvironmentId; + paths: string[]; + }; + return Atom.make((get): ReadonlyArray => + paths.map((cwd) => + AsyncResult.getOrElse( + get(vcsEnvironment.status({ environmentId, input: { cwd } })), + () => null, + ), + ), + ); +}); +export const umbrellaMemberStatusesKey = ( + environmentId: EnvironmentId, + paths: ReadonlyArray, +) => JSON.stringify({ environmentId, paths }); +export const NO_UMBRELLA_MEMBER_STATUSES_ATOM = Atom.make( + (): ReadonlyArray => [], +); + /** * Refreshes a checkout's status when the user comes back to the window, where * edits made in another app or terminal may be waiting. diff --git a/apps/web/src/umbrellaMembership.logic.test.ts b/apps/web/src/umbrellaMembership.logic.test.ts new file mode 100644 index 0000000000000..a45469bd47c7d --- /dev/null +++ b/apps/web/src/umbrellaMembership.logic.test.ts @@ -0,0 +1,127 @@ +import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell"; +import { EnvironmentId, ProjectId } from "@t3tools/contracts"; +import { describe, expect, it } from "vite-plus/test"; + +import { + resolveUmbrellaMenuAction, + umbrellaConfirmationMessage, + umbrellaMembershipActions, + umbrellaMenuItems, +} from "./umbrellaMembership.logic"; + +const desktop = EnvironmentId.make("desktop"); +const grouping = { + sidebarProjectGroupingMode: "repository" as const, + sidebarProjectGroupingOverrides: {}, +}; +const project = ( + id: string, + workspaceRoot: string, + overrides: Partial = {}, +): EnvironmentProject => ({ + environmentId: desktop, + id: ProjectId.make(id), + title: id, + workspaceRoot, + repositoryIdentity: null, + defaultModelSelection: null, + scripts: [], + createdAt: "2026-07-01T00:00:00.000Z", + updatedAt: "2026-07-01T00:00:00.000Z", + umbrellaMembers: [], + ...overrides, +}); +const member = (path: string, relativePath: string) => ({ + path, + relativePath, + repositoryIdentity: null, + source: "nested" as const, +}); + +const acme = project("acme", "/clients/acme", { + umbrellaMembers: [member("/clients/acme/api", "api"), member("/clients/acme/web", "web")], +}); +const globex = project("globex", "/clients/globex", { + umbrellaMembers: [member("/clients/globex/site", "site")], +}); +const api = project("api", "/clients/acme/api"); +const web = project("web", "/clients/acme/web"); +const tools = project("tools", "/work/tools"); +const projects = [acme, globex, api, web, tools]; + +describe("umbrellaMembershipActions", () => { + it("offers a free project every umbrella on its environment and a member only its exit", () => { + const free = umbrellaMembershipActions([tools], projects, grouping); + expect(free.adoptions.map(({ umbrella, path }) => [umbrella.id, path])).toEqual([ + ["acme", "/work/tools"], + ["globex", "/work/tools"], + ]); + expect(free.removals).toEqual([]); + + const joined = umbrellaMembershipActions([api], projects, grouping); + expect(joined.adoptions).toEqual([]); + expect(joined.removals.map(({ umbrella, member }) => [umbrella.id, member.path])).toEqual([ + ["acme", "/clients/acme/api"], + ]); + }); + + it("lists each folded project of an umbrella group once and ignores scratch projects", () => { + const scratch = project("scratch", "/tmp/scratch", { isScratch: true }); + const actions = umbrellaMembershipActions([acme, api, web, api, scratch], projects, grouping); + expect(actions.adoptions).toEqual([]); + expect(actions.removals.map(({ member }) => member.relativePath)).toEqual(["api", "web"]); + }); +}); + +describe("umbrellaMenuItems", () => { + it("maps clicked ids back to the adoption or removal they name", () => { + const actions = { + adoptions: umbrellaMembershipActions([tools], projects, grouping).adoptions, + removals: umbrellaMembershipActions([api, web], projects, grouping).removals, + }; + const items = umbrellaMenuItems(actions); + expect(items.map((item) => [item.label, item.children?.map((child) => child.label)])).toEqual([ + ["Add to umbrella", ["acme", "globex"]], + ["Remove from umbrella", ["api (acme)", "web (acme)"]], + ]); + const globexId = items[0]!.children![1]!.id; + expect(resolveUmbrellaMenuAction(actions, globexId)).toMatchObject({ + kind: "adopt", + umbrella: { id: "globex" }, + path: "/work/tools", + }); + const webId = items[1]!.children![1]!.id; + expect(resolveUmbrellaMenuAction(actions, webId)).toMatchObject({ + kind: "remove", + member: { path: "/clients/acme/web" }, + }); + expect(resolveUmbrellaMenuAction(actions, "project-settings")).toBeNull(); + }); + + it("uses a single item when one removal is possible", () => { + const actions = umbrellaMembershipActions([api], projects, grouping); + expect(umbrellaMenuItems(actions)).toEqual([ + { id: "umbrella-remove:0", label: "Remove api from umbrella", detail: "acme" }, + ]); + expect(resolveUmbrellaMenuAction(actions, "umbrella-remove:0")?.kind).toBe("remove"); + }); +}); + +describe("umbrellaConfirmationMessage", () => { + it("names every checkout the umbrella will take in", () => { + expect( + umbrellaConfirmationMessage("Acme", [ + { relativePath: "api" }, + { relativePath: "../../work/acme-site" }, + ]), + ).toBe( + [ + "Use Acme as an umbrella?", + "Acme will span these checkouts:", + "• api", + "• acme-site", + "The diff panel shows each one's changes, turns checkpoint them so reverting a turn restores them, and their projects' threads group under Acme. You can turn this off in project settings.", + ].join("\n"), + ); + }); +}); diff --git a/apps/web/src/umbrellaMembership.logic.ts b/apps/web/src/umbrellaMembership.logic.ts new file mode 100644 index 0000000000000..c0bf1b09ec084 --- /dev/null +++ b/apps/web/src/umbrellaMembership.logic.ts @@ -0,0 +1,130 @@ +import { + findUmbrellaMembership, + type ProjectGroupingSettings, +} from "@t3tools/client-runtime/state/project-grouping"; +import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell"; +import { + umbrellaAdoptionTargets, + umbrellaMemberLabel, +} from "@t3tools/client-runtime/state/umbrella"; +import type { ContextMenuItem, UmbrellaMember } from "@t3tools/contracts"; + +interface UmbrellaAdoption { + readonly umbrella: TProject; + readonly path: string; +} + +export interface UmbrellaRemoval { + readonly umbrella: TProject; + readonly member: UmbrellaMember; + readonly project: EnvironmentProject; + /** A repository match is another clone grouped under the umbrella; leaving only ungroups it. */ + readonly match: "folder" | "repository"; +} + +/** + * What the given projects can do with umbrellas: join one on their environment, or leave the + * one they belong to. A project already in an umbrella only offers to leave it. + */ +export function umbrellaMembershipActions( + subjects: ReadonlyArray, + projects: ReadonlyArray, + settings: ProjectGroupingSettings, +): { + readonly adoptions: ReadonlyArray>; + readonly removals: ReadonlyArray>; +} { + const adoptions = new Map>(); + const removals = new Map>(); + for (const project of subjects) { + if (project.isScratch) continue; + const membership = findUmbrellaMembership(project, projects, settings); + if (membership !== null) { + const { umbrella, member } = membership; + removals.set( + `${umbrella.environmentId}:${umbrella.id}\0${member.path}\0${project.environmentId}:${project.id}`, + { ...membership, project }, + ); + continue; + } + for (const umbrella of umbrellaAdoptionTargets(project, projects)) { + const key = `${umbrella.environmentId}:${umbrella.id}`; + if (!adoptions.has(key)) adoptions.set(key, { umbrella, path: project.workspaceRoot }); + } + } + return { adoptions: [...adoptions.values()], removals: [...removals.values()] }; +} + +const ADOPT_PREFIX = "umbrella-adopt:"; +const REMOVE_PREFIX = "umbrella-remove:"; + +export function umbrellaMenuItems( + actions: ReturnType, +): ContextMenuItem[] { + const items: ContextMenuItem[] = []; + if (actions.adoptions.length > 0) { + items.push({ + id: "umbrella-adopt", + label: "Add to umbrella", + children: actions.adoptions.map((adoption, index) => ({ + id: `${ADOPT_PREFIX}${index}`, + label: adoption.umbrella.title, + })), + }); + } + const [onlyRemoval] = actions.removals; + if (actions.removals.length === 1 && onlyRemoval) { + items.push({ + id: `${REMOVE_PREFIX}0`, + // Named, since the folder clicked can be the umbrella itself holding a folded member. + label: `Remove ${umbrellaMemberLabel(onlyRemoval.member)} from umbrella`, + detail: onlyRemoval.umbrella.title, + }); + } else if (actions.removals.length > 1) { + items.push({ + id: "umbrella-remove", + label: "Remove from umbrella", + children: actions.removals.map((removal, index) => ({ + id: `${REMOVE_PREFIX}${index}`, + label: `${umbrellaMemberLabel(removal.member)} (${removal.umbrella.title})`, + })), + }); + } + return items; +} + +/** The action a clicked `umbrellaMenuItems` id stands for, or null for any other id. */ +export function resolveUmbrellaMenuAction( + actions: { + readonly adoptions: ReadonlyArray>; + readonly removals: ReadonlyArray>; + }, + id: string | null, +): + | ({ readonly kind: "adopt" } & UmbrellaAdoption) + | ({ readonly kind: "remove" } & UmbrellaRemoval) + | null { + if (id === null) return null; + if (id.startsWith(ADOPT_PREFIX)) { + const adoption = actions.adoptions[Number(id.slice(ADOPT_PREFIX.length))]; + return adoption ? { kind: "adopt", ...adoption } : null; + } + if (id.startsWith(REMOVE_PREFIX)) { + const removal = actions.removals[Number(id.slice(REMOVE_PREFIX.length))]; + return removal ? { kind: "remove", ...removal } : null; + } + return null; +} + +/** The confirmation that lists every checkout an umbrella will take in, and what changes, before it is turned on. */ +export function umbrellaConfirmationMessage( + title: string, + checkouts: ReadonlyArray>, +): string { + return [ + `Use ${title} as an umbrella?`, + `${title} will span these checkouts:`, + ...checkouts.map((checkout) => `• ${umbrellaMemberLabel(checkout)}`), + `The diff panel shows each one's changes, turns checkpoint them so reverting a turn restores them, and their projects' threads group under ${title}. You can turn this off in project settings.`, + ].join("\n"); +} diff --git a/docs/user/project-settings.md b/docs/user/project-settings.md index 899640ad23590..c32ee5eec5cf6 100644 --- a/docs/user/project-settings.md +++ b/docs/user/project-settings.md @@ -64,6 +64,52 @@ back. On mobile, both are in **Settings → Projects → Organize**. A project on several machines must have every machine connected to pin or archive it. +## Umbrella projects + +Keep one project for a folder that holds several repositories, such as a client folder with an +API, a website, and copy or design files beside them. Add the folder as a project. T3 Code looks +for repositories up to three folders below it, skipping hidden folders, dependency and vendored +folders such as `node_modules`, `vendor`, and `venv`, linked worktrees, and submodules. + +Nothing changes until you confirm. When repositories are found, the diff panel and the top of +your project's page in **Settings → Projects** offer **Use as umbrella**, and **Umbrella +checkouts** on that page lists them with a **Use as umbrella** switch. Each shows every repository +that will join before you turn it on. +Adding a checkout by path in that section also turns the umbrella on. Turn the switch off to stop. +A folder inside another repository cannot be an umbrella; use that repository's root instead. + +Threads in an umbrella start in the folder and can work in any member. The diff panel has a tab +for each member with changes, turn diffs and checkpoints include edits inside members, and a +pull request open on the branch of a member a turn edited is linked to the thread; unlinking it +keeps it off. Reverting a turn restores only the members whose files differ from that turn. When +the folder is a repository itself, its status, diffs, commits, and checkpoints leave the members +out. + +Projects you already have for a member fold into the umbrella: the same folder on the umbrella's +machine, or the same repository on any connected machine. The sidebar gathers the umbrella's +active threads and its members' under the umbrella's name, indented beside a line, and a member's +thread names its member first. Threads showing a status such as Working, Input or Done come first, +ahead of every umbrella, and join their umbrella once they no longer show one. A command +palette search lists the umbrella with its matching members indented under it. Use **Add to umbrella** and **Remove _member_ from umbrella** from a project +folder's menu in the sidebar or from the command palette. For a clone on another machine, +removing it only stops grouping it there; its grouping rule in **Settings → Projects** +brings it back. To add a checkout stored elsewhere on the same machine, or to remove or restore a +member, use **Umbrella checkouts**. + +Worktree mode needs the umbrella folder to be a Git repository itself. A thread then works in its +own copy of the umbrella, so its edits stay out of your checkouts: the folder's own worktree, in +your worktree location, with a worktree of every member at the same path, all on the thread's +branch. Members added from outside the umbrella sit under `_external/` in that folder. Each +member starts from the base branch you pick when it has one, and otherwise from the branch it has +checked out. The **Start from remote** and submodule settings apply to every member. Deleting the +thread's worktree, and storage cleanup by age, settlement or deletion, removes every member's +worktree and keeps the branches. + +When the umbrella folder is not a repository, the composer offers only local mode, and a worktree +launch is refused with the member checkouts and their projects named. To work in one member in a +worktree, start the thread in that member's project. To give the whole umbrella worktrees, make +the umbrella folder a Git repository with at least one commit. + ## Worktree branch names In **Settings → Worktrees → Worktree branch naming**, choose a static prefix, diff --git a/packages/client-runtime/package.json b/packages/client-runtime/package.json index d303b27c879f9..99c2c003744f1 100644 --- a/packages/client-runtime/package.json +++ b/packages/client-runtime/package.json @@ -283,6 +283,10 @@ "types": "./src/state/projectGrouping.ts", "default": "./src/state/projectGrouping.ts" }, + "./state/umbrella": { + "types": "./src/state/umbrella.ts", + "default": "./src/state/umbrella.ts" + }, "./state/relay": { "types": "./src/state/relayDiscovery.ts", "default": "./src/state/relayDiscovery.ts" diff --git a/packages/client-runtime/src/state/projectGrouping.test.ts b/packages/client-runtime/src/state/projectGrouping.test.ts index a991e7a45cb22..70a9803d22e4e 100644 --- a/packages/client-runtime/src/state/projectGrouping.test.ts +++ b/packages/client-runtime/src/state/projectGrouping.test.ts @@ -184,6 +184,62 @@ describe("buildProjectGroups", () => { }, ); + it("folds member projects into their umbrella by folder or by repository", () => { + const remote = EnvironmentId.make("laptop"); + const apiIdentity = { ...repositoryIdentity, canonicalKey: "github.com/acme/api" }; + const siteIdentity = { ...repositoryIdentity, canonicalKey: "github.com/acme/site" }; + const umbrella = makeProject("acme", "/clients/acme", { + repositoryIdentity: null, + umbrellaMembers: [ + { + path: "/clients/acme/api", + relativePath: "api", + repositoryIdentity: apiIdentity, + source: "nested", + }, + { + path: "/work/acme-site", + relativePath: "../../work/acme-site", + repositoryIdentity: siteIdentity, + source: "adopted", + }, + ], + }); + const sameFolder = makeProject("api-here", "/clients/acme/api", { repositoryIdentity: null }); + const sameRepository = makeProject("api-laptop", "/home/me/api", { + environmentId: remote, + repositoryIdentity: apiIdentity, + }); + const separate = makeProject("site-laptop", "/home/me/site", { + environmentId: remote, + repositoryIdentity: siteIdentity, + }); + const unrelated = makeProject("other", "/clients/other", { repositoryIdentity: null }); + const groupingSettings = settings("repository", { + [derivePhysicalProjectKey(separate)]: "separate", + }); + + const groups = buildProjectGroups({ + projects: [sameFolder, umbrella, sameRepository, separate, unrelated], + settings: groupingSettings, + }); + + expect(groups.map((group) => group.label)).toEqual(["acme", "site-laptop", "other"]); + const [umbrellaGroup] = groups; + expect(umbrellaGroup!.representative.id).toBe(umbrella.id); + expect(umbrellaGroup!.memberProjectRefs.map((ref) => ref.projectId)).toEqual([ + sameFolder.id, + umbrella.id, + sameRepository.id, + ]); + expect( + [...umbrellaGroup!.umbrellaMembers].map(([key, member]) => [key, member.relativePath]), + ).toEqual([ + [`${environmentId}:${sameFolder.id}`, "api"], + [`${remote}:${sameRepository.id}`, "api"], + ]); + }); + it("retains a repository filter that still belongs to an ordinary project", () => { const scratch = makeProject("scratch", "/scratch", { isScratch: true }); const ordinary = makeProject("ordinary", "/ordinary"); diff --git a/packages/client-runtime/src/state/projectGrouping.ts b/packages/client-runtime/src/state/projectGrouping.ts index 607f28dc8ee10..72012082d8458 100644 --- a/packages/client-runtime/src/state/projectGrouping.ts +++ b/packages/client-runtime/src/state/projectGrouping.ts @@ -5,6 +5,7 @@ import { type EnvironmentId, type ScopedProjectRef, type SidebarProjectGroupingMode, + type UmbrellaMember, } from "@t3tools/contracts"; import type { ClientSettings } from "@t3tools/contracts/settings"; @@ -12,6 +13,7 @@ import type { EnvironmentProject } from "./models.ts"; import { normalizeProjectPathForComparison } from "./projects.ts"; const SCRATCH_PROJECT_SCOPE_KEY = "\0no-project"; +const EMPTY_UMBRELLA_MEMBERS: ReadonlyMap = new Map(); export interface ProjectGroupingSettings { readonly sidebarProjectGroupingMode: SidebarProjectGroupingMode; @@ -257,6 +259,10 @@ export interface ProjectGroup>; + /** Projects folded into an umbrella group, by scoped project key, with the member they matched. */ + readonly umbrellaMembers: ReadonlyMap; + /** The keys of the groups those folded projects left, so scopes saved with them follow. */ + readonly foldedProjectKeys: ReadonlyArray; readonly memberProjectRefs: ReadonlyArray; /** Clients write every member together. When members still disagree, the project stays visible. */ readonly pinned: boolean; @@ -311,6 +317,88 @@ function selectProjectIdentitySource( return freshestIdentifiedProject ?? winner; } +/** True for an umbrella: a project spanning at least one member checkout. */ +export function isUmbrellaProject(project: Pick): boolean { + return (project.umbrellaMembers?.length ?? 0) > 0; +} + +/** + * The umbrella a project belongs to as a member, matching how the sidebar folds it: its folder + * on the umbrella's environment, or else its repository on any environment. Only a folder match + * is the umbrella's own checkout; a repository match is a separate clone that merely groups there. + * Scratch projects and projects set to group separately belong to none. + */ +export function findUmbrellaMembership< + TProject extends Pick< + EnvironmentProject, + "environmentId" | "id" | "workspaceRoot" | "umbrellaMembers" + >, +>( + project: Pick< + EnvironmentProject, + "environmentId" | "id" | "workspaceRoot" | "repositoryIdentity" | "isScratch" + >, + projects: ReadonlyArray, + settings: ProjectGroupingSettings, +): { + readonly umbrella: TProject; + readonly member: UmbrellaMember; + readonly match: "folder" | "repository"; +} | null { + if (project.isScratch || resolveProjectGroupingMode(project, settings) === "separate") { + return null; + } + const projectPath = normalizeProjectPathForComparison(project.workspaceRoot); + const umbrellas = projects.filter( + (umbrella) => !(umbrella.id === project.id && umbrella.environmentId === project.environmentId), + ); + for (const umbrella of umbrellas) { + if (umbrella.environmentId !== project.environmentId) continue; + const member = umbrella.umbrellaMembers?.find( + (candidate) => normalizeProjectPathForComparison(candidate.path) === projectPath, + ); + if (member) return { umbrella, member, match: "folder" }; + } + if (!project.repositoryIdentity) return null; + const repositoryKey = repositoryGroupingKeyOf(project.repositoryIdentity); + for (const umbrella of umbrellas) { + const member = umbrella.umbrellaMembers?.find( + (candidate) => + candidate.repositoryIdentity && + repositoryGroupingKeyOf(candidate.repositoryIdentity) === repositoryKey, + ); + if (member) return { umbrella, member, match: "repository" }; + } + return null; +} + +interface Fold { + readonly key: string; + readonly ownKey: string; + readonly member: UmbrellaMember; +} + +/** Where each umbrella member project folds, when that is not already its own group. */ +function foldIntoUmbrellas( + winners: ReadonlyMap, + logicalKeyByPhysicalKey: ReadonlyMap, + settings: ProjectGroupingSettings, +): Map { + const umbrellas = [...winners.values()].filter(isUmbrellaProject); + const folded = new Map(); + if (umbrellas.length === 0) return folded; + for (const [physicalKey, project] of winners) { + // Umbrellas never fold into another. + if (isUmbrellaProject(project)) continue; + const membership = findUmbrellaMembership(project, umbrellas, settings); + if (membership === null) continue; + const key = logicalKeyByPhysicalKey.get(derivePhysicalProjectKey(membership.umbrella))!; + const ownKey = logicalKeyByPhysicalKey.get(physicalKey)!; + if (key !== ownKey) folded.set(physicalKey, { key, ownKey, member: membership.member }); + } + return folded; +} + export function buildProjectGroups(input: { readonly projects: ReadonlyArray; readonly settings: ProjectGroupingSettings; @@ -329,23 +417,39 @@ export function buildProjectGroups(input: { } const logicalKeyByPhysicalKey = new Map(); - const groupedMembers = new Map[]>(); + const winners = new Map(); for (const [physicalProjectKey, physicalProjects] of projectsByPhysicalKey) { const winner = physicalProjects.reduce((current, candidate) => shouldReplacePhysicalProjectWinner(current, candidate) ? candidate : current, ); const identitySource = selectProjectIdentitySource(physicalProjects, winner); - const logicalKey = deriveLogicalProjectKey(identitySource, { - groupingMode: resolveProjectGroupingMode(winner, input.settings), - groupScratchProjects: input.groupScratchProjects ?? false, - }); - logicalKeyByPhysicalKey.set(physicalProjectKey, logicalKey); - const member = { physicalProjectKey, project: winner }; - const existing = groupedMembers.get(logicalKey); - if (existing) { - existing.push(member); - } else { - groupedMembers.set(logicalKey, [member]); + logicalKeyByPhysicalKey.set( + physicalProjectKey, + deriveLogicalProjectKey(identitySource, { + groupingMode: resolveProjectGroupingMode(winner, input.settings), + groupScratchProjects: input.groupScratchProjects ?? false, + }), + ); + winners.set(physicalProjectKey, winner); + } + const folded = foldIntoUmbrellas(winners, logicalKeyByPhysicalKey, input.settings); + for (const [physicalProjectKey, { key }] of folded) { + logicalKeyByPhysicalKey.set(physicalProjectKey, key); + } + + const groupedMembers = new Map[]>(); + // A folded project joins after the umbrella's own projects, which keep naming the group. + for (const pass of [false, true]) { + for (const [physicalProjectKey, winner] of winners) { + if (folded.has(physicalProjectKey) !== pass) continue; + const logicalKey = logicalKeyByPhysicalKey.get(physicalProjectKey)!; + const member = { physicalProjectKey, project: winner }; + const existing = groupedMembers.get(logicalKey); + if (existing) { + existing.push(member); + } else { + groupedMembers.set(logicalKey, [member]); + } } } @@ -370,26 +474,41 @@ export function buildProjectGroups(input: { } } + const umbrellaMembersByProjectRef = new Map>(); + for (const project of input.projects) { + const fold = folded.get(derivePhysicalProjectKey(project)); + if (fold === undefined) continue; + const forGroup = new Map(umbrellaMembersByProjectRef.get(fold.key)); + forGroup.set(scopedProjectKey(scopeProjectRef(project.environmentId, project.id)), fold.member); + umbrellaMembersByProjectRef.set(fold.key, forGroup); + } + const preferredEnvironmentId = input.preferredEnvironmentId ?? null; return Array.from(groupedMembers, ([key, members]) => { + const own = members.filter((member) => !folded.has(member.physicalProjectKey)); + const naming = own.length > 0 ? own : members; const representative = (preferredEnvironmentId - ? members.find((member) => member.project.environmentId === preferredEnvironmentId)?.project - : null) ?? members[0]!.project; + ? naming.find((member) => member.project.environmentId === preferredEnvironmentId)?.project + : null) ?? naming[0]!.project; return { key, label: input.groupScratchProjects && representative.isScratch ? "No project" - : members.length > 1 + : naming.length > 1 ? deriveProjectGroupLabel({ groupKey: key, representative, - members: members.map((member) => member.project), + members: naming.map((member) => member.project), }) : representative.title, representative, members, + umbrellaMembers: umbrellaMembersByProjectRef.get(key) ?? EMPTY_UMBRELLA_MEMBERS, + foldedProjectKeys: members.flatMap( + (member) => folded.get(member.physicalProjectKey)?.ownKey ?? [], + ), memberProjectRefs: projectRefsByLogicalKey.get(key) ?? [], pinned: members.some((member) => member.project.pinnedAt != null), archived: members.every((member) => member.project.archivedAt != null), diff --git a/packages/client-runtime/src/state/shellReducer.test.ts b/packages/client-runtime/src/state/shellReducer.test.ts index f98a14c3ed32d..6491a3f176545 100644 --- a/packages/client-runtime/src/state/shellReducer.test.ts +++ b/packages/client-runtime/src/state/shellReducer.test.ts @@ -167,6 +167,49 @@ describe("applyShellStreamEvent", () => { expect(next.projects[0]?.repositoryIdentity).toEqual(repositoryIdentity); }); + it("takes umbrella members from a metadata refresh and keeps them through unscanned updates", () => { + const umbrellaMembers = [ + { + path: `${v2Project.workspaceRoot}/api`, + relativePath: "api", + repositoryIdentity: null, + source: "nested" as const, + }, + ]; + const previous = { ...v2ShellSnapshot, snapshotSequence: 5, projects: [v2Project] }; + const refreshed = mergeShellSnapshotProjects( + previous, + { ...previous, projects: [{ ...v2Project, title: "Ignored", umbrellaMembers }] }, + { resolvedRepositoryIdentityRoots: [] }, + ); + expect(refreshed.projects[0]).toEqual({ ...v2Project, umbrellaMembers }); + + const renamed = applyShellStreamEvent(refreshed, { + kind: "project.updated", + sequence: 6, + project: { ...v2Project, title: "Renamed" }, + }); + expect(renamed.projects[0]?.umbrellaMembers).toEqual(umbrellaMembers); + + // Turning the umbrella off turns its members back into suggestions. + const dissolved = mergeShellSnapshotProjects( + renamed, + { + ...renamed, + projects: [{ ...v2Project, umbrellaMembers: [], umbrellaSuggestions: umbrellaMembers }], + }, + { resolvedRepositoryIdentityRoots: [] }, + ); + expect(dissolved.projects[0]?.umbrellaMembers).toEqual([]); + expect(dissolved.projects[0]?.umbrellaSuggestions).toEqual(umbrellaMembers); + const enabledAgain = mergeShellSnapshotProjects( + dissolved, + { ...dissolved, projects: [{ ...v2Project, umbrellaMembers }] }, + { resolvedRepositoryIdentityRoots: [] }, + ); + expect(enabledAgain.projects[0]?.umbrellaSuggestions).toBeUndefined(); + }); + it("lower-sequence enrichment cannot resurrect empty structural state", () => { const previous = { ...v2ShellSnapshot, diff --git a/packages/client-runtime/src/state/shellReducer.ts b/packages/client-runtime/src/state/shellReducer.ts index 2ef7dea533f3c..35fc563757b63 100644 --- a/packages/client-runtime/src/state/shellReducer.ts +++ b/packages/client-runtime/src/state/shellReducer.ts @@ -3,6 +3,7 @@ import { OrchestrationV2ThreadShell, RepositoryIdentity, ThreadPullRequestLink, + UmbrellaMember, type OrchestrationV2ShellSnapshot, type OrchestrationV2ShellStreamItem, } from "@t3tools/contracts"; @@ -14,6 +15,7 @@ const sameLinks = Schema.toEquivalence(Schema.UndefinedOr(Schema.Array(ThreadPul const sameRepositoryIdentity = Schema.toEquivalence( Schema.UndefinedOr(Schema.NullOr(RepositoryIdentity)), ); +const sameUmbrellaMembers = Schema.toEquivalence(Schema.UndefinedOr(Schema.Array(UmbrellaMember))); export function sameThreadPullRequests( left: OrchestrationV2ThreadShell["pullRequests"], @@ -56,18 +58,54 @@ function upsertById( return items.map((candidate, candidateIndex) => (candidateIndex === index ? item : candidate)); } +/** A scanned project's umbrella fields travel together: members, suggestions, and why it cannot be one. */ +function umbrellaFieldsOf(project: OrchestrationProjectShell) { + return { + umbrellaMembers: project.umbrellaMembers, + ...(project.umbrellaSuggestions === undefined + ? {} + : { umbrellaSuggestions: project.umbrellaSuggestions }), + ...(project.umbrellaEnclosingRepository === undefined + ? {} + : { umbrellaEnclosingRepository: project.umbrellaEnclosingRepository }), + }; +} + +function withUmbrellaFieldsOf( + project: OrchestrationProjectShell, + source: OrchestrationProjectShell, +): OrchestrationProjectShell { + const { + umbrellaMembers: _members, + umbrellaSuggestions: _suggestions, + umbrellaEnclosingRepository: _enclosingRepository, + ...rest + } = project; + return { ...rest, ...umbrellaFieldsOf(source) }; +} + +function sameUmbrellaFields(left: OrchestrationProjectShell, right: OrchestrationProjectShell) { + return ( + sameUmbrellaMembers(left.umbrellaMembers, right.umbrellaMembers) && + sameUmbrellaMembers(left.umbrellaSuggestions, right.umbrellaSuggestions) && + left.umbrellaEnclosingRepository === right.umbrellaEnclosingRepository + ); +} + function retainRepositoryIdentity( previous: OrchestrationProjectShell | undefined, next: OrchestrationProjectShell, ): OrchestrationProjectShell { - if ( - next.repositoryIdentity == null && - previous?.repositoryIdentity != null && - previous.workspaceRoot === next.workspaceRoot - ) { - return { ...next, repositoryIdentity: previous.repositoryIdentity }; - } - return next; + if (previous === undefined || previous.workspaceRoot !== next.workspaceRoot) return next; + // Members are scanned asynchronously too; an unscanned update keeps the last known list. + const keepIdentity = next.repositoryIdentity == null && previous.repositoryIdentity != null; + const keepMembers = next.umbrellaMembers === undefined && previous.umbrellaMembers !== undefined; + if (!keepIdentity && !keepMembers) return next; + return { + ...next, + ...(keepIdentity ? { repositoryIdentity: previous.repositoryIdentity } : {}), + ...(keepMembers ? umbrellaFieldsOf(previous) : {}), + }; } export interface MergeShellSnapshotOptions { @@ -93,11 +131,15 @@ export function mergeShellSnapshotProjects( if (isEnrichment) { const nextById = new Map(next.projects.map((project) => [project.id, project] as const)); - const projects = previous.projects.map((project) => { - const candidate = nextById.get(project.id); - if (candidate === undefined || candidate.workspaceRoot !== project.workspaceRoot) { - return project; + const projects = previous.projects.map((prior) => { + const candidate = nextById.get(prior.id); + if (candidate === undefined || candidate.workspaceRoot !== prior.workspaceRoot) { + return prior; } + const project = + candidate.umbrellaMembers !== undefined && !sameUmbrellaFields(prior, candidate) + ? withUmbrellaFieldsOf(prior, candidate) + : prior; if (resolvedRootSet?.has(project.workspaceRoot) === true) { // Refreshes re-resolve every root; an unchanged identity keeps the project's identity // so every subscriber (each pull request row, the sidebar) skips re-rendering. diff --git a/packages/client-runtime/src/state/umbrella.test.ts b/packages/client-runtime/src/state/umbrella.test.ts new file mode 100644 index 0000000000000..1d166ccf9887b --- /dev/null +++ b/packages/client-runtime/src/state/umbrella.test.ts @@ -0,0 +1,191 @@ +import { EnvironmentId, ProjectId } from "@t3tools/contracts"; +import { describe, expect, it } from "vite-plus/test"; + +import type { EnvironmentProject } from "./models.ts"; +import { findUmbrellaMembership, type ProjectGroupingSettings } from "./projectGrouping.ts"; +import { + adoptUmbrellaMember, + removeUmbrellaMember, + restoreUmbrellaMember, + umbrellaAdoptionTargets, + umbrellaMemberLabel, + umbrellaMembersForThread, + umbrellaMembersInFiles, +} from "./umbrella.ts"; + +const environmentId = EnvironmentId.make("desktop"); +const grouping: ProjectGroupingSettings = { + sidebarProjectGroupingMode: "repository", + sidebarProjectGroupingOverrides: {}, +}; +const apiIdentity = { + canonicalKey: "github.com/acme/api", + locator: { source: "git-remote" as const, remoteName: "origin", remoteUrl: "x" }, +}; +const project = ( + id: string, + workspaceRoot: string, + overrides: Partial = {}, +): EnvironmentProject => ({ + environmentId, + id: ProjectId.make(id), + title: id, + workspaceRoot, + repositoryIdentity: null, + defaultModelSelection: null, + scripts: [], + createdAt: "2026-07-01T00:00:00.000Z", + updatedAt: "2026-07-01T00:00:00.000Z", + ...overrides, +}); +const umbrella = project("acme", "/clients/acme", { + umbrellaMembers: [ + { + path: "/clients/acme/api", + relativePath: "api", + repositoryIdentity: apiIdentity, + source: "nested", + }, + ], +}); + +describe("umbrella settings edits", () => { + it("excludes a discovered member, restores it, and forgets an adopted one", () => { + const removed = removeUmbrellaMember(umbrella, undefined, { + path: "/clients/acme/api", + source: "nested", + }); + expect(removed).toEqual({ + umbrellaAdoptedPaths: [], + umbrellaExcludedPaths: ["/clients/acme/api"], + }); + expect(restoreUmbrellaMember(umbrella, removed, "/clients/acme/api")).toEqual({ + umbrellaAdoptedPaths: [], + umbrellaExcludedPaths: [], + }); + + const adopted = adoptUmbrellaMember( + umbrella, + { umbrellaAdoptedPaths: ["/work/site"], umbrellaExcludedPaths: ["legacy"] }, + "/clients/acme/legacy", + ); + // Adopting a checkout is the user's confirmation, so it turns the umbrella on. + expect(adopted).toEqual({ + umbrellaEnabled: true, + umbrellaAdoptedPaths: ["/work/site", "/clients/acme/legacy"], + umbrellaExcludedPaths: [], + }); + expect( + removeUmbrellaMember(umbrella, adopted, { path: "/work/site", source: "adopted" }), + ).toEqual({ + umbrellaEnabled: true, + umbrellaAdoptedPaths: ["/clients/acme/legacy"], + umbrellaExcludedPaths: [], + }); + }); +}); + +describe("umbrella membership", () => { + it("matches a project by folder on the same environment or by repository anywhere", () => { + const here = project("api-here", "/clients/acme/api"); + const laptop = project("api-laptop", "/home/me/api", { + environmentId: EnvironmentId.make("laptop"), + repositoryIdentity: apiIdentity, + }); + const elsewhere = project("api-elsewhere", "/clients/acme/api", { + environmentId: EnvironmentId.make("laptop"), + }); + const projects = [umbrella, here, laptop, elsewhere]; + + expect(findUmbrellaMembership(here, projects, grouping)).toMatchObject({ + umbrella: { id: umbrella.id }, + match: "folder", + }); + // Another machine's clone only groups under the umbrella; removing it must not exclude the + // umbrella's own checkout. + expect(findUmbrellaMembership(laptop, projects, grouping)).toMatchObject({ + member: { relativePath: "api" }, + match: "repository", + }); + expect(findUmbrellaMembership(elsewhere, projects, grouping)).toBeNull(); + // A project set to group separately stays out of the umbrella, as the sidebar keeps it. + expect( + findUmbrellaMembership(here, projects, { + ...grouping, + sidebarProjectGroupingOverrides: { [`${environmentId}:/clients/acme/api`]: "separate" }, + }), + ).toBeNull(); + expect(umbrellaAdoptionTargets(here, projects)).toEqual([]); + expect(umbrellaAdoptionTargets(project("site", "/work/site"), projects)).toEqual([umbrella]); + expect(umbrellaAdoptionTargets(elsewhere, projects)).toEqual([]); + }); + + it("labels outside members by folder name", () => { + expect(umbrellaMemberLabel({ relativePath: "sites/web" })).toBe("sites/web"); + expect(umbrellaMemberLabel({ relativePath: "../../work/acme-site" })).toBe("acme-site"); + }); +}); + +describe("umbrellaMembersInFiles", () => { + const members = [ + { relativePath: "api" }, + { relativePath: "apps" }, + { relativePath: "apps/web" }, + { relativePath: "../../design/site" }, + ]; + const labels = ( + touched: ReadonlyArray<{ member: { relativePath: string } | null; folder: string }>, + ) => touched.map((entry) => entry.member?.relativePath ?? null); + + it("names each member a file sits in once, in member order, and the root for the rest", () => { + expect( + labels( + umbrellaMembersInFiles( + members, + ["apps/web/index.ts", "api/routes.txt", "api/README.md", "apps-notes.md"], + false, + ), + ), + ).toEqual([null, "api", "apps/web"]); + expect(labels(umbrellaMembersInFiles(members, ["apps/README.md"], false))).toEqual(["apps"]); + expect( + labels(umbrellaMembersInFiles(members, ["../../design/site/index.html"], false)), + ).toEqual(["../../design/site"]); + expect(umbrellaMembersInFiles([], ["README.md"], false)).toEqual([]); + }); + + it("finds adopted members under the worktree folder's _external", () => { + expect( + umbrellaMembersInFiles(members, ["_external/site/index.html", "api/a.ts"], true).map( + (entry) => [entry.member?.relativePath, entry.folder], + ), + ).toEqual([ + ["api", "api"], + ["../../design/site", "_external/site"], + ]); + }); +}); + +describe("umbrellaMembersForThread", () => { + const members = [ + { path: "/clients/acme/api", relativePath: "api" }, + { path: "/clients/acme/apps/web", relativePath: "apps/web" }, + { path: "/design/site", relativePath: "../../design/site" }, + { path: "/other/site", relativePath: "../../other/site" }, + ]; + + it("maps members into a worktree-mode thread's folder, adopted ones under _external", () => { + expect( + umbrellaMembersForThread(members, "/worktrees/acme/feature-1/").map((m) => m.path), + ).toEqual([ + "/worktrees/acme/feature-1/api", + "/worktrees/acme/feature-1/apps/web", + "/worktrees/acme/feature-1/_external/site", + "/worktrees/acme/feature-1/_external/site-2", + ]); + expect(umbrellaMembersForThread(members.slice(1, 2), "C:\\worktrees\\acme\\f")[0]?.path).toBe( + "C:\\worktrees\\acme\\f\\apps\\web", + ); + expect(umbrellaMembersForThread(members, null)).toBe(members); + }); +}); diff --git a/packages/client-runtime/src/state/umbrella.ts b/packages/client-runtime/src/state/umbrella.ts new file mode 100644 index 0000000000000..20428cd5c6923 --- /dev/null +++ b/packages/client-runtime/src/state/umbrella.ts @@ -0,0 +1,157 @@ +import type { ProjectSettingsOverrides, UmbrellaMember } from "@t3tools/contracts"; + +import { isAbsolutePath } from "@t3tools/shared/path"; +import { umbrellaWorktreeMemberPaths } from "@t3tools/shared/umbrellaWorktree"; + +import type { EnvironmentProject } from "./models.ts"; +import { normalizeProjectPathForComparison } from "./projects.ts"; +import { isUmbrellaProject } from "./projectGrouping.ts"; + +type UmbrellaProject = Pick< + EnvironmentProject, + "environmentId" | "id" | "title" | "workspaceRoot" | "umbrellaMembers" +>; +type UmbrellaOverrides = Pick< + ProjectSettingsOverrides, + "umbrellaEnabled" | "umbrellaAdoptedPaths" | "umbrellaExcludedPaths" +>; + +/** How a member reads in a list: its path under the umbrella, or its folder name when adopted from outside. */ +export function umbrellaMemberLabel(member: Pick): string { + return member.relativePath.startsWith("../") + ? (member.relativePath.split("/").at(-1) ?? member.relativePath) + : member.relativePath; +} + +/** The member each folded project's threads work in, labelled, by scoped project key. */ +export function umbrellaMemberLabelsByProjectKey( + foldedMembers: Iterable>>, +): ReadonlyMap { + const labels = new Map(); + for (const members of foldedMembers) { + for (const [key, member] of members) labels.set(key, umbrellaMemberLabel(member)); + } + return labels; +} + +/** + * The members as a thread sees them: their own checkouts, or, for a worktree-mode thread, their + * worktrees inside the thread's folder. + */ +export function umbrellaMembersForThread< + TMember extends Pick, +>( + members: ReadonlyArray, + worktreePath: string | null | undefined, +): ReadonlyArray { + if (!worktreePath || members.length === 0) return members; + const root = worktreePath.replace(/[\\/]+$/, ""); + const separator = root.includes("/") || !root.includes("\\") ? "/" : "\\"; + const paths = umbrellaWorktreeMemberPaths(members.map((member) => member.relativePath)); + return members.map((member, index) => ({ + ...member, + path: `${root}${separator}${paths[index]!.split("/").join(separator)}`, + })); +} + +/** + * The members a turn's files touch, in member order, each with its folder in the file paths: under + * the umbrella folder or, for a worktree-mode thread, its folder. A null member with folder "" leads + * when files sit in the umbrella's own repository, outside every member. + */ +export function umbrellaMembersInFiles>( + members: ReadonlyArray, + filePaths: ReadonlyArray, + worktreeMode: boolean, +): ReadonlyArray<{ readonly member: TMember | null; readonly folder: string }> { + if (members.length === 0) return []; + const relativePaths = members.map((member) => member.relativePath); + const folders = worktreeMode ? umbrellaWorktreeMemberPaths(relativePaths) : relativePaths; + const prefixes = folders.map((path, index) => ({ prefix: `${path}/`, index })); + // A member nested in another's folder owns its own files. + prefixes.sort((left, right) => right.prefix.length - left.prefix.length); + const touched = new Set(); + let root = false; + for (const filePath of filePaths) { + const owner = prefixes.find(({ prefix }) => filePath.startsWith(prefix)); + if (owner === undefined) root = true; + else touched.add(owner.index); + } + return [ + ...(root ? [{ member: null, folder: "" }] : []), + ...members.flatMap((member, index) => + touched.has(index) ? [{ member, folder: folders[index]! }] : [], + ), + ]; +} + +/** Settings may hold paths relative to the umbrella root; compare them resolved. */ +function sameSettingPath(root: string, entry: string, path: string): boolean { + const resolved = isAbsolutePath(entry) ? entry : `${root.replace(/[\\/]+$/, "")}/${entry}`; + return normalizeProjectPathForComparison(resolved) === normalizeProjectPathForComparison(path); +} + +function without(root: string, entries: ReadonlyArray | undefined, path: string) { + return (entries ?? []).filter((entry) => !sameSettingPath(root, entry, path)); +} + +/** Adds a checkout, lifting an exclusion that hid it, and turns the umbrella on. */ +export function adoptUmbrellaMember( + umbrella: Pick, + overrides: UmbrellaOverrides | undefined, + path: string, +): UmbrellaOverrides { + const root = umbrella.workspaceRoot; + return { + ...overrides, + umbrellaEnabled: true, + umbrellaAdoptedPaths: [...without(root, overrides?.umbrellaAdoptedPaths, path), path], + umbrellaExcludedPaths: without(root, overrides?.umbrellaExcludedPaths, path), + }; +} + +/** Drops a member: an adopted one is forgotten, a discovered one is excluded so scans skip it. */ +export function removeUmbrellaMember( + umbrella: Pick, + overrides: UmbrellaOverrides | undefined, + member: Pick, +): UmbrellaOverrides { + const root = umbrella.workspaceRoot; + const excluded = without(root, overrides?.umbrellaExcludedPaths, member.path); + return { + ...overrides, + umbrellaAdoptedPaths: without(root, overrides?.umbrellaAdoptedPaths, member.path), + umbrellaExcludedPaths: member.source === "nested" ? [...excluded, member.path] : excluded, + }; +} + +/** Lets a discovered checkout back in. */ +export function restoreUmbrellaMember( + umbrella: Pick, + overrides: UmbrellaOverrides | undefined, + path: string, +): UmbrellaOverrides { + return { + ...overrides, + umbrellaAdoptedPaths: overrides?.umbrellaAdoptedPaths ?? [], + umbrellaExcludedPaths: without(umbrella.workspaceRoot, overrides?.umbrellaExcludedPaths, path), + }; +} + +/** Umbrellas on the project's environment that could adopt its folder. */ +export function umbrellaAdoptionTargets( + project: Pick, + projects: ReadonlyArray, +): ReadonlyArray { + if (isUmbrellaProject(project)) return []; + const projectPath = normalizeProjectPathForComparison(project.workspaceRoot); + return projects.filter( + (umbrella) => + umbrella.environmentId === project.environmentId && + umbrella.id !== project.id && + isUmbrellaProject(umbrella) && + !(umbrella.umbrellaMembers ?? []).some( + (member) => normalizeProjectPathForComparison(member.path) === projectPath, + ), + ); +} diff --git a/packages/contracts/src/orchestrationProject.ts b/packages/contracts/src/orchestrationProject.ts index 35cee805b8812..08ed3bccf0595 100644 --- a/packages/contracts/src/orchestrationProject.ts +++ b/packages/contracts/src/orchestrationProject.ts @@ -3,7 +3,7 @@ import * as Schema from "effect/Schema"; import { IsoDateTime, ProjectId, TrimmedNonEmptyString } from "./baseSchemas.ts"; import { RepositoryIdentity, ThreadEnvMode } from "./environment.ts"; import { ModelSelection } from "./modelSelection.ts"; -import { ProjectScript, ReceivedProjectIcon } from "./project.ts"; +import { ProjectScript, ReceivedProjectIcon, UmbrellaMember } from "./project.ts"; export const OrchestrationProjectShell = Schema.Struct({ id: ProjectId, @@ -13,6 +13,12 @@ export const OrchestrationProjectShell = Schema.Struct({ hasCustomTitle: Schema.optional(Schema.Boolean), workspaceRoot: TrimmedNonEmptyString, repositoryIdentity: Schema.optional(Schema.NullOr(RepositoryIdentity)), + // Absent until the server has scanned the root; empty means the project is not an umbrella. + umbrellaMembers: Schema.optional(Schema.Array(UmbrellaMember)), + // Checkouts found under the root while the umbrella is off, offered for the user to confirm. + umbrellaSuggestions: Schema.optional(Schema.Array(UmbrellaMember)), + // The repository whose work tree holds the root; umbrella mode is unavailable there. + umbrellaEnclosingRepository: Schema.optional(TrimmedNonEmptyString), defaultModelSelection: Schema.NullOr(ModelSelection), defaultThreadEnvMode: Schema.optional(Schema.NullOr(ThreadEnvMode)), // Opt-in because background sync performs network I/O and may move the checkout. diff --git a/packages/contracts/src/project.ts b/packages/contracts/src/project.ts index 80848ba81f557..7e4e83ee0b1fd 100644 --- a/packages/contracts/src/project.ts +++ b/packages/contracts/src/project.ts @@ -151,6 +151,16 @@ export const ReceivedProjectIcon = ForwardCompatibleUnion(projectIconMembers, "k ), ); +/** A checkout an umbrella project spans: discovered under its root, or adopted from elsewhere on the environment. */ +export const UmbrellaMember = Schema.Struct({ + path: TrimmedNonEmptyString, + /** Relative to the umbrella root, with `/` separators; starts with `../` for an adopted checkout outside it. */ + relativePath: TrimmedNonEmptyString, + repositoryIdentity: Schema.NullOr(RepositoryIdentity), + source: Schema.Literals(["nested", "adopted"]), +}); +export type UmbrellaMember = typeof UmbrellaMember.Type; + export const Project = Schema.Struct({ id: ProjectId, title: TrimmedNonEmptyString, diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.ts index 0013e288983e0..2700b06aeaf88 100644 --- a/packages/contracts/src/settings.ts +++ b/packages/contracts/src/settings.ts @@ -1238,7 +1238,20 @@ export const ProjectSettingsOverrides = Schema.Struct({ providerInstances: Schema.optionalKey( Schema.Record(ProviderInstanceId, ProjectProviderInstanceOverride), ), -} satisfies Record); + /** Discovered checkouts join the project only once the user turns this on. */ + umbrellaEnabled: Schema.optionalKey(Schema.Boolean), + /** Checkouts anywhere on this environment that join the project as umbrella members. */ + umbrellaAdoptedPaths: Schema.optionalKey(Schema.Array(TrimmedNonEmptyString)), + /** Checkouts left out of the umbrella, including ones discovered under its root. */ + umbrellaExcludedPaths: Schema.optionalKey(Schema.Array(TrimmedNonEmptyString)), +} satisfies Record< + | ProjectScopedServerSettingKey + | "providerInstances" + | "umbrellaEnabled" + | "umbrellaAdoptedPaths" + | "umbrellaExcludedPaths", + unknown +>); export type ProjectSettingsOverrides = typeof ProjectSettingsOverrides.Type; // Whole-entry writers must round-trip unknown keys; keep the type closed to catch misspellings. diff --git a/packages/shared/package.json b/packages/shared/package.json index 3de18958220ef..4964af8437f7f 100644 --- a/packages/shared/package.json +++ b/packages/shared/package.json @@ -71,6 +71,10 @@ "types": "./src/agentAwareness.ts", "import": "./src/agentAwareness.ts" }, + "./umbrellaWorktree": { + "types": "./src/umbrellaWorktree.ts", + "import": "./src/umbrellaWorktree.ts" + }, "./git": { "types": "./src/git.ts", "import": "./src/git.ts" diff --git a/packages/shared/src/umbrellaWorktree.ts b/packages/shared/src/umbrellaWorktree.ts new file mode 100644 index 0000000000000..8b0d695a38aa8 --- /dev/null +++ b/packages/shared/src/umbrellaWorktree.ts @@ -0,0 +1,29 @@ +/** Folder in a worktree-mode umbrella thread that holds members adopted from outside the umbrella. */ +const UMBRELLA_WORKTREE_EXTERNAL_FOLDER = "_external"; + +/** + * Where each umbrella member sits inside a worktree-mode thread's folder, given members' paths + * relative to the umbrella root. A member under the root keeps its path; one adopted from outside + * goes under `_external/`, numbered when two share a name. + */ +export function umbrellaWorktreeMemberPaths( + relativePaths: ReadonlyArray, +): ReadonlyArray { + const isExternal = (relativePath: string) => + relativePath === ".." || relativePath.startsWith("../"); + const taken = new Set(relativePaths.filter((relativePath) => !isExternal(relativePath))); + return relativePaths.map((relativePath) => { + if (!isExternal(relativePath)) return relativePath; + const name = + relativePath + .split("/") + .filter((segment) => segment !== ".." && segment !== "") + .at(-1) ?? "member"; + let candidate = `${UMBRELLA_WORKTREE_EXTERNAL_FOLDER}/${name}`; + for (let suffix = 2; taken.has(candidate); suffix++) { + candidate = `${UMBRELLA_WORKTREE_EXTERNAL_FOLDER}/${name}-${suffix}`; + } + taken.add(candidate); + return candidate; + }); +}