The best way to control Claude Code, Codex and more from any computer or phone
fix: proxied usage limits follow the hub's model routing and show on the thread card (#30778)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: maria-rcks <maria@kuuro.net> Co-authored-by: Julius Marminge <julius0216@outlook.com>
Bilal Bakr committed
Nov 21, 2026 at 04:51 UTC
c436409da05e29185f47b5bc83c51b570d93b58a
32 files changed
+913
-67
apps/mobile/src/features/threads/ThreadComposer.tsx
+1
@@ -401,6 +401,7 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps
401
props.serverConfig?.providers ?? [],
402
props.serverConfig?.usageLimitSources ?? [],
403
Date.now(),
404
+ currentModelSelection.model,
405
);
406
onShowUsageLimits(report);
407
if (!report) {
apps/mobile/src/features/threads/ThreadDetailScreen.tsx
+1
@@ -1017,6 +1017,7 @@ function ThreadDetailBody(
1017
props.serverConfig?.providers ?? [],
1018
props.serverConfig?.usageLimitSources ?? [],
1019
usageLimitsPanel.now,
1020
+ props.selectedThread.modelSelection.model,
1021
)
1022
: null;
1023
const showUsageLimits = (report: UsageLimitsReport | null) =>
apps/server/scripts/record-claude-agent-sdk-replay-fixture.ts
+7
@@ -82,6 +82,13 @@ const CLAUDE_RECORDINGS = {
82
queryMode: "streaming",
83
enableTools: true,
84
},
85
+ // Record with ANTHROPIC_BASE_URL at a CLIProxyAPI hub whose upstream accounts answer 429.
86
+ usage_limit: {
87
+ prompts: [SIMPLE_PROMPT],
88
+ defaultTranscriptFile: "fixtures/usage_limit/claude_transcript.ndjson",
89
+ queryMode: "streaming",
90
+ enableTools: true,
91
+ },
92
multi_turn: {
93
prompts: [MULTI_TURN_FIRST_PROMPT, MULTI_TURN_SECOND_PROMPT],
94
defaultTranscriptFile: "fixtures/multi_turn/claude_transcript.ndjson",
apps/server/src/orchestration-v2/testkit/ClaudeReplayFixtures.integration.test.ts
+77
@@ -6,13 +6,19 @@ import {
6
MessageId,
7
ProviderDriverKind,
8
type ProviderReplayEntry,
9
+ type ServerProvider,
10
+ UsageLimitSourceId,
11
+ type UsageLimitSourceSnapshot,
12
} from "@t3tools/contracts";
13
import * as Effect from "effect/Effect";
14
+import * as Layer from "effect/Layer";
15
16
import { ClaudeOrchestratorReplayHarness } from "../Adapters/ClaudeAdapterV2.testkit.ts";
17
import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
18
import * as Orchestrator from "../Orchestrator.ts";
19
import { userFacingDispatchErrorMessage } from "../UserFacingErrors.ts";
20
+import * as UsageLimitSources from "../../usage/UsageLimitSources.ts";
21
+import { claudeUsageLimitFailure } from "./fixtures/usage_limit/claude_output.ts";
22
import { provideDeterministicTestRuntime } from "./DeterministicRuntime.ts";
23
import { subagentInput } from "./fixtures/subagent/input.ts";
24
import { runOrchestratorV2Scenario } from "./OrchestratorScenario.ts";
@@ -122,6 +128,77 @@ describe("Claude Agent SDK replay fixtures", () => {
128
}),
129
);
130
131
+ it.effect("takes the reset of the hub accounts that serve the model the hub refused", () =>
132
+ Effect.gen(function* () {
133
+ const fixture = findReplayFixture("usage_limit")!;
134
+ const driver = fixture.providers[0]!;
135
+ const endpoint = "http://127.0.0.1:18319";
136
+ const account = (id: string, model: string, usedPercent: number, resetsAt: string) => ({
137
+ id,
138
+ driver: ProviderDriverKind.make("claudeAgent"),
139
+ models: [model],
140
+ usageLimits: {
141
+ checkedAt: resetsAt,
142
+ windows: [
143
+ { id: "five_hour", kind: "session" as const, label: "Session", usedPercent, resetsAt },
144
+ ],
145
+ },
146
+ });
147
+ const hub = (id: string, origin: string, accounts: ReadonlyArray<object>) =>
148
+ ({
149
+ id: UsageLimitSourceId.make(id),
150
+ kind: "cliproxy",
151
+ label: id,
152
+ origin,
153
+ checkedAt: "",
154
+ accounts,
155
+ }) as UsageLimitSourceSnapshot;
156
+ yield* runReplayFixture({
157
+ fixtureName: fixture.name,
158
+ buildInput: fixture.buildInput,
159
+ driver: {
160
+ ...driver,
161
+ assertOutput: (result, transcript) =>
162
+ assert.equal(
163
+ claudeUsageLimitFailure(result, transcript).resetAt,
164
+ "2033-05-19T07:20:00.000Z",
165
+ ),
166
+ },
167
+ harness: ClaudeOrchestratorReplayHarness,
168
+ providerInstances: {
169
+ getInstance: () =>
170
+ Effect.succeed({
171
+ snapshot: {
172
+ getSnapshot: Effect.succeed({
173
+ auth: { status: "unknown", type: "customEndpoint", endpoint },
174
+ } as ServerProvider),
175
+ },
176
+ } as never),
177
+ },
178
+ }).pipe(
179
+ Effect.provide(
180
+ UsageLimitSources.layerResetFallback.pipe(
181
+ Layer.provide(
182
+ Layer.mock(UsageLimitSources.UsageLimitSources)({
183
+ current: Effect.succeed([
184
+ hub("home", endpoint, [
185
+ account("sonnet", driver.modelSelection.model, 100, "2033-05-19T07:20:00.000Z"),
186
+ // regression: #30778 an account the hub does not route the model to has no say
187
+ account("opus", "claude-opus-4-8", 10, "2033-05-19T05:00:00.000Z"),
188
+ ]),
189
+ hub("elsewhere", "http://127.0.0.1:9999", [
190
+ account("other", driver.modelSelection.model, 100, "2033-05-18T00:00:00.000Z"),
191
+ ]),
192
+ ]),
193
+ refresh: Effect.void,
194
+ }),
195
+ ),
196
+ ),
197
+ ),
198
+ );
199
+ }),
200
+ );
201
+
202
const afterRootFixture = findReplayFixture("claude_background_subagent_after_root");
203
const afterRootProvider = afterRootFixture?.providers[0];
204
if (afterRootFixture !== undefined && afterRootProvider !== undefined) {
apps/server/src/orchestration-v2/testkit/ProviderReplayFixtures.ts
+9
-5
@@ -8,6 +8,7 @@ import * as Path from "effect/Path";
8
import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
9
import { checkpointWorkspace } from "@t3tools/provider-testing/replayWorkspace";
10
import { readProviderReplayTranscript } from "@t3tools/provider-testing/replayTranscript";
11
+import type { ProviderInstanceRegistry } from "../../provider/ProviderInstanceRegistry.ts";
12
import { provideDeterministicTestRuntime } from "./DeterministicRuntime.ts";
13
import { ORCHESTRATOR_REPLAY_FIXTURES } from "./fixtures/index.ts";
14
import {
@@ -94,6 +95,8 @@ export interface ReplayFixtureCase {
95
readonly buildInput: () => OrchestratorFixtureInput;
96
readonly driver: ProviderOrchestratorReplayVariant;
97
readonly transformTranscript?: (transcript: ProviderReplayTranscript) => ProviderReplayTranscript;
98
+ /** The instances the ingestor reads snapshots from, such as an endpoint behind a hub. */
99
+ readonly providerInstances?: Partial<ProviderInstanceRegistry["Service"]>;
100
}
101
102
export interface ReplayFixtureRun<
@@ -145,11 +148,12 @@ const runFixtureProvider = Effect.fn("runOrchestratorReplayFixture")(function* <
148
},
149
};
150
148
- const result = yield* runOrchestratorV2ProviderReplayScenario(
149
- scenario,
150
- input.harness,
151
- input.driver.runContinuationWorker === true ? { runContinuationWorker: true } : {},
152
- ).pipe(provideDeterministicTestRuntime);
151
+ const result = yield* runOrchestratorV2ProviderReplayScenario(scenario, input.harness, {
152
+ ...(input.driver.runContinuationWorker === true ? { runContinuationWorker: true } : {}),
153
+ ...(input.providerInstances === undefined
154
+ ? {}
155
+ : { providerInstances: input.providerInstances }),
156
+ }).pipe(provideDeterministicTestRuntime);
157
input.driver.assertOutput(result, transcript);
158
assertProviderNativeSubagentRootTurns(result);
159
const expectedAbsentWorkspacePaths = input.driver.expectedAbsentWorkspacePaths;
apps/server/src/orchestration-v2/testkit/ProviderReplayHarness.ts
+13
-3
@@ -208,6 +208,9 @@ export function runOrchestratorV2ProviderReplayScenario<
208
readonly recoverOnStartup?: boolean;
209
readonly continueThreadsAfterServerUpdate?: boolean;
210
readonly managedPolicy?: ManagedPolicyDocument;
211
+ readonly providerInstances?: Partial<
212
+ ProviderInstanceRegistry.ProviderInstanceRegistry["Service"]
213
+ >;
214
} = {},
215
): Effect.Effect<
216
OrchestratorV2ScenarioResult,
@@ -252,6 +255,9 @@ export function layerProviderReplay<Transcript extends ProviderReplayTranscript,
255
readonly continueThreadsAfterServerUpdate?: boolean;
256
readonly managedPolicy?: ManagedPolicyDocument;
257
readonly replayGate?: ProviderReplayGate;
258
+ readonly providerInstances?: Partial<
259
+ ProviderInstanceRegistry.ProviderInstanceRegistry["Service"]
260
+ >;
261
} = {},
262
): Layer.Layer<
263
| Orchestrator.OrchestratorV2
@@ -289,6 +295,10 @@ export function layerWithRegistry<Error>(
295
store: ProjectionStore.ProjectionStoreV2Shape,
296
) => ProjectionStore.ProjectionStoreV2Shape;
297
readonly managedPolicy?: ManagedPolicyDocument;
298
+ /** The instances the ingestor reads snapshots from, such as an endpoint behind a hub. */
299
+ readonly providerInstances?: Partial<
300
+ ProviderInstanceRegistry.ProviderInstanceRegistry["Service"]
301
+ >;
302
} = {},
303
): Layer.Layer<
304
| Orchestrator.OrchestratorV2
@@ -361,9 +371,9 @@ export function layerWithRegistry<Error>(
371
const layerProviderEventIngestorProvided = ProviderEventIngestor.layer.pipe(
372
Layer.provide(
373
Layer.mergeAll(
364
- Layer.mock(ProviderInstanceRegistry.ProviderInstanceRegistry)({
365
- getInstance: () => Effect.undefined,
366
- }),
374
+ Layer.mock(ProviderInstanceRegistry.ProviderInstanceRegistry)(
375
+ options.providerInstances ?? { getInstance: () => Effect.undefined },
376
+ ),
377
layerStores,
378
layerEventSinkProvided,
379
IdAllocator.layer,
apps/server/src/orchestration-v2/testkit/fixtures/index.ts
+13
@@ -36,6 +36,7 @@ import { claudeMcpToolPresentationInput } from "./claude_mcp_tool_presentation/i
36
import { assertClaudeMcpToolPresentationOutput } from "./claude_mcp_tool_presentation/output.ts";
37
import { claudeResultIsErrorInput } from "./claude_result_is_error/input.ts";
38
import { assertClaudeResultIsErrorOutput } from "./claude_result_is_error/output.ts";
39
+import { assertClaudeUsageLimitOutput } from "./usage_limit/claude_output.ts";
40
import { grokAutoBlockedCommandInput } from "./grok_auto_blocked_command/input.ts";
41
import { kiroCompactionInput } from "./kiro_compaction/input.ts";
42
import { kiroForkFromTurnInput } from "./kiro_fork_from_turn/input.ts";
@@ -513,6 +514,18 @@ export const ORCHESTRATOR_REPLAY_FIXTURES: ReadonlyArray<OrchestratorReplayFixtu
514
},
515
],
516
},
517
+ {
518
+ name: "usage_limit",
519
+ buildInput: simpleInput,
520
+ providers: [
521
+ {
522
+ driver: ProviderDriverKind.make("claudeAgent"),
523
+ transcriptFile: new URL("./usage_limit/claude_transcript.ndjson", import.meta.url),
524
+ modelSelection: CLAUDE_MODEL_SELECTION,
525
+ assertOutput: assertClaudeUsageLimitOutput,
526
+ },
527
+ ],
528
+ },
529
{
530
name: "claude_result_is_error",
531
buildInput: claudeResultIsErrorInput,
apps/server/src/orchestration-v2/testkit/fixtures/usage_limit/claude_output.ts
new
+28
@@ -0,0 +1,28 @@
1
+import { assert } from "@effect/vitest";
2
+import type { ProviderReplayTranscript } from "@t3tools/contracts";
3
+
4
+import type { OrchestratorV2ScenarioResult } from "../../OrchestratorScenario.ts";
5
+import { assertBaseProjection, projectionFor } from "../shared.ts";
6
+
7
+/** The usage-limit failure Claude reports through a CLIProxyAPI hub with every account spent. */
8
+export function claudeUsageLimitFailure(
9
+ result: OrchestratorV2ScenarioResult,
10
+ transcript: ProviderReplayTranscript,
11
+) {
12
+ assertBaseProjection({ result, transcript, runCount: 1, runStatuses: ["failed"] });
13
+ const error = projectionFor(result, transcript.scenario).turnItems.find(
14
+ (item) => item.type === "error",
15
+ );
16
+ if (error?.type !== "error") throw new Error("expected an error turn item");
17
+ assert.equal(error.failure.class, "usage_limit");
18
+ assert.equal(error.failure.code, "api_error_429");
19
+ return error.failure;
20
+}
21
+
22
+export function assertClaudeUsageLimitOutput(
23
+ result: OrchestratorV2ScenarioResult,
24
+ transcript: ProviderReplayTranscript,
25
+) {
26
+ // The hub drops the upstream rate-limit headers, so the CLI reports no reset time.
27
+ assert.isNull(claudeUsageLimitFailure(result, transcript).resetAt);
28
+}
apps/server/src/orchestration-v2/testkit/fixtures/usage_limit/claude_transcript.ndjson
new
+20
@@ -0,0 +1,20 @@
1
+{"type":"transcript_start","provider":"claudeAgent","protocol":"claude-agent-sdk.query","version":"0.2.111","scenario":"usage_limit","metadata":{"prompts":["Respond with the following text: fixture simple ok"],"model":"claude-sonnet-4-6","nativeSessionId":"b8eed9d2-ed85-48fb-a4f2-316f6a0b1117","queryMode":"streaming","tools":"claude_code","permissionMode":"bypassPermissions","generatedBy":"recordClaudeAgentSdkReplayTranscript","recordedThrough":"CLIProxyAPI 7.2.130 at ANTHROPIC_BASE_URL with ANTHROPIC_AUTH_TOKEN; its one Claude API key upstream answered 429 rate_limit_error with anthropic-ratelimit-unified-reset, which the hub does not forward. Claude Code 2.1.326."}}
2
+{"type":"expect_outbound","label":"query.open","frame":{"type":"query.open","options":{"model":"claude-sonnet-4-6","tools":{"type":"preset","preset":"claude_code"},"permissionMode":"bypassPermissions","settings":{"showThinkingSummaries":true},"allowDangerouslySkipPermissions":true,"sessionId":"b8eed9d2-ed85-48fb-a4f2-316f6a0b1117"}}}
3
+{"type":"expect_outbound","label":"prompt.offer:1","frame":{"type":"prompt.offer","message":{"type":"user","message":{"role":"user","content":"Respond with the following text: fixture simple ok"},"parent_tool_use_id":null,"uuid":"301cffa7-d83e-49db-bbd8-1312e0e79c4e"}}}
4
+{"type":"emit_inbound","label":"command_lifecycle","frame":{"type":"command_lifecycle","command_uuid":"301cffa7-d83e-49db-bbd8-1312e0e79c4e","state":"queued","uuid":"683f753d-e44d-418b-81be-fe1635105ee0","session_id":"b8eed9d2-ed85-48fb-a4f2-316f6a0b1117"}}
5
+{"type":"emit_inbound","label":"command_lifecycle","frame":{"type":"command_lifecycle","command_uuid":"301cffa7-d83e-49db-bbd8-1312e0e79c4e","state":"started","uuid":"b00be524-44da-49bf-8d43-a4e060e6ed2f","session_id":"b8eed9d2-ed85-48fb-a4f2-316f6a0b1117"}}
6
+{"type":"emit_inbound","label":"system","frame":{"type":"system","subtype":"init","agents":[],"apiKeySource":"none","claude_code_version":"2.1.326","cwd":"/tmp/claude-replay-usage_limit","tools":[],"mcp_servers":[],"model":"claude-sonnet-4-6","permissionMode":"bypassPermissions","slash_commands":[],"output_style":"default","skills":[],"plugins":[],"fast_mode_state":"off","uuid":"ad82e0c8-db2d-4309-af62-5e1072c2d771","session_id":"b8eed9d2-ed85-48fb-a4f2-316f6a0b1117"}}
7
+{"type":"emit_inbound","label":"system","frame":{"type":"system","subtype":"status","status":"requesting","session_id":"b8eed9d2-ed85-48fb-a4f2-316f6a0b1117","uuid":"7d799f81-c12e-4f47-8cd9-273fef1b30a3","user_message_uuids":["301cffa7-d83e-49db-bbd8-1312e0e79c4e"]}}
8
+{"type":"emit_inbound","label":"system","frame":{"type":"system","subtype":"api_retry","attempt":1,"max_retries":10,"retry_delay_ms":526,"error_status":429,"error":"rate_limit","session_id":"b8eed9d2-ed85-48fb-a4f2-316f6a0b1117","uuid":"593bcdde-73d4-42c5-857a-49bc8054f108"}}
9
+{"type":"emit_inbound","label":"system","frame":{"type":"system","subtype":"api_retry","attempt":2,"max_retries":10,"retry_delay_ms":1084,"error_status":429,"error":"rate_limit","session_id":"b8eed9d2-ed85-48fb-a4f2-316f6a0b1117","uuid":"78b8707b-2945-4a47-a417-865211f63165"}}
10
+{"type":"emit_inbound","label":"system","frame":{"type":"system","subtype":"api_retry","attempt":3,"max_retries":10,"retry_delay_ms":2101,"error_status":429,"error":"rate_limit","session_id":"b8eed9d2-ed85-48fb-a4f2-316f6a0b1117","uuid":"e5a2272c-ac69-40dc-afc1-74b8664dd394"}}
11
+{"type":"emit_inbound","label":"system","frame":{"type":"system","subtype":"api_retry","attempt":4,"max_retries":10,"retry_delay_ms":4924,"error_status":429,"error":"rate_limit","session_id":"b8eed9d2-ed85-48fb-a4f2-316f6a0b1117","uuid":"e88d160e-9ed6-4075-91a8-c46c5df070fc"}}
12
+{"type":"emit_inbound","label":"system","frame":{"type":"system","subtype":"api_retry","attempt":5,"max_retries":10,"retry_delay_ms":8012,"error_status":429,"error":"rate_limit","session_id":"b8eed9d2-ed85-48fb-a4f2-316f6a0b1117","uuid":"67cb3f4c-35dd-47b8-a484-fb4341403e3e"}}
13
+{"type":"emit_inbound","label":"system","frame":{"type":"system","subtype":"api_retry","attempt":6,"max_retries":10,"retry_delay_ms":19519,"error_status":429,"error":"rate_limit","session_id":"b8eed9d2-ed85-48fb-a4f2-316f6a0b1117","uuid":"8d70cb4a-6c32-4956-ac87-37cc1af2757a"}}
14
+{"type":"emit_inbound","label":"system","frame":{"type":"system","subtype":"api_retry","attempt":7,"max_retries":10,"retry_delay_ms":39008,"error_status":429,"error":"rate_limit","session_id":"b8eed9d2-ed85-48fb-a4f2-316f6a0b1117","uuid":"62a2c80e-71dd-433d-be92-9cbc4a122dc1"}}
15
+{"type":"emit_inbound","label":"system","frame":{"type":"system","subtype":"api_retry","attempt":8,"max_retries":10,"retry_delay_ms":39524,"error_status":429,"error":"rate_limit","session_id":"b8eed9d2-ed85-48fb-a4f2-316f6a0b1117","uuid":"6c828da7-7f7d-492b-82f5-394b3eaab75b"}}
16
+{"type":"emit_inbound","label":"system","frame":{"type":"system","subtype":"api_retry","attempt":9,"max_retries":10,"retry_delay_ms":33452,"error_status":429,"error":"rate_limit","session_id":"b8eed9d2-ed85-48fb-a4f2-316f6a0b1117","uuid":"293b9b2f-4c97-4790-b28f-9c8c0d80827a"}}
17
+{"type":"emit_inbound","label":"system","frame":{"type":"system","subtype":"api_retry","attempt":10,"max_retries":10,"retry_delay_ms":35131,"error_status":429,"error":"rate_limit","session_id":"b8eed9d2-ed85-48fb-a4f2-316f6a0b1117","uuid":"7d3b9d7a-587b-4a07-a4fe-d67b5dbfa7e9"}}
18
+{"type":"emit_inbound","label":"assistant","frame":{"type":"assistant","message":{"diagnostics":null,"id":"815983ba-9182-4ae4-a656-8158541615e4","container":null,"model":"<synthetic>","role":"assistant","stop_details":null,"stop_reason":"stop_sequence","stop_sequence":"","type":"message","usage":{"output_tokens_details":null,"input_tokens":0,"output_tokens":0,"cache_creation_input_tokens":0,"cache_read_input_tokens":0,"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":null,"cache_creation":{"ephemeral_1h_input_tokens":0,"ephemeral_5m_input_tokens":0},"inference_geo":null,"iterations":null,"speed":null,"fallback_credit":null},"content":[{"type":"text","text":"API Error: Request rejected (429) · All credentials for model claude-sonnet-4-6 are cooling down via provider claude"}],"context_management":null},"parent_tool_use_id":null,"session_id":"b8eed9d2-ed85-48fb-a4f2-316f6a0b1117","uuid":"c56a86ab-b7cf-4ca5-b9fe-2a44ff5f7adc","timestamp":"2026-11-17T18:47:23.739Z","error":"rate_limit","is_api_error_message":true,"api_error_status":429,"api_error_type":"rate_limit_error","user_message_uuid":"301cffa7-d83e-49db-bbd8-1312e0e79c4e","user_message_uuids":["301cffa7-d83e-49db-bbd8-1312e0e79c4e"]}}
19
+{"type":"emit_inbound","label":"result","frame":{"duration_api_ms":0,"stop_reason":"stop_sequence","session_id":"b8eed9d2-ed85-48fb-a4f2-316f6a0b1117","total_cost_usd":0,"usage":{"output_tokens_details":{"thinking_tokens":0},"input_tokens":0,"cache_creation_input_tokens":0,"cache_read_input_tokens":0,"output_tokens":0,"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":0,"ephemeral_5m_input_tokens":0},"inference_geo":"","iterations":[],"speed":"standard","fallback_credit":null},"modelUsage":{},"permission_denials":[],"terminal_reason":"api_error","fast_mode_state":"off","fast_mode_disabled_reason":"sdk_opt_in_required","subagent_stats":{"spawned":0,"requested":{"background":0,"foreground":0,"unset":0},"started_in_background":0,"max_depth":0,"spawned_by_subagents":0,"completed":0,"failed":0,"killed":{"parent":0,"user":0,"system":0},"refused":{"depth_limit":0,"concurrency_limit":0,"budget":0},"by_type":{}},"safety_stops":0,"is_error":true,"num_turns":1,"subtype":"success","api_error_status":429,"api_error_type":"rate_limit_error","result":"API Error: Request rejected (429) · All credentials for model claude-sonnet-4-6 are cooling down via provider claude","type":"result","duration_ms":185616,"uuid":"ec685404-a730-46d8-a867-3b40e87cdc94","user_message_uuid":"301cffa7-d83e-49db-bbd8-1312e0e79c4e","user_message_uuids":["301cffa7-d83e-49db-bbd8-1312e0e79c4e"],"queued_turn_count":0,"result_index":0,"model_usage_since_last_result":{}}}
20
+{"type":"runtime_exit","status":"success"}
apps/server/src/usage/UsageLimitSources.test.ts
+82
@@ -288,6 +288,7 @@ const spent = (id: string, hours: number): ServerProviderUsageWindow => ({
288
const hub = (
289
accounts: ReadonlyArray<{
290
driver?: string;
291
+ models?: ReadonlyArray<string>;
292
windows?: ReadonlyArray<ServerProviderUsageWindow>;
293
unavailable?: true;
294
}>,
@@ -299,6 +300,7 @@ const hub = (
300
accounts: accounts.map((account, index) => ({
301
id: `account-${index}`,
302
driver: ProviderDriverKind.make(account.driver ?? "claudeAgent"),
303
+ ...(account.models ? { models: account.models } : {}),
304
usageLimits: {
305
checkedAt: at(0),
306
windows: account.windows ?? [],
@@ -354,6 +356,86 @@ it.each([
356
model: "claude-haiku-5-5",
357
expected: null,
358
},
359
+ // regression: #30778 only the accounts the hub routes the model to can refill it
360
+ {
361
+ name: "an account of another driver the hub routes the model to counts",
362
+ accounts: [
363
+ { driver: "codex", models: ["gpt-5.6-sol"], windows: [spent("five_hour", 3)] },
364
+ { models: ["claude-sonnet-4-6"], windows: [] },
365
+ ],
366
+ model: "gpt-5.6-sol",
367
+ expected: at(3),
368
+ },
369
+ {
370
+ name: "an account that lists no models is left out of an alias",
371
+ accounts: [{ windows: [spent("five_hour", 1)] }, { models: [], windows: [] }],
372
+ model: "opus",
373
+ expected: at(1),
374
+ },
375
+ {
376
+ name: "a spent Gemini quota does not hold back Claude on Antigravity",
377
+ accounts: [
378
+ {
379
+ driver: "antigravity",
380
+ models: ["claude-opus-4-6-thinking"],
381
+ windows: [spent("3p-5h", 1), spent("gemini-5h", 24)],
382
+ },
383
+ ],
384
+ model: "claude-opus-4-6-thinking",
385
+ expected: at(1),
386
+ },
387
+ {
388
+ name: "a hub thinking suffix routes by its base model",
389
+ accounts: [
390
+ { driver: "codex", models: ["gpt-5.2"], windows: [spent("five_hour", 3)] },
391
+ { models: ["claude-sonnet-4-6"], windows: [] },
392
+ ],
393
+ model: "gpt-5.2(high)",
394
+ expected: at(3),
395
+ },
396
+ {
397
+ name: "a prefixed Gemini model is held back by the Gemini quota",
398
+ accounts: [
399
+ {
400
+ driver: "antigravity",
401
+ models: ["ag/gemini-3.1-pro-high"],
402
+ windows: [spent("3p-5h", 1), spent("gemini-5h", 24)],
403
+ },
404
+ ],
405
+ model: "ag/gemini-3.1-pro-high",
406
+ expected: at(24),
407
+ },
408
+ {
409
+ name: "an alias of unknown family is held back by every Antigravity quota",
410
+ accounts: [{ driver: "antigravity", models: ["fast"], windows: [spent("gemini-5h", 24)] }],
411
+ model: "fast",
412
+ expected: at(24),
413
+ },
414
+ {
415
+ name: "an own-driver account whose model list was unread still counts",
416
+ accounts: [
417
+ { windows: [spent("five_hour", 1)] },
418
+ {
419
+ driver: "antigravity",
420
+ models: ["claude-sonnet-4-6"],
421
+ windows: [spent("3p-5h", 8)],
422
+ },
423
+ ],
424
+ model: "claude-sonnet-4-6",
425
+ expected: at(1),
426
+ },
427
+ {
428
+ name: "an Argon model waits only for the Argon quota",
429
+ accounts: [
430
+ {
431
+ driver: "antigravity",
432
+ models: ["gemini-4-argon-high"],
433
+ windows: [spent("gemini-argon-5h", 2), spent("gemini-carbon-weekly", 96)],
434
+ },
435
+ ],
436
+ model: "gemini-4-argon-high",
437
+ expected: at(2),
438
+ },
439
])("hub pool reset: $name", ({ accounts, model, expected }) => {
440
expect(
441
UsageLimitSources.hubPoolResetAt(
apps/server/src/usage/UsageLimitSources.ts
+21
-17
@@ -11,6 +11,7 @@ import {
11
type UsageLimitSourceSnapshot,
12
} from "@t3tools/contracts";
13
import { resolveServerBackgroundActivitySettings } from "@t3tools/shared/backgroundActivitySettings";
14
+import { antigravityWindowLimitsModel, hubRoutes } from "@t3tools/shared/usageLimits";
15
import * as Context from "effect/Context";
16
import * as DateTime from "effect/DateTime";
17
import * as Duration from "effect/Duration";
@@ -81,7 +82,9 @@ function keepLastGoodReadings(
82
candidate.email === account.email &&
83
candidate.workspaceId === account.workspaceId,
84
);
84
- return last && !last.usageLimits.unavailable ? last : account;
85
+ if (!last || last.usageLimits.unavailable) return account;
86
+ // Only the reading is lent; an unread model list stays unknown.
87
+ return { ...last, models: account.models };
88
}),
89
};
90
});
@@ -249,7 +252,7 @@ export const layer = Layer.effect(UsageLimitSources, make).pipe(
252
Layer.provide(SecretResolverLayer.layer),
253
);
254
252
-/** A hub answers with a usage limit only when every account it routes the driver to is spent. */
255
+/** A hub returns a usage limit only when every account it routes the model to is spent. */
256
export function hubPoolResetAt(
257
sources: ReadonlyArray<UsageLimitSourceSnapshot>,
258
driver: ProviderDriverKind,
@@ -257,21 +260,22 @@ export function hubPoolResetAt(
260
now: number,
261
): string | null {
262
let earliest: number | null = null;
260
- for (const source of sources) {
261
- for (const account of source.accounts) {
262
- if (account.driver !== driver) continue;
263
- // An unread account may be the one still blocked, so its refill is unknown.
264
- if (account.usageLimits.unavailable) return null;
265
- const spent = account.usageLimits.windows.filter(
266
- (window) => window.usedPercent >= 100 && windowLimitsModel(window, model),
267
- );
268
- if (spent.length === 0) return null;
269
- const resets = spent.map((window) => Date.parse(window.resetsAt ?? ""));
270
- if (resets.some((reset) => !Number.isFinite(reset))) return null;
271
- const recoversAt = Math.max(...resets);
272
- if (recoversAt <= now) return null;
273
- earliest = earliest === null ? recoversAt : Math.min(earliest, recoversAt);
274
- }
263
+ const routes = hubRoutes(sources, driver, model);
264
+ for (const account of sources.flatMap((source) => source.accounts).filter(routes)) {
265
+ // An unread account may be the one still blocked, so its refill is unknown.
266
+ if (account.usageLimits.unavailable) return null;
267
+ const spent = account.usageLimits.windows.filter(
268
+ (window) =>
269
+ window.usedPercent >= 100 &&
270
+ windowLimitsModel(window, model) &&
271
+ (account.driver !== "antigravity" || antigravityWindowLimitsModel(window, model)),
272
+ );
273
+ if (spent.length === 0) return null;
274
+ const resets = spent.map((window) => Date.parse(window.resetsAt ?? ""));
275
+ if (resets.some((reset) => !Number.isFinite(reset))) return null;
276
+ const recoversAt = Math.max(...resets);
277
+ if (recoversAt <= now) return null;
278
+ earliest = earliest === null ? recoversAt : Math.min(earliest, recoversAt);
279
}
280
return earliest === null ? null : DateTime.formatIso(DateTime.makeUnsafe(earliest));
281
}
apps/server/src/usage/cliproxyApi.test.ts
+28
-1
@@ -60,6 +60,7 @@ function fixture(
60
}>;
61
upstream?: (request: RequestBody) => { status: number; body: unknown };
62
cooldownStatus?: number;
63
+ models?: (name: string) => Response;
64
} = {},
65
) {
66
const requests: Array<{ path: string; body?: RequestBody }> = [];
@@ -72,6 +73,12 @@ function fixture(
73
? decodeRequest(new TextDecoder().decode(request.body.body))
74
: undefined;
75
requests.push({ path, ...(body ? { body } : {}) });
76
+ if (path.endsWith("/auth-files/models"))
77
+ return HttpClientResponse.fromWeb(
78
+ request,
79
+ options.models?.(new URL(request.url).searchParams.get("name")!) ??
80
+ Response.json({}, { status: 404 }),
81
+ );
82
if (path.endsWith("/auth-files"))
83
return HttpClientResponse.fromWeb(
84
request,
@@ -228,6 +235,24 @@ describe("CLIProxyAPI built-in management API", () => {
235
}),
236
);
237
238
+ it.effect("names the models the hub routes to each account, when the hub lists them", () =>
239
+ Effect.gen(function* () {
240
+ const test = fixture({
241
+ accounts: [...accounts, { ...accounts[1]!, id: "third.json", auth_index: "c" }],
242
+ models: (name) =>
243
+ name === "first.json"
244
+ ? Response.json({ models: [{ id: "gpt-5.6-sol" }, { id: " " }] })
245
+ : name === "third.json"
246
+ ? Response.json({ models: [] })
247
+ : Response.json({}, { status: 404 }),
248
+ });
249
+ const api = yield* test.api;
250
+ const result = yield* api.readAccounts(config);
251
+ expect(result.map((account) => account.models)).toEqual([["gpt-5.6-sol"], undefined, []]);
252
+ expect(result[1]?.usageLimits.windows).toHaveLength(1);
253
+ }),
254
+ );
255
+
256
it.effect("resolves a missing usage plan from current, then legacy, token plans", () =>
257
Effect.gen(function* () {
258
const test = fixture({
@@ -620,7 +645,9 @@ describe("CLIProxyAPI built-in management API", () => {
645
});
646
const [account] = yield* (yield* test.api).readAccounts(config);
647
expect(account?.usageLimits.unavailable?.reason).toBe("probeFailed");
623
- expect(test.requests.map((request) => request.path)).toEqual(["/v0/management/auth-files"]);
648
+ expect(test.requests.map((request) => request.path)).not.toContain(
649
+ "/v0/management/api-call",
650
+ );
651
}),
652
);
653
apps/server/src/usage/cliproxyApi.ts
+44
-7
@@ -55,6 +55,9 @@ const AuthFile = Schema.Struct({
55
),
56
});
57
const AuthFiles = Schema.Struct({ files: Schema.Array(AuthFile) });
58
+const AuthFileModels = Schema.Struct({
59
+ models: Schema.Array(Schema.Struct({ id: Schema.String })),
60
+});
61
const ApiResponse = Schema.Struct({ status_code: Schema.Number, body: Schema.String });
62
const CodexWindow = Schema.Struct({
63
used_percent: Schema.Number,
@@ -118,6 +121,7 @@ const CreditList = Schema.Struct({
121
});
122
123
const decodeAuthFiles = Schema.decodeUnknownEffect(AuthFiles);
124
+const decodeAuthFileModels = Schema.decodeUnknownEffect(AuthFileModels);
125
const encodeJson = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown));
126
const decodeApiResponse = Schema.decodeUnknownEffect(ApiResponse);
127
const decodeCreditList = Schema.decodeUnknownEffect(Schema.fromJsonString(CreditList));
@@ -439,6 +443,20 @@ export const makeCliproxyApi = Effect.gen(function* () {
443
return (yield* decodeAuthFiles(response)).files;
444
});
445
446
+ // Older hubs lack this endpoint; the account then counts for every model of its driver.
447
+ const routedModels = Effect.fn("CliproxyApi.routedModels")(function* (
448
+ hub: CliproxyHub,
449
+ account: AuthFile,
450
+ ) {
451
+ const response = yield* management(
452
+ hub,
453
+ `auth-files/models?name=${encodeURIComponent(account.id)}`,
454
+ );
455
+ return (yield* decodeAuthFileModels(response)).models.flatMap(({ id }) =>
456
+ id.trim() ? [id.trim()] : [],
457
+ );
458
+ });
459
+
460
const apiCall = Effect.fn("CliproxyApi.apiCall")(function* (
461
hub: CliproxyHub,
462
account: AuthFile,
@@ -494,14 +512,33 @@ export const makeCliproxyApi = Effect.gen(function* () {
512
: new UsageLimitSourceError({ detail: "The hub could not list accounts." }),
513
),
514
);
497
- return yield* Effect.forEach(
498
- accounts.flatMap((account) => {
499
- const provider = HUB_PROVIDERS.get(account.provider);
500
- return provider && !account.disabled ? [{ account, provider }] : [];
501
- }),
502
- ({ account, provider }) => readAccount(hub, account, provider),
503
- { concurrency: 4 },
515
+ const readable = accounts.flatMap((account) => {
516
+ const provider = HUB_PROVIDERS.get(account.provider);
517
+ return provider && !account.disabled ? [{ account, provider }] : [];
518
+ });
519
+ // Model lists are optional, so their lookups run apart from the quota reads and stop at one
520
+ // short deadline; a slow lookup must not push a refresh past its budget.
521
+ const [readings, models] = yield* Effect.all(
522
+ [
523
+ Effect.forEach(readable, ({ account, provider }) => readAccount(hub, account, provider), {
524
+ concurrency: 4,
525
+ }),
526
+ Effect.forEach(
527
+ readable,
528
+ ({ account }) =>
529
+ routedModels(hub, account).pipe(
530
+ Effect.timeoutOption("2 seconds"),
531
+ Effect.orElseSucceed(() => Option.none()),
532
+ ),
533
+ { concurrency: "unbounded" },
534
+ ),
535
+ ],
536
+ { concurrency: 2 },
537
);
538
+ return readings.map((reading, index) => {
539
+ const listed = models[index];
540
+ return listed && Option.isSome(listed) ? { ...reading, models: listed.value } : reading;
541
+ });
542
});
543
544
const consume = Effect.fn("CliproxyApi.consume")(function* (
apps/web/src/components/ChatView.tsx
+7
@@ -1401,6 +1401,11 @@ export default function ChatView(props: ChatViewProps) {
1401
const selectedProvider = selectedProviderEntry?.driverKind ?? requestedDriverKind;
1402
const activeProviderInstanceId = selectedProviderEntry?.instanceId ?? null;
1403
const activeProviderStatus = selectedProviderEntry?.snapshot ?? null;
1404
+ const activeUsageModel =
1405
+ [
1406
+ composerModelSelectionApplies ? composerSelectedModelSelection : null,
1407
+ activeThread?.modelSelection,
1408
+ ].find((selection) => selection?.instanceId === activeProviderInstanceId)?.model ?? null;
1409
const conversationProviderStatus =
1410
providerStatuses.find((status) => status.instanceId === activeRuntime?.providerInstanceId) ??
1411
activeProviderStatus;
@@ -1473,6 +1478,7 @@ export default function ChatView(props: ChatViewProps) {
1478
threadKey: routeThreadKey,
1479
panelKey: usageLimitsKey,
1480
providerInstanceId: activeProviderInstanceId,
1481
+ model: activeUsageModel,
1482
providerDriver: activeProviderStatus?.driver ?? null,
1483
providers: providerStatuses,
1484
sources: serverConfig?.usageLimitSources ?? EMPTY_USAGE_LIMIT_SOURCES,
@@ -4046,6 +4052,7 @@ export default function ChatView(props: ChatViewProps) {
4052
onDeleteProjectScript={deleteProjectScriptStable}
4053
usage={{
4054
providerInstanceId: activeProviderInstanceId,
4055
+ model: activeUsageModel,
4056
providers: providerStatuses,
4057
sources: serverConfig?.usageLimitSources ?? EMPTY_USAGE_LIMIT_SOURCES,
4058
contextWindow: activeContextWindow,
apps/web/src/components/chat/ThreadDetailsUsage.logic.test.ts
new
+147
@@ -0,0 +1,147 @@
1
+import {
2
+ ProviderDriverKind,
3
+ ProviderInstanceId,
4
+ type ServerProvider,
5
+ type ServerProviderUsageLimits,
6
+ type UsageLimitSourceSnapshot,
7
+ UsageLimitSourceId,
8
+} from "@t3tools/contracts";
9
+import { describe, expect, it } from "vite-plus/test";
10
+
11
+import { poolSources, resolveThreadDetailsLimits } from "./ThreadDetailsUsage.logic";
12
+
13
+const now = Date.parse("2026-10-30T12:00:00.000Z");
14
+const checkedAt = "2026-10-30T11:59:00.000Z";
15
+const claude = ProviderDriverKind.make("claudeAgent");
16
+const codex = ProviderDriverKind.make("codex");
17
+const instanceId = ProviderInstanceId.make("claudeAgent");
18
+
19
+function limitsAt(usedPercent: number): ServerProviderUsageLimits {
20
+ return {
21
+ checkedAt,
22
+ windows: [
23
+ {
24
+ id: "five_hour",
25
+ kind: "session",
26
+ label: "Session",
27
+ usedPercent,
28
+ windowDurationMins: 300,
29
+ resetsAt: "2026-10-30T13:17:00.000Z",
30
+ },
31
+ ],
32
+ };
33
+}
34
+
35
+const unsupported: ServerProviderUsageLimits = {
36
+ checkedAt,
37
+ windows: [],
38
+ unavailable: { reason: "unsupported" },
39
+};
40
+
41
+function claudeInstance(usageLimits: ServerProviderUsageLimits): ServerProvider {
42
+ return {
43
+ instanceId,
44
+ driver: claude,
45
+ enabled: true,
46
+ installed: true,
47
+ version: null,
48
+ status: "ready",
49
+ auth: {
50
+ status: "authenticated",
51
+ type: "customEndpoint",
52
+ label: "Custom API endpoint",
53
+ endpoint: "http://127.0.0.1:8317",
54
+ },
55
+ checkedAt,
56
+ models: [],
57
+ slashCommands: [],
58
+ skills: [],
59
+ usageLimits,
60
+ };
61
+}
62
+
63
+interface HubAccountInput {
64
+ readonly id: string;
65
+ readonly driver?: ProviderDriverKind;
66
+ readonly models?: readonly string[];
67
+ readonly limits: ServerProviderUsageLimits;
68
+}
69
+
70
+function hub(
71
+ label: string,
72
+ accounts: readonly HubAccountInput[],
73
+ origin = "http://127.0.0.1:8317",
74
+): UsageLimitSourceSnapshot {
75
+ return {
76
+ id: UsageLimitSourceId.make(label),
77
+ kind: "cliproxy",
78
+ label,
79
+ origin,
80
+ checkedAt,
81
+ accounts: accounts.map((account) => ({
82
+ id: account.id,
83
+ driver: account.driver ?? claude,
84
+ ...(account.models ? { models: account.models } : {}),
85
+ usageLimits: account.limits,
86
+ })),
87
+ };
88
+}
89
+
90
+function shown(
91
+ own: ServerProviderUsageLimits,
92
+ sources: readonly UsageLimitSourceSnapshot[],
93
+ model: string | null,
94
+) {
95
+ const resolved = resolveThreadDetailsLimits(
96
+ instanceId,
97
+ model,
98
+ [claudeInstance(own)],
99
+ sources,
100
+ now,
101
+ );
102
+ if (resolved?.kind !== "pool") return resolved;
103
+ return {
104
+ kind: resolved.kind,
105
+ rows: resolved.windows.map((window) => ({
106
+ label: window.label,
107
+ left: window.remainingPercent,
108
+ accounts: window.members.length,
109
+ from: poolSources(window),
110
+ })),
111
+ };
112
+}
113
+
114
+describe("resolveThreadDetailsLimits", () => {
115
+ it("keeps an instance's failed reading instead of a hub it is not sent to", () => {
116
+ const failed: ServerProviderUsageLimits = {
117
+ checkedAt,
118
+ windows: [],
119
+ unavailable: { reason: "probeFailed" },
120
+ };
121
+ const direct = { ...claudeInstance(failed), auth: { status: "authenticated" as const } };
122
+ const elsewhere = claudeInstance(unsupported);
123
+ const readableHub = hub("Hub", [{ id: "a.json", limits: limitsAt(20) }]);
124
+ const otherHub = hub("Other", [{ id: "a.json", limits: limitsAt(20) }], "http://hub");
125
+ expect(resolveThreadDetailsLimits(instanceId, null, [direct], [readableHub], now)).toEqual({
126
+ kind: "instance",
127
+ limits: failed,
128
+ });
129
+ expect(resolveThreadDetailsLimits(instanceId, null, [elsewhere], [otherHub], now)).toEqual({
130
+ kind: "instance",
131
+ limits: unsupported,
132
+ });
133
+ });
134
+
135
+ it("pools only the accounts the hub routes the model to, even of another driver", () => {
136
+ const sources = [
137
+ hub("Hub", [
138
+ { id: "a.json", models: ["claude-opus-5-5"], limits: limitsAt(10) },
139
+ { id: "c.json", driver: codex, models: ["gpt-5.6-sol"], limits: limitsAt(30) },
140
+ ]),
141
+ ];
142
+ expect(shown(unsupported, sources, "gpt-5.6-sol[1m]")).toEqual({
143
+ kind: "pool",
144
+ rows: [{ label: "Session", left: 70, accounts: 1, from: { hubs: ["Hub"], signedIn: false } }],
145
+ });
146
+ });
147
+});
apps/web/src/components/chat/ThreadDetailsUsage.logic.ts
new
+113
@@ -0,0 +1,113 @@
1
+import {
2
+ EnvironmentId,
3
+ type ProviderInstanceId,
4
+ type ServerProvider,
5
+ type ServerProviderUsageLimits,
6
+ type UsageLimitSourceSnapshots,
7
+} from "@t3tools/contracts";
8
+import {
9
+ antigravityWindowLimitsModel,
10
+ collectLimitAccounts,
11
+ collectLimitPools,
12
+ collectProviderUsageLimits,
13
+ displayLimitWindows,
14
+ hubRoutes,
15
+ instanceHubs,
16
+ type LimitPoolWindow,
17
+} from "@t3tools/shared/usageLimits";
18
+import { limitsNotice } from "@t3tools/shared/usageLimitsCopy";
19
+
20
+export type ThreadDetailsLimits =
21
+ | { readonly kind: "instance"; readonly limits: ServerProviderUsageLimits }
22
+ | { readonly kind: "pool"; readonly windows: readonly LimitPoolWindow[] };
23
+
24
+// collectLimitAccounts keys its input by environment; the card reads one, so any id serves.
25
+const CARD_ENVIRONMENT = EnvironmentId.make("thread-details");
26
+
27
+export function resolveThreadDetailsLimits(
28
+ providerInstanceId: ProviderInstanceId | null,
29
+ model: string | null,
30
+ providers: readonly ServerProvider[],
31
+ sources: UsageLimitSourceSnapshots,
32
+ now: number,
33
+): ThreadDetailsLimits | null {
34
+ const provider = providers.find((entry) => entry.instanceId === providerInstanceId);
35
+ if (!provider) return null;
36
+ const report = collectProviderUsageLimits(provider.instanceId, providers, sources, now, model);
37
+ // Only this instance's data: the report keeps one instance per login, and any other entry may be
38
+ // a different login or workspace, so fall back to the instance's own snapshot.
39
+ const own =
40
+ report?.accounts.find((entry) => entry.instanceId === provider.instanceId)?.limits ??
41
+ provider.usageLimits;
42
+ if (!own) return null;
43
+ const hubs = instanceHubs(provider, sources);
44
+ if (limitsNotice(own) === null || hubs.length === 0) return { kind: "instance", limits: own };
45
+ // An instance sent to a hub reads no limits of its own; its hub pools the accounts it spends.
46
+ return hubPool(provider.driver, model, providers, hubs, now) ?? { kind: "instance", limits: own };
47
+}
48
+
49
+export function nextPoolReset(window: LimitPoolWindow, now: number) {
50
+ const pooled = window.members.length > 1;
51
+ return (
52
+ window.resets.find((reset) => reset.at > now && (!pooled || reset.restoresPercent > 0)) ?? null
53
+ );
54
+}
55
+
56
+function hubPool(
57
+ driver: ServerProvider["driver"],
58
+ model: string | null,
59
+ providers: readonly ServerProvider[],
60
+ sources: UsageLimitSourceSnapshots,
61
+ now: number,
62
+): ThreadDetailsLimits | null {
63
+ const routes = hubRoutes(sources, driver, model);
64
+ const routed = sources.map((source) => ({
65
+ ...source,
66
+ accounts: source.accounts.filter(routes).map((account) =>
67
+ account.driver === "antigravity"
68
+ ? {
69
+ ...account,
70
+ usageLimits: {
71
+ ...account.usageLimits,
72
+ windows: account.usageLimits.windows.filter((window) =>
73
+ antigravityWindowLimitsModel(window, model),
74
+ ),
75
+ },
76
+ }
77
+ : account,
78
+ ),
79
+ }));
80
+ const readable = routed
81
+ .flatMap((source) => source.accounts)
82
+ .filter((account) => limitsNotice(account.usageLimits) === null);
83
+ if (readable.length === 0) return null;
84
+ // A signed-in login joins the pool only as a fresher reading of an account the hub routes to.
85
+ const signedIn = providers.filter((provider) =>
86
+ readable.some(
87
+ (account) =>
88
+ account.driver === provider.driver &&
89
+ account.workspaceId === provider.auth.workspaceId &&
90
+ account.email !== undefined &&
91
+ account.email.toLowerCase() === provider.auth.email?.toLowerCase(),
92
+ ),
93
+ );
94
+ const presentations = new Map([
95
+ [
96
+ CARD_ENVIRONMENT,
97
+ {
98
+ entry: { target: { label: "" } },
99
+ serverConfig: { providers: signedIn, usageLimitSources: routed },
100
+ },
101
+ ],
102
+ ]);
103
+ const pools = collectLimitPools(collectLimitAccounts(presentations), now);
104
+ return pools.length > 0 ? { kind: "pool", windows: pools.flatMap(displayLimitWindows) } : null;
105
+}
106
+
107
+export function poolSources(window: LimitPoolWindow) {
108
+ const hubs = window.members.flatMap(({ account }) =>
109
+ account.environments.length === 0 && account.sourceLabel ? [account.sourceLabel] : [],
110
+ );
111
+ const signedIn = window.members.some(({ account }) => account.environments.length > 0);
112
+ return { hubs: [...new Set(hubs)], signedIn };
113
+}
apps/web/src/components/chat/ThreadDetailsUsage.tsx
+102
-24
@@ -1,12 +1,13 @@
1
import type {
2
ProviderInstanceId,
3
ServerProvider,
4
+ ServerProviderUsageLimits,
5
ServerProviderUsageWindow,
6
UsageLimitSourceSnapshots,
7
} from "@t3tools/contracts";
8
import {
8
- collectProviderUsageLimits,
9
type LimitPace,
10
+ type LimitPoolWindow,
11
paceOf,
12
paceRemainingPercent,
13
remainingPercent,
@@ -25,6 +26,7 @@ import { formatUpcomingTimestamp } from "../../timestampFormat";
26
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
27
import { formatContextWindowCompactionMessage } from "./compaction.logic";
28
import { ThreadDetailsSection } from "./ThreadDetailsSection";
29
+import { nextPoolReset, poolSources, resolveThreadDetailsLimits } from "./ThreadDetailsUsage.logic";
30
31
const PACE_LABEL: Record<LimitPace, string> = {
32
ahead: msg("Ahead of pace"),
@@ -34,6 +36,7 @@ const PACE_LABEL: Record<LimitPace, string> = {
36
37
export interface ThreadDetailsUsageInput {
38
readonly providerInstanceId: ProviderInstanceId | null;
39
+ readonly model: string | null;
40
readonly providers: readonly ServerProvider[];
41
readonly sources: UsageLimitSourceSnapshots;
42
readonly contextWindow: ContextWindowSnapshot | null;
@@ -41,27 +44,24 @@ export interface ThreadDetailsUsageInput {
44
45
type UsageTone = "error" | "warning" | null;
46
47
+function limitTone(left: number): UsageTone {
48
+ if (left <= 10) return "error";
49
+ if (left <= 20) return "warning";
50
+ return null;
51
+}
52
+
53
/** The selected provider's limit windows. Each row reads as room left and opens the usage page. */
54
export function ThreadDetailsUsage({
55
providerInstanceId,
56
+ model,
57
providers,
58
sources,
59
}: Omit<ThreadDetailsUsageInput, "contextWindow">) {
60
const gt = useGT();
51
- const m = useMessages();
61
const nowMinute = useNowMinute();
62
const now = Date.parse(`${nowMinute}:00Z`);
54
- const report =
55
- providerInstanceId !== null
56
- ? collectProviderUsageLimits(providerInstanceId, providers, sources, now)
57
- : null;
58
- // Only this instance's data: the report keeps one instance per login, and any other entry may be
59
- // a different login or workspace, so fall back to the instance's own snapshot.
60
- const limits =
61
- report?.accounts.find((entry) => entry.instanceId === providerInstanceId)?.limits ??
62
- providers.find((provider) => provider.instanceId === providerInstanceId)?.usageLimits;
63
- if (!limits) return null;
64
- const notice = limitsNotice(limits, m);
63
+ const resolved = resolveThreadDetailsLimits(providerInstanceId, model, providers, sources, now);
64
+ if (!resolved) return null;
65
66
return (
67
<ThreadDetailsSection
@@ -70,23 +70,41 @@ export function ThreadDetailsUsage({
70
showHeading={false}
71
>
72
<div className="grid grid-cols-[auto_minmax(3rem,1fr)_auto] gap-x-3 text-xs">
73
- {notice ? (
74
- <UsageRow
75
- label={gt("Limits", { $context: "usage limits row label" })}
76
- fill={null}
77
- tone={null}
78
- value={gt("Unavailable")}
79
- tooltip={<span className="text-foreground">{notice}</span>}
80
- opensUsage
81
- />
73
+ {resolved.kind === "pool" ? (
74
+ resolved.windows.map((window) => <PoolRow key={window.id} window={window} now={now} />)
75
) : (
83
- limits.windows.map((window) => <LimitRow key={window.id} window={window} now={now} />)
76
+ <InstanceRows limits={resolved.limits} now={now} />
77
)}
78
</div>
79
</ThreadDetailsSection>
80
);
81
}
82
83
+function InstanceRows({
84
+ limits,
85
+ now,
86
+}: {
87
+ readonly limits: ServerProviderUsageLimits;
88
+ readonly now: number;
89
+}) {
90
+ const gt = useGT();
91
+ const m = useMessages();
92
+ const notice = limitsNotice(limits, m);
93
+ if (notice) {
94
+ return (
95
+ <UsageRow
96
+ label={gt("Limits", { $context: "usage limits row label" })}
97
+ fill={null}
98
+ tone={null}
99
+ value={gt("Unavailable")}
100
+ tooltip={<span className="text-foreground">{notice}</span>}
101
+ opensUsage
102
+ />
103
+ );
104
+ }
105
+ return limits.windows.map((window) => <LimitRow key={window.id} window={window} now={now} />);
106
+}
107
+
108
/** The thread's context window. The bar fills as context is used; the tick marks auto-compaction. */
109
export function ThreadDetailsContext({ usage }: { readonly usage: ContextWindowSnapshot }) {
110
const maxTokens = usage.maxTokens != null && usage.maxTokens > 0 ? usage.maxTokens : null;
@@ -172,7 +190,7 @@ function LimitRow({
190
<UsageRow
191
label={window.label}
192
fill={left}
175
- tone={left <= 10 ? "error" : left <= 20 ? "warning" : null}
193
+ tone={limitTone(left)}
194
tick={timeLeft}
195
value={`${left}%`}
196
ariaValue={gt("{left}% left", { left })}
@@ -201,6 +219,66 @@ function LimitRow({
219
);
220
}
221
222
+function PoolRow({ window, now }: { readonly window: LimitPoolWindow; readonly now: number }) {
223
+ const gt = useGT();
224
+ const m = useMessages();
225
+ const timestampFormat = usePrimarySettings((settings) => settings.timestampFormat);
226
+ const left = window.remainingPercent;
227
+ const accounts = window.members.length;
228
+ const from = poolSources(window);
229
+ const sourceLabels = [...from.hubs, ...(from.signedIn ? [gt("Signed-in accounts")] : [])];
230
+ const next = nextPoolReset(window, now);
231
+ const resetsAt = next?.member.window.resetsAt;
232
+ const reset =
233
+ next && resetsAt
234
+ ? {
235
+ duration: formatDuration(next.at - now, m),
236
+ time: formatUpcomingTimestamp(resetsAt, timestampFormat, now, undefined, m),
237
+ }
238
+ : null;
239
+ return (
240
+ <UsageRow
241
+ label={window.label}
242
+ fill={left}
243
+ tone={limitTone(left)}
244
+ value={`${left}%`}
245
+ ariaValue={gt("{left}% left", { left })}
246
+ opensUsage
247
+ tooltip={
248
+ <>
249
+ <span className="text-foreground">
250
+ {accounts > 1
251
+ ? gt("{label}: {left}% left across {accounts} accounts", {
252
+ label: window.label,
253
+ left,
254
+ accounts,
255
+ })
256
+ : gt("{label}: {left}% left", { label: window.label, left })}
257
+ </span>
258
+ {window.pace ? (
259
+ <span className="text-muted-foreground">{m(PACE_LABEL[window.pace])}</span>
260
+ ) : null}
261
+ {next && reset ? (
262
+ <span className="text-muted-foreground">
263
+ {accounts > 1
264
+ ? gt("+{percent}% in {duration} · {time}", {
265
+ percent: next.restoresPercent,
266
+ ...reset,
267
+ })
268
+ : gt("Resets in {duration} · {time}", reset)}
269
+ </span>
270
+ ) : null}
271
+ {sourceLabels.length > 0 ? (
272
+ <span className="text-muted-foreground">
273
+ {gt("From {sources}", { sources: sourceLabels.join(", ") })}
274
+ </span>
275
+ ) : null}
276
+ </>
277
+ }
278
+ />
279
+ );
280
+}
281
+
282
/** One label, hairline, and value row; the whole row opens the details tooltip. With `opensUsage` it links to the usage page. */
283
function UsageRow({
284
label,
apps/web/src/components/chat/useUsageLimitsPanel.ts
+4
-2
@@ -18,6 +18,7 @@ export function useUsageLimitsPanel(input: {
18
readonly threadKey: string;
19
readonly panelKey: string | null;
20
readonly providerInstanceId: ProviderInstanceId | null;
21
+ readonly model: string | null;
22
readonly providerDriver: ServerProvider["driver"] | null;
23
readonly providers: readonly ServerProvider[];
24
readonly sources: UsageLimitSourceSnapshots;
@@ -27,6 +28,7 @@ export function useUsageLimitsPanel(input: {
28
threadKey,
29
panelKey,
30
providerInstanceId,
31
+ model,
32
providerDriver,
33
providers,
34
sources,
@@ -42,7 +44,7 @@ export function useUsageLimitsPanel(input: {
44
}
45
const report =
46
panel !== null && panelKey !== null && panel.key === panelKey && providerInstanceId !== null
45
- ? collectProviderUsageLimits(providerInstanceId, providers, sources, panel.now)
47
+ ? collectProviderUsageLimits(providerInstanceId, providers, sources, panel.now, model)
48
: null;
49
const banner =
50
report !== null && panel !== null
@@ -63,7 +65,7 @@ export function useUsageLimitsPanel(input: {
65
const now = Date.now();
66
const nextReport =
67
providerInstanceId !== null && panelKey !== null
66
- ? collectProviderUsageLimits(providerInstanceId, providers, sources, now)
68
+ ? collectProviderUsageLimits(providerInstanceId, providers, sources, now, model)
69
: null;
70
if (nextReport && panelKey !== null) {
71
setPanel({ key: panelKey, threadKey, now });
apps/web/src/i18n/translations/de.json
+4
@@ -4171,6 +4171,10 @@
4171
"ebb26f93fb83a71b": "{label}: {left} % übrig",
4172
"1b16346722b65812": "{timeLeft} % des Zeitfensters übrig",
4173
"728c6cc1431e76c8": "Wird in {duration} zurückgesetzt · {time}",
4174
+ "23622878aeee86d9": "Angemeldete Konten",
4175
+ "d28c53157c8c0f5f": "{label}: {left} % übrig über {accounts} Konten",
4176
+ "ba03873d5356238b": "+{percent} % in {duration} · {time}",
4177
+ "78c1d280f021a28f": "Von {sources}",
4178
"e16b0b9b490c8bc7": "{label}: {value}",
4179
"ba67d0a9ff5dabf0": "Die Zwischenablage-API ist beim Kopieren der Admin-Anfrage nicht verfügbar.",
4180
"aef4bec20e799aab": "Die Admin-Anfrage konnte nicht in die Zwischenablage kopiert werden.",
apps/web/src/i18n/translations/en.json
+4
@@ -4170,6 +4170,10 @@
4170
"ebb26f93fb83a71b": "{label}: {left}% left",
4171
"1b16346722b65812": "{timeLeft}% of the window left",
4172
"728c6cc1431e76c8": "Resets in {duration} · {time}",
4173
+ "23622878aeee86d9": "Signed-in accounts",
4174
+ "d28c53157c8c0f5f": "{label}: {left}% left across {accounts} accounts",
4175
+ "ba03873d5356238b": "+{percent}% in {duration} · {time}",
4176
+ "78c1d280f021a28f": "From {sources}",
4177
"e16b0b9b490c8bc7": "{label}: {value}",
4178
"ba67d0a9ff5dabf0": "Clipboard API is unavailable while copying admin request.",
4179
"aef4bec20e799aab": "Failed to copy admin request to the clipboard.",
apps/web/src/i18n/translations/es.json
+4
@@ -4168,6 +4168,10 @@
4168
"ebb26f93fb83a71b": "{label}: {left} % restante",
4169
"1b16346722b65812": "Queda un {timeLeft}% de la ventana",
4170
"728c6cc1431e76c8": "Se restablece en {duration} · {time}",
4171
+ "23622878aeee86d9": "Cuentas con sesión iniciada",
4172
+ "d28c53157c8c0f5f": "{label}: queda un {left} % entre {accounts} cuentas",
4173
+ "ba03873d5356238b": "+{percent} % en {duration} · {time}",
4174
+ "78c1d280f021a28f": "De {sources}",
4175
"e16b0b9b490c8bc7": "{label}: {value}",
4176
"ba67d0a9ff5dabf0": "La API del portapapeles no está disponible al copiar la solicitud de administrador.",
4177
"aef4bec20e799aab": "No se pudo copiar la solicitud de administrador al portapapeles.",
apps/web/src/i18n/translations/fr.json
+4
@@ -4169,6 +4169,10 @@
4169
"ebb26f93fb83a71b": "{label} : {left} % restant",
4170
"1b16346722b65812": "{timeLeft} % de la fenêtre restant",
4171
"728c6cc1431e76c8": "Réinitialisation dans {duration} · {time}",
4172
+ "23622878aeee86d9": "Comptes connectés",
4173
+ "d28c53157c8c0f5f": "{label} : {left} % restants sur {accounts} comptes",
4174
+ "ba03873d5356238b": "+{percent} % dans {duration} · {time}",
4175
+ "78c1d280f021a28f": "Depuis {sources}",
4176
"e16b0b9b490c8bc7": "{label} : {value}",
4177
"ba67d0a9ff5dabf0": "L’API Presse-papiers n’est pas disponible pour copier la demande à l’administrateur.",
4178
"aef4bec20e799aab": "Impossible de copier la demande à l’administrateur dans le presse-papiers.",
apps/web/src/i18n/translations/ja.json
+4
@@ -4159,6 +4159,10 @@
4159
"ebb26f93fb83a71b": "{label}: 残り {left}%",
4160
"1b16346722b65812": "期間の残り {timeLeft}%",
4161
"728c6cc1431e76c8": "{duration} 後にリセット · {time}",
4162
+ "23622878aeee86d9": "サインイン済みのアカウント",
4163
+ "d28c53157c8c0f5f": "{label}: {accounts} 個のアカウントで残り {left}%",
4164
+ "ba03873d5356238b": "{duration}後に +{percent}% · {time}",
4165
+ "78c1d280f021a28f": "取得元: {sources}",
4166
"e16b0b9b490c8bc7": "{label}: {value}",
4167
"ba67d0a9ff5dabf0": "管理者へのリクエストをコピーする際にクリップボード API を利用できませんでした。",
4168
"aef4bec20e799aab": "管理者へのリクエストをクリップボードにコピーできませんでした。",
apps/web/src/i18n/translations/ko.json
+4
@@ -4156,6 +4156,10 @@
4156
"ebb26f93fb83a71b": "{label}: {left}% 남음",
4157
"1b16346722b65812": "기간 {timeLeft}% 남음",
4158
"728c6cc1431e76c8": "{duration} 후 초기화 · {time}",
4159
+ "23622878aeee86d9": "로그인된 계정",
4160
+ "d28c53157c8c0f5f": "{label}: 계정 {accounts}개에서 {left}% 남음",
4161
+ "ba03873d5356238b": "{duration} 후 +{percent}% · {time}",
4162
+ "78c1d280f021a28f": "출처: {sources}",
4163
"e16b0b9b490c8bc7": "{label}: {value}",
4164
"ba67d0a9ff5dabf0": "관리자 요청을 복사하는 중 클립보드 API를 사용할 수 없습니다.",
4165
"aef4bec20e799aab": "관리자 요청을 클립보드에 복사하지 못했습니다.",
apps/web/src/i18n/translations/pt-BR.json
+4
@@ -4168,6 +4168,10 @@
4168
"ebb26f93fb83a71b": "{label}: {left}% restante",
4169
"1b16346722b65812": "{timeLeft}% da janela restante",
4170
"728c6cc1431e76c8": "Renova em {duration} · {time}",
4171
+ "23622878aeee86d9": "Contas conectadas",
4172
+ "d28c53157c8c0f5f": "{label}: {left}% restante em {accounts} contas",
4173
+ "ba03873d5356238b": "+{percent}% em {duration} · {time}",
4174
+ "78c1d280f021a28f": "De {sources}",
4175
"e16b0b9b490c8bc7": "{label}: {value}",
4176
"ba67d0a9ff5dabf0": "A API da área de transferência não está disponível ao copiar o pedido para o administrador.",
4177
"aef4bec20e799aab": "Falha ao copiar o pedido para o administrador para a área de transferência.",
apps/web/src/i18n/translations/ru.json
+4
@@ -4168,6 +4168,10 @@
4168
"ebb26f93fb83a71b": "{label}: осталось {left}%",
4169
"1b16346722b65812": "От окна осталось {timeLeft}%",
4170
"728c6cc1431e76c8": "Сброс через {duration} · {time}",
4171
+ "23622878aeee86d9": "Аккаунты, в которые выполнен вход",
4172
+ "d28c53157c8c0f5f": "{label}: осталось {left}% на {accounts} аккаунтах",
4173
+ "ba03873d5356238b": "+{percent}% через {duration} · {time}",
4174
+ "78c1d280f021a28f": "Источник: {sources}",
4175
"e16b0b9b490c8bc7": "{label}: {value}",
4176
"ba67d0a9ff5dabf0": "API буфера обмена недоступен при копировании запроса администратору.",
4177
"aef4bec20e799aab": "Не удалось скопировать запрос администратору в буфер обмена.",
apps/web/src/i18n/translations/sv.json
+4
@@ -4169,6 +4169,10 @@
4169
"ebb26f93fb83a71b": "{label}: {left} % kvar",
4170
"1b16346722b65812": "{timeLeft} % av fönstret kvar",
4171
"728c6cc1431e76c8": "Återställs om {duration} · {time}",
4172
+ "23622878aeee86d9": "Inloggade konton",
4173
+ "d28c53157c8c0f5f": "{label}: {left} % kvar över {accounts} konton",
4174
+ "ba03873d5356238b": "+{percent} % om {duration} · {time}",
4175
+ "78c1d280f021a28f": "Från {sources}",
4176
"e16b0b9b490c8bc7": "{label}: {value}",
4177
"ba67d0a9ff5dabf0": "Urklipps-API:t är inte tillgängligt vid kopiering av administratörsbegäran.",
4178
"aef4bec20e799aab": "Kunde inte kopiera administratörsbegäran till urklipp.",
apps/web/src/i18n/translations/zh.json
+4
@@ -4175,6 +4175,10 @@
4175
"ebb26f93fb83a71b": "{label}:剩余 {left}%",
4176
"1b16346722b65812": "窗口剩余 {timeLeft}%",
4177
"728c6cc1431e76c8": "{duration} 后重置 · {time}",
4178
+ "23622878aeee86d9": "已登录的账号",
4179
+ "d28c53157c8c0f5f": "{label}:{accounts} 个账号共剩余 {left}%",
4180
+ "ba03873d5356238b": "{duration}后 +{percent}% · {time}",
4181
+ "78c1d280f021a28f": "来自 {sources}",
4182
"e16b0b9b490c8bc7": "{label}:{value}",
4183
"ba67d0a9ff5dabf0": "复制管理员请求时剪贴板 API 不可用。",
4184
"aef4bec20e799aab": "无法将管理员请求复制到剪贴板。",
docs/user/usage.md
+4
-2
@@ -188,8 +188,10 @@ accounts for other providers are not read. Codex accounts show banked reset cred
188
account and choose **Use reset** to redeem one. No hub plugin is required.
189
190
This connection supplies usage information; configure
191
-the provider separately to send agent requests through the hub. Remove the hub from the same
192
-settings section when you no longer need it.
191
+the provider separately to send agent requests through the hub. A thread uses the hub's limits and
192
+reset times only when its provider's endpoint has the same address as the hub, for example
193
+`http://127.0.0.1:8317` for both. Remove the hub from the same settings section when you no longer
194
+need it.
195
196
## Subscription usage widget
197
packages/contracts/src/providerUsageLimits.ts
+2
@@ -78,6 +78,8 @@ export const UsageLimitSourceAccount = Schema.Struct({
78
email: Schema.optional(TrimmedNonEmptyString),
79
plan: Schema.optional(TrimmedNonEmptyString),
80
workspaceId: Schema.optional(TrimmedNonEmptyString),
81
+ /** The models the hub routes to this account. */
82
+ models: Schema.optional(Schema.Array(TrimmedNonEmptyString)),
83
usageLimits: ServerProviderUsageLimits,
84
});
85
export type UsageLimitSourceAccount = typeof UsageLimitSourceAccount.Type;
packages/shared/src/usageLimits.test.ts
+67
@@ -1387,6 +1387,7 @@ describe("/usage-limits", () => {
1387
id: UsageLimitSourceId.make("hub"),
1388
kind: "cliproxy" as const,
1389
label: "Accounts",
1390
+ origin: "http://hub:8317",
1391
checkedAt: limits.checkedAt,
1392
accounts: [
1393
{
@@ -1555,6 +1556,72 @@ describe("/usage-limits", () => {
1556
expect(report?.notices).toEqual([]);
1557
});
1558
1559
+ it("shows a proxied instance the hub accounts its model routes to, of any driver", () => {
1560
+ const routed = [
1561
+ {
1562
+ ...sources[0]!,
1563
+ accounts: sources[0]!.accounts.map((account) =>
1564
+ account.id === "oss" ? { ...account, models: ["gpt-5.6-sol"] } : account,
1565
+ ),
1566
+ },
1567
+ ];
1568
+ const proxy = provider({
1569
+ instanceId: ProviderInstanceId.make("claudex"),
1570
+ driver: ProviderDriverKind.make("claudeAgent"),
1571
+ auth: { status: "authenticated", type: "customEndpoint", endpoint: "http://hub:8317" },
1572
+ });
1573
+ // regression: #30778 a local login the hub does not route to is not this thread's account
1574
+ const unrelated = provider({
1575
+ instanceId: ProviderInstanceId.make("codex-personal"),
1576
+ usageLimits: limits,
1577
+ auth: { status: "authenticated", email: "personal@example.com" },
1578
+ });
1579
+ const ids = (instance: ServerProvider, model: string | null) =>
1580
+ collectProviderUsageLimits(
1581
+ instance.instanceId,
1582
+ [selected, proxy, unrelated],
1583
+ routed,
1584
+ now,
1585
+ model,
1586
+ )?.accounts.map((account) => account.id);
1587
+ expect(ids(proxy, "gpt-5.6-sol[1m]")).toEqual(["codex", "hub:oss"]);
1588
+ // regression: #30778 another hub's model list does not decide this hub's routing
1589
+ const other = {
1590
+ ...routed[0]!,
1591
+ id: UsageLimitSourceId.make("other"),
1592
+ origin: "http://other:8317",
1593
+ accounts: [
1594
+ {
1595
+ id: "x",
1596
+ driver: ProviderDriverKind.make("grok"),
1597
+ models: ["gpt-5.6-sol"],
1598
+ usageLimits: limits,
1599
+ },
1600
+ ],
1601
+ };
1602
+ expect(
1603
+ collectProviderUsageLimits(
1604
+ proxy.instanceId,
1605
+ [selected, proxy],
1606
+ [other, ...routed],
1607
+ now,
1608
+ "gpt-5.6-sol",
1609
+ )?.accounts.map((account) => account.id),
1610
+ ).toEqual(["codex", "hub:oss"]);
1611
+ // regression: #30778 a custom endpoint other than the hub does not follow the hub's routing
1612
+ const elsewhere = { ...proxy, auth: { ...proxy.auth, endpoint: "http://other:8317" } };
1613
+ expect(
1614
+ collectProviderUsageLimits(
1615
+ proxy.instanceId,
1616
+ [selected, elsewhere],
1617
+ routed,
1618
+ now,
1619
+ "gpt-5.6-sol",
1620
+ ),
1621
+ ).toBeNull();
1622
+ expect(ids(selected, "gpt-5.6-sol")).toEqual(["codex", "codex-personal", "hub:oss"]);
1623
+ });
1624
+
1625
it("keeps the freshest usable native duplicate and the freshest native credits in either order", () => {
1626
const failed = provider({
1627
auth: selected.auth,
packages/shared/src/usageLimits.ts
+83
-6
@@ -13,6 +13,7 @@ import {
13
type ServerProvider,
14
type ServerProviderUsageLimits,
15
type ServerProviderUsageWindow,
16
+ type UsageLimitSourceAccount,
17
type UsageLimitSourceSnapshot,
18
type UsageLimitSourceSnapshots,
19
} from "@t3tools/contracts";
@@ -838,27 +839,102 @@ export function withUsageLimitsCommands(
839
});
840
}
841
842
+/** The hubs an instance sends its requests through: those whose address is its endpoint. */
843
+export function instanceHubs(
844
+ provider: ServerProvider,
845
+ sources: UsageLimitSourceSnapshots,
846
+): UsageLimitSourceSnapshots {
847
+ const endpoint = provider.auth.endpoint;
848
+ return endpoint === undefined ? [] : sources.filter((source) => source.origin === endpoint);
849
+}
850
+
851
+// Antigravity meters Gemini Argon, Gemini Carbon, other Gemini, and Claude/GPT models apart.
852
+function antigravityQuotaFamily(id: string) {
853
+ if (!id.startsWith("gemini")) return "shared";
854
+ return id.includes("argon") ? "argon" : id.includes("carbon") ? "carbon" : "gemini";
855
+}
856
+
857
+/** Each Antigravity quota blocks only the models it meters. */
858
+export function antigravityWindowLimitsModel(
859
+ window: Pick<ServerProviderUsageWindow, "id">,
860
+ model: string | null,
861
+): boolean {
862
+ // A hub can prefix model ids, such as "ag/gemini-3.1-pro".
863
+ const base = model?.slice(model.lastIndexOf("/") + 1);
864
+ // An alias such as "fast" may route to either quota, so both hold it back.
865
+ if (base === undefined || !/^(gemini|claude|gpt)/.test(base)) return true;
866
+ return antigravityQuotaFamily(window.id) === antigravityQuotaFamily(base);
867
+}
868
+
869
+/** The hub accounts that serve a model: those that list it, else every account of the driver. */
870
+export function hubRoutes(
871
+ sources: UsageLimitSourceSnapshots,
872
+ driver: ServerProvider["driver"],
873
+ model: string | null,
874
+): (account: UsageLimitSourceAccount) => boolean {
875
+ // Claude Code's 1M-context suffix is not part of the model id a hub routes.
876
+ const full = model?.replace(/\[1m\]$/i, "");
877
+ // The hub routes a thinking suffix such as "gpt-5.2(high)" by its base model when one lists it.
878
+ const base = full?.replace(/\([^)]*\)$/, "");
879
+ const lists = (id: string | undefined) =>
880
+ sources.some((source) => source.accounts.some((account) => account.models?.includes(id ?? "")));
881
+ const slug = lists(base) ? base : full;
882
+ const listed = (account: UsageLimitSourceAccount) =>
883
+ slug !== undefined && account.models?.includes(slug) === true;
884
+ const serving = new Set(
885
+ sources.flatMap((source) => source.accounts.filter(listed).map((account) => account.driver)),
886
+ );
887
+ // Model ids such as "opus" are aliases no hub lists, so no listing falls back to the driver.
888
+ if (serving.size === 0)
889
+ return (account) => account.driver === driver && account.models?.length !== 0;
890
+ // An account whose model list was unreadable may serve the model too.
891
+ return (account) =>
892
+ account.models ? listed(account) : serving.has(account.driver) || account.driver === driver;
893
+}
894
+
895
export function collectProviderUsageLimits(
896
instanceId: ProviderInstanceId,
897
providers: readonly ServerProvider[],
898
sources: UsageLimitSourceSnapshots,
899
now: number,
900
+ model: string | null = null,
901
): UsageLimitsReport | null {
902
const selected = providers.find((provider) => provider.instanceId === instanceId);
848
- if (!selected || !hasProviderUsageLimits(selected.driver, providers, sources)) return null;
903
+ if (!selected) return null;
904
+ // Only an instance sent to a hub is known to reach the accounts that hub routes its model to.
905
+ const hubs = instanceHubs(selected, sources);
906
+ const routes =
907
+ hubs.length > 0
908
+ ? hubRoutes(hubs, selected.driver, model)
909
+ : (account: UsageLimitSourceAccount) => account.driver === selected.driver;
910
+ const shownHubs = hubs.length > 0 ? hubs : sources;
911
+ const drivers = new Set(
912
+ shownHubs.flatMap((source) => source.accounts.filter(routes).map((account) => account.driver)),
913
+ );
914
+ if (drivers.size === 0) drivers.add(selected.driver);
915
+ if (![...drivers].some((driver) => hasProviderUsageLimits(driver, providers, sources))) {
916
+ return null;
917
+ }
918
const resolveKey = accountKeyResolver([
919
...providers.filter((provider) => provider.enabled).map(nativeReport),
920
...sources.flatMap((source) => source.accounts),
921
]);
922
+ // Behind a hub, a local login counts only when it is one of the accounts the hub routes to.
923
+ const routedKeys =
924
+ hubs.length > 0
925
+ ? new Set(hubs.flatMap((source) => source.accounts.filter(routes).map(resolveKey)))
926
+ : null;
927
type NativeSnapshot = { provider: ServerProvider; limits: ServerProviderUsageLimits };
928
const nativeByAccount = new Map<
929
string,
930
{ usage: NativeSnapshot; credits: NativeSnapshot | null }
931
>();
932
for (const provider of providersWithLimits(providers)) {
859
- if (provider.driver !== selected.driver || !provider.usageLimits) continue;
933
+ if (!drivers.has(provider.driver) || !provider.usageLimits) continue;
934
+ const accountKey = resolveKey(nativeReport(provider));
935
+ if (routedKeys && (accountKey === null || !routedKeys.has(accountKey))) continue;
936
const snapshot = { provider, limits: provider.usageLimits };
861
- const key = resolveKey(nativeReport(provider)) ?? `instance:${provider.instanceId}`;
937
+ const key = accountKey ?? `instance:${provider.instanceId}`;
938
const previous = nativeByAccount.get(key);
939
const previousUsable = previous ? limitsNotice(previous.usage.limits) === null : false;
940
const usable = limitsNotice(snapshot.limits) === null;
@@ -893,7 +969,8 @@ export function collectProviderUsageLimits(
969
credits,
970
} of native) {
971
const key = resolveKey(nativeReport(provider));
896
- const hubCredits = sources
972
+ // Only a hub this instance reaches may redeem a credit for its thread.
973
+ const hubCredits = shownHubs
974
.flatMap((source) => source.accounts.map((account) => ({ source, account })))
975
.filter(
976
({ account }) =>
@@ -935,8 +1012,8 @@ export function collectProviderUsageLimits(
1012
limits: shownCredits ? { ...limits, resetCredits: shownCredits } : limits,
1013
});
1014
}
938
- for (const source of sources) {
939
- const matching = source.accounts.filter((account) => account.driver === selected.driver);
1015
+ for (const source of shownHubs) {
1016
+ const matching = source.accounts.filter(routes);
1017
for (const account of matching) {
1018
const key = resolveKey(account);
1019
if (key && nativeAccountKeys.has(key)) continue;