Skip to content

[FEATURE] Frontend Dashboard - Next.js + 3D Parcel Visualization #4

@AGI-Corporation

Description

@AGI-Corporation

Summary

Build the Next.js 14 frontend dashboard for Sapient.X — a real-time, 3D-enabled control center for monitoring parcel agents, visualizing the metaverse economy, executing trades, and managing smart contracts. The dashboard bridges human operators and autonomous AI agents through an intuitive, data-rich interface.

Roadmap Position: Depends on #1 (AgentState data), #2 (wallet/trading data), #3 (WebSocket from MCP MessageBus). This is the final user-facing layer.


Background & Motivation

Sapient.X is a fully autonomous agent economy—but humans still need visibility and control. The dashboard serves three audiences:

  1. Developers monitoring agent behavior and debugging
  2. Parcel owners tracking asset performance and trades
  3. Investors/Operators viewing portfolio metrics and market activity

The 3D parcel visualization (Three.js) creates an intuitive spatial representation of the metaverse world, while real-time WebSocket updates ensure the dashboard reflects current agent states without polling.


Objectives

  • Set up Next.js 14 with App Router and TypeScript
  • Create 3D parcel map using Three.js / React Three Fiber
  • Build real-time WebSocket connection to MCP message bus ([FEATURE] Route.X MCP Server - Parcel Plugin Implementation #3)
  • Create agent activity panel (decisions, trades, contracts)
  • Build trading interface with market data and order book
  • Create wallet balance display with transaction history
  • Add dark mode with TailwindCSS
  • Responsive mobile layout

Pages & Routes

Route Component Data Source
/ Dashboard overview + 3D map MCP WebSocket, REST API
/parcels Parcel list/grid with filters GET /api/parcels
/parcels/[id] Parcel detail + agent activity GET /api/parcels/:id, WebSocket
/trades Order book + trade history GET /api/trades, WebSocket
/contracts Smart contract status GET /api/contracts
/settings API keys, wallet config Local state + env

Key Components

<ParcelMap3D> — Three.js World Visualization

// Uses React Three Fiber for declarative Three.js
import { Canvas, useFrame } from '@react-three/fiber'
import { OrbitControls, Grid } from '@react-three/drei'

function ParcelMap3D({ parcels }: { parcels: Parcel[] }) {
  return (
    <Canvas camera={{ position: [0, 20, 40] }}>
      <ambientLight intensity={0.5} />
      <Grid args={[100, 100]} />
      {parcels.map(parcel => (
        <ParcelBox
          key={parcel.id}
          position={parcel.coordinates}
          color={parcel.agent?.status === 'active' ? '#00ff88' : '#333'}
          onClick={() => router.push(`/parcels/${parcel.id}`)}
        />
      ))}
      <OrbitControls />
    </Canvas>
  )
}

<AgentActivityFeed> — Real-Time Decision Log

Displays live stream of agent decisions from MCP WebSocket:

  • Agent ID + parcel
  • Decision type (trade, hold, sign contract, broadcast)
  • Reasoning excerpt from Sentient-70b
  • Timestamp and execution result

<TradingInterface> — Order Book + Market

  • Live order book (bids/asks) from web4agi://market resource
  • Trade execution UI (market or limit orders)
  • Price chart (candlestick using lightweight-charts)
  • USDC/USDT pair selector

<WalletPanel> — Agent Wallet Dashboard

  • Balance display (USDC, USDT, ETH for gas)
  • Recent transaction history
  • Pending escrow positions from ParcelServiceAgreement.sol
  • Base Sepolia/mainnet toggle

<ContractManager> — Smart Contract Status

  • Active service agreements
  • Contract lifecycle status (Created → Signed → Executed)
  • Dispute resolution interface

Technical Architecture

State Management (Zustand)

interface SapientXStore {
  // Agent data
  agents: Record<string, AgentState>
  updateAgent: (id: string, state: Partial<AgentState>) => void
  
  // Market data
  orderBook: OrderBook
  recentTrades: Trade[]
  
  // Wallet
  walletBalance: { usdc: string; usdt: string; eth: string }
  
  // WebSocket
  wsConnected: boolean
  lastMessage: MCPMessage | null
}

WebSocket Hook (useWebSocket.ts)

function useWebSocket(url: string) {
  const { updateAgent, addTrade } = useSapientXStore()
  
  useEffect(() => {
    const ws = new WebSocket(url)
    
    ws.onmessage = (event) => {
      const msg: MCPMessage = JSON.parse(event.data)
      
      switch (msg.type) {
        case 'agent_update': updateAgent(msg.agentId, msg.state); break
        case 'trade_executed': addTrade(msg.trade); break
        case 'contract_signed': updateContract(msg.contract); break
      }
    }
    
    return () => ws.close()
  }, [url])
}

Data Fetching (SWR)

// Auto-revalidates every 30s, or on WebSocket push
const { data: parcels } = useSWR('/api/parcels', fetcher, {
  refreshInterval: 30000,
  revalidateOnFocus: false,
})

Tech Stack

Technology Version Purpose
Next.js 14 (App Router) React framework + SSR
TypeScript 5.x Type safety
Three.js / React Three Fiber 8.x / 0.15.x 3D parcel visualization
@react-three/drei 9.x Three.js helpers
TailwindCSS 3.x Styling
shadcn/ui latest Component library
Zustand 4.x Global state management
SWR 2.x Data fetching + caching
WebSocket (native) Real-time MCP updates
lightweight-charts 4.x Price charts

Implementation Plan

Phase 1: Project Setup (Day 1)

  • npx create-next-app@latest frontend --typescript --tailwind --app
  • Install and configure shadcn/ui
  • Set up Zustand store structure
  • Configure API client (frontend/lib/api.ts)
  • Create WebSocket hook (frontend/hooks/useWebSocket.ts)

Phase 2: Layout + Navigation (Day 2)

  • Build root layout with sidebar navigation
  • Dark mode implementation (TailwindCSS + next-themes)
  • Responsive breakpoints (mobile-first)
  • Loading states and skeleton components

Phase 3: 3D Parcel Map (Days 3-4)

  • Set up React Three Fiber Canvas on dashboard home
  • Create ParcelBox mesh with agent status coloring
  • Add camera controls (OrbitControls)
  • Click-through navigation to parcel detail
  • Real-time agent status updates on 3D parcels via WebSocket
  • Performance: LOD (Level of Detail) for 10,000+ parcels

Phase 4: Agent Activity + Trading UI (Days 5-6)

  • Build AgentActivityFeed with WebSocket real-time updates
  • Build TradingInterface with order book and price chart
  • Build WalletPanel with balance display
  • Build ContractManager with contract lifecycle status

Phase 5: Polish + Testing (Day 7)

  • Mobile responsive layout fixes
  • Performance audit (Lighthouse > 90)
  • Error boundaries and loading states
  • Playwright E2E tests for critical flows

Environment Variables

NEXT_PUBLIC_API_URL=http://localhost:8000
NEXT_PUBLIC_WS_URL=ws://localhost:8000/ws
NEXT_PUBLIC_CHAIN_ID=84532
NEXT_PUBLIC_USDC_ADDRESS=0x...

Acceptance Criteria

  • 3D parcel map renders with correct agent status coloring
  • WebSocket receives and renders agent updates in < 500ms
  • Order book updates in real-time from web4agi://market feed
  • Wallet balance correctly shows USDC/USDT from blockchain
  • All 6 pages render without errors
  • Dark mode works across all components
  • Mobile layout works on 375px viewport
  • Lighthouse Performance score > 90
  • TypeScript: zero any types in production code

Files to Create

frontend/
├── app/
│   ├── page.tsx                # Dashboard + 3D map
│   ├── parcels/page.tsx
│   ├── parcels/[id]/page.tsx
│   ├── trades/page.tsx
│   ├── contracts/page.tsx
│   └── settings/page.tsx
├── components/
│   ├── ParcelMap3D.tsx
│   ├── AgentActivityFeed.tsx
│   ├── TradingInterface.tsx
│   ├── WalletPanel.tsx
│   ├── ContractManager.tsx
│   └── ui/                     # shadcn components
├── hooks/
│   ├── useWebSocket.ts         # MCP WebSocket client
│   ├── useParcels.ts
│   └── useWallet.ts
├── lib/
│   ├── api.ts                  # REST API client
│   └── store.ts                # Zustand store
└── types/
    └── index.ts                # AgentState, Trade, Contract types

Estimated Effort

Task Estimate
Project setup + routing 1 day
3D parcel map 2 days
Agent activity + trading UI 2 days
WebSocket real-time updates 0.5 days
Mobile responsive + polish 1 day
Playwright E2E tests 0.5 days
Total ~7 days

Related Issues & Dependencies


References

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    Status

    Todo

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions