Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

PullRequestWatchService.ts

235 lines9.2 KB

1import {
2 CommandId,
3 ThreadId,
4 type OrchestrationV2ThreadShell,
5 type PullRequestChecksState,
6 type PullRequestUnavailableError,
7 type PullRequestWatchUntil,
8} from "@t3tools/contracts";
9import * as Cause from "effect/Cause";
10import * as Context from "effect/Context";
11import * as SecureRandom from "effect/crypto/SecureRandom";
12import * as Effect from "effect/Effect";
13import * as Layer from "effect/Layer";
14import * as Schema from "effect/Schema";
15​
16import * as Orchestrator from "../orchestration-v2/Orchestrator.ts";
17import * as PullRequestService from "./PullRequestService.ts";
18import {
19 resolveTarget,
20 type PullRequestTarget,
21 type PullRequestTargetError,
22 type ResolvedTarget,
23} from "./pullRequestTarget.ts";
24import {
25 threadPullRequestKeyOf,
26 threadPullRequestKeysEqual,
27 threadPullRequestsOf,
28} from "../sourceControl/threadPullRequests.ts";
29​
30export class PullRequestWatchFailedError extends Schema.TaggedError<PullRequestWatchFailedError>()(
31 "PullRequestWatchFailedError",
32 { cause: Schema.Defect() },
33) {
34 override get message(): string {
35 return "Could not change whether the pull request is watched.";
36 }
38​
39export class PullRequestWatchFromSubagentError extends Schema.TaggedError<PullRequestWatchFromSubagentError>()(
40 "PullRequestWatchFromSubagentError",
41 {},
42) {
43 override get message(): string {
44 return "This thread is a subagent, so it cannot watch pull requests. Its parent thread owns the pull request: finish your task and report back instead.";
45 }
47​
48export class PullRequestWatchThreadNotFoundError extends Schema.TaggedError<PullRequestWatchThreadNotFoundError>()(
49 "PullRequestWatchThreadNotFoundError",
50 { threadId: ThreadId },
51) {
52 override get message(): string {
53 return `Thread ${this.threadId} was not found.`;
54 }
56​
57export class PullRequestWatchService extends Context.Service<
58 PullRequestWatchService,
59 {
60 readonly setWatching: (input: {
61 readonly threadId: ThreadId;
62 readonly target: PullRequestTarget;
63 readonly watching: boolean;
64 readonly until?: PullRequestWatchUntil | undefined;
65 }) => Effect.Effect<
66 ResolvedTarget & {
67 readonly watching: boolean;
68 readonly wasWatching: boolean;
69 /** Set when the PR already ended, so no watch was registered. */
70 readonly state?: "merged" | "closed";
71 /** CI as the start read saw it. Checks that already passed never wake the watch. */
72 readonly checksState?: PullRequestChecksState;
73 },
74 | PullRequestWatchFailedError
75 | PullRequestWatchFromSubagentError
76 | PullRequestWatchThreadNotFoundError
77 | PullRequestTargetError
78 | PullRequestUnavailableError
79 >;
80 }
81>()("t3/pullRequest/PullRequestWatchService") {}
82​
83const make = Effect.gen(function* () {
84 const engine = yield* Orchestrator.OrchestratorV2;
85 const pullRequests = yield* PullRequestService.PullRequestService;
86 const random = yield* SecureRandom.SecureRandom;
87 // Calls are ordered as they arrive. A start must not register its watch after a later stop
88 // for the same thread and pull request, or it would undo a stop that already returned.
89 let lastCall = 0;
90 const inFlight = new Set<number>();
91 const stoppedBy = new Map<string, number>();
92 // The last stop from this service per thread and pull request, and the last call that had
93 // arrived when it finished, so a start that arrived after it does not take it for a later stop.
94 const lastStop = new Map<string, { readonly call: number; readonly through: number }>();
95​
96 const requireThread = Effect.fn("PullRequestWatchService.requireThread")(function* (
97 threadId: ThreadId,
98 ) {
99 const thread = yield* engine
100 .getThreadShell(threadId)
101 .pipe(Effect.mapError((cause) => new PullRequestWatchFailedError({ cause })));
102 if (thread === null || thread.deletedAt !== null) {
103 return yield* new PullRequestWatchThreadNotFoundError({ threadId });
104 }
105 return thread;
106 });
107​
108 // Keep the registration span stable across the service extraction.
109 const setWatching = Effect.fn("PullRequestsToolkit.setWatching")(function* (input: {
110 readonly threadId: ThreadId;
111 readonly target: PullRequestTarget;
112 readonly watching: boolean;
113 readonly until?: PullRequestWatchUntil | undefined;
114 }) {
115 const { watching } = input;
116 const call = ++lastCall;
117 inFlight.add(call);
118 let stopping: string | undefined;
119 yield* Effect.addFinalizer(() =>
120 Effect.sync(() => {
121 inFlight.delete(call);
122 if (stopping !== undefined && lastStop.get(stopping)?.call === call) {
123 lastStop.set(stopping, { call, through: lastCall });
124 }
125 const oldest = Math.min(...inFlight);
126 for (const [key, stop] of stoppedBy) if (stop < oldest) stoppedBy.delete(key);
127 for (const [key, stop] of lastStop) if (stop.through < oldest) lastStop.delete(key);
128 }),
129 );
130 const thread = yield* requireThread(input.threadId);
131 const project = yield* pullRequests
132 .addressedProject(thread.projectId)
133 .pipe(Effect.mapError((cause) => new PullRequestWatchFailedError({ cause })));
134 const target = yield* resolveTarget(input.target, project);
135 const callKey = `${thread.id}\u0000${threadPullRequestKeyOf(target)}`;
136 if (!watching) stoppedBy.set(callKey, Math.max(stoppedBy.get(callKey) ?? 0, call));
137 const watchedLink = (shell: OrchestrationV2ThreadShell) =>
138 threadPullRequestsOf(shell).find(
139 (link) => link.source !== "stack-dismissed" && threadPullRequestKeysEqual(link, target),
140 );
141 if (watching && thread.lineage.relationshipToParent === "subagent") {
142 return yield* new PullRequestWatchFromSubagentError();
143 }
144 const before = watchedLink(thread);
145 const wasWatching = before?.watch !== undefined;
146 // A watch on an ended PR could only report that it ended, so report it now instead.
147 const alreadyEnded = (state: "merged" | "closed") => ({
148 ...target,
149 watching: false,
150 wasWatching,
151 state,
152 });
153 // A closed snapshot still gets a read below, since the PR may have reopened.
154 if (watching && before?.snapshot?.state === "merged") return alreadyEnded("merged");
155 // A pending rollup has no failure yet, so any failure the first read finds is news.
156 let checksPendingAtStart: boolean | undefined;
157 let checksStateAtStart: PullRequestChecksState | undefined;
158 if (watching && !wasWatching) {
159 const read = yield* pullRequests
160 .summary(
161 {
162 projectId: thread.projectId,
163 host: target.host,
164 repository: target.repository,
165 number: target.number,
166 allowStale: false,
167 },
168 { recoverTransientFailure: false, bypassCache: true },
169 )
170 .pipe(
171 Effect.catchTags({
172 // Host and transport errors can recover while the watch is active.
173 // A failed read leaves the seed to the link's last sync.
174 PullRequestOperationError: () => Effect.undefined,
175 }),
176 );
177 if (read?.state === "merged" || read?.state === "closed") return alreadyEnded(read.state);
178 checksPendingAtStart = read === undefined ? undefined : read.checksState === "pending";
179 checksStateAtStart = read?.checksState ?? undefined;
180 }
181 if (watching && (stoppedBy.get(callKey) ?? 0) > call) {
182 const current = yield* requireThread(thread.id);
183 return { ...target, watching: watchedLink(current)?.watch !== undefined, wasWatching };
184 }
185 // Clients stop watches without this service, so the engine refuses the start when the link
186 // was stopped since this call looked, unless by an earlier stop from this service.
187 const earlierStop = lastStop.get(callKey);
188 const expectedEndedWatch =
189 before?.watch !== undefined &&
190 earlierStop !== undefined &&
191 earlierStop.call < call &&
192 earlierStop.through >= call
193 ? before.watch.startedAt
194 : (before?.endedWatch?.startedAt ?? null);
195 if (!watching) {
196 stopping = callKey;
197 lastStop.set(callKey, { call, through: Infinity });
198 }
199 const uuid = yield* random.uuidV4().pipe(Effect.orDie);
200 yield* engine
201 .dispatch({
202 type: "thread.pull-request.watch",
203 commandId: CommandId.make(`server:mcp-pr-watch:${thread.id}:${uuid}`),
204 threadId: thread.id,
205 host: target.host,
206 repository: target.repository,
207 number: target.number,
208 watching,
209 ...(watching ? { link: { url: target.url, source: "agent" as const } } : {}),
210 ...(watching && input.until !== undefined && { until: input.until }),
211 ...(watching && { expectedEndedWatch }),
212 ...(watching && checksPendingAtStart !== undefined
213 ? { checksPending: checksPendingAtStart }
214 : {}),
215 })
216 .pipe(
217 Effect.catchCause((cause) =>
218 Cause.hasInterruptsOnly(cause)
219 ? Effect.failCause(cause as Cause.Cause<never>)
220 : Effect.fail(new PullRequestWatchFailedError({ cause })),
221 ),
222 );
223 const after = yield* requireThread(thread.id);
224 return {
225 ...target,
226 watching: watchedLink(after)?.watch !== undefined,
227 wasWatching,
228 ...(checksStateAtStart !== undefined && { checksState: checksStateAtStart }),
229 };
230 }, Effect.scoped);
231​
232 return PullRequestWatchService.of({ setWatching });
233});
234​
235export const layer = Layer.effect(PullRequestWatchService, make);