diff --git a/doc/embedding-app-browser.md b/doc/embedding-app-browser.md index c7f1e0c05..72df66f2c 100644 --- a/doc/embedding-app-browser.md +++ b/doc/embedding-app-browser.md @@ -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: diff --git a/src/puter-js/src/lib/topUp.js b/src/puter-js/src/lib/topUp.js new file mode 100644 index 000000000..0c1e04c4f --- /dev/null +++ b/src/puter-js/src/lib/topUp.js @@ -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); diff --git a/src/puter-js/src/lib/upgradePrompt.js b/src/puter-js/src/lib/upgradePrompt.js index a480c1643..5672ee2a6 100644 --- a/src/puter-js/src/lib/upgradePrompt.js +++ b/src/puter-js/src/lib/upgradePrompt.js @@ -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 }, + * 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. diff --git a/src/puter-js/src/lib/upgradePrompt.test.js b/src/puter-js/src/lib/upgradePrompt.test.js index 6cd4dc21d..028bb44d1 100644 --- a/src/puter-js/src/lib/upgradePrompt.test.js +++ b/src/puter-js/src/lib/upgradePrompt.test.js @@ -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')); diff --git a/src/puter-js/src/modules/UsageLimitDialog.js b/src/puter-js/src/modules/UsageLimitDialog.js index c09e73cc2..ba3a9e543 100644 --- a/src/puter-js/src/modules/UsageLimitDialog.js +++ b/src/puter-js/src/modules/UsageLimitDialog.js @@ -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) {

${escapeHtml(this.heading)}

-

${escapeHtml(this.message)}
Please upgrade to continue.

+

${escapeHtml(this.message)}
${onTopUp ? 'Add credits to continue.' : 'Please upgrade to continue.'}

${this.method ? `

${escapeHtml(this.method)}

` : ''}
- + ${onTopUp ? ` + + ` : ` + `}
@@ -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 = {}) { diff --git a/src/puter-js/src/modules/UsageLimitDialog.upgrade.test.js b/src/puter-js/src/modules/UsageLimitDialog.upgrade.test.js index 34bb9f2e7..63602baf3 100644 --- a/src/puter-js/src/modules/UsageLimitDialog.upgrade.test.js +++ b/src/puter-js/src/modules/UsageLimitDialog.upgrade.test.js @@ -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.'); + }); +}); diff --git a/src/puter-js/src/ui/components/PuterUserMenu.js b/src/puter-js/src/ui/components/PuterUserMenu.js index 65aaee3ae..13736b050 100644 --- a/src/puter-js/src/ui/components/PuterUserMenu.js +++ b/src/puter-js/src/ui/components/PuterUserMenu.js @@ -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 = `