@devries-cameron20 / t3code-1 / commits / f59aa4eba0
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

fix(server): reject PR watches when hosting dependencies are unavailable (#33389)

Co-authored-by: Daniel D <1325654+complynx@users.noreply.github.com> Co-authored-by: Julius Marminge <julius0216@outlook.com>

Daniel committed Nov 13, 2026 at 00:46 UTC f59aa4eba0b3e588e8232ba5bf68a3829d6fc80b
11 files changed +718 -288
apps/server/src/mcp/McpHttpServer.test.ts
+3
@@ -44,6 +44,7 @@ import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
44
45 import * as DeviceService from "../device/DeviceService.ts";
46 import * as PullRequestReviewGuideService from "../pullRequest/PullRequestReviewGuideService.ts";
47 +import * as PullRequestService from "../pullRequest/PullRequestService.ts";
48 import * as ServerConfig from "../config.ts";
49 import * as ServerSettings from "../serverSettings.ts";
50 import { advertisedJsonSchema } from "./advertisedJsonSchema.ts";
@@ -100,6 +101,7 @@ const layerPullRequestsTest = McpHttpServer.layerPullRequestsToolkit.pipe(
101 Layer.mergeAll(
102 Layer.mock(ProjectService.ProjectService)({}),
103 Layer.mock(PullRequestReviewGuideService.PullRequestReviewGuideService)({}),
104 + Layer.mock(PullRequestService.PullRequestService)({}),
105 Layer.mock(Orchestrator.OrchestratorV2)({}),
106 Layer.mock(ProjectionStore.ProjectionStoreV2)({}),
107 NodeServices.layer,
@@ -1543,6 +1545,7 @@ it.effect("lists pull request watch tools only to threads that are not delegated
1545 McpToolAccessTestkit.liveThreadsLayer,
1546 Layer.mock(ProjectService.ProjectService)({}),
1547 Layer.mock(PullRequestReviewGuideService.PullRequestReviewGuideService)({}),
1548 + Layer.mock(PullRequestService.PullRequestService)({}),
1549 Layer.mock(Orchestrator.OrchestratorV2)({}),
1550 Layer.mock(ProjectionStore.ProjectionStoreV2)({}),
1551 NodeServices.layer,
apps/server/src/mcp/McpHttpServer.ts
+2 -1
@@ -33,6 +33,7 @@ import * as DeviceService from "../device/DeviceService.ts";
33 import * as HtmlRender from "../htmlRender/HtmlRender.ts";
34 import * as ThreadCommandExecutor from "../orchestration-v2/ThreadCommandExecutor.ts";
35 import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts";
36 +import * as PullRequestWatchService from "../pullRequest/PullRequestWatchService.ts";
37 import * as ProviderRegistry from "../provider/ProviderRegistry.ts";
38 import * as AnalyticsService from "../telemetry/AnalyticsService.ts";
39 import {
@@ -1268,7 +1269,7 @@ export const layerAttachmentToolkit = toolkitRegistration(
1269 export const layerPullRequestsToolkit = toolkitRegistration(
1270 PullRequestsToolkit,
1271 PullRequestsHandlers.layer,
1271 -);
1272 +).pipe(Layer.provide(PullRequestWatchService.layer));
1273
1274 const layerDeviceStandardToolkitRegistration = toolkitRegistration(
1275 DeviceStandardToolkit,
apps/server/src/mcp/toolkits/pullRequests/handlers.test.ts
+2 -87
@@ -26,6 +26,7 @@ import {
26 v2PullRequestThread,
27 } from "../../../orchestration-v2/testkit/pullRequestFixtures.ts";
28 import * as ProjectService from "../../../project/ProjectService.ts";
29 +import * as PullRequestWatchService from "../../../pullRequest/PullRequestWatchService.ts";
30 import * as PullRequestReviewGuideService from "../../../pullRequest/PullRequestReviewGuideService.ts";
31 import * as McpInvocationContext from "../../McpInvocationContext.ts";
32 import * as McpToolAccess from "../../McpToolAccess.ts";
@@ -167,6 +168,7 @@ const makeHarness = Effect.fn("makePullRequestsToolkitHarness")(function* (
168 return { sequence: 1, storedEvents: [] };
169 });
170 const layerDependencies = Layer.mergeAll(
171 + Layer.mock(PullRequestWatchService.PullRequestWatchService)({}),
172 Layer.mock(ProjectService.ProjectService)({
173 getShell: () => Effect.succeed(Option.fromNullishOr(project)),
174 listShells: () => Effect.succeed(options.projects ?? (project ? [project] : [])),
@@ -278,93 +280,6 @@ describe("pull request toolkit handlers", () => {
280 }),
281 );
282
281 - it.effect("watching an unlinked pull request links it first", () =>
282 - Effect.gen(function* () {
283 - const harness = yield* makeHarness();
284 - const result = yield* harness.call("watch_pull_request", {
285 - url: "https://github.com/t3tools/t3code/pull/9",
286 - });
287 - expect(result).toMatchObject({ number: 9, watching: false, wasWatching: false });
288 - expect(yield* Ref.get(harness.commands)).toMatchObject([
289 - {
290 - type: "thread.pull-request.watch",
291 - number: 9,
292 - watching: true,
293 - link: { url: "https://github.com/t3tools/t3code/pull/9", source: "agent" },
294 - },
295 - ]);
296 - }),
297 - );
298 -
299 - it.effect("refuses to watch a merged pull request and stops an existing watch", () =>
300 - Effect.gen(function* () {
301 - const watch = {
302 - startedAt: "2026-08-20T00:00:00.000Z",
303 - headSha: null,
304 - failedChecks: [],
305 - passed: false,
306 - passedChecks: [],
307 - remarksThrough: "2026-08-20T00:00:00.000Z",
308 - remarkIds: [],
309 - conflicting: false,
310 - wakes: 0,
311 - };
312 - const merged = makeLink(1, { headBranch: "done" });
313 - const harness = yield* makeHarness({
314 - thread: makeThread([
315 - { ...merged, snapshot: merged.snapshot && { ...merged.snapshot, state: "merged" } },
316 - makeLink(2, { headBranch: "idle" }),
317 - makeLink(3, { headBranch: "watched", watch }),
318 - ]),
319 - });
320 - const error = yield* harness
321 - .call("watch_pull_request", { repository: "t3tools/t3code", number: 1 })
322 - .pipe(Effect.flip);
323 - expect(error).toMatchObject({ _tag: "PullRequestNotOpenError", state: "merged" });
324 - expect(
325 - yield* harness.call("unwatch_pull_request", { repository: "t3tools/t3code", number: 3 }),
326 - ).toMatchObject({ wasWatching: true });
327 - expect(yield* Ref.get(harness.commands)).toMatchObject([
328 - { type: "thread.pull-request.watch", number: 3, watching: false },
329 - ]);
330 - }),
331 - );
332 -
333 - it.effect("watches a pull request saved as closed, since it may have reopened", () =>
334 - Effect.gen(function* () {
335 - const closed = makeLink(1, { headBranch: "closed" });
336 - const harness = yield* makeHarness({
337 - thread: makeThread([
338 - { ...closed, snapshot: closed.snapshot && { ...closed.snapshot, state: "closed" } },
339 - ]),
340 - });
341 - yield* harness.call("watch_pull_request", { repository: "t3tools/t3code", number: 1 });
342 - expect(yield* Ref.get(harness.commands)).toMatchObject([
343 - { type: "thread.pull-request.watch", number: 1, watching: true },
344 - ]);
345 - }),
346 - );
347 -
348 - it.effect("refuses a watch from a subagent thread, whose parent owns the pull request", () =>
349 - Effect.gen(function* () {
350 - const harness = yield* makeHarness({
351 - thread: {
352 - ...makeThread([makeLink(1, { headBranch: "feature" })]),
353 - lineage: {
354 - rootThreadId: ThreadId.make("parent"),
355 - parentThreadId: ThreadId.make("parent"),
356 - relationshipToParent: "subagent",
357 - },
358 - },
359 - });
360 - const error = yield* harness
361 - .call("watch_pull_request", { repository: "t3tools/t3code", number: 1 })
362 - .pipe(Effect.flip);
363 - expect(error).toMatchObject({ _tag: "PullRequestWatchFromSubagentError" });
364 - expect(yield* Ref.get(harness.commands)).toEqual([]);
365 - }),
366 - );
367 -
283 it.effect("asks a subagent thread to end with its PR report after it links", () =>
284 Effect.gen(function* () {
285 const harness = yield* makeHarness({
apps/server/src/mcp/toolkits/pullRequests/handlers.ts
+18 -128
@@ -2,11 +2,9 @@ import {
2 CommandId,
3 type OrchestrationProjectShell,
4 type OrchestrationV2ThreadShell,
5 - type SourceControlProviderKind,
5 type ThreadId,
6 type ThreadPullRequestLink,
7 } from "@t3tools/contracts";
9 -import { canonicalizeGitCafePullRequestUrl } from "@t3tools/source-control-definitions/registry";
8 import * as Cause from "effect/Cause";
9 import * as SecureRandom from "effect/crypto/SecureRandom";
10 import * as Effect from "effect/Effect";
@@ -14,6 +12,8 @@ import * as Option from "effect/Option";
12
13 import * as Orchestrator from "../../../orchestration-v2/Orchestrator.ts";
14 import * as ProjectService from "../../../project/ProjectService.ts";
15 +import * as PullRequestWatchService from "../../../pullRequest/PullRequestWatchService.ts";
16 +import { resolveTarget, type ResolvedTarget } from "../../../pullRequest/pullRequestTarget.ts";
17 import * as PullRequestReviewGuideService from "../../../pullRequest/PullRequestReviewGuideService.ts";
18 import { pullRequestSyncKey } from "../../../pullRequest/pullRequestSyncKey.ts";
19 import { sourceControlDefinitions } from "../../../sourceControl/sourceControlDefinitions.ts";
@@ -31,16 +31,9 @@ import { threadNotFound } from "../../threadAccess.ts";
31 import {
32 type ListThreadPullRequestsResult,
33 PullRequestLinkFailedError,
34 - PullRequestUrlInvalidError,
35 - PullRequestTargetIncompleteError,
36 - PullRequestHostRequiredError,
37 - PullRequestUrlUnavailableError,
34 PullRequestUnlinkFailedError,
35 PullRequestListFailedError,
40 - PullRequestNotOpenError,
36 type PullRequestTargetInput,
42 - PullRequestWatchFailedError,
43 - PullRequestWatchFromSubagentError,
37 PullRequestThreadRequiredError,
38 PullRequestGuideFailedError,
39 PullRequestProjectNotFoundError,
@@ -49,73 +42,6 @@ import {
42 CHILD_PULL_REQUEST_REPORT_NEXT,
43 } from "./tools.ts";
44
52 -interface ResolvedTarget {
53 - readonly host: string;
54 - readonly repository: string;
55 - readonly number: number;
56 - readonly url: string;
57 -}
58 -
59 -function projectHostAndProvider(project: OrchestrationProjectShell | undefined): {
60 - readonly host: string | null;
61 - readonly kind: SourceControlProviderKind | null;
62 -} {
63 - const identity = project?.repositoryIdentity;
64 - const kind = identity?.provider ?? null;
65 - if (!identity || kind === null) return { host: null, kind: null };
66 - return {
67 - host: sourceControlDefinitions.changeRequestHost(identity, kind),
68 - kind,
69 - };
70 -}
71 -
72 -const resolveTarget = Effect.fn("PullRequestsToolkit.resolveTarget")(function* (
73 - input: PullRequestTargetInput,
74 - project: OrchestrationProjectShell | undefined,
75 -) {
76 - if (input.url !== undefined) {
77 - const parsed = sourceControlDefinitions.parseChangeRequestUrl(input.url)?.link;
78 - if (parsed === undefined) {
79 - return yield* new PullRequestUrlInvalidError({});
80 - }
81 - return {
82 - ...normalizeThreadPullRequestKey(parsed),
83 - url: canonicalizeGitCafePullRequestUrl(input.url),
84 - } satisfies ResolvedTarget;
85 - }
86 - if (input.repository === undefined || input.number === undefined) {
87 - return yield* new PullRequestTargetIncompleteError({});
88 - }
89 - const projectHost = projectHostAndProvider(project);
90 - const host = (input.host ?? projectHost.host)?.toLowerCase();
91 - if (host === undefined) {
92 - return yield* new PullRequestHostRequiredError({});
93 - }
94 - const repository = input.repository.toLowerCase();
95 - // Without a URL, a public forge host says what shape its change request URLs take;
96 - // any other host is taken to run the project's own forge.
97 - const recognizedKind = sourceControlDefinitions.recognizeRemote(`https://${host}`)?.kind;
98 - const kind =
99 - sourceControlDefinitions.findByPublicHost(host)?.kind ??
100 - (recognizedKind === "gitcafe" ? recognizedKind : projectHost.kind);
101 - const url =
102 - kind === null
103 - ? null
104 - : sourceControlDefinitions.get(kind).changeRequestUrl({
105 - host,
106 - repository,
107 - number: input.number,
108 - remoteUrl: project?.repositoryIdentity?.locator.remoteUrl,
109 - });
110 - if (url === null) {
111 - return yield* new PullRequestUrlUnavailableError({});
112 - }
113 - return {
114 - ...normalizeThreadPullRequestKey({ host, repository, number: input.number, url }),
115 - url: canonicalizeGitCafePullRequestUrl(url),
116 - } satisfies ResolvedTarget;
117 -});
118 -
45 function entryOf(
46 link: ThreadPullRequestLink,
47 chains: ReturnType<typeof resolveThreadPullRequestChains>,
@@ -198,6 +124,7 @@ function projectForPullRequest(
124 const make = Effect.gen(function* () {
125 const engine = yield* Orchestrator.OrchestratorV2;
126 const reviewGuides = yield* PullRequestReviewGuideService.PullRequestReviewGuideService;
127 + const watches = yield* PullRequestWatchService.PullRequestWatchService;
128
129 const projects = yield* ProjectService.ProjectService;
130 const random = yield* SecureRandom.SecureRandom;
@@ -212,8 +139,7 @@ const make = Effect.gen(function* () {
139 Failure:
140 | typeof PullRequestLinkFailedError
141 | typeof PullRequestUnlinkFailedError
215 - | typeof PullRequestListFailedError
216 - | typeof PullRequestWatchFailedError,
142 + | typeof PullRequestListFailedError,
143 requested: ThreadId | undefined,
144 ) {
145 const scope = yield* McpInvocationContext.requireMcpCapability("pull-requests");
@@ -233,10 +159,7 @@ const make = Effect.gen(function* () {
159
160 const projectOf = (
161 thread: OrchestrationV2ThreadShell,
236 - Failure:
237 - | typeof PullRequestLinkFailedError
238 - | typeof PullRequestUnlinkFailedError
239 - | typeof PullRequestWatchFailedError,
162 + Failure: typeof PullRequestLinkFailedError | typeof PullRequestUnlinkFailedError,
163 ) =>
164 projects.getShell(thread.projectId).pipe(
165 Effect.map(Option.getOrUndefined),
@@ -244,61 +167,28 @@ const make = Effect.gen(function* () {
167 );
168
169 const dispatchFailure =
247 - (
248 - Failure:
249 - | typeof PullRequestLinkFailedError
250 - | typeof PullRequestUnlinkFailedError
251 - | typeof PullRequestWatchFailedError,
252 - ) =>
170 + (Failure: typeof PullRequestLinkFailedError | typeof PullRequestUnlinkFailedError) =>
171 <E>(
172 cause: Cause.Cause<E>,
255 - ): Effect.Effect<
256 - never,
257 - PullRequestLinkFailedError | PullRequestUnlinkFailedError | PullRequestWatchFailedError
258 - > =>
173 + ): Effect.Effect<never, PullRequestLinkFailedError | PullRequestUnlinkFailedError> =>
174 Cause.hasInterruptsOnly(cause)
175 ? Effect.failCause(cause as Cause.Cause<never>)
176 : Effect.fail(new Failure({ cause }));
177
263 - const setWatching = Effect.fn("PullRequestsToolkit.setWatching")(function* (
178 + // The domain service owns the registration span.
179 + const setWatching = Effect.fnUntraced(function* (
180 input: PullRequestTargetInput,
181 watching: boolean,
182 ) {
267 - const thread = yield* requireThread(PullRequestWatchFailedError, input.threadId);
268 - const project = yield* projectOf(thread, PullRequestWatchFailedError);
269 - const target = yield* resolveTarget(input, project);
270 - const watchedLink = (shell: OrchestrationV2ThreadShell) =>
271 - threadPullRequestsOf(shell).find(
272 - (link) => link.source !== "stack-dismissed" && threadPullRequestKeysEqual(link, target),
273 - );
274 - if (watching && thread.lineage.relationshipToParent === "subagent") {
275 - return yield* new PullRequestWatchFromSubagentError();
276 - }
277 - const before = watchedLink(thread);
278 - if (watching && before?.snapshot?.state === "merged") {
279 - return yield* new PullRequestNotOpenError({ state: "merged" });
280 - }
281 - yield* engine
282 - .dispatch({
283 - type: "thread.pull-request.watch",
284 - commandId: yield* commandId("mcp-pr-watch", thread.id),
285 - threadId: thread.id,
286 - host: target.host,
287 - repository: target.repository,
288 - number: target.number,
289 - watching,
290 - ...(watching ? { link: { url: target.url, source: "agent" as const } } : {}),
291 - })
292 - .pipe(Effect.catchCause(dispatchFailure(PullRequestWatchFailedError)));
293 - const after = yield* requireThread(PullRequestWatchFailedError, thread.id);
294 - return {
295 - host: target.host,
296 - repository: target.repository,
297 - number: target.number,
298 - url: target.url,
299 - watching: watchedLink(after)?.watch !== undefined,
300 - wasWatching: before?.watch !== undefined,
301 - };
183 + const scope = yield* McpInvocationContext.requireMcpCapability("pull-requests");
184 + const threadId = input.threadId ?? scope.thread?.threadId;
185 + if (threadId === undefined) return yield* new PullRequestThreadRequiredError();
186 + return yield* watches.setWatching({ threadId, target: input, watching }).pipe(
187 + Effect.catchTags({
188 + PullRequestWatchThreadNotFoundError: (error) =>
189 + threadNotFound(engine, error.threadId, error.message),
190 + }),
191 + );
192 });
193
194 const locateAll = Effect.fn("PullRequestsToolkit.locateAll")(function* (
apps/server/src/mcp/toolkits/pullRequests/tools.ts
+16 -68
@@ -6,6 +6,7 @@ import {
6 PullRequestReviewGuide,
7 PullRequestReviewGuideRun,
8 PullRequestState,
9 + PullRequestUnavailableError,
10 ThreadPullRequestLinkSource,
11 TrimmedNonEmptyString,
12 ThreadId,
@@ -19,6 +20,13 @@ import * as McpInvocationContext from "../../McpInvocationContext.ts";
20 import * as Orchestrator from "../../../orchestration-v2/Orchestrator.ts";
21 import * as ThreadManagementService from "../../../orchestration-v2/ThreadManagementService.ts";
22 import * as ProjectService from "../../../project/ProjectService.ts";
23 +import * as PullRequestWatchService from "../../../pullRequest/PullRequestWatchService.ts";
24 +import {
25 + PullRequestUrlInvalidError,
26 + PullRequestTargetIncompleteError,
27 + PullRequestHostRequiredError,
28 + PullRequestUrlUnavailableError,
29 +} from "../../../pullRequest/pullRequestTarget.ts";
30 import * as PullRequestReviewGuideService from "../../../pullRequest/PullRequestReviewGuideService.ts";
31
32 const dependencies = [
@@ -33,6 +41,8 @@ const guideDependencies = [
41 PullRequestReviewGuideService.PullRequestReviewGuideService,
42 ];
43
44 +const watchDependencies = [...dependencies, PullRequestWatchService.PullRequestWatchService];
45 +
46 export const PullRequestTargetInput = Schema.Struct({
47 environmentId: OrchestratorMcpEnvironmentTarget,
48 threadId: Schema.optional(
@@ -59,42 +69,6 @@ export const PullRequestTargetInput = Schema.Struct({
69 });
70 export type PullRequestTargetInput = typeof PullRequestTargetInput.Type;
71
62 -export class PullRequestUrlInvalidError extends Schema.TaggedError<PullRequestUrlInvalidError>()(
63 - "PullRequestUrlInvalidError",
64 - {},
65 -) {
66 - override get message(): string {
67 - return "This is not a recognised pull request URL. Pass repository and number instead.";
68 - }
69 -}
70 -
71 -export class PullRequestTargetIncompleteError extends Schema.TaggedError<PullRequestTargetIncompleteError>()(
72 - "PullRequestTargetIncompleteError",
73 - {},
74 -) {
75 - override get message(): string {
76 - return "Pass either url, or both repository and number.";
77 - }
78 -}
79 -
80 -export class PullRequestHostRequiredError extends Schema.TaggedError<PullRequestHostRequiredError>()(
81 - "PullRequestHostRequiredError",
82 - {},
83 -) {
84 - override get message(): string {
85 - return "This thread's project has no recognised remote. Pass host or url.";
86 - }
87 -}
88 -
89 -export class PullRequestUrlUnavailableError extends Schema.TaggedError<PullRequestUrlUnavailableError>()(
90 - "PullRequestUrlUnavailableError",
91 - {},
92 -) {
93 - override get message(): string {
94 - return "This thread's project is on a host with no known pull request URL shape. Pass url.";
95 - }
96 -}
97 -
72 export class PullRequestThreadRequiredError extends Schema.TaggedError<PullRequestThreadRequiredError>()(
73 "PullRequestThreadRequiredError",
74 {},
@@ -122,33 +96,6 @@ export class PullRequestUnlinkFailedError extends Schema.TaggedError<PullRequest
96 }
97 }
98
125 -export class PullRequestWatchFailedError extends Schema.TaggedError<PullRequestWatchFailedError>()(
126 - "PullRequestWatchFailedError",
127 - { cause: Schema.Defect() },
128 -) {
129 - override get message(): string {
130 - return "Could not change whether the pull request is watched.";
131 - }
132 -}
133 -
134 -export class PullRequestNotOpenError extends Schema.TaggedError<PullRequestNotOpenError>()(
135 - "PullRequestNotOpenError",
136 - { state: Schema.String },
137 -) {
138 - override get message(): string {
139 - return `The pull request is ${this.state}, so there is nothing to watch.`;
140 - }
141 -}
142 -
143 -export class PullRequestWatchFromSubagentError extends Schema.TaggedError<PullRequestWatchFromSubagentError>()(
144 - "PullRequestWatchFromSubagentError",
145 - {},
146 -) {
147 - override get message(): string {
148 - 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.";
149 - }
150 -}
151 -
99 export class PullRequestListFailedError extends Schema.TaggedError<PullRequestListFailedError>()(
100 "PullRequestListFailedError",
101 { cause: Schema.Defect() },
@@ -187,9 +134,10 @@ export const PullRequestToolError = Schema.Union([
134 PullRequestLinkFailedError,
135 PullRequestUnlinkFailedError,
136 PullRequestListFailedError,
190 - PullRequestWatchFailedError,
191 - PullRequestNotOpenError,
192 - PullRequestWatchFromSubagentError,
137 + PullRequestWatchService.PullRequestWatchFailedError,
138 + PullRequestUnavailableError,
139 + PullRequestWatchService.PullRequestNotOpenError,
140 + PullRequestWatchService.PullRequestWatchFromSubagentError,
141 PullRequestProjectNotFoundError,
142 PullRequestGuideFailedError,
143 ]);
@@ -378,7 +326,7 @@ const WatchPullRequestTool = Tool.make("watch_pull_request", {
326 parameters: PullRequestTargetInput,
327 success: WatchPullRequestResult,
328 failure: PullRequestToolError,
381 - dependencies,
329 + dependencies: watchDependencies,
330 })
331 .annotate(Tool.Title, "Watch pull request")
332 .annotate(Tool.Readonly, false)
@@ -392,7 +340,7 @@ const UnwatchPullRequestTool = Tool.make("unwatch_pull_request", {
340 parameters: PullRequestTargetInput,
341 success: WatchPullRequestResult,
342 failure: PullRequestToolError,
395 - dependencies,
343 + dependencies: watchDependencies,
344 })
345 .annotate(Tool.Title, "Stop watching pull request")
346 .annotate(Tool.Readonly, false)
apps/server/src/provider/AgentContextBudget.test.ts
+2
@@ -35,6 +35,7 @@ import { ProjectCloneTracker } from "../project/ProjectCloneTracker.ts";
35 import { ProjectService } from "../project/ProjectService.ts";
36 import { ProjectSetupScriptRunner } from "../project/ProjectSetupScriptRunner.ts";
37 import { PullRequestReviewGuideService } from "../pullRequest/PullRequestReviewGuideService.ts";
38 +import { PullRequestService } from "../pullRequest/PullRequestService.ts";
39 import { ScheduledTaskService } from "../scheduledTasks/ScheduledTaskService.ts";
40 import { SecretRequests } from "../secrets/SecretRequests.ts";
41 import { ServerSettingsService } from "../serverSettings.ts";
@@ -68,6 +69,7 @@ const toolHandlerServices = Layer.mergeAll(
69 Layer.mock(ProviderAdapterRegistryV2)({}),
70 Layer.mock(ProviderRegistry)({}),
71 Layer.mock(PullRequestReviewGuideService)({}),
72 + Layer.mock(PullRequestService)({}),
73 Layer.mock(RemoteDelegation)({}),
74 Layer.mock(ScheduledTaskService)({}),
75 Layer.mock(SecretRequests)({}),
apps/server/src/pullRequest/PullRequestService.test.ts
+66
@@ -2215,6 +2215,72 @@ it.effect("routes a hosted reference to another repository through a project on
2215 }),
2216 );
2217
2218 +it.effect("an uncached summary reaches the host despite a cached read in another project", () =>
2219 + Effect.gen(function* () {
2220 + const caller = project({
2221 + id: "caller",
2222 + title: "caller",
2223 + workspaceRoot: "/caller",
2224 + repository: "acme/other",
2225 + });
2226 + const target = project({
2227 + id: "gitlab",
2228 + title: "gitlab",
2229 + workspaceRoot: "/gitlab",
2230 + repository: "team/project",
2231 + provider: "gitlab",
2232 + });
2233 + let missing = false;
2234 + let reads = 0;
2235 + const service = yield* makeService({
2236 + projects: [caller, target],
2237 + providers: [
2238 + fakePullRequestProvider(SourceControlProviderKind.make("github")),
2239 + fakePullRequestProvider(SourceControlProviderKind.make("gitlab"), {
2240 + getChangeRequestSummary: (input) =>
2241 + Effect.suspend(() => {
2242 + reads++;
2243 + assert.strictEqual(input.cwd, target.workspaceRoot);
2244 + assert.strictEqual(input.repository, "team/project");
2245 + assert.strictEqual(input.host, "gitlab.com");
2246 + return missing
2247 + ? Effect.fail(
2248 + new PullRequestProviderError({
2249 + provider: SourceControlProviderKind.make("gitlab"),
2250 + operation: "summary",
2251 + reason: "missing-tool",
2252 + detail: "The hosting CLI is unavailable.",
2253 + }),
2254 + )
2255 + : Effect.succeed(changeRequest(42, "2026-07-02T00:00:00Z"));
2256 + }),
2257 + }),
2258 + ],
2259 + });
2260 + const reference = {
2261 + projectId: caller.id,
2262 + host: "gitlab.com",
2263 + repository: "team/project",
2264 + number: 42,
2265 + allowStale: false,
2266 + };
2267 + yield* service.summary(reference, { recoverTransientFailure: false });
2268 + missing = true;
2269 + yield* service.summary(reference, { recoverTransientFailure: false });
2270 + assert.strictEqual(reads, 1);
2271 +
2272 + const error = yield* service
2273 + .summary(reference, { recoverTransientFailure: false, bypassCache: true })
2274 + .pipe(Effect.flip);
2275 + expect(error).toMatchObject({
2276 + _tag: "PullRequestUnavailableError",
2277 + reason: "cli-missing",
2278 + provider: "gitlab",
2279 + });
2280 + assert.strictEqual(reads, 2);
2281 + }),
2282 +);
2283 +
2284 it.effect("routes Azure reads and writes through the requested organization's checkout", () =>
2285 Effect.gen(function* () {
2286 const seen: string[] = [];
apps/server/src/pullRequest/PullRequestService.ts
+12 -4
@@ -198,7 +198,11 @@ export class PullRequestService extends Context.Service<
198 ) => Effect.Effect<A, E | PullRequestError, R>;
199 readonly summary: (
200 input: PullRequestRef,
201 - options?: { readonly recoverTransientFailure?: boolean },
201 + options?: {
202 + readonly recoverTransientFailure?: boolean;
203 + /** Registration preflights must reach the provider despite a successful cached read. */
204 + readonly bypassCache?: boolean;
205 + },
206 ) => Effect.Effect<PullRequestSummary, PullRequestError>;
207 /** Whether the reference's host batches summary reads; false when it cannot be resolved. */
208 readonly batchesReads: (input: PullRequestRef) => Effect.Effect<boolean>;
@@ -3067,13 +3071,17 @@ export const make = Effect.gen(function* () {
3071
3072 const summary: PullRequestService["Service"]["summary"] = (input, options) => {
3073 const key = refCacheKey(input);
3070 - const cached = persistedRead(input, "summary", summaryCodec, summaryUncached(input));
3074 + const read =
3075 + options?.bypassCache === true
3076 + ? summaryUncached(input)
3077 + : persistedRead(input, "summary", summaryCodec, summaryUncached(input));
3078 const held = lastGoodSummary.peek(key);
3072 - return held !== undefined &&
3079 + return options?.bypassCache !== true &&
3080 + held !== undefined &&
3081 input.allowStale !== false &&
3082 (options?.recoverTransientFailure !== false || held.state === "merged")
3083 ? Effect.succeed(held)
3076 - : cached.pipe(
3084 + : read.pipe(
3085 Effect.tap((value) =>
3086 shouldReplaceHeldSummary(key, value) ? lastGoodSummary.record(key, value) : Effect.void,
3087 ),
apps/server/src/pullRequest/PullRequestWatchService.test.ts new
+294
@@ -0,0 +1,294 @@
1 +import {
2 + ProjectId,
3 + ProviderInstanceId,
4 + ThreadId,
5 + PullRequestOperationError,
6 + PullRequestUnavailableError,
7 + type PullRequestSummary,
8 + type OrchestrationV2ServerCommand as OrchestrationCommand,
9 + type OrchestrationProjectShell,
10 + type ThreadPullRequestLink,
11 + SourceControlProviderKind,
12 +} from "@t3tools/contracts";
13 +import { describe, expect, it } from "@effect/vitest";
14 +import * as SecureRandom from "effect/crypto/SecureRandom";
15 +import * as Effect from "effect/Effect";
16 +import * as Layer from "effect/Layer";
17 +import * as Option from "effect/Option";
18 +import * as Ref from "effect/Ref";
19 +
20 +import * as Orchestrator from "../orchestration-v2/Orchestrator.ts";
21 +import {
22 + type PullRequestTestThread,
23 + v2PullRequestThread,
24 +} from "../orchestration-v2/testkit/pullRequestFixtures.ts";
25 +import * as ProjectService from "../project/ProjectService.ts";
26 +import * as PullRequestService from "./PullRequestService.ts";
27 +import * as PullRequestWatchService from "./PullRequestWatchService.ts";
28 +import type { PullRequestTarget } from "./pullRequestTarget.ts";
29 +
30 +const PROJECT_ID = ProjectId.make("project-1");
31 +const THREAD_ID = ThreadId.make("thread-1");
32 +const testCrypto = SecureRandom.make((size) => new Uint8Array(size).fill(7));
33 +
34 +function makeProject(
35 + repositoryIdentity: OrchestrationProjectShell["repositoryIdentity"] = {
36 + canonicalKey: "github.com/t3tools/t3code",
37 + locator: {
38 + source: "git-remote",
39 + remoteName: "origin",
40 + remoteUrl: "git@github.com:T3Tools/T3Code.git",
41 + },
42 + provider: SourceControlProviderKind.make("github"),
43 + displayName: "T3Tools/T3Code",
44 + owner: "T3Tools",
45 + name: "T3Code",
46 + },
47 +): OrchestrationProjectShell {
48 + return {
49 + id: PROJECT_ID,
50 + title: "Project",
51 + workspaceRoot: "/workspace/project",
52 + defaultModelSelection: null,
53 + scripts: [],
54 + repositoryIdentity,
55 + createdAt: "2026-08-01T00:00:00.000Z",
56 + updatedAt: "2026-08-01T00:00:00.000Z",
57 + };
58 +}
59 +
60 +function makeThread(pullRequests: ReadonlyArray<ThreadPullRequestLink>): PullRequestTestThread {
61 + return {
62 + id: THREAD_ID,
63 + projectId: PROJECT_ID,
64 + title: "Thread",
65 + modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5" },
66 + runtimeMode: "full-access",
67 + interactionMode: "default",
68 + branch: null,
69 + worktreePath: null,
70 + pullRequests,
71 + createdAt: "2026-08-01T00:00:00.000Z",
72 + updatedAt: "2026-08-20T00:00:00.000Z",
73 + archivedAt: null,
74 + settledOverride: null,
75 + settledAt: null,
76 + latestUserMessageAt: "2026-08-20T00:00:00.000Z",
77 + };
78 +}
79 +
80 +function makeLink(
81 + number: number,
82 + overrides: Partial<ThreadPullRequestLink> & {
83 + readonly headBranch?: string;
84 + readonly baseBranch?: string;
85 + } = {},
86 +): ThreadPullRequestLink {
87 + const { headBranch, baseBranch, ...rest } = overrides;
88 + return {
89 + host: "github.com",
90 + repository: "t3tools/t3code",
91 + number,
92 + url: `https://github.com/t3tools/t3code/pull/${number}`,
93 + source: "manual",
94 + linkedAt: "2026-08-10T00:00:00.000Z",
95 + snapshot:
96 + headBranch === undefined
97 + ? null
98 + : {
99 + state: "open",
100 + title: `PR ${number}`,
101 + headBranch,
102 + baseBranch: baseBranch ?? "main",
103 + isDraft: false,
104 + updatedAt: null,
105 + syncedAt: "2026-08-27T00:00:00.000Z",
106 + },
107 + stack: null,
108 + ...rest,
109 + };
110 +}
111 +
112 +interface HarnessOptions {
113 + readonly thread?: PullRequestTestThread | null;
114 + readonly project?: OrchestrationProjectShell | null;
115 + readonly readFailure?: PullRequestService.PullRequestError;
116 + readonly readState?: PullRequestSummary["state"];
117 +}
118 +
119 +const makeHarness = Effect.fn("makePullRequestWatchHarness")(function* (
120 + options: HarnessOptions = {},
121 +) {
122 + const commands = yield* Ref.make<ReadonlyArray<OrchestrationCommand>>([]);
123 + const thread = options.thread === undefined ? makeThread([]) : options.thread;
124 + const project = options.project === undefined ? makeProject() : options.project;
125 + const dependencies = Layer.mergeAll(
126 + Layer.mock(ProjectService.ProjectService)({
127 + getShell: () => Effect.succeed(Option.fromNullishOr(project)),
128 + }),
129 + Layer.mock(Orchestrator.OrchestratorV2)({
130 + getThreadShell: (id) =>
131 + Effect.succeed(id === thread?.id ? v2PullRequestThread(thread) : null),
132 + dispatch: (command) =>
133 + Ref.update(commands, (recorded) => [...recorded, command]).pipe(
134 + Effect.as({ sequence: 1, storedEvents: [] }),
135 + ),
136 + }),
137 + Layer.mock(PullRequestService.PullRequestService)({
138 + summary: (input) =>
139 + options.readFailure !== undefined
140 + ? Effect.fail(options.readFailure)
141 + : Effect.succeed({
142 + ...input,
143 + provider: SourceControlProviderKind.make("github"),
144 + title: "Pull request",
145 + url: `https://github.com/${input.repository}/pull/${input.number}`,
146 + state: options.readState ?? "open",
147 + headBranch: "feature",
148 + baseBranch: "main",
149 + updatedAt: "2026-08-20T00:00:00.000Z",
150 + }),
151 + }),
152 + Layer.succeed(SecureRandom.SecureRandom, testCrypto),
153 + );
154 + const service = yield* PullRequestWatchService.PullRequestWatchService.pipe(
155 + Effect.provide(PullRequestWatchService.layer.pipe(Layer.provide(dependencies))),
156 + );
157 + return {
158 + commands,
159 + setWatching: (watching: boolean, target: PullRequestTarget) =>
160 + service.setWatching({ threadId: THREAD_ID, target, watching }),
161 + };
162 +});
163 +
164 +describe("PullRequestWatchService", () => {
165 + it.effect("links an unlinked watch even while the host has a transient read failure", () =>
166 + Effect.gen(function* () {
167 + for (const options of [
168 + {},
169 + {
170 + readFailure: new PullRequestOperationError({
171 + operation: "summary",
172 + detail: "The host is temporarily unavailable.",
173 + }),
174 + },
175 + ]) {
176 + const harness = yield* makeHarness(options);
177 + const result = yield* harness.setWatching(true, {
178 + url: "https://github.com/t3tools/t3code/pull/9",
179 + });
180 + expect(result).toMatchObject({ number: 9, wasWatching: false });
181 + expect(yield* Ref.get(harness.commands)).toMatchObject([
182 + {
183 + type: "thread.pull-request.watch",
184 + number: 9,
185 + watching: true,
186 + link: { url: "https://github.com/t3tools/t3code/pull/9", source: "agent" },
187 + },
188 + ]);
189 + }
190 + }),
191 + );
192 +
193 + it.effect("reports a missing hosting CLI before saving a watch and still allows unwatch", () =>
194 + Effect.gen(function* () {
195 + const missing = new PullRequestUnavailableError({
196 + reason: "cli-missing",
197 + provider: SourceControlProviderKind.make("gitlab"),
198 + requirement: "Install glab on the T3 server's PATH.",
199 + });
200 + const harness = yield* makeHarness({ readFailure: missing });
201 + const target = { url: "https://gitlab.example.com/team/project/-/merge_requests/42" };
202 + const error = yield* harness.setWatching(true, target).pipe(Effect.flip);
203 + expect(error).toEqual(missing);
204 + expect(yield* Ref.get(harness.commands)).toEqual([]);
205 +
206 + yield* harness.setWatching(false, target);
207 + expect(yield* Ref.get(harness.commands)).toMatchObject([
208 + { type: "thread.pull-request.watch", watching: false },
209 + ]);
210 + }),
211 + );
212 +
213 + it.effect("rejects merged PRs and keeps an active watch usable without hosting access", () =>
214 + Effect.gen(function* () {
215 + const freshMerged = yield* makeHarness({ readState: "merged" });
216 + const freshError = yield* freshMerged
217 + .setWatching(true, { repository: "t3tools/t3code", number: 1 })
218 + .pipe(Effect.flip);
219 + expect(freshError).toMatchObject({ _tag: "PullRequestNotOpenError", state: "merged" });
220 + expect(yield* Ref.get(freshMerged.commands)).toEqual([]);
221 +
222 + const watch = {
223 + startedAt: "2026-08-20T00:00:00.000Z",
224 + headSha: null,
225 + failedChecks: [],
226 + passed: false,
227 + passedChecks: [],
228 + remarksThrough: "2026-08-20T00:00:00.000Z",
229 + remarkIds: [],
230 + conflicting: false,
231 + wakes: 0,
232 + };
233 + const merged = makeLink(1, { headBranch: "done" });
234 + const harness = yield* makeHarness({
235 + readFailure: new PullRequestUnavailableError({ reason: "cli-missing" }),
236 + thread: makeThread([
237 + { ...merged, snapshot: merged.snapshot && { ...merged.snapshot, state: "merged" } },
238 + makeLink(2, { headBranch: "idle" }),
239 + makeLink(3, { headBranch: "watched", watch }),
240 + ]),
241 + });
242 + const error = yield* harness
243 + .setWatching(true, { repository: "t3tools/t3code", number: 1 })
244 + .pipe(Effect.flip);
245 + expect(error).toMatchObject({ _tag: "PullRequestNotOpenError", state: "merged" });
246 + expect(
247 + yield* harness.setWatching(true, { repository: "t3tools/t3code", number: 3 }),
248 + ).toMatchObject({ watching: true, wasWatching: true });
249 + expect(
250 + yield* harness.setWatching(false, { repository: "t3tools/t3code", number: 3 }),
251 + ).toMatchObject({ wasWatching: true });
252 + expect(yield* Ref.get(harness.commands)).toMatchObject([
253 + { type: "thread.pull-request.watch", number: 3, watching: true },
254 + { type: "thread.pull-request.watch", number: 3, watching: false },
255 + ]);
256 + }),
257 + );
258 +
259 + it.effect("watches a pull request saved as closed, since it may have reopened", () =>
260 + Effect.gen(function* () {
261 + const closed = makeLink(1, { headBranch: "closed" });
262 + const harness = yield* makeHarness({
263 + readState: "closed",
264 + thread: makeThread([
265 + { ...closed, snapshot: closed.snapshot && { ...closed.snapshot, state: "closed" } },
266 + ]),
267 + });
268 + yield* harness.setWatching(true, { repository: "t3tools/t3code", number: 1 });
269 + expect(yield* Ref.get(harness.commands)).toMatchObject([
270 + { type: "thread.pull-request.watch", number: 1, watching: true },
271 + ]);
272 + }),
273 + );
274 +
275 + it.effect("refuses a watch from a subagent thread, whose parent owns the pull request", () =>
276 + Effect.gen(function* () {
277 + const harness = yield* makeHarness({
278 + thread: {
279 + ...makeThread([makeLink(1, { headBranch: "feature" })]),
280 + lineage: {
281 + rootThreadId: ThreadId.make("parent"),
282 + parentThreadId: ThreadId.make("parent"),
283 + relationshipToParent: "subagent",
284 + },
285 + },
286 + });
287 + const error = yield* harness
288 + .setWatching(true, { repository: "t3tools/t3code", number: 1 })
289 + .pipe(Effect.flip);
290 + expect(error).toMatchObject({ _tag: "PullRequestWatchFromSubagentError" });
291 + expect(yield* Ref.get(harness.commands)).toEqual([]);
292 + }),
293 + );
294 +});
apps/server/src/pullRequest/PullRequestWatchService.ts new
+180
@@ -0,0 +1,180 @@
1 +import {
2 + CommandId,
3 + ThreadId,
4 + type OrchestrationV2ThreadShell,
5 + type PullRequestUnavailableError,
6 +} from "@t3tools/contracts";
7 +import * as Cause from "effect/Cause";
8 +import * as Context from "effect/Context";
9 +import * as SecureRandom from "effect/crypto/SecureRandom";
10 +import * as Effect from "effect/Effect";
11 +import * as Layer from "effect/Layer";
12 +import * as Option from "effect/Option";
13 +import * as Schema from "effect/Schema";
14 +
15 +import * as Orchestrator from "../orchestration-v2/Orchestrator.ts";
16 +import * as ProjectService from "../project/ProjectService.ts";
17 +import * as PullRequestService from "./PullRequestService.ts";
18 +import {
19 + resolveTarget,
20 + type PullRequestTarget,
21 + type PullRequestTargetError,
22 + type ResolvedTarget,
23 +} from "./pullRequestTarget.ts";
24 +import {
25 + threadPullRequestKeysEqual,
26 + threadPullRequestsOf,
27 +} from "../sourceControl/threadPullRequests.ts";
28 +
29 +export 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 +
38 +export 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 +
47 +export 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 +
56 +export 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 +
65 +export 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 +
84 +const 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 +
180 +export const layer = Layer.effect(PullRequestWatchService, make);
apps/server/src/pullRequest/pullRequestTarget.ts new
+123
@@ -0,0 +1,123 @@
1 +import type { OrchestrationProjectShell, SourceControlProviderKind } from "@t3tools/contracts";
2 +import { canonicalizeGitCafePullRequestUrl } from "@t3tools/source-control-definitions/registry";
3 +import * as Effect from "effect/Effect";
4 +import * as Schema from "effect/Schema";
5 +
6 +import { sourceControlDefinitions } from "../sourceControl/sourceControlDefinitions.ts";
7 +import { normalizeThreadPullRequestKey } from "../sourceControl/threadPullRequests.ts";
8 +
9 +export interface PullRequestTarget {
10 + readonly url?: string | undefined;
11 + readonly repository?: string | undefined;
12 + readonly number?: number | undefined;
13 + readonly host?: string | undefined;
14 +}
15 +
16 +export class PullRequestUrlInvalidError extends Schema.TaggedError<PullRequestUrlInvalidError>()(
17 + "PullRequestUrlInvalidError",
18 + {},
19 +) {
20 + override get message(): string {
21 + return "This is not a recognised pull request URL. Pass repository and number instead.";
22 + }
23 +}
24 +
25 +export class PullRequestTargetIncompleteError extends Schema.TaggedError<PullRequestTargetIncompleteError>()(
26 + "PullRequestTargetIncompleteError",
27 + {},
28 +) {
29 + override get message(): string {
30 + return "Pass either url, or both repository and number.";
31 + }
32 +}
33 +
34 +export class PullRequestHostRequiredError extends Schema.TaggedError<PullRequestHostRequiredError>()(
35 + "PullRequestHostRequiredError",
36 + {},
37 +) {
38 + override get message(): string {
39 + return "This thread's project has no recognised remote. Pass host or url.";
40 + }
41 +}
42 +
43 +export class PullRequestUrlUnavailableError extends Schema.TaggedError<PullRequestUrlUnavailableError>()(
44 + "PullRequestUrlUnavailableError",
45 + {},
46 +) {
47 + override get message(): string {
48 + return "This thread's project is on a host with no known pull request URL shape. Pass url.";
49 + }
50 +}
51 +
52 +export type PullRequestTargetError =
53 + | PullRequestUrlInvalidError
54 + | PullRequestTargetIncompleteError
55 + | PullRequestHostRequiredError
56 + | PullRequestUrlUnavailableError;
57 +
58 +export interface ResolvedTarget {
59 + readonly host: string;
60 + readonly repository: string;
61 + readonly number: number;
62 + readonly url: string;
63 +}
64 +
65 +function projectHostAndProvider(project: OrchestrationProjectShell | undefined): {
66 + readonly host: string | null;
67 + readonly kind: SourceControlProviderKind | null;
68 +} {
69 + const identity = project?.repositoryIdentity;
70 + const kind = identity?.provider ?? null;
71 + if (!identity || kind === null) return { host: null, kind: null };
72 + return {
73 + host: sourceControlDefinitions.changeRequestHost(identity, kind),
74 + kind,
75 + };
76 +}
77 +
78 +export const resolveTarget = Effect.fn("PullRequestsToolkit.resolveTarget")(function* (
79 + input: PullRequestTarget,
80 + project: OrchestrationProjectShell | undefined,
81 +) {
82 + if (input.url !== undefined) {
83 + const parsed = sourceControlDefinitions.parseChangeRequestUrl(input.url)?.link;
84 + if (parsed === undefined) {
85 + return yield* new PullRequestUrlInvalidError({});
86 + }
87 + return {
88 + ...normalizeThreadPullRequestKey(parsed),
89 + url: canonicalizeGitCafePullRequestUrl(input.url),
90 + } satisfies ResolvedTarget;
91 + }
92 + if (input.repository === undefined || input.number === undefined) {
93 + return yield* new PullRequestTargetIncompleteError({});
94 + }
95 + const projectHost = projectHostAndProvider(project);
96 + const host = (input.host ?? projectHost.host)?.toLowerCase();
97 + if (host === undefined) {
98 + return yield* new PullRequestHostRequiredError({});
99 + }
100 + const repository = input.repository.toLowerCase();
101 + // Without a URL, a public forge host says what shape its change request URLs take;
102 + // any other host is taken to run the project's own forge.
103 + const recognizedKind = sourceControlDefinitions.recognizeRemote(`https://${host}`)?.kind;
104 + const kind =
105 + sourceControlDefinitions.findByPublicHost(host)?.kind ??
106 + (recognizedKind === "gitcafe" ? recognizedKind : projectHost.kind);
107 + const url =
108 + kind === null
109 + ? null
110 + : sourceControlDefinitions.get(kind).changeRequestUrl({
111 + host,
112 + repository,
113 + number: input.number,
114 + remoteUrl: project?.repositoryIdentity?.locator.remoteUrl,
115 + });
116 + if (url === null) {
117 + return yield* new PullRequestUrlUnavailableError({});
118 + }
119 + return {
120 + ...normalizeThreadPullRequestKey({ host, repository, number: input.number, url }),
121 + url: canonicalizeGitCafePullRequestUrl(url),
122 + } satisfies ResolvedTarget;
123 +});