Commit Graph
471 Commits
Author SHA1 Message Date
Daniel Salazar 0a5328bb24 fix: launch args decoded once, revoked sessions off the list, per-session socket eviction, writes into respelled folders, read URLs through folder access (#4752)
Backend Tests / changes (push) Canceled after 0s
Backend Tests / typecheck (push) Canceled after 0s
Backend Tests / test shard 1/4 (push) Canceled after 0s
Backend Tests / test shard 2/4 (push) Canceled after 0s
Backend Tests / test shard 3/4 (push) Canceled after 0s
Backend Tests / test shard 4/4 (push) Canceled after 0s
Backend Tests / test (main) (push) Canceled after 0s
Backend Tests / coverage (push) Canceled after 0s
Benchmarks / changes (push) Canceled after 0s
Benchmarks / bench shard 1/3 (push) Canceled after 0s
Benchmarks / bench shard 2/3 (push) Canceled after 0s
Benchmarks / bench shard 3/3 (push) Canceled after 0s
Benchmarks / benchmarks (push) Canceled after 0s
Notify HeyPuter / notify (push) Canceled after 0s
* fix: decode puter.args once and keep just-revoked sessions off the session list

* fix(socket): a session revoke drops only that session's sockets; the GUI reconnects after a server disconnect

* fix(fs): a write into a folder spelled in another case or form lands under the folder's stored path

* fix(auth): access tokens for fs: scopes accept access held through a parent folder

* docs(changelog): read URLs through folder access and writes into respelled folders

* style: format

* fix: address review — stored paths for created parents, batch alias dedupe, uid-only ACL mint, scoped socket eviction fallback, events suites

* test(fs): build the legacy respelled-descendant rows directly

* fix: address second review — refuse duplicate overwrite targets before upload, reuse ensured folders, check stored path length, match created folders by entry, decode a doubly encoded API origin

* docs(changelog): file this PR's entries under its merge day
2026-11-22 13:40:24 -07:00
Hanad Hassan 8cd680fb60 fix(ai): the Responses route gives a streamed function call its arguments in the finished item
The Responses route asks the driver to stream tool input, so every
function call starts with tool_use_start, even from an upstream that
sends the call whole. The route added each call to the response output
with empty arguments and sent the pieces only as
function_call_arguments.delta events. The items in
response.output_item.done and in the output of response.completed kept
arguments "", so a client that reads the finished response rather than
the deltas, such as the OpenAI SDK's finalResponse() or the Agents SDK,
got every streamed tool call with no arguments.

When the call ends, its item now takes the arguments the route collected
for it, before the done events are sent.
2026-11-21 18:59:43 -07:00
Daniel Salazar 5b8e0576fd feat(auth): the SMS-to-card fallback follows what the account owes (#4748)
A card stands in for the phone step only on an account that neither owes a
card nor has verified one. A number on file is still stood in for by the card
on file. An account that owes both keeps both steps.

`puter.phone-verification.check` gains two optional fields:

- `countsTowardFallback: false` keeps a refused send out of the count that
  opens the fallback. Refused sends count by default, as before.
- `refuseWithoutFallback` keeps a `card_fallback_instead` refusal in place
  when there is no fallback to offer, instead of letting the send through.

GUI: a message for a card the verification doesn't accept, and the
virtual-number message no longer mentions a card (the card link shows on its
own when one is offered).
2026-11-21 15:45:32 -07:00
Daniel Salazar 78a7400c98 feat(auth): an extension can switch the SMS-to-card fallback on or off over config (#4747)
Adds the puter.card-fallback.policy event, asked before
phone_verification_card_fallback.enabled is read. A listener that sets
enabled decides in place of config; with none, config decides as before.
2026-11-21 14:41:15 -07:00
Daniel Salazar af15ba8bfb feat(auth): proof on file signs out other sessions; a sign-in reads the team seat once (#4719)
* perf(auth): a sign-in reads the team seat once; validate event carries request signals

- The seat a sign-in reads for its listeners is handed to the account
  payload it builds afterwards, instead of being read again: one cache read
  and, for an account with no seat, one database read fewer, and two fewer
  serial stages.
- puter.signin.validate carries `request_signals`, every signal the edge
  proxy raised on the request.
- A card step on an account that already has a card asks for that card,
  entered again, the way a number on file asks for its number.

* feat(auth): proof of the phone or card on file belongs to the session that gives it

A sign-in made while the account owes proof of its phone or card on file
doesn't have its device remembered, and its session is noted. When a
session proves the phone or card, its device is remembered then, and every
other session opened while the proof was owed is revoked before the gate
clears, so clearing it from one session can't let another one in.

* fix(auth): proving the phone or card on file signs out the account's other web sessions

The proving session keeps its sign-in and is the only device remembered. A
sign-in that completes after the proof was given is not kept and is asked to
sign in again. If the other sessions can't be signed out, the gate goes back
on and the request fails.

* fix(auth): other sessions are signed out before the on-file gate clears; the phone proof counts for its sign-in

Proving the phone or card on file signs the account's other web sessions out
before the gate clears and again after it, so a session never sees the gate
open. Only the gates the request cleared go back on if the second pass fails.
The proof that allows an email change while the address is pending is kept
with the sign-in that gave it. A sign-in that isn't kept sets no session
cookie, and a provider sign-in in that case returns to its page.

* fix(auth): a gated sign-in checks the gate after its device id is kept

The check is the last step before the session cookie is set. Tests assert the
order of the gate writes and that a provider sign-in that isn't kept leaves no
session.
2026-11-20 11:23:07 -07:00
Daniel Salazar 59524cc580 feat(auth): phone on file step, email replacement while unconfirmed, no lock without email (#4707)
Benchmarks / changes (push) Canceled after 0s
Benchmarks / bench shard 1/3 (push) Canceled after 0s
Benchmarks / bench shard 2/3 (push) Canceled after 0s
Benchmarks / bench shard 3/3 (push) Canceled after 0s
Benchmarks / benchmarks (push) Canceled after 0s
Backend Tests / changes (push) Canceled after 0s
Backend Tests / typecheck (push) Canceled after 0s
Backend Tests / test shard 1/4 (push) Canceled after 0s
Backend Tests / test shard 2/4 (push) Canceled after 0s
Backend Tests / test shard 3/4 (push) Canceled after 0s
Backend Tests / test shard 4/4 (push) Canceled after 0s
Backend Tests / test (main) (push) Canceled after 0s
Backend Tests / coverage (push) Canceled after 0s
Notify HeyPuter / notify (push) Canceled after 0s
* feat(auth): phone on file step, email replacement while unconfirmed, no lock without email

- Phone gate on an account that already has a number: /send-confirm-phone
  sends the code to that number and ignores any other, /confirm-phone checks
  only that number, and `lostNumber: true` opens the card fallback (409 when
  there is none). The send response and whoami carry `phone_on_file`, the
  number's last two digits; the phone window drops the number field for it.
- /user-protected/change-email runs while the email code is pending, with
  every other gate still applied, for an account with a verified phone,
  card, paid plan or second factor; otherwise the code is still required.
  Provider-only accounts keep the code. Confirming the replacement runs the
  same side effects as confirming the code. The email window gets a step
  for it.
- The per-account wrong-password lock skips accounts with no email; the
  failures still count and alarm.
- puter.signin.validate carries `credential_exposed`.
- GUI gate flows read the account again between gate windows and before
  opening one.

* feat(auth): a number on file is stood in for only by the card on file; two codes a day

- The card fallback for a phone on file opens only when the account already
  has a card, and confirming it clears the phone step only when the card's
  fingerprint matches the one on file (`card_not_on_file` otherwise).
- Codes to a number on file: two per account per day; past that the route
  answers 429 `phone_on_file_send_limit` and offers the card on file.
- Phone window drops the signup help line in on-file mode; the email
  window's footer no longer shows a stray separator in the change step.

* feat(auth): replacing an unconfirmed email takes a factor the account had before

A phone or card first verified while the address is unconfirmed is recorded
in the account's metadata (`factorsAddedWhileEmailPending`), before it is
stored, and no longer counts toward /user-protected/change-email. A number
on file proven again and the card already on file still count, as do a
second factor and a paid plan. The route no longer asks for a new factor;
with none from before it answers `email_confirmation_required`, and the
email window says the code is needed.

* feat(auth): email replacement and the card stand-in each take proof in hand

- Replacing an unconfirmed email: a dormant sign-in records, once, the
  number the account had (`phoneAtDormantSignIn` in metadata). The change is
  allowed only when the account still has that number and proved it within
  the hour, by its code or by the card on file; otherwise the route starts
  the phone step for it, or answers `email_confirmation_required`. A phone
  or card merely being on the account, a paid plan, and a number or card
  verified since no longer count. This replaces the list of factors added
  while unconfirmed.
- Card confirmation while a number on file waits: only the card already on
  file verifies, under any gate order. The confirm event carries
  `required_fingerprint`, and the listener reports `card_entered` (details
  typed for this confirmation, not a saved card or an old confirmation);
  both are checked.
- A card fallback opened earlier no longer offers a card to an account whose
  number on file has no card to stand in for it.
2026-11-19 23:28:35 -07:00
Daniel Salazar bfcacc8469 fix(db): bound numbers must be safe integers; path, cursor and lookup input checks (#4708)
* fix(db): bound numbers must be safe integers; path and cursor input checks

Bound numbers outside ±2^53 (including NaN and Infinity) are refused with a
400 by every database client.

- Paths longer than 4096 characters are refused with a 400.
- The path lineage lookup returns null for paths deeper than its walk
  without querying.
- The read batcher's circuit breaker counts a failed fallback flush only
  when an item could not reach the database.
- App, subdomain and worker list cursors must carry a non-negative integer
  id.
- App stats grouping accepts only its own keys.
- App batch lookups skip values of the wrong type, and app writes refuse
  keys that are not column names.
- User, notification, durable subscription and KV share handle lookups
  return no row for values of the wrong type.
- OIDC links are looked up by the sub as a string.
- User-to-user and group permission reads keep exact matches only.
- revoke-dev-app validates its parameters like grant-dev-app.
- A durable subscription's expiresAt must be before the year 10000.
- Installed apps paging reads page and limit as whole numbers.

* fix(db): review follow-ups for input checks

- The path length check measures the canonical absolute path, after the
  leading slash is added and a trailing one dropped.
- The lineage lookup handles up to 500 segments, SQLite's compound select
  limit.
- Group permission reads keep matching by the column's collation.
- A server error code is never read as a lost connection from its message.
- Cursor ids must be integers or digit strings, and a cursor that is
  neither a string nor an object is refused.
- OIDC links store the sub as a string, matching lookups.
- findEmailOwner returns no row for a value that is not a string.
- Invalid stats groupings and non-string or non-number expiresAt values
  return a 400.
- Installed apps limit clamps before rounding down.
2026-11-19 15:19:28 -07:00
Nariman Jelveh 8955253e2f feat(gui): app launches say what the user did and which page sent them (#4697)
Apps get `utm_content` set to how the user opened them: `app_icon`,
`file_open`, `open_with` or `file_drop`. Apps opened from the app browser
embed get the framing page's host as `utm_source`, which the server reads
from the same referrer check that pins `frame-ancestors`.
2026-11-19 09:40:36 -07:00
Daniel Salazar 442a50baed fix(auth): user lookups match only string and number values (#4698)
UserStore.getByProperty returns null for a value that is not a string or a
number, so an array or object from a request body never reaches the query.
POST /send-pass-recovery-email answers 400 for a username that is not a
string; it answered 500 for an array.
2026-11-19 09:13:16 -07:00
Daniel Salazar 6b8af52077 feat(auth): sign-in pipeline, per-account wrong-password budget and idle session expiry (#4692)
Sign-in
- One sign-in path (SignInService) for password, 2FA, recovery code, signup
  and OIDC. It emits puter.signin.attempt (before the account lookup on
  POST /login), puter.signin.validate (before the session is created) and
  puter.signin. Listeners can refuse or require phone or card verification; a
  listener that throws is ignored.
- POST /login keeps a wrong-password budget per account across all networks,
  20 an hour and 50 a day. A browser that has signed in to the account before
  is not refused, and the budget belongs to the current password.
- An account unused for dormantSignInDays (default 180) confirms an
  unconfirmed email at sign-in, where the deployment can send mail.
- New account emails: sign-in from a new browser, sign-in attempts blocked,
  password reset completed.
- pwnedPasswords (off by default): a k-anonymity range lookup after a
  successful password sign-in, with a notice to the owner.
- requestSignalHeaders and requestSignalValue turn configured request headers
  into req.requestSignals and a puter.request.flagged event.

Sessions
- web and app sessions end after 180 days without activity; accounts with no
  password and no email keep 365 days. A missing expiry on web, app and asset
  rows no longer means no expiry, and ended rows are purged.
- The cookie a private hosted site sets from ?auth_token= is tied to the
  token's session row and carries a 7-day expiry.

Email confirmation codes
- A 6-digit code is valid for 60 minutes and has a wrong-code budget.

Mailbox ingress
- email.ingress.validate runs before a message is stored; a listener can refuse
  it or record a sender check. X-Puter-Sender-Auth is written by the server
  only. Header blocks over 256 KiB are refused.

GUI
- Login sends the device fingerprint, can show the captcha widget
  (gui_params.turnstileLogin), offers a password reset when sign-in is locked,
  and runs pending verification windows after a popup sign-in or signup.
2026-11-18 23:02:16 -07:00
Nariman Jelveh e62418f7a9 fix(thumbnails): files edited or written by apps get a thumbnail in the dashboard (#4691)
* fix(thumbnails): files edited or written by apps get a thumbnail in the dashboard

An overwrite clears a file's thumbnail and nothing made a new one, so a file
an app saved over lost its picture, and files apps created never had one.

The dashboard now makes a thumbnail for a file with none as its row comes
into view, with the upload thumbnail generator, within budgets on size,
downloads at a time, files per minute, and bytes per page load. A version
that gives no thumbnail is remembered so it isn't downloaded again.

/update-fsentry-thumbnail takes an optional expectedModified and refuses a
thumbnail made from an older version with 409, tells the owner's other
clients about the new thumbnail, and has its own rate-limit scope instead of
sharing the one opening a file uses. Overwrites and replacements emit
thumbnail.discarded, and the thumbnails extension deletes the object behind
it, so replaced thumbnails no longer stay in the bucket.

* fix(thumbnails): expectedModified must be a whole number of seconds the column can hold

A fraction or a value past the column's range reached the UPDATE, which
Postgres refuses with an error after the thumbnail was already uploaded.
The route now answers 400 before it uploads anything.

* fix(thumbnails): setting a thumbnail keeps the current one when the new one can't be stored

The route stored whatever the thumbnail.created listeners left behind:
a pointer whose upload failed, or the null left for an image that can't
be decoded. Either replaced a working thumbnail and answered 200. It now
answers 500 or 400 and leaves the entry as it was.

* fix(thumbnails): the update announced after setting a thumbnail carries the entry's current name and path

The event was built from the entry read before the thumbnail was
uploaded, so a rename or move that landed during the upload was
announced with the name and path it had just replaced, and open clients
put the row back on a path that no longer exists. The entry is read
again after the thumbnail is stored.

* fix(thumbnails): a file that stops needing a thumbnail is no longer downloaded for one

A file waiting its turn, or already downloading, was still read and its
thumbnail stored after another tab had made one, or after the file was
saved again as something the generator can't read. A queued file is now
checked again before its download starts, and a change that makes the
thumbnail unwanted drops the queued job and cancels the download.

* fix(thumbnails): refreshing the folder on screen keeps its thumbnail downloads

A refresh of the folder on screen (a sort, a view switch, an upload
finishing, coming back to the tab) cancelled the downloads under way.
The rows drawn right after were skipped, because their files still
counted as being tried, so they stayed without a thumbnail until some
later render. The rest were downloaded again from the start.

A download is now cancelled only if its file's row isn't drawn again in
the same task, and the new row takes it over. A row that comes back
while a cancelled download is still ending is queued again.

* fix(thumbnails): a stored thumbnail is recorded on the row's own entry

The filler handed its callback a copy of the row's entry, so the
thumbnail was written to an object nothing else reads, and the row's
entry kept saying the file had none. It now passes the row's entry, and
skips a row whose file was saved again while the thumbnail was being
stored, which would otherwise show the older version's picture.

* fix(thumbnails): the download budget counts the bytes that were downloaded

A cancelled download gave its whole size back to the page's download
budget, though the bytes it had received were already billed as egress.
A file saved over and over while its row was on screen could be started
again each time, well past the budget. A download the server refused
kept its size charged with nothing downloaded.

The file is now read as a stream and the budget is charged what arrived.
Reading also stops as soon as a file turns out to be over the size cap,
where before a file larger than its listed size was buffered whole.

* fix(thumbnails): a thumbnail download that fails to connect is tried again

A download that failed on the network counted as tried, so the file went
without a thumbnail for the rest of the page load. A laptop waking before
its Wi-Fi is back marked every row on screen that way. A failed
connection now pauses the filler like a 429 does, and the file is tried
again after the pause.

* fix(thumbnails): a thumbnail that couldn't be stored yet is sent again, not made again

When storing a thumbnail got a 429, the file was queued again and
downloaded a second time after the pause. When the request failed to
connect, the thumbnail was dropped and the file went without one. The
thumbnail is now kept with the queued job and sent again after the
pause, as long as the file is still at the version it shows.

* fix(thumbnails): a file whose thumbnail the server refuses isn't downloaded again on every page load

When the server answers 400 for a thumbnail, the file's version is now
remembered like one that gave no thumbnail at all. It counted as tried
for the page load only, so each later page load downloaded the file and
sent the same image again.

* fix(thumbnails): only pictures a browser can draw are downloaded for a thumbnail

Any file typed image/ counted as one the generator reads, so TIFF scans,
CAD drawings, DjVu books and the like were each downloaded in full, up
to 20 MiB, to make a thumbnail no browser can draw. A file is now
downloaded only when its type or name is one browsers decode. Uploads
are unchanged: the generator still tries any image there, where the file
is already local.

* fix(thumbnails): missing thumbnails are downloaded one file at a time

Each download holds one of the account's concurrent file reads until it
ends. Two at a time left a temporary account, which has three, a single
read for everything its apps do, so an app reading two files at once got
a 429 while a folder's thumbnails were being filled in. The per-minute
cap of 20 files already bounds how fast they're made.

* fix(thumbnails): an update refreshes the icon of every item it matches

An update can match the Files row and the same item in a file dialog
open over the dashboard. The row updater set the new thumbnail on the
first match only, where it used to set it on all of them.

* perf(thumbnails): an update works out a row's icon again only when its thumbnail changed

Every update event carries a thumbnail key, so the row updater worked
out the icon on each one. For a .app file or a web link that reads the
file, once per event. The icon is now refreshed only when the event's
thumbnail differs from the one the row has.

* perf(thumbnails): drawing a large folder doesn't rescan the thumbnail queue for every row

Each row handed to the filler went through every row queued before it,
looking for a job to start, so drawing a folder of files without
thumbnails took the square of its length: about a second for 20,000
rows. A row that isn't on screen yet has nothing to start, so the queue
is now only gone through when a row is reported on screen, a job ends,
or a wait is over.

* fix(thumbnails): one tab no longer drops the failed files another tab remembered

Each tab read the list of files that gave no thumbnail once, then wrote
its own copy back whole on every addition, which dropped whatever
another tab had added in between. Those files were downloaded again on
a later page load. The stored list is now read again and merged before
each write.

* perf(thumbnails): files downloaded for a thumbnail stay out of the browser's HTTP cache

The download asked the cache to revalidate, which still writes each
response to it, up to 100 MiB of originals per page load that nothing
reads back. The read route doesn't answer conditional requests, so a
cached copy could never save a download either.

* bench(thumbnails): scenario for setting a file's thumbnail from the dashboard

The dashboard calls the route for each file it fills in a thumbnail
for, up to 20 a minute, so its round trips are measured from here on.

* docs(thumbnails): list the picture formats downloaded for a missing thumbnail

* perf(thumbnails): setting a thumbnail reads the entry again alongside the write, not after it

The read that keeps the announced name and path current ran after the
update, which added a serial round trip to the route. It now runs with
the update. The window it closes is the upload before both.

* feat(thumbnails): a file saved over keeps showing its old thumbnail until the new one is ready

A save cleared the row to its type icon for the few seconds it takes to
make the new thumbnail, so a file an app saves repeatedly flashed
between the two. The row now keeps the old thumbnail while a new one is
on its way.

It goes back to the type icon at once when no thumbnail will be made
(the file is too large, the download budget is spent, the filler is
paused), as soon as the attempt fails, and after 10 seconds at most,
counted from the first save, so an old picture can't stay on a file
that keeps changing.

* fix(thumbnails): a document gets its thumbnail when the view goes to the list and back while it's made

A list row shows a document's type icon, so switching to the list gave up
on the thumbnail being made for it. Switching back before that ended found
the version already tried and queued nothing, and the row kept its type
icon until the folder was drawn again. The row now takes the job back.

* fix(thumbnails): a file being saved waits to settle whatever the computer's clock says

The wait before a saved file is downloaded was measured from its modified
time, which the server sets, against the browser's clock. On a computer
whose clock runs a few seconds ahead the wait came out as zero, so every
save of a file an app keeps saving started a download that the next save
cancelled. A file an update just arrived for now waits at least two
seconds, the least it waits when the clocks agree.

* fix(thumbnails): an item in a file dialog gets a new thumbnail when its folder isn't the one on screen

The row updater only set a thumbnail through the entry a Files row
carries. An update for a file shown only in a file dialog, with another
folder open in Files, matched an item that has no entry, and the item
kept the picture it had.

* refactor(thumbnails): the row observer asks for no margin around the screen

The 200px margin never took effect. The rows scroll inside the listing's
own pane, and a margin on the viewport doesn't widen what that pane clips,
so a row was only ever reported once it was on screen. That's also what
the download budget is written for, so the option goes rather than being
made to work.

* test(thumbnails): a version tried once, a hidden tab, and a browser saving data

Three of the filler's cost guards had no test: a version whose thumbnail
the server turned away isn't downloaded again in the page load, nothing
starts while the tab is hidden, and nothing is downloaded when the
browser asks to use less data.
2026-11-18 18:58:43 -07:00
Daniel Salazar 6478f18feb perf: whoami row reuse, thumbnail URL cache, KV refusals, dashboard KV boot batch, profile revalidation (#4687)
* perf(whoami): answer from the user row token auth already loaded

Token auth builds the actor from the user's row with the password hash left
out. It now records `hasPassword` in its place, so /whoami builds the details
(`oidc_only`, `is_temp`) from the actor and skips reading the same row again
by id. An actor built any other way still reads the row.

* perf(thumbnails): reuse a read URL signed this hour

A thumbnail's read URL is the same for the whole signing hour, so listings
re-signed it for nothing. Signed URLs are kept per signing client, keyed by the
signing key, bucket, object key and hour (5,000 entries, one hour). A new
signing key signs afresh.

* perf(kv): a refused conditional write ends at the refusal when it can

`set` with `onlyIfAbsent` on a live key, and a write or delete into a
foreign namespace refused by a private entry, made four store calls: the
refused write, a refused expired-row delete, a consistent read and a second
refused write. The conditional write now asks for the refusing item. When its
`ttl` is absent, null or a number, the condition already judged it the way
reads do and the refusal stands after one call. A text or boolean `ttl`, or a
refusal without the item, still settles and retries as before.

* perf(gui): the dashboard reads its saved settings in the boot batch

The GUI's boot KV batch fetched the desktop's keys on every boot, while the
dashboard read its seven (Files view and sort, Apps order, groups and
uninstalled list) one request each. The batch now carries the keys of the
interface that booted. The uninstalled-apps read-modify-write skips the batch,
which may predate another window's write.

* perf(profile): answer a revalidated GET /profile without reading it

A profile write records a hash of the stored JSON in the file's metadata.
GET /profile sends it as the ETag with `Cache-Control: private, no-cache`
and answers a matching If-None-Match with 304 before reading the stored
profile. Visibility is checked first, so a hidden profile still 404s. A
profile stored before this has no tag until its next write.

* fix(thumbnails): a listing's concurrent signings share one URL cache

The per-client cache was registered after the first signing returned, so a
cold client's first listing kept only one of the URLs it signed.

* fix(kv): recheck a refusing row's expiry and its private flag

A numeric `ttl` that passes while the refusal is on its way now settles and
retries, as before, instead of answering false. A share holder's refused
`onlyIfAbsent` takes the private flag from the refusing item rather than an
eventually consistent read after it. DDBClient tests cover the request and
the undecoded item on the wire.

* fix(gui): Apps refreshes read the saved layout from the store

Only the open's first load takes it from the boot batch. A refresh exists to
pick up another tab's changes, which a batch fetched a few seconds earlier can
predate.

* fix(profile): tag a profile response by the bytes it carries

The file is written before its entry and the entry can be read from a cache
that is behind, so a 200 now carries the tag of what was read. Tags are weak
(the compressed and plain bodies share one) and the early 304 sends
`Vary: Accept-Encoding` like the 200. A profile stored without a tag still
answers 304 to its content tag, after reading the file.

* fix(kv): the GUI boot batch only answers for the token it was fetched with

A sign-in from another tab swaps the token while the batch is still live, so
reads under the new account fall through to the store.
2026-11-18 14:30:29 -07:00
Daniel Salazar bc73cde987 feat(alarms): channel keys, and calls an uptime monitor can poll (#4672)
* feat(alarms): channel keys, warning in chat, and calls an uptime monitor can poll

- `create(..., { channel })` names the area that owns an alarm; config maps
  keys to Slack channels (`pager.slack.channels`), unmapped keys post to the
  default channel. `HttpError` takes `alarmChannel`, and the upstream_* codes
  the error gate forces go to `ai_providers`.
- Slack can post with a bot token (`chat.postMessage`), which reaches any
  channel and links a call to its message; the webhook stays as a fallback.
- Defaults: PagerDuty takes `error` and up, Slack takes up to `warning`.
- `pager.calls.rules` maps alarm ids or prefixes to call groups. A matching
  alarm is recorded in system KV until it has been quiet for `ttlMs`;
  `GET /alarms/calls?group=` (internal-auth secret) answers 503 while one is
  active, with a short plain-text body linking each call's chat message.
- Core alarms retiered: non-urgent `warning`s become `info` with a channel;
  critical and error alarms are unchanged.

* fix(alarms): keep warning on the pager; calls link to where the alarm landed

- PagerDuty takes `warning` and up again, and Slack stays at `info` when a
  pager exists: `warning` is the low-urgency pager queue, `info` is chat.
- An alarm that calls is no longer also posted to Slack. Its link comes from
  the transport that took it: the Slack message, or the PagerDuty incident,
  looked up with the new `pagerduty.apiToken` (REST, read-only is enough).
- The PagerDuty transport moves to its own module.
2026-11-17 22:40:29 -07:00
Daniel Salazar 6b7541d0b6 fix: AuthMe relay names, write size caps, worker teardown on uninstall, and fewer share, cache and whoami round trips (#4683)
* fix(auth): AuthMe reads forwards_to only from configured relays and never redirects onto the GUI

The authorization dialog names the host in `forwards_to` only when the
redirect's origin is listed in the new `authmeRelayOrigins` config, rather
than for any host under the deployment domain. An AuthMe request whose
redirect lands on the GUI's own origin is refused before the dialog opens,
since GUI pages pass their query on to whatever they launch.

* fix(fs): hold direct writes to their declared size or the owner's free storage

Writes that stream straight onto a file's object (`/fs/write`,
`/fs/batchWrite`, WebDAV PUT and signed `/writeFile`) now cap the body
before it is stored:

- A stream that declares a size fails with 400 once more bytes arrive than
  it declared, and the upload is aborted.
- A stream that declares 0 (a chunked WebDAV PUT, `/writeFile`, a multipart
  part sent with size 0) is capped at the owner's free storage and fails with
  413 past it. Parts of one batch share that allowance.
- A body of known length that is longer than declared is checked against
  the owner's free storage before the upload instead of after.

A refused overwrite leaves the stored file and its recorded size unchanged.
A new file whose write fails after its upload has its object deleted. The
last chunk of a capped stream is held until the body ends, so the store
never completes an upload that later turns out too long, and a PutObject is
aborted when its streamed body fails.

* fix(workers): uninstalling an app takes down its workers in the account

The workers an app runs in a user's account, and those bound to apps it
created there, are deleted when the user uninstalls it: script, sessions and
row. A redeploy of any kind (hot reload, unsuspension, an edge redeploy of an
evicted script) reads the row's app, so with the row gone none of them can
mint a token for the uninstalled app again. A worker bound to an app the user
owns is kept. When the edge can't delete the script, the row is still
removed and the script delete is retried in the background.

* perf(share): withdraw a share's access modes in one revoke

Withdrawing a share revoked each of the five access modes on its own, every
one a delete, a primary re-read and a cache bump in series. It now uses the
batch revoke: one delete, one re-read and one bump, with each removed
permission still audited and announced. A file's withdrawal also skips the
subtree scan for re-shares managed below it, since a file has nothing below
it. Adds a benchmark scenario for withdrawing a file share.

* perf(puter-js): an update to a file drops only that file from the FS cache

`item.updated` for a file now removes its cached entry and its folder's
listing, including an entry still cached under the file's old path, since
a rename arrives as an update naming only the new path. An update to a
directory still clears the whole cache. Before, any file overwrite cleared
the whole cache, and the desktop then re-read its warm folders.

* perf(puter-js): the desktop handing back its own token reads the user once

In the GUI environment, `setAuthToken` with the token it already holds no
longer re-reads `/whoami` when the user was read with that token and API
origin, or a read is still in flight; `puter.os.user()` there keeps what it
reads as `puter.whoami`. The auth-state change and its cache check still
run. The desktop merges the user it stores into `puter.whoami` when the token
is unchanged, so an account saved under a new username shows up there.
Other environments behave as before.
2026-11-17 20:56:45 -07:00
Nariman Jelveh 037ba9b214 refactor(gui): /action/change-username redirects to the dashboard's Account tab, and its desktop window is removed (#4665)
The desktop's change-username window was only reachable from
/action/change-username, which nothing links to. The dashboard's Account
tab has its own change-username dialog. Old links now redirect there.
2026-11-16 13:18:01 -07:00
Juan Fernando CastroandDaniel Salazar b85c04d49a fix(redis): a command that gets no answer rejects after a timeout, and commands fail fast while Redis is stalled (#4656)
Backend Tests / changes (push) Canceled after 0s
Backend Tests / typecheck (push) Canceled after 0s
Backend Tests / test shard 1/4 (push) Canceled after 0s
Backend Tests / test shard 2/4 (push) Canceled after 0s
Backend Tests / test shard 3/4 (push) Canceled after 0s
Backend Tests / test shard 4/4 (push) Canceled after 0s
Backend Tests / test (main) (push) Canceled after 0s
Backend Tests / coverage (push) Canceled after 0s
Benchmarks / changes (push) Canceled after 0s
Benchmarks / bench shard 1/3 (push) Canceled after 0s
Benchmarks / bench shard 2/3 (push) Canceled after 0s
Benchmarks / bench shard 3/3 (push) Canceled after 0s
Benchmarks / benchmarks (push) Canceled after 0s
Notify HeyPuter / notify (push) Canceled after 0s
* fix(redis): a command that gets no answer rejects after the configured timeout

redis.commandTimeoutMs (default 2000) arms a per-command timer on the
cluster client, so a command sent to a node that never replies, or queued
while the cluster is not ready, rejects and the caller takes its error
path. Blocking commands and duplicate() clients are left without it.

* fix(broadcast): a failed pubsub publish or subscribe is logged, not left unhandled

With command timeouts, a stalled publish now rejects; the fan-out is
fire-and-forget, so the rejection is caught and logged. The sign-in relay
test pins that /login/set still reaches a subscribed /login/wait when
Redis never answers.

* fix(permissions): a scan cache read that Redis fails to serve counts as a miss

The scan then computes from the store, as the generation and per-check
cache reads already do, instead of failing the permission check.

* refactor(redis): isCommandTimeout names the rejection of a timed-out command

Callers that issue a write can recognise the timeout and queue its undo
on the same key. Also notes that a timed-out command is not withdrawn,
restores the console spies in the timeout tests, and drops formatting
churn in types.ts.

* fix(metering): an increment whose buffering timed out is counted once

On a timeout the write-through runs and the buffered copy is negated on
the same keys, so if the timed-out increment lands later the next flush
nets it out. incr and incrAux both do this.

* fix(rate-limit): a concurrency slot whose acquire timed out is removed

The ZREM goes to the same key behind the timed-out MULTI, so a slot that
lands late does not stay held until the orphan window.

* fix(uploads): leases whose take timed out are released

The release goes to the same keys behind the timed-out take, so leases
that land late do not count against the owner until their deadline.

* fix(redis-lock): a claim that timed out is released if it lands

The token-checked delete goes to the same key behind the timed-out SET
NX, so a late claim does not hold the lock for its full TTL.

* fix(broadcast): a rejected pubsub subscribe is retried with backoff

Retries start at 1s and cap at 30s, and stop once the service shuts down.

* refactor(redis): isCommandTimeout lives in its own module

Stores, the rate limiter and the lock helper recognise a timed-out
command without importing the client.

* fix(credit-holds): a hold whose take or reserve timed out is released

The release goes to the same key behind the timed-out script, so a hold
that lands late does not shrink the spendable budget for its TTL.

* fix(metering): a write-through answers without waiting on its undo

The undo's place in the queue is fixed when it is sent, so the request
no longer waits on it. When the undo itself times out, the warning says
the increment may be counted once more or not at all.

* fix(broadcast): a pubsub subscribe retry checks the client is still current

A retry that fires after shutdown no longer subscribes the closed client.

* feat(redis): after a timeout, commands fail fast until a probe gets a reply

For redis.failFastMs (default 5000) after a command times out, other
commands reject unsent with 'Redis unavailable', so a stall costs a
request one timeout instead of one per call. After each interval one
probe is sent; a reply, or the cluster becoming ready, ends it. Commands
sent through sendAsUndo, blocking commands, CLUSTER commands and
duplicate() clients are not held back. A pipeline is admitted or
rejected as a whole.

* fix(redis): undos of a timed-out command are sent while failing fast

The metering negation, slot ZREM, upload and credit-hold releases and
the lock's token-checked delete go through sendAsUndo, so they still
queue behind the original that may land. A command rejected unsent is
not a timeout, so it triggers no undo.

* test(auth): the sign-in relay completes within one command timeout under a stall

/login/set and /login/wait against a cluster whose node never answers
now finish in about one timeout, since calls after the first fail fast.

* style(redis): one-line comments, and types.ts keeps its existing formatting

* fix(redis): releases are sent while failing fast and not waited on

The lock release, concurrency-slot release, credit-hold release and
upload-lease release and settle go through sendAsUndo, so resources
taken before the breaker opened are freed rather than held for their
TTL. They are sent without awaiting; later commands on the same key
queue behind them. The KV and memory slot backends are still awaited.

* fix(redis): a retried pipeline is timed again, and only replies end failing fast

Pipeline commands whose error reply cleared their timer are re-armed when
the pipeline resends them after MOVED, ASK or a closed connection, and
the ASKING command it adds is always admitted. Only a reply, including an
error reply, counts as an answer: a closed connection or an ended cluster
no longer ends failing fast.

* fix(rate-limit): window take-backs are sent while failing fast, and a release never rejects

The ZREM or DECRBY that takes back a denied window charge goes through
sendAsUndo without being awaited, and the request is still denied. A slot
release that throws synchronously is logged, not rejected, and the
release() doc says when it settles.

* fix(broadcast): a publish failing fast warns once per stretch, not once per event

Warnings for publishes rejected with 'Redis unavailable' are skipped
until a publish succeeds again; other failures still warn every time.

* test(redis): timing bounds name their command timeout and leave CI headroom

The relay test sets a 1000 ms timeout and checks it finishes within one
timeout rather than two; the release timing bound is 250 ms.

* style(broadcast): shorter comment on the publish warning

* fix(metering): the cached base is dropped while failing fast, without waiting

forgetBase sends its DEL through sendAsUndo, so after a write-through it
still queues behind the timed-out increment and its undo instead of being
rejected unsent. incr no longer awaits it on the request path; the
MeteringService callers still do.

* fix(redis): a command rejected while failing fast is handled, so one nobody awaits can't end the process

* style(types): unrelated interfaces keep the formatting lint expects

* fix(cache): invalidations are sent while failing fast, so a write during a stall doesn't leave the old entry cached

---------

Co-authored-by: Daniel Salazar <daniel.salazar@puter.com>
2026-11-16 09:20:13 -07:00
Neal ShahandClaude Opus 5.5 237ff84cc5 feat(hosting): sites list their custom domains, and hosting.detach() removes them (#4651)
* feat(hosting): sites list their custom domains, attach names a moved domain's old site, and hosting.detach() removes domains

- puter-subdomains read/select return `custom_domains` ({ uuid, hostname,
  status }) per site, filled by a `site.customDomains` event listener. Only
  rows attached under the site's current owner count; the field is left out
  when the listener fails, so a failed lookup never reads as "no domains".
- The attach dialog's answer carries `previousSite` when the user moved the
  domain from another site, kept through a status check or switch to www.
- puter.hosting.detach(subdomain) opens the custom domain dialog in a
  remove-only mode (desktop message, frame, or popup) and resolves the
  domains the user removed, or []. Desktops advertise it as
  `custom-domains-detach`; older ones reject with not_supported.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(workers): expect the sandbox-owner message create() throws now

create() rejects another user's sandbox app with "The sandbox app '…'
belongs to another user…" since the workers name-cap fix; the deploy test
still expected the old wording and failed on main.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 21:02:07 -05:00
Neal ShahandClaude Opus 5.5 e7bc94029c fix(workers): name length cap, sandbox app freed on delete, no app opens from workers (#4631)
- Worker names are capped at 50 characters, the most a `workers.puter.<name>`
  subdomain row holds. A longer name is a 400 before any token is minted,
  instead of a 500 from the insert. The publish dialog caps at 50 too.
- Deleting a worker deletes its `sandbox-<name>` app when nothing else runs
  as it, so the name can be reused by another user. A sandbox app owned by
  someone else rejects with `sandbox_not_owned` instead of a TypeError.
- POST /rao records nothing for a worker or events handler actor, and the
  worker runtimes' clients no longer ask.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 00:28:31 -05:00
Daniel Salazar 9ca1acf634 Benchmarks that gate PRs on I/O regressions, wider test baseline, and npm run check (#4644)
* feat(bench): backend benchmarks that fail a PR for waterfalled or uncached I/O

A scenario runs a request against the in-memory backend and records every
SQL, key-value, Redis and object-storage round trip on a modeled clock, then
reports round trips per destination, serial stages and modeled latency.
tools/bench.mjs runs the scenarios on a base commit and on the head and fails
on a regression the pull request description does not accept; benchmarks.yaml
runs that on every pull request.

Also adds npm run check (lint, type check, related tests and the benchmark
comparison for the files a branch changed) and describes the distributed
deployment in AGENTS.md.

* test(bench): scenarios for fs, kv, auth, apps, permissions, sharing and hosted sites

* test(puter-js): count the SDK unit tests in the coverage report

Only the bundle the API runners load was instrumented, so the unit tests next
to the SDK source never counted. In coverage mode the vitest config now
instruments SDK source for them and writes one shard per test file.

* test(puter-js): unit tests for ui messaging, dialogs, components, uploads, peer and smaller modules

* test(backend): cover fs, permission, app, worker, sharing, broadcast and user edge cases

* fix(backend): fs write flags are stored as booleans, app stats weeks are ISO weeks

- A write's boolean flags reach the store only once read as booleans; any
  positive number reads as true.
- App open stats grouped by week use ISO 8601 weeks for both the buckets
  and their labels on every database engine, so the two agree across a
  year boundary.

* fix(puter-js): dialog token source, legacy upload cancel, submenu state, typed-array views

- The sign-in dialog takes the token only from the popup it opened, and
  stops listening when it leaves the page.
- Cancelling a legacy upload rejects with `upload_aborted` and no longer
  runs the `error` callback.
- A context menu's submenu stays in step with its parent when the parent
  item is pressed or the submenu closes itself.
- The FileReader polyfill reads a typed-array view through its own offset
  and length.

* ci(bench): benchmark a pull request as merged into its base

The comparison ran the branch's own head against the tip of the base
branch, so a branch behind its base was charged for (or credited with)
what the base gained since. The head side is now the merge commit and
the base side its first parent. Shards also get a 15 minute timeout.

* test(broadcast): shutdown drain tests send boot's own events first

Boot queues cache updates that flush 10 ms later. A test body that
started after that flush counted it as its own request, which failed
'bounds a hung flush in onServerShutdown' on a slow runner.
2026-11-14 13:57:03 -07:00
Daniel Salazar 679f577cd8 feat(ai): a declined Claude request reruns on a fallback chain, and its conversation stays on the model that answered (#4641)
* Rerun declined Claude requests on Anthropic's fallback model

A Claude model with safety classifiers can decline a request and end it with
stop_reason "refusal". Requests to the models that have server-side fallback
(Fable 5.2, 5.1 and 5, Opus 5.5 and 5, Sonnet 5.5) now carry
`fallbacks: "default"` and the server-side-fallback beta, so Anthropic reruns
a declined request on the model it recommends for that refusal and the caller
gets that model's answer in the same response.

- `refusalFallback: false` turns it off for a request. The Anthropic route
  takes the native `fallbacks` field instead: "default" or a list of models is
  the caller's own chain, null turns it off.
- The `fallback` content block is a `refusal_fallback` chunk in a stream and
  `refusalFallbacks` on a non-streaming result, where it is taken out of
  `message.content`. The Anthropic route writes it back as a native block and
  accepts it in replayed messages.
- `usageDetails.fallbackModel` names the model that answered.
- A final refusal is forwarded as before, without the fallback-credit fields
  of `stop_details`.
- A request Anthropic rejects over a fallback the caller did not ask for is
  sent again without it.

* Meter each Claude fallback attempt on the model that ran it

A request Anthropic reruns on a fallback model is several attempts, each
billed at its own model's rates. `usage.iterations` carries one entry per
attempt and the top-level counts describe only the attempt that answered.

- Every attempt is its own charge, priced at the rates of the model that ran
  it and recorded under that model's key: the answer from the top-level
  counts, each declined attempt from its iteration entry. Nothing is counted
  twice, and a fast request's attempts are priced at each model's fast rates.
- The reported `usage` keeps the answering attempt under the plain keys and
  adds a declined attempt's tokens under `declined_` keys. Like the advisor's,
  only their recorded cost prices them, and they are no part of the request's
  own prompt or output totals.
- A provider's `requestPricing` can name the models the upstream may rerun
  the request on. The credit gate then prices the prompt and the capped
  output once per model, each at its own rates and cost factor, for the
  affordability check, the output cap and the hold. Claude names the priciest
  target of default routing, or every model of a chain the caller named.

* Charge a declined Claude request only when Anthropic bills it

Anthropic bills a request its classifiers decline before any output only in
the bio, frontier_llm and reasoning_extraction categories; any other
category, or none, is not billed. A request declined after it produced
output is billed for its prompt and that output.

Metering follows the same rule for each attempt: the final refusal by its
`stop_details.category`, and an attempt that declined before a fallback by
the `trigger.category` of its `fallback` block. An attempt Anthropic does not
bill is recorded with its token counts at no cost. An attempt whose refusal
details are missing is charged as before.

* Estimate images inside tool results as attachments

The credit gate's prompt estimate read a `tool_result` as the text of its
serialized content, so a base64 image inside one counted as text, at many
times the tokens the image costs. An image or document block inside a tool
result is now estimated the way a top-level one is, from its payload size.
Text and other blocks in the result are counted as before.

* Name each Claude model's fallback chain, and keep a declined conversation on the model that answered

A request to a Claude model with fallback targets names them in order
(Opus 5, then Opus 4.8) instead of asking for default routing, which
leaves some refusal categories declined.

puter.js remembers the model that answered a declined turn and names it
on later turns of the same conversation, so they skip the declined
attempt. The backend runs such a request on that model and presents it
in the requested model's response format.

* Rerun a declined Claude request from the driver, one attempt at a time

A request a Claude model declines is now rerun by the chat driver on the
model's fallback models, instead of by Anthropic inside the same API call.
The request sent upstream is the same as before this branch: no `fallbacks`
field and no extra beta header.

Each rerun is a whole attempt of its own. It goes through the credit gate
against the balance left after the declined attempt, takes its own hold once
the declined attempt's hold is released, and is metered by the provider under
its own model. A request reserves one attempt at a time, as any other chat
request does. When the balance can't cover the rerun, or the rerun fails, the
response is the refusal.

A non-streamed request is rerun on any refusal. A streamed request is rerun
only when it was declined before any output, and the answer follows a
`refusal_fallback` chunk on the same stream. The response reports the model
that answered in `usageDetails.fallbackModel`, each switch in
`refusalFallbacks`, the declined attempts' tokens under `declined_` usage
keys, and the total charged in `usage.cost`. It keeps the requested model's
format.

A conversation pinned to a fallback model that declines continues down the
rest of the requested model's fallback models. The Anthropic route reads
`fallbacks: null` or `false` as an opt-out and ignores any other value.

Claude restores `puter_path` parts after a refusal, so a rerun uploads the
files again.
2026-11-14 13:04:39 -07:00
Daniel Salazar e17783931f fix(ai): follow-ups to the AI driver stack: optional image type hint, stable fuzz cases, provider-only integration workflow (#4638)
Backend Tests / changes (push) Canceled after 0s
Backend Tests / typecheck (push) Canceled after 0s
Backend Tests / test shard 1/4 (push) Canceled after 0s
Backend Tests / test shard 2/4 (push) Canceled after 0s
Backend Tests / test shard 3/4 (push) Canceled after 0s
Backend Tests / test shard 4/4 (push) Canceled after 0s
Backend Tests / test (main) (push) Canceled after 0s
Backend Tests / coverage (push) Canceled after 0s
Notify HeyPuter / notify (push) Canceled after 0s
* fix(ai): the image type hint only has to be a string when a request carries an input image

* fix(ai): OpenAI speech to text answers 400 to a prompt that is a list or an object

* test(ai): a fuzz case keeps its input and route when the catalog changes, and a suite that reaches no provider fails

* fix(ai): a model id with a colon after its vendor keeps its name when it is qualified

* fix(ai): the native Gemini request type accepts the xhigh effort Hydrogen takes

* style: restore the repo formatting in files the AI stack reflowed

* docs(ai): the image reference and quotas page cover Replicate's safety reruns

* ci: the AI provider workflow runs only the provider tests and passes every provider's key
2026-11-14 01:37:43 -07:00
Filip KujundžićandDaniel Salazar f6139147fd Hold the AI concurrency slot until a detached chat completion settles (#4615)
A chat completion keeps running for up to 10 minutes after the caller
hangs up, so the upstream can report usage. It now counts against the
caller's concurrency cap for as long as the upstream runs, instead of
until the response closes.

- The chat driver registers its upstream run with the request's
  concurrency slot, so `/drivers/call` keeps the slot until the
  upstream is done. The cleanup after it does not hold the slot.
- The route concurrency gate now uses the same CallSlot as
  `/drivers/call`: the slot is held until the response is done and the
  work the handler registered has settled. The OpenAI- and
  Anthropic-compatible chat routes register the completion, so a
  non-streaming call counts until the upstream answers too.
- CallSlot moves to core/http, since the route gate below the
  controllers uses it. The context key is renamed keepConcurrencySlot.
- rate-limits-and-quotas.md says a completion counts until the model
  finishes it, even after a disconnect.

Co-authored-by: Daniel Salazar <daniel.salazar@puter.com>
2026-11-14 00:23:04 -07:00
Filip KujundžićandDaniel Salazar 2d12dcc99f Reorganize AI drivers and harden request handling (#4614)
* Move the AI drivers into drivers/ai

The seven drivers/ai-* folders and the AI-only helpers in drivers/util
become one tree:

  drivers/ai/interfaces/<interface>/            the Puter-facing drivers
  drivers/ai/providers/<vendor>/<interface>/    vendor adapters, catalogs, tests
  drivers/ai/protocols/openaiCompatible/        the shared OpenAI wire protocol
  drivers/ai/shared/                            helpers several interfaces use

Files are moved and their relative imports rewritten; no implementation
changes. Driver names, aliases, interfaces, config keys, model ids and
usage keys are unchanged.

The chat catalog registration test scanned providers/*/ next to itself.
It now scans providers/*/chat/ and fails if the scan finds no catalog, so
a wrong directory can't pass it.

General helpers that non-AI code also uses stay in drivers/util: file
input, data URIs, upstream errors, stream piping, CRUD limits.

* Document the AI driver layout

doc/ai-drivers.md explains what interfaces, providers, protocols and
shared each own, the import rules between them, where a new file goes,
and the steps for adding a provider or an AI interface. It also lists
the three places that don't follow the layout yet.

doc/architecture.md and AGENTS.md link to it.

* Move catalogPrice into ai/shared

Chat providers and the Cloudflare and xAI image catalogs all parse vendor
prices with catalogPrice, so it lives in shared/ instead of the chat
interface's pricing helpers. The image catalogs no longer import from
the chat interface.

* Move the Textract and Mistral OCR calls into provider classes

OCRDriver held both vendors' clients, request building, response
normalizing and metering. That now lives in TextractOcrProvider
(providers/awsTextract/ocr) and MistralOcrProvider (providers/mistral/ocr),
both implementing IOcrProvider. The driver keeps the provider catalog,
model resolution, auth and credit gates, and input resolution.

The page estimate, document detection and credit hold both providers use
are in interfaces/ocr/common.ts.

No behavior change: same validation order, error messages, usage keys,
holds and charges.

* Move the ElevenLabs voice changer into a provider class

VoiceChangerDriver built the ElevenLabs request, measured the converted
audio and metered it, and imported the output formats from the ElevenLabs
text-to-speech provider. That code is now in providers/elevenlabs:

  outputFormats.ts                         formats both speech interfaces use
  speechToSpeech/ElevenLabsSpeechToSpeechProvider.ts
  speechToSpeech/measuredOutput.ts         WAV, Opus and byte-rate timing
  speechToSpeech/costs.ts

The driver keeps provider resolution, test mode and the auth check. With
one provider it holds the class directly; there is no provider interface.

No behavior change: same validation order, error messages, usage keys,
holds and charges.

* Move the AI billing helpers the realtime relay uses below the driver layer

OpenAIRealtimeRelayService is a service, and it imported the cost factor,
the provider key reader and a transcription price from drivers/ai. Those
now live in src/backend/util, which both layers can import:

  util/aiCostFactor.ts    withAiCostFactor, withAiCreditHold and the
                          request cost helpers, unchanged
  util/aiProviderKey.ts   readProviderKey, cut from providerRegistry.ts
  util/aiPrices.ts        the gpt-transcribe per-second price, read by the
                          OpenAI speech-to-text cost table and the relay

withStreamedAiCharge returns a DriverStreamResult, so it stays in the
driver layer as drivers/ai/shared/streamedAiCharge.ts with its tests.

MeteringService is untouched. No prices or billing behavior change.

* Remove the aiUserIdentifier alias

shared/aiUserIdentifier.ts re-exported upstreamUserIdentifier under a
second name, and only its own test imported it. The alias is gone; its
tests, which cover truncation and actor shapes the other file didn't,
replace the four cases in upstreamIdentifier.test.ts.

* Move the AI test helpers into the AI tree

drivers/integrationTestUtil.ts held helpers for AI provider tests, but a
store test and the realtime relay test imported from it too.

  drivers/ai/shared/integrationTestUtil.ts   the provider test helpers
  testEnv.ts                                 optionalEnv and skipUnlessEnv,
                                             for any env-gated suite
  testUtil.ts                                withAiCostFactorHook, next to
                                             the server it hooks

No test under services/ or stores/ imports from the driver layer's AI
code now. The typecheck baseline entry for the moved file is renamed, not
regenerated.

* Split the tool and compaction helpers by dialect

FunctionCalling.js and compaction.js each held Puter-facing parsing next
to OpenAI and Anthropic request shapes. Each dialect now owns its mapping:

  interfaces/chat/utils     normalize_tools_object, readCompaction and the
                            other dialect-neutral checks
  protocols/openaiCompatible/openaiParams.ts
                            toolsToWire (was make_openai_tools) and
                            toOpenAiContextManagement
  providers/claude/chat/contextManagement.ts
                            toAnthropicContextManagement

toolsToWire takes the dialect as its second argument, like the other
mappers in that module, and takes an array; every caller already guarded
the empty case.

make_claude_tools is removed. Nothing but its tests called it: the Claude
provider uses claudeToolPolicy directly. The three cases only those tests
had are added to the claudeToolPolicy tests. The chat interface helpers no
longer import from providers/claude.

* Remove the unused ImageProvider base class

Every image provider implements IImageProvider directly; nothing extended
or imported the abstract class in interfaces/image/ImageProvider.ts.

The guide's import rules now say that only an interface's driver file
imports providers, which holds since the tool helpers stopped importing
the Claude policy.

* Rerun Replicate predictions an output safety checker rejects

Some community models check the generated image and fail the
prediction with "Try running it again" for a share of seeds, whatever
the prompt. adirik/realvisxl-v3.0-turbo failed 5 of 24 runs of "a small
red cube on a white table" that way.

A prediction that fails with that message is now run again, up to two
more times, inside the same deadline and credit hold. A request that
pins a seed is not rerun, because the same seed is rejected again.
Only the prediction that succeeds is metered, as before.

* Answer malformed AI requests with a 400 where they enter

A value that used to end in an unclassified error, in a request or in
an upstream answer, now gets a classified one before provider code runs
on it. A value a driver or provider ignored or refused before is
handled as it was.

Every driver:
- shared/scalarOptions.ts answers 400 for a value that cannot be
  converted to text, such as { "toString": null }, in the options a
  driver reads as text, a number or a flag. The chat, video, text to
  speech, speech to text, voice changer and OCR drivers call it first.
- An unknown provider name that is not text gets the same 400 as any
  other unknown name.

Chat requests:
- A falsy `tools` means no tools on every provider.
- A tool call id or a content block type that cannot be converted to
  text is a 400.
- A tool result that is an object is sent as its JSON, like the content
  of a `tool` message.
- `include` that is not an array is a 400.
- `anthropicBetas` that is not a list of names is dropped.
- Gemini's native route answers 400 when no user or assistant message
  is left to send.
- The prompt estimate reads a compaction block whose content is not a
  string.

Image, video, speech and OCR requests:
- The image driver checks `input_image_mime_type` with `quality` and
  `resolution`.
- The video driver answers 400 for a model that is not a string.
- The voice changer answers 400 for an `output_format` that is not a
  string.
- Mistral OCR answers 400 when the SDK refuses the options before
  sending them, as Mistral chat does.

Upstream answers to chat:
- A choice without a message is the existing 400 bad_response, which
  still falls back.
- A usage count that is not a number is reported as zero in the cost
  event, as pricing already skips it.

* Fuzz the AI drivers with seeded requests and upstream answers

Two seeded suites send malformed input through the real drivers and
providers. The vendors are played at the HTTP boundary, so each
provider's request and response code runs.

- ChatCompletionDriver.fuzz.test.ts covers the 17 chat providers that
  have a static catalog. Requests with a few values changed must
  resolve or reject below 500 without marking a route unhealthy.
  Valid requests against wrong statuses, bodies of the wrong shape and
  broken event streams must end with an answer or a classified error.
  A stream only has to end; the error line it carries is not checked.
- mediaDrivers.fuzz.test.ts covers the image, video, speech and OCR
  drivers, called as a user with unlimited metering so a request gets
  past file input and the credit hold. Every vendor refuses the
  request, and every call must end with a classified error.

shared/fuzzTestUtil.ts holds the seeded random source, the hostile JSON
values, the mutation, and the stand-in for fetch, undici and axios. An
SDK that calls https.request itself fails the suite. PUTER_FUZZ_CASES
raises the case count for a longer run. doc/ai-drivers.md describes the
suites.

* Restore the CODEOWNERS default owner and wildcard patterns

The default owner line read `- @Salazareo`, which only matches a file
named `-`, so files without a specific owner had none. Three patterns
had their `*` escaped, which GitHub rejects as invalid, so their lines
assigned no owner.

---------

Co-authored-by: Daniel Salazar <daniel.salazar@puter.com>
2026-11-14 00:23:04 -07:00
Nariman JelvehandClaude Opus 5.5 3e11e7dc79 refactor: keep folder sort and layout in puter.kv, drop /set_sort_by and /set_layout (#4642)
Explorer saved each folder's sort and layout through POST /set_sort_by and
/set_layout, which wrote them onto the folder's fsentries row. stat only
returns `layout`, so a saved sort was never read back.

The GUI now keeps them in the user's key-value store, one key per folder
uid (`folder_view:<uid>` holding `{ sort_by, sort_order, layout }`), via
helpers/folderViewPrefs.js. A change to one preference keeps the others.
A folder with nothing stored falls back to the layout its fsentry still
carries, then to the defaults, so existing layouts carry over.

refresh_item_container reads the folder's view after stat and re-sorts
items that went in under the previous sort; a view for a folder the
window has left is ignored. update_window_path no longer applies sort and
layout itself, since the refresh it starts does.

With no callers left, DesktopController and its two routes are removed.
The fsentries columns and stat's `layout` field stay.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 21:34:37 -07:00
Daniel Salazar b2eb8ed895 feat(auth): a first-party page served on its own origin signs in with a session of its own (#4635)
Backend Tests / changes (push) Canceled after 0s
Backend Tests / typecheck (push) Canceled after 0s
Backend Tests / test shard 1/4 (push) Canceled after 0s
Backend Tests / test shard 2/4 (push) Canceled after 0s
Backend Tests / test shard 3/4 (push) Canceled after 0s
Backend Tests / test shard 4/4 (push) Canceled after 0s
Backend Tests / test (main) (push) Canceled after 0s
Backend Tests / coverage (push) Canceled after 0s
Notify HeyPuter / notify (push) Canceled after 0s
A deployment can list origins of its own pages in
`first_party_session_origins`. When such a page asks the GUI to sign it in,
the sign-in hands it a GUI token on a `web` session of its own, parented to
the user's sign-in, instead of an app token.

The session is minted by POST /auth/first-party-session, which only the GUI's
own page script may call, and only as the user's sign-in itself: app tokens,
access tokens and a session minted this way are refused. It never gets a
session cookie, ends with the sign-in it was handed out under (revoking either
takes the tokens minted under the page along), is not counted as a sign-in,
and stays up with its sign-in when all other sessions are revoked.

The sessions list shows it under its sign-in, titled with the page's host and
badged as a site session.
2026-11-13 17:47:57 -07:00
Daniel Salazar c253b7e05e feat(auth): signups record the request's TLS fingerprint when a fronting proxy supplies one (#4622)
`tlsFingerprintHeader` names a request header that a TLS-terminating proxy
sets to the client's TLS fingerprint. When set, the value is exposed as
`req.tlsFingerprint`, stored on the new `user.signup_tls_fingerprint`
column, passed to `puter.signup.validate`, and forwarded to the phone
verification provider when it is a JA4.
2026-11-13 10:41:57 -07:00
647995133e fix(http): responses stay under Node's close-listener limit, starting with WebDAV GET (#4621)
Backend Tests / changes (push) Canceled after 0s
Backend Tests / typecheck (push) Canceled after 0s
Backend Tests / test shard 1/4 (push) Canceled after 0s
Backend Tests / test shard 2/4 (push) Canceled after 0s
Backend Tests / test shard 3/4 (push) Canceled after 0s
Backend Tests / test shard 4/4 (push) Canceled after 0s
Backend Tests / test (main) (push) Canceled after 0s
Backend Tests / coverage (push) Canceled after 0s
Notify HeyPuter / notify (push) Canceled after 0s
* fix(webdav): GET pipes the file without stacking close listeners on the response

stream.pipeline put seven close listeners on the response. With metering,
compression, the concurrency gate and request tracing on top, every WebDAV
download crossed Node's ten-listener warning. GET now uses pipeToResponse,
like the other file download routes.

* fix(drivers): a streamed result stops its source on unpipe instead of its own close listener

pipe already unpipes when the response finishes, closes or fails, so the
extra close listener only spent part of the response's listener budget. The
routes that hold a response open now have a test that keeps each within that
budget.

* refactor(http): everything that waits on a response's close shares one listener

Egress metering, the concurrency gate, the large-body budget, route
lifecycle events, driver call slots, disconnect aborts and SSE writers each
put their own close listener on the response. They now register callbacks
with onResponseClose, which keeps one listener per response and runs them in
the order added, so a streamed response holds three close listeners instead
of five or six and request tracing has room for its own.

* test(webdav): handle streamed response errors in test sink

Co-authored-by: Salazareo <25314977+Salazareo@users.noreply.github.com>

* test(webdav): a storage failure mid-download is covered against a real response

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: Salazareo <25314977+Salazareo@users.noreply.github.com>
2026-11-13 09:56:21 -07:00
Juan Fernando CastroandDaniel Salazar 5d541cd8e2 fix(auth): a just-minted read URL or token is found while the replica catches up (#4556)
* fix(auth): a just-minted read URL or token is found while the replica catches up

* fix(auth): a token's grants aren't cached when it's revoked mid-mint

* fix(permissions): a mint succeeds when its grants cannot be read back to cache

The grants are already stored at that point, so a failed read-back drops
the cache key and the next read fills it.

* test(auth): assert the grant list cached at mint; skip the sqlite-copy replica test on postgres

* fix(auth): test that a token row is read from the primary only when both replica lookups miss

* fix(auth): one-line comments on the replica-then-primary token row lookup

* perf(auth): a mint caches the grants it stored without reading them back

---------

Co-authored-by: Daniel Salazar <daniel.salazar@puter.com>
2026-11-12 22:22:42 -07:00
Daniel Salazar b5e4f20087 fix: KV size and credit edge cases, a metering double count, site name caching, /token-read content type (#4618)
* fix(fs): /token-read serves a file with no known extension as application/octet-stream

* fix(kv): a value too large once stored rejects with value_too_large, and a consistent read of several keys is consistent

* fix(kv): remove on an account with no credits left removes the paths and returns null

* fix(metering): a buffered increment whose base read fails is not also written through

* fix(hosting): site lookups by name share one cache entry for every spelling

* fix(metering): an increment whose base read fails is written through and taken back out of the buffer

* fix(hosting): create stores a site name trimmed and lowercased
2026-11-12 20:49:51 -07:00
Juan Fernando Castro 0694b76751 feat(email): sends name a stream, and streams add headers, a from address and message tags from config (#4520)
* feat(email): sends name a stream, and streams add headers, a from address and message tags from config

`email.streams` maps a stream name to optional headers, a from address and a
tags header. A send that names a configured stream gets that stream's
headers (caller headers win) and from address (when the caller gives none),
and its tags rendered as `name=value` pairs into the tags header. Unknown or
missing streams change nothing, and `streams` never reaches the transport.

Account mail is sent on `auth`, share and app feedback mail on `notify`, and
the signup confirmation on `signup` unless a `puter.signup.validate` listener
names another stream, which is remembered in the account metadata for
resends, deferred sends and save-account.

The signup response carries `confirmation_email_sent` when a confirmation
email was due at signup, and `/send-confirm-email` answers `{ sent }`.

PUT-2346

* fix(email): review fixes for stream naming

* fix(email): contact form mail names the notify stream, streams resolve from own config entries, the no-transport log shows the stream

Templated sends take only replyTo and stream; the header and tag options had no caller.

* fix(signup): a claimed row drops its earlier confirmation stream, and save-account reports a failed send under its own stage
2026-11-12 22:46:34 -05:00
Juan Fernando Castro c3ff8ca3b2 fix(permissions): an app opened on a file in a shared folder can read and save it (#4555)
* fix(permissions): an app opened on a file in a shared folder can read and save it

* perf(permissions): app scans check implied options before scanning the user

* test(permissions): cover app grants on folders and revoked shares

* fix(permissions): an app's folder grant counts only while its user holds that folder

The app branch of the ACL check counted a user-to-app grant on any folder above the file. It now counts a grant on the file itself, or on a folder above it that the user holds at the asked mode, so the grant and the user's own access meet on the same node.

* test(fs): the other-app case pins 404 beside the opened app's 200
2026-11-12 22:46:15 -05:00
Juan Fernando Castro 39d931306d fix(auth): sign-in relays a token set between waits (#4572)
* fix(auth): sign-in relays a token set between waits

* fix(auth): sign-in relay skips another app's stored token and survives a failed store

* fix(auth): sign-in relay always clears the stored copy and logs only the error message

* fix(auth): the sign-in relay keeps only signed app tokens, per app, and a subscribed wait answers without Redis

/login/set stores a token only when this server signed it for an app, under a
key that includes the app, so a later set for another app or an unsigned value
leaves a pending token in place. /login/wait takes the stored copy once and
falls back to listening when Redis cannot be read. A token that arrives by
event is delivered to every subscribed wait for that app; the stored copy is
then removed best-effort, and left in place when the wait's client has gone.
A relayed token for another app no longer ends the wait. The event payload is
back to { authtoken }.

* chore(events): event types file matches main again
2026-11-12 22:46:04 -05:00
Daniel Salazar 36e2d199c8 fix(fs): refuse instead of replacing an entry whose name differs only by an emoji or accent (#4589)
* fix(fs): refuse instead of replacing an entry whose name differs only by an emoji or accent

MySQL compares fsentries names and paths under collations that also fold
accents and most emoji, so a lookup for one name could return a sibling
with another, and writes then overwrote and renamed it.

Path lookups now return only an entry whose stored path matches the
requested one after NFC normalization and lower-casing; case-only and
NFC/NFD spellings still resolve as before. Name-collision checks opt in
to the folded match and treat it as taken by a different entry: write,
mkdir, touch, rename, shortcut, move and copy dedupe when asked and
otherwise answer 409, and never replace or return that entry.

* fix(fs): leave a sibling's subtree alone when a folder its path folds onto is renamed or moved

The subtree rewrite matches descendants with `path LIKE 'old/%'`, and LIKE
compares under the path collation (ASCII case on SQLite). With a sibling
folder whose path differs only that way, renaming or moving one folder also
rewrote the paths below the other.

When another row sits at such a path, the rewrite now follows parent links
down from the moved folder instead. Without one, the rewrite is unchanged,
after one indexed lookup.

* fix(fs): resolve an entry whose stored path is spelled unlike its names, and heal that path on the first read

Older rows can store a `path` whose spelling differs from the names on their
parent chain in ways the path collation ignores. A lookup that finds such a row
by its real spelling now confirms it through the parent chain, writes the path
from the stored names, and returns it, so overwriting, touching or copying over
it by name works and the next read takes the single indexed query again.

The lineage walk now writes a row's path only when it differs byte for byte
from the one its names give, and drops only those rows' cache keys, so a walk
over rows that are already right issues no writes. Whether an entry found at a
name is a different, folded name is decided by its own name and its path after
that walk, not by a stale path column. With `foldedNames`, a row only the path
collation matches still counts as holding the name.

* fix(fs): match entry names under full case mapping

Names are compared after upper- then lower-casing, with a dotted capital I
taken as I, so a request in another case finds the stored entry for Greek
final sigma (`οδος.txt` for `ΟΔΟΣ.txt`), German sharp s (`STRASSE.txt` for
`Straße.txt`) and Turkish dotted I (`istanbul.txt` for `İstanbul.txt`).
Accent, emoji, kana and width differences still make two names different.

* fix(fs): name the existing entry when a folded name is already taken, and show why a confirmed replace failed

`item_with_same_name_exists` from write, move and copy now carries the
existing entry's own name in `entry_name` when it differs from the requested
one only by accents or emoji, so the prompt names the file the folder shows.

In the GUI, a replace confirmed from that prompt that still fails is reported
with its error message and counts as not written, instead of rejecting out of
`handle_same_name_exists` and leaving the caller waiting.

* fix(webdav): answer MKCOL with 405 and COPY or MOVE with Overwrite: F with 412 on a folded name

The existence checks before MKCOL, COPY and MOVE now see an entry whose name
differs from the target only by accents or emoji, so those requests answer as
for an existing target instead of reaching the filesystem and coming back as
409.

* docs(fs): list the errors write, move and copy return when a name is taken

`puter.fs.write()` gets an Errors section with `item_with_same_name_exists`,
`cannot_overwrite_a_directory` and `conflict`, the last for a name that differs
from an existing one only by accents or emoji. The move and copy pages say how
they reject in that case.

* fix(fs): walk the parent chain on the primary when a path lookup reads hard

A lookup that asks for a try-hard read (the checks after a create or move hits
the unique key) now also runs its parent-chain walk on the primary, and falls
back to the primary for the entry it finds. Before, the walk read a replica, so
a name the replica had not seen yet came back as missing and the mkdir or move
surfaced the duplicate-key error as a 500 instead of a 409.

Lookups without a try-hard read are unchanged. A try-hard lookup issues the
same number of queries; its walk reads the primary instead of a replica.

* fix(fs): treat a folder only the collation matches as missing instead of naming a file in it

A name-collision lookup lets only the last segment of the path match a
differently spelled name. When a folder above it matches only under the
collation (`😁dir` for `😀dir`), the lookup reports no occupant, so a write,
mkdir or touch there fails as for a missing folder: 404, or with
`createMissingParents` a 409 that names the folder. Before, it reported the
file inside the other folder and answered 409 naming that file. A folder whose
stored path is spelled that way still counts as the same folder, so lookups
built from stored paths find what they did before.

A rename onto a name the unique key already holds now answers 409 when the
lookup before it missed the occupant, instead of a 500.

* fix(fs): name the existing entry when a rename's name is folded, and leave a copy onto itself out of the copy docs

A rename refused because the folder holds a name that differs only by accents
or emoji now names that entry in its 409, as write, move and copy do.

A copy onto a folded spelling of the source's own name answers as a copy onto
itself (400 with `overwrite`), so the copy page's paragraph on folded names
now covers only items other than the source.

* fix(fs): walk the parent chain on the primary only when a hard read found another spelling of the path
2026-11-12 17:26:22 -07:00
Juan Fernando CastroandDaniel Salazar eefc1f2f2e fix(auth): the session list leaves out expired sessions, and revoking one works (#4573)
* fix(auth): the session list leaves out expired sessions

* test(auth): cover revoking expired sessions and their children

* fix(auth): the session list follows what authentication accepts

A token minted under a session that has expired is left out of the
list along with that session. The check runs in listSessions with the
rule authentication uses, so getByUserId returns expired rows again
and the revoke callers need no option.

* fix(auth): revoke-session answers 404 for another user's session

Missing, already revoked and other users' rows now share one answer.

* fix(auth): type the session list rows instead of casting them

---------

Co-authored-by: Daniel Salazar <daniel.salazar@puter.com>
2026-11-12 17:57:51 -05:00
velzie bd7614372a fix(peer): grant forgery bug and stale comment 2026-11-12 17:48:10 -05:00
Daniel Salazar 61b5aa4900 fix(fs): treat path-less entries found by uid or id as missing (#4611)
A uid or id lookup can return a legacy row with no path when its parent
chain is broken. resolveNode now reports it as not found, so readdir,
stat and the other uid-addressed routes answer 404 instead of crashing
in the ACL check.
2026-11-12 15:44:14 -07:00
Nariman Jelveh aaa5c82236 Redirect /show/* to the dashboard and remove leftover desktop code (#4610)
* Redirect /show/* to the dashboard's Files tab

/show/<path> redirects to /dashboard#files/<path> with its query intact,
instead of booting the desktop and opening Explorer there.

Also removes what only that route used: the shell's launch options, the
launch_options GUI param, and the GUI service that ran them.

* Remove the unused component window and Flexer

Nothing opens UIComponentWindow or uses Flexer, and JustHTML was only the
component window's default body. Also drops the attach() shim UIQRCode kept
for component containers.

* Remove translation keys left by removed features

Drops 36 keys nothing references in every language: the keyboard shortcuts
guide, desktop shortcuts, personalization, the toolbar's fullscreen, GitHub
and refer entries, the referral strings, and the publishing option prompt.

* Inline the toolbar height, which is always zero

The toolbar is gone, so window.toolbar_height only added or subtracted zero
in window sizing and placement.

* Remove window edge snapping

Dragging a window to a screen edge or corner no longer snaps it to half or a
quarter of the screen. Double-clicking the head and the scale button still
maximize.

* Remove the window color theme service

Nothing can set a window theme, so the GUI stops reading the saved theme
file on boot and windows keep the default colors. puter.ui.on() still
accepts themeChanged, which is never sent; its docs entry is removed.

* Remove styles and icons nothing references

Drops the stylesheet rules of the removed Settings window, launch menu,
intro menu and a few other removed features, and 16 icons whose names
appear nowhere in the GUI.

* Remove more translation keys nothing references

Drops 56 keys in every language that no GUI code, extension or backend
message uses, such as the system information labels, the old 2FA setup and
confirm-code steps, and the auth token copy dialog strings.

* Remove the global menubar leftovers and more unused styles

Nothing creates a global menubar, so the window code stops hiding, showing
and removing one. Also drops stylesheet rules for classes nothing uses,
including the old auth dialog, the responsive hidden-* and visible-*
helpers, and two keyframes only those rules animated.
2026-11-12 15:31:38 -07:00
Daniel Salazar 8b68c103c5 fix(auth): mint under a full-access token without re-reading its session row, and look token rows up by uid through their indexes (#4588)
* fix(auth): mint under a full-access token from the row auth loaded, and look up token rows by uid with one index per column

A token minted by a full-access token now parents to the session row that
authentication already loaded and checked for the minting token, instead of
reading it again by token uid. The same applies to the session a relay token
is bound to. Tokens whose claims name no row of their own still look it up.

findActiveByAccessTokenUid now queries access_token_uid first and the legacy
uid only on a miss, each through its own index, instead of one OR across both
columns.

* fix(auth): send both access-token row lookups together, so a miss on the first costs no second round trip
2026-11-12 15:17:45 -07:00
Daniel Salazar f114b13306 perf(gui): boot keeps a same-session token and skips /get-gui-token when the page already answers it (#4591)
* perf(gui): keep the stored token when /get-gui-token returns one for the same session

/get-gui-token signs a new string on every call, so every signed-in boot
stored a token that differed from the one it held only in `iat` and passed
it to puter.setAuthToken. That opened a second FS socket, re-sent /whoami
and the cache timestamp, and every other open tab picked the new token up
from storage and did the same.

The boot now keeps the stored token when the returned one carries exactly
the same claims apart from `iat`; any other difference replaces it as
before. A kept token still starts the boot from an empty FS cache, as the
swap did. A boot that keeps the persisted cache (no session cookie) now
waits for the cache timestamp check before the first render, which it
started before reading the user.

* perf(gui): skip /get-gui-token at boot when the page already says what it would return

Every signed-in boot waited on /get-gui-token before it read the user. The
shell is rendered from the same session cookie that route reads, so it now
carries `guiTokenDigest` in gui_params: a digest of the claims (minus
`iat`) of the GUI token the cookie's session would get, or null when the
request has no session cookie. A cookie that doesn't resolve to a user
session leaves it out.

The GUI skips the request when the digest matches its stored token (same
session, user and token type), or when it is null (the route would refuse).
It still asks when the parameter is missing, the digest names another
session, nothing is stored, the page and the route are on different
origins, or Navigation Timing doesn't show this page as freshly served for
this load (a history navigation or restored tab can reuse a page rendered
for an older cookie).
2026-11-12 14:26:09 -07:00
Nariman Jelveh ce70728eeb Remove the desktop's icons and right-click menu, and redirect /desktop (#4609)
* Remove the desktop's icons and right-click menu

The desktop no longer lists the Desktop folder's items, and right-clicking
its background opens no menu. It stays as the surface windows open on.

Also removes what only the icons used: file drops and item drops on the
desktop, rubber-band selection, auto arrange and saved icon positions, and
their two keys in puter.js's GUI boot cache. Clicking the desktop clears the
active item container so keyboard shortcuts stop acting on a window's items.

* Redirect /desktop and /settings to the dashboard

/desktop redirects to the root with its query intact, and /settings to the
dashboard's Home tab. /desktop drops out of the OIDC return_to allowlist,
sign-out returns to the root, and the auth cover page's logo links there.

Also removes eight GUI globals nothing references.

* Remove code paths that only ran for the desktop's item container

The desktop is no longer an item container, so the Trash item that
refresh_item_container added to it, the empty-folder message exemption,
and the context menu parent check for it can't be reached.
2026-11-12 14:00:29 -07:00
Nariman Jelveh 8518023b0b Remove more desktop-only features and entry points (#4607)
* Remove the desktop's Publish Website window

The right-click menu on desktop folders and on an Explorer window's
background no longer has a Publish as Website item. This removes
UIWindowPublishWebsite, the publishAsWebsite helper that opened it, both
menu items, the window's CSS, window.extractProtocol (only the window used
it), and the dir_published_as_website and pick_name_for_website i18n keys.

The dashboard keeps publishing websites through its own dialog.
generateFileContextMenu no longer falls back to the removed window, so it
offers Publish as Website only when the caller passes onPublishWebsite,
which the dashboard's Files tab does. The website badge on desktop items
and the backend hosting API are unchanged.

* Remove the desktop's Hide Desktop Icons toggle

The desktop's right-click menu no longer has a Hide/Show Desktop Icons
item. Without the wallpaper, hiding the icons left an empty page. This
removes the menu item, toggleDesktopIcons/hideDesktopIcons/
showDesktopIcons, the boot-time read of the saved setting, and the
.desktop-icons-hidden CSS rule.

puter.js's GUI boot cache no longer batch-fetches desktop_icons_hidden,
menubar_style or user_preferences.clock_visible, which nothing reads
anymore. Values already saved under those keys stay in KV, unread.

Also drops the desktop's BroadcastChannel, whose message handler was
empty and which nothing else referenced.

* Remove the desktop's ?download= link handler

Opening puter.com/?download=<url> or /desktop?download=<url> no longer
asks to save that remote file to the Desktop. The parameter is ignored,
and a root URL that carries it boots the dashboard like any other root
URL instead of forcing the desktop.

This removes the handler in UIDesktop, its UIWindowProgress import, the
download entry in the GUI's dashboard routing, and the
confirm_download_file_to_desktop, downloading, downloading_file,
uploading_file and error_download_failed i18n keys only it used.

The decision of whether a page load boots the dashboard moves from an
inline block in initgui into helpers/bootsDashboard.js, so it is tested.

* Stop granting Camera and Recorder Desktop access on desktop boot

The desktop no longer grants Camera and Recorder write access to the
user's Desktop folder the first time it loads. Those apps now ask
through the normal permission prompt, as they already did for users
who only used the dashboard. Grants already given stay in place.

puter.js's GUI boot cache no longer batch-fetches the
has_set_default_app_user_permissions flag that kept the grant to one
run. Values already saved under it stay in KV, unread.

* Redirect /@username links to the dashboard

puter.com/@<username> no longer opens that user's Public folder on the
desktop. The backend now redirects /@:username to /, so old links land
on the dashboard instead of booting the desktop.

This removes the GUI's /@ handler and the error_invalid_username i18n
key only it used. error_user_or_path_not_found stays, since share links
still use it.

* Redirect /desktop/app links and stop opening share links on the desktop

/desktop/app/<name> now redirects to /app/<name>, keeping its query
string, so the app opens in the dashboard. The backend no longer serves
an app shell there, OIDC sign-in no longer returns to it, and the GUI no
longer strips a leading /desktop from its route segments. The rate-limits
page lists only /app/<name>, the route the limit still applies to.

/desktop?shared=<path> no longer opens the shared item on the desktop.
The desktop ignores ?shared=: it doesn't ask a guest to sign in for it,
doesn't switch to the account a share email names, and OIDC sign-in from
/desktop doesn't carry it along. Share emails link to /?shared=, which
the dashboard handles as before. Opening a share notification on the
desktop still opens the item.

* Remove the desktop's ?app=explorer link handler

?app=explorer[&path=<folder>] no longer boots the desktop and opens an
Explorer window. ?app= is ignored and no longer forces the desktop, so a
root URL that carries it opens the dashboard, and /app/<name>?app=... now
launches its app in the dashboard instead of booting the desktop and
launching nothing.

* Stop ?puter.fullpage= from booting the desktop

The root and /app/<name> with ?puter.fullpage= now open in the dashboard
like a plain /app/<name>, with the app maximized. The dashboard always
shows apps full page, so the parameter no longer overrides that. Iframe
embeds and popups, which still boot the desktop, read it as before.

bootsDashboard no longer takes the query string, since no parameter
decides the interface anymore.
2026-11-12 11:54:40 -07:00
Nariman Jelveh 33988ac84c Remove the desktop taskbar (#4605)
release-please / release-please (push) Canceled after 0s
Maintain Release Merge PR / update-release-pr (push) Canceled after 0s
Notify HeyPuter / notify (push) Canceled after 0s
Backend Tests / changes (push) Canceled after 0s
Backend Tests / typecheck (push) Canceled after 0s
Backend Tests / test shard 1/4 (push) Canceled after 0s
Backend Tests / test shard 2/4 (push) Canceled after 0s
Backend Tests / test shard 3/4 (push) Canceled after 0s
Backend Tests / test shard 4/4 (push) Canceled after 0s
Backend Tests / test (main) (push) Canceled after 0s
Backend Tests / coverage (push) Canceled after 0s
* Remove the desktop taskbar

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

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

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

* Keep desktop backdrops above ordinary windows

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

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

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

A desktop icon drop is accepted only where the whole item fits above the
bottom edge. Phone popovers use the full viewport height.
2026-11-11 20:16:13 -07:00
Nariman Jelveh 72de6e16b2 Remove the desktop wallpaper (#4604)
Maintain Release Merge PR / update-release-pr (push) Canceled after 0s
Backend Tests / changes (push) Canceled after 0s
Backend Tests / typecheck (push) Canceled after 0s
Backend Tests / test shard 1/4 (push) Canceled after 0s
Backend Tests / test shard 2/4 (push) Canceled after 0s
Backend Tests / test shard 3/4 (push) Canceled after 0s
Backend Tests / test shard 4/4 (push) Canceled after 0s
Backend Tests / test (main) (push) Canceled after 0s
Backend Tests / coverage (push) Canceled after 0s
Notify HeyPuter / notify (push) Canceled after 0s
release-please / release-please (push) Canceled after 0s
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 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
Daniel Salazar d8c3e01dd9 fix(http): parse large JSON bodies in slices; store WebDAV uploads labeled as JSON (#4563)
Maintain Release Merge PR / update-release-pr (push) Canceled after 0s
Notify HeyPuter / notify (push) Canceled after 0s
release-please / release-please (push) Canceled after 0s
Backend Tests / changes (push) Canceled after 0s
Backend Tests / typecheck (push) Canceled after 0s
Backend Tests / test shard 1/4 (push) Canceled after 0s
Backend Tests / test shard 2/4 (push) Canceled after 0s
Backend Tests / test shard 3/4 (push) Canceled after 0s
Backend Tests / test shard 4/4 (push) Canceled after 0s
Backend Tests / test (main) (push) Canceled after 0s
Backend Tests / coverage (push) Canceled after 0s
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
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 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 2394221745 Answer requestEmailConfirmation() once, and show it in a frame on first-party pages (#4551)
* Answer requestEmailConfirmation() once, and show it in a frame on first-party pages

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Escape in the framed code or save-account window closes that window, and the window's answer closes the frame. A code already sent is waited for, as it is when the window's close button is used. Before, Escape closed the frame and answered false while the check went on to confirm the email.
2026-11-09 13:48:10 -07:00
Neal Shah e441880f13 add more data to user audit events (#4542) 2026-11-08 19:22:09 -05:00
Nariman Jelveh 9a86803418 Show the upgrade in a frame on first-party pages (#4541)
Backend Tests / changes (push) Canceled after 0s
Backend Tests / typecheck (push) Canceled after 0s
Backend Tests / test shard 1/4 (push) Canceled after 0s
Backend Tests / test shard 2/4 (push) Canceled after 0s
Backend Tests / test shard 3/4 (push) Canceled after 0s
Backend Tests / test shard 4/4 (push) Canceled after 0s
Backend Tests / test (main) (push) Canceled after 0s
Backend Tests / coverage (push) Canceled after 0s
release-please / release-please (push) Canceled after 0s
Maintain Release Merge PR / update-release-pr (push) Canceled after 0s
Notify HeyPuter / notify (push) Canceled after 0s
* Show the upgrade in a frame on first-party pages

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

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

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

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

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

* Document when the framed upgrade posts ready

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

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

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

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

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

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

* Say which plan changes count as upgraded in UpgradeResult

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

* Stop the page scrolling behind a framed GUI embed

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

* Skip the usage limit dialog while the framed upgrade shows

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

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

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

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

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

* Keep the upgrade showing until its tab consent is answered

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

* Say where requestUpgrade never settles

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

* Treat a GUI embed the page removes as dismissed

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

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

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

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

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

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

A page whose body carries the viewport's overflow (html and body at 100%
height, body with overflow-x hidden) jumped to the top while an embed
showed, and stayed there after: hiding the root's overflow made the body
a scroller of its own. The lock now hides the overflow of whichever
element the viewport uses, and restores a single-axis inline overflow.
2026-11-08 14:27:41 -07:00