515 lines
26 KiB
TypeScript
515 lines
26 KiB
TypeScript
import { ListChecks, Pause, Play, RotateCw, Send, Sparkles, Terminal, Trash2, X } from "lucide-react";
|
|
import { type FormEvent, type KeyboardEvent as ReactKeyboardEvent, type ReactNode, useCallback, useEffect, useMemo, useRef, useState } from "react";
|
|
|
|
import { platformApiClient } from "../api/client";
|
|
import type { GameClientBridgeCommandResponse, LogEntryBody, LogStreamResponse } from "../api/types";
|
|
import { scumManagementRCONCommandRequest } from "../schemas/scumManagementRcon";
|
|
import { cx } from "../utils/classes";
|
|
import { appendLiveLogEntries, entryFromServerLogEvent, mergeLogStreams, parseLogStreamEvent, parseServerLogEvent, streamFromServerLogEvent, type LiveLogEntry } from "../utils/logEvents";
|
|
import { EmptyState, ErrorState, LoadingState, ResultBadge } from "./StateViews";
|
|
|
|
type LoadState<T> = { status: "loading" } | { status: "error"; reason: string } | { status: "ready"; data: T };
|
|
type TerminalLine = { id: string; tone: "input" | "info" | "success" | "warn" | "error"; text: string; at: string; sortKey: number; streamKey?: string; level?: string; seq?: number };
|
|
type TerminalQuickCommand = { label: string; command: string; hint: string };
|
|
|
|
const terminalBridgeResultPollMs = 1000;
|
|
const terminalBridgeResultPollAttempts = 30;
|
|
const liveLogHistoryWindow = 100;
|
|
const terminalHistoryWindow = 10000;
|
|
const maxLogEntries = 500;
|
|
const maxTerminalLines = 10000;
|
|
const terminalQuickCommandCatalog: Record<string, TerminalQuickCommand[]> = {
|
|
"game.scum": [
|
|
{ label: "查询玩家", command: "#ListPlayers", hint: "在线玩家列表" },
|
|
{ label: "查询队伍", command: "#ListSquads 1", hint: "服务器队伍列表" },
|
|
{ label: "查询车辆", command: "#ListSpawnedVehicles true", hint: "已生成车辆列表" },
|
|
{ label: "设为中午", command: "#SetTime 12", hint: "设置游戏时间" }
|
|
]
|
|
};
|
|
|
|
interface LiveOperationDrawerProps {
|
|
open: boolean;
|
|
title: string;
|
|
description?: string;
|
|
onClose: () => void;
|
|
children: ReactNode;
|
|
backdropClassName?: string;
|
|
panelClassName?: string;
|
|
bodyClassName?: string;
|
|
hideHeader?: boolean;
|
|
}
|
|
|
|
function LiveOperationDrawer({ open, title, description, onClose, children, backdropClassName, panelClassName, bodyClassName, hideHeader }: 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 (
|
|
<div className={cx("drawer-backdrop", backdropClassName)} role="presentation" onClick={onClose}>
|
|
<aside className={cx("drawer-panel live-operation-drawer", panelClassName)} role="dialog" aria-modal="true" aria-label={title} onClick={(event) => event.stopPropagation()}>
|
|
{!hideHeader && (
|
|
<div className="panel-header">
|
|
<div>
|
|
<h2>{title}</h2>
|
|
{description && <p className="page-status">{description}</p>}
|
|
</div>
|
|
<button type="button" className="theme-upload drawer-close" aria-label={`关闭${title}`} onClick={onClose}><X size={14} /><span>关闭</span></button>
|
|
</div>
|
|
)}
|
|
<div className={cx("live-operation-content", bodyClassName)}>{children}</div>
|
|
</aside>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
interface ServerLiveLogDrawerProps {
|
|
open: boolean;
|
|
serverId: string;
|
|
serverName: string;
|
|
onClose: () => void;
|
|
}
|
|
|
|
export function ServerLiveLogDrawer({ open, serverId, serverName, onClose }: ServerLiveLogDrawerProps) {
|
|
const [streams, setStreams] = useState<LoadState<LogStreamResponse[]>>({ status: "loading" });
|
|
const [selectedStreamId, setSelectedStreamId] = useState("");
|
|
const [entries, setEntries] = useState<LiveLogEntry[]>([]);
|
|
const [paused, setPaused] = useState(false);
|
|
const [keyword, setKeyword] = useState("");
|
|
const [lastRefreshAt, setLastRefreshAt] = useState("");
|
|
const [eventSourceKey, setEventSourceKey] = useState(0);
|
|
const pausedRef = useRef(paused);
|
|
|
|
useEffect(() => {
|
|
pausedRef.current = paused;
|
|
}, [paused]);
|
|
|
|
const loadStreams = useCallback(async (showLoading = true) => {
|
|
if (!open) return;
|
|
if (showLoading) 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([]);
|
|
setPaused(false);
|
|
setLastRefreshAt("");
|
|
void loadStreams();
|
|
}, [loadStreams, open]);
|
|
|
|
useEffect(() => {
|
|
if (!open) return undefined;
|
|
let ready = false;
|
|
const events = platformApiClient.openServerLogEvents(serverId, { historyLimit: liveLogHistoryWindow });
|
|
events.addEventListener("open", () => setLastRefreshAt(new Date().toLocaleTimeString()));
|
|
events.addEventListener("stream", (event) => {
|
|
const stream = parseLogStreamEvent(event);
|
|
if (!stream) return;
|
|
ready = true;
|
|
setStreams((current) => ({ status: "ready", data: mergeLogStreams(current.status === "ready" ? current.data : [], stream) }));
|
|
setSelectedStreamId((current) => current || stream.id);
|
|
});
|
|
events.addEventListener("ready", () => {
|
|
ready = true;
|
|
setStreams((current) => current.status === "ready" ? current : { status: "ready", data: [] });
|
|
});
|
|
events.addEventListener("log", (event) => {
|
|
const payload = parseServerLogEvent(event);
|
|
if (!payload) return;
|
|
ready = true;
|
|
setLastRefreshAt(new Date().toLocaleTimeString());
|
|
setStreams((current) => ({ status: "ready", data: mergeLogStreams(current.status === "ready" ? current.data : [], streamFromServerLogEvent(payload)) }));
|
|
setSelectedStreamId((current) => current || payload.streamId);
|
|
if (pausedRef.current) return;
|
|
setEntries((current) => appendLiveLogEntries(current, [entryFromServerLogEvent(payload)], maxLogEntries));
|
|
});
|
|
events.onerror = () => {
|
|
if (!ready) setStreams({ status: "error", reason: "实时日志推送连接失败" });
|
|
};
|
|
return () => events.close();
|
|
}, [eventSourceKey, open, serverId]);
|
|
|
|
const selectedStream = streams.status === "ready" ? streams.data.find((stream) => stream.id === selectedStreamId) : undefined;
|
|
|
|
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));
|
|
}
|
|
|
|
function selectLogStream(nextStreamId: string) {
|
|
setSelectedStreamId(nextStreamId);
|
|
}
|
|
|
|
return (
|
|
<LiveOperationDrawer open={open} title="实时日志" description={`${serverName} · SSE 实时推送平台日志`} onClose={onClose}>
|
|
<div className="log-filter-bar live-operation-toolbar">
|
|
<select value={selectedStreamId} aria-label="选择日志源" onChange={(event) => selectLogStream(event.target.value)}>
|
|
{streams.status === "ready" && streams.data.map((stream) => <option key={stream.id} value={stream.id}>{stream.streamKey || stream.source} · seq {stream.latestSeq}</option>)}
|
|
</select>
|
|
<input type="search" value={keyword} placeholder="过滤可见日志" aria-label="过滤可见日志" onChange={(event) => setKeyword(event.target.value)} />
|
|
<button type="button" className="icon-command" onClick={() => setPaused((current) => !current)}>{paused ? <Play size={14} /> : <Pause size={14} />}<span>{paused ? "继续" : "暂停"}</span></button>
|
|
<button type="button" className="icon-command" onClick={() => setEventSourceKey((current) => current + 1)}><RotateCw size={14} /><span>重连</span></button>
|
|
<button type="button" className="icon-command" onClick={clearVisibleBuffer}><Trash2 size={14} /><span>清屏</span></button>
|
|
</div>
|
|
<span className="page-status">状态:{paused ? "已暂停" : "实时推送"} · 最新事件 {lastRefreshAt || "等待"} · 游标 {selectedStream ? selectedStream.latestSeq : "--"}</span>
|
|
{streams.status === "loading" && <LoadingState label="正在加载日志源…" compact />}
|
|
{streams.status === "error" && <ErrorState title="实时日志不可用" reason={streams.reason} diagnosticId={`live-logs:${serverId}`} onRetry={() => void loadStreams()} compact />}
|
|
{streams.status === "ready" && streams.data.length === 0 && <EmptyState title="暂无日志源" description="运行端还没有向平台登记该服务器的日志流。" />}
|
|
{streams.status === "ready" && streams.data.length > 0 && visibleEntries.length === 0 && <EmptyState title="等待日志" description="没有新的匹配日志;保持窗口打开会继续接收平台推送。" />}
|
|
{visibleEntries.length > 0 && (
|
|
<div className="log-list live-log-list" role="log" aria-live={paused ? "off" : "polite"}>
|
|
{visibleEntries.map((entry) => (
|
|
<div key={`${entry.streamId}-${entry.seq}`} className="log-line live-log-line">
|
|
<time>{new Date(entry.timestamp).toLocaleTimeString()}</time>
|
|
<span className={cx("log-level", levelClass(entry.level))}>{(entry.level ?? "info").toUpperCase()}</span>
|
|
<span>{entry.line}</span>
|
|
</div>
|
|
))}
|
|
</div>
|
|
)}
|
|
</LiveOperationDrawer>
|
|
);
|
|
}
|
|
|
|
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<TerminalLine[]>([]);
|
|
const [streams, setStreams] = useState<LoadState<LogStreamResponse[]>>({ status: "loading" });
|
|
const [commandHistory, setCommandHistory] = useState<string[]>([]);
|
|
const [historyIndex, setHistoryIndex] = useState<number | null>(null);
|
|
const [result, setResult] = useState<{ status: "pending" | "succeeded" | "failed"; label: string } | null>(null);
|
|
const [followLatest, setFollowLatest] = useState(true);
|
|
const outputRef = useRef<HTMLDivElement>(null);
|
|
const followLatestRef = useRef(true);
|
|
const quickCommands = useMemo(() => terminalQuickCommandsForPlugin(pluginId), [pluginId]);
|
|
const supportsCommands = quickCommands.length > 0;
|
|
const terminalStreams = useMemo(() => streams.status === "ready" ? terminalRelevantStreams(streams.data) : [], [streams]);
|
|
|
|
const appendLines = useCallback((incoming: TerminalLine[]) => {
|
|
if (incoming.length === 0) return;
|
|
setLines((current) => mergeTerminalLines(current, incoming));
|
|
}, []);
|
|
|
|
const loadStreams = useCallback(async (showLoading = true) => {
|
|
if (!open) return;
|
|
if (showLoading) setStreams({ status: "loading" });
|
|
try {
|
|
const response = await platformApiClient.listServerLiveLogs(serverId);
|
|
setStreams({ status: "ready", data: response.items });
|
|
} catch (error) {
|
|
setStreams({ status: "error", reason: error instanceof Error ? error.message : "实时日志源加载失败" });
|
|
}
|
|
}, [open, serverId]);
|
|
|
|
useEffect(() => {
|
|
if (!open) return;
|
|
setCommand("");
|
|
setPending(false);
|
|
setResult(null);
|
|
setHistoryIndex(null);
|
|
followLatestRef.current = true;
|
|
setFollowLatest(true);
|
|
setLines([terminalSystemLine("info", supportsCommands ? "连接平台日志推送,先补最近历史再实时追加。" : "该插件暂未声明可用的管理终端命令通道。", "SYSTEM")]);
|
|
void loadStreams();
|
|
}, [loadStreams, open, supportsCommands]);
|
|
|
|
useEffect(() => {
|
|
if (!open || !followLatestRef.current) return undefined;
|
|
const frame = window.requestAnimationFrame(() => {
|
|
const output = outputRef.current;
|
|
if (output) output.scrollTop = output.scrollHeight;
|
|
});
|
|
return () => window.cancelAnimationFrame(frame);
|
|
}, [lines, open]);
|
|
|
|
useEffect(() => {
|
|
if (!open) return undefined;
|
|
let ready = false;
|
|
const events = platformApiClient.openServerLogEvents(serverId, { historyLimit: terminalHistoryWindow });
|
|
events.addEventListener("stream", (event) => {
|
|
const stream = parseLogStreamEvent(event);
|
|
if (!stream) return;
|
|
ready = true;
|
|
setStreams((current) => ({ status: "ready", data: mergeLogStreams(current.status === "ready" ? current.data : [], stream) }));
|
|
});
|
|
events.addEventListener("ready", () => {
|
|
ready = true;
|
|
setStreams((current) => current.status === "ready" ? current : { status: "ready", data: [] });
|
|
});
|
|
events.addEventListener("log", (event) => {
|
|
const payload = parseServerLogEvent(event);
|
|
if (!payload) return;
|
|
ready = true;
|
|
const stream = streamFromServerLogEvent(payload);
|
|
setStreams((current) => ({ status: "ready", data: mergeLogStreams(current.status === "ready" ? current.data : [], stream) }));
|
|
appendLines([terminalLineFromLog(stream, payload.entry)]);
|
|
});
|
|
events.onerror = () => {
|
|
if (!ready) setStreams({ status: "error", reason: "实时日志推送连接失败" });
|
|
};
|
|
return () => events.close();
|
|
}, [appendLines, open, serverId]);
|
|
|
|
function selectQuickCommand(item: TerminalQuickCommand) {
|
|
setCommand(item.command);
|
|
setHistoryIndex(null);
|
|
}
|
|
|
|
function handleCommandKeyDown(event: ReactKeyboardEvent<HTMLInputElement>) {
|
|
if (event.key !== "ArrowUp" && event.key !== "ArrowDown") return;
|
|
if (commandHistory.length === 0) return;
|
|
event.preventDefault();
|
|
const lastIndex = commandHistory.length - 1;
|
|
if (event.key === "ArrowUp") {
|
|
const nextIndex = historyIndex === null ? lastIndex : Math.max(0, historyIndex - 1);
|
|
setHistoryIndex(nextIndex);
|
|
setCommand(commandHistory[nextIndex] ?? "");
|
|
return;
|
|
}
|
|
if (historyIndex === null) return;
|
|
const nextIndex = historyIndex + 1;
|
|
if (nextIndex > lastIndex) {
|
|
setHistoryIndex(null);
|
|
setCommand("");
|
|
return;
|
|
}
|
|
setHistoryIndex(nextIndex);
|
|
setCommand(commandHistory[nextIndex] ?? "");
|
|
}
|
|
|
|
function clearTerminalBuffer() {
|
|
setLines([]);
|
|
}
|
|
|
|
function handleTerminalScroll() {
|
|
const output = outputRef.current;
|
|
if (!output) return;
|
|
const nextFollowLatest = output.scrollHeight - output.clientHeight - output.scrollTop <= 24;
|
|
followLatestRef.current = nextFollowLatest;
|
|
setFollowLatest(nextFollowLatest);
|
|
}
|
|
|
|
async function submitCommand(event: FormEvent<HTMLFormElement>) {
|
|
event.preventDefault();
|
|
if (!supportsCommands || !canManage || pending || !command.trim()) return;
|
|
const submitted = command.trim();
|
|
setCommand("");
|
|
setHistoryIndex(null);
|
|
setCommandHistory((current) => [...current.filter((item) => item !== submitted), submitted].slice(-50));
|
|
setPending(true);
|
|
setResult({ status: "pending", label: "正在提交命令" });
|
|
appendLines([terminalSystemLine("input", `> ${submitted}`, "COMMAND")]);
|
|
try {
|
|
const response = await platformApiClient.queueGameClientBridgeCommand(serverId, scumManagementRCONCommandRequest(serverId, submitted));
|
|
const label = bridgeCommandDispatchLabel(response.state, response.id);
|
|
setResult({ status: "pending", label: `${label} · 等待 Run 返回结果` });
|
|
appendLines([terminalSystemLine("success", `${label} · protected RCON`, "PLATFORM", `ok-${response.id}`)]);
|
|
const finalCommand = await waitForBridgeCommandTerminal(response.id);
|
|
if (finalCommand) {
|
|
const outcome = terminalLineFromBridgeCommand(finalCommand);
|
|
setResult({ status: outcome.tone === "success" ? "succeeded" : "failed", label: outcome.text });
|
|
appendLines([outcome]);
|
|
} else {
|
|
const timeoutLine = terminalSystemLine("warn", `桥接命令 ${response.id} 已排队,但尚未返回终态;继续观察实时日志。`, "PLATFORM", `pending-${response.id}`);
|
|
setResult({ status: "pending", label: "等待 Run 返回结果" });
|
|
appendLines([timeoutLine]);
|
|
}
|
|
} catch (error) {
|
|
const label = error instanceof Error ? error.message : "命令提交失败";
|
|
setResult({ status: "failed", label });
|
|
appendLines([terminalSystemLine("error", label, "ERROR")]);
|
|
} finally {
|
|
setPending(false);
|
|
}
|
|
}
|
|
|
|
async function waitForBridgeCommandTerminal(commandId: string): Promise<GameClientBridgeCommandResponse | null> {
|
|
for (let attempt = 0; attempt < terminalBridgeResultPollAttempts; attempt += 1) {
|
|
const current = await platformApiClient.getGameClientBridgeCommand(serverId, commandId);
|
|
if (isTerminalBridgeCommandState(current.state)) return current;
|
|
await delay(terminalBridgeResultPollMs);
|
|
}
|
|
return null;
|
|
}
|
|
|
|
return (
|
|
<LiveOperationDrawer open={open} title="管理终端" onClose={onClose} backdropClassName="terminal-drawer-backdrop" panelClassName="management-terminal-drawer" bodyClassName="management-terminal-body" hideHeader>
|
|
<section className="terminal-output-panel" aria-label="terminal output">
|
|
<div className="terminal-output-topbar">
|
|
<div>
|
|
<strong>{serverName}</strong>
|
|
<span>最近历史 + SSE 实时推送 · {streams.status === "ready" ? `${terminalStreams.length} 个日志源` : streams.status === "loading" ? "读取日志源" : "日志源异常"} · {followLatest ? "自动置底" : "已解锁滚动"}</span>
|
|
</div>
|
|
<div>
|
|
<button type="button" className="terminal-output-action" onClick={clearTerminalBuffer}><Trash2 size={14} /><span>清屏</span></button>
|
|
<button type="button" className="terminal-output-action" aria-label="关闭管理终端" onClick={onClose}><X size={14} /><span>关闭</span></button>
|
|
</div>
|
|
</div>
|
|
<div ref={outputRef} className="terminal-output" role="log" aria-live="polite" onScroll={handleTerminalScroll}>
|
|
{streams.status === "error" && <div className="terminal-line terminal-line-error"><time>{new Date().toLocaleTimeString()}</time><span className="terminal-stream">LOGS</span><span className="terminal-text">{streams.reason}</span></div>}
|
|
{streams.status === "ready" && streams.data.length === 0 && <div className="terminal-line terminal-line-warn"><time>{new Date().toLocaleTimeString()}</time><span className="terminal-stream">LOGS</span><span className="terminal-text">暂无日志源。需要 Run 上报或历史日志回填后,这里才会持续追加。</span></div>}
|
|
{lines.map((line) => <div key={line.id} className={`terminal-line terminal-line-${line.tone}`}><time>{line.at}</time><span className="terminal-stream">{line.streamKey || line.level || "LOG"}</span><span className="terminal-text">{line.text}</span></div>)}
|
|
</div>
|
|
</section>
|
|
<section className="terminal-command-dock" aria-label="terminal command controls">
|
|
<div className="terminal-command-dock-header">
|
|
<span><ListChecks size={14} />{quickCommands.length > 0 ? "插件快捷指令" : "命令输入"}</span>
|
|
{result && <ResultBadge status={result.status} label={result.label} />}
|
|
</div>
|
|
{quickCommands.length > 0 && <div className="terminal-quick-command-list">
|
|
{quickCommands.map((item) => <button key={item.command} type="button" className="terminal-quick-command" disabled={!canManage || pending} onClick={() => selectQuickCommand(item)}><strong>{item.label}</strong><span>{item.command}</span><small>{item.hint}</small></button>)}
|
|
</div>}
|
|
{!supportsCommands && <EmptyState icon={<Terminal size={24} />} title="终端不可用" description="当前插件没有声明平台可调度的即时命令能力,因此不会开放浏览器直连 shell。" />}
|
|
{supportsCommands && (
|
|
<form className="terminal-command-form" onSubmit={(event) => void submitCommand(event)}>
|
|
<label>
|
|
<span>SCUM 管理命令</span>
|
|
<small>Enter 发送,↑/↓ 调出历史;命令结果以 Run 日志追加为准。</small>
|
|
<input value={command} disabled={!canManage || pending} placeholder={canManage ? "输入单行命令" : "当前账号没有运行操作权限"} onKeyDown={handleCommandKeyDown} onChange={(event) => { setCommand(event.target.value); setHistoryIndex(null); }} />
|
|
</label>
|
|
<button type="submit" className="primary-command" disabled={!canManage || pending || !command.trim()}>{pending ? <Sparkles size={15} /> : <Send size={15} />}<span>{pending ? "提交中…" : "发送"}</span></button>
|
|
</form>
|
|
)}
|
|
</section>
|
|
</LiveOperationDrawer>
|
|
);
|
|
}
|
|
|
|
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";
|
|
}
|
|
|
|
function terminalQuickCommandsForPlugin(pluginId: string): TerminalQuickCommand[] {
|
|
return terminalQuickCommandCatalog[pluginId] ?? [];
|
|
}
|
|
|
|
function bridgeCommandDispatchLabel(state: string, commandId: string): string {
|
|
return `已${state === "pending" ? "排队" : "提交"} · 桥接命令 ${commandId}`;
|
|
}
|
|
|
|
function terminalRelevantStreams(streams: LogStreamResponse[]): LogStreamResponse[] {
|
|
const active = streams.filter((stream) => stream.latestSeq > 0);
|
|
const candidates = active.length > 0 ? active : streams;
|
|
return [...candidates].sort(compareTerminalStreams).slice(0, 12);
|
|
}
|
|
|
|
function compareTerminalStreams(a: LogStreamResponse, b: LogStreamResponse): number {
|
|
const rank = terminalStreamRank(a) - terminalStreamRank(b);
|
|
if (rank !== 0) return rank;
|
|
const updated = (Date.parse(b.updatedAt) || 0) - (Date.parse(a.updatedAt) || 0);
|
|
if (updated !== 0) return updated;
|
|
return b.latestSeq - a.latestSeq || a.streamKey.localeCompare(b.streamKey) || a.id.localeCompare(b.id);
|
|
}
|
|
|
|
function terminalStreamRank(stream: LogStreamResponse): number {
|
|
const key = `${stream.source}:${stream.streamKey}`.toLowerCase();
|
|
if (stream.source === "file" || key.includes("scum.")) return 0;
|
|
if (key.includes("management-program")) return 1;
|
|
if (key.includes("stderr")) return 2;
|
|
if (key.includes("stdout")) return 3;
|
|
return 4;
|
|
}
|
|
|
|
function terminalLineFromLog(stream: LogStreamResponse, entry: LogEntryBody): TerminalLine {
|
|
return {
|
|
id: `log-${stream.id}-${entry.seq}`,
|
|
tone: terminalTone(entry),
|
|
text: entry.line,
|
|
at: new Date(entry.timestamp).toLocaleTimeString(),
|
|
sortKey: Date.parse(entry.timestamp) || Date.now(),
|
|
streamKey: stream.streamKey || stream.source,
|
|
level: entry.level,
|
|
seq: entry.seq
|
|
};
|
|
}
|
|
|
|
function terminalSystemLine(tone: TerminalLine["tone"], text: string, streamKey: string, id = `${streamKey.toLowerCase()}-${Date.now()}-${Math.random().toString(36).slice(2, 7)}`): TerminalLine {
|
|
const now = Date.now();
|
|
return { id, tone, text, at: new Date(now).toLocaleTimeString(), sortKey: now, streamKey };
|
|
}
|
|
|
|
function isTerminalBridgeCommandState(state: GameClientBridgeCommandResponse["state"]): boolean {
|
|
return state === "succeeded" || state === "failed" || state === "cancelled" || state === "expired" || state === "unknown";
|
|
}
|
|
|
|
function terminalLineFromBridgeCommand(command: GameClientBridgeCommandResponse): TerminalLine {
|
|
const summary = command.result?.summary || command.resultSummary || command.cancellation?.reason || bridgeCommandStateLabel(command.state);
|
|
const completed = command.completedAt || command.result?.completedAt || command.cancellation?.cancelledAt || command.updatedAt;
|
|
const sortKey = Date.parse(completed) || Date.now();
|
|
const tone: TerminalLine["tone"] = command.state === "succeeded" ? "success" : command.state === "failed" ? "error" : "warn";
|
|
return { id: `bridge-${command.id}-${command.state}`, tone, text: `桥接命令 ${command.id} · ${bridgeCommandStateLabel(command.state)} · ${summary}`, at: new Date(sortKey).toLocaleTimeString(), sortKey, streamKey: "BRIDGE" };
|
|
}
|
|
|
|
function bridgeCommandStateLabel(state: GameClientBridgeCommandResponse["state"]): string {
|
|
switch (state) {
|
|
case "succeeded": return "已成功";
|
|
case "failed": return "已失败";
|
|
case "cancelled": return "已取消";
|
|
case "expired": return "已过期";
|
|
case "unknown": return "状态未知";
|
|
case "claimed": return "Run 已领取";
|
|
case "pending": return "已排队";
|
|
}
|
|
}
|
|
|
|
function delay(ms: number): Promise<void> {
|
|
return new Promise((resolve) => window.setTimeout(resolve, ms));
|
|
}
|
|
|
|
function terminalTone(entry: LogEntryBody): TerminalLine["tone"] {
|
|
const value = `${entry.level ?? ""} ${entry.line}`.toLowerCase();
|
|
if (/\b(error|fatal|panic|exception|failed|failure)\b/.test(value)) return "error";
|
|
if (/\b(warn|warning|timeout|retry)\b/.test(value)) return "warn";
|
|
if (/\b(success|succeeded|ready|started|online|listening|accepted)\b/.test(value)) return "success";
|
|
return "info";
|
|
}
|
|
|
|
function mergeTerminalLines(current: TerminalLine[], incoming: TerminalLine[]): TerminalLine[] {
|
|
const seen = new Set(current.map((line) => line.id));
|
|
const merged = [...current];
|
|
for (const line of incoming) {
|
|
if (seen.has(line.id)) continue;
|
|
seen.add(line.id);
|
|
merged.push(line);
|
|
}
|
|
return merged.sort(compareTerminalLines).slice(-maxTerminalLines);
|
|
}
|
|
|
|
function compareTerminalLines(a: TerminalLine, b: TerminalLine): number {
|
|
return a.sortKey - b.sortKey || (a.seq ?? 0) - (b.seq ?? 0) || a.id.localeCompare(b.id);
|
|
}
|