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

ProviderContinuationService.test.ts

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