Skip to content
TypeScript

fix(usage): combine duplicated skipped-record warnings (#23411)

Alexb010581aea0a
diff --git a/apps/mobile/src/features/usage/UsageRouteScreen.tsx b/apps/mobile/src/features/usage/UsageRouteScreen.tsx
index 1cba6c00547..32e12be28f0 100644
--- a/apps/mobile/src/features/usage/UsageRouteScreen.tsx
+++ b/apps/mobile/src/features/usage/UsageRouteScreen.tsx
@@ -27,6 +27,7 @@ import {
formatUsageContractMismatch,
formatUsd,
makeWindow,
+ usageSourceMessages,
} from "@t3tools/shared/usageFormat";
import { useRef, useState, type ReactNode } from "react";
import { Platform, Pressable, RefreshControl, View } from "react-native";
@@ -119,22 +120,9 @@ function UsageScreen(props: {
void refresh();
void limits.refreshAfterEnable();
};
- const sourceMessages = [
- ...new Set(
- selectedEnvironments.flatMap(
- (environment) =>
- environment.summary?.sources.flatMap((source) =>
- source.message &&
- !source.action &&
- (source.status === "partial" ||
- source.status === "failed" ||
- source.fingerprint.provider === "cursor")
- ? [source.message]
- : [],
- ) ?? [],
- ),
- ),
- ];
+ const sourceMessages = usageSourceMessages(
+ selectedEnvironments.flatMap((environment) => environment.summary?.sources ?? []),
+ );
const canReadDiagnostics = selectedEnvironments.some(
(environment) => environment.canReadDiagnostics,
);
diff --git a/apps/server/src/usage/UsageService.ts b/apps/server/src/usage/UsageService.ts
index c1f619eaae1..f5f10fb156f 100644
--- a/apps/server/src/usage/UsageService.ts
+++ b/apps/server/src/usage/UsageService.ts
@@ -28,6 +28,7 @@ import * as Semaphore from "effect/Semaphore";
import { HttpClient, HttpClientResponse } from "effect/http";
import { writeFileStringAtomically } from "@t3tools/shared/atomicWrite";
+import { formatMalformedUsageWarning } from "@t3tools/shared/usageFormat";
import * as ServerConfig from "../config.ts";
import * as ServerSettings from "../serverSettings.ts";
import { BUILT_IN_USAGE_DRIVERS, type BuiltInUsageReadersEnv } from "../provider/builtInDrivers.ts";
@@ -855,10 +856,7 @@ export const make = Effect.gen(function* () {
distinctSessions: sessionIds.size,
message:
malformedRecords > 0
- ? [
- sourceMessage,
- `${malformedRecords} malformed or inconsistent usage record(s) were skipped; usage may be incomplete.`,
- ]
+ ? [sourceMessage, formatMalformedUsageWarning(malformedRecords)]
.filter(Boolean)
.join(" ")
: sourceMessage,
diff --git a/apps/web/src/components/usage/UsagePage.tsx b/apps/web/src/components/usage/UsagePage.tsx
index 8373d3439eb..fb7e29948ec 100644
--- a/apps/web/src/components/usage/UsagePage.tsx
+++ b/apps/web/src/components/usage/UsagePage.tsx
@@ -56,6 +56,7 @@ import {
formatUsageContractMismatch,
formatUsd,
makeWindow,
+ usageSourceMessages,
} from "@t3tools/shared/usageFormat";
import { Button, InlineButton } from "../ui/button";
import { ProviderInstanceIcon } from "../chat/ProviderInstanceIcon";
@@ -650,23 +651,14 @@ function UsageOverview({
const chartLoadingProviders = new Set(
activeProviders.filter((provider) => loadingProviders.has(provider)),
);
- const sourceMessages = [
- ...new Set(
- selectedEnvironments.flatMap(
- (environment) =>
- environment.summary?.sources.flatMap((source) =>
- source.message &&
- !source.action &&
- !hiddenProviders.has(source.fingerprint.provider) &&
- (source.status === "partial" ||
- source.status === "failed" ||
- source.fingerprint.provider === "cursor")
- ? [source.message]
- : [],
- ) ?? [],
- ),
+ const sourceMessages = usageSourceMessages(
+ selectedEnvironments.flatMap(
+ (environment) =>
+ environment.summary?.sources.filter(
+ (source) => !hiddenProviders.has(source.fingerprint.provider),
+ ) ?? [],
),
- ];
+ );
const breakdownPeriods: readonly (DailyTotals | HourlyTotals)[] = (
shownHourly ? merged.hourly : merged.daily
).toReversed();
diff --git a/packages/shared/src/usageFormat.test.ts b/packages/shared/src/usageFormat.test.ts
index 73d4e357661..6682a194ab2 100644
--- a/packages/shared/src/usageFormat.test.ts
+++ b/packages/shared/src/usageFormat.test.ts
@@ -1,7 +1,132 @@
// @effect-diagnostics globalDate:off -- A fixed instant keeps calendar-window assertions deterministic.
import { describe, expect, it, vi } from "vite-plus/test";
+import type { UsageSource } from "@t3tools/contracts";
-import { formatHourShort, makeWindow } from "./usageFormat.ts";
+import { formatHourShort, makeWindow, usageSourceMessages } from "./usageFormat.ts";
+
+function malformedSource(count: number, overrides: Partial<UsageSource> = {}): UsageSource {
+ return {
+ fingerprint: {
+ hostId: "demo-host",
+ provider: "codex",
+ resolvedHomePath: "/demo/codex",
+ volumeId: "demo-volume",
+ },
+ status: "partial",
+ scannedFiles: 1,
+ skippedFiles: 0,
+ malformedRecords: count,
+ distinctSessions: 1,
+ message: `${count} malformed or inconsistent usage record(s) were skipped; usage may be incomplete.`,
+ ...overrides,
+ };
+}
+
+describe("usage source messages", () => {
+ it("combines different skipped-record counts into one warning", () => {
+ const codex = malformedSource(1);
+ const claude = malformedSource(11, {
+ fingerprint: { ...codex.fingerprint, provider: "claude", resolvedHomePath: "/demo/claude" },
+ });
+
+ expect(usageSourceMessages([codex, claude])).toEqual([
+ "12 malformed or inconsistent usage record(s) were skipped; usage may be incomplete.",
+ ]);
+ });
+
+ it.each([
+ { first: 1, second: 1, total: 2 },
+ { first: 1, second: 11, total: 12 },
+ ])(
+ "combines hosts reporting $first and $second skipped records once per source",
+ ({ first, second, total }) => {
+ const source = malformedSource(first);
+ const otherHost = malformedSource(second, {
+ fingerprint: { ...source.fingerprint, hostId: "other-demo-host" },
+ });
+
+ expect(usageSourceMessages([source, source, otherHost, otherHost])).toEqual([
+ `${total} malformed or inconsistent usage record(s) were skipped; usage may be incomplete.`,
+ ]);
+ expect(usageSourceMessages([source, source])).toEqual([
+ `${first} malformed or inconsistent usage record(s) were skipped; usage may be incomplete.`,
+ ]);
+ expect(usageSourceMessages([otherHost, otherHost])).toEqual([
+ `${second} malformed or inconsistent usage record(s) were skipped; usage may be incomplete.`,
+ ]);
+ },
+ );
+
+ it("keeps different machines with the same hostname and home path distinct", () => {
+ const source = malformedSource(1);
+ const otherMachine = malformedSource(11, {
+ fingerprint: { ...source.fingerprint, volumeId: "other-demo-volume" },
+ });
+
+ expect(usageSourceMessages([source, otherMachine])).toEqual([
+ "12 malformed or inconsistent usage record(s) were skipped; usage may be incomplete.",
+ ]);
+ });
+
+ it("uses the largest count when connected environments report the same source", () => {
+ const source = malformedSource(1);
+
+ expect(usageSourceMessages([source, malformedSource(11), source])).toEqual([
+ "11 malformed or inconsistent usage record(s) were skipped; usage may be incomplete.",
+ ]);
+ });
+
+ it("retains other diagnostics beside the combined warning", () => {
+ const source = malformedSource(1);
+ const readFailure = "2 transcript path(s) could not be read; usage may be incomplete.";
+ const cursor = malformedSource(0, {
+ fingerprint: { ...source.fingerprint, provider: "cursor" },
+ status: "ok",
+ message: "Cursor history is limited to the last 30 days.",
+ });
+
+ expect(
+ usageSourceMessages([
+ { ...source, message: `${readFailure} ${source.message}` },
+ { ...source, malformedRecords: 0, message: readFailure },
+ cursor,
+ ]),
+ ).toEqual([
+ readFailure,
+ cursor.message,
+ "1 malformed or inconsistent usage record(s) were skipped; usage may be incomplete.",
+ ]);
+ });
+
+ it("includes cached diagnostics when a transcript directory is missing", () => {
+ const source = malformedSource(1);
+ const missing = malformedSource(2, {
+ fingerprint: { ...source.fingerprint, hostId: "other-demo-host" },
+ status: "missing",
+ scannedFiles: 0,
+ skippedFiles: 1,
+ distinctSessions: 0,
+ message:
+ "No transcript directory on this environment. 2 malformed or inconsistent usage record(s) were skipped; usage may be incomplete.",
+ });
+
+ expect(usageSourceMessages([source, missing, missing])).toEqual([
+ "No transcript directory on this environment.",
+ "3 malformed or inconsistent usage record(s) were skipped; usage may be incomplete.",
+ ]);
+ });
+
+ it("omits empty missing sources, healthy sources, and diagnostics handled by an action", () => {
+ expect(
+ usageSourceMessages([
+ malformedSource(0, { status: "missing" }),
+ malformedSource(1, { status: "ok" }),
+ malformedSource(1, { action: "enableCursorKeychain" }),
+ ]),
+ ).toEqual([]);
+ expect(usageSourceMessages([])).toEqual([]);
+ });
+});
describe("hourly usage formatting", () => {
it("keeps requested zones separate when formatting repeated calls", () => {
diff --git a/packages/shared/src/usageFormat.ts b/packages/shared/src/usageFormat.ts
index 8c9792353af..51398982e04 100644
--- a/packages/shared/src/usageFormat.ts
+++ b/packages/shared/src/usageFormat.ts
@@ -1,5 +1,10 @@
// @effect-diagnostics globalDate:off -- Usage windows are calendar days in the viewer's zone, derived from wall-clock "now" via Intl.
-import { UsageDay, type UsageResolution, type UsageSummaryInput } from "@t3tools/contracts";
+import {
+ UsageDay,
+ type UsageResolution,
+ type UsageSource,
+ type UsageSummaryInput,
+} from "@t3tools/contracts";
import type { UsageContractMismatch } from "./usageMerge.ts";
@@ -12,6 +17,45 @@ const CURRENCY = new Intl.NumberFormat("en-US", {
const INTEGER = new Intl.NumberFormat("en-US");
+export function formatMalformedUsageWarning(count: number): string {
+ return `${count} malformed or inconsistent usage record(s) were skipped; usage may be incomplete.`;
+}
+
+export function usageSourceMessages(sources: readonly UsageSource[]): readonly string[] {
+ const messages = new Set<string>();
+ const malformedBySource = new Map<string, number>();
+ for (const source of sources) {
+ if (
+ source.action ||
+ (source.status !== "partial" &&
+ source.status !== "failed" &&
+ source.fingerprint.provider !== "cursor" &&
+ !(source.status === "missing" && source.malformedRecords > 0))
+ ) {
+ continue;
+ }
+ let message = source.message;
+ if (source.malformedRecords > 0) {
+ const { hostId, provider, resolvedHomePath, volumeId } = source.fingerprint;
+ const key = JSON.stringify([hostId, provider, resolvedHomePath, volumeId]);
+ malformedBySource.set(
+ key,
+ Math.max(malformedBySource.get(key) ?? 0, source.malformedRecords),
+ );
+ // Servers also append this warning to message; retain any preceding read failure.
+ const warning = formatMalformedUsageWarning(source.malformedRecords);
+ if (message?.endsWith(warning)) message = message.slice(0, -warning.length).trim();
+ }
+ if (message) messages.add(message);
+ }
+ const malformedRecords = [...malformedBySource.values()].reduce(
+ (total, count) => total + count,
+ 0,
+ );
+ if (malformedRecords > 0) messages.add(formatMalformedUsageWarning(malformedRecords));
+ return [...messages];
+}
+
export function formatUsd(value: number): string {
return CURRENCY.format(value);
}