refactor(web): 前端目录重构 — consoles/pages → layouts/features + shared
- consoles/admin/ → layouts/admin-layout/ - consoles/workbench/ → layouts/workbench-layout/ + features/chat/ - pages/ → features/ (dashboard, models, projects, not-found) - components/ → shared/components/ - hooks/ → shared/hooks/ - utils/ → shared/utils/ - 更新所有 import 路径 (src/web/ + tests/web/) - 更新开发文档 (README.md, frontend.md, architecture.md)
This commit is contained in:
93
src/web/features/chat/ChatPage.tsx
Normal file
93
src/web/features/chat/ChatPage.tsx
Normal file
@@ -0,0 +1,93 @@
|
||||
import { DeleteOutlined, MoreOutlined } from "@ant-design/icons";
|
||||
import { Conversations } from "@ant-design/x";
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { App, Spin } from "antd";
|
||||
import { useState } from "react";
|
||||
|
||||
import type { Conversation } from "../../../shared/api";
|
||||
|
||||
import { useCurrentProject } from "../../layouts/workbench-layout/useCurrentProject";
|
||||
import { createConversation, deleteConversation, fetchConversations } from "../../shared/hooks/use-conversations";
|
||||
import { useModelList } from "../../shared/hooks/use-models";
|
||||
import { ChatPanel } from "./ChatPanel";
|
||||
|
||||
export function ChatPage() {
|
||||
const project = useCurrentProject();
|
||||
const [activeConversationId, setActiveConversationId] = useState<null | string>(null);
|
||||
const queryClient = useQueryClient();
|
||||
const { message } = App.useApp();
|
||||
|
||||
const CONVERSATIONS_KEY = ["conversations", project.id] as const;
|
||||
|
||||
const { data, isLoading } = useQuery({
|
||||
queryFn: () => fetchConversations(project.id),
|
||||
queryKey: CONVERSATIONS_KEY,
|
||||
});
|
||||
|
||||
const { data: modelsData } = useModelList({ pageSize: 200 });
|
||||
const textModels = (modelsData?.items ?? []).filter((m) => m.capabilities.includes("text"));
|
||||
const defaultModelId = textModels[0]?.id;
|
||||
|
||||
const deleteMutation = useMutation({
|
||||
mutationFn: (id: string) => deleteConversation(project.id, id),
|
||||
onError: (err: Error) => {
|
||||
void message.error(`删除会话失败:${err.message}`);
|
||||
},
|
||||
onSuccess: (_data: void, id: string) => {
|
||||
void queryClient.invalidateQueries({ queryKey: CONVERSATIONS_KEY });
|
||||
if (activeConversationId === id) setActiveConversationId(null);
|
||||
},
|
||||
});
|
||||
|
||||
const conversations = (data?.items ?? []).map((c: Conversation) => ({
|
||||
key: c.id,
|
||||
label: c.title,
|
||||
}));
|
||||
|
||||
return (
|
||||
<div className="app-chat-page">
|
||||
<div className="app-chat-conversations">
|
||||
{isLoading ? (
|
||||
<Spin />
|
||||
) : (
|
||||
<Conversations
|
||||
activeKey={activeConversationId ?? ""}
|
||||
creation={{
|
||||
onClick: () => {
|
||||
void createConversation(project.id, defaultModelId)
|
||||
.then((conv) => {
|
||||
void queryClient.invalidateQueries({ queryKey: CONVERSATIONS_KEY });
|
||||
setActiveConversationId(conv.id);
|
||||
})
|
||||
.catch((err: Error) => {
|
||||
void message.error(`创建会话失败:${err.message}`);
|
||||
});
|
||||
},
|
||||
}}
|
||||
items={conversations}
|
||||
menu={(conv) => ({
|
||||
items: [
|
||||
{
|
||||
danger: true,
|
||||
icon: <DeleteOutlined />,
|
||||
key: "delete",
|
||||
label: "删除",
|
||||
onClick: () => {
|
||||
deleteMutation.mutate(conv.key);
|
||||
},
|
||||
},
|
||||
],
|
||||
trigger: <MoreOutlined />,
|
||||
})}
|
||||
onActiveChange={(key) => setActiveConversationId(key)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
<ChatPanel
|
||||
conversationId={activeConversationId}
|
||||
onConversationCreated={setActiveConversationId}
|
||||
projectId={project.id}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
455
src/web/features/chat/ChatPanel.tsx
Normal file
455
src/web/features/chat/ChatPanel.tsx
Normal file
@@ -0,0 +1,455 @@
|
||||
import { useChat } from "@ai-sdk/react";
|
||||
import { CopyOutlined, EditOutlined, RedoOutlined, RobotOutlined } from "@ant-design/icons";
|
||||
import { Sender } from "@ant-design/x";
|
||||
import { useQueryClient } from "@tanstack/react-query";
|
||||
import { DefaultChatTransport, type UIMessage } from "ai";
|
||||
import { App, Button, Card, Divider, Flex, Input, Select, Spin, Typography } from "antd";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
|
||||
import {
|
||||
createConversation,
|
||||
fetchConversation,
|
||||
fetchMessages,
|
||||
updateConversation,
|
||||
} from "../../shared/hooks/use-conversations";
|
||||
import { useLogger } from "../../shared/hooks/use-logger";
|
||||
import { useModelList } from "../../shared/hooks/use-models";
|
||||
import { ChatScrollArea } from "./ChatScrollArea";
|
||||
import { ReasoningPart } from "./parts/ReasoningPart";
|
||||
import { TextPart } from "./parts/TextPart";
|
||||
import { ToolPart } from "./parts/ToolPart";
|
||||
|
||||
interface ChatPanelProps {
|
||||
conversationId: null | string;
|
||||
onConversationCreated: (id: string) => void;
|
||||
projectId: string;
|
||||
}
|
||||
|
||||
export function ChatPanel({ conversationId, onConversationCreated, projectId }: ChatPanelProps) {
|
||||
const { message } = App.useApp();
|
||||
const logger = useLogger({ component: "ChatPanel", page: "workbench" });
|
||||
const queryClient = useQueryClient();
|
||||
const [input, setInput] = useState("");
|
||||
const [editingMessageId, setEditingMessageId] = useState<null | string>(null);
|
||||
const [editText, setEditText] = useState("");
|
||||
const [loadingHistory, setLoadingHistory] = useState(false);
|
||||
const [selectedModelId, setSelectedModelId] = useState<null | string>(null);
|
||||
const fetchRef = useRef(fetchMessages);
|
||||
const skipHistoryLoadRef = useRef<null | string>(null);
|
||||
|
||||
const { data: modelsData } = useModelList({ pageSize: 200 });
|
||||
const textModels = useMemo(
|
||||
() => (modelsData?.items ?? []).filter((m) => m.capabilities.includes("text")),
|
||||
[modelsData],
|
||||
);
|
||||
|
||||
const modelOptions = useMemo(() => textModels.map((m) => ({ label: m.name, value: m.id })), [textModels]);
|
||||
|
||||
const { messages, regenerate, sendMessage, setMessages, status, stop } = useChat({
|
||||
onError: (err) => {
|
||||
logger.error("聊天发送失败", { error: err.message });
|
||||
void message.error(`发送失败:${err.message}`);
|
||||
},
|
||||
transport: new DefaultChatTransport({ api: `/api/projects/${projectId}/chat` }),
|
||||
});
|
||||
|
||||
const isLoading = status === "submitted" || status === "streaming";
|
||||
|
||||
useEffect(() => {
|
||||
if (!conversationId) {
|
||||
setMessages([]);
|
||||
return;
|
||||
}
|
||||
|
||||
if (skipHistoryLoadRef.current === conversationId) {
|
||||
skipHistoryLoadRef.current = null;
|
||||
return;
|
||||
}
|
||||
|
||||
let cancelled = false;
|
||||
|
||||
const load = async () => {
|
||||
setLoadingHistory(true);
|
||||
setInput("");
|
||||
setMessages([]);
|
||||
try {
|
||||
const msgPromise = fetchRef.current(projectId, conversationId);
|
||||
|
||||
const data = await msgPromise;
|
||||
if (cancelled) return;
|
||||
|
||||
const history = data.items
|
||||
.filter((m: { role: string }) => m.role === "user" || m.role === "assistant")
|
||||
.reverse()
|
||||
.map((m: { content: string; id: string; parts: null | string; role: string }) => ({
|
||||
id: m.id,
|
||||
parts: m.parts ? (JSON.parse(m.parts) as UIMessage["parts"]) : [{ text: m.content, type: "text" as const }],
|
||||
role: m.role as "assistant" | "user",
|
||||
}));
|
||||
setMessages(history);
|
||||
} catch (err: unknown) {
|
||||
if (!cancelled) {
|
||||
const msg = err instanceof Error ? err.message : String(err);
|
||||
logger.error("加载历史失败", { conversationId, error: msg, projectId });
|
||||
void message.error(`加载历史失败:${msg}`);
|
||||
}
|
||||
} finally {
|
||||
if (!cancelled) setLoadingHistory(false);
|
||||
}
|
||||
};
|
||||
|
||||
void load();
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [conversationId, projectId, setMessages, message, logger]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!conversationId) return;
|
||||
const firstTextId = textModels[0]?.id;
|
||||
if (!firstTextId) return;
|
||||
|
||||
void fetchConversation(projectId, conversationId)
|
||||
.then((conv) => {
|
||||
if (textModels.every((m) => m.id !== conv.modelId)) {
|
||||
setSelectedModelId(firstTextId);
|
||||
void updateConversation(projectId, conversationId, { modelId: firstTextId });
|
||||
} else {
|
||||
setSelectedModelId(conv.modelId);
|
||||
}
|
||||
})
|
||||
.catch((err: unknown) => {
|
||||
const msg = err instanceof Error ? err.message : String(err);
|
||||
logger.warn("获取会话模型信息失败", { conversationId, error: msg, projectId });
|
||||
});
|
||||
}, [conversationId, textModels, projectId, logger]);
|
||||
|
||||
useEffect(() => {
|
||||
if (status === "ready" && conversationId) {
|
||||
void queryClient.invalidateQueries({ queryKey: ["conversations", projectId] });
|
||||
}
|
||||
}, [status, conversationId, projectId, queryClient]);
|
||||
|
||||
const displayModelId = conversationId ? selectedModelId : (textModels[0]?.id ?? null);
|
||||
|
||||
const handleModelChange = useCallback(
|
||||
(value: string) => {
|
||||
setSelectedModelId(value);
|
||||
if (conversationId) {
|
||||
void updateConversation(projectId, conversationId, { modelId: value }).catch((err: unknown) => {
|
||||
const msg = err instanceof Error ? err.message : String(err);
|
||||
logger.warn("更新会话模型失败", { conversationId, error: msg, projectId });
|
||||
});
|
||||
}
|
||||
},
|
||||
[projectId, conversationId, logger],
|
||||
);
|
||||
|
||||
const handleSenderSubmit = useCallback(
|
||||
(msg: string) => {
|
||||
if (!msg.trim()) return;
|
||||
|
||||
if (!conversationId) {
|
||||
void (async () => {
|
||||
try {
|
||||
const conv = await createConversation(projectId, displayModelId ?? undefined);
|
||||
skipHistoryLoadRef.current = conv.id;
|
||||
void queryClient.invalidateQueries({ queryKey: ["conversations", projectId] });
|
||||
void sendMessage({ text: msg }, { body: { conversationId: conv.id } });
|
||||
setInput("");
|
||||
onConversationCreated(conv.id);
|
||||
} catch (err: unknown) {
|
||||
setInput(msg);
|
||||
const errMsg = err instanceof Error ? err.message : String(err);
|
||||
logger.error("创建会话失败", { error: errMsg, projectId });
|
||||
void message.error(`创建会话失败:${errMsg}`);
|
||||
}
|
||||
})();
|
||||
return;
|
||||
}
|
||||
|
||||
setInput("");
|
||||
void sendMessage({ text: msg }, { body: { conversationId } }).catch((err: unknown) => {
|
||||
const errMsg = err instanceof Error ? err.message : String(err);
|
||||
logger.error("发送消息失败", { conversationId, error: errMsg, projectId });
|
||||
});
|
||||
},
|
||||
[sendMessage, conversationId, projectId, onConversationCreated, message, queryClient, displayModelId, logger],
|
||||
);
|
||||
|
||||
const extractText = useCallback((msg: UIMessage) => {
|
||||
return msg.parts
|
||||
.filter((p) => p.type === "text")
|
||||
.map((p) => (p as { text: string; type: "text" }).text)
|
||||
.join("");
|
||||
}, []);
|
||||
|
||||
const handleCopy = useCallback(
|
||||
(msg: UIMessage) => {
|
||||
const text = extractText(msg);
|
||||
void navigator.clipboard
|
||||
.writeText(text)
|
||||
.then(() => {
|
||||
void message.success("已复制");
|
||||
})
|
||||
.catch((err: unknown) => {
|
||||
const msg = err instanceof Error ? err.message : String(err);
|
||||
logger.warn("复制失败", { error: msg });
|
||||
});
|
||||
},
|
||||
[extractText, message, logger],
|
||||
);
|
||||
|
||||
const handleEditStart = useCallback(
|
||||
(msg: UIMessage) => {
|
||||
setEditingMessageId(msg.id);
|
||||
setEditText(extractText(msg));
|
||||
},
|
||||
[extractText],
|
||||
);
|
||||
|
||||
const handleEditConfirm = useCallback(() => {
|
||||
if (!editText.trim() || !conversationId) return;
|
||||
setEditingMessageId(null);
|
||||
const idx = messages.findIndex((m) => m.id === editingMessageId);
|
||||
if (idx === -1) return;
|
||||
setMessages(messages.slice(0, idx));
|
||||
void sendMessage({ text: editText }, { body: { conversationId } }).catch((err: unknown) => {
|
||||
const msg = err instanceof Error ? err.message : String(err);
|
||||
logger.error("重新发送消息失败", { conversationId, error: msg, projectId });
|
||||
});
|
||||
}, [editText, conversationId, messages, editingMessageId, setMessages, sendMessage, logger, projectId]);
|
||||
|
||||
const handleEditCancel = useCallback(() => {
|
||||
setEditingMessageId(null);
|
||||
setEditText("");
|
||||
}, []);
|
||||
|
||||
const handleRegenerate = useCallback(() => {
|
||||
if (!conversationId) return;
|
||||
void regenerate({ body: { conversationId } }).catch((err: unknown) => {
|
||||
const msg = err instanceof Error ? err.message : String(err);
|
||||
logger.error("重新生成失败", { conversationId, error: msg, projectId });
|
||||
});
|
||||
}, [regenerate, conversationId, logger, projectId]);
|
||||
|
||||
const getCardExtra = useCallback(
|
||||
(msg: UIMessage, idx: number) => {
|
||||
const isLast = idx === messages.length - 1;
|
||||
const lastUserIdx = messages.findLastIndex((m) => m.role === "user");
|
||||
const isLastUser = lastUserIdx >= 0 && idx === lastUserIdx;
|
||||
const isLastAssistant = isLast && msg.role === "assistant";
|
||||
const isEditing = editingMessageId === msg.id;
|
||||
|
||||
if (isLoading) return null;
|
||||
|
||||
const buttons: React.ReactNode[] = [];
|
||||
|
||||
buttons.push(
|
||||
<Button
|
||||
className="btn-dimmed"
|
||||
icon={<CopyOutlined />}
|
||||
key="copy"
|
||||
onClick={() => handleCopy(msg)}
|
||||
size="small"
|
||||
type="text"
|
||||
/>,
|
||||
);
|
||||
|
||||
if (isLastUser && !isEditing) {
|
||||
buttons.push(
|
||||
<Button
|
||||
className="btn-dimmed"
|
||||
icon={<EditOutlined />}
|
||||
key="edit"
|
||||
onClick={() => handleEditStart(msg)}
|
||||
size="small"
|
||||
type="text"
|
||||
/>,
|
||||
);
|
||||
}
|
||||
|
||||
if (isLastAssistant) {
|
||||
buttons.push(
|
||||
<Button
|
||||
className="btn-dimmed"
|
||||
icon={<RedoOutlined />}
|
||||
key="regenerate"
|
||||
onClick={handleRegenerate}
|
||||
size="small"
|
||||
type="text"
|
||||
/>,
|
||||
);
|
||||
}
|
||||
|
||||
return <Flex gap={4}>{buttons}</Flex>;
|
||||
},
|
||||
[messages, isLoading, editingMessageId, handleCopy, handleEditStart, handleRegenerate],
|
||||
);
|
||||
|
||||
if (!conversationId) {
|
||||
return (
|
||||
<div className="app-chat-panel">
|
||||
<div className="chat-welcome-area">
|
||||
<Flex align="center" gap={12} vertical>
|
||||
<RobotOutlined className="welcome-icon" />
|
||||
<Typography.Title className="welcome-title" level={3}>
|
||||
你好,我是阿福
|
||||
</Typography.Title>
|
||||
<Typography.Text type="secondary">有什么我可以帮助你的吗?</Typography.Text>
|
||||
</Flex>
|
||||
</div>
|
||||
<div className="chat-sender-area">
|
||||
<Sender
|
||||
autoSize={{ maxRows: 3, minRows: 1 }}
|
||||
classNames={{ root: "chat-sender-box" }}
|
||||
footer={(actionNode) => (
|
||||
<Flex align="center" justify="space-between">
|
||||
<Select
|
||||
className="chat-model-select"
|
||||
disabled={isLoading}
|
||||
onChange={handleModelChange}
|
||||
options={modelOptions}
|
||||
placeholder="选择模型"
|
||||
value={displayModelId}
|
||||
/>
|
||||
<Flex align="center">
|
||||
<Divider orientation="vertical" />
|
||||
{actionNode}
|
||||
</Flex>
|
||||
</Flex>
|
||||
)}
|
||||
loading={isLoading}
|
||||
onCancel={() => {
|
||||
void stop().catch((err: unknown) => {
|
||||
const msg = err instanceof Error ? err.message : String(err);
|
||||
logger.warn("停止聊天失败", { error: msg });
|
||||
});
|
||||
}}
|
||||
onChange={setInput}
|
||||
onSubmit={handleSenderSubmit}
|
||||
placeholder="输入消息..."
|
||||
suffix={false}
|
||||
value={input}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="app-chat-panel">
|
||||
{loadingHistory ? (
|
||||
<div className="app-chat-panel-loading">
|
||||
<Spin />
|
||||
</div>
|
||||
) : (
|
||||
<ChatScrollArea messages={messages} status={status}>
|
||||
<Flex gap={8} vertical>
|
||||
{messages.map((msg, idx) => (
|
||||
<Card
|
||||
classNames={{ extra: "card-extra-actions" }}
|
||||
extra={getCardExtra(msg, idx)}
|
||||
key={msg.id}
|
||||
size="small"
|
||||
title={msg.role === "user" ? "用户" : <span className="msg-title-ai">阿福</span>}
|
||||
>
|
||||
<div className="message-body">
|
||||
{editingMessageId === msg.id ? (
|
||||
<Flex gap={8} vertical>
|
||||
<Input.TextArea
|
||||
autoSize={{ maxRows: 6, minRows: 1 }}
|
||||
onChange={(e) => setEditText(e.target.value)}
|
||||
value={editText}
|
||||
/>
|
||||
<Flex gap={8} justify="flex-end">
|
||||
<Button onClick={handleEditCancel} size="small">
|
||||
取消
|
||||
</Button>
|
||||
<Button onClick={handleEditConfirm} size="small" type="primary">
|
||||
确认
|
||||
</Button>
|
||||
</Flex>
|
||||
</Flex>
|
||||
) : (
|
||||
msg.parts.map((part: Record<string, unknown>, i: number) => (
|
||||
<PartRenderer
|
||||
isStreaming={isLoading && idx === messages.length - 1 && msg.role === "assistant"}
|
||||
key={i}
|
||||
part={part}
|
||||
role={msg.role}
|
||||
/>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</Card>
|
||||
))}
|
||||
{isLoading && (
|
||||
<Flex className="chat-loading-indicator" justify="center">
|
||||
<Spin size="small" />
|
||||
</Flex>
|
||||
)}
|
||||
</Flex>
|
||||
</ChatScrollArea>
|
||||
)}
|
||||
<div className="chat-sender-area">
|
||||
<Sender
|
||||
autoSize={{ maxRows: 3, minRows: 1 }}
|
||||
classNames={{ root: "chat-sender-box" }}
|
||||
footer={(actionNode) => (
|
||||
<Flex align="center" justify="space-between">
|
||||
<Select
|
||||
className="chat-model-select"
|
||||
disabled={isLoading}
|
||||
onChange={handleModelChange}
|
||||
options={modelOptions}
|
||||
placeholder="选择模型"
|
||||
value={displayModelId}
|
||||
/>
|
||||
<Flex align="center">
|
||||
<Divider orientation="vertical" />
|
||||
{actionNode}
|
||||
</Flex>
|
||||
</Flex>
|
||||
)}
|
||||
loading={isLoading}
|
||||
onCancel={() => {
|
||||
void stop().catch((err: unknown) => {
|
||||
const msg = err instanceof Error ? err.message : String(err);
|
||||
logger.warn("停止聊天失败", { error: msg });
|
||||
});
|
||||
}}
|
||||
onChange={setInput}
|
||||
onSubmit={handleSenderSubmit}
|
||||
placeholder="输入消息..."
|
||||
suffix={false}
|
||||
value={input}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function PartRenderer({
|
||||
isStreaming,
|
||||
part,
|
||||
role,
|
||||
}: {
|
||||
isStreaming: boolean;
|
||||
part: Record<string, unknown>;
|
||||
role: string;
|
||||
}) {
|
||||
const partType = typeof part["type"] === "string" ? part["type"] : "";
|
||||
|
||||
if (partType === "text") {
|
||||
return <TextPart isStreaming={isStreaming} part={part} role={role} />;
|
||||
}
|
||||
if (partType.startsWith("tool-")) {
|
||||
return <ToolPart part={part} />;
|
||||
}
|
||||
if (partType === "reasoning") {
|
||||
return <ReasoningPart part={part} />;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
63
src/web/features/chat/ChatScrollArea.tsx
Normal file
63
src/web/features/chat/ChatScrollArea.tsx
Normal file
@@ -0,0 +1,63 @@
|
||||
import type { UIMessage } from "ai";
|
||||
|
||||
import { ArrowDownOutlined } from "@ant-design/icons";
|
||||
import { Button } from "antd";
|
||||
import "overlayscrollbars/styles/overlayscrollbars.css";
|
||||
import { OverlayScrollbarsComponent, type OverlayScrollbarsComponentRef } from "overlayscrollbars-react";
|
||||
import { useCallback, useRef, useState } from "react";
|
||||
|
||||
import { useIsDark } from "../../shared/hooks/use-is-dark";
|
||||
import { useChatScroll } from "./use-chat-scroll";
|
||||
|
||||
interface ChatScrollAreaProps {
|
||||
children: React.ReactNode;
|
||||
messages: UIMessage[];
|
||||
status: string;
|
||||
}
|
||||
|
||||
export function ChatScrollArea({ children, messages, status }: ChatScrollAreaProps) {
|
||||
const scrollRef = useRef<HTMLDivElement>(null);
|
||||
const osRef = useRef<OverlayScrollbarsComponentRef>(null);
|
||||
const [viewportElement, setViewportElement] = useState<HTMLDivElement | null>(null);
|
||||
const isDark = useIsDark();
|
||||
|
||||
const handleOsInitialized = useCallback(() => {
|
||||
const os = osRef.current;
|
||||
if (!os) return;
|
||||
const instance = os.osInstance();
|
||||
if (!instance) return;
|
||||
const viewport = instance.elements().viewport as HTMLDivElement;
|
||||
scrollRef.current = viewport;
|
||||
setViewportElement(viewport);
|
||||
}, []);
|
||||
|
||||
const { isAtBottom, scrollToBottom } = useChatScroll({ messages, scrollRef, status, viewportElement });
|
||||
|
||||
return (
|
||||
<>
|
||||
<OverlayScrollbarsComponent
|
||||
className="chat-scroll-area"
|
||||
events={{ initialized: handleOsInitialized }}
|
||||
options={{
|
||||
overflow: { x: "hidden", y: "scroll" },
|
||||
scrollbars: {
|
||||
autoHide: "move",
|
||||
theme: isDark ? "os-theme-custom-dark" : "os-theme-custom",
|
||||
},
|
||||
}}
|
||||
ref={osRef}
|
||||
>
|
||||
{children}
|
||||
</OverlayScrollbarsComponent>
|
||||
{!isAtBottom && (
|
||||
<Button
|
||||
className="chat-scroll-bottom-btn"
|
||||
icon={<ArrowDownOutlined />}
|
||||
onClick={scrollToBottom}
|
||||
shape="circle"
|
||||
size="small"
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
82
src/web/features/chat/parts/CodeBlockWithCopy.tsx
Normal file
82
src/web/features/chat/parts/CodeBlockWithCopy.tsx
Normal file
@@ -0,0 +1,82 @@
|
||||
import { CopyOutlined } from "@ant-design/icons";
|
||||
import { CodeHighlighter } from "@ant-design/x";
|
||||
import { App, Button, Flex, Typography } from "antd";
|
||||
import React from "react";
|
||||
import { oneDark, oneLight } from "react-syntax-highlighter/dist/esm/styles/prism";
|
||||
|
||||
import { useIsDark } from "../../../shared/hooks/use-is-dark";
|
||||
|
||||
type SyntaxTheme = Record<string, Record<string, null | number | string>>;
|
||||
|
||||
const customOneDark: SyntaxTheme = {
|
||||
...(oneDark as SyntaxTheme),
|
||||
'pre[class*="language-"]': {
|
||||
...(oneDark as SyntaxTheme)['pre[class*="language-"]'],
|
||||
margin: 0,
|
||||
},
|
||||
};
|
||||
|
||||
const customOneLight: SyntaxTheme = {
|
||||
...(oneLight as SyntaxTheme),
|
||||
'pre[class*="language-"]': {
|
||||
...(oneLight as SyntaxTheme)['pre[class*="language-"]'],
|
||||
margin: 0,
|
||||
},
|
||||
};
|
||||
|
||||
interface CodeBlockWithCopyProps {
|
||||
block?: boolean;
|
||||
children?: React.ReactNode;
|
||||
className?: string;
|
||||
lang?: string;
|
||||
streamStatus?: "done" | "loading";
|
||||
}
|
||||
|
||||
export function CodeBlockWithCopy({ block, children, className, lang }: CodeBlockWithCopyProps) {
|
||||
const { message } = App.useApp();
|
||||
const isDark = useIsDark();
|
||||
|
||||
if (!block) {
|
||||
return <code className={className}>{children}</code>;
|
||||
}
|
||||
|
||||
const codeText = extractText(children);
|
||||
const displayLang = lang ?? "plaintext";
|
||||
|
||||
const handleCopy = () => {
|
||||
void navigator.clipboard.writeText(codeText).then(() => {
|
||||
void message.success("已复制");
|
||||
});
|
||||
};
|
||||
|
||||
const header = (
|
||||
<Flex align="center" justify="space-between" style={{ padding: "0 4px" }}>
|
||||
<Typography.Text style={{ color: "var(--ant-color-text-quaternary)", fontSize: 12 }}>
|
||||
{displayLang}
|
||||
</Typography.Text>
|
||||
<Button
|
||||
icon={<CopyOutlined />}
|
||||
onClick={handleCopy}
|
||||
size="small"
|
||||
style={{ color: "var(--ant-color-text-quaternary)" }}
|
||||
type="text"
|
||||
/>
|
||||
</Flex>
|
||||
);
|
||||
|
||||
return (
|
||||
<CodeHighlighter
|
||||
header={header}
|
||||
highlightProps={{ style: (isDark ? customOneDark : customOneLight) as React.CSSProperties }}
|
||||
lang={displayLang}
|
||||
>
|
||||
{codeText}
|
||||
</CodeHighlighter>
|
||||
);
|
||||
}
|
||||
|
||||
function extractText(children: React.ReactNode): string {
|
||||
return React.Children.toArray(children)
|
||||
.map((child) => (typeof child === "string" ? child : ""))
|
||||
.join("");
|
||||
}
|
||||
55
src/web/features/chat/parts/ReasoningPart.tsx
Normal file
55
src/web/features/chat/parts/ReasoningPart.tsx
Normal file
@@ -0,0 +1,55 @@
|
||||
import { CheckCircleFilled, LoadingOutlined } from "@ant-design/icons";
|
||||
import { Collapse, Flex, Typography } from "antd";
|
||||
import { useCallback, useMemo, useState } from "react";
|
||||
|
||||
import type { PartProps } from "./types";
|
||||
|
||||
const REASONING_KEY = "reasoning";
|
||||
|
||||
export function ReasoningPart({ part }: PartProps) {
|
||||
const text = typeof part["text"] === "string" ? part["text"] : "";
|
||||
const state = typeof part["state"] === "string" ? part["state"] : "";
|
||||
const isStreaming = state === "streaming";
|
||||
|
||||
const [userToggled, setUserToggled] = useState(false);
|
||||
const [userActiveKey, setUserActiveKey] = useState<string[]>([]);
|
||||
|
||||
const autoActiveKey = useMemo(() => {
|
||||
if (isStreaming) return [REASONING_KEY];
|
||||
if (state === "complete" || text.length > 0) return [];
|
||||
return [];
|
||||
}, [isStreaming, state, text]);
|
||||
|
||||
const activeKey = userToggled ? userActiveKey : autoActiveKey;
|
||||
|
||||
const handleChange = useCallback((keys: string | string[]) => {
|
||||
setUserToggled(true);
|
||||
setUserActiveKey(keys as string[]);
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<Collapse
|
||||
activeKey={activeKey}
|
||||
ghost
|
||||
items={[
|
||||
{
|
||||
children: <Typography.Text type="secondary">{text}</Typography.Text>,
|
||||
key: REASONING_KEY,
|
||||
label: isStreaming ? (
|
||||
<Flex align="center" component="span" gap={4}>
|
||||
<LoadingOutlined className="icon-primary" />
|
||||
<Typography.Text type="secondary">思考中</Typography.Text>
|
||||
</Flex>
|
||||
) : (
|
||||
<Flex align="center" component="span" gap={4}>
|
||||
<CheckCircleFilled className="icon-success" />
|
||||
<Typography.Text type="secondary">思考完成</Typography.Text>
|
||||
</Flex>
|
||||
),
|
||||
},
|
||||
]}
|
||||
onChange={handleChange}
|
||||
size="small"
|
||||
/>
|
||||
);
|
||||
}
|
||||
39
src/web/features/chat/parts/TextPart.tsx
Normal file
39
src/web/features/chat/parts/TextPart.tsx
Normal file
@@ -0,0 +1,39 @@
|
||||
import { XMarkdown } from "@ant-design/x-markdown";
|
||||
import "@ant-design/x-markdown/themes/dark.css";
|
||||
import "@ant-design/x-markdown/themes/light.css";
|
||||
import { Typography } from "antd";
|
||||
|
||||
import type { PartProps } from "./types";
|
||||
|
||||
import { useIsDark } from "../../../shared/hooks/use-is-dark";
|
||||
import { CodeBlockWithCopy } from "./CodeBlockWithCopy";
|
||||
|
||||
interface TextPartProps extends PartProps {
|
||||
isStreaming: boolean;
|
||||
role: string;
|
||||
}
|
||||
|
||||
const xmarkdownComponents = {
|
||||
code: CodeBlockWithCopy,
|
||||
pre: ({ children }: { children?: React.ReactNode }) => <>{children}</>,
|
||||
};
|
||||
|
||||
export function TextPart({ isStreaming, part, role }: TextPartProps) {
|
||||
const text = typeof part["text"] === "string" ? part["text"] : "";
|
||||
const isDark = useIsDark();
|
||||
|
||||
return (
|
||||
<div className="part-body">
|
||||
{role === "user" ? (
|
||||
<Typography.Paragraph className="message-body-text">{text}</Typography.Paragraph>
|
||||
) : (
|
||||
<XMarkdown
|
||||
className={isDark ? "x-markdown-dark" : "x-markdown-light"}
|
||||
components={xmarkdownComponents}
|
||||
content={text}
|
||||
streaming={{ hasNextChunk: isStreaming }}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
99
src/web/features/chat/parts/ToolPart.tsx
Normal file
99
src/web/features/chat/parts/ToolPart.tsx
Normal file
@@ -0,0 +1,99 @@
|
||||
import { CheckCircleFilled, CloseCircleFilled, LoadingOutlined } from "@ant-design/icons";
|
||||
import { Collapse, Flex, Typography } from "antd";
|
||||
|
||||
import type { PartProps } from "./types";
|
||||
|
||||
interface ToolPartData {
|
||||
errorText?: string;
|
||||
input?: unknown;
|
||||
output?: unknown;
|
||||
toolCallId?: string;
|
||||
toolMetadata?: Record<string, unknown>;
|
||||
toolName?: string;
|
||||
type?: string;
|
||||
}
|
||||
|
||||
function getToolState(part: ToolPartData) {
|
||||
if ("errorText" in part && part.errorText) return "output-error" as const;
|
||||
if ("output" in part) return "output-available" as const;
|
||||
if ("input" in part) return "input-available" as const;
|
||||
return "input-streaming" as const;
|
||||
}
|
||||
|
||||
const FORMAT_JSON = (v: unknown) => JSON.stringify(v, null, 2);
|
||||
|
||||
export function ToolPart({ part }: PartProps) {
|
||||
const toolPart = part as unknown as ToolPartData;
|
||||
const state = getToolState(toolPart);
|
||||
const rawToolName = toolPart.toolName ?? (toolPart.type ?? "unknown").replace(/^tool-/, "");
|
||||
const toolName =
|
||||
typeof toolPart.toolMetadata?.["displayName"] === "string" ? toolPart.toolMetadata["displayName"] : rawToolName;
|
||||
|
||||
const isStreaming = state === "input-streaming" || state === "input-available";
|
||||
|
||||
if (state === "output-error") {
|
||||
return (
|
||||
<Collapse
|
||||
ghost
|
||||
items={[
|
||||
{
|
||||
children: <Typography.Text type="danger">{toolPart.errorText}</Typography.Text>,
|
||||
key: toolPart.toolCallId ?? toolName,
|
||||
label: (
|
||||
<Flex align="center" component="span" gap={4}>
|
||||
<CloseCircleFilled className="icon-error" />
|
||||
<Typography.Text type="danger">{toolName} 失败</Typography.Text>
|
||||
</Flex>
|
||||
),
|
||||
},
|
||||
]}
|
||||
size="small"
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Collapse
|
||||
defaultActiveKey={isStreaming ? [toolPart.toolCallId ?? toolName] : undefined}
|
||||
ghost
|
||||
items={[
|
||||
{
|
||||
children: (
|
||||
<Flex gap={4} vertical>
|
||||
{toolPart.input != null && (
|
||||
<>
|
||||
<Typography.Text type="secondary">参数:</Typography.Text>
|
||||
<pre className="tool-result-pre">{FORMAT_JSON(toolPart.input)}</pre>
|
||||
</>
|
||||
)}
|
||||
{"output" in toolPart && toolPart.output != null && (
|
||||
<>
|
||||
<Typography.Text type="secondary">结果:</Typography.Text>
|
||||
<pre className="tool-result-pre">{FORMAT_JSON(toolPart.output)}</pre>
|
||||
</>
|
||||
)}
|
||||
{!toolPart.input && !("output" in toolPart) && (
|
||||
<Typography.Text type="secondary">生成中...</Typography.Text>
|
||||
)}
|
||||
</Flex>
|
||||
),
|
||||
key: toolPart.toolCallId ?? toolName,
|
||||
label: isStreaming ? (
|
||||
<Flex align="center" component="span" gap={4}>
|
||||
<LoadingOutlined className="icon-primary" />
|
||||
<Typography.Text type="secondary">
|
||||
{state === "input-streaming" ? "生成参数" : `调用 ${toolName}`}
|
||||
</Typography.Text>
|
||||
</Flex>
|
||||
) : (
|
||||
<Flex align="center" component="span" gap={4}>
|
||||
<CheckCircleFilled className="icon-success" />
|
||||
<Typography.Text type="secondary">{toolName}</Typography.Text>
|
||||
</Flex>
|
||||
),
|
||||
},
|
||||
]}
|
||||
size="small"
|
||||
/>
|
||||
);
|
||||
}
|
||||
3
src/web/features/chat/parts/types.ts
Normal file
3
src/web/features/chat/parts/types.ts
Normal file
@@ -0,0 +1,3 @@
|
||||
export interface PartProps {
|
||||
part: Record<string, unknown>;
|
||||
}
|
||||
70
src/web/features/chat/use-chat-scroll.ts
Normal file
70
src/web/features/chat/use-chat-scroll.ts
Normal file
@@ -0,0 +1,70 @@
|
||||
import type { UIMessage } from "ai";
|
||||
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
|
||||
const NEAR_BOTTOM_THRESHOLD = 80;
|
||||
|
||||
interface UseChatScrollOptions {
|
||||
loadingHistory?: boolean;
|
||||
messages: UIMessage[];
|
||||
scrollRef: React.RefObject<HTMLDivElement | null>;
|
||||
status: string;
|
||||
viewportElement: HTMLDivElement | null;
|
||||
}
|
||||
|
||||
export function useChatScroll({ loadingHistory, messages, scrollRef, status, viewportElement }: UseChatScrollOptions) {
|
||||
const [isAtBottom, setIsAtBottom] = useState(true);
|
||||
const isStreaming = status === "streaming";
|
||||
const prevLoadingRef = useRef(loadingHistory ?? false);
|
||||
|
||||
const checkNearBottom = useCallback(() => {
|
||||
const el = scrollRef.current;
|
||||
if (!el) return true;
|
||||
return el.scrollHeight - el.scrollTop - el.clientHeight < NEAR_BOTTOM_THRESHOLD;
|
||||
}, [scrollRef]);
|
||||
|
||||
useEffect(() => {
|
||||
const el = viewportElement;
|
||||
if (!el) return;
|
||||
|
||||
const handleScroll = () => {
|
||||
setIsAtBottom(checkNearBottom());
|
||||
};
|
||||
|
||||
el.addEventListener("scroll", handleScroll, { passive: true });
|
||||
return () => el.removeEventListener("scroll", handleScroll);
|
||||
}, [viewportElement, checkNearBottom]);
|
||||
|
||||
useEffect(() => {
|
||||
const wasLoading = prevLoadingRef.current;
|
||||
prevLoadingRef.current = loadingHistory ?? false;
|
||||
|
||||
if (wasLoading && !loadingHistory) {
|
||||
const el = scrollRef.current;
|
||||
if (!el) return;
|
||||
requestAnimationFrame(() => {
|
||||
const target = scrollRef.current;
|
||||
if (!target) return;
|
||||
target.scrollTo({ behavior: "instant", top: target.scrollHeight });
|
||||
setIsAtBottom(true);
|
||||
});
|
||||
return;
|
||||
}
|
||||
}, [loadingHistory, scrollRef]);
|
||||
|
||||
useEffect(() => {
|
||||
const el = scrollRef.current;
|
||||
if (!el || !isAtBottom) return;
|
||||
|
||||
el.scrollTo({ behavior: "instant", top: el.scrollHeight });
|
||||
}, [messages, isStreaming, isAtBottom, scrollRef]);
|
||||
|
||||
const scrollToBottom = useCallback(() => {
|
||||
const el = scrollRef.current;
|
||||
if (!el) return;
|
||||
el.scrollTo({ behavior: "instant", top: el.scrollHeight });
|
||||
setIsAtBottom(true);
|
||||
}, [scrollRef]);
|
||||
|
||||
return { isAtBottom, scrollToBottom };
|
||||
}
|
||||
32
src/web/features/dashboard/index.tsx
Normal file
32
src/web/features/dashboard/index.tsx
Normal file
@@ -0,0 +1,32 @@
|
||||
import type { DescriptionsProps } from "antd";
|
||||
|
||||
import { Alert, Card, Descriptions, Space, Spin, Typography } from "antd";
|
||||
|
||||
import { APP } from "../../../shared/app";
|
||||
import { useMeta } from "../../shared/hooks/use-meta";
|
||||
|
||||
export function DashboardPage() {
|
||||
const { data: meta, error, isLoading } = useMeta();
|
||||
|
||||
const descriptionItems: DescriptionsProps["items"] = meta
|
||||
? [
|
||||
{ children: meta.service, key: "service", label: "服务" },
|
||||
{ children: meta.version, key: "version", label: "版本" },
|
||||
{ children: meta.timestamp, key: "timestamp", label: "时间戳" },
|
||||
]
|
||||
: [];
|
||||
|
||||
return (
|
||||
<Space size="large" vertical>
|
||||
<Typography.Title level={2}>总览</Typography.Title>
|
||||
<Typography.Paragraph>欢迎使用 {APP.title}。以下是 /api/meta 的返回数据(前后端联调示例):</Typography.Paragraph>
|
||||
{isLoading && <Spin size="large" />}
|
||||
{error && <Alert description={error.message} showIcon title="加载失败" type="error" />}
|
||||
{meta && (
|
||||
<Card>
|
||||
<Descriptions column={1} items={descriptionItems} title="服务信息" />
|
||||
</Card>
|
||||
)}
|
||||
</Space>
|
||||
);
|
||||
}
|
||||
236
src/web/features/models/components/ModelFormModal.tsx
Normal file
236
src/web/features/models/components/ModelFormModal.tsx
Normal file
@@ -0,0 +1,236 @@
|
||||
import { App as AntApp, Button, Checkbox, Col, Form, Input, InputNumber, Modal, Row, Select, Space } from "antd";
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
import type {
|
||||
CreateModelRequest,
|
||||
Model,
|
||||
ModelCapability,
|
||||
ModelTestResponse,
|
||||
ProviderOption,
|
||||
TestModelRequest,
|
||||
UpdateModelRequest,
|
||||
} from "../../../../shared/api";
|
||||
|
||||
interface FormValues {
|
||||
capabilities: ModelCapability[];
|
||||
contextLength: null | number;
|
||||
maxOutputTokens: null | number;
|
||||
modelId: string;
|
||||
name: string;
|
||||
providerId: string;
|
||||
}
|
||||
|
||||
interface ModelFormModalProps {
|
||||
editingModel: Model | null;
|
||||
onCancel: () => void;
|
||||
onCreate: (data: CreateModelRequest) => Promise<unknown>;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
onUpdate: (args: { data: UpdateModelRequest; id: string }) => Promise<unknown>;
|
||||
open: boolean;
|
||||
providers: ProviderOption[];
|
||||
providersError: Error | null;
|
||||
providersLoading: boolean;
|
||||
submitting: boolean;
|
||||
testModelConnection?: (data: TestModelRequest) => Promise<ModelTestResponse>;
|
||||
}
|
||||
|
||||
const DEFAULT_CAPABILITIES: ModelCapability[] = ["text", "reasoning"];
|
||||
|
||||
const CAPABILITY_OPTIONS: Array<{ label: string; value: ModelCapability }> = [
|
||||
{ label: "文本", value: "text" },
|
||||
{ label: "推理", value: "reasoning" },
|
||||
{ label: "图片生成", value: "image-generation" },
|
||||
{ label: "视频生成", value: "video-generation" },
|
||||
{ label: "音频生成", value: "audio-generation" },
|
||||
{ label: "图片识别", value: "image-recognition" },
|
||||
{ label: "视频识别", value: "video-recognition" },
|
||||
{ label: "音频识别", value: "audio-recognition" },
|
||||
];
|
||||
|
||||
export function ModelFormModal({
|
||||
editingModel,
|
||||
onCancel,
|
||||
onCreate,
|
||||
onOpenChange,
|
||||
onUpdate,
|
||||
open,
|
||||
providers,
|
||||
providersError,
|
||||
providersLoading,
|
||||
submitting,
|
||||
testModelConnection,
|
||||
}: ModelFormModalProps) {
|
||||
const { message } = AntApp.useApp();
|
||||
const [form] = Form.useForm<FormValues>();
|
||||
const [testing, setTesting] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
if (editingModel) {
|
||||
form.setFieldsValue({
|
||||
capabilities: editingModel.capabilities,
|
||||
contextLength: editingModel.contextLength,
|
||||
maxOutputTokens: editingModel.maxOutputTokens,
|
||||
modelId: editingModel.modelId,
|
||||
name: editingModel.name,
|
||||
providerId: editingModel.providerId,
|
||||
});
|
||||
} else {
|
||||
form.resetFields();
|
||||
form.setFieldsValue({ capabilities: DEFAULT_CAPABILITIES });
|
||||
}
|
||||
}, [editingModel, form, open]);
|
||||
|
||||
const handleFinish = async (values: FormValues) => {
|
||||
try {
|
||||
if (editingModel) {
|
||||
const reqData: UpdateModelRequest = {};
|
||||
if (values.name !== editingModel.name) reqData.name = values.name;
|
||||
if (values.modelId !== editingModel.modelId) reqData.modelId = values.modelId;
|
||||
if (values.providerId !== editingModel.providerId) reqData.providerId = values.providerId;
|
||||
const capsChanged =
|
||||
values.capabilities.length !== editingModel.capabilities.length ||
|
||||
values.capabilities.some((c, i) => c !== editingModel.capabilities[i]);
|
||||
if (capsChanged) reqData.capabilities = values.capabilities;
|
||||
if (values.contextLength !== editingModel.contextLength) reqData.contextLength = values.contextLength;
|
||||
if (values.maxOutputTokens !== editingModel.maxOutputTokens) reqData.maxOutputTokens = values.maxOutputTokens;
|
||||
await onUpdate({ data: reqData, id: editingModel.id });
|
||||
message.success("模型已更新");
|
||||
} else {
|
||||
const reqData: CreateModelRequest = {
|
||||
capabilities: values.capabilities,
|
||||
contextLength: values.contextLength ?? undefined,
|
||||
maxOutputTokens: values.maxOutputTokens ?? undefined,
|
||||
modelId: values.modelId,
|
||||
name: values.name,
|
||||
providerId: values.providerId,
|
||||
};
|
||||
await onCreate(reqData);
|
||||
message.success("模型已创建");
|
||||
}
|
||||
onOpenChange(false);
|
||||
} catch (err: unknown) {
|
||||
if (err instanceof Error) {
|
||||
message.error(err.message);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const handleTest = async () => {
|
||||
if (!testModelConnection) return;
|
||||
const providerId: unknown = form.getFieldValue("providerId");
|
||||
const modelId: unknown = form.getFieldValue("modelId");
|
||||
if (typeof providerId !== "string" || !providerId) {
|
||||
message.warning("请先选择供应商");
|
||||
return;
|
||||
}
|
||||
if (typeof modelId !== "string" || !modelId) {
|
||||
message.warning("请先输入模型 ID");
|
||||
return;
|
||||
}
|
||||
setTesting(true);
|
||||
try {
|
||||
const result = await testModelConnection({ modelId, providerId });
|
||||
if (result.ok) {
|
||||
message.success(result.message);
|
||||
} else {
|
||||
message.error(result.message);
|
||||
}
|
||||
} catch (err: unknown) {
|
||||
message.error((err as Error).message);
|
||||
} finally {
|
||||
setTesting(false);
|
||||
}
|
||||
};
|
||||
|
||||
const providerOptions = providers.map((p) => ({ label: p.name, value: p.id }));
|
||||
|
||||
return (
|
||||
<Modal
|
||||
confirmLoading={submitting}
|
||||
destroyOnHidden
|
||||
okText="确定"
|
||||
onCancel={onCancel}
|
||||
onOk={() => void form.submit()}
|
||||
open={open}
|
||||
title={editingModel ? "编辑模型" : "新建模型"}
|
||||
width={600}
|
||||
>
|
||||
<Form form={form} layout="vertical" onFinish={(values) => void handleFinish(values)}>
|
||||
<Form.Item
|
||||
label="模型名称"
|
||||
name="name"
|
||||
rules={[{ message: "请输入模型名称", required: true, whitespace: true }]}
|
||||
>
|
||||
<Input placeholder="请输入模型名称" />
|
||||
</Form.Item>
|
||||
<Form.Item label="所属供应商" name="providerId" rules={[{ message: "请选择供应商", required: true }]}>
|
||||
<Select
|
||||
loading={providersLoading}
|
||||
notFoundContent={getProviderNotFoundContent(providersLoading, providersError)}
|
||||
optionFilterProp="label"
|
||||
options={providerOptions}
|
||||
placeholder="请选择供应商"
|
||||
showSearch
|
||||
status={providersError ? "error" : undefined}
|
||||
/>
|
||||
</Form.Item>
|
||||
<Form.Item
|
||||
label="模型 ID"
|
||||
name="modelId"
|
||||
rules={[{ message: "请输入模型 ID", required: true, whitespace: true }]}
|
||||
>
|
||||
<Input placeholder="gpt-4o, claude-3-opus-20240229, deepseek-chat 等" />
|
||||
</Form.Item>
|
||||
<Form.Item label="能力标签" name="capabilities" rules={[{ message: "请至少选择一个能力标签", required: true }]}>
|
||||
<Checkbox.Group>
|
||||
<Row gutter={[8, 8]}>
|
||||
{CAPABILITY_OPTIONS.map((opt) => (
|
||||
<Col key={opt.value} md={8} sm={12} xs={24}>
|
||||
<Checkbox value={opt.value}>{opt.label}</Checkbox>
|
||||
</Col>
|
||||
))}
|
||||
</Row>
|
||||
</Checkbox.Group>
|
||||
</Form.Item>
|
||||
<Row gutter={16}>
|
||||
<Col sm={12} xs={24}>
|
||||
<Form.Item label="上下文长度" name="contextLength" rules={[positiveIntegerRule("上下文长度")]}>
|
||||
<InputNumber min={1} placeholder="可选" precision={0} styles={{ root: { width: "100%" } }} />
|
||||
</Form.Item>
|
||||
</Col>
|
||||
<Col sm={12} xs={24}>
|
||||
<Form.Item label="最大输出 Token" name="maxOutputTokens" rules={[positiveIntegerRule("最大输出 Token")]}>
|
||||
<InputNumber min={1} placeholder="可选" precision={0} styles={{ root: { width: "100%" } }} />
|
||||
</Form.Item>
|
||||
</Col>
|
||||
</Row>
|
||||
{testModelConnection && (
|
||||
<Form.Item>
|
||||
<Space>
|
||||
<Button loading={testing} onClick={() => void handleTest()}>
|
||||
测试连接
|
||||
</Button>
|
||||
</Space>
|
||||
</Form.Item>
|
||||
)}
|
||||
</Form>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
|
||||
function getProviderNotFoundContent(loading: boolean, error: Error | null): string {
|
||||
if (loading) return "正在加载供应商";
|
||||
if (error) return `供应商加载失败:${error.message}`;
|
||||
return "暂无供应商,请先新建供应商";
|
||||
}
|
||||
|
||||
function positiveIntegerRule(label: string) {
|
||||
return {
|
||||
validator(_: unknown, value: null | number | undefined) {
|
||||
if (value === undefined || value === null) return Promise.resolve();
|
||||
if (Number.isInteger(value) && value > 0) return Promise.resolve();
|
||||
return Promise.reject(new Error(`${label}必须为正整数`));
|
||||
},
|
||||
};
|
||||
}
|
||||
124
src/web/features/models/components/ModelTable.tsx
Normal file
124
src/web/features/models/components/ModelTable.tsx
Normal file
@@ -0,0 +1,124 @@
|
||||
import type { ColumnsType } from "antd/es/table";
|
||||
|
||||
import { DeleteOutlined, EditOutlined } from "@ant-design/icons";
|
||||
import { App as AntApp, Button, Popconfirm, Space, Table, Tag } from "antd";
|
||||
|
||||
import type { Model, ModelListResponse, ProviderOption } from "../../../../shared/api";
|
||||
|
||||
interface ModelTableProps {
|
||||
data: ModelListResponse | undefined;
|
||||
loading: boolean;
|
||||
onDelete: (id: string) => Promise<unknown>;
|
||||
onEdit: (model: Model) => void;
|
||||
onPageChange: (page: number, pageSize: number) => void;
|
||||
page: number;
|
||||
pageSize: number;
|
||||
providers: ProviderOption[];
|
||||
}
|
||||
|
||||
const CAPABILITY_LABELS: Record<string, string> = {
|
||||
"audio-generation": "音频生成",
|
||||
"audio-recognition": "音频识别",
|
||||
"image-generation": "图片生成",
|
||||
"image-recognition": "图片识别",
|
||||
reasoning: "推理",
|
||||
text: "文本",
|
||||
"video-generation": "视频生成",
|
||||
"video-recognition": "视频识别",
|
||||
};
|
||||
|
||||
function getProviderName(providerId: string, providers: ProviderOption[]): string {
|
||||
return providers.find((p) => p.id === providerId)?.name ?? providerId;
|
||||
}
|
||||
|
||||
const COLUMNS: ColumnsType<Model> = [
|
||||
{ dataIndex: "name", ellipsis: true, title: "名称", width: 180 },
|
||||
{
|
||||
dataIndex: "providerId",
|
||||
ellipsis: true,
|
||||
title: "供应商",
|
||||
width: 120,
|
||||
},
|
||||
{
|
||||
dataIndex: "capabilities",
|
||||
render: (value: string[]) =>
|
||||
value.length > 0 ? (
|
||||
<Space size={[4, 4]} wrap>
|
||||
{value.map((c) => (
|
||||
<Tag key={c}>{CAPABILITY_LABELS[c] ?? c}</Tag>
|
||||
))}
|
||||
</Space>
|
||||
) : null,
|
||||
title: "能力",
|
||||
},
|
||||
];
|
||||
|
||||
export function ModelTable({
|
||||
data,
|
||||
loading,
|
||||
onDelete,
|
||||
onEdit,
|
||||
onPageChange,
|
||||
page,
|
||||
pageSize,
|
||||
providers,
|
||||
}: ModelTableProps) {
|
||||
const { message } = AntApp.useApp();
|
||||
|
||||
const handleDelete = async (id: string) => {
|
||||
try {
|
||||
await onDelete(id);
|
||||
message.success("模型已删除");
|
||||
} catch (err: unknown) {
|
||||
message.error((err as Error).message);
|
||||
}
|
||||
};
|
||||
|
||||
const columnsWithProvider: ColumnsType<Model> = COLUMNS.map((col) =>
|
||||
"dataIndex" in col && col.dataIndex === "providerId"
|
||||
? {
|
||||
...col,
|
||||
render: (_value: unknown, record: Model) => getProviderName(record.providerId, providers),
|
||||
}
|
||||
: col,
|
||||
);
|
||||
|
||||
const operationColumn: ColumnsType<Model>[number] = {
|
||||
dataIndex: "op",
|
||||
render: (_value: unknown, record: Model) => (
|
||||
<Space size="small">
|
||||
<Button icon={<EditOutlined />} onClick={() => onEdit(record)} size="small" type="link">
|
||||
编辑
|
||||
</Button>
|
||||
<Popconfirm
|
||||
description="此操作不可恢复。"
|
||||
onConfirm={() => void handleDelete(record.id)}
|
||||
title="确认删除此模型?"
|
||||
>
|
||||
<Button danger icon={<DeleteOutlined />} size="small" type="link">
|
||||
删除
|
||||
</Button>
|
||||
</Popconfirm>
|
||||
</Space>
|
||||
),
|
||||
title: "操作",
|
||||
width: 180,
|
||||
};
|
||||
|
||||
return (
|
||||
<Table
|
||||
columns={[...columnsWithProvider, operationColumn]}
|
||||
dataSource={data?.items ?? []}
|
||||
loading={loading}
|
||||
pagination={{
|
||||
current: page,
|
||||
hideOnSinglePage: false,
|
||||
onChange: onPageChange,
|
||||
pageSize,
|
||||
showSizeChanger: true,
|
||||
total: data?.total ?? 0,
|
||||
}}
|
||||
rowKey="id"
|
||||
/>
|
||||
);
|
||||
}
|
||||
53
src/web/features/models/components/ModelsToolbar.tsx
Normal file
53
src/web/features/models/components/ModelsToolbar.tsx
Normal file
@@ -0,0 +1,53 @@
|
||||
import { PlusOutlined } from "@ant-design/icons";
|
||||
import { Button, Flex, Input, Space, Tabs } from "antd";
|
||||
import { useState } from "react";
|
||||
|
||||
interface ModelsToolbarProps {
|
||||
activeTab: string;
|
||||
keyword: string;
|
||||
onSearch: (value: string) => void;
|
||||
onSearchClear: () => void;
|
||||
onTabChange: (key: string) => void;
|
||||
openCreateDialog: () => void;
|
||||
}
|
||||
|
||||
const TAB_ITEMS = [
|
||||
{ key: "models", label: "模型" },
|
||||
{ key: "providers", label: "供应商" },
|
||||
];
|
||||
|
||||
export function ModelsToolbar({
|
||||
activeTab,
|
||||
keyword,
|
||||
onSearch,
|
||||
onSearchClear,
|
||||
onTabChange,
|
||||
openCreateDialog,
|
||||
}: ModelsToolbarProps) {
|
||||
const [draftKeyword, setDraftKeyword] = useState(keyword);
|
||||
const placeholder = activeTab === "providers" ? "搜索供应商名称" : "搜索模型名称或 ID";
|
||||
const createLabel = activeTab === "providers" ? "新建供应商" : "新建模型";
|
||||
|
||||
return (
|
||||
<Flex align="center" gap="large" justify="space-between" wrap="wrap">
|
||||
<Tabs activeKey={activeTab} items={TAB_ITEMS} onChange={onTabChange} />
|
||||
<Space size="small">
|
||||
<Input.Search
|
||||
allowClear
|
||||
enterButton="搜索"
|
||||
onChange={(event) => setDraftKeyword(event.target.value)}
|
||||
onClear={() => {
|
||||
setDraftKeyword("");
|
||||
onSearchClear();
|
||||
}}
|
||||
onSearch={(value) => onSearch(value)}
|
||||
placeholder={placeholder}
|
||||
value={draftKeyword}
|
||||
/>
|
||||
<Button icon={<PlusOutlined />} onClick={openCreateDialog} type="primary">
|
||||
{createLabel}
|
||||
</Button>
|
||||
</Space>
|
||||
</Flex>
|
||||
);
|
||||
}
|
||||
162
src/web/features/models/components/ProviderFormModal.tsx
Normal file
162
src/web/features/models/components/ProviderFormModal.tsx
Normal file
@@ -0,0 +1,162 @@
|
||||
import { App as AntApp, Button, Form, Input, Modal, Select, Space } from "antd";
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
import type {
|
||||
CreateProviderRequest,
|
||||
Provider,
|
||||
ProviderTestResponse,
|
||||
ProviderType,
|
||||
UpdateProviderRequest,
|
||||
} from "../../../../shared/api";
|
||||
|
||||
interface FormValues {
|
||||
apiKey: string;
|
||||
baseUrl: string;
|
||||
name: string;
|
||||
type: ProviderType;
|
||||
}
|
||||
|
||||
interface ProviderFormModalProps {
|
||||
editingProvider: null | Provider;
|
||||
onCancel: () => void;
|
||||
onCreate: (data: CreateProviderRequest) => Promise<unknown>;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
onTest: (data: CreateProviderRequest) => Promise<ProviderTestResponse>;
|
||||
onUpdate: (args: { data: UpdateProviderRequest; id: string }) => Promise<unknown>;
|
||||
open: boolean;
|
||||
submitting: boolean;
|
||||
}
|
||||
|
||||
const TYPE_OPTIONS = [
|
||||
{ label: "OpenAI 兼容", value: "openai-compatible" },
|
||||
{ label: "OpenAI", value: "openai" },
|
||||
{ label: "Anthropic", value: "anthropic" },
|
||||
];
|
||||
|
||||
export function ProviderFormModal({
|
||||
editingProvider,
|
||||
onCancel,
|
||||
onCreate,
|
||||
onOpenChange,
|
||||
onTest,
|
||||
onUpdate,
|
||||
open,
|
||||
submitting,
|
||||
}: ProviderFormModalProps) {
|
||||
const { message } = AntApp.useApp();
|
||||
const [form] = Form.useForm<FormValues>();
|
||||
const [testing, setTesting] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
if (editingProvider) {
|
||||
form.setFieldsValue({
|
||||
apiKey: editingProvider.apiKey,
|
||||
baseUrl: editingProvider.baseUrl,
|
||||
name: editingProvider.name,
|
||||
type: editingProvider.type,
|
||||
});
|
||||
} else {
|
||||
form.resetFields();
|
||||
form.setFieldsValue({ type: "openai-compatible" });
|
||||
}
|
||||
}, [editingProvider, form, open]);
|
||||
|
||||
const handleFinish = async (values: FormValues) => {
|
||||
try {
|
||||
if (editingProvider) {
|
||||
const reqData: UpdateProviderRequest = {};
|
||||
if (values.name !== editingProvider.name) reqData.name = values.name;
|
||||
if (values.baseUrl !== editingProvider.baseUrl) reqData.baseUrl = values.baseUrl;
|
||||
if (values.apiKey !== editingProvider.apiKey) reqData.apiKey = values.apiKey;
|
||||
if (values.type !== editingProvider.type) reqData.type = values.type;
|
||||
await onUpdate({ data: reqData, id: editingProvider.id });
|
||||
message.success("供应商已更新");
|
||||
} else {
|
||||
const reqData: CreateProviderRequest = {
|
||||
apiKey: values.apiKey,
|
||||
baseUrl: values.baseUrl,
|
||||
name: values.name,
|
||||
type: values.type,
|
||||
};
|
||||
await onCreate(reqData);
|
||||
message.success("供应商已创建");
|
||||
}
|
||||
onOpenChange(false);
|
||||
} catch (err: unknown) {
|
||||
if (err instanceof Error) {
|
||||
message.error(err.message);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const handleTest = async () => {
|
||||
try {
|
||||
const values = await form.validateFields(["name", "type", "baseUrl", "apiKey"]);
|
||||
setTesting(true);
|
||||
const result = await onTest({
|
||||
apiKey: values.apiKey,
|
||||
baseUrl: values.baseUrl,
|
||||
name: values.name,
|
||||
type: values.type,
|
||||
});
|
||||
if (result.ok) {
|
||||
message.success(result.message);
|
||||
} else {
|
||||
message.error(result.message);
|
||||
}
|
||||
} catch (err: unknown) {
|
||||
if (err instanceof Error) {
|
||||
message.error(err.message);
|
||||
}
|
||||
} finally {
|
||||
setTesting(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Modal
|
||||
confirmLoading={submitting}
|
||||
destroyOnHidden
|
||||
okText="确定"
|
||||
onCancel={onCancel}
|
||||
onOk={() => void form.submit()}
|
||||
open={open}
|
||||
title={editingProvider ? "编辑供应商" : "新建供应商"}
|
||||
>
|
||||
<Form form={form} layout="vertical" onFinish={(values) => void handleFinish(values)}>
|
||||
<Form.Item
|
||||
label="供应商名称"
|
||||
name="name"
|
||||
rules={[{ message: "请输入供应商名称", required: true, whitespace: true }]}
|
||||
>
|
||||
<Input placeholder="请输入供应商名称" />
|
||||
</Form.Item>
|
||||
<Form.Item label="供应商类型" name="type" rules={[{ message: "请选择供应商类型", required: true }]}>
|
||||
<Select options={TYPE_OPTIONS} placeholder="请选择供应商类型" />
|
||||
</Form.Item>
|
||||
<Form.Item
|
||||
label="Base URL"
|
||||
name="baseUrl"
|
||||
rules={[{ message: "请输入 Base URL", required: true, whitespace: true }]}
|
||||
>
|
||||
<Input placeholder="https://api.openai.com/v1" />
|
||||
</Form.Item>
|
||||
<Form.Item
|
||||
label="API Key"
|
||||
name="apiKey"
|
||||
rules={[{ message: "请输入 API Key", required: true, whitespace: true }]}
|
||||
>
|
||||
<Input.Password placeholder="请输入 API Key" />
|
||||
</Form.Item>
|
||||
<Form.Item>
|
||||
<Space>
|
||||
<Button loading={testing} onClick={() => void handleTest()}>
|
||||
测试连接
|
||||
</Button>
|
||||
</Space>
|
||||
</Form.Item>
|
||||
</Form>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
85
src/web/features/models/components/ProviderTable.tsx
Normal file
85
src/web/features/models/components/ProviderTable.tsx
Normal file
@@ -0,0 +1,85 @@
|
||||
import type { ColumnsType } from "antd/es/table";
|
||||
|
||||
import { DeleteOutlined, EditOutlined } from "@ant-design/icons";
|
||||
import { App as AntApp, Button, Popconfirm, Space, Table } from "antd";
|
||||
|
||||
import type { Provider, ProviderListResponse } from "../../../../shared/api";
|
||||
|
||||
interface ProviderTableProps {
|
||||
data: ProviderListResponse | undefined;
|
||||
loading: boolean;
|
||||
onDelete: (id: string) => Promise<unknown>;
|
||||
onEdit: (provider: Provider) => void;
|
||||
onPageChange: (page: number, pageSize: number) => void;
|
||||
page: number;
|
||||
pageSize: number;
|
||||
}
|
||||
|
||||
const TYPE_LABELS: Record<Provider["type"], string> = {
|
||||
anthropic: "Anthropic",
|
||||
openai: "OpenAI",
|
||||
"openai-compatible": "OpenAI 兼容",
|
||||
};
|
||||
|
||||
const COLUMNS: ColumnsType<Provider> = [
|
||||
{ dataIndex: "name", ellipsis: true, title: "名称", width: 180 },
|
||||
{
|
||||
dataIndex: "type",
|
||||
render: (value: Provider["type"]) => TYPE_LABELS[value] ?? value,
|
||||
title: "类型",
|
||||
width: 140,
|
||||
},
|
||||
{ dataIndex: "baseUrl", ellipsis: true, title: "Base URL" },
|
||||
];
|
||||
|
||||
export function ProviderTable({ data, loading, onDelete, onEdit, onPageChange, page, pageSize }: ProviderTableProps) {
|
||||
const { message } = AntApp.useApp();
|
||||
|
||||
const handleDelete = async (id: string) => {
|
||||
try {
|
||||
await onDelete(id);
|
||||
message.success("供应商已删除");
|
||||
} catch (err: unknown) {
|
||||
message.error((err as Error).message);
|
||||
}
|
||||
};
|
||||
|
||||
const operationColumn: ColumnsType<Provider>[number] = {
|
||||
dataIndex: "op",
|
||||
render: (_value: unknown, record: Provider) => (
|
||||
<Space size="small">
|
||||
<Button icon={<EditOutlined />} onClick={() => onEdit(record)} size="small" type="link">
|
||||
编辑
|
||||
</Button>
|
||||
<Popconfirm
|
||||
description="该供应商下存在模型时无法删除,请先删除或迁移相关模型。"
|
||||
onConfirm={() => void handleDelete(record.id)}
|
||||
title="确认删除此供应商?"
|
||||
>
|
||||
<Button danger icon={<DeleteOutlined />} size="small" type="link">
|
||||
删除
|
||||
</Button>
|
||||
</Popconfirm>
|
||||
</Space>
|
||||
),
|
||||
title: "操作",
|
||||
width: 180,
|
||||
};
|
||||
|
||||
return (
|
||||
<Table
|
||||
columns={[...COLUMNS, operationColumn]}
|
||||
dataSource={data?.items ?? []}
|
||||
loading={loading}
|
||||
pagination={{
|
||||
current: page,
|
||||
hideOnSinglePage: false,
|
||||
onChange: onPageChange,
|
||||
pageSize,
|
||||
showSizeChanger: true,
|
||||
total: data?.total ?? 0,
|
||||
}}
|
||||
rowKey="id"
|
||||
/>
|
||||
);
|
||||
}
|
||||
190
src/web/features/models/index.tsx
Normal file
190
src/web/features/models/index.tsx
Normal file
@@ -0,0 +1,190 @@
|
||||
import { Space } from "antd";
|
||||
import { useState } from "react";
|
||||
|
||||
import type { Model, Provider, TestModelRequest } from "../../../shared/api";
|
||||
|
||||
import {
|
||||
useCreateModel,
|
||||
useDeleteModel,
|
||||
useModelList,
|
||||
useTestModelConnection,
|
||||
useUpdateModel,
|
||||
} from "../../shared/hooks/use-models";
|
||||
import {
|
||||
useCreateProvider,
|
||||
useDeleteProvider,
|
||||
useProviderList,
|
||||
useProviderOptions,
|
||||
useTestProviderConfig,
|
||||
useUpdateProvider,
|
||||
} from "../../shared/hooks/use-providers";
|
||||
import { ModelFormModal } from "./components/ModelFormModal";
|
||||
import { ModelsToolbar } from "./components/ModelsToolbar";
|
||||
import { ModelTable } from "./components/ModelTable";
|
||||
import { ProviderFormModal } from "./components/ProviderFormModal";
|
||||
import { ProviderTable } from "./components/ProviderTable";
|
||||
|
||||
export function ModelsPage() {
|
||||
const [activeTab, setActiveTab] = useState<string>("models");
|
||||
|
||||
const [providerPage, setProviderPage] = useState(1);
|
||||
const [providerPageSize, setProviderPageSize] = useState(20);
|
||||
const [providerKeyword, setProviderKeyword] = useState("");
|
||||
const [providerDialogOpen, setProviderDialogOpen] = useState(false);
|
||||
const [editingProvider, setEditingProvider] = useState<null | Provider>(null);
|
||||
|
||||
const [modelPage, setModelPage] = useState(1);
|
||||
const [modelPageSize, setModelPageSize] = useState(20);
|
||||
const [modelKeyword, setModelKeyword] = useState("");
|
||||
const [modelDialogOpen, setModelDialogOpen] = useState(false);
|
||||
const [editingModel, setEditingModel] = useState<Model | null>(null);
|
||||
|
||||
const { data: providerData, isLoading: providerLoading } = useProviderList({
|
||||
keyword: providerKeyword || undefined,
|
||||
page: providerPage,
|
||||
pageSize: providerPageSize,
|
||||
});
|
||||
|
||||
const {
|
||||
data: providerOptionsData,
|
||||
error: providerOptionsError,
|
||||
isError: providerOptionsIsError,
|
||||
isLoading: providerOptionsLoading,
|
||||
} = useProviderOptions();
|
||||
|
||||
const { data: modelData, isLoading: modelLoading } = useModelList({
|
||||
keyword: modelKeyword || undefined,
|
||||
page: modelPage,
|
||||
pageSize: modelPageSize,
|
||||
});
|
||||
|
||||
const createProviderMutation = useCreateProvider();
|
||||
const updateProviderMutation = useUpdateProvider();
|
||||
const deleteProviderMutation = useDeleteProvider();
|
||||
const testProviderConfigMutation = useTestProviderConfig();
|
||||
|
||||
const createModelMutation = useCreateModel();
|
||||
const updateModelMutation = useUpdateModel();
|
||||
const deleteModelMutation = useDeleteModel();
|
||||
const testModelMutation = useTestModelConnection();
|
||||
|
||||
const isProviderSubmitting = createProviderMutation.isPending || updateProviderMutation.isPending;
|
||||
const isProviderActionPending = deleteProviderMutation.isPending;
|
||||
|
||||
const isModelSubmitting = createModelMutation.isPending || updateModelMutation.isPending;
|
||||
const isModelActionPending = deleteModelMutation.isPending;
|
||||
const modelProviders = providerOptionsData?.items ?? [];
|
||||
|
||||
const currentKeyword = activeTab === "providers" ? providerKeyword : modelKeyword;
|
||||
|
||||
const handleSearch =
|
||||
activeTab === "providers"
|
||||
? (value: string) => {
|
||||
setProviderKeyword(value);
|
||||
setProviderPage(1);
|
||||
}
|
||||
: (value: string) => {
|
||||
setModelKeyword(value);
|
||||
setModelPage(1);
|
||||
};
|
||||
|
||||
const handleSearchClear =
|
||||
activeTab === "providers"
|
||||
? () => {
|
||||
setProviderKeyword("");
|
||||
setProviderPage(1);
|
||||
}
|
||||
: () => {
|
||||
setModelKeyword("");
|
||||
setModelPage(1);
|
||||
};
|
||||
|
||||
const handleOpenCreate =
|
||||
activeTab === "providers"
|
||||
? () => {
|
||||
setEditingProvider(null);
|
||||
setProviderDialogOpen(true);
|
||||
}
|
||||
: () => {
|
||||
setEditingModel(null);
|
||||
setModelDialogOpen(true);
|
||||
};
|
||||
|
||||
return (
|
||||
<Space className="app-page-flex" orientation="vertical" size="large">
|
||||
<ModelsToolbar
|
||||
activeTab={activeTab}
|
||||
key={activeTab}
|
||||
keyword={currentKeyword}
|
||||
onSearch={handleSearch}
|
||||
onSearchClear={handleSearchClear}
|
||||
onTabChange={(key) => setActiveTab(key)}
|
||||
openCreateDialog={handleOpenCreate}
|
||||
/>
|
||||
|
||||
{activeTab === "providers" && (
|
||||
<>
|
||||
<ProviderTable
|
||||
data={providerData}
|
||||
loading={providerLoading || isProviderActionPending}
|
||||
onDelete={(id) => deleteProviderMutation.mutateAsync(id)}
|
||||
onEdit={(provider) => {
|
||||
setEditingProvider(provider);
|
||||
setProviderDialogOpen(true);
|
||||
}}
|
||||
onPageChange={(p, ps) => {
|
||||
setProviderPage(p);
|
||||
setProviderPageSize(ps);
|
||||
}}
|
||||
page={providerPage}
|
||||
pageSize={providerPageSize}
|
||||
/>
|
||||
<ProviderFormModal
|
||||
editingProvider={editingProvider}
|
||||
onCancel={() => setProviderDialogOpen(false)}
|
||||
onCreate={(data) => createProviderMutation.mutateAsync(data)}
|
||||
onOpenChange={setProviderDialogOpen}
|
||||
onTest={(data) => testProviderConfigMutation.mutateAsync(data)}
|
||||
onUpdate={(args) => updateProviderMutation.mutateAsync(args)}
|
||||
open={providerDialogOpen}
|
||||
submitting={isProviderSubmitting}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
|
||||
{activeTab === "models" && (
|
||||
<>
|
||||
<ModelTable
|
||||
data={modelData}
|
||||
loading={modelLoading || providerOptionsLoading || isModelActionPending}
|
||||
onDelete={(id) => deleteModelMutation.mutateAsync(id)}
|
||||
onEdit={(model) => {
|
||||
setEditingModel(model);
|
||||
setModelDialogOpen(true);
|
||||
}}
|
||||
onPageChange={(p, ps) => {
|
||||
setModelPage(p);
|
||||
setModelPageSize(ps);
|
||||
}}
|
||||
page={modelPage}
|
||||
pageSize={modelPageSize}
|
||||
providers={modelProviders}
|
||||
/>
|
||||
<ModelFormModal
|
||||
editingModel={editingModel}
|
||||
onCancel={() => setModelDialogOpen(false)}
|
||||
onCreate={(data) => createModelMutation.mutateAsync(data)}
|
||||
onOpenChange={setModelDialogOpen}
|
||||
onUpdate={(args) => updateModelMutation.mutateAsync(args)}
|
||||
open={modelDialogOpen}
|
||||
providers={modelProviders}
|
||||
providersError={providerOptionsIsError ? providerOptionsError : null}
|
||||
providersLoading={providerOptionsLoading}
|
||||
submitting={isModelSubmitting}
|
||||
testModelConnection={(data: TestModelRequest) => testModelMutation.mutateAsync(data)}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</Space>
|
||||
);
|
||||
}
|
||||
19
src/web/features/not-found/index.tsx
Normal file
19
src/web/features/not-found/index.tsx
Normal file
@@ -0,0 +1,19 @@
|
||||
import { Button, Result } from "antd";
|
||||
import { useNavigate } from "react-router";
|
||||
|
||||
export function NotFoundPage() {
|
||||
const navigate = useNavigate();
|
||||
|
||||
return (
|
||||
<Result
|
||||
extra={
|
||||
<Button onClick={() => void navigate("/")} type="primary">
|
||||
返回首页
|
||||
</Button>
|
||||
}
|
||||
status="404"
|
||||
subTitle="您访问的页面不存在"
|
||||
title="404"
|
||||
/>
|
||||
);
|
||||
}
|
||||
87
src/web/features/projects/components/ProjectFormModal.tsx
Normal file
87
src/web/features/projects/components/ProjectFormModal.tsx
Normal file
@@ -0,0 +1,87 @@
|
||||
import { App as AntApp, Form, Input, Modal } from "antd";
|
||||
import { useEffect } from "react";
|
||||
|
||||
import type { CreateProjectRequest, Project, UpdateProjectRequest } from "../../../../shared/api";
|
||||
|
||||
interface FormValues {
|
||||
description?: string;
|
||||
name: string;
|
||||
}
|
||||
|
||||
interface ProjectFormModalProps {
|
||||
editingProject: null | Project;
|
||||
onCancel: () => void;
|
||||
onCreate: (data: CreateProjectRequest) => Promise<unknown>;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
onUpdate: (args: { data: UpdateProjectRequest; id: string }) => Promise<unknown>;
|
||||
open: boolean;
|
||||
submitting: boolean;
|
||||
}
|
||||
|
||||
export function ProjectFormModal({
|
||||
editingProject,
|
||||
onCancel,
|
||||
onCreate,
|
||||
onOpenChange,
|
||||
onUpdate,
|
||||
open,
|
||||
submitting,
|
||||
}: ProjectFormModalProps) {
|
||||
const { message } = AntApp.useApp();
|
||||
const [form] = Form.useForm<FormValues>();
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
if (editingProject) {
|
||||
form.setFieldsValue({ description: editingProject.description, name: editingProject.name });
|
||||
} else {
|
||||
form.resetFields();
|
||||
}
|
||||
}, [editingProject, form, open]);
|
||||
|
||||
const handleFinish = async (values: FormValues) => {
|
||||
try {
|
||||
if (editingProject) {
|
||||
const reqData: UpdateProjectRequest = {};
|
||||
if (values.name !== editingProject.name) reqData.name = values.name;
|
||||
if ((values.description ?? "") !== (editingProject.description ?? "")) reqData.description = values.description;
|
||||
await onUpdate({ data: reqData, id: editingProject.id });
|
||||
message.success("项目已更新");
|
||||
} else {
|
||||
const reqData: CreateProjectRequest = { description: values.description, name: values.name };
|
||||
await onCreate(reqData);
|
||||
message.success("项目已创建");
|
||||
}
|
||||
onOpenChange(false);
|
||||
} catch (err: unknown) {
|
||||
if (err instanceof Error) {
|
||||
message.error(err.message);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Modal
|
||||
confirmLoading={submitting}
|
||||
destroyOnHidden
|
||||
okText="确定"
|
||||
onCancel={onCancel}
|
||||
onOk={() => void form.submit()}
|
||||
open={open}
|
||||
title={editingProject ? "编辑项目" : "新建项目"}
|
||||
>
|
||||
<Form form={form} layout="vertical" onFinish={(values) => void handleFinish(values)}>
|
||||
<Form.Item
|
||||
label="项目名称"
|
||||
name="name"
|
||||
rules={[{ max: 10, message: "项目名称不能超过 10 个字符", required: true, whitespace: true }]}
|
||||
>
|
||||
<Input maxLength={10} placeholder="请输入项目名称" />
|
||||
</Form.Item>
|
||||
<Form.Item label="项目描述" name="description">
|
||||
<Input.TextArea autoSize={{ minRows: 5 }} maxLength={500} placeholder="请输入项目描述" />
|
||||
</Form.Item>
|
||||
</Form>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
169
src/web/features/projects/components/ProjectTable.tsx
Normal file
169
src/web/features/projects/components/ProjectTable.tsx
Normal file
@@ -0,0 +1,169 @@
|
||||
import type { ColumnsType } from "antd/es/table";
|
||||
|
||||
import { DeleteOutlined, EditOutlined, InboxOutlined, LoginOutlined, RedoOutlined } from "@ant-design/icons";
|
||||
import { App as AntApp, Button, Popconfirm, Space, Table, Tag } from "antd";
|
||||
import { useNavigate } from "react-router";
|
||||
|
||||
import type { Project, ProjectListResponse, ProjectStatus } from "../../../../shared/api";
|
||||
|
||||
interface ProjectTableProps {
|
||||
data: ProjectListResponse | undefined;
|
||||
loading: boolean;
|
||||
onArchive: (id: string) => Promise<unknown>;
|
||||
onDelete: (id: string) => Promise<unknown>;
|
||||
onEdit: (project: Project) => void;
|
||||
onPageChange: (page: number, pageSize: number) => void;
|
||||
onRestore: (id: string) => Promise<unknown>;
|
||||
page: number;
|
||||
pageSize: number;
|
||||
status: ProjectStatus;
|
||||
}
|
||||
|
||||
const COLUMNS: ColumnsType<Project> = [
|
||||
{ dataIndex: "name", ellipsis: true, title: "名称", width: 140 },
|
||||
{ dataIndex: "description", ellipsis: true, title: "描述" },
|
||||
{
|
||||
align: "center",
|
||||
dataIndex: "status",
|
||||
render: (_value, record: Project) => {
|
||||
if (record.status === "archived") {
|
||||
return <Tag>已归档</Tag>;
|
||||
}
|
||||
return <Tag color="blue">进行中</Tag>;
|
||||
},
|
||||
title: "状态",
|
||||
width: 90,
|
||||
},
|
||||
{
|
||||
align: "center",
|
||||
dataIndex: "createdAt",
|
||||
render: (_value, record: Project) => formatDatetime(record.createdAt),
|
||||
title: "创建时间",
|
||||
width: 180,
|
||||
},
|
||||
{
|
||||
align: "center",
|
||||
dataIndex: "updatedAt",
|
||||
render: (_value, record: Project) => formatDatetime(record.updatedAt),
|
||||
title: "更新时间",
|
||||
width: 180,
|
||||
},
|
||||
];
|
||||
|
||||
export function ProjectTable({
|
||||
data,
|
||||
loading,
|
||||
onArchive,
|
||||
onDelete,
|
||||
onEdit,
|
||||
onPageChange,
|
||||
onRestore,
|
||||
page,
|
||||
pageSize,
|
||||
status,
|
||||
}: ProjectTableProps) {
|
||||
const { message } = AntApp.useApp();
|
||||
const navigate = useNavigate();
|
||||
|
||||
const handleArchive = async (id: string) => {
|
||||
try {
|
||||
await onArchive(id);
|
||||
message.success("项目已归档");
|
||||
} catch (err: unknown) {
|
||||
message.error((err as Error).message);
|
||||
}
|
||||
};
|
||||
|
||||
const handleRestore = async (id: string) => {
|
||||
try {
|
||||
await onRestore(id);
|
||||
message.success("项目已恢复");
|
||||
} catch (err: unknown) {
|
||||
message.error((err as Error).message);
|
||||
}
|
||||
};
|
||||
|
||||
const handleDelete = async (id: string) => {
|
||||
try {
|
||||
await onDelete(id);
|
||||
message.success("项目已永久删除");
|
||||
} catch (err: unknown) {
|
||||
message.error((err as Error).message);
|
||||
}
|
||||
};
|
||||
|
||||
const operationColumn: ColumnsType<Project>[number] = {
|
||||
dataIndex: "op",
|
||||
render: (_value, record: Project) => {
|
||||
if (record.status === "active") {
|
||||
return (
|
||||
<Space size="small">
|
||||
<Button
|
||||
icon={<LoginOutlined />}
|
||||
onClick={() => void navigate(`/workbench/${record.id}`)}
|
||||
size="small"
|
||||
type="link"
|
||||
>
|
||||
工作台
|
||||
</Button>
|
||||
<Button icon={<EditOutlined />} onClick={() => onEdit(record)} size="small" type="link">
|
||||
编辑
|
||||
</Button>
|
||||
<Popconfirm
|
||||
description="归档后项目将变为只读。"
|
||||
onConfirm={() => void handleArchive(record.id)}
|
||||
title="确认归档此项目?"
|
||||
>
|
||||
<Button color="orange" icon={<InboxOutlined />} size="small" variant="link">
|
||||
归档
|
||||
</Button>
|
||||
</Popconfirm>
|
||||
</Space>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<Space size="small">
|
||||
<Popconfirm onConfirm={() => void handleRestore(record.id)} title="确认恢复此项目?">
|
||||
<Button icon={<RedoOutlined />} size="small" type="link">
|
||||
恢复
|
||||
</Button>
|
||||
</Popconfirm>
|
||||
<Popconfirm
|
||||
description="此操作不可恢复。"
|
||||
onConfirm={() => void handleDelete(record.id)}
|
||||
title="确认永久删除此项目?"
|
||||
>
|
||||
<Button danger icon={<DeleteOutlined />} size="small" type="link">
|
||||
删除
|
||||
</Button>
|
||||
</Popconfirm>
|
||||
</Space>
|
||||
);
|
||||
},
|
||||
title: "操作",
|
||||
width: status === "active" ? 260 : 160,
|
||||
};
|
||||
|
||||
return (
|
||||
<Table
|
||||
columns={[...COLUMNS, operationColumn]}
|
||||
dataSource={data?.items ?? []}
|
||||
loading={loading}
|
||||
pagination={{
|
||||
current: page,
|
||||
hideOnSinglePage: false,
|
||||
onChange: onPageChange,
|
||||
pageSize,
|
||||
showSizeChanger: true,
|
||||
total: data?.total ?? 0,
|
||||
}}
|
||||
rowKey="id"
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function formatDatetime(dateStr: string): string {
|
||||
const d = new Date(dateStr);
|
||||
const pad = (n: number) => String(n).padStart(2, "0");
|
||||
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
|
||||
}
|
||||
55
src/web/features/projects/components/ProjectToolbar.tsx
Normal file
55
src/web/features/projects/components/ProjectToolbar.tsx
Normal file
@@ -0,0 +1,55 @@
|
||||
import { PlusOutlined } from "@ant-design/icons";
|
||||
import { Button, Flex, Input, Space, Tabs } from "antd";
|
||||
import { useState } from "react";
|
||||
|
||||
import type { ProjectStatus } from "../../../../shared/api";
|
||||
|
||||
interface ProjectToolbarProps {
|
||||
activeTab: ProjectStatus;
|
||||
keyword: string;
|
||||
onSearch: (value: string) => void;
|
||||
onSearchClear: () => void;
|
||||
onTabChange: (key: string) => void;
|
||||
openCreateDialog: () => void;
|
||||
}
|
||||
|
||||
const STATUS_TAB_ITEMS = [
|
||||
{ key: "active", label: "进行中" },
|
||||
{ key: "archived", label: "已归档" },
|
||||
];
|
||||
|
||||
export function ProjectToolbar({
|
||||
activeTab,
|
||||
keyword,
|
||||
onSearch,
|
||||
onSearchClear,
|
||||
onTabChange,
|
||||
openCreateDialog,
|
||||
}: ProjectToolbarProps) {
|
||||
const [draftKeyword, setDraftKeyword] = useState(keyword);
|
||||
|
||||
return (
|
||||
<Flex align="center" gap="large" justify="space-between" wrap="wrap">
|
||||
<Tabs activeKey={activeTab} items={STATUS_TAB_ITEMS} onChange={onTabChange} />
|
||||
<Space size="small">
|
||||
<Input.Search
|
||||
allowClear
|
||||
enterButton="搜索"
|
||||
onChange={(event) => setDraftKeyword(event.target.value)}
|
||||
onClear={() => {
|
||||
setDraftKeyword("");
|
||||
onSearchClear();
|
||||
}}
|
||||
onSearch={(value) => onSearch(value)}
|
||||
placeholder="搜索名称或描述"
|
||||
value={draftKeyword}
|
||||
/>
|
||||
{activeTab === "active" && (
|
||||
<Button icon={<PlusOutlined />} onClick={openCreateDialog} type="primary">
|
||||
新建项目
|
||||
</Button>
|
||||
)}
|
||||
</Space>
|
||||
</Flex>
|
||||
);
|
||||
}
|
||||
90
src/web/features/projects/index.tsx
Normal file
90
src/web/features/projects/index.tsx
Normal file
@@ -0,0 +1,90 @@
|
||||
import { Space } from "antd";
|
||||
import { useState } from "react";
|
||||
|
||||
import type { Project, ProjectStatus } from "../../../shared/api";
|
||||
|
||||
import {
|
||||
useArchiveProject,
|
||||
useCreateProject,
|
||||
useDeleteProject,
|
||||
useProjectList,
|
||||
useRestoreProject,
|
||||
useUpdateProject,
|
||||
} from "../../shared/hooks/use-projects";
|
||||
import { ProjectFormModal } from "./components/ProjectFormModal";
|
||||
import { ProjectTable } from "./components/ProjectTable";
|
||||
import { ProjectToolbar } from "./components/ProjectToolbar";
|
||||
|
||||
export function ProjectsPage() {
|
||||
const [tabValue, setTabValue] = useState<ProjectStatus>("active");
|
||||
const [page, setPage] = useState(1);
|
||||
const [pageSize, setPageSize] = useState(20);
|
||||
const [keyword, setKeyword] = useState("");
|
||||
|
||||
const [dialogOpen, setDialogOpen] = useState(false);
|
||||
const [editingProject, setEditingProject] = useState<null | Project>(null);
|
||||
|
||||
const { data, isLoading } = useProjectList({ keyword: keyword || undefined, page, pageSize, status: tabValue });
|
||||
const createMutation = useCreateProject();
|
||||
const updateMutation = useUpdateProject();
|
||||
const archiveMutation = useArchiveProject();
|
||||
const restoreMutation = useRestoreProject();
|
||||
const deleteMutation = useDeleteProject();
|
||||
|
||||
const isSubmitting = createMutation.isPending || updateMutation.isPending;
|
||||
const isRowActionPending = archiveMutation.isPending || restoreMutation.isPending || deleteMutation.isPending;
|
||||
|
||||
return (
|
||||
<Space className="app-page-flex" orientation="vertical" size="large">
|
||||
<ProjectToolbar
|
||||
activeTab={tabValue}
|
||||
keyword={keyword}
|
||||
onSearch={(value) => {
|
||||
setKeyword(value);
|
||||
setPage(1);
|
||||
}}
|
||||
onSearchClear={() => {
|
||||
setKeyword("");
|
||||
setPage(1);
|
||||
}}
|
||||
onTabChange={(key) => {
|
||||
setTabValue(key as ProjectStatus);
|
||||
setPage(1);
|
||||
}}
|
||||
openCreateDialog={() => {
|
||||
setEditingProject(null);
|
||||
setDialogOpen(true);
|
||||
}}
|
||||
/>
|
||||
|
||||
<ProjectTable
|
||||
data={data}
|
||||
loading={isLoading || isRowActionPending}
|
||||
onArchive={(id) => archiveMutation.mutateAsync(id)}
|
||||
onDelete={(id) => deleteMutation.mutateAsync(id)}
|
||||
onEdit={(project) => {
|
||||
setEditingProject(project);
|
||||
setDialogOpen(true);
|
||||
}}
|
||||
onPageChange={(p, ps) => {
|
||||
setPage(p);
|
||||
setPageSize(ps);
|
||||
}}
|
||||
onRestore={(id) => restoreMutation.mutateAsync(id)}
|
||||
page={page}
|
||||
pageSize={pageSize}
|
||||
status={tabValue}
|
||||
/>
|
||||
|
||||
<ProjectFormModal
|
||||
editingProject={editingProject}
|
||||
onCancel={() => setDialogOpen(false)}
|
||||
onCreate={(data) => createMutation.mutateAsync(data)}
|
||||
onOpenChange={setDialogOpen}
|
||||
onUpdate={(args) => updateMutation.mutateAsync(args)}
|
||||
open={dialogOpen}
|
||||
submitting={isSubmitting}
|
||||
/>
|
||||
</Space>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user