Open History to see the last commit
1import { CheckpointScopeId, ProjectId, RunId, ThreadId } from "@t3tools/contracts";
2import * as Context from "effect/Context";
3import * as Effect from "effect/Effect";
4import * as FiberMap from "effect/FiberMap";
5import * as Layer from "effect/Layer";
6import * as Schema from "effect/Schema";
7
8import * as PullRequestService from "../pullRequest/PullRequestService.ts";
9import * as VcsStatusBroadcaster from "../vcs/VcsStatusBroadcaster.ts";
10import * as WorkspaceEntries from "../workspace/WorkspaceEntries.ts";
11import * as CheckpointCapture from "./CheckpointCaptureService.ts";
12import * as ProjectionStore from "./ProjectionStore.ts";
13
14export class RunFinalizationError extends Schema.TaggedError<RunFinalizationError>()(
15 "RunFinalizationError",
16 {
17 threadId: ThreadId,
18 runId: RunId,
19 scopeId: CheckpointScopeId,
20 operation: Schema.Literals(["capture-checkpoint", "refresh-workspace"]),
21 cause: Schema.Defect(),
22 },
23) {}
24
25export class RunFinalizationRefreshError extends Schema.TaggedError<RunFinalizationRefreshError>()(
26 "RunFinalizationRefreshError",
27 { cwd: Schema.String, cause: Schema.Defect() },
28) {}
29
30export class RunFinalizationObserver extends Context.Reference<{
31 readonly refreshAfterTurn: (projectId: ProjectId) => Effect.Effect<void>;
32 readonly refresh: (input: {
33 readonly cwd: string;
34 readonly threadId: ThreadId;
35 readonly runId: RunId;
36 }) => Effect.Effect<void, RunFinalizationRefreshError>;
37}>("t3/orchestration-v2/RunFinalizationObserver", {
38 defaultValue: () => ({ refresh: () => Effect.void, refreshAfterTurn: () => Effect.void }),
39}) {}
40
41export class RunFinalizationService extends Context.Service<
42 RunFinalizationService,
43 {
44 readonly finalize: (input: {
45 readonly threadId: ThreadId;
46 readonly runId: RunId;
47 readonly scopeId: CheckpointScopeId;
48 }) => Effect.Effect<void, RunFinalizationError>;
49 }
50>()("t3/orchestration-v2/RunFinalizationService") {}
51
52const make = Effect.gen(function* () {
53 const checkpointCapture = yield* CheckpointCapture.CheckpointCaptureServiceV2;
54 const projections = yield* ProjectionStore.ProjectionStoreV2;
55 const observer = yield* RunFinalizationObserver;
56
57 const finalize: RunFinalizationService["Service"]["finalize"] = Effect.fn(
58 "RunFinalizationService.finalize",
59 )(function* (input) {
60 yield* checkpointCapture
61 .execute(input)
62 .pipe(
63 Effect.mapError(
64 (cause) => new RunFinalizationError({ ...input, operation: "capture-checkpoint", cause }),
65 ),
66 );
67 const projection = yield* projections
68 .getCheckpointContext(input.threadId)
69 .pipe(
70 Effect.mapError(
71 (cause) => new RunFinalizationError({ ...input, operation: "refresh-workspace", cause }),
72 ),
73 );
74 const cwd = projection.checkpointScopes.find((scope) => scope.id === input.scopeId)?.cwd;
75 if (cwd !== undefined) {
76 // Retrying a display refresh after the checkpoint is durable blocks the next turn.
77 yield* observer.refresh({ cwd, threadId: input.threadId, runId: input.runId }).pipe(
78 Effect.catchTags({
79 RunFinalizationRefreshError: (cause) =>
80 Effect.logWarning("Failed to refresh workspace after checkpoint capture", {
81 ...input,
82 cause,
83 }),
84 }),
85 );
86 }
87 });
88 return RunFinalizationService.of({ finalize });
89});
90
91export const layer = Layer.effect(RunFinalizationService, make);
92
93export const layerObserver = Layer.effect(
94 RunFinalizationObserver,
95 Effect.gen(function* () {
96 const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
97 const vcsStatus = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
98 const projections = yield* ProjectionStore.ProjectionStoreV2;
99 const pullRequests = yield* PullRequestService.PullRequestService;
100 const pullRequestLookups = yield* FiberMap.make<string>();
101 return {
102 refreshAfterTurn: pullRequests.refreshAfterTurn,
103 refresh: Effect.fn("RunFinalizationService.refresh")(
104 function* ({ cwd, threadId, runId }) {
105 const [, local] = yield* Effect.all(
106 [workspaceEntries.refresh(cwd), vcsStatus.refreshLocalStatus(cwd)],
107 { concurrency: "unbounded" },
108 );
109 if (local.refName === null || local.isDefaultRef) return;
110 const thread = yield* projections.getThreadShell(threadId);
111 if (!thread || thread.branch !== local.refName) return;
112 if (thread.activeRunId !== null && thread.activeRunId !== runId) return;
113 // The forge CLI can take minutes, so the next turn must not wait for it. A newer
114 // turn's lookup replaces a running one instead of queueing behind the cwd's lock.
115 yield* vcsStatus.refreshPullRequestStatus(cwd).pipe(
116 Effect.catch((error) =>
117 Effect.logWarning("failed to refresh pull request status after run completion", {
118 threadId,
119 cwd,
120 detail: error.message,
121 }),
122 ),
123 FiberMap.run(pullRequestLookups, cwd),
124 );
125 },
126 (effect, { cwd }) =>
127 effect.pipe(Effect.mapError((cause) => new RunFinalizationRefreshError({ cwd, cause }))),
128 ),
129 };
130 }),
131);