diff --git a/frontend/package.json b/frontend/package.json index a2da51c9..fcb20e12 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -8,6 +8,7 @@ "dev": "vite", "build": "tsc -b && vite build", "lint": "eslint .", + "test": "node --test --experimental-strip-types src/features/creative-console/*.test.mts", "preview": "vite preview" }, "dependencies": { diff --git a/frontend/src/app/app-shell.tsx b/frontend/src/app/app-shell.tsx index c70c6853..eb2fd96f 100644 --- a/frontend/src/app/app-shell.tsx +++ b/frontend/src/app/app-shell.tsx @@ -1,5 +1,5 @@ import { zodResolver } from "@hookform/resolvers/zod"; -import { Box, ChevronDown, Eye, Image, KeyRound, Languages, LayoutDashboard, LogOut, Menu, MessageSquareText, Monitor, Moon, MoreHorizontal, Settings, Sun, Users, Video } from "lucide-react"; +import { Box, ChevronDown, Eye, Image, KeyRound, Languages, LayoutDashboard, LogOut, Menu, MessageSquareText, Monitor, Moon, MoreHorizontal, Settings, Sparkles, Sun, Users, Video } from "lucide-react"; import { useTheme } from "next-themes"; import { useState, type ReactNode } from "react"; import { useForm } from "react-hook-form"; @@ -24,6 +24,7 @@ const navigation = [ { href: "/accounts", label: "nav.accounts", icon: Users }, { href: "/client-keys", label: "nav.clientKeys", icon: KeyRound }, { href: "/models", label: "nav.models", icon: Box }, + { href: "/creative-console", label: "nav.creativeConsole", icon: Sparkles }, { href: "/gallery", label: "nav.gallery", icon: Image }, { href: "/video-gallery", label: "nav.videoGallery", icon: Video }, { href: "/request-audits", label: "nav.audits", icon: Eye }, diff --git a/frontend/src/app/deferred-pages.tsx b/frontend/src/app/deferred-pages.tsx index 958f78c8..16a4e440 100644 --- a/frontend/src/app/deferred-pages.tsx +++ b/frontend/src/app/deferred-pages.tsx @@ -6,6 +6,7 @@ const AccountsPage = lazyNamed(() => import("@/features/accounts/accounts-page") const AppShell = lazyNamed(() => import("@/app/app-shell"), "AppShell"); const RequestAuditsPage = lazyNamed(() => import("@/features/audits/request-audits-page"), "RequestAuditsPage"); const ClientKeysPage = lazyNamed(() => import("@/features/client-keys/client-keys-page"), "ClientKeysPage"); +const CreativeConsolePage = lazyNamed(() => import("@/features/creative-console/creative-console-page"), "CreativeConsolePage"); const DashboardPage = lazyNamed(() => import("@/features/dashboard/dashboard-page"), "DashboardPage"); const ApiDocsPage = lazyNamed(() => import("@/features/docs/api-docs-page"), "ApiDocsPage"); const GalleryPage = lazyNamed(() => import("@/features/media/gallery-page"), "GalleryPage"); @@ -41,6 +42,10 @@ export function DeferredClientKeysPage() { return ; } +export function DeferredCreativeConsolePage() { + return ; +} + export function DeferredRequestAuditsPage() { return ; } diff --git a/frontend/src/app/router.tsx b/frontend/src/app/router.tsx index ecbefca9..dc50cd4a 100644 --- a/frontend/src/app/router.tsx +++ b/frontend/src/app/router.tsx @@ -1,7 +1,7 @@ import { Navigate, createBrowserRouter } from "react-router-dom"; import { AnonymousBoundary, AuthBoundary } from "@/app/auth-boundary"; -import { DeferredAccountsPage, DeferredApiDocsPage, DeferredAppShell, DeferredClientKeysPage, DeferredDashboardPage, DeferredGalleryPage, DeferredModelsPage, DeferredRequestAuditsPage, DeferredSettingsPage, DeferredVideoGalleryPage } from "@/app/deferred-pages"; +import { DeferredAccountsPage, DeferredApiDocsPage, DeferredAppShell, DeferredClientKeysPage, DeferredCreativeConsolePage, DeferredDashboardPage, DeferredGalleryPage, DeferredModelsPage, DeferredRequestAuditsPage, DeferredSettingsPage, DeferredVideoGalleryPage } from "@/app/deferred-pages"; import { LoginPage } from "@/features/auth/login-page"; export const router = createBrowserRouter([ @@ -19,6 +19,7 @@ export const router = createBrowserRouter([ { path: "/dashboard", element: }, { path: "/accounts", element: }, { path: "/models", element: }, + { path: "/creative-console", element: }, { path: "/client-keys", element: }, { path: "/gallery", element: }, { path: "/video-gallery", element: }, diff --git a/frontend/src/features/creative-console/creative-console-api-parsers.test.mts b/frontend/src/features/creative-console/creative-console-api-parsers.test.mts new file mode 100644 index 00000000..ee91d040 --- /dev/null +++ b/frontend/src/features/creative-console/creative-console-api-parsers.test.mts @@ -0,0 +1,109 @@ +import assert from "node:assert/strict"; +import test from "node:test"; + +import { + CreativeApiError, + createPublicApiBaseURL, + readChatText, + readError, + readImages, + readVideoRequestID, + readVideoStatus, +} from "./creative-console-api-parsers.ts"; +import { listAllPaginatedItems } from "./creative-console-pagination.ts"; + +test("createPublicApiBaseURL normalizes trailing slashes and an existing v1 suffix", () => { + assert.equal(createPublicApiBaseURL("https://api.example.com/"), "https://api.example.com/v1"); + assert.equal(createPublicApiBaseURL("https://api.example.com/base/v1/"), "https://api.example.com/base/v1"); + assert.equal(createPublicApiBaseURL(" "), ""); +}); + +test("readVideoRequestID trims a valid request ID and rejects malformed payloads", () => { + assert.equal(readVideoRequestID({ request_id: " job-1 " }), "job-1"); + assert.equal(readVideoRequestID({ request_id: 1 }), ""); +}); + +test("readChatText supports string and content-part responses", () => { + assert.equal(readChatText({ choices: [{ message: { content: " hello " } }] }), "hello"); + assert.equal(readChatText({ choices: [{ message: { content: [{ text: "first" }, { content: "second" }] } }] }), "first\nsecond"); +}); + +test("readImages supports URL and base64 results", () => { + assert.deepEqual(readImages({ data: [{ url: "/media/a.png", revised_prompt: "revised" }, { b64_json: "YWJj" }] }), [ + { url: "/media/a.png", revisedPrompt: "revised" }, + { url: "data:image/png;base64,YWJj", revisedPrompt: undefined }, + ]); +}); + +test("readVideoStatus parses pending, done, and failed polling responses", () => { + assert.deepEqual(readVideoStatus({ status: "pending", model: "video-model", progress: 42 }), { + status: "pending", + model: "video-model", + progress: 42, + }); + assert.deepEqual(readVideoStatus({ status: "done", progress: 100, video: { url: "/media/video.mp4", duration: 8, respect_moderation: true } }), { + status: "done", + model: undefined, + progress: 100, + video: { url: "/media/video.mp4", duration: 8, respectModeration: true }, + }); + assert.deepEqual(readVideoStatus({ status: "failed", error: { code: "service_unavailable", message: "try later" } }), { + status: "failed", + model: undefined, + progress: 0, + error: { code: "service_unavailable", message: "try later" }, + }); +}); + +test("readVideoStatus rejects malformed polling responses", () => { + assert.throws(() => readVideoStatus({ status: "completed" }), (error: unknown) => { + if (!(error instanceof CreativeApiError)) return false; + assert.equal(error.code, "invalid_response"); + return true; + }); +}); + +test("readError supports OpenAI-style and flat errors", () => { + assert.deepEqual(readError({ error: { code: "invalid_request", message: "bad input" } }), { code: "invalid_request", message: "bad input" }); + assert.deepEqual(readError({ code: "fallback", message: "flat" }), { code: "fallback", message: "flat" }); +}); + +test("listAllPaginatedItems follows total across pages", async () => { + const requestedPages: number[] = []; + const items = await listAllPaginatedItems(async (page, pageSize) => { + requestedPages.push(page); + const allItems = [1, 2, 3, 4, 5]; + const start = (page - 1) * pageSize; + return { items: allItems.slice(start, start + pageSize), page, pageSize, total: allItems.length }; + }, { pageSize: 2 }); + assert.deepEqual(items, [1, 2, 3, 4, 5]); + assert.deepEqual(requestedPages, [1, 2, 3]); +}); + +test("listAllPaginatedItems stops on a short page even when total is stale", async () => { + let calls = 0; + const items = await listAllPaginatedItems(async (page, pageSize) => { + calls += 1; + return { items: page === 1 ? [1, 2] : [], page, pageSize, total: 100 }; + }); + assert.deepEqual(items, [1, 2]); + assert.equal(calls, 1); +}); + +test("listAllPaginatedItems stops on an empty page and respects its safety bound", async () => { + let calls = 0; + const emptyStopped = await listAllPaginatedItems(async (page, pageSize) => { + calls += 1; + return { items: [], page, pageSize, total: 10 }; + }, { pageSize: 1 }); + assert.deepEqual(emptyStopped, []); + assert.equal(calls, 1); + + calls = 0; + const bounded = await listAllPaginatedItems(async (page, pageSize) => { + calls += 1; + return { items: [page], page, pageSize, total: 100 }; + }, { pageSize: 1, maxPages: 2 }); + assert.deepEqual(bounded, [1, 2]); + assert.equal(calls, 2); +}); diff --git a/frontend/src/features/creative-console/creative-console-api-parsers.ts b/frontend/src/features/creative-console/creative-console-api-parsers.ts new file mode 100644 index 00000000..1f30ba82 --- /dev/null +++ b/frontend/src/features/creative-console/creative-console-api-parsers.ts @@ -0,0 +1,137 @@ +export type ChatMessage = { + role: "system" | "user" | "assistant"; + content: string; +}; + +export type ImageResult = { + url: string; + revisedPrompt?: string; +}; + +export type VideoStatus = { + status: "pending" | "done" | "failed"; + model?: string; + progress: number; + video?: { + url: string; + duration?: number; + respectModeration?: boolean; + }; + error?: { + code?: string; + message: string; + }; +}; + +export class CreativeApiError extends Error { + readonly status: number; + readonly code?: string; + + constructor(status: number, message: string, code?: string) { + super(message); + this.name = "CreativeApiError"; + this.status = status; + this.code = code; + } +} + +export function createPublicApiBaseURL(publicApiBaseURL: string): string { + const normalized = publicApiBaseURL.trim().replace(/\/+$/, ""); + if (!normalized) return ""; + return normalized.toLowerCase().endsWith("/v1") ? normalized : `${normalized}/v1`; +} + +export function readVideoRequestID(payload: unknown): string { + if (!isRecord(payload) || typeof payload.request_id !== "string") return ""; + return payload.request_id.trim(); +} + +export function readChatText(payload: unknown): string { + if (!isRecord(payload) || !Array.isArray(payload.choices)) return ""; + for (const choice of payload.choices) { + if (!isRecord(choice) || !isRecord(choice.message)) continue; + const text = readContentText(choice.message.content); + if (text) return text; + } + return ""; +} + +function readContentText(content: unknown): string { + if (typeof content === "string") return content.trim(); + if (!Array.isArray(content)) return ""; + return content + .map((item) => { + if (typeof item === "string") return item; + if (!isRecord(item)) return ""; + return typeof item.text === "string" ? item.text : typeof item.content === "string" ? item.content : ""; + }) + .filter(Boolean) + .join("\n") + .trim(); +} + +export function readImages(payload: unknown): ImageResult[] { + if (!isRecord(payload) || !Array.isArray(payload.data)) return []; + return payload.data.flatMap((item) => { + if (!isRecord(item)) return []; + const url = typeof item.url === "string" && item.url.trim() + ? item.url + : typeof item.b64_json === "string" && item.b64_json.trim() + ? `data:image/png;base64,${item.b64_json}` + : ""; + if (!url) return []; + return [{ url, revisedPrompt: typeof item.revised_prompt === "string" ? item.revised_prompt : undefined }]; + }); +} + +export function readVideoStatus(payload: unknown): VideoStatus { + if (!isRecord(payload) || !isVideoStatus(payload.status)) { + throw new CreativeApiError(200, "The video status response was invalid", "invalid_response"); + } + const progress = typeof payload.progress === "number" && Number.isFinite(payload.progress) + ? Math.max(0, Math.min(100, payload.progress)) + : payload.status === "done" ? 100 : 0; + const result: VideoStatus = { + status: payload.status, + model: typeof payload.model === "string" ? payload.model : undefined, + progress, + }; + if (isRecord(payload.video) && typeof payload.video.url === "string") { + result.video = { + url: payload.video.url, + duration: typeof payload.video.duration === "number" ? payload.video.duration : undefined, + respectModeration: typeof payload.video.respect_moderation === "boolean" ? payload.video.respect_moderation : undefined, + }; + } + if (isRecord(payload.error) && typeof payload.error.message === "string") { + result.error = { + code: typeof payload.error.code === "string" ? payload.error.code : undefined, + message: payload.error.message, + }; + } + return result; +} + +export function readError(payload: unknown): { code?: string; message?: string } { + if (!isRecord(payload)) return {}; + if (isRecord(payload.error)) { + return { + code: typeof payload.error.code === "string" ? payload.error.code : undefined, + message: typeof payload.error.message === "string" ? payload.error.message : undefined, + }; + } + return { + code: typeof payload.code === "string" ? payload.code : undefined, + message: typeof payload.message === "string" ? payload.message : undefined, + }; +} + +function isVideoStatus(value: unknown): value is VideoStatus["status"] { + return value === "pending" || value === "done" || value === "failed"; +} + +function isRecord(value: unknown): value is Record { + return typeof value === "object" && value !== null && !Array.isArray(value); +} + +export const creativeApiInternals = { createPublicApiBaseURL, readChatText, readImages, readVideoRequestID, readVideoStatus, readError }; diff --git a/frontend/src/features/creative-console/creative-console-api.test.mts b/frontend/src/features/creative-console/creative-console-api.test.mts new file mode 100644 index 00000000..96b38800 --- /dev/null +++ b/frontend/src/features/creative-console/creative-console-api.test.mts @@ -0,0 +1,172 @@ +import assert from "node:assert/strict"; +import test from "node:test"; + +import { + createChatCompletion, + createPublicApiBaseURL, + createVideo, + generateImage, + getVideo, +} from "./creative-console-api.ts"; + +type FetchCall = { + input: string; + init?: RequestInit; +}; + +function jsonResponse(payload: unknown, init: ResponseInit = {}): Response { + return new Response(JSON.stringify(payload), { + status: init.status ?? 200, + headers: { "Content-Type": "application/json", ...init.headers }, + }); +} + +async function withFetchMock(handler: (input: string, init?: RequestInit) => Response | Promise, run: () => Promise): Promise { + const previousFetch = globalThis.fetch; + globalThis.fetch = ((input: RequestInfo | URL, init?: RequestInit) => handler(String(input), init)) as typeof fetch; + try { + return await run(); + } finally { + globalThis.fetch = previousFetch; + } +} + +function readBody(call: FetchCall): Record { + const body = call.init?.body; + assert.equal(typeof body, "string"); + return JSON.parse(body as string) as Record; +} + +test("createPublicApiBaseURL does not duplicate a case-insensitive v1 suffix", () => { + assert.equal(createPublicApiBaseURL("https://api.example.com/V1/"), "https://api.example.com/V1"); +}); + +test("createChatCompletion uses the OpenAI endpoint, bearer key, and non-streaming body", async () => { + const calls: FetchCall[] = []; + const text = await withFetchMock((input, init) => { + calls.push({ input, init }); + return jsonResponse({ choices: [{ message: { content: "pong" } }] }); + }, () => createChatCompletion({ + publicApiBaseURL: "https://api.example.com/root/", + apiKey: "test-key", + model: "grok-chat", + messages: [{ role: "user", content: "ping" }], + })); + + assert.equal(text, "pong"); + assert.equal(calls.length, 1); + assert.equal(calls[0]?.input, "https://api.example.com/root/v1/chat/completions"); + assert.equal(calls[0]?.init?.method, "POST"); + const headers = new Headers(calls[0]?.init?.headers); + assert.equal(headers.get("Authorization"), "Bearer test-key"); + assert.equal(headers.get("Content-Type"), "application/json"); + assert.deepEqual(readBody(calls[0]!), { + model: "grok-chat", + messages: [{ role: "user", content: "ping" }], + stream: false, + }); +}); + +test("generateImage uses the generation contract and resolves relative media URLs", async () => { + const calls: FetchCall[] = []; + const images = await withFetchMock((input, init) => { + calls.push({ input, init }); + return jsonResponse({ data: [{ url: "/media/generated.png", revised_prompt: "refined" }] }); + }, () => generateImage({ + publicApiBaseURL: "https://api.example.com/root", + apiKey: "test-key", + model: "grok-image", + prompt: "draw a raven", + count: 2, + aspectRatio: "3:2", + resolution: "2k", + })); + + assert.deepEqual(images, [{ url: "https://api.example.com/media/generated.png", revisedPrompt: "refined" }]); + assert.equal(calls[0]?.input, "https://api.example.com/root/v1/images/generations"); + assert.deepEqual(readBody(calls[0]!), { + model: "grok-image", + prompt: "draw a raven", + n: 2, + aspect_ratio: "3:2", + resolution: "2k", + response_format: "url", + stream: false, + }); +}); + +test("generateImage resolves path-relative media URLs under the configured API base path", async () => { + const images = await withFetchMock( + () => jsonResponse({ data: [{ url: "media/generated.png" }] }), + () => generateImage({ + publicApiBaseURL: "https://api.example.com/root", + apiKey: "test-key", + model: "grok-image", + prompt: "draw a raven", + count: 1, + aspectRatio: "1:1", + resolution: "1k", + }), + ); + assert.equal(images[0]?.url, "https://api.example.com/root/media/generated.png"); +}); + +test("createVideo sends the official image.url shape and getVideo polls the official endpoint", async () => { + const calls: FetchCall[] = []; + const result = await withFetchMock((input, init) => { + calls.push({ input, init }); + if (calls.length === 1) return jsonResponse({ request_id: "job/1" }); + return jsonResponse({ status: "done", progress: 100, video: { url: "videos/result.mp4", duration: 8 } }); + }, async () => { + const requestId = await createVideo({ + publicApiBaseURL: "https://api.example.com/root", + apiKey: "test-key", + model: "grok-video", + prompt: "animate it", + imageURL: "https://images.example.com/input.png", + duration: 8, + aspectRatio: "16:9", + resolution: "720p", + }); + const status = await getVideo({ + publicApiBaseURL: "https://api.example.com/root", + apiKey: "test-key", + requestId, + }); + return { requestId, status }; + }); + + assert.equal(result.requestId, "job/1"); + assert.deepEqual(readBody(calls[0]!), { + model: "grok-video", + prompt: "animate it", + duration: 8, + aspect_ratio: "16:9", + resolution: "720p", + image: { url: "https://images.example.com/input.png" }, + }); + assert.equal(calls[1]?.input, "https://api.example.com/root/v1/videos/job%2F1"); + assert.equal(calls[1]?.init?.method, "GET"); + assert.equal(result.status.status, "done"); + assert.equal(result.status.video?.url, "https://api.example.com/root/videos/result.mp4"); +}); + +test("public API errors preserve the sanitized OpenAI message and code", async () => { + await withFetchMock(() => jsonResponse({ error: { code: "invalid_api_key", message: "bad key" } }, { status: 401 }), async () => { + await assert.rejects( + () => createChatCompletion({ + publicApiBaseURL: "https://api.example.com", + apiKey: "bad-key", + model: "grok-chat", + messages: [{ role: "user", content: "ping" }], + }), + (error: unknown) => { + if (!(error instanceof Error)) return false; + assert.equal(error.message, "bad key"); + assert.equal((error as Error & { status?: number }).status, 401); + assert.equal((error as Error & { code?: string }).code, "invalid_api_key"); + return true; + }, + ); + }); +}); diff --git a/frontend/src/features/creative-console/creative-console-api.ts b/frontend/src/features/creative-console/creative-console-api.ts new file mode 100644 index 00000000..b72313ac --- /dev/null +++ b/frontend/src/features/creative-console/creative-console-api.ts @@ -0,0 +1,180 @@ +import { + CreativeApiError, + createPublicApiBaseURL as createPublicApiBaseURLFromString, + creativeApiInternals, + readChatText, + readError, + readImages, + readVideoRequestID, + readVideoStatus, + type ChatMessage, + type ImageResult, + type VideoStatus, +} from "./creative-console-api-parsers.ts"; + +export { CreativeApiError, creativeApiInternals }; +export type { ChatMessage, ImageResult, VideoStatus }; + +type RequestOptions = { + method?: "GET" | "POST"; + body?: Record; + signal?: AbortSignal; +}; + +export function createPublicApiBaseURL(publicApiBaseURL = browserPublicApiBaseURL()): string { + return createPublicApiBaseURLFromString(publicApiBaseURL); +} + +function browserPublicApiBaseURL(): string { + if (typeof window === "undefined") return ""; + const apiBaseURL = window.__GROK2API_RUNTIME_CONFIG__?.apiBaseUrl?.replace(/\/$/, "") ?? ""; + const publicApiBaseURL = window.__GROK2API_RUNTIME_CONFIG__?.publicApiBaseUrl?.replace(/\/$/, "") ?? ""; + const developmentApiBaseURL = typeof __GROK2API_DEV_API_TARGET__ === "string" ? __GROK2API_DEV_API_TARGET__.replace(/\/$/, "") : ""; + return publicApiBaseURL || apiBaseURL || developmentApiBaseURL || window.location.origin; +} + +export async function createChatCompletion(input: { + publicApiBaseURL: string; + apiKey: string; + model: string; + messages: ChatMessage[]; + signal?: AbortSignal; +}): Promise { + const payload = await publicApiRequest( + input.publicApiBaseURL, + input.apiKey, + "/chat/completions", + { method: "POST", body: { model: input.model, messages: input.messages, stream: false }, signal: input.signal }, + ); + const text = readChatText(payload); + if (!text) throw new CreativeApiError(200, "The chat response did not contain assistant text", "invalid_response"); + return text; +} + +export async function generateImage(input: { + publicApiBaseURL: string; + apiKey: string; + model: string; + prompt: string; + count: number; + aspectRatio: string; + resolution: string; + signal?: AbortSignal; +}): Promise { + const payload = await publicApiRequest( + input.publicApiBaseURL, + input.apiKey, + "/images/generations", + { + method: "POST", + body: { + model: input.model, + prompt: input.prompt, + n: input.count, + aspect_ratio: input.aspectRatio, + resolution: input.resolution, + response_format: "url", + stream: false, + }, + signal: input.signal, + }, + ); + const images = readImages(payload); + if (images.length === 0) throw new CreativeApiError(200, "The image response did not contain any images", "invalid_response"); + return images.map((image) => ({ ...image, url: resolveMediaURL(input.publicApiBaseURL, image.url) })); +} + +export async function createVideo(input: { + publicApiBaseURL: string; + apiKey: string; + model: string; + prompt: string; + imageURL?: string; + duration: number; + aspectRatio: string; + resolution: string; + signal?: AbortSignal; +}): Promise { + const body: Record = { + model: input.model, + prompt: input.prompt, + duration: input.duration, + aspect_ratio: input.aspectRatio, + resolution: input.resolution, + }; + if (input.imageURL) body.image = { url: input.imageURL }; + const payload = await publicApiRequest( + input.publicApiBaseURL, + input.apiKey, + "/videos/generations", + { method: "POST", body, signal: input.signal }, + ); + const requestId = readVideoRequestID(payload); + if (!requestId) { + throw new CreativeApiError(200, "The video response did not contain a request ID", "invalid_response"); + } + return requestId; +} + +export async function getVideo(input: { + publicApiBaseURL: string; + apiKey: string; + requestId: string; + signal?: AbortSignal; +}): Promise { + const payload = await publicApiRequest( + input.publicApiBaseURL, + input.apiKey, + `/videos/${encodeURIComponent(input.requestId)}`, + { method: "GET", signal: input.signal }, + ); + const status = readVideoStatus(payload); + return status.video ? { ...status, video: { ...status.video, url: resolveMediaURL(input.publicApiBaseURL, status.video.url) } } : status; +} + +async function publicApiRequest(publicApiBaseURL: string, apiKey: string, path: string, options: RequestOptions): Promise { + const baseURL = createPublicApiBaseURL(publicApiBaseURL); + if (!baseURL) throw new CreativeApiError(0, "The public API base URL is not configured", "invalid_base_url"); + const headers = new Headers({ Accept: "application/json", Authorization: `Bearer ${apiKey}` }); + let body: string | undefined; + if (options.body) { + headers.set("Content-Type", "application/json"); + body = JSON.stringify(options.body); + } + const response = await fetch(`${baseURL}${path}`, { + method: options.method ?? "GET", + headers, + body, + signal: options.signal, + }); + const responseText = await response.text(); + let payload: unknown = null; + if (responseText) { + try { + payload = JSON.parse(responseText); + } catch { + payload = null; + } + } + if (!response.ok) { + const error = readError(payload); + const fallback = responseText.trim() || response.statusText || `HTTP ${response.status}`; + throw new CreativeApiError(response.status, error.message ?? fallback, error.code); + } + if (payload === null) throw new CreativeApiError(response.status, "The API returned a non-JSON response", "invalid_response"); + return payload; +} + +function resolveMediaURL(publicApiBaseURL: string, value: string): string { + const url = value.trim(); + if (!url || url.startsWith("data:") || url.startsWith("blob:")) return url; + try { + const baseURL = publicApiBaseURL.replace(/\/+$/, ""); + const relativeBaseURL = url.startsWith("/") + ? `${new URL(baseURL).origin}/` + : `${baseURL}/`; + return new URL(url, relativeBaseURL).toString(); + } catch { + return url; + } +} diff --git a/frontend/src/features/creative-console/creative-console-page.tsx b/frontend/src/features/creative-console/creative-console-page.tsx new file mode 100644 index 00000000..105fe7a3 --- /dev/null +++ b/frontend/src/features/creative-console/creative-console-page.tsx @@ -0,0 +1,530 @@ +import { useMutation, useQuery } from "@tanstack/react-query"; +import { Bot, ExternalLink, ImageIcon, KeyRound, Loader2, MessageSquareText, RefreshCw, Send, Trash2, UserRound, Video } from "lucide-react"; +import { useEffect, useMemo, useRef, useState, type FormEvent, type KeyboardEvent, type ReactNode } from "react"; +import { useTranslation } from "react-i18next"; + +import { Badge } from "@/components/ui/badge"; +import { Button } from "@/components/ui/button"; +import { Input } from "@/components/ui/input"; +import { Label } from "@/components/ui/label"; +import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"; +import { Spinner } from "@/components/ui/spinner"; +import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs"; +import { Textarea } from "@/components/ui/textarea"; +import { listModels } from "@/entities/model/model-api"; +import type { ModelRouteDTO } from "@/entities/model/types"; +import { + createChatCompletion, + createVideo, + generateImage, + getVideo, + type ChatMessage, + type ImageResult, + type VideoStatus, +} from "@/features/creative-console/creative-console-api"; +import { getClientKeySecret, listClientKeys, type ClientKeyDTO } from "@/features/client-keys/client-keys-api"; +import { getSystemInfo } from "@/entities/system/system-api"; +import { PageHeader } from "@/shared/components/page-header"; +import { runtimeConfig } from "@/shared/config/runtime-config"; +import { cn } from "@/shared/lib/cn"; + +import { listAllPaginatedItems } from "./creative-console-pagination"; + +type CreativeMode = "chat" | "image" | "video"; +type ConversationMessage = ChatMessage & { id: string }; + +type SecretState = { + keyId: string; + secret: string; +}; + +type ChatRequest = { + requestMessages: ChatMessage[]; + apiKey: string; + model: string; + publicApiBaseURL: string; +}; + +const imageAspectRatios = ["1:1", "16:9", "9:16", "4:3", "3:4", "3:2", "2:3"] as const; +const videoAspectRatios = ["1:1", "16:9", "9:16", "4:3", "3:4", "3:2", "2:3"] as const; +const imageResolutions = ["1k", "2k"] as const; +const videoResolutions = ["480p", "720p", "1080p"] as const; + +export function CreativeConsolePage() { + const { t } = useTranslation(); + const [mode, setMode] = useState("chat"); + const [selectedKeyId, setSelectedKeyId] = useState(""); + const [secretState, setSecretState] = useState(null); + const [keyError, setKeyError] = useState(""); + const [selectedModels, setSelectedModels] = useState>({ chat: "", image: "", video: "" }); + + const keysQuery = useQuery({ + queryKey: ["creative-console", "client-keys"], + queryFn: () => listAllPaginatedItems((page, pageSize) => listClientKeys({ page, pageSize, status: "active" })), + staleTime: 30_000, + }); + const modelsQuery = useQuery({ + queryKey: ["creative-console", "models"], + queryFn: () => listAllPaginatedItems((page, pageSize) => listModels({ page, pageSize, status: "enabled" })), + staleTime: 30_000, + }); + const systemQuery = useQuery({ + queryKey: ["system-info"], + queryFn: getSystemInfo, + staleTime: Number.POSITIVE_INFINITY, + retry: 1, + }); + + const activeKeys = useMemo(() => (keysQuery.data ?? []).filter(isUsableKey), [keysQuery.data]); + const effectiveKeyId = activeKeys.some((key) => key.id === selectedKeyId) ? selectedKeyId : activeKeys[0]?.id ?? ""; + const selectedKey = activeKeys.find((key) => key.id === effectiveKeyId); + const availableModels = useMemo(() => (modelsQuery.data ?? []).filter((model) => model.enabled && model.available), [modelsQuery.data]); + const permittedModels = useMemo(() => { + if (!selectedKey || selectedKey.allowedModelIds.length === 0) return availableModels; + const allowedModelIds = new Set(selectedKey.allowedModelIds); + return availableModels.filter((model) => allowedModelIds.has(model.id)); + }, [availableModels, selectedKey]); + const modelGroups = useMemo(() => ({ + chat: permittedModels.filter((model) => model.capability === "chat" || model.capability === "responses"), + image: permittedModels.filter((model) => model.capability === "image"), + video: permittedModels.filter((model) => model.capability === "video"), + }), [permittedModels]); + const effectiveModels = useMemo>(() => ({ + chat: modelGroups.chat.some((model) => model.publicId === selectedModels.chat) ? selectedModels.chat : modelGroups.chat[0]?.publicId ?? "", + image: modelGroups.image.some((model) => model.publicId === selectedModels.image) ? selectedModels.image : modelGroups.image[0]?.publicId ?? "", + video: modelGroups.video.some((model) => model.publicId === selectedModels.video) ? selectedModels.video : modelGroups.video[0]?.publicId ?? "", + }), [modelGroups, selectedModels]); + + const secretMutation = useMutation({ + mutationFn: (id: string) => getClientKeySecret(id), + onSuccess: ({ secret }, id) => { + setSecretState({ keyId: id, secret }); + setKeyError(""); + }, + onError: (error) => setKeyError(error instanceof Error ? error.message : t("creativeConsole.errors.keyUnavailable")), + }); + + const publicApiBaseURL = systemQuery.data?.publicApiBaseURL || runtimeConfig.publicApiBaseUrl; + const apiKey = secretState?.keyId === effectiveKeyId ? secretState.secret : ""; + + const sharedProps: CreativePanelProps = { + publicApiBaseURL, + apiKey, + model: effectiveModels[mode], + modelOptions: modelGroups[mode], + onModelChange: (model) => setSelectedModels((current) => ({ ...current, [mode]: model })), + }; + + function changeKey(id: string): void { + setSelectedKeyId(id); + setSecretState(null); + setKeyError(""); + } + + function unlockKey(): void { + if (!effectiveKeyId || secretMutation.isPending) return; + secretMutation.mutate(effectiveKeyId); + } + + return ( +
+ + +
+
+ + + +
+ + + {apiKey ? t("creativeConsole.keyReady") : t("creativeConsole.keyLocked")} + + +
+
+ {keysQuery.isError ? void keysQuery.refetch()} /> : null} + {!keysQuery.isPending && !keysQuery.isError && activeKeys.length === 0 ? : null} + {keyError ? : null} +

{t("creativeConsole.keyNotice")}

+
+ + setMode(value as CreativeMode)}> + + {t("creativeConsole.modes.chat")} + {t("creativeConsole.modes.image")} + + + + + {modelsQuery.isError ? void modelsQuery.refetch()} /> : null} + {mode === "chat" ? : null} + {mode === "image" ? : null} + {mode === "video" ? : null} +
+ ); +} + +type CreativePanelProps = { + publicApiBaseURL: string; + apiKey: string; + model: string; + modelOptions: ModelRouteDTO[]; + onModelChange: (model: string) => void; +}; + +function ChatPanel({ publicApiBaseURL, apiKey, model, modelOptions, onModelChange }: CreativePanelProps) { + const { t } = useTranslation(); + const [systemPrompt, setSystemPrompt] = useState(""); + const [prompt, setPrompt] = useState(""); + const [messages, setMessages] = useState([]); + const listEndRef = useRef(null); + + const mutation = useMutation({ + mutationFn: (request: ChatRequest) => createChatCompletion({ + publicApiBaseURL: request.publicApiBaseURL, + apiKey: request.apiKey, + model: request.model, + messages: request.requestMessages, + }), + onSuccess: (content, request) => setMessages([ + ...messagesFromRequest(request.requestMessages), + { id: crypto.randomUUID(), role: "assistant", content }, + ]), + }); + + useEffect(() => { + listEndRef.current?.scrollIntoView({ block: "nearest" }); + }, [messages]); + + function submit(event?: FormEvent): void { + event?.preventDefault(); + const userText = prompt.trim(); + if (!apiKey || !model || !userText || mutation.isPending) return; + const userMessage: ConversationMessage = { id: crypto.randomUUID(), role: "user", content: userText }; + const requestMessages: ChatMessage[] = [ + ...(systemPrompt.trim() ? [{ role: "system" as const, content: systemPrompt.trim() }] : []), + ...messages.map(({ role, content }) => ({ role, content })), + { role: "user", content: userText }, + ]; + setMessages((current) => [...current, userMessage]); + setPrompt(""); + mutation.reset(); + mutation.mutate({ requestMessages, apiKey, model, publicApiBaseURL }); + } + + function handlePromptKeyDown(event: KeyboardEvent): void { + if (event.key === "Enter" && !event.shiftKey) { + event.preventDefault(); + submit(); + } + } + + return ( +
+ +
+ + +