Files
adolf/extensions/xai/image-generation-provider.test.ts
alvis bedb527145
Some checks failed
ClawSweeper Dispatch / dispatch (push) Has been cancelled
CodeQL / Security High (actions) (push) Has been cancelled
CodeQL / Security High (channel-runtime-boundary) (push) Has been cancelled
CodeQL / Security High (core-auth-secrets) (push) Has been cancelled
CodeQL / Security High (mcp-process-tool-boundary) (push) Has been cancelled
CodeQL / Security High (network-ssrf-boundary) (push) Has been cancelled
CodeQL / Security High (plugin-trust-boundary) (push) Has been cancelled
CodeQL / Security High (process-exec-boundary) (push) Has been cancelled
Docs Sync Publish Repo / sync-publish-repo (push) Has been cancelled
Docs / docs (push) Has been cancelled
OpenClaw Stable Main Closeout / Resolve stable release closeout inputs (push) Has been cancelled
OpenClaw Stable Main Closeout / Verify stable main closeout (push) Has been cancelled
Workflow Sanity / no-tabs (push) Has been cancelled
Workflow Sanity / actionlint (push) Has been cancelled
Workflow Sanity / generated-doc-baselines (push) Has been cancelled
CI / runner-admission (push) Has been cancelled
CI / preflight (push) Has been cancelled
CI / security-fast (push) Has been cancelled
CI / pnpm-store-warmup (push) Has been cancelled
CI / build-artifacts (push) Has been cancelled
CI / native-i18n (push) Has been cancelled
CI / ${{ matrix.check_name }} (push) Has been cancelled
CI / ${{ matrix.checkName }} (push) Has been cancelled
CI / checks-node-compat-node22 (push) Has been cancelled
CI / check-bundled-channel-config-metadata (push) Has been cancelled
CI / check-dependencies (push) Has been cancelled
CI / check-guards (push) Has been cancelled
CI / check-lint (push) Has been cancelled
CI / check-prod-types (push) Has been cancelled
CI / check-shrinkwrap (push) Has been cancelled
CI / check-test-types (push) Has been cancelled
CI / check-additional-boundaries-a (push) Has been cancelled
CI / check-additional-boundaries-bcd (push) Has been cancelled
CI / check-additional-extension-bundled (push) Has been cancelled
CI / check-additional-extension-channels (push) Has been cancelled
CI / check-additional-extension-package-boundary (push) Has been cancelled
CI / check-additional-runtime-topology-architecture (push) Has been cancelled
CI / check-session-accessor-boundary (push) Has been cancelled
CI / check-session-transcript-reader-boundary (push) Has been cancelled
CI / check-docs (push) Has been cancelled
CI / skills-python (push) Has been cancelled
CI / macos-swift (push) Has been cancelled
CI / ios-build (push) Has been cancelled
CI / ci-timings-summary (push) Has been cancelled
Native App Locale Refresh / Refresh native fa (push) Has been cancelled
Native App Locale Refresh / Refresh native fr (push) Has been cancelled
Native App Locale Refresh / Refresh native hi (push) Has been cancelled
Native App Locale Refresh / Refresh native id (push) Has been cancelled
Native App Locale Refresh / Refresh native it (push) Has been cancelled
Native App Locale Refresh / Refresh native ja-JP (push) Has been cancelled
Control UI Locale Refresh / plan (push) Has been cancelled
Control UI Locale Refresh / Refresh ${{ matrix.locale }} (push) Has been cancelled
Control UI Locale Refresh / Commit control UI locale refresh (push) Has been cancelled
Live Media Runner Image / Build live media runner image (push) Has been cancelled
Native App Locale Refresh / Refresh native ar (push) Has been cancelled
Native App Locale Refresh / Refresh native de (push) Has been cancelled
Native App Locale Refresh / Refresh native es (push) Has been cancelled
Native App Locale Refresh / Refresh native ko (push) Has been cancelled
Native App Locale Refresh / Refresh native nl (push) Has been cancelled
Native App Locale Refresh / Refresh native pl (push) Has been cancelled
Native App Locale Refresh / Refresh native pt-BR (push) Has been cancelled
Native App Locale Refresh / Refresh native ru (push) Has been cancelled
Native App Locale Refresh / Refresh native sv (push) Has been cancelled
Native App Locale Refresh / Refresh native th (push) Has been cancelled
Native App Locale Refresh / Refresh native tr (push) Has been cancelled
Native App Locale Refresh / Refresh native uk (push) Has been cancelled
Native App Locale Refresh / Refresh native vi (push) Has been cancelled
Native App Locale Refresh / Refresh native zh-CN (push) Has been cancelled
Native App Locale Refresh / Refresh native zh-TW (push) Has been cancelled
Native App Locale Refresh / Commit native locale refresh (push) Has been cancelled
Plugin Init Scaffold Validation / Validate provider scaffold (push) Has been cancelled
Plugin NPM Release / preview_plugins_npm (push) Has been cancelled
Plugin NPM Release / Validate release publish approval (push) Has been cancelled
Plugin NPM Release / preview_plugin_pack (push) Has been cancelled
Plugin NPM Release / publish_plugins_npm (push) Has been cancelled
Sandbox Common Smoke / sandbox-common-smoke (push) Has been cancelled
Website Installer Sync / static (push) Has been cancelled
Website Installer Sync / linux-docker (push) Has been cancelled
Website Installer Sync / macos-installer (push) Has been cancelled
Website Installer Sync / windows-installer (push) Has been cancelled
Website Installer Sync / sync-website (push) Has been cancelled
Vendor OpenClaw source as Adolf fork baseline
Adolf is a fork/vendored clone of github.com/openclaw/openclaw (v2026.6.11),
free to diverge. Tree copied sans upstream .git; upstream remote added for
future syncs. Node pinned to 24 (.nvmrc); engines already require >=22.19.
Preserves docs/ARCHITECTURE.md.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LeqyaxJF2nbRXJtae2kNB2
2026-07-05 09:36:54 +00:00

300 lines
10 KiB
TypeScript

// Xai tests cover image generation provider plugin behavior.
import { afterEach, describe, expect, it, vi } from "vitest";
import { buildXaiImageGenerationProvider } from "./image-generation-provider.js";
const {
resolveApiKeyForProviderMock,
isProviderApiKeyConfiguredMock,
postJsonRequestMock,
postMultipartRequestMock,
assertOkOrThrowHttpErrorMock,
resolveProviderHttpRequestConfigMock,
createProviderOperationDeadlineMock,
resolveProviderOperationTimeoutMsMock,
sanitizeConfiguredModelProviderRequestMock,
} = vi.hoisted(() => ({
resolveApiKeyForProviderMock: vi.fn(async () => ({ apiKey: "xai-key" })),
isProviderApiKeyConfiguredMock: vi.fn(() => true),
postJsonRequestMock: vi.fn(),
postMultipartRequestMock: vi.fn(),
assertOkOrThrowHttpErrorMock: vi.fn(async () => {}),
resolveProviderHttpRequestConfigMock: vi.fn((params: Record<string, unknown>) => {
const headers = new Headers(params.defaultHeaders as HeadersInit | undefined);
// Stub mirroring the xAI attribution policy headers (real wire is locked in provider-attribution.test.ts).
if (params.provider === "xai") {
const version = process.env.OPENCLAW_VERSION?.trim() || "unknown";
headers.set("User-Agent", `openclaw/${version}`);
headers.set("originator", "openclaw");
headers.set("version", version);
}
return {
baseUrl: params.baseUrl ?? params.defaultBaseUrl ?? "https://api.x.ai/v1",
allowPrivateNetwork: false,
headers,
dispatcherPolicy: undefined,
};
}),
createProviderOperationDeadlineMock: vi.fn((params: Record<string, unknown>) => ({
timeoutMs: params.timeoutMs,
label: params.label,
})),
resolveProviderOperationTimeoutMsMock: vi.fn(
(params: Record<string, unknown>) => params.defaultTimeoutMs ?? 60000,
),
sanitizeConfiguredModelProviderRequestMock: vi.fn((request) => request),
}));
vi.mock("openclaw/plugin-sdk/provider-auth-runtime", () => ({
resolveApiKeyForProvider: resolveApiKeyForProviderMock,
}));
vi.mock("openclaw/plugin-sdk/provider-auth", () => ({
isProviderApiKeyConfigured: isProviderApiKeyConfiguredMock,
}));
vi.mock("openclaw/plugin-sdk/provider-http", async () => {
const actual = await vi.importActual<typeof import("openclaw/plugin-sdk/provider-http")>(
"openclaw/plugin-sdk/provider-http",
);
return {
assertOkOrThrowHttpError: assertOkOrThrowHttpErrorMock,
createProviderOperationDeadline: createProviderOperationDeadlineMock,
postJsonRequest: postJsonRequestMock,
postMultipartRequest: postMultipartRequestMock,
readProviderJsonResponse: actual.readProviderJsonResponse,
resolveProviderHttpRequestConfig: resolveProviderHttpRequestConfigMock,
resolveProviderOperationTimeoutMs: resolveProviderOperationTimeoutMsMock,
sanitizeConfiguredModelProviderRequest: sanitizeConfiguredModelProviderRequestMock,
};
});
vi.mock("openclaw/plugin-sdk/string-coerce-runtime", () => ({
normalizeOptionalString: (v: unknown) => (typeof v === "string" ? v.trim() : undefined),
normalizeOptionalLowercaseString: (v: unknown) =>
typeof v === "string" ? v.trim().toLowerCase() : undefined,
readStringValue: (v: unknown) => (typeof v === "string" ? v.trim() : undefined),
}));
function jsonResponse(payload: unknown): Response {
return new Response(JSON.stringify(payload), {
status: 200,
headers: { "Content-Type": "application/json" },
});
}
function requirePostJsonCall(index = 0): {
url?: string;
timeoutMs?: number;
body?: Record<string, unknown>;
headers?: Headers;
} {
const params = (postJsonRequestMock.mock.calls as unknown as Array<[unknown]>)[index]?.[0] as
| {
url?: string;
timeoutMs?: number;
body?: Record<string, unknown>;
headers?: Headers;
}
| undefined;
if (!params) {
throw new Error(`Expected postJsonRequest call ${index}`);
}
return params;
}
describe("xai image generation provider", () => {
afterEach(() => {
resolveApiKeyForProviderMock.mockClear();
isProviderApiKeyConfiguredMock.mockClear();
postJsonRequestMock.mockReset();
assertOkOrThrowHttpErrorMock.mockClear();
resolveProviderHttpRequestConfigMock.mockClear();
createProviderOperationDeadlineMock.mockClear();
resolveProviderOperationTimeoutMsMock.mockClear();
sanitizeConfiguredModelProviderRequestMock.mockClear();
});
it("builds provider with correct models, default, and capabilities", () => {
const provider = buildXaiImageGenerationProvider();
expect(provider.id).toBe("xai");
expect(provider.label).toBe("xAI");
expect(provider.defaultModel).toBe("grok-imagine-image");
expect(provider.models).toEqual(["grok-imagine-image", "grok-imagine-image-quality"]);
expect(provider.capabilities.generate.maxCount).toBe(4);
expect(provider.capabilities.generate.supportsAspectRatio).toBe(true);
expect(provider.capabilities.geometry?.aspectRatios).toEqual([
"1:1",
"16:9",
"9:16",
"4:3",
"3:4",
"2:3",
"3:2",
]);
expect(provider.capabilities.edit.enabled).toBe(true);
expect(provider.capabilities.edit.maxInputImages).toBe(5);
const isConfigured = provider.isConfigured;
if (!isConfigured) {
throw new Error("expected XAI image provider config predicate");
}
expect(isConfigured({ agentDir: "/tmp/openclaw-xai-test" })).toBe(true);
expect(isProviderApiKeyConfiguredMock).toHaveBeenCalledWith({
provider: "xai",
agentDir: "/tmp/openclaw-xai-test",
});
});
it("uses main provider URL and resolves auth for generation", async () => {
postJsonRequestMock.mockResolvedValue({
response: jsonResponse({
data: [{ b64_json: Buffer.from("testpng").toString("base64") }],
}),
release: vi.fn(async () => {}),
});
const provider = buildXaiImageGenerationProvider();
await provider.generateImage({
provider: "xai",
model: "grok-imagine-image",
prompt: "test prompt",
aspectRatio: "2:3",
resolution: "2K",
cfg: {
models: {
providers: {
xai: {
baseUrl: "https://custom.x.ai/v1",
},
},
},
},
} as any);
const authParams = (
resolveApiKeyForProviderMock.mock.calls as unknown as Array<[unknown]>
)[0]?.[0] as { provider?: string } | undefined;
expect(authParams?.provider).toBe("xai");
const httpParams = (
resolveProviderHttpRequestConfigMock.mock.calls as unknown as Array<[unknown]>
)[0]?.[0] as
| {
provider?: string;
capability?: string;
baseUrl?: string;
}
| undefined;
expect(httpParams?.provider).toBe("xai");
expect(httpParams?.capability).toBe("image");
expect(httpParams?.baseUrl).toBe("https://custom.x.ai/v1");
const request = requirePostJsonCall();
expect(request.url).toContain("/images/generations");
expect(provider.defaultTimeoutMs).toBe(600_000);
expect(request.timeoutMs).toBe(600_000);
expect(request.body?.aspect_ratio).toBe("2:3");
expect(request.body?.resolution).toBe("2k");
expect(resolveProviderOperationTimeoutMsMock).toHaveBeenCalledWith(
expect.objectContaining({
defaultTimeoutMs: 600_000,
}),
);
});
it("supports edit with exact user-provided payload format including image object with type image_url", async () => {
postJsonRequestMock.mockResolvedValue({
response: jsonResponse({
data: [
{
b64_json:
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYGD4z0ABAAEfAG0B0xMAAAAASUVORK5CYII=",
mime_type: "image/png",
},
],
}),
release: vi.fn(async () => {}),
});
const provider = buildXaiImageGenerationProvider();
const buffer = Buffer.from("fakeimage");
await provider.generateImage({
provider: "xai",
model: "grok-imagine-image-quality",
prompt: "Render this as a pencil sketch with detailed shading",
inputImages: [
{
buffer,
mimeType: "image/png",
},
],
cfg: {},
} as any);
const request = requirePostJsonCall();
expect(request.url).toContain("/images/edits");
expect(request.body?.model).toBe("grok-imagine-image-quality");
expect(request.body?.prompt).toBe("Render this as a pencil sketch with detailed shading");
const image = request.body?.image as { url?: string; type?: string } | undefined;
expect(image?.url).toContain("data:image/png;base64,");
expect(image?.type).toBe("image_url");
expect(request.body?.response_format).toBe("b64_json");
});
it("forwards xAI attribution User-Agent through the SDK image request", async () => {
vi.stubEnv("OPENCLAW_VERSION", "2026.3.22");
postJsonRequestMock.mockResolvedValue({
response: jsonResponse({
data: [{ b64_json: Buffer.from("ua-png").toString("base64") }],
}),
release: vi.fn(async () => {}),
});
const provider = buildXaiImageGenerationProvider();
await provider.generateImage({
provider: "xai",
model: "grok-imagine-image",
prompt: "ua check",
cfg: {},
} as any);
const request = requirePostJsonCall();
expect(request.headers?.get("user-agent")).toBe("openclaw/2026.3.22");
expect(request.headers?.get("originator")).toBe("openclaw");
expect(request.headers?.get("version")).toBe("2026.3.22");
vi.unstubAllEnvs();
});
it("uses the plural xAI images payload for multiple edit inputs", async () => {
postJsonRequestMock.mockResolvedValue({
response: jsonResponse({
data: [
{
b64_json: Buffer.from("edited").toString("base64"),
mime_type: "image/png",
},
],
}),
release: vi.fn(async () => {}),
});
const provider = buildXaiImageGenerationProvider();
await provider.generateImage({
provider: "xai",
model: "grok-imagine-image",
prompt: "Combine the references",
inputImages: [
{ buffer: Buffer.from("first"), mimeType: "image/png" },
{ buffer: Buffer.from("second"), mimeType: "image/jpeg" },
],
cfg: {},
} as any);
const request = requirePostJsonCall();
expect(request.url).toContain("/images/edits");
const images = request.body?.images as Array<{ url?: string; type?: string }> | undefined;
expect(images).toHaveLength(2);
expect(images?.[0]?.url).toContain("data:image/png;base64,");
expect(images?.[0]?.type).toBe("image_url");
expect(images?.[1]?.url).toContain("data:image/jpeg;base64,");
expect(images?.[1]?.type).toBe("image_url");
});
});