Skip to content

Commit d65bb0c

Browse files
committed
fix(usage): state the window as observed extrema, and prove the tests
Three review findings, all correct. The notice said totals cover usage 'from start to end' and that older entries exceed the read limit. Both claims overstate what the data supports, and they overstate it in exactly the way this PR exists to stop: usage.jsonl is appended on request completion while rows carry the request start time, so retained rows can have gaps and the dropped prefix can contain requests whose start times fall inside the displayed interval. The wording now describes the bounds as what they are — the range of request start times among loaded rows — in all eight locales. The filter-invariance test was vacuous. A 256-byte tail retained a single row, so the surface and range filters discarded nothing and the comparisons held trivially; on unmodified dev every compared field was undefined, which also compared equal. It now builds its own fixture where the retained set is 3 rows that the filters cut to 2 and then 1, asserts exact independently computed bounds, and asserts the fields are numeric. The cache test now asserts the second request is a cache hit. Presence-checking the bounds prevented an omitted field from rendering 'Invalid Date' but not an out-of-range one, and the reader preserves whatever a hand-edited row carries. Both bounds now have to round-trip through Date before the detailed wording is used, with a rendered test covering the unrenderable case.
1 parent f7c7814 commit d65bb0c

11 files changed

Lines changed: 186 additions & 24 deletions

File tree

‎gui/src/i18n/de.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -737,7 +737,7 @@ export const de: Record<TKey, string> = {
737737
"usage.range.all": "Alle",
738738
"usage.range.available": "Verfügbarer Verlauf",
739739
"usage.historyTruncated": "Die Summen beziehen sich nur auf den verfügbaren Verlauf, da ältere Nutzungsdaten nicht geladen wurden.",
740-
"usage.historyTruncatedWindow": "Die Summen umfassen nur die von {start} bis {end} geladene Nutzung. Ältere Einträge überschreiten das Leselimit, daher kann jeder gewählte Zeitraum unvollständig sein.",
740+
"usage.historyTruncatedWindow": "Die geladenen Zeilen haben Anfragestartzeiten zwischen {start} und {end}. Frühere Dateieinträge wurden durch das Leselimit ausgelassen, daher kann jeder gewählte Zeitraum unvollständig sein.",
741741
"usage.range.30d": "30d",
742742
"usage.range.7d": "7d",
743743
"usage.card.requests": "Anfragen",

‎gui/src/i18n/en.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -768,7 +768,7 @@ export const en = {
768768
"usage.range.all": "All",
769769
"usage.range.available": "Available history",
770770
"usage.historyTruncated": "Totals cover available history only because older usage was not loaded.",
771-
"usage.historyTruncatedWindow": "Totals cover only the usage loaded from {start} to {end}. Older entries exceed the read limit, so any selected range may be incomplete.",
771+
"usage.historyTruncatedWindow": "Loaded rows have request start times ranging from {start} to {end}. Earlier file entries were omitted by the read limit, so any selected range may be incomplete.",
772772
"usage.range.30d": "30d",
773773
"usage.range.7d": "7d",
774774
"usage.card.requests": "Requests",

‎gui/src/i18n/ja.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -726,7 +726,7 @@ export const ja: Record<TKey, string> = {
726726
"usage.range.all": "すべて",
727727
"usage.range.available": "利用可能な履歴",
728728
"usage.historyTruncated": "古い利用履歴が読み込まれていないため、合計は利用可能な履歴のみを対象とします。",
729-
"usage.historyTruncatedWindow": "合計は {start} から {end} までに読み込まれた利用量のみを対象とします。それより古い記録は読み取り上限を超えるため、選択した期間が不完全な場合があります。",
729+
"usage.historyTruncatedWindow": "読み込まれた行のリクエスト開始時刻は {start} から {end} の範囲です。読み取り上限によりファイル前方の記録が除外されているため、選択した期間は不完全な場合があります。",
730730
"usage.range.30d": "30日",
731731
"usage.range.7d": "7日",
732732
"usage.card.requests": "リクエスト",

‎gui/src/i18n/ko.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -759,7 +759,7 @@ export const ko: Record<TKey, string> = {
759759
"usage.range.all": "전체",
760760
"usage.range.available": "사용 가능한 기록",
761761
"usage.historyTruncated": "이전 사용 기록을 불러오지 않아 합계는 사용 가능한 기록만 포함합니다.",
762-
"usage.historyTruncatedWindow": "합계는 {start}부터 {end}까지 불러온 사용량만 포함합니다. 그보다 오래된 기록은 읽기 한도를 넘어 선택한 기간이 완전하지 않을 수 있습니다.",
762+
"usage.historyTruncatedWindow": "불러온 기록의 요청 시작 시각은 {start}부터 {end} 사이입니다. 읽기 한도 때문에 파일 앞부분의 기록이 빠졌으므로 선택한 기간이 완전하지 않을 수 있습니다.",
763763
"usage.range.30d": "30일",
764764
"usage.range.7d": "7일",
765765
"usage.card.requests": "요청",

‎gui/src/i18n/ru.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -758,7 +758,7 @@ export const ru: Record<TKey, string> = {
758758
"usage.range.all": "Все",
759759
"usage.range.available": "Доступная история",
760760
"usage.historyTruncated": "Итоги охватывают только доступную историю, поскольку старые данные не загружены.",
761-
"usage.historyTruncatedWindow": "Итоги охватывают только использование, загруженное с {start} по {end}. Более старые записи превышают лимит чтения, поэтому выбранный период может быть неполным.",
761+
"usage.historyTruncatedWindow": "У загруженных записей время начала запроса находится в диапазоне от {start} до {end}. Более ранние записи файла пропущены из-за лимита чтения, поэтому выбранный период может быть неполным.",
762762
"usage.range.30d": "30 дн.",
763763
"usage.range.7d": "7 дн.",
764764
"usage.card.requests": "Запросы",

‎gui/src/i18n/tr.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -765,7 +765,7 @@ export const tr: Record<TKey, string> = {
765765
"usage.range.all": "Tümü",
766766
"usage.range.available": "Mevcut geçmiş",
767767
"usage.historyTruncated": "Toplamlar yalnızca mevcut geçmişi kapsar.",
768-
"usage.historyTruncatedWindow": "Toplamlar yalnızca {start} - {end} aralığında yüklenen kullanımı kapsar. Daha eski kayıtlar okuma sınırını aştığı için seçilen aralık eksik olabilir.",
768+
"usage.historyTruncatedWindow": "Yüklenen satırların istek başlangıç zamanları {start} ile {end} arasındadır. Dosyanın önceki kayıtları okuma sınırı nedeniyle atlandı, bu yüzden seçilen aralık eksik olabilir.",
769769
"usage.range.30d": "30 gün",
770770
"usage.range.7d": "7 gün",
771771
"usage.card.requests": "İstekler",

‎gui/src/i18n/zh-TW.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1586,7 +1586,7 @@ export const zhTW: Record<TKey, string> = {
15861586
"provider.name.volcengineAgentPlan": "Volcengine Ark Agent Plan",
15871587
"usage.range.available": "可用歷史紀錄",
15881588
"usage.historyTruncated": "總計僅涵蓋可用歷史紀錄,因為較舊的用量未被載入。",
1589-
"usage.historyTruncatedWindow": "總計僅涵蓋從 {start} 到 {end} 已載入的用量。更早的紀錄超出讀取上限,因此所選期間可能不完整。",
1589+
"usage.historyTruncatedWindow": "已載入紀錄的請求開始時間介於 {start} 到 {end} 之間。受讀取上限限制,檔案較前的項目已被略過,所選期間可能不完整。",
15901590
"codexAuth.autoSwitchQuotaDesc": "配額:使用率達 {threshold}% 或以上時,下一個請求可能移至用量較低的合格帳號,包括已綁定的任務;Go/Free 僅使用 30 天。",
15911591
"codexAuth.autoSwitchQuotaOffDesc": "基於用量的主動切換已關閉。新增/未綁定分派與故障恢復仍然適用。",
15921592
"codexAuth.autoSwitchRoundRobinDesc": "輪詢分派不使用此閾值;它會繼續輪換新增/未綁定的任務。",

‎gui/src/i18n/zh.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -752,7 +752,7 @@ export const zh: Record<TKey, string> = {
752752
"usage.range.all": "全部",
753753
"usage.range.available": "可用历史",
754754
"usage.historyTruncated": "由于未加载较早的使用记录,合计仅涵盖可用历史。",
755-
"usage.historyTruncatedWindow": "合计仅涵盖从 {start} 到 {end} 已加载的用量。更早的记录超出读取上限,因此所选时间范围可能不完整。",
755+
"usage.historyTruncatedWindow": "已加载记录的请求开始时间介于 {start} 到 {end} 之间。受读取上限限制,文件较前的条目已被省略,所选时间范围可能不完整。",
756756
"usage.range.30d": "30 天",
757757
"usage.range.7d": "7 天",
758758
"usage.card.requests": "请求数",

‎gui/src/pages/Usage.tsx‎

Lines changed: 19 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -827,15 +827,16 @@ export default function Usage({ apiBase }: { apiBase: string }) {
827827
// they claim (#1497). `warn` rather than `ok` because a total that silently omits
828828
// in-range rows is a caveat, not a status update.
829829
<Notice tone="warn">
830-
{/* `!= null` rather than `!== null`: an older proxy that predates these fields
831-
omits them entirely, and an undefined bound must fall back to the generic
832-
wording instead of rendering "Invalid Date". */}
833-
{data.snapshotWindowStart != null && data.snapshotWindowEnd != null
834-
? t("usage.historyTruncatedWindow", {
835-
start: new Date(data.snapshotWindowStart).toLocaleString(),
836-
end: new Date(data.snapshotWindowEnd).toLocaleString(),
837-
})
838-
: t("usage.historyTruncated")}
830+
{(() => {
831+
// Both bounds must be renderable before the detailed wording is used: an older
832+
// proxy omits the fields entirely, and a hand-edited row can carry a timestamp
833+
// outside Date's range. Either way the generic string is the honest fallback.
834+
const start = renderableInstant(data.snapshotWindowStart);
835+
const end = renderableInstant(data.snapshotWindowEnd);
836+
return start !== null && end !== null
837+
? t("usage.historyTruncatedWindow", { start, end })
838+
: t("usage.historyTruncated");
839+
})()}
839840
</Notice>
840841
)}
841842
<UsageWorkspaceBody
@@ -856,3 +857,12 @@ export default function Usage({ apiBase }: { apiBase: string }) {
856857
</>
857858
);
858859
}
860+
function renderableInstant(value: number | null | undefined): string | null {
861+
// The reader preserves whatever timestamp a row carries, including hand-edited values far
862+
// outside Date's supported range. A presence check alone would then render the literal
863+
// string "Invalid Date" in a notice whose whole job is to be trustworthy, so the bound is
864+
// only used once it round-trips through Date.
865+
if (typeof value !== "number" || !Number.isFinite(value)) return null;
866+
const at = new Date(value);
867+
return Number.isFinite(at.getTime()) ? at.toLocaleString() : null;
868+
}

‎gui/tests/usage-layout.test.ts‎

Lines changed: 78 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -152,11 +152,88 @@ test("Usage names the loaded window when history is truncated", async () => {
152152
// indistinguishable on a busy installation. `!= null` keeps an older proxy that omits the
153153
// fields on the generic string rather than rendering "Invalid Date".
154154
expect(page).toContain("usage.historyTruncatedWindow");
155-
expect(page).toContain("data.snapshotWindowStart != null && data.snapshotWindowEnd != null");
155+
// Presence alone is not enough: a hand-edited row can carry a timestamp outside Date's
156+
// range, so both bounds must round-trip through Date before the detailed wording is used.
157+
expect(page).toContain("function renderableInstant");
158+
expect(page).toContain("Number.isFinite(at.getTime())");
156159
// A total that silently omits in-range rows is a caveat, not a status update.
157160
expect(page).toContain('<Notice tone="warn">');
158161
});
159162

163+
test("Usage falls back to the generic caveat when a reported bound is unrenderable", async () => {
164+
const globalKeys = ["document", "window", "navigator", "localStorage", "IS_REACT_ACT_ENVIRONMENT"] as const;
165+
const previous = Object.fromEntries(globalKeys.map(key => [key, Reflect.get(globalThis, key)]));
166+
const originalFetch = globalThis.fetch;
167+
const testWindow = new Window({ url: "http://localhost/" });
168+
Object.defineProperties(globalThis, {
169+
document: { configurable: true, value: testWindow.document },
170+
window: { configurable: true, value: testWindow },
171+
navigator: { configurable: true, value: testWindow.navigator },
172+
localStorage: { configurable: true, value: testWindow.localStorage },
173+
});
174+
(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
175+
clearClientResourceStoresForTests();
176+
// A timestamp beyond Date's supported range. Rendering it would put the literal string
177+
// "Invalid Date" inside a notice whose entire purpose is to be trustworthy.
178+
globalThis.fetch = (async () => Response.json({
179+
range: "30d",
180+
surface: "all",
181+
since: null,
182+
generatedAt: Date.now(),
183+
summary: {
184+
requests: 0,
185+
measuredRequests: 0,
186+
reportedRequests: 0,
187+
unreportedRequests: 0,
188+
unsupportedRequests: 0,
189+
estimatedRequests: 0,
190+
inputTokens: 0,
191+
outputTokens: 0,
192+
cachedInputTokens: 0,
193+
reasoningOutputTokens: 0,
194+
totalTokens: 0,
195+
coverageRatio: 1,
196+
},
197+
days: [],
198+
models: [],
199+
providers: [],
200+
historyTruncated: true,
201+
truncatedPrefixBytes: 1,
202+
entriesTruncated: false,
203+
entriesDropped: 0,
204+
snapshotWindowStart: 1e18,
205+
snapshotWindowEnd: 1e18,
206+
})) as typeof fetch;
207+
208+
const container = document.createElement("div");
209+
document.body.append(container);
210+
const { createRoot } = await import("react-dom/client");
211+
const root = createRoot(container);
212+
try {
213+
await act(async () => {
214+
root.render(createElement(LanguageProvider, null, createElement(Usage, { apiBase: "http://usage-invalid-window-test" })));
215+
});
216+
const deadline = Date.now() + 1_000;
217+
while (!(container.textContent ?? "").includes("Totals cover available history only")) {
218+
if (Date.now() >= deadline) throw new Error("Usage fallback qualification did not render");
219+
await act(async () => {
220+
await new Promise<void>(resolve => testWindow.setTimeout(resolve, 10));
221+
});
222+
}
223+
expect(container.textContent).not.toContain("Invalid Date");
224+
expect(container.textContent).not.toContain("request start times ranging");
225+
} finally {
226+
await act(async () => { root.unmount(); });
227+
container.remove();
228+
globalThis.fetch = originalFetch;
229+
clearClientResourceStoresForTests();
230+
testWindow.close();
231+
for (const key of globalKeys) {
232+
Object.defineProperty(globalThis, key, { configurable: true, value: previous[key] });
233+
}
234+
}
235+
});
236+
160237
test("Usage source marks keep brand colors and invert only the monochrome Grok mark", async () => {
161238
const page = await Bun.file(new URL("../src/pages/Usage.tsx", import.meta.url)).text();
162239
const css = await Bun.file(new URL("../src/styles.css", import.meta.url)).text();

0 commit comments

Comments
 (0)