Merge origin/main into juancastro/put-2219-admin-worker-teardown

This commit is contained in:
Juan Castro committed 2026-10-21 17:52:21 -04:00
commit a5bd1c0c61
19 files changed
+530 -52

No files matched your search

@@ -22,7 +22,7 @@ jobs:
- name: Set up Node.js
uses: actions/setup-node@v7
with:
node-version: '24'
node-version: '26'
cache: 'npm'
- name: Install dependencies
+3 -3
View File
@@ -57,7 +57,7 @@ jobs:
- name: Set up Node.js
uses: actions/setup-node@v7
with:
node-version: '24'
node-version: '26'
cache: 'npm'
- name: Install dependencies
@@ -88,7 +88,7 @@ jobs:
- name: Set up Node.js
uses: actions/setup-node@v7
with:
node-version: '24'
node-version: '26'
cache: 'npm'
- name: Install dependencies
@@ -154,7 +154,7 @@ jobs:
- name: Set up Node.js
uses: actions/setup-node@v7
with:
node-version: '24'
node-version: '26'
cache: 'npm'
- name: Install dependencies
+1 -1
View File
@@ -16,7 +16,7 @@ jobs:
- name: Set up Node.js
uses: actions/setup-node@v7
with:
node-version: '24'
node-version: '26'
cache: 'npm'
- name: Install dependencies
+3 -3
View File
@@ -57,7 +57,7 @@ jobs:
- name: Set up Node.js
uses: actions/setup-node@v7
with:
node-version: '24'
node-version: '26'
cache: 'npm'
- name: Install dependencies
@@ -78,7 +78,7 @@ jobs:
- name: Set up Node.js
uses: actions/setup-node@v7
with:
node-version: '24'
node-version: '26'
cache: 'npm'
- name: Install dependencies
@@ -135,7 +135,7 @@ jobs:
if: needs.changes.outputs.puterjs == 'true'
uses: actions/setup-node@v7
with:
node-version: '24'
node-version: '26'
cache: 'npm'
- name: Install dependencies
+2 -2
View File
@@ -14,7 +14,7 @@
# config.default.json, so partial overrides work. Absent file = defaults.
# ---- Build stage ----
FROM node:24-slim AS build
FROM node:26-bookworm-slim AS build
WORKDIR /opt/puter
@@ -59,7 +59,7 @@ RUN set -e; \
wait $pjs_pid
# ---- Runtime stage (slim — no build tools) ----
FROM node:24-slim
FROM node:26-bookworm-slim
WORKDIR /opt/puter
+2 -1
View File
@@ -99,7 +99,8 @@ describe('image downloads', () => {
statusCode: 400,
code: 'input_too_large',
});
expect(pulled).toBeLessThanOrEqual(4);
// Readable.fromWeb reads ahead by a few chunks before the cap trips.
expect(pulled).toBeLessThanOrEqual(6);
});
it('gives up on a slow host with a 400 rather than waiting it out', async () => {
secureFetchMock.mockImplementationOnce(
+63 -25
View File
@@ -18,8 +18,8 @@
*/
// Importing npm `undici` has a process-wide side effect: if the global
// dispatcher slot — `Symbol.for('undici.globalDispatcher.1')`, shared with
// Node's built-in fetch — is empty, undici's module initializer installs its
// dispatcher slots — `Symbol.for('undici.globalDispatcher.N')`, shared with
// Node's built-in fetch — are empty, undici's module initializer installs its
// own Agent there. From that moment EVERY plain `fetch()` in the process
// (the AI provider SDKs, everything) is silently served by the npm copy of
// undici instead of the copy bundled with — and security-patched by — Node.
@@ -34,7 +34,12 @@
// This module must therefore be imported before `undici` — it intentionally
// imports nothing itself, and secureHttp.ts (the backend's only undici
// importer) imports it before importing undici.
const DISPATCHER_SLOT = Symbol.for('undici.globalDispatcher.1');
//
// Newer undici reads the `.2` slot and older undici the `.1` slot, and both
// copies can share the process, so every present slot gets wrapped.
const PRIMARY_SLOT = Symbol.for('undici.globalDispatcher.2');
const LEGACY_SLOT = Symbol.for('undici.globalDispatcher.1');
const DISPATCHER_SLOTS = [PRIMARY_SLOT, LEGACY_SLOT];
const globalSlots = globalThis as unknown as Record<symbol, unknown>;
void fetch('data:text/plain,dispatcher-guard').catch(() => {
@@ -52,7 +57,11 @@ void fetch('data:text/plain,dispatcher-guard').catch(() => {
const OUTBOUND_FETCH_TIMEOUT_MS = 10 * 60 * 1000;
// Symbol.for so a re-imported copy of this module (fresh module registry,
// same process) recognizes an already-wrapped dispatcher and doesn't re-wrap.
const TIMEOUTS_APPLIED = Symbol.for('puter.outboundFetchTimeouts');
// A set, not a marker property: compose() can return a Proxy, which would
// write the marker through to the unwrapped dispatcher.
const WRAPPED_DISPATCHERS = Symbol.for('puter.outboundFetchTimeouts');
const wrappedDispatchers = (globalSlots[WRAPPED_DISPATCHERS] ??=
new WeakSet<object>()) as WeakSet<object>;
type DispatchFn = (opts: Record<string, unknown>, handler: unknown) => boolean;
interface ComposableDispatcher {
@@ -61,29 +70,58 @@ interface ComposableDispatcher {
) => ComposableDispatcher;
}
const claimed = globalSlots[DISPATCHER_SLOT] as
| (ComposableDispatcher & Record<symbol, unknown>)
| undefined;
const withOutboundTimeouts =
(dispatch: DispatchFn): DispatchFn =>
(opts, handler) =>
// Defaults first so a per-request timeout, if one is ever passed,
// still wins.
dispatch(
{
headersTimeout: OUTBOUND_FETCH_TIMEOUT_MS,
bodyTimeout: OUTBOUND_FETCH_TIMEOUT_MS,
...opts,
},
handler,
);
// Newer undici negotiates HTTP/2, whose 256 KB default per-stream receive
// window caps a download at about window / RTT. That undici keeps a wrapper of
// its Agent in the legacy slot, so swap in a same-class Agent with larger
// windows and re-wrap it there.
const H2_WINDOWS = {
initialWindowSize: 4 * 1024 * 1024,
connectionWindowSize: 16 * 1024 * 1024,
};
type DispatcherClass = new (options: unknown) => ComposableDispatcher;
const primary = globalSlots[PRIMARY_SLOT] as ComposableDispatcher | undefined;
const legacy = globalSlots[LEGACY_SLOT] as ComposableDispatcher | undefined;
if (
claimed &&
typeof claimed.compose === 'function' &&
!(TIMEOUTS_APPLIED in claimed)
primary &&
legacy &&
primary !== legacy &&
primary.constructor.name === 'Agent' &&
!wrappedDispatchers.has(primary)
) {
const wrapped = claimed.compose(
(dispatch) => (opts, handler) =>
// Defaults first so a per-request timeout, if one is ever passed,
// still wins.
dispatch(
{
headersTimeout: OUTBOUND_FETCH_TIMEOUT_MS,
bodyTimeout: OUTBOUND_FETCH_TIMEOUT_MS,
...opts,
},
handler,
),
) as ComposableDispatcher & Record<symbol, unknown>;
wrapped[TIMEOUTS_APPLIED] = true;
globalSlots[DISPATCHER_SLOT] = wrapped;
const agent = new (primary.constructor as DispatcherClass)({
h2Options: H2_WINDOWS,
});
globalSlots[PRIMARY_SLOT] = agent;
globalSlots[LEGACY_SLOT] = new (legacy.constructor as DispatcherClass)(
agent,
);
}
for (const slot of DISPATCHER_SLOTS) {
const claimed = globalSlots[slot] as ComposableDispatcher | undefined;
if (
!claimed ||
typeof claimed.compose !== 'function' ||
wrappedDispatchers.has(claimed)
)
continue;
const wrapped = claimed.compose(withOutboundTimeouts);
wrappedDispatchers.add(wrapped);
globalSlots[slot] = wrapped;
}
export {};
+94
View File
@@ -17,6 +17,9 @@
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import diagnosticsChannel from 'node:diagnostics_channel';
import { createServer } from 'node:http';
import type { AddressInfo } from 'node:net';
import { Agent as UndiciAgent } from 'undici';
import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
import { configContainer } from '../exports.js';
@@ -139,6 +142,97 @@ describe('global fetch dispatcher isolation', () => {
globalSlots[SLOT] = before;
}
});
it('sends plain fetch() requests out with the 10-minute timeouts', async () => {
const created: { headersTimeout?: number; bodyTimeout?: number }[] = [];
const onCreate = (message: unknown) => {
created.push((message as { request: (typeof created)[0] }).request);
};
const server = createServer((_req, res) => res.end('ok'));
await new Promise<void>((resolve) =>
server.listen(0, '127.0.0.1', resolve),
);
diagnosticsChannel.subscribe('undici:request:create', onCreate);
try {
const { port } = server.address() as AddressInfo;
const response = await fetch(`http://127.0.0.1:${port}/`);
expect(await response.text()).toBe('ok');
expect(created).toHaveLength(1);
expect(created[0].headersTimeout).toBe(10 * 60 * 1000);
expect(created[0].bodyTimeout).toBe(10 * 60 * 1000);
} finally {
diagnosticsChannel.unsubscribe('undici:request:create', onCreate);
server.close();
}
});
describe('HTTP/2 receive windows', () => {
// Stand-ins shaped like undici's: compose() returns a wrapper that
// records what it wraps.
class Agent {
options: unknown;
constructor(options?: unknown) {
this.options = options;
}
compose() {
return { wraps: this };
}
}
class Dispatcher1Wrapper {
agent: Agent;
constructor(agent: Agent) {
this.agent = agent;
}
compose() {
return { wraps: this };
}
}
const globalSlots = globalThis as unknown as Record<symbol, unknown>;
const PRIMARY = Symbol.for('undici.globalDispatcher.2');
const LEGACY = Symbol.for('undici.globalDispatcher.1');
const runGuardWith = async (primary: unknown, legacy: unknown) => {
const before = [globalSlots[PRIMARY], globalSlots[LEGACY]];
globalSlots[PRIMARY] = primary;
globalSlots[LEGACY] = legacy;
try {
vi.resetModules();
await import('./nodeFetchDispatcherGuard.js');
return {
primary: (globalSlots[PRIMARY] as { wraps: unknown }).wraps,
legacy: (globalSlots[LEGACY] as { wraps: unknown }).wraps,
};
} finally {
[globalSlots[PRIMARY], globalSlots[LEGACY]] = before;
}
};
it('swaps in an Agent with 4 MB stream / 16 MB connection windows', async () => {
const original = new Agent();
const slots = await runGuardWith(
original,
new Dispatcher1Wrapper(original),
);
expect(slots.primary).toBeInstanceOf(Agent);
expect(slots.primary).not.toBe(original);
expect((slots.primary as Agent).options).toEqual({
h2Options: {
initialWindowSize: 4 * 1024 * 1024,
connectionWindowSize: 16 * 1024 * 1024,
},
});
expect(slots.legacy).toBeInstanceOf(Dispatcher1Wrapper);
expect((slots.legacy as Dispatcher1Wrapper).agent).toBe(
slots.primary,
);
});
it('keeps a dispatcher both slots share', async () => {
const shared = new Agent();
const slots = await runGuardWith(shared, shared);
expect(slots.primary).toBe(shared);
expect(slots.legacy).toBe(shared);
});
});
});
describe('secureHttp URL validation', () => {
+1 -1
View File
@@ -4,7 +4,7 @@ description: Read a user's profile, returning null when it is not available.
platforms: [websites, apps, nodejs, workers]
---
Returns a user's profile: their picture, display name, and bio. A user can always read their own profile. Another user's profile is available only while that user is on a paid plan; otherwise the method resolves to `null`, the same as for a user who does not exist.
Returns a user's profile: their picture, display name, and bio. Users set these on the [Account page](https://puter.com/dashboard#account) of their Puter dashboard. A user can always read their own profile. Another user's profile is available only while that user is on a paid plan; otherwise the method resolves to `null`, the same as for a user who does not exist.
## Syntax
+31
View File
@@ -22,6 +22,7 @@ import UIWindowChangeEmail from '../Settings/UIWindowChangeEmail.js';
import UIWindowChangeUsername from '../UIWindowChangeUsername.js';
import UIWindowConfirmUserDeletion from '../Settings/UIWindowConfirmUserDeletion.js';
import UIWindowCopyToken from '../UIWindowCopyToken.js';
import UIWindowEditProfile from '../UIWindowEditProfile.js';
import UIWindow from '../UIWindow.js';
import UIProfilePictureCropModal from './UIProfilePictureCropModal.js';
import { isOrgSeat, orgSeatTeamName } from './orgSeat.js';
@@ -59,6 +60,20 @@ const TabAccount = {
// Account settings cards
h += '<div class="dashboard-settings-grid">';
// Display name and bio card
h += '<div class="dashboard-card dashboard-settings-card">';
h += '<div class="dashboard-settings-card-content">';
h += '<div class="dashboard-settings-card-icon">';
h += '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="2" y="5" width="20" height="14" rx="2"/><circle cx="8" cy="12" r="2"/><path d="M14 10h4M14 14h4"/></svg>';
h += '</div>';
h += '<div class="dashboard-settings-card-info">';
h += `<strong>${i18n('profile')}</strong>`;
h += `<span class="dashboard-profile-display-name">${html_encode(window.user?.profile?.displayName || i18n('profile_empty', [], false))}</span>`;
h += '</div>';
h += '</div>';
h += `<button class="button edit-profile">${i18n('edit_profile')}</button>`;
h += '</div>';
// Username card
h += '<div class="dashboard-card dashboard-settings-card">';
h += '<div class="dashboard-settings-card-content">';
@@ -163,6 +178,22 @@ const TabAccount = {
},
init ($el_window) {
$el_window.find('.dashboard-section-account .edit-profile').on('click', function (e) {
UIWindowEditProfile({
window_options: {
parent_uuid: $el_window.attr('data-element_uuid'),
backdrop: true,
close_on_backdrop_click: true,
parent_center: true,
stay_on_top: true,
has_head: false,
},
onSave: (profile) => {
$el_window.find('.dashboard-section-account .dashboard-profile-display-name')
.text(profile.displayName || i18n('profile_empty', [], false));
},
});
});
$el_window.find('.dashboard-section-account .change-password').on('click', function (e) {
UIWindowChangePassword({
window_options: {
+116
View File
@@ -0,0 +1,116 @@
/*
* Copyright (C) 2024-present Puter Technologies Inc.
*
* This file is part of Puter.
*
* Puter is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import UIWindow from './UIWindow.js';
// Keep in sync with ProfileService on the backend.
const DISPLAY_NAME_MAX_LENGTH = 64;
const BIO_MAX_LENGTH = 280;
/**
* Edits the signed-in user's display name and bio. `options.onSave` receives
* the saved profile.
*/
async function UIWindowEditProfile (options) {
options = options ?? {};
const internal_id = window.uuidv4();
let h = '';
h += '<div class="edit-profile" style="padding: 20px; border-bottom: 1px solid #ced7e1;">';
h += '<div class="form-error-msg"></div>';
h += '<div class="form-success-msg"></div>';
h += '<div style="overflow: hidden; margin-bottom: 20px;">';
h += `<label for="edit-profile-display-name-${internal_id}">${i18n('display_name')}</label>`;
h += `<input id="edit-profile-display-name-${internal_id}" type="text" class="edit-profile-display-name" maxlength="${DISPLAY_NAME_MAX_LENGTH}" autocomplete="off" />`;
h += '</div>';
h += '<div style="overflow: hidden; margin-bottom: 20px;">';
h += `<label for="edit-profile-bio-${internal_id}">${i18n('bio')}</label>`;
h += `<textarea id="edit-profile-bio-${internal_id}" class="edit-profile-bio" maxlength="${BIO_MAX_LENGTH}" rows="4" style="display: block; width: 100%; padding: 8px; box-sizing: border-box; resize: vertical; border: 1px solid #ccc; border-radius: 4px; font: inherit; font-size: 14px; color: #393f46;"></textarea>`;
h += '</div>';
h += `<button class="edit-profile-btn button button-primary button-block button-normal">${i18n('save')}</button>`;
h += '</div>';
const el_window = await UIWindow({
title: i18n('edit_profile'),
app: 'edit-profile',
single_instance: true,
icon: null,
uid: null,
is_dir: false,
body_content: h,
has_head: true,
selectable_body: false,
draggable_body: false,
allow_context_menu: false,
is_resizable: false,
is_droppable: false,
init_center: true,
allow_native_ctxmenu: false,
allow_user_select: false,
width: 350,
height: 'auto',
dominant: true,
show_in_taskbar: false,
onAppend: function (this_window) {
$(this_window).find('.edit-profile-display-name').get(0)?.focus({ preventScroll: true });
},
window_class: 'window-publishWebsite',
body_css: {
width: 'initial',
height: '100%',
'background-color': 'rgb(245 247 249)',
'backdrop-filter': 'blur(3px)',
},
...options.window_options,
});
const $fields = $(el_window).find('.edit-profile-display-name, .edit-profile-bio');
$(el_window).find('.edit-profile-display-name').val(window.user?.profile?.displayName ?? '');
$(el_window).find('.edit-profile-bio').val(window.user?.profile?.bio ?? '');
$(el_window).find('.edit-profile-btn').on('click', async function () {
const $btn = $(el_window).find('.edit-profile-btn');
$(el_window).find('.form-success-msg, .form-error-msg').hide();
$btn.addClass('disabled');
$fields.attr('disabled', true);
// An empty field clears it.
const patch = {
displayName: String($(el_window).find('.edit-profile-display-name').val() ?? '').trim() || null,
bio: String($(el_window).find('.edit-profile-bio').val() ?? '').trim() || null,
};
// update_profile resolves with no profile when the request failed.
const profile = await window.update_profile(window.user.username, patch);
$btn.removeClass('disabled');
$fields.attr('disabled', false);
if ( ! profile ) {
$(el_window).find('.form-error-msg').html(i18n('profile_save_failed'));
$(el_window).find('.form-error-msg').fadeIn();
return;
}
$(el_window).find('.edit-profile-display-name').val(profile.displayName ?? '');
$(el_window).find('.edit-profile-bio').val(profile.bio ?? '');
$(el_window).find('.form-success-msg').html(i18n('profile_saved'));
$(el_window).find('.form-success-msg').fadeIn();
options.onSave?.(profile);
});
}
export default UIWindowEditProfile;
@@ -0,0 +1,87 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
vi.mock('./UIWindow.js', () => ({
default: vi.fn(async () => ({})),
}));
globalThis.i18n = (key) => key;
/** Minimal jQuery stand-in: a selector -> value map drives the handler. */
const fields = {};
const shown = {};
let clickHandler = null;
const node = (sel) => {
const self = {
val: (v) => {
if ( v === undefined ) return fields[sel];
fields[sel] = v;
return self;
},
on: (evt, fn) => {
if ( evt === 'click' && sel === '.edit-profile-btn' ) clickHandler = fn;
return self;
},
html: (v) => {
shown[sel] = v;
return self;
},
show: () => self,
hide: () => self,
fadeIn: () => self,
addClass: () => self,
removeClass: () => self,
attr: () => self,
get: () => undefined,
};
return self;
};
globalThis.$ = () => ({ find: node });
const { default: UIWindowEditProfile } = await import('./UIWindowEditProfile.js');
describe('the edit-profile window', () => {
beforeEach(() => {
for ( const key of Object.keys(fields) ) delete fields[key];
for ( const key of Object.keys(shown) ) delete shown[key];
clickHandler = null;
globalThis.window = {
uuidv4: () => 'test-id',
user: { username: 'alice', profile: { displayName: 'Alice', bio: 'Hi there' } },
update_profile: vi.fn(async (_username, patch) => patch),
};
});
it('prefills the current display name and bio', async () => {
await UIWindowEditProfile({});
expect(fields['.edit-profile-display-name']).toBe('Alice');
expect(fields['.edit-profile-bio']).toBe('Hi there');
});
it('saves trimmed values and clears empty fields', async () => {
const onSave = vi.fn();
await UIWindowEditProfile({ onSave });
fields['.edit-profile-display-name'] = ' Alice Smith ';
fields['.edit-profile-bio'] = ' ';
await clickHandler();
expect(window.update_profile).toHaveBeenCalledWith('alice', {
displayName: 'Alice Smith',
bio: null,
});
expect(onSave).toHaveBeenCalledWith({ displayName: 'Alice Smith', bio: null });
expect(shown['.form-success-msg']).toBe('profile_saved');
});
it('shows an error and skips onSave when the save fails', async () => {
window.update_profile = vi.fn(async () => undefined);
const onSave = vi.fn();
await UIWindowEditProfile({ onSave });
await clickHandler();
expect(shown['.form-error-msg']).toBe('profile_save_failed');
expect(onSave).not.toHaveBeenCalled();
});
});
+5
View File
@@ -630,6 +630,11 @@ window.update_auth_data = async (auth_token, user) => {
// ----------------------------------------------------
user.profile = {};
puter.auth.getProfile().then((profile) => {
window.user.profile.displayName = profile?.displayName ?? null;
window.user.profile.bio = profile?.bio ?? null;
if ( profile?.displayName ) {
$('.dashboard-profile-display-name').text(profile.displayName);
}
if ( profile?.picture ) {
window.user.profile.picture = html_encode(profile.picture);
$('.profile-pic').css('background-image', `url(${window.user.profile.picture})`);
+7
View File
@@ -66,6 +66,7 @@ const en = {
auto_arrange: 'Auto Arrange',
back: 'Back',
background: 'Background',
bio: 'Bio',
browse: 'Browse',
browser: 'Browser',
browser_version: 'Browser Version',
@@ -172,6 +173,7 @@ const en = {
disable_2fa_confirm: 'Are you sure you want to disable 2FA?',
disable_2fa_instructions: 'Confirm your identity and enter the code from your authenticator app to disable 2FA.',
disassociate_dir: 'Disassociate Directory',
display_name: 'Display Name',
directory: 'Directory',
disassociate: 'disassociate',
disk_storage: 'Disk Storage',
@@ -307,6 +309,7 @@ const en = {
apps_load_failed: 'Failed to load apps',
done_editing: 'Done editing',
edit_apps: 'Edit apps',
edit_profile: 'Edit Profile',
folder_pages: 'Folder pages',
next_page: 'Next page',
no_apps_installed: 'No apps installed yet',
@@ -388,12 +391,16 @@ const en = {
process_type_app: 'App',
process_type_init: 'Init',
process_type_ui: 'UI',
profile: 'Profile',
profile_empty: 'Add a display name and bio',
profile_picture_adjust_hint: 'Drag to reposition. Scroll or use the slider to zoom.',
profile_picture_adjust_hint_touch: 'Drag to move. Pinch or use the slider to zoom.',
profile_picture_hint: 'Click the avatar to change your profile picture',
profile_picture_load_failed: 'This image could not be opened. Please try another file.',
profile_picture_remove_failed: 'Your photo could not be removed. Please try again.',
profile_picture_save_failed: 'Your photo could not be saved. Please try again.',
profile_save_failed: 'Your profile could not be saved. Please try again.',
profile_saved: 'Profile saved.',
properties: 'Properties',
public: 'Public',
publish: 'Publish',
+30 -3
View File
@@ -21,6 +21,18 @@ import { showUsageLimitDialog } from '../modules/UsageLimitDialog.js';
* }} RefusalShape
*/
/**
* The parts of the SDK instance the prompt reads.
*
* @typedef {{
* env?: string,
* ui?: { requestUpgrade: Function },
* authToken?: string,
* appID?: string,
* getAppIDFromAuthToken?: (token: unknown) => string | null,
* }} PromptingSdk
*/
const TITLES = {
funds: 'Low Balance',
subscription: 'Subscription Required',
@@ -102,8 +114,8 @@ const messageFor = (reason, error, context) => {
* @param {unknown} error The rejection, in whatever shape it arrived.
* @param {UpgradePromptContext} [context] Which SDK method was refused and,
* for a plan gate, why it needs one.
* @param {{ env?: string, ui?: { requestUpgrade: Function } }} [puter] The SDK
* instance the call ran against; defaults to the global one.
* @param {PromptingSdk} [puter] The SDK instance the call ran against;
* defaults to the global one.
*/
export const promptIfUpgradeRequired = (error, context = {}, puter = globalThis.puter) => {
const reason = classifyUpgradeRefusal(error);
@@ -115,6 +127,21 @@ export const promptIfUpgradeRequired = (error, context = {}, puter = globalThis.
if ( puter?.env === 'app' ) {
puter.ui.requestUpgrade({ reason, method, message });
} else if ( puter?.env === 'web' || reason === 'storage' ) {
showUsageLimitDialog(message, { title: TITLES[reason], method });
showUsageLimitDialog(message, {
title: TITLES[reason],
method,
reason,
appID: appIDOf(puter),
});
}
};
/**
* The app the refused call ran as: the one the auth token was issued to, else
* the one the page set.
*
* @param {PromptingSdk | undefined} puter
* @returns {string | undefined}
*/
const appIDOf = (puter) =>
puter?.getAppIDFromAuthToken?.(puter.authToken) || puter?.appID || undefined;
+28 -7
View File
@@ -96,7 +96,7 @@ describe('promptIfUpgradeRequired', () => {
promptIfUpgradeRequired({ code: 'insufficient_funds', status: 402 }, { method: 'puter-kvstore::set' });
expect(showUsageLimitDialog).toHaveBeenCalledWith(
'Your account does not have enough funding to complete this request.',
{ title: 'Low Balance', method: 'puter-kvstore::set' },
{ title: 'Low Balance', method: 'puter-kvstore::set', reason: 'funds' },
);
});
@@ -104,7 +104,7 @@ describe('promptIfUpgradeRequired', () => {
promptIfUpgradeRequired({ code: 'storage_limit_reached', status: 413 }, { method: 'puter.fs.upload' });
expect(showUsageLimitDialog).toHaveBeenCalledWith(
'Not enough storage space available.',
{ title: 'Out of Storage', method: 'puter.fs.upload' },
{ title: 'Out of Storage', method: 'puter.fs.upload', reason: 'storage' },
);
});
@@ -115,7 +115,7 @@ describe('promptIfUpgradeRequired', () => {
);
expect(showUsageLimitDialog).toHaveBeenCalledWith(
'Sending email requires a subscription.',
{ title: 'Subscription Required', method: 'puter.email.sendTransactional' },
{ title: 'Subscription Required', method: 'puter.email.sendTransactional', reason: 'subscription' },
);
});
@@ -126,7 +126,7 @@ describe('promptIfUpgradeRequired', () => {
);
expect(showUsageLimitDialog).toHaveBeenCalledWith(
'External email requires a subscription.',
{ title: 'Subscription Required', method: 'puter.email.send' },
{ title: 'Subscription Required', method: 'puter.email.send', reason: 'subscription' },
);
});
@@ -137,7 +137,7 @@ describe('promptIfUpgradeRequired', () => {
});
expect(showUsageLimitDialog).toHaveBeenCalledWith(
'Pro plan only.',
{ title: 'Subscription Required', method: undefined },
{ title: 'Subscription Required', method: undefined, reason: 'subscription' },
);
});
@@ -145,7 +145,28 @@ describe('promptIfUpgradeRequired', () => {
promptIfUpgradeRequired({ code: 'subscription_required', status: 402 });
expect(showUsageLimitDialog).toHaveBeenCalledWith(
'This action requires a subscription.',
{ title: 'Subscription Required', method: undefined },
{ title: 'Subscription Required', method: undefined, reason: 'subscription' },
);
});
it('names the app the refused call ran as, from its token first', () => {
globalThis.puter = {
env: 'web',
authToken: 'token',
appID: 'app-set-by-page',
getAppIDFromAuthToken: (token) => (token === 'token' ? 'app-from-token' : null),
};
promptIfUpgradeRequired({ status: 402 }, { method: 'puter.ai.chat' });
expect(showUsageLimitDialog).toHaveBeenLastCalledWith(
expect.any(String),
expect.objectContaining({ appID: 'app-from-token' }),
);
globalThis.puter.getAppIDFromAuthToken = () => null;
promptIfUpgradeRequired({ status: 402 }, { method: 'puter.ai.chat' });
expect(showUsageLimitDialog).toHaveBeenLastCalledWith(
expect.any(String),
expect.objectContaining({ appID: 'app-set-by-page' }),
);
});
@@ -185,7 +206,7 @@ describe('promptIfUpgradeRequired', () => {
promptIfUpgradeRequired({ code: 'storage_limit_reached' }, { method: 'puter.fs (/copy)' });
expect(showUsageLimitDialog).toHaveBeenCalledWith(
'Not enough storage space available.',
{ title: 'Out of Storage', method: 'puter.fs (/copy)' },
{ title: 'Out of Storage', method: 'puter.fs (/copy)', reason: 'storage' },
);
expect(globalThis.puter.ui.requestUpgrade).not.toHaveBeenCalled();
},
+29 -5
View File
@@ -1,19 +1,43 @@
import { escapeHtml } from '../lib/html.js';
/** @typedef {{ title?: string, method?: string }} UsageLimitDialogOptions */
/**
* @typedef {Object} UsageLimitDialogOptions
* @property {string} [title] Replaces the default heading.
* @property {string} [method] The SDK call that was refused.
* @property {string} [reason] Which upgrade the refusal asks for.
* @property {string} [appID] The app the refused call ran as.
*/
const UPGRADE_PAGE = 'https://puter.com/dashboard/';
/**
* The dashboard page the upgrade button opens. It carries what was refused,
* so the dashboard can open its upgrade flow with that context.
*
* @param {Pick<UsageLimitDialogOptions, 'reason' | 'appID' | 'method'>} [context]
* @returns {string}
*/
export const upgradeUrl = ({ reason, appID, method } = {}) => {
const url = new URL(UPGRADE_PAGE);
if ( reason ) url.searchParams.set('upgrade', reason);
if ( appID ) url.searchParams.set('upgrade_app', appID);
if ( method ) url.searchParams.set('upgrade_method', method);
url.hash = 'home';
return url.href;
};
class UsageLimitDialog extends (globalThis.HTMLElement || Object) {
/**
* @param {string} message Plain-text line saying what was refused.
* @param {UsageLimitDialogOptions} [options] `title` replaces the default
* heading; `method` names the SDK call that was refused.
* @param {UsageLimitDialogOptions} [options]
*/
constructor (message, { title = 'Low Balance', method } = {}) {
constructor (message, { title = 'Low Balance', method, reason, appID } = {}) {
super();
this.message = message || 'You have reached your usage limit for this account.';
// Not `this.title`: on an HTMLElement that is the tooltip attribute.
this.heading = title;
this.method = method;
this.upgradeUrl = upgradeUrl({ reason, appID, method });
this.attachShadow({ mode: 'open' });
@@ -246,7 +270,7 @@ class UsageLimitDialog extends (globalThis.HTMLElement || Object) {
});
this.shadowRoot.querySelector('#upgrade-btn').addEventListener('click', () => {
window.open('https://puter.com/dashboard/#home', '_blank');
window.open(this.upgradeUrl, '_blank');
this.close();
});
@@ -0,0 +1,24 @@
import { describe, expect, it } from 'vitest';
import { upgradeUrl } from './UsageLimitDialog.js';
describe('upgradeUrl', () => {
it('opens the dashboard with what was refused', () => {
const url = new URL(upgradeUrl({
reason: 'funds',
appID: 'app-0b8a6d4e-6c1f-4a52-9d3e-2f7b1c9e8a10',
method: 'puter-chat-completion::complete',
}));
expect(url.origin + url.pathname).toBe('https://puter.com/dashboard/');
expect(url.hash).toBe('#home');
expect(Object.fromEntries(url.searchParams)).toEqual({
upgrade: 'funds',
upgrade_app: 'app-0b8a6d4e-6c1f-4a52-9d3e-2f7b1c9e8a10',
upgrade_method: 'puter-chat-completion::complete',
});
});
it('leaves out what it was not told', () => {
expect(upgradeUrl({ reason: 'storage' })).toBe('https://puter.com/dashboard/?upgrade=storage#home');
expect(upgradeUrl()).toBe('https://puter.com/dashboard/#home');
});
});
+3
View File
@@ -44,6 +44,9 @@ export default defineConfig(({ mode }) => ({
// workerd runners are slower than unit tests.
testTimeout: 60_000,
hookTimeout: 120_000,
// Node's own localStorage global is undefined without a storage file
// and keeps vitest from installing jsdom's in its place.
execArgv: ['--no-experimental-webstorage'],
root: repoRoot,
},
}));