Skip to content

Commit c2931a6

Browse files
fix(server): honor worktree prefixes when automatic naming fails (#35718)
Co-authored-by: akash9676 <[email protected]>
1 parent d4b77d2 commit c2931a6

4 files changed

Lines changed: 155 additions & 29 deletions

File tree

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

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1863,15 +1863,18 @@ layer("ProviderEventIngestorV2", (it) => {
18631863
);
18641864

18651865
it.effect.each([
1866-
{ parentMoved: false, failure: null },
1867-
{ parentMoved: true, failure: null },
1868-
{ parentMoved: false, failure: "write" },
1869-
{ parentMoved: false, failure: "git" },
1866+
{ parentMoved: false, failure: null, temporaryBranch: "t3/abcd1234" },
1867+
{ parentMoved: true, failure: null, temporaryBranch: "t3/abcd1234" },
1868+
{ parentMoved: false, failure: "write", temporaryBranch: "t3/abcd1234" },
1869+
{ parentMoved: false, failure: "git", temporaryBranch: "t3/abcd1234" },
1870+
{ parentMoved: false, failure: null, temporaryBranch: "my-prefix/abcd1234" },
18701871
])(
18711872
"rechecks a pending native child's branch after the rename scan: %j",
1872-
({ parentMoved, failure }) =>
1873+
({ parentMoved, failure, temporaryBranch }) =>
18731874
Effect.gen(function* () {
18741875
const { worktreePath, command } = yield* makeSharedWorktree;
1876+
if (temporaryBranch !== "t3/abcd1234")
1877+
yield* command(worktreePath, ["branch", "-m", temporaryBranch]);
18751878
const git = yield* GitVcsDriver.GitVcsDriver;
18761879
const now = yield* DateTime.now;
18771880
const eventSink = yield* EventSink.EventSinkV2;
@@ -1881,13 +1884,13 @@ layer("ProviderEventIngestorV2", (it) => {
18811884
if (rootEvent.type !== "thread.created") throw new Error("Expected thread fixture");
18821885
const parent = {
18831886
...rootEvent.payload,
1884-
branch: "t3/abcd1234",
1887+
branch: temporaryBranch,
18851888
worktreePath,
18861889
};
18871890
yield* eventSink.write({ events: [{ ...rootEvent, payload: parent }] });
18881891
const childId = ids.derive.threadFromProviderThread({
18891892
driver: CODEX_DRIVER,
1890-
nativeThreadId: `child-created-during-rename:${parentMoved}:${failure}`,
1893+
nativeThreadId: `child-created-during-rename:${parentMoved}:${failure}:${temporaryBranch}`,
18911894
});
18921895
const beforeCommit = yield* Deferred.make<
18931896
void,
@@ -2056,7 +2059,7 @@ layer("ProviderEventIngestorV2", (it) => {
20562059
});
20572060
assert.equal((yield* projections.getThread(childId)).branch, branch);
20582061
assert.equal(stored.length, 1);
2059-
assert.equal(gitReads, scenario === "explicit" ? 0 : 1);
2062+
assert.equal(gitReads, 1);
20602063
}),
20612064
);
20622065

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

Lines changed: 1 addition & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,6 @@ import * as Schema from "effect/Schema";
2525
import * as SqlError from "effect/sql/SqlError";
2626

2727
import { AgentScope } from "@t3tools/shared/AgentScope";
28-
import { isTemporaryWorktreeBranch } from "@t3tools/shared/git";
2928
import { modelSelectionsEqual } from "@t3tools/shared/model";
3029
import {
3130
ProviderTurnAnalytics,
@@ -771,12 +770,7 @@ export const layer: Layer.Layer<
771770
);
772771
if (created?.event.type !== "thread.created") return storedEvents;
773772
const child = created.event.payload;
774-
if (
775-
child.worktreePath === null ||
776-
child.branch === null ||
777-
!isTemporaryWorktreeBranch(child.branch)
778-
)
779-
return storedEvents;
773+
if (child.worktreePath === null || child.branch === null) return storedEvents;
780774
// Git renames before scanning committed threads. If that scan missed this
781775
// creation, HEAD already has the new name, even if the parent moved away.
782776
const branch = yield* git.resolveBranchName(child.worktreePath, "HEAD");

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

Lines changed: 110 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ import {
2626
type ServerProvider,
2727
ThreadId,
2828
TextGenerationError,
29+
ServerSettingsError,
2930
} from "@t3tools/contracts";
3031
import * as Cause from "effect/Cause";
3132
import * as Deferred from "effect/Deferred";
@@ -131,6 +132,7 @@ interface HarnessOptions {
131132
readonly generateTitle?: TextGeneration.TextGeneration["Service"]["generateThreadTitle"];
132133
readonly generateBranchName?: TextGeneration.TextGeneration["Service"]["generateBranchName"];
133134
readonly serverSettings?: Parameters<typeof ServerSettings.layerTest>[0];
135+
readonly getLaunchSettings?: ServerSettings.ServerSettingsService["Service"]["getSettings"];
134136
readonly providers?: ReadonlyArray<ServerProvider>;
135137
readonly git?: Partial<GitWorkflow.GitWorkflowService["Service"]>;
136138
}
@@ -244,6 +246,11 @@ function makeHarness(options: HarnessOptions = {}) {
244246
layerReceipts,
245247
layerOrchestrator,
246248
IdAllocator.layer,
249+
options.getLaunchSettings === undefined
250+
? Layer.empty
251+
: Layer.mock(ServerSettings.ServerSettingsService)({
252+
getSettings: options.getLaunchSettings,
253+
}),
247254
),
248255
),
249256
);
@@ -969,6 +976,109 @@ const preparationSettled = (threadId: ThreadId) =>
969976
return yield* threads.getThreadProjection(threadId);
970977
});
971978

979+
it.effect.each([
980+
{ prefix: "my-prefix", collision: null, expected: /^my-prefix\/[0-9a-f]{8}$/ },
981+
{ prefix: "my-prefix", collision: "my-prefix", expected: /^my-prefix-[0-9a-f]{8}$/ },
982+
{ prefix: "team/topic", collision: "team", expected: /^team-topic-[0-9a-f]{8}$/ },
983+
])("keeps prefix '$prefix' with collision '$collision' when naming fails", (scenario) =>
984+
Effect.gen(function* () {
985+
const namingAttempted = yield* Deferred.make<void>();
986+
const harness = makeHarness({
987+
serverSettings: {
988+
branchNamePrefix: "global-prefix",
989+
projectSettingsOverrides: {
990+
[projectId]: { branchNamingMode: "static", branchNamePrefix: scenario.prefix },
991+
},
992+
},
993+
hasCommit: ({ refName }) => Effect.succeed(refName === `refs/heads/${scenario.collision}`),
994+
generateBranchName: () =>
995+
Deferred.succeed(namingAttempted, undefined).pipe(
996+
Effect.andThen(
997+
Effect.fail(
998+
new TextGenerationError({ operation: "generateBranchName", detail: "Unavailable" }),
999+
),
1000+
),
1001+
),
1002+
});
1003+
yield* Effect.gen(function* () {
1004+
const launches = yield* ThreadLaunch.ThreadLaunchService;
1005+
const launched = yield* launches.launch(
1006+
launchInput({
1007+
command: "prefix-launch",
1008+
thread: "prefix-thread",
1009+
message: "Fix the parser",
1010+
workspace: { type: "worktree", baseRef: "main" },
1011+
}),
1012+
);
1013+
const projection = yield* preparationSettled(launched.threadId);
1014+
assert.match(projection.thread.branch!, scenario.expected);
1015+
yield* Deferred.await(namingAttempted);
1016+
assert.equal(projection.runs[0]?.status, "starting");
1017+
assert.equal(harness.createWorktree.mock.calls[0]?.[0]?.newRefName, projection.thread.branch);
1018+
assert.equal(harness.renameBranch.mock.calls.length, 0);
1019+
assert.isFalse(projection.turnItems.some((item) => item.type === "error"));
1020+
}).pipe(Effect.provide(harness.layer));
1021+
}),
1022+
);
1023+
1024+
it.effect(
1025+
"starts a worktree with the default temporary name when settings secrets cannot be read",
1026+
() => {
1027+
const harness = makeHarness({
1028+
getLaunchSettings: Effect.fail(
1029+
new ServerSettingsError({ settingsPath: "/settings.json", operation: "read-secret" }),
1030+
),
1031+
});
1032+
return Effect.gen(function* () {
1033+
const launches = yield* ThreadLaunch.ThreadLaunchService;
1034+
const launched = yield* launches.launch(
1035+
launchInput({
1036+
command: "settings-fallback",
1037+
thread: "settings-fallback-thread",
1038+
message: "Fix the parser",
1039+
workspace: { type: "worktree", baseRef: "main" },
1040+
}),
1041+
);
1042+
const projection = yield* preparationSettled(launched.threadId);
1043+
assert.equal(projection.runs[0]?.status, "starting");
1044+
assert.match(projection.thread.branch!, /^t3\/[0-9a-f]{8}$/);
1045+
assert.equal(harness.createWorktree.mock.calls[0]?.[0]?.newRefName, projection.thread.branch);
1046+
assert.equal(harness.runSetup.mock.calls.length, 1);
1047+
assert.equal(harness.renameBranch.mock.calls.length, 0);
1048+
assert.isFalse(projection.turnItems.some((item) => item.type === "error"));
1049+
}).pipe(Effect.provide(harness.layer));
1050+
},
1051+
);
1052+
1053+
it.effect("renames a temporary branch with a configured prefix when generation succeeds", () => {
1054+
const harness = makeHarness({
1055+
serverSettings: { branchNamingMode: "static", branchNamePrefix: "my-prefix" },
1056+
generateBranchName: () => Effect.succeed({ branch: "my-prefix/fix-parser" }),
1057+
});
1058+
return Effect.gen(function* () {
1059+
const launches = yield* ThreadLaunch.ThreadLaunchService;
1060+
const threads = yield* ThreadManagement.ThreadManagementService;
1061+
const launched = yield* launches.launch(
1062+
launchInput({
1063+
command: "prefix-rename",
1064+
thread: "prefix-rename-thread",
1065+
message: "Fix the parser",
1066+
workspace: { type: "worktree", baseRef: "main" },
1067+
}),
1068+
);
1069+
yield* threads.streamStoredEventsFrom({ threadId: launched.threadId }).pipe(
1070+
Stream.filter((stored) => stored.commandId === "prefix-rename:branch-rename"),
1071+
Stream.runHead,
1072+
);
1073+
const projection = yield* threads.getThreadProjection(launched.threadId);
1074+
assert.equal(projection.thread.branch, "my-prefix/fix-parser");
1075+
assert.match(
1076+
harness.renameBranch.mock.calls[0]?.[0]?.oldBranch ?? "",
1077+
/^my-prefix\/[0-9a-f]{8}$/,
1078+
);
1079+
}).pipe(Effect.provide(harness.layer));
1080+
});
1081+
9721082
function scheduledTaskInput(id: string, targetProjectId: ProjectId) {
9731083
return {
9741084
id: ScheduledTaskId.make(id),

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

Lines changed: 33 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -37,8 +37,8 @@ import * as Stream from "effect/Stream";
3737
import {
3838
buildTemporaryWorktreeBranchName,
3939
flattenTemporaryWorktreeBranchName,
40+
formatGeneratedBranchName,
4041
isTemporaryWorktreeBranch,
41-
WORKTREE_BRANCH_PREFIX,
4242
} from "@t3tools/shared/git";
4343

4444
import * as GitWorkflow from "../git/GitWorkflowService.ts";
@@ -491,10 +491,23 @@ const make = Effect.gen(function* () {
491491
);
492492

493493
const requestedBranch = input.workspaceStrategy.branch;
494+
const generatedTemporaryBranch =
495+
input.workspaceStrategy.type === "worktree" && requestedBranch === undefined;
494496
let branch: string | null;
495-
if (input.workspaceStrategy.type === "worktree" && requestedBranch === undefined) {
497+
if (generatedTemporaryBranch) {
496498
const uuid = yield* randomUuidV4;
497499
branch = buildTemporaryWorktreeBranchName(() => uuid.replaceAll("-", ""));
500+
const settings = yield* serverSettings.getSettings.pipe(
501+
Effect.map((settings) => resolveProjectSettings(settings, input.projectId).settings),
502+
Effect.orElseSucceed(() => null),
503+
);
504+
if (settings?.branchNamingMode === "static") {
505+
branch = formatGeneratedBranchName(branch.slice(-8), {
506+
mode: "static",
507+
prefix: settings.branchNamePrefix,
508+
instructions: "",
509+
});
510+
}
498511
} else {
499512
branch = yield* launchBranch(input.workspaceStrategy, project.workspaceRoot);
500513
}
@@ -541,17 +554,23 @@ const make = Effect.gen(function* () {
541554
}
542555
}
543556
if (shouldFetch) yield* setupTracker.stageStatus(threadId, "fetch", "done");
544-
if (
545-
branch !== null &&
546-
isTemporaryWorktreeBranch(branch) &&
547-
(yield* git
548-
.hasCommit({
549-
cwd: project.workspaceRoot,
550-
refName: `refs/heads/${WORKTREE_BRANCH_PREFIX}`,
551-
})
552-
.pipe(Effect.mapError(mapError(input, "provision-worktree", threadId))))
553-
) {
554-
branch = flattenTemporaryWorktreeBranchName(branch);
557+
if (branch !== null && (generatedTemporaryBranch || isTemporaryWorktreeBranch(branch))) {
558+
const parts = branch.split("/");
559+
for (let depth = 1; depth < parts.length; depth++) {
560+
if (
561+
yield* git
562+
.hasCommit({
563+
cwd: project.workspaceRoot,
564+
refName: `refs/heads/${parts.slice(0, depth).join("/")}`,
565+
})
566+
.pipe(Effect.mapError(mapError(input, "provision-worktree", threadId)))
567+
) {
568+
branch = generatedTemporaryBranch
569+
? branch.replaceAll("/", "-")
570+
: flattenTemporaryWorktreeBranchName(branch);
571+
break;
572+
}
573+
}
555574
}
556575
yield* setupTracker.stageStatus(threadId, "checkout", "running");
557576
let submoduleProgressReportedAt = Number.NEGATIVE_INFINITY;
@@ -649,7 +668,7 @@ const make = Effect.gen(function* () {
649668
worktreePath !== null &&
650669
branch !== null &&
651670
initialMessage !== undefined &&
652-
isTemporaryWorktreeBranch(branch)
671+
(generatedTemporaryBranch || isTemporaryWorktreeBranch(branch))
653672
) {
654673
const oldBranch = branch;
655674
const worktreeCwd = worktreePath;

0 commit comments

Comments
 (0)