Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
80 changes: 78 additions & 2 deletions apps/web/src/lib/coding-plans/minimax-usage.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,13 +38,13 @@ afterEach(() => {
});

describe('MiniMax managed usage transport', () => {
it('uses the fixed endpoint and returns normalized subscription quota windows', async () => {
it('uses the documented endpoint and returns normalized subscription quota windows', async () => {
const request = jest.spyOn(global, 'fetch').mockResolvedValue(jsonResponse(payload()));

const result = await getMiniMaxUsage(API_KEY);

expect(request).toHaveBeenCalledWith(
'https://api.minimax.io/v1/token_plan/remains',
'https://www.minimax.io/v1/token_plan/remains',
expect.objectContaining({
method: 'GET',
cache: 'no-store',
Expand All @@ -56,6 +56,7 @@ describe('MiniMax managed usage transport', () => {
},
})
);
expect(request).toHaveBeenCalledTimes(1);
expect(result).toEqual({
fetchedAt: expect.stringContaining('T'),
windows: [
Expand All @@ -81,6 +82,81 @@ describe('MiniMax managed usage transport', () => {
expect(JSON.stringify(result)).not.toContain('status_code');
});

it('falls back to the gateway endpoint when the documented host is unavailable', async () => {
const request = jest
.spyOn(global, 'fetch')
.mockResolvedValueOnce(new Response('raw upstream body', { status: 503 }))
.mockResolvedValueOnce(jsonResponse(payload()));

const result = await getMiniMaxUsage(API_KEY);

expect(request).toHaveBeenNthCalledWith(
1,
'https://www.minimax.io/v1/token_plan/remains',
expect.anything()
);
expect(request).toHaveBeenNthCalledWith(
2,
'https://api.minimax.io/v1/token_plan/remains',
expect.anything()
);
expect(result.windows).toHaveLength(2);
});

it('accepts the MiniMax-M* aggregate row returned by the gateway host', async () => {
jest.spyOn(global, 'fetch').mockResolvedValue(
jsonResponse(
payload({
model_remains: [
{
model_name: 'MiniMax-M*',
current_interval_remaining_percent: 64,
Comment thread
iscekic marked this conversation as resolved.
Resolved
current_interval_status: 1,
end_time: 1_781_280_000_000,
current_weekly_remaining_percent: 91,
current_weekly_status: 1,
weekly_end_time: 1_781_884_800_000,
},
],
})
)
);

await expect(getMiniMaxUsage(API_KEY)).resolves.toMatchObject({
windows: [
{ id: 'short_term', remainingPercent: 64 },
{ id: 'weekly', remainingPercent: 91 },
],
});
});

it('clamps out-of-range remaining percent values to the 0-100 range', async () => {
jest.spyOn(global, 'fetch').mockResolvedValue(
jsonResponse(
payload({
model_remains: [
{
model_name: 'general',
current_interval_remaining_percent: 175,
current_interval_status: 1,
end_time: 1_781_280_000_000,
current_weekly_remaining_percent: -25,
current_weekly_status: 1,
weekly_end_time: 1_781_884_800_000,
},
],
})
)
);

await expect(getMiniMaxUsage(API_KEY)).resolves.toMatchObject({
windows: [
{ id: 'short_term', remainingPercent: 100 },
{ id: 'weekly', remainingPercent: 0 },
],
});
});

it('returns independently valid windows and applies weekly boosts above 100 percent', async () => {
jest.spyOn(global, 'fetch').mockResolvedValue(
jsonResponse(
Expand Down
73 changes: 54 additions & 19 deletions apps/web/src/lib/coding-plans/minimax-usage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,13 @@ import {
type CodingPlanQuotaWindow,
} from '@/lib/coding-plans/usage-contract';

const MINIMAX_USAGE_URL = 'https://api.minimax.io/v1/token_plan/remains';
const MINIMAX_USAGE_URLS = [
'https://www.minimax.io/v1/token_plan/remains',
'https://api.minimax.io/v1/token_plan/remains',
] as const;
const MINIMAX_USAGE_TIMEOUT_MS = 5_000;

const NativePercentSchema = z.number().finite().min(0).max(100);
const NativePercentSchema = z.number().finite();
const NativeIntegerSchema = z.number().int().safe();

const MiniMaxModelRemainsSchema = z.object({
Expand Down Expand Up @@ -61,22 +64,39 @@ function quotaWindow(input: {

const boost =
input.boostPermille !== undefined && input.boostPermille > 0 ? input.boostPermille / 1000 : 1;
const percent = Math.min(100, Math.max(0, input.percent));
const startsAt = isoTimestamp(input.start);
return {
id: input.id,
remainingPercent: input.status === 2 ? 0 : input.percent * boost,
remainingPercent: input.status === 2 ? 0 : percent * boost,
resetsAt,
...(startsAt ? { startsAt } : {}),
period: input.period,
};
}

const AGGREGATE_MODEL_NAME = 'general';

function isMiniMaxModelRow(modelName: string): boolean {
return /^minimax-m/i.test(modelName.trim());
}

function normalizeUsage(rows: MiniMaxModelRemains[]): CodingPlanQuotaWindow[] {
const aggregateRows = rows.filter(row => row.model_name === 'general');
if (aggregateRows.length !== 1) {
const aggregateRows = rows.filter(
row => row.model_name.trim().toLowerCase() === AGGREGATE_MODEL_NAME
);
// MiniMax has returned the aggregate pool under `general` and, on the
// gateway host, under the `MiniMax-M*` family name. Accept both, but keep
// rejecting ambiguous responses that carry several `general` rows.
const aggregate =
aggregateRows.length === 1
? aggregateRows[0]
: aggregateRows.length === 0
? rows.find(row => isMiniMaxModelRow(row.model_name))
Comment thread
iscekic marked this conversation as resolved.
Resolved
: undefined;
if (!aggregate) {
throw new CodingPlanUsageError('invalid_response');
}
const aggregate = aggregateRows[0];
const windows = [
quotaWindow({
id: 'short_term',
Expand Down Expand Up @@ -104,8 +124,8 @@ function normalizeUsage(rows: MiniMaxModelRemains[]): CodingPlanQuotaWindow[] {
return result.data;
}

export async function getMiniMaxUsage(apiKey: string) {
const response = await fetch(MINIMAX_USAGE_URL, {
async function fetchUsageJson(url: string, apiKey: string): Promise<unknown> {
const response = await fetch(url, {
method: 'GET',
headers: {
Accept: 'application/json',
Expand All @@ -123,18 +143,33 @@ export async function getMiniMaxUsage(apiKey: string) {
throw new CodingPlanUsageError('http');
}

const json: unknown = await response.json().catch(() => {
return response.json().catch(() => {
throw new CodingPlanUsageError('invalid_response');
});
const result = MiniMaxUsageResponseSchema.safeParse(json);
if (!result.success) {
throw new CodingPlanUsageError('invalid_response');
}
if (result.data.base_resp.status_code !== 0) {
throw new CodingPlanUsageError('application');
}

export async function getMiniMaxUsage(apiKey: string) {
let failure: CodingPlanUsageError | undefined;

for (const url of MINIMAX_USAGE_URLS) {
try {
const json = await fetchUsageJson(url, apiKey);
const result = MiniMaxUsageResponseSchema.safeParse(json);
if (!result.success) {
throw new CodingPlanUsageError('invalid_response');
}
if (result.data.base_resp.status_code !== 0) {
throw new CodingPlanUsageError('application');
}
return {
fetchedAt: new Date().toISOString(),
windows: normalizeUsage(result.data.model_remains ?? []),
};
} catch (error) {
if (!(error instanceof CodingPlanUsageError)) throw error;
failure ??= error;
}
}
return {
fetchedAt: new Date().toISOString(),
windows: normalizeUsage(result.data.model_remains ?? []),
};

throw failure ?? new CodingPlanUsageError('invalid_response');
}
2 changes: 1 addition & 1 deletion apps/web/src/routers/coding-plans-router.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -535,7 +535,7 @@ describe('coding plans router', () => {

expect(request).toHaveBeenCalledTimes(1);
for (const call of request.mock.calls) {
expect(call[0]).toBe('https://api.minimax.io/v1/token_plan/remains');
expect(call[0]).toBe('https://www.minimax.io/v1/token_plan/remains');
expect(call[1]?.headers).toEqual(
expect.objectContaining({ Authorization: `Bearer ${managedKey}` })
);
Expand Down