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

usageTranscripts.test.ts

251 lines8.9 KB

1import { describe, expect, it } from "@effect/vitest";
2​
3import {
4 initialCodexScanState,
5 parseClaudeLine,
6 parseCodexLine,
7 totalTokens,
8} from "./usageTranscripts.ts";
9​
10/** Shaped after a real Claude Code assistant record. */
11function claudeLine(overrides: {
12 messageId: string;
13 contentType: string;
14 model?: string;
15 outputTokens?: number;
16}): string {
17 return JSON.stringify({
18 type: "assistant",
19 timestamp: "2026-08-07T04:05:13.944Z",
20 sessionId: "5a128faa-8253-489e-b935-6c08e8e670c0",
21 cwd: "/home/theo/project",
22 message: {
23 id: overrides.messageId,
24 role: "assistant",
25 model: overrides.model ?? "claude-fable-5",
26 content: [{ type: overrides.contentType }],
27 usage: {
28 input_tokens: 2,
29 cache_creation_input_tokens: 66818,
30 cache_read_input_tokens: 1000,
31 output_tokens: overrides.outputTokens ?? 286,
32 },
33 },
34 });
36​
37describe("parseClaudeLine", () => {
38 it("extracts token totals and a dedupe key", () => {
39 const record = parseClaudeLine(claudeLine({ messageId: "msg_1", contentType: "text" }));
40​
41 expect(record).not.toBeNull();
42 expect(record?.provider).toBe("claude");
43 expect(record?.model).toBe("claude-fable-5");
44 expect(record?.totals).toEqual({
45 uncachedInputTokens: 2,
46 cachedInputTokens: 1000,
47 cacheCreationTokens: 66818,
48 outputTokens: 286,
49 reasoningTokens: 0,
50 });
51 expect(record?.dedupeKey).toBe("msg_1:");
52 });
53​
54 it("gives every content block of one message the same dedupe key", () => {
55 // T3 Code writes one record per content block, each repeating the parent
56 // message's full usage. Summing them would overcount ~2.4x on real data.
57 const text = parseClaudeLine(claudeLine({ messageId: "msg_2", contentType: "text" }));
58 const toolUse = parseClaudeLine(claudeLine({ messageId: "msg_2", contentType: "tool_use" }));
59​
60 expect(text?.dedupeKey).toBe(toolUse?.dedupeKey);
61 expect(text?.totals).toEqual(toolUse?.totals);
62 });
63​
64 it("ignores records that are not assistant messages", () => {
65 expect(parseClaudeLine(JSON.stringify({ type: "user", message: {} }))).toBeNull();
66 expect(parseClaudeLine("not json")).toBeNull();
67 });
68});
69​
70describe("parseCodexLine", () => {
71 const sessionMeta = JSON.stringify({
72 type: "session_meta",
73 timestamp: "2026-08-01T05:17:41.289Z",
74 payload: { type: "session_meta", id: "019fbbc1-b12c-7360-a685-28c181f0025f" },
75 });
76 const turnContext = JSON.stringify({
77 type: "turn_context",
78 timestamp: "2026-08-01T05:17:42.694Z",
79 payload: { type: "turn_context", model: "gpt-5.6-sol" },
80 });
81 const tokenCount = (inputTokens: number, cached: number, output: number, reasoning: number) =>
82 JSON.stringify({
83 type: "event_msg",
84 timestamp: "2026-08-01T05:17:49.919Z",
85 payload: {
86 type: "token_count",
87 info: {
88 last_token_usage: {
89 input_tokens: inputTokens,
90 cached_input_tokens: cached,
91 cache_write_input_tokens: 0,
92 output_tokens: output,
93 reasoning_output_tokens: reasoning,
94 },
95 },
96 },
97 });
98​
99 it("attributes usage to the model from the preceding turn context", () => {
100 const state = initialCodexScanState();
101 parseCodexLine(sessionMeta, state);
102 parseCodexLine(turnContext, state);
103 const record = parseCodexLine(tokenCount(19239, 11008, 299, 116), state);
104​
105 expect(record?.provider).toBe("codex");
106 expect(record?.model).toBe("gpt-5.6-sol");
107 expect(record?.sessionId).toBe("019fbbc1-b12c-7360-a685-28c181f0025f");
108 // Codex reports input_tokens inclusive of the cached portion.
109 expect(record?.totals.uncachedInputTokens).toBe(19239 - 11008);
110 expect(record?.totals.cachedInputTokens).toBe(11008);
111 expect(record?.totals.reasoningTokens).toBe(116);
112 });
113​
114 it("skips a repeated token_count so deltas are not double counted", () => {
115 const state = initialCodexScanState();
116 parseCodexLine(turnContext, state);
117 const first = parseCodexLine(tokenCount(100, 0, 10, 0), state);
118 const repeat = parseCodexLine(tokenCount(100, 0, 10, 0), state);
119​
120 expect(first).not.toBeNull();
121 expect(repeat).toBeNull();
122 });
123​
124 it("drops usage that arrives before any model is known", () => {
125 const state = initialCodexScanState();
126 expect(parseCodexLine(tokenCount(100, 0, 10, 0), state)).toBeNull();
127 });
128​
129 it("does not let a pre-model event poison the duplicate signature", () => {
130 // A token_count before its turn_context is dropped; the identical event
131 // re-emitted once the model is known must still be counted.
132 const state = initialCodexScanState();
133 expect(parseCodexLine(tokenCount(100, 0, 10, 0), state)).toBeNull();
134 parseCodexLine(turnContext, state);
135 expect(parseCodexLine(tokenCount(100, 0, 10, 0), state)).not.toBeNull();
136 });
137​
138 // A forked/subagent rollout opens with the parent's history copied in and
139 // every line re-stamped to the fork instant, then the ancestors' session
140 // metas. Counting those again multiplied usage ~1.85x on real data (#5758).
141 describe("forked rollouts", () => {
142 const meta = (overrides: {
143 id: string;
144 timestamp: string;
145 forkedFromId?: string;
146 spawnParentId?: string;
147 }) =>
148 JSON.stringify({
149 type: "session_meta",
150 timestamp: overrides.timestamp,
151 payload: {
152 type: "session_meta",
153 id: overrides.id,
154 ...(overrides.forkedFromId === undefined
155 ? {}
156 : { forked_from_id: overrides.forkedFromId }),
157 ...(overrides.spawnParentId === undefined
158 ? {}
159 : {
160 source: {
161 subagent: { thread_spawn: { parent_thread_id: overrides.spawnParentId } },
162 },
163 }),
164 },
165 });
166 const stamped = (timestamp: string, line: string) => {
167 const parsed = JSON.parse(line) as { timestamp: string };
168 parsed.timestamp = timestamp;
169 return JSON.stringify(parsed);
170 };
171​
172 it("keeps the child session id over copied ancestor metas", () => {
173 const state = initialCodexScanState();
174 parseCodexLine(meta({ id: "child", timestamp: "2026-08-01T05:00:00.000Z" }), state);
175 parseCodexLine(meta({ id: "parent", timestamp: "2026-08-01T05:00:00.000Z" }), state);
176 parseCodexLine(turnContext, state);
177 const record = parseCodexLine(tokenCount(100, 0, 10, 0), state);
178​
179 expect(record?.sessionId).toBe("child");
180 });
181​
182 it("drops the re-stamped copied burst and keeps the first real event", () => {
183 const state = initialCodexScanState();
184 const forkInstant = "2026-08-01T05:00:00.000Z";
185 parseCodexLine(meta({ id: "child", timestamp: forkInstant, forkedFromId: "parent" }), state);
186 parseCodexLine(meta({ id: "parent", timestamp: forkInstant }), state);
187 parseCodexLine(stamped(forkInstant, turnContext), state);
188​
189 // Copied history: written in one burst at the fork instant.
190 expect(
191 parseCodexLine(stamped("2026-08-01T05:00:00.001Z", tokenCount(100, 0, 10, 0)), state),
192 ).toBeNull();
193 expect(
194 parseCodexLine(stamped("2026-08-01T05:00:00.002Z", tokenCount(200, 0, 20, 0)), state),
195 ).toBeNull();
196​
197 // The child's first genuine turn lands seconds later and must count.
198 const real = parseCodexLine(
199 stamped("2026-08-01T05:00:06.000Z", tokenCount(300, 0, 30, 0)),
200 state,
201 );
202 expect(real).not.toBeNull();
203 expect(real?.totals.outputTokens).toBe(30);
204​
205 // Suppression never restarts, even for closely spaced later events.
206 const next = parseCodexLine(
207 stamped("2026-08-01T05:00:06.100Z", tokenCount(400, 0, 40, 0)),
208 state,
209 );
210 expect(next).not.toBeNull();
211 });
212​
213 it("recognizes subagent spawns without forked_from_id", () => {
214 const state = initialCodexScanState();
215 const spawnInstant = "2026-08-01T05:00:00.000Z";
216 parseCodexLine(
217 meta({ id: "child", timestamp: spawnInstant, spawnParentId: "parent" }),
218 state,
219 );
220 parseCodexLine(stamped(spawnInstant, turnContext), state);
221 expect(
222 parseCodexLine(stamped("2026-08-01T05:00:00.001Z", tokenCount(100, 0, 10, 0)), state),
223 ).toBeNull();
224 });
225​
226 it("does not suppress anything in a rollout that is not a fork", () => {
227 const state = initialCodexScanState();
228 parseCodexLine(meta({ id: "root", timestamp: "2026-08-01T05:00:00.000Z" }), state);
229 parseCodexLine(stamped("2026-08-01T05:00:00.100Z", turnContext), state);
230 const record = parseCodexLine(
231 stamped("2026-08-01T05:00:00.200Z", tokenCount(100, 0, 10, 0)),
232 state,
233 );
234 expect(record).not.toBeNull();
235 });
236 });
237});
238​
239describe("totalTokens", () => {
240 it("does not add reasoning on top of output", () => {
241 expect(
242 totalTokens({
243 uncachedInputTokens: 10,
244 cachedInputTokens: 20,
245 cacheCreationTokens: 30,
246 outputTokens: 40,
247 reasoningTokens: 25,
248 }),
249 ).toBe(100);
250 });
251});