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

PullRequestWatchService.ts

195 lines7.3 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 Option from "effect/Option";
15import * as Schema from "effect/Schema";
16​
17import * as Orchestrator from "../orchestration-v2/Orchestrator.ts";
18import * as ProjectService from "../project/ProjectService.ts";
19import * as PullRequestService from "./PullRequestService.ts";
20import {
21 resolveTarget,
22 type PullRequestTarget,
23 type PullRequestTargetError,
24 type ResolvedTarget,
25} from "./pullRequestTarget.ts";
26import {
27 threadPullRequestKeysEqual,
28 threadPullRequestsOf,
29} from "../sourceControl/threadPullRequests.ts";
30​
31export class PullRequestWatchFailedError extends Schema.TaggedError<PullRequestWatchFailedError>()(
32 "PullRequestWatchFailedError",
33 { cause: Schema.Defect() },
34) {
35 override get message(): string {
36 return "Could not change whether the pull request is watched.";
37 }
39​
40export class PullRequestWatchFromSubagentError extends Schema.TaggedError<PullRequestWatchFromSubagentError>()(
41 "PullRequestWatchFromSubagentError",
42 {},
43) {
44 override get message(): string {
45 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.";
46 }
48​
49export class PullRequestWatchThreadNotFoundError extends Schema.TaggedError<PullRequestWatchThreadNotFoundError>()(
50 "PullRequestWatchThreadNotFoundError",
51 { threadId: ThreadId },
52) {
53 override get message(): string {
54 return `Thread ${this.threadId} was not found.`;
55 }
57​
58export class PullRequestWatchService extends Context.Service<
59 PullRequestWatchService,
60 {
61 readonly setWatching: (input: {
62 readonly threadId: ThreadId;
63 readonly target: PullRequestTarget;
64 readonly watching: boolean;
65 readonly until?: PullRequestWatchUntil | undefined;
66 }) => Effect.Effect<
67 ResolvedTarget & {
68 readonly watching: boolean;
69 readonly wasWatching: boolean;
70 /** Set when the PR already ended, so no watch was registered. */
71 readonly state?: "merged" | "closed";
72 /** CI as the start read saw it. Checks that already passed never wake the watch. */
73 readonly checksState?: PullRequestChecksState;
74 },
75 | PullRequestWatchFailedError
76 | PullRequestWatchFromSubagentError
77 | PullRequestWatchThreadNotFoundError
78 | PullRequestTargetError
79 | PullRequestUnavailableError
80 >;
81 }
82>()("t3/pullRequest/PullRequestWatchService") {}
83​
84const make = Effect.gen(function* () {
85 const engine = yield* Orchestrator.OrchestratorV2;
86 const projects = yield* ProjectService.ProjectService;
87 const pullRequests = yield* PullRequestService.PullRequestService;
88 const random = yield* SecureRandom.SecureRandom;
89​
90 const requireThread = Effect.fn("PullRequestWatchService.requireThread")(function* (
91 threadId: ThreadId,
92 ) {
93 const thread = yield* engine
94 .getThreadShell(threadId)
95 .pipe(Effect.mapError((cause) => new PullRequestWatchFailedError({ cause })));
96 if (thread === null || thread.deletedAt !== null) {
97 return yield* new PullRequestWatchThreadNotFoundError({ threadId });
98 }
99 return thread;
100 });
101​
102 // Keep the registration span stable across the service extraction.
103 const setWatching = Effect.fn("PullRequestsToolkit.setWatching")(function* (input: {
104 readonly threadId: ThreadId;
105 readonly target: PullRequestTarget;
106 readonly watching: boolean;
107 readonly until?: PullRequestWatchUntil | undefined;
108 }) {
109 const { watching } = input;
110 const thread = yield* requireThread(input.threadId);
111 const project = yield* projects.getShell(thread.projectId).pipe(
112 Effect.map(Option.getOrUndefined),
113 Effect.mapError((cause) => new PullRequestWatchFailedError({ cause })),
114 );
115 const target = yield* resolveTarget(input.target, project);
116 const watchedLink = (shell: OrchestrationV2ThreadShell) =>
117 threadPullRequestsOf(shell).find(
118 (link) => link.source !== "stack-dismissed" && threadPullRequestKeysEqual(link, target),
119 );
120 if (watching && thread.lineage.relationshipToParent === "subagent") {
121 return yield* new PullRequestWatchFromSubagentError();
122 }
123 const before = watchedLink(thread);
124 const wasWatching = before?.watch !== undefined;
125 // A watch on an ended PR could only report that it ended, so report it now instead.
126 const alreadyEnded = (state: "merged" | "closed") => ({
127 ...target,
128 watching: false,
129 wasWatching,
130 state,
131 });
132 // A closed snapshot still gets a read below, since the PR may have reopened.
133 if (watching && before?.snapshot?.state === "merged") return alreadyEnded("merged");
134 // A pending rollup has no failure yet, so any failure the first read finds is news.
135 let checksPendingAtStart: boolean | undefined;
136 let checksStateAtStart: PullRequestChecksState | undefined;
137 if (watching && !wasWatching) {
138 const read = yield* pullRequests
139 .summary(
140 {
141 projectId: thread.projectId,
142 host: target.host,
143 repository: target.repository,
144 number: target.number,
145 allowStale: false,
146 },
147 { recoverTransientFailure: false, bypassCache: true },
148 )
149 .pipe(
150 Effect.catchTags({
151 // Host and transport errors can recover while the watch is active.
152 // A failed read leaves the seed to the link's last sync.
153 PullRequestOperationError: () => Effect.undefined,
154 }),
155 );
156 if (read?.state === "merged" || read?.state === "closed") return alreadyEnded(read.state);
157 checksPendingAtStart = read === undefined ? undefined : read.checksState === "pending";
158 checksStateAtStart = read?.checksState ?? undefined;
159 }
160 const uuid = yield* random.uuidV4().pipe(Effect.orDie);
161 yield* engine
162 .dispatch({
163 type: "thread.pull-request.watch",
164 commandId: CommandId.make(`server:mcp-pr-watch:${thread.id}:${uuid}`),
165 threadId: thread.id,
166 host: target.host,
167 repository: target.repository,
168 number: target.number,
169 watching,
170 ...(watching ? { link: { url: target.url, source: "agent" as const } } : {}),
171 ...(watching && input.until !== undefined && { until: input.until }),
172 ...(watching && checksPendingAtStart !== undefined
173 ? { checksPending: checksPendingAtStart }
174 : {}),
175 })
176 .pipe(
177 Effect.catchCause((cause) =>
178 Cause.hasInterruptsOnly(cause)
179 ? Effect.failCause(cause as Cause.Cause<never>)
180 : Effect.fail(new PullRequestWatchFailedError({ cause })),
181 ),
182 );
183 const after = yield* requireThread(thread.id);
184 return {
185 ...target,
186 watching: watchedLink(after)?.watch !== undefined,
187 wasWatching,
188 ...(checksStateAtStart !== undefined && { checksState: checksStateAtStart }),
189 };
190 });
191​
192 return PullRequestWatchService.of({ setWatching });
193});
194​
195export const layer = Layer.effect(PullRequestWatchService, make);