fix(scene): persist editor and battery profiles in Core
This commit is contained in:
@@ -335,3 +335,19 @@ decoders before BLE/Wi-Fi/data-session evidence exists.
|
||||
unchanged searches or model variants under a new name.
|
||||
- Worker access/power/runtime authority comes from the owner's current session
|
||||
instructions, never from the card or an old experiment's training allowance.
|
||||
|
||||
|
||||
## Scene profile persistence — owner requirement, 2026-11-09
|
||||
|
||||
- Rover/battery materials, imported textures, scene/environment profiles, camera
|
||||
pose, editor-window layout and battery UI/view settings are durable Core JSON
|
||||
configuration. Use `data_dir/scene-profiles/.../meta.json`; never make browser
|
||||
IndexedDB/localStorage their sole authority. Do not classify these files or
|
||||
their recovery copies as cache or task scratch.
|
||||
- Legacy browser records may be read once only when the Core document is absent.
|
||||
A failed read must not save defaults over user settings. Preserve source data
|
||||
during migration/recovery; use atomic replacement, previous-version backup and
|
||||
revision checks so a stale tab cannot silently replace a newer profile.
|
||||
- Recover actual settings from retained JSON/records before considering manual
|
||||
reconstruction. Distinguish a proven storage defect from an unproven deletion
|
||||
trigger, and state the timestamp/fidelity limit of any recovered source.
|
||||
|
||||
@@ -11,13 +11,13 @@ export function BatteryAppearanceSettings({open,onClose,profile,sensor}:{sensor?
|
||||
const {value,update}=profile,m=value.markings;
|
||||
const range=(label:string,value:number,min:number,max:number,onChange:(v:number)=>void)=><RangeControl label={label} value={value} min={min} max={max} step={1} exactValueBounds={{min,max}} onChange={onChange}/>;
|
||||
const exportJson=()=>{const url=URL.createObjectURL(new Blob([JSON.stringify(value,null,2)],{type:'application/json'}));const a=document.createElement('a');a.href=url;a.download='battery-ui.json';a.click();setTimeout(()=>URL.revokeObjectURL(url),1000);};
|
||||
return <FeatureSettingsWindow open={open} title="Настройки батареи" identity={{title:'Батарея',subtitle:section==='markings'||section==='panels'?'Локальный профиль':'BMS',avatarLabel:'АКБ'}} sections={[{id:'markings',label:'Маркировка ячеек',icon:'layers'},{id:'panels',label:'Дизайн',icon:'settings'},...(sensor?[{id:'diagnostics' as const,label:'Диагностика BMS',icon:'activity' as const},{id:'protection' as const,label:'Параметры BMS',icon:'sliders' as const},{id:'control' as const,label:'Управление BMS',icon:'power' as const}]:[])]} activeSection={section} onSectionChange={setSection} onClose={onClose}
|
||||
return <FeatureSettingsWindow open={open} title="Настройки батареи" identity={{title:'Батарея',subtitle:section==='markings'||section==='panels'?'Профиль Mission Core':'BMS',avatarLabel:'АКБ'}} sections={[{id:'markings',label:'Маркировка ячеек',icon:'layers'},{id:'panels',label:'Дизайн',icon:'settings'},...(sensor?[{id:'diagnostics' as const,label:'Диагностика BMS',icon:'activity' as const},{id:'protection' as const,label:'Параметры BMS',icon:'sliders' as const},{id:'control' as const,label:'Управление BMS',icon:'power' as const}]:[])]} activeSection={section} onSectionChange={setSection} onClose={onClose}
|
||||
headerActions={(section==='markings'||section==='panels')&&<><IconButton label="Отменить настройку батареи" disabled={!profile.canUndo} onClick={profile.undo}><Icon name="undo"/></IconButton><IconButton label="Повторить настройку батареи" disabled={!profile.canRedo} onClick={profile.redo}><Icon name="redo"/></IconButton></>}
|
||||
footer={(section==='markings'||section==='panels')&&<><Button onClick={exportJson}>Экспорт JSON</Button><Button onClick={()=>input.current?.click()}>Импорт JSON</Button><input ref={input} type="file" accept="application/json,.json" hidden onChange={async event=>{const file=event.currentTarget.files?.[0];event.currentTarget.value='';if(!file)return;try{if(file.size>32000)throw new Error('Файл настроек слишком большой.');update(parseBatteryAppearance(JSON.parse(await file.text())));}catch(error){profile.setError(error instanceof Error?error.message:'Не удалось прочитать профиль.');}}}/></>}>
|
||||
{sensor&§ion!=='markings'&§ion!=='panels'?<BmsSettings {...sensor} section={section} open={open}/>:section==='markings'?<SettingsCard title="Маркировка ячеек" description="Номер и напряжение на заводских площадках модели. Размер меняет надпись внутри площадки.">
|
||||
<ControlRow label="Цвет маркировки"><ColorField label="Цвет маркировки" value={m.color} onChange={color=>update({...value,markings:{...m,color}})}/></ControlRow>
|
||||
{range('Размер маркировки, %',m.size,50,160,size=>update({...value,markings:{...m,size}}))}
|
||||
</SettingsCard>:<BatteryDesignSettings value={value} update={update}/>}
|
||||
{(section==='markings'||section==='panels')&&<Description>Сохраняется на этом компьютере для этой батареи. Ctrl Z / ⌘ Z — отмена, Shift Ctrl Z / ⇧ ⌘ Z — повтор.</Description>}
|
||||
{(section==='markings'||section==='panels')&&<Description>Сохраняется в Mission Core для этой батареи. Ctrl Z / ⌘ Z — отмена, Shift Ctrl Z / ⇧ ⌘ Z — повтор.</Description>}
|
||||
</FeatureSettingsWindow>;
|
||||
}
|
||||
|
||||
@@ -1,23 +1,24 @@
|
||||
import {useBatteryView} from '../../core/batteryScene/useBatteryView';
|
||||
import type {SensorDetailProps} from '../../../../../packages/sensor-ui/src/extensions';
|
||||
import {BatteryAppearanceSettings} from './BatteryAppearanceSettings';
|
||||
import {useBatteryAppearance} from '../../core/batteryScene/useBatteryAppearance';
|
||||
import type {BatteryAppearance} from '../../core/batteryScene/appearance';
|
||||
import {useEffect,useState,type ReactNode} from 'react';
|
||||
import {createPortal} from 'react-dom';
|
||||
import {EditorWorkspace,Icon,IconButton,ResizableViewport,ToastStack,useApplicationPanelFullscreen} from '@nodedc/ui-react';
|
||||
import {batteryViewHeight,batteryViewHeightKey,minBatteryViewHeight,maxBatteryViewHeight} from '../../core/batteryScene/viewHeight';
|
||||
import {EditorWorkspace,Icon,IconButton,LoadingRegion,ResizableViewport,ToastStack,useApplicationPanelFullscreen} from '@nodedc/ui-react';
|
||||
import {minBatteryViewHeight,maxBatteryViewHeight} from '../../core/batteryScene/viewHeight';
|
||||
|
||||
export function BatteryWorkspace({children,deviceId,title,headerActionsTarget,back,sensor,fullscreenControl}:{sensor?:SensorDetailProps;fullscreenControl?:{fullscreen:boolean;setFullscreen:(value:boolean)=>void};deviceId:string;title:string;headerActionsTarget?:HTMLElement|null;back:()=>void;children:(controls:{editing:boolean;appearance:BatteryAppearance;renderViewport:(children:ReactNode)=>ReactNode})=>ReactNode}){
|
||||
const inheritedFull=useApplicationPanelFullscreen(),full=fullscreenControl??inheritedFull,[editing,setEditing]=useState(false),[error,setError]=useState(''),[settings,setSettings]=useState(false);
|
||||
const profile=useBatteryAppearance(deviceId,settings);
|
||||
const [height,setHeight]=useState(()=>{try{return batteryViewHeight(localStorage.getItem(batteryViewHeightKey(deviceId)),window.innerHeight);}catch{return batteryViewHeight(null,window.innerHeight);}});
|
||||
const view=useBatteryView(deviceId);const {height,setHeight,commitHeight}=view;
|
||||
const fullscreen=full?.fullscreen??false,setFullscreen=full?.setFullscreen;
|
||||
useEffect(()=>()=>{setFullscreen?.(false);},[setFullscreen]);
|
||||
useEffect(()=>{const escape=(event:KeyboardEvent)=>{
|
||||
if(event.key!=='Escape'||event.defaultPrevented||document.querySelector('[role=dialog],[role=listbox]'))return;
|
||||
event.preventDefault();if(fullscreen)setFullscreen?.(false);else if(editing)setEditing(false);else back();
|
||||
};window.addEventListener('keydown',escape);return()=>window.removeEventListener('keydown',escape);},[editing,fullscreen,setFullscreen,back]);
|
||||
const commitHeight=(value:number)=>{try{localStorage.setItem(batteryViewHeightKey(deviceId),JSON.stringify({height:value}));setError('');}catch{setError('Не удалось сохранить высоту окна на этом компьютере.');}};
|
||||
|
||||
const actions=<>{full&&<IconButton label={fullscreen?'Восстановить окно батареи':'Развернуть окно батареи'} onClick={()=>setFullscreen?.(!fullscreen)}><Icon name={fullscreen?'minimize':'expand'}/></IconButton>}<IconButton label={editing?'Завершить редактирование сцены':'Редактировать сцену'} aria-pressed={editing} onClick={()=>{setSettings(false);setEditing(value=>!value);}}><Icon name="edit"/></IconButton><IconButton label="Настройки батареи" aria-pressed={settings} onClick={()=>{setEditing(false);setSettings(true);}}><Icon name="settings"/></IconButton></>;
|
||||
return <>{headerActionsTarget?createPortal(actions,headerActionsTarget):actions}{children({editing,appearance:profile.value,renderViewport:content=><ResizableViewport resizeIndicator={false} className="bms-stage" height={height} minHeight={minBatteryViewHeight} maxHeight={maxBatteryViewHeight} onHeightChange={setHeight} onHeightCommit={commitHeight}><EditorWorkspace editing={editing} title={title} subtitle="Редактирование сцены аккумулятора" onBack={()=>setEditing(false)}><div className="bms-stage bms-editor-content">{content}</div></EditorWorkspace></ResizableViewport>})}<BatteryAppearanceSettings open={settings} onClose={()=>setSettings(false)} profile={profile} sensor={sensor}/><ToastStack items={(error||profile.error)?[{id:'battery-view-save',title:error||profile.error,tone:'error'}]:[]} onDismiss={()=>{setError('');profile.setError('');}}/></>;
|
||||
return <>{headerActionsTarget?createPortal(actions,headerActionsTarget):actions}<LoadingRegion loading={!profile.ready||!view.ready} label="Загрузка настроек батареи">{profile.ready&&view.ready&&children({editing,appearance:profile.value,renderViewport:content=><ResizableViewport resizeIndicator={false} className="bms-stage" height={height} minHeight={minBatteryViewHeight} maxHeight={maxBatteryViewHeight} onHeightChange={setHeight} onHeightCommit={commitHeight}><EditorWorkspace editing={editing} title={title} subtitle="Редактирование сцены аккумулятора" onBack={()=>setEditing(false)}><div className="bms-stage bms-editor-content">{content}</div></EditorWorkspace></ResizableViewport>})}</LoadingRegion><BatteryAppearanceSettings open={settings} onClose={()=>setSettings(false)} profile={profile} sensor={sensor}/><ToastStack items={(error||profile.error||view.error)?[{id:'battery-view-save',title:error||profile.error||view.error,tone:'error'}]:[]} onDismiss={()=>{setError('');profile.setError('');view.setError('');}}/></>;
|
||||
}
|
||||
|
||||
@@ -23,7 +23,7 @@ export function EnvironmentProfiles({document:doc,update,onError}:{document:Scen
|
||||
<Description>{dirty?'Есть изменения относительно профиля. Настройки сцены сохраняются автоматически.':'Настройки совпадают с профилем.'}</Description>
|
||||
<div className="rover-scene-actions"><Button size="compact" disabled={!ready||!selected||selected.id===builtin.id||pending||!dirty} loading={pending&&!draft} onClick={()=>void save(false)}>Пересохранить профиль</Button><Button size="compact" disabled={!ready||pending} onClick={()=>begin()}>Сохранить как…</Button></div>
|
||||
<div className="rover-scene-actions"><Button size="compact" onClick={exportJson}>Экспорт JSON</Button><Button size="compact" disabled={!ready||pending} onClick={()=>input.current?.click()}>Импорт JSON</Button></div>
|
||||
<Description>Библиотека общая для сцен на этом компьютере. Профиль переносит окружение и поведение камеры; ракурс, материалы и компоновка сцены сохраняются.</Description>
|
||||
<Description>Библиотека общая для сцен в Mission Core. Профиль переносит окружение и поведение камеры; ракурс, материалы и компоновка сцены сохраняются.</Description>
|
||||
<input ref={input} type="file" hidden accept=".json,application/json" onChange={async e=>{const f=e.currentTarget.files?.[0];e.currentTarget.value='';if(!f)return;try{if(f.size>2_000_000)throw new Error('Профиль больше 2 МБ.');const value=parseEnvironmentProfile(JSON.parse(await f.text()));if(mounted.current)begin(value);}catch(error){onError(error instanceof Error?error.message:'Не удалось импортировать профиль.');}}}/>
|
||||
<Window open={!!draft} onClose={()=>{if(!pending)setDraft(null);}} title="Сохранить профиль окружения" size="sm" footer={<WindowFooterActions><Button disabled={pending} onClick={()=>setDraft(null)}>Отмена</Button><Button variant="primary" loading={pending} disabled={!name.trim()} onClick={()=>void save(true)}>Сохранить</Button></WindowFooterActions>}>
|
||||
<TextField label="Название профиля" value={name} maxLength={80} disabled={pending} onChange={e=>setName(e.target.value)}/>
|
||||
|
||||
@@ -44,7 +44,7 @@ export function SceneEditor({scene,editing,onModelState,modelUrl=roverModelURL,o
|
||||
const node=findSceneObject(root,selectedObject),targets=node?objectTargets(node):[];
|
||||
useObjectSelection(sceneApi,targets,editing&&modelPhase==='ready');
|
||||
const material=selected?scene.document.materials[selected]:null;
|
||||
const saved=scene.saveState==='saved',status=textureState==='loading'?'Загрузка текстур':scene.saveState==='loading'?'Загрузка настроек сцены':scene.saveState==='saving'?'Сохранение сцены':scene.saveState==='error'?'Изменения не сохранены':'Сохранено на этом компьютере';
|
||||
const saved=scene.saveState==='saved',status=textureState==='loading'?'Загрузка текстур':scene.saveState==='loading'?'Загрузка настроек сцены':scene.saveState==='saving'?'Сохранение сцены':scene.saveState==='error'?'Изменения не сохранены':'Сохранено в Mission Core';
|
||||
const tools:EditorDockTool[]=[
|
||||
{id:'objects',title:'Объекты сцены',label:'Объекты сцены',open:objectsOpen,onClose:()=>setObjectsOpen(false),className:'scene-object-window',initialRect:{left:16,top:16,width:380,height:600},content:<SceneObjectTree revealVersion={selectionVersion} root={root} selected={selectedObject} visibility={scene.document.objectVisibility} legacyVisibility={scene.document.objects} onSelect={selectObject} onVisibility={(id,value)=>scene.update(doc=>({...doc,objectVisibility:{...doc.objectVisibility,[id]:value}}))}/>},
|
||||
{id:'palette',title:'Материалы сцены',label:'Материалы сцены',open:palette,onClose:()=>setPalette(false),className:'rover-material-palette',initialRect:{left:400,top:420,width:640,height:340},minimumSize:{width:280,height:180},
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import {legacyRecord,profileClient} from '../roverScene/profileClient';
|
||||
import {defaultChargeGradient} from '../roverScene/chargeGradient';
|
||||
import r04 from './r04.json';
|
||||
import {defaultScene,parseScene,type SceneDocument} from '../roverScene/sceneDocument';
|
||||
@@ -8,27 +9,16 @@ export function defaultBatteryScene():SceneDocument {
|
||||
return {...defaultScene(),schema:'missioncore.battery-scene/v1',model:'catl-r04/v1',
|
||||
materials:{...structuredClone(r04.materials),'bms/cells':{...structuredClone(r04.materials['bms/cells']),color:'#050505',emissiveIntensity:0,chargeGradient:defaultChargeGradient()}},assignments:{},objects:{...r04.objects}};
|
||||
}
|
||||
function database():Promise<IDBDatabase>{return new Promise((resolve,reject)=>{
|
||||
const request=indexedDB.open('missioncore-battery-scenes',1);
|
||||
request.onupgradeneeded=()=>request.result.createObjectStore('scenes');
|
||||
request.onsuccess=()=>resolve(request.result);request.onerror=()=>reject(request.error);
|
||||
request.onblocked=()=>reject(new Error('Хранилище батареи занято другим окном.'));
|
||||
});}
|
||||
async function save(id:string,document:SceneDocument){const db=await database();try{await new Promise<void>((resolve,reject)=>{
|
||||
const tx=db.transaction('scenes','readwrite');tx.objectStore('scenes').put(document,id);
|
||||
tx.oncomplete=()=>resolve();tx.onerror=()=>reject(tx.error);tx.onabort=()=>reject(tx.error);
|
||||
});}finally{db.close();}}
|
||||
export function batterySceneProfile(seedKey?:string):SceneDocumentProfile {
|
||||
return {defaults:defaultBatteryScene,write:save,filename:'battery-r04-scene.json',read:async id=>{
|
||||
const db=await database();let raw:unknown;try{raw=await new Promise((resolve,reject)=>{
|
||||
const request=db.transaction('scenes').objectStore('scenes').get(id);
|
||||
request.onsuccess=()=>resolve(request.result);request.onerror=()=>reject(request.error);
|
||||
});}finally{db.close();}
|
||||
const clients=new Map<string,ReturnType<typeof profileClient<SceneDocument>>>();
|
||||
const client=(id:string)=>{let c=clients.get(id);if(!c){c=profileClient<SceneDocument>('battery',id);clients.set(id,c);}return c;};
|
||||
return {defaults:defaultBatteryScene,write:(id,doc)=>client(id).write(doc),filename:'battery-r04-scene.json',read:async id=>{
|
||||
const raw=await client(id).read(async()=>{const old=await legacyRecord('missioncore-battery-scenes','scenes',id);return old?parseScene(old,defaultBatteryScene):null;});
|
||||
if(raw)return parseScene(raw,defaultBatteryScene);
|
||||
const seed=seedKey?await readScene(seedKey):null;
|
||||
const doc=defaultBatteryScene();
|
||||
if(seed){doc.postFx=structuredClone(seed.postFx);doc.cameraAutoRotate=seed.cameraAutoRotate;doc.cameraZoomStrength=seed.cameraZoomStrength;}
|
||||
// Copy once. Subsequent rover edits and battery edits have separate owners.
|
||||
await save(id,doc);return doc;
|
||||
// Defaults remain in memory until an explicit edit. Never overwrite a failed read.
|
||||
return doc;
|
||||
}};
|
||||
}
|
||||
|
||||
@@ -1,14 +1,23 @@
|
||||
import {useCallback,useEffect,useState} from 'react';
|
||||
import {useCallback,useEffect,useMemo,useRef,useState} from 'react';
|
||||
import {SceneHistory,historyCommand} from '../roverScene/sceneHistory';
|
||||
import {profileClient} from '../roverScene/profileClient';
|
||||
import {batteryAppearanceKey,defaultBatteryAppearance,parseBatteryAppearance,type BatteryAppearance} from './appearance';
|
||||
async function legacy(id:string){const raw=localStorage.getItem(batteryAppearanceKey(id));return raw?parseBatteryAppearance(JSON.parse(raw)):null;}
|
||||
export function useBatteryAppearance(id:string,active:boolean){
|
||||
const [error,setError]=useState('');
|
||||
const [history]=useState(()=>{let profile=defaultBatteryAppearance();try{const raw=localStorage.getItem(batteryAppearanceKey(id));if(raw)profile=parseBatteryAppearance(JSON.parse(raw));}catch{/* Keep the usable default if the local profile is unavailable. */}return new SceneHistory(profile);});
|
||||
const [value,setValue]=useState(history.present);
|
||||
const publish=useCallback(()=>{setValue(history.present);try{localStorage.setItem(batteryAppearanceKey(id),JSON.stringify(history.present));window.dispatchEvent(new CustomEvent('missioncore:battery-ui',{detail:id}));setError('');}catch{setError('Не удалось сохранить настройки батареи на этом компьютере.');}},[history,id]);
|
||||
const update=useCallback((next:BatteryAppearance)=>{if(JSON.stringify(next)!==JSON.stringify(history.present)){history.update(next);publish();}},[history,publish]);
|
||||
const undo=useCallback(()=>{if(history.undo())publish();},[history,publish]);
|
||||
const redo=useCallback(()=>{if(history.redo())publish();},[history,publish]);
|
||||
const [error,setError]=useState(''),[ready,setReady]=useState(false);
|
||||
const client=useMemo(()=>profileClient<BatteryAppearance>('battery-ui',id),[id]);
|
||||
const history=useMemo(()=>new SceneHistory(defaultBatteryAppearance()),[id]);
|
||||
const [value,setValue]=useState(history.present),loaded=useRef(false);
|
||||
const pending=useRef<BatteryAppearance|null>(null),timer=useRef<ReturnType<typeof setTimeout>|null>(null);
|
||||
const flush=useCallback(()=>{if(timer.current)clearTimeout(timer.current);const next=pending.current;if(!next)return;pending.current=null;
|
||||
void client.write(next).then(()=>{window.dispatchEvent(new CustomEvent('missioncore:battery-ui',{detail:id}));setError('');}).catch(e=>setError(e instanceof Error?e.message:'Не удалось сохранить оформление батареи.'));
|
||||
},[client,id]);
|
||||
useEffect(()=>{let cancelled=false;loaded.current=false;setReady(false);setError('');client.read(()=>legacy(id)).then(raw=>{if(!cancelled){const next=raw?parseBatteryAppearance(raw):defaultBatteryAppearance();history.reset(next);setValue(next);loaded.current=true;setReady(true);}}).catch(e=>{if(!cancelled)setError(e instanceof Error?e.message:'Не удалось прочитать оформление батареи.');});return()=>{cancelled=true;loaded.current=false;flush();};},[client,history,id,flush]);
|
||||
useEffect(()=>{window.addEventListener('pagehide',flush);return()=>window.removeEventListener('pagehide',flush);},[flush]);
|
||||
const publish=useCallback(()=>{setValue(history.present);pending.current=history.present;if(timer.current)clearTimeout(timer.current);timer.current=setTimeout(flush,300);},[history,flush]);
|
||||
const update=useCallback((next:BatteryAppearance)=>{if(!loaded.current){setError('Дождитесь загрузки профиля.');return;}if(JSON.stringify(next)!==JSON.stringify(history.present)){history.update(next);publish();}},[history,publish]);
|
||||
const undo=useCallback(()=>{if(loaded.current&&history.undo())publish();},[history,publish]);
|
||||
const redo=useCallback(()=>{if(loaded.current&&history.redo())publish();},[history,publish]);
|
||||
useEffect(()=>{
|
||||
if(!active)return;
|
||||
const begin=()=>history.begin(),end=()=>history.end();
|
||||
@@ -17,18 +26,18 @@ export function useBatteryAppearance(id:string,active:boolean){
|
||||
window.addEventListener('keydown',key,true);window.addEventListener('keyup',up,true);window.addEventListener('pointerdown',begin,true);window.addEventListener('pointerup',end);window.addEventListener('pointercancel',end);window.addEventListener('blur',end);
|
||||
return()=>{end();window.removeEventListener('keydown',key,true);window.removeEventListener('keyup',up,true);window.removeEventListener('pointerdown',begin,true);window.removeEventListener('pointerup',end);window.removeEventListener('pointercancel',end);window.removeEventListener('blur',end);};
|
||||
},[active,history,undo,redo]);
|
||||
return {value,update,undo,redo,canUndo:history.canUndo,canRedo:history.canRedo,error,setError};
|
||||
return {value,ready,update,undo,redo,canUndo:history.canUndo,canRedo:history.canRedo,error,setError};
|
||||
}
|
||||
|
||||
/** Read-only subscribers update immediately when this battery's design is edited. */
|
||||
/** Read-only subscribers share the persistent Core profile, across browsers. */
|
||||
export function useBatteryAppearanceValue(id:string|undefined){
|
||||
const [value,setValue]=useState(defaultBatteryAppearance);
|
||||
useEffect(()=>{
|
||||
const read=()=>{try{const raw=id&&localStorage.getItem(batteryAppearanceKey(id));setValue(raw?parseBatteryAppearance(JSON.parse(raw)):defaultBatteryAppearance());}catch{setValue(defaultBatteryAppearance());}};
|
||||
let cancelled=false;
|
||||
const read=()=>{if(!id){setValue(defaultBatteryAppearance());return;}void profileClient<BatteryAppearance>('battery-ui',id).read(()=>legacy(id)).then(raw=>{if(!cancelled)setValue(raw?parseBatteryAppearance(raw):defaultBatteryAppearance());}).catch(()=>{/* Retain the current indicator on a temporary Core disconnect. */});};
|
||||
const local=(event:Event)=>{if((event as CustomEvent).detail===id)read();};
|
||||
const external=(event:StorageEvent)=>{if(!event.key||event.key===(id&&batteryAppearanceKey(id)))read();};
|
||||
read();window.addEventListener('missioncore:battery-ui',local);window.addEventListener('storage',external);
|
||||
return()=>{window.removeEventListener('missioncore:battery-ui',local);window.removeEventListener('storage',external);};
|
||||
read();window.addEventListener('missioncore:battery-ui',local);window.addEventListener('focus',read);
|
||||
return()=>{cancelled=true;window.removeEventListener('missioncore:battery-ui',local);window.removeEventListener('focus',read);};
|
||||
},[id]);
|
||||
return value;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
import {useEffect,useMemo,useState} from 'react';
|
||||
import {profileClient} from '../roverScene/profileClient';
|
||||
import {batteryViewHeight,batteryViewHeightKey} from './viewHeight';
|
||||
type View={schema:'missioncore.battery-view/v1';height:number};
|
||||
export function useBatteryView(id:string){
|
||||
const client=useMemo(()=>profileClient<View>('battery-view',id),[id]);
|
||||
const [height,setHeight]=useState(()=>batteryViewHeight(null,window.innerHeight));
|
||||
const [ready,setReady]=useState(false),[error,setError]=useState('');
|
||||
useEffect(()=>{let cancelled=false;setReady(false);setError('');void client.read(async()=>{
|
||||
const raw=localStorage.getItem(batteryViewHeightKey(id));return raw?{schema:'missioncore.battery-view/v1',height:batteryViewHeight(raw,window.innerHeight)}:null;
|
||||
}).then(value=>{if(!cancelled){setHeight(batteryViewHeight(JSON.stringify(value),window.innerHeight));setReady(true);}}).catch(e=>{if(!cancelled)setError(e.message);});return()=>{cancelled=true;};},[client,id]);
|
||||
const commitHeight=(value:number)=>{if(!ready)return;void client.write({schema:'missioncore.battery-view/v1',height:value}).then(()=>setError('')).catch(e=>setError(e.message));};
|
||||
return {height,setHeight,commitHeight,ready,error,setError};
|
||||
}
|
||||
@@ -1,17 +1,17 @@
|
||||
import {parseEnvironmentProfile,prepareEnvironmentSave,validEnvironmentId,type StoredEnvironmentProfile} from './environmentProfiles';
|
||||
import {legacyRecord,profileClient} from './profileClient';
|
||||
const eventName='missioncore:environment-profiles';
|
||||
function database():Promise<IDBDatabase>{return new Promise((resolve,reject)=>{const r=indexedDB.open('missioncore-environment-profiles',1);r.onupgradeneeded=()=>r.result.createObjectStore('profiles',{keyPath:'id'});r.onsuccess=()=>resolve(r.result);r.onerror=()=>reject(r.error);r.onblocked=()=>reject(new Error('Хранилище профилей занято другим окном.'));});}
|
||||
type Library={schema:'missioncore.environment-library/v1';profiles:StoredEnvironmentProfile[]};
|
||||
function records(raw:unknown[]):StoredEnvironmentProfile[]{return raw.map((r:any)=>{if(!validEnvironmentId(r?.id)||r.id==='nodedc'||!Number.isInteger(r.revision)||r.revision<1)throw new Error('Не удалось прочитать библиотеку профилей.');return {...parseEnvironmentProfile(r),id:r.id,revision:r.revision};});}
|
||||
export async function readEnvironmentProfiles():Promise<StoredEnvironmentProfile[]>{
|
||||
const db=await database();try{return await new Promise((resolve,reject)=>{const r=db.transaction('profiles').objectStore('profiles').getAll();r.onsuccess=()=>{try{resolve(records(r.result));}catch(e){reject(e);}};r.onerror=()=>reject(r.error);});}finally{db.close();}
|
||||
async function library(){
|
||||
const client=profileClient<Library>('environments','shared');
|
||||
const value=await client.read(async()=>{const raw=await legacyRecord('missioncore-environment-profiles','profiles');return Array.isArray(raw)&&raw.length?{schema:'missioncore.environment-library/v1',profiles:records(raw)}:null;});
|
||||
return {client,profiles:records(value?.profiles??[])};
|
||||
}
|
||||
export async function readEnvironmentProfiles():Promise<StoredEnvironmentProfile[]>{return (await library()).profiles;}
|
||||
export async function saveEnvironmentProfile(profile:StoredEnvironmentProfile,expectedRevision:number|null):Promise<StoredEnvironmentProfile>{
|
||||
const db=await database();let saved:StoredEnvironmentProfile;
|
||||
try{saved=await new Promise((resolve,reject)=>{
|
||||
const tx=db.transaction('profiles','readwrite'),store=tx.objectStore('profiles'),r=store.getAll();let next:StoredEnvironmentProfile,error:unknown;
|
||||
r.onsuccess=()=>{try{next=prepareEnvironmentSave(records(r.result),profile,expectedRevision);store.put(next);}catch(e){error=e;tx.abort();}};
|
||||
tx.oncomplete=()=>resolve(next);tx.onabort=()=>reject(error??tx.error);tx.onerror=()=>reject(error??tx.error);
|
||||
});}finally{db.close();}
|
||||
const {client,profiles}=await library(),saved=prepareEnvironmentSave(profiles,profile,expectedRevision);
|
||||
await client.write({schema:'missioncore.environment-library/v1',profiles:[...profiles.filter(p=>p.id!==saved.id),saved]});
|
||||
window.dispatchEvent(new Event(eventName));
|
||||
if(typeof BroadcastChannel!=='undefined'){const channel=new BroadcastChannel(eventName);channel.postMessage('changed');channel.close();}
|
||||
return saved;
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
/** Durable JSON authority. A legacy browser record is only a one-time migration input. */
|
||||
export type ProfileKind='battery'|'rover'|'battery-ui'|'battery-view'|'environments';
|
||||
type Stored<T>={revision:number;document:T|null};
|
||||
export function profileClient<T>(kind:ProfileKind,owner:string){
|
||||
let revision:number|undefined;
|
||||
let queue=Promise.resolve();
|
||||
const url=`/api/v1/scene-profiles/${kind}?owner=${encodeURIComponent(owner)}`;
|
||||
async function request(method='GET',body?:unknown):Promise<Stored<T>>{
|
||||
const response=await fetch(url,{method,cache:'no-store',headers:{'Content-Type':'application/json'},...(body?{body:JSON.stringify(body),keepalive:JSON.stringify(body).length<60000}:{})});
|
||||
if(!response.ok){let message='Не удалось загрузить или сохранить профиль в Mission Core.';try{const value=await response.json();if(typeof value.detail==='string')message=value.detail;}catch{}throw new Error(message);}
|
||||
const result=await response.json();if(!Number.isInteger(result.revision)||!Object.hasOwn(result,'document'))throw new Error('Неверный ответ хранилища профилей.');return result;
|
||||
}
|
||||
async function read(legacy?:()=>Promise<T|null>):Promise<T|null>{
|
||||
let value=await request();
|
||||
if(value.document===null&&legacy){const old=await legacy();if(old!==null){
|
||||
try{value=await request('PUT',{document:old,expected_revision:0});}
|
||||
catch(error){const winner=await request();if(winner.document===null)throw error;value=winner;}
|
||||
}}
|
||||
revision=value.revision;return value.document;
|
||||
}
|
||||
function write(document:T):Promise<void>{
|
||||
const next=queue.catch(()=>{}).then(async()=>{
|
||||
if(revision===undefined)throw new Error('Профиль ещё не загружен. Сохранение отменено.');
|
||||
const value=await request('PUT',{document,expected_revision:revision});revision=value.revision;
|
||||
});queue=next;return next;
|
||||
}
|
||||
return {read,write};
|
||||
}
|
||||
|
||||
export async function legacyRecord(database:string,store:string,key?:string):Promise<unknown>{
|
||||
if(typeof indexedDB==='undefined'||typeof indexedDB.databases!=='function')return null;
|
||||
const databases=await indexedDB.databases();if(!databases.some(d=>d.name===database))return null;
|
||||
const db=await new Promise<IDBDatabase>((resolve,reject)=>{const r=indexedDB.open(database);r.onupgradeneeded=()=>{r.transaction?.abort();reject(new Error('Старое хранилище исчезло.'));};r.onsuccess=()=>resolve(r.result);r.onerror=()=>reject(r.error);});
|
||||
try{if(!db.objectStoreNames.contains(store))return null;return await new Promise((resolve,reject)=>{const s=db.transaction(store,'readonly').objectStore(store),r=key===undefined?s.getAll():s.get(key);r.onsuccess=()=>resolve(r.result??null);r.onerror=()=>reject(r.error);});}finally{db.close();}
|
||||
}
|
||||
@@ -1,22 +1,13 @@
|
||||
import type {SceneDocument} from './sceneDocument';
|
||||
import {loadStoredScene} from './sceneMigration';
|
||||
// Retain the original storage slot so upgrades preserve operator materials and environment.
|
||||
import {legacyRecord,profileClient} from './profileClient';
|
||||
const key=(vehicle:string)=>`${vehicle}:dcd006-v020-materials-v2`;
|
||||
function database():Promise<IDBDatabase>{return new Promise((resolve,reject)=>{const r=indexedDB.open('missioncore-rover-scenes',1);r.onupgradeneeded=()=>r.result.createObjectStore('scenes');r.onerror=()=>reject(r.error);r.onblocked=()=>reject(new Error('Хранилище сцены занято другим окном.'));r.onsuccess=()=>resolve(r.result);});}
|
||||
export async function readScene(vehicle:string):Promise<SceneDocument|null>{
|
||||
const db=await database();try{
|
||||
const raw=await new Promise<unknown>((resolve,reject)=>{const r=db.transaction('scenes').objectStore('scenes').get(key(vehicle));r.onerror=()=>reject(r.error);r.onsuccess=()=>resolve(r.result);});
|
||||
if(!raw)return null;
|
||||
const result=loadStoredScene(raw);
|
||||
if(result.updated)await new Promise<void>((resolve,reject)=>{
|
||||
const tx=db.transaction('scenes','readwrite'),store=tx.objectStore('scenes');
|
||||
if(result.restoredEnvironment)store.put(raw,`${key(vehicle)}:before-environment-v2`);
|
||||
store.put(result.document,key(vehicle));tx.oncomplete=()=>resolve();tx.onabort=()=>reject(tx.error);tx.onerror=()=>reject(tx.error);
|
||||
});
|
||||
return result.document;
|
||||
}finally{db.close();}
|
||||
export function roverSceneProfile(){
|
||||
const clients=new Map<string,ReturnType<typeof profileClient<SceneDocument>>>();
|
||||
const client=(id:string)=>{let c=clients.get(id);if(!c){c=profileClient<SceneDocument>('rover',id);clients.set(id,c);}return c;};
|
||||
return {read:async(id:string)=>{const value=await client(id).read(async()=>{const raw=await legacyRecord('missioncore-rover-scenes','scenes',key(id));return raw?loadStoredScene(raw).document:null;});return value?loadStoredScene(value).document:null;},write:(id:string,doc:SceneDocument)=>client(id).write(doc)};
|
||||
}
|
||||
export async function saveScene(vehicle:string,document:SceneDocument):Promise<void>{const db=await database();try{await new Promise<void>((resolve,reject)=>{const tx=db.transaction('scenes','readwrite');tx.objectStore('scenes').put(document,key(vehicle));tx.oncomplete=()=>resolve();tx.onabort=()=>reject(tx.error);tx.onerror=()=>reject(tx.error);});}finally{db.close();}}
|
||||
export async function readScene(vehicle:string):Promise<SceneDocument|null>{return roverSceneProfile().read(vehicle);}
|
||||
export async function textureFromFile(file:File):Promise<{name:string;data:string}>{
|
||||
if(!['image/png','image/jpeg','image/webp'].includes(file.type)||file.size>8_000_000)throw new Error('Выберите PNG, JPEG или WebP до 8 МБ.');
|
||||
const bitmap=await createImageBitmap(file);try{if(bitmap.width>4096||bitmap.height>4096)throw new Error('Максимальный размер текстуры — 4096 × 4096.');}finally{bitmap.close();}
|
||||
|
||||
@@ -1,32 +1,44 @@
|
||||
import type {CameraState} from './cameraState';
|
||||
import {useCallback,useEffect,useRef,useState} from 'react';
|
||||
import {useCallback,useEffect,useMemo,useRef,useState} from 'react';
|
||||
import {defaultScene,parseScene,type SceneDocument} from './sceneDocument';
|
||||
import {SceneHistory} from './sceneHistory';
|
||||
import {readScene,saveScene} from './sceneStorage';
|
||||
import {roverSceneProfile} from './sceneStorage';
|
||||
let writes=Promise.resolve();
|
||||
const enqueue=(vehicle:string,doc:SceneDocument,write=saveScene)=>{const next=writes.catch(()=>{}).then(()=>write(vehicle,doc));writes=next;return next;};
|
||||
export type SceneDocumentProfile={defaults:()=>SceneDocument;read:(id:string)=>Promise<SceneDocument|null>;write:typeof saveScene;filename:string};
|
||||
type Write=(id:string,doc:SceneDocument)=>Promise<void>;
|
||||
const enqueue=(id:string,doc:SceneDocument,write:Write)=>{const next=writes.catch(()=>{}).then(()=>write(id,doc));writes=next;return next;};
|
||||
export type SceneDocumentProfile={defaults:()=>SceneDocument;read:(id:string)=>Promise<SceneDocument|null>;write:Write;filename:string};
|
||||
export function useSceneDocument(vehicle:string,profile?:SceneDocumentProfile){
|
||||
const defaults=profile?.defaults??defaultScene,read=profile?.read??readScene,write=profile?.write??saveScene;
|
||||
const storage=useMemo(()=>profile??{...roverSceneProfile(),defaults:defaultScene,filename:'rover-scene.json'},[profile]);
|
||||
const {defaults,read,write}=storage;
|
||||
const [document,setDocument]=useState(defaults),[ready,setReady]=useState(false),[revision,setRevision]=useState(0);
|
||||
const [saveState,setSaveState]=useState<'loading'|'saved'|'saving'|'error'>('loading'),[error,setError]=useState('');
|
||||
const latest=useRef({document,revision,vehicle,write});latest.current={document,revision,vehicle,write};
|
||||
const loaded=useRef(false),savedRevision=useRef(0),history=useRef(new SceneHistory(document));
|
||||
const pendingCamera=useRef<CameraState|null>(null);
|
||||
const savedRevision=useRef(0),history=useRef(new SceneHistory(document));
|
||||
const latest=useRef({document,revision,vehicle,write,ready});latest.current={document,revision,vehicle,write,ready};
|
||||
const publish=useCallback(()=>{setDocument(history.current.present);setRevision(v=>v+1);setSaveState('saving');},[]);
|
||||
const undo=useCallback(()=>{pendingCamera.current=null;if(history.current.undo())publish();},[publish]);
|
||||
const redo=useCallback(()=>{pendingCamera.current=null;if(history.current.redo())publish();},[publish]);
|
||||
const beginGesture=useCallback(()=>history.current.begin(),[]),endGesture=useCallback(()=>history.current.end(),[]);
|
||||
useEffect(()=>{let cancelled=false;read(vehicle).then(value=>{if(!cancelled){const doc=value??defaults();history.current.reset(doc);setDocument(doc);setSaveState('saved');}}).catch(()=>{if(!cancelled){setError('Не удалось прочитать сохранённую сцену. Изменения можно экспортировать в JSON.');setSaveState('error');}}).finally(()=>{if(!cancelled)setReady(true);});return()=>{cancelled=true;};},[vehicle,profile]);
|
||||
const update=useCallback((fn:(doc:SceneDocument)=>SceneDocument)=>{if(history.current.update(fn(history.current.present)))publish();},[publish]);
|
||||
const recordCamera=useCallback((camera:CameraState,commit=false)=>{pendingCamera.current=camera;if(commit){pendingCamera.current=null;update(doc=>JSON.stringify(doc.camera)===JSON.stringify(camera)?doc:{...doc,camera});}},[update]);
|
||||
const undo=useCallback(()=>{if(!loaded.current)return;pendingCamera.current=null;if(history.current.undo())publish();},[publish]);
|
||||
const redo=useCallback(()=>{if(!loaded.current)return;pendingCamera.current=null;if(history.current.redo())publish();},[publish]);
|
||||
const beginGesture=useCallback(()=>{if(loaded.current)history.current.begin();},[]),endGesture=useCallback(()=>history.current.end(),[]);
|
||||
useEffect(()=>{
|
||||
let cancelled=false;loaded.current=false;pendingCamera.current=null;savedRevision.current=0;
|
||||
setReady(false);setRevision(0);setSaveState('loading');setError('');
|
||||
read(vehicle).then(value=>{if(!cancelled){const doc=value??defaults();history.current.reset(doc);setDocument(doc);loaded.current=true;setReady(true);setSaveState('saved');}}).catch(e=>{if(!cancelled){setError(e instanceof Error?e.message:'Не удалось прочитать сохранённую сцену.');setSaveState('error');}});
|
||||
return()=>{cancelled=true;loaded.current=false;};
|
||||
},[vehicle,storage,read,defaults]);
|
||||
const update=useCallback((fn:(doc:SceneDocument)=>SceneDocument)=>{if(loaded.current&&history.current.update(fn(history.current.present)))publish();},[publish]);
|
||||
const recordCamera=useCallback((camera:CameraState,commit=false)=>{if(!loaded.current)return;pendingCamera.current=camera;if(commit){pendingCamera.current=null;update(doc=>JSON.stringify(doc.camera)===JSON.stringify(camera)?doc:{...doc,camera});}},[update]);
|
||||
useEffect(()=>{
|
||||
if(!ready||revision===0)return;
|
||||
let cancelled=false;const timer=setTimeout(()=>{enqueue(vehicle,document,write).then(()=>{savedRevision.current=revision;if(!cancelled)setSaveState('saved');}).catch(()=>{if(!cancelled){setSaveState('error');setError('Не удалось сохранить сцену на этом компьютере. Экспортируйте JSON, чтобы сохранить изменения.');}});},400);
|
||||
let cancelled=false;const timer=setTimeout(()=>{enqueue(vehicle,document,write).then(()=>{savedRevision.current=revision;if(!cancelled)setSaveState('saved');}).catch(e=>{if(!cancelled){setSaveState('error');setError(e instanceof Error?e.message:'Не удалось сохранить сцену. Экспортируйте JSON, чтобы сохранить изменения.');}});},400);
|
||||
return()=>{cancelled=true;clearTimeout(timer);};
|
||||
},[ready,revision,vehicle,document,write]);
|
||||
useEffect(()=>()=>{const v=latest.current;if(pendingCamera.current||v.revision>savedRevision.current)void enqueue(v.vehicle,pendingCamera.current?{...v.document,camera:pendingCamera.current}:v.document,v.write).catch(()=>{});},[]);
|
||||
const importDocument=async(file:File)=>{try{if(file.size>32_000_000)throw new Error('Файл сцены больше 32 МБ.');const next=parseScene(JSON.parse(await file.text()),defaults);pendingCamera.current=null;update(()=>next);}catch(e){setError(e instanceof Error?e.message:'Не удалось загрузить сцену.');}};
|
||||
const exportDocument=()=>{const blob=new Blob([JSON.stringify(pendingCamera.current?{...document,camera:pendingCamera.current}:document,null,2)],{type:'application/json'});const url=URL.createObjectURL(blob);const a=globalThis.document.createElement('a');a.href=url;a.download=profile?.filename??'rover-scene.json';a.click();setTimeout(()=>URL.revokeObjectURL(url),1000);};
|
||||
useEffect(()=>{
|
||||
const flush=()=>{const v=latest.current;if(v.ready&&(pendingCamera.current||v.revision>savedRevision.current))void enqueue(v.vehicle,pendingCamera.current?{...v.document,camera:pendingCamera.current}:v.document,v.write).catch(()=>{});};
|
||||
const hidden=()=>{if(globalThis.document.visibilityState==='hidden')flush();};
|
||||
window.addEventListener('pagehide',flush);globalThis.document.addEventListener('visibilitychange',hidden);
|
||||
return()=>{flush();window.removeEventListener('pagehide',flush);globalThis.document.removeEventListener('visibilitychange',hidden);};
|
||||
},[]);
|
||||
const importDocument=async(file:File)=>{try{if(!ready)throw new Error('Дождитесь загрузки профиля.');if(file.size>32_000_000)throw new Error('Файл сцены больше 32 МБ.');const next=parseScene(JSON.parse(await file.text()),defaults);pendingCamera.current=null;update(()=>next);}catch(e){setError(e instanceof Error?e.message:'Не удалось загрузить сцену.');}};
|
||||
const exportDocument=()=>{const blob=new Blob([JSON.stringify(pendingCamera.current?{...document,camera:pendingCamera.current}:document,null,2)],{type:'application/json'});const url=URL.createObjectURL(blob);const a=globalThis.document.createElement('a');a.href=url;a.download=storage.filename;a.click();setTimeout(()=>URL.revokeObjectURL(url),1000);};
|
||||
return {document,recordCamera,ready,saveState,error,setError,update,undo,redo,canUndo:history.current.canUndo,canRedo:history.current.canRedo,beginGesture,endGesture,importDocument,exportDocument};
|
||||
}
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {build} from 'esbuild';
|
||||
const b=await build({entryPoints:['src/core/roverScene/profileClient.ts'],bundle:true,write:false,platform:'node',format:'esm'});
|
||||
const {profileClient,legacyRecord}=await import('data:text/javascript;base64,'+Buffer.from(b.outputFiles[0].contents).toString('base64'));
|
||||
function server(){let value={revision:0,document:null},puts=0;return {get value(){return value;},get puts(){return puts;},fetch:async(url,options)=>{if(options.method==='PUT'){puts++;const body=JSON.parse(options.body);if(body.expected_revision!==value.revision)return new Response(JSON.stringify({detail:'conflict'}),{status:409});value={revision:value.revision+1,document:body.document};}return new Response(JSON.stringify(value));}};}
|
||||
test('server JSON wins over stale browser records and persists across fresh clients',async()=>{
|
||||
const s=server();globalThis.fetch=s.fetch;const a=profileClient('battery','a');
|
||||
assert.equal(await a.read(),null);assert.equal(s.puts,0);
|
||||
await a.write({materials:'white'});const b=profileClient('battery','a');
|
||||
assert.deepEqual(await b.read(async()=>{throw Error('must not read browser');}),{materials:'white'});
|
||||
assert.equal(s.puts,1);
|
||||
});
|
||||
test('legacy record migrates once, never on a failed server read',async()=>{
|
||||
const s=server();globalThis.fetch=s.fetch;
|
||||
assert.deepEqual(await profileClient('battery','a').read(async()=>({old:true})),{old:true});
|
||||
await profileClient('battery','a').read(async()=>({old:false}));assert.equal(s.puts,1);
|
||||
globalThis.fetch=async()=>new Response('unavailable',{status:503});let legacyRead=false;
|
||||
await assert.rejects(profileClient('battery','a').read(async()=>{legacyRead=true;return {};}));assert.equal(legacyRead,false);
|
||||
});
|
||||
test('stale independent clients cannot replace newer materials and writes are ordered',async()=>{
|
||||
const s=server();globalThis.fetch=s.fetch;const a=profileClient('battery','a'),b=profileClient('battery','a');await a.read();await b.read();
|
||||
await Promise.all([a.write({color:'white'}),a.write({color:'silver'})]);
|
||||
assert.equal(s.value.revision,2);assert.equal(s.value.document.color,'silver');
|
||||
await assert.rejects(b.write({color:'default'}),/conflict/);assert.equal(s.value.document.color,'silver');
|
||||
});
|
||||
test('unhydrated profiles never write defaults',async()=>{
|
||||
const s=server();globalThis.fetch=s.fetch;await assert.rejects(profileClient('battery','a').write({default:true}),/не загружен/);assert.equal(s.puts,0);
|
||||
});
|
||||
test('migration race accepts the winning durable document',async()=>{
|
||||
const s=server();globalThis.fetch=s.fetch;const winner=profileClient('battery','a');await winner.read();
|
||||
const result=await profileClient('battery','a').read(async()=>{await winner.write({restored:true});return {stale:true};});
|
||||
assert.deepEqual(result,{restored:true});
|
||||
});
|
||||
test('legacy lookup never creates an empty IndexedDB database',async()=>{
|
||||
globalThis.indexedDB={databases:async()=>[],open:()=>{throw Error('must not create');}};
|
||||
assert.equal(await legacyRecord('missioncore-battery-scenes','scenes','a'),null);
|
||||
});
|
||||
@@ -10,9 +10,11 @@ owner. Driving settings retain their existing modal. A separate workspace
|
||||
would hide the live scene and duplicate navigation; the admitted surface is an
|
||||
edit mode of the existing rover view, with no new product root.
|
||||
|
||||
The scene document belongs to vehicle + model revision, persists in IndexedDB
|
||||
on this operator computer, includes imported texture data, and can be exported
|
||||
or imported as JSON. Loading and persistence failures remain visible; closing
|
||||
The scene document belongs to its vehicle or battery and records the model
|
||||
revision. It persists in the canonical Core data directory as `meta.json`,
|
||||
including imported texture data, and can be exported or imported as JSON.
|
||||
Browser storage is only a read-only migration source (see the 2026-11-09
|
||||
refinement below). Loading and persistence failures remain visible; closing
|
||||
an inspector never waits for saving. This is appearance only, not a firmware,
|
||||
calibration or hardware profile. Editing pauses local drive input and prevents
|
||||
new drive input until exit; it never arms a vehicle.
|
||||
@@ -51,10 +53,12 @@ A synthetic checker texture was uploaded, rendered and retained with its custom
|
||||
material, name and assignment after a page reload. The texture was then removed
|
||||
and the enclosure's original material reassigned. Browser error/warning log was
|
||||
empty. No motor commands were sent; the canonical service remains on port 8000.
|
||||
The inherited renderer still reduces MSAA to one sample. Local scene storage is
|
||||
not cross-computer synchronization. Both bounds are recorded in MISSIONCOR-85.
|
||||
The inherited renderer still reduces MSAA to one sample. At that acceptance,
|
||||
scene storage was browser-local and not cross-computer synchronization. The
|
||||
browser-only persistence was superseded on 2026-11-09; the earlier bounds were
|
||||
recorded in MISSIONCOR-85.
|
||||
|
||||
Follow-up: the owner still saw the withdrawn gray preset after clearing browser
|
||||
Historical migration finding: the owner still saw the withdrawn gray preset after clearing browser
|
||||
cache. Changing defaults and using the reset in one browser did not migrate
|
||||
other saved IndexedDB scene documents. Added environmentVersion 2 and a narrow
|
||||
load migration: only the exact original neutral environment is replaced with
|
||||
@@ -69,11 +73,11 @@ custom environments, deliberate gray scenes, imports and already restored scenes
|
||||
Owner refinement, 2026-11-04: reusable environment profiles and SOC surfaces
|
||||
------------------------------------------------------------------------
|
||||
|
||||
The first Environment Inspector section is now Profiles. A shared local
|
||||
IndexedDB library (`missioncore-environment-profiles`) holds named environment
|
||||
snapshots, independently of a model. The immutable NodeDC preset is the initial
|
||||
The first Environment Inspector section is now Profiles. A shared Core JSON
|
||||
library holds named environment snapshots independently of a model. It replaces
|
||||
the original `missioncore-environment-profiles` IndexedDB library. The immutable NodeDC preset is the initial
|
||||
option. Save as creates a new identity; overwrite retains that identity and
|
||||
uses a transactional revision check. Duplicate names and stale overwrites are
|
||||
uses a revision check and an atomic file replacement. Duplicate names and stale overwrites are
|
||||
rejected. Library updates notify other mounted scene editors and browser tabs.
|
||||
Limits are 64 user profiles and 16 MB of encoded configuration including LUTs.
|
||||
|
||||
@@ -125,3 +129,47 @@ It selects the copy in the palette without assigning it to an object; creation
|
||||
is undoable and obeys the existing material-count and total texture limits.
|
||||
LevelButton owns compact geometry: text and padding scale together below
|
||||
64 × 24 px down to 32 × 12 px, including both contrasting fill text layers.
|
||||
|
||||
|
||||
Owner correction, 2026-11-09: durable Core JSON authority
|
||||
------------------------------------------------------
|
||||
|
||||
All rover/battery scene documents, materials and embedded textures, environment
|
||||
profiles, camera poses, editor layouts, battery appearance and viewport height
|
||||
belong to `data_dir/scene-profiles/<kind>/<sha256(ownerId)>/meta.json`. The
|
||||
canonical operator service currently uses `.runtime/mission-core` as data_dir.
|
||||
These files are durable configuration, excluded from cache/temporary retention.
|
||||
Battery and rover documents are isolated; the environment library is shared.
|
||||
This synchronizes browsers using the same Core, not unrelated Core installations.
|
||||
|
||||
GET/PUT `/api/v1/scene-profiles/{kind}?owner=…` uses the existing local-operator
|
||||
origin boundary. Each document envelope has schema, owner, kind, revision and
|
||||
updatedAt. A writer must supply the revision it read. Atomic replacement and a
|
||||
`meta.previous.json` backup protect the prior saved document; a stale tab gets a
|
||||
conflict instead of overwriting newer settings. Failed or corrupt reads never
|
||||
turn into an automatic default save. Texture-bearing documents retain the 32 MB
|
||||
bound. Ordered/debounced saves flush pending edits on close/pagehide.
|
||||
|
||||
Only an absent Core document may import a validated legacy IndexedDB/localStorage
|
||||
record. Existing browser records are never deleted, and an existing Core profile
|
||||
always wins. A server error does not fall back to browser storage. The old neutral
|
||||
environment migration remains a parser transformation; its historical browser
|
||||
backup is no longer the persistence authority. Import/export and editor Undo/Redo
|
||||
continue to use the same scene document.
|
||||
|
||||
Incident evidence: the Chrome origin IndexedDB inspected on 2026-11-09 was created
|
||||
at 13:48:26; the old full scene was absent. The exact deletion/recreation trigger
|
||||
was not established. Clear Cache's inspected settings excluded IndexedDB and
|
||||
localStorage; blaming that extension is not supported. Actual Nov 4 00:15 scene
|
||||
JSON restored the white enclosure, transparent side, black background and stored
|
||||
camera/layout. A retained Chrome localStorage record separately recovered the
|
||||
newer battery UI (90 px cards, 11/13 px text, 160% markings, 61×18 indicator).
|
||||
No more recent complete material/environment scene was found, so recovery is not
|
||||
a claim of an exact final Nov 4 afternoon state. Evidence and source hashes:
|
||||
`outputs/scene-profile-recovery-20261109/README.md`.
|
||||
|
||||
Validation: 1531 frontend tests, 6 Python persistence/API tests, TypeScript, Ruff
|
||||
and production build passed. Chrome reload and a separate browser loaded the same
|
||||
restored Core document. Changing the material-palette tile size produced the next
|
||||
JSON revision; Undo restored the entire recovered scene document byte-for-byte
|
||||
after JSON normalization. No hardware commands were used.
|
||||
|
||||
@@ -0,0 +1,146 @@
|
||||
"""Durable operator scene documents. Never part of telemetry/cache retention."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import fcntl
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from contextlib import contextmanager
|
||||
from datetime import UTC, datetime
|
||||
from pathlib import Path
|
||||
from threading import RLock
|
||||
from typing import Any
|
||||
|
||||
MAX_BYTES = 32_000_000
|
||||
KINDS = {
|
||||
"battery": "missioncore.battery-scene/v1",
|
||||
"rover": "missioncore.rover-scene/v1",
|
||||
"battery-ui": "missioncore.battery-ui/v1",
|
||||
"battery-view": "missioncore.battery-view/v1",
|
||||
"environments": "missioncore.environment-library/v1",
|
||||
}
|
||||
_lock = RLock()
|
||||
|
||||
|
||||
class ProfileConflict(ValueError):
|
||||
pass
|
||||
|
||||
|
||||
def validate_document(kind: str, document: Any) -> None:
|
||||
if kind not in KINDS or not isinstance(document, dict) or document.get("schema") != KINDS[kind]:
|
||||
raise ValueError("Неверный тип профиля.")
|
||||
if kind in ("battery", "rover"):
|
||||
if not all(
|
||||
isinstance(document.get(k), dict) for k in ("materials", "postFx", "assignments")
|
||||
):
|
||||
raise ValueError("Неполный документ сцены.")
|
||||
if not isinstance(document.get("model"), str) or len(document["materials"]) > 256:
|
||||
raise ValueError("Неверная модель или библиотека материалов.")
|
||||
elif kind == "battery-ui":
|
||||
if not all(isinstance(document.get(k), dict) for k in ("markings", "panels")):
|
||||
raise ValueError("Неполный профиль оформления батареи.")
|
||||
elif kind == "battery-view":
|
||||
height = document.get("height")
|
||||
if type(height) not in (int, float) or not 360 <= height <= 2160:
|
||||
raise ValueError("Неверная высота окна.")
|
||||
else:
|
||||
profiles = document.get("profiles")
|
||||
if not isinstance(profiles, list) or len(profiles) > 64:
|
||||
raise ValueError("Неверная библиотека окружений.")
|
||||
ids = []
|
||||
for profile in profiles:
|
||||
if (
|
||||
not isinstance(profile, dict)
|
||||
or profile.get("schema") != "missioncore.environment-profile/v1"
|
||||
):
|
||||
raise ValueError("Неверный профиль окружения.")
|
||||
pid = profile.get("id")
|
||||
if not isinstance(pid, str) or not pid.startswith("env/") or pid in ids:
|
||||
raise ValueError("Повторяющийся или неверный профиль окружения.")
|
||||
ids.append(pid)
|
||||
|
||||
|
||||
class SceneProfileStore:
|
||||
def __init__(self, root: Path):
|
||||
self.root = root
|
||||
|
||||
def path(self, kind: str, owner: str) -> Path:
|
||||
if kind not in KINDS or not owner or len(owner) > 512 or any(ord(c) < 32 for c in owner):
|
||||
raise ValueError("Неверный идентификатор профиля.")
|
||||
return self.root / kind / hashlib.sha256(owner.encode()).hexdigest() / "meta.json"
|
||||
|
||||
def read(self, kind: str, owner: str) -> dict:
|
||||
path = self.path(kind, owner)
|
||||
if not path.exists():
|
||||
return {"revision": 0, "document": None}
|
||||
value = json.loads(path.read_text())
|
||||
if (
|
||||
value.get("schema") != "missioncore.scene-profile-meta/v1"
|
||||
or value.get("kind") != kind
|
||||
or value.get("ownerId") != owner
|
||||
or type(value.get("revision")) is not int
|
||||
or value["revision"] < 1
|
||||
):
|
||||
raise ValueError("Повреждён файл профиля. Исходный файл сохранён.")
|
||||
validate_document(kind, value.get("document"))
|
||||
return value
|
||||
|
||||
@contextmanager
|
||||
def locked(self):
|
||||
with _lock:
|
||||
self.root.mkdir(parents=True, exist_ok=True)
|
||||
with (self.root / ".write.lock").open("a") as stream:
|
||||
fcntl.flock(stream, fcntl.LOCK_EX)
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
fcntl.flock(stream, fcntl.LOCK_UN)
|
||||
|
||||
@staticmethod
|
||||
def atomic(path: Path, data: bytes) -> None:
|
||||
temporary = path.with_name(path.name + ".tmp")
|
||||
try:
|
||||
with temporary.open("wb") as stream:
|
||||
stream.write(data)
|
||||
stream.flush()
|
||||
os.fsync(stream.fileno())
|
||||
os.replace(temporary, path)
|
||||
descriptor = os.open(path.parent, os.O_RDONLY)
|
||||
try:
|
||||
os.fsync(descriptor)
|
||||
finally:
|
||||
os.close(descriptor)
|
||||
finally:
|
||||
temporary.unlink(missing_ok=True)
|
||||
|
||||
def save(self, kind: str, owner: str, document: dict, expected_revision: int) -> dict:
|
||||
validate_document(kind, document)
|
||||
if type(expected_revision) is not int or expected_revision < 0:
|
||||
raise ValueError("Неверная ревизия профиля.")
|
||||
path = self.path(kind, owner)
|
||||
with self.locked():
|
||||
current = self.read(kind, owner)
|
||||
if current["revision"] != expected_revision:
|
||||
raise ProfileConflict(
|
||||
"Профиль изменён в другом окне. Откройте сцену заново; "
|
||||
"изменения можно экспортировать."
|
||||
)
|
||||
if current["document"] == document:
|
||||
return current
|
||||
value = {
|
||||
"schema": "missioncore.scene-profile-meta/v1",
|
||||
"kind": kind,
|
||||
"ownerId": owner,
|
||||
"revision": expected_revision + 1,
|
||||
"updatedAt": datetime.now(UTC).isoformat(),
|
||||
"document": document,
|
||||
}
|
||||
data = json.dumps(value, ensure_ascii=False, allow_nan=False, indent=2).encode()
|
||||
if len(data) > MAX_BYTES:
|
||||
raise ValueError("Профиль превышает 32 МБ.")
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
if path.exists():
|
||||
self.atomic(path.with_name("meta.previous.json"), path.read_bytes())
|
||||
self.atomic(path, data)
|
||||
return value
|
||||
@@ -235,6 +235,7 @@ from k1link.web.runtime_readiness import (
|
||||
BackgroundReconcilerReadiness,
|
||||
build_runtime_readiness,
|
||||
)
|
||||
from k1link.web.scene_profiles_api import build_scene_profiles_router
|
||||
from k1link.web.session_api import build_session_router
|
||||
from k1link.web.session_overview_api import build_session_overview_router
|
||||
from k1link.sessions.overview import SessionOverviewService
|
||||
@@ -2010,6 +2011,7 @@ app.include_router(
|
||||
service=simulation_project_service,
|
||||
)
|
||||
)
|
||||
app.include_router(build_scene_profiles_router(lambda: session_store.data_dir / "scene-profiles"))
|
||||
frontend_dist = REPOSITORY_ROOT / "apps" / "control-station" / "dist"
|
||||
try:
|
||||
app.include_router(build_ai_polygon_router(session_store.data_dir, OBSERVATORY_RECORDED_JOB_QUEUE))
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
"""Scene persistence on the canonical operator Core, not in browser storage."""
|
||||
|
||||
import json
|
||||
from collections.abc import Callable
|
||||
from pathlib import Path
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, Request, Response
|
||||
|
||||
from k1link.scene_profiles import MAX_BYTES, ProfileConflict, SceneProfileStore
|
||||
|
||||
from .fleet_api import local_operator
|
||||
|
||||
|
||||
def build_scene_profiles_router(root_provider: Callable[[], Path]) -> APIRouter:
|
||||
router = APIRouter(
|
||||
prefix="/api/v1/scene-profiles",
|
||||
tags=["scene-profiles"],
|
||||
dependencies=[Depends(local_operator)],
|
||||
)
|
||||
|
||||
@router.get("/{kind}")
|
||||
def read(kind: str, response: Response, owner: str = Query(min_length=1, max_length=512)):
|
||||
response.headers["Cache-Control"] = "no-store"
|
||||
try:
|
||||
return SceneProfileStore(root_provider()).read(kind, owner)
|
||||
except (OSError, ValueError) as error:
|
||||
raise HTTPException(
|
||||
500, "Не удалось прочитать файл профиля. Сохранённые настройки не изменены."
|
||||
) from error
|
||||
|
||||
@router.put("/{kind}")
|
||||
async def save(
|
||||
kind: str,
|
||||
request: Request,
|
||||
response: Response,
|
||||
owner: str = Query(min_length=1, max_length=512),
|
||||
):
|
||||
response.headers["Cache-Control"] = "no-store"
|
||||
data = bytearray()
|
||||
async for chunk in request.stream():
|
||||
data.extend(chunk)
|
||||
if len(data) > MAX_BYTES:
|
||||
raise HTTPException(413, "Профиль превышает 32 МБ.")
|
||||
try:
|
||||
body = json.loads(data)
|
||||
if not isinstance(body, dict) or set(body) != {"document", "expected_revision"}:
|
||||
raise ValueError("Неверный запрос сохранения.")
|
||||
return SceneProfileStore(root_provider()).save(
|
||||
kind, owner, body["document"], body["expected_revision"]
|
||||
)
|
||||
except ProfileConflict as error:
|
||||
raise HTTPException(409, str(error)) from error
|
||||
except (ValueError, TypeError, KeyError) as error:
|
||||
raise HTTPException(422, str(error)) from error
|
||||
except OSError as error:
|
||||
raise HTTPException(
|
||||
500, "Не удалось записать профиль. Предыдущая версия сохранена."
|
||||
) from error
|
||||
|
||||
return router
|
||||
@@ -0,0 +1,128 @@
|
||||
import json
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
from fastapi import FastAPI
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from k1link.scene_profiles import ProfileConflict, SceneProfileStore
|
||||
from k1link.web.scene_profiles_api import build_scene_profiles_router
|
||||
|
||||
|
||||
def scene(color="#ffffff"):
|
||||
return {
|
||||
"schema": "missioncore.battery-scene/v1",
|
||||
"model": "catl-r04/v1",
|
||||
"materials": {"case": {"color": color}},
|
||||
"postFx": {"grid": {"enabled": False}},
|
||||
"assignments": {},
|
||||
"camera": {"distance": 1.2},
|
||||
"editorLayout": {"windows": {}},
|
||||
}
|
||||
|
||||
|
||||
def test_persistent_roundtrip_and_backup(tmp_path):
|
||||
store = SceneProfileStore(tmp_path)
|
||||
assert store.read("battery", "device")["document"] is None
|
||||
assert not tmp_path.joinpath("battery").exists()
|
||||
first = store.save("battery", "device", scene(), 0)
|
||||
assert SceneProfileStore(tmp_path).read("battery", "device") == first
|
||||
second = store.save("battery", "device", scene("#aaaaaa"), 1)
|
||||
assert second["revision"] == 2
|
||||
assert (
|
||||
json.loads(store.path("battery", "device").with_name("meta.previous.json").read_text())
|
||||
== first
|
||||
)
|
||||
assert store.save("battery", "device", scene("#aaaaaa"), 2) == second
|
||||
with pytest.raises(ProfileConflict):
|
||||
store.save("battery", "device", scene(), 1)
|
||||
assert store.read("battery", "device") == second
|
||||
|
||||
|
||||
def test_corrupt_profile_never_becomes_defaults(tmp_path):
|
||||
store = SceneProfileStore(tmp_path)
|
||||
store.save("battery", "device", scene(), 0)
|
||||
path = store.path("battery", "device")
|
||||
path.write_text("broken file")
|
||||
with pytest.raises(ValueError):
|
||||
store.read("battery", "device")
|
||||
with pytest.raises(ValueError):
|
||||
store.save("battery", "device", scene(), 0)
|
||||
assert path.read_text() == "broken file"
|
||||
|
||||
|
||||
def test_atomic_failure_preserves_last_saved_document(tmp_path, monkeypatch):
|
||||
store = SceneProfileStore(tmp_path)
|
||||
first = store.save("battery", "a", scene(), 0)
|
||||
import k1link.scene_profiles as module
|
||||
|
||||
replace = module.os.replace
|
||||
|
||||
def fail(source, destination):
|
||||
if destination.name == "meta.json":
|
||||
raise OSError("disk full")
|
||||
return replace(source, destination)
|
||||
|
||||
monkeypatch.setattr(module.os, "replace", fail)
|
||||
with pytest.raises(OSError):
|
||||
store.save("battery", "a", scene("#111111"), 1)
|
||||
assert store.read("battery", "a") == first
|
||||
assert not list(tmp_path.rglob("*.tmp"))
|
||||
|
||||
|
||||
def test_competing_browsers_cannot_overwrite_each_other(tmp_path):
|
||||
store = SceneProfileStore(tmp_path)
|
||||
store.save("battery", "device", scene(), 0)
|
||||
|
||||
def writer(color):
|
||||
try:
|
||||
return store.save("battery", "device", scene(color), 1)["revision"]
|
||||
except ProfileConflict:
|
||||
return "conflict"
|
||||
|
||||
with ThreadPoolExecutor(max_workers=2) as pool:
|
||||
results = list(pool.map(writer, ["#aaaaaa", "#bbbbbb"]))
|
||||
assert sorted(map(str, results)) == ["2", "conflict"]
|
||||
|
||||
|
||||
def test_path_isolation_and_schema_checks(tmp_path):
|
||||
store = SceneProfileStore(tmp_path)
|
||||
store.save("battery", "../anything", scene(), 0)
|
||||
assert store.path("battery", "../anything").is_relative_to(tmp_path)
|
||||
assert store.read("battery", "other")["document"] is None
|
||||
assert store.read("rover", "../anything")["document"] is None
|
||||
with pytest.raises(ValueError):
|
||||
store.save("rover", "a", scene(), 0)
|
||||
with pytest.raises(ValueError):
|
||||
store.save("battery", "a", scene(), True)
|
||||
|
||||
|
||||
def client(root):
|
||||
app = FastAPI()
|
||||
app.state.fleet = SimpleNamespace()
|
||||
app.include_router(build_scene_profiles_router(lambda: root))
|
||||
return TestClient(app, base_url="http://127.0.0.1:8000", client=("127.0.0.1", 5555))
|
||||
|
||||
|
||||
def test_api_cross_browser_read_and_stale_write(tmp_path):
|
||||
a = client(tmp_path)
|
||||
b = client(tmp_path)
|
||||
url = "/api/v1/scene-profiles/battery?owner=device"
|
||||
assert a.get(url).json() == {"revision": 0, "document": None}
|
||||
saved = a.put(url, json={"document": scene(), "expected_revision": 0})
|
||||
assert saved.status_code == 200
|
||||
assert b.get(url).json() == saved.json()
|
||||
assert (
|
||||
b.put(url, json={"document": scene("#000000"), "expected_revision": 0}).status_code == 409
|
||||
)
|
||||
assert a.get(url).headers["cache-control"] == "no-store"
|
||||
assert (
|
||||
a.put(
|
||||
url,
|
||||
json={"document": scene(), "expected_revision": 1},
|
||||
headers={"Origin": "https://evil.invalid"},
|
||||
).status_code
|
||||
== 403
|
||||
)
|
||||
assert a.get(url, headers={"Sec-Fetch-Site": "cross-site"}).status_code == 403
|
||||
Reference in New Issue
Block a user