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