feat(usage): Limits tab with provider quota windows and Codex banked resets #9421
ClosedStiensWout(GitHub profile, opens in a new tab)wants to merge 18 commits into
main fromrefs/pull/9421/headopened View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XXL
- apps/web/src/components/usage/UsageLimits.tsx lines 69 to 78OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +58,21 @@58+ const at = Date.parse(iso);59+ return Number.isFinite(at) ? RESET_AT.format(at) : null;60+}61+62+const OUTCOME_TEXT: Record<UsageLimitsConsumeResetOutcome, string> = {63+ reset: "Reset applied.",64+ nothingToReset: "Nothing to reset right now.",65+ noCredit: "No reset credit left.",66+ alreadyRedeemed: "That credit was already redeemed.",67+};68+69+function ProviderMark({70+ provider,71+ className,72+}: {73+ readonly provider: UsageProviderKind;74+ readonly className?: string;75+}) {76+ const Mark = PROVIDER_PRESENTATION[provider].mark;77+ return <Mark className={cn("shrink-0", className)} aria-hidden />;78+}
- apps/server/src/provider/Layers/CodexAdapter.ts line 2254OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -2229,3 +2235,20 @@22292235 );22302236 };223122372238+ // Account requests ride on a live session's app-server when one exists and2239+ // otherwise on a short-lived process, so limits never need an open thread.2240+ const liveSession = () => {2241+ for (const session of sessions.values()) {2242+ if (!session.stopped) return session;2243+ }2244+ return undefined;2245+ };2246+2247+ const accountRequest = <A>(2248+ method: string,2249+ viaSession: (runtime: CodexSessionRuntimeShape) => Effect.Effect<A, CodexSessionRuntimeError>,2250+ viaClient: (2251+ client: Parameters<Parameters<typeof withCodexAccountClient<A, never>>[1]>[0],2252+ ) => Effect.Effect<A, CodexErrors.CodexAppServerError>,2253+ ): Effect.Effect<A, ProviderAdapterError> =>2254+ Effect.suspend(() => {apps/server/src/provider/Layers/CodexAdapter.ts line 2297Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -2229,3 +2235,21 @@22292235 );22302236 };223122372238+ // Account requests ride on a live session's app-server when one exists and2239+ // otherwise on a short-lived process, so limits never need an open thread.2240+ const liveSession = () => {2241+ for (const session of sessions.values()) {2242+ if (!session.stopped) return session;2243+ }2244+ return undefined;2245+ };2246+2247+ const accountRequest = <A>(2248+ method: string,2249+ viaSession: (runtime: CodexSessionRuntimeShape) => Effect.Effect<A, CodexSessionRuntimeError>,2250+ viaClient: (2251+ client: Parameters<Parameters<typeof withCodexAccountClient<A, never>>[1]>[0],2252+ ) => Effect.Effect<A, CodexErrors.CodexAppServerError>,2253+ ): Effect.Effect<A, ProviderAdapterError> =>2254+ Effect.suspend(() => {2255+ const session = liveSession();apps/web/src/state/usage.ts line 178Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -146,0 +156,21 @@156+ readonly environmentId: EnvironmentId;157+ readonly label: string;158+ readonly isPending: boolean;159+ readonly providers: readonly UsageProviderLimits[] | null;160+}161+162+/**163+ * Every environment's live limits subscription. Subscribing makes the server164+ * ask its adapters for fresh numbers, so a refresh is a resubscribe.165+ */166+const usageLimitsAtom = Atom.make((get) => {167+ const presentations = get(environmentPresentations.presentationsAtom);168+ const statuses: EnvironmentLimitsStatus[] = [];169+ for (const [environmentId, presentation] of presentations) {170+ const result = get(serverEnvironment.usageLimits({ environmentId, input: {} }));171+ const snapshot = Option.getOrNull(AsyncResult.value(result));172+ statuses.push({173+ environmentId,174+ label: presentation.entry.target.label,175+ isPending: result.waiting && snapshot === null,176+ providers: snapshot?.providers ?? null,apps/web/src/components/usage/UsageLimits.tsx line 394Resolvedby StiensWout(GitHub profile, opens in a new tab)@@ -0,0 +388,21 @@388+ const environmentCount = new Set(providers.map((entry) => entry.environmentId)).size;389+ const instanceCounts = new Map<string, number>();390+ for (const entry of providers) {391+ const key = `${entry.environmentId}:${entry.provider}`;392+ instanceCounts.set(key, (instanceCounts.get(key) ?? 0) + 1);393+ }394+ const props: SectionProps = {395+ providers,396+ now,397+ showEnvironment: environmentCount > 1,398+ instanceCounts,399+ };400+ return (401+ <div className="flex flex-col gap-8">402+ {providers.length === 0 && !isPending ? (403+ <span className="text-sm text-muted-foreground">No limits reported yet.</span>404+ ) : null}405+ {providers.map((entry) => (406+ <section key={entryKey(entry)} className="flex flex-col gap-3">407+ <ProviderHeading entry={entry} props={props} />408+ <ProviderWindows entry={entry} now={now} />docs/user/usage.md lines 18 to 21OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -13,3 +13,9 @@1313 headline and chart. Refreshing rescans every connected environment and refetches model pricing on1414 each of them, so a newly released model that showed $0.00 gets a price without waiting for the daily1515 pricing update.16+17+The **Limits** tab shows the rolling quota windows your subscription providers report for the18+signed-in account, across every connected environment. Each window in use is a bar from the moment19+it opened to its reset, filled by how much of the quota is spent. A thin line marks how far into the20+window you are, which is also where even spending would have put the fill, and a small icon says21+whether you are ahead of, on, or under that pace. Hover a bar for the exact figures and the reset
- apps/server/src/provider/Layers/claudeRateLimits.ts line 30OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +10,21 @@10+import { epochToIso } from "./codexRateLimits.ts";11+12+export interface ClaudeRateLimitInfo {13+ readonly status: "allowed" | "allowed_warning" | "rejected";14+ readonly resetsAt?: number;15+ readonly rateLimitType?: string;16+ /** Fraction of the window used, 0..1, as the unified rate-limit headers report it. */17+ readonly utilization?: number;18+}19+20+const WINDOWS: Record<string, { readonly label: string; readonly windowMinutes: number | null }> = {21+ five_hour: { label: "5 hour", windowMinutes: 300 },22+ seven_day: { label: "Weekly", windowMinutes: 10080 },23+ seven_day_opus: { label: "Weekly Opus", windowMinutes: 10080 },24+ seven_day_sonnet: { label: "Weekly Sonnet", windowMinutes: 10080 },25+ overage: { label: "Extra usage", windowMinutes: null },26+};27+28+export function normalizeClaudeRateLimit(info: ClaudeRateLimitInfo): UsageLimitsUpdate | null {29+ const kind = info.rateLimitType === undefined ? undefined : WINDOWS[info.rateLimitType];30+ if (info.rateLimitType === undefined || kind === undefined) return null;@@ -146,0 +206,21 @@206+ })),207+ ),208+ [environments],209+ );210+211+ const refresh = useCallback(() => {212+ for (const environment of environments) {213+ appAtomRegistry.refresh(214+ serverEnvironment.usageLimits({ environmentId: environment.environmentId, input: {} }),215+ );216+ }217+ }, [environments]);218+219+ return {220+ providers,221+ receivedAt,222+ isPending:223+ environments.length > 0 &&224+ environments.every((environment) => environment.providers === null) &&225+ environments.some((environment) => environment.isPending),226+ refresh,apps/server/src/usage/UsageLimitsService.ts line 307Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +142,21 @@142+ const update = yield* adapter.readAccountLimits;143+ if (update === null) return;144+ yield* apply(instanceId, provider, update);145+ });146+147+ const refresh: UsageLimitsServiceShape["refresh"] = Effect.gen(function* () {148+ const instances = yield* sources.listInstances;149+ yield* Effect.forEach(150+ instances,151+ (instanceId) =>152+ refreshInstance(instanceId).pipe(153+ Effect.catchCause((cause) =>154+ Effect.logDebug("usage limits refresh skipped", {155+ instanceId,156+ detail: errorDetail(cause),157+ }),158+ ),159+ ),160+ { concurrency: 4, discard: true },161+ );162+ });
- apps/server/src/usage/UsageLimitsService.ts lines 41 to 54OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +34,21 @@34+import { ProviderAdapterRegistry } from "../provider/Services/ProviderAdapterRegistry.ts";35+import { ProviderService } from "../provider/Services/ProviderService.ts";36+import {37+ type SnapshotSubscription,38+ subscribeBeforeSnapshotWithoutMutex,39+} from "../utils/subscribeBeforeSnapshot.ts";40+41+export interface UsageLimitsServiceShape {42+ /** Latest snapshot plus every later change. Subscribing also triggers a fresh read. */43+ readonly subscribe: Effect.Effect<SnapshotSubscription<UsageLimitsSnapshot>, never, Scope.Scope>;44+ /** Ask every adapter that can answer for its current limits. Never fails. */45+ readonly refresh: Effect.Effect<void>;46+ readonly consumeReset: (47+ input: UsageLimitsConsumeResetInput,48+ ) => Effect.Effect<UsageLimitsConsumeResetResult, UsageLimitsError>;49+}50+51+export class UsageLimitsService extends Context.Service<52+ UsageLimitsService,53+ UsageLimitsServiceShape54+>()("t3/usage/UsageLimitsService") {}apps/server/src/usage/UsageLimitsService.ts lines 69 to 111Resolvedby StiensWout(GitHub profile, opens in a new tab)@@ -0,0 +72,21 @@72+ /** Configured display name for an instance, null when it has none. */73+ readonly getInstanceLabel: (instanceId: ProviderInstanceId) => Effect.Effect<string | null>;74+}75+76+/** Only subscription providers report limits; everything else is ignored. */77+function usageProviderFor(driver: ProviderDriverKind): UsageProviderKind | null {78+ switch (driver) {79+ case "codex":80+ return "codex";81+ case "claudeAgent":82+ return "claude";83+ default:84+ return null;85+ }86+}87+88+function errorDetail(cause: unknown): string {89+ return cause instanceof Error ? cause.message : String(cause);90+}91+92+export const make = Effect.fn("UsageLimitsService.make")(function* (sources: UsageLimitsSources) {apps/server/src/provider/Layers/claudeAccountLimits.ts lines 158 to 174OutdatedResolvedby StiensWout(GitHub profile, opens in a new tab)@@ -0,0 +154,21 @@154+ detail,155+ ...(cause === undefined ? {} : { cause }),156+ });157+158+export interface ClaudeAccountLimitsServices {159+ readonly settings: Pick<ClaudeSettings, "homePath">;160+ readonly fileSystem: FileSystem.FileSystem;161+ readonly path: Path.Path;162+ readonly httpClient: HttpClient.HttpClient;163+}164+165+/**166+ * Builds the reader once per adapter with its services captured, so the167+ * adapter can expose it with no requirements. Yields null when this machine168+ * has no usable claude.ai sign-in (API key sessions, expired token); the169+ * runtime event path still updates limits during turns.170+ */171+export function makeClaudeAccountLimitsReader(172+ services: ClaudeAccountLimitsServices,173+): Effect.Effect<UsageLimitsUpdate | null, ProviderAdapterError> {174+ const { settings, fileSystem, path, httpClient } = services;apps/server/src/usage/UsageLimitsService.ts lines 344 to 348Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +178,21 @@178+ }).pipe(Effect.forkScoped);179+180+ const subscribe: UsageLimitsServiceShape["subscribe"] = Effect.gen(function* () {181+ // Read first so the initial snapshot already carries fresh numbers and a182+ // client never mistakes the boot-time empty map for "nothing reported".183+ yield* refresh;184+ return yield* subscribeBeforeSnapshotWithoutMutex(changes, snapshot);185+ });186+187+ const consumeReset: UsageLimitsServiceShape["consumeReset"] = Effect.fn(188+ "UsageLimitsService.consumeReset",189+ )(function* (input) {190+ const adapter = yield* sources.getAdapter(input.instanceId);191+ const consume = adapter.consumeRateLimitResetCredit;192+ if (consume === undefined) {193+ return yield* new UsageLimitsError({194+ reason: "unsupported",195+ detail: `Provider '${adapter.provider}' does not bank reset credits.`,196+ });197+ }198+ const outcome = yield* consume.pipe(
- apps/server/src/usage/UsageLimitsService.ts line 117OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +97,21 @@97+ Effect.map((map) => ({98+ providers: Array.from(map.values()).toSorted(99+ (left, right) =>100+ left.provider.localeCompare(right.provider) ||101+ left.instanceId.localeCompare(right.instanceId),102+ ),103+ })),104+ );105+106+ /** Merge a sparse update into one instance's limits and publish the result. */107+ const apply = Effect.fn("UsageLimitsService.apply")(function* (108+ instanceId: ProviderInstanceId,109+ provider: UsageProviderKind,110+ update: UsageLimitsUpdate,111+ ) {112+ const observedAt = DateTime.formatIso(yield* DateTime.now);113+ const instanceLabel = yield* sources.getInstanceLabel(instanceId);114+ yield* Ref.update(state, (map) => {115+ const previous = map.get(instanceId);116+ const windows = new Map((previous?.windows ?? []).map((window) => [window.id, window]));117+ for (const window of update.windows) windows.set(window.id, window);apps/server/src/usage/UsageLimitsService.ts line 176Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +99,21 @@99+ (left, right) =>100+ left.provider.localeCompare(right.provider) ||101+ left.instanceId.localeCompare(right.instanceId),102+ ),103+ })),104+ );105+106+ /** Merge a sparse update into one instance's limits and publish the result. */107+ const apply = Effect.fn("UsageLimitsService.apply")(function* (108+ instanceId: ProviderInstanceId,109+ provider: UsageProviderKind,110+ update: UsageLimitsUpdate,111+ ) {112+ const observedAt = DateTime.formatIso(yield* DateTime.now);113+ const instanceLabel = yield* sources.getInstanceLabel(instanceId);114+ yield* Ref.update(state, (map) => {115+ const previous = map.get(instanceId);116+ const windows = new Map((previous?.windows ?? []).map((window) => [window.id, window]));117+ for (const window of update.windows) windows.set(window.id, window);118+ const next = new Map(map);119+ next.set(instanceId, {apps/server/src/provider/Layers/CodexAdapter.ts line 2302OutdatedResolvedby StiensWout(GitHub profile, opens in a new tab)@@ -2231,0 +2282,21 @@2282+ const request = session2283+ ? viaSession(session.runtime).pipe(Effect.catch(() => standalone))2284+ : standalone;2285+ return request.pipe(2286+ Effect.timeout(ACCOUNT_REQUEST_TIMEOUT),2287+ Effect.catchTag("TimeoutError", () =>2288+ requestError(`Codex did not answer ${method} within ${ACCOUNT_REQUEST_TIMEOUT}.`),2289+ ),2290+ );2291+ });2292+ };2293+2294+ const readAccountLimits: NonNullable<CodexAdapterShape["readAccountLimits"]> = accountRequest(2295+ "account/rateLimits/read",2296+ (runtime) => runtime.readRateLimits,2297+ (client) => client.request("account/rateLimits/read", undefined),2298+ ).pipe(Effect.map((response) => normalizeCodexRateLimits(response)));2299+2300+ const consumeRateLimitResetCredit: NonNullable<CodexAdapterShape["consumeRateLimitResetCredit"]> =2301+ Effect.suspend(() => {2302+ const idempotencyKey = NodeCrypto.randomUUID();apps/web/src/components/usage/UsagePage.tsx line 61OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -41,9 +45,17 @@4145 { days: 90, label: "90 days" },4246 ] as const;434748+type UsageMetric = UsageChartMetric | "limits";49+const METRIC_LABELS = { cost: "Cost", tokens: "Tokens", limits: "Limits" } as const;50+51+function isUsageMetric(value: string | null | undefined): value is UsageMetric {52+ return value === "cost" || value === "tokens" || value === "limits";53+}54+4455 export function UsagePage() {4556 const [windowSelection, setWindowSelection] = useState(() => ({4657 days: 30,4758 window: makeWindow(30),4859 }));49- const [metric, setMetric] = useState<UsageChartMetric>("cost");60+ const [metric, setMetric] = useState<UsageMetric>("cost");61+ const limits = useUsageLimits();
- apps/server/src/provider/Layers/CodexAdapter.ts line 2288OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -2231,0 +2268,21 @@2268+ homePath: codexConfig.homePath,2269+ cwd: process.cwd(),2270+ },2271+ viaClient,2272+ ).pipe(2273+ Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, childProcessSpawner),2274+ Effect.mapError((cause) =>2275+ requestError(cause instanceof Error ? cause.message : String(cause), cause),2276+ ),2277+ );2278+ return Effect.suspend(() => {2279+ const session = liveSession();2280+ // A session whose app-server died is still in the map until it is2281+ // stopped, so any failure there falls through to a fresh process.2282+ const request = session2283+ ? viaSession(session.runtime).pipe(Effect.catch(() => standalone))2284+ : standalone;2285+ return request.pipe(2286+ Effect.timeout(ACCOUNT_REQUEST_TIMEOUT),2287+ Effect.catchTag("TimeoutError", () =>2288+ requestError(`Codex did not answer ${method} within ${ACCOUNT_REQUEST_TIMEOUT}.`),
- apps/server/src/provider/Layers/CodexAdapter.ts lines 2287 to 2289OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -2231,0 +2269,21 @@2269+ cwd: process.cwd(),2270+ },2271+ viaClient,2272+ ).pipe(2273+ Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, childProcessSpawner),2274+ Effect.mapError((cause) =>2275+ requestError(cause instanceof Error ? cause.message : String(cause), cause),2276+ ),2277+ );2278+ return Effect.suspend(() => {2279+ const session = liveSession();2280+ // A session whose app-server died is still in the map until it is2281+ // stopped, so any failure there falls through to a fresh process.2282+ const request = session2283+ ? viaSession(session.runtime).pipe(Effect.catch(() => standalone))2284+ : standalone;2285+ return request.pipe(2286+ Effect.timeout(ACCOUNT_REQUEST_TIMEOUT),2287+ Effect.catchTag("TimeoutError", () =>2288+ requestError(`Codex did not answer ${method} within ${ACCOUNT_REQUEST_TIMEOUT}.`),2289+ ),apps/server/src/provider/Layers/CodexAdapter.ts lines 2274 to 2275OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -2231,0 +2255,21 @@2255+ ): Effect.Effect<A, ProviderAdapterError> => {2256+ const requestError = (detail: string, cause?: unknown) =>2257+ new ProviderAdapterRequestError({2258+ provider: PROVIDER,2259+ method,2260+ detail,2261+ ...(cause === undefined ? {} : { cause }),2262+ });2263+ const standalone = withCodexAccountClient(2264+ {2265+ binaryPath: codexConfig.binaryPath,2266+ launchArgs: resolveCodexLaunchArgs(codexConfig.launchArgs, options?.environment),2267+ environment: options?.environment,2268+ homePath: codexConfig.homePath,2269+ cwd: process.cwd(),2270+ },2271+ viaClient,2272+ ).pipe(2273+ Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, childProcessSpawner),2274+ Effect.mapError((cause) =>2275+ requestError(cause instanceof Error ? cause.message : String(cause), cause),
- apps/mobile/src/features/usage/UsageRouteScreen.tsx line 47Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -43,3 +44,4 @@4344 const [metric, setMetric] = useState<UsageChartMetric>("cost");4445 const { days: windowDays, window } = windowSelection;4546 const isPast24Hours = windowDays === 1;47+ const limits = useUsageLimits();
- apps/mobile/src/features/usage/UsageRouteScreen.tsx line 150Resolvedby StiensWout(GitHub profile, opens in a new tab)@@ -139,3 +142,7 @@139142 timeZone={window.timeZone}140143 />141144 <ProviderSection merged={merged} metric={metric} />145+ <UsageLimitsSection146+ providers={limits.providers}147+ failedEnvironments={limits.failedEnvironments}148+ now={limits.receivedAt}
- apps/server/src/usage/UsageLimitsService.ts line 139OutdatedResolvedby StiensWout(GitHub profile, opens in a new tab)@@ -0,0 +119,21 @@119+ instanceId: ProviderInstanceId,120+ provider: UsageProviderKind,121+ update: UsageLimitsUpdate,122+ since: number,123+ ) {124+ const nowMs = yield* Clock.currentTimeMillis;125+ const observedAt = DateTime.formatIso(DateTime.makeUnsafe(nowMs));126+ const instanceLabel = yield* sources.getInstanceLabel(instanceId);127+ const stamps = yield* Ref.get(windowStamps);128+ const fresh = update.windows.filter(129+ (window) => (stamps.get(stampKey(instanceId, window.id)) ?? 0) <= since,130+ );131+ yield* Ref.update(windowStamps, (map) => {132+ const next = new Map(map);133+ for (const window of fresh) next.set(stampKey(instanceId, window.id), nowMs);134+ return next;135+ });136+ yield* Ref.update(state, (map) => {137+ const previous = map.get(instanceId);138+ const windows = new Map((previous?.windows ?? []).map((window) => [window.id, window]));139+ for (const window of fresh) windows.set(window.id, window);
- apps/server/src/usage/UsageLimitsService.ts line 177Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +126,21 @@126+ since: number,127+ ) {128+ const nowMs = yield* Clock.currentTimeMillis;129+ const observedAt = DateTime.formatIso(DateTime.makeUnsafe(nowMs));130+ const instanceLabel = yield* sources.getInstanceLabel(instanceId);131+ yield* Ref.update(state, (map) => {132+ const previous = map.get(instanceId);133+ const fresh = update.windows.filter(134+ (window) => (previous?.stamps.get(window.id) ?? 0) <= since,135+ );136+ const windows = new Map(137+ (previous?.limits.windows ?? []).map((window) => [window.id, window]),138+ );139+ const stamps = new Map(previous?.stamps ?? []);140+ for (const window of fresh) {141+ windows.set(window.id, window);142+ stamps.set(window.id, nowMs);143+ }144+ const next = new Map(map);145+ next.set(instanceId, {146+ limits: {
- apps/server/src/usage/UsageLimitsService.ts line 183OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +163,21 @@163+ });164+ yield* PubSub.publish(changes, yield* snapshot);165+ });166+167+ const refreshInstance = Effect.fn("UsageLimitsService.refreshInstance")(function* (168+ instanceId: ProviderInstanceId,169+ ) {170+ const adapter = yield* sources.getAdapter(instanceId);171+ const provider = usageProviderFor(adapter.provider);172+ if (provider === null) {173+ // Re-pointed at a provider without limits: drop what the old one left.174+ const dropped = yield* Ref.modify(state, (map) => {175+ if (!map.has(instanceId)) return [false, map] as const;176+ const next = new Map(map);177+ next.delete(instanceId);178+ return [true, next] as const;179+ });180+ if (dropped) yield* PubSub.publish(changes, yield* snapshot);181+ return;182+ }183+ if (adapter.readAccountLimits === undefined) return;apps/server/src/usage/UsageLimitsService.ts line 134OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +114,21 @@114+ );115+116+ /**117+ * Merge a sparse update into one instance's limits and publish the result.118+ * `since` is when a read began: windows that an event touched after that119+ * moment keep the event's newer numbers. The stamp check and the write are120+ * one `Ref.update`, so concurrent applies cannot interleave between them.121+ */122+ const apply = Effect.fn("UsageLimitsService.apply")(function* (123+ instanceId: ProviderInstanceId,124+ provider: UsageProviderKind,125+ update: UsageLimitsUpdate,126+ since: number,127+ ) {128+ const nowMs = yield* Clock.currentTimeMillis;129+ const observedAt = DateTime.formatIso(DateTime.makeUnsafe(nowMs));130+ const instanceLabel = yield* sources.getInstanceLabel(instanceId);131+ yield* Ref.update(state, (map) => {132+ // An instance re-pointed at another provider starts from a clean slate.133+ const stored = map.get(instanceId);134+ const previous = stored?.limits.provider === provider ? stored : undefined;
- apps/server/src/usage/UsageLimitsService.ts line 187OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +167,21 @@167+ const refreshInstance = Effect.fn("UsageLimitsService.refreshInstance")(function* (168+ instanceId: ProviderInstanceId,169+ ) {170+ const adapter = yield* sources.getAdapter(instanceId);171+ const provider = usageProviderFor(adapter.provider);172+ if (provider === null) {173+ // Re-pointed at a provider without limits: drop what the old one left.174+ const dropped = yield* Ref.modify(state, (map) => {175+ if (!map.has(instanceId)) return [false, map] as const;176+ const next = new Map(map);177+ next.delete(instanceId);178+ return [true, next] as const;179+ });180+ if (dropped) yield* PubSub.publish(changes, yield* snapshot);181+ return;182+ }183+ if (adapter.readAccountLimits === undefined) return;184+ const startedAt = yield* Clock.currentTimeMillis;185+ const update = yield* adapter.readAccountLimits;186+ if (update === null) return;187+ yield* apply(instanceId, provider, update, startedAt);apps/server/src/usage/UsageLimitsService.ts line 157Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +121,21 @@121+ */122+ const apply = Effect.fn("UsageLimitsService.apply")(function* (123+ instanceId: ProviderInstanceId,124+ provider: UsageProviderKind,125+ update: UsageLimitsUpdate,126+ since: number,127+ ) {128+ const nowMs = yield* Clock.currentTimeMillis;129+ const observedAt = DateTime.formatIso(DateTime.makeUnsafe(nowMs));130+ const instanceLabel = yield* sources.getInstanceLabel(instanceId);131+ yield* Ref.update(state, (map) => {132+ // An instance re-pointed at another provider starts from a clean slate.133+ const stored = map.get(instanceId);134+ const previous = stored?.limits.provider === provider ? stored : undefined;135+ const fresh = update.windows.filter(136+ (window) => (previous?.stamps.get(window.id) ?? 0) <= since,137+ );138+ const windows = new Map(139+ (previous?.limits.windows ?? []).map((window) => [window.id, window]),140+ );141+ const stamps = new Map(previous?.stamps ?? []);
- apps/server/src/usage/UsageLimitsService.ts lines 134 to 136Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +110,21 @@110+ const snapshot: Effect.Effect<UsageLimitsSnapshot> = Ref.get(state).pipe(111+ Effect.map((map) => ({112+ providers: Array.from(map.values(), (entry) => entry.limits).toSorted(113+ (left, right) =>114+ left.provider.localeCompare(right.provider) ||115+ left.instanceId.localeCompare(right.instanceId),116+ ),117+ })),118+ );119+120+ /**121+ * Merge a sparse update into one instance's limits and publish the result.122+ * `since` is when a read began: windows that an event touched after that123+ * moment keep the event's newer numbers. The stamp check and the write are124+ * one `Ref.update`, so concurrent applies cannot interleave between them.125+ */126+ const apply = Effect.fn("UsageLimitsService.apply")(function* (127+ instanceId: ProviderInstanceId,128+ provider: UsageProviderKind,129+ update: UsageLimitsUpdate,130+ since: number,
Sign in to join this conversation.




macroscopeapp[bot](GitHub profile, opens in a new tab) reviewed