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

ThreadPullRequestReactor.test.ts

643 lines23.0 KB

1import {
2 CheckpointRef,
3 EventId,
4 GitManagerError,
5 ProjectId,
6 ProviderInstanceId,
7 ThreadId,
8 TurnId,
9 type OrchestrationCommand,
10 type OrchestrationEvent,
11 type OrchestrationProjectShell,
12 type OrchestrationShellSnapshot,
13 type OrchestrationThreadShell,
14 type PullRequestRef,
15 type PullRequestSummary,
16 type ThreadLinkedPullRequest,
17} from "@t3tools/contracts";
18import { describe, expect, it } from "@effect/vitest";
19import * as Crypto from "effect/Crypto";
20import * as Deferred from "effect/Deferred";
21import * as Effect from "effect/Effect";
22import * as FileSystem from "effect/FileSystem";
23import * as Layer from "effect/Layer";
24import * as PubSub from "effect/PubSub";
25import * as Queue from "effect/Queue";
26import * as Ref from "effect/Ref";
27import * as Stream from "effect/Stream";
28import { TestClock } from "effect/testing";
29​
30import { GitManager, type GitBranchPullRequest } from "../git/GitManager.ts";
31import { PullRequestService } from "../pullRequest/PullRequestService.ts";
32import { RepositoryIdentityResolver } from "../project/RepositoryIdentityResolver.ts";
33import { ServerActivation } from "../serverActivation.ts";
34import { OrchestrationEngineService } from "./Services/OrchestrationEngine.ts";
35import { ProjectionSnapshotQuery } from "./Services/ProjectionSnapshotQuery.ts";
36import * as ThreadPullRequestReactor from "./ThreadPullRequestReactor.ts";
37​
38const NOW = "2026-09-01T12:00:00.000Z";
39const PROJECT_ID = ProjectId.make("project");
40const REPOSITORY = "owner/repository";
41const REPOSITORY_KEY = `github.com/${REPOSITORY}`;
42type SyncCommand = Extract<OrchestrationCommand, { type: "thread.pull-request.sync" }>;
43​
44function reference(number: number): ThreadLinkedPullRequest {
45 return {
46 projectId: PROJECT_ID,
47 repository: REPOSITORY,
48 number,
49 url: `https://github.com/${REPOSITORY}/pull/${number}`,
50 };
52​
53function branchPullRequest(
54 number = 42,
55 state: GitBranchPullRequest["state"] = "open",
56): GitBranchPullRequest {
57 return {
58 ...reference(number),
59 title: "Branch pull request",
60 baseRef: "main",
61 headRef: "feature",
62 state,
63 updatedAt: NOW,
64 repositoryKey: REPOSITORY_KEY,
65 };
67​
68function summary(input: PullRequestRef, state: PullRequestSummary["state"]): PullRequestSummary {
69 return {
70 ...input,
71 provider: "github",
72 title: "Pull request",
73 url: reference(input.number).url,
74 state,
75 headBranch: "feature",
76 baseBranch: "main",
77 updatedAt: NOW,
78 };
80​
81function thread(
82 id: string,
83 overrides: Partial<OrchestrationThreadShell> = {},
84): OrchestrationThreadShell {
85 return {
86 id: ThreadId.make(id),
87 projectId: PROJECT_ID,
88 title: id,
89 modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5" },
90 runtimeMode: "full-access",
91 interactionMode: "default",
92 pullRequests: [],
93 branch: "feature",
94 worktreePath: null,
95 latestTurn: null,
96 createdAt: NOW,
97 updatedAt: NOW,
98 archivedAt: null,
99 settledOverride: null,
100 settledAt: null,
101 session: null,
102 latestUserMessageAt: NOW,
103 hasPendingApprovals: false,
104 hasPendingUserInput: false,
105 hasActionableProposedPlan: false,
106 ...overrides,
107 };
109​
110const project = {
111 id: PROJECT_ID,
112 title: "Project",
113 workspaceRoot: "/workspace/project",
114 repositoryIdentity: {
115 canonicalKey: REPOSITORY_KEY,
116 displayName: REPOSITORY,
117 rootPath: "/workspace/project",
118 locator: {
119 source: "git-remote",
120 remoteName: "origin",
121 remoteUrl: `git@github.com:${REPOSITORY}.git`,
122 },
123 },
124 defaultModelSelection: null,
125 scripts: [],
126 createdAt: NOW,
127 updatedAt: NOW,
128} satisfies OrchestrationProjectShell;
129​
130const makeHarness = Effect.fn("makeThreadPullRequestHarness")(function* (options: {
131 readonly threads: ReadonlyArray<OrchestrationThreadShell>;
132 readonly branchPullRequest?: GitManager["Service"]["branchPullRequest"];
133 readonly summary?: PullRequestService["Service"]["summary"];
134 readonly existingWorktrees?: ReadonlyArray<string>;
135 readonly project?: OrchestrationProjectShell;
136 readonly resolveRepositoryIdentity?: RepositoryIdentityResolver["Service"]["resolve"];
137}) {
138 const activation = yield* Deferred.make<void>();
139 const snapshots = yield* Ref.make<OrchestrationShellSnapshot>({
140 snapshotSequence: 1,
141 projects: [options.project ?? project],
142 threads: options.threads,
143 updatedAt: NOW,
144 });
145 const reads = yield* Queue.unbounded<void>();
146 const events = yield* PubSub.unbounded<OrchestrationEvent>();
147 const commands = yield* Ref.make<ReadonlyArray<SyncCommand>>([]);
148 const branchCalls = yield* Ref.make<
149 ReadonlyArray<{ readonly cwd: string; readonly branch: string; readonly refresh: boolean }>
150 >([]);
151 const summaryCalls = yield* Ref.make<ReadonlyArray<PullRequestRef>>([]);
152 let uuid = 0;
153 const dependencies = Layer.mergeAll(
154 Layer.mock(ProjectionSnapshotQuery)({
155 getShellSnapshot: () =>
156 Ref.get(snapshots).pipe(Effect.tap(() => Queue.offer(reads, undefined))),
157 }),
158 Layer.mock(GitManager)({
159 branchPullRequest: (input, readOptions) =>
160 Ref.update(branchCalls, (calls) => [
161 ...calls,
162 { ...input, refresh: readOptions?.refresh === true },
163 ]).pipe(
164 Effect.andThen(options.branchPullRequest?.(input, readOptions) ?? Effect.succeed(null)),
165 ),
166 }),
167 Layer.mock(PullRequestService)({
168 summary: (input, readOptions) =>
169 Ref.update(summaryCalls, (calls) => [...calls, input]).pipe(
170 Effect.andThen(
171 options.summary?.(input, readOptions) ?? Effect.succeed(summary(input, "open")),
172 ),
173 ),
174 }),
175 Layer.mock(RepositoryIdentityResolver)({
176 resolve:
177 options.resolveRepositoryIdentity ??
178 (() => Effect.succeed(options.project?.repositoryIdentity ?? project.repositoryIdentity)),
179 }),
180 Layer.mock(OrchestrationEngineService)({
181 subscribeDomainEvents: PubSub.subscribe(events).pipe(
182 Effect.map((subscription) => Stream.fromSubscription(subscription)),
183 ),
184 dispatch: (command) => {
185 if (command.type !== "thread.pull-request.sync") {
186 return Effect.die(`Unexpected command: ${command.type}`);
187 }
188 return Ref.update(commands, (current) => [...current, command]).pipe(
189 Effect.andThen(
190 Ref.updateAndGet(snapshots, (snapshot) => ({
191 ...snapshot,
192 snapshotSequence: snapshot.snapshotSequence + 1,
193 threads: snapshot.threads.map((current) =>
194 current.id === command.threadId
195 ? {
196 ...current,
197 branchPullRequest: command.branchPullRequest,
198 ...(command.linkedPullRequest !== undefined
199 ? { linkedPullRequest: command.linkedPullRequest }
200 : {}),
201 }
202 : current,
203 ),
204 })),
205 ),
206 Effect.map((snapshot) => ({ sequence: snapshot.snapshotSequence })),
207 );
208 },
209 }),
210 Layer.succeed(ServerActivation, Deferred.await(activation)),
211 Layer.succeed(
212 Crypto.Crypto,
213 Crypto.make({
214 randomBytes: (size) => new Uint8Array(size).fill(++uuid),
215 digest: (_algorithm, data) => Effect.succeed(data),
216 }),
217 ),
218 FileSystem.layerNoop({
219 exists: (path) => Effect.succeed(options.existingWorktrees?.includes(path) ?? false),
220 }),
221 );
222​
223 const start = Effect.fn("startThreadPullRequestHarness")(function* () {
224 const reactor = yield* ThreadPullRequestReactor.ThreadPullRequestReactor;
225 yield* reactor.start();
226 yield* Deferred.succeed(activation, undefined);
227 yield* Queue.take(reads);
228 yield* reactor.drain;
229 return reactor;
230 });
231​
232 return {
233 start,
234 reads,
235 snapshots,
236 commands,
237 branchCalls,
238 summaryCalls,
239 publish: (event: OrchestrationEvent) => PubSub.publish(events, event),
240 layer: ThreadPullRequestReactor.layer.pipe(Layer.provide(dependencies)),
241 };
242});
243​
244describe("ThreadPullRequestReactor", () => {
245 it.effect("discovers saved branch PRs without a client and shares branch lookups", () =>
246 Effect.scoped(
247 Effect.gen(function* () {
248 const fixture = yield* makeHarness({
249 threads: [
250 thread("first"),
251 thread("second"),
252 thread("archived", { archivedAt: NOW }),
253 thread("no-branch", { branch: null }),
254 ],
255 branchPullRequest: () => Effect.succeed(branchPullRequest()),
256 });
257 yield* Effect.gen(function* () {
258 const reactor = yield* fixture.start();
259 expect(yield* Ref.get(fixture.branchCalls)).toEqual([
260 { cwd: project.workspaceRoot, branch: "feature", refresh: false },
261 { cwd: project.workspaceRoot, branch: "feature", refresh: false },
262 ]);
263 expect((yield* Ref.get(fixture.commands)).map((command) => command.threadId)).toEqual([
264 "first",
265 "second",
266 ]);
267 expect((yield* Ref.get(fixture.snapshots)).threads[0]?.branchPullRequest).toEqual(
268 reference(42),
269 );
270​
271 yield* TestClock.adjust("1 minute");
272 yield* Queue.take(fixture.reads);
273 yield* reactor.drain;
274 expect(yield* Ref.get(fixture.commands)).toHaveLength(2);
275 }).pipe(Effect.provide(fixture.layer));
276 }),
277 ),
278 );
279​
280 it.effect("replaces terminal manual links but preserves open links and explicit unlink", () =>
281 Effect.scoped(
282 Effect.gen(function* () {
283 const fixture = yield* makeHarness({
284 threads: [
285 thread("merged", { linkedPullRequest: reference(1) }),
286 thread("closed", { linkedPullRequest: reference(2) }),
287 thread("open", { linkedPullRequest: reference(3) }),
288 thread("unlinked", { linkedPullRequest: null }),
289 ],
290 branchPullRequest: () => Effect.succeed(branchPullRequest()),
291 summary: (input) =>
292 Effect.succeed(
293 summary(
294 input,
295 input.number === 1 ? "merged" : input.number === 2 ? "closed" : "open",
296 ),
297 ),
298 });
299 yield* Effect.gen(function* () {
300 yield* fixture.start();
301 const snapshot = yield* Ref.get(fixture.snapshots);
302 expect(snapshot.threads.map((current) => current.linkedPullRequest)).toEqual([
303 reference(42),
304 reference(42),
305 reference(3),
306 null,
307 ]);
308 expect(
309 snapshot.threads.every((current) => current.branchPullRequest?.number === 42),
310 ).toBe(true);
311 }).pipe(Effect.provide(fixture.layer));
312 }),
313 ),
314 );
315​
316 it.effect.each(["session-first", "checkpoint-first"] as const)(
317 "refreshes discovery once after a turn ends with %s event ordering",
318 (order) =>
319 Effect.scoped(
320 Effect.gen(function* () {
321 const current = thread("turn-thread");
322 const detected = yield* Ref.make<GitBranchPullRequest | null>(null);
323 const fixture = yield* makeHarness({
324 threads: [current],
325 branchPullRequest: (_input, options) =>
326 options?.refresh
327 ? Ref.set(detected, branchPullRequest()).pipe(Effect.andThen(Ref.get(detected)))
328 : Ref.get(detected),
329 });
330 yield* Effect.gen(function* () {
331 const reactor = yield* fixture.start();
332 expect(yield* Ref.get(fixture.commands)).toHaveLength(0);
333 const sessionEvent: OrchestrationEvent = {
334 type: "thread.session-set",
335 sequence: 2,
336 eventId: EventId.make("turn-finished"),
337 aggregateKind: "thread",
338 aggregateId: current.id,
339 occurredAt: NOW,
340 commandId: null,
341 causationEventId: null,
342 correlationId: null,
343 metadata: {},
344 payload: {
345 threadId: current.id,
346 session: {
347 threadId: current.id,
348 status: "ready",
349 providerName: "Codex",
350 runtimeMode: "full-access",
351 activeTurnId: null,
352 lastError: null,
353 updatedAt: NOW,
354 },
355 },
356 };
357 const checkpointEvent: OrchestrationEvent = {
358 ...sessionEvent,
359 type: "thread.turn-diff-completed",
360 sequence: 3,
361 eventId: EventId.make("checkpoint-finished"),
362 payload: {
363 threadId: current.id,
364 turnId: TurnId.make("turn"),
365 checkpointTurnCount: 1,
366 checkpointRef: CheckpointRef.make("checkpoint"),
367 status: "ready",
368 files: [],
369 assistantMessageId: null,
370 completedAt: NOW,
371 },
372 };
373 const events =
374 order === "session-first"
375 ? [sessionEvent, checkpointEvent]
376 : [checkpointEvent, sessionEvent];
377 for (const event of events) {
378 yield* fixture.publish(event);
379 yield* Queue.take(fixture.reads);
380 yield* reactor.drain;
381 }
382 expect((yield* Ref.get(fixture.commands))[0]?.branchPullRequest).toEqual(reference(42));
383 expect(
384 (yield* Ref.get(fixture.branchCalls)).filter((call) => call.refresh),
385 ).toHaveLength(1);
386 }).pipe(Effect.provide(fixture.layer));
387 }),
388 ),
389 );
390​
391 it.effect("uses live worktrees and falls back to the project for removed worktrees", () =>
392 Effect.scoped(
393 Effect.gen(function* () {
394 const fixture = yield* makeHarness({
395 threads: [
396 thread("live", { worktreePath: "/workspace/worktree" }),
397 thread("removed", { worktreePath: "/workspace/removed" }),
398 ],
399 existingWorktrees: ["/workspace/worktree"],
400 branchPullRequest: () => Effect.succeed(branchPullRequest()),
401 });
402 yield* Effect.gen(function* () {
403 yield* fixture.start();
404 expect(new Set((yield* Ref.get(fixture.branchCalls)).map((call) => call.cwd))).toEqual(
405 new Set(["/workspace/project", "/workspace/worktree"]),
406 );
407 }).pipe(Effect.provide(fixture.layer));
408 }),
409 ),
410 );
411​
412 it.effect("retains only terminal PRs on shared checkouts and clears a removed branch", () =>
413 Effect.scoped(
414 Effect.gen(function* () {
415 const fixture = yield* makeHarness({
416 threads: [
417 thread("terminal", { branch: "main", branchPullRequest: reference(1) }),
418 thread("open", { branchPullRequest: reference(2) }),
419 thread("worktree", {
420 worktreePath: "/workspace/worktree",
421 branchPullRequest: reference(1),
422 }),
423 thread("cleared", {
424 branch: null,
425 branchPullRequest: reference(1),
426 linkedPullRequest: reference(3),
427 }),
428 ],
429 summary: (input) =>
430 Effect.succeed(summary(input, input.number === 1 ? "merged" : "open")),
431 });
432 yield* Effect.gen(function* () {
433 yield* fixture.start();
434 const snapshot = yield* Ref.get(fixture.snapshots);
435 expect(snapshot.threads.map((current) => current.branchPullRequest)).toEqual([
436 reference(1),
437 null,
438 null,
439 null,
440 ]);
441 expect(snapshot.threads[3]?.linkedPullRequest).toEqual(reference(3));
442 }).pipe(Effect.provide(fixture.layer));
443 }),
444 ),
445 );
446​
447 it.effect("keeps saved links on lookup failures and rejects a different repository", () =>
448 Effect.scoped(
449 Effect.gen(function* () {
450 const fixture = yield* makeHarness({
451 threads: [
452 thread("failed", { branch: "failed", branchPullRequest: reference(1) }),
453 thread("wrong-repository", {
454 branch: "wrong-repository",
455 branchPullRequest: reference(2),
456 }),
457 thread("healthy"),
458 ],
459 branchPullRequest: ({ cwd, branch }) =>
460 branch === "failed"
461 ? Effect.fail(
462 new GitManagerError({
463 operation: "branchPullRequest",
464 cwd,
465 detail: "Lookup failed",
466 }),
467 )
468 : Effect.succeed({
469 ...branchPullRequest(),
470 repositoryKey:
471 branch === "wrong-repository" ? "github.com/other/repository" : REPOSITORY_KEY,
472 }),
473 });
474 yield* Effect.gen(function* () {
475 yield* fixture.start();
476 expect(
477 (yield* Ref.get(fixture.snapshots)).threads.map((current) => current.branchPullRequest),
478 ).toEqual([reference(1), reference(2), reference(42)]);
479 expect(yield* Ref.get(fixture.commands)).toHaveLength(1);
480 }).pipe(Effect.provide(fixture.layer));
481 }),
482 ),
483 );
484​
485 it.effect.each(["settled", null] as const)(
486 "retries settled backfills and stops after success with settledOverride %s",
487 (settledOverride) =>
488 Effect.scoped(
489 Effect.gen(function* () {
490 const online = yield* Ref.make(false);
491 const fixture = yield* makeHarness({
492 threads: [
493 thread("backfill", { settledOverride, settledAt: NOW }),
494 thread("known", {
495 branch: "known",
496 settledOverride,
497 settledAt: NOW,
498 branchPullRequest: reference(1),
499 }),
500 ],
501 branchPullRequest: ({ cwd }) =>
502 Ref.get(online).pipe(
503 Effect.flatMap((connected) =>
504 connected
505 ? Effect.succeed(branchPullRequest(42, "merged"))
506 : Effect.fail(
507 new GitManagerError({
508 operation: "branchPullRequest",
509 cwd,
510 detail: "Offline",
511 }),
512 ),
513 ),
514 ),
515 });
516 yield* Effect.gen(function* () {
517 const reactor = yield* fixture.start();
518 expect(yield* Ref.get(fixture.commands)).toHaveLength(0);
519 yield* Ref.set(online, true);
520 yield* TestClock.adjust("1 minute");
521 yield* Queue.take(fixture.reads);
522 yield* reactor.drain;
523 expect((yield* Ref.get(fixture.commands))[0]?.threadId).toBe("backfill");
524 yield* TestClock.adjust("1 minute");
525 yield* Queue.take(fixture.reads);
526 yield* reactor.drain;
527 expect((yield* Ref.get(fixture.branchCalls)).map((call) => call.branch)).toEqual([
528 "feature",
529 "feature",
530 "feature",
531 ]);
532 }).pipe(Effect.provide(fixture.layer));
533 }),
534 ),
535 );
536​
537 it.effect("stops retrying a settled backfill after repeated lookup failures", () =>
538 Effect.scoped(
539 Effect.gen(function* () {
540 const fixture = yield* makeHarness({
541 threads: [thread("backfill", { settledOverride: "settled", settledAt: NOW })],
542 branchPullRequest: ({ cwd }) =>
543 Effect.fail(
544 new GitManagerError({ operation: "branchPullRequest", cwd, detail: "No gh" }),
545 ),
546 });
547 yield* Effect.gen(function* () {
548 const reactor = yield* fixture.start();
549 for (
550 let attempt = 1;
551 attempt < ThreadPullRequestReactor.BACKFILL_ATTEMPTS + 2;
552 attempt++
553 ) {
554 yield* TestClock.adjust("1 minute");
555 yield* Queue.take(fixture.reads);
556 yield* reactor.drain;
557 }
558 expect(yield* Ref.get(fixture.branchCalls)).toHaveLength(
559 ThreadPullRequestReactor.BACKFILL_ATTEMPTS,
560 );
561 expect(yield* Ref.get(fixture.commands)).toHaveLength(0);
562 }).pipe(Effect.provide(fixture.layer));
563 }),
564 ),
565 );
566​
567 it.effect("matches Azure SSH projects to HTTPS PRs with the provider repository selector", () =>
568 Effect.scoped(
569 Effect.gen(function* () {
570 const fixture = yield* makeHarness({
571 threads: [thread("azure")],
572 project: {
573 ...project,
574 repositoryIdentity: {
575 canonicalKey: "ssh.dev.azure.com/v3/org/project/repository",
576 displayName: "v3/org/project/repository",
577 name: "repository",
578 provider: "azure-devops",
579 rootPath: project.workspaceRoot,
580 locator: {
581 source: "git-remote",
582 remoteName: "origin",
583 remoteUrl: "git@ssh.dev.azure.com:v3/org/project/repository",
584 },
585 },
586 },
587 branchPullRequest: () =>
588 Effect.succeed({
589 ...branchPullRequest(),
590 repositoryKey: "dev.azure.com/org/project/_git/repository",
591 url: "https://dev.azure.com/org/project/_git/repository/pullrequest/42",
592 }),
593 });
594 yield* Effect.gen(function* () {
595 yield* fixture.start();
596 expect((yield* Ref.get(fixture.commands))[0]?.branchPullRequest).toEqual({
597 projectId: PROJECT_ID,
598 repository: "repository",
599 number: 42,
600 url: "https://dev.azure.com/org/project/_git/repository/pullrequest/42",
601 });
602 }).pipe(Effect.provide(fixture.layer));
603 }),
604 ),
605 );
606​
607 it.effect.each(["primary", "branch"] as const)(
608 "rejects the group's links if the %s remote changes during a summary read",
609 (changedRemote) =>
610 Effect.scoped(
611 Effect.gen(function* () {
612 const identity = yield* Ref.make(project.repositoryIdentity);
613 const detected = yield* Ref.make(branchPullRequest());
614 const fixture = yield* makeHarness({
615 threads: [thread("manual", { linkedPullRequest: reference(1) }), thread("automatic")],
616 branchPullRequest: () => Ref.get(detected),
617 resolveRepositoryIdentity: (_cwd, options) =>
618 options?.refresh ? Ref.get(identity) : Effect.succeed(project.repositoryIdentity),
619 summary: (input) =>
620 (changedRemote === "primary"
621 ? Ref.set(identity, {
622 ...project.repositoryIdentity,
623 canonicalKey: "github.com/other/repository",
624 displayName: "other/repository",
625 })
626 : Ref.set(detected, {
627 ...branchPullRequest(99),
628 repositoryKey: "github.com/other/repository",
629 url: "https://github.com/other/repository/pull/99",
630 })
631 ).pipe(Effect.as(summary(input, "merged"))),
632 });
633 yield* Effect.gen(function* () {
634 yield* fixture.start();
635 expect(yield* Ref.get(fixture.commands)).toEqual([]);
636 expect((yield* Ref.get(fixture.snapshots)).threads[0]?.linkedPullRequest).toEqual(
637 reference(1),
638 );
639 }).pipe(Effect.provide(fixture.layer));
640 }),
641 ),
642 );
643});