import type {SensorLiveFrame} from '../../../../packages/sensor-ui/src/contracts'; /** One abortable read at a time; no command path and no queued catch-up reads. */ export class TraceObserver { private closed=false;private busy=false;private abort:AbortController|undefined; private timer:ReturnType; constructor(private read:(signal:AbortSignal)=>Promise, private receive:(frame:SensorLiveFrame|null,now:number,roundTripMs:number)=>void, private tick:(now:number)=>void,private visible:()=>boolean=()=>!document.hidden, private clock:()=>number=()=>performance.now()){ this.timer=setInterval(()=>this.step(),500);this.step(); } private step(){ if(this.closed)return;this.tick(this.clock()); if(!this.visible()){this.abort?.abort();this.receive(null,this.clock(),0);return;} if(this.busy)return; this.busy=true;const abort=new AbortController();this.abort=abort;const started=this.clock(); const deadline=setTimeout(()=>abort.abort(),1200); Promise.resolve().then(()=>this.read(abort.signal)).then(frame=>{ if(!this.closed&&!abort.signal.aborted&&this.visible())this.receive(frame,this.clock(),this.clock()-started); }).catch(()=>{if(!this.closed)this.receive(null,this.clock(),0);}) .finally(()=>{clearTimeout(deadline);this.busy=false;if(this.abort===abort)this.abort=undefined;}); } close(){this.closed=true;clearInterval(this.timer);this.abort?.abort();} }