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