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