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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions docs-site/src/content/docs/guides/providers.md
Original file line number Diff line number Diff line change
Expand Up @@ -1404,6 +1404,10 @@ WorkBuddy's Chat endpoint. The Overview and Accounts tabs show remaining credits
balances, and the next expiring non-daily credits when available. Refresh reads the signed-in
account's billing summary; an unavailable read is not a zero balance. These credits are
informational and do not disable free models when paid credits run out.
When the reported total is positive, the header quota summary shows the unavailable percentage,
including frozen credits, rounded to the nearest whole percent. It gives no exhaustion warning:
free models may still work. An individual
credit expiry is not shown as a reset of the entire balance.

This uses an unofficial subscription protocol based on
[Magpie's WorkBuddy plugin](https://github.com/magpie-community/plugins/tree/e7f65641df820dfd715c0d2241f99f2092e4efb1/packages/workbuddy).
Expand Down
2 changes: 2 additions & 0 deletions docs-site/src/content/docs/zh-cn/guides/providers.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
实现的非官方订阅协议。上游的客户端通道或账号限制会原样拒绝请求,不会改写代理身份提示词
Expand Down
3 changes: 3 additions & 0 deletions gui/src/components/quota-summary-bar/QuotaSummaryBar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -209,6 +209,9 @@ function QuotaSummaryItem({ row, t, locale }: { row: QuotaSummaryRow; t: TFn; lo
onClick={onClick}
>
<span className="quota-summary-name">{row.label}</span>
{headline.labelKey === "quotaSummary.creditsUnavailable" && (
<span className="quota-summary-name">{t("quotaSummary.creditsUnavailable")}</span>
)}
<span className="quota-summary-pct">{formatQuotaPercent(headline.percent)}</span>
{row.provider === "meta-muse" && headline.resetAt !== undefined && (
<span className="quota-summary-name" title={formatResetFuture(headline.resetAt, t, locale)}>
Expand Down
1 change: 1 addition & 0 deletions gui/src/i18n/de.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4231,6 +4231,7 @@ export const de: Record<TKey, string> = {
"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",
Expand Down
1 change: 1 addition & 0 deletions gui/src/i18n/en.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
1 change: 1 addition & 0 deletions gui/src/i18n/fr.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4220,6 +4220,7 @@ export const fr: Record<TKey, string> = {
"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",
Expand Down
1 change: 1 addition & 0 deletions gui/src/i18n/ja.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4253,6 +4253,7 @@ export const ja: Record<TKey, string> = {
"quotaSummary.warn": "70%以上使用",
"quotaSummary.critical": "90%以上使用",
"quotaSummary.credits": "クレジット",
"quotaSummary.creditsUnavailable": "利用できないクレジット",
"quotaSummary.refreshFailed": "最新の更新に失敗しました。前回の値を表示しています",
"quotaSummary.scrollPrev": "プロバイダーを左へスクロール",
"quotaSummary.scrollNext": "プロバイダーを右へスクロール",
Expand Down
1 change: 1 addition & 0 deletions gui/src/i18n/ko.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4253,6 +4253,7 @@ export const ko: Record<TKey, string> = {
"quotaSummary.warn": "70% 이상 사용",
"quotaSummary.critical": "90% 이상 사용",
"quotaSummary.credits": "크레딧",
"quotaSummary.creditsUnavailable": "사용할 수 없는 크레딧",
"quotaSummary.refreshFailed": "최근 갱신에 실패해 이전 값을 표시합니다",
"quotaSummary.scrollPrev": "프로바이더 목록 왼쪽으로",
"quotaSummary.scrollNext": "프로바이더 목록 오른쪽으로",
Expand Down
1 change: 1 addition & 0 deletions gui/src/i18n/pt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4226,6 +4226,7 @@ export const pt: Record<TKey, string> = {
"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",
Expand Down
1 change: 1 addition & 0 deletions gui/src/i18n/ru.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4254,6 +4254,7 @@ export const ru: Record<TKey, string> = {
"quotaSummary.warn": "Использовано более 70%",
"quotaSummary.critical": "Использовано более 90%",
"quotaSummary.credits": "Кредиты",
"quotaSummary.creditsUnavailable": "Недоступные кредиты",
"quotaSummary.refreshFailed": "Последнее обновление не удалось; показаны предыдущие данные",
"quotaSummary.scrollPrev": "Прокрутить провайдеров влево",
"quotaSummary.scrollNext": "Прокрутить провайдеров вправо",
Expand Down
1 change: 1 addition & 0 deletions gui/src/i18n/tr.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4254,6 +4254,7 @@ export const tr: Record<TKey, string> = {
"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",
Expand Down
1 change: 1 addition & 0 deletions gui/src/i18n/vi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4223,6 +4223,7 @@ export const vi: Record<TKey, string> = {
"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",
Expand Down
1 change: 1 addition & 0 deletions gui/src/i18n/zh-TW.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4217,6 +4217,7 @@ export const zhTW: Record<TKey, string> = {
"quotaSummary.warn": "已用 70% 以上",
"quotaSummary.critical": "已用 90% 以上",
"quotaSummary.credits": "額度",
"quotaSummary.creditsUnavailable": "不可用額度",
"quotaSummary.refreshFailed": "最近一次重新整理失敗,顯示上次資料",
"quotaSummary.scrollPrev": "向左捲動供應商",
"quotaSummary.scrollNext": "向右捲動供應商",
Expand Down
1 change: 1 addition & 0 deletions gui/src/i18n/zh.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4252,6 +4252,7 @@ export const zh: Record<TKey, string> = {
"quotaSummary.warn": "已用 70% 以上",
"quotaSummary.critical": "已用 90% 以上",
"quotaSummary.credits": "额度",
"quotaSummary.creditsUnavailable": "不可用额度",
"quotaSummary.refreshFailed": "最近一次刷新失败,显示上次数据",
"quotaSummary.scrollPrev": "向左滚动提供商",
"quotaSummary.scrollNext": "向右滚动提供商",
Expand Down
29 changes: 29 additions & 0 deletions gui/src/quota-summary.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,23 @@ export function formatQuotaPercent(percent: number | undefined): string {
return finite(percent) ? `${Math.floor(percent)}%` : "-";
}

/** Interpret the reported decimal numbers exactly when rounding an informational balance. */
function decimalRatio(value: number): [bigint, bigint] {
const [coefficient, exponent = "0"] = value.toString().split("e");
const [whole, fraction = ""] = coefficient!.split(".");
const digits = BigInt(`${whole}${fraction}`);
const scale = fraction.length - Number(exponent);
return scale >= 0 ? [digits, 10n ** BigInt(scale)] : [digits * 10n ** BigInt(-scale), 1n];
}

function roundedUnavailablePercent(total: number, remaining: number): number {
const [totalNumerator, totalDenominator] = decimalRatio(total);
const [remainingNumerator, remainingDenominator] = decimalRatio(Math.min(remaining, total));
const denominator = totalNumerator * remainingDenominator;
const numerator = (denominator - remainingNumerator * totalDenominator) * 100n;
return Number((2n * numerator + denominator) / (2n * denominator));
}

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

Expand Down Expand Up @@ -81,6 +98,18 @@ function summaryWindows(quota: AccountQuota): QuotaSummaryWindow[] {
severity: quotaSeverity(credits.percent),
});
}
const workbuddy = quota.workbuddyCredits;
// The provider can sum up to 512 packages; tolerate only their accumulated roundoff.
if (workbuddy && workbuddy.total > 0 && workbuddy.remaining / workbuddy.total <= 1 + Number.EPSILON * 1024) {
// Remaining is authoritative and includes frozen credits; the meter is informational.
const percent = roundedUnavailablePercent(workbuddy.total, workbuddy.remaining);
windows.push({
id: "quotaSummary.creditsUnavailable",
labelKey: "quotaSummary.creditsUnavailable",
percent,
severity: "normal",
});
}
// Credits are appended after provider windows, whose labels can equal any fixed id.
const used = new Set<string>();
return windows.map(window => {
Expand Down
27 changes: 25 additions & 2 deletions gui/tests/quota-summary-bar.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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(<QuotaSummaryChips rows={rows} t={t} locale="en" />);
root.render(<QuotaSummaryChips rows={renderRows} t={t} locale="en" />);
});
const list = container.querySelector("ul")!;
return {
Expand All @@ -57,6 +57,29 @@ async function mount() {
};
}

test("WorkBuddy chip names unavailable credits so frozen funds are not called used", async () => {
const workbuddy = buildQuotaSummary(freshQuotaReportsFromResponse([
{ provider: "workbuddy-ai", label: "WorkBuddy AI", updatedAt: now, quota: {
updatedAt: now, workbuddyCredits: { total: 100, used: 0, remaining: 0, frozen: 100, groups: [] },
} },
], now), provider => provider);
const view = await mount(workbuddy);
expect(view.chip("WorkBuddy AI").textContent).toContain("quotaSummary.creditsUnavailable");
expect(view.chip("WorkBuddy AI").textContent).toContain("100%");
await view.unmount();
});

test("WorkBuddy chip rounds its informational percentage to the nearest whole number", async () => {
const workbuddy = buildQuotaSummary(freshQuotaReportsFromResponse([
{ provider: "workbuddy-ai", label: "WorkBuddy AI", updatedAt: now, quota: {
updatedAt: now, workbuddyCredits: { total: 100, used: 89.6, remaining: 10.4, frozen: 0, groups: [] },
} },
], now), provider => provider);
const view = await mount(workbuddy);
expect(view.chip("WorkBuddy AI").textContent).toContain("90%");
await view.unmount();
});

async function click(element: Element) {
await act(async () => {
element.dispatchEvent(new testWindow.MouseEvent("click", { bubbles: true, cancelable: true, button: 0 }) as unknown as Event);
Expand Down
77 changes: 77 additions & 0 deletions gui/tests/quota-summary.test.ts
Original file line number Diff line number Diff line change
@@ -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;
Expand Down Expand Up @@ -52,6 +53,82 @@ describe("quota summary", () => {
]);
});

test("WorkBuddy shows unavailable credits neutrally, including frozen balance, without a reset", () => {
const balance = (total: number, used: number, remaining: number, frozen = 0) => ({
total, used, remaining, frozen, groups: [],
expiring: { amount: 10, at: now + 3_600_000 },
});
const reports = freshQuotaReportsFromResponse([
{ provider: "workbuddy-ai", updatedAt: now, quota: { updatedAt: now, workbuddyCredits: balance(100, 75, 25) } },
{ provider: "frozen", updatedAt: now, quota: { updatedAt: now, workbuddyCredits: balance(100, 0, 0, 100) } },
{ provider: "fractional", updatedAt: now, quota: { updatedAt: now, workbuddyCredits: balance(9, 8.1, 9 - 8.1) } },
{ provider: "below", updatedAt: now, quota: { updatedAt: now, workbuddyCredits: balance(100, 89.4, 10.6) } },
{ provider: "close-below", updatedAt: now, quota: { updatedAt: now, workbuddyCredits: balance(100, 89.99999999999, 10.00000000001) } },
{ provider: "zero-total", updatedAt: now, quota: { updatedAt: now, workbuddyCredits: balance(0, 0, 0) } },
{ provider: "malformed", updatedAt: now, quota: { updatedAt: now, workbuddyCredits: { total: 100, used: 0 } } },
], now);
const rows = buildQuotaSummary(reports, name);
expect(rows.map(row => [row.provider, row.headline.labelKey, row.headline.percent, row.severity])).toEqual([
["workbuddy-ai", "quotaSummary.creditsUnavailable", 75, "normal"],
["frozen", "quotaSummary.creditsUnavailable", 100, "normal"],
["fractional", "quotaSummary.creditsUnavailable", expect.any(Number), "normal"],
["below", "quotaSummary.creditsUnavailable", expect.any(Number), "normal"],
["close-below", "quotaSummary.creditsUnavailable", expect.any(Number), "normal"],
]);
expect(formatQuotaPercent(rows[2]!.headline.percent)).toBe("90%");
expect(formatQuotaPercent(rows[3]!.headline.percent)).toBe("89%");
expect(formatQuotaPercent(rows[4]!.headline.percent)).toBe("90%");
expect(rows[0]!.headline.resetAt).toBeUndefined();
});

test("summed decimal WorkBuddy packages display their exact integer percentage", () => {
const workbuddyCredits = parseWorkBuddyCredits({ Packages: Array.from({ length: 54 }, () => ({
CycleTotalCapacity: 0.91, CycleUsedCapacity: 0.819, CycleRemainCapacity: 0.091,
})) });
expect(workbuddyCredits).toBeDefined();
const reports = freshQuotaReportsFromResponse([
{ provider: "workbuddy-ai", updatedAt: now, quota: { updatedAt: now, workbuddyCredits } },
], now);
const [row] = buildQuotaSummary(reports, name);
expect(formatQuotaPercent(row!.headline.percent)).toBe("90%");
});

test("summed WorkBuddy packages retain decimal half-percent and below-half distinctions", () => {
const balance = (remaining: number) => parseWorkBuddyCredits({ Packages: Array.from({ length: 5 }, () => ({
CycleTotalCapacity: 1, CycleUsedCapacity: 0, CycleRemainCapacity: remaining,
})) });
const reports = freshQuotaReportsFromResponse([
{ provider: "tie", updatedAt: now, quota: { updatedAt: now, workbuddyCredits: balance(0.935) } },
{ provider: "below", updatedAt: now, quota: { updatedAt: now, workbuddyCredits: balance(0.93500000001) } },
], now);
expect(buildQuotaSummary(reports, name).map(row => formatQuotaPercent(row.headline.percent))).toEqual(["7%", "6%"]);
});

test("WorkBuddy rounds an exact half percent up and a smaller share down", () => {
const balance = (total: number, remaining: number) => ({ total, used: 0, remaining, frozen: 0, groups: [] });
const reports = freshQuotaReportsFromResponse([
{ provider: "tie", updatedAt: now, quota: { updatedAt: now, workbuddyCredits: balance(100, 93.5) } },
{ provider: "below", updatedAt: now, quota: { updatedAt: now, workbuddyCredits: balance(100, 93.50000000001) } },
{ provider: "decimal-tie", updatedAt: now, quota: { updatedAt: now, workbuddyCredits: balance(3, 2.955) } },
{ provider: "decimal-below", updatedAt: now, quota: { updatedAt: now, workbuddyCredits: balance(3, 2.9550000000001) } },
{ provider: "tiny", updatedAt: now, quota: { updatedAt: now, workbuddyCredits: balance(1e-300, 5e-301) } },
], now);
expect(buildQuotaSummary(reports, name).map(row => formatQuotaPercent(row.headline.percent)))
.toEqual(["7%", "6%", "2%", "1%", "50%"]);
});

test("contradictory WorkBuddy balances are omitted without hiding valid quota windows", () => {
const balance = (remaining: number) => ({ total: 100, used: 2, remaining, frozen: 0, groups: [] });
const reports = freshQuotaReportsFromResponse([
{ provider: "invalid", updatedAt: now, quota: { updatedAt: now, workbuddyCredits: balance(110) } },
{ provider: "mixed", updatedAt: now, quota: { updatedAt: now, weeklyPercent: 25, workbuddyCredits: balance(110) } },
{ provider: "roundoff", updatedAt: now, quota: { updatedAt: now, workbuddyCredits: balance(100 + 1e-12) } },
], now);
const rows = buildQuotaSummary(reports, name);
expect(rows.map(row => [row.provider, row.headline.percent])).toEqual([["mixed", 25], ["roundoff", 0]]);
expect(rows[0]!.windows.map(window => window.labelKey)).toEqual(["quota.weeklyLimit"]);
});

test("critical credits override a noncritical headline, but not a critical one", () => {
const credits = (percent: number) => ({ used: percent, limit: 100, remaining: 100 - percent, percent });
const reports = freshQuotaReportsFromResponse([
Expand Down
4 changes: 2 additions & 2 deletions src/providers/quota/workbuddy.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import type { OAuthCredentials } from "../../oauth/types";
import { workBuddyApi, WorkBuddyApiError } from "../../oauth/workbuddy";
import { workBuddyHeaders } from "../workbuddy";
import { parseWorkBuddyCredits, 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";

Expand Down Expand Up @@ -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) {
Expand Down
Loading
Loading