Compare commits

...
Author SHA1 Message Date
Nariman Jelveh 76ad6cbc2e Keep dropped desktop icons fully on screen, and fill the phone popover
A desktop icon drop is accepted only where the whole item fits above the
bottom edge. Phone popovers use the full viewport height.
2026-11-11 18:38:36 -07:00
Nariman Jelveh 9251bfa30b Keep desktop backdrops above ordinary windows
A backdrop's z-index used to take the taskbar's as a floor, which kept
modal dialogs on /desktop above every ordinary window, including ones
focused after the dialog opened. Keep that floor on the desktop; the
dashboard and fullpage mode stack as before.

Also drops commented-out geometry that referenced window.taskbar_height,
and a dashboard comment about the removed fullpage minimize rule.
2026-11-11 18:15:40 -07:00
Nariman Jelveh bf99c3c680 Remove the desktop taskbar
The desktop no longer has a taskbar. Windows on /desktop can't be
minimized, since nothing could bring them back; the dashboard still
minimizes into app tiles. The desktop and maximized windows use the
full page height.

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

puter.ui.createWindow() still accepts show_in_taskbar, which has no
effect and is marked deprecated.
2026-11-11 18:02:40 -07:00
Nariman Jelveh 72de6e16b2 Remove the desktop wallpaper (#4604)
The desktop no longer shows a wallpaper. It shows the page's plain
background color: white, or #1e1e1e in dark mode. The sign-in dialogs
and account picker that opened over the wallpaper now open over that
color too.

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

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

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

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

* Remove the desktop's My Websites window

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

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

* Remove the desktop's Task Manager window

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

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

* Remove the desktop's Change Desktop Background window

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

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

* Remove the desktop's Start menu

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

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

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

* Remove the desktop's Search window

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

The backend /search endpoint is unchanged.

* Remove the desktop toolbar

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

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

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

* Remove the desktop's Share window

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

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

* Remove the desktop's Welcome window

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

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

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

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

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

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

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

* Remove the desktop's Publish Worker window

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

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

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

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

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

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

* Remove the Open Desktop card from the dashboard Home tab

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

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

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

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

* Update RecommendedAppsService.ts

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Windows opened by path, such as with Ctrl-click on a breadcrumb or sidebar
entry, never received the marker used to find a deleted folder's windows,
so they stayed open on a folder that no longer existed.
2026-11-10 11:23:30 -07:00
226 changed files with 5641 additions and 12154 deletions

No files matched your search

+1 -1
View File
@@ -40,7 +40,7 @@ The following have already been reviewed and determined **not to be vulnerabilit
- **SSRF via `secureFetch`.** Production routes outbound requests through an isolated proxy that has no access to internal/SSRF-sensitive resources.
- **Attacks that depend on guessing an `appInstanceID` or app UID.** These are random 128-bit secret values and are not considered guessable.
- **Apps invoking drivers, creating workers, or using KV.** Applications are intended to do this; worker permissions are scoped to the owning app. This is by design.
- **App metadata or app user-count "leaks".** This information is currently public by design. This covers **private apps** too: private apps are an unreleased, admin-only beta for paid listings in the Puter App Center. Their `index_url` and other metadata are not secret, the flag is not user-settable, and no production app relies on it. Reports that a private app's metadata is reachable through a sibling route (taskbar items, `/get-launch-apps`, `index_url` drift on the hosting gate, etc.) are normalization work, not vulnerabilities.
- **App metadata or app user-count "leaks".** This information is currently public by design. This covers **private apps** too: private apps are an unreleased, admin-only beta for paid listings in the Puter App Center. Their `index_url` and other metadata are not secret, the flag is not user-settable, and no production app relies on it. Reports that a private app's metadata is reachable through a sibling route (`/get-launch-apps`, `index_url` drift on the hosting gate, etc.) are normalization work, not vulnerabilities.
- **Worker hot-reload driven by a share recipient.** Sharing a worker's source file with write access is how you let a collaborator change that worker's code and have it deploy live. The redeploy running as the file owner, with the owner's worker credentials, is the intended behavior of that grant — the owner chose to hand out write access to executable code. If you do not want that, do not share the source file with write access.
- **Re-claiming a site or worker name its owner deleted.** A hosted site or worker name that its owner deletes is treated as abandoned by that owner. If one of their apps still points at it, whoever claims the name next serves that app's `index_url` and receives what the app is launched with, and a new app on the same origin may share the old one's identity. Guarding app identities against being recycled this way is ongoing hardening, not a security boundary, so new ways to re-claim an abandoned name, or to inherit an app's tokens or data through one, are not eligible.
- **Share-mode downgrades that do not cascade.** Demoting a delegate does not retroactively revoke the grants that delegate already issued downstream. Shares are independent grants once issued, not a live-evaluated chain. Revoking the downstream grant is a separate, supported action.
+61 -1
View File
@@ -259,6 +259,36 @@ no user to name), puter.js opens the dashboard's upgrade page in a new tab with
what was refused, through a consent dialog when the click has expired or the
tab is blocked, and `requestUpgrade()` resolves `{ upgraded: false }`.
## Top-up
`GET /embed/top-up` is the deployment's top-up dialog, where a user with a plan
buys add-on credit, served and framed like the upgrade: a transparent GUI page
covering the host with no box or close button, allowing `payment` and
`otp-credentials`, with Escape left to the dialog. Its fragment names `user`.
puter.js frames it for the **Add credits** item of `<puter-user-menu>`, which
shows only when whoami reports `subscribed: true` and no `team` paying for the
account. On a page that can't frame the GUI, the item opens the dashboard with
`?topup=` in a new tab instead.
The GUI reports `unavailable` unless its session belongs to `user`, the account
has no verification or password change waiting, and the deployment defines
`window.UITopUp` with `UITopUp.embeddable === true`. Otherwise it runs:
```js
new UITopUp({ onClose }).open();
```
`open()` resolves once the dialog has loaded the account and shows what it can
buy, and `onClose({ toppedUp })` must run exactly once, when the dialog closes
or when it declines to open for the account. The GUI then posts `{ msg: 'puterPopupFrame', state: 'closed', toppedUp }`
and the page removes the frame. When the frame can't show the top-up, puter.js
opens the dashboard's top-up in a new tab, as it does the upgrade.
While the top-up shows, a call refused for funds still rejects but opens no
usage limit dialog over it, and `requestUpgrade()` frames nothing over it: it
resolves `{ upgraded: false }` once the top-up closes.
## Email confirmation
`GET /embed/request-email-confirmation` walks a first-party page's user through
@@ -292,6 +322,36 @@ app reads from the desktop's answer. A call made while the frame shows settles
with it. A frame that is refused, never ready, or `unavailable` resolves
`{ response: false }`, since there's no popup to fall back to.
## Custom domains
`GET /embed/attach-custom-domain` is the custom domain dialog of
`puter.hosting.attach()`, the popup at `/action/attach-custom-domain`, served
like the upgrade: the GUI shell with the same framing rules, redirects and
`no-store`, run only when framed by an allowed page. puter.js frames it on a
signed-in first-party page (the same pages as the pickers).
The frame covers the page with no box or close button, over a transparent GUI
page, so the dialog floats over the host with its own scrim as it does on the
desktop. The frame allows `clipboard-write`, for the dialog's copy buttons, as
well as `otp-credentials`. Escape on the page is left to the dialog, which
doesn't close while a request is in flight. Its fragment names `user` (the
page's signed-in user), `subdomain` (the site to attach a domain to) and
`msg_id`.
The GUI reports `unavailable` unless its session belongs to `user` and the
account has no verification or password change waiting. It then runs the
popup's action unchanged, with the framing page as the requester the dialog
names: it posts `ready` once the dialog is on the page, answers
`{ msg: 'customDomainAttached', domain, original_msg_id }` once the dialog has
closed and its exit has played, and then posts `closed`. `domain` is the domain the user chose, or
null. `attach()` resolves it. A frame that closes without an answer, or a
loading scrim the user dismisses, resolves null.
A call made while the frame shows resolves null without replacing it, as a
second call does on the desktop. A frame that is refused, never ready, or
`unavailable` falls back to the popup, which can sign in, through a consent
dialog when the click has expired.
## Checks
Run the GUI component/browser tests (with the SDK bundle built and Playwright
@@ -299,7 +359,7 @@ 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 src/puter-js/src/lib/guiEmbed.test.js src/puter-js/src/modules/UI.showFeedbackDialog.test.js src/puter-js/src/modules/Auth.signInFrame.test.js src/puter-js/src/modules/UI.pickerFrame.test.js src/puter-js/src/modules/UI.requestUpgrade.test.js src/puter-js/src/modules/UI.showTopUp.test.js src/puter-js/src/modules/UI.attachCustomDomainFrame.test.js src/puter-js/src/lib/upgradePrompt.test.js src/puter-js/src/modules/UsageLimitDialog.upgrade.test.js
npx vitest run --config src/gui/vitest.config.js src/gui/src/helpers/popupFrame.test.js
npx vitest run --config src/backend/vitest.config.ts src/backend/server.test.ts
```
+40 -10
View File
@@ -257,8 +257,41 @@ describe('whoami extension — handleWhoami', () => {
expect(body.created_ts).toBeGreaterThan(0);
// `directories` is only sent to user actors — confirm it’s present.
expect(body.directories).toBeDefined();
// taskbar_items is only sent to user actors.
expect(body).toHaveProperty('taskbar_items');
});
it('leaves out taskbar items saved on the account', async () => {
const user = await seedUser();
await server.stores.user.update(user.id as number, {
taskbar_items: JSON.stringify([{ type: 'app', name: 'editor' }]),
});
const { res, captured } = makeRes();
await runWithContext(
{ actor: { user: { uuid: user.uuid, id: user.id as number } } },
() => handleWhoami(makeReq(), res),
);
expect(captured.body).not.toHaveProperty('taskbar_items');
});
it('leaves out a desktop background saved on the account', async () => {
const user = await seedUser();
await server.stores.user.update(user.id as number, {
desktop_bg_url: 'https://cdn.test/wallpaper.png',
desktop_bg_color: '#000000',
desktop_bg_fit: 'cover',
});
const { res, captured } = makeRes();
await runWithContext(
{ actor: { user: { uuid: user.uuid, id: user.id as number } } },
() => handleWhoami(makeReq(), res),
);
const body = captured.body as Record<string, unknown>;
expect(body).not.toHaveProperty('desktop_bg_url');
expect(body).not.toHaveProperty('desktop_bg_color');
expect(body).not.toHaveProperty('desktop_bg_fit');
});
it('reports the SMS-to-card fallback only once a send has opened it', async () => {
@@ -322,7 +355,7 @@ describe('whoami extension — handleWhoami', () => {
expect(flags.payment_bypass).toBeUndefined();
});
it('strips desktop_bg_*, created_ts and human_readable_age fields for app actors', async () => {
it('strips created_ts and human_readable_age fields for app actors', async () => {
const user = await seedUser();
const { res, captured } = makeRes();
@@ -340,9 +373,6 @@ describe('whoami extension — handleWhoami', () => {
expect(body.app_name).toBe('app-test-actor');
// is_user_token is stripped for app actors.
expect(body.is_user_token).toBeUndefined();
expect(body.desktop_bg_url).toBeUndefined();
expect(body.desktop_bg_color).toBeUndefined();
expect(body.desktop_bg_fit).toBeUndefined();
expect(body.human_readable_age).toBeUndefined();
// Account age, in either form, is not exposed to apps.
expect(body.created_ts).toBeUndefined();
@@ -432,7 +462,7 @@ describe('whoami extension — handleWhoami', () => {
});
});
it('cannot add taskbar_items for an app actor, which core omits', async () => {
it('cannot add directories for an app actor, which core omits', async () => {
const user = await seedUser();
const body = await whoamiWithListener(
makeActor({
@@ -440,11 +470,11 @@ describe('whoami extension — handleWhoami', () => {
app: { uid: 'app-test-actor' },
}),
(_key, event) => {
event.details.taskbar_items = [{ name: 'injected' }];
event.details.directories = { '/injected': 'uuid' };
},
);
expect(body).not.toHaveProperty('taskbar_items');
expect(body).not.toHaveProperty('directories');
});
});
@@ -525,7 +555,7 @@ describe('whoami extension — handleWhoami', () => {
expect(body.otp_secret).toBeUndefined();
expect(body.signup_ip).toBeUndefined();
// Not just absent as a key — the values must not appear anywhere
// in the payload (nested under metadata, taskbar items, …).
// in the payload (nested under metadata, …).
const serialized = JSON.stringify(body);
expect(serialized).not.toContain('5551234567');
expect(serialized).not.toContain('fp_ABC123');
+2 -16
View File
@@ -1,6 +1,5 @@
import { Context } from '@heyputer/backend/src/core';
import { extension } from '@heyputer/backend/src/extensions';
import { APP_ICON_SIZES } from '@heyputer/backend/src/util/appIcon.js';
import {
buildUserDetails,
scrubSensitive,
@@ -54,19 +53,10 @@ export const handleWhoami = async (
return;
}
const rawIconSize =
typeof req.query?.icon_size === 'string'
? Number(req.query.icon_size)
: undefined;
const iconSize =
rawIconSize !== undefined && APP_ICON_SIZES.includes(rawIconSize)
? rawIconSize
: undefined;
const details = await buildUserDetails(
user,
{ config: extension.config, clients, stores, services },
{ isUser, iconSize, noIcons: !iconSize },
{ isUser },
);
details.human_readable_age = user.timestamp
? timeago.format(new Date(user.timestamp as string))
@@ -81,9 +71,6 @@ export const handleWhoami = async (
delete details.email;
delete details.unconfirmed_email;
}
delete details.desktop_bg_url;
delete details.desktop_bg_color;
delete details.desktop_bg_fit;
delete details.human_readable_age;
delete details.created_ts;
delete details.is_user_token;
@@ -121,8 +108,7 @@ export const handleWhoami = async (
}
const subscription = details.subscription as
| { offering?: Record<string, unknown> }
| undefined;
{ offering?: Record<string, unknown> } | undefined;
if (subscription?.offering) {
delete subscription.offering.group;
delete subscription.offering.benefits;
@@ -52,8 +52,8 @@ const APP_READ_LIMIT = {
/**
* Unauthenticated icon serving; no actor to key on, so the bucket is the
* address — and an address is a NAT, a campus or a carrier gateway that can
* hold hundreds of desktops. Each desktop boot pulls the taskbar's icons at
* once, so a single burst from one network is already thousands of requests.
* hold hundreds of desktops. Each dashboard load pulls its app icons at once,
* so a single burst from one network is already thousands of requests.
* Responses are publicly cacheable and usually a redirect, so the ceiling is
* not protecting bandwidth; it is there so a client looping on a broken icon
* can't spin unbounded.
@@ -523,7 +523,7 @@ export class AppController extends PuterController {
};
// Icons are <img src> targets from the GUI (root) AND resolved via
// api_base_url in taskbar payloads. Register on both so either origin
// api_base_url in app summaries. Register on both so either origin
// works without a cross-subdomain redirect.
router.get(
'/app-icon/:app_uid',
@@ -1271,7 +1271,7 @@ describe('AppController app-icon rate limit', () => {
it('sizes the icon bucket for a whole network rather than one desktop', () => {
// Icons are unauthenticated `<img src>` targets, so the only key is
// the address — which one NAT shares across every desktop behind it,
// and each boot pulls the taskbar's icons in a burst.
// and each dashboard load pulls its app icons in a burst.
for (const path of ['/app-icon/:app_uid', '/app-icon/:app_uid/:size']) {
const route = router.routes.find(
(r) => r.method === 'get' && r.path === path,
@@ -1416,7 +1416,7 @@ describe('AuthController.handleLogin', () => {
is_user_token: true,
});
expect(body.user.directories).toBeTypeOf('object');
expect(Array.isArray(body.user.taskbar_items)).toBe(true);
expect(body.user).not.toHaveProperty('taskbar_items');
});
// A deleted row still answering from cache reaches the session INSERT.
@@ -25,18 +25,13 @@ const ALLOWED_SORT_BY = ['name', 'size', 'modified', 'type'];
const ALLOWED_SORT_ORDER = ['asc', 'desc'];
/**
* Desktop/UI preference routes.
*
* Two categories:
*
* - User-level: desktop background, taskbar items (UserStore)
* - Folder-level: layout, sort_by/sort_order (fsentries table)
* Folder view preference routes: layout and sort_by/sort_order, stored on the
* folder's fsentries row.
*/
/**
* Desktop preference writes — background, taskbar, layout, sort order. All four
* persist to the user row on every call, and the GUI fires them on direct user
* action, so a per-minute ceiling well above human speed is enough to catch a
* stuck client.
* Desktop preference writes — layout, sort order. Each persists on every call,
* and the GUI fires them on direct user action, so a per-minute ceiling well
* above human speed is enough to catch a stuck client.
*/
const PREFERENCE_WRITE_LIMIT = {
scope: 'desktop-preference',
@@ -47,89 +42,6 @@ const PREFERENCE_WRITE_LIMIT = {
export class DesktopController extends PuterController {
registerRoutes(router) {
// -- Desktop background --------------------------------------
router.post(
'/set-desktop-bg',
{
subdomain: 'api',
requireUserActor: true,
allowFullAccessToken: true,
rateLimit: PREFERENCE_WRITE_LIMIT,
},
async (req, res) => {
const { url, color, fit } = req.body ?? {};
const patch = {};
if (url !== undefined) {
if (url !== null && typeof url !== 'string') {
throw new HttpError(
400,
'`url` must be a string or null',
{ legacyCode: 'bad_request' },
);
}
patch.desktop_bg_url = url;
}
if (color !== undefined) {
if (color !== null && typeof color !== 'string') {
throw new HttpError(
400,
'`color` must be a string or null',
{ legacyCode: 'bad_request' },
);
}
patch.desktop_bg_color = color;
}
if (fit !== undefined) {
if (fit !== null && typeof fit !== 'string') {
throw new HttpError(
400,
'`fit` must be a string or null',
{ legacyCode: 'bad_request' },
);
}
patch.desktop_bg_fit = fit;
}
if (Object.keys(patch).length === 0) {
throw new HttpError(400, 'No fields provided', {
legacyCode: 'bad_request',
});
}
await this.stores.user.update(req.actor.user.id, patch);
res.json({});
},
);
// -- Taskbar items -------------------------------------------
router.post(
'/update-taskbar-items',
{
subdomain: 'api',
requireUserActor: true,
allowFullAccessToken: true,
rateLimit: PREFERENCE_WRITE_LIMIT,
},
async (req, res) => {
const { items } = req.body ?? {};
if (!Array.isArray(items)) {
throw new HttpError(
400,
'Missing or invalid `items` array',
{ legacyCode: 'bad_request' },
);
}
await this.stores.user.update(req.actor.user.id, {
taskbar_items: JSON.stringify(items),
});
res.json({});
},
);
// -- Folder layout -------------------------------------------
router.post(
@@ -130,147 +130,17 @@ const callRoute = async (
});
};
// ── /set-desktop-bg ─────────────────────────────────────────────────
describe('DesktopController POST /set-desktop-bg', () => {
it('persists url/color/fit on the user row', async () => {
const { actor, userId } = await makeUser();
const { res, captured } = makeRes();
await callRoute(
'post',
'/set-desktop-bg',
makeReq({
body: {
url: 'https://cdn.test/wallpaper.png',
color: '#000000',
fit: 'cover',
},
actor,
}),
res,
);
expect(captured.body).toEqual({});
const refreshed = await server.stores.user.getById(userId);
expect(refreshed?.desktop_bg_url).toBe(
'https://cdn.test/wallpaper.png',
);
expect(refreshed?.desktop_bg_color).toBe('#000000');
expect(refreshed?.desktop_bg_fit).toBe('cover');
describe('DesktopController routes', () => {
it('has no desktop background route', () => {
expect(
router.routes.some((r) => r.path === '/set-desktop-bg'),
).toBe(false);
});
it('persists only the supplied fields (partial update)', async () => {
const { actor, userId } = await makeUser();
const { res } = makeRes();
await callRoute(
'post',
'/set-desktop-bg',
makeReq({ body: { color: '#ffffff' }, actor }),
res,
);
const refreshed = await server.stores.user.getById(userId);
expect(refreshed?.desktop_bg_color).toBe('#ffffff');
// Untouched fields remain at their column default.
expect(refreshed?.desktop_bg_url).toBeFalsy();
expect(refreshed?.desktop_bg_fit).toBeFalsy();
});
it('passes through `null` to clear a field', async () => {
const { actor, userId } = await makeUser();
// First populate, then clear.
const populate = makeRes();
await callRoute(
'post',
'/set-desktop-bg',
makeReq({
body: { url: 'https://cdn.test/x.png' },
actor,
}),
populate.res,
);
const before = await server.stores.user.getById(userId);
expect(before?.desktop_bg_url).toBe('https://cdn.test/x.png');
const clear = makeRes();
await callRoute(
'post',
'/set-desktop-bg',
makeReq({ body: { url: null }, actor }),
clear.res,
);
const after = await server.stores.user.getById(userId);
expect(after?.desktop_bg_url).toBeNull();
});
it('throws 400 when url is not a string or null', async () => {
const { actor } = await makeUser();
const { res } = makeRes();
await expect(
callRoute(
'post',
'/set-desktop-bg',
makeReq({ body: { url: 123 }, actor }),
res,
),
).rejects.toMatchObject({ statusCode: 400 });
});
it('throws 400 when no fields are provided', async () => {
const { actor } = await makeUser();
const { res } = makeRes();
await expect(
callRoute(
'post',
'/set-desktop-bg',
makeReq({ body: {}, actor }),
res,
),
).rejects.toMatchObject({ statusCode: 400 });
});
});
// ── /update-taskbar-items ───────────────────────────────────────────
describe('DesktopController POST /update-taskbar-items', () => {
it('persists items as a JSON-encoded string', async () => {
const { actor, userId } = await makeUser();
const items = [{ name: 'editor' }, { name: 'browser' }];
const { res } = makeRes();
await callRoute(
'post',
'/update-taskbar-items',
makeReq({ body: { items }, actor }),
res,
);
const refreshed = await server.stores.user.getById(userId);
expect(refreshed?.taskbar_items).toBe(JSON.stringify(items));
});
it('throws 400 when items is missing', async () => {
const { actor } = await makeUser();
const { res } = makeRes();
await expect(
callRoute(
'post',
'/update-taskbar-items',
makeReq({ body: {}, actor }),
res,
),
).rejects.toMatchObject({ statusCode: 400 });
});
it('throws 400 when items is not an array', async () => {
const { actor } = await makeUser();
const { res } = makeRes();
await expect(
callRoute(
'post',
'/update-taskbar-items',
makeReq({ body: { items: 'oops' }, actor }),
res,
),
).rejects.toMatchObject({ statusCode: 400 });
it('has no taskbar items route', () => {
expect(
router.routes.some((r) => r.path === '/update-taskbar-items'),
).toBe(false);
});
});
@@ -501,6 +501,29 @@ describe('DriverController.#handleCall (via captured router)', () => {
expect(body.service.name).toBe('puter-kvstore');
});
it('treats null `args` as no arguments', async () => {
const actor = await makeUserActor();
await server.stores.permission.setFlatUserPerm(
actor.user!.id!,
'service:puter-subdomains:ii:puter-subdomains',
{
permission: 'service:puter-subdomains:ii:puter-subdomains',
deleted: false,
issuer_user_id: actor.user!.id!,
} as never,
);
const res = makeRes();
const req = makeReq(
{ interface: 'puter-subdomains', method: 'select', args: null },
actor,
);
await runWithContext({ actor }, () =>
routes['POST /call'](req, res as unknown as Response, () => {}),
);
expect((res.body as { success: boolean }).success).toBe(true);
});
it('pipes a stream-shaped result instead of JSON', async () => {
// Use an ephemeral driver registered onto the controller's bag.
const streamPayload = Buffer.from('hello-world');
@@ -276,8 +276,10 @@ export class DriverController extends PuterController {
interface: ifaceName,
method,
driver: driverName,
args = {},
args: rawArgs,
} = (req.body ?? {}) as Record<string, unknown>;
// Drivers read fields off `args`, so a null one counts as absent.
const args = rawArgs ?? {};
if (!ifaceName || typeof ifaceName !== 'string') {
throw new HttpError(400, 'Missing or invalid `interface`', {
@@ -5111,9 +5111,8 @@ describe('LegacyFSController.updateFsentryThumbnail', () => {
// ── GET /get-launch-apps ────────────────────────────────────────────
//
// `recent` is a launch-metadata producer: it returns `index_url` for
// apps the user has opened before. The taskbar happens to launch these
// by name (so AppDriver's hosted-backing guard applies), but the field
// is served regardless, so the guard is applied here too.
// apps the user has opened before. The field is served whoever reads it,
// so AppDriver's hosted-backing guard is applied here too.
describe('LegacyFSController GET /get-launch-apps', () => {
const hostedUrl = (sub: string) => `https://${sub}.site.puter.localhost/`;
@@ -401,11 +401,9 @@ export class LegacyFSController extends PuterController {
.filter(Boolean);
// Don't hand out an index_url whose puter-hosted backing is
// gone or reclaimed. The taskbar launches recents by name (so
// AppDriver's guard applies), but this list is a
// launch-metadata producer like any other — a future consumer
// reading index_url straight off it shouldn't inherit a stale
// origin.
// gone or reclaimed. This list is a launch-metadata producer
// like any other — a consumer reading index_url straight off
// it shouldn't inherit a stale origin.
let backingGoneFlags: boolean[];
try {
backingGoneFlags =
@@ -950,9 +948,7 @@ export class LegacyFSController extends PuterController {
// Trash, and `null`/`{}` when restoring. See
// `src/gui/src/helpers.js` → `window.move_items`.
newMetadata: (body.new_metadata ?? undefined) as
| Record<string, unknown>
| null
| undefined,
Record<string, unknown> | null | undefined,
});
const overwrittenEntry = replacedByMove(overwriteTarget, moved, name);
const oldPath = source.path;
@@ -1426,8 +1422,7 @@ export class LegacyFSController extends PuterController {
}
type SignedOrEmpty =
| (SignedFile & { path?: string })
| Record<string, never>;
(SignedFile & { path?: string }) | Record<string, never>;
const result: { signatures: SignedOrEmpty[]; token?: string } = {
signatures: [],
};
@@ -2054,10 +2049,7 @@ export class LegacyFSController extends PuterController {
const subjectRef = body.subject;
const appRef = body.app;
const mode = (getString(body, 'mode') ?? 'read') as
| 'see'
| 'list'
| 'read'
| 'write';
'see' | 'list' | 'read' | 'write';
if (!subjectRef || !appRef)
throw new HttpError(400, '`subject` and `app` are required', {
legacyCode: 'bad_request',
@@ -36,9 +36,9 @@ import type {
/**
* GUI popups a first-party page can show in a frame at `/embed/<action>`,
* instead of opening `/action/<action>` in a window, plus the upgrade dialog,
* which it would otherwise open in a dashboard tab, and the email confirmation,
* which it otherwise can't show.
* instead of opening `/action/<action>` in a window, plus the upgrade and
* top-up dialogs, which it would otherwise open in a dashboard tab, and the
* email confirmation, which it otherwise can't show.
*/
export const FRAMED_POPUP_ACTIONS = [
'sign-in',
@@ -46,7 +46,9 @@ export const FRAMED_POPUP_ACTIONS = [
'show-save-file-picker',
'show-directory-picker',
'upgrade',
'top-up',
'request-email-confirmation',
'attach-custom-domain',
] as const;
/** Longest description/og:description/twitter:description on `/app/<name>`. */
@@ -0,0 +1,89 @@
/*
* Copyright (C) 2024-present Puter Technologies Inc.
*
* This file is part of Puter.
*
* Puter is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import { randomUUID } from 'node:crypto';
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
import {
setupPuterTestEnv,
TEST_USER_CREDENTIALS,
type PuterTestEnv,
} from '../../testUtil.js';
/** A PUT body is the file, whatever content type the client labels it with. */
describe('PUT stores the body as sent', () => {
let env: PuterTestEnv;
beforeAll(async () => {
env = await setupPuterTestEnv();
}, 60_000);
afterAll(async () => {
await env?.shutdown();
});
const dav = (path: string, init: RequestInit) => {
const port = new URL(env.apiOrigin).port;
const auth = Buffer.from(
`${TEST_USER_CREDENTIALS.username}:${TEST_USER_CREDENTIALS.password}`,
).toString('base64');
return fetch(`http://dav.puter.localhost:${port}${encodeURI(path)}`, {
...init,
headers: { Authorization: `Basic ${auth}`, ...init.headers },
});
};
it.each([
['application/json', '{"name":"report","rows":[1,2,3]}'],
// Not JSON at all: the label alone must not get the body rejected.
['application/json', 'not json'],
['text/plain;actually=json', '{"a":1}'],
['application/x-www-form-urlencoded', 'a=1&b=two'],
['application/octet-stream', 'plain bytes'],
])(
'with Content-Type %s',
async (contentType, content) => {
const path = `/${env.users.user.username}/Documents/put-${randomUUID().slice(0, 8)}.bin`;
const put = await dav(path, {
method: 'PUT',
headers: { 'Content-Type': contentType },
body: content,
});
expect(put.status).toBe(201);
const get = await dav(path, { method: 'GET' });
expect(get.status).toBe(200);
expect(await get.text()).toBe(content);
},
30_000,
);
it('with a form body over the form parser limit', async () => {
const path = `/${env.users.user.username}/Documents/put-${randomUUID().slice(0, 8)}.bin`;
const content = `a=${'x'.repeat(200 * 1024)}`;
const put = await dav(path, {
method: 'PUT',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: content,
});
expect(put.status).toBe(201);
const get = await dav(path, { method: 'GET' });
expect(await get.text()).toBe(content);
}, 30_000);
});
@@ -224,7 +224,7 @@ const extractToken = (
}
}
// 5. Query string (used by e.g. QR login, asset URLs).
// 5. Query string (used by e.g. asset URLs).
const queryToken = (req.query as { auth_token?: unknown } | undefined)
?.auth_token;
if (typeof queryToken === 'string' && queryToken.length > 0) {
@@ -0,0 +1,263 @@
/*
* Copyright (C) 2024-present Puter Technologies Inc.
*
* This file is part of Puter.
*
* Puter is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import type { Server } from 'node:http';
import type { AddressInfo } from 'node:net';
import { brotliCompressSync, deflateSync, gzipSync } from 'node:zlib';
import express, {
type ErrorRequestHandler,
type RequestHandler,
} from 'express';
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
import { SLICE_BYTES } from '../../../util/slicedJson';
import { createJsonBodyParser } from './jsonBody';
const LIMIT = 4 * 1024 * 1024;
const TEXT_AS_JSON = 'text/plain;actually=json';
type Verify = NonNullable<Parameters<typeof express.json>[0]>['verify'];
const captureRawBody: Verify = (req, _res, buf) => {
(req as { rawBody?: Buffer }).rawBody = buf;
};
/** An app that answers with what its parsers left on the request. */
const listen = (parsers: RequestHandler[]): Promise<Server> => {
const app = express();
app.use(...parsers);
app.post('/', (req, res) => {
const rawBody = (req as { rawBody?: Buffer }).rawBody;
res.json({
body: req.body,
hasBody: req.body !== undefined,
rawBody: rawBody?.toString('base64'),
});
});
const onError: ErrorRequestHandler = (err, _req, res, _next) => {
res.status(err.statusCode ?? 500).json({ type: err.type });
};
app.use(onError);
return new Promise((resolve) => {
const server = app.listen(0, '127.0.0.1', () => resolve(server));
});
};
describe('createJsonBodyParser', () => {
let sliced: Server;
let framework: Server;
beforeAll(async () => {
sliced = await listen([
createJsonBodyParser({ limit: LIMIT, verify: captureRawBody }),
]);
// What the server ran before: one parser per content type.
framework = await listen([
express.json({ limit: LIMIT, verify: captureRawBody }),
express.json({
limit: LIMIT,
type: (req) => req.headers['content-type'] === TEXT_AS_JSON,
verify: captureRawBody,
}),
]);
});
afterAll(() => {
sliced?.close();
framework?.close();
});
const post = async (
server: Server,
body: string | Buffer | undefined,
headers: Record<string, string>,
) => {
const { port } = server.address() as AddressInfo;
const response = await fetch(`http://127.0.0.1:${port}/`, {
method: 'POST',
headers,
body,
});
return { status: response.status, answer: await response.json() };
};
const large = `${JSON.stringify({
text: 'é😀 "quoted" \\ line\n'.repeat(SLICE_BYTES / 8),
list: Array.from({ length: 20_000 }, (_, i) => ({
i,
on: i % 2 === 0,
})),
}).slice(0, -1)},"__proto__":{"nested":true}}`;
it.each<[string, string | Buffer | undefined, Record<string, string>]>([
['an object', '{"a":1}', { 'Content-Type': 'application/json' }],
['an array', '[1,2]', { 'Content-Type': 'application/json' }],
[
'a body sent as text',
'{"interface":"x","auth_token":"t"}',
{ 'Content-Type': TEXT_AS_JSON },
],
['a large body', large, { 'Content-Type': 'application/json' }],
['a large body sent as text', large, { 'Content-Type': TEXT_AS_JSON }],
[
'a charset parameter',
large,
{ 'Content-Type': 'application/json; charset=UTF-8' },
],
[
'a quoted charset parameter',
'{"a":"é"}',
{ 'Content-Type': 'application/json;charset="utf-8"' },
],
[
'another parameter',
'{"a":1}',
{ 'Content-Type': 'application/json; profile=x' },
],
['an empty body', '', { 'Content-Type': 'application/json' }],
['no body', undefined, { 'Content-Type': 'application/json' }],
[
'a byte order mark',
`\ufeff${large}`,
{ 'Content-Type': 'application/json' },
],
[
'only a byte order mark',
'\ufeff',
{ 'Content-Type': 'application/json' },
],
['only whitespace', ' \n', { 'Content-Type': 'application/json' }],
['a bare string', '"text"', { 'Content-Type': 'application/json' }],
['a bare number', ' 12', { 'Content-Type': 'application/json' }],
['null', 'null', { 'Content-Type': 'application/json' }],
['malformed JSON', '{"a":', { 'Content-Type': 'application/json' }],
[
'malformed large JSON',
`${large.slice(0, -1)},]`,
{ 'Content-Type': 'application/json' },
],
[
'a large bare string',
JSON.stringify('x'.repeat(4 * SLICE_BYTES)),
{ 'Content-Type': 'application/json' },
],
[
'invalid UTF-8',
Buffer.concat([
Buffer.from('{"a":"'),
Buffer.from([0xff, 0xe2, 0x82]),
Buffer.from('"}'),
]),
{ 'Content-Type': 'application/json' },
],
[
'a body over the limit',
`["${'x'.repeat(LIMIT)}"]`,
{ 'Content-Type': 'application/json' },
],
[
'a gzipped body',
gzipSync(large),
{ 'Content-Type': 'application/json', 'Content-Encoding': 'gzip' },
],
[
'a deflated body',
deflateSync(large),
{
'Content-Type': 'application/json',
'Content-Encoding': 'deflate',
},
],
[
'a brotli body',
brotliCompressSync(large),
{ 'Content-Type': 'application/json', 'Content-Encoding': 'br' },
],
[
'a body that inflates past the limit',
gzipSync(`["${'x'.repeat(LIMIT)}"]`),
{ 'Content-Type': 'application/json', 'Content-Encoding': 'gzip' },
],
[
'an unknown content encoding',
'{"a":1}',
{ 'Content-Type': 'application/json', 'Content-Encoding': 'lzw' },
],
['plain text', '{"a":1}', { 'Content-Type': 'text/plain' }],
[
'text with the marker and a charset',
'{"a":1}',
{ 'Content-Type': `${TEXT_AS_JSON}; charset=utf-8` },
],
[
'a JSON-suffixed type',
'{"a":1}',
{ 'Content-Type': 'application/vnd.api+json' },
],
[
'form data',
'a=1',
{ 'Content-Type': 'application/x-www-form-urlencoded' },
],
['no content type', '{"a":1}', { 'Content-Type': '' }],
])('answers %s the way express.json does', async (_name, body, headers) => {
const got = await post(sliced, body, headers);
const want = await post(framework, body, headers);
expect(got).toEqual(want);
});
it('leaves a body in another charset unread', async () => {
for (const charset of ['utf-16', 'utf8', 'latin1']) {
const { status, answer } = await post(
sliced,
Buffer.from('{"a":1}', 'utf16le'),
{ 'Content-Type': `application/json; charset=${charset}` },
);
expect(status).toBe(200);
expect(answer.hasBody).toBe(false);
}
// The last charset named is the one that counts.
const { answer } = await post(sliced, '{"a":1}', {
'Content-Type': 'application/json; charset=utf-8; charset=utf-16',
});
expect(answer.hasBody).toBe(false);
});
it('parses bodies that arrive together, each to its own result', async () => {
const bodies = Array.from({ length: 6 }, (_, n) =>
JSON.stringify({ n, pad: 'x'.repeat((n + 1) * SLICE_BYTES) }),
);
const answers = await Promise.all(
bodies.map((body) =>
post(sliced, body, { 'Content-Type': 'application/json' }),
),
);
answers.forEach(({ status, answer }, n) => {
expect(status).toBe(200);
expect(answer.body).toEqual(JSON.parse(bodies[n]!));
});
// A failed parse hands its turn on like a finished one.
const mixed = await Promise.all([
post(sliced, `${bodies[5]!},`, {
'Content-Type': 'application/json',
}),
post(sliced, bodies[4], { 'Content-Type': 'application/json' }),
post(sliced, bodies[3], { 'Content-Type': 'application/json' }),
]);
expect(mixed.map(({ status }) => status)).toEqual([400, 200, 200]);
});
});
@@ -0,0 +1,127 @@
/*
* Copyright (C) 2024-present Puter Technologies Inc.
*
* This file is part of Puter.
*
* Puter is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import express, { type Request, type RequestHandler } from 'express';
import { parseJsonInSlices, SLICE_BYTES } from '../../../util/slicedJson';
/** What puter.js labels a JSON driver call, to keep it a simple CORS request. */
const TEXT_AS_JSON = 'text/plain;actually=json';
const UTF8_CHARSET = /;\s*charset=("?)utf-8\1\s*(?:;|$)/i;
/** No charset, or exactly UTF-8. Anything else is left to `express.json`. */
const declaresUtf8 = (contentType: string): boolean => {
const mentions = contentType.match(/charset/gi)?.length ?? 0;
return mentions === 0 || (mentions === 1 && UTF8_CHARSET.test(contentType));
};
const isUtf8Json = (req: Request): boolean => {
const contentType = req.headers['content-type'];
if (contentType === TEXT_AS_JSON) return true;
return (
typeof contentType === 'string' &&
Boolean(req.is('application/json')) &&
declaresUtf8(contentType)
);
};
/** The error `express.json` raises, which the error handler answers with a 400. */
const parseFailed = (message: string): Error =>
Object.assign(new SyntaxError(message), {
status: 400,
statusCode: 400,
expose: true,
type: 'entity.parse.failed',
});
const waiting: Array<() => void> = [];
let parsing = false;
/**
* Bodies too large for one `JSON.parse` call parse one at a time, so a single
* tree is under construction however many arrive together.
*/
const parseInTurn = async (body: Buffer): Promise<unknown> => {
if (body.length <= SLICE_BYTES) return parseJsonInSlices(body);
if (parsing) await new Promise<void>((resolve) => waiting.push(resolve));
parsing = true;
try {
return await parseJsonInSlices(body);
} finally {
// Handing over keeps `parsing` set, so a new arrival can't cut in.
const next = waiting.shift();
if (next) next();
else parsing = false;
}
};
interface JsonBodyOptions {
limit: number;
verify?: NonNullable<Parameters<typeof express.raw>[0]>['verify'];
}
/**
* `express.json` for UTF-8 bodies, with the parse done in slices so a large
* body can't hold the event loop. Reading, limits, decompression and `verify`
* are the framework's; the result and the errors match `express.json`.
*/
export const createJsonBodyParser = ({
limit,
verify,
}: JsonBodyOptions): RequestHandler => {
const read = express.raw({
limit,
verify,
type: (req) => isUtf8Json(req as Request),
});
return (req, res, next) => {
read(req, res, async (err?: unknown) => {
// Not a Buffer: the reader skipped this request.
if (err || !Buffer.isBuffer(req.body)) {
next(err);
return;
}
let body: Buffer = req.body;
req.body = undefined;
// The framework's decoder drops a byte order mark.
if (body[0] === 0xef && body[1] === 0xbb && body[2] === 0xbf) {
body = body.subarray(3);
}
if (body.length === 0) {
req.body = {};
next();
return;
}
let parsed: unknown;
try {
parsed = await parseInTurn(body);
} catch (e) {
next(parseFailed((e as Error).message));
return;
}
if (typeof parsed !== 'object' || parsed === null) {
next(parseFailed('JSON body must be an object or an array'));
return;
}
req.body = parsed;
next();
});
};
};
@@ -0,0 +1,184 @@
/*
* Copyright (C) 2024-present Puter Technologies Inc.
*
* This file is part of Puter.
*
* Puter is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import { request, type Server } from 'node:http';
import type { AddressInfo } from 'node:net';
import { setImmediate as nextTurn } from 'node:timers/promises';
import express, {
type ErrorRequestHandler,
type RequestHandler,
} from 'express';
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
import { createJsonBodyParser } from './jsonBody';
import {
createLargeJsonBodyParser,
DEFAULT_JSON_LIMIT_BYTES,
} from './largeJsonBody';
const MiB = 1024 * 1024;
const TOKEN = 'valid-token';
const PAD = 'x'.repeat(DEFAULT_JSON_LIMIT_BYTES);
/** Stands in for the auth probe: one token is valid, wherever it is sent. */
const authProbe: RequestHandler = (req, _res, next) => {
const token =
(req.body as { auth_token?: string } | undefined)?.auth_token ??
req.headers.authorization;
if (!req.actor && token === TOKEN) {
req.actor = { user: { uuid: 'u1' } } as typeof req.actor;
}
next();
};
describe('a JSON body over the default limit', () => {
let server: Server;
beforeAll(async () => {
const app = express();
app.post(
'/call',
createLargeJsonBodyParser({
authProbe,
limitBytes: 128 * MiB,
budgetBytes: 256 * MiB,
perUserBytes: 128 * MiB,
}),
);
app.use(createJsonBodyParser({ limit: DEFAULT_JSON_LIMIT_BYTES }));
app.use(authProbe);
app.post('/call', (req, res) => {
const body = req.body as { auth_token?: string; pad: string };
res.json({
user: req.actor?.user.uuid ?? null,
token: body.auth_token ?? null,
padLength: body.pad.length,
});
});
const onError: ErrorRequestHandler = (err, _req, res, _next) => {
res.status(err.statusCode ?? 500).json({});
};
app.use(onError);
await new Promise<void>((resolve) => {
server = app.listen(0, '127.0.0.1', resolve);
});
});
afterAll(() => {
server?.close();
});
/** Sends `chunks` one write at a time, so the server sees them apart. */
const post = (chunks: string[], headers: Record<string, string> = {}) =>
new Promise<{ status: number; answer: Record<string, unknown> }>(
(resolve, reject) => {
const { port } = server.address() as AddressInfo;
const req = request(
{
host: '127.0.0.1',
port,
path: '/call',
method: 'POST',
headers: {
'Content-Type': 'text/plain;actually=json',
'Content-Length': chunks.reduce(
(total, chunk) =>
total + Buffer.byteLength(chunk),
0,
),
...headers,
},
},
(res) => {
const parts: Buffer[] = [];
res.on('data', (part: Buffer) => parts.push(part));
res.on('end', () =>
resolve({
status: res.statusCode!,
answer: JSON.parse(
Buffer.concat(parts).toString(),
),
}),
);
},
);
req.on('error', reject);
void (async () => {
for (const chunk of chunks) {
req.write(chunk);
await nextTurn();
}
req.end();
})();
},
);
it('is accepted when it opens with a valid auth_token', async () => {
const { status, answer } = await post([
`{"auth_token":"${TOKEN}","pad":"${PAD}"}`,
]);
expect(status).toBe(200);
expect(answer).toEqual({
user: 'u1',
token: TOKEN,
padLength: PAD.length,
});
}, 60_000);
it('is accepted when the token arrives in pieces, with spacing', async () => {
const opening = ` {\n "auth_token" : "${TOKEN}" ,`;
const { status, answer } = await post([...opening, `"pad":"${PAD}"}`]);
expect(status).toBe(200);
expect(answer.user).toBe('u1');
}, 60_000);
it('is accepted with a header credential, as before', async () => {
const { status, answer } = await post([`{"pad":"${PAD}"}`], {
Authorization: TOKEN,
});
expect(status).toBe(200);
expect(answer).toEqual({
user: 'u1',
token: null,
padLength: PAD.length,
});
}, 60_000);
it.each([
[
'its token comes after other fields',
`{"pad":"${PAD}","auth_token":"${TOKEN}"}`,
],
['its token is not valid', `{"auth_token":"expired","pad":"${PAD}"}`],
['it has no token', `{"pad":"${PAD}"}`],
[
'a later field replaces the token it opens with',
`{"auth_token":"${TOKEN}","pad":"${PAD}","auth_token":"other"}`,
],
[
'the token it opens with is nested',
`{"args":{"auth_token":"${TOKEN}"},"pad":"${PAD}"}`,
],
])(
'is refused with 413 when %s',
async (_name, body) => {
expect((await post([body])).status).toBe(413);
},
60_000,
);
});
@@ -18,6 +18,7 @@
*/
import { EventEmitter } from 'node:events';
import { Readable } from 'node:stream';
import type { NextFunction, Request, RequestHandler, Response } from 'express';
import { describe, expect, it, vi } from 'vitest';
import { isHttpError } from '../HttpError';
@@ -35,7 +36,7 @@ const makeReq = (
user: string | null = 'u1',
body?: unknown,
) =>
({
Object.assign(Readable.from([]), {
complete: true,
body,
headers: {
+115 -65
View File
@@ -17,13 +17,54 @@
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import express, { type Request, type RequestHandler } from 'express';
import type { Request, RequestHandler, Response } from 'express';
import { actorUid } from '../../actor';
import { HttpError } from '../HttpError';
import { createJsonBodyParser } from './jsonBody';
/** The global JSON parser's limit, which applies before auth. */
export const DEFAULT_JSON_LIMIT_BYTES = 50 * 1024 * 1024;
/** How much of a body is read to find a token it opens with. */
const LEADING_TOKEN_BYTES = 8 * 1024;
const LEADING_TOKEN =
/^[ \t\n\r]*\{[ \t\n\r]*"auth_token"[ \t\n\r]*:[ \t\n\r]*"([^"\\]+)"/;
/**
* The first `bytes` of the body, put back for the parser to read. Empty when
* the body ends or fails before that many arrive.
*/
const peekBody = (req: Request, bytes: number): Promise<Buffer> =>
new Promise((resolve) => {
const settle = (head: Buffer | null) => {
req.off('readable', onReadable);
req.off('end', onGone);
req.off('close', onGone);
req.off('error', onGone);
if (head) req.unshift(head);
resolve(head ?? Buffer.alloc(0));
};
const onReadable = () => {
// Null until `bytes` are buffered.
const head = req.read(bytes) as Buffer | null;
if (head) settle(head);
};
const onGone = () => settle(null);
req.on('readable', onReadable);
req.on('end', onGone);
req.on('close', onGone);
req.on('error', onGone);
});
/**
* The `auth_token` a JSON body opens with, which puter.js sends first so it can
* be read ahead of the body.
*/
const leadingBodyToken = async (req: Request): Promise<string | undefined> => {
const head = await peekBody(req, LEADING_TOKEN_BYTES);
return LEADING_TOKEN.exec(head.toString('latin1'))?.[1];
};
interface LargeJsonBodyOptions {
/** The global auth probe; it skips requests that already carry an actor. */
authProbe: RequestHandler;
@@ -38,9 +79,9 @@ interface LargeJsonBodyOptions {
/**
* Parses JSON bodies over the default limit, up to `limitBytes`, once the
* caller's header or cookie credential resolves. Unauthenticated requests and
* requests without a Content-Length fall through to the global parser and its
* limit.
* caller's credential resolves: a header, a cookie, or an `auth_token` the body
* opens with. Unauthenticated requests and requests without a Content-Length
* fall through to the global parser and its limit.
*
* The parsed body lives as long as the request, so a body's bytes count against
* both budgets until its response closes. Over the user's budget gets a 429,
@@ -53,82 +94,91 @@ export const createLargeJsonBodyParser = ({
perUserBytes,
accepts,
}: LargeJsonBodyOptions): RequestHandler => {
const json = express.json({ limit: limitBytes });
const textAsJson = express.json({
limit: limitBytes,
type: (req) =>
req.headers['content-type'] === 'text/plain;actually=json',
});
const json = createJsonBodyParser({ limit: limitBytes });
let inFlightBytes = 0;
const inFlightByUser = new Map<string, number>();
return (req, res, next) => {
const probe = (req: Request, res: Response) =>
new Promise<void>((resolve) => {
void authProbe(req, res, () => resolve());
});
return async (req, res, next) => {
const declared = Number(req.headers['content-length']);
if (!(declared > DEFAULT_JSON_LIMIT_BYTES && declared <= limitBytes)) {
next();
return;
}
void authProbe(req, res, () => {
// `res.closed`: the client left during the probe, so `close` has
// already fired and would never release a charge.
if (!req.actor || res.closed) {
next();
await probe(req, res);
let bodyToken: string | undefined;
if (!req.actor && !res.closed) {
bodyToken = await leadingBodyToken(req);
if (bodyToken) {
// Where the probe looks for a body token.
req.body = { auth_token: bodyToken };
await probe(req, res);
req.body = undefined;
}
}
// `res.closed`: the client left during the probe, so `close` has
// already fired and would never release a charge.
if (!req.actor || res.closed) {
next();
return;
}
const user = req.actor.user.uuid ?? actorUid(req.actor);
const userBytes = inFlightByUser.get(user) ?? 0;
if (userBytes + declared > perUserBytes) {
res.setHeader('Retry-After', '5');
next(
new HttpError(
429,
'Too many large requests in progress for this account',
{ legacyCode: 'too_many_requests' },
),
);
return;
}
if (inFlightBytes + declared > budgetBytes) {
res.setHeader('Retry-After', '5');
next(
new HttpError(503, 'Too many large requests in progress', {
code: 'large_body_capacity',
// Load shedding, not a fault: record it, don't page.
alarmSeverity: 'info',
}),
);
return;
}
inFlightBytes += declared;
inFlightByUser.set(user, userBytes + declared);
res.once('close', () => {
inFlightBytes -= declared;
const left = (inFlightByUser.get(user) ?? 0) - declared;
if (left > 0) inFlightByUser.set(user, left);
else inFlightByUser.delete(user);
});
json(req, res, (err?: unknown) => {
if (err) {
next(err);
return;
}
const user = req.actor.user.uuid ?? actorUid(req.actor);
const userBytes = inFlightByUser.get(user) ?? 0;
if (userBytes + declared > perUserBytes) {
res.setHeader('Retry-After', '5');
// The caller was resolved from the token the body opens with,
// so the parsed body has to name the same one.
const tokenMoved =
bodyToken !== undefined &&
(req.body as { auth_token?: unknown } | undefined)
?.auth_token !== bodyToken;
if (tokenMoved || (accepts && !accepts(req))) {
// The same answer the default limit gives.
next(
new HttpError(
429,
'Too many large requests in progress for this account',
{ legacyCode: 'too_many_requests' },
),
);
return;
}
if (inFlightBytes + declared > budgetBytes) {
res.setHeader('Retry-After', '5');
next(
new HttpError(503, 'Too many large requests in progress', {
code: 'large_body_capacity',
// Load shedding, not a fault: record it, don't page.
alarmSeverity: 'info',
new HttpError(413, 'request entity too large', {
legacyCode: 'client_bad_request',
}),
);
return;
}
inFlightBytes += declared;
inFlightByUser.set(user, userBytes + declared);
res.once('close', () => {
inFlightBytes -= declared;
const left = (inFlightByUser.get(user) ?? 0) - declared;
if (left > 0) inFlightByUser.set(user, left);
else inFlightByUser.delete(user);
});
json(req, res, (err?: unknown) => {
if (err) {
next(err);
return;
}
textAsJson(req, res, (err?: unknown) => {
if (err) {
next(err);
return;
}
if (accepts && !accepts(req)) {
// The same answer the default limit gives.
next(
new HttpError(413, 'request entity too large', {
legacyCode: 'client_bad_request',
}),
);
return;
}
next();
});
});
next();
});
};
};
@@ -355,6 +355,17 @@ describe('ChatCompletionDriver.complete auth and model resolution', () => {
).rejects.toMatchObject({ statusCode: 400 });
});
it('rejects a model that is not a string with 400', async () => {
await expect(
withTestActor(() =>
driver.complete({
messages: [{ role: 'user', content: 'hi' }],
model: { id: 'gpt' },
} as unknown as ICompleteArguments),
),
).rejects.toMatchObject({ statusCode: 400 });
});
it('routes by alias when a provider exposes one (puterId is auto-aliased on the bucket)', async () => {
// Inject a model that carries a `puterId` so we can verify the
// alias bucket resolves back to the canonical id. Spy on
@@ -79,6 +79,7 @@ import type {
} from './types.js';
import { normalize_tools_object } from './utils/FunctionCalling.js';
import {
requestedServiceSpeed,
selectServiceSpeed,
lowerServiceSpeed,
isServiceSpeedUnavailable,
@@ -909,18 +910,16 @@ export class ChatCompletionDriver extends PuterDriver {
attemptProvider: IChatProvider,
baseModel: IChatModel,
) => {
let requestedSpeed = requestedServiceSpeed(
args,
baseModel.provider,
);
const offers =
args.serviceSpeed !== undefined &&
args.serviceSpeed !== 'standard'
requestedSpeed !== undefined && requestedSpeed !== 'standard'
? ((await attemptProvider.serviceSpeedModels?.(
baseModel,
)) ?? {})
: {};
let requestedSpeed =
args.serviceSpeed ??
(baseModel.provider === 'claude' && args.speed === 'fast'
? 'fast'
: undefined);
for (;;) {
const selection = selectServiceSpeed(
baseModel,
@@ -2130,7 +2129,9 @@ export class ChatCompletionDriver extends PuterDriver {
}
#resolveModel(modelId: string, provider?: string): IChatModel | null {
const models = this.#modelIdMap[normalizeModelKey(modelId ?? '')];
// `model` comes straight from the caller and may not be a string.
if (typeof modelId !== 'string') return null;
const models = this.#modelIdMap[normalizeModelKey(modelId)];
if (!models || models.length === 0) return null;
// An explicitly requested provider is honoured even if its route is
// marked — the caller asked for that one, not for the cheapest hop.
@@ -44,7 +44,9 @@ import {
type MockInstance,
} from 'vitest';
import { SYSTEM_ACTOR } from '../../../../core/actor.js';
import { SYSTEM_ACTOR, type Actor } from '../../../../core/actor.js';
import { v4 as uuidv4 } from 'uuid';
import { ChatCompletionDriver } from '../../ChatCompletionDriver.js';
import type { MeteringService } from '../../../../services/metering/MeteringService.js';
import { PuterServer } from '../../../../server.js';
import { setupTestServer } from '../../../../testUtil.js';
@@ -1580,3 +1582,117 @@ describe('OpenAiResponsesChatProvider.complete error mapping', () => {
expect(recordSpy).not.toHaveBeenCalled();
});
});
describe('ChatCompletionDriver OpenAI billing', () => {
const makeBillingUser = async () => {
const user = await server.stores.user.create({
username: `billing-${uuidv4().slice(0, 8)}`,
uuid: uuidv4(),
password: null,
email: null,
free_storage: 1000000,
requires_email_confirmation: false,
});
return { user: { ...user, email_confirmed: true } } as Actor;
};
const makeBillingDriver = async () => {
const driver = new ChatCompletionDriver(
{
providers: {
ollama: { enabled: false },
'openai-completion': { apiKey: 'test-key' },
},
} as never,
server.clients,
server.stores,
server.services,
);
await driver.onServerStart();
return driver;
};
it('meters an empty Responses completion before returning its error', async () => {
const actor = await makeBillingUser();
const driver = await makeBillingDriver();
const before = await server.services.metering.getRemainingUsage(actor);
responsesCreateMock.mockResolvedValueOnce({
status: 'incomplete',
incomplete_details: { reason: 'max_output_tokens' },
output: [],
output_text: '',
usage: {
input_tokens: 1200,
output_tokens: 2000,
output_tokens_details: { reasoning_tokens: 2000 },
},
});
await expect(
withTestActor(
() =>
driver.complete({
model: 'gpt-5.4-mini',
provider: 'openai-responses',
messages: [{ role: 'user', content: 'hello' }],
max_tokens: 1,
fallback: false,
}),
actor,
),
).rejects.toMatchObject({ statusCode: 400 });
expect(responsesCreateMock).toHaveBeenCalledTimes(1);
expect(recordSpy).toHaveBeenCalledTimes(1);
expect(recordSpy.mock.calls[0][0]).toMatchObject({
prompt_tokens: 1200,
completion_tokens: 2000,
});
await Promise.all(recordSpy.mock.results.map((result) => result.value));
expect(
await server.services.metering.getRemainingUsage(actor),
).toBeLessThan(before);
});
it('prices a raw priority tier with the same rate card as fast service', async () => {
const actor = await makeBillingUser();
const driver = await makeBillingDriver();
const charges: number[] = [];
for (const extra of [
{},
{ service_tier: 'priority' },
{ serviceSpeed: 'fast' },
]) {
responsesCreateMock.mockResolvedValueOnce({
output: [],
output_text: 'hi',
service_tier: Object.keys(extra).length
? 'priority'
: 'default',
usage: { input_tokens: 100, output_tokens: 100 },
});
const before =
await server.services.metering.getRemainingUsage(actor);
await withTestActor(
() =>
driver.complete({
model: 'gpt-6.1-terra',
provider: 'openai-responses',
messages: [{ role: 'user', content: 'hello' }],
max_tokens: 100,
fallback: false,
...extra,
} as never),
actor,
);
await Promise.all(
recordSpy.mock.results.map((result) => result.value),
);
charges.push(
before -
(await server.services.metering.getRemainingUsage(actor)),
);
}
expect(responsesCreateMock.mock.calls[1][0].service_tier).toBe(
'priority',
);
expect(charges[0]).toBeGreaterThan(0);
expect(charges[1]).toBe(charges[2]);
expect(charges[2]).toBe(charges[0] * 2);
});
});
@@ -1122,16 +1122,6 @@ export const handle_completion_output_responses_api = async ({
// Inline-compaction artifact, if the upstream compacted this turn.
const compactionItem = output.find((item) => item?.type === 'compaction');
const is_empty = completion.output_text.trim() === '';
if (is_empty && responseToolCalls.length < 1 && !compactionItem) {
// GPT refuses to generate an empty response if you ask it to,
// so this will probably only happen on an error condition.
// A compaction-only output is legitimate, so don't reject it.
throw new HttpError(400, 'an empty response was generated', {
legacyCode: 'bad_response',
});
}
// Reasoning models return `reasoning` output items; their human-readable
// text only exists when the caller requested summaries via
// `reasoning: { summary: ... }` (raw chain-of-thought is never returned).
@@ -1234,6 +1224,14 @@ export const handle_completion_output_responses_api = async ({
if (usageDetails) ret.usageDetails = usageDetails;
}
// Empty output can still include paid reasoning and input tokens.
const isEmpty = completion.output_text.trim() === '';
if (isEmpty && responseToolCalls.length < 1 && !compactionItem) {
throw new HttpError(400, 'an empty response was generated', {
legacyCode: 'bad_response',
});
}
const mod_text = completion.output_text;
if (moderate && mod_text !== null) {
await applyModeration(moderate, mod_text);
@@ -26,6 +26,7 @@ import {
} from './OpenAIUtil.js';
import type { IChatModel, ServiceSpeed } from '../types.js';
import {
requestedServiceSpeed,
selectServiceSpeed,
servedServiceSpeed,
serviceSpeedBillingModel,
@@ -83,6 +84,31 @@ describe('service speed selection', () => {
expect(selected.model).toBe(entry);
expect(selected.args).toBe(args);
});
it.each([
[{ service_tier: 'priority' }, 'openai-responses', 'fast'],
[{ service_tier: 'ultrafast' }, 'openai-responses', 'ultrafast'],
[{ service_tier: 'auto' }, 'mistral', 'fast'],
[{ speed: 'fast' }, 'claude', 'fast'],
[{ service_tier: 'auto' }, 'openai-responses', undefined],
[{ service_tier: 'flex' }, 'openai-responses', undefined],
[{ speed: 'fast' }, 'openai-responses', undefined],
[{ serviceSpeed: 'standard', service_tier: 'priority' }, 'openai-responses', 'standard'],
] as const)('reads %j on %s as speed %s', (args, provider, speed) => {
expect(requestedServiceSpeed(args, provider)).toBe(speed);
});
it('prices a native priority tier like fast service', () => {
const entry = model('openai-responses', 'gpt-6.1-sol');
const args = { ...request(), service_tier: 'priority' as const };
const selected = selectServiceSpeed(
entry,
{ ...args, serviceSpeed: requestedServiceSpeed(args, entry.provider) },
noVariant,
);
const explicit = selectServiceSpeed(entry, request('fast'), noVariant);
expect(selected.speed).toBe('fast');
expect(selected.model).toEqual(explicit.model);
expect(selected.args.service_tier).toBe('priority');
});
it.each([
'deepseek',
'zai',
@@ -248,6 +274,33 @@ describe('served speed billing', () => {
expect(recorded).toEqual([result.costs]);
},
);
it.each([
['fast', 2],
['ultrafast', 6],
] as const)(
'bills a served %s tier at its catalog rate without a selection snapshot',
(speed, multiplier) => {
const entry = model('openai-responses', 'gpt-6.1-sol');
entry.pricingOverrides = [
{
minPromptTokens: 100,
costs: { prompt_tokens: 400, completion_tokens: 1500 },
},
];
const billed = serviceSpeedBillingModel(entry, speed);
expect(billed.costs.prompt_tokens).toBe(200 * multiplier);
expect(billed.pricingOverrides?.[0]?.costs.prompt_tokens).toBe(
400 * multiplier,
);
expect(serviceSpeedBillingModel(entry, 'standard')).toBe(entry);
},
);
it('bills a served premium tier as standard when the catalog has no rate for it', () => {
const entry = model('groq', 'some-model');
expect(serviceSpeedBillingModel(entry, 'fast').costs).toEqual(
entry.costs,
);
});
it('restores standard scheduled and long-context rates after a downgrade', () => {
const entry = model('openai-responses', 'gpt-6.1-sol');
entry.pricingOverrides = [
@@ -59,6 +59,26 @@ export interface ServiceSpeedSelection {
speed: ServiceSpeed;
}
/**
* The speed a request asks for. Native premium tier parameters count as the
* matching `serviceSpeed`, so they are priced like it; `serviceSpeed` wins.
*/
export const requestedServiceSpeed = (
args: Pick<ICompleteArguments, 'serviceSpeed' | 'service_tier' | 'speed'>,
provider: string | undefined,
): ServiceSpeed | undefined => {
if (args.serviceSpeed !== undefined) return args.serviceSpeed;
if (args.service_tier === 'ultrafast') return 'ultrafast';
if (
args.service_tier === 'priority' ||
(provider === 'claude' && args.speed === 'fast') ||
// Mistral's `auto` tier is its priority tier.
(provider === 'mistral' && args.service_tier === 'auto')
)
return 'fast';
return undefined;
};
/** Select only an equivalent model from the same provider's loaded catalog. */
export const selectServiceSpeed = (
model: IChatModel,
@@ -201,16 +221,27 @@ export const servedServiceSpeed = (
: 'standard';
};
/**
* The model priced at the speed the provider served. Without a selection
* snapshot the catalog's rates for that speed apply, so a premium tier reached
* some other way is never billed as standard.
*/
export const serviceSpeedBillingModel = (
model: IChatModel,
speed: ServiceSpeed,
): IChatModel => {
const pricing = model.serviceSpeedPricing;
if (!pricing || pricing.speed === speed) return model;
const pricing = model.serviceSpeedPricing ?? {
speed: 'standard',
standardCosts: model.costs,
standardOverrides: model.pricingOverrides,
fastCosts: serviceSpeedCosts(model, 'fast'),
ultrafastCosts: serviceSpeedCosts(model, 'ultrafast'),
};
if (pricing.speed === speed) return model;
const costs =
speed === 'fast'
? (pricing.fastCosts ?? pricing.standardCosts)
: pricing.standardCosts;
(speed === 'ultrafast' ? pricing.ultrafastCosts : undefined) ??
(speed !== 'standard' ? pricing.fastCosts : undefined) ??
pricing.standardCosts;
return {
...model,
costs,
@@ -190,6 +190,39 @@ describe('VoiceChangerDriver.convert argument validation', () => {
withActor(actor, () => driver.convert({ audio: undefined })),
).rejects.toMatchObject({ statusCode: 400 });
});
it.each([
['an unpriced', 'eleven_multilingual_sts_v1'],
['a malformed', 'eleven_english_sts_v2&x=1'],
])(
'rejects %s model before loading audio or calling ElevenLabs',
async (_label, model) => {
const { actor } = await makeUser();
await expect(
withActor(actor, () =>
driver.convert({
audio: 'https://audio.example/sample.wav',
model,
}),
),
).rejects.toMatchObject({
statusCode: 400,
legacyCode: 'field_invalid',
fields: {
key: 'model',
expected: [
'eleven_multilingual_sts_v2',
'eleven_english_sts_v2',
],
got: model,
},
});
expect(webFetchMock).not.toHaveBeenCalled();
expect(fetchSpy).not.toHaveBeenCalled();
expect(admitSpy).not.toHaveBeenCalled();
expect(incrementUsageSpy).not.toHaveBeenCalled();
},
);
});
// ── Credit gate ─────────────────────────────────────────────────────
@@ -51,6 +51,10 @@ const MAX_AUDIO_FILE_SIZE = 25 * 1024 * 1024;
// Covers the upload as well as the conversion.
const CONVERT_TIMEOUT_MS = 10 * 60 * 1000;
const SUPPORTED_MODELS = Object.keys(VOICE_CHANGER_COSTS).map(
(key) => key.split(':')[1]!,
);
const VOICE_CHANGER_CATALOG: ProviderCatalog = {
label: 'Speech-to-speech',
ids: ['elevenlabs'],
@@ -165,14 +169,6 @@ export class VoiceChangerDriver extends PuterDriver {
});
}
const loaded = await loadFileInput(
this.stores,
this.services.fs,
actor,
args.audio,
{ maxBytes: MAX_AUDIO_FILE_SIZE, acceptWebInput: true },
);
const modelId =
args.model_id || args.model || elevenlabs.defaultModelId;
const voiceId =
@@ -184,21 +180,41 @@ export class VoiceChangerDriver extends PuterDriver {
throw new HttpError(400, '`voice` is required', {
legacyCode: 'bad_request',
});
// `voiceId` lands in the request URL path; `modelId` lands in a
// multipart field. Both are forwarded to ElevenLabs with our
// long-lived API key, so anything other than a strict alphanumeric
// shape lets a caller steer the request at a different endpoint or
// inject parameters. ElevenLabs voice/model IDs are always
// `[A-Za-z0-9_-]+` in practice.
const ID_REGEX = /^[A-Za-z0-9_-]+$/;
if (!ID_REGEX.test(voiceId))
// `voiceId` lands in the request URL path, which carries our API key,
// so anything outside ElevenLabs' `[A-Za-z0-9_-]+` id shape could
// steer the request at a different endpoint.
if (!/^[A-Za-z0-9_-]+$/.test(voiceId))
throw new HttpError(400, '`voice` must be alphanumeric', {
legacyCode: 'bad_request',
});
if (!ID_REGEX.test(modelId))
throw new HttpError(400, '`model` must be alphanumeric', {
legacyCode: 'bad_request',
});
// Gate on the cost table: an id we can't price is one we can't bill
// for, and ElevenLabs bills us for it either way. This also keeps
// anything but a known id out of the multipart `model_id` field.
const usageKey = `elevenlabs:${modelId}:second`;
if (!Object.hasOwn(VOICE_CHANGER_COSTS, usageKey)) {
throw new HttpError(
400,
`Invalid model: ${modelId}. Expected: ${SUPPORTED_MODELS.join(', ')}`,
{
legacyCode: 'field_invalid',
fields: {
key: 'model',
expected: SUPPORTED_MODELS,
got: modelId,
},
},
);
}
const ucentsPerSecond = VOICE_CHANGER_COSTS[usageKey]!;
const loaded = await loadFileInput(
this.stores,
this.services.fs,
actor,
args.audio,
{ maxBytes: MAX_AUDIO_FILE_SIZE, acceptWebInput: true },
);
// The hold estimates seconds from the input at 128 kbps: compact audio
// is under-held rather than refused. Usage is metered from the length
@@ -207,8 +223,6 @@ export class VoiceChangerDriver extends PuterDriver {
1,
Math.ceil(loaded.buffer.byteLength / 16000),
);
const usageKey = `elevenlabs:${modelId}:second`;
const ucentsPerSecond = VOICE_CHANGER_COSTS[usageKey] ?? 0;
const estimatedCost = ucentsPerSecond * estimatedSeconds;
const formData = new FormData();
@@ -37,7 +37,7 @@ import {
postGeminiJson,
geminiTokenCount as tokenCount,
} from '../../../util/geminiRest.js';
import { decodeStrictBase64 } from '../../../../util/mediaSniff.js';
import { decodeStrictBase64InSlices } from '../../../../util/mediaSniff.js';
import { isUpstreamTimeoutError } from '../../../util/upstreamErrors.js';
import { SAMPLE_AUDIO_URL } from '../../../util/testMode.js';
import type {
@@ -456,7 +456,8 @@ export class GeminiTTSProvider implements ITTSProvider {
},
);
}
const { body, contentType } = this.#decodeAudio(audio);
const { body, contentType } =
await this.#decodeAudio(audio);
outputTokens = usageTokens(
usage?.output_tokens_by_modality,
@@ -474,7 +475,7 @@ export class GeminiTTSProvider implements ITTSProvider {
dataType: 'stream',
content_type: contentType,
chunked: true,
stream: Readable.from(body),
stream: Readable.from(body, { objectMode: false }),
};
} finally {
// Every outcome pays once for the counts it reports.
@@ -519,13 +520,15 @@ export class GeminiTTSProvider implements ITTSProvider {
}
/** WAV passes through byte for byte; raw PCM is wrapped in a WAV header. */
#decodeAudio(audio: InteractionContent): {
body: Buffer;
async #decodeAudio(audio: InteractionContent): Promise<{
body: Buffer[];
contentType: string;
} {
}> {
const { data, mime_type: mimeType } = audio;
const bytes =
typeof data === 'string' ? decodeStrictBase64(data) : null;
typeof data === 'string'
? await decodeStrictBase64InSlices(data)
: null;
if (!bytes || typeof mimeType !== 'string') {
throw upstreamFailure('Gemini TTS returned invalid audio data');
}
@@ -541,7 +544,7 @@ export class GeminiTTSProvider implements ITTSProvider {
) {
throw upstreamFailure('Gemini TTS returned invalid audio data');
}
return { body: bytes, contentType: 'audio/wav' };
return { body: [bytes], contentType: 'audio/wav' };
}
if (PCM_MIME_TYPES.has(essence) && bytes.length > 0) {
const rate = Number(
@@ -551,8 +554,9 @@ export class GeminiTTSProvider implements ITTSProvider {
Number.isSafeInteger(rate) && rate > 0
? rate
: DEFAULT_PCM_SAMPLE_RATE;
// Sent ahead of the samples, which are never copied behind it.
return {
body: this.#wrapPcmInWav(bytes, sampleRate, 1, 16),
body: [this.#wavHeader(bytes.length, sampleRate, 1, 16), bytes],
contentType: 'audio/wav',
};
}
@@ -560,17 +564,15 @@ export class GeminiTTSProvider implements ITTSProvider {
}
/** Wrap raw PCM samples in a WAV container so browsers can play it. */
#wrapPcmInWav(
pcm: Buffer,
#wavHeader(
dataSize: number,
sampleRate: number,
channels: number,
bitsPerSample: number,
): Buffer {
const byteRate = (sampleRate * channels * bitsPerSample) / 8;
const blockAlign = (channels * bitsPerSample) / 8;
const dataSize = pcm.length;
const headerSize = 44;
const buffer = Buffer.alloc(headerSize + dataSize);
const buffer = Buffer.alloc(44);
// RIFF header
buffer.write('RIFF', 0);
@@ -590,7 +592,6 @@ export class GeminiTTSProvider implements ITTSProvider {
// data sub-chunk
buffer.write('data', 36);
buffer.writeUInt32LE(dataSize, 40);
pcm.copy(buffer, headerSize);
return buffer;
}
@@ -25,7 +25,7 @@ import { insufficientCreditsError } from '../../../../services/metering/enforcem
import type { UsageInput } from '../../../../services/metering/types.js';
import { normalizeRawBase64ImageString } from '../../../../util/appIcon.js';
import {
decodeStrictBase64,
decodeStrictBase64InSlices,
sniffImageMime,
sniffVideoMime,
} from '../../../../util/mediaSniff.js';
@@ -405,7 +405,7 @@ export class GeminiVideoProvider extends VideoProvider {
'Gemini video generation did not complete the request',
);
}
const video = this.#readVideo(videoBlock);
const video = await this.#readVideo(videoBlock);
if (!billed) {
throw geminiUpstreamFailure(
'Gemini video generation returned unusable usage',
@@ -722,7 +722,7 @@ export class GeminiVideoProvider extends VideoProvider {
}
/** The base64 MP4 held by the video block. */
#readVideo(video: InteractionContent | undefined): string {
async #readVideo(video: InteractionContent | undefined): Promise<string> {
if (!video) {
throw new HttpError(400, 'Gemini did not return a video', {
legacyCode: 'upstream_bad_request',
@@ -731,7 +731,7 @@ export class GeminiVideoProvider extends VideoProvider {
}
const bytes =
video.mime_type === 'video/mp4' && typeof video.data === 'string'
? decodeStrictBase64(video.data)
? await decodeStrictBase64InSlices(video.data)
: null;
if (!bytes || sniffVideoMime(bytes) !== 'video/mp4') {
throw geminiUpstreamFailure(
+5 -3
View File
@@ -18,6 +18,7 @@
*/
import { HttpError } from '../../core/http/HttpError.js';
import { parseJsonInSlices } from '../../util/slicedJson.js';
import { readBoundedBody } from './fileInput.js';
import { upstreamFetch } from './upstreamErrors.js';
@@ -39,8 +40,8 @@ export const geminiUpstreamFailure = (message: string): HttpError =>
/**
* POSTs `body` to a Gemini REST `path` and parses the JSON object it answers
* with. `timeoutMs` covers the body read, and a reply over `maxBytes` fails as
* an upstream error unless `tooLarge` supplies another. `T` is the documented reply shape; callers check every
* field before use.
* an upstream error unless `tooLarge` supplies another. `T` is the documented
* reply shape; callers check every field before use.
*/
export async function postGeminiJson<T extends object>(
apiKey: string,
@@ -87,7 +88,8 @@ export async function postGeminiJson<T extends object>(
const raw = await readBoundedBody(response, maxBytes, tooLarge);
let parsed: unknown = null;
try {
parsed = JSON.parse(raw.toString('utf8'));
// Media replies run to tens of megabytes of base64.
parsed = await parseJsonInSlices(raw);
} catch {
// Handled with the non-object case below.
}
+23 -1
View File
@@ -414,7 +414,9 @@ describe('PuterServer host header validation', () => {
'show-save-file-picker',
'show-directory-picker',
'upgrade',
'top-up',
'request-email-confirmation',
'attach-custom-domain',
])('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) =>
@@ -447,7 +449,7 @@ describe('PuterServer host header validation', () => {
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/', '/embed/Request-Email-Confirmation'])(
it.each(['/embed/SIGN-IN', '/embed/Show-Open-File-Picker', '/embed/sign-in/', '/embed/Upgrade', '/embed/upgrade/', '/embed/Top-Up', '/embed/top-up/', '/embed/Request-Email-Confirmation'])(
'lets a first-party page frame only the exact spelling of %s',
async (spelling) => {
const res = await request(spelling, {
@@ -792,6 +794,26 @@ describe('PuterServer request parsing', () => {
}
});
it('parses a chat call above 50 MiB whose body opens with its token', async () => {
const fields = `"interface":"puter-chat-completion","method":"no-such-method","pad":"${'x'.repeat(51 * MiB)}"`;
const asText = { 'content-type': 'text/plain;actually=json' };
const first = await postJson(
'/drivers/call',
`{"auth_token":"${token}",${fields}}`,
asText,
);
expect(first.status).toBe(404);
expect(first.body).toContain('no-such-method');
// A token after other fields can't be read ahead of the body.
const last = await postJson(
'/drivers/call',
`{${fields},"auth_token":"${token}"}`,
asText,
);
expect(last.status).toBe(413);
});
it('keeps the default JSON limit for other drivers', async () => {
const payload = JSON.stringify({
interface: 'puter-kvstore',
+30 -11
View File
@@ -36,6 +36,7 @@ import { createAuthProbe } from './core/http/middleware/authProbe';
import { createRequestContextMiddleware } from './core/http/middleware/requestContext';
import { createFingerprintMiddleware } from './core/http/middleware/fingerprint';
import { createErrorHandler } from './core/http/middleware/errorHandler';
import { createJsonBodyParser } from './core/http/middleware/jsonBody';
import {
createLargeJsonBodyParser,
DEFAULT_JSON_LIMIT_BYTES,
@@ -144,6 +145,8 @@ const LARGE_JSON_ROUTES = [
const LARGE_JSON_LIMIT_BYTES = 128 * 1024 * 1024;
/** Two max-size bodies per process. */
const LARGE_JSON_BUDGET_BYTES = 2 * LARGE_JSON_LIMIT_BYTES;
/** These parse in one go, so they stay small enough for that to be quick. */
const NON_UTF8_JSON_LIMIT_BYTES = 1024 * 1024;
/**
* Through `/drivers/call`, only chat takes a large body; other drivers keep the
@@ -575,26 +578,42 @@ export class PuterServer {
}),
);
}
// A WebDAV body is the file being stored, whatever content type the
// client labels it with, so the controller reads it off the stream.
const exceptDav =
(parser: RequestHandler): RequestHandler =>
(req, res, next) => {
if (activeSubdomain(req) === 'dav') {
next();
return;
}
return parser(req, res, next);
};
this.#app.use(
express.json({
limit: DEFAULT_JSON_LIMIT_BYTES,
verify: captureRawBody,
}),
exceptDav(
createJsonBodyParser({
limit: DEFAULT_JSON_LIMIT_BYTES,
verify: captureRawBody,
}),
),
);
// JSON in another charset, which the parser above leaves alone.
this.#app.use(
express.json({
limit: DEFAULT_JSON_LIMIT_BYTES,
type: (req) =>
req.headers['content-type'] === 'text/plain;actually=json',
verify: captureRawBody,
}),
exceptDav(
express.json({
limit: NON_UTF8_JSON_LIMIT_BYTES,
verify: captureRawBody,
}),
),
);
// Form-encoded bodies (e.g. `/down` from the GUI's iframe-triggered
// download form). Needs to run before the auth probe so
// `req.body.auth_token` is populated for urlencoded POSTs the same
// way it is for JSON POSTs. Small cap — this parser is only here to
// cover the auth_token / anti_csrf field shape, not file uploads.
this.#app.use(express.urlencoded({ extended: true, limit: '100kb' }));
this.#app.use(
exceptDav(express.urlencoded({ extended: true, limit: '100kb' })),
);
// -- Auth probe ----------------------------------------------
if (authProbe) {
@@ -31,24 +31,13 @@ export const RECOMMENDED_APP_NAMES = [
'spreadsheet',
'presentation',
'whiteboard',
'notes',
'pdf-editor',
'contacts',
'calendar',
'meetings',
'teamchat',
'email',
'dev-center',
'cap-table',
'invoices',
'crm',
'signatures',
'projects',
'point-of-sale',
'inventory',
'hiring',
'time-tracking',
'shift-planner',
'equipment',
'chess',
'checkers',
'backgammon',
+1 -1
View File
@@ -2864,7 +2864,7 @@ export class AuthService extends PuterService {
#actorUserFromRow(user: UserRow) {
// Strip the password hash; pass everything else through so callers
// can read metadata, desktop_bg_*, otp_enabled, etc. without
// can read metadata, otp_enabled, etc. without
// re-fetching the user. Mirrors what /whoami exposes off of UserRow.
const { password: _password, ...rest } = user;
return {
+2 -4
View File
@@ -43,7 +43,7 @@ export type TokenType = 'session' | 'gui' | 'app-under-user' | 'access-token';
/**
* Browser session token. `'session'` is the HTTP-only-cookie flavor, `'gui'`
* the same shape served in a response body (e.g. QR login).
* the same shape served in a response body (e.g. the login response).
*/
export interface SessionTokenPayload extends TokenPayloadBase {
type: 'session' | 'gui';
@@ -109,9 +109,7 @@ export interface AccessTokenPayload extends TokenPayloadBase {
}
export type AnyTokenPayload =
| SessionTokenPayload
| AppUnderUserTokenPayload
| AccessTokenPayload;
SessionTokenPayload | AppUnderUserTokenPayload | AccessTokenPayload;
// -- Session row (from `sessions` table) ----------------------------
+16
View File
@@ -647,6 +647,22 @@ describe('FSService overwrite and dedupe resolution', () => {
expect(await readBack(second)).toBe('second');
});
it('leaves one readable file when two overwrites create the same path at once', async () => {
const path = `${user.home}/Documents/raced.txt`;
const written = await Promise.all([
writeFile(user, path, 'short', { overwrite: true }),
writeFile(user, path, 'a much longer body', { overwrite: true }),
]);
// Both started before the row existed, so each uploaded under its own
// key; the row has to end up describing bytes that are really there.
expect(written[0].uuid).toBe(written[1].uuid);
const stored = (await entryAt(user, '/Documents/raced.txt'))!;
const body = await readBack(stored);
expect(['short', 'a much longer body']).toContain(body);
expect(stored.size).toBe(Buffer.byteLength(body));
});
it('dedupes into an unused " (n)" name, skipping names already taken', async () => {
await writeFile(user, `${user.home}/Documents/d.txt`, 'a');
await writeFile(user, `${user.home}/Documents/d (1).txt`, 'a');
+96 -31
View File
@@ -2073,10 +2073,7 @@ export class FSService extends PuterService {
);
});
const fsEntries = await this.stores.fsEntry.batchCreateEntries(
createInputs,
true,
);
const fsEntries = await this.#createUploadedEntries(createInputs);
return preparedBatch.items.map((item, index) => {
const fsEntry = fsEntries[index];
if (!fsEntry) {
@@ -3001,30 +2998,97 @@ export class FSService extends PuterService {
legacyCode: 'conflict',
});
}
await this.#moveObjectOntoKey(
session.objectKey,
liveKey,
{ bucket, region, size },
session.contentType,
);
}
async #moveObjectOntoKey(
fromKey: string,
toKey: string,
at: { bucket: string; region: string; size: number },
contentType?: string | null,
): Promise<void> {
await this.stores.s3Object.copyObjectOfAnySize(
{
sourceBucket: bucket,
sourceKey: session.objectKey,
destinationBucket: bucket,
destinationKey: liveKey,
contentType: session.contentType,
sourceBucket: at.bucket,
sourceKey: fromKey,
destinationBucket: at.bucket,
destinationKey: toKey,
...(contentType ? { contentType } : {}),
metadataDirective: 'REPLACE',
},
region,
size,
at.region,
at.size,
);
try {
await this.stores.s3Object.deleteObject(
bucket,
session.objectKey,
region,
at.bucket,
fromKey,
at.region,
);
} catch (e) {
// The live object is already right; the staged one is only litter.
console.warn('[fs] staged overwrite left behind:', e);
// The destination is already right; the source is only litter.
console.warn('[fs] moved object left behind:', e);
}
}
/**
* Creates the rows for objects already uploaded. A row another writer
* created first keeps its uuid, so those bytes move onto that key.
*/
async #createUploadedEntries(
inputs: FSEntryCreateInput[],
): Promise<FSEntry[]> {
const entries = await this.stores.fsEntry.batchCreateEntries(
inputs,
true,
);
const raced = inputs.flatMap((input, index) => {
const liveKey = entries[index]?.uuid;
return liveKey && liveKey !== input.uuid
? [{ input, index, liveKey }]
: [];
});
if (raced.length === 0) return entries;
await Promise.all(
raced.map(({ input, liveKey }) =>
this.#moveObjectOntoKey(
input.uuid,
liveKey,
{
bucket: this.stores.s3Object.resolveBucket(
input.bucket,
),
region: this.stores.s3Object.resolveRegion(
input.bucketRegion,
),
size: input.size,
},
input.contentType,
),
),
);
const adopted = await this.stores.fsEntry.batchCreateEntries(
raced.map(({ input, liveKey }) => ({ ...input, uuid: liveKey })),
true,
);
raced.forEach(({ index, liveKey }, i) => {
const entry = adopted[i];
if (entry?.uuid !== liveKey) {
throw new HttpError(409, 'Write target changed mid-write', {
legacyCode: 'conflict',
});
}
entries[index] = entry;
});
return entries;
}
async completeUrlWrite(
userId: number,
completeWriteRequest: CompleteWriteRequest,
@@ -3581,10 +3645,10 @@ export class FSService extends PuterService {
: uploadBody.contentHashSha256;
const createInput = this.#toCreateInput(normalizedInput, objectKey);
const fsEntry = await this.stores.fsEntry.createEntry(
createInput,
normalizedInput.createMissingParents,
);
const [fsEntry] = await this.#createUploadedEntries([createInput]);
if (!fsEntry) {
throw new Error('Failed to create entry');
}
this.#emitFsEvent(
existingEntry ? 'fs.write.file' : 'fs.create.file',
@@ -3682,17 +3746,18 @@ export class FSService extends PuterService {
updates.filter(isValid),
);
let next = 0;
return updates.map((update): PromiseSettledResult<FSEntry> =>
isValid(update)
? stored[next++]
: {
status: 'rejected',
reason: new HttpError(
400,
'Invalid file entry identifier for thumbnail update',
{ legacyCode: 'bad_request' },
),
},
return updates.map(
(update): PromiseSettledResult<FSEntry> =>
isValid(update)
? stored[next++]
: {
status: 'rejected',
reason: new HttpError(
400,
'Invalid file entry identifier for thumbnail update',
{ legacyCode: 'bad_request' },
),
},
);
}
@@ -517,8 +517,6 @@ export class PuterHomepageService extends PuterService {
<meta name="theme-color" content="#ffffff">
${bundled ? `<link rel="stylesheet" href="${guiCss}">` : ''}
<link rel="preload" as="image" href="https://puter-assets.b-cdn.net/wallpaper.webp">
<script>
if ( ! window.service_script ) {
window.service_script_api_promise = (() => {
@@ -18,6 +18,7 @@
*/
import { Writable } from 'node:stream';
import v8 from 'node:v8';
import type { Request, Response } from 'express';
import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
import { v4 as uuidv4 } from 'uuid';
@@ -229,6 +230,37 @@ describe('ProfileService', () => {
).toBeNull();
});
// V8 stops optimizing regexps once a process holds enough compiled code,
// as long-running servers do, and an unoptimized one overflows on this.
it('answers a picture of several megabytes with 413', () => {
const picture = `data:image/png;base64,${'A'.repeat(6 * 1024 * 1024)}`;
v8.setFlagsFromString('--no-regexp-optimization');
try {
expect(() => service.validatePatch({ picture })).toThrow(
expect.objectContaining({
statusCode: 413,
code: 'profile_picture_too_large',
}),
);
} finally {
v8.setFlagsFromString('--regexp-optimization');
}
});
it('accepts a picture of the largest size, with or without padding', () => {
const prefix = 'data:image/png;base64,';
const full = `${prefix}${'A'.repeat(PROFILE_PICTURE_MAX_BYTES - prefix.length)}`;
expect(service.validatePatch({ picture: full })).toEqual({
picture: full,
});
expect(service.validatePatch({ picture: `${prefix}QQ` })).toEqual({
picture: `${prefix}QQ`,
});
expect(() => service.validatePatch({ picture: `${full}A` })).toThrow(
expect.objectContaining({ code: 'profile_picture_too_large' }),
);
});
it('keeps what validates from a legacy profile and names the rest', () => {
expect(
service.normalizeLegacyProfile({
@@ -83,6 +83,14 @@ const validateField = (field: ProfileField, value: unknown): string | null => {
);
}
if (field === 'picture') {
// Sized before the pattern runs, which fails outright on megabytes of
// text. Only ASCII passes the pattern, so the length is the byte count.
if (value.length > PROFILE_PICTURE_MAX_BYTES) {
throw new HttpError(413, 'picture is too large', {
code: 'profile_picture_too_large',
fields: { field, maxBytes: PROFILE_PICTURE_MAX_BYTES },
});
}
if (!PICTURE_DATA_URL.test(value)) {
throw invalid(
field,
@@ -90,12 +98,6 @@ const validateField = (field: ProfileField, value: unknown): string | null => {
'profile_picture_invalid',
);
}
if (Buffer.byteLength(value) > PROFILE_PICTURE_MAX_BYTES) {
throw new HttpError(413, 'picture is too large', {
code: 'profile_picture_too_large',
fields: { field, maxBytes: PROFILE_PICTURE_MAX_BYTES },
});
}
return value;
}
const maxLength =
+27 -14
View File
@@ -26,6 +26,7 @@ import {
PuterStore,
} from '../types';
import { HttpError } from '../../core/http/HttpError.js';
import { runWithConcurrencyLimit } from '../../util/concurrency.js';
import { isUniqueViolation } from '../../util/dbError.js';
import {
validateUrl,
@@ -89,6 +90,8 @@ const STATS_CACHE_TTL_SECONDS = 30 * 60;
// `app-` + a UUID. ClickHouse's `app_opens.app_uid` is FixedString(40) and
// fails the whole query on a longer value.
const APP_UID_MAX_BYTES = 40;
// ClickHouse caps the size of one query parameter, and the uid list is one.
const CLICKHOUSE_UIDS_PER_QUERY = 1000;
// Period helpers for detailed/grouped stats. Ported from v1
// AppInformationService — queries go straight to ClickHouse/MySQL on demand
@@ -1727,20 +1730,30 @@ export class AppStore extends PuterStore {
const clickhouse = this.clients.clickhouse;
if (clickhouse) {
const res = await clickhouse.query({
query: `
SELECT app_uid,
uniqExact((user_id, intDiv(ts, ${APP_OPEN_COUNT_PERIOD_SECONDS}))) AS open_count,
count(DISTINCT user_id) AS user_count
FROM app_opens
WHERE app_uid IN {uids:Array(String)}
GROUP BY app_uid
`,
query_params: { uids: uids.map((u) => String(u)) },
format: 'JSONEachRow',
});
const rows = await res.json();
for (const row of rows) {
const chunks = [];
for (let i = 0; i < uids.length; i += CLICKHOUSE_UIDS_PER_QUERY) {
chunks.push(uids.slice(i, i + CLICKHOUSE_UIDS_PER_QUERY));
}
const results = await runWithConcurrencyLimit(
chunks,
4,
async (chunk) => {
const res = await clickhouse.query({
query: `
SELECT app_uid,
uniqExact((user_id, intDiv(ts, ${APP_OPEN_COUNT_PERIOD_SECONDS}))) AS open_count,
count(DISTINCT user_id) AS user_count
FROM app_opens
WHERE app_uid IN {uids:Array(String)}
GROUP BY app_uid
`,
query_params: { uids: chunk.map((u) => String(u)) },
format: 'JSONEachRow',
});
return res.json();
},
);
for (const row of results.flat()) {
out.set(row.app_uid, {
open_count: parseInt(row.open_count, 10) || 0,
user_count: parseInt(row.user_count, 10) || 0,
+31
View File
@@ -200,6 +200,37 @@ describe('AppStore app stats (cache-on-read)', () => {
}
});
it('splits a long uid list across ClickHouse queries', async () => {
const uids = Array.from({ length: 2500 }, () => freshUid());
const queried = [];
server.clients.clickhouse = {
query: async ({ query_params }) => {
queried.push(query_params.uids.length);
return {
json: async () =>
query_params.uids.map((u) => ({
app_uid: u,
open_count: '2',
user_count: '1',
})),
};
},
};
try {
const stats = await appStore.getAppsStats(uids);
expect(queried.sort((a, b) => b - a)).toEqual([1000, 1000, 500]);
expect(stats.size).toBe(2500);
expect(stats.get(uids[2499])).toMatchObject({
open_count: 2,
user_count: 1,
});
} finally {
delete server.clients.clickhouse;
}
});
it('keeps ids longer than an app uid out of the ClickHouse query', async () => {
const uid = freshUid();
const longId = `iap-${'a'.repeat(36)}-extra`;
+40 -8
View File
@@ -444,7 +444,7 @@ describe('FSEntryStore cache invalidation', () => {
store.batchCreateEntries([
{
userId: user.userId,
uuid: uuidv4(),
uuid: file.uuid,
path: file.path,
size: 7,
overwrite: true,
@@ -1185,7 +1185,7 @@ describe('FSEntryStore entry creation', () => {
const [updated] = await store.batchCreateEntries([
{
userId: user.userId,
uuid: uuidv4(),
uuid: original.uuid,
path: `${user.home}/Documents/ow.txt`,
size: 42,
overwrite: true,
@@ -1204,6 +1204,33 @@ describe('FSEntryStore entry creation', () => {
expect(updated?.thumbnail).toBe('data:image/png;base64,AA');
});
it('leaves the row alone when an overwrite brings a different object key', async () => {
const user = await makeUser();
const original = await createFile(
user,
`${user.home}/Documents/otherkey.txt`,
{ size: 1 },
);
// The bytes for this write sit under a key the row doesn't name, so
// repointing bucket or size would describe an object that isn't there.
const returned = await createFile(user, original.path, {
size: 42,
overwrite: true,
bucket: 'elsewhere',
bucketRegion: 'eu-central-1',
});
expect(returned.uuid).toBe(original.uuid);
await expect(
store.getEntryByPath(original.path),
).resolves.toMatchObject({
uuid: original.uuid,
size: 1,
bucket: 'puter-local',
});
});
it('refuses to clobber an existing entry without overwrite, or a directory with it', async () => {
const user = await makeUser();
await createFile(user, `${user.home}/Documents/keep.txt`);
@@ -1227,7 +1254,10 @@ describe('FSEntryStore entry creation', () => {
it('propagates the underlying failure when an overwrite update fails', async () => {
const user = await makeUser();
await createFile(user, `${user.home}/Documents/upfail.txt`);
const existing = await createFile(
user,
`${user.home}/Documents/upfail.txt`,
);
const db = server.clients.db;
const originalWrite = (Object.getPrototypeOf(db) as typeof db).write;
@@ -1243,6 +1273,7 @@ describe('FSEntryStore entry creation', () => {
await expect(
createFile(user, `${user.home}/Documents/upfail.txt`, {
overwrite: true,
uuid: existing.uuid,
}),
).rejects.toThrow('update rejected');
@@ -3801,7 +3832,7 @@ describe('FSEntryStore lost-insert recovery', () => {
spy.mockRestore();
});
it('updates the race winner in place when overwrite was requested', async () => {
it('hands back the race winner untouched when overwrite was requested', async () => {
const user = await makeUser();
const uuid = uuidv4();
const spy = loseInsertRace(uuid, () =>
@@ -3827,13 +3858,14 @@ describe('FSEntryStore lost-insert recovery', () => {
]);
spy.mockRestore();
// The winner's row survived; our payload was written onto it.
// Our object is under `uuid`, not the winner's key, so the winner's
// row is returned as it stands for the caller to move the bytes onto.
expect(entry?.uuid).not.toBe(uuid);
expect(entry?.size).toBe(77);
expect(entry?.thumbnail).toBe('thumb');
expect(entry?.size).not.toBe(77);
expect(entry?.thumbnail).not.toBe('thumb');
await expect(
store.getEntryByPath(`${user.home}/Documents/recovered.txt`),
).resolves.toMatchObject({ size: 77, uuid: entry?.uuid });
).resolves.toMatchObject({ size: entry?.size, uuid: entry?.uuid });
});
});
+13
View File
@@ -1941,6 +1941,11 @@ export class FSEntryStore extends PuterStore {
return entry;
}
/**
* An overwrite whose `uuid` is not the existing row's leaves that row
* untouched and returns it: the caller's object is under another key, so
* the row can't describe it until the caller moves the bytes.
*/
async batchCreateEntries(
entries: FSEntryCreateInput[],
createPaths = true,
@@ -2074,6 +2079,10 @@ export class FSEntryStore extends PuterStore {
{ legacyCode: 'cannot_overwrite_a_directory' },
);
}
if (existingEntry.uuid !== entry.input.uuid) {
updatedResultsByIndex.set(entry.index, existingEntry);
continue;
}
const updatedEntry = {
...existingEntry,
@@ -2398,6 +2407,10 @@ export class FSEntryStore extends PuterStore {
);
continue;
}
if (existing.uuid !== entry.input.uuid) {
updatedResultsByIndex.set(entry.index, existing);
continue;
}
const updatedEntry: FSEntry = {
...existing,
+2 -2
View File
@@ -159,8 +159,8 @@ export interface AppSummaryOptions {
/**
* The summary the desktop launches from directly, without re-reading the app
* (suggested, recommended, recent and taskbar apps), so every launch-relevant
* flag belongs here.
* (suggested, recommended and recent apps), so every launch-relevant flag
* belongs here.
*/
export function toAppSummary(
app: AppRow,
+53 -1
View File
@@ -18,7 +18,10 @@
*/
import { describe, expect, it } from 'vitest';
import { decodeStrictBase64 } from './mediaSniff.ts';
import {
decodeStrictBase64,
decodeStrictBase64InSlices,
} from './mediaSniff.ts';
describe('decodeStrictBase64', () => {
it.each([
@@ -50,3 +53,52 @@ describe('decodeStrictBase64', () => {
}
});
});
describe('decodeStrictBase64InSlices', () => {
// Several slices, with a last one that is partial and padded.
const bytes = Buffer.alloc(5 * 1024 * 1024 + 2);
for (let i = 0; i < bytes.length; i += 4099) bytes[i] = i % 251;
const valid = bytes.toString('base64');
it('decodes a multi-MB payload to the same bytes', async () => {
expect(valid.endsWith('==')).toBe(true);
expect((await decodeStrictBase64InSlices(valid))?.equals(bytes)).toBe(
true,
);
const short = Buffer.from('abcd').toString('base64');
expect(await decodeStrictBase64InSlices(short)).toEqual(
Buffer.from('abcd'),
);
});
it.each([
['empty input', ''],
['unpadded input', valid.slice(0, -2)],
[
'a character outside the alphabet in the first slice',
`*${valid.slice(1)}`,
],
[
'a character outside the alphabet in the last slice',
`${valid.slice(0, -5)}*${valid.slice(-4)}`,
],
[
'the URL-safe alphabet',
`${valid.slice(0, 3_000_000)}-${valid.slice(3_000_001)}`,
],
[
'a non-ASCII character',
`${valid.slice(0, 3_000_000)}ī${valid.slice(3_000_001)}`,
],
[
'padding where a slice ends',
`${valid.slice(0, 1024 * 1024 - 1)}=${valid.slice(1024 * 1024)}`,
],
[
'padding inside a slice',
`${valid.slice(0, 2_000_002)}==${valid.slice(2_000_004)}`,
],
])('rejects %s', async (_label, value) => {
expect(await decodeStrictBase64InSlices(value)).toBeNull();
});
});
+29
View File
@@ -17,6 +17,8 @@
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import { setImmediate as nextTurn } from 'node:timers/promises';
// Identify uploaded media by its bytes. A caller-supplied MIME type or file
// extension is never trusted.
@@ -69,6 +71,33 @@ export function decodeStrictBase64(value: string): Buffer | null {
return bytes.length === (value.length / 4) * 3 - padding ? bytes : null;
}
/** Base64 characters decoded per turn; a multiple of four. */
const BASE64_SLICE_CHARS = 1024 * 1024;
/**
* `decodeStrictBase64` for payloads of many megabytes: decodes a slice per turn
* of the event loop, so the whole string never holds it.
*/
export async function decodeStrictBase64InSlices(
value: string,
): Promise<Buffer | null> {
if (value.length <= BASE64_SLICE_CHARS) return decodeStrictBase64(value);
if (value.length % 4 !== 0) return null;
const padding = value.endsWith('==') ? 2 : value.endsWith('=') ? 1 : 0;
const bytes = Buffer.allocUnsafe((value.length / 4) * 3 - padding);
let written = 0;
for (let at = 0; at < value.length; at += BASE64_SLICE_CHARS) {
const slice = decodeStrictBase64(
value.slice(at, at + BASE64_SLICE_CHARS),
);
// Padding inside the string leaves a slice short, and the total with it.
if (!slice || written + slice.length > bytes.length) return null;
written += slice.copy(bytes, written);
await nextTurn();
}
return written === bytes.length ? bytes : null;
}
function looksLikeSvg(bytes: Buffer): boolean {
let head = bytes.subarray(0, SVG_SNIFF_WINDOW).toString('utf8');
if (head.charCodeAt(0) === 0xfeff) head = head.slice(1);
+374
View File
@@ -0,0 +1,374 @@
/*
* Copyright (C) 2024-present Puter Technologies Inc.
*
* This file is part of Puter.
*
* Puter is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import { afterEach, describe, expect, it, vi } from 'vitest';
import {
MAX_DEPTH,
parseJsonInSlices,
SLICE_BYTES,
STRING_PIECE_BYTES,
} from './slicedJson.js';
type Outcome = { value: unknown } | { error: string };
const native = (body: Buffer): Outcome => {
try {
return { value: JSON.parse(body.toString('utf8')) };
} catch (e) {
return { error: (e as Error).name };
}
};
const sliced = async (body: Buffer): Promise<Outcome> => {
try {
return { value: await parseJsonInSlices(body) };
} catch (e) {
return { error: (e as Error).name };
}
};
/** Key order, own `__proto__` keys and lone surrogates all show in the text. */
const shown = (outcome: Outcome): string =>
'error' in outcome ? outcome.error : JSON.stringify(outcome.value);
const expectSameAsNative = async (body: Buffer | string): Promise<void> => {
const buffer = typeof body === 'string' ? Buffer.from(body) : body;
expect(shown(await sliced(buffer))).toBe(shown(native(buffer)));
};
/** Whitespace that pushes `text` onto the sliced path without changing it. */
const padded = (text: string): string => `${' '.repeat(SLICE_BYTES)}${text}`;
// mulberry32: the cases must be the same on every run.
const seeded = (seed: number) => () => {
seed = (seed + 0x6d2b79f5) | 0;
let t = Math.imul(seed ^ (seed >>> 15), 1 | seed);
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
const STRING_PARTS = [
'a',
'word ',
'"',
'\\',
'\\\\"',
'\n',
'\u0001',
'é',
'日本',
'😀',
'\ud83d',
'\u2028',
'/',
'\\u00e9',
];
const KEYS = ['id', 'name', '__proto__', '7', '3', 'constructor', 'a b', ''];
// No key holds a backslash: with one in a key seen earlier, some V8 versions
// misread a later escaped key, in `JSON.parse` itself.
const KEY_PARTS = STRING_PARTS.filter((part) => !part.includes('\\'));
const SCALARS = [
'0',
'-0',
'1.5e300',
'-12.25',
'1e-7',
'9007199254740993',
'true',
'false',
'null',
];
const GAPS = ['', '', '', ' ', '\n\t', '\r\n '];
/** A random JSON document, written as text so spacing and escapes vary. */
const randomDocument = (
random: () => number,
targetBytes: number,
{ plainKeys = false } = {},
): string => {
const pick = <T>(items: readonly T[]): T =>
items[Math.floor(random() * items.length)]!;
const gap = () => pick(GAPS);
const string = (maxParts: number, from = STRING_PARTS): string => {
let text = '';
const parts = Math.floor(random() * maxParts);
for (let i = 0; i < parts; i++) text += pick(from);
return JSON.stringify(text);
};
let written = 0;
const value = (depth: number): string => {
const roll = random();
let text: string;
if (depth > 0 && roll < 0.25) {
const count = Math.floor(random() * 12);
const items: string[] = [];
for (let i = 0; i < count; i++) items.push(value(depth - 1));
text = `[${gap()}${items.join(`${gap()},${gap()}`)}${gap()}]`;
} else if (depth > 0 && roll < 0.5) {
const count = Math.floor(random() * 12);
const members: string[] = [];
for (let i = 0; i < count; i++) {
const key =
plainKeys || random() < 0.7
? JSON.stringify(pick(KEYS))
: string(6, KEY_PARTS);
members.push(`${key}${gap()}:${gap()}${value(depth - 1)}`);
}
text = `{${gap()}${members.join(`${gap()},${gap()}`)}${gap()}}`;
} else if (roll < 0.75) {
// Now and then one long enough to be read in pieces.
text = string(random() < 0.002 ? 3 * SLICE_BYTES : 20);
} else {
text = pick(SCALARS);
}
written += text.length;
return text;
};
const items: string[] = [];
while (written < targetBytes) items.push(value(6));
return random() < 0.5
? `[${items.join(',')}]`
: `{${items.map((item, i) => `"k${i % 50}":${item}`).join(',')}}`;
};
describe('parseJsonInSlices', () => {
afterEach(() => {
vi.restoreAllMocks();
});
it('parses what JSON.parse parses, the same way', async () => {
const random = seeded(1);
for (let i = 0; i < 60; i++) {
const size = SLICE_BYTES * (1 + Math.floor(random() * 12));
await expectSameAsNative(randomDocument(random, size));
}
}, 60_000);
it('parses the same when every clock read ends the turn', async () => {
let now = 0;
vi.spyOn(performance, 'now').mockImplementation(() => (now += 1000));
const random = seeded(3);
for (let i = 0; i < 30; i++) {
await expectSameAsNative(randomDocument(random, 6 * SLICE_BYTES));
}
// Strings long enough for a turn to end inside them.
await expectSameAsNative(
`["${'ab\\n'.repeat(SLICE_BYTES)}",{"k":"${'\\\\'.repeat(SLICE_BYTES)}"},${'1234567890'.repeat(SLICE_BYTES / 2)}]`,
);
}, 60_000);
it('rejects what JSON.parse rejects', async () => {
const random = seeded(2);
const replacements = Buffer.from('[]{},:"\\ 0a\néx-.e');
for (let i = 0; i < 40; i++) {
// Plain keys, so no edit can leave a backslash in one.
const valid = Buffer.from(
randomDocument(random, 2 * SLICE_BYTES, { plainKeys: true }),
);
for (let edit = 0; edit < 12; edit++) {
const body = Buffer.from(valid);
const at = Math.floor(random() * body.length);
const roll = random();
if (roll < 0.4) {
body[at] =
replacements[
Math.floor(random() * replacements.length)
]!;
await expectSameAsNative(body);
} else if (roll < 0.7) {
await expectSameAsNative(
Buffer.concat([
body.subarray(0, at),
body.subarray(at + 1),
]),
);
} else {
await expectSameAsNative(body.subarray(0, at));
}
}
}
}, 120_000);
it.each([
['an empty body', ''],
['only whitespace', ' \n '],
['two values', '[1] [2]'],
['a trailing comma in an array', '[1,2,]'],
['a trailing comma in an object', '{"a":1,}'],
['a leading comma', '[,1]'],
['a doubled comma', '[1,,2]'],
['a missing colon', '{"a" 1}'],
['a missing value', '{"a":}'],
['a bare key', '{a:1}'],
['a colon in an array', '[1:2]'],
['mismatched brackets', '[1}'],
['an extra close', '[1]]'],
['an unterminated string', '["abc'],
['an unterminated array', '[1,2'],
['a byte order mark', '\ufeff[1]'],
['a comment', '[1/* x */]'],
['a bad literal', '[tru]'],
['a bad number', '[01]'],
['a bad escape', '["\\x"]'],
['a raw control character in a string', '["a\tb"]'],
['a wide space between values', '[1,\u00a02]'],
])('rejects %s', async (_name, text) => {
await expectSameAsNative(text);
// Short input takes the native path, so check the sliced one too.
await expectSameAsNative(padded(text));
await expectSameAsNative(
`[${'1,'.repeat(SLICE_BYTES)}${text},${'2,'.repeat(SLICE_BYTES)}3]`,
);
});
it('reads a string longer than one piece, wherever a piece ends', async () => {
const units = [
'\\u00e9',
'\\n',
'\\\\',
'\\"',
'é',
'日',
'😀',
'\\ud83d\\ude00',
];
for (const unit of units) {
for (let shift = 0; shift < 9; shift++) {
const lead = 'a'.repeat(STRING_PIECE_BYTES - 12 + shift);
const text = `{"text":"${lead}${unit.repeat(8)}${lead}","n":1}`;
await expectSameAsNative(text);
}
}
}, 60_000);
it('reads long runs of escapes and stray UTF-8 bytes', async () => {
const length = STRING_PIECE_BYTES + SLICE_BYTES;
await expectSameAsNative(`["${'\\\\'.repeat(length)}"]`);
await expectSameAsNative(`["${'\\"'.repeat(length)}"]`);
await expectSameAsNative(`["${'\\'.repeat(2 * length + 1)}"]`);
await expectSameAsNative(
Buffer.concat([
Buffer.from('["'),
Buffer.alloc(2 * length, 0x80),
Buffer.from([0xe2, 0x82]),
Buffer.from('"]'),
]),
);
}, 60_000);
it('reads a long key', async () => {
const key = 'k'.repeat(2 * SLICE_BYTES);
await expectSameAsNative(`{"a":1,"${key}":{"b":[2]},"${key}x":"v"}`);
await expectSameAsNative(`{"${key}\\n":2,"z":3}`);
});
it('reads long gaps of whitespace', async () => {
const gap = ' '.repeat(2 * SLICE_BYTES);
await expectSameAsNative(
`${gap}{${gap}"a"${gap}:${gap}1${gap},${gap}"b":[${gap}2${gap},3${gap}]${gap}}${gap}`,
);
await expectSameAsNative(`[1,${gap}2${gap}]`);
});
it('reads a scalar or a string at the top level', async () => {
await expectSameAsNative(padded('12.5'));
await expectSameAsNative(padded('null'));
await expectSameAsNative(`"${'x'.repeat(4 * SLICE_BYTES)}"`);
});
it('keeps the last of a repeated key, in its first position', async () => {
const filler = `"f":"${'x'.repeat(SLICE_BYTES)}"`;
await expectSameAsNative(`{"a":1,"b":2,${filler},"a":3,"7":4,"3":5}`);
const value = (await parseJsonInSlices(
Buffer.from(`{"a":1,"b":2,${filler},"a":3}`),
)) as Record<string, unknown>;
expect(Object.keys(value)).toEqual(['a', 'b', 'f']);
expect(value.a).toBe(3);
});
it('keeps __proto__ as a plain own property', async () => {
const filler = `"f":"${'x'.repeat(SLICE_BYTES)}"`;
const bodies = [
// In a batch of members, as a container of its own, and alone.
`{${filler},"__proto__":{"polluted":true},"z":1}`,
`{"__proto__":{"polluted":true,${filler}}}`,
`{"__proto__":"${'y'.repeat(2 * SLICE_BYTES)}"}`,
];
for (const body of bodies) {
const value = (await parseJsonInSlices(
Buffer.from(body),
)) as Record<string, unknown>;
expect(Object.getPrototypeOf(value)).toBe(Object.prototype);
expect(Object.hasOwn(value, '__proto__')).toBe(true);
expect(({} as { polluted?: boolean }).polluted).toBeUndefined();
}
});
it('keeps the sign of negative zero', async () => {
const value = (await parseJsonInSlices(
Buffer.from(`[${'0,'.repeat(SLICE_BYTES)}-0]`),
)) as number[];
expect(Object.is(value.at(-1), -0)).toBe(true);
});
it('reads nesting up to the depth limit and refuses more', async () => {
const nested = (depth: number) =>
padded(`${'['.repeat(depth)}${']'.repeat(depth)}`);
// The root is not a level of nesting.
let value = await parseJsonInSlices(Buffer.from(nested(MAX_DEPTH)));
let depth = 0;
while (Array.isArray(value)) {
depth++;
value = value[0];
}
expect(depth).toBe(MAX_DEPTH);
await expect(
parseJsonInSlices(Buffer.from(nested(MAX_DEPTH + 1))),
).rejects.toThrow(SyntaxError);
});
it('reads members spread thinly across many levels', async () => {
// No level holds a slice of members, but together they hold many.
const members = '1,'.repeat(SLICE_BYTES / 8);
const depth = 200;
await expectSameAsNative(
`${`[${members}`.repeat(depth)}0${']'.repeat(depth)}`,
);
await expectSameAsNative(
`${`{"a":[${members}0],"b":`.repeat(depth)}0${'}'.repeat(depth)}`,
);
});
it('lets the event loop run while it parses', async () => {
// Dense input: the slowest kind to parse for its size.
const body = Buffer.from(`[${'[],'.repeat(1_000_000)}[]]`);
let turns = 0;
let running = true;
const tick = () => {
turns++;
if (running) setImmediate(tick);
};
setImmediate(tick);
const value = (await parseJsonInSlices(body)) as unknown[];
running = false;
expect(value).toHaveLength(1_000_001);
expect(turns).toBeGreaterThan(5);
});
});
+581
View File
@@ -0,0 +1,581 @@
/*
* Copyright (C) 2024-present Puter Technologies Inc.
*
* This file is part of Puter.
*
* Puter is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import { setImmediate as nextTurn } from 'node:timers/promises';
/**
* Text handed to one native `JSON.parse` call stays within a few multiples of
* this, which bounds how long the call can run. Shorter input parses whole.
*/
export const SLICE_BYTES = 32 * 1024;
/** Bytes of a long string decoded per turn. */
export const STRING_PIECE_BYTES = 512 * 1024;
/** Deeper nesting is refused. No mainstream serializer writes this deep. */
export const MAX_DEPTH = 10_000;
/** How long a parse runs before the event loop gets a turn. */
const TURN_BUDGET_MS = 3;
/** Bytes scanned between clock reads. */
const CLOCK_INTERVAL_BYTES = 16 * 1024;
/** Bytes of a string scanned one at a time before a native search takes over. */
const BYTEWISE_BYTES = 64;
/** Rounds of a string scan between clock reads. */
const CLOCK_INTERVAL_ROUNDS = 64;
const QUOTE = 0x22;
const BACKSLASH = 0x5c;
// Byte classes. Anything unlisted is part of a number or literal.
const C_SCALAR = 0;
const C_SPACE = 1;
const C_QUOTE = 2;
const C_OPEN_ARRAY = 3;
const C_OPEN_OBJECT = 4;
const C_CLOSE_ARRAY = 5;
const C_CLOSE_OBJECT = 6;
const C_COMMA = 7;
const C_COLON = 8;
const BYTE_CLASS = new Uint8Array(256);
for (const byte of [0x20, 0x09, 0x0a, 0x0d]) BYTE_CLASS[byte] = C_SPACE;
BYTE_CLASS[QUOTE] = C_QUOTE;
BYTE_CLASS[0x5b] = C_OPEN_ARRAY;
BYTE_CLASS[0x7b] = C_OPEN_OBJECT;
BYTE_CLASS[0x5d] = C_CLOSE_ARRAY;
BYTE_CLASS[0x7d] = C_CLOSE_OBJECT;
BYTE_CLASS[0x2c] = C_COMMA;
BYTE_CLASS[0x3a] = C_COLON;
const ROOT = 0;
const ARRAY = 1;
const OBJECT = 2;
/** Just opened: a member or the close. */
const S_FIRST = 0;
/** After a comma: a member. */
const S_MEMBER = 1;
/** After an object key. */
const S_COLON = 2;
/** After a colon, and the root before its value. */
const S_VALUE = 3;
/** After a value: a comma or the close. The root is done. */
const S_AFTER = 4;
const DONE = 0;
const TURN = 1;
const LONG_STRING = 2;
/**
* One open container, or the root. Members are scanned, not parsed: `pending`
* marks text handed to `JSON.parse` once enough of it has built up, and a
* container too large for one call gets its `out` filled a batch at a time.
*/
class Frame {
kind = ROOT;
state = S_VALUE;
/** Offset of the opening bracket. */
start = 0;
/** The container under construction, once it is known to be large. */
out: unknown[] | Record<string, unknown> | null = null;
/** Where the members not yet parsed start, or -1. */
pending = -1;
/** Where the last complete member ended. */
lastEnd = -1;
/** Bounds of the member being scanned. */
memberStart = -1;
keyStart = -1;
keyEnd = -1;
valueStart = -1;
/** The current member's key, when the member is parsed apart from `pending`. */
ownKey: string | null = null;
/** Bytes of the parent's `pending` waiting behind this container. */
backlog = 0;
open(kind: number, start: number): void {
this.kind = kind;
this.state = kind === ROOT ? S_VALUE : S_FIRST;
this.start = start;
this.out = null;
this.pending = -1;
this.lastEnd = -1;
this.memberStart = -1;
this.keyStart = -1;
this.keyEnd = -1;
this.valueStart = -1;
this.ownKey = null;
this.backlog = 0;
}
}
const unexpected = (at: number): SyntaxError =>
new SyntaxError(`Unexpected token in JSON at position ${at}`);
/** `JSON.parse` keeps `__proto__` as an own property; assignment would not. */
const setOwn = (
target: Record<string, unknown>,
key: string,
value: unknown,
): void => {
if (key === '__proto__') {
Object.defineProperty(target, key, {
value,
writable: true,
enumerable: true,
configurable: true,
});
} else {
target[key] = value;
}
};
class SlicedJsonParser {
result: unknown;
/** Bounds of the string `run` stopped at, quotes included. */
longStart = -1;
longEnd = -1;
readonly #body: Buffer;
readonly #end: number;
#pos = 0;
#frames = [new Frame()];
#depth = 0;
/** Frames below this depth have an `out`; the root counts as one. */
#filling = 1;
/** Bytes of `pending` in frames below the top one. */
#backlog = 0;
#inScalar = false;
/** The string being scanned, and where its scan resumes. */
#stringStart = -1;
#stringPos = 0;
/** Next quote and backslash at or after the last search origin. */
#quoteAt = -1;
#backslashAt = -1;
#longIsKey = false;
constructor(body: Buffer) {
this.#body = body;
this.#end = body.length;
}
/** Scans until the input ends, `deadline` passes, or a long string starts. */
run(deadline: number): number {
const body = this.#body;
const end = this.#end;
let i = this.#pos;
let frame = this.#frames[this.#depth]!;
let clockAt = i + CLOCK_INTERVAL_BYTES;
for (;;) {
if (this.#stringStart !== -1) {
const close = this.#stringEnd(deadline);
if (close === -1) return TURN;
const start = this.#stringStart;
this.#stringStart = -1;
i = close + 1;
if (this.#string(frame, start, close)) {
this.#pos = i;
return LONG_STRING;
}
continue;
}
if (i >= clockAt) {
clockAt = i + CLOCK_INTERVAL_BYTES;
if (performance.now() >= deadline) {
this.#pos = i;
return TURN;
}
}
if (i >= end) break;
const byteClass = BYTE_CLASS[body[i]!]!;
if (byteClass === C_SCALAR) {
if (!this.#inScalar) {
this.#valueStart(frame, i);
this.#inScalar = true;
}
const stop = Math.min(end, clockAt);
i++;
while (i < stop && BYTE_CLASS[body[i]!] === C_SCALAR) i++;
continue;
}
if (this.#inScalar) {
this.#inScalar = false;
this.#valueEnd(frame, i);
}
switch (byteClass) {
case C_SPACE: {
const stop = Math.min(end, clockAt);
i++;
while (i < stop && BYTE_CLASS[body[i]!] === C_SPACE) i++;
break;
}
case C_QUOTE:
this.#stringStart = i;
this.#stringPos = i + 1;
break;
case C_OPEN_ARRAY:
case C_OPEN_OBJECT: {
this.#valueStart(frame, i);
if (this.#depth === MAX_DEPTH) {
throw new SyntaxError('JSON is nested too deeply');
}
const parent = frame;
// Members before this one wait until it closes or grows.
const before =
parent.pending !== -1 &&
parent.pending !== parent.memberStart
? parent.lastEnd - parent.pending
: 0;
this.#depth++;
frame = this.#frames[this.#depth] ??= new Frame();
frame.open(byteClass === C_OPEN_ARRAY ? ARRAY : OBJECT, i);
frame.backlog = before;
this.#backlog += before;
// Parsed now, so deep nesting can't save it all up.
if (this.#backlog >= SLICE_BYTES) this.#fill();
i++;
break;
}
case C_CLOSE_ARRAY:
case C_CLOSE_OBJECT: {
if (
frame.kind !==
(byteClass === C_CLOSE_ARRAY ? ARRAY : OBJECT) ||
(frame.state !== S_FIRST && frame.state !== S_AFTER)
) {
throw unexpected(i);
}
let filled = this.#depth < this.#filling;
if (!filled && i + 1 - frame.start > SLICE_BYTES) {
this.#fill();
filled = true;
}
if (filled) {
if (frame.pending !== -1) {
this.#parsePending(frame);
}
frame.out = null;
this.#filling = this.#depth;
}
this.#backlog -= frame.backlog;
this.#depth--;
frame = this.#frames[this.#depth]!;
i++;
if (filled) {
frame.state = S_AFTER;
frame.lastEnd = i;
} else {
this.#valueEnd(frame, i);
}
break;
}
case C_COMMA:
if (frame.kind === ROOT || frame.state !== S_AFTER) {
throw unexpected(i);
}
frame.state = S_MEMBER;
i++;
break;
default:
if (frame.kind !== OBJECT || frame.state !== S_COLON) {
throw unexpected(i);
}
frame.state = S_VALUE;
i++;
}
}
if (this.#inScalar) {
this.#inScalar = false;
this.#valueEnd(frame, end);
}
if (this.#depth !== 0 || frame.state !== S_AFTER) {
throw new SyntaxError('Unexpected end of JSON input');
}
if (frame.pending !== -1) this.#parsePending(frame);
return DONE;
}
/** Supplies the string `run` stopped at. */
resolveLongString(value: string): void {
const frame = this.#frames[this.#depth]!;
if (this.#longIsKey) {
frame.ownKey = value;
return;
}
this.#attach(frame, frame.ownKey, value);
frame.ownKey = null;
frame.lastEnd = this.longEnd + 1;
frame.state = S_AFTER;
}
/**
* Offset of the quote closing the string being scanned, or -1 when
* `deadline` passed first.
*/
#stringEnd(deadline: number): number {
const body = this.#body;
const end = this.#end;
let at = this.#stringPos;
for (let round = 1; ; round++) {
// Bytewise through a short string or a stretch of escapes.
const near = Math.min(at + BYTEWISE_BYTES, end);
while (at < near) {
const byte = body[at]!;
if (byte === QUOTE) return at;
at += byte === BACKSLASH ? 2 : 1;
}
if (at >= end) throw new SyntaxError('Unterminated string in JSON');
// Then a native search across text that holds neither.
if (this.#quoteAt < at) {
this.#quoteAt = body.indexOf(QUOTE, at);
if (this.#quoteAt === -1) {
throw new SyntaxError('Unterminated string in JSON');
}
}
if (this.#backslashAt < at) {
const found = body.indexOf(BACKSLASH, at);
this.#backslashAt = found === -1 ? end : found;
}
if (this.#backslashAt > this.#quoteAt) return this.#quoteAt;
at = this.#backslashAt;
if (round % CLOCK_INTERVAL_ROUNDS === 0) {
if (performance.now() >= deadline) {
this.#stringPos = at;
return -1;
}
}
}
}
/** Handles a scanned string; true when `run` must stop for a long one. */
#string(frame: Frame, start: number, close: number): boolean {
const long = close - start > SLICE_BYTES;
if (
frame.kind === OBJECT &&
(frame.state === S_FIRST || frame.state === S_MEMBER)
) {
this.#memberStart(frame, start);
frame.keyStart = start;
frame.keyEnd = close;
frame.state = S_COLON;
if (!long) return false;
this.#detachMember(frame);
this.#longIsKey = true;
} else {
this.#valueStart(frame, start);
if (!long) {
this.#valueEnd(frame, close + 1);
return false;
}
if (frame.ownKey === null) {
this.#detachMember(frame);
if (frame.kind === OBJECT) frame.ownKey = this.#key(frame);
}
this.#longIsKey = false;
}
this.longStart = start;
this.longEnd = close;
return true;
}
#memberStart(frame: Frame, at: number): void {
if (frame.pending !== -1 && at - frame.pending >= SLICE_BYTES) {
this.#fill();
this.#parsePending(frame);
}
frame.memberStart = at;
if (frame.pending === -1) frame.pending = at;
}
#valueStart(frame: Frame, at: number): void {
if (frame.kind === OBJECT) {
if (frame.state !== S_VALUE) throw unexpected(at);
// A long gap after the key would reach `JSON.parse` with it.
if (frame.ownKey === null && at - frame.memberStart > SLICE_BYTES) {
this.#detachMember(frame);
frame.ownKey = this.#key(frame);
}
} else {
if (
frame.kind === ROOT
? frame.state !== S_VALUE
: frame.state > S_MEMBER
) {
throw unexpected(at);
}
this.#memberStart(frame, at);
}
frame.valueStart = at;
}
#valueEnd(frame: Frame, at: number): void {
frame.lastEnd = at;
frame.state = S_AFTER;
if (frame.ownKey !== null) {
this.#attach(
frame,
frame.ownKey,
JSON.parse(this.#text(frame.valueStart, at)),
);
frame.ownKey = null;
}
}
/** Takes the current member out of `pending`; its value is attached alone. */
#detachMember(frame: Frame): void {
this.#fill();
if (frame.pending !== -1 && frame.pending !== frame.memberStart) {
this.#parsePending(frame);
}
frame.pending = -1;
}
/**
* Gives every open container an `out`, attached to its parent after the
* members that precede it.
*/
#fill(): void {
const frames = this.#frames;
for (let level = this.#filling; level <= this.#depth; level++) {
const parent = frames[level - 1]!;
const child = frames[level]!;
if (
parent.pending !== -1 &&
parent.pending !== parent.memberStart
) {
this.#parsePending(parent);
}
parent.pending = -1;
const key =
parent.kind === OBJECT
? (parent.ownKey ?? this.#key(parent))
: null;
parent.ownKey = null;
child.out = child.kind === ARRAY ? [] : {};
child.backlog = 0;
this.#attach(parent, key, child.out);
}
this.#filling = this.#depth + 1;
this.#backlog = 0;
}
/** Parses the complete members in `pending` into the frame's container. */
#parsePending(frame: Frame): void {
const text = this.#text(frame.pending, frame.lastEnd);
frame.pending = -1;
if (frame.kind === ROOT) {
this.result = JSON.parse(text);
} else if (frame.kind === ARRAY) {
const out = frame.out as unknown[];
const items = JSON.parse(`[${text}]`) as unknown[];
for (let k = 0; k < items.length; k++) out.push(items[k]);
} else {
const out = frame.out as Record<string, unknown>;
const members = JSON.parse(`{${text}}`) as Record<string, unknown>;
for (const key of Object.keys(members)) {
setOwn(out, key, members[key]);
}
}
}
#attach(frame: Frame, key: string | null, value: unknown): void {
if (frame.kind === ROOT) this.result = value;
else if (frame.kind === ARRAY) (frame.out as unknown[]).push(value);
else setOwn(frame.out as Record<string, unknown>, key!, value);
}
#key(frame: Frame): string {
return JSON.parse(
this.#text(frame.keyStart, frame.keyEnd + 1),
) as string;
}
#text(from: number, to: number): string {
return this.#body.toString('utf8', from, to);
}
}
/**
* Where a string's content can be cut at or before `target` without splitting
* an escape or a UTF-8 sequence. `from` starts a character or an escape.
*/
const pieceEnd = (body: Buffer, from: number, target: number): number => {
// Far enough back that a `\uXXXX` reaching `target` starts after it.
let at = Math.max(from, target - 8);
// An odd run of backslashes before `at` means `at` is an escaped byte.
let run = 0;
while (at - run > from && body[at - run - 1] === BACKSLASH) run++;
at -= run % 2;
for (;;) {
const length =
body[at] !== BACKSLASH ? 1 : body[at + 1] === 0x75 ? 6 : 2;
if (at + length > target) break;
at += length;
}
// A sequence has at most three continuation bytes; more are stray.
for (let back = 0; back < 3 && (body[at]! & 0xc0) === 0x80; back++) at--;
return at;
};
/** The string literal at `[start, close]`, decoded a piece per turn. */
const readLongString = async (
body: Buffer,
start: number,
close: number,
): Promise<string> => {
const pieces: string[] = [];
let at = start + 1;
while (at < close) {
const end =
close - at <= STRING_PIECE_BYTES
? close
: pieceEnd(body, at, at + STRING_PIECE_BYTES);
pieces.push(
JSON.parse(`"${body.toString('utf8', at, end)}"`) as string,
);
at = end;
await nextTurn();
}
return pieces.join('');
};
/**
* `JSON.parse` of UTF-8 `body`, done in slices with the event loop running
* between them, so no input holds it for long. Throws a `SyntaxError` for
* malformed JSON, and for nesting deeper than `MAX_DEPTH`.
*/
export async function parseJsonInSlices(body: Buffer): Promise<unknown> {
if (body.length <= SLICE_BYTES) return JSON.parse(body.toString('utf8'));
const parser = new SlicedJsonParser(body);
for (;;) {
const signal = parser.run(performance.now() + TURN_BUDGET_MS);
if (signal === DONE) return parser.result;
if (signal === LONG_STRING) {
parser.resolveLongString(
await readLongString(body, parser.longStart, parser.longEnd),
);
} else {
await nextTurn();
}
}
}
-271
View File
@@ -1,271 +0,0 @@
/**
* Copyright (C) 2024-present Puter Technologies Inc.
*
* This file is part of Puter.
*
* Puter is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import { v4 as uuidv4 } from 'uuid';
import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
import { PuterServer } from '../server.ts';
import { setupTestServer } from '../testUtil.ts';
import { getTaskbarItems } from './taskbarItems.ts';
describe('getTaskbarItems', () => {
let server: PuterServer;
let deps: Parameters<typeof getTaskbarItems>[1];
beforeAll(async () => {
server = await setupTestServer();
deps = {
clients: server.clients,
stores: server.stores,
apiBaseUrl: 'https://api.puter.com',
config: { static_hosting_domain: 'puter.site' },
} as unknown as Parameters<typeof getTaskbarItems>[1];
});
afterAll(async () => {
await server?.shutdown();
});
const makeUser = async (taskbarItems?: unknown) => {
const username = `tb-${Math.random().toString(36).slice(2, 10)}`;
const created = await server.stores.user.create({
username,
uuid: uuidv4(),
password: null,
email: `${username}@test.local`,
} as never);
if (taskbarItems !== undefined) {
await server.stores.user.update(created.id, {
taskbar_items:
typeof taskbarItems === 'string'
? taskbarItems
: JSON.stringify(taskbarItems),
});
}
return (await server.stores.user.getById(created.id))!;
};
const makeApp = async (ownerUserId: number, overrides = {}) => {
const name = `tb-app-${Math.random().toString(36).slice(2, 10)}`;
return server.stores.app.create(
{
name,
title: `Title ${name}`,
index_url: `https://${name}.example.com/`,
description: 'a test app',
...overrides,
},
{ ownerUserId },
);
};
it('seeds the default taskbar for a user that has none, and persists it', async () => {
const user = await makeUser();
expect(user.taskbar_items).toBeFalsy();
await getTaskbarItems(user as never, deps);
const [row] = await server.clients.db.read(
'SELECT `taskbar_items` FROM `user` WHERE `id` = ?',
[user.id],
);
const stored = JSON.parse(String(row.taskbar_items));
expect(stored.map((e: { name: string }) => e.name)).toContain(
'app-center',
);
// The cached row must not keep serving the pre-seed value.
expect(
(await server.stores.user.getById(user.id))?.taskbar_items,
).toBeTruthy();
});
it('resolves entries by name, uid and id', async () => {
const owner = await makeUser([]);
const byName = await makeApp(owner.id);
const byUid = await makeApp(owner.id);
const byId = await makeApp(owner.id);
const user = await makeUser([
{ name: byName.name, type: 'app' },
{ uid: byUid.uid, type: 'app' },
{ id: byId.id, type: 'app' },
]);
const items = await getTaskbarItems(user as never, deps);
expect(items.map((i) => i.uid)).toEqual([
byName.uid,
byUid.uid,
byId.uid,
]);
expect(items[0]).toMatchObject({
uuid: byName.uid,
name: byName.name,
title: byName.title,
godmode: false,
maximize_on_start: false,
description: 'a test app',
});
});
it('resolves the whole taskbar with one batched lookup per key, not one per entry', async () => {
const owner = await makeUser([]);
const apps = await Promise.all([0, 1, 2].map(() => makeApp(owner.id)));
const byUid = await makeApp(owner.id);
const user = await makeUser([
...apps.map((app) => ({ name: app.name, type: 'app' })),
{ uid: byUid.uid, type: 'app' },
]);
const appStore = server.stores.app;
const spies = {
getByName: vi.spyOn(appStore, 'getByName'),
getByUid: vi.spyOn(appStore, 'getByUid'),
getById: vi.spyOn(appStore, 'getById'),
getByNames: vi.spyOn(appStore, 'getByNames'),
getByUids: vi.spyOn(appStore, 'getByUids'),
};
try {
const items = await getTaskbarItems(user as never, deps);
expect(items.map((i) => i.uid)).toEqual([
...apps.map((app) => app.uid),
byUid.uid,
]);
expect(spies.getByName).not.toHaveBeenCalled();
expect(spies.getByUid).not.toHaveBeenCalled();
expect(spies.getById).not.toHaveBeenCalled();
expect(spies.getByNames).toHaveBeenCalledTimes(1);
expect(spies.getByUids).toHaveBeenCalledTimes(1);
} finally {
for (const spy of Object.values(spies)) spy.mockRestore();
}
});
it('skips non-app entries, the explorer pin, and unresolvable apps', async () => {
const owner = await makeUser([]);
const app = await makeApp(owner.id);
const user = await makeUser([
{ name: 'explorer', type: 'app' },
{ name: 'nothing-here', type: 'app' },
{ name: app.name, type: 'separator' },
{ type: 'app' },
{ name: app.name, type: 'app' },
]);
const items = await getTaskbarItems(user as never, deps);
expect(items).toHaveLength(1);
expect(items[0].name).toBe(app.name);
});
it('falls back to an empty taskbar when the stored JSON is corrupt', async () => {
const user = await makeUser('{not json');
expect(await getTaskbarItems(user as never, deps)).toEqual([]);
});
it('accepts an already-parsed taskbar array on the user row', async () => {
const owner = await makeUser([]);
const app = await makeApp(owner.id);
const user = await makeUser([]);
const items = await getTaskbarItems(
{ ...user, taskbar_items: [{ name: app.name, type: 'app' }] },
deps,
);
expect(items.map((i) => i.name)).toEqual([app.name]);
});
it('builds a sized icon URL by default and drops the icon on request', async () => {
const owner = await makeUser([]);
const app = await makeApp(owner.id);
const user = await makeUser([{ name: app.name, type: 'app' }]);
const withIcon = await getTaskbarItems(user as never, deps, {
iconSize: 64,
});
expect(withIcon[0].icon).toBe(
`https://api.puter.com/app-icon/${app.uid}/64`,
);
const withoutIcon = await getTaskbarItems(user as never, deps, {
noIcons: true,
});
expect('icon' in withoutIcon[0]).toBe(false);
});
it('pairs the icon URL with the direct subdomain URL when one exists', async () => {
const owner = await makeUser([]);
// An http(s) icon column is what the resize pipeline leaves behind, so
// the sized PNG is on the subdomain.
const app = await makeApp(owner.id, {
icon: 'https://api.puter.com/app-icon/x',
});
const user = await makeUser([{ name: app.name, type: 'app' }]);
const items = await getTaskbarItems(user as never, deps, {
iconSize: 64,
});
expect(items[0].icon).toBe(
`https://api.puter.com/app-icon/${app.uid}/64`,
);
expect(items[0].iconCdnUrl).toBe(
`https://puter-app-icons.puter.site/${app.uid}-64.png`,
);
});
it('reports no subdomain URL for an app whose icon was never generated', async () => {
const owner = await makeUser([]);
const app = await makeApp(owner.id);
const user = await makeUser([{ name: app.name, type: 'app' }]);
const items = await getTaskbarItems(user as never, deps, {
iconSize: 64,
});
expect(items[0].iconCdnUrl).toBeNull();
});
it('falls back to the raw icon column when no API base URL is configured', async () => {
const owner = await makeUser([]);
const app = await makeApp(owner.id, {
icon: 'https://cdn.example.com/i.png',
});
const user = await makeUser([{ name: app.name, type: 'app' }]);
const items = await getTaskbarItems(
user as never,
{
...deps,
apiBaseUrl: undefined,
} as never,
);
expect(items[0].icon).toBe('https://cdn.example.com/i.png');
});
it('reports null for an app with no icon and no API base URL', async () => {
const owner = await makeUser([]);
const app = await makeApp(owner.id);
const user = await makeUser([{ name: app.name, type: 'app' }]);
const items = await getTaskbarItems(
user as never,
{
...deps,
apiBaseUrl: undefined,
} as never,
);
expect(items[0].icon).toBeNull();
});
});
-134
View File
@@ -1,134 +0,0 @@
/*
* Copyright (C) 2024-present Puter Technologies Inc.
*
* This file is part of Puter.
*
* Puter is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import type { AppIconHostConfig } from './appIcon.js';
import { toAppSummary, type AppRow } from './appView.js';
interface TaskbarEntry {
name?: string;
id?: number;
uid?: string;
type?: string;
}
interface TaskbarOptions {
iconSize?: number;
noIcons?: boolean;
}
interface TaskbarDeps {
apiBaseUrl?: string;
config?: AppIconHostConfig;
stores: {
app: {
getByNames: (names: string[]) => Promise<Map<string, AppRow>>;
getByUids: (uids: string[]) => Promise<Map<string, AppRow>>;
getByIds: (ids: number[]) => Promise<Map<number, AppRow>>;
};
user: {
update: (
id: number,
patch: Record<string, unknown>,
) => Promise<unknown>;
};
};
}
const DEFAULT_TASKBAR_ITEMS: TaskbarEntry[] = [
{ name: 'app-center', type: 'app' },
{ name: 'builder', type: 'app' },
{ name: 'dev-center', type: 'app' },
{ name: 'editor', type: 'app' },
{ name: 'code', type: 'app' },
{ name: 'camera', type: 'app' },
{ name: 'recorder', type: 'app' },
{ name: 'browser', type: 'app' },
];
export async function getTaskbarItems(
user: Record<string, unknown>,
deps: TaskbarDeps,
options: TaskbarOptions = {},
): Promise<Array<Record<string, unknown>>> {
let raw: TaskbarEntry[];
if (!user.taskbar_items) {
raw = DEFAULT_TASKBAR_ITEMS;
await deps.stores.user.update(user.id as number, {
taskbar_items: JSON.stringify(raw),
});
} else {
try {
raw =
typeof user.taskbar_items === 'string'
? JSON.parse(user.taskbar_items as string)
: (user.taskbar_items as TaskbarEntry[]);
} catch {
raw = [];
}
}
const entries = raw.filter(
(entry) => entry.type === 'app' && entry.name !== 'explorer',
);
const [byName, byUid, byId] = await Promise.all([
deps.stores.app.getByNames(
entries.flatMap((entry) => (entry.name ? [entry.name] : [])),
),
deps.stores.app.getByUids(
entries.flatMap((entry) =>
!entry.name && entry.uid ? [entry.uid] : [],
),
),
deps.stores.app.getByIds(
entries.flatMap((entry) =>
!entry.name && !entry.uid && entry.id ? [entry.id] : [],
),
),
]);
const items: Array<Record<string, unknown>> = [];
for (const entry of entries) {
const app = entry.name
? byName.get(entry.name)
: entry.uid
? byUid.get(entry.uid)
: entry.id
? byId.get(entry.id)
: undefined;
if (!app) continue;
const item: Record<string, unknown> = {
uid: app.uid,
...toAppSummary(app, {
apiBaseUrl: deps.apiBaseUrl,
config: deps.config,
iconSize: options.iconSize,
}),
description: app.description,
};
if (options.noIcons) {
delete item.icon;
delete item.iconCdnUrl;
}
items.push(item);
}
return items;
}
+13 -21
View File
@@ -85,7 +85,17 @@ describe('buildUserDetails', () => {
[`/${user.username}/Desktop`]: user.desktop_uuid,
[`/${user.username}/Trash`]: user.trash_uuid,
});
expect(Array.isArray(details.taskbar_items)).toBe(true);
});
it('leaves out taskbar items saved on the account', async () => {
const user = {
...(await makeUser()),
taskbar_items: JSON.stringify([{ type: 'app', name: 'editor' }]),
};
const details = await buildUserDetails(user, deps(), {
isUser: true,
});
expect(details).not.toHaveProperty('taskbar_items');
});
it('leaves the desktop-only parts out for an app actor', async () => {
@@ -93,7 +103,6 @@ describe('buildUserDetails', () => {
const details = await buildUserDetails(user, deps(), {
isUser: false,
});
expect(details).not.toHaveProperty('taskbar_items');
expect(details).not.toHaveProperty('directories');
expect(details.card_fallback_available).toBe(false);
});
@@ -124,7 +133,7 @@ describe('buildUserDetails lookups', () => {
return keys.slice(keys.indexOf('hasDevAccountAccess') + 1);
};
it('reads the linked provider, taskbar and seat together, listed in a fixed order', async () => {
it('reads the linked provider and seat together, listed in a fixed order', async () => {
const user = {
...(await makeUser()),
password: null,
@@ -162,7 +171,6 @@ describe('buildUserDetails lookups', () => {
);
expect(tailKeys(details)).toEqual([
'oidc_revalidate_url',
'taskbar_items',
'directories',
'team',
'last_activity_ts',
@@ -177,7 +185,6 @@ describe('buildUserDetails lookups', () => {
const user = {
...(await makeUser()),
password: null,
taskbar_items: JSON.stringify([{ type: 'app', name: 'editor' }]),
last_activity_ts: '2026-01-02 03:04:05',
};
const events: string[] = [];
@@ -199,15 +206,6 @@ describe('buildUserDetails lookups', () => {
},
},
stores: Object.assign(Object.create(d.stores), {
app: {
getByNames: () =>
timed(events, 'taskbar', 20, () => {
throw new Error('taskbar down');
}),
getByUids: async () => new Map(),
getByIds: async () => new Map(),
},
// Fails first, but is reported after the taskbar.
team: {
getOrgSeat: () =>
timed(events, 'seat', 5, () => {
@@ -219,18 +217,12 @@ describe('buildUserDetails lookups', () => {
{ isUser: true },
);
expect(warn.mock.calls).toEqual([
['[user-details] taskbar_items failed:', expect.any(Error)],
['[user-details] team lookup failed:', expect.any(Error)],
]);
} finally {
warn.mockRestore();
}
expect(tailKeys(details)).toEqual([
'taskbar_items',
'directories',
'last_activity_ts',
]);
expect(details.taskbar_items).toEqual([]);
expect(tailKeys(details)).toEqual(['directories', 'last_activity_ts']);
});
});
+7 -49
View File
@@ -27,18 +27,12 @@ import {
isCardFallbackEligible,
type CardFallbackClients,
} from './cardFallback.js';
import { getTaskbarItems } from './taskbarItems.js';
import { isEmailGateLast } from './verificationOrder.js';
type TaskbarDeps = Parameters<typeof getTaskbarItems>[1];
export interface UserDetailsDeps {
config: IConfig;
// `db.write` backs the taskbar's first-read default row.
clients: CardFallbackClients & {
db: { write: (query: string, params?: unknown[]) => Promise<unknown> };
};
stores: TaskbarDeps['stores'] & {
clients: CardFallbackClients;
stores: {
kv: Pick<SystemKVStore, 'get'>;
team?: Pick<TeamStoreContract, 'getOrgSeat'>;
};
@@ -78,8 +72,8 @@ const SENSITIVE_KEYS: ReadonlySet<string> = new Set([
]);
/**
* Delete every sensitive key at any depth (`metadata` and `taskbar_items` are
* nested). Depth-limited and cycle-safe. Runs last over a whole payload.
* Delete every sensitive key at any depth (`metadata` is nested). Depth-limited
* and cycle-safe. Runs last over a whole payload.
*/
export const scrubSensitive = (
value: unknown,
@@ -124,7 +118,7 @@ export const toUnixSeconds = (value: unknown): number | undefined => {
export async function buildUserDetails(
user: UserRow,
deps: UserDetailsDeps,
opts: { isUser: boolean; iconSize?: number; noIcons?: boolean },
opts: { isUser: boolean },
): Promise<Record<string, unknown>> {
const { config, clients, stores, services } = deps;
const { isUser } = opts;
@@ -170,9 +164,6 @@ export async function buildUserDetails(
cardFallbackDepsFrom(clients),
)
: false,
desktop_bg_url: user.desktop_bg_url,
desktop_bg_color: user.desktop_bg_color,
desktop_bg_fit: user.desktop_bg_fit,
is_temp: user.password === null && user.email === null,
is_user_token: true,
// Null until the account asks for a code; never minted here.
@@ -185,14 +176,6 @@ export async function buildUserDetails(
hasDevAccountAccess: !!user.metadata?.hasDevAccountAccess,
};
// Not an inline literal, so a `TaskbarDeps` without `clients` still
// accepts it.
const taskbarDeps = {
clients,
stores,
apiBaseUrl: String(config.api_base_url ?? ''),
config,
};
const linkedProvider = async () => {
if (!oidcOnly) return null;
try {
@@ -202,19 +185,6 @@ export async function buildUserDetails(
return null;
}
};
const taskbarItems = async () => {
if (!isUser) return null;
try {
return {
items: await getTaskbarItems(user, taskbarDeps, {
iconSize: opts.iconSize,
noIcons: opts.noIcons,
}),
};
} catch (error) {
return { error };
}
};
// The team that pays for the account; every seat restriction keys on it.
const orgSeat = async () => {
if (!isUser || config.teams_enabled !== true) return null;
@@ -226,26 +196,14 @@ export async function buildUserDetails(
};
// Independent and each best-effort, so read together; the results land
// below in the order the payload has always listed them.
const [provider, taskbar, team] = await Promise.all([
linkedProvider(),
taskbarItems(),
orgSeat(),
]);
const [provider, team] = await Promise.all([linkedProvider(), orgSeat()]);
if (provider) {
const origin = (config.origin ?? '').replace(/\/$/, '');
details.oidc_revalidate_url = `${origin}/auth/oidc/${provider}/start?flow=revalidate&user_uuid=${encodeURIComponent(user.uuid)}`;
}
if (taskbar) {
// Best-effort: the account still works without them.
if ('error' in taskbar) {
console.warn('[user-details] taskbar_items failed:', taskbar.error);
details.taskbar_items = [];
} else {
details.taskbar_items = taskbar.items;
}
if (isUser) {
const directories: Record<string, unknown> = {};
const nameToProp: Record<string, string> = {
desktop_uuid: `/${user.username}/Desktop`,
+6
View File
@@ -385,6 +385,10 @@ The `usageDetails.serviceSpeed` field reports the served speed. Billing uses the
### OpenAI models
Passing `service_tier: "priority"` selects fast service, and `service_tier: "ultrafast"` selects ultrafast service. These requests use the same prices and supported-speed selection as `serviceSpeed`. An explicit `serviceSpeed` takes precedence.
Input and reasoning tokens reported by a non-streaming Responses API call are billed even when its output is empty. These charges apply whether the request fails or retries another provider.
Fast service is available on models with a published Fast rate card. Ultrafast is available for GPT-6.1 Sol and GPT-6 Astra. Other models fall back to fast or standard. Cache and long-context rates apply to the served tier.
#### `temperature`
@@ -588,6 +592,8 @@ MiniMax M3 uses Priority admission for fast service. Earlier models with an equi
Fast service requests Priority when the account and model are eligible. The provider can serve the request at standard speed.
Passing `service_tier: "auto"` selects fast service, with the same prices as `serviceSpeed: "fast"`. An explicit `serviceSpeed` takes precedence.
### Alibaba Cloud models
Models with an equivalent Prime or Fast variant select that variant for fast service. Other models use standard service.
+1 -1
View File
@@ -32,7 +32,7 @@ Fine-tune the conversion:
| Option | Type | Description |
|--------|------|-------------|
| `voice` | `String` | Target ElevenLabs voice ID. Defaults to `21m00Tcm4TlvDq8ikWAM`. |
| `model` | `String` | Voice-changer model. Defaults to `eleven_multilingual_sts_v2`. You can also use `eleven_english_sts_v2` for English-only inputs. |
| `model` | `String` | Voice-changer model, either `eleven_multilingual_sts_v2` or `eleven_english_sts_v2` (English-only inputs). Defaults to `eleven_multilingual_sts_v2`. Any other value fails with a `field_invalid` error. |
| `output_format` | `String` | Desired output codec and bitrate, e.g. `mp3_44100_128`, `opus_48000_64`, or `pcm_48000`. Defaults to `mp3_44100_128`. |
| `voice_settings` | `Object \| String` | ElevenLabs voice settings payload (e.g. `{"stability":0.5,"similarity_boost":0.75}`). |
| `remove_background_noise` | `Boolean` | Apply background noise removal. |
+1 -1
View File
@@ -12,7 +12,7 @@ When the user adds a new domain, the dialog shows the DNS records to set at thei
Your app doesn't need any permission to call this method. The user makes the choice in the dialog, and your app only receives the domain they chose. Custom domains are billed to the user's Puter account, and the dialog shows the price before the user adds one.
Inside Puter, the dialog is rendered by the desktop environment. On a website, a puter.com popup hosts the dialog and signs the user in first if needed.
Inside Puter, the dialog is rendered by the desktop environment. On a website, a puter.com popup hosts the dialog and signs the user in first if needed. Puter's own apps on puter.com subdomains show it in a frame over the page instead, when the user is signed in to both.
## Syntax
+1 -2
View File
@@ -27,7 +27,7 @@ A set of key/value pairs that configure the window.
| `is_resizable` | `Boolean` | If set to `true`, the user can resize the window. |
| `has_head` | `Boolean` | If set to `true`, the window has a head which contains the icon and the close, minimize, and maximize buttons. |
| `disable_parent_window` | `Boolean` | If set to `true`, the parent window is blocked until the current window is closed. |
| `show_in_taskbar` | `Boolean` | If set to `true`, the window is represented in the taskbar. |
| `show_in_taskbar` | `Boolean` | Deprecated. It has no effect. |
## Return value
A `Promise` that resolves to a window handle object with an `id` (String) property identifying the created window. This `id` can be passed as the `window_id` argument to the `setWindow*` methods.
@@ -50,7 +50,6 @@ A `Promise` that resolves to a window handle object with an `id` (String) proper
is_resizable: false,
has_head: true,
center: true,
show_in_taskbar: false,
})
</script>
</body>
+5 -6
View File
@@ -36,12 +36,11 @@ Without `background`, Puter creates and shows the window before the app's own co
runs, so a service app cannot avoid briefly appearing on screen.
A background instance stays private to your app for as long as it is hidden: it has no
taskbar item and no running mark on its icon, and opening the app from the
taskbar or from Puter's app list starts a separate, ordinary instance for the
user rather than handing them the one you are talking to. It can show itself at
any time with [`puter.ui.showWindow()`](/UI/showWindow), and from that moment it
is an ordinary window. It takes its place in the taskbar, and the user can
return to it, hide it, or close it like any other.
running mark on its icon, and opening the app from Puter's app list starts a
separate, ordinary instance for the user rather than handing them the one you
are talking to. It can show itself at any time with
[`puter.ui.showWindow()`](/UI/showWindow), and from that moment it is an
ordinary window that the user can return to, hide, or close like any other.
A background app closes when the app that launched it closes: it was launched to
serve that app, and the user never saw it. Once it has shown itself it keeps
+17 -1
View File
@@ -13,6 +13,20 @@ puter.ui.showColorPicker(defaultColor)
puter.ui.showColorPicker(options)
```
## Parameters
#### `defaultColor` (String)
The color to select when the color picker is opened, as a hex string such as `#3b82f6` or `#38f`.
#### `options` (Object)
An object with the following properties:
| Option | Type | Description |
|--------|------|-------------|
| `defaultColor` | `String` | The color to select when the color picker is opened, as a hex string. The picker has no alpha, so the alpha in an 8-digit hex such as `#3b82f680` is ignored. If the value isn't a valid hex color, the picker opens on `#3b82f6`. The `defaultValue` and `default` options are accepted as aliases. If more than one is given, `defaultValue` is used, then `defaultColor`, then `default`. |
## Return value
A `Promise` that resolves to the selected color as a lowercase 6-digit hex string, such as `#ff0000`. If the user closes the picker without selecting a color, the promise resolves to `null`.
## Examples
### Change the background to the picked color
@@ -23,7 +37,9 @@ puter.ui.showColorPicker(options)
<script src="https://js.puter.com/v2/"></script>
<script>
puter.ui.showColorPicker().then((color)=>{
document.body.style.backgroundColor = color;
if (color) {
document.body.style.backgroundColor = color;
}
})
</script>
</body>
@@ -6,8 +6,10 @@
<script>
document.getElementById('pick-color').addEventListener('click', () => {
puter.ui.showColorPicker().then((color) => {
document.body.style.backgroundColor = color;
puter.print('Selected color: ' + color);
if (color) {
document.body.style.backgroundColor = color;
puter.print('Selected color: ' + color);
}
});
});
</script>
+1 -1
View File
@@ -159,7 +159,7 @@ The [`puter.ai.realtime()`](/AI/realtime/) SDK also applies these limits before
`/puterai/anthropic/v1/messages/count_tokens` has its own budget of 120 requests per minute per user, with no concurrency limit, and is not charged.
Chat requests accept JSON bodies up to 128 MiB (134,217,728 bytes), including `text/plain;actually=json` bodies. That covers `puter-chat-completion` calls through `/drivers/call`, which `puter.ai.chat()` uses, and POSTs to `/puterai/openai/v1/*`, `/puterai/anthropic/v1/messages` and `/puterai/anthropic/v1/messages/count_tokens`. A body over 50 MiB needs a `Content-Length` header and a token in the `Authorization` or `x-api-key` header (or a session cookie); an `auth_token` inside the body isn't read until the body is, so it only works up to 50 MiB. Larger bodies, and bodies over 50 MiB for other drivers, return HTTP 413. One account can have up to 128 MiB of these large bodies in flight at once; past that, requests get `429` with `Retry-After`. A server handling too many large bodies at once returns `503` with `Retry-After`. Retry either after the given number of seconds. Other routes accept JSON bodies up to 50 MiB.
Chat requests accept JSON bodies up to 128 MiB (134,217,728 bytes), including `text/plain;actually=json` bodies. That covers `puter-chat-completion` calls through `/drivers/call`, which `puter.ai.chat()` uses, and POSTs to `/puterai/openai/v1/*`, `/puterai/anthropic/v1/messages` and `/puterai/anthropic/v1/messages/count_tokens`. A body over 50 MiB needs a `Content-Length` header and a credential that can be read before the rest of the body. That is a token in the `Authorization` or `x-api-key` header, a session cookie, or an `auth_token` that is the first field of the body, which is where Puter.js sends it. An `auth_token` after other fields isn't read until the body is, so it only works up to 50 MiB. Larger bodies, and bodies over 50 MiB for other drivers, return HTTP 413. One account can have up to 128 MiB of these large bodies in flight at once; past that, requests get `429` with `Retry-After`. A server handling too many large bodies at once returns `503` with `Retry-After`. Retry either after the given number of seconds. Other routes accept JSON bodies up to 50 MiB. A JSON body in a charset other than UTF-8 is accepted up to 1 MiB. A JSON body over 32 KiB can nest arrays and objects up to 10,000 levels deep, and deeper nesting returns HTTP 400.
Claude's server-executed tools are clamped so a request can't reserve an unbounded amount of credit:
-2
View File
@@ -1,7 +1,5 @@
## Credits
The default wallpaper is created by [Milad Fakurian](https://unsplash.com/photos/blue-orange-and-yellow-wallpaper-E8Ufcyxz514) and published on [Unsplash](https://unsplash.com/).
Icons by [Papirus](https://github.com/PapirusDevelopmentTeam/papirus-icon-theme) under GPL-3.0 license.
Icons by [Iconoir](https://iconoir.com/) under MIT license.
-1
View File
@@ -11,7 +11,6 @@
"/lib/jquery.dragster.js",
"/lib/html-entities.js",
"/lib/timeago.min.js",
"/lib/iro.min.js",
"/lib/isMobile.min.js",
"/lib/fflate-0.8.2.min.js"
],
-1
View File
@@ -40,7 +40,6 @@ vi.mock('./UI/UIPopover.js', stub);
vi.mock('./UI/UIPrompt.js', stub);
vi.mock('./UI/UIWindow.js', stub);
vi.mock('./UI/UIWindowAppFeedback.js', stub);
vi.mock('./UI/UIWindowColorPicker.js', stub);
vi.mock('./UI/UIWindowEmailConfirmationRequired.js', stub);
vi.mock('./UI/UIWindowFontPicker.js', stub);
vi.mock('./UI/UIPermissionDialog.js', () => ({ default: permissionDialog }));
-1
View File
@@ -18,7 +18,6 @@ vi.mock('./UI/UIPopover.js', stub);
vi.mock('./UI/UIPrompt.js', stub);
vi.mock('./UI/UIWindow.js', stub);
vi.mock('./UI/UIWindowAppFeedback.js', stub);
vi.mock('./UI/UIWindowColorPicker.js', stub);
vi.mock('./UI/UIWindowEmailConfirmationRequired.js', stub);
vi.mock('./UI/UIWindowFontPicker.js', stub);
vi.mock('./UI/UIPermissionDialog.js', stub);
+28 -22
View File
@@ -32,7 +32,6 @@ import UIPrompt from './UI/UIPrompt.js';
import UIWindow from './UI/UIWindow.js';
import UIWindowAppFeedback from './UI/UIWindowAppFeedback.js';
import UIWindowAttachCustomDomain from './UI/UIWindowAttachCustomDomain.js';
import UIWindowColorPicker from './UI/UIWindowColorPicker.js';
import UIWindowFontPicker from './UI/UIWindowFontPicker.js';
import UIPermissionDialog from './UI/UIPermissionDialog.js';
import UIEnablePushDialog from './UI/UIEnablePushDialog.js';
@@ -485,7 +484,6 @@ const ipc_listener = async (event, handled) => {
is_resizable: event.data.options.is_resizable,
has_head: event.data.options.has_head,
center: event.data.options.center,
show_in_taskbar: event.data.options.show_in_taskbar,
iframe_srcdoc: event.data.options.content,
parent_uuid: event.data.appInstanceID,
});
@@ -1150,9 +1148,9 @@ const ipc_listener = async (event, handled) => {
if ( event.data.y !== undefined ) {
event.data.y = parseFloat(event.data.y);
// we don't want the window to go off the top edge of the screen
if ( event.data.y < window.taskbar_height )
if ( event.data.y < 0 )
{
event.data.y = window.taskbar_height;
event.data.y = 0;
}
// we don't want the window to go off the bottom edge of the screen
if ( event.data.y > window.innerHeight - 100 )
@@ -1218,9 +1216,9 @@ const ipc_listener = async (event, handled) => {
if ( event.data.y !== undefined ) {
event.data.y = parseFloat(event.data.y);
// we don't want the window to go off the top edge of the screen
if ( event.data.y < window.taskbar_height )
if ( event.data.y < 0 )
{
event.data.y = window.taskbar_height;
event.data.y = 0;
}
// we don't want the window to go off the bottom edge of the screen
if ( event.data.y > window.innerHeight - 100 )
@@ -1625,26 +1623,34 @@ const ipc_listener = async (event, handled) => {
return;
}
// set options
if ( typeof event.data.options === 'string' ) {
event.data.options = { defaultColor: event.data.options };
}
event.data.options = event.data.options ?? {};
const options = typeof event.data.options === 'string'
? { defaultColor: event.data.options }
: (event.data.options ?? {});
const requested_color = options.defaultValue ?? options.defaultColor ?? options.default;
// The picker has no alpha, so an 8-digit hex loses its last two digits.
// Anything still not a 3- or 6-digit hex is left out: older builds of
// the picker fail to open on it.
const default_color = typeof requested_color === 'string'
? requested_color.trim().replace(/^(#?[0-9a-f]{6})[0-9a-f]{2}$/i, '$1')
: '';
// Clear window_options for security reasons
event.data.options.window_options = {};
// The same picker puter.js shows outside Puter, so an app gets one
// answer shape everywhere: a 6-digit hex string, or null on cancel.
const picker = document.createElement('puter-color-picker');
if ( /^#?([0-9a-f]{3}|[0-9a-f]{6})$/i.test(default_color) ) picker.setAttribute('default-color', default_color);
const selected_color = await new Promise((resolve) => {
picker.addEventListener('response', (e) => resolve(e.detail ?? null), { once: true });
document.body.appendChild(picker);
picker.open();
});
// Older builds leave the element behind when Escape closes it.
picker.remove();
// Set app as parent window of the font picker window
event.data.options.window_options.parent_uuid = event.data.appInstanceID;
// Open color picker
let selected_color = await UIWindowColorPicker(event.data.options);
// Send selected color to requester window
target_iframe.contentWindow.postMessage({
// The app may have closed while the picker was up.
target_iframe.contentWindow?.postMessage({
msg: 'colorPicked',
original_msg_id: msg_id,
color: selected_color ? selected_color.color : undefined,
color: selected_color,
}, '*');
$(target_iframe).get(0).focus({ preventScroll: true });
}
@@ -41,7 +41,6 @@ vi.mock('./UI/UIPopover.js', stub);
vi.mock('./UI/UIPrompt.js', stub);
vi.mock('./UI/UIWindow.js', stub);
vi.mock('./UI/UIWindowAppFeedback.js', stub);
vi.mock('./UI/UIWindowColorPicker.js', stub);
vi.mock('./UI/UIWindowEmailConfirmationRequired.js', () => ({ default: confirmEmail }));
vi.mock('./UI/UIWindowFontPicker.js', stub);
vi.mock('./UI/UIPermissionDialog.js', stub);
+152
View File
@@ -0,0 +1,152 @@
// @vitest-environment jsdom
/*
* Copyright (C) 2024-present Puter Technologies Inc.
*
* This file is part of Puter.
*
* Puter is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
import jQuery from './lib/jquery-3.6.1/jquery-3.6.1.min.js';
globalThis.def = globalThis.def ?? ((cls) => cls);
globalThis.use = globalThis.use ?? (() => ({}));
globalThis.$ = globalThis.jQuery = jQuery;
globalThis.i18n = (key) => key;
const { stub } = vi.hoisted(() => ({ stub: () => ({ default: () => {} }) }));
vi.mock('./helpers/download.js', stub);
vi.mock('./helpers/itemIcon.js', stub);
vi.mock('./helpers/socialLink.js', stub);
vi.mock('./helpers/updateMousePosition.js', stub);
vi.mock('./UI/UIAlert.js', stub);
vi.mock('./UI/UIContextMenu.js', stub);
vi.mock('./UI/UIItem.js', stub);
vi.mock('./UI/UIPopover.js', stub);
vi.mock('./UI/UIPrompt.js', stub);
vi.mock('./UI/UIWindow.js', stub);
vi.mock('./UI/UIWindowAppFeedback.js', stub);
vi.mock('./UI/UIWindowEmailConfirmationRequired.js', stub);
vi.mock('./UI/UIWindowFontPicker.js', stub);
vi.mock('./UI/UIPermissionDialog.js', stub);
vi.mock('./UI/UIEnablePushDialog.js', stub);
vi.mock('./UI/UIWindowSaveAccount.js', stub);
vi.mock('./UI/Auth/UIAuthSignup.js', stub);
vi.mock('./UI/UINotification.js', stub);
vi.mock('./helpers/godmodeTokens.js', () => ({ renewGodmodeToken: vi.fn() }));
vi.mock('./helpers/watchItems.js', () => ({ addItemWatcher: vi.fn() }));
vi.mock('./helpers/verification_gates.js', () => ({
openVerificationGateWindow: vi.fn(),
}));
// Stands in for puter.js's <puter-color-picker>, which the GUI page gets from
// the SDK: it records how it was opened, and the test answers for the user.
const opened = [];
class FakeColorPicker extends HTMLElement {
open () {
opened.push(this);
}
answer (color) {
this.dispatchEvent(new CustomEvent('response', { detail: color }));
}
}
customElements.define('puter-color-picker', FakeColorPicker);
let iframe;
let posted;
beforeAll(async () => {
window.when_puter_happens = [];
window.appCallbackFunctions = {};
await import('./IPC.js');
globalThis.puter = { services: undefined, util: { rpc: { send: vi.fn() } } };
for (const fn of window.when_puter_happens) await fn();
});
beforeEach(() => {
opened.length = 0;
document.body.innerHTML = '';
const win = document.createElement('div');
win.setAttribute('data-app_uuid', 'app-1');
iframe = document.createElement('iframe');
iframe.setAttribute('data-app', 'notes');
win.append(iframe);
document.body.append(win);
posted = vi.spyOn(iframe.contentWindow, 'postMessage').mockImplementation(() => {});
window.app_instance_ids = new Set(['inst-1']);
window.iframe_for_app_instance = (id) => (id === 'inst-1' ? iframe : null);
window.window_for_app_instance = () => win;
window.is_auth = () => true;
window.ipc_handlers = {};
globalThis.services = { get: () => ({ get_by_uuid: () => ({ name: 'caller', uuid: 'inst-1' }) }) };
});
const request = (options) =>
window.dispatchEvent(
new MessageEvent('message', {
data: { appInstanceID: 'inst-1', env: 'app', msg: 'showColorPicker', uuid: 'cb-1', options },
source: iframe.contentWindow,
origin: 'https://app.example',
}),
);
const settle = () => new Promise((r) => setTimeout(r, 20));
const replies = () => posted.mock.calls
.map(([data]) => data)
.filter((data) => data.msg === 'colorPicked');
describe('showColorPicker', () => {
it.each([
['a string', '#abcdef'],
['defaultColor', { defaultColor: '#abcdef' }],
['the legacy default alias', { default: '#abcdef' }],
['the legacy defaultValue alias', { defaultValue: '#abcdef' }],
['an 8-digit hex, without its alpha', '#abcdef80'],
])('opens the picker on the color given as %s', async (_, options) => {
request(options);
await settle();
expect(opened).toHaveLength(1);
expect(opened[0].getAttribute('default-color')).toBe('#abcdef');
expect(opened[0].isConnected).toBe(true);
});
it.each([
['no color', undefined],
['a color that isn\'t hex', 'red'],
['a malformed hex', '#abcd'],
])('leaves the picker\'s own default when the app gives %s', async (_, options) => {
request(options);
await settle();
expect(opened[0].hasAttribute('default-color')).toBe(false);
});
it('replies with the picked color', async () => {
request('#abcdef');
await settle();
opened[0].answer('#123456');
await settle();
expect(replies()).toEqual([{ msg: 'colorPicked', original_msg_id: 'cb-1', color: '#123456' }]);
expect(opened[0].isConnected).toBe(false);
});
it('replies null when the user cancels', async () => {
request();
await settle();
opened[0].answer(null);
await settle();
expect(replies()).toEqual([{ msg: 'colorPicked', original_msg_id: 'cb-1', color: null }]);
expect(opened[0].isConnected).toBe(false);
});
});
@@ -69,6 +69,7 @@ beforeAll(async () => {
[sessionToken]: { uuid: sessionUser, username: 'session-user' },
'app-token-session-user': { uuid: sessionUser, username: 'session-user' },
'app-token-other-user': { uuid: otherUser, username: 'other-user' },
'app-token-subscriber': { uuid: sessionUser, username: 'session-user', subscribed: true },
};
// The SDK on a sibling subdomain sends credentialed cross-origin requests.
app.use(['/whoami', '/profile', '/rao'], (req, res, next) => {
@@ -513,6 +514,81 @@ describe('embedded app browser', () => {
}
});
it('offers Add credits to an account with a plan, and frames the top-up over the page', async () => {
const context = await menuContext('app-token-subscriber');
try {
const page = await context.newPage();
page.setDefaultTimeout(6000);
await page.goto(`http://spreadsheet.puter.localhost:${port}/menu-host`);
await page.locator('puter-user-menu .avatar').click();
const item = page.locator('puter-user-menu .add-credits');
await item.waitFor();
expect(await item.textContent()).toBe('Add credits');
// Under Usage, in the same row style as the links around it.
expect(await page.locator('puter-user-menu .usage + .add-credits').count()).toBe(1);
expect(await item.evaluate(el => getComputedStyle(el).height))
.toBe(await page.locator('puter-user-menu .feedback').evaluate(el => getComputedStyle(el).height));
await item.click();
const frame = page.locator('dialog.puter-popup-frame iframe');
await frame.waitFor({ state: 'attached' });
expect(await frame.getAttribute('src')).toBe(`${origin}/embed/top-up#user=${sessionUser}`);
expect(await frame.getAttribute('allow')).toBe('payment; otp-credentials');
expect(await page.locator('puter-user-menu .menu').isHidden()).toBe(true);
} finally {
guestApps = [];
await context.close();
}
});
it('returns keyboard focus to the account button when Add credits is chosen', async () => {
const context = await menuContext('app-token-subscriber');
try {
const page = await context.newPage();
page.setDefaultTimeout(6000);
await page.goto(`http://spreadsheet.puter.localhost:${port}/menu-host`);
await page.locator('puter-user-menu .avatar').focus();
await page.keyboard.press('Enter');
await page.locator('puter-user-menu .add-credits').waitFor();
await page.locator('puter-user-menu .add-credits').focus();
await page.keyboard.press('Enter');
await page.locator('dialog.puter-popup-frame iframe').waitFor({ state: 'attached' });
const focused = () => page.evaluate(() => document.activeElement.shadowRoot?.activeElement?.className ?? document.activeElement.tagName);
expect(await focused()).toBe('avatar');
// The dialog hands the focus back when it closes.
const fromFrame = (state) => page.evaluate(([guiOrigin, frameState]) => {
const source = document.querySelector('dialog.puter-popup-frame iframe').contentWindow;
window.dispatchEvent(new MessageEvent('message', {
data: { msg: 'puterPopupFrame', state: frameState }, origin: guiOrigin, source,
}));
}, [origin, state]);
await fromFrame('ready');
expect(await page.locator('dialog.puter-popup-frame').evaluate(el => el.open)).toBe(true);
await fromFrame('closed');
await page.locator('dialog.puter-popup-frame').waitFor({ state: 'detached' });
expect(await focused()).toBe('avatar');
} finally {
guestApps = [];
await context.close();
}
});
it('leaves Add credits out of the menu of an account without a plan', async () => {
const context = await menuContext('app-token-session-user');
try {
const page = await context.newPage();
page.setDefaultTimeout(6000);
await page.goto(`http://spreadsheet.puter.localhost:${port}/menu-host`);
await page.locator('puter-user-menu .avatar').click();
await page.locator('puter-user-menu .usage').waitFor();
expect(await page.locator('puter-user-menu .add-credits').isHidden()).toBe(true);
} finally {
guestApps = [];
await context.close();
}
});
it('closes the account menu when Tab leaves it', async () => {
const context = await menuContext('app-token-session-user');
try {
+19 -2
View File
@@ -20,6 +20,7 @@
import UIWindow from '../UIWindow.js';
import {
openChangeEmailDialog,
openChangeLanguageDialog,
openChangePasswordDialog,
openChangeUsernameDialog,
openCreateTokenDialog,
@@ -141,6 +142,21 @@ const TabAccount = {
h += '</div>';
}
// Language card
const language = window.listSupportedLanguages().find((lang) => lang.code === window.locale);
h += '<div class="dashboard-card dashboard-settings-card">';
h += '<div class="dashboard-settings-card-content">';
h += '<div class="dashboard-settings-card-icon">';
h += '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><path d="M2 12h20"/><path d="M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"/></svg>';
h += '</div>';
h += '<div class="dashboard-settings-card-info">';
h += `<strong>${i18n('language')}</strong>`;
h += `<span>${html_encode(language?.name ?? window.locale)}</span>`;
h += '</div>';
h += '</div>';
h += `<button class="button change-language">${i18n('change_language')}</button>`;
h += '</div>';
// API token card
h += '<div class="dashboard-card dashboard-settings-card">';
h += '<div class="dashboard-settings-card-content">';
@@ -213,6 +229,9 @@ const TabAccount = {
$el_window.find('.dashboard-section-account .change-email').on('click', function () {
openChangeEmailDialog(dialogOptions(this));
});
$el_window.find('.dashboard-section-account .change-language').on('click', function () {
openChangeLanguageDialog(dialogOptions(this));
});
$el_window.find('.dashboard-section-account .copy-auth-token').on('click', function () {
openCreateTokenDialog({ ...dialogOptions(this), $sessionsParent: $el_window });
});
@@ -251,8 +270,6 @@ const TabAccount = {
function showProfilePicture (picture) {
const url = picture ?? window.icons['profile.svg'];
$('.profile-pic').css('background-image', `url(${ html_encode(url) })`);
$('.profile-image').css('background-image', `url(${ html_encode(url) })`);
$('.profile-image').toggleClass('profile-image-has-picture', !! picture);
}
// A save started after another one owns the avatar and the hint; the
// earlier one's answer must not put its picture (or a failure) back.
-19
View File
@@ -296,25 +296,6 @@ const TabHome = {
h += '</div>';
h += '</div>';
// Open Desktop card (spans full width, links to the desktop interface)
h +=
'<a href="/desktop" target="_blank" rel="noopener" class="bento-card bento-desktop allow-native-ctxmenu">';
h +=
'<div class="bento-card-fancy-icon bento-card-fancy-icon-desktop">';
h +=
'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8"><rect x="2" y="3" width="20" height="14" rx="2"/><line x1="8" y1="21" x2="16" y2="21"/><line x1="12" y1="17" x2="12" y2="21"/></svg>';
h += '</div>';
h += '<div class="bento-card-fancy-text">';
h += `<h2>${i18n('open_desktop')}</h2>`;
h += '<span class="bento-card-fancy-subtitle">';
h +=
'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="5" y1="12" x2="19" y2="12"/><polyline points="12 5 19 12 12 19"/></svg>';
h += i18n('open_desktop_hint');
h += '</span>';
h += '</div>';
h += '<span class="bento-desktop-arrow">›</span>';
h += '</a>';
h += '</div>';
return h;
},
+32 -9
View File
@@ -19,7 +19,7 @@
import { formatCount, formatCredits, formatDollarsFromMicrocents, usageIsCredits } from './credits.js';
import { isOrgSeat } from './orgSeat.js';
import { addonCreditsRemaining, meterPercent, monthlyUsageOrThrow, usageBudget } from './usageBudget.js';
import { addonCreditsBudget, addonCreditsRemaining, meterPercent, monthlyUsageOrThrow, usageBudget } from './usageBudget.js';
import { getMonthlyUsage, getStorageSpace } from './usageRequests.js';
// Whether the server reported credits — decides whether the usage surfaces
@@ -67,7 +67,7 @@ const TabUsage = {
</div>
<div class="driver-usage-container" style="margin-top: 30px;">
<div class="driver-usage-header">
<h3 style="margin:0; font-size: 14px; flex-grow: 1; font-weight: 500;">${i18n('Resources')}</h3>
<h3 style="margin:0; font-size: 14px; flex-grow: 1; font-weight: 500;">${i18n('monthly_credits_title')}</h3>
<div style="font-size: 13px; margin-bottom: 3px; opacity:0.85;">
<span class="usage-progbar-percent">--%</span>
<span> &middot; </span>
@@ -77,10 +77,22 @@ const TabUsage = {
<div class="usage-progbar-wrapper">
<div class="usage-progbar" style="width: 0;"></div>
</div>
<p class="usage-addon-credits" style="display: none;">
<span class="usage-addon-left"></span>
<span class="usage-addon-note">&middot; ${i18n('addon_credits_note')}</span>
</p>
<div class="usage-addon" style="display: none;">
<div class="driver-usage-header">
<h3 id="usage-addon-title" style="margin:0; font-size: 14px; flex-grow: 1; font-weight: 500;">${i18n('addon_credits')}</h3>
<div style="font-size: 13px; margin-bottom: 3px; opacity:0.85;">
<span class="usage-addon-percent">--%</span>
<span> &middot; </span>
${i18n('used_of', { used: '<span class="usage-addon-used">--</span>', available: '<span class="usage-addon-capacity">--</span>' }, false)}
</div>
</div>
<div class="usage-progbar-wrapper" role="progressbar" aria-labelledby="usage-addon-title" aria-valuemin="0" aria-valuemax="100">
<div class="usage-addon-bar" style="width: 0;"></div>
</div>
<p class="usage-addon-credits">
<span class="usage-addon-note">${i18n('addon_credits_note')}</span>
</p>
</div>
<h3 style="margin:15px 0 10px 0; font-size: 14px; font-weight: 500;">${i18n('usage_details')}</h3>
<div class="driver-usage-details-content visible">
</div>
@@ -330,9 +342,20 @@ async function update_usage_details ($el_window) {
'background-color': window.usage_bar_color(budget.barPercent),
});
$('.usage-addon-credits').toggle(addonLeft !== null);
if ( addonLeft !== null ) {
$('.usage-addon-left').html(i18n('addon_credits_available', { amount: amount(addonLeft) }));
// Its own meter under the monthly one, for an account that has ever had any.
const addon = addonCreditsBudget(res.allowanceInfo);
$('.usage-addon').toggle(addon !== null);
if ( addon !== null ) {
$('.usage-addon-used').html(amount(addon.used));
$('.usage-addon-capacity').html(amount(addon.capacity));
$('.usage-addon-percent').html(`${addon.percent}%`);
$('.usage-addon-bar').css({
width: `${addon.barPercent}%`,
'background-color': window.usage_bar_color(addon.barPercent),
}).parent().attr({
'aria-valuenow': addon.percent,
'aria-valuetext': `${addon.percent}%`,
});
}
// Store raw data for sorting
@@ -25,6 +25,7 @@ import check_password_strength from '../../helpers/checkPasswordStrength.js';
import create_access_token from '../../helpers/createAccessToken.js';
import postUserProtected from '../../helpers/postUserProtected.js';
import update_username_in_gui from '../../helpers/updateUsernameInGui.js';
import changeLanguage from '../../i18n/i18nChangeLanguage.js';
import UIWindowManageSessions from '../UIWindowManageSessions.js';
import UIDashboardFormDialog, { copyRowHtml } from './UIDashboardFormDialog.js';
@@ -119,6 +120,42 @@ export function openEditProfileDialog ({ onSave, ...opts } = {}) {
});
}
/**
* Changes the language Puter is shown in, then reloads the page in it.
*
* @param {AccountDialogOptions} [opts]
*/
export function openChangeLanguageDialog (opts = {}) {
return UIDashboardFormDialog({
...opts,
title: t('change_language'),
submitLabel: t('save'),
fields: [
{
name: 'language',
type: 'select',
label: i18n('language'),
value: window.locale,
options: window.listSupportedLanguages().map((lang) => ({
value: lang.code,
label: html_encode(lang.name),
})),
},
],
async onSubmit (dialog) {
const { language } = dialog.values();
if ( language === window.locale ) {
dialog.close();
return;
}
// On success the page reloads, so the dialog stays in progress.
if ( ! await changeLanguage(language) ) {
dialog.setStatus(t('language_save_failed'), { field: 'language' });
}
},
});
}
/**
* Changes the signed-in user's username.
*
@@ -293,6 +293,57 @@ describe('create API token', () => {
});
});
describe('change language', () => {
beforeEach(() => {
window.locale = 'en';
window.listSupportedLanguages = () => [
{ code: 'en', name: 'English' },
{ code: 'de', name: 'Deutsch' },
{ code: 'ja', name: '日本語' },
];
window.mutate_user_preferences = vi.fn();
globalThis.puter.kv = { set: vi.fn(async () => true) };
});
it('lists every language by its own name, with the current one selected', () => {
dialogs.openChangeLanguageDialog();
const options = field('language').find('option').map((_, el) => [[el.value, el.textContent]]).get();
expect(options).toEqual([['en', 'English'], ['de', 'Deutsch'], ['ja', '日本語']]);
expect(field('language').val()).toBe('en');
});
it('closes without saving when the language is unchanged', async () => {
dialogs.openChangeLanguageDialog();
await submitWith({ language: 'en' });
expect(puter.kv.set).not.toHaveBeenCalled();
expect(isOpen()).toBe(false);
});
it('saves the picked language to the account', async () => {
dialogs.openChangeLanguageDialog();
await submitWith({ language: 'de' });
expect(puter.kv.set).toHaveBeenCalledWith('user_preferences.language', 'de');
expect(window.mutate_user_preferences).toHaveBeenCalledWith({ language: 'de' });
expect(status()).toBe('');
});
it('stays open with an error when the save fails', async () => {
puter.kv.set.mockRejectedValue(new Error('offline'));
vi.spyOn(console, 'warn').mockImplementation(() => {});
dialogs.openChangeLanguageDialog();
await submitWith({ language: 'de' });
expect(window.mutate_user_preferences).not.toHaveBeenCalled();
expect(status()).toBe('language_save_failed');
expect(isOpen()).toBe(true);
});
});
describe('delete account', () => {
it('asks a temporary account to type confirm', async () => {
// What the server sends for a temporary account: no password, so `oidc_only` too.
+1 -2
View File
@@ -75,8 +75,7 @@ async function UIDashboard (options) {
// eslint-disable-next-line no-unused-vars
options = options ?? {};
// Mark dashboard mode on <body> so window chrome can adapt — e.g. app
// windows keep their minimize button even though fullpage-mode hides it.
// Mark dashboard mode on <body> so window chrome and notifications can adapt.
$('body').addClass('dashboard-mode');
// Create mutable tabs array from built-in tabs
+6 -8
View File
@@ -109,10 +109,9 @@ const count_label = (count) => (count === 1
: i18n('items_count_other', { count }));
/**
* A responsive, from-scratch sharing modal for the Dashboard's Files tab.
* Unlike UIWindowShare (which spawns a desktop UIWindow), this renders a
* self-contained overlay that behaves as a centered card on desktop and a
* bottom sheet on mobile, styled with the dashboard's design tokens.
* A responsive sharing modal for the Dashboard's Files tab: a self-contained
* overlay that behaves as a centered card on desktop and a bottom sheet on
* mobile, styled with the dashboard's design tokens.
*
* Shares one item or a whole selection. With several items the access list is
* one row per person folded across them ({@link aggregateShares}), so every
@@ -120,10 +119,9 @@ const count_label = (count) => (count === 1
* rather than a chore repeated per file. A person who holds only some of the
* selection says so, and can be extended to the rest in one click.
*
* Feature-equivalent to UIWindowShare: grant access by email or username,
* list who has access (owner, direct grants, grants inherited from an
* ancestor folder), change a grant's mode, and revoke — with the revoke
* confirmation inlined into the row instead of a stacked alert window.
* Grants access by email or username, lists who has access (owner, direct
* grants, grants inherited from an ancestor folder), changes a grant's mode,
* and revokes, with the revoke confirmation inlined into the row.
*
* @param {Object} opts
* @param {Array<Object>} [opts.items] - The items to share, each
@@ -221,7 +221,7 @@ describe('aggregateShares', () => {
it('falls back to the handle, then the uid, for an unnamed team', () => {
// Whatever team_label says, so a team reads the same here as it does
// in the desktop dialog's access list.
// in the recipient suggestions.
const named = (team) => aggregateShares(['/me/a'], new Map([
['/me/a', [grant(null, 'read', { holderTeam: team })]],
]))[0].name;
+24 -2
View File
@@ -30,8 +30,8 @@ export const meterPercent = (share) => (share < 100 ? Math.min(99, Math.round(sh
/**
* @typedef {Object} UsageBudget
* @property {number} used - Allowance-charged spend, in the server's units.
* @property {number} capacity - The monthly plan allowance.
* @property {number} used - Spend charged to it, in the server's units.
* @property {number} capacity - What the meter is out of: the monthly plan allowance, or the add-on credit bought.
* @property {number} percent - `used` as a whole-number share of `capacity`.
* @property {number} barPercent - The share clamped to 0-100, for a bar width.
*/
@@ -83,6 +83,28 @@ export const addonCreditsRemaining = (allowanceInfo) => {
return Math.max(0, purchased - nonNegative(addons.consumedPurchaseCredits));
};
/**
* The add-on credit meter: what has been spent of all the add-on credit the
* account ever bought. Null when it has never had any, as there is no pool
* to meter.
*
* @param {Object | null | undefined} allowanceInfo
* @returns {UsageBudget | null}
*/
export const addonCreditsBudget = (allowanceInfo) => {
const left = addonCreditsRemaining(allowanceInfo);
if ( left === null ) return null;
const capacity = nonNegative(allowanceInfo.addons.purchasedCredits);
const used = capacity - left;
const share = (used / capacity) * 100;
return {
used,
capacity,
percent: meterPercent(share),
barPercent: Math.max(0, Math.min(100, share)),
};
};
/**
* `getMonthlyUsage()` resolves with whatever body the server answered, an
* error included. Throws unless that body is a usage report, so a failed
+36 -1
View File
@@ -18,7 +18,7 @@
*/
import { describe, expect, it } from 'vitest';
import { addonCreditsRemaining, meterPercent, monthlyUsageOrThrow, usageBudget } from './usageBudget.js';
import { addonCreditsBudget, addonCreditsRemaining, meterPercent, monthlyUsageOrThrow, usageBudget } from './usageBudget.js';
const info = (allowance, addons = {}) => ({
monthUsageAllowance: allowance,
@@ -148,6 +148,41 @@ describe('addonCreditsRemaining', () => {
});
});
describe('addonCreditsBudget', () => {
it('has no meter for an account that never had add-on credit', () => {
expect(addonCreditsBudget(info(900_000_000))).toBeNull();
expect(addonCreditsBudget(info(900_000_000, { purchasedCredits: 0 }))).toBeNull();
expect(addonCreditsBudget(undefined)).toBeNull();
});
it('meters what was spent of the credit bought', () => {
expect(addonCreditsBudget(info(900_000_000, {
purchasedCredits: 2_500,
consumedPurchaseCredits: 850,
}))).toEqual({ used: 850, capacity: 2_500, percent: 34, barPercent: 34 });
});
it('starts empty when nothing has been spent, or the spend is unreadable', () => {
expect(addonCreditsBudget(info(0, { purchasedCredits: 1_000 })))
.toEqual({ used: 0, capacity: 1_000, percent: 0, barPercent: 0 });
expect(addonCreditsBudget(info(0, { purchasedCredits: 1_000, consumedPurchaseCredits: NaN })).used).toBe(0);
});
it('reads full, never past it, once the pool is spent', () => {
expect(addonCreditsBudget(info(0, {
purchasedCredits: 1_000,
consumedPurchaseCredits: 1_200,
}))).toEqual({ used: 1_000, capacity: 1_000, percent: 100, barPercent: 100 });
});
it('holds at 99% while any credit is left', () => {
expect(addonCreditsBudget(info(0, {
purchasedCredits: 100_000,
consumedPurchaseCredits: 99_999,
})).percent).toBe(99);
});
});
describe('monthlyUsageOrThrow', () => {
it('passes a usage report through', () => {
const res = { usage: { total: 0 }, allowanceInfo: null };
@@ -79,7 +79,6 @@ async function UIWindowDisable2FA (options) {
width: 350,
height: 'auto',
dominant: true,
show_in_taskbar: false,
on_before_exit: async () => {
if ( ! disabled_successfully ) {
promise.resolve(false);
-1
View File
@@ -136,7 +136,6 @@ function UIAlert (options) {
selectable_body: false,
draggable_body: options.draggable_body ?? true,
allow_context_menu: false,
show_in_taskbar: false,
window_class: 'window-alert',
dominant: true,
body_content: h,
-243
View File
@@ -1,243 +0,0 @@
/*
* Copyright (C) 2024-present Puter Technologies Inc.
*
* This file is part of Puter.
*
* Puter is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
/**
* Creates a reusable color picker widget using iro.ColorPicker
* @param {HTMLElement|jQuery} container - Container element for the color picker
* @param {Object} options - Configuration options
* @param {string} options.default - Default color in hex format (e.g., "#f00" or "#ff0000ff")
* @param {Object} options.layout - Custom layout configuration for iro.ColorPicker
* @param {Function} options.onColorChange - Callback function called when color changes
* @returns {Object} Color picker instance with methods to interact with it
*/
export function UIColorPickerWidget (container, options = {}) {
// Get the DOM element if it's a jQuery object
const domElement = container instanceof HTMLElement
? container
: $(container).get(0);
if ( ! domElement ) {
throw new Error('Container element is required');
}
// Default layout configuration
const defaultLayout = [
{
component: iro.ui.Box,
options: {
layoutDirection: 'horizontal',
width: 265,
height: 265,
},
},
{
component: iro.ui.Slider,
options: {
sliderType: 'alpha',
layoutDirection: 'horizontal',
height: 265,
width: 265,
},
},
{
component: iro.ui.Slider,
options: {
sliderType: 'hue',
},
},
];
// Initialize the color picker
const colorPicker = new iro.ColorPicker(domElement, {
layout: options.layout ?? defaultLayout,
color: options.default ?? '#f00',
});
// Set up color change callback if provided
if ( options.onColorChange ) {
colorPicker.on('color:change', (color) => {
options.onColorChange(color);
});
}
return {
/**
* Get the current color
* @returns {Object} iro.Color object
*/
getColor: () => colorPicker.color,
/**
* Get the current color as hex8 string (includes alpha)
* @returns {string} Color in hex8 format (e.g., "#ff0000ff")
*/
getHex8String: () => colorPicker.color.hex8String,
/**
* Get the current color as hex string (no alpha)
* @returns {string} Color in hex format (e.g., "#ff0000")
*/
getHexString: () => colorPicker.color.hexString,
/**
* Get the current color as HSLA object
* @returns {Object} Object with h, s, l, a properties
*/
getHSLA: () => {
const color = colorPicker.color;
return color.hsla;
},
/**
* Set the color
* @param {string|Object} color - Color in hex format (e.g., "#f00" or "#ff0000ff") or HSLA object
*/
setColor: (color) => {
if ( typeof color === 'string' ) {
// Remove # if present for matching
const hexValue = color.startsWith('#') ? color.substring(1) : color;
// Check if it's a hex8 string (8 hex digits)
if ( /^[0-9a-fA-F]{8}$/.test(hexValue) ) {
// It's a hex8 string, set both hex and alpha
const hex6 = `#${ hexValue.substring(0, 6)}`; // Get first 6 hex digits
const alphaHex = hexValue.substring(6, 8); // Get last 2 hex digits (alpha)
colorPicker.color.hexString = hex6;
colorPicker.color.alpha = parseInt(alphaHex, 16) / 255;
} else {
// Regular hex string (with or without #)
colorPicker.color.hexString = color.startsWith('#') ? color : `#${ color}`;
}
} else if ( typeof color === 'object' && color.h !== undefined ) {
// HSLA object - set properties directly
colorPicker.color.hue = color.h;
colorPicker.color.saturation = color.s;
colorPicker.color.lightness = color.l;
colorPicker.color.alpha = color.a !== undefined ? color.a : 1;
}
},
/**
* Add an event listener
* @param {string} event - Event name (e.g., 'color:change')
* @param {Function} callback - Callback function
*/
on: (event, callback) => {
colorPicker.on(event, callback);
},
/**
* Remove an event listener
* @param {string} event - Event name
* @param {Function} callback - Callback function
*/
off: (event, callback) => {
colorPicker.off(event, callback);
},
/**
* Get the underlying iro.ColorPicker instance
* @returns {iro.ColorPicker} The iro.ColorPicker instance
*/
getPicker: () => colorPicker,
};
}
/**
* Converts HSLA values to hex8 string
* @param {number} h - Hue (0-360)
* @param {number} s - Saturation (0-100)
* @param {number} l - Lightness (0-100)
* @param {number} a - Alpha (0-1)
* @returns {string} Color in hex8 format
*/
export function hslaToHex8 (h, s, l, a) {
// Convert HSL to RGB
s /= 100;
l /= 100;
const c = (1 - Math.abs(2 * l - 1)) * s;
const x = c * (1 - Math.abs((h / 60) % 2 - 1));
const m = l - c / 2;
let r = 0, g = 0, b = 0;
if ( h >= 0 && h < 60 ) {
r = c; g = x; b = 0;
} else if ( h >= 60 && h < 120 ) {
r = x; g = c; b = 0;
} else if ( h >= 120 && h < 180 ) {
r = 0; g = c; b = x;
} else if ( h >= 180 && h < 240 ) {
r = 0; g = x; b = c;
} else if ( h >= 240 && h < 300 ) {
r = x; g = 0; b = c;
} else if ( h >= 300 && h < 360 ) {
r = c; g = 0; b = x;
}
r = Math.round((r + m) * 255);
g = Math.round((g + m) * 255);
b = Math.round((b + m) * 255);
const alpha = Math.round(a * 255);
return `#${[r, g, b, alpha].map(x => {
const hex = x.toString(16);
return hex.length === 1 ? `0${ hex}` : hex;
}).join('')}`;
}
/**
* Converts hex8 string to HSLA object
* @param {string} hex8 - Color in hex8 format (e.g., "#ff0000ff")
* @returns {Object} Object with h, s, l, a properties
*/
export function hex8ToHSLA (hex8) {
// Remove # if present
hex8 = hex8.replace('#', '');
// Parse hex values
const r = parseInt(hex8.substring(0, 2), 16) / 255;
const g = parseInt(hex8.substring(2, 4), 16) / 255;
const b = parseInt(hex8.substring(4, 6), 16) / 255;
const a = parseInt(hex8.substring(6, 8), 16) / 255;
// Convert RGB to HSL
const max = Math.max(r, g, b);
const min = Math.min(r, g, b);
let h, s, l = (max + min) / 2;
if ( max === min ) {
h = s = 0; // achromatic
} else {
const d = max - min;
s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
switch ( max ) {
case r: h = ((g - b) / d + (g < b ? 6 : 0)) / 6; break;
case g: h = ((b - r) / d + 2) / 6; break;
case b: h = ((r - g) / d + 4) / 6; break;
}
}
return {
h: Math.round(h * 360),
s: Math.round(s * 100),
l: Math.round(l * 100),
a: a,
};
}
+2 -5
View File
@@ -568,9 +568,9 @@ function UIContextMenu (options) {
// Y position
// is the menu going to go out of the window from the bottom?
if ( (start_y + menu_height) > (window.innerHeight - window.taskbar_height - 10) )
if ( (start_y + menu_height) > (window.innerHeight - 10) )
{
y_pos = window.innerHeight - menu_height - window.taskbar_height - 10;
y_pos = window.innerHeight - menu_height - 10;
}
else
{
@@ -801,9 +801,6 @@ function UIContextMenu (options) {
$(options.parent_element).css('overflow', 'scroll');
$(options.parent_element).removeClass('has-open-contextmenu');
if ( $(options.parent_element).hasClass('taskbar-item') ) {
window.make_taskbar_sortable();
}
}
});
File diff suppressed because it is too large. Load diff
+42 -100
View File
@@ -18,21 +18,17 @@
*/
import UIWindowItemProperties from './UIWindowItemProperties.js';
import ensureConfirmedEmail from '../helpers/ensureConfirmedEmail.js';
import UIPopover from './UIPopover.js';
import UIContextMenu from './UIContextMenu.js';
import UIAlert from './UIAlert.js';
import UIWindowPublishWorker from './UIWindowPublishWorker.js';
import UIWindowShare from './UIWindowShare.js';
import path from '../lib/path.js';
import truncate_filename from '../helpers/truncateFilename.js';
import launch_app from '../helpers/launchApp.js';
import open_item from '../helpers/openItem.js';
import publish_as_website from '../helpers/publishAsWebsite.js';
import mime from '../lib/mime.js';
import { isWeblinkName, weblinkChangeIconMenuItem } from '../helpers/weblink.js';
import { is_owned_by_me } from '../helpers/pathOwner.js';
import { can_rename, can_restructure, invalidate_shared_roots, shared_mode_for } from '../helpers/sharedAccess.js';
import { can_rename, can_restructure, invalidate_shared_roots } from '../helpers/sharedAccess.js';
import { is_default_app } from '../helpers/defaultApp.js';
import openWithAI from '../helpers/openWithAI.js';
import refresh_item_container from '../helpers/refreshItemContainer.js';
@@ -329,7 +325,6 @@ async function UIItem (options) {
last_window_dragged_over = null;
window.an_item_is_being_dragged = true;
$('.toolbar').css('pointer-events', 'none');
},
drag: function (event, ui) {
// Constrain item within desktop bounds
@@ -396,7 +391,7 @@ async function UIItem (options) {
// do not highlight if the target is the same as the item being moved
$(el_item).attr('data-path') !== $(window.mouseover_item_container).attr('data-path') &&
// do not highlight if item is being moved to where it already is
$(el_item).attr('data-path') !== $(window.mouseover_item_container).attr('data-path') ) {
path.dirname($(el_item).attr('data-path')) !== $(window.mouseover_item_container).attr('data-path') ) {
// highlight item container
$(window.mouseover_item_container).addClass('item-container-active');
@@ -416,10 +411,11 @@ async function UIItem (options) {
},
stop: function (event, ui) {
// Allow rearranging only if item is on desktop, not trash container, auto arrange is disabled and item is not dropped into another item
if ( $(el_item).closest('.item-container').attr('data-path') === window.desktop_path &&
// the desktop itself, not a window showing the Desktop folder
if ( $(el_item).closest('.item-container').hasClass('desktop') &&
!window.is_auto_arrange_enabled && $(el_item).attr('data-path') !== window.trash_path && !ui.helper.data('dropped') &&
// Item must be dropped on the Desktop and not on the taskbar
window.mouseover_window === undefined && ui.position.top <= window.desktop_height - window.taskbar_height - 15 ) {
// .desktop clips its overflow, so the whole item has to fit above the bottom edge
window.mouseover_window === undefined && ui.position.top + $(el_item).outerHeight(true) <= window.desktop_height ) {
el_item.style.position = 'absolute';
el_item.style.left = `${ui.position.left }px`;
@@ -434,12 +430,13 @@ async function UIItem (options) {
// re-enable all droppable UIItems that are not a dir
$('.item[data-is_dir=\'0\']:not(.item-selected)').droppable('enable');
// remove active item-container border highlights
$('.item-container').removeClass('item-container-active');
$('.item-container').removeClass('item-container-active item-container-transparent-border');
// a drop that bailed out early never re-enables the containers an item's hover disabled
$('.item-container.ui-droppable').droppable('enable');
// reset longer hover timeout and last window dragged over
clearTimeout(longer_hover_timeout);
last_window_dragged_over = null;
window.an_item_is_being_dragged = false;
$('.toolbar').css('pointer-events', 'auto');
},
});
@@ -548,11 +545,14 @@ async function UIItem (options) {
}
// Otherwise, move items
else if ( options.is_dir ) {
// a selected folder can be the drop target of its own selection; it stays where it is
const items_to_drop = items_to_move.filter(item => $(item).attr('data-uid') !== $(el_item).attr('data-uid'));
if ( $(el_item).closest('.item-container').attr('data-path') === window.desktop_path ) {
delete window.desktop_item_positions[$(el_item).attr('data-uid')];
// the items leaving the desktop lose their saved positions, not the folder they land in
items_to_drop.forEach(item => delete window.desktop_item_positions[$(item).attr('data-uid')]);
window.save_desktop_item_positions();
}
window.move_items(items_to_move, $(el_item).attr('data-shortcut_to_path') !== '' ? $(el_item).attr('data-shortcut_to_path') : $(el_item).attr('data-path'));
window.move_items(items_to_drop, $(el_item).attr('data-shortcut_to_path') !== '' ? $(el_item).attr('data-shortcut_to_path') : $(el_item).attr('data-path'));
}
}
@@ -563,8 +563,9 @@ async function UIItem (options) {
},
over: function (event, ui) {
// Check hovering over an item that is VISIBILE
// A desktop item has no window, so it only counts while the pointer is over the desktop itself
const $event_parent_win = $(event.target).closest('.window');
if ( $event_parent_win.length > 0 && $event_parent_win.attr('data-id') !== $(window.mouseover_window).attr('data-id') )
if ( $event_parent_win.attr('data-id') !== $(window.mouseover_window).attr('data-id') )
{
return;
}
@@ -722,7 +723,7 @@ async function UIItem (options) {
}
});
$(document).on('click', function (e) {
$(document).on(`click.item-${item_id}`, function (e) {
if ( !$(e.target).hasClass('item') && !$(e.target).hasClass('item-name') && !$(e.target).hasClass('item-icon') ) {
skip_a_rename_click = true;
}
@@ -731,6 +732,10 @@ async function UIItem (options) {
skip_a_rename_click = true;
}
});
// a document handler outlives the row unless it is released with it
$(el_item).on('remove', function () {
$(document).off(`click.item-${item_id}`);
});
// --------------------------------------------------------
// Rename
@@ -738,6 +743,7 @@ async function UIItem (options) {
function rename () {
if ( rename_cancelled ) {
rename_cancelled = false;
$(el_item_name_editor).removeClass('item-name-editor-active');
return;
}
@@ -757,10 +763,12 @@ async function UIItem (options) {
UIAlert('The name ".." is not allowed, because it is a reserved name. Please choose another name.');
}
$(el_item_name).html(html_encode(truncate_filename(options.name)));
$(el_item_name).html(html_encode(truncate_filename($(el_item).attr('data-name'))));
$(el_item_name).show();
$(el_item_name_editor).val($(el_item).attr('data-name'));
$(el_item_name_editor).hide();
// the Delete shortcut skips an item whose editor is marked active
$(el_item_name_editor).removeClass('item-name-editor-active');
return;
}
// deactivate item name editable
@@ -806,8 +814,9 @@ async function UIItem (options) {
e.stopPropagation();
e.preventDefault();
rename_cancelled = true;
$(el_item_name_editor).removeClass('item-name-editor-active');
$(el_item_name_editor).hide();
$(el_item_name_editor).val(options.name);
$(el_item_name_editor).val($(el_item).attr('data-name'));
$(el_item_name).show();
}
});
@@ -866,6 +875,11 @@ async function UIItem (options) {
return;
}
// The menu is built after lookups that take time, so it opens where the pointer was when it was asked for.
const menu_position = (isMobile.phone || isMobile.tablet)
? { left: window.last_touch_x, top: window.last_touch_y }
: { left: window.mouseX, top: window.mouseY };
// if editing item name, preserve native context menu
if ( event.target === el_item_name_editor )
{
@@ -1079,11 +1093,6 @@ async function UIItem (options) {
// Someone else's, however we got here — including items reached by
// opening a shared folder, which carry no share markers.
const is_not_mine = !is_owned_by_me($(el_item).attr('data-path'));
// `manage` inherits downwards, so a file inside a folder you manage
// counts too — the row itself only carries a mode at a shared root.
const can_manage_share =
$(el_item).attr('data-share_mode') === 'manage'
|| (await shared_mode_for($(el_item).attr('data-path'))) === 'manage';
// Moving and deleting go by the holding folder, not by the item.
const may_restructure = !is_not_mine
|| await can_restructure($(el_item).attr('data-path'));
@@ -1137,7 +1146,7 @@ async function UIItem (options) {
// try to find suitable apps
const suitable_apps = await window.suggest_apps_for_fsentry({
uid: options.uid,
path: options.path,
path: $(el_item).attr('data-path'),
});
if ( suitable_apps && suitable_apps.length > 0 ) {
options.suggested_apps = suitable_apps;
@@ -1249,19 +1258,6 @@ async function UIItem (options) {
});
}
//-------------------------------------------
// Publish as Worker
// -------------------------------------------
// The backend refuses deploys from a file someone else owns.
if ( !is_trashed && !is_trash && !is_not_mine && !options.is_dir && $(el_item).attr('data-name').toLowerCase().endsWith('.js') ) {
menu_items.push({
html: i18n('publish_as_serverless_worker'),
onClick: async function () {
if ( ! await ensureConfirmedEmail(i18n('save_account_to_publish')) ) return;
UIWindowPublishWorker(options.uid, $(el_item).attr('data-name'), $(el_item).attr('data-path'));
},
});
}
// -------------------------------------------
// Deploy As App
// -------------------------------------------
@@ -1275,7 +1271,7 @@ async function UIItem (options) {
file_path: $(el_item).attr('data-path'),
file_uid: $(el_item).attr('data-uid'),
params: {
source_path: options.path,
source_path: $(el_item).attr('data-path'),
},
});
},
@@ -1295,20 +1291,6 @@ async function UIItem (options) {
});
}
// -------------------------------------------
// Share
// -------------------------------------------
if ( !is_trash && !is_trashed && (!is_not_mine || can_manage_share) ) {
menu_items.push({
html: i18n('share_ellipsis'),
onClick: async function () {
UIWindowShare({
path: $(el_item).attr('data-path'),
name: $(el_item).attr('data-name'),
});
},
});
}
// -------------------------------------------
// Download
// -------------------------------------------
if ( !is_trash && !is_trashed && (options.associated_app_name === null || options.associated_app_name === undefined) ) {
@@ -1322,49 +1304,7 @@ async function UIItem (options) {
}
else
{
window.trigger_download([options.path]);
}
},
});
}
// -------------------------------------------
// Set as Wallpaper
// -------------------------------------------
const mime_type = mime.getType($(el_item).attr('data-name')) ??
'application/octet-stream';
if ( !is_trashed && !is_trash && !options.is_dir && mime_type.startsWith('image/') ) {
menu_items.push({
html: i18n('set_as_background'),
onClick: async function () {
const read_url = await puter.fs.sign(undefined, { uid: $(el_item).attr('data-uid'), action: 'read' });
window.set_desktop_background({
url: read_url.items.read_url,
fit: window.desktop_bg_fit,
});
try {
$.ajax({
url: `${window.api_origin }/set-desktop-bg`,
type: 'POST',
data: JSON.stringify({
url: window.desktop_bg_url,
color: window.desktop_bg_color,
fit: window.desktop_bg_fit,
}),
async: true,
contentType: 'application/json',
headers: {
'Authorization': `Bearer ${window.auth_token}`,
},
statusCode: {
401: function (xhr) {
window.handle401(xhr);
},
},
});
$(el_window).close();
resolve(true);
} catch ( err ) {
// Ignore
window.trigger_download([$(el_item).attr('data-path')]);
}
},
});
@@ -1437,12 +1377,13 @@ async function UIItem (options) {
// -------------------------------------------
// Cut
// -------------------------------------------
if ( $(el_item).attr('data-immutable') === '0' ) {
// Trashed items leave the Trash through Restore; moved any other way, they'd keep their uid as their name.
if ( $(el_item).attr('data-immutable') === '0' && !is_trashed && may_restructure ) {
menu_items.push({
html: i18n('cut'),
onClick: function () {
window.clipboard_op = 'move';
window.clipboard = [options.path];
window.clipboard = [$(el_item).attr('data-path')];
},
});
}
@@ -1454,7 +1395,7 @@ async function UIItem (options) {
html: i18n('copy'),
onClick: function () {
window.clipboard_op = 'copy';
window.clipboard = [{ path: options.path }];
window.clipboard = [{ path: $(el_item).attr('data-path') }];
},
});
}
@@ -1502,7 +1443,7 @@ async function UIItem (options) {
base_dir,
options.appendTo,
options.shortcut_to === '' ? options.uid : options.shortcut_to,
options.shortcut_to_path === '' ? options.path : options.shortcut_to_path,
options.shortcut_to_path === '' ? $(el_item).attr('data-path') : options.shortcut_to_path,
);
},
});
@@ -1613,7 +1554,7 @@ async function UIItem (options) {
left = left > (window.innerWidth - window_width) ? (window.innerWidth - window_width) : left;
let top = $(el_item).position().top + $(el_item).height();
top = top > (window.innerHeight - (window_height + window.taskbar_height + window.toolbar_height)) ? (window.innerHeight - (window_height + window.taskbar_height + window.toolbar_height)) : top;
top = top > (window.innerHeight - (window_height + window.toolbar_height)) ? (window.innerHeight - (window_height + window.toolbar_height)) : top;
UIWindowItemProperties(
$(el_item).attr('data-name'),
@@ -1631,6 +1572,7 @@ async function UIItem (options) {
// Create ContextMenu
UIContextMenu({
parent_element: ($(options.appendTo).hasClass('desktop') ? undefined : options.appendTo),
position: menu_position,
items: menu_items,
});
+88 -2
View File
@@ -27,8 +27,6 @@ vi.mock('./UIPopover.js', () => ({ default: vi.fn() }));
vi.mock('./UIWindowEmailConfirmationRequired.js', () => ({ default: vi.fn() }));
vi.mock('./UIContextMenu.js', () => ({ default: vi.fn() }));
vi.mock('./UIAlert.js', () => ({ default: vi.fn() }));
vi.mock('./UIWindowPublishWorker.js', () => ({ default: vi.fn() }));
vi.mock('./UIWindowShare.js', () => ({ default: vi.fn() }));
vi.mock('../helpers/launchApp.js', () => ({ default: vi.fn() }));
vi.mock('../helpers/openItem.js', () => ({ default: vi.fn() }));
vi.mock('../helpers/publishAsWebsite.js', () => ({ default: vi.fn() }));
@@ -139,3 +137,91 @@ describe('UIItem Remove from Shared', () => {
expect(refresh_item_container.mock.calls[0][0][0]).toBe($('.item-container')[0]);
});
});
describe('UIItem Share', () => {
beforeEach(() => {
window.user = { username: 'alice' };
window.trash_path = '/alice/Trash';
});
it('is not offered, even on an item the user owns', async () => {
const labels = await menuLabels({
path: '/alice/Photos',
owner: 'alice',
shared_with_me: false,
share_mode: undefined,
shared_by: undefined,
});
expect(labels).not.toContain('share_ellipsis');
});
});
describe('UIItem Publish as Worker', () => {
beforeEach(() => {
window.user = { username: 'alice' };
window.trash_path = '/alice/Trash';
});
it('is not offered, even on a .js file the user owns', async () => {
const labels = await menuLabels({
path: '/alice/worker.js',
name: 'worker.js',
is_dir: false,
owner: 'alice',
shared_with_me: false,
share_mode: undefined,
shared_by: undefined,
});
expect(labels).not.toContain('publish_as_serverless_worker');
});
});
describe('UIItem dropped on the desktop', () => {
let stop;
beforeEach(async () => {
document.body.innerHTML = '<div class="item-container desktop"></div>';
Object.assign(window, {
user: { username: 'alice' },
trash_path: '/alice/Trash',
desktop_height: 800,
is_auto_arrange_enabled: false,
mouseover_window: undefined,
desktop_item_positions: {},
save_desktop_item_positions: vi.fn(),
});
const draggable = jQuery.fn.draggable;
jQuery.fn.draggable = function (options) {
if ( typeof options === 'object' ) stop = options.stop;
return this;
};
try {
await UIItem({
appendTo: $('.item-container'),
uid: 'u-2',
path: '/alice/Desktop/Notes',
name: 'Notes',
is_dir: true,
icon: { image: '', type: 'icon' },
});
} finally {
jQuery.fn.draggable = draggable;
}
// jsdom has no stylesheet, so give the item the size style.css does.
$('.item').css({ height: '70px', margin: '15px 5px 30px 5px' });
});
const dropAt = (top) => stop({}, { position: { top, left: 300 }, helper: $('<div>') });
it('moves there when the whole item fits on screen', () => {
dropAt(685);
expect($('.item')[0].style.top).toBe('685px');
expect(window.save_desktop_item_positions).toHaveBeenCalledTimes(1);
});
it('stays put when the item would hang off the bottom edge', () => {
dropAt(735);
expect($('.item')[0].style.top).toBe('');
expect(window.save_desktop_item_positions).not.toHaveBeenCalled();
});
});
+8 -38
View File
@@ -62,47 +62,17 @@ function UIPopover (options) {
function position_popover () {
// X position
const popover_width = options.width ?? $(el_popover).width();
if ( options.center_horizontally ) {
// Check taskbar position to determine popover positioning
const taskbar_position = window.taskbar_position || 'bottom';
if ( taskbar_position === 'left' ) {
// Position in top-left corner for left taskbar
x_pos = window.taskbar_height + 10; // Just to the right of the taskbar
} else if ( taskbar_position === 'right' ) {
// Position in top-right corner for right taskbar
x_pos = window.innerWidth - popover_width - window.taskbar_height - 40; // Just to the left of the taskbar
} else {
// Default bottom taskbar behavior - center horizontally
x_pos = window.innerWidth / 2 - popover_width / 2 - 15;
}
} else {
if ( options.position === 'bottom' || options.position === 'top' )
{
x_pos = options.left ?? ($(options.snapToElement).offset().left - (popover_width / 2) + 10);
}
else
{
x_pos = options.left ?? ($(options.snapToElement).offset().left + 5);
}
if ( options.position === 'bottom' || options.position === 'top' )
{
x_pos = options.left ?? ($(options.snapToElement).offset().left - (popover_width / 2) + 10);
}
else
{
x_pos = options.left ?? ($(options.snapToElement).offset().left + 5);
}
// Y position
const popover_height = options.height ?? $(el_popover).height();
if ( options.center_horizontally ) {
// Check taskbar position to determine popover positioning
const taskbar_position = window.taskbar_position || 'bottom';
if ( taskbar_position === 'left' || taskbar_position === 'right' ) {
// Position at top for left/right taskbars
y_pos = window.toolbar_height + 10; // Just below the toolbar
} else {
// Default bottom taskbar behavior - position above taskbar
y_pos = options.top ?? (window.innerHeight - (window.taskbar_height + popover_height + 10));
}
} else {
y_pos = options.top ?? ($(options.snapToElement).offset().top + $(options.snapToElement).height() + 5);
}
y_pos = options.top ?? ($(options.snapToElement).offset().top + $(options.snapToElement).height() + 5);
$(el_popover).css({
left: `${x_pos }px`,
-1
View File
@@ -71,7 +71,6 @@ function UIPrompt (options) {
selectable_body: false,
draggable_body: true,
allow_context_menu: false,
show_in_taskbar: false,
window_class: 'window-alert',
dominant: true,
body_content: h,
-769
View File
@@ -1,769 +0,0 @@
/*
* Copyright (C) 2024-present Puter Technologies Inc.
*
* This file is part of Puter.
*
* Puter is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import { createUploadThumbnailGenerator } from '../services/pdfThumbnails/index.js';
import UITaskbarItem from './UITaskbarItem.js';
import UIPopover from './UIPopover.js';
import launch_app from '../helpers/launchApp.js';
import UIContextMenu from './UIContextMenu.js';
import { appIconAttrs, appIconSrc } from '../helpers/appIcon.js';
import { filterLaunchableApps } from '../helpers/launchAppsList.js';
const TASKBAR_POSITIONS = ['left', 'bottom', 'right'];
async function UITaskbar (options) {
window.global_element_id++;
options = options ?? {};
options.content = options.content ?? '';
let taskbar_position;
// if first visit ever, set taskbar position to left
if ( window.first_visit_ever ) {
puter.kv.set('taskbar_position', 'left').catch(err => console.warn('Could not save taskbar_position:', err));
taskbar_position = 'left';
} else {
taskbar_position = await puter.kv.get('taskbar_position').catch(() => null);
// if this is not first visit, set taskbar position to bottom since it's from a user that
// used puter before customizing taskbar position was added and the taskbar position was set to bottom
// Unknown values are discarded too: this ends up in markup and stored values may be poisoned.
if ( ! TASKBAR_POSITIONS.includes(taskbar_position) ) {
taskbar_position = 'bottom'; // default position
puter.kv.set('taskbar_position', taskbar_position).catch(err => console.warn('Could not save taskbar_position:', err));
}
}
// Force bottom position on mobile devices
if ( isMobile.phone || isMobile.tablet ) {
taskbar_position = 'bottom';
}
// Set global taskbar position
window.taskbar_position = taskbar_position;
let launchAppsRequest = 0;
let pendingLaunchApps;
const fetchLaunchApps = () => {
pendingLaunchApps?.abort();
pendingLaunchApps = $.ajax({
url: `${window.api_origin}/get-launch-apps?icon_size=64`,
type: 'GET',
contentType: 'application/json',
timeout: 30000,
headers: { 'Authorization': `Bearer ${window.auth_token}` },
});
return pendingLaunchApps;
};
const logRefreshFailure = (xhr, status) => {
if ( status !== 'abort' ) console.error('Failed to refresh launch apps:', status);
};
fetchLaunchApps().done(apps => {
if ( launchAppsRequest === 0 ) window.launch_apps = apps;
}).fail(logRefreshFailure);
let h = '';
h += `<div id="ui-taskbar_${window.global_element_id}" class="taskbar taskbar-position-${taskbar_position}" style="height:${window.taskbar_height}px;">`;
h += '<div class="taskbar-sortable" style="display: flex; justify-content: center; z-index: 99999;"></div>';
h += '</div>';
if ( taskbar_position === 'left' || taskbar_position === 'right' ) {
$('.desktop').addClass(`desktop-taskbar-position-${taskbar_position}`);
}
$('.desktop').append(h);
//---------------------------------------------
// add `Start` to taskbar
//---------------------------------------------
UITaskbarItem({
icon: window.icons['start.svg'],
name: i18n('start'),
sortable: false,
keep_in_taskbar: true,
disable_context_menu: true,
onClick: async function (item) {
// skip if popover already open
if ( $(item).hasClass('has-open-popover') )
{
$('.popover-launcher').remove();
return;
}
// show popover
let popover = UIPopover({
content: '<div class="launch-popover hide-scrollbar"></div>',
snapToElement: item,
parent_element: item,
width: 500,
height: 500,
class: 'popover-launcher',
center_horizontally: true,
});
$(popover).on('remove', () => pendingLaunchApps?.abort());
const request = ++launchAppsRequest;
if ( ! window.launch_apps?.recent ) {
window.launch_apps = { recent: [], recommended: [] };
}
$(popover).find('.launch-popover').append(`
<div class="launch-search-wrapper">
<input style="background-image:url('${window.icons['magnifier-outline.svg']}');" class="launch-search">
<img class="launch-search-clear" src="${window.icons['close.svg']}">
</div>
`);
const renderApps = () => {
const recentApps = filterLaunchableApps(window.launch_apps.recent);
const recommendedApps = filterLaunchableApps(window.launch_apps.recommended);
let apps_str = '';
// -------------------------------------------
// Recent apps
// -------------------------------------------
if ( recentApps.length > 0 ) {
// heading
apps_str += `<h1 class="start-section-heading start-section-heading-recent">${i18n('recent')}</h1>`;
// apps
apps_str += '<div class="launch-apps-recent">';
for ( let index = 0; index < window.launch_recent_apps_count && index < recentApps.length; index++ ) {
const app_info = recentApps[index];
apps_str += `<div title="${html_encode(app_info.title)}" data-name="${html_encode(app_info.name)}" class="start-app-card">`;
const icon = appIconSrc(app_info);
apps_str += `<div class="start-app" data-app-name="${html_encode(app_info.name)}" data-app-uuid="${html_encode(app_info.uuid)}" data-app-icon="${html_encode(icon.src)}" data-app-icon-fallback="${html_encode(icon.fallback)}" data-app-title="${html_encode(app_info.title)}">`;
apps_str += `<img class="start-app-icon" ${appIconAttrs(app_info, window.icons['app.svg'])}>`;
apps_str += `<span class="start-app-title">${html_encode(app_info.title)}</span>`;
apps_str += '</div>';
apps_str += '</div>';
}
apps_str += '</div>';
}
// -------------------------------------------
// Recommended apps
// -------------------------------------------
if ( recommendedApps.length > 0 ) {
// heading
apps_str += `<h1 class="start-section-heading start-section-heading-recommended" style="${recentApps.length > 0 ? 'padding-top: 30px;' : ''}">${i18n('recommended')}</h1>`;
// apps
apps_str += '<div class="launch-apps-recommended">';
for ( let index = 0; index < recommendedApps.length; index++ ) {
const app_info = recommendedApps[index];
apps_str += `<div title="${html_encode(app_info.title)}" data-name="${html_encode(app_info.name)}" class="start-app-card">`;
const icon = appIconSrc(app_info);
apps_str += `<div class="start-app" data-app-name="${html_encode(app_info.name)}" data-app-uuid="${html_encode(app_info.uuid)}" data-app-icon="${html_encode(icon.src)}" data-app-icon-fallback="${html_encode(icon.fallback)}" data-app-title="${html_encode(app_info.title)}">`;
apps_str += `<img class="start-app-icon" ${appIconAttrs(app_info, window.icons['app.svg'])}>`;
apps_str += `<span class="start-app-title">${html_encode(app_info.title)}</span>`;
apps_str += '</div>';
apps_str += '</div>';
}
apps_str += '</div>';
}
// Replace tiles only, so the search input keeps its text and focus.
$(popover).find('.start-section-heading, .launch-apps-recent, .launch-apps-recommended').remove();
$(popover).find('.launch-popover').append(apps_str);
// make apps draggable
$(popover).find('.start-app').draggable({
appendTo: 'body',
revert: 'invalid',
connectToSortable: '.taskbar-sortable',
zIndex: parseInt($(popover).css('z-index')) + 1,
scroll: false,
distance: 5,
revertDuration: 100,
helper: 'clone',
cursorAt: { left: 18, top: 20 },
start: function (event, ui) {
},
drag: function (event, ui) {
},
stop: function () {
},
});
};
renderApps();
if ( ! isMobile.phone ) $(popover).find('.launch-search').focus();
fetchLaunchApps().done(apps => {
if ( request !== launchAppsRequest || !popover.isConnected ) return;
window.launch_apps = apps;
renderApps();
$(popover).find('.launch-search').trigger('change');
}).fail(logRefreshFailure);
$(popover).on('click', function () {
// close other context menus
$('.context-menu').fadeOut(200, function () {
$(this).remove();
$('.launch-app-selected').removeClass('launch-app-selected');
});
});
$(popover).on('contextmenu taphold', function (e) {
if ( ! e.target.closest('.launch-search') ) {
e.preventDefault();
}
});
$(document).on('contextmenu taphold', '.start-app', function (e) {
if ( e.type === 'taphold' && !isMobile.phone && !isMobile.tablet )
{
return;
}
e.stopImmediatePropagation();
e.preventDefault();
// close other context menus
$('.context-menu').fadeOut(200, function () {
$(this).remove();
});
let items = [{
html: i18n('open'),
onClick: function () {
$(e.currentTarget).trigger('click');
},
}];
$('.launch-app-selected').removeClass('launch-app-selected');
$(e.currentTarget).parent().addClass('launch-app-selected');
// Determine pin state
const $existingTaskbarItem = $(`.taskbar-item[data-app="${e.currentTarget.dataset.appName}"]`);
const isPinned = $existingTaskbarItem.length > 0 && $existingTaskbarItem.attr('data-keep-in-taskbar') === 'true';
items.push({
html: i18n('add_to_desktop'),
onClick: async function () {
try {
const fileName = `${e.currentTarget.dataset.appTitle}.app`;
const content = JSON.stringify({
app: e.currentTarget.dataset.appName,
title: e.currentTarget.dataset.appTitle,
icon: e.currentTarget.dataset.appIcon,
});
await puter.fs.upload(new File([content], fileName), window.desktop_path, {
generateThumbnails: true,
thumbnailGenerator: createUploadThumbnailGenerator(),
});
} catch ( err ) {
console.error('Failed to add shortcut to desktop:', err);
// Consider showing a user-facing error notification
}
},
});
if ( ! isPinned ) {
items.push({
html: i18n('keep_in_taskbar'),
onClick: function () {
const $taskbarItem = $(`.taskbar-item[data-app="${e.currentTarget.dataset.appName}"]`);
if ( $taskbarItem.length === 0 ) {
// No taskbar item yet: create a new pinned one
UITaskbarItem({
icon: e.currentTarget.dataset.appIcon,
iconFallback: e.currentTarget.dataset.appIconFallback,
app: e.currentTarget.dataset.appName,
name: e.currentTarget.dataset.appTitle,
keep_in_taskbar: true,
});
} else if ( $taskbarItem.attr('data-keep-in-taskbar') !== 'true' ) {
// mark as pinned
$taskbarItem.attr('data-keep-in-taskbar', 'true');
}
// Persist
window.update_taskbar();
},
});
} else {
items.push({
html: i18n('remove_from_taskbar'),
onClick: function () {
const $taskbarItem = $(`.taskbar-item[data-app="${e.currentTarget.dataset.appName}"]`);
if ( $taskbarItem.length === 0 ) return; // nothing to do
// Unpin
$taskbarItem.attr('data-keep-in-taskbar', 'false');
// If no open windows for this app, remove the item
if ( $taskbarItem.attr('data-open-windows') === '0' ) {
if ( window.remove_taskbar_item ) {
window.remove_taskbar_item($taskbarItem.get(0));
} else {
$taskbarItem.remove();
}
}
window.update_taskbar();
},
});
}
UIContextMenu({
items: items,
});
return false;
});
},
});
//---------------------------------------------
// add `Explorer` to the taskbar
//---------------------------------------------
UITaskbarItem({
icon: window.icons['folders.svg'],
app: 'explorer',
name: 'Explorer',
sortable: false,
keep_in_taskbar: true,
lock_keep_in_taskbar: true,
onClick: function () {
let open_window_count = parseInt($('.taskbar-item[data-app="explorer"]').attr('data-open-windows'));
if ( open_window_count === 0 ) {
launch_app({ name: 'explorer', path: window.home_path });
} else {
return false;
}
},
});
//---------------------------------------------
// add separator before trash
//---------------------------------------------
UITaskbarItem({
icon: '', // No icon for separator
name: 'separator',
app: 'separator',
sortable: false,
keep_in_taskbar: true,
lock_keep_in_taskbar: true,
disable_context_menu: true,
style: 'pointer-events: none;', // Make it non-interactive
onClick: function () {
// Separator is non-interactive
return false;
},
});
//---------------------------------------------
// Add other useful apps to the taskbar
//---------------------------------------------
if ( window.user.taskbar_items && window.user.taskbar_items.length > 0 ) {
for ( let index = 0; index < window.user.taskbar_items.length; index++ ) {
const app_info = window.user.taskbar_items[index];
const icon = appIconSrc(app_info);
// add taskbar item for each app
UITaskbarItem({
icon: icon.src,
iconFallback: icon.fallback,
app: app_info.name,
name: app_info.title,
keep_in_taskbar: true,
onClick: function () {
let open_window_count = parseInt($(`.taskbar-item[data-app="${app_info.name}"]`).attr('data-open-windows'));
if ( open_window_count === 0 ) {
launch_app({
name: app_info.name,
});
} else {
return false;
}
},
});
}
}
//---------------------------------------------
// add `Trash` to the taskbar
//---------------------------------------------
const trash = await puter.fs.stat({ path: window.trash_path, consistency: 'eventual' });
if ( window.socket ) {
window.socket.emit('trash.is_empty', { is_empty: trash.is_empty });
}
UITaskbarItem({
icon: trash.is_empty ? window.icons['trash.svg'] : window.icons['trash-full.svg'],
app: 'trash',
name: `${i18n('trash')}`,
sortable: false,
keep_in_taskbar: true,
lock_keep_in_taskbar: true,
onClick: function () {
let open_windows = $(`.window[data-path="${html_encode(window.trash_path)}"]`);
if ( open_windows.length === 0 ) {
launch_app({ name: 'explorer', path: window.trash_path });
} else {
open_windows.focusWindow();
}
},
onItemsDrop: function (items) {
window.move_items(items, window.trash_path);
},
});
//---------------------------------------------
// add separator before trash
//---------------------------------------------
UITaskbarItem({
icon: '', // No icon for separator
name: 'separator',
app: 'separator',
sortable: false,
keep_in_taskbar: true,
lock_keep_in_taskbar: true,
disable_context_menu: true,
style: 'pointer-events: none;', // Make it non-interactive
onClick: function () {
// Separator is non-interactive
return false;
},
});
window.make_taskbar_sortable();
}
//-------------------------------------------
// Taskbar is sortable
//-------------------------------------------
window.make_taskbar_sortable = function () {
const position = window.taskbar_position || 'bottom';
const axis = position === 'bottom' ? 'x' : 'y';
$('.taskbar-sortable').sortable({
axis: axis,
items: '.taskbar-item-sortable:not(.has-open-contextmenu):not([data-app="separator"])',
cancel: '.has-open-contextmenu',
placeholder: 'taskbar-item-sortable-placeholder',
helper: 'clone',
distance: 5,
revert: 10,
receive: function (event, ui) {
if ( ! $(ui.item).hasClass('taskbar-item') ) {
// if app is already in taskbar, cancel
if ( $(`.taskbar-item[data-app="${$(ui.item).attr('data-app-name')}"]`).length !== 0 ) {
$(this).sortable('cancel');
$('.taskbar .start-app').remove();
return;
}
}
},
update: function (event, ui) {
if ( ! $(ui.item).hasClass('taskbar-item') ) {
// if app is already in taskbar, cancel
if ( $(`.taskbar-item[data-app="${$(ui.item).attr('data-app-name')}"]`).length !== 0 ) {
$(this).sortable('cancel');
$('.taskbar .start-app').remove();
return;
}
let item = UITaskbarItem({
icon: $(ui.item).attr('data-app-icon'),
iconFallback: $(ui.item).attr('data-app-icon-fallback'),
app: $(ui.item).attr('data-app-name'),
name: $(ui.item).attr('data-app-title'),
append_to_taskbar: false,
keep_in_taskbar: true,
onClick: function () {
let open_window_count = parseInt($(`.taskbar-item[data-app="${$(ui.item).attr('data-app-name')}"]`).attr('data-open-windows'));
if ( open_window_count === 0 ) {
launch_app({
name: $(ui.item).attr('data-app-name'),
});
} else {
return false;
}
},
});
let el = ($(item).detach());
$(el).insertAfter(ui.item);
$(el).show();
$(ui.item).removeItems();
window.update_taskbar();
}
// only proceed to update DB if the item sorted was a pinned item otherwise no point in updating the taskbar in DB
else if ( $(ui.item).attr('data-keep-in-taskbar') === 'true' ) {
window.update_taskbar();
}
},
});
};
// Function to update taskbar position
window.update_taskbar_position = async function (new_position) {
// Prevent position changes on mobile devices - always keep bottom
if ( isMobile.phone || isMobile.tablet ) {
return;
}
if ( ! TASKBAR_POSITIONS.includes(new_position) ) {
return;
}
// Store the new position
puter.kv.set('taskbar_position', new_position).catch(err => console.warn('Could not save taskbar_position:', err));
window.taskbar_position = new_position;
// Remove old position classes and add new one
$('.taskbar').removeClass('taskbar-position-left taskbar-position-bottom taskbar-position-right');
$('.taskbar').addClass(`taskbar-position-${new_position}`);
// update desktop class, if left or right, add `desktop-taskbar-position-left` or `desktop-taskbar-position-right`
$('.desktop').removeClass('desktop-taskbar-position-left');
$('.desktop').removeClass('desktop-taskbar-position-right');
$('.desktop').addClass(`desktop-taskbar-position-${new_position}`);
// Update desktop height/width calculations based on new position
window.update_desktop_dimensions_for_taskbar();
// Update window positions if needed (for maximized windows)
$('.window[data-is_maximized="1"]').each(function () {
const el_window = this;
window.update_maximized_window_for_taskbar(el_window);
});
// Re-initialize sortable with correct axis
$('.taskbar-sortable').sortable('destroy');
window.make_taskbar_sortable();
// Adjust taskbar item sizes for the new position
setTimeout(() => {
window.adjust_taskbar_item_sizes();
}, 10);
// Reinitialize all taskbar item tooltips with new position
$('.taskbar-item').each(function () {
const $item = $(this);
// Destroy existing tooltip
if ( $item.data('ui-tooltip') ) {
$item.tooltip('destroy');
}
// Helper function to get tooltip position based on taskbar position
function getTooltipPosition () {
const taskbarPosition = window.taskbar_position || 'bottom';
if ( taskbarPosition === 'bottom' ) {
return {
my: 'center bottom-20',
at: 'center top',
};
} else if ( taskbarPosition === 'top' ) {
return {
my: 'center top+20',
at: 'center bottom',
};
} else if ( taskbarPosition === 'left' ) {
return {
my: 'left+20 center',
at: 'right center',
};
} else if ( taskbarPosition === 'right' ) {
return {
my: 'right-20 center',
at: 'left center',
};
}
return {
my: 'center bottom-20',
at: 'center top',
}; // fallback
}
const tooltipPosition = getTooltipPosition();
// Reinitialize tooltip with new position
$item.tooltip({
items: ".taskbar:not(.children-have-open-contextmenu) .taskbar-item:not([data-app='separator'])",
position: {
my: tooltipPosition.my,
at: tooltipPosition.at,
using: function ( position, feedback ) {
$(this).css( position);
$('<div>')
.addClass( 'arrow')
.addClass( feedback.vertical)
.addClass( feedback.horizontal)
.appendTo( this);
},
},
});
});
};
// Function to update desktop dimensions based on taskbar position
window.update_desktop_dimensions_for_taskbar = function () {
const position = window.taskbar_position || 'bottom';
if ( position === 'bottom' ) {
$('.desktop').css({
'height': `calc(100vh - ${window.taskbar_height + window.toolbar_height}px)`,
'width': '100%',
'left': '0',
'top': `${window.toolbar_height}px`,
});
} else if ( position === 'left' ) {
$('.desktop').css({
'height': `calc(100vh - ${window.toolbar_height}px)`,
'width': `calc(100% - ${window.taskbar_height}px)`,
'left': `${window.taskbar_height}px`,
'top': `${window.toolbar_height}px`,
});
} else if ( position === 'right' ) {
$('.desktop').css({
'height': `calc(100vh - ${window.toolbar_height}px)`,
'width': `calc(100% - ${window.taskbar_height}px)`,
'left': '0',
'top': `${window.toolbar_height}px`,
});
}
};
//-------------------------------------------
// Dynamic taskbar item resizing for left/right positions
//-------------------------------------------
window.adjust_taskbar_item_sizes = function () {
const position = window.taskbar_position || 'bottom';
// Only apply to left and right positions
if ( position !== 'left' && position !== 'right' ) {
// Reset to default sizes for bottom position
$('.taskbar .taskbar-item').css({
'width': '40px',
'height': '40px',
'min-width': '40px',
'min-height': '40px',
});
$('.taskbar-icon').css('height', '40px');
return;
}
const taskbar = $('.taskbar')[0];
const taskbarItems = $('.taskbar .taskbar-item:visible');
if ( !taskbar || taskbarItems.length === 0 ) return;
// Get available height (minus padding)
const totalItemsNeeded = taskbarItems.length;
const taskbarHeight = taskbar.clientHeight;
const paddingTop = 20; // from CSS
const paddingBottom = 20; // from CSS
const availableHeight = taskbarHeight - paddingTop - paddingBottom - 180;
// Calculate space needed with default sizes
const defaultItemSize = 40;
const defaultMargin = 5;
const spaceNeededDefault = (totalItemsNeeded * defaultItemSize) + ((totalItemsNeeded - 1) * defaultMargin);
if ( spaceNeededDefault <= availableHeight ) {
// No overflow, use default sizes
taskbarItems.css({
'width': '40px',
'height': '40px',
'min-width': '40px',
'min-height': '40px',
'padding': '6px 5px 10px 5px', // default padding
});
$('.taskbar-icon').css('height', `${defaultItemSize }px`);
$('.taskbar-icon').css('width', '40px');
$('.taskbar-icon > img').css('width', 'auto');
$('.taskbar-icon > img').css('margin', 'auto');
$('.taskbar-icon > img').css('display', 'block');
// Reset margins to default
taskbarItems.css('margin-bottom', '5px');
taskbarItems.last().css('margin-bottom', '0px');
} else {
// Overflow detected, calculate smaller sizes
// Reserve some margin space (minimum 2px between items)
const minMargin = 2;
const marginSpace = (totalItemsNeeded - 1) * minMargin;
const availableForItems = availableHeight - marginSpace;
const newItemSize = Math.floor(availableForItems / totalItemsNeeded);
// Ensure minimum size of 20px
const finalItemSize = Math.max(20, newItemSize);
// Calculate proportional padding based on size ratio
const sizeRatio = finalItemSize / defaultItemSize;
const paddingTop = Math.max(1, Math.floor(6 * sizeRatio));
const paddingRight = Math.max(1, Math.floor(5 * sizeRatio));
const paddingBottom = Math.max(1, Math.floor(10 * sizeRatio));
const paddingLeft = Math.max(1, Math.floor(5 * sizeRatio));
// Apply new sizes and padding
taskbarItems.css({
'width': '40px',
'height': `${finalItemSize }px`,
'min-width': '40px',
'min-height': `${finalItemSize }px`,
'padding': `${paddingTop}px ${paddingRight}px ${paddingBottom}px ${paddingLeft}px`,
});
$('.taskbar-icon').css('height', `${finalItemSize }px`);
$('.taskbar-icon').css('width', '40px');
$('.taskbar-icon > img').css('width', 'auto');
$('.taskbar-icon > img').css('margin', 'auto');
$('.taskbar-icon > img').css('display', 'block');
// Adjust margins
taskbarItems.css('margin-bottom', `${minMargin }px`);
taskbarItems.last().css('margin-bottom', '0px');
}
};
// Hook into existing taskbar functionality
$(document).ready(function () {
// Watch for taskbar item changes
const observer = new MutationObserver(function (mutations) {
mutations.forEach(function (mutation) {
if ( mutation.type === 'childList' || mutation.type === 'attributes' ) {
// Delay to ensure DOM updates are complete
setTimeout(() => {
window.adjust_taskbar_item_sizes();
}, 10);
}
});
});
// Start observing when taskbar is available
const checkTaskbar = setInterval(() => {
const taskbar = document.querySelector('.taskbar-sortable');
if ( taskbar ) {
observer.observe(taskbar, {
childList: true,
attributes: true,
subtree: true,
});
clearInterval(checkTaskbar);
// Initial call
setTimeout(() => {
window.adjust_taskbar_item_sizes();
}, 100);
}
}, 100);
// Also watch for window resize events
window.addEventListener('resize', () => {
setTimeout(() => {
window.adjust_taskbar_item_sizes();
}, 10);
});
});
export default UITaskbar;
-181
View File
@@ -1,181 +0,0 @@
// @vitest-environment jsdom
/*
* Copyright (C) 2024-present Puter Technologies Inc.
*
* This file is part of Puter.
*
* Puter is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import { afterEach, beforeEach, expect, it, vi } from 'vitest';
import jQuery from '../lib/jquery-3.6.1/jquery-3.6.1.min.js';
vi.mock('../helpers/launchApp.js', () => ({ default: vi.fn() }));
vi.mock('./UIContextMenu.js', () => ({ default: vi.fn() }));
globalThis.$ = globalThis.jQuery = jQuery;
globalThis.i18n = (key) => (key === 'start' ? 'Start' : key);
globalThis.html_encode = (value) => String(value ?? '');
globalThis.isMobile = { phone: false, tablet: false };
await import('../lib/jquery-ui-1.13.2/jquery-ui.js');
const { default: UITaskbar } = await import('./UITaskbar.js');
const app = { name: 'test-app', uuid: 'test-uid', title: 'Test app' };
let launchApps;
let start;
let requests;
afterEach(() => {
$('.popover-launcher, .taskbar').remove();
$(document).off();
$(window).off();
document.body.innerHTML = '';
delete window.launch_apps;
vi.unstubAllGlobals();
vi.useRealTimers();
vi.restoreAllMocks();
});
beforeEach(async () => {
document.body.innerHTML = '<div class="desktop"></div>';
Object.assign(window, {
global_element_id: 0,
taskbar_height: 50,
toolbar_height: 0,
api_origin: 'http://api.test',
auth_token: 'test-token',
icons: {},
user: {},
launch_recent_apps_count: 10,
});
vi.stubGlobal('puter', {
kv: { get: async () => 'bottom' },
fs: { stat: async () => ({ is_empty: true }) },
});
launchApps = { recent: [app], recommended: [] };
requests = [];
$.ajaxTransport('+*', () => {
let complete;
const request = {
send(headers, done) {
complete = done;
},
abort: vi.fn(),
resolve(data) {
complete(
200,
'OK',
{ text: JSON.stringify(data) },
'Content-Type: application/json',
);
},
};
requests.push(request);
return request;
});
await UITaskbar();
requests[0].resolve(launchApps);
start = $('.taskbar-item[data-name="Start"]');
});
it.each([true, false])(
'keeps cached search usable after a timeout, cached=%s',
async (cached) => {
if (!cached) window.launch_apps = [];
vi.spyOn(console, 'error').mockImplementation(() => {});
vi.useFakeTimers();
start.trigger('click');
await vi.advanceTimersByTimeAsync(30000);
expect(requests.at(-1).abort).toHaveBeenCalledOnce();
expect($('.launch-search')).toHaveLength(1);
expect($('.start-app')).toHaveLength(cached ? 1 : 0);
},
);
function deferRefresh() {
return (data) => requests.at(-1).resolve(data);
}
it('refreshes reopened Start without losing cached tiles or search input', async () => {
const survivor = {
name: 'survivor',
uuid: 'survivor-uid',
title: 'Survivor',
};
launchApps.recent.push(survivor);
start.trigger('click');
requests.at(-1).resolve(launchApps);
start.trigger('click');
const resolve = deferRefresh();
start.trigger('click');
const input = $('.launch-search').get(0);
expect(input).toBeDefined();
expect($('.start-app[data-app-name="test-app"]')).toHaveLength(1);
input.value = 'notes';
const onChange = vi.fn();
$(input).on('change', onChange);
resolve({
recent: [survivor],
recommended: [{ name: 'notes', uuid: 'notes-uid', title: 'Notes' }],
});
await vi.waitFor(() =>
expect($('.start-app[data-app-name="notes"]')).toHaveLength(1),
);
expect($('.launch-search').get(0)).toBe(input);
expect(input.value).toBe('notes');
expect(document.activeElement).toBe(input);
expect(onChange).toHaveBeenCalledOnce();
expect($('.start-app[data-app-name="survivor"]')).toHaveLength(1);
expect($('.start-app[data-app-name="test-app"]')).toHaveLength(0);
});
it('cancels closed menus and ignores their late responses', () => {
start.trigger('click');
const old = requests.at(-1);
start.trigger('click');
expect(old.abort).toHaveBeenCalledOnce();
start.trigger('click');
requests.at(-1).resolve({ recent: [], recommended: [] });
old.resolve({ recent: [app], recommended: [] });
expect(window.launch_apps.recent).toHaveLength(0);
expect($('.start-app')).toHaveLength(0);
});
it('cancels the startup request when Start opens', async () => {
requests = [];
document.body.innerHTML = '<div class="desktop"></div>';
await UITaskbar();
const startup = requests[0];
$('.taskbar-item[data-name="Start"]').trigger('click');
expect(startup.abort).toHaveBeenCalledOnce();
});
it('hides apps the backend marks unlaunchable', () => {
start.trigger('click');
requests.at(-1).resolve({
recent: [
app,
{
name: 'reclaimed',
uuid: 'reclaimed-uid',
title: 'Reclaimed',
index_url: null,
privateAccess: { hasAccess: false },
},
],
recommended: [],
});
expect($('.start-app[data-app-name="test-app"]')).toHaveLength(1);
expect($('.start-app[data-app-name="reclaimed"]')).toHaveLength(0);
});
-543
View File
@@ -1,543 +0,0 @@
/*
* Copyright (C) 2024-present Puter Technologies Inc.
*
* This file is part of Puter.
*
* Puter is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import UIContextMenu from './UIContextMenu.js';
import path from '../lib/path.js';
import launch_app from '../helpers/launchApp.js';
import { user_facing_windows } from '../helpers/windowVisibility.js';
import { appIconFallbackAttr } from '../helpers/appIcon.js';
let tray_item_id = 1;
function UITaskbarItem (options) {
let h = '';
tray_item_id++;
options.sortable = options.sortable ?? true;
options.open_windows_count = options.open_windows_count ?? 0;
options.lock_keep_in_taskbar = options.lock_keep_in_taskbar ?? false;
options.append_to_taskbar = options.append_to_taskbar ?? true;
options.before_trash = options.before_trash ?? false;
// The windows this item stands for: the user's own. An instance another
// app launched in the background is not counted in data-open-windows and
// has no item of its own (see UIWindow's taskbar block) — it must not be
// shown, hidden, or closed through the item its app's OTHER windows own.
const item_windows = () => $(user_facing_windows($(`.window[data-app="${options.app}"]`)));
const element_id = window.global_element_id++;
h += `<div class = "taskbar-item ${options.sortable ? 'taskbar-item-sortable' : ''} disable-user-select"
id = "taskbar-item-${tray_item_id}"
data-taskbar-item-id = "${tray_item_id}"
data-element-id = "${html_encode(element_id)}"
data-name = "${html_encode(options.name)}"
data-app = "${html_encode(options.app)}"
data-keep-in-taskbar = "${html_encode(options.keep_in_taskbar ?? 'false')}"
data-open-windows="${(options.open_windows_count)}"
title = "${html_encode(options.name)}"
style= "${options.style ? html_encode(options.style) : ''}"
>`;
let icon = options.icon ? options.icon : window.icons['app.svg'];
// App icons carry a retry URL (see helpers/appIcon.js); the bundled icons
// below never need one.
let icon_fallback = options.iconFallback ?? '';
if ( options.app === 'explorer' )
{
icon = window.icons['folders.svg'];
icon_fallback = '';
}
// taskbar icon
h += '<div class="taskbar-icon">';
// Don't add img tag for separator
if ( options.app !== 'separator' ) {
h += `<img src="${html_encode(icon)}"${appIconFallbackAttr(icon_fallback)} style="${options.group === 'apps' ? 'filter:none;' : ''}">`;
}
h += '</div>';
// active indicator
if ( options.app !== 'apps' )
{
h += '<span class="active-taskbar-indicator"></span>';
}
h += '</div>';
if ( options.append_to_taskbar ) {
if ( options.before_trash ) {
$('.taskbar-sortable').append(h);
} else {
if ( options.sortable )
{
$('.taskbar-sortable').append(h);
}
else {
// if taskbar-sortable is empty then append before it
if ( $('.taskbar-sortable').children().length === 0 )
{
$('.taskbar').find('.taskbar-sortable').before(h);
}
else
{
$('.taskbar').find('.taskbar-sortable').after(h);
}
}
}
} else {
$('body').prepend(h);
}
const el_taskbar_item = document.querySelector(`#taskbar-item-${tray_item_id}`);
// fade in the taskbar item
$(el_taskbar_item).show(50);
// Adjust taskbar item sizes after adding new item
if ( window.adjust_taskbar_item_sizes ) {
setTimeout(() => {
window.adjust_taskbar_item_sizes();
}, 100);
}
$(el_taskbar_item).on('click', function (e) {
e.preventDefault();
e.stopPropagation();
// Don't handle clicks for separators
if ( options.app === 'separator' ) {
return;
}
// if this is for the launcher popover, and it's mobile, and has-open-popover, close the popover
if ( $(el_taskbar_item).attr('data-name') === 'Start'
&& (isMobile.phone || isMobile.tablet) && $(el_taskbar_item).hasClass('has-open-popover') ) {
$('.popover').remove();
return;
}
// If this item has an open context menu, don't do anything
if ( $(el_taskbar_item).hasClass('has-open-contextmenu') )
{
return;
}
if ( options.onClick === undefined || options.onClick(el_taskbar_item) === false ) {
// re-show each window in this app group
item_windows().showWindow();
}
});
$(el_taskbar_item).on('contextmenu taphold', function (e) {
// seems like the only way to stop sortable is to destroy it
if ( options.sortable ) {
$('.taskbar-sortable').sortable('destroy');
}
e.preventDefault();
e.stopPropagation();
// Don't show context menu for separators
if ( options.app === 'separator' ) {
return;
}
// If context menu is disabled on this item, return
if ( options.disable_context_menu )
{
return;
}
// don't allow context menu to open if it's already open
if ( $(el_taskbar_item).hasClass('has-open-contextmenu') )
{
return;
}
const menu_items = [];
const open_windows = parseInt($(el_taskbar_item).attr('data-open-windows'));
// -------------------------------------------
// List of open windows belonging to this app
// -------------------------------------------
item_windows().each(function () {
menu_items.push({
html: $(this).find('.window-head-title').html(),
val: $(this).attr('data-id'),
onClick: function (e) {
$(`.window[data-id="${e.value}"]`).showWindow();
},
});
});
// -------------------------------------------
// divider
// -------------------------------------------
if ( menu_items.length > 0 )
{
menu_items.push('-');
}
//------------------------------------------
// New Window
//------------------------------------------
if ( options.app && options.app !== 'trash' ) {
menu_items.push({
html: i18n('new_window'),
val: $(this).attr('data-id'),
onClick: function () {
// is trash?
launch_app({
name: options.app,
maximized: (isMobile.phone || isMobile.tablet),
});
},
});
}
//------------------------------------------
// Open Trash
//------------------------------------------
else if ( options.app && options.app === 'trash' ) {
menu_items.push({
html: i18n('open_trash'),
val: $(this).attr('data-id'),
onClick: function () {
launch_app({
name: options.app,
path: window.trash_path,
maximized: (isMobile.phone || isMobile.tablet),
});
},
});
}
//------------------------------------------
// Empty Trash
//------------------------------------------
if ( options.app && options.app === 'trash' ) {
// divider
menu_items.push('-');
// Empty Trash menu item
menu_items.push({
html: i18n('empty_trash'),
val: $(this).attr('data-id'),
onClick: async function () {
window.empty_trash();
},
});
}
//------------------------------------------
// Remove from Taskbar
//------------------------------------------
if ( options.keep_in_taskbar && !options.lock_keep_in_taskbar ) {
menu_items.push({
html: i18n('remove_from_taskbar'),
val: $(this).attr('data-id'),
onClick: function () {
$(el_taskbar_item).attr('data-keep-in-taskbar', 'false');
if ( $(el_taskbar_item).attr('data-open-windows') === '0' ) {
window.remove_taskbar_item(el_taskbar_item);
}
window.update_taskbar();
options.keep_in_taskbar = false;
},
});
}
//------------------------------------------
// Keep in Taskbar
//------------------------------------------
else if ( ! options.keep_in_taskbar ) {
menu_items.push({
html: i18n('keep_in_taskbar'),
val: $(this).attr('data-id'),
onClick: function () {
$(el_taskbar_item).attr('data-keep-in-taskbar', 'true');
window.update_taskbar();
options.keep_in_taskbar = true;
},
});
}
if ( open_windows > 0 ) {
// -------------------------------------------
// divider
// -------------------------------------------
menu_items.push('-');
// -------------------------------------------
// Show All Windows
// -------------------------------------------
menu_items.push({
html: i18n('show_all_windows'),
onClick: function () {
item_windows().showWindow();
},
});
// -------------------------------------------
// Hide All Windows
// -------------------------------------------
menu_items.push({
html: i18n('hide_all_windows'),
onClick: function () {
if ( open_windows > 0 )
{
item_windows().hideWindow();
}
},
});
// -------------------------------------------
// Close All Windows
// -------------------------------------------
menu_items.push({
html: i18n('close_all_windows'),
onClick: function () {
// "All" means the windows this item lists — a background
// helper belongs to the app running it, and goes when
// that app does (UIWindow's close path).
item_windows().close();
},
});
}
const pos = el_taskbar_item.getBoundingClientRect();
UIContextMenu({
parent_element: el_taskbar_item,
position: getContextMenuPosition(pos),
items: menu_items,
});
return false;
});
// Helper function to get tooltip position based on taskbar position
function getTooltipPosition () {
const taskbarPosition = window.taskbar_position || 'bottom';
if ( taskbarPosition === 'bottom' ) {
return {
my: 'center bottom-20',
at: 'center top',
};
} else if ( taskbarPosition === 'top' ) {
return {
my: 'center top+20',
at: 'center bottom',
};
} else if ( taskbarPosition === 'left' ) {
return {
my: 'left+20 center',
at: 'right center',
};
} else if ( taskbarPosition === 'right' ) {
return {
my: 'right-20 center',
at: 'left center',
};
}
return {
my: 'center bottom-20',
at: 'center top',
}; // fallback
}
// Helper function to get context menu position based on taskbar position
function getContextMenuPosition (pos) {
const taskbarPosition = window.taskbar_position || 'bottom';
if ( taskbarPosition === 'bottom' ) {
return {
top: pos.top - 15,
left: pos.left + 5,
};
} else if ( taskbarPosition === 'top' ) {
return {
top: pos.bottom + 15,
left: pos.left + 5,
};
} else if ( taskbarPosition === 'left' ) {
return {
top: pos.top + 5,
left: pos.right + 5,
};
} else if ( taskbarPosition === 'right' ) {
return {
top: pos.top + 5,
left: pos.left - 20,
};
}
return {
top: pos.top - 15,
left: pos.left + 5,
}; // fallback
}
const tooltipPosition = getTooltipPosition();
$(el_taskbar_item).tooltip({
// only show tooltip if desktop is not selectable active
items: ".desktop:not(.desktop-selectable-active) .taskbar:not(.children-have-open-contextmenu) .taskbar-item:not([data-app='separator'])",
position: {
my: tooltipPosition.my,
at: tooltipPosition.at,
using: function ( position, feedback ) {
$(this).css( position);
$('<div>')
.addClass( 'arrow')
.addClass( feedback.vertical)
.addClass( feedback.horizontal)
.appendTo( this);
},
},
});
// --------------------------------------------------------
// Droppable
// --------------------------------------------------------
// Don't make separators droppable
if ( options.app !== 'separator' ) {
$(el_taskbar_item).droppable({
accept: '.item',
// 'pointer' is very important because of active window tracking is based on the position of cursor.
tolerance: 'pointer',
drop: async function ( event, ui ) {
// Check if hovering over an item that is VISIBILE
if ( $(event.target).closest('.window').attr('data-id') !== $(window.mouseover_window).attr('data-id') )
{
return;
}
// If ctrl is pressed and source is Trashed, cancel whole operation
if ( event.ctrlKey && path.dirname($(ui.draggable).attr('data-path')) === window.trash_path )
{
return;
}
const items_to_move = [];
// First item
items_to_move.push(ui.draggable);
// All subsequent items
const cloned_items = document.getElementsByClassName('item-selected-clone');
for ( let i = 0; i < cloned_items.length; i++ ) {
const source_item = document.getElementById(`item-${ $(cloned_items[i]).attr('data-id')}`);
if ( source_item !== null )
{
items_to_move.push(source_item);
}
}
// --------------------------------------------------------
// If `options.onItemsDrop` is set, call it with the items to move
//--------------------------------------------------------
if ( options.onItemsDrop && typeof options.onItemsDrop === 'function' ) {
options.onItemsDrop(items_to_move);
return;
}
// --------------------------------------------------------
// If dropped on an app, open the app with the dropped item as an argument
//--------------------------------------------------------
else if ( options.app ) {
// an array that hold the items to sign
const items_to_sign = [];
// prepare items to sign
for ( let i = 0; i < items_to_move.length; i++ ) {
items_to_sign.push({
name: $(items_to_move[i]).attr('data-name'),
uid: $(items_to_move[i]).attr('data-uid'),
action: 'write',
path: $(items_to_move[i]).attr('data-path'),
});
}
// open each item
for ( let i = 0; i < items_to_sign.length; i++ ) {
const item = items_to_sign[i];
launch_app({
name: options.app,
file_path: item.path,
// app_obj: open_item_meta.suggested_apps[0],
window_title: item.name,
file_uid: item.uid,
// file_signature: item,
});
}
// deselect dragged item
for ( let i = 0; i < items_to_move.length; i++ )
{
$(items_to_move[i]).removeClass('item-selected');
}
}
// Unselect directory/app if item is dropped
if ( options.is_dir || options.app ) {
$(el_taskbar_item).removeClass('active');
$(el_taskbar_item).tooltip('close');
$('.ui-draggable-dragging .item-name, .item-selected-clone .item-name').css('opacity', 'initial');
$('.item-container').removeClass('item-container-transparent-border');
}
// Re-enable droppable on all item-container
$('.item-container').droppable('enable');
return false;
},
over: function (event, ui) {
// Check hovering over an item that is VISIBILE
const $event_parent_win = $(event.target).closest('.window');
if ( $event_parent_win.length > 0 && $event_parent_win.attr('data-id') !== $(window.mouseover_window).attr('data-id') )
{
return;
}
// Don't do anything if the dragged item is NOT a UIItem
if ( ! $(ui.draggable).hasClass('item') )
{
return;
}
// If this is a directory or an app, and an item was dragged over it, highlight it.
if ( options.is_dir || options.app ) {
$(el_taskbar_item).addClass('active');
// show tooltip of this item
$(el_taskbar_item).tooltip().mouseover();
// make item name partially transparent
$('.ui-draggable-dragging .item-name, .item-selected-clone .item-name').css('opacity', 0.1);
// remove all item-container active borders
$('.item-container').addClass('item-container-transparent-border');
}
// Disable all window bodies
$('.item-container').droppable( 'disable');
},
out: function (event, ui) {
// Don't do anything if the dragged item is NOT a UIItem
if ( ! $(ui.draggable).hasClass('item') )
{
return;
}
// Unselect directory/app if item is dragged out
if ( options.is_dir || options.app ) {
$(el_taskbar_item).removeClass('active');
$(el_taskbar_item).tooltip('close');
$('.ui-draggable-dragging .item-name, .item-selected-clone .item-name').css('opacity', 'initial');
$('.item-container').removeClass('item-container-transparent-border');
}
$('.item-container').droppable( 'enable');
},
});
}
return el_taskbar_item;
}
export default UITaskbarItem;
+123
View File
@@ -0,0 +1,123 @@
// @vitest-environment jsdom
/*
* Copyright (C) 2024-present Puter Technologies Inc.
*
* This file is part of Puter.
*
* Puter is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import jQuery from '../lib/jquery-3.6.1/jquery-3.6.1.min.js';
vi.mock('../helpers/launchApp.js', () => ({ default: vi.fn() }));
globalThis.$ = globalThis.jQuery = jQuery;
globalThis.i18n = (key) => key;
globalThis.html_encode = (value) => String(value ?? '');
globalThis.isMobile = { phone: false, tablet: false };
globalThis.def = globalThis.def ?? ((value) => value);
await import('../lib/jquery-ui-1.13.2/jquery-ui.js');
// The page loads this plugin from a vendored script; nothing here drops files.
$.fn.dragster = function () {
return this;
};
const { default: UIWindow } = await import('./UIWindow.js');
const openWindow = (options = {}) => UIWindow({
title: 'Notes',
app: 'notes',
body_content: '<p>hello</p>',
width: 400,
height: 300,
...options,
});
/** Opens the window head's context menu and returns its item labels. */
const headMenuLabels = (el_window) => {
$(el_window).find('.window-head').trigger('contextmenu');
return $('.context-menu .contextmenu-label').map((_, el) => $(el).text().toLowerCase()).get();
};
beforeEach(() => {
document.body.innerHTML = '<div class="desktop"></div>';
Object.assign(window, {
global_element_id: 0,
window_counter: 0,
last_window_zindex: 1,
window_stack: [],
toolbar_height: 0,
icons: {},
uuidv4: () => crypto.randomUUID(),
is_dashboard_mode: false,
is_fullpage_mode: false,
is_embedded: false,
});
});
afterEach(() => {
$(document).off();
document.body.innerHTML = '';
});
describe('minimize', () => {
it('is not offered on the desktop, where nothing could restore the window', async () => {
const el_window = await openWindow();
expect($(el_window).find('.window-minimize-btn').length).toBe(0);
const labels = headMenuLabels(el_window);
expect(labels.some((label) => label === 'maximize')).toBe(true);
expect(labels.some((label) => label === 'minimize')).toBe(false);
});
it('is offered on the dashboard, which restores the window from its tile', async () => {
window.is_dashboard_mode = true;
const el_window = await openWindow();
expect($(el_window).find('.window-minimize-btn').length).toBe(1);
expect(headMenuLabels(el_window).some((label) => label === 'minimize')).toBe(true);
});
it('hides the window in place and brings it back', async () => {
window.is_dashboard_mode = true;
const el_window = await openWindow();
const before = { top: el_window.style.top, left: el_window.style.left };
await $(el_window).hideWindow();
expect($(el_window).attr('data-is_minimized')).toBe('true');
expect($(el_window).attr('data-minimized_in_place')).toBe('1');
await $(el_window).showWindow({ no_history: true });
expect($(el_window).attr('data-is_minimized')).toBe('false');
expect({ top: el_window.style.top, left: el_window.style.left }).toEqual(before);
});
});
describe('backdrop', () => {
const backdropZ = (el_window) => Number($(el_window).closest('.window-backdrop').css('z-index'));
it('stays above ordinary windows on the desktop', async () => {
const el_window = await openWindow({ backdrop: true });
expect(backdropZ(el_window)).toBeGreaterThan(window.last_window_zindex + 1000);
});
it('stacks at the window counter on the dashboard', async () => {
window.is_dashboard_mode = true;
const el_window = await openWindow({ backdrop: true });
expect(backdropZ(el_window)).toBeLessThanOrEqual(window.last_window_zindex);
});
});
+387 -640
View File
File diff suppressed because it is too large. Load diff
-1
View File
@@ -782,7 +782,6 @@ const UIWindow2FASetup = async function UIWindow2FASetup () {
width: Math.min(480, window.innerWidth - 24),
height: 'auto',
dominant: true,
show_in_taskbar: false,
is_draggable: false,
backdrop: true,
on_before_exit: async () => {
-1
View File
@@ -215,7 +215,6 @@ async function UIWindowAuthMe (options = {}) {
width: 400,
height: 'auto',
dominant: true,
show_in_taskbar: false,
window_class: 'window-authme',
body_css: {
width: 'initial',
-1
View File
@@ -87,7 +87,6 @@ async function UIWindowBlockedSenders (options) {
width: 420,
height: 'auto',
dominant: true,
show_in_taskbar: false,
onAppend: function (this_window) {
$(this_window).find('.blocked-username').get(0)?.focus({ preventScroll: true });
},
-1
View File
@@ -68,7 +68,6 @@ async function UIWindowChangeUsername (options) {
width: 350,
height: 'auto',
dominant: true,
show_in_taskbar: false,
onAppend: function (this_window) {
$(this_window).find('.new-username').get(0)?.focus({ preventScroll: true });
const oidc_only = !!(window.user && window.user.oidc_only);
-103
View File
@@ -1,103 +0,0 @@
/*
* Copyright (C) 2024-present Puter Technologies Inc.
*
* This file is part of Puter.
*
* Puter is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import { UIColorPickerWidget } from './UIColorPickerWidget.js';
import UIWindow from './UIWindow.js';
async function UIWindowColorPicker (options) {
// set sensible defaults
if ( arguments.length > 0 ) {
// if first argument is a string, then assume it is the default color
if ( window.isString(arguments[0]) ) {
options = {};
options.default = arguments[0];
}
}
options = options ?? {};
return new Promise(async (resolve) => {
let colorPickerWidget;
let h = '';
h += '<div>';
h += '<div style="padding: 20px; border-bottom: 1px solid #ced7e1; width: 100%; box-sizing: border-box;">';
// picker
h += '<div style="padding: 0; margin-bottom: 20px;">';
h += '<div class="picker"></div>';
h += '</div>';
// Select button
h += `<button class="select-btn button button-primary button-block button-normal">${i18n('select')}</button>`;
h += '</form>';
h += '</div>';
h += '</div>';
const el_window = await UIWindow({
title: i18n('select_color'),
app: 'color-picker',
single_instance: true,
icon: null,
uid: null,
is_dir: false,
body_content: h,
has_head: true,
selectable_body: false,
draggable_body: false,
allow_context_menu: false,
is_draggable: true,
is_droppable: false,
is_resizable: false,
stay_on_top: false,
allow_native_ctxmenu: true,
allow_user_select: true,
...options.window_options,
width: 350,
dominant: true,
on_close: async () => {
resolve(false);
},
onAppend: function (window) {
colorPickerWidget = UIColorPickerWidget($(window).find('.picker'), {
default: options.defaultValue ?? options.defaultColor ?? options.default ?? '#f00',
});
},
window_class: 'window-login',
window_css: {
height: 'initial',
},
body_css: {
width: 'initial',
padding: '0',
'background-color': 'rgba(231, 238, 245, .95)',
'backdrop-filter': 'blur(3px)',
},
});
$(el_window).find('.select-btn').on('click', function (e) {
resolve({ color: colorPickerWidget.getHex8String() });
$(el_window).close();
});
$(el_window).find('.font-selector').on('click', function (e) {
$(el_window).find('.font-selector').removeClass('font-selector-active');
$(this).addClass('font-selector-active');
});
});
}
export default UIWindowColorPicker;
Loaded 100 of 226 files, more files were not shown because too many files have changed in this diff. Show more