Skip to content

Commit 7190bf2

Browse files
fix(server): restore worktree branch naming in the v2 orchestrator
The v2 launch path only generated a branch name when no branch was passed, but the web client always passed a temporary t3code/<hash> branch — so the guard never fired and threads kept the hash as their branch, with no later rename pass (unlike v1). The server now owns worktree naming: without an explicit branch, the worktree is provisioned immediately under a server-invented temporary t3code/<hash> name, then renamed to a generated name in a background fork so name generation never delays provisioning or the provider turn. Temporary names from clients that still send them (mobile outbox) are renamed the same way, and stick if generation fails. The web client stops inventing temporary branch names. Co-Authored-By: Claude Fable 5 <[email protected]>
1 parent f76271d commit 7190bf2

3 files changed

Lines changed: 245 additions & 39 deletions

File tree

‎apps/server/src/orchestration-v2/ThreadLaunchService.test.ts‎

Lines changed: 176 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,7 @@ const adapter = {
6767

6868
interface HarnessOptions {
6969
readonly createWorktree?: GitWorkflow.GitWorkflowService["Service"]["createWorktree"];
70+
readonly renameBranch?: GitWorkflow.GitWorkflowService["Service"]["renameBranch"];
7071
readonly runSetup?: ProjectSetupScriptRunner.ProjectSetupScriptRunner["Service"]["runForThread"];
7172
readonly generateTitle?: TextGeneration.TextGeneration["Service"]["generateThreadTitle"];
7273
readonly generateBranchName?: TextGeneration.TextGeneration["Service"]["generateBranchName"];
@@ -87,11 +88,14 @@ function makeHarness(options: HarnessOptions = {}) {
8788
const outbox = EffectOutbox.layer.pipe(Layer.provide(database));
8889
const createWorktree = vi.fn(
8990
options.createWorktree ??
90-
(() =>
91+
((input) =>
9192
Effect.succeed({
92-
worktree: { path: "/repo-worktrees/feature", refName: "feature", headSha: "abc" },
93+
worktree: { path: "/repo-worktrees/feature", refName: input.newRefName, headSha: "abc" },
9394
} as never)),
9495
);
96+
const renameBranch = vi.fn(
97+
options.renameBranch ?? ((input) => Effect.succeed({ branch: input.newBranch })),
98+
);
9599
const runSetup = vi.fn(
96100
options.runSetup ?? (() => Effect.succeed({ status: "no-script" as const })),
97101
);
@@ -113,6 +117,7 @@ function makeHarness(options: HarnessOptions = {}) {
113117
}),
114118
Layer.mock(GitWorkflow.GitWorkflowService)({
115119
createWorktree,
120+
renameBranch,
116121
fetchRemote: () => Effect.void,
117122
removeWorktree: () => Effect.void,
118123
resolveRemoteTrackingCommit: () =>
@@ -154,6 +159,7 @@ function makeHarness(options: HarnessOptions = {}) {
154159
return {
155160
layer: Layer.mergeAll(launch, threadManagement, titleRegeneration, outbox, database),
156161
createWorktree,
162+
renameBranch,
157163
generateBranchName,
158164
generateThreadTitle,
159165
runSetup,
@@ -721,6 +727,174 @@ it.effect("falls back when the source control writer is unavailable", () =>
721727
}),
722728
);
723729

730+
it.effect("names the worktree itself when the client provides no branch", () =>
731+
Effect.gen(function* () {
732+
const harness = makeHarness();
733+
yield* Effect.gen(function* () {
734+
const launches = yield* ThreadLaunch.ThreadLaunchService;
735+
const threads = yield* ThreadManagement.ThreadManagementService;
736+
const launched = yield* launches.launch(
737+
launchInput({
738+
command: "command:launch:server-named-branch",
739+
thread: "thread:launch:server-named-branch",
740+
message: "Build the feature",
741+
workspace: { type: "worktree", baseRef: "main" },
742+
}),
743+
);
744+
yield* waitUntil(() => Effect.sync(() => harness.createWorktree.mock.calls.length === 1));
745+
assert.match(
746+
harness.createWorktree.mock.calls[0]?.[0].newRefName ?? "",
747+
/^t3code\/[0-9a-f]{8}$/u,
748+
);
749+
yield* waitUntil(() =>
750+
threads
751+
.getThreadProjection(launched.threadId)
752+
.pipe(Effect.map((projection) => projection.thread.branch === "generated-branch")),
753+
);
754+
}).pipe(Effect.provide(harness.layer));
755+
}),
756+
);
757+
758+
it.effect("renames a temporary t3code/<hash> branch off the provisioning critical path", () =>
759+
Effect.gen(function* () {
760+
const branchNameStarted = yield* Deferred.make<void>();
761+
const allowBranchName = yield* Deferred.make<void>();
762+
const harness = makeHarness({
763+
createWorktree: (input) =>
764+
Effect.succeed({
765+
worktree: { path: "/repo-worktrees/temp", refName: input.newRefName, headSha: "abc" },
766+
} as never),
767+
generateBranchName: () =>
768+
Deferred.succeed(branchNameStarted, undefined).pipe(
769+
Effect.andThen(Deferred.await(allowBranchName)),
770+
Effect.as({ branch: "generated-branch" }),
771+
),
772+
});
773+
yield* Effect.gen(function* () {
774+
const launches = yield* ThreadLaunch.ThreadLaunchService;
775+
const threads = yield* ThreadManagement.ThreadManagementService;
776+
const launched = yield* launches.launch(
777+
launchInput({
778+
command: "command:launch:temp-branch",
779+
thread: "thread:launch:temp-branch",
780+
message: "Build the feature",
781+
workspace: { type: "worktree", baseRef: "main", branch: "t3code/abcd1234" },
782+
}),
783+
);
784+
yield* Deferred.await(branchNameStarted);
785+
assert.equal(harness.createWorktree.mock.calls[0]?.[0].newRefName, "t3code/abcd1234");
786+
yield* waitUntil(() =>
787+
threads
788+
.getThreadProjection(launched.threadId)
789+
.pipe(Effect.map((projection) => projection.runs[0]?.status === "starting")),
790+
);
791+
assert.equal(
792+
(yield* threads.getThreadProjection(launched.threadId)).thread.branch,
793+
"t3code/abcd1234",
794+
);
795+
yield* Deferred.succeed(allowBranchName, undefined);
796+
yield* waitUntil(() =>
797+
threads
798+
.getThreadProjection(launched.threadId)
799+
.pipe(Effect.map((projection) => projection.thread.branch === "generated-branch")),
800+
);
801+
assert.deepEqual(harness.renameBranch.mock.calls[0]?.[0], {
802+
cwd: "/repo-worktrees/temp",
803+
oldBranch: "t3code/abcd1234",
804+
newBranch: "generated-branch",
805+
});
806+
}).pipe(Effect.provide(harness.layer));
807+
}),
808+
);
809+
810+
it.effect("keeps an explicit branch name instead of generating one", () =>
811+
Effect.gen(function* () {
812+
const harness = makeHarness();
813+
yield* Effect.gen(function* () {
814+
const launches = yield* ThreadLaunch.ThreadLaunchService;
815+
yield* launches.launch(
816+
launchInput({
817+
command: "command:launch:explicit-branch",
818+
thread: "thread:launch:explicit-branch",
819+
message: "Build the feature",
820+
workspace: { type: "worktree", baseRef: "main", branch: "my-feature" },
821+
}),
822+
);
823+
yield* waitUntil(() => Effect.sync(() => harness.createWorktree.mock.calls.length === 1));
824+
assert.equal(harness.generateBranchName.mock.calls.length, 0);
825+
assert.equal(harness.createWorktree.mock.calls[0]?.[0].newRefName, "my-feature");
826+
}).pipe(Effect.provide(harness.layer));
827+
}),
828+
);
829+
830+
it.effect("keeps the temporary branch when branch generation fails", () =>
831+
Effect.gen(function* () {
832+
const harness = makeHarness({
833+
createWorktree: (input) =>
834+
Effect.succeed({
835+
worktree: { path: "/repo-worktrees/temp", refName: input.newRefName, headSha: "abc" },
836+
} as never),
837+
generateBranchName: () => Effect.die("branch generation is down"),
838+
});
839+
yield* Effect.gen(function* () {
840+
const launches = yield* ThreadLaunch.ThreadLaunchService;
841+
const threads = yield* ThreadManagement.ThreadManagementService;
842+
const launched = yield* launches.launch(
843+
launchInput({
844+
command: "command:launch:branch-fallback",
845+
thread: "thread:launch:branch-fallback",
846+
message: "Build the feature",
847+
workspace: { type: "worktree", baseRef: "main", branch: "t3code/abcd1234" },
848+
}),
849+
);
850+
yield* waitUntil(() => Effect.sync(() => harness.generateBranchName.mock.calls.length === 1));
851+
assert.equal(harness.createWorktree.mock.calls[0]?.[0].newRefName, "t3code/abcd1234");
852+
yield* waitUntil(() =>
853+
threads
854+
.getThreadProjection(launched.threadId)
855+
.pipe(Effect.map((projection) => projection.runs[0]?.status === "starting")),
856+
);
857+
assert.equal(harness.renameBranch.mock.calls.length, 0);
858+
assert.equal(
859+
(yield* threads.getThreadProjection(launched.threadId)).thread.branch,
860+
"t3code/abcd1234",
861+
);
862+
}).pipe(Effect.provide(harness.layer));
863+
}),
864+
);
865+
866+
it.effect("renames a temporary branch on an existing worktree to a generated name", () =>
867+
Effect.gen(function* () {
868+
const harness = makeHarness();
869+
yield* Effect.gen(function* () {
870+
const launches = yield* ThreadLaunch.ThreadLaunchService;
871+
const threads = yield* ThreadManagement.ThreadManagementService;
872+
const launched = yield* launches.launch(
873+
launchInput({
874+
command: "command:launch:existing-worktree-rename",
875+
thread: "thread:launch:existing-worktree-rename",
876+
message: "Build the feature",
877+
workspace: {
878+
type: "existing_worktree",
879+
worktreePath: "/repo-worktrees/t3code-abcd1234",
880+
branch: "t3code/abcd1234",
881+
},
882+
}),
883+
);
884+
yield* waitUntil(() =>
885+
threads
886+
.getThreadProjection(launched.threadId)
887+
.pipe(Effect.map((projection) => projection.thread.branch === "generated-branch")),
888+
);
889+
assert.deepEqual(harness.renameBranch.mock.calls[0]?.[0], {
890+
cwd: "/repo-worktrees/t3code-abcd1234",
891+
oldBranch: "t3code/abcd1234",
892+
newBranch: "generated-branch",
893+
});
894+
}).pipe(Effect.provide(harness.layer));
895+
}),
896+
);
897+
724898
for (const failurePoint of ["worktree", "setup"] as const) {
725899
it.effect(
726900
`${failurePoint} failure keeps the thread and message visible and emits failure items`,

‎apps/server/src/orchestration-v2/ThreadLaunchService.ts‎

Lines changed: 68 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ import * as Option from "effect/Option";
2121
import * as Ref from "effect/Ref";
2222
import * as Schema from "effect/Schema";
2323
import * as Scope from "effect/Scope";
24+
import { buildTemporaryWorktreeBranchName, isTemporaryWorktreeBranch } from "@t3tools/shared/git";
2425

2526
import * as GitWorkflow from "../git/GitWorkflowService.ts";
2627
import * as ProjectService from "../project/ProjectService.ts";
@@ -31,6 +32,7 @@ import * as TextGeneration from "../textGeneration/TextGeneration.ts";
3132
import * as CommandReceiptStore from "./CommandReceiptStore.ts";
3233
import * as IdAllocator from "./IdAllocator.ts";
3334
import { makeProviderFailure } from "./ProviderFailure.ts";
35+
import { randomUuidV4 } from "./RandomUuid.ts";
3436
import * as ThreadManagement from "./ThreadManagementService.ts";
3537

3638
export type ThreadLaunchWorkspaceStrategy =
@@ -112,16 +114,6 @@ export class ThreadLaunchService extends Context.Service<
112114

113115
const isThreadLaunchError = Schema.is(ThreadLaunchError);
114116

115-
function fallbackBranchName(threadId: ThreadId): string {
116-
const suffix = String(threadId)
117-
.split(":")
118-
.at(-1)
119-
?.replace(/[^a-zA-Z0-9-]+/gu, "-")
120-
.replace(/^-+|-+$/gu, "")
121-
.slice(0, 16);
122-
return `thread-${suffix || "new"}`;
123-
}
124-
125117
function failureDetail(error: unknown): string {
126118
if (isThreadLaunchError(error)) {
127119
const cause = error.cause;
@@ -200,30 +192,37 @@ export const make = Effect.gen(function* () {
200192
);
201193

202194
const initialMessage = input.initialMessage;
203-
let branch =
204-
input.workspaceStrategy.type === "worktree" &&
205-
input.workspaceStrategy.branch === undefined &&
206-
initialMessage !== undefined
207-
? yield* Effect.gen(function* () {
208-
const settings = yield* serverSettings.getSettings;
209-
const modelSelection =
210-
settings.sourceControlWriterModelSelection === null
211-
? settings.textGenerationModelSelection
212-
: ServerSettings.resolveSourceControlWriterModelSelection(
213-
settings,
214-
yield* providerRegistry.getProviders,
215-
);
216-
return yield* textGeneration
217-
.generateBranchName({
218-
cwd: project.workspaceRoot,
219-
message: initialMessage.text,
220-
attachments: initialMessage.attachments,
221-
modelSelection,
222-
})
223-
.pipe(Effect.map((result) => result.branch));
224-
}).pipe(Effect.mapError(mapError(input, "generate-metadata", threadId)))
225-
: (input.workspaceStrategy.branch ??
226-
(input.workspaceStrategy.type === "worktree" ? fallbackBranchName(threadId) : null));
195+
const generateBranchNameFor = (cwd: string, message: ThreadLaunchInitialMessage) =>
196+
Effect.gen(function* () {
197+
const settings = yield* serverSettings.getSettings;
198+
const modelSelection =
199+
settings.sourceControlWriterModelSelection === null
200+
? settings.textGenerationModelSelection
201+
: ServerSettings.resolveSourceControlWriterModelSelection(
202+
settings,
203+
yield* providerRegistry.getProviders,
204+
);
205+
return yield* textGeneration
206+
.generateBranchName({
207+
cwd,
208+
message: message.text,
209+
attachments: message.attachments,
210+
modelSelection,
211+
})
212+
.pipe(Effect.map((result) => result.branch));
213+
});
214+
215+
// The server owns worktree naming: without an explicit branch, provision
216+
// under a temporary `t3code/<hash>` name so the worktree never waits on
217+
// name generation, then rename in the background below.
218+
const requestedBranch = input.workspaceStrategy.branch;
219+
let branch: string | null;
220+
if (input.workspaceStrategy.type === "worktree" && requestedBranch === undefined) {
221+
const uuid = yield* randomUuidV4;
222+
branch = buildTemporaryWorktreeBranchName(() => uuid.replaceAll("-", ""));
223+
} else {
224+
branch = requestedBranch ?? null;
225+
}
227226
let worktreePath =
228227
input.workspaceStrategy.type === "existing_worktree"
229228
? input.workspaceStrategy.worktreePath
@@ -279,6 +278,41 @@ export const make = Effect.gen(function* () {
279278
})
280279
.pipe(Effect.mapError(mapError(input, "update-thread", threadId)));
281280

281+
// Rename temporary branches (server-invented above, or sent by clients
282+
// that name worktrees themselves) in the background so generation latency
283+
// never delays provisioning or the provider turn. The temporary name
284+
// simply sticks if generation or the rename fails.
285+
if (
286+
worktreePath !== null &&
287+
branch !== null &&
288+
initialMessage !== undefined &&
289+
isTemporaryWorktreeBranch(branch)
290+
) {
291+
const oldBranch = branch;
292+
const worktreeCwd = worktreePath;
293+
yield* generateBranchNameFor(worktreeCwd, initialMessage).pipe(
294+
Effect.flatMap((newBranch) => git.renameBranch({ cwd: worktreeCwd, oldBranch, newBranch })),
295+
Effect.flatMap((renamed) =>
296+
threads.dispatch({
297+
type: "thread.metadata.update",
298+
commandId: CommandId.make(`${input.commandId}:branch-rename`),
299+
threadId,
300+
branch: renamed.branch,
301+
worktreePath: worktreeCwd,
302+
}),
303+
),
304+
Effect.catchCause((cause) =>
305+
Effect.logWarning("Thread worktree branch rename failed", {
306+
commandId: input.commandId,
307+
threadId,
308+
oldBranch,
309+
cause,
310+
}),
311+
),
312+
Effect.forkIn(preparationScope),
313+
);
314+
}
315+
282316
const cwd = worktreePath ?? project.workspaceRoot;
283317
if (runId !== null) {
284318
yield* threads

‎apps/web/src/components/ChatView.tsx‎

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -123,7 +123,6 @@ import {
123123
import { useTheme } from "../hooks/useTheme";
124124
import { useTurnDiffSummaries } from "../hooks/useTurnDiffSummaries";
125125
import { isCommandPaletteOpen } from "../commandPaletteBus";
126-
import { buildTemporaryWorktreeBranchName } from "@t3tools/shared/git";
127126
import { useMediaQuery } from "../hooks/useMediaQuery";
128127
import { useElementWidth } from "../hooks/useElementWidth";
129128
import { usePreviewPanelInlineSize } from "../hooks/usePreviewPanelInlineSize";
@@ -167,7 +166,7 @@ import {
167166
TriangleAlertIcon,
168167
WifiOffIcon,
169168
} from "lucide-react";
170-
import { cn, randomHex } from "~/lib/utils";
169+
import { cn } from "~/lib/utils";
171170
import { COLLAPSED_SIDEBAR_TITLEBAR_INSET_CLASS } from "~/workspaceTitlebar";
172171
import { stackedThreadToast, toastManager } from "./ui/toast";
173172
import { decodeProjectScriptKeybindingRule } from "~/lib/projectScriptKeybindings";
@@ -5223,7 +5222,6 @@ function ChatViewContent(props: ChatViewProps) {
52235222
prepareWorktree: {
52245223
projectCwd: activeProject.workspaceRoot,
52255224
baseBranch: baseBranchForWorktree,
5226-
branch: buildTemporaryWorktreeBranchName(randomHex),
52275225
...(startFromOrigin ? { startFromOrigin: true } : {}),
52285226
},
52295227
runSetupScript: true,

0 commit comments

Comments
 (0)