Compare commits

...
Author SHA1 Message Date
jelveh 3cafef587e 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:01:59 -07:00
jelveh a031f26dfc 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.
2026-11-08 13:40:45 -07:00
jelveh e02cd75e99 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.
2026-11-08 13:37:29 -07:00
jelveh 6edfdd2382 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.
2026-11-08 13:35:40 -07:00
jelveh b0c4a28787 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.
2026-11-08 13:12:20 -07:00
jelveh 380f372eca 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.
2026-11-08 13:11:55 -07:00
jelveh f64ba23f8a 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.
2026-11-08 13:11:06 -07:00
jelveh f229747581 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.
2026-11-08 13:10:07 -07:00
jelveh 9ec6f165a4 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.
2026-11-08 13:00:31 -07:00
jelveh 49f116e02e 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.
2026-11-08 12:32:00 -07:00
jelveh 719b9c7b01 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.
2026-11-08 12:28:27 -07:00
jelveh 52e6e82b7b 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.
2026-11-08 12:28:09 -07:00
jelveh e7c4c80c3b 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.
2026-11-08 12:16:58 -07:00
jelveh 0b688872df 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.
2026-11-08 12:14:51 -07:00
jelveh 081a399c46 Document when the framed upgrade posts ready 2026-11-08 12:03:14 -07:00
jelveh af40c9e8bc 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.
2026-11-08 11:50:32 -07:00
jelveh 5ab3d8a90f 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.
2026-11-08 11:06:46 -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
392 changed files with 26579 additions and 11284 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
+4 -1
View File
@@ -159,7 +159,9 @@ 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
@@ -200,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
@@ -1 +1 @@
FOLLOW ./AGENTS.md
FOLLOW @AGENTS.md
+272
View File
@@ -0,0 +1,272 @@
# 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 }`.
## 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/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
+22 -11
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;
@@ -636,6 +636,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 ----
@@ -1067,10 +1079,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>;
@@ -1081,18 +1094,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 = {
@@ -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;
}
@@ -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 ────────────────────────────────────────────────────
//
@@ -529,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,12 +22,31 @@ 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, and the upgrade dialog,
* which it would otherwise open in a dashboard tab.
*/
export const FRAMED_POPUP_ACTIONS = [
'sign-in',
'show-open-file-picker',
'show-save-file-picker',
'show-directory-picker',
'upgrade',
] as const;
/** Longest description/og:description/twitter:description on `/app/<name>`. */
export const APP_META_DESCRIPTION_MAX = 150;
@@ -43,9 +62,9 @@ const APP_LANDING_LIMIT = {
};
/**
* App descriptions can run long; search snippets and social cards want a
* short blurb. Collapses whitespace, then cuts at a word boundary with an
* ellipsis so the result never exceeds `APP_META_DESCRIPTION_MAX`.
* App descriptions can run long; search snippets and social cards want a short
* blurb. Collapses whitespace, then cuts at a word boundary with an ellipsis so
* the result never exceeds `APP_META_DESCRIPTION_MAX`.
*/
export function appMetaDescription(text: string): string {
const clean = text.replace(/\s+/g, ' ').trim();
@@ -56,6 +75,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
@@ -90,6 +167,7 @@ export class HomepageController extends PuterController {
res: express.Response,
metaOverrides: Partial<PageMeta> = {},
launch: LaunchOptions = {},
popupFrame?: PopupFrame,
) => {
const meta = { ...defaultMeta(req), ...metaOverrides };
const actor =
@@ -98,13 +176,89 @@ export class HomepageController extends PuterController {
actor?: Parameters<typeof homepage.send>[0]['actor'];
}
).actor ?? null;
await homepage.send({ req, res, actor }, meta, launch);
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));
@@ -1620,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 + '/',
@@ -1646,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)}`;
@@ -1686,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 () => {
+5 -17
View File
@@ -688,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);
@@ -834,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 =
@@ -881,7 +871,7 @@ if (window.opener) {
error: outcome.error ?? 'Failed to link provider.',
};
}
return { user: byEmail, origin: 'linked-email' };
return { user: byEmail };
}
}
@@ -911,7 +901,7 @@ if (window.opener) {
requestCode: outcome.requestCode,
};
}
return { user: outcome.user, origin: 'created' };
return { user: outcome.user };
}
async #processCallback(
@@ -1000,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 = {
@@ -1018,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
@@ -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)) {
+166
View File
@@ -336,6 +336,172 @@ describe('PuterServer host header validation', () => {
expect(api.headers['x-frame-options']).toBeUndefined();
});
it('allows deployment subdomains to frame the app browser embed', async () => {
const parent = `http://spreadsheet.puter.localhost:${port}`;
for (const path of ['/embed/apps', '/embed/apps/']) {
const res = await request(path, {
host: `puter.localhost:${port}`,
referer: `${parent}/sheet/1`,
});
expect(res.status).toBe(200);
expect(res.headers['x-frame-options']).toBeUndefined();
expect(res.headers['content-security-policy']).toBe(
`frame-ancestors 'self' ${parent}`,
);
expect(res.headers['cache-control']).toBe('no-store');
expect(res.body).toContain('/dist/apps-embed.min.js');
expect(res.body).not.toContain('/dist/bundle.min.js');
expect(res.body).toContain(`http://api.puter.localhost:${port}`);
const config = JSON.parse(
res.body.match(/id="app-browser-config">(.*?)<\/script>/)[1],
);
expect(Array.isArray(config.guestApps)).toBe(true);
}
const gui = await request('/embed/apps', {
host: `puter.localhost:${port}`,
referer: `http://puter.localhost:${port}/dashboard`,
});
expect(gui.headers['content-security-policy']).toBe("frame-ancestors 'self'");
const dashboard = await request('/dashboard', { host: `puter.localhost:${port}` });
expect(dashboard.headers['x-frame-options']).toBe('SAMEORIGIN');
const api = await request('/embed/apps', { host: `api.puter.localhost:${port}` });
expect(api.status).toBe(404);
});
it('lets a deployment subdomain frame the feedback embed and names it', async () => {
const parent = `http://spreadsheet.puter.localhost:${port}`;
const res = await request('/embed/feedback', {
host: `puter.localhost:${port}`,
referer: `${parent}/sheet/1`,
});
expect(res.status).toBe(200);
expect(res.headers['x-frame-options']).toBeUndefined();
expect(res.headers['content-security-policy']).toBe(
`frame-ancestors 'self' ${parent}`,
);
expect(res.headers['cache-control']).toBe('no-store');
expect(res.body).toContain('/dist/feedback-embed.min.js');
expect(res.body).not.toContain('/dist/bundle.min.js');
const config = JSON.parse(
res.body.match(/id="feedback-embed-config">(.*?)<\/script>/)[1],
);
expect(config).toEqual({
apiOrigin: `http://api.puter.localhost:${port}`,
hostOrigin: parent,
});
const hosted = await request('/embed/feedback', {
host: `puter.localhost:${port}`,
referer: `http://someone.site.puter.localhost:${port}/`,
});
expect(hosted.headers['content-security-policy']).toBe("frame-ancestors 'self'");
expect(
JSON.parse(
hosted.body.match(/id="feedback-embed-config">(.*?)<\/script>/)[1],
).hostOrigin,
).toBeNull();
const redirected = await request('/embed/feedback?puter.api_origin=https://other.test', {
host: `puter.localhost:${port}`,
});
expect(redirected.status).toBe(302);
expect(redirected.headers.location).toBe('/embed/feedback');
});
it.each([
'sign-in',
'show-open-file-picker',
'show-save-file-picker',
'show-directory-picker',
'upgrade',
])('lets a deployment subdomain frame the %s popup and names it to the GUI', async (action) => {
const parent = `http://spreadsheet.puter.localhost:${port}`;
const guiParams = (body: string) =>
JSON.parse(body.match(/gui\((\{.*\})\);/)[1]);
const res = await request(`/embed/${action}`, {
host: `puter.localhost:${port}`,
referer: `${parent}/sheet/1`,
});
expect(res.status).toBe(200);
expect(res.headers['x-frame-options']).toBeUndefined();
expect(res.headers['content-security-policy']).toBe(
`frame-ancestors 'self' ${parent}`,
);
expect(res.headers['cache-control']).toBe('no-store');
expect(guiParams(res.body).embed_host_origin).toBe(parent);
const hosted = await request(`/embed/${action}`, {
host: `puter.localhost:${port}`,
referer: `http://someone.site.puter.localhost:${port}/`,
});
expect(hosted.headers['content-security-policy']).toBe("frame-ancestors 'self'");
expect(guiParams(hosted.body).embed_host_origin).toBeNull();
const redirected = await request(`/embed/${action}?auth_token=x&embedded_in_popup=true`, {
host: `puter.localhost:${port}`,
referer: `${parent}/sheet/1`,
});
expect(redirected.status).toBe(302);
expect(redirected.headers.location).toBe(`/embed/${action}`);
expect(redirected.headers['x-frame-options']).toBe('SAMEORIGIN');
});
it.each(['/embed/SIGN-IN', '/embed/Show-Open-File-Picker', '/embed/sign-in/', '/embed/Upgrade', '/embed/upgrade/'])(
'lets a first-party page frame only the exact spelling of %s',
async (spelling) => {
const res = await request(spelling, {
host: `puter.localhost:${port}`,
referer: `http://spreadsheet.puter.localhost:${port}/`,
});
expect(res.status).toBe(302);
expect(res.headers.location).toBe(spelling.toLowerCase().replace(/\/$/, ''));
expect(res.headers['x-frame-options']).toBe('SAMEORIGIN');
expect(res.headers['content-security-policy']).toBeUndefined();
},
);
it('names no framing page to the popups it serves in a window', async () => {
const res = await request('/action/sign-in?embedded_in_popup=true', {
host: `puter.localhost:${port}`,
referer: `http://spreadsheet.puter.localhost:${port}/`,
});
expect(res.headers['x-frame-options']).toBe('SAMEORIGIN');
expect(res.headers['content-security-policy']).toBeUndefined();
expect(res.body).not.toContain('embed_host_origin');
});
it.each([
['a user-hosted site', 'http://someone.site.puter.localhost:PORT/'],
['a private app host', 'http://someone.app.puter.localhost:PORT/'],
['the API host', 'http://api.puter.localhost:PORT/'],
['the WebDAV host', 'http://dav.puter.localhost:PORT/'],
['a native app host', 'http://about.puter.localhost:PORT/'],
['a nested subdomain', 'http://a.spreadsheet.puter.localhost:PORT/'],
['another site', 'http://evil.test:PORT/'],
['another port', 'http://spreadsheet.puter.localhost:1/'],
['a suppressed referrer', undefined],
])('keeps the embed same-origin only when framed by %s', async (_label, referer) => {
const res = await request('/embed/apps', {
host: `puter.localhost:${port}`,
...(referer ? { referer: referer.replace('PORT', String(port)) } : {}),
});
expect(res.status).toBe(200);
expect(res.headers['content-security-policy']).toBe("frame-ancestors 'self'");
});
it.each([
['plain', ''],
// Past the parser's 1000-pair limit, so `req.query` comes back empty.
['padded', '&'.repeat(1000)],
])('strips %s SDK bootstrap query parameters from the embed route', async (_label, padding) => {
const res = await request(`/embed/apps?${padding}puter.app_instance_id=other&puter.api_origin=https://other.test`, {
host: `puter.localhost:${port}`,
});
expect(res.status).toBe(302);
expect(res.headers.location).toBe('/embed/apps');
expect(res.headers['x-frame-options']).toBe('SAMEORIGIN');
});
it('blocks a request the ip.validate listeners veto', async () => {
const handler = (_key: unknown, data: unknown) => {
(data as { allow: boolean }).allow = false;
@@ -27,17 +27,16 @@ import { PuterService } from '../types.js';
*/
export const RECOMMENDED_APP_NAMES = [
'builder',
'word-processor',
'spreadsheet',
'presentation',
'whiteboard',
'pdf-editor',
'contacts',
'calendar',
'meetings',
'teamchat',
'email',
'whiteboard',
'spreadsheet',
'word-processor',
'presentation',
'pdf-editor',
'terminal',
'dev-center',
'cap-table',
'invoices',
+10 -2
View File
@@ -121,7 +121,9 @@ export interface ProjectedNotifEvent extends ProjectedEventBase {
}
export type ProjectedEvent =
ProjectedFsEvent | ProjectedKvEvent | ProjectedNotifEvent;
| ProjectedFsEvent
| ProjectedKvEvent
| ProjectedNotifEvent;
export type GapReason =
| 'matched_subscription_limit'
@@ -270,7 +272,9 @@ export interface NotifPublicSubject extends SubjectSpec<
}
export type PublicSubject =
FsPublicSubject | KvPublicSubject | NotifPublicSubject;
| FsPublicSubject
| KvPublicSubject
| NotifPublicSubject;
export interface UnpublishedInternalEvent {
event: EventKey;
@@ -508,6 +512,10 @@ export const UNPUBLISHED_INTERNAL_EVENTS = [
event: 'notif.delivery.settled',
reason: 'A node-local report on how the live socket copy of a notification went; the notification itself publishes through `notif.created`.',
},
{
event: 'notif.handled',
reason: 'A node-local report that a page saw a notification live, for extensions deciding whether to push it; not a change to the notification.',
},
] as const satisfies readonly UnpublishedInternalEvent[];
// Every `fs.*`/`kv.*`/`notif.*` bus key needs a decision. A new key that is in
@@ -144,11 +144,22 @@ const createInline = async (
return String(response.body.subId);
};
const delivered = (count = 1): Promise<void> =>
vi.waitFor(() => expect(sinkPosts.length).toBeGreaterThanOrEqual(count), {
timeout: 30_000,
interval: 50,
});
/**
* The post each label made, in order, once all have arrived. Matched by label
* since earlier tests' subscriptions stay live and post to the same sink.
*/
const delivered = async (...labels: string[]): Promise<SinkPost[]> => {
await vi.waitFor(
() =>
expect(sinkPosts.map((post) => post.label)).toEqual(
expect.arrayContaining(labels),
),
{ timeout: 30_000, interval: 50 },
);
return labels.map((label) =>
sinkPosts.find((post) => post.label === label)!,
);
};
beforeAll(async () => {
env = await setupPuterTestEnv({
@@ -255,14 +266,11 @@ describe('an inline handler in a user scope, end to end', () => {
await env.server.services.fs.touch(holder.id, {
path: `${holder.anchor}/note.txt`,
});
await delivered();
const [post] = await delivered('inline');
expect(sinkPosts[0]).toMatchObject({
label: 'inline',
path: `${holder.anchor}/note.txt`,
});
expect(post.path).toBe(`${holder.anchor}/note.txt`);
const { actor } = await env.server.services.auth.authenticate(
sinkPosts[0].token!,
post.token!,
);
expect(actor!.user?.id).toBe(holder.id);
expect(actor!.effectiveApp?.uid).toBe(appUid);
@@ -297,14 +305,14 @@ describe('an inline handler in a user scope, end to end', () => {
await env.server.services.fs.touch(holder.id, {
path: `${holder.anchor}/shared-${i}.txt`,
});
await delivered(2);
const runAs = new Set<number>();
for (const post of sinkPosts)
runAs.add(
(await env.server.services.auth.authenticate(post.token!))
.actor!.user!.id,
// The first test's 'inline' handler also posts for holders[0].
const posts = await delivered('first', 'second');
for (const [i, post] of posts.entries()) {
const { actor } = await env.server.services.auth.authenticate(
post.token!,
);
expect(runAs).toEqual(new Set(holders.map((h) => h.id)));
expect(actor!.user!.id).toBe(holders[i].id);
}
create.mockRestore();
},
);
@@ -49,6 +49,89 @@ const makeReq = (over: Partial<Request> = {}): Request =>
...over,
}) as unknown as Request;
describe('app browser embed shell', () => {
it.each([
[{ env: 'dev' }, '/sdk/puter.dev.js'],
[{ env: 'prod' }, 'https://js.puter.com/v2/'],
[{ gui_puterjs_bundle: '/custom-sdk.js' }, '/custom-sdk.js'],
])('uses the deployment SDK configuration %j', (config, sdkUrl) => {
const service = makeService({
...config,
api_base_url: 'https://api.deployment.test',
domain: 'deployment.test',
});
const html = service.renderAppBrowserEmbed();
const configJson = html.match(/id="app-browser-config">(.*?)<\/script>/)![1];
expect(JSON.parse(configJson)).toEqual({
apiOrigin: 'https://api.deployment.test', sdkUrl, guestApps: [],
});
expect(html).toContain('/dist/apps-embed.min.js');
expect(html).not.toContain('/dist/bundle.min.js');
expect(html).not.toContain('gui(');
});
it.each([
[{}, '/dist/apps-embed.min.js'],
[
{ gui_bundle: 'https://gui-cdn.deployment.test/bundle.min.js' },
'https://gui-cdn.deployment.test/apps-embed.min.js',
],
[
{ gui_bundle: '/static/bundle.min.js?v=42' },
'/static/apps-embed.min.js?v=42',
],
])('loads its script from beside the GUI bundle %j', (config, script) => {
const html = makeService(config).renderAppBrowserEmbed();
expect(html).toContain(`<script defer src="${script}"></script>`);
});
it('escapes configured values without breaking its JSON bootstrap', () => {
const sdkUrl = '/sdk.js?value=</script><script>unexpected()</script>';
const html = makeService({
gui_params: { title: '<script>unexpected()</script>' },
gui_puterjs_bundle: sdkUrl,
}).renderAppBrowserEmbed();
expect(html).not.toContain('<script>unexpected()');
const configJson = html.match(/id="app-browser-config">(.*?)<\/script>/)![1];
expect(JSON.parse(configJson).sdkUrl).toBe(sdkUrl);
});
it('carries the apps shown without a session, escaped', () => {
const guestApps = [
{ name: 'notes', title: '</script><script>unexpected()</script>' },
];
const html = makeService({}).renderAppBrowserEmbed({ guestApps });
expect(html).not.toContain('<script>unexpected()');
const configJson = html.match(/id="app-browser-config">(.*?)<\/script>/)![1];
expect(JSON.parse(configJson).guestApps).toEqual(guestApps);
});
});
describe('feedback embed shell', () => {
it('carries the framing page and API origin, and loads only its own script', () => {
const html = makeService({
api_base_url: 'https://api.deployment.test',
gui_bundle: '/static/bundle.min.js?v=42',
}).renderFeedbackEmbed({ hostOrigin: 'https://notes.deployment.test' });
const configJson = html.match(/id="feedback-embed-config">(.*?)<\/script>/)![1];
expect(JSON.parse(configJson)).toEqual({
apiOrigin: 'https://api.deployment.test',
hostOrigin: 'https://notes.deployment.test',
});
expect(html).toContain('<script defer src="/static/feedback-embed.min.js?v=42"></script>');
expect(html).toContain('<link rel="stylesheet" href="/css/feedback-embed.css">');
expect(html).toContain('<main id="feedback-embed"></main>');
expect(html).not.toContain('bundle.min.js');
expect(html).not.toContain('apps-embed');
});
it('carries no framing page when none is allowed', () => {
const html = makeService({}).renderFeedbackEmbed({ hostOrigin: null });
const configJson = html.match(/id="feedback-embed-config">(.*?)<\/script>/)![1];
expect(JSON.parse(configJson).hostOrigin).toBeNull();
});
});
/** Capture what the service sends, and return the rendered HTML. */
const render = async (
service: PuterHomepageService,
@@ -48,6 +48,15 @@ export interface LaunchOptions {
on_initialized?: Array<Record<string, unknown>>;
}
/**
* A GUI popup a first-party page frames at `/embed/<action>`. `hostOrigin` is
* that page, read from the referrer and pinned with frame-ancestors; null when
* no allowed page frames it.
*/
export interface PopupFrame {
hostOrigin: string | null;
}
interface PuterGuiAddonsEvent {
req: Request;
path: string;
@@ -167,6 +176,91 @@ export class PuterHomepageService extends PuterService {
this.#guiParams[key] = val;
}
/** `guestApps` is what the embed shows a visitor without a session. */
renderAppBrowserEmbed({
guestApps = [],
}: { guestApps?: Array<Record<string, unknown>> } = {}): string {
return this.#renderEmbed({
rootId: 'app-browser',
rootClass: 'dashboard',
stylesheet: 'apps-embed.css',
script: 'apps-embed.min.js',
config: {
apiOrigin: this.config.api_base_url,
sdkUrl:
this.config.env === 'dev'
? '/sdk/puter.dev.js'
: (this.config.gui_puterjs_bundle ??
'https://js.puter.com/v2/'),
guestApps,
},
});
}
/**
* `hostOrigin` is the first-party page framing the dialog, which the
* feedback is sent for; null when no allowed page frames it.
*/
renderFeedbackEmbed({ hostOrigin }: { hostOrigin: string | null }): string {
return this.#renderEmbed({
rootId: 'feedback-embed',
stylesheet: 'feedback-embed.css',
script: 'feedback-embed.min.js',
config: { apiOrigin: this.config.api_base_url, hostOrigin },
});
}
#renderEmbed({
rootId,
rootClass,
stylesheet,
script,
config,
}: {
rootId: string;
rootClass?: string;
stylesheet: string;
script: string;
config: Record<string, unknown>;
}): string {
const configJson = JSON.stringify(config).replace(/</g, '\\u003c');
return `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="robots" content="noindex">
<title>${encode(String(this.config.gui_params?.title ?? 'Puter'))}</title>
<link rel="stylesheet" href="/css/normalize.css">
<link rel="stylesheet" href="/css/dashboard.css">
<link rel="stylesheet" href="/css/${stylesheet}">
</head>
<body>
<main id="${rootId}"${rootClass ? ` class="${rootClass}"` : ''}></main>
<script type="application/json" id="${rootId}-config">${configJson}</script>
<script defer src="${encode(this.#embedScript(script))}"></script>
</body>
</html>`;
}
/**
* Embed scripts are built beside the GUI bundle, so they are served from
* wherever `gui_bundle` is (a CDN in production), with the same query.
*/
#embedScript(name: string): string {
const base = 'http://relative.invalid';
const bundle = new URL(
this.config.gui_bundle ?? '/dist/bundle.min.js',
base,
);
const script = new URL(name, bundle);
script.search = bundle.search;
return script.origin === base
? `${script.pathname}${script.search}`
: script.href;
}
/** `scriptPath` is a same-origin absolute path, like `/ext/push/worker.js`. */
registerServiceWorkerScript(scriptPath: string): void {
if (
@@ -218,6 +312,7 @@ export class PuterHomepageService extends PuterService {
ctx: { req: Request; res: Response; actor?: Actor | null },
meta: PageMeta,
launchOptions: LaunchOptions = {},
popupFrame?: PopupFrame,
): Promise<void> {
const { req, res, actor } = ctx;
@@ -242,6 +337,7 @@ export class PuterHomepageService extends PuterService {
{ req, actor: actor ?? null },
meta,
launchOptions,
popupFrame,
);
res.send(html);
}
@@ -252,6 +348,7 @@ export class PuterHomepageService extends PuterService {
ctx: { req: Request; actor: Actor | null },
meta: PageMeta,
launchOptions: LaunchOptions,
popupFrame?: PopupFrame,
): Promise<string> {
const { req, actor } = ctx;
const env = this.config.env ?? 'prod';
@@ -297,6 +394,8 @@ export class PuterHomepageService extends PuterService {
eventsNotifications: notificationsFoldInEnabled(this.config),
...meta,
launch_options: launchOptions,
// After `meta`, so nothing page-specific can name the opener.
...(popupFrame ? { embed_host_origin: popupFrame.hostOrigin } : {}),
};
const event: PuterGuiAddonsEvent = {
@@ -78,7 +78,10 @@ describe('LocalWorkerService shutdown disposal', () => {
disposals[0].mockImplementationOnce(async () => {
await held;
});
vi.useFakeTimers();
vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });
// The test server keeps arming timers from real callbacks while fakes
// are installed, so only what shutdown arms synchronously is checked.
const arm = vi.spyOn(globalThis, 'setTimeout');
try {
let finished = false;
const draining = Promise.resolve(service.onServerShutdown()).then(
@@ -86,12 +89,13 @@ describe('LocalWorkerService shutdown disposal', () => {
finished = true;
},
);
expect(arm.mock.calls.map(([, ms]) => ms)).toEqual([5_000]);
await vi.advanceTimersByTimeAsync(4_999);
expect(finished).toBe(false);
await vi.advanceTimersByTimeAsync(1);
await draining;
expect(vi.getTimerCount()).toBe(0);
} finally {
arm.mockRestore();
release();
vi.useRealTimers();
}
@@ -23,10 +23,14 @@ import { handlerDepthOf, type Actor } from '../../core/actor.js';
import { Context } from '../../core/context.js';
import type { NotifEventContext } from '../events/registry.js';
import { PuterService } from '../types.js';
import { checkRateLimit } from '../../core/http/middleware/rateLimit.js';
import {
NOTIF_HANDLED_EVENT,
NOTIF_HANDLED_PER_MINUTE,
NotificationSocketAdapter,
notificationAckTimeoutMs,
notificationsFoldInEnabled,
type NotifSocket,
type ReceiptScope,
} from './notificationSocket.js';
import {
@@ -404,6 +408,11 @@ export class NotificationService extends PuterService {
return this.#socket().receipt(scope);
}
/** Installs the `notif.handled` verb on one connection. */
attachSocket(socket: NotifSocket, actor: Actor): void {
this.#socket().attachSocket(socket, actor);
}
/**
* Drop notifications past the retention window, in batches, and report how
* many went. Deleting is all there is to it: nothing is pushed, because a
@@ -439,6 +448,12 @@ export class NotificationService extends PuterService {
ackTimeoutMs: () => notificationAckTimeoutMs(this.config),
heldInPeerRegion: (userId, appUid) =>
this.#heldInPeerRegion(userId, appUid),
allowHandled: (userId) =>
checkRateLimit(
`socket:${NOTIF_HANDLED_EVENT}:${userId}`,
NOTIF_HANDLED_PER_MINUTE,
60_000,
),
});
return this.#adapter;
}
@@ -32,7 +32,10 @@ import {
import type { EventMap } from '../../clients/event/types.js';
import type { PuterServer } from '../../server.js';
import { accountSocketRoom, SocketService } from '../socket/SocketService.js';
import { NOTIF_RECEIPT_EVENT } from './notificationSocket.js';
import {
NOTIF_HANDLED_EVENT,
NOTIF_RECEIPT_EVENT,
} from './notificationSocket.js';
import {
allocateEphemeralPort,
createTestUser,
@@ -309,12 +312,13 @@ describe('live notification delivery receipts', () => {
complete: true,
peerRegions: false,
responders: [{ visibilityState: 'hidden' }],
handled: false,
};
expect(settled).toEqual(expected);
expect(state.settled).toEqual([expected]);
});
it('passes a tab`s focus and own display through, typed strictly', async () => {
it('passes a tab`s focus through, typed strictly', async () => {
const answers = [
{
received: true,
@@ -326,7 +330,6 @@ describe('live notification delivery receipts', () => {
received: true,
visibilityState: 'nope',
focused: 1,
showsOwn: 'yes',
},
];
for (const answer of answers) {
@@ -341,11 +344,39 @@ describe('live notification delivery receipts', () => {
expect(settled.outcome).toBe('received');
expect(settled.responders).toEqual(
expect.arrayContaining([
{ visibilityState: 'hidden', focused: false, showsOwn: true },
{ visibilityState: 'hidden', focused: false },
{ visibilityState: 'unknown' },
]),
);
expect(settled.responders).toHaveLength(2);
expect(settled.handled).toBe(false);
});
it('counts as handled only a visible tab that is focused, or an older one that is visible', async () => {
const cases: Array<[Record<string, unknown>, boolean]> = [
[{ visibilityState: 'visible', focused: true }, true],
[{ visibilityState: 'visible', focused: false }, false],
[{ visibilityState: 'hidden', focused: true }, false],
[{ visibilityState: 'visible' }, true],
];
for (const [answer, handled] of cases) {
const tab = await connect({ acks: [NOTIF_RECEIPT_EVENT] });
tab.on(NOTIF_RECEIPT_EVENT, (_data: unknown, ack: Ack) =>
ack({ received: true, ...answer }),
);
const { settled } = await ask();
expect(settled.handled, JSON.stringify(answer)).toBe(handled);
tab.disconnect();
await vi.waitFor(() =>
expect(
state.server.services.socket.has({
room: accountSocketRoom(state.userId),
}),
).toBe(false),
);
}
});
it('settles as unreceived when every tab answers that it never got it', async () => {
@@ -549,6 +580,7 @@ describe('live receipts from an app’s own sockets', () => {
complete: true,
peerRegions: false,
responders: [{ visibilityState: 'visible' }],
handled: true,
};
expect(settled).toEqual(expected);
expect(state.settled).toEqual([expected]);
@@ -719,3 +751,59 @@ describe('app receipts where the adapter cannot count servers', () => {
});
});
});
describe('a page reporting a notification it handled', () => {
const { state, connect, appSocket } = withAppReceipts({ cluster: true });
const reports: Array<EventMap['notif.handled']> = [];
const onHandled = (_key: string, data: unknown) => {
reports.push(data as EventMap['notif.handled']);
};
beforeAll(() => {
state.server.clients.event.on('notif.handled', onHandled);
});
afterEach(() => {
reports.length = 0;
});
afterAll(() => {
state.server?.clients.event.off('notif.handled', onHandled);
});
it('relays a desktop tab`s report for its user, without an app', async () => {
const tab = await connect({});
const uid = uuidv4();
tab.emit(NOTIF_HANDLED_EVENT, { uid });
await vi.waitFor(() =>
expect(reports).toEqual([{ userId: state.userId, uid }]),
);
});
it('relays an app page`s report with the app it acts as', async () => {
const page = await appSocket();
const uid = uuidv4();
page.emit(NOTIF_HANDLED_EVENT, { uid });
await vi.waitFor(() =>
expect(reports).toEqual([
{ userId: state.userId, uid, appUid: OWN_APP },
]),
);
});
it('drops a report without a notification uid', async () => {
const tab = await connect({});
tab.emit(NOTIF_HANDLED_EVENT, { uid: 'not-a-uid' });
tab.emit(NOTIF_HANDLED_EVENT, null);
tab.emit(NOTIF_HANDLED_EVENT, { uid: uuidv4() });
await vi.waitFor(() => expect(reports).toHaveLength(1));
await new Promise((resolve) => setTimeout(resolve, 100));
expect(reports).toHaveLength(1);
});
});
@@ -17,7 +17,9 @@
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import { validate as validateUuid } from 'uuid';
import type { EventClient } from '../../clients/event/EventClient.js';
import type { Actor } from '../../core/actor.js';
import type {
EventMap,
NotifDeliveryOutcome,
@@ -53,7 +55,10 @@ import type { IConfig } from '../../types.js';
*/
export type NotifWire =
'notif.message' | 'notif.unreads' | 'notif.ack' | 'notif.removed';
| 'notif.message'
| 'notif.unreads'
| 'notif.ack'
| 'notif.removed';
export const NOTIF_DELIVERY_EVENT = 'outer.notif.delivery';
@@ -67,6 +72,15 @@ export const DEFAULT_NOTIFICATION_ACK_TIMEOUT_MS = 5_000;
*/
export const NOTIF_RECEIPT_EVENT = 'notif.receipt';
/**
* Sent by a page with `{ uid }` when it got that notification live while
* visible and focused, so a region that didn't ask the page can still hear it.
*/
export const NOTIF_HANDLED_EVENT = 'notif.handled';
/** `notif.handled` reports one user's sockets may send per minute. */
export const NOTIF_HANDLED_PER_MINUTE = 60;
/** One unread as the replay payload carries it. */
export interface UnreadNotification {
uid: string;
@@ -122,12 +136,16 @@ const responderOf = (response: unknown): NotifDeliveryResponder | null => {
...(typeof answer.focused === 'boolean'
? { focused: answer.focused }
: {}),
...(typeof answer.showsOwn === 'boolean'
? { showsOwn: answer.showsOwn }
: {}),
};
};
/**
* Visible and focused. An older client doesn't say whether it's focused, so it
* counts while visible.
*/
export const handledBy = (responder: NotifDeliveryResponder): boolean =>
responder.visibilityState === 'visible' && responder.focused !== false;
interface AdapterDeps {
event: EventClient;
socket: SocketService;
@@ -138,6 +156,13 @@ interface AdapterDeps {
userId: number,
appUid: string | null,
) => Promise<boolean>;
/** Spends one of the user's `notif.handled` reports; false past the limit. */
allowHandled: (userId: number) => Promise<boolean>;
}
/** The part of a socket `attachSocket` installs its verb on. */
export interface NotifSocket {
on(event: string, listener: (...args: never[]) => void): unknown;
}
type SettledDelivery = EventMap['notif.delivery.settled'];
@@ -253,6 +278,7 @@ export class NotificationSocketAdapter {
complete: asked.complete,
peerRegions,
responders,
handled: responders.some(handledBy),
};
this.#deps.event.emit(
'notif.delivery.settled',
@@ -266,6 +292,28 @@ export class NotificationSocketAdapter {
}
}
/**
* Relays a page's `notif.handled` as the node-local `notif.handled` event,
* scoped to the socket's user and app.
*/
attachSocket(socket: NotifSocket, actor: Actor): void {
const userId = actor.user?.id;
if (userId === undefined) return;
const appUid = actor.effectiveApp?.uid;
socket.on(NOTIF_HANDLED_EVENT, ((payload: unknown) => {
const uid = (payload as { uid?: unknown } | null)?.uid;
if (typeof uid !== 'string' || !validateUuid(uid)) return;
void this.#deps.allowHandled(userId).then((ok) => {
if (!ok) return;
this.#deps.event.emit(
'notif.handled',
{ userId, uid, ...(appUid ? { appUid } : {}) },
{},
);
});
}) as (...args: never[]) => void);
}
/** Whether this region holds a socket for the recipient right now. */
hasSocket(userId: number): boolean {
return this.#deps.socket.has({ room: userId });
@@ -39,6 +39,7 @@ import {
MAX_REALTIME_MESSAGE_BYTES,
MAX_UPSTREAM_MESSAGE_BYTES,
OpenAIRealtimeRelayService,
promptMessagesOf,
REALTIME_PATH,
type RealtimeUsage,
type RealtimeTranscriptionUsage,
@@ -122,6 +123,65 @@ describe('realtimeUsageRows', () => {
});
});
describe('promptMessagesOf', () => {
it('reads message text, transcripts and function output from items', () => {
expect(
promptMessagesOf({
type: 'conversation.item.create',
item: {
type: 'message',
role: 'assistant',
content: [
{ type: 'output_text', text: 'Hi' },
{ type: 'output_audio', transcript: 'Spoken' },
{ type: 'input_audio', audio: 'AAAA' },
],
},
}),
).toEqual([
{ role: 'assistant', content: 'Hi' },
{ role: 'assistant', content: 'Spoken' },
]);
expect(
promptMessagesOf({
type: 'conversation.item.create',
item: { type: 'function_call_output', output: '{"ok":1}' },
}),
).toEqual([{ role: 'tool', content: '{"ok":1}' }]);
});
it('reads response instructions and out-of-band input', () => {
expect(
promptMessagesOf({
type: 'response.create',
response: {
instructions: 'Summarize.',
input: [
{ type: 'item_reference', id: 'item_1' },
{
type: 'message',
role: 'user',
content: [{ type: 'input_text', text: 'Text' }],
},
],
},
}),
).toEqual([
{ role: 'system', content: 'Summarize.' },
{ role: 'user', content: 'Text' },
]);
});
it('returns nothing for audio and other events', () => {
expect(
promptMessagesOf({ type: 'input_audio_buffer.append', audio: 'x' }),
).toEqual([]);
expect(
promptMessagesOf({ type: 'session.update', session: {} }),
).toEqual([]);
});
});
describe('realtimeTranscriptionRows', () => {
it('prices token usage by transcription model', () => {
const rows = realtimeTranscriptionRows('gpt-4o-mini-transcribe', {
@@ -1380,6 +1440,139 @@ describe('OpenAIRealtimeRelayService relay', () => {
}
});
describe('prompt checks', () => {
type Check = {
completionId: string;
allow: boolean;
parameters: { model: string; messages: unknown[] };
};
let checks: Check[];
let costs: Record<string, unknown>[];
let refuse: (check: Check) => boolean;
const validate = (_key: string, data: Check) => {
checks.push(structuredClone(data));
if (refuse(data)) data.allow = false;
};
const costCalculated = (_key: string, data: Record<string, unknown>) =>
void costs.push(data);
beforeEach(() => {
checks = [];
costs = [];
refuse = () => false;
server.clients.event.on('ai.prompt.validate', validate as never);
server.clients.event.on(
'ai.prompt.cost-calculated',
costCalculated as never,
);
});
afterEach(() => {
server.clients.event.off('ai.prompt.validate', validate as never);
server.clients.event.off(
'ai.prompt.cost-calculated',
costCalculated as never,
);
});
it('checks the text sent before each response and logs its cost under the same id', async () => {
const c = open(
`${relayUrl}?model=gpt-realtime-mini&auth_token=${user.token}`,
);
await c.waitFor('session.created');
c.ws.send(
JSON.stringify({
type: 'session.update',
session: { instructions: 'Be brief.' },
}),
);
c.ws.send(
JSON.stringify({
type: 'conversation.item.create',
item: {
type: 'message',
role: 'user',
content: [{ type: 'input_text', text: 'Hello' }],
},
}),
);
c.ws.send(JSON.stringify({ type: 'response.create' }));
await vi.waitFor(() => expect(costs).toHaveLength(1));
expect(checks).toEqual([
expect.objectContaining({
allow: true,
parameters: {
model: 'gpt-realtime-mini',
messages: [
{ role: 'system', content: 'Be brief.' },
{ role: 'user', content: 'Hello' },
],
},
}),
]);
expect(costs[0]).toMatchObject({
completionId: checks[0].completionId,
input_tokens: 7,
output_tokens: 3,
input_ucents: 7 * 60,
output_ucents: 3 * 240,
total_ucents: 7 * 60 + 3 * 240,
model_used: 'gpt-realtime-mini',
});
// A response with no new text is still logged.
c.ws.send(JSON.stringify({ type: 'response.create' }));
await vi.waitFor(() => expect(costs).toHaveLength(2));
expect(checks[1].parameters.messages).toEqual([]);
expect(costs[1].completionId).toBe(checks[1].completionId);
c.ws.close();
});
it('closes the session when the check refuses the text', async () => {
refuse = (check) =>
JSON.stringify(check.parameters.messages).includes('refuse me');
const c = open(`${relayUrl}?auth_token=${user.token}`);
await c.waitFor('session.created');
c.ws.send(
JSON.stringify({
type: 'response.create',
response: { instructions: 'refuse me' },
}),
);
expect(await c.waitFor('error')).toMatchObject({
error: { code: 'permission_denied' },
});
expect((await c.closed).code).toBe(1008);
expect(costs).toHaveLength(0);
});
it('checks pending text on its own once it passes 64 KiB', async () => {
const c = open(`${relayUrl}?auth_token=${user.token}`);
await c.waitFor('session.created');
const item = (text: string) =>
JSON.stringify({
type: 'conversation.item.create',
item: {
type: 'message',
role: 'user',
content: [{ type: 'input_text', text }],
},
});
c.ws.send(item('a'.repeat(40 * 1024)));
c.ws.send(item('b'.repeat(40 * 1024)));
c.ws.send(JSON.stringify({ type: 'response.create' }));
await vi.waitFor(() => expect(costs).toHaveLength(1));
expect(
checks.map((check) =>
(check.parameters.messages as { content: string }[]).map(
(m) => m.content[0],
),
),
).toEqual([['a'], ['b']]);
expect(costs[0].completionId).toBe(checks[1].completionId);
c.ws.close();
});
});
it('does not allocate credential limiter buckets for many unique invalid signatures', async () => {
const before = upstreamRequests.length;
const auth = vi.spyOn(server.services.auth, 'authenticate');
@@ -2667,8 +2860,12 @@ describe('OpenAIRealtimeRelayService relay', () => {
),
).toHaveLength(64),
);
// Holds are reserved and usage recorded one at a time, which a loaded
// runner takes past vi.waitFor's default second.
const settled = (check: () => Promise<void> | void) =>
vi.waitFor(check, { timeout: 5_000 });
// The pool grew one item per commit, with nothing spare at the cap.
await vi.waitFor(async () =>
await settled(async () =>
expect(
await server.services.metering.getOutstandingHolds(actor),
).toBe(64 * 10_896_000),
@@ -2697,7 +2894,7 @@ describe('OpenAIRealtimeRelayService relay', () => {
for (let batch = 0; batch < 8; batch++) {
for (let i = Math.max(1, batch * 8); i < (batch + 1) * 8; i++)
complete(i);
await vi.waitFor(() =>
await settled(() =>
expect(
recorded.mock.calls
.flatMap(([, rows]) => rows)
@@ -2713,13 +2910,13 @@ describe('OpenAIRealtimeRelayService relay', () => {
.filter((row) => row.usageType.includes('transcription_'))
.reduce((sum, row) => sum + row.costOverride!, 0),
).toBe(640);
await vi.waitFor(async () =>
await settled(async () =>
expect(
await server.services.metering.getOutstandingHolds(actor),
).toBe(2 * 10_896_000),
);
c.ws.close();
await vi.waitFor(async () =>
await settled(async () =>
expect(
await server.services.metering.getOutstandingHolds(actor),
).toBe(0),
@@ -17,11 +17,12 @@
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import { createHash } from 'node:crypto';
import { createHash, randomUUID } from 'node:crypto';
import type { IncomingMessage, Server as HttpServer } from 'node:http';
import type { Duplex } from 'node:stream';
import express from 'express';
import type { AnyTokenPayload } from '../auth/types.js';
import type { EventMap } from '../../clients/event/types.js';
import WebSocket, { WebSocketServer, type RawData } from 'ws';
import type { Actor } from '../../core/actor.js';
import {
@@ -201,6 +202,8 @@ const RECONNECT_NOTICE_INTERVAL_MS = 60_000;
const TRANSCRIPTION_DONE =
'conversation.item.input_audio_transcription.completed';
const METERING_DRIVER = 'openai-realtime';
// Text awaiting a prompt check; past this it is checked without a response.
const MAX_PENDING_PROMPT_CHARS = 64 * 1024;
// Provider organization IDs, as OpenAI puts them in some error messages.
const ORG_ID = /\borg-[A-Za-z0-9]{8,}/g;
@@ -477,6 +480,50 @@ const clientEventRefusal = (event: RealtimeEvent): string | null => {
return null;
};
type PromptMessage = { role: string; content: string };
const itemPromptMessages = (item: unknown): PromptMessage[] => {
if (!isRecord(item)) return [];
if (item.type === 'function_call_output') {
return typeof item.output === 'string' && item.output
? [{ role: 'tool', content: item.output }]
: [];
}
if (item.type !== 'message' || !Array.isArray(item.content)) return [];
const role = typeof item.role === 'string' ? item.role : 'user';
return item.content.flatMap((part) => {
if (!isRecord(part)) return [];
const text = part.text ?? part.transcript;
return typeof text === 'string' && text
? [{ role, content: text }]
: [];
});
};
/** The text a client event adds to the model's context, as chat messages. */
export const promptMessagesOf = (event: unknown): PromptMessage[] => {
if (!isRecord(event)) return [];
if (event.type === 'conversation.item.create') {
return itemPromptMessages(event.item);
}
const config =
event.type === 'session.update'
? event.session
: event.type === 'response.create'
? event.response
: undefined;
if (!isRecord(config)) return [];
const messages: PromptMessage[] =
typeof config.instructions === 'string' && config.instructions
? [{ role: 'system', content: config.instructions }]
: [];
if (Array.isArray(config.input)) {
for (const item of config.input)
messages.push(...itemPromptMessages(item));
}
return messages;
};
/** Whichever of two pricings of the same usage costs more. */
export const costlierRows = (
a: UsageInput[],
@@ -900,6 +947,14 @@ export class OpenAIRealtimeRelayService extends PuterService {
let requested = 0;
// Credit holds of responses whose usage isn't recorded yet.
const responseHolds = new Map<string, Promise<CreditHold | null>>();
// Text sent since the last prompt check, checked when the next
// response starts. Each started response maps to the completion id
// its check logged, or null if the check refused it.
const checkPrompts =
this.clients.event.hasListeners('ai.prompt.validate');
let promptMessages: PromptMessage[] = [];
let promptChars = 0;
const responseCompletions = new Map<string, Promise<string | null>>();
// Committed input items awaiting usage, each with the transcription
// model in force at commit and the credit held for it.
const pendingTranscriptions = new Map<
@@ -1062,13 +1117,15 @@ export class OpenAIRealtimeRelayService extends PuterService {
identity?.type === 'app-under-user'
? identity.session
: undefined;
if (!(
sessionUids?.has(sessionUid ?? '') ||
sessionUids?.has(parentUid ?? '') ||
(tokenUid &&
identity?.type === 'access-token' &&
identity.token_uid === tokenUid)
))
if (
!(
sessionUids?.has(sessionUid ?? '') ||
sessionUids?.has(parentUid ?? '') ||
(tokenUid &&
identity?.type === 'access-token' &&
identity.token_uid === tokenUid)
)
)
return;
if (token) {
kv.del(realtimeAuthKey(token));
@@ -1430,6 +1487,82 @@ export class OpenAIRealtimeRelayService extends PuterService {
}
};
// Runs the host's prompt check on the pending text, which also logs
// it. A refusal closes the session.
const checkPrompt = async (): Promise<string | null> => {
const completionId = randomUUID().replaceAll('-', '').slice(0, 25);
const check: EventMap['ai.prompt.validate'] = {
username: actor!.user?.username || '',
actor,
completionId,
allow: true,
intended_service: METERING_DRIVER,
parameters: { model: billingModel, messages: promptMessages },
};
promptMessages = [];
promptChars = 0;
try {
await this.clients.event.emitAndWait(
'ai.prompt.validate',
check,
{},
);
} catch (err) {
console.warn('[realtime] prompt check failed', err);
}
if (check.allow !== false) return completionId;
reject('permission_denied', 'Prompt blocked by policy');
return null;
};
const notePrompt = (event: RealtimeEvent) => {
for (const message of promptMessagesOf(event)) {
if (
promptChars + message.content.length >
MAX_PENDING_PROMPT_CHARS
)
void checkPrompt();
promptMessages.push(message);
promptChars += message.content.length;
}
};
// Adds a response's cost to the row its prompt check logged.
const logResponseCost = async (
id: string,
rows: UsageInput[],
usage: unknown,
) => {
const completion = responseCompletions.get(id);
if (!completion) return;
responseCompletions.delete(id);
const completionId = await completion;
if (!completionId) return;
const input = { tokens: 0, ucents: 0 };
const output = { tokens: 0, ucents: 0 };
for (const row of rows) {
const side = row.usageType.endsWith('_output') ? output : input;
side.tokens += row.usageAmount;
side.ucents += row.costOverride ?? 0;
}
this.clients.event.emit(
'ai.prompt.cost-calculated',
{
completionId,
username: actor!.user?.username || '',
usage,
input_tokens: input.tokens,
output_tokens: output.tokens,
input_ucents: input.ucents,
output_ucents: output.ucents,
total_ucents: input.ucents + output.ucents,
costs_currency: 'usd-cents',
model_used: billingModel,
service_used: 'openai',
intended_service: METERING_DRIVER,
},
{},
);
};
// One transcription item's credit at `name`'s price and cost factor,
// or null when the account can't cover it. Reservations run one at a
// time, so a session's own holds don't race each other's balance check.
@@ -1565,6 +1698,8 @@ export class OpenAIRealtimeRelayService extends PuterService {
if (typeof id !== 'string') break;
inFlightIds.add(id);
holdResponse(id);
if (checkPrompts)
responseCompletions.set(id, checkPrompt());
if (closed) {
upstream?.send(
JSON.stringify({
@@ -1575,18 +1710,15 @@ export class OpenAIRealtimeRelayService extends PuterService {
}
break;
}
case 'response.done':
case 'response.done': {
inFlight = Math.max(0, inFlight - 1);
const usage = event.response?.usage ?? undefined;
const rows = realtimeUsageRows(billingModel, usage);
meter(rows, takeHold(event.response?.id));
if (typeof event.response?.id === 'string') {
inFlightIds.delete(event.response.id);
void logResponseCost(event.response.id, rows, usage);
}
meter(
realtimeUsageRows(
billingModel,
event.response?.usage ?? undefined,
),
takeHold(event.response?.id),
);
if (inFlight === 0) {
onIdle?.();
if (
@@ -1598,6 +1730,7 @@ export class OpenAIRealtimeRelayService extends PuterService {
endUpstream();
}
break;
}
case 'input_audio_buffer.speech_started': {
// Detected speech is committed when it stops, from where
// the provider says it began.
@@ -1839,6 +1972,7 @@ export class OpenAIRealtimeRelayService extends PuterService {
pending.shift();
pendingBytes -= (next.data as Buffer).length;
if (event.type === 'response.create') requested++;
if (checkPrompts) notePrompt(event);
sendUpstream(next.data, next.isBinary);
}
return undefined;
+10 -8
View File
@@ -1,11 +1,11 @@
# OpenAI Realtime relay
The relay serves `/puterai/openai/v1/realtime` on the API host. The SDK exposes
it through [`puter.ai.convo()`](../../../docs/src/AI/convo.md).
it through [`puter.ai.realtime()`](../../../docs/src/AI/realtime.md).
**Beta:** This API is incomplete. Its methods, options, events, and behavior may change abruptly, including breaking changes without notice.
Direct clients are documented in the [Realtime WebSocket API reference](../../../docs/src/AI/realtime.md).
Direct clients are documented in the [Realtime WebSocket API reference](../../../docs/src/AI/realtime-websocket.md).
## Transport
@@ -27,7 +27,7 @@ The socket opens before authentication completes. Authentication and model
failures arrive as OpenAI-shaped error events followed by a close frame.
```js
const conversation = await puter.ai.convo({ output: ['text'] });
const conversation = await puter.ai.realtime({ output: ['text'] });
conversation.on('error', (event) => console.error(event));
conversation.on('text', ({ delta }) => console.log(delta));
conversation.on('turn.done', () => conversation.close());
@@ -105,11 +105,13 @@ excludes outstanding holds and accepts fractional positive credit. Admission of
new billable work continues to use the atomic hold path, which includes every
outstanding reservation.
Text, transcripts and raw audio are forwarded without new content logging.
The relay does not invoke `ai.prompt.validate`. A realtime adapter needs the host
listeners' chat payload and denial contracts before that hook can safely apply
to instructions and conversation text. Raw audio and generated transcripts need
separate policy decisions.
When the host listens for `ai.prompt.validate`, each response that starts runs
it on the text the client sent since the previous check: session and response
instructions, message text and transcripts, and function call output, as chat
messages. The response's cost follows as `ai.prompt.cost-calculated` under the
same completion id. A refusal closes the session with `permission_denied`; the
response may already be streaming by then. Pending text past 64 KiB is checked
on its own. Audio is not checked.
Credential checks run in batches of at most 16 with no overlapping sweeps.
Session and access-token revocation events close affected sockets and invalidate
+8 -3
View File
@@ -699,7 +699,8 @@ export class SocketService extends PuterService {
// `{ auth: { ... } }`, not the query string. puter-js uses
// `io(url, { auth: { auth_token } })`.
const handshakeAuth = socket.handshake.auth as
Record<string, unknown> | undefined;
| Record<string, unknown>
| undefined;
const tokenRaw =
typeof handshakeAuth?.auth_token === 'string'
? handshakeAuth.auth_token
@@ -1085,6 +1086,7 @@ export class SocketService extends PuterService {
// them. Off unless events are enabled, in which case the verbs
// answer with `events_disabled` rather than going unanswered.
this.services.events.attachSocket(socket, actor);
this.services.notification.attachSocket(socket, actor);
// Everything below is the desktop session's own traffic: two verbs
// that reach the user's other tabs, and a connect announcement
@@ -1221,7 +1223,8 @@ export class SocketService extends PuterService {
// their next poll of /cache/last-change-timestamp.
const originalSocketId = (
data.response as
{ original_client_socket_id?: string } | undefined
| { original_client_socket_id?: string }
| undefined
)?.original_client_socket_id;
await this.send({ room: userId }, 'cache.updated', {
timestamp,
@@ -1235,7 +1238,9 @@ export class SocketService extends PuterService {
#handleUploadProgress(data: UploadProgressPayload): void {
const meta = data.meta ?? {};
const userId = (meta.user_id ?? meta.userId) as
number | string | undefined;
| number
| string
| undefined;
if (!userId) {
console.warn('[socket] upload-progress missing user_id', { meta });
return;
+9 -4
View File
@@ -1542,18 +1542,22 @@ describe('AppStore detailed stats', () => {
let db;
const APP_UID = `app-stats-${Date.now()}`;
const nowSeconds = Math.floor(Date.now() / 1000);
// The windows come from the clock, so it is pinned: mid-week and
// mid-month, and minutes clear of midnight in any time zone.
const NOW = new Date('2026-06-17T12:07:30Z');
const nowSeconds = Math.floor(NOW.getTime() / 1000);
beforeAll(async () => {
server = await setupTestServer();
appStore = server.stores.app;
db = server.clients.db;
await clearAppCache(server.clients.redis);
vi.useFakeTimers({ toFake: ['Date'], now: NOW });
// Two users; the repeat shares a timestamp so it is always same-hour.
// Two users in one hour. Windows end at now, exclusive.
for (const [userId, offset] of [
[1, 0],
[1, 0],
[1, 60],
[1, 60],
[2, 120],
]) {
await db.write(
@@ -1564,6 +1568,7 @@ describe('AppStore detailed stats', () => {
});
afterAll(async () => {
vi.useRealTimers();
await server?.shutdown();
});
+3
View File
@@ -154,6 +154,9 @@ export const setupTestServer = async (
redis: { useMock: true },
// Suites run system jobs themselves, not on the poll timer.
jobs: { enabled: false },
// The health loop's timed `SELECT 1` would land in tests that
// count queries.
server_health: { disabled_checks: ['database-liveness'] },
s3: { localConfig: { inMemory: true } },
no_default_user: true,
no_devwatch: true,
+8 -8
View File
@@ -256,12 +256,7 @@ export interface IPreludeConfig {
* an RCS agent provisioned in the Prelude account to actually use RCS.
*/
preferredChannel?:
| 'sms'
| 'rcs'
| 'whatsapp'
| 'viber'
| 'zalo'
| 'telegram';
'sms' | 'rcs' | 'whatsapp' | 'viber' | 'zalo' | 'telegram';
}
/**
@@ -1106,7 +1101,11 @@ interface IConfigOptional {
builtin_apps: Record<string, string>;
/** Force the bundled GUI even in dev. Default: false. */
use_bundled_gui: boolean;
/** Override the GUI bundle JS path. Default: `/dist/bundle.min.js`. */
/**
* Override the GUI bundle JS path. Default: `/dist/bundle.min.js`. The
* `/embed/*` pages load `apps-embed.min.js` and `feedback-embed.min.js`
* from the same directory.
*/
gui_bundle: string;
/** Override the GUI CSS path when bundled. Default: `/dist/bundle.min.css`. */
gui_css: string;
@@ -1393,7 +1392,8 @@ export interface ServerDrainInfo {
}
export interface WithCostsReporting extends WithLifecycle {
getReportedCosts?: () => // eslint-disable-next-line @typescript-eslint/no-explicit-any
getReportedCosts?: () =>
// eslint-disable-next-line @typescript-eslint/no-explicit-any
| Promise<Record<string, any>[]>
// eslint-disable-next-line @typescript-eslint/no-explicit-any
| Record<string, any>[];
+10 -3
View File
@@ -37,6 +37,9 @@ const repoRoot = path.resolve(backendDir, '../..');
const isPgmockMode =
(process.env.PUTER_TEST_DB_ENGINE ?? '').toLowerCase() === 'postgres';
const pgmockTimeoutMs = 600_000;
// Loaded CI runners stall timers well past the 5 s / 10 s defaults; a real
// hang still fails, just later.
const ciTimeouts = { testTimeout: 20_000, hookTimeout: 60_000 };
// Tests that always boot pgmock regardless of PUTER_TEST_DB_ENGINE. Too slow
// for CI; run locally or via `npm run test:backend:postgres`.
@@ -103,9 +106,11 @@ export const lowerDecoratorsPlugin = {
loader: 'ts',
target: 'es2024',
sourcefile: id,
sourcemap: 'inline',
sourcemap: 'external',
});
return { code: result.code, map: null };
// Without the map, coverage and stack traces report esbuild's
// output lines instead of the source's.
return { code: result.code, map: result.map };
},
};
@@ -145,7 +150,9 @@ export default defineConfig(({ mode }) => ({
hookTimeout: pgmockTimeoutMs,
fileParallelism: false,
}
: {}),
: isCi
? ciTimeouts
: {}),
coverage: {
provider: 'v8',
reporter: isCi
+13 -5
View File
@@ -247,10 +247,10 @@ function generateTableOfContentsHTML (htmlContent, title) {
html += '<nav class="toc-nav">';
const cleanTitle = removeTags(title);
html += `<a href="#" class="toc-link toc-level-1" data-level="1">${cleanTitle}</a>`;
html += `<a href="#" class="toc-link toc-level-1" data-level="1">${breakAfterDots(cleanTitle)}</a>`;
for ( const heading of headings ) {
html += `<a href="#${heading.slug}" class="toc-link toc-level-${heading.level}" data-level="${heading.level}">${heading.text}</a>`;
html += `<a href="#${heading.slug}" class="toc-link toc-level-${heading.level}" data-level="${heading.level}">${breakAfterDots(heading.text)}</a>`;
}
html += '</nav>';
@@ -457,10 +457,12 @@ function generateDocsHTML (filePath, rootDir, page, isIndex = false) {
html += '</div>';
// content
html += `<div id="docs-content-${page.slug ?? ''}" class="docs-content col-xl-7 col-lg-7 col-md-12 col-sm-12 col-xs-12">`;
// context menu
// title, with the context menu beside it
const pageTitle = breakAfterDots(page.page_title ?? page.title);
html += '<div class="page-title-row">';
html += `<h1>${page.icon ? `<img src="/${baseURL}${page.icon}" style="opacity:0.5; width: 24px; height: 24px; margin-right: 10px;">` : '' }${pageTitle}</h1>`;
html += generateMenuHTML();
html += `<h1>${page.icon ? `<img src="/${baseURL}${page.icon}" style="opacity:0.5; width: 24px; height: 24px; margin-right: 10px;">` : '' }${page.page_title ?? page.title}</h1>`;
html += '</div>';
// Platform compatibility badges
html += generatePlatformCompatibilityHTML(frontMatter);
html += '<hr class="hr-inset">';
@@ -852,6 +854,12 @@ function removeTags (html) {
return html.replace(/<[^>]*>?/gm, '');
}
// Let a long title wrap after a dot, so `puter.auth.getDetailedAppUsage()`
// never splits inside the method name.
function breakAfterDots (html) {
return html.replace(/\.(?=\w)/g, '.<wbr>');
}
// Replace '/path/to/root-directory' with the path to your root directory
generateDocumentation('./src');
generateRedirects();
+8 -8
View File
@@ -194,18 +194,18 @@ Choose a model and compare provider rates in the [AI model directory](https://de
These AI features are supported out of the box when using Puter.js:
- **[`puter.ai.chat()`](/AI/chat/)** - Chat with AI models like Claude, GPT, and others
- **[`puter.ai.txt2img()`](/AI/txt2img/)** - Generate images from text descriptions
- **[`puter.ai.txt2speech()`](/AI/txt2speech/)** - Convert text to speech
- **[`puter.ai.speech2txt()`](/AI/speech2txt/)** - Transcribe audio recordings into text
- **[`puter.ai.img2txt()`](/AI/img2txt/)** - Extract text from images (OCR)
- **[`puter.ai.txt2vid()`](/AI/txt2vid/)** - Generate short video clips from text or a reference image with Wan, Seedance, Veo, Kling, MiniMax H3 and other models, or edit a video you supply with Gemini Omni, FLUX 3 or Kling Omni
- **[`puter.ai.speech2speech()`](/AI/speech2speech/)** - Convert speech in one voice to another voice
- **[`puter.ai.realtime()`](/AI/realtime/)** - Prepare a beta realtime conversation with optional text, microphone, playback, and interruption helpers
- **[Realtime WebSocket API](/AI/realtime-websocket/)** - Connect directly without puter.js. This API is in beta and may change abruptly.
- **[`puter.ai.listModels()`](/AI/listModels/)** - List available AI chat models (and providers) that Puter currently exposes.
- **[`puter.ai.listModelProviders()`](/AI/listModelProviders/)** - List the AI providers that Puter currently exposes.
- **[`puter.ai.txt2img()`](/AI/txt2img/)** - Generate images from text descriptions
- **[`puter.ai.img2txt()`](/AI/img2txt/)** - Extract text from images (OCR)
- **[`puter.ai.txt2speech()`](/AI/txt2speech/)** - Convert text to speech
- **[`puter.ai.txt2speech.listEngines()`](/AI/txt2speech.listEngines/)** - List available TTS engines/models
- **[`puter.ai.txt2speech.listVoices()`](/AI/txt2speech.listVoices/)** - List available TTS voices
- **[`puter.ai.speech2speech()`](/AI/speech2speech/)** - Convert speech in one voice to another voice
- **[`puter.ai.txt2vid()`](/AI/txt2vid/)** - Generate short video clips from text or a reference image with Wan, Seedance, Veo, Kling, MiniMax H3 and other models, or edit a video you supply with Gemini Omni, FLUX 3 or Kling Omni
- **[`puter.ai.speech2txt()`](/AI/speech2txt/)** - Transcribe audio recordings into text
- **[Realtime WebSocket API](/AI/realtime/)** - Connect directly without puter.js. This API is in beta and may change abruptly.
- **[`puter.ai.convo()`](/AI/convo/)** - Prepare a beta realtime conversation with optional text, microphone, playback, and interruption helpers
## Examples
+18 -18
View File
@@ -29,24 +29,24 @@ An object containing the following properties:
| Option | Type | Description |
|--------|------|-------------|
| `model` | String | The model you want to use for the completion. If not specified, defaults to `gpt-5.4-nano`. More than 500 models are available from providers including OpenAI, Anthropic, Google, Alibaba Cloud, xAI, Mistral, OpenRouter, Infron, and others. For a full list, see the [AI models list](https://developer.puter.com/ai/models/) page. |
| `stream` | Boolean | A boolean indicating whether you want to stream the completion. Defaults to `false`. |
| `max_tokens` | Number | The maximum number of tokens to generate in the completion. By default, the specific model's maximum is used. |
| `temperature` | Number | A number between 0 and 2 indicating the randomness of the completion. Lower values make the output more focused and deterministic, while higher values make it more random. By default, the model's own temperature is used. See [Model-specific features](#model-specific-features). |
| `reasoning_effort` / `reasoning.effort` | String | Controls how much effort reasoning models spend thinking. Supported values: `none`, `minimal`, `low`, `medium`, `high`, `xhigh`, and `max`. Lower values give faster responses with less reasoning. OpenAI models, Moonshot's Kimi K3.1 Pro models, Meta's Muse Spark models, `gemini-4-argon`, `gemini-3.1-flash-lite` and `gemini-3-flash-preview` only. See [Model-specific features](#model-specific-features). |
| `thinking` | Object \| null | Extended-thinking control: `{ type: "adaptive" \| "enabled" \| "disabled" \| "between_tools", budgetTokens?, display? }`. Pass `null` to send no thinking configuration at all (the model's own default); leaving it unset falls back to the legacy derivation from `reasoning_effort`. `budgetTokens` only applies to `type: "enabled"`. |
| `verbosity` / `text.verbosity` | String | Controls how long or short responses are. Supported values: `low`, `medium`, and `high`. Lower values give shorter responses. OpenAI models only. |
| `tools` | Array | Function definitions the AI can call. See [Function Calling](#function-calling) for details. |
| `toolChoice` | String \| Object | Which tool, if any, the model must call. Pass `"auto"` (the model decides), `"none"` (never call a tool), `"required"` (call at least one), or an object naming a specific tool: `{ type: "tool", name: "..." }`. Requires `tools`. |
| `parallelToolCalls` | Boolean | Whether the model may call more than one tool in a single turn. Left unset, tool calls run one at a time. |
| `streamToolInput` | Boolean | Streaming only. When `true`, a tool call's arguments arrive incrementally as `tool_use_start` / `tool_input_delta` chunks instead of a single `tool_use` chunk once the call completes. |
| `normalize` | Boolean | Controls the format of the non-streaming response. See [Response normalization](#response-normalization). |
| `compaction` | Boolean \| Object | Opt into inline context compaction for long conversations. See [Compaction](#compaction). |
| `signal` | AbortSignal | Abort the request, including while waiting for the next streamed chunk. Cancellation rejects with the signal reason (normally an `AbortError`). |
| `provider` | String | Pin the request to a specific provider, for example `openrouter` or `infron`. Without it, Puter selects a provider for the requested model. Call [`puter.ai.listModelProviders()`](/AI/listModelProviders) for the available values, and [`puter.ai.listModels(provider)`](/AI/listModels) for the models a given provider serves. See [Providers](#providers). |
| `fallback` | Boolean | Set to `false` to fail the request when the first provider tried fails, instead of retrying it on another provider that serves the same model. Defaults to `true`. See [Providers](#providers). |
| `outputFormat` | Object | Constrains the response to a JSON schema: `{ type: "json_schema", schema, name?, strict? }`. |
| `stopSequences` | Array of String | Up to the model's limit of strings; generation stops the moment one of them appears in the output. |
| `model` | `String` | The model you want to use for the completion. If not specified, defaults to `gpt-5.4-nano`. More than 500 models are available from providers including OpenAI, Anthropic, Google, Alibaba Cloud, xAI, Mistral, OpenRouter, Infron, and others. For a full list, see the [AI models list](https://developer.puter.com/ai/models/) page. |
| `stream` | `Boolean` | A boolean indicating whether you want to stream the completion. Defaults to `false`. |
| `max_tokens` | `Number` | The maximum number of tokens to generate in the completion. By default, the specific model's maximum is used. |
| `temperature` | `Number` | A number between 0 and 2 indicating the randomness of the completion. Lower values make the output more focused and deterministic, while higher values make it more random. By default, the model's own temperature is used. See [Model-specific features](#model-specific-features). |
| `reasoning_effort` / `reasoning.effort` | `String` | Controls how much effort reasoning models spend thinking. Supported values: `none`, `minimal`, `low`, `medium`, `high`, `xhigh`, and `max`. Lower values give faster responses with less reasoning. OpenAI models, Moonshot's Kimi K3.1 Pro models, Meta's Muse Spark models, `gemini-4-argon`, `gemini-3.1-flash-lite` and `gemini-3-flash-preview` only. See [Model-specific features](#model-specific-features). |
| `thinking` | `Object \| null` | Extended-thinking control: `{ type: "adaptive" \| "enabled" \| "disabled" \| "between_tools", budgetTokens?, display? }`. Pass `null` to send no thinking configuration at all (the model's own default); leaving it unset falls back to the legacy derivation from `reasoning_effort`. `budgetTokens` only applies to `type: "enabled"`. |
| `verbosity` / `text.verbosity` | `String` | Controls how long or short responses are. Supported values: `low`, `medium`, and `high`. Lower values give shorter responses. OpenAI models only. |
| `tools` | `Array` | Function definitions the AI can call. See [Function Calling](#function-calling) for details. |
| `toolChoice` | `String \| Object` | Which tool, if any, the model must call. Pass `"auto"` (the model decides), `"none"` (never call a tool), `"required"` (call at least one), or an object naming a specific tool: `{ type: "tool", name: "..." }`. Requires `tools`. |
| `parallelToolCalls` | `Boolean` | Whether the model may call more than one tool in a single turn. Left unset, tool calls run one at a time. |
| `streamToolInput` | `Boolean` | Streaming only. When `true`, a tool call's arguments arrive incrementally as `tool_use_start` / `tool_input_delta` chunks instead of a single `tool_use` chunk once the call completes. |
| `normalize` | `Boolean` | Controls the format of the non-streaming response. See [Response normalization](#response-normalization). |
| `compaction` | `Boolean \| Object` | Opt into inline context compaction for long conversations. See [Compaction](#compaction). |
| `signal` | `AbortSignal` | Abort the request, including while waiting for the next streamed chunk. Cancellation rejects with the signal reason (normally an `AbortError`). |
| `provider` | `String` | Pin the request to a specific provider, for example `openrouter` or `infron`. Without it, Puter selects a provider for the requested model. Call [`puter.ai.listModelProviders()`](/AI/listModelProviders) for the available values, and [`puter.ai.listModels(provider)`](/AI/listModels) for the models a given provider serves. See [Providers](#providers). |
| `fallback` | `Boolean` | Set to `false` to fail the request when the first provider tried fails, instead of retrying it on another provider that serves the same model. Defaults to `true`. See [Providers](#providers). |
| `outputFormat` | `Object` | Constrains the response to a JSON schema: `{ type: "json_schema", schema, name?, strict? }`. |
| `stopSequences` | `Array<String>` | Up to the model's limit of strings; generation stops the moment one of them appears in the output. |
Some models accept additional options or handle these options differently. See [Model-specific features](#model-specific-features).
-143
View File
@@ -1,143 +0,0 @@
---
title: puter.ai.convo()
description: Prepare an OpenAI realtime conversation with optional audio and text helpers.
platforms: [websites, apps, nodejs, workers]
---
The conversation API prepares a realtime session, verifies Puter sign-in, and lets you connect when your app is ready. Realtime conversations require a paid Puter plan; usage is billed to the signed-in user. Native OpenAI events and convenience methods use the same session. Microphone capture and speaker playback start when your app requests them.
In Node.js, the SDK requires a global `WebSocket`, available in Node.js 22 or later.
**Beta:** This API is incomplete. Its methods, options, events, and behavior may change abruptly, including breaking changes without notice.
To connect without puter.js, see the [Realtime WebSocket API](/AI/realtime/).
## Syntax
```js
const conversation = await puter.ai.convo(options = {});
await conversation.connect();
```
## Parameters
The options object accepts these fields.
| Field | Type | Default | Description |
| --- | --- | --- | --- |
| `model` | String | `gpt-realtime-2.1-mini` | Also accepts `gpt-realtime-2.1`, `gpt-realtime-2`, `gpt-realtime-1.5`, `gpt-realtime`, and `gpt-realtime-mini`. |
| `instructions` | String | Provider default | Session instructions, up to 8192 characters. |
| `output` | Array of Strings | `['audio']` | Accepts `['text']`, `['audio']`, or both. Audio includes a transcript. Requesting both uses audio output and emits transcript deltas through the `text` event. |
| `voice` | String | Provider default | OpenAI voice identifier, up to 128 characters. |
| `turnDetection` | Boolean | `true` | Whether the provider detects the end of spoken turns automatically. Set to `false` for manual audio commits. |
## Return value
A Promise resolves to a prepared conversation after options and sign-in are checked. In a browser, preparation opens the Puter sign-in prompt if needed. Preparation opens no realtime connection and requests no microphone access.
The conversation exposes these properties and methods.
| Member | Behavior |
| --- | --- |
| `state` | `prepared`, `connecting`, `connected`, or `closed`. |
| `model` | Resolved model name. |
| `connect()` | Opens the connection and applies settings. Resolves after the provider acknowledges session configuration. Concurrent calls share one connection Promise, including bounded retries for transient setup failures. Calling it while connected opens no additional connection. During a reconnection, it resolves when the reconnection succeeds and rejects if the conversation closes instead. |
| `configure(options)` | Updates the given session settings and resolves after the provider acknowledges this update. Settings it isn't given, including ones set through native events, are left alone. Accepts the factory options except `model`. One update can be pending at a time. Provider rules apply to changes such as switching a voice after audio has been generated. |
| `sendText(text)` | Adds a user message and requests a response. Text must be nonempty and at most 8192 characters. |
| `appendAudio(pcm)` | Appends an `Int16Array` containing PCM16, 24 kHz mono audio. A chunk contains at most 12000 samples. |
| `commitAudio()` | Commits buffered audio and requests a response. Requires turn detection to be off, through `turnDetection: false` or a native session update. The provider requires at least 100 ms of buffered audio. |
| `interrupt(position?)` | Stops built-in playback immediately and waits for cancellation and playback-history synchronization. A reply requested but not yet started is cancelled as soon as it starts. Custom players provide `{ itemId, contentIndex, playedMs }`. An idle call resolves immediately. Readiness failures reject the returned Promise with `session_not_ready` or `session_closed`. |
| `send(event)` | Sends a native OpenAI JSON event. |
| `on(type, handler)` | Registers a listener and returns an unsubscribe function. Use `'*'` to receive every native and convenience event. |
| `off(type, handler)` | Removes a listener. |
| `close()` | Closes the session, rejects pending operations, and releases SDK-owned capture and playback resources. Repeated calls have no additional effect. |
Attach listeners before connecting to receive initial session events. Closing during connection rejects the pending attempt.
If the connection drops because of network loss, a server restart or a provider error, the conversation reconnects on its own. Normal closes with code 1000 end the conversation. While it reconnects, `state` is `connecting`, a `reconnecting` event fires, and pending operations reject with `connection_lost`. The new session gets every setting the provider acknowledged, from the factory options, `configure()` and native `session.update` events. Then `ready` fires again with `reconnected: true`. Listeners, the microphone and the speaker carry over. Microphone audio captured while reconnecting is dropped.
The conversation also restores recent context. Before `ready` fires, it adds back up to 40 of the most recent conversation items, 48 KiB in total. Restored items are user text, user speech that has a transcript, assistant replies as text, and function calls with their outputs. User speech has a transcript only when input transcription is configured through native session settings. An assistant reply that was interrupted, or still playing when the connection dropped, is cut to what the user saw or heard. The cut is estimated from how much of the audio played, so it can be off by a few words. Images, speech without a transcript, deleted items, and replies still generating when the connection dropped are left out. Restored items get new item IDs, don't fire item events, and count as input tokens on the next response. Item IDs from before the reconnect don't work in later events. Restoration uses a contiguous suffix of restorable items. An oversized newest item leaves that suffix empty. Older items left out to fit the window fire a `context_trimmed` event with the count in `omittedItems`; this is routine and not an error. A provider refusal or a failure to send the restored items fires one `error` event with code `context_restore_failed` per restoration. In both cases the conversation stays connected. Items are preserved without truncating text, function arguments or function results.
When Puter knows ahead of time that the server a session runs on will restart, it sends a `puter.reconnect` event, which also reaches your listeners. Without that notice, a restart drops the connection and the conversation reconnects as above. Within a few seconds, the conversation opens a replacement session in the background while the current one keeps working. It switches once no reply is generating or playing, no user turn is being spoken or transcribed, no function call is waiting for its output, and nothing you sent is waiting on the provider. The switch goes through the same steps as a reconnect, and the `reconnecting` event has code 1012. If the replacement can't open yet, the conversation keeps the current session and tries again later. A refusal that retrying can't fix, such as `insufficient_funds`, stops the attempts. If the server closes the session first, the conversation switches to the replacement, or reconnects if none is open.
The conversation makes up to ten attempts over about a minute. In a browser that reports being offline, it first waits up to two minutes for the connection to come back. If every attempt fails, or the server refuses with an error such as `insufficient_funds`, the conversation closes. A closed conversation cannot reconnect. To start another session, prepare a new one.
Native event definitions are listed in the [OpenAI realtime reference](https://developers.openai.com/api/reference/resources/realtime/server-events). Native events retain their provider fields. Sending native events preserves direct control of the session. Puter refuses `conversation.item.retrieve` events and MCP tools (`"type": "mcp"`) in `session.update` and `response.create` events. Sending one fires an `error` event with code `invalid_event`, and the conversation closes with code 1008. Audio helpers expect the session to use PCM16 at 24 kHz.
## Convenience events
The conversation emits these events alongside native events.
| Event | Fields |
| --- | --- |
| `ready` | `model`, `provider`, and `reconnected: true` after a reconnection |
| `reconnecting` | `code`, `reason` of the dropped connection. After a `puter.reconnect` event, `code` is 1012. |
| `context_trimmed` | `omittedItems`, the number of restorable items left out of the restored context after a reconnection. Fires before `ready`. |
| `text` | `delta`, `responseId` |
| `transcript` | `role`, `text`, `final`. Assistant deltas use `final: false`. Completed assistant and user transcripts use `final: true`. User transcripts require transcription to be configured through native session settings. |
| `audio` | `pcm`, `sampleRate`, `responseId`, `itemId`, `contentIndex`. The PCM chunk is an `Int16Array`. |
| `interrupted` | `source` (`manual` or `speech`), `responseId` |
| `turn.done` | `responseId`, native provider `usage`, `status` |
| `close` | `code`, `reason` |
Each event includes its `type`. When the provider event leaves out an ID, `responseId` and `itemId` are empty strings and `contentIndex` is `0`. The `interrupted` event signals local interruption immediately. Its corresponding operation resolves after the provider acknowledges cancellation and any requested truncation. Late audio from a canceled response remains visible as native events and is excluded from convenience audio and built-in playback.
## Browser media
The optional microphone and speaker helpers require a browser with Web Audio support. Microphone capture also requires media permissions and a secure context. Start audio from a user action so the browser can allow playback.
| Member | Behavior |
| --- | --- |
| `microphone.start()` | Requests microphone access and streams PCM16, resampled to 24 kHz, in 20 ms chunks through an AudioWorklet. If the page or network falls behind, chunks are dropped rather than stopping capture. |
| `microphone.mute()` | Disables capture tracks and stops forwarding captured chunks. |
| `microphone.unmute()` | Enables capture tracks and forwarding. |
| `microphone.stop()` | Stops capture tracks and releases capture resources. A `start()` still waiting on the permission prompt rejects with `session_closed`. |
| `speaker.start({ bargeIn: true })` | Starts playback. Barge-in defaults to `true`. With barge-in enabled, provider speech-start events interrupt playback and synchronize played audio with conversation history. Starting the speaker requests no microphone access. |
| `speaker.stop()` | Clears playback and releases its audio context. |
Both start methods require a connected session. Capture and playback are independent, so custom audio input can use the built-in speaker, and built-in capture can use custom playback.
## Errors and limits
Failures use objects containing `code` and `message`. Preparation can reject with `invalid_argument`, `model_not_found`, `auth_required`, `auth_canceled`, or `auth_failed`. Connection can reject with `subscription_required` or `insufficient_funds`, which also show the Puter upgrade prompt. Connection and asynchronous operations can reject with provider errors, `session_closed`, `connection_lost`, `operation_timeout`, or `operation_in_progress`. Sending before readiness, or while reconnecting, throws `session_not_ready`.
Invalid input throws `invalid_argument`, `invalid_event`, or `input_too_large`. A full SDK send queue throws `queue_full`. Media helpers report `unsupported_environment`, `permission_denied`, `media_error`, `media_timeout`, or `queue_full`. Runtime media errors and `context_restore_failed` arrive through the `error` event. Provider errors also arrive as native `error` events with a nested `error` object.
Each native event is capped at 64 KiB. The SDK bounds JSON traversal, outgoing queues, acknowledgment waits, microphone work, and playback. All numeric limits are listed on [rate limits and quotas](/rate-limits-and-quotas/).
## Examples
A text conversation uses convenience methods for input and streamed output.
```js
const conversation = await puter.ai.convo({
output: ['text'],
instructions: 'Keep replies short.',
});
conversation.on('text', ({ delta }) => console.log(delta));
conversation.on('turn.done', () => conversation.close());
conversation.on('error', (event) => console.error(event));
await conversation.connect();
conversation.sendText('Say hello in three words.');
```
A voice conversation enables the microphone and speaker after connection.
```js
const conversation = await puter.ai.convo();
conversation.on('transcript', ({ role, text }) => console.log(role, text));
conversation.on('error', (event) => console.error(event));
await conversation.connect();
await conversation.speaker.start();
await conversation.microphone.start();
// To interrupt a response and submit a replacement text turn:
await conversation.interrupt();
conversation.sendText('Actually, make it Wednesday.');
// When the user ends the conversation:
conversation.close();
```
+2
View File
@@ -22,6 +22,8 @@ A `Promise` that will resolve to an array of string containing each AI providers
## Examples
### List all model providers
```html;ai-list-model-providers
<html>
<body>
+6 -2
View File
@@ -43,13 +43,15 @@ Example model entry:
]
```
<div class="info">Successful results are cached for 60 seconds per provider.</div>
## Errors
Network and server failures reject the promise; they do not resolve to an empty
catalogue. Network failures use `{ message, code: "network_error" }`, invalid
catalogue responses use `invalid_response`, idle timeouts use `request_timeout`,
and server errors pass through unchanged.
<div class="info">Successful results are cached for 60 seconds per provider.</div>
## Model variants
Some models have variants. A variant is the same model with a different price, rate limit, or speed. The variant is a suffix on the model ID, separated by a colon.
@@ -64,6 +66,8 @@ The model ID without a suffix is the standard variant. Not every model has varia
## Examples
### List all models
```html;ai-list-models
<html>
<body>
+126
View File
@@ -0,0 +1,126 @@
---
title: Realtime WebSocket API (Beta)
description: Connect to OpenAI realtime conversations through Puter without puter.js.
platforms: [websites, apps, nodejs, workers]
---
The Realtime WebSocket API lets your client send and receive native OpenAI realtime JSON events through Puter.
Puter authenticates the user and charges their account for usage.
**Beta:** This API is incomplete. Its methods, options, events, and behavior may change abruptly, including breaking changes without notice.
For optional text, microphone, playback, and interruption helpers, use [`puter.ai.realtime()`](/AI/realtime/).
## Connection and authentication
Connect to this URL on the Puter API host:
```text
wss://api.puter.com/puterai/openai/v1/realtime?model=gpt-realtime-2.1-mini
```
The `model` query parameter defaults to `gpt-realtime-2.1-mini`. The model is fixed for the connection. A session update that changes it is rejected. It also accepts `gpt-realtime-2.1`, `gpt-realtime-2`, `gpt-realtime-1.5`, `gpt-realtime`, and `gpt-realtime-mini`.
Authenticate with a Puter session, app, or full-access API token. Puter supplies the provider credential. Server clients pass this header:
```text
Authorization: Bearer <PUTER_TOKEN>
```
Browser WebSocket clients pass `realtime` and `openai-insecure-api-key.<PUTER_TOKEN>` as subprotocols. The server echoes only `realtime`. The endpoint also accepts an `auth_token` query parameter. Prefer the authorization header where supported because URLs and subprotocols can appear in logs. Authentication takes precedence in this order, header, subprotocol, then query parameter.
The socket can open before authentication and provider setup finish. Listen for errors and closure immediately. Wait for `session.created`, send your session settings, then wait for `session.updated` before submitting a turn.
To open a replacement while another connection remains healthy, set the optional `purpose=handover` query parameter. These attempts share a smaller per-credential budget, checked before the general connection-attempt budget. Initial connections and dropped-connection recovery use the URL without this parameter. The limits are listed in [rate limits and quotas](/rate-limits-and-quotas/).
## Text example
Install the `ws` package and set `PUTER_TOKEN` to your Puter token. Run this example as a Node.js ES module:
```js
import WebSocket from 'ws';
const socket = new WebSocket(
'wss://api.puter.com/puterai/openai/v1/realtime?model=gpt-realtime-2.1-mini',
{ headers: { Authorization: `Bearer ${process.env.PUTER_TOKEN}` } },
);
const send = (event) => socket.send(JSON.stringify(event));
socket.on('message', (data) => {
const event = JSON.parse(data.toString());
if (event.type === 'session.created') {
send({
type: 'session.update',
session: {
type: 'realtime',
output_modalities: ['text'],
instructions: 'Keep replies short.',
},
});
}
if (event.type === 'session.updated') {
send({
type: 'conversation.item.create',
item: {
type: 'message',
role: 'user',
content: [{ type: 'input_text', text: 'Hello!' }],
},
});
send({ type: 'response.create' });
}
if (event.type === 'response.output_text.delta')
process.stdout.write(event.delta);
if (event.type === 'error')
console.error(event.error);
if (event.type === 'response.done')
socket.close();
});
socket.on('error', console.error);
socket.on('close', (code, reason) => console.log(code, reason.toString()));
```
## Events, audio, and interruption
Each message contains one JSON object with a nonempty string `type` of at most 128 characters. Binary messages are rejected. Native events retain their provider fields. The endpoint doesn't deliver `rate_limits.updated`, which describes Puter's provider account rather than yours, and it removes provider organization IDs from error messages. The endpoint exposes the WebSocket event protocol. Your client manages capture, playback, acknowledgments, and timeouts.
The endpoint refuses `conversation.item.retrieve` events and MCP tools (`"type": "mcp"`) in `session.update` and `response.create` events. A refused event isn't sent to the provider. The session gets an `invalid_event` error and closes with 1008.
PCM16 audio configured at 24 kHz mono is sent as base64 chunks in `input_audio_buffer.append` events. Output arrives in `response.output_audio.delta` events. With manual turn detection, commit buffered input with `input_audio_buffer.commit`, then request a reply with `response.create`.
To interrupt, stop local playback immediately and send `response.cancel` with the active `response_id`. If some generated audio was not played, send `conversation.item.truncate` with its `item_id`, `content_index`, and `audio_end_ms` set to the amount actually played. Wait for `response.done` and any requested `conversation.item.truncated` acknowledgment before submitting a replacement turn.
Connection loss ends the session. Reconnecting creates a new conversation. Tool execution and automatic reconnection belong to your client.
## Server restarts
When Puter knows ahead of time that the server a session runs on will restart, it sends each open session this event, at most once a minute:
```json
{
"type": "puter.reconnect",
"event_id": "event_puter_1767225600000",
"reason": "server_restarting",
"close_in_ms": 90000
}
```
The `reason` field is `server_restarting`. The `close_in_ms` field, when present, is about how long until the server closes the session itself. The session keeps working until then. Open a new connection after a short, randomized delay, and once it gets `session.created` and your client is idle, with no response generating and no user turn in progress, move to it and close the old one. A connection that reaches a server that is also restarting gets a `server_restarting` error and closes with 1012. In that case keep the old session and try again after a short, randomized delay. If the server closes the old session first, the close code is 1012, and your client reconnects the same way. A restart can also drop the connection without any notice, so treat an unexpected close the same way.
A new connection starts an empty conversation. To keep context, add earlier items back with `conversation.item.create` before you request a response. Event types that start with `puter.` come from Puter, not the provider.
## Errors, billing, and limits
API errors arrive as `{ "type": "error", "error": { "code": "...", "message": "..." } }`. Handle socket errors and close frames too. Invalid, missing, or revoked credentials use `invalid_api_key`. If Puter can't check a credential or the account's plan, the error is `internal_error` and the session closes with 1011, so try again after a short, randomized delay. Other relay codes include `permission_denied`, `model_not_found`, `insufficient_funds`, `subscription_required`, `rate_limit_exceeded`, `invalid_event`, `connection_timeout`, `provider_unavailable`, `upstream_error`, and `server_restarting`.
Policy failures generally close with 1008, oversized client messages with 1009, upstream or setup failures with 1011, server restarts with 1012, and temporary server overload with 1013. Reconnect after 1011, 1012, or 1013. Authentication and model failures can arrive after the WebSocket handshake succeeds.
The endpoint requires a paid Puter plan. Usage is charged after completed responses and input transcriptions. While a response generates, part of your balance is held for it, so a session opens only if your balance covers one response. If the provider connection closes before a response reports its usage, the response is charged the full amount held for it. Each account can open 20 sessions at once by default. Each JSON message you send is limited to 64 KiB, including reassembled fragments. Messages from the provider can be up to 4 MiB. Stream audio in small chunks. All message rates, queue caps, timeouts, and other bounds are published in [rate limits and quotas](/rate-limits-and-quotas/).
Input transcription holds a small amount of your balance per transcribed item, priced at the transcription model you select. Two items are reserved ahead of your audio and replenished as the provider commits them, so a session holds only its spare items plus the items still awaiting a transcript. Changing the transcription model reprices the spare items. If your balance can't cover another item, audio waits while earlier items settle; once none are left to settle, the session closes with `insufficient_funds`. Failed transcriptions, items without final usage, and audio whose commit the provider never acknowledges before the connection closes are each charged that model's fixed per-item amount. Unacknowledged audio is charged one item per started 160 seconds. With server turn detection, only detected speech counts, so silence is never charged. The amounts, timeout and audio limits are listed in [rate limits and quotas](/rate-limits-and-quotas/).
Provider-reported realtime models must have a known price. A missing model uses the last known model. An explicitly unpriced model closes the connection with `upstream_error`.
After recording usage, the connection can continue while settled credit is positive, including a fractional balance. Each new billable operation still needs its full reservation after accounting for other outstanding holds.
+129 -102
View File
@@ -1,124 +1,151 @@
---
title: Realtime WebSocket API (Beta)
description: Connect to OpenAI realtime conversations through Puter without puter.js.
title: puter.ai.realtime()
description: Prepare an OpenAI realtime conversation with optional audio and text helpers.
platforms: [websites, apps, nodejs, workers]
---
The Realtime WebSocket API lets your client send and receive native OpenAI realtime JSON events through Puter. Puter authenticates the user and charges their account for usage.
Prepares a realtime OpenAI conversation that your app can connect to when it's ready.
Preparing the conversation verifies Puter sign-in. Realtime conversations require a paid Puter plan, and usage is billed to the signed-in user. Native OpenAI events and convenience methods use the same session. Microphone capture and speaker playback start when your app requests them.
In Node.js, the SDK requires a global `WebSocket`, available in Node.js 22 or later.
**Beta:** This API is incomplete. Its methods, options, events, and behavior may change abruptly, including breaking changes without notice.
For optional text, microphone, playback, and interruption helpers, use [`puter.ai.convo()`](/AI/convo/).
To connect without puter.js, see the [Realtime WebSocket API](/AI/realtime-websocket/).
## Connection and authentication
Connect to this URL on the Puter API host:
```text
wss://api.puter.com/puterai/openai/v1/realtime?model=gpt-realtime-2.1-mini
```
The `model` query parameter defaults to `gpt-realtime-2.1-mini`. The model is fixed for the connection. A session update that changes it is rejected. It also accepts `gpt-realtime-2.1`, `gpt-realtime-2`, `gpt-realtime-1.5`, `gpt-realtime`, and `gpt-realtime-mini`.
Authenticate with a Puter session, app, or full-access API token. Puter supplies the provider credential. Server clients pass this header:
```text
Authorization: Bearer <PUTER_TOKEN>
```
Browser WebSocket clients pass `realtime` and `openai-insecure-api-key.<PUTER_TOKEN>` as subprotocols. The server echoes only `realtime`. The endpoint also accepts an `auth_token` query parameter. Prefer the authorization header where supported because URLs and subprotocols can appear in logs. Authentication takes precedence in this order, header, subprotocol, then query parameter.
The socket can open before authentication and provider setup finish. Listen for errors and closure immediately. Wait for `session.created`, send your session settings, then wait for `session.updated` before submitting a turn.
To open a replacement while another connection remains healthy, set the optional `purpose=handover` query parameter. These attempts share a smaller per-credential budget, checked before the general connection-attempt budget. Initial connections and dropped-connection recovery use the URL without this parameter. The limits are listed in [rate limits and quotas](/rate-limits-and-quotas/).
## Text example
Install the `ws` package and set `PUTER_TOKEN` to your Puter token. Run this example as a Node.js ES module:
## Syntax
```js
import WebSocket from 'ws';
const conversation = await puter.ai.realtime(options = {});
await conversation.connect();
```
const socket = new WebSocket(
'wss://api.puter.com/puterai/openai/v1/realtime?model=gpt-realtime-2.1-mini',
{ headers: { Authorization: `Bearer ${process.env.PUTER_TOKEN}` } },
);
const send = (event) => socket.send(JSON.stringify(event));
## Parameters
socket.on('message', (data) => {
const event = JSON.parse(data.toString());
#### `options` (Object) (Optional)
if (event.type === 'session.created') {
send({
type: 'session.update',
session: {
type: 'realtime',
output_modalities: ['text'],
instructions: 'Keep replies short.',
},
});
}
if (event.type === 'session.updated') {
send({
type: 'conversation.item.create',
item: {
type: 'message',
role: 'user',
content: [{ type: 'input_text', text: 'Hello!' }],
},
});
send({ type: 'response.create' });
}
if (event.type === 'response.output_text.delta')
process.stdout.write(event.delta);
if (event.type === 'error')
console.error(event.error);
if (event.type === 'response.done')
socket.close();
The options object accepts these fields.
| Option | Type | Description |
|--------|------|-------------|
| `model` | `String` | The realtime model. Defaults to `gpt-realtime-2.1-mini`. Also accepts `gpt-realtime-2.1`, `gpt-realtime-2`, `gpt-realtime-1.5`, `gpt-realtime`, and `gpt-realtime-mini`. |
| `instructions` | `String` | Session instructions, up to 8192 characters. Defaults to the provider's default. |
| `output` | `Array<String>` | Accepts `['text']`, `['audio']`, or both. Defaults to `['audio']`. Audio includes a transcript. Requesting both uses audio output and emits transcript deltas through the `text` event. |
| `voice` | `String` | OpenAI voice identifier, up to 128 characters. Defaults to the provider's default. |
| `turnDetection` | `Boolean` | Whether the provider detects the end of spoken turns automatically. Defaults to `true`. Set to `false` for manual audio commits. |
## Return value
A Promise resolves to a prepared conversation after options and sign-in are checked. In a browser, preparation opens the Puter sign-in prompt if needed. Preparation opens no realtime connection and requests no microphone access.
The conversation exposes these properties and methods.
| Member | Behavior |
| --- | --- |
| `state` | `prepared`, `connecting`, `connected`, or `closed`. |
| `model` | Resolved model name. |
| `connect()` | Opens the connection and applies settings. Resolves after the provider acknowledges session configuration. Concurrent calls share one connection Promise, including bounded retries for transient setup failures. Calling it while connected opens no additional connection. During a reconnection, it resolves when the reconnection succeeds and rejects if the conversation closes instead. |
| `configure(options)` | Updates the given session settings and resolves after the provider acknowledges this update. Settings it isn't given, including ones set through native events, are left alone. Accepts the factory options except `model`. One update can be pending at a time. Provider rules apply to changes such as switching a voice after audio has been generated. |
| `sendText(text)` | Adds a user message and requests a response. Text must be nonempty and at most 8192 characters. |
| `appendAudio(pcm)` | Appends an `Int16Array` containing PCM16, 24 kHz mono audio. A chunk contains at most 12000 samples. |
| `commitAudio()` | Commits buffered audio and requests a response. Requires turn detection to be off, through `turnDetection: false` or a native session update. The provider requires at least 100 ms of buffered audio. |
| `interrupt(position?)` | Stops built-in playback immediately and waits for cancellation and playback-history synchronization. A reply requested but not yet started is cancelled as soon as it starts. Custom players provide `{ itemId, contentIndex, playedMs }`. An idle call resolves immediately. Readiness failures reject the returned Promise with `session_not_ready` or `session_closed`. |
| `send(event)` | Sends a native OpenAI JSON event. |
| `on(type, handler)` | Registers a listener and returns an unsubscribe function. Use `'*'` to receive every native and convenience event. |
| `off(type, handler)` | Removes a listener. |
| `close()` | Closes the session, rejects pending operations, and releases SDK-owned capture and playback resources. Repeated calls have no additional effect. |
Attach listeners before connecting to receive initial session events. Closing during connection rejects the pending attempt.
If the connection drops because of network loss, a server restart or a provider error, the conversation reconnects on its own. Normal closes with code 1000 end the conversation. While it reconnects, `state` is `connecting`, a `reconnecting` event fires, and pending operations reject with `connection_lost`. The new session gets every setting the provider acknowledged, from the factory options, `configure()` and native `session.update` events. Then `ready` fires again with `reconnected: true`. Listeners, the microphone and the speaker carry over. Microphone audio captured while reconnecting is dropped.
The conversation also restores recent context. Before `ready` fires, it adds back up to 40 of the most recent conversation items, 48 KiB in total. Restored items are user text, user speech that has a transcript, assistant replies as text, and function calls with their outputs. User speech has a transcript only when input transcription is configured through native session settings. An assistant reply that was interrupted, or still playing when the connection dropped, is cut to what the user saw or heard. The cut is estimated from how much of the audio played, so it can be off by a few words. Images, speech without a transcript, deleted items, and replies still generating when the connection dropped are left out. Restored items get new item IDs, don't fire item events, and count as input tokens on the next response. Item IDs from before the reconnect don't work in later events. Restoration uses a contiguous suffix of restorable items. An oversized newest item leaves that suffix empty. Older items left out to fit the window fire a `context_trimmed` event with the count in `omittedItems`; this is routine and not an error. A provider refusal or a failure to send the restored items fires one `error` event with code `context_restore_failed` per restoration. In both cases the conversation stays connected. Items are preserved without truncating text, function arguments or function results.
When Puter knows ahead of time that the server a session runs on will restart, it sends a `puter.reconnect` event, which also reaches your listeners. Without that notice, a restart drops the connection and the conversation reconnects as above. Within a few seconds, the conversation opens a replacement session in the background while the current one keeps working. It switches once no reply is generating or playing, no user turn is being spoken or transcribed, no function call is waiting for its output, and nothing you sent is waiting on the provider. The switch goes through the same steps as a reconnect, and the `reconnecting` event has code 1012. If the replacement can't open yet, the conversation keeps the current session and tries again later. A refusal that retrying can't fix, such as `insufficient_funds`, stops the attempts. If the server closes the session first, the conversation switches to the replacement, or reconnects if none is open.
The conversation makes up to ten attempts over about a minute. In a browser that reports being offline, it first waits up to two minutes for the connection to come back. If every attempt fails, or the server refuses with an error such as `insufficient_funds`, the conversation closes. A closed conversation cannot reconnect. To start another session, prepare a new one.
Native event definitions are listed in the [OpenAI realtime reference](https://developers.openai.com/api/reference/resources/realtime/server-events). Native events retain their provider fields. Sending native events preserves direct control of the session. Puter refuses `conversation.item.retrieve` events and MCP tools (`"type": "mcp"`) in `session.update` and `response.create` events. Sending one fires an `error` event with code `invalid_event`, and the conversation closes with code 1008. Audio helpers expect the session to use PCM16 at 24 kHz.
## Errors and limits
Failures use objects containing `code` and `message`. Preparation can reject with `invalid_argument`, `model_not_found`, `auth_required`, `auth_canceled`, or `auth_failed`. Connection can reject with `subscription_required` or `insufficient_funds`, which also show the Puter upgrade prompt. Connection and asynchronous operations can reject with provider errors, `session_closed`, `connection_lost`, `operation_timeout`, or `operation_in_progress`. Sending before readiness, or while reconnecting, throws `session_not_ready`.
Invalid input throws `invalid_argument`, `invalid_event`, or `input_too_large`. A full SDK send queue throws `queue_full`. Media helpers report `unsupported_environment`, `permission_denied`, `media_error`, `media_timeout`, or `queue_full`. Runtime media errors and `context_restore_failed` arrive through the `error` event. Provider errors also arrive as native `error` events with a nested `error` object.
Each native event is capped at 64 KiB. The SDK bounds JSON traversal, outgoing queues, acknowledgment waits, microphone work, and playback. All numeric limits are listed on [rate limits and quotas](/rate-limits-and-quotas/).
## Convenience events
The conversation emits these events alongside native events.
| Event | Fields |
| --- | --- |
| `ready` | `model`, `provider`, and `reconnected: true` after a reconnection |
| `reconnecting` | `code`, `reason` of the dropped connection. After a `puter.reconnect` event, `code` is 1012. |
| `context_trimmed` | `omittedItems`, the number of restorable items left out of the restored context after a reconnection. Fires before `ready`. |
| `text` | `delta`, `responseId` |
| `transcript` | `role`, `text`, `final`. Assistant deltas use `final: false`. Completed assistant and user transcripts use `final: true`. User transcripts require transcription to be configured through native session settings. |
| `audio` | `pcm`, `sampleRate`, `responseId`, `itemId`, `contentIndex`. The PCM chunk is an `Int16Array`. |
| `interrupted` | `source` (`manual` or `speech`), `responseId` |
| `turn.done` | `responseId`, native provider `usage`, `status` |
| `close` | `code`, `reason` |
Each event includes its `type`. When the provider event leaves out an ID, `responseId` and `itemId` are empty strings and `contentIndex` is `0`. The `interrupted` event signals local interruption immediately. Its corresponding operation resolves after the provider acknowledges cancellation and any requested truncation. Late audio from a canceled response remains visible as native events and is excluded from convenience audio and built-in playback.
## Browser media
The optional microphone and speaker helpers require a browser with Web Audio support. Microphone capture also requires media permissions and a secure context. Start audio from a user action so the browser can allow playback.
| Member | Behavior |
| --- | --- |
| `microphone.start()` | Requests microphone access and streams PCM16, resampled to 24 kHz, in 20 ms chunks through an AudioWorklet. If the page or network falls behind, chunks are dropped rather than stopping capture. |
| `microphone.mute()` | Disables capture tracks and stops forwarding captured chunks. |
| `microphone.unmute()` | Enables capture tracks and forwarding. |
| `microphone.stop()` | Stops capture tracks and releases capture resources. A `start()` still waiting on the permission prompt rejects with `session_closed`. |
| `speaker.start({ bargeIn: true })` | Starts playback. Barge-in defaults to `true`. With barge-in enabled, provider speech-start events interrupt playback and synchronize played audio with conversation history. Starting the speaker requests no microphone access. |
| `speaker.stop()` | Clears playback and releases its audio context. |
Both start methods require a connected session. Capture and playback are independent, so custom audio input can use the built-in speaker, and built-in capture can use custom playback.
## Examples
### Have a text conversation
A text conversation uses convenience methods for input and streamed output.
```js
const conversation = await puter.ai.realtime({
output: ['text'],
instructions: 'Keep replies short.',
});
socket.on('error', console.error);
socket.on('close', (code, reason) => console.log(code, reason.toString()));
conversation.on('text', ({ delta }) => console.log(delta));
conversation.on('turn.done', () => conversation.close());
conversation.on('error', (event) => console.error(event));
await conversation.connect();
conversation.sendText('Say hello in three words.');
```
## Events, audio, and interruption
### Have a voice conversation
Each message contains one JSON object with a nonempty string `type` of at most 128 characters. Binary messages are rejected. Native events retain their provider fields. The endpoint doesn't deliver `rate_limits.updated`, which describes Puter's provider account rather than yours, and it removes provider organization IDs from error messages. The endpoint exposes the WebSocket event protocol. Your client manages capture, playback, acknowledgments, and timeouts.
A voice conversation enables the microphone and speaker after connection.
The endpoint refuses `conversation.item.retrieve` events and MCP tools (`"type": "mcp"`) in `session.update` and `response.create` events. A refused event isn't sent to the provider. The session gets an `invalid_event` error and closes with 1008.
```js
const conversation = await puter.ai.realtime();
conversation.on('transcript', ({ role, text }) => console.log(role, text));
conversation.on('error', (event) => console.error(event));
PCM16 audio configured at 24 kHz mono is sent as base64 chunks in `input_audio_buffer.append` events. Output arrives in `response.output_audio.delta` events. With manual turn detection, commit buffered input with `input_audio_buffer.commit`, then request a reply with `response.create`.
await conversation.connect();
await conversation.speaker.start();
await conversation.microphone.start();
To interrupt, stop local playback immediately and send `response.cancel` with the active `response_id`. If some generated audio was not played, send `conversation.item.truncate` with its `item_id`, `content_index`, and `audio_end_ms` set to the amount actually played. Wait for `response.done` and any requested `conversation.item.truncated` acknowledgment before submitting a replacement turn.
// To interrupt a response and submit a replacement text turn:
await conversation.interrupt();
conversation.sendText('Actually, make it Wednesday.');
Connection loss ends the session. Reconnecting creates a new conversation. Tool execution and automatic reconnection belong to your client.
## Server restarts
When Puter knows ahead of time that the server a session runs on will restart, it sends each open session this event, at most once a minute:
```json
{
"type": "puter.reconnect",
"event_id": "event_puter_1767225600000",
"reason": "server_restarting",
"close_in_ms": 90000
}
// When the user ends the conversation:
conversation.close();
```
The `reason` field is `server_restarting`. The `close_in_ms` field, when present, is about how long until the server closes the session itself. The session keeps working until then. Open a new connection after a short, randomized delay, and once it gets `session.created` and your client is idle, with no response generating and no user turn in progress, move to it and close the old one. A connection that reaches a server that is also restarting gets a `server_restarting` error and closes with 1012. In that case keep the old session and try again after a short, randomized delay. If the server closes the old session first, the close code is 1012, and your client reconnects the same way. A restart can also drop the connection without any notice, so treat an unexpected close the same way.
A new connection starts an empty conversation. To keep context, add earlier items back with `conversation.item.create` before you request a response. Event types that start with `puter.` come from Puter, not the provider.
## Errors, billing, and limits
API errors arrive as `{ "type": "error", "error": { "code": "...", "message": "..." } }`. Handle socket errors and close frames too. Invalid, missing, or revoked credentials use `invalid_api_key`. If Puter can't check a credential or the account's plan, the error is `internal_error` and the session closes with 1011, so try again after a short, randomized delay. Other relay codes include `permission_denied`, `model_not_found`, `insufficient_funds`, `subscription_required`, `rate_limit_exceeded`, `invalid_event`, `connection_timeout`, `provider_unavailable`, `upstream_error`, and `server_restarting`.
Policy failures generally close with 1008, oversized client messages with 1009, upstream or setup failures with 1011, server restarts with 1012, and temporary server overload with 1013. Reconnect after 1011, 1012, or 1013. Authentication and model failures can arrive after the WebSocket handshake succeeds.
The endpoint requires a paid Puter plan. Usage is charged after completed responses and input transcriptions. While a response generates, part of your balance is held for it, so a session opens only if your balance covers one response. If the provider connection closes before a response reports its usage, the response is charged the full amount held for it. Each account can open 20 sessions at once by default. Each JSON message you send is limited to 64 KiB, including reassembled fragments. Messages from the provider can be up to 4 MiB. Stream audio in small chunks. All message rates, queue caps, timeouts, and other bounds are published in [rate limits and quotas](/rate-limits-and-quotas/).
Input transcription holds a small amount of your balance per transcribed item, priced at the transcription model you select. Two items are reserved ahead of your audio and replenished as the provider commits them, so a session holds only its spare items plus the items still awaiting a transcript. Changing the transcription model reprices the spare items. If your balance can't cover another item, audio waits while earlier items settle; once none are left to settle, the session closes with `insufficient_funds`. Failed transcriptions, items without final usage, and audio whose commit the provider never acknowledges before the connection closes are each charged that model's fixed per-item amount. Unacknowledged audio is charged one item per started 160 seconds. With server turn detection, only detected speech counts, so silence is never charged. The amounts, timeout and audio limits are listed in [rate limits and quotas](/rate-limits-and-quotas/).
Provider-reported realtime models must have a known price. A missing model uses the last known model. An explicitly unpriced model closes the connection with `upstream_error`.
After recording usage, the connection can continue while settled credit is positive, including a fractional balance. Each new billable operation still needs its full reservation after accounting for other outstanding holds.
+2 -2
View File
@@ -54,7 +54,7 @@ Example response:
## Examples
<strong class="example-title">List engines for a specific provider</strong>
### List engines for a specific provider
```html;ai-txt2speech-list-engines
<html>
@@ -73,7 +73,7 @@ Example response:
</html>
```
<strong class="example-title">List engines using options object</strong>
### List engines using options object
```js
const engines = await puter.ai.txt2speech.listEngines({ provider: 'elevenlabs' });
+6 -4
View File
@@ -4,7 +4,9 @@ description: List available TTS voices, optionally filtered by provider.
platforms: [websites, apps, nodejs, workers]
---
Returns the voices available from a TTS provider. Each voice entry includes metadata such as language, category, and supported models.
Returns the voices available from a TTS provider.
Each voice entry includes metadata such as language, category, and supported models.
## Syntax
@@ -52,7 +54,7 @@ Example response (with `provider: 'all'`):
## Examples
<strong class="example-title">List voices for a provider</strong>
### List voices for a provider
```html;ai-txt2speech-list-voices
<html>
@@ -71,7 +73,7 @@ Example response (with `provider: 'all'`):
</html>
```
<strong class="example-title">List all default (AWS Polly) voices</strong>
### List all default (AWS Polly) voices
```js
const voices = await puter.ai.txt2speech.listVoices();
@@ -81,7 +83,7 @@ for (const voice of voices) {
}
```
<strong class="example-title">List Gemini voices</strong>
### List Gemini voices
```js
const voices = await puter.ai.txt2speech.listVoices({ provider: 'gemini' });
+3 -1
View File
@@ -4,7 +4,9 @@ description: Convert text to speech with AI using multiple languages, voices, an
platforms: [websites, apps, nodejs, workers]
---
Converts text into speech using AI. Supports multiple languages and voices.
Converts text into speech using AI.
It supports multiple languages and voices.
## Syntax
+2 -2
View File
@@ -183,9 +183,9 @@ These Apps API are supported out of the box when using Puter.js:
- **[`puter.apps.create()`](/Apps/create/)** - Create a new application
- **[`puter.apps.list()`](/Apps/list/)** - List all applications
- **[`puter.apps.delete()`](/Apps/delete/)** - Delete an application
- **[`puter.apps.update()`](/Apps/update/)** - Update application settings
- **[`puter.apps.get()`](/Apps/get/)** - Get information about a specific application
- **[`puter.apps.update()`](/Apps/update/)** - Update application settings
- **[`puter.apps.delete()`](/Apps/delete/)** - Delete an application
- **[`puter.apps.checkName()`](/Apps/checkName/)** - Check whether an app name is available
## Examples
+4 -2
View File
@@ -4,7 +4,9 @@ description: Check whether an app name is still available.
platforms: [websites, apps, nodejs, workers]
---
Checks whether an app name is free, without creating anything. App names are unique across all Puter accounts, so a name is free only when no app on any account uses it. Useful before calling [`puter.apps.create()`](/Apps/create/), which rejects when the name is already taken.
Checks whether an app name is free, without creating anything.
App names are unique across all Puter accounts, so a name is free only when no app on any account uses it. Useful before calling [`puter.apps.create()`](/Apps/create/), which rejects when the name is already taken.
## Syntax
@@ -24,7 +26,7 @@ A `Promise` that will resolve to an object describing the name's availability.
## Examples
<strong class="example-title">Check a name before creating the app</strong>
### Check a name before creating the app
```html
<html>
+17 -13
View File
@@ -4,7 +4,9 @@ description: Create apps in the Puter desktop environment.
platforms: [websites, apps, nodejs, workers]
---
Creates a Puter app with the given name. The app will be created in the user's apps, and will be accessible to this app. The app will be created with no permissions, and will not be able to access any data until permissions are granted to it.
Creates a Puter app with the given name.
The app will be created in the user's apps, and will be accessible to this app. The app will be created with no permissions, and will not be able to access any data until permissions are granted to it.
## Syntax
@@ -39,17 +41,19 @@ The title of the app. If this parameter is not provided, the app will be created
An object containing the options for the app to create. The object can contain the following properties:
- `name` (String) (required): The name of the app to create. App names are unique across all Puter accounts. If any app already has this name, the promise will be rejected.
- `indexURL` (String) (required): The URL of the app's index page. This URL must be accessible to the user. If this parameter is not provided, the promise will be rejected.
- `title` (String) (optional): The human-readable title of the app. If this parameter is not provided, the app will be created with `name` as its title.
- `description` (String) (optional): The description of the app aimed at the end user.
- `icon` (String) (optional): The new icon of the app.
- `maximizeOnStart` (Boolean) (optional): Whether the app should be maximized when it is started. Defaults to `false`.
- `filetypeAssociations` (Array<String>) (optional): An array of strings representing the filetypes that the app can open. Defaults to `[]`. File extentions and MIME types are supported; For example, `[".txt", ".md", "application/pdf"]` would allow the app to open `.txt`, `.md`, and PDF files. At most 200 entries, each at most 60 characters.
- `dedupeName` (Boolean) (optional) - Whether to deduplicate the app name if it already exists. Defaults to `false`.
- `background` (Boolean) (optional) - Whether the app should run in the background. Defaults to `false`.
- `feedbackEnabled` (Boolean) (optional) - Whether users can send feedback to you through [`puter.ui.showFeedbackDialog()`](/UI/showFeedbackDialog/). Defaults to `false`.
- `metadata` (Object) (optional) - An object containing custom metadata for the app. This can be used to store arbitrary key-value pairs associated with the app. At most 16 KiB when serialized as JSON.
| Option | Type | Description |
|--------|------|-------------|
| `name` | `String` | Required. The name of the app to create. App names are unique across all Puter accounts. If any app already has this name, the promise will be rejected. |
| `indexURL` | `String` | Required. The URL of the app's index page. This URL must be accessible to the user. If it's missing, the promise will be rejected. |
| `title` | `String` | The human-readable title of the app. If it's missing, the app will be created with `name` as its title. |
| `description` | `String` | The description of the app aimed at the end user. |
| `icon` | `String` | The new icon of the app. |
| `filetypeAssociations` | `Array<String>` | An array of strings representing the filetypes that the app can open. Defaults to `[]`. File extensions and MIME types are supported. For example, `[".txt", ".md", "application/pdf"]` would allow the app to open `.txt`, `.md`, and PDF files. At most 200 entries, each at most 60 characters. |
| `maximizeOnStart` | `Boolean` | Whether the app should be maximized when it is started. Defaults to `false`. |
| `background` | `Boolean` | Whether the app should run in the background. Defaults to `false`. |
| `feedbackEnabled` | `Boolean` | Whether users can send feedback to you through [`puter.ui.showFeedbackDialog()`](/UI/showFeedbackDialog/). Defaults to `false`. |
| `metadata` | `Object` | An object containing custom metadata for the app. This can be used to store arbitrary key-value pairs associated with the app. At most 16 KiB when serialized as JSON. |
| `dedupeName` | `Boolean` | Whether to deduplicate the app name if it already exists. Defaults to `false`. |
## Return value
@@ -57,7 +61,7 @@ A `Promise` that will resolve to the [`CreateAppResult`](/Objects/createappresul
## Examples
<strong class="example-title">Create an app pointing to example.com</strong>
### Create an app pointing to example.com
```html;app-create
<html>
+1 -1
View File
@@ -24,7 +24,7 @@ A `Promise` that will resolve to an object `{ success: true, uid: <app uid> }` i
## Examples
<strong class="example-title">Create a random app then delete it</strong>
### Create a random app then delete it
```html;app-delete
<html>
+9 -6
View File
@@ -4,7 +4,9 @@ description: Retrieve details of your Puter app.
platforms: [websites, apps, nodejs, workers]
---
Returns an app with the given name. If the app does not exist, the promise will be rejected.
Returns an app with the given name.
If the app does not exist, the promise will be rejected.
## Syntax
@@ -19,13 +21,14 @@ puter.apps.get(name, options)
The name of the app to get.
### options (optional)
#### `options` (Object) (optional)
An object containing the following properties:
- `stats_period` (optional): A string representing the period for which to get the user and open count. Possible values are `today`, `yesterday`, `7d`, `30d`, `this_month`, `last_month`, `this_year`, `last_year`, `month_to_date`, `year_to_date`, `last_12_months`. Default is `all` (all time).
- `icon_size` (optional): An integer representing the size of the icons to return. Possible values are `null`, `16`, `32`, `64`, `128`, `256`, and `512`. Default is `null` (the original size).
| Option | Type | Description |
|--------|------|-------------|
| `icon_size` | `Number \| null` | An integer representing the size of the icons to return. Possible values are `null`, `16`, `32`, `64`, `128`, `256`, and `512`. Default is `null` (the original size). |
| `stats_period` | `String` | The period for which to get the user and open count. Possible values are `today`, `yesterday`, `7d`, `30d`, `this_month`, `last_month`, `this_year`, `last_year`, `month_to_date`, `year_to_date`, `last_12_months`. Default is `all` (all time). |
## Return value
@@ -33,7 +36,7 @@ A `Promise` that will resolve to the [`App`](/Objects/app/) object with the give
## Examples
<strong class="example-title">Create a random app then get it</strong>
### Create a random app then get it
```html;app-get
<html>
+13 -15
View File
@@ -4,7 +4,9 @@ description: List all apps in your Puter account.
platforms: [websites, apps, nodejs, workers]
---
Returns an array of all apps belonging to the user and that this app has access to. If the user has no apps, the array will be empty.
Returns an array of all apps belonging to the user and that this app has access to.
If the user has no apps, the array will be empty.
## Syntax
@@ -19,19 +21,15 @@ puter.apps.list(options)
An object containing the following properties:
- `stats_period` (optional): A string representing the period for which to get the user and open count. Possible values are `today`, `yesterday`, `7d`, `30d`, `this_month`, `last_month`, `this_year`, `last_year`, `month_to_date`, `year_to_date`, `last_12_months`. Default is `all` (all time).
- `icon_size` (optional): An integer representing the size of the icons to return. Possible values are `null`, `16`, `32`, `64`, `128`, `256`, and `512`. Default is `null` (the original size).
- `limit` (optional): Maximum number of apps to return in a single call.
- `offset` (optional): Skips the given number of apps. Prefer `cursor` for paging through large lists.
- `cursor` (optional): Opts into paginated results. Pass `null` for the first page, then the `cursor` from each page to fetch the next one.
- `includeTotal` (optional): If `true`, the paginated result includes a `total` count of the user's apps.
- `stream` (optional): If `true`, the method returns an async iterator of page objects instead of a promise, for use with `for await ... of`. Combine with `limit` to control the page size, or `cursor` to resume from a previous page. Cannot be combined with `offset`. With `includeTotal`, only the first page carries `total`.
| Option | Type | Description |
|--------|------|-------------|
| `limit` | `Number` | Maximum number of apps to return in a single call. |
| `cursor` | `String \| null` | Opts into paginated results. Pass `null` for the first page, then the `cursor` from each page to fetch the next one. |
| `stream` | `Boolean` | If `true`, the method returns an async iterator of page objects instead of a promise, for use with `for await ... of`. Combine with `limit` to control the page size, or `cursor` to resume from a previous page. Cannot be combined with `offset`. With `includeTotal`, only the first page carries `total`. |
| `includeTotal` | `Boolean` | If `true`, the paginated result includes a `total` count of the user's apps. |
| `offset` | `Number` | Skips the given number of apps. Prefer `cursor` for paging through large lists. |
| `icon_size` | `Number \| null` | An integer representing the size of the icons to return. Possible values are `null`, `16`, `32`, `64`, `128`, `256`, and `512`. Default is `null` (the original size). |
| `stats_period` | `String` | The period for which to get the user and open count. Possible values are `today`, `yesterday`, `7d`, `30d`, `this_month`, `last_month`, `this_year`, `last_year`, `month_to_date`, `year_to_date`, `last_12_months`. Default is `all` (all time). |
## Return value
@@ -57,7 +55,7 @@ for await (const page of puter.apps.list({ stream: true })) {
## Examples
<strong class="example-title">Create 3 random apps and then list them</strong>
### Create 3 random apps and then list them
```html;app-list
<html>
+14 -11
View File
@@ -17,16 +17,19 @@ The name of the app to update.
#### `attributes` (required)
An object containing the attributes to update. The object can contain the following properties:
- `name` (optional): The new name of the app. App names are unique across all Puter accounts. If any app already has this name, the promise will be rejected.
- `indexURL` (optional): The new URL of the app's index page. This URL must be accessible to the user.
- `title` (optional): The new title of the app.
- `description` (optional): The new description of the app aimed at the end user.
- `icon` (optional): The new icon of the app.
- `maximizeOnStart` (optional): Whether the app should be maximized when it is started. Defaults to `false`.
- `background` (optional): Whether the app should run in the background. Defaults to `false`.
- `feedbackEnabled` (optional): Whether users can send feedback to you through [`puter.ui.showFeedbackDialog()`](/UI/showFeedbackDialog/). Omitted leaves the app's current value unchanged.
- `filetypeAssociations` (optional): An array of strings representing the filetypes that the app can open. Defaults to `[]`. File extentions and MIME types are supported; For example, `[".txt", ".md", "application/pdf"]` would allow the app to open `.txt`, `.md`, and PDF files. At most 200 entries, each at most 60 characters.
- `metadata` (optional): An object containing custom metadata for the app. This can be used to store arbitrary key-value pairs associated with the app. At most 16 KiB when serialized as JSON.
| Option | Type | Description |
|--------|------|-------------|
| `title` | `String` | The new title of the app. |
| `indexURL` | `String` | The new URL of the app's index page. This URL must be accessible to the user. |
| `description` | `String` | The new description of the app aimed at the end user. |
| `icon` | `String` | The new icon of the app. |
| `name` | `String` | The new name of the app. App names are unique across all Puter accounts. If any app already has this name, the promise will be rejected. |
| `filetypeAssociations` | `Array<String>` | An array of strings representing the filetypes that the app can open. Defaults to `[]`. File extensions and MIME types are supported. For example, `[".txt", ".md", "application/pdf"]` would allow the app to open `.txt`, `.md`, and PDF files. At most 200 entries, each at most 60 characters. |
| `maximizeOnStart` | `Boolean` | Whether the app should be maximized when it is started. Defaults to `false`. |
| `background` | `Boolean` | Whether the app should run in the background. Defaults to `false`. |
| `feedbackEnabled` | `Boolean` | Whether users can send feedback to you through [`puter.ui.showFeedbackDialog()`](/UI/showFeedbackDialog/). Omitted leaves the app's current value unchanged. |
| `metadata` | `Object` | An object containing custom metadata for the app. This can be used to store arbitrary key-value pairs associated with the app. At most 16 KiB when serialized as JSON. |
Changing `indexURL` can merge the app into an existing app for that hosted origin. The returned app can have a different UID. The deleted source app's KV data and KV shares are removed. Data already belonging to the surviving app is retained.
@@ -35,7 +38,7 @@ A `Promise` that will resolve to the [`App`](/Objects/app/) object that was upda
## Examples
<strong class="example-title">Create a random app then change its title</strong>
### Create a random app then change its title
```html;app-update
<html>
+1 -1
View File
@@ -98,8 +98,8 @@ This is essential for users to access the various Puter.js APIs integrated into
These authentication features are supported out of the box when using Puter.js:
- **[`puter.auth.signIn()`](/Auth/signIn/)** - Sign in a user
- **[`puter.auth.signOut()`](/Auth/signOut/)** - Sign out the current user
- **[`puter.auth.isSignedIn()`](/Auth/isSignedIn/)** - Check if a user is signed in
- **[`puter.auth.signOut()`](/Auth/signOut/)** - Sign out the current user
- **[`puter.auth.getUser()`](/Auth/getUser/)** - Get information about the current user
- **[`puter.auth.getProfile()`](/Auth/getProfile/)** - Get a user's profile, when available
- **[`puter.auth.getProfilePicture()`](/Auth/getProfilePicture/)** - Get a user's profile picture, when available
+3 -1
View File
@@ -29,7 +29,9 @@ The id of the application.
A `Promise` that resolves to a [`DetailedAppUsage`](/Objects/detailedappusage) object containing resource usage statistics for the given application.
## Example
## Examples
### Get an app's usage
```html
<html>
+3 -1
View File
@@ -26,7 +26,9 @@ None
A `Promise` that resolves to a [`MonthlyUsage`](/Objects/monthlyusage) object containing the user's monthly usage information.
## Example
## Examples
### Get the user's monthly usage
```html;auth-get-monthly-usage
<html>
+7 -3
View File
@@ -4,7 +4,9 @@ description: Read a user's profile, returning null when it is not available.
platforms: [websites, apps, nodejs, workers]
---
Returns a user's profile: their picture, display name, and bio. Users set these on the [Account page](https://puter.com/dashboard#account) of their Puter dashboard. A user can always read their own profile. Another user's profile is available only while that user is on a paid plan; otherwise the method resolves to `null`, the same as for a user who does not exist.
Returns a user's profile, which holds their picture, display name, and bio.
Users set these on the [Account page](https://puter.com/dashboard#account) of their Puter dashboard. A user can always read their own profile. Another user's profile is available only while that user is on a paid plan; otherwise the method resolves to `null`, the same as for a user who does not exist.
## Syntax
@@ -15,7 +17,7 @@ puter.auth.getProfile(username);
## Parameters
### `username` (optional)
#### `username` (optional)
The username to look up. Defaults to the signed-in user.
@@ -25,7 +27,9 @@ A promise that resolves to a [`UserProfile`](/Objects/userprofile) object, or `n
When signed out with no `username`, it resolves to `null` without opening a sign-in prompt.
## Example
## Examples
### Show the user's profile
```html
<html>
+7 -3
View File
@@ -4,7 +4,9 @@ description: Read a user's profile picture, returning null when unavailable.
platforms: [websites, apps, nodejs, workers]
---
Returns the `picture` field of a user's profile (see [`puter.auth.getProfile()`](/Auth/getProfile/)). A user can always read their own picture. Another user's picture is available only while that user is on a paid plan.
Returns the `picture` field of a user's profile (see [`puter.auth.getProfile()`](/Auth/getProfile/)).
A user can always read their own picture. Another user's picture is available only while that user is on a paid plan.
## Syntax
@@ -15,7 +17,7 @@ puter.auth.getProfilePicture(username);
## Parameters
### `username` (optional)
#### `username` (optional)
The username to look up. Defaults to the signed-in user.
@@ -27,7 +29,9 @@ Missing users, profiles that are not public to the caller, profiles with no pict
When signed out with no `username`, it resolves to `null` without opening a sign-in prompt.
## Example
## Examples
### Show the user's profile picture
```html
<html>
+3 -1
View File
@@ -20,7 +20,9 @@ None
A promise that resolves to a [`User`](/Objects/user) object containing the user's basic information.
## Example
## Examples
### Get the signed-in user
```html;auth-get-user
<html>
+3 -1
View File
@@ -20,7 +20,9 @@ None
Returns `true` if the user is signed in, `false` otherwise.
## Example
## Examples
### Check whether the user is signed in
```html;auth-is-signed-in
<html>
+12 -7
View File
@@ -4,7 +4,9 @@ description: Initiate sign in process in your application with user's Puter acco
platforms: [websites]
---
Initiates the sign in process for the user. This will open a popup window with the appropriate authentication method. Puter automatically handles the authentication process and will resolve the promise when the user has signed in.
Initiates the sign in process for the user.
This will open a popup window with the appropriate authentication method. Puter automatically handles the authentication process and will resolve the promise when the user has signed in. Puter's own apps on puter.com subdomains show the sign-in in a frame over the page instead, and open the popup when the user picks a sign-in provider such as Google.
It is important to note that all essential methods in Puter handle authentication automatically. This method is only necessary if you want to handle authentication manually, for example if you want to build your own custom authentication flow.
@@ -27,11 +29,12 @@ puter.auth.signIn(options)
#### `options` (optional)
`options` is an object with the following properties:
An object with the following properties:
- `attempt_temp_user_creation`: A boolean value that indicates whether to Puter should automatically create a temporary user. This is useful if you want to quickly onboard a user without requiring them to sign up. They can always sign up later if they want to.
- `request_auth`: A boolean value that asks the popup to let the user re-pick their account, even when your site already holds a token for them. Puter otherwise skips that prompt for a site it has seen before. Useful for an explicit "switch account" button.
| Option | Type | Description |
|--------|------|-------------|
| `attempt_temp_user_creation` | `Boolean` | Whether Puter should automatically create a temporary user. This is useful if you want to quickly onboard a user without requiring them to sign up. They can always sign up later if they want to. |
| `request_auth` | `Boolean` | Asks the popup to let the user re-pick their account, even when your site already holds a token for them. Puter otherwise skips that prompt for a site it has seen before. Useful for an explicit "switch account" button. |
Each call completes from its own sign-in window, including when multiple calls run at once.
@@ -39,7 +42,7 @@ Each call completes from its own sign-in window, including when multiple calls r
A `Promise` that will resolve to a [`SignInResult`](/Objects/signinresult/) object when the user has signed in.
## Rejection
## Errors
The promise will reject with an object containing an `error` code and a human-readable `msg` in the following cases:
@@ -53,7 +56,9 @@ The promise will reject with an object containing an `error` code and a human-re
The promise may also reject with the failure response returned by the authentication window itself.
## Example
## Examples
### Sign in from a button click
```html;auth-sign-in
<html>
+3 -1
View File
@@ -22,7 +22,9 @@ None
A `Promise` that resolves with nothing once the user is signed out and, on a website, this browser's push subscription for your app is ended. It doesn't reject.
## Example
## Examples
### Sign the user out
```html;auth-sign-out
<html>
+18 -8
View File
@@ -5,7 +5,9 @@ platforms: [websites, apps, nodejs, workers]
draft: true
---
Changes fields on the signed-in user's profile and returns the updated profile. Fields left out of the patch are left as they are; `null` clears a field.
Changes fields on the signed-in user's profile and returns the updated profile.
Fields left out of the patch are left as they are; `null` clears a field.
## Syntax
@@ -15,19 +17,27 @@ puter.auth.updateProfile(patch);
## Parameters
### `patch` (required)
#### `patch` (required)
An object with any of these fields:
- `picture` (String or `null`): a base64 image data URL such as `data:image/png;base64,...`. At most 512 KiB.
- `displayName` (String or `null`): at most 64 characters. Surrounding whitespace is removed.
- `bio` (String or `null`): at most 280 characters. Surrounding whitespace is removed.
| Option | Type | Description |
|--------|------|-------------|
| `displayName` | `String \| null` | The user's display name, at most 64 characters. Surrounding whitespace is removed. |
| `picture` | `String \| null` | A base64 image data URL such as `data:image/png;base64,...`. At most 512 KiB. |
| `bio` | `String \| null` | The user's bio, at most 280 characters. Surrounding whitespace is removed. |
Any other field is rejected.
## Return value
A promise that resolves to the stored [`UserProfile`](/Objects/userprofile). It rejects with an object carrying a `code` and `message` when the patch is not accepted:
A promise that resolves to the stored [`UserProfile`](/Objects/userprofile).
The profile belongs to the account, so the call must be made with a user session; an app acting on a user's behalf cannot change it.
## Errors
The promise rejects with an object carrying a `code` and `message` when the patch is not accepted:
| `code` | Meaning |
| --------------------------- | ----------------------------------------------------- |
@@ -37,9 +47,9 @@ A promise that resolves to the stored [`UserProfile`](/Objects/userprofile). It
| `profile_picture_too_large` | `picture` is over the size limit |
| `profile_field_too_long` | `displayName` or `bio` is over its length limit |
The profile belongs to the account, so the call must be made with a user session; an app acting on a user's behalf cannot change it.
## Examples
## Example
### Change the user's display name
```html;auth-update-profile
<html>
+1 -1
View File
@@ -88,6 +88,6 @@ router.post('/notify', async ({ request, user }) => {
## Functions
- **[`puter.email.sendTransactional()`](/Email/sendTransactional/)** - Send a transactional email from your app
- **[`puter.email.list()`](/Email/list/)** - List the messages in the user's mailbox, newest first
- **[`puter.email.get()`](/Email/get/)** - Fetch and parse one message, attachments included
- **[`puter.email.sendTransactional()`](/Email/sendTransactional/)** - Send a transactional email from your app
+11 -7
View File
@@ -4,7 +4,9 @@ description: Fetch and parse one message from the user's mailbox by its id.
platforms: [websites, apps, nodejs, workers]
---
Reads one message by the `id` a listing returned. The whole raw message is downloaded and parsed, so the result carries the full subject, sender and recipients, the text and HTML bodies, every header, and each attachment with its bytes. Pass `raw: true` to get the unparsed `message/rfc822` bytes as a `Blob` instead.
Reads one message by the `id` a listing returned.
The whole raw message is downloaded and parsed, so the result carries the full subject, sender and recipients, the text and HTML bodies, every header, and each attachment with its bytes. Pass `raw: true` to get the unparsed `message/rfc822` bytes as a `Blob` instead.
Reading the mailbox requires read access to the `~/.mail` folder, the same grant [`puter.email.list()`](/Email/list/) needs.
@@ -23,9 +25,11 @@ The message id from `puter.email.list()`. Looks up the inbox.
#### `options` (Object)
- `id` (String) (required): The message id.
- `folder` (String): `'inbox'` or `'sent'`. Default `'inbox'`. A message id is unique within a folder, so a sent message must be read with `folder: 'sent'`.
- `raw` (Boolean): When `true`, resolve with the raw message `Blob` and skip parsing. Default `false`.
| Option | Type | Description |
|--------|------|-------------|
| `id` | `String` | Required. The message id. |
| `folder` | `String` | Either `'inbox'` or `'sent'`. Default `'inbox'`. A message id is unique within a folder, so a sent message must be read with `folder: 'sent'`. |
| `raw` | `Boolean` | When `true`, resolve with the raw message `Blob` and skip parsing. Default `false`. |
## Return value
@@ -45,7 +49,7 @@ Rejects with an object carrying a `code`:
## Examples
<strong class="example-title">Read the newest message in the inbox</strong>
### Read the newest message in the inbox
```html
<html>
@@ -66,7 +70,7 @@ Rejects with an object carrying a `code`:
</html>
```
<strong class="example-title">Save every attachment of a message to the user's Documents</strong>
### Save every attachment of a message to the user's Documents
```html
<html>
@@ -89,7 +93,7 @@ Rejects with an object carrying a `code`:
</html>
```
<strong class="example-title">Download the raw message</strong>
### Download the raw message
```html
<html>
+12 -8
View File
@@ -4,7 +4,9 @@ description: List the messages in the user's mailbox, newest first, one page at
platforms: [websites, apps, nodejs, workers]
---
Lists the messages in one folder of the user's mailbox, newest first. Every call returns one page of `items` plus, while more pages exist, a `cursor` to pass back for the next one. Listing reads the mailbox's folder structure only, so it never downloads a message: each item carries the subject, date, and size, and `puter.email.get()` fetches the rest.
Lists the messages in one folder of the user's mailbox, newest first.
Every call returns one page of `items` plus, while more pages exist, a `cursor` to pass back for the next one. Listing reads the mailbox's folder structure only, so it never downloads a message: each item carries the subject, date, and size, and `puter.email.get()` fetches the rest.
The mailbox belongs to the user, so it is protected like the rest of their files. An app reads it only after the user grants read access to the `~/.mail` folder. To ask for it, call [`puter.perms.request()`](/Perms/request/):
@@ -23,10 +25,12 @@ puter.email.list(options)
#### `options` (Object) (optional)
- `folder` (String): `'inbox'` for mail received at the user's address, `'sent'` for their outgoing copies. Default `'inbox'`.
- `limit` (Number): Maximum messages per page. Default `50`, capped at `1000`.
- `cursor` (String | null): The `cursor` from the previous page. `null` or absent fetches the first page.
- `stream` (Boolean): When `true`, returns an async iterator of pages for `for await ... of` instead of a single page.
| Option | Type | Description |
|--------|------|-------------|
| `limit` | `Number` | Maximum messages per page. Default `50`, capped at `1000`. |
| `folder` | `String` | Use `'inbox'` for mail received at the user's address, or `'sent'` for their outgoing copies. Default `'inbox'`. |
| `cursor` | `String \| null` | The `cursor` from the previous page. Pass `null` or leave it out to fetch the first page. |
| `stream` | `Boolean` | When `true`, returns an async iterator of pages for `for await ... of` instead of a single page. |
`offset` and `includeTotal` are not supported for mailboxes; passing either rejects with `invalid_request`.
@@ -45,7 +49,7 @@ Rejects with an object carrying a `code`:
## Examples
<strong class="example-title">List the ten newest messages</strong>
### List the ten newest messages
```html
<html>
@@ -64,7 +68,7 @@ Rejects with an object carrying a `code`:
</html>
```
<strong class="example-title">Walk the whole sent folder with a cursor</strong>
### Walk the whole sent folder with a cursor
```html
<html>
@@ -86,7 +90,7 @@ Rejects with an object carrying a `code`:
</html>
```
<strong class="example-title">Stream pages</strong>
### Stream pages
```html
<html>
+30 -20
View File
@@ -4,7 +4,9 @@ description: Send a transactional email from your app — authorized by a worker
platforms: [websites, apps, nodejs, workers]
---
Sends one transactional email from your app. Every send must be authorized by a worker: call it from inside a worker, or pass the worker's token as `emailAccessToken`. The account that makes the call is the one billed and rate-limited.
Sends one transactional email from your app.
Every send must be authorized by a worker: call it from inside a worker, or pass the worker's token as `emailAccessToken`. The account that makes the call is the one billed and rate-limited.
<div class="info">Transactional email is available to accounts on a paid plan for now. A call from a free account fails with <code>402</code> <code>subscription_required</code>. Under the <a href="/user-pays-model/">User-Pays Model</a> that is the plan of the <em>calling</em> account — your users when your app sends with their session, your own when the worker sends directly.</div>
@@ -31,21 +33,25 @@ A plain-text body. Shorthand for `text`; use the options form for anything else.
#### `options` (Object)
- `to` (String | Array) (required) - Recipient address(es).
- `subject` (String) (required) - As above.
- `text` (String) - Plain-text body. At least one of `text` and `html` is required.
- `html` (String) - HTML body. An inline image is shown with `<img src="cid:...">` — see `cid` under `attachments`.
- `cc` (String | Array) - Carbon-copy recipient(s).
- `bcc` (String | Array) - Blind-copy recipient(s). At most **10** recipients across `to`, `cc` and `bcc`.
- `replyTo` (String) - Where replies go. Defaults to the confirmed account email of the worker's owner when the worker has no app binding, or its owner owns the bound app and that app wasn't created by another app. Otherwise, or while the address is unconfirmed, the message goes out without a Reply-To.
- `emailAccessToken` (String) - A worker's auth token — inside a worker, `me.puter.authToken`. Required when the caller is not itself a worker. The caller stays the billed and rate-limited identity.
- `attachments` (Array) - Up to **10** attachments, **25 MB** in total. Each is an object:
- `filename` (String) - Required with `content`; defaults to the file's name for a `path`/`uid` attachment.
- `content` (String) - The file body as base64. Mutually exclusive with `path`/`uid`.
- `path` (String) - A Puter path (`~/` allowed, meaning the caller's home). The file is read on the server with the caller's file permissions only, and streamed rather than uploaded — prefer this over `content` for anything larger than a few hundred kilobytes.
- `uid` (String) - A Puter file uid, as an alternative to `path`. Read with the caller's file permissions, falling back to the worker owner's — use a uid to attach a file from the worker owner's storage.
- `contentType` (String) - MIME type. Detected from the file for `path`/`uid` attachments.
- `cid` (String) - Content-ID that makes the attachment an inline part of the `html` body: with `cid: 'logo'`, `<img src="cid:logo">` shows it. Printable ASCII with no whitespace or angle brackets. Inline parts are billed like any other attachment.
| Option | Type | Description |
|--------|------|-------------|
| `to` | `String \| Array` | Required. One recipient address, or an array of them. |
| `subject` | `String` | Required. As above. |
| `text` | `String` | Plain-text body. At least one of `text` and `html` is required. |
| `html` | `String` | HTML body. An inline image is shown with `<img src="cid:...">`. See `attachments.cid`. |
| `emailAccessToken` | `String` | A worker's auth token. Inside a worker, that's `me.puter.authToken`. Required when the caller is not itself a worker. The caller stays the billed and rate-limited identity. |
| `attachments` | `Array` | Up to **10** attachments, **25 MB** in total. Each attachment is an object with the `attachments.*` fields in the rows that follow. |
| `attachments.path` | `String` | A Puter path (`~/` allowed, meaning the caller's home). The file is read on the server with the caller's file permissions only, and streamed rather than uploaded. Prefer this over `content` for anything larger than a few hundred kilobytes. |
| `attachments.uid` | `String` | A Puter file uid, as an alternative to `path`. Read with the caller's file permissions, falling back to the worker owner's. Use a uid to attach a file from the worker owner's storage. |
| `attachments.content` | `String` | The file body as base64. Mutually exclusive with `path`/`uid`. |
| `attachments.filename` | `String` | Required with `content`. Defaults to the file's name for a `path`/`uid` attachment. |
| `attachments.contentType` | `String` | MIME type. Detected from the file for `path`/`uid` attachments. |
| `attachments.cid` | `String` | Content-ID that makes the attachment an inline part of the `html` body. With `cid: 'logo'`, `<img src="cid:logo">` shows it. Printable ASCII with no whitespace or angle brackets. Inline parts are billed like any other attachment. |
| `replyTo` | `String` | Where replies go. Defaults to the confirmed account email of the worker's owner when the worker has no app binding, or its owner owns the bound app and that app wasn't created by another app. Otherwise, or while the address is unconfirmed, the message goes out without a Reply-To. |
| `cc` | `String \| Array` | Carbon-copy recipient(s). |
| `bcc` | `String \| Array` | Blind-copy recipient(s). |
A message can have at most **10** recipients across `to`, `cc` and `bcc`.
## Return value
@@ -56,7 +62,11 @@ A `Promise` that resolves to an object:
- `suppressed` (Array) - Recipients (lowercased) dropped because they unsubscribed from your app's mail. The message went to the others.
- `failed` (Array) - Recipients (lowercased) whose delivery failed. Everyone else got their copy — retry with just these addresses.
Each recipient gets a private copy of the message, so the unsubscribe link in one copy can only act for the mailbox that received it. Per-recipient failures come back in `failed` rather than failing the call; the promise rejects only when no recipient could be delivered, or when every `to` recipient has unsubscribed (`400`).
Each recipient gets a private copy of the message, so the unsubscribe link in one copy can only act for the mailbox that received it. Per-recipient failures come back in `failed` rather than failing the call.
## Errors
The promise rejects only when no recipient could be delivered, or when every `to` recipient has unsubscribed (`400`).
In case of an error, the `Promise` rejects with `{ message, code }`. Codes you may see:
@@ -90,7 +100,7 @@ Sends are rate-limited per calling account; the numbers are on [Rate Limits and
## Examples
<strong class="example-title">Send a plain-text notification from a worker</strong>
### Send a plain-text notification from a worker
```js
// The worker is the caller, so its owner is billed and rate-limited.
@@ -104,7 +114,7 @@ router.post('/api/alert', async ({ request }) => {
});
```
<strong class="example-title">Let the user pay for their own sends</strong>
### Let the user pay for their own sends
```js
// The user's session makes the call; the worker's token authorizes it.
@@ -122,7 +132,7 @@ router.post('/api/receipt', async ({ request, user }) => {
});
```
<strong class="example-title">Attach a file and show an inline image</strong>
### Attach a file and show an inline image
```js
// The uid of a file in the worker owner's storage, e.g. from
+26 -20
View File
@@ -4,9 +4,11 @@ description: Read what a subject recorded while nothing was listening.
platforms: [websites, apps, nodejs, workers]
---
Reads the events a subject has stored, a page at a time.
<div class="info">The Events API is in beta. Event shapes, limits, and behavior may change between releases.</div>
Reads the events a subject has stored, a page at a time. A subscription only delivers while something is listening, and `fetch()` catches up on what happened while the client was closed or offline. Only `notif:` subjects (the notification mailbox) store events. Subjects for `fs:` and `kv:` are refused with `fetch_unsupported_subject`.
A subscription only delivers while something is listening, and `fetch()` catches up on what happened while the client was closed or offline. Only `notif:` subjects (the notification mailbox) store events. Subjects for `fs:` and `kv:` are refused with `fetch_unsupported_subject`.
It's a plain query. Nothing is registered and no position is saved, so calling it twice returns the same result. You keep the `cursor` and pass it back.
@@ -25,11 +27,13 @@ puter.events.fetch(options)
#### `options` (Object) (required)
- `subject` (String) (required): What to read. Use `notif:app-user` for your app's notifications for the user, and `notif:developer` for notifications about your app, for its owner. The full form is `notif:<appId>:<audience>`, where the audience is `account`, `developer`, or `app-user`. Apps and websites never see `account` notifications, so `notif:account` returns an empty page for them.
- `cursor` (String): The `cursor` from the previous page. Leave it off to start from the oldest notification still kept. A read from a cursor returns the notifications created after it, plus any notification [replaced](/Notifications/notify/#groups) since that page was read, even one from an earlier page.
- `after` (String): The older name for `cursor`, still accepted. If both are given, `cursor` is used.
- `from` (String): Where a read without a cursor starts. `'start'`, the default, starts from the oldest notification still kept. `'end'` skips what's already there: it returns no items and a `cursor` at the newest notification, and reads from that cursor return only notifications created or replaced after it. Ignored when a cursor is given.
- `limit` (Number): Events per page. Defaults to 50, max 200.
| Option | Type | Description |
|--------|------|-------------|
| `subject` | `String` | Required. What to read. Use `notif:app-user` for your app's notifications for the user, and `notif:developer` for notifications about your app, for its owner. The full form is `notif:<appId>:<audience>`, where the audience is `account`, `developer`, or `app-user`. Apps and websites never see `account` notifications, so `notif:account` returns an empty page for them. |
| `cursor` | `String` | The `cursor` from the previous page. Leave it off to start from the oldest notification still kept. A read from a cursor returns the notifications created after it, plus any notification [replaced](/Notifications/notify/#groups) since that page was read, even one from an earlier page. |
| `limit` | `Number` | Events per page. Defaults to 50, max 200. |
| `from` | `String` | Where a read without a cursor starts. The default, `'start'`, starts from the oldest notification still kept. With `'end'`, the read skips what's already there. It returns no items and a `cursor` at the newest notification, and reads from that cursor return only notifications created or replaced after it. Ignored when a cursor is given. |
| `after` | `String` | The older name for `cursor`, still accepted. If both are given, `cursor` is used. |
## Return value
@@ -42,18 +46,18 @@ Each item is a notification event:
| Field | Type | Description |
| --- | --- | --- |
| `id` | String | The notification's uid. Live deliveries carry the same id, so you can drop duplicates. A replacement keeps the id, so tell it apart by `replaced` and `ts`. |
| `subject` | String | `notif:<appId or userId>:<audience>`, the part of the mailbox it belongs to. |
| `op` | String | Always `post`. |
| `uid` | String | The notification's uid. |
| `type` | String | The kind of notification, such as `share.received`, `app.worker.deployed`, or `app.message`. The types are listed below. |
| `audience` | String | `account`, `developer`, or `app-user`. |
| `appUid` | String \| null | The app it's about, or `null` for one that names no app. |
| `notification` | Object | The stored payload. It always has `type`, and every type except `kv.share.received` has a `title`. Other fields depend on `type`. |
| `replaced` | Boolean | Present and `true` when the notification replaced an earlier one with the same `uid`, as an app's notification with a [`group`](/Notifications/notify/#groups) does. |
| `self` | Boolean | Always `true`, since a mailbox is your own. |
| `ts` | Number | When it was created, in milliseconds since the epoch. On a replacement, when it was replaced, and the same on its live and fetched copies. |
| `seq` | Number | Position within the page. |
| `id` | `String` | The notification's uid. Live deliveries carry the same id, so you can drop duplicates. A replacement keeps the id, so tell it apart by `replaced` and `ts`. |
| `subject` | `String` | `notif:<appId or userId>:<audience>`, the part of the mailbox it belongs to. |
| `op` | `String` | Always `post`. |
| `uid` | `String` | The notification's uid. |
| `type` | `String` | The kind of notification, such as `share.received`, `app.worker.deployed`, or `app.message`. The types are listed below. |
| `audience` | `String` | `account`, `developer`, or `app-user`. |
| `appUid` | `String \| null` | The app it's about, or `null` for one that names no app. |
| `notification` | `Object` | The stored payload. It always has `type`, and every type except `kv.share.received` has a `title`. Other fields depend on `type`. |
| `replaced` | `Boolean` | Present and `true` when the notification replaced an earlier one with the same `uid`, as an app's notification with a [`group`](/Notifications/notify/#groups) does. |
| `self` | `Boolean` | Always `true`, since a mailbox is your own. |
| `ts` | `Number` | When it was created, in milliseconds since the epoch. On a replacement, when it was replaced, and the same on its live and fetched copies. |
| `seq` | `Number` | Position within the page. |
Besides `type` and `title`, `notification` carries these fields for each type:
@@ -74,6 +78,8 @@ Apps see `developer` notifications only for apps the user owns. Asking for a par
Notifications are kept for the server's retention window. A client away for longer starts from what's left.
## Errors
The promise rejects with `{ message, code }`:
| `code` | Meaning |
@@ -89,7 +95,7 @@ The promise rejects with `{ message, code }`:
## Examples
<strong class="example-title">Catch up on everything missed</strong>
### Catch up on everything missed
```html;events-fetch
<html>
@@ -118,7 +124,7 @@ The promise rejects with `{ message, code }`:
</html>
```
<strong class="example-title">Read the missed ones, then keep listening</strong>
### Read the missed ones, then keep listening
```html;events-fetch-then-listen
<html>
+6 -2
View File
@@ -4,9 +4,11 @@ description: Read one schedule, including one that has ended.
platforms: [websites, apps, nodejs, workers]
---
Reads one schedule created with [`puter.events.onSchedule()`](/Events/onSchedule/), or one notification your app stored to send later with [`puter.notifications.notify()`](/Notifications/notify/#send-it-later).
<div class="info">The Events API is in beta. Event shapes, limits, and behavior may change between releases.</div>
Reads one schedule created with [`puter.events.onSchedule()`](/Events/onSchedule/), or one notification your app stored to send later with [`puter.notifications.notify()`](/Notifications/notify/#send-it-later). An ended schedule can be read for 7 days after it ends.
An ended schedule can be read for 7 days after it ends.
An app can read only the schedules it created. An account session can read any of the user's schedules. An id this caller can't read reads as not existing, so the call doesn't reveal which schedules exist.
@@ -26,6 +28,8 @@ The `scheduleId` from [`onSchedule()`](/Events/onSchedule/), [`notify()`](/Notif
A `Promise` that resolves to the schedule, the object [`onSchedule()`](/Events/onSchedule/#return-value) returns, without `off()`. Its `state` says whether it's `active`, `suspended`, `sending` or `ended`, and `nextRunAt` says when it's next due.
## Errors
The promise rejects with `{ message, code }`:
| `code` | Meaning |
@@ -38,7 +42,7 @@ The promise rejects with `{ message, code }`:
## Examples
<strong class="example-title">Check when a stored notification goes out</strong>
### Check when a stored notification goes out
```html;events-get-schedule
<html>
+14 -7
View File
@@ -4,9 +4,11 @@ description: Publish, list and remove the named handlers that persistent subscri
platforms: [websites, apps, nodejs, workers]
---
A **handler** is a function that [persistent subscriptions](/Events/onPersistent/) and [schedules](/Events/onSchedule/) run in the background.
<div class="info">The Events API is in beta. Event shapes, limits, and behavior may change between releases.</div>
A **handler** is a function that [persistent subscriptions](/Events/onPersistent/) and [schedules](/Events/onSchedule/) run in the background. A handler runs only when a subscription bound to it has a delivery, or a schedule bound to it is due. Nothing else can trigger it.
A handler runs only when a subscription bound to it has a delivery, or a schedule bound to it is due. Nothing else can trigger it.
A handler lives in one of two scopes:
@@ -97,9 +99,14 @@ puter.events.handlers.publish(name, handler, options)
- `name` (String) (required): The name subscriptions bind to. Letters, digits, and `_ . : -`, starting with a letter or digit, up to 128 characters. Unique within the app.
- `handler` (Function | String | Object) (required): A function (serialized with `toString()`), a source string, or `{ file: '~/AppData/…/handler.js' }`. A file is read at this call, so later edits to it take effect only when you publish again.
- `options.replace` (Boolean): Overwrite whatever is published under the name.
- `options.scope` (String): `'app'` or `'user'`. Defaults to `'app'`. `'user'` publishes into the signed-in user's own [user scope](#user-scope) of the app.
- `options.appUid` (String): The app to publish into. Required outside an app. Inside an app, it can only name that app. With `scope: 'user'` it can only name the app making the call, and needs no value. Only [`workers.destroy()`](/Events/workers/) can name another app for a user scope, from an account session.
The `options` object takes these options:
| Option | Type | Description |
|--------|------|-------------|
| `appUid` | `String` | Required outside an app. The app to publish into. Inside an app, it can only name that app. With `scope: 'user'` it can only name the app making the call, and needs no value. Only [`workers.destroy()`](/Events/workers/) can name another app for a user scope, from an account session. |
| `scope` | `String` | Either `'app'` or `'user'`. Defaults to `'app'`. With `'user'`, it publishes into the signed-in user's own [user scope](#user-scope) of the app. |
| `replace` | `Boolean` | Overwrite whatever is published under the name. |
Resolves to `{ name, hash, updatedAt, outcome, resumed }`. Its `outcome` is `'created'`, `'updated'`, or `'unchanged'` (the same source was already published), and `resumed` counts the suspended subscriptions this publish brought back.
@@ -184,7 +191,7 @@ All four methods reject with `{ message, code }`:
The first example publishes into a user scope from inside an app, for the signed-in user. The others run in Node.js signed in with your account token, and `appUid` names an app you own. Inside your own app, leave out `appUid`.
<strong class="example-title">Publish into the user's scope, list it, then remove it</strong>
### Publish into the user's scope, list it, then remove it
```js
const published = await puter.events.handlers.publish(
@@ -203,7 +210,7 @@ for (const handler of await puter.events.handlers.list({ scope: 'user' })) {
await puter.events.handlers.remove('digest', { scope: 'user' });
```
<strong class="example-title">Publish a handler, list it, then remove it</strong>
### Publish a handler, list it, then remove it
```js
const published = await puter.events.handlers.publish(
@@ -224,7 +231,7 @@ const removed = await puter.events.handlers.remove('ingestUpload', { appUid });
console.log(removed.removed, removed.suspended);
```
<strong class="example-title">Deploy a whole set from a build step</strong>
### Deploy a whole set from a build step
```js
const published = await puter.events.handlers.publishAll([
+13 -7
View File
@@ -4,9 +4,11 @@ description: List the persistent subscriptions this caller holds.
platforms: [websites, apps, nodejs, workers]
---
Lists the persistent subscriptions created with [`puter.events.onPersistent()`](/Events/onPersistent/).
<div class="info">The Events API is in beta. Event shapes, limits, and behavior may change between releases.</div>
Lists the persistent subscriptions created with [`puter.events.onPersistent()`](/Events/onPersistent/). Session subscriptions from [`onLocal()`](/Events/onLocal/) aren't stored, so they aren't listed.
Session subscriptions from [`onLocal()`](/Events/onLocal/) aren't stored, so they aren't listed.
An app sees only the subscriptions it created. Outside an app, such as in Node.js with an account token, you see all of them. Deleting an app deletes its subscriptions. A scoped access token, such as the one in a [`getReadURL()`](/FS/getReadURL/) URL, sees none, whether the account or an app created it.
@@ -22,10 +24,12 @@ puter.events.list(options)
#### `options` (Object) (optional)
- `limit` (Number): Maximum subscriptions per request. Defaults to 50, max 200.
- `cursor` (String | null): The cursor from a previous page. Passing it, even as `null`, returns a single page instead of the full list.
- `includeTotal` (Boolean): Adds `total` to the page. Ask for it on the first page only, since it gets slower as the count grows.
- `stream` (Boolean): Returns an async iterator of pages instead of a promise.
| Option | Type | Description |
|--------|------|-------------|
| `limit` | `Number` | Maximum subscriptions per request. Defaults to 50, max 200. |
| `cursor` | `String \| null` | The cursor from a previous page. Passing it, even as `null`, returns a single page instead of the full list. |
| `stream` | `Boolean` | Returns an async iterator of pages instead of a promise. |
| `includeTotal` | `Boolean` | Adds `total` to the page. Ask for it on the first page only, since it gets slower as the count grows. |
## Return value
@@ -40,6 +44,8 @@ Each subscription is the object [`onPersistent()`](/Events/onPersistent/#return-
- `contextKeys` (Array | null) and `contextHash` (String | null) describe the stored `context`. The values are never returned, since context often holds secrets. The hash changes whenever a value does.
- `suspendedAt` (Number | null) and `suspendedReason` (String | null) are set when a subscription is [suspended](/Events/onPersistent/#suspended-subscriptions), with `handler_not_found`, `failures`, `no_credit`, or `permission_revoked`.
## Errors
The promise rejects with `{ message, code }`:
| `code` | Meaning |
@@ -51,7 +57,7 @@ The promise rejects with `{ message, code }`:
## Examples
<strong class="example-title">List everything this account is watching</strong>
### List everything this account is watching
```html;events-list
<html>
@@ -78,7 +84,7 @@ The promise rejects with `{ message, code }`:
</html>
```
<strong class="example-title">Find the ones that stopped, and why</strong>
### Find the ones that stopped, and why
```html;events-list-suspended
<html>
+11 -5
View File
@@ -4,9 +4,11 @@ description: List the schedules this caller holds, one page at a time.
platforms: [websites, apps, nodejs, workers]
---
Lists the schedules created with [`puter.events.onSchedule()`](/Events/onSchedule/), and the notifications your app stored to send later with [`puter.notifications.notify()`](/Notifications/notify/#send-it-later).
<div class="info">The Events API is in beta. Event shapes, limits, and behavior may change between releases.</div>
Lists the schedules created with [`puter.events.onSchedule()`](/Events/onSchedule/), and the notifications your app stored to send later with [`puter.notifications.notify()`](/Notifications/notify/#send-it-later). Ended schedules stay in the list for 7 days, with the reason they ended.
Ended schedules stay in the list for 7 days, with the reason they ended.
An app sees only the schedules it created for the user it runs for. An account session, such as the Puter desktop, sees all of the user's schedules, including ones left by apps they no longer use, so that's where to clean up stray schedules. A scoped access token, such as the one in a [`getReadURL()`](/FS/getReadURL/) URL, sees none.
@@ -24,9 +26,11 @@ puter.events.listSchedules(options)
#### `options` (Object) (optional)
- `limit` (Number): Maximum schedules per page. Capped at 200, and defaults to 50.
- `cursor` (String | null): The `cursor` from the previous page. Leave it out, or pass `null`, for the first page.
- `includeTotal` (Boolean): Adds `total`, the number of schedules across every page. Ask for it on the first page only.
| Option | Type | Description |
|--------|------|-------------|
| `limit` | `Number` | Maximum schedules per page. Capped at 200, and defaults to 50. |
| `cursor` | `String \| null` | The `cursor` from the previous page. Leave it out, or pass `null`, for the first page. |
| `includeTotal` | `Boolean` | Adds `total`, the number of schedules across every page. Ask for it on the first page only. |
## Return value
@@ -40,6 +44,8 @@ Pages can be shorter than `limit` before the last one, so keep going until `curs
The `context` a schedule was created with is never returned, since it often holds secrets. The `contextKeys` field lists its key names, and `contextHash` changes whenever a value does.
## Errors
The promise rejects with `{ message, code }`:
| `code` | Meaning |
@@ -53,7 +59,7 @@ The promise rejects with `{ message, code }`:
## Examples
<strong class="example-title">List every schedule, page by page</strong>
### List every schedule, page by page
```html;events-list-schedules
<html>
+4 -2
View File
@@ -4,9 +4,11 @@ description: End a subscription created with puter.events.onLocal().
platforms: [websites, apps, nodejs]
---
Ends a subscription returned by [`puter.events.onLocal()`](/Events/onLocal/).
<div class="info">The Events API is in beta. Event shapes, limits, and behavior may change between releases.</div>
Ends a subscription returned by [`puter.events.onLocal()`](/Events/onLocal/). The handler stops being called immediately, and the server is told if the connection is still open.
The handler stops being called immediately, and the server is told if the connection is still open.
Ending a subscription counts toward its own [unsubscribe rate limit](/rate-limits-and-quotas/#events), not the `subscribe` one. Over that limit `off()` still resolves and the handler still stops, but the server may keep the subscription until the connection closes, and a warning is logged to the console.
@@ -25,7 +27,7 @@ A `Promise` that resolves when the subscription is gone. It never rejects. Calli
## Examples
<strong class="example-title">Watch a directory, then stop watching it</strong>
### Watch a directory, then stop watching it
```html;events-off
<html>
+13 -7
View File
@@ -4,9 +4,11 @@ description: Subscribe to changes on a file, directory, key-value key, or notifi
platforms: [websites, apps, nodejs]
---
Subscribes to a subject and calls `handler` each time something matching it changes.
<div class="info">The Events API is in beta. Event shapes, limits, and behavior may change between releases.</div>
Subscribes to a subject and calls `handler` each time something matching it changes. The subscription belongs to this client's connection. Nothing is stored, nothing runs while the page is closed, and the subscription ends when the connection does. Changes from other devices and regions reach it too. A change made in another region usually arrives a few hundred milliseconds later than a local one. See [Subjects and events](/Events/subjects/) for the subject syntax and the event shape.
The subscription belongs to this client's connection. Nothing is stored, nothing runs while the page is closed, and the subscription ends when the connection does. Changes from other devices and regions reach it too. A change made in another region usually arrives a few hundred milliseconds later than a local one. See [Subjects and events](/Events/subjects/) for the subject syntax and the event shape.
In a Puter worker, a subscription only lasts for one invocation. To react to changes from a worker, use [`onPersistent()`](/Events/onPersistent/) with a published handler.
@@ -28,9 +30,11 @@ Called with `{ event }` for each delivery. See [The event](/Events/subjects/#the
#### `options` (Object) (optional)
- `onError` (Function): Called with `{ message, code }` once the subscription is over. That happens when it can't be restored after a disconnect (see [Reconnects](#reconnects)), or when the server ends it, with `code: 'subscription_ended'` and a `reason` (see [Subscriptions the server ends](#subscriptions-the-server-ends)). The handler isn't called after that. Call `onLocal()` again to resume. Without `onError`, the error is logged to the console.
- `timeout` (Number): How long to wait for the server to confirm the subscription, in milliseconds. Defaults to `30000`.
- `includeValue` (Boolean): For a `kv:` subject, include the key's new value as `event.value`. See [Getting the new value](/Events/subjects/#getting-the-new-value) for when it's left out. Other subjects are refused with `invalid_include_value`.
| Option | Type | Description |
|--------|------|-------------|
| `onError` | `Function` | Called with `{ message, code }` once the subscription is over. That happens when it can't be restored after a disconnect (see [Reconnects](#reconnects)), or when the server ends it, with `code: 'subscription_ended'` and a `reason` (see [Subscriptions the server ends](#subscriptions-the-server-ends)). The handler isn't called after that. Call `onLocal()` again to resume. Without `onError`, the error is logged to the console. |
| `includeValue` | `Boolean` | For a `kv:` subject, include the key's new value as `event.value`. See [Getting the new value](/Events/subjects/#getting-the-new-value) for when it's left out. Other subjects are refused with `invalid_include_value`. |
| `timeout` | `Number` | How long to wait for the server to confirm the subscription, in milliseconds. Defaults to `30000`. |
## Return value
@@ -47,6 +51,8 @@ A `Promise` that resolves, once the server confirms the subscription, to a subsc
- `includeValue` (Boolean): Whether `kv:` deliveries carry the new value.
- `off` (Function): Ends the subscription. See [`subscription.off()`](/Events/off/).
## Errors
The promise rejects with `{ message, code }`:
| `code` | Meaning |
@@ -98,7 +104,7 @@ If the connection is down when this happens, or drops before `onError` is called
## Examples
<strong class="example-title">Watch a directory and print what changes</strong>
### Watch a directory and print what changes
```html;events-watch-folder
<html>
@@ -130,7 +136,7 @@ If the connection is down when this happens, or drops before `onError` is called
</html>
```
<strong class="example-title">React to a file that does not exist yet</strong>
### React to a file that does not exist yet
```html;events-watch-missing
<html>
@@ -163,7 +169,7 @@ If the connection is down when this happens, or drops before `onError` is called
</html>
```
<strong class="example-title">Watch this app's key-value store</strong>
### Watch this app's key-value store
```html;events-watch-kv
<html>
+78 -72
View File
@@ -4,9 +4,11 @@ description: Subscribe to changes with a subscription that keeps running when yo
platforms: [websites, apps, nodejs, workers]
---
Creates a subscription that outlives this connection.
<div class="info">The Events API is in beta. Event shapes, limits, and behavior may change between releases.</div>
Creates a subscription that outlives this connection. It's stored on the account, keeps matching while your app is closed, and runs a handler in an [events worker](/Events/workers/). The handler is either inline code you pass as `handler`, which is published into the signed-in user's own [user scope](/Events/handlers/#user-scope) of your app, or a handler published under a name with [`puter.events.handlers.publish()`](/Events/handlers/). Each event also reaches every connected client. Compare [`puter.events.onLocal()`](/Events/onLocal/), which ends with the page.
It's stored on the account, keeps matching while your app is closed, and runs a handler in an [events worker](/Events/workers/). The handler is either inline code you pass as `handler`, which is published into the signed-in user's own [user scope](/Events/handlers/#user-scope) of your app, or a handler published under a name with [`puter.events.handlers.publish()`](/Events/handlers/). Each event also reaches every connected client. Compare [`puter.events.onLocal()`](/Events/onLocal/), which ends with the page.
The subscription is live right away in the region where it was created. Right after this call resolves, changes made in other regions can take a moment longer to reach it, usually well under a second.
@@ -23,17 +25,78 @@ puter.events.onPersistent(options)
#### `options` (Object) (required)
- `subject` (String) (required): What to watch, in the same form [`onLocal()`](/Events/onLocal/) takes, such as `fs:~/Documents` or `kv:<handle>:*`.
- `handlerName` (String): The published handler to run in an [events worker](/Events/workers/). Up to 128 characters. A subscription made outside an app has no events worker, so its handler runs only in connected clients.
- `handlerScope` (String): Where `handlerName` is looked up, `'app'` or `'user'`. Defaults to `'app'`, the handlers the app's owner published. `'user'` binds to a handler in the signed-in user's own scope, published with `handlers.publish(name, handler, { scope: 'user' })`.
- `queue` (Boolean): Handles events like a work queue. Each event goes to one consumer at a time, and it's offered again if a run never finishes or hits a temporary error. Requires `handlerName` or an inline `handler`. Defaults to `false`. See [Choosing a mode](#choosing-a-mode).
- `handler` (Function | String | Object): The handler code, as a function, a source string, or `{ file: '~/AppData/…/handler.js' }`. Without `handlerName`, the source is sent and published into the signed-in user's own user scope, and it runs for this user's events only. With `handlerName`, only its hash is sent, and the subscription is created only if it matches what's published under that name. A function also runs in this client for each delivery it receives (see [Where the handler runs](#where-the-handler-runs)).
- `context` (Object): Values the handler needs, passed to it as a frozen `ctx`. Up to 4 KB serialized. See [Context is captured once](#context-is-captured-once-up-to-4-kb).
- `expiresAt` (Number | String): When the subscription ends on its own, as unix seconds or an ISO-8601 string. Must be in the future.
- `includeValue` (Boolean): For a `kv:` subject, include the key's new value as `event.value`. See [Getting the new value](/Events/subjects/#getting-the-new-value) for when it's left out. Other subjects are refused with `invalid_include_value`.
- `onError` (Function): Called with `{ message, code }` when this client stops running `handler` because its connection can't be restored (`reauth_required` after a sign-out, `events_connection_failed` otherwise). The subscription itself keeps going in the events worker, and this client takes deliveries again once it reconnects. Only used with a function `handler`. Without it, the stop is logged to the console.
- `delivery` (String): Deprecated. Use `queue` instead. The value `'single'` is the same as `queue: true`, and `'broadcast'` is the default.
- `targets` (Array): Deprecated and ignored.
| Option | Type | Description |
|--------|------|-------------|
| `subject` | `String` | Required. What to watch, in the same form [`onLocal()`](/Events/onLocal/) takes, such as `fs:~/Documents` or `kv:<handle>:*`. |
| `handler` | `Function \| String \| Object` | The handler code, as a function, a source string, or `{ file: '~/AppData/…/handler.js' }`. Without `handlerName`, the source is sent and published into the signed-in user's own user scope, and it runs for this user's events only. With `handlerName`, only its hash is sent, and the subscription is created only if it matches what's published under that name. A function also runs in this client for each delivery it receives (see [Where the handler runs](#where-the-handler-runs)). |
| `handlerName` | `String` | The published handler to run in an [events worker](/Events/workers/). Up to 128 characters. A subscription made outside an app has no events worker, so its handler runs only in connected clients. |
| `context` | `Object` | Values the handler needs, passed to it as a frozen `ctx`. Up to 4 KB serialized. See [Context is captured once](#context-is-captured-once-up-to-4-kb). |
| `queue` | `Boolean` | Handles events like a work queue. Each event goes to one consumer at a time, and it's offered again if a run never finishes or hits a temporary error. Requires `handlerName` or an inline `handler`. Defaults to `false`. See [Choosing a mode](#choosing-a-mode). |
| `includeValue` | `Boolean` | For a `kv:` subject, include the key's new value as `event.value`. See [Getting the new value](/Events/subjects/#getting-the-new-value) for when it's left out. Other subjects are refused with `invalid_include_value`. |
| `expiresAt` | `Number \| String` | When the subscription ends on its own, as unix seconds or an ISO-8601 string. Must be in the future. |
| `handlerScope` | `String` | Where `handlerName` is looked up, `'app'` or `'user'`. Defaults to `'app'`, the handlers the app's owner published. With `'user'`, it binds to a handler in the signed-in user's own scope, published with `handlers.publish(name, handler, { scope: 'user' })`. |
| `onError` | `Function` | Called with `{ message, code }` when this client stops running `handler` because its connection can't be restored (`reauth_required` after a sign-out, `events_connection_failed` otherwise). The subscription itself keeps going in the events worker, and this client takes deliveries again once it reconnects. Only used with a function `handler`. Without it, the stop is logged to the console. |
| `delivery` | `String` | Deprecated. Use `queue` instead. The value `'single'` is the same as `queue: true`, and `'broadcast'` is the default. |
| `targets` | `Array` | Deprecated and ignored. |
## Return value
A `Promise` that resolves to the subscription:
- `subId` (String): Its id, which [`puter.events.update()`](/Events/update/) and [`puter.events.unsubscribe()`](/Events/unsubscribe/) take. It never changes.
- `subject` (String): For `kv:` and `notif:`, the subject in full form, so `kv:cart` comes back as `kv:<appId>:cart`. For `fs:`, as you passed it, except a relative path comes back resolved the same way [`onLocal()`](/Events/onLocal/) returns it.
- `anchor`, `match`, `op`: As [`onLocal()`](/Events/onLocal/#return-value) returns them.
- `queue` (Boolean), `handlerName` (String | null), `includeValue` (Boolean). An inline handler comes back as its server-assigned `handlerName`, which starts with `@`.
- `handlerScope` (String): `'user'` when the subscription is bound to a handler in the user's own scope. Absent otherwise.
- `appUid` (String | null): The app that created it, or `null` if it was created outside an app.
- `contextKeys` (Array | null), `contextHash` (String | null): The key names and a hash of the stored context, never its values.
- `createdAt`, `expiresAt` (Number | null): Unix seconds.
- `suspendedAt` (Number | null), `suspendedReason` (String | null): Set when the subscription is [suspended](#suspended-subscriptions).
- `off()` (Function): Ends the subscription and stops running its handler here. Same as [`puter.events.unsubscribe(subId)`](/Events/unsubscribe/).
## Errors
The promise rejects with `{ message, code }`:
| `code` | Meaning |
| --- | --- |
| `events_handler_conflict` | The inline handler couldn't be confirmed after a concurrent publish. Try again. |
| `events_handler_hash_mismatch` | The published handler isn't the source passed as `handler`. |
| `events_handler_not_found` | Nothing is published under `handlerName` in that scope, or source was supplied to check a named handler outside an app. |
| `events_handler_hash_unavailable` | This environment has no `crypto.subtle`, so `handler` can't be hashed. Pass `handlerName` alone. |
| `events_handler_invalid` | `handler` isn't a function, a nonempty source string, or `{ file }`. |
| `invalid_subject` | The subject is empty, not a string, or can't be parsed, or it's a `notif:` subject and this server has notification events turned off. |
| `auth_canceled` | Nobody was signed in, and the user closed the sign-in without finishing it. |
| `events_user_handlers_disabled` | Publishing into a user scope isn't turned on for this server. |
| `events_handler_forbidden` | The call can't publish into a user scope: it came from a scoped access token, a temporary account, or on behalf of a different app. |
| `insufficient_funds` | Publishing into a user scope needs credit on a hosted Puter server, and the user has none. Arrives as HTTP 402. |
| `forbidden` | The user already holds as many [worker units](/rate-limits-and-quotas/#worker-units) as their plan allows, so a new user scope can't be created. |
| `events_handler_limit` | The user scope already holds the [maximum number of handlers](/rate-limits-and-quotas/#handlers). |
| `events_handler_too_large` | The handler is over 64 KB. |
| `events_worker_too_large` | The user scope's handlers would exceed 1 MB combined. |
| `events_handler_name_invalid` | `handlerName` has characters that aren't allowed, or starts with `@`, which is reserved for inline handlers. |
| `events_handler_free_variable` | The handler uses an outside variable. The message names it. |
| `events_handler_invalid` | `handler` isn't a function, a source string, or `{ file }`. |
| `events_handler_hash_unavailable` | This environment has no `crypto.subtle`, so `handler` can't be hashed. Pass `handlerName` alone. |
| `events_handler_not_found` | Nothing is published under `handlerName` in that scope of this app. |
| `events_handler_hash_mismatch` | The published handler isn't the source you passed as `handler`. |
| `events_handler_required` | `queue: true` without a `handlerName` or an inline `handler`. |
| `events_background_consent_required` | An app subscribed with a handler, and the user hasn't granted `events:background`. |
| `events_context_too_large` | The serialized `context` is over 4 KB. |
| `events_context_invalid` | `context` isn't JSON-serializable. |
| `bad_request` | `queue` isn't a boolean, `delivery` isn't `'broadcast'` or `'single'`, the two disagree, or `handlerName` isn't a string or is over 128 characters. |
| `invalid_expires_at` | `expiresAt` isn't a future time. |
| `invalid_include_value` | `includeValue` isn't a boolean, or the subject isn't `kv:`. |
| `invalid_subject_op`, `invalid_subject_audience`, `invalid_subject_pattern`, `invalid_kv_pattern`, `invalid_kv_handle_key`, `events_cross_app_disabled`, `events_kv_handles_disabled`, `forbidden` | As on [`onLocal()`](/Events/onLocal/#errors). |
| `subject_does_not_exist` | The subject doesn't exist, or this account can't read it. |
| `events_subscription_limit` | The account or app is at its [persistent subscription limit](/rate-limits-and-quotas/#events). |
| `events_value_too_large` | A field is longer than can be stored, such as an app id over 40 characters. |
| `events_durable_requires_account` | Temporary (anonymous) accounts only get session subscriptions. Scoped access tokens, such as the one in a [`getReadURL()`](/FS/getReadURL/) URL, get no persistent subscriptions either, whether the account or an app created them. |
| `too_many_requests` | Over the subscribe rate limit. |
| `events_disabled` | Events aren't enabled on this server. |
| `events_failed` | The server sent a response the SDK couldn't read. |
With a `{ file }` handler, errors from [`puter.fs.read()`](/FS/read/) also pass through.
## Background delivery needs consent
@@ -163,68 +226,11 @@ Clients connect to the nearest region. Events reach a client wherever it's conne
- Undelivered events are held in the region where the change happened. If that region goes down, only what it was holding is lost.
- Order is kept within a region and is best effort across regions. Without `queue`, coalescing (250 ms) also runs per region, so two quick writes can arrive as one event nearby and as two farther away.
## Return value
A `Promise` that resolves to the subscription:
- `subId` (String): Its id, which [`puter.events.update()`](/Events/update/) and [`puter.events.unsubscribe()`](/Events/unsubscribe/) take. It never changes.
- `subject` (String): For `kv:` and `notif:`, the subject in full form, so `kv:cart` comes back as `kv:<appId>:cart`. For `fs:`, as you passed it, except a relative path comes back resolved the same way [`onLocal()`](/Events/onLocal/) returns it.
- `anchor`, `match`, `op`: As [`onLocal()`](/Events/onLocal/#return-value) returns them.
- `queue` (Boolean), `handlerName` (String | null), `includeValue` (Boolean). An inline handler comes back as its server-assigned `handlerName`, which starts with `@`.
- `handlerScope` (String): `'user'` when the subscription is bound to a handler in the user's own scope. Absent otherwise.
- `appUid` (String | null): The app that created it, or `null` if it was created outside an app.
- `contextKeys` (Array | null), `contextHash` (String | null): The key names and a hash of the stored context, never its values.
- `createdAt`, `expiresAt` (Number | null): Unix seconds.
- `suspendedAt` (Number | null), `suspendedReason` (String | null): Set when the subscription is [suspended](#suspended-subscriptions).
- `off()` (Function): Ends the subscription and stops running its handler here. Same as [`puter.events.unsubscribe(subId)`](/Events/unsubscribe/).
The promise rejects with `{ message, code }`:
| `code` | Meaning |
| --- | --- |
| `events_handler_conflict` | The inline handler couldn't be confirmed after a concurrent publish. Try again. |
| `events_handler_hash_mismatch` | The published handler isn't the source passed as `handler`. |
| `events_handler_not_found` | Nothing is published under `handlerName` in that scope, or source was supplied to check a named handler outside an app. |
| `events_handler_hash_unavailable` | This environment has no `crypto.subtle`, so `handler` can't be hashed. Pass `handlerName` alone. |
| `events_handler_invalid` | `handler` isn't a function, a nonempty source string, or `{ file }`. |
| `invalid_subject` | The subject is empty, not a string, or can't be parsed, or it's a `notif:` subject and this server has notification events turned off. |
| `auth_canceled` | Nobody was signed in, and the user closed the sign-in without finishing it. |
| `events_user_handlers_disabled` | Publishing into a user scope isn't turned on for this server. |
| `events_handler_forbidden` | The call can't publish into a user scope: it came from a scoped access token, a temporary account, or on behalf of a different app. |
| `insufficient_funds` | Publishing into a user scope needs credit on a hosted Puter server, and the user has none. Arrives as HTTP 402. |
| `forbidden` | The user already holds as many [worker units](/rate-limits-and-quotas/#worker-units) as their plan allows, so a new user scope can't be created. |
| `events_handler_limit` | The user scope already holds the [maximum number of handlers](/rate-limits-and-quotas/#handlers). |
| `events_handler_too_large` | The handler is over 64 KB. |
| `events_worker_too_large` | The user scope's handlers would exceed 1 MB combined. |
| `events_handler_name_invalid` | `handlerName` has characters that aren't allowed, or starts with `@`, which is reserved for inline handlers. |
| `events_handler_free_variable` | The handler uses an outside variable. The message names it. |
| `events_handler_invalid` | `handler` isn't a function, a source string, or `{ file }`. |
| `events_handler_hash_unavailable` | This environment has no `crypto.subtle`, so `handler` can't be hashed. Pass `handlerName` alone. |
| `events_handler_not_found` | Nothing is published under `handlerName` in that scope of this app. |
| `events_handler_hash_mismatch` | The published handler isn't the source you passed as `handler`. |
| `events_handler_required` | `queue: true` without a `handlerName` or an inline `handler`. |
| `events_background_consent_required` | An app subscribed with a handler, and the user hasn't granted `events:background`. |
| `events_context_too_large` | The serialized `context` is over 4 KB. |
| `events_context_invalid` | `context` isn't JSON-serializable. |
| `bad_request` | `queue` isn't a boolean, `delivery` isn't `'broadcast'` or `'single'`, the two disagree, or `handlerName` isn't a string or is over 128 characters. |
| `invalid_expires_at` | `expiresAt` isn't a future time. |
| `invalid_include_value` | `includeValue` isn't a boolean, or the subject isn't `kv:`. |
| `invalid_subject_op`, `invalid_subject_audience`, `invalid_subject_pattern`, `invalid_kv_pattern`, `invalid_kv_handle_key`, `events_cross_app_disabled`, `events_kv_handles_disabled`, `forbidden` | As on [`onLocal()`](/Events/onLocal/#return-value). |
| `subject_does_not_exist` | The subject doesn't exist, or this account can't read it. |
| `events_subscription_limit` | The account or app is at its [persistent subscription limit](/rate-limits-and-quotas/#events). |
| `events_value_too_large` | A field is longer than can be stored, such as an app id over 40 characters. |
| `events_durable_requires_account` | Temporary (anonymous) accounts only get session subscriptions. Scoped access tokens, such as the one in a [`getReadURL()`](/FS/getReadURL/) URL, get no persistent subscriptions either, whether the account or an app created them. |
| `too_many_requests` | Over the subscribe rate limit. |
| `events_disabled` | Events aren't enabled on this server. |
| `events_failed` | The server sent a response the SDK couldn't read. |
With a `{ file }` handler, errors from [`puter.fs.read()`](/FS/read/) also pass through.
## Examples
The first example is the inline form, which any app can use for the signed-in user. The others bind to a handler the app's owner published, so they run in your own app or from Node.js signed in as its developer.
<strong class="example-title">Watch a folder with an inline handler</strong>
### Watch a folder with an inline handler
```js
await puter.perms.request('backgroundEvents');
@@ -242,7 +248,7 @@ await puter.events.unsubscribe(sub.subId);
The handler is stored in the user's scope under `sub.handlerName`, and keeps running for this user until the subscription ends. After the subscription ends, Puter removes the handler about a day later, once nothing is bound to it. You can remove it sooner, as [Clean Up Background Work](/recipes/clean-up-background-work/#remove-a-user-scope) shows.
<strong class="example-title">Watch a folder with a handler the app's owner published</strong>
### Watch a folder with a handler the app's owner published
Publish once as the developer to ship one shared handler to every user.
@@ -267,7 +273,7 @@ const sub = await puter.events.onPersistent({
await puter.events.unsubscribe(sub.subId);
```
<strong class="example-title">Bind to the exact source you wrote against</strong>
### Bind to the exact source you wrote against
```js
const handler = ({ event, ctx }) => console.log(ctx.label, event.path);
+95 -89
View File
@@ -4,11 +4,13 @@ description: Run your app's handler at an interval, on a cron expression in a ti
platforms: [websites, apps, nodejs, workers]
---
Runs a handler on a timer.
<div class="info">The Events API is in beta. Event shapes, limits, and behavior may change between releases.</div>
<div class="info">Schedules are available on puter.com. A self-hosted Puter server answers <code>events_disabled</code>.</div>
Runs a handler on a timer. A schedule can run at an interval, on a cron expression in a time zone, or once at a set time. It's stored on the user's account and runs in an [events worker](/Events/workers/), whether or not your app is open. It never runs in the client that created it.
A schedule can run at an interval, on a cron expression in a time zone, or once at a set time. It's stored on the user's account and runs in an [events worker](/Events/workers/), whether or not your app is open. It never runs in the client that created it.
The handler is either inline code you pass as `handler`, or a handler published under a name with [`puter.events.handlers.publish()`](/Events/handlers/). Inline code is published into the signed-in user's own [user scope](/Events/handlers/#user-scope) of your app and runs for that user only. A named handler published by the app's owner is shared by every user of the app.
@@ -29,20 +31,87 @@ puter.events.onSchedule(options)
Give exactly one of `every`, `cron` or `at`.
- `every` (Number | String): Run at this interval, in milliseconds or as a duration such as `'30m'`, `'6h'` or `'1d'`. The units are `s`, `m`, `h`, `d` and `w`. The interval must be a whole number of seconds, at least your plan's [minimum interval](#how-often-a-schedule-can-run), and at most 366 days.
- `cron` (String): Run on a [cron expression](#cron-expressions), such as `'0 9 * * 1-5'` for 09:00 on weekdays.
- `tz` (String): The IANA time zone the `cron` expression runs in, such as `'America/New_York'`. Defaults to `'UTC'`. Only allowed with `cron`. See [Time zones and daylight saving time](#time-zones-and-daylight-saving-time).
- `at` (Number | String | Date): Run once, at this [time](#times). It must be at least 1 second and at most 366 days ahead. A schedule with `at` takes no `startAt`, `expiresAt` or `maxRuns`.
- `startAt` (Number | String | Date): For `every`, the first run. Without it, the first run is one interval after this call. A `startAt` in the past sets where the intervals line up, and the first run is the next one after this call. For example, `every: '1d'` with `startAt: '2026-01-01'` runs at midnight UTC every day. For `cron`, the earliest time the schedule may run. At most 366 days ahead.
- `expiresAt` (Number | String | Date): The last time the schedule may run. A run due at exactly this time still runs.
- `maxRuns` (Number): How many slots the schedule has, from 1 to 100,000. It ends at its `maxRuns`-th slot counted from the first. It counts slots, not runs that happened, so slots skipped while the schedule was behind or suspended (see [When a schedule runs](#when-a-schedule-runs)) still count, and the retries of one slot count once. With `expiresAt` too, the one that comes first ends the schedule.
- `handler` (Function | String | Object): The handler code, as a function, a source string, or `{ file: '~/AppData/…/handler.js' }`. Required unless you pass `handlerName`. Without `handlerName`, the source is sent and published into the signed-in user's own user scope, and every run calls it. With `handlerName`, only its hash is sent, and the schedule is created only if it matches what's published under that name. It never runs in this client.
- `handlerName` (String): The published handler each run calls. Required unless you pass `handler`.
- `handlerScope` (String): Where `handlerName` is looked up, `'app'` or `'user'`. Defaults to `'app'`, the handlers the app's owner published. `'user'` binds to a handler the signed-in user's scope holds, published with `handlers.publish(name, handler, { scope: 'user' })`.
- `handlerHash` (String): The SHA-256 hex digest of the handler source, in place of `handler`, to check it against `handlerName`.
- `context` (Object): Values the handler needs, passed to every run as a frozen `ctx`. Up to 4 KB serialized. It's read once, at this call. To replace it, use [`updateSchedule()`](/Events/updateSchedule/).
| Option | Type | Description |
|--------|------|-------------|
| `every` | `Number \| String` | Run at this interval, in milliseconds or as a duration such as `'30m'`, `'6h'` or `'1d'`. The units are `s`, `m`, `h`, `d` and `w`. The interval must be a whole number of seconds, at least your plan's [minimum interval](#how-often-a-schedule-can-run), and at most 366 days. |
| `cron` | `String` | Run on a [cron expression](#cron-expressions), such as `'0 9 * * 1-5'` for 09:00 on weekdays. |
| `at` | `Number \| String \| Date` | Run once, at this [time](#times). It must be at least 1 second and at most 366 days ahead. A schedule with `at` takes no `startAt`, `expiresAt` or `maxRuns`. |
| `handler` | `Function \| String \| Object` | Required unless you pass `handlerName`. The handler code, as a function, a source string, or `{ file: '~/AppData/…/handler.js' }`. Without `handlerName`, the source is sent and published into the signed-in user's own user scope, and every run calls it. With `handlerName`, only its hash is sent, and the schedule is created only if it matches what's published under that name. It never runs in this client. |
| `handlerName` | `String` | Required unless you pass `handler`. The published handler each run calls. |
| `context` | `Object` | Values the handler needs, passed to every run as a frozen `ctx`. Up to 4 KB serialized. It's read once, at this call. To replace it, use [`updateSchedule()`](/Events/updateSchedule/). |
| `tz` | `String` | The IANA time zone the `cron` expression runs in, such as `'America/New_York'`. Defaults to `'UTC'`. Only allowed with `cron`. See [Time zones and daylight saving time](#time-zones-and-daylight-saving-time). |
| `startAt` | `Number \| String \| Date` | For `every`, the first run. Without it, the first run is one interval after this call. A `startAt` in the past sets where the intervals line up, and the first run is the next one after this call. For example, `every: '1d'` with `startAt: '2026-01-01'` runs at midnight UTC every day. For `cron`, the earliest time the schedule may run. At most 366 days ahead. |
| `expiresAt` | `Number \| String \| Date` | The last time the schedule may run. A run due at exactly this time still runs. |
| `maxRuns` | `Number` | How many slots the schedule has, from 1 to 100,000. It ends at its `maxRuns`-th slot counted from the first. It counts slots, not runs that happened, so slots skipped while the schedule was behind or suspended (see [When a schedule runs](#when-a-schedule-runs)) still count, and the retries of one slot count once. With `expiresAt` too, the one that comes first ends the schedule. |
| `handlerScope` | `String` | Where `handlerName` is looked up, `'app'` or `'user'`. Defaults to `'app'`, the handlers the app's owner published. With `'user'`, it binds to a handler the signed-in user's scope holds, published with `handlers.publish(name, handler, { scope: 'user' })`. |
| `handlerHash` | `String` | The SHA-256 hex digest of the handler source, in place of `handler`, to check it against `handlerName`. |
### Times
## Return value
A `Promise` that resolves to the schedule. All times are in milliseconds since the epoch.
- `scheduleId` (String): Its id, which [`getSchedule()`](/Events/getSchedule/), [`updateSchedule()`](/Events/updateSchedule/) and [`removeSchedule()`](/Events/removeSchedule/) take.
- `kind` (String): `'recurring'` for `every` and `cron`, `'once'` for `at`, and `'deferred'` for a notification sent later with [`notify()`](/Notifications/notify/#send-it-later).
- `appUid` (String): The app that created it.
- `handlerName` (String | null): The handler each run calls, or `null` once the schedule has ended. For a schedule created with an inline `handler`, it's the name Puter gave the handler, which starts with `@`.
- `handlerScope` (String): `'user'` when the handler is in the user's own [user scope](/Events/handlers/#user-scope). Absent for an app handler.
- `contextKeys` (Array | null), `contextHash` (String | null): The key names and a hash of the stored context, never its values. The `contextKeys` field is `null` when there's no context, and once the schedule has ended.
- `every` (Number | null): The interval, in milliseconds, of an `every` schedule.
- `cron` (String | null): The expression of a `cron` schedule.
- `tz` (String): The time zone of a `cron` schedule, and `'UTC'` for the others.
- `startAt` (Number): The first time it may run. For `at`, its only run.
- `endsAt` (Number | null): The last time it may run, from `expiresAt` or `maxRuns`. For `at`, its only run.
- `state` (String): `'active'`, `'suspended'`, `'sending'`, or `'ended'`. A delayed notification is `'sending'` during a send attempt. A failed attempt can return it to `'active'` before retrying.
- `suspendedReason` (String | null): Why it's [suspended](#suspended-and-ended-schedules).
- `endReason` (String | null), `endedAt` (Number | null): Why and when it [ended](#suspended-and-ended-schedules).
- `nextRunAt` (Number | null): The next slot of the schedule, worked out from its definition and the clock. A late or retried run for an earlier slot can still happen first. After the last slot is due, it stays at that slot until the run for it is done. It's `null` while the schedule is suspended or sending, and once it has ended.
- `createdAt` (Number): When it was created.
- `off()` (Function): Removes the schedule. Same as [`puter.events.removeSchedule(scheduleId)`](/Events/removeSchedule/). Only on the object `onSchedule()` returns.
## Errors
The promise rejects with `{ message, code }`:
| `code` | Meaning |
| --- | --- |
| `events_value_too_large` | A field is longer than can be stored. |
| `events_handler_conflict` | The inline handler couldn't be confirmed after a concurrent publish. Try again. |
| `invalid_request` | `options` isn't an object. |
| `events_handler_required` | There's neither a `handler` nor a `handlerName`. |
| `events_user_handlers_disabled` | Publishing into a user scope isn't turned on for this server. |
| `events_handler_forbidden` | The call can't publish into a user scope: it came from a scoped access token, a temporary account, or on behalf of a different app. |
| `insufficient_funds` | Publishing into a user scope needs credit on a hosted Puter server, and the user has none. Arrives as HTTP 402. |
| `forbidden` | The user already holds as many [worker units](/rate-limits-and-quotas/#worker-units) as their plan allows, so a new user scope can't be created. |
| `events_handler_limit` | The user scope already holds the [maximum number of handlers](/rate-limits-and-quotas/#handlers). |
| `events_handler_too_large` | The handler is over 64 KB. |
| `events_worker_too_large` | The user scope's handlers would exceed 1 MB combined. |
| `events_handler_name_invalid` | `handlerName` is empty, too long, has characters that aren't allowed, or starts with `@`, which is reserved for inline handlers. |
| `events_handler_free_variable` | The handler uses an outside variable. The message names it. |
| `events_handler_invalid` | `handler` isn't a function, a source string, or `{ file }`. |
| `events_handler_hash_unavailable` | This environment has no `crypto.subtle`, so `handler` can't be hashed. Pass `handlerName` alone. |
| `events_context_invalid` | `context` isn't JSON-serializable. |
| `events_context_too_large` | The serialized `context` is over 4 KB. |
| `auth_canceled` | Nobody was signed in, and the user closed the sign-in without finishing it. |
| `events_schedule_app_required` | The call wasn't made by an app, for example from Node.js with an account token. |
| `events_durable_requires_account` | The call came from a scoped access token, such as the one in a [`getReadURL()`](/FS/getReadURL/) URL, or from a temporary (guest) account. |
| `too_many_requests` | Over the create rate limit, which is shared with subscribing. |
| `events_background_consent_required` | The user hasn't granted your app `events:background`. |
| `events_schedule_invalid` | An option is malformed. For example, more than one of `every`, `cron` and `at`, an `every` that isn't a whole number of seconds, a time with no zone, an `at` less than 1 second or more than 366 days ahead, an unsupported cron expression, an unknown `tz`, or `tz` without `cron`. The message says which. |
| `events_schedule_never_fires` | The schedule would never run. Its first run or its `startAt` is more than 366 days away, or it ends before its first run. |
| `events_schedule_too_frequent` | It would run more often than your plan's [minimum interval](#how-often-a-schedule-can-run). |
| `events_schedule_too_deep` | The call was made from a handler at the end of a [handler chain](/Events/onPersistent/#handlers-that-trigger-handlers), so the schedule could never run. |
| `bad_request` | `handlerName` is empty or over 128 characters, `handlerHash` isn't a SHA-256 hex digest, or `handlerScope` isn't `'app'` or `'user'`. |
| `events_handler_not_found` | Nothing is published under `handlerName` in that scope. The schedule isn't created. |
| `events_handler_hash_mismatch` | The published handler isn't the source you passed as `handler`. |
| `events_schedule_limit` | The user holds as many schedules as their plan allows, for your app or in total. |
| `events_schedule_budget` | The schedule would make your app's schedules, or all of the user's schedules, run more times an hour than their plan allows. |
| `events_schedule_busy` | Puter is checking too many cron expressions at once. Try again in a moment. |
| `events_disabled` | Schedules aren't available on this server, as on self-hosted servers. |
| `events_failed` | The server sent a response the SDK couldn't read. |
With a `{ file }` handler, errors from [`puter.fs.read()`](/FS/read/) also pass through.
## Times
The `at`, `startAt` and `expiresAt` options each take one of these:
@@ -144,15 +213,15 @@ A run's `event` carries:
| Field | Type | Description |
| --- | --- | --- |
| `subject` | String | `schedule:<scheduleId>`. |
| `op` | String | Always `'tick'`. |
| `id` | String | `<scheduleId>:<scheduledFor>`. The same on every attempt at one run, so use it to skip work you've already done. |
| `scheduleId` | String | The schedule this run belongs to. |
| `scheduledFor` | Number | The slot this run is for, in milliseconds since the epoch. |
| `firedAt` | Number | When this attempt was sent to the handler, in milliseconds since the epoch. |
| `missed` | Number | Slots skipped since the last run, for example while the schedule was suspended. Only this run happens for them. |
| `missedCapped` | Boolean | Present, and `true`, when `missed` stopped counting at 1,000. |
| `attempt` | Number | Attempts at this run, this one included. `1` on the first try. |
| `subject` | `String` | `schedule:<scheduleId>`. |
| `op` | `String` | Always `'tick'`. |
| `id` | `String` | `<scheduleId>:<scheduledFor>`. The same on every attempt at one run, so use it to skip work you've already done. |
| `scheduleId` | `String` | The schedule this run belongs to. |
| `scheduledFor` | `Number` | The slot this run is for, in milliseconds since the epoch. |
| `firedAt` | `Number` | When this attempt was sent to the handler, in milliseconds since the epoch. |
| `missed` | `Number` | Slots skipped since the last run, for example while the schedule was suspended. Only this run happens for them. |
| `missedCapped` | `Boolean` | Present, and `true`, when `missed` stopped counting at 1,000. |
| `attempt` | `Number` | Attempts at this run, this one included. `1` on the first try. |
The `user` binding is valid for 15 minutes, so use it only during the run. Writes made through `user` count toward the same [handler chain](/Events/onPersistent/#handlers-that-trigger-handlers) limit as a subscription's, starting from the depth of the call that created the schedule.
@@ -208,74 +277,11 @@ An ended schedule never runs again. It has `state: 'ended'` and an `endReason`,
When schedules end with `permission_revoked`, the user's app gets an `app.events.ended` notification about them, which you can read with [`puter.events.fetch()`](/Events/fetch/).
## Return value
A `Promise` that resolves to the schedule. All times are in milliseconds since the epoch.
- `scheduleId` (String): Its id, which [`getSchedule()`](/Events/getSchedule/), [`updateSchedule()`](/Events/updateSchedule/) and [`removeSchedule()`](/Events/removeSchedule/) take.
- `kind` (String): `'recurring'` for `every` and `cron`, `'once'` for `at`, and `'deferred'` for a notification sent later with [`notify()`](/Notifications/notify/#send-it-later).
- `appUid` (String): The app that created it.
- `handlerName` (String | null): The handler each run calls, or `null` once the schedule has ended. For a schedule created with an inline `handler`, it's the name Puter gave the handler, which starts with `@`.
- `handlerScope` (String): `'user'` when the handler is in the user's own [user scope](/Events/handlers/#user-scope). Absent for an app handler.
- `contextKeys` (Array | null), `contextHash` (String | null): The key names and a hash of the stored context, never its values. The `contextKeys` field is `null` when there's no context, and once the schedule has ended.
- `every` (Number | null): The interval, in milliseconds, of an `every` schedule.
- `cron` (String | null): The expression of a `cron` schedule.
- `tz` (String): The time zone of a `cron` schedule, and `'UTC'` for the others.
- `startAt` (Number): The first time it may run. For `at`, its only run.
- `endsAt` (Number | null): The last time it may run, from `expiresAt` or `maxRuns`. For `at`, its only run.
- `state` (String): `'active'`, `'suspended'`, `'sending'`, or `'ended'`. A delayed notification is `'sending'` during a send attempt. A failed attempt can return it to `'active'` before retrying.
- `suspendedReason` (String | null): Why it's [suspended](#suspended-and-ended-schedules).
- `endReason` (String | null), `endedAt` (Number | null): Why and when it [ended](#suspended-and-ended-schedules).
- `nextRunAt` (Number | null): The next slot of the schedule, worked out from its definition and the clock. A late or retried run for an earlier slot can still happen first. After the last slot is due, it stays at that slot until the run for it is done. It's `null` while the schedule is suspended or sending, and once it has ended.
- `createdAt` (Number): When it was created.
- `off()` (Function): Removes the schedule. Same as [`puter.events.removeSchedule(scheduleId)`](/Events/removeSchedule/). Only on the object `onSchedule()` returns.
The promise rejects with `{ message, code }`:
| `code` | Meaning |
| --- | --- |
| `events_value_too_large` | A field is longer than can be stored. |
| `events_handler_conflict` | The inline handler couldn't be confirmed after a concurrent publish. Try again. |
| `invalid_request` | `options` isn't an object. |
| `events_handler_required` | There's neither a `handler` nor a `handlerName`. |
| `events_user_handlers_disabled` | Publishing into a user scope isn't turned on for this server. |
| `events_handler_forbidden` | The call can't publish into a user scope: it came from a scoped access token, a temporary account, or on behalf of a different app. |
| `insufficient_funds` | Publishing into a user scope needs credit on a hosted Puter server, and the user has none. Arrives as HTTP 402. |
| `forbidden` | The user already holds as many [worker units](/rate-limits-and-quotas/#worker-units) as their plan allows, so a new user scope can't be created. |
| `events_handler_limit` | The user scope already holds the [maximum number of handlers](/rate-limits-and-quotas/#handlers). |
| `events_handler_too_large` | The handler is over 64 KB. |
| `events_worker_too_large` | The user scope's handlers would exceed 1 MB combined. |
| `events_handler_name_invalid` | `handlerName` is empty, too long, has characters that aren't allowed, or starts with `@`, which is reserved for inline handlers. |
| `events_handler_free_variable` | The handler uses an outside variable. The message names it. |
| `events_handler_invalid` | `handler` isn't a function, a source string, or `{ file }`. |
| `events_handler_hash_unavailable` | This environment has no `crypto.subtle`, so `handler` can't be hashed. Pass `handlerName` alone. |
| `events_context_invalid` | `context` isn't JSON-serializable. |
| `events_context_too_large` | The serialized `context` is over 4 KB. |
| `auth_canceled` | Nobody was signed in, and the user closed the sign-in without finishing it. |
| `events_schedule_app_required` | The call wasn't made by an app, for example from Node.js with an account token. |
| `events_durable_requires_account` | The call came from a scoped access token, such as the one in a [`getReadURL()`](/FS/getReadURL/) URL, or from a temporary (guest) account. |
| `too_many_requests` | Over the create rate limit, which is shared with subscribing. |
| `events_background_consent_required` | The user hasn't granted your app `events:background`. |
| `events_schedule_invalid` | An option is malformed. For example, more than one of `every`, `cron` and `at`, an `every` that isn't a whole number of seconds, a time with no zone, an `at` less than 1 second or more than 366 days ahead, an unsupported cron expression, an unknown `tz`, or `tz` without `cron`. The message says which. |
| `events_schedule_never_fires` | The schedule would never run. Its first run or its `startAt` is more than 366 days away, or it ends before its first run. |
| `events_schedule_too_frequent` | It would run more often than your plan's [minimum interval](#how-often-a-schedule-can-run). |
| `events_schedule_too_deep` | The call was made from a handler at the end of a [handler chain](/Events/onPersistent/#handlers-that-trigger-handlers), so the schedule could never run. |
| `bad_request` | `handlerName` is empty or over 128 characters, `handlerHash` isn't a SHA-256 hex digest, or `handlerScope` isn't `'app'` or `'user'`. |
| `events_handler_not_found` | Nothing is published under `handlerName` in that scope. The schedule isn't created. |
| `events_handler_hash_mismatch` | The published handler isn't the source you passed as `handler`. |
| `events_schedule_limit` | The user holds as many schedules as their plan allows, for your app or in total. |
| `events_schedule_budget` | The schedule would make your app's schedules, or all of the user's schedules, run more times an hour than their plan allows. |
| `events_schedule_busy` | Puter is checking too many cron expressions at once. Try again in a moment. |
| `events_disabled` | Schedules aren't available on this server, as on self-hosted servers. |
| `events_failed` | The server sent a response the SDK couldn't read. |
With a `{ file }` handler, errors from [`puter.fs.read()`](/FS/read/) also pass through.
## Examples
The handler is published once, by the app's developer, from a deploy script or the browser console. The schedule is created from the app, for each user.
<strong class="example-title">Run a handler on weekday mornings in the user's time zone</strong>
### Run a handler on weekday mornings in the user's time zone
```js
// Deploy script, run as the app's developer
@@ -308,7 +314,7 @@ const schedule = await puter.events.onSchedule({
if (schedule.nextRunAt !== null) console.log(`next digest at ${new Date(schedule.nextRunAt).toString()}`);
```
<strong class="example-title">Run once, an hour from now</strong>
### Run once, an hour from now
```js
const reminder = await puter.events.onSchedule({
@@ -324,7 +330,7 @@ await puter.events.updateSchedule(reminder.scheduleId, { at: Date.now() + 2 * 60
await reminder.off();
```
<strong class="example-title">Run every 6 hours, on the hour, 28 times</strong>
### Run every 6 hours, on the hour, 28 times
```js
await puter.events.onSchedule({
+6 -2
View File
@@ -4,9 +4,11 @@ description: End a schedule, or cancel a notification stored to send later.
platforms: [websites, apps, nodejs, workers]
---
Ends a schedule created with [`puter.events.onSchedule()`](/Events/onSchedule/).
<div class="info">The Events API is in beta. Event shapes, limits, and behavior may change between releases.</div>
Ends a schedule created with [`puter.events.onSchedule()`](/Events/onSchedule/). It doesn't run again, and it stays in [`listSchedules()`](/Events/listSchedules/) for 7 days with `endReason: 'removed'`. A run that already started isn't stopped.
It doesn't run again, and it stays in [`listSchedules()`](/Events/listSchedules/) for 7 days with `endReason: 'removed'`. A run that already started isn't stopped.
It also cancels a notification your app stored to send later with [`puter.notifications.notify()`](/Notifications/notify/#send-it-later), the same as [`puter.notifications.cancel()`](/Notifications/cancel/).
@@ -30,6 +32,8 @@ A `Promise` that resolves when the schedule has ended.
An app can only remove schedules it created. An account session can remove any of the user's schedules, including ones left by apps they no longer use. A scoped access token can't remove any.
## Errors
An id this caller doesn't hold, or a schedule that already ended, is reported as not existing, so removing a schedule twice rejects the second time. With `events_schedule_sending`, `auth_canceled`, `too_many_requests` or `events_disabled`, nothing was removed. When the call fails any other way, such as a network error or `events_failed`, the removal may still have happened, so read the schedule again with [`getSchedule()`](/Events/getSchedule/) to find out.
It rejects with `{ message, code }`:
@@ -45,7 +49,7 @@ It rejects with `{ message, code }`:
## Examples
<strong class="example-title">Cancel a notification, then read it</strong>
### Cancel a notification, then read it
```html;events-remove-schedule
<html>
+22 -20
View File
@@ -4,9 +4,11 @@ description: The subject strings Events subscriptions watch, and the events they
platforms: [websites, apps, nodejs, workers]
---
A subject is the string that says what a subscription watches.
<div class="info">The Events API is in beta. Event shapes, limits, and behavior may change between releases.</div>
A subject is the string that says what a subscription watches. [`onLocal()`](/Events/onLocal/) and [`onPersistent()`](/Events/onPersistent/) take the same subjects and deliver the same events.
[`onLocal()`](/Events/onLocal/) and [`onPersistent()`](/Events/onPersistent/) take the same subjects and deliver the same events.
## Syntax
@@ -149,30 +151,30 @@ The handler is called with `{ event }`. A file change carries:
| Field | Type | Description |
| --- | --- | --- |
| `id` | String | Unique id for the event. |
| `subject` | String | The node it happened to, as `fs:<uid>:<op>`. Not the subject you subscribed with. |
| `op` | String | `add` (a create, or a copy's destination), `write`, `move` (a move or a rename), or `remove`. |
| `uid` | String | The uid of the node that changed. |
| `path` | String | The path of the node that changed. In another user's files, it's a [masked path](/FS/listShared/), `/<owner>/<uid>/<name>/…`, where `<uid>` and `<name>` are those of the node the subscription is attached to. |
| `from` | String | On a `move`, the path the node left, masked the same way. Only present when the subscription was watching that location. |
| `self` | Boolean | `true` when the account holding the subscription made the change. Mail filed into the account's `~/.mail` folder is always `false`, including mail the account sent to itself. |
| `viaWorker` | Boolean | `true` when the change came from server-side code running as an account, such as a worker using `me.puter` or an [events handler](/Events/handlers/) running in the events worker. A worker using `user.puter` acts as the user who called it, so its changes are that user's own, with `viaWorker` set to `false`. A handler running in a client writes as that client, also with `viaWorker` set to `false`. To skip your own changes, check `self && !viaWorker`, which still lets through the ones a worker made as your account. |
| `ts` | Number | When it happened, in milliseconds since the epoch. |
| `seq` | Number | Position within one dispatch, when a change goes to several subscriptions. |
| `id` | `String` | Unique id for the event. |
| `subject` | `String` | The node it happened to, as `fs:<uid>:<op>`. Not the subject you subscribed with. |
| `op` | `String` | `add` (a create, or a copy's destination), `write`, `move` (a move or a rename), or `remove`. |
| `uid` | `String` | The uid of the node that changed. |
| `path` | `String` | The path of the node that changed. In another user's files, it's a [masked path](/FS/listShared/), `/<owner>/<uid>/<name>/…`, where `<uid>` and `<name>` are those of the node the subscription is attached to. |
| `from` | `String` | On a `move`, the path the node left, masked the same way. Only present when the subscription was watching that location. |
| `self` | `Boolean` | `true` when the account holding the subscription made the change. Mail filed into the account's `~/.mail` folder is always `false`, including mail the account sent to itself. |
| `viaWorker` | `Boolean` | `true` when the change came from server-side code running as an account, such as a worker using `me.puter` or an [events handler](/Events/handlers/) running in the events worker. A worker using `user.puter` acts as the user who called it, so its changes are that user's own, with `viaWorker` set to `false`. A handler running in a client writes as that client, also with `viaWorker` set to `false`. To skip your own changes, check `self && !viaWorker`, which still lets through the ones a worker made as your account. |
| `ts` | `Number` | When it happened, in milliseconds since the epoch. |
| `seq` | `Number` | Position within one dispatch, when a change goes to several subscriptions. |
A key-value change carries `key` instead of `uid` and `path`, and different ops:
| Field | Type | Description |
| --- | --- | --- |
| `id` | String | Unique id for the event. |
| `subject` | String | `kv:<appId>:<key>`, naming the key that changed. Through a share, `kv:<handle>:<key>`. |
| `op` | String | `set` for a write, `del` for a removal, `expire` when only the key's lifetime changed. |
| `key` | String | The key that changed. Through a share, relative to the handle. |
| `value` | Any | The new value, or `null` on a `del`. Only with `includeValue`, and only within the [limits above](#getting-the-new-value). Never on an `expire`. |
| `self` | Boolean | As above. |
| `viaWorker` | Boolean | As above. |
| `ts` | Number | As above. |
| `seq` | Number | As above. |
| `id` | `String` | Unique id for the event. |
| `subject` | `String` | `kv:<appId>:<key>`, naming the key that changed. Through a share, `kv:<handle>:<key>`. |
| `op` | `String` | `set` for a write, `del` for a removal, `expire` when only the key's lifetime changed. |
| `key` | `String` | The key that changed. Through a share, relative to the handle. |
| `value` | `Any` | The new value, or `null` on a `del`. Only with `includeValue`, and only within the [limits above](#getting-the-new-value). Never on an `expire`. |
| `self` | `Boolean` | As above. |
| `viaWorker` | `Boolean` | As above. |
| `ts` | `Number` | As above. |
| `seq` | `Number` | As above. |
A posted notification carries the fields listed on [`fetch()`](/Events/fetch/#return-value). An app message's live dismissal carries `op: 'dismiss'` and its `uid`, with no `notification` content. Dismissals follow the same audience rules. The notification SDK exposes them through [`on('dismiss')`](/Notifications/on/).
+6 -2
View File
@@ -4,9 +4,11 @@ description: End a persistent subscription.
platforms: [websites, apps, nodejs, workers]
---
Ends a subscription created with [`puter.events.onPersistent()`](/Events/onPersistent/).
<div class="info">The Events API is in beta. Event shapes, limits, and behavior may change between releases.</div>
Ends a subscription created with [`puter.events.onPersistent()`](/Events/onPersistent/). It stops right away, and any undelivered backlog is dropped. For a session subscription from [`puter.events.onLocal()`](/Events/onLocal/), use [`subscription.off()`](/Events/off/).
It stops right away, and any undelivered backlog is dropped. For a session subscription from [`puter.events.onLocal()`](/Events/onLocal/), use [`subscription.off()`](/Events/off/).
An app can end only the subscriptions it created. Outside an app, you can end any of yours, including ones left by deleted apps. A scoped access token, such as the one in a [`getReadURL()`](/FS/getReadURL/) URL, can't end any.
@@ -26,6 +28,8 @@ The `subId` of the subscription, from [`onPersistent()`](/Events/onPersistent/)
A `Promise` that resolves when the subscription is gone.
## Errors
An id you don't hold, because it already ended or another app created it, is reported as not existing, so the call doesn't reveal which subscriptions exist. If the call rejects with any other code, the subscription is still running, and so is any handler it runs on this page.
The promise rejects with `{ message, code }`:
@@ -41,7 +45,7 @@ The promise rejects with `{ message, code }`:
## Examples
<strong class="example-title">Create a persistent subscription, then end it</strong>
### Create a persistent subscription, then end it
```html;events-unsubscribe
<html>
+6 -2
View File
@@ -4,9 +4,11 @@ description: Change the context of a persistent subscription without ending it.
platforms: [websites, apps, nodejs, workers]
---
Changes the `context` of a subscription created with [`puter.events.onPersistent()`](/Events/onPersistent/).
<div class="info">The Events API is in beta. Event shapes, limits, and behavior may change between releases.</div>
Changes the `context` of a subscription created with [`puter.events.onPersistent()`](/Events/onPersistent/). The subscription keeps its `subId`, its handler, and any events it hasn't delivered yet, and later deliveries in the events worker run with the new `context` as `ctx`. Ending the subscription and subscribing again would give it a new `subId` and drop its undelivered events. To change a [schedule's](/Events/onSchedule/) context, use [`updateSchedule()`](/Events/updateSchedule/).
The subscription keeps its `subId`, its handler, and any events it hasn't delivered yet, and later deliveries in the events worker run with the new `context` as `ctx`. Ending the subscription and subscribing again would give it a new `subId` and drop its undelivered events. To change a [schedule's](/Events/onSchedule/) context, use [`updateSchedule()`](/Events/updateSchedule/).
An app can change only the subscriptions it created. Outside an app, you can change any of yours. A scoped access token, such as the one in a [`getReadURL()`](/FS/getReadURL/) URL, can't change any.
@@ -31,6 +33,8 @@ A `Promise` that resolves to the updated subscription, in the same shape [`puter
A delivery already running when you call `update()` finishes with the old context. A suspended subscription stays suspended and uses the new context once it resumes. If this page runs a function `handler` for the subscription, that handler gets the new context too. Handlers in other open pages keep the context they registered with.
## Errors
The promise rejects with `{ message, code }`:
| `code` | Meaning |
@@ -47,7 +51,7 @@ The promise rejects with `{ message, code }`:
## Examples
<strong class="example-title">Point a subscription at a new endpoint</strong>
### Point a subscription at a new endpoint
```html;events-update
<html>
+34 -7
View File
@@ -4,9 +4,11 @@ description: Move a schedule to a new time, change its context, or edit a notifi
platforms: [websites, apps, nodejs, workers]
---
Changes a schedule created with [`puter.events.onSchedule()`](/Events/onSchedule/), or a notification stored to send later with [`puter.notifications.notify()`](/Notifications/notify/#send-it-later).
<div class="info">The Events API is in beta. Event shapes, limits, and behavior may change between releases.</div>
Changes a schedule created with [`puter.events.onSchedule()`](/Events/onSchedule/), or a notification stored to send later with [`puter.notifications.notify()`](/Notifications/notify/#send-it-later). The schedule keeps its `scheduleId`, its kind and its handler, so ids you saved elsewhere stay valid.
The schedule keeps its `scheduleId`, its kind and its handler, so ids you saved elsewhere stay valid.
An app can change only the schedules it created. An account session can change any of the user's schedules. A scoped access token can't change any. On a website with nobody signed in, the call asks the user to sign in first, as other Puter.js calls do.
@@ -26,13 +28,36 @@ The `scheduleId` from [`onSchedule()`](/Events/onSchedule/), [`notify()`](/Notif
For a schedule from [`onSchedule()`](/Events/onSchedule/), pass new timing, a new `context`, or both:
- **Timing.** Any of `at`, `every`, `cron`, `tz`, `startAt`, `expiresAt` and `maxRuns` replaces the whole timing, so pass exactly one of `at`, `every` or `cron`, together with every other timing option you want to keep. They take the same values as in [`onSchedule()`](/Events/onSchedule/#parameters). A recurring schedule can switch between `every` and `cron`, and an `at` schedule stays a one-time schedule. Without timing options, the timing stays as it is.
- `context` (Object | null): Replaces the whole context. Pass `null` to clear it. Up to 4 KB serialized, as in [`onSchedule()`](/Events/onSchedule/#parameters).
| Option | Type | Description |
|--------|------|-------------|
| `every` | `Number \| String` | The new interval. A recurring schedule can switch between `every` and `cron`. |
| `cron` | `String` | The new cron expression. A recurring schedule can switch between `every` and `cron`. |
| `at` | `Number \| String \| Date` | The new time for a one-time schedule. An `at` schedule stays a one-time schedule. |
| `context` | `Object \| null` | Replaces the whole context. Pass `null` to clear it. Up to 4 KB serialized, as in [`onSchedule()`](/Events/onSchedule/#parameters). |
| `tz` | `String` | The time zone the `cron` expression runs in. |
| `startAt` | `Number \| String \| Date` | For `every`, the first run. For `cron`, the earliest time the schedule may run. |
| `expiresAt` | `Number \| String \| Date` | The last time the schedule may run. |
| `maxRuns` | `Number` | How many slots the schedule has. |
The timing options are `at`, `every`, `cron`, `tz`, `startAt`, `expiresAt` and `maxRuns`. Any of them replaces the whole timing, so pass exactly one of `at`, `every` or `cron`, together with every other timing option you want to keep. They take the same values as in [`onSchedule()`](/Events/onSchedule/#parameters). Without timing options, the timing stays as it is.
For a stored notification, pass a new `sendAt`, new content, or both:
- `sendAt` (Number | String | Date): The new time to send it, as in [`notify()`](/Notifications/notify/#parameters). A time within 5 seconds, or in the past, sends it now, with the [retries](/Notifications/notify/#send-it-later) of any stored notification.
- `title`, `text`, `icon`, `target`, `data`, `group`, `channel`, `sensitive`, `priority`, `ttl`: Replace the stored values, with the same rules as [`notify()`](/Notifications/notify/#parameters). Fields you leave out keep their values. Pass `null` to clear an optional field. The `title` can't be cleared.
| Option | Type | Description |
|--------|------|-------------|
| `sendAt` | `Number \| String \| Date` | The new time to send it, as in [`notify()`](/Notifications/notify/#parameters). A time within 5 seconds, or in the past, sends it now, with the [retries](/Notifications/notify/#send-it-later) of any stored notification. |
| `title` | `String` | Replaces the stored title. It can't be cleared. |
| `text` | `String` | Replaces the stored text. |
| `icon` | `String` | Replaces the stored icon. |
| `target` | `String` | Replaces the stored target. |
| `data` | `Any` | Replaces the stored data. |
| `group` | `String` | Replaces the stored group. |
| `channel` | `String` | Replaces the stored channel. |
| `sensitive` | `Boolean` | Replaces the stored `sensitive` setting. |
| `priority` | `String` | Replaces the stored priority. |
| `ttl` | `Number` | Replaces the stored `ttl`. |
The content options follow the same rules as in [`notify()`](/Notifications/notify/#parameters). Fields you leave out keep their values. Pass `null` to clear an optional field.
The handler and the recipient can't change. Passing `handler`, `handlerName`, `handlerScope`, `handlerHash`, `handlerSource` or `to` rejects with `invalid_request`. To run different code, remove the schedule and create a new one.
@@ -40,6 +65,8 @@ The handler and the recipient can't change. Passing `handler`, `handlerName`, `h
A `Promise` that resolves to the updated schedule, in the shape [`getSchedule()`](/Events/getSchedule/#return-value) returns. Its `nextRunAt` is the next run under the new timing. It describes the context by its key names and a hash, and never includes a stored notification's content. A stored notification whose new `sendAt` is due now is sent during the call, so the schedule can come back already ended.
## Errors
The promise rejects with `{ message, code }`:
| `code` | Meaning |
@@ -71,7 +98,7 @@ The promise rejects with `{ message, code }`:
## Examples
<strong class="example-title">Move a reminder to a later time</strong>
### Move a reminder to a later time
```html;events-update-reminder
<html>
@@ -103,7 +130,7 @@ The promise rejects with `{ message, code }`:
</html>
```
<strong class="example-title">Move a weekday schedule to another time</strong>
### Move a weekday schedule to another time
```html;events-update-cron
<html>
+19 -7
View File
@@ -4,9 +4,11 @@ description: List and destroy the events worker a published handler set stands u
platforms: [websites, apps, nodejs, workers]
---
An **events worker** runs published [handlers](/Events/handlers/), the app's own or one user's in a [user scope](/Events/handlers/#user-scope).
<div class="info">The Events API is in beta. Event shapes, limits, and behavior may change between releases.</div>
An **events worker** runs published [handlers](/Events/handlers/), the app's own or one user's in a [user scope](/Events/handlers/#user-scope). It runs them for every event on a subscription with a `handlerName`, whether or not a client is connected, for a [`queue`](/Events/onPersistent/#choosing-a-mode) delivery once no connected client takes it, and for every run of a [schedule](/Events/onSchedule/). Each app has at most one for its own handlers, created when it publishes its first handler. Each user scope is a unit of its own, created when the user's first handler in an app is published, whether by publishing it or by passing an inline `handler`.
It runs them for every event on a subscription with a `handlerName`, whether or not a client is connected, for a [`queue`](/Events/onPersistent/#choosing-a-mode) delivery once no connected client takes it, and for every run of a [schedule](/Events/onSchedule/). Each app has at most one for its own handlers, created when it publishes its first handler. Each user scope is a unit of its own, created when the user's first handler in an app is published, whether by publishing it or by passing an inline `handler`.
A hosted Puter server may bill each app's events worker as a monthly cost, even if nothing ever delivers to it, and bills a user scope to the user the same way. Use this API to see which apps and scopes have one and remove the ones you don't need.
@@ -28,8 +30,12 @@ puter.events.workers.list()
puter.events.workers.list(options)
```
- `options.limit` (Number): Apps per page.
- `options.cursor` (String): The `cursor` from a previous page. Leave it off to start from the first page.
The `options` object takes these options:
| Option | Type | Description |
|--------|------|-------------|
| `limit` | `Number` | Apps per page. |
| `cursor` | `String` | The `cursor` from a previous page. Leave it off to start from the first page. |
Resolves to `{ items, cursor, deployable }`:
@@ -44,7 +50,13 @@ puter.events.workers.destroy(appUid)
puter.events.workers.destroy(appUid, options)
```
- `options.scope` (String): `'app'` or `'user'`. Defaults to `'app'`. `'user'` removes the signed-in user's own scope of the app. Inside an app, `appUid` can only name that app. With an account session, outside an app such as the desktop or Node.js with your account token, `appUid` can name any app you hold a user scope in, and it works even when the server has user-scope handlers turned off.
The `options` object takes these options:
| Option | Type | Description |
|--------|------|-------------|
| `scope` | `String` | Either `'app'` or `'user'`. Defaults to `'app'`. With `'user'`, it removes the signed-in user's own scope of the app. |
Inside an app, `appUid` can only name that app. With an account session, outside an app such as the desktop or Node.js with your account token, `appUid` can name any app you hold a user scope in, and it works even when the server has user-scope handlers turned off.
Removes every handler the app has published, or every handler in the user's scope with `scope: 'user'`, the same as calling [`puter.events.handlers.remove()`](/Events/handlers/) on each. Their subscriptions and schedules are suspended with `handler_not_found`, not deleted, and publishing the handlers again resumes them.
@@ -66,9 +78,9 @@ Both methods reject with `{ message, code }`:
| `events_disabled` | Events aren't enabled on this server. |
| `events_failed` | The server sent a response the SDK couldn't read. |
## Example
## Examples
<strong class="example-title">List your events workers, and destroy one you no longer need</strong>
### List your events workers, and destroy one you no longer need
This runs in Node.js signed in with your account token.
@@ -83,7 +95,7 @@ const destroyed = await puter.events.workers.destroy(appUid); // an app you ow
console.log(`removed ${destroyed.removed}, suspended ${destroyed.suspended}`);
```
<strong class="example-title">Remove the signed-in user's scope of your app</strong>
### Remove the signed-in user's scope of your app
The user scope belongs to the user, so it needs no owner step. In your app, name the app itself. With an account session outside an app, name any app you hold a scope in.
+8 -8
View File
@@ -298,15 +298,14 @@ These cloud storage features are supported out of the box when using Puter.js:
- **[`puter.fs.write()`](/FS/write/)** - Write data to a file
- **[`puter.fs.read()`](/FS/read/)** - Read data from a file
- **[`puter.fs.mkdir()`](/FS/mkdir/)** - Create a directory
- **[`puter.fs.readdir()`](/FS/readdir/)** - List contents of a directory
- **[`puter.fs.rename()`](/FS/rename/)** - Rename a file or directory
- **[`puter.fs.copy()`](/FS/copy/)** - Copy a file or directory
- **[`puter.fs.move()`](/FS/move/)** - Move a file or directory
- **[`puter.fs.stat()`](/FS/stat/)** - Get information about a file or directory
- **[`puter.fs.space()`](/FS/space/)** - Get the user's storage capacity and usage
- **[`puter.fs.delete()`](/FS/delete/)** - Delete a file or directory
- **[`puter.fs.upload()`](/FS/upload/)** - Upload a file from the local system
- **[`puter.fs.readdir()`](/FS/readdir/)** - List contents of a directory
- **[`puter.fs.mkdir()`](/FS/mkdir/)** - Create a directory
- **[`puter.fs.delete()`](/FS/delete/)** - Delete a file or directory
- **[`puter.fs.stat()`](/FS/stat/)** - Get information about a file or directory
- **[`puter.fs.rename()`](/FS/rename/)** - Rename a file or directory
- **[`puter.fs.move()`](/FS/move/)** - Move a file or directory
- **[`puter.fs.copy()`](/FS/copy/)** - Copy a file or directory
- **[`puter.fs.getReadURL()`](/FS/getReadURL/)** - Generate a URL that can be used to read a file
- **[`puter.fs.revokeReadURL()`](/FS/revokeReadURL/)** - Revoke a URL created by `getReadURL()`
- **[`puter.fs.share()`](/FS/share/)** - Give another user access to a file or directory
@@ -315,6 +314,7 @@ These cloud storage features are supported out of the box when using Puter.js:
- **[`puter.fs.listSharedByMe()`](/FS/listSharedByMe/)** - List everything you have shared out
- **[`puter.fs.getShares()`](/FS/getShares/)** - List who has access to an item
- **[`puter.fs.getShareLink()`](/FS/getShareLink/)** - Build a link that opens a file in an app
- **[`puter.fs.space()`](/FS/space/)** - Get the user's storage capacity and usage
## Examples
+13 -7
View File
@@ -30,19 +30,25 @@ Relative paths resolve against the app's root directory. A relative name that lo
The options for the `copy` operation. The following options are supported:
- `source` (String) - Path to the file or directory to copy. Required when passing options as the only argument.
- `destination` (String) - Path to the destination. Required when passing options as the only argument.
- `overwrite` (Boolean) - Whether to overwrite the destination file or directory if it already exists. Defaults to `false`.
- `dedupeName` (Boolean) - Whether to deduplicate the file or directory name if it already exists. Defaults to `false`.
- `newName` (String) - The new name to use for the copied file or directory. Defaults to `undefined`.
| Option | Type | Description |
|--------|------|-------------|
| `source` | `String` | Path to the file or directory to copy. Required when passing options as the only argument. |
| `destination` | `String` | Path to the destination. Required when passing options as the only argument. |
| `overwrite` | `Boolean` | Whether to overwrite the destination file or directory if it already exists. Defaults to `false`. |
| `newName` | `String` | The new name to use for the copied file or directory. Defaults to `undefined`. |
| `dedupeName` | `Boolean` | Whether to deduplicate the file or directory name if it already exists. Defaults to `false`. |
## Return value
A `Promise` that will resolve to the [`FSItem`](/Objects/fsitem) object of the copied file or directory. If the source file or directory does not exist, the promise will be rejected with an error.
A `Promise` that will resolve to the [`FSItem`](/Objects/fsitem) object of the copied file or directory.
## Errors
If the source file or directory does not exist, the promise will be rejected with an error.
## Examples
<strong class="example-title"> Copy a file</strong>
### Copy a file
```html;fs-copy
<html>
+7 -5
View File
@@ -25,9 +25,11 @@ If a path is not absolute, it will be resolved relative to the app's root direct
The options for the `delete` operation. The following options are supported:
- `paths` (String | String[]) - A single path or array of paths to delete. Required when passing options as the only argument.
- `recursive` (Boolean) - Whether to delete the directory recursively. Defaults to `true`.
- `descendantsOnly` (Boolean) - Whether to delete only the descendants of the directory and not the directory itself. Defaults to `false`.
| Option | Type | Description |
|--------|------|-------------|
| `paths` | `String \| String[]` | A single path or array of paths to delete. Required when passing options as the only argument. |
| `recursive` | `Boolean` | Whether to delete the directory recursively. Defaults to `true`. |
| `descendantsOnly` | `Boolean` | Whether to delete only the descendants of the directory and not the directory itself. Defaults to `false`. |
## Return value
@@ -39,7 +41,7 @@ as deleting it here, and restoring it does not bring the shares back.
## Examples
<strong class="example-title">Delete a file</strong>
### Delete a file
```html;fs-delete
<html>
@@ -61,7 +63,7 @@ as deleting it here, and restoring it does not bring the shares back.
</html>
```
<strong class="example-title">Delete a directory</strong>
### Delete a directory
```html;fs-delete-directory
<html>
+6 -2
View File
@@ -4,7 +4,9 @@ description: Generate a temporary URL that lets anyone read one file from the us
platforms: [websites, apps, nodejs, workers]
---
Generates a URL that can be used to read a file. To stop it from working before it expires, revoke it with [`revokeReadURL()`](/FS/revokeReadURL/).
Generates a URL that can be used to read a file.
To stop it from working before it expires, revoke it with [`revokeReadURL()`](/FS/revokeReadURL/).
## Syntax
@@ -27,7 +29,9 @@ How long the URL stays valid, in [jsonwebtoken](https://github.com/auth0/node-js
A promise that resolves to a URL string that can be used to read the file.
## Example
## Examples
### Get a read URL for a file
```javascript
const url = await puter.fs.getReadURL("~/myfile.txt");
+15 -11
View File
@@ -4,7 +4,9 @@ description: Build a link that opens a file in an app on Puter, for the people t
platforms: [websites, apps, nodejs, workers]
---
Builds the link that opens a file in an app on Puter, of the form `https://puter.com/app/<appName>?file=<uid>`. Send it to whoever the file is shared with: following it signs them in if needed, then opens the app with the file — after Puter has asked them to allow the app to open it.
Builds a link that opens a file in an app on Puter.
The link has the form `https://puter.com/app/<appName>?file=<uid>`. Send it to whoever the file is shared with. Following it signs them in if needed. Puter then asks them to allow the app to open the file, and opens the app with the file.
The link carries no access of its own. It works for the file's owner, for anyone the file was shared with through [`share()`](/FS/share/), and for any signed-in account once the file is open to **anyone with the link**. For everyone else the file is not found, and the app opens without it.
@@ -30,9 +32,11 @@ The name of the app the link opens the file with. Defaults to the app the code i
An object with the following properties:
- `path` (String) - The file. Required when passing options as the only argument, unless `uid` is given.
- `uid` (String) - The file, by UID. Can be used instead of `path`.
- `appName` (String) - As above.
| Option | Type | Description |
|--------|------|-------------|
| `path` | `String` | The file. Required when passing options as the only argument, unless `uid` is given. |
| `appName` | `String` | The name of the app the link opens the file with. Same as the `appName` argument. |
| `uid` | `String` | The file, by UID. Can be used instead of `path`. |
## Return value
@@ -52,9 +56,14 @@ A file that does not exist, or that you cannot see, rejects the way [`stat()`](/
The app opens on the recipient's Puter, and before it is handed the file Puter shows them what is being asked — which app, which file — and lets them refuse. Refused, the app still opens, just without the file. The app receives the access the recipient has: a file shared read-only opens read-only.
## Related
- [`puter.fs.share()`](/FS/share/) - Grant access, or open the file to anyone with the link
- [`puter.fs.getReadURL()`](/FS/getReadURL/) - A URL that reads the file's bytes without signing in
## Examples
<strong class="example-title">Open a shared file in an app</strong>
### Open a shared file in an app
```html;fs-getShareLink
<html>
@@ -74,15 +83,10 @@ The app opens on the recipient's Puter, and before it is handed the file Puter s
</html>
```
<strong class="example-title">Send a collaborator straight into your app</strong>
### Send a collaborator straight into your app
```js
// Inside a Puter app, the link opens the file in this app.
await puter.fs.share('draft.md', 'friend@example.com', 'write');
const link = await puter.fs.getShareLink('draft.md');
```
## Related
- [`puter.fs.share()`](/FS/share/) - Grant access, or open the file to anyone with the link
- [`puter.fs.getReadURL()`](/FS/getReadURL/) - A URL that reads the file's bytes without signing in
+13 -9
View File
@@ -35,8 +35,10 @@ The path to the file or directory. If `path` is not absolute, it will be resolve
An object with the following properties:
- `path` (String) - The item. Required when passing options as the only argument.
- `uid` (String) - The item, by UID. Can be used instead of `path`.
| Option | Type | Description |
|--------|------|-------------|
| `path` | `String` | The item. Required when passing options as the only argument. |
| `uid` | `String` | The item, by UID. Can be used instead of `path`. |
## Return value
@@ -56,11 +58,18 @@ It also includes **invitations** — shares aimed at an email address with no co
`recipientEmail` is set only for the item's **owner** and for whoever **sent** that invitation; for anyone else the invitation is listed without it. Someone else's invitation is not yours to cancel either, so nothing is lost with the address. An app never sees it, whoever it acts for.
## Errors
If you cannot see the item at all, this rejects the same way a missing file would — it will not confirm that the item exists.
## Related
- [`puter.fs.share()`](/FS/share/) - Grant access
- [`puter.fs.unshare()`](/FS/unshare/) - Withdraw access
## Examples
<strong class="example-title">See who can reach a file</strong>
### See who can reach a file
```html;fs-getShares
<html>
@@ -81,7 +90,7 @@ If you cannot see the item at all, this rejects the same way a missing file woul
</html>
```
<strong class="example-title">Withdraw everyone's access</strong>
### Withdraw everyone's access
```js
const shares = await puter.fs.getShares('report.txt');
@@ -89,8 +98,3 @@ for (const share of shares) {
await puter.fs.unshare('report.txt', share.holder);
}
```
## Related
- [`puter.fs.share()`](/FS/share/) - Grant access
- [`puter.fs.unshare()`](/FS/unshare/) - Withdraw access
+13 -11
View File
@@ -29,9 +29,11 @@ puter.fs.listShared(options)
An object with the following properties:
- `limit` (Number) - Maximum shares per page.
- `cursor` (String) - Continuation token from a previous page.
- `includeTotal` (Boolean) - Include the total count in the response. Defaults to `false`.
| Option | Type | Description |
|--------|------|-------------|
| `limit` | `Number` | Maximum shares per page. |
| `cursor` | `String` | Continuation token from a previous page. |
| `includeTotal` | `Boolean` | Include the total count in the response. Defaults to `false`. |
## Return value
@@ -45,9 +47,14 @@ Iterate until `cursor` is absent rather than comparing `items.length` to `limit`
Items shared with you appear at a **masked path**, `/<owner>/<uid>/<name>`, where `<uid>` stands in for wherever the owner keeps the item. Pass that path back to any `puter.fs` method and it resolves normally; what it does not tell you is the folder the item lives in, or what sits beside it. Your own items are never listed here.
## Related
- [`puter.fs.share()`](/FS/share/) - Grant access
- [`puter.fs.getShares()`](/FS/getShares/) - See who can reach an item you manage
## Examples
<strong class="example-title">List everything shared with you</strong>
### List everything shared with you
```html;fs-listShared
<html>
@@ -66,7 +73,7 @@ Items shared with you appear at a **masked path**, `/<owner>/<uid>/<name>`, wher
</html>
```
<strong class="example-title">Page through every share</strong>
### Page through every share
```js
let cursor;
@@ -78,7 +85,7 @@ do {
} while (cursor);
```
<strong class="example-title">Open a file someone shared with you</strong>
### Open a file someone shared with you
```js
const page = await puter.fs.listShared();
@@ -88,8 +95,3 @@ if (shared) {
puter.print(await blob.text());
}
```
## Related
- [`puter.fs.share()`](/FS/share/) - Grant access
- [`puter.fs.getShares()`](/FS/getShares/) - See who can reach an item you manage
+18 -14
View File
@@ -4,7 +4,9 @@ description: List everything you have shared with other users, across all items.
platforms: [websites, apps, nodejs, workers]
---
This method lists everything you have shared out, a page at a time, without naming an item first. [`getShares()`](/FS/getShares/) answers the same question for one item you can already point at; this is what answers it when you can't. The listing includes invites to addresses that have no account yet (marked `pending`), items you opened to anyone with the link (marked `anyone`), and — for items you own — shares that a delegate with `manage` access issued on your behalf.
This method lists everything you have shared out, a page at a time, without naming an item first.
To list the shares on one item you already know, use [`getShares()`](/FS/getShares/). This method lists them when you don't know the item. The listing includes invites to addresses that have no account yet (marked `pending`), items you opened to anyone with the link (marked `anyone`), and, for items you own, shares that a delegate with `manage` access issued on your behalf.
> **What an app sees.** An app never gets more reach than it was given: this
> listing shows an app only the shares on items it can reach in its own right.
@@ -24,10 +26,12 @@ puter.fs.listSharedByMe(options)
An object with the following properties:
- `limit` (Number) - Maximum shares per page.
- `cursor` (String) - Continuation token from a previous page.
- `includeTotal` (Boolean) - Include the total count in the response. Defaults to `false`.
- `appUid` (String) - Narrow the listing to the shares one app issued in your name, or pass `'none'` for the ones you made yourself. An app calling this is bound to its own grants whatever it asks for.
| Option | Type | Description |
|--------|------|-------------|
| `limit` | `Number` | Maximum shares per page. |
| `cursor` | `String` | Continuation token from a previous page. |
| `includeTotal` | `Boolean` | Include the total count in the response. Defaults to `false`. |
| `appUid` | `String` | Narrow the listing to the shares one app issued in your name, or pass `'none'` for the ones you made yourself. An app calling this is bound to its own grants whatever it asks for. |
## Return value
@@ -41,9 +45,15 @@ Iterate until `cursor` is absent rather than comparing `items.length` to `limit`
Items you own appear at their real path. An item you shared as a delegate (from someone else's folder you hold `manage` on) appears at the same masked path you reach it by.
## Related
- [`puter.fs.share()`](/FS/share/) - Grant access
- [`puter.fs.listShared()`](/FS/listShared/) - List what others shared with you
- [`puter.fs.getShares()`](/FS/getShares/) - See who can reach one item you manage
## Examples
<strong class="example-title">See everything you have shared</strong>
### See everything you have shared
```html
<html>
@@ -65,7 +75,7 @@ Items you own appear at their real path. An item you shared as a delegate (from
</html>
```
<strong class="example-title">Page through every share you made</strong>
### Page through every share you made
```js
let cursor;
@@ -77,7 +87,7 @@ do {
} while (cursor);
```
<strong class="example-title">Withdraw everything shared on one item</strong>
### Withdraw everything shared on one item
```js
const page = await puter.fs.listSharedByMe();
@@ -86,9 +96,3 @@ if (target && !target.pending) {
await puter.fs.unshare(target.path, target.holder);
}
```
## Related
- [`puter.fs.share()`](/FS/share/) - Grant access
- [`puter.fs.listShared()`](/FS/listShared/) - List what others shared with you
- [`puter.fs.getShares()`](/FS/getShares/) - See who can reach one item you manage
+9 -7
View File
@@ -25,10 +25,12 @@ If path is not absolute, it will be resolved relative to the app's root director
The options for the `mkdir` operation. The following options are supported:
- `path` (String) The directory path to be created if not specified via function parameter.
- `overwrite` (Boolean) - Whether to overwrite the directory if it already exists. Defaults to `false`.
- `dedupeName` (Boolean) - Whether to deduplicate the directory name if it already exists. Defaults to `false`.
- `createMissingParents` (Boolean) - Whether to create missing parent directories. Defaults to `false`.
| Option | Type | Description |
|--------|------|-------------|
| `path` | `String` | The directory path to be created if not specified via function parameter. |
| `createMissingParents` | `Boolean` | Whether to create missing parent directories. Defaults to `false`. |
| `overwrite` | `Boolean` | Whether to overwrite the directory if it already exists. Defaults to `false`. |
| `dedupeName` | `Boolean` | Whether to deduplicate the directory name if it already exists. Defaults to `false`. |
## Return value
@@ -36,7 +38,7 @@ Returns a `Promise` that resolves to the [`FSItem`](/Objects/fsitem) object of t
## Examples
<strong class="example-title">Create a new directory</strong>
### Create a new directory
```html;fs-mkdir
<html>
@@ -55,7 +57,7 @@ Returns a `Promise` that resolves to the [`FSItem`](/Objects/fsitem) object of t
</html>
```
<strong class="example-title">Create a directory with duplicate name handling</strong>
### Create a directory with duplicate name handling
```html;fs-mkdir-dedupe
<html>
@@ -75,7 +77,7 @@ Returns a `Promise` that resolves to the [`FSItem`](/Objects/fsitem) object of t
</html>
```
<strong class="example-title">Create a new directory with missing parent directories</strong>
### Create a new directory with missing parent directories
```html;fs-mkdir-create-missing-parents
<html>
+15 -9
View File
@@ -32,20 +32,26 @@ Without `newName`, the destination is looked up first to tell the two cases apar
The options for the `move` operation. The following options are supported:
- `source` (String) - Path to the file or directory to move. Required when passing options as the only argument.
- `destination` (String) - Path to the destination. Required when passing options as the only argument.
- `overwrite` (Boolean) - Whether to overwrite the destination file or directory if it already exists. Defaults to `false`.
- `dedupeName` (Boolean) - Whether to deduplicate the file or directory name if it already exists. Defaults to `false`.
- `newName` (String) - The name to give the moved file or directory. When set, `destination` is always treated as the directory to move into. Defaults to the source's own name.
- `createMissingParents` (Boolean) - Whether to create missing parent directories. Defaults to `false`.
| Option | Type | Description |
|--------|------|-------------|
| `source` | `String` | Path to the file or directory to move. Required when passing options as the only argument. |
| `destination` | `String` | Path to the destination. Required when passing options as the only argument. |
| `overwrite` | `Boolean` | Whether to overwrite the destination file or directory if it already exists. Defaults to `false`. |
| `newName` | `String` | The name to give the moved file or directory. When set, `destination` is always treated as the directory to move into. Defaults to the source's own name. |
| `createMissingParents` | `Boolean` | Whether to create missing parent directories. Defaults to `false`. |
| `dedupeName` | `Boolean` | Whether to deduplicate the file or directory name if it already exists. Defaults to `false`. |
## Return value
A `Promise` that will resolve to the [`FSItem`](/Objects/fsitem) object of the moved file or directory. If the source file or directory does not exist, the promise will be rejected with an error.
A `Promise` that will resolve to the [`FSItem`](/Objects/fsitem) object of the moved file or directory.
## Errors
If the source file or directory does not exist, the promise will be rejected with an error.
## Examples
<strong class="example-title">Move a file</strong>
### Move a file
```html;fs-move
<html>
@@ -76,7 +82,7 @@ A `Promise` that will resolve to the [`FSItem`](/Objects/fsitem) object of the m
</html>
```
<strong class="example-title">Move a file and create missing parent directories</strong>
### Move a file and create missing parent directories
```html;fs-move-create-missing-parents
<html>
+6 -6
View File
@@ -25,11 +25,11 @@ If `path` is not absolute, it will be resolved relative to the app's root direct
An object with the following properties:
- `path` (String) - Path to the file to read. Required when passing options as the only argument.
- `offset` (Number) (optional)
The offset to start reading from.
- `byte_count` (Number) (optional)
The number of bytes to read from the offset. When omitted with `offset`, reads through the end of the file.
| Option | Type | Description |
|--------|------|-------------|
| `path` | `String` | Path to the file to read. Required when passing options as the only argument. |
| `offset` | `Number` | The offset to start reading from. |
| `byte_count` | `Number` | The number of bytes to read from the offset. When omitted with `offset`, reads through the end of the file. |
## Return value
@@ -37,7 +37,7 @@ A `Promise` that will resolve to a `Blob` object containing the contents of the
## Examples
<strong class="example-title">Read a file</strong>
### Read a file
```html;fs-read
<html>
+17 -13
View File
@@ -4,7 +4,9 @@ description: List files and directories in the user's own Puter file system.
platforms: [websites, apps, nodejs, workers]
---
Reads the contents of a directory, returning an array of items (files and directories) within it. This method is useful for listing all items in a specified directory in the Puter cloud storage.
Reads the contents of a directory, returning an array of items (files and directories) within it.
This method is useful for listing all items in a specified directory in the Puter cloud storage.
## Syntax
@@ -25,17 +27,19 @@ If `path` is not absolute, it will be resolved relative to the app's root direct
An object with the following properties:
- `path` (String) - The path to the directory to read. Required when passing options as the only argument.
- `uid` (String) (optional) - The UID of the directory to read.
- `limit` (Number) (optional) - Maximum number of entries to return.
- `offset` (Number) (optional) - Skips the given number of entries. Prefer `cursor` for paging through large directories. On a `recursive` listing, `offset` is ignored when a `cursor` is passed; start with `offset`, then follow the returned `cursor`.
- `sortBy` (String) (optional) - Sort field: `name`, `modified`, `type`, or `size`. Default is `name`. With `recursive`, sorting by `name` orders by full path, so each directory's contents stay together; the other fields sort across the whole subtree.
- `sortOrder` (String) (optional) - `asc` or `desc`. Default is `asc`.
- `recursive` (Boolean) (optional) - If `true`, the contents of subdirectories are listed too. Defaults to `false`.
- `depth` (Number) (optional) - How many levels to descend when `recursive` is `true`. Defaults to `10`, which is also the maximum.
- `cursor` (String | null) (optional) - Opts into paginated results. Pass `null` for the first page, then the `cursor` from each page to fetch the next one. The cursor pins the sort, so later pages must not request a different `sortBy`/`sortOrder`.
- `includeTotal` (Boolean) (optional) - If `true`, the paginated result includes a `total` count of all entries in the directory.
- `stream` (Boolean) (optional) - If `true`, the method returns an async iterator of page objects instead of a promise, for use with `for await ... of`. Combine with `limit` to control the page size, or `cursor` to resume from a previous page. Cannot be combined with `offset`. With `includeTotal`, only the first page carries `total`.
| Option | Type | Description |
|--------|------|-------------|
| `path` | `String` | The path to the directory to read. Required when passing options as the only argument. |
| `recursive` | `Boolean` | If `true`, the contents of subdirectories are listed too. Defaults to `false`. |
| `depth` | `Number` | How many levels to descend when `recursive` is `true`. Defaults to `10`, which is also the maximum. |
| `sortBy` | `String` | Sort field. One of `name`, `modified`, `type`, or `size`. Default is `name`. With `recursive`, sorting by `name` orders by full path, so each directory's contents stay together. The other fields sort across the whole subtree. |
| `sortOrder` | `String` | Either `asc` or `desc`. Default is `asc`. |
| `limit` | `Number` | Maximum number of entries to return. |
| `cursor` | `String \| null` | Opts into paginated results. Pass `null` for the first page, then the `cursor` from each page to fetch the next one. The cursor pins the sort, so later pages must not request a different `sortBy` or `sortOrder`. |
| `offset` | `Number` | Skips the given number of entries. Prefer `cursor` for paging through large directories. On a `recursive` listing, `offset` is ignored when a `cursor` is passed. Start with `offset`, then follow the returned `cursor`. |
| `includeTotal` | `Boolean` | If `true`, the paginated result includes a `total` count of all entries in the directory. |
| `stream` | `Boolean` | If `true`, the method returns an async iterator of page objects instead of a promise, for use with `for await ... of`. Combine with `limit` to control the page size, or `cursor` to resume from a previous page. Cannot be combined with `offset`. With `includeTotal`, only the first page carries `total`. |
| `uid` | `String` | The UID of the directory to read. |
## Return value
@@ -63,7 +67,7 @@ for await (const page of puter.fs.readdir({ path: './large-dir', stream: true })
## Examples
<strong class="example-title">Read a directory</strong>
### Read a directory
```html;fs-readdir
<html>
+9 -5
View File
@@ -4,7 +4,9 @@ description: Rename files or directories in the user's own Puter file system.
platforms: [websites, apps, nodejs, workers]
---
Renames a file or directory to a new name. This method allows you to change the name of a file or directory in the Puter cloud storage.
Renames a file or directory to a new name.
This method allows you to change the name of a file or directory in the Puter cloud storage.
## Syntax
@@ -28,9 +30,11 @@ The new name of the file or directory.
The options for the `rename` operation. The following options are supported:
- `path` (String) - Path to the file or directory to rename. Required when passing options as the only argument.
- `uid` (String) - The UID of the file or directory to rename. Can be used instead of `path`.
- `newName` (String) - The new name for the file or directory. Required when passing options as the only argument.
| Option | Type | Description |
|--------|------|-------------|
| `path` | `String` | Path to the file or directory to rename. Required when passing options as the only argument. |
| `newName` | `String` | The new name for the file or directory. Required when passing options as the only argument. |
| `uid` | `String` | The UID of the file or directory to rename. Can be used instead of `path`. |
## Return value
@@ -38,7 +42,7 @@ Returns a promise that resolves to the [`FSItem`](/Objects/fsitem) object of the
## Examples
<strong class="example-title">Rename a file</strong>
### Rename a file
```html;fs-rename
<html>
+5 -3
View File
@@ -4,7 +4,9 @@ description: Revoke a URL created by getReadURL(), so it stops serving the file.
platforms: [websites, apps, nodejs, workers]
---
Revokes a URL created by [`getReadURL()`](/FS/getReadURL/), so it immediately stops serving the file. An app can revoke only URLs it created; the account itself, through its own session or API token, can revoke any of its read URLs. Revoking a URL that is already revoked or has expired resolves without error.
Revokes a URL created by [`getReadURL()`](/FS/getReadURL/), so it immediately stops serving the file.
An app can revoke only URLs it created. The account itself, through its own session or API token, can revoke any of its read URLs. Revoking a URL that is already revoked or has expired resolves without error.
## Syntax
@@ -37,9 +39,9 @@ A rejection carries an `Error` with a stable `code`:
| `not_found` | The URL was created by a different app, or belongs to another account. |
| `too_many_requests` | The rate limit was exceeded. See [Rate Limits & Quotas](/rate-limits-and-quotas/). |
## Example
## Examples
<strong class="example-title">Revoke a read URL</strong>
### Revoke a read URL
```html
<html>
+49 -47
View File
@@ -54,11 +54,13 @@ How much access to grant. Defaults to `'read'`.
An object with the following properties:
- `path` (String) - Item to share. Required when passing options as the only argument.
- `uid` (String) - Item to share, by UID. Can be used instead of `path`.
- `paths` (Array) - Several items to share in one call.
- `recipient` (String | Object | Array) - Who to share with.
- `mode` (String) - Access to grant. Defaults to `'read'`.
| Option | Type | Description |
|--------|------|-------------|
| `path` | `String` | Item to share. Required when passing options as the only argument. |
| `recipient` | `String \| Object \| Array` | Who to share with. |
| `mode` | `String` | Access to grant. Defaults to `'read'`. |
| `paths` | `Array` | Several items to share in one call. |
| `uid` | `String` | Item to share, by UID. Can be used instead of `path`. |
## Return value
@@ -144,48 +146,6 @@ if ( share.pending ) {
}
```
## Examples
<strong class="example-title">Share a file with another user</strong>
```html;fs-share
<html>
<body>
<script src="https://js.puter.com/v2/"></script>
<script>
(async () => {
// (1) create a file
await puter.fs.write('report.txt', 'Quarterly numbers');
// (2) share it, read-only
const shares = await puter.fs.share('report.txt', 'friend@example.com');
puter.print(`Shared with ${shares[0].holder} as ${shares[0].mode}<br>`);
})()
</script>
</body>
</html>
```
<strong class="example-title">Let someone edit, and let someone else re-share</strong>
```js
// An editor can change the file but cannot pass it on.
await puter.fs.share('report.txt', 'editor@example.com', 'write');
// A manager can edit it AND share it with other people.
await puter.fs.share('report.txt', 'manager@example.com', 'manage');
```
<strong class="example-title">Share one item with several people</strong>
```js
await puter.fs.share({
path: 'report.txt',
recipient: ['a@example.com', 'b@example.com'],
mode: 'read',
});
```
## Live updates
Changes inside a shared item are not pushed to recipients in real time —
@@ -236,3 +196,45 @@ Trash does not bring them back; share it again.
- [`puter.fs.unshare()`](/FS/unshare/) - Withdraw access
- [`puter.fs.getShares()`](/FS/getShares/) - See who can reach an item
- [`puter.fs.listShared()`](/FS/listShared/) - See what others have shared with you
## Examples
### Share a file with another user
```html;fs-share
<html>
<body>
<script src="https://js.puter.com/v2/"></script>
<script>
(async () => {
// (1) create a file
await puter.fs.write('report.txt', 'Quarterly numbers');
// (2) share it, read-only
const shares = await puter.fs.share('report.txt', 'friend@example.com');
puter.print(`Shared with ${shares[0].holder} as ${shares[0].mode}<br>`);
})()
</script>
</body>
</html>
```
### Let someone edit, and let someone else re-share
```js
// An editor can change the file but cannot pass it on.
await puter.fs.share('report.txt', 'editor@example.com', 'write');
// A manager can edit it AND share it with other people.
await puter.fs.share('report.txt', 'manager@example.com', 'manage');
```
### Share one item with several people
```js
await puter.fs.share({
path: 'report.txt',
recipient: ['a@example.com', 'b@example.com'],
mode: 'read',
});
```
+1 -1
View File
@@ -25,7 +25,7 @@ A `Promise` that resolves to a [`SpaceInfo`](/Objects/spaceinfo/) object with th
## Examples
<strong class="example-title">Show how much storage the user has used</strong>
### Show how much storage the user has used
```html
<html>
+17 -15
View File
@@ -24,14 +24,16 @@ If `path` is not absolute, it will be resolved relative to the app's root direct
An object with the following properties:
- `path` (String) - Path to the file or directory. Required when passing options as the only argument.
- `uid` (String) - The UID of the file or directory. Can be used instead of `path`.
- `returnSubdomains` (Boolean) - Whether to return subdomain information. Defaults to `false`.
- `returnWorkers` (Boolean) - Whether to return the workers attached to the item. Workers are served alongside subdomains, so this is an alias of `returnSubdomains` — setting either one returns both. Defaults to `false`.
- `returnPermissions` (Boolean) - Whether to return permission information. Defaults to `false`.
- `returnVersions` (Boolean) - Whether to return version information. Defaults to `false`.
- `returnSize` (Boolean) - Whether to return size information. Defaults to `false`.
- `returnShares` (Boolean) - Whether to include who the item is shared with, as a `shares` array on the result. Defaults to `false`.
| Option | Type | Description |
|--------|------|-------------|
| `path` | `String` | Path to the file or directory. Required when passing options as the only argument. |
| `returnSize` | `Boolean` | Whether to return size information. Defaults to `false`. |
| `returnShares` | `Boolean` | Whether to include who the item is shared with, as a `shares` array on the result. Defaults to `false`. |
| `returnSubdomains` | `Boolean` | Whether to return subdomain information. Defaults to `false`. |
| `returnWorkers` | `Boolean` | Whether to return the workers attached to the item. Workers are served alongside subdomains, so this is an alias of `returnSubdomains`. Setting either one returns both. Defaults to `false`. |
| `returnPermissions` | `Boolean` | Whether to return permission information. Defaults to `false`. |
| `returnVersions` | `Boolean` | Whether to return version information. Defaults to `false`. |
| `uid` | `String` | The UID of the file or directory. Can be used instead of `path`. |
## Return value
@@ -41,9 +43,14 @@ The item carries `is_shared`: `true` when it has been shared with someone, `fals
With `returnShares: true`, the result also carries `shares` — an array of the same share objects [`getShares()`](/FS/getShares/) returns, including access inherited from a parent folder and unclaimed invitations. It is empty unless you own the item or hold `manage` on it, so asking for it never fails a `stat()` you were otherwise allowed to make. An app or API token sees only the shares it issued itself, and an invitation's `recipientEmail` is withheld from everyone but the owner and its sender — see [`getShares()`](/FS/getShares/). Because it does `getShares()`'s work, it also spends from the [share-read limit](/rate-limits-and-quotas/#sharing) on top of `stat()`'s own.
## Related
- [`puter.fs.getShares()`](/FS/getShares/) - List who can reach an item
- [`puter.fs.share()`](/FS/share/) - Grant access
## Examples
<strong class="example-title">Get information about a file</strong>
### Get information about a file
```html;fs-stat
<html>
@@ -67,7 +74,7 @@ With `returnShares: true`, the result also carries `shares` — an array of the
</html>
```
<strong class="example-title">See whether a file is shared, and with whom</strong>
### See whether a file is shared, and with whom
```html;fs-stat-shares
<html>
@@ -88,8 +95,3 @@ With `returnShares: true`, the result also carries `shares` — an array of the
</body>
</html>
```
## Related
- [`puter.fs.getShares()`](/FS/getShares/) - List who can reach an item
- [`puter.fs.share()`](/FS/share/) - Grant access
+12 -10
View File
@@ -39,9 +39,11 @@ Pass **yourself** to leave a share someone else gave you. Pass `{ team: uid }` t
An object with the following properties:
- `path` (String) - The item. Required when passing options as the only argument.
- `uid` (String) - The item, by UID. Can be used instead of `path`.
- `recipient` (String | Object) - Whose access to withdraw.
| Option | Type | Description |
|--------|------|-------------|
| `path` | `String` | The item. Required when passing options as the only argument. |
| `recipient` | `String \| Object` | Whose access to withdraw. |
| `uid` | `String` | The item, by UID. Can be used instead of `path`. |
## Return value
@@ -68,9 +70,14 @@ Withdrawing someone's access also withdraws whatever **they** re-shared of that
Passing an email address that was **invited** but has not yet joined cancels the invitation. Nothing was granted, so nothing is revoked from anyone — the pending share simply stops waiting.
## Related
- [`puter.fs.share()`](/FS/share/) - Grant access
- [`puter.fs.getShares()`](/FS/getShares/) - See who can reach an item
## Examples
<strong class="example-title">Stop sharing a file</strong>
### Stop sharing a file
```html;fs-unshare
<html>
@@ -89,14 +96,9 @@ Passing an email address that was **invited** but has not yet joined cancels the
</html>
```
<strong class="example-title">Leave a share someone gave you</strong>
### Leave a share someone gave you
```js
const me = await puter.auth.getUser();
await puter.fs.unshare('/alice/report.txt', me.username);
```
## Related
- [`puter.fs.share()`](/FS/share/) - Grant access
- [`puter.fs.getShares()`](/FS/getShares/) - See who can reach an item
+16 -13
View File
@@ -28,19 +28,20 @@ The path of the directory to upload the items to. If not set, the items will be
A set of key/value pairs that configure the upload process. The following options are supported:
- `overwrite` (Boolean) - Whether to overwrite the destination file if it already exists. Defaults to `false`.
- `dedupeName` (Boolean) - Whether to deduplicate the file name if it already exists. Defaults to `true`. Ignored when `overwrite` is `true`.
- `createMissingParents` (Boolean) - Whether to create missing parent directories. Defaults to `false`.
- `generateThumbnails` (Boolean) - Generate image thumbnails in the browser before uploading. Defaults to `false`. Unsupported files and generation failures are skipped.
- `thumbnailGenerator` (Function) - Optional `(file, context) => string | undefined` callback (which may also return a promise), called once per file instead of the built-in image generator. Return a thumbnail data URL or URL, or `undefined` to skip. Exceptions are ignored. `context.defaultGenerator(file)` delegates to the built-in image generator; `context.signal` is an `AbortSignal` for upload preparation cancellation. Existing one-argument callbacks continue to work. A custom generator enables thumbnail preparation even when `generateThumbnails` is omitted.
- `thumbnail` (String) - Optional thumbnail data URL or URL to use when a file has no generated thumbnail. Data URLs exceeding 2 MiB are discarded.
| Option | Type | Description |
|--------|------|-------------|
| `overwrite` | `Boolean` | Whether to overwrite the destination file if it already exists. Defaults to `false`. |
| `progress` | `Function` | Called with `(operationId, progress)` as bytes are sent, where `progress` is a percentage between `0` and `100`. |
| `createMissingParents` | `Boolean` | Whether to create missing parent directories. Defaults to `false`. |
| `dedupeName` | `Boolean` | Whether to deduplicate the file name if it already exists. Defaults to `true`. Ignored when `overwrite` is `true`. |
| `generateThumbnails` | `Boolean` | Generate image thumbnails in the browser before uploading. Defaults to `false`. Unsupported files and generation failures are skipped. |
| `thumbnail` | `String` | Optional thumbnail data URL or URL to use when a file has no generated thumbnail. Data URLs exceeding 2 MiB are discarded. |
| `thumbnailGenerator` | `Function` | Optional `(file, context) => string \| undefined` callback (which may also return a promise), called once per file instead of the built-in image generator. Return a thumbnail data URL or URL, or `undefined` to skip. Exceptions are ignored. Call `context.defaultGenerator(file)` to use the built-in image generator. The `context.signal` property is an `AbortSignal` for upload preparation cancellation. Existing one-argument callbacks continue to work. A custom generator enables thumbnail preparation even when `generateThumbnails` is omitted. |
| `init` | `Function` | Called with `(operationId, xhr)` once the request has been created, before it is sent. The `XMLHttpRequest` is passed so you can abort the upload yourself. |
| `start` | `Function` | Called with no arguments when the upload starts sending. |
| `abort` | `Function` | Called with `(operationId)` if the upload is aborted. |
The following callbacks report on the upload as it runs. `operationId` identifies the upload, so a page running several uploads at once can tell them apart:
- `init` (Function) - Called with `(operationId, xhr)` once the request has been created, before it is sent. The `XMLHttpRequest` is passed so you can abort the upload yourself.
- `start` (Function) - Called with no arguments when the upload starts sending.
- `progress` (Function) - Called with `(operationId, progress)` as bytes are sent, where `progress` is a percentage between `0` and `100`.
- `abort` (Function) - Called with `(operationId)` if the upload is aborted.
The `init`, `start`, `progress`, and `abort` callbacks report on the upload as it runs. Their `operationId` argument identifies the upload, so a page running several uploads at once can tell them apart.
Cancelling through the `init` request handle during thumbnail preparation rejects with `{ code: 'upload_aborted', message: 'Upload aborted.' }` and prevents the upload from starting. Custom generators should stop their work when `context.signal` aborts and impose their own time and resource budgets; the SDK awaits thumbnail preparation before sending files.
@@ -59,6 +60,8 @@ Returns a `Promise` that resolves to:
- A single [`FSItem`](/Objects/fsitem/) object if `items` parameter contains one item
- An array of [`FSItem`](/Objects/fsitem/) objects if `items` parameter contains multiple items
## Errors
If any part of the upload fails, the promise is rejected — it never resolves to a mix of items and errors. The rejection value always carries a `message`, and a `failedItems` array when individual items failed rather than the request as a whole. Each entry in `failedItems` carries the `path`, `message`, and — when the server gave one — the `code` and `status` for that item. A partially failed upload is not rolled back: the items that were written stay written.
When every failed item failed the same way, that `code` and `status` are also set on the rejection value itself, because the cause belongs to the request rather than to any one file. An upload that exceeds the account's storage quota is the common case: it rejects with `code: 'storage_limit_reached'` and `status: 413` however many files were in it.
@@ -85,7 +88,7 @@ When using signed uploads, a separate thumbnail transfer that fails or exceeds f
## Examples
<strong class="example-title">Upload a file from a file input</strong>
### Upload a file from a file input
```html;fs-upload
<html>
+12 -8
View File
@@ -4,7 +4,9 @@ description: Write data to files in the user's own Puter file system.
platforms: [websites, apps, nodejs, workers]
---
Writes data to a specified file path. This method is useful for creating new files or modifying existing ones in the Puter cloud storage.
Writes data to a specified file path.
This method is useful for creating new files or modifying existing ones in the Puter cloud storage.
## Syntax
@@ -30,9 +32,11 @@ The data to write to the file. If omitted, an empty file is created.
The options for the `write` operation. The following options are supported:
- `overwrite` (boolean) - Whether to overwrite the file if it already exists. Defaults to `true`.
- `dedupeName` (boolean) - Whether to deduplicate the file name if it already exists. Defaults to `false`.
- `createMissingParents` (boolean) - Whether to create missing parent directories. Defaults to `false`.
| Option | Type | Description |
|--------|------|-------------|
| `createMissingParents` | `Boolean` | Whether to create missing parent directories. Defaults to `false`. |
| `overwrite` | `Boolean` | Whether to overwrite the file if it already exists. Defaults to `true`. |
| `dedupeName` | `Boolean` | Whether to deduplicate the file name if it already exists. Defaults to `false`. |
#### `file` (File)
@@ -44,7 +48,7 @@ Returns a `Promise` that resolves to the [`FSItem`](/Objects/fsitem) object of t
## Examples
<strong class="example-title">Create a new file containing "Hello, world!"</strong>
### Create a new file containing "Hello, world!"
```html;fs-write
<html>
@@ -60,7 +64,7 @@ Returns a `Promise` that resolves to the [`FSItem`](/Objects/fsitem) object of t
</html>
```
<strong class="example-title">Create a new file with input coming from a file input</strong>
### Create a new file with input coming from a file input
```html;fs-write-from-input
<html>
@@ -81,7 +85,7 @@ Returns a `Promise` that resolves to the [`FSItem`](/Objects/fsitem) object of t
</html>
```
<strong class="example-title">Create a file with duplicate name handling</strong>
### Create a file with duplicate name handling
```html;fs-write-dedupe
<html>
@@ -101,7 +105,7 @@ Returns a `Promise` that resolves to the [`FSItem`](/Objects/fsitem) object of t
</html>
```
<strong class="example-title">Create a new file with missing parent directories</strong>
### Create a new file with missing parent directories
```html;fs-write-create-missing-parents
<html>
Loaded 100 of 392 files, more files were not shown because too many files have changed in this diff. Show more