Open History to see the last commit
1import { assert, describe, it } from "@effect/vitest";
2import {
3 MessageId,
4 ProjectId,
5 ProviderDriverKind,
6 ProviderInstanceId,
7 ProviderThreadId,
8 RunId,
9 ThreadId,
10 type OrchestrationV2ThreadProjection,
11 type OrchestrationV2Notification,
12} from "@t3tools/contracts";
13import * as Deferred from "effect/Deferred";
14import * as DateTime from "effect/DateTime";
15import * as Effect from "effect/Effect";
16import * as Exit from "effect/Exit";
17import * as Layer from "effect/Layer";
18import * as Option from "effect/Option";
19import * as Queue from "effect/Queue";
20import * as Ref from "effect/Ref";
21import * as Semaphore from "effect/Semaphore";
22import * as TestClock from "effect/testing/TestClock";
23
24import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
25import * as ProviderContinuationRequests from "@t3tools/provider-core/server/ProviderContinuationRequests";
26import * as ProviderContinuationService from "./ProviderContinuationService.ts";
27import * as ThreadManagementService from "./ThreadManagementService.ts";
28
29const threadId = ThreadId.make("thread-provider-continuation");
30const providerThreadId = ProviderThreadId.make("provider-thread-continuation");
31const driver = ProviderDriverKind.make("continuation-test");
32const parentRunId = RunId.make("run-provider-continuation-parent");
33const delegatedMessageId = MessageId.make("message-provider-continuation-delegated");
34const projection = {
35 thread: { archivedAt: null, deletedAt: null },
36 messages: [],
37} as unknown as OrchestrationV2ThreadProjection;
38
39const request = (
40 dispatchIfCurrent?: ProviderContinuationRequests.ProviderContinuationRequest["dispatchIfCurrent"],
41 detail: string | null = null,
42): ProviderContinuationRequests.ProviderContinuationRequest => ({
43 threadId,
44 providerThreadId,
45 driver,
46 detail,
47 ...(dispatchIfCurrent === undefined ? {} : { dispatchIfCurrent }),
48});
49
50const delegatedProjection = (disposition: "open" | "stopped" | "disposed" = "open") =>
51 ({
52 ...projection,
53 runs: [
54 {
55 id: parentRunId,
56 delegatedCompletion: {
57 disposition,
58 nextGeneration: 2,
59 delivery: {
60 generation: 1,
61 messageId: delegatedMessageId,
62 taskIds: ["node-provider-continuation-first", "node-provider-continuation-second"],
63 },
64 },
65 },
66 ],
67 }) as unknown as OrchestrationV2ThreadProjection;
68
69const makeGuard = Effect.fnUntraced(function* (completed?: Deferred.Deferred<void>) {
70 const generation = yield* Ref.make(0);
71 const permit = yield* Semaphore.make(1);
72 const capture = Effect.gen(function* () {
73 const captured = yield* Ref.updateAndGet(generation, (value) => value + 1);
74 return <A, E, R>(effect: Effect.Effect<A, E, R>) =>
75 permit
76 .withPermit(
77 Effect.gen(function* () {
78 if ((yield* Ref.get(generation)) !== captured) return Option.none();
79 return Option.some(yield* effect);
80 }),
81 )
82 .pipe(
83 completed === undefined
84 ? (effect) => effect
85 : Effect.ensuring(Deferred.succeed(completed, undefined)),
86 );
87 });
88 return {
89 capture,
90 invalidate: permit.withPermit(Ref.update(generation, (value) => value + 1)),
91 };
92});
93
94function layerTest(input: {
95 readonly dispatched: Queue.Queue<unknown>;
96 readonly getThreadRecords: () => Effect.Effect<OrchestrationV2ThreadProjection>;
97}) {
98 const layerThreads = Layer.mock(ThreadManagementService.ThreadManagementService)({
99 getThreadRecords: input.getThreadRecords,
100 dispatch: (command) => Queue.offer(input.dispatched, command).pipe(Effect.as({} as never)),
101 });
102 const layerWorker = ProviderContinuationService.layer.pipe(
103 Layer.provide(
104 Layer.mergeAll(IdAllocator.layer, ProviderContinuationRequests.layer, layerThreads),
105 ),
106 );
107 return Layer.merge(ProviderContinuationRequests.layer, layerWorker);
108}
109
110describe("ProviderContinuationService", () => {
111 it.effect("recovers an unaccepted persisted steer using the same delivery identity", () =>
112 Effect.gen(function* () {
113 const dispatched = yield* Queue.unbounded<unknown>();
114 const original = delegatedProjection();
115 const interruptedRunId = RunId.make("interrupted-mailbox-run");
116 const recovered = {
117 ...original,
118 runs: [
119 ...original.runs,
120 {
121 id: interruptedRunId,
122 status: "interrupted",
123 userMessageId: MessageId.make("original-user-input"),
124 },
125 ],
126 messages: [
127 {
128 id: delegatedMessageId,
129 runId: interruptedRunId,
130 delegatedCompletion: { parentRunId, generation: 1, taskIds: [] },
131 },
132 ],
133 } as unknown as OrchestrationV2ThreadProjection;
134 yield* Effect.gen(function* () {
135 const requests = yield* ProviderContinuationRequests.ProviderContinuationRequests;
136 yield* requests.offer({
137 threadId,
138 providerThreadId,
139 driver,
140 detail: null,
141 delivery: "message_text",
142 delegatedCompletion: { parentRunId, generation: 1, messageId: delegatedMessageId },
143 });
144 const command = (yield* Queue.take(dispatched)) as {
145 messageId: MessageId;
146 delegatedCompletion: { generation: number; taskIds: readonly string[] };
147 };
148 assert.equal(command.messageId, delegatedMessageId);
149 assert.equal(command.delegatedCompletion.generation, 1);
150 assert.equal(command.delegatedCompletion.taskIds.length, 2);
151 }).pipe(
152 Effect.provide(
153 layerTest({ dispatched, getThreadRecords: () => Effect.succeed(recovered) }),
154 ),
155 Effect.scoped,
156 );
157 }),
158 );
159
160 it.effect("marks an adapter-buffered wake with the provider creation source", () => {
161 return Effect.gen(function* () {
162 const dispatched = yield* Queue.unbounded<unknown>();
163 yield* Effect.gen(function* () {
164 const requests = yield* ProviderContinuationRequests.ProviderContinuationRequests;
165 yield* requests.offer(request());
166 const command = (yield* Queue.take(dispatched)) as {
167 readonly creationSource: string;
168 readonly notification: OrchestrationV2Notification;
169 };
170 assert.equal(command.creationSource, "provider");
171 assert.deepEqual(command.notification, {
172 source: { kind: "background_task" },
173 outcome: "updated",
174 summary: "Background activity updated",
175 });
176 }).pipe(
177 Effect.provide(
178 layerTest({ dispatched, getThreadRecords: () => Effect.succeed(projection) }),
179 ),
180 Effect.scoped,
181 );
182 });
183 });
184
185 it.effect("dispatches a wake under the message its adapter named", () => {
186 return Effect.gen(function* () {
187 const dispatched = yield* Queue.unbounded<unknown>();
188 const messageId = MessageId.make("message-provider-continuation-adapter-named");
189 yield* Effect.gen(function* () {
190 const requests = yield* ProviderContinuationRequests.ProviderContinuationRequests;
191 yield* requests.offer({ ...request(), messageId });
192 const command = (yield* Queue.take(dispatched)) as { readonly messageId: MessageId };
193 assert.equal(command.messageId, messageId);
194 }).pipe(
195 Effect.provide(
196 layerTest({ dispatched, getThreadRecords: () => Effect.succeed(projection) }),
197 ),
198 Effect.scoped,
199 );
200 });
201 });
202
203 it.effect("delivers a message_text wake as a real prompt, not a buffered wake", () => {
204 return Effect.gen(function* () {
205 const dispatched = yield* Queue.unbounded<unknown>();
206 yield* Effect.gen(function* () {
207 const requests = yield* ProviderContinuationRequests.ProviderContinuationRequests;
208 yield* requests.offer({
209 threadId,
210 providerThreadId,
211 driver,
212 detail: "Delegated task completed.",
213 notification: {
214 source: { kind: "monitor" },
215 outcome: "updated",
216 summary: "Monitor updated",
217 },
218 delivery: "message_text",
219 });
220 const command = (yield* Queue.take(dispatched)) as {
221 readonly creationSource: string;
222 readonly text: string;
223 readonly notification: OrchestrationV2Notification;
224 };
225 // An app-owned child buffers nothing in the adapter, so this text is
226 // the whole wake. Marking it "provider" would make ClaudeAdapterV2
227 // drop it and settle the turn having prompted nothing.
228 assert.notEqual(command.creationSource, "provider");
229 assert.equal(command.creationSource, "server");
230 assert.equal(command.text, "Delegated task completed.");
231 assert.deepEqual(command.notification, {
232 source: { kind: "monitor" },
233 outcome: "updated",
234 summary: "Monitor updated",
235 });
236 }).pipe(
237 Effect.provide(
238 layerTest({ dispatched, getThreadRecords: () => Effect.succeed(projection) }),
239 ),
240 Effect.scoped,
241 );
242 });
243 });
244
245 it.effect("dispatches a current delegated completion as one server-owned queued message", () => {
246 return Effect.gen(function* () {
247 const dispatched = yield* Queue.unbounded<unknown>();
248 yield* Effect.gen(function* () {
249 const requests = yield* ProviderContinuationRequests.ProviderContinuationRequests;
250 yield* requests.offer({
251 threadId,
252 providerThreadId,
253 driver,
254 detail: null,
255 delivery: "message_text",
256 delegatedCompletion: {
257 parentRunId,
258 generation: 1,
259 messageId: delegatedMessageId,
260 },
261 });
262 const command = (yield* Queue.take(dispatched)) as {
263 readonly createdBy: string;
264 readonly creationSource: string;
265 readonly delegatedCompletion: {
266 readonly generation: number;
267 readonly parentRunId: RunId;
268 readonly taskIds: ReadonlyArray<string>;
269 };
270 readonly dispatchMode: { readonly type: string };
271 readonly messageId: MessageId;
272 readonly text: string;
273 };
274 assert.equal(command.createdBy, "agent");
275 assert.equal(command.creationSource, "server");
276 assert.deepEqual(command.dispatchMode, { type: "queue_after_active" });
277 assert.equal(command.messageId, delegatedMessageId);
278 assert.equal(command.delegatedCompletion.parentRunId, parentRunId);
279 assert.equal(command.delegatedCompletion.generation, 1);
280 assert.deepEqual(command.delegatedCompletion.taskIds, [
281 "node-provider-continuation-first",
282 "node-provider-continuation-second",
283 ]);
284 assert.include(command.text, "task_status");
285 }).pipe(
286 Effect.provide(
287 layerTest({
288 dispatched,
289 getThreadRecords: () => Effect.succeed(delegatedProjection()),
290 }),
291 ),
292 Effect.scoped,
293 );
294 });
295 });
296
297 it.effect("retries a delegated completion after a transient dispatch failure", () => {
298 return Effect.gen(function* () {
299 const attempts = yield* Ref.make(0);
300 const dispatched = yield* Queue.unbounded<unknown>();
301 const layerThreads = Layer.mock(ThreadManagementService.ThreadManagementService)({
302 getThreadRecords: () => Effect.succeed(delegatedProjection()),
303 dispatch: (command) =>
304 Ref.getAndUpdate(attempts, (count) => count + 1).pipe(
305 Effect.flatMap((attempt) =>
306 attempt === 0
307 ? Effect.fail(new Error("simulated transient dispatch failure") as never)
308 : Queue.offer(dispatched, command).pipe(Effect.as({} as never)),
309 ),
310 ),
311 });
312 const layerWorker = ProviderContinuationService.layer.pipe(
313 Layer.provide(
314 Layer.mergeAll(IdAllocator.layer, ProviderContinuationRequests.layer, layerThreads),
315 ),
316 );
317
318 yield* Effect.gen(function* () {
319 const requests = yield* ProviderContinuationRequests.ProviderContinuationRequests;
320 yield* requests.offer({
321 threadId,
322 providerThreadId,
323 driver,
324 detail: null,
325 delivery: "message_text",
326 delegatedCompletion: {
327 parentRunId,
328 generation: 1,
329 messageId: delegatedMessageId,
330 },
331 });
332 yield* Effect.yieldNow;
333 assert.equal(yield* Ref.get(attempts), 1);
334 assert.isTrue(Option.isNone(yield* Queue.poll(dispatched)));
335
336 yield* TestClock.adjust("100 millis");
337 const command = (yield* Queue.take(dispatched)) as {
338 readonly messageId: MessageId;
339 };
340 assert.equal(command.messageId, delegatedMessageId);
341 assert.equal(yield* Ref.get(attempts), 2);
342 }).pipe(
343 Effect.provide(Layer.merge(ProviderContinuationRequests.layer, layerWorker)),
344 Effect.scoped,
345 );
346 });
347 });
348
349 it.effect("backs off repeated delegated completion dispatch failures", () => {
350 return Effect.gen(function* () {
351 const attempts = yield* Ref.make(0);
352 const disposition = yield* Ref.make<"open" | "disposed">("open");
353 const layerThreads = Layer.mock(ThreadManagementService.ThreadManagementService)({
354 getThreadRecords: () =>
355 Ref.get(disposition).pipe(Effect.map((state) => delegatedProjection(state))),
356 dispatch: () =>
357 Ref.update(attempts, (count) => count + 1).pipe(
358 Effect.andThen(Effect.fail(new Error("simulated persistent failure") as never)),
359 ),
360 });
361 const layerWorker = ProviderContinuationService.layer.pipe(
362 Layer.provide(
363 Layer.mergeAll(IdAllocator.layer, ProviderContinuationRequests.layer, layerThreads),
364 ),
365 );
366
367 yield* Effect.gen(function* () {
368 const requests = yield* ProviderContinuationRequests.ProviderContinuationRequests;
369 yield* requests.offer({
370 threadId,
371 providerThreadId,
372 driver,
373 detail: null,
374 delivery: "message_text",
375 delegatedCompletion: {
376 parentRunId,
377 generation: 1,
378 messageId: delegatedMessageId,
379 },
380 });
381 yield* Effect.yieldNow;
382 assert.equal(yield* Ref.get(attempts), 1);
383
384 yield* TestClock.adjust("100 millis");
385 yield* Effect.yieldNow;
386 assert.equal(yield* Ref.get(attempts), 2);
387 yield* TestClock.adjust("199 millis");
388 yield* Effect.yieldNow;
389 assert.equal(yield* Ref.get(attempts), 2);
390 yield* TestClock.adjust("1 millis");
391 yield* Effect.yieldNow;
392 assert.equal(yield* Ref.get(attempts), 3);
393
394 yield* Ref.set(disposition, "disposed");
395 yield* TestClock.adjust("400 millis");
396 }).pipe(
397 Effect.provide(Layer.merge(ProviderContinuationRequests.layer, layerWorker)),
398 Effect.scoped,
399 );
400 });
401 });
402
403 it.effect("resets delegated completion retry backoff after archive or deletion", () => {
404 return Effect.gen(function* () {
405 for (const barrier of ["archivedAt", "deletedAt"] as const) {
406 const attempts = yield* Ref.make(0);
407 const blockedProjectionReads = yield* Ref.make(0);
408 const blockedRequestDropped = yield* Deferred.make<void>();
409 const state = yield* Ref.make<"open" | "blocked" | "disposed">("open");
410 const layerThreads = Layer.mock(ThreadManagementService.ThreadManagementService)({
411 getThreadRecords: () =>
412 Effect.gen(function* () {
413 const currentState = yield* Ref.get(state);
414 if (currentState === "blocked") {
415 const reads = yield* Ref.updateAndGet(blockedProjectionReads, (count) => count + 1);
416 if (reads === 2) {
417 yield* Deferred.succeed(blockedRequestDropped, undefined);
418 }
419 }
420 return {
421 ...delegatedProjection(currentState === "disposed" ? "disposed" : "open"),
422 thread: {
423 ...projection.thread,
424 [barrier]:
425 currentState === "blocked"
426 ? DateTime.makeUnsafe("2026-08-05T00:00:00.000Z")
427 : null,
428 },
429 };
430 }),
431 dispatch: () =>
432 Ref.update(attempts, (count) => count + 1).pipe(
433 Effect.andThen(Effect.fail(new Error("simulated persistent failure") as never)),
434 ),
435 });
436 const layerWorker = ProviderContinuationService.layer.pipe(
437 Layer.provide(
438 Layer.mergeAll(IdAllocator.layer, ProviderContinuationRequests.layer, layerThreads),
439 ),
440 );
441 const completionRequest = {
442 threadId,
443 providerThreadId,
444 driver,
445 detail: null,
446 delivery: "message_text" as const,
447 delegatedCompletion: {
448 parentRunId,
449 generation: 1,
450 messageId: delegatedMessageId,
451 },
452 };
453
454 yield* Effect.gen(function* () {
455 const requests = yield* ProviderContinuationRequests.ProviderContinuationRequests;
456 yield* requests.offer(completionRequest);
457 yield* Effect.yieldNow;
458 assert.equal(yield* Ref.get(attempts), 1);
459
460 yield* Ref.set(state, "blocked");
461 yield* TestClock.adjust("100 millis");
462 yield* Deferred.await(blockedRequestDropped);
463 yield* Effect.yieldNow;
464 assert.equal(yield* Ref.get(attempts), 1);
465
466 yield* Ref.set(state, "open");
467 yield* requests.offer(completionRequest);
468 yield* Effect.yieldNow;
469 assert.equal(yield* Ref.get(attempts), 2);
470 yield* TestClock.adjust("99 millis");
471 yield* Effect.yieldNow;
472 assert.equal(yield* Ref.get(attempts), 2);
473 yield* TestClock.adjust("1 millis");
474 yield* Effect.yieldNow;
475 assert.equal(yield* Ref.get(attempts), 3);
476
477 yield* Ref.set(state, "disposed");
478 yield* TestClock.adjust("200 millis");
479 }).pipe(
480 Effect.provide(Layer.merge(ProviderContinuationRequests.layer, layerWorker)),
481 Effect.scoped,
482 );
483 }
484 });
485 });
486
487 it.effect("drops a delegated completion retry after its delivery closes", () => {
488 return Effect.gen(function* () {
489 const attempts = yield* Ref.make(0);
490 const disposition = yield* Ref.make<"open" | "disposed">("open");
491 const layerThreads = Layer.mock(ThreadManagementService.ThreadManagementService)({
492 getThreadRecords: () =>
493 Ref.get(disposition).pipe(Effect.map((state) => delegatedProjection(state))),
494 dispatch: () =>
495 Ref.update(attempts, (count) => count + 1).pipe(
496 Effect.andThen(Effect.fail(new Error("simulated dispatch failure") as never)),
497 ),
498 });
499 const layerWorker = ProviderContinuationService.layer.pipe(
500 Layer.provide(
501 Layer.mergeAll(IdAllocator.layer, ProviderContinuationRequests.layer, layerThreads),
502 ),
503 );
504
505 yield* Effect.gen(function* () {
506 const requests = yield* ProviderContinuationRequests.ProviderContinuationRequests;
507 yield* requests.offer({
508 threadId,
509 providerThreadId,
510 driver,
511 detail: null,
512 delivery: "message_text",
513 delegatedCompletion: {
514 parentRunId,
515 generation: 1,
516 messageId: delegatedMessageId,
517 },
518 });
519 yield* Effect.yieldNow;
520 assert.equal(yield* Ref.get(attempts), 1);
521
522 yield* Ref.set(disposition, "disposed");
523 yield* TestClock.adjust("100 millis");
524 yield* Effect.yieldNow;
525 assert.equal(yield* Ref.get(attempts), 1);
526 }).pipe(
527 Effect.provide(Layer.merge(ProviderContinuationRequests.layer, layerWorker)),
528 Effect.scoped,
529 );
530 });
531 });
532
533 it.effect(
534 "a project-disabled instance refuses a delegated-completion wake exactly once, acknowledges it, and never retries",
535 () => {
536 return Effect.gen(function* () {
537 const attempts = yield* Ref.make(0);
538 const cleared = yield* Ref.make(false);
539 const acknowledged = yield* Queue.unbounded<unknown>();
540 const layerThreads = Layer.mock(ThreadManagementService.ThreadManagementService)({
541 getThreadRecords: () => Effect.succeed(delegatedProjection()),
542 dispatch: (command) => {
543 if ((command as { type: string }).type === "message.dispatch") {
544 return Ref.update(attempts, (count) => count + 1).pipe(
545 Effect.andThen(
546 Effect.fail(
547 new ThreadManagementService.ThreadManagementProviderInstanceDisabledError({
548 projectId: ProjectId.make("project-provider-continuation-disabled"),
549 instanceId: ProviderInstanceId.make(
550 "instance-provider-continuation-disabled",
551 ),
552 }) as never,
553 ),
554 ),
555 );
556 }
557 return Queue.offer(acknowledged, command).pipe(Effect.as({} as never));
558 },
559 });
560 const layerWorker = ProviderContinuationService.layer.pipe(
561 Layer.provide(
562 Layer.mergeAll(IdAllocator.layer, ProviderContinuationRequests.layer, layerThreads),
563 ),
564 );
565
566 yield* Effect.gen(function* () {
567 const requests = yield* ProviderContinuationRequests.ProviderContinuationRequests;
568 yield* requests.offer({
569 threadId,
570 providerThreadId,
571 driver,
572 detail: null,
573 delivery: "message_text",
574 clearIfCurrent: () => Ref.set(cleared, true),
575 delegatedCompletion: {
576 parentRunId,
577 generation: 1,
578 messageId: delegatedMessageId,
579 },
580 });
581 yield* Effect.yieldNow;
582 assert.equal(yield* Ref.get(attempts), 1);
583 assert.isTrue(yield* Ref.get(cleared));
584
585 const acknowledgements = (yield* Queue.takeAll(acknowledged)) as ReadonlyArray<{
586 type: string;
587 taskId: string;
588 observedByRunId: string | null;
589 }>;
590 assert.deepEqual(
591 acknowledgements.map((command) => command.taskId),
592 ["node-provider-continuation-first", "node-provider-continuation-second"],
593 );
594 for (const command of acknowledgements) {
595 assert.equal(command.type, "delegated_task.completion-delivery.acknowledge");
596 assert.isNull(command.observedByRunId);
597 }
598
599 yield* TestClock.adjust("1 hour");
600 yield* Effect.yieldNow;
601 assert.equal(yield* Ref.get(attempts), 1);
602 assert.equal(yield* Queue.size(acknowledged), 0);
603 }).pipe(
604 Effect.provide(Layer.merge(ProviderContinuationRequests.layer, layerWorker)),
605 Effect.scoped,
606 );
607 });
608 },
609 );
610
611 it.effect(
612 "clears the adapter's sticky continuation flag when a non-delegated wake is refused",
613 () => {
614 return Effect.gen(function* () {
615 const requested = yield* Ref.make(true);
616 const layerThreads = Layer.mock(ThreadManagementService.ThreadManagementService)({
617 getThreadRecords: () => Effect.succeed(projection),
618 dispatch: () =>
619 Effect.fail(
620 new ThreadManagementService.ThreadManagementProviderInstanceDisabledError({
621 projectId: ProjectId.make("project-provider-continuation-disabled"),
622 instanceId: ProviderInstanceId.make("instance-provider-continuation-disabled"),
623 }) as never,
624 ),
625 });
626 const layerWorker = ProviderContinuationService.layer.pipe(
627 Layer.provide(
628 Layer.mergeAll(IdAllocator.layer, ProviderContinuationRequests.layer, layerThreads),
629 ),
630 );
631
632 // Mirrors the ACP adapter's own dispatchIfCurrent: on a failed effect
633 // it clears its sticky "continuation requested" flag before
634 // re-raising. If this service pre-recovered the failure before
635 // handing the effect here, this flag would stay stuck set and
636 // hasPendingBackgroundWork would never clear.
637 const dispatchIfCurrent = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
638 Effect.gen(function* () {
639 const exit = yield* Effect.exit(effect);
640 if (Exit.isFailure(exit)) {
641 yield* Ref.set(requested, false);
642 return yield* Effect.failCause(exit.cause);
643 }
644 return Option.some(exit.value);
645 });
646
647 yield* Effect.gen(function* () {
648 const requests = yield* ProviderContinuationRequests.ProviderContinuationRequests;
649 yield* requests.offer(request(dispatchIfCurrent));
650 yield* Effect.yieldNow;
651 yield* Effect.yieldNow;
652 assert.isFalse(
653 yield* Ref.get(requested),
654 "a disabled instance must still clear the adapter's sticky offer flag",
655 );
656 }).pipe(
657 Effect.provide(Layer.merge(ProviderContinuationRequests.layer, layerWorker)),
658 Effect.scoped,
659 );
660 });
661 },
662 );
663
664 it.effect(
665 "clears a sticky continuation offer for an adapter whose dispatchIfCurrent does not self-clear on failure",
666 () => {
667 return Effect.gen(function* () {
668 const wakeHeld = yield* Ref.make(true);
669 const layerThreads = Layer.mock(ThreadManagementService.ThreadManagementService)({
670 getThreadRecords: () => Effect.succeed(projection),
671 dispatch: () =>
672 Effect.fail(
673 new ThreadManagementService.ThreadManagementProviderInstanceDisabledError({
674 projectId: ProjectId.make("project-provider-continuation-disabled"),
675 instanceId: ProviderInstanceId.make("instance-provider-continuation-disabled"),
676 }) as never,
677 ),
678 });
679 const layerWorker = ProviderContinuationService.layer.pipe(
680 Layer.provide(
681 Layer.mergeAll(IdAllocator.layer, ProviderContinuationRequests.layer, layerThreads),
682 ),
683 );
684
685 // Mirrors the Muse adapter: dispatchIfCurrent forwards the dispatch
686 // effect without any failure handling of its own (unlike ACP or Pi),
687 // so only the explicit clearIfCurrent callback can clear the sticky
688 // "wake held" flag. Without it, a disabled instance leaves the flag
689 // set forever and no later background turn is ever offered.
690 const dispatchIfCurrent = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
691 Effect.asSome(effect);
692
693 yield* Effect.gen(function* () {
694 const requests = yield* ProviderContinuationRequests.ProviderContinuationRequests;
695 yield* requests.offer({
696 ...request(dispatchIfCurrent),
697 clearIfCurrent: () => Ref.set(wakeHeld, false),
698 });
699 yield* Effect.yieldNow;
700 yield* Effect.yieldNow;
701 assert.isFalse(
702 yield* Ref.get(wakeHeld),
703 "a disabled instance must clear the offer via the explicit callback " +
704 "when the adapter itself does not clear on dispatch failure",
705 );
706 }).pipe(
707 Effect.provide(Layer.merge(ProviderContinuationRequests.layer, layerWorker)),
708 Effect.scoped,
709 );
710 });
711 },
712 );
713
714 it.effect("keeps a Grok delegated completion queued instead of restarting active work", () => {
715 return Effect.gen(function* () {
716 const dispatched = yield* Queue.unbounded<unknown>();
717 yield* Effect.gen(function* () {
718 const requests = yield* ProviderContinuationRequests.ProviderContinuationRequests;
719 yield* requests.offer({
720 threadId,
721 providerThreadId,
722 driver: ProviderDriverKind.make("grok"),
723 detail: null,
724 delivery: "message_text",
725 delegatedCompletion: {
726 parentRunId,
727 generation: 1,
728 messageId: delegatedMessageId,
729 },
730 });
731 const command = (yield* Queue.take(dispatched)) as {
732 readonly dispatchMode: { readonly type: string };
733 };
734 assert.deepEqual(command.dispatchMode, { type: "queue_after_active" });
735 }).pipe(
736 Effect.provide(
737 layerTest({
738 dispatched,
739 getThreadRecords: () => Effect.succeed(delegatedProjection()),
740 }),
741 ),
742 Effect.scoped,
743 );
744 });
745 });
746
747 it.effect(
748 "drops stopped and disposed delegated completions instead of reviving them after recovery",
749 () => {
750 return Effect.gen(function* () {
751 for (const disposition of ["stopped", "disposed"] as const) {
752 const dispatched = yield* Queue.unbounded<unknown>();
753 yield* Effect.gen(function* () {
754 const requests = yield* ProviderContinuationRequests.ProviderContinuationRequests;
755 yield* requests.offer({
756 threadId,
757 providerThreadId,
758 driver,
759 detail: null,
760 delivery: "message_text",
761 delegatedCompletion: {
762 parentRunId,
763 generation: 1,
764 messageId: delegatedMessageId,
765 },
766 });
767 yield* Effect.yieldNow;
768 yield* Effect.yieldNow;
769 assert.isTrue(Option.isNone(yield* Queue.poll(dispatched)));
770 }).pipe(
771 Effect.provide(
772 layerTest({
773 dispatched,
774 getThreadRecords: () => Effect.succeed(delegatedProjection(disposition)),
775 }),
776 ),
777 Effect.scoped,
778 );
779 }
780 });
781 },
782 );
783
784 it.effect("does not redispatch a persisted delegated completion message during recovery", () => {
785 return Effect.gen(function* () {
786 const dispatched = yield* Queue.unbounded<unknown>();
787 yield* Effect.gen(function* () {
788 const requests = yield* ProviderContinuationRequests.ProviderContinuationRequests;
789 yield* requests.offer({
790 threadId,
791 providerThreadId,
792 driver,
793 detail: null,
794 delivery: "message_text",
795 delegatedCompletion: {
796 parentRunId,
797 generation: 1,
798 messageId: delegatedMessageId,
799 },
800 });
801 yield* Effect.yieldNow;
802 yield* Effect.yieldNow;
803 assert.isTrue(Option.isNone(yield* Queue.poll(dispatched)));
804 }).pipe(
805 Effect.provide(
806 layerTest({
807 dispatched,
808 getThreadRecords: () =>
809 Effect.succeed({
810 ...delegatedProjection(),
811 messages: [{ id: delegatedMessageId }],
812 } as unknown as OrchestrationV2ThreadProjection),
813 }),
814 ),
815 Effect.scoped,
816 );
817 });
818 });
819
820 it.effect("drops archived and deleted delegated completions during recovery", () => {
821 return Effect.gen(function* () {
822 for (const barrier of ["archivedAt", "deletedAt"] as const) {
823 const dispatched = yield* Queue.unbounded<unknown>();
824 yield* Effect.gen(function* () {
825 const requests = yield* ProviderContinuationRequests.ProviderContinuationRequests;
826 yield* requests.offer({
827 threadId,
828 providerThreadId,
829 driver,
830 detail: null,
831 delivery: "message_text",
832 delegatedCompletion: {
833 parentRunId,
834 generation: 1,
835 messageId: delegatedMessageId,
836 },
837 });
838 yield* Effect.yieldNow;
839 yield* Effect.yieldNow;
840 assert.isTrue(Option.isNone(yield* Queue.poll(dispatched)));
841 }).pipe(
842 Effect.provide(
843 layerTest({
844 dispatched,
845 getThreadRecords: () =>
846 Effect.succeed({
847 ...delegatedProjection(),
848 thread: {
849 ...projection.thread,
850 [barrier]: DateTime.makeUnsafe("2026-08-03T00:00:00.000Z"),
851 },
852 } as unknown as OrchestrationV2ThreadProjection),
853 }),
854 ),
855 Effect.scoped,
856 );
857 }
858 });
859 });
860
861 it.effect("dispatches a current request exactly once", () => {
862 return Effect.gen(function* () {
863 const dispatched = yield* Queue.unbounded<unknown>();
864 yield* Effect.gen(function* () {
865 const requests = yield* ProviderContinuationRequests.ProviderContinuationRequests;
866 yield* requests.offer(request());
867 yield* Queue.take(dispatched);
868 yield* Effect.yieldNow;
869 assert.isTrue(Option.isNone(yield* Queue.poll(dispatched)));
870 }).pipe(
871 Effect.provide(
872 layerTest({ dispatched, getThreadRecords: () => Effect.succeed(projection) }),
873 ),
874 Effect.scoped,
875 );
876 });
877 });
878
879 it.effect("queues a continuation behind an active user run", () => {
880 return Effect.gen(function* () {
881 const dispatched = yield* Queue.unbounded<unknown>();
882 yield* Effect.gen(function* () {
883 const requests = yield* ProviderContinuationRequests.ProviderContinuationRequests;
884 yield* requests.offer(request());
885 const command = yield* Queue.take(dispatched);
886 assert.deepEqual((command as { readonly dispatchMode?: unknown }).dispatchMode, {
887 type: "queue_after_active",
888 });
889 }).pipe(
890 Effect.provide(
891 layerTest({ dispatched, getThreadRecords: () => Effect.succeed(projection) }),
892 ),
893 Effect.scoped,
894 );
895 });
896 });
897
898 it.effect("drops a request invalidated before dispatch", () => {
899 return Effect.gen(function* () {
900 const dispatched = yield* Queue.unbounded<unknown>();
901 yield* Effect.gen(function* () {
902 const requests = yield* ProviderContinuationRequests.ProviderContinuationRequests;
903 const guard = yield* makeGuard();
904 const dispatchIfCurrent = yield* guard.capture;
905 yield* guard.invalidate;
906 yield* requests.offer(request(dispatchIfCurrent));
907 yield* Effect.yieldNow;
908 yield* Effect.yieldNow;
909 assert.isTrue(Option.isNone(yield* Queue.poll(dispatched)));
910 }).pipe(
911 Effect.provide(
912 layerTest({ dispatched, getThreadRecords: () => Effect.succeed(projection) }),
913 ),
914 Effect.scoped,
915 );
916 });
917 });
918
919 it.effect("drops a request invalidated while projection is blocked", () => {
920 return Effect.gen(function* () {
921 const dispatched = yield* Queue.unbounded<unknown>();
922 const projectionEntered = yield* Deferred.make<void>();
923 const releaseProjection = yield* Deferred.make<void>();
924 const guardCompleted = yield* Deferred.make<void>();
925 yield* Effect.gen(function* () {
926 const requests = yield* ProviderContinuationRequests.ProviderContinuationRequests;
927 const guard = yield* makeGuard(guardCompleted);
928 const dispatchIfCurrent = yield* guard.capture;
929 yield* requests.offer(request(dispatchIfCurrent));
930 yield* Deferred.await(projectionEntered);
931 yield* guard.invalidate;
932 yield* Deferred.succeed(releaseProjection, undefined);
933 yield* Deferred.await(guardCompleted);
934 assert.isTrue(Option.isNone(yield* Queue.poll(dispatched)));
935 }).pipe(
936 Effect.provide(
937 layerTest({
938 dispatched,
939 getThreadRecords: () =>
940 Deferred.succeed(projectionEntered, undefined).pipe(
941 Effect.andThen(Deferred.await(releaseProjection)),
942 Effect.as(projection),
943 ),
944 }),
945 ),
946 Effect.scoped,
947 );
948 });
949 });
950
951 it.effect("does not revive an old request when a later generation is current", () => {
952 return Effect.gen(function* () {
953 const dispatched = yield* Queue.unbounded<unknown>();
954 const firstProjectionEntered = yield* Deferred.make<void>();
955 const releaseFirstProjection = yield* Deferred.make<void>();
956 let projectionCalls = 0;
957 yield* Effect.gen(function* () {
958 const requests = yield* ProviderContinuationRequests.ProviderContinuationRequests;
959 const guard = yield* makeGuard();
960 const first = yield* guard.capture;
961 yield* requests.offer(request(first, "A"));
962 yield* Deferred.await(firstProjectionEntered);
963 const second = yield* guard.capture;
964 yield* requests.offer(request(second, "B"));
965 yield* Deferred.succeed(releaseFirstProjection, undefined);
966 const command = yield* Queue.take(dispatched);
967 assert.equal((command as { readonly text?: unknown }).text, "B");
968 yield* Effect.yieldNow;
969 assert.isTrue(Option.isNone(yield* Queue.poll(dispatched)));
970 }).pipe(
971 Effect.provide(
972 layerTest({
973 dispatched,
974 getThreadRecords: () => {
975 projectionCalls += 1;
976 return projectionCalls === 1
977 ? Deferred.succeed(firstProjectionEntered, undefined).pipe(
978 Effect.andThen(Deferred.await(releaseFirstProjection)),
979 Effect.as(projection),
980 )
981 : Effect.succeed(projection);
982 },
983 }),
984 ),
985 Effect.scoped,
986 );
987 });
988 });
989
990 it.effect("clears a sticky continuation offer when its thread is archived", () => {
991 return Effect.gen(function* () {
992 const dispatched = yield* Queue.unbounded<unknown>();
993 const cleared = yield* Ref.make(false);
994 yield* Effect.gen(function* () {
995 const requests = yield* ProviderContinuationRequests.ProviderContinuationRequests;
996 yield* requests.offer({
997 ...request(),
998 clearIfCurrent: () => Ref.set(cleared, true),
999 });
1000 for (let attempt = 0; attempt < 20 && !(yield* Ref.get(cleared)); attempt += 1) {
1001 yield* Effect.yieldNow;
1002 }
1003 assert.isTrue(yield* Ref.get(cleared));
1004 assert.isTrue(Option.isNone(yield* Queue.poll(dispatched)));
1005 }).pipe(
1006 Effect.provide(
1007 layerTest({
1008 dispatched,
1009 getThreadRecords: () =>
1010 Effect.succeed({
1011 ...projection,
1012 thread: {
1013 ...projection.thread,
1014 archivedAt: DateTime.makeUnsafe("2026-07-20T00:00:00.000Z"),
1015 },
1016 }),
1017 }),
1018 ),
1019 Effect.scoped,
1020 );
1021 });
1022 });
1023});