Open History to see the last commit
1import { assert, it } from "@effect/vitest";
2import {
3 CheckpointId,
4 CheckpointScopeId,
5 CommandId,
6 GitCommandError,
7 ProviderThreadId,
8 RunId,
9 ThreadId,
10} from "@t3tools/contracts";
11import * as Deferred from "effect/Deferred";
12import * as Effect from "effect/Effect";
13import * as Fiber from "effect/Fiber";
14import * as Layer from "effect/Layer";
15import * as Option from "effect/Option";
16
17import * as SqlitePersistence from "../persistence/Sqlite.ts";
18import * as ProjectEnrichment from "../project/ProjectEnrichmentService.ts";
19import * as ProjectService from "../project/ProjectService.ts";
20import * as PullRequestService from "../pullRequest/PullRequestService.ts";
21import * as ServerSettings from "../serverSettings.ts";
22import * as VcsStatusBroadcaster from "../vcs/VcsStatusBroadcaster.ts";
23import * as WorkspaceEntries from "../workspace/WorkspaceEntries.ts";
24import * as CheckpointCapture from "./CheckpointCaptureService.ts";
25import * as CheckpointRollback from "./CheckpointRollbackService.ts";
26import * as EffectOutbox from "./EffectOutbox.ts";
27import * as EffectWorker from "./EffectWorker.ts";
28import * as ProjectionMaintenance from "./ProjectionMaintenance.ts";
29import * as ProjectionStore from "./ProjectionStore.ts";
30import * as ProviderSessions from "./ProviderSessionManager.ts";
31import * as ProviderTurnControl from "./ProviderTurnControlService.ts";
32import * as ProviderTurnStart from "./ProviderTurnStartService.ts";
33import * as RunFinalization from "./RunFinalizationService.ts";
34import * as RuntimeRequests from "./RuntimeRequestService.ts";
35import * as ThreadManagement from "./ThreadManagementService.ts";
36import * as ThreadTitles from "./ThreadTitleRegenerationService.ts";
37
38const threadId = ThreadId.make("thread:finalization-queue");
39const runId = RunId.make("run:finalization-queue");
40const scopeId = CheckpointScopeId.make("scope:finalization-queue");
41const captureEffect = {
42 id: "effect:finalization-queue:capture",
43 commandId: CommandId.make("command:finalization-queue:capture"),
44 threadId,
45 request: { type: "checkpoint.capture" as const, runId, scopeId },
46};
47const startEffect = {
48 id: "effect:finalization-queue:start",
49 commandId: CommandId.make("command:finalization-queue:start"),
50 threadId,
51 request: { type: "provider-turn.start" as const, runId: RunId.make("run:next") },
52};
53
54const makeWorker = (
55 calls: string[],
56 capture: Effect.Effect<void, CheckpointCapture.CheckpointCaptureExecutionError>,
57) => {
58 const projections = Layer.mock(ProjectionStore.ProjectionStoreV2)({
59 getCheckpointContext: () =>
60 Effect.succeed({
61 runs: [],
62 checkpointScopes: [{ id: scopeId, runId, kind: "root_run" as const, cwd: "/repo" }],
63 checkpoints: [],
64 }),
65 getThreadShell: () => Effect.succeed(null),
66 });
67 const observer = RunFinalization.layerObserver.pipe(
68 Layer.provide(
69 Layer.mergeAll(
70 projections,
71 Layer.mock(ProjectService.ProjectService)({}),
72 Layer.mock(ProjectEnrichment.ProjectEnrichmentService)({}),
73 Layer.mock(WorkspaceEntries.WorkspaceEntries)({ refresh: () => Effect.void }),
74 Layer.mock(PullRequestService.PullRequestService)({ refreshAfterTurn: () => Effect.void }),
75 Layer.mock(VcsStatusBroadcaster.VcsStatusBroadcaster)({
76 refreshLocalStatus: () =>
77 Effect.gen(function* () {
78 calls.push("refresh");
79 return yield* new GitCommandError({
80 operation: "statusDetailsLocal",
81 command: "git",
82 cwd: "/repo",
83 detail: "VCS process timed out after 30000ms",
84 });
85 }),
86 }),
87 ),
88 ),
89 );
90 const finalization = RunFinalization.layer.pipe(
91 Layer.provide(
92 Layer.mergeAll(
93 projections,
94 observer,
95 Layer.mock(CheckpointCapture.CheckpointCaptureServiceV2)({
96 execute: () => Effect.sync(() => calls.push("capture")).pipe(Effect.andThen(capture)),
97 }),
98 ),
99 ),
100 );
101 const executor = EffectWorker.layerExecutor.pipe(
102 Layer.provide(
103 Layer.mergeAll(
104 finalization,
105 Layer.mock(ProviderSessions.ProviderSessionManagerV2)({}),
106 Layer.mock(ProviderTurnControl.ProviderTurnControlServiceV2)({}),
107 Layer.mock(CheckpointRollback.CheckpointRollbackServiceV2)({
108 execute: () => Effect.sync(() => calls.push("rollback")).pipe(Effect.asVoid),
109 }),
110 Layer.mock(RuntimeRequests.RuntimeRequestServiceV2)({}),
111 Layer.mock(ThreadTitles.ThreadTitleRegenerationService)({}),
112 Layer.mock(ThreadManagement.ThreadManagementService)({
113 recoverDelegatedTask: () => Effect.void,
114 }),
115 Layer.mock(ProjectionStore.ProjectionStoreV2)({}),
116 Layer.mock(ProjectionMaintenance.ProjectionMaintenanceV2)({}),
117 ServerSettings.layerTest(),
118 Layer.mock(ProviderTurnStart.ProviderTurnStartServiceV2)({
119 start: () => Effect.sync(() => calls.push("start")).pipe(Effect.asVoid),
120 }),
121 ),
122 ),
123 );
124 const outbox = EffectOutbox.layer.pipe(Layer.provide(SqlitePersistence.layerMemory));
125 return Layer.fresh(EffectWorker.layer.pipe(Layer.provideMerge(Layer.merge(executor, outbox))));
126};
127
128it.effect.each([
129 ["starts the next turn after a post-capture Git status failure", false],
130 ["keeps the next turn queued when checkpoint capture fails", true],
131] as const)("%s", ([, captureFails]) => {
132 const calls: string[] = [];
133 const checkpointFailure = new CheckpointCapture.CheckpointCaptureExecutionError({
134 threadId,
135 runId,
136 scopeId,
137 cause: "checkpoint storage unavailable",
138 });
139 return Effect.gen(function* () {
140 const queue = yield* EffectOutbox.EffectOutboxV2;
141 const effectWorker = yield* EffectWorker.OrchestrationEffectWorkerV2;
142 yield* queue.enqueue([captureEffect, startEffect]);
143
144 assert.equal(yield* effectWorker.drain(2), captureFails ? 1 : 2);
145 const captured = Option.getOrThrow(yield* queue.get("effect:finalization-queue:capture"));
146 const started = Option.getOrThrow(yield* queue.get("effect:finalization-queue:start"));
147 assert.equal(captured.status, captureFails ? "pending" : "succeeded");
148 assert.equal(captured.attemptCount, 1);
149 assert.equal(started.status, captureFails ? "pending" : "succeeded");
150 assert.equal(started.attemptCount, captureFails ? 0 : 1);
151 assert.deepEqual(calls, captureFails ? ["capture"] : ["capture", "refresh", "start"]);
152 if (captureFails) assert.include(captured.lastError ?? "", "checkpoint storage unavailable");
153 else assert.equal(captured.lastError, null);
154 }).pipe(Effect.provide(makeWorker(calls, captureFails ? checkpointFailure : Effect.void)));
155});
156
157// A run completes before its capture, so the next turn's start is enqueued while capture runs.
158it.effect("keeps a next turn started during capture behind that capture", () => {
159 const calls: string[] = [];
160 return Effect.gen(function* () {
161 const captureStarted = yield* Deferred.make<void>();
162 const releaseCapture = yield* Deferred.make<void>();
163 const capture = Deferred.succeed(captureStarted, undefined).pipe(
164 Effect.andThen(Deferred.await(releaseCapture)),
165 );
166 return yield* Effect.gen(function* () {
167 const queue = yield* EffectOutbox.EffectOutboxV2;
168 const effectWorker = yield* EffectWorker.OrchestrationEffectWorkerV2;
169 yield* queue.enqueue([captureEffect]);
170 const draining = yield* Effect.forkChild(effectWorker.drain(2));
171 yield* Deferred.await(captureStarted);
172
173 yield* queue.enqueue([startEffect]);
174 assert.isTrue(Option.isNone(yield* queue.claimNext({ workerId: "second-slot" })));
175 assert.deepEqual(calls, ["capture"]);
176
177 yield* Deferred.succeed(releaseCapture, undefined);
178 assert.equal(yield* Fiber.join(draining), 2);
179 assert.deepEqual(calls, ["capture", "refresh", "start"]);
180 }).pipe(Effect.provide(makeWorker(calls, capture)));
181 });
182});
183
184const rollbackEffect = (restoreFiles: boolean | undefined) => ({
185 id: `effect:finalization-queue:rollback:${restoreFiles}`,
186 commandId: CommandId.make("command:finalization-queue:rollback"),
187 threadId,
188 request: {
189 type: "provider-thread.rollback" as const,
190 ...(restoreFiles === undefined ? {} : { restoreFiles }),
191 providerThreadId: ProviderThreadId.make("provider-thread:finalization-queue"),
192 checkpointId: CheckpointId.make("checkpoint:finalization-queue"),
193 scopeId,
194 },
195});
196
197const claimRollbackDuringCapture = (restoreFiles: boolean | undefined) => {
198 const calls: string[] = [];
199 return Effect.gen(function* () {
200 const captureStarted = yield* Deferred.make<void>();
201 const releaseCapture = yield* Deferred.make<void>();
202 const capture = Deferred.succeed(captureStarted, undefined).pipe(
203 Effect.andThen(Deferred.await(releaseCapture)),
204 );
205 return yield* Effect.gen(function* () {
206 const queue = yield* EffectOutbox.EffectOutboxV2;
207 const effectWorker = yield* EffectWorker.OrchestrationEffectWorkerV2;
208 yield* queue.enqueue([captureEffect]);
209 const draining = yield* Effect.forkChild(effectWorker.drain(2));
210 yield* Deferred.await(captureStarted);
211
212 const rollback = rollbackEffect(restoreFiles);
213 yield* queue.enqueue([rollback]);
214 const claimed = yield* queue.claimNext({ workerId: "second-slot" });
215 const stored = yield* queue.get(rollback.id);
216
217 yield* Deferred.succeed(releaseCapture, undefined);
218 yield* Fiber.interrupt(draining);
219 return { claimed, stored };
220 }).pipe(Effect.provide(makeWorker(calls, capture)));
221 });
222};
223
224// "Edit from here" with "Revert and keep changes" waits for a slow capture to finish.
225it.effect("runs a conversation-only rollback without waiting for a running capture", () =>
226 Effect.gen(function* () {
227 const { claimed } = yield* claimRollbackDuringCapture(false);
228 assert.isTrue(Option.isSome(claimed), "the rollback waited behind the running capture");
229 }),
230);
231
232// Omitted restoreFiles means restoring files, which must not overlap a capture.
233it.effect.each([
234 { name: "omitted", restoreFiles: undefined },
235 { name: "true", restoreFiles: true },
236] as const)(
237 "keeps a rollback with restoreFiles $name behind a running capture",
238 ({ restoreFiles }) =>
239 Effect.gen(function* () {
240 const { claimed, stored } = yield* claimRollbackDuringCapture(restoreFiles);
241 assert.isTrue(Option.isNone(claimed));
242 assert.strictEqual(Option.getOrThrow(stored).status, "pending");
243 }),
244);