import { Pause, Play, RotateCw, Send, Sparkles, Terminal, Trash2, X } from "lucide-react"; import { type FormEvent, type ReactNode, useCallback, useEffect, useMemo, useState } from "react"; import { platformApiClient } from "../api/client"; import type { LogEntryBody, LogStreamResponse } from "../api/types"; import { sourceRCONRawCommandRequest } from "../schemas/sourceRcon"; import { cx } from "../utils/classes"; import { EmptyState, ErrorState, LoadingState, ResultBadge } from "./StateViews"; type LoadState = { status: "loading" } | { status: "error"; reason: string } | { status: "ready"; data: T }; type LiveLogEntry = LogEntryBody & { source: string; streamId: string; streamKey: string }; type TerminalLine = { id: string; tone: "input" | "info" | "success" | "error"; text: string; at: string }; const liveLogPollMs = 2000; const maxLogEntries = 500; interface LiveOperationDrawerProps { open: boolean; title: string; description?: string; onClose: () => void; children: ReactNode; } function LiveOperationDrawer({ open, title, description, onClose, children }: LiveOperationDrawerProps) { useEffect(() => { if (!open) return undefined; const previous = document.body.style.overflow; const handleKeyDown = (event: KeyboardEvent) => { if (event.key === "Escape") onClose(); }; document.body.style.overflow = "hidden"; document.addEventListener("keydown", handleKeyDown); return () => { document.body.style.overflow = previous; document.removeEventListener("keydown", handleKeyDown); }; }, [onClose, open]); if (!open) return null; return (
); } interface ServerLiveLogDrawerProps { open: boolean; serverId: string; serverName: string; onClose: () => void; } export function ServerLiveLogDrawer({ open, serverId, serverName, onClose }: ServerLiveLogDrawerProps) { const [streams, setStreams] = useState>({ status: "loading" }); const [selectedStreamId, setSelectedStreamId] = useState(""); const [entries, setEntries] = useState([]); const [cursorByStream, setCursorByStream] = useState>({}); const [paused, setPaused] = useState(false); const [keyword, setKeyword] = useState(""); const [lastRefreshAt, setLastRefreshAt] = useState(""); const loadStreams = useCallback(async () => { if (!open) return; setStreams({ status: "loading" }); try { const response = await platformApiClient.listServerLiveLogs(serverId); setStreams({ status: "ready", data: response.items }); setSelectedStreamId((current) => response.items.some((stream) => stream.id === current) ? current : response.items[0]?.id ?? ""); } catch (error) { setStreams({ status: "error", reason: error instanceof Error ? error.message : "实时日志源加载失败" }); } }, [open, serverId]); useEffect(() => { if (!open) return; setEntries([]); setCursorByStream({}); setPaused(false); void loadStreams(); }, [loadStreams, open]); const selectedStream = streams.status === "ready" ? streams.data.find((stream) => stream.id === selectedStreamId) : undefined; const tailSelectedStream = useCallback(async () => { if (!open || !selectedStream) return; const afterSeq = cursorByStream[selectedStream.id] ?? 0; const cursor = await platformApiClient.queryLogStream({ logStreamId: selectedStream.id, afterSeq, limit: 100 }); setCursorByStream((current) => ({ ...current, [selectedStream.id]: Math.max(current[selectedStream.id] ?? 0, cursor.nextSeq, cursor.latestSeq) })); setLastRefreshAt(new Date().toLocaleTimeString()); if (cursor.entries.length === 0) return; setEntries((current) => [ ...current, ...cursor.entries.map((entry) => ({ ...entry, source: selectedStream.source || selectedStream.streamKey, streamId: selectedStream.id, streamKey: selectedStream.streamKey })) ].slice(-maxLogEntries)); }, [cursorByStream, open, selectedStream]); useEffect(() => { if (!open || paused || !selectedStream) return undefined; void tailSelectedStream().catch(() => undefined); const timer = window.setInterval(() => void tailSelectedStream().catch(() => undefined), liveLogPollMs); return () => window.clearInterval(timer); }, [open, paused, selectedStream, tailSelectedStream]); const visibleEntries = useMemo(() => { const query = keyword.trim().toLowerCase(); return entries.filter((entry) => entry.streamId === selectedStreamId && (!query || entry.line.toLowerCase().includes(query) || (entry.level ?? "info").toLowerCase().includes(query))); }, [entries, keyword, selectedStreamId]); function clearVisibleBuffer() { setEntries((current) => current.filter((entry) => entry.streamId !== selectedStreamId)); if (selectedStream) setCursorByStream((current) => ({ ...current, [selectedStream.id]: selectedStream.latestSeq })); } return (
setKeyword(event.target.value)} />
状态:{paused ? "已暂停" : "自动刷新"} · 最新刷新 {lastRefreshAt || "等待"} · 游标 {selectedStream ? cursorByStream[selectedStream.id] ?? 0 : "--"} {streams.status === "loading" && } {streams.status === "error" && void loadStreams()} compact />} {streams.status === "ready" && streams.data.length === 0 && } {streams.status === "ready" && streams.data.length > 0 && visibleEntries.length === 0 && } {visibleEntries.length > 0 && (
{visibleEntries.map((entry) => (
{(entry.level ?? "info").toUpperCase()} {entry.line}
))}
)}
); } interface ServerManagementTerminalDrawerProps { open: boolean; serverId: string; serverName: string; pluginId: string; canManage: boolean; onClose: () => void; } export function ServerManagementTerminalDrawer({ open, serverId, serverName, pluginId, canManage, onClose }: ServerManagementTerminalDrawerProps) { const [command, setCommand] = useState(""); const [pending, setPending] = useState(false); const [lines, setLines] = useState([]); const [result, setResult] = useState<{ status: "pending" | "succeeded" | "failed"; label: string } | null>(null); const supportsCommands = pluginId === "game.scum"; useEffect(() => { if (!open) return; setCommand(""); setPending(false); setResult(null); setLines([{ id: `open-${Date.now()}`, tone: "info", text: supportsCommands ? "SCUM 管理终端已连接到平台 Source RCON 调度通道。" : "该插件暂未声明可用的管理终端命令通道。", at: new Date().toLocaleTimeString() }]); }, [open, supportsCommands]); async function submitCommand(event: FormEvent) { event.preventDefault(); if (!supportsCommands || !canManage || pending || !command.trim()) return; const submitted = command.trim(); setCommand(""); setPending(true); setResult({ status: "pending", label: "正在提交命令" }); setLines((current) => [...current, { id: `input-${Date.now()}`, tone: "input", text: `> ${submitted}`, at: new Date().toLocaleTimeString() }]); try { const response = await platformApiClient.sendSourceRCONCommand(serverId, sourceRCONRawCommandRequest(serverId, submitted)); const label = `已排队 · 任务 ${response.jobId}`; setResult({ status: "succeeded", label }); setLines((current) => [...current, { id: `ok-${response.jobId}`, tone: "success", text: `${label} · ${response.message || response.status}`, at: new Date().toLocaleTimeString() }]); } catch (error) { const label = error instanceof Error ? error.message : "命令提交失败"; setResult({ status: "failed", label }); setLines((current) => [...current, { id: `err-${Date.now()}`, tone: "error", text: label, at: new Date().toLocaleTimeString() }]); } finally { setPending(false); } } return (
{lines.map((line) =>
{line.text}
)}
{result && } {!supportsCommands && } title="终端不可用" description="当前插件没有声明平台可调度的即时命令能力,因此不会开放浏览器直连 shell。" />} {supportsCommands && (
void submitCommand(event)}>
)}
); } function levelClass(level?: string): string { const normalized = (level ?? "info").toLowerCase(); if (normalized === "error" || normalized === "fatal") return "log-level-error"; if (normalized === "warn" || normalized === "warning") return "log-level-warn"; return "log-level-info"; }