'use client'; import React, { useState, useEffect, useRef, useMemo } from 'react'; import { Terminal, Radio, Globe, Key, Activity, Vote, User, ArrowRightLeft, Briefcase, Mail, Brain, GitBranch, Cpu, KeyRound } from 'lucide-react'; import { getNodeIdentity, getWormholeIdentityDescriptor } from '@/mesh/meshIdentity'; import { activateWormholeGatePersona, createWormholeGatePersona, enterWormholeGate, fetchWormholeIdentity, listWormholeGatePersonas, } from '@/mesh/wormholeIdentityClient'; import GateView from './GateView'; import MarketView from './MarketView'; import ProfileView from './ProfileView'; import MessagesView from './MessagesView'; import TerminalDashboard from './TerminalDashboard'; import WeatherWidget from './WeatherWidget'; import TrendingPosts from './TrendingPosts'; import HashchainEvents from './HashchainEvents'; import NetworkStats from './NetworkStats'; import AIQueryView from './AIQueryView'; import PetitionsView from './PetitionsView'; import UpgradeView from './UpgradeView'; import ResolutionView from './ResolutionView'; import GateShutdownView from './GateShutdownView'; import BootstrapView from './BootstrapView'; import FunctionKeyView from './FunctionKeyView'; const ASCII_HEADER = ` T H E ██╗███╗ ██╗███████╗██████╗ ███╗ ██╗███████╗████████╗ ██║████╗ ██║██╔════╝██╔═══██╗████╗ ██║██╔════╝╚══██╔══╝ ██║██╔██╗ ██║█████╗ ██║ ██║██╔██╗ ██║█████╗ ██║ ██║██║╚██╗██║██╔══╝ ██║ ██║██║╚██╗██║██╔══╝ ██║ ██║██║ ╚████║██║ ╚██████╔╝██║ ╚████║███████╗ ██║ ╚═╝╚═╝ ╚═══╝╚═╝ ╚═════╝ ╚═╝ ╚═══╝╚══════╝ ╚═╝ C O M M O N S ====================================== INFONET SOVEREIGN SHELL v0.1.1 (TEST) TEST-NET CONNECTION ESTABLISHED ====================================== `; const COMING_SOON_MODULES: Record = { // BALLOT entry removed 2026-04-28: the BALLOT command now navigates // to PetitionsView (live governance DSL + petition lifecycle). GIGS: { title: 'GIGS — NETWORK BOUNTIES', desc: 'Decentralized work contracts, intelligence bounties, and mesh task allocation. Accept jobs, deliver payloads, and earn credits through verified proof-of-work completion.', status: 'MODULE STATUS: TESTNET ONLY — CONTRACT ENGINE IN DEVELOPMENT', }, EXCHANGE: { title: 'EXCHANGE — DECENTRALIZED TRADING', desc: 'Zero-KYC peer-to-peer asset exchange. Trade crypto against credits with on-chain order books, stealth addresses, and privacy-preserving settlement.', status: 'MODULE STATUS: TESTNET ONLY — LIQUIDITY POOLS NOT YET ACTIVE', }, }; const GATES = [ 'infonet', 'general-talk', 'gathered-intel', 'tracked-planes', 'ukraine-front', 'iran-front', 'world-news', 'prediction-markets', 'finance', 'cryptography', 'cryptocurrencies', 'meet-chat', 'opsec-lab' ]; const GATE_LAUNCH_RETRY_DELAY_MS = 3000; const GATE_LAUNCH_RETRY_ATTEMPTS = 20; function sleep(ms: number): Promise { return new Promise((resolve) => { window.setTimeout(resolve, ms); }); } function isGateLaneStartingError(detail: string): boolean { const lowered = String(detail || '').trim().toLowerCase(); return lowered.includes('obfuscated lane is still starting'); } const SHELL_ANON_PERSONAS_KEY = 'sb_infonet_shell_anon_personas'; function readShellAnonPersonas(): string[] { if (typeof window === 'undefined') return []; try { const raw = window.localStorage.getItem(SHELL_ANON_PERSONAS_KEY); const parsed = raw ? JSON.parse(raw) : []; return Array.isArray(parsed) ? parsed.map((value) => String(value || '').trim()).filter(Boolean) : []; } catch { return []; } } function writeShellAnonPersonas(personas: string[]): void { if (typeof window === 'undefined') return; try { window.localStorage.setItem(SHELL_ANON_PERSONAS_KEY, JSON.stringify(personas)); } catch { /* ignore */ } } function allocateShellAnonPersona(): string { const existing = readShellAnonPersonas(); const used = new Set(existing.map((persona) => persona.toLowerCase())); for (let attempt = 0; attempt < 10_000; attempt += 1) { const candidate = `anon_${Math.floor(100 + Math.random() * 9_900)}`; if (used.has(candidate.toLowerCase())) continue; writeShellAnonPersonas([...existing, candidate]); return candidate; } const fallback = `anon_${Date.now()}`; writeShellAnonPersonas([...existing, fallback]); return fallback; } const SECTIONS = [ { name: 'HELP', icon: }, { name: 'AI', icon: }, { name: 'BALLOT', icon: }, { name: 'UPGRADES', icon: }, { name: 'BOOTSTRAP', icon: }, { name: 'F-KEYS', icon: }, { name: 'GIGS', icon: }, { name: 'MESH', icon: }, { name: 'GATES', icon: }, { name: 'MARKETS', icon: }, { name: 'EXCHANGE', icon: }, { name: 'PROFILE', icon: }, { name: 'MESSAGES', icon: }, ]; interface CommandHistory { command: string; output: React.ReactNode; } interface InfonetShellProps { isOpen: boolean; onClose: () => void; onOpenLiveGate?: (gate: string) => void; onOpenDeadDrop?: (peerId: string, options?: { showSas?: boolean }) => void; } export default function InfonetShell({ isOpen, onClose, onOpenLiveGate, onOpenDeadDrop, }: InfonetShellProps) { const [input, setInput] = useState(''); const [history, setHistory] = useState([]); const [isBooting, setIsBooting] = useState(true); const [bootText, setBootText] = useState([]); // Navigation & State type ViewName = | 'terminal' | 'gate' | 'market' | 'profile' | 'messages' | 'ai' | 'petitions' | 'upgrades' | 'resolution' | 'gate-shutdown' | 'bootstrap' | 'function-keys'; const [currentView, setCurrentView] = useState('terminal'); const [activeGate, setActiveGate] = useState(null); const [persona, setPersona] = useState(null); const [activeGateMode, setActiveGateMode] = useState<'anonymous' | 'persona' | null>(null); const [inputMode, setInputMode] = useState<'normal' | 'persona'>('normal'); const [pendingGate, setPendingGate] = useState(null); const [isCitizen] = useState(false); const [comingSoonModule, setComingSoonModule] = useState(null); const [wormholePromptKey, setWormholePromptKey] = useState(''); // Targets for parameterized economy views. const [resolutionMarketId, setResolutionMarketId] = useState(null); const [shutdownGateId, setShutdownGateId] = useState(null); const [bootstrapMarketId, setBootstrapMarketId] = useState(null); const endOfTerminalRef = useRef(null); const inputRef = useRef(null); const containerRef = useRef(null); const gateLaunchAttemptRef = useRef(0); // Real mesh identity const nodeIdentity = useMemo(() => getNodeIdentity(), []); const wormholeDescriptor = useMemo(() => getWormholeIdentityDescriptor(), []); const promptHost = useMemo( () => String( nodeIdentity?.publicKey || wormholePromptKey || wormholeDescriptor?.publicKey || 'no-public-key', ).trim() || 'no-public-key', [nodeIdentity?.publicKey, wormholeDescriptor?.publicKey, wormholePromptKey], ); const shellPrompt = `${isCitizen ? 'citizen' : 'sovereign'}@${promptHost}:~$`; /* Reset + boot sequence when opened */ useEffect(() => { if (!isOpen) return; // Reset state setHistory([]); setCurrentView('terminal'); setActiveGate(null); setPersona(null); setActiveGateMode(null); setInputMode('normal'); setPendingGate(null); setInput(''); gateLaunchAttemptRef.current += 1; setIsBooting(true); setBootText([]); const bootLines = [ 'INITIALIZING KERNEL...', 'LOADING MODULES: [OK]', 'MOUNTING VFS: [OK]', 'STARTING NETWORK INTERFACES...', 'CONNECTING TO INFONET MESH...', 'ESTABLISHING SECURE TUNNEL...', 'HANDSHAKE COMPLETE.', 'WELCOME SOVEREIGN.' ]; let currentLine = 0; const interval = setInterval(() => { if (currentLine < bootLines.length) { setBootText(prev => [...prev, bootLines[currentLine]]); currentLine++; } else { clearInterval(interval); setTimeout(() => setIsBooting(false), 500); } }, 150); return () => clearInterval(interval); }, [isOpen]); /* Focus input after boot — scoped to container */ useEffect(() => { if (!isBooting && isOpen) { inputRef.current?.focus(); const container = containerRef.current; if (!container) return; const handleGlobalClick = () => { if (window.getSelection()?.toString()) return; inputRef.current?.focus(); }; container.addEventListener('click', handleGlobalClick); return () => container.removeEventListener('click', handleGlobalClick); } }, [isBooting, isOpen]); useEffect(() => { let cancelled = false; if (!isOpen || nodeIdentity?.publicKey) return; void (async () => { try { const identity = await fetchWormholeIdentity(); if (!cancelled) { setWormholePromptKey(String(identity?.public_key || '').trim()); } } catch { if (!cancelled) { setWormholePromptKey(''); } } })(); return () => { cancelled = true; }; }, [isOpen, nodeIdentity?.publicKey]); /* Scroll to bottom */ useEffect(() => { endOfTerminalRef.current?.scrollIntoView({ behavior: 'smooth' }); }, [history]); const handleNavigate = (view: 'terminal' | 'gate' | 'market' | 'profile' | 'messages' | 'ai', gate?: string) => { if (view === 'gate' && gate) { if (onOpenLiveGate) { setPendingGate(gate); setInputMode('persona'); setHistory(prev => [...prev, { command: `join ${gate}`, output: ( Type a gate face label to open the encrypted room, or type {' '} anon {' '} for a rotating obfuscated session that opens the room under a fresh gate-scoped key. {' '} 'shadowbroker' is reserved. ) }]); return; } setActiveGate(gate); setActiveGateMode(persona ? 'persona' : 'anonymous'); } setCurrentView(view); }; const renderGateDirectory = (variant: 'landing' | 'command' = 'command') => (

AVAILABLE OBFUSCATED GATES:

{GATES.map(gate => ( ))}
); const openGateWhenReady = async ( gateTarget: string, operation: () => Promise, options: { commandLabel: string; waitingOutput: React.ReactNode; failurePrefix: string }, ) => { const launchId = ++gateLaunchAttemptRef.current; let waitingShown = false; for (let attempt = 0; attempt < GATE_LAUNCH_RETRY_ATTEMPTS; attempt += 1) { if (gateLaunchAttemptRef.current !== launchId) { return; } try { await operation(); return; } catch (error) { const detail = error instanceof Error ? error.message : options.failurePrefix; if (!isGateLaneStartingError(detail)) { if (gateLaunchAttemptRef.current !== launchId) { return; } setHistory(prev => [...prev, { command: options.commandLabel, output: ERR: {detail}, }]); return; } if (!waitingShown) { waitingShown = true; setHistory(prev => [...prev, { command: options.commandLabel, output: options.waitingOutput, }]); } if (attempt === GATE_LAUNCH_RETRY_ATTEMPTS - 1) { if (gateLaunchAttemptRef.current !== launchId) { return; } setHistory(prev => [...prev, { command: options.commandLabel, output: ( ERR: The obfuscated lane is taking too long to come online. It is still warming up in the background. ), }]); return; } await sleep(GATE_LAUNCH_RETRY_DELAY_MS); } } }; const handleCommand = (cmd: string) => { const trimmedCmd = cmd.trim().toLowerCase(); let output: React.ReactNode = ''; if (trimmedCmd === '') return; if (inputMode === 'persona') { if (trimmedCmd === 'shadowbroker') { output = ERR: Persona 'shadowbroker' is reserved and cannot be claimed.; setHistory(prev => [...prev, { command: cmd, output }]); return; } if (!pendingGate) { setInputMode('normal'); output = ERR: No pending gate launch target.; setHistory(prev => [...prev, { command: cmd, output }]); return; } const chosenPersona = trimmedCmd === 'anon' ? allocateShellAnonPersona() : cmd.trim(); setPersona(chosenPersona); setInputMode('normal'); const gateTarget = pendingGate; if (trimmedCmd === 'anon') { output = ( Rotating anonymous gate key for g/{gateTarget}... ); setHistory(prev => [...prev, { command: cmd, output }]); setPendingGate(null); void (async () => { await openGateWhenReady( gateTarget, async () => { await enterWormholeGate(gateTarget, true); setActiveGateMode('anonymous'); setActiveGate(gateTarget); setCurrentView('gate'); }, { commandLabel: `gate ${gateTarget}`, waitingOutput: ( Warming the obfuscated lane for g/{gateTarget}. The room will open automatically as soon as it is ready. ), failurePrefix: 'anonymous_gate_enter_failed', }, ); })(); return; } output = Creating gate face '{chosenPersona}' for g/{gateTarget}...; setHistory(prev => [...prev, { command: cmd, output }]); setPendingGate(null); void (async () => { await openGateWhenReady( gateTarget, async () => { const personas = await listWormholeGatePersonas(gateTarget); const existing = Array.isArray(personas?.personas) ? personas.personas.find( (candidate) => String(candidate?.label || '').trim().toLowerCase() === chosenPersona.toLowerCase(), ) : null; const result = existing?.persona_id ? await activateWormholeGatePersona(gateTarget, existing.persona_id) : await createWormholeGatePersona(gateTarget, chosenPersona); if (!result?.ok) { throw new Error(result?.detail || 'gate_face_create_failed'); } setActiveGateMode('persona'); setActiveGate(gateTarget); setCurrentView('gate'); }, { commandLabel: `join ${gateTarget}`, waitingOutput: ( Warming the obfuscated lane for g/{gateTarget}. Your gate face will open automatically when the room is ready. ), failurePrefix: 'gate_face_create_failed', }, ); })(); return; } if (trimmedCmd === 'help') { output = (

AVAILABLE COMMANDS:

  • help - Display this message
  • clear - Clear terminal output
  • mesh - Access public mesh ledger
  • radio - Open SIGINT / radio surfaces
  • messages - Open Secure Comms
  • profile - View sovereign identity & ledger
  • ballot / petitions / governance - File / sign / vote on petitions (DSL executor)
  • upgrades - Upgrade-hash governance + Heavy-Node readiness
  • resolution [market_id] - Evidence + dispute view
  • shutdown [gate_id] - Gate suspend / shutdown / appeal lifecycle
  • bootstrap - Bootstrap-mode resolution + ramp milestones
  • fkeys / function-keys - Anonymous citizenship proof design
  • gigs - View network bounties & jobs
  • markets - View prediction markets
  • exchange - Decentralized crypto exchange
  • wormhole - Check secure tunneling status
  • gates - List available obfuscated gates
  • join [gate] - Choose anonymous entry or a gate face, then enter the room
  • exit - Disconnect from Infonet
); } else if (trimmedCmd === 'clear') { setHistory([]); return; } else if (trimmedCmd === 'gates') { output = renderGateDirectory('command'); } else if (trimmedCmd.startsWith('join ') || trimmedCmd.startsWith('g/')) { const target = trimmedCmd.startsWith('g/') ? trimmedCmd.slice(2) : trimmedCmd.split(' ')[1]; if (GATES.includes(target)) { handleNavigate('gate', target); return; } else { output = ERR: Gate '{target}' not found or access denied.; } } else if (trimmedCmd === 'ai' || trimmedCmd === 'copilot' || trimmedCmd === 'openclaw') { handleNavigate('ai'); return; } else if (trimmedCmd === 'markets') { handleNavigate('market'); return; } else if (trimmedCmd === 'messages') { handleNavigate('messages'); return; } else if (trimmedCmd === 'profile') { handleNavigate('profile'); return; } else if (trimmedCmd === 'ballot' || trimmedCmd === 'petitions' || trimmedCmd === 'governance') { setCurrentView('petitions'); return; } else if (trimmedCmd === 'upgrades' || trimmedCmd === 'upgrade') { setCurrentView('upgrades'); return; } else if (trimmedCmd === 'bootstrap') { setBootstrapMarketId(null); setCurrentView('bootstrap'); return; } else if (trimmedCmd === 'function-keys' || trimmedCmd === 'fkeys') { setCurrentView('function-keys'); return; } else if (trimmedCmd.startsWith('resolution ')) { const mid = trimmedCmd.slice('resolution '.length).trim(); if (mid) { setResolutionMarketId(mid); setCurrentView('resolution'); return; } output = Usage: resolution <market_id>; } else if (trimmedCmd.startsWith('shutdown ')) { const gid = trimmedCmd.slice('shutdown '.length).trim(); if (gid) { setShutdownGateId(gid); setCurrentView('gate-shutdown'); return; } output = Usage: shutdown <gate_id>; } else if (trimmedCmd === 'work' || trimmedCmd === 'gigs') { setComingSoonModule('GIGS'); return; } else if (trimmedCmd === 'exchange') { setComingSoonModule('EXCHANGE'); return; } else if (trimmedCmd === 'mesh') { output = (

SYNCING PUBLIC MESH LEDGER...

Block: #894921 | Hash: 0x9f8a...2b1c

Block: #894920 | Hash: 0x3e1d...9a4f

Block: #894919 | Hash: 0x7c2b...1e8d

Ledger synchronized.

); } else if (trimmedCmd === 'radio') { output = (

SCANNING FREQUENCIES...

144.390 MHz - APRS traffic detected

462.562 MHz - Encrypted burst

8.992 MHz - EAM broadcast intercepted

); } else if (trimmedCmd === 'wormhole') { output = (

OBFUSCATED LANE STATUS:

Status: ONLINE

Active Tunnels: 3

Use join [gate] to open an obfuscated gate room.

); } else if (trimmedCmd === 'whoami') { output = ( {`${persona || 'unassigned'}${nodeIdentity?.nodeId ? ` (${nodeIdentity.nodeId})` : ''}${nodeIdentity?.publicKey ? ` / ${nodeIdentity.publicKey}` : ''}`} ); } else if (trimmedCmd === 'date') { output = {new Date().toISOString()}; } else if (trimmedCmd === 'exit') { onClose(); return; } else { output = Command not recognized: {trimmedCmd}. Type 'help' for available commands.; } setHistory(prev => [...prev, { command: cmd, output }]); }; const handleKeyDown = (e: React.KeyboardEvent) => { if (e.key === 'Enter') { if (inputMode === 'normal' && input.startsWith('g/') && searchMatch) { handleCommand(`join ${searchMatch}`); } else { handleCommand(input); } setInput(''); } else if (e.key === 'Tab') { e.preventDefault(); if (inputMode === 'normal' && input.startsWith('g/') && searchMatch) { setInput(`g/${searchMatch}`); } } }; // Autocomplete logic const searchMatch = (inputMode === 'normal' && input.startsWith('g/')) ? GATES.find(g => g.startsWith(input.slice(2).toLowerCase())) : null; if (isBooting) { return (
{bootText.map((line, i) => (
{line}
))}
); } return (
{currentView === 'terminal' && ( <> {/* Top Navigation / Quick Launch */}
{SECTIONS.map((section) => ( ))}
{/* Main Terminal Area */}
                  {ASCII_HEADER}
                

Welcome to Infonet. Type 'help' to see available commands.

Type 'gates' or g/ to view available chatrooms.

{renderGateDirectory('landing')}
handleNavigate(view)} onComingSoon={(mod) => setComingSoonModule(mod)} /> {history.map((entry, i) => (
{shellPrompt} {entry.command}
{entry.output}
))}
{/* Input Area */}
{searchMatch && input.length > 2 && (
Jump to: g/{searchMatch} [Press Tab to autocomplete, Enter to join]
)}
{inputMode === 'persona' ? 'Enter Persona: ' : shellPrompt}
setInput(e.target.value)} onKeyDown={handleKeyDown} className="w-full bg-transparent border-none outline-none text-white placeholder-gray-800 focus:ring-0 caret-transparent" spellCheck={false} autoComplete="off" autoFocus /> {/* Custom cursor */}
)} {currentView === 'gate' && activeGate && ( handleNavigate('terminal')} onNavigateGate={(gate) => handleNavigate('gate', gate)} onOpenLiveGate={onOpenLiveGate} onOpenShutdownPetition={(gate) => { setShutdownGateId(gate); setCurrentView('gate-shutdown'); }} availableGates={GATES} /> )} {currentView === 'market' && ( handleNavigate('terminal')} /> )} {currentView === 'profile' && ( handleNavigate('terminal')} persona={persona || 'unassigned'} isCitizen={isCitizen} nodeId={nodeIdentity?.nodeId} publicKey={nodeIdentity?.publicKey} /> )} {currentView === 'messages' && ( handleNavigate('terminal')} onOpenDeadDrop={onOpenDeadDrop} /> )} {currentView === 'ai' && ( handleNavigate('terminal')} /> )} {currentView === 'petitions' && ( setCurrentView('terminal')} /> )} {currentView === 'upgrades' && ( setCurrentView('terminal')} /> )} {currentView === 'resolution' && resolutionMarketId && ( setCurrentView('terminal')} /> )} {currentView === 'gate-shutdown' && shutdownGateId && ( setCurrentView('terminal')} /> )} {currentView === 'bootstrap' && ( setCurrentView('terminal')} /> )} {currentView === 'function-keys' && ( setCurrentView('terminal')} /> )} {/* Coming Soon Popup */} {comingSoonModule && COMING_SOON_MODULES[comingSoonModule] && (
{/* Header bar */}
System Notice
{/* Content */}
{COMING_SOON_MODULES[comingSoonModule].title}

{COMING_SOON_MODULES[comingSoonModule].desc}

{COMING_SOON_MODULES[comingSoonModule].status}
Infonet Sovereign Shell v0.1.1 — Test-Net
)}
); }