From 233e0b45ce84906029056b5c14093dfdcea0830f Mon Sep 17 00:00:00 2001 From: Theo Browne Date: Mon, 13 Jul 2026 20:20:25 -0700 Subject: [PATCH] Address review bot findings - Share a single WorktreeRegistry instance between the deletion reactor and the ws layer (previously two instances with divergent in-memory state). - WorktreeRegistry: take the semaphore for reads too so a first-access disk load can't clobber a concurrent mutation, and only update the in-memory registry after the persist succeeds. - WorktreeBasePlanner: claim the in-flight fetch slot synchronously so concurrent pin/prefetch calls can't start duplicate fetches. - Recognize uniquified retry suffixes (t3code/-N) as temporary worktree branches so auto-rename still applies after a partial bootstrap retry. - Re-derive startFromOrigin when a draft's mode flips via branch selection, and when a stored draft is reused for a different project member; the reused draft also re-derives its surface default instead of inheriting the store's hard-coded local reset. - Mobile waits for environment settings before auto-persisting a workspace selection, so the pre-config fallback can't freeze the wrong default. Co-Authored-By: Claude Fable 5 --- .../threads/new-task-flow-provider.tsx | 9 +++- apps/server/src/git/WorktreeBasePlanner.ts | 9 ++-- apps/server/src/git/WorktreeRegistry.ts | 12 +++-- apps/server/src/server.ts | 6 ++- .../BranchToolbarBranchSelector.tsx | 14 ++++++ apps/web/src/hooks/useHandleNewThread.ts | 47 +++++++++++++------ packages/shared/src/git.test.ts | 5 ++ packages/shared/src/git.ts | 6 ++- 8 files changed, 85 insertions(+), 23 deletions(-) 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 4267354676..19085db46a 100644 --- a/apps/mobile/src/features/threads/new-task-flow-provider.tsx +++ b/apps/mobile/src/features/threads/new-task-flow-provider.tsx @@ -617,6 +617,13 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) { if (workspaceMode !== "worktree" || selectedBranchName !== null) { return; } + // Wait for the environment's settings before auto-writing a workspace + // selection: selectBranch persists the current mode into the draft, and + // doing that against the pre-config fallback would freeze the wrong + // default once the real settings arrive. + if (environmentSettings === undefined) { + return; + } const preferredBranch = availableBranches.find((branch) => branch.current) ?? availableBranches.find((branch) => branch.isDefault) ?? @@ -624,7 +631,7 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) { if (preferredBranch) { selectBranch(preferredBranch); } - }, [availableBranches, selectBranch, selectedBranchName, workspaceMode]); + }, [availableBranches, environmentSettings, selectBranch, selectedBranchName, workspaceMode]); const setRuntimeMode = useCallback( (value: RuntimeMode) => { diff --git a/apps/server/src/git/WorktreeBasePlanner.ts b/apps/server/src/git/WorktreeBasePlanner.ts index 6d1c74fb23..45d6911163 100644 --- a/apps/server/src/git/WorktreeBasePlanner.ts +++ b/apps/server/src/git/WorktreeBasePlanner.ts @@ -108,10 +108,13 @@ export const make = Effect.gen(function* () { const runDedupedFetch = (cwd: string): Effect.Effect => Effect.gen(function* () { const state = getState(cwd); - if (state.inFlight) { - return yield* Deferred.await(state.inFlight); + const existingInFlight = state.inFlight; + if (existingInFlight) { + return yield* Deferred.await(existingInFlight); } - const inFlight = yield* Deferred.make(); + // Claim the slot synchronously (no suspension between the check above + // and this assignment) so concurrent callers can't both start a fetch. + const inFlight = Deferred.makeUnsafe(); state.inFlight = inFlight; return yield* gitWorkflow.fetchRemote({ cwd, remoteName: "origin" }).pipe( Effect.flatMap(() => diff --git a/apps/server/src/git/WorktreeRegistry.ts b/apps/server/src/git/WorktreeRegistry.ts index 4f56794401..92c3e1daf7 100644 --- a/apps/server/src/git/WorktreeRegistry.ts +++ b/apps/server/src/git/WorktreeRegistry.ts @@ -83,7 +83,9 @@ export const make = Effect.gen(function* () { return decoded.value; }); - const getRegistry = Effect.gen(function* () { + // All reads and writes take the semaphore so a first-access disk load can + // never overwrite in-memory state that a concurrent mutation just wrote. + const getRegistryLocked = Effect.gen(function* () { const loaded = yield* Ref.get(loadedRef); if (loaded !== null) { return loaded; @@ -93,14 +95,15 @@ export const make = Effect.gen(function* () { return fromDisk; }); + const getRegistry = Semaphore.withPermit(writeSemaphore)(getRegistryLocked); + const mutate = ( update: (current: WorktreeRegistryFile) => WorktreeRegistryFile, ): Effect.Effect => Semaphore.withPermit(writeSemaphore)( Effect.gen(function* () { - const current = yield* getRegistry; + const current = yield* getRegistryLocked; const next = update(current); - yield* Ref.set(loadedRef, next); const contents = yield* encodeRegistryJson(next); yield* writeFileStringAtomically({ filePath: worktreeRegistryPath, @@ -109,6 +112,9 @@ export const make = Effect.gen(function* () { Effect.provideService(FileSystem.FileSystem, fs), Effect.provideService(Path.Path, path), ); + // Memory reflects disk only after the persist succeeds, so `list` + // never reports an association that was never durably recorded. + yield* Ref.set(loadedRef, next); }), ).pipe( Effect.catchCause((cause) => diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index 63d4b1d8de..5ff65f85c7 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -163,7 +163,11 @@ const ReactorLayerLive = Layer.empty.pipe( Layer.provideMerge(ProviderRuntimeIngestionLive), Layer.provideMerge(ProviderCommandReactorLive), Layer.provideMerge(CheckpointReactorLive), - Layer.provideMerge(ThreadDeletionReactorLive.pipe(Layer.provide(WorktreeRegistry.layer))), + // WorktreeRegistry is deliberately NOT provided here: the reactor must + // share the single instance from VcsLayerLive (provided downstream in + // RuntimeCoreDependenciesLive) so bootstrap registrations and deletion + // markings see the same in-memory state. + Layer.provideMerge(ThreadDeletionReactorLive), Layer.provideMerge(AgentAwarenessRelay.layer.pipe(Layer.provide(ServerSecretStore.layer))), Layer.provideMerge(RuntimeReceiptBusLive), ); diff --git a/apps/web/src/components/BranchToolbarBranchSelector.tsx b/apps/web/src/components/BranchToolbarBranchSelector.tsx index e2ee24c360..2c218b48f8 100644 --- a/apps/web/src/components/BranchToolbarBranchSelector.tsx +++ b/apps/web/src/components/BranchToolbarBranchSelector.tsx @@ -38,6 +38,8 @@ import { resolveEffectiveEnvMode, shouldIncludeBranchPickerItem, } from "./BranchToolbar.logic"; +import { useEnvironmentSettings } from "../hooks/useSettings"; +import { resolveNewDraftStartFromOrigin } from "../lib/chatThreadActions"; import { ChangeRequestStatusIcon, prStatusIndicator, @@ -107,6 +109,7 @@ export function BranchToolbarBranchSelector({ onComposerFocusRequest, }: BranchToolbarBranchSelectorProps) { const startFromOriginSwitchId = useId(); + const settings = useEnvironmentSettings(environmentId); const stopThreadSession = useAtomCommand(threadEnvironment.stopSession, "thread session stop"); const updateThreadMetadata = useAtomCommand( threadEnvironment.updateMetadata, @@ -191,6 +194,16 @@ export function BranchToolbarBranchSelector({ branch, worktreePath, envMode: nextDraftEnvMode, + // Mode changes re-derive the origin pin from settings so a draft + // flipped into worktree mode here doesn't silently skip the fetch. + ...(nextDraftEnvMode !== effectiveEnvMode + ? { + startFromOrigin: resolveNewDraftStartFromOrigin({ + envMode: nextDraftEnvMode, + newWorktreesStartFromOrigin: settings.newWorktreesStartFromOrigin, + }), + } + : {}), projectRef: scopeProjectRef(environmentId, activeProject.id), }); }, @@ -202,6 +215,7 @@ export function BranchToolbarBranchSelector({ hasServerThread, onActiveThreadBranchOverrideChange, setDraftThreadContext, + settings.newWorktreesStartFromOrigin, draftId, threadRef, environmentId, diff --git a/apps/web/src/hooks/useHandleNewThread.ts b/apps/web/src/hooks/useHandleNewThread.ts index 112df727b5..d434b8acfe 100644 --- a/apps/web/src/hooks/useHandleNewThread.ts +++ b/apps/web/src/hooks/useHandleNewThread.ts @@ -80,6 +80,17 @@ export function useNewThreadHandler() { const hasWorktreePathOption = options?.worktreePath !== undefined; const hasEnvModeOption = options?.envMode !== undefined; const hasStartFromOriginOption = options?.startFromOrigin !== undefined; + // The default mode derives from the surface (attached checkout → + // local, detached → worktree) unless a project override or an explicit + // setting pins a mode. Draft exceptions never retrain this default — + // only the project override ("Always for this project") does, and only + // through an explicit settings write. + const resolveDefaultEnvMode = (): DraftThreadEnvMode => + projectThreadEnvModeOverrides[scopedProjectKey(projectRef)] ?? + resolveSurfaceThreadEnvMode({ + settings: environmentSettings, + target: environmentPresentationById.get(projectRef.environmentId)?.entry.target ?? null, + }); const storedDraftThread = getDraftSessionByLogicalProjectKey(logicalProjectKey); const storedDraftThreadRef = storedDraftThread ? scopeThreadRef(storedDraftThread.environmentId, storedDraftThread.threadId) @@ -96,6 +107,14 @@ export function useNewThreadHandler() { ? getDraftThread(currentRouteTarget.threadRef) : getDraftSession(currentRouteTarget.draftId) : null; + // Reusing a stored draft for a different project member must re-derive + // the mode from that member's default — otherwise the store's + // project-changed reset hard-codes "local" regardless of surface. + const storedDraftProjectChanged = + reusableStoredDraftThread !== null && + reusableStoredDraftThread !== undefined && + (reusableStoredDraftThread.environmentId !== projectRef.environmentId || + reusableStoredDraftThread.projectId !== projectRef.projectId); if (reusableStoredDraftThread) { return (async () => { if ( @@ -117,6 +136,19 @@ export function useNewThreadHandler() { reusableStoredDraftThread.draftId, { threadId: reusableStoredDraftThread.threadId, + ...(storedDraftProjectChanged && !hasEnvModeOption + ? (() => { + const envMode = resolveDefaultEnvMode(); + return { + envMode, + startFromOrigin: resolveNewDraftStartFromOrigin({ + envMode, + newWorktreesStartFromOrigin: + environmentSettings.newWorktreesStartFromOrigin, + }), + }; + })() + : {}), }, ); if ( @@ -167,20 +199,7 @@ export function useNewThreadHandler() { const draftId = newDraftId(); const threadId = newThreadId(); const createdAt = new Date().toISOString(); - // The default mode derives from the surface (attached checkout → - // local, detached → worktree) unless a project override or an explicit - // setting pins a mode. Draft exceptions never retrain this default — - // only the project override ("Always for this project") does, and only - // through an explicit settings write. - const projectEnvModeOverride = - projectThreadEnvModeOverrides[scopedProjectKey(projectRef)] ?? null; - const initialEnvMode = - options?.envMode ?? - projectEnvModeOverride ?? - resolveSurfaceThreadEnvMode({ - settings: environmentSettings, - target: environmentPresentationById.get(projectRef.environmentId)?.entry.target ?? null, - }); + const initialEnvMode = options?.envMode ?? resolveDefaultEnvMode(); return (async () => { setLogicalProjectDraftThreadId(logicalProjectKey, projectRef, draftId, { threadId, diff --git a/packages/shared/src/git.test.ts b/packages/shared/src/git.test.ts index 2c02f77e4a..c8b6c067e9 100644 --- a/packages/shared/src/git.test.ts +++ b/packages/shared/src/git.test.ts @@ -72,6 +72,11 @@ describe("isTemporaryWorktreeBranch", () => { expect(isTemporaryWorktreeBranch(`${WORKTREE_BRANCH_PREFIX}/DEADBEEF`)).toBe(true); }); + it("matches uniquified retry suffixes on thread-derived branches", () => { + expect(isTemporaryWorktreeBranch(`${WORKTREE_BRANCH_PREFIX}/deadbeef-2`)).toBe(true); + expect(isTemporaryWorktreeBranch(`${WORKTREE_BRANCH_PREFIX}/deadbeef-10`)).toBe(true); + }); + it("rejects non-temporary refName names", () => { expect(isTemporaryWorktreeBranch(`${WORKTREE_BRANCH_PREFIX}/feature/demo`)).toBe(false); expect(isTemporaryWorktreeBranch("main")).toBe(false); diff --git a/packages/shared/src/git.ts b/packages/shared/src/git.ts index 1a63269625..dc9b23e25a 100644 --- a/packages/shared/src/git.ts +++ b/packages/shared/src/git.ts @@ -11,7 +11,11 @@ import * as Result from "effect/Result"; import { detectSourceControlProviderFromRemoteUrl } from "./sourceControl.ts"; export const WORKTREE_BRANCH_PREFIX = "t3code"; -const TEMP_WORKTREE_BRANCH_PATTERN = new RegExp(`^${WORKTREE_BRANCH_PREFIX}\\/[0-9a-f]{8}$`); +// Optional `-N` suffix: bootstrap retries uniquify a taken thread-derived +// branch name (t3code/a1b2c3d4-2), and those are still temporary branches. +const TEMP_WORKTREE_BRANCH_PATTERN = new RegExp( + `^${WORKTREE_BRANCH_PREFIX}\\/[0-9a-f]{8}(-\\d+)?$`, +); /** * Sanitize an arbitrary string into a valid, lowercase git refName fragment.