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

ThreadSettlementService.test.ts

1,335 lines50.2 KB

1import { assert, describe, expect, it } from "@effect/vitest";
2import * as DateTime from "effect/DateTime";
3import {
4 DEFAULT_SERVER_SETTINGS,
5 ProjectId,
6 EventId,
7 ProviderInstanceId,
8 ProviderSessionId,
9 ThreadId,
10 type OrchestrationProjectShell,
11 type OrchestrationV2AppThread,
12 type OrchestrationV2Command,
13 type OrchestrationV2DomainEvent,
14 type OrchestrationV2ShellSnapshot,
15 type OrchestrationV2ThreadShell,
16 type PullRequestSummary,
17 type ServerSettings as ContractServerSettings,
18 type ServerSettingsPatch,
19} from "@t3tools/contracts";
20import { applyServerSettingsPatch } from "@t3tools/shared/serverSettings";
21import * as Crypto from "effect/Crypto";
22import * as Deferred from "effect/Deferred";
23import * as Effect from "effect/Effect";
24import * as FileSystem from "effect/FileSystem";
25import * as Layer from "effect/Layer";
26import * as PubSub from "effect/PubSub";
27import * as Queue from "effect/Queue";
28import * as Ref from "effect/Ref";
29import * as Stream from "effect/Stream";
30import { TestClock } from "effect/testing";
31​
32import * as GitManager from "../git/GitManager.ts";
33import * as ProjectSetupScriptRunner from "../project/ProjectSetupScriptRunner.ts";
34import * as PullRequestService from "../pullRequest/PullRequestService.ts";
35import * as ServerActivation from "../serverActivation.ts";
36import * as ServerSettings from "../serverSettings.ts";
37import * as TerminalManager from "../terminal/Manager.ts";
38import * as ProjectStore from "./ProjectStore.ts";
39import * as Orchestrator from "./Orchestrator.ts";
40import * as ProjectionStore from "./ProjectionStore.ts";
41import * as ThreadSettlementService from "./ThreadSettlementService.ts";
42​
43const NOW_MS = Date.parse("2026-06-10T12:00:00.000Z");
44const DAY_MS = 24 * 60 * 60 * 1_000;
45​
46function at(offsetMs: number): DateTime.Utc {
47 return DateTime.makeUnsafe(NOW_MS + offsetMs);
49​
50type SettlementShell = OrchestrationV2ThreadShell &
51 Pick<ProjectionStore.ProjectionSettlementCandidate, "latestUserAuthoredMessageAt">;
52​
53// A fixture's user message is one the user wrote unless the test sets
54// latestUserAuthoredMessageAt on its own.
55function shell(overrides: Partial<SettlementShell> = {}): SettlementShell {
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 latestUserAuthoredMessageAt: overrides.latestUserMessageAt ?? null,
93 createdAt: at(-30 * DAY_MS),
94 updatedAt: at(-10 * DAY_MS),
95 archivedAt: null,
96 settledOverride: null,
97 settledAt: null,
98 snoozedUntil: null,
99 snoozedAt: null,
100 pinnedAt: null,
101 ...overrides,
102 };
104​
105describe("isAutoSettlementCandidate", () => {
106 it("excludes overridden, pinned, blocked, and working threads", () => {
107 expect(ThreadSettlementService.isAutoSettlementCandidate(shell(), NOW_MS)).toBe(true);
108 expect(
109 ThreadSettlementService.isAutoSettlementCandidate(shell({ archivedAt: at(-1) }), NOW_MS),
110 ).toBe(false);
111 expect(
112 ThreadSettlementService.isAutoSettlementCandidate(
113 shell({ settledOverride: "settled" }),
114 NOW_MS,
115 ),
116 ).toBe(false);
117 expect(
118 ThreadSettlementService.isAutoSettlementCandidate(
119 shell({ settledOverride: "active" }),
120 NOW_MS,
121 ),
122 ).toBe(false);
123 expect(
124 ThreadSettlementService.isAutoSettlementCandidate(shell({ pinnedAt: at(-1) }), NOW_MS),
125 ).toBe(false);
126 expect(
127 ThreadSettlementService.isAutoSettlementCandidate(
128 shell({ autoSettleDisabledAt: at(-1) }),
129 NOW_MS,
130 ),
131 ).toBe(false);
132 expect(
133 ThreadSettlementService.isAutoSettlementCandidate(
134 shell({ activityRunStatus: "running" }),
135 NOW_MS,
136 ),
137 ).toBe(false);
138 expect(
139 ThreadSettlementService.isAutoSettlementCandidate(
140 shell({
141 pendingRuntimeRequest: { kind: "approval" } as never,
142 }),
143 NOW_MS,
144 ),
145 ).toBe(false);
146 expect(
147 ThreadSettlementService.isAutoSettlementCandidate(
148 shell({ pendingBackgroundTasks: [{ taskId: "review", kind: "subagent" }] }),
149 NOW_MS,
150 ),
151 ).toBe(false);
152 });
153​
154 it("holds a thread whose only background work is a live command", () => {
155 // The agent may be waiting on the command, which wakes it when it exits.
156 expect(
157 ThreadSettlementService.isAutoSettlementCandidate(
158 shell({
159 pendingBackgroundTasks: [
160 { taskId: "ci", kind: "command", description: "gh run watch --exit-status" },
161 ],
162 }),
163 NOW_MS,
164 ),
165 ).toBe(false);
166 });
167​
168 it("keeps snoozed threads parked until they wake early on error or completion", () => {
169 const snoozed = shell({
170 snoozedUntil: at(60 * 60 * 1_000),
171 snoozedAt: at(-60 * 60 * 1_000),
172 });
173 expect(ThreadSettlementService.isAutoSettlementCandidate(snoozed, NOW_MS)).toBe(false);
174 expect(
175 ThreadSettlementService.isAutoSettlementCandidate(
176 shell({ ...snoozed, status: "failed", latestRunCompletedAt: at(-30 * 60 * 1_000) }),
177 NOW_MS,
178 ),
179 ).toBe(true);
180 expect(
181 ThreadSettlementService.isAutoSettlementCandidate(
182 shell({ ...snoozed, latestRunCompletedAt: at(-30 * 60 * 1_000) }),
183 NOW_MS,
184 ),
185 ).toBe(true);
186 expect(
187 ThreadSettlementService.isAutoSettlementCandidate(
188 shell({ ...snoozed, status: "failed", latestRunCompletedAt: at(-2 * 60 * 60 * 1_000) }),
189 NOW_MS,
190 ),
191 ).toBe(false);
192 expect(
193 ThreadSettlementService.isAutoSettlementCandidate(
194 shell({ ...snoozed, status: "failed", latestRunCompletedAt: snoozed.snoozedAt }),
195 NOW_MS,
196 ),
197 ).toBe(false);
198 expect(
199 ThreadSettlementService.isAutoSettlementCandidate(
200 shell({ ...snoozed, status: "failed", latestRunCompletedAt: null }),
201 NOW_MS,
202 ),
203 ).toBe(false);
204 // Expired snooze is no longer a park.
205 expect(
206 ThreadSettlementService.isAutoSettlementCandidate(
207 shell({ ...snoozed, snoozedUntil: at(-1) }),
208 NOW_MS,
209 ),
210 ).toBe(true);
211 });
212});
213​
214describe("threadHasQueuedTurnStart", () => {
215 it("holds a fresh unadopted user message inside the grace window only", () => {
216 const fresh = shell({ latestUserMessageAt: at(-1_000) });
217 expect(ThreadSettlementService.threadHasQueuedTurnStart(fresh, NOW_MS)).toBe(true);
218 // Adoption stamps the run with the message time, clearing the hold.
219 expect(
220 ThreadSettlementService.threadHasQueuedTurnStart(
221 shell({
222 latestUserMessageAt: at(-1_000),
223 latestRunId: "run-1" as never,
224 latestRunRequestedAt: at(-500),
225 }),
226 NOW_MS,
227 ),
228 ).toBe(false);
229 // Outside the grace window the stale message no longer blocks.
230 expect(
231 ThreadSettlementService.threadHasQueuedTurnStart(
232 shell({ latestUserMessageAt: at(-ThreadSettlementService.QUEUED_TURN_START_GRACE_MS - 1) }),
233 NOW_MS,
234 ),
235 ).toBe(false);
236 // Client clocks ahead of the server must not extend the hold.
237 expect(
238 ThreadSettlementService.threadHasQueuedTurnStart(
239 shell({ latestUserMessageAt: at(ThreadSettlementService.QUEUED_TURN_START_GRACE_MS + 1) }),
240 NOW_MS,
241 ),
242 ).toBe(false);
243 // A failed start clears the hold immediately.
244 expect(
245 ThreadSettlementService.threadHasQueuedTurnStart(
246 shell({ latestUserMessageAt: at(-1_000), status: "failed" }),
247 NOW_MS,
248 ),
249 ).toBe(false);
250 });
251});
252​
253describe("resolveAutoSettlementAt", () => {
254 it("uses the latest activity time when the inactivity window elapses", () => {
255 const idle = shell({
256 latestUserMessageAt: at(-4 * DAY_MS),
257 latestRunRequestedAt: at(-4 * DAY_MS),
258 latestRunStartedAt: at(-4 * DAY_MS),
259 latestRunCompletedAt: at(-3 * DAY_MS),
260 });
261 const input = {
262 thread: idle,
263 pullRequest: null,
264 nowMs: NOW_MS,
265 autoSettleAfterDays: 2,
266 autoSettleOnMerge: true,
267 };
268 expect(ThreadSettlementService.resolveAutoSettlementAt(input)).toEqual(at(-3 * DAY_MS));
269 expect(
270 ThreadSettlementService.resolveAutoSettlementAt({ ...input, autoSettleAfterDays: 5 }),
271 ).toBeNull();
272 expect(
273 ThreadSettlementService.resolveAutoSettlementAt({ ...input, autoSettleAfterDays: null }),
274 ).toBeNull();
275 expect(
276 ThreadSettlementService.resolveAutoSettlementAt({ ...input, thread: shell() }),
277 ).toBeNull();
278 });
279​
280 it.each(["manual", "timer"])("restarts inactivity on a %s snooze wake", (wake) => {
281 const thread = {
282 ...shell({ latestRunCompletedAt: at(-4 * DAY_MS) }),
283 ...(wake === "manual"
284 ? { lastSnoozeWakeAt: at(-1_000) }
285 : { snoozedAt: at(-3 * DAY_MS), snoozedUntil: at(-1_000) }),
286 };
287 const input = {
288 thread,
289 pullRequest: null,
290 nowMs: NOW_MS,
291 autoSettleAfterDays: 1,
292 autoSettleOnMerge: false,
293 };
294 expect(ThreadSettlementService.resolveAutoSettlementAt(input)).toBeNull();
295 expect(
296 ThreadSettlementService.resolveAutoSettlementAt({ ...input, nowMs: NOW_MS + DAY_MS }),
297 ).toEqual(at(-1_000));
298 });
299​
300 it("settles on merge only after the user's last action and preserves the activity time", () => {
301 const thread = shell({
302 latestUserMessageAt: at(-2 * 60 * 60 * 1_000),
303 latestRunCompletedAt: at(-90 * 60 * 1_000),
304 });
305 const input = {
306 thread,
307 pullRequest: {
308 state: "merged" as const,
309 mergedAt: DateTime.formatIso(at(-60 * 60 * 1_000)),
310 },
311 nowMs: NOW_MS,
312 autoSettleAfterDays: null,
313 autoSettleOnMerge: true,
314 };
315 expect(ThreadSettlementService.resolveAutoSettlementAt(input)).toEqual(at(-90 * 60 * 1_000));
316 expect(
317 ThreadSettlementService.resolveAutoSettlementAt({ ...input, autoSettleOnMerge: false }),
318 ).toBeNull();
319 expect(
320 ThreadSettlementService.resolveAutoSettlementAt({
321 ...input,
322 pullRequest: { state: "merged", mergedAt: DateTime.formatIso(at(-3 * 60 * 60 * 1_000)) },
323 }),
324 ).toBeNull();
325 // A thread without messages still has a stable timestamp when its PR closes.
326 expect(
327 ThreadSettlementService.resolveAutoSettlementAt({
328 ...input,
329 thread: shell(),
330 pullRequest: { state: "closed", closedAt: DateTime.formatIso(at(-1)) },
331 autoSettleOnMerge: false,
332 }),
333 ).toEqual(shell().createdAt);
334 });
335​
336 it("settles on merge after agent-started runs, but not after the user writes again", () => {
337 // A background command stopped after the merge and its notification
338 // started a run. Only the user's own messages hold a merged thread open.
339 const woken = shell({
340 latestUserMessageAt: at(-30 * 60 * 1_000),
341 latestUserAuthoredMessageAt: at(-2 * 60 * 60 * 1_000),
342 latestRunRequestedAt: at(-30 * 60 * 1_000),
343 latestRunCompletedAt: at(-29 * 60 * 1_000),
344 });
345 const input = {
346 thread: woken,
347 pullRequest: { state: "merged" as const, mergedAt: DateTime.formatIso(at(-60 * 60 * 1_000)) },
348 nowMs: NOW_MS,
349 autoSettleAfterDays: null,
350 autoSettleOnMerge: true,
351 };
352 expect(ThreadSettlementService.resolveAutoSettlementAt(input)).toEqual(at(-29 * 60 * 1_000));
353 expect(
354 ThreadSettlementService.resolveAutoSettlementAt({
355 ...input,
356 thread: { ...woken, latestUserAuthoredMessageAt: at(-30 * 60 * 1_000) },
357 }),
358 ).toBeNull();
359 });
360​
361 it("does not settle on merge or inactivity while a background command runs", () => {
362 const idle = shell({
363 latestUserMessageAt: at(-4 * DAY_MS),
364 latestRunCompletedAt: at(-3 * DAY_MS),
365 });
366 const waiting = {
367 ...idle,
368 pendingBackgroundTasks: [{ taskId: "ci", kind: "command" as const }],
369 };
370 const merged = {
371 state: "merged" as const,
372 mergedAt: DateTime.formatIso(at(-60 * 60 * 1_000)),
373 };
374 const onMerge = {
375 thread: waiting,
376 pullRequest: merged,
377 nowMs: NOW_MS,
378 autoSettleAfterDays: null,
379 autoSettleOnMerge: true,
380 };
381 const onInactivity = {
382 thread: waiting,
383 pullRequest: null,
384 nowMs: NOW_MS,
385 autoSettleAfterDays: 2,
386 autoSettleOnMerge: false,
387 };
388 expect(ThreadSettlementService.resolveAutoSettlementAt(onMerge)).toBeNull();
389 expect(ThreadSettlementService.resolveAutoSettlementAt(onInactivity)).toBeNull();
390 // Once the command exits, both rules settle the same thread.
391 expect(ThreadSettlementService.resolveAutoSettlementAt({ ...onMerge, thread: idle })).toEqual(
392 at(-3 * DAY_MS),
393 );
394 expect(
395 ThreadSettlementService.resolveAutoSettlementAt({ ...onInactivity, thread: idle }),
396 ).toEqual(at(-3 * DAY_MS));
397 });
398​
399 it("settles inactive threads even when their pull request remains open", () => {
400 const input = {
401 thread: shell({ latestUserMessageAt: at(-30 * DAY_MS) }),
402 pullRequest: { state: "open" as const },
403 nowMs: NOW_MS,
404 autoSettleAfterDays: 2,
405 autoSettleOnMerge: true,
406 };
407 expect(ThreadSettlementService.resolveAutoSettlementAt(input)).toEqual(at(-30 * DAY_MS));
408 expect(
409 ThreadSettlementService.resolveAutoSettlementAt({ ...input, autoSettleAfterDays: null }),
410 ).toBeNull();
411 expect(
412 ThreadSettlementService.resolveAutoSettlementAt({
413 ...input,
414 thread: shell({ latestUserMessageAt: at(-DAY_MS) }),
415 }),
416 ).toBeNull();
417 });
418});
419​
420const NOW = "2026-08-28T12:00:00.000Z";
421const PROJECT_ID = ProjectId.make("settlement-project");
422const LINKED_PROJECT_ID = ProjectId.make("linked-settlement-project");
423​
424describe("autoSettlementSettingsKey", () => {
425 it("distinguishes a project that inherits the threshold from one that disables it", () => {
426 const inherits = ThreadSettlementService.autoSettlementSettingsKey({
427 ...DEFAULT_SERVER_SETTINGS,
428 projectSettingsOverrides: { [PROJECT_ID]: { sidebarAutoSettleOnMerge: true } },
429 });
430 const never = ThreadSettlementService.autoSettlementSettingsKey({
431 ...DEFAULT_SERVER_SETTINGS,
432 projectSettingsOverrides: {
433 [PROJECT_ID]: { sidebarAutoSettleOnMerge: true, sidebarAutoSettleAfterDays: null },
434 },
435 });
436 assert.notStrictEqual(inherits, never);
437 });
438​
439 it("ignores project overrides that do not touch settlement", () => {
440 const base = ThreadSettlementService.autoSettlementSettingsKey({
441 ...DEFAULT_SERVER_SETTINGS,
442 projectSettingsOverrides: { [PROJECT_ID]: { sidebarAutoSettleOnMerge: false } },
443 });
444 const unrelated = ThreadSettlementService.autoSettlementSettingsKey({
445 ...DEFAULT_SERVER_SETTINGS,
446 projectSettingsOverrides: {
447 [LINKED_PROJECT_ID]: { defaultThreadEnvMode: "worktree" },
448 [PROJECT_ID]: { sidebarAutoSettleOnMerge: false, defaultAutoPull: true },
449 },
450 });
451 assert.strictEqual(base, unrelated);
452 });
453});
454​
455type AutoSettleCommand = Extract<OrchestrationV2Command, { readonly type: "thread.auto-settle" }>;
456​
457const testCrypto = Crypto.make({
458 randomBytes: (size) => new Uint8Array(size).fill(1),
459 digest: (_algorithm, data) => Effect.succeed(data),
460});
461​
462function makeProject(
463 id: ProjectId = PROJECT_ID,
464 workspaceRoot = "/workspace/project",
465): OrchestrationProjectShell {
466 return {
467 id,
468 title: `Project ${id}`,
469 workspaceRoot,
470 defaultModelSelection: null,
471 scripts: [],
472 createdAt: "2026-08-01T00:00:00.000Z",
473 updatedAt: NOW,
474 };
476​
477function makeThread(id: string, overrides: Partial<SettlementShell> = {}): SettlementShell {
478 return shell({
479 id: ThreadId.make(id),
480 projectId: PROJECT_ID,
481 title: id,
482 createdAt: DateTime.makeUnsafe("2026-08-01T00:00:00.000Z"),
483 updatedAt: DateTime.makeUnsafe("2026-08-20T00:00:00.000Z"),
484 latestUserMessageAt: DateTime.makeUnsafe("2026-08-20T00:00:00.000Z"),
485 ...overrides,
486 });
488​
489type SettlementSnapshot = Omit<OrchestrationV2ShellSnapshot, "threads"> & {
490 readonly threads: ReadonlyArray<SettlementShell>;
491};
492​
493function makeSnapshot(
494 threads: ReadonlyArray<SettlementShell>,
495 projects: ReadonlyArray<OrchestrationProjectShell> = [makeProject()],
496): SettlementSnapshot {
497 return {
498 schemaVersion: 1,
499 snapshotSequence: 1,
500 projects,
501 threads,
502 archivedThreads: [],
503 };
505​
506function makePullRequestSummary(input: {
507 readonly projectId: ProjectId;
508 readonly repository: string;
509 readonly number: number;
510 readonly state: "open" | "closed" | "merged";
511 readonly updatedAt?: string;
512}): PullRequestSummary {
513 return {
514 provider: "github",
515 projectId: input.projectId,
516 repository: input.repository,
517 number: input.number,
518 title: "Pull request",
519 url: `https://example.test/${input.repository}/pull/${input.number}`,
520 state: input.state,
521 headBranch: "feature",
522 baseBranch: "main",
523 updatedAt: input.updatedAt ?? NOW,
524 };
526​
527function makeBranchPullRequest(state: "open" | "closed" | "merged") {
528 return {
529 number: 42,
530 title: "Pull request",
531 url: "https://example.test/owner/repository/pull/42",
532 baseRef: "main",
533 headRef: "feature",
534 state,
535 repositoryKey: "example.test/owner/repository",
536 updatedAt: NOW,
537 closedAt: state === "closed" ? NOW : null,
538 mergedAt: state === "merged" ? NOW : null,
539 } satisfies GitManager.GitBranchPullRequest;
541​
542interface HarnessOptions {
543 readonly snapshot: SettlementSnapshot;
544 readonly settings?: ContractServerSettings;
545 readonly branchPullRequest?: GitManager.GitManager["Service"]["branchPullRequest"];
546 readonly pullRequestSummary?: PullRequestService.PullRequestService["Service"]["summary"];
547 readonly existingWorktreePaths?: ReadonlyArray<string>;
548 readonly onDispatch?: (command: AutoSettleCommand) => Effect.Effect<void>;
549 /** Runs before each settle script start; a failure fails that start. */
550 readonly onScriptRun?: (
551 input: ProjectSetupScriptRunner.ProjectSetupScriptRunnerInput,
552 ) => Effect.Effect<void>;
553 /** Runs inside each `closeIdle` call. */
554 readonly onCloseIdle?: () => Effect.Effect<void>;
555 /** Threads `getThread` returns when a `thread.settled` event is handled. */
556 readonly currentThreads?: ReadonlyArray<OrchestrationV2AppThread>;
558​
559const makeHarness = Effect.fn("makeThreadSettlementHarness")(function* (options: HarnessOptions) {
560 const activation = yield* Deferred.make<void>();
561 const snapshots = yield* Ref.make(options.snapshot);
562 const snapshotReadCount = yield* Ref.make(0);
563 const snapshotReads = yield* Queue.unbounded<number>();
564 const candidateReads = yield* Ref.make<ReadonlyArray<string | undefined>>([]);
565 const settings = yield* Ref.make(options.settings ?? DEFAULT_SERVER_SETTINGS);
566 const settingsChanges = yield* PubSub.unbounded<ContractServerSettings>();
567 const mergedPullRequests = yield* PubSub.unbounded<PullRequestService.PullRequestMergeEvent>();
568 const commands = yield* Ref.make<ReadonlyArray<AutoSettleCommand>>([]);
569 const branchCalls = yield* Ref.make<
570 ReadonlyArray<{ readonly cwd: string; readonly branch: string }>
571 >([]);
572 const summaryCalls = yield* Ref.make<
573 ReadonlyArray<{
574 readonly projectId: ProjectId;
575 readonly repository: string;
576 readonly number: number;
577 }>
578 >([]);
579 const summaryRecovery = yield* Ref.make<ReadonlyArray<boolean | undefined>>([]);
580 const invalidatedCwds = yield* Ref.make<ReadonlyArray<string>>([]);
581 const domainEvents = yield* PubSub.unbounded<OrchestrationV2DomainEvent>();
582 const closedIdle = yield* Queue.unbounded<{ readonly threadId: string }>();
583 const scriptRuns =
584 yield* Queue.unbounded<ProjectSetupScriptRunner.ProjectSetupScriptRunnerInput>();
585​
586 const updateSettings = (patch: ServerSettingsPatch) =>
587 Effect.gen(function* () {
588 const next = applyServerSettingsPatch(yield* Ref.get(settings), patch);
589 yield* Ref.set(settings, next);
590 yield* PubSub.publish(settingsChanges, next);
591 return next;
592 });
593​
594 const branchPullRequest: GitManager.GitManager["Service"]["branchPullRequest"] = (input) =>
595 Ref.update(branchCalls, (calls) => [...calls, input]).pipe(
596 Effect.andThen(options.branchPullRequest?.(input) ?? Effect.succeed(null)),
597 );
598 const pullRequestSummary: PullRequestService.PullRequestService["Service"]["summary"] = (
599 input,
600 readOptions,
601 ) =>
602 Effect.gen(function* () {
603 yield* Ref.update(summaryCalls, (calls) => [...calls, input]);
604 yield* Ref.update(summaryRecovery, (values) => [
605 ...values,
606 readOptions?.recoverTransientFailure,
607 ]);
608 return yield* (
609 options.pullRequestSummary?.(input, readOptions) ??
610 Effect.succeed(
611 makePullRequestSummary({
612 ...input,
613 state: "open",
614 }),
615 )
616 );
617 });
618​
619 const dispatch: Orchestrator.OrchestratorV2Shape["dispatch"] = (command) => {
620 if (command.type !== "thread.auto-settle") {
621 return Effect.die(new Error(`Unexpected command: ${command.type}`));
622 }
623 return Ref.update(commands, (recorded) => [...recorded, command]).pipe(
624 Effect.andThen(options.onDispatch?.(command) ?? Effect.void),
625 Effect.as({ sequence: 1, storedEvents: [] }),
626 );
627 };
628​
629 const serverSettings = ServerSettings.ServerSettingsService.of({
630 start: Effect.void,
631 ready: Effect.void,
632 getSettings: Ref.get(settings),
633 updateSettings,
634 updateProviderInstance: () => Effect.die("Unexpected provider mutation"),
635 withSettingsSnapshot: (use) => Ref.get(settings).pipe(Effect.flatMap(use)),
636 streamChanges: Stream.fromPubSub(settingsChanges),
637 subscribeChanges: PubSub.subscribe(settingsChanges).pipe(
638 Effect.map((subscription) => Stream.fromSubscription(subscription)),
639 ),
640 });
641​
642 const layerDependencies = Layer.mergeAll(
643 Layer.mock(ProjectStore.ProjectStoreV2)({
644 listShells: () => Ref.get(snapshots).pipe(Effect.map((snapshot) => snapshot.projects)),
645 }),
646 Layer.mock(ProjectionStore.ProjectionStoreV2)({
647 getSettlementCandidates: (threadId) =>
648 Ref.update(candidateReads, (reads) => [...reads, threadId]).pipe(
649 Effect.andThen(Ref.updateAndGet(snapshotReadCount, (count) => count + 1)),
650 Effect.tap((count) => Queue.offer(snapshotReads, count)),
651 Effect.andThen(Ref.get(snapshots)),
652 Effect.map((snapshot) =>
653 threadId === undefined
654 ? snapshot.threads
655 : snapshot.threads.filter((thread) => thread.id === threadId),
656 ),
657 ),
658 getThread: (threadId) => {
659 const thread = options.currentThreads?.find((candidate) => candidate.id === threadId);
660 return thread
661 ? Effect.succeed(thread)
662 : Effect.die(new Error(`Unexpected thread read: ${threadId}`));
663 },
664 }),
665 Layer.mock(Orchestrator.OrchestratorV2)({
666 streamDomainEvents: Stream.fromPubSub(domainEvents),
667 dispatch,
668 }),
669 Layer.mock(TerminalManager.TerminalManager)({
670 closeIdle: (input) =>
671 Queue.offer(closedIdle, input).pipe(Effect.andThen(options.onCloseIdle?.() ?? Effect.void)),
672 }),
673 Layer.mock(ProjectSetupScriptRunner.ProjectSetupScriptRunner)({
674 runForThread: (input) =>
675 Queue.offer(scriptRuns, input).pipe(
676 Effect.andThen(options.onScriptRun?.(input) ?? Effect.void),
677 Effect.as({ status: "no-script" } as const),
678 ),
679 }),
680 Layer.mock(GitManager.GitManager)({
681 branchPullRequest,
682 invalidateStatus: (cwd) => Ref.update(invalidatedCwds, (cwds) => [...cwds, cwd]),
683 }),
684 Layer.mock(PullRequestService.PullRequestService)({
685 summary: pullRequestSummary,
686 subscribeMerges: PubSub.subscribe(mergedPullRequests).pipe(
687 Effect.map((subscription) => Stream.fromSubscription(subscription)),
688 ),
689 }),
690 Layer.succeed(ServerSettings.ServerSettingsService, serverSettings),
691 Layer.succeed(ServerActivation.ServerActivation, Deferred.await(activation)),
692 Layer.succeed(Crypto.Crypto, testCrypto),
693 FileSystem.layerNoop({
694 exists: (path) => Effect.succeed(options.existingWorktreePaths?.includes(path) ?? false),
695 }),
696 );
697​
698 return {
699 activation,
700 snapshots,
701 snapshotReadCount,
702 snapshotReads,
703 candidateReads,
704 commands,
705 branchCalls,
706 summaryCalls,
707 summaryRecovery,
708 invalidatedCwds,
709 closedIdle,
710 scriptRuns,
711 publishEvent: (event: OrchestrationV2DomainEvent) => PubSub.publish(domainEvents, event),
712 updateSettings,
713 publishMerge: PubSub.publish(mergedPullRequests, {
714 projectId: PROJECT_ID,
715 repository: "owner/repository",
716 number: 42,
717 mergedAt: NOW,
718 }),
719 layer: ThreadSettlementService.layer.pipe(Layer.provide(layerDependencies)),
720 };
721});
722​
723const startHarness = Effect.fn("startThreadSettlementHarness")(function* (
724 reactor: ThreadSettlementService.ThreadSettlementServiceV2["Service"],
725 activation: Deferred.Deferred<void>,
726 snapshotReads: Queue.Queue<number>,
727) {
728 yield* reactor.start();
729 yield* Deferred.succeed(activation, undefined);
730 yield* Queue.take(snapshotReads);
731 yield* reactor.drain;
732});
733​
734describe("ThreadSettlementServiceV2 worker", () => {
735 it.effect("settles a merged pull request stored only in the thread links", () =>
736 Effect.scoped(
737 Effect.gen(function* () {
738 yield* TestClock.setTime(Date.parse(NOW));
739 const thread = makeThread("merged-link", {
740 pullRequests: [
741 {
742 host: "example.test",
743 repository: "owner/repository",
744 number: 42,
745 url: "https://example.test/owner/repository/pull/42",
746 source: "manual",
747 linkedAt: "2026-08-20T00:00:00.000Z",
748 snapshot: {
749 state: "merged",
750 title: "Pull request",
751 headBranch: "feature",
752 baseBranch: "main",
753 isDraft: false,
754 updatedAt: NOW,
755 syncedAt: NOW,
756 mergedAt: NOW,
757 },
758 stack: null,
759 },
760 ],
761 });
762 const fixture = yield* makeHarness({
763 snapshot: makeSnapshot([thread]),
764 settings: { ...DEFAULT_SERVER_SETTINGS, sidebarAutoSettleAfterDays: null },
765 });
766​
767 yield* Effect.gen(function* () {
768 const service = yield* ThreadSettlementService.ThreadSettlementServiceV2;
769 yield* startHarness(service, fixture.activation, fixture.snapshotReads);
770 expect((yield* Ref.get(fixture.commands)).map((command) => command.threadId)).toEqual([
771 thread.id,
772 ]);
773 }).pipe(Effect.provide(fixture.layer));
774 }),
775 ),
776 );
777​
778 it.effect("settles only the project opted in while environment settlement is disabled", () =>
779 Effect.scoped(
780 Effect.gen(function* () {
781 yield* TestClock.setTime(Date.parse(NOW));
782 const thread = makeThread("project-opt-in", {
783 latestRunCompletedAt: DateTime.makeUnsafe("2026-08-25T00:00:00.000Z"),
784 });
785 const other = makeThread("environment-off", { projectId: ProjectId.make("other-project") });
786 const fixture = yield* makeHarness({
787 snapshot: makeSnapshot([thread, other]),
788 settings: {
789 ...DEFAULT_SERVER_SETTINGS,
790 sidebarAutoSettleAfterDays: null,
791 sidebarAutoSettleOnMerge: false,
792 projectSettingsOverrides: { [PROJECT_ID]: { sidebarAutoSettleAfterDays: 2 } },
793 },
794 });
795 yield* Effect.gen(function* () {
796 const service = yield* ThreadSettlementService.ThreadSettlementServiceV2;
797 yield* startHarness(service, fixture.activation, fixture.snapshotReads);
798 const commands = yield* Ref.get(fixture.commands);
799 expect(commands.map((command) => command.threadId)).toEqual([thread.id]);
800 }).pipe(Effect.provide(fixture.layer));
801 }),
802 ),
803 );
804​
805 it.effect("dispatches the last activity time with the v2 snapshot guard", () =>
806 Effect.scoped(
807 Effect.gen(function* () {
808 yield* TestClock.setTime(Date.parse(NOW));
809 const thread = makeThread("inactive-open-pr", {
810 branch: "feature",
811 latestRunCompletedAt: DateTime.makeUnsafe("2026-08-25T00:00:00.000Z"),
812 });
813 const fixture = yield* makeHarness({
814 snapshot: makeSnapshot([thread]),
815 settings: { ...DEFAULT_SERVER_SETTINGS, sidebarAutoSettleAfterDays: 2 },
816 branchPullRequest: () => Effect.succeed(makeBranchPullRequest("open")),
817 });
818 yield* Effect.gen(function* () {
819 const service = yield* ThreadSettlementService.ThreadSettlementServiceV2;
820 yield* startHarness(service, fixture.activation, fixture.snapshotReads);
821 const commands = yield* Ref.get(fixture.commands);
822 expect(commands).toHaveLength(1);
823 expect(commands[0]?.settledAt).toEqual(thread.latestRunCompletedAt);
824 expect(commands[0]?.snapshotAt).toEqual(thread.updatedAt);
825 }).pipe(Effect.provide(fixture.layer));
826 }),
827 ),
828 );
829​
830 it.effect("skips the branch recheck when a terminal link would settle nothing", () =>
831 Effect.scoped(
832 Effect.gen(function* () {
833 yield* TestClock.setTime(Date.parse(NOW));
834 const previous = {
835 projectId: PROJECT_ID,
836 repository: "owner/repository",
837 number: 1,
838 url: "https://example.test/owner/repository/pull/1",
839 };
840 const fixture = yield* makeHarness({
841 snapshot: makeSnapshot(
842 [
843 makeThread("resumed-manual", {
844 branch: "main",
845 linkedPullRequest: previous,
846 latestUserMessageAt: DateTime.makeUnsafe("2026-08-28T00:00:00.000Z"),
847 }),
848 ],
849 [makeProject()],
850 ),
851 settings: {
852 ...DEFAULT_SERVER_SETTINGS,
853 sidebarAutoSettleAfterDays: null,
854 sidebarAutoSettleOnMerge: true,
855 },
856 branchPullRequest: () => Effect.succeed(makeBranchPullRequest("open")),
857 pullRequestSummary: (input) =>
858 Effect.succeed({
859 ...makePullRequestSummary({ ...input, state: "merged" }),
860 mergedAt: "2026-08-27T00:00:00.000Z",
861 }),
862 });
863 yield* Effect.gen(function* () {
864 const reactor = yield* ThreadSettlementService.ThreadSettlementServiceV2;
865 yield* startHarness(reactor, fixture.activation, fixture.snapshotReads);
866 assert.deepStrictEqual(yield* Ref.get(fixture.commands), []);
867 assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, 1);
868 assert.deepStrictEqual(yield* Ref.get(fixture.branchCalls), []);
869 }).pipe(Effect.provide(fixture.layer));
870 }),
871 ),
872 );
873​
874 it.effect("reevaluates immediately after a pull request merge", () =>
875 Effect.scoped(
876 Effect.gen(function* () {
877 yield* TestClock.setTime(Date.parse(NOW));
878 const periodicLookupStarted = yield* Deferred.make<void>();
879 const releasePeriodicLookup = yield* Deferred.make<void>();
880 const mergedThreadSettled = yield* Deferred.make<void>();
881 const branchLookupCount = yield* Ref.make(0);
882 const fixture = yield* makeHarness({
883 snapshot: makeSnapshot([
884 makeThread("merged-in-app", {
885 latestUserMessageAt: DateTime.makeUnsafe("2026-08-27T00:00:00.000Z"),
886 linkedPullRequest: {
887 projectId: PROJECT_ID,
888 repository: "Owner/Repository",
889 number: 42,
890 url: "https://example.test/owner/repository/pull/42",
891 },
892 }),
893 makeThread("slow-periodic-lookup", {
894 branch: "another-feature",
895 latestUserMessageAt: DateTime.makeUnsafe("2026-08-27T00:00:00.000Z"),
896 }),
897 ]),
898 branchPullRequest: () =>
899 Ref.updateAndGet(branchLookupCount, (count) => count + 1).pipe(
900 Effect.flatMap((count) =>
901 count === 1
902 ? Effect.succeed(makeBranchPullRequest("open"))
903 : Deferred.succeed(periodicLookupStarted, undefined).pipe(
904 Effect.andThen(Deferred.await(releasePeriodicLookup)),
905 Effect.as(makeBranchPullRequest("open")),
906 ),
907 ),
908 ),
909 onDispatch: () => Deferred.succeed(mergedThreadSettled, undefined),
910 });
911​
912 yield* Effect.gen(function* () {
913 const reactor = yield* ThreadSettlementService.ThreadSettlementServiceV2;
914 yield* startHarness(reactor, fixture.activation, fixture.snapshotReads);
915 yield* fixture.updateSettings({ sidebarAutoSettleAfterDays: 4 });
916 yield* Deferred.await(periodicLookupStarted);
917​
918 yield* fixture.publishMerge;
919 yield* Deferred.await(mergedThreadSettled);
920​
921 assert.deepStrictEqual(
922 (yield* Ref.get(fixture.commands)).map((command) => command.threadId),
923 [ThreadId.make("merged-in-app")],
924 );
925 yield* Deferred.succeed(releasePeriodicLookup, undefined);
926 yield* reactor.drain;
927 }).pipe(Effect.provide(fixture.layer));
928 }),
929 ),
930 );
931​
932 it.effect(
933 "settles branch threads on a pull request merge without waiting for the next sweep",
934 () =>
935 Effect.scoped(
936 Effect.gen(function* () {
937 yield* TestClock.setTime(Date.parse(NOW));
938 const state = yield* Ref.make<"open" | "merged">("open");
939 const mergedThreadSettled = yield* Deferred.make<void>();
940 const fixture = yield* makeHarness({
941 snapshot: makeSnapshot([
942 makeThread("branch-thread", {
943 branch: "saved-feature",
944 latestUserMessageAt: DateTime.makeUnsafe("2026-08-27T00:00:00.000Z"),
945 }),
946 ]),
947 branchPullRequest: () => Ref.get(state).pipe(Effect.map(makeBranchPullRequest)),
948 onDispatch: () => Deferred.succeed(mergedThreadSettled, undefined),
949 });
950​
951 yield* Effect.gen(function* () {
952 const reactor = yield* ThreadSettlementService.ThreadSettlementServiceV2;
953 yield* startHarness(reactor, fixture.activation, fixture.snapshotReads);
954 assert.deepStrictEqual(yield* Ref.get(fixture.commands), []);
955 assert.deepStrictEqual(yield* Ref.get(fixture.invalidatedCwds), []);
956​
957 yield* Ref.set(state, "merged");
958 yield* fixture.publishMerge;
959 yield* Deferred.await(mergedThreadSettled);
960​
961 assert.deepStrictEqual(
962 (yield* Ref.get(fixture.commands)).map((command) => command.threadId),
963 [ThreadId.make("branch-thread")],
964 );
965 assert.deepStrictEqual(yield* Ref.get(fixture.invalidatedCwds), ["/workspace/project"]);
966 yield* reactor.drain;
967 }).pipe(Effect.provide(fixture.layer));
968 }),
969 ),
970 );
971​
972 it.effect("a merge does not settle threads linked to an unrelated pull request", () =>
973 Effect.scoped(
974 Effect.gen(function* () {
975 yield* TestClock.setTime(Date.parse(NOW));
976 const mergedThreadSettled = yield* Deferred.make<void>();
977 const mergeLookupStarted = yield* Deferred.make<void>();
978 const releaseMergeLookup = yield* Deferred.make<void>();
979 const lookupCount = yield* Ref.make(0);
980 const fixture = yield* makeHarness({
981 snapshot: makeSnapshot([
982 makeThread("merged-in-app", {
983 latestUserMessageAt: DateTime.makeUnsafe("2026-08-27T00:00:00.000Z"),
984 linkedPullRequest: {
985 projectId: PROJECT_ID,
986 repository: "owner/repository",
987 number: 42,
988 url: "https://example.test/owner/repository/pull/42",
989 },
990 }),
991 makeThread("unrelated-linked", {
992 latestUserMessageAt: DateTime.makeUnsafe("2026-08-27T00:00:00.000Z"),
993 linkedPullRequest: {
994 projectId: PROJECT_ID,
995 repository: "owner/repository",
996 number: 99,
997 url: "https://example.test/owner/repository/pull/99",
998 },
999 }),
1000 ]),
1001 pullRequestSummary: (input) =>
1002 Ref.updateAndGet(lookupCount, (count) => count + 1).pipe(
1003 // The initial sweep looks up both linked threads; the merge
1004 // sweep only looks up the unrelated one, since the merged
1005 // thread settles from the event itself.
1006 Effect.tap((count) =>
1007 count === 3 ? Deferred.succeed(mergeLookupStarted, undefined) : Effect.void,
1008 ),
1009 Effect.tap((count) =>
1010 count === 3 ? Deferred.await(releaseMergeLookup) : Effect.void,
1011 ),
1012 Effect.map(() => makePullRequestSummary({ ...input, state: "open" })),
1013 ),
1014 onDispatch: () => Deferred.succeed(mergedThreadSettled, undefined),
1015 });
1016​
1017 yield* Effect.gen(function* () {
1018 const reactor = yield* ThreadSettlementService.ThreadSettlementServiceV2;
1019 yield* startHarness(reactor, fixture.activation, fixture.snapshotReads);
1020 assert.deepStrictEqual(yield* Ref.get(fixture.commands), []);
1021​
1022 yield* fixture.publishMerge;
1023 yield* Deferred.await(mergeLookupStarted);
1024 yield* Deferred.await(mergedThreadSettled);
1025 yield* Deferred.succeed(releaseMergeLookup, undefined);
1026 yield* reactor.drain;
1027​
1028 assert.deepStrictEqual(
1029 (yield* Ref.get(fixture.commands)).map((command) => command.threadId),
1030 [ThreadId.make("merged-in-app")],
1031 );
1032 assert.deepStrictEqual(
1033 (yield* Ref.get(fixture.summaryCalls))
1034 .map((call) => call.number)
1035 .toSorted((left, right) => left - right),
1036 [42, 99, 99],
1037 );
1038 }).pipe(Effect.provide(fixture.layer));
1039 }),
1040 ),
1041 );
1042​
1043 it.effect("looks up the branch pull request from a thread's live worktree", () =>
1044 Effect.scoped(
1045 Effect.gen(function* () {
1046 yield* TestClock.setTime(Date.parse(NOW));
1047 const fixture = yield* makeHarness({
1048 snapshot: makeSnapshot(
1050 makeThread("live-worktree", {
1051 branch: "feature/live",
1052 worktreePath: "/workspace/project-root/.worktrees/live",
1053 }),
1054 makeThread("deleted-worktree", {
1055 branch: "feature/deleted",
1056 worktreePath: "/workspace/project-root/.worktrees/deleted",
1057 }),
1058 ],
1059 [makeProject(PROJECT_ID, "/workspace/project-root")],
1060 ),
1061 existingWorktreePaths: ["/workspace/project-root/.worktrees/live"],
1062 settings: {
1063 ...DEFAULT_SERVER_SETTINGS,
1064 sidebarAutoSettleAfterDays: null,
1065 sidebarAutoSettleOnMerge: true,
1066 },
1067 });
1068​
1069 yield* Effect.gen(function* () {
1070 const reactor = yield* ThreadSettlementService.ThreadSettlementServiceV2;
1071 yield* startHarness(reactor, fixture.activation, fixture.snapshotReads);
1072​
1073 assert.deepStrictEqual(
1074 new Set(yield* Ref.get(fixture.branchCalls)),
1075 new Set([
1076 { cwd: "/workspace/project-root/.worktrees/live", branch: "feature/live" },
1077 { cwd: "/workspace/project-root", branch: "feature/deleted" },
1078 ]),
1079 );
1080 }).pipe(Effect.provide(fixture.layer));
1081 }),
1082 ),
1083 );
1084});
1085​
1086describe("ThreadSettlementServiceV2 terminals", () => {
1087 const appThread = (
1088 id: string,
1089 settledOverride: OrchestrationV2AppThread["settledOverride"],
1090 worktreePath: string | null = null,
1091 ): OrchestrationV2AppThread => {
1092 const threadId = ThreadId.make(id);
1093 return {
1094 createdBy: "user",
1095 creationSource: "web",
1096 id: threadId,
1097 projectId: PROJECT_ID,
1098 title: id,
1099 providerInstanceId: ProviderInstanceId.make("codex"),
1100 modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5" },
1101 runtimeMode: "full-access",
1102 interactionMode: "default",
1103 branch: null,
1104 worktreePath,
1105 activeProviderThreadId: null,
1106 lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId },
1107 forkedFrom: null,
1108 createdAt: DateTime.makeUnsafe(NOW),
1109 updatedAt: DateTime.makeUnsafe(NOW),
1110 archivedAt: null,
1111 settledOverride,
1112 settledAt: settledOverride === "settled" ? DateTime.makeUnsafe(NOW) : null,
1113 lastVisitedAt: null,
1114 deletedAt: null,
1115 };
1116 };
1117 const settledEvent = (thread: OrchestrationV2AppThread): OrchestrationV2DomainEvent => ({
1118 type: "thread.settled",
1119 id: EventId.make(`event:settled:${thread.id}`),
1120 threadId: thread.id,
1121 occurredAt: DateTime.makeUnsafe(NOW),
1122 payload: thread,
1123 });
1124​
1125 it.effect("closes the thread's idle terminals when it settles", () =>
1126 Effect.scoped(
1127 Effect.gen(function* () {
1128 const thread = appThread("settled-thread", "settled");
1129 const fixture = yield* makeHarness({
1130 snapshot: makeSnapshot([]),
1131 currentThreads: [thread],
1132 });
1133​
1134 yield* Effect.gen(function* () {
1135 const service = yield* ThreadSettlementService.ThreadSettlementServiceV2;
1136 yield* startHarness(service, fixture.activation, fixture.snapshotReads);
1137 yield* fixture.publishEvent(settledEvent(thread));
1138 assert.deepStrictEqual(yield* Queue.take(fixture.closedIdle), { threadId: thread.id });
1139 }).pipe(Effect.provide(fixture.layer));
1140 }),
1141 ),
1142 );
1143​
1144 it.effect("keeps the terminals of a thread re-engaged before the event ran", () =>
1145 Effect.scoped(
1146 Effect.gen(function* () {
1147 const settled = appThread("reengaged-thread", "settled");
1148 const reengaged = appThread("reengaged-thread", "active");
1149 const marker = appThread("marker-thread", "settled");
1150 const fixture = yield* makeHarness({
1151 snapshot: makeSnapshot([]),
1152 currentThreads: [reengaged, marker],
1153 });
1154​
1155 yield* Effect.gen(function* () {
1156 const service = yield* ThreadSettlementService.ThreadSettlementServiceV2;
1157 yield* startHarness(service, fixture.activation, fixture.snapshotReads);
1158 yield* fixture.publishEvent(settledEvent(settled));
1159 // Events run in order, so the first close belongs to the later
1160 // event only if the re-engaged thread was skipped.
1161 yield* fixture.publishEvent(settledEvent(marker));
1162 assert.deepStrictEqual(yield* Queue.take(fixture.closedIdle), { threadId: marker.id });
1163 }).pipe(Effect.provide(fixture.layer));
1164 }),
1165 ),
1166 );
1167​
1168 it.effect("runs the settle script in the thread's own worktree", () =>
1169 Effect.scoped(
1170 Effect.gen(function* () {
1171 const shared = appThread("shared-checkout-thread", "settled");
1172 const missing = appThread("removed-worktree-thread", "settled", "/worktrees/removed");
1173 const worktree = appThread("worktree-thread", "settled", "/worktrees/thread");
1174 const fixture = yield* makeHarness({
1175 snapshot: makeSnapshot([]),
1176 currentThreads: [shared, missing, worktree],
1177 existingWorktreePaths: ["/worktrees/thread"],
1178 });
1179​
1180 yield* Effect.gen(function* () {
1181 const service = yield* ThreadSettlementService.ThreadSettlementServiceV2;
1182 yield* startHarness(service, fixture.activation, fixture.snapshotReads);
1183 // Events run in order, so the first run belongs to the last event
1184 // only if the shared checkout and the removed worktree were skipped.
1185 yield* fixture.publishEvent(settledEvent(shared));
1186 yield* fixture.publishEvent(settledEvent(missing));
1187 yield* fixture.publishEvent(settledEvent(worktree));
1188 const run = yield* Queue.take(fixture.scriptRuns);
1189 assert.strictEqual(run.threadId, worktree.id);
1190 assert.strictEqual(run.worktreePath, "/worktrees/thread");
1191 assert.strictEqual(run.trigger, "settle");
1192 }).pipe(Effect.provide(fixture.layer));
1193 }),
1194 ),
1195 );
1196​
1197 it.effect("skips the settle script for a thread re-engaged while its shells close", () =>
1198 Effect.scoped(
1199 Effect.gen(function* () {
1200 const settled = appThread("reengaging-thread", "settled", "/worktrees/reengaging");
1201 const marker = appThread("marker-thread", "settled", "/worktrees/marker");
1202 const currentThreads = [settled, marker];
1203 const fixture = yield* makeHarness({
1204 snapshot: makeSnapshot([]),
1205 currentThreads,
1206 existingWorktreePaths: ["/worktrees/reengaging", "/worktrees/marker"],
1207 // The user sends a message while the first close checks processes.
1208 onCloseIdle: () =>
1209 Effect.sync(() => {
1210 currentThreads[0] = { ...settled, settledOverride: "active" };
1211 }),
1212 });
1213​
1214 yield* Effect.gen(function* () {
1215 const service = yield* ThreadSettlementService.ThreadSettlementServiceV2;
1216 yield* startHarness(service, fixture.activation, fixture.snapshotReads);
1217 yield* fixture.publishEvent(settledEvent(settled));
1218 yield* fixture.publishEvent(settledEvent(marker));
1219 assert.strictEqual((yield* Queue.take(fixture.scriptRuns)).threadId, marker.id);
1220 }).pipe(Effect.provide(fixture.layer));
1221 }),
1222 ),
1223 );
1224​
1225 it.effect("runs the settle script once when a settlement is re-emitted", () =>
1226 Effect.scoped(
1227 Effect.gen(function* () {
1228 const repeated = appThread("repeated-thread", "settled", "/worktrees/repeated");
1229 const marker = appThread("marker-thread", "settled", "/worktrees/marker");
1230 const fixture = yield* makeHarness({
1231 snapshot: makeSnapshot([]),
1232 currentThreads: [repeated, marker],
1233 existingWorktreePaths: ["/worktrees/repeated", "/worktrees/marker"],
1234 });
1235​
1236 yield* Effect.gen(function* () {
1237 const service = yield* ThreadSettlementService.ThreadSettlementServiceV2;
1238 yield* startHarness(service, fixture.activation, fixture.snapshotReads);
1239 // Settling an already settled thread emits the same settlement again.
1240 yield* fixture.publishEvent(settledEvent(repeated));
1241 yield* fixture.publishEvent(settledEvent(repeated));
1242 yield* fixture.publishEvent(settledEvent(marker));
1243 assert.strictEqual((yield* Queue.take(fixture.scriptRuns)).threadId, repeated.id);
1244 assert.strictEqual((yield* Queue.take(fixture.scriptRuns)).threadId, marker.id);
1245 }).pipe(Effect.provide(fixture.layer));
1246 }),
1247 ),
1248 );
1249​
1250 it.effect("retries the settle script on a re-emitted settlement after a failed start", () =>
1251 Effect.scoped(
1252 Effect.gen(function* () {
1253 const thread = appThread("failed-start-thread", "settled", "/worktrees/failed-start");
1254 const starts = yield* Ref.make(0);
1255 const fixture = yield* makeHarness({
1256 snapshot: makeSnapshot([]),
1257 currentThreads: [thread],
1258 existingWorktreePaths: ["/worktrees/failed-start"],
1259 onScriptRun: () =>
1260 Ref.updateAndGet(starts, (count) => count + 1).pipe(
1261 Effect.flatMap((count) =>
1262 count === 1 ? Effect.die(new Error("terminal failed to open")) : Effect.void,
1263 ),
1264 ),
1265 });
1266​
1267 yield* Effect.gen(function* () {
1268 const service = yield* ThreadSettlementService.ThreadSettlementServiceV2;
1269 yield* startHarness(service, fixture.activation, fixture.snapshotReads);
1270 yield* fixture.publishEvent(settledEvent(thread));
1271 yield* fixture.publishEvent(settledEvent(thread));
1272 assert.strictEqual((yield* Queue.take(fixture.scriptRuns)).threadId, thread.id);
1273 assert.strictEqual((yield* Queue.take(fixture.scriptRuns)).threadId, thread.id);
1274 }).pipe(Effect.provide(fixture.layer));
1275 }),
1276 ),
1277 );
1278});
1279​
1280describe("ThreadSettlementServiceV2 single-thread sweeps", () => {
1281 it.effect("a finished run reads only its own thread's settlement candidate", () =>
1282 Effect.scoped(
1283 Effect.gen(function* () {
1284 yield* TestClock.setTime(Date.parse(NOW));
1285 const finished = makeThread("finished-run");
1286 const other = makeThread("other-thread");
1287 const fixture = yield* makeHarness({
1288 snapshot: makeSnapshot([finished, other]),
1289 settings: { ...DEFAULT_SERVER_SETTINGS, sidebarAutoSettleAfterDays: 3 },
1290 });
1291​
1292 yield* Effect.gen(function* () {
1293 const service = yield* ThreadSettlementService.ThreadSettlementServiceV2;
1294 yield* startHarness(service, fixture.activation, fixture.snapshotReads);
1295 yield* Ref.set(fixture.candidateReads, []);
1296 yield* fixture.publishEvent({
1297 type: "provider-session.detached",
1298 id: EventId.make("event:detached"),
1299 threadId: finished.id,
1300 occurredAt: DateTime.makeUnsafe(NOW),
1301 payload: {
1302 providerSessionId: ProviderSessionId.make("provider-session:finished"),
1303 detachedAt: DateTime.makeUnsafe(NOW),
1304 },
1305 });
1306 yield* Queue.take(fixture.snapshotReads);
1307 yield* service.drain;
1308 assert.deepStrictEqual(yield* Ref.get(fixture.candidateReads), [finished.id]);
1309 }).pipe(Effect.provide(fixture.layer));
1310 }),
1311 ),
1312 );
1313});
1314​
1315describe("isSnoozed", () => {
1316 const snoozed = { snoozedAt: at(-2 * DAY_MS), snoozedUntil: at(DAY_MS) };
1317 it("wakes for completed work after the snooze, but not an interrupted run", () => {
1318 expect(ThreadSettlementService.isSnoozed(shell(snoozed), NOW_MS)).toBe(true);
1319 expect(
1320 ThreadSettlementService.isSnoozed(
1321 shell({ ...snoozed, status: "interrupted", latestRunCompletedAt: at(-DAY_MS) }),
1322 NOW_MS,
1323 ),
1324 ).toBe(true);
1325 expect(
1326 ThreadSettlementService.isSnoozed(
1327 shell({ ...snoozed, status: "completed", latestRunCompletedAt: at(-DAY_MS) }),
1328 NOW_MS,
1329 ),
1330 ).toBe(false);
1331 expect(
1332 ThreadSettlementService.isSnoozed(shell({ ...snoozed, snoozedUntil: at(-1) }), NOW_MS),
1333 ).toBe(false);
1334 });
1335});