feat: add marked library and enhance creative console API for chat response handling

This commit is contained in:
Chenyme committed 2026-07-19 15:38:54 +08:00
1 parent 39b6175bc2
commit 269a81bc4c
5 files changed
+963 -140

No files matched your search

+1
View File
@@ -30,6 +30,7 @@
"date-fns": "^4.4.0",
"i18next": "^26.3.6",
"lucide-react": "^1.24.0",
"marked": "^18.0.6",
"next-themes": "^0.4.6",
"react": "^19.2.7",
"react-day-picker": "^10.0.1",
+10
View File
@@ -65,6 +65,9 @@ importers:
lucide-react:
specifier: ^1.24.0
version: 1.24.0(react@19.2.7)
marked:
specifier: ^18.0.6
version: 18.0.6
next-themes:
specifier: ^0.4.6
version: 0.4.6(react-dom@19.2.7(react@19.2.7))(react@19.2.7)
@@ -1514,6 +1517,11 @@ packages:
magic-string@0.30.21:
resolution: {integrity: sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==}
marked@18.0.6:
resolution: {integrity: sha512-MrV5puXBfuiy6wl6DLaq3BtIJQAJToAd5zt/ZKhRfGRAuFPALE7/4Y7jnxRQoEgK/pBgurGqLyAuRgZ2xOjr6w==}
engines: {node: '>= 20'}
hasBin: true
minimatch@10.2.5:
resolution: {integrity: sha512-MULkVLfKGYDFYejP07QOurDLLQpcjk7Fw+7jXS2R2czRQzR56yHRveU5NDJEOviH+hETZKSkIk5c+T23GjFUMg==}
engines: {node: 18 || 20 || >=22}
@@ -3187,6 +3195,8 @@ snapshots:
dependencies:
'@jridgewell/sourcemap-codec': 1.5.5
marked@18.0.6: {}
minimatch@10.2.5:
dependencies:
brace-expansion: 5.0.7
@@ -3,6 +3,24 @@ export type ChatMessage = {
content: string;
};
export type ReasoningEffort = "auto" | "none" | "low" | "medium" | "high" | "xhigh";
export type ChatToolActivity = {
id: string;
type: string;
name: string;
status: "in_progress" | "completed" | "failed";
detail: string;
};
export type ChatStreamSnapshot = {
text: string;
reasoning: string;
tools: ChatToolActivity[];
};
export type ChatResponseResult = ChatStreamSnapshot;
export type ImageResult = {
url: string;
revisedPrompt?: string;
@@ -34,20 +52,32 @@ type RequestOptions = {
signal?: AbortSignal;
};
export async function createChatCompletion(input: {
export async function createChatResponse(input: {
apiKey: string;
model: string;
messages: ChatMessage[];
promptCacheKey?: string;
reasoningEffort: ReasoningEffort;
webSearch: boolean;
xSearch: boolean;
onUpdate?: (snapshot: ChatStreamSnapshot) => void;
signal?: AbortSignal;
}): Promise<string> {
const payload = await publicApiRequest(
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;
}): Promise<ChatResponseResult> {
const body: Record<string, unknown> = {
model: input.model,
input: input.messages.map(({ role, content }) => ({ role, content })),
stream: true,
store: false,
};
if (input.promptCacheKey) body.prompt_cache_key = input.promptCacheKey;
if (input.reasoningEffort === "auto") body.reasoning = { summary: "auto" };
else if (input.reasoningEffort !== "none") body.reasoning = { effort: input.reasoningEffort, summary: "auto" };
else body.reasoning = { effort: "none" };
const tools: Array<{ type: string }> = [];
if (input.webSearch) tools.push({ type: "web_search" });
if (input.xSearch) tools.push({ type: "x_search" });
if (tools.length > 0) body.tools = tools;
return publicResponsesStream(input.apiKey, body, input.onUpdate, input.signal);
}
export async function generateImage(input: {
@@ -156,6 +186,132 @@ async function publicApiRequest(apiKey: string, path: string, options: RequestOp
return payload;
}
async function publicResponsesStream(apiKey: string, body: Record<string, unknown>, onUpdate?: (snapshot: ChatStreamSnapshot) => void, signal?: AbortSignal): Promise<ChatResponseResult> {
const response = await fetch("/v1/responses", {
method: "POST",
headers: new Headers({ Accept: "text/event-stream", Authorization: `Bearer ${apiKey}`, "Content-Type": "application/json" }),
body: JSON.stringify(body),
signal,
});
if (!response.ok) {
const responseText = await response.text();
const payload = parseJSON(responseText);
const error = readError(payload);
throw new CreativeApiError(response.status, error.message ?? (responseText.trim() || response.statusText || `HTTP ${response.status}`), error.code);
}
if (!response.headers.get("content-type")?.includes("text/event-stream")) {
const responseText = await response.text();
const payload = parseJSON(responseText);
const text = readResponseText(payload);
const reasoning = readResponseReasoning(payload);
const tools = readResponseTools(payload);
if (!text && !reasoning && tools.length === 0) throw new CreativeApiError(response.status, "The Responses API did not return any displayable output", "invalid_response");
return { text, reasoning, tools };
}
if (!response.body) throw new CreativeApiError(response.status, "The Responses API stream was empty", "invalid_response");
const reader = response.body.getReader();
const decoder = new TextDecoder();
let buffer = "";
let text = "";
let reasoning = "";
const tools = new Map<string, ChatToolActivity>();
const snapshot = (): ChatStreamSnapshot => ({ text, reasoning, tools: Array.from(tools.values()) });
const emit = () => onUpdate?.(snapshot());
const applyEnvelope = (payload: unknown) => {
const finalText = readResponseText(payload);
const finalReasoning = readResponseReasoning(payload);
const finalTools = readResponseTools(payload);
if (finalText) text = finalText;
if (finalReasoning) reasoning = finalReasoning;
for (const tool of finalTools) tools.set(tool.id, tool);
};
const consume = (block: string) => {
const data = block.split("\n").filter((line) => line.startsWith("data:")).map((line) => line.slice(5).trimStart()).join("\n");
if (!data || data === "[DONE]") return;
const payload = parseJSON(data);
if (!isRecord(payload)) return;
const type = typeof payload.type === "string" ? payload.type : "";
if (type === "response.output_text.delta" && typeof payload.delta === "string") {
text += payload.delta;
emit();
return;
}
if (type === "response.output_text.done" && typeof payload.text === "string") {
text = payload.text;
emit();
return;
}
if ((type === "response.reasoning_summary_text.delta" || type === "response.reasoning_text.delta") && typeof payload.delta === "string") {
reasoning += payload.delta;
emit();
return;
}
if ((type === "response.reasoning_summary_text.done" || type === "response.reasoning_text.done") && typeof payload.text === "string") {
reasoning = payload.text;
emit();
return;
}
if (type === "response.output_item.added" || type === "response.output_item.done") {
const item = isRecord(payload.item) ? payload.item : undefined;
if (!item) return;
if (item.type === "message") {
const itemText = readContentText(item.content);
if (type === "response.output_item.done" && itemText) text = itemText;
} else if (item.type === "reasoning") {
const itemReasoning = readReasoningItem(item);
if (itemReasoning) reasoning = itemReasoning;
} else {
const tool = readToolItem(item, type === "response.output_item.done" ? "completed" : "in_progress");
if (tool) tools.set(tool.id, tool);
}
emit();
return;
}
if (type === "response.function_call_arguments.delta" || type === "response.custom_tool_call_input.delta") {
updateToolDetail(tools, payload, typeof payload.delta === "string" ? payload.delta : "", true);
emit();
return;
}
if (type === "response.function_call_arguments.done" || type === "response.custom_tool_call_input.done") {
const detail = typeof payload.arguments === "string" ? payload.arguments : typeof payload.input === "string" ? payload.input : "";
updateToolDetail(tools, payload, detail, false);
emit();
return;
}
if (type === "response.created" || type === "response.in_progress" || type === "response.completed" || type === "response.incomplete") {
const responsePayload = isRecord(payload.response) ? payload.response : undefined;
if (type === "response.completed" || type === "response.incomplete") {
applyEnvelope(responsePayload);
emit();
}
if (type === "response.incomplete") {
throw new CreativeApiError(response.status, readIncompleteReason(responsePayload) || "The response ended before completion", "incomplete_response");
}
return;
}
if (type === "response.failed" || type === "error") {
const error = readError(isRecord(payload.response) ? payload.response : payload);
throw new CreativeApiError(response.status, error.message ?? "The Responses API stream failed", error.code);
}
};
while (true) {
const { done, value } = await reader.read();
buffer = (buffer + decoder.decode(value, { stream: !done })).replaceAll("\r\n", "\n");
let boundary = buffer.indexOf("\n\n");
while (boundary >= 0) {
consume(buffer.slice(0, boundary));
buffer = buffer.slice(boundary + 2);
boundary = buffer.indexOf("\n\n");
}
if (done) break;
}
if (buffer.trim()) consume(buffer);
if (!text.trim() && !reasoning.trim() && tools.size === 0) throw new CreativeApiError(response.status, "The Responses API did not return any displayable output", "invalid_response");
return snapshot();
}
function resolveMediaURL(value: string): string {
const url = value.trim();
if (!url || url.startsWith("data:") || url.startsWith("blob:")) return url;
@@ -175,12 +331,77 @@ function readVideoRequestID(payload: unknown): string {
return isRecord(payload) && typeof payload.request_id === "string" ? payload.request_id.trim() : "";
}
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;
function readResponseText(payload: unknown): string {
if (!isRecord(payload)) return "";
if (typeof payload.output_text === "string" && payload.output_text.trim()) return payload.output_text.trim();
if (!Array.isArray(payload.output)) return "";
return payload.output.flatMap((item) => {
if (!isRecord(item) || item.type !== "message") return [];
return [readContentText(item.content)];
}).filter(Boolean).join("\n").trim();
}
function readResponseReasoning(payload: unknown): string {
if (!isRecord(payload) || !Array.isArray(payload.output)) return "";
return payload.output.flatMap((item) => {
if (!isRecord(item) || item.type !== "reasoning") return [];
return [readReasoningItem(item)];
}).filter(Boolean).join("\n").trim();
}
function readResponseTools(payload: unknown): ChatToolActivity[] {
if (!isRecord(payload) || !Array.isArray(payload.output)) return [];
return payload.output.flatMap((item) => {
if (!isRecord(item) || item.type === "message" || item.type === "reasoning") return [];
const tool = readToolItem(item, "completed");
return tool ? [tool] : [];
});
}
function readReasoningItem(item: Record<string, unknown>): string {
const summary = readContentText(item.summary);
return summary || readContentText(item.content);
}
function readToolItem(item: Record<string, unknown>, fallbackStatus: ChatToolActivity["status"]): ChatToolActivity | null {
const type = typeof item.type === "string" ? item.type.trim() : "";
if (!type) return null;
const id = firstString(item.id, item.call_id) || `${type}-${firstString(item.name) || "tool"}`;
const name = firstString(item.name) || toolNameFromType(type);
const action = isRecord(item.action) ? item.action : undefined;
const detail = firstString(item.arguments, item.input, action?.query, item.query);
return { id, type, name, status: readToolStatus(item.status, fallbackStatus), detail };
}
function updateToolDetail(tools: Map<string, ChatToolActivity>, payload: Record<string, unknown>, detail: string, append: boolean): void {
const id = firstString(payload.item_id, payload.call_id);
if (!id) return;
const current = tools.get(id) ?? { id, type: "function_call", name: "tool", status: "in_progress" as const, detail: "" };
tools.set(id, { ...current, detail: append ? current.detail + detail : detail || current.detail });
}
function readToolStatus(value: unknown, fallback: ChatToolActivity["status"]): ChatToolActivity["status"] {
if (value === "completed") return "completed";
if (value === "failed" || value === "incomplete") return "failed";
if (value === "in_progress" || value === "searching") return "in_progress";
return fallback;
}
function toolNameFromType(type: string): string {
if (type === "web_search_call" || type === "web_search") return "web_search";
if (type === "x_search_call" || type === "x_search") return "x_search";
return type.replace(/_call$/, "");
}
function readIncompleteReason(payload: unknown): string {
if (!isRecord(payload) || !isRecord(payload.incomplete_details)) return "";
const reason = firstString(payload.incomplete_details.reason);
return reason ? `The response was incomplete: ${reason}` : "";
}
function firstString(...values: unknown[]): string {
for (const value of values) {
if (typeof value === "string" && value.trim()) return value.trim();
}
return "";
}
@@ -244,6 +465,15 @@ function readError(payload: unknown): { code?: string; message?: string } {
};
}
function parseJSON(value: string): unknown {
if (!value.trim()) return null;
try {
return JSON.parse(value);
} catch {
return null;
}
}
function isVideoStatus(value: unknown): value is VideoStatus["status"] {
return value === "pending" || value === "done" || value === "failed";
}
@@ -1,25 +1,33 @@
import { useMutation, useQuery } from "@tanstack/react-query";
import { ArrowUp, Bot, CheckCircle2, ExternalLink, ImageIcon, KeyRound, Loader2, LockKeyhole, MessageSquareText, RefreshCw, SlidersHorizontal, Trash2, Video } from "lucide-react";
import { useMemo, useState, type FormEvent, type KeyboardEvent } from "react";
import { ArrowUp, BrainCircuit, Check, CheckCircle2, Clock3, ExternalLink, Globe, History, ImageIcon, ImagePlus, ImageUpscale, Images, Loader2, MessageSquareText, RefreshCw, Sparkle, SquarePen, Trash2, TriangleAlert, TvMinimal, Video, Wrench, X } from "lucide-react";
import { marked } from "marked";
import { useEffect, useMemo, useRef, useState, type FormEvent, type KeyboardEvent, type ReactNode } from "react";
import { createPortal } from "react-dom";
import { useTranslation } from "react-i18next";
import { Button } from "@/components/ui/button";
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuLabel, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
import { Input } from "@/components/ui/input";
import { Message, MessageAvatar, MessageContent } from "@/components/ui/message";
import { Message, MessageContent } from "@/components/ui/message";
import { MessageScroller, MessageScrollerButton, MessageScrollerContent, MessageScrollerItem, MessageScrollerProvider, MessageScrollerViewport } from "@/components/ui/message-scroller";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
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 { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { listModels } from "@/entities/model/model-api";
import type { ModelRouteDTO } from "@/entities/model/types";
import {
createChatCompletion,
createChatResponse,
createVideo,
generateImage,
getVideo,
type ChatMessage,
type ChatStreamSnapshot,
type ChatToolActivity,
type ImageResult,
type ReasoningEffort,
type VideoStatus,
} from "@/features/creative-console/creative-console-api";
import { getClientKeySecret, listClientKeys, type ClientKeyDTO } from "@/features/client-keys/client-keys-api";
@@ -27,7 +35,11 @@ import { PageHeader } from "@/shared/components/page-header";
import { cn } from "@/shared/lib/cn";
type CreativeMode = "chat" | "image" | "video";
type ConversationMessage = ChatMessage & { id: string };
type ConversationMessage = ChatMessage & {
id: string;
reasoning?: string;
tools?: ChatToolActivity[];
};
type SecretState = {
keyId: string;
@@ -35,15 +47,38 @@ type SecretState = {
};
type ChatRequest = {
requestMessages: ChatMessage[];
messages: ChatMessage[];
promptCacheKey: string;
reasoningEffort: ReasoningEffort;
webSearch: boolean;
xSearch: boolean;
assistantMessageId: string;
apiKey: string;
model: string;
};
type ChatSession = {
id: string;
title: string;
createdAt: number;
updatedAt: number;
model: string;
promptCacheKey: string;
reasoningEffort: ReasoningEffort;
webSearch: boolean;
xSearch: boolean;
messages: ConversationMessage[];
};
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;
const videoDurations = ["6", "10", "15"] as const;
const chatHistoryStoragePrefix = "grok2api:creative-console:chat-history:";
const chatHistoryMaxSessions = 50;
const chatHistoryMaxBytes = 4 * 1024 * 1024;
const composerClassName = "overflow-hidden rounded-2xl bg-secondary/45 ring-1 ring-transparent transition-colors focus-within:bg-secondary/60 focus-within:ring-ring";
export function CreativeConsolePage() {
const { t } = useTranslation();
@@ -52,6 +87,8 @@ export function CreativeConsolePage() {
const [secretState, setSecretState] = useState<SecretState | null>(null);
const [keyError, setKeyError] = useState("");
const [selectedModels, setSelectedModels] = useState<Record<CreativeMode, string>>({ chat: "", image: "", video: "" });
const [chatToolbarElement, setChatToolbarElement] = useState<HTMLDivElement | null>(null);
const requestedSecretKeyRef = useRef("");
const keysQuery = useQuery({
queryKey: ["creative-console", "client-keys"],
@@ -90,9 +127,23 @@ export function CreativeConsolePage() {
setSecretState({ keyId: id, secret });
setKeyError("");
},
onError: (error) => setKeyError(error instanceof Error ? error.message : t("creativeConsole.errors.keyUnavailable")),
onError: (error, id) => {
if (id !== effectiveKeyId) return;
setKeyError(error instanceof Error ? error.message : t("creativeConsole.errors.keyUnavailable"));
},
});
const loadSecret = secretMutation.mutate;
useEffect(() => {
if (!effectiveKeyId) {
requestedSecretKeyRef.current = "";
return;
}
if (requestedSecretKeyRef.current === effectiveKeyId) return;
requestedSecretKeyRef.current = effectiveKeyId;
loadSecret(effectiveKeyId);
}, [effectiveKeyId, loadSecret]);
const apiKey = secretState?.keyId === effectiveKeyId ? secretState.secret : "";
function panelProps(panelMode: CreativeMode): CreativePanelProps {
@@ -110,17 +161,22 @@ export function CreativeConsolePage() {
setKeyError("");
}
function unlockKey(): void {
if (!effectiveKeyId || secretMutation.isPending) return;
secretMutation.mutate(effectiveKeyId);
}
return (
<div className="flex h-[calc(100dvh-5rem)] min-h-[36rem] flex-col gap-8 overflow-hidden">
<div className="flex h-[calc(100dvh-5rem)] min-h-[36rem] flex-col gap-5 overflow-hidden">
<PageHeader title={t("creativeConsole.title")} description={t("creativeConsole.description")} />
<aside className="flex shrink-0 flex-col gap-2 rounded-lg bg-secondary/45 px-4 py-2.5 text-xs leading-5 text-muted-foreground sm:flex-row sm:items-center sm:justify-between sm:gap-4">
<div className="flex min-w-0 items-center gap-3">
<Sparkle className="size-4 shrink-0 text-foreground/70" />
<p>{t("creativeConsole.promotion", { product: "DEEIX Chat" })}</p>
</div>
<a className="inline-flex shrink-0 items-center gap-1.5 self-end font-medium text-foreground hover:underline sm:self-auto" href="https://github.com/DEEIX-AI/DEEIX-Chat" target="_blank" rel="noopener noreferrer">
{t("creativeConsole.promotionAction")}<ExternalLink className="size-3.5" />
</a>
</aside>
<section className="flex min-h-0 flex-1 flex-col overflow-hidden">
<div className="flex min-h-12 shrink-0 flex-col gap-3 py-2 lg:flex-row lg:items-center lg:justify-between">
<div className="flex min-h-9 shrink-0 flex-col gap-3 lg:flex-row lg:items-center lg:justify-between">
<Tabs value={mode} onValueChange={(value) => setMode(value as CreativeMode)}>
<TabsList className="h-9 w-full rounded-full bg-secondary/50 p-1 lg:w-auto">
<TabsTrigger className="flex-1 gap-1.5 rounded-full px-3 lg:min-w-20 [&_svg]:size-3.5" value="chat"><MessageSquareText />{t("creativeConsole.modes.chat")}</TabsTrigger>
@@ -131,20 +187,14 @@ export function CreativeConsolePage() {
<div className="flex min-w-0 items-center gap-2">
<Select value={effectiveKeyId} onValueChange={changeKey} disabled={keysQuery.isPending || activeKeys.length === 0}>
<SelectTrigger id="creative-key" className="min-w-0 flex-1 rounded-full border-transparent bg-secondary/50 lg:w-64 lg:flex-none" aria-label={t("creativeConsole.clientKey")}>
<SelectTrigger id="creative-key" className="min-w-0 flex-1 bg-secondary/55 lg:w-64 lg:flex-none" 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>
<div className={cn("flex h-8 shrink-0 items-center gap-1.5 px-2 text-[11px]", apiKey ? "text-primary" : "text-muted-foreground")}>
{apiKey ? <CheckCircle2 className="size-3.5" /> : <LockKeyhole className="size-3.5" />}
<span className="hidden sm:inline">{apiKey ? t("creativeConsole.keyReady") : t("creativeConsole.keyLocked")}</span>
</div>
<Button type="button" variant="secondary" size="icon" aria-label={t("creativeConsole.loadKey")} onClick={unlockKey} disabled={!effectiveKeyId || Boolean(apiKey) || secretMutation.isPending}>
{secretMutation.isPending ? <Spinner /> : <KeyRound />}
</Button>
<div ref={setChatToolbarElement} className={cn("items-center gap-1", mode === "chat" ? "flex" : "hidden")} />
</div>
</div>
@@ -156,7 +206,7 @@ export function CreativeConsolePage() {
</div>
<div className="min-h-0 flex-1">
<div className="h-full" hidden={mode !== "chat"}><ChatPanel {...panelProps("chat")} /></div>
<div className="h-full" hidden={mode !== "chat"}><ChatPanel key={effectiveKeyId || "default"} storageScope={effectiveKeyId || "default"} toolbarElement={chatToolbarElement} {...panelProps("chat")} /></div>
<div className="h-full" hidden={mode !== "image"}><ImagePanel {...panelProps("image")} /></div>
<div className="h-full" hidden={mode !== "video"}><VideoPanel {...panelProps("video")} /></div>
</div>
@@ -172,23 +222,112 @@ type CreativePanelProps = {
onModelChange: (model: string) => void;
};
function ChatPanel({ apiKey, model, modelOptions, onModelChange }: CreativePanelProps) {
const { t } = useTranslation();
const [systemPrompt, setSystemPrompt] = useState("");
const [showSystemPrompt, setShowSystemPrompt] = useState(false);
function ChatPanel({ apiKey, model, modelOptions, onModelChange, storageScope, toolbarElement }: CreativePanelProps & { storageScope: string; toolbarElement: HTMLDivElement | null }) {
const { t, i18n } = useTranslation();
const [initialHistory] = useState(() => {
const sessions = loadChatSessions(storageScope);
return { sessions, active: sessions[0] ?? createBlankChatSession(model) };
});
const [sessions, setSessions] = useState<ChatSession[]>(initialHistory.sessions);
const [sessionId, setSessionId] = useState(initialHistory.active.id);
const [sessionCreatedAt, setSessionCreatedAt] = useState(initialHistory.active.createdAt);
const [webSearch, setWebSearch] = useState(initialHistory.active.webSearch);
const [xSearch, setXSearch] = useState(initialHistory.active.xSearch);
const [reasoningEffort, setReasoningEffort] = useState<ReasoningEffort>(initialHistory.active.reasoningEffort);
const [promptCacheKey, setPromptCacheKey] = useState(initialHistory.active.promptCacheKey);
const [prompt, setPrompt] = useState("");
const [messages, setMessages] = useState<ConversationMessage[]>([]);
const [messages, setMessages] = useState<ConversationMessage[]>(initialHistory.active.messages);
const streamSnapshotRef = useRef<ChatStreamSnapshot>({ text: "", reasoning: "", tools: [] });
const streamFrameRef = useRef<number | null>(null);
const requestControllerRef = useRef<AbortController | null>(null);
const restoredInitialModelRef = useRef(false);
useEffect(() => {
if (restoredInitialModelRef.current || modelOptions.length === 0) return;
restoredInitialModelRef.current = true;
if (initialHistory.active.model && modelOptions.some((option) => option.publicId === initialHistory.active.model)) {
onModelChange(initialHistory.active.model);
}
}, [initialHistory.active.model, modelOptions, onModelChange]);
useEffect(() => {
if (messages.length === 0) return;
const timer = window.setTimeout(() => {
const session: ChatSession = {
id: sessionId,
title: createChatSessionTitle(messages),
createdAt: sessionCreatedAt,
updatedAt: currentTimestamp(),
model,
promptCacheKey,
reasoningEffort,
webSearch,
xSearch,
messages,
};
setSessions((current) => {
const next = upsertChatSession(current, session);
return persistChatSessions(storageScope, next);
});
}, 300);
return () => window.clearTimeout(timer);
}, [messages, model, promptCacheKey, reasoningEffort, sessionCreatedAt, sessionId, storageScope, webSearch, xSearch]);
useEffect(() => () => {
if (streamFrameRef.current !== null) cancelAnimationFrame(streamFrameRef.current);
requestControllerRef.current?.abort();
}, []);
function renderStreamSnapshot(messageId: string): void {
if (streamFrameRef.current !== null) return;
streamFrameRef.current = requestAnimationFrame(() => {
streamFrameRef.current = null;
const snapshot = streamSnapshotRef.current;
setMessages((current) => current.map((message) => message.id === messageId
? { ...message, content: snapshot.text, reasoning: snapshot.reasoning, tools: snapshot.tools }
: message));
});
}
const mutation = useMutation({
mutationFn: (request: ChatRequest) => createChatCompletion({
apiKey: request.apiKey,
model: request.model,
messages: request.requestMessages,
}),
onSuccess: (content, request) => setMessages([
...messagesFromRequest(request.requestMessages),
{ id: createCreativeMessageId(), role: "assistant", content },
]),
mutationFn: (request: ChatRequest) => {
streamSnapshotRef.current = { text: "", reasoning: "", tools: [] };
const controller = new AbortController();
requestControllerRef.current = controller;
return createChatResponse({
apiKey: request.apiKey,
model: request.model,
messages: request.messages,
promptCacheKey: request.promptCacheKey || undefined,
reasoningEffort: request.reasoningEffort,
webSearch: request.webSearch,
xSearch: request.xSearch,
signal: controller.signal,
onUpdate: (snapshot) => {
streamSnapshotRef.current = snapshot;
renderStreamSnapshot(request.assistantMessageId);
},
});
},
onSuccess: (result, request) => {
if (streamFrameRef.current !== null) cancelAnimationFrame(streamFrameRef.current);
streamFrameRef.current = null;
setMessages((current) => current.map((message) => message.id === request.assistantMessageId
? { ...message, content: result.text, reasoning: result.reasoning, tools: result.tools }
: message));
requestControllerRef.current = null;
},
onError: (_error, request) => {
if (streamFrameRef.current !== null) cancelAnimationFrame(streamFrameRef.current);
streamFrameRef.current = null;
const snapshot = streamSnapshotRef.current;
setMessages((current) => current.flatMap((message) => {
if (message.id !== request.assistantMessageId) return [message];
if (!snapshot.text.trim() && !snapshot.reasoning.trim() && snapshot.tools.length === 0) return [];
return [{ ...message, content: snapshot.text, reasoning: snapshot.reasoning, tools: snapshot.tools }];
}));
requestControllerRef.current = null;
},
});
function submit(event?: FormEvent): void {
@@ -196,15 +335,100 @@ function ChatPanel({ apiKey, model, modelOptions, onModelChange }: CreativePanel
const userText = prompt.trim();
if (!apiKey || !model || !userText || mutation.isPending) return;
const userMessage: ConversationMessage = { id: createCreativeMessageId(), role: "user", content: userText };
const assistantMessage: ConversationMessage = { id: createCreativeMessageId(), role: "assistant", content: "", reasoning: "", tools: [] };
const requestMessages: ChatMessage[] = [
...(systemPrompt.trim() ? [{ role: "system" as const, content: systemPrompt.trim() }] : []),
...messages.map(({ role, content }) => ({ role, content })),
...messages.filter((message) => message.content.trim()).map(({ role, content }) => ({ role, content })),
{ role: "user", content: userText },
];
setMessages((current) => [...current, userMessage]);
setMessages((current) => [...current, userMessage, assistantMessage]);
setPrompt("");
mutation.reset();
mutation.mutate({ requestMessages, apiKey, model });
mutation.mutate({
messages: requestMessages,
promptCacheKey,
reasoningEffort,
webSearch,
xSearch,
assistantMessageId: assistantMessage.id,
apiKey,
model,
});
}
function clearConversation(): void {
setSessions((current) => {
const next = current.filter((session) => session.id !== sessionId);
return persistChatSessions(storageScope, next);
});
const blank = createBlankChatSession(model);
setSessionId(blank.id);
setSessionCreatedAt(blank.createdAt);
setMessages([]);
setPromptCacheKey(blank.promptCacheKey);
setPrompt("");
mutation.reset();
}
function startNewConversation(): void {
if (mutation.isPending) return;
setSessions((current) => {
const next = messages.length > 0 ? upsertChatSession(current, {
id: sessionId,
title: createChatSessionTitle(messages),
createdAt: sessionCreatedAt,
updatedAt: currentTimestamp(),
model,
promptCacheKey,
reasoningEffort,
webSearch,
xSearch,
messages,
}) : current;
return persistChatSessions(storageScope, next);
});
const blank = createBlankChatSession(model);
setSessionId(blank.id);
setSessionCreatedAt(blank.createdAt);
setMessages([]);
setPromptCacheKey(blank.promptCacheKey);
setReasoningEffort(blank.reasoningEffort);
setWebSearch(blank.webSearch);
setXSearch(blank.xSearch);
setPrompt("");
mutation.reset();
}
function switchConversation(targetId: string): void {
if (mutation.isPending || targetId === sessionId) return;
let availableSessions = sessions;
if (messages.length > 0) {
availableSessions = upsertChatSession(sessions, {
id: sessionId,
title: createChatSessionTitle(messages),
createdAt: sessionCreatedAt,
updatedAt: currentTimestamp(),
model,
promptCacheKey,
reasoningEffort,
webSearch,
xSearch,
messages,
});
}
const target = availableSessions.find((session) => session.id === targetId);
if (!target) return;
availableSessions = persistChatSessions(storageScope, availableSessions);
setSessions(availableSessions);
setSessionId(target.id);
setSessionCreatedAt(target.createdAt);
setMessages(target.messages);
setPromptCacheKey(target.promptCacheKey || createCreativeCacheKey());
setReasoningEffort(target.reasoningEffort);
setWebSearch(target.webSearch);
setXSearch(target.xSearch);
setPrompt("");
mutation.reset();
if (target.model && modelOptions.some((option) => option.publicId === target.model)) onModelChange(target.model);
}
function handlePromptKeyDown(event: KeyboardEvent<HTMLTextAreaElement>): void {
@@ -216,26 +440,55 @@ function ChatPanel({ apiKey, model, modelOptions, onModelChange }: CreativePanel
return (
<div className="flex h-full min-h-0 flex-col overflow-hidden">
{toolbarElement ? createPortal(<>
<Tooltip>
<TooltipTrigger asChild>
<Button type="button" variant="ghost" size="icon" className="rounded-full" aria-label={t("creativeConsole.newConversation")} onClick={startNewConversation} disabled={mutation.isPending}>
<SquarePen />
</Button>
</TooltipTrigger>
<TooltipContent>{t("creativeConsole.newConversation")}</TooltipContent>
</Tooltip>
<Tooltip>
<TooltipTrigger asChild>
<Button type="button" variant="ghost" size="icon" className="rounded-full" aria-label={t("creativeConsole.clearCurrent")} onClick={clearConversation} disabled={messages.length === 0 || mutation.isPending}>
<Trash2 />
</Button>
</TooltipTrigger>
<TooltipContent>{t("creativeConsole.clearCurrent")}</TooltipContent>
</Tooltip>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button type="button" variant="ghost" size="icon" className="rounded-full" aria-label={t("creativeConsole.history")} disabled={mutation.isPending}>
<History />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-80">
<DropdownMenuLabel>{t("creativeConsole.history")}</DropdownMenuLabel>
{sessions.length === 0 ? (
<div className="px-2 py-5 text-center text-xs text-muted-foreground">{t("creativeConsole.noHistory")}</div>
) : sessions.map((session) => (
<DropdownMenuItem key={session.id} className="min-h-12 gap-2" onSelect={() => switchConversation(session.id)}>
<div className="min-w-0 flex-1">
<div className="truncate text-xs">{session.title}</div>
<div className="mt-0.5 truncate text-[10px] text-muted-foreground">{session.model || t("creativeConsole.model")} · {formatChatSessionTime(session.updatedAt, i18n.language)}</div>
</div>
{session.id === sessionId ? <Check className="text-muted-foreground" /> : null}
</DropdownMenuItem>
))}
</DropdownMenuContent>
</DropdownMenu>
</>, toolbarElement) : null}
<MessageScrollerProvider autoScroll defaultScrollPosition="end">
<MessageScroller className="min-h-0 flex-1">
<MessageScrollerViewport aria-label={t("creativeConsole.messageList")}>
<MessageScrollerContent className={cn("w-full px-3 py-6 sm:px-6", messages.length === 0 && !mutation.isPending && "justify-center")}>
{messages.length === 0 && !mutation.isPending ? <WelcomeState title={t("creativeConsole.welcome")} /> : null}
{messages.length > 0 || mutation.isPending ? (
<div className="flex justify-end">
<Button type="button" variant="ghost" size="sm" onClick={() => setMessages([])} disabled={mutation.isPending}><Trash2 />{t("creativeConsole.clear")}</Button>
</div>
) : null}
{messages.map((message) => (
<MessageScrollerItem key={message.id} messageId={message.id} scrollAnchor={message.role === "user"}>
<ChatMessageItem message={message} />
<ChatMessageItem message={message} loading={mutation.isPending && mutation.variables?.assistantMessageId === message.id} />
</MessageScrollerItem>
))}
{mutation.isPending ? (
<MessageScrollerItem messageId="pending">
<ChatMessageItem message={{ id: "pending", role: "assistant", content: t("creativeConsole.thinking") }} loading />
</MessageScrollerItem>
) : null}
</MessageScrollerContent>
</MessageScrollerViewport>
<MessageScrollerButton aria-label={t("creativeConsole.scrollToLatest")} />
@@ -243,17 +496,35 @@ function ChatPanel({ apiKey, model, modelOptions, onModelChange }: CreativePanel
</MessageScrollerProvider>
<form className="w-full shrink-0 px-3 pb-2 sm:px-6 sm:pb-3" onSubmit={submit}>
<div className="overflow-hidden rounded-2xl border border-border/70 bg-background shadow-sm transition-shadow focus-within:shadow-md">
{showSystemPrompt ? (
<div className="border-b border-border/50 bg-secondary/20 p-3">
<Textarea id="chat-system" value={systemPrompt} onChange={(event) => setSystemPrompt(event.target.value)} placeholder={t("creativeConsole.systemPromptPlaceholder")} className="min-h-16 resize-none border-0 bg-transparent px-1 py-0 focus-visible:ring-0" />
</div>
) : null}
<div className={composerClassName}>
<Textarea id="chat-prompt" value={prompt} onChange={(event) => setPrompt(event.target.value)} onKeyDown={handlePromptKeyDown} placeholder={t("creativeConsole.chatPlaceholder")} className="min-h-24 resize-none border-0 bg-transparent px-4 py-3 text-sm focus-visible:ring-0" />
<div className="flex items-center justify-between gap-3 px-3 pb-3">
<div className="flex min-w-0 items-center gap-1">
<Button type="button" variant="ghost" size="icon" className={cn(showSystemPrompt && "bg-secondary")} aria-label={t("creativeConsole.systemPrompt")} onClick={() => setShowSystemPrompt((value) => !value)}><SlidersHorizontal /></Button>
<div className="flex min-w-0 items-center gap-0.5 overflow-x-auto">
<CompactModelSelect value={model} models={modelOptions} onChange={onModelChange} />
<CompactIconSelect
value={webSearch ? "on" : "off"}
options={[{ value: "off", label: t("creativeConsole.webSearchOff") }, { value: "on", label: t("creativeConsole.webSearchOn") }]}
onChange={(value) => setWebSearch(value === "on")}
ariaLabel={t("creativeConsole.webSearch")}
icon={<Globe />}
active={webSearch}
/>
<CompactIconSelect
value={xSearch ? "on" : "off"}
options={[{ value: "off", label: t("creativeConsole.xSearchOff") }, { value: "on", label: t("creativeConsole.xSearchOn") }]}
onChange={(value) => setXSearch(value === "on")}
ariaLabel={t("creativeConsole.xSearch")}
icon={<XSocialIcon />}
active={xSearch}
/>
<CompactIconSelect
value={reasoningEffort}
options={(["auto", "none", "low", "medium", "high", "xhigh"] as ReasoningEffort[]).map((effort) => ({ value: effort, label: t(`creativeConsole.reasoning.${effort}`) }))}
onChange={(value) => setReasoningEffort(value as ReasoningEffort)}
ariaLabel={t("creativeConsole.reasoningEffort")}
icon={<Sparkle />}
active={reasoningEffort !== "auto" && reasoningEffort !== "none"}
/>
</div>
<Button type="submit" size="icon" aria-label={t("creativeConsole.send")} disabled={!apiKey || !model || !prompt.trim() || mutation.isPending}>
{mutation.isPending ? <Loader2 className="animate-spin" /> : <ArrowUp />}
@@ -309,14 +580,14 @@ function ImagePanel({ apiKey, model, modelOptions, onModelChange }: CreativePane
</div>
<form className="w-full shrink-0 px-3 pb-2 sm:px-6 sm:pb-3" onSubmit={submit}>
<div className="overflow-hidden rounded-2xl border border-border/70 bg-background shadow-sm transition-shadow focus-within:shadow-md">
<div className={composerClassName}>
<Textarea id="image-prompt" value={prompt} onChange={(event) => setPrompt(event.target.value)} placeholder={t("creativeConsole.imagePlaceholder")} className="min-h-24 resize-none border-0 bg-transparent px-4 py-3 text-sm focus-visible:ring-0" />
<div className="flex flex-wrap items-center justify-between gap-2 px-3 pb-3">
<div className="flex min-w-0 flex-wrap items-center gap-1">
<CompactModelSelect value={model} models={modelOptions} onChange={onModelChange} />
<CompactSelect value={count} options={["1", "2", "3", "4"]} onChange={setCount} ariaLabel={t("creativeConsole.count")} suffix="×" />
<CompactSelect value={aspectRatio} options={imageAspectRatios} onChange={setAspectRatio} ariaLabel={t("creativeConsole.aspectRatio")} />
<CompactSelect value={resolution} options={imageResolutions} onChange={setResolution} ariaLabel={t("creativeConsole.resolution")} />
<CompactSelect value={count} options={["1", "2", "3", "4"]} onChange={setCount} ariaLabel={t("creativeConsole.count")} suffix="×" icon={<Images />} />
<CompactSelect value={aspectRatio} options={imageAspectRatios} onChange={setAspectRatio} ariaLabel={t("creativeConsole.aspectRatio")} icon={<TvMinimal />} />
<CompactSelect value={resolution} options={imageResolutions} onChange={setResolution} ariaLabel={t("creativeConsole.resolution")} icon={<ImageUpscale />} />
</div>
<Button type="submit" size="icon" aria-label={t("creativeConsole.generateImage")} disabled={!apiKey || !model || !prompt.trim() || mutation.isPending}>{mutation.isPending ? <Loader2 className="animate-spin" /> : <ArrowUp />}</Button>
</div>
@@ -331,10 +602,9 @@ function VideoPanel({ apiKey, model, modelOptions, onModelChange }: CreativePane
const { t } = useTranslation();
const [prompt, setPrompt] = useState("");
const [imageURL, setImageURL] = useState("");
const [duration, setDuration] = useState("8");
const [duration, setDuration] = useState("6");
const [aspectRatio, setAspectRatio] = useState("16:9");
const [resolution, setResolution] = useState("720p");
const [showOptions, setShowOptions] = useState(false);
const [job, setJob] = useState<{ requestId: string; apiKey: string } | null>(null);
const createMutation = useMutation({
@@ -385,38 +655,28 @@ function VideoPanel({ apiKey, model, modelOptions, onModelChange }: CreativePane
</div>
<form className="w-full shrink-0 px-3 pb-2 sm:px-6 sm:pb-3" onSubmit={submit}>
<div className="overflow-hidden rounded-2xl border border-border/70 bg-background shadow-sm transition-shadow focus-within:shadow-md">
{showOptions ? (
<div className="grid gap-2 border-b border-border/50 bg-secondary/20 p-3 sm:grid-cols-[minmax(0,1fr)_7rem_7rem_7rem]">
<Input
id="video-image"
type="url"
className="border-transparent bg-background/70 shadow-none"
value={imageURL}
onChange={(event) => setImageURL(event.target.value)}
placeholder={t("creativeConsole.referenceImage")}
aria-label={t("creativeConsole.referenceImage")}
/>
<Input
id="video-duration"
type="number"
className="border-transparent bg-background/70 shadow-none"
min={1}
max={15}
step={1}
value={duration}
onChange={(event) => setDuration(event.target.value)}
aria-label={t("creativeConsole.duration")}
/>
<CompactSelect value={aspectRatio} options={videoAspectRatios} onChange={setAspectRatio} ariaLabel={t("creativeConsole.aspectRatio")} surfaced />
<CompactSelect value={resolution} options={videoResolutions} onChange={setResolution} ariaLabel={t("creativeConsole.resolution")} surfaced />
</div>
) : null}
<div className={composerClassName}>
<Textarea id="video-prompt" value={prompt} onChange={(event) => setPrompt(event.target.value)} placeholder={t("creativeConsole.videoPlaceholder")} className="min-h-24 resize-none border-0 bg-transparent px-4 py-3 text-sm focus-visible:ring-0" />
<div className="flex items-center justify-between gap-3 px-3 pb-3">
<div className="flex min-w-0 items-center gap-1">
<Button type="button" variant="ghost" size="icon" className={cn(showOptions && "bg-secondary")} aria-label={t("creativeConsole.videoOptions")} onClick={() => setShowOptions((value) => !value)}><SlidersHorizontal /></Button>
<div className="flex min-w-0 items-center gap-1 overflow-x-auto">
<CompactModelSelect value={model} models={modelOptions} onChange={onModelChange} />
<Popover>
<PopoverTrigger asChild>
<Button type="button" variant="ghost" size="sm" className={cn("h-8 gap-1.5 px-2 font-normal", imageURL && "bg-secondary/70 text-foreground")} aria-label={t("creativeConsole.referenceImage")}>
<ImagePlus />{imageURL ? t("creativeConsole.referenceImageAdded") : t("creativeConsole.referenceImageShort")}
</Button>
</PopoverTrigger>
<PopoverContent align="start" className="w-80 p-3">
<div className="mb-2 text-xs font-medium">{t("creativeConsole.referenceImage")}</div>
<div className="flex items-center gap-2">
<Input id="video-image" type="url" value={imageURL} onChange={(event) => setImageURL(event.target.value)} placeholder="https://..." aria-label={t("creativeConsole.referenceImage")} />
{imageURL ? <Button type="button" variant="ghost" size="icon" className="shrink-0" aria-label={t("creativeConsole.clearReferenceImage")} onClick={() => setImageURL("")}><X /></Button> : null}
</div>
</PopoverContent>
</Popover>
<CompactSelect value={duration} options={videoDurations} onChange={setDuration} ariaLabel={t("creativeConsole.duration")} suffix="s" icon={<Clock3 />} />
<CompactSelect value={aspectRatio} options={videoAspectRatios} onChange={setAspectRatio} ariaLabel={t("creativeConsole.aspectRatio")} icon={<TvMinimal />} />
<CompactSelect value={resolution} options={videoResolutions} onChange={setResolution} ariaLabel={t("creativeConsole.resolution")} icon={<ImageUpscale />} />
</div>
<Button type="submit" size="icon" aria-label={t("creativeConsole.generateVideo")} disabled={!apiKey || !model || (!prompt.trim() && !imageURL.trim()) || !validDuration(duration) || createMutation.isPending}>
{createMutation.isPending ? <Loader2 className="animate-spin" /> : <ArrowUp />}
@@ -460,8 +720,8 @@ function VideoResult({ requestId, status, loading, error, onRetry }: { requestId
function WelcomeState({ title }: { title: string }) {
return (
<div className="flex min-h-[24rem] items-center justify-center px-6 text-center">
<h2 className="max-w-2xl text-2xl font-medium tracking-tight text-foreground/80 sm:text-3xl">{title}</h2>
<div className="flex min-h-[20rem] items-center justify-center px-6 text-center">
<h2 className="max-w-2xl text-xl font-medium tracking-tight text-muted-foreground sm:text-2xl">{title}</h2>
</div>
);
}
@@ -478,39 +738,112 @@ function CompactModelSelect({ value, models, onChange }: { value: string; models
);
}
function CompactSelect({ value, options, onChange, ariaLabel, suffix, surfaced = false }: { value: string; options: readonly string[]; onChange: (value: string) => void; ariaLabel: string; suffix?: string; surfaced?: boolean }) {
function CompactSelect({ value, options, onChange, ariaLabel, suffix, icon }: { value: string; options: readonly string[]; onChange: (value: string) => void; ariaLabel: string; suffix?: string; icon?: ReactNode }) {
return (
<Select value={value} onValueChange={onChange}>
<SelectTrigger className={cn("h-8 w-auto gap-1 border-0 bg-transparent px-2 shadow-none hover:bg-secondary/70 focus:bg-secondary/70 focus:ring-0", surfaced && "w-full bg-background/70 hover:bg-background")} aria-label={ariaLabel}>
<span className="flex min-w-0 items-center gap-0.5"><SelectValue />{suffix ? <span>{suffix}</span> : null}</span>
<SelectTrigger className="h-8 w-auto gap-1.5 border-0 bg-transparent px-2 shadow-none hover:bg-secondary/70 focus:bg-secondary/70 focus:ring-0 [&>svg]:size-3.5 [&>svg]:shrink-0" aria-label={ariaLabel}>
{icon}<SelectValue />
</SelectTrigger>
<SelectContent>{options.map((option) => <SelectItem key={option} value={option}>{option}{suffix}</SelectItem>)}</SelectContent>
</Select>
);
}
function messagesFromRequest(messages: ChatMessage[]): ConversationMessage[] {
return messages
.filter((message) => message.role !== "system")
.map((message) => ({ ...message, id: createCreativeMessageId() }));
function CompactIconSelect({ value, options, onChange, ariaLabel, icon, active = false }: { value: string; options: Array<{ value: string; label: string }>; onChange: (value: string) => void; ariaLabel: string; icon: ReactNode; active?: boolean }) {
const selectedLabel = options.find((option) => option.value === value)?.label ?? ariaLabel;
return (
<Select value={value} onValueChange={onChange}>
<Tooltip>
<TooltipTrigger asChild>
<SelectTrigger className={cn("h-8 w-auto min-w-8 gap-1 bg-transparent px-2 shadow-none hover:bg-secondary/70 focus:bg-secondary/70 focus:ring-0", active && "bg-secondary/70 text-foreground")} aria-label={`${ariaLabel}: ${selectedLabel}`}>
<span className="flex items-center [&_svg]:size-3.5">{icon}</span>
</SelectTrigger>
</TooltipTrigger>
<TooltipContent>{ariaLabel} · {selectedLabel}</TooltipContent>
</Tooltip>
<SelectContent>{options.map((option) => <SelectItem key={option.value} value={option.value}>{option.label}</SelectItem>)}</SelectContent>
</Select>
);
}
function XSocialIcon({ className }: { className?: string }) {
return (
<svg className={className} viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
<path d="M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231zm-1.161 17.52h1.833L7.084 4.126H5.117z" />
</svg>
);
}
function ChatMessageItem({ message, loading = false }: { message: ConversationMessage; loading?: boolean }) {
const { t } = useTranslation();
const isUser = message.role === "user";
return (
<Message align={isUser ? "end" : "start"}>
{!isUser ? <MessageAvatar><Bot className="size-4" /></MessageAvatar> : null}
<MessageContent>
<div className={cn("whitespace-pre-wrap break-words text-sm leading-6", isUser ? "rounded-2xl rounded-br-md bg-secondary px-4 py-2.5" : "py-1")}>
{loading ? <span className="flex items-center gap-2 text-muted-foreground"><Spinner />{message.content}</span> : message.content}
</div>
<MessageContent className={cn(!isUser && "w-full max-w-full")}>
{!isUser && message.reasoning ? (
<div className="w-full rounded-xl bg-secondary/45 px-3 py-2.5 text-xs text-muted-foreground">
<div className="mb-1.5 flex items-center gap-1.5 font-medium text-foreground/75"><BrainCircuit className="size-3.5" />{t("creativeConsole.thinkingProcess")}</div>
<div className="whitespace-pre-wrap break-words leading-5">{message.reasoning}</div>
</div>
) : null}
{!isUser && message.tools?.length ? (
<div className="flex w-full flex-col gap-1.5">
{message.tools.map((tool) => <ToolActivityItem key={tool.id} tool={tool} />)}
</div>
) : null}
{message.content || isUser ? (
isUser ? (
<div className="whitespace-pre-wrap break-words rounded-2xl rounded-br-md bg-secondary px-4 py-2.5 text-sm leading-6">{message.content}</div>
) : <AssistantContent content={message.content} />
) : null}
{loading ? <div className="flex items-center gap-2 py-1 text-xs text-muted-foreground"><Spinner />{t("creativeConsole.streaming")}</div> : null}
</MessageContent>
</Message>
);
}
function AssistantContent({ content }: { content: string }) {
const renderedHTML = useMemo(() => renderAssistantMarkup(content), [content]);
if (!renderedHTML) return <div className="w-full whitespace-pre-wrap break-words py-1 text-sm leading-6">{content}</div>;
return (
<div
className="w-full break-words py-1 text-sm leading-6 [&>:first-child]:mt-0 [&>:last-child]:mb-0 [&_a]:text-primary [&_a]:underline [&_a]:underline-offset-2 [&_blockquote]:my-3 [&_blockquote]:border-l-2 [&_blockquote]:border-border [&_blockquote]:pl-3 [&_code]:rounded [&_code]:bg-secondary [&_code]:px-1 [&_code]:py-0.5 [&_h1]:mb-3 [&_h1]:mt-5 [&_h1]:text-xl [&_h1]:font-semibold [&_h2]:mb-2 [&_h2]:mt-4 [&_h2]:text-lg [&_h2]:font-semibold [&_h3]:mb-2 [&_h3]:mt-3 [&_h3]:font-semibold [&_hr]:my-4 [&_hr]:border-border [&_img]:my-3 [&_img]:max-h-[32rem] [&_img]:max-w-full [&_img]:rounded-xl [&_li]:my-1 [&_ol]:my-3 [&_ol]:list-decimal [&_ol]:pl-6 [&_p]:my-2 [&_pre]:my-3 [&_pre]:overflow-x-auto [&_pre]:rounded-xl [&_pre]:bg-secondary [&_pre]:p-3 [&_pre_code]:bg-transparent [&_pre_code]:p-0 [&_table]:my-3 [&_table]:w-full [&_table]:border-collapse [&_td]:border-b [&_td]:border-border [&_td]:px-3 [&_td]:py-2 [&_th]:border-b [&_th]:border-border [&_th]:px-3 [&_th]:py-2 [&_th]:text-left [&_ul]:my-3 [&_ul]:list-disc [&_ul]:pl-6"
dangerouslySetInnerHTML={{ __html: renderedHTML }}
/>
);
}
function ToolActivityItem({ tool }: { tool: ChatToolActivity }) {
const { t } = useTranslation();
const isWebSearch = tool.name === "web_search" || tool.type === "web_search_call";
const isXSearch = tool.name === "x_search" || tool.type === "x_search_call";
const label = isWebSearch
? t("creativeConsole.toolNames.webSearch")
: isXSearch
? t("creativeConsole.toolNames.xSearch")
: tool.name;
const statusLabel = t(`creativeConsole.toolStatus.${tool.status}`);
return (
<div className="flex min-w-0 items-start gap-2 rounded-xl bg-secondary/45 px-3 py-2.5 text-xs">
<span className="mt-0.5 text-muted-foreground">
{isWebSearch ? <Globe className="size-3.5" /> : isXSearch ? <XSocialIcon className="size-3.5" /> : <Wrench className="size-3.5" />}
</span>
<div className="min-w-0 flex-1">
<div className="flex min-w-0 items-center gap-2">
<span className="truncate font-medium">{t("creativeConsole.toolCall")} · {label}</span>
<span className="ml-auto flex shrink-0 items-center gap-1 text-muted-foreground">
{tool.status === "in_progress" ? <Loader2 className="size-3 animate-spin" /> : tool.status === "failed" ? <TriangleAlert className="size-3 text-destructive" /> : <CheckCircle2 className="size-3" />}
{statusLabel}
</span>
</div>
{tool.detail ? <div className="mt-1 line-clamp-2 break-all leading-5 text-muted-foreground" title={tool.detail}>{tool.detail}</div> : null}
</div>
</div>
);
}
function LoadingResult({ text }: { text: string }) {
return <div className="flex min-h-[24rem] items-center justify-center gap-3 text-xs text-muted-foreground"><Spinner className="size-5" />{text}</div>;
return <div className="flex min-h-[20rem] items-center justify-center gap-3 text-xs text-muted-foreground"><Spinner className="size-5" />{text}</div>;
}
function InlineError({ message }: { message: string }) {
@@ -560,6 +893,225 @@ function createCreativeMessageId(): string {
return `creative-${Date.now().toString(36)}-${fallbackMessageID.toString(36)}`;
}
function createCreativeCacheKey(): string {
return `creative-console-${createCreativeMessageId()}`;
}
function currentTimestamp(): number {
return Date.now();
}
function createBlankChatSession(model: string): ChatSession {
const now = Date.now();
return {
id: createCreativeMessageId(),
title: "",
createdAt: now,
updatedAt: now,
model,
promptCacheKey: createCreativeCacheKey(),
reasoningEffort: "auto",
webSearch: false,
xSearch: false,
messages: [],
};
}
function createChatSessionTitle(messages: ConversationMessage[]): string {
const title = messages.find((message) => message.role === "user")?.content.replace(/\s+/g, " ").trim() ?? "";
return title.length > 48 ? `${title.slice(0, 48)}…` : title || "Conversation";
}
function upsertChatSession(sessions: ChatSession[], session: ChatSession): ChatSession[] {
return [session, ...sessions.filter((item) => item.id !== session.id)]
.sort((left, right) => right.updatedAt - left.updatedAt)
.slice(0, chatHistoryMaxSessions);
}
function chatHistoryStorageKey(scope: string): string {
return `${chatHistoryStoragePrefix}${encodeURIComponent(scope)}`;
}
function loadChatSessions(scope: string): ChatSession[] {
if (typeof window === "undefined") return [];
try {
const parsed: unknown = JSON.parse(window.localStorage.getItem(chatHistoryStorageKey(scope)) ?? "[]");
if (!Array.isArray(parsed)) return [];
return parsed.flatMap(parseChatSession).sort((left, right) => right.updatedAt - left.updatedAt).slice(0, chatHistoryMaxSessions);
} catch {
return [];
}
}
function persistChatSessions(scope: string, sessions: ChatSession[]): ChatSession[] {
if (typeof window === "undefined") return sessions;
const retained = sessions.slice(0, chatHistoryMaxSessions);
while (retained.length > 0) {
try {
const serialized = JSON.stringify(retained);
if (serialized.length * 2 > chatHistoryMaxBytes) {
retained.pop();
continue;
}
window.localStorage.setItem(chatHistoryStorageKey(scope), serialized);
return retained;
} catch {
retained.pop();
}
}
try {
window.localStorage.removeItem(chatHistoryStorageKey(scope));
} catch {
// Storage may be unavailable; the in-memory conversation remains usable.
}
return retained;
}
function parseChatSession(value: unknown): ChatSession[] {
if (!isLocalRecord(value) || typeof value.id !== "string" || !Array.isArray(value.messages)) return [];
const messages = value.messages.flatMap(parseConversationMessage);
if (messages.length === 0) return [];
const now = Date.now();
const createdAt = finiteTimestamp(value.createdAt) ?? now;
const updatedAt = finiteTimestamp(value.updatedAt) ?? createdAt;
return [{
id: value.id,
title: typeof value.title === "string" && value.title.trim() ? value.title.trim() : createChatSessionTitle(messages),
createdAt,
updatedAt,
model: typeof value.model === "string" ? value.model : "",
promptCacheKey: typeof value.promptCacheKey === "string" && value.promptCacheKey ? value.promptCacheKey : createCreativeCacheKey(),
reasoningEffort: isReasoningEffort(value.reasoningEffort) ? value.reasoningEffort : "auto",
webSearch: value.webSearch === true,
xSearch: value.xSearch === true,
messages,
}];
}
function parseConversationMessage(value: unknown): ConversationMessage[] {
if (!isLocalRecord(value) || (value.role !== "user" && value.role !== "assistant") || typeof value.content !== "string") return [];
return [{
id: typeof value.id === "string" && value.id ? value.id : createCreativeMessageId(),
role: value.role,
content: value.content,
reasoning: typeof value.reasoning === "string" ? value.reasoning : undefined,
tools: Array.isArray(value.tools) ? value.tools.flatMap(parseChatToolActivity) : undefined,
}];
}
function parseChatToolActivity(value: unknown): ChatToolActivity[] {
if (!isLocalRecord(value) || typeof value.id !== "string" || typeof value.type !== "string" || typeof value.name !== "string") return [];
const status = value.status === "completed" || value.status === "failed" || value.status === "in_progress" ? value.status : "completed";
return [{ id: value.id, type: value.type, name: value.name, status, detail: typeof value.detail === "string" ? value.detail : "" }];
}
function isReasoningEffort(value: unknown): value is ReasoningEffort {
return value === "auto" || value === "none" || value === "low" || value === "medium" || value === "high" || value === "xhigh";
}
function finiteTimestamp(value: unknown): number | null {
return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : null;
}
function isLocalRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
function formatChatSessionTime(value: number, language: string): string {
return new Intl.DateTimeFormat(language, { month: "short", day: "numeric", hour: "2-digit", minute: "2-digit" }).format(new Date(value));
}
const safeAssistantHTMLTags = new Set([
"a", "b", "blockquote", "br", "code", "del", "details", "div", "em", "h1", "h2", "h3", "h4", "h5", "h6",
"hr", "i", "img", "kbd", "li", "mark", "ol", "p", "pre", "s", "span", "strong", "sub", "summary", "sup", "table",
"tbody", "td", "tfoot", "th", "thead", "tr", "u", "ul",
]);
const discardedAssistantHTMLTags = new Set([
"applet", "audio", "base", "button", "canvas", "embed", "form", "frame", "frameset", "iframe", "input", "link",
"math", "meta", "object", "picture", "script", "select", "source", "style", "svg", "template", "textarea", "video",
]);
function renderAssistantMarkup(content: string): string {
const rendered = marked.parse(content, { async: false, breaks: true, gfm: true });
return sanitizeAssistantHTML(typeof rendered === "string" ? rendered : "");
}
function sanitizeAssistantHTML(content: string): string {
if (typeof DOMParser === "undefined") return "";
const source = content.trim();
if (!/<\/?[a-z][^>]*>/i.test(source)) return "";
const documentValue = new DOMParser().parseFromString(source, "text/html");
const elements = Array.from(documentValue.body.querySelectorAll("*"));
for (const element of elements) {
if (!element.isConnected) continue;
const tag = element.tagName.toLowerCase();
if (discardedAssistantHTMLTags.has(tag)) {
element.remove();
continue;
}
if (!safeAssistantHTMLTags.has(tag)) {
element.replaceWith(...Array.from(element.childNodes));
continue;
}
const href = tag === "a" ? safeAssistantLink(element.getAttribute("href")) : "";
const title = tag === "a" ? element.getAttribute("title")?.slice(0, 512) ?? "" : "";
const imageSource = tag === "img" ? safeAssistantImage(element.getAttribute("src")) : "";
const imageAlt = tag === "img" ? element.getAttribute("alt")?.slice(0, 512) ?? "" : "";
const colSpan = tag === "td" || tag === "th" ? boundedTableSpan(element.getAttribute("colspan")) : "";
const rowSpan = tag === "td" || tag === "th" ? boundedTableSpan(element.getAttribute("rowspan")) : "";
const open = tag === "details" && element.hasAttribute("open");
for (const attribute of Array.from(element.attributes)) element.removeAttribute(attribute.name);
if (href) {
element.setAttribute("href", href);
element.setAttribute("target", "_blank");
element.setAttribute("rel", "nofollow noopener noreferrer");
}
if (title) element.setAttribute("title", title);
if (imageSource) {
element.setAttribute("src", imageSource);
element.setAttribute("alt", imageAlt);
element.setAttribute("loading", "lazy");
element.setAttribute("decoding", "async");
element.setAttribute("referrerpolicy", "no-referrer");
} else if (tag === "img") {
element.remove();
continue;
}
if (colSpan) element.setAttribute("colspan", colSpan);
if (rowSpan) element.setAttribute("rowspan", rowSpan);
if (open) element.setAttribute("open", "");
}
return documentValue.body.innerHTML;
}
function safeAssistantLink(value: string | null): string {
const link = value?.trim() ?? "";
if (!link) return "";
try {
const parsed = new URL(link);
return parsed.protocol === "http:" || parsed.protocol === "https:" || parsed.protocol === "mailto:" ? parsed.toString() : "";
} catch {
return "";
}
}
function safeAssistantImage(value: string | null): string {
const source = value?.trim() ?? "";
if (!source) return "";
if (source.startsWith("/v1/media/images/")) return source;
try {
const parsed = new URL(source);
return parsed.protocol === "https:" ? parsed.toString() : "";
} catch {
return "";
}
}
function boundedTableSpan(value: string | null): string {
const parsed = Number.parseInt(value ?? "", 10);
return Number.isInteger(parsed) && parsed >= 1 && parsed <= 100 ? String(parsed) : "";
}
async function listAllPaginatedItems<T>(loadPage: (page: number, pageSize: number) => Promise<{ items: T[]; total: number }>): Promise<T[]> {
const items: T[] = [];
for (let page = 1; page <= 50; page += 1) {
+44 -14
View File
@@ -181,11 +181,10 @@ const resources = {
creativeConsole: {
title: "创作控制台",
description: "使用已创建的客户端密钥直接测试聊天、图片和视频生成。",
promotion: "想要更完整的 AI 创作体验?试试我开发的另一个项目 {{product}}:开箱即用的轻量 Web Chat,支持多模型对话与图片生成,静态运行时仅约 34 MB。",
promotionAction: "了解 DEEIX Chat",
clientKey: "客户端密钥",
selectKey: "选择客户端密钥",
keyReady: "密钥就绪",
keyLocked: "密钥未加载",
loadKey: "加载密钥",
modes: { chat: "聊天", image: "图片", video: "视频" },
welcome: "今天想创作什么?",
welcomeImage: "描述你的想法,生成一幅图片",
@@ -193,15 +192,29 @@ const resources = {
model: "模型",
selectModel: "选择模型",
noModels: "暂无可用模型",
systemPrompt: "系统提示词",
systemPromptPlaceholder: "可选:设定助手角色、语气或输出格式。",
webSearch: "联网搜索",
webSearchOn: "开启联网搜索",
webSearchOff: "关闭联网搜索",
xSearch: "X 搜索",
xSearchOn: "开启 X 搜索",
xSearchOff: "关闭 X 搜索",
reasoningEffort: "推理模式",
reasoning: { auto: "自动", none: "关闭", low: "低", medium: "中等", high: "高", xhigh: "极高" },
thinkingProcess: "思考过程",
streaming: "正在生成",
toolCall: "工具调用",
toolNames: { webSearch: "联网搜索", xSearch: "X 搜索" },
toolStatus: { in_progress: "执行中", completed: "已完成", failed: "失败" },
chatPlaceholder: "输入要发送给模型的内容。",
imagePlaceholder: "描述要生成的画面、主体、风格和细节。",
videoPlaceholder: "描述视频画面、动作、镜头和节奏。",
send: "发送",
messageList: "对话消息",
scrollToLatest: "滚动到最新消息",
clear: "清空",
newConversation: "新建对话",
clearCurrent: "清空本轮会话",
history: "历史记录",
noHistory: "暂无历史记录",
thinking: "模型正在回复...",
count: "数量",
aspectRatio: "宽高比",
@@ -212,7 +225,9 @@ const resources = {
imageNumber: "图片 {{index}}",
open: "打开",
referenceImage: "参考图片 URL",
videoOptions: "视频参数",
referenceImageShort: "参考图片",
referenceImageAdded: "已添加图片",
clearReferenceImage: "移除参考图片",
duration: "时长(秒)",
generateVideo: "生成视频",
submittingVideo: "正在提交视频任务...",
@@ -1055,11 +1070,10 @@ const resources = {
creativeConsole: {
title: "Creative console",
description: "Use an existing client key to test chat, image, and video generation directly.",
promotion: "Looking for a more complete AI creation experience? Try another project I built, {{product}}: a lightweight, ready-to-deploy Web Chat for multi-model conversations and image generation with a static runtime footprint of about 34 MB.",
promotionAction: "Explore DEEIX Chat",
clientKey: "Client key",
selectKey: "Select a client key",
keyReady: "Key ready",
keyLocked: "Key locked",
loadKey: "Load key",
modes: { chat: "Chat", image: "Image", video: "Video" },
welcome: "What would you like to create today?",
welcomeImage: "Describe an idea and create an image",
@@ -1067,15 +1081,29 @@ const resources = {
model: "Model",
selectModel: "Select a model",
noModels: "No available models",
systemPrompt: "System prompt",
systemPromptPlaceholder: "Optional: set the assistant role, tone, or output format.",
webSearch: "Web search",
webSearchOn: "Enable web search",
webSearchOff: "Disable web search",
xSearch: "X search",
xSearchOn: "Enable X search",
xSearchOff: "Disable X search",
reasoningEffort: "Reasoning mode",
reasoning: { auto: "Auto", none: "Off", low: "Low", medium: "Medium", high: "High", xhigh: "Extra high" },
thinkingProcess: "Reasoning",
streaming: "Generating",
toolCall: "Tool call",
toolNames: { webSearch: "Web search", xSearch: "X search" },
toolStatus: { in_progress: "Running", completed: "Completed", failed: "Failed" },
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.",
send: "Send",
messageList: "Conversation messages",
scrollToLatest: "Scroll to latest message",
clear: "Clear",
newConversation: "New conversation",
clearCurrent: "Clear current conversation",
history: "History",
noHistory: "No conversation history",
thinking: "The model is replying...",
count: "Count",
aspectRatio: "Aspect ratio",
@@ -1086,7 +1114,9 @@ const resources = {
imageNumber: "Image {{index}}",
open: "Open",
referenceImage: "Reference image URL",
videoOptions: "Video options",
referenceImageShort: "Reference image",
referenceImageAdded: "Image added",
clearReferenceImage: "Remove reference image",
duration: "Duration (seconds)",
generateVideo: "Generate video",
submittingVideo: "Submitting video job...",