mirror of
https://github.com/HeyPuter/puter.git
synced 2026-11-13 20:12:57 -10:00
Compare commits
13
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6704fa64ed | ||
|
|
917daf12af | ||
|
|
f7c0fdda9f | ||
|
|
4efd966be9 | ||
|
|
11c519ed08 | ||
|
|
41f6edeab1 | ||
|
|
7ca1d97ef3 | ||
|
|
40eed41ce5 | ||
|
|
3ef18a2259 | ||
|
|
1621da6bf9 | ||
|
|
10e4606b9c | ||
|
|
6d06c23cc7 | ||
|
|
b30e1c9af5 |
No files matched your search
@@ -259,36 +259,6 @@ no user to name), puter.js opens the dashboard's upgrade page in a new tab with
|
||||
what was refused, through a consent dialog when the click has expired or the
|
||||
tab is blocked, and `requestUpgrade()` resolves `{ upgraded: false }`.
|
||||
|
||||
## Top-up
|
||||
|
||||
`GET /embed/top-up` is the deployment's top-up dialog, where a user with a plan
|
||||
buys add-on credit, served and framed like the upgrade: a transparent GUI page
|
||||
covering the host with no box or close button, allowing `payment` and
|
||||
`otp-credentials`, with Escape left to the dialog. Its fragment names `user`.
|
||||
|
||||
puter.js frames it for the **Add credits** item of `<puter-user-menu>`, which
|
||||
shows only when whoami reports `subscribed: true` and no `team` paying for the
|
||||
account. On a page that can't frame the GUI, the item opens the dashboard with
|
||||
`?topup=` in a new tab instead.
|
||||
|
||||
The GUI reports `unavailable` unless its session belongs to `user`, the account
|
||||
has no verification or password change waiting, and the deployment defines
|
||||
`window.UITopUp` with `UITopUp.embeddable === true`. Otherwise it runs:
|
||||
|
||||
```js
|
||||
new UITopUp({ onClose }).open();
|
||||
```
|
||||
|
||||
`open()` resolves once the dialog has loaded the account and shows what it can
|
||||
buy, and `onClose({ toppedUp })` must run exactly once, when the dialog closes
|
||||
or when it declines to open for the account. The GUI then posts `{ msg: 'puterPopupFrame', state: 'closed', toppedUp }`
|
||||
and the page removes the frame. When the frame can't show the top-up, puter.js
|
||||
opens the dashboard's top-up in a new tab, as it does the upgrade.
|
||||
|
||||
While the top-up shows, a call refused for funds still rejects but opens no
|
||||
usage limit dialog over it, and `requestUpgrade()` frames nothing over it: it
|
||||
resolves `{ upgraded: false }` once the top-up closes.
|
||||
|
||||
## Email confirmation
|
||||
|
||||
`GET /embed/request-email-confirmation` walks a first-party page's user through
|
||||
@@ -329,7 +299,7 @@ Chromium installed), and the backend route tests:
|
||||
|
||||
```sh
|
||||
npx vitest run --config src/gui/vitest.config.js src/gui/src/UI/Dashboard/AppBrowser src/feedbackEmbed
|
||||
npx vitest run src/puter-js/src/lib/guiEmbed.test.js src/puter-js/src/modules/UI.showFeedbackDialog.test.js src/puter-js/src/modules/Auth.signInFrame.test.js src/puter-js/src/modules/UI.pickerFrame.test.js src/puter-js/src/modules/UI.requestUpgrade.test.js src/puter-js/src/modules/UI.showTopUp.test.js src/puter-js/src/lib/upgradePrompt.test.js src/puter-js/src/modules/UsageLimitDialog.upgrade.test.js
|
||||
npx vitest run src/puter-js/src/lib/guiEmbed.test.js src/puter-js/src/modules/UI.showFeedbackDialog.test.js src/puter-js/src/modules/Auth.signInFrame.test.js src/puter-js/src/modules/UI.pickerFrame.test.js src/puter-js/src/modules/UI.requestUpgrade.test.js src/puter-js/src/lib/upgradePrompt.test.js src/puter-js/src/modules/UsageLimitDialog.upgrade.test.js
|
||||
npx vitest run --config src/gui/vitest.config.js src/gui/src/helpers/popupFrame.test.js
|
||||
npx vitest run --config src/backend/vitest.config.ts src/backend/server.test.ts
|
||||
```
|
||||
@@ -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,
|
||||
|
||||
@@ -36,9 +36,9 @@ import type {
|
||||
|
||||
/**
|
||||
* GUI popups a first-party page can show in a frame at `/embed/<action>`,
|
||||
* instead of opening `/action/<action>` in a window, plus the upgrade and
|
||||
* top-up dialogs, which it would otherwise open in a dashboard tab, and the
|
||||
* email confirmation, which it otherwise can't show.
|
||||
* instead of opening `/action/<action>` in a window, plus the upgrade 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',
|
||||
@@ -46,7 +46,6 @@ export const FRAMED_POPUP_ACTIONS = [
|
||||
'show-save-file-picker',
|
||||
'show-directory-picker',
|
||||
'upgrade',
|
||||
'top-up',
|
||||
'request-email-confirmation',
|
||||
] as const;
|
||||
|
||||
|
||||
@@ -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,
|
||||
)
|
||||
);
|
||||
};
|
||||
@@ -330,11 +330,14 @@ export class AppDriver extends PuterDriver {
|
||||
}
|
||||
|
||||
/**
|
||||
* Paged listing of the caller's own apps. Apps owned by anyone else are
|
||||
* reachable only by name or uid, through `read` and `/query/app`.
|
||||
* Paged app listing. Unlike `/query/app`, which answers only for apps named
|
||||
* by the caller and so must not confirm ones it may not see, this is the
|
||||
* listing surface a launcher reads: `protected` apps are filtered by the
|
||||
* permission check below, and everything else is listable by design. Narrow
|
||||
* it with `predicate: ['user-can-edit']` to the caller's own.
|
||||
*/
|
||||
async select(args = {}) {
|
||||
const { params = {} } = args;
|
||||
const { predicate, params = {} } = args;
|
||||
const actor = requireContextActor();
|
||||
this.#requireUserOrAppActor(actor);
|
||||
|
||||
@@ -350,12 +353,16 @@ export class AppDriver extends PuterDriver {
|
||||
const includeTotal = args.includeTotal === true;
|
||||
const paginated = hasCursor || offset !== undefined || includeTotal;
|
||||
|
||||
// Always the caller's own. `predicate: ['user-can-edit']` asks for the
|
||||
// same thing and is accepted for older clients.
|
||||
const ownerUserId = actor.user.id;
|
||||
const filters = {};
|
||||
// predicate: ['user-can-edit'] → scope to owner
|
||||
const ownerScoped =
|
||||
Array.isArray(predicate) && predicate[0] === 'user-can-edit';
|
||||
if (ownerScoped) {
|
||||
filters.ownerUserId = actor.user.id;
|
||||
}
|
||||
|
||||
let apps = await this.appStore.list({
|
||||
ownerUserId,
|
||||
...filters,
|
||||
limit: paginated ? limit + 1 : limit,
|
||||
offset,
|
||||
afterId: payload?.id !== undefined ? Number(payload.id) : undefined,
|
||||
@@ -364,18 +371,23 @@ export class AppDriver extends PuterDriver {
|
||||
let cursor;
|
||||
if (paginated && apps.length > limit) {
|
||||
apps = apps.slice(0, limit);
|
||||
// The cursor tracks the last fetched row, not the last visible
|
||||
// one, so rows hidden by the permission filter below aren't
|
||||
// re-scanned on the next page.
|
||||
cursor = sealCursor(
|
||||
{ id: Number(apps[apps.length - 1].id) },
|
||||
this.config.jwt_secret_v2,
|
||||
);
|
||||
}
|
||||
|
||||
// Stats and the shared views are each one batched lookup per page.
|
||||
// Protected apps are filtered by one batched grant check; stats and
|
||||
// the shared views are each one batched lookup across the page.
|
||||
const visible = await this.services.app.filterReadable(apps, actor);
|
||||
const [statsByUid, views] = await Promise.all([
|
||||
this.appStore.getAppsStats(apps.map((a) => a.uid)),
|
||||
this.services.app.views(apps, actor),
|
||||
this.appStore.getAppsStats(visible.map((a) => a.uid)),
|
||||
this.services.app.views(visible, actor),
|
||||
]);
|
||||
const items = apps.map((app, i) =>
|
||||
const items = visible.map((app, i) =>
|
||||
toAppReadView(app, views[i], {
|
||||
viewer: actor.user,
|
||||
stats: statsByUid.get(app.uid),
|
||||
@@ -384,9 +396,14 @@ export class AppDriver extends PuterDriver {
|
||||
);
|
||||
if (!paginated) return items;
|
||||
|
||||
const total = includeTotal
|
||||
? await this.appStore.count({ ownerUserId })
|
||||
: undefined;
|
||||
let total;
|
||||
if (includeTotal) {
|
||||
total = ownerScoped
|
||||
? await this.appStore.count({ ownerUserId: actor.user.id })
|
||||
: await this.appStore.count({
|
||||
visibleToUserId: actor.user?.id ?? null,
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
items,
|
||||
|
||||
@@ -509,7 +509,7 @@ describe('AppDriver.read', () => {
|
||||
// ── select ──────────────────────────────────────────────────────────
|
||||
|
||||
describe('AppDriver.select', () => {
|
||||
it("returns only the caller's apps when no predicate is sent", async () => {
|
||||
it('returns visible apps including those owned by other users', async () => {
|
||||
const a = await makeUser();
|
||||
const b = await makeUser();
|
||||
const aName = uniqueName('a');
|
||||
@@ -538,7 +538,7 @@ describe('AppDriver.select', () => {
|
||||
)) as Array<Record<string, unknown>>;
|
||||
const names = result.map((r) => r.name);
|
||||
expect(names).toContain(aName);
|
||||
expect(names).not.toContain(bName);
|
||||
expect(names).toContain(bName);
|
||||
});
|
||||
|
||||
it('predicate `user-can-edit` filters to actor-owned apps only', async () => {
|
||||
@@ -1670,10 +1670,11 @@ describe('AppDriver.select pagination', () => {
|
||||
expect(page.total).toBe(names.length);
|
||||
});
|
||||
|
||||
it("pages through only the caller's apps, protected ones included", async () => {
|
||||
it("hides other users' protected apps from paginated catalog listings", async () => {
|
||||
const a = await makeApps(3);
|
||||
const [visible1, hidden, visible2] = a.names;
|
||||
const created = await withActor(a.actor, () =>
|
||||
driver.read({ id: { name: a.names[1] } }),
|
||||
driver.read({ id: { name: hidden } }),
|
||||
);
|
||||
const row = await server.stores.app.getByUid(
|
||||
(created as Record<string, unknown>).uid as string,
|
||||
@@ -1684,29 +1685,20 @@ describe('AppDriver.select pagination', () => {
|
||||
);
|
||||
await server.stores.app.invalidateByUid(row!.uid as string);
|
||||
|
||||
const listAll = async (actor: Actor) => {
|
||||
const seen: string[] = [];
|
||||
let total: number | undefined;
|
||||
let cursor: string | null | undefined = null;
|
||||
do {
|
||||
const page = (await withActor(actor, () =>
|
||||
driver.select({ limit: 2, cursor, includeTotal: true }),
|
||||
)) as {
|
||||
items: Array<{ name: string }>;
|
||||
cursor?: string;
|
||||
total?: number;
|
||||
};
|
||||
seen.push(...page.items.map((r) => r.name));
|
||||
total ??= page.total;
|
||||
cursor = page.cursor;
|
||||
} while (cursor);
|
||||
return { seen, total };
|
||||
};
|
||||
|
||||
expect(await listAll(a.actor)).toEqual({ seen: a.names, total: 3 });
|
||||
|
||||
const b = await makeUser();
|
||||
expect(await listAll(b.actor)).toEqual({ seen: [], total: 0 });
|
||||
const seen: string[] = [];
|
||||
let cursor: string | null | undefined = null;
|
||||
do {
|
||||
const page = (await withActor(b.actor, () =>
|
||||
driver.select({ limit: 50, cursor }),
|
||||
)) as { items: Array<{ name: string }>; cursor?: string };
|
||||
seen.push(...page.items.map((r) => r.name));
|
||||
cursor = page.cursor;
|
||||
} while (cursor);
|
||||
|
||||
expect(seen).toContain(visible1);
|
||||
expect(seen).toContain(visible2);
|
||||
expect(seen).not.toContain(hidden);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -2525,6 +2517,22 @@ describe('AppDriver.select query-count regression', () => {
|
||||
// -- select / read parity --
|
||||
|
||||
describe('AppDriver.select / read parity', () => {
|
||||
const findViaBroadSelect = async (
|
||||
actor: Actor,
|
||||
uid: string,
|
||||
): Promise<Record<string, unknown> | undefined> => {
|
||||
let cursor: string | null | undefined = null;
|
||||
do {
|
||||
const page = (await withActor(actor, () =>
|
||||
driver.select({ limit: 50, cursor }),
|
||||
)) as { items: Array<Record<string, unknown>>; cursor?: string };
|
||||
const found = page.items.find((r) => r.uid === uid);
|
||||
if (found) return found;
|
||||
cursor = page.cursor;
|
||||
} while (cursor);
|
||||
return undefined;
|
||||
};
|
||||
|
||||
it('every select item (minus stats) deep-equals the corresponding read', async () => {
|
||||
const { actor } = await makeUser();
|
||||
const names: string[] = [];
|
||||
@@ -2632,7 +2640,7 @@ describe('AppDriver.select / read parity', () => {
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it('dangling hosted app: owner keeps index_url in select, others do not in read', async () => {
|
||||
it('dangling hosted app via select: owner keeps index_url, others do not', async () => {
|
||||
const owner = await makeUser();
|
||||
const other = await makeUser();
|
||||
const sub = uniqueName('qcdangsel');
|
||||
@@ -2664,12 +2672,13 @@ describe('AppDriver.select / read parity', () => {
|
||||
?.reason,
|
||||
).toBe('hosted_backing_unavailable');
|
||||
|
||||
const otherItem = (await withActor(other.actor, () =>
|
||||
driver.read({ uid: created.uid }),
|
||||
)) as Record<string, unknown>;
|
||||
expect(otherItem.index_url).toBeUndefined();
|
||||
const otherItem = await findViaBroadSelect(
|
||||
other.actor,
|
||||
created.uid as string,
|
||||
);
|
||||
expect(otherItem?.index_url).toBeUndefined();
|
||||
expect(
|
||||
(otherItem.privateAccess as { hasAccess?: boolean } | undefined)
|
||||
(otherItem?.privateAccess as { hasAccess?: boolean } | undefined)
|
||||
?.hasAccess,
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
@@ -414,7 +414,6 @@ describe('PuterServer host header validation', () => {
|
||||
'show-save-file-picker',
|
||||
'show-directory-picker',
|
||||
'upgrade',
|
||||
'top-up',
|
||||
'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}`;
|
||||
@@ -448,7 +447,7 @@ describe('PuterServer host header validation', () => {
|
||||
expect(redirected.headers['x-frame-options']).toBe('SAMEORIGIN');
|
||||
});
|
||||
|
||||
it.each(['/embed/SIGN-IN', '/embed/Show-Open-File-Picker', '/embed/sign-in/', '/embed/Upgrade', '/embed/upgrade/', '/embed/Top-Up', '/embed/top-up/', '/embed/Request-Email-Confirmation'])(
|
||||
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, {
|
||||
|
||||
@@ -20,7 +20,6 @@
|
||||
import { createHmac } from 'node:crypto';
|
||||
import jwt from 'jsonwebtoken';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { isTokenForAnotherUser } from '../../../gui/src/helpers/tokenUser.js';
|
||||
import { TokenService } from './TokenService.js';
|
||||
|
||||
const V2_SECRET = 'test-v2-secret';
|
||||
@@ -385,21 +384,3 @@ describe('TokenService payload key handling', () => {
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
describe('session token read by the desktop', () => {
|
||||
// The desktop reads the user out of a token another tab stored, to tell
|
||||
// an account switch from a renewed token for the same account.
|
||||
it('names its user in the form the desktop decodes', () => {
|
||||
const svc = createTokenService();
|
||||
const userUid = '5d4adce0-a381-4982-9c02-6e2540026238';
|
||||
const otherUid = 'a1b2c3d4-0000-4000-8000-00000000beef';
|
||||
const token = svc.sign('auth', {
|
||||
type: 'gui',
|
||||
version: '2',
|
||||
user_uid: userUid,
|
||||
});
|
||||
|
||||
expect(isTokenForAnotherUser(token, { uuid: userUid })).toBe(false);
|
||||
expect(isTokenForAnotherUser(token, { uuid: otherUid })).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -686,7 +686,12 @@ export class AppStore extends PuterStore {
|
||||
return apps;
|
||||
}
|
||||
|
||||
/** Count apps matching the same equality filters as `list`. */
|
||||
/**
|
||||
* Count apps matching the same equality filters as `list`.
|
||||
* `visibleToUserId` counts the public catalog for one caller —
|
||||
* non-protected apps plus their own; apps visible only via explicit
|
||||
* permission grants are not included.
|
||||
*/
|
||||
async count(filters = {}) {
|
||||
const where = [];
|
||||
const params = [];
|
||||
@@ -699,6 +704,12 @@ export class AppStore extends PuterStore {
|
||||
where.push('`app_owner` = ?');
|
||||
params.push(filters.appOwner);
|
||||
}
|
||||
if (filters.visibleToUserId !== undefined) {
|
||||
where.push(
|
||||
'(`protected` IS NULL OR `protected` = false OR `owner_user_id` = ?)',
|
||||
);
|
||||
params.push(filters.visibleToUserId);
|
||||
}
|
||||
|
||||
const whereClause = where.length ? `WHERE ${where.join(' AND ')}` : '';
|
||||
const rows = await this.clients.db.read(
|
||||
|
||||
@@ -1292,14 +1292,31 @@ describe('AppStore CRUD and cache invalidation', () => {
|
||||
).toBe('Bumped');
|
||||
});
|
||||
|
||||
it('counts apps by owner and creator', async () => {
|
||||
it('counts apps by owner, creator and per-caller visibility', async () => {
|
||||
const countOwner = 4600;
|
||||
const viewer = 4601;
|
||||
const open = await createApp({}, { ownerUserId: countOwner });
|
||||
await createApp({}, { ownerUserId: countOwner, appOwner: open.id });
|
||||
await createApp({}, { ownerUserId: countOwner });
|
||||
const hidden = await createApp({}, { ownerUserId: countOwner });
|
||||
await db.write('UPDATE `apps` SET `protected` = 1 WHERE `id` = ?', [
|
||||
hidden.id,
|
||||
]);
|
||||
|
||||
expect(await appStore.count({ ownerUserId: countOwner })).toBe(3);
|
||||
expect(await appStore.count({ appOwner: open.id })).toBe(1);
|
||||
|
||||
// The protected app is invisible to a stranger but visible to its
|
||||
// owner.
|
||||
const strangerView = await appStore.count({
|
||||
ownerUserId: countOwner,
|
||||
visibleToUserId: viewer,
|
||||
});
|
||||
expect(strangerView).toBe(2);
|
||||
const ownerView = await appStore.count({
|
||||
ownerUserId: countOwner,
|
||||
visibleToUserId: countOwner,
|
||||
});
|
||||
expect(ownerView).toBe(3);
|
||||
});
|
||||
|
||||
// -- filetype association batch + recent opens ----------------------
|
||||
|
||||
@@ -1339,7 +1339,7 @@ async function saveEditedApp (mode) {
|
||||
// Update title
|
||||
$(`.app-title[data-uid="${uid}"]`).html(html_encode(app.title));
|
||||
// Update app link
|
||||
$(`.app-url[data-uid="${uid}"]`).html(html_encode(applink(app)));
|
||||
$(`.app-url[data-uid="${uid}"]`).html(applink(app));
|
||||
$(`.app-url[data-uid="${uid}"]`).attr('href', applink(app));
|
||||
// Update icons
|
||||
$(`.app-icon[data-uid="${uid}"]`).attr('src', html_encode(app.icon ? app.icon : './img/app.svg'));
|
||||
|
||||
@@ -38,27 +38,22 @@ window.user = null;
|
||||
}
|
||||
})();
|
||||
|
||||
// domain and port are built into links and deploy URLs, so anything other
|
||||
// than a bare hostname and a numeric port is ignored
|
||||
const domainParam = window.url_params.get('puter.domain');
|
||||
if ( domainParam && /^[a-z0-9-]+(\.[a-z0-9-]+)*$/i.test(domainParam) ) {
|
||||
window.domain = domainParam;
|
||||
// domain and APIOrigin
|
||||
if ( window.url_params.has('puter.domain') ) {
|
||||
window.domain = window.url_params.get('puter.domain');
|
||||
}
|
||||
|
||||
const portParam = window.url_params.get('puter.port');
|
||||
window.port = portParam && /^\d{1,5}$/.test(portParam) ? portParam : '';
|
||||
|
||||
// static hosting domain
|
||||
window.static_hosting_domain = 'puter.site';
|
||||
if ( window.domain === 'puter.localhost' ) {
|
||||
window.static_hosting_domain = 'site.puter.localhost';
|
||||
} else if ( window.domain && window.domain !== 'puter.com' ) {
|
||||
window.static_hosting_domain = `site.${window.domain}`;
|
||||
}
|
||||
if ( window.domain === 'puter.localhost' ) {
|
||||
window.static_hosting_domain = 'site.puter.localhost';
|
||||
} else if ( window.domain && window.domain !== 'puter.com' ) {
|
||||
window.static_hosting_domain = `site.${window.domain}`;
|
||||
}
|
||||
|
||||
// add port to static_hosting_domain if provided
|
||||
if ( window.port ) {
|
||||
window.static_hosting_domain = `${window.static_hosting_domain}:${window.port}`;
|
||||
if ( window.url_params.has('puter.port') && window.url_params.get('puter.port') ) {
|
||||
window.static_hosting_domain = `${window.static_hosting_domain }:${ html_encode(window.url_params.get('puter.port'))}`;
|
||||
}
|
||||
|
||||
// protocol
|
||||
@@ -68,6 +63,12 @@ if ( window.url_params.has('puter.protocol') && window.url_params.get('puter.pro
|
||||
window.protocol = 'http';
|
||||
}
|
||||
|
||||
// port
|
||||
window.port = '';
|
||||
if ( window.url_params.has('puter.port') && window.url_params.get('puter.port') ) {
|
||||
window.port = html_encode(window.url_params.get('puter.port'));
|
||||
}
|
||||
|
||||
// source_path
|
||||
if ( window.url_params.has('source_path') ) {
|
||||
window.source_path = window.url_params.get('source_path');
|
||||
|
||||
@@ -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>
|
||||
```
|
||||
@@ -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)
|
||||
|
||||
|
||||
@@ -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>
|
||||
@@ -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):
|
||||
|
||||
+2
-3
@@ -20,7 +20,6 @@
|
||||
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';
|
||||
@@ -1703,7 +1702,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 +1716,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();
|
||||
|
||||
@@ -69,7 +69,6 @@ beforeAll(async () => {
|
||||
[sessionToken]: { uuid: sessionUser, username: 'session-user' },
|
||||
'app-token-session-user': { uuid: sessionUser, username: 'session-user' },
|
||||
'app-token-other-user': { uuid: otherUser, username: 'other-user' },
|
||||
'app-token-subscriber': { uuid: sessionUser, username: 'session-user', subscribed: true },
|
||||
};
|
||||
// The SDK on a sibling subdomain sends credentialed cross-origin requests.
|
||||
app.use(['/whoami', '/profile', '/rao'], (req, res, next) => {
|
||||
@@ -514,81 +513,6 @@ describe('embedded app browser', () => {
|
||||
}
|
||||
});
|
||||
|
||||
it('offers Add credits to an account with a plan, and frames the top-up over the page', async () => {
|
||||
const context = await menuContext('app-token-subscriber');
|
||||
try {
|
||||
const page = await context.newPage();
|
||||
page.setDefaultTimeout(6000);
|
||||
await page.goto(`http://spreadsheet.puter.localhost:${port}/menu-host`);
|
||||
await page.locator('puter-user-menu .avatar').click();
|
||||
const item = page.locator('puter-user-menu .add-credits');
|
||||
await item.waitFor();
|
||||
expect(await item.textContent()).toBe('Add credits');
|
||||
// Under Usage, in the same row style as the links around it.
|
||||
expect(await page.locator('puter-user-menu .usage + .add-credits').count()).toBe(1);
|
||||
expect(await item.evaluate(el => getComputedStyle(el).height))
|
||||
.toBe(await page.locator('puter-user-menu .feedback').evaluate(el => getComputedStyle(el).height));
|
||||
|
||||
await item.click();
|
||||
const frame = page.locator('dialog.puter-popup-frame iframe');
|
||||
await frame.waitFor({ state: 'attached' });
|
||||
expect(await frame.getAttribute('src')).toBe(`${origin}/embed/top-up#user=${sessionUser}`);
|
||||
expect(await frame.getAttribute('allow')).toBe('payment; otp-credentials');
|
||||
expect(await page.locator('puter-user-menu .menu').isHidden()).toBe(true);
|
||||
} finally {
|
||||
guestApps = [];
|
||||
await context.close();
|
||||
}
|
||||
});
|
||||
|
||||
it('returns keyboard focus to the account button when Add credits is chosen', async () => {
|
||||
const context = await menuContext('app-token-subscriber');
|
||||
try {
|
||||
const page = await context.newPage();
|
||||
page.setDefaultTimeout(6000);
|
||||
await page.goto(`http://spreadsheet.puter.localhost:${port}/menu-host`);
|
||||
await page.locator('puter-user-menu .avatar').focus();
|
||||
await page.keyboard.press('Enter');
|
||||
await page.locator('puter-user-menu .add-credits').waitFor();
|
||||
await page.locator('puter-user-menu .add-credits').focus();
|
||||
await page.keyboard.press('Enter');
|
||||
await page.locator('dialog.puter-popup-frame iframe').waitFor({ state: 'attached' });
|
||||
const focused = () => page.evaluate(() => document.activeElement.shadowRoot?.activeElement?.className ?? document.activeElement.tagName);
|
||||
expect(await focused()).toBe('avatar');
|
||||
|
||||
// The dialog hands the focus back when it closes.
|
||||
const fromFrame = (state) => page.evaluate(([guiOrigin, frameState]) => {
|
||||
const source = document.querySelector('dialog.puter-popup-frame iframe').contentWindow;
|
||||
window.dispatchEvent(new MessageEvent('message', {
|
||||
data: { msg: 'puterPopupFrame', state: frameState }, origin: guiOrigin, source,
|
||||
}));
|
||||
}, [origin, state]);
|
||||
await fromFrame('ready');
|
||||
expect(await page.locator('dialog.puter-popup-frame').evaluate(el => el.open)).toBe(true);
|
||||
await fromFrame('closed');
|
||||
await page.locator('dialog.puter-popup-frame').waitFor({ state: 'detached' });
|
||||
expect(await focused()).toBe('avatar');
|
||||
} finally {
|
||||
guestApps = [];
|
||||
await context.close();
|
||||
}
|
||||
});
|
||||
|
||||
it('leaves Add credits out of the menu of an account without a plan', async () => {
|
||||
const context = await menuContext('app-token-session-user');
|
||||
try {
|
||||
const page = await context.newPage();
|
||||
page.setDefaultTimeout(6000);
|
||||
await page.goto(`http://spreadsheet.puter.localhost:${port}/menu-host`);
|
||||
await page.locator('puter-user-menu .avatar').click();
|
||||
await page.locator('puter-user-menu .usage').waitFor();
|
||||
expect(await page.locator('puter-user-menu .add-credits').isHidden()).toBe(true);
|
||||
} finally {
|
||||
guestApps = [];
|
||||
await context.close();
|
||||
}
|
||||
});
|
||||
|
||||
it('closes the account menu when Tab leaves it', async () => {
|
||||
const context = await menuContext('app-token-session-user');
|
||||
try {
|
||||
|
||||
@@ -50,7 +50,7 @@ import { parent_path_for, parse_shared_path, shared_crumbs_for, shared_uids_from
|
||||
import resolve_shared_item from '../../helpers/resolveSharedItem.js';
|
||||
import { is_owned_by_me } from '../../helpers/pathOwner.js';
|
||||
import parse_item_metadata from '../../helpers/parseItemMetadata.js';
|
||||
import { compareSharers, filterBySharer, fitSharedByWidth, sharedByCellHtml, sharerFilterHtml, sharerOf, summarizeSharers } from './sharedBy.js';
|
||||
import { compareSharers, filterBySharer, fitSharedByWidth, sharedByCellHtml, sharerFilterHtml, summarizeSharers } from './sharedBy.js';
|
||||
import { paintAvatars } from '../../helpers/profilePictures.js';
|
||||
|
||||
const { html_encode, SelectionArea } = window;
|
||||
@@ -2983,7 +2983,7 @@ const TabFiles = {
|
||||
// Rebuilding the chips drops focus and scroll; carry both across.
|
||||
const focused = $bar.find('.sharer-chip:focus').attr('data-sharer');
|
||||
const scrollLeft = bar.scrollLeft;
|
||||
const html = sharerFilterHtml(sharers, this.sharerFilter, rows.filter((row) => sharerOf(row)).length);
|
||||
const html = sharerFilterHtml(sharers, this.sharerFilter);
|
||||
$bar.html(html).prop('hidden', ! html);
|
||||
paintAvatars(bar);
|
||||
bar.scrollLeft = scrollLeft;
|
||||
@@ -6011,10 +6011,8 @@ const TabFiles = {
|
||||
shared_with_me: true,
|
||||
share_mode: share.mode,
|
||||
shared_by: share.issuer,
|
||||
shared_by_all: share.issuers,
|
||||
owner: share.owner,
|
||||
holder_team: share.holderTeam,
|
||||
also_team_share: share.alsoHeldByTeam,
|
||||
}));
|
||||
|
||||
const linked = this.pendingSharedLinks ?? [];
|
||||
|
||||
@@ -1667,34 +1667,6 @@ describe('TabFiles listSharedView', () => {
|
||||
});
|
||||
expect(rows[1].holder_team).toEqual(team);
|
||||
});
|
||||
|
||||
it('merges the grants on one item into a single row', async () => {
|
||||
const team = { uid: 't-1', name: 'Acme', handle: 'acme' };
|
||||
const grant = { entryUid: 'u-1', name: 'a.txt', path: '/bob/u-1/a.txt', isDir: false, owner: 'bob' };
|
||||
window.puter = {
|
||||
fs: {
|
||||
listShared: vi.fn(async () => ({
|
||||
items: [
|
||||
{ ...grant, mode: 'read', issuer: 'bob', holderTeam: team },
|
||||
{ ...grant, mode: 'manage', issuer: 'bob' },
|
||||
{ ...grant, mode: 'read', issuer: 'carol' },
|
||||
],
|
||||
})),
|
||||
},
|
||||
};
|
||||
|
||||
const rows = await TabFiles.listSharedView();
|
||||
|
||||
expect(rows).toHaveLength(1);
|
||||
expect(rows[0]).toMatchObject({
|
||||
uid: 'u-1',
|
||||
share_mode: 'manage',
|
||||
shared_by: 'bob',
|
||||
shared_by_all: ['bob', 'carol'],
|
||||
also_team_share: true,
|
||||
});
|
||||
expect(rows[0].holder_team).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('TabFiles path field', () => {
|
||||
|
||||
@@ -22,10 +22,9 @@
|
||||
|
||||
import { avatarHue, avatarInitial } from '../../helpers/shareAvatar.js';
|
||||
import { avatarUserAttr } from '../../helpers/profilePictures.js';
|
||||
import { intlLocale } from '../../i18n/intlLocale.js';
|
||||
|
||||
/**
|
||||
* @typedef {{ shared_by?: string | null, shared_by_all?: string[], owner?: string | null }} SharedRow
|
||||
* @typedef {{ shared_by?: string | null, owner?: string | null }} SharedRow
|
||||
* @typedef {{ name: string, count: number }} Sharer
|
||||
*/
|
||||
|
||||
@@ -38,19 +37,6 @@ import { intlLocale } from '../../i18n/intlLocale.js';
|
||||
*/
|
||||
export const sharerOf = (row) => row?.shared_by || row?.owner || '';
|
||||
|
||||
/**
|
||||
* Everyone who shared a row with the user, `sharerOf` first. More than one
|
||||
* when the item was granted by several people.
|
||||
*
|
||||
* @param {SharedRow} [row]
|
||||
* @returns {string[]} usernames
|
||||
*/
|
||||
export const sharersOf = (row) => {
|
||||
const first = sharerOf(row);
|
||||
if ( ! row?.shared_by_all?.length ) return first ? [first] : [];
|
||||
return [...new Set([first, ...row.shared_by_all])].filter(Boolean);
|
||||
};
|
||||
|
||||
/**
|
||||
* Everyone who shared something in `rows`, with how many items each, most
|
||||
* items first and ties by name.
|
||||
@@ -61,7 +47,8 @@ export const sharersOf = (row) => {
|
||||
export const summarizeSharers = (rows) => {
|
||||
const counts = new Map();
|
||||
for ( const row of rows ) {
|
||||
for ( const name of sharersOf(row) ) counts.set(name, (counts.get(name) ?? 0) + 1);
|
||||
const name = sharerOf(row);
|
||||
if ( name ) counts.set(name, (counts.get(name) ?? 0) + 1);
|
||||
}
|
||||
return [...counts]
|
||||
.map(([name, count]) => ({ name, count }))
|
||||
@@ -69,8 +56,7 @@ export const summarizeSharers = (rows) => {
|
||||
};
|
||||
|
||||
/**
|
||||
* The rows `sharer` shared, each shown as shared by them; every row when
|
||||
* `sharer` is empty.
|
||||
* The rows `sharer` shared; every row when `sharer` is empty.
|
||||
*
|
||||
* @template {SharedRow} T
|
||||
* @param {T[]} rows
|
||||
@@ -78,9 +64,7 @@ export const summarizeSharers = (rows) => {
|
||||
* @returns {T[]}
|
||||
*/
|
||||
export const filterBySharer = (rows, sharer) => (sharer
|
||||
? rows
|
||||
.filter((row) => sharersOf(row).includes(sharer))
|
||||
.map((row) => (sharerOf(row) === sharer ? row : { ...row, shared_by: sharer }))
|
||||
? rows.filter((row) => sharerOf(row) === sharer)
|
||||
: rows);
|
||||
|
||||
/**
|
||||
@@ -96,21 +80,6 @@ export const compareSharers = (a, b) => compareNames(sharerOf(a), sharerOf(b));
|
||||
// one per call, which made sorting a large Shared listing over 20x slower.
|
||||
const compareNames = new Intl.Collator(undefined, { sensitivity: 'base' }).compare;
|
||||
|
||||
/**
|
||||
* Names joined the way the user's language lists them ("ann and bob").
|
||||
*
|
||||
* @param {string[]} names
|
||||
* @returns {string}
|
||||
*/
|
||||
const listNames = (names) => {
|
||||
if ( names.length === 1 ) return names[0];
|
||||
try {
|
||||
return new Intl.ListFormat(intlLocale(window.locale ?? 'en'), { type: 'conjunction' }).format(names);
|
||||
} catch {
|
||||
return names.join(', ');
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* The "Shared by" column's width beside an auto-width name column: `width`,
|
||||
* held to 40% of the `room` the two split so the name keeps the larger part,
|
||||
@@ -133,16 +102,15 @@ export const fitSharedByWidth = (width, room) => Math.max(60, Math.min(width, Ma
|
||||
const avatarHtml = (name, className) => `<span class="${className}" style="--share-avatar-hue: ${avatarHue(name)}"${avatarUserAttr(name)} aria-hidden="true">${window.html_encode(avatarInitial(name))}</span>`;
|
||||
|
||||
/**
|
||||
* Tooltip for a row's sharers, naming the owner too when none of them owns it.
|
||||
* Tooltip for a row's sharer, naming the owner too when someone else re-shared it.
|
||||
*
|
||||
* @param {SharedRow} row
|
||||
* @returns {string} plain text
|
||||
*/
|
||||
export const sharedByTitle = (row) => {
|
||||
const sharers = sharersOf(row);
|
||||
if ( sharers.length === 0 ) return '';
|
||||
const username = listNames(sharers);
|
||||
return row.owner && ! sharers.includes(row.owner)
|
||||
const username = sharerOf(row);
|
||||
if ( ! username ) return '';
|
||||
return row.owner && row.owner !== username
|
||||
? i18n('shared_by_user_owned_by', { username, owner: row.owner }, false)
|
||||
: i18n('shared_by_user', { username }, false);
|
||||
};
|
||||
@@ -169,11 +137,11 @@ export const sharedByCellHtml = (row) => {
|
||||
*
|
||||
* @param {Sharer[]} sharers - From summarizeSharers
|
||||
* @param {string | null} active - The sharer filtered to, or null for everyone
|
||||
* @param {number} total - Items anyone shared; an item counts once however many shared it
|
||||
* @returns {string} markup
|
||||
*/
|
||||
export const sharerFilterHtml = (sharers, active, total) => {
|
||||
export const sharerFilterHtml = (sharers, active) => {
|
||||
if ( sharers.length < 2 ) return '';
|
||||
const total = sharers.reduce((sum, sharer) => sum + sharer.count, 0);
|
||||
const chip = (value, inner, count, title) => {
|
||||
const pressed = (active ?? '') === value;
|
||||
return `<button type="button" class="sharer-chip${pressed ? ' active' : ''}" data-sharer="${window.html_encode(value)}" aria-pressed="${pressed}"${title ? ` title="${window.html_encode(title)}"` : ''}>`
|
||||
|
||||
@@ -40,13 +40,6 @@ const {
|
||||
} = await import('./sharedBy.js');
|
||||
|
||||
const row = (shared_by, owner = shared_by, name = 'f') => ({ shared_by, owner, name });
|
||||
// An item granted by more than one person: `shared_by` holds the strongest grant's.
|
||||
const multiRow = (shared_by_all, owner = shared_by_all[0], name = 'f') => ({
|
||||
shared_by: shared_by_all[0],
|
||||
shared_by_all,
|
||||
owner,
|
||||
name,
|
||||
});
|
||||
|
||||
describe('sharerOf', () => {
|
||||
it('names whoever granted the share', () => {
|
||||
@@ -81,13 +74,6 @@ describe('summarizeSharers', () => {
|
||||
it('skips rows that name nobody', () => {
|
||||
expect(summarizeSharers([{}, row('ann')])).toEqual([{ name: 'ann', count: 1 }]);
|
||||
});
|
||||
|
||||
it('counts an item for everyone who shared it', () => {
|
||||
expect(summarizeSharers([multiRow(['bob', 'ann']), row('ann')])).toEqual([
|
||||
{ name: 'ann', count: 2 },
|
||||
{ name: 'bob', count: 1 },
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('filterBySharer', () => {
|
||||
@@ -97,20 +83,6 @@ describe('filterBySharer', () => {
|
||||
expect(filterBySharer(rows, 'ann').map((r) => r.name)).toEqual(['a', 'c']);
|
||||
});
|
||||
|
||||
it('keeps an item for each person who shared it', () => {
|
||||
const shared = [multiRow(['bob', 'ann'], 'ann', 'both'), row('cy', 'cy', 'c')];
|
||||
expect(filterBySharer(shared, 'ann').map((r) => r.name)).toEqual(['both']);
|
||||
expect(filterBySharer(shared, 'bob').map((r) => r.name)).toEqual(['both']);
|
||||
});
|
||||
|
||||
it('shows a kept item as shared by the person filtered to', () => {
|
||||
const [both, own] = filterBySharer([multiRow(['bob', 'ann'], 'ann', 'both'), row('ann', 'ann', 'own')], 'ann');
|
||||
expect(sharerOf(both)).toBe('ann');
|
||||
expect(sharedByCellHtml(both)).toContain('<span class="item-shared-by-name">ann</span>');
|
||||
expect(sharedByTitle(both)).toBe('shared_by_user:ann and bob');
|
||||
expect(sharerOf(own)).toBe('ann');
|
||||
});
|
||||
|
||||
it('keeps everything without a filter', () => {
|
||||
expect(filterBySharer(rows, null)).toBe(rows);
|
||||
expect(filterBySharer(rows, '')).toBe(rows);
|
||||
@@ -151,11 +123,6 @@ describe('sharedByTitle', () => {
|
||||
it('names the owner too when someone else re-shared it', () => {
|
||||
expect(sharedByTitle(row('ann', 'bob'))).toBe('shared_by_user_owned_by:ann,bob');
|
||||
});
|
||||
|
||||
it('names everyone who shared the item', () => {
|
||||
expect(sharedByTitle(multiRow(['bob', 'ann'], 'ann'))).toBe('shared_by_user:bob and ann');
|
||||
expect(sharedByTitle(multiRow(['bob', 'cy'], 'ann'))).toBe('shared_by_user_owned_by:bob and cy,ann');
|
||||
});
|
||||
});
|
||||
|
||||
describe('sharedByCellHtml', () => {
|
||||
@@ -188,7 +155,7 @@ describe('sharerFilterHtml', () => {
|
||||
});
|
||||
|
||||
it('leads with Everyone, counting every item', () => {
|
||||
const h = sharerFilterHtml([{ name: 'bob', count: 2 }, { name: 'ann', count: 1 }], null, 3);
|
||||
const h = sharerFilterHtml([{ name: 'bob', count: 2 }, { name: 'ann', count: 1 }], null);
|
||||
const chips = h.match(/<button[^>]*>/g);
|
||||
expect(chips).toHaveLength(3);
|
||||
expect(chips[0]).toContain('data-sharer=""');
|
||||
@@ -198,11 +165,6 @@ describe('sharerFilterHtml', () => {
|
||||
expect(h).toContain('data-avatar-user="bob"');
|
||||
});
|
||||
|
||||
it('counts an item shared by two people once under Everyone', () => {
|
||||
const h = sharerFilterHtml([{ name: 'ann', count: 2 }, { name: 'bob', count: 1 }], null, 2);
|
||||
expect(h).toContain('shared_filter_everyone:</span><span class="sharer-chip-count">2</span>');
|
||||
});
|
||||
|
||||
it('presses the active sharer only', () => {
|
||||
const h = sharerFilterHtml([{ name: 'bob', count: 2 }, { name: 'ann', count: 1 }], 'ann');
|
||||
const pressed = h.match(/<button[^>]*aria-pressed="true"[^>]*>/g);
|
||||
|
||||
+48
-45
@@ -34,7 +34,6 @@ import UIWindowProgress from './UIWindowProgress.js';
|
||||
import UITaskbar from './UITaskbar.js';
|
||||
import new_context_menu_item from '../helpers/newContextMenuItem.js';
|
||||
import refresh_item_container from '../helpers/refreshItemContainer.js';
|
||||
import { atPath, retargetNavHistory, retargetPaths, underPath } from '../helpers/pathElements.js';
|
||||
import changeLanguage from '../i18n/i18nChangeLanguage.js';
|
||||
import UIWindowTaskManager from './UIWindowTaskManager.js';
|
||||
import truncate_filename from '../helpers/truncateFilename.js';
|
||||
@@ -233,12 +232,7 @@ async function UIDesktop (options) {
|
||||
// empty trash windows if needed
|
||||
if ( msg.is_empty )
|
||||
{
|
||||
// only the rows: the container also holds its empty, error and loading states
|
||||
$(`.window[data-path="${html_encode(window.trash_path)}" i]`).each(function () {
|
||||
$(this).find('.item-container .item').removeItems();
|
||||
window.update_explorer_footer_item_count(this);
|
||||
window.update_explorer_footer_selected_items_count(this);
|
||||
});
|
||||
$(`.window[data-path="${html_encode(window.trash_path)}" i]`).find('.item-container').empty();
|
||||
}
|
||||
});
|
||||
|
||||
@@ -421,17 +415,14 @@ async function UIDesktop (options) {
|
||||
return;
|
||||
}
|
||||
|
||||
// remove all UIItems at the removed path
|
||||
atPath('.item', item.path).fadeOut(150, function () {
|
||||
const $parent_window = $(this).closest('.window');
|
||||
$(this).removeItems();
|
||||
window.update_explorer_footer_item_count($parent_window);
|
||||
window.update_explorer_footer_selected_items_count($parent_window);
|
||||
// hide all UIItems with matching uids
|
||||
$(`.item[data-path='${item.path}']`).fadeOut(150, function () {
|
||||
// close all windows with matching uids
|
||||
// $('.window-' + item.uid).close();
|
||||
// close all windows that belong to a descendant of this item
|
||||
// todo this has to be case-insensitive but the `i` selector doesn't work on ^=
|
||||
$(`.window[data-path^="${item.path}/"]`).close();
|
||||
});
|
||||
// close the windows showing the removed folder or anything inside it,
|
||||
// whether or not its own row is displayed anywhere
|
||||
// todo this has to be case-insensitive
|
||||
atPath('.window[data-app="explorer"]', item.path).add(underPath('.window', item.path)).close();
|
||||
});
|
||||
|
||||
window.socket.on('item.updated', async (item) => {
|
||||
@@ -463,20 +454,25 @@ async function UIDesktop (options) {
|
||||
$(`.item[data-uid='${item.uid}'] .item-name-editor`).val(item.name);
|
||||
$(`.item[data-uid='${item.uid}'] .item-name`).attr('title', item.name);
|
||||
|
||||
// An overwrite arrives as an update, with a new size and date
|
||||
if ( item.size !== undefined && item.modified !== undefined ) {
|
||||
const $updated_items = $(`.item[data-uid='${item.uid}']`);
|
||||
$updated_items.attr({ 'data-size': item.size ?? '', 'data-modified': item.modified ?? '' });
|
||||
$updated_items.find('.item-attr--size > span').text(item.size ? window.byte_format(item.size) : '-');
|
||||
$updated_items.find('.item-attr--modified > span').text(item.modified === 0 ? '-' : timeago.format(item.modified * 1000));
|
||||
}
|
||||
|
||||
// Set new data-path
|
||||
const new_path = item.path;
|
||||
$(`.item[data-uid='${item.uid}']`).attr('data-path', new_path);
|
||||
$(`.window-${item.uid}`).attr('data-path', new_path);
|
||||
|
||||
retargetPaths(item.old_path, new_path, item.name);
|
||||
// Update all elements that have matching paths
|
||||
$(`[data-path="${html_encode(item.old_path)}" i]`).each(function () {
|
||||
$(this).attr('data-path', new_path);
|
||||
if ( $(this).hasClass('window-navbar-path-dirname') )
|
||||
{
|
||||
$(this).text(item.name);
|
||||
}
|
||||
});
|
||||
|
||||
// Update all elements whose paths start with old_path
|
||||
$(`[data-path^="${`${html_encode(item.old_path) }/`}"]`).each(function () {
|
||||
const new_el_path = $(this).attr('data-path').replace(`${item.old_path }/`, `${new_path }/`);
|
||||
$(this).attr('data-path', new_el_path);
|
||||
});
|
||||
|
||||
// Update all exact-matching windows
|
||||
$(`.window-${item.uid}`).each(function () {
|
||||
@@ -511,7 +507,7 @@ async function UIDesktop (options) {
|
||||
const metadata = parse_item_metadata(fsentry.metadata);
|
||||
|
||||
// update all shortcut_to_path
|
||||
atPath('.item', resp.old_path, 'data-shortcut_to_path').attr('data-shortcut_to_path', fsentry.path);
|
||||
$(`.item[data-shortcut_to_path="${html_encode(resp.old_path)}" i]`).attr('data-shortcut_to_path', html_encode(fsentry.path));
|
||||
|
||||
// remove all items with matching uids
|
||||
$(`.item[data-uid='${fsentry.uid}']`).fadeOut(150, function () {
|
||||
@@ -528,18 +524,17 @@ async function UIDesktop (options) {
|
||||
|
||||
// if trashing, close windows of trashed items and its descendants
|
||||
if ( dest_path === window.trash_path ) {
|
||||
atPath('.window', resp.old_path).close();
|
||||
// todo this has to be case-insensitive
|
||||
underPath('.window', resp.old_path).close();
|
||||
$(`.window[data-path="${html_encode(resp.old_path)}" i]`).close();
|
||||
// todo this has to be case-insensitive but the `i` selector doesn't work on ^=
|
||||
$(`.window[data-path^="${html_encode(resp.old_path)}/"]`).close();
|
||||
}
|
||||
|
||||
// update all paths of its and its descendants' open windows
|
||||
else {
|
||||
// todo this has to be case-insensitive
|
||||
underPath('.window', resp.old_path).add(atPath('.window', resp.old_path)).each(function () {
|
||||
window.update_window_path(this, fsentry.path + $(this).attr('data-path').slice(resp.old_path.length));
|
||||
// todo this has to be case-insensitive but the `i` selector doesn't work on ^=
|
||||
$(`.window[data-path^="${html_encode(resp.old_path)}/"], .window[data-path="${html_encode(resp.old_path)}" i]`).each(function () {
|
||||
window.update_window_path(this, $(this).attr('data-path').replace(resp.old_path, fsentry.path));
|
||||
});
|
||||
retargetNavHistory(resp.old_path, fsentry.path);
|
||||
}
|
||||
|
||||
if ( dest_path === window.trash_path ) {
|
||||
@@ -563,18 +558,13 @@ async function UIDesktop (options) {
|
||||
// Trashing renames the entry to its uid; the real name is in metadata.
|
||||
fsentry.name = metadata.original_name ?? fsentry.name;
|
||||
|
||||
const moved_item_icon = await item_icon(fsentry);
|
||||
const $dest_containers = atPath('.item-container', dest_path);
|
||||
// the tab that made this move renders the row itself, in either order
|
||||
$dest_containers.find(`.item[data-uid='${fsentry.uid}']`).removeItems();
|
||||
|
||||
// create new item on matching containers
|
||||
UIItem({
|
||||
appendTo: $dest_containers,
|
||||
appendTo: $(`.item-container[data-path='${html_encode(dest_path)}' i]`),
|
||||
immutable: fsentry.immutable || fsentry.writable === false,
|
||||
uid: fsentry.uid,
|
||||
path: fsentry.path,
|
||||
icon: moved_item_icon,
|
||||
icon: await item_icon(fsentry),
|
||||
name: fsentry.name,
|
||||
is_dir: fsentry.is_dir,
|
||||
size: fsentry.size,
|
||||
@@ -595,8 +585,8 @@ async function UIDesktop (options) {
|
||||
// if these new path have any open parents that need to be updated
|
||||
|
||||
fsentry.parent_dirs_created.forEach(async dir => {
|
||||
let item_container = atPath('.item-container', path.dirname(dir.path));
|
||||
if ( item_container.length > 0 && atPath('.item', dir.path).length === 0 ) {
|
||||
let item_container = $(`.item-container[data-path='${html_encode(path.dirname(dir.path))}' i]`);
|
||||
if ( item_container.length > 0 && $(`.item[data-path="${html_encode(dir.path)}" i]`).length === 0 ) {
|
||||
UIItem({
|
||||
appendTo: item_container,
|
||||
immutable: false,
|
||||
@@ -616,7 +606,7 @@ async function UIDesktop (options) {
|
||||
});
|
||||
}
|
||||
//sort each container
|
||||
atPath('.item-container', dest_path).each(function () {
|
||||
$(`.item-container[data-path='${html_encode(dest_path)}' i]`).each(function () {
|
||||
window.sort_items(this, $(this).attr('data-sort_by'), $(this).attr('data-sort_order'));
|
||||
});
|
||||
});
|
||||
@@ -703,7 +693,20 @@ async function UIDesktop (options) {
|
||||
$(`.item[data-uid='${item.uid}']`).attr('data-path', new_path);
|
||||
$(`.window-${item.uid}`).attr('data-path', new_path);
|
||||
|
||||
retargetPaths(item.old_path, new_path, item.name);
|
||||
// Update all elements that have matching paths
|
||||
$(`[data-path="${html_encode(item.old_path)}" i]`).each(function () {
|
||||
$(this).attr('data-path', new_path);
|
||||
if ( $(this).hasClass('window-navbar-path-dirname') )
|
||||
{
|
||||
$(this).text(item.name);
|
||||
}
|
||||
});
|
||||
|
||||
// Update all elements whose paths start with old_path
|
||||
$(`[data-path^="${`${html_encode(item.old_path) }/`}"]`).each(function () {
|
||||
const new_el_path = $(this).attr('data-path').replace(`${item.old_path }/`, `${new_path }/`);
|
||||
$(this).attr('data-path', new_el_path);
|
||||
});
|
||||
|
||||
// Update all exact-matching windows
|
||||
$(`.window-${item.uid}`).each(function () {
|
||||
|
||||
+17
-48
@@ -35,7 +35,6 @@ import { is_owned_by_me } from '../helpers/pathOwner.js';
|
||||
import { can_rename, can_restructure, invalidate_shared_roots, shared_mode_for } from '../helpers/sharedAccess.js';
|
||||
import { is_default_app } from '../helpers/defaultApp.js';
|
||||
import openWithAI from '../helpers/openWithAI.js';
|
||||
import refresh_item_container from '../helpers/refreshItemContainer.js';
|
||||
|
||||
async function UIItem (options) {
|
||||
const matching_appendto_count = $(options.appendTo).length;
|
||||
@@ -65,7 +64,6 @@ async function UIItem (options) {
|
||||
options.share_mode = options.share_mode ?? '';
|
||||
options.shared_by = options.shared_by ?? '';
|
||||
options.is_team_share = options.is_team_share ?? false;
|
||||
options.is_also_team_share = options.is_also_team_share ?? false;
|
||||
options.owner = options.owner ?? '';
|
||||
options.metadata = options.metadata ?? '';
|
||||
options.multiselectable = (options.multiselectable === undefined || options.multiselectable === true) ? true : false;
|
||||
@@ -104,7 +102,6 @@ async function UIItem (options) {
|
||||
data-share_mode="${html_encode(options.share_mode)}"
|
||||
data-shared_by="${html_encode(options.shared_by)}"
|
||||
data-is_team_share="${options.is_team_share ? 1 : 0}"
|
||||
data-is_also_team_share="${options.is_also_team_share ? 1 : 0}"
|
||||
data-owner="${html_encode(options.owner)}"
|
||||
data-has_website="${show_website_badge ? 1 : 0 }"
|
||||
data-website_url = "${website_url ? html_encode(website_url) : ''}"
|
||||
@@ -396,7 +393,7 @@ async function UIItem (options) {
|
||||
// do not highlight if the target is the same as the item being moved
|
||||
$(el_item).attr('data-path') !== $(window.mouseover_item_container).attr('data-path') &&
|
||||
// do not highlight if item is being moved to where it already is
|
||||
path.dirname($(el_item).attr('data-path')) !== $(window.mouseover_item_container).attr('data-path') ) {
|
||||
$(el_item).attr('data-path') !== $(window.mouseover_item_container).attr('data-path') ) {
|
||||
|
||||
// highlight item container
|
||||
$(window.mouseover_item_container).addClass('item-container-active');
|
||||
@@ -416,8 +413,7 @@ async function UIItem (options) {
|
||||
},
|
||||
stop: function (event, ui) {
|
||||
// Allow rearranging only if item is on desktop, not trash container, auto arrange is disabled and item is not dropped into another item
|
||||
// the desktop itself, not a window showing the Desktop folder
|
||||
if ( $(el_item).closest('.item-container').hasClass('desktop') &&
|
||||
if ( $(el_item).closest('.item-container').attr('data-path') === window.desktop_path &&
|
||||
!window.is_auto_arrange_enabled && $(el_item).attr('data-path') !== window.trash_path && !ui.helper.data('dropped') &&
|
||||
// Item must be dropped on the Desktop and not on the taskbar
|
||||
window.mouseover_window === undefined && ui.position.top <= window.desktop_height - window.taskbar_height - 15 ) {
|
||||
@@ -435,9 +431,7 @@ async function UIItem (options) {
|
||||
// re-enable all droppable UIItems that are not a dir
|
||||
$('.item[data-is_dir=\'0\']:not(.item-selected)').droppable('enable');
|
||||
// remove active item-container border highlights
|
||||
$('.item-container').removeClass('item-container-active item-container-transparent-border');
|
||||
// a drop that bailed out early never re-enables the containers an item's hover disabled
|
||||
$('.item-container.ui-droppable').droppable('enable');
|
||||
$('.item-container').removeClass('item-container-active');
|
||||
// reset longer hover timeout and last window dragged over
|
||||
clearTimeout(longer_hover_timeout);
|
||||
last_window_dragged_over = null;
|
||||
@@ -551,14 +545,11 @@ async function UIItem (options) {
|
||||
}
|
||||
// Otherwise, move items
|
||||
else if ( options.is_dir ) {
|
||||
// a selected folder can be the drop target of its own selection; it stays where it is
|
||||
const items_to_drop = items_to_move.filter(item => $(item).attr('data-uid') !== $(el_item).attr('data-uid'));
|
||||
if ( $(el_item).closest('.item-container').attr('data-path') === window.desktop_path ) {
|
||||
// the items leaving the desktop lose their saved positions, not the folder they land in
|
||||
items_to_drop.forEach(item => delete window.desktop_item_positions[$(item).attr('data-uid')]);
|
||||
delete window.desktop_item_positions[$(el_item).attr('data-uid')];
|
||||
window.save_desktop_item_positions();
|
||||
}
|
||||
window.move_items(items_to_drop, $(el_item).attr('data-shortcut_to_path') !== '' ? $(el_item).attr('data-shortcut_to_path') : $(el_item).attr('data-path'));
|
||||
window.move_items(items_to_move, $(el_item).attr('data-shortcut_to_path') !== '' ? $(el_item).attr('data-shortcut_to_path') : $(el_item).attr('data-path'));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -569,9 +560,8 @@ async function UIItem (options) {
|
||||
},
|
||||
over: function (event, ui) {
|
||||
// Check hovering over an item that is VISIBILE
|
||||
// A desktop item has no window, so it only counts while the pointer is over the desktop itself
|
||||
const $event_parent_win = $(event.target).closest('.window');
|
||||
if ( $event_parent_win.attr('data-id') !== $(window.mouseover_window).attr('data-id') )
|
||||
if ( $event_parent_win.length > 0 && $event_parent_win.attr('data-id') !== $(window.mouseover_window).attr('data-id') )
|
||||
{
|
||||
return;
|
||||
}
|
||||
@@ -729,7 +719,7 @@ async function UIItem (options) {
|
||||
}
|
||||
});
|
||||
|
||||
$(document).on(`click.item-${item_id}`, function (e) {
|
||||
$(document).on('click', function (e) {
|
||||
if ( !$(e.target).hasClass('item') && !$(e.target).hasClass('item-name') && !$(e.target).hasClass('item-icon') ) {
|
||||
skip_a_rename_click = true;
|
||||
}
|
||||
@@ -738,10 +728,6 @@ async function UIItem (options) {
|
||||
skip_a_rename_click = true;
|
||||
}
|
||||
});
|
||||
// a document handler outlives the row unless it is released with it
|
||||
$(el_item).on('remove', function () {
|
||||
$(document).off(`click.item-${item_id}`);
|
||||
});
|
||||
|
||||
// --------------------------------------------------------
|
||||
// Rename
|
||||
@@ -749,7 +735,6 @@ async function UIItem (options) {
|
||||
function rename () {
|
||||
if ( rename_cancelled ) {
|
||||
rename_cancelled = false;
|
||||
$(el_item_name_editor).removeClass('item-name-editor-active');
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -769,12 +754,10 @@ async function UIItem (options) {
|
||||
UIAlert('The name ".." is not allowed, because it is a reserved name. Please choose another name.');
|
||||
}
|
||||
|
||||
$(el_item_name).html(html_encode(truncate_filename($(el_item).attr('data-name'))));
|
||||
$(el_item_name).html(html_encode(truncate_filename(options.name)));
|
||||
$(el_item_name).show();
|
||||
$(el_item_name_editor).val($(el_item).attr('data-name'));
|
||||
$(el_item_name_editor).hide();
|
||||
// the Delete shortcut skips an item whose editor is marked active
|
||||
$(el_item_name_editor).removeClass('item-name-editor-active');
|
||||
return;
|
||||
}
|
||||
// deactivate item name editable
|
||||
@@ -820,9 +803,8 @@ async function UIItem (options) {
|
||||
e.stopPropagation();
|
||||
e.preventDefault();
|
||||
rename_cancelled = true;
|
||||
$(el_item_name_editor).removeClass('item-name-editor-active');
|
||||
$(el_item_name_editor).hide();
|
||||
$(el_item_name_editor).val($(el_item).attr('data-name'));
|
||||
$(el_item_name_editor).val(options.name);
|
||||
$(el_item_name).show();
|
||||
}
|
||||
});
|
||||
@@ -881,11 +863,6 @@ async function UIItem (options) {
|
||||
return;
|
||||
}
|
||||
|
||||
// The menu is built after lookups that take time, so it opens where the pointer was when it was asked for.
|
||||
const menu_position = (isMobile.phone || isMobile.tablet)
|
||||
? { left: window.last_touch_x, top: window.last_touch_y }
|
||||
: { left: window.mouseX, top: window.mouseY };
|
||||
|
||||
// if editing item name, preserve native context menu
|
||||
if ( event.target === el_item_name_editor )
|
||||
{
|
||||
@@ -1157,7 +1134,7 @@ async function UIItem (options) {
|
||||
// try to find suitable apps
|
||||
const suitable_apps = await window.suggest_apps_for_fsentry({
|
||||
uid: options.uid,
|
||||
path: $(el_item).attr('data-path'),
|
||||
path: options.path,
|
||||
});
|
||||
if ( suitable_apps && suitable_apps.length > 0 ) {
|
||||
options.suggested_apps = suitable_apps;
|
||||
@@ -1295,7 +1272,7 @@ async function UIItem (options) {
|
||||
file_path: $(el_item).attr('data-path'),
|
||||
file_uid: $(el_item).attr('data-uid'),
|
||||
params: {
|
||||
source_path: $(el_item).attr('data-path'),
|
||||
source_path: options.path,
|
||||
},
|
||||
});
|
||||
},
|
||||
@@ -1342,7 +1319,7 @@ async function UIItem (options) {
|
||||
}
|
||||
else
|
||||
{
|
||||
window.trigger_download([$(el_item).attr('data-path')]);
|
||||
window.trigger_download([options.path]);
|
||||
}
|
||||
},
|
||||
});
|
||||
@@ -1457,13 +1434,12 @@ async function UIItem (options) {
|
||||
// -------------------------------------------
|
||||
// Cut
|
||||
// -------------------------------------------
|
||||
// Trashed items leave the Trash through Restore; moved any other way, they'd keep their uid as their name.
|
||||
if ( $(el_item).attr('data-immutable') === '0' && !is_trashed && may_restructure ) {
|
||||
if ( $(el_item).attr('data-immutable') === '0' ) {
|
||||
menu_items.push({
|
||||
html: i18n('cut'),
|
||||
onClick: function () {
|
||||
window.clipboard_op = 'move';
|
||||
window.clipboard = [$(el_item).attr('data-path')];
|
||||
window.clipboard = [options.path];
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -1475,7 +1451,7 @@ async function UIItem (options) {
|
||||
html: i18n('copy'),
|
||||
onClick: function () {
|
||||
window.clipboard_op = 'copy';
|
||||
window.clipboard = [{ path: $(el_item).attr('data-path') }];
|
||||
window.clipboard = [{ path: options.path }];
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -1523,7 +1499,7 @@ async function UIItem (options) {
|
||||
base_dir,
|
||||
options.appendTo,
|
||||
options.shortcut_to === '' ? options.uid : options.shortcut_to,
|
||||
options.shortcut_to_path === '' ? $(el_item).attr('data-path') : options.shortcut_to_path,
|
||||
options.shortcut_to_path === '' ? options.path : options.shortcut_to_path,
|
||||
);
|
||||
},
|
||||
});
|
||||
@@ -1553,13 +1529,7 @@ async function UIItem (options) {
|
||||
// Or mode lookups keep answering for a share we
|
||||
// just walked away from.
|
||||
invalidate_shared_roots();
|
||||
// A team that still shares it keeps it listed,
|
||||
// as the team's share.
|
||||
if ( $(el_item).attr('data-is_also_team_share') === '1' ) {
|
||||
refresh_item_container($(el_item).closest('.item-container'));
|
||||
} else {
|
||||
$(el_item).removeItems();
|
||||
}
|
||||
$(el_item).removeItems();
|
||||
} catch (e) {
|
||||
UIAlert({ message: e?.message ?? i18n('error_unknown_cause') });
|
||||
}
|
||||
@@ -1652,7 +1622,6 @@ async function UIItem (options) {
|
||||
// Create ContextMenu
|
||||
UIContextMenu({
|
||||
parent_element: ($(options.appendTo).hasClass('desktop') ? undefined : options.appendTo),
|
||||
position: menu_position,
|
||||
items: menu_items,
|
||||
});
|
||||
|
||||
|
||||
@@ -33,7 +33,6 @@ vi.mock('../helpers/launchApp.js', () => ({ default: vi.fn() }));
|
||||
vi.mock('../helpers/openItem.js', () => ({ default: vi.fn() }));
|
||||
vi.mock('../helpers/publishAsWebsite.js', () => ({ default: vi.fn() }));
|
||||
vi.mock('../helpers/openWithAI.js', () => ({ default: vi.fn() }));
|
||||
vi.mock('../helpers/refreshItemContainer.js', () => ({ default: vi.fn() }));
|
||||
|
||||
globalThis.$ = jQuery;
|
||||
globalThis.jQuery = jQuery;
|
||||
@@ -68,8 +67,6 @@ Object.assign(window, {
|
||||
|
||||
const { default: UIItem } = await import('./UIItem.js');
|
||||
const { default: UIContextMenu } = await import('./UIContextMenu.js');
|
||||
const { default: refresh_item_container } =
|
||||
await import('../helpers/refreshItemContainer.js');
|
||||
|
||||
const menuLabels = async (options) => {
|
||||
document.body.innerHTML =
|
||||
@@ -93,25 +90,14 @@ const menuLabels = async (options) => {
|
||||
return UIContextMenu.mock.calls[0][0].items.map((item) => item?.html);
|
||||
};
|
||||
|
||||
const removeFromShared = async (options) => {
|
||||
await menuLabels(options);
|
||||
await UIContextMenu.mock.calls[0][0].items
|
||||
.find((item) => item?.html === 'share_remove_from_shared')
|
||||
.onClick();
|
||||
};
|
||||
|
||||
describe('UIItem Remove from Shared', () => {
|
||||
beforeEach(() => {
|
||||
window.user = { username: 'alice' };
|
||||
window.trash_path = '/alice/Trash';
|
||||
window.puter = {
|
||||
fs: {
|
||||
listShared: vi.fn(async () => ({ items: [] })),
|
||||
unshare: vi.fn(async () => ({ revoked: 1 })),
|
||||
},
|
||||
fs: { listShared: vi.fn(async () => ({ items: [] })) },
|
||||
};
|
||||
globalThis.puter = window.puter;
|
||||
refresh_item_container.mockClear();
|
||||
});
|
||||
|
||||
it('is offered on an item shared with the user directly', async () => {
|
||||
@@ -123,19 +109,4 @@ describe('UIItem Remove from Shared', () => {
|
||||
expect($('.item').attr('data-is_team_share')).toBe('1');
|
||||
expect(labels).not.toContain('share_remove_from_shared');
|
||||
});
|
||||
|
||||
it('takes the item away once the user has left it', async () => {
|
||||
await removeFromShared({});
|
||||
expect(puter.fs.unshare).toHaveBeenCalledWith('/bob/u-1/Photos', 'alice');
|
||||
expect($('.item')).toHaveLength(0);
|
||||
expect(refresh_item_container).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('lists the item again when a team still shares it', async () => {
|
||||
await removeFromShared({ is_also_team_share: true });
|
||||
expect(puter.fs.unshare).toHaveBeenCalledWith('/bob/u-1/Photos', 'alice');
|
||||
expect($('.item')).toHaveLength(1);
|
||||
expect(refresh_item_container).toHaveBeenCalledTimes(1);
|
||||
expect(refresh_item_container.mock.calls[0][0][0]).toBe($('.item-container')[0]);
|
||||
});
|
||||
});
|
||||
+128
-146
@@ -25,8 +25,6 @@ import UIAuthLogin from './Auth/UIAuthLogin.js';
|
||||
import UIWindowItemProperties from './UIWindowItemProperties.js';
|
||||
import new_context_menu_item from '../helpers/newContextMenuItem.js';
|
||||
import refresh_item_container from '../helpers/refreshItemContainer.js';
|
||||
import { atPath } from '../helpers/pathElements.js';
|
||||
import { resolve_typed_path } from '../helpers/expandHomePath.js';
|
||||
import UIWindowAppFeedback from './UIWindowAppFeedback.js';
|
||||
import launch_app from '../helpers/launchApp.js';
|
||||
import publish_as_website from '../helpers/publishAsWebsite.js';
|
||||
@@ -348,18 +346,7 @@ async function UIWindow (options) {
|
||||
if ( ! items.some(item => item.path === window.home_path) ) {
|
||||
items.unshift({ path: window.home_path, name: i18n('home') });
|
||||
}
|
||||
// A saved order stores the label it was rendered with; system folders follow the current language instead.
|
||||
const system_folder_labels = {
|
||||
[window.home_path]: i18n('home'),
|
||||
[window.docs_path]: i18n('documents'),
|
||||
[window.public_path]: i18n('public'),
|
||||
[window.pictures_path]: i18n('pictures'),
|
||||
[window.desktop_path]: i18n('desktop'),
|
||||
[window.videos_path]: i18n('videos'),
|
||||
[window.shared_path]: i18n('shared'),
|
||||
};
|
||||
for ( let item of items ) {
|
||||
const label = system_folder_labels[item.path] ?? item.name;
|
||||
let icon;
|
||||
if ( item.path === window.home_path )
|
||||
{
|
||||
@@ -393,7 +380,7 @@ async function UIWindow (options) {
|
||||
{
|
||||
icon = window.icons['sidebar-folder.svg'];
|
||||
}
|
||||
h += `<div title="${html_encode(label)}" class="window-sidebar-item disable-user-select ${options.path === item.path ? 'window-sidebar-item-active' : ''}" data-path="${html_encode(item.path)}"><img draggable="false" class="window-sidebar-item-icon" src="${html_encode(icon)}">${html_encode(label)}</div>`;
|
||||
h += `<div title="${html_encode(item.label)}" class="window-sidebar-item disable-user-select ${options.path === item.path ? 'window-sidebar-item-active' : ''}" data-path="${html_encode(item.path)}"><img draggable="false" class="window-sidebar-item-icon" src="${html_encode(icon)}">${html_encode(item.name)}</div>`;
|
||||
}
|
||||
}
|
||||
h += '</div>';
|
||||
@@ -418,7 +405,7 @@ async function UIWindow (options) {
|
||||
// Path editor
|
||||
h += `<input class="window-navbar-path-input" data-path="${html_encode(options.path)}" value="${html_encode(options.path)}" spellcheck="false"/>`;
|
||||
// Layout settings
|
||||
h += `<img class="window-navbar-layout-settings" src="${html_encode(options.layout === 'icons' ? window.icons['layout-icons.svg'] : window.icons['layout-list.svg'])}" draggable="false" title="${i18n('window_click_to_change_layout')}">`;
|
||||
h += `<img class="window-navbar-layout-settings" src="${html_encode(options.layout === 'icons' ? window.icons['layout-icons.svg'] : window.icons['layout-list.svg'])}" draggable="false">`;
|
||||
h += '</div>';
|
||||
}
|
||||
|
||||
@@ -478,7 +465,7 @@ async function UIWindow (options) {
|
||||
|
||||
// Loading spinner
|
||||
h += '<div class="explorer-loading-spinner">';
|
||||
h += '<svg style="display:block; margin: 0 auto; " xmlns="http://www.w3.org/2000/svg" height="24" width="24" viewBox="0 0 24 24"><g fill="#212121" class="nc-icon-wrapper"><g class="nc-loop-circle-24-icon-f"><path d="M12 24a12 12 0 1 1 12-12 12.013 12.013 0 0 1-12 12zm0-22a10 10 0 1 0 10 10A10.011 10.011 0 0 0 12 2z" fill="#212121" opacity=".4"></path><path d="M24 12h-2A10.011 10.011 0 0 0 12 2V0a12.013 12.013 0 0 1 12 12z" data-color="color-2"></path></g><style>.nc-loop-circle-24-icon-f{--animation-duration:0.5s;transform-origin:12px 12px;animation:nc-loop-circle-anim var(--animation-duration) infinite linear}@keyframes nc-loop-circle-anim{0%{transform:rotate(0)}100%{transform:rotate(360deg)}}</style></g></svg>';
|
||||
h += '<svg style="display:block; margin: 0 auto; " xmlns="http://www.w3.org/2000/svg" height="24" width="24" viewBox="0 0 24 24"><title>circle anim</title><g fill="#212121" class="nc-icon-wrapper"><g class="nc-loop-circle-24-icon-f"><path d="M12 24a12 12 0 1 1 12-12 12.013 12.013 0 0 1-12 12zm0-22a10 10 0 1 0 10 10A10.011 10.011 0 0 0 12 2z" fill="#212121" opacity=".4"></path><path d="M24 12h-2A10.011 10.011 0 0 0 12 2V0a12.013 12.013 0 0 1 12 12z" data-color="color-2"></path></g><style>.nc-loop-circle-24-icon-f{--animation-duration:0.5s;transform-origin:12px 12px;animation:nc-loop-circle-anim var(--animation-duration) infinite linear}@keyframes nc-loop-circle-anim{0%{transform:rotate(0)}100%{transform:rotate(360deg)}}</style></g></svg>';
|
||||
h += `<p class="explorer-loading-spinner-msg">${i18n('loading')}...</p>`;
|
||||
h += '</div>';
|
||||
}
|
||||
@@ -1126,7 +1113,7 @@ async function UIWindow (options) {
|
||||
|
||||
// build item for context menu
|
||||
items.push({
|
||||
html: `<span>${html_encode(nav_history_label(history_item))}</span>`,
|
||||
html: `<span>${history_item === window.home_path ? i18n('home') : html_encode(path.basename(history_item))}</span>`,
|
||||
val: index,
|
||||
onClick: async function (e) {
|
||||
let history_index = e.value;
|
||||
@@ -1199,7 +1186,7 @@ async function UIWindow (options) {
|
||||
|
||||
// build item for context menu
|
||||
items.push({
|
||||
html: `<span>${html_encode(nav_history_label(history_item))}</span>`,
|
||||
html: `<span>${history_item === window.home_path ? 'Home' : html_encode(path.basename(history_item))}</span>`,
|
||||
val: index,
|
||||
onClick: async function (e) {
|
||||
let history_index = e.value;
|
||||
@@ -1345,8 +1332,6 @@ async function UIWindow (options) {
|
||||
$(el_window).on('remove', function (e) {
|
||||
// if on_close callback is set, call it
|
||||
options.on_close?.();
|
||||
delete window.window_nav_history[win_id];
|
||||
delete window.window_nav_history_current_position[win_id];
|
||||
});
|
||||
|
||||
// --------------------------------------------------------
|
||||
@@ -1440,18 +1425,18 @@ async function UIWindow (options) {
|
||||
.on('beforedrag', evt => {
|
||||
})
|
||||
.on('start', ({ store, event }) => {
|
||||
// Get the scroll position of the window body
|
||||
const scrollLeft = $(el_window_body).scrollLeft();
|
||||
const scrollTop = $(el_window_body).scrollTop();
|
||||
|
||||
// Get the window body's bounding rect relative to the viewport
|
||||
const windowBodyRect = el_window_body.getBoundingClientRect();
|
||||
|
||||
// Calculate position relative to the window body (accounting for scroll)
|
||||
selection_area_start_x = window.mouseX - windowBodyRect.left + scrollLeft;
|
||||
selection_area_start_y = window.mouseY - windowBodyRect.top + scrollTop;
|
||||
|
||||
if ( !event.ctrlKey && !event.metaKey ) {
|
||||
// Get the scroll position of the window body
|
||||
const scrollLeft = $(el_window_body).scrollLeft();
|
||||
const scrollTop = $(el_window_body).scrollTop();
|
||||
|
||||
// Get the window body's bounding rect relative to the viewport
|
||||
const windowBodyRect = el_window_body.getBoundingClientRect();
|
||||
|
||||
// Calculate position relative to the window body (accounting for scroll)
|
||||
selection_area_start_x = window.mouseX - windowBodyRect.left + scrollLeft;
|
||||
selection_area_start_y = window.mouseY - windowBodyRect.top + scrollTop;
|
||||
|
||||
for ( const el of store.stored ) {
|
||||
el.classList.remove('item-selected');
|
||||
}
|
||||
@@ -1526,7 +1511,7 @@ async function UIWindow (options) {
|
||||
window.update_explorer_footer_selected_items_count(el_window);
|
||||
|
||||
// If this is openFileDialog, enable/disable the Open button accordingly
|
||||
if ( options.is_openFileDialog && $(el_window).find('.item-selected[data-is_dir="0"]').length )
|
||||
if ( options.is_openFileDialog && $(el_window).find('.item-selected').length )
|
||||
{
|
||||
$(el_openfiledialog_open_btn).removeClass('disabled');
|
||||
}
|
||||
@@ -1537,7 +1522,7 @@ async function UIWindow (options) {
|
||||
})
|
||||
.on('stop', ({ store, event }) => {
|
||||
// If this is openFileDialog, enable/disable the Open button accordingly
|
||||
if ( options.is_openFileDialog && $(el_window).find('.item-selected[data-is_dir="0"]').length )
|
||||
if ( options.is_openFileDialog && $(el_window).find('.item-selected').length )
|
||||
{
|
||||
$(el_openfiledialog_open_btn).removeClass('disabled');
|
||||
}
|
||||
@@ -1546,20 +1531,6 @@ async function UIWindow (options) {
|
||||
$(el_openfiledialog_open_btn).addClass('disabled');
|
||||
}
|
||||
});
|
||||
|
||||
$(document).on(`mouseup.window-selection-${win_id}`, function () {
|
||||
if ( selection_area ) {
|
||||
$(selection_area).hide();
|
||||
$(selection_area).remove();
|
||||
selection_area = null;
|
||||
}
|
||||
});
|
||||
|
||||
// viselect and the handler above listen on document, so they outlive the window unless released
|
||||
$(el_window).on('remove', function () {
|
||||
$(document).off(`mouseup.window-selection-${win_id}`);
|
||||
selection.destroy();
|
||||
});
|
||||
}
|
||||
|
||||
// --------------------------------------------------------
|
||||
@@ -2707,8 +2678,37 @@ async function UIWindow (options) {
|
||||
{
|
||||
html: i18n('empty_trash'),
|
||||
disabled: false,
|
||||
onClick: function () {
|
||||
window.empty_trash();
|
||||
onClick: async function () {
|
||||
// TODO: Merge this with window.empty_trash()
|
||||
const alert_resp = await UIAlert({
|
||||
message: i18n('empty_trash_confirmation'),
|
||||
buttons: [
|
||||
{
|
||||
label: i18n('yes'),
|
||||
value: 'yes',
|
||||
type: 'primary',
|
||||
},
|
||||
{
|
||||
label: i18n('no'),
|
||||
value: 'no',
|
||||
},
|
||||
],
|
||||
});
|
||||
if ( alert_resp === 'no' )
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// todo this has to be case-insensitive but the `i` selector doesn't work on ^=
|
||||
$(`.item[data-path^="${html_encode(window.trash_path)}/"]`).each(function () {
|
||||
window.delete_item(this);
|
||||
});
|
||||
// update other clients
|
||||
if ( window.socket ) {
|
||||
window.socket.emit('trash.is_empty', { is_empty: true });
|
||||
}
|
||||
// use the 'empty trash' icon
|
||||
window.update_trash_icons(true);
|
||||
},
|
||||
},
|
||||
],
|
||||
@@ -2844,6 +2844,14 @@ async function UIWindow (options) {
|
||||
});
|
||||
}
|
||||
|
||||
$(document).on('mouseup', function (e) {
|
||||
if ( selection_area ) {
|
||||
$(selection_area).hide();
|
||||
$(selection_area).remove();
|
||||
selection_area = null;
|
||||
}
|
||||
});
|
||||
|
||||
//set styles
|
||||
$(el_window_body).css(options.body_css);
|
||||
|
||||
@@ -3063,21 +3071,7 @@ $(document).on('blur', '.window-navbar-path-input', function (e) {
|
||||
|
||||
$(document).on('keyup', '.window-navbar-path-input', function (e) {
|
||||
if ( e.key === 'Enter' || e.keyCode === 13 ) {
|
||||
const $el_window = $(e.target).closest('.window');
|
||||
const win_id = $el_window.attr('data-id');
|
||||
const current_path = $el_window.attr('data-path');
|
||||
// Other code matches containers by exact path, so navigate to the canonical form.
|
||||
const target_path = resolve_typed_path($(e.target).val(), {
|
||||
current_path,
|
||||
home_path: window.home_path,
|
||||
shared_path: window.shared_path,
|
||||
});
|
||||
if ( target_path !== current_path && window.window_nav_history[win_id] ) {
|
||||
window.window_nav_history[win_id] = window.window_nav_history[win_id].slice(0, window.window_nav_history_current_position[win_id] + 1);
|
||||
window.window_nav_history[win_id].push(target_path);
|
||||
window.window_nav_history_current_position[win_id] = window.window_nav_history[win_id].length - 1;
|
||||
}
|
||||
window.update_window_path($el_window, target_path);
|
||||
window.update_window_path($(e.target).closest('.window'), $(e.target).val());
|
||||
$(e.target).hide();
|
||||
$(e.target).siblings('.window-navbar-path').show().select();
|
||||
}
|
||||
@@ -3341,14 +3335,6 @@ window.navbar_path = (abs_path) => {
|
||||
return str;
|
||||
};
|
||||
|
||||
// The root and the Shared view have no basename to show in the Back/Forward menus.
|
||||
const nav_history_label = (history_path) => {
|
||||
if ( history_path === window.home_path ) return i18n('home');
|
||||
if ( history_path === '/' ) return window.root_dirname;
|
||||
if ( history_path === window.shared_path ) return i18n('shared');
|
||||
return path.basename(history_path);
|
||||
};
|
||||
|
||||
window.update_window_path = async function (el_window, target_path) {
|
||||
const win_id = $(el_window).attr('data-id');
|
||||
const el_window_navbar_forward_btn = $(el_window).find('.window-navbar-btn-forward');
|
||||
@@ -3362,7 +3348,7 @@ window.update_window_path = async function (el_window, target_path) {
|
||||
|
||||
// update sidebar items' active status
|
||||
$(el_window).find('.window-sidebar-item').removeClass('window-sidebar-item-active');
|
||||
atPath($(el_window).find('.window-sidebar-item'), target_path).addClass('window-sidebar-item-active');
|
||||
$(el_window).find(`.window-sidebar-item[data-path="${html_encode(target_path)}"]`).addClass('window-sidebar-item-active');
|
||||
|
||||
// clean
|
||||
$(el_window).find('.explore-table-headers-th > .header-sort-icon').html('');
|
||||
@@ -3406,8 +3392,6 @@ window.update_window_path = async function (el_window, target_path) {
|
||||
|
||||
// empty body to be filled with the results of /readdir
|
||||
$(el_window_body).find('.item').removeItems();
|
||||
// nothing is selected in the folder being opened
|
||||
$(el_window).find('.openfiledialog-open-btn').addClass('disabled');
|
||||
|
||||
// add the 'Detail View' table header
|
||||
if ( $(el_window).find('.explore-table-headers').length === 0 )
|
||||
@@ -3448,10 +3432,8 @@ window.update_window_path = async function (el_window, target_path) {
|
||||
}
|
||||
}
|
||||
|
||||
$(el_window).attr('data-path', target_path);
|
||||
$(el_window).attr('data-name', path.basename(target_path));
|
||||
$(el_window_navbar_path_input).val(target_path);
|
||||
$(el_window_navbar_path_input).attr('data-path', target_path);
|
||||
$(el_window).attr('data-path', html_encode(target_path));
|
||||
$(el_window).attr('data-name', html_encode(path.basename(target_path)));
|
||||
|
||||
// /stat
|
||||
if ( target_path === window.shared_path ) {
|
||||
@@ -3462,72 +3444,72 @@ window.update_window_path = async function (el_window, target_path) {
|
||||
$(el_window).find('.window-head-icon').attr('src', window.icons['shared.svg']);
|
||||
}
|
||||
else if ( target_path !== '/' ) {
|
||||
puter.fs.stat({ path: target_path, consistency: 'eventual' }).then(fsentry => {
|
||||
// the window may have moved on while this stat was in flight
|
||||
if ( $(el_window).attr('data-path') !== target_path ) {
|
||||
return;
|
||||
}
|
||||
$(el_window).removeClass(`window-${ $(el_window).attr('data-uid')}`);
|
||||
$(el_window).addClass(`window-${ fsentry.id}`);
|
||||
$(el_window).attr('data-uid', fsentry.id);
|
||||
$(el_window).attr('data-sort_by', fsentry.sort_by ?? 'name');
|
||||
$(el_window).attr('data-sort_order', fsentry.sort_order ?? 'asc');
|
||||
$(el_window).attr('data-layout', fsentry.layout ?? 'icons');
|
||||
$(el_window_item_container).attr('data-uid', fsentry.id);
|
||||
// title - use i18n for system directories
|
||||
if ( target_path === window.home_path )
|
||||
{
|
||||
$(el_window).find('.window-head-title').text(i18n('home'));
|
||||
}
|
||||
else if ( target_path === window.desktop_path )
|
||||
{
|
||||
$(el_window).find('.window-head-title').text(i18n('desktop'));
|
||||
}
|
||||
else if ( target_path === window.docs_path || target_path === window.documents_path )
|
||||
{
|
||||
$(el_window).find('.window-head-title').text(i18n('documents'));
|
||||
}
|
||||
else if ( target_path === window.pictures_path )
|
||||
{
|
||||
$(el_window).find('.window-head-title').text(i18n('pictures'));
|
||||
}
|
||||
else if ( target_path === window.videos_path )
|
||||
{
|
||||
$(el_window).find('.window-head-title').text(i18n('videos'));
|
||||
}
|
||||
else if ( target_path === window.public_path )
|
||||
{
|
||||
$(el_window).find('.window-head-title').text(i18n('public'));
|
||||
}
|
||||
else if ( target_path === window.trash_path )
|
||||
{
|
||||
$(el_window).find('.window-head-title').text(i18n('trash'));
|
||||
}
|
||||
else
|
||||
{
|
||||
$(el_window).find('.window-head-title').text(fsentry.name);
|
||||
}
|
||||
// data-name
|
||||
$(el_window).attr('data-name', fsentry.name);
|
||||
// data-path
|
||||
$(el_window).attr('data-path', target_path);
|
||||
$(el_window_navbar_path_input).val(target_path);
|
||||
$(el_window_navbar_path_input).attr('data-path', target_path);
|
||||
// update layout
|
||||
window.update_window_layout(el_window, fsentry.layout);
|
||||
// update explore header if in details view
|
||||
if ( fsentry.layout === 'details' ) {
|
||||
window.update_details_layout_sort_visuals(el_window, fsentry.sort_by, fsentry.sort_order);
|
||||
}
|
||||
}).catch(() => {
|
||||
if ( $(el_window).attr('data-path') !== target_path ) {
|
||||
return;
|
||||
}
|
||||
// The folder couldn't be read, so the window must stop identifying as the previous one.
|
||||
$(el_window).removeClass(`window-${ $(el_window).attr('data-uid')}`);
|
||||
$(el_window).attr('data-uid', 'null');
|
||||
$(el_window).find('.window-head-title').text(path.basename(target_path));
|
||||
});
|
||||
try {
|
||||
puter.fs.stat({ path: target_path, consistency: 'eventual' }).then(fsentry => {
|
||||
// the window may have moved on while this stat was in flight
|
||||
if ( $(el_window).attr('data-path') !== html_encode(target_path) ) {
|
||||
return;
|
||||
}
|
||||
$(el_window).removeClass(`window-${ $(el_window).attr('data-uid')}`);
|
||||
$(el_window).addClass(`window-${ fsentry.id}`);
|
||||
$(el_window).attr('data-uid', fsentry.id);
|
||||
$(el_window).attr('data-sort_by', fsentry.sort_by ?? 'name');
|
||||
$(el_window).attr('data-sort_order', fsentry.sort_order ?? 'asc');
|
||||
$(el_window).attr('data-layout', fsentry.layout ?? 'icons');
|
||||
$(el_window_item_container).attr('data-uid', fsentry.id);
|
||||
// title - use i18n for system directories
|
||||
if ( target_path === window.home_path )
|
||||
{
|
||||
$(el_window).find('.window-head-title').text(i18n('home'));
|
||||
}
|
||||
else if ( target_path === window.desktop_path )
|
||||
{
|
||||
$(el_window).find('.window-head-title').text(i18n('desktop'));
|
||||
}
|
||||
else if ( target_path === window.docs_path || target_path === window.documents_path )
|
||||
{
|
||||
$(el_window).find('.window-head-title').text(i18n('documents'));
|
||||
}
|
||||
else if ( target_path === window.pictures_path )
|
||||
{
|
||||
$(el_window).find('.window-head-title').text(i18n('pictures'));
|
||||
}
|
||||
else if ( target_path === window.videos_path )
|
||||
{
|
||||
$(el_window).find('.window-head-title').text(i18n('videos'));
|
||||
}
|
||||
else if ( target_path === window.public_path )
|
||||
{
|
||||
$(el_window).find('.window-head-title').text(i18n('public'));
|
||||
}
|
||||
else if ( target_path === window.trash_path )
|
||||
{
|
||||
$(el_window).find('.window-head-title').text(i18n('trash'));
|
||||
}
|
||||
else
|
||||
{
|
||||
$(el_window).find('.window-head-title').text(fsentry.name);
|
||||
}
|
||||
// data-name
|
||||
$(el_window).attr('data-name', html_encode(fsentry.name));
|
||||
// data-path
|
||||
$(el_window).attr('data-path', html_encode(target_path));
|
||||
$(el_window_navbar_path_input).val(target_path);
|
||||
$(el_window_navbar_path_input).attr('data-path', target_path);
|
||||
// update layout
|
||||
window.update_window_layout(el_window, fsentry.layout);
|
||||
// update explore header if in details view
|
||||
if ( fsentry.layout === 'details' ) {
|
||||
window.update_details_layout_sort_visuals(el_window, fsentry.sort_by, fsentry.sort_order);
|
||||
}
|
||||
});
|
||||
} catch ( err ) {
|
||||
UIAlert(err.responseText);
|
||||
|
||||
// todo optim: this is dumb because updating the window should only happen if this /readdir request is successful,
|
||||
// in that case there is no need for using update_window_path on error!!
|
||||
window.update_window_path(el_window, old_path);
|
||||
}
|
||||
}
|
||||
// path is '/' (global root)
|
||||
else {
|
||||
@@ -3883,7 +3865,7 @@ window.scale_window = (el_window) => {
|
||||
|
||||
window.update_explorer_footer_item_count = function (el_window) {
|
||||
//update dir count in explorer footer
|
||||
let item_count = $(el_window).find('.item:not(.item-hidden)').length;
|
||||
let item_count = $(el_window).find('.item').length;
|
||||
$(el_window).find('.explorer-footer .explorer-footer-item-count').html(`${item_count } ${i18n('item')}${ item_count == 0 || item_count > 1 ? `${i18n('plural_suffix')}` : ''}`);
|
||||
};
|
||||
|
||||
|
||||
@@ -19,7 +19,6 @@
|
||||
|
||||
import UIWindow from './UIWindow.js';
|
||||
import UIWindowMyWebsites from './UIWindowMyWebsites.js';
|
||||
import { underPath } from '../helpers/pathElements.js';
|
||||
|
||||
async function UIWindowPublishWebsite (target_dir_uid, target_dir_name, target_dir_path) {
|
||||
let h = '';
|
||||
@@ -111,7 +110,7 @@ async function UIWindowPublishWebsite (target_dir_uid, target_dir_name, target_d
|
||||
});
|
||||
|
||||
// find all items whose path starts with target_dir_path
|
||||
underPath('.item', target_dir_path).each(function () {
|
||||
$(`.item[data-path^="${target_dir_path}/"]`).each(function () {
|
||||
// show the link badge
|
||||
$(this).find('.item-has-website-url-badge').show();
|
||||
// update item's website_url attribute
|
||||
|
||||
@@ -19,7 +19,6 @@
|
||||
|
||||
import UIWindow from './UIWindow.js';
|
||||
import UIWindowMyWebsites from './UIWindowMyWebsites.js';
|
||||
import { underPath } from '../helpers/pathElements.js';
|
||||
|
||||
async function UIWindowPublishWorker (target_dir_uid, target_dir_name, target_dir_path) {
|
||||
let h = '';
|
||||
@@ -118,7 +117,7 @@ async function UIWindowPublishWorker (target_dir_uid, target_dir_name, target_di
|
||||
});
|
||||
|
||||
// find all items whose path starts with target_dir_path
|
||||
underPath('.item', target_dir_path).each(function () {
|
||||
$(`.item[data-path^="${target_dir_path}/"]`).each(function () {
|
||||
// show the link badge
|
||||
// $(this).find('.item-has-website-url-badge').show();
|
||||
// update item's website_url attribute
|
||||
|
||||
@@ -500,9 +500,8 @@ input[type=text]:focus, input[type=password]:focus, input[type=email]:focus, sel
|
||||
|
||||
.explore-table-headers {
|
||||
display: none;
|
||||
/* the negative margin below shifts it left by the body's padding */
|
||||
width: calc(100% + 10px);
|
||||
min-width: 805px;
|
||||
width: 100%;
|
||||
min-width: 795px;
|
||||
height: 25px;
|
||||
border-bottom: 1px solid rgb(226, 226, 226);
|
||||
background-color: #fff;
|
||||
@@ -535,7 +534,6 @@ span.header-sort-icon img {
|
||||
margin-left: 15px;
|
||||
color: #555c61;
|
||||
display: inline-block;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.explore-table-headers-th-active {
|
||||
@@ -844,14 +842,6 @@ span.header-sort-icon img {
|
||||
color: white;
|
||||
}
|
||||
|
||||
.device-desktop .item-container-details .item-selected.item-blurred {
|
||||
background-color: #dbdada;
|
||||
}
|
||||
|
||||
.device-desktop .item-container-details .item-selected.item-blurred .item-attr {
|
||||
color: rgb(73, 73, 73);
|
||||
}
|
||||
|
||||
.item-container-details .item-attr--modified {
|
||||
left: 350px;
|
||||
}
|
||||
@@ -1209,22 +1199,6 @@ span.header-sort-icon img {
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
/* A path too long for the bar is cut at the root end, so the current folder stays visible. */
|
||||
.window-navbar-path {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
align-items: baseline;
|
||||
min-height: 37px;
|
||||
}
|
||||
|
||||
.window-navbar-path > * {
|
||||
flex: none;
|
||||
}
|
||||
|
||||
.window-navbar-path > :last-child {
|
||||
margin-right: auto;
|
||||
}
|
||||
|
||||
.device-phone .window-navbar-path {
|
||||
display: none;
|
||||
}
|
||||
@@ -1234,7 +1208,6 @@ span.header-sort-icon img {
|
||||
height: 30px;
|
||||
margin-left: 10px;
|
||||
margin-top: 3px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.device-phone .window-navbar-layout-settings {
|
||||
|
||||
+117
-140
@@ -23,7 +23,6 @@ import { archiveEntryPath } from './helpers/archiveEntryPath.js';
|
||||
import get_html_element_from_options from './helpers/getHtmlElementFromOptions.js';
|
||||
import globToRegExp from './helpers/globToRegExp.js';
|
||||
import item_icon from './helpers/itemIcon.js';
|
||||
import { atPath, retargetNavHistory, retargetPaths, underPath } from './helpers/pathElements.js';
|
||||
import { is_owned_by_me, trash_path_for } from './helpers/pathOwner.js';
|
||||
import { invalidate_shared_roots } from './helpers/sharedAccess.js';
|
||||
import truncate_filename from './helpers/truncateFilename.js';
|
||||
@@ -32,13 +31,11 @@ import update_username_in_gui from './helpers/updateUsernameInGui.js';
|
||||
import { notifyItemWatchers } from './helpers/watchItems.js';
|
||||
import { select_uploaded_items } from './helpers/uploadSelection.js';
|
||||
import { templateMenuItem } from './helpers/templateMenuItem.js';
|
||||
import { isTokenForAnotherUser } from './helpers/tokenUser.js';
|
||||
import { uuidv4 } from './helpers/uuidv4.js';
|
||||
import mime from './lib/mime.js';
|
||||
import path from './lib/path.js';
|
||||
import UIAlert from './UI/UIAlert.js';
|
||||
import UIItem from './UI/UIItem.js';
|
||||
import { compareEntries, compareNames } from './UI/Dashboard/sortEntries.js';
|
||||
import UIAuthLogin from './UI/Auth/UIAuthLogin.js';
|
||||
import UIWindowProgress from './UI/UIWindowProgress.js';
|
||||
import UIWindowSaveAccount from './UI/UIWindowSaveAccount.js';
|
||||
@@ -627,6 +624,10 @@ window.refresh_user_data = async (auth_token) => {
|
||||
|
||||
window.update_auth_data = async (auth_token, user) => {
|
||||
window.auth_token = auth_token;
|
||||
// Write the v2 key going forward and clear any lingering v1 key so
|
||||
// a single localStorage source-of-truth is used.
|
||||
localStorage.setItem(window.AUTH_TOKEN_KEY_V2, auth_token);
|
||||
localStorage.removeItem(window.AUTH_TOKEN_KEY_RETIRED);
|
||||
|
||||
// Set http-only session cookie when user is changing.
|
||||
// This ensures user-protected endpoints, which only refer to the http-only cookie,
|
||||
@@ -652,13 +653,6 @@ window.update_auth_data = async (auth_token, user) => {
|
||||
}
|
||||
}
|
||||
|
||||
// Stored only after the cookie sync: a peer tab reloads when it sees
|
||||
// another account's token, and its boot signs in from the cookie.
|
||||
// A token adopted from a peer tab during the sync must not outlive it.
|
||||
window.auth_token = auth_token;
|
||||
localStorage.setItem(window.AUTH_TOKEN_KEY_V2, auth_token);
|
||||
localStorage.removeItem(window.AUTH_TOKEN_KEY_RETIRED);
|
||||
|
||||
// Has username changed?
|
||||
if ( window.user?.username !== user.username )
|
||||
{
|
||||
@@ -863,12 +857,6 @@ if ( typeof window !== 'undefined' && window.addEventListener ) {
|
||||
window.addEventListener('storage', (event) => {
|
||||
if ( event.key !== window.AUTH_TOKEN_KEY_V2 ) return;
|
||||
if ( event.newValue ) {
|
||||
// A peer tab changed accounts. Reload as that account instead of
|
||||
// sending its token from a desktop still showing this one.
|
||||
if ( isTokenForAnotherUser(event.newValue, window.user) ) {
|
||||
window.location.reload();
|
||||
return;
|
||||
}
|
||||
// A peer tab just (re)authed. Pick up the fresh token so
|
||||
// subsequent requests stop bouncing on reauth_required.
|
||||
window.auth_token = event.newValue;
|
||||
@@ -1121,19 +1109,48 @@ window.sort_items = (item_container, sort_by, sort_order) => {
|
||||
sort_order = 'asc';
|
||||
}
|
||||
|
||||
const direction = sort_order === 'asc' ? 1 : -1;
|
||||
$(item_container).find('.item[data-sortable="true"]').detach().sort(function (a, b) {
|
||||
const name_a = a.dataset.name;
|
||||
const name_b = b.dataset.name;
|
||||
if ( sort_by === 'type' ) {
|
||||
const by_extension = compareNames(path.extname(name_a).toLowerCase(), path.extname(name_b).toLowerCase());
|
||||
return direction * (by_extension || compareNames(name_a, name_b));
|
||||
// Name
|
||||
if ( !sort_by || sort_by === 'name' ) {
|
||||
if ( a.dataset.name.toLowerCase() < b.dataset.name.toLowerCase() ) {
|
||||
return (sort_order === 'asc' ? -1 : 1);
|
||||
}
|
||||
if ( a.dataset.name.toLowerCase() > b.dataset.name.toLowerCase() ) {
|
||||
return (sort_order === 'asc' ? 1 : -1);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
return direction * compareEntries(
|
||||
{ name: name_a, size: parseInt(a.dataset.size), modified: parseInt(a.dataset.modified) },
|
||||
{ name: name_b, size: parseInt(b.dataset.size), modified: parseInt(b.dataset.modified) },
|
||||
sort_by,
|
||||
);
|
||||
// Size
|
||||
else if ( sort_by === 'size' ) {
|
||||
if ( parseInt(a.dataset.size) < parseInt(b.dataset.size) ) {
|
||||
return (sort_order === 'asc' ? -1 : 1);
|
||||
}
|
||||
if ( parseInt(a.dataset.size) > parseInt(b.dataset.size) ) {
|
||||
return (sort_order === 'asc' ? 1 : -1);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
// Modified
|
||||
else if ( sort_by === 'modified' ) {
|
||||
if ( parseInt(a.dataset.modified) < parseInt(b.dataset.modified) ) {
|
||||
return (sort_order === 'asc' ? -1 : 1);
|
||||
}
|
||||
if ( parseInt(a.dataset.modified) > parseInt(b.dataset.modified) ) {
|
||||
return (sort_order === 'asc' ? 1 : -1);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
// Type
|
||||
else if ( sort_by === 'type' ) {
|
||||
if ( path.extname(a.dataset.name.toLowerCase()) < path.extname(b.dataset.name.toLowerCase()) ) {
|
||||
return (sort_order === 'asc' ? -1 : 1);
|
||||
}
|
||||
if ( path.extname(a.dataset.name.toLowerCase()) > path.extname(b.dataset.name.toLowerCase()) ) {
|
||||
return (sort_order === 'asc' ? 1 : -1);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
}).appendTo(item_container);
|
||||
};
|
||||
|
||||
@@ -1141,18 +1158,10 @@ window.show_or_hide_files = (item_containers) => {
|
||||
const show_hidden_files = window.user_preferences.show_hidden_files;
|
||||
const class_to_add = show_hidden_files ? 'item-revealed' : 'item-hidden';
|
||||
const class_to_remove = show_hidden_files ? 'item-hidden' : 'item-revealed';
|
||||
const $dotfiles = $(item_containers)
|
||||
$(item_containers)
|
||||
.find('.item')
|
||||
.filter((_, item) => item.dataset.name.startsWith('.'))
|
||||
.removeClass(class_to_remove).addClass(class_to_add);
|
||||
// an item the user can no longer see must not stay in the selection
|
||||
if ( ! show_hidden_files ) {
|
||||
$dotfiles.removeClass('item-selected');
|
||||
}
|
||||
$(item_containers).closest('.window').each(function () {
|
||||
window.update_explorer_footer_item_count(this);
|
||||
window.update_explorer_footer_selected_items_count(this);
|
||||
});
|
||||
};
|
||||
|
||||
window.create_folder = async (basedir, appendto_element) => {
|
||||
@@ -1169,7 +1178,7 @@ window.create_folder = async (basedir, appendto_element) => {
|
||||
rename: true,
|
||||
overwrite: false,
|
||||
success: function (data) {
|
||||
const el_created_dir = atPath($(appendto_element).find('.item'), `${dirname}/${data.name}`);
|
||||
const el_created_dir = $(appendto_element).find(`.item[data-path="${html_encode(dirname)}/${html_encode(data.name)}"]`);
|
||||
if ( el_created_dir.length > 0 ) {
|
||||
window.activate_item_name_editor(el_created_dir);
|
||||
|
||||
@@ -1202,7 +1211,7 @@ window.create_file = async (options) => {
|
||||
generateThumbnails: true,
|
||||
thumbnailGenerator: createUploadThumbnailGenerator(),
|
||||
success: async function (data) {
|
||||
const created_file = atPath($(appendto_element).find('.item'), `${dirname}/${data.name}`);
|
||||
const created_file = $(appendto_element).find(`.item[data-path="${html_encode(dirname)}/${html_encode(data.name)}"]`);
|
||||
if ( created_file.length > 0 ) {
|
||||
window.activate_item_name_editor(created_file);
|
||||
|
||||
@@ -1255,9 +1264,6 @@ window.available_templates = () => {
|
||||
};
|
||||
|
||||
window.create_shortcut = async (filename, is_dir, basedir, appendto_element, shortcut_to, shortcut_to_path) => {
|
||||
// The Shared view is a query, not a directory — nothing can be created in it.
|
||||
if ( basedir === window.shared_path ) return;
|
||||
|
||||
const extname = path.extname(filename);
|
||||
const basename = `${path.basename(filename, extname) } - Shortcut`;
|
||||
filename = basename + extname;
|
||||
@@ -1292,8 +1298,6 @@ window.copy_clipboard_items = async function (dest_path, dest_container_element)
|
||||
let progwin;
|
||||
let latest_status;
|
||||
const arm_progwin = () => setTimeout(async () => {
|
||||
// re-armed after a dialog while the window from before it is still open
|
||||
if ( progwin ) return;
|
||||
progwin = await UIWindowProgress({
|
||||
operation_id: copy_op_id,
|
||||
on_cancel: () => {
|
||||
@@ -1427,9 +1431,6 @@ window.copy_clipboard_items = async function (dest_path, dest_container_element)
|
||||
* @param {string} dest_path - Destination path to copy items to
|
||||
*/
|
||||
window.copy_items = function (el_items, dest_path) {
|
||||
// The Shared view is a query, not a directory — nothing can be copied into it.
|
||||
if ( dest_path === window.shared_path ) return;
|
||||
|
||||
let copy_op_id = window.operation_id++;
|
||||
let overwrite_all = false;
|
||||
(async () => {
|
||||
@@ -1439,8 +1440,6 @@ window.copy_items = function (el_items, dest_path) {
|
||||
let progwin;
|
||||
let latest_status;
|
||||
const arm_progwin = () => setTimeout(async () => {
|
||||
// re-armed after a dialog while the window from before it is still open
|
||||
if ( progwin ) return;
|
||||
progwin = await UIWindowProgress({
|
||||
operation_id: copy_op_id,
|
||||
on_cancel: () => {
|
||||
@@ -1584,8 +1583,8 @@ window.delete_item = async function (el_item, descendants_only = false) {
|
||||
// close all windows with matching uids
|
||||
$(`.window-${ $(el_item).attr('data-uid')}`).close();
|
||||
// close all windows that belong to a descendant of this item
|
||||
// todo this has to be case-insensitive
|
||||
underPath('.window', $(el_item).attr('data-path')).close();
|
||||
// todo this has to be case-insensitive but the `i` selector doesn't work on ^=
|
||||
$(`.window[data-path^="${$(el_item).attr('data-path')}/"]`).close();
|
||||
});
|
||||
|
||||
try {
|
||||
@@ -1606,7 +1605,7 @@ window.delete_item = async function (el_item, descendants_only = false) {
|
||||
window.update_explorer_footer_selected_items_count(this);
|
||||
});
|
||||
// update all shortcuts to this item
|
||||
atPath('.item', $(el_item).attr('data-path'), 'data-shortcut_to_path').attr('data-shortcut_to_path', '');
|
||||
$(`.item[data-shortcut_to_path="${html_encode($(el_item).attr('data-path'))}" i]`).attr('data-shortcut_to_path', '');
|
||||
});
|
||||
} catch ( err ) {
|
||||
// Nothing was deleted: bring back what was faded out above.
|
||||
@@ -1615,37 +1614,20 @@ window.delete_item = async function (el_item, descendants_only = false) {
|
||||
}
|
||||
};
|
||||
|
||||
window.move_clipboard_items = async function (el_target_container, target_path) {
|
||||
window.move_clipboard_items = function (el_target_container, target_path) {
|
||||
let dest_path = target_path === undefined ? $(el_target_container).attr('data-path') : target_path;
|
||||
const cut_paths = window.clipboard;
|
||||
window.clipboard = [];
|
||||
|
||||
// A cut item's row is gone once its folder is no longer displayed, so
|
||||
// move_items gets a stand-in carrying what it reads off a row.
|
||||
const el_items = (await Promise.all(cut_paths.map(async (cut_path) => {
|
||||
const $el_item = atPath('.item', cut_path);
|
||||
if ( $el_item.length > 0 ) {
|
||||
return $el_item;
|
||||
let el_items = [];
|
||||
if ( window.clipboard.length > 0 ) {
|
||||
for ( let i = 0; i < window.clipboard.length; i++ ) {
|
||||
el_items.push($(`.item[data-path="${html_encode(window.clipboard[i])}" i]`));
|
||||
}
|
||||
try {
|
||||
const fsentry = await puter.fs.stat({ path: cut_path, consistency: 'eventual' });
|
||||
return $('<div>').attr({
|
||||
'data-uid': fsentry.uid,
|
||||
'data-path': cut_path,
|
||||
'data-name': fsentry.name,
|
||||
'data-is_dir': fsentry.is_dir ? '1' : '0',
|
||||
'data-immutable': (fsentry.immutable || fsentry.writable === false) ? '1' : '0',
|
||||
'data-metadata': fsentry.metadata ?? '',
|
||||
});
|
||||
} catch ( e ) {
|
||||
// the item no longer exists, so there is nothing to move
|
||||
return null;
|
||||
if ( el_items.length > 0 )
|
||||
{
|
||||
window.move_items(el_items, dest_path);
|
||||
}
|
||||
}))).filter(Boolean);
|
||||
|
||||
if ( el_items.length > 0 ) {
|
||||
window.move_items(el_items, dest_path);
|
||||
}
|
||||
|
||||
window.clipboard = [];
|
||||
};
|
||||
|
||||
function downloadFile (url, postData = {}) {
|
||||
@@ -1703,7 +1685,7 @@ window.trigger_download = (paths) => {
|
||||
let urls = [];
|
||||
for ( let index = 0; index < paths.length; index++ ) {
|
||||
urls.push({
|
||||
download: `${window.origin }/down?path=${ encodeURIComponent(paths[index])}`,
|
||||
download: `${window.origin }/down?path=${ paths[index]}`,
|
||||
filename: path.basename(paths[index]),
|
||||
});
|
||||
}
|
||||
@@ -1809,8 +1791,6 @@ window.move_items = async function (el_items, dest_path, is_undo = false) {
|
||||
let progwin;
|
||||
let latest_status;
|
||||
const arm_progwin = () => setTimeout(async () => {
|
||||
// re-armed after a dialog while the window from before it is still open
|
||||
if ( progwin ) return;
|
||||
progwin = await UIWindowProgress({
|
||||
operation_id: move_op_id,
|
||||
on_cancel: () => {
|
||||
@@ -1858,8 +1838,7 @@ window.move_items = async function (el_items, dest_path, is_undo = false) {
|
||||
if ( path.dirname($(el_item).attr('data-path')) === item_dest_path ) {
|
||||
// pause the progress-window timer while waiting for the user
|
||||
clearTimeout(progwin_timeout);
|
||||
// UIAlert escapes the message itself
|
||||
await UIAlert(`<p>Moving <strong>${$(el_item).attr('data-name')}</strong></p>Cannot move item to its current location.`);
|
||||
await UIAlert(`<p>Moving <strong>${html_encode($(el_item).attr('data-name'))}</strong></p>Cannot move item to its current location.`);
|
||||
progwin_timeout = arm_progwin();
|
||||
|
||||
continue;
|
||||
@@ -1933,7 +1912,7 @@ window.move_items = async function (el_items, dest_path, is_undo = false) {
|
||||
}
|
||||
|
||||
// moving an item into a trashed directory? deny.
|
||||
else if ( dest_path === window.trash_path || dest_path.startsWith(`${window.trash_path}/`) ) {
|
||||
else if ( dest_path.startsWith(window.trash_path) ) {
|
||||
// the pending timer would otherwise open an orphan
|
||||
// progress window after the operation already bailed
|
||||
clearTimeout(progwin_timeout);
|
||||
@@ -1982,18 +1961,24 @@ window.move_items = async function (el_items, dest_path, is_undo = false) {
|
||||
// skip next loop iteration because this iteration was successful
|
||||
item_with_same_name_already_exists = false;
|
||||
|
||||
const moved_from_path = $(el_item).attr('data-path');
|
||||
|
||||
// update all shortcut_to_path
|
||||
atPath('.item', moved_from_path, 'data-shortcut_to_path').attr('data-shortcut_to_path', fsentry.path);
|
||||
// update all shortcut_to_path — compare raw attribute values
|
||||
// (item rows store paths unencoded, so an html_encode()d
|
||||
// selector misses names containing & < > " ')
|
||||
const moved_from_path_lc = String($(el_item).attr('data-path') || '').toLowerCase();
|
||||
$('.item[data-shortcut_to_path]').filter(function () {
|
||||
return String($(this).attr('data-shortcut_to_path')).toLowerCase() === moved_from_path_lc;
|
||||
}).attr('data-shortcut_to_path', fsentry.path);
|
||||
|
||||
// Remove all items with matching uids from their OLD location(s).
|
||||
// Exclude any row already at the item's new path: a concurrent
|
||||
// item.moved socket handler may have just created a row at the
|
||||
// destination (e.g. the dashboard file view showing the target
|
||||
// directory), and removing by uid alone would delete it too.
|
||||
const $moved_items = $(`.item[data-uid='${$(el_item).attr('data-uid')}']`);
|
||||
$moved_items.not(atPath($moved_items, fsentry.path)).fadeOut(150, function () {
|
||||
// Raw case-insensitive compare, for the same reason as above.
|
||||
const dest_item_path_lc = fsentry.path.toLowerCase();
|
||||
$(`.item[data-uid='${$(el_item).attr('data-uid')}']`).not(function () {
|
||||
return String($(this).attr('data-path') || '').toLowerCase() === dest_item_path_lc;
|
||||
}).fadeOut(150, function () {
|
||||
// find all parent windows that contain this item
|
||||
let parent_windows = $(`.item[data-uid='${$(el_item).attr('data-uid')}']`).closest('.window');
|
||||
// remove this item
|
||||
@@ -2007,24 +1992,23 @@ window.move_items = async function (el_items, dest_path, is_undo = false) {
|
||||
|
||||
// if trashing, close windows of trashed items and its descendants
|
||||
if ( is_trashing ) {
|
||||
atPath('.window', moved_from_path).close();
|
||||
// todo this has to be case-insensitive
|
||||
underPath('.window', moved_from_path).close();
|
||||
$(`.window[data-path="${html_encode($(el_item).attr('data-path'))}" i]`).close();
|
||||
// todo this has to be case-insensitive but the `i` selector doesn't work on ^=
|
||||
$(`.window[data-path^="${html_encode($(el_item).attr('data-path'))}/"]`).close();
|
||||
}
|
||||
|
||||
// update all paths of its and its descendants' open windows
|
||||
else {
|
||||
// todo this has to be case-insensitive
|
||||
underPath('.window', moved_from_path).add(atPath('.window', moved_from_path)).each(function () {
|
||||
window.update_window_path(this, path.join(item_dest_path, fsentry.name) + $(this).attr('data-path').slice(moved_from_path.length));
|
||||
// todo this has to be case-insensitive but the `i` selector doesn't work on ^=
|
||||
$(`.window[data-path^="${html_encode($(el_item).attr('data-path'))}/"], .window[data-path="${html_encode($(el_item).attr('data-path'))}" i]`).each(function () {
|
||||
window.update_window_path(this, $(this).attr('data-path').replace($(el_item).attr('data-path'), path.join(item_dest_path, fsentry.name)));
|
||||
});
|
||||
retargetNavHistory(moved_from_path, fsentry.path);
|
||||
}
|
||||
|
||||
// The dashboard's Back/Forward follows a moved folder, and
|
||||
// forgets a trashed one.
|
||||
if ( $(el_item).attr('data-is_dir') === '1' ) {
|
||||
window.dashboard_object?.folderMoved?.(moved_from_path, is_trashing ? null : fsentry.path);
|
||||
window.dashboard_object?.folderMoved?.($(el_item).attr('data-path'), is_trashing ? null : fsentry.path);
|
||||
}
|
||||
|
||||
if ( is_trashing ) {
|
||||
@@ -2046,19 +2030,14 @@ window.move_items = async function (el_items, dest_path, is_undo = false) {
|
||||
// if this is trash, get original name from item metadata
|
||||
fsentry.name = metadata?.original_name || fsentry.name;
|
||||
|
||||
const moved_item_icon = await item_icon(fsentry);
|
||||
const $dest_containers = atPath('.item-container', item_dest_path);
|
||||
// the item.moved echo of this move can render the row first
|
||||
$dest_containers.find(`.item[data-uid='${fsentry.uid}']`).removeItems();
|
||||
|
||||
// create new item on matching containers
|
||||
const options = {
|
||||
appendTo: $dest_containers,
|
||||
appendTo: $(`.item-container[data-path="${html_encode(item_dest_path)}" i]`),
|
||||
immutable: fsentry.immutable || (fsentry.writable === false),
|
||||
associated_app_name: fsentry.associated_app?.name,
|
||||
uid: fsentry.uid,
|
||||
path: fsentry.path,
|
||||
icon: moved_item_icon,
|
||||
icon: await item_icon(fsentry),
|
||||
name: is_trashing ? $(el_item).attr('data-name') : fsentry.name,
|
||||
is_dir: fsentry.is_dir,
|
||||
size: fsentry.size,
|
||||
@@ -2084,8 +2063,8 @@ window.move_items = async function (el_items, dest_path, is_undo = false) {
|
||||
// see if any of the directories in the path of this file is new AND
|
||||
// if these new path have any open parents that need to be updated
|
||||
resp.parent_dirs_created?.forEach(async dir => {
|
||||
let item_container = atPath('.item-container', path.dirname(dir.path));
|
||||
if ( item_container.length > 0 && atPath('.item', dir.path).length === 0 ) {
|
||||
let item_container = $(`.item-container[data-path="${html_encode(path.dirname(dir.path))}" i]`);
|
||||
if ( item_container.length > 0 && $(`.item[data-path="${html_encode(dir.path)}" i]`).length === 0 ) {
|
||||
UIItem({
|
||||
appendTo: item_container,
|
||||
immutable: false,
|
||||
@@ -2111,7 +2090,7 @@ window.move_items = async function (el_items, dest_path, is_undo = false) {
|
||||
});
|
||||
|
||||
//sort each container
|
||||
atPath('.item-container', item_dest_path).each(function () {
|
||||
$(`.item-container[data-path="${html_encode(item_dest_path)}" i]`).each(function () {
|
||||
window.sort_items(this, $(this).attr('data-sort_by'), $(this).attr('data-sort_order'));
|
||||
});
|
||||
} catch ( err ) {
|
||||
@@ -2153,7 +2132,7 @@ window.move_items = async function (el_items, dest_path, is_undo = false) {
|
||||
item_with_same_name_already_exists = false;
|
||||
// error message after source item has reappeared
|
||||
$(el_item).show(0, function () {
|
||||
UIAlert(`<p>Moving <strong>${$(el_item).attr('data-name')}</strong></p>${err.message ?? ''}`);
|
||||
UIAlert(`<p>Moving <strong>${html_encode($(el_item).attr('data-name'))}</strong></p>${err.message ?? ''}`);
|
||||
});
|
||||
|
||||
break;
|
||||
@@ -2306,7 +2285,9 @@ window.updateSubdomainsForItems = async function (fsentries, container) {
|
||||
|
||||
// If not found by uid, try path-based search
|
||||
if ( $item.length === 0 && fsentry.path ) {
|
||||
$item = atPath('.item', fsentry.path);
|
||||
// Escape special characters in path for jQuery selector
|
||||
const escapedPath = fsentry.path.replace(/[!"#$%&'()*+,.\/:;<=>?@[\\\]^`{|}~]/g, '\\$&');
|
||||
$item = $(document).find(`.item[data-path="${escapedPath}"]`);
|
||||
}
|
||||
|
||||
if ( $item.length > 0 ) {
|
||||
@@ -2416,9 +2397,6 @@ window.upload_items = async function (items, dest_path) {
|
||||
let upload_progress_window;
|
||||
let opid;
|
||||
|
||||
// The Shared view is a query, not a directory — nothing can be uploaded into it.
|
||||
if ( dest_path === window.shared_path ) return;
|
||||
|
||||
if ( dest_path == window.trash_path ) {
|
||||
UIAlert('Uploading to trash is not allowed!');
|
||||
return;
|
||||
@@ -2898,15 +2876,13 @@ window.unzipItem = async function (itemPath) {
|
||||
terminateOp = fflate.unzip(file, async (err, unzipped) => {
|
||||
currentProgress += window.zippingProgressConfig.ZIPPING;
|
||||
progwin?.set_progress(currentProgress.toPrecision(2));
|
||||
const close_progwin = (hide_delay) => {
|
||||
if ( err ) {
|
||||
UIAlert(e.message);
|
||||
// close progress window
|
||||
clearTimeout(progwin_timeout);
|
||||
setTimeout(() => {
|
||||
progwin?.close();
|
||||
}, Math.max(0, hide_delay - (Date.now() - start_ts)));
|
||||
};
|
||||
if ( err ) {
|
||||
UIAlert(err.message);
|
||||
close_progwin(window.copy_progress_hide_delay);
|
||||
}, Math.max(0, window.copy_progress_hide_delay - (Date.now() - start_ts)));
|
||||
} else {
|
||||
const rootdir = await puter.fs.mkdir(`${path.dirname(filePath) }/${ path.basename(filePath, '.zip')}`, { dedupeName: true });
|
||||
let perItemProgress = window.zippingProgressConfig.WRITING / Object.keys(unzipped).length;
|
||||
@@ -2924,10 +2900,6 @@ window.unzipItem = async function (itemPath) {
|
||||
UIAlert(e.message);
|
||||
}
|
||||
});
|
||||
// an archive with no files leaves nothing to upload, so nothing else would end the operation
|
||||
if ( queuedFileWrites.length === 0 ) {
|
||||
close_progwin(window.unzip_progress_hide_delay);
|
||||
}
|
||||
queuedFileWrites.length && puter.fs.upload(
|
||||
// what to upload
|
||||
queuedFileWrites,
|
||||
@@ -2939,7 +2911,7 @@ window.unzipItem = async function (itemPath) {
|
||||
generateThumbnails: true,
|
||||
thumbnailGenerator: createUploadThumbnailGenerator(),
|
||||
progress: async function (operation_id, op_progress) {
|
||||
progwin?.set_progress(op_progress);
|
||||
progwin.set_progress(op_progress);
|
||||
// update title if window is not visible
|
||||
if ( document.visibilityState !== 'visible' ) {
|
||||
update_title_based_on_uploads();
|
||||
@@ -2947,10 +2919,11 @@ window.unzipItem = async function (itemPath) {
|
||||
},
|
||||
success: async function (items) {
|
||||
progwin?.set_progress(window.zippingProgressConfig.TOTAL.toPrecision(2));
|
||||
close_progwin(window.unzip_progress_hide_delay);
|
||||
},
|
||||
error: function () {
|
||||
close_progwin(window.unzip_progress_hide_delay);
|
||||
// close progress window
|
||||
clearTimeout(progwin_timeout);
|
||||
setTimeout(() => {
|
||||
progwin?.close();
|
||||
}, Math.max(0, window.unzip_progress_hide_delay - (Date.now() - start_ts)));
|
||||
},
|
||||
},
|
||||
);
|
||||
@@ -3182,13 +3155,6 @@ window.untarItem = async function (itemPath) {
|
||||
}
|
||||
}
|
||||
|
||||
// an archive with no files leaves nothing to upload, so nothing else would end the operation
|
||||
if ( queuedFileWrites.length === 0 ) {
|
||||
clearTimeout(progwin_timeout);
|
||||
setTimeout(() => {
|
||||
progwin?.close();
|
||||
}, Math.max(0, window.unzip_progress_hide_delay - (Date.now() - start_ts)));
|
||||
}
|
||||
queuedFileWrites.length && puter.fs.upload(
|
||||
queuedFileWrites,
|
||||
`${rootdir.path }/`,
|
||||
@@ -3197,7 +3163,7 @@ window.untarItem = async function (itemPath) {
|
||||
generateThumbnails: true,
|
||||
thumbnailGenerator: createUploadThumbnailGenerator(),
|
||||
progress: async function (operation_id, op_progress) {
|
||||
progwin?.set_progress(op_progress);
|
||||
progwin.set_progress(op_progress);
|
||||
if ( document.visibilityState !== 'visible' ) {
|
||||
update_title_based_on_uploads();
|
||||
}
|
||||
@@ -3335,7 +3301,20 @@ window.rename_file = async (options, new_name, old_name, old_path, el_item, el_i
|
||||
$(`.item[data-uid='${$(el_item).attr('data-uid')}']`).attr('data-path', new_path);
|
||||
$(`.window-${options.uid}`).attr('data-path', new_path);
|
||||
|
||||
retargetPaths(old_path, new_path, new_name);
|
||||
// Update all elements that have matching paths
|
||||
$(`[data-path="${html_encode(old_path)}" i]`).each(function () {
|
||||
$(this).attr('data-path', new_path);
|
||||
if ( $(this).hasClass('window-navbar-path-dirname') )
|
||||
{
|
||||
$(this).text(new_name);
|
||||
}
|
||||
});
|
||||
|
||||
// Update the paths of all elements whose paths start with `old_path`
|
||||
$(`[data-path^="${`${html_encode(old_path) }/`}"]`).each(function () {
|
||||
const new_el_path = $(this).attr('data-path').replace(`${old_path }/`, `${new_path}/`);
|
||||
$(this).attr('data-path', new_el_path);
|
||||
});
|
||||
|
||||
// Update the 'Sites Cache'
|
||||
if ( $(el_item).attr('data-has_website') === '1' )
|
||||
@@ -3416,9 +3395,7 @@ window.undo_last_action = async () => {
|
||||
delete: () => window.undo_delete(data),
|
||||
rename: () => {
|
||||
const { options, new_name, old_name, old_path, el_item, el_item_name, el_item_icon, el_item_name_editor, website_url, onDone } = data;
|
||||
// the item now sits at its renamed path, which is what this rename moves away from
|
||||
const renamed_path = path.join(path.dirname(old_path), new_name);
|
||||
window.rename_file(options, old_name, new_name, renamed_path, el_item, el_item_name, el_item_icon, el_item_name_editor, website_url, true, onDone);
|
||||
window.rename_file(options, old_name, new_name, old_path, el_item, el_item_name, el_item_icon, el_item_name_editor, website_url, true, onDone);
|
||||
},
|
||||
};
|
||||
|
||||
|
||||
@@ -1,170 +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';
|
||||
|
||||
vi.mock('./UI/UIAlert.js', () => ({ default: vi.fn() }));
|
||||
vi.mock('./UI/UIItem.js', () => ({ default: vi.fn() }));
|
||||
vi.mock('./UI/Auth/UIAuthLogin.js', () => ({ default: vi.fn() }));
|
||||
vi.mock('./UI/UIWindowProgress.js', () => ({ default: vi.fn() }));
|
||||
vi.mock('./UI/UIWindowSaveAccount.js', () => ({ default: vi.fn() }));
|
||||
|
||||
globalThis.$ = jQuery;
|
||||
globalThis.jQuery = jQuery;
|
||||
globalThis.i18n = key => key;
|
||||
globalThis.def = globalThis.def ?? (value => value);
|
||||
globalThis.use = globalThis.use ?? (() => class {});
|
||||
globalThis.html_encode = value => jQuery('<div>').text(value).html();
|
||||
|
||||
await import('./helpers.js');
|
||||
const { default: apply_item_added_to_containers } = await import('./helpers/applyItemAddedToContainers.js');
|
||||
const { default: UIItem } = await import('./UI/UIItem.js');
|
||||
const { atPath, retargetNavHistory, retargetPaths, underPath } = await import('./helpers/pathElements.js');
|
||||
|
||||
// A plain name, then names holding characters a selector or HTML treats specially.
|
||||
const NAMES = ['Reports 2024', 'R&D', "Dan's files", 'the "big" one', 'a<b>c', 'back\\slash'];
|
||||
|
||||
const el = (className, attrs) => jQuery('<div>').addClass(className).attr(attrs).appendTo(document.body);
|
||||
|
||||
beforeEach(() => {
|
||||
document.body.innerHTML = '';
|
||||
jQuery.fx.off = true;
|
||||
jQuery.fn.close = vi.fn();
|
||||
jQuery.fn.removeItems = vi.fn();
|
||||
window.icons = { 'folder.svg': 'folder.svg' };
|
||||
window.actions_history = [];
|
||||
window.user = { username: 'alice' };
|
||||
window.update_window_path = vi.fn();
|
||||
window.sort_items = vi.fn();
|
||||
window.update_explorer_footer_item_count = vi.fn();
|
||||
window.update_explorer_footer_selected_items_count = vi.fn();
|
||||
window.determine_website_url = () => '';
|
||||
UIItem.mockClear();
|
||||
});
|
||||
|
||||
describe.each(NAMES)('a folder named %s', (name) => {
|
||||
const folderPath = `/alice/${name}`;
|
||||
|
||||
it('keeps its open subfolders and their items on the new path when renamed', async () => {
|
||||
const $item = el('item', { 'data-uid': 'u1', 'data-path': folderPath, 'data-name': name });
|
||||
const $crumb = el('window-navbar-path-dirname', { 'data-path': folderPath });
|
||||
const $subWindow = el('window', { 'data-path': `${folderPath}/sub` });
|
||||
const $subItem = el('item', { 'data-uid': 'u2', 'data-path': `${folderPath}/sub/a.txt` });
|
||||
globalThis.puter = { fs: { rename: ({ success }) => success({ uid: 'u1', name: 'Plain', is_dir: true }) } };
|
||||
|
||||
await new Promise(resolve => {
|
||||
window.rename_file({ uid: 'u1', name, path: folderPath, is_dir: true }, 'Plain', name, folderPath,
|
||||
$item[0], null, null, null, '', false, resolve);
|
||||
});
|
||||
|
||||
expect($item.attr('data-path')).toBe('/alice/Plain');
|
||||
expect($crumb.attr('data-path')).toBe('/alice/Plain');
|
||||
expect($crumb.text()).toBe('Plain');
|
||||
expect($subWindow.attr('data-path')).toBe('/alice/Plain/sub');
|
||||
expect($subItem.attr('data-path')).toBe('/alice/Plain/sub/a.txt');
|
||||
});
|
||||
|
||||
it('closes the windows of its subfolders when deleted', async () => {
|
||||
const $item = el('item', { 'data-uid': 'u1', 'data-path': folderPath });
|
||||
el('window', { 'data-path': `${folderPath}/sub` });
|
||||
el('window', { 'data-path': '/alice/Other/sub' });
|
||||
el('item', { 'data-uid': 'u3', 'data-shortcut_to_path': folderPath });
|
||||
globalThis.puter = { fs: { delete: vi.fn().mockResolvedValue() } };
|
||||
|
||||
await window.delete_item($item[0]);
|
||||
|
||||
const closed = jQuery.fn.close.mock.contexts.flatMap($set => $set.toArray().map(w => jQuery(w).attr('data-path')));
|
||||
expect(closed).toEqual([`${folderPath}/sub`]);
|
||||
expect(puter.fs.delete).toHaveBeenCalled();
|
||||
expect(jQuery('[data-uid="u3"]').attr('data-shortcut_to_path')).toBe('');
|
||||
});
|
||||
|
||||
it('shows an item another tab added to it', async () => {
|
||||
const $container = el('item-container', { 'data-path': folderPath });
|
||||
|
||||
await apply_item_added_to_containers({ uid: 'u9', dirpath: folderPath, path: `${folderPath}/new.txt`, name: 'new.txt', is_dir: true });
|
||||
|
||||
expect(UIItem).toHaveBeenCalledTimes(1);
|
||||
expect(UIItem.mock.calls[0][0].appendTo.toArray()).toEqual([$container[0]]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('retargetPaths', () => {
|
||||
it('ignores the case of the renamed path itself, and leaves its siblings alone', () => {
|
||||
const $window = el('window', { 'data-path': '/alice/docs' });
|
||||
const $sibling = el('item', { 'data-path': '/alice/Docs 2/a.txt' });
|
||||
|
||||
retargetPaths('/alice/Docs', '/alice/Papers', 'Papers');
|
||||
|
||||
expect($window.attr('data-path')).toBe('/alice/Papers');
|
||||
expect($sibling.attr('data-path')).toBe('/alice/Docs 2/a.txt');
|
||||
});
|
||||
|
||||
it('writes a new name holding a replacement pattern as it is', () => {
|
||||
const $item = el('item', { 'data-path': '/alice/Docs/a.txt' });
|
||||
|
||||
retargetPaths('/alice/Docs', '/alice/$& and $1', '$& and $1');
|
||||
|
||||
expect($item.attr('data-path')).toBe('/alice/$& and $1/a.txt');
|
||||
});
|
||||
|
||||
it('changes nothing when the old path is unknown', () => {
|
||||
const $item = el('item', { 'data-path': '/alice/Docs/a.txt' });
|
||||
|
||||
retargetPaths(undefined, '/alice/Papers', 'Papers');
|
||||
|
||||
expect($item.attr('data-path')).toBe('/alice/Docs/a.txt');
|
||||
});
|
||||
});
|
||||
|
||||
describe.each([undefined, null, ''])('a lookup for the path %s', (missing) => {
|
||||
it('matches nothing, including elements that have no path', () => {
|
||||
el('item', { 'data-path': '/alice/a.txt', 'data-shortcut_to_path': '' });
|
||||
el('window', { 'data-path': '' });
|
||||
el('window', { 'data-path': '/alice/Docs' });
|
||||
|
||||
expect(atPath('.item', missing, 'data-shortcut_to_path')).toHaveLength(0);
|
||||
expect(atPath('.window', missing)).toHaveLength(0);
|
||||
expect(underPath('.window', missing)).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('retargetNavHistory', () => {
|
||||
it('rewrites entries at or inside the old path and leaves the rest', () => {
|
||||
window.window_nav_history = {
|
||||
1: ['/alice', '/alice/A', '/alice/A/sub', '/alice/AB', 'puter://shared'],
|
||||
2: ['/alice/Documents'],
|
||||
};
|
||||
|
||||
retargetNavHistory('/alice/A', '/alice/B');
|
||||
|
||||
expect(window.window_nav_history[1]).toEqual(['/alice', '/alice/B', '/alice/B/sub', '/alice/AB', 'puter://shared']);
|
||||
expect(window.window_nav_history[2]).toEqual(['/alice/Documents']);
|
||||
});
|
||||
|
||||
it('is applied by retargetPaths', () => {
|
||||
window.window_nav_history = { 1: ['/alice/A/sub'] };
|
||||
|
||||
retargetPaths('/alice/A', '/alice/B', 'B');
|
||||
|
||||
expect(window.window_nav_history[1]).toEqual(['/alice/B/sub']);
|
||||
});
|
||||
});
|
||||
@@ -19,7 +19,6 @@
|
||||
|
||||
import UIItem from '../UI/UIItem.js';
|
||||
import item_icon from './itemIcon.js';
|
||||
import { atPath } from './pathElements.js';
|
||||
import { select_added_item_if_pending } from './uploadSelection.js';
|
||||
|
||||
/**
|
||||
@@ -38,7 +37,7 @@ import { select_added_item_if_pending } from './uploadSelection.js';
|
||||
* @param {object} item fsentry from the `item.added` event
|
||||
*/
|
||||
const apply_item_added_to_containers = async function (item) {
|
||||
const $containers = atPath('.item-container', item.dirpath);
|
||||
const $containers = $(`.item-container[data-path='${html_encode(item.dirpath)}' i]`);
|
||||
if ( $containers.length === 0 ) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -17,8 +17,6 @@
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
import path from '../lib/path.js';
|
||||
|
||||
/**
|
||||
* Expands a user-facing path into the absolute path the filesystem API takes:
|
||||
* `~` and `~/x` resolve under the user's home, a bare relative path is read as
|
||||
@@ -41,20 +39,3 @@ export const expand_home_path = (fspath, home_path) => {
|
||||
if ( fspath.startsWith('/') ) return fspath;
|
||||
return `${home}/${fspath}`;
|
||||
};
|
||||
|
||||
/**
|
||||
* Turns what a user typed into an address bar into the canonical absolute
|
||||
* path: trimmed, home-expanded, with `.`/`..`, doubled and trailing slashes
|
||||
* resolved. An empty entry keeps the current path.
|
||||
*
|
||||
* @param {string} typed_path - the raw text the user entered
|
||||
* @param {{ current_path: string, home_path: string, shared_path: string }} context
|
||||
* @returns {string} the path to navigate to
|
||||
*/
|
||||
export const resolve_typed_path = (typed_path, { current_path, home_path, shared_path }) => {
|
||||
const trimmed = typeof typed_path === 'string' ? typed_path.trim() : '';
|
||||
if ( trimmed === '' ) return current_path;
|
||||
// The Shared view is a pseudo-path, not a filesystem one.
|
||||
if ( trimmed === shared_path ) return shared_path;
|
||||
return path.resolve('/', expand_home_path(trimmed, home_path));
|
||||
};
|
||||
@@ -18,7 +18,7 @@
|
||||
*/
|
||||
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { expand_home_path, resolve_typed_path } from './expandHomePath.js';
|
||||
import { expand_home_path } from './expandHomePath.js';
|
||||
|
||||
describe('expand_home_path', () => {
|
||||
it('resolves a tilde path under the home path', () => {
|
||||
@@ -57,28 +57,3 @@ describe('expand_home_path', () => {
|
||||
expect(expand_home_path(null, '/alice')).toBe(null);
|
||||
});
|
||||
});
|
||||
|
||||
describe('resolve_typed_path', () => {
|
||||
const context = { current_path: '/alice/Videos', home_path: '/alice', shared_path: 'puter://shared' };
|
||||
|
||||
it('canonicalizes trailing, doubled and dot segments', () => {
|
||||
expect(resolve_typed_path('/alice/Documents/', context)).toBe('/alice/Documents');
|
||||
expect(resolve_typed_path('/alice//Documents', context)).toBe('/alice/Documents');
|
||||
expect(resolve_typed_path('/alice/Documents/../Pictures', context)).toBe('/alice/Pictures');
|
||||
expect(resolve_typed_path('/', context)).toBe('/');
|
||||
});
|
||||
|
||||
it('trims whitespace and expands home-relative entries', () => {
|
||||
expect(resolve_typed_path(' ~/Documents ', context)).toBe('/alice/Documents');
|
||||
expect(resolve_typed_path('Documents', context)).toBe('/alice/Documents');
|
||||
});
|
||||
|
||||
it('keeps the current path for an empty entry', () => {
|
||||
expect(resolve_typed_path('', context)).toBe('/alice/Videos');
|
||||
expect(resolve_typed_path(' ', context)).toBe('/alice/Videos');
|
||||
});
|
||||
|
||||
it('passes the Shared view through untouched', () => {
|
||||
expect(resolve_typed_path('puter://shared', context)).toBe('puter://shared');
|
||||
});
|
||||
});
|
||||
@@ -50,7 +50,7 @@ import { is_default_app } from './defaultApp.js';
|
||||
* @param {Function} options.onPublishWebsite - Optional custom publish-as-website handler (used by Dashboard); receives {uid, name, path}
|
||||
* @param {Function} options.onPublishWorker - Optional custom publish-as-worker handler (used by Dashboard); receives {uid, name, path}
|
||||
* @param {Function} options.onPasteInto - Optional custom paste handler (used by Dashboard); receives the folder's path
|
||||
* @param {Function} options.onRemovedFromShared - Optional, called once Remove from Shared has dropped the user's own access (used by Dashboard)
|
||||
* @param {Function} options.onRemovedFromShared - Optional, called once Remove from Shared has taken the item's row away (used by Dashboard)
|
||||
* @returns {Promise<Array>} Array of context menu items
|
||||
*/
|
||||
const generate_file_context_menu = async function (options) {
|
||||
@@ -389,9 +389,7 @@ const generate_file_context_menu = async function (options) {
|
||||
// Or mode lookups keep answering for a share we just
|
||||
// walked away from.
|
||||
invalidate_shared_roots();
|
||||
// A team that still shares it keeps it listed, as the
|
||||
// team's share; the refreshed listing shows it that way.
|
||||
if ( fsentry.also_team_share !== true ) $(el_item).remove();
|
||||
$(el_item).remove();
|
||||
options.onRemovedFromShared?.();
|
||||
} catch (e) {
|
||||
UIAlert({ message: e?.message ?? i18n('error_unknown_cause') });
|
||||
|
||||
@@ -89,38 +89,6 @@ it('does not offer it on a share held through a team', async () => {
|
||||
);
|
||||
});
|
||||
|
||||
describe('Remove from Shared', () => {
|
||||
const remove = async (fsentry) => {
|
||||
const row = sharedRow();
|
||||
document.body.append(row);
|
||||
const onRemovedFromShared = vi.fn();
|
||||
window.user = { username: 'me' };
|
||||
globalThis.puter = { fs: { unshare: vi.fn(async () => ({ revoked: 1 })) } };
|
||||
const items = await generate_file_context_menu({
|
||||
element: row,
|
||||
fsentry: { name: 'notes.txt', path: '/ann/uid-1/notes.txt', ...fsentry },
|
||||
associated_app_name: 'editor',
|
||||
onRemovedFromShared,
|
||||
});
|
||||
await items.find((item) => item.html === 'share_remove_from_shared').onClick();
|
||||
expect(puter.fs.unshare).toHaveBeenCalledWith('/ann/uid-1/notes.txt', 'me');
|
||||
expect(onRemovedFromShared).toHaveBeenCalledTimes(1);
|
||||
return row;
|
||||
};
|
||||
|
||||
afterEach(() => {
|
||||
document.body.innerHTML = '';
|
||||
});
|
||||
|
||||
it('takes the row away once the user has left it', async () => {
|
||||
expect((await remove({})).isConnected).toBe(false);
|
||||
});
|
||||
|
||||
it('keeps the row for the listing to update when a team still shares it', async () => {
|
||||
expect((await remove({ also_team_share: true })).isConnected).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Open With', () => {
|
||||
const editor = { name: 'editor', title: 'Editor', uuid: 'app-editor' };
|
||||
const viewer = { name: 'viewer', title: 'Viewer', uuid: 'app-viewer' };
|
||||
|
||||
@@ -18,7 +18,6 @@
|
||||
*/
|
||||
|
||||
import { isAttestedOrigin } from './attestedOrigin.js';
|
||||
import { jwtPayload } from './jwtPayload.js';
|
||||
|
||||
/**
|
||||
* Godmode apps that run on their own full-access token instead of the
|
||||
@@ -74,7 +73,14 @@ export const shouldRenew = (expiresAt, nowMs) =>
|
||||
!Number.isFinite(expiresAt) || expiresAt * 1000 - nowMs < RENEW_WHEN_LEFT_MS;
|
||||
|
||||
/** The token row a JWT belongs to; renewals of a live row keep it. */
|
||||
const tokenRowOf = (token) => jwtPayload(token)?.token_uid ?? null;
|
||||
const tokenRowOf = (token) => {
|
||||
try {
|
||||
const part = token.split('.')[1].replace(/-/g, '+').replace(/_/g, '/');
|
||||
return JSON.parse(atob(part))?.token_uid ?? null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Whether two tokens are the same row, so the app already holds a working one.
|
||||
|
||||
@@ -100,7 +100,7 @@ const item_icon = async (fsentry) => {
|
||||
// --------------------------------------------------
|
||||
// .app files
|
||||
// --------------------------------------------------
|
||||
else if ( !fsentry.is_dir && fsentry.name && fsentry.name.toLowerCase().endsWith('.app') ) {
|
||||
else if ( fsentry.name && fsentry.name.toLowerCase().endsWith('.app') ) {
|
||||
try {
|
||||
const content = await puter.fs.read({ path: fsentry.path });
|
||||
const text = typeof content === 'string' ? content : await content.text();
|
||||
|
||||
@@ -1,35 +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 claims of a JWT, read without checking its signature, so they say what
|
||||
* the token claims and prove nothing.
|
||||
*
|
||||
* @param {string} token
|
||||
* @returns {Record<string, unknown> | null} null when the token isn't a readable JWT
|
||||
*/
|
||||
export const jwtPayload = (token) => {
|
||||
try {
|
||||
const part = token.split('.')[1].replace(/-/g, '+').replace(/_/g, '/');
|
||||
const payload = JSON.parse(atob(part));
|
||||
return payload && typeof payload === 'object' ? payload : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
@@ -17,50 +17,13 @@
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
import { strongerMode } from './shareModes.js';
|
||||
|
||||
// Largest page the backend will serve (ShareStore.MAX_HOLDER_PAGE_SIZE).
|
||||
const PAGE_SIZE = 200;
|
||||
|
||||
/**
|
||||
* One row per shared item. The API lists a row per grant and grants add up, so
|
||||
* an item granted twice keeps its strongest row. It stays a team share only
|
||||
* when no grant names the user directly, since a direct grant is theirs to leave.
|
||||
* A merged row lists everyone who granted it in `issuers`, strongest grant first,
|
||||
* and sets `alsoHeldByTeam` when leaving the direct grant leaves a team's in place.
|
||||
*
|
||||
* @param {Array<Object>} shares
|
||||
* @returns {Array<Object>}
|
||||
*/
|
||||
const issuersOf = (share) => share.issuers ?? [share.issuer];
|
||||
const heldByTeam = (share) => Boolean(share.holderTeam) || share.alsoHeldByTeam === true;
|
||||
|
||||
export const mergeGrants = (shares) => {
|
||||
const merged = new Map();
|
||||
for ( const share of shares ) {
|
||||
const key = share.entryUid ?? share.path;
|
||||
const held = merged.get(key);
|
||||
if ( ! held ) {
|
||||
merged.set(key, share);
|
||||
continue;
|
||||
}
|
||||
const [best, other] = strongerMode(held.mode, share.mode) === held.mode ? [held, share] : [share, held];
|
||||
const teamOnly = held.holderTeam && share.holderTeam;
|
||||
const issuers = [...issuersOf(best), ...issuersOf(other)].filter(Boolean);
|
||||
merged.set(key, {
|
||||
...best,
|
||||
holderTeam: teamOnly ? best.holderTeam : undefined,
|
||||
alsoHeldByTeam: ! teamOnly && (heldByTeam(held) || heldByTeam(share)),
|
||||
issuers: [...new Set(issuers)],
|
||||
});
|
||||
}
|
||||
return [...merged.values()];
|
||||
};
|
||||
|
||||
/**
|
||||
* Every item shared with the current user, across all pages. A page can be
|
||||
* short once unreachable items are filtered out, so it pages on `cursor`
|
||||
* rather than on the item count.
|
||||
* Every share the current user holds, across all pages. A page can be short
|
||||
* once unreachable items are filtered out, so it pages on `cursor` rather than
|
||||
* on the item count.
|
||||
*
|
||||
* @returns {Promise<Array<Object>>}
|
||||
*/
|
||||
@@ -77,7 +40,7 @@ const list_all_shared = async () => {
|
||||
cursor = page.cursor;
|
||||
} while ( cursor );
|
||||
|
||||
return mergeGrants(shares);
|
||||
return shares;
|
||||
};
|
||||
|
||||
export default list_all_shared;
|
||||
@@ -1,127 +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 { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import list_all_shared, { mergeGrants } from './listAllShared.js';
|
||||
|
||||
const BUDGET = '33333333-3333-3333-3333-333333333333';
|
||||
const REPORT = '44444444-4444-4444-4444-444444444444';
|
||||
const TEAM = { uid: 'team-1', name: 'Finance', handle: 'finance' };
|
||||
|
||||
const grant = (entryUid, name, extra) => ({
|
||||
entryUid,
|
||||
path: `/jf/${entryUid}/${name}`,
|
||||
name,
|
||||
...extra,
|
||||
});
|
||||
|
||||
describe('mergeGrants', () => {
|
||||
it('lists an item once, with its strongest grant', () => {
|
||||
const merged = mergeGrants([
|
||||
grant(BUDGET, 'Budget', { mode: 'manage', issuer: 'jf' }),
|
||||
grant(REPORT, 'report.pdf', { mode: 'read', issuer: 'jf' }),
|
||||
grant(BUDGET, 'Budget', { mode: 'read', issuer: 'delegate' }),
|
||||
grant(REPORT, 'report.pdf', { mode: 'write', issuer: 'delegate' }),
|
||||
]);
|
||||
expect(merged.map((share) => [share.entryUid, share.mode, share.issuer])).toEqual([
|
||||
[BUDGET, 'manage', 'jf'],
|
||||
[REPORT, 'write', 'delegate'],
|
||||
]);
|
||||
});
|
||||
|
||||
it('names everyone who granted the item, strongest grant first', () => {
|
||||
const [share] = mergeGrants([
|
||||
grant(BUDGET, 'Budget', { mode: 'read', issuer: 'jf' }),
|
||||
grant(BUDGET, 'Budget', { mode: 'write', issuer: 'delegate' }),
|
||||
grant(BUDGET, 'Budget', { mode: 'read', issuer: 'jf', holderTeam: TEAM }),
|
||||
]);
|
||||
expect(share.issuer).toBe('delegate');
|
||||
expect(share.issuers).toEqual(['delegate', 'jf']);
|
||||
});
|
||||
|
||||
it('keeps the first of two equal grants', () => {
|
||||
const [share] = mergeGrants([
|
||||
grant(BUDGET, 'Budget', { mode: 'read', issuer: 'jf' }),
|
||||
grant(BUDGET, 'Budget', { mode: 'read', issuer: 'delegate' }),
|
||||
]);
|
||||
expect(share.issuer).toBe('jf');
|
||||
});
|
||||
|
||||
it('is not a team share when one grant names the user directly', () => {
|
||||
const [share] = mergeGrants([
|
||||
grant(BUDGET, 'Budget', { mode: 'read', issuer: 'jf' }),
|
||||
grant(BUDGET, 'Budget', { mode: 'write', issuer: 'jf', holderTeam: TEAM }),
|
||||
]);
|
||||
expect(share.mode).toBe('write');
|
||||
expect(share.holderTeam).toBeUndefined();
|
||||
expect(share.alsoHeldByTeam).toBe(true);
|
||||
});
|
||||
|
||||
it('marks only an item held both ways as also held by a team', () => {
|
||||
const [direct, team] = mergeGrants([
|
||||
grant(BUDGET, 'Budget', { mode: 'read', issuer: 'jf' }),
|
||||
grant(BUDGET, 'Budget', { mode: 'write', issuer: 'delegate' }),
|
||||
grant(REPORT, 'report.pdf', { mode: 'read', holderTeam: TEAM }),
|
||||
grant(REPORT, 'report.pdf', { mode: 'write', holderTeam: TEAM }),
|
||||
]);
|
||||
expect(direct.alsoHeldByTeam).toBe(false);
|
||||
expect(team.alsoHeldByTeam).toBe(false);
|
||||
});
|
||||
|
||||
it('still marks it when a later grant is direct again', () => {
|
||||
const [share] = mergeGrants([
|
||||
grant(BUDGET, 'Budget', { mode: 'read', holderTeam: TEAM }),
|
||||
grant(BUDGET, 'Budget', { mode: 'read', issuer: 'jf' }),
|
||||
grant(BUDGET, 'Budget', { mode: 'write', issuer: 'delegate' }),
|
||||
]);
|
||||
expect(share.holderTeam).toBeUndefined();
|
||||
expect(share.alsoHeldByTeam).toBe(true);
|
||||
});
|
||||
|
||||
it('stays a team share when every grant is to a team', () => {
|
||||
const [share] = mergeGrants([
|
||||
grant(BUDGET, 'Budget', { mode: 'read', holderTeam: { ...TEAM, uid: 'team-2' } }),
|
||||
grant(BUDGET, 'Budget', { mode: 'write', holderTeam: TEAM }),
|
||||
]);
|
||||
expect(share.holderTeam).toEqual(TEAM);
|
||||
});
|
||||
});
|
||||
|
||||
describe('list_all_shared', () => {
|
||||
beforeEach(() => {
|
||||
globalThis.window = { puter: { fs: { listShared: vi.fn() } } };
|
||||
});
|
||||
|
||||
it('merges grants for one item that arrive on different pages', async () => {
|
||||
window.puter.fs.listShared
|
||||
.mockResolvedValueOnce({
|
||||
items: [grant(BUDGET, 'Budget', { mode: 'manage' })],
|
||||
cursor: 'next',
|
||||
})
|
||||
.mockResolvedValueOnce({
|
||||
items: [grant(BUDGET, 'Budget', { mode: 'read' })],
|
||||
});
|
||||
|
||||
const shares = await list_all_shared();
|
||||
|
||||
expect(shares).toHaveLength(1);
|
||||
expect(shares[0].mode).toBe('manage');
|
||||
expect(window.puter.fs.listShared).toHaveBeenLastCalledWith({ limit: 200, cursor: 'next' });
|
||||
});
|
||||
});
|
||||
@@ -145,14 +145,9 @@ const new_context_menu_item = function (dirname, append_to_element) {
|
||||
canvas.width = 800;
|
||||
canvas.height = 600;
|
||||
|
||||
// JPEG has no transparency, so the blank image needs a background
|
||||
const ctx = canvas.getContext('2d');
|
||||
ctx.fillStyle = '#ffffff';
|
||||
ctx.fillRect(0, 0, canvas.width, canvas.height);
|
||||
|
||||
canvas.toBlob((blob) => {
|
||||
window.create_file({ dirname: dirname, append_to_element: append_to_element, name: 'New Image.jpg', content: blob });
|
||||
}, 'image/jpeg');
|
||||
});
|
||||
},
|
||||
},
|
||||
// Worker
|
||||
|
||||
@@ -19,9 +19,8 @@
|
||||
|
||||
import UIWindow from '../UI/UIWindow.js';
|
||||
import UIAlert from '../UI/UIAlert.js';
|
||||
import i18n from '../i18n/i18n.js';
|
||||
import launch_app from './launchApp.js';
|
||||
// installs the global i18n()
|
||||
import '../i18n/i18n.js';
|
||||
import path from '../lib/path.js';
|
||||
import item_icon from './itemIcon.js';
|
||||
import { resolve_default_app } from './defaultApp.js';
|
||||
|
||||
@@ -23,6 +23,7 @@ import jQuery from '../lib/jquery-3.6.1/jquery-3.6.1.min.js';
|
||||
|
||||
vi.mock('../UI/UIWindow.js', () => ({ default: vi.fn() }));
|
||||
vi.mock('../UI/UIAlert.js', () => ({ default: vi.fn(async () => undefined) }));
|
||||
vi.mock('../i18n/i18n.js', () => ({ default: key => key }));
|
||||
vi.mock('./launchApp.js', () => ({ default: vi.fn(async () => ({ launchResult: { launched: true } })) }));
|
||||
vi.mock('./itemIcon.js', () => ({ default: vi.fn() }));
|
||||
vi.mock('./defaultApp.js', () => ({ resolve_default_app: vi.fn(async () => null) }));
|
||||
@@ -112,18 +113,3 @@ describe('open_item with a new tab', () => {
|
||||
expect(tab.close).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('open_item with no app for the file', () => {
|
||||
it('offers to download it', async () => {
|
||||
window.is_dashboard_mode = false;
|
||||
window.trigger_download = vi.fn();
|
||||
UIAlert.mockResolvedValueOnce('download_file');
|
||||
|
||||
await open_item({ item: row({ name: 'data.bin', path: '/user/data.bin' }) });
|
||||
|
||||
expect(UIAlert).toHaveBeenCalledTimes(1);
|
||||
expect(UIAlert.mock.calls[0][1].map(button => button.value ?? button.label)).toEqual(['download_file', 'Cancel']);
|
||||
expect(window.trigger_download).toHaveBeenCalledWith(['/user/data.bin']);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,92 +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/>.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Narrows `elements` to those whose `attr` is `path`, ignoring case. Reads the
|
||||
* attribute, because a path can hold any character a selector can't.
|
||||
*
|
||||
* @param {string | Element | JQuery} elements - a selector or a set of elements
|
||||
* @param {string} path
|
||||
* @param {string} [attr]
|
||||
* @returns {JQuery}
|
||||
*/
|
||||
export const atPath = (elements, path, attr = 'data-path') => {
|
||||
// Without this, a missing path matches every element whose attribute is empty.
|
||||
if ( ! path ) return $();
|
||||
const wanted = String(path).toLowerCase();
|
||||
return $(elements).filter(function () {
|
||||
const value = this.getAttribute(attr);
|
||||
return value !== null && value.toLowerCase() === wanted;
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Narrows `elements` to those whose `data-path` is inside the folder at `path`.
|
||||
*
|
||||
* @param {string | Element | JQuery} elements - a selector or a set of elements
|
||||
* @param {string} path
|
||||
* @returns {JQuery}
|
||||
*/
|
||||
export const underPath = (elements, path) => {
|
||||
if ( ! path ) return $();
|
||||
const prefix = `${path}/`;
|
||||
return $(elements).filter(function () {
|
||||
return this.getAttribute('data-path')?.startsWith(prefix) === true;
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Points every element at `oldPath`, or inside it, to `newPath`.
|
||||
*
|
||||
* @param {string} oldPath
|
||||
* @param {string} newPath
|
||||
* @param {string} newName - shown by the breadcrumbs that pointed at `oldPath`
|
||||
*/
|
||||
export const retargetPaths = (oldPath, newPath, newName) => {
|
||||
if ( ! oldPath ) return;
|
||||
const $inside = underPath('[data-path]', oldPath);
|
||||
atPath('[data-path]', oldPath).each(function () {
|
||||
$(this).attr('data-path', newPath);
|
||||
if ( $(this).hasClass('window-navbar-path-dirname') ) {
|
||||
$(this).text(newName);
|
||||
}
|
||||
});
|
||||
$inside.each(function () {
|
||||
$(this).attr('data-path', newPath + $(this).attr('data-path').slice(oldPath.length));
|
||||
});
|
||||
retargetNavHistory(oldPath, newPath);
|
||||
};
|
||||
|
||||
/**
|
||||
* Points every window's Back/Forward entries at `oldPath`, or inside it, to
|
||||
* `newPath`, so they still lead somewhere after a rename or move.
|
||||
*
|
||||
* @param {string} oldPath
|
||||
* @param {string} newPath
|
||||
*/
|
||||
export const retargetNavHistory = (oldPath, newPath) => {
|
||||
if ( ! oldPath ) return;
|
||||
const prefix = `${oldPath}/`;
|
||||
for ( const history of Object.values(window.window_nav_history ?? {}) ) {
|
||||
history.forEach((entry, index) => {
|
||||
if ( entry === oldPath ) history[index] = newPath;
|
||||
else if ( entry.startsWith(prefix) ) history[index] = newPath + entry.slice(oldPath.length);
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -30,7 +30,6 @@ export const FRAMED_POPUP_ACTIONS = new Set([
|
||||
'show-save-file-picker',
|
||||
'show-directory-picker',
|
||||
'upgrade',
|
||||
'top-up',
|
||||
'request-email-confirmation',
|
||||
]);
|
||||
|
||||
@@ -40,18 +39,17 @@ const HOST_USER_ACTIONS = new Set([
|
||||
'show-save-file-picker',
|
||||
'show-directory-picker',
|
||||
'upgrade',
|
||||
'top-up',
|
||||
'request-email-confirmation',
|
||||
]);
|
||||
|
||||
// Actions framed over the whole page with no box, which their own dialog's
|
||||
// scrim covers.
|
||||
const TRANSPARENT_ACTIONS = new Set(['upgrade', 'top-up', 'request-email-confirmation']);
|
||||
const TRANSPARENT_ACTIONS = new Set(['upgrade', 'request-email-confirmation']);
|
||||
|
||||
const UPGRADE_REASONS = new Set(['funds', 'subscription', 'storage']);
|
||||
const UPGRADE_METHOD_MAX = 200;
|
||||
|
||||
// Modal UI the upgrade and top-up dialogs and the GUI's windows show. Once some has shown
|
||||
// Modal UI the upgrade dialog and the GUI's windows show. Once some has shown
|
||||
// and all of it has been gone this long, the dialog closed without reporting
|
||||
// it, and the frame mustn't be left covering the page.
|
||||
const UPGRADE_MODAL_UI = '.window, [aria-modal="true"]';
|
||||
@@ -253,23 +251,6 @@ export const canShowUpgradeFrame = (win, session) =>
|
||||
!session.requires_card_verification &&
|
||||
!session.requires_password_change;
|
||||
|
||||
/**
|
||||
* Whether a framed top-up can show for the GUI session `session` (its
|
||||
* `/whoami`): the deployment has a top-up dialog that reports when it closes,
|
||||
* and no account check is waiting, which a frame couldn't be closed from.
|
||||
*
|
||||
* @param {Window} win
|
||||
* @param {Record<string, unknown> | null} session
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export const canShowTopUpFrame = (win, session) =>
|
||||
win.UITopUp?.embeddable === true &&
|
||||
!!session &&
|
||||
!session.requires_email_confirmation &&
|
||||
!session.requires_phone_verification &&
|
||||
!session.requires_card_verification &&
|
||||
!session.requires_password_change;
|
||||
|
||||
/**
|
||||
* Whether a framed email confirmation can show for the GUI session `session`
|
||||
* (its `/whoami`): no check other than the email is waiting, since those show
|
||||
@@ -319,18 +300,19 @@ export const framedUpgradeDetails = (hash) => {
|
||||
};
|
||||
|
||||
/**
|
||||
* Shows one of the deployment's dialogs in a framed popup and tells the
|
||||
* Shows the deployment's upgrade dialog in a framed popup and tells the
|
||||
* framing page it's ready once it's open, or before it opens when the page
|
||||
* still hides the frame. Resolves what the dialog reports when it closes, or
|
||||
* false once every dialog and window it showed has gone without it reporting
|
||||
* a close.
|
||||
* still hides the frame. Resolves whether the user upgraded,
|
||||
* once the dialog closes, or false once every dialog and window it showed has
|
||||
* gone without it reporting a close.
|
||||
*
|
||||
* @param {Window} win
|
||||
* @param {(closed: (result: boolean) => void) => unknown} open - opens the dialog, which calls `closed` when it closes
|
||||
* @param {{ appUid?: string, reason?: string, method?: string }} attribution - what prompted it;
|
||||
* an empty one is passed as null, so the dialog credits the prompt it remembers
|
||||
* @param {(state: 'ready') => void} tell
|
||||
* @returns {Promise<boolean>}
|
||||
*/
|
||||
const showFramedDialog = (win, open, tell) => new Promise((resolve, reject) => {
|
||||
export const showFramedUpgrade = (win, attribution, tell) => new Promise((resolve, reject) => {
|
||||
let settled = false;
|
||||
let seen = false;
|
||||
let goneTimer = null;
|
||||
@@ -363,47 +345,21 @@ const showFramedDialog = (win, open, tell) => new Promise((resolve, reject) => {
|
||||
toldReady = true;
|
||||
tell('ready');
|
||||
};
|
||||
const open = () => {
|
||||
const dialog = new win.UIUpgradeAccount({
|
||||
attribution: Object.keys(attribution).length ? attribution : null,
|
||||
onClose: (result) => settle(() => resolve(result?.upgraded === true)),
|
||||
});
|
||||
return dialog.open_as_window();
|
||||
};
|
||||
whenFrameSized(win, ready)
|
||||
.then(() => open((result) => settle(() => resolve(result))))
|
||||
.then(open)
|
||||
.then(() => {
|
||||
check();
|
||||
ready();
|
||||
}, (e) => settle(() => reject(e)));
|
||||
});
|
||||
|
||||
/**
|
||||
* Shows the deployment's upgrade dialog in a framed popup. Resolves whether
|
||||
* the user upgraded, once the dialog closes.
|
||||
*
|
||||
* @param {Window} win
|
||||
* @param {{ appUid?: string, reason?: string, method?: string }} attribution - what prompted it;
|
||||
* an empty one is passed as null, so the dialog credits the prompt it remembers
|
||||
* @param {(state: 'ready') => void} tell
|
||||
* @returns {Promise<boolean>}
|
||||
*/
|
||||
export const showFramedUpgrade = (win, attribution, tell) => showFramedDialog(win, (closed) => {
|
||||
const dialog = new win.UIUpgradeAccount({
|
||||
attribution: Object.keys(attribution).length ? attribution : null,
|
||||
onClose: (result) => closed(result?.upgraded === true),
|
||||
});
|
||||
return dialog.open_as_window();
|
||||
}, tell);
|
||||
|
||||
/**
|
||||
* Shows the deployment's top-up dialog in a framed popup. Resolves whether
|
||||
* the user bought credit, once the dialog closes.
|
||||
*
|
||||
* @param {Window} win
|
||||
* @param {(state: 'ready') => void} tell
|
||||
* @returns {Promise<boolean>}
|
||||
*/
|
||||
export const showFramedTopUp = (win, tell) => showFramedDialog(win, (closed) => {
|
||||
const dialog = new win.UITopUp({
|
||||
onClose: (result) => closed(result?.toppedUp === true),
|
||||
});
|
||||
return dialog.open();
|
||||
}, tell);
|
||||
|
||||
/**
|
||||
* Resolves once the frame has a viewport. The page keeps a loading frame
|
||||
* hidden, which Chromium and WebKit lay out at 0x0, and a GUI window opened
|
||||
|
||||
@@ -3,7 +3,6 @@ import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import {
|
||||
POPUP_FRAME_MSG,
|
||||
canShowEmailConfirmationFrame,
|
||||
canShowTopUpFrame,
|
||||
canShowUpgradeFrame,
|
||||
closeAccountChecksOnEscape,
|
||||
confirmEmailInFrame,
|
||||
@@ -12,7 +11,6 @@ import {
|
||||
framedPopupParams,
|
||||
framedUpgradeDetails,
|
||||
framesHostUser,
|
||||
showFramedTopUp,
|
||||
showFramedUpgrade,
|
||||
startPopupFrame,
|
||||
} from './popupFrame.js';
|
||||
@@ -52,7 +50,6 @@ describe('framedPopupAction', () => {
|
||||
['/embed/show-save-file-picker', 'show-save-file-picker'],
|
||||
['/embed/show-directory-picker', 'show-directory-picker'],
|
||||
['/embed/upgrade', 'upgrade'],
|
||||
['/embed/top-up', 'top-up'],
|
||||
['/embed/request-email-confirmation', 'request-email-confirmation'],
|
||||
['/embed/apps', null],
|
||||
['/embed/feedback', null],
|
||||
@@ -88,7 +85,6 @@ describe('framesHostUser', () => {
|
||||
['show-save-file-picker', true],
|
||||
['show-directory-picker', true],
|
||||
['upgrade', true],
|
||||
['top-up', true],
|
||||
['request-email-confirmation', true],
|
||||
['sign-in', false],
|
||||
[null, false],
|
||||
@@ -137,34 +133,6 @@ describe('canShowUpgradeFrame', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('canShowTopUpFrame', () => {
|
||||
const win = { UITopUp: Object.assign(function () {}, { embeddable: true }) };
|
||||
const session = { uuid: 'u-1' };
|
||||
|
||||
it('shows for a session with nothing to verify, when the dialog reports its close', () => {
|
||||
expect(canShowTopUpFrame(win, session)).toBe(true);
|
||||
});
|
||||
|
||||
it('needs a top-up dialog that reports its close, whatever the upgrade dialog does', () => {
|
||||
expect(canShowTopUpFrame({}, session)).toBe(false);
|
||||
expect(canShowTopUpFrame({ UITopUp: function () {} }, session)).toBe(false);
|
||||
expect(canShowTopUpFrame({ UIUpgradeAccount: Object.assign(function () {}, { embeddable: true }) }, session)).toBe(false);
|
||||
});
|
||||
|
||||
it.each([
|
||||
'requires_email_confirmation',
|
||||
'requires_phone_verification',
|
||||
'requires_card_verification',
|
||||
'requires_password_change',
|
||||
])('leaves an account with %s to the tab', (check) => {
|
||||
expect(canShowTopUpFrame(win, { ...session, [check]: true })).toBe(false);
|
||||
});
|
||||
|
||||
it('needs a session', () => {
|
||||
expect(canShowTopUpFrame(win, null)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('canShowEmailConfirmationFrame', () => {
|
||||
const session = { uuid: 'u-1' };
|
||||
|
||||
@@ -393,64 +361,6 @@ describe('showFramedUpgrade', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('showFramedTopUp', () => {
|
||||
const topUpWindow = (open) => {
|
||||
const events = new EventTarget();
|
||||
return {
|
||||
document,
|
||||
innerWidth: 1280,
|
||||
innerHeight: 800,
|
||||
addEventListener: events.addEventListener.bind(events),
|
||||
removeEventListener: events.removeEventListener.bind(events),
|
||||
MutationObserver: window.MutationObserver,
|
||||
UITopUp: function (options) {
|
||||
this.open = () => open(options);
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it('tells the page it is ready once open, and resolves whether credit was bought', async () => {
|
||||
const tell = vi.fn();
|
||||
let options;
|
||||
const result = showFramedTopUp(topUpWindow(async (o) => {
|
||||
options = o;
|
||||
}), tell);
|
||||
await vi.waitFor(() => expect(tell).toHaveBeenCalledWith('ready'));
|
||||
expect(tell).toHaveBeenCalledTimes(1);
|
||||
|
||||
options.onClose({ toppedUp: true });
|
||||
await expect(result).resolves.toBe(true);
|
||||
});
|
||||
|
||||
it('resolves false for a close without a purchase', async () => {
|
||||
await expect(showFramedTopUp(topUpWindow(async (o) => o.onClose({ toppedUp: false })), vi.fn())).resolves.toBe(false);
|
||||
await expect(showFramedTopUp(topUpWindow(async (o) => o.onClose()), vi.fn())).resolves.toBe(false);
|
||||
});
|
||||
|
||||
it('resolves false once the dialog is gone without reporting a close', async () => {
|
||||
vi.useFakeTimers();
|
||||
const root = document.createElement('div');
|
||||
root.setAttribute('aria-modal', 'true');
|
||||
const result = showFramedTopUp(topUpWindow(async () => {
|
||||
document.body.append(root);
|
||||
}), vi.fn());
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
root.remove();
|
||||
await vi.advanceTimersByTimeAsync(600);
|
||||
await expect(result).resolves.toBe(false);
|
||||
});
|
||||
|
||||
it('rejects when the dialog fails to open', async () => {
|
||||
await expect(showFramedTopUp(topUpWindow(async () => {
|
||||
throw new Error('no dialog');
|
||||
}), vi.fn())).rejects.toThrow('no dialog');
|
||||
});
|
||||
});
|
||||
|
||||
describe('startPopupFrame', () => {
|
||||
it('does nothing without a framing page to answer', () => {
|
||||
const win = frameWindow();
|
||||
@@ -486,11 +396,6 @@ describe('startPopupFrame', () => {
|
||||
);
|
||||
});
|
||||
|
||||
it('lets the framing page show through a top-up frame', () => {
|
||||
startPopupFrame({ ...frameWindow(), location: { pathname: '/embed/top-up' } }, HOST);
|
||||
expect(document.documentElement.classList.contains('popup-frame-transparent')).toBe(true);
|
||||
});
|
||||
|
||||
it('lets the framing page show through an upgrade or email confirmation frame only', () => {
|
||||
startPopupFrame({ ...frameWindow(), location: { pathname: '/embed/sign-in' } }, HOST);
|
||||
expect(document.documentElement.classList.contains('popup-frame-transparent')).toBe(false);
|
||||
|
||||
@@ -72,13 +72,9 @@ const refresh_item_container = function (el_item_container, options) {
|
||||
}
|
||||
|
||||
// show the loading spinner
|
||||
$(loading_spinner).find('.explorer-loading-spinner-msg').text(`${i18n('loading')}...`);
|
||||
$(loading_spinner).show();
|
||||
setTimeout(function () {
|
||||
// only a load that is still running has taken long
|
||||
if ( is_current() && $(loading_spinner).is(':visible') ) {
|
||||
$(loading_spinner).find('.explorer-loading-spinner-msg').text(i18n('taking_longer_than_usual'));
|
||||
}
|
||||
$(loading_spinner).find('.explorer-loading-spinner-msg').html('Taking a little longer than usual. Please wait...');
|
||||
}, 3000);
|
||||
}, 1000);
|
||||
|
||||
@@ -102,16 +98,14 @@ const refresh_item_container = function (el_item_container, options) {
|
||||
return;
|
||||
}
|
||||
if ( el_window ) {
|
||||
// the class is how a deleted folder's windows are found, and a window opened by path starts without it
|
||||
$(el_window).removeClass(`window-${$(el_window).attr('data-uid')}`).addClass(`window-${fsentry.id}`);
|
||||
$(el_window).attr('data-uid', fsentry.id);
|
||||
$(el_window).attr('data-sort_by', fsentry.sort_by ?? 'name');
|
||||
$(el_window).attr('data-sort_order', fsentry.sort_order ?? 'asc');
|
||||
$(el_window).attr('data-layout', fsentry.layout ?? 'icons');
|
||||
// data-name
|
||||
$(el_window).attr('data-name', fsentry.name);
|
||||
$(el_window).attr('data-name', html_encode(fsentry.name));
|
||||
// data-path
|
||||
$(el_window).attr('data-path', container_path);
|
||||
$(el_window).attr('data-path', html_encode(container_path));
|
||||
$(el_window).find('.window-navbar-path-input').val(container_path);
|
||||
$(el_window).find('.window-navbar-path-input').attr('data-path', container_path);
|
||||
}
|
||||
@@ -126,8 +120,6 @@ const refresh_item_container = function (el_item_container, options) {
|
||||
if ( fsentry.layout === 'details' ) {
|
||||
window.update_details_layout_sort_visuals(el_window, fsentry.sort_by, fsentry.sort_order);
|
||||
}
|
||||
}).catch(() => {
|
||||
// The listing request below reports the failure to the user.
|
||||
});
|
||||
|
||||
// is_directoryPicker
|
||||
@@ -143,8 +135,6 @@ const refresh_item_container = function (el_item_container, options) {
|
||||
|
||||
// remove all existing items
|
||||
$(el_item_container).find('.item').removeItems();
|
||||
// removing the last row shows the empty message, which is wrong while the folder is loading
|
||||
$(empty_message).hide();
|
||||
|
||||
// get items with subdomains/workers included to avoid per-item stat calls
|
||||
const entries_promise = is_shared_view
|
||||
@@ -169,7 +159,6 @@ const refresh_item_container = function (el_item_container, options) {
|
||||
shared_by: share.issuer,
|
||||
owner: share.owner,
|
||||
holder_team: share.holderTeam,
|
||||
also_team_share: share.alsoHeldByTeam,
|
||||
metadata: '',
|
||||
})))
|
||||
: puter.fs.readdir({ path: container_path, consistency: options.consistency ?? 'eventual' });
|
||||
@@ -275,7 +264,6 @@ const refresh_item_container = function (el_item_container, options) {
|
||||
shared_by: fsentry.shared_by,
|
||||
is_shared: fsentry.is_shared,
|
||||
is_team_share: !!fsentry.holder_team,
|
||||
is_also_team_share: fsentry.also_team_share === true,
|
||||
owner: fsentry.owner?.username ?? fsentry.owner,
|
||||
});
|
||||
}
|
||||
@@ -362,11 +350,6 @@ const refresh_item_container = function (el_item_container, options) {
|
||||
$(error_message).html(`Failed to load directory${ html_encode((e && e.message ? `: ${ e.message}` : ''))}`);
|
||||
$(error_message).show();
|
||||
|
||||
// the previous folder's items are gone, so its count must not linger
|
||||
if ( el_window ) {
|
||||
window.update_explorer_footer_item_count(el_window);
|
||||
}
|
||||
|
||||
// Call onComplete callback even in error case, since the "loading" is technically complete
|
||||
if ( options.onComplete && typeof options.onComplete === 'function' ) {
|
||||
options.onComplete();
|
||||
|
||||
@@ -107,31 +107,6 @@ describe('refresh_item_container in the Shared view', () => {
|
||||
is_team_share: true,
|
||||
});
|
||||
});
|
||||
|
||||
it('flags a direct share the team holds too', async () => {
|
||||
list_all_shared.mockResolvedValue([
|
||||
{
|
||||
entryUid: 'u-1',
|
||||
name: 'a.txt',
|
||||
path: '/bob/u-1/a.txt',
|
||||
isDir: false,
|
||||
mode: 'read',
|
||||
issuer: 'bob',
|
||||
owner: 'bob',
|
||||
alsoHeldByTeam: true,
|
||||
},
|
||||
]);
|
||||
document.body.innerHTML =
|
||||
'<div class="window"><div class="item-container" data-path="/alice/Shared"></div></div>';
|
||||
|
||||
refresh_item_container($('.item-container'));
|
||||
|
||||
await vi.waitFor(() => expect(UIItem).toHaveBeenCalledTimes(1));
|
||||
expect(UIItem.mock.calls[0][0]).toMatchObject({
|
||||
is_team_share: false,
|
||||
is_also_team_share: true,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
const deferred = () => {
|
||||
@@ -192,15 +167,6 @@ describe('refresh_item_container after the window moves to another folder', () =
|
||||
expect($('.window').attr('data-uid')).toBe('pictures');
|
||||
});
|
||||
|
||||
it('stores a folder name holding HTML characters on the window as it is', async () => {
|
||||
navigate('/alice/R&D');
|
||||
|
||||
pending.stat['/alice/R&D'].resolve({ id: 'rd', name: 'R&D' });
|
||||
await vi.waitFor(() => expect($('.window').attr('data-uid')).toBe('rd'));
|
||||
|
||||
expect($('.window').attr('data-name')).toBe('R&D');
|
||||
});
|
||||
|
||||
it('drops a listing that arrives just before the window moves on', async () => {
|
||||
vi.useFakeTimers();
|
||||
navigate('/alice/Documents');
|
||||
|
||||
@@ -23,20 +23,6 @@
|
||||
// place in these dialogs; a row already set to one is shown as-is.
|
||||
export const MODES = ['read', 'write', 'manage'];
|
||||
|
||||
// Every mode the API grants, weakest first. Each one implies those before it.
|
||||
const STRENGTH = ['see', 'list', 'read', 'write', 'manage'];
|
||||
|
||||
/**
|
||||
* The stronger of two access modes. `held` wins a tie, and a mode outside the
|
||||
* API's five never beats a known one.
|
||||
*
|
||||
* @param {string} held
|
||||
* @param {string} other
|
||||
* @returns {string}
|
||||
*/
|
||||
export const strongerMode = (held, other) =>
|
||||
STRENGTH.indexOf(other) > STRENGTH.indexOf(held) ? other : held;
|
||||
|
||||
/**
|
||||
* Human-readable label for an access mode, ready to drop into HTML.
|
||||
*
|
||||
|
||||
@@ -6,12 +6,12 @@ import { decode, encode } from 'html-entities';
|
||||
globalThis.window = globalThis.window ?? {};
|
||||
globalThis.html_encode = (str) => encode(str);
|
||||
|
||||
let MODES, mode_label, options_for, strongerMode;
|
||||
let MODES, mode_label, options_for;
|
||||
|
||||
beforeAll(async () => {
|
||||
await import('../i18n/i18n.js'); // installs window.i18n
|
||||
globalThis.i18n = window.i18n;
|
||||
({ MODES, mode_label, options_for, strongerMode } = await import('./shareModes.js'));
|
||||
({ MODES, mode_label, options_for } = await import('./shareModes.js'));
|
||||
});
|
||||
|
||||
// What the browser renders for a fragment of HTML-safe markup.
|
||||
@@ -41,21 +41,6 @@ describe('mode_label', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('strongerMode', () => {
|
||||
it('ranks all five API modes', () => {
|
||||
const modes = ['see', 'list', 'read', 'write', 'manage'];
|
||||
for ( let i = 1; i < modes.length; i++ ) {
|
||||
expect(strongerMode(modes[i - 1], modes[i])).toBe(modes[i]);
|
||||
expect(strongerMode(modes[i], modes[i - 1])).toBe(modes[i]);
|
||||
}
|
||||
});
|
||||
|
||||
it('never lets an unrecognized mode beat a known one', () => {
|
||||
expect(strongerMode('see', 'owner')).toBe('see');
|
||||
expect(strongerMode('owner', 'see')).toBe('see');
|
||||
});
|
||||
});
|
||||
|
||||
describe('options_for', () => {
|
||||
const values = (html) => [...html.matchAll(/value="([^"]*)"/g)].map((m) => m[1]);
|
||||
|
||||
|
||||
@@ -19,7 +19,6 @@
|
||||
|
||||
import list_all_shared from './listAllShared.js';
|
||||
import { is_owned_by_me } from './pathOwner.js';
|
||||
import { strongerMode } from './shareModes.js';
|
||||
import { is_share_root } from './sharePaths.js';
|
||||
|
||||
// What we hold on each shared root, by path: `{ mode, name }`. A `readdir`
|
||||
@@ -30,16 +29,13 @@ let inflight = null;
|
||||
|
||||
/**
|
||||
* Record what a Shared listing reported. Replaces rather than merges, so a
|
||||
* share withdrawn elsewhere does not linger. Grants add up, so a path listed
|
||||
* more than once keeps its strongest mode.
|
||||
* share withdrawn elsewhere does not linger.
|
||||
*/
|
||||
export const remember_shared_roots = (shares) => {
|
||||
roots.clear();
|
||||
for ( const share of shares ) {
|
||||
if ( ! share?.path || ! share?.mode ) continue;
|
||||
const held = roots.get(share.path);
|
||||
const mode = held ? strongerMode(held.mode, share.mode) : share.mode;
|
||||
roots.set(share.path, { mode, name: share.name });
|
||||
roots.set(share.path, { mode: share.mode, name: share.name });
|
||||
}
|
||||
loaded = true;
|
||||
};
|
||||
|
||||
@@ -64,19 +64,6 @@ describe('shared_access', () => {
|
||||
);
|
||||
});
|
||||
|
||||
it('keeps the strongest mode when a path is granted more than once', async () => {
|
||||
remember_shared_roots([
|
||||
{ path: `/jf/${BUDGET}/Budget`, mode: 'manage' },
|
||||
{ path: `/jf/${BUDGET}/Budget`, mode: 'read' },
|
||||
{ path: `/jf/${REPORT}/report.pdf`, mode: 'read' },
|
||||
{ path: `/jf/${REPORT}/report.pdf`, mode: 'write' },
|
||||
]);
|
||||
expect(await shared_mode_for(`/jf/${BUDGET}/Budget`)).toBe('manage');
|
||||
expect(await shared_mode_for(`/jf/${REPORT}/report.pdf`)).toBe('write');
|
||||
expect(await can_share(`/jf/${BUDGET}/Budget/q1.xlsx`)).toBe(true);
|
||||
expect(await can_rename(`/jf/${REPORT}/report.pdf`)).toBe(true);
|
||||
});
|
||||
|
||||
it('reports nothing outside every shared root', async () => {
|
||||
expect(await shared_mode_for(`/jf/${CONTENTS}/Private/a.txt`)).toBe(null);
|
||||
});
|
||||
|
||||
@@ -17,8 +17,6 @@
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
import { atPath } from './pathElements.js';
|
||||
|
||||
/**
|
||||
* Whether a `getShares()` list means this item is shared.
|
||||
*
|
||||
@@ -35,7 +33,10 @@ export const has_direct_share = (shares) =>
|
||||
* can be on the desktop and in any number of open windows.
|
||||
*/
|
||||
export const mark_item_shared = (path, is_shared) => {
|
||||
const $items = atPath('.item', path);
|
||||
if ( ! path ) return;
|
||||
const $items = $('.item').filter(function() {
|
||||
return ($(this).attr('data-path') || '').toLowerCase() === path.toLowerCase();
|
||||
});
|
||||
$items.attr('data-is_shared', is_shared ? 1 : 0);
|
||||
$items
|
||||
.find('.item-shared-marker')
|
||||
|
||||
@@ -1,66 +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 { jwtPayload } from './jwtPayload.js';
|
||||
|
||||
const UUID_HEX = /^[0-9a-f]{32}$/;
|
||||
|
||||
/** @param {unknown} uuid */
|
||||
const uuidHex = (uuid) => {
|
||||
if ( typeof uuid !== 'string' ) return null;
|
||||
const hex = uuid.replace(/-/g, '').toLowerCase();
|
||||
return UUID_HEX.test(hex) ? hex : null;
|
||||
};
|
||||
|
||||
/**
|
||||
* The uuid of the user a session token was issued to. The token carries it as
|
||||
* the `uu` claim: the uuid's 16 bytes in base64, or the dashed uuid itself.
|
||||
*
|
||||
* @param {string} token
|
||||
* @returns {string | null} dashless lowercase hex, or null when the token doesn't say
|
||||
*/
|
||||
const tokenUserHex = (token) => {
|
||||
const claim = jwtPayload(token)?.uu;
|
||||
if ( typeof claim !== 'string' || !claim ) return null;
|
||||
if ( claim.includes('-') ) return uuidHex(claim);
|
||||
try {
|
||||
const bytes = atob(claim);
|
||||
let hex = '';
|
||||
for ( let i = 0; i < bytes.length; i++ ) {
|
||||
hex += bytes.charCodeAt(i).toString(16).padStart(2, '0');
|
||||
}
|
||||
return UUID_HEX.test(hex) ? hex : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Whether a session token was issued to a user other than `user`. False when
|
||||
* either side can't be read, so an unreadable token is never taken for a switch.
|
||||
*
|
||||
* @param {string} token
|
||||
* @param {{ uuid?: string } | null | undefined} user
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export const isTokenForAnotherUser = (token, user) => {
|
||||
const tokenUser = tokenUserHex(token);
|
||||
const currentUser = uuidHex(user?.uuid);
|
||||
return !!tokenUser && !!currentUser && tokenUser !== currentUser;
|
||||
};
|
||||
@@ -1,69 +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 { isTokenForAnotherUser } from './tokenUser.js';
|
||||
|
||||
const ALICE = '5d4adce0-a381-4982-9c02-6e2540026238';
|
||||
const BOB = 'a1b2c3d4-0000-4000-8000-00000000beef';
|
||||
|
||||
const jwtWith = (claims) =>
|
||||
`h.${Buffer.from(JSON.stringify(claims)).toString('base64url')}.s`;
|
||||
// The claim as the server writes it: the uuid's bytes in base64.
|
||||
const tokenFor = (uuid) =>
|
||||
jwtWith({ uu: Buffer.from(uuid.replace(/-/g, ''), 'hex').toString('base64') });
|
||||
|
||||
describe('isTokenForAnotherUser', () => {
|
||||
it('is true for a token issued to a different user', () => {
|
||||
expect(isTokenForAnotherUser(tokenFor(BOB), { uuid: ALICE })).toBe(true);
|
||||
});
|
||||
|
||||
it('is false for a token issued to the same user', () => {
|
||||
expect(isTokenForAnotherUser(tokenFor(ALICE), { uuid: ALICE })).toBe(false);
|
||||
});
|
||||
|
||||
it('compares uuids regardless of letter case', () => {
|
||||
expect(isTokenForAnotherUser(tokenFor(ALICE), { uuid: ALICE.toUpperCase() })).toBe(false);
|
||||
});
|
||||
|
||||
it('reads a claim that holds the dashed uuid itself', () => {
|
||||
expect(isTokenForAnotherUser(jwtWith({ uu: BOB }), { uuid: ALICE })).toBe(true);
|
||||
expect(isTokenForAnotherUser(jwtWith({ uu: ALICE }), { uuid: ALICE })).toBe(false);
|
||||
});
|
||||
|
||||
it('is false when no user is signed in here', () => {
|
||||
expect(isTokenForAnotherUser(tokenFor(BOB), null)).toBe(false);
|
||||
expect(isTokenForAnotherUser(tokenFor(BOB), undefined)).toBe(false);
|
||||
expect(isTokenForAnotherUser(tokenFor(BOB), {})).toBe(false);
|
||||
});
|
||||
|
||||
it('is false when the token does not name a user', () => {
|
||||
for ( const token of [
|
||||
jwtWith({}),
|
||||
jwtWith({ uu: '' }),
|
||||
jwtWith({ uu: 42 }),
|
||||
jwtWith({ uu: 'AAAA' }),
|
||||
jwtWith({ uu: '!!not base64!!' }),
|
||||
'not-a-jwt',
|
||||
'',
|
||||
] ) {
|
||||
expect(isTokenForAnotherUser(token, { uuid: ALICE })).toBe(false);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -1067,7 +1067,6 @@ const en = {
|
||||
'window_click_to_go_back': 'Click to go back.',
|
||||
'window_click_to_go_forward': 'Click to go forward.',
|
||||
'window_click_to_go_up': 'Click to go one directory up.',
|
||||
'window_click_to_change_layout': 'Click to change the layout.',
|
||||
'window_title_public': 'Public',
|
||||
'window_title_videos': 'Videos',
|
||||
'window_title_pictures': 'Pictures',
|
||||
|
||||
@@ -69,51 +69,6 @@ describe('the popup token hand-off in postAuthActions', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('the requests a sign-in popup makes after an account is picked', () => {
|
||||
const postAuthActions = src.slice(
|
||||
src.indexOf('const postAuthActions = async'),
|
||||
src.indexOf('window.initgui = async'),
|
||||
);
|
||||
|
||||
it('matches the early exchange before every exchange in postAuthActions', () => {
|
||||
const exchanges = postAuthActions.split('await window.getUserAppToken(origin)').length - 1;
|
||||
const matched = postAuthActions.split(
|
||||
'reusableTokenExchange(early_token_exchange, origin, window.auth_token) ??',
|
||||
).length - 1;
|
||||
expect(exchanges).toBe(2);
|
||||
expect(matched).toBe(2);
|
||||
expect(postAuthActions.split('getUserAppToken(').length - 1).toBe(2);
|
||||
});
|
||||
|
||||
it('records every early exchange, so none is repeated unmatched', () => {
|
||||
const boot = src.slice(src.indexOf('window.initgui = async'));
|
||||
const sdkLogin = boot.slice(
|
||||
boot.indexOf('// show signup window'),
|
||||
boot.indexOf('window.popup_signin_consent = !!picked_a_user_for_sdk_login;'),
|
||||
);
|
||||
expect(sdkLogin.split('await exchangeUserAppTokenEarly();').length - 1).toBe(3);
|
||||
expect(sdkLogin).not.toContain('getUserAppToken(');
|
||||
});
|
||||
|
||||
it('skips the relationship check only for a picked account', () => {
|
||||
// Signup in the popup sets consent without a pick, and still needs
|
||||
// the check to keep a second account picker away.
|
||||
const check = src.indexOf('await window.checkUserSiteRelationship(');
|
||||
const guard = src.lastIndexOf('if (', check);
|
||||
expect(src.slice(guard, check)).toContain('if (!picked_a_user_for_sdk_login) {');
|
||||
expect(src.slice(guard, check)).not.toContain('popup_signin_consent');
|
||||
});
|
||||
|
||||
it('reuses the early whoami only through reusablePopupUser', () => {
|
||||
const reuse = src.indexOf('whoami = popup_whoami.user;');
|
||||
expect(reuse).toBeGreaterThan(-1);
|
||||
expect(src.split('popup_whoami.user').length - 1).toBe(1);
|
||||
const guard = src.slice(src.lastIndexOf('if (', reuse), reuse);
|
||||
expect(guard).toContain('picked_a_user_for_sdk_login &&');
|
||||
expect(guard).toContain('reusablePopupUser(popup_whoami, {');
|
||||
});
|
||||
});
|
||||
|
||||
describe('the permission popup and browser push', () => {
|
||||
const postAuthActions = src.slice(
|
||||
src.indexOf('const postAuthActions = async'),
|
||||
|
||||
+9
-79
@@ -49,7 +49,6 @@ import { isAttestedOrigin } from './helpers/attestedOrigin.js';
|
||||
import { embedHostUser } from './helpers/embedHostUser.js';
|
||||
import {
|
||||
canShowEmailConfirmationFrame,
|
||||
canShowTopUpFrame,
|
||||
canShowUpgradeFrame,
|
||||
closeAccountChecksOnEscape,
|
||||
confirmEmailInFrame,
|
||||
@@ -58,7 +57,6 @@ import {
|
||||
framedPopupParams,
|
||||
framedUpgradeDetails,
|
||||
framesHostUser,
|
||||
showFramedTopUp,
|
||||
showFramedUpgrade,
|
||||
startPopupFrame,
|
||||
} from './helpers/popupFrame.js';
|
||||
@@ -114,8 +112,6 @@ import {
|
||||
relationshipIsConsent,
|
||||
relaysTokenAtBoot,
|
||||
resolveOpenerOrigin,
|
||||
reusablePopupUser,
|
||||
reusableTokenExchange,
|
||||
runsUserAppTokenExchange,
|
||||
} from './util/popupAuth.js';
|
||||
import { verifyOidcPopupReturn } from './util/popupOidcReturn.js';
|
||||
@@ -165,21 +161,6 @@ const follow_share_recipient = async (action) => {
|
||||
}));
|
||||
};
|
||||
|
||||
// A sign-in popup exchanges as soon as the user has chosen an account, and
|
||||
// `postAuthActions` hands over that result instead of exchanging again.
|
||||
let early_token_exchange = null;
|
||||
const exchangeUserAppTokenEarly = async () => {
|
||||
const authToken = window.auth_token;
|
||||
const data = await window.getUserAppToken(window.openerOrigin);
|
||||
let origin = null;
|
||||
try {
|
||||
origin = new URL(window.openerOrigin).origin;
|
||||
} catch (e) {
|
||||
// No origin to match on, so the result is not reused.
|
||||
}
|
||||
early_token_exchange = { origin, authToken, data };
|
||||
};
|
||||
|
||||
const postAuthActions = async (action) => {
|
||||
if ( await follow_share_recipient(action) ) return;
|
||||
// Set when a popup's user-app token exchange fails. The exchange is what
|
||||
@@ -459,10 +440,7 @@ const postAuthActions = async (action) => {
|
||||
|
||||
if (isolated) {
|
||||
try {
|
||||
const origin = new URL(window.openerOrigin).origin;
|
||||
const data =
|
||||
reusableTokenExchange(early_token_exchange, origin, window.auth_token) ??
|
||||
await window.getUserAppToken(origin);
|
||||
const data = await window.getUserAppToken(new URL(window.openerOrigin).origin);
|
||||
// Same two failure modes the postMessage path below guards
|
||||
// against: `getUserAppToken` reports a network failure by
|
||||
// returning null, and an HTTP failure (a blocked origin, an
|
||||
@@ -506,10 +484,7 @@ const postAuthActions = async (action) => {
|
||||
// Its failure carries `token: null`, which the SDK sets too.
|
||||
const deliver_token_to_opener = deliversTokenAtBoot(action);
|
||||
try {
|
||||
const origin = new URL(window.openerOrigin).origin;
|
||||
let data =
|
||||
reusableTokenExchange(early_token_exchange, origin, window.auth_token) ??
|
||||
await window.getUserAppToken(origin);
|
||||
let data = await window.getUserAppToken(new URL(window.openerOrigin).origin);
|
||||
// `getUserAppToken` reports a network failure by returning
|
||||
// null, and an HTTP failure (a blocked origin, a 5xx) by
|
||||
// returning the parsed *error* body — which is truthy but
|
||||
@@ -1050,23 +1025,6 @@ const postAuthActions = async (action) => {
|
||||
window.tell_popup_frame('closed', { upgraded });
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------------------
|
||||
// Action: top-up — the deployment's top-up dialog for the first-party page framing it,
|
||||
// which hears whether the user bought credit once the dialog closes.
|
||||
// -------------------------------------------------------------------------------------
|
||||
if ( action === 'top-up' && window.embedded_in_frame ) {
|
||||
let toppedUp;
|
||||
try {
|
||||
toppedUp = await showFramedTopUp(window, window.tell_popup_frame);
|
||||
} catch (e) {
|
||||
// A dialog that failed to open leaves the page to open the top-up in a tab.
|
||||
console.error('top-up action failed', e);
|
||||
window.tell_popup_frame('unavailable');
|
||||
return;
|
||||
}
|
||||
window.tell_popup_frame('closed', { toppedUp });
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------------------
|
||||
// Action: request-email-confirmation — puter.ui.requestEmailConfirmation() on the
|
||||
// first-party page framing it, which hears whether the email is confirmed once the
|
||||
@@ -1556,8 +1514,6 @@ window.initgui = async function (options) {
|
||||
let picked_a_user_for_sdk_login = false;
|
||||
// Whether a popup put an account picker in front of the user.
|
||||
let showed_account_picker = false;
|
||||
// The `/whoami` a sign-in popup read before its account picker.
|
||||
let popup_whoami = null;
|
||||
|
||||
// update SDK if auth_token is different from the one in the SDK
|
||||
if (window.auth_token && puter.authToken !== window.auth_token) {
|
||||
@@ -1860,7 +1816,6 @@ window.initgui = async function (options) {
|
||||
!host_user ||
|
||||
session_user !== host_user ||
|
||||
(action === 'upgrade' && !canShowUpgradeFrame(window, session)) ||
|
||||
(action === 'top-up' && !canShowTopUpFrame(window, session)) ||
|
||||
(action === 'request-email-confirmation' && !canShowEmailConfirmationFrame(session))
|
||||
) {
|
||||
window.tell_popup_frame('unavailable');
|
||||
@@ -1913,7 +1868,7 @@ window.initgui = async function (options) {
|
||||
// Completing signup in a sign-in popup is the user asking to
|
||||
// be signed in to the opener.
|
||||
window.popup_signin_consent = true;
|
||||
await exchangeUserAppTokenEarly();
|
||||
await window.getUserAppToken(window.openerOrigin);
|
||||
}
|
||||
} else if (
|
||||
// An action-less popup is a sign-in popup — `postAuthActions`
|
||||
@@ -1937,11 +1892,6 @@ window.initgui = async function (options) {
|
||||
whoami_popup.token || window.auth_token,
|
||||
whoami_popup,
|
||||
);
|
||||
popup_whoami = {
|
||||
user: whoami_popup,
|
||||
authToken: window.auth_token,
|
||||
fetchedAt: Date.now(),
|
||||
};
|
||||
} catch (e) {
|
||||
// session/auth errors will be handled further ahead;
|
||||
// let's log the error for now in case a change in state occurred.
|
||||
@@ -1967,7 +1917,7 @@ window.initgui = async function (options) {
|
||||
String(currentUserUuid);
|
||||
if (proofMatchesCurrentUser) {
|
||||
picked_a_user_for_sdk_login = true;
|
||||
await exchangeUserAppTokenEarly();
|
||||
await window.getUserAppToken(window.openerOrigin);
|
||||
} else {
|
||||
// Show session list so user can pick which account to use
|
||||
showed_account_picker = true;
|
||||
@@ -1977,7 +1927,7 @@ window.initgui = async function (options) {
|
||||
});
|
||||
|
||||
if (picked_a_user_for_sdk_login) {
|
||||
await exchangeUserAppTokenEarly();
|
||||
await window.getUserAppToken(window.openerOrigin);
|
||||
}
|
||||
}
|
||||
// Picking an account here *is* the consent to sign the opener in.
|
||||
@@ -2100,14 +2050,10 @@ window.initgui = async function (options) {
|
||||
// if not, we need to ask the user for confirmation before proceeding BUT only if the action is a file-picker action
|
||||
// -------------------------------------------------------------------------------------
|
||||
if (window.embedded_in_popup && window.openerOrigin) {
|
||||
// An account picked above already answers both questions below, the
|
||||
// picker and the consent. Signup in the popup is not a pick.
|
||||
if (!picked_a_user_for_sdk_login) {
|
||||
let response = await window.checkUserSiteRelationship(
|
||||
window.openerOrigin,
|
||||
);
|
||||
window.userAppToken = response?.token;
|
||||
}
|
||||
let response = await window.checkUserSiteRelationship(
|
||||
window.openerOrigin,
|
||||
);
|
||||
window.userAppToken = response?.token;
|
||||
|
||||
// A framed picker or upgrade already holds the framing page's user,
|
||||
// so it doesn't offer to switch.
|
||||
@@ -2464,22 +2410,6 @@ window.initgui = async function (options) {
|
||||
// Authed
|
||||
// -------------------------------------------------------------------------------------
|
||||
if (window.is_auth()) {
|
||||
// A sign-in popup whose user kept the account it opened with, and whose
|
||||
// exchange just proved the session, already has this user's data.
|
||||
if (
|
||||
!whoami &&
|
||||
picked_a_user_for_sdk_login &&
|
||||
reusablePopupUser(popup_whoami, {
|
||||
userUuid: window.user?.uuid,
|
||||
authToken: window.auth_token,
|
||||
exchangedAuthToken: early_token_exchange?.data?.token
|
||||
? early_token_exchange.authToken
|
||||
: null,
|
||||
now: Date.now(),
|
||||
})
|
||||
) {
|
||||
whoami = popup_whoami.user;
|
||||
}
|
||||
// try to get user data using /whoami, only if that data is missing
|
||||
if (!whoami) {
|
||||
try {
|
||||
|
||||
+31
-50
@@ -23,25 +23,6 @@ import launch_app from './helpers/launchApp.js';
|
||||
import open_item from './helpers/openItem.js';
|
||||
import determine_active_container_parent from './helpers/determineActiveContainerParent.js';
|
||||
|
||||
// The item container the user is working in: around or inside the element they
|
||||
// last pressed, or elsewhere in its window. A pressed item that the window has
|
||||
// since navigated away from leaves only the container it was in.
|
||||
const selection_container = () => {
|
||||
const $active = $(window.active_element);
|
||||
let $container = $active.closest('.item-container');
|
||||
if ( $container.length === 0 ) {
|
||||
$container = $active.find('.item-container');
|
||||
}
|
||||
if ( $container.length === 0 ) {
|
||||
$container = $active.closest('.window').find('.item-container');
|
||||
}
|
||||
if ( $container.length === 0 && window.active_element && !document.contains(window.active_element)
|
||||
&& document.contains(window.active_item_container) ) {
|
||||
$container = $(window.active_item_container);
|
||||
}
|
||||
return $container;
|
||||
};
|
||||
|
||||
$(document).bind('keydown', async function (e) {
|
||||
const focused_el = document.activeElement;
|
||||
//-----------------------------------------------------------------------------
|
||||
@@ -309,14 +290,13 @@ $(document).bind('keydown', async function (e) {
|
||||
if ( selected.length === 1 ) {
|
||||
return selected.get(0);
|
||||
}
|
||||
// only an item that is still selected in this container can anchor the move
|
||||
if ( selected.is(window.latest_selected_item) ) {
|
||||
if ( selected.length > 1 && window.latest_selected_item ) {
|
||||
return window.latest_selected_item;
|
||||
}
|
||||
if ( selected.is(window.active_element) ) {
|
||||
if ( window.active_element && $(window.active_element).hasClass('item') ) {
|
||||
return window.active_element;
|
||||
}
|
||||
return selected.get(-1);
|
||||
return $(window.active_item_container).find('.item').get(0);
|
||||
}
|
||||
|
||||
function findNeighbor (current, direction) {
|
||||
@@ -383,19 +363,18 @@ $(document).bind('keydown', async function (e) {
|
||||
// select first item if none are already selected
|
||||
const selected = $(window.active_item_container).find('.item-selected');
|
||||
if ( selected.length === 0 ) {
|
||||
const first = $(window.active_item_container).find('.item:not(.item-hidden)').get(0);
|
||||
const first = $(window.active_item_container).find('.item').get(0);
|
||||
if ( first ) {
|
||||
$(first).addClass('item-selected');
|
||||
window.active_element = first;
|
||||
window.latest_selected_item = first;
|
||||
first.scrollIntoView({ block: 'nearest', inline: 'nearest' });
|
||||
window.update_explorer_footer_selected_items_count($(window.active_item_container).closest('.window'));
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// virtual grid layout to determine item layout and next items
|
||||
const items = Array.from($(window.active_item_container).find('.item:not(.item-hidden)'));
|
||||
const items = Array.from($(window.active_item_container).find('.item'));
|
||||
const grid = items.map(item => {
|
||||
const rect = item.getBoundingClientRect();
|
||||
return {
|
||||
@@ -414,7 +393,6 @@ $(document).bind('keydown', async function (e) {
|
||||
|
||||
const currentEl = getActiveItem();
|
||||
const current = grid.find(i => i.el === currentEl);
|
||||
if ( ! current ) return;
|
||||
const next = findNeighbor(current, dir);
|
||||
|
||||
// apply new selection(s)
|
||||
@@ -431,7 +409,6 @@ $(document).bind('keydown', async function (e) {
|
||||
$(next.el).addClass('item-selected');
|
||||
}
|
||||
next.el.scrollIntoView({ block: 'nearest', inline: 'nearest' });
|
||||
window.update_explorer_footer_selected_items_count($(window.active_item_container).closest('.window'));
|
||||
}
|
||||
}
|
||||
// ----------------------------------------------
|
||||
@@ -523,15 +500,14 @@ $(document).bind('keydown', async function (e) {
|
||||
// Shift+Delete (win)/ option+command+delete (Mac) key pressed
|
||||
// Permanent delete bypassing trash after alert
|
||||
//-----------------------------------------------------------------------
|
||||
if ( ((e.keyCode === 46 && e.shiftKey) || (e.altKey && e.metaKey && e.keyCode === 8)) && !$(focused_el).is('input, textarea') ) {
|
||||
let $selected_items = selection_container().find('.item-selected');
|
||||
if ( (e.keyCode === 46 && e.shiftKey) || (e.altKey && e.metaKey && e.keyCode === 8) ) {
|
||||
let $selected_items = $(window.active_element).closest('.item-container').find('.item-selected');
|
||||
if ( $selected_items.length > 0 ) {
|
||||
const alert_resp = await UIAlert({
|
||||
message: i18n('confirm_delete_multiple_items'),
|
||||
buttons: [
|
||||
{
|
||||
label: i18n('delete'),
|
||||
value: 'delete',
|
||||
type: 'primary',
|
||||
},
|
||||
{
|
||||
@@ -539,7 +515,7 @@ $(document).bind('keydown', async function (e) {
|
||||
},
|
||||
],
|
||||
});
|
||||
if ( (alert_resp) === 'delete' ) {
|
||||
if ( (alert_resp) === 'Delete' ) {
|
||||
for ( let index = 0; index < $selected_items.length; index++ ) {
|
||||
const element = $selected_items[index];
|
||||
await window.delete_item(element);
|
||||
@@ -552,16 +528,15 @@ $(document).bind('keydown', async function (e) {
|
||||
// Delete (win)/ ctrl+delete (Mac) / cmd+delete (Mac) key pressed
|
||||
// Permanent delete from trash after alert or move to trash
|
||||
//-----------------------------------------------------------------------
|
||||
if ( (e.keyCode === 46 || (e.keyCode === 8 && (e.ctrlKey || e.metaKey))) && !$(focused_el).is('input, textarea') ) {
|
||||
if ( e.keyCode === 46 || (e.keyCode === 8 && (e.ctrlKey || e.metaKey)) ) {
|
||||
// permanent delete?
|
||||
let $selected_items = selection_container().find(`.item-selected[data-path^="${`${window.trash_path }/`}"]`);
|
||||
let $selected_items = $(window.active_element).closest('.item-container').find(`.item-selected[data-path^="${`${window.trash_path }/`}"]`);
|
||||
if ( $selected_items.length > 0 ) {
|
||||
const alert_resp = await UIAlert({
|
||||
message: i18n('confirm_delete_multiple_items'),
|
||||
buttons: [
|
||||
{
|
||||
label: i18n('delete'),
|
||||
value: 'delete',
|
||||
type: 'primary',
|
||||
},
|
||||
{
|
||||
@@ -569,7 +544,7 @@ $(document).bind('keydown', async function (e) {
|
||||
},
|
||||
],
|
||||
});
|
||||
if ( (alert_resp) === 'delete' ) {
|
||||
if ( (alert_resp) === 'Delete' ) {
|
||||
for ( let index = 0; index < $selected_items.length; index++ ) {
|
||||
const element = $selected_items[index];
|
||||
await window.delete_item(element);
|
||||
@@ -579,7 +554,7 @@ $(document).bind('keydown', async function (e) {
|
||||
}
|
||||
// regular delete?
|
||||
else {
|
||||
$selected_items = selection_container().find('.item-selected');
|
||||
$selected_items = $(window.active_element).closest('.item-container').find('.item-selected');
|
||||
if ( $selected_items.length > 0 ) {
|
||||
// Only delete the items if we're not renaming one.
|
||||
if ( $selected_items.children('.item-name-editor-active').length === 0 ) {
|
||||
@@ -594,11 +569,6 @@ $(document).bind('keydown', async function (e) {
|
||||
// A letter or number is pressed and there is no context menu open: search items by name
|
||||
//-----------------------------------------------------------------------
|
||||
if ( !e.ctrlKey && !e.metaKey && !$(focused_el).is('input') && !$(focused_el).is('textarea') && $('.context-menu').length === 0 ) {
|
||||
// Shift, arrows, Enter and other named keys are not part of a name
|
||||
if ( e.key?.length !== 1 ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if ( window.keypress_item_seach_term !== '' )
|
||||
{
|
||||
clearTimeout(window.keypress_item_seach_buffer_timeout);
|
||||
@@ -619,7 +589,7 @@ $(document).bind('keydown', async function (e) {
|
||||
}
|
||||
|
||||
// search for matches
|
||||
let haystack = $(window.active_item_container).find('.item').not('.item-disabled, .item-hidden');
|
||||
let haystack = $(window.active_item_container).find('.item').not('.item-disabled');
|
||||
for ( let j = 0; j < haystack.length; j++ ) {
|
||||
if ( $(haystack[j]).attr('data-name').toLowerCase().startsWith(window.keypress_item_seach_term) ) {
|
||||
matches.push(haystack[j]);
|
||||
@@ -643,7 +613,7 @@ $(document).bind('keydown', async function (e) {
|
||||
// select matching item
|
||||
$(matches[0]).not('.item-disabled').addClass('item-selected');
|
||||
matches[0].scrollIntoView(false);
|
||||
window.update_explorer_footer_selected_items_count($(window.active_item_container).closest('.window'));
|
||||
window.update_explorer_footer_selected_items_count($(window.active_element).closest('.window'));
|
||||
}
|
||||
|
||||
return false;
|
||||
@@ -717,7 +687,11 @@ $(document).bind('keyup keydown', async function (e) {
|
||||
// ctrl/command + a, will select all items on desktop and windows
|
||||
//-----------------------------------------------------------------------------
|
||||
if ( (e.ctrlKey || e.metaKey) && e.which === 65 && !$(focused_el).is('input') && !$(focused_el).is('textarea') ) {
|
||||
const $parent_container = selection_container();
|
||||
let $parent_container = $(window.active_element).closest('.item-container');
|
||||
if ( $parent_container.length === 0 )
|
||||
{
|
||||
$parent_container = $(window.active_element).find('.item-container');
|
||||
}
|
||||
|
||||
if ( $parent_container.attr('data-multiselectable') === 'false' )
|
||||
{
|
||||
@@ -725,7 +699,7 @@ $(document).bind('keyup keydown', async function (e) {
|
||||
}
|
||||
|
||||
if ( $parent_container ) {
|
||||
$($parent_container).find('.item').not('.item-disabled, .item-hidden').addClass('item-selected');
|
||||
$($parent_container).find('.item').not('.item-disabled').addClass('item-selected');
|
||||
window.update_explorer_footer_selected_items_count($parent_container.closest('.window'));
|
||||
}
|
||||
|
||||
@@ -758,7 +732,11 @@ $(document).bind('keyup keydown', async function (e) {
|
||||
!$(focused_el).is('textarea') ) {
|
||||
let $selected_items;
|
||||
|
||||
const parent_container = selection_container();
|
||||
let parent_container = $(window.active_element).closest('.item-container');
|
||||
if ( parent_container.length === 0 )
|
||||
{
|
||||
parent_container = $(window.active_element).find('.item-container');
|
||||
}
|
||||
|
||||
if ( parent_container !== null ) {
|
||||
$selected_items = $(parent_container).find('.item-selected');
|
||||
@@ -783,7 +761,11 @@ $(document).bind('keyup keydown', async function (e) {
|
||||
//-----------------------------------------------------------------------------
|
||||
if ( (e.ctrlKey || e.metaKey) && e.which === 88 && !$(focused_el).is('input') && !$(focused_el).is('textarea') ) {
|
||||
let $selected_items;
|
||||
const parent_container = selection_container();
|
||||
let parent_container = $(window.active_element).closest('.item-container');
|
||||
if ( parent_container.length === 0 )
|
||||
{
|
||||
parent_container = $(window.active_element).find('.item-container');
|
||||
}
|
||||
|
||||
if ( parent_container !== null ) {
|
||||
$selected_items = $(parent_container).find('.item-selected');
|
||||
@@ -881,8 +863,7 @@ $(document).bind('keyup keydown', async function (e) {
|
||||
// Paste
|
||||
// ctrl/command + v, will paste items from the clipboard to the active element
|
||||
//----------------------------------------------
|
||||
// Once per press: releasing V with Ctrl still held would paste a second time.
|
||||
if ( (e.ctrlKey || e.metaKey) && e.which === 86 && e.type === 'keydown' && !$(focused_el).is('input') && !$(focused_el).is('textarea') ) {
|
||||
if ( (e.ctrlKey || e.metaKey) && e.which === 86 && !$(focused_el).is('input') && !$(focused_el).is('textarea') ) {
|
||||
let target_path, target_el;
|
||||
|
||||
// continue only if there is something in the clipboard
|
||||
|
||||
@@ -135,65 +135,6 @@ export const resolveOpenerOrigin = async ({
|
||||
export const relationshipIsConsent = ({ hasRelationship, showedAccountPicker }) =>
|
||||
hasRelationship && !showedAccountPicker;
|
||||
|
||||
/**
|
||||
* The result of a popup's early user-app token exchange, when it stands in for
|
||||
* a second one: it returned a token, for the same opener and the same session.
|
||||
*
|
||||
* @param {{
|
||||
* origin: string|null;
|
||||
* authToken: string|null|undefined;
|
||||
* data: { token?: string; app_uid?: string }|null;
|
||||
* }|null} early - The early exchange, or null when none ran.
|
||||
* @param {string} origin - The opener origin the token is needed for.
|
||||
* @param {string|null|undefined} authToken - The session token in use.
|
||||
* @returns {{ token: string; app_uid?: string }|null} null means exchange again.
|
||||
*/
|
||||
export const reusableTokenExchange = (early, origin, authToken) => {
|
||||
if ( !early?.data?.token || !origin || !authToken ) return null;
|
||||
if ( early.origin !== origin || early.authToken !== authToken ) return null;
|
||||
return /** @type {{ token: string; app_uid?: string }} */ (early.data);
|
||||
};
|
||||
|
||||
/** How long a sign-in popup's first `/whoami` stays usable. */
|
||||
export const POPUP_WHOAMI_MAX_AGE_MS = 60_000;
|
||||
|
||||
const VERIFICATION_GATE_FLAGS = [
|
||||
'requires_email_confirmation',
|
||||
'requires_phone_verification',
|
||||
'requires_card_verification',
|
||||
'requires_password_change',
|
||||
];
|
||||
|
||||
/**
|
||||
* Whether the `/whoami` a sign-in popup read before its account picker still
|
||||
* describes the session, so boot can skip reading it again.
|
||||
*
|
||||
* A pending verification gate always gets a fresh read, and so does a session
|
||||
* the token exchange has not just accepted.
|
||||
*
|
||||
* @param {{
|
||||
* user: Record<string, unknown>;
|
||||
* authToken: string|null|undefined;
|
||||
* fetchedAt: number;
|
||||
* }|null} early - The early read, or null when none succeeded.
|
||||
* @param {{
|
||||
* userUuid: string|null|undefined;
|
||||
* authToken: string|null|undefined;
|
||||
* exchangedAuthToken: string|null|undefined;
|
||||
* now: number;
|
||||
* }} session - The signed-in user and token now, and the session token the
|
||||
* early token exchange succeeded with (null when it returned no token).
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export const reusablePopupUser = (early, { userUuid, authToken, exchangedAuthToken, now }) => {
|
||||
if ( !early?.user?.uuid || !authToken ) return false;
|
||||
if ( early.user.uuid !== userUuid ) return false;
|
||||
if ( early.authToken !== authToken || exchangedAuthToken !== authToken ) return false;
|
||||
if ( VERIFICATION_GATE_FLAGS.some(flag => early.user[flag]) ) return false;
|
||||
const age = now - early.fetchedAt;
|
||||
return age >= 0 && age <= POPUP_WHOAMI_MAX_AGE_MS;
|
||||
};
|
||||
|
||||
/**
|
||||
* Whether a popup running `action` runs the user-app token exchange.
|
||||
*
|
||||
|
||||
Loaded 100 of 118 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user