Refine management terminal logs and command UX
This commit is contained in:
@@ -1,5 +1,5 @@
|
||||
import { ListChecks, Pause, Play, RotateCw, Send, Sparkles, Terminal, Trash2, X } from "lucide-react";
|
||||
import { type FormEvent, type ReactNode, useCallback, useEffect, useMemo, useState } from "react";
|
||||
import { type FormEvent, type KeyboardEvent as ReactKeyboardEvent, type ReactNode, useCallback, useEffect, useMemo, useState } from "react";
|
||||
|
||||
import { platformApiClient } from "../api/client";
|
||||
import type { LogEntryBody, LogStreamResponse } from "../api/types";
|
||||
@@ -9,16 +9,24 @@ import { EmptyState, ErrorState, LoadingState, ResultBadge } from "./StateViews"
|
||||
|
||||
type LoadState<T> = { 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 };
|
||||
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 liveLogPollMs = 2000;
|
||||
const liveLogPollMs = 1000;
|
||||
const terminalLogPollMs = 1000;
|
||||
const logStreamPollMs = 5000;
|
||||
const liveLogHistoryWindow = 100;
|
||||
const terminalLogQueryLimit = 150;
|
||||
const terminalHistoryWindow = 150;
|
||||
const maxLogEntries = 500;
|
||||
const terminalQuickCommands = [
|
||||
{ label: "查询玩家", command: "ListPlayers" },
|
||||
{ label: "服务器状态", command: "ServerInfo" },
|
||||
{ label: "设为中午", command: "SetTime 12" },
|
||||
{ label: "保存世界", command: "SaveWorld" }
|
||||
];
|
||||
const maxTerminalLines = 600;
|
||||
const terminalQuickCommandCatalog: Record<string, TerminalQuickCommand[]> = {
|
||||
"game.scum": [
|
||||
{ label: "查询玩家", command: "ListPlayers", hint: "SCUM RCON" },
|
||||
{ label: "服务器信息", command: "ServerInfo", hint: "SCUM RCON" },
|
||||
{ label: "设为中午", command: "SetTime 12", hint: "SCUM RCON" }
|
||||
]
|
||||
};
|
||||
|
||||
interface LiveOperationDrawerProps {
|
||||
open: boolean;
|
||||
@@ -29,9 +37,10 @@ interface LiveOperationDrawerProps {
|
||||
backdropClassName?: string;
|
||||
panelClassName?: string;
|
||||
bodyClassName?: string;
|
||||
hideHeader?: boolean;
|
||||
}
|
||||
|
||||
function LiveOperationDrawer({ open, title, description, onClose, children, backdropClassName, panelClassName, bodyClassName }: LiveOperationDrawerProps) {
|
||||
function LiveOperationDrawer({ open, title, description, onClose, children, backdropClassName, panelClassName, bodyClassName, hideHeader }: LiveOperationDrawerProps) {
|
||||
useEffect(() => {
|
||||
if (!open) return undefined;
|
||||
const previous = document.body.style.overflow;
|
||||
@@ -50,13 +59,15 @@ function LiveOperationDrawer({ open, title, description, onClose, children, back
|
||||
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()}>
|
||||
<div className="panel-header">
|
||||
<div>
|
||||
<h2>{title}</h2>
|
||||
{description && <p className="page-status">{description}</p>}
|
||||
{!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>
|
||||
<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>
|
||||
@@ -79,9 +90,9 @@ export function ServerLiveLogDrawer({ open, serverId, serverName, onClose }: Ser
|
||||
const [keyword, setKeyword] = useState("");
|
||||
const [lastRefreshAt, setLastRefreshAt] = useState("");
|
||||
|
||||
const loadStreams = useCallback(async () => {
|
||||
const loadStreams = useCallback(async (showLoading = true) => {
|
||||
if (!open) return;
|
||||
setStreams({ status: "loading" });
|
||||
if (showLoading) setStreams({ status: "loading" });
|
||||
try {
|
||||
const response = await platformApiClient.listServerLiveLogs(serverId);
|
||||
setStreams({ status: "ready", data: response.items });
|
||||
@@ -99,13 +110,20 @@ export function ServerLiveLogDrawer({ open, serverId, serverName, onClose }: Ser
|
||||
void loadStreams();
|
||||
}, [loadStreams, open]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return undefined;
|
||||
const timer = window.setInterval(() => void loadStreams(false).catch(() => undefined), logStreamPollMs);
|
||||
return () => window.clearInterval(timer);
|
||||
}, [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 afterSeq = cursorByStream[selectedStream.id] ?? initialLogCursor(selectedStream, liveLogHistoryWindow);
|
||||
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) }));
|
||||
const nextSeq = nextCursorSeq(afterSeq, cursor.entries, cursor.nextSeq);
|
||||
setCursorByStream((current) => updateCursor(current, selectedStream.id, nextSeq));
|
||||
setLastRefreshAt(new Date().toLocaleTimeString());
|
||||
if (cursor.entries.length === 0) return;
|
||||
setEntries((current) => [
|
||||
@@ -131,10 +149,20 @@ export function ServerLiveLogDrawer({ open, serverId, serverName, onClose }: Ser
|
||||
if (selectedStream) setCursorByStream((current) => ({ ...current, [selectedStream.id]: selectedStream.latestSeq }));
|
||||
}
|
||||
|
||||
function selectLogStream(nextStreamId: string) {
|
||||
setSelectedStreamId(nextStreamId);
|
||||
setEntries([]);
|
||||
setCursorByStream((current) => {
|
||||
const next = { ...current };
|
||||
delete next[nextStreamId];
|
||||
return next;
|
||||
});
|
||||
}
|
||||
|
||||
return (
|
||||
<LiveOperationDrawer open={open} title="实时日志" description={`${serverName} · 每 ${liveLogPollMs / 1000} 秒刷新一次平台日志游标`} onClose={onClose}>
|
||||
<div className="log-filter-bar live-operation-toolbar">
|
||||
<select value={selectedStreamId} aria-label="选择日志源" onChange={(event) => { setSelectedStreamId(event.target.value); setEntries([]); setCursorByStream((current) => ({ ...current, [event.target.value]: 0 })); }}>
|
||||
<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)} />
|
||||
@@ -175,60 +203,173 @@ export function ServerManagementTerminalDrawer({ open, serverId, serverName, plu
|
||||
const [command, setCommand] = useState("");
|
||||
const [pending, setPending] = useState(false);
|
||||
const [lines, setLines] = useState<TerminalLine[]>([]);
|
||||
const [streams, setStreams] = useState<LoadState<LogStreamResponse[]>>({ status: "loading" });
|
||||
const [cursorByStream, setCursorByStream] = useState<Record<string, number>>({});
|
||||
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 supportsCommands = pluginId === "game.scum";
|
||||
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]);
|
||||
|
||||
const tailTerminalLogs = useCallback(async (targetStreams = terminalStreams) => {
|
||||
if (!open || targetStreams.length === 0) return;
|
||||
const cursorUpdates: Record<string, number> = {};
|
||||
const batches = await Promise.all(targetStreams.map(async (stream) => {
|
||||
const afterSeq = cursorByStream[stream.id] ?? initialLogCursor(stream, terminalHistoryWindow);
|
||||
const cursor = await platformApiClient.queryLogStream({ logStreamId: stream.id, afterSeq, limit: terminalLogQueryLimit });
|
||||
cursorUpdates[stream.id] = nextCursorSeq(afterSeq, cursor.entries, cursor.nextSeq);
|
||||
return cursor.entries.map((entry) => terminalLineFromLog(stream, entry));
|
||||
}));
|
||||
setCursorByStream((current) => {
|
||||
let changed = false;
|
||||
const next = { ...current };
|
||||
for (const [streamId, cursor] of Object.entries(cursorUpdates)) {
|
||||
const nextCursor = Math.max(next[streamId] ?? 0, cursor);
|
||||
if (nextCursor !== next[streamId]) {
|
||||
next[streamId] = nextCursor;
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
return changed ? next : current;
|
||||
});
|
||||
appendLines(batches.flat().sort(compareTerminalLines));
|
||||
}, [appendLines, cursorByStream, open, terminalStreams]);
|
||||
|
||||
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]);
|
||||
setCursorByStream({});
|
||||
setHistoryIndex(null);
|
||||
setLines([terminalSystemLine("info", supportsCommands ? "读取平台历史日志,后续按游标实时追加。" : "该插件暂未声明可用的管理终端命令通道。", "SYSTEM")]);
|
||||
void loadStreams();
|
||||
}, [loadStreams, open, supportsCommands]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return undefined;
|
||||
const timer = window.setInterval(() => void loadStreams(false).catch(() => undefined), logStreamPollMs);
|
||||
return () => window.clearInterval(timer);
|
||||
}, [loadStreams, open]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open || streams.status !== "ready") return;
|
||||
void tailTerminalLogs(terminalRelevantStreams(streams.data)).catch((error) => appendLines([terminalSystemLine("error", error instanceof Error ? error.message : "历史日志读取失败", "LOGS")]));
|
||||
}, [appendLines, open, streams]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open || terminalStreams.length === 0) return undefined;
|
||||
const timer = window.setInterval(() => void tailTerminalLogs().catch(() => undefined), terminalLogPollMs);
|
||||
return () => window.clearInterval(timer);
|
||||
}, [open, tailTerminalLogs, terminalStreams]);
|
||||
|
||||
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([]);
|
||||
}
|
||||
|
||||
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: "正在提交命令" });
|
||||
setLines((current) => [...current, { id: `input-${Date.now()}`, tone: "input", text: `> ${submitted}`, at: new Date().toLocaleTimeString() }]);
|
||||
appendLines([terminalSystemLine("input", `> ${submitted}`, "COMMAND")]);
|
||||
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() }]);
|
||||
appendLines([terminalSystemLine("success", `${label} · ${response.message || response.status}`, "PLATFORM", `ok-${response.jobId}`)]);
|
||||
void tailTerminalLogs().catch(() => undefined);
|
||||
} 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() }]);
|
||||
appendLines([terminalSystemLine("error", label, "ERROR")]);
|
||||
} finally {
|
||||
setPending(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<LiveOperationDrawer open={open} title="管理终端" description={`${serverName} · 平台授权的一次性命令调度`} onClose={onClose} backdropClassName="terminal-drawer-backdrop" panelClassName="management-terminal-drawer" bodyClassName="management-terminal-body">
|
||||
<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>最近历史 + {terminalLogPollMs / 1000}s 实时刷新 · 日志源 {logStreamPollMs / 1000}s 探测 · {streams.status === "ready" ? `${terminalStreams.length} 个日志源` : streams.status === "loading" ? "读取日志源" : "日志源异常"}</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 className="terminal-output" role="log" aria-live="polite">
|
||||
{lines.map((line) => <div key={line.id} className={`terminal-line terminal-line-${line.tone}`}><time>{line.at}</time><span>{line.text}</span></div>)}
|
||||
{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} />快捷指令</span>
|
||||
<span><ListChecks size={14} />{quickCommands.length > 0 ? "插件快捷指令" : "命令输入"}</span>
|
||||
{result && <ResultBadge status={result.status} label={result.label} />}
|
||||
</div>
|
||||
<div className="terminal-quick-command-list">
|
||||
{terminalQuickCommands.map((item) => <button key={item.command} type="button" className="terminal-quick-command" disabled={!supportsCommands || !canManage || pending} onClick={() => setCommand(item.command)}><strong>{item.label}</strong><span>{item.command}</span></button>)}
|
||||
</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>
|
||||
SCUM 管理命令
|
||||
<input value={command} disabled={!canManage || pending} placeholder={canManage ? "输入单行命令,回车提交" : "当前账号没有运行操作权限"} onChange={(event) => setCommand(event.target.value)} />
|
||||
<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>
|
||||
@@ -244,3 +385,79 @@ function levelClass(level?: string): string {
|
||||
if (normalized === "warn" || normalized === "warning") return "log-level-warn";
|
||||
return "log-level-info";
|
||||
}
|
||||
|
||||
function initialLogCursor(stream: LogStreamResponse, historyWindow: number): number {
|
||||
return Math.max(0, stream.latestSeq - historyWindow);
|
||||
}
|
||||
|
||||
function nextCursorSeq(afterSeq: number, entries: LogEntryBody[], nextSeq: number): number {
|
||||
if (entries.length === 0) return Math.max(afterSeq, nextSeq);
|
||||
return Math.max(afterSeq, nextSeq, entries[entries.length - 1]?.seq ?? afterSeq);
|
||||
}
|
||||
|
||||
function updateCursor(current: Record<string, number>, streamId: string, cursor: number): Record<string, number> {
|
||||
const nextCursor = Math.max(current[streamId] ?? 0, cursor);
|
||||
if (nextCursor === current[streamId]) return current;
|
||||
return { ...current, [streamId]: nextCursor };
|
||||
}
|
||||
|
||||
function terminalQuickCommandsForPlugin(pluginId: string): TerminalQuickCommand[] {
|
||||
return terminalQuickCommandCatalog[pluginId] ?? [];
|
||||
}
|
||||
|
||||
function terminalRelevantStreams(streams: LogStreamResponse[]): LogStreamResponse[] {
|
||||
return [...streams].sort(compareTerminalStreams).slice(0, 8);
|
||||
}
|
||||
|
||||
function compareTerminalStreams(a: LogStreamResponse, b: LogStreamResponse): number {
|
||||
return terminalStreamRank(a) - terminalStreamRank(b) || a.streamKey.localeCompare(b.streamKey) || a.id.localeCompare(b.id);
|
||||
}
|
||||
|
||||
function terminalStreamRank(stream: LogStreamResponse): number {
|
||||
const key = `${stream.source}:${stream.streamKey}`.toLowerCase();
|
||||
if (key.includes("management-program")) return 0;
|
||||
if (key.includes("stderr")) return 1;
|
||||
if (key.includes("stdout")) return 2;
|
||||
return 3;
|
||||
}
|
||||
|
||||
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 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);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user