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

ThreadPullRequestService.ts

626 lines25.2 KB

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