feat(events): deliver state changes to the configurable operator event center
This commit is contained in:
@@ -50,6 +50,8 @@ import type {
|
||||
import { useRecordedSessionAdmission } from "./core/observation/useRecordedSessionAdmission";
|
||||
import { useWorkspaceLayoutProfile } from "./core/observation/useWorkspaceLayoutProfile";
|
||||
import { useSessionDisplayProfile } from "./core/observation/useSessionDisplayProfile";
|
||||
import { EventPanel } from './components/notifications/NotificationHost';
|
||||
import { useNotifications } from './core/notifications/useNotificationHistory';
|
||||
import { viewerSettingsTargetIdentity } from "./core/observation/viewerSettingsTarget";
|
||||
import { resolvePolygonRunRoute } from "./core/polygon/runArchive";
|
||||
import {
|
||||
@@ -233,6 +235,7 @@ export default function App() {
|
||||
);
|
||||
runtimeUpdateViewerSettingsRef.current = runtime.updateViewerSettings;
|
||||
replayActiveRef.current = replayPresented;
|
||||
const notifications = useNotifications();
|
||||
const sessionDisplayProfile = useSessionDisplayProfile(replayPresented ? recordedReplay?.sessionId ?? null : null, (settings) => {
|
||||
sceneSettingsRef.current = settings;
|
||||
displayDraftRef.current = settings;
|
||||
@@ -691,6 +694,7 @@ export default function App() {
|
||||
displayName="DC"
|
||||
subtitle="Mission Core"
|
||||
triggerLabel={null}
|
||||
headerAction={{label: notifications.unread ? `Центр событий · непрочитанных: ${notifications.unread}` : 'Центр событий', pressed: notifications.open, controls: 'operator-events', onSelect: () => notifications.setOpen(open => !open)}}
|
||||
actions={[
|
||||
{
|
||||
id: "refresh",
|
||||
@@ -721,6 +725,8 @@ export default function App() {
|
||||
}
|
||||
contentOpen={workspace.contentOpen && activeDefinition !== null}
|
||||
contentExpanded
|
||||
endPanel={<EventPanel/>}
|
||||
endPanelOpen={notifications.open}
|
||||
header={header}
|
||||
stage={activeDefinition ? null :
|
||||
<LandingStage
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
import {useEffect, useState} from 'react';
|
||||
import {Button, Checker, Description, FeatureSettingsWindow, SettingsCard} from '@nodedc/ui-react';
|
||||
import {notificationRequest} from '../../core/notifications/history';
|
||||
|
||||
interface Preference {
|
||||
key: string;
|
||||
section: string;
|
||||
group: string;
|
||||
label: string;
|
||||
enabled: boolean;
|
||||
}
|
||||
|
||||
export function EventSettings({onClose}: {onClose: () => void}) {
|
||||
const [items, setItems] = useState<Preference[]>([]);
|
||||
const [section, setSection] = useState('Сеть');
|
||||
const [error, setError] = useState('');
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [attempt, setAttempt] = useState(0);
|
||||
useEffect(() => {
|
||||
let active = true;
|
||||
setError('');
|
||||
notificationRequest<Preference[]>('/preferences').then(result => {
|
||||
if (active) setItems(result);
|
||||
}).catch(() => { if (active) setError('Не удалось загрузить настройки событий.'); });
|
||||
return () => { active = false; };
|
||||
}, [attempt]);
|
||||
|
||||
async function configure(key: string, enabled: boolean) {
|
||||
setSaving(true);
|
||||
setError('');
|
||||
try {
|
||||
setItems(await notificationRequest<Preference[]>('/preferences', 'PATCH', {key, enabled}));
|
||||
} catch {
|
||||
setError('Не удалось подтвердить изменение. Обновите настройки и повторите попытку.');
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
}
|
||||
const sections = [...new Set(items.map(item => item.section))];
|
||||
const current = items.filter(item => item.section === section);
|
||||
const groups = [...new Set(current.map(item => item.group))];
|
||||
return <FeatureSettingsWindow open title="Настройки центра событий"
|
||||
identity={{title: 'Центр событий', avatarLabel: 'ЦС'}}
|
||||
sections={sections.map(label => ({id: label, label, icon: label === 'Сеть' ? 'network' : 'activity'}))}
|
||||
activeSection={section} onSectionChange={setSection} onClose={onClose}>
|
||||
{error && <><Description role="alert">{error}</Description><Button onClick={() => setAttempt(n => n + 1)}>Обновить настройки</Button></>}
|
||||
{!error && !items.length && <Description role="status">Загружаем настройки…</Description>}
|
||||
{groups.map(group => <SettingsCard key={group} title={group}>
|
||||
{current.filter(item => item.group === group).map(item => <Checker key={item.key}
|
||||
label={item.label} checked={item.enabled} disabled={saving}
|
||||
onChange={enabled => void configure(item.key, enabled)}/>)}
|
||||
</SettingsCard>)}
|
||||
</FeatureSettingsWindow>;
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import {useEffect, useRef, useState, type ReactNode} from 'react';
|
||||
import {ApplicationSidePanel, Button, Description, Icon, IconButton, ResourceList, ResourceRow, StatusBadge, ToastStack} from '@nodedc/ui-react';
|
||||
import {NotificationContext, useNotificationHistory, useNotifications} from '../../core/notifications/useNotificationHistory';
|
||||
import type {NotificationTone} from '../../core/notifications/history';
|
||||
import {EventSettings} from './EventSettings';
|
||||
|
||||
const tones = {success: 'success', warning: 'warning', error: 'danger', info: 'neutral'} as const;
|
||||
const labels: Record<NotificationTone, string> = {success: 'Успешно', warning: 'Внимание', error: 'Ошибка', info: 'Информация'};
|
||||
|
||||
export function NotificationHost({children}: {children: ReactNode}) {
|
||||
const state = useNotificationHistory();
|
||||
return <NotificationContext.Provider value={state}>
|
||||
{children}
|
||||
<ToastStack items={state.toasts} onDismiss={state.dismiss} observe={false}/>
|
||||
</NotificationContext.Provider>;
|
||||
}
|
||||
|
||||
export function EventPanel() {
|
||||
const state = useNotifications();
|
||||
const [settings, setSettings] = useState(false);
|
||||
const gear = useRef<HTMLButtonElement>(null);
|
||||
const close = () => {
|
||||
state.setOpen(false);
|
||||
document.querySelector<HTMLButtonElement>('[aria-controls="operator-events"]')?.focus();
|
||||
};
|
||||
useEffect(() => {
|
||||
if (!state.open) return;
|
||||
gear.current?.focus({preventScroll: true});
|
||||
}, [state.open]);
|
||||
return <ApplicationSidePanel id="operator-events" eyebrow="Mission Core" title="Центр событий"
|
||||
inert={!state.open} aria-label="Центр событий" closeLabel="Закрыть центр событий" onClose={close}
|
||||
onKeyDown={event => {
|
||||
if (event.key === 'Escape' && !settings) { event.stopPropagation(); close(); }
|
||||
}}
|
||||
headerActions={<IconButton ref={gear} label="Настройки центра событий" onClick={() => setSettings(true)}><Icon name="settings"/></IconButton>}>
|
||||
{state.error && <Description role="status">{state.error}</Description>}
|
||||
{!state.items.length && <Description>{state.loading ? 'Получаем события…' : 'Событий пока нет.'}</Description>}
|
||||
<ResourceList aria-label="История событий">{state.items.map(item => <li key={item.identity}>
|
||||
<ResourceRow title={item.title} description={item.description}
|
||||
metadata={new Date(item.at * 1000).toLocaleString('ru-RU')}
|
||||
statusPlacement="leading" status={<StatusBadge variant="indicator" tone={tones[item.tone]}
|
||||
aria-label={labels[item.tone]} title={labels[item.tone]}/>}/>
|
||||
</li>)}</ResourceList>
|
||||
{state.more && <Button loading={state.loading} onClick={() => void state.loadMore()}>Показать ещё</Button>}
|
||||
{settings && state.open && <EventSettings onClose={() => setSettings(false)}/>}
|
||||
</ApplicationSidePanel>;
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
export type NotificationTone='success'|'error'|'warning'|'info';
|
||||
export interface NotificationMessage {id:string;tone:NotificationTone|'loading';title:string;description?:string;durationMs?:number|null}
|
||||
export interface NotificationRecord {sequence:number;identity:string;at:number;tone:NotificationTone;title:string;description:string;source:string;read:number}
|
||||
export interface NotificationPage {items:NotificationRecord[];unread:number;latest:number;retention_limit:number}
|
||||
export async function notificationRequest<T>(path='',method='GET',body?:unknown):Promise<T>{
|
||||
const response=await fetch('/api/v1/notifications'+path,{method,credentials:'same-origin',cache:'no-store',signal:AbortSignal.timeout(10000),headers:body===undefined?{}:{'Content-Type':'application/json'},body:body===undefined?undefined:JSON.stringify(body)});
|
||||
if(!response.ok)throw new Error('История уведомлений временно недоступна.');
|
||||
return response.json();
|
||||
}
|
||||
export function mergeNotifications(current:NotificationRecord[],incoming:NotificationRecord[]){
|
||||
return [...new Map([...current,...incoming].map(item=>[item.sequence,item])).values()].sort((a,b)=>b.sequence-a.sequence).slice(0,5000);
|
||||
}
|
||||
export function networkToasts(items:NotificationRecord[],seen:Set<string>,now:number){
|
||||
const result:NotificationMessage[]=[];
|
||||
for(const item of items){
|
||||
if(seen.has(item.identity))continue;
|
||||
seen.add(item.identity);
|
||||
if(item.source!=='interface'&&now-item.at<=120&&now>=item.at-10)result.push({id:item.identity,tone:item.tone,title:item.title,description:item.description});
|
||||
}
|
||||
while(seen.size>5000)seen.delete(seen.values().next().value!);
|
||||
return result;
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
import {createContext,useContext,useEffect,useRef,useState} from 'react';
|
||||
import {mergeNotifications,networkToasts,notificationRequest,type NotificationMessage,type NotificationPage,type NotificationRecord} from './history';
|
||||
|
||||
export function useNotificationHistory(){
|
||||
const [items,setItems]=useState<NotificationRecord[]>([]),[unread,setUnread]=useState(0),[open,setOpen]=useState(false),[error,setError]=useState(''),[loading,setLoading]=useState(true),[more,setMore]=useState(false),[toasts,setToasts]=useState<NotificationMessage[]>([]);
|
||||
const seen=useRef(new Set<string>()),readThrough=useRef(0);
|
||||
useEffect(()=>{
|
||||
let live=true, stream:EventSource|undefined, retry:ReturnType<typeof setTimeout>|undefined;
|
||||
async function connect(){
|
||||
try{
|
||||
const initial=await notificationRequest<NotificationPage>();
|
||||
if(!live)return;
|
||||
setItems(initial.items);setUnread(initial.unread);setMore(initial.items.length===100);
|
||||
setLoading(false);setError('');
|
||||
stream=new EventSource('/api/v1/notifications/events?after='+initial.latest);
|
||||
stream.onopen=()=>{if(live)setError('');};
|
||||
stream.onerror=()=>{if(live)setError('Восстанавливаем связь с центром событий…');};
|
||||
stream.onmessage=event=>{
|
||||
if(!live)return;
|
||||
const page:NotificationPage=JSON.parse(event.data);
|
||||
setUnread(page.unread);setError('');
|
||||
if(page.items.length){
|
||||
setItems(old=>mergeNotifications(old,page.items));
|
||||
const incoming=networkToasts(page.items,seen.current,Date.now()/1000);
|
||||
if(incoming.length)setToasts(old=>[...old,...incoming].slice(-5));
|
||||
}
|
||||
};
|
||||
}catch{
|
||||
if(live){setLoading(false);setError('Восстанавливаем связь с центром событий…');retry=setTimeout(connect,5000);}
|
||||
}
|
||||
}
|
||||
void connect();
|
||||
return()=>{live=false;stream?.close();clearTimeout(retry);};
|
||||
},[]);
|
||||
const maximum=items[0]?.sequence??0;
|
||||
useEffect(()=>{
|
||||
if(!open||!unread||maximum<=readThrough.current)return;
|
||||
let active=true,timer:ReturnType<typeof setTimeout>|undefined;
|
||||
async function markRead(){
|
||||
try{
|
||||
await notificationRequest('/read','POST',{through:maximum});
|
||||
if(active){readThrough.current=maximum;setItems(old=>old.map(item=>item.sequence<=maximum?{...item,read:1}:item));}
|
||||
}catch{if(active)timer=setTimeout(markRead,5000);}
|
||||
}
|
||||
void markRead();
|
||||
return()=>{active=false;clearTimeout(timer);};
|
||||
},[open,maximum,unread]);
|
||||
const loadMore=async()=>{
|
||||
if(loading||!items.length)return;setLoading(true);
|
||||
try{const page=await notificationRequest<NotificationPage>('?before='+items[items.length-1].sequence);setItems(old=>mergeNotifications(old,page.items));setMore(page.items.length===100);setError('');}
|
||||
catch(e){setError(e instanceof Error?e.message:'История недоступна.');}finally{setLoading(false);}
|
||||
};
|
||||
return {items,unread,open,setOpen,error,loading,more,loadMore,toasts,dismiss:(id:string)=>setToasts(old=>old.filter(item=>item.id!==id))};
|
||||
}
|
||||
export const NotificationContext=createContext<ReturnType<typeof useNotificationHistory>|null>(null);
|
||||
export function useNotifications(){const context=useContext(NotificationContext);if(!context)throw new Error('Notification host missing');return context;}
|
||||
@@ -7,6 +7,7 @@ import "@nodedc/tokens/themes.css";
|
||||
import "@nodedc/ui-core/styles.css";
|
||||
|
||||
import App from "./App";
|
||||
import { NotificationHost } from './components/notifications/NotificationHost';
|
||||
import { installedDevicePlugins, installedNodeSensorContributions } from "./composition/devicePlugins";
|
||||
import { PlanningTestProvider } from "./core/missions/PlanningTestContext";
|
||||
import { DevicePluginHostProvider } from "./core/device-plugins/DevicePluginHost";
|
||||
@@ -27,7 +28,7 @@ createRoot(rootElement).render(
|
||||
<StrictMode><TooltipProvider>
|
||||
<DevicePluginHostProvider plugins={installedDevicePlugins} nodeSensorContributions={installedNodeSensorContributions}>
|
||||
<ComputeContourProvider>
|
||||
<PlanningTestProvider><App /></PlanningTestProvider>
|
||||
<PlanningTestProvider><NotificationHost><App /></NotificationHost></PlanningTestProvider>
|
||||
</ComputeContourProvider>
|
||||
</DevicePluginHostProvider>
|
||||
</TooltipProvider></StrictMode>,
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import {after,before,test} from 'node:test';
|
||||
import {createServer} from './support/vite-server.mjs';
|
||||
let server,merge,network,canSet,pending,canSelect;
|
||||
before(async()=>{server=await createServer({appType:'custom',logLevel:'silent',server:{middlewareMode:true}});
|
||||
({mergeNotifications:merge,networkToasts:network}=await server.ssrLoadModule('/src/core/notifications/history.ts'));
|
||||
({canSetFallback:canSet,fallbackPending:pending,canSelectUplink:canSelect}=await server.ssrLoadModule('/src/core/fleet/boardUplink.ts'));});
|
||||
after(async()=>{await server?.close();});
|
||||
test('history merges pages without losing dates or read status',()=>{
|
||||
assert.deepEqual(merge([{sequence:1,read:0},{sequence:3,read:0}],[{sequence:1,read:1},{sequence:2,read:0}]),[{sequence:3,read:0},{sequence:2,read:0},{sequence:1,read:1}]);
|
||||
});
|
||||
test('confirmed network transitions toast once; history and UI errors are not replayed',()=>{
|
||||
const seen=new Set(),message={identity:'transition',source:'uplink',at:1000,tone:'warning',title:'Связь',description:'Ethernet → Wi-Fi'};
|
||||
assert.equal(network([message],seen,1010).length,1);
|
||||
assert.equal(network([message],seen,1011).length,0);
|
||||
assert.equal(network([{...message,identity:'old',at:500},{...message,identity:'ui',source:'interface'}],seen,1011).length,0);
|
||||
});
|
||||
test('router outcomes toast globally once even outside the router window',()=>{
|
||||
const seen=new Set(),message={identity:'router:operation',source:'router',at:1000,tone:'error',title:'Режим роутера',description:'Роутер занят'};
|
||||
assert.equal(network([message],seen,1010).length,1);
|
||||
assert.equal(network([message],seen,1011).length,0);
|
||||
assert.equal(network([{...message,identity:'old',at:500}],seen,1011).length,0);
|
||||
});
|
||||
test('fallback control requires live support and does not turn a queued write into saved state',()=>{
|
||||
const v={available:true,path_verified:true,fallback:{enabled:true,revision:0},current_id:'a',candidates:[{id:'b',verified:true}],operation:null};
|
||||
assert.ok(canSet(v));assert.ok(!canSet({...v,fallback:null}));assert.ok(!canSet({...v,path_verified:false}));
|
||||
const queued={...v,fallback_operation:{phase:'queued'}};assert.ok(pending(queued));assert.ok(!canSet(queued));assert.ok(!canSelect(queued,'b'));assert.equal(queued.fallback.enabled,true);
|
||||
});
|
||||
Reference in New Issue
Block a user