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

contextWindow.test.ts

256 lines8.5 KB

1import { describe, expect, it } from "vite-plus/test";
2import { OrchestrationV2ProviderTurnTokenUsage } from "@t3tools/contracts";
3import * as Schema from "effect/Schema";
4import { formatContextWindowCompactionMessage } from "../components/chat/ContextWindowMeter.logic";
5import * as DateTime from "effect/DateTime";
6import {
7 ContextTransferId,
8 ProviderDriverKind,
9 ProviderInstanceId,
10 RunId,
11 ThreadId,
12} from "@t3tools/contracts";
13import { makeThreadProjectionFixture } from "../test-fixtures";
14import { shouldOfferResumeCompaction } from "../components/chat/ContextWindowMeter.logic";
15import {
16 deriveLatestContextWindowSnapshot,
17 formatContextWindowTokens,
18 latestProviderTurnTokenUsage,
19} from "./contextWindow";
20​
21const decodeTokenUsage = Schema.decodeSync(OrchestrationV2ProviderTurnTokenUsage);
22​
23describe("V2 context window presentation", () => {
24 it("uses retained compaction token data when available", () => {
25 const snapshot = deriveLatestContextWindowSnapshot([
26 {
27 item: {
28 id: "compaction-1" as never,
29 threadId: "thread-1" as never,
30 runId: null,
31 nodeId: null,
32 providerThreadId: null,
33 providerTurnId: null,
34 nativeItemRef: null,
35 parentItemId: null,
36 ordinal: 1,
37 status: "completed",
38 title: null,
39 startedAt: null,
40 completedAt: null,
41 updatedAt: DateTime.makeUnsafe("2026-06-20T00:00:00.000Z"),
42 type: "compaction",
43 driver: null,
44 beforeTokenCount: 10_000,
45 afterTokenCount: 2_000,
46 },
47 },
48 ]);
49 expect(snapshot?.usedTokens).toBe(2_000);
50 expect(snapshot?.totalProcessedTokens).toBe(10_000);
51 });
52​
53 it("prefers current provider usage and preserves ACP cost", () => {
54 const snapshot = deriveLatestContextWindowSnapshot([], undefined, {
55 contextUsage: {
56 usedTokens: 2_500,
57 maxTokens: 10_000,
58 cost: { amount: 0.42, currency: "USD" },
59 },
60 updatedAt: DateTime.makeUnsafe("2026-08-23T00:00:00.000Z"),
61 });
62​
63 expect(snapshot).toMatchObject({
64 usedTokens: 2_500,
65 maxTokens: 10_000,
66 remainingTokens: 7_500,
67 usedPercentage: 25,
68 cost: { amount: 0.42, currency: "USD" },
69 });
70 });
71​
72 it("formats compact token values", () => {
73 expect(formatContextWindowTokens(1_500)).toBe("1.5k");
74 });
75​
76 it.each([
77 [999_499, "999k"],
78 [999_500, "1m"],
79 [999_999, "1m"],
80 [1_000_000, "1m"],
81 [1_100_000, "1.1m"],
82 ])("formats %d tokens as %s at the million boundary", (tokens, expected) => {
83 expect(formatContextWindowTokens(tokens)).toBe(expected);
84 });
85});
86​
87describe("live provider-turn usage (#8144)", () => {
88 it("prefers the provider's live report over compaction items", () => {
89 const usage = decodeTokenUsage({
90 usedTokens: 42_000,
91 maxTokens: 200_000,
92 inputTokens: 40_000,
93 outputTokens: 2_000,
94 autoCompactThreshold: 150_000,
95 updatedAt: "2026-08-27T00:00:00.000Z",
96 });
97 const snapshot = deriveLatestContextWindowSnapshot([], usage);
98 expect(snapshot).not.toBeNull();
99 expect(snapshot?.usedTokens).toBe(42_000);
100 expect(snapshot?.maxTokens).toBe(200_000);
101 expect(snapshot?.remainingTokens).toBe(158_000);
102 expect(snapshot?.usedPercentage).toBe(21);
103 expect(snapshot?.autoCompactThreshold).toBe(150_000);
104 expect(
105 formatContextWindowCompactionMessage("Claude Sonnet 4.6", snapshot?.autoCompactThreshold),
106 ).toBe("Compacts automatically at about 150,000 tokens.");
107 });
108​
109 it("handles a report without a known context window", () => {
110 const snapshot = deriveLatestContextWindowSnapshot([], {
111 usedTokens: 42_000,
112 updatedAt: "2026-08-27T00:00:00.000Z",
113 });
114 expect(snapshot?.maxTokens).toBeNull();
115 expect(snapshot?.usedPercentage).toBeNull();
116 expect(snapshot?.autoCompactThreshold).toBeNull();
117 expect(formatContextWindowCompactionMessage(null, snapshot?.autoCompactThreshold)).toBe(
118 "Context compacts automatically when needed.",
119 );
120 });
121});
122​
123describe("latestProviderTurnTokenUsage", () => {
124 it("picks the newest report, not the last turn in snapshot order", () => {
125 const usage = (usedTokens: number, updatedAt: string) => ({
126 tokenUsage: { usedTokens, updatedAt },
127 });
128 const latest = latestProviderTurnTokenUsage([
129 usage(300_000, "2026-06-20T12:00:00.000Z"),
130 {},
131 usage(90_000, "2026-06-20T09:00:00.000Z"),
132 ]);
133 expect(latest?.usedTokens).toBe(300_000);
134 });
135​
136 const sourceUsage = {
137 usedTokens: 513_000,
138 maxTokens: 1_000_000,
139 promptCacheTtlMs: 5 * 60_000,
140 updatedAt: "2026-10-19T12:00:00.000Z",
141 };
142 function forkProjection() {
143 const projection = makeThreadProjectionFixture();
144 const sourceThreadId = ThreadId.make("parent");
145 const runId = RunId.make("fork-point");
146 return {
147 thread: {
148 ...projection.thread,
149 forkedFrom: { type: "run" as const, threadId: sourceThreadId, runId },
150 },
151 contextTransfers: [
152 {
153 id: ContextTransferId.make("fork-transfer"),
154 type: "fork" as const,
155 sourceThreadId,
156 targetThreadId: projection.thread.id,
157 sourcePoint: { threadId: sourceThreadId, runId },
158 basePoint: null,
159 sourceProviderInstanceId: projection.thread.modelSelection.instanceId,
160 sourceTokenUsage: sourceUsage,
161 targetProviderInstanceId: null,
162 targetRunId: null,
163 status: "pending" as const,
164 resolution: null,
165 createdBy: "user" as const,
166 error: null,
167 createdAt: projection.updatedAt,
168 updatedAt: projection.updatedAt,
169 consumedAt: null,
170 },
171 ],
172 };
173 }
174​
175 it("keeps fork-point context and its cache expiry before the fork reports usage", () => {
176 const usage = latestProviderTurnTokenUsage([], forkProjection());
177 expect(usage).toEqual(sourceUsage);
178 const snapshot = deriveLatestContextWindowSnapshot([], usage);
179 expect(snapshot?.usedTokens).toBe(513_000);
180 expect(
181 shouldOfferResumeCompaction({
182 provider: "claudeAgent",
183 usedTokens: snapshot?.usedTokens,
184 updatedAt: snapshot?.updatedAt,
185 promptCacheTtlMs: usage?.promptCacheTtlMs,
186 now: "2026-10-19T12:06:00.000Z",
187 }),
188 ).toBe(true);
189 });
190​
191 it("replaces inherited usage with the fork's own report", () => {
192 const tokenUsage = { usedTokens: 42_000, updatedAt: "2026-10-19T12:10:00.000Z" };
193 expect(latestProviderTurnTokenUsage([{ tokenUsage }], forkProjection())).toEqual(tokenUsage);
194 });
195​
196 it.each([0, 42_000])(
197 "prefers target provider-thread usage of %d tokens over inherited usage",
198 (usedTokens) => {
199 const providerThread = {
200 contextUsage: {
201 usedTokens,
202 maxTokens: 200_000,
203 cost: { amount: 0.42, currency: "USD" },
204 },
205 updatedAt: DateTime.makeUnsafe("2026-10-19T12:10:00.000Z"),
206 };
207 const usage = latestProviderTurnTokenUsage([], forkProjection(), providerThread);
208 const snapshot = deriveLatestContextWindowSnapshot([], usage, providerThread);
209​
210 expect(snapshot).toMatchObject({
211 usedTokens,
212 maxTokens: 200_000,
213 cost: { amount: 0.42, currency: "USD" },
214 updatedAt: "2026-10-19T12:10:00.000Z",
215 });
216 },
217 );
218​
219 it("keeps the fallback after a native fork is consumed", () => {
220 const projection = forkProjection();
221 const transfer = projection.contextTransfers[0]!;
222 expect(
223 latestProviderTurnTokenUsage([], {
224 ...projection,
225 contextTransfers: [
226 {
227 ...transfer,
228 status: "consumed",
229 resolution: {
230 strategy: "native_fork",
231 providerThreadRef: {
232 driver: ProviderDriverKind.make("claudeAgent"),
233 nativeId: "fork",
234 strength: "strong",
235 },
236 },
237 },
238 ],
239 }),
240 ).toEqual(sourceUsage);
241 });
242​
243 it("does not reuse usage for portable handoffs, different providers, or missing history", () => {
244 const projection = forkProjection();
245 const transfer = projection.contextTransfers[0]!;
246 for (const contextTransfers of [
247 [],
248 [{ ...transfer, sourceTokenUsage: undefined }],
249 [{ ...transfer, status: "resolved_portable" as const }],
250 [{ ...transfer, sourceProviderInstanceId: ProviderInstanceId.make("other") }],
251 [{ ...transfer, sourcePoint: { ...transfer.sourcePoint, runId: RunId.make("later") } }],
252 ]) {
253 expect(latestProviderTurnTokenUsage([], { ...projection, contextTransfers })).toBeNull();
254 }
255 });
256});