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