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

ProviderContinuationService.test.ts

595 lines22.3 KB

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 Effect from "effect/Effect";
15import * as Exit from "effect/Exit";
16import * as Layer from "effect/Layer";
17import * as Option from "effect/Option";
18import * as Queue from "effect/Queue";
19import * as Ref from "effect/Ref";
20import * as Semaphore from "effect/Semaphore";
21import * as TestClock from "effect/testing/TestClock";
22​
23import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
24import * as ProviderContinuationRequests from "@t3tools/provider-core/server/ProviderContinuationRequests";
25import * as ProviderContinuationService from "./ProviderContinuationService.ts";
26import * as ThreadManagementService from "./ThreadManagementService.ts";
27​
28const threadId = ThreadId.make("thread-provider-continuation");
29const providerThreadId = ProviderThreadId.make("provider-thread-continuation");
30const driver = ProviderDriverKind.make("continuation-test");
31const parentRunId = RunId.make("run-provider-continuation-parent");
32const delegatedMessageId = MessageId.make("message-provider-continuation-delegated");
33const projection = {
34 thread: { archivedAt: null, deletedAt: null },
35 messages: [],
36} as unknown as OrchestrationV2ThreadProjection;
37​
38const request = (
39 dispatchIfCurrent?: ProviderContinuationRequests.ProviderContinuationRequest["dispatchIfCurrent"],
40 detail: string | null = null,
41): ProviderContinuationRequests.ProviderContinuationRequest => ({
42 threadId,
43 providerThreadId,
44 driver,
45 detail,
46 ...(dispatchIfCurrent === undefined ? {} : { dispatchIfCurrent }),
47});
48​
49const delegatedProjection = (disposition: "open" | "stopped" | "disposed" = "open") =>
50 ({
51 ...projection,
52 runs: [
53 {
54 id: parentRunId,
55 delegatedCompletion: {
56 disposition,
57 nextGeneration: 2,
58 delivery: {
59 generation: 1,
60 messageId: delegatedMessageId,
61 taskIds: ["node-provider-continuation-first", "node-provider-continuation-second"],
62 },
63 },
64 },
65 ],
66 }) as unknown as OrchestrationV2ThreadProjection;
67​
68const makeGuard = Effect.fnUntraced(function* (completed?: Deferred.Deferred<void>) {
69 const generation = yield* Ref.make(0);
70 const permit = yield* Semaphore.make(1);
71 const capture = Effect.gen(function* () {
72 const captured = yield* Ref.updateAndGet(generation, (value) => value + 1);
73 return <A, E, R>(effect: Effect.Effect<A, E, R>) =>
74 permit
75 .withPermit(
76 Effect.gen(function* () {
77 if ((yield* Ref.get(generation)) !== captured) return Option.none();
78 return Option.some(yield* effect);
79 }),
80 )
81 .pipe(
82 completed === undefined
83 ? (effect) => effect
84 : Effect.ensuring(Deferred.succeed(completed, undefined)),
85 );
86 });
87 return {
88 capture,
89 invalidate: permit.withPermit(Ref.update(generation, (value) => value + 1)),
90 };
91});
92​
93function layerTest(input: {
94 readonly dispatched: Queue.Queue<unknown>;
95 readonly getThreadRecords: () => Effect.Effect<OrchestrationV2ThreadProjection>;
96}) {
97 const layerThreads = Layer.mock(ThreadManagementService.ThreadManagementService)({
98 getThreadRecords: input.getThreadRecords,
99 dispatch: (command) => Queue.offer(input.dispatched, command).pipe(Effect.as({} as never)),
100 });
101 const layerWorker = ProviderContinuationService.layer.pipe(
102 Layer.provide(
103 Layer.mergeAll(IdAllocator.layer, ProviderContinuationRequests.layer, layerThreads),
104 ),
105 );
106 return Layer.merge(ProviderContinuationRequests.layer, layerWorker);
108​
109describe("ProviderContinuationService", () => {
110 it.effect("recovers an unaccepted persisted steer using the same delivery identity", () =>
111 Effect.gen(function* () {
112 const dispatched = yield* Queue.unbounded<unknown>();
113 const original = delegatedProjection();
114 const interruptedRunId = RunId.make("interrupted-mailbox-run");
115 const recovered = {
116 ...original,
117 runs: [
118 ...original.runs,
119 {
120 id: interruptedRunId,
121 status: "interrupted",
122 userMessageId: MessageId.make("original-user-input"),
123 },
124 ],
125 messages: [
126 {
127 id: delegatedMessageId,
128 runId: interruptedRunId,
129 delegatedCompletion: { parentRunId, generation: 1, taskIds: [] },
130 },
131 ],
132 } as unknown as OrchestrationV2ThreadProjection;
133 yield* Effect.gen(function* () {
134 const requests = yield* ProviderContinuationRequests.ProviderContinuationRequests;
135 yield* requests.offer({
136 threadId,
137 providerThreadId,
138 driver,
139 detail: null,
140 delivery: "message_text",
141 delegatedCompletion: { parentRunId, generation: 1, messageId: delegatedMessageId },
142 });
143 const command = (yield* Queue.take(dispatched)) as {
144 messageId: MessageId;
145 delegatedCompletion: { generation: number; taskIds: readonly string[] };
146 };
147 assert.equal(command.messageId, delegatedMessageId);
148 assert.equal(command.delegatedCompletion.generation, 1);
149 assert.equal(command.delegatedCompletion.taskIds.length, 2);
150 }).pipe(
151 Effect.provide(
152 layerTest({ dispatched, getThreadRecords: () => Effect.succeed(recovered) }),
153 ),
154 Effect.scoped,
155 );
156 }),
157 );
158​
159 it.effect("delivers a message_text wake as a real prompt, not a buffered wake", () => {
160 return Effect.gen(function* () {
161 const dispatched = yield* Queue.unbounded<unknown>();
162 yield* Effect.gen(function* () {
163 const requests = yield* ProviderContinuationRequests.ProviderContinuationRequests;
164 yield* requests.offer({
165 threadId,
166 providerThreadId,
167 driver,
168 detail: "Delegated task completed.",
169 notification: {
170 source: { kind: "monitor" },
171 outcome: "updated",
172 summary: "Monitor updated",
173 },
174 delivery: "message_text",
175 });
176 const command = (yield* Queue.take(dispatched)) as {
177 readonly creationSource: string;
178 readonly text: string;
179 readonly notification: OrchestrationV2Notification;
180 };
181 // An app-owned child buffers nothing in the adapter, so this text is
182 // the whole wake. Marking it "provider" would make ClaudeAdapterV2
183 // drop it and settle the turn having prompted nothing.
184 assert.notEqual(command.creationSource, "provider");
185 assert.equal(command.creationSource, "server");
186 assert.equal(command.text, "Delegated task completed.");
187 assert.deepEqual(command.notification, {
188 source: { kind: "monitor" },
189 outcome: "updated",
190 summary: "Monitor updated",
191 });
192 }).pipe(
193 Effect.provide(
194 layerTest({ dispatched, getThreadRecords: () => Effect.succeed(projection) }),
195 ),
196 Effect.scoped,
197 );
198 });
199 });
200​
201 it.effect("dispatches a current delegated completion as one server-owned queued message", () => {
202 return Effect.gen(function* () {
203 const dispatched = yield* Queue.unbounded<unknown>();
204 yield* Effect.gen(function* () {
205 const requests = yield* ProviderContinuationRequests.ProviderContinuationRequests;
206 yield* requests.offer({
207 threadId,
208 providerThreadId,
209 driver,
210 detail: null,
211 delivery: "message_text",
212 delegatedCompletion: {
213 parentRunId,
214 generation: 1,
215 messageId: delegatedMessageId,
216 },
217 });
218 const command = (yield* Queue.take(dispatched)) as {
219 readonly createdBy: string;
220 readonly creationSource: string;
221 readonly delegatedCompletion: {
222 readonly generation: number;
223 readonly parentRunId: RunId;
224 readonly taskIds: ReadonlyArray<string>;
225 };
226 readonly dispatchMode: { readonly type: string };
227 readonly messageId: MessageId;
228 readonly text: string;
229 };
230 assert.equal(command.createdBy, "agent");
231 assert.equal(command.creationSource, "server");
232 assert.deepEqual(command.dispatchMode, { type: "queue_after_active" });
233 assert.equal(command.messageId, delegatedMessageId);
234 assert.equal(command.delegatedCompletion.parentRunId, parentRunId);
235 assert.equal(command.delegatedCompletion.generation, 1);
236 assert.deepEqual(command.delegatedCompletion.taskIds, [
237 "node-provider-continuation-first",
238 "node-provider-continuation-second",
239 ]);
240 assert.include(command.text, "task_status");
241 }).pipe(
242 Effect.provide(
243 layerTest({
244 dispatched,
245 getThreadRecords: () => Effect.succeed(delegatedProjection()),
246 }),
247 ),
248 Effect.scoped,
249 );
250 });
251 });
252​
253 it.effect(
254 "a project-disabled instance refuses a delegated-completion wake exactly once, acknowledges it, and never retries",
255 () => {
256 return Effect.gen(function* () {
257 const attempts = yield* Ref.make(0);
258 const cleared = yield* Ref.make(false);
259 const acknowledged = yield* Queue.unbounded<unknown>();
260 const layerThreads = Layer.mock(ThreadManagementService.ThreadManagementService)({
261 getThreadRecords: () => Effect.succeed(delegatedProjection()),
262 dispatch: (command) => {
263 if ((command as { type: string }).type === "message.dispatch") {
264 return Ref.update(attempts, (count) => count + 1).pipe(
265 Effect.andThen(
266 Effect.fail(
267 new ThreadManagementService.ThreadManagementProviderInstanceDisabledError({
268 projectId: ProjectId.make("project-provider-continuation-disabled"),
269 instanceId: ProviderInstanceId.make(
270 "instance-provider-continuation-disabled",
271 ),
272 }) as never,
273 ),
274 ),
275 );
276 }
277 return Queue.offer(acknowledged, command).pipe(Effect.as({} as never));
278 },
279 });
280 const layerWorker = ProviderContinuationService.layer.pipe(
281 Layer.provide(
282 Layer.mergeAll(IdAllocator.layer, ProviderContinuationRequests.layer, layerThreads),
283 ),
284 );
285​
286 yield* Effect.gen(function* () {
287 const requests = yield* ProviderContinuationRequests.ProviderContinuationRequests;
288 yield* requests.offer({
289 threadId,
290 providerThreadId,
291 driver,
292 detail: null,
293 delivery: "message_text",
294 clearIfCurrent: () => Ref.set(cleared, true),
295 delegatedCompletion: {
296 parentRunId,
297 generation: 1,
298 messageId: delegatedMessageId,
299 },
300 });
301 yield* Effect.yieldNow;
302 assert.equal(yield* Ref.get(attempts), 1);
303 assert.isTrue(yield* Ref.get(cleared));
304​
305 const acknowledgements = (yield* Queue.takeAll(acknowledged)) as ReadonlyArray<{
306 type: string;
307 taskId: string;
308 observedByRunId: string | null;
309 }>;
310 assert.deepEqual(
311 acknowledgements.map((command) => command.taskId),
312 ["node-provider-continuation-first", "node-provider-continuation-second"],
313 );
314 for (const command of acknowledgements) {
315 assert.equal(command.type, "delegated_task.completion-delivery.acknowledge");
316 assert.isNull(command.observedByRunId);
317 }
318​
319 yield* TestClock.adjust("1 hour");
320 yield* Effect.yieldNow;
321 assert.equal(yield* Ref.get(attempts), 1);
322 assert.equal(yield* Queue.size(acknowledged), 0);
323 }).pipe(
324 Effect.provide(Layer.merge(ProviderContinuationRequests.layer, layerWorker)),
325 Effect.scoped,
326 );
327 });
328 },
329 );
330​
331 it.effect(
332 "clears the adapter's sticky continuation flag when a non-delegated wake is refused",
333 () => {
334 return Effect.gen(function* () {
335 const requested = yield* Ref.make(true);
336 const layerThreads = Layer.mock(ThreadManagementService.ThreadManagementService)({
337 getThreadRecords: () => Effect.succeed(projection),
338 dispatch: () =>
339 Effect.fail(
340 new ThreadManagementService.ThreadManagementProviderInstanceDisabledError({
341 projectId: ProjectId.make("project-provider-continuation-disabled"),
342 instanceId: ProviderInstanceId.make("instance-provider-continuation-disabled"),
343 }) as never,
344 ),
345 });
346 const layerWorker = ProviderContinuationService.layer.pipe(
347 Layer.provide(
348 Layer.mergeAll(IdAllocator.layer, ProviderContinuationRequests.layer, layerThreads),
349 ),
350 );
351​
352 // Mirrors the ACP adapter's own dispatchIfCurrent: on a failed effect
353 // it clears its sticky "continuation requested" flag before
354 // re-raising. If this service pre-recovered the failure before
355 // handing the effect here, this flag would stay stuck set and
356 // hasPendingBackgroundWork would never clear.
357 const dispatchIfCurrent = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
358 Effect.gen(function* () {
359 const exit = yield* Effect.exit(effect);
360 if (Exit.isFailure(exit)) {
361 yield* Ref.set(requested, false);
362 return yield* Effect.failCause(exit.cause);
363 }
364 return Option.some(exit.value);
365 });
366​
367 yield* Effect.gen(function* () {
368 const requests = yield* ProviderContinuationRequests.ProviderContinuationRequests;
369 yield* requests.offer(request(dispatchIfCurrent));
370 yield* Effect.yieldNow;
371 yield* Effect.yieldNow;
372 assert.isFalse(
373 yield* Ref.get(requested),
374 "a disabled instance must still clear the adapter's sticky offer flag",
375 );
376 }).pipe(
377 Effect.provide(Layer.merge(ProviderContinuationRequests.layer, layerWorker)),
378 Effect.scoped,
379 );
380 });
381 },
382 );
383​
384 it.effect(
385 "clears a sticky continuation offer for an adapter whose dispatchIfCurrent does not self-clear on failure",
386 () => {
387 return Effect.gen(function* () {
388 const wakeHeld = yield* Ref.make(true);
389 const layerThreads = Layer.mock(ThreadManagementService.ThreadManagementService)({
390 getThreadRecords: () => Effect.succeed(projection),
391 dispatch: () =>
392 Effect.fail(
393 new ThreadManagementService.ThreadManagementProviderInstanceDisabledError({
394 projectId: ProjectId.make("project-provider-continuation-disabled"),
395 instanceId: ProviderInstanceId.make("instance-provider-continuation-disabled"),
396 }) as never,
397 ),
398 });
399 const layerWorker = ProviderContinuationService.layer.pipe(
400 Layer.provide(
401 Layer.mergeAll(IdAllocator.layer, ProviderContinuationRequests.layer, layerThreads),
402 ),
403 );
404​
405 // Mirrors the Muse adapter: dispatchIfCurrent forwards the dispatch
406 // effect without any failure handling of its own (unlike ACP or Pi),
407 // so only the explicit clearIfCurrent callback can clear the sticky
408 // "wake held" flag. Without it, a disabled instance leaves the flag
409 // set forever and no later background turn is ever offered.
410 const dispatchIfCurrent = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
411 Effect.asSome(effect);
412​
413 yield* Effect.gen(function* () {
414 const requests = yield* ProviderContinuationRequests.ProviderContinuationRequests;
415 yield* requests.offer({
416 ...request(dispatchIfCurrent),
417 clearIfCurrent: () => Ref.set(wakeHeld, false),
418 });
419 yield* Effect.yieldNow;
420 yield* Effect.yieldNow;
421 assert.isFalse(
422 yield* Ref.get(wakeHeld),
423 "a disabled instance must clear the offer via the explicit callback " +
424 "when the adapter itself does not clear on dispatch failure",
425 );
426 }).pipe(
427 Effect.provide(Layer.merge(ProviderContinuationRequests.layer, layerWorker)),
428 Effect.scoped,
429 );
430 });
431 },
432 );
433​
434 it.effect(
435 "drops stopped and disposed delegated completions instead of reviving them after recovery",
436 () => {
437 return Effect.gen(function* () {
438 for (const disposition of ["stopped", "disposed"] as const) {
439 const dispatched = yield* Queue.unbounded<unknown>();
440 yield* Effect.gen(function* () {
441 const requests = yield* ProviderContinuationRequests.ProviderContinuationRequests;
442 yield* requests.offer({
443 threadId,
444 providerThreadId,
445 driver,
446 detail: null,
447 delivery: "message_text",
448 delegatedCompletion: {
449 parentRunId,
450 generation: 1,
451 messageId: delegatedMessageId,
452 },
453 });
454 yield* Effect.yieldNow;
455 yield* Effect.yieldNow;
456 assert.isTrue(Option.isNone(yield* Queue.poll(dispatched)));
457 }).pipe(
458 Effect.provide(
459 layerTest({
460 dispatched,
461 getThreadRecords: () => Effect.succeed(delegatedProjection(disposition)),
462 }),
463 ),
464 Effect.scoped,
465 );
466 }
467 });
468 },
469 );
470​
471 it.effect("does not redispatch a persisted delegated completion message during recovery", () => {
472 return Effect.gen(function* () {
473 const dispatched = yield* Queue.unbounded<unknown>();
474 yield* Effect.gen(function* () {
475 const requests = yield* ProviderContinuationRequests.ProviderContinuationRequests;
476 yield* requests.offer({
477 threadId,
478 providerThreadId,
479 driver,
480 detail: null,
481 delivery: "message_text",
482 delegatedCompletion: {
483 parentRunId,
484 generation: 1,
485 messageId: delegatedMessageId,
486 },
487 });
488 yield* Effect.yieldNow;
489 yield* Effect.yieldNow;
490 assert.isTrue(Option.isNone(yield* Queue.poll(dispatched)));
491 }).pipe(
492 Effect.provide(
493 layerTest({
494 dispatched,
495 getThreadRecords: () =>
496 Effect.succeed({
497 ...delegatedProjection(),
498 messages: [{ id: delegatedMessageId }],
499 } as unknown as OrchestrationV2ThreadProjection),
500 }),
501 ),
502 Effect.scoped,
503 );
504 });
505 });
506​
507 it.effect("dispatches a current request exactly once", () => {
508 return Effect.gen(function* () {
509 const dispatched = yield* Queue.unbounded<unknown>();
510 yield* Effect.gen(function* () {
511 const requests = yield* ProviderContinuationRequests.ProviderContinuationRequests;
512 yield* requests.offer(request());
513 yield* Queue.take(dispatched);
514 yield* Effect.yieldNow;
515 assert.isTrue(Option.isNone(yield* Queue.poll(dispatched)));
516 }).pipe(
517 Effect.provide(
518 layerTest({ dispatched, getThreadRecords: () => Effect.succeed(projection) }),
519 ),
520 Effect.scoped,
521 );
522 });
523 });
524​
525 it.effect("drops a request invalidated while projection is blocked", () => {
526 return Effect.gen(function* () {
527 const dispatched = yield* Queue.unbounded<unknown>();
528 const projectionEntered = yield* Deferred.make<void>();
529 const releaseProjection = yield* Deferred.make<void>();
530 const guardCompleted = yield* Deferred.make<void>();
531 yield* Effect.gen(function* () {
532 const requests = yield* ProviderContinuationRequests.ProviderContinuationRequests;
533 const guard = yield* makeGuard(guardCompleted);
534 const dispatchIfCurrent = yield* guard.capture;
535 yield* requests.offer(request(dispatchIfCurrent));
536 yield* Deferred.await(projectionEntered);
537 yield* guard.invalidate;
538 yield* Deferred.succeed(releaseProjection, undefined);
539 yield* Deferred.await(guardCompleted);
540 assert.isTrue(Option.isNone(yield* Queue.poll(dispatched)));
541 }).pipe(
542 Effect.provide(
543 layerTest({
544 dispatched,
545 getThreadRecords: () =>
546 Deferred.succeed(projectionEntered, undefined).pipe(
547 Effect.andThen(Deferred.await(releaseProjection)),
548 Effect.as(projection),
549 ),
550 }),
551 ),
552 Effect.scoped,
553 );
554 });
555 });
556​
557 it.effect("does not revive an old request when a later generation is current", () => {
558 return Effect.gen(function* () {
559 const dispatched = yield* Queue.unbounded<unknown>();
560 const firstProjectionEntered = yield* Deferred.make<void>();
561 const releaseFirstProjection = yield* Deferred.make<void>();
562 let projectionCalls = 0;
563 yield* Effect.gen(function* () {
564 const requests = yield* ProviderContinuationRequests.ProviderContinuationRequests;
565 const guard = yield* makeGuard();
566 const first = yield* guard.capture;
567 yield* requests.offer(request(first, "A"));
568 yield* Deferred.await(firstProjectionEntered);
569 const second = yield* guard.capture;
570 yield* requests.offer(request(second, "B"));
571 yield* Deferred.succeed(releaseFirstProjection, undefined);
572 const command = yield* Queue.take(dispatched);
573 assert.equal((command as { readonly text?: unknown }).text, "B");
574 yield* Effect.yieldNow;
575 assert.isTrue(Option.isNone(yield* Queue.poll(dispatched)));
576 }).pipe(
577 Effect.provide(
578 layerTest({
579 dispatched,
580 getThreadRecords: () => {
581 projectionCalls += 1;
582 return projectionCalls === 1
583 ? Deferred.succeed(firstProjectionEntered, undefined).pipe(
584 Effect.andThen(Deferred.await(releaseFirstProjection)),
585 Effect.as(projection),
586 )
587 : Effect.succeed(projection);
588 },
589 }),
590 ),
591 Effect.scoped,
592 );
593 });
594 });
595});