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
12 changes: 12 additions & 0 deletions .changeset/cloud-4853-quota-notice-gates-on-upgrade.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
---
'@object-ui/plugin-chatbot': patch
'@object-ui/i18n': patch
---

fix(plugin-chatbot): the AI quota notice offers an upgrade only when the refusal names one

Clause-②: yes (widening) — one new published language-pack key, `chatbotQuota.limitTitle`, in every locale
Metadata-protocol: none

- The composer's AI quota notice and the confirm card's blocked state now read the 429's `upgrade` / `topUp` flags. `upgrade: true` keeps the "Upgrade needed" title and the "Upgrade plan" action; `topUp: true` shows a neutral "AI limit reached" title and the "Buy a credit pack" action; a refusal with neither (a paid plan's five-hour limit, a developer organization) shows "AI limit reached", the server's sentence about when it frees up, and no action. Before, every refusal was titled "Upgrade needed" and offered "Upgrade plan" unless `topUp` was set, so a paying team at its five-hour limit was told to upgrade.
- New locale key `chatbotQuota.limitTitle` in every `@object-ui/i18n` locale.
1 change: 1 addition & 0 deletions ui/packages/i18n/src/locales/ar.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5303,6 +5303,7 @@ const ar = {
},
chatbotQuota: {
title: "الترقية مطلوبة",
limitTitle: "تم بلوغ حد الذكاء الاصطناعي",
fallbackMessage: "لقد بلغت حصتك من الذكاء الاصطناعي.",
buyCredits: "شراء باقة أرصدة",
upgradePlan: "ترقية الخطة",
Expand Down
1 change: 1 addition & 0 deletions ui/packages/i18n/src/locales/de.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4869,6 +4869,7 @@ const de = {
},
chatbotQuota: {
title: "Upgrade erforderlich",
limitTitle: "KI-Limit erreicht",
fallbackMessage: "Sie haben Ihr KI-Kontingent erreicht.",
buyCredits: "Credit-Paket kaufen",
upgradePlan: "Tarif upgraden",
Expand Down
1 change: 1 addition & 0 deletions ui/packages/i18n/src/locales/en.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5841,6 +5841,7 @@ const en = {
},
chatbotQuota: {
title: 'Upgrade needed',
limitTitle: 'AI limit reached',
fallbackMessage: 'You have reached your AI quota.',
buyCredits: 'Buy a credit pack',
upgradePlan: 'Upgrade plan',
Expand Down
1 change: 1 addition & 0 deletions ui/packages/i18n/src/locales/es.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4978,6 +4978,7 @@ const es = {
},
chatbotQuota: {
title: "Se requiere actualizar",
limitTitle: "Límite de IA alcanzado",
fallbackMessage: "Ha alcanzado su cuota de IA.",
buyCredits: "Comprar un paquete de créditos",
upgradePlan: "Mejorar el plan",
Expand Down
1 change: 1 addition & 0 deletions ui/packages/i18n/src/locales/fr.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4974,6 +4974,7 @@ const fr = {
},
chatbotQuota: {
title: "Mise à niveau requise",
limitTitle: "Limite d'IA atteinte",
fallbackMessage: "Vous avez atteint votre quota d'IA.",
buyCredits: "Acheter un pack de crédits",
upgradePlan: "Changer d'offre",
Expand Down
1 change: 1 addition & 0 deletions ui/packages/i18n/src/locales/ja.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4871,6 +4871,7 @@ const ja = {
},
chatbotQuota: {
title: "アップグレードが必要です",
limitTitle: "AI の利用上限に達しました",
fallbackMessage: "AI の利用上限に達しました。",
buyCredits: "クレジットパックを購入",
upgradePlan: "プランをアップグレード",
Expand Down
1 change: 1 addition & 0 deletions ui/packages/i18n/src/locales/ko.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4868,6 +4868,7 @@ const ko = {
},
chatbotQuota: {
title: "업그레이드 필요",
limitTitle: "AI 사용 한도 도달",
fallbackMessage: "AI 사용 한도에 도달했습니다.",
buyCredits: "크레딧 팩 구매",
upgradePlan: "요금제 업그레이드",
Expand Down
1 change: 1 addition & 0 deletions ui/packages/i18n/src/locales/pt-BR.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4973,6 +4973,7 @@ const pt = {
},
chatbotQuota: {
title: "Upgrade necessário",
limitTitle: "Limite de IA atingido",
fallbackMessage: "Você atingiu sua cota de IA.",
buyCredits: "Comprar um pacote de créditos",
upgradePlan: "Fazer upgrade do plano",
Expand Down
1 change: 1 addition & 0 deletions ui/packages/i18n/src/locales/ru.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5096,6 +5096,7 @@ const ru = {
},
chatbotQuota: {
title: "Требуется обновление тарифа",
limitTitle: "Лимит ИИ исчерпан",
fallbackMessage: "Вы исчерпали квоту ИИ.",
buyCredits: "Купить пакет кредитов",
upgradePlan: "Повысить тариф",
Expand Down
1 change: 1 addition & 0 deletions ui/packages/i18n/src/locales/zh-Hans.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5130,6 +5130,7 @@ const zh = {
},
chatbotQuota: {
title: '需要升级',
limitTitle: 'AI 额度已用尽',
fallbackMessage: 'AI 额度已用完。',
buyCredits: '购买额度包',
upgradePlan: '升级方案',
Expand Down
1 change: 1 addition & 0 deletions ui/packages/i18n/src/locales/zh-Hant.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5130,6 +5130,7 @@ const zhHant = {
},
chatbotQuota: {
title: '需要升級',
limitTitle: 'AI 額度已用盡',
fallbackMessage: 'AI 額度已用完。',
buyCredits: '購買額度包',
upgradePlan: '升級方案',
Expand Down
33 changes: 24 additions & 9 deletions ui/packages/plugin-chatbot/src/ChatbotEnhanced.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7405,8 +7405,16 @@ function formatSizeLimit(bytes: number, locale: string): string {
* `messageEn`; that pair is server-owned, so we still choose between them — by
* the in-app locale, not `navigator.language`, which ignored the locale
* switcher entirely (objectui#2871).
*
* The title and the action follow the refusal's own next-step flags, never a
* default: `topUp` offers a credit pack, `upgrade` offers the plan upgrade, and
* a refusal with neither (a paid plan's five-hour pace, a developer
* organization) gets a neutral title and NO action — waiting is the only exit,
* and the server's sentence already says when it frees up.
*/
function useAiQuotaCopy(error: unknown): { text: string; cta: string } | null {
function useAiQuotaCopy(
error: unknown,
): { title: string; text: string; cta: string | null } | null {
const { language } = useObjectTranslation();
const tt = useSafeTranslate();
const quota = React.useMemo(() => parseAiQuotaError(error), [error]);
Expand All @@ -7416,17 +7424,24 @@ function useAiQuotaCopy(error: unknown): { text: string; cta: string } | null {
text:
(isZh ? quota.message : quota.messageEn ?? quota.message) ||
tt('chatbotQuota.fallbackMessage', 'You have reached your AI quota.'),
title:
quota.upgrade && !quota.topUp
? tt('chatbotQuota.title', 'Upgrade needed')
: tt('chatbotQuota.limitTitle', 'AI limit reached'),
cta: quota.topUp
? tt('chatbotQuota.buyCredits', 'Buy a credit pack')
: tt('chatbotQuota.upgradePlan', 'Upgrade plan'),
: quota.upgrade
? tt('chatbotQuota.upgradePlan', 'Upgrade plan')
: null,
};
}

/**
* The next step under a confirm card that a quota refusal blocked
* (objectui#7253): what happened (the server's own sentence — it names both
* exits, "resets tomorrow" and "upgrade to keep designing") and, when the host
* wired one, the upgrade action. Renders nothing when the blocking error is not
* wired one, the upgrade or top-up action the refusal names (none when it
* names neither). Renders nothing when the blocking error is not
* a quota refusal, so the badge above it degrades to a bare "not applied"
* rather than to an invented explanation.
*/
Expand All @@ -7447,7 +7462,7 @@ function QuotaBlockedNextStep({
>
{copy.text}
</span>
{onUpgrade ? (
{onUpgrade && copy.cta ? (
<button
type="button"
onClick={onUpgrade}
Expand Down Expand Up @@ -7479,12 +7494,12 @@ function ErrorBanner({
const { summary, details } = React.useMemo(() => summarizeChatError(error), [error]);
const [expanded, setExpanded] = React.useState(false);

// AI quota refusal (429 from the cloud token guardrail) -> friendly upgrade /
// top-up CTA instead of a red "Response failed" banner. Copy resolved by the
// AI quota refusal (429 from the cloud token guardrail) -> an amber notice
// with the upgrade / top-up action the refusal names (none when it names
// neither) instead of a red "Response failed" banner. Copy resolved by the
// shared helper, which the confirm card's blocked state reads too.
if (quota) {
const { text, cta } = quota;
const title = tt('chatbotQuota.title', 'Upgrade needed');
const { title, text, cta } = quota;
return (
<div className="border-t bg-background px-3 py-2 text-sm" role="alert">
<div className="rounded-md border border-amber-300/40 bg-amber-50/60 px-3 py-2 text-foreground dark:bg-amber-950/20">
Expand All @@ -7493,7 +7508,7 @@ function ErrorBanner({
<div className="font-medium leading-snug text-foreground">{title}</div>
<div className="mt-0.5 break-words leading-snug text-muted-foreground">{text}</div>
</div>
{onUpgrade ? (
{onUpgrade && cta ? (
<button
type="button"
onClick={onUpgrade}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -244,3 +244,52 @@ describe('confirm card — transient not-sent failure keeps the retry path', ()
await waitFor(() => expect(textarea.value).toBe('add a status field'));
});
});

describe('confirm card — a refusal that names no upgrade offers none (cloud#4853)', () => {
/** The cloud guardrail's paid-plan five-hour 429: upgrade:false, topUp:false. */
function paidFiveHourRefusal(): Error {
const e = new Error(
JSON.stringify({
success: false,
error: {
code: 'AI_ALLOWANCE_EXHAUSTED',
message: '近五小时的 AI 用量已达上限,五小时内恢复后即可继续。',
category: 'rate_limit',
details: {
messageEn: "You've hit the five-hour AI usage limit. It resets within five hours — then you're good to go.",
upgrade: false,
topUp: false,
},
},
}),
) as Error & { notSent?: boolean; status?: number };
e.notSent = true;
e.status = 429;
return e;
}

it('paid plan, resetKind fiveHour: the reason shows, the upgrade action does not', async () => {
const onSendMessage = vi.fn();
const onUpgrade = vi.fn();
const { rerender } = render(
<ChatbotEnhanced placeholder="Ask…" messages={changesMessage()} onSendMessage={onSendMessage} onUpgrade={onUpgrade} />,
);
fireEvent.click(screen.getByTestId('proposed-changes-confirm'));
rerender(
<ChatbotEnhanced
placeholder="Ask…"
messages={changesMessage()}
onSendMessage={onSendMessage}
onUpgrade={onUpgrade}
error={paidFiveHourRefusal()}
/>,
);

await waitFor(() =>
expect(screen.getByTestId('proposed-changes-quota-blocked')).toBeInTheDocument(),
);
expect(screen.getByTestId('proposed-changes-quota-reason')).toHaveTextContent(/five-hour AI usage limit/);
expect(screen.queryByTestId('proposed-changes-quota-upgrade')).not.toBeInTheDocument();
expect(screen.queryByRole('button', { name: 'Upgrade plan' })).toBeNull();
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
import '@testing-library/jest-dom/vitest';
import { describe, it, expect, vi } from 'vitest';
import { render, screen } from '@testing-library/react';
import { I18nProvider } from '@object-ui/i18n';
import { ChatbotEnhanced } from '../ChatbotEnhanced';
import { parseAiQuotaError } from '../tool-display';

Expand Down Expand Up @@ -125,3 +126,74 @@ describe('free-plan 429 banner — the reset promise nobody makes (objectui#7587
expect(withTrue).toBe(withFalse);
});
});

/**
* cloud#4853 — the banner's title and action follow the refusal's own
* next-step flags. The usage door (`GET /api/v1/ai/usage`) names a paid
* team's five-hour wall `{planType:'paid', resetKind:'fiveHour', upgrade:false,
* topUp:false}`; the 429 the composer actually receives carries no
* planType/resetKind, only the flags in `error.details` beside the server's
* sentence. Each fixture below is the cloud guardrail's body for that plan and
* window, so the card's acceptance reads 1:1 against what reaches the banner.
*/
describe('quota banner — title and action follow upgrade / topUp (cloud#4853)', () => {
const FIVE_HOUR_ZH = '近五小时的 AI 用量已达上限,五小时内恢复后即可继续。';
const FIVE_HOUR_EN =
"You've hit the five-hour AI usage limit. It resets within five hours — then you're good to go.";

function refusal(details: Record<string, unknown>, message = FIVE_HOUR_ZH): Error {
const e = new Error(
JSON.stringify({
success: false,
error: { code: 'AI_ALLOWANCE_EXHAUSTED', message, category: 'rate_limit', details },
}),
) as Error & { notSent?: boolean; status?: number };
e.notSent = true;
e.status = 429;
return e;
}

function renderZh(error: Error, onUpgrade = vi.fn()) {
render(
<I18nProvider config={{ defaultLanguage: 'zh', detectBrowserLanguage: false }}>
<ChatbotEnhanced placeholder="Ask…" messages={[]} onSendMessage={vi.fn()} onUpgrade={onUpgrade} error={error} />
</I18nProvider>,
);
return screen.getByRole('alert');
}

it("paid plan, resetKind fiveHour ({planType:'paid', resetKind:'fiveHour', upgrade:false, topUp:false}): no 「需要升级」 heading, no 「升级方案」 button", () => {
const banner = renderZh(
refusal({ messageEn: FIVE_HOUR_EN, upgrade: false, topUp: false, resetsTonight: false, resetsAt: RESETS_AT }),
);
expect(banner).not.toHaveTextContent('需要升级');
expect(screen.queryByRole('button', { name: '升级方案' })).toBeNull();
expect(banner.querySelectorAll('button')).toHaveLength(0);
// The notice still says when it frees up: the server's sentence, verbatim.
expect(banner.textContent).toBe(`AI 额度已用尽${FIVE_HOUR_ZH}`);
});

it('developer plan (upgrade:false, no topUp key): neutral title and no action', () => {
const banner = renderZh(refusal({ messageEn: FIVE_HOUR_EN, upgrade: false, resetsTonight: false, resetsAt: RESETS_AT }));
expect(banner).not.toHaveTextContent('需要升级');
expect(banner.querySelectorAll('button')).toHaveLength(0);
});

it('paid plan, weekly allowance (topUp:true): a top-up action, not an upgrade', () => {
const onUpgrade = vi.fn();
const banner = renderZh(
refusal({ messageEn: 'Weekly allowance used up.', upgrade: false, topUp: true }, '本周的 AI 额度已用完。'),
onUpgrade,
);
expect(banner).not.toHaveTextContent('需要升级');
expect(screen.queryByRole('button', { name: '升级方案' })).toBeNull();
screen.getByRole('button', { name: '购买额度包' }).click();
expect(onUpgrade).toHaveBeenCalledTimes(1);
});

it('free plan (upgrade:true): the upgrade heading and button stay', () => {
const banner = renderZh(refusal({ messageEn: FREE_PLAN_EN, upgrade: true }, FREE_PLAN_ZH));
expect(banner).toHaveTextContent('需要升级');
expect(screen.getByRole('button', { name: '升级方案' })).toBeInTheDocument();
});
});
Loading