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

ThreadSettlementService.test.ts

862 lines30.9 KB

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