@devries-cameron20 / t3code Mirror · read-only / commits / 9ac4535b06
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 18:30 UTC

fix(shared): token counts just below a unit boundary use the next unit (#35634)

Julius Marminge committed Nov 12, 2026 at 14:47 UTC 9ac4535b06ffd60579efb710f0fab07a22035d92
2 files changed +20 -7
packages/shared/src/usageFormat.test.ts
+9 -1
@@ -2,7 +2,7 @@
2 import { describe, expect, it, vi } from "vite-plus/test";
3 import type { UsageSource } from "@t3tools/contracts";
4
5 -import { formatHourShort, makeWindow, usageSourceMessages } from "./usageFormat.ts";
5 +import { formatHourShort, formatTokens, makeWindow, usageSourceMessages } from "./usageFormat.ts";
6
7 function malformedSource(count: number, overrides: Partial<UsageSource> = {}): UsageSource {
8 return {
@@ -176,3 +176,11 @@ describe("hourly usage formatting", () => {
176 }
177 });
178 });
179 +
180 +describe("token formatting", () => {
181 + it("moves to the next unit when rounding reaches it", () => {
182 + expect(formatTokens(999_999)).toBe("1M");
183 + expect(formatTokens(999_999_999)).toBe("1B");
184 + expect(formatTokens(-999_999)).toBe("-1M");
185 + });
186 +});
packages/shared/src/usageFormat.ts
+11 -6
@@ -63,13 +63,18 @@ export function formatCount(value: number): string {
63 return INTEGER.format(Math.round(value));
64 }
65
66 +const TOKEN_SUFFIXES = ["K", "M", "B", "T"] as const;
67 +
68 export function formatTokens(value: number): string {
67 - const abs = Math.abs(value);
68 - if (abs >= 1e12) return `${trim(value / 1e12)}T`;
69 - if (abs >= 1e9) return `${trim(value / 1e9)}B`;
70 - if (abs >= 1e6) return `${trim(value / 1e6)}M`;
71 - if (abs >= 1e3) return `${trim(value / 1e3)}K`;
72 - return INTEGER.format(Math.round(value));
69 + if (Math.abs(Math.round(value)) < 1e3) return INTEGER.format(Math.round(value));
70 + let scaled = value / 1e3;
71 + let unit = 0;
72 + // Choose the unit after rounding, so 999,999 reads 1M rather than 1000K.
73 + while (Math.abs(Number(trim(scaled))) >= 1e3 && unit < TOKEN_SUFFIXES.length - 1) {
74 + scaled /= 1e3;
75 + unit += 1;
76 + }
77 + return `${trim(scaled)}${TOKEN_SUFFIXES[unit]}`;
78 }
79
80 function trim(value: number): string {