Skip to content

Commit c8b94a4

Browse files
refactor(shared): one account ranking for the limit switch, for clients and server
Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent c7ab042 commit c8b94a4

4 files changed

Lines changed: 242 additions & 79 deletions

File tree

‎packages/client-runtime/src/state/limitSwitchTargets.ts‎

Lines changed: 10 additions & 79 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@
66
*/
77
import type { ModelSelection, ServerProvider, ServerProviderUsageWindow } from "@t3tools/contracts";
88

9+
import { exhaustedUsageWindow, rankLimitSwitchCandidates } from "@t3tools/shared/usageLimitSwitch";
10+
911
import { resolveProviderInstanceDisplayName } from "./providerInstanceDisplay.ts";
1012

1113
export interface LimitSwitchTarget {
@@ -15,12 +17,6 @@ export interface LimitSwitchTarget {
1517
readonly remainingPercent: number | null;
1618
}
1719

18-
function remainingPercent(provider: ServerProvider): number | null {
19-
const usage = provider.usageLimits;
20-
if (!usage || usage.unavailable || usage.windows.length === 0) return null;
21-
return Math.max(0, 100 - Math.max(...usage.windows.map((window) => window.usedPercent)));
22-
}
23-
2420
/**
2521
* The window an account is closest to running out of, for a compact "where do I
2622
* stand" readout. Null when the account reports no windows, so the caller shows
@@ -46,86 +42,21 @@ export function tightestUsageWindow(
4642
: null;
4743
}
4844

49-
/** The used-up window that reopens last, which is the one the account is waiting on. */
50-
function exhaustedWindow(
51-
provider: ServerProvider,
52-
nowMs: number,
53-
): ServerProviderUsageWindow | undefined {
54-
return provider.usageLimits?.windows
55-
.filter(
56-
(window) =>
57-
window.usedPercent >= 100 &&
58-
(window.resetsAt === undefined || Date.parse(window.resetsAt) > nowMs),
59-
)
60-
.reduce<ServerProviderUsageWindow | undefined>(
61-
(latest, window) =>
62-
latest === undefined ||
63-
Date.parse(window.resetsAt ?? "") > Date.parse(latest.resetsAt ?? "") ||
64-
window.resetsAt === undefined
65-
? window
66-
: latest,
67-
undefined,
68-
);
69-
}
70-
71-
function isExhausted(provider: ServerProvider, nowMs: number): boolean {
72-
return exhaustedWindow(provider, nowMs) !== undefined;
73-
}
74-
7545
/**
7646
* Other ready, signed-in instances of the current instance's driver that offer
77-
* the thread's model and are not known to be out of quota. Instances sharing the
78-
* thread's continuation group come first, since they resume the native thread;
79-
* after that, the most headroom wins.
47+
* the thread's model and are not known to be out of quota, best first. See
48+
* `rankLimitSwitchCandidates` for the order.
8049
*/
8150
export function listLimitSwitchTargets(input: {
8251
readonly providers: ReadonlyArray<ServerProvider>;
8352
readonly current: ModelSelection;
8453
readonly nowMs: number;
8554
}): ReadonlyArray<LimitSwitchTarget> {
86-
const source = input.providers.find(
87-
(provider) => provider.instanceId === input.current.instanceId,
88-
);
89-
if (!source) return [];
90-
const candidates = input.providers.flatMap((provider) => {
91-
if (
92-
provider.instanceId === source.instanceId ||
93-
provider.driver !== source.driver ||
94-
!provider.enabled ||
95-
!provider.installed ||
96-
provider.availability === "unavailable" ||
97-
provider.status !== "ready" ||
98-
provider.auth.status !== "authenticated" ||
99-
isExhausted(provider, input.nowMs)
100-
) {
101-
return [];
102-
}
103-
const model = provider.models.find(
104-
(entry) => entry.slug === input.current.model || entry.aliases?.includes(input.current.model),
105-
);
106-
if (!model) return [];
107-
const sameContinuation =
108-
source.continuation !== undefined &&
109-
source.continuation.groupKey === provider.continuation?.groupKey;
110-
return [
111-
{
112-
sameContinuation,
113-
target: {
114-
selection: { ...input.current, instanceId: provider.instanceId, model: model.slug },
115-
label: resolveProviderInstanceDisplayName(provider),
116-
remainingPercent: remainingPercent(provider),
117-
} satisfies LimitSwitchTarget,
118-
},
119-
];
120-
});
121-
return [...candidates]
122-
.sort(
123-
(left, right) =>
124-
Number(right.sameContinuation) - Number(left.sameContinuation) ||
125-
(right.target.remainingPercent ?? -1) - (left.target.remainingPercent ?? -1) ||
126-
left.target.label.localeCompare(right.target.label),
127-
)
128-
.map((candidate) => candidate.target);
55+
return rankLimitSwitchCandidates(input).map((candidate) => ({
56+
selection: candidate.selection,
57+
label: resolveProviderInstanceDisplayName(candidate.provider),
58+
remainingPercent: candidate.remainingPercent,
59+
}));
12960
}
13061

13162
/** At or below this headroom the selected account is worth a heads-up. */
@@ -160,7 +91,7 @@ export function suggestLimitSwitch(input: {
16091
);
16192
if (!source) return null;
16293
const window =
163-
exhaustedWindow(source, input.nowMs) ??
94+
exhaustedUsageWindow(source, input.nowMs) ??
16495
source.usageLimits?.windows
16596
.filter(
16697
(candidate) =>

‎packages/shared/package.json‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -351,6 +351,10 @@
351351
"types": "./src/usageLimits.ts",
352352
"import": "./src/usageLimits.ts"
353353
},
354+
"./usageLimitSwitch": {
355+
"types": "./src/usageLimitSwitch.ts",
356+
"import": "./src/usageLimitSwitch.ts"
357+
},
354358
"./desktopAppControl": {
355359
"types": "./src/desktopAppControl.ts",
356360
"import": "./src/desktopAppControl.ts"
Lines changed: 98 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,98 @@
1+
import {
2+
ProviderDriverKind,
3+
ProviderInstanceId,
4+
type ModelSelection,
5+
type ServerProvider,
6+
} from "@t3tools/contracts";
7+
import { describe, expect, it } from "vite-plus/test";
8+
9+
import { selectionAfterExhaustedLimit } from "./usageLimitSwitch.ts";
10+
11+
const NOW = Date.parse("2026-10-10T12:00:00.000Z");
12+
13+
function provider(
14+
instanceId: string,
15+
weeklyUsed: number | null,
16+
overrides: Partial<ServerProvider> = {},
17+
): ServerProvider {
18+
return {
19+
instanceId: ProviderInstanceId.make(instanceId),
20+
driver: ProviderDriverKind.make("codex"),
21+
enabled: true,
22+
installed: true,
23+
version: "1.0.0",
24+
status: "ready",
25+
auth: { status: "authenticated" },
26+
checkedAt: "2026-10-10T11:59:00.000Z",
27+
models: [{ slug: "gpt-6", name: "GPT-6", isCustom: false, capabilities: null }],
28+
slashCommands: [],
29+
skills: [],
30+
...(weeklyUsed === null
31+
? {}
32+
: {
33+
usageLimits: {
34+
checkedAt: "2026-10-10T11:59:00.000Z",
35+
windows: [
36+
{
37+
id: "secondary",
38+
kind: "weekly" as const,
39+
label: "Weekly",
40+
usedPercent: weeklyUsed,
41+
resetsAt: "2026-10-14T02:00:00.000Z",
42+
},
43+
],
44+
},
45+
}),
46+
...overrides,
47+
};
48+
}
49+
50+
const current: ModelSelection = {
51+
instanceId: ProviderInstanceId.make("codex"),
52+
model: "gpt-6",
53+
options: [{ id: "effort", value: "high" }],
54+
};
55+
56+
describe("selectionAfterExhaustedLimit", () => {
57+
it("moves a used-up account's turn to the account with the most allowance, keeping model and options", () => {
58+
expect(
59+
selectionAfterExhaustedLimit({
60+
providers: [provider("codex", 100), provider("codex_busy", 70), provider("codex_free", 10)],
61+
current,
62+
nowMs: NOW,
63+
}),
64+
).toEqual({ ...current, instanceId: "codex_free" });
65+
});
66+
67+
it("leaves the turn alone while the account has allowance, or reports none", () => {
68+
expect(
69+
selectionAfterExhaustedLimit({
70+
providers: [provider("codex", 99), provider("codex_free", 10)],
71+
current,
72+
nowMs: NOW,
73+
}),
74+
).toBeNull();
75+
expect(
76+
selectionAfterExhaustedLimit({
77+
providers: [provider("codex", null), provider("codex_free", 10)],
78+
current,
79+
nowMs: NOW,
80+
}),
81+
).toBeNull();
82+
});
83+
84+
it("leaves the turn alone when no other account can take it", () => {
85+
expect(
86+
selectionAfterExhaustedLimit({
87+
providers: [
88+
provider("codex", 100),
89+
provider("codex_out", 100),
90+
provider("codex_signed_out", 5, { auth: { status: "unauthenticated" } }),
91+
provider("claude", 5, { driver: ProviderDriverKind.make("claudeAgent") }),
92+
],
93+
current,
94+
nowMs: NOW,
95+
}),
96+
).toBeNull();
97+
});
98+
});
Lines changed: 130 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,130 @@
1+
/**
2+
* Which other accounts of the same provider can take over when one account
3+
* has used up a quota window. Shared by the clients, which offer the switch,
4+
* and the server, which can make it on its own.
5+
*
6+
* @module usageLimitSwitch
7+
*/
8+
import type { ModelSelection, ServerProvider, ServerProviderUsageWindow } from "@t3tools/contracts";
9+
10+
type SwitchProvider = Pick<
11+
ServerProvider,
12+
| "instanceId"
13+
| "driver"
14+
| "enabled"
15+
| "installed"
16+
| "availability"
17+
| "status"
18+
| "auth"
19+
| "models"
20+
| "continuation"
21+
| "usageLimits"
22+
>;
23+
24+
/** The used-up window that reopens last, which is the one the account is waiting on. */
25+
export function exhaustedUsageWindow(
26+
provider: Pick<ServerProvider, "usageLimits">,
27+
nowMs: number,
28+
): ServerProviderUsageWindow | undefined {
29+
return provider.usageLimits?.windows
30+
.filter(
31+
(window) =>
32+
window.usedPercent >= 100 &&
33+
(window.resetsAt === undefined || Date.parse(window.resetsAt) > nowMs),
34+
)
35+
.reduce<ServerProviderUsageWindow | undefined>(
36+
(latest, window) =>
37+
latest === undefined ||
38+
Date.parse(window.resetsAt ?? "") > Date.parse(latest.resetsAt ?? "") ||
39+
window.resetsAt === undefined
40+
? window
41+
: latest,
42+
undefined,
43+
);
44+
}
45+
46+
/** Headroom of the tightest known window, or null when the account reports none. */
47+
export function usageHeadroomPercent(provider: Pick<ServerProvider, "usageLimits">): number | null {
48+
const usage = provider.usageLimits;
49+
if (!usage || usage.unavailable || usage.windows.length === 0) return null;
50+
return Math.max(0, 100 - Math.max(...usage.windows.map((window) => window.usedPercent)));
51+
}
52+
53+
export interface LimitSwitchCandidate<P extends SwitchProvider> {
54+
readonly provider: P;
55+
readonly selection: ModelSelection;
56+
readonly remainingPercent: number | null;
57+
}
58+
59+
/**
60+
* Other ready, signed-in instances of the current instance's driver that offer
61+
* the same model and are not known to be out of quota. Instances sharing the
62+
* current one's continuation group come first, since they resume the native
63+
* thread; after that, the most headroom wins, then the instance id so the
64+
* order is stable.
65+
*/
66+
export function rankLimitSwitchCandidates<P extends SwitchProvider>(input: {
67+
readonly providers: ReadonlyArray<P>;
68+
readonly current: ModelSelection;
69+
readonly nowMs: number;
70+
}): ReadonlyArray<LimitSwitchCandidate<P>> {
71+
const source = input.providers.find(
72+
(provider) => provider.instanceId === input.current.instanceId,
73+
);
74+
if (!source) return [];
75+
const candidates = input.providers.flatMap((provider) => {
76+
if (
77+
provider.instanceId === source.instanceId ||
78+
provider.driver !== source.driver ||
79+
!provider.enabled ||
80+
!provider.installed ||
81+
provider.availability === "unavailable" ||
82+
provider.status !== "ready" ||
83+
provider.auth.status !== "authenticated" ||
84+
exhaustedUsageWindow(provider, input.nowMs) !== undefined
85+
) {
86+
return [];
87+
}
88+
const model = provider.models.find(
89+
(entry) => entry.slug === input.current.model || entry.aliases?.includes(input.current.model),
90+
);
91+
if (!model) return [];
92+
return [
93+
{
94+
sameContinuation:
95+
source.continuation !== undefined &&
96+
source.continuation.groupKey === provider.continuation?.groupKey,
97+
candidate: {
98+
provider,
99+
selection: { ...input.current, instanceId: provider.instanceId, model: model.slug },
100+
remainingPercent: usageHeadroomPercent(provider),
101+
} satisfies LimitSwitchCandidate<P>,
102+
},
103+
];
104+
});
105+
return [...candidates]
106+
.sort(
107+
(left, right) =>
108+
Number(right.sameContinuation) - Number(left.sameContinuation) ||
109+
(right.candidate.remainingPercent ?? -1) - (left.candidate.remainingPercent ?? -1) ||
110+
left.candidate.provider.instanceId.localeCompare(right.candidate.provider.instanceId),
111+
)
112+
.map((entry) => entry.candidate);
113+
}
114+
115+
/**
116+
* The selection a turn should run on instead of `current`, when `current`'s
117+
* account has used up a window and another account can take the turn. Null
118+
* when the account still has allowance or nobody can take over.
119+
*/
120+
export function selectionAfterExhaustedLimit(input: {
121+
readonly providers: ReadonlyArray<SwitchProvider>;
122+
readonly current: ModelSelection;
123+
readonly nowMs: number;
124+
}): ModelSelection | null {
125+
const source = input.providers.find(
126+
(provider) => provider.instanceId === input.current.instanceId,
127+
);
128+
if (!source || exhaustedUsageWindow(source, input.nowMs) === undefined) return null;
129+
return rankLimitSwitchCandidates(input)[0]?.selection ?? null;
130+
}

0 commit comments

Comments
 (0)