Compare commits

..
Author SHA1 Message Date
Nariman Jelveh 33988ac84c Remove the desktop taskbar (#4605)
* Remove the desktop taskbar

The desktop no longer has a taskbar. Windows on /desktop can't be
minimized, since nothing could bring them back; the dashboard still
minimizes into app tiles. The desktop and maximized windows use the
full page height.

Backend: POST /update-taskbar-items is removed, and /whoami and the
login response no longer include taskbar_items. The user table's
taskbar_items column stays until a migration drops it.

puter.ui.createWindow() still accepts show_in_taskbar, which has no
effect and is marked deprecated.

* Keep desktop backdrops above ordinary windows

A backdrop's z-index used to take the taskbar's as a floor, which kept
modal dialogs on /desktop above every ordinary window, including ones
focused after the dialog opened. Keep that floor on the desktop; the
dashboard and fullpage mode stack as before.

Also drops commented-out geometry that referenced window.taskbar_height,
and a dashboard comment about the removed fullpage minimize rule.

* Keep dropped desktop icons fully on screen, and fill the phone popover

A desktop icon drop is accepted only where the whole item fits above the
bottom edge. Phone popovers use the full viewport height.
2026-11-11 20:16:13 -07:00
Nariman Jelveh 72de6e16b2 Remove the desktop wallpaper (#4604)
The desktop no longer shows a wallpaper. It shows the page's plain
background color: white, or #1e1e1e in dark mode. The sign-in dialogs
and account picker that opened over the wallpaper now open over that
color too.

This removes the default wallpaper image and its credit, its preload in
both page shells, the "Set as Desktop Background" item on images'
right-click menu, the GUI's set_desktop_background and
refresh_desktop_background, and the set_as_background i18n key.
Desktop icon labels were white with a shadow to read on the wallpaper;
they now use the same gray as labels inside windows, and a light gray
in dark mode.

The backend drops POST /set-desktop-bg, and /whoami no longer returns
desktop_bg_url, desktop_bg_color or desktop_bg_fit. The user table's
desktop_bg_* columns stay; dropping them needs a migration.
2026-11-11 17:40:52 -07:00
Nariman Jelveh 234994d3af Remove the desktop toolbar and nine desktop features, and use puter.js's color picker on the desktop (#4602)
* Remove the desktop's QR login button

The desktop toolbar no longer shows a QR code that signs another device
into the current session. This removes the toolbar button, its click
handler, the UIWindowQR window (its only caller), the qr.svg icon, the
window's CSS, and the four i18n keys only that window used.

UIQRCode and the qrcode library stay, since 2FA setup still uses them.
The ?auth_token= handler in initgui also stays, because the Playwright
e2e harness signs in through it.

* Remove the desktop's My Websites window

The user menu no longer has a My Websites item. This removes the
UIWindowMyWebsites window, its menu item, its CSS, the plug.svg icon only
it used, and the i18n keys only it used.

When publishing a website or worker hits the subdomain limit, the error
now shows only the server's message, without the "Manage your subdomains"
link that opened the window. The trash handlers keep fading the website
badge on a trashed folder and no longer touch the window's rows.

* Remove the desktop's Task Manager window

The user menu no longer has a Task Manager item. This removes the
UIWindowTaskManager window, its menu item, its CSS, the cog.svg icon only
it used, and the i18n keys only it used, including the process_type_*
and process_status_* keys it built at runtime.

The process model in definitions.js, including END_SOFT and END_HARD,
stays: windows still register processes, and a process still forwards
an end signal to its children.

* Remove the desktop's Change Desktop Background window

The desktop's context menu no longer has a "Change Desktop Background…"
item, or the separator above it. This removes the
UIWindowDesktopBGSettings window, its CSS, the palette.svg icon only it
used, and the i18n keys only it used.

Desktop backgrounds still work: the saved background loads at boot, and
an image's "Set as Desktop Background" item still applies and saves it
through /set-desktop-bg.

* Remove the desktop's Start menu

The taskbar no longer has a Start button, so it begins at Explorer. This
removes the Start item and its app popover (recent and recommended apps,
search, tile context menu, and drag-to-taskbar), along with:

- The taskbar's startup /get-launch-apps request and the desktop's
  app.opened socket handler, which only kept the menu's lists current
- The Start popover's search, click and keyboard handlers in UIDesktop.js,
  keyboard.js, initgui.js and UITaskbarItem.js
- The taskbar's handling of items dropped from outside it, and the
  UITaskbarItem append_to_taskbar option only that path used
- The Start CSS, the start.svg icon, and the i18n keys only the menu used

The dashboard's recently used apps still load, since the dashboard fetches
its own list and launchApp.js still records launches. UITaskbar.test.js now
covers the taskbar's item order and that it doesn't fetch launch apps.

* Remove the desktop's Search window

The desktop toolbar no longer has a Search button, and Ctrl/Cmd+F on the
desktop no longer opens the Search window, so it falls through to the
browser's find as it already did on the dashboard. This removes
UIWindowSearch, the toolbar button and its handler, the window's
keyboard handling (arrow keys, Enter, Escape) and click-outside close,
its CSS, the search.svg and magnifier-outline.svg icons only it used, and
the i18n keys only it used.

The backend /search endpoint is unchanged.

* Remove the desktop toolbar

The desktop no longer has the toolbar at the top of the screen, so its
Puter logo, guest Save Account button, and account menu are gone from the
desktop. Log out, account switching, language, settings, and contact all
remain on the dashboard.

Removed:
- The toolbar markup, its auto-hide logic and mouse tracking, its
  right-click menu, and the account menu with its click handlers
- The modify-user-options-menu GUI extension, which only added a
  Developer item to that menu
- UIWindowFeedback, the desktop's Contact Us window, which only the menu
  opened; the dashboard keeps its own contact dialog
- Toolbar hooks elsewhere: the hide_toolbar() call on window maximize,
  pointer-events toggles during window and item drags, the click guard in
  initgui, the account-button toggle in helpers.js, and the avatar sync
  for the toolbar's profile image in TabAccount
- The toolbar and feedback CSS, the toolbar's two KV keys from the
  puter.js GUI read cache, and the i18n keys only these used

window.toolbar_height stays: it was already 0, so window and desktop
layout are unchanged. The welcome window keeps its backdrop stacking.

* Remove the desktop's Share window

The right-click menu on desktop and Explorer items, and on items in open
and save file dialogs, no longer has a Share item. This removes
UIWindowShare, that menu item, the share-outline.svg icon only it used, its
CSS, and the share_with and share_row_team i18n keys only it used.

The Dashboard keeps sharing through UIShareModal. generateFileContextMenu
no longer falls back to the removed window, so it offers Share only when
the caller passes onShare, which the Dashboard's Files tab does. The share
dialog layout classes the Blocked Senders window uses, and the recipient
suggestion styles the share modal uses, stay.

* Remove the desktop's Welcome window

New desktop users no longer see the Welcome window on their first visit.
This removes UIWindowWelcome, the first-visit check in UIDesktop that
opened it, its CSS, the welcome_* i18n keys only it used, and the
UIWindow backdrop_covers_toolbar option only it passed.

has_seen_welcome_window is also dropped from the puter.js GUI boot read
cache. Values already saved under that key stay in KV, unread.

* Replace the desktop's color picker with puter.js's picker

puter.ui.showColorPicker() inside Puter now opens puter.js's own
<puter-color-picker>, the one it already shows on websites outside Puter,
instead of the desktop's iro-based window. Apps get the same answer
everywhere: a lowercase 6-digit hex string, or null when the user cancels.
Inside Puter it used to resolve to an 8-digit hex with alpha, or undefined.

This removes UIWindowColorPicker, UIColorPickerWidget, iro.min.js and its
lib-list entries, and the select_color i18n key only that window used.

The GUI loads puter.js from js.puter.com, so the IPC handler doesn't rely
on this branch's component: it drops the alpha from an 8-digit default,
leaves out a default that isn't a 3- or 6-digit hex, and removes the
picker once it answers.

<puter-color-picker> drops the alpha from an 8-digit default instead of
failing to open, opens on its own color when the default isn't valid,
and removes itself when Escape closes it. showColorPicker()'s type and
docs now give the 6-digit return value and null on cancel.

* Remove the desktop's Publish Worker window

The right-click menu on .js files on the desktop and in Explorer, and in
open and save file dialogs, no longer has a Publish as Worker item. This
removes UIWindowPublishWorker, that menu item, its CSS, and the
pick_name_for_worker i18n key only it used.

The Dashboard keeps publishing workers through its own dialog.
generateFileContextMenu no longer falls back to the removed window, so it
offers Publish as Worker only when the caller passes onPublishWorker,
which the Dashboard's Files tab does.

* Add a Language setting to the dashboard's Account tab

The desktop toolbar's account menu was the only place to change Puter's
language, so removing the toolbar left no way to change it. The Account
tab now has a Language card that shows the current language and opens a
dialog listing every supported language by its own name. Saving a new
one stores it on the account and reloads the page in it.

changeLanguage() now returns false when the language can't be saved, so
the dialog can show an error instead of doing nothing. The
change_language key comes back in every locale, and
language_save_failed is new.
2026-11-11 17:17:30 -07:00
Nariman Jelveh eef2d089a8 Remove the dashboard's Open Desktop card and the unused theme dialog (#4601)
* Remove the unused theme dialog and its translations

UIWindowThemeDialog has had no importers since the settings window was
removed, and the reset_colors, ui_colors and change_ui_colors strings
are referenced only by it or by nothing at all.

* Remove the Open Desktop card from the dashboard Home tab

Drops the card's markup, styles, color tokens, and the open_desktop and
open_desktop_hint strings, which nothing else uses.
2026-11-11 15:12:34 -07:00
Nariman Jelveh 711ece5800 feat(gui): let a first-party page frame the custom domain dialog (#4581)
* feat(gui): let a first-party page frame the custom domain dialog

`/embed/attach-custom-domain` joins the framed popups. On a signed-in page
one label under the Puter origin, `puter.hosting.attach()` now shows the
custom domain dialog in a frame over the page instead of a popup window.
Apps, the desktop and every other website keep their current behavior.

The frame covers the page with a transparent GUI page, so the dialog
floats over it with its own scrim as it does on the desktop. The GUI
serves only the framing page's own user, with no account check waiting,
and otherwise reports `unavailable`, which leaves the page to open the
popup as before. It runs the popup's action unchanged: the framing page
is the requester the dialog names, and gets the same
`customDomainAttached` answer.

Escape is left to the dialog, which doesn't close while a request is in
flight, and the frame allows `clipboard-write` for the DNS record copy
buttons. A call made while the frame shows resolves null without
replacing it, as a second call does on the desktop.

* Update RecommendedAppsService.ts

* fix(gui): let the framed custom domain dialog finish closing before it answers

The answer removes the frame from the page, so the dialog's exit transition
never showed. The framed action waits for the overlay to leave first, with the
wait the feedback embed already had, now one shared helper.
2026-11-11 11:44:39 -07:00
Filip Kujundžić 40ea3686da Merge pull request #4594 from HeyPuter/fix/chat-served-tier-pricing
Price native service tiers and served premium capacity
2026-11-11 18:02:29 +01:00
404oops db7ca8382b Price native service tiers and served premium capacity 2026-11-11 12:53:12 +01:00
404oops 0f2c325598 Meter Responses usage before validating empty output 2026-11-11 12:53:12 +01:00
404oops ffcfb85749 Validate voice changer models against the price table 2026-11-11 12:53:11 +01:00
Nariman Jelveh 44bf99f808 Update recommended apps 2026-11-10 20:36:06 -07:00
Nariman Jelveh d392b6857d fix(dashboard): drop the repeated add-on credits remainder from the Usage tab 2026-11-10 17:38:03 -07:00
Daniel Salazar d8c3e01dd9 fix(http): parse large JSON bodies in slices; store WebDAV uploads labeled as JSON (#4563)
JSON request bodies over 32 KiB are parsed in slices, with the event loop
running between them, instead of in one JSON.parse call. Reading, limits,
decompression, req.rawBody and the errors stay as express.json has them.
Large bodies parse one at a time.

Gemini TTS and video replies use the same parser, and their base64 is
checked and decoded 1 MiB at a time.

A profile picture is sized before its pattern runs, so one of several
megabytes gets a 413.

Body parsers skip the dav subdomain: a PUT labeled as JSON or form data
was read by them and stored empty, or refused.

puter.js sends auth_token as the first field of a driver call. A chat body
over 50 MiB that opens with a valid token is accepted up to 128 MiB, as
one with a header credential is.

JSON in a charset other than UTF-8 is now limited to 1 MiB, and a body
over 32 KiB nested deeper than 10,000 levels is refused.
2026-11-10 16:36:52 -07:00
Nariman Jelveh 4bc679956f fix(dashboard): label the Usage tab's credit bar "Monthly credits" 2026-11-10 16:28:49 -07:00
Daniel Salazar b751f75467 fix(fs): keep a file readable when two overwrites create the same path at once (#4579)
Two writers that both start before the row exists each upload under their
own object key. The second one found the first writer's row and updated its
bucket and size while keeping the first writer's uuid, so the row could name
an object that was never written under that key.

The store now leaves a row untouched when an overwrite arrives with a
different object key, and the service moves the uploaded bytes onto the
row's key before updating it. The last writer wins and the uuid is stable.
2026-11-10 16:15:42 -07:00
Daniel Salazar 224b2f2367 fix(backend): null driver args, non-string chat model, and long app-stats uid lists no longer answer 500 (#4576)
- drivers: a null `args` in a driver call is treated as no arguments
- ai-chat: a `model` that is not a string is answered as model not found (400)
- apps: app stats split a long uid list across ClickHouse queries, which cap the size of one query parameter
2026-11-10 16:08:55 -07:00
Nariman Jelveh 80bcc4ba14 feat(dashboard): show add-on credit as its own bar on the Usage tab (#4578)
The Usage tab told an account how much add-on credit it had left in a
line of text under the monthly meter. It now gets a meter of its own
there: a heading, how much of the credit bought has been spent, and a
bar, with the line saying what is left and when it is used kept under
it. An account that never had add-on credit sees the tab as before.
2026-11-10 15:11:21 -07:00
Nariman Jelveh f26201649a feat(gui): let a first-party page frame the deployment's top-up dialog (#4570)
* feat(gui): let a first-party page frame the deployment's top-up dialog

`/embed/top-up` joins the framed popups. Like the upgrade, it covers the
framing page with a transparent GUI page, serves only the page's own
user, and reports `unavailable` unless the deployment defines
`window.UITopUp` with `embeddable === true` and no account check is
waiting. It runs `new UITopUp({ onClose }).open()` and posts
`closed { toppedUp }` once the dialog closes. The frame's lifecycle is the
upgrade's, now shared by both.

`<puter-user-menu>` gets an Add credits item under Usage, shown only when
whoami reports `subscribed: true`. It frames the top-up on a page that can
frame the GUI, and otherwise opens the dashboard with `?topup=` in a new
tab, within the click. Hidden items are skipped by the menu's arrow keys.

`puter.ui.showTopUp_()` is internal; no public SDK method is added.

* fix(puter-js): show no usage-limit dialog over an open top-up

A call refused for funds while the framed top-up was open put the
usage-limit dialog in the top layer over it, covering the payment the
user was making to clear that refusal. The prompt now stays out of the
way while a top-up shows, as it does for the framed upgrade.

* fix(puter-js): leave Add credits out of the user menu for a team seat

whoami reports a seat as subscribed through its team's plan, so the menu
offered Add credits to an account that can't buy any: the dialog only
answers that the team pays. The item now stays hidden when whoami names a
team paying for the account, as the desktop's own menu already does.

* fix(puter-js): open the top-up tab on the page's own deployment

The tab the Add credits item falls back to went to puter.com whatever
GUI origin the page belongs to, so on another deployment it opened a
different one, signed in as whoever is signed in there. It now opens the
dashboard of the GUI origin, like the menu's Usage link beside it.

* fix(puter-js): return keyboard focus to the account button after Add credits

Choosing Add credits closed the menu with focus on the item it had just
hidden, and the frame restored focus to the menu's shadow host, which
can't take it, so a keyboard user was left on the page body once the
dialog closed. The menu now moves focus to its button first, and a
framed popup restores focus to the element inside a shadow root.

* docs(embed): say when the top-up dialog's open() resolves

It resolves after the account has loaded, not as soon as the dialog
shows.

* fix(puter-js): offer Add credits after an upgrade made on the page

The user menu showed Add credits by the whoami it loaded with the page.
A user who subscribed in the framed upgrade therefore found no Add
credits in the menu until a reload. A framed upgrade that reports a plan
now marks the page's cached whoami as subscribed, as a confirmed email
already is, and the menu reads it again each time it opens.

* fix(puter-js): let a top-up that failed to start be asked for again

showTopUp_ cleared its in-flight marker in a finally inside the async
function it stored. A failure before that function's first await, such
as building the dashboard address from an origin with no scheme, ran the
finally before the marker was set, so the marker kept the rejected
promise for good: every later call got the same rejection, and
topUpShowing_ went on suppressing the usage-limit dialog. The marker is
now cleared once the stored promise settles.

* fix(puter-js): keep requestUpgrade from framing the upgrade over an open top-up

The usage-limit dialog already stays away while the top-up shows, but a
page's own requestUpgrade() call, such as one in the handler of a call
refused mid-payment, still mounted the upgrade frame. Frames are single
per path, so it covered the top-up and the payment being typed in it,
and the two dialogs' own guard can't see across documents. The call now
waits for the top-up and resolves { upgraded: false } once it closes.

* fix(puter-js): offer Add credits after an upgrade when whoami was read again

The user menu keeps the whoami object it loaded and ignores a token set
again unchanged, but the SDK reads whoami into a new object each time a
token is set. A framed upgrade then marked the new object as subscribed
and the menu went on reading the old one, so Add credits stayed hidden
until a reload. The menu now reads the SDK's cached whoami when it is
the same account's.

* docs(embed): list the top-up tests among the checks to run
2026-11-10 14:53:34 -07:00
Nariman Jelveh 1550be358d fix(explorer): navigation, keyboard, drag-and-drop, realtime and layout fixes (#4569)
* fix(explorer): record typed address-bar paths in navigation history and canonicalize them

Pressing Enter in the path input now pushes the destination onto the
window's Back/Forward history like every other navigation, and resolves
the entry first (trim, ~ and home-relative expansion, trailing or doubled
slashes) so the window's path matches the form the rest of the GUI compares
against.

* fix(explorer): keep the address-bar input in step with the Shared view and the root

The path input was only updated after a successful stat, so in views that
are never statted it kept the previous folder's path and Enter navigated
back there.

* fix(explorer): drop the previous folder's identity when a folder fails to load

A rejected stat was never handled, so the window kept the previous folder's
uid, title and item count while showing the load error, and layout or sort
changes were saved to the wrong folder. The window now clears them, and the
failed request no longer surfaces as an unhandled rejection.

* fix(explorer): release a window's selection listeners and history when it closes

Each folder window left its rubber-band selection instance, a document
mouseup handler and its navigation history behind after closing, so every
later mouse press ran once per window ever opened. Windows that are not
folders no longer bind the handler at all.

* fix(explorer): anchor a Ctrl/Cmd rubber-band selection where the drag started

The rectangle's origin was only recorded for unmodified drags, so adding to
a selection drew it from the previous drag's start point or the top-left
corner.

* fix(explorer): keep arrow-key navigation on visible items and a valid anchor

Arrow keys could land on a hidden dotfile and then stop moving, threw when
the remembered anchor belonged to another window, and left the footer's
selected count stale.

* fix(explorer): ignore non-character keys in type-to-select

Shift, arrows and Enter were appended to the search term by name, so typing
a capital letter or typing right after navigating matched nothing. Hidden
files are no longer matched, and the footer count follows the container the
selection changed in.

* fix(explorer): make the keyboard permanent-delete confirmation work in every language

The confirmation compared the dialog's answer with the English button label,
so in any other language confirming did nothing.

* fix(explorer): paste once per Ctrl+V press

The shortcut ran on both keydown and keyup, so releasing V before Ctrl
pasted the clipboard twice.

* fix(explorer): keep selection shortcuts working after navigating, and out of text fields

Select All, Copy, Cut and Delete looked up the folder from the element last
pressed, which is a removed item or a sidebar entry after navigating, so the
shortcuts did nothing. Select All also skips hidden files, and Delete keys
typed in a text field are left to the field.

* fix(explorer): count only visible items in the footer and drop hidden files from the selection

The item count included dotfiles that were not shown, and hiding hidden
files left them selected, so a later Delete or Cut acted on files the user
could not see.

* fix(explorer): paste cut items after their folder is no longer displayed

Paste resolved the cut paths to rows on screen, so cutting a file and then
navigating the same window to the destination moved nothing and silently
emptied the clipboard. Items without a row are now looked up and moved the
same way.

* fix(explorer): show a moved item once in its destination

The tab that moves an item renders the row and also receives the move
event, so the destination showed the item twice whenever the event arrived
first. Both paths now replace any row the other already rendered.

* fix(explorer): sort names the way the dashboard does, with a stable tie-break

Folder windows and the desktop compared raw lowercase strings, so file10
came before file2 and accented names landed after z, and equal sizes, dates
or types kept whatever order they arrived in. They now use the dashboard's
comparator, so the same folder reads the same in both.

* fix(explorer): keep the Trash window's states when Trash is emptied elsewhere

Emptying Trash from another tab cleared the whole container, including its
empty, error and loading elements, and left the item count stale.

* fix(explorer): remove rows deleted elsewhere instead of hiding them

A deletion from another tab or an app only faded the row out, so it still
counted in the footer, in Select All and in keyboard actions. The row is now
removed, and windows showing the deleted folder close even when its own row
is not displayed anywhere.

* fix(explorer): refresh size and date when a file is overwritten elsewhere

An overwrite arrives as an update event, which only applied the name, icon
and path, so the size and modified columns and sorting kept old values.

* fix(explorer): download files whose names contain &, #, % or +

The path went into the download URL unencoded, so the server received a
truncated path and the download failed.

* fix(explorer): allow moving into folders whose name starts with Trash

The deleted-folder check matched any sibling of Trash sharing its prefix,
so moving into a folder such as Trash-old was refused.

* fix(explorer): end the extract operation when an archive is corrupt or has no files

A corrupt zip threw before its error could be shown, and an archive with
nothing to write or a failed upload never closed the progress window. A
progress update arriving before the window existed also threw.

* fix(explorer): follow renamed and moved folders in Back/Forward and on undo

A window's navigation history kept the old path after a folder was renamed
or moved, so Back led to a load error. Undoing a folder rename also left
windows and items inside it on the renamed path, because the undo retargeted
from the path it was restoring.

* fix(explorer): keep one progress window per copy or move

The progress timer is re-armed after every conflict dialog, and it opened a
second window when one was already showing, leaving the first on screen for
good.

* fix(explorer): show file names once-escaped in move alerts

The name was escaped before being passed to an alert that escapes its whole
message, so names with &, quotes or angle brackets showed entity text.

* fix(explorer): don't flash the empty-folder message while a folder refreshes

Clearing the rows for a refresh showed the message until the listing came
back, even for a folder full of items.

* fix(explorer): accept drops into a window that covers a desktop folder

A desktop folder hidden under a window still reacted to the drag and
disabled the window as a drop target, so the drop was ignored. A drop that
bailed out early also left every folder view disabled as a target until the
next hover; targets are now restored when the drag ends.

* fix(explorer): release each row's document click handler when the row is removed

Every file row bound a click handler on document that was never unbound, so
browsing folders grew the number of handlers run on every click and kept the
removed rows alive.

* fix(explorer): let Delete work on a file after its rename was cancelled

Cancelling a rename with Escape, or leaving the editor without a change,
left the item marked as being renamed, and the Delete shortcut skips such
items.

* fix(explorer): offer a download when no app can open a file

The prompt called a translation import that is not a function, so opening
a file with no suitable app threw and did nothing.

* fix(explorer): use an item's current path and name in its context menu

Cut, Copy, Download, Create Shortcut and the rename editor read the path and
name captured when the row was created. After a rename made from another
window or tab they acted on the old path, and closing the editor repainted
the old name.

* fix(explorer): offer Cut only where the item can be moved

The item menu on the desktop and in folder windows offered Cut on trashed
items and on shared items the user may not move, unlike the same menu built
for the dashboard.

* fix(explorer): give a folder named *.app a folder icon

The app-shortcut branch ran before the directory branch, so such a folder
was read as a file on every listing, failed, and showed the app icon.

* fix(explorer): make New > JPEG Image create an actual JPEG

The blank image was encoded with the canvas default, so the .jpg file held
transparent PNG data.

* fix(explorer): handle a drop onto a folder that is part of the dragged selection

Dragging a selection onto one of its own selected folders also tried to move
that folder into itself. On the desktop the drop also cleared the saved
position of the target folder instead of the items that left the desktop.

* fix(explorer): don't highlight a window as a drop target for its own items

The check meant to skip the folder an item is already in compared the wrong
path, so dragging inside a window outlined it although dropping there does
nothing.

* fix(explorer): keep desktop rearranging to the desktop itself

Dropping an item from a window showing the Desktop folder onto the desktop
background positioned the window's row absolutely and saved that position.

* fix(explorer): empty Trash from its window in one request

The Trash window's own Empty Trash sent one delete request per item and
reported Trash as empty before any of them finished. It now runs the same
single operation as the taskbar and desktop.

* fix(explorer): label the root and Shared in the Back/Forward menus

The long-press history menus showed an empty row for the root folder and a
lowercase path segment for Shared, and the Forward menu's Home entry was not
translated.

* fix(explorer): keep sidebar labels translated and titled after reordering

A reordered sidebar rendered the labels saved at the time of the drag, so
they stayed in the old language, and every item's tooltip was empty.

* fix(explorer): enable the Open dialog's button only for a selected file

The button stayed enabled after navigating to another folder, and a
rubber-band selection of folders alone enabled it, although clicking it then
did nothing.

* fix(explorer): show the slow-load message only for a load that is slow

Once any folder took over a second to load, the spinner text switched to
the slow-load message three seconds later even after the load finished, and
every later load in that window opened with it. The text is also translated
now.

* fix(explorer): keep the current folder visible in a long breadcrumb

A path too long for the bar was cut at its end, hiding the folder being
viewed and its nearest parents. It is now cut at the root end.

* fix(explorer): grey out the whole selected row in an unfocused details view

Only the name lost its highlight when the window lost focus, leaving a grey
pill inside a blue row.

* fix(explorer): align the details header with its rows and mark it clickable

The header ended 10px before the rows and the selection highlight, and its
sortable column titles kept the default cursor.

* fix(explorer): give the layout button a tooltip and a pointer cursor

It was the only navbar control without either, so it did not read as
clickable.

* fix(explorer): remove the stray tooltip from the loading spinner

The spinner's SVG carried an internal title that showed as a tooltip and
was read out by screen readers.

* fix(explorer): refuse uploads, copies and shortcuts into the Shared view

Dropping files on Shared in the sidebar, or Ctrl/Alt-dropping items onto a
window showing it, sent requests against a path that is not a directory and
ended in an error or a stuck progress window.

* fix(explorer): open an item's context menu where it was requested

The menu is built after permission and app lookups, and it opened wherever
the pointer had moved to by the time they finished.

* fix(explorer): close a folder's window when the folder is deleted, however it was opened

Windows opened by path, such as with Ctrl-click on a breadcrumb or sidebar
entry, never received the marker used to find a deleted folder's windows,
so they stayed open on a folder that no longer existed.
2026-11-10 11:23:30 -07:00
Nariman Jelveh 8a15f09f48 Send one request, not four, after the account pick in the sign-in popup (#4564)
* Send one request, not four, after the account pick in the sign-in popup

A sign-in popup exchanges for the opener's app token as soon as the user
picks an account. postAuthActions now hands over that result when the
opener origin and session token still match, and exchanges again otherwise.

The relationship check is skipped when an account was picked, since the
pick already decides both the second picker and consent. Signup in the
popup is not a pick and still runs it.

The /whoami read before the picker is reused only when the same user and
session token are still in place, the exchange just accepted that session,
no verification gate is pending, and the read is under a minute old.

* Test picking a different account in the sign-in popup

The popup has to read the picked account once and hand over a token for
it, not for the account it opened with. The second-account helper moves
to the shared e2e helpers so both specs that need one use the same copy.
2026-11-10 08:31:12 -07:00
Daniel Salazar 2084587885 fix(apps): list only the caller's own apps (#4562)
The `puter-apps` `select` method returned every app that was not
protected unless the caller sent `predicate: ['user-can-edit']`. It now
always scopes to the caller's own apps. The predicate is still accepted
and no longer changes the result.

Apps owned by someone else stay reachable by name or uid through `read`
and `/query/app`.

`AppStore.count` drops `visibleToUserId`, which only the unscoped
listing used.
2026-11-09 17:43:28 -07:00
Daniel Salazar 222ffcfe39 fix(dev-center): accept only a hostname for puter.domain and digits for puter.port; escape the saved app link (#4561) 2026-11-09 17:27:42 -07:00
Nariman Jelveh 7494aa1cbc Reload a tab when another tab switches to a different account (#4560)
* Reload a tab when another tab switches to a different account

Every tab shares one stored session token. A tab that sees a new token
appear in storage adopted it whoever it was issued to, so after an account
switch in one tab the others kept showing the previous account while
sending requests as the new one.

A tab now reads the user out of the stored token. A token for the account
it already shows is adopted as before. A token for a different account
reloads the tab, which comes back up as that account. A tab with no
signed-in user, or a token whose user can't be read, behaves as before.

* Store a new account's token only after its session cookie is set

A tab that sees another account's token in storage reloads and signs in
from the session cookie. update_auth_data() stored the token before it
synced the cookie, so a tab that reloaded faster than the sync came back
up as the previous account and stored that account's token again, which
the switching tab then adopted under the new account.

The token is now stored after the cookie sync, in the same task as the
stored user.

* Keep the new account's token when another tab stores one during the cookie sync

update_auth_data() sets window.auth_token, then waits for the session cookie sync. A token another tab stored during that wait was adopted over it, so the tab finished the switch holding the previous account's token and saved it under the new account in logged_in_users. The token is set again once the sync has settled.

* Create one visitor account for the account switch e2e tests

Each test signed up its own visitor, and sign-ups are limited to 10 per 15 minutes, so a few runs in a row failed in setup.
2026-11-09 16:49:50 -07:00
Nariman Jelveh 1adca8a794 Show a shared item once, with its strongest access, when it has more than one share (#4559)
* Show a shared item once, with its strongest access, when it has more than one share

The Shared listing returns one row per grant, so an item shared by two
people, or directly and through a team, appeared twice and took its
actions from whichever grant was listed last. The GUI now merges the
rows for an item and keeps the strongest mode.

* Keep a shared item under each person who shared it in the people filter

A merged row carried only the strongest grant's issuer, so filtering the
Shared view to someone whose grant was the weaker one hid an item they
shared, and their chip left it out of its count. A merged row now lists
every issuer. The filter and its counts match any of them, Everyone
counts the item once, and the Shared by tooltip names them all.

* Keep an item listed after Remove from Shared when a team still shares it

Leaving an item drops the grants made to the user directly. One a team
also holds stays shared, but the desktop took its icon away until the
next refresh and the dashboard removed the row before re-listing it. A
merged row now records that a team holds the item too. The desktop
re-lists the Shared folder so the item shows as the team share it has
become, and the dashboard leaves the row in place for its refresh.

* Show an item as shared by the person the Shared view is filtered to

An item several people shared showed the strongest grant's issuer in
the Shared by column even when the listing was filtered to one of the
others. A filtered row now shows the person filtered to, which also
keeps the Shared by sort in step with what the column displays.
2026-11-09 14:55:24 -07:00
Nariman Jelveh 07b19888a4 Match desktop items and windows by their path value, not by a selector (#4558)
* Match desktop items and windows by their path value, not by a selector

Path lookups on the desktop compare data-path values through one helper, so
a name holding &, ' or " is found like any other. Explorer windows keep the
raw path in data-path after navigating, the same as when they open.

* Read data-path straight from the element in path lookups

atPath() and underPath() built two jQuery objects for every element they
looked at. On a desktop with 5,000 items a lookup took about 1.4 ms,
against 0.08 ms for the selector it replaced. Reading the attribute from
the element brings it to about 0.3 ms.

* Match no element when a path lookup has no path

atPath() with a missing path matched every element whose attribute is
empty, which is every item that is not a shortcut and every app window.
An item.moved event without old_path would point all of those items at
the moved file. underPath() with an empty path matched every path.

* Use atPath() to find the items a share badge belongs to

mark_item_shared() had its own copy of the same lookup.

* Keep the raw folder name in an explorer window's data-name

update_window_path() and refresh_item_container() wrote the HTML-encoded
name there, so after navigating into "R&D" the tab title and the publish
dialog showed "R&amp;D". A newly opened window already held the raw name.
2026-11-09 14:24:52 -07:00
Nariman Jelveh 2394221745 Answer requestEmailConfirmation() once, and show it in a frame on first-party pages (#4551)
* Answer requestEmailConfirmation() once, and show it in a frame on first-party pages

puter.ui.requestEmailConfirmation() in an app opened a second code dialog
after the first: a confirmed user got a dialog they couldn't complete and
two answers, and an unconfirmed one entered the code and then got a second
dialog, whose result was the only answer. The desktop handler now runs one
walk-through and answers once with its result.

That walk-through is ensureConfirmedEmail: save a temporary account, then
ask an unconfirmed email for its code, each window at most once. Publishing
a website or worker uses it too, replacing two copies of the same steps.
The code window now resolves false when it closes without a confirmation,
so dismissing it answers the app instead of leaving it waiting, and it
marks window.user confirmed before resolving, so a caller that checks next
doesn't ask again before the refresh lands. A logout from its footer still
leaves it unsettled, so the boot gates don't reopen it. In the dashboard
the windows open above the app's window, which stays on top and covered
them.

On a signed-in page one label under the Puter origin, the call now frames
/embed/request-email-confirmation over the page, served like the upgrade
frame, and resolves { response }, the field an app reads from the
desktop's answer. The GUI shows it only for the framing page's own user
with no phone, card or password check waiting. It skips the boot's
non-closable email gate for this action, so the user gets one code window
they can close or Escape. An email already confirmed resolves true without
showing the frame. A frame that can't show it resolves { response: false }.

* Skip the email confirmation frame when the page knows the email is confirmed

A confirmed email never goes back to unconfirmed, so requestEmailConfirmation()
on a first-party page resolves { response: true } from the page's whoami
instead of booting the GUI in a frame behind a loading scrim.

* Close the framed email confirmation on Escape in the save-account window

A temporary account sees the save-account window first, where Escape did
nothing, while it closed the code window that follows.

* Let the email code window recover from a failed code check with no response body

A network failure has no JSON body, so reading its error threw, leaving the
window spinning with its inputs disabled. It now shows an unknown-error message
and lets the user try again.

* Answer an email confirmation asked for while one is showing with the windows already open

A second walk-through opened a second code window over the first, and for a
temporary account it never answered, since the save-account window opens once.

* Read the email code from the code window it was typed in

A second code window read the inputs of the first one on the page, so typing
in it never filled in the code or enabled its button.

* Keep the email code window's answer in step with a code check it was closed during

Closing the window while a code was being checked answered false, and the
check went on to confirm the email. A code not sent yet is no longer sent, and
the window waits for one already sent before it closes.

* Show why a new email code couldn't be sent

A failed re-send, such as one past the hourly limit or a network failure,
showed nothing, so the link seemed to do nothing.

* Skip the email confirmation frame on calls after the user confirmed in one

The page's cached whoami kept reading the email as unconfirmed, so each later
call framed the GUI again and flashed its loading scrim before resolving true.

* Leave the email code window unsettled when any logout closes it

Only a logout from its footer did. One from elsewhere, such as after a 401,
answered false, so the boot's email gate opened a new code window while the
page was navigating away.

* Hide the save-account window while its email code window shows

A save-account window with a backdrop stayed under the code window's own, so
the page behind was dimmed twice, and on a phone the window showed around the
code window's edge.

* Answer a save-account request made while the save-account window is open

The window opens once, so the second request got no window and never
answered, which left an email confirmation that asked for it waiting too.

* Answer a framed email confirmation closed with Escape with the code check it was closed during

Escape in the framed code or save-account window closes that window, and the window's answer closes the frame. A code already sent is waited for, as it is when the window's close button is used. Before, Escape closed the frame and answered false while the check went on to confirm the email.
2026-11-09 13:48:10 -07:00
Filip Kujundžić ee2cdbfe1a Merge pull request #4552 from HeyPuter/feat/claude-fable-5-2
Add Claude Fable 5.2 with published pricing and fast mode
2026-11-09 20:50:25 +01:00
404oops 9b6350beab Remove redundant Fable model documentation 2026-11-09 20:36:58 +01:00
404oops b649d9ada7 Apply published Fable 5.2 pricing and fast mode rates 2026-11-09 20:03:16 +01:00
404oops 50b0639d02 Add Claude Fable 5.2 with provisional Fable 5.1 pricing 2026-11-09 20:02:49 +01:00
Filip Kujundžić ab96702718 Merge pull request #4546 from HeyPuter/feat/chat-service-speed
Add service speed selection and fallbacks to AI chat
2026-11-09 20:01:58 +01:00
404oops 47f9b0bdf3 Use the common service speed rate shape for Claude 2026-11-09 19:54:54 +01:00
404oops 8c4b0eb1fc Keep chat service speed rates in provider model catalogs 2026-11-09 19:31:25 +01:00
404oops a88c1b9d65 Fall back to standard Claude speed on fast capacity overload 2026-11-09 19:04:31 +01:00
Daniel Salazar 9caaf7162c fix(fs): follow S3 region redirects (#4544)
A file row without a stored region is read with the server's configured
region. When its bucket lives elsewhere, S3 answers 301 PermanentRedirect
and the read failed with a 500. The SDK now retries once in the region the
redirect names.
2026-11-09 10:31:30 -07:00
404oops 0191f2bfec Update chat.md 2026-11-09 16:11:51 +01:00
404oops 7aadc48cca Add service speed selection and billing to AI chat 2026-11-09 15:59:08 +01:00
Daniel Salazar 6b06793750 fix(gui): send picker results only to the popup opener's origin (#4543)
File, directory and save pickers opened in a popup now post their results,
cancellations and the save-data request to window.openerOrigin instead of
'*', matching the token hand-off. A test checks that opener messages in the
GUI only target '*' when the opener's origin is not yet known.
2026-11-08 23:11:57 -07:00
Neal Shah e441880f13 add more data to user audit events (#4542) 2026-11-08 19:22:09 -05:00
Nariman Jelveh 9a86803418 Show the upgrade in a frame on first-party pages (#4541)
* Show the upgrade in a frame on first-party pages

puter.ui.requestUpgrade() on a signed-in page one label under the Puter
origin now frames /embed/upgrade over the page and resolves { upgraded }
once it closes. The usage limit dialog's Upgrade button does the same on
those pages instead of opening the dashboard in a new tab. Apps, the
desktop and every other page keep their current behavior.

/embed/upgrade is served like the sign-in and picker frames: the GUI
shell with the same framing rules, query and exact-path redirects and
no-store. The GUI shows the deployment's upgrade dialog
(window.UIUpgradeAccount) only for the framing page's own user, with
nothing left to verify, and only when the dialog says it reports its
close (UIUpgradeAccount.embeddable). Otherwise it reports unavailable and
the page opens the dashboard upgrade in a tab, through a consent dialog
when the click has expired. The app it credits is resolved from the
framing page's origin, never read from the fragment.

The frame covers the page with a transparent GUI page so the dialog's own
scrim shows, allows payment, and leaves Escape to the dialog. A call made
while it shows settles with it. If every dialog and window in the frame
goes without a close being reported, the frame closes itself rather than
staying over the page.

* Open the framed upgrade only once the frame has a viewport

The page keeps a loading frame hidden, which Chromium and WebKit lay out at
0x0. The team-seat alert, a GUI window that centers itself when it opens,
landed at (-175, 0) with its message and OK button cut off. A hidden frame
now tells the page it's ready first, and opens the dialog on the resize that
follows, or after a second if none comes.

* Document when the framed upgrade posts ready

* Retry a framed popup's focus() that the frame ignored

Firefox and WebKit ignore focus() inside a frame for a moment after the
page shows it, and Firefox sends no focus event afterwards, so the framed
upgrade dialog and its team-seat alert opened with nothing focused there:
Enter didn't press OK and screen readers didn't land in the dialog. A
focus() that didn't take is now retried briefly, until the user presses a
key or the pointer.

* Keep the framed upgrade's GUI in the light color scheme

The transparent upgrade frame put `color-scheme: light dark` on body as
well as the root, so in dark mode form fields the GUI leaves at browser
defaults turned dark. The email confirmation code digits showed slate
text on a dark grey field inside a white window. Only the root needs to
match the frame's scheme to stay transparent; body now keeps the light
scheme the GUI uses everywhere else.

* Fall back to the upgrade tab when the framed dialog fails to open

If the deployment's upgrade dialog threw while opening, the frame reported
a close, so requestUpgrade() resolved { upgraded: false } and the user's
click did nothing. It now reports itself unavailable, and the page opens
the dashboard's upgrade page as it does for any frame that can't show it.

* Say which plan changes count as upgraded in UpgradeResult

The upgrade dialog sets `upgraded` only for a subscribe or an upgrade;
a downgrade, cancellation or resume closes with false. The type said any
plan change counted.

* Stop the page scrolling behind a framed GUI embed

Firefox and WebKit pass a wheel or touch scroll over a frame on to the
page behind it, whatever the dialog's overscroll-behavior, so scrolling
over the framed upgrade, sign-in or a picker scrolled the page under the
scrim. The page's root now stops scrolling while an embed shows, taking
a classic scrollbar's width as padding so its content doesn't shift, and
gets its own styles back once the last embed closes.

* Skip the usage limit dialog while the framed upgrade shows

A refused call while the upgrade shows in a frame over a first-party
page opened the usage limit dialog on top of it, which made the upgrade
dialog inert until the user closed it. The refusal still rejects.

* Restore the page's root styles after an embed the page removed

An embed dialog the page removed itself never unlocked the page scroll,
and the next embed read the locked styles as the page's own, so the
page stayed unscrollable once it closed. The page's styles now go back
before the next lock reads them.

* Open the upgrade tab when the page can no longer frame it

The usage limit dialog decided to frame the upgrade when it opened, so
an Upgrade click after the page signed out did nothing. onUpgrade now
returns false when the page can't frame it, and the dialog opens the
dashboard tab as it does without onUpgrade.

* Keep the upgrade showing until its tab consent is answered

When the framed upgrade fell back to a consent dialog, requestUpgrade
settled as soon as the dialog showed. A refusal meanwhile opened a usage
limit dialog over it, and a second call asked again. The upgrade now
counts as showing until the user answers, so both join it.

* Say where requestUpgrade never settles

Its JSDoc named only apps, though on any website that can't frame the
upgrade the promise doesn't settle either.

* Treat a GUI embed the page removes as dismissed

A page that re-renders its body took the embed's dialog with it, and the
embed's promise never settled. For the upgrade that left it counted as
showing for good: later requestUpgrade() calls joined the dead one, no
refused call opened the usage limit dialog again, and the page stayed
unscrollable.

* Let the framed upgrade credit the remembered prompt when it knows none

When the framing page's origin resolved to no app and the call named no
reason or method, the frame handed the dialog an empty attribution. The
dialog then remembered that as the latest prompt, erasing another app's
credit, and sent the purchase with no attribution at all. It now gets
null, as from every other entry point.

* Pad the page by the width its scrollbar gives back behind an embed

A page with scrollbar-gutter: stable keeps its gutter once the root stops
scrolling, so padding it by the scrollbar's width as well shifted its
content left while any GUI embed showed. The lock now measures how much
width the root actually gets back.

* Keep the page's scroll position behind an embed when its body scrolls it

A page whose body carries the viewport's overflow (html and body at 100%
height, body with overflow-x hidden) jumped to the top while an embed
showed, and stayed there after: hiding the root's overflow made the body
a scroller of its own. The lock now hides the overflow of whichever
element the viewport uses, and restores a single-axis inline overflow.
2026-11-08 14:27:41 -07:00
Nariman Jelveh 09c6ce6f46 Dashboard: fix 30 bugs, UX, a11y and perf issues from an adversarial review (#4540)
* fix(dashboard): middle-truncate long names in the default Files list view

In the list view's default auto-width name column, a long name was cut at
the end by CSS with no tooltip, so names that differ only near the end
("report … (1).txt", "report ….txt") looked identical and the extension
was hidden. The name is now cut in the middle to the room its cell has,
like a resized column and grid tiles already are, and the full name shows
on hover. The phone layout's two-row rows get the same treatment.

* fix(dashboard): toast the newest notifications of a catch-up burst

A burst of more than four notifications toasts three and folds the rest
into an "N new notifications" summary. The split kept the first three it
was given, assuming newest first, but the reconnect catch-up and the
events-feed replay hand notifications over oldest first, so after a tab
woke up the toasts showed the oldest three and hid the newest. The split
now sorts the burst itself.

* fix(dashboard): act on a regrouped notification's current content when its toast is clicked

When more shares from the same person fold into a notification that's
already toasted, the toast's text updates ("alice shared 3 items") but
its click still acted on the notification as first shown, so it selected
only the first file instead of opening Shared. The click now looks up the
notification's current content.

* fix(dashboard): show browsers on Puter's own Web Push as browsers in Your devices

A device registered through Puter's own Web Push client reports platform
"webpush", which the Notifications tab didn't know: it got the phone icon
and no "Web" label. It's now treated like the other browser platform.

* fix(dashboard): clear the push preference's load error once it loads

If the Puter notifications preference couldn't be read, its card's hint
was replaced with a load error. Coming back to the tab once the read
worked re-enabled the switch but left the error text in place. A
successful read now puts the hint back.

* fix(dashboard): keep push off for this browser when removing it half-fails

Removing "This browser" from Your devices turns its push off and then
deletes the server record. If the delete failed (a dropped connection),
the handler returned before saving the opt-out, so the card still read
"on" and the next dashboard load quietly turned push back on. The opt-out
is now saved as soon as push is off, and the card is redrawn on failure.

* fix(dashboard): don't let an older device or app listing redraw a removed row

The Notifications tab lists devices and apps each time it opens. If one
of those listings was still in flight when the user removed a device or
turned an app off, it landed afterwards and drew the removed row again.
Only the newest listing draws now, and a removal outdates any listing
already in flight, as the browser card already did.

* fix(dashboard): report the items that were shared when a large share fails partway

Sharing more than 50 items sends one request per 50. If a later request
failed (the daily share limit, say), the items earlier requests had
already shared were forgotten: the dialog showed a flat failure and none
of their rows got the shared badge until a reload. The dialog now says
"Shared with bob on 50 of 60 items" along with the error, badges those
rows, and refreshes the shared listing.

* fix(dashboard): drop the site address from files inside a disassociated folder

Disassociating a folder's website from its Properties cleared the
folder's own badge, but the files inside it kept their website-address
badge and URL, which now led to a site that no longer exists. Their
addresses are now worked out again without that site, so a file still
served by a site on a folder within keeps its address.

* fix(dashboard): keep an app's own "(N) " title prefix beside the unread badge

The dashboard puts the unread count in front of the page title and keeps
it there as app windows rewrite the title. It removed any leading
"(N) " before adding its own, so an app titled "(3) Inbox" lost its
count ("(1) Inbox"). Only the badge the dashboard itself put there is
replaced now ("(1) (3) Inbox").

* perf(dashboard): redraw the notification list once per burst of acks from other tabs

"Mark all read" in one tab sends the other open dashboards one ack per
notification, and each ack rebuilt the whole list. With 150 unread that
was about half a second of main-thread work in every other tab (more on
slower devices). Acks and removals from other tabs now redraw once per
50ms beat: 150 acks take about 5ms.

* fix(dashboard): let the keyboard reach "Also delete data" in the Uninstall dialog

The Apps tab's dialogs keep Tab inside the card, but the trap only
cycled buttons and text areas, so Tab and Shift+Tab bounced between
Cancel and Uninstall and the delete-data checkbox couldn't be reached
without a mouse. Inputs, selects and links are part of the cycle now.

* fix(dashboard): don't leave the app request form on an IME composition's Escape

In the "Request an app" form, Escape steps back to the options. While
typing with an input method (Chinese, Japanese, Korean), Escape is how
the composition is cancelled, and that Escape also left the form. It's
now ignored while composing, as the Apps grid and folder name already do.

* fix(dashboard): keep focus out of an Apps folder while it closes

A folder's card stays on screen for its 240ms close animation. During
that time its tiles could still take focus: an arrow key pressed right
after Escape moved into the closing card, and focus then fell to the
page when the card was removed, losing the user's place. The closing
card is now inert and the arrow keys skip it.

* fix(dashboard): save the Apps layout one write at a time

The app order and folders were saved with a write per change, without
waiting for the one before. Changes close together (ejecting an app from
a folder saves, and the drop right after saves again) put two writes of
the same key in flight, and if they landed out of order the older layout
was what the next load showed. Each key now has one write in flight at a
time, and the next carries only the newest layout.

* fix(dashboard): close an open dialog when browser Back switches tabs

Back and Forward between dashboard tabs closed the drawer, menus, Share
and Properties, but not the dashboard's dialogs (Edit Profile, Change
password, confirmations) or the photo crop. The tab changed underneath a
dialog that stayed up with focus inside it. They now close through their
own close buttons, like the rest.

* fix(dashboard): count the trial countdown in calendar days

The Home tab's trial badge rounded the time left up to whole 24-hour
blocks, so it disagreed with the date shown under it: a trial ending at
3pm today read "1 day left" beside today's date and never "Ends today",
and one ending tomorrow morning read "2 days left". It now counts
calendar days in the user's time zone.

* perf(gui): rewrite paths after a username change only on elements that carry one

Changing the username from the dashboard's Account tab rewrote paths on
every element in the document (the selector matched them all) and set
every username label once per element, which grows with the size of the
Files listing on screen. It now visits only elements with a path
attribute and sets the labels once. With no earlier username (signing
in) there's nothing to rewrite, which also stops it throwing then.

* fix(dashboard): make long resource names in the Usage table readable

Resource names in Usage details are cut off with an ellipsis, and on a
phone the resource column is the one that shrinks, so a key like
"openai:gpt-4o-mini-2024-07-18:prompt_tokens" read "openai:gpt-4o-mi…"
with no way to see the rest. The full name now shows on hover, and on
phones, which have no hover, the name wraps instead of being cut.

* fix(dashboard): show Usage units in the dashboard's language

In Usage details the Cost column followed the dashboard's language but
the Units column beside it always used English separators, so a German
row read "1,234,567 | 1,23 $", where the units look like 1.2. Units now
use the language's separators too ("1.234.567").

* fix(gui): translate the 2FA setup wizard's step labels and messages

The two-factor setup opened from the dashboard's Security tab had
English hardcoded in its progress steps (Scan, Backup, Verify, Done),
the "Enabling…" spinner, the success message and its Done button, the
copy-secret button's label, the "Copied!" confirmation and the printed
recovery codes' heading. They go through i18n now.

* fix(dashboard): leave Alt and Cmd arrow shortcuts to the browser in Files

Files took every arrow, Home/End and Page key to move the selection,
whatever modifier was held, so Alt+Left (Back) and Cmd+Up/Down moved the
selection instead of doing what the browser does with them. Arrow keys
with Alt or Cmd are left alone now.

* fix(dashboard): explain in the user's language why a Trash item can't be restored

An item moved into the Trash by an app or the API has no record of where
it came from. Choosing Restore on it showed "Cannot restore: original
path not found in metadata", in English and in internal terms. The
message now says which item it is and why, through i18n.

* perf(dashboard): delete Trash items permanently a few at a time

"Delete permanently" on a Trash selection deleted one item after another,
a round trip each: 60 items took about 8s at 100ms of latency, and a few
hundred took most of a minute. Six run at once now (60 items: about
1.3s). The bounded runner the notification center used for "Mark all
read" moves to a shared helper for both.

* fix(dashboard): don't leave a "folder is empty" notice over the next folder's rows

Opening a folder clears the pane while its listing loads. If something
finished in that time and found the pane empty (a Trash restore, a
failed new folder), it added the "This folder is empty" notice, and the
listing's rows were then drawn under it. The listing now clears a stale
notice before drawing its rows.

* fix(dashboard): restore create_file when two "New" creates overlap in Files

Each "New > Text Document" (or HTML, Web Link…) in Files swaps in its own
window.create_file while it runs and put back whatever it found when it
finished. When two overlapped and the first finished first, the second
put back the first's stand-in for good. Any later create that reached it
counted a create that never ended, and from then on files added by apps
or other tabs stopped showing in the listing until a reload. The stand-ins
are now tracked together, and the real function comes back once none is
left.

* fix(dashboard): don't let a slow "New" file pull the user back or land in another listing

After "New > Text Document" (or HTML, Web Link…) in Files, the new file's
row is drawn once its upload finishes. If the user opened another folder
meanwhile, then:
- if that folder was still loading, the row (with its rename box) was
  drawn into the loading pane and the spinner removed, and the folder
  then lost its "empty" notice;
- if it had loaded, the user was taken back to the folder the file was
  made in.
The row is now drawn only if the folder is still on screen, and the user
is only taken to the folder whose menu made it if they haven't moved.

* fix(dashboard): keep an uninstalled app off the Apps grid until its uninstall lands

Uninstalling an app takes its tile away at once, but the server keeps
listing the app as installed until the revoke request finishes. A grid
refresh in that time (switching tabs, coming back to the browser tab)
put the tile back, and it stayed until the next refresh; clicking it
reinstalled the app. Refreshes now leave the app out until the revoke
settles, and ones started before it landed are discarded.

* fix(dashboard): keep keyboard focus when uninstalling an app from inside a folder

After uninstalling an app from the Apps grid, focus goes to the tile that
took its place. An app uninstalled from inside an open folder had no
place on the grid, so focus fell to the page, and a keyboard user had to
start over from the top. Focus now goes to the folder's next app, to the
folder itself, or, when only one app was left and the folder dissolved,
to that app.

* fix(gui): show sizes under 1 KB as whole bytes

The size formatter wrote a size under 1 KB with two decimals and a
mismatched unit: a new account's storage on the dashboard read "0 Byte
Used", and a small file "149.00 Bytes". Bytes are now whole, with the
unit in the right number: "0 Bytes", "1 Byte", "149 Bytes".

* fix(dashboard): show the bottom edge of the Files drop outline in list view

Dragging files over the Files listing outlines it with a dashed border,
but in list view the bottom edge was missing: the listing cleared the
footer with padding, so its box ran under the footer and the footer hid
the outline's bottom edge. It now clears the footer with a margin, as
the grid view already did, so the outline shows all the way round.
2026-11-08 09:55:22 -07:00
Nariman Jelveh 0fdf40b8da Fill the send-feedback popup with the feedback dialog; fix <puter-user-menu> arrow focus (#4539)
* Fill the send-feedback popup with the feedback dialog

The popup opened by puter.ui.showFeedbackDialog() drew the floating modal
over a scrim. It now fills the window like the custom domain popup, with
the actions pinned to the bottom and the message box taking the spare
height. The full-page styles move from .custom-domain-fullpage to a shared
.app-feedback-fullpage on the modal shell.

* Land the first ArrowDown on the first <puter-user-menu> item after a click

Opening the menu with the pointer focused the first item without a visible
focus ring, so ArrowDown appeared to skip it. A pointer open now focuses the
menu itself; opening from the keyboard still focuses the first item.
2026-11-07 21:43:21 -07:00
Nariman Jelveh 5b850113ff Show sign-in and file pickers in a frame on first-party pages (#4537)
* Show sign-in and file pickers in a frame on first-party pages

puter.auth.signIn(), showOpenFilePicker(), showSaveFilePicker() and
showDirectoryPicker() on a page one label under the Puter origin now
show the GUI popup in a frame over the page instead of a window. Every
other page, and any frame that can't serve the request, keeps the popup
exactly as before, so apps need no changes.

/embed/sign-in and /embed/show-{open-file,save-file,directory}-picker
render the normal GUI shell with the framing rules, query redirect and
no-store of /embed/apps, and name the framing page (read from the
referrer, pinned with frame-ancestors) as embed_host_origin. The GUI
runs the popup boot unchanged with that page as window.opener; close()
asks it to remove the frame. Popup parameters come from the fragment
(msg_id, options, request_auth, and user for a picker).

Sign-in has a close button that rejects with auth_window_closed, as
closing the popup does. A federated provider can't be framed, so
choosing one continues in the popup. attempt_temp_user_creation and
cross-origin isolated pages keep the popup.

Pickers frame only for a signed-in page whose user owns the GUI
session; otherwise the GUI reports unavailable and the page opens the
popup, through a consent dialog if the click has expired. The page
keeps its own token rather than adopting the one sent with the answer.

The feedback embed and the new frames share one loading/ready state
machine in guiEmbed.js.

* Close a framed picker when Escape cancels it

Escape closes only the picker window inside the frame, so the frame now
closes with it. The mismatched-user e2e test waits for sign-in's whoami
before naming another user, which it could otherwise overwrite.

* Close a framed sign-in on Escape

The sign-in shows as a page in the frame, which ignored Escape. Escape
now asks the framing page to close it, as its close button does, unless
a request is in flight.

* Focus a framed sign-in once the page focuses the frame

A cross-origin frame's focus() calls do nothing until the framing page
focuses it, so the sign-in opened with focus on the body: keys missed
the form and Escape never reached the dialog. The screen now takes
focus when the frame gains it, unless something already has it.

* Skip the frame on subdomains the server refuses to let frame

The SDK framed embeds from any page one label under the GUI origin, but
the server refuses its own subdomains (api, docs, apps, ...). On those,
sign-in and the pickers waited on a refused frame before opening the
popup, which Safari could then block for want of a recent click. They
open the popup straight away now, and the user menu hides Apps there,
as its docs say.

* Keep a framed picker on the framing page's user

With several saved accounts, a framed picker could still show the
account picker (no grant yet, or request_auth in its fragment). Picking
another account switched the session inside the frame, and the picker
then ran with the first user's details and the second user's token,
saving that token under the first account. A framed picker already
holds the framing page's user, so it no longer offers to switch, and
its user check no longer writes the boot's shared whoami.

* Take a save picker's file only from the page that asked

The save picker opened a dialog for every showSaveFilePickerPopup
message from any window. In a frame, a sibling frame of the framing
page can reach it, so it could supply the bytes the user then saved,
or stack extra dialogs. The picker now takes the file once, and only
from its opener.

* Reopen a framed embed that reloads itself into a refused frame

A reload or navigation the embed starts itself names the embed as its
referrer, so the server refuses the framing: logging out at an account
gate, a sign-out in another tab, or a reset session left a blank box.
The page now shows its spinner and opens the embed again itself, once
per ready, and falls back as for a refused frame if that fails too.

* Correct why a temporary-account sign-in keeps the popup

notes.puter.com and puter.com are the same site, so browsers don't
partition the frame's storage. The popup is kept because only it
creates a temporary account.

* Remove the picker's consent dialog once answered

The consent dialog a picker shows when its click has expired was
closed but left in the page after Continue or Cancel, one element per
fallback. It is removed now, as the other consent dialogs are.

* Name the embed dialog for assistive tech

The modal dialog around a framed embed had no accessible name, so
screen readers announced an unnamed dialog. It is labelled with the
frame's title.

* Expose an embed's loading status only while it shows

The spinner is faded out rather than removed, so assistive tech still
read a Loading status over a frame that was ready. The status is
hidden from it whenever the spinner isn't showing.

* Let a popup frame fill in texted codes

Signup and the account checks fill a texted code in through WebOTP,
which a cross-origin frame may only use when allowed. Popup frames now
allow otp-credentials, so the code fills in as it does in the popup.

* Close a popup frame on Escape from the page too

Once a popup frame was ready, Escape with focus on the page (after a
click on the scrim) only moved focus back into the frame, so it took a
second Escape to close, and none if the frame stopped responding. It
now closes the frame, as Escape inside it does. The feedback embed
still leaves dismissal to the embed.

* Keep scrolling over an embed's scrim from scrolling the page

A wheel or swipe over the scrim around a framed embed chained to the
page behind the modal. The dialog now contains its overscroll.

* Frame a GUI popup only at its exact path

Routes match case-insensitively and with a trailing slash, so another
spelling of /embed/<action> was served frameable while the shell booted
the desktop for it. Any other spelling now redirects to the exact path.

* Prefill a web save picker with the suggested name

The popup and framed save pickers ignored suggestedName and opened with
an empty filename, unlike the save picker an app gets in the desktop.

* Open a provider picked in a framed sign-in straight in the popup

Picking a provider in the framed sign-in fell back to the sign-in popup,
where the user had to pick the provider again. The frame now hands the
page the provider's start URL for its sign-in, and the page opens the
popup there after checking it is the GUI's OIDC start for that sign-in.

* Open the popup straight away for a page framed by another site

frame-ancestors on the embeds allows only the GUI and the framing page,
so a first-party page inside another site's frame waited about a second
on a refused frame before sign-in or a picker opened the popup, by which
time Safari asks for another click. Such a page opens the popup straight
away now, as it did before the frame.

* Close a framed sign-in on Escape at its account checks

Escape closed the framed sign-in on its auth screens but did nothing once
signup moved on to confirming the email, phone or card, which show as
windows. Escape there now closes the frame as well, as its close button
does.

* Leave Escape that cancels an IME conversion to the IME in sign-in

In a framed sign-in, Escape pressed to cancel an IME conversion in a
field also closed the sign-in, losing what was typed. The auth screens
and the account checks now leave an Escape mid-composition to the IME,
as the dashboard's text fields do.

* Fade in a popup frame's scrim and box

The scrim behind a framed sign-in or picker, and the box's white
background, appeared at full opacity in one frame while the GUI's content
faded in over them. Both now fade in briefly, unless the user prefers
reduced motion.

* Keep a page's own styles off a popup frame's dialog, frame and close button

The dialog, its frame and the close button live in the page's document, so
a page's global dialog, iframe and button rules reached them: a transform
that centers the page's own dialogs moved the overlay half off screen, an
iframe max-width shrank the frame inside its box, and button margins and
min sizes turned the close button into a pill. The dialog and frame now
reset those properties inline, and the close button starts from all:unset.

* Fall back to the popup when a reopened embed frame never loads

After a refused self-reload the page opens the embed again, but nothing
timed that second start: a stalled request left the loading spinner up
until the user dismissed it, which settled the request as closed instead
of opening the popup. The reopened frame now gets the same ready timeout
as the first start.

* Hand a save picker frame its file again after it reloads

The page answered a picker's sendMeFileData once and then stopped
listening. A framed save picker that reloads asks again, and without an
answer it never opened its dialog, so the page waited out the ready
timeout and fell back to the popup. A frame is now answered until it
closes; a popup is still answered once.

* Keep a popup frame's white backing off its rounded edge in dark mode

The box's white background shared the frame's anti-aliased corner, so a
light arc showed around the dark sign-in. The backing now stops 1px inside
the edge, which leaves the curve to the frame and the scrim.

* Center a popup frame's box with margins so it fills a phone edge to edge

On a phone with a fractional pixel ratio the translate that centered the
full-screen box left it a fraction of a pixel short of the top, so a line
of scrim showed above the sign-in. Margins snap to device pixels.

* Focus a framed save picker's file name as the popup does

A cross-origin frame's focus() does nothing until the page focuses it, and
the page focusing it again resets it, so the framed save picker opened with
nothing focused and typing went nowhere. A framed popup now gets its latest
focus() back whenever the frame gains focus with nothing focused, until the
user presses a key or the pointer in it.

* Replace a showing popup frame instead of stacking a second one

A double click on a page's picker button framed two GUIs, one over the
other under two scrims, and the user had to cancel twice. A popup reuses
its named window instead. Now a newer popup frame dismisses the one
showing, which settles it as closed.

* Share one framed sign-in between calls made while it's open

A double click on a page's sign-in button started a second framed
sign-in, which replaced the first and rejected it as closed while the
user was still signing in. A call made while a framed sign-in with the
same request_auth is open now settles with it.

* Close only a context menu on Escape over a file dialog

Escape to dismiss a right-click menu in a file dialog also closed the
dialog, which cancels a picker and, in a framed picker, removes the whole
frame. An open context menu now takes the Escape on its own.

* Document that one popup frame shows at a time

* Keep a save dialog's file name and buttons on a phone's screen

The save dialog's bottom bar couldn't shrink below the file name's own
width, so on a phone it spilled off both edges: the name's start and
the Save button were cut off. A framed save picker fills the phone, so it
always hit this. The name now shrinks to fit.

* Keep a file dialog's buttons on one line on a small phone

On a 320px-wide screen the open picker's Open button wrapped under
Cancel and ran into the screen's edge, and Upload wrapped under its
icon. The buttons now stay on one line, with less side padding up to
480px wide so the save dialog's file name keeps room to show.

* Say what a picker is for when its popup needs a click to open

When a framed picker falls back to the popup after the click expired,
the consent dialog said the page used Puter for AI and Cloud features,
not that it wanted a file or folder. It now names the picker, as the
push notification dialog does.

* Share a framed sign-in with a call that differs in request_auth

Implicit auth asks with request_auth, so an explicit signIn() made while
it was open replaced its frame and rejected every puter.* call waiting
on it. Any framed sign-in in progress is now joined.

* Keep a popup frame open when a frame for another popup shows

A sign-in replaced a showing picker frame, cancelling the picker, and
the other way round, though their popups have different window names and
stay open together. Only a frame for the same popup is replaced now.

* Reopen a refused embed frame in WebKit

WebKit took the refused URL as a fragment navigation of its error page
and loaded nothing, so a frame that reloaded itself fell back to the
popup. The frame is reopened through the server's query redirect, which
keeps the fragment.

* Go back to the save picker on Escape at its replace prompt

Escape closed the alert without an answer, so the save waited on it
forever behind the picker's busy mask. In a frame nothing could close
the picker after that. The alert closing now counts as Cancel.

* Leave Safari's IME-ending Escape alone at a framed sign-in's account checks

Safari sends the Escape that ends an IME conversion with keyCode 229 and
isComposing false, so it closed the framed sign-in. The auth screens
already check for it.

* Keep an open dialog's buttons whole on a small phone in German

At 320px, German's longer labels pushed the Open button past the screen
edge, since the upload label couldn't shrink and the buttons could. The
upload label now gives way, cut off with an ellipsis.
2026-11-07 20:56:19 -07:00
Nariman Jelveh 51bf8697a8 Drop the alert after a provider signup lands on an existing account (#4538)
Signing up with a provider whose account already exists signs the user
in to it, then showed a blocking "You have been logged in to an existing
account" alert. In a sign-in popup it held back the token until the user
clicked OK, right before the popup closed. The sign-in now completes
without it, and the callback no longer adds oidc_switched to the return
URL.
2026-11-07 17:59:54 -07:00
Nariman Jelveh 8c14e7de30 Add account links and Send feedback to <puter-user-menu> (#4536)
The signed-in menu now shows the user's picture, username and email
(hidden when whoami leaves the email out), links to Manage account,
Usage and Open Puter on the GUI origin in a new tab, and Send feedback,
which calls puter.ui.showFeedbackDialog(). Each new item takes a label
attribute like the existing ones. The menu opens on its first item, and
the arrow, Home and End keys move between items.
2026-11-07 11:40:42 -07:00
Filip Kujundžić 84faf5c40c refactor(ai): rename convo API to realtime (#4524) 2026-11-07 10:55:35 -07:00
Rasad Regmi aba2666f26 fix(gui): improve dark mode input visibility (#4450) 2026-11-07 09:32:33 -07:00
tgarver-gdm abe6882de9 Import AGENTS.md from CLAUDE.md so Claude Code loads it (#4529) 2026-11-07 09:21:28 -07:00
jelveh 770af49528 Show a loading scrim while the feedback embed checks the session
The framed feedback dialog stayed hidden until the embed had checked the
GUI session, so on a slow network a click on Send feedback showed
nothing for seconds, and a second click silently resolved false. A
check that takes longer than 200ms now shows a scrim with a spinner over
the page, matching the embed's own scrim, which takes its place once
the dialog is ready. Escape or a click on it cancels, and a refused
session still falls back to the popup.
2026-11-07 02:12:59 -07:00
jelveh 47b4cc1158 Follow the OS theme in the feedback embed on Safari
WebKit gives a frame the color-scheme of its iframe element as its
preferred scheme, and the feedback embed's frame was set to normal, so
Safari in dark mode showed the light dialog. The frame and the embed's
root now both declare light dark: the embed follows the OS in every
engine, and the frame stays transparent because the two match.
2026-11-07 02:12:06 -07:00
Nariman Jelveh e253a7f862 Show the app feedback dialog in a frame on first-party pages (#4534)
* Show the app feedback dialog in a frame on first-party pages

puter.ui.showFeedbackDialog() on a page one label under the Puter origin
now frames /embed/feedback in a modal over the page, instead of opening a
puter.com popup. The embed uses the same framing rules, query redirect,
and host-user binding as /embed/apps, and sends the feedback for the
framing page's origin, which the server reads from the referrer and pins
with frame-ancestors. Without the named user's Puter session, or with an
email still to confirm, the embed reports itself unavailable and the SDK
falls back to the popup, which can sign in. A frame that never answers
(such as one the host's CSP blocks) falls back too.

The embed session check moves out of appsEmbed.js into a shared helper,
and the first-party page check out of <puter-user-menu> into puter.js's
lib, so both embeds use one copy of each.

* Keep the framing page from scrolling behind the feedback embed

A wheel or touch scroll over the feedback embed's scrim chained out of
the frame and scrolled the first-party page underneath the open dialog.
The embed's root now stops overscroll from leaving the frame.

* Name the feedback embed's user from the cached whoami

showFeedbackDialog() on a first-party page fetched /whoami before it
started loading the embed, adding a round trip to every call. It now
uses the user puter.js already cached for the session and asks the API
only when there is none.
2026-11-07 01:57:47 -07:00
Nariman Jelveh af35783df4 Test native app hosts with apps still served natively (#4535)
editor, markus and pdf moved to standard host routing, but the host
redirect and embed framing tests still used editor as their native app,
so they failed. They now use about, and a test checks that editor,
markus and pdf are passed through even with a folder under the native
apps root.
2026-11-07 01:39:45 -07:00
Nariman Jelveh cb214f28cc Open Contact Us as a dashboard dialog in the dashboard (#4533)
The dashboard's Contact Us now uses the dashboard form dialog instead of a
UIWindow: a centered card on desktop and a bottom sheet on phones. Files can
be picked, dropped anywhere over the dialog, or pasted into the message, and
images show a preview. Cmd/Ctrl+Enter sends. The desktop keeps
UIWindowFeedback.
2026-11-07 00:40:45 -07:00
Nariman Jelveh 8ed439e897 Stop the signup screen redrawing when it opens (#4532)
The signup screen showed its email form, then looked up the identity
providers and folded the form away behind "Sign up with email" once they
arrived, a round trip later. Every screen made its own lookup, so moving
from login to signup redrew the card each time.

The provider lookup now happens once per auth flow, so moving between
login and signup draws the providers before the next paint. When signup
is the first screen, its email form stays hidden until the lookup
answers, or for 1.5 seconds if it is slow, and shows when no providers
are offered or the form was opened prefilled.
2026-11-06 23:58:44 -07:00
jelveh 672a704193 Shorten popup Puter branding message
Updates the English translation for `popup_opener_uses_puter` to a shorter single-line message. This removes the extra explanatory text about AI/cloud features and using a Puter account, likely for a cleaner popup prompt.
2026-11-06 23:41:00 -07:00
jelveh 35ae464d86 Tighten signup terms typography
Reduce the signup terms text in the auth dialog to match the tighter dashboard layout. This is a small styling adjustment for the dialog copy to keep it balanced and readable.
2026-11-06 23:37:37 -07:00
jelveh 79f24ed3df Hide the opener notice on the popup login screen
Someone logging in already has a Puter account, so like the account
picker the login screen no longer explains that the site uses Puter.
The signup screen keeps it.
2026-11-06 23:31:49 -07:00
Nariman Jelveh f30d2134b1 Keep profile pictures in the saved account list (#4531)
The account picker reads pictures from the logged_in_users list in
localStorage, but update_auth_data saved that list with an empty profile
and only added the picture in memory once the profile loaded. A picture
reached storage only when a later account switch or sign-out rewrote the
list, so the active account usually showed just its initial.

update_auth_data now keeps the account's saved profile until the fresh
one loads, then saves the user and the account list again. The profile
loads after puter.js holds the new account's token, so a switch can no
longer fetch the previous account's profile, and a profile that arrives
after another account signed in is dropped.

The first-visit migration in globals.js now stores the account list as
JSON instead of "[object Object]".
2026-11-06 23:22:11 -07:00
Nariman Jelveh c24c8589cb Hide the opener notice on the popup account picker (#4530)
Someone choosing from accounts they've already signed in with doesn't need
to be told the site uses Puter. The login and signup screens keep it.
2026-11-06 23:02:18 -07:00
Nariman Jelveh 2f8f81e621 Bind the app browser embed to the host's user and add <puter-user-menu> (#4528)
* Show the app browser embed's session only to the host's signed-in user

/embed/apps now reads the host page's signed-in user from its fragment
(#user=<uuid>) and asks /whoami which user the GUI session belongs to.
It shows the user's apps only when the two match. A host that names no
user, a malformed one, or another user, and a session the API refuses,
get the signed-out view of recommended apps with no SDK and no app
tokens. A failed /whoami check shows the unavailable state. Changing the
fragment reloads the embed.

Hosts pass the uuid from puter.auth.getUser() and remove the iframe when
their own sign-in changes; the doc's example does both.

* Add <puter-user-menu> for first-party apps on Puter subdomains

puter.js registers a <puter-user-menu> element that follows the page's
own puter.js sign-in. Signed out it shows Sign in; signed in it shows the
user's profile picture, or their initial when there is none, with a menu
holding the username and Sign out. On a page one label under the Puter
origin, an Apps button opens /embed/apps in a modal with the signed-in
user named in the fragment, so the app browser shows the Puter session's
apps only to that user. Any change to the page's sign-in closes the app
browser. The element renders nothing outside a top-level page.

Its labels can be set with apps-label, sign-in-label, sign-out-label,
close-label and account-label, and it fires signin and signout events.
It is documented internally in components.md and the embed doc, and is
left out of the public docs because the app browser only works on Puter
subdomains.

* Show <puter-user-menu>'s app browser in a panel under its button

The Apps view and the account menu are now panels that hang under their
button with a caret, closing on Escape, an outside press or the button.
They use the top layer where the browser has one, so a host's transform,
overflow or z-index can't clip or cover them. On screens up to 600px wide
the Apps panel spans the width below the button.

Closing the Apps panel keeps the app browser loaded; a change to the
page's sign-in still discards it. A spinner shows until it loads, and its
colour scheme follows the component's theme, which follows the OS unless
the theme attribute is set.

A temporary account counts as signed out: it gets Sign in, no profile
picture request, and an app browser with no user named. The signin event
carries the signed-in user, and the component exposes the parts
apps-button, avatar, sign-in, menu and apps-panel for host styling.

* Read the user <puter-user-menu> signs in as after the SDK starts its whoami

setAuthToken notifies auth listeners before it starts the new token's
/whoami, so a sign-in on a loaded page showed '?' and opened the app
browser without naming the user.

* Close <puter-user-menu>'s account menu when Tab leaves it

Focus moved on to the page with the menu still open, where Escape no
longer reached it. Tab now closes the menu and moves on from its button.

* Move focus to Sign in after signing out from <puter-user-menu>

The focused menu and avatar disappear on sign-out, which dropped focus
to the page body.

* Show the app browser in the theme <puter-user-menu> forces

Chromium doesn't pass an iframe's color-scheme on to the page inside it,
so a forced theme that differed from the OS showed the app browser in
the OS's theme inside a panel in the forced one. The component now
passes a forced theme as theme= in the fragment, and the embed applies
it to its color-scheme rules.

* Show <puter-user-menu>'s account before its profile picture loads

The avatar and Apps button waited for the /profile request as well as
the user, so a slow profile kept them hidden. The picture is now added
when it arrives.

* Open one sign-in popup at a time from <puter-user-menu>

Clicking Sign in again while its popup is still open opened another popup each time. Further clicks are ignored until the sign-in finishes or its popup is closed. A cross-origin isolated page can't see its popup close, so it keeps the old behavior rather than locking the button.

* Keep <puter-user-menu>'s Apps button unshaded after a tap closes it

Touch screens keep :hover on the last tapped element, so tapping the Apps button to close the panel left it shaded as if the panel were still open. Hover shading now applies only where the device can hover; the open state still shades the button everywhere.

* Show <puter-user-menu>'s Sign in pressed and its account hovered

Sign in had no pressed state and the account button no hover state, so neither responded to the pointer. Sign in now takes the pressed look of Puter's other primary buttons, and the account button shows its open-menu ring on hover where the device can hover.

* Show a spinner in the app browser embed until its apps arrive

The embed stayed blank while it checked the session with /whoami and loaded the SDK. <puter-user-menu> hides its own spinner once the embed's page loads, so its panel went blank for that whole time. The empty embed now shows the same spinner in the same place until it renders its apps or its unavailable message.
2026-11-06 22:18:38 -07:00
Nariman Jelveh 7d02c7f622 Offer a custom domain when publishing a folder from the dashboard (#4527)
* Offer a custom domain when publishing a folder from the dashboard

The Files tab's Publish Website dialog has a "Use a custom domain" switch.
It appears only when the server has custom domains. Turned on, it asks for
the domain, with the monthly price and suggestions from the domains already
on the account. Picking one of those moves it to the new site instead of
adding it again.

Publishing creates the site, then adds the domain. The done screen shows the
live address and the domain's status with the DNS records to set, each with
a Copy button, and a Check Status button. A failure after the site is live
keeps the site: the address locks, and the button retries only the domain.
A domain held by another account shows its ownership record to verify.

On a plan without custom domains, the switch shows an upgrade prompt in
place of the field and opens the upgrade flow where the deployment has one.
Once the plan changes, the field unlocks in place.

The /custom-domains request, error wording, price format and status-check
merge move to helpers/customDomains.js, shared with the desktop's attach
dialog.

* Name the served and forwarding domains the right way round in the redirect note

The note reads "served on {first}, forwarded from {second}", but both the
publish dialog and the attach dialog passed the root domain first.

* Fit DNS record labels of any length in the publish dialog

The label column was a fixed 44px, so a longer translation ("Pangalan")
ran under the field beside it. Each record card is now one grid whose label
column grows to its longest label, keeping the name and value aligned.

* Run one domain action at a time on the publish done screen

Check Status and the switch to www each disabled only themselves, so both
could be in flight and a slow status check could redraw the root domain
over the www one it had just become.

* Keep focus on the custom domain switch when it shows the upgrade prompt

Turning the switch on moved focus to Upgrade, so a second Space meant to
turn it back off opened the upgrade flow instead. The prompt follows the
switch in tab order.

* Finish with the live site when the plan can't add its domain

Once the site was live, a 402 from adding the domain left the button
reading Add Domain, and pressing it said to turn the switch off "to publish
without one". The button now reads Done and finishes with the site; an
upgrade brings the add back.

* Keep the ownership record and the Verify step in step while typing

Any edit hid the claim's TXT record for good, but the button went back to
Verify and Add as soon as the claimed hostname was typed again, asking to
verify a record no longer on screen. Both now follow the typed hostname.

* Keep the publish done screen up through a stray backdrop click when it lists DNS records

The records to set at the DNS provider appear only on this screen; a click
outside the card while switching to the provider's tab threw them away.
Done, Escape and the close button still close it.

* Listen for plan changes only once the publish dialog has offered the upgrade

Every website publish dialog added a window listener that held its closed
dialog until the next plan change, which may never come. The dialog is
modal, so the plan can only change after its Upgrade button opened the flow;
the listener is added then.

* Keep the upgrade prompt's text beside its icon on phones

Wrapping put the text on its own line under the icon, leaving the icon
alone on the first row; now only the button wraps.

* Drop "After publishing" from the domain hint once the site is live

When adding the domain needed another try, the hint still promised DNS
records "after publishing" for a site already published; it now keeps
only the price.

* Announce publish domain checks in a status region that stays on screen

Each check redrew the domain section, status line included, so its result
landed in a brand-new live region that screen readers don't announce, while
the redrawn records sat in the done screen's status region. The summary is
now redrawn on its own, outside the announcements.
2026-11-06 20:06:30 -07:00
Nariman Jelveh d2bbe2b5e2 Ignore Explorer responses for a folder the window has left (#4526)
Each refresh of an item container now takes an id, and only the newest
refresh may write to the container or its window. Before, a slow stat for
the folder a window had left could point the window back at it, so New
folder, Paste and Upload went to the old folder while the window showed
the new one. A listing that arrived just before navigating away added its
rows to the new folder, and returning to a folder while its first listing
was in flight rendered every row twice. The stat in update_window_path
also skips its writes once the window has moved to another path.
2026-11-06 18:28:25 -07:00
Nariman Jelveh 3ff70ef97f Remove web apps from native host redirects
Allow the `editor`, `markus`, and `pdf` subdomains to use standard host routing.
2026-11-06 17:20:22 -07:00
Nariman Jelveh f791024b2e Support dark mode in the desktop context menu (#4525)
The desktop context menu (UIContextMenu) stayed white with dark text when
the OS was in dark mode, even though the dashboard around it turns dark.
It now follows prefers-color-scheme like the dashboard: a dark translucent
surface, light text, and dark variants for dividers, the open-submenu and
blurred highlights, the submenu chevron, monochrome icons, and the mobile
action sheet.
2026-11-06 16:01:08 -07:00
Nariman Jelveh cce9718b45 Stop the sign-in page jumping when the iOS keyboard opens
A sign-in page already fills the screen, so it no longer shrinks itself
to the area above an on-screen keyboard. On iOS that resize fought the
browser's own pan to the focused field and the form moved up and down
as the keyboard opened. Dialogs still fit above the keyboard.
2026-11-06 15:40:36 -07:00
Nariman Jelveh 9758ada36e Keep the wallpaper off sign-in pages and drop the OIDC-only signup notice
Signed out, /action/login, /action/signup, /action/password-recovery and
the sign-in page for returning visitors, app landings and share links no
longer load the wallpaper behind them, and the page covers the screen at
once instead of fading in over whatever was there.

The signup screen no longer explains that only providers are offered when
email signup is closed; it just shows the provider buttons.
2026-11-06 15:30:57 -07:00
Nariman Jelveh 37dcee78f0 Move login, signup, account picker, password recovery and 2FA to dashboard-style dialogs (#4522)
* Move login, signup, account picker, password recovery and 2FA to dashboard-style dialogs

The sign-in surfaces were separate UIWindows that opened over each other
(login, then a recovery window over it, then a 2FA window over that). They
are now screens of one dashboard-style card built on mountDashboardOverlay,
the same shell, fields, buttons and status line as the dashboard's account
dialogs. Screens replace each other in place, with Back, and keep what was
typed.

- Page presentation for cover pages and sign-in popups: an opaque page with
  a centered card, filling the screen on phones and in popups. Dialog
  presentation elsewhere: dimmed backdrop, centered card, bottom sheet on
  phones.
- Each call site keeps whether it could be dismissed, its promise contract,
  OIDC gating in popups, Turnstile, the honeypot, bonus codes, the
  post-signup verification gates, reauth auth_id, and redirect handling.
- Keys typed in the card no longer reach the desktop's document shortcuts.
- A second sign-in prompt joins the open flow instead of stacking a card.
- Server messages render as text; prefilled values are encoded.

* Show the signup screen's errors above the provider buttons

The status line lived inside the email form, which hides behind the
provider buttons (or for good, when only provider signups are open), so
an error the screen opened with, like a refused provider signup, was
never shown.

* Cover the page with a new account's checks when signup was a page

Signup as a page (a sign-in popup, /action/signup) closes its card for
the email, phone and card checks; they opened as floating windows over
an empty backdrop instead of covering the page as they did before.

* Give the auth card's Back and close bar a background once it scrolls

On a short screen the card's content scrolled under the bare Back and
close buttons, which then sat on top of it: the Back chevron covered the
edge of a provider button and took its taps. Once the showing screen is
scrolled, the bar turns opaque with a divider, as the footer has; at
rest nothing changes.

* Raise a failed session-cookie sync alert above the sign-in card

Signing in waits on this alert with the auth card still up. The card
sits above every ordinary window, so the alert opened underneath it and
the login spun forever. It now opens in the stay-on-top band.

* Keep focus where it is when a second sign-in prompt joins the card

A prompt that joins the open auth card focused the screen's first
field, so one arriving while the user typed their password sent the
rest of it into the username field. It now only brings focus back when
it has left the card.

* Keep focus in the auth card while its form is busy

Submitting disabled the focused field, which dropped focus to the page,
so keys pressed while the request was in flight (Delete, Enter, letters)
reached the desktop's document shortcuts.

* Keep focus in the auth card when its backdrop is pressed

A press on the dimmed backdrop (or a page's background) that didn't
dismiss the card moved focus to the page, so the next keys went to the
desktop's document shortcuts and Tab could leave the card.

* Point the Turnstile migration note at the new signup screen

UIWindowSignup no longer exists; the widget renders in UI/Auth/UIAuthSignup.js.

* Reload after sign-in when only the URL's hash would change

On a dashboard tab (/#files) the redirect after a login or signup was
the same page with a hash, so location.replace only scrolled: the new
account was signed in but the page never reloaded, and the card stayed
up, busy, until closed.

* Span the screen with the auth bottom sheet on wider phones

The card's 400px cap outranked the dashboard sheet's full width, so on
phones between 401 and 600px wide the sheet left gaps on both sides.

* Return focus to the auth form when a request fails

A busy card parks focus on itself while its fields are locked. When the
server refused a signup, focus stayed there, so Enter did nothing and the
user had to tab back in. Ending busy now hands focus back to the control
that had it, once that control is enabled again.

* Keep the current account when a login is dismissed mid-request

Closing the auth card while its login request was out still signed the
browser in to the other account and reloaded once the server answered,
though the caller had already been told the user dismissed it. A login
that answers after the card closed is now dropped.

* Make the auth card's logo a link where it leads somewhere

On a cover page the Puter logo was an image with a click handler: no
keyboard access, no name for screen readers, no middle-click. It is now a
link named Puter. Everywhere else the logo is marked decorative, since the
title beside it names the screen.

* Return to the login screen when signing in fails after a 2FA code

If storing the new session failed after a verified code, the error went
to the hidden login screen while the code screen stayed up, busy, with
its boxes locked. The card now goes back to the login screen first.

* Hand the session cookie back when a login is dismissed mid-request

The server sets the session cookie as soon as it accepts a login or a
second-factor code. Dropping an answer that arrived after the card closed
kept the page on its account while the cookie had moved to the other one,
so cookie-gated actions (password, 2FA) applied to that account and the
next load picked up its token. The cookie is now synced back to the
account the page is signed in as.

* Keep padded notices inside the auth page's column

On a phone-width page or in a sign-in popup, every direct child of the
auth body is stretched to the column's width. The overlay sits outside
.dashboard, so it isn't border-box, and the padded error line and bonus
notice came out wider than the fields and scrolled the page sideways.

* Keep the recovery-code field one size when it takes focus

On phones the generic dialog-input and phone input rules outranked the
recovery-code field's style until it was focused, so tapping it grew the
text from 16-17px to 20px and shifted the screen. The field's rule now
carries the same weight as theirs, like the code boxes beside it.

* Show the provider buttons' hover in dark mode

The hover shade was the sidebar background, which in dark mode is one
step off the card's, so Google, Apple and the other sign-in buttons gave
no feedback under the pointer. Dark mode now uses the hover shade.

* Theme the signup bonus notice with the auth card

The notice kept the old signup window's fixed pastel colors, which stood
out as a light box on the card in dark mode. It now uses the dashboard's
success and danger colors, which follow the color scheme.

* Keep a new account's email check from closing without an answer

A signup that needs its email confirmed takes the auth card down and
waits on the confirmation window, whose ✕ closed it without ever
answering. In a sign-in popup reached from the account picker that left
an empty popup with nothing to pick. The check now stays until the code
is confirmed, like the phone and card checks and the boot-time email
check.
2026-11-06 15:20:08 -07:00
Daniel Salazar 162398a827 test: fix coverage line mapping, puter.js coverage OOM, and flaky backend tests (#4523)
- lowerDecoratorsPlugin dropped esbuild's source map, so coverage and
  stack traces reported transformed lines. Pass the external map through.
- puter.js node runner kept a ~6 MB `__coverage__` per vm context and ran
  out of heap. Contexts now share one object; workerd merges as it goes.
  report-coverage skips its comparison when the PR leg failed.
- CI-only test/hook timeouts of 20 s / 60 s.
- setupTestServer disables the database-liveness health check, whose
  `SELECT 1` landed in query-counting tests.
- LocalWorkerService.shutdown asserts the timer shutdown arms instead of
  the global fake-timer count.
- userHandlers worker test waits for posts by label.
- AppStore stats test pins the clock so rows don't cross midnight UTC.
- Realtime backpressure test waits up to 5 s for holds to settle.
2026-11-06 12:30:36 -07:00
jelveh 6785b4d9cc Reorder recommended apps and drop terminal
Updates `RECOMMENDED_APP_NAMES` to prioritize core productivity apps (`word-processor`, `spreadsheet`, `presentation`, `whiteboard`, `pdf-editor`) immediately after `builder`, and removes `terminal` from the recommended list.
2026-11-06 09:05:33 -07:00
Nariman Jelveh d2acdafaed Show recommended apps in the app browser embed without a session (#4517)
* Show recommended apps in the app browser embed without a session

/embed/apps only worked for a signed-in user; without a session it showed
an unavailable state. The route now puts the recommended apps
(RecommendedAppsService) in the page's config as guestApps, and when the
embed finds no session it shows those, without loading puter.js or reading
installed apps, folders, or saved order. Selecting one opens it at the
same URL a signed-in launch uses, with no opener and no token on offer, so
the app signs in on its own; apps that need the desktop open /app/<name>.
Signed-in behavior is unchanged.

createAppBrowser takes a guestApps option for this, and appTabLaunch's
URL building is shared between launchAppInTab and the new
guestAppLaunchUrl.

* Show the app browser embed's error state when the session lookup fails

Only a 401 from /get-gui-token now means there is no session. A rate
limit or server error shows the unavailable state, as before, instead of
the signed-out list of recommended apps.

* Let the app browser embed find no session when storage is refused

Reading local storage can throw when the browser blocks site data. The
embed now falls back to the session cookie, as it does for empty
storage, so a visitor without a session sees the recommended apps
instead of the unavailable state.

* Fix the app browser embed doc's broken sentence about puterOrigin
2026-11-06 07:48:11 -07:00
Reynaldi Chernando 6a46363d6d reorder api sections (#4519) 2026-11-06 17:30:22 +07:00
Reynaldi Chernando 2de9d509e8 docs layout cleanup (#4518) 2026-11-06 16:22:48 +07:00
Nariman Jelveh 763742dbc0 fix(embed): read the app browser's session from the cookie when its storage is empty (#4516)
Safari keys a framed origin's local storage by the top-level origin, so the
app browser embedded on a sibling subdomain finds no auth_token_v2 and shows
"Apps are unavailable". The session cookie is still sent there, so the embed
now falls back to /get-gui-token and keeps the token in memory.
2026-11-05 23:41:38 -07:00
Daniel Salazar 7f0cd1689b fix(embed): only sibling subdomains not served by core can frame the app browser (#4515)
/embed/apps now names the referring origin in frame-ancestors only when it
is exactly one label under the domain and that label is not one the server
answers itself (api, dav, js, www, native-app hosts) or the host of
api_base_url. Nested subdomains are refused too.

The query-string redirect now checks the raw URL instead of the parsed
query, so every request carrying a query string is redirected.
2026-11-05 23:10:34 -07:00
Daniel Salazar 9d22f39928 Ask for notification permission from Puter's dialog when the click has expired (#4514)
On a website, puter.notifications.enable() threw user_gesture_required
without prompting once the calling click's activation was gone: after
puter.auth.signIn() or requestPermission() opened a popup in the same
click, after a few seconds of awaited work, or when called on load. Apps
that ignored the error showed nothing.

It now shows Puter's consent dialog in that case and asks the browser
from its Continue click; Cancel resolves false. Calls made while an ask
is open share it. PuterDialog gets an onContinue option and a show()
that launch() also uses. Inside Puter's own desktop page the call still
throws, since it always runs from a click.

The push guide also notes that Chrome stops showing the prompt after
three dismissals and that its quieter messaging shows a bell icon.
2026-11-05 23:10:06 -07:00
Nariman Jelveh ef185c04ca Open apps from the dashboard's Home tab at their own URL (#4513)
Recently used apps on the Home tab opened /app/<name> in a new tab, which
loads the desktop and launches the app from there. They now open the way
Apps tab tiles do: a new tab at the app's index_url through launch_app's
newTab, or in this page when the browser refuses the tab. The Apps tab's
open-window lookup moves to helpers/focusAppWindow.js so both share it,
and the shared launch lives in helpers/dashboardAppLaunch.js, outside the
app browser so the embed bundle doesn't pull in launch_app.
2026-11-05 21:30:52 -07:00
Nariman Jelveh dec7d1fd96 Load the app browser embed's script from beside the GUI bundle (#4511)
The embed page always loaded /dist/apps-embed.min.js from the server,
while the GUI bundle and the embed build are published to gui_bundle's
location (a CDN in production). The server's /dist copy can be stale, so
the embed ran an old build. It now loads apps-embed.min.js from
gui_bundle's directory, keeping /dist when gui_bundle isn't set.
2026-11-05 21:07:05 -07:00
Nariman Jelveh fb9e7d70c6 Open apps from the embedded app browser at their own URL (#4510)
* Open apps from the embedded app browser at their own URL

Selecting an app in the /embed/apps browser now opens it in a new tab at
its index_url, with the same launch params the dashboard's tab launch
uses, instead of the GUI's /app/<name> landing. The tab is opened inside
the click and without noopener; the app's SDK asks the embed for its
token through the opener, so the token stays out of the URL.

Apps that need the desktop (built-in and godmode apps, private apps the
user can't open, or a failed token request) still open /app/<name>, with
the tab's opener cleared. Website shortcuts are unchanged.

The app URL, the app token request and the /rao report move out of
launch_app into helpers without desktop globals (appLaunchUrl.js,
appLaunchApi.js), so launch_app and the embed build the same URL.
uuidv4 moves to a helper the embed can import.

* Tag app launches with utm_medium and a utm_campaign naming the launch surface

Apps now get utm_medium=referral and utm_campaign=desktop, dashboard, or
app_browser_embed alongside utm_source=puter.com, so their analytics can
tell where in Puter they were opened from.
2026-11-05 20:31:30 -07:00
Nariman Jelveh 819e77bb4c Open dashboard apps and files in a new tab at the app's index_url (#4508)
* Open dashboard app tiles in a new tab at the app's index_url

Clicking an app tile in the dashboard now opens the app in a new browser
tab at its index_url, with the same query params (puter.app_instance_id,
puter.app.*, puter.auth.token, puter.domain, puter.api_origin,
puter.locale, puter.args, ...) its in-page iframe gets.

launch_app takes a newTab option: it runs the normal launch (private
access, file signing, token) and sends the caller's tab to the built URL
instead of opening a window. The tile click opens the blank tab inside
the click so popup blockers allow it, and closes it if the launch fails.

* Hand an app tab its token through the opener, not the URL

An app opened in its own tab no longer gets puter.auth.token in its URL,
which kept the token in browser history, and which puter.js ignored anyway
outside an iframe.

The GUI now holds the token for the tab it opened. Once the app loads,
puter.js (standalone, with puter.app_instance_id in its URL and an opener)
asks its opener for it at the configured GUI origin, takes only a reply
from that window at that origin, and then clears window.opener. The GUI
answers once, only to that tab at the origin it sent the tab to, and
drops the offer after two minutes. Sign-in and implicit auth wait for the
handoff, then fall back to the normal sign-in flow when no token came
(opener closed, slow load, redirect to another origin).

Built-in apps join explorer in opening in-page, since they belong to the
desktop.

* Open files from the dashboard Files tab in a new tab

Opening a file in the Files tab (double-click, Enter, tap, or the Open
menu item) now opens its app in a new browser tab, the same way app
tiles do. The tab is opened inside the gesture and handed to open_item,
which passes it to launch_app or closes it when the file opens no app.
Web links reuse the tab, cut off from the dashboard. A second file of a
multi-select Enter, whose tab the popup blocker refuses, opens in-page.

The opened file's signed read/write URLs don't expire, so a tab gets
them through the opener handoff with its token instead of in its URL;
the URL keeps only puter.item.uid as a marker. puter.js delivers the
handed-over item to onLaunchedWithItems / onItemsOpened, and
wasLaunchedWithItems answers true while it's on its way.

launch_app now closes a tab it was given whenever the launch fails, so
callers don't each have to.

* Open "Open With" apps from the Files tab in a new tab

Picking an app under Open With in the dashboard Files tab now opens it
in a new browser tab, like opening the row. The tab is opened in the
menu click, or, when the "always open with" prompt comes first, right
after it's answered, since that click counts as a fresh user gesture.
If the popup blocker refuses the tab, the app opens in-page. The desktop
keeps opening in-page.

* Wait for a GUI-opened tab's token in getUser, whoami and getProfile

A tab the GUI opens for an app gets its token over postMessage moments
after puter.js loads. These calls short-circuited on a missing token, so
an app reading the user at startup failed with a 401 (or a null profile)
even though the token was on its way. They now wait for the handoff
first, the same way sign-in already does.

* Close an app's blank tab before alerting that its launch failed

A launch denied for a private app, or one whose token couldn't be
fetched, awaited its alert while the blank tab it was given stayed in
front. The alert renders on the dashboard behind it, so the user was
left on an empty tab until they went looking. The tab is now closed
before the alert shows.

* Launch an app tile in-page when the browser refuses its tab

When window.open returned null (a popup-blocking setting, or a context
that can't open tabs), clicking an app tile did nothing at all. It now
falls back to the in-page launch it had before, as opening a file from
the Files tab and Open With already do: an open window is surfaced,
otherwise the app opens maximized with the tile's open morph.

* Open no tab for a file opened from the Trash

Opening a file in the Trash only explains that it can't be opened, but
the Files tab still opened a blank tab for it first, which then closed
again: a flash of a new tab before the alert. Trashed files (by the
path a shortcut resolves to) now get no tab.

* Don't count a tab launch as one that can report interactivity

launch.ipc_tracked on app-is-ready is the denominator for the
app-interactive series: launches that could produce one. An app opened
in a new tab never signals over IPC, yet was recorded as tracked, so
every tab launch counted as an interactive span that never came. Tab
launches are now recorded as untracked.

* Leave openerLaunch_ unset when there is no GUI opener to ask

requestLaunchFromOpener resolved null asynchronously even when there was
no opener at all, so openerLaunch_ was briefly set on every boot with an
app instance id in the URL. A reloaded app tab (opener already cut off,
URL still marking the opened item with puter.item.uid) reported
wasLaunchedWithItems() as true to code running in the same task as the
boot, though no item would ever arrive. With no opener to ask it now
returns null synchronously and nothing is left pending.

* Call an app tab launch off when the user closed its tab

Closing the blank tab while the launch's fetches were in flight didn't
stop the launch: it still navigated the closed tab, offered it a token,
and recorded the app as opened (recent apps and /rao). The launch now
checks the tab before sending the app there and ends as not launched,
without an alert, when the user has closed it.

* Keep a same-origin opener instead of asking it for a GUI launch

Any top-level page with an app instance id and an opener asked that
opener for its launch, waited out the timeout when no answer came, and
then nulled window.opener. A page an app opened from its own origin (a
pop-out of itself, say) can't have the GUI as its opener, yet it waited
five seconds before its launch item and sign-in, and lost its link to
the app window that opened it. An opener readable from this page, on an
origin other than the GUI's, is now left alone and not asked.
2026-11-05 19:27:46 -07:00
Daniel Salazar 7355eaa77b feat(realtime): run the host prompt check per response and log its cost (#4507)
Each response that starts runs `ai.prompt.validate` on the text the client
sent since the previous check (instructions, message text and transcripts,
function call output), and its usage follows as `ai.prompt.cost-calculated`
under the same completion id. A refusal closes the session with
`permission_denied`. Nothing runs when no host listens for the check.
2026-11-05 18:05:43 -07:00
Nariman Jelveh d55aac1f98 Add embeddable Puter toolbar and shared app browser (#4019)
* Add embeddable Puter toolbar and shared app browser

Provide deployment-scoped iframe routes, a responsive host helper, read-only app browsing, saved-account switching, and new-tab account and upgrade links. Validate account sessions before switching and keep credentials inside the GUI origin.

Verified with 182 targeted tests, production GUI build, backend type checking, lint, and a real-backend browser smoke test. Translation checker could not run because tools/check-translations.js is missing.

* Prevent embedded toolbar from scrolling when menus open

* Stop double-encoding translated toolbar labels

i18n() already HTML-encodes its result, so wrapping it in escape() again
turned accented labels into literal entities (e.g. "Schlie&szlig;en") for
screen readers, and .text() did the same for the error message.

* Load only the preferred language in the toolbar and app browser embeds

Importing i18n.js pulled every translation into each embed, making the
toolbar bundle 1.1 MB. The embeds now bundle English and fetch the user's
language on demand (toolbar 1.12 MB -> 179 KB, app browser 1.18 MB -> 237 KB).
The desktop bundle keeps all translations.

* Keep toolbar buttons in place when a menu opens near the viewport edge

On phones the expanded frame was clamped to an 8px viewport margin, which
moved the whole toolbar row (by the header padding minus 8px) under the
user's finger. The frame now shrinks to fit beside and below the collapsed
toolbar, and only falls back to shifting when there isn't enough room.

* Don't pull focus back into the toolbar when the host page closes its menu

Clicking a host text field while a toolbar menu was open closed the menu and
then refocused the toolbar button, so the host field lost focus and typing
went nowhere. Focus is now restored only while the toolbar document has it.

* Close toolbar menus when the empty part of the expanded frame is pressed

While a menu is open the toolbar frame covers host content beside the
buttons; presses there reached neither the host nor the toolbar's outside
click handling, so the menu stayed open. They now close it.

* Omit the empty email line in the toolbar account menu

Temporary accounts and saved accounts without an email rendered an empty
element, adding a stray gap under the username.

* Stop user-hosted sites from framing the toolbar and app browser embeds

frame-ancestors allowed every *.<domain> subdomain, which on the default
self-hosted layout includes user sites (*.site.<domain>) and private apps
(*.app.<domain>), letting any hosted page clickjack sign-out and account
switching. The policy now names the embedding page exactly, from the
request's referrer, and refuses the user-content hosting domains.

* Use the dashboard danger color for the toolbar sign-out confirmation

The hardcoded red had 3:1 contrast on the dark panel, below WCAG AA for
14px text. The dashboard's danger token is 4.8:1 in light and 6:1 in dark.

* Drop the dashboard's hamburger clearance from the embedded app browser

At narrow widths the dashboard pads the search 60px down to clear its fixed
menu button. The embeds have no such button, so the toolbar's app panel
lost 90px of a ~500px frame to empty space above the search.

* Keep the toolbar's Upgrade button legible in dark mode

Upgrade was filled with the link color, which dark mode lightens to
#6b8cff: 3.1:1 under white text. Use the dashboard's primary-button fill
(4.6:1 in both themes) and its hover color, and drop the button classes
nothing styles on this page.

* Keep the toolbar's apps icon legible on hosts in the other theme

The toolbar follows the OS theme but draws on the host page, so in dark
mode on a light host its icon was #d4d4d4 on white (and the reverse on a
dark host). Give the apps toggle a surface of its own, like the avatar
beside it, and the session-unavailable notice one too.

* Let the toolbar sign out of a session that already ended

When the session was ended elsewhere (revoked, or signed out in another
tab), the anti-CSRF and logout requests answer 401 and sign-out failed
on every retry, stranding the stale token. Treat 401 as already signed
out and finish clearing it locally, as the desktop does; other failures
still keep the session and show the error.

* Keep the toolbar's slot following the host layout while a menu is open

The helper reserved the toolbar's space with a span frozen at the
frame's resolved size and margins, so a host that right-aligns it with
margin-left: auto (or sizes it in percentages or media queries) left the
open menu anchored to a stale spot, overflowing the header, after a
resize or rotation. Reserve it with an empty clone of the frame instead,
which the page's own rules keep laying out; if they target
data-puter-toolbar, which the clone drops so hosts still find one frame,
hold the frame's measured size.

* Reuse isOrgSeat for the toolbar's Upgrade check

The toolbar re-implemented the dashboard's organization-seat test
inline. Use the shared helper so both surfaces agree on who sees an
upgrade offer.

* Point comments at AppBrowser.js, where the Apps tab code now lives

The constants and methods these comments name moved out of TabApps.js
when the app browser became shared.

* Restore the license header on the new embed and toolbar files

TabApps.js lost its AGPL header when its code moved to AppBrowser.js,
and the new embed, toolbar, and host-helper modules were added without
one; every other GUI source file carries it.

* Remove the embeddable toolbar, keeping the standalone app browser

Drop /embed/toolbar, its page and host helper, their styles, strings and
tests, and the dashboard's ?upgrade=1 deep link that only the toolbar's
Upgrade button used. /embed/apps no longer allows the GUI origin to frame
it with a wildcard over deployment subdomains, which existed only for the
toolbar's nested app browser, and its bootstrap config no longer carries
the domain the toolbar read.
2026-11-05 17:19:05 -07:00
Daniel Salazar c6987d9606 feat(notifications): push unless a page is visible and focused (#4506)
A push is skipped only when a page that got the notification live was
visible and focused. Hidden, unfocused or unanswering pages no longer hold
it back, and pages no longer show browser notifications themselves, so the
push reaches every subscribed browser.

- Receipts carry the page's visibility and focus as of arrival; the settle
  gains `handled`. `showsOwn` is gone.
- Pages send `notif.handled { uid }` on the socket a notification arrived on
  when they got it while visible and focused. Core relays it as the
  node-local `notif.handled` event (60 a minute per user) for extensions.
- puter.js drops the page-shown notification path; push-sw.js drops its
  page-show message. Handlers still run live in the page.
- The desktop registers /sw.js only when push is turned on, updates it when
  subscribed, and removes one left without a subscription. Its hidden-tab
  banners are gone.
- Docs describe the focus rule.
2026-11-05 14:43:33 -07:00
Filip Kujundžić 796b42c74d Merge pull request #4475 from HeyPuter/fix/openai-cache-write-tiers 2026-11-05 21:27:46 +01:00
404oopsandClaude Opus 5.5 e2043a5e58 Merge remote-tracking branch 'origin/main' into fix/openai-cache-write-tiers
Main's docs cleanup (#4504) moved the prompt caching docs under
per-provider sections; the OpenAI paragraphs now live under
OpenAI models > Prompt Caching.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-05 19:55:55 +01:00
Filip Kujundžić 8b98c7ada8 Merge pull request #4503 from HeyPuter/codex/openai-image-default
feat(ai): add GPT Image 2.6 and default to Flare
2026-11-05 19:53:05 +01:00
Filip Kujundžić b27e84d181 Merge pull request #4457 from HeyPuter/fix/convo-bounded-recovery
Bound conversation recovery and report omitted replay context
2026-11-05 19:46:10 +01:00
404oopsandClaude Opus 5.5 add0e7be7d fix(convo): report routine context trimming as context_trimmed
A reconnect that left older items out of the 40-item, 48 KiB restore window
fired an error event with context_restore_failed, the code a provider
refusal uses, with the count only in the message. Every reconnect of a long
conversation raised an error that apps treating error as fatal would surface.

Trimming now fires a nonfatal context_trimmed event, before ready, with the
count in omittedItems. context_restore_failed is kept for a provider refusal
of a restored item or a failed send of the replay.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-05 19:28:02 +01:00
404oops b5d221ede6 fix(convo): bound recovery attempts and report omitted context 2026-11-05 19:28:02 +01:00
404oops 3137a631a7 fix(realtime): reuse settled credit for post-record continuation 2026-11-05 19:28:02 +01:00
404oopsandClaude Opus 5.5 57706d8093 fix(realtime): bound unacknowledged audio by duration, not a byte cap
The per-commit cap of 1,280,000 bytes assumed G.711, so a PCM16 session
(48,000 bytes/s, the SDK's format) with transcription on was closed with
1013 after about 27 seconds without a commit: silence under server VAD,
one long utterance, or a long assistant reply.

Unacknowledged audio is now a duration at the provider-confirmed input
format (the lower rate while a requested format is unconfirmed). Without
turn detection it counts all audio since the last commit or clear; with
server VAD only speech from speech_started, plus the buffer after an
explicit commit, since the provider drops silence. Each started 160 s
claims one spare item as its hold instead of closing the session; a
commit, clear or input_audio_buffer_commit_empty returns the holds to the
pool. If the upstream closes first, every claimed item is billed. The
settle no longer commits silence.

The relay test file now expires the in-memory per-IP pre-auth window
after each test; every test connects from loopback and the added tests
pushed the file past 120 upgrades a minute.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-05 19:27:54 +01:00
Reynaldi ChernandoandClaude Opus 5.5 fec1d1916f Merge remote-tracking branch 'upstream/main' into codex/openai-image-default
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-06 01:03:08 +07:00
Juan Fernando CastroandReynaldi Chernando da369039e0 docs: complex teams recipe (PUT-1986) (#4095)
* docs: complex teams recipe (PUT-1986)

Showing which teammates have a file open, built from a folder shared with the
team plus `puter.events` watching it. There is no presence API, so the recipe
is about composing the two.

One use case per the recipe guidance. Uses the masked path from
`listShared()` so members address the owner's folder, keys presence files on
`uuid` rather than username, and re-reads the folder on each event so a missed
delivery cannot leave the list wrong.

* refine

---------

Co-authored-by: Reynaldi Chernando <[email protected]>
2026-11-06 00:53:25 +07:00
404oopsandClaude Opus 5.5 4f36152850 fix(realtime): hold transcription credit per item at the selected model
Input transcription reserved 64 items up front at the costliest model's
price and largest cost factor, about $7 before factors per session. Ordinary
subscribers couldn't enable it, and concurrent sessions were refused while
balance was left.

Each item now holds its own credit at the selected transcription model's
budget and cost factor. Two spare items are reserved before configuration or
audio is forwarded and refilled as the provider commits items, within the
64-item pending cap. A commit with no spare reserves its own item. A model
change releases the spares and reserves new ones at the new price; committed
items keep their hold. When the account can't cover another item, client
reads pause while the session's own holds may still free credit, and the
session is refused with insufficient_funds once it holds none.

Audio awaiting a commit acknowledgement is now tracked separately from pool
capacity and reset by each acknowledged commit or clear. If the upstream
closes before that acknowledgement, the audio bills as one item. Previously
the fallback required an untouched window, so a lost acknowledgement after an
earlier completed item went unbilled; the cumulative byte count could not
simply be reused without charging earlier work twice. The uncommitted-audio
cap is now 160 seconds of audio instead of a per-window total.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-05 10:23:49 -07:00
404oops 86db96d587 fix(realtime): reserve and settle pending transcription work 2026-11-05 10:23:49 -07:00
404oops 214ffb6605 fix(realtime): evict revoked credentials and recheck paid eligibility 2026-11-05 10:23:48 -07:00
404oops 871cc2cf87 fix(realtime): bound upgrades before credential admission 2026-11-05 10:23:48 -07:00
404oops ba002be0f7 fix(convo): reject interrupt readiness failures asynchronously 2026-11-05 10:23:47 -07:00
404oops 2832926f8d test(realtime): isolate credential attempt budgets between cases 2026-11-05 10:23:47 -07:00
404oops 1ab1c04760 fix(realtime): redact structured provider diagnostics 2026-11-05 10:23:47 -07:00
404oopsandClaude Opus 5.5 63a98f89ff test(metering): find the actor key in any meterIncr argument
The buffered write now passes the claim key too, which moves the counter
key's position. The image provider's write-ordering test matched it by
index and stopped seeing the write.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-05 10:23:46 -07:00
404oops d2cef27085 perf(metering): avoid retries for growing buffers 2026-11-05 10:23:46 -07:00
404oopsandClaude Opus 5.5 74b60c1227 fix(metering): type the array read's retry callback
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-05 10:23:46 -07:00
404oopsandClaude Opus 5.5 2ed3e78dfa fix(metering): keep buffered and store reads from missing or doubling usage
Three reads still got a flush wrong:

- A write re-sent after its reply was lost, found already applied, left
  the claim without touching a warm cached base, so balance reads stayed
  short of what the store held. The claim and the base are now dropped
  together, and the next read seeds a fresh base from the store.
- A read with no cached base took the buffer, then the store; a flush
  that wrote a batch and left its claim in between had it counted twice.
- An exact read added another deployment's claim but not the usage that
  arrived behind it, which that read can't flush, so a charge crossing
  the allowance went entirely to the allowance.

Reads that go to the store now take everything buffered (delta and
claim), read the store consistently, and read the buffer again, retrying
when it shrank in between. Single and array reads and exact reads all
use it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-05 10:23:46 -07:00
404oopsandClaude Opus 5.5 22ebd353b8 fix(metering): read the claim before the store in an exact read
`readExact` read the store and the outstanding claim side by side. When
a flush wrote a batch and took it off its claim between the two, the
store read had the counter from before the write and the claim read had
nothing, so the batch was missed: 10 units recorded, 0 read.

The claim is now read first. An amount gone from it by then was written
before the store read, which is consistent, so the read has it. When the
claim changes during the store read, the batch may be in both, so the
read is retried, up to three times.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-05 10:23:46 -07:00
404oopsandClaude Opus 5.5 7551e12370 fix(metering): count claims on the write path and read missing bases exactly
The running total `incr` returns and `readExact` also missed usage a
flush had claimed but not yet written. Both feed how a charge is split
between the allowance and purchased credit, so an account could be
charged to its allowance for usage that had already used it up. Both
now add the counter's outstanding claim.

A read or seed with no cached base asked the store with an ordinary
read, which could miss a write a settle had just made; it now reads
consistently. A write-through after a cache failure drops the cached
base, which doesn't have the write, so the next read reseeds it.

The dirty-set reconcile test no longer depends on how many flush cycles
earlier tests ran.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-05 10:23:46 -07:00
404oopsandClaude Opus 5.5 6e29e32fe9 fix(metering): count usage mid-flush in balance reads
A flush takes a counter's buffered amounts aside before writing them
onward, and reads only looked at the live delta and the cached base.
From the claim until the settle replaced the base, those amounts were
missing from every read: one store write normally, up to the orphan
sweep if the write failed. Balance checks, credit reservations among
them, could see an account as having more than it does.

Reads now add the counter's outstanding claim. A batch written onward
leaves the claim and joins the cached base in one step, so it stays
counted until the settle replaces the base with the store's view.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-05 10:23:46 -07:00
404oopsandClaude Opus 5.5 54bfc0ffe5 test(puter-js): prove microphone chunks hit the closing-socket gap
The browser test now counts the chunks the transport refused while the
socket read as closing, and requires at least one, so it can't pass
without exercising the gap. The socket stays closing until the
connection drops instead of going back to open.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-05 10:23:45 -07:00
404oopsandClaude Opus 5.5 c27883134b fix(puter-js): keep microphone capture when the socket closes first
A conversation still reads as connected for a moment after its socket
starts closing. A microphone chunk sent in that moment got
`session_closed`, and the capture handler treated that like a real
media failure: it stopped the tracks and the AudioContext, so the
replacement session after the reconnect had no microphone.

The built-in microphone now drops a chunk the transport refuses with
`session_closed` or `session_not_ready`, as it already did for
`queue_full`, and keeps capturing. A reconnect resumes sending; a final
close still stops capture through the conversation, and processor or
other errors still release it. Dropped chunks aren't replayed, and
public sends keep reporting the transport error.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-05 10:23:45 -07:00
404oopsandClaude Opus 5.5 cf4c1f6b64 fix(puter-js): end the conversation on an oversized event mid-reconnect
A server event over the 4 MiB limit closes the socket with 4009, which
ends a connected conversation. During a reconnect attempt the same close
was reported as `session_closed`, which is retried, so the conversation
tried ten more times and finally closed with the original drop code.
A replacement session opened after a restart notice was reopened again
and again for the same reason.

A 4009 close now ends the conversation during a reconnect too, reporting
4009, and a replacement session that hits it isn't reopened. Tests cover
both, a multibyte event of exactly 4 MiB, and a whole retrieved item
through the relay.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-05 10:23:44 -07:00
404oopsandClaude Opus 5.5 305d20ab1c fix(puter-js): accept provider events up to the relay's 4 MiB cap
The conversation transport refused any server event over 64 KiB with a
terminal 4009 close, the limit meant for what the SDK sends. The relay
forwards provider events up to 4 MiB, and a session.updated echo or a
whole audio item easily passes 64 KiB, so valid conversations ended.

Incoming events now have their own 4 MiB limit, matching the relay,
counted in UTF-8 bytes (a string short enough that it can't exceed the
limit isn't encoded to check). An event over it still closes with 4009
and doesn't reconnect. Uploads keep their 64 KiB cap, and malformed
events are still ignored.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-05 10:23:44 -07:00
404oopsandClaude Opus 5.5 0ce6b0646a perf(metering): stop releases from churning the reservation version
Every release bumped the balance version, so an account's own short-lived
holds (each realtime session probes one and releases it at once) could
keep its other reservations reading a stale version until they were
refused. The usage a hold stands for already bumps the version when it's
recorded, before the hold is released, and a release without usage
leaves the balance as it was, so releases no longer bump it.

The admission read also uses the cached add-ons record when it shows no
purchased credit left, which can only understate the balance; it reads
consistently only while credit remains.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-05 10:23:44 -07:00
404oopsandClaude Opus 5.5 6b5c4f3d9e fix(metering): refuse a reservation whose balance never holds still
A reservation that found the balance changed three times in a row used
to skip the version check on its fourth attempt, which brought back the
race the check closes; an account could provoke that itself. It now
waits a short randomized time between attempts and refuses after five.

A missing version key now starts from a random value, so a version read
before the key expired can't match its successor. Credit grants,
allowance changes, manual usage corrections and a usage write that
fails partway also bump the version, and the store refuses an amount
it can't hold instead of storing a negative hold.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-05 10:23:44 -07:00
404oopsandClaude Opus 5.5 d6fdc5f268 fix(metering): reserve AI credit only when it fits, in one step
`reserveAiCredits` checked the balance and then took an unconditional
hold, so concurrent requests could all pass the check before any hold
was visible; two 16.2M µ¢ holds were admitted against a 20M µ¢ balance.

The hold store now takes a hold only if it fits beside the live holds,
in one Lua script on the actor's hold key. A per-user version, bumped
when usage is recorded and when a hold is released, lets the script
refuse a balance read that a settlement has since overtaken; the
service reads the balance again and retries, and skips the version
check on its last attempt rather than refuse an account whose balance
keeps moving. Both keys share the actor's hash tag, so the script runs
on Redis Cluster. The balance read for this check reads purchased
credit consistently.

`reserveCreditsIfAffordable` carries this through the service, and the
AI facade calls it once with the cost factor applied. `reserveCredits`
keeps its unconditional semantics. When the cache is unreachable, the
balance alone decides and nothing is held, as before.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-05 10:23:44 -07:00
404oopsandClaude Opus 5.5 4f3f946941 fix(realtime): judge a refusal by the plan it was decided on
A plan or funds refusal was classified by a plan lookup made after the
decision. A fallback plan is cached for only a few seconds, so when it
ran out in between, the refusal was judged against the recovered plan
and still ended the session with a terminal 1008. The plan is now also
checked just before each decision, and a refusal is retryable if either
check found a fallback.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-05 10:23:43 -07:00
404oopsandClaude Opus 5.5 4e36672b6b test(puter-js): fail credential lookups until the relay hits one
The reconnect test made the next credential lookup fail once, but the
SDK's own socket.io connection could take that failure before the
relay's reconnect attempt did, so the relay never saw a failed lookup
and the test failed in CI. Lookups now fail until the relay has refused
an attempt on one, then recover.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-05 10:23:43 -07:00
404oopsandClaude Opus 5.5 6b0b530ab1 fix(realtime): retry instead of refusing when the plan lookup fails
When the billing lookup failed, metering answered with a provisional
fallback plan, so the relay refused the session with
`subscription_required` or, against the fallback's allowance,
`insufficient_funds`, both terminal 1008 closes, and the SDK showed the
upgrade prompt to a paying account. A plan or funds refusal decided on a
provisional plan now sends `internal_error` and closes with 1011, at
connection and mid-session, so the client retries once the lookup
recovers.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-05 10:23:43 -07:00
404oopsandClaude Opus 5.5 68b8f341e9 test(realtime): cover a revoked session credential
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-05 10:23:43 -07:00
404oopsandClaude Opus 5.5 c3756d3ac3 fix(realtime): tell transient server failures apart from bad credentials
A credential lookup that threw (a database or cache outage) was treated
as no actor, so the session got `invalid_api_key` and a 1008 close. That
is terminal for the SDK, which then ended an established conversation
that only needed to reconnect. A failed lookup now gets `internal_error`
and closes with 1011, which the SDK retries; missing, invalid and
revoked credentials keep `invalid_api_key` and 1008. Nothing is cached
for the failed lookup, and the cause is logged server-side only.

A session whose usage records pile up behind metering now closes with
1013 instead of 1008, still with `rate_limit_exceeded`. Queued usage is
still recorded and its holds released. An unexpected setup failure now
sends `internal_error` before its 1011 close.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-05 10:23:43 -07:00
404oopsandClaude Opus 5.5 0c927ac5a4 fix(realtime): listen for client socket errors before refusing a session
A session refused while the server drains returned before its client
error and close listeners were registered, so a frame that errored the
socket during the close handshake (an oversized one, for example)
emitted an unhandled `error` and ended the process. The listeners now
go on as soon as the session exists, ahead of every refusal.

The 404 answer to an upgrade for another host also ends a raw socket
that has no error listener once Node hands it over; it now has one.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-05 10:23:42 -07:00
Neal Shah 64c3b3c0ce subdomain and worker recipes complex, writing full stack applications with both (#4206) 2026-11-05 21:33:21 +07:00
Reynaldi Chernando e9a4c7a461 ai docs cleanup (#4504)
* ai docs cleanup

* fixes
2026-11-05 19:15:32 +07:00
Filip Kujundžić be9cd9eb89 feat(ai): add GPT Image 2.6 and default to Flare 2026-11-05 11:13:43 +01:00
Daniel Salazar 8b64cc5076 docs(notifications): recipes and format pass for dismissal, priority, buttons and schedule updates (#4502)
- dismiss.md is the one place that explains closing a notification on other
  devices; on/onNotification/push link to it instead of repeating it.
- Pages follow the house format: section order, error tables, playground
  examples for dismiss() and markShown(), sidebar and index listings.
- updateSchedule.md describes what a developer sees instead of internals.
- New recipes: mark notifications as read, incoming calls (high priority,
  short ttl, buttons), unread counts on the app icon.
- Existing recipes move reminders, snoozes and recurring summaries with
  updateSchedule() instead of cancel-and-recreate; the buttons recipe follows
  the recipe format.
2026-11-05 00:32:53 -07:00
Daniel Salazar d3869b7846 feat(notifications): dismissal across devices, high priority, buttons, schedule updates, docs fixes (#4501)
- Docs: status(), browser limits, events worker fetch/ack, update() across
  pages, stored-notification retries, device removal, push delivery, queue
  coalescing, existing service workers and missing error codes match the code.
- puter.notifications.markShown(uid) / dismiss(uid).
- Dismissals reach the app's live feed (on('dismiss')); pages close the
  notification on screen, and a later page load closes ones already dismissed.
  The desktop closes its own copies on notif.ack.
- Live notification postings are forwarded to sessions in other regions.
- notify({ priority: 'high' }).
- onPush() results accept requireInteraction and actions; clicks carry action.
- replaced reaches service-worker onPush() handlers.
- puter.events.updateSchedule(scheduleId, changes), with the invoker
  re-checking a schedule run's guard right before it is sent.
2026-11-05 00:17:27 -07:00
Daniel Salazar 91230697cd fix(backend): shutdown hooks don't skip each other, and final flushes wait for in-flight work (#4499) (#4500)
A throwing prepare/shutdown hook stopped the loop, so shutdown() skipped
closeAllConnections and every later hook, including the final metering
flush; each hook now runs and failures are logged. Broadcast, events
forwarding and share digests joined nothing already in flight and could
drop what was queued behind it; their final flushes now wait for it, ship
the tail, and drain once more at shutdown. Local worker disposal and the
OpenAI image metering call are awaited. settleWithin and
FINAL_FLUSH_TIMEOUT_MS bound each final flush.
2026-11-04 21:47:35 -07:00
Daniel Salazar 56e4856518 feat(backend): drain-start hooks run concurrently and can hold the listener open (#4498)
The listener closes once every onServerDrainStart hook settles, and the
drain window now starts at the signal, so time a hook spends holding the
listener open counts against drainMs instead of extending shutdown. A
failing hook no longer skips the others.
2026-11-04 19:40:54 -07:00
Reynaldi Chernando 8acd73675c use gpt 6 luna as example in docs (#4497) 2026-11-05 08:20:12 +07:00
Nariman Jelveh fc4af97885 fix(gui): the custom domain empty state holds its add button
With no domains, the only way on was the add button in the footer, which
the full-page popup pins to the bottom edge, far from the empty state the
eye lands on. The button now sits in the empty state under its hint, and
the footer keeps only Cancel until there's a domain to list.
2026-11-04 17:08:06 -07:00
Nariman Jelveh 7cec710014 feat(gui): redesign the custom domain dialog, full page in its popup (#4496)
* feat(gui): redesign the custom domain dialog, full page in its popup

- Domains list as cards with a status badge, trash icon, and inline
  Cancel/Confirm for remove and move
- DNS records as cards with copy buttons that confirm with a check
- Status card on the records step; a green check once the domain serves
  the site, after which the dialog closes
- Spinners on the button that's working, skeleton while loading, empty
  and unavailable states
- Pasted URLs are trimmed to their hostname before adding
- In the attach-custom-domain popup the dialog fills the page, with the
  actions pinned to the bottom

* fix(gui): Escape backs out of removing the chosen custom domain

Escape already put back a list row's pending confirmation. On the records
step, it closed the dialog while Remove was asking to confirm; it now puts
the button back first, like the rows.

* fix(gui): each custom domain step opens scrolled to the top

Switching steps reset the scroll of the dialog's body, which only scrolls
when the dialog fills a popup. The floating modal scrolls itself, so a
step opened from far down the list started scrolled past its status card.

* fix(gui): keyboard focus stays in the custom domain dialog

Focus on a control that got hidden or disabled fell to the page behind the
dialog, so Tab started over from there. Switching steps now focuses the
dialog, backing out of a row's confirmation returns to the button that
asked, a request gives focus back to the button that started it, and
removing a row moves focus to the next one.

* fix(gui): a removed custom domain row takes no input as it fades

Its buttons came back on once the delete finished, so a second click in
the fade sent the delete again, and Cancel brought back Use for a domain
that no longer exists. The row is inert until it's gone.

* fix(gui): DNS record copy buttons work without the clipboard API

On an origin with no navigator.clipboard (a Puter served over plain http)
or when the browser refuses the write, the copy buttons did nothing. They
now select the value and try the legacy copy, like the dashboard's form
dialog, and leave it selected to copy by hand if that fails too.

* fix(gui): custom domain rows keep the icon beside the name on phones

The name was sized to the row less 46px for the icon and gap, but the icon
is 36px wide with its border, so the row overflowed by 2px and every name
dropped below its icon. Only the actions wrap now; the name takes the rest
of the first line.

* fix(gui): hostnames in the custom domain dialog wrap whole

Every bold hostname broke at any letter, so one that would fit on the
next line was split mid-word at the end of this one ("puter.lo / calhost").
It now moves down whole and breaks only when it's wider than the line.

* fix(gui): readable Remove and Confirm buttons in dark mode

The red fill under their white labels used the danger text color, which
dark mode lightens to #f87171: 2.8:1 against white. Fills now use their
own token that stays #dc2626 (4.8:1); light mode is unchanged.

* fix(gui): the switch-to-www link shows when it's working

The link that switches a root domain to www had no disabled or loading
style, so while its request ran it still looked clickable and showed
nothing, while every other control dimmed. It now dims like them when
waiting and shows a spinner when it's the one working.
2026-11-04 16:45:56 -07:00
Daniel Salazar 48cd4ea355 fix: oidc toggle (#4494) 2026-11-04 13:13:15 -07:00
Neal ShahandClaude Opus 5.5 a110be0340 feat(gui): remove a custom domain from the attach dialog (#4493)
Each domain in the list gets a Remove button, confirmed in place like Move,
and the records pane can remove the domain just added. A removed domain is
never handed back as the dialog's answer.

Also fixes two strings that went stale: the claim prompt (an active domain
can be claimed too now) and the redirect note (root domains get two A
records).

PUT-2338

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-04 13:23:04 -05:00
404oopsandClaude Fable 5.1 0128e8779d fix(ai): route per-breakpoint cache lifetimes through the Responses API
Chat Completions rejects `prompt_cache_breakpoint.ttl` whatever its
value, so a request whose content parts name a breakpoint lifetime is
handed to the Responses provider like a request-level `ttl: '12h'`. The
`/openai/v1/responses` translator keeps `prompt_cache_breakpoint` on
text, image and file parts instead of dropping it with the other unknown
fields.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-11-03 00:58:29 +01:00
404oopsandClaude Fable 5.1 89f070f7d0 fix(ai): meter OpenAI cache writes by lifetime
GPT-5.6 and later write prompt-cache entries with a 30m or 12h lifetime
and bill them at 1.25x and 2.5x input; every write was metered at the
30m rate. The OpenAI calculators now split `cache_write_tokens_details`
into `cache_write_tokens` (30m) and `cache_write_12h_tokens` (12h), the
GPT-5.6+ catalog carries the 12h rate, and `usageDetails` reports
`cacheWrite30mTokens` / `cacheWrite12hTokens` instead of labelling the
writes as 5m entries.

Callers pick the lifetime with `prompt_cache_options` ({ mode, ttl }) on
`puter.ai.chat`, `/openai/v1/responses` and `/openai/v1/chat/completions`.
The Chat Completions provider hands a 12h request to the Responses
provider, the only API that writes 12h entries. `prompt_cache_retention`
is forwarded on Chat Completions too, and the hyphenated `in-memory`
spelling maps to the `in_memory` value the upstreams accept.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-11-03 00:52:33 +01:00
759 changed files with 55139 additions and 20065 deletions

No files matched your search

@@ -53,7 +53,7 @@ jobs:
# step above fails; the tests skip themselves without the key.
- name: Run live realtime conversation tests
if: ${{ !cancelled() }}
run: npm run setupExtensions && (cd src/puter-js && npm run build) && npx vitest run --config src/puter-js/tests/api/vitest.config.ts src/puter-js/tests/api/realtime/convoLive.test.ts
run: npm run setupExtensions && (cd src/puter-js && npm run build) && npx vitest run --config src/puter-js/tests/api/vitest.config.ts src/puter-js/tests/api/realtime/realtimeLive.test.ts
env:
CI: 'true'
PUTER_TEST_AI_OPENAI_API_KEY: ${{ secrets.PUTER_TEST_AI_OPENAI_API_KEY }}
+6 -2
View File
@@ -176,7 +176,10 @@ jobs:
- name: Checkout repository
uses: actions/checkout@v7
# Missing when the PR leg failed; `coverage (pr)` already reports that.
- name: Download PR coverage
id: pr-coverage
continue-on-error: true
uses: actions/download-artifact@v8
with:
name: puterjs-coverage-pr
@@ -186,6 +189,7 @@ jobs:
# base run) — then report without the comparison column.
- name: Download base coverage
id: base-coverage
if: steps.pr-coverage.outcome == 'success'
continue-on-error: true
uses: actions/download-artifact@v8
with:
@@ -193,7 +197,7 @@ jobs:
path: coverage-base
- name: Report coverage on PR
if: steps.base-coverage.outcome == 'success'
if: steps.pr-coverage.outcome == 'success' && steps.base-coverage.outcome == 'success'
uses: davelosert/vitest-coverage-report-action@v2
with:
name: puter.js SDK
@@ -202,7 +206,7 @@ jobs:
json-summary-compare-path: coverage-base/coverage-summary.json
- name: Report coverage on PR (no base comparison)
if: steps.base-coverage.outcome != 'success'
if: steps.pr-coverage.outcome == 'success' && steps.base-coverage.outcome != 'success'
uses: davelosert/vitest-coverage-report-action@v2
with:
name: puter.js SDK
+31 -1
View File
@@ -159,13 +159,42 @@ The reference has two kinds of page:
An overview page answers "what is this API and is it what I need?", and a function page answers "how exactly does this call behave?". A change to one function usually only touches that function's page, so a new `kv.list()` option goes in `KV/list.md` without a matching update to `KV.md`. Don't copy a function's options, limits, or edge cases onto the overview page for completeness. Where a detail goes is a judgment call, not a hard rule: update the overview when a change affects how someone would describe the API as a whole.
When you add a page, add it to [src/docs/src/sidebar.js](src/docs/src/sidebar.js) under its area, or it won't show up in the navigation. When you add a runnable example, add its HTML to `src/docs/src/playground/examples/<slug>.html`, register the slug in [src/docs/src/examples.js](src/docs/src/examples.js), and link the code block to it by putting the slug after the language with a semicolon (` ```html;kv-set `).
When you add a page, add it to [src/docs/src/sidebar.js](src/docs/src/sidebar.js) under its area, or it won't show up in the navigation.
**Sidebar order.** Order the API areas in the sidebar by how often developers use them, most common first. Overview stays first and Objects stays last. Inside an area, order the pages by use too, and keep pages that make up one feature next to each other, such as `share()`, `unshare()`, `listShared()`, and `listSharedByMe()`. A group goes where its most-used page would go. A helper that only supports another function, such as `listModels()` for `chat()`, goes by its own use. Put create, list, get, update, and delete in that order, and constants such as `MAX_KEY_SIZE` last. The function list on the area's overview page uses the sidebar's order. When you add a runnable example, add its HTML to `src/docs/src/playground/examples/<slug>.html`, register the slug in [src/docs/src/examples.js](src/docs/src/examples.js), and link the code block to it by putting the slug after the language with a semicolon (` ```html;kv-set `).
### Function page layout
A function page opens with one sentence that says what the function does, in its own paragraph, such as "Given a prompt, generate an image using AI." Put any more detail in the paragraphs after it.
After the intro, a function page has these `##` sections, in this order:
1. Syntax
2. Parameters
3. Return value
4. Errors, if the function has any
5. Sections for specific topics, if the page needs them, with `## Model-specific features` last
6. Examples
[chat.md](src/docs/src/AI/chat.md) follows this layout.
- **Options as a table.** Document an options object as a table with Option, Type, and Description columns. Give each option its own row, even when two options go together, such as `width` and `height`. Order the rows by how often developers use them, most common first, without group rows. In chat.md that's the core options, then reasoning, tools, response handling, request control, and output.
- **Common options in the table, model-specific behavior in its own section.** A page whose function works with many models or providers, such as [chat.md](src/docs/src/AI/chat.md) and [txt2img.md](src/docs/src/AI/txt2img.md), splits its options this way:
- **The options table** under Parameters lists the options that work with every model, and describes each one the way it works for every model.
- **`## Model-specific features`**, the last section before Examples, covers everything else. It has a `###` for each model family or provider, named after it, such as "OpenAI models" or "Cloudflare models". Under it go the options only some models accept, and the common options a model handles differently, such as a narrower range, other allowed values, or an option it ignores.
- **Write there only what's different.** A `###` lists an option only when that model or provider adds it or handles it differently. An option that works the same everywhere stays out, even if the provider supports it, and a model or provider with nothing different gets no `###`.
- **Model-specific features is the only place for model-specific details.** Every limit, format, allowed value, default, price, or quirk that applies to some models goes there, in that model's or provider's `###`, and nowhere else. The options table and topic sections (such as Image inputs or Video input) describe what's true for every model and link to Model-specific features for the rest. Don't add a table or sentence there that compares providers or repeats a model's limits. Each copy is another source of truth to keep in sync, and copies drift when a model changes.
- **Link the two.** Directly under the options table, put `Some models accept additional options or handle these options differently. See [Model-specific features](#model-specific-features).` A row whose option behaves differently on some models can also end with `See [Model-specific features](#model-specific-features).`
- **A long topic gets its own `##` section.** When explaining an option or feature takes more than a sentence or two, such as function calling or output dimensions, give it a section between Errors and Examples and link to it from the options table. This keeps the reference sections short.
- **Usage patterns are examples.** A way of using the API, such as stopping a stream, goes in a runnable example that the relevant section links to ("See the [stop a stream example](/playground/ai-chat-stop-stream/)."), not in a section of its own.
- **Each example has a `###` heading** under `## Examples`, so every example shows in the table of contents.
### Writing docs
These apply to reference pages and recipes alike.
- **Document the developer-facing side only.** The reader is building on top of puter.js, so cover what affects their code: signatures, defaults, return shapes, errors, limits, and behavior they can observe. Leave out internal workings (which service handles the call, storage layout, caching, retries) unless they change what the developer has to do. [rate-limits-and-quotas.md](src/docs/src/rate-limits-and-quotas.md) is the exception: it publishes every limit, including timeouts and caps that come from how the backend works.
- **Document Puter as it runs on puter.com.** The docs are for developers building on production Puter. Leave out behavior that only happens on a self-hosted or differently configured server, such as a provider that isn't set up there.
- **Describe the current state.** Docs aren't a changelog. Write how the API behaves now, without "now", "no longer", "existing code is unaffected", or other wording that compares it to an older version.
- **Verify before you document.** Run the calls you describe against a running Puter instead of inferring behavior from the source.
- **Write plainly.** Use the literal words a developer would say out loud, with contractions and everyday words. No idioms or figurative verbs ("walk away from something shared with you" → "remove your own access", "nothing to page through" → "without pagination"). No formal register ("present only while more pages remain" → "includes a `cursor` if there are more pages to load"). Prefer dev terms such as atomic, concurrent, and insertion order.
@@ -173,6 +202,7 @@ These apply to reference pages and recipes alike.
- **Describe behavior directly.** No quoted inner-voice phrases. Write "`isNew` is `true` when the person did not have access before", not "this tells 'I just gave this to someone' from 'they already had it'".
- **Keep references easy to follow.** Name what a list or code block belongs to in the sentence directly above it. Name a thing once and keep that name. Introduce an actor as "a user" before giving them a role: "A user can create a team. The user who creates the team becomes its owner."
- **Sentence mechanics.** Never start a sentence with inline code: write "To store data, use the [`set()`](/KV/set/) method." Link every inline mention of an API to its page, every time. No em dashes, and no colons or semicolons mid-sentence; a colon that introduces a code block is fine.
- **No `##` or `###` headings inside tabs.** The table of contents lists every `##` and `###` heading on the page, including the ones in a hidden tab (an `example-content` block switched by the `example-group` pills), so its links lead to content the reader can't see. Put the heading above the tabs, or use `####` inside a tab, which the table of contents skips.
- **Show the correct way.** No "don't" and no wrong-way-first examples, in recipes and playground examples alike. Mention a wrong approach only when developers already hit it in practice, and state how it fails as a fact: "`add()` reads a plain object as a path map, so the call rejects with …".
### Recipes
+1 -1
View File
@@ -40,7 +40,7 @@ The following have already been reviewed and determined **not to be vulnerabilit
- **SSRF via `secureFetch`.** Production routes outbound requests through an isolated proxy that has no access to internal/SSRF-sensitive resources.
- **Attacks that depend on guessing an `appInstanceID` or app UID.** These are random 128-bit secret values and are not considered guessable.
- **Apps invoking drivers, creating workers, or using KV.** Applications are intended to do this; worker permissions are scoped to the owning app. This is by design.
- **App metadata or app user-count "leaks".** This information is currently public by design. This covers **private apps** too: private apps are an unreleased, admin-only beta for paid listings in the Puter App Center. Their `index_url` and other metadata are not secret, the flag is not user-settable, and no production app relies on it. Reports that a private app's metadata is reachable through a sibling route (taskbar items, `/get-launch-apps`, `index_url` drift on the hosting gate, etc.) are normalization work, not vulnerabilities.
- **App metadata or app user-count "leaks".** This information is currently public by design. This covers **private apps** too: private apps are an unreleased, admin-only beta for paid listings in the Puter App Center. Their `index_url` and other metadata are not secret, the flag is not user-settable, and no production app relies on it. Reports that a private app's metadata is reachable through a sibling route (`/get-launch-apps`, `index_url` drift on the hosting gate, etc.) are normalization work, not vulnerabilities.
- **Worker hot-reload driven by a share recipient.** Sharing a worker's source file with write access is how you let a collaborator change that worker's code and have it deploy live. The redeploy running as the file owner, with the owner's worker credentials, is the intended behavior of that grant — the owner chose to hand out write access to executable code. If you do not want that, do not share the source file with write access.
- **Re-claiming a site or worker name its owner deleted.** A hosted site or worker name that its owner deletes is treated as abandoned by that owner. If one of their apps still points at it, whoever claims the name next serves that app's `index_url` and receives what the app is launched with, and a new app on the same origin may share the old one's identity. Guarding app identities against being recycled this way is ongoing hardening, not a security boundary, so new ways to re-claim an abandoned name, or to inherit an app's tokens or data through one, are not eligible.
- **Share-mode downgrades that do not cascade.** Demoting a delegate does not retroactively revoke the grants that delegate already issued downstream. Shares are independent grants once issued, not a live-evaluated chain. Revoking the downstream grant is a separate, supported action.
+1 -1
View File
@@ -1 +1 @@
FOLLOW ./AGENTS.md
FOLLOW @AGENTS.md
+365
View File
@@ -0,0 +1,365 @@
# Embedded app browser
`GET /embed/apps` on the deployment's main GUI origin renders the same app browser
as the dashboard's Apps tab, without the desktop or dashboard navigation.
It supports search, paging, saved folders, and saved ordering. It uses the same
installed-app and recommendation data as the dashboard, including the user's
removed recommendations. Editing, adding, reordering, renaming, and uninstalling
are disabled. Selecting an app opens it in a new browser tab at its own URL, the
same way the dashboard does, and the host page stays open. The app's token isn't
put in the URL: the app's SDK asks the embed for it once the tab loads, so the
embed must still be open then. If the iframe is removed first, the app falls back
to its normal sign-in. Apps that need the desktop (built-in and godmode apps,
private apps the user can't open, or a failed token request) open `/app/<name>`
on the GUI origin, cut off from the embed. Website shortcuts open their external
destination with no opener.
The embed follows the OS's light or dark setting. A host with a fixed theme adds
`theme=dark` or `theme=light` to the fragment (`#user=<uuid>&theme=dark`), since
Chromium doesn't pass an iframe's `color-scheme` on to the page inside it.
Apps opened from the embed carry `utm_source=puter.com&utm_medium=referral&utm_campaign=app_browser_embed`;
the desktop and dashboard send `utm_campaign=desktop` and `utm_campaign=dashboard`.
## Session and framing
The embed shows the GUI session only to the user the host page is signed in as.
The host names that user's `uuid` (from `puter.auth.getUser()`) in the iframe
URL's fragment, as `/embed/apps#user=<uuid>`. The embed reads the session, asks
`/whoami` which user it belongs to, and shows the signed-out view unless the two
match. So a host that names no user, a malformed one, or a user other than the
session's, gets the signed-out view, and so does a session the API refuses. A
failed `/whoami` check shows the error state. The fragment never reaches the
server and can only narrow what the embed shows: naming the session's own user
gives the same view as a direct visit to the GUI. Changing the fragment of a
loaded embed reloads it.
The embed reads the existing GUI session from local storage on its own origin.
If that storage holds no session, the embed gets the session from the GUI origin's session cookie through
`/get-gui-token`. This matters in Safari, which gives a framed origin separate
local storage under each top-level origin, so even a sibling subdomain's iframe
can't see the GUI's stored token. The session cookie is still sent, because the
host is on the same site. The embed doesn't write that token back to storage. It
does not create accounts, show a login dialog, or accept a token from its parent.
Being signed in on a subdomain alone does not create a session on the main GUI
origin.
Without a session it can show, the embed shows the recommended apps (`RecommendedAppsService`)
that the server put in the page, and nothing else: no installed apps, folders, or
saved order, and no puter.js. Selecting one opens it at the same URL a signed-in
launch uses, with no opener and no token on offer, so the app signs in on its own.
Apps that need the desktop open `/app/<name>`. If the page carries no recommended
apps, or a load fails, the embed displays an unavailable/error state.
The route's `Content-Security-Policy: frame-ancestors` allows the GUI origin and
the embedding page's origin when it is exactly one label under `config.domain`
with the scheme and port from `config.origin`. Subdomains the server answers
itself (`api`, `dav`, `js`, `www`, the native-app hosts, and the host of
`api_base_url`) and the user-content hosting domains (`static_hosting_domain`,
`private_app_hosting_domain`, and their `_alt` variants) are refused. For
example, `https://puter.com` permits `https://spreadsheet.puter.com` but not
`https://api.puter.com`, and `http://puter.localhost:4100` permits
`http://spreadsheet.puter.localhost:4100` but not
`http://someone.site.puter.localhost:4100`. The embedding page is read from the
iframe request's referrer, so the host must not suppress it (the browser default
`strict-origin-when-cross-origin` is enough). All ancestors in a nested iframe
chain must be allowed. Other GUI routes retain `X-Frame-Options: SAMEORIGIN`.
The embed accepts no query parameters. Requests with a query string redirect to
the same embed path so SDK bootstrap parameters cannot override the session or API
origin. The host needs to allow the GUI origin in its own `frame-src` CSP if it
sets one. If sandboxing the iframe, allow scripts, same-origin storage, popups,
and popups to escape the sandbox.
## Host integration
A first-party app that signs in with puter.js can place `<puter-user-menu>` from
the SDK in its header instead (see `src/puter-js/src/ui/components.md`). It opens
this embed with the signed-in user named and closes it when the app's sign-in
changes. The rest of this section is for a host that builds the iframe itself.
The iframe can be shown whether or not the user is signed in. Create it when
“More apps” is opened, naming the signed-in user in its fragment, and remove it
on close so reopening loads current apps and preferences. Remove it when the
host's own sign-in changes too, such as on sign-out, so an open embed doesn't
keep the previous user. The host owns the modal and close control;
there is no parent messaging API and no app list or credential is sent to it.
The app browser fills its iframe and responds to its size. It shows a spinner until its apps load.
This example assumes `puterOrigin` comes from the host app's deployment
settings. Translate the button and frame labels using the host app's
localization system.
```html
<button id="more-apps" type="button">More apps</button>
<dialog id="apps-dialog" aria-label="More apps">
<button id="close-apps" type="button">Close</button>
<div id="apps-frame"></div>
</dialog>
<style>
#apps-dialog { padding: 12px; width: min(900px, 90vw); }
#apps-frame iframe { width: 100%; height: min(650px, 75vh); border: 0; }
</style>
<script type="module">
const puterOrigin = 'https://puter.com'; // Use this deployment's configured origin.
const dialog = document.querySelector('#apps-dialog');
const container = document.querySelector('#apps-frame');
const trigger = document.querySelector('#more-apps');
trigger.addEventListener('click', async () => {
const url = new URL('/embed/apps', puterOrigin);
// Signed out, the embed shows the recommended apps.
const user = puter.auth.isSignedIn() ? await puter.auth.getUser().catch(() => null) : null;
if (user) url.hash = `user=${encodeURIComponent(user.uuid)}`;
const frame = document.createElement('iframe');
frame.title = 'Your apps';
frame.src = url.href;
container.replaceChildren(frame);
dialog.showModal();
});
document.querySelector('#close-apps').addEventListener('click', () => dialog.close());
dialog.addEventListener('close', () => {
container.replaceChildren();
trigger.focus();
});
</script>
```
## Implementation
`createAppBrowser` in `src/gui/src/UI/Dashboard/AppBrowser.js` owns the shared UI
and data behavior; its `guestApps` option is the signed-out list. `TabApps.js`
injects desktop actions. `appsEmbed.js` supplies new-tab launching through
`launchAppInTab` (signed in) and `guestAppLaunchUrl` (signed out) in
`src/gui/src/helpers/appTabLaunch.js`, which build the same app URL as
`launch_app`, and loads only the embed entry, its SDK, and shared styles. `embedHostUser` in
`src/gui/src/helpers/embedHostUser.js` reads the host's user from the fragment, and
`embedHostTheme.js` beside it applies the host's theme.
The normal GUI webpack build emits `bundle.min.js`, `apps-embed.min.js`, and `feedback-embed.min.js`.
The `/embed/apps` route puts the recommended list in the page's config as
`guestApps`. No puter.js API or app-list endpoint changes are needed.
## Feedback dialog
`GET /embed/feedback` is the app feedback dialog (`puter.ui.showFeedbackDialog()`)
for a first-party page, with the same framing rules, query redirect, and
host-user binding as `/embed/apps`. It sends the feedback for the framing
page's origin, which the server reads from the referrer and pins with
`frame-ancestors`; opened top-level, it does nothing. Its page is transparent
so the dialog's own scrim covers the host.
puter.js uses it on a page one label under the GUI origin, other than the
subdomains the server refuses, when the page is signed in, framing it in a
modal `<dialog>` that stays hidden until the embed is ready. A session check that takes longer than 200ms shows a loading scrim
with a spinner in its place; Escape or a click on it cancels. The embed posts `{ msg: 'feedbackEmbed', state }` to its parent
(`loading`, then `ready` or `unavailable`) and finally
`{ msg: 'feedbackDialogClosed', sent }`. It reports `unavailable` without the
named user's session, or while that user's email still needs confirming, and
puter.js then uses the `/action/send-feedback` popup, which can sign in. So does
a frame that never answers, such as one the host's CSP blocks. `feedbackEmbed.js`
is the entry, sharing `embedSession` in `src/gui/src/helpers/embedSession.js`
with the app browser; `showFeedbackEmbed` in `src/puter-js/src/lib/guiEmbed.js`
is the host side.
## Sign-in and file pickers
`GET /embed/sign-in`, `/embed/show-open-file-picker`, `/embed/show-save-file-picker`
and `/embed/show-directory-picker` serve the same GUI popups as `/action/<action>`
for a first-party page, with the same framing rules, query redirect, and
`no-store` as `/embed/apps`. Any other spelling of the path (another case, a
trailing slash) redirects to it, since the shell boots the desktop for it. They render the normal GUI shell, which names the
framing page (read from the referrer, pinned with `frame-ancestors`) as
`gui_params.embed_host_origin`. The GUI then runs the popup boot unchanged, with
the framing page as `window.opener`, and `window.close()` asks the page to
remove the frame (`src/gui/src/helpers/popupFrame.js`). Without a framing page
to answer (opened top-level, or framed by a refused page) it does nothing. The
popup's parameters come from the fragment instead of the query: `msg_id`,
`options` and `request_auth`, plus `user` for a picker.
The frame posts `{ msg: 'puterPopupFrame', state }` to its parent: `loading` as
soon as the shell boots, `ready` once it shows a window or dialog, `unavailable`
when the page has to use the popup, `provider` when the user picks a sign-in
provider (below), and `closed` where a popup would close. Its
answers (`puter.token`, `fileOpenPicked`, `directoryPicked`, `fileSaved`, the
cancel messages, `sendMeFileData`) are the popup's.
puter.js uses them on a page one label under the GUI origin, other than the
subdomains the server refuses, unless the page is cross-origin isolated or in a
frame of another site (which `frame-ancestors` refuses too).
`showPopupFrame` in `src/puter-js/src/lib/guiEmbed.js` shows the frame in a box
the size of the popup window, over a scrim, hidden until `ready` and behind the
loading spinner after 200ms. Escape closes it, on the page or in the frame. One shows per popup, as each
popup has its own window name: a second picker request of the same kind
replaces the one showing, and a `signIn()` call made while a framed sign-in is
open settles with it. On
screens up to 600px wide the box fills the screen. A frame that is refused,
never answers, or reports `unavailable` falls back to the popup, opened through
a consent dialog when the click that asked for it has expired. A reload or navigation the frame
starts itself (logging out, a sign-out in another tab) names the frame as its
referrer, so the server refuses it; the page then shows its spinner and opens
the frame again, once per `ready`.
- **Sign-in** (`puter.auth.signIn()`) has no host-user binding: it is how the
page gets a user. The box has a close button, which rejects with
`auth_window_closed` as closing the popup does. Providers refuse to be
framed, so choosing one posts `{ state: 'provider', url }` with the
provider's start URL for this sign-in's `msg_id`, then `unavailable`. The
page opens the popup straight at that URL, once it checks the URL is the
GUI's `/auth/oidc/<provider>/start` for this `msg_id`, and the provider
returns it as this sign-in's popup. `attempt_temp_user_creation` keeps the popup, since
only the popup creates a temporary account.
- **Pickers** frame only for a signed-in page. The GUI reports `unavailable`
unless its session belongs to the user named in `user`, and the page then uses
the popup, which can sign in and switch accounts. The token the GUI sends
before a picker's answer isn't adopted, since it is for the page's own user.
Dismissing the loading scrim settles the picker as cancelled.
## Upgrade
`GET /embed/upgrade` is the deployment's upgrade dialog for a first-party page,
served like the popups above: the GUI shell with the same framing rules, query
redirect, exact-path redirect and `no-store`, naming the framing page as
`gui_params.embed_host_origin`. It runs only when framed by an allowed page.
puter.js frames it on a signed-in first-party page (the same pages as the
pickers) for `puter.ui.requestUpgrade(details)`, and for the Upgrade button of
the usage limit dialog a refused call shows there. Elsewhere both keep their
behavior: inside an app `requestUpgrade()` asks the desktop, and on any other
page the usage limit dialog opens the dashboard's upgrade page in a new tab.
The frame covers the page with no box or close button, and the GUI page is
transparent (`html.popup-frame-transparent`) so the dialog's own scrim covers
the host. The frame allows `payment` as well as `otp-credentials`. Escape on the
page is left to the dialog, since one there shouldn't drop a payment in
progress. Its fragment names `user` (the page's signed-in user) and, when the
refusal gave them, `reason` (`funds`, `subscription` or `storage`) and `method`.
The GUI reports `unavailable` unless its session belongs to `user`, the account
has no verification or password change waiting (which the frame couldn't be
closed from), and the deployment defines `window.UIUpgradeAccount` with
`UIUpgradeAccount.embeddable === true`. Otherwise it runs:
```js
new UIUpgradeAccount({ attribution: { appUid, reason, method }, onClose }).open_as_window();
```
`appUid` is the app the framing page's origin resolves to, never one the
fragment names. `open_as_window()` resolves once the dialog shows, and the GUI
then posts `ready`. While the page still hides the frame, which Chromium and
WebKit lay out at 0x0, the GUI posts `ready` first and opens the dialog once
the frame has a viewport, so a window it opens doesn't center on 0x0.
`onClose({ upgraded })` must run exactly once, when the
dialog closes or when it declines to open for the account; the GUI then posts
`{ msg: 'puterPopupFrame', state: 'closed', upgraded }` and the page removes
the frame. If `open_as_window()` rejects, the GUI posts `unavailable` instead. `requestUpgrade()` resolves `{ upgraded }`. A call made while the
frame shows settles with it rather than replacing it, and a call refused while
it shows still rejects but opens no usage limit dialog over it.
When the frame can't show the upgrade (refused, never ready, `unavailable`, or
no user to name), puter.js opens the dashboard's upgrade page in a new tab with
what was refused, through a consent dialog when the click has expired or the
tab is blocked, and `requestUpgrade()` resolves `{ upgraded: false }`.
## Top-up
`GET /embed/top-up` is the deployment's top-up dialog, where a user with a plan
buys add-on credit, served and framed like the upgrade: a transparent GUI page
covering the host with no box or close button, allowing `payment` and
`otp-credentials`, with Escape left to the dialog. Its fragment names `user`.
puter.js frames it for the **Add credits** item of `<puter-user-menu>`, which
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 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:
```js
new UITopUp({ onClose }).open();
```
`open()` resolves once the dialog has loaded the account and shows what it can
buy, and `onClose({ toppedUp })` must run exactly once, when the dialog closes
or when it declines to open for the account. The GUI then posts `{ msg: 'puterPopupFrame', state: 'closed', toppedUp }`
and the page removes the frame. When the frame can't show the top-up, puter.js
opens the dashboard's top-up in a new tab, as it does the upgrade.
While the top-up shows, a call refused for funds still rejects but opens no
usage limit dialog over it, and `requestUpgrade()` frames nothing over it: it
resolves `{ upgraded: false }` once the top-up closes.
## Email confirmation
`GET /embed/request-email-confirmation` walks a first-party page's user through
confirming their email, served like the upgrade: the GUI shell with the same
framing rules, redirects and `no-store`, run only when framed by an allowed
page. puter.js frames it on a signed-in first-party page for
`puter.ui.requestEmailConfirmation()`. Inside an app the desktop shows the same
windows over the app instead.
Like the upgrade, the frame covers the page with no box or close button, over a
transparent GUI page, and its fragment names `user`. Escape closes it, on the
page or on the save-account or code window. On a window, Escape closes that
window as its close button does, so a code already sent still answers. The GUI
reports `unavailable` unless its session belongs to `user` and the account has
no phone, card or password check waiting.
An email check is fine: the boot skips its own email gate for this action, so
the user gets one code window they can close.
The GUI then runs `ensureConfirmedEmail` (`src/gui/src/helpers/ensureConfirmedEmail.js`),
which the desktop's handler uses too: a temporary account gets the save-account
window first, then an unconfirmed email gets the code window, each at most
once. When the page's whoami already reads the email as confirmed,
`requestEmailConfirmation()` resolves `{ response: true }` without framing
anything, and a confirmation in the frame marks that whoami confirmed for the
calls after it. An email the GUI reads as confirmed shows nothing. Before
opening a window the GUI waits for the frame to have a viewport, as the upgrade
does. It then posts
`{ msg: 'puterPopupFrame', state: 'closed', confirmed }`, and
`requestEmailConfirmation()` resolves `{ response: confirmed }`, the field an
app reads from the desktop's answer. A call made while the frame shows settles
with it. A frame that is refused, never ready, or `unavailable` resolves
`{ response: false }`, since there's no popup to fall back to.
## Custom domains
`GET /embed/attach-custom-domain` is the custom domain dialog of
`puter.hosting.attach()`, the popup at `/action/attach-custom-domain`, served
like the upgrade: the GUI shell with the same framing rules, redirects and
`no-store`, run only when framed by an allowed page. puter.js frames it on a
signed-in first-party page (the same pages as the pickers).
The frame covers the page with no box or close button, over a transparent GUI
page, so the dialog floats over the host with its own scrim as it does on the
desktop. The frame allows `clipboard-write`, for the dialog's copy buttons, as
well as `otp-credentials`. Escape on the page is left to the dialog, which
doesn't close while a request is in flight. Its fragment names `user` (the
page's signed-in user), `subdomain` (the site to attach a domain to) and
`msg_id`.
The GUI reports `unavailable` unless its session belongs to `user` and the
account has no verification or password change waiting. It then runs the
popup's action unchanged, with the framing page as the requester the dialog
names: it posts `ready` once the dialog is on the page, answers
`{ msg: 'customDomainAttached', domain, original_msg_id }` once the dialog has
closed and its exit has played, and then posts `closed`. `domain` is the domain the user chose, or
null. `attach()` resolves it. A frame that closes without an answer, or a
loading scrim the user dismisses, resolves null.
A call made while the frame shows resolves null without replacing it, as a
second call does on the desktop. A frame that is refused, never ready, or
`unavailable` falls back to the popup, which can sign in, through a consent
dialog when the click has expired.
## Checks
Run the GUI component/browser tests (with the SDK bundle built and Playwright
Chromium installed), and the backend route tests:
```sh
npx vitest run --config src/gui/vitest.config.js src/gui/src/UI/Dashboard/AppBrowser src/feedbackEmbed
npx vitest run src/puter-js/src/lib/guiEmbed.test.js src/puter-js/src/modules/UI.showFeedbackDialog.test.js src/puter-js/src/modules/Auth.signInFrame.test.js src/puter-js/src/modules/UI.pickerFrame.test.js src/puter-js/src/modules/UI.requestUpgrade.test.js src/puter-js/src/modules/UI.showTopUp.test.js src/puter-js/src/modules/UI.attachCustomDomainFrame.test.js src/puter-js/src/lib/upgradePrompt.test.js src/puter-js/src/modules/UsageLimitDialog.upgrade.test.js
npx vitest run --config src/gui/vitest.config.js src/gui/src/helpers/popupFrame.test.js
npx vitest run --config src/backend/vitest.config.ts src/backend/server.test.ts
```
+7 -6
View File
@@ -1,6 +1,6 @@
# Browser push client
Puter's desktop shows pushes through `/sw.js`. Core registers it, and shows Settings → Notifications, only when the `pushEnabled` gui param is `true`; core never sets it. A backend extension that delivers pushes sets it with `services.homepage.setGuiParam('pushEnabled', true)` and can load its own code into the worker with `services.homepage.registerServiceWorkerScript(path)`.
Puter's desktop shows pushes through `/sw.js`. Core shows Settings → Notifications only when the `pushEnabled` gui param is `true`; core never sets it. The worker is registered only when push is turned on in the browser, and a load removes one left without a subscription. A backend extension that delivers pushes sets it with `services.homepage.setGuiParam('pushEnabled', true)` and can load its own code into the worker with `services.homepage.registerServiceWorkerScript(path)`.
Core subscribes the browser to a push service only when the server also publishes `pushWebPushKey` (see [Built-in Web Push client](#built-in-web-push-client)), and it has no `/push/*` routes of its own. The device, app, preference and subscription endpoints below come from that extension. On a deployment without one, such as most self-hosted servers, they answer core's plain 404 (`code: 'not_found'`), which `puter.notifications` reports as `push_unavailable` and the Notifications tab shows as unavailable. A device the extension can't find is `device_not_found`.
@@ -22,12 +22,13 @@ When the browser replaces the subscription (`pushsubscriptionchange`), `sw.js` p
Before a notification is pushed, the server asks the open clients whether they received it live. It sends `notif.receipt` with `{ uid }` on the user's sockets for the app that sent it, or on the desktop's sockets for Puter's own notifications. The SDK remembers the uids its page received through `onNotification()`, `onPush()` or the desktop's feed, and answers once its page has that notification, or with `{ received: false }` when it never gets it. The server waits up to 5 seconds (`notificationAckTimeoutMs`).
An answer carries `visibilityState`, `focused` and `showsOwn`, the last being whether the page shows the notification itself. A website page shows it itself when it is hidden or unfocused, has an `onPush()` handler and notification permission, and no other tab of the same site is focused. Inside the desktop, the desktop shows it, and an app's `onPush()` result is never shown as a browser notification.
An answer carries `visibilityState` and `focused` as they were when the page received the notification. Pages never show a browser notification themselves; pushes do.
- An answer from a page that is visible and focused, or that shows the notification itself, stops the push.
- Otherwise the notification is pushed. A website's pushes go only to the browsers that subscribed through its own worker, never to Puter's `/sw.js`. An app inside the desktop pushes through `/sw.js`, which shows the app's name and icon.
- A hidden desktop tab shows no banner, so answers only from hidden desktop tabs don't stop a push of Puter's own notifications.
- A client that can't answer, such as an older puter.js, holds the push back while it is connected.
- An answer from a page that was visible and focused stops the push (`handled` on `notif.delivery.settled`). An older client that doesn't send `focused` counts while visible.
- Otherwise the notification is pushed, to every browser the user subscribed. A website's pushes go only to the browsers that subscribed through its own worker, never to Puter's `/sw.js`. An app inside the desktop pushes through `/sw.js`, which shows the app's name and icon.
- A client that can't answer, such as an older puter.js, doesn't hold the push back.
The ask reaches only the sockets in the asking region. So that other regions hear about a page too, a page that receives a notification live while visible and focused also sends `notif.handled` with `{ uid }` on the socket it came on. Core relays it as the node-local `notif.handled` event with the socket's user and app, at most 60 a minute per user; an extension that delivers pushes decides what to do with it.
## Registering
+36 -1
View File
@@ -259,6 +259,41 @@ describe('whoami extension — handleWhoami', () => {
expect(body.directories).toBeDefined();
});
it('leaves out taskbar items saved on the account', async () => {
const user = await seedUser();
await server.stores.user.update(user.id as number, {
taskbar_items: JSON.stringify([{ type: 'app', name: 'editor' }]),
});
const { res, captured } = makeRes();
await runWithContext(
{ actor: { user: { uuid: user.uuid, id: user.id as number } } },
() => handleWhoami(makeReq(), res),
);
expect(captured.body).not.toHaveProperty('taskbar_items');
});
it('leaves out a desktop background saved on the account', async () => {
const user = await seedUser();
await server.stores.user.update(user.id as number, {
desktop_bg_url: 'https://cdn.test/wallpaper.png',
desktop_bg_color: '#000000',
desktop_bg_fit: 'cover',
});
const { res, captured } = makeRes();
await runWithContext(
{ actor: { user: { uuid: user.uuid, id: user.id as number } } },
() => handleWhoami(makeReq(), res),
);
const body = captured.body as Record<string, unknown>;
expect(body).not.toHaveProperty('desktop_bg_url');
expect(body).not.toHaveProperty('desktop_bg_color');
expect(body).not.toHaveProperty('desktop_bg_fit');
});
it('reports the SMS-to-card fallback only once a send has opened it', async () => {
const user = await server.stores.user.create({
username: `wuser_${Math.random().toString(36).slice(2, 8)}`,
@@ -435,7 +470,7 @@ describe('whoami extension — handleWhoami', () => {
app: { uid: 'app-test-actor' },
}),
(_key, event) => {
event.details.directories = { '/injected': 'x' };
event.details.directories = { '/injected': 'uuid' };
},
);
+1 -1
View File
@@ -25,7 +25,7 @@ const APP_VISIBLE_LISTENER_KEYS: ReadonlySet<string> = new Set([
]);
export const handleWhoami = async (
_req: Request,
req: Request,
res: Response,
): Promise<void> => {
const actor = Context.get('actor');
@@ -318,3 +318,13 @@ describe('AbstractDatabaseClient — SQL generation', () => {
);
});
});
it('builds an insert for batchWrite and shares it with insert', async () => {
const client = new FixtureDatabaseClient([]);
const entry = client.insertEntry('widget', { name: "reader's", enabled: true });
expect(entry.values).toEqual(["reader's", true]);
expect(entry.statement).toContain('VALUES (?, ?)');
await client.insert('widget', { name: "reader's", enabled: true });
expect(client.writes).toEqual([{ query: entry.statement, params: entry.values }]);
});
+16 -7
View File
@@ -110,14 +110,23 @@ export class AbstractDatabaseClient extends PuterClient {
tableName: string,
data: Record<string, unknown>,
): Promise<WriteResult> {
const entry = this.insertEntry(tableName, data);
return this.write(
entry.statement + this.returningIdClause(),
entry.values,
);
}
/** An insert that can join other writes in a transaction. */
insertEntry(tableName: string, data: Record<string, unknown>): BatchEntry {
const cols = Object.keys(data);
const values = Object.values(data);
const sql =
`INSERT INTO ${this.quoteIdentifier(tableName)} ` +
`(${cols.map((c) => this.quoteIdentifier(c)).join(', ')}) ` +
`VALUES (${cols.map(() => '?').join(', ')})` +
this.returningIdClause();
return this.write(sql, values);
return {
statement:
`INSERT INTO ${this.quoteIdentifier(tableName)} ` +
`(${cols.map((c) => this.quoteIdentifier(c)).join(', ')}) ` +
`VALUES (${cols.map(() => '?').join(', ')})`,
values: Object.values(data),
};
}
/** Whether `read()` goes to a separate replica rather than the primary. */
+53 -12
View File
@@ -117,7 +117,7 @@ export type EventMap = {
model_used: string;
service_used: string;
intended_service: string;
model_details: {
model_details?: {
id: string;
provider: string;
input_cost_key: string;
@@ -200,6 +200,16 @@ export type EventMap = {
};
// ---- Auth / signup ----
/**
* Which signup methods are open, emitted via `emitAndWait` before every
* signup and whenever the GUI reads the provider list. A listener sets
* `oidcOnly` to refuse form and temp signups, leaving OIDC and team
* provisioning open; `message` is what a refused form signup is told.
*/
'puter.signup.policy': {
oidcOnly: boolean;
message: string | null;
};
'puter.signup.validate': {
allow: boolean;
email?: string;
@@ -410,7 +420,11 @@ export type EventMap = {
old_username: string;
new_username: string;
};
'user.email-changed': { user_id: number; new_email: string };
'user.email-changed': {
user_id: number;
old_email: string | null;
new_email: string;
};
/** An account was suspended, or its suspension lifted. Local events. */
'user.suspended': { userId: number };
'user.unsuspended': { userId: number };
@@ -546,6 +560,14 @@ export type EventMap = {
'kv.share.retired': { handles: string[]; userId: number };
// ---- Notifications ----
/** An app message was acknowledged after its state committed. */
'notif.acknowledged': {
userId: number;
uid: string;
type: string;
audience: string;
appUid: string;
};
/**
* A notification row exists. Emitted after the insert commits — nothing
* pushes a uid before there is a row to name — and carries the scope tuple
@@ -579,6 +601,8 @@ export type EventMap = {
value: Record<string, unknown>;
/** An earlier notification rewritten in place. */
updated?: true;
/** Replaced an earlier notification in its group. */
replaced?: true;
/** Names this one send, for a receipt asked about it. */
sendId: string;
/** The same `sendId` may be emitted again, as a delayed send is. */
@@ -616,6 +640,18 @@ export type EventMap = {
/** A peer region holds a socket for the user. */
peerRegions: boolean;
responders: NotifDeliveryResponder[];
/** A page here got it live while visible and focused. */
handled: boolean;
};
/**
* A page reported that it got a notification live while visible and
* focused. Node-local; `appUid` is the reporting socket's app, absent for
* the desktop.
*/
'notif.handled': {
userId: number;
appUid?: string;
uid: string;
};
// ---- Metering ----
@@ -841,6 +877,12 @@ export type EventMap = {
/** One access token was revoked; only its own connections should drop. */
'auth.access-token.revoked': { token_uid: string };
/** Same-cluster eviction for raw realtime WebSockets. */
'pubsub.realtime.auth-revoked': {
sessionUids?: string[];
tokenUid?: string;
};
/**
* A grant was withdrawn, so whatever was standing on it has to be settled
* rather than left to fail its next check.
@@ -1041,10 +1083,11 @@ export type EventKey = keyof EventMap & string;
// Generates a wildcard for every non-final dot-separated prefix of K.
export type WildcardPrefixes<K extends string> =
K extends `${infer Head}.${infer Tail}`
? | `${Head}.*`
| (Tail extends `${string}.${string}`
? `${Head}.${WildcardPrefixes<Tail>}`
: never)
?
| `${Head}.*`
| (Tail extends `${string}.${string}`
? `${Head}.${WildcardPrefixes<Tail>}`
: never)
: never;
export type ListenKey = EventKey | WildcardPrefixes<EventKey>;
@@ -1055,18 +1098,16 @@ export type MatchingEvents<P extends ListenKey> = P extends `${infer Prefix}.*`
/** Acked, not acked, no socket anywhere, or sockets only in a peer region. */
export type NotifDeliveryOutcome =
'received' | 'unreceived' | 'no-socket' | 'remote-only';
| 'received'
| 'unreceived'
| 'no-socket'
| 'remote-only';
/** One socket's receipt for a live notification. */
export interface NotifDeliveryResponder {
visibilityState: 'visible' | 'hidden' | 'unknown';
/** The page's window has focus. Absent from older clients. */
focused?: boolean;
/**
* The page shows its own browser notification while hidden or unfocused.
* Absent from older clients.
*/
showsOwn?: boolean;
}
export type EventMetadata = {
@@ -347,6 +347,46 @@ describe('DispatcherInvokeTransport with every connection busy', () => {
held[INVOKE_CONNECTIONS].answer();
await expect(after).resolves.toMatchObject({ status: 200 });
});
it('rechecks the guard once a connection frees, and drops a superseded call', async () => {
const { transport, held, answerAll } = await saturated();
let current = true;
const guard = vi.fn(async () => current);
const waiting = transport.send({ ...CALL, beforeSend: guard });
current = false;
held[0].answer();
await expect(waiting).resolves.toEqual({
status: null,
error: 'invocation superseded',
});
expect(guard).toHaveBeenCalledTimes(1);
expect(held).toHaveLength(INVOKE_CONNECTIONS);
await answerAll();
});
it('fails a call whose guard throws after the wait, and frees its slot', async () => {
const { transport, held, answerAll } = await saturated();
const waiting = transport.send({
...CALL,
beforeSend: async () => {
throw new Error('lease store down');
},
});
held[0].answer();
await expect(waiting).rejects.toThrow('lease store down');
expect(held).toHaveLength(INVOKE_CONNECTIONS);
await answerAll();
const after = transport.send(CALL);
await vi.waitFor(() =>
expect(held).toHaveLength(INVOKE_CONNECTIONS + 1),
);
held[INVOKE_CONNECTIONS].answer();
await expect(after).resolves.toMatchObject({ status: 200 });
});
});
describe('DispatcherInvokeTransport schedule lane', () => {
@@ -771,6 +811,138 @@ describe('DispatcherInvokeTransport batches', () => {
]);
});
it('leaves a call superseded while gathered out of the batch', async () => {
const { fetchImpl, batches, singles } = streamingFetch();
const transport = transportFor(fetchImpl, { batchWindowMs: 20 });
let current = true;
const sent = [
transport.send(CALL),
transport.send({ ...CALL, beforeSend: async () => current }),
transport.send({ ...CALL, script: 'evw-other' }),
];
current = false;
await vi.waitFor(() => expect(batches).toHaveLength(1));
expect(batches[0].body.calls.map((call) => call.script)).toEqual([
'evw-test',
'evw-other',
]);
await expect(sent[1]).resolves.toEqual({
status: null,
error: 'invocation superseded',
});
batches[0].answer({ i: 0, status: 200, handled: true });
batches[0].answer({ i: 1, status: 200, handled: true });
await expect(Promise.all([sent[0], sent[2]])).resolves.toEqual([
{ status: 200, handled: true },
{ status: 200, handled: true },
]);
expect(singles).toHaveLength(0);
});
it('sends nothing when every gathered call was superseded', async () => {
const fetchImpl = vi.fn(
stubFetch(200, { [EVENTS_HANDLED_HEADER]: '1' }),
);
const transport = transportFor(fetchImpl as unknown as FetchImpl);
const superseded = { ...CALL, beforeSend: async () => false };
await expect(
Promise.all([
transport.send(superseded),
transport.send(superseded),
]),
).resolves.toEqual([
{ status: null, error: 'invocation superseded' },
{ status: null, error: 'invocation superseded' },
]);
expect(fetchImpl).not.toHaveBeenCalled();
});
it('fails only the call whose guard throws at flush', async () => {
const { fetchImpl, batches, singles } = streamingFetch();
const transport = transportFor(fetchImpl);
const failing = transport.send({
...CALL,
beforeSend: async () => {
throw new Error('lease store down');
},
});
const kept = transport.send(CALL);
await expect(failing).rejects.toThrow('lease store down');
// One call left, so it goes alone.
await expect(kept).resolves.toEqual({ status: 200, handled: true });
expect(batches).toHaveLength(0);
expect(singles).toHaveLength(1);
});
it('rechecks the guard before resending a batch call on its own', async () => {
const urls: string[] = [];
let current = true;
const fetchImpl = (async (url: string) => {
urls.push(url);
if (url.endsWith(EVENTS_DISPATCH_BATCH_PATH)) {
// Superseded while the batch was out.
current = false;
return new Response('no-such-route', {
status: 404,
headers: {
[EVENTS_DISPATCH_ERROR_HEADER]: 'no-such-route',
},
});
}
return new Response(null, {
status: 200,
headers: { [EVENTS_HANDLED_HEADER]: '1' },
});
}) as unknown as FetchImpl;
const transport = transportFor(fetchImpl);
await expect(
Promise.all([
transport.send({ ...CALL, beforeSend: async () => current }),
transport.send(CALL),
]),
).resolves.toEqual([
{ status: null, error: 'invocation superseded' },
{ status: 200, handled: true },
]);
expect(urls.map((url) => new URL(url).pathname)).toEqual([
EVENTS_DISPATCH_BATCH_PATH,
EVENTS_DISPATCH_PATH,
]);
});
it('answers a schedule run superseded in the batch as the early check does', async () => {
const { fetchImpl, batches } = streamingFetch();
const client = new EventsWorkerInvokerClient({
events: { invokeTimeoutMs: 5_000 },
} as unknown as IConfig);
client.setTransport(transportFor(fetchImpl, { batchWindowMs: 20 }));
let current = true;
const guard = vi.fn(async () => current);
const run = client.invoke(REQUEST, {
lane: 'schedule',
beforeSend: guard,
});
const other = client.invoke(REQUEST);
const another = client.invoke(REQUEST);
await vi.waitFor(() => expect(guard).toHaveBeenCalledTimes(1));
current = false;
await vi.waitFor(() => expect(batches).toHaveLength(1));
expect(batches[0].body.calls).toHaveLength(2);
await expect(run).resolves.toEqual(
await client.invoke(REQUEST, { beforeSend: async () => false }),
);
await expect(run).resolves.toMatchObject({
outcome: 'unavailable',
error: 'invocation superseded',
});
batches[0].answer({ i: 0, status: 200, handled: true });
batches[0].answer({ i: 1, status: 200, handled: true });
await Promise.all([other, another]);
});
it('builds each body when the batch goes out', async () => {
const { fetchImpl, batches } = streamingFetch();
const transport = transportFor(fetchImpl);
@@ -827,6 +999,26 @@ describe('DispatcherInvokeTransport batches', () => {
});
describe('EventsWorkerInvokerClient invoke options', () => {
it('does not send a superseded invocation', async () => {
const client = makeClient();
const send = vi.fn(async () => ({ status: 200, handled: true }));
client.setTransport({ send });
const result = await client.invoke(REQUEST, { beforeSend: async () => false });
expect(result.outcome).toBe('unavailable');
expect(send).not.toHaveBeenCalled();
});
it('rechecks before resending after a deployment', async () => {
const client = makeClient();
let current = true;
const send = vi.fn(async () => ({ status: null, dispatchReason: 'missing' }));
client.setTransport({ send });
client.setMissHandler(async () => { current = false; return 'deployed'; });
const result = await client.invoke(REQUEST, { beforeSend: async () => current });
expect(result.outcome).toBe('unavailable');
expect(send).toHaveBeenCalledTimes(1);
});
it('stamps the event as each attempt goes out', async () => {
const bodies: string[] = [];
const client = makeClient();
@@ -282,6 +282,11 @@ export interface EventsInvokeCall {
* connection first, so a send time stamped into it is the real one.
*/
render?: () => string;
/**
* Rechecked by a transport that waits before sending; false drops the call
* with {@link supersededAnswer}.
*/
beforeSend?: () => Promise<boolean>;
}
/** What one attempt at delivering an invocation came back with. */
@@ -334,6 +339,8 @@ export interface WorkerInvokeResult {
/** How one invocation is sent. */
export interface WorkerInvokeOptions {
lane?: InvokeLane;
/** Rechecked before each send, including a resend after deployment. */
beforeSend?: () => Promise<boolean>;
/** Applied to the event as each attempt is sent. */
stampEvent?: (event: unknown) => unknown;
}
@@ -341,6 +348,12 @@ export interface WorkerInvokeOptions {
const NO_TRANSPORT =
'no events dispatcher configured (url and internal secret)';
/** What a call whose `beforeSend` said no answers instead of being sent. */
const supersededAnswer = (): EventsInvokeAnswer => ({
status: null,
error: 'invocation superseded',
});
export class EventsWorkerInvokerClient extends PuterClient {
/** Set only where invocations do not leave the process — local development. */
#transport: EventsInvokeTransport | null = null;
@@ -395,11 +408,13 @@ export class EventsWorkerInvokerClient extends PuterClient {
const margin = Math.min(EVENTS_DEADLINE_MARGIN_MS, timeoutMs / 2);
const deadline =
Date.now() + timeoutMs * EVENTS_WORKER_LEASE_FACTOR - margin;
const send = (
const send = async (
deployed: boolean,
sendTimeoutMs = timeoutMs,
): Promise<EventsInvokeAnswer> =>
transport.send({
): Promise<EventsInvokeAnswer> => {
if (options.beforeSend && !(await options.beforeSend()))
return supersededAnswer();
return transport.send({
script: request.script,
appUid: request.appUid,
...(request.holder ? { holder: request.holder } : {}),
@@ -409,7 +424,11 @@ export class EventsWorkerInvokerClient extends PuterClient {
...(deployed ? { deployed: true } : {}),
...(options.lane ? { lane: options.lane } : {}),
...(stampEvent ? { render } : {}),
...(options.beforeSend
? { beforeSend: options.beforeSend }
: {}),
});
};
// A send may wait for a connection for half its timeout before the
// run's own timeout starts, so it is given what is left divided by that.
@@ -534,6 +553,8 @@ export class EventsWorkerInvokerClient extends PuterClient {
interface BatchedCall {
call: EventsInvokeCall;
resolve: (answer: EventsInvokeAnswer) => void;
/** For a `beforeSend` that threw. */
reject: (err: unknown) => void;
/** When its wait for a connection began, for what is left of it. */
waitingSince: number;
}
@@ -604,9 +625,14 @@ export class DispatcherInvokeTransport implements EventsInvokeTransport {
error: 'no free connection to the events dispatcher',
};
try {
if (this.#batchSize === 1) return await this.#sendOne(call);
return await new Promise<EventsInvokeAnswer>((resolve) => {
this.#batch.push({ call, resolve, waitingSince });
if (this.#batchSize === 1) {
// The wait for a connection may have outlived the call.
if (call.beforeSend && !(await call.beforeSend()))
return supersededAnswer();
return await this.#sendOne(call);
}
return await new Promise<EventsInvokeAnswer>((resolve, reject) => {
this.#batch.push({ call, resolve, reject, waitingSince });
if (this.#batch.length >= this.#batchSize) this.#flush();
else
this.#batchTimer ??= setTimeout(
@@ -626,6 +652,12 @@ export class DispatcherInvokeTransport implements EventsInvokeTransport {
const batch = this.#batch;
this.#batch = [];
if (batch.length === 0) return;
if (batch.some(({ call }) => call.beforeSend))
void this.#sendStillCurrent(batch);
else this.#sendGathered(batch);
}
#sendGathered(batch: BatchedCall[]): void {
if (batch.length === 1 || Date.now() < this.#batchUnsupportedUntil) {
for (const { call, resolve } of batch)
void this.#sendOne(call).then(resolve);
@@ -634,6 +666,26 @@ export class DispatcherInvokeTransport implements EventsInvokeTransport {
void this.#sendBatch(batch);
}
/** Drops calls superseded while they were gathered, then sends the rest. */
async #sendStillCurrent(batch: BatchedCall[]): Promise<void> {
const checked = await Promise.all(
batch.map(async (entry) => {
if (!entry.call.beforeSend) return entry;
try {
if (await entry.call.beforeSend()) return entry;
entry.resolve(supersededAnswer());
} catch (err) {
entry.reject(err);
}
return null;
}),
);
const current = checked.filter(
(entry): entry is BatchedCall => entry !== null,
);
if (current.length > 0) this.#sendGathered(current);
}
/** One call on the single route. */
async #sendOne(call: EventsInvokeCall): Promise<EventsInvokeAnswer> {
try {
@@ -688,13 +740,15 @@ export class DispatcherInvokeTransport implements EventsInvokeTransport {
let open = batch.length;
const answered = batch.map(() => false);
const timers: ReturnType<typeof setTimeout>[] = [];
const settle = (i: number, answer: EventsInvokeAnswer): void => {
const finish = (i: number, done: (entry: BatchedCall) => void) => {
if (answered[i]) return;
answered[i] = true;
clearTimeout(timers[i]);
batch[i].resolve(answer);
done(batch[i]);
if (--open === 0) hangUp.abort();
};
const settle = (i: number, answer: EventsInvokeAnswer): void =>
finish(i, (entry) => entry.resolve(answer));
const settleRest = (answer: EventsInvokeAnswer): void => {
for (let i = 0; i < batch.length; i++) settle(i, answer);
};
@@ -777,8 +831,22 @@ export class DispatcherInvokeTransport implements EventsInvokeTransport {
this.#batchUnsupportedUntil =
Date.now() + BATCH_UNSUPPORTED_RETRY_MS;
batch.forEach(({ call }, i) => {
if (!answered[i])
if (answered[i]) return;
const { beforeSend } = call;
if (!beforeSend) {
void this.#sendOne(call).then((a) => settle(i, a));
return;
}
// The batch round trip may have outlived the call.
void (async () => {
try {
if (!(await beforeSend()))
return settle(i, supersededAnswer());
} catch (err) {
return finish(i, (entry) => entry.reject(err));
}
settle(i, await this.#sendOne(call));
})();
});
return;
}
+73
View File
@@ -21,6 +21,8 @@
import { GetObjectCommand } from '@aws-sdk/client-s3';
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { existsSync } from 'node:fs';
import { createServer, type Server } from 'node:http';
import type { AddressInfo } from 'node:net';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
@@ -200,6 +202,77 @@ describe('S3Client — remote endpoint configuration', () => {
});
});
describe('S3Client — bucket in another region', () => {
let server: Server;
let client: S3Client;
let signedRegions: string[];
// Answers like a bucket that lives in us-west-2: a request signed for any
// other region gets S3's 301 naming the bucket's region.
beforeEach(async () => {
signedRegions = [];
server = createServer((req, res) => {
const region =
/Credential=[^/]+\/\d{8}\/([^/]+)\//.exec(
req.headers.authorization ?? '',
)?.[1] ?? '';
signedRegions.push(region);
if (region !== 'us-west-2') {
res.writeHead(301, {
'content-type': 'application/xml',
'x-amz-bucket-region': 'us-west-2',
});
res.end(
'<?xml version="1.0" encoding="UTF-8"?><Error><Code>PermanentRedirect</Code><Message>The bucket you are attempting to access must be addressed using the specified endpoint.</Message></Error>',
);
return;
}
res.writeHead(200, {
'content-type': 'text/plain',
'content-length': '5',
});
res.end('hello');
});
await new Promise<void>((resolve) =>
server.listen(0, '127.0.0.1', resolve),
);
const { port } = server.address() as AddressInfo;
client = new S3Client({
port: 0,
extensions: [],
s3: {
s3Config: {
endpoint: `http://127.0.0.1:${port}`,
accessKeyId: 'fakeAccessKeyId',
secretAccessKey: 'fakeSecretAccessKey',
forcePathStyle: true,
},
},
} as unknown as IConfig);
await client.onServerStart();
});
afterEach(async () => {
await client.onServerShutdown();
server.closeAllConnections();
await new Promise<void>((resolve) => server.close(() => resolve()));
});
it("retries a read in the bucket's region when S3 redirects it", async () => {
const result = await client
.get('ap-northeast-2')
.send(
new GetObjectCommand({
Bucket: 'other-bucket',
Key: 'index.html',
}),
);
expect(await result.Body?.transformToString()).toBe('hello');
expect(signedRegions).toEqual(['ap-northeast-2', 'us-west-2']);
});
});
describe('S3Client — legacy storage migration', () => {
let client: S3Client;
let dir: string;
+3
View File
@@ -235,6 +235,9 @@ export class S3Client extends PuterClient {
const client = new AwsS3Client({
region,
// Rows without a stored region are read with the server's own, so
// retry where S3's 301 says the bucket actually lives.
followRegionRedirects: true,
requestStreamBufferSize: 32 * 1024,
requestHandler: new NodeHttpHandler({
socketTimeout: 5000,
@@ -52,8 +52,8 @@ const APP_READ_LIMIT = {
/**
* Unauthenticated icon serving; no actor to key on, so the bucket is the
* address — and an address is a NAT, a campus or a carrier gateway that can
* hold hundreds of desktops. Each desktop boot pulls the taskbar's icons at
* once, so a single burst from one network is already thousands of requests.
* hold hundreds of desktops. Each dashboard load pulls its app icons at once,
* so a single burst from one network is already thousands of requests.
* Responses are publicly cacheable and usually a redirect, so the ceiling is
* not protecting bandwidth; it is there so a client looping on a broken icon
* can't spin unbounded.
@@ -523,7 +523,7 @@ export class AppController extends PuterController {
};
// Icons are <img src> targets from the GUI (root) AND resolved via
// api_base_url in taskbar payloads. Register on both so either origin
// api_base_url in app summaries. Register on both so either origin
// works without a cross-subdomain redirect.
router.get(
'/app-icon/:app_uid',
@@ -1271,7 +1271,7 @@ describe('AppController app-icon rate limit', () => {
it('sizes the icon bucket for a whole network rather than one desktop', () => {
// Icons are unauthenticated `<img src>` targets, so the only key is
// the address — which one NAT shares across every desktop behind it,
// and each boot pulls the taskbar's icons in a burst.
// and each dashboard load pulls its app icons in a burst.
for (const path of ['/app-icon/:app_uid', '/app-icon/:app_uid/:size']) {
const route = router.routes.find(
(r) => r.method === 'get' && r.path === path,
@@ -1416,6 +1416,7 @@ describe('AuthController.handleLogin', () => {
is_user_token: true,
});
expect(body.user.directories).toBeTypeOf('object');
expect(body.user).not.toHaveProperty('taskbar_items');
});
// A deleted row still answering from cache reaches the session INSERT.
@@ -7467,6 +7468,11 @@ describe('AuthController user-protected mutations (validation paths)', () => {
{ expiresIn: '1h' },
);
const heard: Array<Record<string, unknown>> = [];
eventClient.on('user.email-changed', (_k, data) => {
heard.push(data as Record<string, unknown>);
});
const req = makeReq({});
(req as unknown as { query: Record<string, string> }).query = {
token: linkJwt,
@@ -7474,6 +7480,11 @@ describe('AuthController user-protected mutations (validation paths)', () => {
const res = makeRes();
await controller.handleChangeEmailConfirm(req, res);
expect(res.sent).toMatch(/Email changed successfully/);
expect(heard).toContainEqual({
user_id: user.id,
old_email: user.email ?? null,
new_email: newEmail,
});
const after = await server.stores.user.getById(user.id, {
force: true,
@@ -2647,6 +2647,7 @@ export class AuthController extends PuterController {
'user.email-changed' as never,
{
user_id: user.id,
old_email: user.email ?? null,
new_email: newEmail,
} as never,
{},
@@ -15,7 +15,6 @@ export interface OidcLoginContinuation {
embeddedInPopup: boolean;
openerOrigin: string | null;
messageId: string | null;
switchedToLogin: boolean;
}
interface OidcReturnDeps {
@@ -56,7 +55,6 @@ export function completeOidcLoginReturn(
data.userUuid !== user.uuid ||
typeof data.redirectUri !== 'string' ||
typeof data.embeddedInPopup !== 'boolean' ||
typeof data.switchedToLogin !== 'boolean' ||
(data.openerOrigin !== null && typeof data.openerOrigin !== 'string') ||
(data.messageId !== null && typeof data.messageId !== 'string')
) {
@@ -91,6 +89,5 @@ export function completeOidcLoginReturn(
),
);
}
if (data.switchedToLogin) append('oidc_switched', 'login');
return target;
}
@@ -25,13 +25,13 @@ const ALLOWED_SORT_BY = ['name', 'size', 'modified', 'type'];
const ALLOWED_SORT_ORDER = ['asc', 'desc'];
/**
* Folder view preference routes: an explorer window's layout and sort order,
* kept on the folder's fsentry.
* Folder view preference routes: layout and sort_by/sort_order, stored on the
* folder's fsentries row.
*/
/**
* Folder preference writes — layout, sort order. The GUI fires them on direct
* user action, so a per-minute ceiling well above human speed is enough to
* catch a stuck client.
* Desktop preference writes — layout, sort order. Each persists on every call,
* and the GUI fires them on direct user action, so a per-minute ceiling well
* above human speed is enough to catch a stuck client.
*/
const PREFERENCE_WRITE_LIMIT = {
scope: 'desktop-preference',
@@ -130,6 +130,20 @@ const callRoute = async (
});
};
describe('DesktopController routes', () => {
it('has no desktop background route', () => {
expect(
router.routes.some((r) => r.path === '/set-desktop-bg'),
).toBe(false);
});
it('has no taskbar items route', () => {
expect(
router.routes.some((r) => r.path === '/update-taskbar-items'),
).toBe(false);
});
});
// ── /set_layout ─────────────────────────────────────────────────────
describe('DesktopController POST /set_layout', () => {
@@ -501,6 +501,29 @@ describe('DriverController.#handleCall (via captured router)', () => {
expect(body.service.name).toBe('puter-kvstore');
});
it('treats null `args` as no arguments', async () => {
const actor = await makeUserActor();
await server.stores.permission.setFlatUserPerm(
actor.user!.id!,
'service:puter-subdomains:ii:puter-subdomains',
{
permission: 'service:puter-subdomains:ii:puter-subdomains',
deleted: false,
issuer_user_id: actor.user!.id!,
} as never,
);
const res = makeRes();
const req = makeReq(
{ interface: 'puter-subdomains', method: 'select', args: null },
actor,
);
await runWithContext({ actor }, () =>
routes['POST /call'](req, res as unknown as Response, () => {}),
);
expect((res.body as { success: boolean }).success).toBe(true);
});
it('pipes a stream-shaped result instead of JSON', async () => {
// Use an ephemeral driver registered onto the controller's bag.
const streamPayload = Buffer.from('hello-world');
@@ -276,8 +276,10 @@ export class DriverController extends PuterController {
interface: ifaceName,
method,
driver: driverName,
args = {},
args: rawArgs,
} = (req.body ?? {}) as Record<string, unknown>;
// Drivers read fields off `args`, so a null one counts as absent.
const args = rawArgs ?? {};
if (!ifaceName || typeof ifaceName !== 'string') {
throw new HttpError(400, 'Missing or invalid `interface`', {
@@ -236,6 +236,17 @@ export class EventsController extends PuterController {
});
}
@Post('/schedules/update', {
subdomain: 'api',
requireAuth: true,
allowAccessToken: true,
})
async updateSchedule(req: Request, res: Response): Promise<void> {
const actor = this.#requireActor(req);
const { scheduleId, changes } = bodyRecord(req);
res.json(await this.#schedules().update(actor, scheduleId, changes));
}
/**
* POST /events/schedules/remove — end one schedule. An id the caller does
* not hold reads as absent.
@@ -75,6 +75,7 @@ const fakeSchedules = () =>
total: 3,
})),
get: vi.fn(async () => view),
update: vi.fn(async () => view),
remove: vi.fn(async () => {}),
receivePeerChanges: vi.fn(async () => ({ applied: 2 })),
prepareSendAt: vi.fn(),
@@ -129,6 +130,10 @@ const routes: Array<[string, (response: Response) => Promise<void>]> = [
(r) =>
events.getSchedule(req({ params: { scheduleId: SCHEDULE_ID } }), r),
],
[
'POST /events/schedules/update',
(r) => events.updateSchedule(req({ body: { scheduleId: SCHEDULE_ID, changes: { every: '2h' } } }), r),
],
[
'POST /events/schedules/remove',
(r) =>
@@ -250,6 +255,16 @@ describe('with services.schedules', () => {
expect(sent.body).toEqual(view);
});
it('updates through update and answers its view', async () => {
const schedules = fakeSchedules();
setSchedules(schedules);
const { response, sent } = res();
const changes = { every: '2h' };
await events.updateSchedule(req({ body: { scheduleId: SCHEDULE_ID, changes } }), response);
expect(schedules.update).toHaveBeenCalledWith(actor, SCHEDULE_ID, changes);
expect(sent.body).toEqual(view);
});
it('removes through remove and answers {}', async () => {
const schedules = fakeSchedules();
setSchedules(schedules);
@@ -0,0 +1,77 @@
import type { Request, Response } from 'express';
import { describe, expect, it } from 'vitest';
import { makeActor } from '../../core/actor.js';
import type {
ScheduleServiceContract,
ScheduleView,
} from '../../core/schedules.js';
import { EventsController } from './EventsController.js';
const actor = makeActor({
user: { id: 1, uuid: 'user-1', username: 'user1' } as never,
});
const request = (body: unknown) => ({ actor, body }) as Request;
const controller = (schedules?: Pick<ScheduleServiceContract, 'update'>) =>
new EventsController(
{} as never,
{} as never,
{} as never,
{ schedules } as never,
{} as never,
);
describe('update schedule route contract', () => {
it('answers events_disabled when schedules are unavailable', async () => {
await expect(
controller().updateSchedule(
request({ scheduleId: 'id', changes: {} }),
{} as Response,
),
).rejects.toMatchObject({
legacyCode: 'events_disabled',
statusCode: 503,
noAlarm: true,
});
});
it('passes the actor, id and changes through and returns the updated view', async () => {
const view = {
scheduleId: 'id',
kind: 'recurring',
state: 'suspended',
} as ScheduleView;
const changes = { cron: '0 9 * * *', tz: 'UTC' };
const calls: unknown[][] = [];
const events = controller({
update: async (...args) => {
calls.push(args);
return view;
},
});
let sent: unknown;
await events.updateSchedule(request({ scheduleId: 'id', changes }), {
json: (value: unknown) => {
sent = value;
},
} as Response);
expect(calls).toEqual([[actor, 'id', changes]]);
expect(sent).toBe(view);
});
it('preserves validation and sending errors from the implementation', async () => {
const error = {
code: 'events_schedule_sending',
message: 'Already sending',
};
await expect(
controller({
update: async () => {
throw error;
},
}).updateSchedule(
request({ scheduleId: 'id', changes: {} }),
{} as Response,
),
).rejects.toBe(error);
});
});
@@ -5111,9 +5111,8 @@ describe('LegacyFSController.updateFsentryThumbnail', () => {
// ── GET /get-launch-apps ────────────────────────────────────────────
//
// `recent` is a launch-metadata producer: it returns `index_url` for
// apps the user has opened before. The taskbar happens to launch these
// by name (so AppDriver's hosted-backing guard applies), but the field
// is served regardless, so the guard is applied here too.
// apps the user has opened before. The field is served whoever reads it,
// so AppDriver's hosted-backing guard is applied here too.
describe('LegacyFSController GET /get-launch-apps', () => {
const hostedUrl = (sub: string) => `https://${sub}.site.puter.localhost/`;
@@ -401,11 +401,9 @@ export class LegacyFSController extends PuterController {
.filter(Boolean);
// Don't hand out an index_url whose puter-hosted backing is
// gone or reclaimed. The taskbar launches recents by name (so
// AppDriver's guard applies), but this list is a
// launch-metadata producer like any other — a future consumer
// reading index_url straight off it shouldn't inherit a stale
// origin.
// gone or reclaimed. This list is a launch-metadata producer
// like any other — a consumer reading index_url straight off
// it shouldn't inherit a stale origin.
let backingGoneFlags: boolean[];
try {
backingGoneFlags =
@@ -950,9 +948,7 @@ export class LegacyFSController extends PuterController {
// Trash, and `null`/`{}` when restoring. See
// `src/gui/src/helpers.js` → `window.move_items`.
newMetadata: (body.new_metadata ?? undefined) as
| Record<string, unknown>
| null
| undefined,
Record<string, unknown> | null | undefined,
});
const overwrittenEntry = replacedByMove(overwriteTarget, moved, name);
const oldPath = source.path;
@@ -1426,8 +1422,7 @@ export class LegacyFSController extends PuterController {
}
type SignedOrEmpty =
| (SignedFile & { path?: string })
| Record<string, never>;
(SignedFile & { path?: string }) | Record<string, never>;
const result: { signatures: SignedOrEmpty[]; token?: string } = {
signatures: [],
};
@@ -2054,10 +2049,7 @@ export class LegacyFSController extends PuterController {
const subjectRef = body.subject;
const appRef = body.app;
const mode = (getString(body, 'mode') ?? 'read') as
| 'see'
| 'list'
| 'read'
| 'write';
'see' | 'list' | 'read' | 'write';
if (!subjectRef || !appRef)
throw new HttpError(400, '`subject` and `app` are required', {
legacyCode: 'bad_request',
@@ -27,6 +27,7 @@ import type { Actor } from '../../core/actor.js';
import { PuterRouter } from '../../core/http/PuterRouter.js';
import { PuterServer } from '../../server.js';
import { setupTestServer } from '../../testUtil.js';
import { embedFrameAncestors, embedHostOrigin } from './HomepageController.js';
// ── Test harness ────────────────────────────────────────────────────
//
@@ -78,13 +79,11 @@ interface CapturedResponse {
statusCode: number;
body: unknown;
contentType?: string;
location?: string;
}
const makeReq = (init: {
params?: Record<string, unknown>;
path?: string;
originalUrl?: string;
actor?: Actor;
hostname?: string;
protocol?: string;
@@ -95,7 +94,6 @@ const makeReq = (init: {
headers: {},
params: init.params ?? {},
path: init.path ?? '/',
originalUrl: init.originalUrl ?? init.path ?? '/',
hostname: init.hostname ?? 'test.local',
protocol: init.protocol ?? 'http',
actor: init.actor,
@@ -133,11 +131,6 @@ const makeRes = () => {
captured.contentType = value;
return res;
}),
redirect: vi.fn((code: number, location: string) => {
captured.statusCode = code;
captured.location = location;
return res;
}),
};
return { res: res as unknown as Response, captured };
};
@@ -221,12 +214,14 @@ describe('HomepageController shell routes', () => {
expect(String(captured.body)).toMatch(/<!DOCTYPE html>/i);
});
it('serves the shell on /settings, /dashboard, /action, /@:username', async () => {
it('serves the shell on /settings, /dashboard, /desktop, /action, /@:username', async () => {
for (const path of [
'/settings',
'/settings/*splat',
'/dashboard',
'/dashboard/',
'/desktop',
'/desktop/',
'/action/*splat',
'/@:username',
]) {
@@ -236,18 +231,6 @@ describe('HomepageController shell routes', () => {
expect(String(captured.body)).toMatch(/<!DOCTYPE html>/i);
}
});
it('serves the shell on a path inside a public folder, /@:username/*splat', async () => {
const { res, captured } = makeRes();
await callRoute(
'get',
'/@:username/*splat',
makeReq({ path: '/@alice/photos/cat.png' }),
res,
);
expect(captured.statusCode).toBe(200);
expect(String(captured.body)).toMatch(/<!DOCTYPE html>/i);
});
});
// ── /app/:name ──────────────────────────────────────────────────────
@@ -377,6 +360,49 @@ describe('HomepageController GET /app/:name', () => {
expect(html).not.toContain('owner_user_id');
});
it('serves the same app shell under /desktop/app/:name', async () => {
const { userId } = await makeUser();
const name = `desk-${Math.random().toString(36).slice(2, 10)}`;
await server.stores.app.create(
{
name,
title: 'Desktop App',
description: 'opens on the desktop instead of the dashboard',
index_url: `https://example.com/${name}/`,
approved_for_listing: 1,
},
{ ownerUserId: userId },
);
const { res, captured } = makeRes();
await callRoute(
'get',
'/desktop/app/:name',
makeReq({ params: { name }, path: `/desktop/app/${name}` }),
res,
);
expect(captured.statusCode).toBe(200);
const html = String(captured.body);
expect(html).toMatch(/<!DOCTYPE html>/i);
expect(html).toContain('Desktop App');
});
it('returns 404 under /desktop/app/:name when the app is unknown', async () => {
const { res, captured } = makeRes();
await callRoute(
'get',
'/desktop/app/:name',
makeReq({
params: { name: 'no-such-app' },
path: '/desktop/app/no-such-app',
}),
res,
);
expect(captured.statusCode).toBe(404);
expect(String(captured.body)).toMatch(/<!DOCTYPE html>/i);
});
it('omits index_url even for a public app — the shell is not the launch authority', async () => {
const { userId } = await makeUser();
const name = `pub-${Math.random().toString(36).slice(2, 10)}`;
@@ -408,8 +434,8 @@ describe('HomepageController GET /app/:name', () => {
// -- app landing rate limit --
describe('HomepageController app landing rate limit', () => {
it('rate-limits /app/:name per network', () => {
for (const path of ['/app/:name']) {
it('rate-limits /app/:name and /desktop/app/:name per network', () => {
for (const path of ['/app/:name', '/desktop/app/:name']) {
const route = router.routes.find(
(r) => r.method === 'get' && r.path === path,
);
@@ -427,7 +453,7 @@ describe('HomepageController app landing rate limit', () => {
// ── /show/* ─────────────────────────────────────────────────────────
describe('HomepageController GET /show/*splat', () => {
it('serves the plain shell; the GUI opens the path itself', async () => {
it('emits a launch_app explorer call with the post-/show path', async () => {
const { res, captured } = makeRes();
await callRoute(
'get',
@@ -435,52 +461,13 @@ describe('HomepageController GET /show/*splat', () => {
makeReq({ path: '/show/alice/Documents' }),
res,
);
// The launch payload is JSON-serialized into the rendered HTML.
// We assert the rendered shell included the explorer launch hint
// pointing at the expected (slashed) path.
const html = String(captured.body);
expect(html).toMatch(/<!DOCTYPE html>/i);
// No boot-time launch hook: the one it used to carry named a GUI
// global that no longer exists, which stopped the GUI booting.
expect(html).not.toContain('launch_app');
});
});
// ── /desktop ────────────────────────────────────────────────────────
describe('HomepageController GET /desktop', () => {
it('redirects /desktop to the root, keeping the query', async () => {
for (const path of ['/desktop', '/desktop/']) {
const { res, captured } = makeRes();
await callRoute('get', path, makeReq({ path }), res);
expect(captured.statusCode).toBe(302);
expect(captured.location).toBe('/');
}
const { res, captured } = makeRes();
await callRoute(
'get',
'/desktop',
makeReq({
path: '/desktop',
originalUrl: '/desktop?shared=%2Falice%2Fx%2Fy&download=a',
}),
res,
);
expect(captured.location).toBe('/?shared=%2Falice%2Fx%2Fy&download=a');
});
it('redirects /desktop/app/:name to the app landing', async () => {
const { res, captured } = makeRes();
await callRoute(
'get',
'/desktop/app/:name',
makeReq({
params: { name: 'editor' },
path: '/desktop/app/editor',
originalUrl: '/desktop/app/editor?file=%2Falice%2Fa.txt',
}),
res,
);
expect(captured.statusCode).toBe(302);
expect(captured.location).toBe('/app/editor?file=%2Falice%2Fa.txt');
expect(html).toContain('launch_app');
expect(html).toContain('explorer');
expect(html).toContain('/alice/Documents');
});
});
@@ -543,3 +530,46 @@ describe('HomepageController GET /sw.js', () => {
expect(route?.options.subdomain).toBe('');
});
});
describe('embedFrameAncestors', () => {
const config = {
origin: 'https://example.test',
domain: 'example.test',
api_base_url: 'https://backend.example.test',
};
it('names a sibling subdomain that embeds the browser', () => {
expect(
embedFrameAncestors(config, 'https://sheets.example.test/doc/1'),
).toBe("'self' https://sheets.example.test");
});
it('refuses the configured API host even off the api label', () => {
expect(
embedFrameAncestors(config, 'https://backend.example.test/x'),
).toBe("'self'");
});
});
describe('embedHostOrigin', () => {
const config = {
origin: 'https://example.test',
domain: 'example.test',
api_base_url: 'https://backend.example.test',
static_hosting_domain: 'site.example.test',
};
it.each([
['https://sheets.example.test/doc/1', 'https://sheets.example.test'],
['https://backend.example.test/x', null],
['https://api.example.test/', null],
['https://someone.site.example.test/', null],
['https://a.sheets.example.test/', null],
['http://sheets.example.test/', null],
['https://example.test/', null],
['not a url', null],
[undefined, null],
])('%s frames as %s', (referer, expected) => {
expect(embedHostOrigin(config, referer)).toBe(expected);
});
});
@@ -22,11 +22,35 @@ import path from 'node:path';
import { PuterController } from '../types.js';
import { toAppShellView } from '../../util/appShellView.js';
import type { PuterRouter } from '../../core/http/PuterRouter';
import {
isReservedSubdomain,
subdomainLabelOf,
} from '../../core/http/middleware/hostRedirects.js';
import type { IConfig } from '../../types';
import type {
PuterHomepageService,
PageMeta,
LaunchOptions,
PopupFrame,
} from '../../services/homepage/PuterHomepageService';
/**
* GUI popups a first-party page can show in a frame at `/embed/<action>`,
* instead of opening `/action/<action>` in a window, plus the upgrade and
* top-up dialogs, which it would otherwise open in a dashboard tab, and the
* email confirmation, which it otherwise can't show.
*/
export const FRAMED_POPUP_ACTIONS = [
'sign-in',
'show-open-file-picker',
'show-save-file-picker',
'show-directory-picker',
'upgrade',
'top-up',
'request-email-confirmation',
'attach-custom-domain',
] as const;
/** Longest description/og:description/twitter:description on `/app/<name>`. */
export const APP_META_DESCRIPTION_MAX = 150;
@@ -55,6 +79,64 @@ export function appMetaDescription(text: string): string {
return `${cut.replace(/[\s,;:.!?…—-]+$/, '')}…`;
}
type EmbedFramingConfig = Pick<
IConfig,
| 'origin'
| 'domain'
| 'api_base_url'
| 'static_hosting_domain'
| 'static_hosting_domain_alt'
| 'private_app_hosting_domain'
| 'private_app_hosting_domain_alt'
>;
/**
* The origin of a first-party page that may frame an `/embed/*` page, named
* exactly from the request's referrer, or null. A wildcard over `*.<domain>`
* would also admit user-hosted sites whenever the hosting domains sit under it,
* so only a single label under `<domain>` qualifies, and not one this server
* answers itself (the API, WebDAV, SDK and native-app hosts).
*/
export function embedHostOrigin(
config: EmbedFramingConfig,
referer: string | undefined,
): string | null {
const gui = new URL(config.origin ?? `https://${config.domain}`);
let parent: URL;
try {
parent = new URL(referer ?? '');
} catch {
return null;
}
const host = parent.hostname.toLowerCase();
const label = subdomainLabelOf(host, config.domain);
const hostingDomains = [
config.static_hosting_domain,
config.static_hosting_domain_alt,
config.private_app_hosting_domain,
config.private_app_hosting_domain_alt,
]
.map((d) => (d ?? '').toLowerCase().split(':')[0])
.filter(Boolean);
const allowed =
parent.protocol === gui.protocol &&
parent.port === gui.port &&
label !== undefined &&
!isReservedSubdomain(label) &&
host !== new URL(config.api_base_url).hostname &&
!hostingDomains.some((d) => host === d || host.endsWith(`.${d}`));
return allowed ? parent.origin : null;
}
/** `frame-ancestors` for an `/embed/*` page: the GUI and {@link embedHostOrigin}. */
export function embedFrameAncestors(
config: EmbedFramingConfig,
referer: string | undefined,
): string {
const host = embedHostOrigin(config, referer);
return host ? `'self' ${host}` : "'self'";
}
/**
* Routes that render the Puter GUI shell, plus a catch-all static fallback
* under `<gui_assets_root>/src` for non-dist/src paths (images, fonts, lib
@@ -88,6 +170,8 @@ export class HomepageController extends PuterController {
req: express.Request,
res: express.Response,
metaOverrides: Partial<PageMeta> = {},
launch: LaunchOptions = {},
popupFrame?: PopupFrame,
) => {
const meta = { ...defaultMeta(req), ...metaOverrides };
const actor =
@@ -96,54 +180,106 @@ export class HomepageController extends PuterController {
actor?: Parameters<typeof homepage.send>[0]['actor'];
}
).actor ?? null;
await homepage.send({ req, res, actor }, meta);
await homepage.send({ req, res, actor }, meta, launch, popupFrame);
};
// -- Root + path-aliased shell routes ------------------------
router.get('/', {}, (req, res) => sendShell(req, res));
/**
* Headers shared by the `/embed/*` pages; false when the request was
* redirected instead. SDK bootstrap parameters must not change an
* embed's account or API origin, so a query string is dropped. Checked
* on the raw URL; `req.query` drops pairs past the parser's limit.
*/
const prepareEmbed = (
req: express.Request,
res: express.Response,
path: string,
): boolean => {
if (req.originalUrl.includes('?')) {
res.redirect(path);
return false;
}
res.removeHeader('X-Frame-Options');
res.setHeader(
'Content-Security-Policy',
`frame-ancestors ${embedFrameAncestors(this.config, req.get('referer'))}`,
);
res.setHeader('Cache-Control', 'no-store');
return true;
};
router.get('/embed/apps', {}, async (req, res) => {
if (!prepareEmbed(req, res, '/embed/apps')) return;
// Shown to visitors without a session; a signed-in embed fetches
// its own list, so a failure here only costs signed-out visitors.
const guestApps = await this.services.recommendedApps
.getRecommendedApps()
.catch((): Array<Record<string, unknown>> => []);
res.send(homepage.renderAppBrowserEmbed({ guestApps }));
});
router.get('/embed/feedback', {}, (req, res) => {
if (!prepareEmbed(req, res, '/embed/feedback')) return;
// The feedback is recorded against this origin, which
// frame-ancestors has just pinned to the actual framing page.
res.send(
homepage.renderFeedbackEmbed({
hostOrigin: embedHostOrigin(
this.config,
req.get('referer'),
),
}),
);
});
// The GUI runs the popup's own boot, answering the framing page
// instead of an opener.
for (const action of FRAMED_POPUP_ACTIONS) {
const embedPath = `/embed/${action}`;
router.get(embedPath, {}, async (req, res) => {
// Routes match case-insensitively and with a trailing slash,
// and the shell boots the desktop for any other spelling, so
// only the exact one may be framed.
if (req.originalUrl !== embedPath) {
res.redirect(embedPath);
return;
}
if (!prepareEmbed(req, res, embedPath)) return;
await sendShell(
req,
res,
{},
{},
{
hostOrigin: embedHostOrigin(
this.config,
req.get('referer'),
),
},
);
});
}
router.get('/settings', {}, (req, res) => sendShell(req, res));
router.get('/settings/*splat', {}, (req, res) => sendShell(req, res));
router.get('/dashboard', {}, (req, res) => sendShell(req, res));
router.get('/dashboard/', {}, (req, res) => sendShell(req, res));
// `/desktop` used to pick the desktop interface. What follows it is
// the same route at the root, so it redirects there, keeping the query
// (`?shared=`, `?download=`); the browser carries the hash over.
const redirectWithoutDesktop = (
req: express.Request,
res: express.Response,
target: string,
) => {
const url = req.originalUrl ?? req.url ?? '';
const query = url.includes('?') ? url.slice(url.indexOf('?')) : '';
res.redirect(302, `${target}${query}`);
};
router.get('/desktop', {}, (req, res) =>
redirectWithoutDesktop(req, res, '/'),
);
router.get('/desktop/', {}, (req, res) =>
redirectWithoutDesktop(req, res, '/'),
);
router.get('/desktop/app/:name', {}, (req, res) =>
redirectWithoutDesktop(
req,
res,
`/app/${encodeURIComponent(String(req.params.name))}`,
),
);
router.get('/desktop', {}, (req, res) => sendShell(req, res));
router.get('/desktop/', {}, (req, res) => sendShell(req, res));
router.get('/action/*splat', {}, (req, res) => sendShell(req, res));
// `/@<user>/<path>` names something in that user's Public folder; the
// GUI opens it.
router.get('/@:username', {}, (req, res) => sendShell(req, res));
router.get('/@:username/*splat', {}, (req, res) => sendShell(req, res));
// -- /app/:name - app metadata baked into the shell ----------
// `/desktop/app/:name` is the same landing booted on the desktop
// instead of the dashboard; the GUI strips the prefix and treats the
// rest of the path identically, so both render the same shell.
const sendAppShell = async (
req: express.Request,
@@ -198,10 +334,27 @@ export class HomepageController extends PuterController {
{ rateLimit: APP_LANDING_LIMIT },
sendAppShell,
);
router.get(
'/desktop/app/:name',
{ rateLimit: APP_LANDING_LIMIT },
sendAppShell,
);
// -- /show/* - the GUI opens the path that follows ----------
// -- /show/* - launch explorer with the requested file path --
router.get('/show/*splat', {}, (req, res) => sendShell(req, res));
router.get('/show/*splat', {}, (req, res) => {
const filePath = req.path.slice('/show'.length);
const launch: LaunchOptions = {
on_initialized: [
{
$: 'window-call',
fn_name: 'launch_app',
args: [{ name: 'explorer', path: filePath }],
},
],
};
return sendShell(req, res, {}, launch);
});
// -- /sw.js - the service worker, scoped to the whole origin --
@@ -244,7 +244,10 @@ describe('OIDCController GET /auth/oidc/providers', () => {
await callRoute('get', '/auth/oidc/providers', makeReq({}), res);
// We configured a single `custom` provider; the live service
// walks the config and returns its id.
expect(captured.body).toEqual({ providers: ['custom'] });
expect(captured.body).toEqual({
providers: ['custom'],
signupOidcOnly: false,
});
});
});
@@ -1617,7 +1620,7 @@ describe('OIDCController signup callback', () => {
expect(captured.redirectUrl).toContain('action=signup');
});
it('creates a fresh user without oidc_switched on first signup', async () => {
it('creates a fresh user on first signup', async () => {
const state = oidc().signState({
provider: 'custom',
redirect_uri: TEST_ORIGIN + '/',
@@ -1643,11 +1646,9 @@ describe('OIDCController signup callback', () => {
);
expect(captured.cookies).toHaveLength(1);
expect(captured.redirectUrl).toBe(TEST_ORIGIN + '/');
// Fresh creation — must NOT advertise "you've actually been signed in".
expect(captured.redirectUrl).not.toContain('oidc_switched=login');
});
it('adds oidc_switched=login when signup hits an already-linked account', async () => {
it('signs in to an already-linked account on signup, returning as a login would', async () => {
// Seed an account linked on (provider, sub) so the signup callback
// resolves to `linked-sub` rather than creating a new user.
const sub = `sub-${Math.random().toString(36).slice(2, 8)}`;
@@ -1683,7 +1684,7 @@ describe('OIDCController signup callback', () => {
res,
);
expect(captured.cookies).toHaveLength(1);
expect(captured.redirectUrl).toContain('oidc_switched=login');
expect(captured.redirectUrl).toBe(TEST_ORIGIN + '/');
});
it('redirects to action=signup with auth_error when user resolution fails (unconfirmed email)', async () => {
+11 -20
View File
@@ -396,9 +396,12 @@ export class OIDCController extends PuterController {
},
},
async (_req: Request, res: Response) => {
const providers =
await this.services.oidc.getEnabledProviderIds();
res.json({ providers });
const [providers, policy] = await Promise.all([
this.services.oidc.getEnabledProviderIds(),
this.services.signup.signupPolicy(),
]);
// The signup window drops its email form when this is set.
res.json({ providers, signupOidcOnly: policy.oidcOnly });
},
);
@@ -685,14 +688,7 @@ export class OIDCController extends PuterController {
);
}
// If we landed on an existing account (either via the
// provider_sub or via email match), signal the GUI so it can
// render a "signed in" flow rather than "account created".
const extra =
resolved.origin === 'created'
? undefined
: { oidc_switched: 'login' };
await this.#finishLogin(req, res, user, stateDecoded, extra);
await this.#finishLogin(req, res, user, stateDecoded);
};
router.get('/auth/oidc/callback/signup', cbOpts, signupCb);
router.post('/auth/oidc/callback/signup', cbOpts, signupCb);
@@ -831,17 +827,14 @@ if (window.opener) {
attempt = 0,
): Promise<
| { error: string; code?: string; requestCode?: string }
| {
user: import('../../stores/user/UserStore.js').UserRow;
origin: 'linked-sub' | 'linked-email' | 'created';
}
| { user: import('../../stores/user/UserStore.js').UserRow }
> {
// 1. Existing provider/sub link.
const linked = await this.services.oidc.findUserByProviderSub(
provider,
userinfo.sub,
);
if (linked) return { user: linked, origin: 'linked-sub' };
if (linked) return { user: linked };
// 2/3. Email match branch.
const claimedEmail =
@@ -878,7 +871,7 @@ if (window.opener) {
error: outcome.error ?? 'Failed to link provider.',
};
}
return { user: byEmail, origin: 'linked-email' };
return { user: byEmail };
}
}
@@ -908,7 +901,7 @@ if (window.opener) {
requestCode: outcome.requestCode,
};
}
return { user: outcome.user, origin: 'created' };
return { user: outcome.user };
}
async #processCallback(
@@ -997,7 +990,6 @@ if (window.opener) {
res: Response,
user: UserRow,
stateDecoded: Record<string, unknown>,
extraQueryParams?: Record<string, string>,
): Promise<void> {
const origin = (this.config.origin ?? '').replace(/\/$/, '');
const continuation: OidcLoginContinuation = {
@@ -1015,7 +1007,6 @@ if (window.opener) {
stateDecoded.msg_id == null
? null
: String(stateDecoded.msg_id),
switchedToLogin: extraQueryParams?.oidc_switched === 'login',
};
if (user.otp_enabled) {
const challenge = this.services.token.sign(
@@ -139,7 +139,7 @@ describe('OIDC account second-factor login', () => {
expect(await response.json()).toMatchObject({
proceed: true,
next_step: 'complete',
redirectUrl: `${env.origin}/dashboard${flow === 'signup' ? '?oidc_switched=login' : ''}`,
redirectUrl: `${env.origin}/dashboard`,
});
expect(
response.headers
@@ -201,6 +201,7 @@ describe('PuterAIController.openaiResponses parameter forwarding', () => {
context_management: [{ type: 'compaction' }],
prompt_cache_key: 'ck',
prompt_cache_retention: '24h',
prompt_cache_options: { ttl: '12h', prewarm: true },
store: true,
truncation: 'auto',
service_tier: 'default',
@@ -226,6 +227,9 @@ describe('PuterAIController.openaiResponses parameter forwarding', () => {
context_management: [{ type: 'compaction' }],
prompt_cache_key: 'ck',
prompt_cache_retention: '24h',
// Forwarded as sent; the provider keeps only the fields it
// accepts.
prompt_cache_options: { ttl: '12h', prewarm: true },
// forced false regardless of the client's request.
store: false,
truncation: 'auto',
@@ -359,13 +363,18 @@ describe('PuterAIController.openaiResponses input normalization', () => {
role: 'user',
content: [
'a bare string part',
{ type: 'input_text', text: 'typed text' },
{
type: 'input_text',
text: 'typed text',
prompt_cache_breakpoint: { mode: 'explicit', ttl: '12h' },
},
{ type: 'output_text', text: 'echoed text' },
{
type: 'input_image',
detail: 'high',
image_url: 'https://img.test/a.png',
file_id: 'file_img',
prompt_cache_breakpoint: { mode: 'explicit' },
},
{ type: 'input_audio', input_audio: { data: 'AAA' } },
{
@@ -386,13 +395,18 @@ describe('PuterAIController.openaiResponses input normalization', () => {
role: 'user',
content: [
{ type: 'text', text: 'a bare string part' },
{ type: 'text', text: 'typed text' },
{
type: 'text',
text: 'typed text',
prompt_cache_breakpoint: { mode: 'explicit', ttl: '12h' },
},
{ type: 'text', text: 'echoed text' },
{
type: 'image_url',
detail: 'high',
image_url: { url: 'https://img.test/a.png' },
file_id: 'file_img',
prompt_cache_breakpoint: { mode: 'explicit' },
},
{ type: 'input_audio', input_audio: { data: 'AAA' } },
{
@@ -639,6 +653,33 @@ describe('PuterAIController.openaiResponses output items', () => {
// -- /openai/v1/chat/completions edges -------------------------------
describe('PuterAIController.openaiChatCompletions translation edges', () => {
it('forwards the prompt-cache fields to the driver', async () => {
const completeSpy = stubChatComplete({
message: { role: 'assistant', content: 'ok' },
});
const { res } = makeRes();
await controller.openaiChatCompletions(
makeReq({
body: {
model: 'gpt-test',
messages: [{ role: 'user', content: 'hi' }],
prompt_cache_key: 'ck',
prompt_cache_retention: 'in_memory',
prompt_cache_options: { ttl: '30m' },
},
}),
res,
);
const args = completeSpy.mock.calls[0]![0] as Record<string, unknown>;
expect(args).toMatchObject({
prompt_cache_key: 'ck',
prompt_cache_retention: 'in_memory',
prompt_cache_options: { ttl: '30m' },
});
});
it('derives tool_calls from tool_use content blocks when the message has none', async () => {
stubChatComplete({
message: {
@@ -447,6 +447,7 @@ export class PuterAIController extends PuterController {
body.reasoning_effort as ICompleteArguments['reasoning_effort'],
}
: {}),
...promptCacheArgsFromBody(body),
...openaiCompatProvider(body),
...(body.fallback === false ? { fallback: false } : {}),
};
@@ -842,15 +843,7 @@ export class PuterAIController extends PuterController {
body.compaction as ICompleteArguments['compaction'],
}
: {}),
...(body.prompt_cache_key
? { prompt_cache_key: String(body.prompt_cache_key) }
: {}),
...(body.prompt_cache_retention
? {
prompt_cache_retention:
body.prompt_cache_retention as ICompleteArguments['prompt_cache_retention'],
}
: {}),
...promptCacheArgsFromBody(body),
// forced off regardless of what the caller sent — OpenAI
// defaults `store` to true, which would persist state server-side
// on OpenAI's end that this route gives no way to retrieve.
@@ -1343,6 +1336,33 @@ const openaiCompatProvider = (
return { provider: DEFAULTS.openaiChat };
};
/**
* The prompt-cache fields both OpenAI-shaped routes forward as sent; the
* provider checks the values.
*/
const promptCacheArgsFromBody = (
body: Record<string, unknown>,
): Pick<
ICompleteArguments,
'prompt_cache_key' | 'prompt_cache_retention' | 'prompt_cache_options'
> => ({
...(body.prompt_cache_key
? { prompt_cache_key: String(body.prompt_cache_key) }
: {}),
...(body.prompt_cache_retention
? {
prompt_cache_retention:
body.prompt_cache_retention as ICompleteArguments['prompt_cache_retention'],
}
: {}),
...(body.prompt_cache_options
? {
prompt_cache_options:
body.prompt_cache_options as ICompleteArguments['prompt_cache_options'],
}
: {}),
});
const randomId = (): string => crypto.randomUUID().replace(/-/g, '');
const generateId = (prefix: string): string => `${prefix}_${randomId()}`;
@@ -1590,12 +1610,24 @@ const parseJsonMaybe = (value: unknown): unknown => {
}
};
/** An OpenAI `prompt_cache_breakpoint` marker, kept on the translated part. */
const cacheBreakpointOf = (
p: Record<string, unknown>,
): { prompt_cache_breakpoint?: unknown } =>
p.prompt_cache_breakpoint && typeof p.prompt_cache_breakpoint === 'object'
? { prompt_cache_breakpoint: p.prompt_cache_breakpoint }
: {};
const normalizeContentPart = (part: unknown): Record<string, unknown> => {
if (typeof part === 'string') return { type: 'text', text: part };
if (!part || typeof part !== 'object') return { type: 'text', text: '' };
const p = part as Record<string, unknown>;
if (p.type === 'input_text' || p.type === 'output_text') {
return { type: 'text', text: String(p.text ?? '') };
return {
type: 'text',
text: String(p.text ?? ''),
...cacheBreakpointOf(p),
};
}
if (p.type === 'input_image') {
return {
@@ -1603,6 +1635,7 @@ const normalizeContentPart = (part: unknown): Record<string, unknown> => {
...(p.detail ? { detail: p.detail } : {}),
...(p.image_url ? { image_url: { url: p.image_url } } : {}),
...(p.file_id ? { file_id: p.file_id } : {}),
...cacheBreakpointOf(p),
};
}
if (p.type === 'input_audio')
@@ -1614,6 +1647,7 @@ const normalizeContentPart = (part: unknown): Record<string, unknown> => {
...(p.file_id ? { file_id: p.file_id } : {}),
...(p.file_url ? { file_url: p.file_url } : {}),
...(p.filename ? { filename: p.filename } : {}),
...cacheBreakpointOf(p),
};
}
return p;
@@ -0,0 +1,89 @@
/*
* 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 { randomUUID } from 'node:crypto';
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
import {
setupPuterTestEnv,
TEST_USER_CREDENTIALS,
type PuterTestEnv,
} from '../../testUtil.js';
/** A PUT body is the file, whatever content type the client labels it with. */
describe('PUT stores the body as sent', () => {
let env: PuterTestEnv;
beforeAll(async () => {
env = await setupPuterTestEnv();
}, 60_000);
afterAll(async () => {
await env?.shutdown();
});
const dav = (path: string, init: RequestInit) => {
const port = new URL(env.apiOrigin).port;
const auth = Buffer.from(
`${TEST_USER_CREDENTIALS.username}:${TEST_USER_CREDENTIALS.password}`,
).toString('base64');
return fetch(`http://dav.puter.localhost:${port}${encodeURI(path)}`, {
...init,
headers: { Authorization: `Basic ${auth}`, ...init.headers },
});
};
it.each([
['application/json', '{"name":"report","rows":[1,2,3]}'],
// Not JSON at all: the label alone must not get the body rejected.
['application/json', 'not json'],
['text/plain;actually=json', '{"a":1}'],
['application/x-www-form-urlencoded', 'a=1&b=two'],
['application/octet-stream', 'plain bytes'],
])(
'with Content-Type %s',
async (contentType, content) => {
const path = `/${env.users.user.username}/Documents/put-${randomUUID().slice(0, 8)}.bin`;
const put = await dav(path, {
method: 'PUT',
headers: { 'Content-Type': contentType },
body: content,
});
expect(put.status).toBe(201);
const get = await dav(path, { method: 'GET' });
expect(get.status).toBe(200);
expect(await get.text()).toBe(content);
},
30_000,
);
it('with a form body over the form parser limit', async () => {
const path = `/${env.users.user.username}/Documents/put-${randomUUID().slice(0, 8)}.bin`;
const content = `a=${'x'.repeat(200 * 1024)}`;
const put = await dav(path, {
method: 'PUT',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: content,
});
expect(put.status).toBe(201);
const get = await dav(path, { method: 'GET' });
expect(await get.text()).toBe(content);
}, 30_000);
});
@@ -224,7 +224,7 @@ const extractToken = (
}
}
// 5. Query string (used by e.g. QR login, asset URLs).
// 5. Query string (used by e.g. asset URLs).
const queryToken = (req.query as { auth_token?: unknown } | undefined)
?.auth_token;
if (typeof queryToken === 'string' && queryToken.length > 0) {
@@ -187,9 +187,9 @@ describe('createUserSubdomainNotFound', () => {
});
it('passes through reserved subdomains (api, js, native apps, etc.)', () => {
// `api`, `js`, `dav`, `docs`, `developer`, `editor`, `pdf`,
// `api`, `js`, `dav`, `docs`, `developer`, `about`, `apps`,
// `puter-app-icons`, etc. all pass through.
for (const sub of ['api', 'js', 'docs', 'editor', 'puter-app-icons']) {
for (const sub of ['api', 'js', 'docs', 'about', 'puter-app-icons']) {
const { out, next } = run(
createUserSubdomainNotFound(config),
makeReq({
@@ -865,13 +865,13 @@ describe('createNativeAppStatic', () => {
beforeAll(() => {
root = mkdtempSync(nodePath.join(tmpdir(), 'native-apps-'));
mkdirSync(nodePath.join(root, 'editor', 'assets'), { recursive: true });
mkdirSync(nodePath.join(root, 'about', 'assets'), { recursive: true });
writeFileSync(
nodePath.join(root, 'editor', 'index.html'),
'<h1>editor</h1>',
nodePath.join(root, 'about', 'index.html'),
'<h1>about</h1>',
);
writeFileSync(
nodePath.join(root, 'editor', 'assets', 'app.js'),
nodePath.join(root, 'about', 'assets', 'app.js'),
'console.log(1);',
);
mkdirSync(nodePath.join(root, 'docs', 'dist'), { recursive: true });
@@ -893,7 +893,7 @@ describe('createNativeAppStatic', () => {
it('leaves a native app name alone on a host outside our domains', async () => {
const req = staticReq({
subdomains: ['com', 'example', 'editor'],
subdomains: ['com', 'example', 'about'],
path: '/index.html',
});
(req as Request & { is_custom_domain?: boolean }).is_custom_domain =
@@ -907,7 +907,7 @@ describe('createNativeAppStatic', () => {
const { out, next } = await runStatic(
createNativeAppStatic(config),
staticReq({
subdomains: ['localhost', 'puter', 'editor'],
subdomains: ['localhost', 'puter', 'about'],
path: '/index.html',
}),
);
@@ -915,17 +915,24 @@ describe('createNativeAppStatic', () => {
expect(next).toHaveBeenCalledTimes(1);
});
it('passes through subdomains that are not native apps', async () => {
const { out, next } = await runStatic(
withRoot(),
staticReq({
subdomains: ['localhost', 'puter', 'api'],
path: '/index.html',
}),
);
expect(out.sent).toBeUndefined();
expect(next).toHaveBeenCalledTimes(1);
});
// `editor`, `markus` and `pdf` are web apps on standard host routing,
// even with a folder of their own under the native apps root.
it.each(['api', 'editor', 'markus', 'pdf'])(
'passes %s through, as it is not a native app',
async (sub) => {
mkdirSync(nodePath.join(root, sub), { recursive: true });
writeFileSync(nodePath.join(root, sub, 'index.html'), sub);
const { out, next } = await runStatic(
withRoot(),
staticReq({
subdomains: ['localhost', 'puter', sub],
path: '/index.html',
}),
);
expect(out.sent).toBeUndefined();
expect(next).toHaveBeenCalledTimes(1);
},
);
it('passes through when there is no subdomain at all', async () => {
const { next } = await runStatic(
@@ -939,13 +946,13 @@ describe('createNativeAppStatic', () => {
const { out, next } = await runStatic(
withRoot(),
staticReq({
subdomains: ['localhost', 'puter', 'editor'],
subdomains: ['localhost', 'puter', 'about'],
path: '/index.html',
}),
);
expect(out.sent).toEqual({
path: '/index.html',
root: nodePath.join(root, 'editor'),
root: nodePath.join(root, 'about'),
});
expect(next).not.toHaveBeenCalled();
});
@@ -954,11 +961,11 @@ describe('createNativeAppStatic', () => {
const { out } = await runStatic(
withRoot(),
staticReq({
subdomains: ['localhost', 'puter', 'EDITOR'],
subdomains: ['localhost', 'puter', 'ABOUT'],
path: '/index.html',
}),
);
expect(out.sent?.root).toBe(nodePath.join(root, 'editor'));
expect(out.sent?.root).toBe(nodePath.join(root, 'about'));
});
it('serves docs out of its dist/ subdirectory, not the app root', async () => {
@@ -979,7 +986,7 @@ describe('createNativeAppStatic', () => {
const { out, next } = await runStatic(
withRoot(),
staticReq({
subdomains: ['localhost', 'puter', 'editor'],
subdomains: ['localhost', 'puter', 'about'],
path: '/assets',
originalUrl: '/assets?v=2',
}),
@@ -995,7 +1002,7 @@ describe('createNativeAppStatic', () => {
const { out } = await runStatic(
withRoot(),
staticReq({
subdomains: ['localhost', 'puter', 'editor'],
subdomains: ['localhost', 'puter', 'about'],
path: '/assets/',
}),
);
@@ -1007,7 +1014,7 @@ describe('createNativeAppStatic', () => {
const { out, next } = await runStatic(
withRoot(),
staticReq({
subdomains: ['localhost', 'puter', 'editor'],
subdomains: ['localhost', 'puter', 'about'],
path: '/nope.html',
}),
);
@@ -1019,7 +1026,7 @@ describe('createNativeAppStatic', () => {
const { next } = await runStatic(
withRoot(),
staticReq({
subdomains: ['localhost', 'puter', 'editor'],
subdomains: ['localhost', 'puter', 'about'],
path: '/index.html',
}),
new Error('send failed'),
@@ -1032,7 +1039,7 @@ describe('createNativeAppStatic', () => {
runStatic(
withRoot(),
staticReq({
subdomains: ['localhost', 'puter', 'editor'],
subdomains: ['localhost', 'puter', 'about'],
path: '/../../etc/passwd',
}),
),
@@ -27,15 +27,7 @@ import { HttpError, isHttpError } from '../HttpError';
import { isLocalWorkerHost } from './localWorkerProxy';
/** Native-app subdomains served via `nativeAppStatic`. */
const NATIVE_APP_SUBDOMAINS = [
'about',
'developer',
'docs',
'editor',
'markus',
'pdf',
'apps',
] as const;
const NATIVE_APP_SUBDOMAINS = ['about', 'developer', 'docs', 'apps'] as const;
/** Subset served out of a `dist/` subdirectory rather than the app root. */
const NATIVE_APPS_WITH_DIST = new Set(['docs', 'developer']);
@@ -111,6 +103,10 @@ export const subdomainLabelOf = (
return label && !label.includes('.') ? label : undefined;
};
/** Whether core itself answers `<name>.<domain>` (`www` redirects to the root). */
export const isReservedSubdomain = (name: string): boolean =>
name === 'www' || RESERVED_SUBDOMAINS.has(name);
/**
* Record a claim on `<name>.<domain>`. Throws on a malformed or uppercase
* label, a subdomain core already handles, or a name that is already claimed.
@@ -123,7 +119,7 @@ export const addClaimedSubdomain = (
if (typeof name !== 'string' || !SUBDOMAIN_LABEL.test(name)) {
throw new Error(`Invalid subdomain label: ${JSON.stringify(name)}`);
}
if (name === 'www' || RESERVED_SUBDOMAINS.has(name)) {
if (isReservedSubdomain(name)) {
throw new Error(`Subdomain '${name}' is reserved`);
}
if (claims.has(name)) {
@@ -0,0 +1,263 @@
/*
* 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 type { Server } from 'node:http';
import type { AddressInfo } from 'node:net';
import { brotliCompressSync, deflateSync, gzipSync } from 'node:zlib';
import express, {
type ErrorRequestHandler,
type RequestHandler,
} from 'express';
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
import { SLICE_BYTES } from '../../../util/slicedJson';
import { createJsonBodyParser } from './jsonBody';
const LIMIT = 4 * 1024 * 1024;
const TEXT_AS_JSON = 'text/plain;actually=json';
type Verify = NonNullable<Parameters<typeof express.json>[0]>['verify'];
const captureRawBody: Verify = (req, _res, buf) => {
(req as { rawBody?: Buffer }).rawBody = buf;
};
/** An app that answers with what its parsers left on the request. */
const listen = (parsers: RequestHandler[]): Promise<Server> => {
const app = express();
app.use(...parsers);
app.post('/', (req, res) => {
const rawBody = (req as { rawBody?: Buffer }).rawBody;
res.json({
body: req.body,
hasBody: req.body !== undefined,
rawBody: rawBody?.toString('base64'),
});
});
const onError: ErrorRequestHandler = (err, _req, res, _next) => {
res.status(err.statusCode ?? 500).json({ type: err.type });
};
app.use(onError);
return new Promise((resolve) => {
const server = app.listen(0, '127.0.0.1', () => resolve(server));
});
};
describe('createJsonBodyParser', () => {
let sliced: Server;
let framework: Server;
beforeAll(async () => {
sliced = await listen([
createJsonBodyParser({ limit: LIMIT, verify: captureRawBody }),
]);
// What the server ran before: one parser per content type.
framework = await listen([
express.json({ limit: LIMIT, verify: captureRawBody }),
express.json({
limit: LIMIT,
type: (req) => req.headers['content-type'] === TEXT_AS_JSON,
verify: captureRawBody,
}),
]);
});
afterAll(() => {
sliced?.close();
framework?.close();
});
const post = async (
server: Server,
body: string | Buffer | undefined,
headers: Record<string, string>,
) => {
const { port } = server.address() as AddressInfo;
const response = await fetch(`http://127.0.0.1:${port}/`, {
method: 'POST',
headers,
body,
});
return { status: response.status, answer: await response.json() };
};
const large = `${JSON.stringify({
text: 'é😀 "quoted" \\ line\n'.repeat(SLICE_BYTES / 8),
list: Array.from({ length: 20_000 }, (_, i) => ({
i,
on: i % 2 === 0,
})),
}).slice(0, -1)},"__proto__":{"nested":true}}`;
it.each<[string, string | Buffer | undefined, Record<string, string>]>([
['an object', '{"a":1}', { 'Content-Type': 'application/json' }],
['an array', '[1,2]', { 'Content-Type': 'application/json' }],
[
'a body sent as text',
'{"interface":"x","auth_token":"t"}',
{ 'Content-Type': TEXT_AS_JSON },
],
['a large body', large, { 'Content-Type': 'application/json' }],
['a large body sent as text', large, { 'Content-Type': TEXT_AS_JSON }],
[
'a charset parameter',
large,
{ 'Content-Type': 'application/json; charset=UTF-8' },
],
[
'a quoted charset parameter',
'{"a":"é"}',
{ 'Content-Type': 'application/json;charset="utf-8"' },
],
[
'another parameter',
'{"a":1}',
{ 'Content-Type': 'application/json; profile=x' },
],
['an empty body', '', { 'Content-Type': 'application/json' }],
['no body', undefined, { 'Content-Type': 'application/json' }],
[
'a byte order mark',
`\ufeff${large}`,
{ 'Content-Type': 'application/json' },
],
[
'only a byte order mark',
'\ufeff',
{ 'Content-Type': 'application/json' },
],
['only whitespace', ' \n', { 'Content-Type': 'application/json' }],
['a bare string', '"text"', { 'Content-Type': 'application/json' }],
['a bare number', ' 12', { 'Content-Type': 'application/json' }],
['null', 'null', { 'Content-Type': 'application/json' }],
['malformed JSON', '{"a":', { 'Content-Type': 'application/json' }],
[
'malformed large JSON',
`${large.slice(0, -1)},]`,
{ 'Content-Type': 'application/json' },
],
[
'a large bare string',
JSON.stringify('x'.repeat(4 * SLICE_BYTES)),
{ 'Content-Type': 'application/json' },
],
[
'invalid UTF-8',
Buffer.concat([
Buffer.from('{"a":"'),
Buffer.from([0xff, 0xe2, 0x82]),
Buffer.from('"}'),
]),
{ 'Content-Type': 'application/json' },
],
[
'a body over the limit',
`["${'x'.repeat(LIMIT)}"]`,
{ 'Content-Type': 'application/json' },
],
[
'a gzipped body',
gzipSync(large),
{ 'Content-Type': 'application/json', 'Content-Encoding': 'gzip' },
],
[
'a deflated body',
deflateSync(large),
{
'Content-Type': 'application/json',
'Content-Encoding': 'deflate',
},
],
[
'a brotli body',
brotliCompressSync(large),
{ 'Content-Type': 'application/json', 'Content-Encoding': 'br' },
],
[
'a body that inflates past the limit',
gzipSync(`["${'x'.repeat(LIMIT)}"]`),
{ 'Content-Type': 'application/json', 'Content-Encoding': 'gzip' },
],
[
'an unknown content encoding',
'{"a":1}',
{ 'Content-Type': 'application/json', 'Content-Encoding': 'lzw' },
],
['plain text', '{"a":1}', { 'Content-Type': 'text/plain' }],
[
'text with the marker and a charset',
'{"a":1}',
{ 'Content-Type': `${TEXT_AS_JSON}; charset=utf-8` },
],
[
'a JSON-suffixed type',
'{"a":1}',
{ 'Content-Type': 'application/vnd.api+json' },
],
[
'form data',
'a=1',
{ 'Content-Type': 'application/x-www-form-urlencoded' },
],
['no content type', '{"a":1}', { 'Content-Type': '' }],
])('answers %s the way express.json does', async (_name, body, headers) => {
const got = await post(sliced, body, headers);
const want = await post(framework, body, headers);
expect(got).toEqual(want);
});
it('leaves a body in another charset unread', async () => {
for (const charset of ['utf-16', 'utf8', 'latin1']) {
const { status, answer } = await post(
sliced,
Buffer.from('{"a":1}', 'utf16le'),
{ 'Content-Type': `application/json; charset=${charset}` },
);
expect(status).toBe(200);
expect(answer.hasBody).toBe(false);
}
// The last charset named is the one that counts.
const { answer } = await post(sliced, '{"a":1}', {
'Content-Type': 'application/json; charset=utf-8; charset=utf-16',
});
expect(answer.hasBody).toBe(false);
});
it('parses bodies that arrive together, each to its own result', async () => {
const bodies = Array.from({ length: 6 }, (_, n) =>
JSON.stringify({ n, pad: 'x'.repeat((n + 1) * SLICE_BYTES) }),
);
const answers = await Promise.all(
bodies.map((body) =>
post(sliced, body, { 'Content-Type': 'application/json' }),
),
);
answers.forEach(({ status, answer }, n) => {
expect(status).toBe(200);
expect(answer.body).toEqual(JSON.parse(bodies[n]!));
});
// A failed parse hands its turn on like a finished one.
const mixed = await Promise.all([
post(sliced, `${bodies[5]!},`, {
'Content-Type': 'application/json',
}),
post(sliced, bodies[4], { 'Content-Type': 'application/json' }),
post(sliced, bodies[3], { 'Content-Type': 'application/json' }),
]);
expect(mixed.map(({ status }) => status)).toEqual([400, 200, 200]);
});
});
@@ -0,0 +1,127 @@
/*
* 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 express, { type Request, type RequestHandler } from 'express';
import { parseJsonInSlices, SLICE_BYTES } from '../../../util/slicedJson';
/** What puter.js labels a JSON driver call, to keep it a simple CORS request. */
const TEXT_AS_JSON = 'text/plain;actually=json';
const UTF8_CHARSET = /;\s*charset=("?)utf-8\1\s*(?:;|$)/i;
/** No charset, or exactly UTF-8. Anything else is left to `express.json`. */
const declaresUtf8 = (contentType: string): boolean => {
const mentions = contentType.match(/charset/gi)?.length ?? 0;
return mentions === 0 || (mentions === 1 && UTF8_CHARSET.test(contentType));
};
const isUtf8Json = (req: Request): boolean => {
const contentType = req.headers['content-type'];
if (contentType === TEXT_AS_JSON) return true;
return (
typeof contentType === 'string' &&
Boolean(req.is('application/json')) &&
declaresUtf8(contentType)
);
};
/** The error `express.json` raises, which the error handler answers with a 400. */
const parseFailed = (message: string): Error =>
Object.assign(new SyntaxError(message), {
status: 400,
statusCode: 400,
expose: true,
type: 'entity.parse.failed',
});
const waiting: Array<() => void> = [];
let parsing = false;
/**
* Bodies too large for one `JSON.parse` call parse one at a time, so a single
* tree is under construction however many arrive together.
*/
const parseInTurn = async (body: Buffer): Promise<unknown> => {
if (body.length <= SLICE_BYTES) return parseJsonInSlices(body);
if (parsing) await new Promise<void>((resolve) => waiting.push(resolve));
parsing = true;
try {
return await parseJsonInSlices(body);
} finally {
// Handing over keeps `parsing` set, so a new arrival can't cut in.
const next = waiting.shift();
if (next) next();
else parsing = false;
}
};
interface JsonBodyOptions {
limit: number;
verify?: NonNullable<Parameters<typeof express.raw>[0]>['verify'];
}
/**
* `express.json` for UTF-8 bodies, with the parse done in slices so a large
* body can't hold the event loop. Reading, limits, decompression and `verify`
* are the framework's; the result and the errors match `express.json`.
*/
export const createJsonBodyParser = ({
limit,
verify,
}: JsonBodyOptions): RequestHandler => {
const read = express.raw({
limit,
verify,
type: (req) => isUtf8Json(req as Request),
});
return (req, res, next) => {
read(req, res, async (err?: unknown) => {
// Not a Buffer: the reader skipped this request.
if (err || !Buffer.isBuffer(req.body)) {
next(err);
return;
}
let body: Buffer = req.body;
req.body = undefined;
// The framework's decoder drops a byte order mark.
if (body[0] === 0xef && body[1] === 0xbb && body[2] === 0xbf) {
body = body.subarray(3);
}
if (body.length === 0) {
req.body = {};
next();
return;
}
let parsed: unknown;
try {
parsed = await parseInTurn(body);
} catch (e) {
next(parseFailed((e as Error).message));
return;
}
if (typeof parsed !== 'object' || parsed === null) {
next(parseFailed('JSON body must be an object or an array'));
return;
}
req.body = parsed;
next();
});
};
};
@@ -0,0 +1,184 @@
/*
* 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 { request, type Server } from 'node:http';
import type { AddressInfo } from 'node:net';
import { setImmediate as nextTurn } from 'node:timers/promises';
import express, {
type ErrorRequestHandler,
type RequestHandler,
} from 'express';
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
import { createJsonBodyParser } from './jsonBody';
import {
createLargeJsonBodyParser,
DEFAULT_JSON_LIMIT_BYTES,
} from './largeJsonBody';
const MiB = 1024 * 1024;
const TOKEN = 'valid-token';
const PAD = 'x'.repeat(DEFAULT_JSON_LIMIT_BYTES);
/** Stands in for the auth probe: one token is valid, wherever it is sent. */
const authProbe: RequestHandler = (req, _res, next) => {
const token =
(req.body as { auth_token?: string } | undefined)?.auth_token ??
req.headers.authorization;
if (!req.actor && token === TOKEN) {
req.actor = { user: { uuid: 'u1' } } as typeof req.actor;
}
next();
};
describe('a JSON body over the default limit', () => {
let server: Server;
beforeAll(async () => {
const app = express();
app.post(
'/call',
createLargeJsonBodyParser({
authProbe,
limitBytes: 128 * MiB,
budgetBytes: 256 * MiB,
perUserBytes: 128 * MiB,
}),
);
app.use(createJsonBodyParser({ limit: DEFAULT_JSON_LIMIT_BYTES }));
app.use(authProbe);
app.post('/call', (req, res) => {
const body = req.body as { auth_token?: string; pad: string };
res.json({
user: req.actor?.user.uuid ?? null,
token: body.auth_token ?? null,
padLength: body.pad.length,
});
});
const onError: ErrorRequestHandler = (err, _req, res, _next) => {
res.status(err.statusCode ?? 500).json({});
};
app.use(onError);
await new Promise<void>((resolve) => {
server = app.listen(0, '127.0.0.1', resolve);
});
});
afterAll(() => {
server?.close();
});
/** Sends `chunks` one write at a time, so the server sees them apart. */
const post = (chunks: string[], headers: Record<string, string> = {}) =>
new Promise<{ status: number; answer: Record<string, unknown> }>(
(resolve, reject) => {
const { port } = server.address() as AddressInfo;
const req = request(
{
host: '127.0.0.1',
port,
path: '/call',
method: 'POST',
headers: {
'Content-Type': 'text/plain;actually=json',
'Content-Length': chunks.reduce(
(total, chunk) =>
total + Buffer.byteLength(chunk),
0,
),
...headers,
},
},
(res) => {
const parts: Buffer[] = [];
res.on('data', (part: Buffer) => parts.push(part));
res.on('end', () =>
resolve({
status: res.statusCode!,
answer: JSON.parse(
Buffer.concat(parts).toString(),
),
}),
);
},
);
req.on('error', reject);
void (async () => {
for (const chunk of chunks) {
req.write(chunk);
await nextTurn();
}
req.end();
})();
},
);
it('is accepted when it opens with a valid auth_token', async () => {
const { status, answer } = await post([
`{"auth_token":"${TOKEN}","pad":"${PAD}"}`,
]);
expect(status).toBe(200);
expect(answer).toEqual({
user: 'u1',
token: TOKEN,
padLength: PAD.length,
});
}, 60_000);
it('is accepted when the token arrives in pieces, with spacing', async () => {
const opening = ` {\n "auth_token" : "${TOKEN}" ,`;
const { status, answer } = await post([...opening, `"pad":"${PAD}"}`]);
expect(status).toBe(200);
expect(answer.user).toBe('u1');
}, 60_000);
it('is accepted with a header credential, as before', async () => {
const { status, answer } = await post([`{"pad":"${PAD}"}`], {
Authorization: TOKEN,
});
expect(status).toBe(200);
expect(answer).toEqual({
user: 'u1',
token: null,
padLength: PAD.length,
});
}, 60_000);
it.each([
[
'its token comes after other fields',
`{"pad":"${PAD}","auth_token":"${TOKEN}"}`,
],
['its token is not valid', `{"auth_token":"expired","pad":"${PAD}"}`],
['it has no token', `{"pad":"${PAD}"}`],
[
'a later field replaces the token it opens with',
`{"auth_token":"${TOKEN}","pad":"${PAD}","auth_token":"other"}`,
],
[
'the token it opens with is nested',
`{"args":{"auth_token":"${TOKEN}"},"pad":"${PAD}"}`,
],
])(
'is refused with 413 when %s',
async (_name, body) => {
expect((await post([body])).status).toBe(413);
},
60_000,
);
});
@@ -18,6 +18,7 @@
*/
import { EventEmitter } from 'node:events';
import { Readable } from 'node:stream';
import type { NextFunction, Request, RequestHandler, Response } from 'express';
import { describe, expect, it, vi } from 'vitest';
import { isHttpError } from '../HttpError';
@@ -35,7 +36,7 @@ const makeReq = (
user: string | null = 'u1',
body?: unknown,
) =>
({
Object.assign(Readable.from([]), {
complete: true,
body,
headers: {
+115 -65
View File
@@ -17,13 +17,54 @@
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import express, { type Request, type RequestHandler } from 'express';
import type { Request, RequestHandler, Response } from 'express';
import { actorUid } from '../../actor';
import { HttpError } from '../HttpError';
import { createJsonBodyParser } from './jsonBody';
/** The global JSON parser's limit, which applies before auth. */
export const DEFAULT_JSON_LIMIT_BYTES = 50 * 1024 * 1024;
/** How much of a body is read to find a token it opens with. */
const LEADING_TOKEN_BYTES = 8 * 1024;
const LEADING_TOKEN =
/^[ \t\n\r]*\{[ \t\n\r]*"auth_token"[ \t\n\r]*:[ \t\n\r]*"([^"\\]+)"/;
/**
* The first `bytes` of the body, put back for the parser to read. Empty when
* the body ends or fails before that many arrive.
*/
const peekBody = (req: Request, bytes: number): Promise<Buffer> =>
new Promise((resolve) => {
const settle = (head: Buffer | null) => {
req.off('readable', onReadable);
req.off('end', onGone);
req.off('close', onGone);
req.off('error', onGone);
if (head) req.unshift(head);
resolve(head ?? Buffer.alloc(0));
};
const onReadable = () => {
// Null until `bytes` are buffered.
const head = req.read(bytes) as Buffer | null;
if (head) settle(head);
};
const onGone = () => settle(null);
req.on('readable', onReadable);
req.on('end', onGone);
req.on('close', onGone);
req.on('error', onGone);
});
/**
* The `auth_token` a JSON body opens with, which puter.js sends first so it can
* be read ahead of the body.
*/
const leadingBodyToken = async (req: Request): Promise<string | undefined> => {
const head = await peekBody(req, LEADING_TOKEN_BYTES);
return LEADING_TOKEN.exec(head.toString('latin1'))?.[1];
};
interface LargeJsonBodyOptions {
/** The global auth probe; it skips requests that already carry an actor. */
authProbe: RequestHandler;
@@ -38,9 +79,9 @@ interface LargeJsonBodyOptions {
/**
* Parses JSON bodies over the default limit, up to `limitBytes`, once the
* caller's header or cookie credential resolves. Unauthenticated requests and
* requests without a Content-Length fall through to the global parser and its
* limit.
* caller's credential resolves: a header, a cookie, or an `auth_token` the body
* opens with. Unauthenticated requests and requests without a Content-Length
* fall through to the global parser and its limit.
*
* The parsed body lives as long as the request, so a body's bytes count against
* both budgets until its response closes. Over the user's budget gets a 429,
@@ -53,82 +94,91 @@ export const createLargeJsonBodyParser = ({
perUserBytes,
accepts,
}: LargeJsonBodyOptions): RequestHandler => {
const json = express.json({ limit: limitBytes });
const textAsJson = express.json({
limit: limitBytes,
type: (req) =>
req.headers['content-type'] === 'text/plain;actually=json',
});
const json = createJsonBodyParser({ limit: limitBytes });
let inFlightBytes = 0;
const inFlightByUser = new Map<string, number>();
return (req, res, next) => {
const probe = (req: Request, res: Response) =>
new Promise<void>((resolve) => {
void authProbe(req, res, () => resolve());
});
return async (req, res, next) => {
const declared = Number(req.headers['content-length']);
if (!(declared > DEFAULT_JSON_LIMIT_BYTES && declared <= limitBytes)) {
next();
return;
}
void authProbe(req, res, () => {
// `res.closed`: the client left during the probe, so `close` has
// already fired and would never release a charge.
if (!req.actor || res.closed) {
next();
await probe(req, res);
let bodyToken: string | undefined;
if (!req.actor && !res.closed) {
bodyToken = await leadingBodyToken(req);
if (bodyToken) {
// Where the probe looks for a body token.
req.body = { auth_token: bodyToken };
await probe(req, res);
req.body = undefined;
}
}
// `res.closed`: the client left during the probe, so `close` has
// already fired and would never release a charge.
if (!req.actor || res.closed) {
next();
return;
}
const user = req.actor.user.uuid ?? actorUid(req.actor);
const userBytes = inFlightByUser.get(user) ?? 0;
if (userBytes + declared > perUserBytes) {
res.setHeader('Retry-After', '5');
next(
new HttpError(
429,
'Too many large requests in progress for this account',
{ legacyCode: 'too_many_requests' },
),
);
return;
}
if (inFlightBytes + declared > budgetBytes) {
res.setHeader('Retry-After', '5');
next(
new HttpError(503, 'Too many large requests in progress', {
code: 'large_body_capacity',
// Load shedding, not a fault: record it, don't page.
alarmSeverity: 'info',
}),
);
return;
}
inFlightBytes += declared;
inFlightByUser.set(user, userBytes + declared);
res.once('close', () => {
inFlightBytes -= declared;
const left = (inFlightByUser.get(user) ?? 0) - declared;
if (left > 0) inFlightByUser.set(user, left);
else inFlightByUser.delete(user);
});
json(req, res, (err?: unknown) => {
if (err) {
next(err);
return;
}
const user = req.actor.user.uuid ?? actorUid(req.actor);
const userBytes = inFlightByUser.get(user) ?? 0;
if (userBytes + declared > perUserBytes) {
res.setHeader('Retry-After', '5');
// The caller was resolved from the token the body opens with,
// so the parsed body has to name the same one.
const tokenMoved =
bodyToken !== undefined &&
(req.body as { auth_token?: unknown } | undefined)
?.auth_token !== bodyToken;
if (tokenMoved || (accepts && !accepts(req))) {
// The same answer the default limit gives.
next(
new HttpError(
429,
'Too many large requests in progress for this account',
{ legacyCode: 'too_many_requests' },
),
);
return;
}
if (inFlightBytes + declared > budgetBytes) {
res.setHeader('Retry-After', '5');
next(
new HttpError(503, 'Too many large requests in progress', {
code: 'large_body_capacity',
// Load shedding, not a fault: record it, don't page.
alarmSeverity: 'info',
new HttpError(413, 'request entity too large', {
legacyCode: 'client_bad_request',
}),
);
return;
}
inFlightBytes += declared;
inFlightByUser.set(user, userBytes + declared);
res.once('close', () => {
inFlightBytes -= declared;
const left = (inFlightByUser.get(user) ?? 0) - declared;
if (left > 0) inFlightByUser.set(user, left);
else inFlightByUser.delete(user);
});
json(req, res, (err?: unknown) => {
if (err) {
next(err);
return;
}
textAsJson(req, res, (err?: unknown) => {
if (err) {
next(err);
return;
}
if (accepts && !accepts(req)) {
// The same answer the default limit gives.
next(
new HttpError(413, 'request entity too large', {
legacyCode: 'client_bad_request',
}),
);
return;
}
next();
});
});
next();
});
};
};
+9 -1
View File
@@ -170,8 +170,16 @@ export interface ScheduleServiceContract {
request: ScheduleListRequest,
): Promise<PageResult<ScheduleView>>;
get(actor: Actor, scheduleId: unknown): Promise<ScheduleView>;
update(
actor: Actor,
scheduleId: unknown,
changes: unknown,
): Promise<ScheduleView>;
remove(actor: Actor, scheduleId: unknown): Promise<void>;
receivePeerChanges(body: unknown): Promise<{ applied: number }>;
/** `results`: each change's index outcome, in order (`null` if dropped). */
receivePeerChanges(
body: unknown,
): Promise<{ applied: number; results?: Array<number | null> }>;
/** Checks a caller supplying `sendAt`; `events_disabled` when off. */
prepareSendAt(actor: Actor, sendAt: unknown): Promise<DeferredSendPlan>;
createDeferredAppMessage(
@@ -355,6 +355,17 @@ describe('ChatCompletionDriver.complete auth and model resolution', () => {
).rejects.toMatchObject({ statusCode: 400 });
});
it('rejects a model that is not a string with 400', async () => {
await expect(
withTestActor(() =>
driver.complete({
messages: [{ role: 'user', content: 'hi' }],
model: { id: 'gpt' },
} as unknown as ICompleteArguments),
),
).rejects.toMatchObject({ statusCode: 400 });
});
it('routes by alias when a provider exposes one (puterId is auto-aliased on the bucket)', async () => {
// Inject a model that carries a `puterId` so we can verify the
// alias bucket resolves back to the canonical id. Spy on
@@ -2222,3 +2233,166 @@ describe('ChatCompletionDriver.countTokens', () => {
).rejects.toMatchObject({ statusCode: 400 });
});
});
describe('ChatCompletionDriver service speed', () => {
it.each([
[{ serviceSpeed: 'ultrafast' }, 'fast', 0.028],
[{ speed: 'fast' }, 'fast', 0.028],
[{ serviceSpeed: 'standard', speed: 'fast' }, 'standard', 0.014],
] as const)('uses the Claude catalog rate card for %j', async (options, speed, cents) => {
const sent: Record<string, unknown>[] = [];
vi.stubGlobal('fetch', async (input: Request | string, init?: RequestInit) => {
const body = input instanceof Request
? await input.clone().json()
: JSON.parse(String(init?.body));
sent.push(body);
return new Response(JSON.stringify({
id: 'claude-speed-test', type: 'message', role: 'assistant',
model: body.model, stop_reason: 'end_turn',
content: [{ type: 'text', text: 'OK' }],
usage: { input_tokens: 10, output_tokens: 5, speed },
}), { headers: { 'content-type': 'application/json' } });
});
const d = new ChatCompletionDriver(
{ providers: { claude: { apiKey: 'test-key' }, ollama: { enabled: false } } } as never,
server.clients, server.stores, server.services,
);
try {
await d.onServerStart();
const result = await withTestActor(() => d.complete({
model: 'claude-opus-5-5', provider: 'claude',
messages: [{ role: 'user', content: 'Hello' }],
fallback: false, max_tokens: 32, normalize: true, ...options,
}));
expect(sent).toHaveLength(1);
expect(sent[0]!.speed).toBe(speed === 'fast' ? 'fast' : undefined);
expect(result).toMatchObject({
message: { content: 'OK' }, usage: { usd_cents: cents },
});
} finally {
d.onServerShutdown();
vi.unstubAllGlobals();
}
});
it.each([
null, false, true, 0, 1, -1, NaN, Infinity, '', 'invalid', 'FAST',
'fast ', ' fast', 'ultraFast', [], ['fast'], {}, { speed: 'fast' },
{ toString: 'fast' },
])('rejects invalid speed %j before sending a request', async (serviceSpeed) => {
await expect(
withTestActor(() =>
driver.complete({
model: 'fake',
messages: [{ role: 'user', content: 'Hello' }],
serviceSpeed: serviceSpeed as never,
}),
),
).rejects.toMatchObject({
statusCode: 400,
legacyCode: 'invalid_service_speed',
});
});
it.each([
['openai-responses', true],
['openai-responses', false],
['openai-completion', false],
] as const)(
'settles unavailable tiers at standard rates on %s with provider fallback disabled (admission rejection: %s)',
async (provider, rejectFast) => {
const sent: Record<string, unknown>[] = [];
vi.stubGlobal(
'fetch',
async (_input: unknown, init?: RequestInit) => {
const body =
_input instanceof Request
? await _input.clone().json()
: JSON.parse(String(init?.body));
sent.push(body);
if (rejectFast && body.service_tier !== 'default') {
return new Response(
JSON.stringify({
error: {
message: `${body.service_tier} service_tier capacity unavailable`,
type: 'invalid_request_error',
},
}),
{
status: 400,
headers: { 'content-type': 'application/json' },
},
);
}
return new Response(
JSON.stringify({
id: 'response-test',
object: 'response',
model: body.model,
status: 'completed',
service_tier: 'default',
output: [
{
type: 'message',
role: 'assistant',
content: [
{ type: 'output_text', text: 'OK' },
],
},
],
usage: {
input_tokens: 10,
output_tokens: 2,
input_tokens_details: { cached_tokens: 0 },
},
}),
{ headers: { 'content-type': 'application/json' } },
);
},
);
const d = new ChatCompletionDriver(
{
providers: {
'openai-completion': { apiKey: 'test-key' },
ollama: { enabled: false },
},
} as never,
server.clients,
server.stores,
server.services,
);
try {
await d.onServerStart();
const result = (await withTestActor(() =>
d.complete({
model: 'gpt-6.1-sol',
provider,
messages: [{ role: 'user', content: 'Hello' }],
serviceSpeed: 'ultrafast',
fallback: false,
max_tokens: 32,
normalize: true,
}),
)) as {
message: { content: string };
usageDetails: { serviceSpeed: string };
usage: { usd_cents: number };
};
expect(sent.map((body) => body.service_tier)).toEqual(
rejectFast
? ['ultrafast', 'priority', 'default']
: ['ultrafast'],
);
expect(sent.every((body) => body.model === 'gpt-6.1-sol')).toBe(
true,
);
expect(result.message.content).toBe('OK');
expect(result.usageDetails.serviceSpeed).toBe('standard');
expect(result.usage.usd_cents).toBeCloseTo(0.004, 8);
} finally {
d.onServerShutdown();
vi.unstubAllGlobals();
}
},
);
});
@@ -78,6 +78,12 @@ import type {
UsageDetails,
} from './types.js';
import { normalize_tools_object } from './utils/FunctionCalling.js';
import {
requestedServiceSpeed,
selectServiceSpeed,
lowerServiceSpeed,
isServiceSpeedUnavailable,
} from './utils/serviceSpeed.js';
import {
messagesHavePuterPaths,
modelSupportsModality,
@@ -674,6 +680,16 @@ export class ChatCompletionDriver extends PuterDriver {
}
async complete(args: ICompleteArguments): Promise<IChatCompleteResult> {
if (
args.serviceSpeed !== undefined &&
!['standard', 'fast', 'ultrafast'].includes(args.serviceSpeed)
) {
throw new HttpError(
400,
'serviceSpeed must be standard, fast, or ultrafast',
{ legacyCode: 'invalid_service_speed' },
);
}
const abortSignal = Context.get('abortSignal');
abortSignal?.throwIfAborted();
const actor = Context.get('actor');
@@ -700,15 +716,16 @@ export class ChatCompletionDriver extends PuterDriver {
args.model = this.#providers[intendedProvider].getDefaultModel();
}
let model = await this.#resolveLoadedModel(
const initialModel = await this.#resolveLoadedModel(
args.model,
intendedProvider,
);
if (!model) {
if (!initialModel) {
throw new HttpError(400, `Model not found: ${args.model}`, {
legacyCode: 'bad_request',
});
}
let model: IChatModel = initialModel;
// A pinned provider without a route for the model normally resolves
// to another vendor; with `fallback: false` that is the one thing the
// caller asked us not to do.
@@ -840,18 +857,6 @@ export class ChatCompletionDriver extends PuterDriver {
// The instant the current attempt is priced at, from its hold to its
// charge, so a rate change mid-request can't split the two.
let pricingTime = new Date();
if (!useFakeProvider) {
({
hold,
fundsCap,
costFactor,
promptTokenEstimate: attemptPromptTokenEstimate,
} = await this.#applyCreditGate(actor, model, args, {
promptTokenEstimate,
requestedMaxTokens,
pricingTime,
}));
}
// First attempt
const provider = this.#providers[model.provider!];
@@ -899,24 +904,132 @@ export class ChatCompletionDriver extends PuterDriver {
return attempt;
};
let variantSpeed: ICompleteArguments['serviceSpeed'];
let creditGateError: unknown;
const runAttempt = async (
attemptProvider: IChatProvider,
attemptModel: IChatModel,
baseModel: IChatModel,
) => {
if (!useFakeProvider) {
await this.#resolvePuterPaths(attemptProvider, args, actor);
}
// Last point where a caller who left costs nothing.
abortSignal?.throwIfAborted();
return attemptProvider.complete(
{
...args,
let requestedSpeed = requestedServiceSpeed(
args,
baseModel.provider,
);
const offers =
requestedSpeed !== undefined && requestedSpeed !== 'standard'
? ((await attemptProvider.serviceSpeedModels?.(
baseModel,
)) ?? {})
: {};
for (;;) {
const selection = selectServiceSpeed(
baseModel,
{ ...args, serviceSpeed: requestedSpeed },
(id) => {
const variant = this.#resolveModel(
id,
baseModel.provider!,
);
return variant &&
variant.provider === baseModel.provider
? variant
: undefined;
},
offers,
);
const attemptModel = selection.model;
const requestArgs = {
...selection.args,
model: attemptModel.id,
provider: attemptModel.provider,
},
this.#catalogEntries.get(attemptModel),
pricingTime,
);
};
const catalogModel = this.#resolveModel(
attemptModel.id,
attemptModel.provider!,
);
const rawModel = this.#catalogEntries.get(
catalogModel ?? baseModel,
);
const snapshot = rawModel
? {
...rawModel,
costs: attemptModel.costs,
pricingOverrides: attemptModel.pricingOverrides,
serviceSpeedPricing: attemptModel.serviceSpeedPricing,
}
: attemptModel;
if (!useFakeProvider) {
try {
({
hold,
fundsCap,
costFactor,
promptTokenEstimate: attemptPromptTokenEstimate,
} = await this.#applyCreditGate(
actor,
attemptModel,
requestArgs,
{
promptTokenEstimate,
requestedMaxTokens,
pricingTime,
},
));
} catch (error) {
creditGateError = error;
throw error;
}
await this.#resolvePuterPaths(
attemptProvider,
requestArgs,
actor,
);
}
abortSignal?.throwIfAborted();
try {
const result = await attemptProvider.complete(
requestArgs,
snapshot,
pricingTime,
);
model = attemptModel;
variantSpeed =
attemptModel.id !== baseModel.id
? selection.speed
: undefined;
if (
args.serviceSpeed !== undefined &&
'message' in result
) {
const messageResult = result as IChatMessageResult;
const details =
messageResult.usageDetails ??
usageDetailsFromUsage(messageResult.usage, model);
messageResult.usageDetails = {
...details,
serviceSpeed:
variantSpeed ??
details?.serviceSpeed ??
details?.speed ??
'standard',
};
}
return result;
} catch (error) {
await hold.release();
hold = NO_CREDIT_HOLD;
if (
args.serviceSpeed === undefined ||
selection.speed === 'standard' ||
!isServiceSpeedUnavailable(
error,
attemptModel.id !== baseModel.id,
)
)
throw error;
requestedSpeed = lowerServiceSpeed(selection.speed);
pricingTime = new Date();
}
}
};
try {
@@ -984,29 +1097,17 @@ export class ChatCompletionDriver extends PuterDriver {
// The previous attempt released its hold when it failed, so
// this one starts from nothing held.
pricingTime = new Date();
if (!useFakeProvider) {
({
hold,
fundsCap,
costFactor,
promptTokenEstimate: attemptPromptTokenEstimate,
} = await this.#applyCreditGate(actor, fallback, args, {
promptTokenEstimate,
requestedMaxTokens,
pricingTime,
}));
}
tried.add(routeId(fallback.provider!, fallback.id));
try {
res = await runAttempt(fbProvider, fallback);
model = fallback;
lastError = null;
console.warn(
`[ai-chat] fallback served (${completionId}, ${first.provider}:${first.model} -> ${fallback.provider}:${fallback.id}, first ${first.status ?? 'none'}${first.upstreamType ? `/${first.upstreamType}` : ''})`,
);
} catch (fbErr) {
if (fbErr === creditGateError) throw fbErr;
await hold.release();
hold = NO_CREDIT_HOLD;
abortSignal?.throwIfAborted();
@@ -1162,6 +1263,20 @@ export class ChatCompletionDriver extends PuterDriver {
usageDetailsFromUsage(usage, model),
);
}
if (
args.serviceSpeed !== undefined &&
chatStream.usageDetails
) {
const details = chatStream.usageDetails;
chatStream.setUsageDetails({
...details,
serviceSpeed:
variantSpeed ??
details.serviceSpeed ??
details.speed ??
'standard',
});
}
withClaudeThinkingTokens(
enrichedUsage,
model,
@@ -1474,12 +1589,7 @@ export class ChatCompletionDriver extends PuterDriver {
const metering = this.services.metering;
const { requestedMaxTokens, pricingTime } = estimates;
let { promptTokenEstimate } = estimates;
// A provider can name its own cost keys for this request (Claude's
// fast-mode rate card), cap its output, and size an extra reservation
// the per-token math can't see (a web-search/advisor tool that could
// run several times before the model answers) — the same clamps it
// applies when building the request, so the hold and the request
// agree.
// Providers reserve tool calls using the same caps they send upstream.
const pricing =
this.#providers[model.provider!]?.requestPricing?.(args, model, {
promptTokenEstimate,
@@ -2019,7 +2129,9 @@ export class ChatCompletionDriver extends PuterDriver {
}
#resolveModel(modelId: string, provider?: string): IChatModel | null {
const models = this.#modelIdMap[normalizeModelKey(modelId ?? '')];
// `model` comes straight from the caller and may not be a string.
if (typeof modelId !== 'string') return null;
const models = this.#modelIdMap[normalizeModelKey(modelId)];
if (!models || models.length === 0) return null;
// An explicitly requested provider is honoured even if its route is
// marked — the caller asked for that one, not for the cheapest hop.
@@ -41,6 +41,7 @@ import {
meterChatUsage,
type MeterChatUsageOptions,
} from '../utils/meterChatUsage.js';
import { servedServiceSpeed } from '../utils/serviceSpeed.js';
import { catalogPrice, costKeys } from '../utils/pricing.js';
import { normalizeModelKey } from '../utils/modelRouting.js';
import * as OpenAIUtil from '../utils/OpenAIUtil.js';
@@ -232,6 +233,8 @@ export class OpenAICompatProvider implements IChatProvider {
)
: {}),
};
if (args.serviceSpeed !== undefined && args.service_tier !== undefined)
shared.service_tier = args.service_tier;
const params = this.vendorParams(shared, args, model, actor);
let pricingTime = attemptPricingTime ?? new Date();
@@ -271,15 +274,29 @@ export class OpenAICompatProvider implements IChatProvider {
source,
model,
);
if (usageDetails) source.setUsageDetails?.(usageDetails);
const serviceSpeed = servedServiceSpeed(source);
if (usageDetails)
source.setUsageDetails?.({
...usageDetails,
...(args.serviceSpeed !== undefined
? { serviceSpeed }
: {}),
});
const metered = meterChatUsage(
this.#metering,
actor,
this.meteringModelKey(model.id),
model,
usage,
{ ...meterOptions, pricingTime },
{ ...meterOptions, pricingTime, serviceSpeed },
);
if (args.serviceSpeed !== undefined && !usageDetails) {
const details = OpenAIUtil.usageDetailsFromTrackedUsage(
metered.usage,
);
if (details)
source.setUsageDetails?.({ ...details, serviceSpeed });
}
source.setUsageCosts(metered.costs);
return this.reportedUsage(metered.usage);
},
@@ -174,6 +174,9 @@ export const mapAlibabaCatalogModel = (
: undefined;
return {
...existing,
serviceSpeedVariants: {
fast: id === 'glm-5.2' ? 'glm-5.2-fast-preview' : `${id}-prime`,
},
id,
puterId,
name: raw.name ?? existing?.name ?? id,
@@ -37,6 +37,7 @@ export const ALIBABA_MODELS: IChatModel[] = [
costs_currency: 'usd-cents',
input_cost_key: 'prompt_tokens',
output_cost_key: 'completion_tokens',
serviceSpeedVariants: { fast: 'qwen-max-prime' },
costs: {
tokens: 1_000_000,
prompt_tokens: 160,
@@ -60,6 +61,7 @@ export const ALIBABA_MODELS: IChatModel[] = [
costs_currency: 'usd-cents',
input_cost_key: 'prompt_tokens',
output_cost_key: 'completion_tokens',
serviceSpeedVariants: { fast: 'qwen-plus-prime' },
costs: {
tokens: 1_000_000,
prompt_tokens: 40,
@@ -81,6 +83,7 @@ export const ALIBABA_MODELS: IChatModel[] = [
costs_currency: 'usd-cents',
input_cost_key: 'prompt_tokens',
output_cost_key: 'completion_tokens',
serviceSpeedVariants: { fast: 'qwen3.5-plus-prime' },
costs: {
tokens: 1_000_000,
prompt_tokens: 40,
@@ -102,6 +105,7 @@ export const ALIBABA_MODELS: IChatModel[] = [
costs_currency: 'usd-cents',
input_cost_key: 'prompt_tokens',
output_cost_key: 'completion_tokens',
serviceSpeedVariants: { fast: 'qwen3.6-plus-prime' },
costs: {
tokens: 1_000_000,
prompt_tokens: 50,
@@ -123,6 +127,7 @@ export const ALIBABA_MODELS: IChatModel[] = [
costs_currency: 'usd-cents',
input_cost_key: 'prompt_tokens',
output_cost_key: 'completion_tokens',
serviceSpeedVariants: { fast: 'qwen3.6-flash-prime' },
costs: {
tokens: 1_000_000,
prompt_tokens: 19,
@@ -143,6 +148,7 @@ export const ALIBABA_MODELS: IChatModel[] = [
costs_currency: 'usd-cents',
input_cost_key: 'prompt_tokens',
output_cost_key: 'completion_tokens',
serviceSpeedVariants: { fast: 'qwen3.7-plus-prime' },
costs: {
tokens: 1_000_000,
prompt_tokens: 50,
@@ -164,6 +170,7 @@ export const ALIBABA_MODELS: IChatModel[] = [
costs_currency: 'usd-cents',
input_cost_key: 'prompt_tokens',
output_cost_key: 'completion_tokens',
serviceSpeedVariants: { fast: 'qwen3.7-max-prime' },
costs: {
tokens: 1_000_000,
prompt_tokens: 250,
@@ -188,6 +195,7 @@ export const ALIBABA_MODELS: IChatModel[] = [
costs_currency: 'usd-cents',
input_cost_key: 'prompt_tokens',
output_cost_key: 'completion_tokens',
serviceSpeedVariants: { fast: 'qwen3.8-max-prime' },
costs: {
tokens: 1_000_000,
prompt_tokens: 200,
@@ -210,6 +218,7 @@ export const ALIBABA_MODELS: IChatModel[] = [
costs_currency: 'usd-cents',
input_cost_key: 'prompt_tokens',
output_cost_key: 'completion_tokens',
serviceSpeedVariants: { fast: 'qwen3.8-max-0902-prime' },
costs: {
tokens: 1_000_000,
prompt_tokens: 200,
@@ -234,6 +243,7 @@ export const ALIBABA_MODELS: IChatModel[] = [
costs_currency: 'usd-cents',
input_cost_key: 'prompt_tokens',
output_cost_key: 'completion_tokens',
serviceSpeedVariants: { fast: 'qwen-flash-prime' },
costs: {
tokens: 1_000_000,
prompt_tokens: 5,
@@ -257,6 +267,7 @@ export const ALIBABA_MODELS: IChatModel[] = [
costs_currency: 'usd-cents',
input_cost_key: 'prompt_tokens',
output_cost_key: 'completion_tokens',
serviceSpeedVariants: { fast: 'qwen3-coder-flash-prime' },
costs: {
tokens: 1_000_000,
prompt_tokens: 30,
@@ -282,6 +293,7 @@ export const ALIBABA_MODELS: IChatModel[] = [
costs_currency: 'usd-cents',
input_cost_key: 'prompt_tokens',
output_cost_key: 'completion_tokens',
serviceSpeedVariants: { fast: 'qwen3.5-397b-a17b-prime' },
costs: {
tokens: 1_000_000,
prompt_tokens: 60,
@@ -305,6 +317,7 @@ export const ALIBABA_MODELS: IChatModel[] = [
costs_currency: 'usd-cents',
input_cost_key: 'prompt_tokens',
output_cost_key: 'completion_tokens',
serviceSpeedVariants: { fast: 'qwen3.5-122b-a10b-prime' },
costs: {
tokens: 1_000_000,
prompt_tokens: 40,
@@ -328,6 +341,7 @@ export const ALIBABA_MODELS: IChatModel[] = [
costs_currency: 'usd-cents',
input_cost_key: 'prompt_tokens',
output_cost_key: 'completion_tokens',
serviceSpeedVariants: { fast: 'qwen3.5-35b-a3b-prime' },
costs: {
tokens: 1_000_000,
prompt_tokens: 25,
@@ -351,6 +365,7 @@ export const ALIBABA_MODELS: IChatModel[] = [
costs_currency: 'usd-cents',
input_cost_key: 'prompt_tokens',
output_cost_key: 'completion_tokens',
serviceSpeedVariants: { fast: 'qwen3.5-27b-prime' },
costs: {
tokens: 1_000_000,
prompt_tokens: 30,
@@ -376,6 +391,7 @@ export const ALIBABA_MODELS: IChatModel[] = [
costs_currency: 'usd-cents',
input_cost_key: 'prompt_tokens',
output_cost_key: 'completion_tokens',
serviceSpeedVariants: { fast: 'qwen3.6-35b-a3b-prime' },
costs: {
tokens: 1_000_000,
prompt_tokens: 24.8,
@@ -399,6 +415,7 @@ export const ALIBABA_MODELS: IChatModel[] = [
costs_currency: 'usd-cents',
input_cost_key: 'prompt_tokens',
output_cost_key: 'completion_tokens',
serviceSpeedVariants: { fast: 'qwen3.6-27b-prime' },
costs: {
tokens: 1_000_000,
prompt_tokens: 60,
@@ -422,6 +439,7 @@ export const ALIBABA_MODELS: IChatModel[] = [
costs_currency: 'usd-cents',
input_cost_key: 'prompt_tokens',
output_cost_key: 'completion_tokens',
serviceSpeedVariants: { fast: 'qwen3-vl-plus-prime' },
costs: {
tokens: 1_000_000,
prompt_tokens: 20,
@@ -447,6 +465,7 @@ export const ALIBABA_MODELS: IChatModel[] = [
costs_currency: 'usd-cents',
input_cost_key: 'prompt_tokens',
output_cost_key: 'completion_tokens',
serviceSpeedVariants: { fast: 'qwen3-omni-flash-prime' },
costs: {
tokens: 1_000_000,
prompt_tokens: 43,
@@ -469,6 +488,7 @@ export const ALIBABA_MODELS: IChatModel[] = [
costs_currency: 'usd-cents',
input_cost_key: 'prompt_tokens',
output_cost_key: 'completion_tokens',
serviceSpeedVariants: { fast: 'qwen-mt-plus-prime' },
costs: {
tokens: 1_000_000,
prompt_tokens: 246,
@@ -491,6 +511,7 @@ export const ALIBABA_MODELS: IChatModel[] = [
costs_currency: 'usd-cents',
input_cost_key: 'prompt_tokens',
output_cost_key: 'completion_tokens',
serviceSpeedVariants: { fast: 'qwen-plus-2025-01-25-prime' },
costs: {
tokens: 1_000_000,
prompt_tokens: 40,
@@ -511,6 +532,7 @@ export const ALIBABA_MODELS: IChatModel[] = [
costs_currency: 'usd-cents',
input_cost_key: 'prompt_tokens',
output_cost_key: 'completion_tokens',
serviceSpeedVariants: { fast: 'qwen-plus-2025-04-28-prime' },
costs: {
tokens: 1_000_000,
prompt_tokens: 40,
@@ -531,6 +553,7 @@ export const ALIBABA_MODELS: IChatModel[] = [
costs_currency: 'usd-cents',
input_cost_key: 'prompt_tokens',
output_cost_key: 'completion_tokens',
serviceSpeedVariants: { fast: 'qwen-plus-2025-07-14-prime' },
costs: {
tokens: 1_000_000,
prompt_tokens: 40,
@@ -553,6 +576,7 @@ export const ALIBABA_MODELS: IChatModel[] = [
costs_currency: 'usd-cents',
input_cost_key: 'prompt_tokens',
output_cost_key: 'completion_tokens',
serviceSpeedVariants: { fast: 'qwen-plus-2025-12-01-prime' },
costs: {
tokens: 1_000_000,
prompt_tokens: 40,
@@ -574,6 +598,7 @@ export const ALIBABA_MODELS: IChatModel[] = [
costs_currency: 'usd-cents',
input_cost_key: 'prompt_tokens',
output_cost_key: 'completion_tokens',
serviceSpeedVariants: { fast: 'qwen3.7-max-2026-05-20-prime' },
costs: {
tokens: 1_000_000,
prompt_tokens: 250,
@@ -594,6 +619,7 @@ export const ALIBABA_MODELS: IChatModel[] = [
costs_currency: 'usd-cents',
input_cost_key: 'prompt_tokens',
output_cost_key: 'completion_tokens',
serviceSpeedVariants: { fast: 'qwen3.7-max-2026-06-08-prime' },
costs: {
tokens: 1_000_000,
prompt_tokens: 250,
@@ -614,6 +640,7 @@ export const ALIBABA_MODELS: IChatModel[] = [
costs_currency: 'usd-cents',
input_cost_key: 'prompt_tokens',
output_cost_key: 'completion_tokens',
serviceSpeedVariants: { fast: 'qwen3.7-max-2026-05-17-prime' },
costs: {
tokens: 1_000_000,
prompt_tokens: 250,
@@ -635,6 +662,7 @@ export const ALIBABA_MODELS: IChatModel[] = [
costs_currency: 'usd-cents',
input_cost_key: 'prompt_tokens',
output_cost_key: 'completion_tokens',
serviceSpeedVariants: { fast: 'qwen3.7-max-preview-prime' },
costs: {
tokens: 1_000_000,
prompt_tokens: 250,
@@ -657,6 +685,7 @@ export const ALIBABA_MODELS: IChatModel[] = [
costs_currency: 'usd-cents',
input_cost_key: 'prompt_tokens',
output_cost_key: 'completion_tokens',
serviceSpeedVariants: { fast: 'qwen3.5-plus-2026-02-15-prime' },
costs: {
tokens: 1_000_000,
prompt_tokens: 40,
@@ -678,6 +707,7 @@ export const ALIBABA_MODELS: IChatModel[] = [
costs_currency: 'usd-cents',
input_cost_key: 'prompt_tokens',
output_cost_key: 'completion_tokens',
serviceSpeedVariants: { fast: 'qwen3.5-plus-2026-04-20-prime' },
costs: {
tokens: 1_000_000,
prompt_tokens: 40,
@@ -700,6 +730,7 @@ export const ALIBABA_MODELS: IChatModel[] = [
costs_currency: 'usd-cents',
input_cost_key: 'prompt_tokens',
output_cost_key: 'completion_tokens',
serviceSpeedVariants: { fast: 'qwen3.5-flash-prime' },
costs: {
tokens: 1_000_000,
prompt_tokens: 10,
@@ -722,6 +753,7 @@ export const ALIBABA_MODELS: IChatModel[] = [
costs_currency: 'usd-cents',
input_cost_key: 'prompt_tokens',
output_cost_key: 'completion_tokens',
serviceSpeedVariants: { fast: 'qwen3.7-flash-prime' },
costs: {
tokens: 1_000_000,
prompt_tokens: 3,
@@ -743,6 +775,7 @@ export const ALIBABA_MODELS: IChatModel[] = [
costs_currency: 'usd-cents',
input_cost_key: 'prompt_tokens',
output_cost_key: 'completion_tokens',
serviceSpeedVariants: { fast: 'qwen3.8-flash-prime' },
costs: {
tokens: 1_000_000,
prompt_tokens: 15,
@@ -765,6 +798,7 @@ export const ALIBABA_MODELS: IChatModel[] = [
costs_currency: 'usd-cents',
input_cost_key: 'prompt_tokens',
output_cost_key: 'completion_tokens',
serviceSpeedVariants: { fast: 'qwen3.8-27b-prime' },
costs: {
tokens: 1_000_000,
prompt_tokens: 50,
@@ -785,6 +819,7 @@ export const ALIBABA_MODELS: IChatModel[] = [
costs_currency: 'usd-cents',
input_cost_key: 'prompt_tokens',
output_cost_key: 'completion_tokens',
serviceSpeedVariants: { fast: 'qwen3.8-2.4t-a95b-prime' },
costs: {
tokens: 1_000_000,
prompt_tokens: 200,
@@ -809,6 +844,7 @@ export const ALIBABA_MODELS: IChatModel[] = [
costs_currency: 'usd-cents',
input_cost_key: 'prompt_tokens',
output_cost_key: 'completion_tokens',
serviceSpeedVariants: { fast: 'qwen3.5-omni-flash-prime' },
costs: {
tokens: 1_000_000,
prompt_tokens: 40,
@@ -832,6 +868,7 @@ export const ALIBABA_MODELS: IChatModel[] = [
costs_currency: 'usd-cents',
input_cost_key: 'prompt_tokens',
output_cost_key: 'completion_tokens',
serviceSpeedVariants: { fast: 'qwen3.5-omni-plus-prime' },
costs: {
tokens: 1_000_000,
prompt_tokens: 140,
@@ -855,6 +892,7 @@ export const ALIBABA_MODELS: IChatModel[] = [
costs_currency: 'usd-cents',
input_cost_key: 'prompt_tokens',
output_cost_key: 'completion_tokens',
serviceSpeedVariants: { fast: 'qwen3.8-omni-flash-prime' },
costs: {
tokens: 1_000_000,
prompt_tokens: 15,
@@ -877,6 +915,7 @@ export const ALIBABA_MODELS: IChatModel[] = [
costs_currency: 'usd-cents',
input_cost_key: 'prompt_tokens',
output_cost_key: 'completion_tokens',
serviceSpeedVariants: { fast: 'qwen-mt-flash-prime' },
costs: {
tokens: 1_000_000,
prompt_tokens: 16,
@@ -897,6 +936,7 @@ export const ALIBABA_MODELS: IChatModel[] = [
costs_currency: 'usd-cents',
input_cost_key: 'prompt_tokens',
output_cost_key: 'completion_tokens',
serviceSpeedVariants: { fast: 'qwen-mt-lite-prime' },
costs: {
tokens: 1_000_000,
prompt_tokens: 12,
@@ -919,6 +959,7 @@ export const ALIBABA_MODELS: IChatModel[] = [
costs_currency: 'usd-cents',
input_cost_key: 'prompt_tokens',
output_cost_key: 'completion_tokens',
serviceSpeedVariants: { fast: 'glm-5.1-prime' },
costs: {
tokens: 1_000_000,
prompt_tokens: 140,
@@ -938,6 +979,7 @@ export const ALIBABA_MODELS: IChatModel[] = [
costs_currency: 'usd-cents',
input_cost_key: 'prompt_tokens',
output_cost_key: 'completion_tokens',
serviceSpeedVariants: { fast: 'glm-5.2-fast-preview' },
costs: {
tokens: 1_000_000,
prompt_tokens: 140,
@@ -958,6 +1000,7 @@ export const ALIBABA_MODELS: IChatModel[] = [
costs_currency: 'usd-cents',
input_cost_key: 'prompt_tokens',
output_cost_key: 'completion_tokens',
serviceSpeedVariants: { fast: 'glm-5.2-fast-preview-prime' },
costs: {
tokens: 1_000_000,
prompt_tokens: 280,
@@ -981,6 +1024,7 @@ export const ALIBABA_MODELS: IChatModel[] = [
costs_currency: 'usd-cents',
input_cost_key: 'prompt_tokens',
output_cost_key: 'completion_tokens',
serviceSpeedVariants: { fast: 'deepseek-v4-flash-0731-prime' },
costs: {
tokens: 1_000_000,
prompt_tokens: 44,
@@ -1003,6 +1047,7 @@ export const ALIBABA_MODELS: IChatModel[] = [
costs_currency: 'usd-cents',
input_cost_key: 'prompt_tokens',
output_cost_key: 'completion_tokens',
serviceSpeedVariants: { fast: 'deepseek-v4.1-flash-prime' },
costs: {
tokens: 1_000_000,
prompt_tokens: 30,
@@ -1023,6 +1068,7 @@ export const ALIBABA_MODELS: IChatModel[] = [
costs_currency: 'usd-cents',
input_cost_key: 'prompt_tokens',
output_cost_key: 'completion_tokens',
serviceSpeedVariants: { fast: 'deepseek-v4-pro-prime' },
costs: {
tokens: 1_000_000,
prompt_tokens: 240,
@@ -1045,6 +1091,7 @@ export const ALIBABA_MODELS: IChatModel[] = [
costs_currency: 'usd-cents',
input_cost_key: 'prompt_tokens',
output_cost_key: 'completion_tokens',
serviceSpeedVariants: { fast: 'deepseek-v4-pro-0813-prime' },
costs: {
tokens: 1_000_000,
prompt_tokens: 132,
@@ -1065,6 +1112,7 @@ export const ALIBABA_MODELS: IChatModel[] = [
costs_currency: 'usd-cents',
input_cost_key: 'prompt_tokens',
output_cost_key: 'completion_tokens',
serviceSpeedVariants: { fast: 'kimi-k2.7-code-prime' },
costs: {
tokens: 1_000_000,
prompt_tokens: 95,
@@ -20,6 +20,10 @@
import { HttpError } from '@heyputer/backend/src/core/http/HttpError.js';
import { OpenAI } from 'openai';
import { ChatCompletionCreateParams } from 'openai/resources/index.js';
import {
serviceSpeedBillingModel,
servedServiceSpeed,
} from '../../utils/serviceSpeed.js';
import { Context } from '../../../../core/context.js';
import type { FSService } from '../../../../services/fs/FSService.js';
import type { MeteringService } from '../../../../services/metering/MeteringService.js';
@@ -153,6 +157,7 @@ export class AzureChatProvider implements IChatProvider {
async complete(
params: ICompleteArguments,
resolved?: IChatModel,
): ReturnType<IChatProvider['complete']> {
const {
max_tokens,
@@ -180,7 +185,9 @@ export class AzureChatProvider implements IChatProvider {
{ legacyCode: 'bad_request' },
);
}
return await this.#responsesProvider.complete(params);
return await (resolved
? this.#responsesProvider.complete(params, resolved)
: this.#responsesProvider.complete(params));
}
// Inline compaction is a Responses-API feature; chat.completions can't
// express `context_management` or a `compaction` content block.
@@ -194,7 +201,9 @@ export class AzureChatProvider implements IChatProvider {
{ legacyCode: 'bad_request' },
);
}
return await this.#responsesProvider.complete(params);
return await (resolved
? this.#responsesProvider.complete(params, resolved)
: this.#responsesProvider.complete(params));
}
// Validate messages
if (!Array.isArray(messages)) {
@@ -207,9 +216,11 @@ export class AzureChatProvider implements IChatProvider {
model = model ?? this.#defaultModel;
const modelUsed =
this.models().find((m) =>
resolved ??
(this.models().find((m) =>
[m.id, ...(m.aliases || [])].includes(model),
) || this.models().find((m) => m.id === this.getDefaultModel())!;
) ||
this.models().find((m) => m.id === this.getDefaultModel())!);
// messages.unshift({
// role: 'system',
@@ -279,6 +290,9 @@ export class AzureChatProvider implements IChatProvider {
}),
messages: messages,
model: modelUsed.id,
...(params.service_tier !== undefined
? { service_tier: params.service_tier }
: {}),
...(mappedTools?.length ? { tools: mappedTools } : {}),
...(max_tokens !== undefined
? { max_completion_tokens: max_tokens }
@@ -315,7 +329,12 @@ export class AzureChatProvider implements IChatProvider {
);
return OpenAiUtil.handle_completion_output({
usage_calculator: ({ usage }) => {
usage_calculator: ({
service_tier,
usage,
setUsageCosts,
setUsageDetails,
}) => {
const cachedTokens =
usage.prompt_tokens_details?.cached_tokens ?? 0;
const trackedUsage = {
@@ -335,9 +354,20 @@ export class AzureChatProvider implements IChatProvider {
const costsOverrideFromModel = buildCostsOverride(
trackedUsage,
modelUsed,
serviceSpeedBillingModel(
modelUsed,
servedServiceSpeed({ service_tier }),
),
);
setUsageCosts(costsOverrideFromModel);
if (params.serviceSpeed !== undefined)
setUsageDetails({
...OpenAiUtil.usageDetailsFromTrackedUsage(
trackedUsage,
)!,
serviceSpeed: servedServiceSpeed({ service_tier }),
});
this.#meteringService.utilRecordUsageObject(
trackedUsage,
actor!,
@@ -449,6 +449,22 @@ describe('AzureResponsesProvider.complete request shape', () => {
expect(args.service_tier).toBe('default');
});
it('sends the wire spelling of the in-memory cache retention', async () => {
const provider = makeProvider();
responsesCreateMock.mockResolvedValueOnce(okResponse);
await withTestActor(() =>
provider.complete({
model: 'gpt-5.3-codex',
messages: [{ role: 'user', content: 'hi' }],
prompt_cache_retention: 'in-memory',
} as never),
);
const [args] = responsesCreateMock.mock.calls[0]!;
expect(args.prompt_cache_retention).toBe('in_memory');
});
it.each([
['previous_response_id', 'resp_1'],
['conversation', 'conv_1'],
@@ -19,6 +19,10 @@
import { OpenAI } from 'openai';
import { ResponseCreateParams } from 'openai/resources/responses/responses.mjs';
import {
serviceSpeedBillingModel,
servedServiceSpeed,
} from '../../utils/serviceSpeed.js';
import { Context } from '../../../../core/context.js';
import type { FSService } from '../../../../services/fs/FSService.js';
import type { MeteringService } from '../../../../services/metering/MeteringService.js';
@@ -35,6 +39,7 @@ import * as OpenAiUtil from '../../utils/OpenAIUtil.js';
import {
clampReasoningEffort,
openAICompatParams,
promptCacheRetentionToWire,
rejectStatefulResponsesFields,
} from '../../utils/openaiParams.js';
import { buildCostsOverride } from '../../utils/pricing.js';
@@ -151,37 +156,41 @@ export class AzureResponsesProvider implements IChatProvider {
: {};
}
async complete({
messages,
model,
max_tokens,
moderation,
tools,
tool_choice,
parallel_tool_calls,
include,
conversation,
compaction,
context_management,
previous_response_id,
instructions,
metadata,
prompt,
prompt_cache_key,
prompt_cache_retention,
store,
top_p,
truncation,
background,
service_tier,
verbosity,
stream,
reasoning,
reasoning_effort,
temperature,
text,
outputFormat,
}: ICompleteArguments): ReturnType<IChatProvider['complete']> {
async complete(
{
messages,
model,
max_tokens,
moderation,
tools,
tool_choice,
parallel_tool_calls,
include,
conversation,
compaction,
context_management,
previous_response_id,
instructions,
metadata,
prompt,
prompt_cache_key,
prompt_cache_retention,
store,
top_p,
truncation,
background,
service_tier,
serviceSpeed: requestedServiceSpeed,
verbosity,
stream,
reasoning,
reasoning_effort,
temperature,
text,
outputFormat,
}: ICompleteArguments,
resolved?: IChatModel,
): ReturnType<IChatProvider['complete']> {
// Validate messages
if (!Array.isArray(messages)) {
throw new HttpError(400, '`messages` must be an array', {
@@ -199,16 +208,20 @@ export class AzureResponsesProvider implements IChatProvider {
model = model ?? this.#defaultModel;
const modelUsed =
this.models({ no_restrictions: true }).find((m) =>
resolved ??
(this.models({ no_restrictions: true }).find((m) =>
[m.id, ...(m.aliases || [])].includes(model),
) ||
this.models({ no_restrictions: true }).find(
(m) => m.id === this.getDefaultModel(),
)!;
this.models({ no_restrictions: true }).find(
(m) => m.id === this.getDefaultModel(),
)!);
const userIdentifier = upstreamUserIdentifier(actor);
// Cache key defaults to the actor identifier; see upstreamUserIdentifier.
const cacheKey = prompt_cache_key ?? userIdentifier;
const cacheRetention = promptCacheRetentionToWire(
prompt_cache_retention,
);
// Resolve any `puter_path` content parts into inline base64 data URLs
// before the Responses API sees them.
@@ -307,8 +320,8 @@ export class AzureResponsesProvider implements IChatProvider {
...(instructions !== undefined ? { instructions } : {}),
...(metadata !== undefined ? { metadata } : {}),
...(cacheKey !== undefined ? { prompt_cache_key: cacheKey } : {}),
...(prompt_cache_retention !== undefined
? { prompt_cache_retention }
...(cacheRetention !== undefined
? { prompt_cache_retention: cacheRetention }
: {}),
...(store !== undefined ? { store } : {}),
...(max_tokens !== undefined
@@ -331,9 +344,11 @@ export class AzureResponsesProvider implements IChatProvider {
return OpenAiUtil.handle_completion_output_responses_api({
usage_calculator: ({
usage,
service_tier,
webSearchCalls,
tool_usage,
setUsageCosts,
setUsageDetails,
}) => {
const numWebSearches: number =
// eslint-disable-next-line @typescript-eslint/no-explicit-any
@@ -359,7 +374,10 @@ export class AzureResponsesProvider implements IChatProvider {
const costsOverrideFromModel = buildCostsOverride(
trackedUsage,
modelUsed,
serviceSpeedBillingModel(
modelUsed,
servedServiceSpeed({ service_tier }),
),
);
if (numWebSearches) {
costsOverrideFromModel.web_search_calls =
@@ -370,6 +388,14 @@ export class AzureResponsesProvider implements IChatProvider {
});
}
setUsageCosts?.(costsOverrideFromModel);
if (requestedServiceSpeed !== undefined)
setUsageDetails?.({
...OpenAiUtil.usageDetailsFromTrackedUsage(
trackedUsage,
)!,
serviceSpeed: servedServiceSpeed({ service_tier }),
});
this.#meteringService.utilRecordUsageObject(
trackedUsage,
actor,
@@ -40,7 +40,11 @@ const STANDALONE = [
];
// Fields an Azure deployment genuinely differs from its source on, by puterId.
const OVERRIDES: Record<string, string[]> = {};
const OVERRIDES: Record<string, string[]> = {
'azure:x-ai/grok-4.3': ['serviceSpeedRates'],
'azure:x-ai/grok-4-20-non-reasoning': ['serviceSpeedRates'],
'azure:x-ai/grok-4-20-reasoning': ['serviceSpeedRates'],
};
const IDENTITY = ['id', 'puterId', 'aliases'];
@@ -65,6 +69,18 @@ const mirrored = AZURE_MODELS.filter(
).map((m) => [m.puterId!, m] as const);
describe('AZURE_MODELS mirroring', () => {
it('inherits OpenAI fast rates without enabling direct-only speed tiers', () => {
for (const model of AZURE_MODELS) {
expect(model.serviceSpeedRates?.ultrafast).toBeUndefined();
if (model.puterId?.startsWith('azure:x-ai/')) {
expect(model.serviceSpeedRates?.fast).toBeUndefined();
}
}
const azure = AZURE_MODELS.find((model) => model.id === 'gpt-5.4')!;
expect(azure.serviceSpeedRates).toEqual({
fast: sourceOf(azure)!.serviceSpeedRates!.fast,
});
});
it('has a direct-provider source for every entry not listed as standalone', () => {
const orphans = mirrored
.filter(([, m]) => !sourceOf(m))
@@ -22,10 +22,8 @@ import { OPEN_AI_MODELS } from '../openai/models.js';
import { XAI_MODELS } from '../xai/models.js';
/**
* An Azure deployment of a model we also serve direct. Every field but the
* identity comes from the source entry, so prices, long-context tiers and
* limits can't drift from it. `name` is the vendor-qualified name both catalogs
* share (`openai/gpt-5.4`); extra fields override the source.
* Azure shares its source model's list prices, context tiers, and limits.
* Identity and available service speeds belong to the deployment.
*/
const mirror = (
source: readonly IChatModel[],
@@ -41,6 +39,11 @@ const mirror = (
puterId: `azure:${name}`,
id: azure.id,
...shared,
serviceSpeedRates:
source === OPEN_AI_MODELS &&
shared.serviceSpeedRates?.fast !== undefined
? { fast: shared.serviceSpeedRates.fast }
: undefined,
aliases: [name],
...azure,
};
@@ -127,6 +130,13 @@ export const AZURE_MODELS: IChatModel[] = [
costs_currency: 'usd-cents',
input_cost_key: 'prompt_tokens',
output_cost_key: 'completion_tokens',
serviceSpeedRates: {
fast: {
prompt_tokens: 250,
cached_tokens: 25,
completion_tokens: 2000,
},
},
costs: {
tokens: 1_000_000,
prompt_tokens: 125,
@@ -171,6 +181,13 @@ export const AZURE_MODELS: IChatModel[] = [
costs_currency: 'usd-cents',
input_cost_key: 'prompt_tokens',
output_cost_key: 'completion_tokens',
serviceSpeedRates: {
fast: {
prompt_tokens: 45,
cached_tokens: 4.5,
completion_tokens: 360,
},
},
costs: {
tokens: 1_000_000,
prompt_tokens: 25,
@@ -147,6 +147,22 @@ describe.skipIf(skipUnlessEnv(ENV_VAR))('ClaudeProvider (integration)', () => {
},
);
it('returns a completion from claude-fable-5-2', { timeout: INTEGRATION_TEST_TIMEOUT_MS }, async () => {
const provider = buildProvider();
const result = await withTestActor(() =>
provider.complete({
model: 'claude-fable-5-2',
messages: [{ role: 'user', content: 'Reply with OK.' }],
reasoning_effort: 'low',
max_tokens: 128,
}),
);
const content = (result as {
message: { content: Array<{ type: string; text?: string }> };
}).message.content;
expect(content.find((block) => block.type === 'text')?.text?.length).toBeGreaterThan(0);
});
// (a) Claude Code-shaped system blocks, attribution header first — the
// pipeline must never merge or reorder system blocks: the header is
// only recognized by Anthropic when it is the sole content of an
@@ -1173,6 +1173,7 @@ describe('ClaudeProvider.complete request shape', () => {
});
it.each([
'claude-fable-5-2',
'claude-fable-5-1',
'claude-haiku-5-5',
'claude-opus-5-5',
@@ -1198,6 +1199,7 @@ describe('ClaudeProvider.complete request shape', () => {
);
it.each([
'claude-fable-5-2',
'claude-fable-5-1',
'claude-haiku-5-5',
'claude-opus-5-5',
@@ -1303,6 +1305,73 @@ describe('ClaudeProvider model resolution', () => {
);
});
it.each([
'claude-fable-5-2',
'claude-fable-5-2-latest',
'claude-fable-5.2',
'anthropic/claude-fable-5-2',
])(
'routes %s to Fable 5.2 with published rates',
async (model) => {
const { provider } = makeProvider();
messagesCreateMock.mockResolvedValueOnce({
content: [{ type: 'text', text: 'ok' }],
usage: {
input_tokens: 100,
output_tokens: 50,
cache_read_input_tokens: 1000,
cache_creation_input_tokens: 200,
cache_creation: {
ephemeral_5m_input_tokens: 150,
ephemeral_1h_input_tokens: 50,
},
},
});
await withTestActor(() =>
provider.complete({
model,
messages: [{ role: 'user', content: 'hi' }],
}),
);
expect(messagesCreateMock.mock.calls[0]![0].model).toBe(
'claude-fable-5-2',
);
const fable52 = CLAUDE_MODELS.find(
(m) => m.id === 'claude-fable-5-2',
)!;
expect(fable52.costs).toMatchObject({
input_tokens: 800,
output_tokens: 4000,
cache_read_input_tokens: 20,
ephemeral_5m_input_tokens: 1000,
ephemeral_1h_input_tokens: 1600,
});
expect(fable52.serviceSpeedRates?.fast).toMatchObject({
input_tokens: 1600,
output_tokens: 8000,
cache_read_input_tokens: 40,
ephemeral_5m_input_tokens: 2000,
ephemeral_1h_input_tokens: 3200,
});
expect(fable52.context).toBe(1_000_000);
expect(fable52.max_tokens).toBe(128_000);
const [, , prefix, overrides] = recordSpy.mock.calls[0]!;
expect(prefix).toBe('claude:claude-fable-5-2');
expect(overrides).toMatchObject({
input_tokens: 100 * Number(fable52.costs.input_tokens),
output_tokens: 50 * Number(fable52.costs.output_tokens),
cache_read_input_tokens:
1000 * Number(fable52.costs.cache_read_input_tokens),
ephemeral_5m_input_tokens:
150 * Number(fable52.costs.ephemeral_5m_input_tokens),
ephemeral_1h_input_tokens:
50 * Number(fable52.costs.ephemeral_1h_input_tokens),
});
},
);
it('routes the bare claude-fable alias to fable 5.1 rather than fable 5', async () => {
const { provider } = makeProvider();
messagesCreateMock.mockResolvedValueOnce(baseResponse);
@@ -2311,16 +2380,20 @@ describe('ClaudeProvider metering', () => {
expect('thinking_tokens' in overrides).toBe(false);
});
it('bills at the fast_* rates when the upstream reports usage.speed:"fast"', async () => {
it.each(['claude-opus-5-5', 'claude-fable-5-2'])('bills at fast rates for %s when the upstream reports fast usage', async (model) => {
const { provider } = makeProvider();
messagesCreateMock.mockResolvedValueOnce({
content: [{ type: 'text', text: 'hi' }],
usage: { input_tokens: 10, output_tokens: 5, speed: 'fast' },
usage: {
input_tokens: 10, output_tokens: 5, speed: 'fast',
cache_creation: { ephemeral_5m_input_tokens: 7, ephemeral_1h_input_tokens: 3 },
cache_read_input_tokens: 20,
},
});
const result = (await withTestActor(() =>
provider.complete({
model: 'claude-opus-5-5',
model,
messages: [{ role: 'user', content: 'hi' }],
speed: 'fast',
}),
@@ -2331,11 +2404,15 @@ describe('ClaudeProvider metering', () => {
expect('input_tokens' in result.usage).toBe(false);
expect(result.usageDetails.speed).toBe('fast');
const opus = CLAUDE_MODELS.find((m) => m.id === 'claude-opus-5-5')!;
const selectedModel = CLAUDE_MODELS.find((m) => m.id === model)!;
const [, , prefix, overrides] = recordSpy.mock.calls[0]!;
expect(prefix).toBe('claude:claude-opus-5-5');
expect(overrides.fast_input_tokens).toBe(10 * Number(opus.costs.fast_input_tokens));
expect(overrides.fast_output_tokens).toBe(5 * Number(opus.costs.fast_output_tokens));
expect(prefix).toBe(`claude:${model}`);
const fastRates = selectedModel.serviceSpeedRates!.fast as Record<string, number>;
expect(overrides.fast_input_tokens).toBe(10 * fastRates.input_tokens);
expect(overrides.fast_output_tokens).toBe(5 * fastRates.output_tokens);
expect(overrides.fast_ephemeral_5m_input_tokens).toBe(7 * fastRates.ephemeral_5m_input_tokens);
expect(overrides.fast_ephemeral_1h_input_tokens).toBe(3 * fastRates.ephemeral_1h_input_tokens);
expect(overrides.fast_cache_read_input_tokens).toBe(20 * fastRates.cache_read_input_tokens);
});
it('bills at standard rates when fast mode was requested but not granted by the upstream', async () => {
@@ -2357,13 +2434,15 @@ describe('ClaudeProvider metering', () => {
expect('fast_input_tokens' in result.usage).toBe(false);
});
it('retries at standard speed on Claude when fast mode is rate limited', async () => {
it.each([
[429, "This request would exceed your organization's rate limit of 0 fast mode input tokens per minute"],
[529, 'Overloaded'],
[529, 'Fast mode capacity unavailable'],
])('retries at standard speed on Claude after fast capacity failure %s', async (status, message) => {
const { provider } = makeProvider();
const fastLimited = Object.assign(
new Error(
"This request would exceed your organization's rate limit of 0 fast mode input tokens per minute",
),
{ status: 429 },
new Error(message),
{ status },
);
messagesCreateMock.mockRejectedValueOnce(fastLimited).mockResolvedValueOnce({
content: [{ type: 'text', text: 'hi' }],
@@ -2587,13 +2666,13 @@ describe('ClaudeProvider.requestPricing', () => {
const haiku = CLAUDE_MODELS.find((m) => m.id === 'claude-haiku-4-5-20251001')!;
const opus55 = CLAUDE_MODELS.find((m) => m.id === 'claude-opus-5-5')!;
it('returns fast cost keys only when the model has fast rates and fast was requested', () => {
it('leaves token reservation keys to the selected catalog rate card', () => {
const { provider } = makeProvider();
expect(
provider.requestPricing({ speed: 'fast', tools: [] } as never, opus55, {
promptTokenEstimate: 10,
}),
).toMatchObject({ inputKey: 'fast_input_tokens', outputKey: 'fast_output_tokens' });
).toEqual({});
expect(
provider.requestPricing({ speed: 'fast', tools: [] } as never, haiku, {
promptTokenEstimate: 10,
@@ -43,6 +43,7 @@ import {
} from '../../utils/mediaParts.js';
import { isToolChoice, toolChoiceFromWire } from '../../utils/openaiParams.js';
import { buildCostsOverride } from '../../utils/pricing.js';
import { serviceSpeedCosts } from '../../utils/serviceSpeed.js';
import type {
AIChatStream,
AIChatTextStream,
@@ -107,20 +108,21 @@ const toAnthropicMediaPart = (part: any): any => {
return part;
};
/** A 429 from fast mode's separate quota, not the model's normal limits. */
const isFastModeRateLimit = (e: unknown): boolean => {
/** Fast quota or overload failures can be retried at standard speed. */
const isFastModeUnavailable = (e: unknown): boolean => {
const err = e as { status?: unknown; message?: unknown };
return (
err?.status === 429 &&
typeof err.message === 'string' &&
/fast mode/i.test(err.message)
typeof err?.message === 'string' &&
((err?.status === 429 && /fast mode/i.test(err.message)) ||
(err?.status === 529 && /overload|fast mode/i.test(err.message)))
);
};
// Models whose current turn rejects a non-default temperature/top_p/top_k
// outright. Fable 5/5.1, Sonnet 5/5.5, Haiku 5.5, and Opus 4.7+.
// outright. Fable 5/5.1/5.2, Sonnet 5/5.5, Haiku 5.5, and Opus 4.7+.
const OMITS_SAMPLING_PARAMS = new Set([
'claude-haiku-5-5',
'claude-fable-5-2',
'claude-fable-5-1',
'claude-fable-5',
'claude-sonnet-5-5',
@@ -133,6 +135,7 @@ const OMITS_SAMPLING_PARAMS = new Set([
const SUPPORTS_EFFORT = new Set([
'claude-haiku-5-5',
'claude-fable-5-2',
'claude-fable-5-1',
'claude-fable-5',
'claude-sonnet-5-5',
@@ -298,20 +301,12 @@ export class ClaudeProvider implements IChatProvider {
return `claude:${modelId}`;
}
/**
* Sizes the credit hold for Claude-only extras the generic per-token math
* can't see: fast mode's own rate card, and a web-search/advisor tool that
* could run several times before the model answers.
*/
/** Reserves tools that can run several times before the model answers. */
requestPricing(
args: ICompleteArguments,
model: IChatModel,
est: { promptTokenEstimate: number },
): { inputKey?: string; outputKey?: string; extraCost?: number } {
const fast =
args.speed === 'fast' &&
model.costs?.fast_output_tokens !== undefined;
): { extraCost?: number } {
let extraCost = 0;
for (const raw of args.tools ?? []) {
const tool = raw as Record<string, unknown>;
@@ -350,12 +345,6 @@ export class ClaudeProvider implements IChatProvider {
}
return {
...(fast
? {
inputKey: 'fast_input_tokens',
outputKey: 'fast_output_tokens',
}
: {}),
...(extraCost > 0 ? { extraCost } : {}),
};
}
@@ -364,11 +353,9 @@ export class ClaudeProvider implements IChatProvider {
try {
return await this.#completeOnce(args);
} catch (e) {
// Fast mode has its own quota. Anthropic's advice on that 429 is to
// drop `speed` and run at standard speed; doing it here keeps the
// request on Claude instead of marking the route unhealthy and
// replaying it on a reseller.
if (args.speed === 'fast' && isFastModeRateLimit(e)) {
// Retry fast-capacity failures on Claude at standard speed before
// considering a different provider.
if (args.speed === 'fast' && isFastModeUnavailable(e)) {
return await this.#completeOnce({ ...args, speed: undefined });
}
throw e;
@@ -637,7 +624,7 @@ export class ClaudeProvider implements IChatProvider {
: undefined;
const fast =
args.speed === 'fast' &&
modelUsed.costs?.fast_output_tokens !== undefined;
modelUsed.serviceSpeedRates?.fast !== undefined;
const safeguardsPolicy = applySafeguardsPolicy(
args.safeguards,
args.anthropicBetas,
@@ -1071,6 +1058,7 @@ export class ClaudeProvider implements IChatProvider {
// keeps reasoning visible in the stream.
if (
modelId === 'claude-haiku-5-5' ||
modelId === 'claude-fable-5-2' ||
modelId === 'claude-fable-5-1' ||
modelId === 'claude-fable-5' ||
modelId === 'claude-sonnet-5-5' ||
@@ -1505,7 +1493,8 @@ export class ClaudeProvider implements IChatProvider {
const fast =
raw.speed === 'fast' &&
modelUsed.costs?.fast_output_tokens !== undefined;
modelUsed.serviceSpeedRates?.fast !== undefined;
// Keep published usage keys while resolving rates from the common catalog shape.
const executorUsage: Record<string, number> = fast
? Object.fromEntries(
Object.entries(exec).map(([k, v]) => [`fast_${k}`, v]),
@@ -1517,7 +1506,24 @@ export class ClaudeProvider implements IChatProvider {
const fetches = raw.server_tool_use?.web_fetch_requests ?? 0;
if (fetches) executorUsage.web_fetch_requests = fetches;
const executorCosts = buildCostsOverride(executorUsage, modelUsed);
const fastRates = fast
? serviceSpeedCosts(modelUsed, 'fast')
: undefined;
const billingModel = fastRates
? {
...modelUsed,
costs: {
...modelUsed.costs,
...Object.fromEntries(
Object.keys(exec).map((key) => [
`fast_${key}`,
fastRates[key],
]),
),
},
}
: modelUsed;
const executorCosts = buildCostsOverride(executorUsage, billingModel);
let advisorUsage: Record<string, number> | undefined;
let advisorCosts: Record<string, number> | undefined;
@@ -55,6 +55,46 @@ export const CLAUDE_MODELS: IChatModel[] = [
context: 1_000_000,
max_tokens: 128_000,
},
{
puterId: 'anthropic:anthropic/claude-fable-5-2',
id: 'claude-fable-5-2',
modalities: { input: ['text', 'image', 'pdf'], output: ['text'] },
open_weights: false,
tool_call: true,
release_date: '2026-11-09',
aliases: [
'claude-fable-5-2-latest',
'claude-fable-5.2',
'anthropic/claude-fable-5-2',
],
name: 'Claude Fable 5.2',
midConversationSystem: true,
costs_currency: 'usd-cents',
input_cost_key: 'input_tokens',
output_cost_key: 'output_tokens',
// Source: https://www.anthropic.com/claude-fable-and-mythos-5-2
serviceSpeedRates: {
fast: {
input_tokens: 1600,
output_tokens: 8000,
ephemeral_5m_input_tokens: 1600 * 1.25,
ephemeral_1h_input_tokens: 1600 * 2,
cache_read_input_tokens: 1600 * 0.025,
},
},
costs: {
tokens: 1_000_000,
input_tokens: 800,
ephemeral_5m_input_tokens: 800 * 1.25,
ephemeral_1h_input_tokens: 800 * 2,
// 0.025x input, not the usual 0.1x.
cache_read_input_tokens: 800 * 0.025,
output_tokens: 4000,
web_search_requests: 1_000_000, // $10/1k requests
},
context: 1000000,
max_tokens: 128000,
},
{
puterId: 'anthropic:anthropic/claude-fable-5-1',
id: 'claude-fable-5-1',
@@ -190,6 +230,15 @@ export const CLAUDE_MODELS: IChatModel[] = [
costs_currency: 'usd-cents',
input_cost_key: 'input_tokens',
output_cost_key: 'output_tokens',
serviceSpeedRates: {
fast: {
input_tokens: 800,
output_tokens: 4000,
ephemeral_5m_input_tokens: 1000,
ephemeral_1h_input_tokens: 1600,
cache_read_input_tokens: 40,
},
},
costs: {
tokens: 1_000_000,
input_tokens: 400,
@@ -199,12 +248,6 @@ export const CLAUDE_MODELS: IChatModel[] = [
cache_read_input_tokens: 400 * 0.05,
output_tokens: 2000,
web_search_requests: 1_000_000,
// Fast mode (`speed:'fast'`), live-verified.
fast_input_tokens: 800,
fast_output_tokens: 4000,
fast_ephemeral_5m_input_tokens: 1000,
fast_ephemeral_1h_input_tokens: 1600,
fast_cache_read_input_tokens: 40, // 0.05x fast_input_tokens
},
context: 1000000,
max_tokens: 128000,
@@ -223,6 +266,15 @@ export const CLAUDE_MODELS: IChatModel[] = [
costs_currency: 'usd-cents',
input_cost_key: 'input_tokens',
output_cost_key: 'output_tokens',
serviceSpeedRates: {
fast: {
input_tokens: 1000,
output_tokens: 5000,
ephemeral_5m_input_tokens: 1250,
ephemeral_1h_input_tokens: 2000,
cache_read_input_tokens: 100,
},
},
costs: {
tokens: 1_000_000,
input_tokens: 500,
@@ -231,11 +283,6 @@ export const CLAUDE_MODELS: IChatModel[] = [
cache_read_input_tokens: 500 * 0.1,
output_tokens: 2500,
web_search_requests: 1_000_000,
fast_input_tokens: 1000,
fast_output_tokens: 5000,
fast_ephemeral_5m_input_tokens: 1250,
fast_ephemeral_1h_input_tokens: 2000,
fast_cache_read_input_tokens: 100,
},
context: 1000000,
max_tokens: 128000,
@@ -258,6 +305,15 @@ export const CLAUDE_MODELS: IChatModel[] = [
costs_currency: 'usd-cents',
input_cost_key: 'input_tokens',
output_cost_key: 'output_tokens',
serviceSpeedRates: {
fast: {
input_tokens: 1000,
output_tokens: 5000,
ephemeral_5m_input_tokens: 1250,
ephemeral_1h_input_tokens: 2000,
cache_read_input_tokens: 100,
},
},
costs: {
tokens: 1_000_000,
input_tokens: 500,
@@ -266,11 +322,6 @@ export const CLAUDE_MODELS: IChatModel[] = [
cache_read_input_tokens: 500 * 0.1,
output_tokens: 2500,
web_search_requests: 1_000_000,
fast_input_tokens: 1000,
fast_output_tokens: 5000,
fast_ephemeral_5m_input_tokens: 1250,
fast_ephemeral_1h_input_tokens: 2000,
fast_cache_read_input_tokens: 100,
},
context: 1000000,
max_tokens: 128000,
@@ -84,8 +84,14 @@ export class GeminiChatProvider extends OpenAICompatProvider {
chat: {
completions: {
create: (params, options) => {
const { model } = params as { model: string };
if (!GEMINI_NATIVE_MODELS.has(model)) {
const { model, service_tier } = params as {
model: string;
service_tier?: string;
};
if (
!GEMINI_NATIVE_MODELS.has(model) &&
(service_tier === undefined || !native)
) {
return compat.chat.completions.create(
params,
options,
@@ -103,7 +109,12 @@ export class GeminiChatProvider extends OpenAICompatProvider {
},
},
};
const models = native ? GEMINI_MODELS : COMPAT_ONLY_MODELS;
const models: IChatModel[] = native
? GEMINI_MODELS
: COMPAT_ONLY_MODELS.map((model) => ({
...model,
serviceSpeeds: ['standard'],
}));
super(meteringService, {
client,
defaultModel: 'gemini-2.5-flash',
@@ -183,7 +194,10 @@ export class GeminiChatProvider extends OpenAICompatProvider {
}
protected override meteredUsage(source: UsageSource, model: IChatModel) {
if (GEMINI_NATIVE_MODELS.has(model.id)) {
if (
GEMINI_NATIVE_MODELS.has(model.id) ||
'promptTokenCount' in (source.usage ?? {})
) {
return nativeMeteredUsage(
source.usage as unknown as
GenerateContentResponseUsageMetadata | undefined,
@@ -80,6 +80,7 @@ interface ChatParams {
temperature?: number;
reasoning_effort?: 'minimal' | 'low' | 'medium' | 'high';
stream?: boolean;
service_tier?: string;
}
/** Ids made up for calls Gemini returned without one; never sent back. */
@@ -240,6 +241,12 @@ const toGenerateContentRequest = (
? toolConfigOf(params.tool_choice)
: undefined;
const config: GenerateContentConfig = {
...(params.service_tier !== undefined
? {
serviceTier:
params.service_tier as GenerateContentConfig['serviceTier'],
}
: {}),
...(signal ? { abortSignal: signal } : {}),
...(systemInstruction ? { systemInstruction } : {}),
...(params.max_completion_tokens !== undefined
@@ -142,6 +142,7 @@ export const GEMINI_MODELS: IChatModel[] = [
costs_currency: 'usd-cents',
input_cost_key: 'prompt_tokens',
output_cost_key: 'completion_tokens',
serviceSpeedRates: { fast: 1.8 },
costs: ARGON_LAUNCH_COSTS,
pricingOverrides: listPricingFrom(
'2026-12-01T00:00:00Z',
@@ -174,6 +175,7 @@ export const GEMINI_MODELS: IChatModel[] = [
input_cost_key: 'prompt_tokens',
output_cost_key: 'completion_tokens',
// Google serves this endpoint with gemini-3.6-flash and bills its rates.
serviceSpeedRates: { fast: 1.8 },
costs: FLASH_LAUNCH_COSTS,
pricingOverrides: FLASH_LIST_PRICING,
},
@@ -201,6 +203,7 @@ export const GEMINI_MODELS: IChatModel[] = [
costs_currency: 'usd-cents',
input_cost_key: 'prompt_tokens',
output_cost_key: 'completion_tokens',
serviceSpeedRates: { fast: 1.8 },
costs: {
tokens: 1_000_000,
prompt_tokens: 30,
@@ -228,6 +231,7 @@ export const GEMINI_MODELS: IChatModel[] = [
costs_currency: 'usd-cents',
input_cost_key: 'prompt_tokens',
output_cost_key: 'completion_tokens',
serviceSpeedRates: { fast: 1.8 },
costs: FLASH_LAUNCH_COSTS,
pricingOverrides: FLASH_LIST_PRICING,
},
@@ -250,6 +254,7 @@ export const GEMINI_MODELS: IChatModel[] = [
input_cost_key: 'prompt_tokens',
output_cost_key: 'completion_tokens',
// Google serves this endpoint with gemini-3.8-flash and bills its rates.
serviceSpeedRates: { fast: 1.8 },
costs: FLASH_LAUNCH_COSTS,
pricingOverrides: FLASH_LIST_PRICING,
},
@@ -270,6 +275,7 @@ export const GEMINI_MODELS: IChatModel[] = [
costs_currency: 'usd-cents',
input_cost_key: 'prompt_tokens',
output_cost_key: 'completion_tokens',
serviceSpeedRates: { fast: 1.8 },
costs: FLASH_LAUNCH_COSTS,
pricingOverrides: FLASH_LIST_PRICING,
},
@@ -291,6 +297,7 @@ export const GEMINI_MODELS: IChatModel[] = [
costs_currency: 'usd-cents',
input_cost_key: 'prompt_tokens',
output_cost_key: 'completion_tokens',
serviceSpeedRates: { fast: 1.8 },
costs: {
tokens: 1_000_000,
prompt_tokens: 25,
@@ -318,6 +325,7 @@ export const GEMINI_MODELS: IChatModel[] = [
costs_currency: 'usd-cents',
input_cost_key: 'prompt_tokens',
output_cost_key: 'completion_tokens',
serviceSpeedRates: { fast: 1.8 },
costs: {
tokens: 1_000_000,
prompt_tokens: 50,
@@ -344,6 +352,7 @@ export const GEMINI_MODELS: IChatModel[] = [
costs_currency: 'usd-cents',
input_cost_key: 'prompt_tokens',
output_cost_key: 'completion_tokens',
serviceSpeedRates: { fast: 1.8 },
costs: {
tokens: 1_000_000,
prompt_tokens: 30,
@@ -374,6 +383,7 @@ export const GEMINI_MODELS: IChatModel[] = [
costs_currency: 'usd-cents',
input_cost_key: 'prompt_tokens',
output_cost_key: 'completion_tokens',
serviceSpeedRates: { fast: 1.8 },
costs: {
tokens: 1_000_000,
prompt_tokens: 10,
@@ -402,6 +412,7 @@ export const GEMINI_MODELS: IChatModel[] = [
costs_currency: 'usd-cents',
input_cost_key: 'prompt_tokens',
output_cost_key: 'completion_tokens',
serviceSpeedRates: { fast: 1.8 },
costs: {
tokens: 1_000_000,
prompt_tokens: 125,
@@ -448,6 +459,7 @@ export const GEMINI_MODELS: IChatModel[] = [
costs_currency: 'usd-cents',
input_cost_key: 'prompt_tokens',
output_cost_key: 'completion_tokens',
serviceSpeedRates: { fast: 1.8 },
costs: {
tokens: 1_000_000,
prompt_tokens: 200,
@@ -266,6 +266,15 @@ export class InfronProvider extends OpenAICompatProvider {
return coerced_models;
}
async serviceSpeedModels(model: IChatModel) {
const variant = (await this.models()).find(
(entry) => entry.id === `${model.id}:priority`,
);
return variant
? { fast: { ...variant, provider: model.provider } }
: {};
}
protected override vendorParams(
params: Record<string, unknown>,
_args: unknown,
@@ -23,6 +23,7 @@ import { HttpError } from '../../../../core/http/HttpError.js';
import type { MeteringService } from '../../../../services/metering/MeteringService.js';
import { upstreamUserIdentifier } from '../../../util/upstreamIdentifier.js';
import type { IChatModel, ICompleteArguments } from '../../types.js';
import { promptCacheRetentionToWire } from '../../utils/openaiParams.js';
import { sdkClientOptions } from '../../utils/sdkClient.js';
import {
type ChatProviderConfig,
@@ -107,12 +108,9 @@ export class MetaProvider extends OpenAICompatProvider {
? requestedEffort
: undefined;
// Puter spells the in-memory retention with a hyphen; Meta's enum
// uses an underscore.
const cacheRetention =
args.prompt_cache_retention === 'in-memory'
? 'in_memory'
: args.prompt_cache_retention;
const cacheRetention = promptCacheRetentionToWire(
args.prompt_cache_retention,
);
// The identifier is Puter's abuse attribution, so `custom` can't
// override it. Cache key defaults to it; see upstreamUserIdentifier.
@@ -43,6 +43,8 @@ export const MINIMAX_MODELS: MiniMaxChatModel[] = [
costs_currency: 'usd-cents',
input_cost_key: 'prompt_tokens',
output_cost_key: 'completion_tokens',
serviceSpeedRates: { fast: 1.5 },
serviceSpeedVariants: { fast: 'minimax-m3-highspeed' },
costs: {
tokens: 1_000_000,
prompt_tokens: 30, // $0.30 per 1M (input <= 512k tokens)
@@ -70,6 +72,7 @@ export const MINIMAX_MODELS: MiniMaxChatModel[] = [
costs_currency: 'usd-cents',
input_cost_key: 'prompt_tokens',
output_cost_key: 'completion_tokens',
serviceSpeedVariants: { fast: 'minimax-m2.7-highspeed' },
costs: {
tokens: 1_000_000,
prompt_tokens: 30, // $0.30 per 1M
@@ -122,6 +125,7 @@ export const MINIMAX_MODELS: MiniMaxChatModel[] = [
costs_currency: 'usd-cents',
input_cost_key: 'prompt_tokens',
output_cost_key: 'completion_tokens',
serviceSpeedVariants: { fast: 'minimax-m2.5-highspeed' },
costs: {
tokens: 1_000_000,
prompt_tokens: 30, // $0.30 per 1M
@@ -174,6 +178,7 @@ export const MINIMAX_MODELS: MiniMaxChatModel[] = [
costs_currency: 'usd-cents',
input_cost_key: 'prompt_tokens',
output_cost_key: 'completion_tokens',
serviceSpeedVariants: { fast: 'minimax-m2.1-highspeed' },
costs: {
tokens: 1_000_000,
prompt_tokens: 30, // $0.30 per 1M
@@ -222,6 +227,7 @@ export const MINIMAX_MODELS: MiniMaxChatModel[] = [
costs_currency: 'usd-cents',
input_cost_key: 'prompt_tokens',
output_cost_key: 'completion_tokens',
serviceSpeedVariants: { fast: 'minimax-m2-highspeed' },
costs: {
tokens: 1_000_000,
prompt_tokens: 30, // $0.30 per 1M
@@ -20,13 +20,12 @@
/**
* Offline unit tests for MistralAIProvider.
*
* Boots a real PuterServer (in-memory sqlite + dynamo + s3 + mock
* redis) and constructs MistralAIProvider directly against the live
* wired `MeteringService` so the recording side is exercised end-to-
* end. The Mistral SDK is mocked at the module boundary (the real
* network egress point) so the provider never reaches the network.
* The companion integration test (MistralAiProvider.integration.test.ts)
* exercises the real Mistral endpoint.
* Boots a real PuterServer (in-memory sqlite + dynamo + s3 + mock redis) and
* constructs MistralAIProvider directly against the live wired
* `MeteringService` so the recording side is exercised end-to- end. The Mistral
* SDK is mocked at the module boundary (the real network egress point) so the
* provider never reaches the network. The companion integration test
* (MistralAiProvider.integration.test.ts) exercises the real Mistral endpoint.
*/
import { Context } from '../../../../core/context.js';
@@ -147,7 +146,9 @@ describe('MistralAIProvider construction', () => {
it('constructs the Mistral SDK with the configured API key', () => {
makeProvider();
expect(mistralCtor).toHaveBeenCalledTimes(1);
expect(mistralCtor).toHaveBeenCalledWith({ apiKey: 'test-key' });
expect(mistralCtor).toHaveBeenCalledWith(
expect.objectContaining({ apiKey: 'test-key' }),
);
});
});
@@ -606,7 +607,11 @@ describe('MistralAIProvider.complete non-stream output', () => {
if (stream) {
streamMock.mockResolvedValueOnce(
asAsyncIterable([
{ data: { choices: [{ delta: { content: 'hello' } }] } },
{
data: {
choices: [{ delta: { content: 'hello' } }],
},
},
{ data: { choices: [], usage } },
]),
);
@@ -643,7 +648,11 @@ describe('MistralAIProvider.complete non-stream output', () => {
expect(result).toMatchObject({ message: { content: 'hello' } });
}
expect(recordSpy).toHaveBeenCalledWith(
{ prompt_tokens: 5, cached_tokens: 1008, completion_tokens: 30 },
{
prompt_tokens: 5,
cached_tokens: 1008,
completion_tokens: 30,
},
SYSTEM_ACTOR,
`mistral:${model}`,
{
@@ -688,8 +697,7 @@ describe('MistralAIProvider.complete non-stream output', () => {
});
expect(recordSpy).toHaveBeenCalledTimes(1);
const [usage, actor, prefix, overrides] =
recordSpy.mock.calls[0]!;
const [usage, actor, prefix, overrides] = recordSpy.mock.calls[0]!;
expect(usage).toEqual({
prompt_tokens: 100,
completion_tokens: 50,
@@ -718,15 +726,11 @@ describe('MistralAIProvider.complete non-stream output', () => {
content: [
{
type: 'thinking',
thinking: [
{ type: 'text', text: 'step one.' },
],
thinking: [{ type: 'text', text: 'step one.' }],
},
{
type: 'thinking',
thinking: [
{ type: 'text', text: 'step two.' },
],
thinking: [{ type: 'text', text: 'step two.' }],
},
{ type: 'text', text: 'the answer' },
],
@@ -916,8 +920,7 @@ describe('MistralAIProvider.complete streaming', () => {
// mistral-small-2603: prompt=15, completion=60.
expect(recordSpy).toHaveBeenCalledTimes(1);
const [, , prefix, overrides] =
recordSpy.mock.calls[0]!;
const [, , prefix, overrides] = recordSpy.mock.calls[0]!;
expect(prefix).toBe('mistral:mistral-small-2603');
expect(overrides).toMatchObject({
prompt_tokens: 4 * 15,
@@ -1115,7 +1118,7 @@ describe('MistralAIProvider image_url coercion', () => {
usage: { promptTokens: 1, completionTokens: 1 },
};
it('rewrites canonical image_url parts to the SDK\'s camelCase imageUrl', async () => {
it("rewrites canonical image_url parts to the SDK's camelCase imageUrl", async () => {
const { provider } = makeProvider();
completeMock.mockResolvedValueOnce(baseCompletion);
@@ -1175,7 +1178,8 @@ describe('MistralAIProvider image_url coercion', () => {
},
{
type: 'image_url',
image_url: 'https://example.com/already-flat.png',
image_url:
'https://example.com/already-flat.png',
},
],
},
@@ -1251,7 +1255,9 @@ describe('MistralAIProvider image_url coercion', () => {
{ type: 'text', text: 'what is in this image?' },
{
type: 'image_url',
image_url: { url: 'https://example.com/photo.jpg' },
image_url: {
url: 'https://example.com/photo.jpg',
},
},
],
},
@@ -1260,7 +1266,11 @@ describe('MistralAIProvider image_url coercion', () => {
);
const [args] = completeMock.mock.calls[0]!;
const parts = args.messages[0].content as { type: string; text?: string; imageUrl?: unknown }[];
const parts = args.messages[0].content as {
type: string;
text?: string;
imageUrl?: unknown;
}[];
const textPart = parts.find((p) => p.type === 'text');
const imgPart = parts.find((p) => p.type === 'image_url');
expect(textPart?.text).toBe('what is in this image?');
@@ -1300,3 +1310,41 @@ describe('MistralAIProvider.checkModeration', () => {
);
});
});
describe('Mistral service speed wire mapping', () => {
it('adds the tier after SDK serialization and removes its internal header', async () => {
makeProvider();
const options = mistralCtor.mock.calls[0][0] as {
httpClient: import('@mistralai/mistralai/lib/http.js').HTTPClient;
};
let sent: Request | undefined;
vi.stubGlobal('fetch', async (input: Request) => {
sent = input;
return new Response('{}', {
headers: { 'content-type': 'application/json' },
});
});
try {
await options.httpClient.request(
new Request('https://api.mistral.ai/v1/chat/completions', {
method: 'POST',
headers: {
'content-type': 'application/json',
'x-puter-service-tier': 'auto',
},
body: JSON.stringify({
model: 'mistral-medium-latest',
messages: [],
}),
}),
);
expect(sent?.headers.has('x-puter-service-tier')).toBe(false);
expect(await sent?.json()).toMatchObject({
model: 'mistral-medium-latest',
service_tier: 'auto',
});
} finally {
vi.unstubAllGlobals();
}
});
});
@@ -17,6 +17,8 @@
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import { HTTPClient } from '@mistralai/mistralai/lib/http.js';
import { servedServiceSpeed } from '../../utils/serviceSpeed.js';
import { Mistral } from '@mistralai/mistralai';
import { ChatCompletionResponse } from '@mistralai/mistralai/models/components/chatcompletionresponse.js';
import { MistralError } from '@mistralai/mistralai/models/errors/mistralerror.js';
@@ -26,6 +28,7 @@ import { Context } from '../../../../core/context.js';
import { HttpError } from '../../../../core/http/HttpError.js';
import type { MeteringService } from '../../../../services/metering/MeteringService.js';
import type {
IChatModel,
IChatCompleteResult,
IChatProvider,
ICompleteArguments,
@@ -106,6 +109,7 @@ const coerceMistralUsage = (usage: UsageInfo) => {
prompt_tokens: (usage.promptTokens ?? 0) - cachedTokens,
completion_tokens: usage.completionTokens ?? 0,
prompt_tokens_details: { cached_tokens: cachedTokens },
service_tier: usage.additionalProperties?.service_tier,
};
};
@@ -115,7 +119,24 @@ export class MistralAIProvider implements IChatProvider {
#meteringService: MeteringService;
constructor(config: { apiKey: string }, meteringService: MeteringService) {
const httpClient = new HTTPClient();
// The SDK strips service_tier during body serialization.
httpClient.addHook('beforeRequest', async (request) => {
const tier = request.headers.get('x-puter-service-tier');
if (!tier) return;
const headers = new Headers(request.headers);
headers.delete('x-puter-service-tier');
const body = await request.json();
return new Request(request, {
headers,
body: JSON.stringify({
...body,
service_tier: tier === 'auto' ? 'auto' : 'standard_only',
}),
});
});
this.#client = new Mistral({
httpClient,
apiKey: config.apiKey,
});
this.#meteringService = meteringService;
@@ -181,17 +202,22 @@ export class MistralAIProvider implements IChatProvider {
return `mistral:${modelId}`;
}
async complete({
messages,
stream,
model,
tools,
max_tokens,
temperature,
normalize,
response,
custom,
}: ICompleteArguments): Promise<IChatCompleteResult> {
async complete(
{
messages,
stream,
model,
tools,
max_tokens,
temperature,
normalize,
response,
custom,
service_tier,
serviceSpeed: requestedServiceSpeed,
}: ICompleteArguments,
resolved?: IChatModel,
): Promise<IChatCompleteResult> {
// Mistral's reasoning prompt mode: with `prompt_mode: 'reasoning'`,
// reasoning-capable models return their thinking as structured ThinkChunk
// content (which the splitter below separates into `reasoning`)
@@ -217,10 +243,13 @@ export class MistralAIProvider implements IChatProvider {
}
const selectedModel =
(await this.models()).find((m) =>
resolved ??
((await this.models()).find((m) =>
[m.id, ...(m.aliases || [])].includes(model),
) ||
(await this.models()).find((m) => m.id === this.getDefaultModel())!;
(await this.models()).find(
(m) => m.id === this.getDefaultModel(),
)!);
const actor = Context.get('actor');
let completion: Awaited<
ReturnType<Mistral['chat']['complete' | 'stream']>
@@ -242,6 +271,9 @@ export class MistralAIProvider implements IChatProvider {
// The SDK retries nothing by default and has no timeout once a
// signal is passed; a stream is bounded by its caller instead.
{
...(service_tier !== undefined
? { headers: { 'x-puter-service-tier': service_tier } }
: {}),
signal: stream
? Context.get('upstreamSignal')
: withSdkTimeout(Context.get('upstreamSignal')),
@@ -398,7 +430,8 @@ export class MistralAIProvider implements IChatProvider {
},
completion: completion as ChatCompletionResponse,
stream,
usage_calculator: ({ usage, setUsageCosts }) => {
usage_calculator: ({ usage, setUsageCosts, setUsageDetails }) => {
const serviceSpeed = servedServiceSpeed({ usage });
// `coerceMistralUsage` has already taken cached reads out of
// `prompt_tokens`.
const metered = meterChatUsage(
@@ -407,8 +440,16 @@ export class MistralAIProvider implements IChatProvider {
this.meteringModelKey(selectedModel.id),
selectedModel,
OpenAIUtil.extractMeteredUsage(usage),
{ serviceSpeed },
);
setUsageCosts(metered.costs);
if (requestedServiceSpeed !== undefined)
setUsageDetails({
...OpenAIUtil.usageDetailsFromTrackedUsage(
metered.usage,
)!,
serviceSpeed,
});
return metered.usage;
},
});
@@ -42,6 +42,7 @@ export const MISTRAL_MODELS: IChatModel[] = [
costs_currency: 'usd-cents',
input_cost_key: 'prompt_tokens',
output_cost_key: 'completion_tokens',
serviceSpeedRates: { fast: 1.75 },
costs: {
tokens: 1_000_000,
prompt_tokens: 136,
@@ -75,6 +76,7 @@ export const MISTRAL_MODELS: IChatModel[] = [
costs_currency: 'usd-cents',
input_cost_key: 'prompt_tokens',
output_cost_key: 'completion_tokens',
serviceSpeedRates: { fast: 1.75 },
costs: {
tokens: 1_000_000,
prompt_tokens: 150,
@@ -105,6 +107,7 @@ export const MISTRAL_MODELS: IChatModel[] = [
costs_currency: 'usd-cents',
input_cost_key: 'prompt_tokens',
output_cost_key: 'completion_tokens',
serviceSpeedRates: { fast: 1.75 },
costs: {
tokens: 1_000_000,
prompt_tokens: 50,
@@ -135,6 +138,7 @@ export const MISTRAL_MODELS: IChatModel[] = [
costs_currency: 'usd-cents',
input_cost_key: 'prompt_tokens',
output_cost_key: 'completion_tokens',
serviceSpeedRates: { fast: 1.75 },
costs: {
tokens: 1_000_000,
prompt_tokens: 15,
@@ -159,6 +163,7 @@ export const MISTRAL_MODELS: IChatModel[] = [
costs_currency: 'usd-cents',
input_cost_key: 'prompt_tokens',
output_cost_key: 'completion_tokens',
serviceSpeedRates: { fast: 1.75 },
costs: {
tokens: 1_000_000,
prompt_tokens: 140,
@@ -188,6 +193,7 @@ export const MISTRAL_MODELS: IChatModel[] = [
costs_currency: 'usd-cents',
input_cost_key: 'prompt_tokens',
output_cost_key: 'completion_tokens',
serviceSpeedRates: { fast: 1.75 },
costs: {
tokens: 1_000_000,
prompt_tokens: 30,
@@ -213,6 +219,7 @@ export const MISTRAL_MODELS: IChatModel[] = [
costs_currency: 'usd-cents',
input_cost_key: 'prompt_tokens',
output_cost_key: 'completion_tokens',
serviceSpeedRates: { fast: 1.75 },
costs: {
tokens: 1_000_000,
prompt_tokens: 20,
@@ -238,6 +245,7 @@ export const MISTRAL_MODELS: IChatModel[] = [
costs_currency: 'usd-cents',
input_cost_key: 'prompt_tokens',
output_cost_key: 'completion_tokens',
serviceSpeedRates: { fast: 1.75 },
costs: {
tokens: 1_000_000,
prompt_tokens: 15,
@@ -262,6 +270,7 @@ export const MISTRAL_MODELS: IChatModel[] = [
costs_currency: 'usd-cents',
input_cost_key: 'prompt_tokens',
output_cost_key: 'completion_tokens',
serviceSpeedRates: { fast: 1.75 },
costs: {
tokens: 1_000_000,
prompt_tokens: 10,
@@ -30,6 +30,7 @@ export const MOONSHOT_MODELS: IChatModel[] = [
costs_currency: 'usd-cents',
input_cost_key: 'prompt_tokens',
output_cost_key: 'completion_tokens',
serviceSpeedVariants: { fast: 'kimi-k3.1-pro-highspeed' },
costs: {
tokens: 1_000_000,
prompt_tokens: 200, // $2.00 per 1M
@@ -77,6 +78,7 @@ export const MOONSHOT_MODELS: IChatModel[] = [
costs_currency: 'usd-cents',
input_cost_key: 'prompt_tokens',
output_cost_key: 'completion_tokens',
serviceSpeedVariants: { fast: 'kimi-k3-highspeed' },
costs: {
tokens: 1_000_000,
prompt_tokens: 300, // $3.00 per 1M
@@ -104,6 +106,7 @@ export const MOONSHOT_MODELS: IChatModel[] = [
costs_currency: 'usd-cents',
input_cost_key: 'prompt_tokens',
output_cost_key: 'completion_tokens',
serviceSpeedVariants: { fast: 'kimi-k2.6-highspeed' },
costs: {
tokens: 1_000_000,
prompt_tokens: 95, // $0.95 per 1M
@@ -126,6 +129,7 @@ export const MOONSHOT_MODELS: IChatModel[] = [
costs_currency: 'usd-cents',
input_cost_key: 'prompt_tokens',
output_cost_key: 'completion_tokens',
serviceSpeedVariants: { fast: 'kimi-k2.7-code-highspeed' },
costs: {
tokens: 1_000_000,
prompt_tokens: 95,
@@ -249,6 +249,130 @@ describe('OpenAiChatProvider.complete argument validation', () => {
expect(result).toEqual({ delegated: true });
});
it('delegates a 12h cache lifetime to the Responses provider, which is the only API that writes it', async () => {
const { provider } = makeProvider();
const sibling = {
complete: vi.fn().mockResolvedValue({ delegated: true }),
};
provider.setResponsesProvider(
sibling as unknown as Parameters<
typeof provider.setResponsesProvider
>[0],
);
const params = {
model: 'gpt-6-luna',
messages: [{ role: 'user', content: 'hi' }],
prompt_cache_options: { ttl: '12h' as const },
};
const result = await withTestActor(() => provider.complete(params));
expect(createMock).not.toHaveBeenCalled();
expect(sibling.complete).toHaveBeenCalledWith(params);
expect(result).toEqual({ delegated: true });
});
it.each([
['30m', { mode: 'explicit', ttl: '30m' }],
['12h', { mode: 'explicit', ttl: '12h' }],
])(
'delegates a %s breakpoint lifetime to the Responses provider, since Chat Completions rejects the field',
async (_ttl, breakpoint) => {
const { provider } = makeProvider();
const sibling = {
complete: vi.fn().mockResolvedValue({ delegated: true }),
};
provider.setResponsesProvider(
sibling as unknown as Parameters<
typeof provider.setResponsesProvider
>[0],
);
const params = {
model: 'gpt-6-luna',
messages: [
{
role: 'system',
content: [
{
type: 'text',
text: 'long prefix',
prompt_cache_breakpoint: breakpoint,
},
],
},
{ role: 'user', content: 'hi' },
],
};
const result = await withTestActor(() =>
provider.complete(params as never),
);
expect(createMock).not.toHaveBeenCalled();
expect(sibling.complete).toHaveBeenCalledWith(params);
expect(result).toEqual({ delegated: true });
},
);
it('keeps a breakpoint without a lifetime on the Chat Completions path, intact', async () => {
const { provider } = makeProvider();
createMock.mockResolvedValueOnce({
choices: [
{
message: { content: 'ok', role: 'assistant' },
finish_reason: 'stop',
},
],
usage: { prompt_tokens: 1, completion_tokens: 1 },
});
await withTestActor(() =>
provider.complete({
model: 'gpt-6-luna',
messages: [
{
role: 'system',
content: [
{
type: 'text',
text: 'long prefix',
prompt_cache_breakpoint: { mode: 'explicit' },
},
],
},
{ role: 'user', content: 'hi' },
],
} as never),
);
const [args] = createMock.mock.calls[0]!;
expect(args.messages[0]).toMatchObject({
role: 'system',
content: [
{
type: 'text',
text: 'long prefix',
prompt_cache_breakpoint: { mode: 'explicit' },
},
],
});
});
it('throws 400 for a 12h cache lifetime without a Responses sibling provider', async () => {
const { provider } = makeProvider();
await expect(
withTestActor(() =>
provider.complete({
model: 'gpt-6-luna',
messages: [{ role: 'user', content: 'hi' }],
prompt_cache_options: { ttl: '12h' },
}),
),
).rejects.toMatchObject({ statusCode: 400 });
expect(createMock).not.toHaveBeenCalled();
});
it('requestPricing delegates to the Responses sibling (web_search\'s own hold), and no-ops without one', async () => {
const { provider } = makeProvider();
const args = {
@@ -349,6 +473,31 @@ describe('OpenAiChatProvider.complete request shape', () => {
expect(args.safety_identifier).toBe('puter-u42');
});
it('forwards 30m prompt_cache_options and the wire spelling of prompt_cache_retention', async () => {
const { provider } = makeProvider();
createMock.mockResolvedValueOnce(baseCompletion);
await withTestActor(() =>
provider.complete({
model: 'gpt-6-luna',
messages: [{ role: 'user', content: 'hello' }],
prompt_cache_retention: 'in-memory',
prompt_cache_options: {
mode: 'explicit',
ttl: '30m',
prewarm: true,
} as never,
}),
);
const [args] = createMock.mock.calls[0]!;
expect(args.prompt_cache_retention).toBe('in_memory');
expect(args.prompt_cache_options).toEqual({
mode: 'explicit',
ttl: '30m',
});
});
it.each([
'gpt-6-astra',
'gpt-6.1-sol',
@@ -665,7 +814,7 @@ describe('OpenAiChatProvider.complete non-stream output', () => {
},
});
await withTestActor(() =>
const result = await withTestActor(() =>
provider.complete({
model: 'gpt-6-luna',
messages: [{ role: 'user', content: 'hi' }],
@@ -685,6 +834,13 @@ describe('OpenAiChatProvider.complete non-stream output', () => {
cached_tokens: 1000 * Number(luna.costs.cached_tokens),
cache_write_tokens: 3000 * Number(luna.costs.cache_write_tokens),
});
// Chat Completions only writes OpenAI's default 30m entries.
expect((result as { usageDetails: unknown }).usageDetails).toEqual({
inputTokens: 1000,
outputTokens: 12,
cacheReadTokens: 1000,
cacheWrite30mTokens: 3000,
});
});
it('zeroes cached_tokens when prompt_tokens_details is missing', async () => {
@@ -20,6 +20,7 @@
import { HttpError } from '@heyputer/backend/src/core/http/HttpError.js';
import { OpenAI } from 'openai';
import { ChatCompletionCreateParams } from 'openai/resources/index.js';
import { servedServiceSpeed } from '../../utils/serviceSpeed.js';
import { Context } from '../../../../core/context.js';
import type { MeteringService } from '../../../../services/metering/MeteringService.js';
import type {
@@ -35,7 +36,10 @@ import { make_openai_tools } from '../../utils/FunctionCalling.js';
import * as OpenAiUtil from '../../utils/OpenAIUtil.js';
import {
clampReasoningEffort,
messagesHaveCacheBreakpointTtl,
openAICompatParams,
promptCacheOptionsToWire,
promptCacheRetentionToWire,
} from '../../utils/openaiParams.js';
import { OPEN_AI_MODELS } from './models.js';
import type { OpenAiResponsesChatProvider } from './OpenAiChatResponsesProvider.js';
@@ -114,6 +118,7 @@ export class OpenAiChatProvider implements IChatProvider {
async complete(
params: ICompleteArguments,
resolved?: IChatModel,
): ReturnType<IChatProvider['complete']> {
const {
max_tokens,
@@ -126,8 +131,16 @@ export class OpenAiChatProvider implements IChatProvider {
temperature,
text,
prompt_cache_key,
prompt_cache_retention,
prompt_cache_options,
} = params;
let { messages, model } = params;
const cacheOptions = promptCacheOptionsToWire(prompt_cache_options);
if (params.service_tier === 'ultrafast' && this.#responsesProvider) {
return resolved
? this.#responsesProvider.complete(params, resolved)
: this.#responsesProvider.complete(params);
}
if (
tools?.filter((e) => isWebSearchTool(e as Record<string, unknown>))
.length
@@ -141,7 +154,9 @@ export class OpenAiChatProvider implements IChatProvider {
{ legacyCode: 'bad_request' },
);
}
return await this.#responsesProvider.complete(params);
return await (resolved
? this.#responsesProvider.complete(params, resolved)
: this.#responsesProvider.complete(params));
}
// Inline compaction is a Responses-API feature; chat.completions can't
// express `context_management` or a `compaction` content block.
@@ -155,7 +170,26 @@ export class OpenAiChatProvider implements IChatProvider {
{ legacyCode: 'bad_request' },
);
}
return await this.#responsesProvider.complete(params);
return await (resolved
? this.#responsesProvider.complete(params, resolved)
: this.#responsesProvider.complete(params));
}
// Only the Responses API writes 12h cache entries or takes a lifetime
// on a `prompt_cache_breakpoint`; Chat Completions rejects both.
if (
cacheOptions?.ttl === '12h' ||
messagesHaveCacheBreakpointTtl(messages)
) {
if (!this.#responsesProvider) {
throw new HttpError(
400,
'a prompt cache lifetime requires the OpenAI Responses provider, which is not configured',
{ legacyCode: 'bad_request' },
);
}
return await (resolved
? this.#responsesProvider.complete(params, resolved)
: this.#responsesProvider.complete(params));
}
// Validate messages
if (!Array.isArray(messages)) {
@@ -168,9 +202,11 @@ export class OpenAiChatProvider implements IChatProvider {
model = model ?? this.#defaultModel;
const modelUsed =
this.models().find((m) =>
resolved ??
(this.models().find((m) =>
[m.id, ...(m.aliases || [])].includes(model),
) || this.models().find((m) => m.id === this.getDefaultModel())!;
) ||
this.models().find((m) => m.id === this.getDefaultModel())!);
// messages.unshift({
// role: 'system',
@@ -180,6 +216,9 @@ export class OpenAiChatProvider implements IChatProvider {
const userIdentifier = upstreamUserIdentifier(actor);
// Cache key defaults to the actor identifier; see upstreamUserIdentifier.
const cacheKey = prompt_cache_key ?? userIdentifier;
const cacheRetention = promptCacheRetentionToWire(
prompt_cache_retention,
);
// Strip Anthropic-only shape a fallback-replayed message can carry
// (thinking/server-tool blocks, cache_control, citations) before the
@@ -216,8 +255,17 @@ export class OpenAiChatProvider implements IChatProvider {
user: userIdentifier,
safety_identifier: userIdentifier,
...(cacheKey !== undefined ? { prompt_cache_key: cacheKey } : {}),
...(cacheRetention !== undefined
? { prompt_cache_retention: cacheRetention }
: {}),
...(cacheOptions !== undefined
? { prompt_cache_options: cacheOptions }
: {}),
messages: messages,
model: modelUsed.id,
...(params.service_tier !== undefined
? { service_tier: params.service_tier }
: {}),
...(mappedTools?.length ? { tools: mappedTools } : {}),
...(max_tokens !== undefined
? { max_completion_tokens: max_tokens }
@@ -254,28 +302,17 @@ export class OpenAiChatProvider implements IChatProvider {
);
return OpenAiUtil.handle_completion_output({
usage_calculator: ({ usage, setUsageCosts }) => {
const cachedTokens =
usage.prompt_tokens_details?.cached_tokens ?? 0;
// GPT-5.6 and later bill cache writes at 1.25x input. They're
// reported inside `prompt_tokens`, like cached reads.
// The SDK doesn't type `cache_write_tokens` yet.
const cacheWriteTokens =
(
usage.prompt_tokens_details as
{ cache_write_tokens?: number } | undefined
)?.cache_write_tokens ?? 0;
const trackedUsage = {
prompt_tokens:
(usage.prompt_tokens ?? 0) -
cachedTokens -
cacheWriteTokens,
completion_tokens: usage.completion_tokens ?? 0,
cached_tokens: cachedTokens,
...(cacheWriteTokens
? { cache_write_tokens: cacheWriteTokens }
: {}),
};
usage_calculator: ({
usage,
service_tier,
setUsageCosts,
setUsageDetails,
}) => {
const serviceSpeed = servedServiceSpeed({ service_tier });
// GPT-5.6 and later report cache writes inside
// `prompt_tokens`, like cached reads; Chat Completions only
// writes the default 30m entries, billed at 1.25x input.
const trackedUsage = OpenAiUtil.splitCachedPrompt(usage);
const metered = meterChatUsage(
this.#meteringService,
@@ -283,8 +320,17 @@ export class OpenAiChatProvider implements IChatProvider {
this.meteringModelKey(modelUsed.id),
modelUsed,
trackedUsage,
{ serviceSpeed },
);
setUsageCosts(metered.costs);
setUsageDetails({
...OpenAiUtil.usageDetailsFromTrackedUsage(metered.usage, {
writeTtl: '30m',
})!,
...(params.serviceSpeed !== undefined
? { serviceSpeed }
: {}),
});
return metered.usage;
},
stream,
@@ -44,7 +44,9 @@ import {
type MockInstance,
} from 'vitest';
import { SYSTEM_ACTOR } from '../../../../core/actor.js';
import { SYSTEM_ACTOR, type Actor } from '../../../../core/actor.js';
import { v4 as uuidv4 } from 'uuid';
import { ChatCompletionDriver } from '../../ChatCompletionDriver.js';
import type { MeteringService } from '../../../../services/metering/MeteringService.js';
import { PuterServer } from '../../../../server.js';
import { setupTestServer } from '../../../../testUtil.js';
@@ -246,6 +248,7 @@ describe('OpenAiResponsesChatProvider model catalog', () => {
prompt_tokens: input,
cached_tokens: cached,
cache_write_tokens: input * 1.25,
cache_write_12h_tokens: input * 2.5,
completion_tokens: output,
},
context: 1_050_000,
@@ -844,7 +847,7 @@ describe('OpenAiResponsesChatProvider.complete non-stream output', () => {
},
});
await withTestActor(() =>
const result = await withTestActor(() =>
provider.complete({
model: 'gpt-6-luna',
messages: [{ role: 'user', content: 'hi' }],
@@ -867,6 +870,115 @@ describe('OpenAiResponsesChatProvider.complete non-stream output', () => {
cached_tokens: 1000 * Number(luna.costs.cached_tokens),
cache_write_tokens: 3000 * Number(luna.costs.cache_write_tokens),
});
// Writes without a per-lifetime breakdown are OpenAI's default 30m
// entries, and the neutral breakdown says so.
expect((result as { usageDetails: unknown }).usageDetails).toEqual({
inputTokens: 1000,
outputTokens: 20,
cacheReadTokens: 1000,
cacheWrite30mTokens: 3000,
});
});
it('bills 12h cache writes at 2.5x input and the other writes at 1.25x', async () => {
const luna = OPEN_AI_MODELS.find((m) => m.id === 'gpt-6-luna')!;
const { provider } = makeProvider();
// One request can write both lifetimes: an explicit 12h breakpoint
// plus the implicit 30m one OpenAI adds at the end of the prompt.
responsesCreateMock.mockResolvedValueOnce({
output: [{ role: 'assistant' }],
output_text: 'ok',
usage: {
input_tokens: 6026,
output_tokens: 5,
input_tokens_details: {
cached_tokens: 0,
cache_write_tokens: 6023,
cache_write_tokens_details: {
ttl_12h_tokens: 6012,
ttl_30m_tokens: 11,
},
},
},
});
const result = await withTestActor(() =>
provider.complete({
model: 'gpt-6-luna',
messages: [{ role: 'user', content: 'hi' }],
prompt_cache_options: { ttl: '12h' },
}),
);
const [usage, , , overrides] = recordSpy.mock.calls[0]!;
expect(usage).toEqual({
prompt_tokens: 3,
completion_tokens: 5,
cached_tokens: 0,
cache_write_tokens: 11,
cache_write_12h_tokens: 6012,
});
expect(luna.costs.cache_write_12h_tokens).toBe(
Number(luna.costs.prompt_tokens) * 2.5,
);
expect(overrides).toEqual({
prompt_tokens: 3 * Number(luna.costs.prompt_tokens),
completion_tokens: 5 * Number(luna.costs.completion_tokens),
cached_tokens: 0,
cache_write_tokens: 11 * Number(luna.costs.cache_write_tokens),
cache_write_12h_tokens:
6012 * Number(luna.costs.cache_write_12h_tokens),
});
expect((result as { usageDetails: unknown }).usageDetails).toEqual({
inputTokens: 3,
outputTokens: 5,
cacheWrite30mTokens: 11,
cacheWrite12hTokens: 6012,
});
});
it('forwards prompt_cache_options and the wire spelling of prompt_cache_retention', async () => {
const { provider } = makeProvider();
responsesCreateMock.mockResolvedValueOnce({
output: [{ role: 'assistant' }],
output_text: 'ok',
usage: { input_tokens: 1, output_tokens: 1 },
});
await withTestActor(() =>
provider.complete({
model: 'gpt-6-luna',
messages: [{ role: 'user', content: 'hi' }],
prompt_cache_retention: 'in-memory',
prompt_cache_options: {
mode: 'explicit',
ttl: '12h',
comparison_response_id: 'resp_1',
} as never,
}),
);
const [args] = responsesCreateMock.mock.calls[0]!;
expect(args.prompt_cache_retention).toBe('in_memory');
expect(args.prompt_cache_options).toEqual({
mode: 'explicit',
ttl: '12h',
});
});
it('rejects a cache lifetime OpenAI does not offer before calling upstream', async () => {
const { provider } = makeProvider();
await expect(
withTestActor(() =>
provider.complete({
model: 'gpt-6-luna',
messages: [{ role: 'user', content: 'hi' }],
prompt_cache_options: { ttl: '2h' } as never,
}),
),
).rejects.toMatchObject({ statusCode: 400 });
expect(responsesCreateMock).not.toHaveBeenCalled();
});
it.each([
@@ -1068,6 +1180,69 @@ describe('OpenAiResponsesChatProvider.complete streaming', () => {
});
});
it('labels streamed cache writes by lifetime on the final usage chunk', async () => {
const luna = OPEN_AI_MODELS.find((m) => m.id === 'gpt-6-luna')!;
const { provider } = makeProvider();
responsesCreateMock.mockReturnValueOnce(
asAsyncIterable([
{ type: 'response.output_text.delta', delta: 'ok' },
{
type: 'response.completed',
response: {
usage: {
input_tokens: 6026,
output_tokens: 5,
input_tokens_details: {
cached_tokens: 0,
cache_write_tokens: 6023,
cache_write_tokens_details: {
ttl_12h_tokens: 6012,
ttl_30m_tokens: 11,
},
},
},
},
},
]),
);
const result = await withTestActor(() =>
provider.complete({
model: 'gpt-6-luna',
messages: [{ role: 'user', content: 'say ok' }],
stream: true,
prompt_cache_options: { ttl: '12h' },
}),
);
const harness = makeCapturingChatStream();
await (
result as {
init_chat_stream: (p: { chatStream: unknown }) => Promise<void>;
}
).init_chat_stream({ chatStream: harness.chatStream });
const usageEvent = harness.events().find((e) => e.type === 'usage');
expect(usageEvent?.usage).toEqual({
prompt_tokens: 3,
completion_tokens: 5,
cached_tokens: 0,
cache_write_tokens: 11,
cache_write_12h_tokens: 6012,
});
expect(usageEvent?.usageDetails).toEqual({
inputTokens: 3,
outputTokens: 5,
cacheWrite30mTokens: 11,
cacheWrite12hTokens: 6012,
});
const [, , , overrides] = recordSpy.mock.calls[0]!;
expect(overrides).toMatchObject({
cache_write_tokens: 11 * Number(luna.costs.cache_write_tokens),
cache_write_12h_tokens:
6012 * Number(luna.costs.cache_write_12h_tokens),
});
});
it('emits a tool_use block when response.output_item.done arrives with a function_call', async () => {
const { provider } = makeProvider();
responsesCreateMock.mockReturnValueOnce(
@@ -1407,3 +1582,117 @@ describe('OpenAiResponsesChatProvider.complete error mapping', () => {
expect(recordSpy).not.toHaveBeenCalled();
});
});
describe('ChatCompletionDriver OpenAI billing', () => {
const makeBillingUser = async () => {
const user = await server.stores.user.create({
username: `billing-${uuidv4().slice(0, 8)}`,
uuid: uuidv4(),
password: null,
email: null,
free_storage: 1000000,
requires_email_confirmation: false,
});
return { user: { ...user, email_confirmed: true } } as Actor;
};
const makeBillingDriver = async () => {
const driver = new ChatCompletionDriver(
{
providers: {
ollama: { enabled: false },
'openai-completion': { apiKey: 'test-key' },
},
} as never,
server.clients,
server.stores,
server.services,
);
await driver.onServerStart();
return driver;
};
it('meters an empty Responses completion before returning its error', async () => {
const actor = await makeBillingUser();
const driver = await makeBillingDriver();
const before = await server.services.metering.getRemainingUsage(actor);
responsesCreateMock.mockResolvedValueOnce({
status: 'incomplete',
incomplete_details: { reason: 'max_output_tokens' },
output: [],
output_text: '',
usage: {
input_tokens: 1200,
output_tokens: 2000,
output_tokens_details: { reasoning_tokens: 2000 },
},
});
await expect(
withTestActor(
() =>
driver.complete({
model: 'gpt-5.4-mini',
provider: 'openai-responses',
messages: [{ role: 'user', content: 'hello' }],
max_tokens: 1,
fallback: false,
}),
actor,
),
).rejects.toMatchObject({ statusCode: 400 });
expect(responsesCreateMock).toHaveBeenCalledTimes(1);
expect(recordSpy).toHaveBeenCalledTimes(1);
expect(recordSpy.mock.calls[0][0]).toMatchObject({
prompt_tokens: 1200,
completion_tokens: 2000,
});
await Promise.all(recordSpy.mock.results.map((result) => result.value));
expect(
await server.services.metering.getRemainingUsage(actor),
).toBeLessThan(before);
});
it('prices a raw priority tier with the same rate card as fast service', async () => {
const actor = await makeBillingUser();
const driver = await makeBillingDriver();
const charges: number[] = [];
for (const extra of [
{},
{ service_tier: 'priority' },
{ serviceSpeed: 'fast' },
]) {
responsesCreateMock.mockResolvedValueOnce({
output: [],
output_text: 'hi',
service_tier: Object.keys(extra).length
? 'priority'
: 'default',
usage: { input_tokens: 100, output_tokens: 100 },
});
const before =
await server.services.metering.getRemainingUsage(actor);
await withTestActor(
() =>
driver.complete({
model: 'gpt-6.1-terra',
provider: 'openai-responses',
messages: [{ role: 'user', content: 'hello' }],
max_tokens: 100,
fallback: false,
...extra,
} as never),
actor,
);
await Promise.all(
recordSpy.mock.results.map((result) => result.value),
);
charges.push(
before -
(await server.services.metering.getRemainingUsage(actor)),
);
}
expect(responsesCreateMock.mock.calls[1][0].service_tier).toBe(
'priority',
);
expect(charges[0]).toBeGreaterThan(0);
expect(charges[1]).toBe(charges[2]);
expect(charges[2]).toBe(charges[0] * 2);
});
});
@@ -19,6 +19,7 @@
import { OpenAI } from 'openai';
import { ResponseCreateParams } from 'openai/resources/responses/responses.mjs';
import { servedServiceSpeed } from '../../utils/serviceSpeed.js';
import { Context } from '../../../../core/context.js';
import type { MeteringService } from '../../../../services/metering/MeteringService.js';
import type {
@@ -32,6 +33,8 @@ import * as OpenAiUtil from '../../utils/OpenAIUtil.js';
import {
clampReasoningEffort,
openAICompatParams,
promptCacheOptionsToWire,
promptCacheRetentionToWire,
rejectStatefulResponsesFields,
} from '../../utils/openaiParams.js';
import { responseSamplingParams } from '../../utils/responseSampling.js';
@@ -132,37 +135,42 @@ export class OpenAiResponsesChatProvider implements IChatProvider {
return rate ? { extraCost: rate } : {};
}
async complete({
messages,
model,
max_tokens,
moderation,
tools,
tool_choice,
parallel_tool_calls,
include,
conversation,
compaction,
context_management,
previous_response_id,
instructions,
metadata,
prompt,
prompt_cache_key,
prompt_cache_retention,
store,
top_p,
truncation,
background,
service_tier,
verbosity,
stream,
reasoning,
reasoning_effort,
temperature,
text,
outputFormat,
}: ICompleteArguments): ReturnType<IChatProvider['complete']> {
async complete(
{
messages,
model,
max_tokens,
moderation,
tools,
tool_choice,
parallel_tool_calls,
include,
conversation,
compaction,
context_management,
previous_response_id,
instructions,
metadata,
prompt,
prompt_cache_key,
prompt_cache_retention,
prompt_cache_options,
store,
top_p,
truncation,
background,
service_tier,
serviceSpeed: requestedServiceSpeed,
verbosity,
stream,
reasoning,
reasoning_effort,
temperature,
text,
outputFormat,
}: ICompleteArguments,
resolved?: IChatModel,
): ReturnType<IChatProvider['complete']> {
// Validate messages
if (!Array.isArray(messages)) {
throw new HttpError(400, '`messages` must be an array', {
@@ -180,12 +188,13 @@ export class OpenAiResponsesChatProvider implements IChatProvider {
model = model ?? this.#defaultModel;
const modelUsed =
this.models({ no_restrictions: true }).find((m) =>
resolved ??
(this.models({ no_restrictions: true }).find((m) =>
[m.id, ...(m.aliases || [])].includes(model),
) ||
this.models({ no_restrictions: true }).find(
(m) => m.id === this.getDefaultModel(),
)!;
this.models({ no_restrictions: true }).find(
(m) => m.id === this.getDefaultModel(),
)!);
// messages.unshift({
// role: 'system',
@@ -195,6 +204,10 @@ export class OpenAiResponsesChatProvider implements IChatProvider {
const userIdentifier = upstreamUserIdentifier(actor);
// Cache key defaults to the actor identifier; see upstreamUserIdentifier.
const cacheKey = prompt_cache_key ?? userIdentifier;
const cacheRetention = promptCacheRetentionToWire(
prompt_cache_retention,
);
const cacheOptions = promptCacheOptionsToWire(prompt_cache_options);
if (tools) {
// Unravel tools to OpenAI Responses API format
@@ -288,8 +301,11 @@ export class OpenAiResponsesChatProvider implements IChatProvider {
...(instructions !== undefined ? { instructions } : {}),
...(metadata !== undefined ? { metadata } : {}),
...(cacheKey !== undefined ? { prompt_cache_key: cacheKey } : {}),
...(prompt_cache_retention !== undefined
? { prompt_cache_retention }
...(cacheRetention !== undefined
? { prompt_cache_retention: cacheRetention }
: {}),
...(cacheOptions !== undefined
? { prompt_cache_options: cacheOptions }
: {}),
...(store !== undefined ? { store } : {}),
...(max_tokens !== undefined
@@ -310,24 +326,18 @@ export class OpenAiResponsesChatProvider implements IChatProvider {
{ signal: Context.get('upstreamSignal') },
);
return OpenAiUtil.handle_completion_output_responses_api({
usage_calculator: ({ usage, webSearchCalls, setUsageCosts }) => {
const cachedTokens =
(usage as any).input_tokens_details?.cached_tokens ?? 0;
// GPT-5.6 and later bill cache writes at 1.25x input. They're
// reported inside `input_tokens`, like cached reads.
const cacheWriteTokens =
(usage as any).input_tokens_details?.cache_write_tokens ??
0;
usage_calculator: ({
usage,
service_tier,
webSearchCalls,
setUsageCosts,
setUsageDetails,
}) => {
// GPT-5.6 and later report cache writes inside `input_tokens`,
// like cached reads, split by lifetime (30m and 12h entries
// cost 1.25x and 2.5x input to write).
const trackedUsage: Record<string, number> = {
prompt_tokens:
((usage as any).input_tokens ?? 0) -
cachedTokens -
cacheWriteTokens,
completion_tokens: (usage as any).output_tokens ?? 0,
cached_tokens: cachedTokens,
...(cacheWriteTokens
? { cache_write_tokens: cacheWriteTokens }
: {}),
...OpenAiUtil.splitCachedPrompt(usage),
...(webSearchCalls
? { web_search_calls: webSearchCalls }
: {}),
@@ -344,18 +354,31 @@ export class OpenAiResponsesChatProvider implements IChatProvider {
// model is a reasoning model, not a static per-model
// cost-table entry — the model's rates would otherwise
// price it (wrongly) at the input/output token rate.
webSearchCalls
? {
costOverrides: {
web_search_calls:
webSearchCalls *
(webSearchCallRate(tools, modelUsed.id) ??
0),
},
}
: {},
{
serviceSpeed: servedServiceSpeed({ service_tier }),
...(webSearchCalls
? {
costOverrides: {
web_search_calls:
webSearchCalls *
(webSearchCallRate(
tools,
modelUsed.id,
) ?? 0),
},
}
: {}),
},
);
setUsageCosts?.(metered.costs);
setUsageDetails?.({
...(requestedServiceSpeed !== undefined
? { serviceSpeed: servedServiceSpeed({ service_tier }) }
: {}),
...OpenAiUtil.usageDetailsFromTrackedUsage(metered.usage, {
writeTtl: '30m',
})!,
});
return metered.usage;
},
stream,
@@ -23,6 +23,8 @@ import type { IChatModel } from '../../types.js';
// Prompts over 272K input tokens are billed at 2x input (cached reads and
// cache writes included) and 1.5x output for the full request.
// GPT-5.6 and later bill cache writes by the lifetime requested: 1.25x input
// for the default 30m entries, 2.5x for 12h entries.
const GPT_LONG_CONTEXT_PRICING = {
threshold: 272_000,
input_multiplier: 2,
@@ -44,11 +46,13 @@ export const OPEN_AI_MODELS: IChatModel[] = [
costs_currency: 'usd-cents',
input_cost_key: 'prompt_tokens',
output_cost_key: 'completion_tokens',
serviceSpeedRates: { fast: 2 },
costs: {
tokens: 1_000_000,
prompt_tokens: 100,
cached_tokens: 5,
cache_write_tokens: 100 * 1.25,
cache_write_12h_tokens: 100 * 2.5,
completion_tokens: 500,
},
long_context_pricing: GPT_LONG_CONTEXT_PRICING,
@@ -69,11 +73,13 @@ export const OPEN_AI_MODELS: IChatModel[] = [
costs_currency: 'usd-cents',
input_cost_key: 'prompt_tokens',
output_cost_key: 'completion_tokens',
serviceSpeedRates: { fast: 2, ultrafast: 6 },
costs: {
tokens: 1_000_000,
prompt_tokens: 200,
cached_tokens: 10,
cache_write_tokens: 200 * 1.25,
cache_write_12h_tokens: 200 * 2.5,
completion_tokens: 1000,
},
long_context_pricing: GPT_LONG_CONTEXT_PRICING,
@@ -94,11 +100,13 @@ export const OPEN_AI_MODELS: IChatModel[] = [
costs_currency: 'usd-cents',
input_cost_key: 'prompt_tokens',
output_cost_key: 'completion_tokens',
serviceSpeedRates: { fast: 2 },
costs: {
tokens: 1_000_000,
prompt_tokens: 200,
cached_tokens: 20,
cache_write_tokens: 200 * 1.25,
cache_write_12h_tokens: 200 * 2.5,
completion_tokens: 1000,
},
long_context_pricing: GPT_LONG_CONTEXT_PRICING,
@@ -119,11 +127,13 @@ export const OPEN_AI_MODELS: IChatModel[] = [
costs_currency: 'usd-cents',
input_cost_key: 'prompt_tokens',
output_cost_key: 'completion_tokens',
serviceSpeedRates: { fast: 2 },
costs: {
tokens: 1_000_000,
prompt_tokens: 10,
cached_tokens: 1,
cache_write_tokens: 10 * 1.25,
cache_write_12h_tokens: 10 * 2.5,
completion_tokens: 50,
},
long_context_pricing: GPT_LONG_CONTEXT_PRICING,
@@ -144,11 +154,13 @@ export const OPEN_AI_MODELS: IChatModel[] = [
costs_currency: 'usd-cents',
input_cost_key: 'prompt_tokens',
output_cost_key: 'completion_tokens',
serviceSpeedRates: { fast: 2, ultrafast: 6 },
costs: {
tokens: 1_000_000,
prompt_tokens: 1000,
cached_tokens: 100,
cache_write_tokens: 1000 * 1.25,
cache_write_12h_tokens: 1000 * 2.5,
completion_tokens: 5000,
},
long_context_pricing: GPT_LONG_CONTEXT_PRICING,
@@ -169,11 +181,13 @@ export const OPEN_AI_MODELS: IChatModel[] = [
input_cost_key: 'prompt_tokens',
output_cost_key: 'completion_tokens',
// OpenAI's promotional pricing, guaranteed only through 2026-11-21.
serviceSpeedRates: { fast: 2 },
costs: {
tokens: 1_000_000,
prompt_tokens: 400,
cached_tokens: 40,
cache_write_tokens: 400 * 1.25,
cache_write_12h_tokens: 400 * 2.5,
completion_tokens: 2000,
},
long_context_pricing: GPT_LONG_CONTEXT_PRICING,
@@ -193,11 +207,13 @@ export const OPEN_AI_MODELS: IChatModel[] = [
costs_currency: 'usd-cents',
input_cost_key: 'prompt_tokens',
output_cost_key: 'completion_tokens',
serviceSpeedRates: { fast: 2 },
costs: {
tokens: 1_000_000,
prompt_tokens: 200,
cached_tokens: 20,
cache_write_tokens: 200 * 1.25,
cache_write_12h_tokens: 200 * 2.5,
completion_tokens: 1200,
},
long_context_pricing: GPT_LONG_CONTEXT_PRICING,
@@ -217,11 +233,13 @@ export const OPEN_AI_MODELS: IChatModel[] = [
costs_currency: 'usd-cents',
input_cost_key: 'prompt_tokens',
output_cost_key: 'completion_tokens',
serviceSpeedRates: { fast: 2 },
costs: {
tokens: 1_000_000,
prompt_tokens: 20,
cached_tokens: 2,
cache_write_tokens: 20 * 1.25,
cache_write_12h_tokens: 20 * 2.5,
completion_tokens: 120,
},
long_context_pricing: GPT_LONG_CONTEXT_PRICING,
@@ -241,6 +259,13 @@ export const OPEN_AI_MODELS: IChatModel[] = [
costs_currency: 'usd-cents',
input_cost_key: 'prompt_tokens',
output_cost_key: 'completion_tokens',
serviceSpeedRates: {
fast: {
prompt_tokens: 1250,
cached_tokens: 125,
completion_tokens: 7500,
},
},
costs: {
tokens: 1_000_000,
prompt_tokens: 500,
@@ -285,6 +310,13 @@ export const OPEN_AI_MODELS: IChatModel[] = [
costs_currency: 'usd-cents',
input_cost_key: 'prompt_tokens',
output_cost_key: 'completion_tokens',
serviceSpeedRates: {
fast: {
prompt_tokens: 500,
cached_tokens: 50,
completion_tokens: 3000,
},
},
costs: {
tokens: 1_000_000,
prompt_tokens: 250,
@@ -328,6 +360,13 @@ export const OPEN_AI_MODELS: IChatModel[] = [
costs_currency: 'usd-cents',
input_cost_key: 'prompt_tokens',
output_cost_key: 'completion_tokens',
serviceSpeedRates: {
fast: {
prompt_tokens: 150,
cached_tokens: 15,
completion_tokens: 900,
},
},
costs: {
tokens: 1_000_000,
prompt_tokens: 75,
@@ -415,6 +454,13 @@ export const OPEN_AI_MODELS: IChatModel[] = [
costs_currency: 'usd-cents',
input_cost_key: 'prompt_tokens',
output_cost_key: 'completion_tokens',
serviceSpeedRates: {
fast: {
prompt_tokens: 350,
cached_tokens: 35,
completion_tokens: 2800,
},
},
costs: {
tokens: 1_000_000,
prompt_tokens: 175,
@@ -436,6 +482,13 @@ export const OPEN_AI_MODELS: IChatModel[] = [
costs_currency: 'usd-cents',
input_cost_key: 'prompt_tokens',
output_cost_key: 'completion_tokens',
serviceSpeedRates: {
fast: {
prompt_tokens: 250,
cached_tokens: 25,
completion_tokens: 2000,
},
},
costs: {
tokens: 1_000_000,
prompt_tokens: 125,
@@ -457,6 +510,13 @@ export const OPEN_AI_MODELS: IChatModel[] = [
costs_currency: 'usd-cents',
input_cost_key: 'prompt_tokens',
output_cost_key: 'completion_tokens',
serviceSpeedRates: {
fast: {
prompt_tokens: 425,
cached_tokens: 212.5,
completion_tokens: 1700,
},
},
costs: {
tokens: 1_000_000,
prompt_tokens: 250,
@@ -480,6 +540,13 @@ export const OPEN_AI_MODELS: IChatModel[] = [
costs_currency: 'usd-cents',
input_cost_key: 'prompt_tokens',
output_cost_key: 'completion_tokens',
serviceSpeedRates: {
fast: {
prompt_tokens: 25,
cached_tokens: 12.5,
completion_tokens: 100,
},
},
costs: {
tokens: 1_000_000,
prompt_tokens: 15,
@@ -499,6 +566,13 @@ export const OPEN_AI_MODELS: IChatModel[] = [
costs_currency: 'usd-cents',
input_cost_key: 'prompt_tokens',
output_cost_key: 'completion_tokens',
serviceSpeedRates: {
fast: {
prompt_tokens: 350,
cached_tokens: 87.5,
completion_tokens: 1400,
},
},
costs: {
tokens: 1_000_000,
prompt_tokens: 200,
@@ -520,6 +594,13 @@ export const OPEN_AI_MODELS: IChatModel[] = [
costs_currency: 'usd-cents',
input_cost_key: 'prompt_tokens',
output_cost_key: 'completion_tokens',
serviceSpeedRates: {
fast: {
prompt_tokens: 70,
cached_tokens: 17.5,
completion_tokens: 280,
},
},
costs: {
tokens: 1_000_000,
prompt_tokens: 40,
@@ -561,6 +642,13 @@ export const OPEN_AI_MODELS: IChatModel[] = [
costs_currency: 'usd-cents',
input_cost_key: 'prompt_tokens',
output_cost_key: 'completion_tokens',
serviceSpeedRates: {
fast: {
prompt_tokens: 425,
cached_tokens: 212.5,
completion_tokens: 1700,
},
},
costs: {
tokens: 1_000_000,
prompt_tokens: 250,
@@ -20,15 +20,14 @@
/**
* Offline unit tests for OpenRouterProvider.
*
* Boots a real PuterServer (in-memory sqlite + dynamo + s3 + mock
* redis) and constructs OpenRouterProvider directly against the live
* wired `MeteringService` so the recording side is exercised end-to-
* end. OpenRouter is OpenAI-compatible, so the OpenAI SDK is mocked
* at the module boundary; the model catalog is fetched via `axios`
* which is mocked at its module boundary too. Both are the real
* network egress points.
* The companion integration test (OpenRouterProvider.integration.test.ts)
* exercises the real OpenRouter endpoint.
* Boots a real PuterServer (in-memory sqlite + dynamo + s3 + mock redis) and
* constructs OpenRouterProvider directly against the live wired
* `MeteringService` so the recording side is exercised end-to- end. OpenRouter
* is OpenAI-compatible, so the OpenAI SDK is mocked at the module boundary; the
* model catalog is fetched via `axios` which is mocked at its module boundary
* too. Both are the real network egress points. The companion integration test
* (OpenRouterProvider.integration.test.ts) exercises the real OpenRouter
* endpoint.
*/
import { Writable } from 'node:stream';
@@ -300,16 +299,20 @@ describe('OpenRouterProvider model catalog', () => {
it('coerces string prices and normalizes conditional tiers', async () => {
const { provider } = makeProvider();
const models = await provider.models();
const sol = models.find((m) => m.id === 'openrouter:openai/gpt-6.1-sol')!;
const sol = models.find(
(m) => m.id === 'openrouter:openai/gpt-6.1-sol',
)!;
expect(sol.costs).toEqual({
tokens: 1_000_000,
prompt: 200,
completion: 1000,
});
expect(sol.pricingOverrides).toEqual([{
minPromptTokens: 272000,
costs: { prompt: 400, completion: 1500 },
}]);
expect(sol.pricingOverrides).toEqual([
{
minPromptTokens: 272000,
costs: { prompt: 400, completion: 1500 },
},
]);
});
it('caches the coerced model list after the first axios round-trip', async () => {
@@ -368,9 +371,12 @@ describe('OpenRouterProvider model catalog', () => {
it('does not reinterpret catalog-added timestamps as release dates', async () => {
const { provider } = makeProvider();
expect((await provider.models()).every(model => model.release_date === undefined)).toBe(true);
expect(
(await provider.models()).every(
(model) => model.release_date === undefined,
),
).toBe(true);
});
});
// ── Disallowed model gate ───────────────────────────────────────────
@@ -868,11 +874,14 @@ describe('OpenRouterProvider billed cost through the driver', () => {
event.factor = factor;
};
server.clients.event.on('ai.cost.factor.*', listener as never);
return () => server.clients.event.off('ai.cost.factor.*', listener as never);
return () =>
server.clients.event.off('ai.cost.factor.*', listener as never);
};
/** µ¢ the ledger was handed for every usage recorded so far. */
const ledgerTotal = (spy: MockInstance<MeteringService['batchIncrementUsages']>) =>
/** Μ¢ the ledger was handed for every usage recorded so far. */
const ledgerTotal = (
spy: MockInstance<MeteringService['batchIncrementUsages']>,
) =>
spy.mock.calls
.flatMap(([, usages]) => usages)
.reduce((total, usage) => total + (usage.costOverride ?? 0), 0);
@@ -928,7 +937,10 @@ describe('OpenRouterProvider billed cost through the driver', () => {
it('reports what a billed completion was charged, after the cost factor', async () => {
const driver = await makeDriver();
const stopFactor = withCostFactor(1.6);
const recorded = vi.spyOn(server.services.metering, 'batchIncrementUsages');
const recorded = vi.spyOn(
server.services.metering,
'batchIncrementUsages',
);
createMock.mockResolvedValueOnce({
choices: [
{
@@ -1023,7 +1035,10 @@ describe('OpenRouterProvider billed cost through the driver', () => {
it('ends a stream with what it was charged at the catalog rates, after the cost factor', async () => {
const driver = await makeDriver();
const stopFactor = withCostFactor(1.6);
const recorded = vi.spyOn(server.services.metering, 'batchIncrementUsages');
const recorded = vi.spyOn(
server.services.metering,
'batchIncrementUsages',
);
createMock.mockReturnValueOnce(
asAsyncIterable([
{ choices: [{ delta: { content: 'hello' } }] },
@@ -1126,31 +1141,180 @@ describe('OpenRouterProvider.checkModeration', () => {
});
});
describe('OpenRouter catalog refresh validation', () => {
it('keeps missing model fields and prices unknown and blocks unpriced inference', async () => {
axiosRequestMock.mockResolvedValue({ data: { data: [{ id: 'fixture/model', name: 'Fixture' }] } });
axiosRequestMock.mockResolvedValue({
data: { data: [{ id: 'fixture/model', name: 'Fixture' }] },
});
const { provider } = makeProvider();
const [model] = await provider.models();
expect(model.costs).toEqual({ tokens: 1_000_000 });
expect(model.context).toBeUndefined();
expect(model.max_tokens).toBe(0);
await expect(withTestActor(() => provider.complete({ model: 'openrouter:fixture/model', messages: [] })))
.rejects.toMatchObject({ legacyCode: 'model_pricing_unavailable' });
await expect(
withTestActor(() =>
provider.complete({
model: 'openrouter:fixture/model',
messages: [],
}),
),
).rejects.toMatchObject({ legacyCode: 'model_pricing_unavailable' });
expect(createMock).not.toHaveBeenCalled();
});
it.each(['malformed', 'failed', 'ambiguous conditional price'])('retains last-good data after a %s refresh', async failure => {
vi.useFakeTimers({ toFake: ['Date'] });
vi.spyOn(console, 'warn').mockImplementation(() => {});
it.each(['malformed', 'failed', 'ambiguous conditional price'])(
'retains last-good data after a %s refresh',
async (failure) => {
vi.useFakeTimers({ toFake: ['Date'] });
vi.spyOn(console, 'warn').mockImplementation(() => {});
const { provider } = makeProvider();
const good = await provider.models();
vi.advanceTimersByTime(15 * 60 * 1000 + 1);
if (failure === 'failed')
axiosRequestMock.mockRejectedValueOnce(
new Error('unavailable'),
);
else if (failure === 'malformed')
axiosRequestMock.mockResolvedValueOnce({ data: {} });
else
axiosRequestMock.mockResolvedValueOnce({
data: {
data: [
{
...SAMPLE_API_MODELS[0],
pricing: {
prompt: '0.000002',
overrides: [
{ min_prompt_tokens: 10, prompt: '' },
],
},
},
],
},
});
expect(await provider.models()).toBe(good);
},
);
});
describe('OpenRouter service speed offerings', () => {
it('loads and caches tier prices while reserving for endpoint and context differences', async () => {
const { provider } = makeProvider();
const good = await provider.models();
vi.advanceTimersByTime(15 * 60 * 1000 + 1);
if (failure === 'failed') axiosRequestMock.mockRejectedValueOnce(new Error('unavailable'));
else if (failure === 'malformed') axiosRequestMock.mockResolvedValueOnce({ data: {} });
else axiosRequestMock.mockResolvedValueOnce({ data: { data: [{ ...SAMPLE_API_MODELS[0], pricing: {
prompt: '0.000002', overrides: [{ min_prompt_tokens: 10, prompt: '' }],
} }] } });
expect(await provider.models()).toBe(good);
const base = {
...(await provider.models())[0],
provider: 'openrouter',
};
axiosRequestMock.mockClear();
axiosRequestMock.mockResolvedValueOnce({
data: {
data: {
endpoints: [
{
service_tier: 'priority',
pricing: {
prompt: '0.000004',
completion: '0.00002',
input_cache_read: '0.0000002',
},
},
{
service_tier: 'priority',
pricing: {
prompt: '0.000005',
completion: '0.00001',
},
},
{
service_tier: 'ultrafast',
pricing: {
prompt: '0.000012',
completion: '0.00006',
overrides: [
{
min_prompt_tokens: 272000,
prompt: '0.000024',
completion: '0.00009',
},
],
},
},
{
service_tier: 'priority',
pricing: { prompt: 'invalid' },
},
],
},
},
});
const offers = await provider.serviceSpeedModels(base);
expect(offers.fast?.costs).toMatchObject({
prompt: 500,
completion: 2000,
input_cache_read: 20,
});
expect(offers.ultrafast?.costs).toMatchObject({
prompt: 2400,
completion: 9000,
});
expect(await provider.serviceSpeedModels(base)).toBe(offers);
expect(axiosRequestMock).toHaveBeenCalledTimes(1);
});
it('uses standard when the tier catalog cannot be fetched', async () => {
const { provider } = makeProvider();
const base = {
...(await provider.models())[0],
provider: 'openrouter',
};
axiosRequestMock.mockRejectedValueOnce(new Error('Unavailable'));
expect(await provider.serviceSpeedModels(base)).toEqual({});
});
});
describe('OpenRouter speed billing', () => {
it('requires an authoritative bill instead of charging the reservation ceiling', async () => {
const { selectServiceSpeed } =
await import('../../utils/serviceSpeed.js');
const { provider } = makeProvider();
const base = {
...(await provider.models())[0],
provider: 'openrouter',
};
const selected = selectServiceSpeed(
base,
{
model: base.id,
messages: [{ role: 'user', content: 'Hello' }],
serviceSpeed: 'fast',
},
() => undefined,
{
fast: {
...base,
costs: { ...base.costs, prompt: 500, completion: 2000 },
},
},
);
const completion = {
choices: [
{
index: 0,
message: { role: 'assistant', content: 'OK' },
finish_reason: 'stop',
},
],
usage: { prompt_tokens: 10, completion_tokens: 1 },
};
createMock.mockResolvedValueOnce({
...completion,
service_tier: 'priority',
usage: { ...completion.usage, cost: undefined },
});
await expect(
withTestActor(() =>
provider.complete(selected.args, selected.model),
),
).rejects.toMatchObject({ legacyCode: 'model_pricing_unavailable' });
expect(recordSpy).not.toHaveBeenCalled();
});
});
@@ -22,8 +22,10 @@ import { OpenAI } from 'openai';
import { HttpError, isHttpError } from '../../../../core/http/HttpError.js';
import { UpstreamResponseError } from '../../../util/upstreamErrors.js';
import type { MeteringService } from '../../../../services/metering/MeteringService.js';
import type { IChatModel, ICompleteArguments } from '../../types.js';
import type { IChatModel, ICompleteArguments, ModelCost } from '../../types.js';
import { BoundedTtlMap } from '../../../../util/boundedTtlMap.js';
import { cachedRemoteCatalog } from '../../utils/cachedRemoteCatalog.js';
import { servedServiceSpeed } from '../../utils/serviceSpeed.js';
import { catalogPrice } from '../../utils/pricing.js';
import { mapOpenRouterPricing } from './pricing.js';
import { sdkClientOptions } from '../../utils/sdkClient.js';
@@ -64,6 +66,75 @@ const isPolicyBlock = (err: unknown): boolean => {
export class OpenRouterProvider extends OpenAICompatProvider {
#apiBaseUrl: string;
#speedCatalogs = new BoundedTtlMap<
string,
() => Promise<Partial<Record<'fast' | 'ultrafast', IChatModel>>>
>({ maxEntries: 256 });
async serviceSpeedModels(model: IChatModel) {
let load = this.#speedCatalogs.get(model.id);
if (!load) {
load = cachedRemoteCatalog({
name: 'OpenRouter speed catalog',
fallback: {} as Partial<
Record<'fast' | 'ultrafast', IChatModel>
>,
fetch: async (signal) => {
const id = model.id.replace(/^openrouter:/, '');
const response = await axios.request({
url: `${this.#apiBaseUrl}/models/${id}/endpoints`,
method: 'GET',
signal,
maxContentLength: 2 * 1024 * 1024,
});
const offers: Partial<
Record<'fast' | 'ultrafast', IChatModel>
> = {};
for (const endpoint of response.data?.data?.endpoints ??
[]) {
const speed =
endpoint.service_tier === 'ultrafast'
? 'ultrafast'
: ['priority', 'fast'].includes(
endpoint.service_tier,
)
? 'fast'
: undefined;
if (!speed || !endpoint.pricing) continue;
const pricing = mapOpenRouterPricing(endpoint.pricing);
if (
pricing.costs.prompt === undefined ||
pricing.costs.completion === undefined
)
continue;
// Reserve for the most expensive eligible endpoint and context tier.
const costs: ModelCost = {
...offers[speed]?.costs,
tokens: model.costs.tokens,
};
for (const rates of [
pricing.costs,
...pricing.overrides.map(
(override) => override.costs,
),
]) {
for (const [key, value] of Object.entries(rates))
costs[key] = Math.max(costs[key] ?? 0, value);
}
offers[speed] = {
...model,
costs,
pricingOverrides: [],
};
}
return offers;
},
});
this.#speedCatalogs.set(model.id, load);
}
return load();
}
constructor(config: ChatProviderConfig, meteringService: MeteringService) {
const apiBaseUrl = config.apiBaseUrl || 'https://openrouter.ai/api/v1';
super(meteringService, {
@@ -202,8 +273,17 @@ export class OpenRouterProvider extends OpenAICompatProvider {
return { ...params, usage: { include: true } };
}
protected override meteredUsage(source: UsageSource) {
protected override meteredUsage(source: UsageSource, model: IChatModel) {
const usage = source.usage as OpenrouterUsage;
if (
model.serviceSpeedPricing &&
servedServiceSpeed(source) !== 'standard' &&
catalogPrice(usage.cost) === undefined
) {
throw new HttpError(503, 'Service tier billing is unavailable', {
legacyCode: 'model_pricing_unavailable',
});
}
return {
usage: {
prompt:
@@ -20,13 +20,12 @@
/**
* Offline unit tests for XAIProvider.
*
* Boots a real PuterServer (in-memory sqlite + dynamo + s3 + mock
* redis) and constructs XAIProvider directly against the live wired
* `MeteringService` so the recording side is exercised end-to-end.
* xAI is OpenAI-compatible so the OpenAI SDK is mocked at the module
* boundary; that's the real network egress point. The companion
* integration test (XAIProvider.integration.test.ts) exercises the
* real xAI endpoint.
* Boots a real PuterServer (in-memory sqlite + dynamo + s3 + mock redis) and
* constructs XAIProvider directly against the live wired `MeteringService` so
* the recording side is exercised end-to-end. xAI is OpenAI-compatible so the
* OpenAI SDK is mocked at the module boundary; that's the real network egress
* point. The companion integration test (XAIProvider.integration.test.ts)
* exercises the real xAI endpoint.
*/
import { Writable } from 'node:stream';
@@ -933,8 +932,7 @@ describe('XAIProvider.complete non-stream output', () => {
// namespace, actor, and a costsOverride priced from
// models.ts (grok-4.6: prompt=200, completion=600, cached=50).
expect(recordSpy).toHaveBeenCalledTimes(1);
const [usage, actor, prefix, overrides] =
recordSpy.mock.calls[0]!;
const [usage, actor, prefix, overrides] = recordSpy.mock.calls[0]!;
expect(usage).toEqual({
prompt_tokens: 90,
completion_tokens: 50,
@@ -1022,8 +1020,7 @@ describe('XAIProvider.complete non-stream output', () => {
}),
);
const [usage, , , overrides] =
recordSpy.mock.calls[0]!;
const [usage, , , overrides] = recordSpy.mock.calls[0]!;
expect(usage.cached_tokens).toBe(0);
// 0 cached tokens × any rate = 0 metered cost.
expect(overrides).toMatchObject({ cached_tokens: 0 });
@@ -1081,8 +1078,7 @@ describe('XAIProvider.complete streaming', () => {
// grok-build-0.1 costs: prompt=100, completion=200, cached=20.
expect(recordSpy).toHaveBeenCalledTimes(1);
const [, , prefix, overrides] =
recordSpy.mock.calls[0]!;
const [, , prefix, overrides] = recordSpy.mock.calls[0]!;
expect(prefix).toBe('xai:grok-build-0.1');
expect(overrides).toEqual({
prompt_tokens: 3 * 100,
@@ -1200,3 +1196,60 @@ describe('XAIProvider.checkModeration', () => {
);
});
});
describe('xAI service speed billing', () => {
it('records the reported Priority charge with cached input and reasoning', async () => {
const { selectServiceSpeed } =
await import('../../utils/serviceSpeed.js');
const { provider } = makeProvider();
const base = {
...(await provider.models()).find(
(entry) => entry.id === 'grok-4.7',
)!,
provider: 'xai',
};
const selected = selectServiceSpeed(
base,
{
model: base.id,
messages: [{ role: 'user', content: 'Hello' }],
serviceSpeed: 'ultrafast',
},
() => undefined,
);
createMock.mockResolvedValueOnce({
choices: [
{
index: 0,
message: { role: 'assistant', content: 'OK' },
finish_reason: 'stop',
},
],
service_tier: 'priority',
usage: {
prompt_tokens: 1247,
completion_tokens: 1,
total_tokens: 1282,
prompt_tokens_details: { cached_tokens: 1152 },
completion_tokens_details: { reasoning_tokens: 34 },
cost_in_usd_ticks: 19520000,
},
});
const result = await withTestActor(() =>
provider.complete(selected.args, selected.model),
);
expect(result).toMatchObject({
usageDetails: {
serviceSpeed: 'fast',
outputTokens: 35,
reasoningTokens: 34,
},
});
expect(recordSpy).toHaveBeenCalledWith(
expect.objectContaining({ billedUsage: 1, completion_tokens: 35 }),
expect.anything(),
'xai:grok-4.7',
expect.objectContaining({ billedUsage: 195200 }),
);
});
});
@@ -19,6 +19,8 @@
import { OpenAI } from 'openai';
import { ChatCompletionCreateParams } from 'openai/resources/index.js';
import { catalogPrice } from '../../utils/pricing.js';
import { servedServiceSpeed } from '../../utils/serviceSpeed.js';
import { Context } from '../../../../core/context.js';
import type { MeteringService } from '../../../../services/metering/MeteringService.js';
import * as OpenAIUtil from '../../utils/OpenAIUtil.js';
@@ -74,7 +76,15 @@ export class XAIProvider implements IChatProvider {
}
async complete(
{ messages, stream, model, tools, max_tokens }: ICompleteArguments,
{
messages,
stream,
model,
tools,
max_tokens,
service_tier,
serviceSpeed: requestedServiceSpeed,
}: ICompleteArguments,
resolved?: IChatModel,
): Promise<IChatCompleteResult> {
const actor = Context.get('actor');
@@ -88,6 +98,7 @@ export class XAIProvider implements IChatProvider {
{
messages,
model: modelUsed.id,
...(service_tier !== undefined ? { service_tier } : {}),
...(tools ? { tools } : {}),
...(max_tokens !== undefined ? { max_tokens } : {}),
stream,
@@ -107,18 +118,49 @@ export class XAIProvider implements IChatProvider {
}
return OpenAIUtil.handle_completion_output({
usage_calculator: ({ usage, setUsageCosts }) => {
usage_calculator: ({
usage,
service_tier: servedTier,
setUsageCosts,
setUsageDetails,
}) => {
const serviceSpeed = servedServiceSpeed({
service_tier: servedTier,
});
// xAI reports cached reads inside `prompt_tokens`; bill them
// only at the cached rate.
const metered = OpenAIUtil.extractMeteredUsage(usage);
const reasoningTokens =
usage.completion_tokens_details?.reasoning_tokens ?? 0;
const trackedUsage = OpenAIUtil.splitCachedPrompt(usage);
trackedUsage.completion_tokens += reasoningTokens;
const reportedTicks = catalogPrice(
(usage as typeof usage & { cost_in_usd_ticks?: number })
.cost_in_usd_ticks,
);
const { costs } = meterChatUsage(
this.#meteringService,
actor,
this.meteringModelKey(modelUsed.id),
modelUsed,
OpenAIUtil.splitCachedPrompt(usage),
trackedUsage,
{
serviceSpeed,
authoritativeUsd:
reportedTicks === undefined
? undefined
: reportedTicks / 10_000_000_000,
},
);
setUsageCosts(costs);
if (requestedServiceSpeed !== undefined)
setUsageDetails?.({
...OpenAIUtil.usageDetailsFromTrackedUsage(
trackedUsage,
)!,
serviceSpeed,
...(reasoningTokens ? { reasoningTokens } : {}),
});
return metered;
},
stream,
@@ -42,6 +42,7 @@ export const XAI_MODELS: IChatModel[] = [
costs_currency: 'usd-cents',
input_cost_key: 'prompt_tokens',
output_cost_key: 'completion_tokens',
serviceSpeedRates: { fast: 2 },
costs: {
tokens: 1_000_000,
prompt_tokens: 200,
@@ -65,6 +66,7 @@ export const XAI_MODELS: IChatModel[] = [
costs_currency: 'usd-cents',
input_cost_key: 'prompt_tokens',
output_cost_key: 'completion_tokens',
serviceSpeedRates: { fast: 2 },
costs: {
tokens: 1_000_000,
prompt_tokens: 200,
@@ -87,6 +89,7 @@ export const XAI_MODELS: IChatModel[] = [
costs_currency: 'usd-cents',
input_cost_key: 'prompt_tokens',
output_cost_key: 'completion_tokens',
serviceSpeedRates: { fast: 2 },
costs: {
tokens: 1_000_000,
prompt_tokens: 200,
@@ -109,6 +112,7 @@ export const XAI_MODELS: IChatModel[] = [
costs_currency: 'usd-cents',
input_cost_key: 'prompt_tokens',
output_cost_key: 'completion_tokens',
serviceSpeedRates: { fast: 2 },
costs: {
tokens: 1_000_000,
prompt_tokens: 125,
@@ -151,6 +155,7 @@ export const XAI_MODELS: IChatModel[] = [
costs_currency: 'usd-cents',
input_cost_key: 'prompt_tokens',
output_cost_key: 'completion_tokens',
serviceSpeedRates: { fast: 2 },
costs: {
tokens: 1_000_000,
prompt_tokens: 125,
@@ -186,6 +191,7 @@ export const XAI_MODELS: IChatModel[] = [
costs_currency: 'usd-cents',
input_cost_key: 'prompt_tokens',
output_cost_key: 'completion_tokens',
serviceSpeedRates: { fast: 2 },
costs: {
tokens: 1_000_000,
prompt_tokens: 125,
@@ -217,6 +223,7 @@ export const XAI_MODELS: IChatModel[] = [
costs_currency: 'usd-cents',
input_cost_key: 'prompt_tokens',
output_cost_key: 'completion_tokens',
serviceSpeedRates: { fast: 2 },
costs: {
tokens: 1_000_000,
prompt_tokens: 125,
@@ -246,6 +253,7 @@ export const XAI_MODELS: IChatModel[] = [
costs_currency: 'usd-cents',
input_cost_key: 'prompt_tokens',
output_cost_key: 'completion_tokens',
serviceSpeedRates: { fast: 2 },
costs: {
tokens: 1_000_000,
prompt_tokens: 100,
+58 -7
View File
@@ -26,6 +26,8 @@
export type ModelCost = Record<string, number>;
export type ServiceSpeed = 'standard' | 'fast' | 'ultrafast';
export interface ModelModalities {
input: string[];
output: string[];
@@ -67,6 +69,22 @@ export interface IChatModel<T extends ModelCost = ModelCost> extends Record<
output_multiplier: number;
};
pricingOverrides?: ModelPricingOverride[];
/**
* A token-rate multiplier or explicit per-key rates merged with standard
* costs.
*/
serviceSpeedRates?: Partial<
Record<'fast' | 'ultrafast', number | ModelCost>
>;
serviceSpeedVariants?: { fast?: string };
/** Request-local pricing snapshot; never part of the model catalog. */
serviceSpeedPricing?: {
speed: ServiceSpeed;
standardCosts: ModelCost;
standardOverrides?: ModelPricingOverride[];
fastCosts?: ModelCost;
ultrafastCosts?: ModelCost;
};
context?: number;
max_tokens: number;
subscriberOnly?: boolean;
@@ -76,6 +94,8 @@ export interface IChatModel<T extends ModelCost = ModelCost> extends Record<
tool_call?: boolean;
responses_api?: boolean;
responses_api_only?: boolean;
/** Restricts service speeds for deployments with a limited API dialect. */
serviceSpeeds?: ServiceSpeed[];
/**
* Omitted preserves sampling; reasoningDisabled requires explicit effort
* none.
@@ -145,18 +165,25 @@ export type StopReason =
| 'model_context_window_exceeded'
| (string & {});
/** Provider-neutral usage breakdown. `inputTokens` excludes cache reads/writes. */
/**
* Provider-neutral usage breakdown. `inputTokens` excludes cache reads/writes.
* Cache writes are keyed by the lifetime the entry was written with: Claude and
* Moonshot write 5m and 1h entries, OpenAI writes 30m and 12h entries.
*/
export interface UsageDetails {
inputTokens: number;
outputTokens: number; // includes reasoning
cacheReadTokens?: number;
cacheWrite5mTokens?: number;
cacheWrite30mTokens?: number;
cacheWrite1hTokens?: number;
cacheWrite12hTokens?: number;
reasoningTokens?: number;
webSearchRequests?: number;
webFetchRequests?: number;
speed?: 'fast' | 'standard';
serviceTier?: string;
serviceSpeed?: ServiceSpeed;
/**
* Per-pass breakdown when the upstream ran several passes (compaction,
* advisor).
@@ -168,10 +195,22 @@ export interface UsageDetails {
outputTokens: number;
cacheReadTokens?: number;
cacheWrite5mTokens?: number;
cacheWrite30mTokens?: number;
cacheWrite1hTokens?: number;
cacheWrite12hTokens?: number;
}>;
}
/**
* OpenAI `prompt_cache_options`, GPT-5.6 and later. `ttl` is the minimum
* lifetime of every cache entry the request writes; `12h` entries cost twice
* what `30m` entries do to write and only the Responses API writes them.
*/
export interface PromptCacheOptions {
mode?: 'implicit' | 'explicit';
ttl?: '30m' | '12h';
}
export interface ICompleteArguments {
messages: PuterMessage[];
provider?: string;
@@ -180,6 +219,7 @@ export interface ICompleteArguments {
* request on another provider that serves the same model.
*/
fallback?: boolean;
serviceSpeed?: ServiceSpeed;
stream?: boolean;
model: string;
test_mode?: boolean;
@@ -199,10 +239,7 @@ export interface ICompleteArguments {
taskBudget?: { total: number; remaining?: number };
/** Claude only: top-level automatic `cache_control`. */
cacheControl?: CacheControl;
/**
* Claude only; forwarded only when the model's catalog entry has
* `fast_output_tokens`.
*/
/** Claude only; fast is forwarded when the catalog declares fast rates. */
speed?: 'fast' | 'standard';
/** Claude only. */
safeguards?: SafeguardRequest[];
@@ -234,13 +271,23 @@ export interface ICompleteArguments {
metadata?: Record<string, string>;
prompt?: unknown;
prompt_cache_key?: string;
prompt_cache_retention?: 'in-memory' | '24h' | undefined;
/** `in-memory` is accepted as a spelling of OpenAI's `in_memory`. */
prompt_cache_retention?: 'in-memory' | 'in_memory' | '24h' | undefined;
prompt_cache_options?: PromptCacheOptions;
store?: boolean;
top_p?: number;
truncation?: 'auto' | 'disabled' | undefined;
background?: boolean;
service_tier?:
'auto' | 'default' | 'flex' | 'scale' | 'priority' | undefined;
| 'auto'
| 'default'
| 'flex'
| 'scale'
| 'priority'
| 'fast'
| 'ultrafast'
| 'standard'
| undefined;
max_tokens?: number;
temperature?: number;
reasoning?: { effort: ReasoningEffort } | undefined;
@@ -308,6 +355,10 @@ export interface IChatMessageResult {
export type IChatCompleteResult = IChatStreamResult | IChatMessageResult;
export interface IChatProvider {
/** Account/catalog-specific speed offerings, fetched before the credit hold. */
serviceSpeedModels?(
model: IChatModel,
): Promise<Partial<Record<'fast' | 'ultrafast', IChatModel>>>;
models(extra_params?: unknown): IChatModel[] | Promise<IChatModel[]>;
getDefaultModel(): string;
/**
+96 -30
View File
@@ -481,43 +481,86 @@ export const extractMeteredUsage = (usage) => {
};
/**
* Chat Completions usage as it's metered: `prompt_tokens` reports cached reads
* inside its count, so they come out of it and are priced only once, under
* `cached_tokens`.
* @typedef {{
* cached_tokens?: number | null;
* cache_write_tokens?: number | null;
* cache_write_tokens_details?: {
* ttl_30m_tokens?: number | null;
* ttl_12h_tokens?: number | null;
* } | null;
* }} OpenAiCacheDetails
*/
/**
* OpenAI-shaped usage as it's metered. The prompt count reports cached reads
* and cache writes inside it, so they come out of it and are priced once each
* under their own keys: `cached_tokens` for reads, `cache_write_tokens` for
* writes at the model's default lifetime and `cache_write_12h_tokens` for
* writes at OpenAI's 12h lifetime. Without the per-lifetime breakdown every
* write is a default-lifetime write: Chat Completions writes no 12h entries,
* and Responses reports the breakdown whenever a request asked for them. Reads
* the Chat Completions (`prompt_tokens`) and Responses (`input_tokens`)
* spellings alike.
*
* @param {import('openai/resources/completions.mjs').CompletionUsage | undefined} usage
* @param {{
* prompt_tokens?: number;
* completion_tokens?: number;
* prompt_tokens_details?: OpenAiCacheDetails | null;
* input_tokens?: number;
* output_tokens?: number;
* input_tokens_details?: OpenAiCacheDetails | null;
* }
* | undefined} usage
*/
export const splitCachedPrompt = (usage) => {
const details = usage?.prompt_tokens_details;
const details = usage?.prompt_tokens_details ?? usage?.input_tokens_details;
const cachedTokens = details?.cached_tokens ?? 0;
// Moonshot counts the prompt tokens it wrote to its prefix cache here;
// they're billed at the model's write rate, not the plain prompt rate.
// Moonshot and GPT-5.6+ count the prompt tokens they wrote to the prefix
// cache here; they're billed at the model's write rate, not the prompt rate.
const writeTokens =
typeof details?.cache_write_tokens === 'number'
? details.cache_write_tokens
: undefined;
const reported12h = details?.cache_write_tokens_details?.ttl_12h_tokens;
const write12hTokens =
typeof reported12h === 'number'
? Math.min(reported12h, writeTokens ?? 0)
: undefined;
return {
prompt_tokens:
(usage?.prompt_tokens ?? 0) - cachedTokens - (writeTokens ?? 0),
completion_tokens: usage?.completion_tokens ?? 0,
(usage?.prompt_tokens ?? usage?.input_tokens ?? 0) -
cachedTokens -
(writeTokens ?? 0),
completion_tokens:
usage?.completion_tokens ?? usage?.output_tokens ?? 0,
cached_tokens: cachedTokens,
...(writeTokens !== undefined
? { cache_write_tokens: writeTokens }
? { cache_write_tokens: writeTokens - (write12hTokens ?? 0) }
: {}),
...(write12hTokens !== undefined
? { cache_write_12h_tokens: write12hTokens }
: {}),
};
};
/**
* The `{prompt_tokens, completion_tokens, cached_tokens, cache_write_tokens}`
* shape every OpenAI-family `usage_calculator` already returns for billing,
* mapped to the provider-neutral `UsageDetails` the end-of-stream/non-stream
* result carries. `inputTokens`/`outputTokens` are the same numbers already
* billed — this never introduces a new figure, only exposes the breakdown.
* The `{prompt_tokens, completion_tokens, cached_tokens, cache_write_tokens,
* cache_write_12h_tokens}` shape every OpenAI-family `usage_calculator` already
* returns for billing, mapped to the provider-neutral `UsageDetails` the
* end-of-stream/non-stream result carries. `inputTokens`/`outputTokens` are the
* same numbers already billed — this never introduces a new figure, only
* exposes the breakdown.
*
* @param {Record<string, number> | undefined | null} trackedUsage
* @param {{ writeTtl?: '5m' | '30m' }} [opts] The lifetime `cache_write_tokens`
* were written with: 5m unless the provider says otherwise (OpenAI's default
* entries live 30m).
* @returns {import('../types.js').UsageDetails | undefined}
*/
export const usageDetailsFromTrackedUsage = (trackedUsage) => {
export const usageDetailsFromTrackedUsage = (
trackedUsage,
{ writeTtl = '5m' } = {},
) => {
if (!trackedUsage || typeof trackedUsage !== 'object') return undefined;
// OpenRouter, Infron and Ollama track `{prompt, completion,
// input_cache_read}` instead; any other shape is left to the driver.
@@ -526,12 +569,19 @@ export const usageDetailsFromTrackedUsage = (trackedUsage) => {
if (input === undefined && output === undefined) return undefined;
const cacheRead =
trackedUsage.cached_tokens ?? trackedUsage.input_cache_read;
const cacheWrite = trackedUsage.cache_write_tokens;
return {
inputTokens: input ?? 0,
outputTokens: output ?? 0,
...(cacheRead ? { cacheReadTokens: cacheRead } : {}),
...(trackedUsage.cache_write_tokens
? { cacheWrite5mTokens: trackedUsage.cache_write_tokens }
...(cacheWrite && writeTtl === '30m'
? { cacheWrite30mTokens: cacheWrite }
: {}),
...(cacheWrite && writeTtl !== '30m'
? { cacheWrite5mTokens: cacheWrite }
: {}),
...(trackedUsage.cache_write_12h_tokens
? { cacheWrite12hTokens: trackedUsage.cache_write_12h_tokens }
: {}),
};
};
@@ -600,12 +650,15 @@ export const create_chat_stream_handler =
block.end();
};
let serviceTier;
let last_usage = null;
let last_extra_content = null;
let finish_reason = null;
for await (let chunk of completion) {
await chatStream.waitForDrain();
chunk = deviations.chunk_but_like_actually(chunk);
if (chunk.service_tier !== undefined)
serviceTier = chunk.service_tier;
const chunk_usage = deviations.index_usage_from_stream_chunk(chunk);
if (chunk_usage) last_usage = chunk_usage;
if (chunk.choices.length < 1) continue;
@@ -696,6 +749,7 @@ export const create_chat_stream_handler =
const usage = last_usage
? usage_calculator({
usage: last_usage,
service_tier: serviceTier,
extra_content: last_extra_content,
setUsageCosts: (c) => chatStream.setUsageCosts(c),
setUsageDetails: (d) => {
@@ -729,6 +783,7 @@ export const create_chat_stream_handler_responses_api =
const message = chatStream.message();
const textblock = message.contentBlock({ type: 'text' });
let serviceTier;
let last_usage = null;
let completed = false;
let sawFunctionCall = false;
@@ -737,6 +792,8 @@ export const create_chat_stream_handler_responses_api =
let toolUsage = null;
for await (const chunk of completion) {
await chatStream.waitForDrain();
if (chunk.response?.service_tier !== undefined)
serviceTier = chunk.response.service_tier;
if (chunk.type === 'response.failed' || chunk.type === 'error') {
throw new Error(
chunk.response?.error?.message ??
@@ -864,12 +921,17 @@ export const create_chat_stream_handler_responses_api =
// Missing usage is left undefined rather than fed to the calculator —
// see the sibling handler above, including why usage is reported
// before the block flushes.
let usageDetails;
const usage = last_usage
? usage_calculator({
usage: last_usage,
service_tier: serviceTier,
webSearchCalls,
tool_usage: toolUsage,
setUsageCosts: (c) => chatStream.setUsageCosts(c),
setUsageDetails: (d) => {
usageDetails = d;
},
})
: undefined;
chatStream.reportUsage(usage);
@@ -877,7 +939,7 @@ export const create_chat_stream_handler_responses_api =
reason:
incompleteReason ?? (sawFunctionCall ? 'tool_use' : 'end_turn'),
});
const usageDetails = usageDetailsFromTrackedUsage(usage);
usageDetails ??= usageDetailsFromTrackedUsage(usage);
if (usageDetails) chatStream.setUsageDetails(usageDetails);
textblock.end();
@@ -918,6 +980,7 @@ export const handle_completion_output = async (
/**
* @type {Record<string, unknown> & {
* usage_calculator: (args: {
* service_tier?: string;
* usage: import('openai/resources/completions.mjs').CompletionUsage;
* setUsageCosts: (costs: Record<string, number>) => void;
* setUsageDetails: (
@@ -1012,9 +1075,11 @@ export const handle_completion_output = async (
* @param {((text: string) => Promise<{ flagged: boolean }>) | undefined} [params.moderate]
* @param {(args: {
* usage: import('openai/resources/responses/responses.mjs').ResponseUsage;
* service_tier?: string;
* webSearchCalls?: number;
* tool_usage?: Record<string, unknown>;
* setUsageCosts?: (costs: Record<string, number>) => void;
* setUsageDetails?: (details: import('../types').UsageDetails) => void;
* }) => unknown} params.usage_calculator
* @param {() => Promise<void>} [params.finally_fn]
* @returns {ReturnType<import('../types').IChatProvider['complete']>}
@@ -1057,16 +1122,6 @@ export const handle_completion_output_responses_api = async ({
// Inline-compaction artifact, if the upstream compacted this turn.
const compactionItem = output.find((item) => item?.type === 'compaction');
const is_empty = completion.output_text.trim() === '';
if (is_empty && responseToolCalls.length < 1 && !compactionItem) {
// GPT refuses to generate an empty response if you ask it to,
// so this will probably only happen on an error condition.
// A compaction-only output is legitimate, so don't reject it.
throw new HttpError(400, 'an empty response was generated', {
legacyCode: 'bad_response',
});
}
// Reasoning models return `reasoning` output items; their human-readable
// text only exists when the caller requested summaries via
// `reasoning: { summary: ... }` (raw chain-of-thought is never returned).
@@ -1156,16 +1211,27 @@ export const handle_completion_output_responses_api = async ({
setUsageCosts: (c) => {
ret.usageCosts = c;
},
setUsageDetails: (d) => {
ret.usageDetails = d;
},
})
: {
input_tokens: completion.usage.input_tokens,
output_tokens: completion.usage.output_tokens,
};
if (usage_calculator) {
if (usage_calculator && ret.usageDetails === undefined) {
const usageDetails = usageDetailsFromTrackedUsage(ret.usage);
if (usageDetails) ret.usageDetails = usageDetails;
}
// Empty output can still include paid reasoning and input tokens.
const isEmpty = completion.output_text.trim() === '';
if (isEmpty && responseToolCalls.length < 1 && !compactionItem) {
throw new HttpError(400, 'an empty response was generated', {
legacyCode: 'bad_response',
});
}
const mod_text = completion.output_text;
if (moderate && mod_text !== null) {
await applyModeration(moderate, mod_text);
@@ -247,6 +247,40 @@ describe('usageDetailsFromTrackedUsage', () => {
});
});
it('labels cache writes by the lifetime the provider says it wrote them with', () => {
expect(
usageDetailsFromTrackedUsage(
{
prompt_tokens: 10,
completion_tokens: 5,
cached_tokens: 3,
cache_write_tokens: 11,
cache_write_12h_tokens: 6012,
},
{ writeTtl: '30m' },
),
).toEqual({
inputTokens: 10,
outputTokens: 5,
cacheReadTokens: 3,
cacheWrite30mTokens: 11,
cacheWrite12hTokens: 6012,
});
// Zero counts, as OpenAI reports on a cache hit, add no field.
expect(
usageDetailsFromTrackedUsage(
{
prompt_tokens: 10,
completion_tokens: 5,
cached_tokens: 3,
cache_write_tokens: 0,
cache_write_12h_tokens: 0,
},
{ writeTtl: '30m' },
),
).toEqual({ inputTokens: 10, outputTokens: 5, cacheReadTokens: 3 });
});
it('returns undefined for a missing/non-object usage', () => {
expect(usageDetailsFromTrackedUsage(undefined)).toBeUndefined();
expect(usageDetailsFromTrackedUsage(null)).toBeUndefined();
@@ -962,6 +996,66 @@ describe('splitCachedPrompt', () => {
cached_tokens: 3,
});
});
it('reads the Responses usage spelling', () => {
expect(
splitCachedPrompt({
input_tokens: 6026,
output_tokens: 5,
input_tokens_details: { cached_tokens: 0, cache_write_tokens: 6023 },
}),
).toEqual({
prompt_tokens: 3,
completion_tokens: 5,
cached_tokens: 0,
cache_write_tokens: 6023,
});
});
it('splits 12h writes out of the write count when the breakdown is reported', () => {
// One request can write both lifetimes: an explicit 12h breakpoint
// plus the implicit 30m one OpenAI adds at the end of the prompt.
expect(
splitCachedPrompt({
input_tokens: 6026,
output_tokens: 5,
input_tokens_details: {
cached_tokens: 0,
cache_write_tokens: 6023,
cache_write_tokens_details: {
ttl_12h_tokens: 6012,
ttl_30m_tokens: 11,
},
},
}),
).toEqual({
prompt_tokens: 3,
completion_tokens: 5,
cached_tokens: 0,
cache_write_tokens: 11,
cache_write_12h_tokens: 6012,
});
});
it('never reports more 12h writes than writes in total', () => {
expect(
splitCachedPrompt({
input_tokens: 100,
output_tokens: 1,
input_tokens_details: {
cached_tokens: 0,
cache_write_tokens: 40,
cache_write_tokens_details: { ttl_12h_tokens: 50 },
},
}),
).toEqual({
prompt_tokens: 60,
completion_tokens: 1,
cached_tokens: 0,
cache_write_tokens: 0,
cache_write_12h_tokens: 40,
});
});
});
// ── recorded usage costs ────────────────────────────────────────────
@@ -19,13 +19,15 @@
import type { Actor } from '../../../core/actor.js';
import type { MeteringService } from '../../../services/metering/MeteringService.js';
import type { IChatModel } from '../types.js';
import type { IChatModel, ServiceSpeed } from '../types.js';
import { serviceSpeedBillingModel } from './serviceSpeed.js';
import { buildCostsOverride } from './pricing.js';
/** Microcents per US dollar. */
const MICROCENTS_PER_USD = 100_000_000;
export interface MeterChatUsageOptions {
serviceSpeed?: ServiceSpeed;
/**
* What the upstream says it billed, in USD. Recorded as one `billedUsage`
* line instead of pricing the tokens, which are still recorded at zero.
@@ -77,10 +79,15 @@ export const meterChatUsage = (
authoritativeUsd,
costOverrides,
pricingTime,
serviceSpeed = 'standard',
}: MeterChatUsageOptions = {},
): { usage: Record<string, number>; costs: Record<string, number> } => {
const priced = {
...buildCostsOverride(usage, model, pricingTime),
...buildCostsOverride(
usage,
serviceSpeedBillingModel(model, serviceSpeed),
pricingTime,
),
...costOverrides,
};
if (authoritativeUsd !== undefined) {
@@ -22,11 +22,14 @@ import { describe, expect, it } from 'vitest';
import type { ICompleteArguments } from '../types.js';
import {
clampReasoningEffort,
messagesHaveCacheBreakpointTtl,
openAICompatParams,
outputFormatFromResponseFormat,
outputFormatFromResponsesText,
outputFormatToResponseFormat,
outputFormatToResponsesText,
promptCacheOptionsToWire,
promptCacheRetentionToWire,
rejectStatefulResponsesFields,
toolChoiceFromWire,
toolChoiceToWire,
@@ -334,3 +337,109 @@ describe('rejectStatefulResponsesFields', () => {
).toThrow(/previous_response_id/);
});
});
describe('promptCacheRetentionToWire', () => {
it('spells the in-memory retention the way the upstreams expect', () => {
expect(promptCacheRetentionToWire('in-memory')).toBe('in_memory');
expect(promptCacheRetentionToWire('in_memory')).toBe('in_memory');
expect(promptCacheRetentionToWire('24h')).toBe('24h');
expect(promptCacheRetentionToWire(undefined)).toBeUndefined();
});
});
describe('promptCacheOptionsToWire', () => {
it('forwards mode and ttl and nothing else', () => {
expect(
promptCacheOptionsToWire({
mode: 'explicit',
ttl: '12h',
prewarm: true,
comparison_response_id: 'resp_1',
}),
).toEqual({ mode: 'explicit', ttl: '12h' });
expect(promptCacheOptionsToWire({ ttl: '30m' })).toEqual({
ttl: '30m',
});
});
it('sends nothing for an absent or empty object', () => {
expect(promptCacheOptionsToWire(undefined)).toBeUndefined();
expect(promptCacheOptionsToWire(null)).toBeUndefined();
expect(promptCacheOptionsToWire({})).toBeUndefined();
expect(promptCacheOptionsToWire({ prewarm: true })).toBeUndefined();
});
it('rejects a lifetime or mode OpenAI does not offer', () => {
expect(() => promptCacheOptionsToWire({ ttl: '2h' })).toThrow(
expect.objectContaining({ statusCode: 400 }),
);
expect(() => promptCacheOptionsToWire({ ttl: '24h' })).toThrow(
/30m.*12h/,
);
expect(() => promptCacheOptionsToWire({ mode: 'auto' })).toThrow(
/implicit.*explicit/,
);
expect(() => promptCacheOptionsToWire('12h')).toThrow(
/must be an object/,
);
});
});
describe('messagesHaveCacheBreakpointTtl', () => {
it('finds a breakpoint lifetime on any content part', () => {
expect(
messagesHaveCacheBreakpointTtl([
{ role: 'user', content: 'plain' },
{
role: 'system',
content: [
{ type: 'text', text: 'a' },
{
type: 'text',
text: 'b',
prompt_cache_breakpoint: {
mode: 'explicit',
ttl: '30m',
},
},
],
},
]),
).toBe(true);
expect(
messagesHaveCacheBreakpointTtl([
{
role: 'user',
content: {
type: 'text',
text: 'a',
prompt_cache_breakpoint: { ttl: '12h' },
},
},
]),
).toBe(true);
});
it('ignores breakpoints without a lifetime and odd message shapes', () => {
expect(
messagesHaveCacheBreakpointTtl([
{
role: 'system',
content: [
{
type: 'text',
text: 'a',
prompt_cache_breakpoint: { mode: 'explicit' },
},
'bare string part',
null,
],
},
{ role: 'user', content: null },
null,
]),
).toBe(false);
expect(messagesHaveCacheBreakpointTtl(undefined)).toBe(false);
expect(messagesHaveCacheBreakpointTtl('nope')).toBe(false);
});
});
@@ -29,6 +29,7 @@ import { HttpError } from '../../../core/http/HttpError.js';
import type {
ICompleteArguments,
OutputFormat,
PromptCacheOptions,
ReasoningEffort,
ToolChoice,
} from '../types.js';
@@ -305,6 +306,80 @@ export const openAICompatParams = (
return out;
};
// -- prompt caching ----------------------------------------------------------
/**
* The wire spelling of `prompt_cache_retention`. Puter also accepts the
* hyphenated `in-memory`, which every OpenAI-shaped upstream rejects.
*/
export const promptCacheRetentionToWire = (
retention: ICompleteArguments['prompt_cache_retention'],
): 'in_memory' | '24h' | undefined =>
retention === 'in-memory' ? 'in_memory' : retention;
const PROMPT_CACHE_MODES = new Set(['implicit', 'explicit']);
const PROMPT_CACHE_TTLS = new Set(['30m', '12h']);
/**
* `prompt_cache_options` as forwarded upstream: `mode` and `ttl` only, each
* checked against the values OpenAI accepts, so a bad value fails here with a
* clear message instead of as an upstream 400 the fallback loop may hide.
* `comparison_response_id` names a stored response, which Puter never keeps,
* and `prewarm` is dropped with it.
*/
export const promptCacheOptionsToWire = (
options: unknown,
): PromptCacheOptions | undefined => {
if (options === undefined || options === null) return undefined;
if (typeof options !== 'object' || Array.isArray(options)) {
throw new HttpError(400, '`prompt_cache_options` must be an object', {
legacyCode: 'bad_request',
});
}
const { mode, ttl } = options as Record<string, unknown>;
if (mode !== undefined && !PROMPT_CACHE_MODES.has(mode as string)) {
throw new HttpError(
400,
'`prompt_cache_options.mode` must be `implicit` or `explicit`',
{ legacyCode: 'bad_request' },
);
}
if (ttl !== undefined && !PROMPT_CACHE_TTLS.has(ttl as string)) {
throw new HttpError(
400,
'`prompt_cache_options.ttl` must be `30m` or `12h`',
{ legacyCode: 'bad_request' },
);
}
const wire: PromptCacheOptions = {
...(mode !== undefined
? { mode: mode as PromptCacheOptions['mode'] }
: {}),
...(ttl !== undefined ? { ttl: ttl as PromptCacheOptions['ttl'] } : {}),
};
return Object.keys(wire).length ? wire : undefined;
};
/**
* Whether any content part carries a `prompt_cache_breakpoint` with its own
* `ttl`. Chat Completions rejects the field whatever its value; only the
* Responses API honours a per-breakpoint lifetime.
*/
export const messagesHaveCacheBreakpointTtl = (messages: unknown): boolean =>
Array.isArray(messages) &&
messages.some((message) => {
const content = (message as { content?: unknown } | null)?.content;
const parts = Array.isArray(content) ? content : [content];
return parts.some(
(part) =>
(
part as {
prompt_cache_breakpoint?: { ttl?: unknown } | null;
} | null
)?.prompt_cache_breakpoint?.ttl !== undefined,
);
});
// -- Responses server-side state ---------------------------------------------
const STATEFUL_RESPONSES_FIELDS = [
@@ -0,0 +1,150 @@
/*
* 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.
*
* Puter 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 Puter. If not, see <https://www.gnu.org/licenses/>.
*/
import { describe, expect, it } from 'vitest';
import type { IChatModel, ServiceSpeed } from '../types.js';
import { ALIBABA_MODELS } from '../providers/alibaba/models.js';
import { AZURE_MODELS } from '../providers/azure/models.js';
import { BYTEPLUS_MODELS } from '../providers/byteplus/models.js';
import { CLAUDE_MODELS } from '../providers/claude/models.js';
import { DEEPSEEK_MODELS } from '../providers/deepseek/models.js';
import { GEMINI_MODELS } from '../providers/gemini/models.js';
import { GROQ_MODELS } from '../providers/groq/models.js';
import { HOONIFY_MODELS } from '../providers/hoonify/models.js';
import { META_MODELS } from '../providers/meta/models.js';
import { MINIMAX_MODELS } from '../providers/minimax/models.js';
import { MISTRAL_MODELS } from '../providers/mistral/models.js';
import { MOONSHOT_MODELS } from '../providers/moonshot/models.js';
import { OPEN_AI_MODELS } from '../providers/openai/models.js';
import { XAI_MODELS } from '../providers/xai/models.js';
import { ZAI_MODELS } from '../providers/zai/models.js';
import { shouldPresentAsOpenAI } from './normalizeToOpenAI.js';
import {
isServiceSpeedUnavailable,
lowerServiceSpeed,
selectServiceSpeed,
servedServiceSpeed,
serviceSpeedBillingModel,
} from './serviceSpeed.js';
const catalogs: Array<[string, IChatModel[]]> = [
['alibaba', ALIBABA_MODELS],
['azure-openai', AZURE_MODELS],
['byteplus', BYTEPLUS_MODELS],
['claude', CLAUDE_MODELS],
['deepseek', DEEPSEEK_MODELS],
['gemini', GEMINI_MODELS],
['groq', GROQ_MODELS],
['hoonify', HOONIFY_MODELS],
['meta', META_MODELS],
['minimax', MINIMAX_MODELS],
['mistral', MISTRAL_MODELS],
['moonshotai', MOONSHOT_MODELS],
['openai-completion', OPEN_AI_MODELS],
['openai-responses', OPEN_AI_MODELS],
['xai', XAI_MODELS],
['zai', ZAI_MODELS],
];
const speeds: ServiceSpeed[] = ['standard', 'fast', 'ultrafast'];
describe('service speed seeded fuzzing', () => {
it('preserves catalog, request, normalization, and billing invariants across model changes', () => {
let seed = 0x51eed;
const pick = <T>(values: T[]): T => {
seed = (Math.imul(seed, 1664525) + 1013904223) >>> 0;
return values[seed % values.length]!;
};
const seenProviders = new Set<string>();
for (let index = 0; index < 10_000; index++) {
const [provider, catalog] = pick(catalogs);
seenProviders.add(provider);
const base = { ...structuredClone(pick(catalog)), provider };
const before = structuredClone(base);
Object.freeze(base.costs);
Object.freeze(base);
const args = Object.freeze({
model: base.id,
messages: [{ role: 'user', content: `Case ${index}` }],
serviceSpeed: pick([...speeds, undefined]),
normalize: pick([true, false, undefined]),
temperature: pick([0, 0.5, 1]),
service_tier: pick(['flex' as const, 'ultrafast' as const, undefined]),
speed: pick(['standard' as const, 'fast' as const, undefined]),
});
const selected = selectServiceSpeed(base, args, (id) => {
const variant = catalog.find((entry) => entry.id === id);
return variant && { ...variant, provider };
});
expect(base).toEqual(before);
expect(selected.args.messages).toBe(args.messages);
expect(selected.args.temperature).toBe(args.temperature);
expect(selected.model.provider).toBe(provider);
expect(selected.model.release_date).toBe(base.release_date);
expect(
shouldPresentAsOpenAI(selected.args, selected.model.release_date),
).toBe(shouldPresentAsOpenAI(args, base.release_date));
if (args.serviceSpeed === undefined) {
expect(selected.args).toBe(args);
expect(selected.model).toBe(base);
continue;
}
expect(speeds.indexOf(selected.speed)).toBeLessThanOrEqual(
speeds.indexOf(args.serviceSpeed),
);
expect(selected.args.serviceSpeed).toBe(selected.speed);
if (args.serviceSpeed === 'standard') {
expect(selected.args.speed).not.toBe('fast');
expect(selected.args.service_tier).not.toBe('ultrafast');
}
for (const cost of Object.values(selected.model.costs)) {
expect(Number.isFinite(cost)).toBe(true);
expect(cost).toBeGreaterThanOrEqual(0);
}
if (selected.model.serviceSpeedPricing) {
const settled = serviceSpeedBillingModel(selected.model, 'standard');
expect(settled.costs).toEqual(base.costs);
expect(settled.pricingOverrides).toEqual(base.pricingOverrides);
}
let speed = selected.speed;
for (let attempts = 0; speed !== 'standard'; attempts++) {
expect(attempts).toBeLessThan(2);
speed = lowerServiceSpeed(speed);
}
}
expect([...seenProviders].sort()).toEqual(catalogs.map(([provider]) => provider).sort());
});
it('handles malformed upstream tier and admission-error metadata without coercion or retries', () => {
const values = [null, false, 0, 429, '', 'unrelated', [], {},
['service_tier capacity unavailable'],
{ toString: null }, { toString: 'priority capacity unavailable' }];
for (const value of values) {
expect(isServiceSpeedUnavailable(value)).toBe(false);
for (const status of [undefined, 400, 401, 403, 404, 429, 500, 503]) {
for (const variant of [false, true]) {
expect(isServiceSpeedUnavailable({ status, message: value }, variant)).toBe(false);
expect(isServiceSpeedUnavailable({ status, error: { message: value } }, variant)).toBe(false);
}
}
expect(servedServiceSpeed({ usage: value })).toBe('standard');
expect(servedServiceSpeed({ service_tier: value })).toBe('standard');
expect(servedServiceSpeed({ usage: { speed: value, service_tier: value } })).toBe('standard');
}
});
});
@@ -0,0 +1,148 @@
/*
* 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 { describe, expect, it } from 'vitest';
import {
makeMeteringStub,
optionalEnv,
withTestActor,
} from '../../integrationTestUtil.js';
import type {
IChatMessageResult,
IChatProvider,
ICompleteArguments,
} from '../types.js';
import { OpenAiResponsesChatProvider } from '../providers/openai/OpenAiChatResponsesProvider.js';
import { GeminiChatProvider } from '../providers/gemini/GeminiChatProvider.js';
import { MiniMaxProvider } from '../providers/minimax/MiniMaxProvider.js';
import { MoonshotProvider } from '../providers/moonshot/MoonshotProvider.js';
import { MistralAIProvider } from '../providers/mistral/MistralAiProvider.js';
import { selectServiceSpeed } from './serviceSpeed.js';
type Case = {
name: string;
env: string;
provider: string;
model: string;
build: (key: string) => IChatProvider;
};
const cases: Case[] = [
{
name: 'OpenAI Ultrafast',
env: 'PUTER_TEST_AI_OPENAI_API_KEY',
provider: 'openai-responses',
model: 'gpt-6.1-sol',
build: (key) =>
new OpenAiResponsesChatProvider(
{ apiKey: key },
makeMeteringStub(),
),
},
{
name: 'Gemini Priority',
env: 'PUTER_TEST_AI_GEMINI_API_KEY',
provider: 'gemini',
model: 'gemini-3.8-flash',
build: (key) =>
new GeminiChatProvider({ apiKey: key }, makeMeteringStub()),
},
{
name: 'MiniMax Priority',
env: 'PUTER_TEST_AI_MINIMAX_API_KEY',
provider: 'minimax',
model: 'minimax-m3',
build: (key) =>
new MiniMaxProvider({ apiKey: key }, makeMeteringStub()),
},
{
name: 'Moonshot Highspeed',
env: 'PUTER_TEST_AI_MOONSHOT_API_KEY',
provider: 'moonshotai',
model: 'kimi-k3.1-pro',
build: (key) =>
new MoonshotProvider({ apiKey: key }, makeMeteringStub()),
},
{
name: 'Mistral served tier',
env: 'PUTER_TEST_AI_MISTRAL_API_KEY',
provider: 'mistral',
model: 'mistral-medium-latest',
build: (key) =>
new MistralAIProvider({ apiKey: key }, makeMeteringStub()),
},
];
for (const testCase of cases) {
describe.skipIf(!optionalEnv(testCase.env))(
`serviceSpeed ${testCase.name} (integration)`,
() => {
it(
'completes with a selected speed and normalized text',
{ timeout: 90_000 },
async () => {
const provider = testCase.build(optionalEnv(testCase.env)!);
const catalog = (await provider.models()).map((model) => ({
...model,
provider: testCase.provider,
}));
const base = catalog.find(
(model) =>
model.id === testCase.model ||
model.aliases?.includes(testCase.model),
)!;
expect(base).toBeDefined();
const args: ICompleteArguments = {
model: base.id,
messages: [
{ role: 'user', content: 'Reply with exactly OK.' },
],
serviceSpeed: 'ultrafast',
max_tokens: 256,
reasoning_effort: 'low',
normalize: true,
};
const selection = selectServiceSpeed(base, args, (id) =>
catalog.find((model) => model.id === id),
);
expect(selection.speed).toBe(
testCase.provider === 'openai-responses'
? 'ultrafast'
: 'fast',
);
const result = (await withTestActor(() =>
provider.complete(
{ ...selection.args, model: selection.model.id },
selection.model,
),
)) as IChatMessageResult;
expect(typeof result.message.content).toBe('string');
expect(result.message.content.length).toBeGreaterThan(0);
if (
['openai-responses', 'gemini', 'minimax'].includes(
testCase.provider,
)
)
expect(result.usageDetails?.serviceSpeed).toBe(
selection.speed,
);
},
);
},
);
}
@@ -0,0 +1,421 @@
/*
* 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 { describe, expect, it } from 'vitest';
import { Writable } from 'node:stream';
import { AIChatStream } from './Streaming.js';
import {
handle_completion_output,
handle_completion_output_responses_api,
} from './OpenAIUtil.js';
import type { IChatModel, ServiceSpeed } from '../types.js';
import {
requestedServiceSpeed,
selectServiceSpeed,
servedServiceSpeed,
serviceSpeedBillingModel,
isServiceSpeedUnavailable,
} from './serviceSpeed.js';
import { meterChatUsage } from './meterChatUsage.js';
import { OPEN_AI_MODELS } from '../providers/openai/models.js';
import { XAI_MODELS } from '../providers/xai/models.js';
import { GEMINI_MODELS } from '../providers/gemini/models.js';
import { CLAUDE_MODELS } from '../providers/claude/models.js';
const model = (provider: string, id: string): IChatModel => ({
provider,
id,
serviceSpeedRates: [...OPEN_AI_MODELS, ...XAI_MODELS, ...GEMINI_MODELS, ...CLAUDE_MODELS]
.find((entry) => entry.id === id)?.serviceSpeedRates,
costs_currency: 'usd-cents',
input_cost_key: 'prompt_tokens',
output_cost_key: 'completion_tokens',
max_tokens: 1000,
costs: {
tokens: 1_000_000,
prompt_tokens: 200,
completion_tokens: 1000,
cached_tokens: 10,
web_search_requests: 1_000_000,
},
});
const request = (serviceSpeed?: ServiceSpeed) => ({
model: 'test',
messages: [{ role: 'user', content: 'Hello' }],
serviceSpeed,
});
const noVariant = () => undefined;
describe('service speed selection', () => {
it.each([2, { prompt_tokens: 400, completion_tokens: 2000 }])(
'uses catalog rates independently of provider and model names: %j',
(rates) => {
const entry = {
...model('catalog-provider', 'renamed-model'),
serviceSpeedRates: { fast: rates },
};
const selected = selectServiceSpeed(entry, request('ultrafast'), noVariant);
expect(selected.speed).toBe('fast');
expect(selected.model.costs.prompt_tokens).toBe(400);
expect(selected.model.costs.completion_tokens).toBe(2000);
expect(entry.costs.prompt_tokens).toBe(200);
},
);
it('preserves an omitted option and native parameters', () => {
const entry = model('openai-responses', 'gpt-6.1-sol');
const args = { ...request(), service_tier: 'flex' as const };
const selected = selectServiceSpeed(entry, args, noVariant);
expect(selected.model).toBe(entry);
expect(selected.args).toBe(args);
});
it.each([
[{ service_tier: 'priority' }, 'openai-responses', 'fast'],
[{ service_tier: 'ultrafast' }, 'openai-responses', 'ultrafast'],
[{ service_tier: 'auto' }, 'mistral', 'fast'],
[{ speed: 'fast' }, 'claude', 'fast'],
[{ service_tier: 'auto' }, 'openai-responses', undefined],
[{ service_tier: 'flex' }, 'openai-responses', undefined],
[{ speed: 'fast' }, 'openai-responses', undefined],
[{ serviceSpeed: 'standard', service_tier: 'priority' }, 'openai-responses', 'standard'],
] as const)('reads %j on %s as speed %s', (args, provider, speed) => {
expect(requestedServiceSpeed(args, provider)).toBe(speed);
});
it('prices a native priority tier like fast service', () => {
const entry = model('openai-responses', 'gpt-6.1-sol');
const args = { ...request(), service_tier: 'priority' as const };
const selected = selectServiceSpeed(
entry,
{ ...args, serviceSpeed: requestedServiceSpeed(args, entry.provider) },
noVariant,
);
const explicit = selectServiceSpeed(entry, request('fast'), noVariant);
expect(selected.speed).toBe('fast');
expect(selected.model).toEqual(explicit.model);
expect(selected.args.service_tier).toBe('priority');
});
it.each([
'deepseek',
'zai',
'groq',
'byteplus',
'together-ai',
'meta',
'ollama',
'hoonify',
'neuralwatt',
'fake-chat',
])('uses standard when %s has no verified faster offering', (provider) => {
const selected = selectServiceSpeed(
model(provider, 'some-model'),
request('ultrafast'),
noVariant,
);
expect(selected.speed).toBe('standard');
expect(selected.args.service_tier).toBeUndefined();
});
it.each(['standard', 'fast', 'ultrafast'] as const)(
'selects %s without changing the model or catalog prices',
(speed) => {
const entry = model('openai-responses', 'gpt-6.1-sol');
const selected = selectServiceSpeed(
entry,
request(speed),
noVariant,
);
expect(selected.speed).toBe(speed);
expect(selected.model.id).toBe(entry.id);
expect(selected.model.costs.prompt_tokens).toBe(
200 * { standard: 1, fast: 2, ultrafast: 6 }[speed],
);
expect(selected.model.costs.web_search_requests).toBe(1_000_000);
expect(entry.costs.prompt_tokens).toBe(200);
},
);
it('downgrades ultrafast to fast on a model without ultrafast', () => {
const selected = selectServiceSpeed(
model('xai', 'grok-4.7'),
request('ultrafast'),
noVariant,
);
expect(selected.speed).toBe('fast');
expect(selected.args.service_tier).toBe('priority');
});
it('keeps a compatibility-only Gemini deployment at standard speed', () => {
const entry = {
...model('gemini', 'gemini-3.8-flash'),
serviceSpeeds: ['standard'] as ServiceSpeed[],
};
expect(
selectServiceSpeed(entry, request('ultrafast'), noVariant).speed,
).toBe('standard');
});
it('uses Claude speed independently of its service tier', () => {
const entry = model('claude', 'claude-opus-5-5');
expect(
selectServiceSpeed(entry, request('ultrafast'), noVariant).args
.speed,
).toBe('fast');
expect(
selectServiceSpeed(entry, request('ultrafast'), noVariant).args
.service_tier,
).toBeUndefined();
expect(
servedServiceSpeed({
usage: { speed: 'fast', service_tier: 'standard' },
}),
).toBe('fast');
});
it.each([
['minimax', 'minimax-m2.7', 'minimax-m2.7-highspeed'],
['moonshotai', 'kimi-k3.1-pro', 'kimi-k3.1-pro-highspeed'],
['alibaba', 'glm-5.3', 'glm-5.3-prime'],
['alibaba', 'glm-5.2', 'glm-5.2-fast-preview'],
['infron', 'infron:vendor/model', 'infron:vendor/model:priority'],
])(
'selects an equivalent %s variant and preserves normalization policy',
(provider, id, variantId) => {
const base = {
...model(provider, id),
serviceSpeedVariants: { fast: variantId },
release_date: '2026-08-01',
};
const variant = {
...model(provider, variantId),
release_date: '2026-10-01',
};
const selected = selectServiceSpeed(
base,
request('ultrafast'),
(candidate) => (candidate === variantId ? variant : undefined),
);
expect(selected.model.id).toBe(variantId);
expect(selected.model.release_date).toBe(base.release_date);
expect(selected.speed).toBe('fast');
expect(
selectServiceSpeed(base, request('fast'), noVariant).speed,
).toBe('standard');
},
);
it('keeps caller media on Gemini compatibility when native speed cannot carry it', () => {
const args = {
...request('fast'),
messages: [
{
role: 'user',
content: [
{
type: 'video_url',
video_url: { url: 'data:video/mp4;base64,AA==' },
},
],
},
],
};
expect(
selectServiceSpeed(
model('gemini', 'gemini-3.8-flash'),
args,
noVariant,
).speed,
).toBe('standard');
});
});
describe('served speed billing', () => {
it.each(['standard', 'fast', 'ultrafast'] as const)(
'settles an ultrafast hold at the served %s rate',
(speed) => {
const selected = selectServiceSpeed(
model('openai-responses', 'gpt-6.1-sol'),
request('ultrafast'),
noVariant,
).model;
const recorded: Array<Record<string, number> | undefined> = [];
const meter = {
utilRecordUsageObject: (
_usage: Record<string, number>,
_actor: unknown,
_key: string,
costs?: Record<string, number>,
) => {
recorded.push(costs);
},
};
const result = meterChatUsage(
meter as never,
undefined,
'openai:gpt-6.1-sol',
selected,
{ prompt_tokens: 10, completion_tokens: 5, cached_tokens: 20 },
{ serviceSpeed: speed },
);
expect(result.costs.prompt_tokens).toBe(
2000 * { standard: 1, fast: 2, ultrafast: 6 }[speed],
);
expect(result.costs.cached_tokens).toBe(
200 * { standard: 1, fast: 2, ultrafast: 6 }[speed],
);
expect(recorded).toEqual([result.costs]);
},
);
it.each([
['fast', 2],
['ultrafast', 6],
] as const)(
'bills a served %s tier at its catalog rate without a selection snapshot',
(speed, multiplier) => {
const entry = model('openai-responses', 'gpt-6.1-sol');
entry.pricingOverrides = [
{
minPromptTokens: 100,
costs: { prompt_tokens: 400, completion_tokens: 1500 },
},
];
const billed = serviceSpeedBillingModel(entry, speed);
expect(billed.costs.prompt_tokens).toBe(200 * multiplier);
expect(billed.pricingOverrides?.[0]?.costs.prompt_tokens).toBe(
400 * multiplier,
);
expect(serviceSpeedBillingModel(entry, 'standard')).toBe(entry);
},
);
it('bills a served premium tier as standard when the catalog has no rate for it', () => {
const entry = model('groq', 'some-model');
expect(serviceSpeedBillingModel(entry, 'fast').costs).toEqual(
entry.costs,
);
});
it('restores standard scheduled and long-context rates after a downgrade', () => {
const entry = model('openai-responses', 'gpt-6.1-sol');
entry.pricingOverrides = [
{
minPromptTokens: 100,
costs: { prompt_tokens: 400, completion_tokens: 1500 },
},
];
const selected = selectServiceSpeed(
entry,
request('ultrafast'),
noVariant,
).model;
expect(
serviceSpeedBillingModel(selected, 'standard').pricingOverrides,
).toEqual(entry.pricingOverrides);
expect(
serviceSpeedBillingModel(selected, 'fast').pricingOverrides?.[0]
.costs.prompt_tokens,
).toBe(800);
});
it.each([
[{ service_tier: 'priority' }, 'fast'],
[{ usage: { serviceTier: 'priority' } }, 'fast'],
[{ usage: { service_tier: 'standard' } }, 'standard'],
[{ service_tier: 'ultrafast' }, 'ultrafast'],
[{}, 'standard'],
])('reads actual speed from %j', (source, speed) => {
expect(servedServiceSpeed(source)).toBe(speed);
});
});
describe('speed admission failures', () => {
it.each([
[{ status: 429, message: 'Fast mode rate limit exceeded' }, true],
[{ status: 403, message: 'Ultrafast access unavailable' }, true],
[{ status: 400, message: 'service_tier is not supported' }, true],
[{ status: 401, message: 'Invalid API key' }, false],
[{ status: 429, message: 'Rate limit exceeded' }, false],
[{ status: 400, message: 'Invalid messages' }, false],
])('classifies %j without swallowing unrelated errors', (error, retry) => {
expect(isServiceSpeedUnavailable(error)).toBe(retry);
});
it('downgrades a missing speed variant without retrying an invalid base model', () => {
const error = { status: 404, message: 'Model not found' };
expect(isServiceSpeedUnavailable(error, true)).toBe(true);
expect(isServiceSpeedUnavailable(error)).toBe(false);
});
});
describe('streamed service tier metadata', () => {
it('retains a tier from an earlier Chat Completions chunk until usage arrives', async () => {
let servedTier: string | undefined;
const result = await handle_completion_output({
stream: true,
completion: (async function* () {
yield {
service_tier: 'priority',
choices: [{ index: 0, delta: { content: 'OK' } }],
};
yield {
choices: [{ index: 0, delta: {}, finish_reason: 'stop' }],
};
yield {
choices: [],
usage: { prompt_tokens: 10, completion_tokens: 1 },
};
})(),
usage_calculator: (source) => {
servedTier = source.service_tier;
return source.usage;
},
});
const chatStream = new AIChatStream({
stream: new Writable({
write(_chunk, _encoding, callback) {
callback();
},
}),
});
await result.init_chat_stream!({ chatStream });
expect(servedTier).toBe('priority');
});
it('uses the final Responses tier when the provider downgrades a stream', async () => {
let servedTier: string | undefined;
const result = await handle_completion_output_responses_api({
stream: true,
completion: (async function* () {
yield {
type: 'response.created',
response: { service_tier: 'ultrafast' },
};
yield { type: 'response.output_text.delta', delta: 'OK' };
yield {
type: 'response.completed',
response: {
service_tier: 'default',
usage: { input_tokens: 10, output_tokens: 1 },
},
};
})(),
usage_calculator: (source) => {
servedTier = source.service_tier;
return source.usage;
},
});
const chatStream = new AIChatStream({
stream: new Writable({
write(_chunk, _encoding, callback) {
callback();
},
}),
});
await result.init_chat_stream!({ chatStream });
expect(servedTier).toBe('default');
});
});
@@ -0,0 +1,292 @@
/*
* 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 { requiredInputModalities } from './mediaParts.js';
import type {
IChatModel,
ICompleteArguments,
ModelCost,
ServiceSpeed,
} from '../types.js';
export const lowerServiceSpeed = (speed: ServiceSpeed): ServiceSpeed =>
speed === 'ultrafast' ? 'fast' : 'standard';
const tokenRates = (costs: ModelCost, multiplier: number): ModelCost =>
Object.fromEntries(
Object.entries(costs).map(([key, value]) => [
key,
key !== 'tokens' &&
/token|^prompt$|^completion$|^input_cache_/.test(key)
? value * multiplier
: value,
]),
);
export const serviceSpeedCosts = (
model: IChatModel,
speed: 'fast' | 'ultrafast',
): ModelCost | undefined => {
if (model.serviceSpeeds && !model.serviceSpeeds.includes(speed))
return undefined;
const rates = model.serviceSpeedRates?.[speed];
return typeof rates === 'number'
? tokenRates(model.costs, rates)
: rates
? { ...model.costs, ...rates }
: undefined;
};
export interface ServiceSpeedSelection {
model: IChatModel;
args: ICompleteArguments;
speed: ServiceSpeed;
}
/**
* The speed a request asks for. Native premium tier parameters count as the
* matching `serviceSpeed`, so they are priced like it; `serviceSpeed` wins.
*/
export const requestedServiceSpeed = (
args: Pick<ICompleteArguments, 'serviceSpeed' | 'service_tier' | 'speed'>,
provider: string | undefined,
): ServiceSpeed | undefined => {
if (args.serviceSpeed !== undefined) return args.serviceSpeed;
if (args.service_tier === 'ultrafast') return 'ultrafast';
if (
args.service_tier === 'priority' ||
(provider === 'claude' && args.speed === 'fast') ||
// Mistral's `auto` tier is its priority tier.
(provider === 'mistral' && args.service_tier === 'auto')
)
return 'fast';
return undefined;
};
/** Select only an equivalent model from the same provider's loaded catalog. */
export const selectServiceSpeed = (
model: IChatModel,
args: ICompleteArguments,
findVariant: (id: string) => IChatModel | undefined,
offers: Partial<Record<'fast' | 'ultrafast', IChatModel>> = {},
): ServiceSpeedSelection => {
if (args.serviceSpeed === undefined)
return { model, args, speed: 'standard' };
const provider = model.provider;
const fast =
offers.fast?.costs ??
(provider === 'gemini' &&
(requiredInputModalities(args.messages).some(
(modality) => !['text', 'image'].includes(modality),
) ||
args.messages.some(
(message) =>
Array.isArray(message.content) &&
message.content.some(
(part: Record<string, unknown>) =>
part &&
[
'input_audio',
'audio_url',
'document',
'file',
'input_file',
].includes(String(part.type)),
),
))
? undefined
: serviceSpeedCosts(model, 'fast'));
const ultra =
offers.ultrafast?.costs ?? serviceSpeedCosts(model, 'ultrafast');
let speed = args.serviceSpeed;
const variantId = model.serviceSpeedVariants?.fast;
const variant =
offers.fast && offers.fast.id !== model.id
? offers.fast
: variantId
? findVariant(variantId)
: undefined;
while (speed !== 'standard') {
if (speed === 'ultrafast' && ultra) break;
if (speed === 'fast' && (fast || variant)) break;
speed = lowerServiceSpeed(speed);
}
const request: ICompleteArguments = {
...args,
serviceSpeed: speed,
speed: undefined,
service_tier: undefined,
};
if (speed === 'fast' && variant) {
return {
model: { ...variant, release_date: model.release_date },
args: request,
speed,
};
}
if (provider === 'gemini' && fast)
request.service_tier = speed === 'fast' ? 'priority' : 'standard';
else if (provider === 'claude')
request.speed = speed === 'fast' ? 'fast' : 'standard';
else if (provider === 'mistral')
request.service_tier = speed === 'fast' ? 'auto' : 'default';
else if (
provider === 'minimax' &&
model.serviceSpeedRates?.fast !== undefined
)
request.service_tier = speed === 'fast' ? 'priority' : 'standard';
else if (fast || ultra)
request.service_tier =
speed === 'ultrafast'
? 'ultrafast'
: speed === 'fast'
? 'priority'
: 'default';
if (
speed === 'standard' &&
[
'openai-completion',
'openai-responses',
'azure-openai',
'azure-openai-responses',
'openrouter',
].includes(provider ?? '')
)
request.service_tier = 'default';
const selectedCosts =
speed === 'ultrafast' ? ultra : speed === 'fast' ? fast : undefined;
return {
args: request,
speed,
model: selectedCosts
? {
...model,
costs: selectedCosts,
pricingOverrides: model.pricingOverrides?.map((override) => ({
...override,
costs: Object.fromEntries(
Object.entries(override.costs).map(([key, value]) => [
key,
model.costs[key] > 0
? (value *
(selectedCosts[key] ??
model.costs[key])) /
model.costs[key]
: value,
]),
),
})),
serviceSpeedPricing: {
speed,
standardCosts: model.costs,
standardOverrides: model.pricingOverrides,
fastCosts: fast,
ultrafastCosts: ultra,
},
}
: model,
};
};
/** The response is authoritative; an absent tier never earns a premium. */
export const servedServiceSpeed = (
source: Record<string, unknown>,
): ServiceSpeed => {
const usage = source.usage as Record<string, unknown> | undefined;
const tier =
usage?.speed ??
usage?.serviceTier ??
usage?.service_tier ??
source.service_tier;
return tier === 'ultrafast'
? 'ultrafast'
: tier === 'fast' || tier === 'priority'
? 'fast'
: 'standard';
};
/**
* The model priced at the speed the provider served. Without a selection
* snapshot the catalog's rates for that speed apply, so a premium tier reached
* some other way is never billed as standard.
*/
export const serviceSpeedBillingModel = (
model: IChatModel,
speed: ServiceSpeed,
): IChatModel => {
const pricing = model.serviceSpeedPricing ?? {
speed: 'standard',
standardCosts: model.costs,
standardOverrides: model.pricingOverrides,
fastCosts: serviceSpeedCosts(model, 'fast'),
ultrafastCosts: serviceSpeedCosts(model, 'ultrafast'),
};
if (pricing.speed === speed) return model;
const costs =
(speed === 'ultrafast' ? pricing.ultrafastCosts : undefined) ??
(speed !== 'standard' ? pricing.fastCosts : undefined) ??
pricing.standardCosts;
return {
...model,
costs,
pricingOverrides: pricing.standardOverrides?.map((override) => ({
...override,
costs: Object.fromEntries(
Object.entries(override.costs).map(([key, value]) => [
key,
pricing.standardCosts[key] > 0
? (value * (costs[key] ?? pricing.standardCosts[key])) /
pricing.standardCosts[key]
: value,
]),
),
})),
};
};
/** Retry only failures that explicitly concern admission to the faster tier. */
export const isServiceSpeedUnavailable = (
error: unknown,
variant = false,
): boolean => {
const e = error as {
status?: number;
statusCode?: number;
message?: unknown;
error?: { message?: unknown };
};
const status = e?.status ?? e?.statusCode;
const message = e?.error?.message ?? e?.message ?? '';
if (typeof message !== 'string') return false;
if (
variant &&
[400, 404].includes(status ?? 0) &&
/model.*(?:not found|not exist|unavailable)/i.test(message)
)
return true;
return (
[400, 403, 429, 503].includes(status ?? 0) &&
/fast mode|ultrafast|service[_ ]?tier|priority (?:tier|processing|capacity)|speed parameter/i.test(
message,
) &&
/unavailable|unsupported|not support|rate.limit|quota|capacity|not enabled|not allowed|access|exceed|invalid value/i.test(
message,
)
);
};
@@ -463,10 +463,26 @@ describe('ImageGenerationDriver.generate provider routing', () => {
driver.generate({ prompt: 'a landscape' }),
);
expect(openaiImagesGenerateMock).toHaveBeenCalledWith(
expect.objectContaining({ model: 'gpt-image-2' }),
expect.objectContaining({ model: 'gpt-image-2.6-flare' }),
);
});
it.each(['gpt-image-2.6-flare', 'gpt-image-2.6-sunburst'])(
'routes %s and its OpenAI alias', async (model) => {
for (const id of [model, `openai/${model}`]) {
openaiImagesGenerateMock.mockResolvedValueOnce({
data: [{ url: 'https://oai/image.png' }],
});
await withDriverName('ai-image', () => driver.generate({
model: id, prompt: 'a landscape',
}));
expect(openaiImagesGenerateMock).toHaveBeenLastCalledWith(
expect.objectContaining({ model }),
);
}
},
);
it('rejects an excluded model regardless of caller casing', async () => {
await expect(withActor(() =>
driver.generate({
@@ -742,7 +758,10 @@ describe('ImageGenerationDriver.generate provider routing', () => {
}),
);
const reserveSpy = vi.spyOn(server.services.metering, 'reserveCredits');
const reserveSpy = vi.spyOn(
server.services.metering,
'reserveCreditsIfAffordable',
);
const usageSpy = vi.spyOn(
server.services.metering,
'batchIncrementUsages',
@@ -836,7 +855,7 @@ describe('ImageGenerationDriver.generate provider routing', () => {
});
const reserveSpy = vi.spyOn(
server.services.metering,
'reserveCredits',
'reserveCreditsIfAffordable',
);
// Cloudflare answers the scheduled refresh with new rates at once;
@@ -1146,8 +1165,8 @@ describe('ImageGenerationDriver.generate Puter file inputs', () => {
);
beforeEach(() => {
vi.spyOn(server.services.metering, 'hasEnoughCredits').mockResolvedValue(
true,
vi.spyOn(server.services.metering, 'reserveCreditsIfAffordable').mockImplementation((who, amount, opts) =>
server.services.metering.reserveCredits(who, amount, opts),
);
});
@@ -1649,7 +1668,10 @@ it.each([undefined, null, '', ' ', 42, {}])(
describe('ImageGenerationDriver cost factor', () => {
it('holds and meters at the AI cost factor', async () => {
const reserveSpy = vi.spyOn(server.services.metering, 'reserveCredits');
const reserveSpy = vi.spyOn(
server.services.metering,
'reserveCreditsIfAffordable',
);
const usageSpy = vi.spyOn(
server.services.metering,
'batchIncrementUsages',
@@ -72,7 +72,7 @@ vi.mock('openai', () => {
// -- Test harness ----------------------------------------------------
let server: PuterServer;
let hasCreditsSpy: MockInstance<MeteringService['hasEnoughCredits']>;
let admitSpy: MockInstance<MeteringService['reserveCreditsIfAffordable']>;
let batchIncrementUsagesSpy: MockInstance<
MeteringService['batchIncrementUsages']
>;
@@ -107,7 +107,7 @@ const makeProvider = (
beforeEach(() => {
generateMock.mockReset();
openAICtor.mockReset();
hasCreditsSpy = vi.spyOn(server.services.metering, 'hasEnoughCredits');
admitSpy = vi.spyOn(server.services.metering, 'reserveCreditsIfAffordable');
batchIncrementUsagesSpy = vi.spyOn(
server.services.metering,
'batchIncrementUsages',
@@ -177,7 +177,7 @@ describe('BytePlusImageProvider.generate gates', () => {
expect(result).toBe(
'https://puter-sample-data.puter.site/image_example.png',
);
expect(hasCreditsSpy).not.toHaveBeenCalled();
expect(admitSpy).not.toHaveBeenCalled();
expect(generateMock).not.toHaveBeenCalled();
});
@@ -196,7 +196,7 @@ describe('BytePlusImageProvider.generate gates', () => {
});
it('throws 402 BEFORE hitting ModelArk when the actor lacks credits', async () => {
hasCreditsSpy.mockResolvedValueOnce(false);
admitSpy.mockResolvedValueOnce(null);
await expect(
withTestActor(() => makeProvider().generate({ prompt: 'hi' })),
).rejects.toMatchObject({ statusCode: 402 });
@@ -713,7 +713,7 @@ it.each([
}),
),
).rejects.toMatchObject({ statusCode: 400, legacyCode: 'bad_request' });
expect(hasCreditsSpy).not.toHaveBeenCalled();
expect(admitSpy).not.toHaveBeenCalled();
expect(generateMock).not.toHaveBeenCalled();
});
@@ -73,7 +73,7 @@ let server: PuterServer;
let globalFetchSpy: MockInstance<typeof fetch>;
let fetchSpy: Mock<typeof fetch>;
let modelSearchFetch: Mock<typeof fetch>;
let hasCreditsSpy: MockInstance<MeteringService['hasEnoughCredits']>;
let admitSpy: MockInstance<MeteringService['reserveCreditsIfAffordable']>;
let batchIncrementUsagesSpy: MockInstance<
MeteringService['batchIncrementUsages']
>;
@@ -123,7 +123,7 @@ beforeEach(() => {
? modelSearchFetch(input, init)
: fetchSpy(input, init),
);
hasCreditsSpy = vi.spyOn(server.services.metering, 'hasEnoughCredits');
admitSpy = vi.spyOn(server.services.metering, 'reserveCreditsIfAffordable');
batchIncrementUsagesSpy = vi.spyOn(
server.services.metering,
'batchIncrementUsages',
@@ -188,7 +188,7 @@ describe('CloudflareImageProvider.generate test_mode', () => {
expect(result).toBe(
'https://puter-sample-data.puter.site/image_example.png',
);
expect(hasCreditsSpy).not.toHaveBeenCalled();
expect(admitSpy).not.toHaveBeenCalled();
expect(fetchSpy).not.toHaveBeenCalled();
});
});
@@ -210,7 +210,7 @@ describe('CloudflareImageProvider.generate argument validation', () => {
describe('CloudflareImageProvider.generate credit gate', () => {
it('throws 402 BEFORE hitting Cloudflare when actor lacks credits', async () => {
const provider = makeProvider();
hasCreditsSpy.mockResolvedValueOnce(false);
admitSpy.mockResolvedValueOnce(null);
await expect(
withTestActor(() => provider.generate({ prompt: 'hi' })),
@@ -240,7 +240,7 @@ describe('CloudflareImageProvider.generate credit gate', () => {
actor,
);
const [, estimate] = hasCreditsSpy.mock.calls[0]!;
const [, estimate] = admitSpy.mock.calls[0]!;
expect(estimate).toBeGreaterThan(0);
expect(heldDuringCall).toBe(Math.ceil(estimate));
// The hold stays until the usage write lands.
@@ -708,7 +708,7 @@ describe('Cloudflare legacy image option', () => {
legacyCode: 'bad_request',
});
expect(fetchSpy).not.toHaveBeenCalled();
expect(hasCreditsSpy).not.toHaveBeenCalled();
expect(admitSpy).not.toHaveBeenCalled();
},
);
@@ -726,7 +726,7 @@ describe('Cloudflare legacy image option', () => {
message: 'Invalid input image (empty or not base64)',
});
expect(fetchSpy).not.toHaveBeenCalled();
expect(hasCreditsSpy).not.toHaveBeenCalled();
expect(admitSpy).not.toHaveBeenCalled();
});
});
@@ -823,12 +823,12 @@ describe('Cloudflare priced legacy models', () => {
imageSize: { kind: 'pixels', w: 512, h: 512 },
}));
expect(JSON.parse(fetchSpy.mock.calls[0]![1]!.body as string)).toMatchObject({ image: [1, 2, 3], mask: [4, 5, 6], num_steps: 20, width: 512, height: 512 });
expect(hasCreditsSpy).toHaveBeenCalledWith(expect.anything(), 0);
expect(admitSpy).toHaveBeenCalledWith(expect.anything(), 0, undefined);
});
it('rejects missing inpainting inputs before credit checks', async () => {
await expect(withTestActor(() => makeProvider().generate({ model: '@cf/runwayml/stable-diffusion-v1-5-inpainting', prompt: 'A cup' }))).rejects.toMatchObject({ statusCode: 400 });
expect(hasCreditsSpy).not.toHaveBeenCalled();
expect(admitSpy).not.toHaveBeenCalled();
expect(fetchSpy).not.toHaveBeenCalled();
});
@@ -844,7 +844,7 @@ describe('Cloudflare priced legacy models', () => {
it('charges Lucid at the price returned by the model API', async () => {
fetchSpy.mockResolvedValueOnce(new Response(new Uint8Array([1, 2, 3]), { headers: { 'content-type': 'image/png' } }));
await withTestActor(() => makeProvider().generate({ model: '@cf/leonardo/lucid-origin', prompt: 'A cup', imageSize: { kind: 'pixels', w: 512, h: 512 }, steps: 1 }));
expect(hasCreditsSpy).toHaveBeenCalledWith(expect.anything(), 713200);
expect(admitSpy).toHaveBeenCalledWith(expect.anything(), 713200, undefined);
});
});
@@ -897,9 +897,10 @@ describe('Cloudflare model-search pricing', () => {
await runPhoenix(provider);
expect(listed?.costs).toEqual({ tile_512: 1_000_000, step: 20_200 });
expect(hasCreditsSpy).toHaveBeenCalledWith(
expect(admitSpy).toHaveBeenCalledWith(
expect.anything(),
4 * 1_000_000 + 10 * 20_200,
undefined,
);
expect(batchIncrementUsagesSpy.mock.calls[0]![1]).toEqual([
expect.objectContaining({
@@ -930,9 +931,10 @@ describe('Cloudflare model-search pricing', () => {
await runPhoenix(makeProvider());
expect(modelSearchFetch).not.toHaveBeenCalled();
expect(hasCreditsSpy).toHaveBeenCalledWith(
expect(admitSpy).toHaveBeenCalledWith(
expect.anything(),
4 * 583_000 + 10 * 11_000,
undefined,
);
});
@@ -955,7 +957,7 @@ describe('Cloudflare model-search pricing', () => {
await refresh;
await runPhoenix(provider);
expect(hasCreditsSpy.mock.calls.map(([, cost]) => cost)).toEqual([
expect(admitSpy.mock.calls.map(([, cost]) => cost)).toEqual([
2_442_000, 4_202_000,
]);
});
@@ -977,9 +979,10 @@ describe('Cloudflare model-search pricing', () => {
await runPhoenix(provider);
expect(modelSearchFetch).toHaveBeenCalledTimes(2);
expect(hasCreditsSpy).toHaveBeenCalledWith(
expect(admitSpy).toHaveBeenCalledWith(
expect.anything(),
4_202_000,
undefined,
);
});
@@ -1015,7 +1018,7 @@ describe('Cloudflare model-search pricing', () => {
steps: 10,
} as never),
);
return hasCreditsSpy.mock.lastCall![1];
return admitSpy.mock.lastCall![1];
};
const settle = () => new Promise((resolve) => setImmediate(resolve));
const OLD = { tile_512: 583_000, step: 11_000 };
@@ -1069,9 +1072,10 @@ describe('Cloudflare model-search pricing', () => {
}),
);
expect(modelSearchFetch).toHaveBeenCalledOnce();
expect(hasCreditsSpy).toHaveBeenCalledWith(
expect(admitSpy).toHaveBeenCalledWith(
expect.anything(),
4 * 5280 + 4 * 10560,
undefined,
);
});
@@ -82,7 +82,7 @@ vi.mock('../../inputImage.js', async (orig) => ({
// ── Test harness ────────────────────────────────────────────────────
let server: PuterServer;
let hasCreditsSpy: MockInstance<MeteringService['hasEnoughCredits']>;
let admitSpy: MockInstance<MeteringService['reserveCreditsIfAffordable']>;
let incrementUsageSpy: MockInstance<MeteringService['incrementUsage']>;
let batchIncrementUsagesSpy: MockInstance<
MeteringService['batchIncrementUsages']
@@ -111,7 +111,7 @@ beforeEach(() => {
generateContentMock.mockReset();
toBase64DataUriMock.mockReset();
googleAICtor.mockReset();
hasCreditsSpy = vi.spyOn(server.services.metering, 'hasEnoughCredits');
admitSpy = vi.spyOn(server.services.metering, 'reserveCreditsIfAffordable');
incrementUsageSpy = vi.spyOn(server.services.metering, 'incrementUsage');
batchIncrementUsagesSpy = vi.spyOn(
server.services.metering,
@@ -167,7 +167,7 @@ describe('GeminiImageProvider.generate test_mode', () => {
expect(result).toBe(
'https://puter-sample-data.puter.site/image_example.png',
);
expect(hasCreditsSpy).not.toHaveBeenCalled();
expect(admitSpy).not.toHaveBeenCalled();
expect(generateContentMock).not.toHaveBeenCalled();
});
});
@@ -219,7 +219,7 @@ describe('GeminiImageProvider.generate argument validation', () => {
legacyCode: 'bad_request',
message: expect.stringContaining('Unsupported quality tier'),
});
expect(hasCreditsSpy).not.toHaveBeenCalled();
expect(admitSpy).not.toHaveBeenCalled();
expect(generateContentMock).not.toHaveBeenCalled();
},
);
@@ -427,7 +427,7 @@ describe('GeminiImageProvider.generate Flash path (generateContent)', () => {
it('throws 402 BEFORE hitting Gemini when actor lacks credits', async () => {
const provider = makeProvider();
hasCreditsSpy.mockResolvedValueOnce(false);
admitSpy.mockResolvedValueOnce(null);
await expect(
withTestActor(() =>
@@ -466,7 +466,7 @@ describe('GeminiImageProvider.generate Flash path (generateContent)', () => {
actor,
);
const [, estimate] = hasCreditsSpy.mock.calls[0]!;
const [, estimate] = admitSpy.mock.calls[0]!;
expect(estimate).toBeGreaterThan(0);
expect(heldDuringCall).toBe(Math.ceil(estimate));
// The hold stays until the usage write lands.
@@ -643,7 +643,7 @@ describe('Gemini Nano Banana image generation', () => {
const request = generateContentMock.mock.calls[0][0];
expect(request.config.imageConfig.imageSize).toBe('1K');
// Input + 1120 image tokens at $30/1M + 1000 text tokens at $7.50/1M.
expect(hasCreditsSpy).toHaveBeenCalledWith(expect.anything(), 4_194_450);
expect(admitSpy).toHaveBeenCalledWith(expect.anything(), 4_194_450, undefined);
expect(batchIncrementUsagesSpy).toHaveBeenCalledWith(
expect.anything(),
expect.arrayContaining([
@@ -50,7 +50,7 @@ import { KlingImageProvider } from './KlingImageProvider.js';
let server: PuterServer;
let fetchSpy: MockInstance<typeof fetch>;
let hasCreditsSpy: MockInstance<MeteringService['hasEnoughCredits']>;
let admitSpy: MockInstance<MeteringService['reserveCreditsIfAffordable']>;
let incrementUsageSpy: MockInstance<MeteringService['incrementUsage']>;
beforeAll(async () => {
@@ -73,7 +73,7 @@ const makeProvider = () =>
beforeEach(() => {
fetchSpy = vi.spyOn(globalThis, 'fetch') as MockInstance<typeof fetch>;
hasCreditsSpy = vi.spyOn(server.services.metering, 'hasEnoughCredits');
admitSpy = vi.spyOn(server.services.metering, 'reserveCreditsIfAffordable');
incrementUsageSpy = vi.spyOn(server.services.metering, 'incrementUsage');
incrementUsageSpy.mockResolvedValue({} as never);
});
@@ -318,7 +318,7 @@ describe('KlingImageProvider billing', () => {
});
it('rejects before calling Kling when credits run short', async () => {
hasCreditsSpy.mockResolvedValueOnce(false);
admitSpy.mockResolvedValueOnce(null);
await expect(generate({})).rejects.toMatchObject({ statusCode: 402 });
expect(fetchSpy).not.toHaveBeenCalled();
});
@@ -97,7 +97,7 @@ vi.mock('../../inputImage.js', async (orig) => ({
// ── Test harness ────────────────────────────────────────────────────
let server: PuterServer;
let hasCreditsSpy: MockInstance<MeteringService['hasEnoughCredits']>;
let admitSpy: MockInstance<MeteringService['reserveCreditsIfAffordable']>;
let batchIncrementUsagesSpy: MockInstance<
MeteringService['batchIncrementUsages']
>;
@@ -126,7 +126,7 @@ beforeEach(() => {
editMock.mockReset();
fetchImageAsBase64Mock.mockReset();
openAICtor.mockReset();
hasCreditsSpy = vi.spyOn(server.services.metering, 'hasEnoughCredits');
admitSpy = vi.spyOn(server.services.metering, 'reserveCreditsIfAffordable');
batchIncrementUsagesSpy = vi.spyOn(
server.services.metering,
'batchIncrementUsages',
@@ -150,9 +150,9 @@ describe('OpenAiImageProvider construction', () => {
// ── Model catalog ───────────────────────────────────────────────────
describe('OpenAiImageProvider model catalog', () => {
it('returns gpt-image-2 as the default', () => {
it('returns gpt-image-2.6-flare as the default', () => {
const provider = makeProvider();
expect(provider.getDefaultModel()).toBe('gpt-image-2');
expect(provider.getDefaultModel()).toBe('gpt-image-2.6-flare');
});
it('drops the deprecated gpt-image-1 family and chatgpt-image-latest', () => {
@@ -195,7 +195,7 @@ describe('OpenAiImageProvider.generate test_mode', () => {
expect(result).toBe(
'https://puter-sample-data.puter.site/image_example.png',
);
expect(hasCreditsSpy).not.toHaveBeenCalled();
expect(admitSpy).not.toHaveBeenCalled();
expect(generateMock).not.toHaveBeenCalled();
});
});
@@ -235,9 +235,60 @@ describe('OpenAiImageProvider.generate argument validation', () => {
// ── Credit gate ─────────────────────────────────────────────────────
describe('OpenAiImageProvider.generate credit gate', () => {
it('waits for the real usage write before returning an image', async () => {
const actor = makeActor({
user: {
id: 62,
uuid: `image-write-${Date.now()}`,
username: 'metered',
},
});
const redis = server.clients.redis as unknown as {
meterIncr: (...args: string[]) => Promise<unknown>;
};
const realIncr = redis.meterIncr.bind(redis);
let release!: () => void;
const held = new Promise<void>((resolve) => {
release = resolve;
});
let blocked = false;
vi.spyOn(redis, 'meterIncr').mockImplementation(async (...args) => {
const actorKey = `:actor:${actor.user!.uuid}:`;
if (!blocked && args.some((arg) => arg.includes(actorKey))) {
blocked = true;
await held;
}
return realIncr(...args);
});
generateMock.mockResolvedValueOnce({
data: [{ url: 'https://image.example/result.png' }],
});
const provider = makeProvider();
let finished = false;
const generating = withTestActor(
() =>
provider.generate({
model: 'gpt-image-2',
prompt: 'an image',
ratio: { w: 1024, h: 1024 },
}),
actor,
).then((result) => {
finished = true;
return result;
});
try {
await vi.waitFor(() => expect(blocked).toBe(true));
expect(finished).toBe(false);
} finally {
release();
await generating;
}
});
it('throws 402 BEFORE hitting OpenAI when actor lacks credits', async () => {
const provider = makeProvider();
hasCreditsSpy.mockResolvedValueOnce(false);
admitSpy.mockResolvedValueOnce(null);
await expect(
withTestActor(() =>
provider.generate({
@@ -273,7 +324,7 @@ describe('OpenAiImageProvider.generate credit gate', () => {
actor,
);
const [, estimate] = hasCreditsSpy.mock.calls[0]!;
const [, estimate] = admitSpy.mock.calls[0]!;
expect(estimate).toBeGreaterThan(0);
expect(heldDuringCall).toBe(Math.ceil(estimate));
// The hold stays until the usage write lands.
@@ -677,8 +728,8 @@ describe('OpenAiImageProvider gpt-image-2.5 models', () => {
);
// Latent factor 48 vs 24 at the medium tier.
const gptImage2Estimate = hasCreditsSpy.mock.calls[0]![1];
const gptImage25Estimate = hasCreditsSpy.mock.calls[1]![1];
const gptImage2Estimate = admitSpy.mock.calls[0]![1];
const gptImage25Estimate = admitSpy.mock.calls[1]![1];
expect(gptImage25Estimate).toBeLessThan(gptImage2Estimate);
});
@@ -703,8 +754,8 @@ describe('OpenAiImageProvider gpt-image-2.5 models', () => {
}),
);
const highEstimate = hasCreditsSpy.mock.calls[0]![1];
const maxEstimate = hasCreditsSpy.mock.calls[1]![1];
const highEstimate = admitSpy.mock.calls[0]![1];
const maxEstimate = admitSpy.mock.calls[1]![1];
expect(maxEstimate).toBeGreaterThan(highEstimate);
});
});
@@ -857,3 +908,64 @@ it('keeps a landscape aspect hint landscape at gpt-image-2 sizes', async () => {
expect(w).toBeGreaterThan(h);
expect(Math.abs(w / h - 1.7)).toBeLessThan(0.1);
});
describe('OpenAiImageProvider GPT Image 2.6', () => {
it.each(['gpt-image-2.6-flare', 'gpt-image-2.6-sunburst'])(
'%s generates and edits with token-based billing', async (model) => {
const provider = makeProvider();
const response = {
data: [{ b64_json: 'AAAA' }],
usage: {
input_tokens: 100,
output_tokens: 800,
input_tokens_details: { text_tokens: 100, image_tokens: 0 },
},
};
generateMock.mockResolvedValue(response);
editMock.mockResolvedValue(response);
for (const input_image of [undefined, 'data:image/png;base64,AAAA']) {
const result = await withTestActor(() => provider.generate({
model, prompt: 'hi', quality: 'xhigh',
ratio: { w: 1024, h: 1024 }, input_image,
}));
expect(result).toBe('data:image/png;base64,AAAA');
}
for (const mock of [generateMock, editMock]) {
expect(mock.mock.calls[0]![0]).toMatchObject({
model, quality: 'xhigh', size: '1024x1024',
});
}
const [, entries] = batchIncrementUsagesSpy.mock.calls[0]!;
expect(entries).toEqual(expect.arrayContaining([
expect.objectContaining({
usageType: `openai:${model}:xhigh:1024x1024:output`,
costOverride: 2_400_000,
}),
]));
},
);
it.each([
['low', 1024, 1024, 823],
['medium', 1024, 1024, 1449],
['high', 1024, 1024, 1756],
['xhigh', 1024, 1024, 3122],
['max', 1024, 1024, 7024],
['auto', 1024, 1024, 1449],
['low', 2048, 1088, 571],
])('estimates %s at %sx%s from the 2.6 calculator', async (quality, w, h, tokens) => {
generateMock.mockResolvedValue({ data: [{ b64_json: 'AAAA' }] });
await withTestActor(() => makeProvider().generate({
model: 'gpt-image-2.6-flare', prompt: 'hi', quality: String(quality),
ratio: { w: Number(w), h: Number(h) },
}));
const [, entries] = batchIncrementUsagesSpy.mock.calls[0]!;
const output = (entries as Array<{ usageType: string; costOverride: number }>)
.find((entry) => entry.usageType.endsWith(':output'))!;
expect(output.usageType).toBe(`openai:gpt-image-2.6-flare:${quality}:${w}x${h}:output`);
// The metering conversion rounds fractional microcents upward.
expect(output.costOverride).toBeGreaterThanOrEqual(Number(tokens) * 3000);
expect(output.costOverride).toBeLessThanOrEqual(Number(tokens) * 3000 + 1);
});
});
@@ -56,8 +56,8 @@ interface OpenAIImageUsage {
/**
* OpenAI image generation provider for v2. Supports the GPT Image models
* (gpt-image-2, -2.5-sunburst, -2.5-flare), including image-to-image editing
* via `input_images` (the `images.edit` endpoint).
* (gpt-image-2 and the 2.5/2.6 Sunburst and Flare models), including
* image-to-image editing via `input_images` (the `images.edit` endpoint).
*/
export class OpenAiImageProvider implements IImageProvider {
#meteringService: AiMeteringService;
@@ -109,7 +109,7 @@ export class OpenAiImageProvider implements IImageProvider {
}
getDefaultModel(): string {
return 'gpt-image-2';
return 'gpt-image-2.6-flare';
}
async generate({
@@ -293,7 +293,10 @@ export class OpenAiImageProvider implements IImageProvider {
});
}
if (usageEntries.length) {
this.#meteringService.batchIncrementUsages(actor, usageEntries);
await this.#meteringService.batchIncrementUsages(
actor,
usageEntries,
);
}
const url =
@@ -601,17 +604,36 @@ export class OpenAiImageProvider implements IImageProvider {
height: number,
quality?: string,
): number {
const factors = model.startsWith('gpt-image-2.5')
? OpenAiImageProvider.#GPT_IMAGE_2_5_LATENT_FACTORS
: OpenAiImageProvider.#GPT_IMAGE_2_LATENT_FACTORS;
const isGptImage26 = model.startsWith('gpt-image-2.6');
const factors =
isGptImage26 || model.startsWith('gpt-image-2.5')
? OpenAiImageProvider.#GPT_IMAGE_2_5_LATENT_FACTORS
: OpenAiImageProvider.#GPT_IMAGE_2_LATENT_FACTORS;
const factor = factors[quality ?? ''] ?? factors.medium;
const longEdge = Math.max(width, height);
const shortEdge = Math.min(width, height);
const shortLatent = Math.round((factor * shortEdge) / longEdge);
const shortGrid = (factor * shortEdge) / longEdge;
const floorGrid = Math.floor(shortGrid);
const shortLatent =
isGptImage26 && shortGrid - floorGrid === 0.5
? floorGrid + (floorGrid % 2)
: Math.round(shortGrid);
const latentW = width >= height ? factor : shortLatent;
const latentH = width >= height ? shortLatent : factor;
const baseArea = latentW * latentH;
return Math.ceil((baseArea * (2_000_000 + width * height)) / 4_000_000);
const tokens = Math.ceil(
(baseArea * (2_000_000 + width * height)) / 4_000_000,
);
// GPT Image 2.6 bills more tokens at low and medium quality.
const estimatedQuality =
quality && quality in factors ? quality : 'medium';
const multiplier =
estimatedQuality === 'low'
? 4.2
: estimatedQuality === 'medium'
? 3.3
: 1;
return isGptImage26 ? Math.round(tokens * multiplier) : tokens;
}
#estimateOutputCostFromTokens(
@@ -20,6 +20,46 @@
import type { IImageModel } from '../../types.js';
export const OPEN_AI_IMAGE_GENERATION_MODELS: IImageModel[] = [
{
puterId: 'openai:openai/gpt-image-2.6-sunburst',
id: 'gpt-image-2.6-sunburst',
aliases: ['openai/gpt-image-2.6-sunburst'],
name: 'GPT Image 2.6 Sunburst',
version: '2.6',
costs_currency: 'usd-cents',
index_cost_key: 'low:1024x1024',
costs: {
// Text tokens (per 1M tokens)
text_input: 500, // $5.00
text_cached_input: 125, // $1.25
// Image tokens (per 1M tokens)
image_input: 800, // $8.00
image_cached_input: 200, // $2.00
image_output: 3000, // $30.00
'low:1024x1024': 2.469,
},
allowedQualityLevels: ['low', 'medium', 'high', 'xhigh', 'max', 'auto'],
},
{
puterId: 'openai:openai/gpt-image-2.6-flare',
id: 'gpt-image-2.6-flare',
aliases: ['openai/gpt-image-2.6-flare'],
name: 'GPT Image 2.6 Flare',
version: '2.6',
costs_currency: 'usd-cents',
index_cost_key: 'low:1024x1024',
costs: {
// Text tokens (per 1M tokens)
text_input: 500, // $5.00
text_cached_input: 125, // $1.25
// Image tokens (per 1M tokens)
image_input: 800, // $8.00
image_cached_input: 200, // $2.00
image_output: 3000, // $30.00
'low:1024x1024': 2.469,
},
allowedQualityLevels: ['low', 'medium', 'high', 'xhigh', 'max', 'auto'],
},
{
puterId: 'openai:openai/gpt-image-2.5-sunburst',
id: 'gpt-image-2.5-sunburst',
@@ -84,7 +84,7 @@ vi.mock('../../../../util/secureHttp.js', () => ({
// ── Test harness ────────────────────────────────────────────────────
let server: PuterServer;
let hasCreditsSpy: MockInstance<MeteringService['hasEnoughCredits']>;
let admitSpy: MockInstance<MeteringService['reserveCreditsIfAffordable']>;
let incrementUsageSpy: MockInstance<MeteringService['incrementUsage']>;
let batchIncrementUsagesSpy: MockInstance<
MeteringService['batchIncrementUsages']
@@ -115,7 +115,7 @@ beforeEach(() => {
cancelMock.mockReset();
replicateCtor.mockReset();
secureFetchMock.mockReset();
hasCreditsSpy = vi.spyOn(server.services.metering, 'hasEnoughCredits');
admitSpy = vi.spyOn(server.services.metering, 'reserveCreditsIfAffordable');
incrementUsageSpy = vi.spyOn(server.services.metering, 'incrementUsage');
batchIncrementUsagesSpy = vi.spyOn(
server.services.metering,
@@ -177,7 +177,7 @@ describe('ReplicateImageGenerationProvider.generate test_mode', () => {
expect(result).toBe(
'https://puter-sample-data.puter.site/image_example.png',
);
expect(hasCreditsSpy).not.toHaveBeenCalled();
expect(admitSpy).not.toHaveBeenCalled();
expect(createPredictionMock).not.toHaveBeenCalled();
});
});
@@ -199,7 +199,7 @@ describe('ReplicateImageGenerationProvider.generate argument validation', () =>
describe('ReplicateImageGenerationProvider.generate credit gate', () => {
it('throws 402 BEFORE hitting Replicate when actor lacks credits', async () => {
const provider = makeProvider();
hasCreditsSpy.mockResolvedValueOnce(false);
admitSpy.mockResolvedValueOnce(null);
await expect(
withTestActor(() => provider.generate({ prompt: 'hi' })),
).rejects.toMatchObject({ statusCode: 402 });
@@ -255,7 +255,10 @@ describe('ReplicateImageGenerationProvider.generate credit gate', () => {
it('holds credits for longer than a prediction can run', async () => {
const provider = makeProvider();
const actor = holdUser('ttl');
const reserveSpy = vi.spyOn(server.services.metering, 'reserveCredits');
const reserveSpy = vi.spyOn(
server.services.metering,
'reserveCreditsIfAffordable',
);
createPredictionMock.mockResolvedValueOnce({
id: 'ttl',
status: 'succeeded',
@@ -274,7 +277,9 @@ describe('ReplicateImageGenerationProvider.generate credit gate', () => {
const provider = makeProvider();
const actor = holdUser('surcharge');
secureFetchMock.mockResolvedValueOnce(new Response('not-an-image'));
hasCreditsSpy.mockResolvedValueOnce(true).mockResolvedValueOnce(false);
admitSpy.mockImplementationOnce((who, amount, opts) =>
server.services.metering.reserveCredits(who, amount, opts),
).mockResolvedValueOnce(false);
await expect(
withTestActor(
@@ -950,7 +955,7 @@ it('does not start a prediction for an already-aborted request', async () => {
),
).rejects.toMatchObject({ statusCode: 400, legacyCode: 'client_aborted' });
expect(createPredictionMock).not.toHaveBeenCalled();
expect(hasCreditsSpy).not.toHaveBeenCalled();
expect(admitSpy).not.toHaveBeenCalled();
});
it('stops polling and cancels at the prediction deadline', async () => {
@@ -1192,12 +1197,12 @@ it('rejects more than ten input images before fetching or pricing any', async ()
),
).rejects.toMatchObject({ statusCode: 400, legacyCode: 'bad_request' });
expect(secureFetchMock).not.toHaveBeenCalled();
expect(hasCreditsSpy).not.toHaveBeenCalled();
expect(admitSpy).not.toHaveBeenCalled();
expect(createPredictionMock).not.toHaveBeenCalled();
});
it('checks credits on the output-only estimate before fetching input images', async () => {
hasCreditsSpy.mockResolvedValueOnce(false);
admitSpy.mockResolvedValueOnce(null);
await expect(
withTestActor(() =>
makeProvider().generate({
Loaded 100 of 759 files, more files were not shown because too many files have changed in this diff. Show more