From b4cd0aea192dbf5ca349fbc29788e473d14e328f Mon Sep 17 00:00:00 2001 From: JUN Date: Sat, 7 Nov 2026 22:21:20 +0900 Subject: [PATCH 01/12] fix(gui): show WorkBuddy credits in quota summary --- docs-site/src/content/docs/guides/providers.md | 2 ++ .../src/content/docs/zh-cn/guides/providers.md | 2 ++ gui/src/quota-summary.ts | 10 ++++++++++ gui/tests/quota-summary.test.ts | 18 ++++++++++++++++++ structure/dashboard-and-usage.md | 2 +- 5 files changed, 33 insertions(+), 1 deletion(-) diff --git a/docs-site/src/content/docs/guides/providers.md b/docs-site/src/content/docs/guides/providers.md index d28873ac404..a2d6e40fd3d 100644 --- a/docs-site/src/content/docs/guides/providers.md +++ b/docs-site/src/content/docs/guides/providers.md @@ -1404,6 +1404,8 @@ 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 also shows the used percentage. +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..517d69f53d0 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/quota-summary.ts b/gui/src/quota-summary.ts index 3e7ec861426..4a948416e95 100644 --- a/gui/src/quota-summary.ts +++ b/gui/src/quota-summary.ts @@ -81,6 +81,16 @@ function summaryWindows(quota: AccountQuota): QuotaSummaryWindow[] { severity: quotaSeverity(credits.percent), }); } + const workbuddy = quota.workbuddyCredits; + if (workbuddy && workbuddy.total > 0) { + const percent = Math.min(100, workbuddy.used / workbuddy.total * 100); + windows.push({ + id: "quotaSummary.credits", + labelKey: "quotaSummary.credits", + percent, + severity: quotaSeverity(percent), + }); + } // 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.test.ts b/gui/tests/quota-summary.test.ts index c4cff2fbb8b..ce2d2859e7d 100644 --- a/gui/tests/quota-summary.test.ts +++ b/gui/tests/quota-summary.test.ts @@ -52,6 +52,24 @@ describe("quota summary", () => { ]); }); + test("WorkBuddy credit usage appears in the summary without treating expiry as a reset", () => { + const balance = (total: number, used: number) => ({ + total, used, remaining: Math.max(0, total - used), frozen: 0, groups: [], + expiring: { amount: 10, at: now + 3_600_000 }, + }); + const reports = freshQuotaReportsFromResponse([ + { provider: "workbuddy-ai", updatedAt: now, quota: { updatedAt: now, workbuddyCredits: balance(100, 75) } }, + { provider: "exhausted", updatedAt: now, quota: { updatedAt: now, workbuddyCredits: balance(100, 125) } }, + { provider: "zero-total", updatedAt: now, quota: { updatedAt: now, workbuddyCredits: balance(0, 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.credits", 75, "warn"], + ["exhausted", "quotaSummary.credits", 100, "critical"], + ]); + expect(rows[0]!.headline.resetAt).toBeUndefined(); + }); + 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/structure/dashboard-and-usage.md b/structure/dashboard-and-usage.md index 7e1f3f7f9bf..4abe33b0ed9 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 a capped used percentage, without presenting a partial expiry 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 From f082ee50ada08a9a8676003234acdeca2c160a44 Mon Sep 17 00:00:00 2001 From: JUN Date: Sat, 7 Nov 2026 22:32:41 +0900 Subject: [PATCH 02/12] fix(gui): represent unavailable WorkBuddy credits accurately --- .../src/content/docs/guides/providers.md | 5 ++-- .../content/docs/zh-cn/guides/providers.md | 4 +-- .../quota-summary-bar/QuotaSummaryBar.tsx | 3 +++ gui/src/i18n/de.ts | 1 + gui/src/i18n/en.ts | 1 + gui/src/i18n/fr.ts | 1 + gui/src/i18n/ja.ts | 1 + gui/src/i18n/ko.ts | 1 + gui/src/i18n/pt.ts | 1 + gui/src/i18n/ru.ts | 1 + gui/src/i18n/tr.ts | 1 + gui/src/i18n/vi.ts | 1 + gui/src/i18n/zh-TW.ts | 1 + gui/src/i18n/zh.ts | 1 + gui/src/quota-summary.ts | 11 +++++--- gui/tests/quota-summary-bar.test.tsx | 16 ++++++++++-- gui/tests/quota-summary.test.ts | 25 +++++++++++++------ structure/dashboard-and-usage.md | 2 +- 18 files changed, 58 insertions(+), 19 deletions(-) diff --git a/docs-site/src/content/docs/guides/providers.md b/docs-site/src/content/docs/guides/providers.md index a2d6e40fd3d..ed6ede5ac05 100644 --- a/docs-site/src/content/docs/guides/providers.md +++ b/docs-site/src/content/docs/guides/providers.md @@ -1404,8 +1404,9 @@ 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 also shows the used percentage. -An individual credit expiry is not shown as a reset of the entire balance. +When the reported total is positive, the header quota summary shows the unavailable percentage, +including frozen credits, without an 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 517d69f53d0..25d8bd50eff 100644 --- a/docs-site/src/content/docs/zh-cn/guides/providers.md +++ b/docs-site/src/content/docs/zh-cn/guides/providers.md @@ -201,8 +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 4a948416e95..4fed8116b4e 100644 --- a/gui/src/quota-summary.ts +++ b/gui/src/quota-summary.ts @@ -83,12 +83,15 @@ function summaryWindows(quota: AccountQuota): QuotaSummaryWindow[] { } const workbuddy = quota.workbuddyCredits; if (workbuddy && workbuddy.total > 0) { - const percent = Math.min(100, workbuddy.used / workbuddy.total * 100); + // Remaining is authoritative and includes frozen credits; the meter is informational. + const raw = (1 - Math.min(workbuddy.remaining / workbuddy.total, 1)) * 100; + const integer = Math.round(raw); + const percent = Math.abs(raw - integer) <= Number.EPSILON * 100 ? integer : raw; windows.push({ - id: "quotaSummary.credits", - labelKey: "quotaSummary.credits", + id: "quotaSummary.creditsUnavailable", + labelKey: "quotaSummary.creditsUnavailable", percent, - severity: quotaSeverity(percent), + severity: "normal", }); } // Credits are appended after provider windows, whose labels can equal any fixed id. diff --git a/gui/tests/quota-summary-bar.test.tsx b/gui/tests/quota-summary-bar.test.tsx index 466b2370f9b..eaf7a41811b 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,18 @@ 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(); +}); + 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 ce2d2859e7d..365b65b0ab5 100644 --- a/gui/tests/quota-summary.test.ts +++ b/gui/tests/quota-summary.test.ts @@ -52,21 +52,30 @@ describe("quota summary", () => { ]); }); - test("WorkBuddy credit usage appears in the summary without treating expiry as a reset", () => { - const balance = (total: number, used: number) => ({ - total, used, remaining: Math.max(0, total - used), frozen: 0, groups: [], + 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) } }, - { provider: "exhausted", updatedAt: now, quota: { updatedAt: now, workbuddyCredits: balance(100, 125) } }, - { provider: "zero-total", updatedAt: now, quota: { updatedAt: now, workbuddyCredits: balance(0, 0) } }, + { 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.999, 10.001) } }, + { 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.credits", 75, "warn"], - ["exhausted", "quotaSummary.credits", 100, "critical"], + ["workbuddy-ai", "quotaSummary.creditsUnavailable", 75, "normal"], + ["frozen", "quotaSummary.creditsUnavailable", 100, "normal"], + ["fractional", "quotaSummary.creditsUnavailable", 90, "normal"], + ["below", "quotaSummary.creditsUnavailable", expect.any(Number), "normal"], ]); + expect(formatQuotaPercent(rows[2]!.headline.percent)).toBe("90%"); + expect(rows[3]!.headline.percent).toBeCloseTo(89.999, 9); + expect(rows[3]!.headline.percent!).toBeLessThan(90); + expect(formatQuotaPercent(rows[3]!.headline.percent)).toBe("89%"); expect(rows[0]!.headline.resetAt).toBeUndefined(); }); diff --git a/structure/dashboard-and-usage.md b/structure/dashboard-and-usage.md index 4abe33b0ed9..9fa7c6b2314 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. For a positive WorkBuddy credit total it derives a capped used percentage, without presenting a partial expiry as a balance reset. `gui/tests/quota-summary.test.ts` covers this projection, 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 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 From eb1acbc96d2ad513d8f2bc2ec509f41e9ecac717 Mon Sep 17 00:00:00 2001 From: JUN Date: Sat, 7 Nov 2026 22:37:25 +0900 Subject: [PATCH 03/12] fix(gui): handle accumulated WorkBuddy credit precision --- gui/src/quota-summary.ts | 3 ++- gui/tests/quota-summary.test.ts | 16 ++++++++++++++++ 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/gui/src/quota-summary.ts b/gui/src/quota-summary.ts index 4fed8116b4e..775cb14b2ed 100644 --- a/gui/src/quota-summary.ts +++ b/gui/src/quota-summary.ts @@ -86,7 +86,8 @@ function summaryWindows(quota: AccountQuota): QuotaSummaryWindow[] { // Remaining is authoritative and includes frozen credits; the meter is informational. const raw = (1 - Math.min(workbuddy.remaining / workbuddy.total, 1)) * 100; const integer = Math.round(raw); - const percent = Math.abs(raw - integer) <= Number.EPSILON * 100 ? integer : raw; + // The provider sums at most 512 packages into both total and remaining. + const percent = Math.abs(raw - integer) <= Number.EPSILON * 100 * 1024 ? integer : raw; windows.push({ id: "quotaSummary.creditsUnavailable", labelKey: "quotaSummary.creditsUnavailable", diff --git a/gui/tests/quota-summary.test.ts b/gui/tests/quota-summary.test.ts index 365b65b0ab5..ab14f4972a0 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; @@ -62,6 +63,7 @@ describe("quota summary", () => { { 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.999, 10.001) } }, + { provider: "close-below", updatedAt: now, quota: { updatedAt: now, workbuddyCredits: balance(100, 89.999999999, 10.000000001) } }, { 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); @@ -71,14 +73,28 @@ describe("quota summary", () => { ["frozen", "quotaSummary.creditsUnavailable", 100, "normal"], ["fractional", "quotaSummary.creditsUnavailable", 90, "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(rows[3]!.headline.percent).toBeCloseTo(89.999, 9); expect(rows[3]!.headline.percent!).toBeLessThan(90); expect(formatQuotaPercent(rows[3]!.headline.percent)).toBe("89%"); + expect(formatQuotaPercent(rows[4]!.headline.percent)).toBe("89%"); 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("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([ From 73e0534f366c5434a6f32b5d7c11c81978eeb007 Mon Sep 17 00:00:00 2001 From: JUN Date: Sat, 7 Nov 2026 22:41:35 +0900 Subject: [PATCH 04/12] fix(gui): define WorkBuddy credit percentage rounding --- .../src/content/docs/guides/providers.md | 3 ++- .../content/docs/zh-cn/guides/providers.md | 4 ++-- .../quota-summary-bar/QuotaSummaryBar.tsx | 6 +++--- gui/src/quota-summary.ts | 14 ++++++------- gui/tests/quota-summary-bar.test.tsx | 11 ++++++++++ gui/tests/quota-summary.test.ts | 20 +++++++++++-------- structure/dashboard-and-usage.md | 2 +- 7 files changed, 38 insertions(+), 22 deletions(-) diff --git a/docs-site/src/content/docs/guides/providers.md b/docs-site/src/content/docs/guides/providers.md index ed6ede5ac05..2419415a450 100644 --- a/docs-site/src/content/docs/guides/providers.md +++ b/docs-site/src/content/docs/guides/providers.md @@ -1405,7 +1405,8 @@ balances, and the next expiring non-daily credits when available. Refresh reads 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, without an exhaustion warning: free models may still work. An individual +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 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 25d8bd50eff..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,8 +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 bb0af453ef0..58c11772cfb 100644 --- a/gui/src/components/quota-summary-bar/QuotaSummaryBar.tsx +++ b/gui/src/components/quota-summary-bar/QuotaSummaryBar.tsx @@ -212,7 +212,7 @@ function QuotaSummaryItem({ row, t, locale }: { row: QuotaSummaryRow; t: TFn; lo {headline.labelKey === "quotaSummary.creditsUnavailable" && ( {t("quotaSummary.creditsUnavailable")} )} - {formatQuotaPercent(headline.percent)} + {formatQuotaPercent(headline.percent, headline.rounding)} {row.provider === "meta-muse" && headline.resetAt !== undefined && ( {formatMuseResetCountdown(headline.resetAt, clock)} @@ -233,7 +233,7 @@ function QuotaSummaryItem({ row, t, locale }: { row: QuotaSummaryRow; t: TFn; lo {row.windows.map(window => ( {windowLabel(window, t)} - {formatQuotaPercent(window.percent)} + {formatQuotaPercent(window.percent, window.rounding)} {window.resetAt !== undefined ? formatResetFuture(window.resetAt, t, locale) : "-"} @@ -293,7 +293,7 @@ export function QuotaSummaryChips({ rows, t, locale }: { rows: QuotaSummaryRow[] // Chips can widen without the list box changing size (a new provider, a longer percent, a late // web font), so the observer watches every chip as well as the list, and the row signature // re-measures on the next frame for chips that arrive with the new rows. - const rowsKey = rows.map(row => `${row.provider}:${row.label}:${formatQuotaPercent(row.headline.percent)}:${row.severity}`).join("|"); + const rowsKey = rows.map(row => `${row.provider}:${row.label}:${formatQuotaPercent(row.headline.percent, row.headline.rounding)}:${row.severity}`).join("|"); useEffect(() => { const list = listRef.current; if (!list) return; diff --git a/gui/src/quota-summary.ts b/gui/src/quota-summary.ts index 775cb14b2ed..afc17c5c85c 100644 --- a/gui/src/quota-summary.ts +++ b/gui/src/quota-summary.ts @@ -23,6 +23,8 @@ export interface QuotaSummaryWindow { /** Provider-named window label, shown verbatim. */ label?: string; percent?: number; + /** Informational balances have no severity threshold and may round to the nearest percent. */ + rounding?: "nearest"; resetAt?: number; severity: QuotaSummarySeverity; } @@ -46,9 +48,9 @@ export function quotaSeverity(percent: number | undefined): QuotaSummarySeverity return "normal"; } -// Flooring keeps the displayed number on the same side of the 70/90 thresholds as the color. -export function formatQuotaPercent(percent: number | undefined): string { - return finite(percent) ? `${Math.floor(percent)}%` : "-"; +// Threshold-bearing windows floor to keep the displayed number on the same side as the color. +export function formatQuotaPercent(percent: number | undefined, rounding?: "nearest"): string { + return finite(percent) ? `${rounding === "nearest" ? Math.round(percent) : Math.floor(percent)}%` : "-"; } /** Long windows first: weekly is the default headline, then monthly, then 5h, then custom. */ @@ -84,14 +86,12 @@ function summaryWindows(quota: AccountQuota): QuotaSummaryWindow[] { const workbuddy = quota.workbuddyCredits; if (workbuddy && workbuddy.total > 0) { // Remaining is authoritative and includes frozen credits; the meter is informational. - const raw = (1 - Math.min(workbuddy.remaining / workbuddy.total, 1)) * 100; - const integer = Math.round(raw); - // The provider sums at most 512 packages into both total and remaining. - const percent = Math.abs(raw - integer) <= Number.EPSILON * 100 * 1024 ? integer : raw; + const percent = (1 - Math.min(workbuddy.remaining / workbuddy.total, 1)) * 100; windows.push({ id: "quotaSummary.creditsUnavailable", labelKey: "quotaSummary.creditsUnavailable", percent, + rounding: "nearest", severity: "normal", }); } diff --git a/gui/tests/quota-summary-bar.test.tsx b/gui/tests/quota-summary-bar.test.tsx index eaf7a41811b..13b69efc6b4 100644 --- a/gui/tests/quota-summary-bar.test.tsx +++ b/gui/tests/quota-summary-bar.test.tsx @@ -69,6 +69,17 @@ test("WorkBuddy chip names unavailable credits so frozen funds are not called us 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 ab14f4972a0..e4f97a8b8de 100644 --- a/gui/tests/quota-summary.test.ts +++ b/gui/tests/quota-summary.test.ts @@ -20,6 +20,8 @@ describe("quota summary", () => { expect([formatQuotaPercent(89.6), quotaSeverity(89.6)]).toEqual(["89%", "warn"]); expect([formatQuotaPercent(90), quotaSeverity(90)]).toEqual(["90%", "critical"]); expect(formatQuotaPercent(undefined)).toBe("-"); + expect(formatQuotaPercent(89.6, "nearest")).toBe("90%"); + expect(formatQuotaPercent(89.4, "nearest")).toBe("89%"); }); test("headline prefers weekly, then monthly, then 5h, then provider windows", () => { @@ -62,8 +64,8 @@ describe("quota summary", () => { { 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.999, 10.001) } }, - { provider: "close-below", updatedAt: now, quota: { updatedAt: now, workbuddyCredits: balance(100, 89.999999999, 10.000000001) } }, + { 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); @@ -71,15 +73,17 @@ describe("quota summary", () => { 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", 90, "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(rows[3]!.headline.percent).toBeCloseTo(89.999, 9); + expect(rows[2]!.headline.rounding).toBe("nearest"); + expect(formatQuotaPercent(rows[2]!.headline.percent, rows[2]!.headline.rounding)).toBe("90%"); + expect(rows[3]!.headline.percent).toBeCloseTo(89.4, 9); expect(rows[3]!.headline.percent!).toBeLessThan(90); - expect(formatQuotaPercent(rows[3]!.headline.percent)).toBe("89%"); - expect(formatQuotaPercent(rows[4]!.headline.percent)).toBe("89%"); + expect(formatQuotaPercent(rows[3]!.headline.percent, rows[3]!.headline.rounding)).toBe("89%"); + expect(rows[4]!.headline.percent!).toBeLessThan(90); + expect(formatQuotaPercent(rows[4]!.headline.percent, rows[4]!.headline.rounding)).toBe("90%"); expect(rows[0]!.headline.resetAt).toBeUndefined(); }); @@ -92,7 +96,7 @@ describe("quota summary", () => { { provider: "workbuddy-ai", updatedAt: now, quota: { updatedAt: now, workbuddyCredits } }, ], now); const [row] = buildQuotaSummary(reports, name); - expect(formatQuotaPercent(row!.headline.percent)).toBe("90%"); + expect(formatQuotaPercent(row!.headline.percent, row!.headline.rounding)).toBe("90%"); }); test("critical credits override a noncritical headline, but not a critical one", () => { diff --git a/structure/dashboard-and-usage.md b/structure/dashboard-and-usage.md index 9fa7c6b2314..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. For a positive WorkBuddy credit total it derives the unavailable share from remaining credits, including frozen amounts, with neutral severity and no partial expiry presented as a balance reset. `gui/tests/quota-summary.test.ts` covers this projection, 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 From fcafb202dd825a5f70280d80e36d360c787aee9f Mon Sep 17 00:00:00 2001 From: JUN Date: Sat, 7 Nov 2026 22:45:55 +0900 Subject: [PATCH 05/12] fix(gui): omit inconsistent WorkBuddy credit ratios --- gui/src/quota-summary.ts | 3 ++- gui/tests/quota-summary.test.ts | 12 ++++++++++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/gui/src/quota-summary.ts b/gui/src/quota-summary.ts index afc17c5c85c..e47befe4b1f 100644 --- a/gui/src/quota-summary.ts +++ b/gui/src/quota-summary.ts @@ -84,7 +84,8 @@ function summaryWindows(quota: AccountQuota): QuotaSummaryWindow[] { }); } const workbuddy = quota.workbuddyCredits; - if (workbuddy && workbuddy.total > 0) { + // 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 = (1 - Math.min(workbuddy.remaining / workbuddy.total, 1)) * 100; windows.push({ diff --git a/gui/tests/quota-summary.test.ts b/gui/tests/quota-summary.test.ts index e4f97a8b8de..0c911a9481f 100644 --- a/gui/tests/quota-summary.test.ts +++ b/gui/tests/quota-summary.test.ts @@ -99,6 +99,18 @@ describe("quota summary", () => { expect(formatQuotaPercent(row!.headline.percent, row!.headline.rounding)).toBe("90%"); }); + 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([ From 59349eacac8cb9dbb448b2ef56856c0252d12059 Mon Sep 17 00:00:00 2001 From: JUN Date: Sat, 7 Nov 2026 22:51:27 +0900 Subject: [PATCH 06/12] fix(gui): round reported WorkBuddy balances precisely --- .../quota-summary-bar/QuotaSummaryBar.tsx | 6 ++-- gui/src/quota-summary.ts | 28 ++++++++++++++----- gui/tests/quota-summary.test.ts | 27 +++++++++++------- 3 files changed, 41 insertions(+), 20 deletions(-) diff --git a/gui/src/components/quota-summary-bar/QuotaSummaryBar.tsx b/gui/src/components/quota-summary-bar/QuotaSummaryBar.tsx index 58c11772cfb..bb0af453ef0 100644 --- a/gui/src/components/quota-summary-bar/QuotaSummaryBar.tsx +++ b/gui/src/components/quota-summary-bar/QuotaSummaryBar.tsx @@ -212,7 +212,7 @@ function QuotaSummaryItem({ row, t, locale }: { row: QuotaSummaryRow; t: TFn; lo {headline.labelKey === "quotaSummary.creditsUnavailable" && ( {t("quotaSummary.creditsUnavailable")} )} - {formatQuotaPercent(headline.percent, headline.rounding)} + {formatQuotaPercent(headline.percent)} {row.provider === "meta-muse" && headline.resetAt !== undefined && ( {formatMuseResetCountdown(headline.resetAt, clock)} @@ -233,7 +233,7 @@ function QuotaSummaryItem({ row, t, locale }: { row: QuotaSummaryRow; t: TFn; lo {row.windows.map(window => ( {windowLabel(window, t)} - {formatQuotaPercent(window.percent, window.rounding)} + {formatQuotaPercent(window.percent)} {window.resetAt !== undefined ? formatResetFuture(window.resetAt, t, locale) : "-"} @@ -293,7 +293,7 @@ export function QuotaSummaryChips({ rows, t, locale }: { rows: QuotaSummaryRow[] // Chips can widen without the list box changing size (a new provider, a longer percent, a late // web font), so the observer watches every chip as well as the list, and the row signature // re-measures on the next frame for chips that arrive with the new rows. - const rowsKey = rows.map(row => `${row.provider}:${row.label}:${formatQuotaPercent(row.headline.percent, row.headline.rounding)}:${row.severity}`).join("|"); + const rowsKey = rows.map(row => `${row.provider}:${row.label}:${formatQuotaPercent(row.headline.percent)}:${row.severity}`).join("|"); useEffect(() => { const list = listRef.current; if (!list) return; diff --git a/gui/src/quota-summary.ts b/gui/src/quota-summary.ts index e47befe4b1f..5ddaa39db33 100644 --- a/gui/src/quota-summary.ts +++ b/gui/src/quota-summary.ts @@ -23,8 +23,6 @@ export interface QuotaSummaryWindow { /** Provider-named window label, shown verbatim. */ label?: string; percent?: number; - /** Informational balances have no severity threshold and may round to the nearest percent. */ - rounding?: "nearest"; resetAt?: number; severity: QuotaSummarySeverity; } @@ -48,9 +46,26 @@ export function quotaSeverity(percent: number | undefined): QuotaSummarySeverity return "normal"; } -// Threshold-bearing windows floor to keep the displayed number on the same side as the color. -export function formatQuotaPercent(percent: number | undefined, rounding?: "nearest"): string { - return finite(percent) ? `${rounding === "nearest" ? Math.round(percent) : Math.floor(percent)}%` : "-"; +// Flooring keeps the displayed number on the same side of the 70/90 thresholds as the color. +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. */ @@ -87,12 +102,11 @@ function summaryWindows(quota: AccountQuota): QuotaSummaryWindow[] { // 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 = (1 - Math.min(workbuddy.remaining / workbuddy.total, 1)) * 100; + const percent = roundedUnavailablePercent(workbuddy.total, workbuddy.remaining); windows.push({ id: "quotaSummary.creditsUnavailable", labelKey: "quotaSummary.creditsUnavailable", percent, - rounding: "nearest", severity: "normal", }); } diff --git a/gui/tests/quota-summary.test.ts b/gui/tests/quota-summary.test.ts index 0c911a9481f..8cd46b09195 100644 --- a/gui/tests/quota-summary.test.ts +++ b/gui/tests/quota-summary.test.ts @@ -20,8 +20,6 @@ describe("quota summary", () => { expect([formatQuotaPercent(89.6), quotaSeverity(89.6)]).toEqual(["89%", "warn"]); expect([formatQuotaPercent(90), quotaSeverity(90)]).toEqual(["90%", "critical"]); expect(formatQuotaPercent(undefined)).toBe("-"); - expect(formatQuotaPercent(89.6, "nearest")).toBe("90%"); - expect(formatQuotaPercent(89.4, "nearest")).toBe("89%"); }); test("headline prefers weekly, then monthly, then 5h, then provider windows", () => { @@ -77,13 +75,9 @@ describe("quota summary", () => { ["below", "quotaSummary.creditsUnavailable", expect.any(Number), "normal"], ["close-below", "quotaSummary.creditsUnavailable", expect.any(Number), "normal"], ]); - expect(rows[2]!.headline.rounding).toBe("nearest"); - expect(formatQuotaPercent(rows[2]!.headline.percent, rows[2]!.headline.rounding)).toBe("90%"); - expect(rows[3]!.headline.percent).toBeCloseTo(89.4, 9); - expect(rows[3]!.headline.percent!).toBeLessThan(90); - expect(formatQuotaPercent(rows[3]!.headline.percent, rows[3]!.headline.rounding)).toBe("89%"); - expect(rows[4]!.headline.percent!).toBeLessThan(90); - expect(formatQuotaPercent(rows[4]!.headline.percent, rows[4]!.headline.rounding)).toBe("90%"); + 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(); }); @@ -96,7 +90,20 @@ describe("quota summary", () => { { provider: "workbuddy-ai", updatedAt: now, quota: { updatedAt: now, workbuddyCredits } }, ], now); const [row] = buildQuotaSummary(reports, name); - expect(formatQuotaPercent(row!.headline.percent, row!.headline.rounding)).toBe("90%"); + expect(formatQuotaPercent(row!.headline.percent)).toBe("90%"); + }); + + 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", () => { From 490cf9d3d69381b14563cc9d76cdba8687686672 Mon Sep 17 00:00:00 2001 From: JUN Date: Sat, 7 Nov 2026 22:57:06 +0900 Subject: [PATCH 07/12] fix(workbuddy): preserve decimal precision in credit sums --- gui/tests/quota-summary.test.ts | 11 +++++++ src/providers/workbuddy-credit-balance.ts | 39 +++++++++++++++++++---- structure/providers/workbuddy.md | 3 +- tests/providers/workbuddy-quota.test.ts | 13 ++++++++ 4 files changed, 59 insertions(+), 7 deletions(-) diff --git a/gui/tests/quota-summary.test.ts b/gui/tests/quota-summary.test.ts index 8cd46b09195..58099679744 100644 --- a/gui/tests/quota-summary.test.ts +++ b/gui/tests/quota-summary.test.ts @@ -93,6 +93,17 @@ describe("quota summary", () => { 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([ diff --git a/src/providers/workbuddy-credit-balance.ts b/src/providers/workbuddy-credit-balance.ts index 19b081d4d15..7905bccfaa9 100644 --- a/src/providers/workbuddy-credit-balance.ts +++ b/src/providers/workbuddy-credit-balance.ts @@ -24,6 +24,30 @@ 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)), + }; +} + function amount(value: unknown): WorkBuddyCreditAmount | undefined { const row = workBuddyRecord(value); const total = workBuddyCapacity(row.total), used = workBuddyCapacity(row.used); @@ -53,29 +77,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 ? Math.max(0, sumCapacities([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/providers/workbuddy.md b/structure/providers/workbuddy.md index bc12127813f..d0ecaa847a5 100644 --- a/structure/providers/workbuddy.md +++ b/structure/providers/workbuddy.md @@ -38,7 +38,8 @@ 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 queries use summary-owned codes, bounded pagination and the same total deadline; a failure diff --git a/tests/providers/workbuddy-quota.test.ts b/tests/providers/workbuddy-quota.test.ts index 357bcc52f70..b28575b8e7e 100644 --- a/tests/providers/workbuddy-quota.test.ts +++ b/tests/providers/workbuddy-quota.test.ts @@ -19,6 +19,19 @@ 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); +}); function stubSummary(value: unknown) { globalThis.fetch = (async (input, init) => { expect(String(input)).toStartWith("https://www.workbuddy.ai/billing/meter/"); From 8e56d5ab497d38d2a31d2282bb635f2cf62023e3 Mon Sep 17 00:00:00 2001 From: JUN Date: Sat, 7 Nov 2026 23:00:50 +0900 Subject: [PATCH 08/12] fix(workbuddy): preserve enterprise balance precision --- src/providers/quota/workbuddy.ts | 4 ++-- src/providers/workbuddy-credit-balance.ts | 7 ++++++- structure/providers/workbuddy.md | 3 ++- tests/providers/workbuddy-quota.test.ts | 13 +++++++++++++ 4 files changed, 23 insertions(+), 4 deletions(-) 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 7905bccfaa9..441a7bc92cc 100644 --- a/src/providers/workbuddy-credit-balance.ts +++ b/src/providers/workbuddy-credit-balance.ts @@ -48,6 +48,11 @@ function sumAmounts(rows: readonly WorkBuddyCreditAmount[]): WorkBuddyCreditAmou }; } +/** 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); @@ -77,7 +82,7 @@ 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, sumCapacities([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 }; } diff --git a/structure/providers/workbuddy.md b/structure/providers/workbuddy.md index d0ecaa847a5..a7997f07e5f 100644 --- a/structure/providers/workbuddy.md +++ b/structure/providers/workbuddy.md @@ -41,7 +41,8 @@ Unavailable discovery degrades to the same-account cache, then the minimal `defa 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 b28575b8e7e..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; @@ -32,6 +34,17 @@ test("decimal package totals preserve the reported remaining balance", () => { 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/"); From b8dc88f36ea7a716ef614ae4bc408dd4e0b4d9f5 Mon Sep 17 00:00:00 2001 From: JUN Date: Sun, 8 Nov 2026 14:16:09 +0900 Subject: [PATCH 09/12] fix(workbuddy): preserve exact quota balance decimals --- gui/src/quota-summary.ts | 25 ++--------- gui/tests/quota-summary.test.ts | 22 +++++++++ src/providers/quota/workbuddy.ts | 6 +-- src/providers/workbuddy-credit-balance.ts | 55 +++++++++++++++++++---- src/providers/workbuddy-decimal.ts | 52 +++++++++++++++++++++ structure/dashboard-and-usage.md | 2 +- structure/providers/workbuddy.md | 11 +++-- tests/providers/workbuddy-quota.test.ts | 12 +++++ 8 files changed, 146 insertions(+), 39 deletions(-) create mode 100644 src/providers/workbuddy-decimal.ts diff --git a/gui/src/quota-summary.ts b/gui/src/quota-summary.ts index 5ddaa39db33..0f5dd544873 100644 --- a/gui/src/quota-summary.ts +++ b/gui/src/quota-summary.ts @@ -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 { workBuddyUnavailablePercent } from "../../src/providers/workbuddy-credit-balance"; export const QUOTA_SUMMARY_WARN_PERCENT = 70; export const QUOTA_SUMMARY_CRITICAL_PERCENT = 90; @@ -51,23 +52,6 @@ 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"]; @@ -99,14 +83,13 @@ 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) { + const workbuddyPercent = workbuddy ? workBuddyUnavailablePercent(workbuddy) : undefined; + if (workbuddyPercent !== undefined) { // 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, + percent: workbuddyPercent, severity: "normal", }); } diff --git a/gui/tests/quota-summary.test.ts b/gui/tests/quota-summary.test.ts index 58099679744..5f16697081e 100644 --- a/gui/tests/quota-summary.test.ts +++ b/gui/tests/quota-summary.test.ts @@ -104,6 +104,18 @@ describe("quota summary", () => { expect(buildQuotaSummary(reports, name).map(row => formatQuotaPercent(row.headline.percent))).toEqual(["7%", "6%"]); }); + test("mixed package decimals keep the exact below-half balance through the report", () => { + const balance = (second: string) => parseWorkBuddyCredits({ Packages: ["0.4975", second].map(remaining => ({ + CycleTotalCapacity: "0.5", CycleUsedCapacity: "0", CycleRemainCapacity: remaining, + })) }); + const wire = JSON.parse(JSON.stringify([ + { provider: "below", updatedAt: now, quota: { updatedAt: now, workbuddyCredits: balance("0.49750000000000005") } }, + { provider: "tie", updatedAt: now, quota: { updatedAt: now, workbuddyCredits: balance("0.4975") } }, + ])); + expect(buildQuotaSummary(freshQuotaReportsFromResponse(wire, now), name) + .map(row => formatQuotaPercent(row.headline.percent))).toEqual(["0%", "1%"]); + }); + 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([ @@ -129,6 +141,16 @@ describe("quota summary", () => { expect(rows[0]!.windows.map(window => window.labelKey)).toEqual(["quota.weeklyLimit"]); }); + test("invalid exact WorkBuddy metadata omits its percentage while preserving regular windows", () => { + const reports = freshQuotaReportsFromResponse([{ provider: "mixed", updatedAt: now, + quota: { updatedAt: now, weeklyPercent: 25, workbuddyCredits: { + total: 1, used: 0, remaining: 0.995, frozen: 0, groups: [], exact: { total: "1", remaining: "2" }, + } } }], now); + const [row] = buildQuotaSummary(reports, name); + expect(row!.headline.percent).toBe(25); + expect(row!.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 b96ebdfedea..12a29b9cabb 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, remainingWorkBuddyCredits, workBuddyCapacity, workBuddyRecord, type WorkBuddyCreditBalance } from "../workbuddy-credit-balance"; +import { enterpriseWorkBuddyCredits, parseWorkBuddyCredits, workBuddyCapacity, workBuddyRecord, type WorkBuddyCreditBalance } from "../workbuddy-credit-balance"; import { REQUEST_TIMEOUT_MS } from "../quota-wire"; import { TERMINAL_QUOTA_FAILURE, type ProviderQuotaProbeResult } from "./report-cache"; @@ -65,9 +65,7 @@ export async function fetchWorkBuddyQuota(provider: string, credential: OAuthCre let credits = parseWorkBuddyCredits(summary); if (credential.workbuddy.enterpriseId && (!credits || credits.total === 0)) { 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: [] }; + credits = enterpriseWorkBuddyCredits(team.limitNum, team.credit); } 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 441a7bc92cc..ae63ed0b545 100644 --- a/src/providers/workbuddy-credit-balance.ts +++ b/src/providers/workbuddy-credit-balance.ts @@ -1,3 +1,5 @@ +import { formatWorkBuddyDecimal, parseWorkBuddyDecimal, roundedWorkBuddyUnavailable, subtractWorkBuddyDecimals, sumWorkBuddyDecimals, type WorkBuddyDecimal } from "./workbuddy-decimal"; + export interface WorkBuddyCreditAmount { total: number; used: number; @@ -12,6 +14,8 @@ export type WorkBuddyCreditKind = typeof WORKBUDDY_CREDIT_KINDS[number]; export interface WorkBuddyCreditBalance extends WorkBuddyCreditAmount { groups: Array; expiring?: { amount: number; at: number }; + /** Optional exact display inputs; null marks malformed or inconsistent metadata. */ + exact?: { total: string; remaining: string } | null; } export function workBuddyRecord(value: unknown): Record { @@ -19,7 +23,7 @@ export function workBuddyRecord(value: unknown): Record { } export function workBuddyCapacity(value: unknown): number | undefined { - if (typeof value !== "number" && !(typeof value === "string" && /^\d+(?:\.\d+)?$/.test(value))) return undefined; + if (typeof value !== "number" && !(typeof value === "string" && value.length <= 384 && /^\d+(?:\.\d+)?$/.test(value))) return undefined; const number = Number(value); return Number.isFinite(number) && number >= 0 && number <= Number.MAX_SAFE_INTEGER ? number : undefined; } @@ -75,27 +79,43 @@ export function normalizeWorkBuddyCredits(value: unknown): WorkBuddyCreditBalanc } 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 } } : {}) }; + let exact: WorkBuddyCreditBalance["exact"]; + if (Object.hasOwn(row, "exact")) { + const raw = workBuddyRecord(row.exact); + const total = typeof raw.total === "string" ? parseWorkBuddyDecimal(raw.total) : undefined; + const remaining = typeof raw.remaining === "string" ? parseWorkBuddyDecimal(raw.remaining) : undefined; + exact = total && remaining && Number(raw.total) === balance.total && Number(raw.remaining) === balance.remaining + ? { total: formatWorkBuddyDecimal(total), remaining: formatWorkBuddyDecimal(remaining) } : null; + } + return { ...balance, groups, ...(exact !== undefined ? { exact } : {}), ...(quantity !== undefined && quantity > 0 && at !== undefined ? { expiring: { amount: quantity, at } } : {}) }; } -function packageAmount(row: Record): WorkBuddyCreditAmount | undefined { +function packageAmount(row: Record): { amount: WorkBuddyCreditAmount; total: WorkBuddyDecimal; remaining: WorkBuddyDecimal } | 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 totalDecimal = parseWorkBuddyDecimal(row.CycleTotalCapacity), usedDecimal = parseWorkBuddyDecimal(row.CycleUsedCapacity); + const frozenDecimal = parseWorkBuddyDecimal(row.CycleFrozenCapacity ?? 0); + if (total === undefined || used === undefined || frozen === undefined || !totalDecimal || !usedDecimal || !frozenDecimal) return undefined; + const remainingDecimal = row.CycleRemainCapacity === undefined + ? subtractWorkBuddyDecimals(totalDecimal, usedDecimal, frozenDecimal) : parseWorkBuddyDecimal(row.CycleRemainCapacity); + if (!remainingDecimal || (row.CycleRemainCapacity !== undefined && workBuddyCapacity(row.CycleRemainCapacity) === undefined)) return undefined; + return { amount: { total, used, remaining: Number(formatWorkBuddyDecimal(remainingDecimal)), frozen }, total: totalDecimal, remaining: remainingDecimal }; } 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 totals: WorkBuddyDecimal[] = [], remaining: WorkBuddyDecimal[] = []; for (const raw of summary.Packages) { const quantities = packageAmount(workBuddyRecord(raw)); if (!quantities) return undefined; - packages.push(quantities); + packages.push(quantities.amount); totals.push(quantities.total); remaining.push(quantities.remaining); } - const balance: WorkBuddyCreditBalance = { ...sumAmounts(packages), groups: [] }; + const totalExact = formatWorkBuddyDecimal(sumWorkBuddyDecimals(totals)); + const remainingExact = formatWorkBuddyDecimal(sumWorkBuddyDecimals(remaining)); + const balance: WorkBuddyCreditBalance = { ...sumAmounts(packages), total: Number(totalExact), remaining: Number(remainingExact), + exact: { total: totalExact, remaining: remainingExact }, 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(); @@ -104,10 +124,27 @@ export function parseWorkBuddyCredits(value: unknown): WorkBuddyCreditBalance | if (!quantities) continue; const kind = WORKBUDDY_CREDIT_KINDS.find(kind => kind === row.Kind) ?? "other"; const rows = grouped.get(kind) ?? []; - rows.push(quantities); + rows.push(quantities.amount); grouped.set(kind, rows); } balance.groups = [...grouped].map(([kind, rows]) => ({ kind, ...sumAmounts(rows) })); } return normalizeWorkBuddyCredits(balance); } + +/** Construct an enterprise balance without rounding subtraction before display. */ +export function enterpriseWorkBuddyCredits(totalValue: unknown, usedValue: unknown): WorkBuddyCreditBalance | undefined { + const total = workBuddyCapacity(totalValue), used = workBuddyCapacity(usedValue); + const totalDecimal = parseWorkBuddyDecimal(totalValue), usedDecimal = parseWorkBuddyDecimal(usedValue); + if (total === undefined || used === undefined || !totalDecimal || !usedDecimal) return undefined; + const remaining = formatWorkBuddyDecimal(subtractWorkBuddyDecimals(totalDecimal, usedDecimal)); + return { total, used, remaining: Number(remaining), frozen: 0, groups: [], exact: { total: formatWorkBuddyDecimal(totalDecimal), remaining } }; +} + +/** Percent is informational; malformed exact metadata must not masquerade as an exact result. */ +export function workBuddyUnavailablePercent(balance: WorkBuddyCreditBalance): number | undefined { + if (balance.total <= 0 || balance.remaining / balance.total > 1 + Number.EPSILON * 1024 || balance.exact === null) return undefined; + const total = parseWorkBuddyDecimal(balance.exact?.total ?? balance.total); + const remaining = parseWorkBuddyDecimal(balance.exact?.remaining ?? balance.remaining); + return total && remaining && total.digits > 0n ? roundedWorkBuddyUnavailable(total, remaining) : undefined; +} diff --git a/src/providers/workbuddy-decimal.ts b/src/providers/workbuddy-decimal.ts new file mode 100644 index 00000000000..606f9203685 --- /dev/null +++ b/src/providers/workbuddy-decimal.ts @@ -0,0 +1,52 @@ +/** Bounded decimal arithmetic for WorkBuddy's informational credit balances. */ +export interface WorkBuddyDecimal { digits: bigint; scale: number } + +const MAX_DECIMAL_LENGTH = 384; +const MAX_SCALE = 324; + +/** Parse the original decimal string, or the decimal representation of an already parsed number. */ +export function parseWorkBuddyDecimal(value: unknown): WorkBuddyDecimal | undefined { + if (typeof value !== "string" && typeof value !== "number") return undefined; + if (typeof value === "number" && (!Number.isFinite(value) || value < 0 || value > Number.MAX_SAFE_INTEGER)) return undefined; + const text = String(value); + if (text.length > MAX_DECIMAL_LENGTH) return undefined; + // Exponents are accepted only for numbers: the public provider input accepts decimal strings. + const match = (typeof value === "number" ? /^(\d+)(?:\.(\d+))?(?:e([+-]?\d{1,3}))?$/i : /^(\d+)(?:\.(\d+))?$/).exec(text); + if (!match) return undefined; + const exponent = Number(match[3] ?? 0); + let scale = (match[2]?.length ?? 0) - exponent; + if (Math.abs(exponent) > MAX_SCALE || scale > MAX_SCALE || scale < -MAX_SCALE) return undefined; + let digits = BigInt(`${match[1]}${match[2] ?? ""}`); + if (scale < 0) { digits *= 10n ** BigInt(-scale); scale = 0; } + while (scale > 0 && digits % 10n === 0n) { digits /= 10n; scale--; } + return { digits, scale }; +} + +export function sumWorkBuddyDecimals(values: readonly WorkBuddyDecimal[]): WorkBuddyDecimal { + const scale = values.reduce((max, value) => Math.max(max, value.scale), 0); + const digits = values.reduce((sum, value) => sum + value.digits * 10n ** BigInt(scale - value.scale), 0n); + return { digits, scale }; +} + +export function subtractWorkBuddyDecimals(total: WorkBuddyDecimal, ...values: WorkBuddyDecimal[]): WorkBuddyDecimal { + const scale = [total, ...values].reduce((max, value) => Math.max(max, value.scale), 0); + const scaled = (value: WorkBuddyDecimal) => value.digits * 10n ** BigInt(scale - value.scale); + const digits = values.reduce((left, value) => left - scaled(value), scaled(total)); + return { digits: digits > 0n ? digits : 0n, scale }; +} + +export function formatWorkBuddyDecimal(value: WorkBuddyDecimal): string { + let digits = value.digits, scale = value.scale; + while (scale > 0 && digits % 10n === 0n) { digits /= 10n; scale--; } + const text = digits.toString().padStart(scale + 1, "0"); + return scale ? `${text.slice(0, -scale)}.${text.slice(-scale)}` : text; +} + +/** Nearest integer, with an exact half rounded up; caller validates the balance. */ +export function roundedWorkBuddyUnavailable(total: WorkBuddyDecimal, remaining: WorkBuddyDecimal): number { + const scale = Math.max(total.scale, remaining.scale); + const totalDigits = total.digits * 10n ** BigInt(scale - total.scale); + const remainingDigits = remaining.digits * 10n ** BigInt(scale - remaining.scale); + const available = remainingDigits > totalDigits ? totalDigits : remainingDigits; + return Number(((totalDigits - available) * 200n + totalDigits) / (2n * totalDigits)); +} diff --git a/structure/dashboard-and-usage.md b/structure/dashboard-and-usage.md index a39fece4261..8450652b73d 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. 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. +`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. Bounded exact decimal totals preserve package aggregation across the quota DTO; legacy numeric-only responses retain their prior display. `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 a7997f07e5f..1400b008d17 100644 --- a/structure/providers/workbuddy.md +++ b/structure/providers/workbuddy.md @@ -38,8 +38,10 @@ 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 using the decimal representation of each validated -number before returning numeric totals, and treats `CreditGroups` as a breakdown; +fixed-origin API helper. It sums `Packages` once using bounded decimal arithmetic and retains the +existing numeric totals alongside optional exact total/remaining strings for the informational +headline. Quoted provider decimals retain their input precision; JSON numbers have already been +parsed as JavaScript numbers. `CreditGroups` is a breakdown; explicit remaining/frozen amounts take precedence over arithmetic estimates. Team accounts use the enterprise meter when the personal summary has no capacity; estimated remaining credits use decimal subtraction on validated amounts. Optional paid/free package @@ -52,8 +54,9 @@ 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 numeric fields and bounded exact decimal +metadata for the GUI. Invalid or inconsistent exact metadata suppresses the headline percentage; +older payloads without it keep the numeric fallback. 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 diff --git a/tests/providers/workbuddy-quota.test.ts b/tests/providers/workbuddy-quota.test.ts index 15bba422d42..8e730949c81 100644 --- a/tests/providers/workbuddy-quota.test.ts +++ b/tests/providers/workbuddy-quota.test.ts @@ -35,6 +35,18 @@ test("decimal package totals preserve the reported remaining balance", () => { expect(parseWorkBuddyCredits({ Packages: [{ CycleTotalCapacity: 1e-300, CycleUsedCapacity: 0, CycleRemainCapacity: 5e-301 }] })?.remaining).toBe(5e-301); }); +test("exact balance metadata stays bounded, validates its numeric projection, and survives JSON", () => { + const balance = parseWorkBuddyCredits({ Packages: [amounts("0.5", "0", "0.4975"), amounts("0.5", "0", "0.49750000000000005")] })!; + expect(balance.exact).toEqual({ total: "1", remaining: "0.99500000000000005" }); + expect(normalizeWorkBuddyCredits(JSON.parse(JSON.stringify(balance)))?.exact).toEqual(balance.exact); + for (const exact of [null, {}, { total: "1", remaining: "2" }, { total: "1e0", remaining: "0.995" }, + { total: "1", remaining: `0.${"0".repeat(384)}1` }]) { + expect(normalizeWorkBuddyCredits({ ...balance, exact })?.exact).toBeNull(); + } + expect(parseWorkBuddyCredits({ Packages: [amounts("1", "0", `0.${"0".repeat(384)}1`)] })).toBeUndefined(); + expect(normalizeWorkBuddyCredits({ total: 1, used: 0, remaining: 0.995, frozen: 0, groups: [] })?.exact).toBeUndefined(); +}); + 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; From 5d75869cf486098c030b27b3e85243176e7438fc Mon Sep 17 00:00:00 2001 From: JUN Date: Sun, 8 Nov 2026 14:21:57 +0900 Subject: [PATCH 10/12] fix(workbuddy): validate exact balances before rounding --- gui/tests/quota-summary.test.ts | 14 ++++++++++++++ src/providers/workbuddy-credit-balance.ts | 9 ++++++--- src/providers/workbuddy-decimal.ts | 7 +++++++ structure/providers/workbuddy.md | 5 +++-- 4 files changed, 30 insertions(+), 5 deletions(-) diff --git a/gui/tests/quota-summary.test.ts b/gui/tests/quota-summary.test.ts index 5f16697081e..8b01f0c9bc4 100644 --- a/gui/tests/quota-summary.test.ts +++ b/gui/tests/quota-summary.test.ts @@ -116,6 +116,20 @@ describe("quota summary", () => { .map(row => formatQuotaPercent(row.headline.percent))).toEqual(["0%", "1%"]); }); + test("exact balances retain subnormal precision and reject exact overdraw", () => { + const small = (digit: string) => `0.${"0".repeat(323)}${digit}`; + const balance = (total: string, remaining: string) => parseWorkBuddyCredits({ Packages: [{ + CycleTotalCapacity: total, CycleUsedCapacity: "0", CycleRemainCapacity: remaining, + }] }); + const reports = freshQuotaReportsFromResponse([ + { provider: "tiny", updatedAt: now, quota: { updatedAt: now, workbuddyCredits: balance(small("2"), small("1")) } }, + { provider: "tiny-over", updatedAt: now, quota: { updatedAt: now, workbuddyCredits: balance(small("4"), small("7")) } }, + { provider: "over", updatedAt: now, quota: { updatedAt: now, workbuddyCredits: balance("1", "1.00000000000000005") } }, + ], now); + expect(buildQuotaSummary(reports, name).map(row => [row.provider, formatQuotaPercent(row.headline.percent)])) + .toEqual([["tiny", "50%"]]); + }); + 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([ diff --git a/src/providers/workbuddy-credit-balance.ts b/src/providers/workbuddy-credit-balance.ts index ae63ed0b545..b74559817bb 100644 --- a/src/providers/workbuddy-credit-balance.ts +++ b/src/providers/workbuddy-credit-balance.ts @@ -1,4 +1,4 @@ -import { formatWorkBuddyDecimal, parseWorkBuddyDecimal, roundedWorkBuddyUnavailable, subtractWorkBuddyDecimals, sumWorkBuddyDecimals, type WorkBuddyDecimal } from "./workbuddy-decimal"; +import { compareWorkBuddyDecimals, formatWorkBuddyDecimal, parseWorkBuddyDecimal, roundedWorkBuddyUnavailable, subtractWorkBuddyDecimals, sumWorkBuddyDecimals, type WorkBuddyDecimal } from "./workbuddy-decimal"; export interface WorkBuddyCreditAmount { total: number; @@ -143,8 +143,11 @@ export function enterpriseWorkBuddyCredits(totalValue: unknown, usedValue: unkno /** Percent is informational; malformed exact metadata must not masquerade as an exact result. */ export function workBuddyUnavailablePercent(balance: WorkBuddyCreditBalance): number | undefined { - if (balance.total <= 0 || balance.remaining / balance.total > 1 + Number.EPSILON * 1024 || balance.exact === null) return undefined; + if (balance.exact === null) return undefined; const total = parseWorkBuddyDecimal(balance.exact?.total ?? balance.total); const remaining = parseWorkBuddyDecimal(balance.exact?.remaining ?? balance.remaining); - return total && remaining && total.digits > 0n ? roundedWorkBuddyUnavailable(total, remaining) : undefined; + if (!total || !remaining || total.digits === 0n) return undefined; + if (balance.exact ? compareWorkBuddyDecimals(remaining, total) > 0 + : balance.remaining / balance.total > 1 + Number.EPSILON * 1024) return undefined; + return roundedWorkBuddyUnavailable(total, remaining); } diff --git a/src/providers/workbuddy-decimal.ts b/src/providers/workbuddy-decimal.ts index 606f9203685..f4f8988ea46 100644 --- a/src/providers/workbuddy-decimal.ts +++ b/src/providers/workbuddy-decimal.ts @@ -35,6 +35,13 @@ export function subtractWorkBuddyDecimals(total: WorkBuddyDecimal, ...values: Wo return { digits: digits > 0n ? digits : 0n, scale }; } +export function compareWorkBuddyDecimals(a: WorkBuddyDecimal, b: WorkBuddyDecimal): number { + const scale = Math.max(a.scale, b.scale); + const left = a.digits * 10n ** BigInt(scale - a.scale); + const right = b.digits * 10n ** BigInt(scale - b.scale); + return left < right ? -1 : left > right ? 1 : 0; +} + export function formatWorkBuddyDecimal(value: WorkBuddyDecimal): string { let digits = value.digits, scale = value.scale; while (scale > 0 && digits % 10n === 0n) { digits /= 10n; scale--; } diff --git a/structure/providers/workbuddy.md b/structure/providers/workbuddy.md index 1400b008d17..1744869b591 100644 --- a/structure/providers/workbuddy.md +++ b/structure/providers/workbuddy.md @@ -55,8 +55,9 @@ semantics. Unknown or malformed summaries never become zero. Explicit zero balan `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 numeric fields and bounded exact decimal -metadata for the GUI. Invalid or inconsistent exact metadata suppresses the headline percentage; -older payloads without it keep the numeric fallback. The shared provider quota panel shows the remaining credits, usage, group balances and +metadata for the GUI. Invalid metadata or an exact remaining amount above the exact total +suppresses the headline percentage, including at subnormal magnitudes; older payloads without +exact metadata keep the numeric fallback. 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 From 5c7e4becaf2f0c81f69b646d8ea44ecafb078770 Mon Sep 17 00:00:00 2001 From: JUN Date: Sun, 8 Nov 2026 14:29:47 +0900 Subject: [PATCH 11/12] fix(workbuddy): sum credit amounts before number conversion --- src/providers/quota/workbuddy.ts | 6 ++-- src/providers/workbuddy-credit-balance.ts | 36 ++++++++++++++++------- structure/providers/workbuddy.md | 7 +++-- tests/providers/workbuddy-quota.test.ts | 32 ++++++++++++++++++++ 4 files changed, 64 insertions(+), 17 deletions(-) diff --git a/src/providers/quota/workbuddy.ts b/src/providers/quota/workbuddy.ts index 12a29b9cabb..db85bc1c999 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 { enterpriseWorkBuddyCredits, parseWorkBuddyCredits, workBuddyCapacity, workBuddyRecord, type WorkBuddyCreditBalance } from "../workbuddy-credit-balance"; +import { enterpriseWorkBuddyCredits, hasWorkBuddyCredits, parseWorkBuddyCredits, workBuddyCapacity, workBuddyRecord, type WorkBuddyCreditBalance } from "../workbuddy-credit-balance"; import { REQUEST_TIMEOUT_MS } from "../quota-wire"; import { TERMINAL_QUOTA_FAILURE, type ProviderQuotaProbeResult } from "./report-cache"; @@ -63,12 +63,12 @@ export async function fetchWorkBuddyQuota(provider: string, credential: OAuthCre const headers = workBuddyHeaders(credential.access, credential.workbuddy); const summary = await workBuddyApi("/billing/meter/get-user-resource-summary", headers, signal, true); let credits = parseWorkBuddyCredits(summary); - if (credential.workbuddy.enterpriseId && (!credits || credits.total === 0)) { + if (credential.workbuddy.enterpriseId && (!credits || !hasWorkBuddyCredits(credits, "total"))) { const team = await workBuddyApi("/billing/meter/get-enterprise-user-usage", headers, signal, true); credits = enterpriseWorkBuddyCredits(team.limitNum, team.credit); } if (!credits) return null; - if (credits.remaining > 0) { + if (hasWorkBuddyCredits(credits, "remaining")) { // Optional expiry failures must not erase a successful balance reading. credits.expiring = await expiringCredits(summary, headers, signal, now).catch(() => undefined); } diff --git a/src/providers/workbuddy-credit-balance.ts b/src/providers/workbuddy-credit-balance.ts index b74559817bb..df1ebbf77ec 100644 --- a/src/providers/workbuddy-credit-balance.ts +++ b/src/providers/workbuddy-credit-balance.ts @@ -43,12 +43,17 @@ function sumCapacities(values: readonly number[]): number { return Number(`${digits}e-${scale}`); } -function sumAmounts(rows: readonly WorkBuddyCreditAmount[]): WorkBuddyCreditAmount { +interface ParsedWorkBuddyAmount { + total: WorkBuddyDecimal; + used: WorkBuddyDecimal; + remaining: WorkBuddyDecimal; + frozen: WorkBuddyDecimal; +} + +function sumAmounts(rows: readonly ParsedWorkBuddyAmount[]): WorkBuddyCreditAmount { + const sum = (field: keyof ParsedWorkBuddyAmount) => Number(formatWorkBuddyDecimal(sumWorkBuddyDecimals(rows.map(row => row[field])))); 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)), + total: sum("total"), used: sum("used"), remaining: sum("remaining"), frozen: sum("frozen"), }; } @@ -90,7 +95,7 @@ export function normalizeWorkBuddyCredits(value: unknown): WorkBuddyCreditBalanc return { ...balance, groups, ...(exact !== undefined ? { exact } : {}), ...(quantity !== undefined && quantity > 0 && at !== undefined ? { expiring: { amount: quantity, at } } : {}) }; } -function packageAmount(row: Record): { amount: WorkBuddyCreditAmount; total: WorkBuddyDecimal; remaining: WorkBuddyDecimal } | undefined { +function packageAmount(row: Record): ParsedWorkBuddyAmount | undefined { const total = workBuddyCapacity(row.CycleTotalCapacity), used = workBuddyCapacity(row.CycleUsedCapacity); const frozen = row.CycleFrozenCapacity === undefined ? 0 : workBuddyCapacity(row.CycleFrozenCapacity); const totalDecimal = parseWorkBuddyDecimal(row.CycleTotalCapacity), usedDecimal = parseWorkBuddyDecimal(row.CycleUsedCapacity); @@ -99,18 +104,18 @@ function packageAmount(row: Record): { amount: WorkBuddyCreditA const remainingDecimal = row.CycleRemainCapacity === undefined ? subtractWorkBuddyDecimals(totalDecimal, usedDecimal, frozenDecimal) : parseWorkBuddyDecimal(row.CycleRemainCapacity); if (!remainingDecimal || (row.CycleRemainCapacity !== undefined && workBuddyCapacity(row.CycleRemainCapacity) === undefined)) return undefined; - return { amount: { total, used, remaining: Number(formatWorkBuddyDecimal(remainingDecimal)), frozen }, total: totalDecimal, remaining: remainingDecimal }; + return { total: totalDecimal, used: usedDecimal, remaining: remainingDecimal, frozen: frozenDecimal }; } 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: ParsedWorkBuddyAmount[] = []; const totals: WorkBuddyDecimal[] = [], remaining: WorkBuddyDecimal[] = []; for (const raw of summary.Packages) { const quantities = packageAmount(workBuddyRecord(raw)); if (!quantities) return undefined; - packages.push(quantities.amount); totals.push(quantities.total); remaining.push(quantities.remaining); + packages.push(quantities); totals.push(quantities.total); remaining.push(quantities.remaining); } const totalExact = formatWorkBuddyDecimal(sumWorkBuddyDecimals(totals)); const remainingExact = formatWorkBuddyDecimal(sumWorkBuddyDecimals(remaining)); @@ -118,13 +123,13 @@ export function parseWorkBuddyCredits(value: unknown): WorkBuddyCreditBalance | exact: { total: totalExact, remaining: remainingExact }, 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(); + 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 rows = grouped.get(kind) ?? []; - rows.push(quantities.amount); + rows.push(quantities); grouped.set(kind, rows); } balance.groups = [...grouped].map(([kind, rows]) => ({ kind, ...sumAmounts(rows) })); @@ -141,6 +146,15 @@ export function enterpriseWorkBuddyCredits(totalValue: unknown, usedValue: unkno return { total, used, remaining: Number(remaining), frozen: 0, groups: [], exact: { total: formatWorkBuddyDecimal(totalDecimal), remaining } }; } +/** Use exact metadata for zero checks so subnormal balances do not disappear. */ +export function hasWorkBuddyCredits(balance: WorkBuddyCreditBalance, field: "total" | "remaining"): boolean { + if (balance.exact) { + const value = parseWorkBuddyDecimal(balance.exact[field]); + if (value) return value.digits > 0n; + } + return balance[field] > 0; +} + /** Percent is informational; malformed exact metadata must not masquerade as an exact result. */ export function workBuddyUnavailablePercent(balance: WorkBuddyCreditBalance): number | undefined { if (balance.exact === null) return undefined; diff --git a/structure/providers/workbuddy.md b/structure/providers/workbuddy.md index 1744869b591..9cce822d082 100644 --- a/structure/providers/workbuddy.md +++ b/structure/providers/workbuddy.md @@ -40,11 +40,12 @@ Unavailable discovery degrades to the same-account cache, then the minimal `defa `src/providers/quota/workbuddy.ts` reads the authenticated resource summary through the bounded, fixed-origin API helper. It sums `Packages` once using bounded decimal arithmetic and retains the existing numeric totals alongside optional exact total/remaining strings for the informational -headline. Quoted provider decimals retain their input precision; JSON numbers have already been +headline. Total, used, remaining, frozen and group amounts are summed before conversion to +numbers. Quoted provider decimals retain their input precision; JSON numbers have already been parsed as JavaScript numbers. `CreditGroups` is a breakdown; explicit remaining/frozen amounts take precedence over arithmetic estimates. Team accounts use -the enterprise meter when the personal summary has no capacity; estimated remaining credits use -decimal subtraction on validated amounts. Optional paid/free package +the enterprise meter when the personal summary has no capacity, with that decision made using the +exact total when available; 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 8e730949c81..10af6d064e6 100644 --- a/tests/providers/workbuddy-quota.test.ts +++ b/tests/providers/workbuddy-quota.test.ts @@ -47,6 +47,38 @@ test("exact balance metadata stays bounded, validates its numeric projection, an expect(normalizeWorkBuddyCredits({ total: 1, used: 0, remaining: 0.995, frozen: 0, groups: [] })?.exact).toBeUndefined(); }); +test("all package and group amounts are summed before conversion to numbers", () => { + const row = { CycleTotalCapacity: "0.10000000000000001", CycleUsedCapacity: "0.10000000000000001", + CycleRemainCapacity: "0", CycleFrozenCapacity: "0.10000000000000001" }; + const balance = parseWorkBuddyCredits({ Packages: [row, row, row], + CreditGroups: [{ ...row, Kind: "benefit" }, { ...row, Kind: "benefit" }, { ...row, Kind: "benefit" }] })!; + expect(balance).toMatchObject({ total: 0.30000000000000004, used: 0.30000000000000004, frozen: 0.30000000000000004 }); + expect(balance.groups[0]).toMatchObject({ total: 0.30000000000000004, used: 0.30000000000000004, frozen: 0.30000000000000004 }); + const tiny = `0.${"0".repeat(323)}2`; + const tinyRow = { CycleTotalCapacity: tiny, CycleUsedCapacity: tiny, CycleFrozenCapacity: tiny, CycleRemainCapacity: "0" }; + const tinyBalance = parseWorkBuddyCredits({ Packages: [tinyRow, tinyRow, tinyRow], + CreditGroups: [{ ...tinyRow, Kind: "benefit" }, { ...tinyRow, Kind: "benefit" }, { ...tinyRow, Kind: "benefit" }] })!; + expect(tinyBalance).toMatchObject({ total: 5e-324, used: 5e-324, frozen: 5e-324 }); + expect(tinyBalance.groups[0]).toMatchObject({ total: 5e-324, used: 5e-324, frozen: 5e-324 }); +}); + +test("enterprise fallback retains a positive personal balance that underflows as a number", async () => { + const tiny = (digit: string) => `0.${"0".repeat(323)}${digit}`; + const requests: string[] = []; + globalThis.fetch = (async input => { + requests.push(String(input)); + return Response.json({ code: 0, data: String(input).endsWith("summary") + ? { Packages: [{ CycleTotalCapacity: tiny("2"), CycleUsedCapacity: "0", CycleRemainCapacity: tiny("1") }] } + : { limitNum: "100", credit: "0" } }); + }) as typeof fetch; + const credential = credentials(); + credential.workbuddy!.enterpriseId = "fixture-team"; + const report = await fetchWorkBuddyQuota("workbuddy-ai", credential); + const rows = buildQuotaSummary(freshQuotaReportsFromResponse([report]), provider => provider); + expect(formatQuotaPercent(rows[0]?.headline.percent)).toBe("50%"); + expect(requests.some(url => url.endsWith("get-enterprise-user-usage"))).toBe(false); +}); + 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; From d123a6c6171516a20e6b1a202c2b7661cd65e1dd Mon Sep 17 00:00:00 2001 From: JUN Date: Sun, 8 Nov 2026 14:47:50 +0900 Subject: [PATCH 12/12] fix(workbuddy): keep quota change within display scope Defer exact-decimal DTO preservation to #8324. Co-authored-by: Rafael Moreira Lima --- gui/src/quota-summary.ts | 25 +++++-- gui/tests/quota-summary.test.ts | 36 ---------- src/providers/quota/workbuddy.ts | 10 +-- src/providers/workbuddy-credit-balance.ts | 84 ++++------------------- src/providers/workbuddy-decimal.ts | 59 ---------------- structure/dashboard-and-usage.md | 2 +- structure/providers/workbuddy.md | 17 ++--- tests/providers/workbuddy-quota.test.ts | 44 ------------ 8 files changed, 49 insertions(+), 228 deletions(-) delete mode 100644 src/providers/workbuddy-decimal.ts diff --git a/gui/src/quota-summary.ts b/gui/src/quota-summary.ts index 0f5dd544873..5ddaa39db33 100644 --- a/gui/src/quota-summary.ts +++ b/gui/src/quota-summary.ts @@ -9,7 +9,6 @@ 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 { workBuddyUnavailablePercent } from "../../src/providers/workbuddy-credit-balance"; export const QUOTA_SUMMARY_WARN_PERCENT = 70; export const QUOTA_SUMMARY_CRITICAL_PERCENT = 90; @@ -52,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"]; @@ -83,13 +99,14 @@ function summaryWindows(quota: AccountQuota): QuotaSummaryWindow[] { }); } const workbuddy = quota.workbuddyCredits; - const workbuddyPercent = workbuddy ? workBuddyUnavailablePercent(workbuddy) : undefined; - if (workbuddyPercent !== undefined) { + // 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: workbuddyPercent, + percent, severity: "normal", }); } diff --git a/gui/tests/quota-summary.test.ts b/gui/tests/quota-summary.test.ts index 8b01f0c9bc4..58099679744 100644 --- a/gui/tests/quota-summary.test.ts +++ b/gui/tests/quota-summary.test.ts @@ -104,32 +104,6 @@ describe("quota summary", () => { expect(buildQuotaSummary(reports, name).map(row => formatQuotaPercent(row.headline.percent))).toEqual(["7%", "6%"]); }); - test("mixed package decimals keep the exact below-half balance through the report", () => { - const balance = (second: string) => parseWorkBuddyCredits({ Packages: ["0.4975", second].map(remaining => ({ - CycleTotalCapacity: "0.5", CycleUsedCapacity: "0", CycleRemainCapacity: remaining, - })) }); - const wire = JSON.parse(JSON.stringify([ - { provider: "below", updatedAt: now, quota: { updatedAt: now, workbuddyCredits: balance("0.49750000000000005") } }, - { provider: "tie", updatedAt: now, quota: { updatedAt: now, workbuddyCredits: balance("0.4975") } }, - ])); - expect(buildQuotaSummary(freshQuotaReportsFromResponse(wire, now), name) - .map(row => formatQuotaPercent(row.headline.percent))).toEqual(["0%", "1%"]); - }); - - test("exact balances retain subnormal precision and reject exact overdraw", () => { - const small = (digit: string) => `0.${"0".repeat(323)}${digit}`; - const balance = (total: string, remaining: string) => parseWorkBuddyCredits({ Packages: [{ - CycleTotalCapacity: total, CycleUsedCapacity: "0", CycleRemainCapacity: remaining, - }] }); - const reports = freshQuotaReportsFromResponse([ - { provider: "tiny", updatedAt: now, quota: { updatedAt: now, workbuddyCredits: balance(small("2"), small("1")) } }, - { provider: "tiny-over", updatedAt: now, quota: { updatedAt: now, workbuddyCredits: balance(small("4"), small("7")) } }, - { provider: "over", updatedAt: now, quota: { updatedAt: now, workbuddyCredits: balance("1", "1.00000000000000005") } }, - ], now); - expect(buildQuotaSummary(reports, name).map(row => [row.provider, formatQuotaPercent(row.headline.percent)])) - .toEqual([["tiny", "50%"]]); - }); - 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([ @@ -155,16 +129,6 @@ describe("quota summary", () => { expect(rows[0]!.windows.map(window => window.labelKey)).toEqual(["quota.weeklyLimit"]); }); - test("invalid exact WorkBuddy metadata omits its percentage while preserving regular windows", () => { - const reports = freshQuotaReportsFromResponse([{ provider: "mixed", updatedAt: now, - quota: { updatedAt: now, weeklyPercent: 25, workbuddyCredits: { - total: 1, used: 0, remaining: 0.995, frozen: 0, groups: [], exact: { total: "1", remaining: "2" }, - } } }], now); - const [row] = buildQuotaSummary(reports, name); - expect(row!.headline.percent).toBe(25); - expect(row!.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 db85bc1c999..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 { enterpriseWorkBuddyCredits, hasWorkBuddyCredits, 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"; @@ -63,12 +63,14 @@ export async function fetchWorkBuddyQuota(provider: string, credential: OAuthCre const headers = workBuddyHeaders(credential.access, credential.workbuddy); const summary = await workBuddyApi("/billing/meter/get-user-resource-summary", headers, signal, true); let credits = parseWorkBuddyCredits(summary); - if (credential.workbuddy.enterpriseId && (!credits || !hasWorkBuddyCredits(credits, "total"))) { + if (credential.workbuddy.enterpriseId && (!credits || credits.total === 0)) { const team = await workBuddyApi("/billing/meter/get-enterprise-user-usage", headers, signal, true); - credits = enterpriseWorkBuddyCredits(team.limitNum, team.credit); + 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: [] }; } if (!credits) return null; - if (hasWorkBuddyCredits(credits, "remaining")) { + if (credits.remaining > 0) { // Optional expiry failures must not erase a successful balance reading. credits.expiring = await expiringCredits(summary, headers, signal, now).catch(() => undefined); } diff --git a/src/providers/workbuddy-credit-balance.ts b/src/providers/workbuddy-credit-balance.ts index df1ebbf77ec..441a7bc92cc 100644 --- a/src/providers/workbuddy-credit-balance.ts +++ b/src/providers/workbuddy-credit-balance.ts @@ -1,5 +1,3 @@ -import { compareWorkBuddyDecimals, formatWorkBuddyDecimal, parseWorkBuddyDecimal, roundedWorkBuddyUnavailable, subtractWorkBuddyDecimals, sumWorkBuddyDecimals, type WorkBuddyDecimal } from "./workbuddy-decimal"; - export interface WorkBuddyCreditAmount { total: number; used: number; @@ -14,8 +12,6 @@ export type WorkBuddyCreditKind = typeof WORKBUDDY_CREDIT_KINDS[number]; export interface WorkBuddyCreditBalance extends WorkBuddyCreditAmount { groups: Array; expiring?: { amount: number; at: number }; - /** Optional exact display inputs; null marks malformed or inconsistent metadata. */ - exact?: { total: string; remaining: string } | null; } export function workBuddyRecord(value: unknown): Record { @@ -23,7 +19,7 @@ export function workBuddyRecord(value: unknown): Record { } export function workBuddyCapacity(value: unknown): number | undefined { - if (typeof value !== "number" && !(typeof value === "string" && value.length <= 384 && /^\d+(?:\.\d+)?$/.test(value))) return undefined; + if (typeof value !== "number" && !(typeof value === "string" && /^\d+(?:\.\d+)?$/.test(value))) return undefined; const number = Number(value); return Number.isFinite(number) && number >= 0 && number <= Number.MAX_SAFE_INTEGER ? number : undefined; } @@ -43,17 +39,12 @@ function sumCapacities(values: readonly number[]): number { return Number(`${digits}e-${scale}`); } -interface ParsedWorkBuddyAmount { - total: WorkBuddyDecimal; - used: WorkBuddyDecimal; - remaining: WorkBuddyDecimal; - frozen: WorkBuddyDecimal; -} - -function sumAmounts(rows: readonly ParsedWorkBuddyAmount[]): WorkBuddyCreditAmount { - const sum = (field: keyof ParsedWorkBuddyAmount) => Number(formatWorkBuddyDecimal(sumWorkBuddyDecimals(rows.map(row => row[field])))); +function sumAmounts(rows: readonly WorkBuddyCreditAmount[]): WorkBuddyCreditAmount { return { - total: sum("total"), used: sum("used"), remaining: sum("remaining"), frozen: sum("frozen"), + 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)), }; } @@ -84,46 +75,30 @@ export function normalizeWorkBuddyCredits(value: unknown): WorkBuddyCreditBalanc } 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; - let exact: WorkBuddyCreditBalance["exact"]; - if (Object.hasOwn(row, "exact")) { - const raw = workBuddyRecord(row.exact); - const total = typeof raw.total === "string" ? parseWorkBuddyDecimal(raw.total) : undefined; - const remaining = typeof raw.remaining === "string" ? parseWorkBuddyDecimal(raw.remaining) : undefined; - exact = total && remaining && Number(raw.total) === balance.total && Number(raw.remaining) === balance.remaining - ? { total: formatWorkBuddyDecimal(total), remaining: formatWorkBuddyDecimal(remaining) } : null; - } - return { ...balance, groups, ...(exact !== undefined ? { exact } : {}), ...(quantity !== undefined && quantity > 0 && at !== undefined ? { expiring: { amount: quantity, at } } : {}) }; + return { ...balance, groups, ...(quantity !== undefined && quantity > 0 && at !== undefined ? { expiring: { amount: quantity, at } } : {}) }; } -function packageAmount(row: Record): ParsedWorkBuddyAmount | undefined { +function packageAmount(row: Record): WorkBuddyCreditAmount | undefined { const total = workBuddyCapacity(row.CycleTotalCapacity), used = workBuddyCapacity(row.CycleUsedCapacity); const frozen = row.CycleFrozenCapacity === undefined ? 0 : workBuddyCapacity(row.CycleFrozenCapacity); - const totalDecimal = parseWorkBuddyDecimal(row.CycleTotalCapacity), usedDecimal = parseWorkBuddyDecimal(row.CycleUsedCapacity); - const frozenDecimal = parseWorkBuddyDecimal(row.CycleFrozenCapacity ?? 0); - if (total === undefined || used === undefined || frozen === undefined || !totalDecimal || !usedDecimal || !frozenDecimal) return undefined; - const remainingDecimal = row.CycleRemainCapacity === undefined - ? subtractWorkBuddyDecimals(totalDecimal, usedDecimal, frozenDecimal) : parseWorkBuddyDecimal(row.CycleRemainCapacity); - if (!remainingDecimal || (row.CycleRemainCapacity !== undefined && workBuddyCapacity(row.CycleRemainCapacity) === undefined)) return undefined; - return { total: totalDecimal, used: usedDecimal, remaining: remainingDecimal, frozen: frozenDecimal }; + 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 }; } export function parseWorkBuddyCredits(value: unknown): WorkBuddyCreditBalance | undefined { const summary = workBuddyRecord(value); if (!Array.isArray(summary.Packages) || summary.Packages.length > 512) return undefined; - const packages: ParsedWorkBuddyAmount[] = []; - const totals: WorkBuddyDecimal[] = [], remaining: WorkBuddyDecimal[] = []; + const packages: WorkBuddyCreditAmount[] = []; for (const raw of summary.Packages) { const quantities = packageAmount(workBuddyRecord(raw)); if (!quantities) return undefined; - packages.push(quantities); totals.push(quantities.total); remaining.push(quantities.remaining); + packages.push(quantities); } - const totalExact = formatWorkBuddyDecimal(sumWorkBuddyDecimals(totals)); - const remainingExact = formatWorkBuddyDecimal(sumWorkBuddyDecimals(remaining)); - const balance: WorkBuddyCreditBalance = { ...sumAmounts(packages), total: Number(totalExact), remaining: Number(remainingExact), - exact: { total: totalExact, remaining: remainingExact }, groups: [] }; + 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(); + const grouped = new Map(); for (const raw of summary.CreditGroups) { const row = workBuddyRecord(raw), quantities = packageAmount(row); if (!quantities) continue; @@ -136,32 +111,3 @@ export function parseWorkBuddyCredits(value: unknown): WorkBuddyCreditBalance | } return normalizeWorkBuddyCredits(balance); } - -/** Construct an enterprise balance without rounding subtraction before display. */ -export function enterpriseWorkBuddyCredits(totalValue: unknown, usedValue: unknown): WorkBuddyCreditBalance | undefined { - const total = workBuddyCapacity(totalValue), used = workBuddyCapacity(usedValue); - const totalDecimal = parseWorkBuddyDecimal(totalValue), usedDecimal = parseWorkBuddyDecimal(usedValue); - if (total === undefined || used === undefined || !totalDecimal || !usedDecimal) return undefined; - const remaining = formatWorkBuddyDecimal(subtractWorkBuddyDecimals(totalDecimal, usedDecimal)); - return { total, used, remaining: Number(remaining), frozen: 0, groups: [], exact: { total: formatWorkBuddyDecimal(totalDecimal), remaining } }; -} - -/** Use exact metadata for zero checks so subnormal balances do not disappear. */ -export function hasWorkBuddyCredits(balance: WorkBuddyCreditBalance, field: "total" | "remaining"): boolean { - if (balance.exact) { - const value = parseWorkBuddyDecimal(balance.exact[field]); - if (value) return value.digits > 0n; - } - return balance[field] > 0; -} - -/** Percent is informational; malformed exact metadata must not masquerade as an exact result. */ -export function workBuddyUnavailablePercent(balance: WorkBuddyCreditBalance): number | undefined { - if (balance.exact === null) return undefined; - const total = parseWorkBuddyDecimal(balance.exact?.total ?? balance.total); - const remaining = parseWorkBuddyDecimal(balance.exact?.remaining ?? balance.remaining); - if (!total || !remaining || total.digits === 0n) return undefined; - if (balance.exact ? compareWorkBuddyDecimals(remaining, total) > 0 - : balance.remaining / balance.total > 1 + Number.EPSILON * 1024) return undefined; - return roundedWorkBuddyUnavailable(total, remaining); -} diff --git a/src/providers/workbuddy-decimal.ts b/src/providers/workbuddy-decimal.ts deleted file mode 100644 index f4f8988ea46..00000000000 --- a/src/providers/workbuddy-decimal.ts +++ /dev/null @@ -1,59 +0,0 @@ -/** Bounded decimal arithmetic for WorkBuddy's informational credit balances. */ -export interface WorkBuddyDecimal { digits: bigint; scale: number } - -const MAX_DECIMAL_LENGTH = 384; -const MAX_SCALE = 324; - -/** Parse the original decimal string, or the decimal representation of an already parsed number. */ -export function parseWorkBuddyDecimal(value: unknown): WorkBuddyDecimal | undefined { - if (typeof value !== "string" && typeof value !== "number") return undefined; - if (typeof value === "number" && (!Number.isFinite(value) || value < 0 || value > Number.MAX_SAFE_INTEGER)) return undefined; - const text = String(value); - if (text.length > MAX_DECIMAL_LENGTH) return undefined; - // Exponents are accepted only for numbers: the public provider input accepts decimal strings. - const match = (typeof value === "number" ? /^(\d+)(?:\.(\d+))?(?:e([+-]?\d{1,3}))?$/i : /^(\d+)(?:\.(\d+))?$/).exec(text); - if (!match) return undefined; - const exponent = Number(match[3] ?? 0); - let scale = (match[2]?.length ?? 0) - exponent; - if (Math.abs(exponent) > MAX_SCALE || scale > MAX_SCALE || scale < -MAX_SCALE) return undefined; - let digits = BigInt(`${match[1]}${match[2] ?? ""}`); - if (scale < 0) { digits *= 10n ** BigInt(-scale); scale = 0; } - while (scale > 0 && digits % 10n === 0n) { digits /= 10n; scale--; } - return { digits, scale }; -} - -export function sumWorkBuddyDecimals(values: readonly WorkBuddyDecimal[]): WorkBuddyDecimal { - const scale = values.reduce((max, value) => Math.max(max, value.scale), 0); - const digits = values.reduce((sum, value) => sum + value.digits * 10n ** BigInt(scale - value.scale), 0n); - return { digits, scale }; -} - -export function subtractWorkBuddyDecimals(total: WorkBuddyDecimal, ...values: WorkBuddyDecimal[]): WorkBuddyDecimal { - const scale = [total, ...values].reduce((max, value) => Math.max(max, value.scale), 0); - const scaled = (value: WorkBuddyDecimal) => value.digits * 10n ** BigInt(scale - value.scale); - const digits = values.reduce((left, value) => left - scaled(value), scaled(total)); - return { digits: digits > 0n ? digits : 0n, scale }; -} - -export function compareWorkBuddyDecimals(a: WorkBuddyDecimal, b: WorkBuddyDecimal): number { - const scale = Math.max(a.scale, b.scale); - const left = a.digits * 10n ** BigInt(scale - a.scale); - const right = b.digits * 10n ** BigInt(scale - b.scale); - return left < right ? -1 : left > right ? 1 : 0; -} - -export function formatWorkBuddyDecimal(value: WorkBuddyDecimal): string { - let digits = value.digits, scale = value.scale; - while (scale > 0 && digits % 10n === 0n) { digits /= 10n; scale--; } - const text = digits.toString().padStart(scale + 1, "0"); - return scale ? `${text.slice(0, -scale)}.${text.slice(-scale)}` : text; -} - -/** Nearest integer, with an exact half rounded up; caller validates the balance. */ -export function roundedWorkBuddyUnavailable(total: WorkBuddyDecimal, remaining: WorkBuddyDecimal): number { - const scale = Math.max(total.scale, remaining.scale); - const totalDigits = total.digits * 10n ** BigInt(scale - total.scale); - const remainingDigits = remaining.digits * 10n ** BigInt(scale - remaining.scale); - const available = remainingDigits > totalDigits ? totalDigits : remainingDigits; - return Number(((totalDigits - available) * 200n + totalDigits) / (2n * totalDigits)); -} diff --git a/structure/dashboard-and-usage.md b/structure/dashboard-and-usage.md index 8450652b73d..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. 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. Bounded exact decimal totals preserve package aggregation across the quota DTO; legacy numeric-only responses retain their prior display. `gui/tests/quota-summary.test.ts` covers this projection, 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 9cce822d082..a7997f07e5f 100644 --- a/structure/providers/workbuddy.md +++ b/structure/providers/workbuddy.md @@ -38,14 +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 using bounded decimal arithmetic and retains the -existing numeric totals alongside optional exact total/remaining strings for the informational -headline. Total, used, remaining, frozen and group amounts are summed before conversion to -numbers. Quoted provider decimals retain their input precision; JSON numbers have already been -parsed as JavaScript numbers. `CreditGroups` is 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, with that decision made using the -exact total when available; estimated remaining credits use decimal subtraction on validated amounts. 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. @@ -55,10 +52,8 @@ 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 numeric fields and bounded exact decimal -metadata for the GUI. Invalid metadata or an exact remaining amount above the exact total -suppresses the headline percentage, including at subnormal magnitudes; older payloads without -exact metadata keep the numeric fallback. The shared provider quota panel shows the remaining credits, usage, group balances and +`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 optional expiry; the existing refresh and stale-state controls apply to it. ## Verification diff --git a/tests/providers/workbuddy-quota.test.ts b/tests/providers/workbuddy-quota.test.ts index 10af6d064e6..15bba422d42 100644 --- a/tests/providers/workbuddy-quota.test.ts +++ b/tests/providers/workbuddy-quota.test.ts @@ -35,50 +35,6 @@ test("decimal package totals preserve the reported remaining balance", () => { expect(parseWorkBuddyCredits({ Packages: [{ CycleTotalCapacity: 1e-300, CycleUsedCapacity: 0, CycleRemainCapacity: 5e-301 }] })?.remaining).toBe(5e-301); }); -test("exact balance metadata stays bounded, validates its numeric projection, and survives JSON", () => { - const balance = parseWorkBuddyCredits({ Packages: [amounts("0.5", "0", "0.4975"), amounts("0.5", "0", "0.49750000000000005")] })!; - expect(balance.exact).toEqual({ total: "1", remaining: "0.99500000000000005" }); - expect(normalizeWorkBuddyCredits(JSON.parse(JSON.stringify(balance)))?.exact).toEqual(balance.exact); - for (const exact of [null, {}, { total: "1", remaining: "2" }, { total: "1e0", remaining: "0.995" }, - { total: "1", remaining: `0.${"0".repeat(384)}1` }]) { - expect(normalizeWorkBuddyCredits({ ...balance, exact })?.exact).toBeNull(); - } - expect(parseWorkBuddyCredits({ Packages: [amounts("1", "0", `0.${"0".repeat(384)}1`)] })).toBeUndefined(); - expect(normalizeWorkBuddyCredits({ total: 1, used: 0, remaining: 0.995, frozen: 0, groups: [] })?.exact).toBeUndefined(); -}); - -test("all package and group amounts are summed before conversion to numbers", () => { - const row = { CycleTotalCapacity: "0.10000000000000001", CycleUsedCapacity: "0.10000000000000001", - CycleRemainCapacity: "0", CycleFrozenCapacity: "0.10000000000000001" }; - const balance = parseWorkBuddyCredits({ Packages: [row, row, row], - CreditGroups: [{ ...row, Kind: "benefit" }, { ...row, Kind: "benefit" }, { ...row, Kind: "benefit" }] })!; - expect(balance).toMatchObject({ total: 0.30000000000000004, used: 0.30000000000000004, frozen: 0.30000000000000004 }); - expect(balance.groups[0]).toMatchObject({ total: 0.30000000000000004, used: 0.30000000000000004, frozen: 0.30000000000000004 }); - const tiny = `0.${"0".repeat(323)}2`; - const tinyRow = { CycleTotalCapacity: tiny, CycleUsedCapacity: tiny, CycleFrozenCapacity: tiny, CycleRemainCapacity: "0" }; - const tinyBalance = parseWorkBuddyCredits({ Packages: [tinyRow, tinyRow, tinyRow], - CreditGroups: [{ ...tinyRow, Kind: "benefit" }, { ...tinyRow, Kind: "benefit" }, { ...tinyRow, Kind: "benefit" }] })!; - expect(tinyBalance).toMatchObject({ total: 5e-324, used: 5e-324, frozen: 5e-324 }); - expect(tinyBalance.groups[0]).toMatchObject({ total: 5e-324, used: 5e-324, frozen: 5e-324 }); -}); - -test("enterprise fallback retains a positive personal balance that underflows as a number", async () => { - const tiny = (digit: string) => `0.${"0".repeat(323)}${digit}`; - const requests: string[] = []; - globalThis.fetch = (async input => { - requests.push(String(input)); - return Response.json({ code: 0, data: String(input).endsWith("summary") - ? { Packages: [{ CycleTotalCapacity: tiny("2"), CycleUsedCapacity: "0", CycleRemainCapacity: tiny("1") }] } - : { limitNum: "100", credit: "0" } }); - }) as typeof fetch; - const credential = credentials(); - credential.workbuddy!.enterpriseId = "fixture-team"; - const report = await fetchWorkBuddyQuota("workbuddy-ai", credential); - const rows = buildQuotaSummary(freshQuotaReportsFromResponse([report]), provider => provider); - expect(formatQuotaPercent(rows[0]?.headline.percent)).toBe("50%"); - expect(requests.some(url => url.endsWith("get-enterprise-user-usage"))).toBe(false); -}); - 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;