Open History to see the last commit
1import {
2 CommandId,
3 ThreadId,
4 type OrchestrationV2ThreadShell,
5 type PullRequestUnavailableError,
6} from "@t3tools/contracts";
7import * as Cause from "effect/Cause";
8import * as Context from "effect/Context";
9import * as SecureRandom from "effect/crypto/SecureRandom";
10import * as Effect from "effect/Effect";
11import * as Layer from "effect/Layer";
12import * as Option from "effect/Option";
13import * as Schema from "effect/Schema";
14
15import * as Orchestrator from "../orchestration-v2/Orchestrator.ts";
16import * as ProjectService from "../project/ProjectService.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 PullRequestNotOpenError extends Schema.TaggedError<PullRequestNotOpenError>()(
39 "PullRequestNotOpenError",
40 { state: Schema.String },
41) {
42 override get message(): string {
43 return `The pull request is ${this.state}, so there is nothing to watch.`;
44 }
45}
46
47export class PullRequestWatchFromSubagentError extends Schema.TaggedError<PullRequestWatchFromSubagentError>()(
48 "PullRequestWatchFromSubagentError",
49 {},
50) {
51 override get message(): string {
52 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.";
53 }
54}
55
56export class PullRequestWatchThreadNotFoundError extends Schema.TaggedError<PullRequestWatchThreadNotFoundError>()(
57 "PullRequestWatchThreadNotFoundError",
58 { threadId: ThreadId },
59) {
60 override get message(): string {
61 return `Thread ${this.threadId} was not found.`;
62 }
63}
64
65export class PullRequestWatchService extends Context.Service<
66 PullRequestWatchService,
67 {
68 readonly setWatching: (input: {
69 readonly threadId: ThreadId;
70 readonly target: PullRequestTarget;
71 readonly watching: boolean;
72 }) => Effect.Effect<
73 ResolvedTarget & { readonly watching: boolean; readonly wasWatching: boolean },
74 | PullRequestWatchFailedError
75 | PullRequestNotOpenError
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 }) {
108 const { watching } = input;
109 const thread = yield* requireThread(input.threadId);
110 const project = yield* projects.getShell(thread.projectId).pipe(
111 Effect.map(Option.getOrUndefined),
112 Effect.mapError((cause) => new PullRequestWatchFailedError({ cause })),
113 );
114 const target = yield* resolveTarget(input.target, project);
115 const watchedLink = (shell: OrchestrationV2ThreadShell) =>
116 threadPullRequestsOf(shell).find(
117 (link) => link.source !== "stack-dismissed" && threadPullRequestKeysEqual(link, target),
118 );
119 if (watching && thread.lineage.relationshipToParent === "subagent") {
120 return yield* new PullRequestWatchFromSubagentError();
121 }
122 const before = watchedLink(thread);
123 if (watching && before?.snapshot?.state === "merged") {
124 return yield* new PullRequestNotOpenError({ state: "merged" });
125 }
126 if (watching && before?.watch === undefined) {
127 yield* pullRequests
128 .summary(
129 {
130 projectId: thread.projectId,
131 host: target.host,
132 repository: target.repository,
133 number: target.number,
134 allowStale: false,
135 },
136 { recoverTransientFailure: false, bypassCache: true },
137 )
138 .pipe(
139 Effect.flatMap((summary) =>
140 summary.state === "merged"
141 ? Effect.fail(new PullRequestNotOpenError({ state: "merged" }))
142 : Effect.void,
143 ),
144 Effect.catchTags({
145 // Host and transport errors can recover while the watch is active.
146 PullRequestOperationError: () => Effect.void,
147 }),
148 );
149 }
150 const uuid = yield* random.uuidV4().pipe(Effect.orDie);
151 yield* engine
152 .dispatch({
153 type: "thread.pull-request.watch",
154 commandId: CommandId.make(`server:mcp-pr-watch:${thread.id}:${uuid}`),
155 threadId: thread.id,
156 host: target.host,
157 repository: target.repository,
158 number: target.number,
159 watching,
160 ...(watching ? { link: { url: target.url, source: "agent" as const } } : {}),
161 })
162 .pipe(
163 Effect.catchCause((cause) =>
164 Cause.hasInterruptsOnly(cause)
165 ? Effect.failCause(cause as Cause.Cause<never>)
166 : Effect.fail(new PullRequestWatchFailedError({ cause })),
167 ),
168 );
169 const after = yield* requireThread(thread.id);
170 return {
171 ...target,
172 watching: watchedLink(after)?.watch !== undefined,
173 wasWatching: before?.watch !== undefined,
174 };
175 });
176
177 return PullRequestWatchService.of({ setWatching });
178});
179
180export const layer = Layer.effect(PullRequestWatchService, make);