GeezerVison is showing github.com — feat(usage): show 5h/weekly rate limits on the usage page and sidebar hover by t3dotgg · Pull Request #5739 · pingdotgg/t3code
feat(usage): show 5h/weekly rate limits on the usage page and sidebar hover
#5739
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and
privacy statement . We’ll occasionally send you account related emails.
Already on GitHub?
Sign in
to your account
Uh oh!
There was an error while loading. Please reload this page.
Show file tree
Hide file tree
Changes from all commits
Commits
File filter
Filter by extension
.json
(1)
.ts
(18)
.tsx
(3)
All 3 file types selected
Only manifest files
Viewed files
Conversations
Failed to load comments.
Loading
Uh oh!
There was an error while loading. Please reload this page.
Jump to
Jump to file
Failed to load files.
Loading
Uh oh!
There was an error while loading. Please reload this page.
Diff view
Hide whitespace
Diff view
Hide whitespace
There are no files selected for viewing
Original file line number
Diff line number
Diff line change
Expand Up
@@ -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 {
Expand Down
Expand Up
@@ -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)({
Expand Down
Original file line number
Diff line number
Diff line change
Expand Up
@@ -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,
Expand Down
Original file line number
Diff line number
Diff line change
Expand Up
@@ -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> = {}) {
Expand Down
Expand Up
@@ -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),
Expand Down
Original file line number
Diff line number
Diff line change
Expand Up
@@ -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";
Comment thread
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more .
Consider importing the service module as a namespace at this boundary, as the other five call sites added in this PR do (server.ts, ws.ts, both test files, the integration harness):
import * as AccountLimitsService from "../../usage/AccountLimitsService.ts" ;
and then const accountLimits = yield* AccountLimitsService.AccountLimitsService; at line 879, so the module shape (AccountLimitsService.layer, AccountLimitsService.layerTest) stays visible.
Posted via Macroscope — Effect Service Conventions
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
const providerTurnKey = (threadId: ThreadId, turnId: TurnId) => `${threadId}:${turnId}`;
const providerTaskKey = (threadId: ThreadId, taskId: string) => `${threadId}:${taskId}`;
Expand Down
Expand Up
@@ -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}`)),
Expand Down
Expand Up
@@ -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;
Expand Down
Original file line number
Diff line number
Diff line change
Expand Up
@@ -15,6 +15,7 @@ import {
type PermissionUpdate,
type SDKMessage,
type SDKControlGetContextUsageResponse,
type SDKControlGetUsageResponse,
type SDKResultMessage,
type SettingSource,
type SDKUserMessage,
Expand Down
Expand Up
@@ -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";
Expand Down
Expand Up
@@ -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,
Expand Down
Expand Up
@@ -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;
}
Expand Down
Expand Up
@@ -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({
Expand Down
Expand Up
@@ -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* (
Comment thread
macroscopeapp[bot] marked this conversation as resolved.
Resolved
Uh oh!
There was an error while loading. Please reload this page.
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 () => {
Comment thread
macroscopeapp[bot] marked this conversation as resolved.
Resolved
Uh oh!
There was an error while loading. Please reload this page.
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({
Comment thread
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more .
🟡 Medium Layers/ClaudeAdapter.ts:3457
The account.rate-limits.updated event emitted by emitAccountUsageSnapshot carries only provider: PROVIDER and omits the owning instance's id, but this adapter supports multiple Claude instances on different accounts. ProviderRuntimeIngestion keys account-limit snapshots by provider, so a usage fetch from one configured Claude instance overwrites the limits stored for a different instance's account, and the usage UI can show limits for the wrong account. Consider including providerInstanceId: boundInstanceId (or context.session.providerInstanceId) on this event so AccountLimitsService can keep per-instance snapshots.
🚀 Reply "fix it for me " or copy this AI Prompt for your agent:
In file @apps/server/src/provider/Layers/ClaudeAdapter.ts around line 3457:
The `account.rate-limits.updated` event emitted by `emitAccountUsageSnapshot` carries only `provider: PROVIDER` and omits the owning instance's id, but this adapter supports multiple Claude instances on different accounts. `ProviderRuntimeIngestion` keys account-limit snapshots by provider, so a usage fetch from one configured Claude instance overwrites the limits stored for a different instance's account, and the usage UI can show limits for the wrong account. Consider including `providerInstanceId: boundInstanceId` (or `context.session.providerInstanceId`) on this event so `AccountLimitsService` can keep per-instance snapshots.
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
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,
Expand Down
Expand Up
@@ -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":
Expand Down
Original file line number
Diff line number
Diff line change
Expand Up
@@ -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";
Expand Down
Expand Up
@@ -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,
Expand Down
Original file line number
Diff line number
Diff line change
Expand Up
@@ -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,
Expand Down
Expand Up
@@ -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)),
Expand Down
Expand Up
@@ -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),
Expand Down
Loading
Oops, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
Loading
Oops, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.