mirror of
https://github.com/HeyPuter/puter.git
synced 2026-11-13 20:12:57 -10:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d2225f1a90 |
No files matched your search
@@ -53,7 +53,7 @@ jobs:
|
||||
# step above fails; the tests skip themselves without the key.
|
||||
- name: Run live realtime conversation tests
|
||||
if: ${{ !cancelled() }}
|
||||
run: npm run setupExtensions && (cd src/puter-js && npm run build) && npx vitest run --config src/puter-js/tests/api/vitest.config.ts src/puter-js/tests/api/realtime/realtimeLive.test.ts
|
||||
run: npm run setupExtensions && (cd src/puter-js && npm run build) && npx vitest run --config src/puter-js/tests/api/vitest.config.ts src/puter-js/tests/api/realtime/convoLive.test.ts
|
||||
env:
|
||||
CI: 'true'
|
||||
PUTER_TEST_AI_OPENAI_API_KEY: ${{ secrets.PUTER_TEST_AI_OPENAI_API_KEY }}
|
||||
+10
-195
@@ -14,25 +14,11 @@ to its normal sign-in. Apps that need the desktop (built-in and godmode apps,
|
||||
private apps the user can't open, or a failed token request) open `/app/<name>`
|
||||
on the GUI origin, cut off from the embed. Website shortcuts open their external
|
||||
destination with no opener.
|
||||
The embed follows the OS's light or dark setting. A host with a fixed theme adds
|
||||
`theme=dark` or `theme=light` to the fragment (`#user=<uuid>&theme=dark`), since
|
||||
Chromium doesn't pass an iframe's `color-scheme` on to the page inside it.
|
||||
Apps opened from the embed carry `utm_source=puter.com&utm_medium=referral&utm_campaign=app_browser_embed`;
|
||||
the desktop and dashboard send `utm_campaign=desktop` and `utm_campaign=dashboard`.
|
||||
|
||||
## Session and framing
|
||||
|
||||
The embed shows the GUI session only to the user the host page is signed in as.
|
||||
The host names that user's `uuid` (from `puter.auth.getUser()`) in the iframe
|
||||
URL's fragment, as `/embed/apps#user=<uuid>`. The embed reads the session, asks
|
||||
`/whoami` which user it belongs to, and shows the signed-out view unless the two
|
||||
match. So a host that names no user, a malformed one, or a user other than the
|
||||
session's, gets the signed-out view, and so does a session the API refuses. A
|
||||
failed `/whoami` check shows the error state. The fragment never reaches the
|
||||
server and can only narrow what the embed shows: naming the session's own user
|
||||
gives the same view as a direct visit to the GUI. Changing the fragment of a
|
||||
loaded embed reloads it.
|
||||
|
||||
The embed reads the existing GUI session from local storage on its own origin.
|
||||
If that storage holds no session, the embed gets the session from the GUI origin's session cookie through
|
||||
`/get-gui-token`. This matters in Safari, which gives a framed origin separate
|
||||
@@ -43,7 +29,7 @@ does not create accounts, show a login dialog, or accept a token from its parent
|
||||
Being signed in on a subdomain alone does not create a session on the main GUI
|
||||
origin.
|
||||
|
||||
Without a session it can show, the embed shows the recommended apps (`RecommendedAppsService`)
|
||||
Without a session, the embed shows the recommended apps (`RecommendedAppsService`)
|
||||
that the server put in the page, and nothing else: no installed apps, folders, or
|
||||
saved order, and no puter.js. Selecting one opens it at the same URL a signed-in
|
||||
launch uses, with no opener and no token on offer, so the app signs in on its own.
|
||||
@@ -72,18 +58,11 @@ and popups to escape the sandbox.
|
||||
|
||||
## Host integration
|
||||
|
||||
A first-party app that signs in with puter.js can place `<puter-user-menu>` from
|
||||
the SDK in its header instead (see `src/puter-js/src/ui/components.md`). It opens
|
||||
this embed with the signed-in user named and closes it when the app's sign-in
|
||||
changes. The rest of this section is for a host that builds the iframe itself.
|
||||
|
||||
The iframe can be shown whether or not the user is signed in. Create it when
|
||||
“More apps” is opened, naming the signed-in user in its fragment, and remove it
|
||||
on close so reopening loads current apps and preferences. Remove it when the
|
||||
host's own sign-in changes too, such as on sign-out, so an open embed doesn't
|
||||
keep the previous user. The host owns the modal and close control;
|
||||
“More apps” is opened, and remove it on close so reopening loads current apps
|
||||
and preferences. The host owns the modal and close control;
|
||||
there is no parent messaging API and no app list or credential is sent to it.
|
||||
The app browser fills its iframe and responds to its size. It shows a spinner until its apps load.
|
||||
The app browser fills its iframe and responds to its size.
|
||||
|
||||
This example assumes `puterOrigin` comes from the host app's deployment
|
||||
settings. Translate the button and frame labels using the host app's
|
||||
@@ -105,14 +84,10 @@ localization system.
|
||||
const container = document.querySelector('#apps-frame');
|
||||
const trigger = document.querySelector('#more-apps');
|
||||
|
||||
trigger.addEventListener('click', async () => {
|
||||
const url = new URL('/embed/apps', puterOrigin);
|
||||
// Signed out, the embed shows the recommended apps.
|
||||
const user = puter.auth.isSignedIn() ? await puter.auth.getUser().catch(() => null) : null;
|
||||
if (user) url.hash = `user=${encodeURIComponent(user.uuid)}`;
|
||||
trigger.addEventListener('click', () => {
|
||||
const frame = document.createElement('iframe');
|
||||
frame.title = 'Your apps';
|
||||
frame.src = url.href;
|
||||
frame.src = new URL('/embed/apps', puterOrigin).href;
|
||||
container.replaceChildren(frame);
|
||||
dialog.showModal();
|
||||
});
|
||||
@@ -124,182 +99,22 @@ localization system.
|
||||
</script>
|
||||
```
|
||||
|
||||
## Implementation
|
||||
## Implementation and checks
|
||||
|
||||
`createAppBrowser` in `src/gui/src/UI/Dashboard/AppBrowser.js` owns the shared UI
|
||||
and data behavior; its `guestApps` option is the signed-out list. `TabApps.js`
|
||||
injects desktop actions. `appsEmbed.js` supplies new-tab launching through
|
||||
`launchAppInTab` (signed in) and `guestAppLaunchUrl` (signed out) in
|
||||
`src/gui/src/helpers/appTabLaunch.js`, which build the same app URL as
|
||||
`launch_app`, and loads only the embed entry, its SDK, and shared styles. `embedHostUser` in
|
||||
`src/gui/src/helpers/embedHostUser.js` reads the host's user from the fragment, and
|
||||
`embedHostTheme.js` beside it applies the host's theme.
|
||||
The normal GUI webpack build emits `bundle.min.js`, `apps-embed.min.js`, and `feedback-embed.min.js`.
|
||||
`launch_app`, and loads only the embed entry, its SDK, and shared styles.
|
||||
The normal GUI webpack build emits `bundle.min.js` and `apps-embed.min.js`.
|
||||
The `/embed/apps` route puts the recommended list in the page's config as
|
||||
`guestApps`. No puter.js API or app-list endpoint changes are needed.
|
||||
|
||||
## Feedback dialog
|
||||
|
||||
`GET /embed/feedback` is the app feedback dialog (`puter.ui.showFeedbackDialog()`)
|
||||
for a first-party page, with the same framing rules, query redirect, and
|
||||
host-user binding as `/embed/apps`. It sends the feedback for the framing
|
||||
page's origin, which the server reads from the referrer and pins with
|
||||
`frame-ancestors`; opened top-level, it does nothing. Its page is transparent
|
||||
so the dialog's own scrim covers the host.
|
||||
|
||||
puter.js uses it on a page one label under the GUI origin, other than the
|
||||
subdomains the server refuses, when the page is signed in, framing it in a
|
||||
modal `<dialog>` that stays hidden until the embed is ready. A session check that takes longer than 200ms shows a loading scrim
|
||||
with a spinner in its place; Escape or a click on it cancels. The embed posts `{ msg: 'feedbackEmbed', state }` to its parent
|
||||
(`loading`, then `ready` or `unavailable`) and finally
|
||||
`{ msg: 'feedbackDialogClosed', sent }`. It reports `unavailable` without the
|
||||
named user's session, or while that user's email still needs confirming, and
|
||||
puter.js then uses the `/action/send-feedback` popup, which can sign in. So does
|
||||
a frame that never answers, such as one the host's CSP blocks. `feedbackEmbed.js`
|
||||
is the entry, sharing `embedSession` in `src/gui/src/helpers/embedSession.js`
|
||||
with the app browser; `showFeedbackEmbed` in `src/puter-js/src/lib/guiEmbed.js`
|
||||
is the host side.
|
||||
|
||||
## Sign-in and file pickers
|
||||
|
||||
`GET /embed/sign-in`, `/embed/show-open-file-picker`, `/embed/show-save-file-picker`
|
||||
and `/embed/show-directory-picker` serve the same GUI popups as `/action/<action>`
|
||||
for a first-party page, with the same framing rules, query redirect, and
|
||||
`no-store` as `/embed/apps`. Any other spelling of the path (another case, a
|
||||
trailing slash) redirects to it, since the shell boots the desktop for it. They render the normal GUI shell, which names the
|
||||
framing page (read from the referrer, pinned with `frame-ancestors`) as
|
||||
`gui_params.embed_host_origin`. The GUI then runs the popup boot unchanged, with
|
||||
the framing page as `window.opener`, and `window.close()` asks the page to
|
||||
remove the frame (`src/gui/src/helpers/popupFrame.js`). Without a framing page
|
||||
to answer (opened top-level, or framed by a refused page) it does nothing. The
|
||||
popup's parameters come from the fragment instead of the query: `msg_id`,
|
||||
`options` and `request_auth`, plus `user` for a picker.
|
||||
|
||||
The frame posts `{ msg: 'puterPopupFrame', state }` to its parent: `loading` as
|
||||
soon as the shell boots, `ready` once it shows a window or dialog, `unavailable`
|
||||
when the page has to use the popup, `provider` when the user picks a sign-in
|
||||
provider (below), and `closed` where a popup would close. Its
|
||||
answers (`puter.token`, `fileOpenPicked`, `directoryPicked`, `fileSaved`, the
|
||||
cancel messages, `sendMeFileData`) are the popup's.
|
||||
|
||||
puter.js uses them on a page one label under the GUI origin, other than the
|
||||
subdomains the server refuses, unless the page is cross-origin isolated or in a
|
||||
frame of another site (which `frame-ancestors` refuses too).
|
||||
`showPopupFrame` in `src/puter-js/src/lib/guiEmbed.js` shows the frame in a box
|
||||
the size of the popup window, over a scrim, hidden until `ready` and behind the
|
||||
loading spinner after 200ms. Escape closes it, on the page or in the frame. One shows per popup, as each
|
||||
popup has its own window name: a second picker request of the same kind
|
||||
replaces the one showing, and a `signIn()` call made while a framed sign-in is
|
||||
open settles with it. On
|
||||
screens up to 600px wide the box fills the screen. A frame that is refused,
|
||||
never answers, or reports `unavailable` falls back to the popup, opened through
|
||||
a consent dialog when the click that asked for it has expired. A reload or navigation the frame
|
||||
starts itself (logging out, a sign-out in another tab) names the frame as its
|
||||
referrer, so the server refuses it; the page then shows its spinner and opens
|
||||
the frame again, once per `ready`.
|
||||
|
||||
- **Sign-in** (`puter.auth.signIn()`) has no host-user binding: it is how the
|
||||
page gets a user. The box has a close button, which rejects with
|
||||
`auth_window_closed` as closing the popup does. Providers refuse to be
|
||||
framed, so choosing one posts `{ state: 'provider', url }` with the
|
||||
provider's start URL for this sign-in's `msg_id`, then `unavailable`. The
|
||||
page opens the popup straight at that URL, once it checks the URL is the
|
||||
GUI's `/auth/oidc/<provider>/start` for this `msg_id`, and the provider
|
||||
returns it as this sign-in's popup. `attempt_temp_user_creation` keeps the popup, since
|
||||
only the popup creates a temporary account.
|
||||
- **Pickers** frame only for a signed-in page. The GUI reports `unavailable`
|
||||
unless its session belongs to the user named in `user`, and the page then uses
|
||||
the popup, which can sign in and switch accounts. The token the GUI sends
|
||||
before a picker's answer isn't adopted, since it is for the page's own user.
|
||||
Dismissing the loading scrim settles the picker as cancelled.
|
||||
|
||||
## Upgrade
|
||||
|
||||
`GET /embed/upgrade` is the deployment's upgrade dialog for a first-party page,
|
||||
served like the popups above: the GUI shell with the same framing rules, query
|
||||
redirect, exact-path redirect and `no-store`, naming the framing page as
|
||||
`gui_params.embed_host_origin`. It runs only when framed by an allowed page.
|
||||
|
||||
puter.js frames it on a signed-in first-party page (the same pages as the
|
||||
pickers) for `puter.ui.requestUpgrade(details)`, and for the Upgrade button of
|
||||
the usage limit dialog a refused call shows there. Elsewhere both keep their
|
||||
behavior: inside an app `requestUpgrade()` asks the desktop, and on any other
|
||||
page the usage limit dialog opens the dashboard's upgrade page in a new tab.
|
||||
|
||||
The frame covers the page with no box or close button, and the GUI page is
|
||||
transparent (`html.popup-frame-transparent`) so the dialog's own scrim covers
|
||||
the host. The frame allows `payment` as well as `otp-credentials`. Escape on the
|
||||
page is left to the dialog, since one there shouldn't drop a payment in
|
||||
progress. Its fragment names `user` (the page's signed-in user) and, when the
|
||||
refusal gave them, `reason` (`funds`, `subscription` or `storage`) and `method`.
|
||||
|
||||
The GUI reports `unavailable` unless its session belongs to `user`, the account
|
||||
has no verification or password change waiting (which the frame couldn't be
|
||||
closed from), and the deployment defines `window.UIUpgradeAccount` with
|
||||
`UIUpgradeAccount.embeddable === true`. Otherwise it runs:
|
||||
|
||||
```js
|
||||
new UIUpgradeAccount({ attribution: { appUid, reason, method }, onClose }).open_as_window();
|
||||
```
|
||||
|
||||
`appUid` is the app the framing page's origin resolves to, never one the
|
||||
fragment names. `open_as_window()` resolves once the dialog shows, and the GUI
|
||||
then posts `ready`. While the page still hides the frame, which Chromium and
|
||||
WebKit lay out at 0x0, the GUI posts `ready` first and opens the dialog once
|
||||
the frame has a viewport, so a window it opens doesn't center on 0x0.
|
||||
`onClose({ upgraded })` must run exactly once, when the
|
||||
dialog closes or when it declines to open for the account; the GUI then posts
|
||||
`{ msg: 'puterPopupFrame', state: 'closed', upgraded }` and the page removes
|
||||
the frame. If `open_as_window()` rejects, the GUI posts `unavailable` instead. `requestUpgrade()` resolves `{ upgraded }`. A call made while the
|
||||
frame shows settles with it rather than replacing it, and a call refused while
|
||||
it shows still rejects but opens no usage limit dialog over it.
|
||||
|
||||
When the frame can't show the upgrade (refused, never ready, `unavailable`, or
|
||||
no user to name), puter.js opens the dashboard's upgrade page in a new tab with
|
||||
what was refused, through a consent dialog when the click has expired or the
|
||||
tab is blocked, and `requestUpgrade()` resolves `{ upgraded: false }`.
|
||||
|
||||
## Email confirmation
|
||||
|
||||
`GET /embed/request-email-confirmation` walks a first-party page's user through
|
||||
confirming their email, served like the upgrade: the GUI shell with the same
|
||||
framing rules, redirects and `no-store`, run only when framed by an allowed
|
||||
page. puter.js frames it on a signed-in first-party page for
|
||||
`puter.ui.requestEmailConfirmation()`. Inside an app the desktop shows the same
|
||||
windows over the app instead.
|
||||
|
||||
Like the upgrade, the frame covers the page with no box or close button, over a
|
||||
transparent GUI page, and its fragment names `user`. Escape closes it, on the
|
||||
page or on the save-account or code window. On a window, Escape closes that
|
||||
window as its close button does, so a code already sent still answers. The GUI
|
||||
reports `unavailable` unless its session belongs to `user` and the account has
|
||||
no phone, card or password check waiting.
|
||||
An email check is fine: the boot skips its own email gate for this action, so
|
||||
the user gets one code window they can close.
|
||||
|
||||
The GUI then runs `ensureConfirmedEmail` (`src/gui/src/helpers/ensureConfirmedEmail.js`),
|
||||
which the desktop's handler uses too: a temporary account gets the save-account
|
||||
window first, then an unconfirmed email gets the code window, each at most
|
||||
once. When the page's whoami already reads the email as confirmed,
|
||||
`requestEmailConfirmation()` resolves `{ response: true }` without framing
|
||||
anything, and a confirmation in the frame marks that whoami confirmed for the
|
||||
calls after it. An email the GUI reads as confirmed shows nothing. Before
|
||||
opening a window the GUI waits for the frame to have a viewport, as the upgrade
|
||||
does. It then posts
|
||||
`{ msg: 'puterPopupFrame', state: 'closed', confirmed }`, and
|
||||
`requestEmailConfirmation()` resolves `{ response: confirmed }`, the field an
|
||||
app reads from the desktop's answer. A call made while the frame shows settles
|
||||
with it. A frame that is refused, never ready, or `unavailable` resolves
|
||||
`{ response: false }`, since there's no popup to fall back to.
|
||||
|
||||
## Checks
|
||||
|
||||
Run the GUI component/browser tests (with the SDK bundle built and Playwright
|
||||
Chromium installed), and the backend route tests:
|
||||
|
||||
```sh
|
||||
npx vitest run --config src/gui/vitest.config.js src/gui/src/UI/Dashboard/AppBrowser src/feedbackEmbed
|
||||
npx vitest run src/puter-js/src/lib/guiEmbed.test.js src/puter-js/src/modules/UI.showFeedbackDialog.test.js src/puter-js/src/modules/Auth.signInFrame.test.js src/puter-js/src/modules/UI.pickerFrame.test.js src/puter-js/src/modules/UI.requestUpgrade.test.js src/puter-js/src/lib/upgradePrompt.test.js src/puter-js/src/modules/UsageLimitDialog.upgrade.test.js
|
||||
npx vitest run --config src/gui/vitest.config.js src/gui/src/helpers/popupFrame.test.js
|
||||
npx vitest run --config src/gui/vitest.config.js src/gui/src/UI/Dashboard/AppBrowser
|
||||
npx vitest run --config src/backend/vitest.config.ts src/backend/server.test.ts
|
||||
```
|
||||
@@ -420,11 +420,7 @@ export type EventMap = {
|
||||
old_username: string;
|
||||
new_username: string;
|
||||
};
|
||||
'user.email-changed': {
|
||||
user_id: number;
|
||||
old_email: string | null;
|
||||
new_email: string;
|
||||
};
|
||||
'user.email-changed': { user_id: number; new_email: string };
|
||||
/** An account was suspended, or its suspension lifted. Local events. */
|
||||
'user.suspended': { userId: number };
|
||||
'user.unsuspended': { userId: number };
|
||||
|
||||
@@ -21,8 +21,6 @@
|
||||
import { GetObjectCommand } from '@aws-sdk/client-s3';
|
||||
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
|
||||
import { existsSync } from 'node:fs';
|
||||
import { createServer, type Server } from 'node:http';
|
||||
import type { AddressInfo } from 'node:net';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
@@ -202,77 +200,6 @@ describe('S3Client — remote endpoint configuration', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('S3Client — bucket in another region', () => {
|
||||
let server: Server;
|
||||
let client: S3Client;
|
||||
let signedRegions: string[];
|
||||
|
||||
// Answers like a bucket that lives in us-west-2: a request signed for any
|
||||
// other region gets S3's 301 naming the bucket's region.
|
||||
beforeEach(async () => {
|
||||
signedRegions = [];
|
||||
server = createServer((req, res) => {
|
||||
const region =
|
||||
/Credential=[^/]+\/\d{8}\/([^/]+)\//.exec(
|
||||
req.headers.authorization ?? '',
|
||||
)?.[1] ?? '';
|
||||
signedRegions.push(region);
|
||||
if (region !== 'us-west-2') {
|
||||
res.writeHead(301, {
|
||||
'content-type': 'application/xml',
|
||||
'x-amz-bucket-region': 'us-west-2',
|
||||
});
|
||||
res.end(
|
||||
'<?xml version="1.0" encoding="UTF-8"?><Error><Code>PermanentRedirect</Code><Message>The bucket you are attempting to access must be addressed using the specified endpoint.</Message></Error>',
|
||||
);
|
||||
return;
|
||||
}
|
||||
res.writeHead(200, {
|
||||
'content-type': 'text/plain',
|
||||
'content-length': '5',
|
||||
});
|
||||
res.end('hello');
|
||||
});
|
||||
await new Promise<void>((resolve) =>
|
||||
server.listen(0, '127.0.0.1', resolve),
|
||||
);
|
||||
const { port } = server.address() as AddressInfo;
|
||||
client = new S3Client({
|
||||
port: 0,
|
||||
extensions: [],
|
||||
s3: {
|
||||
s3Config: {
|
||||
endpoint: `http://127.0.0.1:${port}`,
|
||||
accessKeyId: 'fakeAccessKeyId',
|
||||
secretAccessKey: 'fakeSecretAccessKey',
|
||||
forcePathStyle: true,
|
||||
},
|
||||
},
|
||||
} as unknown as IConfig);
|
||||
await client.onServerStart();
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await client.onServerShutdown();
|
||||
server.closeAllConnections();
|
||||
await new Promise<void>((resolve) => server.close(() => resolve()));
|
||||
});
|
||||
|
||||
it("retries a read in the bucket's region when S3 redirects it", async () => {
|
||||
const result = await client
|
||||
.get('ap-northeast-2')
|
||||
.send(
|
||||
new GetObjectCommand({
|
||||
Bucket: 'other-bucket',
|
||||
Key: 'index.html',
|
||||
}),
|
||||
);
|
||||
|
||||
expect(await result.Body?.transformToString()).toBe('hello');
|
||||
expect(signedRegions).toEqual(['ap-northeast-2', 'us-west-2']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('S3Client — legacy storage migration', () => {
|
||||
let client: S3Client;
|
||||
let dir: string;
|
||||
|
||||
@@ -235,9 +235,6 @@ export class S3Client extends PuterClient {
|
||||
|
||||
const client = new AwsS3Client({
|
||||
region,
|
||||
// Rows without a stored region are read with the server's own, so
|
||||
// retry where S3's 301 says the bucket actually lives.
|
||||
followRegionRedirects: true,
|
||||
requestStreamBufferSize: 32 * 1024,
|
||||
requestHandler: new NodeHttpHandler({
|
||||
socketTimeout: 5000,
|
||||
|
||||
@@ -7468,11 +7468,6 @@ describe('AuthController user-protected mutations (validation paths)', () => {
|
||||
{ expiresIn: '1h' },
|
||||
);
|
||||
|
||||
const heard: Array<Record<string, unknown>> = [];
|
||||
eventClient.on('user.email-changed', (_k, data) => {
|
||||
heard.push(data as Record<string, unknown>);
|
||||
});
|
||||
|
||||
const req = makeReq({});
|
||||
(req as unknown as { query: Record<string, string> }).query = {
|
||||
token: linkJwt,
|
||||
@@ -7480,11 +7475,6 @@ describe('AuthController user-protected mutations (validation paths)', () => {
|
||||
const res = makeRes();
|
||||
await controller.handleChangeEmailConfirm(req, res);
|
||||
expect(res.sent).toMatch(/Email changed successfully/);
|
||||
expect(heard).toContainEqual({
|
||||
user_id: user.id,
|
||||
old_email: user.email ?? null,
|
||||
new_email: newEmail,
|
||||
});
|
||||
|
||||
const after = await server.stores.user.getById(user.id, {
|
||||
force: true,
|
||||
|
||||
@@ -2647,7 +2647,6 @@ export class AuthController extends PuterController {
|
||||
'user.email-changed' as never,
|
||||
{
|
||||
user_id: user.id,
|
||||
old_email: user.email ?? null,
|
||||
new_email: newEmail,
|
||||
} as never,
|
||||
{},
|
||||
|
||||
@@ -15,6 +15,7 @@ export interface OidcLoginContinuation {
|
||||
embeddedInPopup: boolean;
|
||||
openerOrigin: string | null;
|
||||
messageId: string | null;
|
||||
switchedToLogin: boolean;
|
||||
}
|
||||
|
||||
interface OidcReturnDeps {
|
||||
@@ -55,6 +56,7 @@ export function completeOidcLoginReturn(
|
||||
data.userUuid !== user.uuid ||
|
||||
typeof data.redirectUri !== 'string' ||
|
||||
typeof data.embeddedInPopup !== 'boolean' ||
|
||||
typeof data.switchedToLogin !== 'boolean' ||
|
||||
(data.openerOrigin !== null && typeof data.openerOrigin !== 'string') ||
|
||||
(data.messageId !== null && typeof data.messageId !== 'string')
|
||||
) {
|
||||
@@ -89,5 +91,6 @@ export function completeOidcLoginReturn(
|
||||
),
|
||||
);
|
||||
}
|
||||
if (data.switchedToLogin) append('oidc_switched', 'login');
|
||||
return target;
|
||||
}
|
||||
@@ -27,7 +27,7 @@ import type { Actor } from '../../core/actor.js';
|
||||
import { PuterRouter } from '../../core/http/PuterRouter.js';
|
||||
import { PuterServer } from '../../server.js';
|
||||
import { setupTestServer } from '../../testUtil.js';
|
||||
import { embedFrameAncestors, embedHostOrigin } from './HomepageController.js';
|
||||
import { embedFrameAncestors } from './HomepageController.js';
|
||||
|
||||
// ── Test harness ────────────────────────────────────────────────────
|
||||
//
|
||||
@@ -550,26 +550,3 @@ describe('embedFrameAncestors', () => {
|
||||
).toBe("'self'");
|
||||
});
|
||||
});
|
||||
|
||||
describe('embedHostOrigin', () => {
|
||||
const config = {
|
||||
origin: 'https://example.test',
|
||||
domain: 'example.test',
|
||||
api_base_url: 'https://backend.example.test',
|
||||
static_hosting_domain: 'site.example.test',
|
||||
};
|
||||
|
||||
it.each([
|
||||
['https://sheets.example.test/doc/1', 'https://sheets.example.test'],
|
||||
['https://backend.example.test/x', null],
|
||||
['https://api.example.test/', null],
|
||||
['https://someone.site.example.test/', null],
|
||||
['https://a.sheets.example.test/', null],
|
||||
['http://sheets.example.test/', null],
|
||||
['https://example.test/', null],
|
||||
['not a url', null],
|
||||
[undefined, null],
|
||||
])('%s frames as %s', (referer, expected) => {
|
||||
expect(embedHostOrigin(config, referer)).toBe(expected);
|
||||
});
|
||||
});
|
||||
@@ -31,24 +31,8 @@ import type {
|
||||
PuterHomepageService,
|
||||
PageMeta,
|
||||
LaunchOptions,
|
||||
PopupFrame,
|
||||
} from '../../services/homepage/PuterHomepageService';
|
||||
|
||||
/**
|
||||
* GUI popups a first-party page can show in a frame at `/embed/<action>`,
|
||||
* instead of opening `/action/<action>` in a window, plus the upgrade dialog,
|
||||
* which it would otherwise open in a dashboard tab, and the email confirmation,
|
||||
* which it otherwise can't show.
|
||||
*/
|
||||
export const FRAMED_POPUP_ACTIONS = [
|
||||
'sign-in',
|
||||
'show-open-file-picker',
|
||||
'show-save-file-picker',
|
||||
'show-directory-picker',
|
||||
'upgrade',
|
||||
'request-email-confirmation',
|
||||
] as const;
|
||||
|
||||
/** Longest description/og:description/twitter:description on `/app/<name>`. */
|
||||
export const APP_META_DESCRIPTION_MAX = 150;
|
||||
|
||||
@@ -77,34 +61,32 @@ export function appMetaDescription(text: string): string {
|
||||
return `${cut.replace(/[\s,;:.!?…—-]+$/, '')}…`;
|
||||
}
|
||||
|
||||
type EmbedFramingConfig = Pick<
|
||||
IConfig,
|
||||
| 'origin'
|
||||
| 'domain'
|
||||
| 'api_base_url'
|
||||
| 'static_hosting_domain'
|
||||
| 'static_hosting_domain_alt'
|
||||
| 'private_app_hosting_domain'
|
||||
| 'private_app_hosting_domain_alt'
|
||||
>;
|
||||
|
||||
/**
|
||||
* The origin of a first-party page that may frame an `/embed/*` page, named
|
||||
* exactly from the request's referrer, or null. A wildcard over `*.<domain>`
|
||||
* `frame-ancestors` for the app browser embed. A wildcard over `*.<domain>`
|
||||
* would also admit user-hosted sites whenever the hosting domains sit under it,
|
||||
* so only a single label under `<domain>` qualifies, and not one this server
|
||||
* answers itself (the API, WebDAV, SDK and native-app hosts).
|
||||
* so the embedding page is named exactly, from the request's referrer. Only a
|
||||
* single label under `<domain>` qualifies, and not one this server answers
|
||||
* itself (the API, WebDAV, SDK and native-app hosts).
|
||||
*/
|
||||
export function embedHostOrigin(
|
||||
config: EmbedFramingConfig,
|
||||
export function embedFrameAncestors(
|
||||
config: Pick<
|
||||
IConfig,
|
||||
| 'origin'
|
||||
| 'domain'
|
||||
| 'api_base_url'
|
||||
| 'static_hosting_domain'
|
||||
| 'static_hosting_domain_alt'
|
||||
| 'private_app_hosting_domain'
|
||||
| 'private_app_hosting_domain_alt'
|
||||
>,
|
||||
referer: string | undefined,
|
||||
): string | null {
|
||||
): string {
|
||||
const gui = new URL(config.origin ?? `https://${config.domain}`);
|
||||
let parent: URL;
|
||||
try {
|
||||
parent = new URL(referer ?? '');
|
||||
} catch {
|
||||
return null;
|
||||
return "'self'";
|
||||
}
|
||||
const host = parent.hostname.toLowerCase();
|
||||
const label = subdomainLabelOf(host, config.domain);
|
||||
@@ -123,16 +105,7 @@ export function embedHostOrigin(
|
||||
!isReservedSubdomain(label) &&
|
||||
host !== new URL(config.api_base_url).hostname &&
|
||||
!hostingDomains.some((d) => host === d || host.endsWith(`.${d}`));
|
||||
return allowed ? parent.origin : null;
|
||||
}
|
||||
|
||||
/** `frame-ancestors` for an `/embed/*` page: the GUI and {@link embedHostOrigin}. */
|
||||
export function embedFrameAncestors(
|
||||
config: EmbedFramingConfig,
|
||||
referer: string | undefined,
|
||||
): string {
|
||||
const host = embedHostOrigin(config, referer);
|
||||
return host ? `'self' ${host}` : "'self'";
|
||||
return allowed ? `'self' ${parent.origin}` : "'self'";
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -169,7 +142,6 @@ export class HomepageController extends PuterController {
|
||||
res: express.Response,
|
||||
metaOverrides: Partial<PageMeta> = {},
|
||||
launch: LaunchOptions = {},
|
||||
popupFrame?: PopupFrame,
|
||||
) => {
|
||||
const meta = { ...defaultMeta(req), ...metaOverrides };
|
||||
const actor =
|
||||
@@ -178,27 +150,19 @@ export class HomepageController extends PuterController {
|
||||
actor?: Parameters<typeof homepage.send>[0]['actor'];
|
||||
}
|
||||
).actor ?? null;
|
||||
await homepage.send({ req, res, actor }, meta, launch, popupFrame);
|
||||
await homepage.send({ req, res, actor }, meta, launch);
|
||||
};
|
||||
|
||||
// -- Root + path-aliased shell routes ------------------------
|
||||
|
||||
router.get('/', {}, (req, res) => sendShell(req, res));
|
||||
|
||||
/**
|
||||
* Headers shared by the `/embed/*` pages; false when the request was
|
||||
* redirected instead. SDK bootstrap parameters must not change an
|
||||
* embed's account or API origin, so a query string is dropped. Checked
|
||||
* on the raw URL; `req.query` drops pairs past the parser's limit.
|
||||
*/
|
||||
const prepareEmbed = (
|
||||
req: express.Request,
|
||||
res: express.Response,
|
||||
path: string,
|
||||
): boolean => {
|
||||
router.get('/embed/apps', {}, async (req, res) => {
|
||||
// SDK bootstrap parameters must not change this page's account or API origin.
|
||||
// Checked on the raw URL; `req.query` drops pairs past the parser's limit.
|
||||
if (req.originalUrl.includes('?')) {
|
||||
res.redirect(path);
|
||||
return false;
|
||||
res.redirect('/embed/apps');
|
||||
return;
|
||||
}
|
||||
res.removeHeader('X-Frame-Options');
|
||||
res.setHeader(
|
||||
@@ -206,11 +170,6 @@ export class HomepageController extends PuterController {
|
||||
`frame-ancestors ${embedFrameAncestors(this.config, req.get('referer'))}`,
|
||||
);
|
||||
res.setHeader('Cache-Control', 'no-store');
|
||||
return true;
|
||||
};
|
||||
|
||||
router.get('/embed/apps', {}, async (req, res) => {
|
||||
if (!prepareEmbed(req, res, '/embed/apps')) return;
|
||||
// Shown to visitors without a session; a signed-in embed fetches
|
||||
// its own list, so a failure here only costs signed-out visitors.
|
||||
const guestApps = await this.services.recommendedApps
|
||||
@@ -219,48 +178,6 @@ export class HomepageController extends PuterController {
|
||||
res.send(homepage.renderAppBrowserEmbed({ guestApps }));
|
||||
});
|
||||
|
||||
router.get('/embed/feedback', {}, (req, res) => {
|
||||
if (!prepareEmbed(req, res, '/embed/feedback')) return;
|
||||
// The feedback is recorded against this origin, which
|
||||
// frame-ancestors has just pinned to the actual framing page.
|
||||
res.send(
|
||||
homepage.renderFeedbackEmbed({
|
||||
hostOrigin: embedHostOrigin(
|
||||
this.config,
|
||||
req.get('referer'),
|
||||
),
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
// The GUI runs the popup's own boot, answering the framing page
|
||||
// instead of an opener.
|
||||
for (const action of FRAMED_POPUP_ACTIONS) {
|
||||
const embedPath = `/embed/${action}`;
|
||||
router.get(embedPath, {}, async (req, res) => {
|
||||
// Routes match case-insensitively and with a trailing slash,
|
||||
// and the shell boots the desktop for any other spelling, so
|
||||
// only the exact one may be framed.
|
||||
if (req.originalUrl !== embedPath) {
|
||||
res.redirect(embedPath);
|
||||
return;
|
||||
}
|
||||
if (!prepareEmbed(req, res, embedPath)) return;
|
||||
await sendShell(
|
||||
req,
|
||||
res,
|
||||
{},
|
||||
{},
|
||||
{
|
||||
hostOrigin: embedHostOrigin(
|
||||
this.config,
|
||||
req.get('referer'),
|
||||
),
|
||||
},
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
router.get('/settings', {}, (req, res) => sendShell(req, res));
|
||||
router.get('/settings/*splat', {}, (req, res) => sendShell(req, res));
|
||||
|
||||
|
||||
@@ -1620,7 +1620,7 @@ describe('OIDCController signup callback', () => {
|
||||
expect(captured.redirectUrl).toContain('action=signup');
|
||||
});
|
||||
|
||||
it('creates a fresh user on first signup', async () => {
|
||||
it('creates a fresh user without oidc_switched on first signup', async () => {
|
||||
const state = oidc().signState({
|
||||
provider: 'custom',
|
||||
redirect_uri: TEST_ORIGIN + '/',
|
||||
@@ -1646,9 +1646,11 @@ describe('OIDCController signup callback', () => {
|
||||
);
|
||||
expect(captured.cookies).toHaveLength(1);
|
||||
expect(captured.redirectUrl).toBe(TEST_ORIGIN + '/');
|
||||
// Fresh creation — must NOT advertise "you've actually been signed in".
|
||||
expect(captured.redirectUrl).not.toContain('oidc_switched=login');
|
||||
});
|
||||
|
||||
it('signs in to an already-linked account on signup, returning as a login would', async () => {
|
||||
it('adds oidc_switched=login when signup hits an already-linked account', async () => {
|
||||
// Seed an account linked on (provider, sub) so the signup callback
|
||||
// resolves to `linked-sub` rather than creating a new user.
|
||||
const sub = `sub-${Math.random().toString(36).slice(2, 8)}`;
|
||||
@@ -1684,7 +1686,7 @@ describe('OIDCController signup callback', () => {
|
||||
res,
|
||||
);
|
||||
expect(captured.cookies).toHaveLength(1);
|
||||
expect(captured.redirectUrl).toBe(TEST_ORIGIN + '/');
|
||||
expect(captured.redirectUrl).toContain('oidc_switched=login');
|
||||
});
|
||||
|
||||
it('redirects to action=signup with auth_error when user resolution fails (unconfirmed email)', async () => {
|
||||
|
||||
@@ -688,7 +688,14 @@ export class OIDCController extends PuterController {
|
||||
);
|
||||
}
|
||||
|
||||
await this.#finishLogin(req, res, user, stateDecoded);
|
||||
// If we landed on an existing account (either via the
|
||||
// provider_sub or via email match), signal the GUI so it can
|
||||
// render a "signed in" flow rather than "account created".
|
||||
const extra =
|
||||
resolved.origin === 'created'
|
||||
? undefined
|
||||
: { oidc_switched: 'login' };
|
||||
await this.#finishLogin(req, res, user, stateDecoded, extra);
|
||||
};
|
||||
router.get('/auth/oidc/callback/signup', cbOpts, signupCb);
|
||||
router.post('/auth/oidc/callback/signup', cbOpts, signupCb);
|
||||
@@ -827,14 +834,17 @@ if (window.opener) {
|
||||
attempt = 0,
|
||||
): Promise<
|
||||
| { error: string; code?: string; requestCode?: string }
|
||||
| { user: import('../../stores/user/UserStore.js').UserRow }
|
||||
| {
|
||||
user: import('../../stores/user/UserStore.js').UserRow;
|
||||
origin: 'linked-sub' | 'linked-email' | 'created';
|
||||
}
|
||||
> {
|
||||
// 1. Existing provider/sub link.
|
||||
const linked = await this.services.oidc.findUserByProviderSub(
|
||||
provider,
|
||||
userinfo.sub,
|
||||
);
|
||||
if (linked) return { user: linked };
|
||||
if (linked) return { user: linked, origin: 'linked-sub' };
|
||||
|
||||
// 2/3. Email match branch.
|
||||
const claimedEmail =
|
||||
@@ -871,7 +881,7 @@ if (window.opener) {
|
||||
error: outcome.error ?? 'Failed to link provider.',
|
||||
};
|
||||
}
|
||||
return { user: byEmail };
|
||||
return { user: byEmail, origin: 'linked-email' };
|
||||
}
|
||||
}
|
||||
|
||||
@@ -901,7 +911,7 @@ if (window.opener) {
|
||||
requestCode: outcome.requestCode,
|
||||
};
|
||||
}
|
||||
return { user: outcome.user };
|
||||
return { user: outcome.user, origin: 'created' };
|
||||
}
|
||||
|
||||
async #processCallback(
|
||||
@@ -990,6 +1000,7 @@ if (window.opener) {
|
||||
res: Response,
|
||||
user: UserRow,
|
||||
stateDecoded: Record<string, unknown>,
|
||||
extraQueryParams?: Record<string, string>,
|
||||
): Promise<void> {
|
||||
const origin = (this.config.origin ?? '').replace(/\/$/, '');
|
||||
const continuation: OidcLoginContinuation = {
|
||||
@@ -1007,6 +1018,7 @@ if (window.opener) {
|
||||
stateDecoded.msg_id == null
|
||||
? null
|
||||
: String(stateDecoded.msg_id),
|
||||
switchedToLogin: extraQueryParams?.oidc_switched === 'login',
|
||||
};
|
||||
if (user.otp_enabled) {
|
||||
const challenge = this.services.token.sign(
|
||||
|
||||
@@ -139,7 +139,7 @@ describe('OIDC account second-factor login', () => {
|
||||
expect(await response.json()).toMatchObject({
|
||||
proceed: true,
|
||||
next_step: 'complete',
|
||||
redirectUrl: `${env.origin}/dashboard`,
|
||||
redirectUrl: `${env.origin}/dashboard${flow === 'signup' ? '?oidc_switched=login' : ''}`,
|
||||
});
|
||||
expect(
|
||||
response.headers
|
||||
|
||||
@@ -187,9 +187,9 @@ describe('createUserSubdomainNotFound', () => {
|
||||
});
|
||||
|
||||
it('passes through reserved subdomains (api, js, native apps, etc.)', () => {
|
||||
// `api`, `js`, `dav`, `docs`, `developer`, `about`, `apps`,
|
||||
// `api`, `js`, `dav`, `docs`, `developer`, `editor`, `pdf`,
|
||||
// `puter-app-icons`, etc. all pass through.
|
||||
for (const sub of ['api', 'js', 'docs', 'about', 'puter-app-icons']) {
|
||||
for (const sub of ['api', 'js', 'docs', 'editor', 'puter-app-icons']) {
|
||||
const { out, next } = run(
|
||||
createUserSubdomainNotFound(config),
|
||||
makeReq({
|
||||
@@ -865,13 +865,13 @@ describe('createNativeAppStatic', () => {
|
||||
|
||||
beforeAll(() => {
|
||||
root = mkdtempSync(nodePath.join(tmpdir(), 'native-apps-'));
|
||||
mkdirSync(nodePath.join(root, 'about', 'assets'), { recursive: true });
|
||||
mkdirSync(nodePath.join(root, 'editor', 'assets'), { recursive: true });
|
||||
writeFileSync(
|
||||
nodePath.join(root, 'about', 'index.html'),
|
||||
'<h1>about</h1>',
|
||||
nodePath.join(root, 'editor', 'index.html'),
|
||||
'<h1>editor</h1>',
|
||||
);
|
||||
writeFileSync(
|
||||
nodePath.join(root, 'about', 'assets', 'app.js'),
|
||||
nodePath.join(root, 'editor', 'assets', 'app.js'),
|
||||
'console.log(1);',
|
||||
);
|
||||
mkdirSync(nodePath.join(root, 'docs', 'dist'), { recursive: true });
|
||||
@@ -893,7 +893,7 @@ describe('createNativeAppStatic', () => {
|
||||
|
||||
it('leaves a native app name alone on a host outside our domains', async () => {
|
||||
const req = staticReq({
|
||||
subdomains: ['com', 'example', 'about'],
|
||||
subdomains: ['com', 'example', 'editor'],
|
||||
path: '/index.html',
|
||||
});
|
||||
(req as Request & { is_custom_domain?: boolean }).is_custom_domain =
|
||||
@@ -907,7 +907,7 @@ describe('createNativeAppStatic', () => {
|
||||
const { out, next } = await runStatic(
|
||||
createNativeAppStatic(config),
|
||||
staticReq({
|
||||
subdomains: ['localhost', 'puter', 'about'],
|
||||
subdomains: ['localhost', 'puter', 'editor'],
|
||||
path: '/index.html',
|
||||
}),
|
||||
);
|
||||
@@ -915,24 +915,17 @@ describe('createNativeAppStatic', () => {
|
||||
expect(next).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
// `editor`, `markus` and `pdf` are web apps on standard host routing,
|
||||
// even with a folder of their own under the native apps root.
|
||||
it.each(['api', 'editor', 'markus', 'pdf'])(
|
||||
'passes %s through, as it is not a native app',
|
||||
async (sub) => {
|
||||
mkdirSync(nodePath.join(root, sub), { recursive: true });
|
||||
writeFileSync(nodePath.join(root, sub, 'index.html'), sub);
|
||||
const { out, next } = await runStatic(
|
||||
withRoot(),
|
||||
staticReq({
|
||||
subdomains: ['localhost', 'puter', sub],
|
||||
path: '/index.html',
|
||||
}),
|
||||
);
|
||||
expect(out.sent).toBeUndefined();
|
||||
expect(next).toHaveBeenCalledTimes(1);
|
||||
},
|
||||
);
|
||||
it('passes through subdomains that are not native apps', async () => {
|
||||
const { out, next } = await runStatic(
|
||||
withRoot(),
|
||||
staticReq({
|
||||
subdomains: ['localhost', 'puter', 'api'],
|
||||
path: '/index.html',
|
||||
}),
|
||||
);
|
||||
expect(out.sent).toBeUndefined();
|
||||
expect(next).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('passes through when there is no subdomain at all', async () => {
|
||||
const { next } = await runStatic(
|
||||
@@ -946,13 +939,13 @@ describe('createNativeAppStatic', () => {
|
||||
const { out, next } = await runStatic(
|
||||
withRoot(),
|
||||
staticReq({
|
||||
subdomains: ['localhost', 'puter', 'about'],
|
||||
subdomains: ['localhost', 'puter', 'editor'],
|
||||
path: '/index.html',
|
||||
}),
|
||||
);
|
||||
expect(out.sent).toEqual({
|
||||
path: '/index.html',
|
||||
root: nodePath.join(root, 'about'),
|
||||
root: nodePath.join(root, 'editor'),
|
||||
});
|
||||
expect(next).not.toHaveBeenCalled();
|
||||
});
|
||||
@@ -961,11 +954,11 @@ describe('createNativeAppStatic', () => {
|
||||
const { out } = await runStatic(
|
||||
withRoot(),
|
||||
staticReq({
|
||||
subdomains: ['localhost', 'puter', 'ABOUT'],
|
||||
subdomains: ['localhost', 'puter', 'EDITOR'],
|
||||
path: '/index.html',
|
||||
}),
|
||||
);
|
||||
expect(out.sent?.root).toBe(nodePath.join(root, 'about'));
|
||||
expect(out.sent?.root).toBe(nodePath.join(root, 'editor'));
|
||||
});
|
||||
|
||||
it('serves docs out of its dist/ subdirectory, not the app root', async () => {
|
||||
@@ -986,7 +979,7 @@ describe('createNativeAppStatic', () => {
|
||||
const { out, next } = await runStatic(
|
||||
withRoot(),
|
||||
staticReq({
|
||||
subdomains: ['localhost', 'puter', 'about'],
|
||||
subdomains: ['localhost', 'puter', 'editor'],
|
||||
path: '/assets',
|
||||
originalUrl: '/assets?v=2',
|
||||
}),
|
||||
@@ -1002,7 +995,7 @@ describe('createNativeAppStatic', () => {
|
||||
const { out } = await runStatic(
|
||||
withRoot(),
|
||||
staticReq({
|
||||
subdomains: ['localhost', 'puter', 'about'],
|
||||
subdomains: ['localhost', 'puter', 'editor'],
|
||||
path: '/assets/',
|
||||
}),
|
||||
);
|
||||
@@ -1014,7 +1007,7 @@ describe('createNativeAppStatic', () => {
|
||||
const { out, next } = await runStatic(
|
||||
withRoot(),
|
||||
staticReq({
|
||||
subdomains: ['localhost', 'puter', 'about'],
|
||||
subdomains: ['localhost', 'puter', 'editor'],
|
||||
path: '/nope.html',
|
||||
}),
|
||||
);
|
||||
@@ -1026,7 +1019,7 @@ describe('createNativeAppStatic', () => {
|
||||
const { next } = await runStatic(
|
||||
withRoot(),
|
||||
staticReq({
|
||||
subdomains: ['localhost', 'puter', 'about'],
|
||||
subdomains: ['localhost', 'puter', 'editor'],
|
||||
path: '/index.html',
|
||||
}),
|
||||
new Error('send failed'),
|
||||
@@ -1039,7 +1032,7 @@ describe('createNativeAppStatic', () => {
|
||||
runStatic(
|
||||
withRoot(),
|
||||
staticReq({
|
||||
subdomains: ['localhost', 'puter', 'about'],
|
||||
subdomains: ['localhost', 'puter', 'editor'],
|
||||
path: '/../../etc/passwd',
|
||||
}),
|
||||
),
|
||||
|
||||
@@ -27,7 +27,15 @@ import { HttpError, isHttpError } from '../HttpError';
|
||||
import { isLocalWorkerHost } from './localWorkerProxy';
|
||||
|
||||
/** Native-app subdomains served via `nativeAppStatic`. */
|
||||
const NATIVE_APP_SUBDOMAINS = ['about', 'developer', 'docs', 'apps'] as const;
|
||||
const NATIVE_APP_SUBDOMAINS = [
|
||||
'about',
|
||||
'developer',
|
||||
'docs',
|
||||
'editor',
|
||||
'markus',
|
||||
'pdf',
|
||||
'apps',
|
||||
] as const;
|
||||
|
||||
/** Subset served out of a `dist/` subdirectory rather than the app root. */
|
||||
const NATIVE_APPS_WITH_DIST = new Set(['docs', 'developer']);
|
||||
|
||||
@@ -2222,166 +2222,3 @@ describe('ChatCompletionDriver.countTokens', () => {
|
||||
).rejects.toMatchObject({ statusCode: 400 });
|
||||
});
|
||||
});
|
||||
|
||||
describe('ChatCompletionDriver service speed', () => {
|
||||
it.each([
|
||||
[{ serviceSpeed: 'ultrafast' }, 'fast', 0.028],
|
||||
[{ speed: 'fast' }, 'fast', 0.028],
|
||||
[{ serviceSpeed: 'standard', speed: 'fast' }, 'standard', 0.014],
|
||||
] as const)('uses the Claude catalog rate card for %j', async (options, speed, cents) => {
|
||||
const sent: Record<string, unknown>[] = [];
|
||||
vi.stubGlobal('fetch', async (input: Request | string, init?: RequestInit) => {
|
||||
const body = input instanceof Request
|
||||
? await input.clone().json()
|
||||
: JSON.parse(String(init?.body));
|
||||
sent.push(body);
|
||||
return new Response(JSON.stringify({
|
||||
id: 'claude-speed-test', type: 'message', role: 'assistant',
|
||||
model: body.model, stop_reason: 'end_turn',
|
||||
content: [{ type: 'text', text: 'OK' }],
|
||||
usage: { input_tokens: 10, output_tokens: 5, speed },
|
||||
}), { headers: { 'content-type': 'application/json' } });
|
||||
});
|
||||
const d = new ChatCompletionDriver(
|
||||
{ providers: { claude: { apiKey: 'test-key' }, ollama: { enabled: false } } } as never,
|
||||
server.clients, server.stores, server.services,
|
||||
);
|
||||
try {
|
||||
await d.onServerStart();
|
||||
const result = await withTestActor(() => d.complete({
|
||||
model: 'claude-opus-5-5', provider: 'claude',
|
||||
messages: [{ role: 'user', content: 'Hello' }],
|
||||
fallback: false, max_tokens: 32, normalize: true, ...options,
|
||||
}));
|
||||
expect(sent).toHaveLength(1);
|
||||
expect(sent[0]!.speed).toBe(speed === 'fast' ? 'fast' : undefined);
|
||||
expect(result).toMatchObject({
|
||||
message: { content: 'OK' }, usage: { usd_cents: cents },
|
||||
});
|
||||
} finally {
|
||||
d.onServerShutdown();
|
||||
vi.unstubAllGlobals();
|
||||
}
|
||||
});
|
||||
|
||||
it.each([
|
||||
null, false, true, 0, 1, -1, NaN, Infinity, '', 'invalid', 'FAST',
|
||||
'fast ', ' fast', 'ultraFast', [], ['fast'], {}, { speed: 'fast' },
|
||||
{ toString: 'fast' },
|
||||
])('rejects invalid speed %j before sending a request', async (serviceSpeed) => {
|
||||
await expect(
|
||||
withTestActor(() =>
|
||||
driver.complete({
|
||||
model: 'fake',
|
||||
messages: [{ role: 'user', content: 'Hello' }],
|
||||
serviceSpeed: serviceSpeed as never,
|
||||
}),
|
||||
),
|
||||
).rejects.toMatchObject({
|
||||
statusCode: 400,
|
||||
legacyCode: 'invalid_service_speed',
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
['openai-responses', true],
|
||||
['openai-responses', false],
|
||||
['openai-completion', false],
|
||||
] as const)(
|
||||
'settles unavailable tiers at standard rates on %s with provider fallback disabled (admission rejection: %s)',
|
||||
async (provider, rejectFast) => {
|
||||
const sent: Record<string, unknown>[] = [];
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
async (_input: unknown, init?: RequestInit) => {
|
||||
const body =
|
||||
_input instanceof Request
|
||||
? await _input.clone().json()
|
||||
: JSON.parse(String(init?.body));
|
||||
sent.push(body);
|
||||
if (rejectFast && body.service_tier !== 'default') {
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
error: {
|
||||
message: `${body.service_tier} service_tier capacity unavailable`,
|
||||
type: 'invalid_request_error',
|
||||
},
|
||||
}),
|
||||
{
|
||||
status: 400,
|
||||
headers: { 'content-type': 'application/json' },
|
||||
},
|
||||
);
|
||||
}
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
id: 'response-test',
|
||||
object: 'response',
|
||||
model: body.model,
|
||||
status: 'completed',
|
||||
service_tier: 'default',
|
||||
output: [
|
||||
{
|
||||
type: 'message',
|
||||
role: 'assistant',
|
||||
content: [
|
||||
{ type: 'output_text', text: 'OK' },
|
||||
],
|
||||
},
|
||||
],
|
||||
usage: {
|
||||
input_tokens: 10,
|
||||
output_tokens: 2,
|
||||
input_tokens_details: { cached_tokens: 0 },
|
||||
},
|
||||
}),
|
||||
{ headers: { 'content-type': 'application/json' } },
|
||||
);
|
||||
},
|
||||
);
|
||||
const d = new ChatCompletionDriver(
|
||||
{
|
||||
providers: {
|
||||
'openai-completion': { apiKey: 'test-key' },
|
||||
ollama: { enabled: false },
|
||||
},
|
||||
} as never,
|
||||
server.clients,
|
||||
server.stores,
|
||||
server.services,
|
||||
);
|
||||
try {
|
||||
await d.onServerStart();
|
||||
const result = (await withTestActor(() =>
|
||||
d.complete({
|
||||
model: 'gpt-6.1-sol',
|
||||
provider,
|
||||
messages: [{ role: 'user', content: 'Hello' }],
|
||||
serviceSpeed: 'ultrafast',
|
||||
fallback: false,
|
||||
max_tokens: 32,
|
||||
normalize: true,
|
||||
}),
|
||||
)) as {
|
||||
message: { content: string };
|
||||
usageDetails: { serviceSpeed: string };
|
||||
usage: { usd_cents: number };
|
||||
};
|
||||
expect(sent.map((body) => body.service_tier)).toEqual(
|
||||
rejectFast
|
||||
? ['ultrafast', 'priority', 'default']
|
||||
: ['ultrafast'],
|
||||
);
|
||||
expect(sent.every((body) => body.model === 'gpt-6.1-sol')).toBe(
|
||||
true,
|
||||
);
|
||||
expect(result.message.content).toBe('OK');
|
||||
expect(result.usageDetails.serviceSpeed).toBe('standard');
|
||||
expect(result.usage.usd_cents).toBeCloseTo(0.004, 8);
|
||||
} finally {
|
||||
d.onServerShutdown();
|
||||
vi.unstubAllGlobals();
|
||||
}
|
||||
},
|
||||
);
|
||||
});
|
||||
@@ -78,11 +78,6 @@ import type {
|
||||
UsageDetails,
|
||||
} from './types.js';
|
||||
import { normalize_tools_object } from './utils/FunctionCalling.js';
|
||||
import {
|
||||
selectServiceSpeed,
|
||||
lowerServiceSpeed,
|
||||
isServiceSpeedUnavailable,
|
||||
} from './utils/serviceSpeed.js';
|
||||
import {
|
||||
messagesHavePuterPaths,
|
||||
modelSupportsModality,
|
||||
@@ -679,16 +674,6 @@ export class ChatCompletionDriver extends PuterDriver {
|
||||
}
|
||||
|
||||
async complete(args: ICompleteArguments): Promise<IChatCompleteResult> {
|
||||
if (
|
||||
args.serviceSpeed !== undefined &&
|
||||
!['standard', 'fast', 'ultrafast'].includes(args.serviceSpeed)
|
||||
) {
|
||||
throw new HttpError(
|
||||
400,
|
||||
'serviceSpeed must be standard, fast, or ultrafast',
|
||||
{ legacyCode: 'invalid_service_speed' },
|
||||
);
|
||||
}
|
||||
const abortSignal = Context.get('abortSignal');
|
||||
abortSignal?.throwIfAborted();
|
||||
const actor = Context.get('actor');
|
||||
@@ -715,16 +700,15 @@ export class ChatCompletionDriver extends PuterDriver {
|
||||
args.model = this.#providers[intendedProvider].getDefaultModel();
|
||||
}
|
||||
|
||||
const initialModel = await this.#resolveLoadedModel(
|
||||
let model = await this.#resolveLoadedModel(
|
||||
args.model,
|
||||
intendedProvider,
|
||||
);
|
||||
if (!initialModel) {
|
||||
if (!model) {
|
||||
throw new HttpError(400, `Model not found: ${args.model}`, {
|
||||
legacyCode: 'bad_request',
|
||||
});
|
||||
}
|
||||
let model: IChatModel = initialModel;
|
||||
// A pinned provider without a route for the model normally resolves
|
||||
// to another vendor; with `fallback: false` that is the one thing the
|
||||
// caller asked us not to do.
|
||||
@@ -856,6 +840,18 @@ export class ChatCompletionDriver extends PuterDriver {
|
||||
// The instant the current attempt is priced at, from its hold to its
|
||||
// charge, so a rate change mid-request can't split the two.
|
||||
let pricingTime = new Date();
|
||||
if (!useFakeProvider) {
|
||||
({
|
||||
hold,
|
||||
fundsCap,
|
||||
costFactor,
|
||||
promptTokenEstimate: attemptPromptTokenEstimate,
|
||||
} = await this.#applyCreditGate(actor, model, args, {
|
||||
promptTokenEstimate,
|
||||
requestedMaxTokens,
|
||||
pricingTime,
|
||||
}));
|
||||
}
|
||||
|
||||
// First attempt
|
||||
const provider = this.#providers[model.provider!];
|
||||
@@ -903,134 +899,24 @@ export class ChatCompletionDriver extends PuterDriver {
|
||||
return attempt;
|
||||
};
|
||||
|
||||
let variantSpeed: ICompleteArguments['serviceSpeed'];
|
||||
let creditGateError: unknown;
|
||||
const runAttempt = async (
|
||||
attemptProvider: IChatProvider,
|
||||
baseModel: IChatModel,
|
||||
attemptModel: IChatModel,
|
||||
) => {
|
||||
const offers =
|
||||
args.serviceSpeed !== undefined &&
|
||||
args.serviceSpeed !== 'standard'
|
||||
? ((await attemptProvider.serviceSpeedModels?.(
|
||||
baseModel,
|
||||
)) ?? {})
|
||||
: {};
|
||||
let requestedSpeed =
|
||||
args.serviceSpeed ??
|
||||
(baseModel.provider === 'claude' && args.speed === 'fast'
|
||||
? 'fast'
|
||||
: undefined);
|
||||
for (;;) {
|
||||
const selection = selectServiceSpeed(
|
||||
baseModel,
|
||||
{ ...args, serviceSpeed: requestedSpeed },
|
||||
(id) => {
|
||||
const variant = this.#resolveModel(
|
||||
id,
|
||||
baseModel.provider!,
|
||||
);
|
||||
return variant &&
|
||||
variant.provider === baseModel.provider
|
||||
? variant
|
||||
: undefined;
|
||||
},
|
||||
offers,
|
||||
);
|
||||
const attemptModel = selection.model;
|
||||
const requestArgs = {
|
||||
...selection.args,
|
||||
if (!useFakeProvider) {
|
||||
await this.#resolvePuterPaths(attemptProvider, args, actor);
|
||||
}
|
||||
// Last point where a caller who left costs nothing.
|
||||
abortSignal?.throwIfAborted();
|
||||
return attemptProvider.complete(
|
||||
{
|
||||
...args,
|
||||
model: attemptModel.id,
|
||||
provider: attemptModel.provider,
|
||||
};
|
||||
const catalogModel = this.#resolveModel(
|
||||
attemptModel.id,
|
||||
attemptModel.provider!,
|
||||
);
|
||||
const rawModel = this.#catalogEntries.get(
|
||||
catalogModel ?? baseModel,
|
||||
);
|
||||
const snapshot = rawModel
|
||||
? {
|
||||
...rawModel,
|
||||
costs: attemptModel.costs,
|
||||
pricingOverrides: attemptModel.pricingOverrides,
|
||||
serviceSpeedPricing: attemptModel.serviceSpeedPricing,
|
||||
}
|
||||
: attemptModel;
|
||||
if (!useFakeProvider) {
|
||||
try {
|
||||
({
|
||||
hold,
|
||||
fundsCap,
|
||||
costFactor,
|
||||
promptTokenEstimate: attemptPromptTokenEstimate,
|
||||
} = await this.#applyCreditGate(
|
||||
actor,
|
||||
attemptModel,
|
||||
requestArgs,
|
||||
{
|
||||
promptTokenEstimate,
|
||||
requestedMaxTokens,
|
||||
pricingTime,
|
||||
},
|
||||
));
|
||||
} catch (error) {
|
||||
creditGateError = error;
|
||||
throw error;
|
||||
}
|
||||
await this.#resolvePuterPaths(
|
||||
attemptProvider,
|
||||
requestArgs,
|
||||
actor,
|
||||
);
|
||||
}
|
||||
abortSignal?.throwIfAborted();
|
||||
try {
|
||||
const result = await attemptProvider.complete(
|
||||
requestArgs,
|
||||
snapshot,
|
||||
pricingTime,
|
||||
);
|
||||
model = attemptModel;
|
||||
variantSpeed =
|
||||
attemptModel.id !== baseModel.id
|
||||
? selection.speed
|
||||
: undefined;
|
||||
if (
|
||||
args.serviceSpeed !== undefined &&
|
||||
'message' in result
|
||||
) {
|
||||
const messageResult = result as IChatMessageResult;
|
||||
const details =
|
||||
messageResult.usageDetails ??
|
||||
usageDetailsFromUsage(messageResult.usage, model);
|
||||
messageResult.usageDetails = {
|
||||
...details,
|
||||
serviceSpeed:
|
||||
variantSpeed ??
|
||||
details?.serviceSpeed ??
|
||||
details?.speed ??
|
||||
'standard',
|
||||
};
|
||||
}
|
||||
return result;
|
||||
} catch (error) {
|
||||
await hold.release();
|
||||
hold = NO_CREDIT_HOLD;
|
||||
if (
|
||||
args.serviceSpeed === undefined ||
|
||||
selection.speed === 'standard' ||
|
||||
!isServiceSpeedUnavailable(
|
||||
error,
|
||||
attemptModel.id !== baseModel.id,
|
||||
)
|
||||
)
|
||||
throw error;
|
||||
requestedSpeed = lowerServiceSpeed(selection.speed);
|
||||
pricingTime = new Date();
|
||||
}
|
||||
}
|
||||
},
|
||||
this.#catalogEntries.get(attemptModel),
|
||||
pricingTime,
|
||||
);
|
||||
};
|
||||
|
||||
try {
|
||||
@@ -1098,17 +984,29 @@ export class ChatCompletionDriver extends PuterDriver {
|
||||
// The previous attempt released its hold when it failed, so
|
||||
// this one starts from nothing held.
|
||||
pricingTime = new Date();
|
||||
if (!useFakeProvider) {
|
||||
({
|
||||
hold,
|
||||
fundsCap,
|
||||
costFactor,
|
||||
promptTokenEstimate: attemptPromptTokenEstimate,
|
||||
} = await this.#applyCreditGate(actor, fallback, args, {
|
||||
promptTokenEstimate,
|
||||
requestedMaxTokens,
|
||||
pricingTime,
|
||||
}));
|
||||
}
|
||||
|
||||
tried.add(routeId(fallback.provider!, fallback.id));
|
||||
|
||||
try {
|
||||
res = await runAttempt(fbProvider, fallback);
|
||||
model = fallback;
|
||||
lastError = null;
|
||||
console.warn(
|
||||
`[ai-chat] fallback served (${completionId}, ${first.provider}:${first.model} -> ${fallback.provider}:${fallback.id}, first ${first.status ?? 'none'}${first.upstreamType ? `/${first.upstreamType}` : ''})`,
|
||||
);
|
||||
} catch (fbErr) {
|
||||
if (fbErr === creditGateError) throw fbErr;
|
||||
await hold.release();
|
||||
hold = NO_CREDIT_HOLD;
|
||||
abortSignal?.throwIfAborted();
|
||||
@@ -1264,20 +1162,6 @@ export class ChatCompletionDriver extends PuterDriver {
|
||||
usageDetailsFromUsage(usage, model),
|
||||
);
|
||||
}
|
||||
if (
|
||||
args.serviceSpeed !== undefined &&
|
||||
chatStream.usageDetails
|
||||
) {
|
||||
const details = chatStream.usageDetails;
|
||||
chatStream.setUsageDetails({
|
||||
...details,
|
||||
serviceSpeed:
|
||||
variantSpeed ??
|
||||
details.serviceSpeed ??
|
||||
details.speed ??
|
||||
'standard',
|
||||
});
|
||||
}
|
||||
withClaudeThinkingTokens(
|
||||
enrichedUsage,
|
||||
model,
|
||||
@@ -1590,7 +1474,12 @@ export class ChatCompletionDriver extends PuterDriver {
|
||||
const metering = this.services.metering;
|
||||
const { requestedMaxTokens, pricingTime } = estimates;
|
||||
let { promptTokenEstimate } = estimates;
|
||||
// Providers reserve tool calls using the same caps they send upstream.
|
||||
// A provider can name its own cost keys for this request (Claude's
|
||||
// fast-mode rate card), cap its output, and size an extra reservation
|
||||
// the per-token math can't see (a web-search/advisor tool that could
|
||||
// run several times before the model answers) — the same clamps it
|
||||
// applies when building the request, so the hold and the request
|
||||
// agree.
|
||||
const pricing =
|
||||
this.#providers[model.provider!]?.requestPricing?.(args, model, {
|
||||
promptTokenEstimate,
|
||||
|
||||
@@ -41,7 +41,6 @@ import {
|
||||
meterChatUsage,
|
||||
type MeterChatUsageOptions,
|
||||
} from '../utils/meterChatUsage.js';
|
||||
import { servedServiceSpeed } from '../utils/serviceSpeed.js';
|
||||
import { catalogPrice, costKeys } from '../utils/pricing.js';
|
||||
import { normalizeModelKey } from '../utils/modelRouting.js';
|
||||
import * as OpenAIUtil from '../utils/OpenAIUtil.js';
|
||||
@@ -233,8 +232,6 @@ export class OpenAICompatProvider implements IChatProvider {
|
||||
)
|
||||
: {}),
|
||||
};
|
||||
if (args.serviceSpeed !== undefined && args.service_tier !== undefined)
|
||||
shared.service_tier = args.service_tier;
|
||||
const params = this.vendorParams(shared, args, model, actor);
|
||||
|
||||
let pricingTime = attemptPricingTime ?? new Date();
|
||||
@@ -274,29 +271,15 @@ export class OpenAICompatProvider implements IChatProvider {
|
||||
source,
|
||||
model,
|
||||
);
|
||||
const serviceSpeed = servedServiceSpeed(source);
|
||||
if (usageDetails)
|
||||
source.setUsageDetails?.({
|
||||
...usageDetails,
|
||||
...(args.serviceSpeed !== undefined
|
||||
? { serviceSpeed }
|
||||
: {}),
|
||||
});
|
||||
if (usageDetails) source.setUsageDetails?.(usageDetails);
|
||||
const metered = meterChatUsage(
|
||||
this.#metering,
|
||||
actor,
|
||||
this.meteringModelKey(model.id),
|
||||
model,
|
||||
usage,
|
||||
{ ...meterOptions, pricingTime, serviceSpeed },
|
||||
{ ...meterOptions, pricingTime },
|
||||
);
|
||||
if (args.serviceSpeed !== undefined && !usageDetails) {
|
||||
const details = OpenAIUtil.usageDetailsFromTrackedUsage(
|
||||
metered.usage,
|
||||
);
|
||||
if (details)
|
||||
source.setUsageDetails?.({ ...details, serviceSpeed });
|
||||
}
|
||||
source.setUsageCosts(metered.costs);
|
||||
return this.reportedUsage(metered.usage);
|
||||
},
|
||||
|
||||
@@ -174,9 +174,6 @@ export const mapAlibabaCatalogModel = (
|
||||
: undefined;
|
||||
return {
|
||||
...existing,
|
||||
serviceSpeedVariants: {
|
||||
fast: id === 'glm-5.2' ? 'glm-5.2-fast-preview' : `${id}-prime`,
|
||||
},
|
||||
id,
|
||||
puterId,
|
||||
name: raw.name ?? existing?.name ?? id,
|
||||
|
||||
@@ -37,7 +37,6 @@ export const ALIBABA_MODELS: IChatModel[] = [
|
||||
costs_currency: 'usd-cents',
|
||||
input_cost_key: 'prompt_tokens',
|
||||
output_cost_key: 'completion_tokens',
|
||||
serviceSpeedVariants: { fast: 'qwen-max-prime' },
|
||||
costs: {
|
||||
tokens: 1_000_000,
|
||||
prompt_tokens: 160,
|
||||
@@ -61,7 +60,6 @@ export const ALIBABA_MODELS: IChatModel[] = [
|
||||
costs_currency: 'usd-cents',
|
||||
input_cost_key: 'prompt_tokens',
|
||||
output_cost_key: 'completion_tokens',
|
||||
serviceSpeedVariants: { fast: 'qwen-plus-prime' },
|
||||
costs: {
|
||||
tokens: 1_000_000,
|
||||
prompt_tokens: 40,
|
||||
@@ -83,7 +81,6 @@ export const ALIBABA_MODELS: IChatModel[] = [
|
||||
costs_currency: 'usd-cents',
|
||||
input_cost_key: 'prompt_tokens',
|
||||
output_cost_key: 'completion_tokens',
|
||||
serviceSpeedVariants: { fast: 'qwen3.5-plus-prime' },
|
||||
costs: {
|
||||
tokens: 1_000_000,
|
||||
prompt_tokens: 40,
|
||||
@@ -105,7 +102,6 @@ export const ALIBABA_MODELS: IChatModel[] = [
|
||||
costs_currency: 'usd-cents',
|
||||
input_cost_key: 'prompt_tokens',
|
||||
output_cost_key: 'completion_tokens',
|
||||
serviceSpeedVariants: { fast: 'qwen3.6-plus-prime' },
|
||||
costs: {
|
||||
tokens: 1_000_000,
|
||||
prompt_tokens: 50,
|
||||
@@ -127,7 +123,6 @@ export const ALIBABA_MODELS: IChatModel[] = [
|
||||
costs_currency: 'usd-cents',
|
||||
input_cost_key: 'prompt_tokens',
|
||||
output_cost_key: 'completion_tokens',
|
||||
serviceSpeedVariants: { fast: 'qwen3.6-flash-prime' },
|
||||
costs: {
|
||||
tokens: 1_000_000,
|
||||
prompt_tokens: 19,
|
||||
@@ -148,7 +143,6 @@ export const ALIBABA_MODELS: IChatModel[] = [
|
||||
costs_currency: 'usd-cents',
|
||||
input_cost_key: 'prompt_tokens',
|
||||
output_cost_key: 'completion_tokens',
|
||||
serviceSpeedVariants: { fast: 'qwen3.7-plus-prime' },
|
||||
costs: {
|
||||
tokens: 1_000_000,
|
||||
prompt_tokens: 50,
|
||||
@@ -170,7 +164,6 @@ export const ALIBABA_MODELS: IChatModel[] = [
|
||||
costs_currency: 'usd-cents',
|
||||
input_cost_key: 'prompt_tokens',
|
||||
output_cost_key: 'completion_tokens',
|
||||
serviceSpeedVariants: { fast: 'qwen3.7-max-prime' },
|
||||
costs: {
|
||||
tokens: 1_000_000,
|
||||
prompt_tokens: 250,
|
||||
@@ -195,7 +188,6 @@ export const ALIBABA_MODELS: IChatModel[] = [
|
||||
costs_currency: 'usd-cents',
|
||||
input_cost_key: 'prompt_tokens',
|
||||
output_cost_key: 'completion_tokens',
|
||||
serviceSpeedVariants: { fast: 'qwen3.8-max-prime' },
|
||||
costs: {
|
||||
tokens: 1_000_000,
|
||||
prompt_tokens: 200,
|
||||
@@ -218,7 +210,6 @@ export const ALIBABA_MODELS: IChatModel[] = [
|
||||
costs_currency: 'usd-cents',
|
||||
input_cost_key: 'prompt_tokens',
|
||||
output_cost_key: 'completion_tokens',
|
||||
serviceSpeedVariants: { fast: 'qwen3.8-max-0902-prime' },
|
||||
costs: {
|
||||
tokens: 1_000_000,
|
||||
prompt_tokens: 200,
|
||||
@@ -243,7 +234,6 @@ export const ALIBABA_MODELS: IChatModel[] = [
|
||||
costs_currency: 'usd-cents',
|
||||
input_cost_key: 'prompt_tokens',
|
||||
output_cost_key: 'completion_tokens',
|
||||
serviceSpeedVariants: { fast: 'qwen-flash-prime' },
|
||||
costs: {
|
||||
tokens: 1_000_000,
|
||||
prompt_tokens: 5,
|
||||
@@ -267,7 +257,6 @@ export const ALIBABA_MODELS: IChatModel[] = [
|
||||
costs_currency: 'usd-cents',
|
||||
input_cost_key: 'prompt_tokens',
|
||||
output_cost_key: 'completion_tokens',
|
||||
serviceSpeedVariants: { fast: 'qwen3-coder-flash-prime' },
|
||||
costs: {
|
||||
tokens: 1_000_000,
|
||||
prompt_tokens: 30,
|
||||
@@ -293,7 +282,6 @@ export const ALIBABA_MODELS: IChatModel[] = [
|
||||
costs_currency: 'usd-cents',
|
||||
input_cost_key: 'prompt_tokens',
|
||||
output_cost_key: 'completion_tokens',
|
||||
serviceSpeedVariants: { fast: 'qwen3.5-397b-a17b-prime' },
|
||||
costs: {
|
||||
tokens: 1_000_000,
|
||||
prompt_tokens: 60,
|
||||
@@ -317,7 +305,6 @@ export const ALIBABA_MODELS: IChatModel[] = [
|
||||
costs_currency: 'usd-cents',
|
||||
input_cost_key: 'prompt_tokens',
|
||||
output_cost_key: 'completion_tokens',
|
||||
serviceSpeedVariants: { fast: 'qwen3.5-122b-a10b-prime' },
|
||||
costs: {
|
||||
tokens: 1_000_000,
|
||||
prompt_tokens: 40,
|
||||
@@ -341,7 +328,6 @@ export const ALIBABA_MODELS: IChatModel[] = [
|
||||
costs_currency: 'usd-cents',
|
||||
input_cost_key: 'prompt_tokens',
|
||||
output_cost_key: 'completion_tokens',
|
||||
serviceSpeedVariants: { fast: 'qwen3.5-35b-a3b-prime' },
|
||||
costs: {
|
||||
tokens: 1_000_000,
|
||||
prompt_tokens: 25,
|
||||
@@ -365,7 +351,6 @@ export const ALIBABA_MODELS: IChatModel[] = [
|
||||
costs_currency: 'usd-cents',
|
||||
input_cost_key: 'prompt_tokens',
|
||||
output_cost_key: 'completion_tokens',
|
||||
serviceSpeedVariants: { fast: 'qwen3.5-27b-prime' },
|
||||
costs: {
|
||||
tokens: 1_000_000,
|
||||
prompt_tokens: 30,
|
||||
@@ -391,7 +376,6 @@ export const ALIBABA_MODELS: IChatModel[] = [
|
||||
costs_currency: 'usd-cents',
|
||||
input_cost_key: 'prompt_tokens',
|
||||
output_cost_key: 'completion_tokens',
|
||||
serviceSpeedVariants: { fast: 'qwen3.6-35b-a3b-prime' },
|
||||
costs: {
|
||||
tokens: 1_000_000,
|
||||
prompt_tokens: 24.8,
|
||||
@@ -415,7 +399,6 @@ export const ALIBABA_MODELS: IChatModel[] = [
|
||||
costs_currency: 'usd-cents',
|
||||
input_cost_key: 'prompt_tokens',
|
||||
output_cost_key: 'completion_tokens',
|
||||
serviceSpeedVariants: { fast: 'qwen3.6-27b-prime' },
|
||||
costs: {
|
||||
tokens: 1_000_000,
|
||||
prompt_tokens: 60,
|
||||
@@ -439,7 +422,6 @@ export const ALIBABA_MODELS: IChatModel[] = [
|
||||
costs_currency: 'usd-cents',
|
||||
input_cost_key: 'prompt_tokens',
|
||||
output_cost_key: 'completion_tokens',
|
||||
serviceSpeedVariants: { fast: 'qwen3-vl-plus-prime' },
|
||||
costs: {
|
||||
tokens: 1_000_000,
|
||||
prompt_tokens: 20,
|
||||
@@ -465,7 +447,6 @@ export const ALIBABA_MODELS: IChatModel[] = [
|
||||
costs_currency: 'usd-cents',
|
||||
input_cost_key: 'prompt_tokens',
|
||||
output_cost_key: 'completion_tokens',
|
||||
serviceSpeedVariants: { fast: 'qwen3-omni-flash-prime' },
|
||||
costs: {
|
||||
tokens: 1_000_000,
|
||||
prompt_tokens: 43,
|
||||
@@ -488,7 +469,6 @@ export const ALIBABA_MODELS: IChatModel[] = [
|
||||
costs_currency: 'usd-cents',
|
||||
input_cost_key: 'prompt_tokens',
|
||||
output_cost_key: 'completion_tokens',
|
||||
serviceSpeedVariants: { fast: 'qwen-mt-plus-prime' },
|
||||
costs: {
|
||||
tokens: 1_000_000,
|
||||
prompt_tokens: 246,
|
||||
@@ -511,7 +491,6 @@ export const ALIBABA_MODELS: IChatModel[] = [
|
||||
costs_currency: 'usd-cents',
|
||||
input_cost_key: 'prompt_tokens',
|
||||
output_cost_key: 'completion_tokens',
|
||||
serviceSpeedVariants: { fast: 'qwen-plus-2025-01-25-prime' },
|
||||
costs: {
|
||||
tokens: 1_000_000,
|
||||
prompt_tokens: 40,
|
||||
@@ -532,7 +511,6 @@ export const ALIBABA_MODELS: IChatModel[] = [
|
||||
costs_currency: 'usd-cents',
|
||||
input_cost_key: 'prompt_tokens',
|
||||
output_cost_key: 'completion_tokens',
|
||||
serviceSpeedVariants: { fast: 'qwen-plus-2025-04-28-prime' },
|
||||
costs: {
|
||||
tokens: 1_000_000,
|
||||
prompt_tokens: 40,
|
||||
@@ -553,7 +531,6 @@ export const ALIBABA_MODELS: IChatModel[] = [
|
||||
costs_currency: 'usd-cents',
|
||||
input_cost_key: 'prompt_tokens',
|
||||
output_cost_key: 'completion_tokens',
|
||||
serviceSpeedVariants: { fast: 'qwen-plus-2025-07-14-prime' },
|
||||
costs: {
|
||||
tokens: 1_000_000,
|
||||
prompt_tokens: 40,
|
||||
@@ -576,7 +553,6 @@ export const ALIBABA_MODELS: IChatModel[] = [
|
||||
costs_currency: 'usd-cents',
|
||||
input_cost_key: 'prompt_tokens',
|
||||
output_cost_key: 'completion_tokens',
|
||||
serviceSpeedVariants: { fast: 'qwen-plus-2025-12-01-prime' },
|
||||
costs: {
|
||||
tokens: 1_000_000,
|
||||
prompt_tokens: 40,
|
||||
@@ -598,7 +574,6 @@ export const ALIBABA_MODELS: IChatModel[] = [
|
||||
costs_currency: 'usd-cents',
|
||||
input_cost_key: 'prompt_tokens',
|
||||
output_cost_key: 'completion_tokens',
|
||||
serviceSpeedVariants: { fast: 'qwen3.7-max-2026-05-20-prime' },
|
||||
costs: {
|
||||
tokens: 1_000_000,
|
||||
prompt_tokens: 250,
|
||||
@@ -619,7 +594,6 @@ export const ALIBABA_MODELS: IChatModel[] = [
|
||||
costs_currency: 'usd-cents',
|
||||
input_cost_key: 'prompt_tokens',
|
||||
output_cost_key: 'completion_tokens',
|
||||
serviceSpeedVariants: { fast: 'qwen3.7-max-2026-06-08-prime' },
|
||||
costs: {
|
||||
tokens: 1_000_000,
|
||||
prompt_tokens: 250,
|
||||
@@ -640,7 +614,6 @@ export const ALIBABA_MODELS: IChatModel[] = [
|
||||
costs_currency: 'usd-cents',
|
||||
input_cost_key: 'prompt_tokens',
|
||||
output_cost_key: 'completion_tokens',
|
||||
serviceSpeedVariants: { fast: 'qwen3.7-max-2026-05-17-prime' },
|
||||
costs: {
|
||||
tokens: 1_000_000,
|
||||
prompt_tokens: 250,
|
||||
@@ -662,7 +635,6 @@ export const ALIBABA_MODELS: IChatModel[] = [
|
||||
costs_currency: 'usd-cents',
|
||||
input_cost_key: 'prompt_tokens',
|
||||
output_cost_key: 'completion_tokens',
|
||||
serviceSpeedVariants: { fast: 'qwen3.7-max-preview-prime' },
|
||||
costs: {
|
||||
tokens: 1_000_000,
|
||||
prompt_tokens: 250,
|
||||
@@ -685,7 +657,6 @@ export const ALIBABA_MODELS: IChatModel[] = [
|
||||
costs_currency: 'usd-cents',
|
||||
input_cost_key: 'prompt_tokens',
|
||||
output_cost_key: 'completion_tokens',
|
||||
serviceSpeedVariants: { fast: 'qwen3.5-plus-2026-02-15-prime' },
|
||||
costs: {
|
||||
tokens: 1_000_000,
|
||||
prompt_tokens: 40,
|
||||
@@ -707,7 +678,6 @@ export const ALIBABA_MODELS: IChatModel[] = [
|
||||
costs_currency: 'usd-cents',
|
||||
input_cost_key: 'prompt_tokens',
|
||||
output_cost_key: 'completion_tokens',
|
||||
serviceSpeedVariants: { fast: 'qwen3.5-plus-2026-04-20-prime' },
|
||||
costs: {
|
||||
tokens: 1_000_000,
|
||||
prompt_tokens: 40,
|
||||
@@ -730,7 +700,6 @@ export const ALIBABA_MODELS: IChatModel[] = [
|
||||
costs_currency: 'usd-cents',
|
||||
input_cost_key: 'prompt_tokens',
|
||||
output_cost_key: 'completion_tokens',
|
||||
serviceSpeedVariants: { fast: 'qwen3.5-flash-prime' },
|
||||
costs: {
|
||||
tokens: 1_000_000,
|
||||
prompt_tokens: 10,
|
||||
@@ -753,7 +722,6 @@ export const ALIBABA_MODELS: IChatModel[] = [
|
||||
costs_currency: 'usd-cents',
|
||||
input_cost_key: 'prompt_tokens',
|
||||
output_cost_key: 'completion_tokens',
|
||||
serviceSpeedVariants: { fast: 'qwen3.7-flash-prime' },
|
||||
costs: {
|
||||
tokens: 1_000_000,
|
||||
prompt_tokens: 3,
|
||||
@@ -775,7 +743,6 @@ export const ALIBABA_MODELS: IChatModel[] = [
|
||||
costs_currency: 'usd-cents',
|
||||
input_cost_key: 'prompt_tokens',
|
||||
output_cost_key: 'completion_tokens',
|
||||
serviceSpeedVariants: { fast: 'qwen3.8-flash-prime' },
|
||||
costs: {
|
||||
tokens: 1_000_000,
|
||||
prompt_tokens: 15,
|
||||
@@ -798,7 +765,6 @@ export const ALIBABA_MODELS: IChatModel[] = [
|
||||
costs_currency: 'usd-cents',
|
||||
input_cost_key: 'prompt_tokens',
|
||||
output_cost_key: 'completion_tokens',
|
||||
serviceSpeedVariants: { fast: 'qwen3.8-27b-prime' },
|
||||
costs: {
|
||||
tokens: 1_000_000,
|
||||
prompt_tokens: 50,
|
||||
@@ -819,7 +785,6 @@ export const ALIBABA_MODELS: IChatModel[] = [
|
||||
costs_currency: 'usd-cents',
|
||||
input_cost_key: 'prompt_tokens',
|
||||
output_cost_key: 'completion_tokens',
|
||||
serviceSpeedVariants: { fast: 'qwen3.8-2.4t-a95b-prime' },
|
||||
costs: {
|
||||
tokens: 1_000_000,
|
||||
prompt_tokens: 200,
|
||||
@@ -844,7 +809,6 @@ export const ALIBABA_MODELS: IChatModel[] = [
|
||||
costs_currency: 'usd-cents',
|
||||
input_cost_key: 'prompt_tokens',
|
||||
output_cost_key: 'completion_tokens',
|
||||
serviceSpeedVariants: { fast: 'qwen3.5-omni-flash-prime' },
|
||||
costs: {
|
||||
tokens: 1_000_000,
|
||||
prompt_tokens: 40,
|
||||
@@ -868,7 +832,6 @@ export const ALIBABA_MODELS: IChatModel[] = [
|
||||
costs_currency: 'usd-cents',
|
||||
input_cost_key: 'prompt_tokens',
|
||||
output_cost_key: 'completion_tokens',
|
||||
serviceSpeedVariants: { fast: 'qwen3.5-omni-plus-prime' },
|
||||
costs: {
|
||||
tokens: 1_000_000,
|
||||
prompt_tokens: 140,
|
||||
@@ -892,7 +855,6 @@ export const ALIBABA_MODELS: IChatModel[] = [
|
||||
costs_currency: 'usd-cents',
|
||||
input_cost_key: 'prompt_tokens',
|
||||
output_cost_key: 'completion_tokens',
|
||||
serviceSpeedVariants: { fast: 'qwen3.8-omni-flash-prime' },
|
||||
costs: {
|
||||
tokens: 1_000_000,
|
||||
prompt_tokens: 15,
|
||||
@@ -915,7 +877,6 @@ export const ALIBABA_MODELS: IChatModel[] = [
|
||||
costs_currency: 'usd-cents',
|
||||
input_cost_key: 'prompt_tokens',
|
||||
output_cost_key: 'completion_tokens',
|
||||
serviceSpeedVariants: { fast: 'qwen-mt-flash-prime' },
|
||||
costs: {
|
||||
tokens: 1_000_000,
|
||||
prompt_tokens: 16,
|
||||
@@ -936,7 +897,6 @@ export const ALIBABA_MODELS: IChatModel[] = [
|
||||
costs_currency: 'usd-cents',
|
||||
input_cost_key: 'prompt_tokens',
|
||||
output_cost_key: 'completion_tokens',
|
||||
serviceSpeedVariants: { fast: 'qwen-mt-lite-prime' },
|
||||
costs: {
|
||||
tokens: 1_000_000,
|
||||
prompt_tokens: 12,
|
||||
@@ -959,7 +919,6 @@ export const ALIBABA_MODELS: IChatModel[] = [
|
||||
costs_currency: 'usd-cents',
|
||||
input_cost_key: 'prompt_tokens',
|
||||
output_cost_key: 'completion_tokens',
|
||||
serviceSpeedVariants: { fast: 'glm-5.1-prime' },
|
||||
costs: {
|
||||
tokens: 1_000_000,
|
||||
prompt_tokens: 140,
|
||||
@@ -979,7 +938,6 @@ export const ALIBABA_MODELS: IChatModel[] = [
|
||||
costs_currency: 'usd-cents',
|
||||
input_cost_key: 'prompt_tokens',
|
||||
output_cost_key: 'completion_tokens',
|
||||
serviceSpeedVariants: { fast: 'glm-5.2-fast-preview' },
|
||||
costs: {
|
||||
tokens: 1_000_000,
|
||||
prompt_tokens: 140,
|
||||
@@ -1000,7 +958,6 @@ export const ALIBABA_MODELS: IChatModel[] = [
|
||||
costs_currency: 'usd-cents',
|
||||
input_cost_key: 'prompt_tokens',
|
||||
output_cost_key: 'completion_tokens',
|
||||
serviceSpeedVariants: { fast: 'glm-5.2-fast-preview-prime' },
|
||||
costs: {
|
||||
tokens: 1_000_000,
|
||||
prompt_tokens: 280,
|
||||
@@ -1024,7 +981,6 @@ export const ALIBABA_MODELS: IChatModel[] = [
|
||||
costs_currency: 'usd-cents',
|
||||
input_cost_key: 'prompt_tokens',
|
||||
output_cost_key: 'completion_tokens',
|
||||
serviceSpeedVariants: { fast: 'deepseek-v4-flash-0731-prime' },
|
||||
costs: {
|
||||
tokens: 1_000_000,
|
||||
prompt_tokens: 44,
|
||||
@@ -1047,7 +1003,6 @@ export const ALIBABA_MODELS: IChatModel[] = [
|
||||
costs_currency: 'usd-cents',
|
||||
input_cost_key: 'prompt_tokens',
|
||||
output_cost_key: 'completion_tokens',
|
||||
serviceSpeedVariants: { fast: 'deepseek-v4.1-flash-prime' },
|
||||
costs: {
|
||||
tokens: 1_000_000,
|
||||
prompt_tokens: 30,
|
||||
@@ -1068,7 +1023,6 @@ export const ALIBABA_MODELS: IChatModel[] = [
|
||||
costs_currency: 'usd-cents',
|
||||
input_cost_key: 'prompt_tokens',
|
||||
output_cost_key: 'completion_tokens',
|
||||
serviceSpeedVariants: { fast: 'deepseek-v4-pro-prime' },
|
||||
costs: {
|
||||
tokens: 1_000_000,
|
||||
prompt_tokens: 240,
|
||||
@@ -1091,7 +1045,6 @@ export const ALIBABA_MODELS: IChatModel[] = [
|
||||
costs_currency: 'usd-cents',
|
||||
input_cost_key: 'prompt_tokens',
|
||||
output_cost_key: 'completion_tokens',
|
||||
serviceSpeedVariants: { fast: 'deepseek-v4-pro-0813-prime' },
|
||||
costs: {
|
||||
tokens: 1_000_000,
|
||||
prompt_tokens: 132,
|
||||
@@ -1112,7 +1065,6 @@ export const ALIBABA_MODELS: IChatModel[] = [
|
||||
costs_currency: 'usd-cents',
|
||||
input_cost_key: 'prompt_tokens',
|
||||
output_cost_key: 'completion_tokens',
|
||||
serviceSpeedVariants: { fast: 'kimi-k2.7-code-prime' },
|
||||
costs: {
|
||||
tokens: 1_000_000,
|
||||
prompt_tokens: 95,
|
||||
|
||||
@@ -20,10 +20,6 @@
|
||||
import { HttpError } from '@heyputer/backend/src/core/http/HttpError.js';
|
||||
import { OpenAI } from 'openai';
|
||||
import { ChatCompletionCreateParams } from 'openai/resources/index.js';
|
||||
import {
|
||||
serviceSpeedBillingModel,
|
||||
servedServiceSpeed,
|
||||
} from '../../utils/serviceSpeed.js';
|
||||
import { Context } from '../../../../core/context.js';
|
||||
import type { FSService } from '../../../../services/fs/FSService.js';
|
||||
import type { MeteringService } from '../../../../services/metering/MeteringService.js';
|
||||
@@ -157,7 +153,6 @@ export class AzureChatProvider implements IChatProvider {
|
||||
|
||||
async complete(
|
||||
params: ICompleteArguments,
|
||||
resolved?: IChatModel,
|
||||
): ReturnType<IChatProvider['complete']> {
|
||||
const {
|
||||
max_tokens,
|
||||
@@ -185,9 +180,7 @@ export class AzureChatProvider implements IChatProvider {
|
||||
{ legacyCode: 'bad_request' },
|
||||
);
|
||||
}
|
||||
return await (resolved
|
||||
? this.#responsesProvider.complete(params, resolved)
|
||||
: this.#responsesProvider.complete(params));
|
||||
return await this.#responsesProvider.complete(params);
|
||||
}
|
||||
// Inline compaction is a Responses-API feature; chat.completions can't
|
||||
// express `context_management` or a `compaction` content block.
|
||||
@@ -201,9 +194,7 @@ export class AzureChatProvider implements IChatProvider {
|
||||
{ legacyCode: 'bad_request' },
|
||||
);
|
||||
}
|
||||
return await (resolved
|
||||
? this.#responsesProvider.complete(params, resolved)
|
||||
: this.#responsesProvider.complete(params));
|
||||
return await this.#responsesProvider.complete(params);
|
||||
}
|
||||
// Validate messages
|
||||
if (!Array.isArray(messages)) {
|
||||
@@ -216,11 +207,9 @@ export class AzureChatProvider implements IChatProvider {
|
||||
model = model ?? this.#defaultModel;
|
||||
|
||||
const modelUsed =
|
||||
resolved ??
|
||||
(this.models().find((m) =>
|
||||
this.models().find((m) =>
|
||||
[m.id, ...(m.aliases || [])].includes(model),
|
||||
) ||
|
||||
this.models().find((m) => m.id === this.getDefaultModel())!);
|
||||
) || this.models().find((m) => m.id === this.getDefaultModel())!;
|
||||
|
||||
// messages.unshift({
|
||||
// role: 'system',
|
||||
@@ -290,9 +279,6 @@ export class AzureChatProvider implements IChatProvider {
|
||||
}),
|
||||
messages: messages,
|
||||
model: modelUsed.id,
|
||||
...(params.service_tier !== undefined
|
||||
? { service_tier: params.service_tier }
|
||||
: {}),
|
||||
...(mappedTools?.length ? { tools: mappedTools } : {}),
|
||||
...(max_tokens !== undefined
|
||||
? { max_completion_tokens: max_tokens }
|
||||
@@ -329,12 +315,7 @@ export class AzureChatProvider implements IChatProvider {
|
||||
);
|
||||
|
||||
return OpenAiUtil.handle_completion_output({
|
||||
usage_calculator: ({
|
||||
service_tier,
|
||||
usage,
|
||||
setUsageCosts,
|
||||
setUsageDetails,
|
||||
}) => {
|
||||
usage_calculator: ({ usage }) => {
|
||||
const cachedTokens =
|
||||
usage.prompt_tokens_details?.cached_tokens ?? 0;
|
||||
const trackedUsage = {
|
||||
@@ -354,20 +335,9 @@ export class AzureChatProvider implements IChatProvider {
|
||||
|
||||
const costsOverrideFromModel = buildCostsOverride(
|
||||
trackedUsage,
|
||||
serviceSpeedBillingModel(
|
||||
modelUsed,
|
||||
servedServiceSpeed({ service_tier }),
|
||||
),
|
||||
modelUsed,
|
||||
);
|
||||
|
||||
setUsageCosts(costsOverrideFromModel);
|
||||
if (params.serviceSpeed !== undefined)
|
||||
setUsageDetails({
|
||||
...OpenAiUtil.usageDetailsFromTrackedUsage(
|
||||
trackedUsage,
|
||||
)!,
|
||||
serviceSpeed: servedServiceSpeed({ service_tier }),
|
||||
});
|
||||
this.#meteringService.utilRecordUsageObject(
|
||||
trackedUsage,
|
||||
actor!,
|
||||
|
||||
@@ -19,10 +19,6 @@
|
||||
|
||||
import { OpenAI } from 'openai';
|
||||
import { ResponseCreateParams } from 'openai/resources/responses/responses.mjs';
|
||||
import {
|
||||
serviceSpeedBillingModel,
|
||||
servedServiceSpeed,
|
||||
} from '../../utils/serviceSpeed.js';
|
||||
import { Context } from '../../../../core/context.js';
|
||||
import type { FSService } from '../../../../services/fs/FSService.js';
|
||||
import type { MeteringService } from '../../../../services/metering/MeteringService.js';
|
||||
@@ -156,41 +152,37 @@ export class AzureResponsesProvider implements IChatProvider {
|
||||
: {};
|
||||
}
|
||||
|
||||
async complete(
|
||||
{
|
||||
messages,
|
||||
model,
|
||||
max_tokens,
|
||||
moderation,
|
||||
tools,
|
||||
tool_choice,
|
||||
parallel_tool_calls,
|
||||
include,
|
||||
conversation,
|
||||
compaction,
|
||||
context_management,
|
||||
previous_response_id,
|
||||
instructions,
|
||||
metadata,
|
||||
prompt,
|
||||
prompt_cache_key,
|
||||
prompt_cache_retention,
|
||||
store,
|
||||
top_p,
|
||||
truncation,
|
||||
background,
|
||||
service_tier,
|
||||
serviceSpeed: requestedServiceSpeed,
|
||||
verbosity,
|
||||
stream,
|
||||
reasoning,
|
||||
reasoning_effort,
|
||||
temperature,
|
||||
text,
|
||||
outputFormat,
|
||||
}: ICompleteArguments,
|
||||
resolved?: IChatModel,
|
||||
): ReturnType<IChatProvider['complete']> {
|
||||
async complete({
|
||||
messages,
|
||||
model,
|
||||
max_tokens,
|
||||
moderation,
|
||||
tools,
|
||||
tool_choice,
|
||||
parallel_tool_calls,
|
||||
include,
|
||||
conversation,
|
||||
compaction,
|
||||
context_management,
|
||||
previous_response_id,
|
||||
instructions,
|
||||
metadata,
|
||||
prompt,
|
||||
prompt_cache_key,
|
||||
prompt_cache_retention,
|
||||
store,
|
||||
top_p,
|
||||
truncation,
|
||||
background,
|
||||
service_tier,
|
||||
verbosity,
|
||||
stream,
|
||||
reasoning,
|
||||
reasoning_effort,
|
||||
temperature,
|
||||
text,
|
||||
outputFormat,
|
||||
}: ICompleteArguments): ReturnType<IChatProvider['complete']> {
|
||||
// Validate messages
|
||||
if (!Array.isArray(messages)) {
|
||||
throw new HttpError(400, '`messages` must be an array', {
|
||||
@@ -208,13 +200,12 @@ export class AzureResponsesProvider implements IChatProvider {
|
||||
model = model ?? this.#defaultModel;
|
||||
|
||||
const modelUsed =
|
||||
resolved ??
|
||||
(this.models({ no_restrictions: true }).find((m) =>
|
||||
this.models({ no_restrictions: true }).find((m) =>
|
||||
[m.id, ...(m.aliases || [])].includes(model),
|
||||
) ||
|
||||
this.models({ no_restrictions: true }).find(
|
||||
(m) => m.id === this.getDefaultModel(),
|
||||
)!);
|
||||
this.models({ no_restrictions: true }).find(
|
||||
(m) => m.id === this.getDefaultModel(),
|
||||
)!;
|
||||
|
||||
const userIdentifier = upstreamUserIdentifier(actor);
|
||||
// Cache key defaults to the actor identifier; see upstreamUserIdentifier.
|
||||
@@ -344,11 +335,9 @@ export class AzureResponsesProvider implements IChatProvider {
|
||||
return OpenAiUtil.handle_completion_output_responses_api({
|
||||
usage_calculator: ({
|
||||
usage,
|
||||
service_tier,
|
||||
webSearchCalls,
|
||||
tool_usage,
|
||||
setUsageCosts,
|
||||
setUsageDetails,
|
||||
}) => {
|
||||
const numWebSearches: number =
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
@@ -374,10 +363,7 @@ export class AzureResponsesProvider implements IChatProvider {
|
||||
|
||||
const costsOverrideFromModel = buildCostsOverride(
|
||||
trackedUsage,
|
||||
serviceSpeedBillingModel(
|
||||
modelUsed,
|
||||
servedServiceSpeed({ service_tier }),
|
||||
),
|
||||
modelUsed,
|
||||
);
|
||||
if (numWebSearches) {
|
||||
costsOverrideFromModel.web_search_calls =
|
||||
@@ -388,14 +374,6 @@ export class AzureResponsesProvider implements IChatProvider {
|
||||
});
|
||||
}
|
||||
|
||||
setUsageCosts?.(costsOverrideFromModel);
|
||||
if (requestedServiceSpeed !== undefined)
|
||||
setUsageDetails?.({
|
||||
...OpenAiUtil.usageDetailsFromTrackedUsage(
|
||||
trackedUsage,
|
||||
)!,
|
||||
serviceSpeed: servedServiceSpeed({ service_tier }),
|
||||
});
|
||||
this.#meteringService.utilRecordUsageObject(
|
||||
trackedUsage,
|
||||
actor,
|
||||
|
||||
@@ -40,11 +40,7 @@ const STANDALONE = [
|
||||
];
|
||||
|
||||
// Fields an Azure deployment genuinely differs from its source on, by puterId.
|
||||
const OVERRIDES: Record<string, string[]> = {
|
||||
'azure:x-ai/grok-4.3': ['serviceSpeedRates'],
|
||||
'azure:x-ai/grok-4-20-non-reasoning': ['serviceSpeedRates'],
|
||||
'azure:x-ai/grok-4-20-reasoning': ['serviceSpeedRates'],
|
||||
};
|
||||
const OVERRIDES: Record<string, string[]> = {};
|
||||
|
||||
const IDENTITY = ['id', 'puterId', 'aliases'];
|
||||
|
||||
@@ -69,18 +65,6 @@ const mirrored = AZURE_MODELS.filter(
|
||||
).map((m) => [m.puterId!, m] as const);
|
||||
|
||||
describe('AZURE_MODELS mirroring', () => {
|
||||
it('inherits OpenAI fast rates without enabling direct-only speed tiers', () => {
|
||||
for (const model of AZURE_MODELS) {
|
||||
expect(model.serviceSpeedRates?.ultrafast).toBeUndefined();
|
||||
if (model.puterId?.startsWith('azure:x-ai/')) {
|
||||
expect(model.serviceSpeedRates?.fast).toBeUndefined();
|
||||
}
|
||||
}
|
||||
const azure = AZURE_MODELS.find((model) => model.id === 'gpt-5.4')!;
|
||||
expect(azure.serviceSpeedRates).toEqual({
|
||||
fast: sourceOf(azure)!.serviceSpeedRates!.fast,
|
||||
});
|
||||
});
|
||||
it('has a direct-provider source for every entry not listed as standalone', () => {
|
||||
const orphans = mirrored
|
||||
.filter(([, m]) => !sourceOf(m))
|
||||
|
||||
@@ -22,8 +22,10 @@ import { OPEN_AI_MODELS } from '../openai/models.js';
|
||||
import { XAI_MODELS } from '../xai/models.js';
|
||||
|
||||
/**
|
||||
* Azure shares its source model's list prices, context tiers, and limits.
|
||||
* Identity and available service speeds belong to the deployment.
|
||||
* An Azure deployment of a model we also serve direct. Every field but the
|
||||
* identity comes from the source entry, so prices, long-context tiers and
|
||||
* limits can't drift from it. `name` is the vendor-qualified name both catalogs
|
||||
* share (`openai/gpt-5.4`); extra fields override the source.
|
||||
*/
|
||||
const mirror = (
|
||||
source: readonly IChatModel[],
|
||||
@@ -39,11 +41,6 @@ const mirror = (
|
||||
puterId: `azure:${name}`,
|
||||
id: azure.id,
|
||||
...shared,
|
||||
serviceSpeedRates:
|
||||
source === OPEN_AI_MODELS &&
|
||||
shared.serviceSpeedRates?.fast !== undefined
|
||||
? { fast: shared.serviceSpeedRates.fast }
|
||||
: undefined,
|
||||
aliases: [name],
|
||||
...azure,
|
||||
};
|
||||
@@ -130,13 +127,6 @@ export const AZURE_MODELS: IChatModel[] = [
|
||||
costs_currency: 'usd-cents',
|
||||
input_cost_key: 'prompt_tokens',
|
||||
output_cost_key: 'completion_tokens',
|
||||
serviceSpeedRates: {
|
||||
fast: {
|
||||
prompt_tokens: 250,
|
||||
cached_tokens: 25,
|
||||
completion_tokens: 2000,
|
||||
},
|
||||
},
|
||||
costs: {
|
||||
tokens: 1_000_000,
|
||||
prompt_tokens: 125,
|
||||
@@ -181,13 +171,6 @@ export const AZURE_MODELS: IChatModel[] = [
|
||||
costs_currency: 'usd-cents',
|
||||
input_cost_key: 'prompt_tokens',
|
||||
output_cost_key: 'completion_tokens',
|
||||
serviceSpeedRates: {
|
||||
fast: {
|
||||
prompt_tokens: 45,
|
||||
cached_tokens: 4.5,
|
||||
completion_tokens: 360,
|
||||
},
|
||||
},
|
||||
costs: {
|
||||
tokens: 1_000_000,
|
||||
prompt_tokens: 25,
|
||||
|
||||
@@ -147,22 +147,6 @@ describe.skipIf(skipUnlessEnv(ENV_VAR))('ClaudeProvider (integration)', () => {
|
||||
},
|
||||
);
|
||||
|
||||
it('returns a completion from claude-fable-5-2', { timeout: INTEGRATION_TEST_TIMEOUT_MS }, async () => {
|
||||
const provider = buildProvider();
|
||||
const result = await withTestActor(() =>
|
||||
provider.complete({
|
||||
model: 'claude-fable-5-2',
|
||||
messages: [{ role: 'user', content: 'Reply with OK.' }],
|
||||
reasoning_effort: 'low',
|
||||
max_tokens: 128,
|
||||
}),
|
||||
);
|
||||
const content = (result as {
|
||||
message: { content: Array<{ type: string; text?: string }> };
|
||||
}).message.content;
|
||||
expect(content.find((block) => block.type === 'text')?.text?.length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
// (a) Claude Code-shaped system blocks, attribution header first — the
|
||||
// pipeline must never merge or reorder system blocks: the header is
|
||||
// only recognized by Anthropic when it is the sole content of an
|
||||
|
||||
@@ -1173,7 +1173,6 @@ describe('ClaudeProvider.complete request shape', () => {
|
||||
});
|
||||
|
||||
it.each([
|
||||
'claude-fable-5-2',
|
||||
'claude-fable-5-1',
|
||||
'claude-haiku-5-5',
|
||||
'claude-opus-5-5',
|
||||
@@ -1199,7 +1198,6 @@ describe('ClaudeProvider.complete request shape', () => {
|
||||
);
|
||||
|
||||
it.each([
|
||||
'claude-fable-5-2',
|
||||
'claude-fable-5-1',
|
||||
'claude-haiku-5-5',
|
||||
'claude-opus-5-5',
|
||||
@@ -1305,73 +1303,6 @@ describe('ClaudeProvider model resolution', () => {
|
||||
);
|
||||
});
|
||||
|
||||
it.each([
|
||||
'claude-fable-5-2',
|
||||
'claude-fable-5-2-latest',
|
||||
'claude-fable-5.2',
|
||||
'anthropic/claude-fable-5-2',
|
||||
])(
|
||||
'routes %s to Fable 5.2 with published rates',
|
||||
async (model) => {
|
||||
const { provider } = makeProvider();
|
||||
messagesCreateMock.mockResolvedValueOnce({
|
||||
content: [{ type: 'text', text: 'ok' }],
|
||||
usage: {
|
||||
input_tokens: 100,
|
||||
output_tokens: 50,
|
||||
cache_read_input_tokens: 1000,
|
||||
cache_creation_input_tokens: 200,
|
||||
cache_creation: {
|
||||
ephemeral_5m_input_tokens: 150,
|
||||
ephemeral_1h_input_tokens: 50,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
await withTestActor(() =>
|
||||
provider.complete({
|
||||
model,
|
||||
messages: [{ role: 'user', content: 'hi' }],
|
||||
}),
|
||||
);
|
||||
|
||||
expect(messagesCreateMock.mock.calls[0]![0].model).toBe(
|
||||
'claude-fable-5-2',
|
||||
);
|
||||
const fable52 = CLAUDE_MODELS.find(
|
||||
(m) => m.id === 'claude-fable-5-2',
|
||||
)!;
|
||||
expect(fable52.costs).toMatchObject({
|
||||
input_tokens: 800,
|
||||
output_tokens: 4000,
|
||||
cache_read_input_tokens: 20,
|
||||
ephemeral_5m_input_tokens: 1000,
|
||||
ephemeral_1h_input_tokens: 1600,
|
||||
});
|
||||
expect(fable52.serviceSpeedRates?.fast).toMatchObject({
|
||||
input_tokens: 1600,
|
||||
output_tokens: 8000,
|
||||
cache_read_input_tokens: 40,
|
||||
ephemeral_5m_input_tokens: 2000,
|
||||
ephemeral_1h_input_tokens: 3200,
|
||||
});
|
||||
expect(fable52.context).toBe(1_000_000);
|
||||
expect(fable52.max_tokens).toBe(128_000);
|
||||
const [, , prefix, overrides] = recordSpy.mock.calls[0]!;
|
||||
expect(prefix).toBe('claude:claude-fable-5-2');
|
||||
expect(overrides).toMatchObject({
|
||||
input_tokens: 100 * Number(fable52.costs.input_tokens),
|
||||
output_tokens: 50 * Number(fable52.costs.output_tokens),
|
||||
cache_read_input_tokens:
|
||||
1000 * Number(fable52.costs.cache_read_input_tokens),
|
||||
ephemeral_5m_input_tokens:
|
||||
150 * Number(fable52.costs.ephemeral_5m_input_tokens),
|
||||
ephemeral_1h_input_tokens:
|
||||
50 * Number(fable52.costs.ephemeral_1h_input_tokens),
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it('routes the bare claude-fable alias to fable 5.1 rather than fable 5', async () => {
|
||||
const { provider } = makeProvider();
|
||||
messagesCreateMock.mockResolvedValueOnce(baseResponse);
|
||||
@@ -2380,20 +2311,16 @@ describe('ClaudeProvider metering', () => {
|
||||
expect('thinking_tokens' in overrides).toBe(false);
|
||||
});
|
||||
|
||||
it.each(['claude-opus-5-5', 'claude-fable-5-2'])('bills at fast rates for %s when the upstream reports fast usage', async (model) => {
|
||||
it('bills at the fast_* rates when the upstream reports usage.speed:"fast"', async () => {
|
||||
const { provider } = makeProvider();
|
||||
messagesCreateMock.mockResolvedValueOnce({
|
||||
content: [{ type: 'text', text: 'hi' }],
|
||||
usage: {
|
||||
input_tokens: 10, output_tokens: 5, speed: 'fast',
|
||||
cache_creation: { ephemeral_5m_input_tokens: 7, ephemeral_1h_input_tokens: 3 },
|
||||
cache_read_input_tokens: 20,
|
||||
},
|
||||
usage: { input_tokens: 10, output_tokens: 5, speed: 'fast' },
|
||||
});
|
||||
|
||||
const result = (await withTestActor(() =>
|
||||
provider.complete({
|
||||
model,
|
||||
model: 'claude-opus-5-5',
|
||||
messages: [{ role: 'user', content: 'hi' }],
|
||||
speed: 'fast',
|
||||
}),
|
||||
@@ -2404,15 +2331,11 @@ describe('ClaudeProvider metering', () => {
|
||||
expect('input_tokens' in result.usage).toBe(false);
|
||||
expect(result.usageDetails.speed).toBe('fast');
|
||||
|
||||
const selectedModel = CLAUDE_MODELS.find((m) => m.id === model)!;
|
||||
const opus = CLAUDE_MODELS.find((m) => m.id === 'claude-opus-5-5')!;
|
||||
const [, , prefix, overrides] = recordSpy.mock.calls[0]!;
|
||||
expect(prefix).toBe(`claude:${model}`);
|
||||
const fastRates = selectedModel.serviceSpeedRates!.fast as Record<string, number>;
|
||||
expect(overrides.fast_input_tokens).toBe(10 * fastRates.input_tokens);
|
||||
expect(overrides.fast_output_tokens).toBe(5 * fastRates.output_tokens);
|
||||
expect(overrides.fast_ephemeral_5m_input_tokens).toBe(7 * fastRates.ephemeral_5m_input_tokens);
|
||||
expect(overrides.fast_ephemeral_1h_input_tokens).toBe(3 * fastRates.ephemeral_1h_input_tokens);
|
||||
expect(overrides.fast_cache_read_input_tokens).toBe(20 * fastRates.cache_read_input_tokens);
|
||||
expect(prefix).toBe('claude:claude-opus-5-5');
|
||||
expect(overrides.fast_input_tokens).toBe(10 * Number(opus.costs.fast_input_tokens));
|
||||
expect(overrides.fast_output_tokens).toBe(5 * Number(opus.costs.fast_output_tokens));
|
||||
});
|
||||
|
||||
it('bills at standard rates when fast mode was requested but not granted by the upstream', async () => {
|
||||
@@ -2434,15 +2357,13 @@ describe('ClaudeProvider metering', () => {
|
||||
expect('fast_input_tokens' in result.usage).toBe(false);
|
||||
});
|
||||
|
||||
it.each([
|
||||
[429, "This request would exceed your organization's rate limit of 0 fast mode input tokens per minute"],
|
||||
[529, 'Overloaded'],
|
||||
[529, 'Fast mode capacity unavailable'],
|
||||
])('retries at standard speed on Claude after fast capacity failure %s', async (status, message) => {
|
||||
it('retries at standard speed on Claude when fast mode is rate limited', async () => {
|
||||
const { provider } = makeProvider();
|
||||
const fastLimited = Object.assign(
|
||||
new Error(message),
|
||||
{ status },
|
||||
new Error(
|
||||
"This request would exceed your organization's rate limit of 0 fast mode input tokens per minute",
|
||||
),
|
||||
{ status: 429 },
|
||||
);
|
||||
messagesCreateMock.mockRejectedValueOnce(fastLimited).mockResolvedValueOnce({
|
||||
content: [{ type: 'text', text: 'hi' }],
|
||||
@@ -2666,13 +2587,13 @@ describe('ClaudeProvider.requestPricing', () => {
|
||||
const haiku = CLAUDE_MODELS.find((m) => m.id === 'claude-haiku-4-5-20251001')!;
|
||||
const opus55 = CLAUDE_MODELS.find((m) => m.id === 'claude-opus-5-5')!;
|
||||
|
||||
it('leaves token reservation keys to the selected catalog rate card', () => {
|
||||
it('returns fast cost keys only when the model has fast rates and fast was requested', () => {
|
||||
const { provider } = makeProvider();
|
||||
expect(
|
||||
provider.requestPricing({ speed: 'fast', tools: [] } as never, opus55, {
|
||||
promptTokenEstimate: 10,
|
||||
}),
|
||||
).toEqual({});
|
||||
).toMatchObject({ inputKey: 'fast_input_tokens', outputKey: 'fast_output_tokens' });
|
||||
expect(
|
||||
provider.requestPricing({ speed: 'fast', tools: [] } as never, haiku, {
|
||||
promptTokenEstimate: 10,
|
||||
|
||||
@@ -43,7 +43,6 @@ import {
|
||||
} from '../../utils/mediaParts.js';
|
||||
import { isToolChoice, toolChoiceFromWire } from '../../utils/openaiParams.js';
|
||||
import { buildCostsOverride } from '../../utils/pricing.js';
|
||||
import { serviceSpeedCosts } from '../../utils/serviceSpeed.js';
|
||||
import type {
|
||||
AIChatStream,
|
||||
AIChatTextStream,
|
||||
@@ -108,21 +107,20 @@ const toAnthropicMediaPart = (part: any): any => {
|
||||
return part;
|
||||
};
|
||||
|
||||
/** Fast quota or overload failures can be retried at standard speed. */
|
||||
const isFastModeUnavailable = (e: unknown): boolean => {
|
||||
/** A 429 from fast mode's separate quota, not the model's normal limits. */
|
||||
const isFastModeRateLimit = (e: unknown): boolean => {
|
||||
const err = e as { status?: unknown; message?: unknown };
|
||||
return (
|
||||
typeof err?.message === 'string' &&
|
||||
((err?.status === 429 && /fast mode/i.test(err.message)) ||
|
||||
(err?.status === 529 && /overload|fast mode/i.test(err.message)))
|
||||
err?.status === 429 &&
|
||||
typeof err.message === 'string' &&
|
||||
/fast mode/i.test(err.message)
|
||||
);
|
||||
};
|
||||
|
||||
// Models whose current turn rejects a non-default temperature/top_p/top_k
|
||||
// outright. Fable 5/5.1/5.2, Sonnet 5/5.5, Haiku 5.5, and Opus 4.7+.
|
||||
// outright. Fable 5/5.1, Sonnet 5/5.5, Haiku 5.5, and Opus 4.7+.
|
||||
const OMITS_SAMPLING_PARAMS = new Set([
|
||||
'claude-haiku-5-5',
|
||||
'claude-fable-5-2',
|
||||
'claude-fable-5-1',
|
||||
'claude-fable-5',
|
||||
'claude-sonnet-5-5',
|
||||
@@ -135,7 +133,6 @@ const OMITS_SAMPLING_PARAMS = new Set([
|
||||
|
||||
const SUPPORTS_EFFORT = new Set([
|
||||
'claude-haiku-5-5',
|
||||
'claude-fable-5-2',
|
||||
'claude-fable-5-1',
|
||||
'claude-fable-5',
|
||||
'claude-sonnet-5-5',
|
||||
@@ -301,12 +298,20 @@ export class ClaudeProvider implements IChatProvider {
|
||||
return `claude:${modelId}`;
|
||||
}
|
||||
|
||||
/** Reserves tools that can run several times before the model answers. */
|
||||
/**
|
||||
* Sizes the credit hold for Claude-only extras the generic per-token math
|
||||
* can't see: fast mode's own rate card, and a web-search/advisor tool that
|
||||
* could run several times before the model answers.
|
||||
*/
|
||||
requestPricing(
|
||||
args: ICompleteArguments,
|
||||
model: IChatModel,
|
||||
est: { promptTokenEstimate: number },
|
||||
): { extraCost?: number } {
|
||||
): { inputKey?: string; outputKey?: string; extraCost?: number } {
|
||||
const fast =
|
||||
args.speed === 'fast' &&
|
||||
model.costs?.fast_output_tokens !== undefined;
|
||||
|
||||
let extraCost = 0;
|
||||
for (const raw of args.tools ?? []) {
|
||||
const tool = raw as Record<string, unknown>;
|
||||
@@ -345,6 +350,12 @@ export class ClaudeProvider implements IChatProvider {
|
||||
}
|
||||
|
||||
return {
|
||||
...(fast
|
||||
? {
|
||||
inputKey: 'fast_input_tokens',
|
||||
outputKey: 'fast_output_tokens',
|
||||
}
|
||||
: {}),
|
||||
...(extraCost > 0 ? { extraCost } : {}),
|
||||
};
|
||||
}
|
||||
@@ -353,9 +364,11 @@ export class ClaudeProvider implements IChatProvider {
|
||||
try {
|
||||
return await this.#completeOnce(args);
|
||||
} catch (e) {
|
||||
// Retry fast-capacity failures on Claude at standard speed before
|
||||
// considering a different provider.
|
||||
if (args.speed === 'fast' && isFastModeUnavailable(e)) {
|
||||
// Fast mode has its own quota. Anthropic's advice on that 429 is to
|
||||
// drop `speed` and run at standard speed; doing it here keeps the
|
||||
// request on Claude instead of marking the route unhealthy and
|
||||
// replaying it on a reseller.
|
||||
if (args.speed === 'fast' && isFastModeRateLimit(e)) {
|
||||
return await this.#completeOnce({ ...args, speed: undefined });
|
||||
}
|
||||
throw e;
|
||||
@@ -624,7 +637,7 @@ export class ClaudeProvider implements IChatProvider {
|
||||
: undefined;
|
||||
const fast =
|
||||
args.speed === 'fast' &&
|
||||
modelUsed.serviceSpeedRates?.fast !== undefined;
|
||||
modelUsed.costs?.fast_output_tokens !== undefined;
|
||||
const safeguardsPolicy = applySafeguardsPolicy(
|
||||
args.safeguards,
|
||||
args.anthropicBetas,
|
||||
@@ -1058,7 +1071,6 @@ export class ClaudeProvider implements IChatProvider {
|
||||
// keeps reasoning visible in the stream.
|
||||
if (
|
||||
modelId === 'claude-haiku-5-5' ||
|
||||
modelId === 'claude-fable-5-2' ||
|
||||
modelId === 'claude-fable-5-1' ||
|
||||
modelId === 'claude-fable-5' ||
|
||||
modelId === 'claude-sonnet-5-5' ||
|
||||
@@ -1493,8 +1505,7 @@ export class ClaudeProvider implements IChatProvider {
|
||||
|
||||
const fast =
|
||||
raw.speed === 'fast' &&
|
||||
modelUsed.serviceSpeedRates?.fast !== undefined;
|
||||
// Keep published usage keys while resolving rates from the common catalog shape.
|
||||
modelUsed.costs?.fast_output_tokens !== undefined;
|
||||
const executorUsage: Record<string, number> = fast
|
||||
? Object.fromEntries(
|
||||
Object.entries(exec).map(([k, v]) => [`fast_${k}`, v]),
|
||||
@@ -1506,24 +1517,7 @@ export class ClaudeProvider implements IChatProvider {
|
||||
const fetches = raw.server_tool_use?.web_fetch_requests ?? 0;
|
||||
if (fetches) executorUsage.web_fetch_requests = fetches;
|
||||
|
||||
const fastRates = fast
|
||||
? serviceSpeedCosts(modelUsed, 'fast')
|
||||
: undefined;
|
||||
const billingModel = fastRates
|
||||
? {
|
||||
...modelUsed,
|
||||
costs: {
|
||||
...modelUsed.costs,
|
||||
...Object.fromEntries(
|
||||
Object.keys(exec).map((key) => [
|
||||
`fast_${key}`,
|
||||
fastRates[key],
|
||||
]),
|
||||
),
|
||||
},
|
||||
}
|
||||
: modelUsed;
|
||||
const executorCosts = buildCostsOverride(executorUsage, billingModel);
|
||||
const executorCosts = buildCostsOverride(executorUsage, modelUsed);
|
||||
|
||||
let advisorUsage: Record<string, number> | undefined;
|
||||
let advisorCosts: Record<string, number> | undefined;
|
||||
|
||||
@@ -55,46 +55,6 @@ export const CLAUDE_MODELS: IChatModel[] = [
|
||||
context: 1_000_000,
|
||||
max_tokens: 128_000,
|
||||
},
|
||||
{
|
||||
puterId: 'anthropic:anthropic/claude-fable-5-2',
|
||||
id: 'claude-fable-5-2',
|
||||
modalities: { input: ['text', 'image', 'pdf'], output: ['text'] },
|
||||
open_weights: false,
|
||||
tool_call: true,
|
||||
release_date: '2026-11-09',
|
||||
aliases: [
|
||||
'claude-fable-5-2-latest',
|
||||
'claude-fable-5.2',
|
||||
'anthropic/claude-fable-5-2',
|
||||
],
|
||||
name: 'Claude Fable 5.2',
|
||||
midConversationSystem: true,
|
||||
costs_currency: 'usd-cents',
|
||||
input_cost_key: 'input_tokens',
|
||||
output_cost_key: 'output_tokens',
|
||||
// Source: https://www.anthropic.com/claude-fable-and-mythos-5-2
|
||||
serviceSpeedRates: {
|
||||
fast: {
|
||||
input_tokens: 1600,
|
||||
output_tokens: 8000,
|
||||
ephemeral_5m_input_tokens: 1600 * 1.25,
|
||||
ephemeral_1h_input_tokens: 1600 * 2,
|
||||
cache_read_input_tokens: 1600 * 0.025,
|
||||
},
|
||||
},
|
||||
costs: {
|
||||
tokens: 1_000_000,
|
||||
input_tokens: 800,
|
||||
ephemeral_5m_input_tokens: 800 * 1.25,
|
||||
ephemeral_1h_input_tokens: 800 * 2,
|
||||
// 0.025x input, not the usual 0.1x.
|
||||
cache_read_input_tokens: 800 * 0.025,
|
||||
output_tokens: 4000,
|
||||
web_search_requests: 1_000_000, // $10/1k requests
|
||||
},
|
||||
context: 1000000,
|
||||
max_tokens: 128000,
|
||||
},
|
||||
{
|
||||
puterId: 'anthropic:anthropic/claude-fable-5-1',
|
||||
id: 'claude-fable-5-1',
|
||||
@@ -230,15 +190,6 @@ export const CLAUDE_MODELS: IChatModel[] = [
|
||||
costs_currency: 'usd-cents',
|
||||
input_cost_key: 'input_tokens',
|
||||
output_cost_key: 'output_tokens',
|
||||
serviceSpeedRates: {
|
||||
fast: {
|
||||
input_tokens: 800,
|
||||
output_tokens: 4000,
|
||||
ephemeral_5m_input_tokens: 1000,
|
||||
ephemeral_1h_input_tokens: 1600,
|
||||
cache_read_input_tokens: 40,
|
||||
},
|
||||
},
|
||||
costs: {
|
||||
tokens: 1_000_000,
|
||||
input_tokens: 400,
|
||||
@@ -248,6 +199,12 @@ export const CLAUDE_MODELS: IChatModel[] = [
|
||||
cache_read_input_tokens: 400 * 0.05,
|
||||
output_tokens: 2000,
|
||||
web_search_requests: 1_000_000,
|
||||
// Fast mode (`speed:'fast'`), live-verified.
|
||||
fast_input_tokens: 800,
|
||||
fast_output_tokens: 4000,
|
||||
fast_ephemeral_5m_input_tokens: 1000,
|
||||
fast_ephemeral_1h_input_tokens: 1600,
|
||||
fast_cache_read_input_tokens: 40, // 0.05x fast_input_tokens
|
||||
},
|
||||
context: 1000000,
|
||||
max_tokens: 128000,
|
||||
@@ -266,15 +223,6 @@ export const CLAUDE_MODELS: IChatModel[] = [
|
||||
costs_currency: 'usd-cents',
|
||||
input_cost_key: 'input_tokens',
|
||||
output_cost_key: 'output_tokens',
|
||||
serviceSpeedRates: {
|
||||
fast: {
|
||||
input_tokens: 1000,
|
||||
output_tokens: 5000,
|
||||
ephemeral_5m_input_tokens: 1250,
|
||||
ephemeral_1h_input_tokens: 2000,
|
||||
cache_read_input_tokens: 100,
|
||||
},
|
||||
},
|
||||
costs: {
|
||||
tokens: 1_000_000,
|
||||
input_tokens: 500,
|
||||
@@ -283,6 +231,11 @@ export const CLAUDE_MODELS: IChatModel[] = [
|
||||
cache_read_input_tokens: 500 * 0.1,
|
||||
output_tokens: 2500,
|
||||
web_search_requests: 1_000_000,
|
||||
fast_input_tokens: 1000,
|
||||
fast_output_tokens: 5000,
|
||||
fast_ephemeral_5m_input_tokens: 1250,
|
||||
fast_ephemeral_1h_input_tokens: 2000,
|
||||
fast_cache_read_input_tokens: 100,
|
||||
},
|
||||
context: 1000000,
|
||||
max_tokens: 128000,
|
||||
@@ -305,15 +258,6 @@ export const CLAUDE_MODELS: IChatModel[] = [
|
||||
costs_currency: 'usd-cents',
|
||||
input_cost_key: 'input_tokens',
|
||||
output_cost_key: 'output_tokens',
|
||||
serviceSpeedRates: {
|
||||
fast: {
|
||||
input_tokens: 1000,
|
||||
output_tokens: 5000,
|
||||
ephemeral_5m_input_tokens: 1250,
|
||||
ephemeral_1h_input_tokens: 2000,
|
||||
cache_read_input_tokens: 100,
|
||||
},
|
||||
},
|
||||
costs: {
|
||||
tokens: 1_000_000,
|
||||
input_tokens: 500,
|
||||
@@ -322,6 +266,11 @@ export const CLAUDE_MODELS: IChatModel[] = [
|
||||
cache_read_input_tokens: 500 * 0.1,
|
||||
output_tokens: 2500,
|
||||
web_search_requests: 1_000_000,
|
||||
fast_input_tokens: 1000,
|
||||
fast_output_tokens: 5000,
|
||||
fast_ephemeral_5m_input_tokens: 1250,
|
||||
fast_ephemeral_1h_input_tokens: 2000,
|
||||
fast_cache_read_input_tokens: 100,
|
||||
},
|
||||
context: 1000000,
|
||||
max_tokens: 128000,
|
||||
|
||||
@@ -84,14 +84,8 @@ export class GeminiChatProvider extends OpenAICompatProvider {
|
||||
chat: {
|
||||
completions: {
|
||||
create: (params, options) => {
|
||||
const { model, service_tier } = params as {
|
||||
model: string;
|
||||
service_tier?: string;
|
||||
};
|
||||
if (
|
||||
!GEMINI_NATIVE_MODELS.has(model) &&
|
||||
(service_tier === undefined || !native)
|
||||
) {
|
||||
const { model } = params as { model: string };
|
||||
if (!GEMINI_NATIVE_MODELS.has(model)) {
|
||||
return compat.chat.completions.create(
|
||||
params,
|
||||
options,
|
||||
@@ -109,12 +103,7 @@ export class GeminiChatProvider extends OpenAICompatProvider {
|
||||
},
|
||||
},
|
||||
};
|
||||
const models: IChatModel[] = native
|
||||
? GEMINI_MODELS
|
||||
: COMPAT_ONLY_MODELS.map((model) => ({
|
||||
...model,
|
||||
serviceSpeeds: ['standard'],
|
||||
}));
|
||||
const models = native ? GEMINI_MODELS : COMPAT_ONLY_MODELS;
|
||||
super(meteringService, {
|
||||
client,
|
||||
defaultModel: 'gemini-2.5-flash',
|
||||
@@ -194,10 +183,7 @@ export class GeminiChatProvider extends OpenAICompatProvider {
|
||||
}
|
||||
|
||||
protected override meteredUsage(source: UsageSource, model: IChatModel) {
|
||||
if (
|
||||
GEMINI_NATIVE_MODELS.has(model.id) ||
|
||||
'promptTokenCount' in (source.usage ?? {})
|
||||
) {
|
||||
if (GEMINI_NATIVE_MODELS.has(model.id)) {
|
||||
return nativeMeteredUsage(
|
||||
source.usage as unknown as
|
||||
GenerateContentResponseUsageMetadata | undefined,
|
||||
|
||||
@@ -80,7 +80,6 @@ interface ChatParams {
|
||||
temperature?: number;
|
||||
reasoning_effort?: 'minimal' | 'low' | 'medium' | 'high';
|
||||
stream?: boolean;
|
||||
service_tier?: string;
|
||||
}
|
||||
|
||||
/** Ids made up for calls Gemini returned without one; never sent back. */
|
||||
@@ -241,12 +240,6 @@ const toGenerateContentRequest = (
|
||||
? toolConfigOf(params.tool_choice)
|
||||
: undefined;
|
||||
const config: GenerateContentConfig = {
|
||||
...(params.service_tier !== undefined
|
||||
? {
|
||||
serviceTier:
|
||||
params.service_tier as GenerateContentConfig['serviceTier'],
|
||||
}
|
||||
: {}),
|
||||
...(signal ? { abortSignal: signal } : {}),
|
||||
...(systemInstruction ? { systemInstruction } : {}),
|
||||
...(params.max_completion_tokens !== undefined
|
||||
|
||||
@@ -142,7 +142,6 @@ export const GEMINI_MODELS: IChatModel[] = [
|
||||
costs_currency: 'usd-cents',
|
||||
input_cost_key: 'prompt_tokens',
|
||||
output_cost_key: 'completion_tokens',
|
||||
serviceSpeedRates: { fast: 1.8 },
|
||||
costs: ARGON_LAUNCH_COSTS,
|
||||
pricingOverrides: listPricingFrom(
|
||||
'2026-12-01T00:00:00Z',
|
||||
@@ -175,7 +174,6 @@ export const GEMINI_MODELS: IChatModel[] = [
|
||||
input_cost_key: 'prompt_tokens',
|
||||
output_cost_key: 'completion_tokens',
|
||||
// Google serves this endpoint with gemini-3.6-flash and bills its rates.
|
||||
serviceSpeedRates: { fast: 1.8 },
|
||||
costs: FLASH_LAUNCH_COSTS,
|
||||
pricingOverrides: FLASH_LIST_PRICING,
|
||||
},
|
||||
@@ -203,7 +201,6 @@ export const GEMINI_MODELS: IChatModel[] = [
|
||||
costs_currency: 'usd-cents',
|
||||
input_cost_key: 'prompt_tokens',
|
||||
output_cost_key: 'completion_tokens',
|
||||
serviceSpeedRates: { fast: 1.8 },
|
||||
costs: {
|
||||
tokens: 1_000_000,
|
||||
prompt_tokens: 30,
|
||||
@@ -231,7 +228,6 @@ export const GEMINI_MODELS: IChatModel[] = [
|
||||
costs_currency: 'usd-cents',
|
||||
input_cost_key: 'prompt_tokens',
|
||||
output_cost_key: 'completion_tokens',
|
||||
serviceSpeedRates: { fast: 1.8 },
|
||||
costs: FLASH_LAUNCH_COSTS,
|
||||
pricingOverrides: FLASH_LIST_PRICING,
|
||||
},
|
||||
@@ -254,7 +250,6 @@ export const GEMINI_MODELS: IChatModel[] = [
|
||||
input_cost_key: 'prompt_tokens',
|
||||
output_cost_key: 'completion_tokens',
|
||||
// Google serves this endpoint with gemini-3.8-flash and bills its rates.
|
||||
serviceSpeedRates: { fast: 1.8 },
|
||||
costs: FLASH_LAUNCH_COSTS,
|
||||
pricingOverrides: FLASH_LIST_PRICING,
|
||||
},
|
||||
@@ -275,7 +270,6 @@ export const GEMINI_MODELS: IChatModel[] = [
|
||||
costs_currency: 'usd-cents',
|
||||
input_cost_key: 'prompt_tokens',
|
||||
output_cost_key: 'completion_tokens',
|
||||
serviceSpeedRates: { fast: 1.8 },
|
||||
costs: FLASH_LAUNCH_COSTS,
|
||||
pricingOverrides: FLASH_LIST_PRICING,
|
||||
},
|
||||
@@ -297,7 +291,6 @@ export const GEMINI_MODELS: IChatModel[] = [
|
||||
costs_currency: 'usd-cents',
|
||||
input_cost_key: 'prompt_tokens',
|
||||
output_cost_key: 'completion_tokens',
|
||||
serviceSpeedRates: { fast: 1.8 },
|
||||
costs: {
|
||||
tokens: 1_000_000,
|
||||
prompt_tokens: 25,
|
||||
@@ -325,7 +318,6 @@ export const GEMINI_MODELS: IChatModel[] = [
|
||||
costs_currency: 'usd-cents',
|
||||
input_cost_key: 'prompt_tokens',
|
||||
output_cost_key: 'completion_tokens',
|
||||
serviceSpeedRates: { fast: 1.8 },
|
||||
costs: {
|
||||
tokens: 1_000_000,
|
||||
prompt_tokens: 50,
|
||||
@@ -352,7 +344,6 @@ export const GEMINI_MODELS: IChatModel[] = [
|
||||
costs_currency: 'usd-cents',
|
||||
input_cost_key: 'prompt_tokens',
|
||||
output_cost_key: 'completion_tokens',
|
||||
serviceSpeedRates: { fast: 1.8 },
|
||||
costs: {
|
||||
tokens: 1_000_000,
|
||||
prompt_tokens: 30,
|
||||
@@ -383,7 +374,6 @@ export const GEMINI_MODELS: IChatModel[] = [
|
||||
costs_currency: 'usd-cents',
|
||||
input_cost_key: 'prompt_tokens',
|
||||
output_cost_key: 'completion_tokens',
|
||||
serviceSpeedRates: { fast: 1.8 },
|
||||
costs: {
|
||||
tokens: 1_000_000,
|
||||
prompt_tokens: 10,
|
||||
@@ -412,7 +402,6 @@ export const GEMINI_MODELS: IChatModel[] = [
|
||||
costs_currency: 'usd-cents',
|
||||
input_cost_key: 'prompt_tokens',
|
||||
output_cost_key: 'completion_tokens',
|
||||
serviceSpeedRates: { fast: 1.8 },
|
||||
costs: {
|
||||
tokens: 1_000_000,
|
||||
prompt_tokens: 125,
|
||||
@@ -459,7 +448,6 @@ export const GEMINI_MODELS: IChatModel[] = [
|
||||
costs_currency: 'usd-cents',
|
||||
input_cost_key: 'prompt_tokens',
|
||||
output_cost_key: 'completion_tokens',
|
||||
serviceSpeedRates: { fast: 1.8 },
|
||||
costs: {
|
||||
tokens: 1_000_000,
|
||||
prompt_tokens: 200,
|
||||
|
||||
@@ -266,15 +266,6 @@ export class InfronProvider extends OpenAICompatProvider {
|
||||
return coerced_models;
|
||||
}
|
||||
|
||||
async serviceSpeedModels(model: IChatModel) {
|
||||
const variant = (await this.models()).find(
|
||||
(entry) => entry.id === `${model.id}:priority`,
|
||||
);
|
||||
return variant
|
||||
? { fast: { ...variant, provider: model.provider } }
|
||||
: {};
|
||||
}
|
||||
|
||||
protected override vendorParams(
|
||||
params: Record<string, unknown>,
|
||||
_args: unknown,
|
||||
|
||||
@@ -43,8 +43,6 @@ export const MINIMAX_MODELS: MiniMaxChatModel[] = [
|
||||
costs_currency: 'usd-cents',
|
||||
input_cost_key: 'prompt_tokens',
|
||||
output_cost_key: 'completion_tokens',
|
||||
serviceSpeedRates: { fast: 1.5 },
|
||||
serviceSpeedVariants: { fast: 'minimax-m3-highspeed' },
|
||||
costs: {
|
||||
tokens: 1_000_000,
|
||||
prompt_tokens: 30, // $0.30 per 1M (input <= 512k tokens)
|
||||
@@ -72,7 +70,6 @@ export const MINIMAX_MODELS: MiniMaxChatModel[] = [
|
||||
costs_currency: 'usd-cents',
|
||||
input_cost_key: 'prompt_tokens',
|
||||
output_cost_key: 'completion_tokens',
|
||||
serviceSpeedVariants: { fast: 'minimax-m2.7-highspeed' },
|
||||
costs: {
|
||||
tokens: 1_000_000,
|
||||
prompt_tokens: 30, // $0.30 per 1M
|
||||
@@ -125,7 +122,6 @@ export const MINIMAX_MODELS: MiniMaxChatModel[] = [
|
||||
costs_currency: 'usd-cents',
|
||||
input_cost_key: 'prompt_tokens',
|
||||
output_cost_key: 'completion_tokens',
|
||||
serviceSpeedVariants: { fast: 'minimax-m2.5-highspeed' },
|
||||
costs: {
|
||||
tokens: 1_000_000,
|
||||
prompt_tokens: 30, // $0.30 per 1M
|
||||
@@ -178,7 +174,6 @@ export const MINIMAX_MODELS: MiniMaxChatModel[] = [
|
||||
costs_currency: 'usd-cents',
|
||||
input_cost_key: 'prompt_tokens',
|
||||
output_cost_key: 'completion_tokens',
|
||||
serviceSpeedVariants: { fast: 'minimax-m2.1-highspeed' },
|
||||
costs: {
|
||||
tokens: 1_000_000,
|
||||
prompt_tokens: 30, // $0.30 per 1M
|
||||
@@ -227,7 +222,6 @@ export const MINIMAX_MODELS: MiniMaxChatModel[] = [
|
||||
costs_currency: 'usd-cents',
|
||||
input_cost_key: 'prompt_tokens',
|
||||
output_cost_key: 'completion_tokens',
|
||||
serviceSpeedVariants: { fast: 'minimax-m2-highspeed' },
|
||||
costs: {
|
||||
tokens: 1_000_000,
|
||||
prompt_tokens: 30, // $0.30 per 1M
|
||||
|
||||
@@ -20,12 +20,13 @@
|
||||
/**
|
||||
* Offline unit tests for MistralAIProvider.
|
||||
*
|
||||
* Boots a real PuterServer (in-memory sqlite + dynamo + s3 + mock redis) and
|
||||
* constructs MistralAIProvider directly against the live wired
|
||||
* `MeteringService` so the recording side is exercised end-to- end. The Mistral
|
||||
* SDK is mocked at the module boundary (the real network egress point) so the
|
||||
* provider never reaches the network. The companion integration test
|
||||
* (MistralAiProvider.integration.test.ts) exercises the real Mistral endpoint.
|
||||
* Boots a real PuterServer (in-memory sqlite + dynamo + s3 + mock
|
||||
* redis) and constructs MistralAIProvider directly against the live
|
||||
* wired `MeteringService` so the recording side is exercised end-to-
|
||||
* end. The Mistral SDK is mocked at the module boundary (the real
|
||||
* network egress point) so the provider never reaches the network.
|
||||
* The companion integration test (MistralAiProvider.integration.test.ts)
|
||||
* exercises the real Mistral endpoint.
|
||||
*/
|
||||
|
||||
import { Context } from '../../../../core/context.js';
|
||||
@@ -146,9 +147,7 @@ describe('MistralAIProvider construction', () => {
|
||||
it('constructs the Mistral SDK with the configured API key', () => {
|
||||
makeProvider();
|
||||
expect(mistralCtor).toHaveBeenCalledTimes(1);
|
||||
expect(mistralCtor).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ apiKey: 'test-key' }),
|
||||
);
|
||||
expect(mistralCtor).toHaveBeenCalledWith({ apiKey: 'test-key' });
|
||||
});
|
||||
});
|
||||
|
||||
@@ -607,11 +606,7 @@ describe('MistralAIProvider.complete non-stream output', () => {
|
||||
if (stream) {
|
||||
streamMock.mockResolvedValueOnce(
|
||||
asAsyncIterable([
|
||||
{
|
||||
data: {
|
||||
choices: [{ delta: { content: 'hello' } }],
|
||||
},
|
||||
},
|
||||
{ data: { choices: [{ delta: { content: 'hello' } }] } },
|
||||
{ data: { choices: [], usage } },
|
||||
]),
|
||||
);
|
||||
@@ -648,11 +643,7 @@ describe('MistralAIProvider.complete non-stream output', () => {
|
||||
expect(result).toMatchObject({ message: { content: 'hello' } });
|
||||
}
|
||||
expect(recordSpy).toHaveBeenCalledWith(
|
||||
{
|
||||
prompt_tokens: 5,
|
||||
cached_tokens: 1008,
|
||||
completion_tokens: 30,
|
||||
},
|
||||
{ prompt_tokens: 5, cached_tokens: 1008, completion_tokens: 30 },
|
||||
SYSTEM_ACTOR,
|
||||
`mistral:${model}`,
|
||||
{
|
||||
@@ -697,7 +688,8 @@ describe('MistralAIProvider.complete non-stream output', () => {
|
||||
});
|
||||
|
||||
expect(recordSpy).toHaveBeenCalledTimes(1);
|
||||
const [usage, actor, prefix, overrides] = recordSpy.mock.calls[0]!;
|
||||
const [usage, actor, prefix, overrides] =
|
||||
recordSpy.mock.calls[0]!;
|
||||
expect(usage).toEqual({
|
||||
prompt_tokens: 100,
|
||||
completion_tokens: 50,
|
||||
@@ -726,11 +718,15 @@ describe('MistralAIProvider.complete non-stream output', () => {
|
||||
content: [
|
||||
{
|
||||
type: 'thinking',
|
||||
thinking: [{ type: 'text', text: 'step one.' }],
|
||||
thinking: [
|
||||
{ type: 'text', text: 'step one.' },
|
||||
],
|
||||
},
|
||||
{
|
||||
type: 'thinking',
|
||||
thinking: [{ type: 'text', text: 'step two.' }],
|
||||
thinking: [
|
||||
{ type: 'text', text: 'step two.' },
|
||||
],
|
||||
},
|
||||
{ type: 'text', text: 'the answer' },
|
||||
],
|
||||
@@ -920,7 +916,8 @@ describe('MistralAIProvider.complete streaming', () => {
|
||||
|
||||
// mistral-small-2603: prompt=15, completion=60.
|
||||
expect(recordSpy).toHaveBeenCalledTimes(1);
|
||||
const [, , prefix, overrides] = recordSpy.mock.calls[0]!;
|
||||
const [, , prefix, overrides] =
|
||||
recordSpy.mock.calls[0]!;
|
||||
expect(prefix).toBe('mistral:mistral-small-2603');
|
||||
expect(overrides).toMatchObject({
|
||||
prompt_tokens: 4 * 15,
|
||||
@@ -1118,7 +1115,7 @@ describe('MistralAIProvider image_url coercion', () => {
|
||||
usage: { promptTokens: 1, completionTokens: 1 },
|
||||
};
|
||||
|
||||
it("rewrites canonical image_url parts to the SDK's camelCase imageUrl", async () => {
|
||||
it('rewrites canonical image_url parts to the SDK\'s camelCase imageUrl', async () => {
|
||||
const { provider } = makeProvider();
|
||||
completeMock.mockResolvedValueOnce(baseCompletion);
|
||||
|
||||
@@ -1178,8 +1175,7 @@ describe('MistralAIProvider image_url coercion', () => {
|
||||
},
|
||||
{
|
||||
type: 'image_url',
|
||||
image_url:
|
||||
'https://example.com/already-flat.png',
|
||||
image_url: 'https://example.com/already-flat.png',
|
||||
},
|
||||
],
|
||||
},
|
||||
@@ -1255,9 +1251,7 @@ describe('MistralAIProvider image_url coercion', () => {
|
||||
{ type: 'text', text: 'what is in this image?' },
|
||||
{
|
||||
type: 'image_url',
|
||||
image_url: {
|
||||
url: 'https://example.com/photo.jpg',
|
||||
},
|
||||
image_url: { url: 'https://example.com/photo.jpg' },
|
||||
},
|
||||
],
|
||||
},
|
||||
@@ -1266,11 +1260,7 @@ describe('MistralAIProvider image_url coercion', () => {
|
||||
);
|
||||
|
||||
const [args] = completeMock.mock.calls[0]!;
|
||||
const parts = args.messages[0].content as {
|
||||
type: string;
|
||||
text?: string;
|
||||
imageUrl?: unknown;
|
||||
}[];
|
||||
const parts = args.messages[0].content as { type: string; text?: string; imageUrl?: unknown }[];
|
||||
const textPart = parts.find((p) => p.type === 'text');
|
||||
const imgPart = parts.find((p) => p.type === 'image_url');
|
||||
expect(textPart?.text).toBe('what is in this image?');
|
||||
@@ -1310,41 +1300,3 @@ describe('MistralAIProvider.checkModeration', () => {
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Mistral service speed wire mapping', () => {
|
||||
it('adds the tier after SDK serialization and removes its internal header', async () => {
|
||||
makeProvider();
|
||||
const options = mistralCtor.mock.calls[0][0] as {
|
||||
httpClient: import('@mistralai/mistralai/lib/http.js').HTTPClient;
|
||||
};
|
||||
let sent: Request | undefined;
|
||||
vi.stubGlobal('fetch', async (input: Request) => {
|
||||
sent = input;
|
||||
return new Response('{}', {
|
||||
headers: { 'content-type': 'application/json' },
|
||||
});
|
||||
});
|
||||
try {
|
||||
await options.httpClient.request(
|
||||
new Request('https://api.mistral.ai/v1/chat/completions', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'content-type': 'application/json',
|
||||
'x-puter-service-tier': 'auto',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
model: 'mistral-medium-latest',
|
||||
messages: [],
|
||||
}),
|
||||
}),
|
||||
);
|
||||
expect(sent?.headers.has('x-puter-service-tier')).toBe(false);
|
||||
expect(await sent?.json()).toMatchObject({
|
||||
model: 'mistral-medium-latest',
|
||||
service_tier: 'auto',
|
||||
});
|
||||
} finally {
|
||||
vi.unstubAllGlobals();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -17,8 +17,6 @@
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
import { HTTPClient } from '@mistralai/mistralai/lib/http.js';
|
||||
import { servedServiceSpeed } from '../../utils/serviceSpeed.js';
|
||||
import { Mistral } from '@mistralai/mistralai';
|
||||
import { ChatCompletionResponse } from '@mistralai/mistralai/models/components/chatcompletionresponse.js';
|
||||
import { MistralError } from '@mistralai/mistralai/models/errors/mistralerror.js';
|
||||
@@ -28,7 +26,6 @@ import { Context } from '../../../../core/context.js';
|
||||
import { HttpError } from '../../../../core/http/HttpError.js';
|
||||
import type { MeteringService } from '../../../../services/metering/MeteringService.js';
|
||||
import type {
|
||||
IChatModel,
|
||||
IChatCompleteResult,
|
||||
IChatProvider,
|
||||
ICompleteArguments,
|
||||
@@ -109,7 +106,6 @@ const coerceMistralUsage = (usage: UsageInfo) => {
|
||||
prompt_tokens: (usage.promptTokens ?? 0) - cachedTokens,
|
||||
completion_tokens: usage.completionTokens ?? 0,
|
||||
prompt_tokens_details: { cached_tokens: cachedTokens },
|
||||
service_tier: usage.additionalProperties?.service_tier,
|
||||
};
|
||||
};
|
||||
|
||||
@@ -119,24 +115,7 @@ export class MistralAIProvider implements IChatProvider {
|
||||
#meteringService: MeteringService;
|
||||
|
||||
constructor(config: { apiKey: string }, meteringService: MeteringService) {
|
||||
const httpClient = new HTTPClient();
|
||||
// The SDK strips service_tier during body serialization.
|
||||
httpClient.addHook('beforeRequest', async (request) => {
|
||||
const tier = request.headers.get('x-puter-service-tier');
|
||||
if (!tier) return;
|
||||
const headers = new Headers(request.headers);
|
||||
headers.delete('x-puter-service-tier');
|
||||
const body = await request.json();
|
||||
return new Request(request, {
|
||||
headers,
|
||||
body: JSON.stringify({
|
||||
...body,
|
||||
service_tier: tier === 'auto' ? 'auto' : 'standard_only',
|
||||
}),
|
||||
});
|
||||
});
|
||||
this.#client = new Mistral({
|
||||
httpClient,
|
||||
apiKey: config.apiKey,
|
||||
});
|
||||
this.#meteringService = meteringService;
|
||||
@@ -202,22 +181,17 @@ export class MistralAIProvider implements IChatProvider {
|
||||
return `mistral:${modelId}`;
|
||||
}
|
||||
|
||||
async complete(
|
||||
{
|
||||
messages,
|
||||
stream,
|
||||
model,
|
||||
tools,
|
||||
max_tokens,
|
||||
temperature,
|
||||
normalize,
|
||||
response,
|
||||
custom,
|
||||
service_tier,
|
||||
serviceSpeed: requestedServiceSpeed,
|
||||
}: ICompleteArguments,
|
||||
resolved?: IChatModel,
|
||||
): Promise<IChatCompleteResult> {
|
||||
async complete({
|
||||
messages,
|
||||
stream,
|
||||
model,
|
||||
tools,
|
||||
max_tokens,
|
||||
temperature,
|
||||
normalize,
|
||||
response,
|
||||
custom,
|
||||
}: ICompleteArguments): Promise<IChatCompleteResult> {
|
||||
// Mistral's reasoning prompt mode: with `prompt_mode: 'reasoning'`,
|
||||
// reasoning-capable models return their thinking as structured ThinkChunk
|
||||
// content (which the splitter below separates into `reasoning`)
|
||||
@@ -243,13 +217,10 @@ export class MistralAIProvider implements IChatProvider {
|
||||
}
|
||||
|
||||
const selectedModel =
|
||||
resolved ??
|
||||
((await this.models()).find((m) =>
|
||||
(await this.models()).find((m) =>
|
||||
[m.id, ...(m.aliases || [])].includes(model),
|
||||
) ||
|
||||
(await this.models()).find(
|
||||
(m) => m.id === this.getDefaultModel(),
|
||||
)!);
|
||||
(await this.models()).find((m) => m.id === this.getDefaultModel())!;
|
||||
const actor = Context.get('actor');
|
||||
let completion: Awaited<
|
||||
ReturnType<Mistral['chat']['complete' | 'stream']>
|
||||
@@ -271,9 +242,6 @@ export class MistralAIProvider implements IChatProvider {
|
||||
// The SDK retries nothing by default and has no timeout once a
|
||||
// signal is passed; a stream is bounded by its caller instead.
|
||||
{
|
||||
...(service_tier !== undefined
|
||||
? { headers: { 'x-puter-service-tier': service_tier } }
|
||||
: {}),
|
||||
signal: stream
|
||||
? Context.get('upstreamSignal')
|
||||
: withSdkTimeout(Context.get('upstreamSignal')),
|
||||
@@ -430,8 +398,7 @@ export class MistralAIProvider implements IChatProvider {
|
||||
},
|
||||
completion: completion as ChatCompletionResponse,
|
||||
stream,
|
||||
usage_calculator: ({ usage, setUsageCosts, setUsageDetails }) => {
|
||||
const serviceSpeed = servedServiceSpeed({ usage });
|
||||
usage_calculator: ({ usage, setUsageCosts }) => {
|
||||
// `coerceMistralUsage` has already taken cached reads out of
|
||||
// `prompt_tokens`.
|
||||
const metered = meterChatUsage(
|
||||
@@ -440,16 +407,8 @@ export class MistralAIProvider implements IChatProvider {
|
||||
this.meteringModelKey(selectedModel.id),
|
||||
selectedModel,
|
||||
OpenAIUtil.extractMeteredUsage(usage),
|
||||
{ serviceSpeed },
|
||||
);
|
||||
setUsageCosts(metered.costs);
|
||||
if (requestedServiceSpeed !== undefined)
|
||||
setUsageDetails({
|
||||
...OpenAIUtil.usageDetailsFromTrackedUsage(
|
||||
metered.usage,
|
||||
)!,
|
||||
serviceSpeed,
|
||||
});
|
||||
return metered.usage;
|
||||
},
|
||||
});
|
||||
|
||||
@@ -42,7 +42,6 @@ export const MISTRAL_MODELS: IChatModel[] = [
|
||||
costs_currency: 'usd-cents',
|
||||
input_cost_key: 'prompt_tokens',
|
||||
output_cost_key: 'completion_tokens',
|
||||
serviceSpeedRates: { fast: 1.75 },
|
||||
costs: {
|
||||
tokens: 1_000_000,
|
||||
prompt_tokens: 136,
|
||||
@@ -76,7 +75,6 @@ export const MISTRAL_MODELS: IChatModel[] = [
|
||||
costs_currency: 'usd-cents',
|
||||
input_cost_key: 'prompt_tokens',
|
||||
output_cost_key: 'completion_tokens',
|
||||
serviceSpeedRates: { fast: 1.75 },
|
||||
costs: {
|
||||
tokens: 1_000_000,
|
||||
prompt_tokens: 150,
|
||||
@@ -107,7 +105,6 @@ export const MISTRAL_MODELS: IChatModel[] = [
|
||||
costs_currency: 'usd-cents',
|
||||
input_cost_key: 'prompt_tokens',
|
||||
output_cost_key: 'completion_tokens',
|
||||
serviceSpeedRates: { fast: 1.75 },
|
||||
costs: {
|
||||
tokens: 1_000_000,
|
||||
prompt_tokens: 50,
|
||||
@@ -138,7 +135,6 @@ export const MISTRAL_MODELS: IChatModel[] = [
|
||||
costs_currency: 'usd-cents',
|
||||
input_cost_key: 'prompt_tokens',
|
||||
output_cost_key: 'completion_tokens',
|
||||
serviceSpeedRates: { fast: 1.75 },
|
||||
costs: {
|
||||
tokens: 1_000_000,
|
||||
prompt_tokens: 15,
|
||||
@@ -163,7 +159,6 @@ export const MISTRAL_MODELS: IChatModel[] = [
|
||||
costs_currency: 'usd-cents',
|
||||
input_cost_key: 'prompt_tokens',
|
||||
output_cost_key: 'completion_tokens',
|
||||
serviceSpeedRates: { fast: 1.75 },
|
||||
costs: {
|
||||
tokens: 1_000_000,
|
||||
prompt_tokens: 140,
|
||||
@@ -193,7 +188,6 @@ export const MISTRAL_MODELS: IChatModel[] = [
|
||||
costs_currency: 'usd-cents',
|
||||
input_cost_key: 'prompt_tokens',
|
||||
output_cost_key: 'completion_tokens',
|
||||
serviceSpeedRates: { fast: 1.75 },
|
||||
costs: {
|
||||
tokens: 1_000_000,
|
||||
prompt_tokens: 30,
|
||||
@@ -219,7 +213,6 @@ export const MISTRAL_MODELS: IChatModel[] = [
|
||||
costs_currency: 'usd-cents',
|
||||
input_cost_key: 'prompt_tokens',
|
||||
output_cost_key: 'completion_tokens',
|
||||
serviceSpeedRates: { fast: 1.75 },
|
||||
costs: {
|
||||
tokens: 1_000_000,
|
||||
prompt_tokens: 20,
|
||||
@@ -245,7 +238,6 @@ export const MISTRAL_MODELS: IChatModel[] = [
|
||||
costs_currency: 'usd-cents',
|
||||
input_cost_key: 'prompt_tokens',
|
||||
output_cost_key: 'completion_tokens',
|
||||
serviceSpeedRates: { fast: 1.75 },
|
||||
costs: {
|
||||
tokens: 1_000_000,
|
||||
prompt_tokens: 15,
|
||||
@@ -270,7 +262,6 @@ export const MISTRAL_MODELS: IChatModel[] = [
|
||||
costs_currency: 'usd-cents',
|
||||
input_cost_key: 'prompt_tokens',
|
||||
output_cost_key: 'completion_tokens',
|
||||
serviceSpeedRates: { fast: 1.75 },
|
||||
costs: {
|
||||
tokens: 1_000_000,
|
||||
prompt_tokens: 10,
|
||||
|
||||
@@ -30,7 +30,6 @@ export const MOONSHOT_MODELS: IChatModel[] = [
|
||||
costs_currency: 'usd-cents',
|
||||
input_cost_key: 'prompt_tokens',
|
||||
output_cost_key: 'completion_tokens',
|
||||
serviceSpeedVariants: { fast: 'kimi-k3.1-pro-highspeed' },
|
||||
costs: {
|
||||
tokens: 1_000_000,
|
||||
prompt_tokens: 200, // $2.00 per 1M
|
||||
@@ -78,7 +77,6 @@ export const MOONSHOT_MODELS: IChatModel[] = [
|
||||
costs_currency: 'usd-cents',
|
||||
input_cost_key: 'prompt_tokens',
|
||||
output_cost_key: 'completion_tokens',
|
||||
serviceSpeedVariants: { fast: 'kimi-k3-highspeed' },
|
||||
costs: {
|
||||
tokens: 1_000_000,
|
||||
prompt_tokens: 300, // $3.00 per 1M
|
||||
@@ -106,7 +104,6 @@ export const MOONSHOT_MODELS: IChatModel[] = [
|
||||
costs_currency: 'usd-cents',
|
||||
input_cost_key: 'prompt_tokens',
|
||||
output_cost_key: 'completion_tokens',
|
||||
serviceSpeedVariants: { fast: 'kimi-k2.6-highspeed' },
|
||||
costs: {
|
||||
tokens: 1_000_000,
|
||||
prompt_tokens: 95, // $0.95 per 1M
|
||||
@@ -129,7 +126,6 @@ export const MOONSHOT_MODELS: IChatModel[] = [
|
||||
costs_currency: 'usd-cents',
|
||||
input_cost_key: 'prompt_tokens',
|
||||
output_cost_key: 'completion_tokens',
|
||||
serviceSpeedVariants: { fast: 'kimi-k2.7-code-highspeed' },
|
||||
costs: {
|
||||
tokens: 1_000_000,
|
||||
prompt_tokens: 95,
|
||||
|
||||
@@ -20,7 +20,6 @@
|
||||
import { HttpError } from '@heyputer/backend/src/core/http/HttpError.js';
|
||||
import { OpenAI } from 'openai';
|
||||
import { ChatCompletionCreateParams } from 'openai/resources/index.js';
|
||||
import { servedServiceSpeed } from '../../utils/serviceSpeed.js';
|
||||
import { Context } from '../../../../core/context.js';
|
||||
import type { MeteringService } from '../../../../services/metering/MeteringService.js';
|
||||
import type {
|
||||
@@ -118,7 +117,6 @@ export class OpenAiChatProvider implements IChatProvider {
|
||||
|
||||
async complete(
|
||||
params: ICompleteArguments,
|
||||
resolved?: IChatModel,
|
||||
): ReturnType<IChatProvider['complete']> {
|
||||
const {
|
||||
max_tokens,
|
||||
@@ -136,11 +134,6 @@ export class OpenAiChatProvider implements IChatProvider {
|
||||
} = params;
|
||||
let { messages, model } = params;
|
||||
const cacheOptions = promptCacheOptionsToWire(prompt_cache_options);
|
||||
if (params.service_tier === 'ultrafast' && this.#responsesProvider) {
|
||||
return resolved
|
||||
? this.#responsesProvider.complete(params, resolved)
|
||||
: this.#responsesProvider.complete(params);
|
||||
}
|
||||
if (
|
||||
tools?.filter((e) => isWebSearchTool(e as Record<string, unknown>))
|
||||
.length
|
||||
@@ -154,9 +147,7 @@ export class OpenAiChatProvider implements IChatProvider {
|
||||
{ legacyCode: 'bad_request' },
|
||||
);
|
||||
}
|
||||
return await (resolved
|
||||
? this.#responsesProvider.complete(params, resolved)
|
||||
: this.#responsesProvider.complete(params));
|
||||
return await this.#responsesProvider.complete(params);
|
||||
}
|
||||
// Inline compaction is a Responses-API feature; chat.completions can't
|
||||
// express `context_management` or a `compaction` content block.
|
||||
@@ -170,9 +161,7 @@ export class OpenAiChatProvider implements IChatProvider {
|
||||
{ legacyCode: 'bad_request' },
|
||||
);
|
||||
}
|
||||
return await (resolved
|
||||
? this.#responsesProvider.complete(params, resolved)
|
||||
: this.#responsesProvider.complete(params));
|
||||
return await this.#responsesProvider.complete(params);
|
||||
}
|
||||
// Only the Responses API writes 12h cache entries or takes a lifetime
|
||||
// on a `prompt_cache_breakpoint`; Chat Completions rejects both.
|
||||
@@ -187,9 +176,7 @@ export class OpenAiChatProvider implements IChatProvider {
|
||||
{ legacyCode: 'bad_request' },
|
||||
);
|
||||
}
|
||||
return await (resolved
|
||||
? this.#responsesProvider.complete(params, resolved)
|
||||
: this.#responsesProvider.complete(params));
|
||||
return await this.#responsesProvider.complete(params);
|
||||
}
|
||||
// Validate messages
|
||||
if (!Array.isArray(messages)) {
|
||||
@@ -202,11 +189,9 @@ export class OpenAiChatProvider implements IChatProvider {
|
||||
model = model ?? this.#defaultModel;
|
||||
|
||||
const modelUsed =
|
||||
resolved ??
|
||||
(this.models().find((m) =>
|
||||
this.models().find((m) =>
|
||||
[m.id, ...(m.aliases || [])].includes(model),
|
||||
) ||
|
||||
this.models().find((m) => m.id === this.getDefaultModel())!);
|
||||
) || this.models().find((m) => m.id === this.getDefaultModel())!;
|
||||
|
||||
// messages.unshift({
|
||||
// role: 'system',
|
||||
@@ -263,9 +248,6 @@ export class OpenAiChatProvider implements IChatProvider {
|
||||
: {}),
|
||||
messages: messages,
|
||||
model: modelUsed.id,
|
||||
...(params.service_tier !== undefined
|
||||
? { service_tier: params.service_tier }
|
||||
: {}),
|
||||
...(mappedTools?.length ? { tools: mappedTools } : {}),
|
||||
...(max_tokens !== undefined
|
||||
? { max_completion_tokens: max_tokens }
|
||||
@@ -302,13 +284,7 @@ export class OpenAiChatProvider implements IChatProvider {
|
||||
);
|
||||
|
||||
return OpenAiUtil.handle_completion_output({
|
||||
usage_calculator: ({
|
||||
usage,
|
||||
service_tier,
|
||||
setUsageCosts,
|
||||
setUsageDetails,
|
||||
}) => {
|
||||
const serviceSpeed = servedServiceSpeed({ service_tier });
|
||||
usage_calculator: ({ usage, setUsageCosts, setUsageDetails }) => {
|
||||
// GPT-5.6 and later report cache writes inside
|
||||
// `prompt_tokens`, like cached reads; Chat Completions only
|
||||
// writes the default 30m entries, billed at 1.25x input.
|
||||
@@ -320,17 +296,13 @@ export class OpenAiChatProvider implements IChatProvider {
|
||||
this.meteringModelKey(modelUsed.id),
|
||||
modelUsed,
|
||||
trackedUsage,
|
||||
{ serviceSpeed },
|
||||
);
|
||||
setUsageCosts(metered.costs);
|
||||
setUsageDetails({
|
||||
...OpenAiUtil.usageDetailsFromTrackedUsage(metered.usage, {
|
||||
setUsageDetails(
|
||||
OpenAiUtil.usageDetailsFromTrackedUsage(metered.usage, {
|
||||
writeTtl: '30m',
|
||||
})!,
|
||||
...(params.serviceSpeed !== undefined
|
||||
? { serviceSpeed }
|
||||
: {}),
|
||||
});
|
||||
);
|
||||
return metered.usage;
|
||||
},
|
||||
stream,
|
||||
|
||||
@@ -19,7 +19,6 @@
|
||||
|
||||
import { OpenAI } from 'openai';
|
||||
import { ResponseCreateParams } from 'openai/resources/responses/responses.mjs';
|
||||
import { servedServiceSpeed } from '../../utils/serviceSpeed.js';
|
||||
import { Context } from '../../../../core/context.js';
|
||||
import type { MeteringService } from '../../../../services/metering/MeteringService.js';
|
||||
import type {
|
||||
@@ -135,42 +134,38 @@ export class OpenAiResponsesChatProvider implements IChatProvider {
|
||||
return rate ? { extraCost: rate } : {};
|
||||
}
|
||||
|
||||
async complete(
|
||||
{
|
||||
messages,
|
||||
model,
|
||||
max_tokens,
|
||||
moderation,
|
||||
tools,
|
||||
tool_choice,
|
||||
parallel_tool_calls,
|
||||
include,
|
||||
conversation,
|
||||
compaction,
|
||||
context_management,
|
||||
previous_response_id,
|
||||
instructions,
|
||||
metadata,
|
||||
prompt,
|
||||
prompt_cache_key,
|
||||
prompt_cache_retention,
|
||||
prompt_cache_options,
|
||||
store,
|
||||
top_p,
|
||||
truncation,
|
||||
background,
|
||||
service_tier,
|
||||
serviceSpeed: requestedServiceSpeed,
|
||||
verbosity,
|
||||
stream,
|
||||
reasoning,
|
||||
reasoning_effort,
|
||||
temperature,
|
||||
text,
|
||||
outputFormat,
|
||||
}: ICompleteArguments,
|
||||
resolved?: IChatModel,
|
||||
): ReturnType<IChatProvider['complete']> {
|
||||
async complete({
|
||||
messages,
|
||||
model,
|
||||
max_tokens,
|
||||
moderation,
|
||||
tools,
|
||||
tool_choice,
|
||||
parallel_tool_calls,
|
||||
include,
|
||||
conversation,
|
||||
compaction,
|
||||
context_management,
|
||||
previous_response_id,
|
||||
instructions,
|
||||
metadata,
|
||||
prompt,
|
||||
prompt_cache_key,
|
||||
prompt_cache_retention,
|
||||
prompt_cache_options,
|
||||
store,
|
||||
top_p,
|
||||
truncation,
|
||||
background,
|
||||
service_tier,
|
||||
verbosity,
|
||||
stream,
|
||||
reasoning,
|
||||
reasoning_effort,
|
||||
temperature,
|
||||
text,
|
||||
outputFormat,
|
||||
}: ICompleteArguments): ReturnType<IChatProvider['complete']> {
|
||||
// Validate messages
|
||||
if (!Array.isArray(messages)) {
|
||||
throw new HttpError(400, '`messages` must be an array', {
|
||||
@@ -188,13 +183,12 @@ export class OpenAiResponsesChatProvider implements IChatProvider {
|
||||
model = model ?? this.#defaultModel;
|
||||
|
||||
const modelUsed =
|
||||
resolved ??
|
||||
(this.models({ no_restrictions: true }).find((m) =>
|
||||
this.models({ no_restrictions: true }).find((m) =>
|
||||
[m.id, ...(m.aliases || [])].includes(model),
|
||||
) ||
|
||||
this.models({ no_restrictions: true }).find(
|
||||
(m) => m.id === this.getDefaultModel(),
|
||||
)!);
|
||||
this.models({ no_restrictions: true }).find(
|
||||
(m) => m.id === this.getDefaultModel(),
|
||||
)!;
|
||||
|
||||
// messages.unshift({
|
||||
// role: 'system',
|
||||
@@ -328,7 +322,6 @@ export class OpenAiResponsesChatProvider implements IChatProvider {
|
||||
return OpenAiUtil.handle_completion_output_responses_api({
|
||||
usage_calculator: ({
|
||||
usage,
|
||||
service_tier,
|
||||
webSearchCalls,
|
||||
setUsageCosts,
|
||||
setUsageDetails,
|
||||
@@ -354,31 +347,23 @@ export class OpenAiResponsesChatProvider implements IChatProvider {
|
||||
// model is a reasoning model, not a static per-model
|
||||
// cost-table entry — the model's rates would otherwise
|
||||
// price it (wrongly) at the input/output token rate.
|
||||
{
|
||||
serviceSpeed: servedServiceSpeed({ service_tier }),
|
||||
...(webSearchCalls
|
||||
? {
|
||||
costOverrides: {
|
||||
web_search_calls:
|
||||
webSearchCalls *
|
||||
(webSearchCallRate(
|
||||
tools,
|
||||
modelUsed.id,
|
||||
) ?? 0),
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
webSearchCalls
|
||||
? {
|
||||
costOverrides: {
|
||||
web_search_calls:
|
||||
webSearchCalls *
|
||||
(webSearchCallRate(tools, modelUsed.id) ??
|
||||
0),
|
||||
},
|
||||
}
|
||||
: {},
|
||||
);
|
||||
setUsageCosts?.(metered.costs);
|
||||
setUsageDetails?.({
|
||||
...(requestedServiceSpeed !== undefined
|
||||
? { serviceSpeed: servedServiceSpeed({ service_tier }) }
|
||||
: {}),
|
||||
...OpenAiUtil.usageDetailsFromTrackedUsage(metered.usage, {
|
||||
setUsageDetails?.(
|
||||
OpenAiUtil.usageDetailsFromTrackedUsage(metered.usage, {
|
||||
writeTtl: '30m',
|
||||
})!,
|
||||
});
|
||||
);
|
||||
return metered.usage;
|
||||
},
|
||||
stream,
|
||||
|
||||
@@ -46,7 +46,6 @@ export const OPEN_AI_MODELS: IChatModel[] = [
|
||||
costs_currency: 'usd-cents',
|
||||
input_cost_key: 'prompt_tokens',
|
||||
output_cost_key: 'completion_tokens',
|
||||
serviceSpeedRates: { fast: 2 },
|
||||
costs: {
|
||||
tokens: 1_000_000,
|
||||
prompt_tokens: 100,
|
||||
@@ -73,7 +72,6 @@ export const OPEN_AI_MODELS: IChatModel[] = [
|
||||
costs_currency: 'usd-cents',
|
||||
input_cost_key: 'prompt_tokens',
|
||||
output_cost_key: 'completion_tokens',
|
||||
serviceSpeedRates: { fast: 2, ultrafast: 6 },
|
||||
costs: {
|
||||
tokens: 1_000_000,
|
||||
prompt_tokens: 200,
|
||||
@@ -100,7 +98,6 @@ export const OPEN_AI_MODELS: IChatModel[] = [
|
||||
costs_currency: 'usd-cents',
|
||||
input_cost_key: 'prompt_tokens',
|
||||
output_cost_key: 'completion_tokens',
|
||||
serviceSpeedRates: { fast: 2 },
|
||||
costs: {
|
||||
tokens: 1_000_000,
|
||||
prompt_tokens: 200,
|
||||
@@ -127,7 +124,6 @@ export const OPEN_AI_MODELS: IChatModel[] = [
|
||||
costs_currency: 'usd-cents',
|
||||
input_cost_key: 'prompt_tokens',
|
||||
output_cost_key: 'completion_tokens',
|
||||
serviceSpeedRates: { fast: 2 },
|
||||
costs: {
|
||||
tokens: 1_000_000,
|
||||
prompt_tokens: 10,
|
||||
@@ -154,7 +150,6 @@ export const OPEN_AI_MODELS: IChatModel[] = [
|
||||
costs_currency: 'usd-cents',
|
||||
input_cost_key: 'prompt_tokens',
|
||||
output_cost_key: 'completion_tokens',
|
||||
serviceSpeedRates: { fast: 2, ultrafast: 6 },
|
||||
costs: {
|
||||
tokens: 1_000_000,
|
||||
prompt_tokens: 1000,
|
||||
@@ -181,7 +176,6 @@ export const OPEN_AI_MODELS: IChatModel[] = [
|
||||
input_cost_key: 'prompt_tokens',
|
||||
output_cost_key: 'completion_tokens',
|
||||
// OpenAI's promotional pricing, guaranteed only through 2026-11-21.
|
||||
serviceSpeedRates: { fast: 2 },
|
||||
costs: {
|
||||
tokens: 1_000_000,
|
||||
prompt_tokens: 400,
|
||||
@@ -207,7 +201,6 @@ export const OPEN_AI_MODELS: IChatModel[] = [
|
||||
costs_currency: 'usd-cents',
|
||||
input_cost_key: 'prompt_tokens',
|
||||
output_cost_key: 'completion_tokens',
|
||||
serviceSpeedRates: { fast: 2 },
|
||||
costs: {
|
||||
tokens: 1_000_000,
|
||||
prompt_tokens: 200,
|
||||
@@ -233,7 +226,6 @@ export const OPEN_AI_MODELS: IChatModel[] = [
|
||||
costs_currency: 'usd-cents',
|
||||
input_cost_key: 'prompt_tokens',
|
||||
output_cost_key: 'completion_tokens',
|
||||
serviceSpeedRates: { fast: 2 },
|
||||
costs: {
|
||||
tokens: 1_000_000,
|
||||
prompt_tokens: 20,
|
||||
@@ -259,13 +251,6 @@ export const OPEN_AI_MODELS: IChatModel[] = [
|
||||
costs_currency: 'usd-cents',
|
||||
input_cost_key: 'prompt_tokens',
|
||||
output_cost_key: 'completion_tokens',
|
||||
serviceSpeedRates: {
|
||||
fast: {
|
||||
prompt_tokens: 1250,
|
||||
cached_tokens: 125,
|
||||
completion_tokens: 7500,
|
||||
},
|
||||
},
|
||||
costs: {
|
||||
tokens: 1_000_000,
|
||||
prompt_tokens: 500,
|
||||
@@ -310,13 +295,6 @@ export const OPEN_AI_MODELS: IChatModel[] = [
|
||||
costs_currency: 'usd-cents',
|
||||
input_cost_key: 'prompt_tokens',
|
||||
output_cost_key: 'completion_tokens',
|
||||
serviceSpeedRates: {
|
||||
fast: {
|
||||
prompt_tokens: 500,
|
||||
cached_tokens: 50,
|
||||
completion_tokens: 3000,
|
||||
},
|
||||
},
|
||||
costs: {
|
||||
tokens: 1_000_000,
|
||||
prompt_tokens: 250,
|
||||
@@ -360,13 +338,6 @@ export const OPEN_AI_MODELS: IChatModel[] = [
|
||||
costs_currency: 'usd-cents',
|
||||
input_cost_key: 'prompt_tokens',
|
||||
output_cost_key: 'completion_tokens',
|
||||
serviceSpeedRates: {
|
||||
fast: {
|
||||
prompt_tokens: 150,
|
||||
cached_tokens: 15,
|
||||
completion_tokens: 900,
|
||||
},
|
||||
},
|
||||
costs: {
|
||||
tokens: 1_000_000,
|
||||
prompt_tokens: 75,
|
||||
@@ -454,13 +425,6 @@ export const OPEN_AI_MODELS: IChatModel[] = [
|
||||
costs_currency: 'usd-cents',
|
||||
input_cost_key: 'prompt_tokens',
|
||||
output_cost_key: 'completion_tokens',
|
||||
serviceSpeedRates: {
|
||||
fast: {
|
||||
prompt_tokens: 350,
|
||||
cached_tokens: 35,
|
||||
completion_tokens: 2800,
|
||||
},
|
||||
},
|
||||
costs: {
|
||||
tokens: 1_000_000,
|
||||
prompt_tokens: 175,
|
||||
@@ -482,13 +446,6 @@ export const OPEN_AI_MODELS: IChatModel[] = [
|
||||
costs_currency: 'usd-cents',
|
||||
input_cost_key: 'prompt_tokens',
|
||||
output_cost_key: 'completion_tokens',
|
||||
serviceSpeedRates: {
|
||||
fast: {
|
||||
prompt_tokens: 250,
|
||||
cached_tokens: 25,
|
||||
completion_tokens: 2000,
|
||||
},
|
||||
},
|
||||
costs: {
|
||||
tokens: 1_000_000,
|
||||
prompt_tokens: 125,
|
||||
@@ -510,13 +467,6 @@ export const OPEN_AI_MODELS: IChatModel[] = [
|
||||
costs_currency: 'usd-cents',
|
||||
input_cost_key: 'prompt_tokens',
|
||||
output_cost_key: 'completion_tokens',
|
||||
serviceSpeedRates: {
|
||||
fast: {
|
||||
prompt_tokens: 425,
|
||||
cached_tokens: 212.5,
|
||||
completion_tokens: 1700,
|
||||
},
|
||||
},
|
||||
costs: {
|
||||
tokens: 1_000_000,
|
||||
prompt_tokens: 250,
|
||||
@@ -540,13 +490,6 @@ export const OPEN_AI_MODELS: IChatModel[] = [
|
||||
costs_currency: 'usd-cents',
|
||||
input_cost_key: 'prompt_tokens',
|
||||
output_cost_key: 'completion_tokens',
|
||||
serviceSpeedRates: {
|
||||
fast: {
|
||||
prompt_tokens: 25,
|
||||
cached_tokens: 12.5,
|
||||
completion_tokens: 100,
|
||||
},
|
||||
},
|
||||
costs: {
|
||||
tokens: 1_000_000,
|
||||
prompt_tokens: 15,
|
||||
@@ -566,13 +509,6 @@ export const OPEN_AI_MODELS: IChatModel[] = [
|
||||
costs_currency: 'usd-cents',
|
||||
input_cost_key: 'prompt_tokens',
|
||||
output_cost_key: 'completion_tokens',
|
||||
serviceSpeedRates: {
|
||||
fast: {
|
||||
prompt_tokens: 350,
|
||||
cached_tokens: 87.5,
|
||||
completion_tokens: 1400,
|
||||
},
|
||||
},
|
||||
costs: {
|
||||
tokens: 1_000_000,
|
||||
prompt_tokens: 200,
|
||||
@@ -594,13 +530,6 @@ export const OPEN_AI_MODELS: IChatModel[] = [
|
||||
costs_currency: 'usd-cents',
|
||||
input_cost_key: 'prompt_tokens',
|
||||
output_cost_key: 'completion_tokens',
|
||||
serviceSpeedRates: {
|
||||
fast: {
|
||||
prompt_tokens: 70,
|
||||
cached_tokens: 17.5,
|
||||
completion_tokens: 280,
|
||||
},
|
||||
},
|
||||
costs: {
|
||||
tokens: 1_000_000,
|
||||
prompt_tokens: 40,
|
||||
@@ -642,13 +571,6 @@ export const OPEN_AI_MODELS: IChatModel[] = [
|
||||
costs_currency: 'usd-cents',
|
||||
input_cost_key: 'prompt_tokens',
|
||||
output_cost_key: 'completion_tokens',
|
||||
serviceSpeedRates: {
|
||||
fast: {
|
||||
prompt_tokens: 425,
|
||||
cached_tokens: 212.5,
|
||||
completion_tokens: 1700,
|
||||
},
|
||||
},
|
||||
costs: {
|
||||
tokens: 1_000_000,
|
||||
prompt_tokens: 250,
|
||||
|
||||
@@ -20,14 +20,15 @@
|
||||
/**
|
||||
* Offline unit tests for OpenRouterProvider.
|
||||
*
|
||||
* Boots a real PuterServer (in-memory sqlite + dynamo + s3 + mock redis) and
|
||||
* constructs OpenRouterProvider directly against the live wired
|
||||
* `MeteringService` so the recording side is exercised end-to- end. OpenRouter
|
||||
* is OpenAI-compatible, so the OpenAI SDK is mocked at the module boundary; the
|
||||
* model catalog is fetched via `axios` which is mocked at its module boundary
|
||||
* too. Both are the real network egress points. The companion integration test
|
||||
* (OpenRouterProvider.integration.test.ts) exercises the real OpenRouter
|
||||
* endpoint.
|
||||
* Boots a real PuterServer (in-memory sqlite + dynamo + s3 + mock
|
||||
* redis) and constructs OpenRouterProvider directly against the live
|
||||
* wired `MeteringService` so the recording side is exercised end-to-
|
||||
* end. OpenRouter is OpenAI-compatible, so the OpenAI SDK is mocked
|
||||
* at the module boundary; the model catalog is fetched via `axios`
|
||||
* which is mocked at its module boundary too. Both are the real
|
||||
* network egress points.
|
||||
* The companion integration test (OpenRouterProvider.integration.test.ts)
|
||||
* exercises the real OpenRouter endpoint.
|
||||
*/
|
||||
|
||||
import { Writable } from 'node:stream';
|
||||
@@ -299,20 +300,16 @@ describe('OpenRouterProvider model catalog', () => {
|
||||
it('coerces string prices and normalizes conditional tiers', async () => {
|
||||
const { provider } = makeProvider();
|
||||
const models = await provider.models();
|
||||
const sol = models.find(
|
||||
(m) => m.id === 'openrouter:openai/gpt-6.1-sol',
|
||||
)!;
|
||||
const sol = models.find((m) => m.id === 'openrouter:openai/gpt-6.1-sol')!;
|
||||
expect(sol.costs).toEqual({
|
||||
tokens: 1_000_000,
|
||||
prompt: 200,
|
||||
completion: 1000,
|
||||
});
|
||||
expect(sol.pricingOverrides).toEqual([
|
||||
{
|
||||
minPromptTokens: 272000,
|
||||
costs: { prompt: 400, completion: 1500 },
|
||||
},
|
||||
]);
|
||||
expect(sol.pricingOverrides).toEqual([{
|
||||
minPromptTokens: 272000,
|
||||
costs: { prompt: 400, completion: 1500 },
|
||||
}]);
|
||||
});
|
||||
|
||||
it('caches the coerced model list after the first axios round-trip', async () => {
|
||||
@@ -371,12 +368,9 @@ describe('OpenRouterProvider model catalog', () => {
|
||||
|
||||
it('does not reinterpret catalog-added timestamps as release dates', async () => {
|
||||
const { provider } = makeProvider();
|
||||
expect(
|
||||
(await provider.models()).every(
|
||||
(model) => model.release_date === undefined,
|
||||
),
|
||||
).toBe(true);
|
||||
expect((await provider.models()).every(model => model.release_date === undefined)).toBe(true);
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
// ── Disallowed model gate ───────────────────────────────────────────
|
||||
@@ -874,14 +868,11 @@ describe('OpenRouterProvider billed cost through the driver', () => {
|
||||
event.factor = factor;
|
||||
};
|
||||
server.clients.event.on('ai.cost.factor.*', listener as never);
|
||||
return () =>
|
||||
server.clients.event.off('ai.cost.factor.*', listener as never);
|
||||
return () => server.clients.event.off('ai.cost.factor.*', listener as never);
|
||||
};
|
||||
|
||||
/** Μ¢ the ledger was handed for every usage recorded so far. */
|
||||
const ledgerTotal = (
|
||||
spy: MockInstance<MeteringService['batchIncrementUsages']>,
|
||||
) =>
|
||||
/** µ¢ the ledger was handed for every usage recorded so far. */
|
||||
const ledgerTotal = (spy: MockInstance<MeteringService['batchIncrementUsages']>) =>
|
||||
spy.mock.calls
|
||||
.flatMap(([, usages]) => usages)
|
||||
.reduce((total, usage) => total + (usage.costOverride ?? 0), 0);
|
||||
@@ -937,10 +928,7 @@ describe('OpenRouterProvider billed cost through the driver', () => {
|
||||
it('reports what a billed completion was charged, after the cost factor', async () => {
|
||||
const driver = await makeDriver();
|
||||
const stopFactor = withCostFactor(1.6);
|
||||
const recorded = vi.spyOn(
|
||||
server.services.metering,
|
||||
'batchIncrementUsages',
|
||||
);
|
||||
const recorded = vi.spyOn(server.services.metering, 'batchIncrementUsages');
|
||||
createMock.mockResolvedValueOnce({
|
||||
choices: [
|
||||
{
|
||||
@@ -1035,10 +1023,7 @@ describe('OpenRouterProvider billed cost through the driver', () => {
|
||||
it('ends a stream with what it was charged at the catalog rates, after the cost factor', async () => {
|
||||
const driver = await makeDriver();
|
||||
const stopFactor = withCostFactor(1.6);
|
||||
const recorded = vi.spyOn(
|
||||
server.services.metering,
|
||||
'batchIncrementUsages',
|
||||
);
|
||||
const recorded = vi.spyOn(server.services.metering, 'batchIncrementUsages');
|
||||
createMock.mockReturnValueOnce(
|
||||
asAsyncIterable([
|
||||
{ choices: [{ delta: { content: 'hello' } }] },
|
||||
@@ -1141,180 +1126,31 @@ describe('OpenRouterProvider.checkModeration', () => {
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
describe('OpenRouter catalog refresh validation', () => {
|
||||
it('keeps missing model fields and prices unknown and blocks unpriced inference', async () => {
|
||||
axiosRequestMock.mockResolvedValue({
|
||||
data: { data: [{ id: 'fixture/model', name: 'Fixture' }] },
|
||||
});
|
||||
axiosRequestMock.mockResolvedValue({ data: { data: [{ id: 'fixture/model', name: 'Fixture' }] } });
|
||||
const { provider } = makeProvider();
|
||||
const [model] = await provider.models();
|
||||
expect(model.costs).toEqual({ tokens: 1_000_000 });
|
||||
expect(model.context).toBeUndefined();
|
||||
expect(model.max_tokens).toBe(0);
|
||||
await expect(
|
||||
withTestActor(() =>
|
||||
provider.complete({
|
||||
model: 'openrouter:fixture/model',
|
||||
messages: [],
|
||||
}),
|
||||
),
|
||||
).rejects.toMatchObject({ legacyCode: 'model_pricing_unavailable' });
|
||||
await expect(withTestActor(() => provider.complete({ model: 'openrouter:fixture/model', messages: [] })))
|
||||
.rejects.toMatchObject({ legacyCode: 'model_pricing_unavailable' });
|
||||
expect(createMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each(['malformed', 'failed', 'ambiguous conditional price'])(
|
||||
'retains last-good data after a %s refresh',
|
||||
async (failure) => {
|
||||
vi.useFakeTimers({ toFake: ['Date'] });
|
||||
vi.spyOn(console, 'warn').mockImplementation(() => {});
|
||||
const { provider } = makeProvider();
|
||||
const good = await provider.models();
|
||||
vi.advanceTimersByTime(15 * 60 * 1000 + 1);
|
||||
if (failure === 'failed')
|
||||
axiosRequestMock.mockRejectedValueOnce(
|
||||
new Error('unavailable'),
|
||||
);
|
||||
else if (failure === 'malformed')
|
||||
axiosRequestMock.mockResolvedValueOnce({ data: {} });
|
||||
else
|
||||
axiosRequestMock.mockResolvedValueOnce({
|
||||
data: {
|
||||
data: [
|
||||
{
|
||||
...SAMPLE_API_MODELS[0],
|
||||
pricing: {
|
||||
prompt: '0.000002',
|
||||
overrides: [
|
||||
{ min_prompt_tokens: 10, prompt: '' },
|
||||
],
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
expect(await provider.models()).toBe(good);
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
describe('OpenRouter service speed offerings', () => {
|
||||
it('loads and caches tier prices while reserving for endpoint and context differences', async () => {
|
||||
it.each(['malformed', 'failed', 'ambiguous conditional price'])('retains last-good data after a %s refresh', async failure => {
|
||||
vi.useFakeTimers({ toFake: ['Date'] });
|
||||
vi.spyOn(console, 'warn').mockImplementation(() => {});
|
||||
const { provider } = makeProvider();
|
||||
const base = {
|
||||
...(await provider.models())[0],
|
||||
provider: 'openrouter',
|
||||
};
|
||||
axiosRequestMock.mockClear();
|
||||
axiosRequestMock.mockResolvedValueOnce({
|
||||
data: {
|
||||
data: {
|
||||
endpoints: [
|
||||
{
|
||||
service_tier: 'priority',
|
||||
pricing: {
|
||||
prompt: '0.000004',
|
||||
completion: '0.00002',
|
||||
input_cache_read: '0.0000002',
|
||||
},
|
||||
},
|
||||
{
|
||||
service_tier: 'priority',
|
||||
pricing: {
|
||||
prompt: '0.000005',
|
||||
completion: '0.00001',
|
||||
},
|
||||
},
|
||||
{
|
||||
service_tier: 'ultrafast',
|
||||
pricing: {
|
||||
prompt: '0.000012',
|
||||
completion: '0.00006',
|
||||
overrides: [
|
||||
{
|
||||
min_prompt_tokens: 272000,
|
||||
prompt: '0.000024',
|
||||
completion: '0.00009',
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
service_tier: 'priority',
|
||||
pricing: { prompt: 'invalid' },
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
});
|
||||
const offers = await provider.serviceSpeedModels(base);
|
||||
expect(offers.fast?.costs).toMatchObject({
|
||||
prompt: 500,
|
||||
completion: 2000,
|
||||
input_cache_read: 20,
|
||||
});
|
||||
expect(offers.ultrafast?.costs).toMatchObject({
|
||||
prompt: 2400,
|
||||
completion: 9000,
|
||||
});
|
||||
expect(await provider.serviceSpeedModels(base)).toBe(offers);
|
||||
expect(axiosRequestMock).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('uses standard when the tier catalog cannot be fetched', async () => {
|
||||
const { provider } = makeProvider();
|
||||
const base = {
|
||||
...(await provider.models())[0],
|
||||
provider: 'openrouter',
|
||||
};
|
||||
axiosRequestMock.mockRejectedValueOnce(new Error('Unavailable'));
|
||||
expect(await provider.serviceSpeedModels(base)).toEqual({});
|
||||
});
|
||||
});
|
||||
|
||||
describe('OpenRouter speed billing', () => {
|
||||
it('requires an authoritative bill instead of charging the reservation ceiling', async () => {
|
||||
const { selectServiceSpeed } =
|
||||
await import('../../utils/serviceSpeed.js');
|
||||
const { provider } = makeProvider();
|
||||
const base = {
|
||||
...(await provider.models())[0],
|
||||
provider: 'openrouter',
|
||||
};
|
||||
const selected = selectServiceSpeed(
|
||||
base,
|
||||
{
|
||||
model: base.id,
|
||||
messages: [{ role: 'user', content: 'Hello' }],
|
||||
serviceSpeed: 'fast',
|
||||
},
|
||||
() => undefined,
|
||||
{
|
||||
fast: {
|
||||
...base,
|
||||
costs: { ...base.costs, prompt: 500, completion: 2000 },
|
||||
},
|
||||
},
|
||||
);
|
||||
const completion = {
|
||||
choices: [
|
||||
{
|
||||
index: 0,
|
||||
message: { role: 'assistant', content: 'OK' },
|
||||
finish_reason: 'stop',
|
||||
},
|
||||
],
|
||||
usage: { prompt_tokens: 10, completion_tokens: 1 },
|
||||
};
|
||||
createMock.mockResolvedValueOnce({
|
||||
...completion,
|
||||
service_tier: 'priority',
|
||||
usage: { ...completion.usage, cost: undefined },
|
||||
});
|
||||
await expect(
|
||||
withTestActor(() =>
|
||||
provider.complete(selected.args, selected.model),
|
||||
),
|
||||
).rejects.toMatchObject({ legacyCode: 'model_pricing_unavailable' });
|
||||
expect(recordSpy).not.toHaveBeenCalled();
|
||||
const good = await provider.models();
|
||||
vi.advanceTimersByTime(15 * 60 * 1000 + 1);
|
||||
if (failure === 'failed') axiosRequestMock.mockRejectedValueOnce(new Error('unavailable'));
|
||||
else if (failure === 'malformed') axiosRequestMock.mockResolvedValueOnce({ data: {} });
|
||||
else axiosRequestMock.mockResolvedValueOnce({ data: { data: [{ ...SAMPLE_API_MODELS[0], pricing: {
|
||||
prompt: '0.000002', overrides: [{ min_prompt_tokens: 10, prompt: '' }],
|
||||
} }] } });
|
||||
expect(await provider.models()).toBe(good);
|
||||
});
|
||||
});
|
||||
@@ -22,10 +22,8 @@ import { OpenAI } from 'openai';
|
||||
import { HttpError, isHttpError } from '../../../../core/http/HttpError.js';
|
||||
import { UpstreamResponseError } from '../../../util/upstreamErrors.js';
|
||||
import type { MeteringService } from '../../../../services/metering/MeteringService.js';
|
||||
import type { IChatModel, ICompleteArguments, ModelCost } from '../../types.js';
|
||||
import { BoundedTtlMap } from '../../../../util/boundedTtlMap.js';
|
||||
import type { IChatModel, ICompleteArguments } from '../../types.js';
|
||||
import { cachedRemoteCatalog } from '../../utils/cachedRemoteCatalog.js';
|
||||
import { servedServiceSpeed } from '../../utils/serviceSpeed.js';
|
||||
import { catalogPrice } from '../../utils/pricing.js';
|
||||
import { mapOpenRouterPricing } from './pricing.js';
|
||||
import { sdkClientOptions } from '../../utils/sdkClient.js';
|
||||
@@ -66,75 +64,6 @@ const isPolicyBlock = (err: unknown): boolean => {
|
||||
export class OpenRouterProvider extends OpenAICompatProvider {
|
||||
#apiBaseUrl: string;
|
||||
|
||||
#speedCatalogs = new BoundedTtlMap<
|
||||
string,
|
||||
() => Promise<Partial<Record<'fast' | 'ultrafast', IChatModel>>>
|
||||
>({ maxEntries: 256 });
|
||||
|
||||
async serviceSpeedModels(model: IChatModel) {
|
||||
let load = this.#speedCatalogs.get(model.id);
|
||||
if (!load) {
|
||||
load = cachedRemoteCatalog({
|
||||
name: 'OpenRouter speed catalog',
|
||||
fallback: {} as Partial<
|
||||
Record<'fast' | 'ultrafast', IChatModel>
|
||||
>,
|
||||
fetch: async (signal) => {
|
||||
const id = model.id.replace(/^openrouter:/, '');
|
||||
const response = await axios.request({
|
||||
url: `${this.#apiBaseUrl}/models/${id}/endpoints`,
|
||||
method: 'GET',
|
||||
signal,
|
||||
maxContentLength: 2 * 1024 * 1024,
|
||||
});
|
||||
const offers: Partial<
|
||||
Record<'fast' | 'ultrafast', IChatModel>
|
||||
> = {};
|
||||
for (const endpoint of response.data?.data?.endpoints ??
|
||||
[]) {
|
||||
const speed =
|
||||
endpoint.service_tier === 'ultrafast'
|
||||
? 'ultrafast'
|
||||
: ['priority', 'fast'].includes(
|
||||
endpoint.service_tier,
|
||||
)
|
||||
? 'fast'
|
||||
: undefined;
|
||||
if (!speed || !endpoint.pricing) continue;
|
||||
const pricing = mapOpenRouterPricing(endpoint.pricing);
|
||||
if (
|
||||
pricing.costs.prompt === undefined ||
|
||||
pricing.costs.completion === undefined
|
||||
)
|
||||
continue;
|
||||
// Reserve for the most expensive eligible endpoint and context tier.
|
||||
const costs: ModelCost = {
|
||||
...offers[speed]?.costs,
|
||||
tokens: model.costs.tokens,
|
||||
};
|
||||
for (const rates of [
|
||||
pricing.costs,
|
||||
...pricing.overrides.map(
|
||||
(override) => override.costs,
|
||||
),
|
||||
]) {
|
||||
for (const [key, value] of Object.entries(rates))
|
||||
costs[key] = Math.max(costs[key] ?? 0, value);
|
||||
}
|
||||
offers[speed] = {
|
||||
...model,
|
||||
costs,
|
||||
pricingOverrides: [],
|
||||
};
|
||||
}
|
||||
return offers;
|
||||
},
|
||||
});
|
||||
this.#speedCatalogs.set(model.id, load);
|
||||
}
|
||||
return load();
|
||||
}
|
||||
|
||||
constructor(config: ChatProviderConfig, meteringService: MeteringService) {
|
||||
const apiBaseUrl = config.apiBaseUrl || 'https://openrouter.ai/api/v1';
|
||||
super(meteringService, {
|
||||
@@ -273,17 +202,8 @@ export class OpenRouterProvider extends OpenAICompatProvider {
|
||||
return { ...params, usage: { include: true } };
|
||||
}
|
||||
|
||||
protected override meteredUsage(source: UsageSource, model: IChatModel) {
|
||||
protected override meteredUsage(source: UsageSource) {
|
||||
const usage = source.usage as OpenrouterUsage;
|
||||
if (
|
||||
model.serviceSpeedPricing &&
|
||||
servedServiceSpeed(source) !== 'standard' &&
|
||||
catalogPrice(usage.cost) === undefined
|
||||
) {
|
||||
throw new HttpError(503, 'Service tier billing is unavailable', {
|
||||
legacyCode: 'model_pricing_unavailable',
|
||||
});
|
||||
}
|
||||
return {
|
||||
usage: {
|
||||
prompt:
|
||||
|
||||
@@ -20,12 +20,13 @@
|
||||
/**
|
||||
* Offline unit tests for XAIProvider.
|
||||
*
|
||||
* Boots a real PuterServer (in-memory sqlite + dynamo + s3 + mock redis) and
|
||||
* constructs XAIProvider directly against the live wired `MeteringService` so
|
||||
* the recording side is exercised end-to-end. xAI is OpenAI-compatible so the
|
||||
* OpenAI SDK is mocked at the module boundary; that's the real network egress
|
||||
* point. The companion integration test (XAIProvider.integration.test.ts)
|
||||
* exercises the real xAI endpoint.
|
||||
* Boots a real PuterServer (in-memory sqlite + dynamo + s3 + mock
|
||||
* redis) and constructs XAIProvider directly against the live wired
|
||||
* `MeteringService` so the recording side is exercised end-to-end.
|
||||
* xAI is OpenAI-compatible so the OpenAI SDK is mocked at the module
|
||||
* boundary; that's the real network egress point. The companion
|
||||
* integration test (XAIProvider.integration.test.ts) exercises the
|
||||
* real xAI endpoint.
|
||||
*/
|
||||
|
||||
import { Writable } from 'node:stream';
|
||||
@@ -932,7 +933,8 @@ describe('XAIProvider.complete non-stream output', () => {
|
||||
// namespace, actor, and a costsOverride priced from
|
||||
// models.ts (grok-4.6: prompt=200, completion=600, cached=50).
|
||||
expect(recordSpy).toHaveBeenCalledTimes(1);
|
||||
const [usage, actor, prefix, overrides] = recordSpy.mock.calls[0]!;
|
||||
const [usage, actor, prefix, overrides] =
|
||||
recordSpy.mock.calls[0]!;
|
||||
expect(usage).toEqual({
|
||||
prompt_tokens: 90,
|
||||
completion_tokens: 50,
|
||||
@@ -1020,7 +1022,8 @@ describe('XAIProvider.complete non-stream output', () => {
|
||||
}),
|
||||
);
|
||||
|
||||
const [usage, , , overrides] = recordSpy.mock.calls[0]!;
|
||||
const [usage, , , overrides] =
|
||||
recordSpy.mock.calls[0]!;
|
||||
expect(usage.cached_tokens).toBe(0);
|
||||
// 0 cached tokens × any rate = 0 metered cost.
|
||||
expect(overrides).toMatchObject({ cached_tokens: 0 });
|
||||
@@ -1078,7 +1081,8 @@ describe('XAIProvider.complete streaming', () => {
|
||||
|
||||
// grok-build-0.1 costs: prompt=100, completion=200, cached=20.
|
||||
expect(recordSpy).toHaveBeenCalledTimes(1);
|
||||
const [, , prefix, overrides] = recordSpy.mock.calls[0]!;
|
||||
const [, , prefix, overrides] =
|
||||
recordSpy.mock.calls[0]!;
|
||||
expect(prefix).toBe('xai:grok-build-0.1');
|
||||
expect(overrides).toEqual({
|
||||
prompt_tokens: 3 * 100,
|
||||
@@ -1196,60 +1200,3 @@ describe('XAIProvider.checkModeration', () => {
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('xAI service speed billing', () => {
|
||||
it('records the reported Priority charge with cached input and reasoning', async () => {
|
||||
const { selectServiceSpeed } =
|
||||
await import('../../utils/serviceSpeed.js');
|
||||
const { provider } = makeProvider();
|
||||
const base = {
|
||||
...(await provider.models()).find(
|
||||
(entry) => entry.id === 'grok-4.7',
|
||||
)!,
|
||||
provider: 'xai',
|
||||
};
|
||||
const selected = selectServiceSpeed(
|
||||
base,
|
||||
{
|
||||
model: base.id,
|
||||
messages: [{ role: 'user', content: 'Hello' }],
|
||||
serviceSpeed: 'ultrafast',
|
||||
},
|
||||
() => undefined,
|
||||
);
|
||||
createMock.mockResolvedValueOnce({
|
||||
choices: [
|
||||
{
|
||||
index: 0,
|
||||
message: { role: 'assistant', content: 'OK' },
|
||||
finish_reason: 'stop',
|
||||
},
|
||||
],
|
||||
service_tier: 'priority',
|
||||
usage: {
|
||||
prompt_tokens: 1247,
|
||||
completion_tokens: 1,
|
||||
total_tokens: 1282,
|
||||
prompt_tokens_details: { cached_tokens: 1152 },
|
||||
completion_tokens_details: { reasoning_tokens: 34 },
|
||||
cost_in_usd_ticks: 19520000,
|
||||
},
|
||||
});
|
||||
const result = await withTestActor(() =>
|
||||
provider.complete(selected.args, selected.model),
|
||||
);
|
||||
expect(result).toMatchObject({
|
||||
usageDetails: {
|
||||
serviceSpeed: 'fast',
|
||||
outputTokens: 35,
|
||||
reasoningTokens: 34,
|
||||
},
|
||||
});
|
||||
expect(recordSpy).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ billedUsage: 1, completion_tokens: 35 }),
|
||||
expect.anything(),
|
||||
'xai:grok-4.7',
|
||||
expect.objectContaining({ billedUsage: 195200 }),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -19,8 +19,6 @@
|
||||
|
||||
import { OpenAI } from 'openai';
|
||||
import { ChatCompletionCreateParams } from 'openai/resources/index.js';
|
||||
import { catalogPrice } from '../../utils/pricing.js';
|
||||
import { servedServiceSpeed } from '../../utils/serviceSpeed.js';
|
||||
import { Context } from '../../../../core/context.js';
|
||||
import type { MeteringService } from '../../../../services/metering/MeteringService.js';
|
||||
import * as OpenAIUtil from '../../utils/OpenAIUtil.js';
|
||||
@@ -76,15 +74,7 @@ export class XAIProvider implements IChatProvider {
|
||||
}
|
||||
|
||||
async complete(
|
||||
{
|
||||
messages,
|
||||
stream,
|
||||
model,
|
||||
tools,
|
||||
max_tokens,
|
||||
service_tier,
|
||||
serviceSpeed: requestedServiceSpeed,
|
||||
}: ICompleteArguments,
|
||||
{ messages, stream, model, tools, max_tokens }: ICompleteArguments,
|
||||
resolved?: IChatModel,
|
||||
): Promise<IChatCompleteResult> {
|
||||
const actor = Context.get('actor');
|
||||
@@ -98,7 +88,6 @@ export class XAIProvider implements IChatProvider {
|
||||
{
|
||||
messages,
|
||||
model: modelUsed.id,
|
||||
...(service_tier !== undefined ? { service_tier } : {}),
|
||||
...(tools ? { tools } : {}),
|
||||
...(max_tokens !== undefined ? { max_tokens } : {}),
|
||||
stream,
|
||||
@@ -118,49 +107,18 @@ export class XAIProvider implements IChatProvider {
|
||||
}
|
||||
|
||||
return OpenAIUtil.handle_completion_output({
|
||||
usage_calculator: ({
|
||||
usage,
|
||||
service_tier: servedTier,
|
||||
setUsageCosts,
|
||||
setUsageDetails,
|
||||
}) => {
|
||||
const serviceSpeed = servedServiceSpeed({
|
||||
service_tier: servedTier,
|
||||
});
|
||||
usage_calculator: ({ usage, setUsageCosts }) => {
|
||||
// xAI reports cached reads inside `prompt_tokens`; bill them
|
||||
// only at the cached rate.
|
||||
const metered = OpenAIUtil.extractMeteredUsage(usage);
|
||||
const reasoningTokens =
|
||||
usage.completion_tokens_details?.reasoning_tokens ?? 0;
|
||||
const trackedUsage = OpenAIUtil.splitCachedPrompt(usage);
|
||||
trackedUsage.completion_tokens += reasoningTokens;
|
||||
const reportedTicks = catalogPrice(
|
||||
(usage as typeof usage & { cost_in_usd_ticks?: number })
|
||||
.cost_in_usd_ticks,
|
||||
);
|
||||
const { costs } = meterChatUsage(
|
||||
this.#meteringService,
|
||||
actor,
|
||||
this.meteringModelKey(modelUsed.id),
|
||||
modelUsed,
|
||||
trackedUsage,
|
||||
{
|
||||
serviceSpeed,
|
||||
authoritativeUsd:
|
||||
reportedTicks === undefined
|
||||
? undefined
|
||||
: reportedTicks / 10_000_000_000,
|
||||
},
|
||||
OpenAIUtil.splitCachedPrompt(usage),
|
||||
);
|
||||
setUsageCosts(costs);
|
||||
if (requestedServiceSpeed !== undefined)
|
||||
setUsageDetails?.({
|
||||
...OpenAIUtil.usageDetailsFromTrackedUsage(
|
||||
trackedUsage,
|
||||
)!,
|
||||
serviceSpeed,
|
||||
...(reasoningTokens ? { reasoningTokens } : {}),
|
||||
});
|
||||
return metered;
|
||||
},
|
||||
stream,
|
||||
|
||||
@@ -42,7 +42,6 @@ export const XAI_MODELS: IChatModel[] = [
|
||||
costs_currency: 'usd-cents',
|
||||
input_cost_key: 'prompt_tokens',
|
||||
output_cost_key: 'completion_tokens',
|
||||
serviceSpeedRates: { fast: 2 },
|
||||
costs: {
|
||||
tokens: 1_000_000,
|
||||
prompt_tokens: 200,
|
||||
@@ -66,7 +65,6 @@ export const XAI_MODELS: IChatModel[] = [
|
||||
costs_currency: 'usd-cents',
|
||||
input_cost_key: 'prompt_tokens',
|
||||
output_cost_key: 'completion_tokens',
|
||||
serviceSpeedRates: { fast: 2 },
|
||||
costs: {
|
||||
tokens: 1_000_000,
|
||||
prompt_tokens: 200,
|
||||
@@ -89,7 +87,6 @@ export const XAI_MODELS: IChatModel[] = [
|
||||
costs_currency: 'usd-cents',
|
||||
input_cost_key: 'prompt_tokens',
|
||||
output_cost_key: 'completion_tokens',
|
||||
serviceSpeedRates: { fast: 2 },
|
||||
costs: {
|
||||
tokens: 1_000_000,
|
||||
prompt_tokens: 200,
|
||||
@@ -112,7 +109,6 @@ export const XAI_MODELS: IChatModel[] = [
|
||||
costs_currency: 'usd-cents',
|
||||
input_cost_key: 'prompt_tokens',
|
||||
output_cost_key: 'completion_tokens',
|
||||
serviceSpeedRates: { fast: 2 },
|
||||
costs: {
|
||||
tokens: 1_000_000,
|
||||
prompt_tokens: 125,
|
||||
@@ -155,7 +151,6 @@ export const XAI_MODELS: IChatModel[] = [
|
||||
costs_currency: 'usd-cents',
|
||||
input_cost_key: 'prompt_tokens',
|
||||
output_cost_key: 'completion_tokens',
|
||||
serviceSpeedRates: { fast: 2 },
|
||||
costs: {
|
||||
tokens: 1_000_000,
|
||||
prompt_tokens: 125,
|
||||
@@ -191,7 +186,6 @@ export const XAI_MODELS: IChatModel[] = [
|
||||
costs_currency: 'usd-cents',
|
||||
input_cost_key: 'prompt_tokens',
|
||||
output_cost_key: 'completion_tokens',
|
||||
serviceSpeedRates: { fast: 2 },
|
||||
costs: {
|
||||
tokens: 1_000_000,
|
||||
prompt_tokens: 125,
|
||||
@@ -223,7 +217,6 @@ export const XAI_MODELS: IChatModel[] = [
|
||||
costs_currency: 'usd-cents',
|
||||
input_cost_key: 'prompt_tokens',
|
||||
output_cost_key: 'completion_tokens',
|
||||
serviceSpeedRates: { fast: 2 },
|
||||
costs: {
|
||||
tokens: 1_000_000,
|
||||
prompt_tokens: 125,
|
||||
@@ -253,7 +246,6 @@ export const XAI_MODELS: IChatModel[] = [
|
||||
costs_currency: 'usd-cents',
|
||||
input_cost_key: 'prompt_tokens',
|
||||
output_cost_key: 'completion_tokens',
|
||||
serviceSpeedRates: { fast: 2 },
|
||||
costs: {
|
||||
tokens: 1_000_000,
|
||||
prompt_tokens: 100,
|
||||
|
||||
@@ -26,8 +26,6 @@
|
||||
|
||||
export type ModelCost = Record<string, number>;
|
||||
|
||||
export type ServiceSpeed = 'standard' | 'fast' | 'ultrafast';
|
||||
|
||||
export interface ModelModalities {
|
||||
input: string[];
|
||||
output: string[];
|
||||
@@ -69,22 +67,6 @@ export interface IChatModel<T extends ModelCost = ModelCost> extends Record<
|
||||
output_multiplier: number;
|
||||
};
|
||||
pricingOverrides?: ModelPricingOverride[];
|
||||
/**
|
||||
* A token-rate multiplier or explicit per-key rates merged with standard
|
||||
* costs.
|
||||
*/
|
||||
serviceSpeedRates?: Partial<
|
||||
Record<'fast' | 'ultrafast', number | ModelCost>
|
||||
>;
|
||||
serviceSpeedVariants?: { fast?: string };
|
||||
/** Request-local pricing snapshot; never part of the model catalog. */
|
||||
serviceSpeedPricing?: {
|
||||
speed: ServiceSpeed;
|
||||
standardCosts: ModelCost;
|
||||
standardOverrides?: ModelPricingOverride[];
|
||||
fastCosts?: ModelCost;
|
||||
ultrafastCosts?: ModelCost;
|
||||
};
|
||||
context?: number;
|
||||
max_tokens: number;
|
||||
subscriberOnly?: boolean;
|
||||
@@ -94,8 +76,6 @@ export interface IChatModel<T extends ModelCost = ModelCost> extends Record<
|
||||
tool_call?: boolean;
|
||||
responses_api?: boolean;
|
||||
responses_api_only?: boolean;
|
||||
/** Restricts service speeds for deployments with a limited API dialect. */
|
||||
serviceSpeeds?: ServiceSpeed[];
|
||||
/**
|
||||
* Omitted preserves sampling; reasoningDisabled requires explicit effort
|
||||
* none.
|
||||
@@ -183,7 +163,6 @@ export interface UsageDetails {
|
||||
webFetchRequests?: number;
|
||||
speed?: 'fast' | 'standard';
|
||||
serviceTier?: string;
|
||||
serviceSpeed?: ServiceSpeed;
|
||||
/**
|
||||
* Per-pass breakdown when the upstream ran several passes (compaction,
|
||||
* advisor).
|
||||
@@ -219,7 +198,6 @@ export interface ICompleteArguments {
|
||||
* request on another provider that serves the same model.
|
||||
*/
|
||||
fallback?: boolean;
|
||||
serviceSpeed?: ServiceSpeed;
|
||||
stream?: boolean;
|
||||
model: string;
|
||||
test_mode?: boolean;
|
||||
@@ -239,7 +217,10 @@ export interface ICompleteArguments {
|
||||
taskBudget?: { total: number; remaining?: number };
|
||||
/** Claude only: top-level automatic `cache_control`. */
|
||||
cacheControl?: CacheControl;
|
||||
/** Claude only; fast is forwarded when the catalog declares fast rates. */
|
||||
/**
|
||||
* Claude only; forwarded only when the model's catalog entry has
|
||||
* `fast_output_tokens`.
|
||||
*/
|
||||
speed?: 'fast' | 'standard';
|
||||
/** Claude only. */
|
||||
safeguards?: SafeguardRequest[];
|
||||
@@ -279,15 +260,7 @@ export interface ICompleteArguments {
|
||||
truncation?: 'auto' | 'disabled' | undefined;
|
||||
background?: boolean;
|
||||
service_tier?:
|
||||
| 'auto'
|
||||
| 'default'
|
||||
| 'flex'
|
||||
| 'scale'
|
||||
| 'priority'
|
||||
| 'fast'
|
||||
| 'ultrafast'
|
||||
| 'standard'
|
||||
| undefined;
|
||||
'auto' | 'default' | 'flex' | 'scale' | 'priority' | undefined;
|
||||
max_tokens?: number;
|
||||
temperature?: number;
|
||||
reasoning?: { effort: ReasoningEffort } | undefined;
|
||||
@@ -355,10 +328,6 @@ export interface IChatMessageResult {
|
||||
export type IChatCompleteResult = IChatStreamResult | IChatMessageResult;
|
||||
|
||||
export interface IChatProvider {
|
||||
/** Account/catalog-specific speed offerings, fetched before the credit hold. */
|
||||
serviceSpeedModels?(
|
||||
model: IChatModel,
|
||||
): Promise<Partial<Record<'fast' | 'ultrafast', IChatModel>>>;
|
||||
models(extra_params?: unknown): IChatModel[] | Promise<IChatModel[]>;
|
||||
getDefaultModel(): string;
|
||||
/**
|
||||
|
||||
@@ -650,15 +650,12 @@ export const create_chat_stream_handler =
|
||||
block.end();
|
||||
};
|
||||
|
||||
let serviceTier;
|
||||
let last_usage = null;
|
||||
let last_extra_content = null;
|
||||
let finish_reason = null;
|
||||
for await (let chunk of completion) {
|
||||
await chatStream.waitForDrain();
|
||||
chunk = deviations.chunk_but_like_actually(chunk);
|
||||
if (chunk.service_tier !== undefined)
|
||||
serviceTier = chunk.service_tier;
|
||||
const chunk_usage = deviations.index_usage_from_stream_chunk(chunk);
|
||||
if (chunk_usage) last_usage = chunk_usage;
|
||||
if (chunk.choices.length < 1) continue;
|
||||
@@ -749,7 +746,6 @@ export const create_chat_stream_handler =
|
||||
const usage = last_usage
|
||||
? usage_calculator({
|
||||
usage: last_usage,
|
||||
service_tier: serviceTier,
|
||||
extra_content: last_extra_content,
|
||||
setUsageCosts: (c) => chatStream.setUsageCosts(c),
|
||||
setUsageDetails: (d) => {
|
||||
@@ -783,7 +779,6 @@ export const create_chat_stream_handler_responses_api =
|
||||
const message = chatStream.message();
|
||||
const textblock = message.contentBlock({ type: 'text' });
|
||||
|
||||
let serviceTier;
|
||||
let last_usage = null;
|
||||
let completed = false;
|
||||
let sawFunctionCall = false;
|
||||
@@ -792,8 +787,6 @@ export const create_chat_stream_handler_responses_api =
|
||||
let toolUsage = null;
|
||||
for await (const chunk of completion) {
|
||||
await chatStream.waitForDrain();
|
||||
if (chunk.response?.service_tier !== undefined)
|
||||
serviceTier = chunk.response.service_tier;
|
||||
if (chunk.type === 'response.failed' || chunk.type === 'error') {
|
||||
throw new Error(
|
||||
chunk.response?.error?.message ??
|
||||
@@ -925,7 +918,6 @@ export const create_chat_stream_handler_responses_api =
|
||||
const usage = last_usage
|
||||
? usage_calculator({
|
||||
usage: last_usage,
|
||||
service_tier: serviceTier,
|
||||
webSearchCalls,
|
||||
tool_usage: toolUsage,
|
||||
setUsageCosts: (c) => chatStream.setUsageCosts(c),
|
||||
@@ -980,7 +972,6 @@ export const handle_completion_output = async (
|
||||
/**
|
||||
* @type {Record<string, unknown> & {
|
||||
* usage_calculator: (args: {
|
||||
* service_tier?: string;
|
||||
* usage: import('openai/resources/completions.mjs').CompletionUsage;
|
||||
* setUsageCosts: (costs: Record<string, number>) => void;
|
||||
* setUsageDetails: (
|
||||
@@ -1075,7 +1066,6 @@ export const handle_completion_output = async (
|
||||
* @param {((text: string) => Promise<{ flagged: boolean }>) | undefined} [params.moderate]
|
||||
* @param {(args: {
|
||||
* usage: import('openai/resources/responses/responses.mjs').ResponseUsage;
|
||||
* service_tier?: string;
|
||||
* webSearchCalls?: number;
|
||||
* tool_usage?: Record<string, unknown>;
|
||||
* setUsageCosts?: (costs: Record<string, number>) => void;
|
||||
|
||||
@@ -19,15 +19,13 @@
|
||||
|
||||
import type { Actor } from '../../../core/actor.js';
|
||||
import type { MeteringService } from '../../../services/metering/MeteringService.js';
|
||||
import type { IChatModel, ServiceSpeed } from '../types.js';
|
||||
import { serviceSpeedBillingModel } from './serviceSpeed.js';
|
||||
import type { IChatModel } from '../types.js';
|
||||
import { buildCostsOverride } from './pricing.js';
|
||||
|
||||
/** Microcents per US dollar. */
|
||||
const MICROCENTS_PER_USD = 100_000_000;
|
||||
|
||||
export interface MeterChatUsageOptions {
|
||||
serviceSpeed?: ServiceSpeed;
|
||||
/**
|
||||
* What the upstream says it billed, in USD. Recorded as one `billedUsage`
|
||||
* line instead of pricing the tokens, which are still recorded at zero.
|
||||
@@ -79,15 +77,10 @@ export const meterChatUsage = (
|
||||
authoritativeUsd,
|
||||
costOverrides,
|
||||
pricingTime,
|
||||
serviceSpeed = 'standard',
|
||||
}: MeterChatUsageOptions = {},
|
||||
): { usage: Record<string, number>; costs: Record<string, number> } => {
|
||||
const priced = {
|
||||
...buildCostsOverride(
|
||||
usage,
|
||||
serviceSpeedBillingModel(model, serviceSpeed),
|
||||
pricingTime,
|
||||
),
|
||||
...buildCostsOverride(usage, model, pricingTime),
|
||||
...costOverrides,
|
||||
};
|
||||
if (authoritativeUsd !== undefined) {
|
||||
|
||||
@@ -1,150 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2024-present Puter Technologies Inc.
|
||||
*
|
||||
* This file is part of Puter.
|
||||
*
|
||||
* Puter is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published
|
||||
* by the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* Puter is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with Puter. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import type { IChatModel, ServiceSpeed } from '../types.js';
|
||||
import { ALIBABA_MODELS } from '../providers/alibaba/models.js';
|
||||
import { AZURE_MODELS } from '../providers/azure/models.js';
|
||||
import { BYTEPLUS_MODELS } from '../providers/byteplus/models.js';
|
||||
import { CLAUDE_MODELS } from '../providers/claude/models.js';
|
||||
import { DEEPSEEK_MODELS } from '../providers/deepseek/models.js';
|
||||
import { GEMINI_MODELS } from '../providers/gemini/models.js';
|
||||
import { GROQ_MODELS } from '../providers/groq/models.js';
|
||||
import { HOONIFY_MODELS } from '../providers/hoonify/models.js';
|
||||
import { META_MODELS } from '../providers/meta/models.js';
|
||||
import { MINIMAX_MODELS } from '../providers/minimax/models.js';
|
||||
import { MISTRAL_MODELS } from '../providers/mistral/models.js';
|
||||
import { MOONSHOT_MODELS } from '../providers/moonshot/models.js';
|
||||
import { OPEN_AI_MODELS } from '../providers/openai/models.js';
|
||||
import { XAI_MODELS } from '../providers/xai/models.js';
|
||||
import { ZAI_MODELS } from '../providers/zai/models.js';
|
||||
import { shouldPresentAsOpenAI } from './normalizeToOpenAI.js';
|
||||
import {
|
||||
isServiceSpeedUnavailable,
|
||||
lowerServiceSpeed,
|
||||
selectServiceSpeed,
|
||||
servedServiceSpeed,
|
||||
serviceSpeedBillingModel,
|
||||
} from './serviceSpeed.js';
|
||||
|
||||
const catalogs: Array<[string, IChatModel[]]> = [
|
||||
['alibaba', ALIBABA_MODELS],
|
||||
['azure-openai', AZURE_MODELS],
|
||||
['byteplus', BYTEPLUS_MODELS],
|
||||
['claude', CLAUDE_MODELS],
|
||||
['deepseek', DEEPSEEK_MODELS],
|
||||
['gemini', GEMINI_MODELS],
|
||||
['groq', GROQ_MODELS],
|
||||
['hoonify', HOONIFY_MODELS],
|
||||
['meta', META_MODELS],
|
||||
['minimax', MINIMAX_MODELS],
|
||||
['mistral', MISTRAL_MODELS],
|
||||
['moonshotai', MOONSHOT_MODELS],
|
||||
['openai-completion', OPEN_AI_MODELS],
|
||||
['openai-responses', OPEN_AI_MODELS],
|
||||
['xai', XAI_MODELS],
|
||||
['zai', ZAI_MODELS],
|
||||
];
|
||||
const speeds: ServiceSpeed[] = ['standard', 'fast', 'ultrafast'];
|
||||
|
||||
describe('service speed seeded fuzzing', () => {
|
||||
it('preserves catalog, request, normalization, and billing invariants across model changes', () => {
|
||||
let seed = 0x51eed;
|
||||
const pick = <T>(values: T[]): T => {
|
||||
seed = (Math.imul(seed, 1664525) + 1013904223) >>> 0;
|
||||
return values[seed % values.length]!;
|
||||
};
|
||||
const seenProviders = new Set<string>();
|
||||
for (let index = 0; index < 10_000; index++) {
|
||||
const [provider, catalog] = pick(catalogs);
|
||||
seenProviders.add(provider);
|
||||
const base = { ...structuredClone(pick(catalog)), provider };
|
||||
const before = structuredClone(base);
|
||||
Object.freeze(base.costs);
|
||||
Object.freeze(base);
|
||||
const args = Object.freeze({
|
||||
model: base.id,
|
||||
messages: [{ role: 'user', content: `Case ${index}` }],
|
||||
serviceSpeed: pick([...speeds, undefined]),
|
||||
normalize: pick([true, false, undefined]),
|
||||
temperature: pick([0, 0.5, 1]),
|
||||
service_tier: pick(['flex' as const, 'ultrafast' as const, undefined]),
|
||||
speed: pick(['standard' as const, 'fast' as const, undefined]),
|
||||
});
|
||||
const selected = selectServiceSpeed(base, args, (id) => {
|
||||
const variant = catalog.find((entry) => entry.id === id);
|
||||
return variant && { ...variant, provider };
|
||||
});
|
||||
expect(base).toEqual(before);
|
||||
expect(selected.args.messages).toBe(args.messages);
|
||||
expect(selected.args.temperature).toBe(args.temperature);
|
||||
expect(selected.model.provider).toBe(provider);
|
||||
expect(selected.model.release_date).toBe(base.release_date);
|
||||
expect(
|
||||
shouldPresentAsOpenAI(selected.args, selected.model.release_date),
|
||||
).toBe(shouldPresentAsOpenAI(args, base.release_date));
|
||||
if (args.serviceSpeed === undefined) {
|
||||
expect(selected.args).toBe(args);
|
||||
expect(selected.model).toBe(base);
|
||||
continue;
|
||||
}
|
||||
expect(speeds.indexOf(selected.speed)).toBeLessThanOrEqual(
|
||||
speeds.indexOf(args.serviceSpeed),
|
||||
);
|
||||
expect(selected.args.serviceSpeed).toBe(selected.speed);
|
||||
if (args.serviceSpeed === 'standard') {
|
||||
expect(selected.args.speed).not.toBe('fast');
|
||||
expect(selected.args.service_tier).not.toBe('ultrafast');
|
||||
}
|
||||
for (const cost of Object.values(selected.model.costs)) {
|
||||
expect(Number.isFinite(cost)).toBe(true);
|
||||
expect(cost).toBeGreaterThanOrEqual(0);
|
||||
}
|
||||
if (selected.model.serviceSpeedPricing) {
|
||||
const settled = serviceSpeedBillingModel(selected.model, 'standard');
|
||||
expect(settled.costs).toEqual(base.costs);
|
||||
expect(settled.pricingOverrides).toEqual(base.pricingOverrides);
|
||||
}
|
||||
let speed = selected.speed;
|
||||
for (let attempts = 0; speed !== 'standard'; attempts++) {
|
||||
expect(attempts).toBeLessThan(2);
|
||||
speed = lowerServiceSpeed(speed);
|
||||
}
|
||||
}
|
||||
expect([...seenProviders].sort()).toEqual(catalogs.map(([provider]) => provider).sort());
|
||||
});
|
||||
|
||||
it('handles malformed upstream tier and admission-error metadata without coercion or retries', () => {
|
||||
const values = [null, false, 0, 429, '', 'unrelated', [], {},
|
||||
['service_tier capacity unavailable'],
|
||||
{ toString: null }, { toString: 'priority capacity unavailable' }];
|
||||
for (const value of values) {
|
||||
expect(isServiceSpeedUnavailable(value)).toBe(false);
|
||||
for (const status of [undefined, 400, 401, 403, 404, 429, 500, 503]) {
|
||||
for (const variant of [false, true]) {
|
||||
expect(isServiceSpeedUnavailable({ status, message: value }, variant)).toBe(false);
|
||||
expect(isServiceSpeedUnavailable({ status, error: { message: value } }, variant)).toBe(false);
|
||||
}
|
||||
}
|
||||
expect(servedServiceSpeed({ usage: value })).toBe('standard');
|
||||
expect(servedServiceSpeed({ service_tier: value })).toBe('standard');
|
||||
expect(servedServiceSpeed({ usage: { speed: value, service_tier: value } })).toBe('standard');
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -1,148 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2024-present Puter Technologies Inc.
|
||||
*
|
||||
* This file is part of Puter.
|
||||
*
|
||||
* Puter is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published
|
||||
* by the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import {
|
||||
makeMeteringStub,
|
||||
optionalEnv,
|
||||
withTestActor,
|
||||
} from '../../integrationTestUtil.js';
|
||||
import type {
|
||||
IChatMessageResult,
|
||||
IChatProvider,
|
||||
ICompleteArguments,
|
||||
} from '../types.js';
|
||||
import { OpenAiResponsesChatProvider } from '../providers/openai/OpenAiChatResponsesProvider.js';
|
||||
import { GeminiChatProvider } from '../providers/gemini/GeminiChatProvider.js';
|
||||
import { MiniMaxProvider } from '../providers/minimax/MiniMaxProvider.js';
|
||||
import { MoonshotProvider } from '../providers/moonshot/MoonshotProvider.js';
|
||||
import { MistralAIProvider } from '../providers/mistral/MistralAiProvider.js';
|
||||
import { selectServiceSpeed } from './serviceSpeed.js';
|
||||
|
||||
type Case = {
|
||||
name: string;
|
||||
env: string;
|
||||
provider: string;
|
||||
model: string;
|
||||
build: (key: string) => IChatProvider;
|
||||
};
|
||||
const cases: Case[] = [
|
||||
{
|
||||
name: 'OpenAI Ultrafast',
|
||||
env: 'PUTER_TEST_AI_OPENAI_API_KEY',
|
||||
provider: 'openai-responses',
|
||||
model: 'gpt-6.1-sol',
|
||||
build: (key) =>
|
||||
new OpenAiResponsesChatProvider(
|
||||
{ apiKey: key },
|
||||
makeMeteringStub(),
|
||||
),
|
||||
},
|
||||
{
|
||||
name: 'Gemini Priority',
|
||||
env: 'PUTER_TEST_AI_GEMINI_API_KEY',
|
||||
provider: 'gemini',
|
||||
model: 'gemini-3.8-flash',
|
||||
build: (key) =>
|
||||
new GeminiChatProvider({ apiKey: key }, makeMeteringStub()),
|
||||
},
|
||||
{
|
||||
name: 'MiniMax Priority',
|
||||
env: 'PUTER_TEST_AI_MINIMAX_API_KEY',
|
||||
provider: 'minimax',
|
||||
model: 'minimax-m3',
|
||||
build: (key) =>
|
||||
new MiniMaxProvider({ apiKey: key }, makeMeteringStub()),
|
||||
},
|
||||
{
|
||||
name: 'Moonshot Highspeed',
|
||||
env: 'PUTER_TEST_AI_MOONSHOT_API_KEY',
|
||||
provider: 'moonshotai',
|
||||
model: 'kimi-k3.1-pro',
|
||||
build: (key) =>
|
||||
new MoonshotProvider({ apiKey: key }, makeMeteringStub()),
|
||||
},
|
||||
{
|
||||
name: 'Mistral served tier',
|
||||
env: 'PUTER_TEST_AI_MISTRAL_API_KEY',
|
||||
provider: 'mistral',
|
||||
model: 'mistral-medium-latest',
|
||||
build: (key) =>
|
||||
new MistralAIProvider({ apiKey: key }, makeMeteringStub()),
|
||||
},
|
||||
];
|
||||
|
||||
for (const testCase of cases) {
|
||||
describe.skipIf(!optionalEnv(testCase.env))(
|
||||
`serviceSpeed ${testCase.name} (integration)`,
|
||||
() => {
|
||||
it(
|
||||
'completes with a selected speed and normalized text',
|
||||
{ timeout: 90_000 },
|
||||
async () => {
|
||||
const provider = testCase.build(optionalEnv(testCase.env)!);
|
||||
const catalog = (await provider.models()).map((model) => ({
|
||||
...model,
|
||||
provider: testCase.provider,
|
||||
}));
|
||||
const base = catalog.find(
|
||||
(model) =>
|
||||
model.id === testCase.model ||
|
||||
model.aliases?.includes(testCase.model),
|
||||
)!;
|
||||
expect(base).toBeDefined();
|
||||
const args: ICompleteArguments = {
|
||||
model: base.id,
|
||||
messages: [
|
||||
{ role: 'user', content: 'Reply with exactly OK.' },
|
||||
],
|
||||
serviceSpeed: 'ultrafast',
|
||||
max_tokens: 256,
|
||||
reasoning_effort: 'low',
|
||||
normalize: true,
|
||||
};
|
||||
const selection = selectServiceSpeed(base, args, (id) =>
|
||||
catalog.find((model) => model.id === id),
|
||||
);
|
||||
expect(selection.speed).toBe(
|
||||
testCase.provider === 'openai-responses'
|
||||
? 'ultrafast'
|
||||
: 'fast',
|
||||
);
|
||||
const result = (await withTestActor(() =>
|
||||
provider.complete(
|
||||
{ ...selection.args, model: selection.model.id },
|
||||
selection.model,
|
||||
),
|
||||
)) as IChatMessageResult;
|
||||
expect(typeof result.message.content).toBe('string');
|
||||
expect(result.message.content.length).toBeGreaterThan(0);
|
||||
if (
|
||||
['openai-responses', 'gemini', 'minimax'].includes(
|
||||
testCase.provider,
|
||||
)
|
||||
)
|
||||
expect(result.usageDetails?.serviceSpeed).toBe(
|
||||
selection.speed,
|
||||
);
|
||||
},
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -1,368 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2024-present Puter Technologies Inc.
|
||||
*
|
||||
* This file is part of Puter.
|
||||
*
|
||||
* Puter is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published
|
||||
* by the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { Writable } from 'node:stream';
|
||||
import { AIChatStream } from './Streaming.js';
|
||||
import {
|
||||
handle_completion_output,
|
||||
handle_completion_output_responses_api,
|
||||
} from './OpenAIUtil.js';
|
||||
import type { IChatModel, ServiceSpeed } from '../types.js';
|
||||
import {
|
||||
selectServiceSpeed,
|
||||
servedServiceSpeed,
|
||||
serviceSpeedBillingModel,
|
||||
isServiceSpeedUnavailable,
|
||||
} from './serviceSpeed.js';
|
||||
import { meterChatUsage } from './meterChatUsage.js';
|
||||
import { OPEN_AI_MODELS } from '../providers/openai/models.js';
|
||||
import { XAI_MODELS } from '../providers/xai/models.js';
|
||||
import { GEMINI_MODELS } from '../providers/gemini/models.js';
|
||||
import { CLAUDE_MODELS } from '../providers/claude/models.js';
|
||||
|
||||
const model = (provider: string, id: string): IChatModel => ({
|
||||
provider,
|
||||
id,
|
||||
serviceSpeedRates: [...OPEN_AI_MODELS, ...XAI_MODELS, ...GEMINI_MODELS, ...CLAUDE_MODELS]
|
||||
.find((entry) => entry.id === id)?.serviceSpeedRates,
|
||||
costs_currency: 'usd-cents',
|
||||
input_cost_key: 'prompt_tokens',
|
||||
output_cost_key: 'completion_tokens',
|
||||
max_tokens: 1000,
|
||||
costs: {
|
||||
tokens: 1_000_000,
|
||||
prompt_tokens: 200,
|
||||
completion_tokens: 1000,
|
||||
cached_tokens: 10,
|
||||
web_search_requests: 1_000_000,
|
||||
},
|
||||
});
|
||||
const request = (serviceSpeed?: ServiceSpeed) => ({
|
||||
model: 'test',
|
||||
messages: [{ role: 'user', content: 'Hello' }],
|
||||
serviceSpeed,
|
||||
});
|
||||
const noVariant = () => undefined;
|
||||
|
||||
describe('service speed selection', () => {
|
||||
it.each([2, { prompt_tokens: 400, completion_tokens: 2000 }])(
|
||||
'uses catalog rates independently of provider and model names: %j',
|
||||
(rates) => {
|
||||
const entry = {
|
||||
...model('catalog-provider', 'renamed-model'),
|
||||
serviceSpeedRates: { fast: rates },
|
||||
};
|
||||
const selected = selectServiceSpeed(entry, request('ultrafast'), noVariant);
|
||||
expect(selected.speed).toBe('fast');
|
||||
expect(selected.model.costs.prompt_tokens).toBe(400);
|
||||
expect(selected.model.costs.completion_tokens).toBe(2000);
|
||||
expect(entry.costs.prompt_tokens).toBe(200);
|
||||
},
|
||||
);
|
||||
it('preserves an omitted option and native parameters', () => {
|
||||
const entry = model('openai-responses', 'gpt-6.1-sol');
|
||||
const args = { ...request(), service_tier: 'flex' as const };
|
||||
const selected = selectServiceSpeed(entry, args, noVariant);
|
||||
expect(selected.model).toBe(entry);
|
||||
expect(selected.args).toBe(args);
|
||||
});
|
||||
it.each([
|
||||
'deepseek',
|
||||
'zai',
|
||||
'groq',
|
||||
'byteplus',
|
||||
'together-ai',
|
||||
'meta',
|
||||
'ollama',
|
||||
'hoonify',
|
||||
'neuralwatt',
|
||||
'fake-chat',
|
||||
])('uses standard when %s has no verified faster offering', (provider) => {
|
||||
const selected = selectServiceSpeed(
|
||||
model(provider, 'some-model'),
|
||||
request('ultrafast'),
|
||||
noVariant,
|
||||
);
|
||||
expect(selected.speed).toBe('standard');
|
||||
expect(selected.args.service_tier).toBeUndefined();
|
||||
});
|
||||
it.each(['standard', 'fast', 'ultrafast'] as const)(
|
||||
'selects %s without changing the model or catalog prices',
|
||||
(speed) => {
|
||||
const entry = model('openai-responses', 'gpt-6.1-sol');
|
||||
const selected = selectServiceSpeed(
|
||||
entry,
|
||||
request(speed),
|
||||
noVariant,
|
||||
);
|
||||
expect(selected.speed).toBe(speed);
|
||||
expect(selected.model.id).toBe(entry.id);
|
||||
expect(selected.model.costs.prompt_tokens).toBe(
|
||||
200 * { standard: 1, fast: 2, ultrafast: 6 }[speed],
|
||||
);
|
||||
expect(selected.model.costs.web_search_requests).toBe(1_000_000);
|
||||
expect(entry.costs.prompt_tokens).toBe(200);
|
||||
},
|
||||
);
|
||||
it('downgrades ultrafast to fast on a model without ultrafast', () => {
|
||||
const selected = selectServiceSpeed(
|
||||
model('xai', 'grok-4.7'),
|
||||
request('ultrafast'),
|
||||
noVariant,
|
||||
);
|
||||
expect(selected.speed).toBe('fast');
|
||||
expect(selected.args.service_tier).toBe('priority');
|
||||
});
|
||||
it('keeps a compatibility-only Gemini deployment at standard speed', () => {
|
||||
const entry = {
|
||||
...model('gemini', 'gemini-3.8-flash'),
|
||||
serviceSpeeds: ['standard'] as ServiceSpeed[],
|
||||
};
|
||||
expect(
|
||||
selectServiceSpeed(entry, request('ultrafast'), noVariant).speed,
|
||||
).toBe('standard');
|
||||
});
|
||||
it('uses Claude speed independently of its service tier', () => {
|
||||
const entry = model('claude', 'claude-opus-5-5');
|
||||
expect(
|
||||
selectServiceSpeed(entry, request('ultrafast'), noVariant).args
|
||||
.speed,
|
||||
).toBe('fast');
|
||||
expect(
|
||||
selectServiceSpeed(entry, request('ultrafast'), noVariant).args
|
||||
.service_tier,
|
||||
).toBeUndefined();
|
||||
expect(
|
||||
servedServiceSpeed({
|
||||
usage: { speed: 'fast', service_tier: 'standard' },
|
||||
}),
|
||||
).toBe('fast');
|
||||
});
|
||||
it.each([
|
||||
['minimax', 'minimax-m2.7', 'minimax-m2.7-highspeed'],
|
||||
['moonshotai', 'kimi-k3.1-pro', 'kimi-k3.1-pro-highspeed'],
|
||||
['alibaba', 'glm-5.3', 'glm-5.3-prime'],
|
||||
['alibaba', 'glm-5.2', 'glm-5.2-fast-preview'],
|
||||
['infron', 'infron:vendor/model', 'infron:vendor/model:priority'],
|
||||
])(
|
||||
'selects an equivalent %s variant and preserves normalization policy',
|
||||
(provider, id, variantId) => {
|
||||
const base = {
|
||||
...model(provider, id),
|
||||
serviceSpeedVariants: { fast: variantId },
|
||||
release_date: '2026-08-01',
|
||||
};
|
||||
const variant = {
|
||||
...model(provider, variantId),
|
||||
release_date: '2026-10-01',
|
||||
};
|
||||
const selected = selectServiceSpeed(
|
||||
base,
|
||||
request('ultrafast'),
|
||||
(candidate) => (candidate === variantId ? variant : undefined),
|
||||
);
|
||||
expect(selected.model.id).toBe(variantId);
|
||||
expect(selected.model.release_date).toBe(base.release_date);
|
||||
expect(selected.speed).toBe('fast');
|
||||
expect(
|
||||
selectServiceSpeed(base, request('fast'), noVariant).speed,
|
||||
).toBe('standard');
|
||||
},
|
||||
);
|
||||
it('keeps caller media on Gemini compatibility when native speed cannot carry it', () => {
|
||||
const args = {
|
||||
...request('fast'),
|
||||
messages: [
|
||||
{
|
||||
role: 'user',
|
||||
content: [
|
||||
{
|
||||
type: 'video_url',
|
||||
video_url: { url: 'data:video/mp4;base64,AA==' },
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
expect(
|
||||
selectServiceSpeed(
|
||||
model('gemini', 'gemini-3.8-flash'),
|
||||
args,
|
||||
noVariant,
|
||||
).speed,
|
||||
).toBe('standard');
|
||||
});
|
||||
});
|
||||
|
||||
describe('served speed billing', () => {
|
||||
it.each(['standard', 'fast', 'ultrafast'] as const)(
|
||||
'settles an ultrafast hold at the served %s rate',
|
||||
(speed) => {
|
||||
const selected = selectServiceSpeed(
|
||||
model('openai-responses', 'gpt-6.1-sol'),
|
||||
request('ultrafast'),
|
||||
noVariant,
|
||||
).model;
|
||||
const recorded: Array<Record<string, number> | undefined> = [];
|
||||
const meter = {
|
||||
utilRecordUsageObject: (
|
||||
_usage: Record<string, number>,
|
||||
_actor: unknown,
|
||||
_key: string,
|
||||
costs?: Record<string, number>,
|
||||
) => {
|
||||
recorded.push(costs);
|
||||
},
|
||||
};
|
||||
const result = meterChatUsage(
|
||||
meter as never,
|
||||
undefined,
|
||||
'openai:gpt-6.1-sol',
|
||||
selected,
|
||||
{ prompt_tokens: 10, completion_tokens: 5, cached_tokens: 20 },
|
||||
{ serviceSpeed: speed },
|
||||
);
|
||||
expect(result.costs.prompt_tokens).toBe(
|
||||
2000 * { standard: 1, fast: 2, ultrafast: 6 }[speed],
|
||||
);
|
||||
expect(result.costs.cached_tokens).toBe(
|
||||
200 * { standard: 1, fast: 2, ultrafast: 6 }[speed],
|
||||
);
|
||||
expect(recorded).toEqual([result.costs]);
|
||||
},
|
||||
);
|
||||
it('restores standard scheduled and long-context rates after a downgrade', () => {
|
||||
const entry = model('openai-responses', 'gpt-6.1-sol');
|
||||
entry.pricingOverrides = [
|
||||
{
|
||||
minPromptTokens: 100,
|
||||
costs: { prompt_tokens: 400, completion_tokens: 1500 },
|
||||
},
|
||||
];
|
||||
const selected = selectServiceSpeed(
|
||||
entry,
|
||||
request('ultrafast'),
|
||||
noVariant,
|
||||
).model;
|
||||
expect(
|
||||
serviceSpeedBillingModel(selected, 'standard').pricingOverrides,
|
||||
).toEqual(entry.pricingOverrides);
|
||||
expect(
|
||||
serviceSpeedBillingModel(selected, 'fast').pricingOverrides?.[0]
|
||||
.costs.prompt_tokens,
|
||||
).toBe(800);
|
||||
});
|
||||
it.each([
|
||||
[{ service_tier: 'priority' }, 'fast'],
|
||||
[{ usage: { serviceTier: 'priority' } }, 'fast'],
|
||||
[{ usage: { service_tier: 'standard' } }, 'standard'],
|
||||
[{ service_tier: 'ultrafast' }, 'ultrafast'],
|
||||
[{}, 'standard'],
|
||||
])('reads actual speed from %j', (source, speed) => {
|
||||
expect(servedServiceSpeed(source)).toBe(speed);
|
||||
});
|
||||
});
|
||||
|
||||
describe('speed admission failures', () => {
|
||||
it.each([
|
||||
[{ status: 429, message: 'Fast mode rate limit exceeded' }, true],
|
||||
[{ status: 403, message: 'Ultrafast access unavailable' }, true],
|
||||
[{ status: 400, message: 'service_tier is not supported' }, true],
|
||||
[{ status: 401, message: 'Invalid API key' }, false],
|
||||
[{ status: 429, message: 'Rate limit exceeded' }, false],
|
||||
[{ status: 400, message: 'Invalid messages' }, false],
|
||||
])('classifies %j without swallowing unrelated errors', (error, retry) => {
|
||||
expect(isServiceSpeedUnavailable(error)).toBe(retry);
|
||||
});
|
||||
it('downgrades a missing speed variant without retrying an invalid base model', () => {
|
||||
const error = { status: 404, message: 'Model not found' };
|
||||
expect(isServiceSpeedUnavailable(error, true)).toBe(true);
|
||||
expect(isServiceSpeedUnavailable(error)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('streamed service tier metadata', () => {
|
||||
it('retains a tier from an earlier Chat Completions chunk until usage arrives', async () => {
|
||||
let servedTier: string | undefined;
|
||||
const result = await handle_completion_output({
|
||||
stream: true,
|
||||
completion: (async function* () {
|
||||
yield {
|
||||
service_tier: 'priority',
|
||||
choices: [{ index: 0, delta: { content: 'OK' } }],
|
||||
};
|
||||
yield {
|
||||
choices: [{ index: 0, delta: {}, finish_reason: 'stop' }],
|
||||
};
|
||||
yield {
|
||||
choices: [],
|
||||
usage: { prompt_tokens: 10, completion_tokens: 1 },
|
||||
};
|
||||
})(),
|
||||
usage_calculator: (source) => {
|
||||
servedTier = source.service_tier;
|
||||
return source.usage;
|
||||
},
|
||||
});
|
||||
const chatStream = new AIChatStream({
|
||||
stream: new Writable({
|
||||
write(_chunk, _encoding, callback) {
|
||||
callback();
|
||||
},
|
||||
}),
|
||||
});
|
||||
await result.init_chat_stream!({ chatStream });
|
||||
expect(servedTier).toBe('priority');
|
||||
});
|
||||
|
||||
it('uses the final Responses tier when the provider downgrades a stream', async () => {
|
||||
let servedTier: string | undefined;
|
||||
const result = await handle_completion_output_responses_api({
|
||||
stream: true,
|
||||
completion: (async function* () {
|
||||
yield {
|
||||
type: 'response.created',
|
||||
response: { service_tier: 'ultrafast' },
|
||||
};
|
||||
yield { type: 'response.output_text.delta', delta: 'OK' };
|
||||
yield {
|
||||
type: 'response.completed',
|
||||
response: {
|
||||
service_tier: 'default',
|
||||
usage: { input_tokens: 10, output_tokens: 1 },
|
||||
},
|
||||
};
|
||||
})(),
|
||||
usage_calculator: (source) => {
|
||||
servedTier = source.service_tier;
|
||||
return source.usage;
|
||||
},
|
||||
});
|
||||
const chatStream = new AIChatStream({
|
||||
stream: new Writable({
|
||||
write(_chunk, _encoding, callback) {
|
||||
callback();
|
||||
},
|
||||
}),
|
||||
});
|
||||
await result.init_chat_stream!({ chatStream });
|
||||
expect(servedTier).toBe('default');
|
||||
});
|
||||
});
|
||||
@@ -1,261 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2024-present Puter Technologies Inc.
|
||||
*
|
||||
* This file is part of Puter.
|
||||
*
|
||||
* Puter is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published
|
||||
* by the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
import { requiredInputModalities } from './mediaParts.js';
|
||||
import type {
|
||||
IChatModel,
|
||||
ICompleteArguments,
|
||||
ModelCost,
|
||||
ServiceSpeed,
|
||||
} from '../types.js';
|
||||
|
||||
export const lowerServiceSpeed = (speed: ServiceSpeed): ServiceSpeed =>
|
||||
speed === 'ultrafast' ? 'fast' : 'standard';
|
||||
|
||||
const tokenRates = (costs: ModelCost, multiplier: number): ModelCost =>
|
||||
Object.fromEntries(
|
||||
Object.entries(costs).map(([key, value]) => [
|
||||
key,
|
||||
key !== 'tokens' &&
|
||||
/token|^prompt$|^completion$|^input_cache_/.test(key)
|
||||
? value * multiplier
|
||||
: value,
|
||||
]),
|
||||
);
|
||||
|
||||
export const serviceSpeedCosts = (
|
||||
model: IChatModel,
|
||||
speed: 'fast' | 'ultrafast',
|
||||
): ModelCost | undefined => {
|
||||
if (model.serviceSpeeds && !model.serviceSpeeds.includes(speed))
|
||||
return undefined;
|
||||
const rates = model.serviceSpeedRates?.[speed];
|
||||
return typeof rates === 'number'
|
||||
? tokenRates(model.costs, rates)
|
||||
: rates
|
||||
? { ...model.costs, ...rates }
|
||||
: undefined;
|
||||
};
|
||||
|
||||
export interface ServiceSpeedSelection {
|
||||
model: IChatModel;
|
||||
args: ICompleteArguments;
|
||||
speed: ServiceSpeed;
|
||||
}
|
||||
|
||||
/** Select only an equivalent model from the same provider's loaded catalog. */
|
||||
export const selectServiceSpeed = (
|
||||
model: IChatModel,
|
||||
args: ICompleteArguments,
|
||||
findVariant: (id: string) => IChatModel | undefined,
|
||||
offers: Partial<Record<'fast' | 'ultrafast', IChatModel>> = {},
|
||||
): ServiceSpeedSelection => {
|
||||
if (args.serviceSpeed === undefined)
|
||||
return { model, args, speed: 'standard' };
|
||||
const provider = model.provider;
|
||||
const fast =
|
||||
offers.fast?.costs ??
|
||||
(provider === 'gemini' &&
|
||||
(requiredInputModalities(args.messages).some(
|
||||
(modality) => !['text', 'image'].includes(modality),
|
||||
) ||
|
||||
args.messages.some(
|
||||
(message) =>
|
||||
Array.isArray(message.content) &&
|
||||
message.content.some(
|
||||
(part: Record<string, unknown>) =>
|
||||
part &&
|
||||
[
|
||||
'input_audio',
|
||||
'audio_url',
|
||||
'document',
|
||||
'file',
|
||||
'input_file',
|
||||
].includes(String(part.type)),
|
||||
),
|
||||
))
|
||||
? undefined
|
||||
: serviceSpeedCosts(model, 'fast'));
|
||||
const ultra =
|
||||
offers.ultrafast?.costs ?? serviceSpeedCosts(model, 'ultrafast');
|
||||
let speed = args.serviceSpeed;
|
||||
const variantId = model.serviceSpeedVariants?.fast;
|
||||
const variant =
|
||||
offers.fast && offers.fast.id !== model.id
|
||||
? offers.fast
|
||||
: variantId
|
||||
? findVariant(variantId)
|
||||
: undefined;
|
||||
while (speed !== 'standard') {
|
||||
if (speed === 'ultrafast' && ultra) break;
|
||||
if (speed === 'fast' && (fast || variant)) break;
|
||||
speed = lowerServiceSpeed(speed);
|
||||
}
|
||||
const request: ICompleteArguments = {
|
||||
...args,
|
||||
serviceSpeed: speed,
|
||||
speed: undefined,
|
||||
service_tier: undefined,
|
||||
};
|
||||
if (speed === 'fast' && variant) {
|
||||
return {
|
||||
model: { ...variant, release_date: model.release_date },
|
||||
args: request,
|
||||
speed,
|
||||
};
|
||||
}
|
||||
if (provider === 'gemini' && fast)
|
||||
request.service_tier = speed === 'fast' ? 'priority' : 'standard';
|
||||
else if (provider === 'claude')
|
||||
request.speed = speed === 'fast' ? 'fast' : 'standard';
|
||||
else if (provider === 'mistral')
|
||||
request.service_tier = speed === 'fast' ? 'auto' : 'default';
|
||||
else if (
|
||||
provider === 'minimax' &&
|
||||
model.serviceSpeedRates?.fast !== undefined
|
||||
)
|
||||
request.service_tier = speed === 'fast' ? 'priority' : 'standard';
|
||||
else if (fast || ultra)
|
||||
request.service_tier =
|
||||
speed === 'ultrafast'
|
||||
? 'ultrafast'
|
||||
: speed === 'fast'
|
||||
? 'priority'
|
||||
: 'default';
|
||||
if (
|
||||
speed === 'standard' &&
|
||||
[
|
||||
'openai-completion',
|
||||
'openai-responses',
|
||||
'azure-openai',
|
||||
'azure-openai-responses',
|
||||
'openrouter',
|
||||
].includes(provider ?? '')
|
||||
)
|
||||
request.service_tier = 'default';
|
||||
const selectedCosts =
|
||||
speed === 'ultrafast' ? ultra : speed === 'fast' ? fast : undefined;
|
||||
return {
|
||||
args: request,
|
||||
speed,
|
||||
model: selectedCosts
|
||||
? {
|
||||
...model,
|
||||
costs: selectedCosts,
|
||||
pricingOverrides: model.pricingOverrides?.map((override) => ({
|
||||
...override,
|
||||
costs: Object.fromEntries(
|
||||
Object.entries(override.costs).map(([key, value]) => [
|
||||
key,
|
||||
model.costs[key] > 0
|
||||
? (value *
|
||||
(selectedCosts[key] ??
|
||||
model.costs[key])) /
|
||||
model.costs[key]
|
||||
: value,
|
||||
]),
|
||||
),
|
||||
})),
|
||||
serviceSpeedPricing: {
|
||||
speed,
|
||||
standardCosts: model.costs,
|
||||
standardOverrides: model.pricingOverrides,
|
||||
fastCosts: fast,
|
||||
ultrafastCosts: ultra,
|
||||
},
|
||||
}
|
||||
: model,
|
||||
};
|
||||
};
|
||||
|
||||
/** The response is authoritative; an absent tier never earns a premium. */
|
||||
export const servedServiceSpeed = (
|
||||
source: Record<string, unknown>,
|
||||
): ServiceSpeed => {
|
||||
const usage = source.usage as Record<string, unknown> | undefined;
|
||||
const tier =
|
||||
usage?.speed ??
|
||||
usage?.serviceTier ??
|
||||
usage?.service_tier ??
|
||||
source.service_tier;
|
||||
return tier === 'ultrafast'
|
||||
? 'ultrafast'
|
||||
: tier === 'fast' || tier === 'priority'
|
||||
? 'fast'
|
||||
: 'standard';
|
||||
};
|
||||
|
||||
export const serviceSpeedBillingModel = (
|
||||
model: IChatModel,
|
||||
speed: ServiceSpeed,
|
||||
): IChatModel => {
|
||||
const pricing = model.serviceSpeedPricing;
|
||||
if (!pricing || pricing.speed === speed) return model;
|
||||
const costs =
|
||||
speed === 'fast'
|
||||
? (pricing.fastCosts ?? pricing.standardCosts)
|
||||
: pricing.standardCosts;
|
||||
return {
|
||||
...model,
|
||||
costs,
|
||||
pricingOverrides: pricing.standardOverrides?.map((override) => ({
|
||||
...override,
|
||||
costs: Object.fromEntries(
|
||||
Object.entries(override.costs).map(([key, value]) => [
|
||||
key,
|
||||
pricing.standardCosts[key] > 0
|
||||
? (value * (costs[key] ?? pricing.standardCosts[key])) /
|
||||
pricing.standardCosts[key]
|
||||
: value,
|
||||
]),
|
||||
),
|
||||
})),
|
||||
};
|
||||
};
|
||||
|
||||
/** Retry only failures that explicitly concern admission to the faster tier. */
|
||||
export const isServiceSpeedUnavailable = (
|
||||
error: unknown,
|
||||
variant = false,
|
||||
): boolean => {
|
||||
const e = error as {
|
||||
status?: number;
|
||||
statusCode?: number;
|
||||
message?: unknown;
|
||||
error?: { message?: unknown };
|
||||
};
|
||||
const status = e?.status ?? e?.statusCode;
|
||||
const message = e?.error?.message ?? e?.message ?? '';
|
||||
if (typeof message !== 'string') return false;
|
||||
if (
|
||||
variant &&
|
||||
[400, 404].includes(status ?? 0) &&
|
||||
/model.*(?:not found|not exist|unavailable)/i.test(message)
|
||||
)
|
||||
return true;
|
||||
return (
|
||||
[400, 403, 429, 503].includes(status ?? 0) &&
|
||||
/fast mode|ultrafast|service[_ ]?tier|priority (?:tier|processing|capacity)|speed parameter/i.test(
|
||||
message,
|
||||
) &&
|
||||
/unavailable|unsupported|not support|rate.limit|quota|capacity|not enabled|not allowed|access|exceed|invalid value/i.test(
|
||||
message,
|
||||
)
|
||||
);
|
||||
};
|
||||
+1
-104
@@ -368,115 +368,12 @@ describe('PuterServer host header validation', () => {
|
||||
expect(api.status).toBe(404);
|
||||
});
|
||||
|
||||
it('lets a deployment subdomain frame the feedback embed and names it', async () => {
|
||||
const parent = `http://spreadsheet.puter.localhost:${port}`;
|
||||
const res = await request('/embed/feedback', {
|
||||
host: `puter.localhost:${port}`,
|
||||
referer: `${parent}/sheet/1`,
|
||||
});
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.headers['x-frame-options']).toBeUndefined();
|
||||
expect(res.headers['content-security-policy']).toBe(
|
||||
`frame-ancestors 'self' ${parent}`,
|
||||
);
|
||||
expect(res.headers['cache-control']).toBe('no-store');
|
||||
expect(res.body).toContain('/dist/feedback-embed.min.js');
|
||||
expect(res.body).not.toContain('/dist/bundle.min.js');
|
||||
const config = JSON.parse(
|
||||
res.body.match(/id="feedback-embed-config">(.*?)<\/script>/)[1],
|
||||
);
|
||||
expect(config).toEqual({
|
||||
apiOrigin: `http://api.puter.localhost:${port}`,
|
||||
hostOrigin: parent,
|
||||
});
|
||||
|
||||
const hosted = await request('/embed/feedback', {
|
||||
host: `puter.localhost:${port}`,
|
||||
referer: `http://someone.site.puter.localhost:${port}/`,
|
||||
});
|
||||
expect(hosted.headers['content-security-policy']).toBe("frame-ancestors 'self'");
|
||||
expect(
|
||||
JSON.parse(
|
||||
hosted.body.match(/id="feedback-embed-config">(.*?)<\/script>/)[1],
|
||||
).hostOrigin,
|
||||
).toBeNull();
|
||||
|
||||
const redirected = await request('/embed/feedback?puter.api_origin=https://other.test', {
|
||||
host: `puter.localhost:${port}`,
|
||||
});
|
||||
expect(redirected.status).toBe(302);
|
||||
expect(redirected.headers.location).toBe('/embed/feedback');
|
||||
});
|
||||
|
||||
it.each([
|
||||
'sign-in',
|
||||
'show-open-file-picker',
|
||||
'show-save-file-picker',
|
||||
'show-directory-picker',
|
||||
'upgrade',
|
||||
'request-email-confirmation',
|
||||
])('lets a deployment subdomain frame the %s popup and names it to the GUI', async (action) => {
|
||||
const parent = `http://spreadsheet.puter.localhost:${port}`;
|
||||
const guiParams = (body: string) =>
|
||||
JSON.parse(body.match(/gui\((\{.*\})\);/)[1]);
|
||||
const res = await request(`/embed/${action}`, {
|
||||
host: `puter.localhost:${port}`,
|
||||
referer: `${parent}/sheet/1`,
|
||||
});
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.headers['x-frame-options']).toBeUndefined();
|
||||
expect(res.headers['content-security-policy']).toBe(
|
||||
`frame-ancestors 'self' ${parent}`,
|
||||
);
|
||||
expect(res.headers['cache-control']).toBe('no-store');
|
||||
expect(guiParams(res.body).embed_host_origin).toBe(parent);
|
||||
|
||||
const hosted = await request(`/embed/${action}`, {
|
||||
host: `puter.localhost:${port}`,
|
||||
referer: `http://someone.site.puter.localhost:${port}/`,
|
||||
});
|
||||
expect(hosted.headers['content-security-policy']).toBe("frame-ancestors 'self'");
|
||||
expect(guiParams(hosted.body).embed_host_origin).toBeNull();
|
||||
|
||||
const redirected = await request(`/embed/${action}?auth_token=x&embedded_in_popup=true`, {
|
||||
host: `puter.localhost:${port}`,
|
||||
referer: `${parent}/sheet/1`,
|
||||
});
|
||||
expect(redirected.status).toBe(302);
|
||||
expect(redirected.headers.location).toBe(`/embed/${action}`);
|
||||
expect(redirected.headers['x-frame-options']).toBe('SAMEORIGIN');
|
||||
});
|
||||
|
||||
it.each(['/embed/SIGN-IN', '/embed/Show-Open-File-Picker', '/embed/sign-in/', '/embed/Upgrade', '/embed/upgrade/', '/embed/Request-Email-Confirmation'])(
|
||||
'lets a first-party page frame only the exact spelling of %s',
|
||||
async (spelling) => {
|
||||
const res = await request(spelling, {
|
||||
host: `puter.localhost:${port}`,
|
||||
referer: `http://spreadsheet.puter.localhost:${port}/`,
|
||||
});
|
||||
expect(res.status).toBe(302);
|
||||
expect(res.headers.location).toBe(spelling.toLowerCase().replace(/\/$/, ''));
|
||||
expect(res.headers['x-frame-options']).toBe('SAMEORIGIN');
|
||||
expect(res.headers['content-security-policy']).toBeUndefined();
|
||||
},
|
||||
);
|
||||
|
||||
it('names no framing page to the popups it serves in a window', async () => {
|
||||
const res = await request('/action/sign-in?embedded_in_popup=true', {
|
||||
host: `puter.localhost:${port}`,
|
||||
referer: `http://spreadsheet.puter.localhost:${port}/`,
|
||||
});
|
||||
expect(res.headers['x-frame-options']).toBe('SAMEORIGIN');
|
||||
expect(res.headers['content-security-policy']).toBeUndefined();
|
||||
expect(res.body).not.toContain('embed_host_origin');
|
||||
});
|
||||
|
||||
it.each([
|
||||
['a user-hosted site', 'http://someone.site.puter.localhost:PORT/'],
|
||||
['a private app host', 'http://someone.app.puter.localhost:PORT/'],
|
||||
['the API host', 'http://api.puter.localhost:PORT/'],
|
||||
['the WebDAV host', 'http://dav.puter.localhost:PORT/'],
|
||||
['a native app host', 'http://about.puter.localhost:PORT/'],
|
||||
['a native app host', 'http://editor.puter.localhost:PORT/'],
|
||||
['a nested subdomain', 'http://a.spreadsheet.puter.localhost:PORT/'],
|
||||
['another site', 'http://evil.test:PORT/'],
|
||||
['another port', 'http://spreadsheet.puter.localhost:1/'],
|
||||
|
||||
@@ -107,31 +107,6 @@ describe('app browser embed shell', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('feedback embed shell', () => {
|
||||
it('carries the framing page and API origin, and loads only its own script', () => {
|
||||
const html = makeService({
|
||||
api_base_url: 'https://api.deployment.test',
|
||||
gui_bundle: '/static/bundle.min.js?v=42',
|
||||
}).renderFeedbackEmbed({ hostOrigin: 'https://notes.deployment.test' });
|
||||
const configJson = html.match(/id="feedback-embed-config">(.*?)<\/script>/)![1];
|
||||
expect(JSON.parse(configJson)).toEqual({
|
||||
apiOrigin: 'https://api.deployment.test',
|
||||
hostOrigin: 'https://notes.deployment.test',
|
||||
});
|
||||
expect(html).toContain('<script defer src="/static/feedback-embed.min.js?v=42"></script>');
|
||||
expect(html).toContain('<link rel="stylesheet" href="/css/feedback-embed.css">');
|
||||
expect(html).toContain('<main id="feedback-embed"></main>');
|
||||
expect(html).not.toContain('bundle.min.js');
|
||||
expect(html).not.toContain('apps-embed');
|
||||
});
|
||||
|
||||
it('carries no framing page when none is allowed', () => {
|
||||
const html = makeService({}).renderFeedbackEmbed({ hostOrigin: null });
|
||||
const configJson = html.match(/id="feedback-embed-config">(.*?)<\/script>/)![1];
|
||||
expect(JSON.parse(configJson).hostOrigin).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
/** Capture what the service sends, and return the rendered HTML. */
|
||||
const render = async (
|
||||
service: PuterHomepageService,
|
||||
|
||||
@@ -48,15 +48,6 @@ export interface LaunchOptions {
|
||||
on_initialized?: Array<Record<string, unknown>>;
|
||||
}
|
||||
|
||||
/**
|
||||
* A GUI popup a first-party page frames at `/embed/<action>`. `hostOrigin` is
|
||||
* that page, read from the referrer and pinned with frame-ancestors; null when
|
||||
* no allowed page frames it.
|
||||
*/
|
||||
export interface PopupFrame {
|
||||
hostOrigin: string | null;
|
||||
}
|
||||
|
||||
interface PuterGuiAddonsEvent {
|
||||
req: Request;
|
||||
path: string;
|
||||
@@ -180,50 +171,15 @@ export class PuterHomepageService extends PuterService {
|
||||
renderAppBrowserEmbed({
|
||||
guestApps = [],
|
||||
}: { guestApps?: Array<Record<string, unknown>> } = {}): string {
|
||||
return this.#renderEmbed({
|
||||
rootId: 'app-browser',
|
||||
rootClass: 'dashboard',
|
||||
stylesheet: 'apps-embed.css',
|
||||
script: 'apps-embed.min.js',
|
||||
config: {
|
||||
apiOrigin: this.config.api_base_url,
|
||||
sdkUrl:
|
||||
this.config.env === 'dev'
|
||||
? '/sdk/puter.dev.js'
|
||||
: (this.config.gui_puterjs_bundle ??
|
||||
'https://js.puter.com/v2/'),
|
||||
guestApps,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* `hostOrigin` is the first-party page framing the dialog, which the
|
||||
* feedback is sent for; null when no allowed page frames it.
|
||||
*/
|
||||
renderFeedbackEmbed({ hostOrigin }: { hostOrigin: string | null }): string {
|
||||
return this.#renderEmbed({
|
||||
rootId: 'feedback-embed',
|
||||
stylesheet: 'feedback-embed.css',
|
||||
script: 'feedback-embed.min.js',
|
||||
config: { apiOrigin: this.config.api_base_url, hostOrigin },
|
||||
});
|
||||
}
|
||||
|
||||
#renderEmbed({
|
||||
rootId,
|
||||
rootClass,
|
||||
stylesheet,
|
||||
script,
|
||||
config,
|
||||
}: {
|
||||
rootId: string;
|
||||
rootClass?: string;
|
||||
stylesheet: string;
|
||||
script: string;
|
||||
config: Record<string, unknown>;
|
||||
}): string {
|
||||
const configJson = JSON.stringify(config).replace(/</g, '\\u003c');
|
||||
const configJson = JSON.stringify({
|
||||
apiOrigin: this.config.api_base_url,
|
||||
sdkUrl:
|
||||
this.config.env === 'dev'
|
||||
? '/sdk/puter.dev.js'
|
||||
: (this.config.gui_puterjs_bundle ??
|
||||
'https://js.puter.com/v2/'),
|
||||
guestApps,
|
||||
}).replace(/</g, '\\u003c');
|
||||
|
||||
return `<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
@@ -234,27 +190,27 @@ export class PuterHomepageService extends PuterService {
|
||||
<title>${encode(String(this.config.gui_params?.title ?? 'Puter'))}</title>
|
||||
<link rel="stylesheet" href="/css/normalize.css">
|
||||
<link rel="stylesheet" href="/css/dashboard.css">
|
||||
<link rel="stylesheet" href="/css/${stylesheet}">
|
||||
<link rel="stylesheet" href="/css/apps-embed.css">
|
||||
</head>
|
||||
<body>
|
||||
<main id="${rootId}"${rootClass ? ` class="${rootClass}"` : ''}></main>
|
||||
<script type="application/json" id="${rootId}-config">${configJson}</script>
|
||||
<script defer src="${encode(this.#embedScript(script))}"></script>
|
||||
<main id="app-browser" class="dashboard"></main>
|
||||
<script type="application/json" id="app-browser-config">${configJson}</script>
|
||||
<script defer src="${encode(this.#appBrowserEmbedScript())}"></script>
|
||||
</body>
|
||||
</html>`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Embed scripts are built beside the GUI bundle, so they are served from
|
||||
* The embed's script is built beside the GUI bundle, so it is served from
|
||||
* wherever `gui_bundle` is (a CDN in production), with the same query.
|
||||
*/
|
||||
#embedScript(name: string): string {
|
||||
#appBrowserEmbedScript(): string {
|
||||
const base = 'http://relative.invalid';
|
||||
const bundle = new URL(
|
||||
this.config.gui_bundle ?? '/dist/bundle.min.js',
|
||||
base,
|
||||
);
|
||||
const script = new URL(name, bundle);
|
||||
const script = new URL('apps-embed.min.js', bundle);
|
||||
script.search = bundle.search;
|
||||
return script.origin === base
|
||||
? `${script.pathname}${script.search}`
|
||||
@@ -312,7 +268,6 @@ export class PuterHomepageService extends PuterService {
|
||||
ctx: { req: Request; res: Response; actor?: Actor | null },
|
||||
meta: PageMeta,
|
||||
launchOptions: LaunchOptions = {},
|
||||
popupFrame?: PopupFrame,
|
||||
): Promise<void> {
|
||||
const { req, res, actor } = ctx;
|
||||
|
||||
@@ -337,7 +292,6 @@ export class PuterHomepageService extends PuterService {
|
||||
{ req, actor: actor ?? null },
|
||||
meta,
|
||||
launchOptions,
|
||||
popupFrame,
|
||||
);
|
||||
res.send(html);
|
||||
}
|
||||
@@ -348,7 +302,6 @@ export class PuterHomepageService extends PuterService {
|
||||
ctx: { req: Request; actor: Actor | null },
|
||||
meta: PageMeta,
|
||||
launchOptions: LaunchOptions,
|
||||
popupFrame?: PopupFrame,
|
||||
): Promise<string> {
|
||||
const { req, actor } = ctx;
|
||||
const env = this.config.env ?? 'prod';
|
||||
@@ -394,8 +347,6 @@ export class PuterHomepageService extends PuterService {
|
||||
eventsNotifications: notificationsFoldInEnabled(this.config),
|
||||
...meta,
|
||||
launch_options: launchOptions,
|
||||
// After `meta`, so nothing page-specific can name the opener.
|
||||
...(popupFrame ? { embed_host_origin: popupFrame.hostOrigin } : {}),
|
||||
};
|
||||
|
||||
const event: PuterGuiAddonsEvent = {
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
# OpenAI Realtime relay
|
||||
|
||||
The relay serves `/puterai/openai/v1/realtime` on the API host. The SDK exposes
|
||||
it through [`puter.ai.realtime()`](../../../docs/src/AI/realtime.md).
|
||||
it through [`puter.ai.convo()`](../../../docs/src/AI/convo.md).
|
||||
|
||||
**Beta:** This API is incomplete. Its methods, options, events, and behavior may change abruptly, including breaking changes without notice.
|
||||
|
||||
Direct clients are documented in the [Realtime WebSocket API reference](../../../docs/src/AI/realtime-websocket.md).
|
||||
Direct clients are documented in the [Realtime WebSocket API reference](../../../docs/src/AI/realtime.md).
|
||||
|
||||
## Transport
|
||||
|
||||
@@ -27,7 +27,7 @@ The socket opens before authentication completes. Authentication and model
|
||||
failures arrive as OpenAI-shaped error events followed by a close frame.
|
||||
|
||||
```js
|
||||
const conversation = await puter.ai.realtime({ output: ['text'] });
|
||||
const conversation = await puter.ai.convo({ output: ['text'] });
|
||||
conversation.on('error', (event) => console.error(event));
|
||||
conversation.on('text', ({ delta }) => console.log(delta));
|
||||
conversation.on('turn.done', () => conversation.close());
|
||||
|
||||
@@ -1102,9 +1102,8 @@ interface IConfigOptional {
|
||||
/** Force the bundled GUI even in dev. Default: false. */
|
||||
use_bundled_gui: boolean;
|
||||
/**
|
||||
* Override the GUI bundle JS path. Default: `/dist/bundle.min.js`. The
|
||||
* `/embed/*` pages load `apps-embed.min.js` and `feedback-embed.min.js`
|
||||
* from the same directory.
|
||||
* Override the GUI bundle JS path. Default: `/dist/bundle.min.js`. The app
|
||||
* browser embed loads `apps-embed.min.js` from the same directory.
|
||||
*/
|
||||
gui_bundle: string;
|
||||
/** Override the GUI CSS path when bundled. Default: `/dist/bundle.min.css`. */
|
||||
|
||||
+2
-2
@@ -200,8 +200,8 @@ These AI features are supported out of the box when using Puter.js:
|
||||
- **[`puter.ai.img2txt()`](/AI/img2txt/)** - Extract text from images (OCR)
|
||||
- **[`puter.ai.txt2vid()`](/AI/txt2vid/)** - Generate short video clips from text or a reference image with Wan, Seedance, Veo, Kling, MiniMax H3 and other models, or edit a video you supply with Gemini Omni, FLUX 3 or Kling Omni
|
||||
- **[`puter.ai.speech2speech()`](/AI/speech2speech/)** - Convert speech in one voice to another voice
|
||||
- **[`puter.ai.realtime()`](/AI/realtime/)** - Prepare a beta realtime conversation with optional text, microphone, playback, and interruption helpers
|
||||
- **[Realtime WebSocket API](/AI/realtime-websocket/)** - Connect directly without puter.js. This API is in beta and may change abruptly.
|
||||
- **[`puter.ai.convo()`](/AI/convo/)** - Prepare a beta realtime conversation with optional text, microphone, playback, and interruption helpers
|
||||
- **[Realtime WebSocket API](/AI/realtime/)** - Connect directly without puter.js. This API is in beta and may change abruptly.
|
||||
- **[`puter.ai.listModels()`](/AI/listModels/)** - List available AI chat models (and providers) that Puter currently exposes.
|
||||
- **[`puter.ai.listModelProviders()`](/AI/listModelProviders/)** - List the AI providers that Puter currently exposes.
|
||||
- **[`puter.ai.txt2speech.listEngines()`](/AI/txt2speech.listEngines/)** - List available TTS engines/models
|
||||
|
||||
@@ -30,7 +30,6 @@ An object containing the following properties:
|
||||
| Option | Type | Description |
|
||||
|--------|------|-------------|
|
||||
| `model` | `String` | The model you want to use for the completion. If not specified, defaults to `gpt-5.4-nano`. More than 500 models are available from providers including OpenAI, Anthropic, Google, Alibaba Cloud, xAI, Mistral, OpenRouter, Infron, and others. For a full list, see the [AI models list](https://developer.puter.com/ai/models/) page. |
|
||||
| `serviceSpeed` | `String` | Preferred service speed, `"standard"`, `"fast"`, or `"ultrafast"`. Unavailable speeds fall back from ultrafast to fast, then standard. Omitting it preserves the model's default service. Faster service may cost more. See [Service speed](#service-speed) and [Model-specific features](#model-specific-features). |
|
||||
| `stream` | `Boolean` | A boolean indicating whether you want to stream the completion. Defaults to `false`. |
|
||||
| `max_tokens` | `Number` | The maximum number of tokens to generate in the completion. By default, the specific model's maximum is used. |
|
||||
| `temperature` | `Number` | A number between 0 and 2 indicating the randomness of the completion. Lower values make the output more focused and deterministic, while higher values make it more random. By default, the model's own temperature is used. See [Model-specific features](#model-specific-features). |
|
||||
@@ -139,8 +138,6 @@ by a newline. Use the async iterator to receive every chunk as an object.
|
||||
|
||||
In case of an error, the `Promise` will reject with an error message.
|
||||
|
||||
An unrecognized `serviceSpeed` value rejects with `invalid_service_speed`.
|
||||
|
||||
For streaming responses, an error from the AI provider is returned as a chunk
|
||||
with `type: "error"` and a `message` describing the failure. This also happens
|
||||
if the provider stops sending the response before it is complete. Check for
|
||||
@@ -373,20 +370,10 @@ const response = await puter.ai.chat('Hello', {
|
||||
|
||||
With `provider` set as well, the request is answered by that provider or fails. If that provider does not serve the model, the request fails with a `400` instead of going to another provider. The error is the same one you would get if every provider had failed, for example `400 upstream_provider_unavailable` or `429 upstream_rate_limited`.
|
||||
|
||||
## Service speed
|
||||
|
||||
The `serviceSpeed` option selects service capacity independently of reasoning effort. If the requested speed is unavailable for the selected model, the request uses the next supported speed in the order `ultrafast`, `fast`, `standard`.
|
||||
|
||||
A faster tier that rejects a request because its capacity or access is unavailable can retry at a lower speed on the same provider. The `fallback` option controls retries on other providers separately. Once streaming output starts, a failed stream ends with an error instead of restarting at another speed.
|
||||
|
||||
The `usageDetails.serviceSpeed` field reports the served speed. Billing uses the tier or equivalent model that served the request. A provider downgrade is billed at the lower tier's rates. Response normalization follows the same rule as a request without this option, including when a faster equivalent model is selected.
|
||||
|
||||
## Model-specific features
|
||||
|
||||
### OpenAI models
|
||||
|
||||
Fast service is available on models with a published Fast rate card. Ultrafast is available for GPT-6.1 Sol and GPT-6 Astra. Other models fall back to fast or standard. Cache and long-context rates apply to the served tier.
|
||||
|
||||
#### `temperature`
|
||||
|
||||
Some OpenAI reasoning models ignore `temperature` and `top_p`. GPT-5.6, GPT-6 Sol/Luna, and GPT-6.1 Terra accept them only with `reasoning_effort: 'none'`, and GPT-6 Astra, GPT-6.1 Sol, and GPT-5.3 Codex always ignore them.
|
||||
@@ -431,8 +418,6 @@ The `usageDetails` object on every result carries the same counts under provider
|
||||
|
||||
### Anthropic models
|
||||
|
||||
Fast service is available on Claude models with a Fast rate card. Ultrafast falls back to fast. When the account has no Fast quota, the request retries at standard speed. The upstream service tier and inference speed are separate fields.
|
||||
|
||||
#### Prompt Caching
|
||||
|
||||
Specific to Anthropic models, you can use the cache control feature, allowing you to optimize costs for repeated prompts.
|
||||
@@ -457,8 +442,6 @@ You can find the implementation in our [prompt caching example](/playground/ai-c
|
||||
|
||||
### Gemini models
|
||||
|
||||
Fast service uses Priority inference on supported text and image requests. Other media use standard service to preserve input handling.
|
||||
|
||||
#### `temperature`
|
||||
|
||||
`gemini-4-argon` ignores `temperature`. `gemini-3.1-flash-lite` and `gemini-3-flash-preview` use it.
|
||||
@@ -560,8 +543,6 @@ for await (const part of resp) {
|
||||
|
||||
### Moonshot Kimi models
|
||||
|
||||
Models with an equivalent Highspeed variant select that variant for fast service. Other models use standard service.
|
||||
|
||||
#### `reasoning_effort`
|
||||
|
||||
Kimi K3.1 Pro accepts `low`, `high` and `max`, uses `max` when you leave it unset, and fails with `400 bad_request` on any other value.
|
||||
@@ -576,30 +557,6 @@ Moonshot's Kimi K3 and Kimi K3.1 Pro models cache prompt prefixes on their own a
|
||||
|
||||
Muse Spark always reasons, so `none` is ignored for it.
|
||||
|
||||
### xAI models
|
||||
|
||||
Fast service requests Priority processing. Token charges, including cached input and reasoning, follow the served tier.
|
||||
|
||||
### MiniMax models
|
||||
|
||||
MiniMax M3 uses Priority admission for fast service. Earlier models with an equivalent Highspeed variant use that variant. Other models use standard service.
|
||||
|
||||
### Mistral models
|
||||
|
||||
Fast service requests Priority when the account and model are eligible. The provider can serve the request at standard speed.
|
||||
|
||||
### Alibaba Cloud models
|
||||
|
||||
Models with an equivalent Prime or Fast variant select that variant for fast service. Other models use standard service.
|
||||
|
||||
### OpenRouter models
|
||||
|
||||
Faster tiers come from the selected model's endpoint catalog. A tier can fall back upstream. Billing uses the endpoint that serves the request.
|
||||
|
||||
### Infron models
|
||||
|
||||
Models with a Priority offering select that offering for fast service. Other models use standard service.
|
||||
|
||||
## Examples
|
||||
|
||||
### Ask GPT-6 Luna a question
|
||||
@@ -1135,23 +1092,3 @@ Policy 8 - Account Management: Each Enterprise and Ultimate customer is assigned
|
||||
</body>
|
||||
</html>
|
||||
```
|
||||
|
||||
### Select service speed
|
||||
|
||||
For example, request the fastest supported service:
|
||||
|
||||
```html;ai-chat-service-speed
|
||||
<html>
|
||||
<body>
|
||||
<script src="https://js.puter.com/v2/"></script>
|
||||
<script type="module">
|
||||
const response = await puter.ai.chat('Explain closures in one paragraph.', {
|
||||
model: 'gpt-6.1-sol',
|
||||
serviceSpeed: 'ultrafast',
|
||||
});
|
||||
puter.print(response.message.content);
|
||||
puter.print(response.usageDetails.serviceSpeed);
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
```
|
||||
@@ -0,0 +1,151 @@
|
||||
---
|
||||
title: puter.ai.convo()
|
||||
description: Prepare an OpenAI realtime conversation with optional audio and text helpers.
|
||||
platforms: [websites, apps, nodejs, workers]
|
||||
---
|
||||
|
||||
Prepares a realtime OpenAI conversation that your app can connect to when it's ready.
|
||||
|
||||
Preparing the conversation verifies Puter sign-in. Realtime conversations require a paid Puter plan, and usage is billed to the signed-in user. Native OpenAI events and convenience methods use the same session. Microphone capture and speaker playback start when your app requests them.
|
||||
|
||||
In Node.js, the SDK requires a global `WebSocket`, available in Node.js 22 or later.
|
||||
|
||||
**Beta:** This API is incomplete. Its methods, options, events, and behavior may change abruptly, including breaking changes without notice.
|
||||
|
||||
To connect without puter.js, see the [Realtime WebSocket API](/AI/realtime/).
|
||||
|
||||
## Syntax
|
||||
|
||||
```js
|
||||
const conversation = await puter.ai.convo(options = {});
|
||||
await conversation.connect();
|
||||
```
|
||||
|
||||
## Parameters
|
||||
|
||||
#### `options` (Object) (Optional)
|
||||
|
||||
The options object accepts these fields.
|
||||
|
||||
| Option | Type | Description |
|
||||
|--------|------|-------------|
|
||||
| `model` | `String` | The realtime model. Defaults to `gpt-realtime-2.1-mini`. Also accepts `gpt-realtime-2.1`, `gpt-realtime-2`, `gpt-realtime-1.5`, `gpt-realtime`, and `gpt-realtime-mini`. |
|
||||
| `instructions` | `String` | Session instructions, up to 8192 characters. Defaults to the provider's default. |
|
||||
| `output` | `Array<String>` | Accepts `['text']`, `['audio']`, or both. Defaults to `['audio']`. Audio includes a transcript. Requesting both uses audio output and emits transcript deltas through the `text` event. |
|
||||
| `voice` | `String` | OpenAI voice identifier, up to 128 characters. Defaults to the provider's default. |
|
||||
| `turnDetection` | `Boolean` | Whether the provider detects the end of spoken turns automatically. Defaults to `true`. Set to `false` for manual audio commits. |
|
||||
|
||||
## Return value
|
||||
|
||||
A Promise resolves to a prepared conversation after options and sign-in are checked. In a browser, preparation opens the Puter sign-in prompt if needed. Preparation opens no realtime connection and requests no microphone access.
|
||||
|
||||
The conversation exposes these properties and methods.
|
||||
|
||||
| Member | Behavior |
|
||||
| --- | --- |
|
||||
| `state` | `prepared`, `connecting`, `connected`, or `closed`. |
|
||||
| `model` | Resolved model name. |
|
||||
| `connect()` | Opens the connection and applies settings. Resolves after the provider acknowledges session configuration. Concurrent calls share one connection Promise, including bounded retries for transient setup failures. Calling it while connected opens no additional connection. During a reconnection, it resolves when the reconnection succeeds and rejects if the conversation closes instead. |
|
||||
| `configure(options)` | Updates the given session settings and resolves after the provider acknowledges this update. Settings it isn't given, including ones set through native events, are left alone. Accepts the factory options except `model`. One update can be pending at a time. Provider rules apply to changes such as switching a voice after audio has been generated. |
|
||||
| `sendText(text)` | Adds a user message and requests a response. Text must be nonempty and at most 8192 characters. |
|
||||
| `appendAudio(pcm)` | Appends an `Int16Array` containing PCM16, 24 kHz mono audio. A chunk contains at most 12000 samples. |
|
||||
| `commitAudio()` | Commits buffered audio and requests a response. Requires turn detection to be off, through `turnDetection: false` or a native session update. The provider requires at least 100 ms of buffered audio. |
|
||||
| `interrupt(position?)` | Stops built-in playback immediately and waits for cancellation and playback-history synchronization. A reply requested but not yet started is cancelled as soon as it starts. Custom players provide `{ itemId, contentIndex, playedMs }`. An idle call resolves immediately. Readiness failures reject the returned Promise with `session_not_ready` or `session_closed`. |
|
||||
| `send(event)` | Sends a native OpenAI JSON event. |
|
||||
| `on(type, handler)` | Registers a listener and returns an unsubscribe function. Use `'*'` to receive every native and convenience event. |
|
||||
| `off(type, handler)` | Removes a listener. |
|
||||
| `close()` | Closes the session, rejects pending operations, and releases SDK-owned capture and playback resources. Repeated calls have no additional effect. |
|
||||
|
||||
Attach listeners before connecting to receive initial session events. Closing during connection rejects the pending attempt.
|
||||
|
||||
If the connection drops because of network loss, a server restart or a provider error, the conversation reconnects on its own. Normal closes with code 1000 end the conversation. While it reconnects, `state` is `connecting`, a `reconnecting` event fires, and pending operations reject with `connection_lost`. The new session gets every setting the provider acknowledged, from the factory options, `configure()` and native `session.update` events. Then `ready` fires again with `reconnected: true`. Listeners, the microphone and the speaker carry over. Microphone audio captured while reconnecting is dropped.
|
||||
|
||||
The conversation also restores recent context. Before `ready` fires, it adds back up to 40 of the most recent conversation items, 48 KiB in total. Restored items are user text, user speech that has a transcript, assistant replies as text, and function calls with their outputs. User speech has a transcript only when input transcription is configured through native session settings. An assistant reply that was interrupted, or still playing when the connection dropped, is cut to what the user saw or heard. The cut is estimated from how much of the audio played, so it can be off by a few words. Images, speech without a transcript, deleted items, and replies still generating when the connection dropped are left out. Restored items get new item IDs, don't fire item events, and count as input tokens on the next response. Item IDs from before the reconnect don't work in later events. Restoration uses a contiguous suffix of restorable items. An oversized newest item leaves that suffix empty. Older items left out to fit the window fire a `context_trimmed` event with the count in `omittedItems`; this is routine and not an error. A provider refusal or a failure to send the restored items fires one `error` event with code `context_restore_failed` per restoration. In both cases the conversation stays connected. Items are preserved without truncating text, function arguments or function results.
|
||||
|
||||
When Puter knows ahead of time that the server a session runs on will restart, it sends a `puter.reconnect` event, which also reaches your listeners. Without that notice, a restart drops the connection and the conversation reconnects as above. Within a few seconds, the conversation opens a replacement session in the background while the current one keeps working. It switches once no reply is generating or playing, no user turn is being spoken or transcribed, no function call is waiting for its output, and nothing you sent is waiting on the provider. The switch goes through the same steps as a reconnect, and the `reconnecting` event has code 1012. If the replacement can't open yet, the conversation keeps the current session and tries again later. A refusal that retrying can't fix, such as `insufficient_funds`, stops the attempts. If the server closes the session first, the conversation switches to the replacement, or reconnects if none is open.
|
||||
|
||||
The conversation makes up to ten attempts over about a minute. In a browser that reports being offline, it first waits up to two minutes for the connection to come back. If every attempt fails, or the server refuses with an error such as `insufficient_funds`, the conversation closes. A closed conversation cannot reconnect. To start another session, prepare a new one.
|
||||
|
||||
Native event definitions are listed in the [OpenAI realtime reference](https://developers.openai.com/api/reference/resources/realtime/server-events). Native events retain their provider fields. Sending native events preserves direct control of the session. Puter refuses `conversation.item.retrieve` events and MCP tools (`"type": "mcp"`) in `session.update` and `response.create` events. Sending one fires an `error` event with code `invalid_event`, and the conversation closes with code 1008. Audio helpers expect the session to use PCM16 at 24 kHz.
|
||||
|
||||
## Errors and limits
|
||||
|
||||
Failures use objects containing `code` and `message`. Preparation can reject with `invalid_argument`, `model_not_found`, `auth_required`, `auth_canceled`, or `auth_failed`. Connection can reject with `subscription_required` or `insufficient_funds`, which also show the Puter upgrade prompt. Connection and asynchronous operations can reject with provider errors, `session_closed`, `connection_lost`, `operation_timeout`, or `operation_in_progress`. Sending before readiness, or while reconnecting, throws `session_not_ready`.
|
||||
|
||||
Invalid input throws `invalid_argument`, `invalid_event`, or `input_too_large`. A full SDK send queue throws `queue_full`. Media helpers report `unsupported_environment`, `permission_denied`, `media_error`, `media_timeout`, or `queue_full`. Runtime media errors and `context_restore_failed` arrive through the `error` event. Provider errors also arrive as native `error` events with a nested `error` object.
|
||||
|
||||
Each native event is capped at 64 KiB. The SDK bounds JSON traversal, outgoing queues, acknowledgment waits, microphone work, and playback. All numeric limits are listed on [rate limits and quotas](/rate-limits-and-quotas/).
|
||||
|
||||
## Convenience events
|
||||
|
||||
The conversation emits these events alongside native events.
|
||||
|
||||
| Event | Fields |
|
||||
| --- | --- |
|
||||
| `ready` | `model`, `provider`, and `reconnected: true` after a reconnection |
|
||||
| `reconnecting` | `code`, `reason` of the dropped connection. After a `puter.reconnect` event, `code` is 1012. |
|
||||
| `context_trimmed` | `omittedItems`, the number of restorable items left out of the restored context after a reconnection. Fires before `ready`. |
|
||||
| `text` | `delta`, `responseId` |
|
||||
| `transcript` | `role`, `text`, `final`. Assistant deltas use `final: false`. Completed assistant and user transcripts use `final: true`. User transcripts require transcription to be configured through native session settings. |
|
||||
| `audio` | `pcm`, `sampleRate`, `responseId`, `itemId`, `contentIndex`. The PCM chunk is an `Int16Array`. |
|
||||
| `interrupted` | `source` (`manual` or `speech`), `responseId` |
|
||||
| `turn.done` | `responseId`, native provider `usage`, `status` |
|
||||
| `close` | `code`, `reason` |
|
||||
|
||||
Each event includes its `type`. When the provider event leaves out an ID, `responseId` and `itemId` are empty strings and `contentIndex` is `0`. The `interrupted` event signals local interruption immediately. Its corresponding operation resolves after the provider acknowledges cancellation and any requested truncation. Late audio from a canceled response remains visible as native events and is excluded from convenience audio and built-in playback.
|
||||
|
||||
## Browser media
|
||||
|
||||
The optional microphone and speaker helpers require a browser with Web Audio support. Microphone capture also requires media permissions and a secure context. Start audio from a user action so the browser can allow playback.
|
||||
|
||||
| Member | Behavior |
|
||||
| --- | --- |
|
||||
| `microphone.start()` | Requests microphone access and streams PCM16, resampled to 24 kHz, in 20 ms chunks through an AudioWorklet. If the page or network falls behind, chunks are dropped rather than stopping capture. |
|
||||
| `microphone.mute()` | Disables capture tracks and stops forwarding captured chunks. |
|
||||
| `microphone.unmute()` | Enables capture tracks and forwarding. |
|
||||
| `microphone.stop()` | Stops capture tracks and releases capture resources. A `start()` still waiting on the permission prompt rejects with `session_closed`. |
|
||||
| `speaker.start({ bargeIn: true })` | Starts playback. Barge-in defaults to `true`. With barge-in enabled, provider speech-start events interrupt playback and synchronize played audio with conversation history. Starting the speaker requests no microphone access. |
|
||||
| `speaker.stop()` | Clears playback and releases its audio context. |
|
||||
|
||||
Both start methods require a connected session. Capture and playback are independent, so custom audio input can use the built-in speaker, and built-in capture can use custom playback.
|
||||
|
||||
## Examples
|
||||
|
||||
### Have a text conversation
|
||||
|
||||
A text conversation uses convenience methods for input and streamed output.
|
||||
|
||||
```js
|
||||
const conversation = await puter.ai.convo({
|
||||
output: ['text'],
|
||||
instructions: 'Keep replies short.',
|
||||
});
|
||||
|
||||
conversation.on('text', ({ delta }) => console.log(delta));
|
||||
conversation.on('turn.done', () => conversation.close());
|
||||
conversation.on('error', (event) => console.error(event));
|
||||
|
||||
await conversation.connect();
|
||||
conversation.sendText('Say hello in three words.');
|
||||
```
|
||||
|
||||
### Have a voice conversation
|
||||
|
||||
A voice conversation enables the microphone and speaker after connection.
|
||||
|
||||
```js
|
||||
const conversation = await puter.ai.convo();
|
||||
conversation.on('transcript', ({ role, text }) => console.log(role, text));
|
||||
conversation.on('error', (event) => console.error(event));
|
||||
|
||||
await conversation.connect();
|
||||
await conversation.speaker.start();
|
||||
await conversation.microphone.start();
|
||||
|
||||
// To interrupt a response and submit a replacement text turn:
|
||||
await conversation.interrupt();
|
||||
conversation.sendText('Actually, make it Wednesday.');
|
||||
|
||||
// When the user ends the conversation:
|
||||
conversation.close();
|
||||
```
|
||||
@@ -1,126 +0,0 @@
|
||||
---
|
||||
title: Realtime WebSocket API (Beta)
|
||||
description: Connect to OpenAI realtime conversations through Puter without puter.js.
|
||||
platforms: [websites, apps, nodejs, workers]
|
||||
---
|
||||
|
||||
The Realtime WebSocket API lets your client send and receive native OpenAI realtime JSON events through Puter.
|
||||
|
||||
Puter authenticates the user and charges their account for usage.
|
||||
|
||||
**Beta:** This API is incomplete. Its methods, options, events, and behavior may change abruptly, including breaking changes without notice.
|
||||
|
||||
For optional text, microphone, playback, and interruption helpers, use [`puter.ai.realtime()`](/AI/realtime/).
|
||||
|
||||
## Connection and authentication
|
||||
|
||||
Connect to this URL on the Puter API host:
|
||||
|
||||
```text
|
||||
wss://api.puter.com/puterai/openai/v1/realtime?model=gpt-realtime-2.1-mini
|
||||
```
|
||||
|
||||
The `model` query parameter defaults to `gpt-realtime-2.1-mini`. The model is fixed for the connection. A session update that changes it is rejected. It also accepts `gpt-realtime-2.1`, `gpt-realtime-2`, `gpt-realtime-1.5`, `gpt-realtime`, and `gpt-realtime-mini`.
|
||||
|
||||
Authenticate with a Puter session, app, or full-access API token. Puter supplies the provider credential. Server clients pass this header:
|
||||
|
||||
```text
|
||||
Authorization: Bearer <PUTER_TOKEN>
|
||||
```
|
||||
|
||||
Browser WebSocket clients pass `realtime` and `openai-insecure-api-key.<PUTER_TOKEN>` as subprotocols. The server echoes only `realtime`. The endpoint also accepts an `auth_token` query parameter. Prefer the authorization header where supported because URLs and subprotocols can appear in logs. Authentication takes precedence in this order, header, subprotocol, then query parameter.
|
||||
|
||||
The socket can open before authentication and provider setup finish. Listen for errors and closure immediately. Wait for `session.created`, send your session settings, then wait for `session.updated` before submitting a turn.
|
||||
|
||||
To open a replacement while another connection remains healthy, set the optional `purpose=handover` query parameter. These attempts share a smaller per-credential budget, checked before the general connection-attempt budget. Initial connections and dropped-connection recovery use the URL without this parameter. The limits are listed in [rate limits and quotas](/rate-limits-and-quotas/).
|
||||
|
||||
## Text example
|
||||
|
||||
Install the `ws` package and set `PUTER_TOKEN` to your Puter token. Run this example as a Node.js ES module:
|
||||
|
||||
```js
|
||||
import WebSocket from 'ws';
|
||||
|
||||
const socket = new WebSocket(
|
||||
'wss://api.puter.com/puterai/openai/v1/realtime?model=gpt-realtime-2.1-mini',
|
||||
{ headers: { Authorization: `Bearer ${process.env.PUTER_TOKEN}` } },
|
||||
);
|
||||
const send = (event) => socket.send(JSON.stringify(event));
|
||||
|
||||
socket.on('message', (data) => {
|
||||
const event = JSON.parse(data.toString());
|
||||
|
||||
if (event.type === 'session.created') {
|
||||
send({
|
||||
type: 'session.update',
|
||||
session: {
|
||||
type: 'realtime',
|
||||
output_modalities: ['text'],
|
||||
instructions: 'Keep replies short.',
|
||||
},
|
||||
});
|
||||
}
|
||||
if (event.type === 'session.updated') {
|
||||
send({
|
||||
type: 'conversation.item.create',
|
||||
item: {
|
||||
type: 'message',
|
||||
role: 'user',
|
||||
content: [{ type: 'input_text', text: 'Hello!' }],
|
||||
},
|
||||
});
|
||||
send({ type: 'response.create' });
|
||||
}
|
||||
if (event.type === 'response.output_text.delta')
|
||||
process.stdout.write(event.delta);
|
||||
if (event.type === 'error')
|
||||
console.error(event.error);
|
||||
if (event.type === 'response.done')
|
||||
socket.close();
|
||||
});
|
||||
socket.on('error', console.error);
|
||||
socket.on('close', (code, reason) => console.log(code, reason.toString()));
|
||||
```
|
||||
|
||||
## Events, audio, and interruption
|
||||
|
||||
Each message contains one JSON object with a nonempty string `type` of at most 128 characters. Binary messages are rejected. Native events retain their provider fields. The endpoint doesn't deliver `rate_limits.updated`, which describes Puter's provider account rather than yours, and it removes provider organization IDs from error messages. The endpoint exposes the WebSocket event protocol. Your client manages capture, playback, acknowledgments, and timeouts.
|
||||
|
||||
The endpoint refuses `conversation.item.retrieve` events and MCP tools (`"type": "mcp"`) in `session.update` and `response.create` events. A refused event isn't sent to the provider. The session gets an `invalid_event` error and closes with 1008.
|
||||
|
||||
PCM16 audio configured at 24 kHz mono is sent as base64 chunks in `input_audio_buffer.append` events. Output arrives in `response.output_audio.delta` events. With manual turn detection, commit buffered input with `input_audio_buffer.commit`, then request a reply with `response.create`.
|
||||
|
||||
To interrupt, stop local playback immediately and send `response.cancel` with the active `response_id`. If some generated audio was not played, send `conversation.item.truncate` with its `item_id`, `content_index`, and `audio_end_ms` set to the amount actually played. Wait for `response.done` and any requested `conversation.item.truncated` acknowledgment before submitting a replacement turn.
|
||||
|
||||
Connection loss ends the session. Reconnecting creates a new conversation. Tool execution and automatic reconnection belong to your client.
|
||||
|
||||
## Server restarts
|
||||
|
||||
When Puter knows ahead of time that the server a session runs on will restart, it sends each open session this event, at most once a minute:
|
||||
|
||||
```json
|
||||
{
|
||||
"type": "puter.reconnect",
|
||||
"event_id": "event_puter_1767225600000",
|
||||
"reason": "server_restarting",
|
||||
"close_in_ms": 90000
|
||||
}
|
||||
```
|
||||
|
||||
The `reason` field is `server_restarting`. The `close_in_ms` field, when present, is about how long until the server closes the session itself. The session keeps working until then. Open a new connection after a short, randomized delay, and once it gets `session.created` and your client is idle, with no response generating and no user turn in progress, move to it and close the old one. A connection that reaches a server that is also restarting gets a `server_restarting` error and closes with 1012. In that case keep the old session and try again after a short, randomized delay. If the server closes the old session first, the close code is 1012, and your client reconnects the same way. A restart can also drop the connection without any notice, so treat an unexpected close the same way.
|
||||
|
||||
A new connection starts an empty conversation. To keep context, add earlier items back with `conversation.item.create` before you request a response. Event types that start with `puter.` come from Puter, not the provider.
|
||||
|
||||
## Errors, billing, and limits
|
||||
|
||||
API errors arrive as `{ "type": "error", "error": { "code": "...", "message": "..." } }`. Handle socket errors and close frames too. Invalid, missing, or revoked credentials use `invalid_api_key`. If Puter can't check a credential or the account's plan, the error is `internal_error` and the session closes with 1011, so try again after a short, randomized delay. Other relay codes include `permission_denied`, `model_not_found`, `insufficient_funds`, `subscription_required`, `rate_limit_exceeded`, `invalid_event`, `connection_timeout`, `provider_unavailable`, `upstream_error`, and `server_restarting`.
|
||||
|
||||
Policy failures generally close with 1008, oversized client messages with 1009, upstream or setup failures with 1011, server restarts with 1012, and temporary server overload with 1013. Reconnect after 1011, 1012, or 1013. Authentication and model failures can arrive after the WebSocket handshake succeeds.
|
||||
|
||||
The endpoint requires a paid Puter plan. Usage is charged after completed responses and input transcriptions. While a response generates, part of your balance is held for it, so a session opens only if your balance covers one response. If the provider connection closes before a response reports its usage, the response is charged the full amount held for it. Each account can open 20 sessions at once by default. Each JSON message you send is limited to 64 KiB, including reassembled fragments. Messages from the provider can be up to 4 MiB. Stream audio in small chunks. All message rates, queue caps, timeouts, and other bounds are published in [rate limits and quotas](/rate-limits-and-quotas/).
|
||||
|
||||
Input transcription holds a small amount of your balance per transcribed item, priced at the transcription model you select. Two items are reserved ahead of your audio and replenished as the provider commits them, so a session holds only its spare items plus the items still awaiting a transcript. Changing the transcription model reprices the spare items. If your balance can't cover another item, audio waits while earlier items settle; once none are left to settle, the session closes with `insufficient_funds`. Failed transcriptions, items without final usage, and audio whose commit the provider never acknowledges before the connection closes are each charged that model's fixed per-item amount. Unacknowledged audio is charged one item per started 160 seconds. With server turn detection, only detected speech counts, so silence is never charged. The amounts, timeout and audio limits are listed in [rate limits and quotas](/rate-limits-and-quotas/).
|
||||
|
||||
Provider-reported realtime models must have a known price. A missing model uses the last known model. An explicitly unpriced model closes the connection with `upstream_error`.
|
||||
|
||||
After recording usage, the connection can continue while settled credit is positive, including a fractional balance. Each new billable operation still needs its full reservation after accounting for other outstanding holds.
|
||||
+96
-121
@@ -1,151 +1,126 @@
|
||||
---
|
||||
title: puter.ai.realtime()
|
||||
description: Prepare an OpenAI realtime conversation with optional audio and text helpers.
|
||||
title: Realtime WebSocket API (Beta)
|
||||
description: Connect to OpenAI realtime conversations through Puter without puter.js.
|
||||
platforms: [websites, apps, nodejs, workers]
|
||||
---
|
||||
|
||||
Prepares a realtime OpenAI conversation that your app can connect to when it's ready.
|
||||
The Realtime WebSocket API lets your client send and receive native OpenAI realtime JSON events through Puter.
|
||||
|
||||
Preparing the conversation verifies Puter sign-in. Realtime conversations require a paid Puter plan, and usage is billed to the signed-in user. Native OpenAI events and convenience methods use the same session. Microphone capture and speaker playback start when your app requests them.
|
||||
|
||||
In Node.js, the SDK requires a global `WebSocket`, available in Node.js 22 or later.
|
||||
Puter authenticates the user and charges their account for usage.
|
||||
|
||||
**Beta:** This API is incomplete. Its methods, options, events, and behavior may change abruptly, including breaking changes without notice.
|
||||
|
||||
To connect without puter.js, see the [Realtime WebSocket API](/AI/realtime-websocket/).
|
||||
For optional text, microphone, playback, and interruption helpers, use [`puter.ai.convo()`](/AI/convo/).
|
||||
|
||||
## Syntax
|
||||
## Connection and authentication
|
||||
|
||||
```js
|
||||
const conversation = await puter.ai.realtime(options = {});
|
||||
await conversation.connect();
|
||||
Connect to this URL on the Puter API host:
|
||||
|
||||
```text
|
||||
wss://api.puter.com/puterai/openai/v1/realtime?model=gpt-realtime-2.1-mini
|
||||
```
|
||||
|
||||
## Parameters
|
||||
The `model` query parameter defaults to `gpt-realtime-2.1-mini`. The model is fixed for the connection. A session update that changes it is rejected. It also accepts `gpt-realtime-2.1`, `gpt-realtime-2`, `gpt-realtime-1.5`, `gpt-realtime`, and `gpt-realtime-mini`.
|
||||
|
||||
#### `options` (Object) (Optional)
|
||||
Authenticate with a Puter session, app, or full-access API token. Puter supplies the provider credential. Server clients pass this header:
|
||||
|
||||
The options object accepts these fields.
|
||||
```text
|
||||
Authorization: Bearer <PUTER_TOKEN>
|
||||
```
|
||||
|
||||
| Option | Type | Description |
|
||||
|--------|------|-------------|
|
||||
| `model` | `String` | The realtime model. Defaults to `gpt-realtime-2.1-mini`. Also accepts `gpt-realtime-2.1`, `gpt-realtime-2`, `gpt-realtime-1.5`, `gpt-realtime`, and `gpt-realtime-mini`. |
|
||||
| `instructions` | `String` | Session instructions, up to 8192 characters. Defaults to the provider's default. |
|
||||
| `output` | `Array<String>` | Accepts `['text']`, `['audio']`, or both. Defaults to `['audio']`. Audio includes a transcript. Requesting both uses audio output and emits transcript deltas through the `text` event. |
|
||||
| `voice` | `String` | OpenAI voice identifier, up to 128 characters. Defaults to the provider's default. |
|
||||
| `turnDetection` | `Boolean` | Whether the provider detects the end of spoken turns automatically. Defaults to `true`. Set to `false` for manual audio commits. |
|
||||
Browser WebSocket clients pass `realtime` and `openai-insecure-api-key.<PUTER_TOKEN>` as subprotocols. The server echoes only `realtime`. The endpoint also accepts an `auth_token` query parameter. Prefer the authorization header where supported because URLs and subprotocols can appear in logs. Authentication takes precedence in this order, header, subprotocol, then query parameter.
|
||||
|
||||
## Return value
|
||||
The socket can open before authentication and provider setup finish. Listen for errors and closure immediately. Wait for `session.created`, send your session settings, then wait for `session.updated` before submitting a turn.
|
||||
|
||||
A Promise resolves to a prepared conversation after options and sign-in are checked. In a browser, preparation opens the Puter sign-in prompt if needed. Preparation opens no realtime connection and requests no microphone access.
|
||||
To open a replacement while another connection remains healthy, set the optional `purpose=handover` query parameter. These attempts share a smaller per-credential budget, checked before the general connection-attempt budget. Initial connections and dropped-connection recovery use the URL without this parameter. The limits are listed in [rate limits and quotas](/rate-limits-and-quotas/).
|
||||
|
||||
The conversation exposes these properties and methods.
|
||||
## Text example
|
||||
|
||||
| Member | Behavior |
|
||||
| --- | --- |
|
||||
| `state` | `prepared`, `connecting`, `connected`, or `closed`. |
|
||||
| `model` | Resolved model name. |
|
||||
| `connect()` | Opens the connection and applies settings. Resolves after the provider acknowledges session configuration. Concurrent calls share one connection Promise, including bounded retries for transient setup failures. Calling it while connected opens no additional connection. During a reconnection, it resolves when the reconnection succeeds and rejects if the conversation closes instead. |
|
||||
| `configure(options)` | Updates the given session settings and resolves after the provider acknowledges this update. Settings it isn't given, including ones set through native events, are left alone. Accepts the factory options except `model`. One update can be pending at a time. Provider rules apply to changes such as switching a voice after audio has been generated. |
|
||||
| `sendText(text)` | Adds a user message and requests a response. Text must be nonempty and at most 8192 characters. |
|
||||
| `appendAudio(pcm)` | Appends an `Int16Array` containing PCM16, 24 kHz mono audio. A chunk contains at most 12000 samples. |
|
||||
| `commitAudio()` | Commits buffered audio and requests a response. Requires turn detection to be off, through `turnDetection: false` or a native session update. The provider requires at least 100 ms of buffered audio. |
|
||||
| `interrupt(position?)` | Stops built-in playback immediately and waits for cancellation and playback-history synchronization. A reply requested but not yet started is cancelled as soon as it starts. Custom players provide `{ itemId, contentIndex, playedMs }`. An idle call resolves immediately. Readiness failures reject the returned Promise with `session_not_ready` or `session_closed`. |
|
||||
| `send(event)` | Sends a native OpenAI JSON event. |
|
||||
| `on(type, handler)` | Registers a listener and returns an unsubscribe function. Use `'*'` to receive every native and convenience event. |
|
||||
| `off(type, handler)` | Removes a listener. |
|
||||
| `close()` | Closes the session, rejects pending operations, and releases SDK-owned capture and playback resources. Repeated calls have no additional effect. |
|
||||
|
||||
Attach listeners before connecting to receive initial session events. Closing during connection rejects the pending attempt.
|
||||
|
||||
If the connection drops because of network loss, a server restart or a provider error, the conversation reconnects on its own. Normal closes with code 1000 end the conversation. While it reconnects, `state` is `connecting`, a `reconnecting` event fires, and pending operations reject with `connection_lost`. The new session gets every setting the provider acknowledged, from the factory options, `configure()` and native `session.update` events. Then `ready` fires again with `reconnected: true`. Listeners, the microphone and the speaker carry over. Microphone audio captured while reconnecting is dropped.
|
||||
|
||||
The conversation also restores recent context. Before `ready` fires, it adds back up to 40 of the most recent conversation items, 48 KiB in total. Restored items are user text, user speech that has a transcript, assistant replies as text, and function calls with their outputs. User speech has a transcript only when input transcription is configured through native session settings. An assistant reply that was interrupted, or still playing when the connection dropped, is cut to what the user saw or heard. The cut is estimated from how much of the audio played, so it can be off by a few words. Images, speech without a transcript, deleted items, and replies still generating when the connection dropped are left out. Restored items get new item IDs, don't fire item events, and count as input tokens on the next response. Item IDs from before the reconnect don't work in later events. Restoration uses a contiguous suffix of restorable items. An oversized newest item leaves that suffix empty. Older items left out to fit the window fire a `context_trimmed` event with the count in `omittedItems`; this is routine and not an error. A provider refusal or a failure to send the restored items fires one `error` event with code `context_restore_failed` per restoration. In both cases the conversation stays connected. Items are preserved without truncating text, function arguments or function results.
|
||||
|
||||
When Puter knows ahead of time that the server a session runs on will restart, it sends a `puter.reconnect` event, which also reaches your listeners. Without that notice, a restart drops the connection and the conversation reconnects as above. Within a few seconds, the conversation opens a replacement session in the background while the current one keeps working. It switches once no reply is generating or playing, no user turn is being spoken or transcribed, no function call is waiting for its output, and nothing you sent is waiting on the provider. The switch goes through the same steps as a reconnect, and the `reconnecting` event has code 1012. If the replacement can't open yet, the conversation keeps the current session and tries again later. A refusal that retrying can't fix, such as `insufficient_funds`, stops the attempts. If the server closes the session first, the conversation switches to the replacement, or reconnects if none is open.
|
||||
|
||||
The conversation makes up to ten attempts over about a minute. In a browser that reports being offline, it first waits up to two minutes for the connection to come back. If every attempt fails, or the server refuses with an error such as `insufficient_funds`, the conversation closes. A closed conversation cannot reconnect. To start another session, prepare a new one.
|
||||
|
||||
Native event definitions are listed in the [OpenAI realtime reference](https://developers.openai.com/api/reference/resources/realtime/server-events). Native events retain their provider fields. Sending native events preserves direct control of the session. Puter refuses `conversation.item.retrieve` events and MCP tools (`"type": "mcp"`) in `session.update` and `response.create` events. Sending one fires an `error` event with code `invalid_event`, and the conversation closes with code 1008. Audio helpers expect the session to use PCM16 at 24 kHz.
|
||||
|
||||
## Errors and limits
|
||||
|
||||
Failures use objects containing `code` and `message`. Preparation can reject with `invalid_argument`, `model_not_found`, `auth_required`, `auth_canceled`, or `auth_failed`. Connection can reject with `subscription_required` or `insufficient_funds`, which also show the Puter upgrade prompt. Connection and asynchronous operations can reject with provider errors, `session_closed`, `connection_lost`, `operation_timeout`, or `operation_in_progress`. Sending before readiness, or while reconnecting, throws `session_not_ready`.
|
||||
|
||||
Invalid input throws `invalid_argument`, `invalid_event`, or `input_too_large`. A full SDK send queue throws `queue_full`. Media helpers report `unsupported_environment`, `permission_denied`, `media_error`, `media_timeout`, or `queue_full`. Runtime media errors and `context_restore_failed` arrive through the `error` event. Provider errors also arrive as native `error` events with a nested `error` object.
|
||||
|
||||
Each native event is capped at 64 KiB. The SDK bounds JSON traversal, outgoing queues, acknowledgment waits, microphone work, and playback. All numeric limits are listed on [rate limits and quotas](/rate-limits-and-quotas/).
|
||||
|
||||
## Convenience events
|
||||
|
||||
The conversation emits these events alongside native events.
|
||||
|
||||
| Event | Fields |
|
||||
| --- | --- |
|
||||
| `ready` | `model`, `provider`, and `reconnected: true` after a reconnection |
|
||||
| `reconnecting` | `code`, `reason` of the dropped connection. After a `puter.reconnect` event, `code` is 1012. |
|
||||
| `context_trimmed` | `omittedItems`, the number of restorable items left out of the restored context after a reconnection. Fires before `ready`. |
|
||||
| `text` | `delta`, `responseId` |
|
||||
| `transcript` | `role`, `text`, `final`. Assistant deltas use `final: false`. Completed assistant and user transcripts use `final: true`. User transcripts require transcription to be configured through native session settings. |
|
||||
| `audio` | `pcm`, `sampleRate`, `responseId`, `itemId`, `contentIndex`. The PCM chunk is an `Int16Array`. |
|
||||
| `interrupted` | `source` (`manual` or `speech`), `responseId` |
|
||||
| `turn.done` | `responseId`, native provider `usage`, `status` |
|
||||
| `close` | `code`, `reason` |
|
||||
|
||||
Each event includes its `type`. When the provider event leaves out an ID, `responseId` and `itemId` are empty strings and `contentIndex` is `0`. The `interrupted` event signals local interruption immediately. Its corresponding operation resolves after the provider acknowledges cancellation and any requested truncation. Late audio from a canceled response remains visible as native events and is excluded from convenience audio and built-in playback.
|
||||
|
||||
## Browser media
|
||||
|
||||
The optional microphone and speaker helpers require a browser with Web Audio support. Microphone capture also requires media permissions and a secure context. Start audio from a user action so the browser can allow playback.
|
||||
|
||||
| Member | Behavior |
|
||||
| --- | --- |
|
||||
| `microphone.start()` | Requests microphone access and streams PCM16, resampled to 24 kHz, in 20 ms chunks through an AudioWorklet. If the page or network falls behind, chunks are dropped rather than stopping capture. |
|
||||
| `microphone.mute()` | Disables capture tracks and stops forwarding captured chunks. |
|
||||
| `microphone.unmute()` | Enables capture tracks and forwarding. |
|
||||
| `microphone.stop()` | Stops capture tracks and releases capture resources. A `start()` still waiting on the permission prompt rejects with `session_closed`. |
|
||||
| `speaker.start({ bargeIn: true })` | Starts playback. Barge-in defaults to `true`. With barge-in enabled, provider speech-start events interrupt playback and synchronize played audio with conversation history. Starting the speaker requests no microphone access. |
|
||||
| `speaker.stop()` | Clears playback and releases its audio context. |
|
||||
|
||||
Both start methods require a connected session. Capture and playback are independent, so custom audio input can use the built-in speaker, and built-in capture can use custom playback.
|
||||
|
||||
## Examples
|
||||
|
||||
### Have a text conversation
|
||||
|
||||
A text conversation uses convenience methods for input and streamed output.
|
||||
Install the `ws` package and set `PUTER_TOKEN` to your Puter token. Run this example as a Node.js ES module:
|
||||
|
||||
```js
|
||||
const conversation = await puter.ai.realtime({
|
||||
output: ['text'],
|
||||
instructions: 'Keep replies short.',
|
||||
import WebSocket from 'ws';
|
||||
|
||||
const socket = new WebSocket(
|
||||
'wss://api.puter.com/puterai/openai/v1/realtime?model=gpt-realtime-2.1-mini',
|
||||
{ headers: { Authorization: `Bearer ${process.env.PUTER_TOKEN}` } },
|
||||
);
|
||||
const send = (event) => socket.send(JSON.stringify(event));
|
||||
|
||||
socket.on('message', (data) => {
|
||||
const event = JSON.parse(data.toString());
|
||||
|
||||
if (event.type === 'session.created') {
|
||||
send({
|
||||
type: 'session.update',
|
||||
session: {
|
||||
type: 'realtime',
|
||||
output_modalities: ['text'],
|
||||
instructions: 'Keep replies short.',
|
||||
},
|
||||
});
|
||||
}
|
||||
if (event.type === 'session.updated') {
|
||||
send({
|
||||
type: 'conversation.item.create',
|
||||
item: {
|
||||
type: 'message',
|
||||
role: 'user',
|
||||
content: [{ type: 'input_text', text: 'Hello!' }],
|
||||
},
|
||||
});
|
||||
send({ type: 'response.create' });
|
||||
}
|
||||
if (event.type === 'response.output_text.delta')
|
||||
process.stdout.write(event.delta);
|
||||
if (event.type === 'error')
|
||||
console.error(event.error);
|
||||
if (event.type === 'response.done')
|
||||
socket.close();
|
||||
});
|
||||
|
||||
conversation.on('text', ({ delta }) => console.log(delta));
|
||||
conversation.on('turn.done', () => conversation.close());
|
||||
conversation.on('error', (event) => console.error(event));
|
||||
|
||||
await conversation.connect();
|
||||
conversation.sendText('Say hello in three words.');
|
||||
socket.on('error', console.error);
|
||||
socket.on('close', (code, reason) => console.log(code, reason.toString()));
|
||||
```
|
||||
|
||||
### Have a voice conversation
|
||||
## Events, audio, and interruption
|
||||
|
||||
A voice conversation enables the microphone and speaker after connection.
|
||||
Each message contains one JSON object with a nonempty string `type` of at most 128 characters. Binary messages are rejected. Native events retain their provider fields. The endpoint doesn't deliver `rate_limits.updated`, which describes Puter's provider account rather than yours, and it removes provider organization IDs from error messages. The endpoint exposes the WebSocket event protocol. Your client manages capture, playback, acknowledgments, and timeouts.
|
||||
|
||||
```js
|
||||
const conversation = await puter.ai.realtime();
|
||||
conversation.on('transcript', ({ role, text }) => console.log(role, text));
|
||||
conversation.on('error', (event) => console.error(event));
|
||||
The endpoint refuses `conversation.item.retrieve` events and MCP tools (`"type": "mcp"`) in `session.update` and `response.create` events. A refused event isn't sent to the provider. The session gets an `invalid_event` error and closes with 1008.
|
||||
|
||||
await conversation.connect();
|
||||
await conversation.speaker.start();
|
||||
await conversation.microphone.start();
|
||||
PCM16 audio configured at 24 kHz mono is sent as base64 chunks in `input_audio_buffer.append` events. Output arrives in `response.output_audio.delta` events. With manual turn detection, commit buffered input with `input_audio_buffer.commit`, then request a reply with `response.create`.
|
||||
|
||||
// To interrupt a response and submit a replacement text turn:
|
||||
await conversation.interrupt();
|
||||
conversation.sendText('Actually, make it Wednesday.');
|
||||
To interrupt, stop local playback immediately and send `response.cancel` with the active `response_id`. If some generated audio was not played, send `conversation.item.truncate` with its `item_id`, `content_index`, and `audio_end_ms` set to the amount actually played. Wait for `response.done` and any requested `conversation.item.truncated` acknowledgment before submitting a replacement turn.
|
||||
|
||||
// When the user ends the conversation:
|
||||
conversation.close();
|
||||
Connection loss ends the session. Reconnecting creates a new conversation. Tool execution and automatic reconnection belong to your client.
|
||||
|
||||
## Server restarts
|
||||
|
||||
When Puter knows ahead of time that the server a session runs on will restart, it sends each open session this event, at most once a minute:
|
||||
|
||||
```json
|
||||
{
|
||||
"type": "puter.reconnect",
|
||||
"event_id": "event_puter_1767225600000",
|
||||
"reason": "server_restarting",
|
||||
"close_in_ms": 90000
|
||||
}
|
||||
```
|
||||
|
||||
The `reason` field is `server_restarting`. The `close_in_ms` field, when present, is about how long until the server closes the session itself. The session keeps working until then. Open a new connection after a short, randomized delay, and once it gets `session.created` and your client is idle, with no response generating and no user turn in progress, move to it and close the old one. A connection that reaches a server that is also restarting gets a `server_restarting` error and closes with 1012. In that case keep the old session and try again after a short, randomized delay. If the server closes the old session first, the close code is 1012, and your client reconnects the same way. A restart can also drop the connection without any notice, so treat an unexpected close the same way.
|
||||
|
||||
A new connection starts an empty conversation. To keep context, add earlier items back with `conversation.item.create` before you request a response. Event types that start with `puter.` come from Puter, not the provider.
|
||||
|
||||
## Errors, billing, and limits
|
||||
|
||||
API errors arrive as `{ "type": "error", "error": { "code": "...", "message": "..." } }`. Handle socket errors and close frames too. Invalid, missing, or revoked credentials use `invalid_api_key`. If Puter can't check a credential or the account's plan, the error is `internal_error` and the session closes with 1011, so try again after a short, randomized delay. Other relay codes include `permission_denied`, `model_not_found`, `insufficient_funds`, `subscription_required`, `rate_limit_exceeded`, `invalid_event`, `connection_timeout`, `provider_unavailable`, `upstream_error`, and `server_restarting`.
|
||||
|
||||
Policy failures generally close with 1008, oversized client messages with 1009, upstream or setup failures with 1011, server restarts with 1012, and temporary server overload with 1013. Reconnect after 1011, 1012, or 1013. Authentication and model failures can arrive after the WebSocket handshake succeeds.
|
||||
|
||||
The endpoint requires a paid Puter plan. Usage is charged after completed responses and input transcriptions. While a response generates, part of your balance is held for it, so a session opens only if your balance covers one response. If the provider connection closes before a response reports its usage, the response is charged the full amount held for it. Each account can open 20 sessions at once by default. Each JSON message you send is limited to 64 KiB, including reassembled fragments. Messages from the provider can be up to 4 MiB. Stream audio in small chunks. All message rates, queue caps, timeouts, and other bounds are published in [rate limits and quotas](/rate-limits-and-quotas/).
|
||||
|
||||
Input transcription holds a small amount of your balance per transcribed item, priced at the transcription model you select. Two items are reserved ahead of your audio and replenished as the provider commits them, so a session holds only its spare items plus the items still awaiting a transcript. Changing the transcription model reprices the spare items. If your balance can't cover another item, audio waits while earlier items settle; once none are left to settle, the session closes with `insufficient_funds`. Failed transcriptions, items without final usage, and audio whose commit the provider never acknowledges before the connection closes are each charged that model's fixed per-item amount. Unacknowledged audio is charged one item per started 160 seconds. With server turn detection, only detected speech counts, so silence is never charged. The amounts, timeout and audio limits are listed in [rate limits and quotas](/rate-limits-and-quotas/).
|
||||
|
||||
Provider-reported realtime models must have a known price. A missing model uses the last known model. An explicitly unpriced model closes the connection with `upstream_error`.
|
||||
|
||||
After recording usage, the connection can continue while settled credit is positive, including a fractional balance. Each new billable operation still needs its full reservation after accounting for other outstanding holds.
|
||||
@@ -6,7 +6,7 @@ platforms: [websites]
|
||||
|
||||
Initiates the sign in process for the user.
|
||||
|
||||
This will open a popup window with the appropriate authentication method. Puter automatically handles the authentication process and will resolve the promise when the user has signed in. Puter's own apps on puter.com subdomains show the sign-in in a frame over the page instead, and open the popup when the user picks a sign-in provider such as Google.
|
||||
This will open a popup window with the appropriate authentication method. Puter automatically handles the authentication process and will resolve the promise when the user has signed in.
|
||||
|
||||
It is important to note that all essential methods in Puter handle authentication automatically. This method is only necessary if you want to handle authentication manually, for example if you want to build your own custom authentication flow.
|
||||
|
||||
|
||||
@@ -64,7 +64,7 @@ Extra detail on why generation stopped (e.g. a refusal classification). Provider
|
||||
|
||||
#### `usageDetails` (Object)
|
||||
|
||||
A provider-neutral usage breakdown, present alongside `usage` on every result. `inputTokens` excludes cache reads/writes; `outputTokens` includes reasoning tokens. Fields: `inputTokens`, `outputTokens`, `cacheReadTokens`, `cacheWrite5mTokens`, `cacheWrite30mTokens`, `cacheWrite1hTokens`, `cacheWrite12hTokens`, `reasoningTokens`, `webSearchRequests`, `webFetchRequests`, `speed` (`"fast"` or `"standard"`), `serviceTier`, `serviceSpeed` (`"standard"`, `"fast"`, or `"ultrafast"` when requested), and `iterations` (a per-pass breakdown when the upstream ran several passes, e.g. compaction or an advisor sub-call). Each `cacheWrite*Tokens` field counts the tokens written to the cache with that lifetime: Claude and Moonshot write 5 minute and 1 hour entries, OpenAI writes 30 minute and 12 hour entries.
|
||||
A provider-neutral usage breakdown, present alongside `usage` on every result. `inputTokens` excludes cache reads/writes; `outputTokens` includes reasoning tokens. Fields: `inputTokens`, `outputTokens`, `cacheReadTokens`, `cacheWrite5mTokens`, `cacheWrite30mTokens`, `cacheWrite1hTokens`, `cacheWrite12hTokens`, `reasoningTokens`, `webSearchRequests`, `webFetchRequests`, `speed` (`"fast"` or `"standard"`), `serviceTier`, and `iterations` (a per-pass breakdown when the upstream ran several passes, e.g. compaction or an advisor sub-call). Each `cacheWrite*Tokens` field counts the tokens written to the cache with that lifetime: Claude and Moonshot write 5 minute and 1 hour entries, OpenAI writes 30 minute and 12 hour entries.
|
||||
|
||||
Prefer `usageDetails` over `usage` for anything beyond the raw billing totals. Claude's `usage.thinking_tokens` is informational: it's included in `output_tokens` and not billed separately — `usageDetails.reasoningTokens` carries the same count.
|
||||
|
||||
|
||||
@@ -102,7 +102,7 @@ Extra detail on why generation stopped (e.g. a refusal classification). Provider
|
||||
|
||||
#### `usageDetails` (Object)
|
||||
|
||||
A provider-neutral usage breakdown, present on the final `usage` chunk. `inputTokens` excludes cache reads/writes; `outputTokens` includes reasoning tokens. Fields: `inputTokens`, `outputTokens`, `cacheReadTokens`, `cacheWrite5mTokens`, `cacheWrite30mTokens`, `cacheWrite1hTokens`, `cacheWrite12hTokens`, `reasoningTokens`, `webSearchRequests`, `webFetchRequests`, `speed` (`"fast"` or `"standard"`), `serviceTier`, `serviceSpeed` (`"standard"`, `"fast"`, or `"ultrafast"` when requested), and `iterations` (a per-pass breakdown when the upstream ran several passes, e.g. compaction or an advisor sub-call). Each `cacheWrite*Tokens` field counts the tokens written to the cache with that lifetime: Claude and Moonshot write 5 minute and 1 hour entries, OpenAI writes 30 minute and 12 hour entries.
|
||||
A provider-neutral usage breakdown, present on the final `usage` chunk. `inputTokens` excludes cache reads/writes; `outputTokens` includes reasoning tokens. Fields: `inputTokens`, `outputTokens`, `cacheReadTokens`, `cacheWrite5mTokens`, `cacheWrite30mTokens`, `cacheWrite1hTokens`, `cacheWrite12hTokens`, `reasoningTokens`, `webSearchRequests`, `webFetchRequests`, `speed` (`"fast"` or `"standard"`), `serviceTier`, and `iterations` (a per-pass breakdown when the upstream ran several passes, e.g. compaction or an advisor sub-call). Each `cacheWrite*Tokens` field counts the tokens written to the cache with that lifetime: Claude and Moonshot write 5 minute and 1 hour entries, OpenAI writes 30 minute and 12 hour entries.
|
||||
|
||||
#### `message` (String)
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@ Opens a dialog where the user can send you, the app's developer, feedback about
|
||||
|
||||
The message is delivered by Puter: it is stored and emailed to the email address on your Puter account. The feedback never passes through your app's code, and the dialog tells the user what is shared with you: their username, plus their email address (as the email's reply-to, so you can respond) when their email is verified.
|
||||
|
||||
Inside Puter, the dialog is rendered by the desktop environment. On a website, a puter.com popup hosts the dialog (signing the user in first if needed). Puter's own apps on puter.com subdomains show it in a frame over the page instead, when the user is signed in to both.
|
||||
Inside Puter, the dialog is rendered by the desktop environment. On a website, a puter.com popup hosts the dialog (signing the user in first if needed).
|
||||
|
||||
**Feedback is opt-in.** Users can only send feedback if it's enabled for your app. Apps created in the Dev Center have feedback enabled at creation — you can turn it off with the "User Feedback" toggle in the app's settings. Apps created through `puter.apps.create` default to off; enable it by setting `feedbackEnabled`:
|
||||
|
||||
|
||||
@@ -49,12 +49,6 @@ const examples = [
|
||||
slug: 'ai-chatgpt',
|
||||
source: '/playground/examples/ai-chatgpt.html',
|
||||
},
|
||||
{
|
||||
title: 'Select Service Speed',
|
||||
description: 'Request faster AI service and inspect the speed that served the response.',
|
||||
slug: 'ai-chat-service-speed',
|
||||
source: '/playground/examples/ai-chat-service-speed.html',
|
||||
},
|
||||
{
|
||||
title: 'Image Analysis',
|
||||
description: 'Analyze images with AI using Puter.js GPT Vision API. Run and modify this code example instantly in your browser.',
|
||||
|
||||
@@ -1,13 +0,0 @@
|
||||
<html>
|
||||
<body>
|
||||
<script src="https://js.puter.com/v2/"></script>
|
||||
<script type="module">
|
||||
const response = await puter.ai.chat('Explain closures in one paragraph.', {
|
||||
model: 'gpt-6.1-sol',
|
||||
serviceSpeed: 'ultrafast',
|
||||
});
|
||||
puter.print(response.message.content);
|
||||
puter.print(response.usageDetails.serviceSpeed);
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -91,7 +91,7 @@ Gemini speech-to-text first counts the audio's tokens, which times out after 30
|
||||
|
||||
The OpenAI- and Anthropic-compatible endpoints (`/puterai/openai/v1/*`, `/puterai/anthropic/v1/messages`) require a paid plan; a free account gets `402 subscription_required`. The same models are available to every account through `puter.ai.*` and `/drivers/call`, and the model catalogue endpoints are open to everyone.
|
||||
|
||||
Realtime sessions ([`puter.ai.realtime()`](/AI/realtime/), `/puterai/openai/v1/realtime`) require a paid plan, like the other OpenAI-compatible endpoints, and are capped at 20 open at once per account. An account without a plan gets an `error` event with code `subscription_required`. A session over the cap gets `rate_limit_exceeded`. Both close with 1008.
|
||||
Realtime sessions ([`puter.ai.convo()`](/AI/convo/), `/puterai/openai/v1/realtime`) require a paid plan, like the other OpenAI-compatible endpoints, and are capped at 20 open at once per account. An account without a plan gets an `error` event with code `subscription_required`. A session over the cap gets `rate_limit_exceeded`. Both close with 1008.
|
||||
|
||||
| Realtime transport limit | Value | Behavior at the limit |
|
||||
| --- | --- | --- |
|
||||
@@ -131,7 +131,7 @@ Realtime sessions ([`puter.ai.realtime()`](/AI/realtime/), `/puterai/openai/v1/r
|
||||
|
||||
Send audio as a stream of small chunks. The message cap applies to text, configuration, tool output, and audio alike.
|
||||
|
||||
The [`puter.ai.realtime()`](/AI/realtime/) SDK also applies these limits before sending or retaining data.
|
||||
The [`puter.ai.convo()`](/AI/convo/) SDK also applies these limits before sending or retaining data.
|
||||
|
||||
| Conversation SDK limit | Value | Behavior at the limit |
|
||||
| --- | --- | --- |
|
||||
@@ -226,11 +226,6 @@ Image and video inputs to [`txt2img()`](/AI/txt2img/) and [`txt2vid()`](/AI/txt2
|
||||
|
||||
puter.js uploads a `Blob`, a `File` or a `data:` URI over 1 MiB to a temporary Puter file for the call. It counts against the user's storage until puter.js deletes it after the call.
|
||||
|
||||
|
||||
### Chat service speed catalogs
|
||||
|
||||
OpenRouter speed endpoint catalogs are cached for 15 minutes, with at most 256 model entries per backend process. A catalog fetch times out after 10 seconds and accepts at most 2 MiB. Failed fetches are remembered for 30 seconds. If no usable speed offering is available, the request uses standard service.
|
||||
|
||||
### Remote chat image inlining
|
||||
|
||||
For chat providers that require remote image URLs to be inlined (currently Moonshot):
|
||||
|
||||
@@ -124,17 +124,17 @@ let sidebar = [
|
||||
path: '/AI/speech2speech',
|
||||
},
|
||||
{
|
||||
title: '<code>realtime()</code>',
|
||||
page_title: '<code>puter.ai.realtime()</code>',
|
||||
title_tag: 'puter.ai.realtime()',
|
||||
title: '<code>convo()</code>',
|
||||
page_title: '<code>puter.ai.convo()</code>',
|
||||
title_tag: 'puter.ai.convo()',
|
||||
icon: '/assets/img/function.svg',
|
||||
source: '/AI/realtime.md',
|
||||
path: '/AI/realtime',
|
||||
source: '/AI/convo.md',
|
||||
path: '/AI/convo',
|
||||
},
|
||||
{
|
||||
title: 'Realtime WebSocket API (Beta)',
|
||||
source: '/AI/realtime-websocket.md',
|
||||
path: '/AI/realtime-websocket',
|
||||
source: '/AI/realtime.md',
|
||||
path: '/AI/realtime',
|
||||
},
|
||||
{
|
||||
title: '<code>listModels()</code>',
|
||||
|
||||
+44
-7
@@ -18,9 +18,7 @@
|
||||
*/
|
||||
|
||||
import download from './helpers/download.js';
|
||||
import ensureConfirmedEmail from './helpers/ensureConfirmedEmail.js';
|
||||
import item_icon from './helpers/itemIcon.js';
|
||||
import { atPath } from './helpers/pathElements.js';
|
||||
import socialLink from './helpers/socialLink.js';
|
||||
import update_mouse_position from './helpers/updateMousePosition.js';
|
||||
import path from './lib/path.js';
|
||||
@@ -33,9 +31,11 @@ import UIWindow from './UI/UIWindow.js';
|
||||
import UIWindowAppFeedback from './UI/UIWindowAppFeedback.js';
|
||||
import UIWindowAttachCustomDomain from './UI/UIWindowAttachCustomDomain.js';
|
||||
import UIWindowColorPicker from './UI/UIWindowColorPicker.js';
|
||||
import UIWindowEmailConfirmationRequired from './UI/UIWindowEmailConfirmationRequired.js';
|
||||
import UIWindowFontPicker from './UI/UIWindowFontPicker.js';
|
||||
import UIPermissionDialog from './UI/UIPermissionDialog.js';
|
||||
import UIEnablePushDialog from './UI/UIEnablePushDialog.js';
|
||||
import UIWindowSaveAccount from './UI/UIWindowSaveAccount.js';
|
||||
import UIAuthSignup from './UI/Auth/UIAuthSignup.js';
|
||||
import UINotification from './UI/UINotification.js';
|
||||
|
||||
@@ -235,12 +235,49 @@ const ipc_listener = async (event, handled) => {
|
||||
// requestEmailConfirmation
|
||||
//--------------------------------------------------------
|
||||
else if ( event.data.msg === 'requestEmailConfirmation' ) {
|
||||
// Above the app's window, which stays on top in the dashboard.
|
||||
const confirmed = await ensureConfirmedEmail(i18n('save_account_to_proceed'), { stay_on_top: true });
|
||||
// If the user has an email and it is confirmed, respond with success
|
||||
if ( window.user.email && window.user.email_confirmed ) {
|
||||
target_iframe.contentWindow.postMessage({
|
||||
original_msg_id: msg_id,
|
||||
msg: 'requestEmailConfirmationResponded',
|
||||
response: true,
|
||||
}, '*');
|
||||
}
|
||||
|
||||
// If the user is a temporary user, show the save account window
|
||||
if ( window.user.is_temp &&
|
||||
!await UIWindowSaveAccount({
|
||||
send_confirmation_code: true,
|
||||
message: 'Please create an account to proceed.',
|
||||
window_options: {
|
||||
backdrop: true,
|
||||
close_on_backdrop_click: false,
|
||||
},
|
||||
}) ) {
|
||||
target_iframe.contentWindow.postMessage({
|
||||
original_msg_id: msg_id,
|
||||
msg: 'requestEmailConfirmationResponded',
|
||||
response: false,
|
||||
}, '*');
|
||||
return;
|
||||
}
|
||||
else if ( !window.user.email_confirmed && !await UIWindowEmailConfirmationRequired() ) {
|
||||
target_iframe.contentWindow.postMessage({
|
||||
original_msg_id: msg_id,
|
||||
msg: 'requestEmailConfirmationResponded',
|
||||
response: false,
|
||||
}, '*');
|
||||
return;
|
||||
}
|
||||
|
||||
const email_confirm_resp = await UIWindowEmailConfirmationRequired({
|
||||
email: window.user.email,
|
||||
});
|
||||
|
||||
target_iframe.contentWindow.postMessage({
|
||||
original_msg_id: msg_id,
|
||||
msg: 'requestEmailConfirmationResponded',
|
||||
response: confirmed,
|
||||
response: email_confirm_resp,
|
||||
}, '*');
|
||||
}
|
||||
//--------------------------------------------------------
|
||||
@@ -1703,7 +1740,7 @@ const ipc_listener = async (event, handled) => {
|
||||
$(`.item[data-uid="${res.uid}"]`).removeItems();
|
||||
// now add new items
|
||||
UIItem({
|
||||
appendTo: atPath('.item-container', path.dirname(target_path)),
|
||||
appendTo: $(`.item-container[data-path="${html_encode(path.dirname(target_path))}" i]`),
|
||||
immutable: res.immutable || res.writable === false,
|
||||
associated_app_name: res.associated_app?.name,
|
||||
path: target_path,
|
||||
@@ -1717,7 +1754,7 @@ const ipc_listener = async (event, handled) => {
|
||||
suggested_apps: res.suggested_apps,
|
||||
});
|
||||
// sort each window
|
||||
atPath('.item-container', path.dirname(target_path)).each(function () {
|
||||
$(`.item-container[data-path="${html_encode(path.dirname(target_path))}" i]`).each(function () {
|
||||
window.sort_items(this, $(this).attr('data-sort_by'), $(this).attr('data-sort_order'));
|
||||
});
|
||||
$(el_filedialog_window).close();
|
||||
|
||||
@@ -1,146 +0,0 @@
|
||||
// @vitest-environment jsdom
|
||||
/*
|
||||
* Copyright (C) 2024-present Puter Technologies Inc.
|
||||
*
|
||||
* This file is part of Puter.
|
||||
*
|
||||
* Puter is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published
|
||||
* by the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import jQuery from './lib/jquery-3.6.1/jquery-3.6.1.min.js';
|
||||
|
||||
globalThis.def = globalThis.def ?? ((cls) => cls);
|
||||
globalThis.use = globalThis.use ?? (() => ({}));
|
||||
globalThis.$ = globalThis.jQuery = jQuery;
|
||||
globalThis.i18n = (key) => key;
|
||||
|
||||
const { stub, confirmEmail, saveAccount } = vi.hoisted(() => ({
|
||||
stub: () => ({ default: () => {} }),
|
||||
confirmEmail: vi.fn(),
|
||||
saveAccount: vi.fn(),
|
||||
}));
|
||||
vi.mock('./helpers/download.js', stub);
|
||||
vi.mock('./helpers/itemIcon.js', stub);
|
||||
vi.mock('./helpers/socialLink.js', stub);
|
||||
vi.mock('./helpers/updateMousePosition.js', stub);
|
||||
vi.mock('./UI/UIAlert.js', stub);
|
||||
vi.mock('./UI/UIContextMenu.js', stub);
|
||||
vi.mock('./UI/UIItem.js', stub);
|
||||
vi.mock('./UI/UIPopover.js', stub);
|
||||
vi.mock('./UI/UIPrompt.js', stub);
|
||||
vi.mock('./UI/UIWindow.js', stub);
|
||||
vi.mock('./UI/UIWindowAppFeedback.js', stub);
|
||||
vi.mock('./UI/UIWindowColorPicker.js', stub);
|
||||
vi.mock('./UI/UIWindowEmailConfirmationRequired.js', () => ({ default: confirmEmail }));
|
||||
vi.mock('./UI/UIWindowFontPicker.js', stub);
|
||||
vi.mock('./UI/UIPermissionDialog.js', stub);
|
||||
vi.mock('./UI/UIEnablePushDialog.js', stub);
|
||||
vi.mock('./UI/UIWindowSaveAccount.js', () => ({ default: saveAccount }));
|
||||
vi.mock('./UI/Auth/UIAuthSignup.js', stub);
|
||||
vi.mock('./UI/UINotification.js', stub);
|
||||
vi.mock('./helpers/godmodeTokens.js', () => ({ renewGodmodeToken: vi.fn() }));
|
||||
vi.mock('./helpers/watchItems.js', () => ({ addItemWatcher: vi.fn() }));
|
||||
vi.mock('./helpers/verification_gates.js', () => ({
|
||||
openVerificationGateWindow: vi.fn(),
|
||||
}));
|
||||
|
||||
let iframe;
|
||||
let posted;
|
||||
|
||||
beforeAll(async () => {
|
||||
window.when_puter_happens = [];
|
||||
window.appCallbackFunctions = {};
|
||||
await import('./IPC.js');
|
||||
globalThis.puter = { services: undefined, util: { rpc: { send: vi.fn() } } };
|
||||
for (const fn of window.when_puter_happens) await fn();
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
confirmEmail.mockReset();
|
||||
saveAccount.mockReset();
|
||||
document.body.innerHTML = '';
|
||||
const win = document.createElement('div');
|
||||
win.setAttribute('data-app_uuid', 'app-1');
|
||||
iframe = document.createElement('iframe');
|
||||
iframe.setAttribute('data-app', 'notes');
|
||||
win.append(iframe);
|
||||
document.body.append(win);
|
||||
posted = vi.spyOn(iframe.contentWindow, 'postMessage').mockImplementation(() => {});
|
||||
window.app_instance_ids = new Set(['inst-1']);
|
||||
window.iframe_for_app_instance = (id) => (id === 'inst-1' ? iframe : null);
|
||||
window.window_for_app_instance = () => win;
|
||||
window.is_auth = () => true;
|
||||
window.ipc_handlers = {};
|
||||
globalThis.services = { get: () => ({ get_by_uuid: () => ({ name: 'caller', uuid: 'inst-1' }) }) };
|
||||
});
|
||||
|
||||
const request = () =>
|
||||
window.dispatchEvent(
|
||||
new MessageEvent('message', {
|
||||
data: { appInstanceID: 'inst-1', env: 'app', msg: 'requestEmailConfirmation', uuid: 'cb-1' },
|
||||
source: iframe.contentWindow,
|
||||
origin: 'https://app.example',
|
||||
}),
|
||||
);
|
||||
|
||||
const settle = () => new Promise((r) => setTimeout(r, 20));
|
||||
|
||||
const replies = () => posted.mock.calls
|
||||
.map(([data]) => data)
|
||||
.filter((data) => data.msg === 'requestEmailConfirmationResponded');
|
||||
|
||||
describe('requestEmailConfirmation', () => {
|
||||
it('answers a confirmed email true once, without a dialog', async () => {
|
||||
window.user = { email: '[email protected]', email_confirmed: true };
|
||||
request();
|
||||
await settle();
|
||||
expect(replies()).toEqual([{ original_msg_id: 'cb-1', msg: 'requestEmailConfirmationResponded', response: true }]);
|
||||
expect(confirmEmail).not.toHaveBeenCalled();
|
||||
expect(saveAccount).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each([true, false])('shows an unconfirmed email one dialog and answers its result, %s', async (answer) => {
|
||||
window.user = { email: '[email protected]', email_confirmed: false };
|
||||
confirmEmail.mockResolvedValueOnce(answer);
|
||||
request();
|
||||
await settle();
|
||||
expect(confirmEmail).toHaveBeenCalledTimes(1);
|
||||
// The app's window stays on top in the dashboard, so the dialog has to as well.
|
||||
expect(confirmEmail).toHaveBeenCalledWith({ window_options: { stay_on_top: true } });
|
||||
expect(replies()).toEqual([{ original_msg_id: 'cb-1', msg: 'requestEmailConfirmationResponded', response: answer }]);
|
||||
});
|
||||
|
||||
it('answers false once when a temporary account isn\'t saved', async () => {
|
||||
window.user = { is_temp: true };
|
||||
saveAccount.mockResolvedValueOnce(false);
|
||||
request();
|
||||
await settle();
|
||||
expect(saveAccount).toHaveBeenCalledTimes(1);
|
||||
expect(saveAccount.mock.calls[0][0].window_options).toMatchObject({ stay_on_top: true });
|
||||
expect(confirmEmail).not.toHaveBeenCalled();
|
||||
expect(replies()).toEqual([{ original_msg_id: 'cb-1', msg: 'requestEmailConfirmationResponded', response: false }]);
|
||||
});
|
||||
|
||||
it('asks a temporary account that confirmed while saving for nothing more', async () => {
|
||||
window.user = { is_temp: true };
|
||||
saveAccount.mockImplementationOnce(async () => {
|
||||
window.user = { is_temp: false, email: '[email protected]', email_confirmed: true };
|
||||
return true;
|
||||
});
|
||||
request();
|
||||
await settle();
|
||||
expect(confirmEmail).not.toHaveBeenCalled();
|
||||
expect(replies()).toEqual([{ original_msg_id: 'cb-1', msg: 'requestEmailConfirmationResponded', response: true }]);
|
||||
});
|
||||
});
|
||||
@@ -84,8 +84,7 @@ export function pushAccountPickerScreen (flow) {
|
||||
const accounts = Array.isArray(window.logged_in_users) ? window.logged_in_users : [];
|
||||
|
||||
let h = '<div class="dashboard-dialog-body auth-body">';
|
||||
// Everyone here has signed in to Puter before; no need to explain it.
|
||||
h += authHeadHtml(flow, i18n('sign_in_with_puter', [], false), { openerNotice: false });
|
||||
h += authHeadHtml(flow, i18n('sign_in_with_puter', [], false));
|
||||
h += `<ul class="auth-accounts" aria-label="${i18n('sign_in_with_puter')}">`;
|
||||
h += accounts.map(accountRowHtml).join('');
|
||||
h += '</ul>';
|
||||
|
||||
@@ -104,8 +104,7 @@ export function pushLoginScreen (flow, options = {}) {
|
||||
const id = `auth-login-${window.uuidv4?.() ?? Date.now()}`;
|
||||
|
||||
let h = '<div class="dashboard-dialog-body auth-body">';
|
||||
// Logging in means already having a Puter account; no need to explain it.
|
||||
h += authHeadHtml(flow, i18n('log_in', [], false), { openerNotice: false });
|
||||
h += authHeadHtml(flow, i18n('log_in', [], false));
|
||||
h += '<form class="auth-form login-form" novalidate>';
|
||||
h += '<div class="dashboard-form-status" role="status" aria-live="polite"></div>';
|
||||
h += formFieldHtml({
|
||||
@@ -153,7 +152,6 @@ export function pushLoginScreen (flow, options = {}) {
|
||||
|
||||
renderProviderButtons($screen.find('.auth-provider-list'), {
|
||||
kind: 'login',
|
||||
flow,
|
||||
referrer: () => flow.options.referrer ?? window.referrerStr ?? window.openerOrigin,
|
||||
}).then((offered) => {
|
||||
if ( offered ) $screen.find('.auth-providers').prop('hidden', false);
|
||||
|
||||
@@ -60,14 +60,6 @@ afterEach(() => {
|
||||
});
|
||||
|
||||
describe('login screen', () => {
|
||||
it('leaves out the opener notice in a sign-in popup', () => {
|
||||
window.embedded_in_popup = true;
|
||||
window.openerOrigin = 'https://builder.puter.com';
|
||||
void UIAuthLogin({ reload_on_success: false });
|
||||
expect(screen().find('.auth-title')).toHaveLength(1);
|
||||
expect(screen().find('.auth-opener-notice')).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('asks for each field before sending anything', () => {
|
||||
const calls = captureAjax();
|
||||
void UIAuthLogin({ reload_on_success: false });
|
||||
@@ -225,29 +217,6 @@ describe('OIDC buttons on the login and signup screens', () => {
|
||||
window.location = original;
|
||||
expect(assign.mock.calls[0][0]).toBe('https://puter.test/auth/oidc/google/start?flow=login&referrer=ref');
|
||||
});
|
||||
|
||||
it('hands a framed sign-in to the popup instead of leaving for the provider', async () => {
|
||||
asPopup('msg_id=1');
|
||||
window.embedded_in_frame = true;
|
||||
window.tell_popup_frame = vi.fn();
|
||||
try {
|
||||
void UIAuthLogin();
|
||||
await vi.waitFor(() => expect($('.oidc-google-btn')).toHaveLength(1));
|
||||
const href = window.location.href;
|
||||
$('.oidc-google-btn').trigger('click');
|
||||
expect(window.tell_popup_frame.mock.calls).toEqual([
|
||||
['provider', { url: expect.stringContaining('https://puter.test/auth/oidc/google/start?flow=login') }],
|
||||
['unavailable'],
|
||||
]);
|
||||
const start = new URL(window.tell_popup_frame.mock.calls[0][1].url);
|
||||
expect(start.searchParams.get('embedded_in_popup')).toBe('true');
|
||||
expect(start.searchParams.get('msg_id')).toBe('1');
|
||||
expect(window.location.href).toBe(href);
|
||||
} finally {
|
||||
delete window.embedded_in_frame;
|
||||
delete window.tell_popup_frame;
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('second factor', () => {
|
||||
|
||||
@@ -36,13 +36,11 @@ import openAuthFlow, {
|
||||
submitButtonHtml,
|
||||
wireAuthHead,
|
||||
} from './authFlow.js';
|
||||
import { mayOfferProviders, renderProviderButtons } from './authProviders.js';
|
||||
import { renderProviderButtons } from './authProviders.js';
|
||||
import { pushLoginScreen } from './UIAuthLogin.js';
|
||||
|
||||
const SIGNUP_TIMEOUT_MS = 30000;
|
||||
const TURNSTILE_POLL_MS = 100;
|
||||
// How long the email form waits for the provider lookup before showing anyway.
|
||||
const PROVIDERS_WAIT_MS = 1500;
|
||||
|
||||
/**
|
||||
* @typedef {object} SignupScreenOptions
|
||||
@@ -111,8 +109,8 @@ const runVerificationGates = async (user, show_email, reload_on_success, page) =
|
||||
let email_verified = true;
|
||||
const emailGate = async () => {
|
||||
if ( ! show_email ) return;
|
||||
// No ✕: the signup card it replaced is already gone, so there's
|
||||
// nothing to go back to.
|
||||
// Its ✕ would close it without an answer, leaving the caller
|
||||
// waiting on a card that is already gone.
|
||||
email_verified = await UIWindowEmailConfirmationRequired({
|
||||
show_close_button: false,
|
||||
stay_on_top: true,
|
||||
@@ -189,9 +187,6 @@ export const signupRedirectUrl = (redirect_url) => {
|
||||
export function pushSignupScreen (flow, options = {}) {
|
||||
const id = `auth-signup-${window.uuidv4?.() ?? Date.now()}`;
|
||||
const turnstile_key = window.gui_params?.turnstileSiteKey;
|
||||
// The email form stays hidden until the providers are known, so it
|
||||
// doesn't show and then fold away behind "Sign up with email".
|
||||
let awaiting_providers = mayOfferProviders() && ! options.username && ! options.email;
|
||||
|
||||
let h = '<div class="dashboard-dialog-body auth-body">';
|
||||
h += authHeadHtml(flow, i18n('create_free_account', [], false));
|
||||
@@ -205,7 +200,7 @@ export function pushSignupScreen (flow, options = {}) {
|
||||
h += '<div class="signup-with-email-wrapper" hidden>';
|
||||
h += `<button type="button" class="dashboard-dialog-btn auth-provider-btn signup-with-email-btn">${i18n('sign_up_with_email')}</button>`;
|
||||
h += '</div>';
|
||||
h += `<form class="auth-form signup-form" novalidate${awaiting_providers ? ' hidden' : ''}>`;
|
||||
h += '<form class="auth-form signup-form" novalidate>';
|
||||
h += formFieldHtml({
|
||||
name: 'username',
|
||||
label: i18n('username'),
|
||||
@@ -312,32 +307,11 @@ export function pushSignupScreen (flow, options = {}) {
|
||||
})();
|
||||
}
|
||||
|
||||
// With focus on the card itself, nothing on the screen was focusable yet.
|
||||
const focusWasParked = () => document.activeElement === flow.$dialog.get(0);
|
||||
const stopAwaitingProviders = () => {
|
||||
const was_awaiting = awaiting_providers;
|
||||
awaiting_providers = false;
|
||||
clearTimeout(form_fallback);
|
||||
return was_awaiting;
|
||||
};
|
||||
const revealForm = () => {
|
||||
if ( ! stopAwaitingProviders() || flow.isClosed() ) return;
|
||||
showForm();
|
||||
if ( focusWasParked() ) flow.focus();
|
||||
};
|
||||
const form_fallback = awaiting_providers ? setTimeout(revealForm, PROVIDERS_WAIT_MS) : undefined;
|
||||
|
||||
renderProviderButtons($screen.find('.auth-provider-list'), {
|
||||
kind: 'signup',
|
||||
flow,
|
||||
referrer: () => flow.options.referrer ?? window.referrerStr,
|
||||
}).then((offered) => {
|
||||
if ( ! offered ) {
|
||||
revealForm();
|
||||
return;
|
||||
}
|
||||
stopAwaitingProviders();
|
||||
if ( flow.isClosed() ) return;
|
||||
if ( ! offered || flow.isClosed() ) return;
|
||||
offers_providers = true;
|
||||
$screen.find('.oidc-providers-wrapper').prop('hidden', false);
|
||||
if ( offered.signupOidcOnly ) {
|
||||
@@ -353,7 +327,7 @@ export function pushSignupScreen (flow, options = {}) {
|
||||
const had_focus = $form.get(0).contains(document.activeElement);
|
||||
$form.prop('hidden', true);
|
||||
$screen.find('.signup-with-email-wrapper').prop('hidden', false);
|
||||
if ( had_focus || focusWasParked() ) flow.focus();
|
||||
if ( had_focus ) flow.focus();
|
||||
});
|
||||
|
||||
$screen.find('.signup-with-email-btn').on('click', () => {
|
||||
|
||||
@@ -29,7 +29,6 @@ const { activeAuthFlow } = await import('./authFlow.js');
|
||||
const { default: UIAuthSignup, signupRedirectUrl } = await import('./UIAuthSignup.js');
|
||||
const { default: UIAuthAccountPicker } = await import('./UIAuthAccountPicker.js');
|
||||
const { default: UIAuthRecoverPassword } = await import('./UIAuthRecoverPassword.js');
|
||||
const { default: UIAuthLogin } = await import('./UIAuthLogin.js');
|
||||
|
||||
const providers = (body) => {
|
||||
globalThis.fetch = vi.fn(async () => reply(200, body));
|
||||
@@ -111,12 +110,7 @@ describe('signup when only OIDC signups are open', () => {
|
||||
globalThis.fetch = vi.fn(() => new Promise((resolve) => {
|
||||
answer = resolve;
|
||||
}));
|
||||
vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });
|
||||
void UIAuthSignup();
|
||||
// A slow lookup gives up the wait and shows the form.
|
||||
vi.advanceTimersByTime(1500);
|
||||
vi.useRealTimers();
|
||||
expect($('.signup-form').prop('hidden')).toBe(false);
|
||||
$('[name="username"]').val('started');
|
||||
answer(reply(200, { providers: ['google'] }));
|
||||
await vi.waitFor(() => expect($('.oidc-google-btn')).toHaveLength(1));
|
||||
@@ -124,50 +118,6 @@ describe('signup when only OIDC signups are open', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('signup while the providers are looked up', () => {
|
||||
/** Lets promise callbacks run, but no timer, so nothing a paint could show in between. */
|
||||
const settlePromises = async () => {
|
||||
for ( let i = 0; i < 10; i++ ) await Promise.resolve();
|
||||
};
|
||||
|
||||
it('keeps the email form hidden until the providers are known', async () => {
|
||||
let answer;
|
||||
globalThis.fetch = vi.fn(() => new Promise((resolve) => {
|
||||
answer = resolve;
|
||||
}));
|
||||
void UIAuthSignup();
|
||||
expect($('.signup-form').prop('hidden')).toBe(true);
|
||||
answer(reply(200, { providers: ['google'] }));
|
||||
await vi.waitFor(() => expect($('.oidc-google-btn')).toHaveLength(1));
|
||||
expect($('.signup-form').prop('hidden')).toBe(true);
|
||||
expect($('.signup-with-email-wrapper').prop('hidden')).toBe(false);
|
||||
});
|
||||
|
||||
it('shows the email form when no providers are offered', async () => {
|
||||
void UIAuthSignup();
|
||||
await vi.waitFor(() => expect($('.signup-form').prop('hidden')).toBe(false));
|
||||
expect($('.signup-with-email-wrapper').prop('hidden')).toBe(true);
|
||||
});
|
||||
|
||||
it('shows a prefilled email form straight away', () => {
|
||||
globalThis.fetch = vi.fn(() => new Promise(() => {}));
|
||||
void UIAuthSignup({ email: '[email protected]' });
|
||||
expect($('.signup-form').prop('hidden')).toBe(false);
|
||||
});
|
||||
|
||||
it('reuses the login screen\'s lookup, drawing the providers before any paint', async () => {
|
||||
providers({ providers: ['google'], signupOidcOnly: false });
|
||||
void UIAuthLogin({ reload_on_success: false });
|
||||
await vi.waitFor(() => expect(screen().find('.oidc-google-btn')).toHaveLength(1));
|
||||
screen().find('.auth-to-signup').trigger('click');
|
||||
await settlePromises();
|
||||
expect(screen().attr('data-screen')).toBe('signup');
|
||||
expect(screen().find('.oidc-google-btn')).toHaveLength(1);
|
||||
expect(screen().find('.signup-with-email-wrapper').prop('hidden')).toBe(false);
|
||||
expect(fetch).toHaveBeenCalledOnce();
|
||||
});
|
||||
});
|
||||
|
||||
describe('signup form', () => {
|
||||
it.each([
|
||||
[{}, 'username_required', 'username'],
|
||||
|
||||
@@ -191,15 +191,9 @@ export default function openAuthFlow ({ page = false, dismissable = ! page, clos
|
||||
/** @type {Array<AuthScreen & { $el: jQuery, el_return?: Element | null }>} */
|
||||
const stack = [];
|
||||
|
||||
// A frame's focus() calls do nothing until the framing page focuses it,
|
||||
// so the screen takes focus then, unless something already has it.
|
||||
const onFrameFocus = () => {
|
||||
if ( ! document.activeElement || document.activeElement === document.body ) flow.focus();
|
||||
};
|
||||
const teardown = () => {
|
||||
if ( torn_down ) return;
|
||||
torn_down = true;
|
||||
window.removeEventListener('focus', onFrameFocus);
|
||||
if ( active_flow === flow ) active_flow = null;
|
||||
// Screens waiting on the user (the second factor) hear they won't get an answer.
|
||||
while ( stack.length ) stack.pop().onLeave?.();
|
||||
@@ -358,14 +352,8 @@ export default function openAuthFlow ({ page = false, dismissable = ! page, clos
|
||||
$overlay.on('keydown keyup keypress', function (e) {
|
||||
e.stopPropagation();
|
||||
if ( e.type !== 'keydown' || e.key !== 'Escape' ) return;
|
||||
// An Escape that cancels an IME conversion is the IME's; jQuery's
|
||||
// event doesn't carry isComposing, the browser's does.
|
||||
if ( e.originalEvent?.isComposing || e.keyCode === 229 ) return;
|
||||
e.preventDefault();
|
||||
if ( busy ) return;
|
||||
if ( dismissable ) $dialog.find('.dashboard-dialog-close').trigger('click');
|
||||
// A framed sign-in's ✕ is the framing page's, which close() asks.
|
||||
else if ( window.embedded_in_frame ) window.close();
|
||||
if ( dismissable && ! busy ) $dialog.find('.dashboard-dialog-close').trigger('click');
|
||||
});
|
||||
// A press on the backdrop (or a page's background) would move focus to
|
||||
// the page, and with it the keys; it stays where it was.
|
||||
@@ -373,8 +361,6 @@ export default function openAuthFlow ({ page = false, dismissable = ! page, clos
|
||||
if ( e.target === this ) e.preventDefault();
|
||||
});
|
||||
|
||||
if ( window.embedded_in_frame ) window.addEventListener('focus', onFrameFocus);
|
||||
|
||||
active_flow = flow;
|
||||
return flow;
|
||||
}
|
||||
@@ -401,12 +387,9 @@ export const joinAuthFlow = () => {
|
||||
*
|
||||
* @param {AuthFlow} flow
|
||||
* @param {string} title Plain text.
|
||||
* @param {{ openerNotice?: boolean }} [opts] `openerNotice: false` leaves out
|
||||
* the line explaining that the site uses Puter, for screens shown to someone
|
||||
* who already has an account here.
|
||||
* @returns {string}
|
||||
*/
|
||||
export const authHeadHtml = (flow, title, { openerNotice = true } = {}) => {
|
||||
export const authHeadHtml = (flow, title) => {
|
||||
const opener = window.embedded_in_popup && isAttestedOrigin(window.openerOrigin) ? window.openerOrigin : '';
|
||||
let h = '<div class="auth-head">';
|
||||
h += authLogoHeader({
|
||||
@@ -416,7 +399,7 @@ export const authHeadHtml = (flow, title, { openerNotice = true } = {}) => {
|
||||
openerFallbackSrc: window.icons['website.svg'],
|
||||
});
|
||||
h += `<h1 class="auth-title">${html_encode(title)}</h1>`;
|
||||
if ( opener && openerNotice ) {
|
||||
if ( opener ) {
|
||||
h += `<p class="auth-opener-notice">${i18n('popup_opener_uses_puter', [new URL(opener).hostname])}</p>`;
|
||||
}
|
||||
h += '</div>';
|
||||
|
||||
@@ -75,56 +75,6 @@ describe('openAuthFlow', () => {
|
||||
expect(flow.isClosed()).toBe(false);
|
||||
});
|
||||
|
||||
it('lets Escape ask the framing page to close a framed sign-in, unless busy', async () => {
|
||||
window.embedded_in_frame = true;
|
||||
const close = vi.spyOn(window, 'close').mockImplementation(() => {});
|
||||
try {
|
||||
const flow = openAuthFlow({ page: true });
|
||||
flow.push({ name: 'a', html: '<input>' });
|
||||
await tick();
|
||||
flow.setBusy(true);
|
||||
key($('.auth-dialog input').get(0), 'Escape');
|
||||
expect(close).not.toHaveBeenCalled();
|
||||
flow.setBusy(false);
|
||||
// Escape that cancels an IME conversion is the IME's.
|
||||
$('.auth-dialog input').get(0).dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', isComposing: true, bubbles: true }));
|
||||
expect(close).not.toHaveBeenCalled();
|
||||
key($('.auth-dialog input').get(0), 'Escape');
|
||||
expect(close).toHaveBeenCalledTimes(1);
|
||||
flow.finish(false);
|
||||
} finally {
|
||||
close.mockRestore();
|
||||
delete window.embedded_in_frame;
|
||||
}
|
||||
});
|
||||
|
||||
it('focuses a framed screen once the framing page focuses the frame', async () => {
|
||||
window.embedded_in_frame = true;
|
||||
try {
|
||||
const flow = openAuthFlow({ page: true });
|
||||
flow.push({ name: 'a', html: '<input>' });
|
||||
// What a frame's focus() amounts to before the page focuses it.
|
||||
document.activeElement.blur();
|
||||
window.dispatchEvent(new FocusEvent('focus'));
|
||||
// jsdom lays nothing out, so the screen's fallback, the card, takes it.
|
||||
expect($('.auth-dialog').get(0).contains(document.activeElement)).toBe(true);
|
||||
|
||||
// Focus the user moved elsewhere stays there.
|
||||
const el_outside = $('<button class="outside">').appendTo('body').get(0);
|
||||
el_outside.focus();
|
||||
window.dispatchEvent(new FocusEvent('focus'));
|
||||
expect(document.activeElement).toBe(el_outside);
|
||||
el_outside.remove();
|
||||
|
||||
flow.finish(false);
|
||||
document.activeElement.blur();
|
||||
window.dispatchEvent(new FocusEvent('focus'));
|
||||
expect(document.activeElement).toBe(document.body);
|
||||
} finally {
|
||||
delete window.embedded_in_frame;
|
||||
}
|
||||
});
|
||||
|
||||
it('ignores the backdrop unless asked, so a stray click keeps typed credentials', async () => {
|
||||
const kept = openAuthFlow();
|
||||
kept.push({ name: 'a', html: '' });
|
||||
@@ -300,16 +250,6 @@ describe('authHeadHtml', () => {
|
||||
expect($dialog_head.find('a')).toHaveLength(0);
|
||||
expect($dialog_head.find('.auth-logo').attr('alt')).toBe('');
|
||||
});
|
||||
|
||||
it('explains the opener in a sign-in popup unless told not to', () => {
|
||||
window.embedded_in_popup = true;
|
||||
window.openerOrigin = 'https://builder.puter.com';
|
||||
const flow = openAuthFlow();
|
||||
const $notice = $(authHeadHtml(flow, 'Log in')).find('.auth-opener-notice');
|
||||
expect($notice).toHaveLength(1);
|
||||
expect($notice.text()).toContain('builder.puter.com');
|
||||
expect($(authHeadHtml(flow, 'Log in', { openerNotice: false })).find('.auth-opener-notice')).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('authFlowOptions', () => {
|
||||
|
||||
@@ -75,46 +75,27 @@ export const providerStartUrl = (provider, kind, referrer) => {
|
||||
return url;
|
||||
};
|
||||
|
||||
/** @type {WeakMap<import('./authFlow.js').AuthFlow, Promise<{ providers?: string[], signupOidcOnly?: boolean } | null>>} */
|
||||
const lookups = new WeakMap();
|
||||
|
||||
/**
|
||||
* The configured providers, looked up once per auth flow so moving between
|
||||
* its screens draws them straight away instead of after another round trip.
|
||||
*
|
||||
* @param {import('./authFlow.js').AuthFlow} flow
|
||||
*/
|
||||
const lookUpProviders = (flow) => {
|
||||
let lookup = lookups.get(flow);
|
||||
if ( ! lookup ) {
|
||||
lookup = (async () => {
|
||||
try {
|
||||
const res = await fetch(`${window.api_origin}/auth/oidc/providers`);
|
||||
return res.ok ? await res.json() : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
})();
|
||||
lookups.set(flow, lookup);
|
||||
}
|
||||
return lookup;
|
||||
};
|
||||
|
||||
/**
|
||||
* Fills `$list` with a button for each configured provider. A self-hosted
|
||||
* instance's own provider gets a generic button.
|
||||
* Fetches the configured providers and fills `$list` with a button for each.
|
||||
* A self-hosted instance's own provider gets a generic button.
|
||||
*
|
||||
* @param {jQuery} $list Where the buttons go.
|
||||
* @param {object} opts
|
||||
* @param {'login'|'signup'} opts.kind
|
||||
* @param {() => string | undefined} opts.referrer Read when a button is pressed.
|
||||
* @param {import('./authFlow.js').AuthFlow} opts.flow The flow showing `$list`.
|
||||
* @returns {Promise<{ providers: string[], signupOidcOnly: boolean } | null>}
|
||||
* Null when none are offered here or the lookup failed.
|
||||
*/
|
||||
export async function renderProviderButtons ($list, { kind, referrer, flow }) {
|
||||
export async function renderProviderButtons ($list, { kind, referrer }) {
|
||||
if ( ! mayOfferProviders() ) return null;
|
||||
const data = await lookUpProviders(flow);
|
||||
let data;
|
||||
try {
|
||||
const res = await fetch(`${window.api_origin}/auth/oidc/providers`);
|
||||
if ( ! res.ok ) return null;
|
||||
data = await res.json();
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
if ( ! Array.isArray(data?.providers) || ! data.providers.length ) return null;
|
||||
|
||||
const ordered = [
|
||||
@@ -134,15 +115,7 @@ export async function renderProviderButtons ($list, { kind, referrer, flow }) {
|
||||
}
|
||||
$list.html(h);
|
||||
$list.on('click', '.auth-provider-btn', function () {
|
||||
const url = providerStartUrl($(this).attr('data-provider'), kind, referrer());
|
||||
// A provider won't load in a frame, so the framing page opens this
|
||||
// in a popup instead. `unavailable` covers an SDK that can't.
|
||||
if ( window.embedded_in_frame ) {
|
||||
window.tell_popup_frame('provider', { url });
|
||||
window.tell_popup_frame('unavailable');
|
||||
return;
|
||||
}
|
||||
window.location.href = url;
|
||||
window.location.href = providerStartUrl($(this).attr('data-provider'), kind, referrer());
|
||||
});
|
||||
return { providers: ordered, signupOidcOnly: data.signupOidcOnly === true };
|
||||
}
|
||||
@@ -16,8 +16,6 @@ const requests = [];
|
||||
const guiRoot = fileURLToPath(new URL('../../../', import.meta.url));
|
||||
const sessionToken = 'app-browser-test-session';
|
||||
const sessionCookie = 'app-browser-test-cookie';
|
||||
const sessionUser = '0b1c9a52-3f0e-4c7a-9a65-2f6d1e8b7c40';
|
||||
const otherUser = '7d2e4f10-8a3b-4c5d-9e6f-0a1b2c3d4e5f';
|
||||
const appRows = Array.from({ length: 105 }, (_, i) => ({
|
||||
name: `app-${i}`, title: `App ${i}`, icon: null,
|
||||
}));
|
||||
@@ -64,25 +62,6 @@ beforeAll(async () => {
|
||||
if ( ! req.headers.cookie?.includes(`puter_auth_token=${sessionCookie}`) ) return res.sendStatus(401);
|
||||
res.json({ token: sessionToken });
|
||||
});
|
||||
// The GUI session's token and the tokens of apps signed in on a sibling subdomain.
|
||||
const whoamiByToken = {
|
||||
[sessionToken]: { uuid: sessionUser, username: 'session-user' },
|
||||
'app-token-session-user': { uuid: sessionUser, username: 'session-user' },
|
||||
'app-token-other-user': { uuid: otherUser, username: 'other-user' },
|
||||
};
|
||||
// The SDK on a sibling subdomain sends credentialed cross-origin requests.
|
||||
app.use(['/whoami', '/profile', '/rao'], (req, res, next) => {
|
||||
if ( req.headers.origin ) res.set('Access-Control-Allow-Origin', req.headers.origin);
|
||||
res.set('Access-Control-Allow-Credentials', 'true');
|
||||
res.set('Access-Control-Allow-Headers', 'Authorization, Content-Type');
|
||||
if ( req.method === 'OPTIONS' ) return res.sendStatus(204);
|
||||
next();
|
||||
});
|
||||
app.get('/whoami', (req, res) => {
|
||||
const user = whoamiByToken[req.headers.authorization?.replace(/^Bearer /, '')];
|
||||
if ( ! user ) return res.sendStatus(401);
|
||||
res.json(user);
|
||||
});
|
||||
app.get('/get-launch-apps', (_req, res) => res.json({ recommended: [{ name: 'removed', title: 'Removed' }] }));
|
||||
app.get('/cache/last-change-timestamp', (_req, res) => res.json({ timestamp: 0 }));
|
||||
app.post('/drivers/call', (req, res) => {
|
||||
@@ -102,15 +81,9 @@ beforeAll(async () => {
|
||||
app.get('/index', (_req, res) => res.send(`<title>App</title>
|
||||
<script>window.PUTER_ORIGIN = '${origin}'; window.PUTER_API_ORIGIN = '${origin}';</script>
|
||||
<script src="/sdk.js"></script>`));
|
||||
// The host page names its signed-in user as `?user=`, as puter.js does in the fragment.
|
||||
app.get('/host', (req, res) => res.send(`<!DOCTYPE html><html><body style="margin:0">
|
||||
<iframe title="More apps" src="${origin}/embed/apps${req.query.user ? `#user=${req.query.user}` : ''}" style="border:0;width:100vw;height:100vh"></iframe>
|
||||
app.get('/host', (_req, res) => res.send(`<!DOCTYPE html><html><body style="margin:0">
|
||||
<iframe title="More apps" src="${origin}/embed/apps" style="border:0;width:100vw;height:100vh"></iframe>
|
||||
</body></html>`));
|
||||
// An app on a sibling subdomain, signed in with puter.js, with the SDK's user menu.
|
||||
app.get('/menu-host', (_req, res) => res.send(`<!DOCTYPE html><html><head>
|
||||
<script>window.PUTER_ORIGIN = '${origin}'; window.PUTER_API_ORIGIN = '${origin}';</script>
|
||||
<script src="${origin}/sdk.js"></script></head>
|
||||
<body><header><puter-user-menu></puter-user-menu></header></body></html>`));
|
||||
app.get('/embed/apps', (_req, res) => {
|
||||
res.setHeader('Content-Security-Policy', `frame-ancestors 'self' http://*.puter.localhost:${port}`);
|
||||
res.send(`<!DOCTYPE html><html><head><meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
@@ -149,7 +122,7 @@ describe('embedded app browser', () => {
|
||||
page.on('pageerror', error => errors.push(error.message));
|
||||
requests.length = 0;
|
||||
try {
|
||||
const parentUrl = `http://spreadsheet.puter.localhost:${port}/host?user=${sessionUser}`;
|
||||
const parentUrl = `http://spreadsheet.puter.localhost:${port}/host`;
|
||||
await page.goto(parentUrl);
|
||||
const frame = page.frameLocator('iframe');
|
||||
await frame.locator('.myapps-group-tile').waitFor();
|
||||
@@ -209,7 +182,7 @@ describe('embedded app browser', () => {
|
||||
try {
|
||||
const page = await context.newPage();
|
||||
page.setDefaultTimeout(6000);
|
||||
await page.goto(`http://spreadsheet.puter.localhost:${port}/host?user=${sessionUser}`);
|
||||
await page.goto(`http://spreadsheet.puter.localhost:${port}/host`);
|
||||
const frame = page.frameLocator('iframe');
|
||||
await frame.locator('.myapps-group-tile').waitFor();
|
||||
expect(await frame.locator('[data-app-name="app-104"]').count()).toBe(1);
|
||||
@@ -227,7 +200,7 @@ describe('embedded app browser', () => {
|
||||
try {
|
||||
const page = await context.newPage();
|
||||
page.setDefaultTimeout(6000);
|
||||
await page.goto(`${origin}/embed/apps#user=${sessionUser}`);
|
||||
await page.goto(`${origin}/embed/apps`);
|
||||
await page.locator('.myapps-search').fill('App 104');
|
||||
const popupPromise = context.waitForEvent('page');
|
||||
await page.locator('.myapps-tile').click();
|
||||
@@ -302,7 +275,7 @@ describe('embedded app browser', () => {
|
||||
});
|
||||
const page = await context.newPage();
|
||||
page.setDefaultTimeout(6000);
|
||||
await page.goto(`${origin}/embed/apps#user=${sessionUser}`);
|
||||
await page.goto(`${origin}/embed/apps`);
|
||||
await page.locator('[data-app-name="notes"]').waitFor();
|
||||
} finally {
|
||||
guestApps = [];
|
||||
@@ -317,7 +290,7 @@ describe('embedded app browser', () => {
|
||||
const page = await context.newPage();
|
||||
page.setDefaultTimeout(6000);
|
||||
await page.route('**/get-gui-token', route => route.fulfill({ status }));
|
||||
await page.goto(`${origin}/embed/apps#user=${sessionUser}`);
|
||||
await page.goto(`${origin}/embed/apps`);
|
||||
await page.getByRole('status').waitFor();
|
||||
expect(await page.getByRole('status').textContent()).toContain('Apps are unavailable');
|
||||
expect(await page.locator('.myapps-tile').count()).toBe(0);
|
||||
@@ -327,351 +300,6 @@ describe('embedded app browser', () => {
|
||||
}
|
||||
});
|
||||
|
||||
describe('only shows the session to the host\'s own user', () => {
|
||||
const notes = () => ({ name: 'notes', title: 'Notes', uuid: 'uid-notes', index_url: `http://notes.puter.localhost:${port}/index`, icon: null });
|
||||
const signedInContext = () => browser.newContext({ storageState: {
|
||||
cookies: [], origins: [{ origin, localStorage: [{ name: 'auth_token_v2', value: sessionToken }] }],
|
||||
} });
|
||||
|
||||
it.each([
|
||||
['names no user', ''],
|
||||
['names another user', `?user=${otherUser}`],
|
||||
['names a malformed user', '?user=session-user'],
|
||||
])('shows the signed-out list when the host %s', async (_label, query) => {
|
||||
guestApps = [notes()];
|
||||
const context = await signedInContext();
|
||||
requests.length = 0;
|
||||
try {
|
||||
const page = await context.newPage();
|
||||
page.setDefaultTimeout(6000);
|
||||
await page.goto(`http://spreadsheet.puter.localhost:${port}/host${query}`);
|
||||
const frame = page.frameLocator('iframe');
|
||||
await frame.locator('[data-app-name="notes"]').waitFor();
|
||||
expect(await frame.locator('.myapps-tile').count()).toBe(1);
|
||||
expect(requests.some(req => ['/sdk.js', '/installedApps', '/drivers/call'].includes(req.path))).toBe(false);
|
||||
|
||||
const popupPromise = context.waitForEvent('page');
|
||||
await frame.locator('[data-app-name="notes"]').click();
|
||||
const popup = await popupPromise;
|
||||
await popup.waitForURL(/\/index\?/);
|
||||
expect(await popup.evaluate(() => window.opener)).toBeNull();
|
||||
expect(requests.some(req => ['/auth/get-user-app-token', '/rao'].includes(req.path))).toBe(false);
|
||||
} finally {
|
||||
guestApps = [];
|
||||
await context.close();
|
||||
}
|
||||
});
|
||||
|
||||
it('shows the signed-out list when the API refuses the stored session', async () => {
|
||||
guestApps = [notes()];
|
||||
const context = await browser.newContext({ storageState: {
|
||||
cookies: [], origins: [{ origin, localStorage: [{ name: 'auth_token_v2', value: 'revoked-session' }] }],
|
||||
} });
|
||||
try {
|
||||
const page = await context.newPage();
|
||||
page.setDefaultTimeout(6000);
|
||||
await page.goto(`${origin}/embed/apps#user=${sessionUser}`);
|
||||
await page.locator('[data-app-name="notes"]').waitFor();
|
||||
expect(await page.locator('.myapps-tile').count()).toBe(1);
|
||||
} finally {
|
||||
guestApps = [];
|
||||
await context.close();
|
||||
}
|
||||
});
|
||||
|
||||
it('shows a spinner while it checks the session', async () => {
|
||||
const context = await signedInContext();
|
||||
let respond;
|
||||
try {
|
||||
const page = await context.newPage();
|
||||
page.setDefaultTimeout(6000);
|
||||
await page.route('**/whoami', route => { respond = () => route.continue(); });
|
||||
await page.goto(`${origin}/embed/apps#user=${sessionUser}`);
|
||||
await expect.poll(() => typeof respond).toBe('function');
|
||||
const spinner = () => page.locator('#app-browser').evaluate(root => getComputedStyle(root, '::after').animationName);
|
||||
expect(await spinner()).not.toBe('none');
|
||||
await respond();
|
||||
await page.locator('[data-app-name="app-104"]').waitFor();
|
||||
expect(await spinner()).toBe('none');
|
||||
} finally {
|
||||
await context.close();
|
||||
}
|
||||
});
|
||||
|
||||
it('shows an unavailable state when the session check fails', async () => {
|
||||
guestApps = [notes()];
|
||||
const context = await signedInContext();
|
||||
try {
|
||||
const page = await context.newPage();
|
||||
page.setDefaultTimeout(6000);
|
||||
await page.route('**/whoami', route => route.fulfill({ status: 503 }));
|
||||
await page.goto(`${origin}/embed/apps#user=${sessionUser}`);
|
||||
await page.getByRole('status').waitFor();
|
||||
expect(await page.getByRole('status').textContent()).toContain('Apps are unavailable');
|
||||
expect(await page.locator('.myapps-tile').count()).toBe(0);
|
||||
} finally {
|
||||
guestApps = [];
|
||||
await context.close();
|
||||
}
|
||||
});
|
||||
|
||||
it('reloads for the user a changed fragment names', async () => {
|
||||
guestApps = [notes()];
|
||||
const context = await signedInContext();
|
||||
try {
|
||||
const page = await context.newPage();
|
||||
page.setDefaultTimeout(6000);
|
||||
await page.goto(`${origin}/embed/apps#user=${sessionUser}`);
|
||||
await page.locator('[data-app-name="app-104"]').waitFor();
|
||||
await page.evaluate(user => { window.location.hash = `user=${user}`; }, otherUser);
|
||||
await page.locator('[data-app-name="notes"]').waitFor();
|
||||
expect(await page.locator('[data-app-name="app-104"]').count()).toBe(0);
|
||||
} finally {
|
||||
guestApps = [];
|
||||
await context.close();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('opened from the SDK\'s user menu', () => {
|
||||
const menuContext = async (appToken, options = {}) => {
|
||||
guestApps = [{ name: 'notes', title: 'Notes', uuid: 'uid-notes', index_url: `http://notes.puter.localhost:${port}/index`, icon: null }];
|
||||
const host = `http://spreadsheet.puter.localhost:${port}`;
|
||||
return browser.newContext({ ...options, storageState: {
|
||||
cookies: [],
|
||||
origins: [
|
||||
{ origin, localStorage: [{ name: 'auth_token_v2', value: sessionToken }] },
|
||||
{ origin: host, localStorage: appToken ? [
|
||||
{ name: 'puter.auth.token.v2', value: appToken },
|
||||
{ name: 'puter.auth.token.origin.v2', value: origin },
|
||||
] : [] },
|
||||
],
|
||||
} });
|
||||
};
|
||||
|
||||
it('shows the user\'s apps to the same user and the signed-out list once the app signs out', async () => {
|
||||
const context = await menuContext('app-token-session-user');
|
||||
try {
|
||||
const page = await context.newPage();
|
||||
page.setDefaultTimeout(6000);
|
||||
const errors = [];
|
||||
page.on('pageerror', error => errors.push(error.message));
|
||||
await page.goto(`http://spreadsheet.puter.localhost:${port}/menu-host`);
|
||||
await page.locator('puter-user-menu .avatar').waitFor();
|
||||
expect(await page.locator('puter-user-menu .avatar').textContent()).toBe('S');
|
||||
|
||||
await page.locator('puter-user-menu .apps-button').click();
|
||||
const iframe = page.locator('puter-user-menu iframe');
|
||||
expect(await iframe.getAttribute('src')).toBe(`${origin}/embed/apps#user=${sessionUser}`);
|
||||
await page.frameLocator('puter-user-menu iframe').locator('[data-app-name="app-104"]').waitFor();
|
||||
|
||||
// The panel hangs under its button, inside the viewport.
|
||||
const button = await page.locator('puter-user-menu .apps-button').boundingBox();
|
||||
const panel = await page.locator('puter-user-menu .apps-panel').boundingBox();
|
||||
const viewport = page.viewportSize();
|
||||
expect(panel.y).toBeGreaterThan(button.y + button.height);
|
||||
expect(panel.x).toBeGreaterThanOrEqual(0);
|
||||
expect(panel.x + panel.width).toBeLessThanOrEqual(viewport.width);
|
||||
|
||||
// Closing keeps the embed, so reopening shows the same page.
|
||||
const embed = page.frames().find(frame => frame.url().startsWith(`${origin}/embed/apps`));
|
||||
await embed.evaluate(() => { window.keptAcrossOpens = true; });
|
||||
await page.locator('puter-user-menu .apps-close').click();
|
||||
await page.locator('puter-user-menu .apps-panel').waitFor({ state: 'hidden' });
|
||||
await page.locator('puter-user-menu .apps-button').click();
|
||||
expect(await embed.evaluate(() => window.keptAcrossOpens)).toBe(true);
|
||||
|
||||
await page.evaluate(() => puter.auth.signOut());
|
||||
await iframe.waitFor({ state: 'detached' });
|
||||
await page.locator('puter-user-menu .sign-in').waitFor();
|
||||
await page.locator('puter-user-menu .apps-button').click();
|
||||
expect(await iframe.getAttribute('src')).toBe(`${origin}/embed/apps`);
|
||||
const frame = page.frameLocator('puter-user-menu iframe');
|
||||
await frame.locator('[data-app-name="notes"]').waitFor();
|
||||
expect(await frame.locator('[data-app-name="app-104"]').count()).toBe(0);
|
||||
expect(errors).toEqual([]);
|
||||
} finally {
|
||||
guestApps = [];
|
||||
await context.close();
|
||||
}
|
||||
});
|
||||
|
||||
it('shows the signed-out list to an app signed in as another user', async () => {
|
||||
const context = await menuContext('app-token-other-user');
|
||||
try {
|
||||
const page = await context.newPage();
|
||||
page.setDefaultTimeout(6000);
|
||||
await page.goto(`http://spreadsheet.puter.localhost:${port}/menu-host`);
|
||||
await page.locator('puter-user-menu .avatar').waitFor();
|
||||
await page.locator('puter-user-menu .apps-button').click();
|
||||
const frame = page.frameLocator('puter-user-menu iframe');
|
||||
await frame.locator('[data-app-name="notes"]').waitFor();
|
||||
expect(await frame.locator('[data-app-name="app-104"]').count()).toBe(0);
|
||||
} finally {
|
||||
guestApps = [];
|
||||
await context.close();
|
||||
}
|
||||
});
|
||||
|
||||
it('closes the account menu when Tab leaves it', async () => {
|
||||
const context = await menuContext('app-token-session-user');
|
||||
try {
|
||||
const page = await context.newPage();
|
||||
page.setDefaultTimeout(6000);
|
||||
await page.goto(`http://spreadsheet.puter.localhost:${port}/menu-host`);
|
||||
await page.evaluate(() => document.body.insertAdjacentHTML('beforeend', '<button id="after">After</button>'));
|
||||
const menu = page.locator('puter-user-menu .menu');
|
||||
await page.locator('puter-user-menu .avatar').click();
|
||||
await menu.waitFor();
|
||||
await page.keyboard.press('Tab');
|
||||
await menu.waitFor({ state: 'hidden' });
|
||||
expect(await page.evaluate(() => document.activeElement.id)).toBe('after');
|
||||
|
||||
await page.locator('puter-user-menu .avatar').click();
|
||||
await menu.waitFor();
|
||||
await page.keyboard.press('Shift+Tab');
|
||||
await menu.waitFor({ state: 'hidden' });
|
||||
expect(await page.evaluate(() => document.activeElement.shadowRoot?.activeElement?.className)).toBe('apps-button');
|
||||
} finally {
|
||||
guestApps = [];
|
||||
await context.close();
|
||||
}
|
||||
});
|
||||
|
||||
it('moves focus to Sign in after signing out from the keyboard', async () => {
|
||||
const context = await menuContext('app-token-session-user');
|
||||
try {
|
||||
const page = await context.newPage();
|
||||
page.setDefaultTimeout(6000);
|
||||
await page.goto(`http://spreadsheet.puter.localhost:${port}/menu-host`);
|
||||
await page.locator('puter-user-menu .avatar').focus();
|
||||
await page.keyboard.press('Enter');
|
||||
await page.locator('puter-user-menu .menu').waitFor();
|
||||
await page.keyboard.press('Enter');
|
||||
await page.locator('puter-user-menu .sign-in').waitFor();
|
||||
await expect.poll(() => page.evaluate(() => document.activeElement.shadowRoot?.activeElement?.className)).toBe('sign-in');
|
||||
} finally {
|
||||
guestApps = [];
|
||||
await context.close();
|
||||
}
|
||||
});
|
||||
|
||||
it('shows the app browser in a theme the page forces', async () => {
|
||||
const context = await menuContext('app-token-session-user');
|
||||
try {
|
||||
const page = await context.newPage();
|
||||
page.setDefaultTimeout(6000);
|
||||
await page.emulateMedia({ colorScheme: 'light' });
|
||||
await page.goto(`http://spreadsheet.puter.localhost:${port}/menu-host`);
|
||||
const menu = page.locator('puter-user-menu');
|
||||
await menu.evaluate(el => el.setAttribute('theme', 'dark'));
|
||||
await page.locator('puter-user-menu .apps-button').click();
|
||||
const frame = page.frameLocator('puter-user-menu iframe');
|
||||
await frame.locator('[data-app-name="app-104"]').waitFor();
|
||||
const background = () => frame.locator('body').evaluate(body => getComputedStyle(body).backgroundColor);
|
||||
expect(await background()).toBe('rgb(30, 30, 30)');
|
||||
|
||||
await menu.evaluate(el => el.setAttribute('theme', 'light'));
|
||||
await expect.poll(background).toBe('rgb(255, 255, 255)');
|
||||
await frame.locator('[data-app-name="app-104"]').waitFor();
|
||||
expect(await page.locator('puter-user-menu .apps-panel').isVisible()).toBe(true);
|
||||
} finally {
|
||||
guestApps = [];
|
||||
await context.close();
|
||||
}
|
||||
});
|
||||
|
||||
it('leaves no hover shading on the Apps button once a tap closes it', async () => {
|
||||
const context = await menuContext('app-token-session-user', {
|
||||
viewport: { width: 390, height: 700 }, hasTouch: true, isMobile: true,
|
||||
});
|
||||
try {
|
||||
const page = await context.newPage();
|
||||
page.setDefaultTimeout(6000);
|
||||
await page.goto(`http://spreadsheet.puter.localhost:${port}/menu-host`);
|
||||
const button = page.locator('puter-user-menu .apps-button');
|
||||
await button.tap();
|
||||
await page.locator('puter-user-menu .apps-panel').waitFor();
|
||||
await button.tap();
|
||||
await page.locator('puter-user-menu .apps-panel').waitFor({ state: 'hidden' });
|
||||
expect(await button.evaluate(el => getComputedStyle(el).backgroundColor)).toBe('rgba(0, 0, 0, 0)');
|
||||
} finally {
|
||||
guestApps = [];
|
||||
await context.close();
|
||||
}
|
||||
});
|
||||
|
||||
it('shows Sign in pressed and the account hovered', async () => {
|
||||
const context = await menuContext(null);
|
||||
try {
|
||||
const page = await context.newPage();
|
||||
page.setDefaultTimeout(6000);
|
||||
await page.goto(`http://spreadsheet.puter.localhost:${port}/menu-host`);
|
||||
const signIn = page.locator('puter-user-menu .sign-in');
|
||||
await signIn.hover();
|
||||
await page.mouse.down();
|
||||
expect(await signIn.evaluate(el => getComputedStyle(el).color)).toBe('rgb(190, 222, 245)');
|
||||
await page.mouse.move(0, 0);
|
||||
await page.mouse.up();
|
||||
|
||||
await page.evaluate(() => puter.setAuthToken('app-token-session-user'));
|
||||
const avatar = page.locator('puter-user-menu .avatar');
|
||||
await avatar.waitFor();
|
||||
expect(await avatar.evaluate(el => getComputedStyle(el).boxShadow)).toBe('none');
|
||||
await avatar.hover();
|
||||
expect(await avatar.evaluate(el => getComputedStyle(el).boxShadow)).not.toBe('none');
|
||||
} finally {
|
||||
guestApps = [];
|
||||
await context.close();
|
||||
}
|
||||
});
|
||||
|
||||
it('shows the account before its picture arrives', async () => {
|
||||
const context = await menuContext('app-token-session-user');
|
||||
let respond;
|
||||
try {
|
||||
const page = await context.newPage();
|
||||
page.setDefaultTimeout(6000);
|
||||
await page.route('**/profile', route => { respond = () => route.fulfill({
|
||||
status: 200,
|
||||
headers: { 'Access-Control-Allow-Origin': `http://spreadsheet.puter.localhost:${port}`, 'Access-Control-Allow-Credentials': 'true' },
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify({ picture: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==' }),
|
||||
}); });
|
||||
await page.goto(`http://spreadsheet.puter.localhost:${port}/menu-host`);
|
||||
await page.locator('puter-user-menu .avatar').waitFor({ timeout: 2000 });
|
||||
expect(await page.locator('puter-user-menu .avatar').textContent()).toBe('S');
|
||||
expect(await page.locator('puter-user-menu .apps-button').isVisible()).toBe(true);
|
||||
await expect.poll(() => typeof respond).toBe('function');
|
||||
await respond();
|
||||
await page.locator('puter-user-menu .avatar img').waitFor();
|
||||
} finally {
|
||||
guestApps = [];
|
||||
await context.close();
|
||||
}
|
||||
});
|
||||
|
||||
it('names the user an app signs in as after loading', async () => {
|
||||
const context = await menuContext(null);
|
||||
try {
|
||||
const page = await context.newPage();
|
||||
page.setDefaultTimeout(6000);
|
||||
await page.goto(`http://spreadsheet.puter.localhost:${port}/menu-host`);
|
||||
await page.locator('puter-user-menu .sign-in').waitFor();
|
||||
// What `puter.auth.signIn()` does with the token its popup hands back.
|
||||
await page.evaluate(() => puter.setAuthToken('app-token-session-user'));
|
||||
await page.locator('puter-user-menu .avatar').waitFor();
|
||||
await expect.poll(() => page.locator('puter-user-menu .avatar').textContent()).toBe('S');
|
||||
await page.locator('puter-user-menu .apps-button').click();
|
||||
expect(await page.locator('puter-user-menu iframe').getAttribute('src')).toBe(`${origin}/embed/apps#user=${sessionUser}`);
|
||||
await page.frameLocator('puter-user-menu iframe').locator('[data-app-name="app-104"]').waitFor();
|
||||
} finally {
|
||||
guestApps = [];
|
||||
await context.close();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
it('shows an unavailable state if the SDK cannot load', async () => {
|
||||
const context = await browser.newContext({ storageState: {
|
||||
cookies: [], origins: [{ origin, localStorage: [{ name: 'auth_token_v2', value: sessionToken }] }],
|
||||
@@ -679,7 +307,7 @@ describe('embedded app browser', () => {
|
||||
try {
|
||||
const page = await context.newPage();
|
||||
await page.route('**/sdk.js', route => route.abort());
|
||||
await page.goto(`${origin}/embed/apps#user=${sessionUser}`);
|
||||
await page.goto(`${origin}/embed/apps`);
|
||||
await page.getByRole('status').waitFor();
|
||||
expect(await page.getByRole('status').textContent()).toContain('Apps are unavailable');
|
||||
} finally {
|
||||
|
||||
@@ -383,7 +383,7 @@ export function createAppBrowser ({ editable = true, onLaunch, actions = {}, gue
|
||||
function trapModalTab ($overlay) {
|
||||
$overlay.on('keydown', function (e) {
|
||||
if ( e.key !== 'Tab' ) return;
|
||||
const focusables = $overlay.find('button, textarea, input:not([type="hidden"]), select, a[href]').toArray()
|
||||
const focusables = $overlay.find('button, textarea').toArray()
|
||||
.filter(el => ! el.disabled && el.offsetParent !== null);
|
||||
if ( focusables.length === 0 ) return;
|
||||
const first = focusables[0];
|
||||
@@ -456,12 +456,6 @@ export function createAppBrowser ({ editable = true, onLaunch, actions = {}, gue
|
||||
// restores its position if it comes back.
|
||||
const deleteData = $overlay.find('.myapps-modal-delete-data').is(':checked');
|
||||
const removedIndex = self._apps.findIndex(a => a.name === appName);
|
||||
// Uninstalled from inside an open folder: where focus goes after.
|
||||
const fromGroupId = $el_window.find('.myapps-group-panel-grid .myapps-tile').toArray()
|
||||
.some(el => el.dataset.appName === appName) ? self._openGroupId : null;
|
||||
const groupMates = fromGroupId
|
||||
? (findGroupById(self._groups, fromGroupId)?.apps ?? []).filter(name => name !== appName)
|
||||
: [];
|
||||
const removedApp = removedIndex === -1 ? null : self._apps[removedIndex];
|
||||
// A running instance would be stranded: the tile is a headless
|
||||
// app's only switcher, so once it's gone a minimized window could
|
||||
@@ -469,9 +463,6 @@ export function createAppBrowser ({ editable = true, onLaunch, actions = {}, gue
|
||||
// also consumes the app's URL entry if it owns one).
|
||||
$(`.window[data-app="${html_encode(appName)}"]`).close();
|
||||
self._invalidateInFlightLoads();
|
||||
// Until the revoke lands the server still lists the app as
|
||||
// installed, so loads started meanwhile leave it out themselves.
|
||||
self._pendingUninstalls.add(appName);
|
||||
self._setAppRemoved(appName, true);
|
||||
close({ restoreFocus: false });
|
||||
|
||||
@@ -503,19 +494,9 @@ export function createAppBrowser ({ editable = true, onLaunch, actions = {}, gue
|
||||
self.renderApps($el_window, { preservePage: true, instant: true });
|
||||
// The confirm button left with the modal; keep a keyboard user on
|
||||
// the grid, at the slot the app vacated.
|
||||
if ( ! document.activeElement || document.activeElement === document.body ) {
|
||||
if ( slot !== -1 ) {
|
||||
const tiles = $el_window.find('.myapps-page .myapps-tile').toArray();
|
||||
tiles[Math.min(slot, tiles.length - 1)]?.focus({ preventScroll: true });
|
||||
} else if ( fromGroupId ) {
|
||||
// The folder may still be open, closed, or dissolved
|
||||
// into the one app left in it.
|
||||
const target = $el_window.find('.myapps-group-panel-grid .myapps-tile')[0]
|
||||
?? $el_window.find(`.myapps-group-tile[data-group-id="${CSS.escape(fromGroupId)}"]`)[0]
|
||||
?? $el_window.find('.myapps-page .myapps-tile').toArray()
|
||||
.find(el => groupMates.includes(el.dataset.appName));
|
||||
target?.focus({ preventScroll: true });
|
||||
}
|
||||
if ( slot !== -1 && (! document.activeElement || document.activeElement === document.body) ) {
|
||||
const tiles = $el_window.find('.myapps-page .myapps-tile').toArray();
|
||||
tiles[Math.min(slot, tiles.length - 1)]?.focus({ preventScroll: true });
|
||||
}
|
||||
// FLIP the survivors from their old boxes into the new layout.
|
||||
const moved = [];
|
||||
@@ -565,9 +546,6 @@ export function createAppBrowser ({ editable = true, onLaunch, actions = {}, gue
|
||||
puter.perms.revokeApp(appUid, '*', { deleteData }).then(async (result) => {
|
||||
// revokeApp resolves (never rejects) with `error` set on failure.
|
||||
if ( result?.error ) throw result;
|
||||
// Loads started before now may have read the app as installed.
|
||||
self._invalidateInFlightLoads();
|
||||
self._pendingUninstalls.delete(appName);
|
||||
// Clearing the grants is only half of it. An app the user already
|
||||
// opened holds a token that authenticates against a session row,
|
||||
// and that row outlives the permission rows — so without this an
|
||||
@@ -589,7 +567,6 @@ export function createAppBrowser ({ editable = true, onLaunch, actions = {}, gue
|
||||
}
|
||||
}).catch(async err => {
|
||||
console.error('Failed to uninstall app:', err);
|
||||
self._pendingUninstalls.delete(appName);
|
||||
await removalSettled;
|
||||
self._invalidateInFlightLoads();
|
||||
// The uninstall didn't happen — take the name back off the
|
||||
@@ -716,8 +693,6 @@ export function createAppBrowser ({ editable = true, onLaunch, actions = {}, gue
|
||||
$overlay.on('click', '.myapps-add-back', () => showPane('options'));
|
||||
$(document).on('keydown.add-app-modal', function (e) {
|
||||
if ( e.key !== 'Escape' ) return;
|
||||
// Escape while composing (CJK input) cancels the composition only.
|
||||
if ( e.originalEvent?.isComposing || e.keyCode === 229 ) return;
|
||||
// Escape steps back out of the form before it closes the modal, so a
|
||||
// half-written request survives a mis-hit key.
|
||||
if ( currentPane() === 'request' ) showPane('options');
|
||||
@@ -942,8 +917,6 @@ export function createAppBrowser ({ editable = true, onLaunch, actions = {}, gue
|
||||
// The last uninstalled-apps list a read returned, for loads whose read fails.
|
||||
_lastRemovedApps: null,
|
||||
_launchingApps: new Set(),
|
||||
// Apps whose uninstall was confirmed but hasn't landed on the server.
|
||||
_pendingUninstalls: new Set(),
|
||||
// A deep-link install mid-arrival ({ name, $el_window }) — its tile is
|
||||
// parked invisible until the intro's arrival beat (see
|
||||
// _spliceDeepLinkApp); and the session's landing-installed apps, kept
|
||||
@@ -1389,7 +1362,7 @@ export function createAppBrowser ({ editable = true, onLaunch, actions = {}, gue
|
||||
// account dialog, the touch action sheet, or the phone drawer.
|
||||
if ( $('.dashboard-notifications-panel.open, .dashboard-dialog-overlay, .context-menu-modal-backdrop, .dashboard-sidebar.open').length ) return;
|
||||
|
||||
const $panelGrid = $el_window.find('.myapps-group-overlay:not([inert]) .myapps-group-panel-grid');
|
||||
const $panelGrid = $el_window.find('.myapps-group-panel-grid');
|
||||
const pageTiles = ($panelGrid.length
|
||||
? $panelGrid
|
||||
: $el_window.find('.myapps-page').eq(self._page)
|
||||
@@ -2264,8 +2237,6 @@ export function createAppBrowser ({ editable = true, onLaunch, actions = {}, gue
|
||||
// removal below, so the tile a user reaches for the instant a folder
|
||||
// shuts would do nothing.
|
||||
$overlay.css('pointer-events', 'none');
|
||||
// Nor may its tiles take focus (Tab, the arrow keys) on the way out.
|
||||
$overlay.attr('inert', '');
|
||||
|
||||
// Back into the tile it grew out of; if that tile is gone (the folder
|
||||
// dissolved, the page flipped) the card simply recedes where it is.
|
||||
@@ -2363,32 +2334,14 @@ export function createAppBrowser ({ editable = true, onLaunch, actions = {}, gue
|
||||
// boundary so their stale snapshot can't replay over it (see
|
||||
// _resolveGroups).
|
||||
this._groupsSavedAtSeq = this._loadSeq || 0;
|
||||
this._persistLatest(APP_GROUPS_KV_KEY, JSON.stringify(groups), 'Failed to save app folders:');
|
||||
},
|
||||
|
||||
// Saves `value` under `key` one write at a time, sending only the
|
||||
// newest value once the write before it lands: two writes of a key in
|
||||
// flight together (an eject's save, then the drop's) can land in
|
||||
// either order, leaving the older layout stored.
|
||||
_persistLatest (key, value, failureMessage) {
|
||||
this._kvWrites ??= new Map();
|
||||
let slot = this._kvWrites.get(key);
|
||||
if ( ! slot ) this._kvWrites.set(key, slot = { pending: undefined, running: false });
|
||||
slot.pending = value;
|
||||
if ( slot.running ) return;
|
||||
slot.running = true;
|
||||
(async () => {
|
||||
while ( slot.pending !== undefined ) {
|
||||
const next = slot.pending;
|
||||
slot.pending = undefined;
|
||||
try {
|
||||
await puter.kv.set(key, next);
|
||||
} catch ( err ) {
|
||||
console.error(failureMessage, err);
|
||||
}
|
||||
try {
|
||||
const p = puter.kv.set(APP_GROUPS_KV_KEY, JSON.stringify(groups));
|
||||
if ( p && typeof p.catch === 'function' ) {
|
||||
p.catch(err => console.error('Failed to save app folders:', err));
|
||||
}
|
||||
slot.running = false;
|
||||
})();
|
||||
} catch ( err ) {
|
||||
console.error('Failed to save app folders:', err);
|
||||
}
|
||||
},
|
||||
|
||||
// -- Drag-to-reorder --
|
||||
@@ -3316,7 +3269,14 @@ export function createAppBrowser ({ editable = true, onLaunch, actions = {}, gue
|
||||
// boundary so their stale snapshot can't replay over it (see
|
||||
// _resolveOrderNames).
|
||||
this._orderSavedAtSeq = this._loadSeq || 0;
|
||||
this._persistLatest(APPS_ORDER_KV_KEY, JSON.stringify(names), 'Failed to save app order:');
|
||||
try {
|
||||
const p = puter.kv.set(APPS_ORDER_KV_KEY, JSON.stringify(names));
|
||||
if ( p && typeof p.catch === 'function' ) {
|
||||
p.catch(err => console.error('Failed to save app order:', err));
|
||||
}
|
||||
} catch ( err ) {
|
||||
console.error('Failed to save app order:', err);
|
||||
}
|
||||
},
|
||||
|
||||
loadApps ($el_window) {
|
||||
@@ -3484,7 +3444,7 @@ export function createAppBrowser ({ editable = true, onLaunch, actions = {}, gue
|
||||
|
||||
// Append installed apps that aren't already in the list
|
||||
for ( const app of installedApps ) {
|
||||
if ( seen.has(app.name) || this._pendingUninstalls.has(app.name) ) continue;
|
||||
if ( seen.has(app.name) ) continue;
|
||||
seen.add(app.name);
|
||||
merged.push(app);
|
||||
}
|
||||
|
||||
@@ -68,86 +68,6 @@ async function mount (options = {}) {
|
||||
}
|
||||
|
||||
describe('shared app browser', () => {
|
||||
it('keeps an app off the grid while its uninstall is still on its way to the server', async () => {
|
||||
const actions = { showAlert: vi.fn(), revokeAppSessions: vi.fn(async () => {}) };
|
||||
await mount({ editable: true, actions });
|
||||
let finishRevoke;
|
||||
puter.perms = { revokeApp: vi.fn(() => new Promise(resolve => { finishRevoke = resolve; })) };
|
||||
// The app's windows are closed first; the test has none.
|
||||
$.fn.close ??= function () { return this; };
|
||||
window.matchMedia = () => ({ matches: true });
|
||||
browser._setReorderMode($root, true);
|
||||
$('.myapps-tile[data-app-name="editor"] .myapps-tile-remove').trigger('click');
|
||||
$('.myapps-modal-confirm').trigger('click');
|
||||
expect(puter.perms.revokeApp).toHaveBeenCalled();
|
||||
|
||||
// A refresh before the revoke lands still lists the app as installed.
|
||||
await browser.loadApps($root);
|
||||
expect(browser._apps.map(app => app.name)).not.toContain('editor');
|
||||
|
||||
installed = installed.filter(app => app.name !== 'editor');
|
||||
finishRevoke({});
|
||||
await vi.waitFor(() => expect(browser._pendingUninstalls.size).toBe(0));
|
||||
await browser.loadApps($root);
|
||||
expect(browser._apps.map(app => app.name)).not.toContain('editor');
|
||||
expect(actions.showAlert).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('saves one layout at a time, sending only the newest once the last write lands', async () => {
|
||||
await mount({ editable: true });
|
||||
const writes = [];
|
||||
puter.kv.set = vi.fn((key, value) => new Promise(resolve => writes.push({ key, value, resolve })));
|
||||
const orderWrites = () => writes.filter(w => w.key === APPS_ORDER_KV_KEY);
|
||||
|
||||
browser._apps = [{ name: 'a' }, { name: 'b' }];
|
||||
browser.saveOrder();
|
||||
browser._apps = [{ name: 'b' }, { name: 'a' }];
|
||||
browser.saveOrder();
|
||||
browser._apps = [{ name: 'a' }, { name: 'b' }, { name: 'c' }];
|
||||
browser.saveOrder();
|
||||
expect(orderWrites()).toHaveLength(1);
|
||||
|
||||
orderWrites()[0].resolve();
|
||||
await vi.waitFor(() => expect(orderWrites()).toHaveLength(2));
|
||||
expect(orderWrites()[1].value).toBe(JSON.stringify(browser._savedOrderNames));
|
||||
expect(orderWrites()[1].value).not.toBe(orderWrites()[0].value);
|
||||
orderWrites()[1].resolve();
|
||||
await new Promise(resolve => setTimeout(resolve, 0));
|
||||
expect(orderWrites()).toHaveLength(2);
|
||||
});
|
||||
|
||||
it('leaves the app request form open on an Escape that ends an IME composition', async () => {
|
||||
await mount({ editable: true });
|
||||
$('.myapps-add-tile').trigger('click');
|
||||
$('.myapps-add-option[data-add-option="request"]').trigger('click');
|
||||
const pane = () => $('.myapps-add-pane:not([hidden])').attr('data-pane');
|
||||
expect(pane()).toBe('request');
|
||||
|
||||
$('.myapps-add-message')[0].dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', isComposing: true, bubbles: true }));
|
||||
expect(pane()).toBe('request');
|
||||
$('.myapps-add-message')[0].dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true }));
|
||||
expect(pane()).toBe('options');
|
||||
$(document).off('keydown.add-app-modal');
|
||||
});
|
||||
|
||||
it('lets Tab reach the delete-data option in the Uninstall dialog', async () => {
|
||||
// jsdom lays nothing out; the focus trap skips elements with no offsetParent.
|
||||
vi.spyOn(HTMLElement.prototype, 'offsetParent', 'get').mockReturnValue(document.body);
|
||||
await mount({ editable: true });
|
||||
browser._setReorderMode($root, true);
|
||||
$('.myapps-tile[data-app-name="editor"] .myapps-tile-remove').trigger('click');
|
||||
const $overlay = $('.myapps-modal-overlay');
|
||||
expect(document.activeElement.classList.contains('myapps-modal-cancel')).toBe(true);
|
||||
|
||||
// Tab from the last control wraps to the first, the checkbox.
|
||||
$overlay.find('.myapps-modal-confirm')[0].focus();
|
||||
$overlay.trigger($.Event('keydown', { key: 'Tab', shiftKey: false }));
|
||||
expect(document.activeElement.classList.contains('myapps-modal-delete-data')).toBe(true);
|
||||
// Shift+Tab from it wraps back to the last.
|
||||
$overlay.trigger($.Event('keydown', { key: 'Tab', shiftKey: true }));
|
||||
expect(document.activeElement.classList.contains('myapps-modal-confirm')).toBe(true);
|
||||
});
|
||||
|
||||
it('uses saved order, folders, and removed recommendations in read-only mode', async () => {
|
||||
await mount();
|
||||
expect(browser._apps.map(app => app.name)).toEqual(['notes', 'sheet', 'editor']);
|
||||
|
||||
@@ -68,7 +68,7 @@ describe('TabApps.beginDeepLinkLaunch', () => {
|
||||
});
|
||||
|
||||
describe('TabApps cancelling a drag out of a folder', () => {
|
||||
it('puts the folder and the order back as they were', async () => {
|
||||
it('puts the folder and the order back as they were', () => {
|
||||
document.body.innerHTML = '<div class="window"><div class="dashboard-section-apps active"><div class="myapps-container"><div class="myapps-page"><div class="myapps-tile" data-app-name="a"></div></div></div></div></div>';
|
||||
window.puter = { kv: { set: vi.fn(async () => {}), get: vi.fn(async () => null) } };
|
||||
TabApps._groupsLoaded = true;
|
||||
@@ -91,9 +91,7 @@ describe('TabApps cancelling a drag out of a folder', () => {
|
||||
TabApps._endDrag(false);
|
||||
|
||||
expect(TabApps._groups).toEqual([{ id: 'g1', name: 'Work', apps: ['a', 'b'] }]);
|
||||
// The restore is written once the eject's own write lands.
|
||||
const lastSaved = key => JSON.parse(window.puter.kv.set.mock.calls.filter(([k]) => k === key).at(-1)[1]);
|
||||
await vi.waitFor(() => expect(lastSaved('dashboard_app_groups')).toEqual([{ id: 'g1', name: 'Work', apps: ['a', 'b'] }]));
|
||||
expect(JSON.parse(window.puter.kv.set.mock.calls.at(-2)[1])).toEqual([{ id: 'g1', name: 'Work', apps: ['a', 'b'] }]);
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -37,7 +37,6 @@ import UIItemPropertiesModal from './UIItemPropertiesModal.js';
|
||||
import UIShareModal from './UIShareModal.js';
|
||||
import { openPublishWebsiteDialog, openPublishWorkerDialog } from './UIPublishDialogs.js';
|
||||
import { dedupedName } from '../../helpers/dedupedName.js';
|
||||
import { runLimited } from '../../helpers/runLimited.js';
|
||||
import { compareEntries, compareNames } from './sortEntries.js';
|
||||
import { middleTruncate } from './middleTruncate.js';
|
||||
import { resolveTypedPath } from './typedPath.js';
|
||||
@@ -55,14 +54,6 @@ import { paintAvatars } from '../../helpers/profilePictures.js';
|
||||
|
||||
const { html_encode, SelectionArea } = window;
|
||||
|
||||
// Permanent deletes in flight at once: a browser's connections to one host.
|
||||
const DELETE_CONCURRENCY = 6;
|
||||
|
||||
// The "New" menu's stand-ins for window.create_file, one per create in
|
||||
// flight (newest last), and the function they stand in for.
|
||||
const createFileInterceptors = [];
|
||||
let realCreateFile = null;
|
||||
|
||||
/**
|
||||
* `p` with the folder `from` (itself, or anything under it) moved to `to`;
|
||||
* any other path, or a non-string, comes back as it was.
|
||||
@@ -1251,9 +1242,8 @@ const TabFiles = {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Arrow keys, Home/End and PageUp/PageDown - Navigate items. Not
|
||||
// with Alt or Cmd: those are the browser's (Alt+Left is Back).
|
||||
if ( e.which >= 33 && e.which <= 40 && ! e.altKey && ! e.metaKey ) {
|
||||
// Arrow keys, Home/End and PageUp/PageDown - Navigate items
|
||||
if ( e.which >= 33 && e.which <= 40 ) {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
|
||||
@@ -1917,9 +1907,9 @@ const TabFiles = {
|
||||
if ( confirmed !== 'delete' ) return;
|
||||
// The phone selection bar acts on rows that are going away.
|
||||
this.$el_window.find('.files-selection-actions').removeClass('visible');
|
||||
// A few at a time rather than one after another: a few hundred items
|
||||
// took a round trip each. delete_item reports its own failures.
|
||||
await runLimited(list, DELETE_CONCURRENCY, row => window.delete_item(row));
|
||||
for ( const row of list ) {
|
||||
await window.delete_item(row);
|
||||
}
|
||||
await window.refresh_trash_state();
|
||||
},
|
||||
|
||||
@@ -2393,19 +2383,11 @@ const TabFiles = {
|
||||
};
|
||||
|
||||
if ( isList ) {
|
||||
// The name's padding (8px a side) takes room from a set width. An
|
||||
// auto-width column fills the row, so its room is read off the
|
||||
// name's wrapper, less the wrapper's padding: all reads before any
|
||||
// write, so the writes don't force a layout each.
|
||||
const paddingOf = s => (parseFloat(s.paddingLeft) || 0) + (parseFloat(s.paddingRight) || 0);
|
||||
const padding = paddingOf(style);
|
||||
const wrapperPadding = nameWidth ? 0 : paddingOf(getComputedStyle(names[0].parentElement));
|
||||
const rooms = nameWidth ? null : names.map(el => el.parentElement.clientWidth - wrapperPadding);
|
||||
names.forEach((el, i) => {
|
||||
const room = (nameWidth || rooms[i]) - padding;
|
||||
// A listing that isn't laid out yet (hidden tab) has no room to fit to.
|
||||
write(el, room > 0 ? truncateFilenameToWidth(fullNameOf(el), room, font) : fullNameOf(el));
|
||||
});
|
||||
for ( const el of names ) {
|
||||
// 8px padding on each side; an auto-width column shows the
|
||||
// full name, clipped by CSS.
|
||||
write(el, nameWidth ? truncateFilenameToWidth(fullNameOf(el), nameWidth - 16, font) : fullNameOf(el));
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -3330,9 +3312,6 @@ const TabFiles = {
|
||||
// the directories sidebar is hidden — Home carries a row for each.
|
||||
this.renderPlaceRows();
|
||||
|
||||
// Something that ran while the listing loaded (a restore finishing,
|
||||
// a failed mkdir) may have found the pane empty and said so.
|
||||
$files.find('.files-empty-notice').remove();
|
||||
if ( directoryContents.length === 0 ) {
|
||||
this.renderEmptyPlaceholderIfNeeded();
|
||||
this.updateFooterStats();
|
||||
@@ -4454,14 +4433,11 @@ const TabFiles = {
|
||||
const metadata = metadataStr ? JSON.parse(metadataStr) : {};
|
||||
|
||||
// Only a direct child of Trash carries restore metadata.
|
||||
const name = $(el_item).attr('data-name') || '';
|
||||
if ( path.dirname($(el_item).attr('data-path') || '') !== window.trash_path ) {
|
||||
throw new Error(i18n('restore_only_trash_items', { name }, false));
|
||||
throw new Error('Cannot restore: only top-level Trash items can be restored');
|
||||
}
|
||||
// An item an app or the API moved into the Trash has no record of
|
||||
// where it came from.
|
||||
if ( ! metadata.original_path ) {
|
||||
throw new Error(i18n('restore_location_unknown', { name }, false));
|
||||
throw new Error('Cannot restore: original path not found in metadata');
|
||||
}
|
||||
|
||||
const destPath = path.dirname(metadata.original_path);
|
||||
@@ -5394,14 +5370,10 @@ const TabFiles = {
|
||||
return async () => {
|
||||
$('.context-menu').remove();
|
||||
|
||||
// Where the user was, so an upload that lands after
|
||||
// they've moved on neither pulls them back nor draws
|
||||
// its row into another folder's listing.
|
||||
const pathAtClick = _this.currentPath;
|
||||
|
||||
// Temporarily intercept create_file to capture the upload promise
|
||||
let uploadPromise = null;
|
||||
const createFile = (options) => {
|
||||
const origCreateFile = window.create_file;
|
||||
window.create_file = (options) => {
|
||||
// Counted from here, not from the click: Web Link
|
||||
// waits on a prompt first, and other items added
|
||||
// to the folder meanwhile must still show up.
|
||||
@@ -5412,12 +5384,6 @@ const TabFiles = {
|
||||
// a caller that awaits this.
|
||||
return uploadPromise.catch(() => undefined);
|
||||
};
|
||||
// Creates can overlap. Each one's interceptor stays
|
||||
// installed until it finishes, the newest on top, and
|
||||
// the real create_file comes back once none is left.
|
||||
if ( createFileInterceptors.length === 0 ) realCreateFile = window.create_file;
|
||||
createFileInterceptors.push(createFile);
|
||||
window.create_file = createFile;
|
||||
|
||||
try {
|
||||
await originalOnClick();
|
||||
@@ -5435,10 +5401,7 @@ const TabFiles = {
|
||||
operation: 'create_file',
|
||||
data: $('<div>').attr({ 'data-uid': result.uid, 'data-path': result.path }),
|
||||
});
|
||||
// Not mid-way to another folder (currentPath
|
||||
// only moves once its listing arrives).
|
||||
const settled = ! _this.loadingFolder;
|
||||
if ( settled && targetPath === _this.currentPath ) {
|
||||
if ( targetPath === _this.currentPath ) {
|
||||
// Remove empty-directory placeholder if present
|
||||
_this.$el_window.find('.files-tab .files > div:not(.item):not(.place-row):not(.tabfiles-selection-area)').remove();
|
||||
// Add the new file incrementally
|
||||
@@ -5449,15 +5412,11 @@ const TabFiles = {
|
||||
_this.applyColumnWidths();
|
||||
_this.updateFooterStats();
|
||||
}
|
||||
} else if ( settled && _this.currentPath === pathAtClick ) {
|
||||
} else {
|
||||
// Same navigate-to-target treatment as New
|
||||
// Folder above.
|
||||
_this.pushNavHistory(targetPath);
|
||||
await _this.renderDirectory(targetPath, { consistency: 'strong' });
|
||||
} else {
|
||||
// The user went elsewhere meanwhile; the
|
||||
// file is there when they come back.
|
||||
return;
|
||||
}
|
||||
const $newRow = _this.$el_window.find(`.files-tab .files .item[data-uid='${result.uid}']`);
|
||||
if ( $newRow.length > 0 ) {
|
||||
@@ -5468,8 +5427,7 @@ const TabFiles = {
|
||||
} catch ( err ) {
|
||||
UIAlert(err?.message || i18n('error_unknown_cause', [], false));
|
||||
} finally {
|
||||
createFileInterceptors.splice(createFileInterceptors.indexOf(createFile), 1);
|
||||
window.create_file = createFileInterceptors.at(-1) ?? realCreateFile;
|
||||
window.create_file = origCreateFile;
|
||||
if ( uploadPromise ) _this.doneCreating();
|
||||
}
|
||||
};
|
||||
|
||||
@@ -116,131 +116,6 @@ describe('TabFiles emptying the Trash', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('TabFiles restoring from the Trash', () => {
|
||||
beforeEach(() => {
|
||||
window.trash_path = TRASH;
|
||||
window.byte_format = bytes => `${bytes} B`;
|
||||
window.refresh_trash_state = vi.fn(async () => {});
|
||||
window.puter = { fs: { move: vi.fn(async () => ({})) } };
|
||||
});
|
||||
|
||||
afterEach(() => vi.restoreAllMocks());
|
||||
|
||||
it('says in the user\'s language when an item has no record of where it came from', async () => {
|
||||
const { default: UIAlert } = await import('../UIAlert.js');
|
||||
UIAlert.mockClear();
|
||||
mountListing(['uid-1']);
|
||||
const row = $('.files .row')[0];
|
||||
row.setAttribute('data-name', 'notes.txt');
|
||||
row.setAttribute('data-uid', 'uid-1');
|
||||
|
||||
vi.spyOn(console, 'error').mockImplementation(() => {});
|
||||
await TabFiles.restoreRows([row]);
|
||||
|
||||
expect(puter.fs.move).not.toHaveBeenCalled();
|
||||
expect(UIAlert).toHaveBeenCalledWith('“notes.txt” can’t be restored because where it was deleted from isn’t known.');
|
||||
expect($('.files .row')).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('TabFiles New menu creates', () => {
|
||||
const menuItem = (pattern, folder) => TabFiles.generateFolderContextMenu(folder)
|
||||
.find(item => item && item.items).items.find(item => item && pattern.test(item.html));
|
||||
let uploads;
|
||||
|
||||
beforeEach(() => {
|
||||
mountListing([], '/alice/Documents');
|
||||
window.user = { username: 'alice' };
|
||||
window.trash_path = TRASH;
|
||||
window.shared_path = '/alice/Shared';
|
||||
window.file_templates = [];
|
||||
window.sites = [];
|
||||
window.actions_history = [];
|
||||
window.activate_item_name_editor = vi.fn();
|
||||
vi.spyOn(TabFiles, 'pushNavHistory').mockImplementation(() => {});
|
||||
uploads = [];
|
||||
window.puter = { fs: { upload: vi.fn((file, dirname) => new Promise(resolve => {
|
||||
uploads.push(() => resolve({ uid: `u${uploads.length}`, name: file.name, path: `${dirname}/${file.name}` }));
|
||||
})) } };
|
||||
vi.spyOn(TabFiles, 'acceptsNewItemsHere').mockReturnValue(true);
|
||||
vi.spyOn(TabFiles, 'acceptsNewItems').mockReturnValue(true);
|
||||
vi.spyOn(TabFiles, 'renderItem').mockResolvedValue();
|
||||
TabFiles.loadingFolder = false;
|
||||
TabFiles._creatingItem = 0;
|
||||
TabFiles.trashedNames ??= new Map();
|
||||
TabFiles.deferredAdds ??= [];
|
||||
});
|
||||
|
||||
afterEach(() => vi.restoreAllMocks());
|
||||
|
||||
it('puts the real create_file back when two overlap, whichever finishes first', async () => {
|
||||
const real = vi.fn();
|
||||
window.create_file = real;
|
||||
|
||||
const first = menuItem(/text_document|Text/).onClick();
|
||||
const second = menuItem(/html_document|HTML/).onClick();
|
||||
await new Promise(resolve => setTimeout(resolve, 0));
|
||||
expect(uploads).toHaveLength(2);
|
||||
uploads[0]();
|
||||
await first;
|
||||
uploads[1]();
|
||||
await second;
|
||||
|
||||
expect(window.create_file).toBe(real);
|
||||
expect(TabFiles._creatingItem).toBe(0);
|
||||
|
||||
const third = menuItem(/text_document|Text/).onClick();
|
||||
const fourth = menuItem(/html_document|HTML/).onClick();
|
||||
await new Promise(resolve => setTimeout(resolve, 0));
|
||||
uploads[3]();
|
||||
await fourth;
|
||||
uploads[2]();
|
||||
await third;
|
||||
|
||||
expect(window.create_file).toBe(real);
|
||||
expect(TabFiles._creatingItem).toBe(0);
|
||||
});
|
||||
|
||||
it('leaves a listing the user moved to alone when the upload lands after', async () => {
|
||||
window.create_file = vi.fn();
|
||||
vi.spyOn(TabFiles, 'renderDirectory').mockResolvedValue();
|
||||
const created = menuItem(/text_document|Text/).onClick();
|
||||
await new Promise(resolve => setTimeout(resolve, 0));
|
||||
|
||||
// The user opened Pictures; its listing is still loading.
|
||||
TabFiles.loadingFolder = true;
|
||||
uploads[0]();
|
||||
await created;
|
||||
expect(TabFiles.renderItem).not.toHaveBeenCalled();
|
||||
expect(TabFiles.renderDirectory).not.toHaveBeenCalled();
|
||||
expect(window.activate_item_name_editor).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('does not pull the user back once they are in another folder', async () => {
|
||||
window.create_file = vi.fn();
|
||||
vi.spyOn(TabFiles, 'renderDirectory').mockResolvedValue();
|
||||
const created = menuItem(/text_document|Text/).onClick();
|
||||
await new Promise(resolve => setTimeout(resolve, 0));
|
||||
|
||||
TabFiles.currentPath = '/alice/Pictures';
|
||||
uploads[0]();
|
||||
await created;
|
||||
expect(TabFiles.renderDirectory).not.toHaveBeenCalled();
|
||||
expect(TabFiles.renderItem).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('still goes to the folder whose menu made the file', async () => {
|
||||
window.create_file = vi.fn();
|
||||
vi.spyOn(TabFiles, 'renderDirectory').mockResolvedValue();
|
||||
const created = menuItem(/text_document|Text/, '/alice/Videos').onClick();
|
||||
await new Promise(resolve => setTimeout(resolve, 0));
|
||||
|
||||
uploads[0]();
|
||||
await created;
|
||||
expect(TabFiles.renderDirectory).toHaveBeenCalledWith('/alice/Videos', { consistency: 'strong' });
|
||||
});
|
||||
});
|
||||
|
||||
describe('failedUploadsMessage', () => {
|
||||
it('puts each failed item on its own line', () => {
|
||||
const message = failedUploadsMessage({ failedItems: [
|
||||
@@ -1211,57 +1086,6 @@ describe('TabFiles names in a narrow listing', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('TabFiles names in an auto-width name column', () => {
|
||||
const mountNames = (names) => {
|
||||
document.body.innerHTML = `
|
||||
<div class="window"><div class="files-tab">
|
||||
<div class="header"><div class="columns"></div></div>
|
||||
<div class="files files-list-view">${names.map(name => `
|
||||
<div class="row item" data-name="${name}">
|
||||
<div class="item-name-wrapper" style="padding: 0 40px 0 0"><pre class="item-name" style="padding: 0 8px"></pre></div>
|
||||
</div>`).join('')}
|
||||
</div>
|
||||
</div></div>`;
|
||||
TabFiles.$el_window = $('.window');
|
||||
TabFiles.currentView = 'list';
|
||||
TabFiles.appliedColumnWidths = { name: null, sharedBy: 160, size: 60, modified: 80 };
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
// 10px a character; jsdom has no canvas.
|
||||
vi.spyOn(HTMLCanvasElement.prototype, 'getContext').mockReturnValue({ measureText: text => ({ width: text.length * 10 }) });
|
||||
});
|
||||
|
||||
afterEach(() => vi.restoreAllMocks());
|
||||
|
||||
it('cut a long name in the middle to the room its wrapper leaves, keeping the end', () => {
|
||||
const long = `${'x'.repeat(60)} (1).txt`;
|
||||
mountNames([long, 'short.txt']);
|
||||
// 256px wrapper, less its 40px and the name's 16px of padding: 200px, 20 characters.
|
||||
vi.spyOn(HTMLElement.prototype, 'clientWidth', 'get').mockReturnValue(256);
|
||||
|
||||
TabFiles.fitItemNames($('.files .item-name'));
|
||||
|
||||
const [$long, $short] = $('.files .item-name').toArray().map(el => $(el));
|
||||
expect($long.text().length).toBeLessThanOrEqual(20);
|
||||
expect($long.text().length).toBeGreaterThan(15);
|
||||
expect($long.text()).toMatch(/^x+…x* \(1\)\.txt$/);
|
||||
expect($long.attr('title')).toBe(long);
|
||||
expect($short.text()).toBe('short.txt');
|
||||
expect($short.attr('title') ?? '').toBe('');
|
||||
});
|
||||
|
||||
it('show the full name while the listing has no width yet', () => {
|
||||
const long = 'y'.repeat(80);
|
||||
mountNames([long]);
|
||||
vi.spyOn(HTMLElement.prototype, 'clientWidth', 'get').mockReturnValue(0);
|
||||
|
||||
TabFiles.fitItemNames($('.files .item-name'));
|
||||
|
||||
expect($('.files .item-name').text()).toBe(long);
|
||||
});
|
||||
});
|
||||
|
||||
describe('TabFiles uploads', () => {
|
||||
beforeEach(async () => {
|
||||
vi.restoreAllMocks();
|
||||
@@ -1545,22 +1369,6 @@ describe('TabFiles keyboard', () => {
|
||||
expect(selected()).toEqual(['/alice/Documents/a.txt']);
|
||||
});
|
||||
|
||||
it('leaves Alt and Cmd arrows to the browser', () => {
|
||||
mountKeyboard(['a.txt', 'b.txt']);
|
||||
$('.files .row').first().addClass('selected');
|
||||
|
||||
const back = new KeyboardEvent('keydown', { key: 'ArrowLeft', which: 37, keyCode: 37, altKey: true, bubbles: true, cancelable: true });
|
||||
document.body.dispatchEvent(back);
|
||||
const down = new KeyboardEvent('keydown', { key: 'ArrowDown', which: 40, keyCode: 40, metaKey: true, bubbles: true, cancelable: true });
|
||||
document.body.dispatchEvent(down);
|
||||
|
||||
expect(back.defaultPrevented).toBe(false);
|
||||
expect(down.defaultPrevented).toBe(false);
|
||||
expect(selected()).toEqual(['/alice/Documents/a.txt']);
|
||||
press(document.body, 'ArrowDown', { which: 40, keyCode: 40 });
|
||||
expect(selected()).toEqual(['/alice/Documents/b.txt']);
|
||||
});
|
||||
|
||||
it('takes a space typed into a name as part of it', () => {
|
||||
mountKeyboard(['my notes.txt', 'my zebra.txt']);
|
||||
for ( const key of ['m', 'y', ' ', 'z'] ) press(document.body, key, { which: key.toUpperCase().charCodeAt(0) });
|
||||
|
||||
@@ -168,19 +168,15 @@ function buildUsageHTML() {
|
||||
// what the badge carries: a date says when, only a countdown says how long
|
||||
// there is to decide. Returns null when the subscription carries no end date,
|
||||
// so callers fall back to unqualified "Free trial" wording.
|
||||
export function formatTrialEnd(trialEndsAt, now = Date.now()) {
|
||||
function formatTrialEnd(trialEndsAt) {
|
||||
if (!Number.isFinite(trialEndsAt)) return null;
|
||||
const date = new Date(trialEndsAt);
|
||||
if (Number.isNaN(date.getTime())) return null;
|
||||
// Calendar days in the user's time zone, so the countdown agrees with the
|
||||
// date beside it: a trial ending this afternoon ends "today", and one
|
||||
// ending tomorrow morning has one day left. Rounded, for the 23- and
|
||||
// 25-hour days daylight saving makes.
|
||||
const startOfDay = (d) =>
|
||||
new Date(d.getFullYear(), d.getMonth(), d.getDate()).getTime();
|
||||
// Rounded up, so a trial with any time on it never reads "0 days left"
|
||||
// before the day it actually converts.
|
||||
const days = Math.max(
|
||||
0,
|
||||
Math.round((startOfDay(date) - startOfDay(new Date(now))) / 86400000),
|
||||
Math.ceil((date.getTime() - Date.now()) / 86400000),
|
||||
);
|
||||
// In the dashboard's language, which the sentences around it are in.
|
||||
const locale = intlLocale(window.locale);
|
||||
|
||||
@@ -31,7 +31,7 @@ globalThis.i18n = key => key;
|
||||
window.icons = {};
|
||||
window.launch_apps = { recent: [] };
|
||||
|
||||
const { default: TabHome, formatTrialEnd } = await import('./TabHome.js');
|
||||
const { default: TabHome } = await import('./TabHome.js');
|
||||
const { openAppInNewTab } = await import('../../helpers/dashboardAppLaunch.js');
|
||||
|
||||
describe('TabHome recently used', () => {
|
||||
@@ -96,25 +96,3 @@ describe('TabHome recent app clicks', () => {
|
||||
expect(openAppInNewTab).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('formatTrialEnd', () => {
|
||||
const at = (day, hour) => new Date(2026, 10, day, hour).getTime();
|
||||
|
||||
it('counts calendar days, so the countdown agrees with the date', () => {
|
||||
// Ends at 3pm today: today, not "1 day left".
|
||||
expect(formatTrialEnd(at(8, 15), at(8, 9)).days).toBe(0);
|
||||
// Ends tomorrow at 11am: one day, not two.
|
||||
expect(formatTrialEnd(at(9, 11), at(8, 9)).days).toBe(1);
|
||||
expect(formatTrialEnd(at(9, 11), at(8, 23)).days).toBe(1);
|
||||
expect(formatTrialEnd(at(15, 0), at(8, 23)).days).toBe(7);
|
||||
});
|
||||
|
||||
it('reads an end that has passed as today', () => {
|
||||
expect(formatTrialEnd(at(7, 12), at(8, 9)).days).toBe(0);
|
||||
});
|
||||
|
||||
it('has nothing to say without an end date', () => {
|
||||
expect(formatTrialEnd(undefined)).toBeNull();
|
||||
expect(formatTrialEnd(NaN)).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -49,9 +49,7 @@ const ICONS = {
|
||||
puter: svg('<rect x="3" y="3" width="18" height="18" rx="4"/><path d="M8 12h8M12 8v8"/>'),
|
||||
};
|
||||
|
||||
// `webpush` is Puter's own Web Push (see webPushClient.js); both are browsers.
|
||||
const PLATFORM_KEYS = { web: 'push_platform_web', webpush: 'push_platform_web', ios: 'push_platform_ios', android: 'push_platform_android' };
|
||||
const BROWSER_PLATFORMS = new Set(['web', 'webpush']);
|
||||
const PLATFORM_KEYS = { web: 'push_platform_web', ios: 'push_platform_ios', android: 'push_platform_android' };
|
||||
|
||||
/** @param {{ pushEnabled?: boolean }|undefined} params - `window.gui_params` */
|
||||
export const notificationsTabEnabled = (params) => params?.pushEnabled === true;
|
||||
@@ -108,7 +106,7 @@ export const deviceCardHtml = (device, now) => {
|
||||
? i18n('push_device_last_seen', { time: formatRelativeTime(seenAt, now, locale) })
|
||||
: '';
|
||||
return card({
|
||||
icon: BROWSER_PLATFORMS.has(device.platform) ? ICONS.laptop : ICONS.phone,
|
||||
icon: device.platform === 'web' ? ICONS.laptop : ICONS.phone,
|
||||
title: html_encode(deviceName(device)),
|
||||
badge: device.current ? i18n('push_this_browser') : '',
|
||||
detail: [platform, seen].filter(Boolean).join(' · '),
|
||||
@@ -232,18 +230,11 @@ const TabNotifications = {
|
||||
? devices.map(device => deviceCardHtml(device, now)).join('')
|
||||
: emptyHtml('push_devices_empty'));
|
||||
};
|
||||
// Only the newest listing draws, and a local removal outdates any
|
||||
// listing still in flight: it may predate the removal.
|
||||
let devicesSeq = 0;
|
||||
const refreshDevices = async () => {
|
||||
const seq = ++devicesSeq;
|
||||
try {
|
||||
const listed = await listPushDevices();
|
||||
if ( seq !== devicesSeq ) return;
|
||||
devices = listed;
|
||||
devices = await listPushDevices();
|
||||
renderDevices();
|
||||
} catch ( e ) {
|
||||
if ( seq !== devicesSeq ) return;
|
||||
console.warn('[push] device list failed', e);
|
||||
$section.find('.push-devices-list').html(emptyHtml(loadFailedKey(e)));
|
||||
}
|
||||
@@ -254,16 +245,11 @@ const TabNotifications = {
|
||||
? apps.map(appCardHtml).join('')
|
||||
: emptyHtml('push_apps_empty'));
|
||||
};
|
||||
let appsSeq = 0;
|
||||
const refreshApps = async () => {
|
||||
const seq = ++appsSeq;
|
||||
try {
|
||||
const listed = await listPushApps();
|
||||
if ( seq !== appsSeq ) return;
|
||||
apps = listed;
|
||||
apps = await listPushApps();
|
||||
renderApps();
|
||||
} catch ( e ) {
|
||||
if ( seq !== appsSeq ) return;
|
||||
console.warn('[push] app list failed', e);
|
||||
$section.find('.push-apps-list').html(emptyHtml(loadFailedKey(e)));
|
||||
}
|
||||
@@ -271,15 +257,12 @@ const TabNotifications = {
|
||||
|
||||
const refreshPreference = async () => {
|
||||
const $toggle = $section.find('.push-puter-toggle');
|
||||
const $hint = $section.find('.push-puter-card .dashboard-settings-card-info > span');
|
||||
try {
|
||||
$toggle.prop('checked', await getPuterPushPreference()).prop('disabled', false);
|
||||
// A failed earlier read replaced the hint.
|
||||
$hint.html(i18n('push_puter_notifications_hint'));
|
||||
} catch ( e ) {
|
||||
console.warn('[push] preference read failed', e);
|
||||
$toggle.prop('checked', false).prop('disabled', true);
|
||||
$hint.html(i18n(loadFailedKey(e)));
|
||||
$section.find('.push-puter-card .dashboard-settings-card-info > span').html(i18n(loadFailedKey(e)));
|
||||
}
|
||||
};
|
||||
|
||||
@@ -379,21 +362,13 @@ const TabNotifications = {
|
||||
if ( confirmed !== true ) return;
|
||||
// disable() drops the token and record; the DELETE covers a lost record.
|
||||
const client = device.current ? getPushClient() : null;
|
||||
let disabled = false;
|
||||
try {
|
||||
if ( client ) {
|
||||
await client.disable();
|
||||
disabled = true;
|
||||
// Push is off here even if the DELETE fails; without the
|
||||
// opt-out the next load would turn it back on.
|
||||
setBrowserPushOptOut(window.user?.uuid, true);
|
||||
}
|
||||
if ( client ) await client.disable();
|
||||
await removePushDevice(uid);
|
||||
} catch ( e ) {
|
||||
if ( e?.status !== 404 || e?.code === PUSH_UNAVAILABLE ) {
|
||||
console.warn('[push] device removal failed', e);
|
||||
showError('push_device_remove_failed', $el_window);
|
||||
if ( disabled ) refreshBrowser();
|
||||
return;
|
||||
}
|
||||
}
|
||||
@@ -402,7 +377,6 @@ const TabNotifications = {
|
||||
await Promise.all([refreshBrowser(), refreshDevices()]);
|
||||
return;
|
||||
}
|
||||
devicesSeq++;
|
||||
devices = devices.filter(d => d.uid !== uid);
|
||||
renderDevices();
|
||||
if ( device.current ) refreshBrowser();
|
||||
@@ -419,7 +393,6 @@ const TabNotifications = {
|
||||
showError('push_app_turn_off_failed', $el_window);
|
||||
return;
|
||||
}
|
||||
appsSeq++;
|
||||
apps = apps.filter(app => app.uid !== appUid);
|
||||
renderApps();
|
||||
});
|
||||
|
||||
@@ -412,26 +412,6 @@ describe('Puter notifications', () => {
|
||||
expect($('.push-puter-card').text()).toContain('push_load_failed');
|
||||
});
|
||||
|
||||
it('puts the hint back once a later visit reads the preference', async () => {
|
||||
serve({
|
||||
'GET /push/devices': { devices: [] },
|
||||
'GET /push/apps': { apps: [] },
|
||||
'GET /push/preferences': () => reply(500, {}),
|
||||
});
|
||||
await open();
|
||||
serve({
|
||||
'GET /push/devices': { devices: [] },
|
||||
'GET /push/apps': { apps: [] },
|
||||
'GET /push/preferences': { puter: true },
|
||||
});
|
||||
await tab.onActivate($('.win'));
|
||||
await settle();
|
||||
|
||||
expect($('.push-puter-toggle').prop('disabled')).toBe(false);
|
||||
expect($('.push-puter-card').text()).toContain('push_puter_notifications_hint');
|
||||
expect($('.push-puter-card').text()).not.toContain('push_load_failed');
|
||||
});
|
||||
|
||||
it('puts the switch back when the save fails', async () => {
|
||||
serve({
|
||||
'GET /push/devices': { devices: [] },
|
||||
@@ -491,21 +471,6 @@ describe('your devices', () => {
|
||||
expect($cards.eq(2).find('strong').text()).toBe('push_device_unknown');
|
||||
});
|
||||
|
||||
it('labels a browser on Puter\'s own Web Push as a browser', async () => {
|
||||
serve({
|
||||
'GET /push/devices': { devices: [device({ uid: 'a', platform: 'webpush' }), device({ uid: 'b', platform: 'ios' })] },
|
||||
'GET /push/apps': { apps: [] },
|
||||
'GET /push/preferences': { puter: true },
|
||||
});
|
||||
await open();
|
||||
|
||||
const $cards = $('.push-device-card');
|
||||
expect($cards.eq(0).find('.dashboard-settings-card-info > span').text()).toContain('push_platform_web');
|
||||
// Laptop, not phone.
|
||||
expect($cards.eq(0).find('svg rect').attr('width')).toBe('18');
|
||||
expect($cards.eq(1).find('svg rect').attr('width')).toBe('12');
|
||||
});
|
||||
|
||||
it('removes a device once the user confirms', async () => {
|
||||
const remove = vi.fn(() => reply(200, { removed: true }));
|
||||
serve({
|
||||
@@ -557,30 +522,6 @@ describe('your devices', () => {
|
||||
expect(pushClient.browserPushOptedOut('u-1')).toBe(true);
|
||||
});
|
||||
|
||||
it('keeps this browser opted out when its push is off but the server removal fails', async () => {
|
||||
const client = fakeClient({ permission: 'granted', registered: true, deviceUid: 'a' });
|
||||
pushClient.registerPushClient(client);
|
||||
serve({
|
||||
'GET /push/devices': { devices: [device({ uid: 'a', current: true })] },
|
||||
'GET /push/apps': { apps: [] },
|
||||
'GET /push/preferences': { puter: true },
|
||||
'DELETE /push/devices/a': () => reply(500, {}),
|
||||
});
|
||||
await open();
|
||||
client.disable.mockImplementation(async () => {
|
||||
client.status.mockResolvedValue({ permission: 'granted', registered: false });
|
||||
});
|
||||
|
||||
$('.push-remove-device[data-uid="a"]').trigger('click');
|
||||
await settle();
|
||||
dialogButton('push_device_remove').trigger('click');
|
||||
await settle();
|
||||
|
||||
expect(dialog('.dashboard-dialog-message').text()).toContain('push_device_remove_failed');
|
||||
expect(pushClient.browserPushOptedOut('u-1')).toBe(true);
|
||||
expect(browserCard().hasClass('push-browser-off')).toBe(true);
|
||||
});
|
||||
|
||||
it('still removes this browser on the server when it has no local record', async () => {
|
||||
const client = fakeClient({ permission: 'granted', registered: false });
|
||||
pushClient.registerPushClient(client);
|
||||
@@ -607,36 +548,6 @@ describe('your devices', () => {
|
||||
expect($('.push-device-card')).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('does not bring back a removed device when an older listing lands after the removal', async () => {
|
||||
const both = [device({ uid: 'a' }), device({ uid: 'b', label: 'Phone' })];
|
||||
let releaseListing;
|
||||
let deferred = false;
|
||||
serve({
|
||||
'GET /push/devices': () => (deferred
|
||||
? new Promise(resolve => { releaseListing = () => resolve(reply(200, { devices: both })); })
|
||||
: reply(200, { devices: both })),
|
||||
'GET /push/apps': { apps: [] },
|
||||
'GET /push/preferences': { puter: true },
|
||||
'DELETE /push/devices/b': () => reply(200, { removed: true }),
|
||||
});
|
||||
await open();
|
||||
// Coming back to the tab starts a listing that is slow to answer.
|
||||
deferred = true;
|
||||
void tab.onActivate($('.win'));
|
||||
await settle();
|
||||
|
||||
$('.push-remove-device[data-uid="b"]').trigger('click');
|
||||
await settle();
|
||||
dialogButton('push_device_remove').trigger('click');
|
||||
await settle();
|
||||
expect($('.push-remove-device[data-uid="b"]')).toHaveLength(0);
|
||||
|
||||
releaseListing();
|
||||
await settle();
|
||||
expect($('.push-remove-device[data-uid="b"]')).toHaveLength(0);
|
||||
expect($('.push-device-card')).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('removes another device with the server alone', async () => {
|
||||
const client = fakeClient({ permission: 'granted', registered: true, deviceUid: 'a' });
|
||||
pushClient.registerPushClient(client);
|
||||
|
||||
@@ -17,7 +17,7 @@
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
import { formatCount, formatCredits, formatDollarsFromMicrocents, usageIsCredits } from './credits.js';
|
||||
import { formatCredits, formatDollarsFromMicrocents, usageIsCredits } from './credits.js';
|
||||
import { isOrgSeat } from './orgSeat.js';
|
||||
import { addonCreditsRemaining, meterPercent, monthlyUsageOrThrow, usageBudget } from './usageBudget.js';
|
||||
import { getMonthlyUsage, getStorageSpace } from './usageRequests.js';
|
||||
@@ -281,7 +281,7 @@ function renderUsageTable () {
|
||||
for ( const row of rowsToShow ) {
|
||||
h += `
|
||||
<tr>
|
||||
<td title="${window.html_encode(row.resource.replaceAll('_dot_', '.'))}">${window.html_encode(row.resource.replaceAll('_dot_', '.'))}</td>
|
||||
<td>${window.html_encode(row.resource.replaceAll('_dot_', '.'))}</td>
|
||||
<td>${row.formattedUnits}</td>
|
||||
<td>${row.formattedCost}</td>
|
||||
</tr>`;
|
||||
@@ -351,7 +351,7 @@ async function update_usage_details ($el_window) {
|
||||
if ( key.endsWith(':bytes') ) {
|
||||
formattedUnits = window.byte_format(rawUnits);
|
||||
} else {
|
||||
formattedUnits = formatCount(rawUnits);
|
||||
formattedUnits = window.number_format(rawUnits, { decimals: 0, thousandSeparator: ',' });
|
||||
}
|
||||
|
||||
usageTableData.push({
|
||||
|
||||
@@ -24,10 +24,10 @@ import UIContextMenu from '../UIContextMenu.js';
|
||||
import UIAlert from '../UIAlert.js';
|
||||
import UIWindowSaveAccount from '../UIWindowSaveAccount.js';
|
||||
import UIAuthLogin from '../Auth/UIAuthLogin.js';
|
||||
import UIWindowFeedback from '../UIWindowFeedback.js';
|
||||
import apply_item_added_to_containers from '../../helpers/applyItemAddedToContainers.js';
|
||||
import { clear_shared_param } from '../../helpers/parseSharedPath.js';
|
||||
import UIDashboardNotifications from './UIDashboardNotifications.js';
|
||||
import UIDashboardContactDialog from './UIDashboardContactDialog.js';
|
||||
import {
|
||||
answerNotificationReceipts,
|
||||
notificationSocketAcks,
|
||||
@@ -548,13 +548,12 @@ async function UIDashboard (options) {
|
||||
const filePath = route.path;
|
||||
notifications.close({ restoreFocus: false });
|
||||
// What was open over the tab being left goes with it, as on a
|
||||
// sidebar click: the phone drawer, a menu, Files' Share and
|
||||
// sidebar click: the phone drawer, a menu, and Files' Share and
|
||||
// Properties, which act on its rows (their changes are already saved),
|
||||
// its image preview, and a dialog or the photo crop, each through its
|
||||
// own close button.
|
||||
// and its image preview.
|
||||
setMobileSidebar(false);
|
||||
$('.context-menu').remove();
|
||||
$el_window.find('.share-modal-close, .item-props-close, .dashboard-dialog-overlay .dashboard-dialog-close, .profile-crop-close').trigger('click');
|
||||
$el_window.find('.share-modal-close, .item-props-close').trigger('click');
|
||||
if ( tab !== 'files' && TabFiles.previewOpen ) TabFiles.closeImagePreview();
|
||||
|
||||
// Switch to correct tab
|
||||
@@ -901,8 +900,16 @@ async function UIDashboard (options) {
|
||||
// Contact Us
|
||||
{
|
||||
html: i18n('contact_us'),
|
||||
onClick: function () {
|
||||
UIDashboardContactDialog({ $container: $el_window, returnFocusTo: $btn.get(0) });
|
||||
onClick: async function () {
|
||||
UIWindowFeedback({
|
||||
window_options: {
|
||||
backdrop: true,
|
||||
close_on_backdrop_click: true,
|
||||
parent_center: true,
|
||||
stay_on_top: true,
|
||||
has_head: false,
|
||||
},
|
||||
});
|
||||
},
|
||||
},
|
||||
'-',
|
||||
|
||||
@@ -1,277 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2024-present Puter Technologies Inc.
|
||||
*
|
||||
* This file is part of Puter.
|
||||
*
|
||||
* Puter is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published
|
||||
* by the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
// The dashboard's Contact Us form: a dashboard form dialog with screenshots
|
||||
// and screen recordings attached by picking, dropping or pasting them. The
|
||||
// desktop keeps UIWindowFeedback.
|
||||
|
||||
import {
|
||||
ATTACHMENT_ACCEPT_ATTRIBUTE,
|
||||
MAX_ATTACHMENTS,
|
||||
MAX_ATTACHMENT_BYTES,
|
||||
MAX_TOTAL_ATTACHMENT_BYTES,
|
||||
checkAttachment,
|
||||
} from '../../helpers/contact_attachments.js';
|
||||
import { isTouchPrimaryDevice } from './ContextMenu/ContextMenu.js';
|
||||
import { ICONS, SVG } from './UIDashboardDialog.js';
|
||||
import UIDashboardFormDialog from './UIDashboardFormDialog.js';
|
||||
|
||||
const MB = 1024 * 1024;
|
||||
|
||||
// Keep in sync with SystemController on the backend.
|
||||
const MESSAGE_MAX_LENGTH = 100_000;
|
||||
|
||||
// Numbers interpolated into each error message, taken from the enforced limits.
|
||||
const ERROR_VALUES = {
|
||||
contact_us_attachment_too_many: [MAX_ATTACHMENTS],
|
||||
contact_us_attachment_too_large: [MAX_ATTACHMENT_BYTES / MB],
|
||||
contact_us_attachment_total_too_large: [MAX_TOTAL_ATTACHMENT_BYTES / MB],
|
||||
};
|
||||
|
||||
const CONTACT_ICONS = {
|
||||
attach: SVG('<path d="M21.4 11.1l-9.2 9.2a6 6 0 0 1-8.5-8.5l9.2-9.2a4 4 0 0 1 5.7 5.7l-9.2 9.2a2 2 0 0 1-2.8-2.8l8.5-8.5"/>'),
|
||||
video: SVG('<rect x="2" y="5" width="14" height="14" rx="2"/><path d="M16 10l6-3.5v11L16 14"/>'),
|
||||
};
|
||||
|
||||
const t = (key, values = []) => i18n(key, values, false);
|
||||
|
||||
/**
|
||||
* Whether a drag carries files, rather than text or a link from the page.
|
||||
*
|
||||
* @param {DragEvent} e
|
||||
* @returns {boolean}
|
||||
*/
|
||||
const dragHasFiles = (e) => Array.from(e.originalEvent?.dataTransfer?.types ?? []).includes('Files');
|
||||
|
||||
/**
|
||||
* @param {File} file
|
||||
* @returns {string}
|
||||
*/
|
||||
const attachmentHtml = (file) => {
|
||||
const name = html_encode(file.name);
|
||||
// The preview's URL is let go once it has drawn; the <img> keeps the pixels.
|
||||
const thumb = file.type.startsWith('image/')
|
||||
? `<img src="${html_encode(URL.createObjectURL(file))}" alt="" draggable="false">`
|
||||
: CONTACT_ICONS.video;
|
||||
const remove = html_encode(t('contact_us_attachment_remove_named', [file.name]));
|
||||
return '<li class="dashboard-contact-file">'
|
||||
+ `<span class="dashboard-contact-file-thumb" aria-hidden="true">${thumb}</span>`
|
||||
+ '<span class="dashboard-contact-file-text">'
|
||||
+ `<span class="dashboard-contact-file-name" title="${name}">${name}</span>`
|
||||
+ `<span class="dashboard-contact-file-size">${html_encode(window.byte_format(file.size))}</span>`
|
||||
+ '</span>'
|
||||
+ `<button type="button" class="dashboard-contact-file-remove" aria-label="${remove}" title="${i18n('contact_us_attachment_remove')}">${ICONS.close}</button>`
|
||||
+ '</li>';
|
||||
};
|
||||
|
||||
/**
|
||||
* Opens the Contact Us form; the message goes to support, with any
|
||||
* attachments as multipart form data. The checks here only fail fast: the
|
||||
* server enforces the limits.
|
||||
*
|
||||
* @param {object} [opts]
|
||||
* @param {jQuery} [opts.$container] Where the overlay mounts.
|
||||
* @param {HTMLElement} [opts.returnFocusTo] Where focus goes on close.
|
||||
* @returns {import('./UIDashboardFormDialog.js').FormDialog}
|
||||
*/
|
||||
export default function UIDashboardContactDialog ({ $container, returnFocusTo } = {}) {
|
||||
/** @type {File[]} */
|
||||
const attachments = [];
|
||||
let sending = false;
|
||||
// Once sent, the form is gone and a drop or paste has nothing to join.
|
||||
let sent = false;
|
||||
|
||||
const dialog = UIDashboardFormDialog({
|
||||
$container,
|
||||
returnFocusTo,
|
||||
title: t('contact_us'),
|
||||
intro: `<p>${i18n('feedback_c2a')}</p>`,
|
||||
submitLabel: t('send'),
|
||||
fields: [{
|
||||
name: 'message',
|
||||
type: 'textarea',
|
||||
label: i18n('contact_us_message'),
|
||||
placeholder: i18n('contact_us_message_placeholder'),
|
||||
attrs: { rows: 6, maxlength: MESSAGE_MAX_LENGTH },
|
||||
}],
|
||||
async onSubmit () {
|
||||
const { message } = dialog.values();
|
||||
if ( ! message.trim() ) {
|
||||
dialog.setStatus(t('contact_us_message_required'), { field: 'message' });
|
||||
return;
|
||||
}
|
||||
|
||||
setSending(true);
|
||||
try {
|
||||
const body = new FormData();
|
||||
body.append('message', message);
|
||||
for ( const file of attachments ) body.append('attachments', file, file.name);
|
||||
|
||||
// No Content-Type: the browser sets it with the boundary.
|
||||
const resp = await fetch(`${window.api_origin}/contactUs`, {
|
||||
method: 'POST',
|
||||
headers: { Authorization: `Bearer ${window.auth_token}` },
|
||||
body,
|
||||
});
|
||||
if ( ! resp.ok ) {
|
||||
dialog.setStatus(t(resp.status === 429 ? 'contact_us_rate_limited' : 'contact_us_error'));
|
||||
return;
|
||||
}
|
||||
sent = true;
|
||||
dialog.finish({ message: t('feedback_sent_confirmation') });
|
||||
} catch ( err ) {
|
||||
console.error('contact-us: submit failed', err);
|
||||
dialog.setStatus(t('contact_us_error'));
|
||||
} finally {
|
||||
setSending(false);
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
const { $dialog } = dialog;
|
||||
const $overlay = $dialog.parent();
|
||||
const hint_id = `${$dialog.attr('aria-labelledby')}-attach-hint`;
|
||||
|
||||
let h = '<div class="dashboard-contact-attachments">';
|
||||
h += `<input type="file" class="dashboard-contact-file-input" accept="${html_encode(ATTACHMENT_ACCEPT_ATTRIBUTE)}" multiple hidden tabindex="-1">`;
|
||||
h += `<button type="button" class="dashboard-contact-dropzone" aria-describedby="${hint_id}">`;
|
||||
h += `<span class="dashboard-contact-dropzone-icon" aria-hidden="true">${CONTACT_ICONS.attach}</span>`;
|
||||
h += '<span class="dashboard-contact-dropzone-text">';
|
||||
h += `<span class="dashboard-contact-dropzone-label">${i18n(isTouchPrimaryDevice() ? 'contact_us_attach' : 'contact_us_attach_or_drop')}</span>`;
|
||||
h += `<span class="dashboard-contact-dropzone-drop" aria-hidden="true">${i18n('contact_us_drop_to_attach')}</span>`;
|
||||
h += `<span class="dashboard-contact-dropzone-hint" id="${hint_id}">${i18n('contact_us_attach_hint', [MAX_ATTACHMENTS, MAX_ATTACHMENT_BYTES / MB])}</span>`;
|
||||
h += '</span>';
|
||||
h += '</button>';
|
||||
h += `<ul class="dashboard-contact-files" aria-label="${i18n('contact_us_attachments')}" hidden></ul>`;
|
||||
h += '</div>';
|
||||
$dialog.addClass('dashboard-contact-dialog')
|
||||
.find('.dashboard-form-field[data-field="message"]').after(h);
|
||||
|
||||
const $dropzone = $dialog.find('.dashboard-contact-dropzone');
|
||||
const $fileInput = $dialog.find('.dashboard-contact-file-input');
|
||||
const $list = $dialog.find('.dashboard-contact-files');
|
||||
|
||||
const syncControls = () => {
|
||||
$list.prop('hidden', attachments.length === 0);
|
||||
// Nothing left to add once the count cap is reached.
|
||||
$dropzone.prop('disabled', sending || attachments.length >= MAX_ATTACHMENTS);
|
||||
$list.find('.dashboard-contact-file-remove').prop('disabled', sending);
|
||||
};
|
||||
|
||||
function setSending (value) {
|
||||
sending = value;
|
||||
$dialog.toggleClass('dashboard-contact-sending', value);
|
||||
syncControls();
|
||||
}
|
||||
|
||||
/** @param {File[]} files */
|
||||
const addFiles = (files) => {
|
||||
if ( sending || sent || ! files.length ) return;
|
||||
let rejection = null;
|
||||
for ( const file of files ) {
|
||||
const verdict = checkAttachment(file, attachments);
|
||||
if ( ! verdict.ok ) {
|
||||
// Report the first rejection but keep the files that fit.
|
||||
rejection = rejection ?? verdict.error;
|
||||
continue;
|
||||
}
|
||||
attachments.push(file);
|
||||
const $item = $(attachmentHtml(file));
|
||||
$item.find('img').one('load error', function () {
|
||||
URL.revokeObjectURL(this.src);
|
||||
});
|
||||
$list.append($item);
|
||||
}
|
||||
dialog.setStatus(rejection ? t(rejection, ERROR_VALUES[rejection] ?? []) : '');
|
||||
syncControls();
|
||||
};
|
||||
|
||||
$dropzone.on('click', () => $fileInput.trigger('click'));
|
||||
$fileInput.on('change', function () {
|
||||
addFiles(Array.from(this.files ?? []));
|
||||
// Reset so re-picking the same file fires `change` again.
|
||||
this.value = '';
|
||||
});
|
||||
|
||||
$list.on('click', '.dashboard-contact-file-remove', function () {
|
||||
if ( sending ) return;
|
||||
const $item = $(this).closest('.dashboard-contact-file');
|
||||
const index = $list.children().index($item);
|
||||
attachments.splice(index, 1);
|
||||
// Focus stays in the list rather than falling back to the page.
|
||||
const $next = $item.next().length ? $item.next() : $item.prev();
|
||||
$item.remove();
|
||||
dialog.setStatus('');
|
||||
syncControls();
|
||||
($next.length ? $next.find('.dashboard-contact-file-remove') : $dropzone).get(0)?.focus({ preventScroll: true });
|
||||
});
|
||||
|
||||
// The whole overlay takes the drop, and keeps it from the window under it.
|
||||
let drag_depth = 0;
|
||||
const endDrag = () => {
|
||||
drag_depth = 0;
|
||||
$dialog.removeClass('dashboard-contact-dragging');
|
||||
};
|
||||
$overlay.on('dragenter', (e) => {
|
||||
if ( ! dragHasFiles(e) ) return;
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
drag_depth++;
|
||||
if ( ! sending && ! sent ) $dialog.addClass('dashboard-contact-dragging');
|
||||
});
|
||||
$overlay.on('dragover', (e) => {
|
||||
if ( ! dragHasFiles(e) ) return;
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
e.originalEvent.dataTransfer.dropEffect = sending || sent ? 'none' : 'copy';
|
||||
});
|
||||
$overlay.on('dragleave', (e) => {
|
||||
// Matched to the dragenters counted, whatever this one says it carries.
|
||||
if ( drag_depth === 0 ) return;
|
||||
e.stopPropagation();
|
||||
if ( --drag_depth <= 0 ) endDrag();
|
||||
});
|
||||
$overlay.on('drop', (e) => {
|
||||
if ( ! dragHasFiles(e) ) return;
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
endDrag();
|
||||
addFiles(Array.from(e.originalEvent.dataTransfer.files ?? []));
|
||||
});
|
||||
|
||||
// A screenshot pasted into the message is attached to it.
|
||||
$dialog.on('paste', '.dashboard-form-input[name="message"]', (e) => {
|
||||
const clipboard = e.originalEvent?.clipboardData;
|
||||
const files = Array.from(clipboard?.files ?? []);
|
||||
if ( ! files.length ) return;
|
||||
// Some apps put the image's name or markup alongside it; that text still pastes.
|
||||
if ( ! clipboard.getData('text/plain') ) e.preventDefault();
|
||||
addFiles(files);
|
||||
});
|
||||
|
||||
// Enter alone is a new line in the message; with Cmd or Ctrl, it sends.
|
||||
$dialog.on('keydown', '.dashboard-form-input[name="message"]', (e) => {
|
||||
if ( e.key !== 'Enter' || ! (e.metaKey || e.ctrlKey) ) return;
|
||||
e.preventDefault();
|
||||
$dialog.trigger('submit');
|
||||
});
|
||||
|
||||
syncControls();
|
||||
return dialog;
|
||||
}
|
||||
@@ -1,255 +0,0 @@
|
||||
// @vitest-environment jsdom
|
||||
/*
|
||||
* Copyright (C) 2024-present Puter Technologies Inc.
|
||||
*
|
||||
* This file is part of Puter.
|
||||
*
|
||||
* Puter is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published
|
||||
* by the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import jQuery from '../../lib/jquery-3.6.1/jquery-3.6.1.min.js';
|
||||
import { MAX_ATTACHMENTS } from '../../helpers/contact_attachments.js';
|
||||
|
||||
globalThis.$ = jQuery;
|
||||
globalThis.jQuery = jQuery;
|
||||
globalThis.i18n = (key, values = []) => [key, ...values].join(' ');
|
||||
globalThis.html_encode = (value) => String(value ?? '')
|
||||
.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
|
||||
window.html_encode = globalThis.html_encode;
|
||||
window.requestAnimationFrame = (fn) => setTimeout(fn, 0);
|
||||
window.matchMedia = () => ({ matches: false });
|
||||
window.byte_format = (bytes) => `${bytes} B`;
|
||||
URL.createObjectURL = vi.fn(() => 'blob:preview');
|
||||
URL.revokeObjectURL = vi.fn();
|
||||
|
||||
const { default: UIDashboardContactDialog } = await import('./UIDashboardContactDialog.js');
|
||||
|
||||
const settle = async () => {
|
||||
for ( let i = 0; i < 10; i++ ) await new Promise(resolve => setTimeout(resolve, 0));
|
||||
};
|
||||
const message = () => $('.dashboard-form-input[name="message"]');
|
||||
const status = () => $('.dashboard-form-status').text();
|
||||
const fileNames = () => $('.dashboard-contact-file-name').map((_, el) => el.textContent).get();
|
||||
const png = (name = 'shot.png', size = 1024) => new File([new Uint8Array(size)], name, { type: 'image/png' });
|
||||
const mp4 = (name = 'clip.mp4') => new File([new Uint8Array(2048)], name, { type: 'video/mp4' });
|
||||
|
||||
/** Picks files through the hidden file input, as the system picker would. */
|
||||
const pick = (...files) => {
|
||||
const input = $('.dashboard-contact-file-input').get(0);
|
||||
Object.defineProperty(input, 'files', { value: files, configurable: true });
|
||||
$(input).trigger('change');
|
||||
};
|
||||
|
||||
/** A native-event stand-in for jQuery to wrap, carrying `fields`. */
|
||||
const nativeEvent = (fields) => ({ preventDefault () {}, stopPropagation () {}, ...fields });
|
||||
|
||||
/** A file drag event carrying `files`, as the browser sends it. */
|
||||
const fileDrag = (type, files = []) => $.Event(type, {
|
||||
originalEvent: nativeEvent({ dataTransfer: { types: ['Files'], files, dropEffect: 'none' } }),
|
||||
});
|
||||
|
||||
const submit = async () => {
|
||||
$('.dashboard-form-dialog').trigger('submit');
|
||||
await settle();
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
document.body.innerHTML = '';
|
||||
globalThis.fetch = vi.fn(async () => new Response('{}', { status: 200 }));
|
||||
window.api_origin = 'https://api.puter.test';
|
||||
window.auth_token = 'tok-1';
|
||||
});
|
||||
|
||||
describe('Contact Us dialog', () => {
|
||||
it('opens as a dashboard form dialog with no attachments listed', () => {
|
||||
UIDashboardContactDialog();
|
||||
expect($('.dashboard-dialog-overlay .dashboard-contact-dialog').length).toBe(1);
|
||||
expect(message().length).toBe(1);
|
||||
expect($('.dashboard-contact-files').prop('hidden')).toBe(true);
|
||||
});
|
||||
|
||||
it('asks for a message before sending', async () => {
|
||||
UIDashboardContactDialog();
|
||||
message().val(' ');
|
||||
await submit();
|
||||
expect(fetch).not.toHaveBeenCalled();
|
||||
expect(status()).toBe('contact_us_message_required');
|
||||
expect(message().attr('aria-invalid')).toBe('true');
|
||||
});
|
||||
|
||||
it('posts the message and attachments as multipart and confirms', async () => {
|
||||
UIDashboardContactDialog();
|
||||
pick(png(), mp4());
|
||||
message().val('It broke');
|
||||
await submit();
|
||||
|
||||
const [url, init] = fetch.mock.calls[0];
|
||||
expect(url).toBe('https://api.puter.test/contactUs');
|
||||
expect(init.headers).toEqual({ Authorization: 'Bearer tok-1' });
|
||||
expect(init.body.get('message')).toBe('It broke');
|
||||
expect(init.body.getAll('attachments').map(f => f.name)).toEqual(['shot.png', 'clip.mp4']);
|
||||
expect($('.dashboard-form-done').text()).toContain('feedback_sent_confirmation');
|
||||
expect($('.dashboard-contact-attachments').length).toBe(0);
|
||||
});
|
||||
|
||||
it('says when the sender is rate limited and keeps the form', async () => {
|
||||
fetch.mockResolvedValueOnce(new Response('{}', { status: 429 }));
|
||||
UIDashboardContactDialog();
|
||||
message().val('Hello');
|
||||
await submit();
|
||||
expect(status()).toBe('contact_us_rate_limited');
|
||||
expect(message().val()).toBe('Hello');
|
||||
expect(message().prop('disabled')).toBe(false);
|
||||
});
|
||||
|
||||
it('shows a generic error when the request fails', async () => {
|
||||
fetch.mockRejectedValueOnce(new TypeError('offline'));
|
||||
vi.spyOn(console, 'error').mockImplementation(() => {});
|
||||
UIDashboardContactDialog();
|
||||
message().val('Hello');
|
||||
await submit();
|
||||
expect(status()).toBe('contact_us_error');
|
||||
});
|
||||
|
||||
it('locks the attachments while sending', async () => {
|
||||
let respond;
|
||||
fetch.mockReturnValueOnce(new Promise(resolve => {
|
||||
respond = resolve;
|
||||
}));
|
||||
UIDashboardContactDialog();
|
||||
pick(png());
|
||||
message().val('Hello');
|
||||
$('.dashboard-form-dialog').trigger('submit');
|
||||
await settle();
|
||||
|
||||
expect($('.dashboard-contact-dropzone').prop('disabled')).toBe(true);
|
||||
expect($('.dashboard-contact-file-remove').prop('disabled')).toBe(true);
|
||||
pick(png('late.png'));
|
||||
expect(fileNames()).toEqual(['shot.png']);
|
||||
|
||||
respond(new Response('{}', { status: 500 }));
|
||||
await settle();
|
||||
expect($('.dashboard-contact-dropzone').prop('disabled')).toBe(false);
|
||||
expect($('.dashboard-contact-file-remove').prop('disabled')).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('attachments', () => {
|
||||
it('lists picked files with a preview for images', () => {
|
||||
UIDashboardContactDialog();
|
||||
pick(png('a.png'), mp4('b.mp4'));
|
||||
expect(fileNames()).toEqual(['a.png', 'b.mp4']);
|
||||
expect($('.dashboard-contact-files').prop('hidden')).toBe(false);
|
||||
expect($('.dashboard-contact-file').eq(0).find('img').attr('src')).toBe('blob:preview');
|
||||
expect($('.dashboard-contact-file').eq(1).find('img').length).toBe(0);
|
||||
expect($('.dashboard-contact-file-remove').eq(0).attr('aria-label')).toBe('contact_us_attachment_remove_named a.png');
|
||||
});
|
||||
|
||||
it('keeps the files that fit and reports the first rejection', () => {
|
||||
UIDashboardContactDialog();
|
||||
const text = new File(['x'], 'notes.txt', { type: 'text/plain' });
|
||||
pick(png('a.png'), text, png('b.png'));
|
||||
expect(fileNames()).toEqual(['a.png', 'b.png']);
|
||||
expect(status()).toBe('contact_us_attachment_unsupported');
|
||||
});
|
||||
|
||||
it('stops offering to attach once the count cap is reached', () => {
|
||||
UIDashboardContactDialog();
|
||||
pick(...Array.from({ length: MAX_ATTACHMENTS }, (_, i) => png(`${i}.png`)));
|
||||
expect($('.dashboard-contact-dropzone').prop('disabled')).toBe(true);
|
||||
pick(png('extra.png'));
|
||||
expect(fileNames()).toHaveLength(MAX_ATTACHMENTS);
|
||||
expect(status()).toBe(`contact_us_attachment_too_many ${MAX_ATTACHMENTS}`);
|
||||
});
|
||||
|
||||
it('removes the file whose button is pressed and moves focus to the next one', async () => {
|
||||
UIDashboardContactDialog();
|
||||
pick(png('a.png'), png('b.png'), png('c.png'));
|
||||
$('.dashboard-contact-file-remove').eq(1).trigger('click');
|
||||
expect(fileNames()).toEqual(['a.png', 'c.png']);
|
||||
expect(document.activeElement).toBe($('.dashboard-contact-file-remove').get(1));
|
||||
|
||||
message().val('Hello');
|
||||
await submit();
|
||||
expect(fetch.mock.calls[0][1].body.getAll('attachments').map(f => f.name)).toEqual(['a.png', 'c.png']);
|
||||
});
|
||||
|
||||
it('returns focus to the attach button when the last file is removed', () => {
|
||||
UIDashboardContactDialog();
|
||||
pick(png());
|
||||
$('.dashboard-contact-file-remove').trigger('click');
|
||||
expect($('.dashboard-contact-files').prop('hidden')).toBe(true);
|
||||
expect(document.activeElement).toBe($('.dashboard-contact-dropzone').get(0));
|
||||
});
|
||||
|
||||
it('takes files dropped anywhere on the overlay, without letting the drop through', () => {
|
||||
const onWindowDrop = vi.fn();
|
||||
const $win = $('<div class="window"></div>').appendTo('body').on('drop', onWindowDrop);
|
||||
UIDashboardContactDialog({ $container: $win });
|
||||
const $overlay = $('.dashboard-dialog-overlay');
|
||||
|
||||
$overlay.trigger(fileDrag('dragenter'));
|
||||
expect($('.dashboard-contact-dialog').hasClass('dashboard-contact-dragging')).toBe(true);
|
||||
const drop = fileDrag('drop', [png('dropped.png')]);
|
||||
$overlay.trigger(drop);
|
||||
|
||||
expect(drop.isDefaultPrevented()).toBe(true);
|
||||
expect(onWindowDrop).not.toHaveBeenCalled();
|
||||
expect(fileNames()).toEqual(['dropped.png']);
|
||||
expect($('.dashboard-contact-dialog').hasClass('dashboard-contact-dragging')).toBe(false);
|
||||
});
|
||||
|
||||
it('clears the drop highlight when the drag leaves', () => {
|
||||
UIDashboardContactDialog();
|
||||
const $overlay = $('.dashboard-dialog-overlay');
|
||||
$overlay.trigger(fileDrag('dragenter'));
|
||||
$overlay.find('.dashboard-contact-dropzone').trigger(fileDrag('dragenter'));
|
||||
$overlay.find('.dashboard-contact-dropzone').trigger($.Event('dragleave', { originalEvent: nativeEvent({}) }));
|
||||
expect($('.dashboard-contact-dialog').hasClass('dashboard-contact-dragging')).toBe(true);
|
||||
$overlay.trigger($.Event('dragleave', { originalEvent: nativeEvent({}) }));
|
||||
expect($('.dashboard-contact-dialog').hasClass('dashboard-contact-dragging')).toBe(false);
|
||||
});
|
||||
|
||||
it('ignores drags that carry no files', () => {
|
||||
UIDashboardContactDialog();
|
||||
const drag = $.Event('dragenter', { originalEvent: nativeEvent({ dataTransfer: { types: ['text/plain'] } }) });
|
||||
$('.dashboard-dialog-overlay').trigger(drag);
|
||||
expect(drag.isDefaultPrevented()).toBe(false);
|
||||
expect($('.dashboard-contact-dialog').hasClass('dashboard-contact-dragging')).toBe(false);
|
||||
});
|
||||
|
||||
it('attaches an image pasted into the message', () => {
|
||||
UIDashboardContactDialog();
|
||||
const paste = $.Event('paste', {
|
||||
originalEvent: nativeEvent({ clipboardData: { files: [png('pasted.png')], getData: () => '' } }),
|
||||
});
|
||||
message().trigger(paste);
|
||||
expect(fileNames()).toEqual(['pasted.png']);
|
||||
expect(paste.isDefaultPrevented()).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('keyboard', () => {
|
||||
it('sends on Cmd/Ctrl+Enter but not on Enter alone', async () => {
|
||||
UIDashboardContactDialog();
|
||||
message().val('Hello');
|
||||
message().trigger($.Event('keydown', { key: 'Enter' }));
|
||||
await settle();
|
||||
expect(fetch).not.toHaveBeenCalled();
|
||||
|
||||
message().trigger($.Event('keydown', { key: 'Enter', ctrlKey: true }));
|
||||
await settle();
|
||||
expect(fetch).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
@@ -33,7 +33,6 @@ import { startPushWorker } from '../../helpers/pushWorker.js';
|
||||
import { syncBrowserPush } from '../../helpers/pushSync.js';
|
||||
import { get_app_by_uid } from '../../helpers/getAppByUid.js';
|
||||
import launch_app from '../../helpers/launchApp.js';
|
||||
import { runLimited } from '../../helpers/runLimited.js';
|
||||
import {
|
||||
badgeLabel,
|
||||
glyphKey,
|
||||
@@ -47,7 +46,6 @@ import {
|
||||
senderNameFor,
|
||||
setReadAt,
|
||||
takeMarksSince,
|
||||
titleBadge,
|
||||
titleWithBadge,
|
||||
toEntry,
|
||||
unreadCount,
|
||||
@@ -146,6 +144,27 @@ const whenFilesIdle = async (filesTab, timeoutMs = 4_000) => {
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Run `task` over `items`, at most `limit` at a time. Resolves to the items
|
||||
* whose task rejected.
|
||||
*/
|
||||
const runLimited = async (items, limit, task) => {
|
||||
const failed = [];
|
||||
let index = 0;
|
||||
const worker = async () => {
|
||||
while ( index < items.length ) {
|
||||
const item = items[index++];
|
||||
try {
|
||||
await task(item);
|
||||
} catch {
|
||||
failed.push(item);
|
||||
}
|
||||
}
|
||||
};
|
||||
await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
|
||||
return failed;
|
||||
};
|
||||
|
||||
/**
|
||||
* The dashboard's notification center: a bell in the sidebar with the unread
|
||||
* count, a panel listing the most recent notifications read or not, and
|
||||
@@ -341,26 +360,7 @@ export default function UIDashboardNotifications ({ $el_window, socket }) {
|
||||
target.focus({ preventScroll: true });
|
||||
};
|
||||
|
||||
// The badge last put in front of the title, the only prefix replaced.
|
||||
let appliedBadge = '';
|
||||
const applyTitleBadge = () => {
|
||||
const count = unreadCount(entries);
|
||||
const wanted = titleWithBadge(document.title, count, appliedBadge);
|
||||
appliedBadge = titleBadge(count);
|
||||
if ( document.title !== wanted ) document.title = wanted;
|
||||
};
|
||||
|
||||
// Changes made in other tabs arrive one socket event per notification
|
||||
// (Mark all read there sends one ack each), so they redraw once a beat.
|
||||
// Not a frame: a hidden tab's title still carries the count.
|
||||
let renderTimer = null;
|
||||
const scheduleRender = () => {
|
||||
renderTimer ??= setTimeout(render, 50);
|
||||
};
|
||||
|
||||
const render = () => {
|
||||
clearTimeout(renderTimer);
|
||||
renderTimer = null;
|
||||
const hadFocus = $panel[0].contains(document.activeElement);
|
||||
const count = unreadCount(entries);
|
||||
const label = badgeLabel(count);
|
||||
@@ -373,7 +373,7 @@ export default function UIDashboardNotifications ({ $el_window, socket }) {
|
||||
$sidebarToggle.toggleClass('has-unread', count > 0);
|
||||
$count.text(label);
|
||||
$markAll.attr('hidden', count > 0 ? null : '');
|
||||
applyTitleBadge();
|
||||
document.title = titleWithBadge(document.title, count);
|
||||
|
||||
const showLoading = ! loaded && loading !== null;
|
||||
const showError = ! loaded && loadFailed && loading === null;
|
||||
@@ -582,12 +582,9 @@ export default function UIDashboardNotifications ({ $el_window, socket }) {
|
||||
timeout: TOAST_TIMEOUT_MS,
|
||||
// With nothing to open on the dashboard, a click only dismisses;
|
||||
// it mustn't send the apps the user is working in away.
|
||||
// A regrouped notification rewrites the toast under the same uid,
|
||||
// so a click acts on what it says now.
|
||||
click: () => {
|
||||
const current = entries.find((e) => e.uid === entry.uid) ?? entry;
|
||||
if ( notificationTarget(current.notification) === null ) void markRead(current.uid);
|
||||
else void reveal_dashboard().then(() => actOn(current));
|
||||
if ( notificationTarget(notification) === null ) void markRead(entry.uid);
|
||||
else void reveal_dashboard().then(() => actOn(entry));
|
||||
},
|
||||
// The ✕ is a dismissal; timing out is not, so `close` alone acks.
|
||||
close: () => void markRead(entry.uid),
|
||||
@@ -801,8 +798,10 @@ export default function UIDashboardNotifications ({ $el_window, socket }) {
|
||||
// same title again is a no-op, so this can't loop.
|
||||
const titleEl = document.querySelector('title');
|
||||
if ( titleEl ) {
|
||||
new MutationObserver(applyTitleBadge)
|
||||
.observe(titleEl, { childList: true, characterData: true, subtree: true });
|
||||
new MutationObserver(() => {
|
||||
const wanted = titleWithBadge(document.title, unreadCount(entries));
|
||||
if ( document.title !== wanted ) document.title = wanted;
|
||||
}).observe(titleEl, { childList: true, characterData: true, subtree: true });
|
||||
}
|
||||
|
||||
// -- Arrivals -----------------------------------------------------------------
|
||||
@@ -841,7 +840,7 @@ export default function UIDashboardNotifications ({ $el_window, socket }) {
|
||||
acked.set(uid, now);
|
||||
if ( ! entries.some((e) => e.uid === uid && isUnread(e)) ) return;
|
||||
entries = setReadAt(entries, uid, now);
|
||||
scheduleRender();
|
||||
render();
|
||||
});
|
||||
// Removed in another tab. Not gated, for the same reason as the ack.
|
||||
socket.on('notif.removed', ({ uid }) => {
|
||||
@@ -849,7 +848,7 @@ export default function UIDashboardNotifications ({ $el_window, socket }) {
|
||||
removed.set(uid, Date.now());
|
||||
const listed = entries.some((e) => e.uid === uid);
|
||||
dropEntry(uid);
|
||||
if ( listed ) scheduleRender();
|
||||
if ( listed ) render();
|
||||
});
|
||||
// Every (re)connection: anything read elsewhere while this tab was
|
||||
// offline is marked so in the server's list, and anything new is in it.
|
||||
|
||||
@@ -291,24 +291,10 @@ export default function UIItemPropertiesModal ({ name, path: item_path, uid, $co
|
||||
const $link = $(this);
|
||||
if ( $link.prop('disabled') ) return;
|
||||
$link.prop('disabled', true);
|
||||
const subdomain = $link.attr('data-subdomain');
|
||||
puter.hosting.update(subdomain, null).then(() => {
|
||||
puter.hosting.update($link.attr('data-subdomain'), null).then(() => {
|
||||
const $entry = $link.closest('.item-props-website-entry');
|
||||
const $row = $entry.closest('.item-props-row');
|
||||
$entry.remove();
|
||||
// Rows inside the folder carry addresses under the site:
|
||||
// work them out again without it (another site may still
|
||||
// serve them).
|
||||
if ( Array.isArray(window.sites) ) {
|
||||
window.sites = window.sites.filter((site) => site.subdomain !== subdomain);
|
||||
}
|
||||
$('.item').each(function () {
|
||||
const path = this.dataset.path ?? '';
|
||||
if ( ! path.startsWith(`${item_path}/`) ) return;
|
||||
const url = window.determine_website_url?.(path) || '';
|
||||
$(this).attr('data-website_url', url)
|
||||
.find('.item-has-website-url-badge').css('display', url ? 'block' : 'none');
|
||||
});
|
||||
// The focused button just left the DOM; keep focus in the dialog.
|
||||
el_modal.focus({ preventScroll: true });
|
||||
if ( $row.find('.item-props-website-entry').length > 0 ) return;
|
||||
|
||||
@@ -68,40 +68,4 @@ describe('UIItemPropertiesModal', () => {
|
||||
expect(window.update_sites_cache).toHaveBeenCalled();
|
||||
expect(puter._cache.del).toHaveBeenCalledWith('readdir:/alice');
|
||||
});
|
||||
|
||||
it('takes the site address off rows inside the folder, keeping one another site serves', async () => {
|
||||
const fsentry = { uid: 'u1', name: 'site', path: '/alice/site', is_dir: true, has_website: true };
|
||||
$('<div class="item" data-uid="u1" data-has_website="1"><img class="item-has-website-badge"></div>')
|
||||
.data('fsentry', fsentry).appendTo('body');
|
||||
const child = (path, url) => $(`<div class="item" data-path="${path}" data-website_url="${url}"><img class="item-has-website-url-badge" style="display:block"></div>`).appendTo('body');
|
||||
const $inside = child('/alice/site/a.txt', 'https://mysite.puter.site/a.txt');
|
||||
const $nested = child('/alice/site/docs/b.txt', 'https://docs.puter.site/b.txt');
|
||||
const site = (subdomain, path) => ({ subdomain, root_dir: { path, subdomains: [{ subdomain, address: `https://${subdomain}.puter.site` }] } });
|
||||
window.sites = [site('mysite', '/alice/site'), site('docs', '/alice/site/docs')];
|
||||
window.determine_website_url = (path) => {
|
||||
const match = window.sites.find((s) => path.startsWith(`${s.root_dir.path}/`));
|
||||
return match ? `https://${match.subdomain}.puter.site${path.slice(match.root_dir.path.length)}` : null;
|
||||
};
|
||||
window.extractSubdomain = () => 'mysite';
|
||||
window.update_sites_cache = vi.fn();
|
||||
globalThis.puter = {
|
||||
fs: { stat: vi.fn(({ success }) => {
|
||||
success({ ...fsentry, id: 'u1', modified: 1700000000, created: 1700000000, subdomains: [{ uuid: 's1', address: 'https://mysite.puter.site' }] });
|
||||
return Promise.resolve();
|
||||
}) },
|
||||
hosting: { update: vi.fn(async () => ({})) },
|
||||
fsCacheKey: (kind, path) => `${kind}:${path}`,
|
||||
_cache: { del: vi.fn() },
|
||||
};
|
||||
|
||||
UIItemPropertiesModal({ name: 'site', path: '/alice/site', uid: 'u1' });
|
||||
await tick();
|
||||
$('.item-props-disassociate').trigger('click');
|
||||
await tick();
|
||||
|
||||
expect($inside.attr('data-website_url')).toBe('');
|
||||
expect($inside.find('.item-has-website-url-badge').css('display')).toBe('none');
|
||||
expect($nested.attr('data-website_url')).toBe('https://docs.puter.site/b.txt');
|
||||
expect($nested.find('.item-has-website-url-badge').css('display')).toBe('block');
|
||||
});
|
||||
});
|
||||
@@ -17,14 +17,13 @@
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
// The Files tab's publish flows, a folder as a website (optionally on a
|
||||
// custom domain) and a .js file as a worker: dashboard form dialogs rather
|
||||
// than desktop windows.
|
||||
// The Files tab's publish flows, a folder as a website and a .js file as a
|
||||
// worker: dashboard form dialogs rather than desktop windows.
|
||||
|
||||
import ensure_can_publish from '../../helpers/ensureCanPublish.js';
|
||||
import forget_parent_listing from '../../helpers/forgetParentListing.js';
|
||||
import { SVG } from './UIDashboardDialog.js';
|
||||
import UIDashboardFormDialog, { copyRowHtml } from './UIDashboardFormDialog.js';
|
||||
import { openLinkHtml, publishDomainFields, setupPublishDomain } from './publishDomain.js';
|
||||
import { finalizePublishName, normalizePublishName, PUBLISH_NAME_RULES } from './publishName.js';
|
||||
|
||||
/**
|
||||
@@ -37,6 +36,8 @@ import { finalizePublishName, normalizePublishName, PUBLISH_NAME_RULES } from '.
|
||||
|
||||
const t = (key) => i18n(key, [], false);
|
||||
|
||||
const OPEN_ICON = SVG('<path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/><path d="M15 3h6v6"/><path d="M10 14L21 3"/>');
|
||||
|
||||
/** Rows showing `path` or anything under it, on the dashboard or the desktop. */
|
||||
const each_item_at = (path, fn) => $('.item').each(function () {
|
||||
const item_path = this.dataset.path ?? '';
|
||||
@@ -53,8 +54,6 @@ const KINDS = {
|
||||
nameErrors: new Set(['conflict', 'subdomain_reserved']),
|
||||
suffix: () => `.${window.hosting_domain}`,
|
||||
requiresVerification: () => !! window.require_email_verification_to_publish_website,
|
||||
extraFields: publishDomainFields,
|
||||
setup: setupPublishDomain,
|
||||
async publish (name, path) {
|
||||
const site = await puter.hosting.create(name, path);
|
||||
// The server's address carries the deployment's real scheme (a
|
||||
@@ -137,11 +136,6 @@ const open_publish_dialog = async (kind_name, { name, path, ...opts }) => {
|
||||
}];
|
||||
fields.push(...(kind.extraFields?.() ?? []));
|
||||
|
||||
/** Set once the site is live; a retry for a step after it skips publishing. */
|
||||
let published = null;
|
||||
/** @type {import('./publishDomain.js').PublishDomain | undefined} */
|
||||
let extra;
|
||||
|
||||
const dialog = UIDashboardFormDialog({
|
||||
...opts,
|
||||
title: t(kind.title),
|
||||
@@ -150,52 +144,30 @@ const open_publish_dialog = async (kind_name, { name, path, ...opts }) => {
|
||||
fields,
|
||||
async onSubmit () {
|
||||
const values = dialog.values();
|
||||
const hostname = extra?.prepare(!! published) ?? null;
|
||||
if ( hostname === false ) return;
|
||||
if ( ! published ) {
|
||||
const subdomain = finalizePublishName(values.name, kind.rule);
|
||||
dialog.field('name').val(subdomain);
|
||||
if ( ! subdomain ) {
|
||||
dialog.setStatus(t('publish_name_required'), { field: 'name' });
|
||||
return;
|
||||
}
|
||||
let url;
|
||||
try {
|
||||
url = await kind.publish(subdomain, path, values);
|
||||
} catch ( err ) {
|
||||
const code = err?.error?.code ?? err?.code;
|
||||
dialog.setStatus(error_message(err), kind.nameErrors.has(code) ? { field: 'name' } : undefined);
|
||||
return;
|
||||
}
|
||||
kind.markPublished(path, url);
|
||||
published = { name: subdomain, url };
|
||||
// The address is taken now; what's left to retry is the domain.
|
||||
dialog.field('name').prop('readOnly', true).attr('aria-readonly', 'true');
|
||||
update_submit_label();
|
||||
const subdomain = finalizePublishName(values.name, kind.rule);
|
||||
dialog.field('name').val(subdomain);
|
||||
if ( ! subdomain ) {
|
||||
dialog.setStatus(t('publish_name_required'), { field: 'name' });
|
||||
return;
|
||||
}
|
||||
const domain = hostname ? await extra.attach(hostname, published) : null;
|
||||
if ( hostname && ! domain ) return;
|
||||
let url;
|
||||
try {
|
||||
url = await kind.publish(subdomain, path, values);
|
||||
} catch ( err ) {
|
||||
const code = err?.error?.code ?? err?.code;
|
||||
dialog.setStatus(error_message(err), kind.nameErrors.has(code) ? { field: 'name' } : undefined);
|
||||
return;
|
||||
}
|
||||
kind.markPublished(path, url);
|
||||
const open_link = `<a class="dashboard-dialog-btn dashboard-dialog-btn-quiet dashboard-icon-btn dashboard-publish-open" href="${html_encode(url)}"`
|
||||
+ ` target="_blank" rel="noopener noreferrer" aria-label="${i18n('open_in_new_tab')}" title="${i18n('open_in_new_tab')}">${OPEN_ICON}</a>`;
|
||||
dialog.finish({
|
||||
message: t(kind.published),
|
||||
html: copyRowHtml({ value: published.url, label: t('publish_address'), compact: true, after: openLinkHtml(published.url) })
|
||||
+ (domain ? extra.doneHtml(domain) : ''),
|
||||
// The DNS records are shown only here.
|
||||
keepOnBackdrop: !! domain,
|
||||
html: copyRowHtml({ value: url, label: t('publish_address'), compact: true, after: open_link }),
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
// Before the site is live the button publishes; after, it adds the domain.
|
||||
const update_submit_label = () => {
|
||||
let key = 'publish';
|
||||
if ( published ) {
|
||||
if ( extra?.claiming() ) key = 'custom_domain_verify_and_add';
|
||||
else key = extra?.addable() ? 'custom_domain_add' : 'done';
|
||||
}
|
||||
dialog.$dialog.find('.dashboard-form-submit-label').text(t(key));
|
||||
};
|
||||
extra = kind.setup?.(dialog, { onChange: update_submit_label });
|
||||
|
||||
// Shape the name as it's typed, keeping the caret where it was.
|
||||
const el_name = dialog.field('name').get(0);
|
||||
if ( document.activeElement === el_name ) el_name.select();
|
||||
|
||||
@@ -35,59 +35,13 @@ const { openPublishWebsiteDialog, openPublishWorkerDialog } = await import('./UI
|
||||
const { default: ensure_can_publish } = await import('../../helpers/ensureCanPublish.js');
|
||||
|
||||
const settle = () => new Promise(resolve => setTimeout(resolve, 0));
|
||||
const flush = async () => {
|
||||
for ( let i = 0; i < 5; i++ ) await settle();
|
||||
};
|
||||
const nameField = () => $('.dashboard-form-input[name="name"]');
|
||||
const status = () => $('.dashboard-form-status').text();
|
||||
|
||||
const submitWith = async (name) => {
|
||||
if ( name !== undefined ) nameField().val(name);
|
||||
$('.dashboard-form-dialog').trigger('submit');
|
||||
await flush();
|
||||
};
|
||||
|
||||
const json = (code, data) => new Response(JSON.stringify(data), {
|
||||
status: code,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
});
|
||||
|
||||
/**
|
||||
* Stands in for the `/custom-domains` API. The list call answers with
|
||||
* `list`; anything else with its entry in `routes` (keyed `METHOD /path`),
|
||||
* or a 404.
|
||||
*/
|
||||
const serveDomains = ({ list = { items: [], canAdd: true, pricing: { amount: 0.5, currency: 'USD' } }, routes = {} } = {}) => {
|
||||
globalThis.fetch = vi.fn(async (url, opts = {}) => {
|
||||
const key = `${opts.method ?? 'GET'} ${String(url).split('/custom-domains')[1]}`;
|
||||
if ( key === 'GET ' ) return json(200, typeof list === 'function' ? list() : list);
|
||||
return routes[key]?.(opts.body ? JSON.parse(opts.body) : undefined) ?? json(404, {});
|
||||
});
|
||||
};
|
||||
const requests = (method) => fetch.mock.calls
|
||||
.filter(([, opts = {}]) => (opts.method ?? 'GET') === method)
|
||||
.map(([url, opts]) => ({ path: String(url).split('/custom-domains')[1], body: opts.body ? JSON.parse(opts.body) : undefined }));
|
||||
|
||||
const pendingDomain = (overrides = {}) => ({
|
||||
uuid: 'd1',
|
||||
hostname: 'www.example.com',
|
||||
site: 'my-site',
|
||||
status: 'pending',
|
||||
isApex: false,
|
||||
records: [{ type: 'CNAME', name: 'www', value: 'my-site.puter.site', purpose: 'routing', required: true }],
|
||||
...overrides,
|
||||
});
|
||||
|
||||
const domainSwitch = () => $('.dashboard-form-input[name="useDomain"]');
|
||||
const domainField = () => $('.dashboard-form-input[name="domain"]');
|
||||
const shown = (name) => $(`.dashboard-form-field[data-field="${name}"]`).prop('hidden') === false;
|
||||
const submitLabel = () => $('.dashboard-form-submit-label').text();
|
||||
const turnOnDomain = () => domainSwitch().prop('checked', true).trigger('change');
|
||||
|
||||
/** Opens the website dialog and waits for the custom domain list. */
|
||||
const openWebsite = async () => {
|
||||
await openPublishWebsiteDialog({ name: 'Site', path: '/alice/Site' });
|
||||
await flush();
|
||||
for ( let i = 0; i < 5; i++ ) await settle();
|
||||
};
|
||||
|
||||
const addRow = (path) => {
|
||||
@@ -105,10 +59,6 @@ beforeEach(() => {
|
||||
window.generate_identifier = () => 'clever-idea-42';
|
||||
window.update_sites_cache = vi.fn();
|
||||
window.require_email_verification_to_publish_website = false;
|
||||
window.api_origin = 'https://api.puter.test';
|
||||
delete window.UIUpgradeAccount;
|
||||
// A Puter without custom domains, unless a test serves them.
|
||||
globalThis.fetch = vi.fn(async () => json(404, {}));
|
||||
globalThis.puter = {
|
||||
fsCacheKey: (kind, path) => `${kind}:${path}`,
|
||||
_cache: { del: vi.fn() },
|
||||
@@ -176,7 +126,7 @@ describe('publish website', () => {
|
||||
expect(nameField().val()).toBe('cafe');
|
||||
});
|
||||
|
||||
it('asks for an address when nothing usable was typed', async () => {
|
||||
it('asks for an address when nothing usable was typed', async () => {
|
||||
await openPublishWebsiteDialog({ name: 'Site', path: '/alice/Site' });
|
||||
await submitWith('---');
|
||||
expect(status()).toBe('publish_name_required');
|
||||
@@ -214,358 +164,6 @@ describe('publish website', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('publish website on a custom domain', () => {
|
||||
it('leaves the option out where the server has no custom domains', async () => {
|
||||
await openWebsite();
|
||||
expect(shown('useDomain')).toBe(false);
|
||||
expect(shown('domain')).toBe(false);
|
||||
await submitWith('my-site');
|
||||
expect(puter.hosting.create).toHaveBeenCalledWith('my-site', '/alice/Site');
|
||||
expect(requests('POST')).toEqual([]);
|
||||
});
|
||||
|
||||
it('asks for the domain once the switch is on, with what it costs', async () => {
|
||||
serveDomains();
|
||||
await openWebsite();
|
||||
expect(shown('useDomain')).toBe(true);
|
||||
expect(shown('domain')).toBe(false);
|
||||
|
||||
turnOnDomain();
|
||||
|
||||
expect(shown('domain')).toBe(true);
|
||||
expect(document.activeElement).toBe(domainField().get(0));
|
||||
expect($('.dashboard-form-field[data-field="domain"] .dashboard-form-hint').text())
|
||||
.toBe('publish_custom_domain_dns_hint custom_domain_price_note');
|
||||
expect($('.dashboard-publish-upsell').prop('hidden')).toBe(true);
|
||||
});
|
||||
|
||||
it('publishes the site, adds the domain, and shows the records to set', async () => {
|
||||
serveDomains({ routes: { 'POST ': () => json(201, pendingDomain()) } });
|
||||
await openWebsite();
|
||||
turnOnDomain();
|
||||
domainField().val('https://WWW.Example.com/about');
|
||||
|
||||
await submitWith('my-site');
|
||||
|
||||
expect(puter.hosting.create).toHaveBeenCalledWith('my-site', '/alice/Site');
|
||||
expect(requests('POST')).toEqual([{ path: '', body: { site: 'my-site', hostname: 'www.example.com' } }]);
|
||||
expect($('.dashboard-form-done p').text()).toBe('website_published');
|
||||
expect($('.dashboard-copy-value').first().val()).toBe('https://my-site.puter.site');
|
||||
expect($('.dashboard-publish-domain-host').text()).toBe('www.example.com');
|
||||
expect($('.dashboard-publish-domain-badge').attr('data-status')).toBe('pending');
|
||||
expect($('.dashboard-dns-record-type').text()).toBe('CNAME');
|
||||
expect($('.dashboard-dns-record .dashboard-copy-value').map((_, el) => el.value).get())
|
||||
.toEqual(['www', 'my-site.puter.site']);
|
||||
});
|
||||
|
||||
it('keeps the records up through a stray click outside the card', async () => {
|
||||
serveDomains({ routes: { 'POST ': () => json(201, pendingDomain()) } });
|
||||
await openWebsite();
|
||||
turnOnDomain();
|
||||
domainField().val('www.example.com');
|
||||
await submitWith('my-site');
|
||||
|
||||
const $backdrop = $('.dashboard-dialog-overlay');
|
||||
$backdrop.trigger('mousedown').trigger('click');
|
||||
await flush();
|
||||
expect($backdrop.hasClass('dashboard-dialog-show')).toBe(true);
|
||||
expect($('.dashboard-dns-record')).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('checks the domain again and shows its address once connected', async () => {
|
||||
serveDomains({
|
||||
routes: {
|
||||
'POST ': () => json(201, pendingDomain()),
|
||||
'GET /d1': () => json(200, pendingDomain({ status: 'active', records: [] })),
|
||||
},
|
||||
});
|
||||
await openWebsite();
|
||||
turnOnDomain();
|
||||
domainField().val('www.example.com');
|
||||
await submitWith('my-site');
|
||||
|
||||
$('.dashboard-publish-domain-check').trigger('click');
|
||||
await flush();
|
||||
|
||||
expect(requests('GET').map((r) => r.path)).toContain('/d1');
|
||||
expect($('.dashboard-publish-domain-badge').attr('data-status')).toBe('active');
|
||||
expect($('.dashboard-publish-domain .dashboard-copy-value').val()).toBe('https://www.example.com');
|
||||
expect($('.dashboard-publish-domain-status').text()).toBe('custom_domain_success_note');
|
||||
expect($('.dashboard-publish-domain-check')).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('announces a check in the status region already on screen', async () => {
|
||||
serveDomains({
|
||||
routes: {
|
||||
'POST ': () => json(201, pendingDomain()),
|
||||
'GET /d1': () => json(200, pendingDomain()),
|
||||
},
|
||||
});
|
||||
await openWebsite();
|
||||
turnOnDomain();
|
||||
domainField().val('www.example.com');
|
||||
await submitWith('my-site');
|
||||
const el_status = $('.dashboard-publish-domain-status').get(0);
|
||||
|
||||
$('.dashboard-publish-domain-check').trigger('click');
|
||||
await flush();
|
||||
|
||||
expect($('.dashboard-publish-domain-status').get(0)).toBe(el_status);
|
||||
expect(el_status.textContent).toBe('custom_domain_status_pending');
|
||||
// The redrawn records are not read out again.
|
||||
expect($('.dashboard-dns-record').closest('[aria-live]').attr('aria-live')).toBe('off');
|
||||
});
|
||||
|
||||
it('runs one domain action at a time on the done screen', async () => {
|
||||
let answer_check;
|
||||
serveDomains({
|
||||
routes: {
|
||||
'POST ': () => json(201, pendingDomain({ hostname: 'example.com', isApex: true })),
|
||||
'GET /d1': () => new Promise((resolve) => {
|
||||
answer_check = () => resolve(json(200, pendingDomain({ hostname: 'example.com', isApex: true })));
|
||||
}),
|
||||
'POST /d1/use-www': () => json(200, pendingDomain({ redirectFrom: 'example.com' })),
|
||||
},
|
||||
});
|
||||
await openWebsite();
|
||||
turnOnDomain();
|
||||
domainField().val('example.com');
|
||||
await submitWith('my-site');
|
||||
|
||||
$('.dashboard-publish-domain-check').trigger('click');
|
||||
await flush();
|
||||
expect($('.dashboard-publish-domain-www').prop('disabled')).toBe(true);
|
||||
$('.dashboard-publish-domain-www').trigger('click');
|
||||
await flush();
|
||||
expect(requests('POST').map((r) => r.path)).not.toContain('/d1/use-www');
|
||||
|
||||
answer_check();
|
||||
await flush();
|
||||
expect($('.dashboard-publish-domain-www').prop('disabled')).toBe(false);
|
||||
});
|
||||
|
||||
it('stops before publishing when the domain is not one', async () => {
|
||||
serveDomains();
|
||||
await openWebsite();
|
||||
turnOnDomain();
|
||||
domainField().val('localhost');
|
||||
|
||||
await submitWith('my-site');
|
||||
|
||||
expect(status()).toBe('custom_domain_error_invalid');
|
||||
expect(domainField().attr('aria-invalid')).toBe('true');
|
||||
expect(puter.hosting.create).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('keeps the live site and retries only the domain when adding it fails', async () => {
|
||||
const add = vi.fn()
|
||||
.mockReturnValueOnce(json(409, { code: 'custom_domain_taken', message: 'That hostname is already in use' }))
|
||||
.mockReturnValueOnce(json(201, pendingDomain({ hostname: 'www.example.org' })));
|
||||
serveDomains({ routes: { 'POST ': add } });
|
||||
await openWebsite();
|
||||
turnOnDomain();
|
||||
domainField().val('www.example.com');
|
||||
|
||||
await submitWith('my-site');
|
||||
|
||||
expect(status()).toBe('publish_domain_failed\ncustom_domain_error_taken');
|
||||
expect(domainField().attr('aria-invalid')).toBe('true');
|
||||
expect(nameField().prop('readOnly')).toBe(true);
|
||||
expect(submitLabel()).toBe('custom_domain_add');
|
||||
// Published now, so the hint no longer speaks of "after publishing".
|
||||
expect($('.dashboard-form-field[data-field="domain"] .dashboard-form-hint').text()).toBe('custom_domain_price_note');
|
||||
|
||||
domainField().val('www.example.org');
|
||||
await submitWith();
|
||||
|
||||
expect(puter.hosting.create).toHaveBeenCalledTimes(1);
|
||||
expect(add).toHaveBeenLastCalledWith({ site: 'my-site', hostname: 'www.example.org' });
|
||||
expect($('.dashboard-publish-domain-host').text()).toBe('www.example.org');
|
||||
});
|
||||
|
||||
it('finishes with just the site when the domain is turned off after a failure', async () => {
|
||||
serveDomains({ routes: { 'POST ': () => json(409, { code: 'custom_domain_taken' }) } });
|
||||
await openWebsite();
|
||||
turnOnDomain();
|
||||
domainField().val('www.example.com');
|
||||
await submitWith('my-site');
|
||||
|
||||
domainSwitch().prop('checked', false).trigger('change');
|
||||
expect(submitLabel()).toBe('done');
|
||||
await submitWith();
|
||||
|
||||
expect(puter.hosting.create).toHaveBeenCalledTimes(1);
|
||||
expect($('.dashboard-form-done p').text()).toBe('website_published');
|
||||
expect($('.dashboard-publish-domain')).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('moves a domain already on the account instead of adding it again', async () => {
|
||||
serveDomains({
|
||||
list: { items: [pendingDomain({ site: 'old-site', status: 'active' })], canAdd: true },
|
||||
routes: { 'PATCH /d1': () => json(200, pendingDomain({ status: 'active' })) },
|
||||
});
|
||||
await openWebsite();
|
||||
turnOnDomain();
|
||||
expect($(`#${domainField().attr('list')} option`).map((_, el) => el.value).get()).toEqual(['www.example.com']);
|
||||
domainField().val('www.example.com').trigger('input');
|
||||
expect($('.dashboard-form-field[data-field="domain"] .dashboard-form-hint').text()).toBe('publish_custom_domain_moves');
|
||||
|
||||
await submitWith('my-site');
|
||||
|
||||
expect(requests('POST')).toEqual([]);
|
||||
expect(requests('PATCH')).toEqual([{ path: '/d1', body: { site: 'my-site' } }]);
|
||||
expect($('.dashboard-publish-domain-badge').attr('data-status')).toBe('active');
|
||||
});
|
||||
|
||||
it('says the www hostname serves the site and the root domain forwards to it', async () => {
|
||||
serveDomains({
|
||||
routes: {
|
||||
'POST ': () => json(201, pendingDomain({
|
||||
redirectFrom: 'example.com',
|
||||
records: [
|
||||
{ type: 'CNAME', name: 'www', value: 'my-site.puter.site', purpose: 'routing', required: true },
|
||||
{ type: 'A', name: '@', value: '192.0.2.1', purpose: 'redirect', required: true },
|
||||
],
|
||||
})),
|
||||
},
|
||||
});
|
||||
await openWebsite();
|
||||
turnOnDomain();
|
||||
domainField().val('www.example.com');
|
||||
const i18n_stub = globalThis.i18n;
|
||||
globalThis.i18n = (key, replacements) => (Array.isArray(replacements) && replacements.length ? `${key}:${replacements.join('|')}` : key);
|
||||
try {
|
||||
await submitWith('my-site');
|
||||
} finally {
|
||||
globalThis.i18n = i18n_stub;
|
||||
}
|
||||
|
||||
expect($('.dashboard-publish-domain .dashboard-form-hint').last().text())
|
||||
.toBe('custom_domain_redirect_note:www.example.com|example.com');
|
||||
});
|
||||
|
||||
it('shows the ownership record for a domain held by another account', async () => {
|
||||
const add = vi.fn(() => json(409, {
|
||||
code: 'custom_domain_claim_required',
|
||||
verification: { name: '_puter.www.example.com', value: 'token-1' },
|
||||
}));
|
||||
serveDomains({ routes: { 'POST ': add } });
|
||||
await openWebsite();
|
||||
turnOnDomain();
|
||||
domainField().val('www.example.com');
|
||||
|
||||
await submitWith('my-site');
|
||||
|
||||
expect($('.dashboard-publish-claim').prop('hidden')).toBe(false);
|
||||
expect($('.dashboard-publish-claim .dashboard-dns-record-type').text()).toBe('TXT');
|
||||
expect($('.dashboard-publish-claim .dashboard-copy-value').map((_, el) => el.value).get())
|
||||
.toEqual(['_puter.www.example.com', 'token-1']);
|
||||
expect(submitLabel()).toBe('custom_domain_verify_and_add');
|
||||
expect(status()).toBe('publish_site_live');
|
||||
|
||||
await submitWith();
|
||||
expect(status()).toBe('publish_domain_failed\ncustom_domain_claim_not_found');
|
||||
|
||||
// A claim is for one hostname; editing it starts over.
|
||||
domainField().val('www.example.net').trigger('input');
|
||||
expect($('.dashboard-publish-claim').prop('hidden')).toBe(true);
|
||||
expect(submitLabel()).toBe('custom_domain_add');
|
||||
|
||||
// Back to the claimed hostname, its record and the verify step return together.
|
||||
domainField().val('www.example.com').trigger('input');
|
||||
expect($('.dashboard-publish-claim').prop('hidden')).toBe(false);
|
||||
expect(submitLabel()).toBe('custom_domain_verify_and_add');
|
||||
});
|
||||
|
||||
describe('on a plan without custom domains', () => {
|
||||
beforeEach(() => {
|
||||
window.UIUpgradeAccount = vi.fn(function () {
|
||||
this.open_as_window = vi.fn();
|
||||
});
|
||||
});
|
||||
|
||||
it('offers the upgrade in place of the field, leaving focus on the switch', async () => {
|
||||
serveDomains({ list: { items: [], canAdd: false } });
|
||||
await openWebsite();
|
||||
domainSwitch().get(0).focus();
|
||||
turnOnDomain();
|
||||
|
||||
expect(shown('domain')).toBe(false);
|
||||
expect($('.dashboard-publish-upsell').prop('hidden')).toBe(false);
|
||||
expect(document.activeElement).toBe(domainSwitch().get(0));
|
||||
$('.dashboard-publish-upgrade').trigger('click');
|
||||
expect(window.UIUpgradeAccount).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('does not publish while the switch asks for a domain it cannot add', async () => {
|
||||
serveDomains({ list: { items: [], canAdd: false } });
|
||||
await openWebsite();
|
||||
turnOnDomain();
|
||||
await submitWith('my-site');
|
||||
expect(status()).toBe('publish_custom_domain_needs_plan');
|
||||
expect(puter.hosting.create).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('unlocks the field once the upgrade goes through', async () => {
|
||||
let can_add = false;
|
||||
serveDomains({ list: () => ({ items: [], canAdd: can_add }) });
|
||||
await openWebsite();
|
||||
turnOnDomain();
|
||||
$('.dashboard-publish-upgrade').trigger('click');
|
||||
|
||||
can_add = true;
|
||||
window.dispatchEvent(new CustomEvent('puter:subscription:changed'));
|
||||
await flush();
|
||||
|
||||
expect(shown('domain')).toBe(true);
|
||||
expect($('.dashboard-publish-upsell').prop('hidden')).toBe(true);
|
||||
expect(document.activeElement).toBe(domainField().get(0));
|
||||
});
|
||||
|
||||
it('only listens for a plan change once it has offered the upgrade', async () => {
|
||||
serveDomains({ list: { items: [], canAdd: false } });
|
||||
const listen = vi.spyOn(window, 'addEventListener');
|
||||
try {
|
||||
await openWebsite();
|
||||
turnOnDomain();
|
||||
expect(listen.mock.calls.map(([type]) => type)).not.toContain('puter:subscription:changed');
|
||||
$('.dashboard-publish-upgrade').trigger('click');
|
||||
expect(listen.mock.calls.map(([type]) => type)).toContain('puter:subscription:changed');
|
||||
} finally {
|
||||
listen.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
it('explains the plan without a button where there is no upgrade flow', async () => {
|
||||
delete window.UIUpgradeAccount;
|
||||
serveDomains({ list: { items: [], canAdd: false } });
|
||||
await openWebsite();
|
||||
turnOnDomain();
|
||||
expect($('.dashboard-publish-upgrade')).toHaveLength(0);
|
||||
await submitWith('my-site');
|
||||
expect(status()).toBe('custom_domain_error_plan');
|
||||
});
|
||||
|
||||
it('finishes with the live site when adding the domain turns out to need a plan', async () => {
|
||||
serveDomains({ routes: { 'POST ': () => json(402, { code: 'subscription_required' }) } });
|
||||
await openWebsite();
|
||||
turnOnDomain();
|
||||
domainField().val('www.example.com');
|
||||
await submitWith('my-site');
|
||||
|
||||
expect(status()).toBe('publish_domain_failed\ncustom_domain_error_plan');
|
||||
expect($('.dashboard-publish-upsell').prop('hidden')).toBe(false);
|
||||
expect(submitLabel()).toBe('done');
|
||||
|
||||
await submitWith();
|
||||
expect(puter.hosting.create).toHaveBeenCalledTimes(1);
|
||||
expect(requests('POST')).toHaveLength(1);
|
||||
expect($('.dashboard-form-done p').text()).toBe('website_published');
|
||||
expect($('.dashboard-publish-domain')).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('publish worker', () => {
|
||||
it('always needs a verified account', async () => {
|
||||
await openPublishWorkerDialog({ name: 'api.js', path: '/alice/api.js' });
|
||||
|
||||
Loaded 100 of 199 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user