Compare commits

...
Author SHA1 Message Date
Theo BrowneandClaude Fable 5 54d006d522 fix: post-rebase review findings
- Call the SDK usage method through the query object; an extracted
  reference loses its receiver and the catch made that failure silent.
- Treat a backwards wall-clock step as an expired throttle.
- Pick the codex transcript snapshot by its own timestamp, not file mtime.
- Per-provider loading state: a provider without a snapshot shows Loading
  while any environment is still answering, not 'No limit data yet'.
- The usage page refresh button now refreshes the limits cache too.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-08 19:18:30 -07:00
Theo BrowneandClaude Fable 5 a3823306b7 fix(web): limits reset text no longer wraps
Drop the fixed column widths (nowrap instead) and the redundant countdown
suffix; the reset line is just 'resets 8/15 13:34'.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-08 19:11:31 -07:00
Theo BrowneandClaude Fable 5 a3e58c648b fix(web): unambiguous limits copy
Every percentage now reads 'N% used' in both the hover card and the page
strip. Drop plan text, the hover footer, and the freshness caption unless
the snapshot is actually stale (>15m). 24h times, m/d dates.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-08 19:11:31 -07:00
Theo BrowneandClaude Fable 5 6031e5e53e fix(server): make account-limits guard-and-store atomic
The one-permit lock now covers the ordering guard, the map write, and the
persist for both the event ingest and the transcript seed, instead of only
the file write. Two concurrent mutations could previously both pass their
guard against the same prior snapshot and land in either order.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-08 19:11:31 -07:00
Theo BrowneandClaude Fable 5 48bb962515 fix(server): serialize account-limits persists
Atomic rename prevented torn JSON but not ordering: a slow earlier persist
could land after a newer one and drop a provider snapshot from the file.
The encode now runs inside a one-permit semaphore, so the last writer
always persists the latest map.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-08 19:11:31 -07:00
Theo BrowneandClaude Fable 5 ba79f14d2d fix(server): atomic account-limits persist and deeper transcript scan
Concurrent persists (ingestion worker vs the RPC-path transcript seed)
could interleave writes and corrupt account-limits.json, silently dropping
the Claude snapshot on restart. Reuse writeFileStringAtomically. Also raise
the transcript scan cap from 8 to 32 files so a run of Spark-only or
abandoned sessions cannot mask an older main-meter snapshot.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-08 19:11:30 -07:00
Theo BrowneandClaude Fable 5 66b6fb4cf0 fix(server): follow namespace-node-imports lint rule for fs/promises
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-08 19:11:30 -07:00
Theo BrowneandClaude Fable 5 d95c7667e4 feat(usage): account rate limits on the usage page and sidebar hover
Both provider adapters already emitted account.rate-limits.updated events,
but the payload was typed unknown and nothing consumed them. This adds an
AccountLimitsService that caches one normalized snapshot per provider, fed
passively from those events, seeded for Codex from the rate_limits objects
its transcripts already carry, and persisted across restarts (Claude limits
never hit disk). The Claude adapter now also pulls the full window set (5h,
weekly, Fable) through the SDK usage control request, throttled, since the
streamed event only names the binding window.

Exposed via server.getAccountLimits and rendered as a Limits strip on the
usage page plus a hover card on the sidebar Usage button. Windows render
dynamically, so Codex's paused 5-hour window reappears on its own when the
API ships it again. Spark and the opus/sonnet scoped weeklies are hidden.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-08 19:11:30 -07:00
21 changed files with 1454 additions and 3 deletions

No files matched your search

@@ -37,6 +37,7 @@ import { ProviderAdapterRegistry } from "../src/provider/Services/ProviderAdapte
import { makeProviderRegistryLayer } from "../src/provider/testUtils/providerRegistryMock.ts";
import { ProviderSessionDirectoryLive } from "../src/provider/Layers/ProviderSessionDirectory.ts";
import { ServerSettingsService } from "../src/serverSettings.ts";
import * as AccountLimitsService from "../src/usage/AccountLimitsService.ts";
import { makeProviderServiceLive } from "../src/provider/Layers/ProviderService.ts";
import { makeCodexAdapter } from "../src/provider/Layers/CodexAdapter.ts";
import {
@@ -318,6 +319,7 @@ export const makeOrchestrationIntegrationHarness = (
const serverSettingsLayer = ServerSettingsService.layerTest();
const runtimeIngestionLayer = ProviderRuntimeIngestionLive.pipe(
Layer.provideMerge(runtimeServicesLayer),
Layer.provideMerge(AccountLimitsService.layerTest),
Layer.provideMerge(serverSettingsLayer),
);
const gitWorkflowLayer = Layer.mock(GitWorkflowService)({
+1
View File
@@ -46,6 +46,7 @@ export const RPC_REQUIRED_SCOPES = {
[WS_METHODS.serverGetResourceTelemetryHistory]: AuthOrchestrationReadScope,
[WS_METHODS.serverRetryResourceTelemetry]: AuthOrchestrationOperateScope,
[WS_METHODS.serverGetUsageSummary]: AuthOrchestrationReadScope,
[WS_METHODS.serverGetAccountLimits]: AuthOrchestrationReadScope,
[WS_METHODS.serverSignalProcess]: AuthOrchestrationOperateScope,
[WS_METHODS.serverReportClientActivity]: AuthOrchestrationReadScope,
[WS_METHODS.serverReportHostPowerState]: AuthOrchestrationOperateScope,
@@ -53,6 +53,7 @@ import { ProviderRuntimeIngestionService } from "../Services/ProviderRuntimeInge
import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts";
import { ServerConfig } from "../../config.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import * as AccountLimitsService from "../../usage/AccountLimitsService.ts";
import * as NodeServices from "@effect/platform-node/NodeServices";
function makeTestServerSettingsLayer(overrides: Partial<ServerSettings> = {}) {
@@ -246,6 +247,7 @@ describe("ProviderRuntimeIngestion", () => {
Layer.provideMerge(ThreadPlanProgress.layer),
Layer.provideMerge(SqlitePersistenceMemory),
Layer.provideMerge(Layer.succeed(ProviderService, provider.service)),
Layer.provideMerge(AccountLimitsService.layerTest),
Layer.provideMerge(makeTestServerSettingsLayer(options?.serverSettings)),
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
Layer.provideMerge(NodeServices.layer),
@@ -43,6 +43,7 @@ import {
} from "../Services/ProviderRuntimeIngestion.ts";
import { forkParked } from "../../serverActivation.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import { AccountLimitsService } from "../../usage/AccountLimitsService.ts";
const providerTurnKey = (threadId: ThreadId, turnId: TurnId) => `${threadId}:${turnId}`;
const providerTaskKey = (threadId: ThreadId, taskId: string) => `${threadId}:${taskId}`;
@@ -875,6 +876,7 @@ const make = Effect.gen(function* () {
const providerService = yield* ProviderService;
const projectionTurnRepository = yield* ProjectionTurnRepository;
const serverSettingsService = yield* ServerSettingsService;
const accountLimits = yield* AccountLimitsService;
const providerCommandId = (event: ProviderRuntimeEvent, tag: string) =>
crypto.randomUUIDv4.pipe(
Effect.map((uuid) => CommandId.make(`provider:${event.eventId}:${tag}:${uuid}`)),
@@ -1474,6 +1476,17 @@ const make = Effect.gen(function* () {
const processRuntimeEvent = (event: ProviderRuntimeEvent) =>
Effect.gen(function* () {
// Rate-limit payloads feed the server-wide limits cache, not a thread
// projection, so they are folded in before the thread lookup: a
// snapshot must not be lost because its thread is already gone.
if (event.type === "account.rate-limits.updated") {
yield* accountLimits.ingest({
provider: event.provider,
payload: event.payload.rateLimits,
createdAt: event.createdAt,
});
}
const thread = yield* resolveThreadShell(event.threadId);
if (!thread) return;
@@ -15,6 +15,7 @@ import {
type PermissionUpdate,
type SDKMessage,
type SDKControlGetContextUsageResponse,
type SDKControlGetUsageResponse,
type SDKResultMessage,
type SettingSource,
type SDKUserMessage,
@@ -58,6 +59,7 @@ import {
resolvePromptInjectedEffort,
} from "@t3tools/shared/model";
import * as Cause from "effect/Cause";
import * as Clock from "effect/Clock";
import * as Crypto from "effect/Crypto";
import * as DateTime from "effect/DateTime";
import * as Deferred from "effect/Deferred";
@@ -99,6 +101,13 @@ const encodeUnknownJsonStringExit = Schema.encodeUnknownExit(Schema.fromJsonStri
const decodeUnknownJsonStringExit = Schema.decodeUnknownExit(Schema.fromJsonString(Schema.Unknown));
const PROVIDER = ProviderDriverKind.make("claudeAgent");
/**
* Minimum spacing between account usage control requests. The request proxies
* the claude.ai usage endpoint, which rate limits aggressively, and sessions
* start often enough that fetching on every init would hammer it.
*/
const ACCOUNT_USAGE_MIN_INTERVAL_MS = 3 * 60_000;
type ClaudeTextStreamKind = Extract<RuntimeContentStreamKind, "assistant_text" | "reasoning_text">;
type ClaudeToolResultStreamKind = Extract<
RuntimeContentStreamKind,
@@ -256,6 +265,11 @@ interface ClaudeQueryRuntime extends AsyncIterable<SDKMessage> {
readonly setPermissionMode: (mode: PermissionMode) => Promise<void>;
readonly setMaxThinkingTokens: (maxThinkingTokens: number | null) => Promise<void>;
readonly getContextUsage?: () => Promise<SDKControlGetContextUsageResponse>;
/**
* SDK Query usage control request - the full rate-limit window set. The
* name is the SDK's own; optional for test doubles and older SDKs.
*/
readonly usage_EXPERIMENTAL_MAY_CHANGE_DO_NOT_RELY_ON_THIS_API_YET?: () => Promise<SDKControlGetUsageResponse>;
readonly close: () => void;
}
@@ -3077,6 +3091,9 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
config: message as Record<string, unknown>,
},
});
// Session start is the one reliable moment a query handle exists, so
// it doubles as the account-limits refresh point (throttled inside).
yield* refreshAccountUsageSnapshot(context);
return;
case "status":
yield* offerRuntimeEvent({
@@ -3405,6 +3422,64 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
}
});
let lastAccountUsageFetchAtMs = 0;
/**
* Pulls the full rate-limit window set (5h, weekly, model-scoped) through
* the SDK usage control request and re-emits it as
* `account.rate-limits.updated`. The streamed `rate_limit_event` only ever
* names the single window currently binding, and Claude limits never reach
* disk, so this pull is the only source that shows every window at once.
*/
const emitAccountUsageSnapshot = Effect.fn("emitAccountUsageSnapshot")(function* (
context: ClaudeSessionContext,
) {
if (!context.query.usage_EXPERIMENTAL_MAY_CHANGE_DO_NOT_RELY_ON_THIS_API_YET) return;
const now = yield* Clock.currentTimeMillis;
const elapsed = now - lastAccountUsageFetchAtMs;
// A negative elapsed means the wall clock stepped backwards; treat it as
// expired rather than freezing refreshes until the clock catches up.
if (elapsed >= 0 && elapsed < ACCOUNT_USAGE_MIN_INTERVAL_MS) return;
lastAccountUsageFetchAtMs = now;
const usage = yield* Effect.promise(async () => {
try {
// Called through the query object so the SDK method keeps its
// receiver; an extracted reference loses `this` and throws.
return await context.query.usage_EXPERIMENTAL_MAY_CHANGE_DO_NOT_RELY_ON_THIS_API_YET?.();
} catch {
return undefined;
}
});
if (!usage || usage.rate_limits === null || usage.rate_limits === undefined) return;
const stamp = yield* makeEventStamp();
yield* offerRuntimeEvent({
eventId: stamp.eventId,
provider: PROVIDER,
createdAt: stamp.createdAt,
threadId: context.session.threadId,
providerRefs: nativeProviderRefs(context),
type: "account.rate-limits.updated",
// Only the limit fields travel: the full response also carries session
// cost and a local behaviors scan that have no consumer here.
payload: {
rateLimits: {
subscription_type: usage.subscription_type,
rate_limits: usage.rate_limits,
},
},
});
});
/** Fire-and-forget wrapper: a slow claude.ai fetch must not stall the pump. */
const refreshAccountUsageSnapshot = (context: ClaudeSessionContext) =>
emitAccountUsageSnapshot(context).pipe(
Effect.ignoreCause({ log: true }),
Effect.forkDetach,
Effect.asVoid,
);
const handleSdkTelemetryMessage = Effect.fn("handleSdkTelemetryMessage")(function* (
context: ClaudeSessionContext,
message: SDKMessage,
@@ -3511,6 +3586,10 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
case "auth_status":
case "rate_limit_event":
yield* handleSdkTelemetryMessage(context, message);
if (message.type === "rate_limit_event") {
// The streamed event names one window; refresh the full set too.
yield* refreshAccountUsageSnapshot(context);
}
return;
// Composer prompt suggestions have no T3 surface; consumed deliberately.
case "prompt_suggestion":
+2
View File
@@ -150,6 +150,7 @@ import * as NativeTelemetryClient from "./resourceTelemetry/NativeTelemetryClien
import * as ResourceAttribution from "./resourceTelemetry/ResourceAttribution.ts";
import * as ResourceTelemetry from "./resourceTelemetry/ResourceTelemetry.ts";
import * as UsageService from "./usage/UsageService.ts";
import * as AccountLimitsService from "./usage/AccountLimitsService.ts";
import * as Data from "effect/Data";
import { makeOrchestrationIntegrationHarness } from "../integration/OrchestrationEngineHarness.integration.ts";
@@ -827,6 +828,7 @@ const buildAppUnderTest = (options?: {
const appLayer = servedRoutesLayer.pipe(
Layer.provide(resourceTelemetryLayer),
Layer.provide(UsageService.layerTest),
Layer.provide(AccountLimitsService.layerTest),
Layer.provide(
Layer.mock(BrowserTraceCollector.BrowserTraceCollector)({
record: () => Effect.void,
+6
View File
@@ -102,6 +102,7 @@ import * as ResourceAttribution from "./resourceTelemetry/ResourceAttribution.ts
import * as ResourceMonitorBinary from "./resourceTelemetry/ResourceMonitorBinary.ts";
import * as ResourceTelemetry from "./resourceTelemetry/ResourceTelemetry.ts";
import * as UsageService from "./usage/UsageService.ts";
import * as AccountLimitsService from "./usage/AccountLimitsService.ts";
import { OrchestrationLayerLive } from "./orchestration/runtimeLayer.ts";
import {
clearPersistedServerRuntimeState,
@@ -161,6 +162,10 @@ const BackgroundLayerLive = BackgroundPolicy.layer.pipe(
const UsageLayerLive = UsageService.layer.pipe(Layer.provide(ServerSettingsLayerLive));
const AccountLimitsLayerLive = AccountLimitsService.layer.pipe(
Layer.provide(ServerSettingsLayerLive),
);
const ResourceDiagnosticsLayerLive = Layer.mergeAll(
ResourceTelemetryLayerLive,
ProcessDiagnostics.layer.pipe(Layer.provide(ResourceTelemetryLayerLive)),
@@ -414,6 +419,7 @@ const RuntimeDependenciesLive = RuntimeCoreDependenciesLive.pipe(
Layer.provideMerge(BackgroundLayerLive),
Layer.provideMerge(ResourceDiagnosticsLayerLive),
Layer.provideMerge(UsageLayerLive),
Layer.provideMerge(AccountLimitsLayerLive),
Layer.provideMerge(TraceDiagnostics.layer),
Layer.provideMerge(AnalyticsService.layer),
Layer.provideMerge(ExternalLauncher.layer),
@@ -0,0 +1,281 @@
/**
* AccountLimitsService - the server-wide account rate-limit cache.
*
* Fed passively: runtime ingestion forwards every
* `account.rate-limits.updated` event here (Claude usage snapshots and
* single-window events, Codex app-server notifications), so the cache costs
* nothing while sessions run. When asked and Codex has no live snapshot, the
* newest transcript snapshot is recovered from disk. Claude has no disk
* fallback: its limits exist only on the live stream, which is why snapshots
* are persisted across restarts.
*
* One snapshot per provider: T3 Code drives one account per provider today.
*
* @module AccountLimitsService
*/
import {
ACCOUNT_LIMITS_CONTRACT_VERSION,
AccountLimitsSnapshot,
type AccountLimitsSummary,
type UsageProviderKind,
} from "@t3tools/contracts";
import * as Clock from "effect/Clock";
import * as Context from "effect/Context";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Path from "effect/Path";
import * as Schema from "effect/Schema";
import * as Semaphore from "effect/Semaphore";
import { writeFileStringAtomically } from "../atomicWrite.ts";
import { ServerConfig } from "../config.ts";
import * as ServerSettings from "../serverSettings.ts";
import { resolveCodexHomeLayout } from "../provider/Drivers/CodexHomeLayout.ts";
import {
claudeUsageSnapshotFromUnknown,
claudeWindowFromRateLimitEvent,
codexSnapshotFromUnknown,
isPrimaryCodexLimit,
sortWindows,
} from "./accountLimitsNormalize.ts";
import { readLatestCodexRateLimits } from "./accountLimitsTranscripts.ts";
/** Failed or empty transcript scans are not retried more often than this. */
const CODEX_SEED_MIN_INTERVAL_MS = 60_000;
/** On-disk shape of the snapshot cache: the contract array, JSON-encoded. */
const LimitsCacheFile = Schema.Array(AccountLimitsSnapshot);
const decodeLimitsCache = Schema.decodeUnknownEffect(
Schema.fromJsonString(LimitsCacheFile as unknown as Schema.Codec<typeof LimitsCacheFile.Type>),
);
const encodeLimitsCache = Schema.encodeEffect(
Schema.fromJsonString(LimitsCacheFile as unknown as Schema.Codec<typeof LimitsCacheFile.Type>),
);
export interface AccountLimitsIngestInput {
/** Driver kind off the runtime event (`claudeAgent`, `codex`, ...). */
readonly provider: string;
/** The event's `payload.rateLimits`, in whatever shape the adapter emitted. */
readonly payload: unknown;
readonly createdAt: string;
}
export class AccountLimitsService extends Context.Service<
AccountLimitsService,
{
readonly readSummary: () => Effect.Effect<AccountLimitsSummary>;
readonly ingest: (input: AccountLimitsIngestInput) => Effect.Effect<void>;
}
>()("t3/usage/AccountLimitsService") {}
/** Empty cache, for suites that only need the RPC surface to resolve. */
export const layerTest = Layer.succeed(
AccountLimitsService,
AccountLimitsService.of({
readSummary: () =>
Effect.succeed({
contractVersion: ACCOUNT_LIMITS_CONTRACT_VERSION,
readAt: "1970-01-01T00:00:00.000Z",
snapshots: [],
}),
ingest: () => Effect.void,
}),
);
function providerFromDriver(driver: string): UsageProviderKind | null {
if (driver === "claudeAgent") return "claude";
if (driver === "codex") return "codex";
return null;
}
export const make = Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const config = yield* ServerConfig;
const settingsService = yield* ServerSettings.ServerSettingsService;
const snapshots = new Map<UsageProviderKind, AccountLimitsSnapshot>();
const cachePath = path.join(config.stateDir, "account-limits.json");
let lastCodexSeedAttemptAtMs = 0;
// Restarts must not lose the Claude snapshot (stream-only, no disk source),
// so the cache is persisted. Same Effect.cached trick as the usage scan
// cache: concurrent first readers await one load.
const ensureLoaded = yield* Effect.cached(
Effect.gen(function* () {
const stored = yield* fileSystem.readFileString(cachePath).pipe(
Effect.flatMap((raw) => decodeLimitsCache(raw)),
Effect.catchCause(() => Effect.succeed(null)),
);
if (stored === null) return;
for (const snapshot of stored) {
if (!snapshots.has(snapshot.provider)) snapshots.set(snapshot.provider, snapshot);
}
}),
);
/**
* All snapshot mutations - event ingest (worker fiber) and the transcript
* seed (RPC fiber) - run under this one permit, so each ordering guard,
* map write, and persist is atomic with respect to the others. Without it
* a concurrent pair can both pass their guard against the same prior
* snapshot and land in either order, rolling the state backwards. Reads
* stay lock-free.
*/
const stateLock = yield* Semaphore.make(1);
// A cache we cannot write is a colder next start, not a failure. Only
// called while holding `stateLock`, which is what serializes writes; the
// temp-file + rename keeps a crashed write from tearing the file.
const persist = Effect.fn("AccountLimitsService.persist")(function* () {
yield* encodeLimitsCache([...snapshots.values()]).pipe(
Effect.flatMap((serialized) =>
writeFileStringAtomically({ filePath: cachePath, contents: serialized }),
),
Effect.provideService(FileSystem.FileSystem, fileSystem),
Effect.provideService(Path.Path, path),
Effect.catchCause(() => Effect.void),
);
});
const store = Effect.fn("AccountLimitsService.store")(function* (
snapshot: AccountLimitsSnapshot,
) {
snapshots.set(snapshot.provider, snapshot);
yield* persist();
});
const ingestClaude = Effect.fn("AccountLimitsService.ingestClaude")(function* (
payload: unknown,
createdAt: string,
) {
const previous = snapshots.get("claude");
const full = claudeUsageSnapshotFromUnknown(payload);
if (full !== null) {
// Rate limits do not apply to this account (API key / Bedrock / Vertex):
// nothing to show, and nothing worth clearing a previous snapshot over.
if (full.windows.length === 0) return;
yield* store({
provider: "claude",
plan: full.plan ?? previous?.plan ?? null,
windows: full.windows,
asOf: createdAt,
source: "live",
});
return;
}
// The streamed event names one window; patch it into whatever set the
// last full snapshot established.
const window = claudeWindowFromRateLimitEvent(payload);
if (window === null) return;
const windows = sortWindows([
...(previous?.windows ?? []).filter((existing) => existing.id !== window.id),
window,
]);
yield* store({
provider: "claude",
plan: previous?.plan ?? null,
windows,
asOf: createdAt,
source: "live",
});
});
const ingestCodex = Effect.fn("AccountLimitsService.ingestCodex")(function* (
payload: unknown,
createdAt: string,
) {
const snapshot = codexSnapshotFromUnknown(payload);
if (snapshot === null) return;
// Per-model side meters (Spark) are not surfaced.
if (!isPrimaryCodexLimit(snapshot.limitId)) return;
if (snapshot.windows.length === 0) return;
const previous = snapshots.get("codex");
yield* store({
provider: "codex",
plan: snapshot.plan ?? previous?.plan ?? null,
windows: snapshot.windows,
asOf: createdAt,
source: "live",
});
});
const ingest = Effect.fn("AccountLimitsService.ingest")(function* (
input: AccountLimitsIngestInput,
) {
const provider = providerFromDriver(input.provider);
if (provider === null) return;
yield* ensureLoaded;
yield* stateLock.withPermits(1)(
Effect.gen(function* () {
// Guard against out-of-order delivery: an event older than what is
// already stored must not roll the snapshot backwards.
const existing = snapshots.get(provider);
if (existing !== undefined && input.createdAt < existing.asOf) return;
if (provider === "claude") {
yield* ingestClaude(input.payload, input.createdAt);
} else {
yield* ingestCodex(input.payload, input.createdAt);
}
}),
);
});
/**
* Recovers the Codex snapshot from session transcripts when they are newer
* than what the cache holds - which covers both a cold cache and Codex
* sessions driven outside T3 Code.
*/
const maybeSeedCodexFromTranscripts = Effect.fn("AccountLimitsService.seedCodex")(function* (
nowMs: number,
) {
if (nowMs - lastCodexSeedAttemptAtMs < CODEX_SEED_MIN_INTERVAL_MS) return;
lastCodexSeedAttemptAtMs = nowMs;
const settings = yield* settingsService.getSettings.pipe(
Effect.catchCause(() => Effect.succeed(null)),
);
if (settings === null) return;
const layout = yield* resolveCodexHomeLayout(settings.providers.codex).pipe(
Effect.provideService(Path.Path, path),
);
const sessionsDir = path.join(layout.sharedHomePath, "sessions");
const found = yield* Effect.promise(() => readLatestCodexRateLimits(sessionsDir, nowMs));
if (found === null) return;
const asOf = DateTime.formatIso(DateTime.makeUnsafe(found.asOfMs));
// The slow transcript read happened outside the lock; only the
// guard-and-store is serialized against live ingests.
yield* stateLock.withPermits(1)(
Effect.gen(function* () {
const existing = snapshots.get("codex");
// ISO-8601 strings order lexicographically.
if (existing !== undefined && existing.asOf >= asOf) return;
yield* store({
provider: "codex",
plan: found.snapshot.plan ?? existing?.plan ?? null,
windows: found.snapshot.windows,
asOf,
source: "transcript",
});
}),
);
});
const readSummary = Effect.fn("AccountLimitsService.readSummary")(function* () {
yield* ensureLoaded;
const nowMs = yield* Clock.currentTimeMillis;
yield* maybeSeedCodexFromTranscripts(nowMs).pipe(Effect.catchCause(() => Effect.void));
return {
contractVersion: ACCOUNT_LIMITS_CONTRACT_VERSION,
readAt: DateTime.formatIso(DateTime.makeUnsafe(nowMs)),
snapshots: [...snapshots.values()].sort((a, b) => a.provider.localeCompare(b.provider)),
} satisfies AccountLimitsSummary;
});
return { readSummary, ingest } as const;
});
export const layer = Layer.effect(AccountLimitsService, make);
@@ -0,0 +1,171 @@
import { describe, expect, it } from "@effect/vitest";
import * as DateTime from "effect/DateTime";
import {
claudeUsageSnapshotFromUnknown,
claudeWindowFromRateLimitEvent,
codexSnapshotFromUnknown,
isPrimaryCodexLimit,
} from "./accountLimitsNormalize.ts";
describe("claudeUsageSnapshotFromUnknown", () => {
it("keeps 5h, weekly and Fable; hides oauth-apps and model weeklies", () => {
const snapshot = claudeUsageSnapshotFromUnknown({
subscription_type: "max",
rate_limits: {
five_hour: { utilization: 62, resets_at: "2026-08-08T23:00:00.000Z" },
seven_day: { utilization: 41, resets_at: "2026-08-11T17:00:00.000Z" },
seven_day_oauth_apps: { utilization: 5, resets_at: null },
seven_day_opus: { utilization: 78, resets_at: null },
seven_day_sonnet: { utilization: 12, resets_at: null },
iguana_necktie: { utilization: 30, resets_at: "2026-08-11T17:00:00.000Z" },
},
});
expect(snapshot?.plan).toBe("max");
expect(snapshot?.windows.map((window) => window.id)).toEqual([
"five_hour",
"seven_day",
"fable",
]);
expect(snapshot?.windows[2]).toMatchObject({ label: "Fable", usedPercent: 30 });
});
it("reads the newer limits array, including a Fable-scoped weekly", () => {
const snapshot = claudeUsageSnapshotFromUnknown({
subscription_type: "max",
rate_limits: {
five_hour: null,
limits: [
{ kind: "session", percent: 10, resets_at: "2026-08-08T23:00:00.000Z" },
{ kind: "weekly_all", percent: 20, resets_at: "2026-08-11T17:00:00.000Z" },
{
kind: "weekly_scoped",
percent: 55,
resets_at: "2026-08-11T17:00:00.000Z",
scope: { model: { id: "claude-fable-5", display_name: "Fable" } },
},
{
kind: "weekly_scoped",
percent: 90,
resets_at: null,
scope: { model: { id: "claude-opus-5", display_name: "Opus" } },
},
],
},
});
expect(snapshot?.windows.map((window) => [window.id, window.usedPercent])).toEqual([
["five_hour", 10],
["seven_day", 20],
["fable", 55],
]);
});
it("treats a null utilization as an untouched window", () => {
const snapshot = claudeUsageSnapshotFromUnknown({
subscription_type: null,
rate_limits: { five_hour: { utilization: null, resets_at: null } },
});
expect(snapshot?.windows).toEqual([
{ id: "five_hour", label: "5h", usedPercent: 0, resetsAt: null, windowMinutes: 300 },
]);
});
it("returns empty windows when rate limits do not apply", () => {
expect(claudeUsageSnapshotFromUnknown({ rate_limits: null })?.windows).toEqual([]);
});
it("rejects shapes that are not the usage response", () => {
expect(claudeUsageSnapshotFromUnknown({ rate_limit_info: {} })).toBeNull();
});
});
describe("claudeWindowFromRateLimitEvent", () => {
it("maps the binding window with a unix-seconds reset", () => {
const window = claudeWindowFromRateLimitEvent({
type: "rate_limit_event",
rate_limit_info: {
status: "allowed_warning",
rateLimitType: "five_hour",
utilization: 87.5,
resetsAt: 1_786_600_800,
},
});
expect(window).toEqual({
id: "five_hour",
label: "5h",
usedPercent: 87.5,
resetsAt: DateTime.formatIso(DateTime.makeUnsafe(1_786_600_800_000)),
windowMinutes: 300,
});
});
it("drops hidden window types", () => {
expect(
claudeWindowFromRateLimitEvent({
rate_limit_info: { rateLimitType: "seven_day_opus", utilization: 90 },
}),
).toBeNull();
});
});
describe("codexSnapshotFromUnknown", () => {
it("classifies the current weekly-in-primary payload by duration, not slot", () => {
// Shaped after a real transcript line: the 5h window is paused, so the
// weekly rides in the primary slot.
const snapshot = codexSnapshotFromUnknown({
limit_id: "codex",
limit_name: null,
primary: { used_percent: 14, window_minutes: 10080, resets_at: 1_786_677_720 },
secondary: null,
plan_type: "pro",
});
expect(snapshot?.plan).toBe("pro");
expect(snapshot?.windows).toEqual([
{
id: "seven_day",
label: "Week",
usedPercent: 14,
resetsAt: DateTime.formatIso(DateTime.makeUnsafe(1_786_677_720_000)),
windowMinutes: 10080,
},
]);
});
it("brings the 5h window back the moment the API ships it again", () => {
const snapshot = codexSnapshotFromUnknown({
rateLimits: {
limitId: "codex",
planType: "pro",
primary: { usedPercent: 23, windowDurationMins: 300, resetsAt: 1_786_600_800 },
secondary: { usedPercent: 14, windowDurationMins: 10080, resetsAt: 1_786_677_720 },
},
});
expect(snapshot?.windows.map((window) => window.id)).toEqual(["five_hour", "seven_day"]);
});
it("falls back to slot order for legacy payloads without durations", () => {
const snapshot = codexSnapshotFromUnknown({
primary: { used_percent: 40 },
secondary: { used_percent: 10 },
});
expect(snapshot?.windows.map((window) => [window.id, window.usedPercent])).toEqual([
["five_hour", 40],
["seven_day", 10],
]);
});
it("flags side meters like Spark so they can be dropped", () => {
const snapshot = codexSnapshotFromUnknown({
limit_id: "codex_bengalfox",
limit_name: "GPT-5.3-Codex-Spark",
primary: { used_percent: 0, window_minutes: 10080, resets_at: 1_786_828_412 },
});
expect(snapshot?.limitId).toBe("codex_bengalfox");
expect(isPrimaryCodexLimit(snapshot?.limitId ?? null)).toBe(false);
expect(isPrimaryCodexLimit("codex")).toBe(true);
expect(isPrimaryCodexLimit(null)).toBe(true);
});
});
@@ -0,0 +1,315 @@
/**
* Normalizers for provider rate-limit payloads.
*
* Both adapters emit `account.rate-limits.updated` runtime events whose
* payload is whatever the provider produced:
*
* - Claude, full set: the SDK usage control response
* (`{ subscription_type, rate_limits: { five_hour, seven_day, ... } }`).
* - Claude, single window: the streamed `rate_limit_event` SDK message
* (`{ rate_limit_info: { rateLimitType, utilization, resetsAt } }`), which
* only ever names the window that is currently binding.
* - Codex, live: the `account/rateLimits/updated` app-server notification
* (`{ rateLimits: { limitId, primary, secondary, planType, ... } }`,
* camelCase).
* - Codex, transcript: the `rate_limits` object Codex writes beside every
* `token_count` line in its session files (same snapshot, snake_case).
*
* Everything folds into the `AccountLimitsWindow` contract shape here so the
* service and clients never see a provider-specific field name.
*
* @module accountLimitsNormalize
*/
import type { AccountLimitsWindow } from "@t3tools/contracts";
import * as DateTime from "effect/DateTime";
const FIVE_HOUR_MINUTES = 5 * 60;
const SEVEN_DAY_MINUTES = 7 * 24 * 60;
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null;
}
function readNumber(value: unknown): number | null {
return typeof value === "number" && Number.isFinite(value) ? value : null;
}
function readString(value: unknown): string | null {
return typeof value === "string" && value.trim().length > 0 ? value : null;
}
function clampPercent(value: number): number {
return Math.min(100, Math.max(0, value));
}
function isoFromUnixSeconds(value: number): string {
return DateTime.formatIso(DateTime.makeUnsafe(value * 1000));
}
/**
* Window ordering for display: the short window first, then the weekly, then
* scoped windows.
*/
export function sortWindows(windows: readonly AccountLimitsWindow[]): AccountLimitsWindow[] {
const rank = (window: AccountLimitsWindow): number =>
window.id === "five_hour" ? 0 : window.id === "seven_day" ? 1 : 2;
return [...windows].sort(
(a, b) => rank(a) - rank(b) || (a.windowMinutes ?? 0) - (b.windowMinutes ?? 0),
);
}
// ---------------------------------------------------------------------------
// Claude
// ---------------------------------------------------------------------------
/**
* Windows we receive but deliberately do not surface: the oauth-apps bucket
* and the opus/sonnet scoped weeklies are noise next to the three windows
* users actually plan around (5h, weekly, Fable). `extra_usage` and `overage`
* are credit meters, not windows.
*/
const CLAUDE_HIDDEN_WINDOW_KEYS = new Set([
"seven_day_oauth_apps",
"seven_day_opus",
"seven_day_sonnet",
"extra_usage",
"overage",
]);
interface ClaudeWindowMeta {
readonly id: string;
readonly label: string;
readonly minutes: number | null;
}
/**
* Maps a Claude window key to its display identity, or null for hidden keys.
*
* Unrecognised keys still become windows (with a humanized label) so a window
* Anthropic adds or renames shows up without a code change. The Fable weekly
* has already lived under more than one name, so anything fable-ish is
* normalised onto one id.
*/
function claudeWindowMeta(key: string): ClaudeWindowMeta | null {
if (CLAUDE_HIDDEN_WINDOW_KEYS.has(key)) return null;
if (key === "five_hour") return { id: "five_hour", label: "5h", minutes: FIVE_HOUR_MINUTES };
if (key === "seven_day") return { id: "seven_day", label: "Week", minutes: SEVEN_DAY_MINUTES };
if (key === "iguana_necktie" || key.toLowerCase().includes("fable")) {
return { id: "fable", label: "Fable", minutes: SEVEN_DAY_MINUTES };
}
const stripped = key.startsWith("seven_day_") ? key.slice("seven_day_".length) : key;
const label = stripped.replace(/_/g, " ").replace(/^./, (c) => c.toUpperCase());
return {
id: key,
label,
minutes: key.startsWith("seven_day") ? SEVEN_DAY_MINUTES : null,
};
}
function claudeWindowFromEntry(meta: ClaudeWindowMeta, entry: unknown): AccountLimitsWindow | null {
if (!isRecord(entry)) return null;
if (!("utilization" in entry) && !("resets_at" in entry)) return null;
const utilization = readNumber(entry.utilization);
return {
id: meta.id,
label: meta.label,
// A null utilization is an untouched window, which is 0% used.
usedPercent: utilization === null ? 0 : clampPercent(utilization),
resetsAt: readString(entry.resets_at),
windowMinutes: meta.minutes,
};
}
export interface ClaudeUsageSnapshot {
readonly plan: string | null;
readonly windows: AccountLimitsWindow[];
}
/**
* Parses the SDK usage control response. Returns null when the value is not
* that shape (so the caller can try the single-event shape instead), and an
* empty window list when rate limits do not apply (API key, Bedrock, Vertex).
*/
export function claudeUsageSnapshotFromUnknown(value: unknown): ClaudeUsageSnapshot | null {
if (!isRecord(value)) return null;
const rateLimits = value.rate_limits;
if (rateLimits === null) return { plan: readString(value.subscription_type), windows: [] };
if (!isRecord(rateLimits)) return null;
const windows = new Map<string, AccountLimitsWindow>();
for (const [key, entry] of Object.entries(rateLimits)) {
if (key === "limits") continue;
const meta = claudeWindowMeta(key);
if (!meta) continue;
const window = claudeWindowFromEntry(meta, entry);
if (window) windows.set(window.id, window);
}
// Newer payloads replace the flat keys with a self-describing `limits`
// array. Read both; array entries win because the flat keys go null first.
const limits = rateLimits.limits;
if (Array.isArray(limits)) {
for (const entry of limits) {
const window = claudeWindowFromLimitEntry(entry);
if (window) windows.set(window.id, window);
}
}
return { plan: readString(value.subscription_type), windows: sortWindows([...windows.values()]) };
}
/** One entry of the newer `rate_limits.limits` array. */
function claudeWindowFromLimitEntry(entry: unknown): AccountLimitsWindow | null {
if (!isRecord(entry)) return null;
const percent = readNumber(entry.percent);
const resetsAt = readString(entry.resets_at);
const kind = readString(entry.kind);
if (kind === "session") {
return {
id: "five_hour",
label: "5h",
usedPercent: percent === null ? 0 : clampPercent(percent),
resetsAt,
windowMinutes: FIVE_HOUR_MINUTES,
};
}
if (kind === "weekly_all") {
return {
id: "seven_day",
label: "Week",
usedPercent: percent === null ? 0 : clampPercent(percent),
resetsAt,
windowMinutes: SEVEN_DAY_MINUTES,
};
}
if (kind === "weekly_scoped") {
const scope = isRecord(entry.scope) ? entry.scope : null;
const model = scope && isRecord(scope.model) ? scope.model : null;
const name = (model && (readString(model.display_name) ?? readString(model.id))) ?? null;
if (name === null) return null;
// Same visibility call as the flat keys: Fable is its own limit worth
// showing, the opus/sonnet scoped weeklies are hidden.
if (/opus|sonnet/i.test(name)) return null;
const isFable = /fable/i.test(name);
return {
id: isFable ? "fable" : `scoped_${name.toLowerCase().replace(/[^a-z0-9]+/g, "_")}`,
label: isFable ? "Fable" : name,
usedPercent: percent === null ? 0 : clampPercent(percent),
resetsAt,
windowMinutes: SEVEN_DAY_MINUTES,
};
}
return null;
}
/**
* Parses the streamed `rate_limit_event` SDK message into the one window it
* names. Returns null for shapes that are not that message, and for windows
* we hide.
*/
export function claudeWindowFromRateLimitEvent(value: unknown): AccountLimitsWindow | null {
if (!isRecord(value)) return null;
const info = value.rate_limit_info;
if (!isRecord(info)) return null;
const type = readString(info.rateLimitType);
if (type === null) return null;
const meta = claudeWindowMeta(type);
if (!meta) return null;
const utilization = readNumber(info.utilization);
const resetsAt = readNumber(info.resetsAt);
return {
id: meta.id,
label: meta.label,
usedPercent: utilization === null ? 0 : clampPercent(utilization),
resetsAt: resetsAt === null ? null : isoFromUnixSeconds(resetsAt),
windowMinutes: meta.minutes,
};
}
// ---------------------------------------------------------------------------
// Codex
// ---------------------------------------------------------------------------
export interface CodexRateLimitsSnapshot {
readonly limitId: string | null;
readonly plan: string | null;
readonly windows: AccountLimitsWindow[];
}
/**
* The main Codex meter. Other limit ids are per-model side meters (Spark ships
* as `codex_bengalfox` / "GPT-5.3-Codex-Spark") that we do not surface.
*/
export function isPrimaryCodexLimit(limitId: string | null): boolean {
return limitId === null || limitId === "codex";
}
/**
* Parses a Codex rate-limit snapshot, live (camelCase) or transcript
* (snake_case). The live notification nests the snapshot under `rateLimits`.
*/
export function codexSnapshotFromUnknown(value: unknown): CodexRateLimitsSnapshot | null {
if (!isRecord(value)) return null;
const snapshot = isRecord(value.rateLimits) ? value.rateLimits : value;
const limitId = readString(snapshot.limitId ?? snapshot.limit_id);
const plan = readString(snapshot.planType ?? snapshot.plan_type);
const windows: AccountLimitsWindow[] = [];
const primary = codexWindowFromSlot(snapshot.primary, "primary");
if (primary) windows.push(primary);
const secondary = codexWindowFromSlot(snapshot.secondary, "secondary");
if (secondary && !windows.some((window) => window.id === secondary.id)) {
windows.push(secondary);
}
if (windows.length === 0 && limitId === null && plan === null) return null;
return { limitId, plan, windows: sortWindows(windows) };
}
/**
* Classifies a Codex window by its duration, not its slot: OpenAI currently
* ships the weekly window in `primary` with `secondary` empty (the 5-hour
* window is paused), and will presumably shuffle slots again when it returns.
* Slot order is only the fallback for legacy payloads with no duration.
*/
function codexWindowFromSlot(
value: unknown,
slot: "primary" | "secondary",
): AccountLimitsWindow | null {
if (!isRecord(value)) return null;
const usedPercent = readNumber(value.usedPercent ?? value.used_percent);
if (usedPercent === null) return null;
const minutes = readNumber(value.windowDurationMins ?? value.window_minutes);
const resetsAtSeconds = readNumber(value.resetsAt ?? value.resets_at);
const resetsAt = resetsAtSeconds === null ? null : isoFromUnixSeconds(resetsAtSeconds);
const effectiveMinutes = minutes ?? (slot === "primary" ? FIVE_HOUR_MINUTES : SEVEN_DAY_MINUTES);
if (effectiveMinutes === FIVE_HOUR_MINUTES) {
return {
id: "five_hour",
label: "5h",
usedPercent: clampPercent(usedPercent),
resetsAt,
windowMinutes: FIVE_HOUR_MINUTES,
};
}
if (effectiveMinutes === SEVEN_DAY_MINUTES) {
return {
id: "seven_day",
label: "Week",
usedPercent: clampPercent(usedPercent),
resetsAt,
windowMinutes: SEVEN_DAY_MINUTES,
};
}
return {
id: `window_${effectiveMinutes}m`,
label:
effectiveMinutes % (24 * 60) === 0
? `${effectiveMinutes / (24 * 60)}d`
: `${Math.max(1, Math.round(effectiveMinutes / 60))}h`,
usedPercent: clampPercent(usedPercent),
resetsAt,
windowMinutes: effectiveMinutes,
};
}
@@ -0,0 +1,118 @@
// @effect-diagnostics nodeBuiltinImport:off
/**
* Codex transcript recovery for account limits.
*
* Codex writes its full rate-limit snapshot beside every `token_count` line in
* `~/.codex/sessions/**\/*.jsonl`, so the latest snapshot survives on disk even
* when no session has run through T3 Code. Claude has no equivalent: its
* limits exist only on the live SDK stream.
*
* Only file tails are read: the newest lines carry the newest snapshot, and a
* session file can be tens of megabytes. Direct `node:fs` is deliberate, same
* as `usageTranscriptReader`: this is bulk raw-file access on a request path.
*
* @module accountLimitsTranscripts
*/
import * as NodeFSP from "node:fs/promises";
import {
codexSnapshotFromUnknown,
isPrimaryCodexLimit,
type CodexRateLimitsSnapshot,
} from "./accountLimitsNormalize.ts";
import { listTranscriptFiles } from "./usageTranscriptReader.ts";
const TAIL_BYTES = 256 * 1024;
const SCAN_WINDOW_DAYS = 14;
/**
* Newest-first cutoff bounding the scan on the RPC path. The newest file
* almost always hits; the margin covers runs of files without a main-meter
* snapshot (Spark-only sessions, sessions abandoned before any token count).
* If this many consecutive files lack one, the data is genuinely absent.
*/
const MAX_FILES = 32;
export interface CodexTranscriptRateLimits {
readonly snapshot: CodexRateLimitsSnapshot;
readonly asOfMs: number;
}
export async function readLatestCodexRateLimits(
sessionsDir: string,
nowMs: number,
): Promise<CodexTranscriptRateLimits | null> {
let files;
try {
files = await listTranscriptFiles(sessionsDir, nowMs - SCAN_WINDOW_DAYS * 24 * 60 * 60 * 1000);
} catch {
return null;
}
const newestFirst = [...files].sort((a, b) => b.mtimeMs - a.mtimeMs).slice(0, MAX_FILES);
// The newest-mtime file does not necessarily hold the newest snapshot: a
// session can keep appending non-token events after its last rate-limit
// line. A file's snapshot can never be newer than the file's mtime, so
// keep scanning only while a remaining file's mtime could still beat the
// best snapshot found - which usually stops after one or two files.
let best: CodexTranscriptRateLimits | null = null;
for (const file of newestFirst) {
if (best !== null && file.mtimeMs <= best.asOfMs) break;
const found = await readTailRateLimits(file.path, file.mtimeMs);
if (found !== null && (best === null || found.asOfMs > best.asOfMs)) best = found;
}
return best;
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null;
}
async function readTailRateLimits(
filePath: string,
mtimeMs: number,
): Promise<CodexTranscriptRateLimits | null> {
let handle: NodeFSP.FileHandle;
try {
handle = await NodeFSP.open(filePath, "r");
} catch {
return null;
}
try {
const stat = await handle.stat();
const start = Math.max(0, stat.size - TAIL_BYTES);
const length = stat.size - start;
if (length <= 0) return null;
const buffer = Buffer.alloc(length);
await handle.read(buffer, 0, length, start);
// The first line may be cut mid-record by the tail offset; JSON.parse
// rejects it and the scan moves on.
const lines = buffer.toString("utf8").split("\n");
for (let index = lines.length - 1; index >= 0; index -= 1) {
const line = lines[index];
if (!line || !line.includes('"rate_limits"')) continue;
let parsed: unknown;
try {
parsed = JSON.parse(line);
} catch {
continue;
}
if (!isRecord(parsed)) continue;
const payload = isRecord(parsed.payload) ? parsed.payload : null;
if (!payload) continue;
const snapshot = codexSnapshotFromUnknown(payload.rate_limits);
// Side meters (Spark) write their own snapshot lines; keep scanning
// back for the main meter.
if (!snapshot || !isPrimaryCodexLimit(snapshot.limitId) || snapshot.windows.length === 0) {
continue;
}
const timestamp =
typeof parsed.timestamp === "string" ? Date.parse(parsed.timestamp) : Number.NaN;
return { snapshot, asOfMs: Number.isFinite(timestamp) ? timestamp : mtimeMs };
}
return null;
} catch {
return null;
} finally {
await handle.close().catch(() => {});
}
}
+6
View File
@@ -106,6 +106,7 @@ import * as ProcessDiagnostics from "./diagnostics/ProcessDiagnostics.ts";
import * as ProcessResourceMonitor from "./diagnostics/ProcessResourceMonitor.ts";
import * as ResourceTelemetry from "./resourceTelemetry/ResourceTelemetry.ts";
import * as UsageService from "./usage/UsageService.ts";
import * as AccountLimitsService from "./usage/AccountLimitsService.ts";
import * as TraceDiagnostics from "./diagnostics/TraceDiagnostics.ts";
import * as SourceControlDiscovery from "./sourceControl/SourceControlDiscovery.ts";
import * as SourceControlRepositoryService from "./sourceControl/SourceControlRepositoryService.ts";
@@ -414,6 +415,7 @@ const makeWsRpcLayer = (
const processResourceMonitor = yield* ProcessResourceMonitor.ProcessResourceMonitor;
const resourceTelemetry = yield* ResourceTelemetry.ResourceTelemetry;
const usage = yield* UsageService.UsageService;
const accountLimits = yield* AccountLimitsService.AccountLimitsService;
const relayClient = yield* RelayClient.RelayClient;
const authorizationError = (requiredScope: AuthEnvironmentScope) =>
new EnvironmentAuthorizationError({
@@ -1535,6 +1537,10 @@ const makeWsRpcLayer = (
observeRpcEffect(WS_METHODS.serverGetUsageSummary, usage.readSummary(input), {
"rpc.aggregate": "server",
}),
[WS_METHODS.serverGetAccountLimits]: (_input) =>
observeRpcEffect(WS_METHODS.serverGetAccountLimits, accountLimits.readSummary(), {
"rpc.aggregate": "server",
}),
[WS_METHODS.serverRetryResourceTelemetry]: (_input) =>
observeRpcEffect(WS_METHODS.serverRetryResourceTelemetry, resourceTelemetry.retry, {
"rpc.aggregate": "server",
@@ -20,6 +20,7 @@ import {
SidebarTrigger,
useSidebar,
} from "../ui/sidebar";
import { AccountLimitsHoverCard } from "../usage/AccountLimits";
import { SidebarProviderUpdatePill } from "./SidebarProviderUpdatePill";
import { SidebarUpdatePill } from "./SidebarUpdatePill";
@@ -131,7 +132,19 @@ export const SidebarChromeFooter = memo(function SidebarChromeFooter() {
<SidebarUpdatePill />
<SidebarMenu>
<SidebarMenuItem>
<SidebarMenuButton onClick={handleUsageClick}>
{/* `hidden: false` overrides the sidebar default of only showing
menu tooltips while collapsed: availability is worth a hover in
either state. */}
<SidebarMenuButton
onClick={handleUsageClick}
tooltip={{
hidden: false,
side: "right",
align: "end",
sideOffset: 8,
children: <AccountLimitsHoverCard />,
}}
>
<ChartNoAxesColumnIcon />
<span>Usage</span>
</SidebarMenuButton>
@@ -0,0 +1,190 @@
/**
* Account rate-limit views: the sidebar hover card and the usage page's
* "Limits" strip. Both render whatever windows the server reports, so a
* window a provider adds or brings back (Codex's paused 5-hour) appears
* without a client change.
*
* Every percentage is labelled `used` inline - a bare number cannot say
* whether it is used or remaining. Snapshot age only renders once the data
* is actually stale; fresh data needs no caption.
*
* @module AccountLimits
*/
import type { AccountLimitsSnapshot, AccountLimitsWindow } from "@t3tools/contracts";
import { useEffect, useState } from "react";
import { cn } from "../../lib/utils";
import { useAccountLimits } from "../../state/accountLimits";
import { formatAgo, formatResetAt } from "../../usage/limitsFormat";
import { PROVIDER_COLOR, PROVIDER_LABEL, PROVIDER_MARK, PROVIDER_ORDER } from "./usageProviders";
/** Age past which a snapshot stops being "current" and earns a caption. */
const STALE_AFTER_MS = 15 * 60_000;
/**
* Reset countdowns and snapshot ages drift as time passes, not as data
* changes; a coarse tick keeps them honest without re-fetching.
*/
function useNowMs(intervalMs = 30_000): number {
const [nowMs, setNowMs] = useState(() => Date.now());
useEffect(() => {
const timer = window.setInterval(() => setNowMs(Date.now()), intervalMs);
return () => window.clearInterval(timer);
}, [intervalMs]);
return nowMs;
}
function usageTone(usedPercent: number): string | undefined {
if (usedPercent >= 95) return "text-red-400";
if (usedPercent >= 80) return "text-amber-400";
return undefined;
}
function LimitMeter({ window, color }: { window: AccountLimitsWindow; color: string }) {
return (
<div className="h-1 flex-1 overflow-hidden rounded-full bg-muted">
<div
className="h-full rounded-full"
style={{
width: `${Math.min(100, Math.max(0, window.usedPercent))}%`,
backgroundColor: color,
}}
/>
</div>
);
}
/** `6h ago`, and only once the snapshot is old enough to matter. */
function SnapshotAge({ snapshot, nowMs }: { snapshot: AccountLimitsSnapshot; nowMs: number }) {
const ageMs = nowMs - Date.parse(snapshot.asOf);
if (!Number.isFinite(ageMs) || ageMs < STALE_AFTER_MS) return null;
return (
<span className="text-[10px] text-muted-foreground">{formatAgo(snapshot.asOf, nowMs)}</span>
);
}
// ---------------------------------------------------------------------------
// Sidebar hover card
// ---------------------------------------------------------------------------
/** Compact per-provider availability, shown on hovering the Usage button. */
export function AccountLimitsHoverCard() {
const { snapshots, isPending, isSettling } = useAccountLimits();
const nowMs = useNowMs();
if (isPending && snapshots.size === 0) {
return <p className="px-1 py-2 text-xs text-muted-foreground">Loading limits…</p>;
}
return (
<div className="flex w-64 flex-col gap-2.5 p-1.5">
{PROVIDER_ORDER.map((provider) => {
const snapshot = snapshots.get(provider);
const Mark = PROVIDER_MARK[provider];
return (
<div key={provider} className="flex flex-col gap-1">
<div className="flex items-baseline gap-1.5">
<Mark className="size-3 shrink-0 self-center" />
<span className="text-xs font-medium text-foreground">
{PROVIDER_LABEL[provider]}
</span>
<span className="ml-auto">
{snapshot !== undefined ? <SnapshotAge snapshot={snapshot} nowMs={nowMs} /> : null}
</span>
</div>
{snapshot === undefined || snapshot.windows.length === 0 ? (
<p className="text-[11px] text-muted-foreground">
{snapshot === undefined && isSettling ? "Loading…" : "No limit data yet"}
</p>
) : (
snapshot.windows.map((window) => (
<div key={window.id} className="flex items-center gap-2">
<span className="w-9 shrink-0 text-[10px] text-muted-foreground">
{window.label}
</span>
<LimitMeter window={window} color={PROVIDER_COLOR[provider]} />
<span
className={cn(
"shrink-0 whitespace-nowrap text-right text-[11px] tabular-nums text-foreground",
usageTone(window.usedPercent),
)}
>
{Math.round(window.usedPercent)}% used
</span>
<span className="shrink-0 whitespace-nowrap text-right text-[10px] tabular-nums text-muted-foreground">
{formatResetAt(window.resetsAt, nowMs) ?? ""}
</span>
</div>
))
)}
</div>
);
})}
</div>
);
}
// ---------------------------------------------------------------------------
// Usage page section
// ---------------------------------------------------------------------------
/** The "Limits" strip above the analytics: one column per provider. */
export function AccountLimitsSection() {
const { snapshots, isSettling } = useAccountLimits();
const nowMs = useNowMs();
return (
<section className="flex flex-col gap-3">
<h2 className="text-sm font-medium text-foreground">Limits</h2>
<div className="grid gap-x-12 gap-y-4 sm:grid-cols-2">
{PROVIDER_ORDER.map((provider) => {
const snapshot = snapshots.get(provider);
const Mark = PROVIDER_MARK[provider];
return (
<div key={provider} className="flex flex-col gap-1.5">
<div className="flex items-baseline gap-2">
<Mark className="size-3.5 shrink-0 self-center" />
<span className="text-sm font-medium text-foreground">
{PROVIDER_LABEL[provider]}
</span>
<span className="ml-auto">
{snapshot !== undefined ? (
<SnapshotAge snapshot={snapshot} nowMs={nowMs} />
) : null}
</span>
</div>
{snapshot === undefined || snapshot.windows.length === 0 ? (
<p className="text-xs text-muted-foreground">
{snapshot === undefined && isSettling ? "Loading…" : "No limit data yet"}
</p>
) : (
snapshot.windows.map((window) => {
const resetAt = formatResetAt(window.resetsAt, nowMs);
return (
<div key={window.id} className="flex items-center gap-3">
<span className="w-10 shrink-0 text-xs text-muted-foreground">
{window.label}
</span>
<LimitMeter window={window} color={PROVIDER_COLOR[provider]} />
<span
className={cn(
"shrink-0 whitespace-nowrap text-right text-xs font-medium tabular-nums text-foreground",
usageTone(window.usedPercent),
)}
>
{Math.round(window.usedPercent)}% used
</span>
<span className="shrink-0 whitespace-nowrap text-right text-xs tabular-nums text-muted-foreground">
{resetAt === null ? "" : `resets ${resetAt}`}
</span>
</div>
);
})
)}
</div>
);
})}
</div>
</section>
);
}
+15 -2
View File
@@ -1,9 +1,10 @@
import type { UsageProviderKind } from "@t3tools/contracts";
import { useCanGoBack, useNavigate, useRouter } from "@tanstack/react-router";
import { ArrowLeftIcon, CheckIcon, RefreshCwIcon, XIcon } from "lucide-react";
import { useMemo, useState } from "react";
import { useCallback, useMemo, useState } from "react";
import { cn } from "../../lib/utils";
import { useAccountLimits } from "../../state/accountLimits";
import { useUsage, type EnvironmentUsageStatus } from "../../state/usage";
import {
enumerateDays,
@@ -15,6 +16,7 @@ import {
makeWindow,
} from "../../usage/usageFormat";
import { ScrollArea } from "../ui/scroll-area";
import { AccountLimitsSection } from "./AccountLimits";
import { UsageChartLegend, UsageProviderChart, type UsageChartMetric } from "./UsageProviderChart";
import { PROVIDER_COLOR, PROVIDER_LABEL, PROVIDER_MARK, PROVIDER_ORDER } from "./usageProviders";
@@ -35,7 +37,14 @@ export function UsagePage() {
// Recomputed only when the window length changes, so a re-render does not
// shift the range and refetch every environment.
const window = useMemo(() => makeWindow(windowDays), [windowDays]);
const { merged, environments, isPending, isPartial, refresh } = useUsage(window);
const { merged, environments, isPending, isPartial, refresh: refreshUsage } = useUsage(window);
const { refresh: refreshLimits } = useAccountLimits();
// One refresh button, two caches: the transcript scan and the limits
// snapshot both re-read, or the Limits strip lags the rest of the page.
const refresh = useCallback(() => {
refreshUsage();
refreshLimits();
}, [refreshUsage, refreshLimits]);
// Hold the content until every environment is terminal. Rendering merged
// totals while devices are still answering makes every number on the page
@@ -117,6 +126,10 @@ export function UsagePage() {
</div>
</header>
{/* Limits come from the live limits cache, not the transcript scan,
so they render even while the scan below settles. */}
<AccountLimitsSection />
{settling ? (
<>
{environments.length > 1 ? <UsageDeviceStrip environments={environments} /> : null}
+99
View File
@@ -0,0 +1,99 @@
/**
* Multi-environment account-limits state.
*
* Every connected environment reports its cached snapshot per provider; the
* client keeps the freshest one per provider. Environments on the same
* machine answer with identical data, so freshest-wins is also the dedupe.
*
* @module state/accountLimits
*/
import { useAtomValue } from "@effect/atom-react";
import {
ACCOUNT_LIMITS_CONTRACT_VERSION,
type AccountLimitsSnapshot,
type EnvironmentId,
type UsageProviderKind,
} from "@t3tools/contracts";
import * as Option from "effect/Option";
import { AsyncResult, Atom } from "effect/unstable/reactivity";
import { useCallback, useMemo } from "react";
import { appAtomRegistry } from "../rpc/atomRegistry";
import { environmentPresentations } from "./presentation";
import { serverEnvironment } from "./server";
interface EnvironmentLimitsStatus {
readonly environmentId: EnvironmentId;
readonly isPending: boolean;
readonly snapshots: readonly AccountLimitsSnapshot[] | null;
}
const accountLimitsAtom = Atom.make((get): readonly EnvironmentLimitsStatus[] => {
const presentations = get(environmentPresentations.presentationsAtom);
const statuses: EnvironmentLimitsStatus[] = [];
for (const [environmentId] of presentations) {
const result = get(serverEnvironment.accountLimits({ environmentId, input: {} }));
const summary = Option.getOrNull(AsyncResult.value(result));
statuses.push({
environmentId,
isPending: result.waiting,
snapshots:
summary === null || summary.contractVersion !== ACCOUNT_LIMITS_CONTRACT_VERSION
? null
: summary.snapshots,
});
}
return statuses;
}).pipe(Atom.withLabel("web-account-limits"));
export interface AccountLimitsView {
/** Freshest snapshot per provider, in no particular order. */
readonly snapshots: ReadonlyMap<UsageProviderKind, AccountLimitsSnapshot>;
/** True until at least one environment has answered. */
readonly isPending: boolean;
/**
* True while any environment is still answering. A provider with no
* snapshot is "loading" while this holds and "no data" once it clears -
* the first environment to answer must not decide that for the rest.
*/
readonly isSettling: boolean;
readonly refresh: () => void;
}
export function useAccountLimits(): AccountLimitsView {
const environments = useAtomValue(accountLimitsAtom);
const snapshots = useMemo(() => {
const freshest = new Map<UsageProviderKind, AccountLimitsSnapshot>();
for (const environment of environments) {
for (const snapshot of environment.snapshots ?? []) {
const current = freshest.get(snapshot.provider);
// ISO-8601 strings order lexicographically.
if (current === undefined || snapshot.asOf > current.asOf) {
freshest.set(snapshot.provider, snapshot);
}
}
}
return freshest;
}, [environments]);
const refresh = useCallback(() => {
for (const environment of environments) {
appAtomRegistry.refresh(
serverEnvironment.accountLimits({ environmentId: environment.environmentId, input: {} }),
);
}
}, [environments]);
const answered = environments.filter((environment) => environment.snapshots !== null).length;
const stillReporting = environments.filter(
(environment) => environment.snapshots === null && environment.isPending,
).length;
return {
snapshots,
isPending: answered === 0 && stillReporting > 0,
isSettling: stillReporting > 0,
refresh,
};
}
+44
View File
@@ -0,0 +1,44 @@
/**
* Display formatting for account rate limits.
*
* @module limitsFormat
*/
const TIME = new Intl.DateTimeFormat("en-US", {
hourCycle: "h23",
hour: "2-digit",
minute: "2-digit",
});
const DATE_TIME = new Intl.DateTimeFormat("en-US", {
month: "numeric",
day: "numeric",
hourCycle: "h23",
hour: "2-digit",
minute: "2-digit",
});
/**
* When a window resets: `16:00` inside 24 hours, `8/12 16:00` beyond.
* Null for windows with no reset clock yet, "now" once the moment has passed
* (the provider refreshes lazily, so a stale timestamp lingers briefly).
*/
export function formatResetAt(resetsAt: string | null, nowMs: number): string | null {
if (resetsAt === null) return null;
const at = Date.parse(resetsAt);
if (Number.isNaN(at)) return null;
if (at <= nowMs) return "now";
if (at - nowMs < 24 * 60 * 60 * 1000) return TIME.format(at);
return DATE_TIME.format(at).replace(", ", " ");
}
/** Age of a snapshot: `just now`, `5m ago`, `6h ago`, `3d ago`. */
export function formatAgo(asOf: string, nowMs: number): string {
const at = Date.parse(asOf);
if (Number.isNaN(at)) return "";
const minutes = Math.floor(Math.max(0, nowMs - at) / 60_000);
if (minutes < 1) return "just now";
if (minutes < 60) return `${minutes}m ago`;
const hours = Math.floor(minutes / 60);
if (hours < 48) return `${hours}h ago`;
return `${Math.floor(hours / 24)}d ago`;
}
@@ -714,6 +714,13 @@ export function createServerEnvironmentAtoms<R, E>(
tag: WS_METHODS.serverGetUsageSummary,
staleTimeMs: 60_000,
}),
// Limits only move while sessions run, so a minute of staleness is fine
// and keeps the hover card instant after its first open.
accountLimits: createEnvironmentRpcQueryAtomFamily(runtime, {
label: "environment-data:server:account-limits",
tag: WS_METHODS.serverGetAccountLimits,
staleTimeMs: 60_000,
}),
configProjection,
welcome: createEnvironmentRpcSubscriptionAtomFamily(runtime, {
label: "environment-data:server:welcome",
+79
View File
@@ -0,0 +1,79 @@
/**
* Account rate-limit contract.
*
* Providers meter subscription usage in rolling windows (Claude: 5-hour and
* weekly; Codex: weekly today, 5-hour whenever OpenAI turns it back on). Each
* environment folds whatever the provider streams into one snapshot per
* provider account and serves it here; the client merges environments and
* keeps the freshest snapshot per provider.
*
* Windows are data, not schema: the set a provider reports changes without
* notice (Codex paused its 5-hour window, Claude added model-scoped
* weeklies), so clients render the array as-is and a window that reappears
* upstream shows up again with zero client changes.
*
* @module accountLimits
*/
import * as Schema from "effect/Schema";
import { TrimmedNonEmptyString } from "./baseSchemas.ts";
import { UsageProviderKind } from "./usage.ts";
/**
* Bumped whenever the shape of {@link AccountLimitsSummary} changes
* incompatibly. The client skips summaries reporting another version rather
* than failing the merge.
*/
export const ACCOUNT_LIMITS_CONTRACT_VERSION = 1 as const;
export const AccountLimitsWindow = Schema.Struct({
/**
* Stable identifier: `five_hour` and `seven_day` for the standard windows,
* provider-specific slugs for anything scoped (model weeklies etc.).
*/
id: TrimmedNonEmptyString,
/** Short display label ("5h", "Week", "Fable"). */
label: TrimmedNonEmptyString,
/** Share of the window consumed, 0-100. */
usedPercent: Schema.Number,
/**
* ISO timestamp when the window resets. Null until the window has traffic:
* providers report an untouched window with no reset clock.
*/
resetsAt: Schema.NullOr(Schema.String),
/** Window length, when the provider reports one. */
windowMinutes: Schema.NullOr(Schema.Number),
});
export type AccountLimitsWindow = typeof AccountLimitsWindow.Type;
export const AccountLimitsSource = Schema.Literals(["live", "transcript"]);
export type AccountLimitsSource = typeof AccountLimitsSource.Type;
export const AccountLimitsSnapshot = Schema.Struct({
provider: UsageProviderKind,
/** Provider plan slug ("max", "pro"), when known. */
plan: Schema.NullOr(TrimmedNonEmptyString),
windows: Schema.Array(AccountLimitsWindow),
/**
* When the provider reported these numbers, not when we were asked. Live
* Claude data only flows while a session runs, so this can lag by hours;
* clients surface the age instead of pretending the data is current.
*/
asOf: Schema.String,
/**
* `live` - captured off a running provider session.
* `transcript` - recovered from the provider's on-disk session files
* (Codex writes its snapshot beside every token count; Claude never
* persists limits, so Claude snapshots are always `live`).
*/
source: AccountLimitsSource,
});
export type AccountLimitsSnapshot = typeof AccountLimitsSnapshot.Type;
export const AccountLimitsSummary = Schema.Struct({
contractVersion: Schema.Number,
readAt: Schema.String,
/** At most one snapshot per provider. Empty until a session has reported. */
snapshots: Schema.Array(AccountLimitsSnapshot),
});
export type AccountLimitsSummary = typeof AccountLimitsSummary.Type;
+1
View File
@@ -29,4 +29,5 @@ export * from "./preview.ts";
export * from "./previewAutomation.ts";
export * from "./resourceTelemetry.ts";
export * from "./usage.ts";
export * from "./accountLimits.ts";
export * from "./rpc.ts";
+9
View File
@@ -152,6 +152,7 @@ import {
ResourceTelemetryRetryResult,
ResourceTelemetrySnapshot,
} from "./resourceTelemetry.ts";
import { AccountLimitsSummary } from "./accountLimits.ts";
import { UsageReadError, UsageSummary, UsageSummaryInput } from "./usage.ts";
import { ServerSettings, ServerSettingsError, ServerSettingsPatch } from "./settings.ts";
import {
@@ -246,6 +247,7 @@ export const WS_METHODS = {
serverReportHostPowerState: "server.reportHostPowerState",
serverGetBackgroundPolicy: "server.getBackgroundPolicy",
serverGetUsageSummary: "server.getUsageSummary",
serverGetAccountLimits: "server.getAccountLimits",
// Cloud environment methods
cloudGetRelayClientStatus: "cloud.getRelayClientStatus",
@@ -389,6 +391,12 @@ export const WsServerGetUsageSummaryRpc = Rpc.make(WS_METHODS.serverGetUsageSumm
error: Schema.Union([EnvironmentAuthorizationError, UsageReadError]),
});
export const WsServerGetAccountLimitsRpc = Rpc.make(WS_METHODS.serverGetAccountLimits, {
payload: Schema.Struct({}),
success: AccountLimitsSummary,
error: EnvironmentAuthorizationError,
});
export const WsServerSignalProcessRpc = Rpc.make(WS_METHODS.serverSignalProcess, {
payload: ServerSignalProcessInput,
success: ServerSignalProcessResult,
@@ -828,6 +836,7 @@ export const WsRpcGroup = RpcGroup.make(
WsServerGetResourceTelemetryHistoryRpc,
WsServerRetryResourceTelemetryRpc,
WsServerGetUsageSummaryRpc,
WsServerGetAccountLimitsRpc,
WsServerSignalProcessRpc,
WsServerReportClientActivityRpc,
WsServerReportHostPowerStateRpc,