ai-chatbot/tests/routes/vip98k-reference-routing.test.ts

1325 lines
49 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { mergeGenerationHistory, recoverReplacementRun } from "@/lib/agents/replacement-run-recovery";
import { randomBytes } from "node:crypto";
import { readFileSync } from "node:fs";
import { createRequire } from "node:module";
import { resolve } from "node:path";
import { runInNewContext } from "node:vm";
import ts from "typescript";
import sharp from "sharp";
import {
isVip98kReferenceSizeAllowed,
normalizeVip98kReferenceImage,
VIP98K_REFERENCE_MAX_BYTES,
} from "@/lib/ai/vip98k-reference-image";
import { expect, test } from "@playwright/test";
import {
bindVip98kImages,
normalizeVip98kInvocationHeaders,
resolveVip98kTaskInvocation,
resolveVip98kImageTaskSize,
selectVip98kTaskInvocation,
type Vip98kTaskInvocation,
} from "@/lib/ai/vip98k-task-invocation";
import {
buildVip98kModelPresets,
isVip98kImageModelVisible,
} from "@/lib/ai/vip98k-models";
import {
addVip98kReferenceRetryToken,
getStorageObjectKeyFromPublicUrl,
getVip98kReferenceStagingObjectKey,
getVip98kStagedMediaRetryDelay,
getVip98kSubmissionRetryDelay,
isVip98kStagedReferenceUrl,
shouldStageVip98kReferenceUrl,
} from "@/lib/ai/vip98k-reference-staging";
import { shouldResolveVip98kResultDelivery } from "@/lib/ai/vip98k-result-delivery";
import {
normalizeVip98kRuntimeConfig,
resolveVip98kSubmissionTimeoutMs,
} from "@/lib/ai/vip98k-runtime-config";
import { BANANAIMAGE_MODEL_PRESETS } from "@/lib/ai/bananaimage-models";
import { buildTaskBody } from "@/lib/ai/providers/vip98k";
import { getSceneRunResult } from "@/lib/agents/scene-run-recovery";
import { extractImageUrlsFromText } from "@/lib/image-url";
import { serverLoader } from "../helpers/canvas-download-server-loader";
for (const status of ["failed", "unresolved", "unknown", "missing"]) {
test(`a synchronous 502 reconciles ${status} without repeating submission`, async () => {
const methods: string[] = [];
const loader = serverLoader({
"@/lib/db/queries": { getSystemSetting: async () => null },
"@/lib/storage/image-archive": {},
"@/lib/storage/service": {},
"@/lib/observability/logger": { createLogger: () => ({ info() {}, warn() {}, error() {} }) },
fetch: async (url: string, init: RequestInit) => {
methods.push(init.method || "GET");
if (init.method === "POST") return Response.json({ error: { message: "generate failed" } }, { status: 502 });
expect(url).toContain("/api/external/requests/by-idempotency-key");
return status === "missing" ? new Response(null, { status: 404 }) : Response.json({ status, request_id: "original-request", result_available: false });
},
});
const provider = loader("lib/ai/providers/vip98k.ts").createVip98k({ apiKey: "fixture", baseURL: "https://provider.test" });
const error = await provider.chat("gpt-image-2.5").doGenerate({ messages: [{ role: "user", content: "a blue cup" }] }).catch((error: unknown) => error);
expect(methods).toEqual(["POST", "GET"]);
if (status === "failed") {
expect(error).toMatchObject({ confirmedNoResult: true });
expect(loader("lib/ai/runtime/image-generation-error.ts").agentImageGenerationError(error, "pinned")).toBe(error);
expect(loader("lib/request-error.ts").getRequestFailureDetails(error).outcome).toBe("failed");
} else {
expect(loader("lib/request-error.ts").getRequestFailureDetails(error).outcome).toBe("unknown");
}
});
}
test("VIP transparent 4K high notices preserve the request and only report verified route failures", async () => {
const spec = { size: "2880x2880", quality: "high", background: "transparent", output_format: "png" };
const scenarios = [
{ name: "confirmed generation failure", status: 502, recovery: "failed", notice: true },
{ name: "confirmed no eligible route", status: 503, notice: true },
{ name: "explicit submission rejection", status: 400, notice: true },
{ name: "unknown result", status: 502, recovery: "unknown", notice: true },
{ name: "successful generation", status: 200, notice: true },
{ name: "medium quality", status: 200, fields: { quality: "medium" } },
{ name: "opaque background", status: 200, fields: { background: "opaque" } },
{ name: "WebP output", status: 200, fields: { output_format: "webp" } },
{ name: "smaller size", status: 200, fields: { size: "2048x2048" } },
{ name: "ordinary model", status: 200, model: "gpt-image-2" },
];
for (const scenario of scenarios) {
await test.step(scenario.name, async () => {
const events: string[] = [];
const model = scenario.model || "gpt-image-2-vip";
const wireSpec = { ...spec, ...scenario.fields };
const loader = serverLoader({
"@/lib/db": {},
"@/lib/db/queries": { getSystemSetting: async () => null },
"@/lib/storage/image-archive": { createDeferredUploadedImage: async (url: string) => ({ original: url, thumbnail: url }) },
"@/lib/storage/service": {},
"@/lib/observability/logger": { createLogger: () => ({ info() {}, warn() {}, error() {} }) },
fetch: async (url: string, init: RequestInit) => {
if (init.method === "POST") {
events.push("submit");
expect(url).toBe("https://provider.test/v1/images/generations");
expect(JSON.parse(String(init.body))).toMatchObject({ ...wireSpec, model });
if (scenario.status === 200) return Response.json({ data: [{ url: "https://assets.test/image.png" }] });
const error = scenario.status === 400
? { code: "invalid_request", message: "The request is invalid" }
: { code: scenario.status === 503 ? "no_eligible_route" : "service_error", message: "Generation failed" };
return Response.json({ error }, {
status: scenario.status, headers: { "X-Request-ID": "original-request" },
});
}
events.push("lookup");
expect(url).toContain("/api/external/requests/by-idempotency-key");
return Response.json({
status: scenario.recovery,
request_id: "original-request",
result_available: false,
error: { code: "service_error" },
});
},
});
const provider = loader("lib/ai/providers/vip98k.ts").createVip98k({ apiKey: "fixture", baseURL: "https://provider.test" });
const attempt = provider.chat(model, { capabilities: { vip98k: { invocation: {
kind: "image", method: "POST", path: "/v1/images/generations", contentType: "application/json",
requestExample: { ...wireSpec, model, prompt: "Fixture prompt" },
} } } }).doGenerate({
messages: [{ role: "user", content: "a blue cup" }],
onImageGenerationNotice: (notice: string) => {
expect(notice).toContain("组合当前可能生成失败");
events.push("notice");
},
});
if (scenario.status === 200) {
expect((await attempt).text).toContain("https://assets.test/image.png");
} else {
const error = await attempt.catch((cause: Error) => cause);
const { getRequestFailureDetails, formatRequestFailure } = loader("lib/request-error.ts");
const details = getRequestFailureDetails(error);
const failure = formatRequestFailure(details, "canvas-request");
expect(failure).toContain("请求编号:canvas-request");
if (scenario.recovery === "unknown") {
expect(details.outcome).toBe("unknown");
expect(failure).not.toContain("备用线路");
} else if (scenario.status === 400) {
expect(failure).toContain("The request is invalid");
expect(failure).not.toContain("备用线路");
const health = loader("lib/ai/runtime/model-health.ts");
expect(health.shouldFailoverVip98kRequestRejection(error, "vip98k")).toBe(false);
} else {
expect(error).toMatchObject({ confirmedNoResult: true, providerRequestId: "original-request" });
expect(failure).toContain("组合当前可能生成失败");
expect(failure.includes("备用线路")).toBe(scenario.status === 503);
expect(loader("lib/ai/runtime/agent-image-failover.ts").agentImageFailurePolicy(error)).toEqual({ retry: false, pause: null });
const health = loader("lib/ai/runtime/model-health.ts");
expect(health.shouldFailoverAiModelError(error)).toBe(false);
expect(health.classifyAiModelHealthFailure(error).counted).toBe(false);
}
}
expect(events).toEqual([
...(scenario.notice ? ["notice"] : []),
"submit",
...(scenario.recovery ? ["lookup"] : []),
]);
});
}
});
test("catalog defaults allow async failover time while retaining an explicit polling limit", () => {
const models = [{ id: "nano-banana-2", type: "image", invocation: {
kind: "task", method: "POST", path: "/extensions/v1/tasks", content_type: "application/json",
request_example: { file_urls: ["https://image.example/source.png"], model: "nano-banana-2", prompt: "Edit" },
} }];
const [normal] = buildVip98kModelPresets(models);
expect((normal.capabilities.vip98k as any).maxPollSeconds).toBe(900);
expect((normal.imageGenConfig!.vip98k as any).maxPollSeconds).toBe(900);
const [configured] = buildVip98kModelPresets([{ ...models[0], max_poll_seconds: 1200 }]);
expect((configured.capabilities.vip98k as any).maxPollSeconds).toBe(1200);
});
test("a synchronous 502 recovers the original completed image through GET only", async () => {
const calls: string[] = [];
let lookups = 0;
const loader = serverLoader({
"@/lib/db/queries": { getSystemSetting: async () => null },
"@/lib/storage/image-archive": { createDeferredUploadedImage: async (url: string) => ({ original: url, thumbnail: url }) },
"@/lib/storage/service": {},
"@/lib/observability/logger": { createLogger: () => ({ info() {}, warn() {}, error() {} }) },
setTimeout: (callback: () => void) => setTimeout(callback, 0),
fetch: async (url: string, init: RequestInit) => {
calls.push(init.method || "GET");
if (init.method === "POST") return Response.json({ error: { message: "bad gateway" } }, { status: 502 });
if (url.endsWith("/by-idempotency-key")) return Response.json({ status: ++lookups === 1 ? "processing" : "succeeded", request_id: "original-request", result_available: true });
expect(url).toContain("/original-request/result");
return Response.json({ data: [{ url: "https://assets.test/original.png" }] });
},
});
const provider = loader("lib/ai/providers/vip98k.ts").createVip98k({ apiKey: "fixture", baseURL: "https://provider.test" });
const result = await provider.chat("gpt-image-2.5").doGenerate({ messages: [{ role: "user", content: "a blue cup" }] });
expect(calls).toEqual(["POST", "GET", "GET", "GET"]);
expect(result.text).toContain("https://assets.test/original.png");
});
const textToImageInvocation: Vip98kTaskInvocation = {
kind: "tool",
method: "POST",
path: "/api/external/tools/generate?tool_id=google%2Fnano-banana-2%2Ftext-to-image",
contentType: "application/json",
requestExample: { prompt: "Generate an image" },
resultMethod: "GET",
resultPath:
"/api/external/tools/result?tool_id=google%2Fnano-banana-2%2Ftext-to-image&taskId={task_id}",
};
test("native expansion maps final canvas scales to per-side ratios and requests PNG", () => {
const invocation: Vip98kTaskInvocation = {
kind: "task", method: "POST", path: "/extensions/v1/tasks", contentType: "application/json",
resultMethod: "GET", resultPath: "/extensions/v1/tasks/{task_id}/result",
requestExample: { model: "image-expansion", metadata: { top: 0.1, bottom: 0.1, left: 0.1, right: 0.1 }, output_format: "" },
inputSchema: { properties: { model: { type: "string" }, file_urls: { type: "array" }, metadata: { type: "object" }, output_format: { type: "string" } } },
};
const { body } = buildTaskBody({ apiKey: "test", modelId: "image-expansion", kind: "image-tool", prompt: "", imageUrls: ["https://source.test/original.jpg"], videoUrls: [], modelConfig: {}, imageParams: { xScale: 1.5, yScale: 2 } }, invocation);
expect(body).toMatchObject({ model: "image-expansion", file_urls: ["https://source.test/original.jpg"], metadata: { left: 0.25, right: 0.25, top: 0.5, bottom: 0.5 }, output_format: "png" });
expect(body).not.toHaveProperty("mask");
expect(body).not.toHaveProperty("prompt");
expect(body).not.toHaveProperty("x_scale");
});
test("text-to-image uses the advertised task contract with native size and ratio, without example reference images", () => {
const configured: Vip98kTaskInvocation = { ...textToImageInvocation, path: "/v1/images/generations", requestExample: { model: "nano-banana-pro", prompt: "sample" } };
const task: Vip98kTaskInvocation = { ...configured, kind: "task", path: "/extensions/v1/tasks",
requestExample: { model: "nano-banana-pro", prompt: "sample", file_urls: ["https://provider.test/logo.png"] },
inputSchema: { required: ["model"], properties: { resolution: { type: "string" }, aspect_ratio: { type: "string" }, file_urls: { type: "array" } } },
};
const invocation = selectVip98kTaskInvocation({ modelId: "nano-banana-pro", kind: "image", configuredInvocation: configured, configuredInvocations: [configured, task], imageCount: 0 });
expect(invocation?.path).toBe("/extensions/v1/tasks");
const result = buildTaskBody({ apiKey: "test", modelId: "nano-banana-pro", kind: "image", prompt: "a blue mug", imageUrls: [], videoUrls: [], modelConfig: {}, imageParams: { imageSize: "2K", aspectRatio: "3:4" } }, invocation);
expect(result.body).toMatchObject({ prompt: "a blue mug", resolution: "2K", aspect_ratio: "3:4" });
expect(result.body).not.toHaveProperty("file_urls");
expect(result.outputConstraintFallbacks).toEqual([]);
expect(selectVip98kTaskInvocation({ modelId: "nano-banana-pro", kind: "image", configuredInvocation: configured, configuredInvocations: [configured, { ...task, inputSchema: { ...task.inputSchema, required: ["model", "file_urls"] } }], imageCount: 0 })?.path).toBe("/v1/images/generations");
});
test("forwards six requested outputs independently of reference count", () => {
const invocation = selectVip98kTaskInvocation({ modelId: "gpt-image-2.5", configuredInvocation: null, imageCount: 2 });
const { body } = buildTaskBody({
apiKey: "test", modelId: "gpt-image-2.5", kind: "image", prompt: "Style the desk",
imageUrls: ["https://assets.test/product.png", "https://assets.test/model.png"],
videoUrls: [], modelConfig: {}, imageParams: { imageCount: 6, imageSize: "2K", aspectRatio: "1:1" },
}, invocation);
expect(body.n).toBe(6);
expect(body.image).toHaveLength(2);
expect(body.size).toBe("2048x2048");
});
test("does not inject output count into a task contract without n", () => {
const { body } = buildTaskBody({
apiKey: "test", modelId: "nano-banana-2.1", kind: "image", prompt: "Desk",
imageUrls: [], videoUrls: [], modelConfig: {}, imageParams: { imageCount: 6 },
}, textToImageInvocation);
expect(body).not.toHaveProperty("n");
});
test("OCR submits a text request even with a stale synced example", () => {
const invocation: Vip98kTaskInvocation = {
kind: "task", method: "POST", path: "/extensions/v1/tasks",
contentType: "application/json", resultMethod: "GET",
resultPath: "/extensions/v1/tasks/{task_id}/result",
requestExample: {
model: "ocr", size: "auto", language: "", file_urls: [""],
output_format: "txt", metadata: { language: "English,ChinesePRC,Digits" },
},
};
const { body } = buildTaskBody({
apiKey: "test", modelId: "ocr", kind: "image-tool", prompt: "",
imageUrls: ["https://assets.test/item.png"], videoUrls: [], modelConfig: {},
}, invocation);
expect(body).toEqual({
model: "ocr", file_urls: ["https://assets.test/item.png"],
output_format: "txt", metadata: { language: "English,ChinesePRC,Digits" },
});
});
test("scene completion counts the current run and preserves partial results", () => {
const user = { id: "run", role: "user", parts: [] };
const result = (count: number) => ({ id: "result", role: "assistant", parts: [{ type: "text", text:
Array.from({ length: count }, (_, i) => `![thumb|||https://assets.test/${i}.png|||2K](https://assets.test/${i}.png)`).join("\n\n") }] });
expect(getSceneRunResult([user, result(6)], "run")).toEqual({ count: 6 });
expect(getSceneRunResult([user, result(1)], "run")).toEqual({ count: 1 });
expect(getSceneRunResult([user, result(0)], "run")).toEqual({ count: 0 });
expect(getSceneRunResult([result(6), user], "run")).toEqual({ count: 0 });
expect(getSceneRunResult([user, result(6), { ...user, id: "next" }], "run")).toBeNull();
expect(getSceneRunResult([user, result(6)], "other")).toBeNull();
});
test("provider generation retains all six outputs and submits only once", async () => {
const filename = resolve("lib/ai/providers/vip98k.ts");
const localRequire = createRequire(filename);
const module = { exports: {} as any };
const archived: string[] = [];
const requests: any[] = [];
const code = ts.transpileModule(readFileSync(filename, "utf8"), {
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022, esModuleInterop: true },
}).outputText;
runInNewContext(code, {
module, exports: module.exports, Buffer, URL, AbortSignal, setTimeout, clearTimeout, process, console,
require(id: string) {
if (id === "@/lib/db/queries") return { getSystemSetting: async () => null };
if (id === "@/lib/storage/image-archive") return {
createDeferredUploadedImage: async (url: string) => { archived.push(url); return { original: url, thumbnail: url }; },
};
return localRequire(id.startsWith("@/") ? resolve(id.slice(2)) : id);
},
fetch: async (_url: string, init: RequestInit) => {
requests.push(JSON.parse(String(init.body)));
return Response.json({ data: Array.from({ length: 6 }, (_, i) => ({ url: `https://assets.test/result-${i}.png` })) });
},
});
const model = module.exports.createVip98k({ apiKey: "test", baseURL: "https://provider.test" }).chat("gpt-image-2.5");
const result = await model.doGenerate({ messages: [{ role: "user", content: "Style a desk" }], imageParams: { imageCount: 6 } });
expect(requests).toHaveLength(1);
expect(requests[0].n).toBe(6);
expect(archived).toHaveLength(6);
expect(extractImageUrlsFromText(result.text)).toHaveLength(6);
});
test.describe("VIP98K reference-image routing", () => {
test("keeps the provider-selected relay route header", () => {
const [preset] = buildVip98kModelPresets([
{
id: "gpt-image-2.5-flare",
type: "image",
capabilities: ["image-to-image"],
invocation: {
kind: "tool",
method: "POST",
path: "/v1/images/generations",
content_type: "application/json",
headers: {
"X-Relay-Route-Option": "preferred-route",
Authorization: "must-not-be-forwarded",
},
request_example: {
image: ["https://api.vip98k.com/logo.png"],
model: "gpt-image-2.5-flare",
prompt: "Edit",
},
},
invocations: [
{
kind: "tool",
method: "POST",
path: "/v1/images/generations",
content_type: "application/json",
headers: {},
request_example: {
image: ["https://api.vip98k.com/logo.png"],
model: "gpt-image-2.5-flare",
prompt: "Edit",
},
},
],
},
]);
const metadata = preset?.capabilities?.vip98k as {
invocation?: Vip98kTaskInvocation;
invocations?: Vip98kTaskInvocation[];
};
expect(metadata.invocation?.headers).toEqual({
"X-Relay-Route-Option": "preferred-route",
});
expect(metadata.invocations?.[0]?.headers).toEqual({
"X-Relay-Route-Option": "preferred-route",
});
expect(
selectVip98kTaskInvocation({
modelId: "gpt-image-2.5-flare",
configuredInvocation: metadata.invocation || null,
configuredInvocations: metadata.invocations,
imageCount: 2,
})?.headers,
).toEqual({ "X-Relay-Route-Option": "preferred-route" });
expect(
normalizeVip98kInvocationHeaders({
"X-Relay-Route-Option": "route-2",
Authorization: "blocked",
}),
).toEqual({ "X-Relay-Route-Option": "route-2" });
});
test("keeps every restored BananaImage preset multi-reference capable", () => {
expect(BANANAIMAGE_MODEL_PRESETS.map((preset) => preset.modelId)).toEqual([
"gemini-3-pro-image-preview",
"gemini-3.1-flash-image-preview",
"gemini-3-pro-image-preview-plus",
"gemini-3.1-flash-image-preview-plus",
"gpt-image-2",
]);
expect(
BANANAIMAGE_MODEL_PRESETS.every(
(preset) =>
preset.supportsImageGen &&
preset.supportsVision &&
preset.capabilities?.supportsMultiImageReference === true &&
Number(preset.capabilities?.maxReferenceImages) >= 2,
),
).toBe(true);
});
test("uses a stable cross-process cache key for staged references", () => {
const source = "https://storage.example/uploads/reference.png";
const key = getVip98kReferenceStagingObjectKey(source);
expect(key).toMatch(/^uploads\/vip98k-cache-v2\/[a-f0-9]{64}\.jpg$/);
expect(
getVip98kReferenceStagingObjectKey(`${source}?sg_media_retry=retry-2`),
).toBe(key);
expect(
isVip98kStagedReferenceUrl(
`https://minio.example/bucket/${key}`,
),
).toBe(true);
});
test("loads bounded database runtime settings with a Pro timeout override", () => {
const defaults = normalizeVip98kRuntimeConfig(null);
expect(resolveVip98kSubmissionTimeoutMs("nano-banana-2", defaults)).toBe(
300_000,
);
expect(resolveVip98kSubmissionTimeoutMs("nano-banana-pro", defaults)).toBe(
300_000,
);
expect(defaults.referenceCacheTtlMs).toBe(7 * 24 * 60 * 60 * 1000);
const config = normalizeVip98kRuntimeConfig({
submissionTimeoutMs: 90_000,
modelSubmissionTimeoutMs: { "nano-banana-pro": 420_000 },
maxSubmissionAttempts: 20,
referenceCacheTtlMs: 1,
});
expect(config.maxSubmissionAttempts).toBe(5);
expect(config.referenceCacheTtlMs).toBe(5 * 60_000);
expect(resolveVip98kSubmissionTimeoutMs("nano-banana-2", config)).toBe(
300_000,
);
expect(resolveVip98kSubmissionTimeoutMs("NANO-BANANA-PRO", config)).toBe(
420_000,
);
});
test("identifies default-storage references that need provider staging", () => {
expect(
shouldStageVip98kReferenceUrl({
mediaUrl: "https://default.example/uploads/reference.jpg",
sourcePublicUrl: "https://default.example",
targetPublicUrl: "https://backup.example/project",
}),
).toBe(true);
expect(
shouldStageVip98kReferenceUrl({
mediaUrl: "https://backup.example/project/uploads/reference.jpg",
sourcePublicUrl: "https://default.example",
targetPublicUrl: "https://backup.example/project",
}),
).toBe(false);
expect(
shouldStageVip98kReferenceUrl({
mediaUrl: "https://external.example/reference.jpg",
sourcePublicUrl: "https://default.example",
targetPublicUrl: "https://backup.example/project",
}),
).toBe(false);
expect(
getStorageObjectKeyFromPublicUrl(
"https://default.example/assets/folder%20name/reference.jpg?token=secret",
"https://default.example/assets",
),
).toBe("folder name/reference.jpg");
});
test("retries transient media rejection while a staged URL propagates", () => {
expect(
getVip98kStagedMediaRetryDelay({
status: 400,
message: "The media request is invalid.",
attempt: 1,
maxAttempts: 3,
stagedReferenceCount: 2,
}),
).toBe(20_000);
expect(
getVip98kStagedMediaRetryDelay({
status: 400,
message: "The media request is invalid.",
attempt: 3,
maxAttempts: 3,
stagedReferenceCount: 2,
}),
).toBeNull();
expect(
addVip98kReferenceRetryToken(
"https://cdn.example/reference.jpg?existing=1",
"retry-2",
),
).toBe(
"https://cdn.example/reference.jpg?existing=1&sg_media_retry=retry-2",
);
});
test("retries provider reconciliation without treating it as a media failure", () => {
expect(getVip98kSubmissionRetryDelay({ status: 409, message: "A request with this idempotency key is still in progress.",
attempt: 1, maxAttempts: 3 })).toBe(15_000);
expect(getVip98kSubmissionRetryDelay({ status: 409, message: "Conflicting request parameters",
attempt: 1, maxAttempts: 3 })).toBeNull();
expect(getVip98kSubmissionRetryDelay({ status: 409, message: "A request with this idempotency key is still in progress.",
attempt: 3, maxAttempts: 3 })).toBeNull();
expect(
getVip98kSubmissionRetryDelay({
status: 503,
message: "The media request is pending safe reconciliation.",
attempt: 1,
maxAttempts: 3,
}),
).toBe(15_000);
expect(
getVip98kSubmissionRetryDelay({
status: 503,
message: "pending safe reconciliation",
attempt: 2,
maxAttempts: 3,
retryAfterMs: 8_000,
}),
).toBe(8_000);
expect(
getVip98kSubmissionRetryDelay({
status: 503,
message:
"The request was sent, but its final outcome could not be confirmed. Do not retry with a new idempotency key.",
attempt: 1,
maxAttempts: 3,
}),
).toBe(15_000);
expect(
getVip98kSubmissionRetryDelay({
status: 503,
message: "pending safe reconciliation",
attempt: 3,
maxAttempts: 3,
}),
).toBeNull();
expect(
getVip98kSubmissionRetryDelay({
status: 502,
message: "Bad Gateway",
attempt: 1,
maxAttempts: 3,
}),
).toBe(15_000);
expect(
getVip98kSubmissionRetryDelay({
status: 504,
message: "Gateway Timeout",
attempt: 2,
maxAttempts: 3,
retryAfterMs: 6_000,
}),
).toBe(6_000);
});
test("shows the newly published Nano Banana Pro image editor", () => {
expect(
isVip98kImageModelVisible({
modelId: "nano-banana-pro",
type: "image",
}),
).toBe(true);
});
test("replaces a text-to-image alias invocation with the resolved reference tool", () => {
const invocation = resolveVip98kTaskInvocation(
"google/nano-banana-2/reference-to-image",
textToImageInvocation
);
expect(invocation?.path).toContain(
"tool_id=google%2Fnano-banana-2%2Freference-to-image"
);
expect(invocation?.resultPath).toContain(
"tool_id=google%2Fnano-banana-2%2Freference-to-image"
);
expect(invocation?.requestExample).toMatchObject({
prompt: "",
video_clips: [{ fps: 1, url: "", ends: 0, start: 0 }],
});
});
test("keeps the catalog invocation when it already targets the resolved tool", () => {
const catalogInvocation: Vip98kTaskInvocation = {
...textToImageInvocation,
path: "/api/external/tools/generate?tool_id=google%2Fnano-banana-2%2Freference-to-image",
resultPath:
"/api/external/tools/result?tool_id=google%2Fnano-banana-2%2Freference-to-image&taskId={task_id}",
requestExample: {
prompt: "Catalog prompt",
video_clips: [{ fps: 2, url: "catalog", ends: 1, start: 0 }],
},
};
expect(
resolveVip98kTaskInvocation(
"google/nano-banana-2/reference-to-image",
catalogInvocation
)
).toBe(catalogInvocation);
});
test("does not rewrite unrelated tools", () => {
expect(
resolveVip98kTaskInvocation("other/image-model", textToImageInvocation)
).toBe(textToImageInvocation);
});
test("routes remove-background through the dedicated external tool", () => {
const invocation = resolveVip98kTaskInvocation("remove-background", null);
expect(invocation?.path).toBe(
"/api/external/tools/generate?tool_id=remove-background"
);
expect(invocation?.resultPath).toBe(
"/api/external/tools/result?tool_id=remove-background&taskId={task_id}"
);
expect(invocation?.requestExample).toEqual({ image_url: "" });
});
test("routes enhance through the dedicated external tool", () => {
const invocation = resolveVip98kTaskInvocation("enhance", null);
expect(invocation?.path).toBe(
"/api/external/tools/generate?tool_id=enhance"
);
expect(invocation?.requestExample).toEqual({
image_url: "",
scale_factor: 4,
});
});
test("selects the V2 media-task contract when a model receives reference images", () => {
const generationInvocation: Vip98kTaskInvocation = {
kind: "tool",
method: "POST",
path: "/v1/images/generations",
contentType: "application/json",
requestExample: { model: "nano-banana-2", n: 1, prompt: "Generate" },
resultMethod: "GET",
resultPath: "",
};
const editInvocation: Vip98kTaskInvocation = {
kind: "task",
method: "POST",
path: "/extensions/v1/tasks",
contentType: "application/json",
requestExample: {
file_urls: ["https://api.vip98k.com/logo.png"],
model: "nano-banana-2",
prompt: "Edit",
},
resultMethod: "GET",
resultPath: "/extensions/v1/tasks/{task_id}/result",
};
expect(
selectVip98kTaskInvocation({
modelId: "nano-banana-2",
configuredInvocation: generationInvocation,
configuredInvocations: [generationInvocation, editInvocation],
imageCount: 2,
}),
).toBe(editInvocation);
});
test("binds every reference image to the V2 file_urls field", () => {
const body: Record<string, unknown> = {
file_urls: ["https://api.vip98k.com/logo.png"],
model: "nano-banana-2",
prompt: "Edit",
};
expect(
bindVip98kImages(body, [
"https://example.com/a.png",
"https://example.com/b.png",
]),
).toEqual(["file_urls"]);
expect(body.file_urls).toEqual([
"https://example.com/a.png",
"https://example.com/b.png",
]);
});
test("binds every reference image to an array-shaped image field", () => {
const body: Record<string, unknown> = {
image: ["https://api.vip98k.com/logo.png"],
model: "gpt-image-2-vip",
prompt: "Edit",
};
expect(
bindVip98kImages(body, [
"https://example.com/a.png",
"https://example.com/b.png",
]),
).toEqual(["image"]);
expect(body.image).toEqual([
"https://example.com/a.png",
"https://example.com/b.png",
]);
});
test("keeps V2 processing-task contracts instead of rewriting them to retired routes", () => {
const invocation: Vip98kTaskInvocation = {
kind: "task",
method: "POST",
path: "/extensions/v1/tasks",
contentType: "application/json",
requestExample: {
file_urls: ["https://api.vip98k.com/logo.png"],
model: "enhance",
},
resultMethod: "GET",
resultPath: "/extensions/v1/tasks/{task_id}/result",
};
expect(resolveVip98kTaskInvocation("enhance", invocation)).toBe(invocation);
});
test("derives multi-image support and parameter controls from all V2 invocations", () => {
const [preset] = buildVip98kModelPresets([
{
id: "nano-banana-2",
type: "image",
capabilities: ["openai.images.generations", "text_to_image"],
invocation: {
kind: "tool",
method: "POST",
path: "/v1/images/generations",
content_type: "application/json",
request_example: { model: "nano-banana-2", n: 1, prompt: "Generate" },
},
invocations: [
{
kind: "tool",
method: "POST",
path: "/v1/images/generations",
content_type: "application/json",
request_example: { model: "nano-banana-2", n: 1, prompt: "Generate" },
},
{
kind: "task",
method: "POST",
path: "/extensions/v1/tasks",
content_type: "application/json",
request_example: {
file_urls: ["https://api.vip98k.com/logo.png"],
model: "nano-banana-2",
prompt: "Edit",
},
input_schema: {
properties: {
aspect_ratio: { type: "string" },
file_urls: { type: "array", maxItems: 8 },
resolution: { type: "string" },
size: {
type: "string",
enum: [
"auto",
"1024x1024",
"2048x2048",
"4096x4096",
],
},
},
},
result_method: "GET",
result_path: "/extensions/v1/tasks/{task_id}/result",
},
],
},
]);
expect(preset).toMatchObject({
supportsVision: true,
supportsImageGen: true,
capabilities: {
supportsMultiImageReference: true,
maxReferenceImages: 8,
supportedImageSizes: ["1K", "2K", "4K"],
supportedAspectRatios: [
"auto",
"1:1",
"4:3",
"3:4",
"16:9",
"9:16",
"3:2",
"2:3",
"4:5",
"5:4",
],
},
imageGenConfig: {
supportsSize: true,
supportedImageSizes: ["1K", "2K", "4K"],
},
});
expect(
(preset?.imageGenConfig?.vip98k as { invocations?: unknown[] })?.invocations,
).toHaveLength(2);
expect(
(
(preset?.imageGenConfig?.vip98k as { invocations?: Array<any> })
?.invocations?.[1]?.inputSchema as Record<string, unknown>
)?.properties,
).toBeTruthy();
});
test("detects V2 asset-only results that need delivery URL resolution", () => {
expect(
shouldResolveVip98kResultDelivery({
payload: {
ready: true,
result: {
result_available: true,
outputs: [{ asset_id: "opaque", type: "image" }],
},
status: "succeeded",
},
status: "succeeded",
outputUrlCount: 0,
}),
).toBe(true);
expect(
shouldResolveVip98kResultDelivery({
payload: { status: "succeeded" },
status: "succeeded",
outputUrlCount: 1,
}),
).toBe(false);
});
test("imports published text-only models without advertising image editing", () => {
const presets = buildVip98kModelPresets([
{
id: "unverified-image-model",
type: "image",
capabilities: ["openai.images.generations", "text_to_image"],
invocation: {
kind: "tool",
method: "POST",
path: "/v1/images/generations",
content_type: "application/json",
request_example: { model: "unverified-image-model", n: 1, prompt: "Generate" },
},
},
]);
expect(presets).toHaveLength(1);
expect(presets[0]).toMatchObject({ supportsVision: false,
capabilities: { supportedModes: ["text-to-image"], maxReferenceImages: 0 } });
});
test("keeps gpt-image-2-vip when its published image field is an array", () => {
const presets = buildVip98kModelPresets([
{
id: "gpt-image-2-vip",
type: "image",
capabilities: [
"image_to_image",
"openai.images.generations",
"text_to_image",
],
invocation: {
kind: "tool",
method: "POST",
path: "/v1/images/generations",
content_type: "application/json",
request_example: {
image: ["https://api.vip98k.com/logo.png"],
model: "gpt-image-2-vip",
n: 1,
prompt: "Generate",
},
input_schema: {
properties: {
image: { type: "array" },
size: { type: "string" },
},
},
},
},
]);
expect(presets).toHaveLength(1);
expect(presets[0]).toMatchObject({
modelId: "gpt-image-2-vip",
supportsVision: true,
isHidden: false,
capabilities: {
supportsMultiImageReference: true,
maxReferenceImages: 8,
supportedImageSizes: ["1K", "2K", "4K"],
},
imageGenConfig: {
supportsSize: true,
supports1K: true,
supports2K: true,
supports4K: true,
supportedImageSizes: ["1K", "2K", "4K"],
},
});
});
test("publishes only the verified GPT Image 2.5 multi-image variants", () => {
const models = [
"gpt-image-2.5",
"gpt-image-2.5-flare",
"gpt-image-2.5-sunburst",
].map((modelId) => ({
id: modelId,
type: "image",
capabilities: ["image_to_image", "openai.images.generations"],
invocation: {
kind: "tool",
method: "POST",
path: "/v1/images/generations",
content_type: "application/json",
request_example: {
image: ["https://api.vip98k.com/logo.png"],
model: modelId,
n: 1,
prompt: "Edit",
quality: "auto",
stream: false,
},
},
}));
expect(models.map((model) => isVip98kImageModelVisible(model))).toEqual([
true,
true,
false,
]);
const presets = buildVip98kModelPresets(models);
expect(
presets.map((preset) => ({
modelId: preset.modelId,
isHidden: preset.isHidden,
supportsQuality: preset.imageGenConfig?.supportsQuality,
quality: preset.defaultParams.quality,
supportedAspectRatios:
preset.imageGenConfig?.supportedAspectRatios,
})),
).toEqual([
{
modelId: "gpt-image-2.5",
isHidden: false,
supportsQuality: true,
quality: "auto",
supportedAspectRatios: ["auto", "1:1", "4:3", "3:4", "16:9", "9:16", "3:2", "2:3", "4:5", "5:4"],
},
{
modelId: "gpt-image-2.5-flare",
isHidden: false,
supportsQuality: true,
quality: "auto",
supportedAspectRatios: [
"auto",
"1:1",
"4:3",
"3:4",
"16:9",
"9:16",
"3:2",
"2:3",
],
},
{
modelId: "gpt-image-2.5-sunburst",
isHidden: true,
supportsQuality: true,
quality: "auto",
supportedAspectRatios: ["auto"],
},
]);
});
test("repairs stale Flare catalog metadata with verified multi-image and size controls", () => {
const [preset] = buildVip98kModelPresets([
{
id: "gpt-image-2.5-flare",
type: "image",
capabilities: ["image_to_image", "openai.images.generations"],
invocation: {
kind: "tool",
method: "POST",
path: "/v1/images/generations",
content_type: "application/json",
headers: { "X-Relay-Route-Option": "flare-route" },
request_example: {
model: "gpt-image-2.5-flare",
n: 1,
prompt: "Edit",
quality: "auto",
stream: false,
},
},
},
]);
expect(preset).toMatchObject({
modelId: "gpt-image-2.5-flare",
supportsVision: true,
isHidden: false,
capabilities: {
supportsMultiImageReference: true,
maxReferenceImages: 8,
supportedImageSizes: ["1K", "2K", "4K"],
supportedAspectRatios: [
"auto",
"1:1",
"4:3",
"3:4",
"16:9",
"9:16",
"3:2",
"2:3",
],
},
defaultParams: { imageSize: "2K" },
imageGenConfig: {
supportsSize: true,
supports1K: true,
supports2K: true,
supports4K: true,
supportedImageSizes: ["1K", "2K", "4K"],
},
});
const metadata = preset?.capabilities?.vip98k as {
invocation?: Vip98kTaskInvocation;
};
const invocation = selectVip98kTaskInvocation({
modelId: "gpt-image-2.5-flare",
configuredInvocation: metadata.invocation || null,
imageCount: 2,
});
expect(invocation?.headers).toEqual({
"X-Relay-Route-Option": "flare-route",
});
expect(invocation?.requestExample.image).toEqual([]);
expect(invocation?.inputSchema).toMatchObject({
properties: {
aspect_ratio: { type: "string" },
image: { type: "array" },
},
});
});
test("Flare retains non-square pixel geometry", () => {
const contract = resolveVip98kTaskInvocation('gpt-image-2.5-flare', null);
const wide = buildTaskBody({apiKey:'fixture',modelId:'gpt-image-2.5-flare',kind:'image',prompt:'wide product',imageUrls:[],videoUrls:[],modelConfig:{},imageParams:{imageSize:'2K',aspectRatio:'16:9'}},contract);
expect(wide.body.size).toBe('2720x1536');
});
test("does not inherit multi-image support from broad authorized metadata", () => {
const presets = buildVip98kModelPresets([
{
id: "nano-banana-2-lite",
type: "image",
capabilities: ["text_to_image", "image_to_image"],
inputModes: ["text", "image"],
invocation: {
kind: "tool",
method: "POST",
path: "/v1/images/generations",
content_type: "application/json",
request_example: {
model: "nano-banana-2-lite",
n: 1,
prompt: "Generate",
},
},
},
]);
expect(presets).toEqual([]);
});
test("excludes Lite and Fast even when catalog metadata claims image arrays", () => {
const presets = buildVip98kModelPresets(
["nano-banana-2-lite", "nano-banana-fast"].map((modelId) => ({
id: modelId,
type: "image",
capabilities: ["text_to_image", "image_to_image"],
invocation: {
kind: "task",
method: "POST",
path: "/extensions/v1/tasks",
content_type: "application/json",
request_example: {
file_urls: ["https://api.vip98k.com/logo.png"],
model: modelId,
prompt: "Edit",
},
input_schema: {
properties: {
file_urls: { type: "array", maxItems: 8 },
},
},
},
})),
);
expect(presets).toEqual([]);
});
test("maps frontend ratio and resolution to the VIP98K V2 size contract", () => {
expect(
resolveVip98kImageTaskSize({
imageSize: "1K",
aspectRatio: "16:9",
fallbackSize: "auto",
}),
).toBe("1024x576");
expect(
resolveVip98kImageTaskSize({
imageSize: "886*1182",
aspectRatio: "3:4",
fallbackSize: "auto",
}),
).toBe("886x1182");
expect(
resolveVip98kImageTaskSize({
imageSize: "1K",
aspectRatio: "auto",
fallbackSize: "auto",
}),
).toBe("auto");
expect(
resolveVip98kImageTaskSize({
imageSize: "4K",
aspectRatio: "1:1",
fallbackSize: "auto",
preserveResolutionBucket: true,
}),
).toBe("4K");
expect(
resolveVip98kImageTaskSize({
imageSize: "2K",
aspectRatio: "1:1",
fallbackSize: "1024x1024",
preserveResolutionBucket: true,
useGptImage25AspectSizing: true,
}),
).toBe("2048x2048");
expect(
resolveVip98kImageTaskSize({
imageSize: "2K",
aspectRatio: "2:3",
fallbackSize: "1024x1024",
preserveResolutionBucket: true,
useGptImage25AspectSizing: true,
}),
).toBe("1664x2512");
expect(
resolveVip98kImageTaskSize({
imageSize: "4K",
aspectRatio: "2:3",
fallbackSize: "1024x1024",
preserveResolutionBucket: true,
useGptImage25AspectSizing: true,
}),
).toBe("2352x3520");
});
test("keeps rounded GPT 2K requests inside their pixel tier", () => {
for (const ratio of ["16:9", "9:16", "4:3", "3:4", "3:2", "2:3", "4:5", "5:4"]) {
const size = resolveVip98kImageTaskSize({ imageSize: "2K", aspectRatio: ratio, useGptImage25AspectSizing: true });
const [w, h] = size!.split("x").map(Number);
expect(w * h).toBeLessThanOrEqual(2048 * 2048);
}
expect(resolveVip98kImageTaskSize({ imageSize: "2K", aspectRatio: "16:9", useGptImage25AspectSizing: true })).toBe("2720x1536");
});
test("advertises verified Flare resolutions and aspect-ratio controls", () => {
const [preset] = buildVip98kModelPresets([
{
id: "gpt-image-2.5-flare",
type: "image",
capabilities: ["image_to_image"],
supported_resolutions: ["1K", "2K", "4K"],
invocation: {
kind: "tool",
method: "POST",
path: "/v1/images/generations",
content_type: "application/json",
request_example: {
image: ["https://api.vip98k.com/logo.png"],
model: "gpt-image-2.5-flare",
prompt: "Edit",
},
input_schema: {
properties: {
image: { type: "array" },
size: { type: "string" },
},
},
},
},
]);
expect(preset?.imageGenConfig).toMatchObject({
supportsSize: true,
supports1K: true,
supports2K: true,
supports4K: true,
supportedImageSizes: ["1K", "2K", "4K"],
supportedAspectRatios: [
"auto",
"1:1",
"4:3",
"3:4",
"16:9",
"9:16",
"3:2",
"2:3",
],
});
});
});
test.describe("VIP98K reference byte limits", () => {
test("compresses a valid upload above the provider limit without cropping", async () => {
const source = await sharp(randomBytes(2300 * 2000 * 3), {
raw: { width: 2300, height: 2000, channels: 3 },
}).png().toBuffer();
expect(source.byteLength).toBeGreaterThan(VIP98K_REFERENCE_MAX_BYTES);
const normalized = await normalizeVip98kReferenceImage(source);
expect(isVip98kReferenceSizeAllowed(normalized.buffer.byteLength)).toBe(true);
const meta = await sharp(normalized.buffer).metadata();
expect(meta.format).toBe("jpeg");
expect(meta.width).toBe(1920);
expect((meta.width || 0) / (meta.height || 1)).toBeCloseTo(2300 / 2000, 2);
});
test("never falls back to unprocessed bytes after decode failure", async () => {
await expect(normalizeVip98kReferenceImage(Buffer.alloc(VIP98K_REFERENCE_MAX_BYTES + 1))).rejects.toThrow();
expect(isVip98kReferenceSizeAllowed(VIP98K_REFERENCE_MAX_BYTES)).toBe(true);
expect(isVip98kReferenceSizeAllowed(VIP98K_REFERENCE_MAX_BYTES + 1)).toBe(false);
expect(isVip98kReferenceSizeAllowed(0)).toBe(false);
});
test("does not retry a permanently oversized reference as propagation lag", () => {
expect(getVip98kStagedMediaRetryDelay({
status: 400,
message: "reference image at example.top is larger than 10 MiB",
attempt: 1,
maxAttempts: 3,
stagedReferenceCount: 1,
})).toBeNull();
});
});
test.describe("replacement run recovery after backgrounding", () => {
const user = (id: string) => ({ id, role: "user", parts: [{ type: "text", text: "replace" }] });
const result = (id: string, run: string, card: string, failed = false) => ({
id, role: "assistant", parts: [{ type: "text", text:
`<!-- AGENT_REPLACEMENT_RUN_ID:${run} -->\n<!-- AGENT_REPLACEMENT_CARD_ID:${card} -->\n${failed ? "生成失败,当前先沿用参考图" : "完成"}\n![image](https://example.com/${card}.png)` }],
});
const pending = { requestMessageId: "new", userTurnCountAtStart: 1, requestedCardIds: ["a", "b"], expectedCount: 2 };
test("settles each card by ID when parallel responses arrive out of order", () => {
const messages = [user("old"), result("old-a", "old", "a"), user("new"), result("new-b", "new", "b")];
const partial = recoverReplacementRun({ messages, ...pending });
expect(partial.completedCardIds).toEqual(["b"]);
expect(partial.done).toBe(false);
const finished = recoverReplacementRun({ messages: [...messages, result("new-a", "new", "a", true)], ...pending });
expect(finished.done).toBe(true);
expect(finished.failedCardIds).toEqual(["a"]);
});
test("recovers missed SSE results from persisted history after tab return", () => {
const local = [user("old"), user("new")];
const history = [...local, result("a", "new", "a"), result("b", "new", "b", true)];
const merged = mergeGenerationHistory(local, history);
expect(recoverReplacementRun({ messages: merged, ...pending }).done).toBe(true);
expect(mergeGenerationHistory(merged, history)).toBe(merged);
});
test("updates persisted content even if message IDs did not change", () => {
const partial = { id: "a", role: "assistant", parts: [{ type: "text", text: "处理中" }] };
const final = result("a", "new", "a", true);
expect(mergeGenerationHistory([partial], [final])).toEqual([final]);
expect(mergeGenerationHistory([final], [partial])).toEqual([final]);
});
test("does not use an old result or duplicate delivery to finish a rerun", () => {
const stale = result("a-old", "old", "a");
const messages = [user("old"), stale, user("new"), stale, result("b", "new", "b"), result("b-copy", "new", "b")];
const progress = recoverReplacementRun({ messages, ...pending });
expect(progress.done).toBe(false);
expect(progress.completedCardIds).toEqual(["b"]);
});
test("recovers legacy pending runs without a request ID", () => {
const messages = [user("old"), result("old-a", "old", "a"), user("new"), result("a", "new", "a")];
expect(recoverReplacementRun({ messages, userTurnCountAtStart: 1, requestedCardIds: ["a"], expectedCount: 1 }).done).toBe(true);
});
});