Open History to see the last commit
1import { describe, expect, it } from "@effect/vitest";
2import type { OrchestrationThreadActivity } from "@t3tools/contracts";
3
4import { threadContextReachedLimit } from "./contextLimit.ts";
5
6function contextActivity(
7 usedTokens: number,
8 options: { readonly id?: string; readonly sequence?: number; readonly turnId?: string } = {},
9): OrchestrationThreadActivity {
10 return {
11 id: options.id ?? `usage-${usedTokens}`,
12 createdAt: "2026-08-31T00:00:00.000Z",
13 tone: "info",
14 kind: "context-window.updated",
15 summary: "Context window updated",
16 payload: { usedTokens, maxTokens: 400_000 },
17 turnId: options.turnId ?? null,
18 ...(options.sequence === undefined ? {} : { sequence: options.sequence }),
19 } as OrchestrationThreadActivity;
20}
21
22describe("threadContextReachedLimit", () => {
23 it("does not apply a limit before server configuration loads", () => {
24 expect(threadContextReachedLimit([contextActivity(300_000)], undefined)).toBe(false);
25 });
26
27 it("uses the configured limit", () => {
28 expect(threadContextReachedLimit([contextActivity(100_000)], 100_000)).toBe(true);
29 expect(threadContextReachedLimit([contextActivity(99_999)], 100_000)).toBe(false);
30 });
31
32 it("uses lifecycle order when persisted activities arrive out of order", () => {
33 const latest = contextActivity(120_000, { id: "latest", sequence: 20 });
34 const stale = contextActivity(300_000, { id: "stale", sequence: 10 });
35 const latestOverLimit = contextActivity(300_000, {
36 id: "latest-over-limit",
37 sequence: 30,
38 });
39
40 expect(threadContextReachedLimit([latest, stale], 250_000)).toBe(false);
41 expect(threadContextReachedLimit([stale, latest], 250_000)).toBe(false);
42 expect(threadContextReachedLimit([latestOverLimit, latest], 250_000)).toBe(true);
43 });
44
45 it("allows sending after a later compaction lowers context usage", () => {
46 const beforeCompaction = contextActivity(300_000, {
47 id: "before-compaction",
48 sequence: 10,
49 turnId: "turn-before-compaction",
50 });
51 const afterCompaction = contextActivity(20_000, {
52 id: "after-compaction",
53 sequence: 30,
54 turnId: "turn-after-compaction",
55 });
56
57 expect(threadContextReachedLimit([afterCompaction, beforeCompaction], 250_000)).toBe(false);
58 });
59});