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

ProviderContinuationService.test.ts

820 lines29.6 KB

1import { assert, describe, it } from "@effect/vitest";
2import {
3 MessageId,
4 ProviderDriverKind,
5 ProviderThreadId,
6 RunId,
7 ThreadId,
8 type OrchestrationV2ThreadProjection,
9 type OrchestrationV2Notification,
10} from "@t3tools/contracts";
11import * as Deferred from "effect/Deferred";
12import * as DateTime from "effect/DateTime";
13import * as Effect from "effect/Effect";
14import * as Layer from "effect/Layer";
15import * as Option from "effect/Option";
16import * as Queue from "effect/Queue";
17import * as Ref from "effect/Ref";
18import * as Semaphore from "effect/Semaphore";
19import * as TestClock from "effect/testing/TestClock";
20​
21import * as IdAllocator from "./IdAllocator.ts";
22import * as ProviderContinuationRequests from "./ProviderContinuationRequests.ts";
23import * as ProviderContinuationService from "./ProviderContinuationService.ts";
24import * as ThreadManagementService from "./ThreadManagementService.ts";
25​
26const threadId = ThreadId.make("thread-provider-continuation");
27const providerThreadId = ProviderThreadId.make("provider-thread-continuation");
28const driver = ProviderDriverKind.make("continuation-test");
29const parentRunId = RunId.make("run-provider-continuation-parent");
30const delegatedMessageId = MessageId.make("message-provider-continuation-delegated");
31const projection = {
32 thread: { archivedAt: null, deletedAt: null },
33 messages: [],
34} as unknown as OrchestrationV2ThreadProjection;
35​
36const request = (
37 dispatchIfCurrent?: ProviderContinuationRequests.ProviderContinuationRequest["dispatchIfCurrent"],
38 detail: string | null = null,
39): ProviderContinuationRequests.ProviderContinuationRequest => ({
40 threadId,
41 providerThreadId,
42 driver,
43 detail,
44 ...(dispatchIfCurrent === undefined ? {} : { dispatchIfCurrent }),
45});
46​
47const delegatedProjection = (disposition: "open" | "stopped" | "disposed" = "open") =>
48 ({
49 ...projection,
50 runs: [
51 {
52 id: parentRunId,
53 delegatedCompletion: {
54 disposition,
55 nextGeneration: 2,
56 delivery: {
57 generation: 1,
58 messageId: delegatedMessageId,
59 taskIds: ["node-provider-continuation-first", "node-provider-continuation-second"],
60 },
61 },
62 },
63 ],
64 }) as unknown as OrchestrationV2ThreadProjection;
65​
66const makeGuard = Effect.fnUntraced(function* (completed?: Deferred.Deferred<void>) {
67 const generation = yield* Ref.make(0);
68 const permit = yield* Semaphore.make(1);
69 const capture = Effect.gen(function* () {
70 const captured = yield* Ref.updateAndGet(generation, (value) => value + 1);
71 return <A, E, R>(effect: Effect.Effect<A, E, R>) =>
72 permit
73 .withPermit(
74 Effect.gen(function* () {
75 if ((yield* Ref.get(generation)) !== captured) return Option.none();
76 return Option.some(yield* effect);
77 }),
78 )
79 .pipe(
80 completed === undefined
81 ? (effect) => effect
82 : Effect.ensuring(Deferred.succeed(completed, undefined)),
83 );
84 });
85 return {
86 capture,
87 invalidate: permit.withPermit(Ref.update(generation, (value) => value + 1)),
88 };
89});
90​
91function testLayer(input: {
92 readonly dispatched: Queue.Queue<unknown>;
93 readonly getThreadRecords: () => Effect.Effect<OrchestrationV2ThreadProjection>;
94}) {
95 const threads = Layer.mock(ThreadManagementService.ThreadManagementService)({
96 getThreadRecords: input.getThreadRecords,
97 dispatch: (command) => Queue.offer(input.dispatched, command).pipe(Effect.as({} as never)),
98 });
99 const worker = ProviderContinuationService.workerLive.pipe(
100 Layer.provide(Layer.mergeAll(IdAllocator.layer, ProviderContinuationRequests.layer, threads)),
101 );
102 return Layer.merge(ProviderContinuationRequests.layer, worker);
104​
105describe("ProviderContinuationService", () => {
106 it.effect("recovers an unaccepted persisted steer using the same delivery identity", () =>
107 Effect.gen(function* () {
108 const dispatched = yield* Queue.unbounded<unknown>();
109 const original = delegatedProjection();
110 const interruptedRunId = RunId.make("interrupted-mailbox-run");
111 const recovered = {
112 ...original,
113 runs: [
114 ...original.runs,
115 {
116 id: interruptedRunId,
117 status: "interrupted",
118 userMessageId: MessageId.make("original-user-input"),
119 },
120 ],
121 messages: [
122 {
123 id: delegatedMessageId,
124 runId: interruptedRunId,
125 delegatedCompletion: { parentRunId, generation: 1, taskIds: [] },
126 },
127 ],
128 } as unknown as OrchestrationV2ThreadProjection;
129 yield* Effect.gen(function* () {
130 const requests = yield* ProviderContinuationRequests.ProviderContinuationRequests;
131 yield* requests.offer({
132 threadId,
133 providerThreadId,
134 driver,
135 detail: null,
136 delivery: "message_text",
137 delegatedCompletion: { parentRunId, generation: 1, messageId: delegatedMessageId },
138 });
139 const command = (yield* Queue.take(dispatched)) as {
140 messageId: MessageId;
141 delegatedCompletion: { generation: number; taskIds: readonly string[] };
142 };
143 assert.equal(command.messageId, delegatedMessageId);
144 assert.equal(command.delegatedCompletion.generation, 1);
145 assert.equal(command.delegatedCompletion.taskIds.length, 2);
146 }).pipe(
147 Effect.provide(
148 testLayer({ dispatched, getThreadRecords: () => Effect.succeed(recovered) }),
149 ),
150 Effect.scoped,
151 );
152 }),
153 );
154​
155 it.effect("marks an adapter-buffered wake with the provider creation source", () => {
156 return Effect.gen(function* () {
157 const dispatched = yield* Queue.unbounded<unknown>();
158 yield* Effect.gen(function* () {
159 const requests = yield* ProviderContinuationRequests.ProviderContinuationRequests;
160 yield* requests.offer(request());
161 const command = (yield* Queue.take(dispatched)) as {
162 readonly creationSource: string;
163 readonly notification: OrchestrationV2Notification;
164 };
165 // ClaudeAdapterV2 keys on this to attach buffered CLI output.
166 assert.equal(command.creationSource, "provider");
167 assert.deepEqual(command.notification, {
168 source: { kind: "background_task" },
169 outcome: "updated",
170 summary: "Background activity updated",
171 });
172 }).pipe(
173 Effect.provide(
174 testLayer({ dispatched, getThreadRecords: () => Effect.succeed(projection) }),
175 ),
176 Effect.scoped,
177 );
178 });
179 });
180​
181 it.effect("delivers a message_text wake as a real prompt, not a buffered wake", () => {
182 return Effect.gen(function* () {
183 const dispatched = yield* Queue.unbounded<unknown>();
184 yield* Effect.gen(function* () {
185 const requests = yield* ProviderContinuationRequests.ProviderContinuationRequests;
186 yield* requests.offer({
187 threadId,
188 providerThreadId,
189 driver,
190 detail: "Delegated task completed.",
191 notification: {
192 source: { kind: "monitor" },
193 outcome: "updated",
194 summary: "Monitor updated",
195 },
196 delivery: "message_text",
197 });
198 const command = (yield* Queue.take(dispatched)) as {
199 readonly creationSource: string;
200 readonly text: string;
201 readonly notification: OrchestrationV2Notification;
202 };
203 // An app-owned child buffers nothing in the adapter, so this text is
204 // the whole wake. Marking it "provider" would make ClaudeAdapterV2
205 // drop it and settle the turn having prompted nothing.
206 assert.notEqual(command.creationSource, "provider");
207 assert.equal(command.creationSource, "server");
208 assert.equal(command.text, "Delegated task completed.");
209 assert.deepEqual(command.notification, {
210 source: { kind: "monitor" },
211 outcome: "updated",
212 summary: "Monitor updated",
213 });
214 }).pipe(
215 Effect.provide(
216 testLayer({ dispatched, getThreadRecords: () => Effect.succeed(projection) }),
217 ),
218 Effect.scoped,
219 );
220 });
221 });
222​
223 it.effect("dispatches a current delegated completion as one server-owned queued message", () => {
224 return Effect.gen(function* () {
225 const dispatched = yield* Queue.unbounded<unknown>();
226 yield* Effect.gen(function* () {
227 const requests = yield* ProviderContinuationRequests.ProviderContinuationRequests;
228 yield* requests.offer({
229 threadId,
230 providerThreadId,
231 driver,
232 detail: null,
233 delivery: "message_text",
234 delegatedCompletion: {
235 parentRunId,
236 generation: 1,
237 messageId: delegatedMessageId,
238 },
239 });
240 const command = (yield* Queue.take(dispatched)) as {
241 readonly createdBy: string;
242 readonly creationSource: string;
243 readonly delegatedCompletion: {
244 readonly generation: number;
245 readonly parentRunId: RunId;
246 readonly taskIds: ReadonlyArray<string>;
247 };
248 readonly dispatchMode: { readonly type: string };
249 readonly messageId: MessageId;
250 readonly text: string;
251 };
252 assert.equal(command.createdBy, "agent");
253 assert.equal(command.creationSource, "server");
254 assert.deepEqual(command.dispatchMode, { type: "queue_after_active" });
255 assert.equal(command.messageId, delegatedMessageId);
256 assert.equal(command.delegatedCompletion.parentRunId, parentRunId);
257 assert.equal(command.delegatedCompletion.generation, 1);
258 assert.deepEqual(command.delegatedCompletion.taskIds, [
259 "node-provider-continuation-first",
260 "node-provider-continuation-second",
261 ]);
262 assert.include(command.text, "task_status");
263 }).pipe(
264 Effect.provide(
265 testLayer({
266 dispatched,
267 getThreadRecords: () => Effect.succeed(delegatedProjection()),
268 }),
269 ),
270 Effect.scoped,
271 );
272 });
273 });
274​
275 it.effect("retries a delegated completion after a transient dispatch failure", () => {
276 return Effect.gen(function* () {
277 const attempts = yield* Ref.make(0);
278 const dispatched = yield* Queue.unbounded<unknown>();
279 const threads = Layer.mock(ThreadManagementService.ThreadManagementService)({
280 getThreadRecords: () => Effect.succeed(delegatedProjection()),
281 dispatch: (command) =>
282 Ref.getAndUpdate(attempts, (count) => count + 1).pipe(
283 Effect.flatMap((attempt) =>
284 attempt === 0
285 ? Effect.fail(new Error("simulated transient dispatch failure") as never)
286 : Queue.offer(dispatched, command).pipe(Effect.as({} as never)),
287 ),
288 ),
289 });
290 const worker = ProviderContinuationService.workerLive.pipe(
291 Layer.provide(
292 Layer.mergeAll(IdAllocator.layer, ProviderContinuationRequests.layer, threads),
293 ),
294 );
295​
296 yield* Effect.gen(function* () {
297 const requests = yield* ProviderContinuationRequests.ProviderContinuationRequests;
298 yield* requests.offer({
299 threadId,
300 providerThreadId,
301 driver,
302 detail: null,
303 delivery: "message_text",
304 delegatedCompletion: {
305 parentRunId,
306 generation: 1,
307 messageId: delegatedMessageId,
308 },
309 });
310 yield* Effect.yieldNow;
311 assert.equal(yield* Ref.get(attempts), 1);
312 assert.isTrue(Option.isNone(yield* Queue.poll(dispatched)));
313​
314 yield* TestClock.adjust("100 millis");
315 const command = (yield* Queue.take(dispatched)) as {
316 readonly messageId: MessageId;
317 };
318 assert.equal(command.messageId, delegatedMessageId);
319 assert.equal(yield* Ref.get(attempts), 2);
320 }).pipe(
321 Effect.provide(Layer.merge(ProviderContinuationRequests.layer, worker)),
322 Effect.scoped,
323 );
324 });
325 });
326​
327 it.effect("backs off repeated delegated completion dispatch failures", () => {
328 return Effect.gen(function* () {
329 const attempts = yield* Ref.make(0);
330 const disposition = yield* Ref.make<"open" | "disposed">("open");
331 const threads = Layer.mock(ThreadManagementService.ThreadManagementService)({
332 getThreadRecords: () =>
333 Ref.get(disposition).pipe(Effect.map((state) => delegatedProjection(state))),
334 dispatch: () =>
335 Ref.update(attempts, (count) => count + 1).pipe(
336 Effect.andThen(Effect.fail(new Error("simulated persistent failure") as never)),
337 ),
338 });
339 const worker = ProviderContinuationService.workerLive.pipe(
340 Layer.provide(
341 Layer.mergeAll(IdAllocator.layer, ProviderContinuationRequests.layer, threads),
342 ),
343 );
344​
345 yield* Effect.gen(function* () {
346 const requests = yield* ProviderContinuationRequests.ProviderContinuationRequests;
347 yield* requests.offer({
348 threadId,
349 providerThreadId,
350 driver,
351 detail: null,
352 delivery: "message_text",
353 delegatedCompletion: {
354 parentRunId,
355 generation: 1,
356 messageId: delegatedMessageId,
357 },
358 });
359 yield* Effect.yieldNow;
360 assert.equal(yield* Ref.get(attempts), 1);
361​
362 yield* TestClock.adjust("100 millis");
363 yield* Effect.yieldNow;
364 assert.equal(yield* Ref.get(attempts), 2);
365 yield* TestClock.adjust("199 millis");
366 yield* Effect.yieldNow;
367 assert.equal(yield* Ref.get(attempts), 2);
368 yield* TestClock.adjust("1 millis");
369 yield* Effect.yieldNow;
370 assert.equal(yield* Ref.get(attempts), 3);
371​
372 yield* Ref.set(disposition, "disposed");
373 yield* TestClock.adjust("400 millis");
374 }).pipe(
375 Effect.provide(Layer.merge(ProviderContinuationRequests.layer, worker)),
376 Effect.scoped,
377 );
378 });
379 });
380​
381 it.effect("resets delegated completion retry backoff after archive or deletion", () => {
382 return Effect.gen(function* () {
383 for (const barrier of ["archivedAt", "deletedAt"] as const) {
384 const attempts = yield* Ref.make(0);
385 const blockedProjectionReads = yield* Ref.make(0);
386 const blockedRequestDropped = yield* Deferred.make<void>();
387 const state = yield* Ref.make<"open" | "blocked" | "disposed">("open");
388 const threads = Layer.mock(ThreadManagementService.ThreadManagementService)({
389 getThreadRecords: () =>
390 Effect.gen(function* () {
391 const currentState = yield* Ref.get(state);
392 if (currentState === "blocked") {
393 const reads = yield* Ref.updateAndGet(blockedProjectionReads, (count) => count + 1);
394 if (reads === 2) {
395 yield* Deferred.succeed(blockedRequestDropped, undefined);
396 }
397 }
398 return {
399 ...delegatedProjection(currentState === "disposed" ? "disposed" : "open"),
400 thread: {
401 ...projection.thread,
402 [barrier]:
403 currentState === "blocked"
404 ? DateTime.makeUnsafe("2026-08-05T00:00:00.000Z")
405 : null,
406 },
407 };
408 }),
409 dispatch: () =>
410 Ref.update(attempts, (count) => count + 1).pipe(
411 Effect.andThen(Effect.fail(new Error("simulated persistent failure") as never)),
412 ),
413 });
414 const worker = ProviderContinuationService.workerLive.pipe(
415 Layer.provide(
416 Layer.mergeAll(IdAllocator.layer, ProviderContinuationRequests.layer, threads),
417 ),
418 );
419 const completionRequest = {
420 threadId,
421 providerThreadId,
422 driver,
423 detail: null,
424 delivery: "message_text" as const,
425 delegatedCompletion: {
426 parentRunId,
427 generation: 1,
428 messageId: delegatedMessageId,
429 },
430 };
431​
432 yield* Effect.gen(function* () {
433 const requests = yield* ProviderContinuationRequests.ProviderContinuationRequests;
434 yield* requests.offer(completionRequest);
435 yield* Effect.yieldNow;
436 assert.equal(yield* Ref.get(attempts), 1);
437​
438 yield* Ref.set(state, "blocked");
439 yield* TestClock.adjust("100 millis");
440 yield* Deferred.await(blockedRequestDropped);
441 yield* Effect.yieldNow;
442 assert.equal(yield* Ref.get(attempts), 1);
443​
444 yield* Ref.set(state, "open");
445 yield* requests.offer(completionRequest);
446 yield* Effect.yieldNow;
447 assert.equal(yield* Ref.get(attempts), 2);
448 yield* TestClock.adjust("99 millis");
449 yield* Effect.yieldNow;
450 assert.equal(yield* Ref.get(attempts), 2);
451 yield* TestClock.adjust("1 millis");
452 yield* Effect.yieldNow;
453 assert.equal(yield* Ref.get(attempts), 3);
454​
455 yield* Ref.set(state, "disposed");
456 yield* TestClock.adjust("200 millis");
457 }).pipe(
458 Effect.provide(Layer.merge(ProviderContinuationRequests.layer, worker)),
459 Effect.scoped,
460 );
461 }
462 });
463 });
464​
465 it.effect("drops a delegated completion retry after its delivery closes", () => {
466 return Effect.gen(function* () {
467 const attempts = yield* Ref.make(0);
468 const disposition = yield* Ref.make<"open" | "disposed">("open");
469 const threads = Layer.mock(ThreadManagementService.ThreadManagementService)({
470 getThreadRecords: () =>
471 Ref.get(disposition).pipe(Effect.map((state) => delegatedProjection(state))),
472 dispatch: () =>
473 Ref.update(attempts, (count) => count + 1).pipe(
474 Effect.andThen(Effect.fail(new Error("simulated dispatch failure") as never)),
475 ),
476 });
477 const worker = ProviderContinuationService.workerLive.pipe(
478 Layer.provide(
479 Layer.mergeAll(IdAllocator.layer, ProviderContinuationRequests.layer, threads),
480 ),
481 );
482​
483 yield* Effect.gen(function* () {
484 const requests = yield* ProviderContinuationRequests.ProviderContinuationRequests;
485 yield* requests.offer({
486 threadId,
487 providerThreadId,
488 driver,
489 detail: null,
490 delivery: "message_text",
491 delegatedCompletion: {
492 parentRunId,
493 generation: 1,
494 messageId: delegatedMessageId,
495 },
496 });
497 yield* Effect.yieldNow;
498 assert.equal(yield* Ref.get(attempts), 1);
499​
500 yield* Ref.set(disposition, "disposed");
501 yield* TestClock.adjust("100 millis");
502 yield* Effect.yieldNow;
503 assert.equal(yield* Ref.get(attempts), 1);
504 }).pipe(
505 Effect.provide(Layer.merge(ProviderContinuationRequests.layer, worker)),
506 Effect.scoped,
507 );
508 });
509 });
510​
511 it.effect("keeps a Grok delegated completion queued instead of restarting active work", () => {
512 return Effect.gen(function* () {
513 const dispatched = yield* Queue.unbounded<unknown>();
514 yield* Effect.gen(function* () {
515 const requests = yield* ProviderContinuationRequests.ProviderContinuationRequests;
516 yield* requests.offer({
517 threadId,
518 providerThreadId,
519 driver: ProviderDriverKind.make("grok"),
520 detail: null,
521 delivery: "message_text",
522 delegatedCompletion: {
523 parentRunId,
524 generation: 1,
525 messageId: delegatedMessageId,
526 },
527 });
528 const command = (yield* Queue.take(dispatched)) as {
529 readonly dispatchMode: { readonly type: string };
530 };
531 assert.deepEqual(command.dispatchMode, { type: "queue_after_active" });
532 }).pipe(
533 Effect.provide(
534 testLayer({
535 dispatched,
536 getThreadRecords: () => Effect.succeed(delegatedProjection()),
537 }),
538 ),
539 Effect.scoped,
540 );
541 });
542 });
543​
544 it.effect(
545 "drops stopped and disposed delegated completions instead of reviving them after recovery",
546 () => {
547 return Effect.gen(function* () {
548 for (const disposition of ["stopped", "disposed"] as const) {
549 const dispatched = yield* Queue.unbounded<unknown>();
550 yield* Effect.gen(function* () {
551 const requests = yield* ProviderContinuationRequests.ProviderContinuationRequests;
552 yield* requests.offer({
553 threadId,
554 providerThreadId,
555 driver,
556 detail: null,
557 delivery: "message_text",
558 delegatedCompletion: {
559 parentRunId,
560 generation: 1,
561 messageId: delegatedMessageId,
562 },
563 });
564 yield* Effect.yieldNow;
565 yield* Effect.yieldNow;
566 assert.isTrue(Option.isNone(yield* Queue.poll(dispatched)));
567 }).pipe(
568 Effect.provide(
569 testLayer({
570 dispatched,
571 getThreadRecords: () => Effect.succeed(delegatedProjection(disposition)),
572 }),
573 ),
574 Effect.scoped,
575 );
576 }
577 });
578 },
579 );
580​
581 it.effect("does not redispatch a persisted delegated completion message during recovery", () => {
582 return Effect.gen(function* () {
583 const dispatched = yield* Queue.unbounded<unknown>();
584 yield* Effect.gen(function* () {
585 const requests = yield* ProviderContinuationRequests.ProviderContinuationRequests;
586 yield* requests.offer({
587 threadId,
588 providerThreadId,
589 driver,
590 detail: null,
591 delivery: "message_text",
592 delegatedCompletion: {
593 parentRunId,
594 generation: 1,
595 messageId: delegatedMessageId,
596 },
597 });
598 yield* Effect.yieldNow;
599 yield* Effect.yieldNow;
600 assert.isTrue(Option.isNone(yield* Queue.poll(dispatched)));
601 }).pipe(
602 Effect.provide(
603 testLayer({
604 dispatched,
605 getThreadRecords: () =>
606 Effect.succeed({
607 ...delegatedProjection(),
608 messages: [{ id: delegatedMessageId }],
609 } as unknown as OrchestrationV2ThreadProjection),
610 }),
611 ),
612 Effect.scoped,
613 );
614 });
615 });
616​
617 it.effect("drops archived and deleted delegated completions during recovery", () => {
618 return Effect.gen(function* () {
619 for (const barrier of ["archivedAt", "deletedAt"] as const) {
620 const dispatched = yield* Queue.unbounded<unknown>();
621 yield* Effect.gen(function* () {
622 const requests = yield* ProviderContinuationRequests.ProviderContinuationRequests;
623 yield* requests.offer({
624 threadId,
625 providerThreadId,
626 driver,
627 detail: null,
628 delivery: "message_text",
629 delegatedCompletion: {
630 parentRunId,
631 generation: 1,
632 messageId: delegatedMessageId,
633 },
634 });
635 yield* Effect.yieldNow;
636 yield* Effect.yieldNow;
637 assert.isTrue(Option.isNone(yield* Queue.poll(dispatched)));
638 }).pipe(
639 Effect.provide(
640 testLayer({
641 dispatched,
642 getThreadRecords: () =>
643 Effect.succeed({
644 ...delegatedProjection(),
645 thread: {
646 ...projection.thread,
647 [barrier]: DateTime.makeUnsafe("2026-08-03T00:00:00.000Z"),
648 },
649 } as unknown as OrchestrationV2ThreadProjection),
650 }),
651 ),
652 Effect.scoped,
653 );
654 }
655 });
656 });
657​
658 it.effect("dispatches a current request exactly once", () => {
659 return Effect.gen(function* () {
660 const dispatched = yield* Queue.unbounded<unknown>();
661 yield* Effect.gen(function* () {
662 const requests = yield* ProviderContinuationRequests.ProviderContinuationRequests;
663 yield* requests.offer(request());
664 yield* Queue.take(dispatched);
665 yield* Effect.yieldNow;
666 assert.isTrue(Option.isNone(yield* Queue.poll(dispatched)));
667 }).pipe(
668 Effect.provide(
669 testLayer({ dispatched, getThreadRecords: () => Effect.succeed(projection) }),
670 ),
671 Effect.scoped,
672 );
673 });
674 });
675​
676 it.effect("queues a continuation behind an active user run", () => {
677 return Effect.gen(function* () {
678 const dispatched = yield* Queue.unbounded<unknown>();
679 yield* Effect.gen(function* () {
680 const requests = yield* ProviderContinuationRequests.ProviderContinuationRequests;
681 yield* requests.offer(request());
682 const command = yield* Queue.take(dispatched);
683 assert.deepEqual((command as { readonly dispatchMode?: unknown }).dispatchMode, {
684 type: "queue_after_active",
685 });
686 }).pipe(
687 Effect.provide(
688 testLayer({ dispatched, getThreadRecords: () => Effect.succeed(projection) }),
689 ),
690 Effect.scoped,
691 );
692 });
693 });
694​
695 it.effect("drops a request invalidated before dispatch", () => {
696 return Effect.gen(function* () {
697 const dispatched = yield* Queue.unbounded<unknown>();
698 yield* Effect.gen(function* () {
699 const requests = yield* ProviderContinuationRequests.ProviderContinuationRequests;
700 const guard = yield* makeGuard();
701 const dispatchIfCurrent = yield* guard.capture;
702 yield* guard.invalidate;
703 yield* requests.offer(request(dispatchIfCurrent));
704 yield* Effect.yieldNow;
705 yield* Effect.yieldNow;
706 assert.isTrue(Option.isNone(yield* Queue.poll(dispatched)));
707 }).pipe(
708 Effect.provide(
709 testLayer({ dispatched, getThreadRecords: () => Effect.succeed(projection) }),
710 ),
711 Effect.scoped,
712 );
713 });
714 });
715​
716 it.effect("drops a request invalidated while projection is blocked", () => {
717 return Effect.gen(function* () {
718 const dispatched = yield* Queue.unbounded<unknown>();
719 const projectionEntered = yield* Deferred.make<void>();
720 const releaseProjection = yield* Deferred.make<void>();
721 const guardCompleted = yield* Deferred.make<void>();
722 yield* Effect.gen(function* () {
723 const requests = yield* ProviderContinuationRequests.ProviderContinuationRequests;
724 const guard = yield* makeGuard(guardCompleted);
725 const dispatchIfCurrent = yield* guard.capture;
726 yield* requests.offer(request(dispatchIfCurrent));
727 yield* Deferred.await(projectionEntered);
728 yield* guard.invalidate;
729 yield* Deferred.succeed(releaseProjection, undefined);
730 yield* Deferred.await(guardCompleted);
731 assert.isTrue(Option.isNone(yield* Queue.poll(dispatched)));
732 }).pipe(
733 Effect.provide(
734 testLayer({
735 dispatched,
736 getThreadRecords: () =>
737 Deferred.succeed(projectionEntered, undefined).pipe(
738 Effect.andThen(Deferred.await(releaseProjection)),
739 Effect.as(projection),
740 ),
741 }),
742 ),
743 Effect.scoped,
744 );
745 });
746 });
747​
748 it.effect("does not revive an old request when a later generation is current", () => {
749 return Effect.gen(function* () {
750 const dispatched = yield* Queue.unbounded<unknown>();
751 const firstProjectionEntered = yield* Deferred.make<void>();
752 const releaseFirstProjection = yield* Deferred.make<void>();
753 let projectionCalls = 0;
754 yield* Effect.gen(function* () {
755 const requests = yield* ProviderContinuationRequests.ProviderContinuationRequests;
756 const guard = yield* makeGuard();
757 const first = yield* guard.capture;
758 yield* requests.offer(request(first, "A"));
759 yield* Deferred.await(firstProjectionEntered);
760 const second = yield* guard.capture;
761 yield* requests.offer(request(second, "B"));
762 yield* Deferred.succeed(releaseFirstProjection, undefined);
763 const command = yield* Queue.take(dispatched);
764 assert.equal((command as { readonly text?: unknown }).text, "B");
765 yield* Effect.yieldNow;
766 assert.isTrue(Option.isNone(yield* Queue.poll(dispatched)));
767 }).pipe(
768 Effect.provide(
769 testLayer({
770 dispatched,
771 getThreadRecords: () => {
772 projectionCalls += 1;
773 return projectionCalls === 1
774 ? Deferred.succeed(firstProjectionEntered, undefined).pipe(
775 Effect.andThen(Deferred.await(releaseFirstProjection)),
776 Effect.as(projection),
777 )
778 : Effect.succeed(projection);
779 },
780 }),
781 ),
782 Effect.scoped,
783 );
784 });
785 });
786​
787 it.effect("clears a sticky continuation offer when its thread is archived", () => {
788 return Effect.gen(function* () {
789 const dispatched = yield* Queue.unbounded<unknown>();
790 const cleared = yield* Ref.make(false);
791 yield* Effect.gen(function* () {
792 const requests = yield* ProviderContinuationRequests.ProviderContinuationRequests;
793 yield* requests.offer({
794 ...request(),
795 clearIfCurrent: () => Ref.set(cleared, true),
796 });
797 for (let attempt = 0; attempt < 20 && !(yield* Ref.get(cleared)); attempt += 1) {
798 yield* Effect.yieldNow;
799 }
800 assert.isTrue(yield* Ref.get(cleared));
801 assert.isTrue(Option.isNone(yield* Queue.poll(dispatched)));
802 }).pipe(
803 Effect.provide(
804 testLayer({
805 dispatched,
806 getThreadRecords: () =>
807 Effect.succeed({
808 ...projection,
809 thread: {
810 ...projection.thread,
811 archivedAt: DateTime.makeUnsafe("2026-07-20T00:00:00.000Z"),
812 },
813 }),
814 }),
815 ),
816 Effect.scoped,
817 );
818 });
819 });
820});