Skip to content
101 changes: 101 additions & 0 deletions apps/server/src/usage/UsageLimitSources.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,107 @@ it.effect("reads a management key from its secret provider", () => {
);
});

it.effect("keeps an account's last good reading when the hub's next read of it is refused", () => {
let refused = true;
let workspace = "account-a";
let listsIdentity = true;
const readAccount = Effect.gen(function* () {
const sources = yield* UsageLimitSources.make;
return Effect.gen(function* () {
yield* sources.refresh;
const [source] = yield* sources.current;
return source?.accounts[0]?.usageLimits;
});
});
return Effect.gen(function* () {
const read = yield* readAccount;
// Nothing to keep yet: the account stays listed as unreadable.
expect(yield* read).toMatchObject({ windows: [], unavailable: { reason: "probeFailed" } });
refused = false;
const good = yield* read;
expect(good?.windows.map((window) => window.usedPercent)).toEqual([78]);
expect(good?.unavailable).toBeUndefined();
refused = true;
expect(yield* read).toEqual(good);
// The same auth file now holds another login, whose reading is unknown.
workspace = "account-b";
expect(yield* read).toMatchObject({ windows: [], unavailable: { reason: "probeFailed" } });
// A file that lists no login cannot show whether the next one is the same.
listsIdentity = false;
refused = false;
yield* read;
refused = true;
expect(yield* read).toMatchObject({ windows: [], unavailable: { reason: "probeFailed" } });
}).pipe(
Effect.provide([
ServerSettings.layerTest({
usageLimitSources: {
[UsageLimitSourceId.make("hub")]: {
kind: "cliproxy",
url: "http://hub.test:8317",
managementKey: "management-secret",
enabled: true,
},
},
}),
Layer.mock(BackgroundPolicy.BackgroundPolicy)({
shouldRunScopeWork: () => Effect.succeed(false),
}),
Layer.succeed(SecretResolver.SecretResolver, {
label: (provider) => Effect.succeed(provider),
read: (references) => Effect.succeed(references.map(() => undefined)),
invalidate: () => Effect.void,
}),
Layer.succeed(
HttpClient.HttpClient,
HttpClient.make((request) =>
Effect.sync(() => {
if (new URL(request.url).pathname.endsWith("/auth-files")) {
return HttpClientResponse.fromWeb(
request,
Response.json({
files: [
{
id: "first.json",
auth_index: "a",
provider: "codex",
...(listsIdentity
? {
email: "first@example.com",
id_token: { chatgpt_account_id: workspace },
}
: {}),
},
],
}),
);
}
const usage = {
plan_type: "pro",
rate_limit: {
secondary_window: {
used_percent: 78,
reset_at: 4070908800,
limit_window_seconds: 604800,
},
},
};
return HttpClientResponse.fromWeb(
request,
Response.json(
refused
? { status_code: 429, body: "{}" }
: { status_code: 200, body: JSON.stringify(usage) },
),
);
}),
),
),
NodeCrypto.layer,
]),
);
});

const NOW = Date.parse("2026-11-13T12:00:00.000Z");
const at = (hours: number) => DateTime.formatIso(DateTime.makeUnsafe(NOW + hours * 3_600_000));
const spent = (id: string, hours: number): ServerProviderUsageWindow => ({
Expand Down
38 changes: 37 additions & 1 deletion apps/server/src/usage/UsageLimitSources.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,41 @@ function sourceLabel(id: string, config: UsageLimitSourceConfig): string {
}
}

/**
* A refused read of one account keeps its last good reading, as provider probes keep their bars
* (see ServerProviderUsageLimits); a reading with none to keep stays listed as unreadable.
*/
function keepLastGoodReadings(
previous: ReadonlyArray<UsageLimitSourceSnapshot>,
next: ReadonlyArray<UsageLimitSourceSnapshot>,
): ReadonlyArray<UsageLimitSourceSnapshot> {
return next.map((source) => {
// Auth file names can be reused, so only the same hub and login may lend a reading.
const before = previous.find(
(candidate) => candidate.id === source.id && candidate.endpoint === source.endpoint,
);
if (!before) return source;
return {
...source,
accounts: source.accounts.map((account) => {
if (account.usageLimits.unavailable?.reason !== "probeFailed") return account;
// Without a listed login, a reused auth file name cannot be told apart from the old one.
if (account.email === undefined && account.workspaceId === undefined) return account;
const last = before.accounts.find(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟠 High usage/UsageLimitSources.ts:70

A failed probe can display another account’s identity, usage bars, and reset-credit action under the current hub. This lookup matches only the auth-file id and driver, so changing the source URL or replacing the account can still reuse the old snapshot; require the endpoint and available account identity to match before retaining it.

🤖 Copy this AI Prompt to have your agent fix this:
In file @apps/server/src/usage/UsageLimitSources.ts around line 70:

A failed probe can display another account’s identity, usage bars, and reset-credit action under the current hub. This lookup matches only the auth-file `id` and `driver`, so changing the source URL or replacing the account can still reuse the old snapshot; require the endpoint and available account identity to match before retaining it.

(candidate) =>
candidate.id === account.id &&
candidate.driver === account.driver &&
// Fingerprinted Antigravity readings omit the listed identity, so they are never lent.
candidate.usageLimits.credentialFingerprint === undefined &&
candidate.email === account.email &&
candidate.workspaceId === account.workspaceId,
);
return last && !last.usageLimits.unavailable ? last : account;
}),
};
});
}

function missingManagementKey(config: UsageLimitSourceConfig): string {
return typeof config.managementKey === "string"
? "No management key configured."
Expand Down Expand Up @@ -131,7 +166,7 @@ export const make = Effect.gen(function* () {
([id, config]) => readSource(id as UsageLimitSourceId, config),
{ concurrency: 4 },
);
yield* publish(snapshots);
yield* publish(keepLastGoodReadings(yield* Ref.get(stateRef), snapshots));
}).pipe(refreshLock.withPermits(1), Effect.ignoreCause({ log: true }));

// Shares the refresh lock so a stale in-flight read cannot overwrite a redemption.
Expand All @@ -156,6 +191,7 @@ export const make = Effect.gen(function* () {
input.accountId,
input.creditId,
);
// A redemption changes the reading, so a refused re-read must not bring back the one before it.
const snapshot = yield* readSource(input.sourceId, config);
const previous = yield* Ref.get(stateRef);
yield* publish(previous.map((source) => (source.id === input.sourceId ? snapshot : source)));
Expand Down
Loading