1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
import React, { useEffect, useMemo, useRef, useState } from "react";
import { useLocation, useNavigate } from "react-router-dom";
import { useNotify } from "react-admin";
import {
    Alert,
    Box,
    Button,
    Chip,
    Divider,
    Drawer,
    IconButton,
    List,
    ListItemButton,
    ListItemText,
    Paper,
    Stack,
    TextField,
    Typography,
} from "@mui/material";
import SmartToyOutlinedIcon from "@mui/icons-material/SmartToyOutlined";
import SendRoundedIcon from "@mui/icons-material/SendRounded";
import StopCircleOutlinedIcon from "@mui/icons-material/StopCircleOutlined";
import SettingsSuggestOutlinedIcon from "@mui/icons-material/SettingsSuggestOutlined";
import PsychologyAltOutlinedIcon from "@mui/icons-material/PsychologyAltOutlined";
import CableOutlinedIcon from "@mui/icons-material/CableOutlined";
import CloseIcon from "@mui/icons-material/Close";
import AddCommentOutlinedIcon from "@mui/icons-material/AddCommentOutlined";
import DeleteOutlineOutlinedIcon from "@mui/icons-material/DeleteOutlineOutlined";
import { getAiRuntime, getAiSessions, removeAiSession, streamAiChat } from "@/api/ai/chat";
 
const DEFAULT_PROMPT_CODE = "home.default";
 
const quickLinks = [
    { label: "AI 参数", path: "/aiParam", icon: <SettingsSuggestOutlinedIcon fontSize="small" /> },
    { label: "Prompt", path: "/aiPrompt", icon: <PsychologyAltOutlinedIcon fontSize="small" /> },
    { label: "MCP", path: "/aiMcpMount", icon: <CableOutlinedIcon fontSize="small" /> },
];
 
const AiChatDrawer = ({ open, onClose }) => {
    const navigate = useNavigate();
    const location = useLocation();
    const notify = useNotify();
    const abortRef = useRef(null);
    const [runtime, setRuntime] = useState(null);
    const [sessionId, setSessionId] = useState(null);
    const [sessions, setSessions] = useState([]);
    const [persistedMessages, setPersistedMessages] = useState([]);
    const [messages, setMessages] = useState([]);
    const [input, setInput] = useState("");
    const [loadingRuntime, setLoadingRuntime] = useState(false);
    const [streaming, setStreaming] = useState(false);
    const [usage, setUsage] = useState(null);
    const [drawerError, setDrawerError] = useState("");
 
    const promptCode = runtime?.promptCode || DEFAULT_PROMPT_CODE;
 
    const runtimeSummary = useMemo(() => {
        return {
            promptName: runtime?.promptName || "--",
            model: runtime?.model || "--",
            mountedMcpCount: runtime?.mountedMcpCount ?? 0,
        };
    }, [runtime]);
 
    useEffect(() => {
        if (open) {
            initializeDrawer();
        } else {
            stopStream(false);
        }
    }, [open]);
 
    useEffect(() => () => {
        stopStream(false);
    }, []);
 
    const initializeDrawer = async (targetSessionId = null) => {
        await Promise.all([
            loadRuntime(targetSessionId),
            loadSessions(),
        ]);
    };
 
    const loadRuntime = async (targetSessionId = null) => {
        setLoadingRuntime(true);
        setDrawerError("");
        try {
            const data = await getAiRuntime(DEFAULT_PROMPT_CODE, targetSessionId);
            const historyMessages = data?.persistedMessages || [];
            setRuntime(data);
            setSessionId(data?.sessionId || null);
            setPersistedMessages(historyMessages);
            setMessages(historyMessages);
        } catch (error) {
            const message = error.message || "获取 AI 运行时失败";
            setDrawerError(message);
        } finally {
            setLoadingRuntime(false);
        }
    };
 
    const loadSessions = async () => {
        try {
            const data = await getAiSessions(DEFAULT_PROMPT_CODE);
            setSessions(data);
        } catch (error) {
            const message = error.message || "获取 AI 会话列表失败";
            setDrawerError(message);
        }
    };
 
    const startNewSession = () => {
        if (streaming) {
            return;
        }
        setSessionId(null);
        setPersistedMessages([]);
        setMessages([]);
        setUsage(null);
        setDrawerError("");
    };
 
    const handleSwitchSession = async (targetSessionId) => {
        if (streaming || targetSessionId === sessionId) {
            return;
        }
        setUsage(null);
        await loadRuntime(targetSessionId);
    };
 
    const handleDeleteSession = async (targetSessionId) => {
        if (streaming || !targetSessionId) {
            return;
        }
        try {
            await removeAiSession(targetSessionId);
            notify("会话已删除");
            if (targetSessionId === sessionId) {
                startNewSession();
                await loadRuntime(null);
            }
            await loadSessions();
        } catch (error) {
            const message = error.message || "删除 AI 会话失败";
            setDrawerError(message);
            notify(message, { type: "error" });
        }
    };
 
    const stopStream = (showTip = true) => {
        if (abortRef.current) {
            abortRef.current.abort();
            abortRef.current = null;
            setStreaming(false);
            if (showTip) {
                notify("已停止当前对话输出");
            }
        }
    };
 
    const appendAssistantDelta = (delta) => {
        setMessages((prev) => {
            const next = [...prev];
            const last = next[next.length - 1];
            if (last && last.role === "assistant") {
                next[next.length - 1] = {
                    ...last,
                    content: `${last.content || ""}${delta}`,
                };
                return next;
            }
            next.push({ role: "assistant", content: delta });
            return next;
        });
    };
 
    const ensureAssistantPlaceholder = (seedMessages) => {
        const next = [...seedMessages];
        const last = next[next.length - 1];
        if (!last || last.role !== "assistant") {
            next.push({ role: "assistant", content: "" });
        }
        return next;
    };
 
    const handleSend = async () => {
        const content = input.trim();
        if (!content || streaming) {
            return;
        }
        const memoryMessages = [{ role: "user", content }];
        const nextMessages = [...messages, ...memoryMessages];
        setInput("");
        setUsage(null);
        setDrawerError("");
        setMessages(ensureAssistantPlaceholder(nextMessages));
        setStreaming(true);
 
        const controller = new AbortController();
        abortRef.current = controller;
 
        let completed = false;
        let completedSessionId = sessionId;
 
        try {
            await streamAiChat(
                {
                    sessionId,
                    promptCode,
                    messages: memoryMessages,
                    metadata: {
                        path: location.pathname,
                    },
                },
                {
                    signal: controller.signal,
                    onEvent: (eventName, payload) => {
                        if (eventName === "start") {
                            setRuntime(payload);
                            if (payload?.sessionId) {
                                setSessionId(payload.sessionId);
                                completedSessionId = payload.sessionId;
                            }
                        }
                        if (eventName === "delta") {
                            appendAssistantDelta(payload?.content || "");
                        }
                        if (eventName === "done") {
                            setUsage(payload);
                            completed = true;
                            if (payload?.sessionId) {
                                completedSessionId = payload.sessionId;
                            }
                        }
                        if (eventName === "error") {
                            const message = payload?.message || "AI 对话失败";
                            setDrawerError(message);
                            notify(message, { type: "error" });
                        }
                    },
                }
            );
        } catch (error) {
            if (error?.name !== "AbortError") {
                const message = error.message || "AI 对话失败";
                setDrawerError(message);
                notify(message, { type: "error" });
            }
        } finally {
            abortRef.current = null;
            setStreaming(false);
            if (completed) {
                await Promise.all([
                    loadRuntime(completedSessionId),
                    loadSessions(),
                ]);
            }
        }
    };
 
    const handleKeyDown = (event) => {
        if (event.key === "Enter" && !event.shiftKey) {
            event.preventDefault();
            handleSend();
        }
    };
 
    return (
        <Drawer
            anchor="right"
            open={open}
            onClose={onClose}
            ModalProps={{ keepMounted: true }}
            sx={{
                zIndex: 1400,
                "& .MuiDrawer-paper": {
                    top: 0,
                    height: "100vh",
                    width: { xs: "100vw", md: "50vw" },
                },
            }}
        >
            <Box display="flex" flexDirection="column" height="100%">
                <Stack direction="row" alignItems="center" spacing={1} px={2} py={1.5}>
                    <SmartToyOutlinedIcon color="primary" />
                    <Typography variant="h6" flex={1}>
                        AI 对话
                    </Typography>
                    <IconButton size="small" onClick={startNewSession} title="新建会话" disabled={streaming}>
                        <AddCommentOutlinedIcon fontSize="small" />
                    </IconButton>
                    <IconButton size="small" onClick={onClose} title="关闭">
                        <CloseIcon fontSize="small" />
                    </IconButton>
                </Stack>
                <Divider />
 
                <Box flex={1} display="flex" flexDirection={{ xs: "column", md: "row" }} minHeight={0}>
                    <Box
                        width={{ xs: "100%", md: 240 }}
                        borderRight={{ xs: "none", md: "1px solid rgba(224, 224, 224, 1)" }}
                        borderBottom={{ xs: "1px solid rgba(224, 224, 224, 1)", md: "none" }}
                        display="flex"
                        flexDirection="column"
                        minHeight={0}
                    >
                        <Box px={2} py={1.5}>
                            <Stack direction="row" alignItems="center" justifyContent="space-between" mb={1}>
                                <Typography variant="subtitle2">会话列表</Typography>
                                <Button size="small" onClick={startNewSession} disabled={streaming}>
                                    新建会话
                                </Button>
                            </Stack>
                            <Paper variant="outlined" sx={{ overflow: "hidden" }}>
                                {!sessions.length ? (
                                    <Box px={1.5} py={1.25}>
                                        <Typography variant="body2" color="text.secondary">
                                            暂无历史会话
                                        </Typography>
                                    </Box>
                                ) : (
                                    <List disablePadding sx={{ maxHeight: { xs: 180, md: "calc(100vh - 260px)" }, overflow: "auto" }}>
                                        {sessions.map((item) => (
                                            <ListItemButton
                                                key={item.sessionId}
                                                selected={item.sessionId === sessionId}
                                                onClick={() => handleSwitchSession(item.sessionId)}
                                                disabled={streaming}
                                                alignItems="flex-start"
                                            >
                                                <ListItemText
                                                    primary={item.title || `会话 ${item.sessionId}`}
                                                    secondary={item.lastMessageTime || `Session ${item.sessionId}`}
                                                    primaryTypographyProps={{
                                                        noWrap: true,
                                                        fontSize: 14,
                                                    }}
                                                    secondaryTypographyProps={{
                                                        noWrap: true,
                                                        fontSize: 12,
                                                    }}
                                                />
                                                <IconButton
                                                    size="small"
                                                    edge="end"
                                                    disabled={streaming}
                                                    onClick={(event) => {
                                                        event.stopPropagation();
                                                        handleDeleteSession(item.sessionId);
                                                    }}
                                                    title="删除会话"
                                                >
                                                    <DeleteOutlineOutlinedIcon fontSize="small" />
                                                </IconButton>
                                            </ListItemButton>
                                        ))}
                                    </List>
                                )}
                            </Paper>
                        </Box>
                    </Box>
 
                    <Box flex={1} display="flex" flexDirection="column" minHeight={0}>
                        <Box px={2} py={1.5}>
                            <Stack direction="row" spacing={1} flexWrap="wrap" useFlexGap>
                                <Chip size="small" label={`Session: ${sessionId || "--"}`} />
                                <Chip size="small" label={`Prompt: ${runtimeSummary.promptName}`} />
                                <Chip size="small" label={`Model: ${runtimeSummary.model}`} />
                                <Chip size="small" label={`MCP: ${runtimeSummary.mountedMcpCount}`} />
                                <Chip size="small" label={`History: ${persistedMessages.length}`} />
                            </Stack>
                            <Stack direction="row" spacing={1} mt={1.5} flexWrap="wrap" useFlexGap>
                                {quickLinks.map((item) => (
                                    <Button
                                        key={item.path}
                                        size="small"
                                        variant="outlined"
                                        startIcon={item.icon}
                                        onClick={() => navigate(item.path)}
                                    >
                                        {item.label}
                                    </Button>
                                ))}
                            </Stack>
                            {loadingRuntime && (
                                <Typography variant="body2" color="text.secondary" mt={1}>
                                    正在加载 AI 运行时信息...
                                </Typography>
                            )}
                            {!!drawerError && (
                                <Alert severity="warning" sx={{ mt: 1.5 }}>
                                    {drawerError}
                                </Alert>
                            )}
                        </Box>
 
                        <Divider />
 
                        <Box flex={1} overflow="auto" px={2} py={2} display="flex" flexDirection="column" gap={1.5}>
                            {!messages.length && (
                                <Paper variant="outlined" sx={{ p: 2, bgcolor: "grey.50" }}>
                                    <Typography variant="body2" color="text.secondary">
                                        这里会通过 SSE 流式返回 AI 回复。你也可以先去上面的快捷入口维护参数、Prompt 和 MCP 挂载。
                                    </Typography>
                                </Paper>
                            )}
                            {messages.map((message, index) => (
                                <Box
                                    key={`${message.role}-${index}`}
                                    display="flex"
                                    justifyContent={message.role === "user" ? "flex-end" : "flex-start"}
                                >
                                    <Paper
                                        elevation={0}
                                        sx={{
                                            px: 1.5,
                                            py: 1.25,
                                            maxWidth: "85%",
                                            borderRadius: 2,
                                            bgcolor: message.role === "user" ? "primary.main" : "grey.100",
                                            color: message.role === "user" ? "primary.contrastText" : "text.primary",
                                            whiteSpace: "pre-wrap",
                                            wordBreak: "break-word",
                                        }}
                                    >
                                        <Typography variant="caption" display="block" sx={{ opacity: 0.72, mb: 0.5 }}>
                                            {message.role === "user" ? "你" : "AI"}
                                        </Typography>
                                        <Typography variant="body2">
                                            {message.content || (streaming && index === messages.length - 1 ? "思考中..." : "")}
                                        </Typography>
                                    </Paper>
                                </Box>
                            ))}
                        </Box>
 
                        <Divider />
 
                        <Box px={2} py={1.5}>
                            {usage?.totalTokens != null && (
                                <Typography variant="caption" color="text.secondary" display="block" mb={1}>
                                    Tokens: prompt {usage?.promptTokens ?? 0} / completion {usage?.completionTokens ?? 0} / total {usage?.totalTokens ?? 0}
                                </Typography>
                            )}
                            <TextField
                                value={input}
                                onChange={(event) => setInput(event.target.value)}
                                onKeyDown={handleKeyDown}
                                fullWidth
                                multiline
                                minRows={3}
                                maxRows={6}
                                placeholder="输入你的问题,按 Enter 发送,Shift + Enter 换行"
                            />
                            <Stack direction="row" spacing={1} justifyContent="flex-end" mt={1.25}>
                                <Button onClick={() => setInput("")}>清空输入</Button>
                                {streaming ? (
                                    <Button variant="outlined" color="warning" startIcon={<StopCircleOutlinedIcon />} onClick={() => stopStream(true)}>
                                        停止
                                    </Button>
                                ) : (
                                    <Button variant="contained" startIcon={<SendRoundedIcon />} onClick={handleSend}>
                                        发送
                                    </Button>
                                )}
                            </Stack>
                        </Box>
                    </Box>
                </Box>
            </Box>
        </Drawer>
    );
};
 
export default AiChatDrawer;