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