From 7618cc6f2f0743f785e1c5476b32b291e5fb8ee4 Mon Sep 17 00:00:00 2001 From: Na0s Date: Mon, 16 Nov 2026 16:11:55 -0500 Subject: [PATCH 01/59] feat(server): umbrella projects span member checkouts A project folder holding several git checkouts gets one T3 project: members are discovered under the root (cached in project enrichment) or adopted from project settings, the enclosing repository leaves them out of status, review diffs, commits and checkpoints, each member checkpoints under its own prefix, and a turn's edited members link their branch pull requests to the thread. Co-Authored-By: Claude Opus 5.5 --- .../src/checkpointing/CheckpointStore.test.ts | 100 +++++++ .../src/checkpointing/CheckpointStore.ts | 229 ++++++++++++++- apps/server/src/git/linkCreatedPullRequest.ts | 11 +- .../CheckpointCaptureService.test.ts | 6 +- .../CheckpointService.test.ts | 6 +- .../src/orchestration-v2/CheckpointService.ts | 4 +- .../DelegatedCompletionDelivery.test.ts | 2 + .../ThreadPullRequestService.test.ts | 112 ++++++++ .../ThreadPullRequestService.ts | 82 +++++- apps/server/src/orchestration-v2/http.ts | 3 +- .../src/orchestration-v2/runtimeLayer.test.ts | 2 + .../src/project/ProjectEnrichmentService.ts | 79 +++++- apps/server/src/project/ProjectService.ts | 3 + .../src/project/UmbrellaMembership.test.ts | 37 +++ apps/server/src/project/UmbrellaMembership.ts | 267 ++++++++++++++++++ .../src/project/umbrellaDiscovery.test.ts | 53 ++++ apps/server/src/project/umbrellaDiscovery.ts | 56 ++++ apps/server/src/server.ts | 9 + apps/server/src/vcs/GitVcsDriver.ts | 56 +++- apps/server/src/vcs/GitVcsDriverCore.test.ts | 37 +++ apps/server/src/vcs/GitVcsDriverCore.ts | 37 ++- apps/server/src/vcs/UmbrellaMemberIndex.ts | 82 ++++++ apps/server/src/vcs/VcsDriver.ts | 2 + apps/server/src/workspace/KnownWorkspaces.ts | 15 +- apps/server/src/ws.ts | 90 +++++- .../contracts/src/orchestrationProject.ts | 4 +- packages/contracts/src/project.ts | 13 + packages/contracts/src/settings.ts | 12 +- 28 files changed, 1362 insertions(+), 47 deletions(-) create mode 100644 apps/server/src/project/UmbrellaMembership.test.ts create mode 100644 apps/server/src/project/UmbrellaMembership.ts create mode 100644 apps/server/src/project/umbrellaDiscovery.test.ts create mode 100644 apps/server/src/project/umbrellaDiscovery.ts create mode 100644 apps/server/src/vcs/UmbrellaMemberIndex.ts diff --git a/apps/server/src/checkpointing/CheckpointStore.test.ts b/apps/server/src/checkpointing/CheckpointStore.test.ts index 15fa9205dee21..1755519393879 100644 --- a/apps/server/src/checkpointing/CheckpointStore.test.ts +++ b/apps/server/src/checkpointing/CheckpointStore.test.ts @@ -1,4 +1,5 @@ // @effect-diagnostics nodeBuiltinImport:off +import * as NodeFS from "node:fs"; import * as NodePath from "node:path"; import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; @@ -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,102 @@ 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); + 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* 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([ + "apps/api/new.txt", + "apps/api/README.md", + "README.md", + ]); + 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("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); + }), + ); + }); }); diff --git a/apps/server/src/checkpointing/CheckpointStore.ts b/apps/server/src/checkpointing/CheckpointStore.ts index 8eadf2b5342af..02c731907e97a 100644 --- a/apps/server/src/checkpointing/CheckpointStore.ts +++ b/apps/server/src/checkpointing/CheckpointStore.ts @@ -1,11 +1,14 @@ import { type CheckpointRef } 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 { 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"; export interface CaptureCheckpointInput { readonly cwd: string; @@ -49,6 +52,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 +82,35 @@ 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; +} + /** @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 +128,223 @@ export const make = Effect.gen(function* () { return (yield* git.detectRepository(cwd)) !== null; }); + const membersOf = (cwd: string) => + umbrellaMembers.hasMembers() + ? fileSystem.realPath(cwd).pipe( + Effect.map((resolved) => umbrellaMembers.membersOf(resolved)), + Effect.orElseSucceed(() => umbrellaMembers.membersOf(cwd)), + ) + : Effect.succeed([]); + + // 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 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); + } + // A member that cannot be captured drops its ref, so diffs and restores leave it alone. + yield* Effect.forEach( + components, + (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; }); 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); + } + let restored = false; + for (const component of components) { + const checkpoints = yield* resolveCheckpoints(component.cwd); + // Falling back to HEAD would discard a member's edits it never checkpointed. + if ( + yield* checkpoints.restoreCheckpoint({ + cwd: component.cwd, + checkpointRef: input.checkpointRef, + fallbackToHead: component.prefix === "" && input.fallbackToHead === true, + }) + ) { + restored = true; + } + } + return restored; + }); + + const diffComponent = Effect.fn("CheckpointStore.diffComponent")(function* ( + component: CheckpointComponent, + input: DiffCheckpointsInput, + ) { + if ( + component.prefix !== "" && + !( + (yield* hasRef(component.cwd, input.fromCheckpointRef)) && + (yield* hasRef(component.cwd, input.toCheckpointRef)) + ) + ) { + 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* hasRef(component.cwd, input.fromCheckpointRef)) && + (yield* hasRef(component.cwd, input.toCheckpointRef)) + ) + ) { + return { component, authored: new Set() as ReadonlySet | null }; + } + 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); + for (const component of components ?? [{ cwd: input.cwd, prefix: "" }]) { + const checkpoints = yield* resolveCheckpoints(component.cwd); + yield* checkpoints.deleteCheckpointRefs({ ...input, cwd: component.cwd }); + } }); 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/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/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/ThreadPullRequestService.test.ts b/apps/server/src/orchestration-v2/ThreadPullRequestService.test.ts index bd7154dae96ae..eca768bdc659e 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,117 @@ describe("ThreadPullRequestServiceV2 reads", () => { }), ); + it.effect("links the branch pull request of each umbrella member a turn edited", () => + Effect.gen(function* () { + const thread = threadShell("umbrella-thread"); + 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: 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", + baseBranch: "main", + headBranch: 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)({ + membersOf: () => Effect.succeed([member("apps/api"), member("apps/web")]), + }), + Layer.succeed( + SecureRandom.SecureRandom, + SecureRandom.make((size) => new Uint8Array(size).fill(1)), + ), + FileSystem.layerNoop({}), + 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: "README.md" }] }, + } as unknown as OrchestrationV2DomainEvent); + yield* Deferred.await(linked); + yield* service.drain; + + expect(lookups).toEqual(["/clients/acme/apps/api@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..d363607259459 100644 --- a/apps/server/src/orchestration-v2/ThreadPullRequestService.ts +++ b/apps/server/src/orchestration-v2/ThreadPullRequestService.ts @@ -23,11 +23,13 @@ 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 { forkParked } from "../serverActivation.ts"; import { sourceControlDefinitions } from "../sourceControl/sourceControlDefinitions.ts"; import { makeNoPullRequestRechecks } from "./noPullRequestRechecks.ts"; @@ -123,6 +125,7 @@ export const make = Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; const backgroundPolicy = yield* BackgroundPolicy.BackgroundPolicy; + const umbrellaMembership = yield* Effect.serviceOption(UmbrellaMembership.UmbrellaMembership); const pendingBackfill = new Map(); const noPullRequestRechecks = makeNoPullRequestRechecks(); @@ -423,6 +426,70 @@ export const make = Effect.gen(function* () { ), ); + // A checkpoint lists the umbrella members a turn edited; each one's branch pull request joins + // the thread. Only that turn's members are read, so an unlinked pull request stays unlinked. + 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.membersOf(project.value)) ?? []; + const touched = members.filter((member) => + files.some((file) => file.path.startsWith(`${member.relativePath}/`)), + ); + yield* Effect.forEach( + touched, + (member) => + Effect.gen(function* () { + const status = yield* git.localStatus({ cwd: member.path }); + if (status.refName === null || status.isDefaultRef) return; + const detected = yield* git.branchPullRequest( + { cwd: member.path, branch: status.refName }, + { refresh: true, confirmTerminal: false }, + ); + if (detected === null || pullRequestPredatesThread(detected, thread.createdAt)) return; + const key = pullRequestKeyOf(detected, member.repositoryIdentity); + if (key === null) 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 +519,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 +578,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..7474965ef64ff 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, diff --git a/apps/server/src/project/ProjectEnrichmentService.ts b/apps/server/src/project/ProjectEnrichmentService.ts index c08bba24bcceb..edbd29d4cf6eb 100644 --- a/apps/server/src/project/ProjectEnrichmentService.ts +++ b/apps/server/src/project/ProjectEnrichmentService.ts @@ -14,6 +14,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 +23,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; a new checkout under a project root shows up within this window. +const DEFAULT_NESTED_REPOSITORIES_TTL = Duration.minutes(5); export interface ProjectEnrichment { readonly repositoryIdentity: RepositoryIdentity | null; @@ -33,6 +36,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 +55,13 @@ 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; schedules a scan when stale. */ + readonly peekNestedRepositories: ( + workspaceRoot: string, + ) => 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 +161,25 @@ export const make = Effect.fn("ProjectEnrichmentService.make")(function* ( }), }, ); + // Outlive the cache entry, like identities; only the worker's list decides whether to publish. + const knownNestedRepositories = new Map>(); + const publishedNestedRepositories = new Map>(); + const rememberNested = ( + map: Map>, + workspaceRoot: string, + nested: ReadonlyArray, + ) => { + map.delete(workspaceRoot); + if (map.size >= cacheCapacity) { + const oldestRoot = map.keys().next().value; + if (oldestRoot !== undefined) map.delete(oldestRoot); + } + map.set(workspaceRoot, nested); + }; + const nestedRepositoriesCache = yield* Cache.makeWith( + (workspaceRoot: string) => discoverNestedRepositories(workspaceRoot), + { capacity: cacheCapacity, timeToLive: () => DEFAULT_NESTED_REPOSITORIES_TTL }, + ); const makeWorkLane = Effect.gen(function* () { const pendingRoots = yield* Ref.make>(new Set()); const queue = yield* Effect.acquireRelease(Queue.dropping(maxPending), (queue) => @@ -158,6 +189,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 +215,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 +258,27 @@ 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.get(nestedRepositoriesCache, workspaceRoot); + rememberNested(knownNestedRepositories, workspaceRoot, nested); + // Rescans of an unchanged folder would otherwise push a shell frame to every subscriber. + if (sameList(publishedNestedRepositories.get(workspaceRoot), nested)) return; + rememberNested(publishedNestedRepositories, workspaceRoot, nested); + yield* PubSub.publish(changes, { + workspaceRoot, + repositoryIdentityResolved: false, + nestedRepositoriesResolved: true, + enrichment: yield* peek(workspaceRoot), + }); + }, + ); + const startWorkers = ( lane: EnrichmentWorkLane, resolve: (workspaceRoot: string) => Effect.Effect, @@ -244,6 +297,7 @@ export const make = Effect.fn("ProjectEnrichmentService.make")(function* ( [ startWorkers(repositoryIdentityLane, resolveRepositoryIdentity), startWorkers(faviconLane, resolveFavicon), + startWorkers(nestedRepositoriesLane, resolveNestedRepositories), ], { concurrency: "unbounded", discard: true }, ); @@ -252,7 +306,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 +373,22 @@ export const make = Effect.fn("ProjectEnrichmentService.make")(function* ( return Exit.isSuccess(resolved) ? resolved.value : null; }); + const peekNestedRepositories: ProjectEnrichmentService["Service"]["peekNestedRepositories"] = + Effect.fnUntraced(function* (workspaceRoot) { + const cached = yield* Cache.getSuccess(nestedRepositoriesCache, workspaceRoot); + if (Option.isNone(cached)) { + yield* requestLane(nestedRepositoriesLane, workspaceRoot, "nestedRepositories"); + } + return Option.getOrUndefined(cached) ?? knownNestedRepositories.get(workspaceRoot) ?? null; + }); + + const readNestedRepositories: ProjectEnrichmentService["Service"]["readNestedRepositories"] = + Effect.fn("ProjectEnrichmentService.readNestedRepositories")(function* (workspaceRoot) { + const nested = yield* Cache.get(nestedRepositoriesCache, workspaceRoot); + rememberNested(knownNestedRepositories, workspaceRoot, nested); + return nested; + }); + const invalidate: ProjectEnrichmentService["Service"]["invalidate"] = Effect.fn( "ProjectEnrichmentService.invalidate", )(function* (workspaceRoots) { @@ -331,8 +401,11 @@ export const make = Effect.fn("ProjectEnrichmentService.make")(function* ( Effect.sync(() => { lookupsInFlight.delete(workspaceRoot); lastRepositoryIdentities.delete(workspaceRoot); + knownNestedRepositories.delete(workspaceRoot); + publishedNestedRepositories.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 +431,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..b1617caa3028e 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 } from "./UmbrellaMembership.ts"; import { makeIsWorktreeContainer } from "./worktreeContainer.ts"; import * as WorkspacePaths from "../workspace/WorkspacePaths.ts"; @@ -596,6 +597,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..23ceb37ad4975 --- /dev/null +++ b/apps/server/src/project/UmbrellaMembership.test.ts @@ -0,0 +1,37 @@ +import { it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import * as Path from "effect/Path"; +import { expect } from "vite-plus/test"; + +import { resolveUmbrellaMembers } from "./UmbrellaMembership.ts"; + +it.effect("combines discovered and adopted checkouts and drops exclusions", () => + Effect.gen(function* () { + const members = resolveUmbrellaMembers({ + path: yield* Path.Path, + workspaceRoot: "/clients/acme", + nested: ["/clients/acme/api", "/clients/acme/sites/web", "/clients/acme/legacy"], + adopted: ["/work/acme-mobile", "api", "/clients/acme"], + excluded: ["legacy"], + identityOf: (memberPath) => + memberPath.endsWith("api") + ? { + canonicalKey: "github.com/acme/api", + locator: { source: "git-remote", remoteName: "origin", remoteUrl: "x" }, + } + : null, + }); + + expect( + members.map(({ relativePath, source, repositoryIdentity }) => ({ + relativePath, + source, + identity: repositoryIdentity?.canonicalKey ?? null, + })), + ).toEqual([ + { relativePath: "../../work/acme-mobile", source: "adopted", identity: null }, + { relativePath: "api", source: "nested", identity: "github.com/acme/api" }, + { relativePath: "sites/web", source: "nested", identity: null }, + ]); + }).pipe(Effect.provide(Path.layer)), +); diff --git a/apps/server/src/project/UmbrellaMembership.ts b/apps/server/src/project/UmbrellaMembership.ts new file mode 100644 index 0000000000000..4f73d2d18e26b --- /dev/null +++ b/apps/server/src/project/UmbrellaMembership.ts @@ -0,0 +1,267 @@ +import type { + ProjectId, + ProjectSettingsOverrides, + RepositoryIdentity, + ServerSettings as ServerSettingsSchema, + UmbrellaMember, +} from "@t3tools/contracts"; +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 type * as Scope from "effect/Scope"; +import * as Stream from "effect/Stream"; + +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 * as ProjectEnrichmentService from "./ProjectEnrichmentService.ts"; + +interface UmbrellaProject { + readonly id: ProjectId; + readonly workspaceRoot: string; +} + +const EMPTY_PATHS: ReadonlyArray = []; + +function umbrellaSettingsOf( + overrides: + | Pick + | undefined, +) { + return { + adopted: overrides?.umbrellaAdoptedPaths ?? EMPTY_PATHS, + excluded: overrides?.umbrellaExcludedPaths ?? EMPTY_PATHS, + }; +} + +/** + * Discovered checkouts plus adopted ones, minus exclusions, ordered by relative path. Relative + * settings paths resolve against the root; a checkout found both ways counts as nested. + */ +export function resolveUmbrellaMembers(input: { + readonly path: Path.Path; + readonly workspaceRoot: string; + readonly nested: ReadonlyArray; + readonly adopted: ReadonlyArray; + readonly excluded: ReadonlyArray; + readonly identityOf: (memberPath: string) => RepositoryIdentity | null; +}): ReadonlyArray { + const { path } = input; + const root = path.resolve(input.workspaceRoot); + const resolve = (value: string) => path.resolve(root, value); + const excluded = new Set(input.excluded.map(resolve)); + const members = new Map(); + for (const nested of input.nested) members.set(resolve(nested), "nested"); + for (const adopted of input.adopted) { + const memberPath = resolve(adopted); + if (!members.has(memberPath)) members.set(memberPath, "adopted"); + } + return Array.from(members, ([memberPath, source]) => ({ memberPath, source })) + .filter(({ memberPath }) => memberPath !== root && !excluded.has(memberPath)) + .map(({ memberPath, source }) => ({ + path: memberPath, + relativePath: path.relative(root, memberPath).split(path.sep).join("/"), + repositoryIdentity: input.identityOf(memberPath), + source, + })) + .toSorted((left, right) => left.relativePath.localeCompare(right.relativePath)); +} + +const sameSettings = ( + left: ReturnType, + right: ReturnType, +) => + 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 discovery and identities, never scanning inline; undefined before the root's first scan. */ + readonly membersOf: ( + project: UmbrellaProject, + ) => Effect.Effect | undefined>; + /** Projects whose adopted or excluded checkouts changed in settings. */ + 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"] => ({})), + ); + + const resolveFor = ( + project: UmbrellaProject, + nested: ReadonlyArray, + overrides: ServerSettingsSchema["projectSettingsOverrides"], + identityOf: (memberPath: string) => RepositoryIdentity | null, + ) => + resolveUmbrellaMembers({ + path, + workspaceRoot: project.workspaceRoot, + nested, + ...umbrellaSettingsOf(overrides[project.id]), + identityOf, + }); + + const membersOf: UmbrellaMembership["Service"]["membersOf"] = Effect.fnUntraced( + function* (project) { + const nested = yield* enrichment.peekNestedRepositories(project.workspaceRoot); + if (nested === null) return undefined; + const overrides = yield* readSettings; + const { adopted } = umbrellaSettingsOf(overrides[project.id]); + if (nested.length === 0 && adopted.length === 0) return []; + const candidates = resolveFor(project, nested, overrides, () => null); + const identities = new Map( + yield* Effect.forEach(candidates, (member) => + enrichment + .getAvailable(member.path) + .pipe( + Effect.map(({ repositoryIdentity }) => [member.path, repositoryIdentity] as const), + ), + ), + ); + return candidates.map((member) => ({ + ...member, + repositoryIdentity: identities.get(member.path) ?? null, + })); + }, + ); + + const realPath = (value: string) => + fileSystem.realPath(value).pipe(Effect.orElseSucceed(() => path.resolve(value))); + + // Git consults the index on every read, so it holds only the members' resolved paths. + const rebuildIndex = Effect.fn("UmbrellaMembership.rebuildIndex")(function* (options: { + readonly scan: boolean; + }) { + const projects = yield* projectStore.listShells().pipe(Effect.orElseSucceed(() => [])); + const overrides = yield* readSettings; + const umbrellas = new Map>(); + yield* Effect.forEach( + projects, + (project) => + Effect.gen(function* () { + const nested = options.scan + ? yield* enrichment.readNestedRepositories(project.workspaceRoot) + : ((yield* enrichment.peekNestedRepositories(project.workspaceRoot)) ?? EMPTY_PATHS); + const members = resolveFor(project, nested, overrides, () => null); + if (members.length === 0) return; + const root = yield* realPath(project.workspaceRoot); + const checkouts = yield* Effect.forEach(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); + }); + + 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({ scan: false }); + yield* PubSub.publish(changes, changed); + }); + + yield* forkParked( + Effect.gen(function* () { + yield* rebuildIndex({ scan: true }); + yield* Effect.all( + [ + Stream.runForEach(settingsChanges, onSettings), + Stream.fromSubscription(enrichmentChanges).pipe( + Stream.filter((change) => change.nestedRepositoriesResolved === true), + Stream.groupedWithin(64, Duration.millis(250)), + Stream.runForEach(() => rebuildIndex({ scan: false })), + ), + ], + { concurrency: "unbounded", discard: true }, + ); + }).pipe( + Effect.catchCause((cause) => + Effect.logWarning("Umbrella membership sync stopped", { cause }), + ), + ), + ); + + return UmbrellaMembership.of({ + membersOf, + subscribeChanges: PubSub.subscribe(changes), + }); +}); + +export const layer = Layer.effect(UmbrellaMembership, make); + +/** Adds `umbrellaMembers` 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 + .membersOf(project) + .pipe( + Effect.map((umbrellaMembers) => + umbrellaMembers === undefined ? project : { ...project, umbrellaMembers }, + ), + ), + { concurrency: 16 }, + ); +}); diff --git a/apps/server/src/project/umbrellaDiscovery.test.ts b/apps/server/src/project/umbrellaDiscovery.test.ts new file mode 100644 index 0000000000000..4dabf5aad1e0f --- /dev/null +++ b/apps/server/src/project/umbrellaDiscovery.test.ts @@ -0,0 +1,53 @@ +// @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", + ]); + 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"), + ]); + const shallow = yield* discoverNestedRepositories(root, { maxDepth: 1 }); + expect(shallow.map((path) => NodePath.relative(root, path))).toEqual(["api"]); + } 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..689725e2682c2 --- /dev/null +++ b/apps/server/src/project/umbrellaDiscovery.ts @@ -0,0 +1,56 @@ +// @effect-diagnostics nodeBuiltinImport:off +import * as NodeFSP from "node:fs/promises"; +import * as NodePath from "node:path"; + +import * as Effect from "effect/Effect"; + +const DEFAULT_MAX_DEPTH = 3; +// Bounds a scan of a huge non-umbrella folder; a client folder holds far fewer directories. +const DEFAULT_MAX_DIRECTORIES = 1_000; +const SKIPPED_DIRECTORY_NAMES = new Set(["node_modules"]); + +export interface NestedRepositoryDiscoveryOptions { + readonly maxDepth?: number; + readonly maxDirectories?: number; +} + +const readDirectoryEntries = (directory: string) => + Effect.promise(() => NodeFSP.readdir(directory, { withFileTypes: true }).catch(() => [])); + +/** + * Git checkouts under `root`, at most `maxDepth` 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 folders, `node_modules`, and symlinks are never entered. + */ +export const discoverNestedRepositories = Effect.fn("umbrellaDiscovery.discoverNestedRepositories")( + function* (root: string, options: NestedRepositoryDiscoveryOptions = {}) { + const maxDepth = options.maxDepth ?? DEFAULT_MAX_DEPTH; + let budget = options.maxDirectories ?? DEFAULT_MAX_DIRECTORIES; + const found: string[] = []; + let frontier = [{ directory: root, entries: yield* readDirectoryEntries(root) }]; + for (let depth = 1; depth <= maxDepth && 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 < maxDepth) { + next.push({ directory: child, entries: childEntries }); + } + } + } + frontier = next; + } + return found.toSorted(); + }, +); 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/vcs/GitVcsDriver.ts b/apps/server/src/vcs/GitVcsDriver.ts index d0da1b3d09b3d..892d2b3973b55 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 { 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,44 @@ 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"); +} + 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. + const memberExclusionsUnder = (cwd: string) => + umbrellaMembers.hasMembers() + ? fileSystem.realPath(cwd).pipe( + Effect.map((resolved) => + umbrellaMembers + .memberPathsWithin(resolved) + .map((member) => `:(exclude,literal)${member}`), + ), + 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 +1427,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 +1445,7 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( workspaceIgnored ? "-u" : "-A", "--", ".", + ...memberExclusions, ...exclusions, ], env: commitEnv, @@ -1851,6 +1886,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 +1895,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 +1978,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 +1998,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 +2111,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 +2137,9 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( }); } - return result.stdout; + return input.pathPrefix && input.format === "numstat" + ? prefixNumstatPaths(result.stdout, input.pathPrefix) + : result.stdout; }), 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..e9c6daa6bed2d 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,42 @@ 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("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..87776db17e847 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 { UmbrellaMemberIndex } from "./UmbrellaMemberIndex.ts"; import { explicitBareRepositoryEnv, gitConfigEnv, @@ -1024,6 +1025,14 @@ 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 && umbrellaMembers.hasMembers() + ? umbrellaMembers + .memberPathsWithin(worktreeRoot) + .map((member) => `:(top,exclude,literal)${member}`) + : []; type StatusFetchState = { phase: "queued" | "running" | "claimed"; claimed: Deferred.Deferred; @@ -2401,10 +2410,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 +2430,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 +2905,16 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* }); } } + const exclusions = umbrellaMembers.hasMembers() + ? memberExclusions( + (yield* resolveRepositoryPaths(cwd).pipe(Effect.orElseSucceed(() => null))) + ?.worktreeRoot, + ) + : []; yield* runGit( "GitVcsDriver.commit.addAll", cwd, - [...config, "add", "-A"], + [...config, "add", "-A", ...(exclusions.length === 0 ? [] : ["--", ...exclusions])], env ? { env } : {}, ); } @@ -3894,10 +3910,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 +3966,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 +4157,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 +4189,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.ts b/apps/server/src/vcs/UmbrellaMemberIndex.ts new file mode 100644 index 0000000000000..b969acc53bbf4 --- /dev/null +++ b/apps/server/src/vcs/UmbrellaMemberIndex.ts @@ -0,0 +1,82 @@ +// @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; +} + +export interface UmbrellaMemberIndexShape { + /** Replaces every umbrella, keyed by symlink-resolved root. */ + readonly replace: ( + umbrellas: ReadonlyMap>, + ) => Effect.Effect; + readonly membersOf: (resolvedRoot: string) => ReadonlyArray; + readonly hasMembers: () => boolean; + /** Member checkouts strictly inside a work tree, relative to it with `/` separators. */ + readonly memberPathsWithin: (resolvedWorktreeRoot: string) => ReadonlyArray; +} + +const EMPTY: ReadonlyArray = []; + +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>(); + let memberPaths: ReadonlyArray = []; + return { + replace: (next) => + Effect.sync(() => { + umbrellas = new Map( + Array.from(next, ([root, members]) => [NodePath.resolve(root), members] as const), + ); + memberPaths = [ + ...new Set( + Array.from(umbrellas.values()).flatMap((members) => + members.map((member) => NodePath.resolve(member.path)), + ), + ), + ]; + }), + membersOf: (resolvedRoot) => umbrellas.get(NodePath.resolve(resolvedRoot)) ?? EMPTY, + hasMembers: () => memberPaths.length > 0, + memberPathsWithin: (resolvedWorktreeRoot) => { + if (memberPaths.length === 0) return EMPTY; + const root = NodePath.resolve(resolvedWorktreeRoot); + return memberPaths + .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, + 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..5d58c0d3c4dbd 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,14 @@ export const make = Effect.gen(function* () { for (const project of projects) { if (within(yield* resolveRoot(project.workspaceRoot))) return true; } + // Umbrella members adopted from outside the project's folder. + for (const project of projects) { + const adopted = + worktreeSettings.projectSettingsOverrides[project.id]?.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/ws.ts b/apps/server/src/ws.ts index 6defac543eaac..81b1553730882 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, + type ProjectId, authScopeResponse, AuthAccessStreamError, type AuthAccessStreamEvent, @@ -221,6 +222,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 +886,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 +1154,18 @@ export const subscribeOrchestrationV2Shell = Effect.fn("ws.orchestrationV2.subsc shouldPublishShellApplicationEvent(stored, subagentThreadIds); const enrichmentChanges = yield* projectEnrichment.subscribeChanges; + const umbrellaEnrichmentChanges = yield* projectEnrichment.subscribeChanges; + const umbrellaSettingsChanges = yield* Effect.serviceOption( + UmbrellaMembership.UmbrellaMembership, + ).pipe( + Effect.flatMap( + Option.match({ + onNone: () => Effect.succeed(Stream.empty), + onSome: (membership) => + membership.subscribeChanges.pipe(Effect.map(Stream.fromSubscription)), + }), + ), + ); const loadProjectMetadataSnapshot = Effect.fn("ws.orchestrationV2.loadProjectMetadataSnapshot")( function* (snapshotSequence: number) { const enriched = yield* enrichProjectShells(yield* projects.listShells()); @@ -1303,6 +1322,67 @@ 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 = Stream.merge( + Stream.fromSubscription(umbrellaEnrichmentChanges).pipe( + Stream.map((change) => ({ + root: change.workspaceRoot, + rescanned: change.nestedRepositoriesResolved === true, + projectIds: [] as ReadonlyArray, + })), + ), + umbrellaSettingsChanges.pipe( + Stream.map((projectIds) => ({ root: null, rescanned: false, projectIds })), + ), + ).pipe( + Stream.groupedWithin(64, Duration.millis(50)), + Stream.mapEffect((triggers) => + Effect.gen(function* () { + const rescannedRoots = new Set(); + const changedRoots = new Set(); + const projectIds = new Set(); + for (const trigger of triggers) { + if (trigger.root !== null) { + changedRoots.add(trigger.root); + if (trigger.rescanned) rescannedRoots.add(trigger.root); + } + for (const projectId of trigger.projectIds) projectIds.add(projectId); + } + const shells = yield* UmbrellaMembership.attachUmbrellaMembers( + yield* projects.listShells(), + ); + const affected = shells.filter( + (project) => + projectIds.has(project.id) || + (project.umbrellaMembers !== undefined && + (rescannedRoots.has(project.workspaceRoot) || + project.umbrellaMembers.some((member) => changedRoots.has(member.path)))), + ); + if (affected.length === 0) return []; + const changedProjects = yield* Effect.forEach(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 +1418,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 +1433,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 +1473,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( diff --git a/packages/contracts/src/orchestrationProject.ts b/packages/contracts/src/orchestrationProject.ts index 35cee805b8812..678e63e20b336 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,8 @@ 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)), 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..0d9711242c197 100644 --- a/packages/contracts/src/project.ts +++ b/packages/contracts/src/project.ts @@ -151,6 +151,19 @@ export const ReceivedProjectIcon = ForwardCompatibleUnion(projectIconMembers, "k ), ); +export const UmbrellaMemberSource = Schema.Literals(["nested", "adopted"]); +export type UmbrellaMemberSource = typeof UmbrellaMemberSource.Type; + +/** 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: UmbrellaMemberSource, +}); +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..f0bb8bb52f203 100644 --- a/packages/contracts/src/settings.ts +++ b/packages/contracts/src/settings.ts @@ -1238,7 +1238,17 @@ export const ProjectSettingsOverrides = Schema.Struct({ providerInstances: Schema.optionalKey( Schema.Record(ProviderInstanceId, ProjectProviderInstanceOverride), ), -} satisfies Record); + /** 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" + | "umbrellaAdoptedPaths" + | "umbrellaExcludedPaths", + unknown +>); export type ProjectSettingsOverrides = typeof ProjectSettingsOverrides.Type; // Whole-entry writers must round-trip unknown keys; keep the type closed to catch misspellings. From ef9142f860289e7399a6dcab73d62bfe943591e9 Mon Sep 17 00:00:00 2001 From: Na0s Date: Mon, 16 Nov 2026 16:15:16 -0500 Subject: [PATCH 02/59] feat(client-runtime): fold umbrella member projects into the umbrella's group Projects whose folder is an umbrella member on the same environment, or whose repository matches a member on any environment, join the umbrella's sidebar group and carry the member they matched. Shell merges keep scanned members, and shared helpers compute the settings edits to adopt, exclude, or restore a member. Co-Authored-By: Claude Opus 5.5 --- packages/client-runtime/package.json | 4 + .../src/state/projectGrouping.test.ts | 56 +++++++ .../src/state/projectGrouping.ts | 111 ++++++++++++-- .../src/state/shellReducer.test.ts | 32 ++++ .../client-runtime/src/state/shellReducer.ts | 33 ++-- .../client-runtime/src/state/umbrella.test.ts | 100 ++++++++++++ packages/client-runtime/src/state/umbrella.ts | 145 ++++++++++++++++++ 7 files changed, 453 insertions(+), 28 deletions(-) create mode 100644 packages/client-runtime/src/state/umbrella.test.ts create mode 100644 packages/client-runtime/src/state/umbrella.ts 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..4d5e68d05fb67 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,8 @@ export interface ProjectGroup>; + /** Projects folded into an umbrella group, by scoped project key, with the member they matched. */ + readonly umbrellaMembers: ReadonlyMap; readonly memberProjectRefs: ReadonlyArray; /** Clients write every member together. When members still disagree, the project stays visible. */ readonly pinned: boolean; @@ -311,6 +315,53 @@ 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; +} + +/** + * Where each project that is an umbrella's member folds: the same folder on the umbrella's + * environment, or the same repository on any environment. Umbrellas never fold into another. + */ +function foldIntoUmbrellas( + winners: ReadonlyMap, + logicalKeyByPhysicalKey: ReadonlyMap, + settings: ProjectGroupingSettings, +): Map { + const byPath = new Map(); + const byRepository = new Map(); + for (const [physicalKey, project] of winners) { + if (!isUmbrellaProject(project)) continue; + const key = logicalKeyByPhysicalKey.get(physicalKey)!; + for (const member of project.umbrellaMembers ?? []) { + const pathKey = derivePhysicalProjectKeyFromPath(project.environmentId, member.path); + if (!byPath.has(pathKey)) byPath.set(pathKey, { key, member }); + const repositoryKey = member.repositoryIdentity + ? repositoryGroupingKeyOf(member.repositoryIdentity) + : null; + if (repositoryKey && !byRepository.has(repositoryKey)) { + byRepository.set(repositoryKey, { key, member }); + } + } + } + const folded = new Map(); + if (byPath.size === 0 && byRepository.size === 0) return folded; + for (const [physicalKey, project] of winners) { + if (isUmbrellaProject(project) || project.isScratch) continue; + if (resolveProjectGroupingMode(project, settings) === "separate") continue; + const target = + byPath.get(physicalKey) ?? + (project.repositoryIdentity + ? byRepository.get(repositoryGroupingKeyOf(project.repositoryIdentity)) + : undefined); + if (target !== undefined && target.key !== logicalKeyByPhysicalKey.get(physicalKey)) { + folded.set(physicalKey, target); + } + } + return folded; +} + export function buildProjectGroups(input: { readonly projects: ReadonlyArray; readonly settings: ProjectGroupingSettings; @@ -329,23 +380,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 +437,38 @@ 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, 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..53a082dfca269 100644 --- a/packages/client-runtime/src/state/shellReducer.test.ts +++ b/packages/client-runtime/src/state/shellReducer.test.ts @@ -167,6 +167,38 @@ 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); + + const dissolved = mergeShellSnapshotProjects( + renamed, + { ...renamed, projects: [{ ...v2Project, umbrellaMembers: [] }] }, + { resolvedRepositoryIdentityRoots: [] }, + ); + expect(dissolved.projects[0]?.umbrellaMembers).toEqual([]); + }); + 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..35e653bda5f07 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"], @@ -60,14 +62,16 @@ 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 ? { umbrellaMembers: previous.umbrellaMembers } : {}), + }; } export interface MergeShellSnapshotOptions { @@ -93,11 +97,16 @@ 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 && + !sameUmbrellaMembers(prior.umbrellaMembers, candidate.umbrellaMembers) + ? { ...prior, umbrellaMembers: candidate.umbrellaMembers } + : 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..00e11381bbd0b --- /dev/null +++ b/packages/client-runtime/src/state/umbrella.test.ts @@ -0,0 +1,100 @@ +import { EnvironmentId, ProjectId } from "@t3tools/contracts"; +import { describe, expect, it } from "vite-plus/test"; + +import type { EnvironmentProject } from "./models.ts"; +import { + adoptUmbrellaMember, + findUmbrellaMembership, + removeUmbrellaMember, + restoreUmbrellaMember, + umbrellaAdoptionTargets, + umbrellaMemberLabel, +} from "./umbrella.ts"; + +const environmentId = EnvironmentId.make("desktop"); +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", + ); + expect(adopted).toEqual({ + umbrellaAdoptedPaths: ["/work/site", "/clients/acme/legacy"], + umbrellaExcludedPaths: [], + }); + expect( + removeUmbrellaMember(umbrella, adopted, { path: "/work/site", source: "adopted" }), + ).toEqual({ 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)?.umbrella.id).toBe(umbrella.id); + expect(findUmbrellaMembership(laptop, projects)?.member.relativePath).toBe("api"); + expect(findUmbrellaMembership(elsewhere, projects)).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"); + }); +}); diff --git a/packages/client-runtime/src/state/umbrella.ts b/packages/client-runtime/src/state/umbrella.ts new file mode 100644 index 0000000000000..27a6398c23dd9 --- /dev/null +++ b/packages/client-runtime/src/state/umbrella.ts @@ -0,0 +1,145 @@ +import { + repositoryGroupingKeyOf, + type ProjectSettingsOverrides, + type UmbrellaMember, +} from "@t3tools/contracts"; + +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, + "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; +} + +const isAbsolute = (value: string) => value.startsWith("/") || /^[A-Za-z]:[\\/]/.test(value); + +/** Settings may hold paths relative to the umbrella root; compare them resolved. */ +function sameSettingPath(root: string, entry: string, path: string): boolean { + const resolved = isAbsolute(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)); +} + +function withPaths( + overrides: UmbrellaOverrides | undefined, + adopted: ReadonlyArray, + excluded: ReadonlyArray, +): UmbrellaOverrides { + return { + ...overrides, + umbrellaAdoptedPaths: adopted, + umbrellaExcludedPaths: excluded, + }; +} + +/** Adds a checkout, lifting an exclusion that hid it. */ +export function adoptUmbrellaMember( + umbrella: Pick, + overrides: UmbrellaOverrides | undefined, + path: string, +): UmbrellaOverrides { + const root = umbrella.workspaceRoot; + return withPaths( + overrides, + [...without(root, overrides?.umbrellaAdoptedPaths, path), path], + 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 withPaths( + overrides, + without(root, overrides?.umbrellaAdoptedPaths, member.path), + 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 withPaths( + overrides, + overrides?.umbrellaAdoptedPaths ?? [], + without(umbrella.workspaceRoot, overrides?.umbrellaExcludedPaths, path), + ); +} + +/** + * The umbrella a project belongs to as a member: its folder on the umbrella's environment, or + * its repository on any environment, matching how the sidebar folds it. + */ +export function findUmbrellaMembership( + project: Pick< + EnvironmentProject, + "environmentId" | "id" | "workspaceRoot" | "repositoryIdentity" + >, + projects: ReadonlyArray, +): { readonly umbrella: TProject; readonly member: UmbrellaMember } | null { + const projectPath = normalizeProjectPathForComparison(project.workspaceRoot); + const repositoryKey = project.repositoryIdentity + ? repositoryGroupingKeyOf(project.repositoryIdentity) + : null; + for (const umbrella of projects) { + if (umbrella.id === project.id && umbrella.environmentId === project.environmentId) continue; + for (const member of umbrella.umbrellaMembers ?? []) { + if ( + umbrella.environmentId === project.environmentId && + normalizeProjectPathForComparison(member.path) === projectPath + ) { + return { umbrella, member }; + } + if ( + repositoryKey !== null && + member.repositoryIdentity && + repositoryGroupingKeyOf(member.repositoryIdentity) === repositoryKey + ) { + return { umbrella, member }; + } + } + } + return null; +} + +/** 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, + ), + ); +} From 4f9f4355c0319217ed8f4928d07f31d8478b91a9 Mon Sep 17 00:00:00 2001 From: Na0s Date: Mon, 16 Nov 2026 16:18:46 -0500 Subject: [PATCH 03/59] fix(server): refresh umbrella members on clients and keep the git index current Clients get member changes from settings edits, rescans, and member identity resolutions as metadata refreshes, and the member index rebuilds periodically so removed projects stop excluding paths. Co-Authored-By: Claude Opus 5.5 --- .../src/orchestration-v2/ShellStream.test.ts | 41 +++++++++++++++++++ .../src/orchestration-v2/ShellStream.ts | 33 +++++++++++++++ .../ThreadPullRequestService.test.ts | 4 +- apps/server/src/project/UmbrellaMembership.ts | 6 +++ apps/server/src/ws.ts | 25 +++-------- 5 files changed, 87 insertions(+), 22 deletions(-) diff --git a/apps/server/src/orchestration-v2/ShellStream.test.ts b/apps/server/src/orchestration-v2/ShellStream.test.ts index fbc610235dd01..88059f52a6497 100644 --- a/apps/server/src/orchestration-v2/ShellStream.test.ts +++ b/apps/server/src/orchestration-v2/ShellStream.test.ts @@ -17,6 +17,7 @@ import * as Stream from "effect/Stream"; import * as TestClock from "effect/testing/TestClock"; import { + selectUmbrellaRefreshProjects, activeShellRowsForSubscriber, bufferShellLiveStream, composeShellStreamWithEnrichment, @@ -695,3 +696,43 @@ describe("skipUnchangedThreadShells", () => { }), ); }); + +describe("selectUmbrellaRefreshProjects", () => { + it("picks scanned projects a settings edit, rescan, or member identity can change", () => { + const member = (path: string) => ({ + path, + relativePath: path.split("/").at(-1)!, + repositoryIdentity: null, + source: "nested" as const, + }); + const project = ( + id: string, + workspaceRoot: string, + umbrellaMembers?: ReadonlyArray>, + ) => ({ + id: ProjectId.make(id), + workspaceRoot, + ...(umbrellaMembers === undefined ? {} : { umbrellaMembers }), + }); + const projects = [ + project("edited", "/edited", []), + project("rescanned", "/rescanned", []), + project("member-identity", "/acme", [member("/acme/api")]), + project("untouched", "/untouched", [member("/untouched/web")]), + project("unscanned", "/unscanned"), + ]; + + const selected = selectUmbrellaRefreshProjects({ + projects, + triggers: [ + { root: null, rescanned: false, projectIds: [ProjectId.make("edited")] }, + { root: "/rescanned", rescanned: true, projectIds: [] }, + { root: "/acme/api", rescanned: false, projectIds: [] }, + { root: "/untouched", rescanned: false, projectIds: [] }, + { root: null, rescanned: false, projectIds: [ProjectId.make("unscanned")] }, + ], + }); + + expect(selected.map((entry) => entry.id)).toEqual(["edited", "rescanned", "member-identity"]); + }); +}); diff --git a/apps/server/src/orchestration-v2/ShellStream.ts b/apps/server/src/orchestration-v2/ShellStream.ts index 5ee1005b16830..c2feb74c7c6b2 100644 --- a/apps/server/src/orchestration-v2/ShellStream.ts +++ b/apps/server/src/orchestration-v2/ShellStream.ts @@ -690,6 +690,39 @@ export function dedupeShellEnrichment( }); } +/** + * Scanned projects whose members a batch of changes can alter: settings edits name projects, + * a rescan names a root, and a resolved identity names a member's path. + */ +export function selectUmbrellaRefreshProjects< + P extends Pick, +>(input: { + readonly projects: ReadonlyArray

; + readonly triggers: Iterable<{ + readonly root: string | null; + readonly rescanned: boolean; + readonly projectIds: ReadonlyArray; + }>; +}): ReadonlyArray

{ + const rescannedRoots = new Set(); + const changedRoots = new Set(); + const projectIds = new Set(); + for (const trigger of input.triggers) { + if (trigger.root !== null) { + changedRoots.add(trigger.root); + if (trigger.rescanned) rescannedRoots.add(trigger.root); + } + for (const projectId of trigger.projectIds) projectIds.add(projectId); + } + return input.projects.filter( + (project) => + project.umbrellaMembers !== undefined && + (projectIds.has(project.id) || + rescannedRoots.has(project.workspaceRoot) || + project.umbrellaMembers.some((member) => changedRoots.has(member.path))), + ); +} + export function shellStreamItemFromEnrichmentRefresh(input: { readonly snapshot: OrchestrationV2ShellSnapshot; readonly changes: ReadonlyArray<{ readonly workspaceRoot: string }>; diff --git a/apps/server/src/orchestration-v2/ThreadPullRequestService.test.ts b/apps/server/src/orchestration-v2/ThreadPullRequestService.test.ts index eca768bdc659e..5ce13b6e6f36b 100644 --- a/apps/server/src/orchestration-v2/ThreadPullRequestService.test.ts +++ b/apps/server/src/orchestration-v2/ThreadPullRequestService.test.ts @@ -241,8 +241,8 @@ describe("ThreadPullRequestServiceV2 reads", () => { number: 12, title: "API change", url: "https://github.com/acme/api/pull/12", - baseBranch: "main", - headBranch: branch, + baseRef: "main", + headRef: branch, state: "open" as const, repositoryKey: "github.com/acme/api", updatedAt: null, diff --git a/apps/server/src/project/UmbrellaMembership.ts b/apps/server/src/project/UmbrellaMembership.ts index 4f73d2d18e26b..f85a01d5a399e 100644 --- a/apps/server/src/project/UmbrellaMembership.ts +++ b/apps/server/src/project/UmbrellaMembership.ts @@ -13,6 +13,7 @@ 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 type * as Scope from "effect/Scope"; import * as Stream from "effect/Stream"; @@ -228,6 +229,11 @@ export const make = Effect.gen(function* () { Stream.groupedWithin(64, Duration.millis(250)), Stream.runForEach(() => rebuildIndex({ scan: false })), ), + // Catches projects removed or moved since, which publish no membership change. + rebuildIndex({ scan: false }).pipe( + Effect.repeat(Schedule.spaced(Duration.minutes(5))), + Effect.delay(Duration.minutes(5)), + ), ], { concurrency: "unbounded", discard: true }, ); diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index 81b1553730882..b35755044a73e 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -135,6 +135,7 @@ import { dedupeShellEnrichment, loadOlderSettledThreadsPage, loadShellSnapshotParts, + selectUmbrellaRefreshProjects, shellStreamItemFromEnrichmentRefresh, shellStreamItemFromThreadShell, shellStreamItemsFromInitialSnapshot, @@ -1338,26 +1339,10 @@ export const subscribeOrchestrationV2Shell = Effect.fn("ws.orchestrationV2.subsc Stream.groupedWithin(64, Duration.millis(50)), Stream.mapEffect((triggers) => Effect.gen(function* () { - const rescannedRoots = new Set(); - const changedRoots = new Set(); - const projectIds = new Set(); - for (const trigger of triggers) { - if (trigger.root !== null) { - changedRoots.add(trigger.root); - if (trigger.rescanned) rescannedRoots.add(trigger.root); - } - for (const projectId of trigger.projectIds) projectIds.add(projectId); - } - const shells = yield* UmbrellaMembership.attachUmbrellaMembers( - yield* projects.listShells(), - ); - const affected = shells.filter( - (project) => - projectIds.has(project.id) || - (project.umbrellaMembers !== undefined && - (rescannedRoots.has(project.workspaceRoot) || - project.umbrellaMembers.some((member) => changedRoots.has(member.path)))), - ); + const affected = selectUmbrellaRefreshProjects({ + projects: yield* UmbrellaMembership.attachUmbrellaMembers(yield* projects.listShells()), + triggers, + }); if (affected.length === 0) return []; const changedProjects = yield* Effect.forEach(affected, (project) => projectEnrichment From fdd20069c2a5281e8da159d2d4750dbd4711288a Mon Sep 17 00:00:00 2001 From: Na0s Date: Mon, 16 Nov 2026 16:30:03 -0500 Subject: [PATCH 04/59] feat(web): show umbrella members in the diff panel, sidebar, settings and mobile rows MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The diff panel gains a tab per member checkout with changes, folded member projects label their thread rows, project folder menus and the command palette add or remove a project from an umbrella, and Settings → Projects lists an umbrella's checkouts with remove/restore and an "Add checkout" field. Mobile thread cards show the member label. Co-Authored-By: Claude Opus 5.5 --- apps/mobile/src/features/home/HomeScreen.tsx | 11 ++ .../src/features/home/homeThreadList.ts | 18 ++ .../threads/ThreadNavigationSidebar.tsx | 7 + .../new-task-project-selection.test.ts | 1 + .../features/threads/thread-list-v2-items.tsx | 43 +++-- apps/server/src/review/ReviewService.test.ts | 27 ++- apps/web/src/components/CommandPalette.tsx | 38 ++++ apps/web/src/components/DiffPanel.tsx | 142 ++++++++++++--- apps/web/src/components/Sidebar.tsx | 33 ++++ .../diffs/umbrellaDiffSections.logic.test.ts | 84 +++++++++ .../diffs/umbrellaDiffSections.logic.ts | 64 +++++++ .../settings/ProjectSettingsPanel.tsx | 2 + .../settings/ProjectUmbrellaSettings.tsx | 168 ++++++++++++++++++ .../scheduledTasksSettings.logic.test.ts | 1 + .../settings/scopedSettings.test.ts | 35 ++++ .../src/components/settings/scopedSettings.ts | 37 ++++ .../components/settings/settingsScope.test.ts | 1 + .../src/components/settings/settingsSearch.ts | 8 + .../components/settings/useScopedSettings.ts | 12 ++ .../components/sidebar/SidebarThreadRow.tsx | 12 ++ .../src/hooks/useUmbrellaMembershipEdits.ts | 32 ++++ apps/web/src/sidebarProjectGrouping.ts | 4 + apps/web/src/state/vcs.ts | 24 +++ apps/web/src/umbrellaMembership.logic.test.ts | 103 +++++++++++ apps/web/src/umbrellaMembership.logic.ts | 106 +++++++++++ docs/user/project-settings.md | 23 +++ 26 files changed, 996 insertions(+), 40 deletions(-) create mode 100644 apps/web/src/components/diffs/umbrellaDiffSections.logic.test.ts create mode 100644 apps/web/src/components/diffs/umbrellaDiffSections.logic.ts create mode 100644 apps/web/src/components/settings/ProjectUmbrellaSettings.tsx create mode 100644 apps/web/src/hooks/useUmbrellaMembershipEdits.ts create mode 100644 apps/web/src/umbrellaMembership.logic.test.ts create mode 100644 apps/web/src/umbrellaMembership.logic.ts diff --git a/apps/mobile/src/features/home/HomeScreen.tsx b/apps/mobile/src/features/home/HomeScreen.tsx index c2946c59ed065..64fa44d5fcbe5 100644 --- a/apps/mobile/src/features/home/HomeScreen.tsx +++ b/apps/mobile/src/features/home/HomeScreen.tsx @@ -94,6 +94,7 @@ import { findHomeProjectScope, type HomeProjectSortOrder, sortHomeProjectScopes, + umbrellaMemberLabelsByProjectKey, } from "./homeThreadList"; import { createSwipeRowActivation } from "./swipe-row-activation"; import { SwipeableScrollGateProvider, useSwipeableScrollGate } from "./thread-swipe-actions"; @@ -327,6 +328,10 @@ export function HomeScreen(props: HomeScreenProps) { }), [projects, selectedEnvironmentId, projectGroupingMode], ); + const umbrellaMemberLabelByProjectKey = useMemo( + () => umbrellaMemberLabelsByProjectKey(projectScopes), + [projectScopes], + ); const hasSearchQuery = props.searchQuery.trim().length > 0; const projectByKey = (() => { const map = new Map(); @@ -538,6 +543,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 +608,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..c5b026a40108e 100644 --- a/apps/mobile/src/features/home/homeThreadList.ts +++ b/apps/mobile/src/features/home/homeThreadList.ts @@ -7,6 +7,7 @@ import type { EnvironmentProject, EnvironmentThreadShell, } from "@t3tools/client-runtime/state/shell"; +import { umbrellaMemberLabel } from "@t3tools/client-runtime/state/umbrella"; import { getThreadSortTimestamp, toSortableTimestamp, @@ -16,6 +17,7 @@ import type { ScopedProjectRef, SidebarProjectGroupingMode, SidebarProjectSortOrder, + UmbrellaMember, } from "@t3tools/contracts"; import * as Arr from "effect/Array"; import * as Order from "effect/Order"; @@ -31,6 +33,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,12 +72,26 @@ 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, }; }); } +/** The umbrella member each folded project's threads work in, by scoped project key. */ +export function umbrellaMemberLabelsByProjectKey( + scopes: ReadonlyArray>, +): ReadonlyMap { + return new Map( + scopes.flatMap((scope) => + [...scope.umbrellaMembers].map( + ([key, member]) => [key, umbrellaMemberLabel(member)] as const, + ), + ), + ); +} + /** The scope the thread list's project filter shows; an archived or unknown key shows all projects. */ export function resolveHomeProjectFilterScope( scopes: ReadonlyArray, diff --git a/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx b/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx index 6de4c54d6d430..7fdd041895487 100644 --- a/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx +++ b/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx @@ -53,6 +53,7 @@ import { buildHomeProjectScopes, resolveHomeProjectFilterScope, sortHomeProjectScopes, + umbrellaMemberLabelsByProjectKey, } from "../home/homeThreadList"; import { SwipeableScrollGateProvider, useSwipeableScrollGate } from "../home/thread-swipe-actions"; import { usePendingTaskListActions } from "../home/usePendingTaskListActions"; @@ -208,6 +209,10 @@ function ThreadNavigationSidebarPane(props: ThreadNavigationSidebarProps) { ), [projectScopes], ); + const umbrellaMemberLabelByProjectKey = useMemo( + () => umbrellaMemberLabelsByProjectKey(projectScopes), + [projectScopes], + ); const selectedProjectScope = resolveHomeProjectFilterScope(projectScopes, projects, options); const threadSearch = useThreadSearch( searchEnvironmentIds, @@ -356,6 +361,7 @@ function ThreadNavigationSidebarPane(props: ThreadNavigationSidebarProps) { selectedThreadKey: selectedThreadKey ?? "", projectByKey, projectTitleByProjectKey, + umbrellaMemberLabelByProjectKey, savedConnectionsById, listEnvironments, threadSearchMatchByKey, @@ -423,6 +429,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/review/ReviewService.test.ts b/apps/server/src/review/ReviewService.test.ts index 4df56454cfc58..7f0e71045316a 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,13 @@ function layer(input: { ServerSettings.ServerSettingsService.layerTest({ worktreesDirectory: input.worktreesDirectory ?? "", previousWorktreesDirectories: [...(input.previousWorktreesDirectories ?? [])], + ...(input.adoptedPaths === undefined + ? {} + : { + projectSettingsOverrides: { + [ProjectId.make("project-0")]: { umbrellaAdoptedPaths: [...input.adoptedPaths] }, + }, + }), }), ), Layer.provide(ServerConfig.layerTest(input.workspaceRoot, input.baseDir)), @@ -166,17 +174,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/web/src/components/CommandPalette.tsx b/apps/web/src/components/CommandPalette.tsx index cd32eeb4a6468..49ca5d14f0423 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) => @@ -1746,6 +1752,38 @@ function OpenCommandPaletteDialog(props: { run: async () => toggleProjectGroupPin(currentProjectGroup), }); } + const contextualProject = contextualProjectRef + ? projects.find( + (project) => + project.environmentId === contextualProjectRef.environmentId && + project.id === contextualProjectRef.projectId, + ) + : undefined; + const umbrellaActions = contextualProject + ? umbrellaMembershipActions([contextualProject], projects) + : { adoptions: [], removals: [] }; + 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 { umbrella, member } of umbrellaActions.removals) { + actionItems.push({ + kind: "action", + value: `action:umbrella-remove:${umbrella.environmentId}:${umbrella.id}`, + searchTerms: ["umbrella", "remove", "leave", "member", "project", umbrella.title], + title: "Remove project from umbrella", + description: `${umbrella.title} · ${umbrellaMemberLabel(member)}`, + icon: , + run: async () => umbrellaEdits.remove(umbrella, member), + }); + } const contextualProjectGroup = currentProjectGroup ?? projectGroups[0] ?? null; if (contextualProjectGroup) { actionItems.push({ diff --git a/apps/web/src/components/DiffPanel.tsx b/apps/web/src/components/DiffPanel.tsx index 38e3151eb7978..604543b29d0be 100644 --- a/apps/web/src/components/DiffPanel.tsx +++ b/apps/web/src/components/DiffPanel.tsx @@ -11,7 +11,9 @@ import { type ReviewBranchCommitsResult, type ScopedThreadRef, type RunId, + type UmbrellaMember, } from "@t3tools/contracts"; +import { scopedThreadKey } from "@t3tools/client-runtime/environment"; import { ArrowRightIcon, CheckIcon, @@ -105,7 +107,13 @@ 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 { buildBaseRefChoices, filterBaseRefChoices } from "../lib/baseRefChoices"; import { createGitDiffFileContentsLoader } from "../lib/diffFileContents"; @@ -122,6 +130,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 +261,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 +271,73 @@ 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"; + // Members are checkouts beside the project root, which a worktree thread does not work in. + const umbrellaMembers = + activeThread && !activeThread.worktreePath + ? (activeProject?.umbrellaMembers ?? NO_UMBRELLA_MEMBERS) + : NO_UMBRELLA_MEMBERS; + 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 +345,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 +355,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 +402,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 +485,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 +510,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 +868,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 +988,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 (

+ {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.tsx b/apps/web/src/components/Sidebar.tsx index e6cdb90d5c86d..bc7089c6adc1e 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -269,6 +269,13 @@ import { type SidebarSweepAction, } from "./sidebar/SidebarThreadRow"; import { SidebarDraftBlock } from "./sidebar/SidebarDraftBlock"; +import { umbrellaMemberLabel } from "@t3tools/client-runtime/state/umbrella"; +import { useUmbrellaMembershipEdits } from "../hooks/useUmbrellaMembershipEdits"; +import { + resolveUmbrellaMenuAction, + umbrellaMembershipActions, + umbrellaMenuItems, +} from "../umbrellaMembership.logic"; import { SidebarProjectFolderHeader, sidebarFolderRowId, @@ -826,6 +833,13 @@ function useSidebarLookups() { ), ), ); + const umbrellaMemberLabelByKey = new Map( + projectGroups.flatMap((group) => + [...group.foldedUmbrellaMembers].map( + ([key, member]) => [key, umbrellaMemberLabel(member)] as const, + ), + ), + ); const projectGroupByScopeKey = new Map( projectGroups.map((project) => [project.projectKey, project] as const), ); @@ -844,6 +858,7 @@ function useSidebarLookups() { providerEntriesByEnvironment, projectByKey, projectDisplayNameByKey, + umbrellaMemberLabelByKey, projectGroupByScopeKey, projectScopeItems, }; @@ -911,9 +926,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 +1275,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve ) => { const api = readLocalApi(); if (!api) return; + const umbrellaActions = umbrellaMembershipActions(group.memberProjects, projects); void (async () => { const clicked = await settlePromise(() => api.contextMenu.show( @@ -1271,6 +1289,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 +1297,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.remove(umbrellaAction.umbrella, umbrellaAction.member); + return; + } switch (clicked.value) { case "new-thread": startThreadInProjectFolder(group); @@ -3450,6 +3478,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 diff --git a/apps/web/src/components/diffs/umbrellaDiffSections.logic.test.ts b/apps/web/src/components/diffs/umbrellaDiffSections.logic.test.ts new file mode 100644 index 0000000000000..17252bea903af --- /dev/null +++ b/apps/web/src/components/diffs/umbrellaDiffSections.logic.test.ts @@ -0,0 +1,84 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { umbrellaDiffSections } from "./umbrellaDiffSections.logic"; + +const clean = { isRepo: true, hasWorkingTreeChanges: false }; +const dirty = { isRepo: true, hasWorkingTreeChanges: true }; +const branchOnly = { + isRepo: true, + hasWorkingTreeChanges: false, + branchChanges: { baseRef: "main", insertions: 3, deletions: 0 }, +}; +const members = [ + { path: "/acme/api", relativePath: "api" }, + { path: "/acme/web", relativePath: "web" }, + { path: "/elsewhere/tools", relativePath: "../elsewhere/tools" }, +]; + +const sectionPaths = (result: ReturnType) => + result.sections.map((section) => section.memberPath); + +describe("umbrellaDiffSections", () => { + it("lists the root repository and only members with working tree or branch changes", () => { + const result = umbrellaDiffSections({ + rootCwd: "/acme", + rootLabel: "acme", + rootIsRepo: true, + members, + statuses: [dirty, clean, branchOnly], + selectedMemberPath: null, + }); + expect(sectionPaths(result)).toEqual([null, "/acme/api", "/elsewhere/tools"]); + expect(result.sections.map((section) => section.label)).toEqual(["acme", "api", "tools"]); + expect(result.selected?.cwd).toBe("/acme"); + }); + + it("keeps the picked member listed after its changes clear", () => { + const result = umbrellaDiffSections({ + rootCwd: "/acme", + rootLabel: "acme", + rootIsRepo: true, + members, + statuses: [clean, clean, null], + selectedMemberPath: "/acme/web", + }); + expect(sectionPaths(result)).toEqual([null, "/acme/web"]); + expect(result.selected?.cwd).toBe("/acme/web"); + }); + + it("falls back to the root when the picked path is no longer a member", () => { + const result = umbrellaDiffSections({ + rootCwd: "/acme", + rootLabel: "acme", + rootIsRepo: true, + members, + statuses: [clean, clean, clean], + selectedMemberPath: "/acme/removed", + }); + expect(sectionPaths(result)).toEqual([null]); + expect(result.selected?.memberPath).toBeNull(); + }); + + it("leaves out a root that is not a repository and still shows a member", () => { + const withChanges = umbrellaDiffSections({ + rootCwd: "/acme", + rootLabel: "acme", + rootIsRepo: false, + members, + statuses: [clean, dirty, null], + selectedMemberPath: null, + }); + expect(sectionPaths(withChanges)).toEqual(["/acme/web"]); + expect(withChanges.selected?.cwd).toBe("/acme/web"); + + const allClean = umbrellaDiffSections({ + rootCwd: "/acme", + rootLabel: "acme", + rootIsRepo: false, + members, + statuses: [clean, { isRepo: false, hasWorkingTreeChanges: true }, null], + selectedMemberPath: null, + }); + expect(sectionPaths(allClean)).toEqual(["/acme/api"]); + }); +}); diff --git a/apps/web/src/components/diffs/umbrellaDiffSections.logic.ts b/apps/web/src/components/diffs/umbrellaDiffSections.logic.ts new file mode 100644 index 0000000000000..d6a7ed78e703d --- /dev/null +++ b/apps/web/src/components/diffs/umbrellaDiffSections.logic.ts @@ -0,0 +1,64 @@ +import type { UmbrellaMember, VcsStatusResult } from "@t3tools/contracts"; +import { umbrellaMemberLabel } from "@t3tools/client-runtime/state/umbrella"; + +export interface UmbrellaDiffSection { + /** The member's path, or null for the umbrella root. */ + readonly memberPath: string | null; + readonly label: string; + readonly cwd: string; +} + +type MemberStatus = Pick; + +function memberHasChanges(status: MemberStatus | null): boolean { + if (status === null || !status.isRepo) return false; + const branch = status.branchChanges; + return ( + status.hasWorkingTreeChanges || + (branch !== undefined && branch.insertions + branch.deletions > 0) + ); +} + +/** + * The git sections a diff panel offers for an umbrella: the root when it is a repository, then + * each member with changes. The picked member stays listed after its changes clear, and a + * root that is not a repository falls back to its first member so a section is always shown. + */ +export function umbrellaDiffSections(input: { + readonly rootCwd: string; + readonly rootLabel: string; + readonly rootIsRepo: boolean; + readonly members: ReadonlyArray>; + readonly statuses: ReadonlyArray; + readonly selectedMemberPath: string | null; +}): { + readonly sections: ReadonlyArray; + readonly selected: UmbrellaDiffSection | null; +} { + const toSection = (member: Pick) => ({ + memberPath: member.path, + label: umbrellaMemberLabel(member), + cwd: member.path, + }); + const memberSections = input.members.flatMap((member, index) => + memberHasChanges(input.statuses[index] ?? null) || member.path === input.selectedMemberPath + ? [toSection(member)] + : [], + ); + const root: UmbrellaDiffSection = { + memberPath: null, + label: input.rootLabel, + cwd: input.rootCwd, + }; + const firstMember = input.members[0]; + const sections = input.rootIsRepo + ? [root, ...memberSections] + : memberSections.length > 0 || firstMember === undefined + ? memberSections + : [toSection(firstMember)]; + const selected = + sections.find((section) => section.memberPath === input.selectedMemberPath) ?? + sections[0] ?? + null; + return { sections, selected }; +} diff --git a/apps/web/src/components/settings/ProjectSettingsPanel.tsx b/apps/web/src/components/settings/ProjectSettingsPanel.tsx index 3f370ce7108d3..c2038d361c7c0 100644 --- a/apps/web/src/components/settings/ProjectSettingsPanel.tsx +++ b/apps/web/src/components/settings/ProjectSettingsPanel.tsx @@ -51,6 +51,7 @@ import { } from "./ProjectFaviconPickerDialog"; import { ProjectActionsSettings } from "./ProjectActionsSettings"; import { ProjectDefaultsSettings } from "./ProjectDefaultsSettings"; +import { ProjectUmbrellaSettings } from "./ProjectUmbrellaSettings"; import { defaultProjectIcon, hasDefaultProjectIcon, @@ -667,6 +668,7 @@ function ProjectDetail({ {checkoutChoices} + value.startsWith("/") || /^[A-Za-z]:[\\/]/.test(value); + +function UmbrellaAdoptForm(props: { + disabled: boolean; + environmentLabel: string; + onAdopt: (path: string) => void; +}) { + const [path, setPath] = useState(""); + return ( +

{ + event.preventDefault(); + const trimmed = path.trim(); + if (!isAbsolutePath(trimmed)) { + toastManager.add({ + type: "warning", + title: "Checkout not added", + description: `Enter an absolute path on ${props.environmentLabel}.`, + }); + return; + } + props.onAdopt(trimmed); + setPath(""); + }} + > + setPath(event.target.value)} + /> + +
+ ); +} + +/** Members, exclusions, and adoption for each project in the group that can hold checkouts. */ +export function ProjectUmbrellaSettings({ group }: { group: SidebarProjectSnapshot }) { + const { environments } = useEnvironments(); + const pendingWrites = useAtomValue(pendingScopedWritesAtom); + const shownEnvironments = applyPendingScopedWrites(environments, pendingWrites); + const edits = useUmbrellaMembershipEdits(); + const umbrellas = group.memberProjects.filter( + (project) => + !project.isScratch && + !group.foldedUmbrellaMembers.has(`${project.environmentId}:${project.id}`), + ); + const writableIds = useEnvironmentsWithScope(umbrellas, AuthSettingsWriteScope); + if (umbrellas.length === 0) return null; + + const rowsFor = (project: SidebarProjectGroupMember) => { + const environment = shownEnvironments.find( + (candidate) => candidate.environmentId === project.environmentId, + ); + const environmentLabel = project.environmentLabel ?? environment?.label ?? "this environment"; + const overrides = environment?.serverConfig?.settings.projectSettingsOverrides[project.id]; + const excluded = overrides?.umbrellaExcludedPaths ?? []; + const disabled = + !writableIds.has(project.environmentId) || + environment?.connection.phase !== "connected" || + !environment.serverConfig; + const prefix = umbrellas.length > 1 ? `${environmentLabel} · ` : ""; + return ( + + {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. 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..a561c3c0595a1 100644 --- a/apps/web/src/components/settings/scheduledTasksSettings.logic.test.ts +++ b/apps/web/src/components/settings/scheduledTasksSettings.logic.test.ts @@ -73,6 +73,7 @@ function group( environmentPresence: "mixed", allRemoteMembersAreDesktopLocal: false, allRemoteMembersAreWsl: false, + foldedUmbrellaMembers: new Map(), 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..bf2054cb8cc30 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,7 @@ const group: SidebarProjectSnapshot = { environmentPresence: "remote-only", allRemoteMembersAreDesktopLocal: false, allRemoteMembersAreWsl: false, + foldedUmbrellaMembers: new Map(), remoteEnvironmentLabels: [server.label, laptop.label], pinned: false, archived: false, @@ -537,6 +539,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..8731a5e164f63 100644 --- a/apps/web/src/components/settings/settingsScope.test.ts +++ b/apps/web/src/components/settings/settingsScope.test.ts @@ -53,6 +53,7 @@ function group( environmentPresence: "mixed", allRemoteMembersAreDesktopLocal: false, allRemoteMembersAreWsl: false, + foldedUmbrellaMembers: new Map(), 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/SidebarThreadRow.tsx b/apps/web/src/components/sidebar/SidebarThreadRow.tsx index d901418db85a5..0a1cdc953af6a 100644 --- a/apps/web/src/components/sidebar/SidebarThreadRow.tsx +++ b/apps/web/src/components/sidebar/SidebarThreadRow.tsx @@ -579,6 +579,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; @@ -1079,6 +1081,12 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP ); + const umbrellaMemberTag = props.umbrellaMemberLabel ? ( + + {props.umbrellaMemberLabel} + + ) : null; + const prBadgeShape = supportsMultiplePullRequests ? resolveThreadPullRequestBadge(thread.pullRequests) : null; @@ -1282,6 +1290,7 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP )} {draftIndicator} {title} + {umbrellaMemberTag} {multiline ? titleLineIcons : null} {pinIndicator} {multiline ? null : terminalStatusIcon} @@ -1474,6 +1483,9 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP className={cn("min-w-0 flex-1 truncate font-normal text-secondary-label text-xs")} > {props.projectDisplayName} + {props.umbrellaMemberLabel ? ( + · {props.umbrellaMemberLabel} + ) : null} ) : ( diff --git a/apps/web/src/hooks/useUmbrellaMembershipEdits.ts b/apps/web/src/hooks/useUmbrellaMembershipEdits.ts new file mode 100644 index 0000000000000..16f6abe473e78 --- /dev/null +++ b/apps/web/src/hooks/useUmbrellaMembershipEdits.ts @@ -0,0 +1,32 @@ +import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell"; +import { + adoptUmbrellaMember, + removeUmbrellaMember, + restoreUmbrellaMember, +} from "@t3tools/client-runtime/state/umbrella"; +import type { ProjectSettingsOverrides, UmbrellaMember } from "@t3tools/contracts"; + +import { useEditProjectOverrides } from "../components/settings/useScopedSettings"; + +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), + })); + return { + adopt: (umbrella: Umbrella, path: string) => + edit(umbrella, (current) => adoptUmbrellaMember(umbrella, current, path)), + remove: (umbrella: Umbrella, member: Pick) => + edit(umbrella, (current) => removeUmbrellaMember(umbrella, current, member)), + restore: (umbrella: Umbrella, path: string) => + edit(umbrella, (current) => restoreUmbrellaMember(umbrella, current, path)), + }; +} diff --git a/apps/web/src/sidebarProjectGrouping.ts b/apps/web/src/sidebarProjectGrouping.ts index 8fb8c4a5a1c6c..9d53fa3eec43e 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,8 @@ export interface SidebarProjectSnapshot extends Project { allRemoteMembersAreWsl: boolean; memberProjects: readonly SidebarProjectGroupMember[]; memberProjectRefs: readonly ScopedProjectRef[]; + /** Projects folded in as umbrella members, by `environmentId:projectId`. */ + foldedUmbrellaMembers: ReadonlyMap; remoteEnvironmentLabels: readonly string[]; pinned: boolean; archived: boolean; @@ -199,6 +202,7 @@ export function buildSidebarProjectSnapshots(input: { allRemoteMembersAreWsl, memberProjects: members, memberProjectRefs: group.memberProjectRefs, + foldedUmbrellaMembers: group.umbrellaMembers, 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..fd64b184fe926 --- /dev/null +++ b/apps/web/src/umbrellaMembership.logic.test.ts @@ -0,0 +1,103 @@ +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, + umbrellaMembershipActions, + umbrellaMenuItems, +} from "./umbrellaMembership.logic"; + +const desktop = EnvironmentId.make("desktop"); +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); + 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); + 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); + 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).adoptions, + removals: umbrellaMembershipActions([api, web], projects).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); + expect(umbrellaMenuItems(actions)).toEqual([ + { id: "umbrella-remove:0", label: "Remove from umbrella", detail: "acme" }, + ]); + expect(resolveUmbrellaMenuAction(actions, "umbrella-remove:0")?.kind).toBe("remove"); + }); +}); diff --git a/apps/web/src/umbrellaMembership.logic.ts b/apps/web/src/umbrellaMembership.logic.ts new file mode 100644 index 0000000000000..9361900b9ddc2 --- /dev/null +++ b/apps/web/src/umbrellaMembership.logic.ts @@ -0,0 +1,106 @@ +import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell"; +import { + findUmbrellaMembership, + umbrellaAdoptionTargets, + umbrellaMemberLabel, +} from "@t3tools/client-runtime/state/umbrella"; +import type { ContextMenuItem, UmbrellaMember } from "@t3tools/contracts"; + +export interface UmbrellaAdoption { + readonly umbrella: TProject; + readonly path: string; +} + +export interface UmbrellaRemoval { + readonly umbrella: TProject; + readonly member: UmbrellaMember; +} + +/** + * 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, +): { + 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); + if (membership !== null) { + const { umbrella, member } = membership; + removals.set(`${umbrella.environmentId}:${umbrella.id}\0${member.path}`, membership); + 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`, + label: "Remove 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; +} diff --git a/docs/user/project-settings.md b/docs/user/project-settings.md index 899640ad23590..8d12cd5b16b75 100644 --- a/docs/user/project-settings.md +++ b/docs/user/project-settings.md @@ -64,6 +64,29 @@ 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. Repositories +up to three folders below it become its members; hidden folders, `node_modules`, linked +worktrees, and submodules are skipped. A project with at least one member is an umbrella, with +nothing to turn on, and new repositories in the folder show up within a few minutes. + +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. 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's sidebar row: the same folder on +the umbrella's machine, or the same repository on any connected machine. Their threads name the +member they belong to. Use **Add to umbrella** and **Remove from umbrella** from a project +folder's menu in the sidebar or from the command palette. To add a checkout stored elsewhere on +the same machine, or to remove or restore a member, open **Settings → Projects →** your project +**→ Umbrella checkouts**. + +Worktree mode checks out only the folder's own repository, without its members, so use local mode +for work that spans members. + ## Worktree branch names In **Settings → Worktrees → Worktree branch naming**, choose a static prefix, From 58cefc1b69a1973e31d73d58d05db45448e49718 Mon Sep 17 00:00:00 2001 From: Na0s Date: Mon, 16 Nov 2026 17:41:24 -0500 Subject: [PATCH 05/59] fix: umbrella projects are opt-in and isolate member checkpoints Discovered checkouts now wait for the user to turn the umbrella on (from project settings or a diff panel prompt that lists them first); adopting a checkout turns it on. Restores validate refs first, skip members that already match, and report every failing member; deletes reach every member; an outer repository capture failure fails the checkpoint again. Member patches prefix rename headers, index rebuilds are serialized and scoped per umbrella root, roots inside another repository are refused, vendored folders are not scanned, only enabled umbrellas rescan, and shell refreshes skip unrelated changes. An unlinked member pull request stays dismissed, and removing a clone from another machine only ungroups it. Co-Authored-By: Claude Opus 5.5 --- .../src/checkpointing/CheckpointStore.test.ts | 125 ++++++++- .../src/checkpointing/CheckpointStore.ts | 142 +++++++++-- .../src/orchestration-v2/Orchestrator.ts | 15 +- .../src/orchestration-v2/ShellStream.test.ts | 41 --- .../src/orchestration-v2/ShellStream.ts | 33 --- .../ThreadPullRequestService.test.ts | 43 +++- .../ThreadPullRequestService.ts | 25 +- .../src/orchestration-v2/runtimeLayer.test.ts | 24 ++ .../src/project/ProjectEnrichmentService.ts | 45 +++- apps/server/src/project/ProjectService.ts | 4 +- .../src/project/UmbrellaMembership.test.ts | 172 ++++++++++--- apps/server/src/project/UmbrellaMembership.ts | 241 ++++++++++++------ apps/server/src/project/umbrellaDiscovery.ts | 12 +- apps/server/src/review/ReviewService.test.ts | 5 +- apps/server/src/vcs/GitVcsDriver.ts | 13 +- .../src/vcs/UmbrellaMemberIndex.test.ts | 24 ++ apps/server/src/vcs/UmbrellaMemberIndex.ts | 17 +- apps/server/src/workspace/KnownWorkspaces.ts | 5 +- apps/server/src/ws.ts | 138 ++++++---- apps/web/src/components/CommandPalette.tsx | 5 +- .../src/components/DiffPanel.browser.test.tsx | 24 +- apps/web/src/components/DiffPanel.tsx | 24 ++ apps/web/src/components/Sidebar.tsx | 2 +- .../settings/ProjectUmbrellaSettings.tsx | 46 +++- .../src/hooks/useUmbrellaMembershipEdits.ts | 43 +++- apps/web/src/umbrellaMembership.logic.test.ts | 19 ++ apps/web/src/umbrellaMembership.logic.ts | 20 +- docs/user/project-settings.md | 26 +- .../src/state/shellReducer.test.ts | 13 +- .../client-runtime/src/state/shellReducer.ts | 41 ++- .../client-runtime/src/state/umbrella.test.ts | 20 +- packages/client-runtime/src/state/umbrella.ts | 60 +++-- .../contracts/src/orchestrationProject.ts | 4 + packages/contracts/src/settings.ts | 3 + 34 files changed, 1111 insertions(+), 363 deletions(-) create mode 100644 apps/server/src/vcs/UmbrellaMemberIndex.test.ts diff --git a/apps/server/src/checkpointing/CheckpointStore.test.ts b/apps/server/src/checkpointing/CheckpointStore.test.ts index 1755519393879..23c5d97e90363 100644 --- a/apps/server/src/checkpointing/CheckpointStore.test.ts +++ b/apps/server/src/checkpointing/CheckpointStore.test.ts @@ -5,7 +5,7 @@ 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"; @@ -730,6 +730,7 @@ it.layer(layerTest)("CheckpointStore.layer", (it) => { 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 = { @@ -745,6 +746,10 @@ it.layer(layerTest)("CheckpointStore.layer", (it) => { 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, @@ -755,11 +760,21 @@ it.layer(layerTest)("CheckpointStore.layer", (it) => { ignoreWhitespace: false, format: "numstat", }); - expect(parseTurnDiffFilesFromNumstat(numstat).map((file) => file.path)).toEqual([ - "apps/api/new.txt", - "apps/api/README.md", - "README.md", + 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, @@ -785,6 +800,106 @@ it.layer(layerTest)("CheckpointStore.layer", (it) => { }), ); + 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()); diff --git a/apps/server/src/checkpointing/CheckpointStore.ts b/apps/server/src/checkpointing/CheckpointStore.ts index 02c731907e97a..0829082a7ca15 100644 --- a/apps/server/src/checkpointing/CheckpointStore.ts +++ b/apps/server/src/checkpointing/CheckpointStore.ts @@ -1,8 +1,9 @@ -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 Result from "effect/Result"; import { parseTurnDiffFilesFromNumstat } from "./Diffs.ts"; import type { CheckpointStoreError } from "./Errors.ts"; @@ -106,6 +107,18 @@ function routeComponentPaths( 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; @@ -168,9 +181,15 @@ export const make = Effect.gen(function* () { const checkpoints = yield* resolveCheckpoints(input.cwd); return yield* checkpoints.captureCheckpoint(input); } - // A member that cannot be captured drops its ref, so diffs and restores leave it alone. + // 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( - components, + members, (component) => resolveCheckpoints(component.cwd).pipe( Effect.flatMap((checkpoints) => @@ -213,6 +232,35 @@ export const make = Effect.gen(function* () { 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) { @@ -221,21 +269,54 @@ export const make = Effect.gen(function* () { const checkpoints = yield* resolveCheckpoints(input.cwd); return yield* checkpoints.restoreCheckpoint(input); } - let restored = false; - for (const component of components) { - const checkpoints = yield* resolveCheckpoints(component.cwd); - // Falling back to HEAD would discard a member's edits it never checkpointed. - if ( - yield* checkpoints.restoreCheckpoint({ - cwd: component.cwd, - checkpointRef: input.checkpointRef, - fallbackToHead: component.prefix === "" && input.fallbackToHead === true, - }) - ) { - restored = true; + // 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`); } } - return restored; + 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* ( @@ -243,7 +324,6 @@ export const make = Effect.gen(function* () { input: DiffCheckpointsInput, ) { if ( - component.prefix !== "" && !( (yield* hasRef(component.cwd, input.fromCheckpointRef)) && (yield* hasRef(component.cwd, input.toCheckpointRef)) @@ -336,9 +416,31 @@ export const make = Effect.gen(function* () { "deleteCheckpointRefs", )(function* (input) { const components = yield* componentsOf(input.cwd); - for (const component of components ?? [{ cwd: input.cwd, prefix: "" }]) { - const checkpoints = yield* resolveCheckpoints(component.cwd); - yield* checkpoints.deleteCheckpointRefs({ ...input, cwd: component.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("; ")}.`, + }); } }); 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/ShellStream.test.ts b/apps/server/src/orchestration-v2/ShellStream.test.ts index 88059f52a6497..fbc610235dd01 100644 --- a/apps/server/src/orchestration-v2/ShellStream.test.ts +++ b/apps/server/src/orchestration-v2/ShellStream.test.ts @@ -17,7 +17,6 @@ import * as Stream from "effect/Stream"; import * as TestClock from "effect/testing/TestClock"; import { - selectUmbrellaRefreshProjects, activeShellRowsForSubscriber, bufferShellLiveStream, composeShellStreamWithEnrichment, @@ -696,43 +695,3 @@ describe("skipUnchangedThreadShells", () => { }), ); }); - -describe("selectUmbrellaRefreshProjects", () => { - it("picks scanned projects a settings edit, rescan, or member identity can change", () => { - const member = (path: string) => ({ - path, - relativePath: path.split("/").at(-1)!, - repositoryIdentity: null, - source: "nested" as const, - }); - const project = ( - id: string, - workspaceRoot: string, - umbrellaMembers?: ReadonlyArray>, - ) => ({ - id: ProjectId.make(id), - workspaceRoot, - ...(umbrellaMembers === undefined ? {} : { umbrellaMembers }), - }); - const projects = [ - project("edited", "/edited", []), - project("rescanned", "/rescanned", []), - project("member-identity", "/acme", [member("/acme/api")]), - project("untouched", "/untouched", [member("/untouched/web")]), - project("unscanned", "/unscanned"), - ]; - - const selected = selectUmbrellaRefreshProjects({ - projects, - triggers: [ - { root: null, rescanned: false, projectIds: [ProjectId.make("edited")] }, - { root: "/rescanned", rescanned: true, projectIds: [] }, - { root: "/acme/api", rescanned: false, projectIds: [] }, - { root: "/untouched", rescanned: false, projectIds: [] }, - { root: null, rescanned: false, projectIds: [ProjectId.make("unscanned")] }, - ], - }); - - expect(selected.map((entry) => entry.id)).toEqual(["edited", "rescanned", "member-identity"]); - }); -}); diff --git a/apps/server/src/orchestration-v2/ShellStream.ts b/apps/server/src/orchestration-v2/ShellStream.ts index c2feb74c7c6b2..5ee1005b16830 100644 --- a/apps/server/src/orchestration-v2/ShellStream.ts +++ b/apps/server/src/orchestration-v2/ShellStream.ts @@ -690,39 +690,6 @@ export function dedupeShellEnrichment( }); } -/** - * Scanned projects whose members a batch of changes can alter: settings edits name projects, - * a rescan names a root, and a resolved identity names a member's path. - */ -export function selectUmbrellaRefreshProjects< - P extends Pick, ->(input: { - readonly projects: ReadonlyArray

; - readonly triggers: Iterable<{ - readonly root: string | null; - readonly rescanned: boolean; - readonly projectIds: ReadonlyArray; - }>; -}): ReadonlyArray

{ - const rescannedRoots = new Set(); - const changedRoots = new Set(); - const projectIds = new Set(); - for (const trigger of input.triggers) { - if (trigger.root !== null) { - changedRoots.add(trigger.root); - if (trigger.rescanned) rescannedRoots.add(trigger.root); - } - for (const projectId of trigger.projectIds) projectIds.add(projectId); - } - return input.projects.filter( - (project) => - project.umbrellaMembers !== undefined && - (projectIds.has(project.id) || - rescannedRoots.has(project.workspaceRoot) || - project.umbrellaMembers.some((member) => changedRoots.has(member.path))), - ); -} - export function shellStreamItemFromEnrichmentRefresh(input: { readonly snapshot: OrchestrationV2ShellSnapshot; readonly changes: ReadonlyArray<{ readonly workspaceRoot: string }>; diff --git a/apps/server/src/orchestration-v2/ThreadPullRequestService.test.ts b/apps/server/src/orchestration-v2/ThreadPullRequestService.test.ts index 5ce13b6e6f36b..d0b02270fd6d7 100644 --- a/apps/server/src/orchestration-v2/ThreadPullRequestService.test.ts +++ b/apps/server/src/orchestration-v2/ThreadPullRequestService.test.ts @@ -184,7 +184,22 @@ describe("ThreadPullRequestServiceV2 reads", () => { it.effect("links the branch pull request of each umbrella member a turn edited", () => Effect.gen(function* () { - const thread = threadShell("umbrella-thread"); + // The user unlinked this member's pull request earlier; it stays unlinked and is not looked up. + const thread: OrchestrationV2ThreadShell = { + ...threadShell("umbrella-thread"), + 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", @@ -197,7 +212,15 @@ describe("ThreadPullRequestServiceV2 reads", () => { const member = (relativePath: string) => ({ path: `/clients/acme/${relativePath}`, relativePath, - repositoryIdentity: null, + 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(); @@ -258,7 +281,13 @@ describe("ThreadPullRequestServiceV2 reads", () => { shouldRunOpportunisticWork: Effect.succeed(false), }), Layer.mock(UmbrellaMembership.UmbrellaMembership)({ - membersOf: () => Effect.succeed([member("apps/api"), member("apps/web")]), + stateOf: () => + Effect.succeed({ + members: [member("apps/api"), member("apps/web"), member("apps/linked")], + suggestions: [], + enclosingRepository: null, + }), + umbrellasWithMember: () => [], }), Layer.succeed( SecureRandom.SecureRandom, @@ -273,7 +302,13 @@ describe("ThreadPullRequestServiceV2 reads", () => { yield* Queue.offer(domainEvents, { type: "checkpoint.captured", threadId: thread.id, - payload: { files: [{ path: "apps/api/src/server.ts" }, { path: "README.md" }] }, + 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; diff --git a/apps/server/src/orchestration-v2/ThreadPullRequestService.ts b/apps/server/src/orchestration-v2/ThreadPullRequestService.ts index d363607259459..a414763924e53 100644 --- a/apps/server/src/orchestration-v2/ThreadPullRequestService.ts +++ b/apps/server/src/orchestration-v2/ThreadPullRequestService.ts @@ -32,6 +32,10 @@ import * as RepositoryIdentityResolver from "../project/RepositoryIdentityResolv import * as UmbrellaMembership from "../project/UmbrellaMembership.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"; @@ -427,7 +431,8 @@ export const make = Effect.gen(function* () { ); // A checkpoint lists the umbrella members a turn edited; each one's branch pull request joins - // the thread. Only that turn's members are read, so an unlinked pull request stays unlinked. + // 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; @@ -435,23 +440,37 @@ export const make = Effect.gen(function* () { if (thread === null) return; const project = yield* projectStore.getShell(thread.projectId); if (Option.isNone(project)) return; - const members = (yield* umbrellaMembership.value.membersOf(project.value)) ?? []; + const members = (yield* umbrellaMembership.value.stateOf(project.value))?.members ?? []; const touched = members.filter((member) => files.some((file) => file.path.startsWith(`${member.relativePath}/`)), ); + const links = threadPullRequestsOf(thread); yield* Effect.forEach( touched, (member) => Effect.gen(function* () { const status = yield* git.localStatus({ cwd: member.path }); 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.path, branch: status.refName }, { refresh: true, confirmTerminal: false }, ); if (detected === null || pullRequestPredatesThread(detected, thread.createdAt)) return; const key = pullRequestKeyOf(detected, member.repositoryIdentity); - if (key === null) return; + if (key === null || links.some((link) => threadPullRequestKeysEqual(link, key))) return; const uuid = yield* random.uuidV4(); yield* orchestrator.dispatch({ type: "thread.pull-request.link", diff --git a/apps/server/src/orchestration-v2/runtimeLayer.test.ts b/apps/server/src/orchestration-v2/runtimeLayer.test.ts index 7474965ef64ff..8d964b2f768b7 100644 --- a/apps/server/src/orchestration-v2/runtimeLayer.test.ts +++ b/apps/server/src/orchestration-v2/runtimeLayer.test.ts @@ -4102,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 edbd29d4cf6eb..7e18ae5e77497 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"; @@ -23,8 +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; a new checkout under a project root shows up within this window. -const DEFAULT_NESTED_REPOSITORIES_TTL = Duration.minutes(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; @@ -55,9 +56,10 @@ 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; schedules a scan when stale. */ + /** 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, @@ -176,10 +178,25 @@ export const make = Effect.fn("ProjectEnrichmentService.make")(function* ( } map.set(workspaceRoot, nested); }; + const nestedScannedAt = new Map(); const nestedRepositoriesCache = yield* Cache.makeWith( - (workspaceRoot: string) => discoverNestedRepositories(workspaceRoot), - { capacity: cacheCapacity, timeToLive: () => DEFAULT_NESTED_REPOSITORIES_TTL }, + (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) => @@ -265,11 +282,15 @@ export const make = Effect.fn("ProjectEnrichmentService.make")(function* ( const resolveNestedRepositories = Effect.fn("ProjectEnrichmentService.resolveNestedRepositories")( function* (workspaceRoot: string) { - const nested = yield* Cache.get(nestedRepositoriesCache, workspaceRoot); + const nested = (yield* Cache.has(nestedRepositoriesCache, workspaceRoot)) + ? yield* Cache.refresh(nestedRepositoriesCache, workspaceRoot) + : yield* Cache.get(nestedRepositoriesCache, workspaceRoot); rememberNested(knownNestedRepositories, workspaceRoot, nested); - // Rescans of an unchanged folder would otherwise push a shell frame to every subscriber. - if (sameList(publishedNestedRepositories.get(workspaceRoot), nested)) return; + const published = publishedNestedRepositories.get(workspaceRoot); rememberNested(publishedNestedRepositories, 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, @@ -374,9 +395,12 @@ export const make = Effect.fn("ProjectEnrichmentService.make")(function* ( }); const peekNestedRepositories: ProjectEnrichmentService["Service"]["peekNestedRepositories"] = - Effect.fnUntraced(function* (workspaceRoot) { + Effect.fnUntraced(function* (workspaceRoot, options) { const cached = yield* Cache.getSuccess(nestedRepositoriesCache, workspaceRoot); - if (Option.isNone(cached)) { + if ( + Option.isNone(cached) || + (options?.rescanWhenStale === true && (yield* nestedScanIsStale(workspaceRoot))) + ) { yield* requestLane(nestedRepositoriesLane, workspaceRoot, "nestedRepositories"); } return Option.getOrUndefined(cached) ?? knownNestedRepositories.get(workspaceRoot) ?? null; @@ -403,6 +427,7 @@ export const make = Effect.fn("ProjectEnrichmentService.make")(function* ( lastRepositoryIdentities.delete(workspaceRoot); knownNestedRepositories.delete(workspaceRoot); publishedNestedRepositories.delete(workspaceRoot); + nestedScannedAt.delete(workspaceRoot); }), Cache.invalidate(faviconCache, workspaceRoot), Cache.invalidate(nestedRepositoriesCache, workspaceRoot), diff --git a/apps/server/src/project/ProjectService.ts b/apps/server/src/project/ProjectService.ts index b1617caa3028e..428f2444fbd21 100644 --- a/apps/server/src/project/ProjectService.ts +++ b/apps/server/src/project/ProjectService.ts @@ -37,7 +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 } from "./UmbrellaMembership.ts"; +import { attachUmbrellaMembers, refreshUmbrellaIndex } from "./UmbrellaMembership.ts"; import { makeIsWorktreeContainer } from "./worktreeContainer.ts"; import * as WorkspacePaths from "../workspace/WorkspacePaths.ts"; @@ -453,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); }, @@ -587,6 +588,7 @@ export const make = Effect.gen(function* () { yield* clearProjectSettingsOverrides(projectId); } yield* projectEnrichment.invalidate([existing.value.workspaceRoot]); + yield* refreshUmbrellaIndex; return yield* readCommitted(projectId); }, ); diff --git a/apps/server/src/project/UmbrellaMembership.test.ts b/apps/server/src/project/UmbrellaMembership.test.ts index 23ceb37ad4975..ea93c3765639f 100644 --- a/apps/server/src/project/UmbrellaMembership.test.ts +++ b/apps/server/src/project/UmbrellaMembership.test.ts @@ -1,37 +1,147 @@ import { it } from "@effect/vitest"; +import { ProjectId, type ServerSettings } from "@t3tools/contracts"; +import * as Deferred from "effect/Deferred"; 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 Path from "effect/Path"; -import { expect } from "vite-plus/test"; +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 { resolveUmbrellaMembers } from "./UmbrellaMembership.ts"; +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"; -it.effect("combines discovered and adopted checkouts and drops exclusions", () => - Effect.gen(function* () { - const members = resolveUmbrellaMembers({ - path: yield* Path.Path, - workspaceRoot: "/clients/acme", - nested: ["/clients/acme/api", "/clients/acme/sites/web", "/clients/acme/legacy"], - adopted: ["/work/acme-mobile", "api", "/clients/acme"], - excluded: ["legacy"], - identityOf: (memberPath) => - memberPath.endsWith("api") - ? { - canonicalKey: "github.com/acme/api", - locator: { source: "git-remote", remoteName: "origin", remoteUrl: "x" }, - } - : null, - }); +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( - members.map(({ relativePath, source, repositoryIdentity }) => ({ - relativePath, - source, - identity: repositoryIdentity?.canonicalKey ?? null, - })), - ).toEqual([ - { relativePath: "../../work/acme-mobile", source: "adopted", identity: null }, - { relativePath: "api", source: "nested", identity: "github.com/acme/api" }, - { relativePath: "sites/web", source: "nested", identity: null }, - ]); - }).pipe(Effect.provide(Path.layer)), -); + 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), + ); +}); diff --git a/apps/server/src/project/UmbrellaMembership.ts b/apps/server/src/project/UmbrellaMembership.ts index f85a01d5a399e..3a2b35df22b04 100644 --- a/apps/server/src/project/UmbrellaMembership.ts +++ b/apps/server/src/project/UmbrellaMembership.ts @@ -14,6 +14,7 @@ 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"; @@ -28,24 +29,37 @@ interface UmbrellaProject { readonly workspaceRoot: string; } +export 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 + | 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, ordered by relative path. Relative * settings paths resolve against the root; a checkout found both ways counts as nested. */ -export function resolveUmbrellaMembers(input: { +function resolveUmbrellaMembers(input: { readonly path: Path.Path; readonly workspaceRoot: string; readonly nested: ReadonlyArray; @@ -74,21 +88,50 @@ export function resolveUmbrellaMembers(input: { .toSorted((left, right) => left.relativePath.localeCompare(right.relativePath)); } -const sameSettings = ( - left: ReturnType, - right: ReturnType, -) => +/** + * Members take effect only once the user turns the umbrella on; until then they are suggestions. + * A root inside another repository's work tree cannot be an umbrella: that repository's paths + * are relative to its own top level, not to the umbrella. + */ +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 candidates = resolveUmbrellaMembers({ + path: input.path, + workspaceRoot: input.workspaceRoot, + nested: input.nested, + adopted: input.settings.adopted, + excluded: input.settings.excluded, + identityOf: () => null, + }); + if (candidates.length === 0) return EMPTY_STATE; + return input.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 discovery and identities, never scanning inline; undefined before the root's first scan. */ - readonly membersOf: ( - project: UmbrellaProject, - ) => Effect.Effect | undefined>; - /** Projects whose adopted or excluded checkouts changed in settings. */ + /** From cached scans and identities, never scanning inline; undefined before the root's first scan. */ + readonly stateOf: (project: UmbrellaProject) => Effect.Effect; + /** Umbrella projects with a member checked out at this path. */ + readonly umbrellasWithMember: (memberPath: string) => ReadonlyArray; + /** Recomputes which checkouts git leaves out, after projects move or go away. */ + readonly refreshIndex: Effect.Effect; + /** Projects whose umbrella settings changed. */ readonly subscribeChanges: Effect.Effect< PubSub.Subscription>, never, @@ -115,78 +158,98 @@ export const make = Effect.gen(function* () { Effect.orElseSucceed((): ServerSettingsSchema["projectSettingsOverrides"] => ({})), ); - const resolveFor = ( + // 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, - nested: ReadonlyArray, overrides: ServerSettingsSchema["projectSettingsOverrides"], - identityOf: (memberPath: string) => RepositoryIdentity | null, - ) => - resolveUmbrellaMembers({ + 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, - ...umbrellaSettingsOf(overrides[project.id]), - identityOf, + settings, + enclosingRepository: yield* enclosingRepositoryOf(project.workspaceRoot), }); + }); - const membersOf: UmbrellaMembership["Service"]["membersOf"] = Effect.fnUntraced( - function* (project) { - const nested = yield* enrichment.peekNestedRepositories(project.workspaceRoot); - if (nested === null) return undefined; - const overrides = yield* readSettings; - const { adopted } = umbrellaSettingsOf(overrides[project.id]); - if (nested.length === 0 && adopted.length === 0) return []; - const candidates = resolveFor(project, nested, overrides, () => null); - const identities = new Map( - yield* Effect.forEach(candidates, (member) => - enrichment - .getAvailable(member.path) - .pipe( - Effect.map(({ repositoryIdentity }) => [member.path, repositoryIdentity] as const), - ), - ), - ); - return candidates.map((member) => ({ - ...member, - repositoryIdentity: identities.get(member.path) ?? null, - })); - }, - ); + 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))); - // Git consults the index on every read, so it holds only the members' resolved paths. - const rebuildIndex = Effect.fn("UmbrellaMembership.rebuildIndex")(function* (options: { - readonly scan: boolean; - }) { - const projects = yield* projectStore.listShells().pipe(Effect.orElseSucceed(() => [])); - const overrides = yield* readSettings; - const umbrellas = new Map>(); - yield* Effect.forEach( - projects, - (project) => - Effect.gen(function* () { - const nested = options.scan - ? yield* enrichment.readNestedRepositories(project.workspaceRoot) - : ((yield* enrichment.peekNestedRepositories(project.workspaceRoot)) ?? EMPTY_PATHS); - const members = resolveFor(project, nested, overrides, () => null); - if (members.length === 0) return; - const root = yield* realPath(project.workspaceRoot); - const checkouts = yield* Effect.forEach(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); - }); + 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* (options: { readonly scan: boolean }) { + 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, options.scan ? "read" : "peek"); + 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; @@ -229,7 +292,7 @@ export const make = Effect.gen(function* () { Stream.groupedWithin(64, Duration.millis(250)), Stream.runForEach(() => rebuildIndex({ scan: false })), ), - // Catches projects removed or moved since, which publish no membership change. + // Rescans enabled umbrellas and drops projects removed or moved since. rebuildIndex({ scan: false }).pipe( Effect.repeat(Schedule.spaced(Duration.minutes(5))), Effect.delay(Duration.minutes(5)), @@ -245,14 +308,16 @@ export const make = Effect.gen(function* () { ); return UmbrellaMembership.of({ - membersOf, + stateOf, + umbrellasWithMember: (memberPath) => umbrellasByMemberPath.get(memberPath) ?? [], + refreshIndex: rebuildIndex({ scan: false }), subscribeChanges: PubSub.subscribe(changes), }); }); export const layer = Layer.effect(UmbrellaMembership, make); -/** Adds `umbrellaMembers` once the root has been scanned. Runtimes without the umbrella layer keep plain shells. */ +/** 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

, ) { @@ -261,13 +326,27 @@ export const attachUmbrellaMembers = Effect.fnUntraced(function*

- membership.value - .membersOf(project) - .pipe( - Effect.map((umbrellaMembers) => - umbrellaMembers === undefined ? project : { ...project, umbrellaMembers }, - ), + 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 }, ); }); + +/** 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/umbrellaDiscovery.ts b/apps/server/src/project/umbrellaDiscovery.ts index 689725e2682c2..539e392b1fc73 100644 --- a/apps/server/src/project/umbrellaDiscovery.ts +++ b/apps/server/src/project/umbrellaDiscovery.ts @@ -7,7 +7,15 @@ import * as Effect from "effect/Effect"; const DEFAULT_MAX_DEPTH = 3; // Bounds a scan of a huge non-umbrella folder; a client folder holds far fewer directories. const DEFAULT_MAX_DIRECTORIES = 1_000; -const SKIPPED_DIRECTORY_NAMES = new Set(["node_modules"]); +// 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", +]); export interface NestedRepositoryDiscoveryOptions { readonly maxDepth?: number; @@ -20,7 +28,7 @@ const readDirectoryEntries = (directory: string) => /** * Git checkouts under `root`, at most `maxDepth` 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 folders, `node_modules`, and symlinks are never entered. + * another repository. Hidden, dependency, and vendored folders and symlinks are never entered. */ export const discoverNestedRepositories = Effect.fn("umbrellaDiscovery.discoverNestedRepositories")( function* (root: string, options: NestedRepositoryDiscoveryOptions = {}) { diff --git a/apps/server/src/review/ReviewService.test.ts b/apps/server/src/review/ReviewService.test.ts index 7f0e71045316a..51db626fe04c8 100644 --- a/apps/server/src/review/ReviewService.test.ts +++ b/apps/server/src/review/ReviewService.test.ts @@ -93,7 +93,10 @@ function layer(input: { ? {} : { projectSettingsOverrides: { - [ProjectId.make("project-0")]: { umbrellaAdoptedPaths: [...input.adoptedPaths] }, + [ProjectId.make("project-0")]: { + umbrellaEnabled: true, + umbrellaAdoptedPaths: [...input.adoptedPaths], + }, }, }), }), diff --git a/apps/server/src/vcs/GitVcsDriver.ts b/apps/server/src/vcs/GitVcsDriver.ts index 892d2b3973b55..48fdbf57e31fa 100644 --- a/apps/server/src/vcs/GitVcsDriver.ts +++ b/apps/server/src/vcs/GitVcsDriver.ts @@ -631,6 +631,14 @@ function prefixNumstatPaths(numstat: string, prefix: string): string { 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; @@ -2137,9 +2145,10 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( }); } - return input.pathPrefix && input.format === "numstat" + if (!input.pathPrefix) return result.stdout; + return input.format === "numstat" ? prefixNumstatPaths(result.stdout, input.pathPrefix) - : result.stdout; + : prefixPatchHeaderPaths(result.stdout, input.pathPrefix); }), listAuthoredPaths: Effect.fn("GitVcsDriver.checkpoints.listAuthoredPaths")(function* (input) { 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 index b969acc53bbf4..7179418a86007 100644 --- a/apps/server/src/vcs/UmbrellaMemberIndex.ts +++ b/apps/server/src/vcs/UmbrellaMemberIndex.ts @@ -21,7 +21,7 @@ export interface UmbrellaMemberIndexShape { ) => Effect.Effect; readonly membersOf: (resolvedRoot: string) => ReadonlyArray; readonly hasMembers: () => boolean; - /** Member checkouts strictly inside a work tree, relative to it with `/` separators. */ + /** Members of the umbrella rooted at this work tree that sit inside it, relative with `/` separators. */ readonly memberPathsWithin: (resolvedWorktreeRoot: string) => ReadonlyArray; } @@ -39,27 +39,20 @@ const isStrictlyWithin = (root: string, candidate: string) => { export const makeIndex = (): UmbrellaMemberIndexShape => { let umbrellas = new Map>(); - let memberPaths: ReadonlyArray = []; return { replace: (next) => Effect.sync(() => { umbrellas = new Map( Array.from(next, ([root, members]) => [NodePath.resolve(root), members] as const), ); - memberPaths = [ - ...new Set( - Array.from(umbrellas.values()).flatMap((members) => - members.map((member) => NodePath.resolve(member.path)), - ), - ), - ]; }), membersOf: (resolvedRoot) => umbrellas.get(NodePath.resolve(resolvedRoot)) ?? EMPTY, - hasMembers: () => memberPaths.length > 0, + hasMembers: () => umbrellas.size > 0, memberPathsWithin: (resolvedWorktreeRoot) => { - if (memberPaths.length === 0) return EMPTY; + if (umbrellas.size === 0) return EMPTY; const root = NodePath.resolve(resolvedWorktreeRoot); - return memberPaths + return (umbrellas.get(root) ?? EMPTY) + .map((member) => NodePath.resolve(member.path)) .filter((member) => isStrictlyWithin(root, member)) .map((member) => NodePath.relative(root, member).split(NodePath.sep).join("/")); }, diff --git a/apps/server/src/workspace/KnownWorkspaces.ts b/apps/server/src/workspace/KnownWorkspaces.ts index 5d58c0d3c4dbd..7881db214b4da 100644 --- a/apps/server/src/workspace/KnownWorkspaces.ts +++ b/apps/server/src/workspace/KnownWorkspaces.ts @@ -95,10 +95,11 @@ export const make = Effect.gen(function* () { for (const project of projects) { if (within(yield* resolveRoot(project.workspaceRoot))) return true; } - // Umbrella members adopted from outside the project's folder. + // 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 = - worktreeSettings.projectSettingsOverrides[project.id]?.umbrellaAdoptedPaths ?? []; + overrides?.umbrellaEnabled === true ? (overrides.umbrellaAdoptedPaths ?? []) : []; for (const member of adopted) { if (within(yield* resolveRoot(path.resolve(project.workspaceRoot, member)))) return true; } diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index b35755044a73e..f93fbc1af4e07 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -17,6 +17,7 @@ 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 Result from "effect/Result"; import * as Path from "effect/Path"; import * as Queue from "effect/Queue"; import * as Ref from "effect/Ref"; @@ -27,7 +28,6 @@ import { subscribeChatGptHandoff } from "./provider/CodexChatGptHandoff.ts"; import { AcpRegistryOperationError, CommandId, - type ProjectId, authScopeResponse, AuthAccessStreamError, type AuthAccessStreamEvent, @@ -135,7 +135,6 @@ import { dedupeShellEnrichment, loadOlderSettledThreadsPage, loadShellSnapshotParts, - selectUmbrellaRefreshProjects, shellStreamItemFromEnrichmentRefresh, shellStreamItemFromThreadShell, shellStreamItemsFromInitialSnapshot, @@ -870,6 +869,11 @@ function readClientOwners( ); } +interface UmbrellaRefreshTrigger { + readonly rescannedRoot: string | null; + readonly projectIds: ReadonlyArray; +} + const enrichProjectShells = Effect.fn("ws.orchestrationV2.enrichProjectShells")( (projects: ReadonlyArray) => Effect.flatMap(ProjectEnrichmentService.ProjectEnrichmentService, (projectEnrichment) => @@ -1155,18 +1159,14 @@ export const subscribeOrchestrationV2Shell = Effect.fn("ws.orchestrationV2.subsc shouldPublishShellApplicationEvent(stored, subagentThreadIds); const enrichmentChanges = yield* projectEnrichment.subscribeChanges; - const umbrellaEnrichmentChanges = yield* projectEnrichment.subscribeChanges; - const umbrellaSettingsChanges = yield* Effect.serviceOption( - UmbrellaMembership.UmbrellaMembership, - ).pipe( - Effect.flatMap( - Option.match({ - onNone: () => Effect.succeed(Stream.empty), - onSome: (membership) => - membership.subscribeChanges.pipe(Effect.map(Stream.fromSubscription)), - }), - ), - ); + const umbrellaMembership = yield* Effect.serviceOption(UmbrellaMembership.UmbrellaMembership); + const umbrellaTriggers = Option.isNone(umbrellaMembership) + ? null + : { + membership: umbrellaMembership.value, + enrichment: yield* projectEnrichment.subscribeChanges, + settings: yield* umbrellaMembership.value.subscribeChanges, + }; const loadProjectMetadataSnapshot = Effect.fn("ws.orchestrationV2.loadProjectMetadataSnapshot")( function* (snapshotSequence: number) { const enriched = yield* enrichProjectShells(yield* projects.listShells()); @@ -1323,49 +1323,75 @@ 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 = Stream.merge( - Stream.fromSubscription(umbrellaEnrichmentChanges).pipe( - Stream.map((change) => ({ - root: change.workspaceRoot, - rescanned: change.nestedRepositoriesResolved === true, - projectIds: [] as ReadonlyArray, - })), - ), - umbrellaSettingsChanges.pipe( - Stream.map((projectIds) => ({ root: null, rescanned: false, projectIds })), - ), - ).pipe( - Stream.groupedWithin(64, Duration.millis(50)), - Stream.mapEffect((triggers) => - Effect.gen(function* () { - const affected = selectUmbrellaRefreshProjects({ - projects: yield* UmbrellaMembership.attachUmbrellaMembers(yield* projects.listShells()), - triggers, - }); - if (affected.length === 0) return []; - const changedProjects = yield* Effect.forEach(affected, (project) => - projectEnrichment - .peek(project.workspaceRoot) - .pipe(Effect.map(({ repositoryIdentity }) => ({ ...project, repositoryIdentity }))), + // Members are refreshed as metadata: roots stay out of the identity list, so identities are + // not overwritten. Only rescans with checkouts, member identities, and settings edits count. + const umbrellaRefreshes = + umbrellaTriggers === null + ? Stream.empty + : Stream.merge( + Stream.fromSubscription(umbrellaTriggers.enrichment).pipe( + Stream.filterMap((change): Result.Result => { + if (change.nestedRepositoriesResolved === true) { + return Result.succeed({ rescannedRoot: change.workspaceRoot, projectIds: [] }); + } + const projectIds = change.repositoryIdentityResolved + ? umbrellaTriggers.membership.umbrellasWithMember(change.workspaceRoot) + : []; + return projectIds.length === 0 + ? Result.failVoid + : Result.succeed({ rescannedRoot: null, projectIds }); + }), + ), + Stream.fromSubscription(umbrellaTriggers.settings).pipe( + Stream.map((projectIds): UmbrellaRefreshTrigger => ({ + rescannedRoot: null, + projectIds, + })), + ), + ).pipe( + Stream.groupedWithin(64, Duration.millis(50)), + Stream.mapEffect((triggers) => + Effect.gen(function* () { + const projectIds = new Set( + triggers.flatMap((trigger) => trigger.projectIds), + ); + const rescannedRoots = new Set( + triggers.flatMap((trigger) => + trigger.rescannedRoot === null ? [] : [trigger.rescannedRoot], + ), + ); + const affected = (yield* projects.listShells()).filter( + (project) => + projectIds.has(project.id) || rescannedRoots.has(project.workspaceRoot), + ); + 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), ); - 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. diff --git a/apps/web/src/components/CommandPalette.tsx b/apps/web/src/components/CommandPalette.tsx index 49ca5d14f0423..7e09edce019a2 100644 --- a/apps/web/src/components/CommandPalette.tsx +++ b/apps/web/src/components/CommandPalette.tsx @@ -1773,7 +1773,8 @@ function OpenCommandPaletteDialog(props: { run: async () => umbrellaEdits.adopt(umbrella, path), }); } - for (const { umbrella, member } of umbrellaActions.removals) { + for (const removal of umbrellaActions.removals) { + const { umbrella, member } = removal; actionItems.push({ kind: "action", value: `action:umbrella-remove:${umbrella.environmentId}:${umbrella.id}`, @@ -1781,7 +1782,7 @@ function OpenCommandPaletteDialog(props: { title: "Remove project from umbrella", description: `${umbrella.title} · ${umbrellaMemberLabel(member)}`, icon: , - run: async () => umbrellaEdits.remove(umbrella, member), + run: async () => umbrellaEdits.leave(removal), }); } const contextualProjectGroup = currentProjectGroup ?? projectGroups[0] ?? null; diff --git a/apps/web/src/components/DiffPanel.browser.test.tsx b/apps/web/src/components/DiffPanel.browser.test.tsx index e10bd823889cc..211378af8c9b1 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 }), diff --git a/apps/web/src/components/DiffPanel.tsx b/apps/web/src/components/DiffPanel.tsx index 604543b29d0be..ffadb2862818c 100644 --- a/apps/web/src/components/DiffPanel.tsx +++ b/apps/web/src/components/DiffPanel.tsx @@ -114,6 +114,7 @@ import { 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"; @@ -291,6 +292,12 @@ export default function DiffPanel({ activeThread && !activeThread.worktreePath ? (activeProject?.umbrellaMembers ?? NO_UMBRELLA_MEMBERS) : 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 umbrellaEdits = useUmbrellaMembershipEdits(); const umbrellaMemberStatuses = useAtomValue( visible && activeThread && umbrellaMembers.length > 0 ? umbrellaMemberStatusesAtom( @@ -1362,6 +1369,23 @@ export default function DiffPanel({ return ( + {activeProject && umbrellaSuggestions.length > 0 ? ( +

+ + {umbrellaSuggestions.length === 1 + ? "Found a repository in this folder." + : `Found ${umbrellaSuggestions.length} repositories in this folder.`} + + +
+ ) : null} {!activeThread ? (
Select a thread to inspect turn diffs. diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index bc7089c6adc1e..755f638ebcbea 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -1303,7 +1303,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve return; } if (umbrellaAction?.kind === "remove") { - umbrellaEdits.remove(umbrellaAction.umbrella, umbrellaAction.member); + umbrellaEdits.leave(umbrellaAction); return; } switch (clicked.value) { diff --git a/apps/web/src/components/settings/ProjectUmbrellaSettings.tsx b/apps/web/src/components/settings/ProjectUmbrellaSettings.tsx index 8246be5186327..f0a7bbe953552 100644 --- a/apps/web/src/components/settings/ProjectUmbrellaSettings.tsx +++ b/apps/web/src/components/settings/ProjectUmbrellaSettings.tsx @@ -12,6 +12,7 @@ import { useEnvironmentsWithScope } from "../../state/session"; import { Badge } from "../ui/badge"; import { Button } from "../ui/button"; import { Input } from "../ui/input"; +import { Switch } from "../ui/switch"; import { toastManager } from "../ui/toast"; import { applyPendingScopedWrites, pendingScopedWritesAtom } from "./scopedSettings"; import { SettingsRow, SettingsSection } from "./settingsLayout"; @@ -78,14 +79,55 @@ export function ProjectUmbrellaSettings({ group }: { group: SidebarProjectSnapsh ); const environmentLabel = project.environmentLabel ?? environment?.label ?? "this environment"; const overrides = environment?.serverConfig?.settings.projectSettingsOverrides[project.id]; + const enabled = overrides?.umbrellaEnabled === true; const excluded = overrides?.umbrellaExcludedPaths ?? []; + const suggestions = project.umbrellaSuggestions ?? []; const disabled = !writableIds.has(project.environmentId) || environment?.connection.phase !== "connected" || !environment.serverConfig; 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 ? (

- Git checkouts this project spans. Their projects' threads group under it, and the diff panel - shows each checkout's changes. + 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/hooks/useUmbrellaMembershipEdits.ts b/apps/web/src/hooks/useUmbrellaMembershipEdits.ts index 16f6abe473e78..4fea3a205d6dc 100644 --- a/apps/web/src/hooks/useUmbrellaMembershipEdits.ts +++ b/apps/web/src/hooks/useUmbrellaMembershipEdits.ts @@ -1,12 +1,19 @@ import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell"; +import { derivePhysicalProjectKey } from "@t3tools/client-runtime/state/project-grouping"; import { adoptUmbrellaMember, removeUmbrellaMember, restoreUmbrellaMember, + setUmbrellaEnabled, } 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; @@ -21,12 +28,44 @@ export function useUmbrellaMembershipEdits() { ...current, ...change(current), })); + const remove = (umbrella: Umbrella, member: Pick) => + edit(umbrella, (current) => removeUmbrellaMember(umbrella, current, member)); return { + setEnabled: (umbrella: Umbrella, enabled: boolean) => + edit(umbrella, (current) => setUmbrellaEnabled(current, 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) edit(umbrella, (current) => setUmbrellaEnabled(current, true)); + }, adopt: (umbrella: Umbrella, path: string) => edit(umbrella, (current) => adoptUmbrellaMember(umbrella, current, path)), - remove: (umbrella: Umbrella, member: Pick) => - edit(umbrella, (current) => removeUmbrellaMember(umbrella, current, member)), + 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/umbrellaMembership.logic.test.ts b/apps/web/src/umbrellaMembership.logic.test.ts index fd64b184fe926..99af540bd2435 100644 --- a/apps/web/src/umbrellaMembership.logic.test.ts +++ b/apps/web/src/umbrellaMembership.logic.test.ts @@ -4,6 +4,7 @@ import { describe, expect, it } from "vite-plus/test"; import { resolveUmbrellaMenuAction, + umbrellaConfirmationMessage, umbrellaMembershipActions, umbrellaMenuItems, } from "./umbrellaMembership.logic"; @@ -101,3 +102,21 @@ describe("umbrellaMenuItems", () => { 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?", + "Turns record checkpoints in these checkouts, and reverting a turn restores them:", + "• api", + "• acme-site", + ].join("\n"), + ); + }); +}); diff --git a/apps/web/src/umbrellaMembership.logic.ts b/apps/web/src/umbrellaMembership.logic.ts index 9361900b9ddc2..aa59cdb0d5b9b 100644 --- a/apps/web/src/umbrellaMembership.logic.ts +++ b/apps/web/src/umbrellaMembership.logic.ts @@ -14,6 +14,9 @@ export interface UmbrellaAdoption { 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"; } /** @@ -34,7 +37,10 @@ export function umbrellaMembershipActions( const membership = findUmbrellaMembership(project, projects); if (membership !== null) { const { umbrella, member } = membership; - removals.set(`${umbrella.environmentId}:${umbrella.id}\0${member.path}`, 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)) { @@ -104,3 +110,15 @@ export function resolveUmbrellaMenuAction( } return null; } + +/** The confirmation that lists every checkout an umbrella will take in before it is turned on. */ +export function umbrellaConfirmationMessage( + title: string, + checkouts: ReadonlyArray>, +): string { + return [ + `Use ${title} as an umbrella?`, + "Turns record checkpoints in these checkouts, and reverting a turn restores them:", + ...checkouts.map((checkout) => `• ${umbrellaMemberLabel(checkout)}`), + ].join("\n"); +} diff --git a/docs/user/project-settings.md b/docs/user/project-settings.md index 8d12cd5b16b75..b21ab9bef6a2d 100644 --- a/docs/user/project-settings.md +++ b/docs/user/project-settings.md @@ -67,22 +67,30 @@ A project on several machines must have every machine connected to pin or archiv ## 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. Repositories -up to three folders below it become its members; hidden folders, `node_modules`, linked -worktrees, and submodules are skipped. A project with at least one member is an umbrella, with -nothing to turn on, and new repositories in the folder show up within a few minutes. +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 offers **Use as +umbrella**, and **Settings → Projects →** your project **→ Umbrella checkouts** lists them with a +**Use as umbrella** switch. Both show 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. When the -folder is a repository itself, its status, diffs, commits, and checkpoints leave the members out. +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's sidebar row: the same folder on the umbrella's machine, or the same repository on any connected machine. Their threads name the member they belong to. Use **Add to umbrella** and **Remove from umbrella** from a project -folder's menu in the sidebar or from the command palette. To add a checkout stored elsewhere on -the same machine, or to remove or restore a member, open **Settings → Projects →** your project -**→ Umbrella checkouts**. +folder's menu in the sidebar or from the command palette. For a clone on another machine, +**Remove from umbrella** 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 checks out only the folder's own repository, without its members, so use local mode for work that spans members. diff --git a/packages/client-runtime/src/state/shellReducer.test.ts b/packages/client-runtime/src/state/shellReducer.test.ts index 53a082dfca269..6491a3f176545 100644 --- a/packages/client-runtime/src/state/shellReducer.test.ts +++ b/packages/client-runtime/src/state/shellReducer.test.ts @@ -191,12 +191,23 @@ describe("applyShellStreamEvent", () => { }); 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: [] }] }, + { + ...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", () => { diff --git a/packages/client-runtime/src/state/shellReducer.ts b/packages/client-runtime/src/state/shellReducer.ts index 35e653bda5f07..35fc563757b63 100644 --- a/packages/client-runtime/src/state/shellReducer.ts +++ b/packages/client-runtime/src/state/shellReducer.ts @@ -58,6 +58,40 @@ 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, @@ -70,7 +104,7 @@ function retainRepositoryIdentity( return { ...next, ...(keepIdentity ? { repositoryIdentity: previous.repositoryIdentity } : {}), - ...(keepMembers ? { umbrellaMembers: previous.umbrellaMembers } : {}), + ...(keepMembers ? umbrellaFieldsOf(previous) : {}), }; } @@ -103,9 +137,8 @@ export function mergeShellSnapshotProjects( return prior; } const project = - candidate.umbrellaMembers !== undefined && - !sameUmbrellaMembers(prior.umbrellaMembers, candidate.umbrellaMembers) - ? { ...prior, umbrellaMembers: candidate.umbrellaMembers } + 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 diff --git a/packages/client-runtime/src/state/umbrella.test.ts b/packages/client-runtime/src/state/umbrella.test.ts index 00e11381bbd0b..c08831ddc763d 100644 --- a/packages/client-runtime/src/state/umbrella.test.ts +++ b/packages/client-runtime/src/state/umbrella.test.ts @@ -63,13 +63,19 @@ describe("umbrella settings edits", () => { { 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({ umbrellaAdoptedPaths: ["/clients/acme/legacy"], umbrellaExcludedPaths: [] }); + ).toEqual({ + umbrellaEnabled: true, + umbrellaAdoptedPaths: ["/clients/acme/legacy"], + umbrellaExcludedPaths: [], + }); }); }); @@ -85,8 +91,16 @@ describe("umbrella membership", () => { }); const projects = [umbrella, here, laptop, elsewhere]; - expect(findUmbrellaMembership(here, projects)?.umbrella.id).toBe(umbrella.id); - expect(findUmbrellaMembership(laptop, projects)?.member.relativePath).toBe("api"); + expect(findUmbrellaMembership(here, projects)).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)).toMatchObject({ + member: { relativePath: "api" }, + match: "repository", + }); expect(findUmbrellaMembership(elsewhere, projects)).toBeNull(); expect(umbrellaAdoptionTargets(here, projects)).toEqual([]); expect(umbrellaAdoptionTargets(project("site", "/work/site"), projects)).toEqual([umbrella]); diff --git a/packages/client-runtime/src/state/umbrella.ts b/packages/client-runtime/src/state/umbrella.ts index 27a6398c23dd9..1a0157ececec4 100644 --- a/packages/client-runtime/src/state/umbrella.ts +++ b/packages/client-runtime/src/state/umbrella.ts @@ -14,7 +14,7 @@ type UmbrellaProject = Pick< >; type UmbrellaOverrides = Pick< ProjectSettingsOverrides, - "umbrellaAdoptedPaths" | "umbrellaExcludedPaths" + "umbrellaEnabled" | "umbrellaAdoptedPaths" | "umbrellaExcludedPaths" >; /** How a member reads in a list: its path under the umbrella, or its folder name when adopted from outside. */ @@ -48,7 +48,15 @@ function withPaths( }; } -/** Adds a checkout, lifting an exclusion that hid it. */ +/** Turns the umbrella on or off; discovered checkouts wait for this, adopted ones turn it on. */ +export function setUmbrellaEnabled( + overrides: UmbrellaOverrides | undefined, + enabled: boolean, +): UmbrellaOverrides { + return { ...overrides, umbrellaEnabled: enabled }; +} + +/** Adds a checkout, lifting an exclusion that hid it, and turns the umbrella on. */ export function adoptUmbrellaMember( umbrella: Pick, overrides: UmbrellaOverrides | undefined, @@ -56,7 +64,7 @@ export function adoptUmbrellaMember( ): UmbrellaOverrides { const root = umbrella.workspaceRoot; return withPaths( - overrides, + setUmbrellaEnabled(overrides, true), [...without(root, overrides?.umbrellaAdoptedPaths, path), path], without(root, overrides?.umbrellaExcludedPaths, path), ); @@ -91,8 +99,9 @@ export function restoreUmbrellaMember( } /** - * The umbrella a project belongs to as a member: its folder on the umbrella's environment, or - * its repository on any environment, matching how the sidebar folds it. + * 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. */ export function findUmbrellaMembership( project: Pick< @@ -100,28 +109,33 @@ export function findUmbrellaMembership( "environmentId" | "id" | "workspaceRoot" | "repositoryIdentity" >, projects: ReadonlyArray, -): { readonly umbrella: TProject; readonly member: UmbrellaMember } | null { +): { + readonly umbrella: TProject; + readonly member: UmbrellaMember; + readonly match: "folder" | "repository"; +} | null { const projectPath = normalizeProjectPathForComparison(project.workspaceRoot); const repositoryKey = project.repositoryIdentity ? repositoryGroupingKeyOf(project.repositoryIdentity) : null; - for (const umbrella of projects) { - if (umbrella.id === project.id && umbrella.environmentId === project.environmentId) continue; - for (const member of umbrella.umbrellaMembers ?? []) { - if ( - umbrella.environmentId === project.environmentId && - normalizeProjectPathForComparison(member.path) === projectPath - ) { - return { umbrella, member }; - } - if ( - repositoryKey !== null && - member.repositoryIdentity && - repositoryGroupingKeyOf(member.repositoryIdentity) === repositoryKey - ) { - return { umbrella, member }; - } - } + 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 (repositoryKey === null) return null; + 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; } diff --git a/packages/contracts/src/orchestrationProject.ts b/packages/contracts/src/orchestrationProject.ts index 678e63e20b336..08ed3bccf0595 100644 --- a/packages/contracts/src/orchestrationProject.ts +++ b/packages/contracts/src/orchestrationProject.ts @@ -15,6 +15,10 @@ export const OrchestrationProjectShell = Schema.Struct({ 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/settings.ts b/packages/contracts/src/settings.ts index f0bb8bb52f203..2700b06aeaf88 100644 --- a/packages/contracts/src/settings.ts +++ b/packages/contracts/src/settings.ts @@ -1238,6 +1238,8 @@ export const ProjectSettingsOverrides = Schema.Struct({ providerInstances: Schema.optionalKey( Schema.Record(ProviderInstanceId, ProjectProviderInstanceOverride), ), + /** 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. */ @@ -1245,6 +1247,7 @@ export const ProjectSettingsOverrides = Schema.Struct({ } satisfies Record< | ProjectScopedServerSettingKey | "providerInstances" + | "umbrellaEnabled" | "umbrellaAdoptedPaths" | "umbrellaExcludedPaths", unknown From 0fef6af57ccba5c3224cafa7e4b7706ca164dcdc Mon Sep 17 00:00:00 2001 From: Na0s Date: Mon, 16 Nov 2026 18:16:40 -0500 Subject: [PATCH 06/59] fix(web): open the diff panel for an umbrella folder that is not a repository A plain folder holding git checkouts kept the Diff surface disabled because the folder itself is not a repository, which hid both the member tabs and the "Use as umbrella" prompt for the main umbrella layout. Co-Authored-By: Claude Opus 5.5 --- apps/web/src/components/ChatView.tsx | 10 ++++++++-- apps/web/src/components/chat/useRightPanelActions.ts | 6 +++--- 2 files changed, 11 insertions(+), 5 deletions(-) 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/chat/useRightPanelActions.ts b/apps/web/src/components/chat/useRightPanelActions.ts index 7caf0056254a3..832454f4a1f57 100644 --- a/apps/web/src/components/chat/useRightPanelActions.ts +++ b/apps/web/src/components/chat/useRightPanelActions.ts @@ -45,7 +45,7 @@ interface RightPanelActionsInput { readonly isServerThread: boolean; /** A side chat pane; the main view already answers preview bus actions. */ readonly embedded: boolean; - readonly isGitRepo: boolean; + readonly diffAvailable: boolean; readonly browserAvailable: boolean; readonly canOperatePreview: boolean; readonly diffOpen: boolean; @@ -78,7 +78,7 @@ export function useRightPanelActions(input: RightPanelActionsInput) { threadPanelPresentation, isServerThread, embedded, - isGitRepo, + diffAvailable, browserAvailable, canOperatePreview, diffOpen, @@ -128,7 +128,7 @@ export function useRightPanelActions(input: RightPanelActionsInput) { }; const createBrowserSurfaceStable = useStableCallback(createBrowserSurface); const addDiffSurface = () => { - if (!activeThreadRef || !isServerThread || !isGitRepo) return; + if (!activeThreadRef || !diffAvailable) return; useDiffPanelStore.getState().selectGitScope(activeThreadRef, "branch"); useRightPanelStore.getState().open(activeThreadRef, "diff"); onDiffPanelOpen?.(); From 80e592690fe2ae2cbb8df6c77cecce331a016ff3 Mon Sep 17 00:00:00 2001 From: Na0s Date: Mon, 16 Nov 2026 21:06:42 -0500 Subject: [PATCH 07/59] feat(server): build per-thread umbrella worktrees An umbrella thread in worktree mode gets one folder that mirrors the umbrella: the root's own worktree or a plain folder, a worktree of every member on the thread branch, and links to the root's other entries. A manifest beside the folder lets checkpoints, recovery and removal find its repositories, and the server registers these folders at startup. Co-Authored-By: Claude Opus 5.5 --- .../src/checkpointing/CheckpointStore.test.ts | 78 +++ .../src/checkpointing/CheckpointStore.ts | 21 +- apps/server/src/project/UmbrellaMembership.ts | 26 + .../src/project/UmbrellaWorktree.test.ts | 346 ++++++++++ apps/server/src/project/UmbrellaWorktree.ts | 607 ++++++++++++++++++ .../src/project/umbrellaWorktreeLayout.ts | 132 ++++ apps/server/src/vcs/UmbrellaMemberIndex.ts | 26 +- .../src/workspace/recreateBranchWorktree.ts | 82 +++ .../src/workspace/restoreMissingWorktree.ts | 104 +-- packages/shared/package.json | 4 + packages/shared/src/umbrellaWorktree.ts | 29 + 11 files changed, 1374 insertions(+), 81 deletions(-) create mode 100644 apps/server/src/project/UmbrellaWorktree.test.ts create mode 100644 apps/server/src/project/UmbrellaWorktree.ts create mode 100644 apps/server/src/project/umbrellaWorktreeLayout.ts create mode 100644 apps/server/src/workspace/recreateBranchWorktree.ts create mode 100644 packages/shared/src/umbrellaWorktree.ts diff --git a/apps/server/src/checkpointing/CheckpointStore.test.ts b/apps/server/src/checkpointing/CheckpointStore.test.ts index 23c5d97e90363..dfd47bf4682d7 100644 --- a/apps/server/src/checkpointing/CheckpointStore.test.ts +++ b/apps/server/src/checkpointing/CheckpointStore.test.ts @@ -912,5 +912,83 @@ it.layer(layerTest)("CheckpointStore.layer", (it) => { 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, + rootRepository: true, + 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 0829082a7ca15..c8895c063ba03 100644 --- a/apps/server/src/checkpointing/CheckpointStore.ts +++ b/apps/server/src/checkpointing/CheckpointStore.ts @@ -3,6 +3,7 @@ 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"; @@ -10,6 +11,7 @@ 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; @@ -141,13 +143,30 @@ export const make = Effect.gen(function* () { return (yield* git.detectRepository(cwd)) !== null; }); - const membersOf = (cwd: string) => + 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) { diff --git a/apps/server/src/project/UmbrellaMembership.ts b/apps/server/src/project/UmbrellaMembership.ts index 3a2b35df22b04..c7420f4e5d487 100644 --- a/apps/server/src/project/UmbrellaMembership.ts +++ b/apps/server/src/project/UmbrellaMembership.ts @@ -5,6 +5,7 @@ import type { 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"; @@ -18,11 +19,14 @@ 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; @@ -281,8 +285,30 @@ export const make = Effect.gen(function* () { 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({ scan: true }); yield* Effect.all( [ diff --git a/apps/server/src/project/UmbrellaWorktree.test.ts b/apps/server/src/project/UmbrellaWorktree.test.ts new file mode 100644 index 0000000000000..072ecdd9d27d2 --- /dev/null +++ b/apps/server/src/project/UmbrellaWorktree.test.ts @@ -0,0 +1,346 @@ +// @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 ServerSettings from "../serverSettings.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(ServerSettings.ServerSettingsService.layerTest()), + 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"]); + }); + +/** A plain or Git umbrella folder holding two member repositories and a shared notes folder. */ +const makeUmbrella = (rootRepository: boolean) => + 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-" }), + ); + if (rootRepository) { + 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"); + yield* fileSystem.writeFileString(NodePath.join(root, "clients", "contacts.md"), "contacts\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.each([false, true])( + "mirrors the umbrella in one thread folder when the root is a repository: %s", + (rootRepository) => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const umbrella = yield* makeUmbrella(rootRepository); + const worktrees = yield* makeUmbrellaWorktrees; + const created = yield* worktrees.create({ + umbrellaRoot: umbrella.root, + members: umbrella.members, + baseRef: rootRepository ? "main" : "HEAD", + 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); + assert.strictEqual(created.rootRepository, rootRepository); + + // 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"], + ...(rootRepository ? [[umbrella.root, ""] as const] : []), + ] 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"); + } + + const contacts = NodePath.join(folder, "clients", "contacts.md"); + if (rootRepository) { + // The root's own checkout supplies its files; untracked siblings are not linked. + assert.isFalse(yield* fileSystem.exists(NodePath.join(folder, "copy"))); + assert.isTrue(yield* fileSystem.exists(NodePath.join(folder, ".gitignore"))); + } else { + assert.strictEqual( + yield* fileSystem.readLink(NodePath.join(folder, "copy")), + NodePath.join(umbrella.root, "copy"), + ); + assert.strictEqual( + yield* fileSystem.readLink(contacts), + contacts.replace(folder, umbrella.root), + ); + assert.isFalse(yield* fileSystem.exists(NodePath.join(folder, ".git"))); + } + + 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), + ]) { + if (repository === umbrella.root && !rootRepository) continue; + 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(false); + 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"))); + assert.strictEqual( + yield* fileSystem.readLink(NodePath.join(folder, "copy")), + NodePath.join(umbrella.root, "copy"), + ); + + // One member removed by hand comes back alone; a folder the agent unlinked stays unlinked. + yield* fileSystem.remove(NodePath.join(folder, "copy")); + 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* fileSystem.exists(NodePath.join(folder, "copy"))); + + 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(true); + 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({ + worktreePath: 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 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..92007e565bbfa --- /dev/null +++ b/apps/server/src/project/UmbrellaWorktree.ts @@ -0,0 +1,607 @@ +// @effect-diagnostics nodeBuiltinImport:off +import * as NodeCrypto from "node:crypto"; + +import type { UmbrellaMember, WorktreeSubmodules } from "@t3tools/contracts"; +import * as HostProcess from "@t3tools/shared/HostProcess"; +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 Option from "effect/Option"; +import * as Path from "effect/Path"; +import type * as PlatformError from "effect/PlatformError"; + +import * as ServerConfig from "../config.ts"; +import * as GitWorkflowService from "../git/GitWorkflowService.ts"; +import * as ServerSettings from "../serverSettings.ts"; +import { removeEmptyDirectory } from "../vcs/removeEmptyDirectory.ts"; +import { UmbrellaMemberIndex } from "../vcs/UmbrellaMemberIndex.ts"; +import { resolveWorktreesDirectory } from "../worktreesDirectory.ts"; +import { recreateBranchWorktree } from "../workspace/recreateBranchWorktree.ts"; +import { + encodeUmbrellaWorktreeManifest, + joinUmbrellaRelative, + readUmbrellaWorktree, + registerUmbrellaWorktree, + UmbrellaWorktreeError, + type UmbrellaWorktreeLayout, + type UmbrellaWorktreeRepository, + umbrellaWorktreeManifestPath, + umbrellaWorktreeRepositories, +} from "./umbrellaWorktreeLayout.ts"; + +export 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 serverConfig = yield* ServerConfig.ServerConfig; + const serverSettings = yield* ServerSettings.ServerSettingsService; + 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 isInside = (parent: string, child: string) => { + const relative = path.relative(parent, child); + return ( + relative === "" || + (relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative)) + ); + }; + const isLink = (target: string) => + fileSystem.readLink(target).pipe( + Effect.as(true), + Effect.orElseSucceed(() => false), + ); + const present = (target: string) => + Effect.zipWith( + fileSystem.exists(target).pipe(Effect.orElseSucceed(() => false)), + isLink(target), + (exists, link) => exists || link, + ); + + /** 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 }), + ); + }); + + /** + * Links each entry of the plain umbrella root that is neither a member nor holds one, walking + * into folders that hold members. Existing entries are kept, so a recovery only fills gaps. + */ + const linkSiblings = Effect.fn("UmbrellaWorktree.linkSiblings")(function* ( + layout: UmbrellaWorktreeLayout, + ) { + const memberPaths = new Set(layout.members.map((member) => member.path)); + const holdsMember = (relativePath: string) => + layout.members.some((member) => member.path.startsWith(`${relativePath}/`)); + const visit = Effect.fnUntraced(function* ( + relativeDirectory: string, + ): Effect.fn.Return { + const entries = yield* fileSystem + .readDirectory(joinUmbrellaRelative(path, layout.umbrellaRoot, relativeDirectory)) + .pipe(Effect.orElseSucceed((): string[] => [])); + for (const name of entries.toSorted()) { + const relativePath = relativeDirectory === "" ? name : `${relativeDirectory}/${name}`; + if (memberPaths.has(relativePath)) continue; + const source = joinUmbrellaRelative(path, layout.umbrellaRoot, relativePath); + const target = joinUmbrellaRelative(path, layout.path, relativePath); + // A worktree folder set inside the umbrella would otherwise link to itself. + if (isInside(source, layout.path)) continue; + if (holdsMember(relativePath)) { + yield* fileSystem.makeDirectory(target, { recursive: true }); + yield* visit(relativePath); + continue; + } + if (yield* present(target)) continue; + yield* fileSystem.symlink(source, target).pipe( + Effect.catch((cause) => + Effect.logWarning("could not link an umbrella entry into its worktree", { + source, + target, + cause, + }), + ), + ); + } + }); + yield* visit(""); + }); + + /** A plain folder's own entries are links and folders this module made; files are the agent's. */ + const removePlainFolder = Effect.fn("UmbrellaWorktree.removePlainFolder")(function* ( + folder: string, + force: boolean, + ) { + const visit = Effect.fnUntraced(function* ( + target: string, + ): Effect.fn.Return { + if (yield* isLink(target)) { + yield* fileSystem + .remove(target) + .pipe( + Effect.mapError((cause) => + fail("UmbrellaWorktree.remove", `Could not remove ${target}.`, cause), + ), + ); + return true; + } + const info = yield* fileSystem.stat(target).pipe(Effect.option); + if (Option.isNone(info)) return true; + if (info.value.type !== "Directory") { + if (!force) return false; + yield* fileSystem + .remove(target) + .pipe( + Effect.mapError((cause) => + fail("UmbrellaWorktree.remove", `Could not remove ${target}.`, cause), + ), + ); + return true; + } + const entries = yield* fileSystem + .readDirectory(target) + .pipe(Effect.orElseSucceed((): string[] => [])); + let empty = true; + for (const name of entries) { + if (!(yield* visit(path.join(target, name)))) empty = false; + } + if (!empty) return false; + // Files written since the listing keep the folder. + return yield* removeEmptyDirectory(target).pipe( + Effect.mapError((cause) => + fail("UmbrellaWorktree.remove", `Could not remove ${target}.`, cause), + ), + ); + }); + if (!(yield* visit(folder))) { + return yield* fail( + "UmbrellaWorktree.remove", + `${folder} holds files that are not part of any repository; remove it with force to delete them.`, + ); + } + }); + + const threadFolderFor = Effect.fn("UmbrellaWorktree.threadFolderFor")(function* ( + umbrellaRoot: string, + branch: string, + ) { + const settings = yield* serverSettings.getSettings.pipe( + Effect.orElseSucceed(() => ({ worktreesDirectory: "" })), + ); + const parent = resolveWorktreesDirectory( + settings.worktreesDirectory, + serverConfig.worktreesDir, + path, + yield* HostProcess.HomeDirectory, + ); + if (parent === null) { + return yield* fail( + "UmbrellaWorktree.create", + `The worktree location "${settings.worktreesDirectory}" must be an absolute folder on this machine, not a drive root. Change it in Settings → Worktrees.`, + ); + } + // Named as Git worktrees are: by umbrella, then a short branch prefix and a stable hash. + const root = yield* fileSystem + .realPath(umbrellaRoot) + .pipe(Effect.orElseSucceed(() => path.resolve(umbrellaRoot))); + const hash = NodeCrypto.createHash("sha256").update(`${root}\0${branch}`).digest("hex"); + let prefix = ""; + for (const character of branch.replace(/\//g, "-")) { + if (Buffer.byteLength(prefix + character) > 23) break; + prefix += character; + } + const basePath = path.join(parent, path.basename(root), `${prefix}-${hash.slice(0, 16)}`); + let candidate = basePath; + for ( + let suffix = 2; + (yield* present(candidate)) || + (yield* present(umbrellaWorktreeManifestPath(path, candidate))); + suffix++ + ) { + candidate = `${basePath}-${suffix}`; + } + return candidate; + }); + + const create = Effect.fn("UmbrellaWorktree.create")(function* ( + input: CreateUmbrellaWorktreeInput, + ) { + const umbrellaRoot = path.resolve(input.umbrellaRoot); + const rootRepository = + (yield* git.repositoryRoot(umbrellaRoot).pipe(Effect.orElseSucceed(() => null))) !== null; + const memberPaths = umbrellaWorktreeMemberPaths( + input.members.map((member) => member.relativePath), + ); + const sources = [ + ...(rootRepository ? [umbrellaRoot] : []), + ...input.members.map((member) => member.path), + ]; + if (sources.length === 0) { + return yield* fail("UmbrellaWorktree.create", "This umbrella has no repositories."); + } + 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 && !rootRepository) { + yield* fileSystem.remove(folder, { recursive: true }).pipe(Effect.ignore); + } + 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* () { + if (rootRepository) { + 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 }); + }), + }, + }, + ); + folder = worktree.worktree.path; + if (!created.some((piece) => piece.path === folder)) { + created.push({ cwd: umbrellaRoot, path: folder }); + } + } else { + folder = yield* threadFolderFor(umbrellaRoot, branch); + yield* fileSystem.makeDirectory(folder, { recursive: true }); + } + const threadFolder = folder; + const layout: UmbrellaWorktreeLayout = { + path: threadFolder, + umbrellaRoot, + rootRepository, + 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 }, + ); + if (!rootRepository) yield* linkSiblings(layout); + // Members' worktrees exist now, so their real paths register. + yield* local(registerUmbrellaWorktree(layout)); + return { path: threadFolder, branch, rootRepository }; + }); + + 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 repositories = umbrellaWorktreeRepositories(path, layout); + // Members first: removing the root's worktree would delete the members inside it. + const members = repositories + .filter((repository) => repository.relativePath !== "") + .toSorted((left, right) => right.relativePath.length - left.relativePath.length); + // Untraced: the removal's span covers each repository. + const removeRepository = Effect.fnUntraced( + function* (repository: UmbrellaWorktreeRepository) { + if (yield* present(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))}`, + ); + }), + ), + ), + ); + for (const member of members) yield* removeRepository(member); + if (failures.length > 0) { + return yield* fail( + "UmbrellaWorktree.remove", + `Could not remove the worktree of ${failures.join("; ")}.`, + ); + } + const root = repositories.find((repository) => repository.relativePath === ""); + if (root !== undefined) { + yield* removeRepository(root); + } else if (yield* present(layout.path)) { + yield* removePlainFolder(layout.path, input.force); + } + 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), + ); + const folderMissing = !(yield* present(layout.path)); + 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, + }), + ); + } + // Links come back only with the folder; one the agent removed stays removed. + if (!layout.rootRepository && folderMissing) { + yield* fileSystem.makeDirectory(layout.path, { recursive: true }); + yield* linkSiblings(layout); + } + yield* local(registerUmbrellaWorktree(layout)); + return true; + }); + + /** Renames the thread branch in every repository, all to the first repository's resulting name. */ + const renameBranch = Effect.fn("UmbrellaWorktree.renameBranch")(function* (input: { + readonly worktreePath: string; + readonly oldBranch: string; + readonly newBranch: string; + readonly exactName?: boolean; + }) { + const layout = yield* local(readUmbrellaWorktree(input.worktreePath)); + if (layout === null) { + return yield* fail( + "UmbrellaWorktree.renameBranch", + `${input.worktreePath} is not an umbrella worktree.`, + ); + } + const [first, ...rest] = umbrellaWorktreeRepositories(path, layout); + if (first === undefined) return { branch: input.oldBranch }; + const renamed = yield* git.renameBranch({ + cwd: first.cwd, + oldBranch: input.oldBranch, + newBranch: input.newBranch, + ...(input.exactName ? { exactName: true } : {}), + }); + for (const repository of rest) { + 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 { create, remove, restoreMissing, renameBranch }; +}); + +export type UmbrellaWorktrees = Effect.Success; diff --git a/apps/server/src/project/umbrellaWorktreeLayout.ts b/apps/server/src/project/umbrellaWorktreeLayout.ts new file mode 100644 index 0000000000000..19be837b37f6e --- /dev/null +++ b/apps/server/src/project/umbrellaWorktreeLayout.ts @@ -0,0 +1,132 @@ +// A worktree-mode umbrella thread works in one folder that mirrors the umbrella: the root's own +// worktree (or a plain folder), a worktree of every member at its path, and links to the root's +// other entries. 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, + rootRepository: Schema.Boolean, + /** `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, when it is one. */ +export const umbrellaWorktreeRepositories = ( + path: Path.Path, + layout: UmbrellaWorktreeLayout, +): ReadonlyArray => [ + ...(layout.rootRepository + ? [{ 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), +); + +/** 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/vcs/UmbrellaMemberIndex.ts b/apps/server/src/vcs/UmbrellaMemberIndex.ts index 7179418a86007..1117024c1ae90 100644 --- a/apps/server/src/vcs/UmbrellaMemberIndex.ts +++ b/apps/server/src/vcs/UmbrellaMemberIndex.ts @@ -19,6 +19,12 @@ export interface UmbrellaMemberIndexShape { 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. */ @@ -39,6 +45,8 @@ const isStrictlyWithin = (root: string, candidate: string) => { 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(() => { @@ -46,12 +54,20 @@ export const makeIndex = (): UmbrellaMemberIndexShape => { Array.from(next, ([root, members]) => [NodePath.resolve(root), members] as const), ); }), - membersOf: (resolvedRoot) => umbrellas.get(NodePath.resolve(resolvedRoot)) ?? EMPTY, - hasMembers: () => umbrellas.size > 0, + 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) return EMPTY; + if (umbrellas.size === 0 && worktrees.size === 0) return EMPTY; const root = NodePath.resolve(resolvedWorktreeRoot); - return (umbrellas.get(root) ?? EMPTY) + return lookup(root) .map((member) => NodePath.resolve(member.path)) .filter((member) => isStrictlyWithin(root, member)) .map((member) => NodePath.relative(root, member).split(NodePath.sep).join("/")); @@ -65,6 +81,8 @@ export class UmbrellaMemberIndex extends Context.Reference ({ replace: () => Effect.void, + registerWorktree: () => Effect.void, + forgetWorktree: () => Effect.void, membersOf: () => EMPTY, hasMembers: () => false, memberPathsWithin: () => EMPTY, 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..311cd18bf81dd 100644 --- a/apps/server/src/workspace/restoreMissingWorktree.ts +++ b/apps/server/src/workspace/restoreMissingWorktree.ts @@ -10,9 +10,12 @@ 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 { readUmbrellaWorktree } from "../project/umbrellaWorktreeLayout.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 +32,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 +49,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 +94,29 @@ 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* readUmbrellaWorktree(worktreePath).pipe( + Effect.provideService(FileSystem.FileSystem, fileSystem), + Effect.provideService(Path.Path, path), + )) !== 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 +132,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/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; + }); +} From cc53ab12b61bdb143a66ae2234f66050cef89ca4 Mon Sep 17 00:00:00 2001 From: Na0s Date: Mon, 16 Nov 2026 21:12:12 -0500 Subject: [PATCH 08/59] feat(server): launch umbrella threads in an umbrella worktree Worktree mode on an umbrella project, plain folder or repository, builds the umbrella worktree, renames the thread branch in every repository, and removes all of it when setup is cancelled. Recovery of a missing worktree recreates each missing repository from the thread branch. Co-Authored-By: Claude Opus 5.5 --- .../ThreadLaunchService.test.ts | 83 ++++++++ .../orchestration-v2/ThreadLaunchService.ts | 184 +++++++++++++----- apps/server/src/project/UmbrellaWorktree.ts | 9 +- 3 files changed, 227 insertions(+), 49 deletions(-) diff --git a/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts b/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts index c9316bd231fc1..679a02872739c 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,7 @@ interface HarnessOptions { readonly providers?: ReadonlyArray; readonly git?: Partial; readonly isGitRepository?: CheckpointStore.CheckpointStore["Service"]["isGitRepository"]; + readonly umbrellaMembers?: ReadonlyArray; } function makeHarness(options: HarnessOptions = {}) { @@ -255,6 +259,21 @@ 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 + ? Layer.empty + : Layer.mock(UmbrellaMembership.UmbrellaMembership)({ + stateOf: () => + Effect.succeed({ + members: options.umbrellaMembers!, + suggestions: [], + enclosingRepository: null, + }), + umbrellasWithMember: () => [], + }), options.getLaunchSettings === undefined ? Layer.empty : Layer.mock(ServerSettings.ServerSettingsService)({ @@ -3146,6 +3165,70 @@ it.effect.each(["origin/master", ":/initial"])( }), ); +it.effect("checks out every member of a plain umbrella folder into one thread folder", () => + Effect.gen(function* () { + 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, + git: { + repositoryRoot: () => Effect.succeed(null), + currentBranch: () => Effect.succeed("main"), + }, + createWorktree: (input) => + Effect.succeed({ + worktree: { path: input.path!, 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" }; + // A plain umbrella folder is not refused as a non-Git project. + yield* launches.checkWorktreeBase({ projectId, workspaceStrategy: workspace }); + assert.isFalse(yield* launches.isNonGitProject(projectId)); + 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"); + 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" }, + ]); + assert.deepEqual( + harness.createWorktree.mock.calls.map(([input]) => [ + input.cwd, + input.path, + input.newRefName, + ]), + [ + ["/elsewhere/site", `${thread.worktreePath}/_external/site`, "feature"], + ["/repo/api", `${thread.worktreePath}/api`, "feature"], + ], + ); + }).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..ef1b8e42eecd5 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,9 @@ 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 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"; @@ -262,6 +266,16 @@ 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, whether or not its root is a repository. + const umbrellaMembersOf = (project: { + readonly id: ProjectId; + readonly workspaceRoot: string; + }) => + Option.isNone(umbrellaMembership) + ? Effect.succeed([]) + : umbrellaMembership.value.stateOf(project).pipe(Effect.map((state) => state?.members ?? [])); // 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,6 +408,8 @@ const make = Effect.gen(function* () { ], { concurrency: "unbounded" }, ); + // Each member of a plain umbrella folder starts from its own checkout. + if (repositoryRoot === null && (yield* umbrellaMembersOf(project)).length > 0) return; if (repositoryRoot === null) return yield* new ThreadLaunchNotRepositoryError({ projectId: project.id, @@ -444,6 +460,7 @@ const make = Effect.gen(function* () { .getById(projectId) .pipe(Effect.orElseSucceed(() => Option.none())); if (Option.isNone(project)) return false; + if ((yield* umbrellaMembersOf(project.value)).length > 0) return false; // Unlike `git.repositoryRoot`, this fails on a repository Git cannot read, which is not "no repository". return yield* checkpointStore.isGitRepository(project.value.workspaceRoot).pipe( Effect.map((isRepository) => !isRepository), @@ -616,7 +633,58 @@ const make = Effect.gen(function* () { input.workspaceStrategy.type === "existing_worktree" ? input.workspaceStrategy.worktreePath : null; - if (input.workspaceStrategy.type === "worktree") { + const umbrellaMembers = + input.workspaceStrategy.type === "worktree" ? yield* umbrellaMembersOf(project) : []; + if (input.workspaceStrategy.type === "worktree" && umbrellaMembers.length > 0) { + 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 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") { if (runId !== null) { yield* threads .dispatch({ @@ -821,24 +889,31 @@ const make = Effect.gen(function* () { ) { const oldBranch = branch; const worktreeCwd = worktreePath; + const umbrellaWorktree = (yield* umbrellaWorktrees.read(worktreeCwd)) !== null; branchRename = yield* generateBranchNameFor(worktreeCwd, initialMessage).pipe( Effect.flatMap(({ branch: newBranch, exactName }) => - git - .renameBranch({ - cwd: worktreeCwd, - oldBranch, - newBranch, - ...(exactName ? { exactName: true } : {}), - }) - .pipe( - // A cancel must see the renamed branch, or its cleanup deletes the old name. - Effect.tap((renamed) => - Effect.sync(() => { - createdBranch = renamed.branch; - }), - ), - Effect.uninterruptible, + (umbrellaWorktree + ? umbrellaWorktrees.renameBranch({ + worktreePath: worktreeCwd, + oldBranch, + newBranch, + ...(exactName ? { exactName: true } : {}), + }) + : git.renameBranch({ + cwd: worktreeCwd, + oldBranch, + newBranch, + ...(exactName ? { exactName: true } : {}), + }) + ).pipe( + // A cancel must see the renamed branch, or its cleanup deletes the old name. + Effect.tap((renamed) => + Effect.sync(() => { + createdBranch = renamed.branch; + }), ), + Effect.uninterruptible, + ), ), Effect.flatMap((renamed) => Effect.gen(function* () { @@ -1042,41 +1117,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/project/UmbrellaWorktree.ts b/apps/server/src/project/UmbrellaWorktree.ts index 92007e565bbfa..c999437ee1bf7 100644 --- a/apps/server/src/project/UmbrellaWorktree.ts +++ b/apps/server/src/project/UmbrellaWorktree.ts @@ -601,7 +601,14 @@ export const makeUmbrellaWorktrees = Effect.gen(function* () { return renamed; }); - return { create, remove, restoreMissing, renameBranch }; + return { + /** The umbrella worktree at this folder, or null when it is not one. */ + read: (worktreePath: string) => local(readUmbrellaWorktree(worktreePath)), + create, + remove, + restoreMissing, + renameBranch, + }; }); export type UmbrellaWorktrees = Effect.Success; From e105deb46a8d4c38e404a10c1e381d5c5bada802 Mon Sep 17 00:00:00 2001 From: Na0s Date: Mon, 16 Nov 2026 21:15:30 -0500 Subject: [PATCH 09/59] feat(server): remove, restore and hand off umbrella worktrees Deleting a thread's umbrella worktree removes every member's worktree, Edit from here recreates its missing repositories, and the worktree handoff tool builds an umbrella worktree for umbrella projects. Co-Authored-By: Claude Opus 5.5 --- .../server/src/mcp/WorktreeMcpService.test.ts | 54 ++++ apps/server/src/mcp/WorktreeMcpService.ts | 299 ++++++++++++------ .../CheckpointRollbackService.ts | 9 +- apps/server/src/ws.ts | 23 +- 4 files changed, 278 insertions(+), 107 deletions(-) diff --git a/apps/server/src/mcp/WorktreeMcpService.test.ts b/apps/server/src/mcp/WorktreeMcpService.test.ts index 3dc7cc2bcc77a..4e74dadefd2d7 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 = {}) => { @@ -315,6 +319,20 @@ const makeHarness = (options: HarnessOptions = {}) => { } satisfies Partial), NodeServices.layer, NodeCrypto.layer, + Layer.succeed(ServerConfig.ServerConfig, { + worktreesDir: options.worktreesDir ?? "/worktrees", + } as ServerConfig.ServerConfig["Service"]), + options.umbrellaMembers === undefined + ? Layer.empty + : Layer.mock(UmbrellaMembership.UmbrellaMembership)({ + stateOf: () => + Effect.succeed({ + members: options.umbrellaMembers!, + suggestions: [], + enclosingRepository: null, + }), + umbrellasWithMember: () => [], + }), options.existsFails ? FileSystem.layerNoop({ exists: (path) => @@ -399,6 +417,42 @@ describe("t3_worktree_handoff", () => { }); }); + it.effect("hands an umbrella thread off to one folder holding every member", () => + Effect.gen(function* () { + const worktreesDir = yield* (yield* FileSystem.FileSystem).makeTempDirectoryScoped({ + prefix: "handoff-umbrella-", + }); + const harness = makeHarness({ + worktreesDir, + umbrellaMembers: [ + { path: "/project/api", relativePath: "api", repositoryIdentity: null, source: "nested" }, + ], + git: { + repositoryRoot: () => Effect.succeed(null), + 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..04b60183129bb 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 * as ServerConfig from "../config.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 umbrellaMembership = yield* Effect.serviceOption(UmbrellaMembership.UmbrellaMembership); // Serialize handoffs per thread to avoid creating two worktrees and orphaning one. const handoffThreadsInFlight = new Set(); @@ -153,108 +160,45 @@ const make = Effect.gen(function* () { Effect.orDie, ); - const performHandoff = Effect.fn("WorktreeMcpService.performHandoff")(function* ( + const bindWorktree = Effect.fn("WorktreeMcpService.bindWorktree")(function* < + CreateError, + RemoveError, + >( scope: McpThreadInvocationScope, input: WorktreeMcpHandoffInput, + projectId: ProjectId, + 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 }, + CreateError + >; + 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 projection = yield* loadThread(scope); - if (projection.thread.worktreePath !== null) { - return yield* alreadyInWorktree(projection.thread.worktreePath); - } - if (projection.thread.archivedAt !== null) { - return yield* failure( - "invalid_request", - `Thread '${scope.thread.threadId}' is archived and cannot be handed off to a worktree.`, - ); - } - - const project = yield* loadProject(scope, projection.thread.projectId); - const projectCwd = project.workspaceRoot; - - const localStatus = yield* gitWorkflow - .localStatus({ cwd: projectCwd }) - .pipe(asOperationFailed("Unable to read git status")); - if (!localStatus.isRepo) { - return yield* failure( - "invalid_request", - `Project workspace '${projectCwd}' is not a git repository.`, - ); - } - - const localBranchNames = yield* gitWorkflow - .listLocalBranchNames(projectCwd) - .pipe(asOperationFailed("Unable to list branches")); - if (localBranchNames.includes(input.branch)) { - const existingRef = yield* gitWorkflow - .listRefs({ cwd: projectCwd, query: input.branch, refKind: "local" }) - .pipe( - Effect.map((result) => - result.refs.find((ref) => ref.name === input.branch && ref.isRemote !== true), - ), - Effect.orElseSucceed(() => undefined), - ); - const checkoutPath = existingRef?.worktreePath ?? null; - return yield* failure( - "invalid_request", - `Branch '${input.branch}' already exists${ - checkoutPath === null ? "" : ` and is checked out at '${checkoutPath}'` - }. Choose a different branch name, or delete the existing branch${ - checkoutPath === null ? "" : " and its worktree" - } first.`, - ); - } - - let baseRef = input.baseRef; - if (baseRef === undefined) { - if (localStatus.refName === null) { - return yield* failure( - "invalid_request", - "Could not determine the current branch of the project workspace (detached HEAD?). Pass baseRef explicitly.", - ); - } - baseRef = localStatus.refName; - } - - const startFromOrigin = - input.startFromOrigin ?? (yield* readDefaultStartFromOrigin(project.id)); - - let worktreeBaseRef = baseRef; - let baseRefName = baseRef; - let startedFromOrigin = false; - if (startFromOrigin) { - const resolvedRemoteBase = yield* gitWorkflow - .fetchWorktreeBaseCommit({ cwd: projectCwd, refName: baseRef }) - .pipe(asOperationFailed(`Unable to fetch the remote base of '${baseRef}'`)); - if (resolvedRemoteBase !== null) { - worktreeBaseRef = resolvedRemoteBase.commitSha; - baseRefName = `refs/remotes/${resolvedRemoteBase.remoteRefName}`; - startedFromOrigin = true; - } - } - 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 +210,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 +231,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 +285,7 @@ const make = Effect.gen(function* () { setupScript = yield* setupScriptRunner .runForThread({ threadId: scope.thread.threadId, - projectId: projection.thread.projectId, + projectId, projectCwd, worktreePath, project: { @@ -378,7 +312,7 @@ const make = Effect.gen(function* () { const result: WorktreeMcpHandoffResult = { worktreePath, - branch: worktree.worktree.refName, + branch: worktree.branch, baseRef, startedFromOrigin, setupScript, @@ -393,6 +327,159 @@ const make = Effect.gen(function* () { ); }); + const performHandoff = Effect.fn("WorktreeMcpService.performHandoff")(function* ( + scope: McpThreadInvocationScope, + input: WorktreeMcpHandoffInput, + ) { + const alreadyInWorktree = (worktreePath: string) => + failure( + "already_in_worktree", + `Thread '${scope.thread.threadId}' is already attached to worktree '${worktreePath}'.`, + ); + + const projection = yield* loadThread(scope); + if (projection.thread.worktreePath !== null) { + return yield* alreadyInWorktree(projection.thread.worktreePath); + } + if (projection.thread.archivedAt !== null) { + return yield* failure( + "invalid_request", + `Thread '${scope.thread.threadId}' is archived and cannot be handed off to a worktree.`, + ); + } + + const project = yield* loadProject(scope, projection.thread.projectId); + const projectCwd = project.workspaceRoot; + const umbrellaMembers = Option.isNone(umbrellaMembership) + ? [] + : ((yield* umbrellaMembership.value.stateOf(project))?.members ?? []); + if (umbrellaMembers.length > 0) { + return yield* bindWorktree(scope, input, projection.thread.projectId, project, { + baseRef: input.baseRef ?? "HEAD", + 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), + ); + const created = yield* umbrellaWorktrees + .create({ + umbrellaRoot: projectCwd, + members: umbrellaMembers, + baseRef: input.baseRef ?? "HEAD", + startFromOrigin, + branch: input.branch, + flattenOnConflict: false, + submodules, + }) + .pipe(asOperationFailed("Unable to create the umbrella worktree")); + return { path: created.path, branch: created.branch }; + }), + remove: (created) => + umbrellaWorktrees.remove({ + worktreePath: created.path, + force: true, + deleteBranch: created.branch, + }), + }); + } + + const localStatus = yield* gitWorkflow + .localStatus({ cwd: projectCwd }) + .pipe(asOperationFailed("Unable to read git status")); + if (!localStatus.isRepo) { + return yield* failure( + "invalid_request", + `Project workspace '${projectCwd}' is not a git repository.`, + ); + } + + const localBranchNames = yield* gitWorkflow + .listLocalBranchNames(projectCwd) + .pipe(asOperationFailed("Unable to list branches")); + if (localBranchNames.includes(input.branch)) { + const existingRef = yield* gitWorkflow + .listRefs({ cwd: projectCwd, query: input.branch, refKind: "local" }) + .pipe( + Effect.map((result) => + result.refs.find((ref) => ref.name === input.branch && ref.isRemote !== true), + ), + Effect.orElseSucceed(() => undefined), + ); + const checkoutPath = existingRef?.worktreePath ?? null; + return yield* failure( + "invalid_request", + `Branch '${input.branch}' already exists${ + checkoutPath === null ? "" : ` and is checked out at '${checkoutPath}'` + }. Choose a different branch name, or delete the existing branch${ + checkoutPath === null ? "" : " and its worktree" + } first.`, + ); + } + + let baseRef = input.baseRef; + if (baseRef === undefined) { + if (localStatus.refName === null) { + return yield* failure( + "invalid_request", + "Could not determine the current branch of the project workspace (detached HEAD?). Pass baseRef explicitly.", + ); + } + baseRef = localStatus.refName; + } + + const startFromOrigin = + input.startFromOrigin ?? (yield* readDefaultStartFromOrigin(project.id)); + + let worktreeBaseRef = baseRef; + let baseRefName = baseRef; + let startedFromOrigin = false; + if (startFromOrigin) { + const resolvedRemoteBase = yield* gitWorkflow + .fetchWorktreeBaseCommit({ cwd: projectCwd, refName: baseRef }) + .pipe(asOperationFailed(`Unable to fetch the remote base of '${baseRef}'`)); + if (resolvedRemoteBase !== null) { + worktreeBaseRef = resolvedRemoteBase.commitSha; + baseRefName = `refs/remotes/${resolvedRemoteBase.remoteRefName}`; + startedFromOrigin = true; + } + } + + return yield* bindWorktree(scope, input, projection.thread.projectId, 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 handoff: WorktreeMcpService["Service"]["handoff"] = Effect.fn("WorktreeMcpService.handoff")( function* (callerScope, input) { yield* requireCapability(callerScope); @@ -464,4 +551,6 @@ export const layer: Layer.Layer< | GitWorkflowService.GitWorkflowService | ProjectSetupScriptRunner.ProjectSetupScriptRunner | VcsStatusBroadcaster.VcsStatusBroadcaster + | Path.Path + | ServerConfig.ServerConfig > = Layer.effect(WorktreeMcpService, make); diff --git a/apps/server/src/orchestration-v2/CheckpointRollbackService.ts b/apps/server/src/orchestration-v2/CheckpointRollbackService.ts index 8924a3eb9a78b..2076bfa3991ab 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,12 @@ 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) { + const umbrellaWorktree = + worktreePath != null && (yield* umbrellaWorktrees.read(worktreePath)) !== null; + if (umbrellaWorktree && branch != 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: 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/ws.ts b/apps/server/src/ws.ts index f93fbc1af4e07..354d512470615 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -28,6 +28,7 @@ import { subscribeChatGptHandoff } from "./provider/CodexChatGptHandoff.ts"; import { AcpRegistryOperationError, CommandId, + GitCommandError, authScopeResponse, AuthAccessStreamError, type AuthAccessStreamEvent, @@ -195,6 +196,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"; @@ -1607,6 +1609,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; @@ -3269,7 +3273,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(() => From 69dfb4c5dc2e4b37aafcb5337581b644cc60cb6c Mon Sep 17 00:00:00 2001 From: Na0s Date: Mon, 16 Nov 2026 21:17:27 -0500 Subject: [PATCH 10/59] fix(server): treat umbrella worktree folders as the thread's checkouts Member pull request discovery reads the members' worktrees inside the thread folder, settlement skips the branch lookup a plain umbrella folder cannot answer, and a thread's umbrella worktree counts as a known workspace wherever the worktree setting placed it. Co-Authored-By: Claude Opus 5.5 --- .../ThreadPullRequestService.test.ts | 315 ++++++++++-------- .../ThreadPullRequestService.ts | 34 +- .../ThreadSettlementService.ts | 23 +- apps/server/src/review/ReviewService.test.ts | 25 +- apps/server/src/workspace/KnownWorkspaces.ts | 18 + 5 files changed, 264 insertions(+), 151 deletions(-) diff --git a/apps/server/src/orchestration-v2/ThreadPullRequestService.test.ts b/apps/server/src/orchestration-v2/ThreadPullRequestService.test.ts index d0b02270fd6d7..1bc142de783fb 100644 --- a/apps/server/src/orchestration-v2/ThreadPullRequestService.test.ts +++ b/apps/server/src/orchestration-v2/ThreadPullRequestService.test.ts @@ -182,150 +182,179 @@ describe("ThreadPullRequestServiceV2 reads", () => { }), ); - it.effect("links the branch pull request of each umbrella member a turn edited", () => - 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"), - 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, - }), - umbrellasWithMember: () => [], - }), - Layer.succeed( - SecureRandom.SecureRandom, - SecureRandom.make((size) => new Uint8Array(size).fill(1)), - ), - FileSystem.layerNoop({}), - 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(["/clients/acme/apps/api@feature/api"]); - expect(dispatched).toMatchObject([ - { - type: "thread.pull-request.link", + 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, + }), + umbrellasWithMember: () => [], + }), + 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", + rootRepository: false, + 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, - host: "github.com", - repository: "acme/api", - number: 12, - source: "agent", - }, - ]); - }).pipe(Effect.provide(dependencies)); - }), + 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", () => diff --git a/apps/server/src/orchestration-v2/ThreadPullRequestService.ts b/apps/server/src/orchestration-v2/ThreadPullRequestService.ts index a414763924e53..ca889489f122b 100644 --- a/apps/server/src/orchestration-v2/ThreadPullRequestService.ts +++ b/apps/server/src/orchestration-v2/ThreadPullRequestService.ts @@ -30,6 +30,7 @@ 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 { readUmbrellaWorktree } from "../project/umbrellaWorktreeLayout.ts"; import { forkParked } from "../serverActivation.ts"; import { sourceControlDefinitions } from "../sourceControl/sourceControlDefinitions.ts"; import { @@ -441,15 +442,40 @@ export const make = Effect.gen(function* () { const project = yield* projectStore.getShell(thread.projectId); if (Option.isNone(project)) return; const members = (yield* umbrellaMembership.value.stateOf(project.value))?.members ?? []; - const touched = members.filter((member) => - files.some((file) => file.path.startsWith(`${member.relativePath}/`)), + // 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).pipe( + Effect.provideService(FileSystem.FileSystem, fileSystem), + Effect.provideService(Path.Path, path), + ); + 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.path }); + const status = yield* git.localStatus({ cwd: member.cwd }); if (status.refName === null || status.isDefaultRef) return; const repository = sourceControlDefinitions .repositorySelector(member.repositoryIdentity) @@ -465,7 +491,7 @@ export const make = Effect.gen(function* () { return; } const detected = yield* git.branchPullRequest( - { cwd: member.path, branch: status.refName }, + { cwd: member.cwd, branch: status.refName }, { refresh: true, confirmTerminal: false }, ); if (detected === null || pullRequestPredatesThread(detected, thread.createdAt)) return; diff --git a/apps/server/src/orchestration-v2/ThreadSettlementService.ts b/apps/server/src/orchestration-v2/ThreadSettlementService.ts index 512648e6657d2..0f5b6a037cb91 100644 --- a/apps/server/src/orchestration-v2/ThreadSettlementService.ts +++ b/apps/server/src/orchestration-v2/ThreadSettlementService.ts @@ -36,6 +36,7 @@ import * as GitVcsDriver from "../vcs/GitVcsDriver.ts"; import * as ProjectStore from "./ProjectStore.ts"; import { sourceControlDefinitions } from "../sourceControl/sourceControlDefinitions.ts"; import { makeNoPullRequestRechecks } from "./noPullRequestRechecks.ts"; +import { readUmbrellaWorktree } from "../project/umbrellaWorktreeLayout.ts"; import * as Orchestrator from "./Orchestrator.ts"; import * as ProjectionStore from "./ProjectionStore.ts"; import { QUIET_AFTER_MS, QUIET_SYNC_INTERVAL_MS } from "./PullRequestSyncReactor.ts"; @@ -419,7 +420,7 @@ export const make = Effect.gen(function* () { ), ); - const lookupCandidates = (yield* Effect.forEach( + const branchLookupCandidates = (yield* Effect.forEach( candidates, (thread) => { if (thread.lineage.relationshipToParent === "subagent") return settleThread(thread, null); @@ -446,12 +447,27 @@ export const make = Effect.gen(function* () { thread.branchPullRequest != null, ); const lookupCwdByThreadId = new Map(); + // A plain umbrella folder has no branch of its own; its members' pull requests link on their own. + const plainUmbrellaThreads = new Set(); yield* Effect.forEach( - lookupCandidates, + branchLookupCandidates, (thread) => Effect.gen(function* () { const project = projects.get(thread.projectId); if (project === undefined || thread.branch === null) return; + if ( + thread.worktreePath !== null && + !(yield* fileSystem + .exists(path.join(thread.worktreePath, ".git")) + .pipe(Effect.orElseSucceed(() => true))) && + (yield* readUmbrellaWorktree(thread.worktreePath).pipe( + Effect.provideService(FileSystem.FileSystem, fileSystem), + Effect.provideService(Path.Path, path), + )) !== null + ) { + plainUmbrellaThreads.add(thread.id); + return; + } // A worktree folder can outlive its .git, and git there fails with not_a_repository. // An unreadable .git keeps the worktree, so git fails there and the thread is skipped. lookupCwdByThreadId.set( @@ -466,6 +482,9 @@ export const make = Effect.gen(function* () { }), { concurrency: 8, discard: true }, ); + const lookupCandidates = branchLookupCandidates.filter( + (thread) => !plainUmbrellaThreads.has(thread.id), + ); if (mergedPullRequest !== null) { // Invalidate checkout caches on merge; cached open branches would delay settlement beyond this sweep. const cwds = [...new Set(lookupCwdByThreadId.values())]; diff --git a/apps/server/src/review/ReviewService.test.ts b/apps/server/src/review/ReviewService.test.ts index 51db626fe04c8..f43e572f943fb 100644 --- a/apps/server/src/review/ReviewService.test.ts +++ b/apps/server/src/review/ReviewService.test.ts @@ -225,6 +225,19 @@ describe("ReviewService", () => { const unbound = yield* fs.makeTempDirectoryScoped({ prefix: "t3-review-unbound-" }); const claimed = yield* fs.makeTempDirectoryScoped({ prefix: "t3-review-claimed-" }); yield* fs.makeDirectory(`${bound}/sub`); + // Umbrella worktrees are plain folders Git does not list; their manifest names the umbrella. + const umbrella = yield* fs.makeTempDirectoryScoped({ prefix: "t3-review-umbrella-" }); + const foreignUmbrella = yield* fs.makeTempDirectoryScoped({ prefix: "t3-review-foreign-" }); + yield* fs.makeDirectory(`${umbrella}/api`); + for (const [folder, umbrellaRoot] of [ + [umbrella, project], + [foreignUmbrella, unbound], + ] as const) { + yield* fs.writeFileString( + `${folder}.t3-umbrella.json`, + JSON.stringify({ version: 1, umbrellaRoot, rootRepository: false, members: [] }), + ); + } const review = (cwd: string) => Effect.gen(function* () { @@ -240,6 +253,8 @@ describe("ReviewService", () => { threadWorktrees: [ { worktreePath: bound }, { worktreePath: claimed }, + { worktreePath: umbrella }, + { worktreePath: foreignUmbrella }, { worktreePath: deleted, deleted: true }, { worktreePath: "t3-review-relative" }, { worktreePath: "/" }, @@ -248,10 +263,16 @@ describe("ReviewService", () => { ), ); - for (const cwd of [bound, `${bound}/sub`]) { + for (const cwd of [bound, `${bound}/sub`, umbrella, `${umbrella}/api`]) { assert.strictEqual((yield* review(cwd)).cwd, cwd); } - for (const cwd of [deleted, unbound, claimed, `${process.cwd()}/t3-review-relative`]) { + for (const cwd of [ + deleted, + unbound, + claimed, + foreignUmbrella, + `${process.cwd()}/t3-review-relative`, + ]) { const error = yield* review(cwd).pipe(Effect.flip); assert.strictEqual(error._tag, "VcsRepositoryDetectionError"); } diff --git a/apps/server/src/workspace/KnownWorkspaces.ts b/apps/server/src/workspace/KnownWorkspaces.ts index 7881db214b4da..308e4a5200d13 100644 --- a/apps/server/src/workspace/KnownWorkspaces.ts +++ b/apps/server/src/workspace/KnownWorkspaces.ts @@ -12,6 +12,7 @@ import * as SqlClient from "effect/sql/SqlClient"; import * as ServerConfig from "../config.ts"; import * as ProjectStore from "../orchestration-v2/ProjectStore.ts"; +import { readUmbrellaWorktree } from "../project/umbrellaWorktreeLayout.ts"; import * as ServerSettings from "../serverSettings.ts"; import * as GitVcsDriver from "../vcs/GitVcsDriver.ts"; import { isFilesystemRoot, managedWorktreesDirectories } from "../worktreesDirectory.ts"; @@ -134,6 +135,22 @@ export const make = Effect.gen(function* () { const real = yield* resolveRoot(worktreePath); return real !== null && listed.includes(real); }); + // A worktree-mode umbrella thread's folder, wherever the worktree setting put it then. + const isUmbrellaWorktree = Effect.fnUntraced(function* ( + projectId: string, + worktreePath: string, + ) { + const project = projects.find((candidate) => candidate.id === projectId); + if (project === undefined) return false; + const layout = yield* readUmbrellaWorktree(worktreePath).pipe( + Effect.provideService(FileSystem.FileSystem, fileSystem), + Effect.provideService(Path.Path, path), + ); + return ( + layout !== null && + (yield* resolveRoot(layout.umbrellaRoot)) === (yield* resolveRoot(project.workspaceRoot)) + ); + }); for (const { worktreePath, projectId } of threads) { // Relative paths use server cwd; managed paths still need resolution to reject symlinks elsewhere. if (!path.isAbsolute(worktreePath)) continue; @@ -143,6 +160,7 @@ export const make = Effect.gen(function* () { return true; } if (yield* isProjectWorktree(projectId, worktreePath)) return true; + if (yield* isUmbrellaWorktree(projectId, worktreePath)) return true; } return false; }, From 4e92b290ea9da2c5a59266d452794ff5dbc7388f Mon Sep 17 00:00:00 2001 From: Na0s Date: Mon, 16 Nov 2026 21:18:38 -0500 Subject: [PATCH 11/59] fix(server): let agents launch into and delegate from umbrella worktrees Co-Authored-By: Claude Opus 5.5 --- apps/server/src/mcp/OrchestratorMcpService.ts | 25 ++++++++++++++++++- .../src/mcp/toolkits/project/handlers.ts | 6 +++++ 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/apps/server/src/mcp/OrchestratorMcpService.ts b/apps/server/src/mcp/OrchestratorMcpService.ts index 5c5c9636406e1..a40baa5907b0c 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 umbrellaMembership = yield* Effect.serviceOption(UmbrellaMembership.UmbrellaMembership); const serverSettings = yield* ServerSettings.ServerSettingsService; const remoteDelegation = yield* RemoteDelegation.RemoteDelegation; @@ -2699,7 +2701,28 @@ const make = Effect.gen(function* () { input.interactionMode, ); let workspaceStrategy: OrchestrationV2ThreadLaunchWorkspaceStrategy | undefined; - if (input.isolation === "worktree" && !isRetryOfAcceptedDelegation) { + const umbrellaMembers = + input.isolation === "worktree" && Option.isSome(umbrellaMembership) + ? ((yield* umbrellaMembership.value.stateOf( + yield* requireProject(parent.thread.projectId), + ))?.members ?? []) + : []; + 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/toolkits/project/handlers.ts b/apps/server/src/mcp/toolkits/project/handlers.ts index 7a2fb5381227e..a687ed4cf96d3 100644 --- a/apps/server/src/mcp/toolkits/project/handlers.ts +++ b/apps/server/src/mcp/toolkits/project/handlers.ts @@ -9,6 +9,7 @@ import * as Digest from "effect/crypto/Digest"; import * as Effect from "effect/Effect"; import * as Hex from "effect/encoding/Hex"; import * as FileSystem from "effect/FileSystem"; +import * as Path from "effect/Path"; import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; import { OrchestratorRuntimeModeAboveCeilingError } from "../../../orchestration-v2/Orchestrator.ts"; @@ -32,6 +33,7 @@ import * as McpToolAccess from "../../McpToolAccess.ts"; import * as OrchestrationMcp from "../../OrchestratorMcpService.ts"; import { newCommandId, readCaller, resolveProjectId, unavailable } from "../../threadAccess.ts"; import { ProjectToolkit } from "./tools.ts"; +import { readUmbrellaWorktree } from "../../../project/umbrellaWorktreeLayout.ts"; const isAboveCeilingError = Schema.is(OrchestratorRuntimeModeAboveCeilingError); @@ -82,6 +84,10 @@ const assertProjectWorktree = Effect.fn("mcp.assertProjectWorktree")(function* ( Effect.flatMap((paths) => Effect.forEach(paths, real)), Effect.orElseSucceed((): ReadonlyArray => []), ); + // A worktree-mode umbrella thread's folder is not one Git lists; its manifest names the umbrella. + const umbrella = yield* readUmbrellaWorktree(worktreePath).pipe(Effect.provide(Path.layer)); + if (umbrella !== null && (yield* real(umbrella.umbrellaRoot)) === (yield* real(workspaceRoot))) + return; if (!worktrees.includes(yield* real(worktreePath))) return yield* new OrchestratorMcpFailure({ code: "invalid_request", From 586a8ac52460e2c76a65522a62625c723e6f7e25 Mon Sep 17 00:00:00 2001 From: Na0s Date: Mon, 16 Nov 2026 21:21:04 -0500 Subject: [PATCH 12/59] feat(server): clean up umbrella worktrees by age, settlement and deletion Storage cleanup removes an umbrella thread's folder once no repository in it has local changes and its branches are unchanged, keeping branches and the manifest so the next turn recreates the same layout. Checkpoint refs of deleted threads are pruned in member repositories too. Co-Authored-By: Claude Opus 5.5 --- apps/server/src/storageCleanup.test.ts | 66 +++++++++++++++++ apps/server/src/storageCleanup.ts | 99 +++++++++++++++++++++++++- 2 files changed, 163 insertions(+), 2 deletions(-) diff --git a/apps/server/src/storageCleanup.test.ts b/apps/server/src/storageCleanup.test.ts index cf56bde07f214..2147be56bd209 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; + // A plain umbrella folder holding one member repository and a shared folder. + const umbrella = yield* fs.realPath( + yield* fs.makeTempDirectoryScoped({ prefix: "cleanup-umbrella-" }), + ); + const member = `${umbrella}/api`; + yield* fs.makeDirectory(member); + yield* fs.makeDirectory(`${umbrella}/copy`); + yield* fs.writeFileString(`${umbrella}/copy/brief.md`, "brief\n"); + yield* command(member, ["init", "-b", "main"]); + yield* command(member, ["config", "user.email", "cleanup@example.test"]); + yield* command(member, ["config", "user.name", "Cleanup test"]); + yield* fs.writeFileString(`${member}/tracked.txt`, "original\n"); + yield* command(member, ["add", "."]); + yield* command(member, ["commit", "-m", "initial"]); + const folder = `${config.worktreesDir}/umbrella/feature`; + yield* fs.makeDirectory(folder, { recursive: true }); + yield* command(member, ["worktree", "add", "-b", "feature", `${folder}/api`]); + yield* fs.symlink(`${umbrella}/copy`, `${folder}/copy`); + const manifest = `${folder}.t3-umbrella.json`; + yield* fs.writeFileString( + manifest, + JSON.stringify({ + version: 1, + umbrellaRoot: umbrella, + rootRepository: false, + 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); + expect( + (yield* command(member, ["worktree", "list", "--porcelain"])).stdout, + ).not.toContain(folder); + expect((yield* command(member, ["branch", "--list", "feature"])).stdout.trim()).toBe( + "feature", + ); + expect(yield* fs.readFileString(`${umbrella}/copy/brief.md`)).toBe("brief\n"); + // 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..bad3b108f6deb 100644 --- a/apps/server/src/storageCleanup.ts +++ b/apps/server/src/storageCleanup.ts @@ -52,6 +52,11 @@ 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 { + readUmbrellaWorktree, + umbrellaWorktreeRepositories, +} from "./project/umbrellaWorktreeLayout.ts"; import { forkParked } from "./serverActivation.ts"; import * as Settings from "./serverSettings.ts"; import * as TerminalManager from "./terminal/Manager.ts"; @@ -328,6 +333,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 +846,13 @@ 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 + ? [] + : ["--", ".", ...excludedPaths.map((excluded) => `:(exclude,literal)${excluded}`)]; const status = yield* git.execute({ operation: "StorageCleanup.localChanges", cwd, @@ -852,6 +864,7 @@ const make = Effect.gen(function* () { rules.worktreeKeepWhen === "tracked-changes" ? "--untracked-files=no" : "--untracked-files=all", + ...pathspec, ], maxOutputBytes: 64 * 1024, appendTruncationMarker: true, @@ -870,7 +883,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 +1444,71 @@ const make = Effect.gen(function* () { }), ); } + const umbrella = yield* readUmbrellaWorktree(worktreePath).pipe( + Effect.provideService(FileSystem.FileSystem, fs), + Effect.provideService(Path.Path, path), + ); + 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 realFolder = yield* fs.realPath(worktreePath); + const realParent = yield* fs.realPath(path.dirname(worktreePath)); + if (realFolder !== path.join(realParent, path.basename(worktreePath))) + return keep("worktree is a symbolic link"); + if (!roots.some((root) => inside(root, realFolder))) + return keep("outside the managed worktree folder"); + 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 +1780,17 @@ 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* readUmbrellaWorktree(row.worktreePath).pipe( + Effect.provideService(FileSystem.FileSystem, fs), + Effect.provideService(Path.Path, path), + ); + 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(); From b3f3e9c6e27c44b8c9589787af31bbfc121654e5 Mon Sep 17 00:00:00 2001 From: Na0s Date: Mon, 16 Nov 2026 21:24:42 -0500 Subject: [PATCH 13/59] feat(web,mobile): offer worktree mode for umbrella projects The composer offers worktree mode for any umbrella, starting each member of a plain umbrella folder from its own checkout, and the diff panel's member tabs follow a worktree-mode thread into its member worktrees. The umbrella projects guide describes the per-thread layout. Co-Authored-By: Claude Opus 5.5 --- .../features/threads/NewTaskDraftScreen.tsx | 2 +- .../new-task-context-presentation.test.ts | 19 ++++++++++++++ .../threads/new-task-context-presentation.ts | 6 +++++ .../threads/new-task-flow-provider.tsx | 6 +++++ apps/web/src/components/BranchToolbar.tsx | 17 +++++++------ .../web/src/components/ChatView.logic.test.ts | 6 +++++ apps/web/src/components/ChatView.logic.ts | 11 ++++++-- apps/web/src/components/ChatView.tsx | 14 +++++++---- apps/web/src/components/DiffPanel.tsx | 13 ++++++---- .../src/components/chat/useComposerSend.ts | 4 +++ docs/user/project-settings.md | 12 +++++++-- .../client-runtime/src/state/umbrella.test.ts | 25 +++++++++++++++++++ packages/client-runtime/src/state/umbrella.ts | 22 ++++++++++++++++ 13 files changed, 135 insertions(+), 22 deletions(-) diff --git a/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx b/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx index 201204a8a57bf..25c8decdf73da 100644 --- a/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx +++ b/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx @@ -872,7 +872,7 @@ export function NewTaskDraftScreen(props: { ( { ).toEqual({ mode: "local", branch: null, worktreePath: null }); }); + it("keeps worktree mode for a plain umbrella folder, starting each member from its checkout", () => { + const draft = { + selection: undefined, + canChooseWorkspace: true, + defaultMode: "worktree", + defaultModeSettled: true, + isGitRepo: false, + branches: [], + projectCwd: "/clients/acme", + } as const; + expect(resolveNewTaskDraftWorkspace({ ...draft, plainUmbrella: true })).toEqual({ + mode: "worktree", + branch: "HEAD", + worktreePath: null, + }); + expect(resolveNewTaskDraftWorkspace(draft).mode).toBe("local"); + }); + it.each(["local", "worktree"] as const)( "clears stale %s selections for non-git projects", (mode) => { diff --git a/apps/mobile/src/features/threads/new-task-context-presentation.ts b/apps/mobile/src/features/threads/new-task-context-presentation.ts index 44efe4cf04843..5988859ef0ef5 100644 --- a/apps/mobile/src/features/threads/new-task-context-presentation.ts +++ b/apps/mobile/src/features/threads/new-task-context-presentation.ts @@ -164,10 +164,16 @@ export function resolveNewTaskDraftWorkspace(input: { readonly defaultMode: WorkspaceMode; readonly defaultModeSettled: boolean; readonly isGitRepo: boolean; + /** A plain folder holding umbrella members: worktree mode starts each member from its checkout. */ + readonly plainUmbrella?: boolean; readonly branches: Parameters[0]["branches"]; readonly projectCwd: string | null; }): ComposerDraftWorkspaceSelection { const selection = input.canChooseWorkspace ? input.selection : undefined; + if (input.plainUmbrella === true) { + const mode = selection?.mode ?? input.defaultMode; + return { mode, branch: mode === "worktree" ? "HEAD" : null, worktreePath: null }; + } return fillNewTaskWorkspaceBranch({ selection: resolveNewTaskWorkspaceSelection({ selection, diff --git a/apps/mobile/src/features/threads/new-task-flow-provider.tsx b/apps/mobile/src/features/threads/new-task-flow-provider.tsx index 5852206095a8f..bfed39285a167 100644 --- a/apps/mobile/src/features/threads/new-task-flow-provider.tsx +++ b/apps/mobile/src/features/threads/new-task-flow-provider.tsx @@ -137,6 +137,8 @@ type NewTaskFlowContextValue = { readonly workspaceMode: WorkspaceMode; readonly isGitRepo: boolean; readonly isGitRepoKnown: boolean; + /** Worktree mode is offered: a repository, or an umbrella folder whose members it checks out. */ + readonly canUseWorktree: boolean; readonly canChooseWorkspace: boolean; readonly selectedBranchName: string | null; readonly selectedWorktreePath: string | null; @@ -380,6 +382,8 @@ export function NewTaskFlowProvider( }); const knownIsGitRepo = projectGitStatus.data?.isRepo ?? projectBranches.data?.isRepo ?? null; const isGitRepo = knownIsGitRepo ?? true; + const plainUmbrella = + knownIsGitRepo === false && (selectedProject?.umbrellaMembers?.length ?? 0) > 0; const projectSettings = projectDefaults.projectSettings; const canChooseWorkspace = !isScratchDraft; const defaultWorkspaceMode: WorkspaceMode = projectDefaults.defaultWorkspaceMode; @@ -401,6 +405,7 @@ export function NewTaskFlowProvider( defaultMode: defaultWorkspaceMode, defaultModeSettled: projectDefaults.defaultWorkspaceModeSettled, isGitRepo, + plainUmbrella, branches: allBranchRefs, projectCwd: selectedProject?.workspaceRoot ?? null, }); @@ -868,6 +873,7 @@ export function NewTaskFlowProvider( workspaceMode, isGitRepo, isGitRepoKnown: knownIsGitRepo !== null, + canUseWorktree: isGitRepo || plainUmbrella, canChooseWorkspace, selectedBranchName, selectedWorktreePath, diff --git a/apps/web/src/components/BranchToolbar.tsx b/apps/web/src/components/BranchToolbar.tsx index eae9e43459f42..07ff11adcb328 100644 --- a/apps/web/src/components/BranchToolbar.tsx +++ b/apps/web/src/components/BranchToolbar.tsx @@ -85,6 +85,8 @@ interface BranchToolbarProps { worktreePath: string | null; isServerThread: boolean; showGitControls: boolean; + /** Offers local and worktree mode; defaults to `showGitControls`. An umbrella folder has modes without a branch. */ + showWorkspaceModes?: boolean; draftId?: DraftId; onEnvModeChange: (mode: EnvMode) => void; envMode: EnvMode; @@ -595,6 +597,7 @@ export const BranchToolbar = memo(function BranchToolbar({ worktreePath, isServerThread, showGitControls, + showWorkspaceModes = showGitControls, draftId, onEnvModeChange, envMode, @@ -648,7 +651,7 @@ export const BranchToolbar = memo(function BranchToolbar({ () => ({ openBranchPicker: () => branchSelectorRef.current?.open(), usePreviousWorktree: () => { - if (!showGitControls || !canUsePreviousWorktree || !previousWorktreeSeed) return; + if (!showWorkspaceModes || !canUsePreviousWorktree || !previousWorktreeSeed) return; onUsePreviousWorktree(); onComposerFocusRequest?.(); }, @@ -658,7 +661,7 @@ export const BranchToolbar = memo(function BranchToolbar({ onComposerFocusRequest, onUsePreviousWorktree, previousWorktreeSeed, - showGitControls, + showWorkspaceModes, ], ); @@ -734,7 +737,7 @@ export const BranchToolbar = memo(function BranchToolbar({ data-compact={labelsOverflow ? "" : undefined} className={cn("gap-1 text-xs font-normal text-foreground/70 dark:text-muted-foreground")} > - {showGitControls ? ( + {showWorkspaceModes ? (
) : null} - {showGitControls || showEnvironmentIndicator ? ( + {showWorkspaceModes || showEnvironmentIndicator ? (
@@ -777,7 +780,7 @@ export const BranchToolbar = memo(function BranchToolbar({ {...(showEnvironmentPicker ? { onEnvironmentChange } : {})} {...(addTargets.length > 0 ? { onAddToMachine: () => onAddToMachine(null) } : {})} /> - {showGitControls ? ( + {showWorkspaceModes ? ( )} - {showGitControls ? ( + {showWorkspaceModes ? ( { ).toMatchObject({ missingWorktreeBaseBranch: false, baseBranchForWorktree: null, + }); // A plain umbrella folder has no branch to pick; each member starts from its own checkout. + expect( + planComposerTurn({ ...base, activeThreadBranch: null, worktreeBaseFallback: "HEAD" }), + ).toMatchObject({ + missingWorktreeBaseBranch: false, + baseBranchForWorktree: "HEAD", }); }); diff --git a/apps/web/src/components/ChatView.logic.ts b/apps/web/src/components/ChatView.logic.ts index e528246e7aea1..e31e093b9a222 100644 --- a/apps/web/src/components/ChatView.logic.ts +++ b/apps/web/src/components/ChatView.logic.ts @@ -1343,6 +1343,8 @@ export function planComposerTurn(input: { readonly sendEnvMode: DraftThreadEnvMode; readonly worktreePath: string | null; readonly activeThreadBranch: string | null; + /** Used when no branch is picked, as a plain umbrella folder has none to pick. */ + readonly worktreeBaseFallback?: string | null; /** The server launches a No project worktree request at its root, so it needs no base. */ readonly isScratchProject: boolean; readonly resumeCompactionTokens: number | null; @@ -1372,8 +1374,13 @@ export function planComposerTurn(input: { // In worktree mode, require an explicit base branch so we don't silently // fall back to local execution when branch selection is missing. missingWorktreeBaseBranch: - shouldCreateWorktree && !input.activeThreadBranch && !input.isScratchProject, - baseBranchForWorktree: shouldCreateWorktree ? input.activeThreadBranch : null, + shouldCreateWorktree && + !input.activeThreadBranch && + !input.worktreeBaseFallback && + !input.isScratchProject, + baseBranchForWorktree: shouldCreateWorktree + ? (input.activeThreadBranch ?? input.worktreeBaseFallback ?? null) + : null, compactBeforeSend, turnDispatchMode: compactBeforeSend || (input.sendQueuesBehindSetup && dispatchMode !== "steer") diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index 407e3c8d06b2e..e8c5601243028 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -1764,11 +1764,13 @@ export default function ChatView(props: ChatViewProps) { } }, [environmentId, gitStatusCwd, liveIsGitRepo]); const isGitRepo = liveIsGitRepo ?? recallCheckoutIsRepo(environmentId, gitStatusCwd) ?? true; + const isUmbrellaProject = (activeProject?.umbrellaMembers?.length ?? 0) > 0; + // An umbrella checks out every member in worktree mode, even when its root is a plain folder. + const worktreeCapable = isGitRepo || isUmbrellaProject; // 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); + isUmbrellaProject || + (activeThreadWorktreePath === null && (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; @@ -1802,7 +1804,7 @@ export default function ChatView(props: ChatViewProps) { isDraftHeroState, persistInActiveThreads: settings.persistComposerContextStrip, hasActiveProject: activeProject !== null && !showProviderSubagentBar, - isGitRepo, + isGitRepo: worktreeCapable, showEnvironmentIndicator: showComposerEnvironmentIndicator, }); const terminalShortcutLabelOptions = { @@ -2274,7 +2276,7 @@ export default function ChatView(props: ChatViewProps) { : false; const sendEnvMode = resolveSendEnvMode({ requestedEnvMode: envMode, - isGitRepo, + isGitRepo: worktreeCapable, }); const localCheckoutBranchMismatch = isServerThread ? resolveLocalCheckoutBranchMismatch({ @@ -2949,6 +2951,7 @@ export default function ChatView(props: ChatViewProps) { isServerThread, isLocalDraftThread, isGitRepo, + worktreeBaseFallback: !isGitRepo && isUmbrellaProject ? "HEAD" : null, phase, runtimeMode, sendEnvMode, @@ -3806,6 +3809,7 @@ export default function ChatView(props: ChatViewProps) { worktreePath={activeThread.worktreePath} isServerThread={isServerThread} showGitControls={isGitRepo} + showWorkspaceModes={worktreeCapable} {...(routeKind === "draft" && draftId ? { draftId } : {})} onEnvModeChange={onEnvModeChangeStable} startFromOrigin={startFromOrigin} diff --git a/apps/web/src/components/DiffPanel.tsx b/apps/web/src/components/DiffPanel.tsx index ffadb2862818c..1906036d4600c 100644 --- a/apps/web/src/components/DiffPanel.tsx +++ b/apps/web/src/components/DiffPanel.tsx @@ -14,6 +14,7 @@ import { type UmbrellaMember, } from "@t3tools/contracts"; import { scopedThreadKey } from "@t3tools/client-runtime/environment"; +import { umbrellaMembersForThread } from "@t3tools/client-runtime/state/umbrella"; import { ArrowRightIcon, CheckIcon, @@ -287,11 +288,13 @@ export default function DiffPanel({ diffSelection.kind === "branch" || diffSelection.kind === "unstaged" || diffSelection.kind === "commit"; - // Members are checkouts beside the project root, which a worktree thread does not work in. - const umbrellaMembers = - activeThread && !activeThread.worktreePath - ? (activeProject?.umbrellaMembers ?? NO_UMBRELLA_MEMBERS) - : NO_UMBRELLA_MEMBERS; + // 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 diff --git a/apps/web/src/components/chat/useComposerSend.ts b/apps/web/src/components/chat/useComposerSend.ts index 93ff79432708c..116af811ee2a4 100644 --- a/apps/web/src/components/chat/useComposerSend.ts +++ b/apps/web/src/components/chat/useComposerSend.ts @@ -182,6 +182,8 @@ interface ComposerSendInput { readonly isServerThread: boolean; readonly isLocalDraftThread: boolean; readonly isGitRepo: boolean; + /** The base a new worktree uses with no branch picked: "HEAD" for a plain umbrella folder. */ + readonly worktreeBaseFallback: string | null; readonly phase: SessionPhase; readonly runtimeMode: RuntimeMode; readonly sendEnvMode: DraftThreadEnvMode; @@ -283,6 +285,7 @@ export function useComposerSend(input: ComposerSendInput) { isServerThread, isLocalDraftThread, isGitRepo, + worktreeBaseFallback, phase, runtimeMode, sendEnvMode, @@ -817,6 +820,7 @@ export function useComposerSend(input: ComposerSendInput) { sendEnvMode, worktreePath: activeThread.worktreePath, activeThreadBranch, + worktreeBaseFallback, isScratchProject: activeProjectIsScratch, resumeCompactionTokens, keepFullHistory, diff --git a/docs/user/project-settings.md b/docs/user/project-settings.md index b21ab9bef6a2d..be634b56593dc 100644 --- a/docs/user/project-settings.md +++ b/docs/user/project-settings.md @@ -92,8 +92,16 @@ folder's menu in the sidebar or from the command palette. For a clone on another 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 checks out only the folder's own repository, without its members, so use local mode -for work that spans members. +In worktree mode, a thread works in its own copy of the umbrella, so its edits stay out of your +checkouts. T3 Code makes one folder in your worktree location with a worktree of every member at +the same path, all on the thread's branch, plus the folder's own worktree when it is a repository. +Members added from outside the umbrella sit under `_external/` in that folder. When the umbrella +folder is not a repository, its other files and folders, such as `copy/` or `marketing/`, are +linked into the thread's folder rather than copied: edits to them change the originals and are +not part of checkpoints, so **Revert files too** restores only the members. 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. ## Worktree branch names diff --git a/packages/client-runtime/src/state/umbrella.test.ts b/packages/client-runtime/src/state/umbrella.test.ts index c08831ddc763d..698d4abd4d56e 100644 --- a/packages/client-runtime/src/state/umbrella.test.ts +++ b/packages/client-runtime/src/state/umbrella.test.ts @@ -9,6 +9,7 @@ import { restoreUmbrellaMember, umbrellaAdoptionTargets, umbrellaMemberLabel, + umbrellaMembersForThread, } from "./umbrella.ts"; const environmentId = EnvironmentId.make("desktop"); @@ -112,3 +113,27 @@ describe("umbrella membership", () => { expect(umbrellaMemberLabel({ relativePath: "../../work/acme-site" })).toBe("acme-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 index 1a0157ececec4..5e201fc153633 100644 --- a/packages/client-runtime/src/state/umbrella.ts +++ b/packages/client-runtime/src/state/umbrella.ts @@ -4,6 +4,8 @@ import { type UmbrellaMember, } from "@t3tools/contracts"; +import { umbrellaWorktreeMemberPaths } from "@t3tools/shared/umbrellaWorktree"; + import type { EnvironmentProject } from "./models.ts"; import { normalizeProjectPathForComparison } from "./projects.ts"; import { isUmbrellaProject } from "./projectGrouping.ts"; @@ -24,6 +26,26 @@ export function umbrellaMemberLabel(member: Pick : member.relativePath; } +/** + * 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)}`, + })); +} + const isAbsolute = (value: string) => value.startsWith("/") || /^[A-Za-z]:[\\/]/.test(value); /** Settings may hold paths relative to the umbrella root; compare them resolved. */ From 7359d0cd10f55dd69a95ddf66fdb835c7b8e5835 Mon Sep 17 00:00:00 2001 From: Na0s Date: Mon, 16 Nov 2026 21:45:39 -0500 Subject: [PATCH 14/59] fix(server): keep plain umbrella worktrees out of enclosing repositories A plain umbrella worktree folder placed inside another repository, such as a T3 home in a repo, resolved to that repository: checkpoints captured it and its branch replaced the thread's. Git now runs with a ceiling above registered plain folders, an umbrella's own repository must be rooted at its folder, and branch sync ignores branches reported for a plain folder. Co-Authored-By: Claude Opus 5.5 --- .../src/checkpointing/CheckpointStore.test.ts | 5 +- .../src/checkpointing/CheckpointStore.ts | 7 +- .../CheckpointService.test.ts | 136 ++++++++++++++++++ .../WorktreeBranchSync.test.ts | 33 ++++- .../orchestration-v2/WorktreeBranchSync.ts | 9 ++ .../src/project/UmbrellaWorktree.test.ts | 6 + .../src/project/umbrellaWorktreeLayout.ts | 7 +- apps/server/src/vcs/UmbrellaMemberIndex.ts | 32 ++++- apps/server/src/vcs/VcsProcess.ts | 11 ++ 9 files changed, 235 insertions(+), 11 deletions(-) diff --git a/apps/server/src/checkpointing/CheckpointStore.test.ts b/apps/server/src/checkpointing/CheckpointStore.test.ts index dfd47bf4682d7..8d843749f5f08 100644 --- a/apps/server/src/checkpointing/CheckpointStore.test.ts +++ b/apps/server/src/checkpointing/CheckpointStore.test.ts @@ -877,7 +877,10 @@ it.layer(layerTest)("CheckpointStore.layer", (it) => { driver: { checkpoints: checkpointsFor(cwd) }, } as unknown as VcsDriverRegistry.VcsDriverHandle), }), - FileSystem.layerNoop({ realPath: (value) => Effect.succeed(value) }), + FileSystem.layerNoop({ + realPath: (value) => Effect.succeed(value), + exists: (value) => Effect.succeed(value === `${root}/.git`), + }), ), ), Effect.provideService(UmbrellaMemberIndex.UmbrellaMemberIndex, index), diff --git a/apps/server/src/checkpointing/CheckpointStore.ts b/apps/server/src/checkpointing/CheckpointStore.ts index c8895c063ba03..586ee31310d11 100644 --- a/apps/server/src/checkpointing/CheckpointStore.ts +++ b/apps/server/src/checkpointing/CheckpointStore.ts @@ -172,7 +172,12 @@ export const make = Effect.gen(function* () { 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)); + // An umbrella's own repository is rooted at its folder; one enclosing the folder is not its own. + const own = + (yield* fileSystem + .exists(`${cwd.replace(/[\\/]+$/, "")}/.git`) + .pipe(Effect.orElseSucceed(() => false))) && + (yield* isGitRepository(cwd).pipe(Effect.orElseSucceed(() => false))); return [ ...(own ? [{ cwd, prefix: "" }] : []), ...members.map((member) => ({ cwd: member.path, prefix: `${member.relativePath}/` })), diff --git a/apps/server/src/orchestration-v2/CheckpointService.test.ts b/apps/server/src/orchestration-v2/CheckpointService.test.ts index 69bb0ecc07344..62c363e0bebc9 100644 --- a/apps/server/src/orchestration-v2/CheckpointService.test.ts +++ b/apps/server/src/orchestration-v2/CheckpointService.test.ts @@ -1,4 +1,5 @@ import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; +import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, it } from "@effect/vitest"; import { CheckpointScopeId, @@ -15,11 +16,15 @@ import * as DateTime from "effect/DateTime"; import * as Deferred from "effect/Deferred"; 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 Ref from "effect/Ref"; import * as TestClock from "effect/testing/TestClock"; import * as CheckpointStore from "../checkpointing/CheckpointStore.ts"; +import * as UmbrellaMemberIndex from "../vcs/UmbrellaMemberIndex.ts"; +import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts"; +import * as VcsProcess from "../vcs/VcsProcess.ts"; import * as CheckpointService from "./CheckpointService.ts"; import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; @@ -233,3 +238,134 @@ it.effect("records a repository probe failure as an error checkpoint, not a miss assert.deepEqual(statuses, { baseline: "error", turn: "error" }); }), ); + +it.effect( + "checkpoints a plain umbrella worktree inside another repository by its members alone", + () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const vcsProcess = yield* VcsProcess.VcsProcess; + const git = (cwd: string, args: ReadonlyArray) => + vcsProcess + .run({ + operation: "CheckpointService.test", + command: "git", + cwd, + args, + timeoutMs: 10_000, + }) + .pipe(Effect.map((result) => result.stdout.trim())); + const initRepo = Effect.fnUntraced(function* (cwd: string) { + yield* fileSystem.makeDirectory(cwd, { recursive: true }); + yield* git(cwd, ["init", "-b", "main"]); + yield* git(cwd, ["config", "user.email", "test@test.com"]); + yield* git(cwd, ["config", "user.name", "Test"]); + yield* fileSystem.writeFileString(`${cwd}/README.md`, "# original\n"); + yield* git(cwd, ["add", "."]); + yield* git(cwd, ["commit", "-m", "initial"]); + }); + const tmp = yield* fileSystem.realPath( + yield* fileSystem.makeTempDirectoryScoped({ prefix: "checkpoint-umbrella-" }), + ); + // A T3 home inside a repository puts the thread's folder inside that repository too. + const enclosing = `${tmp}/home`; + yield* initRepo(enclosing); + const folder = `${enclosing}/.t3/worktrees/northwind/feature-1`; + yield* fileSystem.makeDirectory(folder, { recursive: true }); + for (const name of ["api", "site"]) { + yield* initRepo(`${tmp}/northwind/${name}`); + yield* git(`${tmp}/northwind/${name}`, [ + "worktree", + "add", + "-b", + "t3/feature", + `${folder}/${name}`, + ]); + } + yield* fileSystem.writeFileString( + `${folder}.t3-umbrella.json`, + JSON.stringify({ + version: 1, + umbrellaRoot: `${tmp}/northwind`, + rootRepository: false, + members: ["api", "site"].map((name) => ({ + source: `${tmp}/northwind/${name}`, + path: name, + })), + }), + ); + const scope: OrchestrationV2CheckpointScope = { + id: CheckpointScopeId.make("checkpoint-scope:umbrella-worktree"), + threadId: ThreadId.make("thread:umbrella-worktree"), + runId: RunId.make("run:umbrella-worktree:1"), + nodeId: NodeId.make("node:umbrella-worktree:1"), + parentScopeId: null, + providerThreadId: ProviderThreadId.make("provider-thread:umbrella-worktree"), + kind: "root_run", + ordinalWithinParent: 0, + advancesAppRunCount: true, + cwd: folder, + createdAt: DateTime.makeUnsafe("2026-07-28T00:00:00.000Z"), + }; + + // The index starts cold, as right after a restart. + yield* Effect.gen(function* () { + const checkpoints = yield* CheckpointService.CheckpointServiceV2; + const store = yield* CheckpointStore.CheckpointStore; + yield* checkpoints.captureBaseline({ scope, ordinalWithinScope: 0 }); + const baseline = yield* checkpoints.materializeBaselineCheckpoint({ + scope, + ordinalWithinScope: 0, + nodeId: scope.nodeId!, + capturedAt: scope.createdAt, + }); + for (const name of ["api", "site"]) { + yield* fileSystem.writeFileString(`${folder}/${name}/README.md`, "# edited\n"); + } + const turn = yield* checkpoints.capture({ + scope, + ordinalWithinScope: 1, + runId: scope.runId!, + nodeId: scope.nodeId!, + appRunOrdinal: 1, + capturedAt: scope.createdAt, + }); + assert.deepEqual( + { + baseline: baseline.status, + turn: turn.status, + files: turn.files.map((file) => file.path), + }, + { baseline: "ready", turn: "ready", files: ["api/README.md", "site/README.md"] }, + ); + // The enclosing repository is not the folder's: it gets no checkpoint and no branch. + assert.strictEqual(yield* git(enclosing, ["for-each-ref", "refs/t3"]), ""); + assert.isFalse(yield* store.isGitRepository(folder)); + + assert.isTrue( + yield* store.restoreCheckpoint({ cwd: folder, checkpointRef: baseline.ref! }), + ); + for (const name of ["api", "site"]) { + assert.strictEqual( + yield* fileSystem.readFileString(`${folder}/${name}/README.md`), + "# original\n", + ); + assert.strictEqual(yield* git(`${tmp}/northwind/${name}`, ["status", "--porcelain"]), ""); + } + }).pipe( + Effect.provide( + CheckpointService.layer.pipe( + Layer.provideMerge(Layer.mergeAll(IdAllocator.layer, CheckpointStore.layer)), + Layer.provide(VcsDriverRegistry.layer), + ), + ), + ); + }).pipe( + Effect.provide( + VcsProcess.layer.pipe( + Layer.provideMerge(UmbrellaMemberIndex.layer), + Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), + ), + ), + ), +); diff --git a/apps/server/src/orchestration-v2/WorktreeBranchSync.test.ts b/apps/server/src/orchestration-v2/WorktreeBranchSync.test.ts index 14c5b5d2751d4..34a0896003968 100644 --- a/apps/server/src/orchestration-v2/WorktreeBranchSync.test.ts +++ b/apps/server/src/orchestration-v2/WorktreeBranchSync.test.ts @@ -9,6 +9,8 @@ import * as Stream from "effect/Stream"; 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 PlatformError from "effect/PlatformError"; import * as GitWorkflowService from "../git/GitWorkflowService.ts"; import * as VcsStatusBroadcaster from "../vcs/VcsStatusBroadcaster.ts"; @@ -33,6 +35,8 @@ it.effect.each([false, true])( thread("current", "union", "/worktree"), thread("root", "main", null), thread("other", "feature", "/other"), + // Status of a plain umbrella folder inside a repository reports that repository's branch. + thread("umbrella", "t3/feature", "/umbrella"), ], archivedThreads: [thread("archived", "t3/bfc349ae", "/worktree")], }; @@ -61,7 +65,26 @@ it.effect.each([false, true])( Layer.mergeAll( FileSystem.layerNoop({ realPath: (path) => Effect.succeed(path === "/link/worktree" ? "/worktree" : path), + readFileString: (path) => + path === "/umbrella.t3-umbrella.json" + ? Effect.succeed( + JSON.stringify({ + version: 1, + umbrellaRoot: "/clients/northwind", + rootRepository: false, + members: [], + }), + ) + : Effect.fail( + PlatformError.systemError({ + _tag: "NotFound", + module: "FileSystem", + method: "readFileString", + pathOrDescriptor: path, + }), + ), }), + Path.layer, Layer.mock(ProjectionStore.ProjectionStoreV2)({ getThreadWorktreePaths: () => Effect.succeed( @@ -74,10 +97,12 @@ it.effect.each([false, true])( }), Layer.mock(VcsStatusBroadcaster.VcsStatusBroadcaster)({ streamBranchChanges: Stream.fromIterable([null, "t3/bfc349ae", "union"]).pipe( - Stream.map((refName) => ({ - cwd: "/worktree", - refName, - })), + Stream.flatMap((refName) => + Stream.fromIterable([ + { cwd: "/worktree", refName }, + { cwd: "/umbrella", refName }, + ]), + ), Stream.ensuring(Deferred.succeed(reconciled, undefined)), ), }), diff --git a/apps/server/src/orchestration-v2/WorktreeBranchSync.ts b/apps/server/src/orchestration-v2/WorktreeBranchSync.ts index 1561a45d01159..b9248587661e7 100644 --- a/apps/server/src/orchestration-v2/WorktreeBranchSync.ts +++ b/apps/server/src/orchestration-v2/WorktreeBranchSync.ts @@ -4,9 +4,11 @@ import * as KeyedLock from "@t3tools/shared/KeyedLock"; 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 Stream from "effect/Stream"; import * as GitWorkflowService from "../git/GitWorkflowService.ts"; +import { readUmbrellaWorktree } from "../project/umbrellaWorktreeLayout.ts"; import { forkParked } from "../serverActivation.ts"; import * as VcsStatusBroadcaster from "../vcs/VcsStatusBroadcaster.ts"; import * as ProjectionStore from "./ProjectionStore.ts"; @@ -17,11 +19,18 @@ export const makeReconcile = Effect.gen(function* () { const git = yield* GitWorkflowService.GitWorkflowService; const projections = yield* ProjectionStore.ProjectionStoreV2; const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; return Effect.fn("WorktreeBranchSync.reconcile")(function* (input: { readonly cwd: string; readonly refName: string | null; }) { if (input.refName === null) return; + // A plain umbrella folder has no branch; one reported for it belongs to an enclosing repository. + const umbrella = yield* readUmbrellaWorktree(input.cwd).pipe( + Effect.provideService(FileSystem.FileSystem, fs), + Effect.provideService(Path.Path, path), + ); + if (umbrella !== null && !umbrella.rootRepository) return; const paths = yield* projections.getThreadWorktreePaths({ includeArchived: true }); const matchingPaths = new Set(); for (const worktreePath of new Set(paths.map((thread) => thread.worktreePath))) { diff --git a/apps/server/src/project/UmbrellaWorktree.test.ts b/apps/server/src/project/UmbrellaWorktree.test.ts index 072ecdd9d27d2..312bd25fa7cfc 100644 --- a/apps/server/src/project/UmbrellaWorktree.test.ts +++ b/apps/server/src/project/UmbrellaWorktree.test.ts @@ -137,6 +137,9 @@ it.layer(layerTest)("UmbrellaWorktree", (it) => { Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; const umbrella = yield* makeUmbrella(rootRepository); + // A T3 home inside a repository puts every thread folder inside that repository too. + const { baseDir } = yield* ServerConfig.ServerConfig; + if (!(yield* fileSystem.exists(NodePath.join(baseDir, ".git")))) yield* initRepo(baseDir); const worktrees = yield* makeUmbrellaWorktrees; const created = yield* worktrees.create({ umbrellaRoot: umbrella.root, @@ -182,6 +185,9 @@ it.layer(layerTest)("UmbrellaWorktree", (it) => { contacts.replace(folder, umbrella.root), ); assert.isFalse(yield* fileSystem.exists(NodePath.join(folder, ".git"))); + // Git never finds the enclosing repository from the plain folder. + const outer = yield* Effect.exit(git(folder, ["rev-parse", "--show-toplevel"])); + assert.isTrue(outer._tag === "Failure"); } const layout = yield* readUmbrellaWorktree(folder); diff --git a/apps/server/src/project/umbrellaWorktreeLayout.ts b/apps/server/src/project/umbrellaWorktreeLayout.ts index 19be837b37f6e..e6ae228347a63 100644 --- a/apps/server/src/project/umbrellaWorktreeLayout.ts +++ b/apps/server/src/project/umbrellaWorktreeLayout.ts @@ -101,7 +101,12 @@ export const registerUmbrellaWorktree = Effect.fn("UmbrellaWorktree.register")(f Effect.map((memberPath) => ({ path: memberPath, relativePath: member.path })), ), ); - yield* index.registerWorktree(yield* realPath(layout.path), members); + const root = yield* realPath(layout.path); + yield* index.registerWorktree( + root, + members, + layout.rootRepository ? undefined : [...new Set([path.resolve(layout.path), root])], + ); }); /** Reads and registers the umbrella worktree at `cwd`, for callers that may run before the startup scan. */ diff --git a/apps/server/src/vcs/UmbrellaMemberIndex.ts b/apps/server/src/vcs/UmbrellaMemberIndex.ts index 1117024c1ae90..bf365aad5cbeb 100644 --- a/apps/server/src/vcs/UmbrellaMemberIndex.ts +++ b/apps/server/src/vcs/UmbrellaMemberIndex.ts @@ -19,16 +19,25 @@ export interface UmbrellaMemberIndexShape { readonly replace: ( umbrellas: ReadonlyMap>, ) => Effect.Effect; - /** Adds or replaces one worktree-mode thread's folder, which `replace` leaves alone. */ + /** + * Adds or replaces one worktree-mode thread's folder, which `replace` leaves alone. A plain + * folder passes every spelling of its path as `plainAliases`, so Git never searches above it. + */ readonly registerWorktree: ( resolvedRoot: string, members: ReadonlyArray, + plainAliases?: 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; + /** + * For a cwd in a plain umbrella worktree folder, the `GIT_CEILING_DIRECTORIES` that keeps Git + * from finding a repository that merely encloses the folder, such as a T3 home inside one. + */ + readonly gitCeilingFor: (cwd: string) => string | null; } const EMPTY: ReadonlyArray = []; @@ -46,6 +55,8 @@ const isStrictlyWithin = (root: string, candidate: string) => { export const makeIndex = (): UmbrellaMemberIndexShape => { let umbrellas = new Map>(); const worktrees = new Map>(); + // Alias of a plain worktree folder → its registered root. + const plainFolders = new Map(); const lookup = (root: string) => umbrellas.get(root) ?? worktrees.get(root) ?? EMPTY; return { replace: (next) => @@ -54,13 +65,17 @@ export const makeIndex = (): UmbrellaMemberIndexShape => { Array.from(next, ([root, members]) => [NodePath.resolve(root), members] as const), ); }), - registerWorktree: (resolvedRoot, members) => + registerWorktree: (resolvedRoot, members, plainAliases) => Effect.sync(() => { - worktrees.set(NodePath.resolve(resolvedRoot), members); + const root = NodePath.resolve(resolvedRoot); + worktrees.set(root, members); + for (const alias of plainAliases ?? []) plainFolders.set(NodePath.resolve(alias), root); }), forgetWorktree: (resolvedRoot) => Effect.sync(() => { - worktrees.delete(NodePath.resolve(resolvedRoot)); + const root = NodePath.resolve(resolvedRoot); + worktrees.delete(root); + for (const [alias, owner] of plainFolders) if (owner === root) plainFolders.delete(alias); }), membersOf: (resolvedRoot) => lookup(NodePath.resolve(resolvedRoot)), hasMembers: () => umbrellas.size > 0 || worktrees.size > 0, @@ -72,6 +87,14 @@ export const makeIndex = (): UmbrellaMemberIndexShape => { .filter((member) => isStrictlyWithin(root, member)) .map((member) => NodePath.relative(root, member).split(NodePath.sep).join("/")); }, + gitCeilingFor: (cwd) => { + if (plainFolders.size === 0) return null; + const target = NodePath.resolve(cwd); + for (const alias of plainFolders.keys()) { + if (target === alias || isStrictlyWithin(alias, target)) return NodePath.dirname(alias); + } + return null; + }, }; }; @@ -86,6 +109,7 @@ export class UmbrellaMemberIndex extends Context.Reference EMPTY, hasMembers: () => false, memberPathsWithin: () => EMPTY, + gitCeilingFor: () => null, }), }, ) {} diff --git a/apps/server/src/vcs/VcsProcess.ts b/apps/server/src/vcs/VcsProcess.ts index da2f988ce1ed8..5487b875aeff0 100644 --- a/apps/server/src/vcs/VcsProcess.ts +++ b/apps/server/src/vcs/VcsProcess.ts @@ -24,6 +24,7 @@ import type { SourceControlProcessInput } from "@t3tools/source-control-core/ser import { gitCommandDuration, gitCommandsTotal, withMetrics } from "../observability/Metrics.ts"; import * as ProcessRunner from "../processRunner.ts"; +import { UmbrellaMemberIndex } from "./UmbrellaMemberIndex.ts"; export interface VcsProcessInput { readonly operation: string; @@ -208,6 +209,7 @@ const canRetryFullFsync = (stderr: string) => export const make = Effect.gen(function* () { const processRunner = yield* ProcessRunner.ProcessRunner; const hostPlatform = yield* HostProcess.Platform; + const umbrellaMembers = yield* UmbrellaMemberIndex; const vcsProcesses = yield* Semaphore.make(VCS_PROCESS_CONCURRENCY); const nonGitProcesses = yield* Semaphore.make(NON_GIT_PROCESS_CONCURRENCY); const keyedProcesses = new Map(); @@ -220,6 +222,14 @@ export const make = Effect.gen(function* () { return semaphore.withPermits(1); }; + // A plain umbrella worktree folder is no repository, even inside one, such as a T3 home in a repo. + const gitCeilingEnv = (input: VcsProcessInput) => { + if (input.command !== "git") return {}; + // Git runs in `cwd` through `-C` even when it spawns elsewhere. + const ceiling = umbrellaMembers.gitCeilingFor(input.cwd); + return ceiling === null ? {} : { GIT_CEILING_DIRECTORIES: ceiling }; + }; + const spawn = Effect.fn("VcsProcess.spawn")(function* ( input: VcsProcessInput, baseError: VcsProcessErrorContext, @@ -241,6 +251,7 @@ export const make = Effect.gen(function* () { // Failures are read by English patterns; without LANG, macOS Git follows the system language. // LANGUAGE leaves LC_CTYPE, which hooks inherit, alone. ...(input.command === "git" ? { LANGUAGE: "C" } : {}), + ...gitCeilingEnv(input), ...input.env, ...explicitBareRepositoryEnv({ ...process.env, ...input.env }, hostPlatform), }, From 909a703c542a57a50dea8aa67f14c0a9216432aa Mon Sep 17 00:00:00 2001 From: Na0s Date: Mon, 16 Nov 2026 21:45:53 -0500 Subject: [PATCH 15/59] fix(web): name the member in Remove from umbrella actions Co-Authored-By: Claude Opus 5.5 --- apps/web/src/components/CommandPalette.tsx | 4 ++-- apps/web/src/umbrellaMembership.logic.test.ts | 2 +- apps/web/src/umbrellaMembership.logic.ts | 3 ++- docs/user/project-settings.md | 4 ++-- 4 files changed, 7 insertions(+), 6 deletions(-) diff --git a/apps/web/src/components/CommandPalette.tsx b/apps/web/src/components/CommandPalette.tsx index 7e09edce019a2..94a6d97d75767 100644 --- a/apps/web/src/components/CommandPalette.tsx +++ b/apps/web/src/components/CommandPalette.tsx @@ -1779,8 +1779,8 @@ function OpenCommandPaletteDialog(props: { kind: "action", value: `action:umbrella-remove:${umbrella.environmentId}:${umbrella.id}`, searchTerms: ["umbrella", "remove", "leave", "member", "project", umbrella.title], - title: "Remove project from umbrella", - description: `${umbrella.title} · ${umbrellaMemberLabel(member)}`, + title: `Remove ${umbrellaMemberLabel(member)} from umbrella`, + description: umbrella.title, icon: , run: async () => umbrellaEdits.leave(removal), }); diff --git a/apps/web/src/umbrellaMembership.logic.test.ts b/apps/web/src/umbrellaMembership.logic.test.ts index 99af540bd2435..cdae49a5a0ae5 100644 --- a/apps/web/src/umbrellaMembership.logic.test.ts +++ b/apps/web/src/umbrellaMembership.logic.test.ts @@ -97,7 +97,7 @@ describe("umbrellaMenuItems", () => { it("uses a single item when one removal is possible", () => { const actions = umbrellaMembershipActions([api], projects); expect(umbrellaMenuItems(actions)).toEqual([ - { id: "umbrella-remove:0", label: "Remove from umbrella", detail: "acme" }, + { id: "umbrella-remove:0", label: "Remove api from umbrella", detail: "acme" }, ]); expect(resolveUmbrellaMenuAction(actions, "umbrella-remove:0")?.kind).toBe("remove"); }); diff --git a/apps/web/src/umbrellaMembership.logic.ts b/apps/web/src/umbrellaMembership.logic.ts index aa59cdb0d5b9b..53d560696003f 100644 --- a/apps/web/src/umbrellaMembership.logic.ts +++ b/apps/web/src/umbrellaMembership.logic.ts @@ -72,7 +72,8 @@ export function umbrellaMenuItems( if (actions.removals.length === 1 && onlyRemoval) { items.push({ id: `${REMOVE_PREFIX}0`, - label: "Remove from umbrella", + // 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) { diff --git a/docs/user/project-settings.md b/docs/user/project-settings.md index be634b56593dc..a594e425d8647 100644 --- a/docs/user/project-settings.md +++ b/docs/user/project-settings.md @@ -86,9 +86,9 @@ out. Projects you already have for a member fold into the umbrella's sidebar row: the same folder on the umbrella's machine, or the same repository on any connected machine. Their threads name the -member they belong to. Use **Add to umbrella** and **Remove from umbrella** from a project +member they belong to. 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, -**Remove from umbrella** only stops grouping it there; its grouping rule in **Settings → Projects** +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**. From fbe013733f5c1ccd83e04b430c8b31b416a759b6 Mon Sep 17 00:00:00 2001 From: Na0s Date: Tue, 17 Nov 2026 20:14:42 -0500 Subject: [PATCH 16/59] test(server): stub manifest reads and accept any member checkout order Worktree restore now looks for an umbrella manifest, so the stub file systems in ProviderTurnStartService tests answer readFileString with NotFound. Umbrella members are checked out concurrently, so the launch test compares createWorktree calls without depending on their order. Co-Authored-By: Claude Opus 5.5 --- .../ProviderTurnStartService.test.ts | 27 +++++++++++++++++++ .../ThreadLaunchService.test.ts | 9 +++---- 2 files changed, 31 insertions(+), 5 deletions(-) diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts index 7b0759ae99b0b..cdd19c4a09e82 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts @@ -165,6 +165,15 @@ function startWithMissingWorktree( Layer.mock(TurnItemPositionStore.TurnItemPositionStoreV2)({}), Layer.succeed(FileSystem.FileSystem, { exists: () => Effect.succeed(false), + readFileString: (target: string) => + Effect.fail( + PlatformError.systemError({ + _tag: "NotFound", + module: "FileSystem", + method: "readFileString", + pathOrDescriptor: target, + }), + ), realPath: (target: string) => normalize(target) in realPaths ? Effect.succeed(realPaths[normalize(target)]) @@ -301,6 +310,15 @@ const layerRestoreLeaseTest = layerThreadWorktreeRestore.pipe( Layer.succeed(FileSystem.FileSystem, { exists: restoreLeaseExists, realPath: (target: string) => Effect.succeed(normalize(target)), + readFileString: (target: string) => + Effect.fail( + PlatformError.systemError({ + _tag: "NotFound", + module: "FileSystem", + method: "readFileString", + pathOrDescriptor: target, + }), + ), } as never), layerWorktreeLocation(), Layer.mock(GitWorkflow.GitWorkflowService)({ @@ -365,6 +383,15 @@ it.each([ exists: () => Effect.succeed(false), realPath: (target: string) => Effect.succeed(target), makeDirectory, + readFileString: (target: string) => + Effect.fail( + PlatformError.systemError({ + _tag: "NotFound", + module: "FileSystem", + method: "readFileString", + pathOrDescriptor: target, + }), + ), } 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 679a02872739c..22a9ac59d55b6 100644 --- a/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts +++ b/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts @@ -3214,12 +3214,11 @@ it.effect("checks out every member of a plain umbrella folder into one thread fo { 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, - ]), + harness.createWorktree.mock.calls + .map(([input]) => [input.cwd, input.path, input.newRefName]) + .toSorted(([a], [b]) => String(a).localeCompare(String(b))), [ ["/elsewhere/site", `${thread.worktreePath}/_external/site`, "feature"], ["/repo/api", `${thread.worktreePath}/api`, "feature"], From a03894f5c5e8a2c4addbf7f355d8b0840316803c Mon Sep 17 00:00:00 2001 From: Na0s Date: Wed, 18 Nov 2026 17:22:03 -0500 Subject: [PATCH 17/59] fix(server): explain plain-folder worktree refusals and check umbrella base refs A worktree launch in a folder that is not a repository now names the checkouts it holds, which of them has the base ref, and their projects, instead of failing later with Git's VCS driver error. Preparation that skips the up-front check fails the same way. An umbrella accepts a base ref that any checkout has and refuses one that none has. The MCP hint points at the checkout's own projectId or the umbrella setting. Co-Authored-By: Claude Opus 5.5 --- .../src/mcp/toolkits/project/handlers.test.ts | 56 +++++ .../src/mcp/toolkits/project/handlers.ts | 20 +- .../ThreadLaunchService.test.ts | 166 ++++++++++++++- .../orchestration-v2/ThreadLaunchService.ts | 199 ++++++++++++++++-- 4 files changed, 414 insertions(+), 27 deletions(-) diff --git a/apps/server/src/mcp/toolkits/project/handlers.test.ts b/apps/server/src/mcp/toolkits/project/handlers.test.ts index c95fadd9096e2..cbde9750be3a1 100644 --- a/apps/server/src/mcp/toolkits/project/handlers.test.ts +++ b/apps/server/src/mcp/toolkits/project/handlers.test.ts @@ -613,6 +613,62 @@ it.effect("a launch into a new worktree creates nothing when its base ref has no }), ); +it.effect("a worktree launch in a plain folder points at the checkout'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 }, + ], + }), + ), + }); + 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('ask the user to turn on Use as umbrella for "Client folder".'); + 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 a687ed4cf96d3..51a28d02c067c 100644 --- a/apps/server/src/mcp/toolkits/project/handlers.ts +++ b/apps/server/src/mcp/toolkits/project/handlers.ts @@ -57,8 +57,24 @@ 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 projects = (error.nestedRepositories ?? []).filter( + (repository) => repository.projectId !== undefined, + ); + const holders = projects.filter((repository) => repository.hasBaseRef === true); + 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(", ")}`; + const umbrella = + (error.nestedRepositories ?? []).length > 0 + ? ` To span all of its checkouts, ask the user to turn on Use as umbrella for "${error.projectTitle}".` + : ""; + return `Use workspaceStrategy: {type: "root"}, or ${suggestion}.${umbrella}`; + } 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/ThreadLaunchService.test.ts b/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts index 22a9ac59d55b6..d6f251deadfaf 100644 --- a/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts +++ b/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts @@ -143,6 +143,9 @@ interface HarnessOptions { 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 = {}) { @@ -210,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"), @@ -263,13 +266,13 @@ function makeHarness(options: HarnessOptions = {}) { ServerConfig.layerTest(process.cwd(), { prefix: "t3-thread-launch-" }).pipe( Layer.provide(NodeServices.layer), ), - options.umbrellaMembers === undefined + options.umbrellaMembers === undefined && options.umbrellaSuggestions === undefined ? Layer.empty : Layer.mock(UmbrellaMembership.UmbrellaMembership)({ stateOf: () => Effect.succeed({ - members: options.umbrellaMembers!, - suggestions: [], + members: options.umbrellaMembers ?? [], + suggestions: options.umbrellaSuggestions ?? [], enclosingRepository: null, }), umbrellasWithMember: () => [], @@ -3228,6 +3231,161 @@ it.effect("checks out every member of a plain umbrella folder into one thread fo }), ); +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").'); + assert.include(failure.message, "turn on Use as umbrella"); + } + }).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("accepts an umbrella base ref that only one of its checkouts has", () => + Effect.gen(function* () { + const harness = plainFolderHarness({ + umbrellaMembers: plainFolderCheckouts, + umbrellaSuggestions: [], + }); + 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({ + umbrellaMembers: plainFolderCheckouts, + umbrellaSuggestions: [], + 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 ef1b8e42eecd5..94333c33da798 100644 --- a/apps/server/src/orchestration-v2/ThreadLaunchService.ts +++ b/apps/server/src/orchestration-v2/ThreadLaunchService.ts @@ -51,6 +51,7 @@ import * as ProjectSetupScriptRunner from "../project/ProjectSetupScriptRunner.t 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"; @@ -172,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)), }, ) { override get message(): string { - return `Project "${this.projectTitle}" (${this.workspaceRoot}) is not a Git repository.`; + const base = `Project "${this.projectTitle}" (${this.workspaceRoot}) is not a Git repository.`; + const nested = this.nestedRepositories ?? []; + if (nested.length === 0) return base; + const names = nested.map((repository) => repository.relativePath).join(", "); + const holders = nested.filter((repository) => repository.hasBaseRef === true); + const located = + this.baseRef !== undefined && holders.length > 0 + ? ` "${this.baseRef}" is in ${holders + .map((repository) => + repository.projectTitle === undefined + ? repository.relativePath + : `${repository.relativePath} (project "${repository.projectTitle}")`, + ) + .join(", ")}.` + : ""; + return `${base} It holds Git repositories: ${names}.${located} To give each one a worktree, turn on Use as umbrella in this project's settings. 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, { @@ -276,6 +315,83 @@ const make = Effect.gen(function* () { Option.isNone(umbrellaMembership) ? Effect.succeed([]) : umbrellaMembership.value.stateOf(project).pipe(Effect.map((state) => state?.members ?? [])); + /** 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, so a refused worktree launch can say where to start instead. + const nestedRepositoriesOf = Effect.fn("ThreadLaunchService.nestedRepositoriesOf")(function* ( + project: { readonly id: ProjectId; readonly workspaceRoot: string }, + baseRef: string | undefined, + ) { + const state = Option.isNone(umbrellaMembership) + ? undefined + : yield* umbrellaMembership.value.stateOf(project); + const root = project.workspaceRoot.replaceAll("\\", "/").replace(/\/+$/, ""); + const checkouts = + state !== undefined + ? state.suggestions.map((member) => ({ + path: member.path, + relativePath: member.relativePath, + })) + : (yield* discoverNestedRepositories(project.workspaceRoot)).map((checkoutPath) => { + const normalized = checkoutPath.replaceAll("\\", "/"); + return { + path: checkoutPath, + relativePath: normalized.startsWith(`${root}/`) + ? normalized.slice(root.length + 1) + : normalized, + }; + }); + return yield* Effect.forEach( + checkouts.slice(0, MAX_REPORTED_NESTED_REPOSITORIES), + (checkout) => + Effect.all( + [ + projects + .getByWorkspaceRoot(checkout.path) + .pipe(Effect.orElseSucceed(() => Option.none())), + baseRef === undefined ? Effect.undefined : refResolvesLocally(checkout.path, baseRef), + ], + { concurrency: "unbounded" }, + ).pipe( + Effect.map(([owner, hasBaseRef]): NestedRepository => ({ + relativePath: checkout.relativePath, + ...(Option.isSome(owner) + ? { projectId: owner.value.id, projectTitle: owner.value.title } + : {}), + ...(hasBaseRef === undefined ? {} : { hasBaseRef }), + })), + ), + { concurrency: 4 }, + ); + }); // 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 @@ -408,37 +524,54 @@ const make = Effect.gen(function* () { ], { concurrency: "unbounded" }, ); - // Each member of a plain umbrella folder starts from its own checkout. - if (repositoryRoot === null && (yield* umbrellaMembersOf(project)).length > 0) return; - if (repositoryRoot === null) + const umbrellaMembers = yield* umbrellaMembersOf(project); + if (repositoryRoot === null && umbrellaMembers.length === 0) return yield* new ThreadLaunchNotRepositoryError({ projectId: project.id, projectTitle: project.title, workspaceRoot: cwd, + baseRef, + nestedRepositories: yield* nestedRepositoriesOf(project, baseRef), }); - const baseResolves = - hasBaseCommit || - (yield* Effect.gen(function* () { - if (strategy.startFromOrigin === true) { - const remote = yield* git.resolveWorktreeBaseRemote({ cwd, refName: baseRef }); - // The remote may have deleted the branch; ask it rather than trusting the name. - if ( - remote !== null && - (yield* git.fetchWorktreeBaseCommit({ cwd, refName: baseRef, remote })) !== null - ) - return true; - } - // git worktree add accepts remote-tracking branches; let Git decide when any matching ref exists. - if (yield* git.hasRefNamed({ cwd, refName: baseRef })) return true; - return !(yield* git.hasCommit({ cwd, refName: "HEAD" })); - }).pipe(Effect.orElseSucceed(() => true))); + const rootResolves = + repositoryRoot !== null && + (hasBaseCommit || + (yield* Effect.gen(function* () { + if (strategy.startFromOrigin === true) { + const remote = yield* git.resolveWorktreeBaseRemote({ cwd, refName: baseRef }); + // The remote may have deleted the branch; ask it rather than trusting the name. + if ( + remote !== null && + (yield* git.fetchWorktreeBaseCommit({ cwd, refName: baseRef, remote })) !== null + ) + return true; + } + // git worktree add accepts remote-tracking branches; let Git decide when any matching ref exists. + 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) }), }); + // A plain umbrella folder has no branches of its own to collide with. + if (repositoryRoot === null) return; // Provisioning flattens temporary names that collide, so only explicit names are refused. if (!checksBranch) return; const conflictingBranch = localBranches.find( @@ -685,6 +818,30 @@ const make = Effect.gen(function* () { })); yield* setupTracker.stageStatus(threadId, "checkout", "done"); } else if (input.workspaceStrategy.type === "worktree") { + // 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 ( + (yield* git + .repositoryRoot(project.workspaceRoot) + .pipe(Effect.orElseSucceed(() => undefined))) === null + ) { + return yield* mapError( + input, + "provision-worktree", + threadId, + )( + new ThreadLaunchNotRepositoryError({ + projectId: project.id, + projectTitle: project.title, + workspaceRoot: project.workspaceRoot, + baseRef: input.workspaceStrategy.baseRef, + nestedRepositories: yield* nestedRepositoriesOf( + project, + input.workspaceStrategy.baseRef, + ), + }), + ); + } if (runId !== null) { yield* threads .dispatch({ From 771886f7bf3f6d94c524d46a49ca91aa8f250240 Mon Sep 17 00:00:00 2001 From: Na0s Date: Wed, 18 Nov 2026 17:56:52 -0500 Subject: [PATCH 18/59] feat(web): gather an umbrella's threads under its name in the sidebar MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The default sidebar listed an umbrella's threads and its members' as unrelated cards, and a member thread read "northwind · api", leading with the umbrella. Active threads of an umbrella now gather at the place of its first thread under a row with its icon and name, indented slightly, and a member thread reads "api · northwind". Boring-mode folders already group them and are unchanged. Co-Authored-By: Claude Opus 5.5 --- apps/web/src/components/Sidebar.logic.test.ts | 50 ++++++++++++++++ apps/web/src/components/Sidebar.logic.ts | 42 +++++++++++++ apps/web/src/components/Sidebar.tsx | 60 ++++++++++++++++++- .../sidebar/SidebarProjectFolderHeader.tsx | 37 +++++++++++- .../components/sidebar/SidebarThreadRow.tsx | 13 +++- 5 files changed, 195 insertions(+), 7 deletions(-) diff --git a/apps/web/src/components/Sidebar.logic.test.ts b/apps/web/src/components/Sidebar.logic.test.ts index 2fa0d608b1f1d..f28f3c2421946 100644 --- a/apps/web/src/components/Sidebar.logic.test.ts +++ b/apps/web/src/components/Sidebar.logic.test.ts @@ -33,6 +33,7 @@ import { type SidebarListMarker, type SidebarSection, resolveSidebarDropVerb, + gatherUmbrellaThreads, groupSidebarThreadsByProject, resolveSidebarFolderDot, sidebarFolderExpansionKeys, @@ -1636,6 +1637,55 @@ describe("groupSidebarThreadsByProject", () => { }); }); +describe("gatherUmbrellaThreads", () => { + it("gathers each umbrella's own and member threads where its first thread is", () => { + 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>) => + gatherUmbrellaThreads(umbrellas, threads).map((run) => ({ + umbrella: run.umbrella?.projectKey ?? null, + threads: run.threads.map((entry) => entry.id), + })); + + 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"] }, + ]); + }); +}); + 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..0f0abb87b8700 100644 --- a/apps/web/src/components/Sidebar.logic.ts +++ b/apps/web/src/components/Sidebar.logic.ts @@ -1065,6 +1065,48 @@ 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. + */ +export function gatherUmbrellaThreads< + TGroup extends { + readonly memberProjectRefs: ReadonlyArray<{ + readonly environmentId: EnvironmentId; + readonly projectId: string; + }>; + }, + TThread extends Pick, +>( + umbrellas: readonly TGroup[], + threads: readonly TThread[], +): 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 runs: Array<{ readonly umbrella: TGroup | null; readonly threads: TThread[] }> = []; + const runByUmbrella = new Map(); + for (const thread of threads) { + 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 runs; +} + export type SidebarV2TopStatusKind = | "approval" | "done" diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index 755f638ebcbea..439b9047c69b2 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,6 +181,7 @@ import { import { applySidebarThreadDrop, filterSidebarV2VisibleThreads, + gatherUmbrellaThreads, groupSidebarThreadsByProject, sidebarFolderExpansionKeys, buildBulkTitleRegenerationContextMenuItem, @@ -278,6 +280,7 @@ import { } from "../umbrellaMembership.logic"; import { SidebarProjectFolderHeader, + SidebarUmbrellaHeader, sidebarFolderRowId, } from "./sidebar/SidebarProjectFolderHeader"; import { @@ -437,6 +440,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 of these gathers its Active threads under its name. + readonly umbrellaGroups: readonly SidebarProjectSnapshot[]; }) { const { projectScopeKey, @@ -449,6 +454,7 @@ function useSidebarThreads(input: { routeRowThreadKey, folderGroups, keepEmptyFolders: keepEmpty, + umbrellaGroups, } = input; // Folders already separate the work, so boring mode has no Working shelf. const workingShelfEnabled = @@ -500,8 +506,27 @@ function useSidebarThreads(input: { clockKey: `${nowMinute}:${snoozeWakeClock}:${inboxReturnsVersion}`, }); - const { pinnedThreads, activeThreads, workingThreads, snoozedThreads, settledThreads } = - partition; + const { pinnedThreads, workingThreads, snoozedThreads, settledThreads } = partition; + const umbrellaRuns = + folderGroups === null && umbrellaGroups.length > 0 + ? gatherUmbrellaThreads(umbrellaGroups, partition.activeThreads) + : null; + const activeThreads = umbrellaRuns + ? umbrellaRuns.flatMap((run) => run.threads) + : partition.activeThreads; + const activeUmbrellaByThreadKey = new Map< + string, + { readonly group: SidebarProjectSnapshot; readonly first: 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, + }); + } + } // 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), @@ -575,6 +600,8 @@ function useSidebarThreads(input: { } return { ...partition, + activeThreads, + activeUmbrellaByThreadKey, threads, workingShelfEnabled, searchableThreads: [ @@ -1331,6 +1358,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve draggableThreadKeys, activeReorderableThreadKeys, activeThreads, + activeUmbrellaByThreadKey, workingThreads, snoozedThreads, settledThreads, @@ -1378,6 +1406,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 @@ -2033,6 +2062,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"); @@ -3389,6 +3420,8 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve section: SidebarSection, // The tree row of the project folder this row sits in. folderRow?: string, + // Sits under an umbrella's name in the Active list. + nested = false, ) => { const threadKey = scopedThreadKey( scopeThreadRef(thread.environmentId, thread.id), @@ -3414,6 +3447,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve } thread={thread} variant={rowVariant} + nested={nested} navigationParent={ folderRow ?? (section === "working" || @@ -3524,7 +3558,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 !== undefined, + ), + ); continue; } if (projectFolders !== null && item.marker === "active-placeholder") { 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 0a1cdc953af6a..3d676d21127e6 100644 --- a/apps/web/src/components/sidebar/SidebarThreadRow.tsx +++ b/apps/web/src/components/sidebar/SidebarThreadRow.tsx @@ -552,6 +552,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. + nested?: boolean; navigationParent?: string | undefined; variantAction: SidebarSweepAction; settlementSupported: boolean; @@ -1440,6 +1442,7 @@ 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.nested && "ps-3", sortable?.isDragging && "relative z-20", )} > @@ -1482,10 +1485,14 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP - {props.projectDisplayName} {props.umbrellaMemberLabel ? ( - · {props.umbrellaMemberLabel} - ) : null} + <> + {props.umbrellaMemberLabel} + · {props.projectDisplayName} + + ) : ( + props.projectDisplayName + )} ) : ( From 5c5e72985a32796c0f139d851d0ff6da58038cab Mon Sep 17 00:00:00 2001 From: Na0s Date: Wed, 18 Nov 2026 17:57:39 -0500 Subject: [PATCH 19/59] feat(web): say what Use as umbrella does and mark the selected member tab The diff panel's prompt only counted the repositories, the confirmation only mentioned checkpoints, and nothing confirmed the change afterwards. The member tabs used ghost and secondary buttons that look alike in the light theme. The prompt names the repositories, the confirmation lists every effect, and a toast says the project is now an umbrella. Member tabs are underlined tabs with each member's icon; the selected one is bold with a dark underline. Co-Authored-By: Claude Opus 5.5 --- .../src/components/DiffPanel.browser.test.tsx | 1 + apps/web/src/components/DiffPanel.tsx | 45 ++++++++++++++----- .../src/hooks/useUmbrellaMembershipEdits.ts | 10 ++++- apps/web/src/umbrellaMembership.logic.test.ts | 3 +- apps/web/src/umbrellaMembership.logic.ts | 5 ++- 5 files changed, 49 insertions(+), 15 deletions(-) diff --git a/apps/web/src/components/DiffPanel.browser.test.tsx b/apps/web/src/components/DiffPanel.browser.test.tsx index 211378af8c9b1..34500b29d866c 100644 --- a/apps/web/src/components/DiffPanel.browser.test.tsx +++ b/apps/web/src/components/DiffPanel.browser.test.tsx @@ -111,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 1906036d4600c..c2ca1508276b6 100644 --- a/apps/web/src/components/DiffPanel.tsx +++ b/apps/web/src/components/DiffPanel.tsx @@ -14,7 +14,10 @@ import { type UmbrellaMember, } from "@t3tools/contracts"; import { scopedThreadKey } from "@t3tools/client-runtime/environment"; -import { umbrellaMembersForThread } from "@t3tools/client-runtime/state/umbrella"; +import { + umbrellaMemberLabel, + umbrellaMembersForThread, +} from "@t3tools/client-runtime/state/umbrella"; import { ArrowRightIcon, CheckIcon, @@ -28,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"; @@ -42,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, @@ -300,6 +305,7 @@ export default function DiffPanel({ 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 @@ -1374,10 +1380,11 @@ export default function DiffPanel({ {activeProject && umbrellaSuggestions.length > 0 ? (
    + {umbrellaSuggestions.length === 1 - ? "Found a repository in this folder." - : `Found ${umbrellaSuggestions.length} repositories in this folder.`} + ? `Found a repository in this folder: ${umbrellaSuggestionNames}.` + : `Found ${umbrellaSuggestions.length} repositories in this folder: ${umbrellaSuggestionNames}.`} + ); })}
    diff --git a/apps/web/src/hooks/useUmbrellaMembershipEdits.ts b/apps/web/src/hooks/useUmbrellaMembershipEdits.ts index 4fea3a205d6dc..f86defde94a52 100644 --- a/apps/web/src/hooks/useUmbrellaMembershipEdits.ts +++ b/apps/web/src/hooks/useUmbrellaMembershipEdits.ts @@ -5,6 +5,7 @@ import { removeUmbrellaMember, restoreUmbrellaMember, setUmbrellaEnabled, + umbrellaMemberLabel, } from "@t3tools/client-runtime/state/umbrella"; import type { ProjectSettingsOverrides, UmbrellaMember } from "@t3tools/contracts"; @@ -41,7 +42,14 @@ export function useUmbrellaMembershipEdits() { umbrellaConfirmationMessage(umbrella.title, umbrella.umbrellaSuggestions ?? []), { initialFocus: "confirm" }, ); - if (confirmed === true) edit(umbrella, (current) => setUmbrellaEnabled(current, true)); + if (confirmed !== true) return; + edit(umbrella, (current) => setUmbrellaEnabled(current, 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)), diff --git a/apps/web/src/umbrellaMembership.logic.test.ts b/apps/web/src/umbrellaMembership.logic.test.ts index cdae49a5a0ae5..9e0ff2582c4ab 100644 --- a/apps/web/src/umbrellaMembership.logic.test.ts +++ b/apps/web/src/umbrellaMembership.logic.test.ts @@ -113,9 +113,10 @@ describe("umbrellaConfirmationMessage", () => { ).toBe( [ "Use Acme as an umbrella?", - "Turns record checkpoints in these checkouts, and reverting a turn restores them:", + "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 index 53d560696003f..63922c880a59f 100644 --- a/apps/web/src/umbrellaMembership.logic.ts +++ b/apps/web/src/umbrellaMembership.logic.ts @@ -112,14 +112,15 @@ export function resolveUmbrellaMenuAction( return null; } -/** The confirmation that lists every checkout an umbrella will take in before it is turned on. */ +/** 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?`, - "Turns record checkpoints in these checkouts, and reverting a turn restores them:", + `${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"); } From ef8721240dc92ca6209faa526863ee0dea91d36b Mon Sep 17 00:00:00 2001 From: Na0s Date: Wed, 18 Nov 2026 17:58:36 -0500 Subject: [PATCH 20/59] feat(web): offer the umbrella at the top of a project's settings Detected checkouts were only listed in the Umbrella checkouts section near the bottom of the page. With the umbrella off and checkouts found, the project's page now opens with "3 projects detected within this folder: api, dev-setup, storefront. Use northwind as umbrella project?" and a button that goes through the same confirmation. Co-Authored-By: Claude Opus 5.5 --- .../settings/ProjectSettingsPanel.tsx | 3 +- .../settings/ProjectUmbrellaSettings.tsx | 82 +++++++++++++++---- 2 files changed, 66 insertions(+), 19 deletions(-) diff --git a/apps/web/src/components/settings/ProjectSettingsPanel.tsx b/apps/web/src/components/settings/ProjectSettingsPanel.tsx index c2038d361c7c0..fd3d3d31e0675 100644 --- a/apps/web/src/components/settings/ProjectSettingsPanel.tsx +++ b/apps/web/src/components/settings/ProjectSettingsPanel.tsx @@ -51,7 +51,7 @@ import { } from "./ProjectFaviconPickerDialog"; import { ProjectActionsSettings } from "./ProjectActionsSettings"; import { ProjectDefaultsSettings } from "./ProjectDefaultsSettings"; -import { ProjectUmbrellaSettings } from "./ProjectUmbrellaSettings"; +import { ProjectUmbrellaPrompt, ProjectUmbrellaSettings } from "./ProjectUmbrellaSettings"; import { defaultProjectIcon, hasDefaultProjectIcon, @@ -518,6 +518,7 @@ function ProjectDetail({ return ( <> + diff --git a/apps/web/src/components/settings/ProjectUmbrellaSettings.tsx b/apps/web/src/components/settings/ProjectUmbrellaSettings.tsx index f0a7bbe953552..1b8b9eeaa90ed 100644 --- a/apps/web/src/components/settings/ProjectUmbrellaSettings.tsx +++ b/apps/web/src/components/settings/ProjectUmbrellaSettings.tsx @@ -1,14 +1,14 @@ import { useAtomValue } from "@effect/atom-react"; import { AuthSettingsWriteScope, repositoryGroupingDisplayNameOf } from "@t3tools/contracts"; +import { umbrellaMemberLabel } from "@t3tools/client-runtime/state/umbrella"; +import { UmbrellaIcon } from "lucide-react"; import { Fragment, useState } from "react"; import { useUmbrellaMembershipEdits } from "../../hooks/useUmbrellaMembershipEdits"; -import type { - SidebarProjectGroupMember, - SidebarProjectSnapshot, -} from "../../sidebarProjectGrouping"; +import type { SidebarProjectSnapshot } from "../../sidebarProjectGrouping"; import { useEnvironments } from "../../state/environments"; import { useEnvironmentsWithScope } from "../../state/session"; +import { Alert, AlertAction, AlertDescription, AlertTitle } from "../ui/alert"; import { Badge } from "../ui/badge"; import { Button } from "../ui/button"; import { Input } from "../ui/input"; @@ -59,33 +59,79 @@ function UmbrellaAdoptForm(props: { ); } -/** Members, exclusions, and adoption for each project in the group that can hold checkouts. */ -export function ProjectUmbrellaSettings({ group }: { group: SidebarProjectSnapshot }) { +/** 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 edits = useUmbrellaMembershipEdits(); const umbrellas = group.memberProjects.filter( (project) => !project.isScratch && !group.foldedUmbrellaMembers.has(`${project.environmentId}:${project.id}`), ); const writableIds = useEnvironmentsWithScope(umbrellas, AuthSettingsWriteScope); - if (umbrellas.length === 0) return null; - - const rowsFor = (project: SidebarProjectGroupMember) => { + return umbrellas.map((project) => { const environment = shownEnvironments.find( (candidate) => candidate.environmentId === project.environmentId, ); - const environmentLabel = project.environmentLabel ?? environment?.label ?? "this environment"; const overrides = environment?.serverConfig?.settings.projectSettingsOverrides[project.id]; - const enabled = overrides?.umbrellaEnabled === true; - const excluded = overrides?.umbrellaExcludedPaths ?? []; - const suggestions = project.umbrellaSuggestions ?? []; - const disabled = - !writableIds.has(project.environmentId) || - environment?.connection.phase !== "connected" || - !environment.serverConfig; + 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 ( From 813596ad25658740086fa51e180d9f9a852728e2 Mon Sep 17 00:00:00 2001 From: Na0s Date: Wed, 18 Nov 2026 17:59:25 -0500 Subject: [PATCH 21/59] feat(web): list an umbrella above its matching members in palette search An umbrella searched as one row matching every member's name and path, with no sign of which member matched. Searches now list the umbrella as one line with its icon and name, and its members indented under it. Rows match by name: a member drops out once the query stops matching it, and the umbrella stays while any member matches or its own name does. A member with its own project opens that project; any other opens the umbrella. Co-Authored-By: Claude Opus 5.5 --- .../components/CommandPalette.logic.test.ts | 33 ++++++++++ .../src/components/CommandPalette.logic.ts | 48 ++++++++++++-- apps/web/src/components/CommandPalette.tsx | 12 +++- .../components/CommandPaletteProjectItems.tsx | 65 ++++++++++++++++++- .../src/components/CommandPaletteResults.tsx | 1 + 5 files changed, 149 insertions(+), 10 deletions(-) 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 94a6d97d75767..94f5e426538c1 100644 --- a/apps/web/src/components/CommandPalette.tsx +++ b/apps/web/src/components/CommandPalette.tsx @@ -809,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( @@ -855,6 +862,7 @@ function OpenCommandPaletteDialog(props: { projectGroupByTargetKey, locationByEnvironmentId: projectEnvironmentLocationById, runProject: openProjectFromSearch, + openMemberProject: (project) => openProjectFromSearch(project, { wholeGroup: false }), pin: projectPin, }), rowOrderKey("project"), 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..9072ed45e90b1 100644 --- a/apps/web/src/components/CommandPaletteResults.tsx +++ b/apps/web/src/components/CommandPaletteResults.tsx @@ -270,6 +270,7 @@ function CommandPaletteResultRow(props: { props.onExecuteItem(props.item); }} > + {props.item.parentValue === undefined ? null : } {props.item.icon} {props.item.description || props.item.threadContentMatch ? ( From 7b2318aeb6c21d97e2f8f6369e489395b48a5b29 Mon Sep 17 00:00:00 2001 From: Na0s Date: Wed, 18 Nov 2026 18:00:18 -0500 Subject: [PATCH 22/59] feat(web): name the member projects a turn's changed files are in A turn in an umbrella worktree that edited two members showed "2 changed files" with nothing in the header saying they span two projects. The card's header now reads "in 2 projects" followed by each member's icon and name, and the umbrella itself when files sit in its own repository. Co-Authored-By: Claude Opus 5.5 --- .../src/components/chat/ChangedFilesTree.tsx | 20 +++++++++++ .../components/chat/TimelineAssistantRows.tsx | 27 ++++++++++++++ .../client-runtime/src/state/umbrella.test.ts | 35 +++++++++++++++++++ packages/client-runtime/src/state/umbrella.ts | 27 ++++++++++++++ 4 files changed, 109 insertions(+) diff --git a/apps/web/src/components/chat/ChangedFilesTree.tsx b/apps/web/src/components/chat/ChangedFilesTree.tsx index 5023da3a7823f..7317d7576c93f 100644 --- a/apps/web/src/components/chat/ChangedFilesTree.tsx +++ b/apps/web/src/components/chat/ChangedFilesTree.tsx @@ -40,6 +40,10 @@ 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, named beside the count. */ + projects?: + | ReadonlyArray<{ readonly key: string; readonly label: string; readonly icon: ReactNode }> + | undefined; }) { const { runId, @@ -76,6 +80,22 @@ 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`} + + {props.projects.map((project) => ( + + {project.icon} + {project.label} + + ))} + + ) : null}
    {hasDirectories && ( diff --git a/apps/web/src/components/chat/TimelineAssistantRows.tsx b/apps/web/src/components/chat/TimelineAssistantRows.tsx index b62f6f8e4b10f..87f7cb637441d 100644 --- a/apps/web/src/components/chat/TimelineAssistantRows.tsx +++ b/apps/web/src/components/chat/TimelineAssistantRows.tsx @@ -14,6 +14,11 @@ import { HtmlRenderFrame } from "./HtmlRenderFrame"; import { McpAppFrame } from "./McpAppFrame"; import { checkpointFileTotals } from "@t3tools/client-runtime/state/thread-checkpoints"; import { ChangedFilesCard } from "./ChangedFilesTree"; +import { + umbrellaMemberLabel, + umbrellaMembersInFiles, +} from "@t3tools/client-runtime/state/umbrella"; +import { ProjectFavicon } from "../ProjectFavicon"; import { useFileContextMenuHandler } from "../../fileContextMenu"; import { readResponseSubagents, @@ -475,9 +480,31 @@ function AssistantChangedFilesSectionInner({ (status) => AsyncResult.getOrElse(status, () => null)?.workingTree.rootPath, ); + const umbrellaProjects = activeProject?.umbrellaMembers?.length + ? umbrellaMembersInFiles( + activeProject.umbrellaMembers, + checkpointFiles.map((file) => file.path), + Boolean(thread?.worktreePath), + ).map((member) => { + const project = member + ? { + environmentId: activeProject.environmentId, + workspaceRoot: member.path, + title: umbrellaMemberLabel(member), + } + : activeProject; + return { + key: member?.path ?? "", + label: project.title, + icon: , + }; + }) + : undefined; + return ( { }); }); +describe("umbrellaMembersInFiles", () => { + const members = [ + { relativePath: "api" }, + { relativePath: "apps" }, + { relativePath: "apps/web" }, + { relativePath: "../../design/site" }, + ]; + const labels = (touched: ReadonlyArray<{ relativePath: string } | null>) => + touched.map((member) => 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( + labels(umbrellaMembersInFiles(members, ["_external/site/index.html", "api/a.ts"], true)), + ).toEqual(["api", "../../design/site"]); + }); +}); + describe("umbrellaMembersForThread", () => { const members = [ { path: "/clients/acme/api", relativePath: "api" }, diff --git a/packages/client-runtime/src/state/umbrella.ts b/packages/client-runtime/src/state/umbrella.ts index 5e201fc153633..5ceb9d66e181b 100644 --- a/packages/client-runtime/src/state/umbrella.ts +++ b/packages/client-runtime/src/state/umbrella.ts @@ -46,6 +46,33 @@ export function umbrellaMembersForThread< })); } +/** + * The members a turn's files touch, in member order, matched by each file's path under the + * umbrella folder or, for a worktree-mode thread, its folder. Null leads when files sit in the + * umbrella's own repository, outside every member. + */ +export function umbrellaMembersInFiles>( + members: ReadonlyArray, + filePaths: ReadonlyArray, + worktreeMode: boolean, +): ReadonlyArray { + if (members.length === 0) return []; + const relativePaths = members.map((member) => member.relativePath); + const prefixes = (worktreeMode ? umbrellaWorktreeMemberPaths(relativePaths) : relativePaths).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 ? [null] : []), ...members.filter((_, index) => touched.has(index))]; +} + const isAbsolute = (value: string) => value.startsWith("/") || /^[A-Za-z]:[\\/]/.test(value); /** Settings may hold paths relative to the umbrella root; compare them resolved. */ From 58e71084b5ed881fb007abec26183de08185c7e3 Mon Sep 17 00:00:00 2001 From: Na0s Date: Wed, 18 Nov 2026 18:01:13 -0500 Subject: [PATCH 23/59] docs: describe the umbrella prompt, sidebar grouping and palette search Co-Authored-By: Claude Opus 5.5 --- docs/user/project-settings.md | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/docs/user/project-settings.md b/docs/user/project-settings.md index a594e425d8647..70f0c79b94384 100644 --- a/docs/user/project-settings.md +++ b/docs/user/project-settings.md @@ -71,9 +71,10 @@ API, a website, and copy or design files beside them. Add the folder as a projec 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 offers **Use as -umbrella**, and **Settings → Projects →** your project **→ Umbrella checkouts** lists them with a -**Use as umbrella** switch. Both show every repository that will join before you turn it on. +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. @@ -84,9 +85,10 @@ keeps it off. Reverting a turn restores only the members whose files differ from 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's sidebar row: the same folder on -the umbrella's machine, or the same repository on any connected machine. Their threads name the -member they belong to. Use **Add to umbrella** and **Remove _member_ from umbrella** from a project +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 lists the umbrella's active +threads and its members' together under its name, and a member's thread names its member first. +A command palette search lists the umbrella with its matching members 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 From 02b49c7eb2769fc0cc6c892248e0e50443f448fa Mon Sep 17 00:00:00 2001 From: Na0s Date: Wed, 18 Nov 2026 23:25:29 -0500 Subject: [PATCH 24/59] feat(web): keep sidebar threads that show a status out of their umbrella An umbrella gathered all its Active threads at the place of its first, so a member thread reading Done, Input, Waiting or Working moved away from where it would sit without the umbrella. A thread showing any status in the sidebar now keeps its own place, as if it had no umbrella, and joins the umbrella's other threads once it shows none. The row's Woke check moves into Sidebar.logic so both use the same rule. Co-Authored-By: Claude Opus 5.5 --- apps/web/src/components/Sidebar.logic.test.ts | 101 +++++++++++++----- apps/web/src/components/Sidebar.logic.ts | 39 ++++++- apps/web/src/components/Sidebar.tsx | 24 ++++- .../components/sidebar/SidebarThreadRow.tsx | 10 +- 4 files changed, 135 insertions(+), 39 deletions(-) diff --git a/apps/web/src/components/Sidebar.logic.test.ts b/apps/web/src/components/Sidebar.logic.test.ts index f28f3c2421946..7a2e01b41000a 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, @@ -331,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", () => { @@ -1638,34 +1662,37 @@ describe("groupSidebarThreadsByProject", () => { }); describe("gatherUmbrellaThreads", () => { - it("gathers each umbrella's own and member threads where its first thread is", () => { - 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>) => - gatherUmbrellaThreads(umbrellas, threads).map((run) => ({ - umbrella: run.umbrella?.projectKey ?? null, - threads: run.threads.map((entry) => entry.id), - })); + 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")), @@ -1684,6 +1711,26 @@ describe("gatherUmbrellaThreads", () => { { umbrella: null, threads: ["other-3"] }, ]); }); + + it("leaves a thread showing a status in its own place", () => { + 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: ["other-1"] }, + { umbrella: "northwind", threads: ["api-1", "northwind-1"] }, + { umbrella: null, threads: ["northwind-working"] }, + ]); + }); }); describe("resolveSidebarFolderDot", () => { diff --git a/apps/web/src/components/Sidebar.logic.ts b/apps/web/src/components/Sidebar.logic.ts index 0f0abb87b8700..304721b069a6f 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. @@ -1067,7 +1098,8 @@ export function groupSidebarThreadsByProject< /** * 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. + * at the place of its first thread, and every other thread is a run of one with no umbrella. A + * thread `gathers` rejects keeps its own place, as if it had no umbrella. */ export function gatherUmbrellaThreads< TGroup extends { @@ -1080,6 +1112,7 @@ export function gatherUmbrellaThreads< >( 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) { @@ -1090,7 +1123,9 @@ export function gatherUmbrellaThreads< const runs: Array<{ readonly umbrella: TGroup | null; readonly threads: TThread[] }> = []; const runByUmbrella = new Map(); for (const thread of threads) { - const umbrella = umbrellaByProject.get(`${thread.environmentId}:${thread.projectId}`); + const umbrella = gathers(thread) + ? umbrellaByProject.get(`${thread.environmentId}:${thread.projectId}`) + : undefined; if (umbrella === undefined) { runs.push({ umbrella: null, threads: [thread] }); continue; diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index 439b9047c69b2..5b162cd3c6185 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -183,6 +183,8 @@ import { filterSidebarV2VisibleThreads, gatherUmbrellaThreads, groupSidebarThreadsByProject, + resolveThreadLastVisitedAt, + sidebarRowShowsStatus, sidebarFolderExpansionKeys, buildBulkTitleRegenerationContextMenuItem, buildBulkUnpinContextMenuItem, @@ -440,7 +442,7 @@ 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 of these gathers its Active threads under its name. + // Outside boring mode, each gathers its Active threads that show no status in one place. readonly umbrellaGroups: readonly SidebarProjectSnapshot[]; }) { const { @@ -483,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, @@ -507,16 +510,31 @@ function useSidebarThreads(input: { }); const { pinnedThreads, workingThreads, snoozedThreads, settledThreads } = partition; + // A row showing a status keeps its place, as it would with no umbrella. const umbrellaRuns = folderGroups === null && umbrellaGroups.length > 0 - ? gatherUmbrellaThreads(umbrellaGroups, partition.activeThreads) + ? 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 group: SidebarProjectSnapshot; readonly first: boolean; readonly last: boolean } >(); for (const run of umbrellaRuns ?? []) { if (run.umbrella === null) continue; diff --git a/apps/web/src/components/sidebar/SidebarThreadRow.tsx b/apps/web/src/components/sidebar/SidebarThreadRow.tsx index 3d676d21127e6..057bec9dfa815 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, @@ -743,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, From ef659e466f9ead0fbf1fa5e89ca4909ba0b2a122 Mon Sep 17 00:00:00 2001 From: Na0s Date: Wed, 18 Nov 2026 23:26:13 -0500 Subject: [PATCH 25/59] feat(web): mark an umbrella's threads with its icon in the sidebar gutter An umbrella's gathered threads sat under a row holding its icon and name, which spent a row of the list on a label. The row is gone. The threads are indented 20px, and the gutter that leaves shows the umbrella's icon beside the first and a line down to the last. The icon is the umbrella's own, image or monogram, so it reads the same whatever icon the umbrella has, and each member thread already names the umbrella. Co-Authored-By: Claude Opus 5.5 --- apps/web/src/components/Sidebar.tsx | 29 +++++---------- .../sidebar/SidebarProjectFolderHeader.tsx | 37 +------------------ .../components/sidebar/SidebarThreadRow.tsx | 25 +++++++++++-- 3 files changed, 32 insertions(+), 59 deletions(-) diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index 5b162cd3c6185..cfeec1c596533 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -282,7 +282,6 @@ import { } from "../umbrellaMembership.logic"; import { SidebarProjectFolderHeader, - SidebarUmbrellaHeader, sidebarFolderRowId, } from "./sidebar/SidebarProjectFolderHeader"; import { @@ -542,6 +541,7 @@ function useSidebarThreads(input: { activeUmbrellaByThreadKey.set(threadShellKey(thread), { group: run.umbrella, first: index === 0, + last: index === run.threads.length - 1, }); } } @@ -2080,8 +2080,6 @@ 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"); @@ -3438,8 +3436,8 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve section: SidebarSection, // The tree row of the project folder this row sits in. folderRow?: string, - // Sits under an umbrella's name in the Active list. - nested = false, + // 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), @@ -3465,7 +3463,9 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve } thread={thread} variant={rowVariant} - nested={nested} + umbrella={umbrella?.group.memberProjects.find(isUmbrellaProject)} + umbrellaFirst={umbrella?.first} + umbrellaLast={umbrella?.last} navigationParent={ folderRow ?? (section === "working" || @@ -3576,25 +3576,14 @@ 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; - 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 !== undefined, + item.section === "active" + ? activeUmbrellaByThreadKey.get(item.key) + : undefined, ), ); continue; diff --git a/apps/web/src/components/sidebar/SidebarProjectFolderHeader.tsx b/apps/web/src/components/sidebar/SidebarProjectFolderHeader.tsx index f4d68a0946d69..b438db4e6a111 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, UmbrellaIcon } from "lucide-react"; +import { ChevronDownIcon, SquarePenIcon } from "lucide-react"; import { memo } from "react"; import { cn } from "~/lib/utils"; @@ -129,38 +129,3 @@ 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 057bec9dfa815..cc6da58037269 100644 --- a/apps/web/src/components/sidebar/SidebarThreadRow.tsx +++ b/apps/web/src/components/sidebar/SidebarThreadRow.tsx @@ -553,8 +553,11 @@ 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. - nested?: boolean; + // Indents the row among its umbrella's threads, with the umbrella's icon in the gutter of the + // first and a line down to the last. + umbrella?: ProjectFaviconProject | undefined; + umbrellaFirst?: boolean | undefined; + umbrellaLast?: boolean | undefined; navigationParent?: string | undefined; variantAction: SidebarSweepAction; settlementSupported: boolean; @@ -1438,10 +1441,26 @@ 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.nested && "ps-3", + props.umbrella && "relative ps-5", sortable?.isDragging && "relative z-20", )} > + {props.umbrella && props.umbrellaFirst ? ( + + ) : null} + {props.umbrella ? ( + + ) : null} Date: Wed, 18 Nov 2026 23:26:33 -0500 Subject: [PATCH 26/59] feat(web): indent umbrella members in palette search as far as the sidebar A member row under its umbrella in a palette search sat 24px in, while the sidebar indents an umbrella's threads 20px. Both now use 20px. Co-Authored-By: Claude Opus 5.5 --- apps/web/src/components/CommandPaletteResults.tsx | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/apps/web/src/components/CommandPaletteResults.tsx b/apps/web/src/components/CommandPaletteResults.tsx index 9072ed45e90b1..9f5ddde3d0689 100644 --- a/apps/web/src/components/CommandPaletteResults.tsx +++ b/apps/web/src/components/CommandPaletteResults.tsx @@ -270,7 +270,8 @@ function CommandPaletteResultRow(props: { props.onExecuteItem(props.item); }} > - {props.item.parentValue === undefined ? null : } + {/* With the row's gap, 20px: the sidebar's indent for an umbrella's threads. */} + {props.item.parentValue === undefined ? null : } {props.item.icon} {props.item.description || props.item.threadContentMatch ? ( From c4629622c7ce2da1ba79bd51e10e94a7e28a1c5f Mon Sep 17 00:00:00 2001 From: Na0s Date: Wed, 18 Nov 2026 23:26:48 -0500 Subject: [PATCH 27/59] feat(web): name each member project after its folder in a turn's changed files A worktree turn across members listed every member's icon and name after "in 2 projects" in the card's header, apart from the folders they belong to. The header keeps the count, and each member's icon and name now follow its folder's row, including a compacted row such as "api/src" and an adopted member under "_external". Co-Authored-By: Claude Opus 5.5 --- .../src/components/chat/ChangedFilesTree.tsx | 42 +++++++++++-------- .../chat/MessagesTimeline.browser.test.tsx | 30 +++++++++++++ .../components/chat/TimelineAssistantRows.tsx | 4 +- .../client-runtime/src/state/umbrella.test.ts | 14 +++++-- packages/client-runtime/src/state/umbrella.ts | 20 +++++---- 5 files changed, 79 insertions(+), 31 deletions(-) diff --git a/apps/web/src/components/chat/ChangedFilesTree.tsx b/apps/web/src/components/chat/ChangedFilesTree.tsx index 7317d7576c93f..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,10 +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, named beside the count. */ - projects?: - | ReadonlyArray<{ readonly key: string; readonly label: string; readonly icon: ReactNode }> - | undefined; + /** The umbrella's projects the files are in, counted beside the totals. */ + projects?: ReadonlyArray | undefined; }) { const { runId, @@ -81,19 +86,8 @@ export const ChangedFilesCard = memo(function ChangedFilesCard(props: { /> )} {props.projects && props.projects.length > 0 ? ( - - - in {props.projects.length === 1 ? "1 project" : `${props.projects.length} projects`} - - {props.projects.map((project) => ( - - {project.icon} - {project.label} - - ))} + + in {props.projects.length === 1 ? "1 project" : `${props.projects.length} projects`} ) : null}
    @@ -155,6 +149,7 @@ export const ChangedFilesCard = memo(function ChangedFilesCard(props: { resolvedTheme={resolvedTheme} onOpenTurnDiff={onOpenTurnDiff} onFileContextMenu={onFileContextMenu} + projects={props.projects} /> {hiddenFileCount > 0 && (
    @@ -180,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; @@ -220,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 (