Open History to see the last commit
1import type { ProviderSession, ThreadId } from "@t3tools/contracts";
2import { describe, expect, it } from "@effect/vitest";
3
4import {
5 evaluateTurnStartLimits,
6 evaluateHandoverStartLimits,
7 MAX_CONCURRENT_PROVIDER_TURNS,
8} from "./ConcurrentTurnPolicy.ts";
9
10const threadId = "thread-limited" as ThreadId;
11
12function session(index: number, status: ProviderSession["status"] = "running"): ProviderSession {
13 return {
14 threadId: `thread-${index}` as ThreadId,
15 status,
16 } as ProviderSession;
17}
18
19describe("evaluateTurnStartLimits", () => {
20 it("allows handover generation at the context ceiling", () => {
21 expect(evaluateHandoverStartLimits({ sessions: [] })).toBeUndefined();
22 });
23
24 it("counts each active thread once across sessions and reservations", () => {
25 const violation = evaluateTurnStartLimits({
26 threadId: "new-thread" as ThreadId,
27 sessions: [session(1), session(1), session(2)],
28 reservedTurnThreadIds: ["thread-1" as ThreadId, "thread-3" as ThreadId],
29 });
30
31 expect(violation).toBeUndefined();
32 });
33
34 it("blocks a new turn when the global concurrency ceiling is full", () => {
35 const violation = evaluateTurnStartLimits({
36 threadId,
37 sessions: Array.from({ length: MAX_CONCURRENT_PROVIDER_TURNS }, (_, index) => session(index)),
38 });
39
40 expect(violation?.code).toBe("concurrent-turn-limit");
41 });
42
43 it("counts a turn reservation before the provider reports it as running", () => {
44 const violation = evaluateTurnStartLimits({
45 threadId,
46 sessions: Array.from({ length: MAX_CONCURRENT_PROVIDER_TURNS - 1 }, (_, index) =>
47 session(index),
48 ),
49 reservedTurnThreadIds: ["reserved-thread" as ThreadId],
50 });
51
52 expect(violation?.code).toBe("concurrent-turn-limit");
53 });
54
55 it("counts handover reservations against the shared provider-work ceiling", () => {
56 const violation = evaluateTurnStartLimits({
57 threadId,
58 sessions: Array.from({ length: MAX_CONCURRENT_PROVIDER_TURNS - 1 }, (_, index) =>
59 session(index),
60 ),
61 reservedHandoverCount: 1,
62 });
63
64 expect(violation?.code).toBe("concurrent-turn-limit");
65 });
66
67 it("does not count ready sessions and permits an already-running thread", () => {
68 const sessions = [
69 ...Array.from({ length: MAX_CONCURRENT_PROVIDER_TURNS }, (_, index) => session(index)),
70 { ...session(99), threadId, status: "running" as const },
71 session(100, "ready"),
72 ];
73
74 expect(evaluateTurnStartLimits({ threadId, sessions })).toBeUndefined();
75 });
76});