A modern platform for visual, flexible, and extensible graph-based investigations. For cybersecurity analysts and investigators.
feat(app): xterm terminal component
dextmorgn15117eeb4d94
diff --git a/flowsint-app/src/components/terminal/index.ts b/flowsint-app/src/components/terminal/index.tsnew file mode 100644index 00000000..3f369132--- /dev/null+++ b/flowsint-app/src/components/terminal/index.ts@@ -0,0 +1,4 @@+export { TerminalLogViewer } from './terminal-log-viewer'+export { XTermTerminal } from './xterm-terminal'+export type { TerminalHandle } from './xterm-terminal'+export * from './log-formatter'diff --git a/flowsint-app/src/components/terminal/log-formatter.ts b/flowsint-app/src/components/terminal/log-formatter.tsnew file mode 100644index 00000000..011a5008--- /dev/null+++ b/flowsint-app/src/components/terminal/log-formatter.ts@@ -0,0 +1,121 @@+import { EventLevel } from '@/types'++// ANSI color codes+export const ANSI = {+ RESET: '\x1b[0m',+ BOLD: '\x1b[1m',+ DIM: '\x1b[2m',++ // Foreground colors+ BLACK: '\x1b[30m',+ RED: '\x1b[31m',+ GREEN: '\x1b[32m',+ YELLOW: '\x1b[33m',+ BLUE: '\x1b[34m',+ MAGENTA: '\x1b[35m',+ CYAN: '\x1b[36m',+ WHITE: '\x1b[37m',+ GRAY: '\x1b[90m',++ // Bright foreground colors+ BRIGHT_RED: '\x1b[91m',+ BRIGHT_GREEN: '\x1b[92m',+ BRIGHT_YELLOW: '\x1b[93m',+ BRIGHT_BLUE: '\x1b[94m',+ BRIGHT_MAGENTA: '\x1b[95m',+ BRIGHT_CYAN: '\x1b[96m',+ BRIGHT_WHITE: '\x1b[97m',+}++// Log level configuration with ANSI colors+export const logLevelColors = {+ [EventLevel.INFO]: {+ color: ANSI.BRIGHT_BLUE,+ emoji: 'ℹ',+ label: 'INFO'+ },+ [EventLevel.WARNING]: {+ color: ANSI.BRIGHT_YELLOW,+ emoji: '⚠',+ label: 'WARN'+ },+ [EventLevel.FAILED]: {+ color: ANSI.BRIGHT_RED,+ emoji: '✗',+ label: 'FAIL'+ },+ [EventLevel.SUCCESS]: {+ color: ANSI.BRIGHT_GREEN,+ emoji: '✓',+ label: 'SUCC'+ },+ [EventLevel.DEBUG]: {+ color: ANSI.BRIGHT_MAGENTA,+ emoji: '⚡',+ label: 'DEBG'+ },+ [EventLevel.PENDING]: {+ color: ANSI.YELLOW,+ emoji: '⏳',+ label: 'PEND'+ },+ [EventLevel.RUNNING]: {+ color: ANSI.CYAN,+ emoji: '↻',+ label: 'RUN '+ },+ [EventLevel.COMPLETED]: {+ color: ANSI.GREEN,+ emoji: '✓',+ label: 'CMPL'+ },+ [EventLevel.GRAPH_APPEND]: {+ color: ANSI.MAGENTA,+ emoji: '📊',+ label: 'GRPH'+ }+}++const defaultColors = {+ color: ANSI.GRAY,+ emoji: '•',+ label: 'INFO'+}++export const formatTime = (date: string): string => {+ return new Date(date).toLocaleTimeString('en-US', {+ hour12: false,+ hour: '2-digit',+ minute: '2-digit',+ second: '2-digit'+ })+}++export const formatLogEntry = (+ timestamp: string,+ level: EventLevel,+ message: string+): string => {+ const config = logLevelColors[level] || defaultColors+ const time = formatTime(timestamp)++ // Format: [HH:MM:SS] LEVEL emoji message+ return (+ `${ANSI.DIM}[${time}]${ANSI.RESET} ` ++ `${config.color}${ANSI.BOLD}${config.label}${ANSI.RESET} ` ++ `${message}\r\n`+ )+}++export const clearScreen = (): string => {+ return '\x1b[2J\x1b[H'+}++export const formatWelcomeMessage = (): string => {+ return (+ `${ANSI.BRIGHT_CYAN}${ANSI.BOLD}╭───────────────────────────────────────────╮${ANSI.RESET}\r\n` ++ `${ANSI.BRIGHT_CYAN}${ANSI.BOLD}│${ANSI.RESET} ${ANSI.BRIGHT_WHITE}⚡ Flowsint transforms terminal${ANSI.RESET} ${ANSI.BRIGHT_CYAN}${ANSI.BOLD}│${ANSI.RESET}\r\n` ++ `${ANSI.BRIGHT_CYAN}${ANSI.BOLD}╰───────────────────────────────────────────╯${ANSI.RESET}\r\n` ++ `${ANSI.DIM}Waiting for investigation activity...${ANSI.RESET}\r\n\r\n`+ )+}diff --git a/flowsint-app/src/components/terminal/terminal-log-viewer.tsx b/flowsint-app/src/components/terminal/terminal-log-viewer.tsxnew file mode 100644index 00000000..62307729--- /dev/null+++ b/flowsint-app/src/components/terminal/terminal-log-viewer.tsx@@ -0,0 +1,172 @@+import { useEffect, useRef, useCallback } from 'react'+import { XTermTerminal, TerminalHandle } from './xterm-terminal'+import { formatLogEntry, formatWelcomeMessage } from './log-formatter'+import { Button } from '../ui/button'+import { RotateCcw, Trash2, Maximize2 } from 'lucide-react'+import { EventLevel } from '@/types'++interface LogEntry {+ type: EventLevel+ payload: {+ message: string+ }+ created_at: string+}++interface TerminalLogViewerProps {+ logs: LogEntry[]+ onRefresh?: () => void+ onClear?: () => void+}++export const TerminalLogViewer = ({+ logs,+ onRefresh,+ onClear+}: TerminalLogViewerProps) => {+ const terminalRef = useRef<TerminalHandle>(null)+ const previousLogsRef = useRef<LogEntry[]>([])+ const isInitializedRef = useRef(false)+ const logsRef = useRef(logs)++ // Keep logs ref in sync+ useEffect(() => {+ logsRef.current = logs+ }, [logs])++ // Initialize terminal with welcome message and existing logs+ const handleTerminalReady = useCallback(() => {+ if (!terminalRef.current) return++ console.log('[TerminalLogViewer] Terminal ready, initializing with logs', {+ logCount: logsRef.current.length,+ wasInitialized: isInitializedRef.current+ })++ // Write welcome message only if no logs+ if (logsRef.current.length === 0) {+ terminalRef.current.write(formatWelcomeMessage())+ } else {+ // Write all existing logs+ logsRef.current.forEach((log) => {+ const formattedLog = formatLogEntry(+ log.created_at,+ log.type,+ log.payload.message+ )+ terminalRef.current?.write(formattedLog)+ })+ }++ previousLogsRef.current = [...logsRef.current]+ isInitializedRef.current = true+ }, [])++ // Write new logs to terminal without causing re-renders+ useEffect(() => {+ if (!terminalRef.current || !isInitializedRef.current) {+ return+ }++ const previousLogs = previousLogsRef.current+ const currentLogs = logs++ console.log('[TerminalLogViewer] Log update', {+ previousCount: previousLogs.length,+ currentCount: currentLogs.length,+ latestLogs: currentLogs.slice(-3)+ })++ // Find new logs by comparing timestamps and messages+ // This works even when the total length stays the same (e.g., 100 logs with slice)+ const newLogs = currentLogs.filter((currentLog) => {+ return !previousLogs.some(+ (prevLog) =>+ prevLog.created_at === currentLog.created_at &&+ prevLog.payload.message === currentLog.payload.message+ )+ })++ if (newLogs.length > 0) {+ console.log('[TerminalLogViewer] Writing new logs', newLogs.length)++ newLogs.forEach((log) => {+ const formattedLog = formatLogEntry(+ log.created_at,+ log.type,+ log.payload.message+ )+ terminalRef.current?.write(formattedLog)+ })+ }++ // Check if logs were cleared (much shorter than before)+ if (currentLogs.length < previousLogs.length / 2) {+ console.log('[TerminalLogViewer] Logs cleared, resetting terminal')+ terminalRef.current.clear()++ if (currentLogs.length === 0) {+ terminalRef.current.write(formatWelcomeMessage())+ } else {+ // Write all current logs+ currentLogs.forEach((log) => {+ const formattedLog = formatLogEntry(+ log.created_at,+ log.type,+ log.payload.message+ )+ terminalRef.current?.write(formattedLog)+ })+ }+ }++ // Update previous logs reference+ previousLogsRef.current = [...currentLogs]+ }, [logs])++ const handleClearTerminal = useCallback(() => {+ terminalRef.current?.clear()+ terminalRef.current?.write(formatWelcomeMessage())+ onClear?.()+ }, [onClear])++ const handleRefresh = useCallback(() => {+ onRefresh?.()+ }, [onRefresh])++ return (+ <div className="h-full flex flex-col relative bg-background rounded-lg overflow-hidden border border-border/50">+ {/* Terminal */}+ <div className="flex-1 min-h-0">+ <XTermTerminal+ ref={terminalRef}+ className="h-full w-full p-2"+ onReady={handleTerminalReady}+ />+ </div>++ {/* Controls */}+ <div className="absolute top-2 right-2 flex gap-1 z-10">+ <Button+ variant="ghost"+ size="icon"+ onClick={handleRefresh}+ className="h-7 w-7 bg-background/80 backdrop-blur-sm hover:bg-background/90 border border-border/50"+ title="Refresh logs"+ >+ <RotateCcw className="w-3.5 h-3.5 opacity-60" strokeWidth={1.7} />+ </Button>+ <Button+ variant="ghost"+ size="icon"+ onClick={handleClearTerminal}+ className="h-7 w-7 bg-background/80 backdrop-blur-sm hover:bg-background/90 border border-border/50"+ title="Clear terminal"+ >+ <Trash2 className="w-3.5 h-3.5 opacity-60" strokeWidth={1.7} />+ </Button>++ </div>+ </div>+ )+}diff --git a/flowsint-app/src/components/terminal/xterm-terminal.tsx b/flowsint-app/src/components/terminal/xterm-terminal.tsxnew file mode 100644index 00000000..612e9c39--- /dev/null+++ b/flowsint-app/src/components/terminal/xterm-terminal.tsx@@ -0,0 +1,170 @@+import { useEffect, useRef, useImperativeHandle, forwardRef } from 'react'+import { Terminal } from '@xterm/xterm'+import { FitAddon } from '@xterm/addon-fit'+import { WebglAddon } from '@xterm/addon-webgl'+import '@xterm/xterm/css/xterm.css'++export interface TerminalHandle {+ write: (data: string) => void+ writeln: (data: string) => void+ clear: () => void+ reset: () => void+}++interface XTermTerminalProps {+ className?: string+ onReady?: (terminal: Terminal) => void+}++export const XTermTerminal = forwardRef<TerminalHandle, XTermTerminalProps>(+ ({ className, onReady }, ref) => {+ const terminalRef = useRef<HTMLDivElement>(null)+ const xtermRef = useRef<Terminal | null>(null)+ const fitAddonRef = useRef<FitAddon | null>(null)++ useImperativeHandle(ref, () => ({+ write: (data: string) => {+ xtermRef.current?.write(data)+ },+ writeln: (data: string) => {+ xtermRef.current?.writeln(data)+ },+ clear: () => {+ xtermRef.current?.clear()+ },+ reset: () => {+ xtermRef.current?.reset()+ }+ }))++ useEffect(() => {+ if (!terminalRef.current) return++ // Detect dark mode+ const isDark = document.documentElement.classList.contains('dark')++ // Light theme colors+ const lightTheme = {+ background: '#fcfcfc',+ foreground: '#1a1a1a',+ cursor: '#3b82f6',+ cursorAccent: '#1e40af',+ selectionBackground: '#3b82f640',+ selectionForeground: '#1a1a1a',+ black: '#1a1a1a',+ red: '#dc2626',+ green: '#16a34a',+ yellow: '#ca8a04',+ blue: '#2563eb',+ magenta: '#9333ea',+ cyan: '#0891b2',+ white: '#737373',+ brightBlack: '#525252',+ brightRed: '#ef4444',+ brightGreen: '#22c55e',+ brightYellow: '#eab308',+ brightBlue: '#3b82f6',+ brightMagenta: '#a855f7',+ brightCyan: '#06b6d4',+ brightWhite: '#171717',+ }++ // Dark theme colors+ const darkTheme = {+ background: '#1b1b1b',+ foreground: '#e5e5e5',+ cursor: '#3b82f6',+ cursorAccent: '#1e40af',+ selectionBackground: '#3b82f640',+ selectionForeground: '#e5e5e5',+ black: '#18181b',+ red: '#ef4444',+ green: '#22c55e',+ yellow: '#eab308',+ blue: '#3b82f6',+ magenta: '#a855f7',+ cyan: '#06b6d4',+ white: '#e5e5e5',+ brightBlack: '#52525b',+ brightRed: '#f87171',+ brightGreen: '#4ade80',+ brightYellow: '#facc15',+ brightBlue: '#60a5fa',+ brightMagenta: '#c084fc',+ brightCyan: '#22d3ee',+ brightWhite: '#fafafa',+ }++ const terminal = new Terminal({+ fontFamily: '"Fira Code", "JetBrains Mono", "Cascadia Code", Menlo, Monaco, "Courier New", monospace',+ fontSize: 13,+ lineHeight: 1.4,+ cursorBlink: false,+ cursorStyle: 'block',+ theme: isDark ? darkTheme : lightTheme,+ allowProposedApi: true,+ scrollback: 10000,+ convertEol: true,+ disableStdin: true,+ allowTransparency: false,+ })++ // Setup addons+ const fitAddon = new FitAddon()+ terminal.loadAddon(fitAddon)++ // Open terminal+ terminal.open(terminalRef.current)++ // Try to load WebGL addon for better performance+ try {+ const webglAddon = new WebglAddon()+ webglAddon.onContextLoss(() => {+ webglAddon.dispose()+ })+ terminal.loadAddon(webglAddon)+ } catch (e) {+ console.warn('WebGL addon could not be loaded, falling back to canvas renderer', e)+ }++ // Fit terminal to container+ fitAddon.fit()++ // Store references+ xtermRef.current = terminal+ fitAddonRef.current = fitAddon++ // Notify parent component+ onReady?.(terminal)++ // Handle resize+ const resizeObserver = new ResizeObserver(() => {+ fitAddon.fit()+ })+ resizeObserver.observe(terminalRef.current)++ // Watch for theme changes (dark/light mode)+ const themeObserver = new MutationObserver(() => {+ const isDark = document.documentElement.classList.contains('dark')+ const newTheme = isDark ? darkTheme : lightTheme+ terminal.options.theme = newTheme+ })++ themeObserver.observe(document.documentElement, {+ attributes: true,+ attributeFilter: ['class']+ })++ // Cleanup+ return () => {+ resizeObserver.disconnect()+ themeObserver.disconnect()+ terminal.dispose()+ }+ }, [onReady])++ return <div ref={terminalRef} className={className} />+ }+)++XTermTerminal.displayName = 'XTermTerminal'