"use client"
import { useEffect, useState } from "react"
import { Card, CardContent, CardHeader, CardTitle } from "./ui/card"
import { Badge } from "./ui/badge"
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from "./ui/dialog"
import { Wifi, Activity, Network, Router, AlertCircle, Zap, Timer, EthernetPort, ArrowDown, ArrowUp, Box, ChevronRight } from 'lucide-react'
import useSWR from "swr"
import { NetworkTrafficChart } from "./network-traffic-chart"
import { NetworkFlow, type NetworkFlowData } from "./network-flow"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "./ui/select"
import { fetchApi } from "../lib/api-config"
import { formatNetworkTraffic, getNetworkUnit } from "../lib/format-network"
import { LatencyDetailModal } from "./latency-detail-modal"
import { AreaChart, Area, LineChart, Line, ResponsiveContainer, YAxis } from "recharts"
interface NetworkData {
interfaces: NetworkInterface[]
physical_interfaces?: NetworkInterface[]
bridge_interfaces?: NetworkInterface[]
vm_lxc_interfaces?: NetworkInterface[]
traffic: {
bytes_sent: number
bytes_recv: number
packets_sent?: number
packets_recv?: number
packet_loss_in?: number
packet_loss_out?: number
dropin?: number
dropout?: number
errin?: number
errout?: number
}
active_count?: number
total_count?: number
physical_active_count?: number
physical_total_count?: number
bridge_active_count?: number
bridge_total_count?: number
vm_lxc_active_count?: number
vm_lxc_total_count?: number
hostname?: string
domain?: string
dns_servers?: string[]
}
interface NetworkInterface {
name: string
type: string
status: string
speed: number
duplex: string
mtu: number
mac_address: string | null
addresses: Array<{
ip: string
netmask: string
}>
bytes_sent?: number
bytes_recv?: number
packets_sent?: number
packets_recv?: number
errors_in?: number
errors_out?: number
drops_in?: number
drops_out?: number
// Live rate (bytes/sec) computed by the backend as the delta
// between this poll and the previous one. Present from the second
// /api/network response onward; absent on the first call after the
// service starts or after a long pause.
rx_Bps?: number
tx_Bps?: number
// Hardware ceiling parsed from ethtool's "Supported link modes".
// The card shows "(max N Gbps)" next to the negotiated speed when
// the link is auto-negotiated below the NIC's max.
max_speed?: number
// Bridges that have this physical NIC as their underlying interface
// (directly, or as a bond slave). Surfaced in the card so the
// operator can see "this NIC → vmbr0" at a glance.
used_by_bridges?: string[]
bond_mode?: string
bond_slaves?: string[]
bond_active_slave?: string | null
bridge_members?: string[]
bridge_physical_interface?: string
bridge_bond_slaves?: string[]
packet_loss_in?: number
packet_loss_out?: number
vmid?: number
vm_name?: string
vm_type?: string
vm_status?: string
}
// Same dot-prefix tone the Storage cards use, so a "no errors" /
// "errors present" cue reads identically across pages.
const NetStatusDot = ({ tone }: { tone: "ok" | "warn" | "fail" }) => {
const cls =
tone === "ok" ? "bg-green-500" : tone === "warn" ? "bg-yellow-500" : "bg-red-500"
return
}
const netCounterTone = (n: number | null | undefined): "ok" | "warn" | "fail" => {
if (!n || n <= 0) return "ok"
if (n < 10) return "warn"
return "fail"
}
// Icon picker — defaults to the actual port type rather than a Wi-Fi
// glyph for everything. Wireless interfaces (wl*/wifi*) keep the Wi-Fi
// glyph; wired NICs use EthernetPort; bonds/bridges/vlans get more
// specific icons so the operator can tell them apart at a glance.
function getInterfaceIcon(iface: NetworkInterface): React.ComponentType<{ className?: string }> {
const name = (iface.name || "").toLowerCase()
const type = (iface.type || "").toLowerCase()
if (name.startsWith("wl") || name.startsWith("wifi")) return Wifi
if (type === "bridge") return Network
if (type === "bond") return Router
if (type === "vlan") return Activity
if (type === "vm_lxc" || type === "virtual") return Box
// Physical wired NIC (eth0, enp*, ens*, eno*, nic0, …) → ethernet port.
return EthernetPort
}
// Match the dark blue badge tone the Storage card uses for the disk
// type chip, but mapped to the actual interface class.
function getInterfaceTypeChip(type: string) {
switch ((type || "").toLowerCase()) {
case "physical":
return { className: "bg-blue-500/10 text-blue-400 border-blue-500/20", label: "Physical" }
case "bridge":
return { className: "bg-green-500/10 text-green-400 border-green-500/20", label: "Bridge" }
case "bond":
return { className: "bg-purple-500/10 text-purple-400 border-purple-500/20", label: "Bond" }
case "vlan":
return { className: "bg-cyan-500/10 text-cyan-400 border-cyan-500/20", label: "VLAN" }
case "vm_lxc":
case "virtual":
return { className: "bg-orange-500/10 text-orange-400 border-orange-500/20", label: "Virtual" }
default:
return { className: "bg-gray-500/10 text-gray-400 border-gray-500/20", label: type || "Unknown" }
}
}
// Per-interface card matching the Storage page's "Physical Disks"
// pattern: 2-line header (identity / live state), horizontal divider,
// vertical key→value stat block, footer with serial + arrow CTA.
// Replaces the row-style block that was unchanged since 1.0.0.
function renderPhysicalInterfaceCardV2(
iface: NetworkInterface,
onOpen: (iface: NetworkInterface) => void,
) {
const Icon = getInterfaceIcon(iface)
const chip = getInterfaceTypeChip(iface.type)
const isUp = (iface.status || "").toLowerCase() === "up"
const firstAddr = iface.addresses?.[0]?.ip || ""
const extraAddrs = Math.max(0, (iface.addresses?.length || 0) - 1)
const speedStr = formatSpeed(iface.speed)
// Hardware max in Mbps from ethtool. Show only when it's different
// from the negotiated speed (avoids "1 Gbps (max 1 Gbps)" noise).
const maxSpeedStr =
iface.max_speed && iface.max_speed !== iface.speed
? formatSpeed(iface.max_speed)
: ""
const bridgesUsing = iface.used_by_bridges || []
const errIn = iface.errors_in ?? 0
const errOut = iface.errors_out ?? 0
const dropIn = iface.drops_in ?? 0
const dropOut = iface.drops_out ?? 0
const totalErrors = errIn + errOut
const totalDrops = dropIn + dropOut
return (
)}
{/* Live RX/TX rate. Same wording the Network Traffic chart
uses ("Received" / "Sent") and the same canonical colours
(green for Received, blue for Sent). Falls back to "—"
until the backend has a delta — first poll after start
has no previous sample to compute against. */}
Received
{iface.rx_Bps !== undefined ? formatRate(iface.rx_Bps) : "—"}
Sent
{iface.tx_Bps !== undefined ? formatRate(iface.tx_Bps) : "—"}
{/* Network Traffic Card with Chart */}
Network Traffic
{/* Network Flow — proof of concept. Lives next to Network Traffic
while the design is validated on a real host. Once approved,
this card replaces (or pairs with) the chart above. */}
{(() => {
const toMBps = (bps?: number) => (bps || 0) / (1024 * 1024)
const allIfaces = [
...(networkData.physical_interfaces || []),
...(networkData.bridge_interfaces || []),
...(networkData.vm_lxc_interfaces || []),
]
const flowData: NetworkFlowData = {
nics: (networkData.physical_interfaces || []).map((p) => ({
id: p.name,
link: formatSpeed(p.speed),
rx: toMBps(p.rx_Bps),
tx: toMBps(p.tx_Bps),
status: (p.status || "").toLowerCase() === "up" ? "up" : "down",
})),
bridges: (networkData.bridge_interfaces || []).map((b) => ({
id: b.name,
parent: b.bridge_physical_interface,
})),
consumers: [
(() => {
// PROXMOX node = sum of every running guest's rate.
// This stays consistent with each bridge's own label
// (which sums the same guest rates), and with the
// total trunk flow — no discrepancy between the host's
// displayed rate and the sum of its bridges.
const runningGuests = (networkData.vm_lxc_interfaces || []).filter(
(v) => v.vm_status !== "stopped"
)
return {
id: "host",
label: "host",
kind: "host" as const,
bridge: (networkData.bridge_interfaces?.[0]?.name) || "",
rx: runningGuests.reduce((a, v) => a + toMBps(v.rx_Bps), 0),
tx: runningGuests.reduce((a, v) => a + toMBps(v.tx_Bps), 0),
}
})(),
...(networkData.vm_lxc_interfaces || []).map((v) => {
// Authoritative bridge from the kernel (read by the
// backend from /sys/class/net//master). Fallback
// to bridge_members scan, then first bridge as last
// resort so we never silently drop a guest.
const ownerName =
(v as any).bridge_owner ||
(networkData.bridge_interfaces || []).find((b) =>
(b.bridge_members || []).includes(v.name)
)?.name ||
(networkData.bridge_interfaces?.[0]?.name || "")
return {
id: v.name,
label: v.vm_name || v.name,
kind: (v.vm_type === "vm" ? "vm" : "lxc") as "vm" | "lxc",
bridge: ownerName,
rx: toMBps(v.rx_Bps),
tx: toMBps(v.tx_Bps),
offline: v.vm_status === "stopped",
}
}),
],
}
return (
{
// Map the clicked node back to a NetworkInterface and
// open the same details modal the cards below use. The
// virtual "host" id never matches a real interface, so
// it's a no-op — tapping the PROXMOX circle does nothing
// (there's no host-level modal in this view).
if (name === "host") return
const match = allIfaces.find((iface) => iface.name === name)
if (match) setSelectedInterface(match)
}}
/>
)
})()}
{/* Physical Interfaces section */}
Physical Interfaces
{networkData.physical_active_count ?? 0}/{networkData.physical_total_count ?? 0} Active
{/* Same responsive grid as the Storage page: 3 cols desktop,
2 cols tablet, 1 col mobile. Cards self-size so a row of
long interface names won't push others off-screen. */}