diff --git a/.github/workflows/ai-provider-integration-tests.yaml b/.github/workflows/ai-provider-integration-tests.yaml index a63a72da2..614e7b027 100644 --- a/.github/workflows/ai-provider-integration-tests.yaml +++ b/.github/workflows/ai-provider-integration-tests.yaml @@ -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 diff --git a/.github/workflows/backend-tests.yaml b/.github/workflows/backend-tests.yaml index 9bb8a62df..6f4de90c9 100644 --- a/.github/workflows/backend-tests.yaml +++ b/.github/workflows/backend-tests.yaml @@ -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 diff --git a/.github/workflows/docs-build.yml b/.github/workflows/docs-build.yml index b711b1578..dd4532ffd 100644 --- a/.github/workflows/docs-build.yml +++ b/.github/workflows/docs-build.yml @@ -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 diff --git a/.github/workflows/puterjs-tests.yaml b/.github/workflows/puterjs-tests.yaml index 5d29bc5fb..c1a3f0e32 100644 --- a/.github/workflows/puterjs-tests.yaml +++ b/.github/workflows/puterjs-tests.yaml @@ -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 diff --git a/Dockerfile b/Dockerfile index 3f612de65..d7c10c0c5 100644 --- a/Dockerfile +++ b/Dockerfile @@ -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 diff --git a/src/backend/drivers/util/imageInput.test.ts b/src/backend/drivers/util/imageInput.test.ts index fd2da9050..6dc19a4a0 100644 --- a/src/backend/drivers/util/imageInput.test.ts +++ b/src/backend/drivers/util/imageInput.test.ts @@ -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( diff --git a/src/backend/util/nodeFetchDispatcherGuard.ts b/src/backend/util/nodeFetchDispatcherGuard.ts index aaadb4f1c..614677377 100644 --- a/src/backend/util/nodeFetchDispatcherGuard.ts +++ b/src/backend/util/nodeFetchDispatcherGuard.ts @@ -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; 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()) as WeakSet; type DispatchFn = (opts: Record, handler: unknown) => boolean; interface ComposableDispatcher { @@ -61,29 +70,58 @@ interface ComposableDispatcher { ) => ComposableDispatcher; } -const claimed = globalSlots[DISPATCHER_SLOT] as - | (ComposableDispatcher & Record) - | 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; - 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 {}; diff --git a/src/backend/util/secureHttp.test.ts b/src/backend/util/secureHttp.test.ts index 8395bcef1..741cb6013 100644 --- a/src/backend/util/secureHttp.test.ts +++ b/src/backend/util/secureHttp.test.ts @@ -17,6 +17,9 @@ * along with this program. If not, see . */ +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((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; + 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', () => { diff --git a/src/docs/src/Auth/getProfile.md b/src/docs/src/Auth/getProfile.md index 59abcc5e6..c9f34e9b7 100644 --- a/src/docs/src/Auth/getProfile.md +++ b/src/docs/src/Auth/getProfile.md @@ -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 diff --git a/src/gui/src/UI/Dashboard/TabAccount.js b/src/gui/src/UI/Dashboard/TabAccount.js index 92c1c508f..a677c21a5 100644 --- a/src/gui/src/UI/Dashboard/TabAccount.js +++ b/src/gui/src/UI/Dashboard/TabAccount.js @@ -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 += '
'; + // Display name and bio card + h += '
'; + h += '
'; + h += '
'; + h += ''; + h += '
'; + h += '
'; + h += `${i18n('profile')}`; + h += `${html_encode(window.user?.profile?.displayName || i18n('profile_empty', [], false))}`; + h += '
'; + h += '
'; + h += ``; + h += '
'; + // Username card h += '
'; h += '
'; @@ -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: { diff --git a/src/gui/src/UI/UIWindowEditProfile.js b/src/gui/src/UI/UIWindowEditProfile.js new file mode 100644 index 000000000..60a21d5d8 --- /dev/null +++ b/src/gui/src/UI/UIWindowEditProfile.js @@ -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 . + */ + +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 += '
'; + h += '
'; + h += '
'; + h += '
'; + h += ``; + h += ``; + h += '
'; + h += '
'; + h += ``; + h += ``; + h += '
'; + h += ``; + h += '
'; + + 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; diff --git a/src/gui/src/UI/UIWindowEditProfile.test.js b/src/gui/src/UI/UIWindowEditProfile.test.js new file mode 100644 index 000000000..e14fc3836 --- /dev/null +++ b/src/gui/src/UI/UIWindowEditProfile.test.js @@ -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(); + }); +}); diff --git a/src/gui/src/helpers.js b/src/gui/src/helpers.js index 5d074f3cb..c8a7926c9 100644 --- a/src/gui/src/helpers.js +++ b/src/gui/src/helpers.js @@ -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})`); diff --git a/src/gui/src/i18n/translations/en.js b/src/gui/src/i18n/translations/en.js index 1bc50b6da..e83676bcd 100644 --- a/src/gui/src/i18n/translations/en.js +++ b/src/gui/src/i18n/translations/en.js @@ -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', diff --git a/src/puter-js/src/lib/upgradePrompt.js b/src/puter-js/src/lib/upgradePrompt.js index 639f5bcb1..57d122bb8 100644 --- a/src/puter-js/src/lib/upgradePrompt.js +++ b/src/puter-js/src/lib/upgradePrompt.js @@ -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; diff --git a/src/puter-js/src/lib/upgradePrompt.test.js b/src/puter-js/src/lib/upgradePrompt.test.js index 56fc75626..c13c44a1f 100644 --- a/src/puter-js/src/lib/upgradePrompt.test.js +++ b/src/puter-js/src/lib/upgradePrompt.test.js @@ -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(); }, diff --git a/src/puter-js/src/modules/UsageLimitDialog.js b/src/puter-js/src/modules/UsageLimitDialog.js index 9a5897a18..eb449352b 100644 --- a/src/puter-js/src/modules/UsageLimitDialog.js +++ b/src/puter-js/src/modules/UsageLimitDialog.js @@ -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} [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(); }); diff --git a/src/puter-js/src/modules/UsageLimitDialog.test.js b/src/puter-js/src/modules/UsageLimitDialog.test.js new file mode 100644 index 000000000..dbd6636e8 --- /dev/null +++ b/src/puter-js/src/modules/UsageLimitDialog.test.js @@ -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'); + }); +}); diff --git a/src/puter-js/tests/api/vitest.config.ts b/src/puter-js/tests/api/vitest.config.ts index a523ff9bb..01edff412 100644 --- a/src/puter-js/tests/api/vitest.config.ts +++ b/src/puter-js/tests/api/vitest.config.ts @@ -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, }, }));