feat(frontend): add chat image and video creative console

This commit is contained in:
TizenryA committed 2026-07-15 10:40:50 +00:00
1 parent 90ec921610
commit abdba88a66
12 files changed
+1302 -4

No files matched your search

+1
View File
@@ -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": {
+2 -1
View File
@@ -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 },
+5
View File
@@ -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 <DeferredPage page={ClientKeysPage} />;
}
export function DeferredCreativeConsolePage() {
return <DeferredPage page={CreativeConsolePage} />;
}
export function DeferredRequestAuditsPage() {
return <DeferredPage page={RequestAuditsPage} />;
}
+2 -1
View File
@@ -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: <DeferredDashboardPage /> },
{ path: "/accounts", element: <DeferredAccountsPage /> },
{ path: "/models", element: <DeferredModelsPage /> },
{ path: "/creative-console", element: <DeferredCreativeConsolePage /> },
{ path: "/client-keys", element: <DeferredClientKeysPage /> },
{ path: "/gallery", element: <DeferredGalleryPage /> },
{ path: "/video-gallery", element: <DeferredVideoGalleryPage /> },
@@ -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);
});
@@ -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<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
export const creativeApiInternals = { createPublicApiBaseURL, readChatText, readImages, readVideoRequestID, readVideoStatus, readError };
@@ -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<T>(handler: (input: string, init?: RequestInit) => Response | Promise<Response>, run: () => Promise<T>): Promise<T> {
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<string, unknown> {
const body = call.init?.body;
assert.equal(typeof body, "string");
return JSON.parse(body as string) as Record<string, unknown>;
}
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;
},
);
});
});
@@ -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<string, unknown>;
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<string> {
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<ImageResult[]> {
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<string> {
const body: Record<string, unknown> = {
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<VideoStatus> {
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<unknown> {
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;
}
}
@@ -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<CreativeMode>("chat");
const [selectedKeyId, setSelectedKeyId] = useState("");
const [secretState, setSecretState] = useState<SecretState | null>(null);
const [keyError, setKeyError] = useState("");
const [selectedModels, setSelectedModels] = useState<Record<CreativeMode, string>>({ 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<Record<CreativeMode, string>>(() => ({
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 (
<div className="space-y-8">
<PageHeader title={t("creativeConsole.title")} description={t("creativeConsole.description")} />
<section className="space-y-4 rounded-lg bg-card p-4 sm:p-5">
<div className="flex flex-col gap-4 lg:flex-row lg:items-end">
<Field className="min-w-0 flex-1" label={t("creativeConsole.clientKey")} htmlFor="creative-key">
<Select value={effectiveKeyId} onValueChange={changeKey} disabled={keysQuery.isPending || activeKeys.length === 0}>
<SelectTrigger id="creative-key" aria-label={t("creativeConsole.clientKey")}>
<SelectValue placeholder={keysQuery.isPending ? t("common.loading") : t("creativeConsole.selectKey")} />
</SelectTrigger>
<SelectContent>
{activeKeys.map((key) => <SelectItem key={key.id} value={key.id}>{key.name} · {key.prefix}</SelectItem>)}
</SelectContent>
</Select>
</Field>
<div className="flex flex-wrap items-center gap-2">
<Badge variant={apiKey ? "default" : "secondary"}>
<KeyRound />
{apiKey ? t("creativeConsole.keyReady") : t("creativeConsole.keyLocked")}
</Badge>
<Button type="button" variant="secondary" size="sm" onClick={unlockKey} disabled={!effectiveKeyId || Boolean(apiKey) || secretMutation.isPending}>
{secretMutation.isPending ? <Spinner /> : <KeyRound />}
{apiKey ? t("creativeConsole.keyLoaded") : t("creativeConsole.loadKey")}
</Button>
</div>
</div>
{keysQuery.isError ? <RetryableError message={keysQuery.error.message} onRetry={() => void keysQuery.refetch()} /> : null}
{!keysQuery.isPending && !keysQuery.isError && activeKeys.length === 0 ? <InlineError message={t("creativeConsole.errors.noKeys")} /> : null}
{keyError ? <InlineError message={keyError} /> : null}
<p className="text-xs leading-5 text-muted-foreground">{t("creativeConsole.keyNotice")}</p>
</section>
<Tabs value={mode} onValueChange={(value) => setMode(value as CreativeMode)}>
<TabsList className="h-auto w-full rounded-md bg-muted p-0.5 sm:w-fit">
<TabsTrigger className="flex-1 rounded-sm data-[state=active]:bg-background data-[state=active]:shadow-sm sm:flex-none" value="chat"><MessageSquareText />{t("creativeConsole.modes.chat")}</TabsTrigger>
<TabsTrigger className="flex-1 rounded-sm data-[state=active]:bg-background data-[state=active]:shadow-sm sm:flex-none" value="image"><ImageIcon />{t("creativeConsole.modes.image")}</TabsTrigger>
<TabsTrigger className="flex-1 rounded-sm data-[state=active]:bg-background data-[state=active]:shadow-sm sm:flex-none" value="video"><Video />{t("creativeConsole.modes.video")}</TabsTrigger>
</TabsList>
</Tabs>
{modelsQuery.isError ? <RetryableError message={modelsQuery.error.message} onRetry={() => void modelsQuery.refetch()} /> : null}
{mode === "chat" ? <ChatPanel {...sharedProps} /> : null}
{mode === "image" ? <ImagePanel {...sharedProps} /> : null}
{mode === "video" ? <VideoPanel {...sharedProps} /> : null}
</div>
);
}
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<ConversationMessage[]>([]);
const listEndRef = useRef<HTMLDivElement>(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<HTMLTextAreaElement>): void {
if (event.key === "Enter" && !event.shiftKey) {
event.preventDefault();
submit();
}
}
return (
<div className="grid min-w-0 gap-4 lg:grid-cols-[minmax(0,0.82fr)_minmax(0,1.18fr)]">
<Panel title={t("creativeConsole.settings")}>
<form className="space-y-4" onSubmit={submit}>
<ModelField value={model} models={modelOptions} onChange={onModelChange} />
<Field label={t("creativeConsole.systemPrompt")} htmlFor="chat-system">
<Textarea id="chat-system" value={systemPrompt} onChange={(event) => setSystemPrompt(event.target.value)} placeholder={t("creativeConsole.systemPromptPlaceholder")} className="min-h-24" />
</Field>
<Field label={t("creativeConsole.prompt")} htmlFor="chat-prompt">
<Textarea id="chat-prompt" value={prompt} onChange={(event) => setPrompt(event.target.value)} onKeyDown={handlePromptKeyDown} placeholder={t("creativeConsole.chatPlaceholder")} className="min-h-36" />
</Field>
<div className="flex flex-col-reverse gap-2 sm:flex-row sm:items-center sm:justify-between">
<span className="text-[11px] text-muted-foreground">{t("creativeConsole.enterHint")}</span>
<Button type="submit" className="w-full sm:w-auto" disabled={!apiKey || !model || !prompt.trim() || mutation.isPending}>
{mutation.isPending ? <Loader2 className="animate-spin" /> : <Send />}
{t("creativeConsole.send")}
</Button>
</div>
{mutation.isError ? <InlineError message={mutation.error.message} /> : null}
</form>
</Panel>
<Panel title={t("creativeConsole.conversation")} actions={messages.length > 0 ? (
<Button type="button" variant="ghost" size="sm" onClick={() => setMessages([])} disabled={mutation.isPending}>
<Trash2 />{t("creativeConsole.clear")}
</Button>
) : undefined}>
<div className="max-h-[65vh] min-h-96 space-y-3 overflow-y-auto pr-1" aria-live="polite">
{messages.length === 0 && !mutation.isPending ? <EmptyResult icon={<MessageSquareText />} text={t("creativeConsole.emptyChat")} /> : null}
{messages.map((message) => <ChatBubble key={message.id} message={message} />)}
{mutation.isPending ? <ChatBubble message={{ id: "pending", role: "assistant", content: t("creativeConsole.thinking") }} loading /> : null}
<div ref={listEndRef} />
</div>
</Panel>
</div>
);
}
function ImagePanel({ publicApiBaseURL, apiKey, model, modelOptions, onModelChange }: CreativePanelProps) {
const { t } = useTranslation();
const [prompt, setPrompt] = useState("");
const [count, setCount] = useState("1");
const [aspectRatio, setAspectRatio] = useState("1:1");
const [resolution, setResolution] = useState("1k");
const [images, setImages] = useState<ImageResult[]>([]);
const mutation = useMutation({
mutationFn: () => generateImage({ publicApiBaseURL, apiKey, model, prompt: prompt.trim(), count: Number(count), aspectRatio, resolution }),
onSuccess: setImages,
});
function submit(event: FormEvent): void {
event.preventDefault();
if (!apiKey || !model || !prompt.trim() || mutation.isPending) return;
mutation.reset();
mutation.mutate();
}
return (
<div className="grid min-w-0 gap-4 lg:grid-cols-[minmax(0,0.82fr)_minmax(0,1.18fr)]">
<Panel title={t("creativeConsole.settings")}>
<form className="space-y-4" onSubmit={submit}>
<ModelField value={model} models={modelOptions} onChange={onModelChange} />
<Field label={t("creativeConsole.prompt")} htmlFor="image-prompt">
<Textarea id="image-prompt" value={prompt} onChange={(event) => setPrompt(event.target.value)} placeholder={t("creativeConsole.imagePlaceholder")} className="min-h-40" />
</Field>
<div className="grid grid-cols-1 gap-4 sm:grid-cols-3">
<SelectField id="image-count" label={t("creativeConsole.count")} value={count} options={["1", "2", "3", "4"]} onChange={setCount} />
<SelectField id="image-aspect" label={t("creativeConsole.aspectRatio")} value={aspectRatio} options={imageAspectRatios} onChange={setAspectRatio} />
<SelectField id="image-resolution" label={t("creativeConsole.resolution")} value={resolution} options={imageResolutions} onChange={setResolution} />
</div>
<Button type="submit" className="w-full sm:w-auto" disabled={!apiKey || !model || !prompt.trim() || mutation.isPending}>
{mutation.isPending ? <Loader2 className="animate-spin" /> : <ImageIcon />}
{t("creativeConsole.generateImage")}
</Button>
{mutation.isError ? <InlineError message={mutation.error.message} /> : null}
</form>
</Panel>
<Panel title={t("creativeConsole.result")}>
{images.length === 0 && !mutation.isPending ? <EmptyResult icon={<ImageIcon />} text={t("creativeConsole.emptyImage")} /> : null}
{mutation.isPending ? <LoadingResult text={t("creativeConsole.generatingImage")} /> : null}
{images.length > 0 ? (
<div className="grid grid-cols-1 gap-3 md:grid-cols-2" aria-live="polite">
{images.map((image, index) => (
<figure key={`${image.url}-${index}`} className="min-w-0 border bg-secondary/20 p-2">
<img src={image.url} alt={t("creativeConsole.generatedImageAlt", { index: index + 1 })} className="aspect-square w-full bg-muted object-contain" loading="lazy" />
<figcaption className="mt-2 flex min-w-0 items-center justify-between gap-2">
<span className="truncate text-xs text-muted-foreground">{t("creativeConsole.imageNumber", { index: index + 1 })}</span>
<Button variant="ghost" size="sm" asChild>
<a href={image.url} target="_blank" rel="noreferrer"><ExternalLink />{t("creativeConsole.open")}</a>
</Button>
</figcaption>
</figure>
))}
</div>
) : null}
</Panel>
</div>
);
}
function VideoPanel({ publicApiBaseURL, apiKey, model, modelOptions, onModelChange }: CreativePanelProps) {
const { t } = useTranslation();
const [prompt, setPrompt] = useState("");
const [imageURL, setImageURL] = useState("");
const [duration, setDuration] = useState("8");
const [aspectRatio, setAspectRatio] = useState("16:9");
const [resolution, setResolution] = useState("720p");
const [job, setJob] = useState<{ requestId: string; apiKey: string; publicApiBaseURL: string } | null>(null);
const createMutation = useMutation({
mutationFn: () => createVideo({
publicApiBaseURL,
apiKey,
model,
prompt: prompt.trim(),
imageURL: imageURL.trim() || undefined,
duration: Number(duration),
aspectRatio,
resolution,
}),
onSuccess: (requestId) => setJob({ requestId, apiKey, publicApiBaseURL }),
});
const statusQuery = useQuery({
queryKey: ["creative-console", "video", job?.requestId, job?.publicApiBaseURL],
queryFn: ({ signal }) => getVideo({ publicApiBaseURL: job!.publicApiBaseURL, apiKey: job!.apiKey, requestId: job!.requestId, signal }),
enabled: Boolean(job),
refetchInterval: (query) => query.state.data?.status === "pending" ? 3_000 : false,
retry: 2,
});
function submit(event: FormEvent): void {
event.preventDefault();
if (!apiKey || !model || (!prompt.trim() && !imageURL.trim()) || createMutation.isPending) return;
setJob(null);
createMutation.reset();
createMutation.mutate();
}
return (
<div className="grid min-w-0 gap-4 lg:grid-cols-[minmax(0,0.82fr)_minmax(0,1.18fr)]">
<Panel title={t("creativeConsole.settings")}>
<form className="space-y-4" onSubmit={submit}>
<ModelField value={model} models={modelOptions} onChange={onModelChange} />
<Field label={t("creativeConsole.prompt")} htmlFor="video-prompt">
<Textarea id="video-prompt" value={prompt} onChange={(event) => setPrompt(event.target.value)} placeholder={t("creativeConsole.videoPlaceholder")} className="min-h-32" />
</Field>
<Field label={t("creativeConsole.referenceImage")} htmlFor="video-image">
<Input id="video-image" type="url" value={imageURL} onChange={(event) => setImageURL(event.target.value)} placeholder="https://example.com/image.png" />
</Field>
<p className="text-[11px] leading-5 text-muted-foreground">{t("creativeConsole.videoInputHint")}</p>
<div className="grid grid-cols-1 gap-4 sm:grid-cols-3">
<Field label={t("creativeConsole.duration")} htmlFor="video-duration">
<Input id="video-duration" type="number" min={1} max={15} step={1} value={duration} onChange={(event) => setDuration(event.target.value)} />
</Field>
<SelectField id="video-aspect" label={t("creativeConsole.aspectRatio")} value={aspectRatio} options={videoAspectRatios} onChange={setAspectRatio} />
<SelectField id="video-resolution" label={t("creativeConsole.resolution")} value={resolution} options={videoResolutions} onChange={setResolution} />
</div>
<Button type="submit" className="w-full sm:w-auto" disabled={!apiKey || !model || (!prompt.trim() && !imageURL.trim()) || !validDuration(duration) || createMutation.isPending}>
{createMutation.isPending ? <Loader2 className="animate-spin" /> : <Video />}
{t("creativeConsole.generateVideo")}
</Button>
{createMutation.isError ? <InlineError message={createMutation.error.message} /> : null}
</form>
</Panel>
<Panel title={t("creativeConsole.result")}>
{!job && !createMutation.isPending ? <EmptyResult icon={<Video />} text={t("creativeConsole.emptyVideo")} /> : null}
{createMutation.isPending ? <LoadingResult text={t("creativeConsole.submittingVideo")} /> : null}
{job ? <VideoResult requestId={job.requestId} status={statusQuery.data} loading={statusQuery.isPending || statusQuery.isFetching} error={statusQuery.isError ? statusQuery.error.message : ""} onRetry={() => void statusQuery.refetch()} /> : null}
</Panel>
</div>
);
}
function VideoResult({ requestId, status, loading, error, onRetry }: { requestId: string; status?: VideoStatus; loading: boolean; error: string; onRetry: () => void }) {
const { t } = useTranslation();
const progress = status?.progress ?? 0;
return (
<div className="space-y-4" aria-live="polite">
<div className="grid gap-3 sm:grid-cols-2">
<MetaItem label={t("creativeConsole.requestId")} value={requestId} mono />
<MetaItem label={t("creativeConsole.status")} value={status ? t(`creativeConsole.videoStatus.${status.status}`) : t("common.loading")} />
</div>
<div className="space-y-2">
<div className="flex items-center justify-between text-xs"><span className="text-muted-foreground">{t("creativeConsole.progress")}</span><span className="tabular-nums">{progress}%</span></div>
<div className="h-2 overflow-hidden bg-muted"><div className="h-full bg-primary transition-[width]" style={{ width: `${progress}%` }} /></div>
</div>
{loading && status?.status !== "done" && status?.status !== "failed" ? <div className="flex items-center gap-2 text-xs text-muted-foreground"><Spinner />{t("creativeConsole.pollingVideo")}</div> : null}
{error ? <RetryableError message={error} onRetry={onRetry} /> : null}
{status?.status === "failed" ? <InlineError message={status.error?.message || t("creativeConsole.errors.videoFailed")} /> : null}
{status?.status === "done" && status.video ? (
<div className="space-y-3">
<video src={status.video.url} controls preload="metadata" className="max-h-[65vh] w-full bg-black" />
<div className="flex flex-wrap items-center justify-between gap-2">
<span className="text-xs text-muted-foreground">{status.video.duration ? t("creativeConsole.videoDuration", { count: status.video.duration }) : ""}</span>
<Button variant="secondary" size="sm" asChild><a href={status.video.url} target="_blank" rel="noreferrer"><ExternalLink />{t("creativeConsole.openVideo")}</a></Button>
</div>
</div>
) : null}
</div>
);
}
function ModelField({ value, models, onChange }: { value: string; models: ModelRouteDTO[]; onChange: (model: string) => void }) {
const { t } = useTranslation();
return (
<Field label={t("creativeConsole.model")} htmlFor="creative-model">
<Select value={value} onValueChange={onChange} disabled={models.length === 0}>
<SelectTrigger id="creative-model" aria-label={t("creativeConsole.model")}>
<SelectValue placeholder={models.length === 0 ? t("creativeConsole.noModels") : t("creativeConsole.selectModel")} />
</SelectTrigger>
<SelectContent>{models.map((item) => <SelectItem key={item.id} value={item.publicId}>{item.publicId}</SelectItem>)}</SelectContent>
</Select>
{models.length === 0 ? <p className="text-[11px] leading-5 text-destructive">{t("creativeConsole.errors.noModels")}</p> : null}
</Field>
);
}
function SelectField({ id, label, value, options, onChange }: { id: string; label: string; value: string; options: readonly string[]; onChange: (value: string) => void }) {
return (
<Field label={label} htmlFor={id}>
<Select value={value} onValueChange={onChange}>
<SelectTrigger id={id} aria-label={label}><SelectValue /></SelectTrigger>
<SelectContent>{options.map((option) => <SelectItem key={option} value={option}>{option}</SelectItem>)}</SelectContent>
</Select>
</Field>
);
}
function Panel({ title, actions, children }: { title: string; actions?: ReactNode; children: ReactNode }) {
return (
<section className="min-w-0 rounded-lg bg-card p-4 sm:p-5">
<div className="mb-5 flex min-h-8 items-center justify-between gap-3 border-b pb-3"><h2 className="text-sm font-medium">{title}</h2>{actions}</div>
{children}
</section>
);
}
function Field({ label, htmlFor, className, children }: { label: string; htmlFor: string; className?: string; children: ReactNode }) {
return <div className={cn("space-y-2", className)}><Label htmlFor={htmlFor}>{label}</Label>{children}</div>;
}
function messagesFromRequest(messages: ChatMessage[]): ConversationMessage[] {
return messages
.filter((message) => message.role !== "system")
.map((message) => ({ ...message, id: crypto.randomUUID() }));
}
function ChatBubble({ message, loading = false }: { message: ConversationMessage; loading?: boolean }) {
const isUser = message.role === "user";
return (
<div className={cn("flex gap-3 rounded-md border p-3", isUser ? "bg-secondary/25" : "bg-background")}>
<div className="flex size-7 shrink-0 items-center justify-center rounded-sm border bg-card">{isUser ? <UserRound className="size-4" /> : <Bot className="size-4" />}</div>
<div className="min-w-0 flex-1 whitespace-pre-wrap break-words text-sm leading-6">{loading ? <span className="flex items-center gap-2 text-muted-foreground"><Spinner />{message.content}</span> : message.content}</div>
</div>
);
}
function EmptyResult({ icon, text }: { icon: ReactNode; text: string }) {
return <div className="flex min-h-80 flex-col items-center justify-center gap-3 rounded-md border border-dashed px-6 text-center text-sm text-muted-foreground [&_svg]:size-6">{icon}<span>{text}</span></div>;
}
function LoadingResult({ text }: { text: string }) {
return <div className="flex min-h-80 items-center justify-center gap-3 rounded-md border border-dashed text-sm text-muted-foreground"><Spinner className="size-5" />{text}</div>;
}
function InlineError({ message }: { message: string }) {
return <div role="alert" className="rounded-md border border-destructive/35 bg-destructive/5 px-3 py-2 text-xs leading-5 text-destructive">{message}</div>;
}
function RetryableError({ message, onRetry }: { message: string; onRetry: () => void }) {
const { t } = useTranslation();
return (
<div role="alert" className="flex flex-col gap-2 rounded-md border border-destructive/35 bg-destructive/5 px-3 py-2 text-xs leading-5 text-destructive sm:flex-row sm:items-center sm:justify-between">
<span>{message}</span>
<Button type="button" variant="ghost" size="sm" className="self-start text-destructive hover:text-destructive sm:self-auto" onClick={onRetry}>
<RefreshCw />{t("common.retry")}
</Button>
</div>
);
}
function MetaItem({ label, value, mono = false }: { label: string; value: string; mono?: boolean }) {
return <div className="min-w-0 rounded-md border bg-secondary/20 p-3"><div className="mb-1 text-[11px] text-muted-foreground">{label}</div><div className={cn("truncate text-xs", mono && "font-mono")} title={value}>{value}</div></div>;
}
function isUsableKey(key: ClientKeyDTO): boolean {
if (!key.enabled) return false;
return !key.expiresAt || new Date(key.expiresAt).getTime() > Date.now();
}
function validDuration(value: string): boolean {
const duration = Number(value);
return Number.isInteger(duration) && duration >= 1 && duration <= 15;
}
@@ -0,0 +1,45 @@
export type PaginatedPage<T> = {
items: T[];
page: number;
pageSize: number;
total: number;
};
type PaginationOptions = {
pageSize?: number;
maxPages?: number;
};
const maxPageSize = 100;
const defaultMaxPages = 50;
export async function listAllPaginatedItems<T>(
loadPage: (page: number, pageSize: number) => Promise<PaginatedPage<T>>,
options: PaginationOptions = {},
): Promise<T[]> {
const pageSize = boundedInteger(options.pageSize ?? maxPageSize, 1, maxPageSize);
const maxPages = boundedInteger(options.maxPages ?? defaultMaxPages, 1, defaultMaxPages);
const items: T[] = [];
let expectedTotal = Number.POSITIVE_INFINITY;
for (let page = 1; page <= maxPages; page += 1) {
const result = await loadPage(page, pageSize);
expectedTotal = normalizeTotal(result.total, expectedTotal);
items.push(...result.items);
if (items.length >= expectedTotal) return items.slice(0, expectedTotal);
if (result.items.length < pageSize) return items;
}
return Number.isFinite(expectedTotal) ? items.slice(0, expectedTotal) : items;
}
function boundedInteger(value: number, min: number, max: number): number {
if (!Number.isFinite(value)) return max;
return Math.min(max, Math.max(min, Math.floor(value)));
}
function normalizeTotal(value: number, fallback: number): number {
if (!Number.isFinite(value)) return fallback;
return Math.max(0, Math.floor(value));
}
+116 -1
View File
@@ -102,12 +102,70 @@ const resources = {
accounts: "账号",
models: "模型",
clientKeys: "密钥",
creativeConsole: "创作控制台",
gallery: "图库",
videoGallery: "视频库",
audits: "请求审计",
docs: "文档",
settings: "设置",
},
creativeConsole: {
title: "创作控制台",
description: "使用已创建的客户端密钥直接测试聊天、图片和视频生成。",
clientKey: "客户端密钥",
selectKey: "选择客户端密钥",
keyReady: "密钥就绪",
keyLocked: "密钥未加载",
keyLoaded: "已加载",
loadKey: "加载密钥",
keyNotice: "密钥仅在当前浏览器会话中用于请求公开 API,不会写入页面持久化存储。",
modes: { chat: "聊天", image: "图片", video: "视频" },
settings: "参数设置",
model: "模型",
selectModel: "选择模型",
noModels: "暂无可用模型",
systemPrompt: "系统提示词",
systemPromptPlaceholder: "可选:设定助手角色、语气或输出格式。",
prompt: "提示词",
chatPlaceholder: "输入要发送给模型的内容。",
imagePlaceholder: "描述要生成的画面、主体、风格和细节。",
videoPlaceholder: "描述视频画面、动作、镜头和节奏。",
enterHint: "按 Enter 发送,Shift + Enter 换行",
send: "发送",
conversation: "对话",
clear: "清空",
emptyChat: "发送一条消息后会在这里显示对话。",
thinking: "模型正在回复...",
count: "数量",
aspectRatio: "宽高比",
resolution: "分辨率",
generateImage: "生成图片",
result: "结果",
emptyImage: "生成图片后会在这里显示结果。",
generatingImage: "正在生成图片...",
generatedImageAlt: "生成图片 {{index}}",
imageNumber: "图片 {{index}}",
open: "打开",
referenceImage: "参考图片 URL",
videoInputHint: "提示词和参考图片至少填写一项;参考图片会作为首帧或生成依据。",
duration: "时长(秒)",
generateVideo: "生成视频",
emptyVideo: "提交视频任务后会在这里显示进度和结果。",
submittingVideo: "正在提交视频任务...",
requestId: "请求 ID",
status: "状态",
progress: "进度",
pollingVideo: "正在轮询视频状态...",
videoDuration: "{{count}} 秒",
openVideo: "打开视频",
videoStatus: { pending: "生成中", done: "已完成", failed: "失败" },
errors: {
keyUnavailable: "无法读取客户端密钥",
noKeys: "没有可用的已启用客户端密钥,请先创建或启用密钥。",
noModels: "当前模式没有可用模型,请确认模型已启用且账号池可服务。",
videoFailed: "视频生成失败",
},
},
media: {
images: {
title: "图库",
@@ -817,7 +875,64 @@ const resources = {
expiryUnknown: "Credential expiry is unknown",
},
common: { actions: "Actions", cancel: "Cancel", close: "Close", copy: "Copy", copied: "Copied", copyFailed: "Copy failed", create: "Create", delete: "Delete", disabled: "Disabled", disable: "Disable", edit: "Edit", enabled: "Enabled", enable: "Enable", loading: "Loading", importingProgress: "Importing, completed {{completed}} / {{total}}", syncingProgress: "Syncing initial data, completed {{completed}} / {{total}}", noData: "No data", pageOf: "Page {{page}}/{{pages}}", perPage: "Per page", rows: "rows", firstPage: "First page", lastPage: "Last page", previousPage: "Previous page", nextPage: "Next page", selectedCount: "{{count}} selected", selectPage: "Select this page", selectItem: "Select {{name}}", refresh: "Refresh", retry: "Retry", filter: "Filters", all: "All", clearFilters: "Clear filters", save: "Save", reset: "Reset", sortAscending: "Sort {{column}} ascending", sortDescending: "Sort {{column}} descending" },
nav: { dashboard: "Dashboard", accounts: "Accounts", models: "Models", clientKeys: "Client keys", gallery: "Gallery", videoGallery: "Video Gallery", audits: "Request audits", docs: "Documentation", settings: "Settings" },
nav: { dashboard: "Dashboard", accounts: "Accounts", models: "Models", clientKeys: "Client keys", creativeConsole: "Creative console", gallery: "Gallery", videoGallery: "Video Gallery", audits: "Request audits", docs: "Documentation", settings: "Settings" },
creativeConsole: {
title: "Creative console",
description: "Use an existing client key to test chat, image, and video generation directly.",
clientKey: "Client key",
selectKey: "Select a client key",
keyReady: "Key ready",
keyLocked: "Key locked",
keyLoaded: "Loaded",
loadKey: "Load key",
keyNotice: "The key is used only in the current browser session for public API requests and is not written to persistent page storage.",
modes: { chat: "Chat", image: "Image", video: "Video" },
settings: "Settings",
model: "Model",
selectModel: "Select a model",
noModels: "No available models",
systemPrompt: "System prompt",
systemPromptPlaceholder: "Optional: set the assistant role, tone, or output format.",
prompt: "Prompt",
chatPlaceholder: "Enter the message to send to the model.",
imagePlaceholder: "Describe the scene, subject, style, and details to generate.",
videoPlaceholder: "Describe the video scene, motion, camera, and pacing.",
enterHint: "Press Enter to send, Shift + Enter for a new line",
send: "Send",
conversation: "Conversation",
clear: "Clear",
emptyChat: "Send a message to show the conversation here.",
thinking: "The model is replying...",
count: "Count",
aspectRatio: "Aspect ratio",
resolution: "Resolution",
generateImage: "Generate image",
result: "Result",
emptyImage: "Generated images will appear here.",
generatingImage: "Generating images...",
generatedImageAlt: "Generated image {{index}}",
imageNumber: "Image {{index}}",
open: "Open",
referenceImage: "Reference image URL",
videoInputHint: "Provide at least a prompt or a reference image. The reference image is used as the first frame or generation source.",
duration: "Duration (seconds)",
generateVideo: "Generate video",
emptyVideo: "Submit a video job to show progress and results here.",
submittingVideo: "Submitting video job...",
requestId: "Request ID",
status: "Status",
progress: "Progress",
pollingVideo: "Polling video status...",
videoDuration: "{{count}} seconds",
openVideo: "Open video",
videoStatus: { pending: "Generating", done: "Done", failed: "Failed" },
errors: {
keyUnavailable: "Unable to read the client key",
noKeys: "No enabled client keys are available. Create or enable a key first.",
noModels: "No model is available for this mode. Confirm that models are enabled and the account pool can serve them.",
videoFailed: "Video generation failed",
},
},
media: { images: { title: "Gallery", description: "Browse generated image assets", search: "Search ID, type, or hash", empty: "No images", noMatches: "No matching images", sha256: "SHA256", totalImages: "Total images", totalImagesDetail: "Archived image count", totalBytes: "Storage", totalBytesDetail: "Total size of all image files", pageSummary: "Showing {{count}} / {{total}}" }, videos: { title: "Video Gallery", description: "View video generation job records", search: "Search prompt or ID", empty: "No video jobs", statusFilter: "Status filter", totalJobs: "Total jobs", queued: "Queued", inProgress: "In progress", completed: "Completed", failed: "Failed", prompt: "Prompt", model: "Model", status: "Status", progress: "Progress", spec: "Spec", owner: "Owner", createdAt: "Created", completedAt: "Completed", seconds: "{{count}} sec", pageSummary: "Showing {{count}} / {{total}}" }, videoStatus: { queued: "Queued", in_progress: "In progress", completed: "Completed", failed: "Failed" } },
auth: { title: "Admin sign in", productTitle: "Lightweight API gateway", subtitle: "Manage upstream accounts, model routes, and client access.", username: "Username", password: "Password", usernameRequired: "Enter your username", passwordRequired: "Enter your password", signIn: "Sign in", signingIn: "Signing in", signOut: "Sign out", changePassword: "Change password", currentPassword: "Current password", newPassword: "New password", passwordUpdated: "Password updated. Sign in again.", sessionUnavailable: "Unable to restore the session", sessionUnavailableDescription: "The service may be temporarily unavailable. Your session was not cleared; please retry shortly.", retrySession: "Retry" },
shell: { appearance: "Appearance", dark: "Dark", light: "Light", system: "System", language: "Language", navigation: "Navigation", openNavigation: "Open navigation" },
+3 -1
View File
@@ -14,6 +14,7 @@
"module": "ESNext",
"moduleResolution": "Bundler",
"resolveJsonModule": true,
"allowImportingTsExtensions": true,
"isolatedModules": true,
"incremental": true,
"tsBuildInfoFile": "./.cache/tsconfig.app.tsbuildinfo",
@@ -23,5 +24,6 @@
"@/*": ["./src/*"]
}
},
"include": ["src"]
"include": ["src"],
"exclude": ["src/**/*.test.mts"]
}