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/<hex>-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 <[email protected]>
This commit is contained in:
Theo BrowneandClaude Fable 5 committed 2026-07-13 20:20:25 -07:00
1 parent 590103ee7f
commit 233e0b45ce
8 files changed
+85 -23

No files matched your search

@@ -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) => {
+6 -3
View File
@@ -108,10 +108,13 @@ export const make = Effect.gen(function* () {
const runDedupedFetch = (cwd: string): Effect.Effect<boolean> =>
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<boolean>();
// 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<boolean>();
state.inFlight = inFlight;
return yield* gitWorkflow.fetchRemote({ cwd, remoteName: "origin" }).pipe(
Effect.flatMap(() =>
+9 -3
View File
@@ -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<void> =>
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) =>
+5 -1
View File
@@ -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),
);
@@ -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,
+33 -14
View File
@@ -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,
+5
View File
@@ -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);
+5 -1
View File
@@ -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.