feat(puter-js): offer Add Credits in the Low Balance dialog to accounts with a plan (#4577)

A call refused for credit on a website shows the Low Balance dialog,
whose only action was Upgrade. An account that already has a plan can
buy add-on credit instead, which is quicker and cheaper than changing
plans. For such an account the dialog now leads with Add Credits, which
shows the top-up as the user menu's item does, and keeps Upgrade Plan
beside it. Accounts without a plan, team seats and every other refusal
see the dialog as before.

The rule for who can top up moves into lib/topUp.js, shared with
<puter-user-menu>.
This commit is contained in:
Nariman Jelveh authored and GitHub committed 2026-11-20 10:07:52 -07:00
1 parent 59524cc580
commit ef5a78e5bd
7 files changed
+137 -10

No files matched your search

+5
View File
@@ -280,6 +280,11 @@ shows only when whoami reports `subscribed: true` and no `team` paying for the
account. On a page that can't frame the GUI, the item opens the dashboard with
`?topup=` in a new tab instead.
The Low Balance dialog puter.js shows on a website when a call is refused for
credit offers the same top-up to the same accounts: **Add Credits** is its main
button, with **Upgrade Plan** beside it. Everyone else gets **Upgrade Now**
alone.
The GUI reports `unavailable` unless its session belongs to `user`, the account
has no verification or password change waiting, and the deployment defines
`window.UITopUp` with `UITopUp.embeddable === true`. Otherwise it runs:
+17
View File
@@ -0,0 +1,17 @@
/**
* Whether `user` (a whoami) is a team seat. A seat's plan is its team's, and so are
* paying for its usage and changing the plan.
*
* @param {{ team?: { uid?: unknown } | null } | null | undefined} user
* @returns {boolean}
*/
export const isSeat = (user) => typeof user?.team?.uid === 'string' && user.team.uid !== '';
/**
* Whether add-on credit is sold to the account `user` (its whoami) describes:
* one with a plan of its own, and not a team seat.
*
* @param {{ subscribed?: unknown, team?: { uid?: unknown } | null } | null | undefined} user
* @returns {boolean}
*/
export const canTopUp = (user) => user?.subscribed === true && !isSeat(user);
+11 -2
View File
@@ -4,6 +4,7 @@
// prompt AND reject, never prompt instead of rejecting.
import { showUsageLimitDialog } from '../modules/UsageLimitDialog.js';
import { canTopUp } from './topUp.js';
/** @typedef {import('./types.js').UpgradeReason} UpgradeReason */
/** @typedef {import('./types.js').UpgradePromptContext} UpgradePromptContext */
@@ -26,7 +27,8 @@ import { showUsageLimitDialog } from '../modules/UsageLimitDialog.js';
*
* @typedef {{
* env?: string,
* ui?: { requestUpgrade: Function, canShowUpgradeFrame_?: () => boolean, upgradeFrameShowing_?: () => boolean, topUpShowing_?: () => boolean },
* ui?: { requestUpgrade: Function, canShowUpgradeFrame_?: () => boolean, upgradeFrameShowing_?: () => boolean, topUpShowing_?: () => boolean, showTopUp_?: () => Promise<unknown> },
* whoami?: { subscribed?: unknown, team?: { uid?: unknown } | null } | null,
* authToken?: string,
* appID?: string,
* getAppIDFromAuthToken?: (token: unknown) => string | null,
@@ -110,7 +112,9 @@ const messageFor = (reason, error, context) => {
* never answers). The SDK's own dialog covers storage refusals everywhere
* else - the desktop leans on it for those - and funding / plan refusals on
* websites only. On a first-party page its Upgrade button shows the upgrade
* in a frame over the page. The error is not consumed; callers still reject.
* in a frame over the page. For an account with a plan that ran out of
* credit, the dialog leads with Add Credits, which shows the top-up. The
* error is not consumed; callers still reject.
*
* @param {unknown} error The rejection, in whatever shape it arrived.
* @param {UpgradePromptContext} [context] Which SDK method was refused and,
@@ -135,11 +139,16 @@ export const promptIfUpgradeRequired = (error, context = {}, puter = globalThis.
// A first-party page shows the upgrade in a frame over itself
// instead of a dashboard tab.
const framed = puter?.env === 'web' && puter.ui?.canShowUpgradeFrame_?.() === true;
// Credit is what ran out, and an account with a plan can buy more
// without changing the plan.
const topUp = reason === 'funds' && puter?.env === 'web' &&
typeof puter.ui?.showTopUp_ === 'function' && canTopUp(puter.whoami);
showUsageLimitDialog(message, {
title: TITLES[reason],
method,
reason,
appID: appIDOf(puter),
...(topUp ? { onTopUp: () => void puter.ui.showTopUp_() } : {}),
...(framed ? {
// The page may have stopped being able to frame it, such as
// by signing out, since the dialog opened.
@@ -238,6 +238,49 @@ describe('promptIfUpgradeRequired', () => {
});
});
describe('on a website, for an account with a plan', () => {
const funds = { code: 'insufficient_funds', status: 402 };
const web = (whoami, ui = {}) => {
globalThis.puter = {
env: 'web',
whoami,
ui: { requestUpgrade: vi.fn(), showTopUp_: vi.fn(async () => ({ toppedUp: false })), ...ui },
};
};
it('has the dialog offer the top-up when credit ran out', () => {
web({ subscribed: true });
promptIfUpgradeRequired(funds, { method: 'puter.ai.chat' });
const [, options] = showUsageLimitDialog.mock.calls[0];
expect(globalThis.puter.ui.showTopUp_).not.toHaveBeenCalled();
options.onTopUp();
expect(globalThis.puter.ui.showTopUp_).toHaveBeenCalledTimes(1);
});
it.each([
['an account without a plan', { subscribed: false }],
['a seat whose team pays for it', { subscribed: true, team: { uid: 'team-1' } }],
['an account not read yet', undefined],
])('offers only the upgrade to %s', (_label, whoami) => {
web(whoami);
promptIfUpgradeRequired(funds, { method: 'puter.ai.chat' });
expect(showUsageLimitDialog.mock.calls[0][1]).not.toHaveProperty('onTopUp');
});
it('offers only the upgrade for a refusal credit would not clear', () => {
web({ subscribed: true });
promptIfUpgradeRequired({ code: 'storage_limit_reached' }, { method: 'puter.fs.upload' });
promptIfUpgradeRequired({ code: 'subscription_required' }, { method: 'puter.hosting.create' });
for ( const [, options] of showUsageLimitDialog.mock.calls ) expect(options).not.toHaveProperty('onTopUp');
});
it('offers only the upgrade where the SDK has no top-up to show', () => {
web({ subscribed: true }, { showTopUp_: undefined });
promptIfUpgradeRequired(funds, { method: 'puter.ai.chat' });
expect(showUsageLimitDialog.mock.calls[0][1]).not.toHaveProperty('onTopUp');
});
});
it('does nothing for a rejection an upgrade would not clear', () => {
promptIfUpgradeRequired({ status: 403 });
promptIfUpgradeRequired(new Error('offline'));
+20 -4
View File
@@ -8,6 +8,8 @@ import { escapeHtml } from '../lib/html.js';
* @property {string} [appID] The app the refused call ran as.
* @property {() => boolean} [onUpgrade] Runs when the user clicks Upgrade, instead of
* opening the dashboard's upgrade page in a new tab. Returning false opens the tab anyway.
* @property {() => void} [onTopUp] Makes Add Credits the dialog's main button, for an account
* that can buy add-on credit, and runs when the user clicks it. Upgrade stays beside it.
*/
const UPGRADE_PAGE = 'https://puter.com/dashboard/';
@@ -49,7 +51,7 @@ class UsageLimitDialog extends (globalThis.HTMLElement || Object) {
* @param {string} message Plain-text line saying what was refused.
* @param {UsageLimitDialogOptions} [options]
*/
constructor (message, { title = 'Low Balance', method, reason, appID, onUpgrade } = {}) {
constructor (message, { title = 'Low Balance', method, reason, appID, onUpgrade, onTopUp } = {}) {
super();
this.message = message || 'You have reached your usage limit for this account.';
// Not `this.title`: on an HTMLElement that is the tooltip attribute.
@@ -57,6 +59,7 @@ class UsageLimitDialog extends (globalThis.HTMLElement || Object) {
this.method = method;
this.upgradeUrl = upgradeUrl({ reason, appID, method });
this.onUpgrade = onUpgrade;
this.onTopUp = onTopUp;
this.attachShadow({ mode: 'open' });
@@ -199,6 +202,10 @@ class UsageLimitDialog extends (globalThis.HTMLElement || Object) {
color: #bedef5;
}
.button-secondary {
margin-bottom: 10px;
}
.button-cancel {
background: none;
}
@@ -266,10 +273,13 @@ class UsageLimitDialog extends (globalThis.HTMLElement || Object) {
</svg>
</div>
<h2>${escapeHtml(this.heading)}</h2>
<p class="message">${escapeHtml(this.message)}<br>Please upgrade to continue.</p>
<p class="message">${escapeHtml(this.message)}<br>${onTopUp ? 'Add credits to continue.' : 'Please upgrade to continue.'}</p>
${this.method ? `<p class="method">${escapeHtml(this.method)}</p>` : ''}
<div class="buttons">
<button class="button button-primary" id="upgrade-btn">Upgrade Now</button>
${onTopUp ? `
<button class="button button-primary" id="top-up-btn">Add Credits</button>
<button class="button button-secondary" id="upgrade-btn">Upgrade Plan</button>` : `
<button class="button button-primary" id="upgrade-btn">Upgrade Now</button>`}
<button class="button button-cancel" id="close-btn">Close</button>
</div>
</div>
@@ -295,6 +305,12 @@ class UsageLimitDialog extends (globalThis.HTMLElement || Object) {
if ( ! shown ) window.open(this.upgradeUrl, '_blank');
});
this.shadowRoot.querySelector('#top-up-btn')?.addEventListener('click', () => {
// Closed first, so the frame the top-up shows in isn't under this modal.
this.close();
this.onTopUp();
});
// Close on backdrop click
dialog.addEventListener('click', (e) => {
if ( e.target === dialog ) {
@@ -325,7 +341,7 @@ if ( typeof globalThis.HTMLElement !== 'undefined' && globalThis.customElements
* dropped, so racing requests can't stack dialogs.
*
* @param {string} message Plain-text line saying what was refused; the dialog
* adds the "upgrade to continue" line itself.
* adds the "upgrade to continue" or "add credits to continue" line itself.
* @param {UsageLimitDialogOptions} [options]
*/
export function showUsageLimitDialog (message, options = {}) {
@@ -49,3 +49,42 @@ describe('the usage limit dialog Upgrade button', () => {
expect(document.querySelector('usage-limit-dialog')).toBeNull();
});
});
describe('the usage limit dialog for an account that can add credits', () => {
const shadow = () => document.querySelector('usage-limit-dialog').shadowRoot;
it('leads with Add Credits, keeps Upgrade beside it, and says what to do', () => {
showUsageLimitDialog('Your account does not have enough funding to complete this request.', {
reason: 'funds', onTopUp: vi.fn(),
});
const labels = [...shadow().querySelectorAll('.buttons button')].map((button) => button.textContent.trim());
expect(labels).toEqual(['Add Credits', 'Upgrade Plan', 'Close']);
expect(shadow().querySelector('#top-up-btn').classList.contains('button-primary')).toBe(true);
expect(shadow().querySelector('#upgrade-btn').classList.contains('button-primary')).toBe(false);
expect(shadow().querySelector('.message').textContent).toContain('Add credits to continue.');
});
it('runs onTopUp once the dialog has closed, and opens no tab', () => {
const onTopUp = vi.fn(() => {
expect(document.querySelector('usage-limit-dialog')).toBeNull();
});
showUsageLimitDialog('Out of credit.', { reason: 'funds', onTopUp });
shadow().querySelector('#top-up-btn').click();
expect(onTopUp).toHaveBeenCalledTimes(1);
expect(window.open).not.toHaveBeenCalled();
});
it('still upgrades from its Upgrade button', () => {
showUsageLimitDialog('Out of credit.', { reason: 'funds', onTopUp: vi.fn() });
upgradeButton().click();
expect(window.open).toHaveBeenCalledWith('https://puter.com/dashboard/?upgrade=funds#home', '_blank');
});
it('offers only the upgrade to everyone else', () => {
showUsageLimitDialog('Out of credit.', { reason: 'funds' });
expect(shadow().querySelector('#top-up-btn')).toBeNull();
expect(upgradeButton().textContent).toBe('Upgrade Now');
expect(upgradeButton().classList.contains('button-primary')).toBe(true);
expect(shadow().querySelector('.message').textContent).toContain('Please upgrade to continue.');
});
});
@@ -27,6 +27,7 @@
import PuterWebComponent from '../PuterWebComponent.js';
import { defaultFontFamily } from '../PuterDefaultStyles.js';
import { canFrameGuiEmbed } from '../../lib/guiEmbed.js';
import { canTopUp, isSeat } from '../../lib/topUp.js';
const APPS_ICON = `<svg viewBox="0 0 24 24" width="20" height="20" aria-hidden="true" focusable="false">${
[5, 12, 19].flatMap(y => [5, 12, 19].map(x => `<circle cx="${x}" cy="${y}" r="2"/>`)).join('')
@@ -59,9 +60,6 @@ const MENU_LINKS = [
// Sits under Usage, and shows only for an account with a plan.
const ADD_CREDITS_ITEM = '<button type="button" class="menu-item add-credits" role="menuitem" hidden></button>';
/** A seat's plan is its team's, and so are paying for its usage and changing the plan. */
const isSeat = user => typeof user?.team?.uid === 'string' && user.team.uid !== '';
// Gap between a panel and the viewport edge, and between its caret and corners.
const EDGE = 8;
const CARET_INSET = 20;
@@ -658,7 +656,7 @@ class PuterUserMenu extends PuterWebComponent {
const user = cached?.uuid && cached.uuid === this.#user?.uuid ? cached : this.#user;
const subscribed = user?.subscribed === true;
const seat = isSeat(user);
this.$('.add-credits').hidden = !subscribed || seat;
this.$('.add-credits').hidden = !canTopUp(user);
const upgrade = this.$('.upgrade-button');
upgrade.hidden = !this.#ready || seat || this.hasAttribute('hide-upgrade');
upgrade.textContent = this._label(subscribed ? 'manage-plan-label' : 'upgrade-label');