feat(node): expose fresh network interface and hardware status

This commit is contained in:
DCCONSTRUCTIONS
2026-11-04 00:42:26 +03:00
parent 2c0a10b687
commit 669ada973f
13 changed files with 861 additions and 7 deletions
@@ -0,0 +1,52 @@
import type {BoardHost,BoardNetworkInterface,Vehicle} from './useFleet';
type NetworkFacts={ssid:string;signal:number|null;addresses:string[]|null};
export interface RememberedNetwork {
name:string; kind:'wifi'|'ethernet'; hardware:BoardNetworkInterface['hardware'];
state:string; stateAt:string; facts:NetworkFacts; observed:boolean; seenAt:number;
}
export interface BoardNetworkMemory {
scope:string; input:BoardHost|null; sampledAt:string; readable:boolean; entries:RememberedNetwork[];
}
export const boardNetworkScope=(v:Vehicle)=>`${v.id}\0${v.node_id}`;
const physical=(n:BoardNetworkInterface)=>n.kind==='wifi'||n.kind==='ethernet';
const compare=(a:BoardNetworkInterface,b:BoardNetworkInterface)=>Number(a.kind!=='wifi')-Number(b.kind!=='wifi')||a.name.localeCompare(b.name);
const reportedStates=new Set(['connected','disconnected','unavailable','connecting','disconnecting','failed']);
const sameFacts=(a:NetworkFacts,b:NetworkFacts)=>a.ssid===b.ssid&&a.signal===b.signal&&JSON.stringify(a.addresses)===JSON.stringify(b.addresses);
function factsFrom(n:BoardNetworkInterface,previous?:NetworkFacts):NetworkFacts {
const ssid=n.connection?.ssid??previous?.ssid??'',sameNetwork=ssid===previous?.ssid;
const signal=n.connection?.signal_percent;
return {ssid,signal:typeof signal==='number'&&Number.isInteger(signal)&&signal>=0&&signal<=100?signal:sameNetwork?previous?.signal??null:null,
addresses:n.addresses_readable===false?previous?.addresses??null:[...n.addresses].sort()};
}
// The snapshot's observation time is separate from the adapter's reported state.
// Only a readable inventory may confirm removal; missing/unknown observations
// cannot erase a known state. Keep current interfaces plus 64 absent rows in RAM.
export function rememberBoardNetworks(previous:BoardNetworkMemory|null,vehicle:Vehicle):BoardNetworkMemory {
const scope=boardNetworkScope(vehicle),host=vehicle.host;
const old=previous?.scope===scope?previous:null;
const sampledAt=host?.collected_at||old?.sampledAt||'';
const at=Date.parse(sampledAt),before=Date.parse(old?.sampledAt??'');
if(old&&Number.isFinite(at)&&Number.isFinite(before)&&at<before)return {...old,input:host};
const readable=!!host&&host.networks_readable!==false;
const current=new Map((readable?host.networks:[]).filter(physical).sort(compare).map(n=>[n.name,n]));
const reportedNames=new Set(host?.networks.map(n=>n.name)??[]);
const prior=new Map(old?.entries.map(e=>[e.name,e])??[]);
const names=[...prior.keys(),...Array.from(current.keys()).filter(name=>!prior.has(name))];
const entries=names.map(name=>{
const existing=prior.get(name),next=current.get(name);
if(!next)return readable&&!reportedNames.has(name)?{...existing!,observed:false}:existing!;
const stamp=next.connection?.collected_at??'',connectionAt=Date.parse(stamp),previousAt=Date.parse(existing?.stateAt??'');
const reported=!!next.connection&&reportedStates.has(next.connection.state)&&Number.isFinite(connectionAt)&&(!Number.isFinite(previousAt)||connectionAt>=previousAt);
const state=reported?next.connection!.state:existing?.observed?existing.state:'unknown';
let facts=!existing||(reported&&state==='connected')?factsFrom(next,existing?.facts):existing.facts;
// Equal packets reuse facts, so timestamps alone never repaint adapter cards.
if(existing&&sameFacts(facts,existing.facts))facts=existing.facts;
const hardware={...existing?.hardware,...Object.fromEntries(Object.entries(next.hardware??{}).filter(([,value])=>!!value))};
return {name,kind:next.kind as 'wifi'|'ethernet',hardware,state,stateAt:reported?stamp:existing?.stateAt??'',facts,
observed:true,seenAt:Number.isFinite(at)?at:existing?.seenAt??0};
});
const retained=new Set(entries.filter(e=>!e.observed).sort((a,b)=>b.seenAt-a.seenAt).slice(0,64).map(e=>e.name));
return {scope,input:host,sampledAt,readable,entries:entries.filter(e=>e.observed||retained.has(e.name))};
}
@@ -0,0 +1,23 @@
import type {Vehicle} from './useFleet';
import {rememberBoardNetworks,type BoardNetworkMemory} from './boardNetworkMemory';
const states=new Map(Object.entries({connected:'Подключён',disconnected:'Не подключён',unavailable:'Недоступен',connecting:'Подключается',disconnecting:'Отключается',failed:'Ошибка подключения',unknown:'Нет сведений'}));
const buses=new Map(Object.entries({usb:'USB',pci:'PCI',sdio:'SDIO',platform:'Платформенный',virtio:'Virtio'}));
export function boardNetworkStatus(vehicle:Vehicle,available:boolean,memory=rememberBoardNetworks(null,vehicle)) {
// Board liveness is not an adapter state and inventory age is not a disconnect.
const live=available&&vehicle.connectivity==='online';
const baseTitle=(n:RememberedNetwork)=>[n.kind==='wifi'?'Wi-Fi':'Ethernet',buses.get(n.hardware?.bus??'')].filter(Boolean).join(' · ');
const totals=new Map<string,number>(),indices=new Map<string,number>();
for(const n of memory.entries){const base=baseTitle(n);totals.set(base,(totals.get(base)??0)+1);}
const links=memory.entries.map(n=>{
const base=baseTitle(n),index=(indices.get(base)??0)+1;indices.set(base,index);
const title=(totals.get(base)??0)>1?`${base} · Адаптер ${index}`:base;
const state=n.observed?n.state:'absent';
return {name:n.name,kind:n.kind,title,model:n.hardware?.model??'',vendor:n.hardware?.vendor??'',state,
status:state==='absent'?'Не обнаружен':states.get(state)??'Нет сведений',...n.facts};
});
return {links,readable:memory.readable,live,collectedAt:memory.sampledAt};
}
type RememberedNetwork=BoardNetworkMemory['entries'][number];
export type BoardNetworkStatusValue=ReturnType<typeof boardNetworkStatus>;
@@ -0,0 +1,15 @@
import {useState} from 'react';
import type {Vehicle} from './useFleet';
import {boardNetworkScope,rememberBoardNetworks} from './boardNetworkMemory';
import {boardNetworkStatus} from './boardNetworkStatus';
export function useBoardNetworkStatus(vehicle:Vehicle,available:boolean) {
const [memory,setMemory]=useState(()=>rememberBoardNetworks(null,vehicle));
// Adjust before rendering children. There is deliberately no clock/expiry
// timer: only a received observation can change an adapter's reported state.
if(memory.scope!==boardNetworkScope(vehicle)||memory.input!==vehicle.host){
const next=rememberBoardNetworks(memory,vehicle);setMemory(next);
return boardNetworkStatus(vehicle,available,next);
}
return boardNetworkStatus(vehicle,available,memory);
}
@@ -1,15 +1,22 @@
import { useCallback, useEffect, useState } from "react";
export interface BoardNetworkInterface {
name: string; up: boolean; addresses: string[]; addresses_readable?: boolean;
kind?: 'wifi'|'ethernet'|'virtual'|'unknown';
hardware?: {bus?:string;vendor?:string;model?:string};
connection?: {state:string;ssid?:string;signal_percent?:number;collected_at:string};
}
export interface BoardHost {
hostname: string; os: string; architecture: string; cpus: number;
memory_kib: number | null; collected_at: string;
networks: { name: string; up: boolean; addresses: string[] }[];
networks: BoardNetworkInterface[]; networks_readable?: boolean;
usb: { port: string; product: string }[];
}
export interface Vehicle {
id: string; node_id: string; name: string; platform: string;
enrollment: "pending" | "paired" | "revoked" | "failed";
connectivity: "online" | "offline"; last_seen: number | null;
inventory_fresh?: boolean;
host: BoardHost | null; notice: string; revision: number;
}
export interface FleetPreview {
@@ -1,6 +1,8 @@
import {useState} from 'react';
import {useBoardNetwork} from '../../core/fleet/useBoardNetwork';
import {useBoardNetworkStatus} from '../../core/fleet/useBoardNetworkStatus';
import {BoardNetworkSettings} from './BoardNetworkSettings';
import {BoardNetworkStatus} from './BoardNetworkStatus';
import {Button,Icon,IconButton,ResourceRow,StatusBadge,FeatureSettingsWindow,WindowFooterActions} from '@nodedc/ui-react';
import type {Vehicle} from '../../core/fleet/useFleet';
@@ -14,11 +16,12 @@ export function BoardComputerRow({vehicle,enabled,showingSavedDevices,onSettings
export function BoardComputerSettings({vehicle,enabled,onClose,onRevoke}:{vehicle:Vehicle;enabled:boolean;onClose:()=>void;onRevoke:()=>void}){
const [section,setSection]=useState('binding');
const network=useBoardNetwork(vehicle.id);
const interfaces=useBoardNetworkStatus(vehicle,enabled);
return <FeatureSettingsWindow open title="Бортовой компьютер" subtitle={vehicle.host?.hostname||'Mission Core Node'}
identity={{title:vehicle.host?.hostname||'Mission Core Node',subtitle:vehicle.node_id,avatarLabel:'БК'}}
sections={[{id:'binding',label:'Привязка',icon:'apps'},{id:'network',label:'Связь с Core',icon:'network'}]} activeSection={section} onSectionChange={setSection} onClose={onClose}
sections={[{id:'binding',label:'Привязка',icon:'apps'},{id:'network',label:'Связь с Core',icon:'network'},{id:'interfaces',label:'Сеть',icon:'network'}]} activeSection={section} onSectionChange={setSection} onClose={onClose}
footer={<WindowFooterActions><Button variant="secondary" onClick={onClose}>Закрыть</Button>{section==='network'&&<Button variant="primary" disabled={!network.canSave} onClick={()=>void network.save()}>{network.applying?'Применяем…':'Сохранить'}</Button>}</WindowFooterActions>}>
{section==='network'?<BoardNetworkSettings network={network}/>:
{section==='network'?<BoardNetworkSettings network={network}/>:section==='interfaces'?<BoardNetworkStatus status={interfaces}/>:
<div className="fleet-form"><StatusBadge tone={enabled?'success':vehicle.enrollment==='pending'?'warning':'neutral'}>{boardStatus(vehicle,enabled)}</StatusBadge>
{vehicle.notice&&<p role="status">{vehicle.notice}</p>}
<dl className="fleet-facts"><div><dt>Идентификатор БК</dt><dd>{vehicle.node_id}</dd></div><div><dt>Последняя связь</dt><dd>{vehicle.last_seen?new Date(vehicle.last_seen*1000).toLocaleString('ru-RU'):'Соединение ещё не получено'}</dd></div>
@@ -0,0 +1,27 @@
import {memo} from 'react';
import {Description,SettingsCard,StatusBadge} from '@nodedc/ui-react';
import type {BoardNetworkStatusValue} from '../../core/fleet/boardNetworkStatus';
const NetworkCard=memo(function NetworkCard(link:BoardNetworkStatusValue['links'][number]) {
return <SettingsCard title={link.title}
actions={<StatusBadge tone={link.state==='connected'?'success':link.state==='connecting'?'warning':'neutral'}>{link.status}</StatusBadge>}>
<dl className="fleet-facts">
<div><dt>Модель</dt><dd>{link.model||'Нет сведений'}</dd></div>
<div><dt>Производитель</dt><dd>{link.vendor||'Нет сведений'}</dd></div>
<div><dt>Интерфейс</dt><dd>{link.name}</dd></div>
{link.kind==='wifi'&&<div><dt>Последняя сеть</dt><dd>{link.ssid||'Нет сведений'}</dd></div>}
{link.kind==='wifi'&&<div><dt>Последний сигнал</dt><dd>{link.signal!==null?`${link.signal}%`:'Нет сведений'}</dd></div>}
<div><dt>Последний IP-адрес</dt><dd>{link.addresses?.length?link.addresses.join(', '):'Нет сведений'}</dd></div>
</dl>
</SettingsCard>;
});
export function BoardNetworkStatus({status}:{status:BoardNetworkStatusValue}) {
const {links,readable,live,collectedAt}=status;
return <div className="fleet-form">
<Description>Состояние Wi-Fi и Ethernet по последним полученным данным борта. Карточки обновляются при изменении сведений. Изменение сети здесь недоступно.</Description>
<StatusBadge tone={live?'success':'neutral'}>{live?'Связь с бортом установлена':'Связь с бортом не подтверждена'}</StatusBadge>
<Description>Данные борта на {collectedAt&&Number.isFinite(Date.parse(collectedAt))?new Date(collectedAt).toLocaleString('ru-RU'):'ещё не получен'}.</Description>
{!links.length?<SettingsCard title={readable?'Нет сведений о Wi-Fi и Ethernet':'Сведения о сети недоступны'} description="Борт пока не передал данные физических подключений."/>:
links.map(link=><NetworkCard key={link.name} {...link}/>)}
</div>;
}
@@ -0,0 +1,142 @@
import assert from 'node:assert/strict';
import {after,before,test} from 'node:test';
import {createElement} from 'react';
import {renderToStaticMarkup} from 'react-dom/server';
import {createServer} from './support/vite-server.mjs';
let server,project,View,remember;
before(async()=>{
server=await createServer({appType:'custom',logLevel:'silent',server:{middlewareMode:true}});
({boardNetworkStatus:project}=await server.ssrLoadModule('/src/core/fleet/boardNetworkStatus.ts'));
({rememberBoardNetworks:remember}=await server.ssrLoadModule('/src/core/fleet/boardNetworkMemory.ts'));
({BoardNetworkStatus:View}=await server.ssrLoadModule('/src/workspaces/fleet/BoardNetworkStatus.tsx'));
});
after(async()=>{await server?.close();});
const fixture=(now=Date.now())=>({connectivity:'online',inventory_fresh:true,host:{networks_readable:true,collected_at:new Date(now).toISOString(),networks:[
{name:'usb-radio',kind:'wifi',addresses:['192.0.2.4/24'],connection:{state:'connected',ssid:'Test <network>',signal_percent:0,collected_at:new Date(now).toISOString()}},
{name:'cable',kind:'ethernet',addresses:[],connection:{state:'unavailable',collected_at:new Date(now).toISOString()}},
{name:'tunnel',kind:'virtual',addresses:['10.0.0.1/32'],connection:{state:'connected',collected_at:new Date(now).toISOString()}},
]}});
test('physical connections retain SSID, zero signal and cable state without VPN interfaces',()=>{
const p=project(fixture(100000),true);
assert.equal(p.links.length,2);assert.equal(p.links[0].ssid,'Test <network>');
assert.equal(p.links[0].signal,0);assert.equal(p.links[0].state,'connected');
assert.equal(p.links[1].status,'Недоступен');assert.deepEqual(p.links[1].addresses,[]);
});
test('inventory age and transport availability never rewrite a received adapter state',()=>{
const v=fixture(100000),memory=remember(null,v),first=project(v,true,memory);
for(const [input,available] of [[v,false],[{...v,inventory_fresh:false},true],[{...v,connectivity:'offline'},true],[fixture(0),true]]){
const status=project(input,available,memory);assert.deepEqual(status.links,first.links);
}
assert.equal(project({...v,inventory_fresh:false},true,memory).live,true);
assert.equal(project(v,false,memory).live,false);
assert.equal(project({...v,connectivity:'offline'},true,memory).live,false);
});
test('missing metadata does not infer Wi-Fi or connection from interface name or IP',()=>{
const v=fixture();v.host.networks=[{name:'wlan0',up:true,addresses:['192.0.2.1']}];
assert.deepEqual(project(v,true).links,[]);
v.host.networks[0].kind='wifi';assert.equal(project(v,true).links[0].status,'Нет сведений');
v.host.networks_readable=false;assert.equal(project(v,true).readable,false);
});
test('invalid signal and failed address reads remain unknown',()=>{
const v=fixture();v.host.networks[0].connection.signal_percent=101;v.host.networks[0].addresses_readable=false;
assert.equal(project(v,true).links[0].signal,null);assert.equal(project(v,true).links[0].addresses,null);
});
test('network section displays escaped real facts and exposes no mutation controls',()=>{
const html=renderToStaticMarkup(createElement(View,{status:project(fixture(),true)}));
assert.match(html,/Test &lt;network&gt;/);assert.match(html,/0%/);assert.match(html,/192\.0\.2\.4/);assert.match(html,/Ethernet/);
assert.doesNotMatch(html,/<button|<input|<select|tunnel|Сохранить/);
const stale=renderToStaticMarkup(createElement(View,{status:project(fixture(0),true)}));
assert.doesNotMatch(stale,/Данные устарели/);assert.match(stale,/по последним полученным данным/);
});
test('hardware labels use reported bus and model, never interface-name guesses',()=>{
const v=fixture();v.host.networks[0].hardware={bus:'usb',vendor:'Example vendor',model:'Radio <X>'};
v.host.networks[1].hardware={bus:'pci',model:'Ethernet model'};
const links=project(v,true).links;
assert.equal(links[0].title,'Wi-Fi · USB');assert.equal(links[0].model,'Radio <X>');
assert.equal(links[1].title,'Ethernet · PCI');
const html=renderToStaticMarkup(createElement(View,{status:project(v,true)}));
assert.match(html,/Radio &lt;X&gt;/);assert.match(html,/Example vendor/);assert.match(html,/Интерфейс/);
delete v.host.networks[0].hardware;v.host.networks[0].name='wlx-looks-like-usb';
assert.equal(project(v,true).links[0].title,'Wi-Fi');assert.equal(project(v,true).links[0].model,'');
});
test('multiple adapters keep their numbering across inventory order and connection changes',()=>{
const v=fixture();const a=v.host.networks[0];a.hardware={bus:'usb'};a.name='radio-b';
const b={...a,name:'radio-a',connection:{...a.connection,state:'disconnected'}};
v.host.networks.push(b);
const names=()=>Object.fromEntries(project(v,true).links.map(x=>[x.name,x.title]));
const expected={'radio-a':'Wi-Fi · USB · Адаптер 1','radio-b':'Wi-Fi · USB · Адаптер 2',cable:'Ethernet'};
assert.deepEqual(names(),expected);
v.host.networks.reverse();a.connection.state='disconnected';b.connection.state='connected';assert.deepEqual(names(),expected);
v.host.networks=v.host.networks.filter(n=>n.name!=='radio-a');
assert.equal(project(v,true).links.find(n=>n.name==='radio-b').title,'Wi-Fi · USB');
});
test('explicit negative response changes status and keeps last association facts and card structure',()=>{
const now=100000,v=fixture(now);let memory=remember(null,v);
const first=project(v,true,memory),names=first.links.map(x=>x.name);
const fields=status=>renderToStaticMarkup(createElement(View,{status})).match(/<dt>[^<]*<\/dt>/g);
const disconnected=structuredClone(v);disconnected.host.collected_at=new Date(now+1000).toISOString();
Object.assign(disconnected.host.networks[0],{addresses:[],connection:{state:'disconnected',collected_at:disconnected.host.collected_at}});
memory=remember(memory,disconnected);const negative=project(disconnected,true,memory);
assert.equal(negative.links[0].status,'Не подключён');assert.equal(negative.links[0].state,'disconnected');
for(const key of ['ssid','signal','addresses'])assert.deepEqual(negative.links[0][key],first.links[0][key]);
assert.deepEqual(fields(negative),fields(first));assert.deepEqual(negative.links.map(x=>x.name),names);
});
test('failed reads and omitted or unknown connection metadata retain the last reported state',()=>{
const v=fixture(100000),initial=remember(null,v),first=project(v,true,initial);
for(const host of [null,{...v.host,networks_readable:false,networks:[]},
{...v.host,networks:v.host.networks.map(n=>({...n,connection:undefined}))},
{...v.host,networks:v.host.networks.map(n=>({...n,kind:'unknown',connection:undefined}))},
{...v.host,networks:v.host.networks.map(n=>({...n,connection:{...n.connection,state:'unknown'}}))}]){
const missing={...v,host},memory=remember(initial,missing),status=project(missing,true,memory);
assert.deepEqual(status.links,first.links);
assert.deepEqual(project(v,true,remember(memory,v)).links,first.links);
}
});
test('a complete inventory confirms removal; reappearance without a state does not revive old connected status',()=>{
const v=fixture(100000),initial=remember(null,v),absent={...v,host:{...v.host,networks:[]}};
const removed=remember(initial,absent);assert.equal(project(absent,true,removed).links[0].status,'Не обнаружен');
const reappeared=structuredClone(v);delete reappeared.host.networks[0].connection;
const memory=remember(removed,reappeared);assert.equal(project(reappeared,true,memory).links[0].status,'Нет сведений');
assert.equal(project(v,true,remember(memory,v)).links[0].state,'connected');
});
test('new adapters append without renumbering known cards when a report omits one',()=>{
const v=fixture(100000);v.host.networks[0].hardware={bus:'usb',model:'Known radio'};v.host.networks[0].name='radio-b';
let memory=remember(null,v);const added=structuredClone(v);added.host.networks.unshift({...v.host.networks[0],name:'radio-a'});
memory=remember(memory,added);let status=project(added,true,memory);
assert.deepEqual(status.links.map(x=>x.name),['radio-b','cable','radio-a']);assert.equal(status.links[0].title,'Wi-Fi · USB · Адаптер 1');
const partial=structuredClone(v);partial.host.networks[0].hardware={bus:'usb'};partial.host.networks[0].connection=undefined;
memory=remember(memory,partial);status=project(partial,true,memory);
assert.deepEqual(status.links.map(x=>x.name),['radio-b','cable','radio-a']);assert.equal(status.links[0].title,'Wi-Fi · USB · Адаптер 1');assert.equal(status.links[0].model,'Known radio');
assert.equal(status.links[2].title,'Wi-Fi · USB · Адаптер 2');assert.equal(status.links[2].status,'Не обнаружен');
});
test('remembered facts never leak to another board and older packets cannot replace accepted state even after read failure',()=>{
const v={...fixture(100000),id:'vehicle-a',node_id:'board-a'},memory=remember(null,v);
for(const other of [{...v,id:'vehicle-b',host:null},{...v,node_id:'board-b',host:null}])assert.deepEqual(remember(memory,other).entries,[]);
const older=structuredClone(v);older.host.collected_at=new Date(99000).toISOString();older.host.networks=[];
const ignored=remember(remember(memory,{...v,host:null}),older);
assert.equal(ignored.input,older.host);assert.deepEqual(ignored.entries,memory.entries);
assert.equal(project(older,true,ignored).links[0].state,'connected');
});
test('timestamps and inventory order alone do not change adapter card props',()=>{
let v=fixture(100000),memory=remember(null,v);const first=project(v,true,memory);
for(const time of [121000,150000,86400000]){
const next=fixture(time);next.host.networks.reverse();
memory=remember(memory,next);const status=project(next,true,memory);
assert.deepEqual(status.links,first.links);
assert.equal(status.links[0].addresses,first.links[0].addresses);
assert.equal(status.collectedAt,next.host.collected_at);
}
});
test('actual network, signal and address changes update facts; an older embedded observation cannot undo them',()=>{
const v=fixture(100000);let memory=remember(null,v);const next=fixture(110000);
Object.assign(next.host.networks[0].connection,{ssid:'Another network',signal_percent:65});next.host.networks[0].addresses=['198.51.100.2/24'];
memory=remember(memory,next);const row=project(next,true,memory).links[0];
assert.equal(row.ssid,'Another network');assert.equal(row.signal,65);assert.deepEqual(row.addresses,['198.51.100.2/24']);
const late=fixture(120000);late.host.networks[0].connection={state:'disconnected',collected_at:new Date(100000).toISOString()};
assert.deepEqual(project(late,true,remember(memory,late)).links[0],row);
});
test('absent-row memory is bounded without limiting the current physical interface list',()=>{
const v=fixture(100000);v.host.networks=Array.from({length:70},(_,i)=>({...v.host.networks[0],name:`radio-${i}`}));
const current=remember(null,v);assert.equal(current.entries.length,70);
const absent=remember(current,{...v,host:{...v.host,networks:[]}});assert.equal(absent.entries.length,64);
});
+10 -4
View File
@@ -12,10 +12,13 @@ import (
)
type Network struct {
Name string `json:"name"`
Up bool `json:"up"`
Addresses []string `json:"addresses"`
AddressesReadable bool `json:"addresses_readable"`
Name string `json:"name"`
Up bool `json:"up"`
Addresses []string `json:"addresses"`
AddressesReadable bool `json:"addresses_readable"`
Kind string `json:"kind,omitempty"`
Connection *NetworkConnection `json:"connection,omitempty"`
Hardware *NetworkHardware `json:"hardware,omitempty"`
}
type USB struct {
Port string `json:"port"`
@@ -74,6 +77,9 @@ func Host(root string) Inventory {
}
var warnings []string
v.Networks, v.NetworksReadable, warnings = readNetworks(net.Interfaces, func(it net.Interface) ([]net.Addr, error) { return it.Addrs() })
if runtime.GOOS == "linux" && root == "/" {
annotateNetworks(root, v.Networks, hostNetworkCache.snapshot(time.Now()))
}
v.Warnings = append(v.Warnings, warnings...)
entries, err := os.ReadDir(filepath.Join(root, "sys/bus/usb/devices"))
v.USBReadable = err == nil
@@ -0,0 +1,48 @@
package node
import (
"os"
"path/filepath"
"strings"
"unicode"
"unicode/utf8"
)
// Hardware describes reported facts, not whether an adapter is physically
// inside the enclosure: USB can be internal and PCI can be hot-pluggable.
type NetworkHardware struct {
Bus string `json:"bus,omitempty"`
Vendor string `json:"vendor,omitempty"`
Model string `json:"model,omitempty"`
}
type networkObservation struct {
NetworkConnection
Hardware NetworkHardware
}
func networkBus(path string) string {
target, err := os.Readlink(filepath.Join(path, "device/subsystem"))
if err != nil {
return ""
}
switch bus := filepath.Base(target); bus {
case "usb", "pci", "sdio", "platform", "virtio":
return bus
default:
return ""
}
}
func networkHardwareText(value string) string {
value = strings.TrimSpace(value)
if value == "--" || len(value) > 256 || !utf8.ValidString(value) {
return ""
}
for _, r := range value {
if unicode.IsControl(r) {
return ""
}
}
return value
}
@@ -0,0 +1,62 @@
package node
import (
"os"
"path/filepath"
"strings"
"testing"
)
func TestNetworkHardwareUsesOSMetadataEvenWhenDisconnected(t *testing.T) {
rows := parseNetworkConnections("GENERAL.DEVICE:arbitrary-name\nGENERAL.TYPE:wifi\nGENERAL.STATE:30 (disconnected)\nGENERAL.VENDOR:Acme\\: radios\nGENERAL.PRODUCT:USB <radio>\nGENERAL.DEVICE:second\nGENERAL.TYPE:wifi\nGENERAL.STATE:100\n")
if rows["arbitrary-name"].Hardware.Vendor != "Acme: radios" || rows["arbitrary-name"].Hardware.Model != "USB <radio>" || rows["second"].Hardware != (NetworkHardware{}) {
t.Fatal(rows)
}
root := t.TempDir()
for name, bus := range map[string]string{"arbitrary-name": "usb", "second": "pci", "wlx-not-a-usb-proof": ""} {
path := filepath.Join(root, "sys/class/net", name)
if err := os.MkdirAll(filepath.Join(path, "wireless"), 0700); err != nil {
t.Fatal(err)
}
if err := os.MkdirAll(filepath.Join(path, "device"), 0700); err != nil {
t.Fatal(err)
}
if bus != "" {
if err := os.Symlink("../../../../bus/"+bus, filepath.Join(path, "device/subsystem")); err != nil {
t.Fatal(err)
}
}
}
networks := []Network{{Name: "arbitrary-name"}, {Name: "second"}, {Name: "wlx-not-a-usb-proof"}}
annotateNetworks(root, networks, rows)
if networks[0].Hardware.Bus != "usb" || networks[0].Hardware.Model != "USB <radio>" || networks[0].Connection.State != "disconnected" || networks[1].Hardware.Bus != "pci" || networks[2].Hardware != nil {
t.Fatal(networks)
}
// Losing NetworkManager metadata must not erase the independently observed bus.
offline := []Network{{Name: "arbitrary-name"}}
annotateNetworks(root, offline, nil)
if offline[0].Hardware.Bus != "usb" || offline[0].Hardware.Model != "" || offline[0].Connection != nil {
t.Fatal(offline)
}
}
func TestNetworkHardwareRejectsInvalidOrUnboundedNames(t *testing.T) {
for _, name := range []string{"--", strings.Repeat("a", 257), "radio\x00name", "radio\tname", string([]byte{255})} {
if got := networkHardwareText(name); got != "" {
t.Fatal(got)
}
}
if got := networkHardwareText(" Example radio "); got != "Example radio" {
t.Fatal(got)
}
path := t.TempDir()
if err := os.Mkdir(filepath.Join(path, "device"), 0700); err != nil {
t.Fatal(err)
}
if err := os.Symlink("../../bus/unknown-bus", filepath.Join(path, "device/subsystem")); err != nil {
t.Fatal(err)
}
if networkBus(path) != "" {
t.Fatal("invented bus")
}
}
@@ -0,0 +1,207 @@
package node
import (
"bytes"
"context"
"errors"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"sync"
"time"
"unicode/utf8"
)
// NetworkConnection describes the OS link, not Internet reachability or VPN health.
type NetworkConnection struct {
State string `json:"state"`
SSID string `json:"ssid,omitempty"`
SignalPercent *int `json:"signal_percent,omitempty"`
CollectedAt string `json:"collected_at"`
}
type networkInventoryCache struct {
mu sync.Mutex
checked time.Time
busy bool
rows map[string]networkObservation
collect func() map[string]networkObservation
}
var hostNetworkCache = networkInventoryCache{collect: collectNetworkConnections}
// Slow or unavailable NetworkManager must never delay a heartbeat. Only one
// bounded read runs at a time; failed reads replace old data instead of renewing it.
func (c *networkInventoryCache) snapshot(now time.Time) map[string]networkObservation {
c.mu.Lock()
defer c.mu.Unlock()
if !c.busy && (c.checked.IsZero() || now.Sub(c.checked) >= 5*time.Second) {
c.busy = true
go func() {
rows := c.collect()
for name, row := range rows {
row.CollectedAt = now.UTC().Format(time.RFC3339Nano)
rows[name] = row
}
c.mu.Lock()
c.rows, c.checked, c.busy = rows, now, false
c.mu.Unlock()
}()
}
if c.checked.IsZero() || now.Sub(c.checked) > 15*time.Second {
return nil
}
copy := make(map[string]networkObservation, len(c.rows))
for name, row := range c.rows {
copy[name] = row
}
return copy
}
type networkOutput struct{ buffer bytes.Buffer }
func (b *networkOutput) Len() int { return b.buffer.Len() }
func (b *networkOutput) String() string { return b.buffer.String() }
func (b *networkOutput) Write(p []byte) (int, error) {
if b.Len()+len(p) > 64*1024 {
return 0, errors.New("network metadata exceeds bound")
}
return b.buffer.Write(p)
}
func collectNetworkConnections() map[string]networkObservation {
ctx, cancel := context.WithTimeout(context.Background(), 1500*time.Millisecond)
defer cancel()
// device show reads NetworkManager's cache. It does not scan, modify a
// connection or read saved credentials. No shell or operator input is used.
cmd := exec.CommandContext(ctx, "/usr/bin/nmcli", "--terse", "--escape", "yes", "--fields",
"GENERAL.DEVICE,GENERAL.TYPE,GENERAL.STATE,GENERAL.VENDOR,GENERAL.PRODUCT,AP.IN-USE,AP.SSID,AP.SIGNAL", "device", "show")
cmd.Env = []string{"PATH=/usr/bin:/bin", "LC_ALL=C", "DBUS_SYSTEM_BUS_ADDRESS=unix:path=/run/dbus/system_bus_socket"}
var output networkOutput
cmd.Stdout = &output
cmd.WaitDelay = 100 * time.Millisecond
if cmd.Run() != nil {
return nil
}
return parseNetworkConnections(output.String())
}
func nmValue(value string) string {
var out strings.Builder
for i := 0; i < len(value); i++ {
if value[i] == '\\' && i+1 < len(value) && (value[i+1] == ':' || value[i+1] == '\\') {
i++
}
out.WriteByte(value[i])
}
return out.String()
}
func parseNetworkConnections(raw string) map[string]networkObservation {
rows := make(map[string]networkObservation)
var name, kind, state, vendor, model string
aps := make(map[string]map[string]string)
flush := func() {
if name == "" || len(name) > 64 || (kind != "wifi" && kind != "ethernet") {
return
}
row := networkObservation{NetworkConnection: NetworkConnection{State: "unknown"}, Hardware: NetworkHardware{Vendor: networkHardwareText(vendor), Model: networkHardwareText(model)}}
switch state {
case "100":
row.State = "connected"
case "30":
row.State = "disconnected"
case "20":
row.State = "unavailable"
case "40", "50", "60", "70", "80", "90":
row.State = "connecting"
case "110":
row.State = "disconnecting"
case "120":
row.State = "failed"
}
if kind == "wifi" && row.State == "connected" {
var active []map[string]string
for _, ap := range aps {
if ap["IN-USE"] == "*" {
active = append(active, ap)
}
}
if len(active) == 1 {
ssid := active[0]["SSID"]
if len(ssid) <= 32 && utf8.ValidString(ssid) && !strings.ContainsAny(ssid, "\r\n\x00") {
row.SSID = ssid
}
if n, err := strconv.Atoi(active[0]["SIGNAL"]); err == nil && n >= 0 && n <= 100 {
row.SignalPercent = &n
}
}
}
rows[name] = row
}
for _, line := range strings.Split(raw, "\n") {
key, value, ok := strings.Cut(line, ":")
if !ok {
if line != "" {
return nil
}
continue
}
value = nmValue(value)
switch key {
case "GENERAL.DEVICE":
flush()
name, kind, state, vendor, model, aps = value, "", "", "", "", make(map[string]map[string]string)
case "GENERAL.TYPE":
kind = value
case "GENERAL.VENDOR":
vendor = value
case "GENERAL.PRODUCT":
model = value
case "GENERAL.STATE":
state, _, _ = strings.Cut(value, " ")
default:
if strings.HasPrefix(key, "AP[") {
id, field, valid := strings.Cut(key, "].")
if valid && (field == "IN-USE" || field == "SSID" || field == "SIGNAL") {
if aps[id] == nil {
aps[id] = make(map[string]string)
}
aps[id][field] = value
}
}
}
}
flush()
return rows
}
func annotateNetworks(root string, networks []Network, rows map[string]networkObservation) {
for i := range networks {
n := &networks[i]
path := filepath.Join(root, "sys/class/net", n.Name)
n.Kind = "unknown"
if _, err := os.Stat(filepath.Join(path, "wireless")); err == nil {
n.Kind = "wifi"
} else if kind, err := os.ReadFile(filepath.Join(path, "type")); err == nil {
if _, err := os.Stat(filepath.Join(path, "device")); err == nil && strings.TrimSpace(string(kind)) == "1" {
n.Kind = "ethernet"
} else {
n.Kind = "virtual"
}
}
if n.Kind == "wifi" || n.Kind == "ethernet" {
hardware := NetworkHardware{Bus: networkBus(path)}
if row, ok := rows[n.Name]; ok {
n.Connection = &row.NetworkConnection
hardware.Vendor, hardware.Model = row.Hardware.Vendor, row.Hardware.Model
}
if hardware != (NetworkHardware{}) {
n.Hardware = &hardware
}
}
}
}
@@ -0,0 +1,126 @@
package node
import (
"io"
"os"
"path/filepath"
"strings"
"testing"
"time"
)
func TestNetworkConnectionsOnlyExposeAssociatedSSID(t *testing.T) {
rows := parseNetworkConnections(`GENERAL.DEVICE:wlan0
GENERAL.TYPE:wifi
GENERAL.STATE:100 (connected)
AP[1].IN-USE:
AP[2].IN-USE:*
AP[1].SSID:unrelated-neighbour
AP[2].SSID:Lab\: one\\two
AP[1].SIGNAL:100
AP[2].SIGNAL:0
GENERAL.DEVICE:wlan1
GENERAL.TYPE:wifi
GENERAL.STATE:30 (disconnected)
AP[1].IN-USE:*
AP[1].SSID:stale-association
AP[1].SIGNAL:70
GENERAL.DEVICE:eth0
GENERAL.TYPE:ethernet
GENERAL.STATE:20 (unavailable)
GENERAL.DEVICE:wt0
GENERAL.TYPE:wireguard
GENERAL.STATE:100 (connected)
`)
row := rows["wlan0"]
if len(rows) != 3 || row.State != "connected" || row.SSID != `Lab: one\two` || row.SignalPercent == nil || *row.SignalPercent != 0 {
t.Fatal(rows)
}
if rows["wlan1"].SSID != "" || rows["wlan1"].SignalPercent != nil || rows["eth0"].State != "unavailable" {
t.Fatal(rows)
}
}
func TestNetworkConnectionsUnknownAndAmbiguousAreNotInvented(t *testing.T) {
for _, state := range []string{"", "200", "100"} {
row := parseNetworkConnections("GENERAL.DEVICE:wlan0\nGENERAL.TYPE:wifi\nGENERAL.STATE:" + state + "\nAP[1].IN-USE:*\nAP[2].IN-USE:*\nAP[1].SSID:first\nAP[2].SSID:second\n")["wlan0"]
if row.SSID != "" || row.SignalPercent != nil || (state != "100" && row.State != "unknown") {
t.Fatal(row)
}
}
row := parseNetworkConnections("GENERAL.DEVICE:wlan0\nGENERAL.TYPE:wifi\nGENERAL.STATE:100\nAP[1].IN-USE:*\nAP[1].SSID:" + strings.Repeat("x", 33) + "\nAP[1].SIGNAL:101")["wlan0"]
if row.SSID != "" || row.SignalPercent != nil {
t.Fatal(row)
}
}
func TestNetworkInventoryClassifiesPhysicalInterfacesWithoutNameHeuristics(t *testing.T) {
root := t.TempDir()
for name, dirs := range map[string][]string{"radio": {"wireless", "device"}, "cable": {"device"}, "tunnel": {}} {
base := filepath.Join(root, "sys/class/net", name)
if err := os.MkdirAll(base, 0700); err != nil {
t.Fatal(err)
}
for _, dir := range dirs {
if err := os.MkdirAll(filepath.Join(base, dir), 0700); err != nil {
t.Fatal(err)
}
}
if err := os.WriteFile(filepath.Join(base, "type"), []byte("1\n"), 0600); err != nil {
t.Fatal(err)
}
}
rows := []Network{{Name: "radio"}, {Name: "cable"}, {Name: "tunnel"}, {Name: "missing"}}
annotateNetworks(root, rows, map[string]networkObservation{"radio": {NetworkConnection: NetworkConnection{State: "connected", SSID: "test"}}, "tunnel": {NetworkConnection: NetworkConnection{State: "connected"}}})
if rows[0].Kind != "wifi" || rows[0].Connection.SSID != "test" || rows[1].Kind != "ethernet" || rows[2].Kind != "virtual" || rows[2].Connection != nil || rows[3].Kind != "unknown" {
t.Fatal(rows)
}
}
func TestNetworkInventoryCacheNeverWaitsForOSAndExpires(t *testing.T) {
started, release := make(chan struct{}, 2), make(chan struct{})
defer close(release)
c := networkInventoryCache{collect: func() map[string]networkObservation { started <- struct{}{}; <-release; return nil }}
now := time.Now()
returned := make(chan struct{})
go func() { c.snapshot(now); close(returned) }()
select {
case <-returned:
case <-time.After(time.Second):
t.Fatal("snapshot blocked on OS")
}
<-started
for range 10 {
if c.snapshot(now) != nil {
t.Fatal("invented initial data")
}
}
select {
case <-started:
t.Fatal("parallel collector")
default:
}
c.mu.Lock()
c.rows, c.checked = map[string]networkObservation{"wlan0": {NetworkConnection: NetworkConnection{State: "connected", SSID: "old"}}}, now
c.mu.Unlock()
if len(c.snapshot(now.Add(10*time.Second))) != 1 || c.snapshot(now.Add(16*time.Second)) != nil {
t.Fatal("freshness bound")
}
}
func TestNetworkOutputBound(t *testing.T) {
var b networkOutput
if _, err := b.Write(make([]byte, 64*1024)); err != nil {
t.Fatal(err)
}
if _, err := b.Write([]byte{1}); err == nil || b.Len() != 64*1024 {
t.Fatal("unbounded metadata")
}
var pipe networkOutput
if _, err := io.Copy(&pipe, io.LimitReader(strings.NewReader(strings.Repeat("x", 65537)), 65537)); err == nil || pipe.Len() > 65536 {
t.Fatal("reader optimization bypassed output bound")
}
}
+136
View File
@@ -0,0 +1,136 @@
# Read-only onboard network status
Operator job: open the existing onboard-computer settings in Core and identify
which physical network the selected board is connected to. The owner selected
a **Network** section in that window. It is domain content in the admitted
FeatureSettingsWindow composition, not a new workspace. The alternative of
mixing Wi-Fi into **Connection to Core** was rejected because physical network
association and the chosen private-network transport are different facts.
The section uses shared FeatureSettingsWindow, SettingsCard, StatusBadge,
Description and the registered network icon, plus existing fleet fact layout.
It shows Wi-Fi SSID, signal percentage, Ethernet state, interface and addresses.
Virtual interfaces are excluded. It has no network mutation or save action.
Missing, unreadable and stale observations remain explicit and never imply a
successful current connection. Stale evidence is labelled and timestamped.
Node adds typed physical interface metadata to its existing authenticated host
inventory. Linux sysfs identifies Wi-Fi/Ethernet without interface-name guesses.
NetworkManager provides association state and only the associated SSID/signal.
`nmcli device show` reads its existing cache; no scan, connection change,
credential read, new network listener, root helper or permission change is used.
NetworkManager was already a mandatory Debian dependency. Everything ships in
Node 0.8.52-97; nothing is manually configured on the qualification host.
An asynchronous single-reader cache refreshes at most every five seconds. The
command has a 1.5-second deadline and 64 KiB output limit. Failed observations
replace previous data; observations older than 15 seconds are not returned as
current by Node. UI freshness also requires current host inventory, a live
Core channel and a recent observation; a one-second local expiry check works
even when no new fleet events arrive. No history database is added.
Connection state reports the last observed OS network association, not Internet
reachability. The current presentation contract below separates it from board
transport liveness.
The read-only pipeline does not change NetBird/Tailscale selection, Worker,
Synology isolation, physical network configuration or vehicle control.
Acceptance (2026-11-01): frontend architecture checks, typecheck, all 1445
unit tests and production build passed. The bounded Ubuntu build completed all
24 jobs, including Go race tests, onboard UI and installer/environment tests.
The qualified Node 0.8.52-97 owner installer upgraded the prepared board with
one package update, no new packages and no removals. The live Core settings
window displayed the associated USB Wi-Fi SSID/signal/addresses, disconnected
internal Wi-Fi and unavailable Ethernet; repeated opening and Escape worked.
Metadata was collected by the installed unprivileged Node service without any
extra OS permission or configuration. The NetBird profile revision and active
X4 preview were preserved. No motor-control command was issued.
Private build/install evidence and the screenshot remain outside Git under the
session's runtime records. A prepared N006 does not establish clean-image
installation or physical Wi-Fi handover acceptance.
Adapter identification (Node 0.8.53-98): the existing NetworkManager read also
returns the OS vendor/product description; sysfs device/subsystem identifies
USB, PCI, SDIO, platform or virtio. Names are bounded and validated. No hardware
catalog, interface-name heuristic, device ID allowlist or new command is added.
The UI titles cards by network type and reported bus and shows model/vendor
alongside the system interface. It deliberately does not infer physical
internal/external placement from a bus (internal USB devices also exist).
If a group contains several adapters, deterministic initial ordering assigns
its numbers. The stable-presentation revision below preserves the known group
and its order across refreshes and missing reports. Numbers describe the open
window’s known group, not permanent hardware identities. Missing metadata stays
explicit. The section remains read-only and no OS change is
required outside the shipped Node update.
Node98 acceptance (2026-11-01): architecture and focused identification tests,
frontend typecheck, 1447 unit tests and the production build passed; all 24
bounded Ubuntu build jobs passed. The owner installer completed with one Node
upgrade and no new packages/removals. Live Core displayed independently
reported USB and PCI Wi-Fi models plus the PCI Ethernet model. The installed
unprivileged Node service supplied all hardware metadata. NetBird profile and
X4 version/preview were preserved; no motor command or network change was made.
Stable Core presentation (2026-11-01): settings retain the latest known adapter
cards for the lifetime of the open board window. Initial order is deterministic;
new interfaces append. Poll order, stale data, connection state and temporary
missing/unreadable inventory never reorder or remove known cards. A readable,
recent report omitting an adapter shows "not detected"; failed observation and
expired observation remain distinct from an explicit disconnected response.
Latest association facts retain their original timestamp after a negative
response, and the UI labels them as last known network/signal/IP. All fact rows
stay mounted, including vendor, signal and timestamp; no status-dependent
paragraph or row changes card height. The 20-second freshness check is preserved.
State resets on board identity change or window close; at most 64 absent rows
are remembered, with no limit on the current physical interface list. Older
inventory packets cannot overwrite accepted observations. This is a Core-only
presentation fix; no onboard package or OS configuration changes are required.
Stability acceptance (2026-11-01): architecture and 12 focused network tests,
frontend typecheck, all 1452 unit tests and production build passed. In the
canonical live UI, three cards retained identical order, field sets, heights
and positions across 21.242 seconds with new signal/timestamp observations.
Escape and reopening passed; no browser errors were recorded. Missing/error,
expiry, negative-state, recovery, board-switch and out-of-order cases were
checked synthetically without interrupting the physical network. The board
remained online. No onboard deployment, OS change or motor command was made.
Packet-driven state revision (2026-11-01, supersedes the UI expiry behavior
above): adapter cards show the last reported OS state. Clock age, board
liveness, inventory freshness and missing/unknown connection metadata never
rewrite that state. Explicit connected/disconnected/failed/etc. observations
change the state; a complete readable inventory can confirm an absent adapter.
An unreadable inventory cannot confirm removal. A reappearing adapter without
connection metadata has unknown state until a new observation confirms it.
Whole-snapshot and per-adapter observation timestamps reject older data.
The network section separately shows whether Core currently has a board link
and the source timestamp of the latest host snapshot. It does not run an expiry
timer. Card facts omit changing sample timestamps; equal semantic packets reuse
the fact data and memoized card props. Actual SSID, signal, address, hardware or
state changes still appear. Last association facts remain labeled as last known
after disconnect. The existing bounded window-owned memory and ordering remain.
No control/lease liveness rules, transport settings or Node installer change.
Read-only diagnosis: 31 local fleet samples over one minute all reported an
online board and identical physical adapter states. Association age ranged
11.02–24.17 seconds, crossing the old 20-second UI threshold in seven samples;
local API reads took 7–24 ms. The Node collects host metadata before the full
sensor inventory and then sends the full heartbeat; sensor driver inventory
reads are sequential with individual timeouts. Network metadata itself comes
from a separate bounded asynchronous cache. These timestamps establish an
inventory publication delay, not Wi-Fi disconnection; they do not attribute
all latency to a single driver or establish transport performance. Raw bounded
timing evidence stays in .runtime/board-network-state-20261101.
Packet-state acceptance: 15 network tests plus four architecture tests pass;
typecheck and production build pass. The full frontend run passed 1454/1455,
with one unrelated K1 manual-control label mismatch in separately modified
code; no K1 source/test was changed for this fix. Live UI snapshots 24.108
seconds apart retained identical adapter headers, order, heights and positions
while the host timestamp and signal updated. Escape/reopen passed with no
browser errors. The canonical 8000 service remained running. This qualifies
the read-only display, not reduced inventory transport latency. An already
open page needs a reload to receive the rebuilt frontend.