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