Open History to see the last commit
1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { assert, it } from "@effect/vitest";
3import {
4 CheckpointRef,
5 CheckpointScopeId,
6 ProjectId,
7 RunId,
8 ThreadId,
9 type OrchestrationV2ThreadShell,
10 type Project,
11 type RepositoryIdentity,
12} from "@t3tools/contracts";
13import * as Deferred from "effect/Deferred";
14import * as Effect from "effect/Effect";
15import * as Fiber from "effect/Fiber";
16import * as FileSystem from "effect/FileSystem";
17import * as Layer from "effect/Layer";
18import * as Option from "effect/Option";
19import * as PubSub from "effect/PubSub";
20import * as TestClock from "effect/testing/TestClock";
21
22import * as ProcessRunner from "../processRunner.ts";
23import * as ProjectEnrichment from "../project/ProjectEnrichmentService.ts";
24import * as ProjectFaviconResolver from "../project/ProjectFaviconResolver.ts";
25import * as ProjectService from "../project/ProjectService.ts";
26import * as RepositoryIdentityResolver from "../project/RepositoryIdentityResolver.ts";
27import * as PullRequestService from "../pullRequest/PullRequestService.ts";
28import * as VcsStatusBroadcaster from "../vcs/VcsStatusBroadcaster.ts";
29import * as WorkspaceEntries from "../workspace/WorkspaceEntries.ts";
30import * as CheckpointCapture from "./CheckpointCaptureService.ts";
31import * as ProjectionStore from "./ProjectionStore.ts";
32import * as RunFinalization from "./RunFinalizationService.ts";
33
34// Without a project the observer never touches enrichment, so its methods stay unimplemented.
35const layerNoProject = Layer.mergeAll(
36 Layer.mock(ProjectService.ProjectService)({ getById: () => Effect.succeedNone }),
37 Layer.mock(ProjectEnrichment.ProjectEnrichmentService)({}),
38);
39
40const finalizationLayer = (
41 scopeId: CheckpointScopeId,
42 runId: RunId,
43 steps: string[],
44 refresh: (typeof RunFinalization.RunFinalizationObserver)["Service"]["refresh"],
45) => {
46 const usedRepositoryScopeId = CheckpointScopeId.make(`${scopeId}_api`);
47 const idleRepositoryScopeId = CheckpointScopeId.make(`${scopeId}_docs`);
48 const repositoryCheckpoint = (repositoryScopeId: CheckpointScopeId, checkpointRunId: RunId) => ({
49 scopeId: repositoryScopeId,
50 runId: checkpointRunId,
51 ordinalWithinScope: 1,
52 appRunOrdinal: null,
53 status: "ready" as const,
54 ref: CheckpointRef.make(`refs/t3/test/${repositoryScopeId}`),
55 });
56 return RunFinalization.layer.pipe(
57 Layer.provide(
58 Layer.mergeAll(
59 Layer.mock(CheckpointCapture.CheckpointCaptureServiceV2)({
60 execute: () =>
61 Effect.sync(() => {
62 steps.push("checkpoint");
63 }),
64 }),
65 Layer.mock(ProjectionStore.ProjectionStoreV2)({
66 getCheckpointContext: () =>
67 Effect.succeed({
68 runs: [],
69 checkpointScopes: [
70 { id: scopeId, runId, kind: "root_run" as const, cwd: "/repo" },
71 {
72 id: usedRepositoryScopeId,
73 runId,
74 kind: "manual" as const,
75 cwd: "/api",
76 repositoryPath: "/api",
77 },
78 {
79 id: idleRepositoryScopeId,
80 runId,
81 kind: "manual" as const,
82 cwd: "/docs",
83 repositoryPath: "/docs",
84 },
85 ],
86 checkpoints: [
87 repositoryCheckpoint(usedRepositoryScopeId, runId),
88 repositoryCheckpoint(idleRepositoryScopeId, RunId.make("run_before")),
89 ],
90 }),
91 }),
92 Layer.succeed(RunFinalization.RunFinalizationObserver, {
93 refresh,
94 refreshAfterTurn: () => Effect.void,
95 refreshRepositories: ({ cwds }) =>
96 Effect.sync(() => {
97 steps.push(`repositories:${cwds.join(",")}`);
98 }),
99 }),
100 ),
101 ),
102 );
103};
104
105it.effect("completes finalization when the post-checkpoint workspace refresh fails", () => {
106 const threadId = ThreadId.make("thread_refresh_failure");
107 const runId = RunId.make("run_refresh_failure");
108 const scopeId = CheckpointScopeId.make("scope_refresh_failure");
109 const captured: string[] = [];
110 const layer = finalizationLayer(scopeId, runId, captured, () =>
111 Effect.gen(function* () {
112 captured.push("refresh");
113 return yield* new RunFinalization.RunFinalizationRefreshError({
114 cwd: "/repo",
115 cause: new Error("Git command timed out"),
116 });
117 }),
118 );
119 return Effect.gen(function* () {
120 const service = yield* RunFinalization.RunFinalizationService;
121 yield* service.finalize({ threadId, runId, scopeId });
122 // Only the tracked repository this run checkpointed is refreshed.
123 assert.deepEqual(captured, ["checkpoint", "refresh", "repositories:/api"]);
124 }).pipe(Effect.provide(layer));
125});
126
127it.effect("completes finalization without waiting for the display refresh", () => {
128 const threadId = ThreadId.make("thread_slow_refresh");
129 const runId = RunId.make("run_slow_refresh");
130 const scopeId = CheckpointScopeId.make("scope_slow_refresh");
131 const steps: string[] = [];
132 const release = Deferred.makeUnsafe<void>();
133 const refreshed = Deferred.makeUnsafe<void>();
134 const layer = finalizationLayer(scopeId, runId, steps, () =>
135 Deferred.await(release).pipe(Effect.andThen(Deferred.succeed(refreshed, undefined))),
136 );
137 return Effect.gen(function* () {
138 const service = yield* RunFinalization.RunFinalizationService;
139 const finalize = yield* service
140 .finalize({ threadId, runId, scopeId })
141 .pipe(Effect.timeoutOption("1 minute"), Effect.forkChild({ startImmediately: true }));
142 yield* TestClock.adjust("1 minute");
143 assert.isTrue(
144 Option.isSome(yield* Fiber.join(finalize)),
145 "finalization waited on the display refresh, blocking the thread's next turn",
146 );
147 yield* Deferred.succeed(release, undefined);
148 yield* Deferred.await(refreshed);
149 }).pipe(Effect.provide(layer));
150});
151
152it.effect.each(
153 (
154 [
155 {
156 label: "discovers a new PR for the completed run's branch",
157 branch: "feature",
158 checkedOut: "feature",
159 activeRun: null,
160 expected: ["/repo"],
161 },
162 {
163 label: "leaves the default branch's PR cache alone",
164 branch: "main",
165 checkedOut: "main",
166 activeRun: null,
167 expected: [],
168 },
169 {
170 label: "does not refresh another thread's checkout",
171 branch: "feature",
172 checkedOut: "other",
173 activeRun: null,
174 expected: [],
175 },
176 {
177 label: "does not refresh during a newer active run",
178 branch: "feature",
179 checkedOut: "feature",
180 activeRun: "newer-run",
181 expected: [],
182 },
183 ] as const
184 ).map((scenario) => [scenario.label, scenario] as const),
185)("%s", ([, scenario]) => {
186 const refreshed: string[] = [];
187 const lookedUp = Deferred.makeUnsafe<void>();
188 const threadId = ThreadId.make("thread-pr-refresh");
189 const runId = RunId.make("completed-run");
190 const layer = RunFinalization.layerObserver.pipe(
191 Layer.provide(
192 Layer.mergeAll(
193 layerNoProject,
194 Layer.mock(WorkspaceEntries.WorkspaceEntries)({ refresh: () => Effect.void }),
195 Layer.mock(PullRequestService.PullRequestService)({
196 refreshAfterTurn: () => Effect.void,
197 }),
198 Layer.mock(VcsStatusBroadcaster.VcsStatusBroadcaster)({
199 refreshLocalStatus: () =>
200 Effect.succeed({
201 isRepo: true,
202 hasPrimaryRemote: true,
203 isDefaultRef: scenario.checkedOut === "main",
204 refName: scenario.checkedOut,
205 hasWorkingTreeChanges: false,
206 workingTree: { files: [], insertions: 0, deletions: 0 },
207 }),
208 refreshStatus: () =>
209 Effect.die("turn completion must preserve known PRs and lookup backoff"),
210 // Requested synchronously by refresh; the lookup itself runs in the background.
211 refreshPullRequestStatus: (cwd) => {
212 refreshed.push(cwd);
213 return Deferred.succeed(lookedUp, undefined).pipe(Effect.as(null));
214 },
215 }),
216 Layer.mock(ProjectionStore.ProjectionStoreV2)({
217 getThreadShell: () =>
218 Effect.succeed({
219 id: threadId,
220 branch: scenario.branch,
221 activeRunId: scenario.activeRun === null ? null : RunId.make(scenario.activeRun),
222 } as OrchestrationV2ThreadShell),
223 }),
224 ),
225 ),
226 );
227 return Effect.gen(function* () {
228 const observer = yield* RunFinalization.RunFinalizationObserver;
229 yield* observer.refresh({ cwd: "/repo", threadId, runId });
230 if (scenario.expected.length > 0) yield* Deferred.await(lookedUp);
231 assert.deepEqual(refreshed, [...scenario.expected]);
232 }).pipe(Effect.provide(layer));
233});
234
235it.effect("returns from the post-turn refresh without waiting for the PR lookup", () => {
236 const threadId = ThreadId.make("thread-slow-forge");
237 const runId = RunId.make("completed-run");
238 const layer = RunFinalization.layerObserver.pipe(
239 Layer.provide(
240 Layer.mergeAll(
241 layerNoProject,
242 Layer.mock(WorkspaceEntries.WorkspaceEntries)({ refresh: () => Effect.void }),
243 Layer.mock(PullRequestService.PullRequestService)({
244 refreshAfterTurn: () => Effect.void,
245 }),
246 Layer.mock(VcsStatusBroadcaster.VcsStatusBroadcaster)({
247 refreshLocalStatus: () =>
248 Effect.succeed({
249 isRepo: true,
250 hasPrimaryRemote: true,
251 isDefaultRef: false,
252 refName: "feature",
253 hasWorkingTreeChanges: false,
254 workingTree: { files: [], insertions: 0, deletions: 0 },
255 }),
256 refreshPullRequestStatus: () => Effect.never,
257 }),
258 Layer.mock(ProjectionStore.ProjectionStoreV2)({
259 getThreadShell: () =>
260 Effect.succeed({
261 id: threadId,
262 branch: "feature",
263 activeRunId: null,
264 } as OrchestrationV2ThreadShell),
265 }),
266 ),
267 ),
268 );
269 return Effect.gen(function* () {
270 const observer = yield* RunFinalization.RunFinalizationObserver;
271 const refresh = yield* observer
272 .refresh({ cwd: "/repo", threadId, runId })
273 .pipe(Effect.timeoutOption("1 minute"), Effect.forkChild({ startImmediately: true }));
274 yield* TestClock.adjust("1 minute");
275 const result = yield* Fiber.join(refresh);
276 assert.isTrue(
277 Option.isSome(result),
278 "turn finalization waited on the forge PR lookup, blocking the thread's next turn",
279 );
280 }).pipe(Effect.provide(layer));
281});
282
283it.effect("replaces a still-running PR lookup when a newer turn finishes", () => {
284 const threadId = ThreadId.make("thread-back-to-back");
285 const runId = RunId.make("completed-run");
286 const firstInterrupted = Deferred.makeUnsafe<void>();
287 const secondLookedUp = Deferred.makeUnsafe<void>();
288 let lookups = 0;
289 const layer = RunFinalization.layerObserver.pipe(
290 Layer.provide(
291 Layer.mergeAll(
292 layerNoProject,
293 Layer.mock(WorkspaceEntries.WorkspaceEntries)({ refresh: () => Effect.void }),
294 Layer.mock(PullRequestService.PullRequestService)({
295 refreshAfterTurn: () => Effect.void,
296 }),
297 Layer.mock(VcsStatusBroadcaster.VcsStatusBroadcaster)({
298 refreshLocalStatus: () =>
299 Effect.succeed({
300 isRepo: true,
301 hasPrimaryRemote: true,
302 isDefaultRef: false,
303 refName: "feature",
304 hasWorkingTreeChanges: false,
305 workingTree: { files: [], insertions: 0, deletions: 0 },
306 }),
307 refreshPullRequestStatus: () =>
308 ++lookups === 1
309 ? Effect.never.pipe(
310 Effect.onInterrupt(() => Deferred.succeed(firstInterrupted, undefined)),
311 )
312 : Deferred.succeed(secondLookedUp, undefined).pipe(Effect.as(null)),
313 }),
314 Layer.mock(ProjectionStore.ProjectionStoreV2)({
315 getThreadShell: () =>
316 Effect.succeed({
317 id: threadId,
318 branch: "feature",
319 activeRunId: null,
320 } as OrchestrationV2ThreadShell),
321 }),
322 ),
323 ),
324 );
325 return Effect.gen(function* () {
326 const observer = yield* RunFinalization.RunFinalizationObserver;
327 yield* observer.refresh({ cwd: "/repo", threadId, runId });
328 yield* observer.refresh({ cwd: "/repo", threadId, runId });
329 yield* Deferred.await(firstInterrupted);
330 yield* Deferred.await(secondLookedUp);
331 assert.strictEqual(lookups, 2);
332 }).pipe(Effect.provide(layer));
333});
334
335const identityProjectId = ProjectId.make("project-identity-refresh");
336const identityThreadId = ThreadId.make("thread-identity-refresh");
337const identityRunId = RunId.make("completed-run");
338
339const layerIdentityRefresh = <R>(
340 workspaceRoot: string,
341 resolver: Layer.Layer<RepositoryIdentityResolver.RepositoryIdentityResolver, never, R>,
342) =>
343 RunFinalization.layerObserver.pipe(
344 Layer.provideMerge(
345 Layer.mergeAll(
346 Layer.effect(ProjectEnrichment.ProjectEnrichmentService, ProjectEnrichment.make()).pipe(
347 Layer.provide(
348 Layer.mergeAll(
349 resolver,
350 Layer.succeed(ProjectFaviconResolver.ProjectFaviconResolver, {
351 invalidate: () => Effect.void,
352 resolvePath: () => Effect.succeed(null),
353 }),
354 ),
355 ),
356 ),
357 Layer.mock(WorkspaceEntries.WorkspaceEntries)({ refresh: () => Effect.void }),
358 Layer.mock(PullRequestService.PullRequestService)({ refreshAfterTurn: () => Effect.void }),
359 Layer.mock(VcsStatusBroadcaster.VcsStatusBroadcaster)({
360 refreshLocalStatus: () =>
361 Effect.succeed({
362 isRepo: true,
363 hasPrimaryRemote: true,
364 isDefaultRef: true,
365 refName: "main",
366 hasWorkingTreeChanges: false,
367 workingTree: { files: [], insertions: 0, deletions: 0 },
368 }),
369 }),
370 Layer.mock(ProjectionStore.ProjectionStoreV2)({
371 getThreadShell: () =>
372 Effect.succeed({
373 id: identityThreadId,
374 projectId: identityProjectId,
375 branch: "main",
376 activeRunId: null,
377 } as OrchestrationV2ThreadShell),
378 }),
379 Layer.mock(ProjectService.ProjectService)({
380 getById: () => Effect.succeedSome({ id: identityProjectId, workspaceRoot } as Project),
381 }),
382 ),
383 ),
384 );
385
386it.effect("resolves the identity of a project whose remote was added during the turn", () =>
387 Effect.gen(function* () {
388 const fileSystem = yield* FileSystem.FileSystem;
389 const processRunner = yield* ProcessRunner.ProcessRunner;
390 const workspaceRoot = yield* fileSystem.makeTempDirectoryScoped({
391 prefix: "t3-run-finalization-identity-test-",
392 });
393 const git = (args: ReadonlyArray<string>) =>
394 processRunner.run({ command: "git", args: ["-C", workspaceRoot, ...args] });
395 yield* git(["init"]);
396
397 yield* Effect.gen(function* () {
398 const enrichment = yield* ProjectEnrichment.ProjectEnrichmentService;
399 // A shell read before the turn caches the folder as having no repository.
400 assert.isNull(yield* enrichment.readRepositoryIdentity(workspaceRoot));
401
402 yield* git(["remote", "add", "origin", "https://github.com/t3-triage/example-29929.git"]);
403 const changes = yield* enrichment.subscribeChanges;
404 const observer = yield* RunFinalization.RunFinalizationObserver;
405 yield* observer.refresh({
406 cwd: workspaceRoot,
407 threadId: identityThreadId,
408 runId: identityRunId,
409 });
410
411 const change = yield* PubSub.take(changes);
412 assert.strictEqual(
413 change.enrichment.repositoryIdentity?.locator.remoteUrl,
414 "https://github.com/t3-triage/example-29929.git",
415 "the project's repository identity is still null after the turn added a remote",
416 );
417 }).pipe(
418 Effect.scoped,
419 Effect.provide(layerIdentityRefresh(workspaceRoot, RepositoryIdentityResolver.layer)),
420 );
421 }).pipe(
422 Effect.scoped,
423 Effect.provide(ProcessRunner.layer.pipe(Layer.provideMerge(NodeServices.layer))),
424 ),
425);
426
427it.effect("returns from the post-turn refresh while the identity resolver is still running", () => {
428 const workspaceRoot = "/repo-stubbed-identity";
429 const identity: RepositoryIdentity = {
430 canonicalKey: "example.test/stubbed-identity",
431 locator: {
432 source: "git-remote",
433 remoteName: "origin",
434 remoteUrl: "https://example.test/stubbed-identity.git",
435 },
436 };
437 const releaseResolver = Deferred.makeUnsafe<void>();
438 let remoteAdded = false;
439 const resolver = Layer.succeed(RepositoryIdentityResolver.RepositoryIdentityResolver, {
440 resolve: (_cwd, options) =>
441 options?.refresh
442 ? Deferred.await(releaseResolver).pipe(
443 Effect.map(() => {
444 remoteAdded = true;
445 return identity;
446 }),
447 )
448 : Effect.sync(() => (remoteAdded ? identity : null)),
449 });
450 return Effect.gen(function* () {
451 const enrichment = yield* ProjectEnrichment.ProjectEnrichmentService;
452 assert.isNull(yield* enrichment.readRepositoryIdentity(workspaceRoot));
453 const changes = yield* enrichment.subscribeChanges;
454 const observer = yield* RunFinalization.RunFinalizationObserver;
455 const refresh = yield* observer
456 .refresh({ cwd: workspaceRoot, threadId: identityThreadId, runId: identityRunId })
457 .pipe(Effect.timeoutOption("1 minute"), Effect.forkChild({ startImmediately: true }));
458 yield* TestClock.adjust("1 minute");
459 assert.isTrue(
460 Option.isSome(yield* Fiber.join(refresh)),
461 "turn finalization waited on the identity resolver, blocking the thread's next turn",
462 );
463
464 yield* Deferred.succeed(releaseResolver, undefined);
465 const change = yield* PubSub.take(changes);
466 assert.strictEqual(change.enrichment.repositoryIdentity?.canonicalKey, identity.canonicalKey);
467 }).pipe(Effect.scoped, Effect.provide(layerIdentityRefresh(workspaceRoot, resolver)));
468});