Open History to see the last commit
1import * as NodeServices from "@effect/platform-node/NodeServices";
2import {
3 ProjectId,
4 ThreadId,
5 TurnId,
6 ProviderDriverKind,
7 ProviderInstanceId,
8 type ProviderSession,
9} from "@t3tools/contracts";
10import * as Clock from "effect/Clock";
11import * as DateTime from "effect/DateTime";
12import * as Effect from "effect/Effect";
13import * as Exit from "effect/Exit";
14import * as Layer from "effect/Layer";
15import * as ManagedRuntime from "effect/ManagedRuntime";
16import * as Option from "effect/Option";
17import * as Scope from "effect/Scope";
18import * as Stream from "effect/Stream";
19import { afterEach, describe, expect, it, vi } from "vite-plus/test";
20
21import { ProjectionSnapshotQuery } from "../../orchestration/Services/ProjectionSnapshotQuery.ts";
22import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts";
23import * as ProviderSessionRuntime from "../../persistence/ProviderSessionRuntime.ts";
24import { ProviderValidationError } from "../Errors.ts";
25import { ProviderSessionReaper } from "../Services/ProviderSessionReaper.ts";
26import { ProviderService, type ProviderServiceShape } from "../Services/ProviderService.ts";
27import { ProviderSessionDirectoryLive } from "./ProviderSessionDirectory.ts";
28import { makeProviderSessionReaperLive } from "./ProviderSessionReaper.ts";
29
30const defaultModelSelection = {
31 instanceId: ProviderInstanceId.make("codex"),
32 model: "gpt-5-codex",
33} as const;
34
35async function waitFor(
36 predicate: () => boolean | Promise<boolean>,
37 timeoutMs = 2_000,
38): Promise<void> {
39 const deadline = (await Effect.runPromise(Clock.currentTimeMillis)) + timeoutMs;
40 const poll = async (): Promise<void> => {
41 if (await predicate()) {
42 return;
43 }
44 if ((await Effect.runPromise(Clock.currentTimeMillis)) >= deadline) {
45 throw new Error("Timed out waiting for expectation.");
46 }
47 await Effect.runPromise(Effect.yieldNow);
48 return poll();
49 };
50
51 return poll();
52}
53
54const drainFibers = Effect.forEach(Array.from({ length: 10 }), () => Effect.yieldNow, {
55 discard: true,
56});
57
58const unsupported = () => Effect.die(new Error("Unsupported provider call in test")) as never;
59
60function makeReadModel(
61 threads: ReadonlyArray<{
62 readonly id: ThreadId;
63 readonly session: {
64 readonly threadId: ThreadId;
65 readonly status: "starting" | "running" | "ready" | "interrupted" | "stopped" | "error";
66 readonly providerName: "codex" | "claudeAgent";
67 readonly runtimeMode: "approval-required" | "full-access" | "auto-accept-edits";
68 readonly activeTurnId: TurnId | null;
69 readonly lastError: string | null;
70 readonly updatedAt: string;
71 } | null;
72 readonly backgroundLiveness?: "working" | "monitoring" | null;
73 }>,
74) {
75 const now = "2026-01-01T00:00:00.000Z";
76 const projectId = ProjectId.make("project-provider-session-reaper");
77
78 return {
79 snapshotSequence: 0,
80 updatedAt: now,
81 projects: [
82 {
83 id: projectId,
84 title: "Provider Reaper Project",
85 workspaceRoot: "/tmp/provider-reaper-project",
86 defaultModelSelection,
87 scripts: [],
88 createdAt: now,
89 updatedAt: now,
90 deletedAt: null,
91 },
92 ],
93 threads: threads.map((thread) => ({
94 id: thread.id,
95 projectId,
96 title: `Thread ${thread.id}`,
97 modelSelection: defaultModelSelection,
98 interactionMode: "default" as const,
99 runtimeMode: "full-access" as const,
100 branch: null,
101 worktreePath: null,
102 createdAt: now,
103 updatedAt: now,
104 archivedAt: null,
105 settledOverride: null,
106 settledAt: null,
107 latestUserMessageAt: null,
108 hasPendingApprovals: false,
109 hasPendingUserInput: false,
110 hasActionableProposedPlan: false,
111 latestTurn: null,
112 messages: [],
113 session: thread.session,
114 backgroundLiveness: thread.backgroundLiveness ?? null,
115 activities: [],
116 proposedPlans: [],
117 checkpoints: [],
118 deletedAt: null,
119 })),
120 };
121}
122
123describe("ProviderSessionReaper", () => {
124 let runtime: ManagedRuntime.ManagedRuntime<
125 ProviderSessionReaper | ProviderSessionRuntime.ProviderSessionRuntimeRepository,
126 unknown
127 > | null = null;
128 let scope: Scope.Closeable | null = null;
129
130 afterEach(async () => {
131 if (scope) {
132 await Effect.runPromise(Scope.close(scope, Exit.void));
133 }
134 scope = null;
135 if (runtime) {
136 await runtime.dispose();
137 }
138 runtime = null;
139 });
140
141 // Shared start sequence so each test adds no manual Effect runners
142 // (no-manual-effect-runtime-in-tests tracks this file's legacy count).
143 async function startReaper() {
144 const reaper = await runtime!.runPromise(Effect.service(ProviderSessionReaper));
145 scope = await Effect.runPromise(Scope.make("sequential"));
146 await Effect.runPromise(reaper.start().pipe(Scope.provide(scope)));
147 }
148
149 async function createHarness(input: {
150 readonly readModel: ReturnType<typeof makeReadModel>;
151 readonly activeSessions?: ReadonlyArray<ProviderSession>;
152 readonly stopSessionImplementation?: (input: {
153 readonly threadId: ThreadId;
154 }) => ReturnType<ProviderServiceShape["stopSession"]>;
155 }) {
156 const stoppedThreadIds = new Set<ThreadId>();
157 const stopSession = vi.fn<ProviderServiceShape["stopSession"]>(
158 (request) =>
159 (input.stopSessionImplementation
160 ? input.stopSessionImplementation(request)
161 : Effect.sync(() => {
162 stoppedThreadIds.add(request.threadId);
163 })) as ReturnType<ProviderServiceShape["stopSession"]>,
164 );
165
166 const providerService: ProviderServiceShape = {
167 startSession: () => unsupported(),
168 sendTurn: () => unsupported(),
169 compactThread: () => unsupported(),
170 interruptTurn: () => unsupported(),
171 respondToRequest: () => unsupported(),
172 respondToUserInput: () => unsupported(),
173 stopSession,
174 listSessions: () => Effect.succeed(input.activeSessions ?? []),
175 getCapabilities: () => Effect.succeed({ sessionModelSwitch: "in-session" }),
176 assertConversationRollbackSupported: () => unsupported(),
177 getInstanceInfo: (instanceId) => {
178 const driverKind = ProviderDriverKind.make(String(instanceId));
179 return Effect.succeed({
180 instanceId,
181 driverKind,
182 displayName: undefined,
183 enabled: true,
184 continuationIdentity: {
185 driverKind,
186 continuationKey: `${driverKind}:instance:${instanceId}`,
187 },
188 });
189 },
190 rollbackConversation: () => unsupported(),
191 uploadFeedback: () => unsupported(),
192 streamEvents: Stream.empty,
193 };
194
195 const runtimeRepositoryLayer = ProviderSessionRuntime.layer.pipe(
196 Layer.provide(SqlitePersistenceMemory),
197 );
198 const providerSessionDirectoryLayer = ProviderSessionDirectoryLive.pipe(
199 Layer.provide(runtimeRepositoryLayer),
200 );
201 const layer = makeProviderSessionReaperLive({
202 inactivityThresholdMs: 1_000,
203 sweepIntervalMs: 60_000,
204 }).pipe(
205 Layer.provideMerge(providerSessionDirectoryLayer),
206 Layer.provideMerge(runtimeRepositoryLayer),
207 Layer.provideMerge(Layer.succeed(ProviderService, providerService)),
208 Layer.provideMerge(
209 Layer.succeed(ProjectionSnapshotQuery, {
210 getUserInputActivity: () => Effect.die("unused"),
211 getCommandReadModel: () => Effect.die("unused"),
212 getSnapshot: () => Effect.die("unused"),
213 getShellSnapshot: () => Effect.die("unused"),
214 getArchivedShellSnapshot: () => Effect.die("unused"),
215 getSnapshotSequence: () =>
216 Effect.succeed({ snapshotSequence: input.readModel.snapshotSequence }),
217 getCounts: () => Effect.die("unused"),
218 getEventReplayStats: () => Effect.die("unused"),
219 getActiveProjectByWorkspaceRoot: () => Effect.die("unused"),
220 getProjectShellById: () => Effect.die("unused"),
221 getFirstActiveThreadIdByProjectId: () => Effect.die("unused"),
222 getThreadCheckpointContext: () => Effect.die("unused"),
223 getFullThreadDiffContext: () => Effect.die("unused"),
224 getThreadShellById: (threadId) =>
225 Effect.succeed(
226 input.readModel.threads.find((thread) => thread.id === threadId)
227 ? Option.some(input.readModel.threads.find((thread) => thread.id === threadId)!)
228 : Option.none(),
229 ),
230 getThreadDetailById: () => Effect.die("unused"),
231 getThreadDetailSnapshot: () => Effect.die("unused"),
232 searchThreads: () => Effect.succeed({ matches: [] }),
233 }),
234 ),
235 Layer.provideMerge(NodeServices.layer),
236 );
237
238 runtime = ManagedRuntime.make(layer);
239 return { stopSession, stoppedThreadIds };
240 }
241
242 it("reaps stale persisted sessions without active turns", async () => {
243 const threadId = ThreadId.make("thread-reaper-stale");
244 const now = "2026-01-01T00:00:00.000Z";
245 const harness = await createHarness({
246 readModel: makeReadModel([
247 {
248 id: threadId,
249 session: {
250 threadId,
251 status: "ready",
252 providerName: "codex",
253 runtimeMode: "full-access",
254 activeTurnId: null,
255 lastError: null,
256 updatedAt: now,
257 },
258 },
259 ]),
260 });
261 const repository = await runtime!.runPromise(
262 Effect.service(ProviderSessionRuntime.ProviderSessionRuntimeRepository),
263 );
264
265 await runtime!.runPromise(
266 repository.upsert({
267 threadId,
268 providerName: "codex",
269 providerInstanceId: null,
270 adapterKey: "codex",
271 runtimeMode: "full-access",
272 status: "running",
273 lastSeenAt: "2026-04-14T00:00:00.000Z",
274 resumeCursor: {
275 opaque: "resume-stale",
276 },
277 runtimePayload: null,
278 }),
279 );
280
281 await startReaper();
282
283 await waitFor(() => harness.stopSession.mock.calls.length === 1);
284
285 expect(harness.stopSession.mock.calls[0]?.[0]).toEqual({ threadId });
286 expect(harness.stoppedThreadIds.has(threadId)).toBe(true);
287 });
288
289 it.each(["ready", "error"] as const)(
290 "keeps stale %s Claude sessions alive for cross-session messaging",
291 async (status) => {
292 const threadId = ThreadId.make(`thread-reaper-claude-messaging-${status}`);
293 const now = "2026-01-01T00:00:00.000Z";
294 const harness = await createHarness({
295 activeSessions: [
296 {
297 threadId,
298 provider: ProviderDriverKind.make("claudeAgent"),
299 status: "ready",
300 runtimeMode: "full-access",
301 createdAt: now,
302 updatedAt: now,
303 },
304 ],
305 readModel: makeReadModel([
306 {
307 id: threadId,
308 session: {
309 threadId,
310 status,
311 providerName: "claudeAgent",
312 runtimeMode: "full-access",
313 activeTurnId: null,
314 lastError: null,
315 updatedAt: now,
316 },
317 },
318 ]),
319 });
320 const repository = await runtime!.runPromise(
321 Effect.service(ProviderSessionRuntime.ProviderSessionRuntimeRepository),
322 );
323
324 await runtime!.runPromise(
325 repository.upsert({
326 threadId,
327 providerName: "claudeAgent",
328 providerInstanceId: null,
329 adapterKey: "claudeAgent",
330 runtimeMode: "full-access",
331 status: "running",
332 lastSeenAt: "2026-04-14T00:00:00.000Z",
333 resumeCursor: {
334 opaque: "resume-claude-messaging",
335 },
336 runtimePayload: null,
337 }),
338 );
339
340 await startReaper();
341 await runtime!.runPromise(drainFibers);
342
343 expect(harness.stopSession).not.toHaveBeenCalled();
344 const remaining = await runtime!.runPromise(repository.getByThreadId({ threadId }));
345 expect(Option.isSome(remaining)).toBe(true);
346 },
347 );
348
349 it("skips stale sessions when the thread still has an active turn", async () => {
350 const threadId = ThreadId.make("thread-reaper-active-turn");
351 const turnId = TurnId.make("turn-reaper-active");
352 const now = "2026-01-01T00:00:00.000Z";
353 const harness = await createHarness({
354 readModel: makeReadModel([
355 {
356 id: threadId,
357 session: {
358 threadId,
359 status: "running",
360 providerName: "claudeAgent",
361 runtimeMode: "full-access",
362 activeTurnId: turnId,
363 lastError: null,
364 updatedAt: now,
365 },
366 },
367 ]),
368 });
369 const repository = await runtime!.runPromise(
370 Effect.service(ProviderSessionRuntime.ProviderSessionRuntimeRepository),
371 );
372
373 await runtime!.runPromise(
374 repository.upsert({
375 threadId,
376 providerName: "claudeAgent",
377 providerInstanceId: null,
378 adapterKey: "claudeAgent",
379 runtimeMode: "full-access",
380 status: "running",
381 lastSeenAt: "2026-04-14T00:00:00.000Z",
382 resumeCursor: {
383 opaque: "resume-active-turn",
384 },
385 runtimePayload: null,
386 }),
387 );
388
389 await startReaper();
390 await Effect.runPromise(drainFibers);
391
392 expect(harness.stopSession).not.toHaveBeenCalled();
393 const remaining = await runtime!.runPromise(repository.getByThreadId({ threadId }));
394 expect(Option.isSome(remaining)).toBe(true);
395 });
396
397 it("skips stale sessions while background work is still live", async () => {
398 const threadId = ThreadId.make("thread-reaper-background-work");
399 const now = "2026-01-01T00:00:00.000Z";
400 const harness = await createHarness({
401 readModel: makeReadModel([
402 {
403 id: threadId,
404 session: {
405 threadId,
406 status: "ready",
407 providerName: "claudeAgent",
408 runtimeMode: "full-access",
409 activeTurnId: null,
410 lastError: null,
411 updatedAt: now,
412 },
413 backgroundLiveness: "working",
414 },
415 ]),
416 });
417 const repository = await runtime!.runPromise(
418 Effect.service(ProviderSessionRuntime.ProviderSessionRuntimeRepository),
419 );
420
421 await runtime!.runPromise(
422 repository.upsert({
423 threadId,
424 providerName: "claudeAgent",
425 providerInstanceId: null,
426 adapterKey: "claudeAgent",
427 runtimeMode: "full-access",
428 status: "running",
429 lastSeenAt: "2026-04-14T00:00:00.000Z",
430 resumeCursor: {
431 opaque: "resume-background-work",
432 },
433 runtimePayload: null,
434 }),
435 );
436
437 await startReaper();
438 await Effect.runPromise(drainFibers);
439
440 expect(harness.stopSession).not.toHaveBeenCalled();
441 const remaining = await runtime!.runPromise(repository.getByThreadId({ threadId }));
442 expect(Option.isSome(remaining)).toBe(true);
443 });
444
445 it("does not reap sessions that are still within the inactivity threshold", async () => {
446 const threadId = ThreadId.make("thread-reaper-fresh");
447 const now = DateTime.formatIso(await Effect.runPromise(DateTime.now));
448 const harness = await createHarness({
449 readModel: makeReadModel([
450 {
451 id: threadId,
452 session: {
453 threadId,
454 status: "ready",
455 providerName: "claudeAgent",
456 runtimeMode: "full-access",
457 activeTurnId: null,
458 lastError: null,
459 updatedAt: now,
460 },
461 },
462 ]),
463 });
464 const repository = await runtime!.runPromise(
465 Effect.service(ProviderSessionRuntime.ProviderSessionRuntimeRepository),
466 );
467
468 await runtime!.runPromise(
469 repository.upsert({
470 threadId,
471 providerName: "claudeAgent",
472 providerInstanceId: null,
473 adapterKey: "claudeAgent",
474 runtimeMode: "full-access",
475 status: "running",
476 lastSeenAt: now,
477 resumeCursor: {
478 opaque: "resume-fresh",
479 },
480 runtimePayload: null,
481 }),
482 );
483
484 await startReaper();
485 await Effect.runPromise(drainFibers);
486
487 expect(harness.stopSession).not.toHaveBeenCalled();
488 const remaining = await runtime!.runPromise(repository.getByThreadId({ threadId }));
489 expect(Option.isSome(remaining)).toBe(true);
490 });
491
492 it("skips persisted sessions that are already marked stopped", async () => {
493 const threadId = ThreadId.make("thread-reaper-stopped");
494 const now = "2026-01-01T00:00:00.000Z";
495 const harness = await createHarness({
496 readModel: makeReadModel([
497 {
498 id: threadId,
499 session: {
500 threadId,
501 status: "stopped",
502 providerName: "claudeAgent",
503 runtimeMode: "full-access",
504 activeTurnId: null,
505 lastError: null,
506 updatedAt: now,
507 },
508 },
509 ]),
510 });
511 const repository = await runtime!.runPromise(
512 Effect.service(ProviderSessionRuntime.ProviderSessionRuntimeRepository),
513 );
514
515 await runtime!.runPromise(
516 repository.upsert({
517 threadId,
518 providerName: "claudeAgent",
519 providerInstanceId: null,
520 adapterKey: "claudeAgent",
521 runtimeMode: "full-access",
522 status: "stopped",
523 lastSeenAt: "2026-04-14T00:00:00.000Z",
524 resumeCursor: {
525 opaque: "resume-stopped",
526 },
527 runtimePayload: null,
528 }),
529 );
530
531 await startReaper();
532 await Effect.runPromise(drainFibers);
533
534 expect(harness.stopSession).not.toHaveBeenCalled();
535 const remaining = await runtime!.runPromise(repository.getByThreadId({ threadId }));
536 expect(Option.isSome(remaining)).toBe(true);
537 });
538
539 it("continues reaping other sessions when one stop attempt fails", async () => {
540 const failedThreadId = ThreadId.make("thread-reaper-stop-failure");
541 const reapedThreadId = ThreadId.make("thread-reaper-stop-success");
542 const now = "2026-01-01T00:00:00.000Z";
543 const harness = await createHarness({
544 readModel: makeReadModel([
545 {
546 id: failedThreadId,
547 session: {
548 threadId: failedThreadId,
549 status: "error",
550 providerName: "claudeAgent",
551 runtimeMode: "full-access",
552 activeTurnId: null,
553 lastError: null,
554 updatedAt: now,
555 },
556 },
557 {
558 id: reapedThreadId,
559 session: {
560 threadId: reapedThreadId,
561 status: "ready",
562 providerName: "codex",
563 runtimeMode: "full-access",
564 activeTurnId: null,
565 lastError: null,
566 updatedAt: now,
567 },
568 },
569 ]),
570 stopSessionImplementation: (request) =>
571 request.threadId === failedThreadId
572 ? Effect.fail(
573 new ProviderValidationError({
574 operation: "ProviderSessionReaper.test",
575 issue: "simulated stop failure",
576 }),
577 )
578 : Effect.void,
579 });
580 const repository = await runtime!.runPromise(
581 Effect.service(ProviderSessionRuntime.ProviderSessionRuntimeRepository),
582 );
583
584 await runtime!.runPromise(
585 repository.upsert({
586 threadId: failedThreadId,
587 providerName: "claudeAgent",
588 providerInstanceId: null,
589 adapterKey: "claudeAgent",
590 runtimeMode: "full-access",
591 status: "running",
592 lastSeenAt: "2026-04-14T00:00:00.000Z",
593 resumeCursor: {
594 opaque: "resume-failure",
595 },
596 runtimePayload: null,
597 }),
598 );
599 await runtime!.runPromise(
600 repository.upsert({
601 threadId: reapedThreadId,
602 providerName: "codex",
603 providerInstanceId: null,
604 adapterKey: "codex",
605 runtimeMode: "full-access",
606 status: "running",
607 lastSeenAt: "2026-04-14T00:01:00.000Z",
608 resumeCursor: {
609 opaque: "resume-success",
610 },
611 runtimePayload: null,
612 }),
613 );
614
615 await startReaper();
616
617 await waitFor(() => harness.stopSession.mock.calls.length === 2);
618
619 expect(harness.stopSession.mock.calls.map(([request]) => request.threadId)).toEqual([
620 failedThreadId,
621 reapedThreadId,
622 ]);
623 });
624
625 it("continues reaping other sessions when one stop attempt defects", async () => {
626 const defectThreadId = ThreadId.make("thread-reaper-stop-defect");
627 const reapedThreadId = ThreadId.make("thread-reaper-stop-after-defect");
628 const now = "2026-01-01T00:00:00.000Z";
629 const harness = await createHarness({
630 readModel: makeReadModel([
631 {
632 id: defectThreadId,
633 session: {
634 threadId: defectThreadId,
635 status: "error",
636 providerName: "claudeAgent",
637 runtimeMode: "full-access",
638 activeTurnId: null,
639 lastError: null,
640 updatedAt: now,
641 },
642 },
643 {
644 id: reapedThreadId,
645 session: {
646 threadId: reapedThreadId,
647 status: "ready",
648 providerName: "codex",
649 runtimeMode: "full-access",
650 activeTurnId: null,
651 lastError: null,
652 updatedAt: now,
653 },
654 },
655 ]),
656 stopSessionImplementation: (request) =>
657 request.threadId === defectThreadId
658 ? Effect.die(new Error("simulated stop defect"))
659 : Effect.void,
660 });
661 const repository = await runtime!.runPromise(
662 Effect.service(ProviderSessionRuntime.ProviderSessionRuntimeRepository),
663 );
664
665 await runtime!.runPromise(
666 repository.upsert({
667 threadId: defectThreadId,
668 providerName: "claudeAgent",
669 providerInstanceId: null,
670 adapterKey: "claudeAgent",
671 runtimeMode: "full-access",
672 status: "running",
673 lastSeenAt: "2026-04-14T00:00:00.000Z",
674 resumeCursor: {
675 opaque: "resume-defect",
676 },
677 runtimePayload: null,
678 }),
679 );
680 await runtime!.runPromise(
681 repository.upsert({
682 threadId: reapedThreadId,
683 providerName: "codex",
684 providerInstanceId: null,
685 adapterKey: "codex",
686 runtimeMode: "full-access",
687 status: "running",
688 lastSeenAt: "2026-04-14T00:01:00.000Z",
689 resumeCursor: {
690 opaque: "resume-after-defect",
691 },
692 runtimePayload: null,
693 }),
694 );
695
696 await startReaper();
697
698 await waitFor(() => harness.stopSession.mock.calls.length === 2);
699
700 expect(harness.stopSession.mock.calls.map(([request]) => request.threadId)).toEqual([
701 defectThreadId,
702 reapedThreadId,
703 ]);
704 });
705});