Open History to see the last commit
1import { assert, describe, expect, it } from "@effect/vitest";
2import * as DateTime from "effect/DateTime";
3import {
4 DEFAULT_SERVER_SETTINGS,
5 ProjectId,
6 ProviderInstanceId,
7 ThreadId,
8 type OrchestrationProjectShell,
9 type OrchestrationV2Command,
10 type OrchestrationV2ShellSnapshot,
11 type OrchestrationV2ThreadShell,
12 type PullRequestSummary,
13 type ServerSettings,
14 type ServerSettingsPatch,
15} from "@t3tools/contracts";
16import { applyServerSettingsPatch } from "@t3tools/shared/serverSettings";
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 {
30 PullRequestService,
31 type PullRequestMergeEvent,
32} from "../pullRequest/PullRequestService.ts";
33import { ServerActivation } from "../serverActivation.ts";
34import { ServerSettingsService } from "../serverSettings.ts";
35import { ProjectionSnapshotQuery } from "../orchestration/Services/ProjectionSnapshotQuery.ts";
36import { OrchestratorV2, type OrchestratorV2Shape } from "./Orchestrator.ts";
37import { ProjectionStoreV2 } from "./ProjectionStore.ts";
38import * as ThreadSettlementService from "./ThreadSettlementService.ts";
39
40import {
41 isAutoSettlementCandidate,
42 QUEUED_TURN_START_GRACE_MS,
43 resolveAutoSettlementAt,
44 threadHasQueuedTurnStart,
45} from "./ThreadSettlementService.ts";
46
47const NOW_MS = Date.parse("2026-06-10T12:00:00.000Z");
48const DAY_MS = 24 * 60 * 60 * 1_000;
49
50function at(offsetMs: number): DateTime.Utc {
51 return DateTime.makeUnsafe(NOW_MS + offsetMs);
52}
53
54function shell(overrides: Partial<OrchestrationV2ThreadShell> = {}): OrchestrationV2ThreadShell {
55 return {
56 id: ThreadId.make("thread-1"),
57 projectId: ProjectId.make("project-1"),
58 title: "Thread",
59 providerInstanceId: ProviderInstanceId.make("codex"),
60 modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
61 runtimeMode: "full-access",
62 interactionMode: "default",
63 worktreePath: null,
64 activeProviderThreadId: null,
65 lineage: {
66 rootThreadId: ThreadId.make("thread-1"),
67 parentThreadId: null,
68 relationshipToParent: null,
69 },
70 forkedFrom: null,
71 createdBy: "user",
72 creationSource: "web",
73 activeRunId: null,
74 latestVisibleMessage: null,
75 hasActionableProposedPlan: false,
76 itemCount: 0,
77 visibleItemCount: 0,
78 lastVisitedAt: null,
79 deletedAt: null,
80 branch: null,
81 linkedPullRequest: null,
82 status: "idle",
83 activityRunStatus: null,
84 pendingRuntimeRequest: null,
85 pendingBackgroundTasks: [],
86 latestRunId: null,
87 latestRunRequestedAt: null,
88 latestRunStartedAt: null,
89 latestRunCompletedAt: null,
90 latestUserMessageAt: null,
91 createdAt: at(-30 * DAY_MS),
92 updatedAt: at(-10 * DAY_MS),
93 archivedAt: null,
94 settledOverride: null,
95 settledAt: null,
96 snoozedUntil: null,
97 snoozedAt: null,
98 pinnedAt: null,
99 ...overrides,
100 };
101}
102
103describe("isAutoSettlementCandidate", () => {
104 it("excludes overridden, pinned, blocked, and working threads", () => {
105 expect(isAutoSettlementCandidate(shell(), NOW_MS)).toBe(true);
106 expect(isAutoSettlementCandidate(shell({ archivedAt: at(-1) }), NOW_MS)).toBe(false);
107 expect(isAutoSettlementCandidate(shell({ settledOverride: "settled" }), NOW_MS)).toBe(false);
108 expect(isAutoSettlementCandidate(shell({ settledOverride: "active" }), NOW_MS)).toBe(false);
109 expect(isAutoSettlementCandidate(shell({ pinnedAt: at(-1) }), NOW_MS)).toBe(false);
110 expect(isAutoSettlementCandidate(shell({ activityRunStatus: "running" }), NOW_MS)).toBe(false);
111 expect(
112 isAutoSettlementCandidate(
113 shell({
114 pendingRuntimeRequest: { kind: "approval" } as never,
115 }),
116 NOW_MS,
117 ),
118 ).toBe(false);
119 expect(
120 isAutoSettlementCandidate(
121 shell({ pendingBackgroundTasks: [{ label: "task" }] as never }),
122 NOW_MS,
123 ),
124 ).toBe(false);
125 });
126
127 it("keeps snoozed threads parked until they wake early on error or completion", () => {
128 const snoozed = shell({
129 snoozedUntil: at(60 * 60 * 1_000),
130 snoozedAt: at(-60 * 60 * 1_000),
131 });
132 expect(isAutoSettlementCandidate(snoozed, NOW_MS)).toBe(false);
133 expect(
134 isAutoSettlementCandidate(
135 shell({ ...snoozed, status: "failed", latestRunCompletedAt: at(-30 * 60 * 1_000) }),
136 NOW_MS,
137 ),
138 ).toBe(true);
139 expect(
140 isAutoSettlementCandidate(
141 shell({ ...snoozed, latestRunCompletedAt: at(-30 * 60 * 1_000) }),
142 NOW_MS,
143 ),
144 ).toBe(true);
145 expect(
146 isAutoSettlementCandidate(
147 shell({ ...snoozed, status: "failed", latestRunCompletedAt: at(-2 * 60 * 60 * 1_000) }),
148 NOW_MS,
149 ),
150 ).toBe(false);
151 expect(
152 isAutoSettlementCandidate(
153 shell({ ...snoozed, status: "failed", latestRunCompletedAt: snoozed.snoozedAt }),
154 NOW_MS,
155 ),
156 ).toBe(false);
157 expect(
158 isAutoSettlementCandidate(
159 shell({ ...snoozed, status: "failed", latestRunCompletedAt: null }),
160 NOW_MS,
161 ),
162 ).toBe(false);
163 // Expired snooze is no longer a park.
164 expect(isAutoSettlementCandidate(shell({ ...snoozed, snoozedUntil: at(-1) }), NOW_MS)).toBe(
165 true,
166 );
167 });
168});
169
170describe("threadHasQueuedTurnStart", () => {
171 it("holds a fresh unadopted user message inside the grace window only", () => {
172 const fresh = shell({ latestUserMessageAt: at(-1_000) });
173 expect(threadHasQueuedTurnStart(fresh, NOW_MS)).toBe(true);
174 // Adoption stamps the run with the message time, clearing the hold.
175 expect(
176 threadHasQueuedTurnStart(
177 shell({
178 latestUserMessageAt: at(-1_000),
179 latestRunId: "run-1" as never,
180 latestRunRequestedAt: at(-500),
181 }),
182 NOW_MS,
183 ),
184 ).toBe(false);
185 // Outside the grace window the stale message no longer blocks.
186 expect(
187 threadHasQueuedTurnStart(
188 shell({ latestUserMessageAt: at(-QUEUED_TURN_START_GRACE_MS - 1) }),
189 NOW_MS,
190 ),
191 ).toBe(false);
192 // Client clocks ahead of the server must not extend the hold.
193 expect(
194 threadHasQueuedTurnStart(
195 shell({ latestUserMessageAt: at(QUEUED_TURN_START_GRACE_MS + 1) }),
196 NOW_MS,
197 ),
198 ).toBe(false);
199 // A failed start clears the hold immediately.
200 expect(
201 threadHasQueuedTurnStart(
202 shell({ latestUserMessageAt: at(-1_000), status: "failed" }),
203 NOW_MS,
204 ),
205 ).toBe(false);
206 });
207});
208
209describe("resolveAutoSettlementAt", () => {
210 it("uses the latest activity time when the inactivity window elapses", () => {
211 const idle = shell({
212 latestUserMessageAt: at(-4 * DAY_MS),
213 latestRunRequestedAt: at(-4 * DAY_MS),
214 latestRunStartedAt: at(-4 * DAY_MS),
215 latestRunCompletedAt: at(-3 * DAY_MS),
216 });
217 const input = {
218 thread: idle,
219 pullRequest: null,
220 nowMs: NOW_MS,
221 autoSettleAfterDays: 2,
222 autoSettleOnMerge: true,
223 };
224 expect(resolveAutoSettlementAt(input)).toEqual(at(-3 * DAY_MS));
225 expect(resolveAutoSettlementAt({ ...input, autoSettleAfterDays: 5 })).toBeNull();
226 expect(resolveAutoSettlementAt({ ...input, autoSettleAfterDays: null })).toBeNull();
227 expect(resolveAutoSettlementAt({ ...input, thread: shell() })).toBeNull();
228 });
229
230 it("settles on merge only after the user's last action and preserves the activity time", () => {
231 const thread = shell({
232 latestUserMessageAt: at(-2 * 60 * 60 * 1_000),
233 latestRunCompletedAt: at(-90 * 60 * 1_000),
234 });
235 const input = {
236 thread,
237 pullRequest: {
238 state: "merged" as const,
239 mergedAt: DateTime.formatIso(at(-60 * 60 * 1_000)),
240 },
241 nowMs: NOW_MS,
242 autoSettleAfterDays: null,
243 autoSettleOnMerge: true,
244 };
245 expect(resolveAutoSettlementAt(input)).toEqual(at(-90 * 60 * 1_000));
246 expect(resolveAutoSettlementAt({ ...input, autoSettleOnMerge: false })).toBeNull();
247 expect(
248 resolveAutoSettlementAt({
249 ...input,
250 pullRequest: { state: "merged", mergedAt: DateTime.formatIso(at(-3 * 60 * 60 * 1_000)) },
251 }),
252 ).toBeNull();
253 // A thread without messages still has a stable timestamp when its PR closes.
254 expect(
255 resolveAutoSettlementAt({
256 ...input,
257 thread: shell(),
258 pullRequest: { state: "closed", closedAt: DateTime.formatIso(at(-1)) },
259 autoSettleOnMerge: false,
260 }),
261 ).toEqual(shell().createdAt);
262 });
263
264 it("settles inactive threads even when their pull request remains open", () => {
265 const input = {
266 thread: shell({ latestUserMessageAt: at(-30 * DAY_MS) }),
267 pullRequest: { state: "open" as const },
268 nowMs: NOW_MS,
269 autoSettleAfterDays: 2,
270 autoSettleOnMerge: true,
271 };
272 expect(resolveAutoSettlementAt(input)).toEqual(at(-30 * DAY_MS));
273 expect(resolveAutoSettlementAt({ ...input, autoSettleAfterDays: null })).toBeNull();
274 expect(
275 resolveAutoSettlementAt({
276 ...input,
277 thread: shell({ latestUserMessageAt: at(-DAY_MS) }),
278 }),
279 ).toBeNull();
280 });
281});
282
283const NOW = "2026-08-28T12:00:00.000Z";
284const PROJECT_ID = ProjectId.make("settlement-project");
285
286type AutoSettleCommand = Extract<OrchestrationV2Command, { readonly type: "thread.auto-settle" }>;
287
288const testCrypto = Crypto.make({
289 randomBytes: (size) => new Uint8Array(size).fill(1),
290 digest: (_algorithm, data) => Effect.succeed(data),
291});
292
293function makeProject(
294 id: ProjectId = PROJECT_ID,
295 workspaceRoot = "/workspace/project",
296): OrchestrationProjectShell {
297 return {
298 id,
299 title: `Project ${id}`,
300 workspaceRoot,
301 defaultModelSelection: null,
302 scripts: [],
303 createdAt: "2026-08-01T00:00:00.000Z",
304 updatedAt: NOW,
305 };
306}
307
308function makeThread(
309 id: string,
310 overrides: Partial<OrchestrationV2ThreadShell> = {},
311): OrchestrationV2ThreadShell {
312 return shell({
313 id: ThreadId.make(id),
314 projectId: PROJECT_ID,
315 title: id,
316 createdAt: DateTime.makeUnsafe("2026-08-01T00:00:00.000Z"),
317 updatedAt: DateTime.makeUnsafe("2026-08-20T00:00:00.000Z"),
318 latestUserMessageAt: DateTime.makeUnsafe("2026-08-20T00:00:00.000Z"),
319 ...overrides,
320 });
321}
322
323function makeSnapshot(
324 threads: ReadonlyArray<OrchestrationV2ThreadShell>,
325 projects: ReadonlyArray<OrchestrationProjectShell> = [makeProject()],
326): OrchestrationV2ShellSnapshot {
327 return {
328 schemaVersion: 1,
329 snapshotSequence: 1,
330 projects,
331 threads,
332 archivedThreads: [],
333 };
334}
335
336function makePullRequestSummary(input: {
337 readonly projectId: ProjectId;
338 readonly repository: string;
339 readonly number: number;
340 readonly state: "open" | "closed" | "merged";
341 readonly updatedAt?: string;
342}): PullRequestSummary {
343 return {
344 provider: "github",
345 projectId: input.projectId,
346 repository: input.repository,
347 number: input.number,
348 title: "Pull request",
349 url: `https://example.test/${input.repository}/pull/${input.number}`,
350 state: input.state,
351 headBranch: "feature",
352 baseBranch: "main",
353 updatedAt: input.updatedAt ?? NOW,
354 };
355}
356
357function makeBranchPullRequest(state: "open" | "closed" | "merged") {
358 return {
359 number: 42,
360 title: "Pull request",
361 url: "https://example.test/owner/repository/pull/42",
362 baseRef: "main",
363 headRef: "feature",
364 state,
365 repositoryKey: "example.test/owner/repository",
366 updatedAt: NOW,
367 closedAt: state === "closed" ? NOW : null,
368 mergedAt: state === "merged" ? NOW : null,
369 } satisfies GitBranchPullRequest;
370}
371
372interface HarnessOptions {
373 readonly snapshot: OrchestrationV2ShellSnapshot;
374 readonly settings?: ServerSettings;
375 readonly branchPullRequest?: GitManager["Service"]["branchPullRequest"];
376 readonly pullRequestSummary?: PullRequestService["Service"]["summary"];
377 readonly existingWorktreePaths?: ReadonlyArray<string>;
378 readonly onDispatch?: (command: AutoSettleCommand) => Effect.Effect<void>;
379}
380
381const makeHarness = Effect.fn("makeThreadSettlementHarness")(function* (options: HarnessOptions) {
382 const activation = yield* Deferred.make<void>();
383 const snapshots = yield* Ref.make(options.snapshot);
384 const snapshotReadCount = yield* Ref.make(0);
385 const snapshotReads = yield* Queue.unbounded<number>();
386 const settings = yield* Ref.make(options.settings ?? DEFAULT_SERVER_SETTINGS);
387 const settingsChanges = yield* PubSub.unbounded<ServerSettings>();
388 const mergedPullRequests = yield* PubSub.unbounded<PullRequestMergeEvent>();
389 const commands = yield* Ref.make<ReadonlyArray<AutoSettleCommand>>([]);
390 const branchCalls = yield* Ref.make<
391 ReadonlyArray<{ readonly cwd: string; readonly branch: string }>
392 >([]);
393 const summaryCalls = yield* Ref.make<
394 ReadonlyArray<{
395 readonly projectId: ProjectId;
396 readonly repository: string;
397 readonly number: number;
398 }>
399 >([]);
400 const summaryRecovery = yield* Ref.make<ReadonlyArray<boolean | undefined>>([]);
401 const invalidatedCwds = yield* Ref.make<ReadonlyArray<string>>([]);
402
403 const updateSettings = (patch: ServerSettingsPatch) =>
404 Effect.gen(function* () {
405 const next = applyServerSettingsPatch(yield* Ref.get(settings), patch);
406 yield* Ref.set(settings, next);
407 yield* PubSub.publish(settingsChanges, next);
408 return next;
409 });
410
411 const branchPullRequest: GitManager["Service"]["branchPullRequest"] = (input) =>
412 Ref.update(branchCalls, (calls) => [...calls, input]).pipe(
413 Effect.andThen(options.branchPullRequest?.(input) ?? Effect.succeed(null)),
414 );
415 const pullRequestSummary: PullRequestService["Service"]["summary"] = (input, readOptions) =>
416 Effect.gen(function* () {
417 yield* Ref.update(summaryCalls, (calls) => [...calls, input]);
418 yield* Ref.update(summaryRecovery, (values) => [
419 ...values,
420 readOptions?.recoverTransientFailure,
421 ]);
422 return yield* (
423 options.pullRequestSummary?.(input, readOptions) ??
424 Effect.succeed(
425 makePullRequestSummary({
426 ...input,
427 state: "open",
428 }),
429 )
430 );
431 });
432
433 const dispatch: OrchestratorV2Shape["dispatch"] = (command) => {
434 if (command.type !== "thread.auto-settle") {
435 return Effect.die(new Error(`Unexpected command: ${command.type}`));
436 }
437 return Ref.update(commands, (recorded) => [...recorded, command]).pipe(
438 Effect.andThen(options.onDispatch?.(command) ?? Effect.void),
439 Effect.as({ sequence: 1, storedEvents: [] }),
440 );
441 };
442
443 const serverSettings = ServerSettingsService.of({
444 start: Effect.void,
445 ready: Effect.void,
446 getSettings: Ref.get(settings),
447 updateSettings,
448 updateProviderInstance: () => Effect.die("Unexpected provider mutation"),
449 withSettingsSnapshot: (use) => Ref.get(settings).pipe(Effect.flatMap(use)),
450 streamChanges: Stream.fromPubSub(settingsChanges),
451 subscribeChanges: PubSub.subscribe(settingsChanges).pipe(
452 Effect.map((subscription) => Stream.fromSubscription(subscription)),
453 ),
454 });
455
456 const dependencies = Layer.mergeAll(
457 Layer.mock(ProjectionSnapshotQuery)({
458 getProjectShellsWithoutEnrichment: () =>
459 Ref.get(snapshots).pipe(Effect.map((snapshot) => snapshot.projects)),
460 }),
461 Layer.mock(ProjectionStoreV2)({
462 getSettlementCandidates: () =>
463 Ref.updateAndGet(snapshotReadCount, (count) => count + 1).pipe(
464 Effect.tap((count) => Queue.offer(snapshotReads, count)),
465 Effect.andThen(Ref.get(snapshots)),
466 Effect.map((snapshot) => snapshot.threads),
467 ),
468 }),
469 Layer.mock(OrchestratorV2)({
470 dispatch,
471 }),
472 Layer.mock(GitManager)({
473 branchPullRequest,
474 invalidateStatus: (cwd) => Ref.update(invalidatedCwds, (cwds) => [...cwds, cwd]),
475 }),
476 Layer.mock(PullRequestService)({
477 summary: pullRequestSummary,
478 subscribeMerges: PubSub.subscribe(mergedPullRequests).pipe(
479 Effect.map((subscription) => Stream.fromSubscription(subscription)),
480 ),
481 }),
482 Layer.succeed(ServerSettingsService, serverSettings),
483 Layer.succeed(ServerActivation, Deferred.await(activation)),
484 Layer.succeed(Crypto.Crypto, testCrypto),
485 FileSystem.layerNoop({
486 exists: (path) => Effect.succeed(options.existingWorktreePaths?.includes(path) ?? false),
487 }),
488 );
489
490 return {
491 activation,
492 snapshots,
493 snapshotReadCount,
494 snapshotReads,
495 commands,
496 branchCalls,
497 summaryCalls,
498 summaryRecovery,
499 invalidatedCwds,
500 updateSettings,
501 publishMerge: PubSub.publish(mergedPullRequests, {
502 projectId: PROJECT_ID,
503 repository: "owner/repository",
504 number: 42,
505 mergedAt: NOW,
506 }),
507 layer: ThreadSettlementService.layer.pipe(Layer.provide(dependencies)),
508 };
509});
510
511const startHarness = Effect.fn("startThreadSettlementHarness")(function* (
512 reactor: ThreadSettlementService.ThreadSettlementServiceV2["Service"],
513 activation: Deferred.Deferred<void>,
514 snapshotReads: Queue.Queue<number>,
515) {
516 yield* reactor.start();
517 yield* Deferred.succeed(activation, undefined);
518 yield* Queue.take(snapshotReads);
519 yield* reactor.drain;
520});
521
522describe("ThreadSettlementServiceV2 worker", () => {
523 it.effect("dispatches the last activity time with the v2 snapshot guard", () =>
524 Effect.scoped(
525 Effect.gen(function* () {
526 yield* TestClock.setTime(Date.parse(NOW));
527 const thread = makeThread("inactive-open-pr", {
528 branch: "feature",
529 latestRunCompletedAt: DateTime.makeUnsafe("2026-08-25T00:00:00.000Z"),
530 });
531 const fixture = yield* makeHarness({
532 snapshot: makeSnapshot([thread]),
533 settings: { ...DEFAULT_SERVER_SETTINGS, sidebarAutoSettleAfterDays: 2 },
534 branchPullRequest: () => Effect.succeed(makeBranchPullRequest("open")),
535 });
536 yield* Effect.gen(function* () {
537 const service = yield* ThreadSettlementService.ThreadSettlementServiceV2;
538 yield* startHarness(service, fixture.activation, fixture.snapshotReads);
539 const commands = yield* Ref.get(fixture.commands);
540 expect(commands).toHaveLength(1);
541 expect(commands[0]?.settledAt).toEqual(thread.latestRunCompletedAt);
542 expect(commands[0]?.snapshotAt).toEqual(thread.updatedAt);
543 }).pipe(Effect.provide(fixture.layer));
544 }),
545 ),
546 );
547
548 it.effect("reevaluates immediately after a pull request merge", () =>
549 Effect.scoped(
550 Effect.gen(function* () {
551 yield* TestClock.setTime(Date.parse(NOW));
552 const periodicLookupStarted = yield* Deferred.make<void>();
553 const releasePeriodicLookup = yield* Deferred.make<void>();
554 const mergedThreadSettled = yield* Deferred.make<void>();
555 const branchLookupCount = yield* Ref.make(0);
556 const fixture = yield* makeHarness({
557 snapshot: makeSnapshot([
558 makeThread("merged-in-app", {
559 latestUserMessageAt: DateTime.makeUnsafe("2026-08-27T00:00:00.000Z"),
560 linkedPullRequest: {
561 projectId: PROJECT_ID,
562 repository: "Owner/Repository",
563 number: 42,
564 url: "https://example.test/owner/repository/pull/42",
565 },
566 }),
567 makeThread("slow-periodic-lookup", {
568 branch: "another-feature",
569 latestUserMessageAt: DateTime.makeUnsafe("2026-08-27T00:00:00.000Z"),
570 }),
571 ]),
572 branchPullRequest: () =>
573 Ref.updateAndGet(branchLookupCount, (count) => count + 1).pipe(
574 Effect.flatMap((count) =>
575 count === 1
576 ? Effect.succeed(makeBranchPullRequest("open"))
577 : Deferred.succeed(periodicLookupStarted, undefined).pipe(
578 Effect.andThen(Deferred.await(releasePeriodicLookup)),
579 Effect.as(makeBranchPullRequest("open")),
580 ),
581 ),
582 ),
583 onDispatch: () => Deferred.succeed(mergedThreadSettled, undefined),
584 });
585
586 yield* Effect.gen(function* () {
587 const reactor = yield* ThreadSettlementService.ThreadSettlementServiceV2;
588 yield* startHarness(reactor, fixture.activation, fixture.snapshotReads);
589 yield* fixture.updateSettings({ sidebarAutoSettleAfterDays: 4 });
590 yield* Deferred.await(periodicLookupStarted);
591
592 yield* fixture.publishMerge;
593 yield* Deferred.await(mergedThreadSettled);
594
595 assert.deepStrictEqual(
596 (yield* Ref.get(fixture.commands)).map((command) => command.threadId),
597 [ThreadId.make("merged-in-app")],
598 );
599 yield* Deferred.succeed(releasePeriodicLookup, undefined);
600 yield* reactor.drain;
601 }).pipe(Effect.provide(fixture.layer));
602 }),
603 ),
604 );
605
606 it.effect(
607 "settles branch threads on a pull request merge without waiting for the next sweep",
608 () =>
609 Effect.scoped(
610 Effect.gen(function* () {
611 yield* TestClock.setTime(Date.parse(NOW));
612 const state = yield* Ref.make<"open" | "merged">("open");
613 const mergedThreadSettled = yield* Deferred.make<void>();
614 const fixture = yield* makeHarness({
615 snapshot: makeSnapshot([
616 makeThread("branch-thread", {
617 branch: "saved-feature",
618 latestUserMessageAt: DateTime.makeUnsafe("2026-08-27T00:00:00.000Z"),
619 }),
620 ]),
621 branchPullRequest: () => Ref.get(state).pipe(Effect.map(makeBranchPullRequest)),
622 onDispatch: () => Deferred.succeed(mergedThreadSettled, undefined),
623 });
624
625 yield* Effect.gen(function* () {
626 const reactor = yield* ThreadSettlementService.ThreadSettlementServiceV2;
627 yield* startHarness(reactor, fixture.activation, fixture.snapshotReads);
628 assert.deepStrictEqual(yield* Ref.get(fixture.commands), []);
629 assert.deepStrictEqual(yield* Ref.get(fixture.invalidatedCwds), []);
630
631 yield* Ref.set(state, "merged");
632 yield* fixture.publishMerge;
633 yield* Deferred.await(mergedThreadSettled);
634
635 assert.deepStrictEqual(
636 (yield* Ref.get(fixture.commands)).map((command) => command.threadId),
637 [ThreadId.make("branch-thread")],
638 );
639 assert.deepStrictEqual(yield* Ref.get(fixture.invalidatedCwds), ["/workspace/project"]);
640 yield* reactor.drain;
641 }).pipe(Effect.provide(fixture.layer));
642 }),
643 ),
644 );
645
646 it.effect("a merge does not settle threads linked to an unrelated pull request", () =>
647 Effect.scoped(
648 Effect.gen(function* () {
649 yield* TestClock.setTime(Date.parse(NOW));
650 const mergedThreadSettled = yield* Deferred.make<void>();
651 const mergeLookupStarted = yield* Deferred.make<void>();
652 const releaseMergeLookup = yield* Deferred.make<void>();
653 const lookupCount = yield* Ref.make(0);
654 const fixture = yield* makeHarness({
655 snapshot: makeSnapshot([
656 makeThread("merged-in-app", {
657 latestUserMessageAt: DateTime.makeUnsafe("2026-08-27T00:00:00.000Z"),
658 linkedPullRequest: {
659 projectId: PROJECT_ID,
660 repository: "owner/repository",
661 number: 42,
662 url: "https://example.test/owner/repository/pull/42",
663 },
664 }),
665 makeThread("unrelated-linked", {
666 latestUserMessageAt: DateTime.makeUnsafe("2026-08-27T00:00:00.000Z"),
667 linkedPullRequest: {
668 projectId: PROJECT_ID,
669 repository: "owner/repository",
670 number: 99,
671 url: "https://example.test/owner/repository/pull/99",
672 },
673 }),
674 ]),
675 pullRequestSummary: (input) =>
676 Ref.updateAndGet(lookupCount, (count) => count + 1).pipe(
677 // The initial sweep looks up both linked threads; the merge
678 // sweep only looks up the unrelated one, since the merged
679 // thread settles from the event itself.
680 Effect.tap((count) =>
681 count === 3 ? Deferred.succeed(mergeLookupStarted, undefined) : Effect.void,
682 ),
683 Effect.tap((count) =>
684 count === 3 ? Deferred.await(releaseMergeLookup) : Effect.void,
685 ),
686 Effect.map(() => makePullRequestSummary({ ...input, state: "open" })),
687 ),
688 onDispatch: () => Deferred.succeed(mergedThreadSettled, undefined),
689 });
690
691 yield* Effect.gen(function* () {
692 const reactor = yield* ThreadSettlementService.ThreadSettlementServiceV2;
693 yield* startHarness(reactor, fixture.activation, fixture.snapshotReads);
694 assert.deepStrictEqual(yield* Ref.get(fixture.commands), []);
695
696 yield* fixture.publishMerge;
697 yield* Deferred.await(mergeLookupStarted);
698 yield* Deferred.await(mergedThreadSettled);
699 yield* Deferred.succeed(releaseMergeLookup, undefined);
700 yield* reactor.drain;
701
702 assert.deepStrictEqual(
703 (yield* Ref.get(fixture.commands)).map((command) => command.threadId),
704 [ThreadId.make("merged-in-app")],
705 );
706 assert.deepStrictEqual(
707 (yield* Ref.get(fixture.summaryCalls))
708 .map((call) => call.number)
709 .toSorted((left, right) => left - right),
710 [42, 99, 99],
711 );
712 }).pipe(Effect.provide(fixture.layer));
713 }),
714 ),
715 );
716
717 it.effect("looks up the branch pull request from a thread's live worktree", () =>
718 Effect.scoped(
719 Effect.gen(function* () {
720 yield* TestClock.setTime(Date.parse(NOW));
721 const fixture = yield* makeHarness({
722 snapshot: makeSnapshot(
723 [
724 makeThread("live-worktree", {
725 branch: "feature/live",
726 worktreePath: "/workspace/project-root/.worktrees/live",
727 }),
728 makeThread("deleted-worktree", {
729 branch: "feature/deleted",
730 worktreePath: "/workspace/project-root/.worktrees/deleted",
731 }),
732 ],
733 [makeProject(PROJECT_ID, "/workspace/project-root")],
734 ),
735 existingWorktreePaths: ["/workspace/project-root/.worktrees/live"],
736 settings: {
737 ...DEFAULT_SERVER_SETTINGS,
738 sidebarAutoSettleAfterDays: null,
739 sidebarAutoSettleOnMerge: true,
740 },
741 });
742
743 yield* Effect.gen(function* () {
744 const reactor = yield* ThreadSettlementService.ThreadSettlementServiceV2;
745 yield* startHarness(reactor, fixture.activation, fixture.snapshotReads);
746
747 assert.deepStrictEqual(
748 new Set(yield* Ref.get(fixture.branchCalls)),
749 new Set([
750 { cwd: "/workspace/project-root/.worktrees/live", branch: "feature/live" },
751 { cwd: "/workspace/project-root", branch: "feature/deleted" },
752 ]),
753 );
754 }).pipe(Effect.provide(fixture.layer));
755 }),
756 ),
757 );
758});