diff --git a/docs-site/src/content/docs/guides/providers.md b/docs-site/src/content/docs/guides/providers.md index d28873ac404..2419415a450 100644 --- a/docs-site/src/content/docs/guides/providers.md +++ b/docs-site/src/content/docs/guides/providers.md @@ -1404,6 +1404,10 @@ WorkBuddy's Chat endpoint. The Overview and Accounts tabs show remaining credits balances, and the next expiring non-daily credits when available. Refresh reads the signed-in account's billing summary; an unavailable read is not a zero balance. These credits are informational and do not disable free models when paid credits run out. +When the reported total is positive, the header quota summary shows the unavailable percentage, +including frozen credits, rounded to the nearest whole percent. It gives no exhaustion warning: +free models may still work. An individual +credit expiry is not shown as a reset of the entire balance. This uses an unofficial subscription protocol based on [Magpie's WorkBuddy plugin](https://github.com/magpie-community/plugins/tree/e7f65641df820dfd715c0d2241f99f2092e4efb1/packages/workbuddy). diff --git a/docs-site/src/content/docs/zh-cn/guides/providers.md b/docs-site/src/content/docs/zh-cn/guides/providers.md index 4cbf796c7fb..d6db5751079 100644 --- a/docs-site/src/content/docs/zh-cn/guides/providers.md +++ b/docs-site/src/content/docs/zh-cn/guides/providers.md @@ -201,6 +201,8 @@ Kiro 登录需要 Kiro CLI:Unix 使用 `curl -fsSL https://cli.kiro.dev/instal `workbuddy-ai/default-model`。支持流式输出、工具调用和非流式客户端;概览和账户页显示剩余积分、已用/总量、基础及赠送积分, 并在可查询时显示下一批非每日积分的到期时间。刷新读取当前账户的账单汇总;查询失败不会 显示为零。积分仅用于展示,不会因付费积分耗尽而禁用仍可用的免费模型。 +报告的积分总量大于零时,顶部配额摘要会显示不可用积分的百分比(包括冻结积分),四舍五入 +到整数。它不会显示耗尽警告,因为免费模型可能仍可使用。单批积分到期不会被显示为整个余额的重置时间。 这是参考 [Magpie WorkBuddy 插件](https://github.com/magpie-community/plugins/tree/e7f65641df820dfd715c0d2241f99f2092e4efb1/packages/workbuddy) 实现的非官方订阅协议。上游的客户端通道或账号限制会原样拒绝请求,不会改写代理身份提示词 diff --git a/gui/src/components/quota-summary-bar/QuotaSummaryBar.tsx b/gui/src/components/quota-summary-bar/QuotaSummaryBar.tsx index b56f7fc2469..bb0af453ef0 100644 --- a/gui/src/components/quota-summary-bar/QuotaSummaryBar.tsx +++ b/gui/src/components/quota-summary-bar/QuotaSummaryBar.tsx @@ -209,6 +209,9 @@ function QuotaSummaryItem({ row, t, locale }: { row: QuotaSummaryRow; t: TFn; lo onClick={onClick} > {row.label} + {headline.labelKey === "quotaSummary.creditsUnavailable" && ( + {t("quotaSummary.creditsUnavailable")} + )} {formatQuotaPercent(headline.percent)} {row.provider === "meta-muse" && headline.resetAt !== undefined && ( diff --git a/gui/src/i18n/de.ts b/gui/src/i18n/de.ts index 855aad80b86..83b052a02b5 100644 --- a/gui/src/i18n/de.ts +++ b/gui/src/i18n/de.ts @@ -4231,6 +4231,7 @@ export const de: Record = { "quotaSummary.warn": "Über 70 % genutzt", "quotaSummary.critical": "Über 90 % genutzt", "quotaSummary.credits": "Guthaben", + "quotaSummary.creditsUnavailable": "Nicht verfügbares Guthaben", "quotaSummary.refreshFailed": "Letzte Aktualisierung fehlgeschlagen; vorheriger Stand wird angezeigt", "quotaSummary.scrollPrev": "Anbieter nach links scrollen", "quotaSummary.scrollNext": "Anbieter nach rechts scrollen", diff --git a/gui/src/i18n/en.ts b/gui/src/i18n/en.ts index 93c33a27e9d..c21ce007931 100644 --- a/gui/src/i18n/en.ts +++ b/gui/src/i18n/en.ts @@ -4265,6 +4265,7 @@ export const en = { "quotaSummary.warn": "70%+ used", "quotaSummary.critical": "90%+ used", "quotaSummary.credits": "Credits", + "quotaSummary.creditsUnavailable": "Unavailable credits", "quotaSummary.refreshFailed": "Last refresh failed; showing the previous reading", "quotaSummary.scrollPrev": "Scroll providers left", "quotaSummary.scrollNext": "Scroll providers right", diff --git a/gui/src/i18n/fr.ts b/gui/src/i18n/fr.ts index 4bac4fb5bdb..b500c155e13 100644 --- a/gui/src/i18n/fr.ts +++ b/gui/src/i18n/fr.ts @@ -4220,6 +4220,7 @@ export const fr: Record = { "quotaSummary.warn": "Plus de 70 % utilisés", "quotaSummary.critical": "Plus de 90 % utilisés", "quotaSummary.credits": "Crédits", + "quotaSummary.creditsUnavailable": "Crédits indisponibles", "quotaSummary.refreshFailed": "Échec de la dernière actualisation ; affichage de la lecture précédente", "quotaSummary.scrollPrev": "Faire défiler les fournisseurs vers la gauche", "quotaSummary.scrollNext": "Faire défiler les fournisseurs vers la droite", diff --git a/gui/src/i18n/ja.ts b/gui/src/i18n/ja.ts index e17c94b7f89..d6fe9c42268 100644 --- a/gui/src/i18n/ja.ts +++ b/gui/src/i18n/ja.ts @@ -4253,6 +4253,7 @@ export const ja: Record = { "quotaSummary.warn": "70%以上使用", "quotaSummary.critical": "90%以上使用", "quotaSummary.credits": "クレジット", + "quotaSummary.creditsUnavailable": "利用できないクレジット", "quotaSummary.refreshFailed": "最新の更新に失敗しました。前回の値を表示しています", "quotaSummary.scrollPrev": "プロバイダーを左へスクロール", "quotaSummary.scrollNext": "プロバイダーを右へスクロール", diff --git a/gui/src/i18n/ko.ts b/gui/src/i18n/ko.ts index bab550b094b..dfcc4af6fd2 100644 --- a/gui/src/i18n/ko.ts +++ b/gui/src/i18n/ko.ts @@ -4253,6 +4253,7 @@ export const ko: Record = { "quotaSummary.warn": "70% 이상 사용", "quotaSummary.critical": "90% 이상 사용", "quotaSummary.credits": "크레딧", + "quotaSummary.creditsUnavailable": "사용할 수 없는 크레딧", "quotaSummary.refreshFailed": "최근 갱신에 실패해 이전 값을 표시합니다", "quotaSummary.scrollPrev": "프로바이더 목록 왼쪽으로", "quotaSummary.scrollNext": "프로바이더 목록 오른쪽으로", diff --git a/gui/src/i18n/pt.ts b/gui/src/i18n/pt.ts index 2f8c7b96c62..b07372a9ada 100644 --- a/gui/src/i18n/pt.ts +++ b/gui/src/i18n/pt.ts @@ -4226,6 +4226,7 @@ export const pt: Record = { "quotaSummary.warn": "70%+ usado", "quotaSummary.critical": "90%+ usado", "quotaSummary.credits": "Créditos", + "quotaSummary.creditsUnavailable": "Créditos indisponíveis", "quotaSummary.refreshFailed": "A última atualização falhou; exibindo a leitura anterior", "quotaSummary.scrollPrev": "Rolar provedores para a esquerda", "quotaSummary.scrollNext": "Rolar provedores para a direita", diff --git a/gui/src/i18n/ru.ts b/gui/src/i18n/ru.ts index 132bf0e533e..84813688b8c 100644 --- a/gui/src/i18n/ru.ts +++ b/gui/src/i18n/ru.ts @@ -4254,6 +4254,7 @@ export const ru: Record = { "quotaSummary.warn": "Использовано более 70%", "quotaSummary.critical": "Использовано более 90%", "quotaSummary.credits": "Кредиты", + "quotaSummary.creditsUnavailable": "Недоступные кредиты", "quotaSummary.refreshFailed": "Последнее обновление не удалось; показаны предыдущие данные", "quotaSummary.scrollPrev": "Прокрутить провайдеров влево", "quotaSummary.scrollNext": "Прокрутить провайдеров вправо", diff --git a/gui/src/i18n/tr.ts b/gui/src/i18n/tr.ts index db0256de5cf..c2dd8ce4ce6 100644 --- a/gui/src/i18n/tr.ts +++ b/gui/src/i18n/tr.ts @@ -4254,6 +4254,7 @@ export const tr: Record = { "quotaSummary.warn": "%70+ kullanıldı", "quotaSummary.critical": "%90+ kullanıldı", "quotaSummary.credits": "Krediler", + "quotaSummary.creditsUnavailable": "Kullanılamayan krediler", "quotaSummary.refreshFailed": "Son yenileme başarısız; önceki değer gösteriliyor", "quotaSummary.scrollPrev": "Sağlayıcıları sola kaydır", "quotaSummary.scrollNext": "Sağlayıcıları sağa kaydır", diff --git a/gui/src/i18n/vi.ts b/gui/src/i18n/vi.ts index e2efd284495..f3d00986843 100644 --- a/gui/src/i18n/vi.ts +++ b/gui/src/i18n/vi.ts @@ -4223,6 +4223,7 @@ export const vi: Record = { "quotaSummary.warn": "Đã dùng trên 70%", "quotaSummary.critical": "Đã dùng trên 90%", "quotaSummary.credits": "Tín dụng", + "quotaSummary.creditsUnavailable": "Tín dụng không khả dụng", "quotaSummary.refreshFailed": "Lần làm mới gần nhất thất bại; đang hiển thị số liệu trước đó", "quotaSummary.scrollPrev": "Cuộn nhà cung cấp sang trái", "quotaSummary.scrollNext": "Cuộn nhà cung cấp sang phải", diff --git a/gui/src/i18n/zh-TW.ts b/gui/src/i18n/zh-TW.ts index f6bfa5ab864..4f72eb16f81 100644 --- a/gui/src/i18n/zh-TW.ts +++ b/gui/src/i18n/zh-TW.ts @@ -4217,6 +4217,7 @@ export const zhTW: Record = { "quotaSummary.warn": "已用 70% 以上", "quotaSummary.critical": "已用 90% 以上", "quotaSummary.credits": "額度", + "quotaSummary.creditsUnavailable": "不可用額度", "quotaSummary.refreshFailed": "最近一次重新整理失敗,顯示上次資料", "quotaSummary.scrollPrev": "向左捲動供應商", "quotaSummary.scrollNext": "向右捲動供應商", diff --git a/gui/src/i18n/zh.ts b/gui/src/i18n/zh.ts index aa3a52e8191..f6e082be7e9 100644 --- a/gui/src/i18n/zh.ts +++ b/gui/src/i18n/zh.ts @@ -4252,6 +4252,7 @@ export const zh: Record = { "quotaSummary.warn": "已用 70% 以上", "quotaSummary.critical": "已用 90% 以上", "quotaSummary.credits": "额度", + "quotaSummary.creditsUnavailable": "不可用额度", "quotaSummary.refreshFailed": "最近一次刷新失败,显示上次数据", "quotaSummary.scrollPrev": "向左滚动提供商", "quotaSummary.scrollNext": "向右滚动提供商", diff --git a/gui/src/quota-summary.ts b/gui/src/quota-summary.ts index 3e7ec861426..5ddaa39db33 100644 --- a/gui/src/quota-summary.ts +++ b/gui/src/quota-summary.ts @@ -51,6 +51,23 @@ export function formatQuotaPercent(percent: number | undefined): string { return finite(percent) ? `${Math.floor(percent)}%` : "-"; } +/** Interpret the reported decimal numbers exactly when rounding an informational balance. */ +function decimalRatio(value: number): [bigint, bigint] { + const [coefficient, exponent = "0"] = value.toString().split("e"); + const [whole, fraction = ""] = coefficient!.split("."); + const digits = BigInt(`${whole}${fraction}`); + const scale = fraction.length - Number(exponent); + 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)); + const denominator = totalNumerator * remainingDenominator; + const numerator = (denominator - remainingNumerator * totalDenominator) * 100n; + return Number((2n * numerator + denominator) / (2n * denominator)); +} + /** Long windows first: weekly is the default headline, then monthly, then 5h, then custom. */ const HEADLINE_ORDER: TKey[] = ["quota.weeklyLimit", "quota.monthlyLimit", "quota.fiveHourLimit"]; @@ -81,6 +98,18 @@ function summaryWindows(quota: AccountQuota): QuotaSummaryWindow[] { severity: quotaSeverity(credits.percent), }); } + 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); + windows.push({ + id: "quotaSummary.creditsUnavailable", + labelKey: "quotaSummary.creditsUnavailable", + percent, + severity: "normal", + }); + } // Credits are appended after provider windows, whose labels can equal any fixed id. const used = new Set(); return windows.map(window => { diff --git a/gui/tests/quota-summary-bar.test.tsx b/gui/tests/quota-summary-bar.test.tsx index 466b2370f9b..13b69efc6b4 100644 --- a/gui/tests/quota-summary-bar.test.tsx +++ b/gui/tests/quota-summary-bar.test.tsx @@ -37,14 +37,14 @@ const rows = buildQuotaSummary(freshQuotaReportsFromResponse([ { provider: "kimi", label: "Kimi", updatedAt: now, quota: { weeklyPercent: 31, updatedAt: now } }, ], now), provider => provider); -async function mount() { +async function mount(renderRows = rows) { const container = document.createElement("div"); document.body.append(container); const { createRoot } = await import("react-dom/client"); let root!: Root; await act(async () => { root = createRoot(container); - root.render(); + root.render(); }); const list = container.querySelector("ul")!; return { @@ -57,6 +57,29 @@ async function mount() { }; } +test("WorkBuddy chip names unavailable credits so frozen funds are not called used", async () => { + const workbuddy = buildQuotaSummary(freshQuotaReportsFromResponse([ + { provider: "workbuddy-ai", label: "WorkBuddy AI", updatedAt: now, quota: { + updatedAt: now, workbuddyCredits: { total: 100, used: 0, remaining: 0, frozen: 100, groups: [] }, + } }, + ], now), provider => provider); + const view = await mount(workbuddy); + expect(view.chip("WorkBuddy AI").textContent).toContain("quotaSummary.creditsUnavailable"); + expect(view.chip("WorkBuddy AI").textContent).toContain("100%"); + await view.unmount(); +}); + +test("WorkBuddy chip rounds its informational percentage to the nearest whole number", async () => { + const workbuddy = buildQuotaSummary(freshQuotaReportsFromResponse([ + { provider: "workbuddy-ai", label: "WorkBuddy AI", updatedAt: now, quota: { + updatedAt: now, workbuddyCredits: { total: 100, used: 89.6, remaining: 10.4, frozen: 0, groups: [] }, + } }, + ], now), provider => provider); + const view = await mount(workbuddy); + expect(view.chip("WorkBuddy AI").textContent).toContain("90%"); + await view.unmount(); +}); + async function click(element: Element) { await act(async () => { element.dispatchEvent(new testWindow.MouseEvent("click", { bubbles: true, cancelable: true, button: 0 }) as unknown as Event); diff --git a/gui/tests/quota-summary.test.ts b/gui/tests/quota-summary.test.ts index c4cff2fbb8b..58099679744 100644 --- a/gui/tests/quota-summary.test.ts +++ b/gui/tests/quota-summary.test.ts @@ -1,6 +1,7 @@ import { describe, expect, test } from "bun:test"; import { buildQuotaSummary, formatQuotaPercent, quotaSeverity } from "../src/quota-summary"; import { accountQuotaFromReport, freshQuotaReportsFromResponse } from "../src/provider-workspace/report"; +import { parseWorkBuddyCredits } from "../../src/providers/workbuddy-credit-balance"; const now = Date.UTC(2026, 8, 23, 3); const name = (provider: string) => provider; @@ -52,6 +53,82 @@ describe("quota summary", () => { ]); }); + test("WorkBuddy shows unavailable credits neutrally, including frozen balance, without a reset", () => { + const balance = (total: number, used: number, remaining: number, frozen = 0) => ({ + total, used, remaining, frozen, groups: [], + expiring: { amount: 10, at: now + 3_600_000 }, + }); + const reports = freshQuotaReportsFromResponse([ + { provider: "workbuddy-ai", updatedAt: now, quota: { updatedAt: now, workbuddyCredits: balance(100, 75, 25) } }, + { provider: "frozen", updatedAt: now, quota: { updatedAt: now, workbuddyCredits: balance(100, 0, 0, 100) } }, + { provider: "fractional", updatedAt: now, quota: { updatedAt: now, workbuddyCredits: balance(9, 8.1, 9 - 8.1) } }, + { provider: "below", updatedAt: now, quota: { updatedAt: now, workbuddyCredits: balance(100, 89.4, 10.6) } }, + { provider: "close-below", updatedAt: now, quota: { updatedAt: now, workbuddyCredits: balance(100, 89.99999999999, 10.00000000001) } }, + { provider: "zero-total", updatedAt: now, quota: { updatedAt: now, workbuddyCredits: balance(0, 0, 0) } }, + { provider: "malformed", updatedAt: now, quota: { updatedAt: now, workbuddyCredits: { total: 100, used: 0 } } }, + ], now); + const rows = buildQuotaSummary(reports, name); + expect(rows.map(row => [row.provider, row.headline.labelKey, row.headline.percent, row.severity])).toEqual([ + ["workbuddy-ai", "quotaSummary.creditsUnavailable", 75, "normal"], + ["frozen", "quotaSummary.creditsUnavailable", 100, "normal"], + ["fractional", "quotaSummary.creditsUnavailable", expect.any(Number), "normal"], + ["below", "quotaSummary.creditsUnavailable", expect.any(Number), "normal"], + ["close-below", "quotaSummary.creditsUnavailable", expect.any(Number), "normal"], + ]); + expect(formatQuotaPercent(rows[2]!.headline.percent)).toBe("90%"); + expect(formatQuotaPercent(rows[3]!.headline.percent)).toBe("89%"); + expect(formatQuotaPercent(rows[4]!.headline.percent)).toBe("90%"); + expect(rows[0]!.headline.resetAt).toBeUndefined(); + }); + + test("summed decimal WorkBuddy packages display their exact integer percentage", () => { + const workbuddyCredits = parseWorkBuddyCredits({ Packages: Array.from({ length: 54 }, () => ({ + CycleTotalCapacity: 0.91, CycleUsedCapacity: 0.819, CycleRemainCapacity: 0.091, + })) }); + expect(workbuddyCredits).toBeDefined(); + const reports = freshQuotaReportsFromResponse([ + { provider: "workbuddy-ai", updatedAt: now, quota: { updatedAt: now, workbuddyCredits } }, + ], now); + const [row] = buildQuotaSummary(reports, name); + expect(formatQuotaPercent(row!.headline.percent)).toBe("90%"); + }); + + test("summed WorkBuddy packages retain decimal half-percent and below-half distinctions", () => { + const balance = (remaining: number) => parseWorkBuddyCredits({ Packages: Array.from({ length: 5 }, () => ({ + CycleTotalCapacity: 1, CycleUsedCapacity: 0, CycleRemainCapacity: remaining, + })) }); + const reports = freshQuotaReportsFromResponse([ + { provider: "tie", updatedAt: now, quota: { updatedAt: now, workbuddyCredits: balance(0.935) } }, + { provider: "below", updatedAt: now, quota: { updatedAt: now, workbuddyCredits: balance(0.93500000001) } }, + ], now); + expect(buildQuotaSummary(reports, name).map(row => formatQuotaPercent(row.headline.percent))).toEqual(["7%", "6%"]); + }); + + 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([ + { provider: "tie", updatedAt: now, quota: { updatedAt: now, workbuddyCredits: balance(100, 93.5) } }, + { provider: "below", updatedAt: now, quota: { updatedAt: now, workbuddyCredits: balance(100, 93.50000000001) } }, + { provider: "decimal-tie", updatedAt: now, quota: { updatedAt: now, workbuddyCredits: balance(3, 2.955) } }, + { provider: "decimal-below", updatedAt: now, quota: { updatedAt: now, workbuddyCredits: balance(3, 2.9550000000001) } }, + { provider: "tiny", updatedAt: now, quota: { updatedAt: now, workbuddyCredits: balance(1e-300, 5e-301) } }, + ], now); + expect(buildQuotaSummary(reports, name).map(row => formatQuotaPercent(row.headline.percent))) + .toEqual(["7%", "6%", "2%", "1%", "50%"]); + }); + + test("contradictory WorkBuddy balances are omitted without hiding valid quota windows", () => { + const balance = (remaining: number) => ({ total: 100, used: 2, remaining, frozen: 0, groups: [] }); + const reports = freshQuotaReportsFromResponse([ + { provider: "invalid", updatedAt: now, quota: { updatedAt: now, workbuddyCredits: balance(110) } }, + { provider: "mixed", updatedAt: now, quota: { updatedAt: now, weeklyPercent: 25, workbuddyCredits: balance(110) } }, + { provider: "roundoff", updatedAt: now, quota: { updatedAt: now, workbuddyCredits: balance(100 + 1e-12) } }, + ], now); + const rows = buildQuotaSummary(reports, name); + expect(rows.map(row => [row.provider, row.headline.percent])).toEqual([["mixed", 25], ["roundoff", 0]]); + expect(rows[0]!.windows.map(window => window.labelKey)).toEqual(["quota.weeklyLimit"]); + }); + test("critical credits override a noncritical headline, but not a critical one", () => { const credits = (percent: number) => ({ used: percent, limit: 100, remaining: 100 - percent, percent }); const reports = freshQuotaReportsFromResponse([ diff --git a/src/providers/quota/workbuddy.ts b/src/providers/quota/workbuddy.ts index 63b764b43de..b96ebdfedea 100644 --- a/src/providers/quota/workbuddy.ts +++ b/src/providers/quota/workbuddy.ts @@ -1,7 +1,7 @@ import type { OAuthCredentials } from "../../oauth/types"; import { workBuddyApi, WorkBuddyApiError } from "../../oauth/workbuddy"; import { workBuddyHeaders } from "../workbuddy"; -import { parseWorkBuddyCredits, workBuddyCapacity, workBuddyRecord, type WorkBuddyCreditBalance } from "../workbuddy-credit-balance"; +import { parseWorkBuddyCredits, remainingWorkBuddyCredits, workBuddyCapacity, workBuddyRecord, type WorkBuddyCreditBalance } from "../workbuddy-credit-balance"; import { REQUEST_TIMEOUT_MS } from "../quota-wire"; import { TERMINAL_QUOTA_FAILURE, type ProviderQuotaProbeResult } from "./report-cache"; @@ -67,7 +67,7 @@ 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: Math.max(0, total - used), frozen: 0, groups: [] }; + credits = { total, used, remaining: remainingWorkBuddyCredits(total, used), frozen: 0, groups: [] }; } if (!credits) return null; if (credits.remaining > 0) { diff --git a/src/providers/workbuddy-credit-balance.ts b/src/providers/workbuddy-credit-balance.ts index 19b081d4d15..441a7bc92cc 100644 --- a/src/providers/workbuddy-credit-balance.ts +++ b/src/providers/workbuddy-credit-balance.ts @@ -24,6 +24,35 @@ export function workBuddyCapacity(value: unknown): number | undefined { return Number.isFinite(number) && number >= 0 && number <= Number.MAX_SAFE_INTEGER ? number : undefined; } +/** 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}`); +} + +function sumAmounts(rows: readonly WorkBuddyCreditAmount[]): WorkBuddyCreditAmount { + return { + total: sumCapacities(rows.map(row => row.total)), + used: sumCapacities(rows.map(row => row.used)), + remaining: sumCapacities(rows.map(row => row.remaining)), + frozen: sumCapacities(rows.map(row => row.frozen)), + }; +} + +/** Remaining credits when the provider omits them, bounded below by zero. */ +export function remainingWorkBuddyCredits(total: number, used: number, frozen = 0): number { + return Math.max(0, sumCapacities([total, -used, -frozen])); +} + function amount(value: unknown): WorkBuddyCreditAmount | undefined { const row = workBuddyRecord(value); const total = workBuddyCapacity(row.total), used = workBuddyCapacity(row.used); @@ -53,29 +82,32 @@ function packageAmount(row: Record): WorkBuddyCreditAmount | un 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 ? Math.max(0, total - used - frozen) : workBuddyCapacity(row.CycleRemainCapacity); + const remaining = row.CycleRemainCapacity === undefined ? remainingWorkBuddyCredits(total, used, frozen) : workBuddyCapacity(row.CycleRemainCapacity); return remaining === undefined ? undefined : { total, used, remaining, frozen }; } export function parseWorkBuddyCredits(value: unknown): WorkBuddyCreditBalance | undefined { const summary = workBuddyRecord(value); if (!Array.isArray(summary.Packages) || summary.Packages.length > 512) return undefined; - const balance: WorkBuddyCreditBalance = { total: 0, used: 0, remaining: 0, frozen: 0, groups: [] }; + const packages: WorkBuddyCreditAmount[] = []; for (const raw of summary.Packages) { const quantities = packageAmount(workBuddyRecord(raw)); if (!quantities) return undefined; - for (const key of ["total", "used", "remaining", "frozen"] as const) balance[key] += quantities[key]; + packages.push(quantities); } + const balance: WorkBuddyCreditBalance = { ...sumAmounts(packages), groups: [] }; // 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(); for (const raw of summary.CreditGroups) { const row = workBuddyRecord(raw), quantities = packageAmount(row); if (!quantities) continue; const kind = WORKBUDDY_CREDIT_KINDS.find(kind => kind === row.Kind) ?? "other"; - const existing = balance.groups.find(group => group.kind === kind); - if (existing) for (const key of ["total", "used", "remaining", "frozen"] as const) existing[key] += quantities[key]; - else balance.groups.push({ kind, ...quantities }); + const rows = grouped.get(kind) ?? []; + rows.push(quantities); + grouped.set(kind, rows); } + balance.groups = [...grouped].map(([kind, rows]) => ({ kind, ...sumAmounts(rows) })); } return normalizeWorkBuddyCredits(balance); } diff --git a/structure/dashboard-and-usage.md b/structure/dashboard-and-usage.md index 7e1f3f7f9bf..a39fece4261 100644 --- a/structure/dashboard-and-usage.md +++ b/structure/dashboard-and-usage.md @@ -100,7 +100,7 @@ Accounts tab through `revealProviderAccounts` instead; following the same link a the entry when its filter is edited, and both targets re-read the hash on `hashchange`/`popstate`, so Back and Forward restore the prefilter. Tests live in `gui/tests/provider-protocol-panel.test.tsx`, `gui/tests/compatibility-protocol-filter.test.tsx`, `gui/tests/protocol-deep-links.test.ts`, `gui/tests/providers-deep-link.test.tsx`, -`gui/tests/quota-summary-bar.test.tsx` and `gui/tests/combo-protocol-plan.test.tsx`; `gui/tests/quota-summary-hover-browser.ts` checks real pointer travel across the quota popover gap with production CSS. `gui/src/quota-summary.ts` selects fixed windows by semantic label and promotes critical credits over a noncritical preferred window; a critical preferred window retains priority. `gui/tests/quota-summary.test.ts` covers precedence and provider-label collisions. +`gui/tests/quota-summary-bar.test.tsx` and `gui/tests/combo-protocol-plan.test.tsx`; `gui/tests/quota-summary-hover-browser.ts` checks real pointer travel across the quota popover gap with production CSS. `gui/src/quota-summary.ts` selects fixed windows by semantic label and promotes critical credits over a noncritical preferred window; a critical preferred window retains priority. For a positive WorkBuddy credit total it derives the unavailable share from remaining credits, including frozen amounts, with neutral severity, nearest-whole-percent display and no partial expiry presented as a balance reset. `gui/tests/quota-summary.test.ts` covers this projection, precedence and provider-label collisions. The API workspace gives `gui/src/components/section-tabs.tsx` its mobile reading line so scroll-spy and the top-bar offset agree; other consumers keep their diff --git a/structure/providers/workbuddy.md b/structure/providers/workbuddy.md index bc12127813f..a7997f07e5f 100644 --- a/structure/providers/workbuddy.md +++ b/structure/providers/workbuddy.md @@ -38,9 +38,11 @@ account metadata; fresh/stale cache and failure cooldowns are bound to the crede Unavailable discovery degrades to the same-account cache, then the minimal `default-model` seed. `src/providers/quota/workbuddy.ts` reads the authenticated resource summary through the bounded, -fixed-origin API helper. It sums `Packages` once and treats `CreditGroups` as a breakdown; +fixed-origin API helper. It sums `Packages` once using the decimal representation of each validated +number before returning numeric totals, and treats `CreditGroups` as a breakdown; explicit remaining/frozen amounts take precedence over arithmetic estimates. Team accounts use -the enterprise meter when the personal summary has no capacity. Optional paid/free package +the enterprise meter when the personal summary has no capacity; estimated remaining credits use +decimal subtraction on validated amounts. Optional paid/free package queries use summary-owned codes, bounded pagination and the same total deadline; a failure omits expiry without losing the balance. Expiry uses the earliest future non-daily package and excludes packages absent from the summary. diff --git a/tests/providers/workbuddy-quota.test.ts b/tests/providers/workbuddy-quota.test.ts index 357bcc52f70..15bba422d42 100644 --- a/tests/providers/workbuddy-quota.test.ts +++ b/tests/providers/workbuddy-quota.test.ts @@ -9,6 +9,8 @@ import { accountHeadroomPercent } from "../../src/oauth/account-quota-rank"; import { cachedProviderQuotaIsExhausted } from "../../src/combos/resolve"; import { providerDecisionWindows } from "../../src/providers/quota-decision-publication"; import type { OAuthCredentials } from "../../src/oauth/types"; +import { buildQuotaSummary, formatQuotaPercent } from "../../gui/src/quota-summary"; +import { freshQuotaReportsFromResponse } from "../../gui/src/provider-workspace/report"; const originalFetch = globalThis.fetch; let home: ReturnType; @@ -19,6 +21,30 @@ const credentials = (suffix = "a"): OAuthCredentials => ({ access: `fixture-acce const amounts = (total = "100", used = "0", remaining = "100") => ({ CycleTotalCapacity: total, CycleUsedCapacity: used, CycleRemainCapacity: remaining, CycleFrozenCapacity: "0" }); const summary = () => ({ Packages: [{ PackageCode: "fixture-base", ...amounts() }, { PackageCode: "fixture-gift", ...amounts("250", "0", "250") }], TotalCredits: "350", CreditGroups: [{ Kind: "plan_base", ...amounts() }, { Kind: "benefit", ...amounts("250", "0", "250") }] }); + +test("decimal package totals preserve the reported remaining balance", () => { + const packages = Array.from({ length: 5 }, () => amounts("1", "0.065", "0.935")); + const credits = parseWorkBuddyCredits({ Packages: packages })!; + expect(credits.total).toBe(5); + expect(credits.remaining).toBe(4.675); + expect(credits.used).toBe(0.325); + const groups = packages.map(row => ({ Kind: "benefit", ...row })); + expect(parseWorkBuddyCredits({ Packages: packages, CreditGroups: groups })?.groups[0]?.remaining).toBe(4.675); + expect(parseWorkBuddyCredits({ Packages: [{ CycleTotalCapacity: 0.3, CycleUsedCapacity: 0.2 }] })?.remaining).toBe(0.1); + expect(parseWorkBuddyCredits({ Packages: Array.from({ length: 512 }, () => amounts("0.1", "0", "0.1")) })?.total).toBe(51.2); + expect(parseWorkBuddyCredits({ Packages: [{ CycleTotalCapacity: 1e-300, CycleUsedCapacity: 0, CycleRemainCapacity: 5e-301 }] })?.remaining).toBe(5e-301); +}); + +test("enterprise decimal balance retains half-percent rounding in the dashboard", async () => { + globalThis.fetch = (async input => Response.json({ code: 0, data: String(input).endsWith("summary") + ? { Packages: [] } : { limitNum: "1", credit: "0.285" } })) as typeof fetch; + const credential = credentials(); + credential.workbuddy!.enterpriseId = "fixture-team"; + const report = await fetchWorkBuddyQuota("workbuddy-ai", credential); + expect(report).toMatchObject({ quota: { workbuddyCredits: { remaining: 0.715 } } }); + const rows = buildQuotaSummary(freshQuotaReportsFromResponse([report]), provider => provider); + expect(formatQuotaPercent(rows[0]?.headline.percent)).toBe("29%"); +}); function stubSummary(value: unknown) { globalThis.fetch = (async (input, init) => { expect(String(input)).toStartWith("https://www.workbuddy.ai/billing/meter/");