Open History to see the last commit
1import {
2 CommandId,
3 type OrchestrationProjectShell,
4 type OrchestrationV2DomainEvent,
5 type OrchestrationV2ThreadShell,
6 type PullRequestSummary,
7 type ThreadId,
8 type ThreadLinkedPullRequest,
9} from "@t3tools/contracts";
10import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker";
11import * as Cause from "effect/Cause";
12import * as Context from "effect/Context";
13import * as SecureRandom from "effect/crypto/SecureRandom";
14import * as DateTime from "effect/DateTime";
15import * as Effect from "effect/Effect";
16import * as FileSystem from "effect/FileSystem";
17import * as Option from "effect/Option";
18import * as Path from "effect/Path";
19import * as Queue from "effect/Queue";
20import * as Schedule from "effect/Schedule";
21import type * as Scope from "effect/Scope";
22import * as Stream from "effect/Stream";
23
24import * as BackgroundPolicy from "../background/BackgroundPolicy.ts";
25import * as GitManager from "../git/GitManager.ts";
26import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
27import * as ProjectStore from "./ProjectStore.ts";
28import * as PullRequestService from "../pullRequest/PullRequestService.ts";
29import { makeLinkedThreadsChangeDetector } from "../pullRequest/linkedThreads.ts";
30import * as RepositoryIdentityResolver from "../project/RepositoryIdentityResolver.ts";
31import { forkParked } from "../serverActivation.ts";
32import { sourceControlDefinitions } from "../sourceControl/sourceControlDefinitions.ts";
33import { makeNoPullRequestRechecks } from "./noPullRequestRechecks.ts";
34import {
35 threadPullRequestKeysEqual,
36 threadPullRequestsOf,
37} from "../sourceControl/threadPullRequests.ts";
38import * as Orchestrator from "./Orchestrator.ts";
39
40class ThreadPullRequestServiceV2 extends Context.Service<
41 ThreadPullRequestServiceV2,
42 {
43 readonly start: () => Effect.Effect<void, never, Scope.Scope>;
44 readonly drain: Effect.Effect<void>;
45 }
46>()("t3/orchestration-v2/ThreadPullRequestService/ThreadPullRequestServiceV2") {}
47
48function samePullRequest(
49 left: ThreadLinkedPullRequest | null | undefined,
50 right: ThreadLinkedPullRequest | null,
51): boolean {
52 if (left == null || right === null) return left == null && right === null;
53 return (
54 left.projectId === right.projectId &&
55 left.repository.toLowerCase() === right.repository.toLowerCase() &&
56 left.number === right.number &&
57 left.url === right.url
58 );
59}
60
61function pullRequestPredatesThread(
62 pullRequest: Pick<PullRequestSummary, "state" | "closedAt" | "mergedAt">,
63 createdAt: DateTime.Utc,
64): boolean {
65 const terminalAt =
66 pullRequest.state === "merged"
67 ? pullRequest.mergedAt
68 : pullRequest.state === "closed"
69 ? pullRequest.closedAt
70 : null;
71 return terminalAt != null && Date.parse(terminalAt) < DateTime.toEpochMillis(createdAt);
72}
73
74function pullRequestMatchesProject(
75 pullRequest: GitManager.GitBranchPullRequest,
76 project: OrchestrationProjectShell,
77): boolean {
78 return (
79 pullRequest.repositoryKey !== null &&
80 project.repositoryIdentity != null &&
81 sourceControlDefinitions.canonicalRepositoryKey(pullRequest.repositoryKey) ===
82 sourceControlDefinitions.canonicalRepositoryKey(project.repositoryIdentity.canonicalKey)
83 );
84}
85
86const resolveProjectForPullRequestDiscovery = Effect.fn(
87 "ThreadPullRequestServiceV2.resolveProject",
88)(function* (
89 project: OrchestrationProjectShell,
90 repositoryIdentities: RepositoryIdentityResolver.RepositoryIdentityResolver["Service"],
91 options?: { readonly refresh?: boolean },
92) {
93 // Post-turn discovery refreshes 15-minute identity caches because agents may add remotes.
94 const repositoryIdentity = yield* repositoryIdentities.resolve(project.workspaceRoot, {
95 refresh: options?.refresh ?? false,
96 });
97 return {
98 project: { ...project, repositoryIdentity },
99 repository: sourceControlDefinitions.repositorySelector(repositoryIdentity),
100 };
101});
102
103export function projectWorkspaceMatchesSnapshot(
104 currentProject: Option.Option<Pick<OrchestrationProjectShell, "workspaceRoot">>,
105 expectedWorkspaceRoot: string,
106): boolean {
107 return (
108 Option.isSome(currentProject) && currentProject.value.workspaceRoot === expectedWorkspaceRoot
109 );
110}
111
112const BACKFILL_ATTEMPTS = 5;
113const REPOSITORY_LOOKUP_CONCURRENCY = 4;
114
115interface RefreshRequest {
116 readonly threadId: ThreadId | null;
117 readonly refresh: boolean;
118 readonly backfill?: boolean;
119}
120
121export const make = Effect.gen(function* () {
122 const orchestrator = yield* Orchestrator.OrchestratorV2;
123 const projectStore = yield* ProjectStore.ProjectStoreV2;
124 const git = yield* GitManager.GitManager;
125 const pullRequests = yield* PullRequestService.PullRequestService;
126 const repositoryIdentities = yield* RepositoryIdentityResolver.RepositoryIdentityResolver;
127 const random = yield* SecureRandom.SecureRandom;
128 const fileSystem = yield* FileSystem.FileSystem;
129 const path = yield* Path.Path;
130 const backgroundPolicy = yield* BackgroundPolicy.BackgroundPolicy;
131 const pendingBackfill = new Map<ThreadId, number>();
132 const noPullRequestRechecks = makeNoPullRequestRechecks();
133
134 const finishBackfill = (threads: ReadonlyArray<Pick<OrchestrationV2ThreadShell, "id">>) => {
135 for (const thread of threads) pendingBackfill.delete(thread.id);
136 };
137 const failBackfill = (threads: ReadonlyArray<Pick<OrchestrationV2ThreadShell, "id">>) => {
138 for (const thread of threads) {
139 const remaining = pendingBackfill.get(thread.id);
140 if (remaining === undefined) continue;
141 if (remaining <= 1) pendingBackfill.delete(thread.id);
142 else pendingBackfill.set(thread.id, remaining - 1);
143 }
144 };
145
146 const readThreadSnapshot = ({ threadId, backfill }: RefreshRequest) =>
147 orchestrator.getPullRequestSnapshot(
148 threadId === null ? { unsettledOnly: !(backfill || pendingBackfill.size > 0) } : { threadId },
149 );
150
151 // The tracked repositories a thread changed each have their own branch, so an open pull
152 // request there is linked like one the thread opened. Only a thread's own events ask: the
153 // sweep would query the host for every repository of every thread each minute.
154 const linkRepositoryPullRequests = Effect.fn(
155 "ThreadPullRequestServiceV2.linkRepositoryPullRequests",
156 )(function* (
157 thread: Pick<
158 OrchestrationV2ThreadShell,
159 "id" | "worktreePath" | "branch" | "archivedAt" | "pullRequests" | "linkedPullRequest"
160 >,
161 project: OrchestrationProjectShell,
162 refresh: boolean,
163 ) {
164 const tracked = project.trackedFolders ?? [];
165 if (tracked.length === 0 || thread.archivedAt !== null) return;
166 const { checkpointScopes } = yield* orchestrator.getCheckpointContext(thread.id);
167 const cwds = new Set(
168 checkpointScopes.flatMap((scope) =>
169 typeof scope.repositoryPath === "string" &&
170 tracked.some((folder) => folder.path === scope.repositoryPath)
171 ? [scope.cwd]
172 : [],
173 ),
174 );
175 yield* Effect.forEach(
176 cwds,
177 (cwd) =>
178 Effect.gen(function* () {
179 const local = yield* git.localStatus({ cwd });
180 if (!local.isRepo || local.refName === null || local.isDefaultRef) return;
181 // A worktree thread's repositories are on its branch. A scope recorded before the
182 // thread moved still names the shared checkout, whose branch is someone else's.
183 if (thread.worktreePath !== null && local.refName !== thread.branch) return;
184 const detected = yield* git.branchPullRequest(
185 { cwd, branch: local.refName },
186 { refresh, confirmTerminal: false },
187 );
188 if (detected === null || detected.state !== "open") return;
189 const key = sourceControlDefinitions.parseChangeRequestUrl(detected.url)?.link;
190 // A link the user removed from a stack stays as a tombstone and is not added back.
191 if (
192 key === undefined ||
193 threadPullRequestsOf(thread).some((link) => threadPullRequestKeysEqual(link, key))
194 ) {
195 return;
196 }
197 const uuid = yield* random.uuidV4();
198 yield* orchestrator.dispatch({
199 type: "thread.pull-request.link",
200 commandId: CommandId.make(`server:thread-repository-pull-request:${thread.id}:${uuid}`),
201 threadId: thread.id,
202 host: key.host,
203 repository: key.repository,
204 number: key.number,
205 url: detected.url,
206 source: "created",
207 });
208 }).pipe(
209 Effect.catchCauseIf(
210 (cause) => !Cause.hasInterruptsOnly(cause),
211 (cause) =>
212 Effect.logWarning("repository pull request lookup failed", {
213 threadId: thread.id,
214 cwd,
215 cause: Cause.pretty(cause),
216 }),
217 ),
218 ),
219 { concurrency: REPOSITORY_LOOKUP_CONCURRENCY, discard: true },
220 );
221 });
222
223 const synchronize = Effect.fn("ThreadPullRequestServiceV2.synchronize")(function* (
224 request: RefreshRequest,
225 ) {
226 const [threadSnapshot, projectShells] = yield* Effect.all([
227 readThreadSnapshot(request),
228 projectStore.listShells(),
229 ]);
230 // Subagent children refresh after their own runs; sweeping them costs a lookup each per minute.
231 const snapshotThreads =
232 request.threadId === null
233 ? threadSnapshot.threads.filter(
234 (thread) => thread.lineage.relationshipToParent !== "subagent",
235 )
236 : threadSnapshot.threads;
237 const projects = new Map(projectShells.map((project) => [project.id, project]));
238 const nowMs = DateTime.toEpochMillis(yield* DateTime.now);
239 if (request.backfill) {
240 for (const thread of snapshotThreads) {
241 if (
242 (thread.settledOverride === "settled" || thread.settledAt !== null) &&
243 thread.branchPullRequest == null
244 ) {
245 pendingBackfill.set(thread.id, BACKFILL_ATTEMPTS);
246 }
247 }
248 }
249 const visibleThreadIds = new Set(
250 snapshotThreads.filter((thread) => thread.branch !== null).map((thread) => thread.id),
251 );
252 const checkedIds = request.threadId === null ? [...pendingBackfill.keys()] : [request.threadId];
253 for (const threadId of checkedIds) {
254 if (!visibleThreadIds.has(threadId)) pendingBackfill.delete(threadId);
255 }
256 const threads = snapshotThreads.filter(
257 (thread) =>
258 thread.archivedAt === null &&
259 ((thread.settledOverride !== "settled" && thread.settledAt === null) ||
260 request.threadId !== null ||
261 pendingBackfill.has(thread.id)) &&
262 (thread.branch !== null || thread.branchPullRequest != null),
263 );
264 const groups = Map.groupBy(threads, (thread) =>
265 JSON.stringify([thread.projectId, thread.worktreePath, thread.branch]),
266 );
267
268 // A thread's own events and a backfill read at once; only scheduled sweeps wait.
269 const scheduled = new Map(
270 request.threadId !== null
271 ? []
272 : [...groups].filter(
273 ([, group]) =>
274 group[0]!.branch !== null &&
275 group.every(
276 (thread) => thread.branchPullRequest == null && !pendingBackfill.has(thread.id),
277 ),
278 ),
279 );
280 const scheduledLookups = noPullRequestRechecks.select(
281 nowMs,
282 Array.from(scheduled, ([key, group]) => ({
283 key,
284 activityAtMs: Math.max(...group.map((thread) => DateTime.toEpochMillis(thread.updatedAt))),
285 })),
286 );
287
288 yield* Effect.forEach(
289 groups,
290 ([key, group]) =>
291 Effect.gen(function* () {
292 const first = group[0]!;
293 const project = projects.get(first.projectId);
294 if (project === undefined) return finishBackfill(group);
295 if (scheduled.has(key) && !scheduledLookups.has(key)) return;
296 const { project: resolvedProject, repository } =
297 yield* resolveProjectForPullRequestDiscovery(project, repositoryIdentities, {
298 refresh: request.refresh,
299 });
300 if (first.branch !== null && repository === null) return finishBackfill(group);
301 // A worktree folder can outlive its .git, and git there fails with not_a_repository.
302 // An unreadable .git keeps the worktree rather than failing the whole group.
303 const cwd =
304 first.worktreePath !== null &&
305 (yield* fileSystem
306 .exists(path.join(first.worktreePath, ".git"))
307 .pipe(Effect.orElseSucceed(() => true)))
308 ? first.worktreePath
309 : project.workspaceRoot;
310 // A detected PR is confirmed against fresh git state before it is saved.
311 const detected =
312 first.branch === null
313 ? null
314 : yield* git.branchPullRequest(
315 { cwd, branch: first.branch },
316 { refresh: request.refresh, confirmTerminal: false },
317 );
318 if (first.branch !== null) noPullRequestRechecks.record(key, nowMs, detected !== null);
319 if (detected !== null && !pullRequestMatchesProject(detected, resolvedProject)) {
320 return finishBackfill(group);
321 }
322 const detectedReference =
323 detected !== null && repository !== null
324 ? {
325 projectId: project.id,
326 repository,
327 number: detected.number,
328 url: detected.url,
329 }
330 : null;
331
332 // Only a new association is refused: a thread keeps a PR it already saved, and a PR the
333 // user checked out stays with the threads made for it, however long ago it closed.
334 const isHistoricalFor = (thread: (typeof group)[number]) =>
335 detected !== null &&
336 pullRequestPredatesThread(detected, thread.createdAt) &&
337 !samePullRequest(thread.branchPullRequest, detectedReference);
338 const dropsHistorical =
339 detected !== null &&
340 first.branch !== null &&
341 group.some(isHistoricalFor) &&
342 !(yield* git.checkedOutPullRequest({ cwd, branch: first.branch, url: detected.url }));
343
344 const plans = yield* Effect.forEach(group, (thread) =>
345 Effect.gen(function* () {
346 let branchPullRequest =
347 dropsHistorical && isHistoricalFor(thread) ? null : detectedReference;
348 if (
349 branchPullRequest === null &&
350 thread.branch !== null &&
351 thread.worktreePath === null &&
352 thread.branchPullRequest != null
353 ) {
354 const previous = yield* pullRequests.summary(thread.branchPullRequest, {
355 recoverTransientFailure: false,
356 });
357 if (
358 previous.headBranch === thread.branch &&
359 (previous.state === "merged" || previous.state === "closed")
360 ) {
361 branchPullRequest = thread.branchPullRequest;
362 }
363 }
364
365 let replacement: ThreadLinkedPullRequest | undefined;
366 if (
367 (thread.pullRequests ?? []).length === 0 &&
368 thread.linkedPullRequest != null &&
369 detected?.state === "open" &&
370 detectedReference !== null &&
371 !samePullRequest(thread.linkedPullRequest, detectedReference)
372 ) {
373 const linked = yield* pullRequests.summary(thread.linkedPullRequest, {
374 recoverTransientFailure: false,
375 });
376 if (linked.state === "merged" || linked.state === "closed") {
377 replacement = detectedReference;
378 }
379 }
380 if (
381 samePullRequest(thread.branchPullRequest, branchPullRequest) &&
382 replacement === undefined
383 ) {
384 pendingBackfill.delete(thread.id);
385 return null;
386 }
387 return { thread, branchPullRequest, replacement };
388 }).pipe(
389 Effect.catchCauseIf(
390 (cause) => !Cause.hasInterruptsOnly(cause),
391 (cause) =>
392 Effect.logWarning("thread pull request discovery failed", {
393 threadId: thread.id,
394 cause: Cause.pretty(cause),
395 }).pipe(
396 Effect.tap(() => Effect.sync(() => failBackfill([thread]))),
397 Effect.as(null),
398 ),
399 ),
400 ),
401 );
402 const updates = plans.filter((plan) => plan !== null);
403 if (updates.length === 0) return;
404
405 if (detected !== null && first.branch !== null) {
406 const current = yield* git.branchPullRequest(
407 { cwd, branch: first.branch },
408 { freshGitState: true },
409 );
410 const currentIdentity = yield* repositoryIdentities.resolve(project.workspaceRoot, {
411 refresh: true,
412 });
413 if (
414 current === null ||
415 current.number !== detected.number ||
416 current.url !== detected.url ||
417 current.state !== detected.state ||
418 current.repositoryKey !== detected.repositoryKey ||
419 !pullRequestMatchesProject(current, {
420 ...project,
421 repositoryIdentity: currentIdentity,
422 })
423 ) {
424 return failBackfill(updates.map((update) => update.thread));
425 }
426 }
427
428 yield* Effect.forEach(
429 updates,
430 ({ thread, branchPullRequest, replacement }) =>
431 Effect.gen(function* () {
432 // Discovery yields to network I/O; recheck the project at commit to reject deleted projects or changed checkouts.
433 const currentProject = yield* projectStore.getShell(project.id);
434 if (!projectWorkspaceMatchesSnapshot(currentProject, project.workspaceRoot)) {
435 return failBackfill([thread]);
436 }
437 const uuid = yield* random.uuidV4();
438 yield* orchestrator.dispatch({
439 type: "thread.pull-request.sync",
440 commandId: CommandId.make(`server:thread-pull-request:${thread.id}:${uuid}`),
441 threadId: thread.id,
442 projectId: project.id,
443 snapshotSequence: threadSnapshot.snapshotSequence,
444 expected: {
445 workspaceRoot: project.workspaceRoot,
446 branch: thread.branch,
447 worktreePath: thread.worktreePath,
448 linkedPullRequest: thread.linkedPullRequest ?? null,
449 branchPullRequest: thread.branchPullRequest ?? null,
450 },
451 branchPullRequest,
452 ...(replacement === undefined ? {} : { linkedPullRequest: replacement }),
453 });
454 pendingBackfill.delete(thread.id);
455 }).pipe(
456 Effect.catchCauseIf(
457 (cause) => !Cause.hasInterruptsOnly(cause),
458 (cause) =>
459 Effect.logWarning("thread pull request update failed", {
460 threadId: thread.id,
461 cause: Cause.pretty(cause),
462 }).pipe(Effect.tap(() => Effect.sync(() => failBackfill([thread])))),
463 ),
464 ),
465 { discard: true },
466 );
467 }).pipe(
468 Effect.catchCauseIf(
469 (cause) => !Cause.hasInterruptsOnly(cause),
470 (cause) =>
471 Effect.logWarning("thread branch pull request lookup failed", {
472 threadIds: group.map((thread) => thread.id),
473 cause: Cause.pretty(cause),
474 }).pipe(Effect.tap(() => Effect.sync(() => failBackfill(group)))),
475 ),
476 ),
477 // Batch concurrent branch lookups into one GitHub GraphQL document.
478 { concurrency: 32, discard: true },
479 );
480
481 const requested =
482 request.threadId === null
483 ? undefined
484 : snapshotThreads.find((thread) => thread.id === request.threadId);
485 const requestedProject =
486 requested === undefined ? undefined : projects.get(requested.projectId);
487 if (requested !== undefined && requestedProject !== undefined) {
488 yield* linkRepositoryPullRequests(requested, requestedProject, request.refresh).pipe(
489 Effect.catchCauseIf(
490 (cause) => !Cause.hasInterruptsOnly(cause),
491 (cause) =>
492 Effect.logWarning("repository pull request discovery failed", {
493 threadId: requested.id,
494 cause: Cause.pretty(cause),
495 }),
496 ),
497 );
498 }
499 if (request.threadId === null) noPullRequestRechecks.retain(groups);
500 });
501
502 // At most one queued request per thread, so a turn end's events share one lookup.
503 // A request after that lookup starts queues another, so later host changes are still read.
504 const queuedThreadRequests = new Map<ThreadId, { threadId: ThreadId; refresh: boolean }>();
505
506 const worker = yield* makeDrainableWorker((request: RefreshRequest) =>
507 Effect.suspend(() => {
508 if (request.threadId !== null) queuedThreadRequests.delete(request.threadId);
509 return synchronize(request);
510 }).pipe(
511 Effect.provideService(GitVcsDriver.BackgroundGitWork, true),
512 Effect.catchCauseIf(
513 (cause) => !Cause.hasInterruptsOnly(cause),
514 (cause) =>
515 Effect.logWarning("thread pull request refresh failed", {
516 cause: Cause.pretty(cause),
517 }),
518 ),
519 ),
520 );
521
522 const enqueueThread = (threadId: ThreadId, refresh: boolean) =>
523 Effect.suspend(() => {
524 const queued = queuedThreadRequests.get(threadId);
525 if (queued !== undefined) {
526 queued.refresh ||= refresh;
527 return Effect.void;
528 }
529 const request = { threadId, refresh };
530 queuedThreadRequests.set(threadId, request);
531 return worker.enqueue(request);
532 });
533
534 const linkedThreadsChange = makeLinkedThreadsChangeDetector();
535 // A running linked thread can reorder its answers on every event, so reorders refresh readers at
536 // most once per 10s, the cadence clients used to poll at.
537 const linkedThreadReorders = yield* Queue.dropping<void>(1);
538
539 const notifyLinkedThreads = (event: OrchestrationV2DomainEvent) => {
540 switch (linkedThreadsChange(event)) {
541 case "changed":
542 return pullRequests.notifyLinkedThreadsChanged;
543 case "reordered":
544 return Queue.offer(linkedThreadReorders, undefined).pipe(Effect.asVoid);
545 case null:
546 return Effect.void;
547 }
548 };
549
550 const processEvent = (event: OrchestrationV2DomainEvent) =>
551 Effect.andThen(notifyLinkedThreads(event), refreshForEvent(event));
552
553 const refreshForEvent = (event: OrchestrationV2DomainEvent) => {
554 switch (event.type) {
555 case "thread.created":
556 case "thread.unarchived":
557 case "thread.metadata-updated":
558 return enqueueThread(event.threadId, false);
559 case "thread.unsettled":
560 case "checkpoint.captured":
561 return enqueueThread(event.threadId, true);
562 case "run.updated":
563 if (
564 event.payload.status === "completed" ||
565 event.payload.status === "failed" ||
566 event.payload.status === "cancelled" ||
567 event.payload.status === "interrupted"
568 ) {
569 return enqueueThread(event.threadId, true);
570 }
571 break;
572 }
573 return Effect.void;
574 };
575
576 const start: ThreadPullRequestServiceV2["Service"]["start"] = Effect.fn(
577 "ThreadPullRequestServiceV2.start",
578 )(function* () {
579 yield* forkParked(Stream.runForEach(orchestrator.streamDomainEvents, processEvent));
580 yield* forkParked(
581 Queue.take(linkedThreadReorders).pipe(
582 Effect.andThen(pullRequests.notifyLinkedThreadsChanged),
583 Effect.andThen(Effect.sleep("10 seconds")),
584 Effect.forever,
585 ),
586 );
587 yield* forkParked(
588 Effect.gen(function* () {
589 yield* worker.enqueue({ threadId: null, refresh: false, backfill: true });
590 yield* worker.drain;
591 yield* Effect.gen(function* () {
592 // The sweep only catches pull requests opened outside a turn, which
593 // nobody sees without a client. Thread events still refresh headless work.
594 if (!(yield* backgroundPolicy.shouldRunOpportunisticWork)) return;
595 yield* worker.enqueue({ threadId: null, refresh: false });
596 yield* worker.drain;
597 }).pipe(Effect.repeat(Schedule.spaced("1 minute")), Effect.delay("1 minute"));
598 }).pipe(Effect.asVoid),
599 );
600 });
601
602 return { start, drain: worker.drain } satisfies ThreadPullRequestServiceV2["Service"];
603});