Skip to content

Commit 78619e3

Browse files
committed
fix(server): hold fork sends until workspace readiness
1 parent 18c07f5 commit 78619e3

6 files changed

Lines changed: 208 additions & 4 deletions

File tree

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

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4567,6 +4567,26 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
45674567
) =>
45684568
Effect.gen(function* () {
45694569
let projection = yield* getProjectionWithPendingEvents(command.threadId, events);
4570+
const preparationCommandId = projection.thread.workspacePreparationCommandId;
4571+
if (preparationCommandId !== undefined) {
4572+
// Forks have no preparing run. The fork-ready receipt gates every sender,
4573+
// including other clients, and honors the setup script's wait policy.
4574+
const ready = yield* commandReceipts
4575+
.getByCommandId(CommandId.make(`${preparationCommandId}:fork-ready`))
4576+
.pipe(mapDispatchError(command));
4577+
if (
4578+
Option.isNone(ready) ||
4579+
ready.value.status !== "accepted" ||
4580+
ready.value.threadId !== command.threadId
4581+
) {
4582+
return yield* new OrchestratorDispatchError({
4583+
commandId: command.commandId,
4584+
commandType: command.type,
4585+
cause:
4586+
"The fork's workspace is not ready. Wait for preparation to finish, or create a new fork if preparation failed.",
4587+
});
4588+
}
4589+
}
45704590
if (command.manualContinuationOfRunId !== undefined) {
45714591
const source = projection.runs.find((run) => run.id === command.manualContinuationOfRunId);
45724592
const limited = latestRootProviderFailure(source ?? null, projection.turnItems);

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

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { assert, it } from "@effect/vitest";
22
import {
3+
CommandId,
34
ContextTransferId,
45
MessageId,
56
type ModelSelection,
@@ -183,6 +184,21 @@ it.effect("forks from a usage-limited failed run", () =>
183184
}),
184185
);
185186

187+
it.effect("does not inherit the source fork's workspace readiness command", () =>
188+
Effect.gen(function* () {
189+
const sourceRun = makeSourceRun("completed");
190+
const sourceProjection = makeSourceProjection(sourceRun);
191+
const result = yield* planFork(sourceRun, {
192+
...sourceProjection,
193+
thread: {
194+
...sourceProjection.thread,
195+
workspacePreparationCommandId: CommandId.make("source:workspace-preparation"),
196+
},
197+
});
198+
assert.isUndefined(result.targetThread.workspacePreparationCommandId);
199+
}),
200+
);
201+
186202
it.effect("preserves pull request context without inheriting any watches", () =>
187203
Effect.gen(function* () {
188204
const sourceRun = makeSourceRun("completed");

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

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -83,7 +83,10 @@ export interface ThreadForkServiceV2Shape {
8383
readonly transferId: ContextTransferId;
8484
readonly targetThreadId: ThreadId;
8585
readonly title?: string;
86-
readonly workspace?: { readonly branch: string | null; readonly worktreePath: string | null };
86+
readonly workspace?: Pick<
87+
OrchestrationV2AppThread,
88+
"branch" | "worktreePath" | "workspacePreparationCommandId"
89+
>;
8790
readonly createdBy: OrchestrationV2Actor;
8891
readonly creationSource: OrchestrationV2CreationSource;
8992
readonly createdAt: DateTime.Utc;
@@ -118,6 +121,7 @@ export const layer: Layer.Layer<ThreadForkServiceV2> = Layer.succeed(
118121
id: input.targetThreadId,
119122
title: input.title ?? `${input.sourceProjection.thread.title} fork`,
120123
...input.workspace,
124+
workspacePreparationCommandId: input.workspace?.workspacePreparationCommandId,
121125
activeProviderThreadId: null,
122126
lineage: {
123127
parentThreadId: input.sourceProjection.thread.id,

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

Lines changed: 158 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ import {
2828
ProjectId,
2929
ProviderDriverKind,
3030
ProviderInstanceId,
31+
ProviderThreadId,
3132
OrchestrationV2ThreadProjectionJson,
3233
ScheduledTaskId,
3334
type ServerProvider,
@@ -338,6 +339,7 @@ function waitUntil<E, R>(predicate: () => Effect.Effect<boolean, E, R>): Effect.
338339

339340
const seedForkSource = Effect.fn("seedForkSource")(function* (
340341
checkpointStatus: "ready" | "missing" = "ready",
342+
providerThreadId: ProviderThreadId | null = null,
341343
) {
342344
const threads = yield* ThreadManagement.ThreadManagementService;
343345
const sink = yield* EventSink.EventSinkV2;
@@ -373,7 +375,7 @@ const seedForkSource = Effect.fn("seedForkSource")(function* (
373375
ordinal: 1,
374376
providerInstanceId: modelSelection.instanceId,
375377
modelSelection,
376-
providerThreadId: null,
378+
providerThreadId,
377379
userMessageId: MessageId.make("message:fork-source"),
378380
rootNodeId: null,
379381
activeAttemptId: null,
@@ -407,6 +409,37 @@ const seedForkSource = Effect.fn("seedForkSource")(function* (
407409
capturedAt: now,
408410
},
409411
},
412+
...(providerThreadId === null
413+
? []
414+
: [
415+
{
416+
id: EventId.make("event:fork-source-provider-thread"),
417+
type: "provider-thread.updated" as const,
418+
threadId,
419+
occurredAt: now,
420+
payload: {
421+
id: providerThreadId,
422+
driver: adapter.driver,
423+
providerInstanceId: modelSelection.instanceId,
424+
providerSessionId: null,
425+
appThreadId: threadId,
426+
ownerNodeId: null,
427+
nativeThreadRef: {
428+
driver: adapter.driver,
429+
nativeId: "native-source",
430+
strength: "strong" as const,
431+
},
432+
nativeConversationHeadRef: null,
433+
status: "idle" as const,
434+
firstRunOrdinal: 1,
435+
lastRunOrdinal: 1,
436+
handoffIds: [],
437+
forkedFrom: null,
438+
createdAt: now,
439+
updatedAt: now,
440+
},
441+
},
442+
]),
410443
],
411444
});
412445
return { sourceThreadId: threadId, sourcePoint: { type: "run" as const, runId } };
@@ -719,6 +752,22 @@ it.effect("rejects a replay after synchronous fork setup failed in a bound workt
719752
assert.include(String(replayError.cause), "did not complete");
720753
assert.equal(harness.createWorktree.mock.calls.length, 1);
721754
assert.equal(harness.runSetup.mock.calls.length, 1);
755+
const sendError = yield* threads
756+
.dispatch({
757+
type: "message.dispatch",
758+
commandId: CommandId.make("fork:send-after-failed-setup"),
759+
threadId: input.threadId,
760+
messageId: MessageId.make("fork:message-after-failed-setup"),
761+
text: "Continue from another client",
762+
attachments: [],
763+
dispatchMode: { type: "start_immediately" },
764+
createdBy: "user",
765+
creationSource: "mobile",
766+
})
767+
.pipe(Effect.flip);
768+
assert(sendError._tag === "OrchestratorDispatchError");
769+
assert.include(String(sendError.cause), "workspace is not ready");
770+
assert.isEmpty((yield* threads.getThreadProjection(input.threadId)).runs);
722771
}).pipe(Effect.provide(harness.layer));
723772
});
724773

@@ -986,6 +1035,94 @@ it.effect("waits for a fork's setup when the script requires completion", () =>
9861035
}),
9871036
);
9881037

1038+
it.effect.each(["checkout", "setup"] as const)(
1039+
"rejects independent sends to a fork during %s, then starts in its prepared worktree",
1040+
(stage) =>
1041+
Effect.gen(function* () {
1042+
const entered = yield* Deferred.make<void>();
1043+
const proceed = yield* Deferred.make<void>();
1044+
const harness = makeHarness(
1045+
stage === "checkout"
1046+
? {
1047+
createWorktree: (input) =>
1048+
Deferred.succeed(entered, undefined).pipe(
1049+
Effect.andThen(Deferred.await(proceed)),
1050+
Effect.as({
1051+
worktree: {
1052+
path: "/repo-worktrees/feature",
1053+
refName: input.newRefName ?? input.refName,
1054+
},
1055+
}),
1056+
),
1057+
}
1058+
: {
1059+
runSetup: () =>
1060+
Effect.succeed({
1061+
status: "started" as const,
1062+
async: false,
1063+
scriptId: "setup",
1064+
scriptName: "Setup",
1065+
scriptCommand: "vp install",
1066+
terminalId: "setup",
1067+
cwd: "/repo-worktrees/feature",
1068+
completion: Deferred.succeed(entered, undefined).pipe(
1069+
Effect.andThen(Deferred.await(proceed)),
1070+
Effect.as({ exitCode: 0, durationMs: 1 }),
1071+
),
1072+
}),
1073+
},
1074+
);
1075+
yield* Effect.gen(function* () {
1076+
const launches = yield* ThreadLaunch.ThreadLaunchService;
1077+
const threads = yield* ThreadManagement.ThreadManagementService;
1078+
const outbox = yield* EffectOutbox.EffectOutboxV2;
1079+
const forkSource = yield* seedForkSource(
1080+
"ready",
1081+
ProviderThreadId.make("provider-thread:fork-source"),
1082+
);
1083+
const input = {
1084+
...launchInput({
1085+
command: "fork:independent-send",
1086+
thread: "thread:fork-independent-send",
1087+
workspace: { type: "worktree", baseRef: "main" },
1088+
}),
1089+
forkSource,
1090+
};
1091+
const launch = yield* launches.launch(input).pipe(Effect.forkChild);
1092+
yield* Deferred.await(entered);
1093+
const send = {
1094+
type: "message.dispatch" as const,
1095+
commandId: CommandId.make("fork:premature-send"),
1096+
threadId: input.threadId,
1097+
messageId: MessageId.make("fork:premature-message"),
1098+
text: "Continue from another client",
1099+
attachments: [],
1100+
dispatchMode: { type: "start_immediately" as const },
1101+
createdBy: "user" as const,
1102+
creationSource: "mobile" as const,
1103+
};
1104+
const premature = yield* threads.dispatch(send).pipe(Effect.result);
1105+
const beforeReady = yield* threads.getThreadProjection(input.threadId);
1106+
const prematureEffects = yield* outbox.listByCommandId(send.commandId);
1107+
yield* Deferred.succeed(proceed, undefined);
1108+
yield* Fiber.join(launch);
1109+
assert.isTrue(Result.isFailure(premature));
1110+
assert.isEmpty(beforeReady.runs);
1111+
assert.isEmpty(beforeReady.checkpointScopes);
1112+
assert.isEmpty(prematureEffects);
1113+
1114+
yield* threads.dispatch({
1115+
...send,
1116+
commandId: CommandId.make("fork:ready-send"),
1117+
messageId: MessageId.make("fork:ready-message"),
1118+
});
1119+
const prepared = yield* threads.getThreadProjection(input.threadId);
1120+
assert.equal(prepared.runs[0]?.status, "starting");
1121+
assert.equal(prepared.checkpointScopes[0]?.cwd, "/repo-worktrees/feature");
1122+
}).pipe(Effect.provide(harness.layer));
1123+
}),
1124+
);
1125+
9891126
it.effect("honors nonblocking setup for a fork while its async script continues", () =>
9901127
Effect.gen(function* () {
9911128
const completion = yield* Deferred.make<{ exitCode: number | null; durationMs: number }>();
@@ -1006,7 +1143,11 @@ it.effect("honors nonblocking setup for a fork while its async script continues"
10061143
const launches = yield* ThreadLaunch.ThreadLaunchService;
10071144
const tracker = yield* WorktreeSetupTracker.WorktreeSetupTracker;
10081145
const receipts = yield* CommandReceiptStore.CommandReceiptStoreV2;
1009-
const forkSource = yield* seedForkSource();
1146+
const threads = yield* ThreadManagement.ThreadManagementService;
1147+
const forkSource = yield* seedForkSource(
1148+
"ready",
1149+
ProviderThreadId.make("provider-thread:fork-source"),
1150+
);
10101151
const input = {
10111152
...launchInput({
10121153
command: "fork:async",
@@ -1030,6 +1171,21 @@ it.effect("honors nonblocking setup for a fork while its async script continues"
10301171
assert.equal(replay.projection.thread.worktreePath, "/repo-worktrees/feature");
10311172
assert.equal(harness.createWorktree.mock.calls.length, 1);
10321173
assert.equal(harness.runSetup.mock.calls.length, 1);
1174+
yield* threads.dispatch({
1175+
type: "message.dispatch",
1176+
commandId: CommandId.make("fork:async-send"),
1177+
threadId: input.threadId,
1178+
messageId: MessageId.make("fork:async-message"),
1179+
text: "Continue while the async script runs",
1180+
attachments: [],
1181+
dispatchMode: { type: "start_immediately" },
1182+
createdBy: "user",
1183+
creationSource: "mobile",
1184+
});
1185+
const prepared = yield* threads.getThreadProjection(input.threadId);
1186+
assert.equal(prepared.runs[0]?.status, "starting");
1187+
assert.equal(prepared.checkpointScopes[0]?.cwd, "/repo-worktrees/feature");
1188+
assert.equal((yield* tracker.get(input.threadId))?.phase, "running");
10331189
yield* Deferred.succeed(completion, { exitCode: 0, durationMs: 1 });
10341190
yield* tracker.stream(result.threadId).pipe(
10351191
Stream.filter((snapshot) => snapshot?.phase === "done"),

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

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1018,7 +1018,13 @@ const make = Effect.gen(function* () {
10181018
targetThreadId: candidateThreadId,
10191019
sourcePoint: input.forkSource.sourcePoint,
10201020
title: input.title,
1021-
workspace: { branch: initialBranch, worktreePath: initialWorktreePath },
1021+
workspace: {
1022+
branch: initialBranch,
1023+
worktreePath: initialWorktreePath,
1024+
...(workspaceStrategy.type === "worktree"
1025+
? { workspacePreparationCommandId: input.commandId }
1026+
: {}),
1027+
},
10221028
createdBy: input.createdBy,
10231029
creationSource: input.creationSource,
10241030
})

‎packages/contracts/src/orchestrationV2.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -364,6 +364,7 @@ export const OrchestrationV2AppThread = Schema.Struct({
364364
interactionMode: ProviderInteractionMode,
365365
branch: Schema.NullOr(TrimmedNonEmptyString),
366366
worktreePath: Schema.NullOr(TrimmedNonEmptyString),
367+
workspacePreparationCommandId: Schema.optional(CommandId),
367368
linkedPullRequest: Schema.optional(Schema.NullOr(ThreadLinkedPullRequest)),
368369
pullRequests: Schema.optional(Schema.Array(ThreadPullRequestLink)),
369370
branchPullRequest: Schema.optional(Schema.NullOr(ThreadLinkedPullRequest)),
@@ -2916,6 +2917,7 @@ export const OrchestrationV2Command = Schema.Union([
29162917
Schema.Struct({
29172918
branch: Schema.NullOr(TrimmedNonEmptyString),
29182919
worktreePath: Schema.NullOr(TrimmedNonEmptyString),
2920+
workspacePreparationCommandId: Schema.optional(CommandId),
29192921
}),
29202922
),
29212923
title: Schema.optional(TrimmedNonEmptyString),

0 commit comments

Comments
 (0)