Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 20 additions & 7 deletions gui/src/quota-summary.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import type { AccountQuota } from "./codex-quota-utils";
import type { TKey } from "./i18n/en";
import { quotaWindows, resetTimestamp } from "./pages/tray-data";
import { accountQuotaFromReport, type ProviderQuotaReportView } from "./provider-workspace/report";
import { workBuddyExactRatio, type WorkBuddyCreditBalance } from "../../src/providers/workbuddy-credit-balance";

export const QUOTA_SUMMARY_WARN_PERCENT = 70;
export const QUOTA_SUMMARY_CRITICAL_PERCENT = 90;
Expand Down Expand Up @@ -64,14 +65,27 @@ function decimalRatio(value: number): [bigint, bigint] {
return scale >= 0 ? [digits, 10n ** BigInt(scale)] : [digits * 10n ** BigInt(-scale), 1n];
}

function roundedUnavailablePercent(total: number, remaining: number): number {
const [totalNumerator, totalDenominator] = decimalRatio(total);
const [remainingNumerator, remainingDenominator] = decimalRatio(Math.min(remaining, total));
/** Unavailable share as a whole percent, rounding an exact half up, from exact ratios. */
function roundedUnavailablePercent([totalNumerator, totalDenominator]: [bigint, bigint], [remainingNumerator, remainingDenominator]: [bigint, bigint]): number {
const denominator = totalNumerator * remainingDenominator;
const numerator = (denominator - remainingNumerator * totalDenominator) * 100n;
return Number((2n * numerator + denominator) / (2n * denominator));
}

/** Unavailable share of a WorkBuddy balance, or undefined when it cannot be shown. */
function workBuddyUnavailablePercent(credits: WorkBuddyCreditBalance): number | undefined {
const total = credits.exact && workBuddyExactRatio(credits.exact.total);
const remaining = credits.exact && workBuddyExactRatio(credits.exact.remaining);
if (total && remaining) {
// Exact sums carry no roundoff, so a remaining balance above the total is contradictory.
if (total[0] <= 0n || remaining[0] * total[1] > total[0] * remaining[1]) return undefined;
return roundedUnavailablePercent(total, remaining);
}
// The provider can sum up to 512 packages; tolerate only their accumulated roundoff.
if (!(credits.total > 0 && credits.remaining / credits.total <= 1 + Number.EPSILON * 1024)) return undefined;
return roundedUnavailablePercent(decimalRatio(credits.total), decimalRatio(Math.min(credits.remaining, credits.total)));
}

/** Long windows first: weekly is the default headline, then monthly, then 5h, then custom. */
const HEADLINE_ORDER: TKey[] = ["quota.weeklyLimit", "quota.monthlyLimit", "quota.fiveHourLimit"];

Expand Down Expand Up @@ -107,10 +121,9 @@ function summaryWindows(quota: AccountQuota): QuotaSummaryWindow[] {
});
}
const workbuddy = quota.workbuddyCredits;
// The provider can sum up to 512 packages; tolerate only their accumulated roundoff.
if (workbuddy && workbuddy.total > 0 && workbuddy.remaining / workbuddy.total <= 1 + Number.EPSILON * 1024) {
// Remaining is authoritative and includes frozen credits; the meter is informational.
const percent = roundedUnavailablePercent(workbuddy.total, workbuddy.remaining);
// Remaining is authoritative and includes frozen credits; the meter is informational.
const percent = workbuddy && workBuddyUnavailablePercent(workbuddy);
if (percent !== undefined) {
windows.push({
id: "quotaSummary.creditsUnavailable",
labelKey: "quotaSummary.creditsUnavailable",
Expand Down
17 changes: 17 additions & 0 deletions gui/tests/quota-summary.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,23 @@ describe("quota summary", () => {
expect(buildQuotaSummary(reports, name).map(row => formatQuotaPercent(row.headline.percent))).toEqual(["7%", "6%"]);
});

test("exact WorkBuddy decimals separate a below-half share from an exact tie after transport", () => {
const balance = (...remaining: string[]) => JSON.parse(JSON.stringify(parseWorkBuddyCredits({ Packages: remaining.map(value => ({
CycleTotalCapacity: "0.5", CycleUsedCapacity: "0", CycleRemainCapacity: value,
})) })));
const reports = freshQuotaReportsFromResponse([
{ provider: "below", updatedAt: now, quota: { updatedAt: now, workbuddyCredits: balance("0.4975", "0.49750000000000005") } },
{ provider: "tie", updatedAt: now, quota: { updatedAt: now, workbuddyCredits: balance("0.4975", "0.4975") } },
{ provider: "above", updatedAt: now, quota: { updatedAt: now, workbuddyCredits: balance("0.4975", "0.49749999999999995") } },
{ provider: "full", updatedAt: now, quota: { updatedAt: now, workbuddyCredits: balance("0.5", "0.5") } },
{ provider: "over-total", updatedAt: now, quota: { updatedAt: now, weeklyPercent: 25, workbuddyCredits: balance("0.5", "0.50000000000000001") } },
], now);
const rows = buildQuotaSummary(reports, name);
expect(rows.map(row => [row.provider, formatQuotaPercent(row.headline.percent)]))
.toEqual([["below", "0%"], ["tie", "1%"], ["above", "1%"], ["full", "0%"], ["over-total", "25%"]]);
expect(rows[4]!.windows.map(window => window.labelKey)).toEqual(["quota.weeklyLimit"]);
});

test("WorkBuddy rounds an exact half percent up and a smaller share down", () => {
const balance = (total: number, remaining: number) => ({ total, used: 0, remaining, frozen: 0, groups: [] });
const reports = freshQuotaReportsFromResponse([
Expand Down
8 changes: 6 additions & 2 deletions src/providers/quota/workbuddy.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import type { OAuthCredentials } from "../../oauth/types";
import { workBuddyApi, WorkBuddyApiError } from "../../oauth/workbuddy";
import { workBuddyHeaders } from "../workbuddy";
import { parseWorkBuddyCredits, remainingWorkBuddyCredits, workBuddyCapacity, workBuddyRecord, type WorkBuddyCreditBalance } from "../workbuddy-credit-balance";
import { parseWorkBuddyCredits, remainingWorkBuddyCredits, workBuddyCapacity, workBuddyExactCredits, workBuddyRecord, type WorkBuddyCreditBalance } from "../workbuddy-credit-balance";
import { REQUEST_TIMEOUT_MS } from "../quota-wire";
import { TERMINAL_QUOTA_FAILURE, type ProviderQuotaProbeResult } from "./report-cache";

Expand Down Expand Up @@ -56,6 +56,7 @@ async function expiringCredits(summary: Record<string, unknown>, headers: Record
return workBuddyExpiringCredits(lists.flat(), new Set(codes), now);
}

/** Display-only credit balance for one account; the enterprise meter fills an empty personal summary. */
export async function fetchWorkBuddyQuota(provider: string, credential: OAuthCredentials): Promise<ProviderQuotaProbeResult> {
if (!credential.workbuddy) return null;
const signal = AbortSignal.timeout(REQUEST_TIMEOUT_MS), now = Date.now();
Expand All @@ -67,7 +68,10 @@ export async function fetchWorkBuddyQuota(provider: string, credential: OAuthCre
const team = await workBuddyApi("/billing/meter/get-enterprise-user-usage", headers, signal, true);
const total = workBuddyCapacity(team.limitNum), used = workBuddyCapacity(team.credit);
if (total === undefined || used === undefined) return null;
credits = { total, used, remaining: remainingWorkBuddyCredits(total, used), frozen: 0, groups: [] };
const exact = workBuddyExactCredits(team.limitNum, team.credit);
credits = exact
? { total: Number(exact.total), used, remaining: Number(exact.remaining), frozen: 0, groups: [], exact }
: { total, used, remaining: remainingWorkBuddyCredits(total, used), frozen: 0, groups: [] };
}
if (!credits) return null;
if (credits.remaining > 0) {
Expand Down
141 changes: 125 additions & 16 deletions src/providers/workbuddy-credit-balance.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,18 @@ export interface WorkBuddyCreditAmount {
export const WORKBUDDY_CREDIT_KINDS = ["plan_base", "plan_bonus", "addon", "benefit", "other"] as const;
export type WorkBuddyCreditKind = typeof WORKBUDDY_CREDIT_KINDS[number];

/** Plain decimal text (no sign or exponent) of a validated, bounded credit amount. */
export interface WorkBuddyExactCredits {
total: string;
remaining: string;
}

/** Display-only credits; they are neither USD nor provider-wide model eligibility. */
export interface WorkBuddyCreditBalance extends WorkBuddyCreditAmount {
groups: Array<WorkBuddyCreditAmount & { kind: WorkBuddyCreditKind }>;
expiring?: { amount: number; at: number };
/** Optional exact companions of `total` and `remaining`; the numeric fields stay the contract. */
exact?: WorkBuddyExactCredits;
}

export function workBuddyRecord(value: unknown): Record<string, unknown> {
Expand All @@ -24,19 +32,69 @@ export function workBuddyCapacity(value: unknown): number | undefined {
return Number.isFinite(number) && number >= 0 && number <= Number.MAX_SAFE_INTEGER ? number : undefined;
}

interface Decimal { digits: bigint; scale: number }

const ZERO: Decimal = { digits: 0n, scale: 0 };
// Exact metadata bounds: balances above MAX_SAFE_INTEGER (16 digits) are already rejected.
const EXACT_TEXT = /^(\d{1,16})(?:\.(\d{1,32}))?$/;
const EXACT_SCALE = 32;

/** Decimal value of a number's shortest round-trip text, as the summed capacities always used. */
function numberDecimal(value: number): Decimal {
const [coefficient, exponent = "0"] = value.toString().split("e");
const [whole, fraction = ""] = coefficient!.split(".");
let digits = BigInt(`${whole}${fraction}`);
let scale = fraction.length - Number(exponent);
if (scale < 0) { digits *= 10n ** BigInt(-scale); scale = 0; }
return { digits, scale };
}

/** Bounded plain decimal text as digits and scale; signs, exponents and spaces are refused. */
function textDecimal(text: string): Decimal | undefined {
const match = EXACT_TEXT.exec(text);
return match ? { digits: BigInt(`${match[1]}${match[2] ?? ""}`), scale: match[2]?.length ?? 0 } : undefined;
}

/**
* Exact value of a validated capacity: quoted decimals keep their text, and numbers (already
* rounded by JSON.parse) use their shortest decimal. Values outside the bounds, such as subnormal
* numbers or long quoted fractions, have no exact form and leave only the numeric projection.
*/
function exactCapacity(value: unknown): Decimal | undefined {
if (workBuddyCapacity(value) === undefined) return undefined;
const decimal = typeof value === "string" ? textDecimal(value) : numberDecimal(value as number);
return decimal && decimal.scale <= EXACT_SCALE ? decimal : undefined;
}

/** Exact sum, aligned to the largest scale among the values. */
function addDecimals(values: readonly Decimal[]): Decimal {
const scale = Math.max(0, ...values.map(value => value.scale));
return { digits: values.reduce((sum, value) => sum + value.digits * 10n ** BigInt(scale - value.scale), 0n), scale };
}

function decimalNumber(value: Decimal): number {
return Number(`${value.digits}e-${value.scale}`);
}

/** Canonical plain text without trailing fractional zeros; undefined outside the exact bounds. */
function decimalText(value: Decimal): string | undefined {
if (value.digits < 0n) return undefined;
let { digits, scale } = value;
while (scale > 0 && digits % 10n === 0n) { digits /= 10n; scale--; }
const raw = digits.toString().padStart(scale + 1, "0");
const text = scale ? `${raw.slice(0, -scale)}.${raw.slice(-scale)}` : raw;
return textDecimal(text) ? text : undefined;
}

/** Exact `[numerator, denominator]` of bounded exact text, for display rounding. */
export function workBuddyExactRatio(text: string): [bigint, bigint] | undefined {
const value = textDecimal(text);
return value && [value.digits, 10n ** BigInt(value.scale)];
}

/** Sum bounded numeric capacities as decimals before converting the result back to a number. */
function sumCapacities(values: readonly number[]): number {
const parts = values.map(value => {
const [coefficient, exponent = "0"] = value.toString().split("e");
const [whole, fraction = ""] = coefficient!.split(".");
let digits = BigInt(`${whole}${fraction}`);
let scale = fraction.length - Number(exponent);
if (scale < 0) { digits *= 10n ** BigInt(-scale); scale = 0; }
return { digits, scale };
});
const scale = Math.max(0, ...parts.map(part => part.scale));
const digits = parts.reduce((sum, part) => sum + part.digits * 10n ** BigInt(scale - part.scale), 0n);
return Number(`${digits}e-${scale}`);
return decimalNumber(addDecimals(values.map(numberDecimal)));
}

function sumAmounts(rows: readonly WorkBuddyCreditAmount[]): WorkBuddyCreditAmount {
Expand All @@ -53,6 +111,29 @@ export function remainingWorkBuddyCredits(total: number, used: number, frozen =
return Math.max(0, sumCapacities([total, -used, -frozen]));
}

/** Exact remaining credits when the provider omits them, bounded below by zero. */
function exactRemaining(total: Decimal, used: Decimal, frozen: Decimal): Decimal {
const remaining = addDecimals([total, { ...used, digits: -used.digits }, { ...frozen, digits: -frozen.digits }]);
return remaining.digits < 0n ? ZERO : remaining;
}

/** Exact total/remaining for raw amounts, or undefined when any lacks a bounded exact form. */
export function workBuddyExactCredits(total: unknown, used: unknown): WorkBuddyExactCredits | undefined {
const exactTotal = exactCapacity(total), exactUsed = exactCapacity(used);
if (!exactTotal || !exactUsed) return undefined;
const totalText = decimalText(exactTotal), remainingText = decimalText(exactRemaining(exactTotal, exactUsed, ZERO));
return totalText !== undefined && remainingText !== undefined ? { total: totalText, remaining: remainingText } : undefined;
}

/** Exact text must be bounded plain decimal text encoding the same numeric fields; null rejects. */
function exactCredits(value: unknown, balance: WorkBuddyCreditAmount): WorkBuddyExactCredits | undefined | null {
if (value === undefined) return undefined;
const row = workBuddyRecord(value), { total, remaining } = row;
if (Object.keys(row).length !== 2 || typeof total !== "string" || typeof remaining !== "string") return null;
if (!textDecimal(total) || !textDecimal(remaining)) return null;
return Number(total) === balance.total && Number(remaining) === balance.remaining ? { total, remaining } : null;
}

function amount(value: unknown): WorkBuddyCreditAmount | undefined {
const row = workBuddyRecord(value);
const total = workBuddyCapacity(row.total), used = workBuddyCapacity(row.used);
Expand All @@ -73,29 +154,57 @@ export function normalizeWorkBuddyCredits(value: unknown): WorkBuddyCreditBalanc
if (!quantities || !kind || seen.has(kind)) return undefined;
seen.add(kind); groups.push({ kind, ...quantities });
}
const exact = exactCredits(row.exact, balance);
if (exact === null) return undefined;
const expiring = workBuddyRecord(row.expiring), quantity = workBuddyCapacity(expiring.amount);
const at = typeof expiring.at === "number" && expiring.at > 0 && Number.isFinite(new Date(expiring.at).getTime()) ? expiring.at : undefined;
return { ...balance, groups, ...(quantity !== undefined && quantity > 0 && at !== undefined ? { expiring: { amount: quantity, at } } : {}) };
return { ...balance, groups, ...(exact ? { exact } : {}),
...(quantity !== undefined && quantity > 0 && at !== undefined ? { expiring: { amount: quantity, at } } : {}) };
}

function packageAmount(row: Record<string, unknown>): WorkBuddyCreditAmount | undefined {
interface PackageAmount extends WorkBuddyCreditAmount { exact?: { total: Decimal; remaining: Decimal } }

/** One summary package or credit group, with exact total/remaining when both have a bounded form. */
function packageAmount(row: Record<string, unknown>): PackageAmount | undefined {
const total = workBuddyCapacity(row.CycleTotalCapacity), used = workBuddyCapacity(row.CycleUsedCapacity);
const frozen = row.CycleFrozenCapacity === undefined ? 0 : workBuddyCapacity(row.CycleFrozenCapacity);
if (total === undefined || used === undefined || frozen === undefined) return undefined;
const remaining = row.CycleRemainCapacity === undefined ? remainingWorkBuddyCredits(total, used, frozen) : workBuddyCapacity(row.CycleRemainCapacity);
return remaining === undefined ? undefined : { total, used, remaining, frozen };
const estimated = row.CycleRemainCapacity === undefined;
const remaining = estimated ? remainingWorkBuddyCredits(total, used, frozen) : workBuddyCapacity(row.CycleRemainCapacity);
if (remaining === undefined) return undefined;
const exactTotal = exactCapacity(row.CycleTotalCapacity);
let exactLeft: Decimal | undefined;
if (!estimated) exactLeft = exactCapacity(row.CycleRemainCapacity);
else {
const exactUsed = exactCapacity(row.CycleUsedCapacity);
const exactFrozen = row.CycleFrozenCapacity === undefined ? ZERO : exactCapacity(row.CycleFrozenCapacity);
if (exactTotal && exactUsed && exactFrozen) exactLeft = exactRemaining(exactTotal, exactUsed, exactFrozen);
}
return { total, used, remaining, frozen, ...(exactTotal && exactLeft ? { exact: { total: exactTotal, remaining: exactLeft } } : {}) };
}

/** Exact package sums, present only when every package has bounded exact amounts. */
function sumExact(rows: readonly PackageAmount[]): WorkBuddyExactCredits | undefined {
if (rows.some(row => !row.exact)) return undefined;
const total = decimalText(addDecimals(rows.map(row => row.exact!.total)));
const remaining = decimalText(addDecimals(rows.map(row => row.exact!.remaining)));
return total !== undefined && remaining !== undefined ? { total, remaining } : undefined;
}

/** Balance from the resource summary: Packages summed once, CreditGroups as a breakdown. */
export function parseWorkBuddyCredits(value: unknown): WorkBuddyCreditBalance | undefined {
const summary = workBuddyRecord(value);
if (!Array.isArray(summary.Packages) || summary.Packages.length > 512) return undefined;
const packages: WorkBuddyCreditAmount[] = [];
const packages: PackageAmount[] = [];
for (const raw of summary.Packages) {
const quantities = packageAmount(workBuddyRecord(raw));
if (!quantities) return undefined;
packages.push(quantities);
}
const balance: WorkBuddyCreditBalance = { ...sumAmounts(packages), groups: [] };
const exact = sumExact(packages);
// The numeric fields are the nearest numbers to the exact sums, which normalization re-checks.
if (exact) Object.assign(balance, { total: Number(exact.total), remaining: Number(exact.remaining), exact });
// CreditGroups is a breakdown of Packages, not another balance to add to it.
if (Array.isArray(summary.CreditGroups) && summary.CreditGroups.length <= 16) {
const grouped = new Map<WorkBuddyCreditKind, WorkBuddyCreditAmount[]>();
Expand Down
12 changes: 10 additions & 2 deletions structure/providers/workbuddy.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,8 +52,16 @@ probe/cache path supplies refresh, paused-account exclusion, stale-reading and 4
semantics. Unknown or malformed summaries never become zero. Explicit zero balances remain visible.
`workbuddyCredits` is a display-only field in the quota DTO, separate from USD balances and
quota windows, so credit exhaustion does not disable free models or influence account ranking.
`src/providers/workbuddy-credit-balance.ts` validates the numeric-only public projection for the
GUI. The shared provider quota panel shows the remaining credits, usage, group balances and
`src/providers/workbuddy-credit-balance.ts` validates the numeric public projection for the GUI.
An optional `exact` pair carries plain decimal text for `total` and `remaining`: quoted
summary or enterprise values keep their text (unquoted numbers are already rounded by
`JSON.parse` and use their shortest decimal), at most 16 integer and 32 fractional digits.
Any input outside those bounds, including subnormal numbers, omits the pair and leaves the
numeric fields alone; numeric-only payloads stay valid. When present, the numeric fields are
the nearest numbers to the exact text, and normalization rejects a balance whose pair is
malformed, unbounded or encodes different numbers. The header quota bar rounds the
unavailable share from the exact pair when present, so a share just below one half percent
stays distinct from an exact tie; the pair never reaches routing or account eligibility. The shared provider quota panel shows the remaining credits, usage, group balances and
optional expiry; the existing refresh and stale-state controls apply to it.

## Verification
Expand Down
Loading
Loading