0)a[s[c]++]=o}return{counts:n,symbols:a,maxBits:i}}var cr=(()=>{let e=new Uint8Array(288);return e.fill(8,0,144),e.fill(9,144,256),e.fill(7,256,280),e.fill(8,280,288),Lt(e,288)})(),dr=(()=>{let e=new Uint8Array(32);return e.fill(5),Lt(e,32)})();class Cn{win=new Uint8Array(32768);winPos=0;feed(e,t=16777216){let n=0,i=0,s=0,r=(p)=>{while(s=e.length)throw Error("truncated deflate frame");i|=e[n++]<>>=p,s-=p,l},a=(p)=>{let l=0,h=0,v=0;for(let u=1;u<=p.maxBits;u++){l|=r(1);let g=p.counts[u];if(l-g{let l=c+p;if(l>t)throw Error("inflated frame exceeds limit");if(l<=o.length)return;let h=o.length;while(h{m(1),o[c++]=p,this.win[this.winPos]=p,this.winPos=this.winPos+1&32767};while(n0){if(n>=e.length&&s<3)break;let p=r(1),l=r(2);if(l===0){if(i=0,s=0,n+4>e.length)throw Error("truncated stored block");let h=e[n]|e[n+1]<<8,v=e[n+2]|e[n+3]<<8;if(n+=4,(h^65535)!==v)throw Error("invalid stored block length");if(n+h>e.length)throw Error("truncated stored payload");m(h);for(let u=0;u=e.length)break}else if(l===1||l===2){let h=cr,v=dr;if(l===2){let u=r(5)+257,g=r(5)+1,f=r(4)+4,w=new Uint8Array(19);for(let M=0;ML)throw Error("code length overflow");for(let V=0;VL)throw Error("code length overflow");A+=T}else if(M===18){let T=r(7)+11;if(A+T>L)throw Error("code length overflow");A+=T}else throw Error("invalid code length symbol")}h=Lt(P,u),v=Lt(P.subarray(u),g)}while(!0){let u=a(h);if(u<256)d(u);else if(u===256)break;else{let g=u-257;if(g>=Ui.length)throw Error("invalid length symbol");let f=Ui[g]+(Wi[g]?r(Wi[g]):0),w=a(v);if(w>=_i.length)throw Error("invalid distance symbol");let x=_i[w]+(zi[w]?r(zi[w]):0);m(f);let L=this.winPos-x&32767;for(let P=0;P{this.stateListeners.delete(e)}}onFrame(e){return this.frameListeners.add(e),()=>{this.frameListeners.delete(e)}}onBinary(e){return this.binaryListeners.add(e),()=>{this.binaryListeners.delete(e)}}rpc(e,t={},n=20000){return new Promise((i,s)=>{if(!this.ws||this.ws.readyState!==WebSocket.OPEN){s(Error("Not connected to hub"));return}let r=this.nextId++,a=window.setTimeout(()=>{this.pending.delete(r),s(Error(`RPC timeout: ${e}`))},n);this.pending.set(r,{resolve:i,reject:s,timer:a}),this.ws.send(JSON.stringify({id:r,m:e,p:t}))})}setState(e){this.state=e;for(let t of this.stateListeners)t(e,this.hello)}rejectAllPending(e){for(let[,t]of this.pending)window.clearTimeout(t.timer),t.reject(Error(e));this.pending.clear()}openSocket(){if(this.closed)return;this.inflater=null;let t=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/ws?data=1&enc=json&z=deflate`,n=new WebSocket(t);n.binaryType="arraybuffer",this.ws=n;let i=(s)=>{let r;try{r=JSON.parse(s)}catch{return}if(r.t==="hub.restarting")this.restarting={reason:String(r.reason??""),build:String(r.build??""),text:String(r.text??""),at:Date.now()};if(r.t==="hello")this.restarting=null,this.hello=r,this.features=new Set(this.hello.features??[]),this.inflater=this.hello.z==="deflate"?new Cn:null,this.reconnectDelay=500,this.setState("connected");else if(r.t==="reply"&&typeof r.id==="number"){let a=this.pending.get(r.id);if(a)if(this.pending.delete(r.id),window.clearTimeout(a.timer),r.ok)a.resolve(r.result??{});else{let o=r.error,c=typeof o==="string"?o:o&&typeof o==="object"&&("message"in o)?String(o.message):"Request failed",m=typeof r.errorCode==="string"?r.errorCode:void 0,d=typeof r.machine==="string"?r.machine:void 0,p=typeof r.thread==="string"?r.thread:void 0;a.reject(new St(c,{code:m,machine:d,thread:p}))}return}for(let a of this.frameListeners)a(r)};n.addEventListener("message",(s)=>{if(s.data instanceof ArrayBuffer){if(this.inflater){let r;try{r=this.inflater.feed(new Uint8Array(s.data))}catch{n.close();return}if(r.length>0&&r[0]===123)i(this.textDecoder.decode(r));else{let a=r.buffer.slice(r.byteOffset,r.byteOffset+r.byteLength);for(let o of this.binaryListeners)o(a)}return}for(let r of this.binaryListeners)r(s.data);return}if(typeof s.data!=="string")return;i(s.data)}),n.addEventListener("close",(s)=>{if(this.ws===n)this.ws=null;if(this.rejectAllPending("Connection closed"),this.closed)return;if(s.code===4001||s.code===4401||s.code===1008){this.handleRevoked();return}this.probeSessionOrReconnect()}),n.addEventListener("error",()=>{})}async probeSessionOrReconnect(){try{let t=await fetch("/",{method:"GET",credentials:"same-origin",cache:"no-store"});if(t.status===401||t.status===403){this.handleRevoked();return}if(t.ok){if((await t.text()).includes('id="pair-root"')){this.handleRevoked();return}}}catch{}this.setState("reconnecting");let e=this.reconnectDelay;this.reconnectDelay=Math.min(8000,Math.round(this.reconnectDelay*1.6)),this.reconnectTimer=window.setTimeout(()=>{this.reconnectTimer=null,this.openSocket()},e)}handleRevoked(){this.closed=!0,this.setState("revoked"),window.location.replace("/")}}var pr=new TextDecoder;function qi(e){return e.length>7&&e[0]>=160&&e[0]<=183&&e[1]===1&&e[2]===100&&e[3]===112&&e[4]===108&&e[5]===111&&e[6]===116}function Ki(e){let t=0,n=0;function i(a){if(a<=23)return a;if(a===24){if(t>=e.length)return null;return e[t++]}if(a===25){if(t+2>e.length)return null;let o=e[t]<<8|e[t+1];return t+=2,o}if(a===26){if(t+4>e.length)return null;let o=(e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3])>>>0;return t+=4,o}return null}function s(a){if(n++,a>32||n>400000||t>=e.length)return null;let o=e[t++],c=o>>5,m=i(o&31);if(m===null)return null;switch(c){case 0:return m;case 1:return-1-m;case 2:{if(t+m>e.length)return null;let d=e.subarray(t,t+m);return t+=m,d}case 3:{if(t+m>e.length)return null;let d=pr.decode(e.subarray(t,t+m));return t+=m,d}case 4:{if(m>e.length)return null;let d=Array(m);for(let p=0;p=this.b.length)return this.ok=!1,0;let n=this.b[this.i++],i=7*t;if(i>=28&&(n&240)!==0)return this.ok=!1,0;if(e=(e|(n&127)<>>0,n<128)return e}return this.ok=!1,0}nextI32(){let e=this.nextU32();return e>>>1^-(e&1)}}function Yi(e){let t=0xcbf29ce484222325n,n=0x100000001b3n,i=0xffffffffffffffffn;for(let s=0;stypeof e[u]==="number"?e[u]:g,n=t("l",0),i=t("c",0),s=t("a",255)/255,r=t("m",1),a=t("w",0),o=a/2,c=r===0&&a!==0,m=e.d instanceof Uint8Array?e.d:new Uint8Array(0),d=new Ji(m),p=[],l=[],h=0,v=0;while(d.more()){let u=d.nextU32(),g=p.length,f=1/0,w=1/0,x=-1/0,L=-1/0;if(r===2)h=h+d.nextI32()|0,v=v+d.nextI32()|0,p.push(h,v),f=x=h,w=L=v;else{let A=Math.min(d.nextU32(),1048576);for(let M=0;Mx)x=h;if(vL)L=v}}let P=(p.length-g)/2;if(P>0){let A=r===2||P===1?2:r===0?0:1,M=r===0?0:o;l.push({info:u,x0:f-M,y0:w-M,x1:x+M,y1:L+M,at:g,n:P,kind:A})}}return{layer:n,color:i,alpha:s,mode:r,r:o,own:c,pts:new Float32Array(p),pieces:l}}function Xi(e,t,n){let i=(a)=>Array.isArray(a)&&a.length>=4?[Number(a[0])||0,Number(a[1])||0,Number(a[2])||0,Number(a[3])||0]:[0,0,0,0],s=Array.isArray(e.cs)?e.cs:[],r=[];for(let a=0;a=0&&o0){n.delete(o.h),n.set(o.h,c);while(n.size>1024){let m=n.keys().next().value;if(m!==void 0)n.delete(m);else break}}}}return{key:typeof e.key==="string"?e.key:"",fam:typeof e.fam==="string"?e.fam:"",base:typeof e.base==="string"?e.base:"",box:i(e.box),edge:i(e.edge),thick:typeof e.thick==="number"?e.thick:1600,note:typeof e.note==="string"?e.note:"",warn:typeof e.warn==="number"?e.warn!==0:!1,chunks:r}}function Zi(e,t,n,i=!0){if(n.width<=0||n.height<=0||n.naturalWidth<=0||n.naturalHeight<=0)return null;let s=Math.min(n.width/n.naturalWidth,n.height/n.naturalHeight),r=n.naturalWidth*s,a=n.naturalHeight*s,o=n.left+(n.width-r)/2,c=i?n.top:n.top+(n.height-a)/2,m=(e-o)/r,d=(t-c)/a;if(m<0||m>1||d<0||d>1)return null;return{x:Math.max(0,Math.min(1000,Math.round(m*1000))),y:Math.max(0,Math.min(1000,Math.round(d*1000)))}}var Qi=[["Enter","Enter"],["Tab","Tab"],["Bksp","Backspace"],["Esc","Escape"],["↑","ArrowUp"],["↓","ArrowDown"],["←","ArrowLeft"],["→","ArrowRight"]];function es(e){let t=e.trim();if(!t)return"";if(/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(t))return t;return`https://${t}`}class kn{tail=Promise.resolve();enqueue(e){let t=this.tail.then(e,e);return this.tail=t.catch(()=>{}),t}}function ts(e,t,n){let i=!0,s=!1,r=!1,a="",o=!1,c=!1,m=-1,d=null,p=new kn,l=document.createElement("div");l.className="bp-pane bp-browser-pane",l.setAttribute("data-testid","pane-browser");let h=document.createElement("div");h.className="bp-pane-bar bp-browser-nav";function v(X,ce,E){let k=document.createElement("button");if(k.type="button",k.className="bp-v-btn",k.textContent=X,k.setAttribute("data-testid",ce),E)k.title=E;return k}let u=v("←","browser-back","Back"),g=v("→","browser-forward","Forward"),f=v("↻","browser-reload","Reload"),w=document.createElement("form");w.className="bp-browser-url-form";let x=document.createElement("input");x.type="text",x.className="bp-browser-input",x.placeholder="https://…",x.autocomplete="off",x.spellcheck=!1,x.setAttribute("data-testid","browser-url");let L=v("Go","browser-go","Navigate");L.type="submit",w.append(x,L);let P=v("Take over","browser-takeover");P.classList.add("is-primary"),h.append(u,g,f,w,P);let A=document.createElement("div");A.className="bp-browser-drive-bar",A.hidden=!0;let M=document.createElement("div");M.className="bp-browser-keys-row";let T=document.createElement("input");T.type="text",T.className="bp-browser-input",T.placeholder="Type text or press Enter/Tab/Arrows…",T.autocomplete="off",T.spellcheck=!1,T.setAttribute("data-testid","browser-keys");let R=v("Send","browser-type-send");M.append(T,R);let V=document.createElement("div");V.className="bp-browser-quick-keys";for(let[X,ce]of Qi){let E=v(X,`browser-key-${ce}`);E.addEventListener("click",()=>he("press",{key:ce})),V.append(E)}A.append(M,V);let H=document.createElement("div");H.className="bp-browser-err",H.setAttribute("data-testid","browser-error"),H.hidden=!0;let ae=document.createElement("div");ae.className="bp-browser-stage",ae.setAttribute("data-testid","browser-stage");let ue=document.createElement("img");ue.className="bp-browser-img",ue.alt="Hub browser screen",ue.draggable=!1,ue.hidden=!0,ue.setAttribute("data-testid","browser-frame");let oe=document.createElement("div");oe.className="bp-pane-empty",oe.setAttribute("data-testid","browser-empty"),oe.textContent="Loading browser screen…",ae.append(ue,oe);let we=document.createElement("div");we.className="bp-browser-hint",we.textContent="You have the page: click to tap, scroll to wheel, type in the key box. Hand it back when done.",we.hidden=!0,l.append(h,A,H,ae,we),e.replaceChildren(l);function Le(X){H.textContent=X,H.hidden=!X}function Me(){A.hidden=!s,we.hidden=!s,P.textContent=s?"Hand back":"Take over",P.setAttribute("data-testid",s?"browser-handback":"browser-takeover"),P.classList.toggle("is-on",s),ue.classList.toggle("is-driving",s)}function he(X,ce={},E){p.enqueue(async()=>{if(!i)return;Le("");try{if(await t.hub.rpc("browser",{thread:n,op:X,...ce}),!i)return;E?.(),le()}catch(k){if(!i)return;Le(k instanceof Error?k.message:String(k))}})}function be(X){he("toolbar",{command:X},()=>{s=!0,Me()})}u.addEventListener("click",()=>be("back")),g.addEventListener("click",()=>be("forward")),f.addEventListener("click",()=>be("reload")),w.addEventListener("submit",(X)=>{X.preventDefault();let ce=es(x.value);if(!ce)return;if(x.value=ce,!s)he("takeover",{},()=>{s=!0,Me()});he("navigate",{url:ce},()=>{s=!0,Me()})}),P.addEventListener("click",()=>{if(s)he("handback",{},()=>{s=!1,Me()});else he("takeover",{},()=>{s=!0,Me(),T.focus()})});function I(){let X=T.value;if(!X)return;T.value="",he("type",{text:X})}R.addEventListener("click",I),T.addEventListener("keydown",(X)=>{if(!s)return;if(X.key==="Enter"){if(X.preventDefault(),T.value)I();he("press",{key:"Enter"});return}if(X.key==="Tab"||X.key==="Escape"||X.key==="ArrowUp"||X.key==="ArrowDown"||X.key==="ArrowLeft"||X.key==="ArrowRight"||X.key==="Backspace"&&T.value==="")X.preventDefault(),he("press",{key:X.key})}),ue.addEventListener("click",(X)=>{if(!s||!r)return;let ce=ue.getBoundingClientRect(),E=Zi(X.clientX,X.clientY,{left:ce.left,top:ce.top,width:ce.width,height:ce.height,naturalWidth:ue.naturalWidth,naturalHeight:ue.naturalHeight});if(!E)return;he("click",E)}),ue.addEventListener("wheel",(X)=>{if(!s||!r)return;X.preventDefault();let ce=Math.round(X.deltaX),E=Math.round(X.deltaY);if(ce===0&&E===0)return;he("scroll",{dx:ce,dy:E})},{passive:!1});async function le(){if(!i)return;if(o){c=!0;return}o=!0;try{do{c=!1,d=new AbortController;let X=await fetch(`/bots/${encodeURIComponent(n)}/screen.jpg`,{credentials:"same-origin",cache:"no-store",signal:d.signal});if(!i)return;if(X.ok){let ce=await X.blob();if(!i)return;let E=URL.createObjectURL(ce),k=a;if(a=E,ue.src=E,ue.hidden=!1,oe.hidden=!0,r=!0,k)URL.revokeObjectURL(k)}else if(!r)ue.hidden=!0,oe.hidden=!1,oe.textContent="No browser page yet. An agent opens one when it needs the web."}while(i&&c)}catch{if(!i)return;if(!r)ue.hidden=!0,oe.hidden=!1,oe.textContent="No browser page yet. An agent opens one when it needs the web."}finally{d=null,o=!1}}let ne=t.hub.onFrame((X)=>{if(!i)return;if(X.t==="shot"&&X.bot===n){if(typeof X.n==="number"){if(X.n===m)return;m=X.n}le()}});return le(),{destroy(){if(i=!1,ne(),d?.abort(),a)URL.revokeObjectURL(a),a=""}}}function z(e,t,n){let i=document.createElement(e);if(t)i.className=t;if(n!==void 0)i.textContent=n;return i}function zt(e){if(!Number.isFinite(e)||e<0)return"";if(e<1024)return`${e} B`;if(e<1048576)return`${Math.round(e/1024)} KB`;return`${(e/1048576).toFixed(1)} MB`}function is(e){let t=e.lastIndexOf(".");return t>=0?e.slice(t+1).toLowerCase():""}function ur(e){return["png","jpg","jpeg","gif","webp","svg","bmp","ico"].includes(e)}function ns(e){return["txt","md","markdown","json","toml","yaml","yml","xml","csv","tsv","rs","ts","tsx","js","mjs","cjs","jsx","css","html","htm","sh","bash","py","c","h","cc","cpp","hpp","go","java","kt","swift","rb","lua","sql","ini","cfg","conf","env","gitignore","lock","log","gbr","gtl","gbl","gts","gbs","gto","gbo","gm1","drl","pos","net","kicad_pro","kicad_prl","kicad_dru","kicad_sym","kicad_mod","kicad_wks"].includes(e)}function hr(e){let t=is(e);if(t==="kicad_pcb")return"board";if(t==="kicad_sch")return"schematic";if(t==="step"||t==="stp"||t==="glb")return"mech";return null}function ss(e,t,n,i){let s=!0,r="",a="",o=z("div","bp-pane bp-files-pane");o.setAttribute("data-testid","pane-files");let c=z("div","bp-pane-bar"),m=z("div","bp-files-crumbs"),d=z("button","bp-v-btn","Refresh");d.type="button",d.addEventListener("click",()=>void g(r)),c.append(m,d);let p=z("div","bp-files-split"),l=z("div","bp-files-list");l.setAttribute("data-testid","files-list");let h=z("div","bp-files-preview");h.setAttribute("data-testid","files-preview"),h.append(z("div","bp-pane-empty","Select a file to preview")),p.append(l,h),o.append(c,p),e.replaceChildren(o);function v(){m.replaceChildren();let f=z("button","bp-crumb-btn","project");if(f.type="button",f.addEventListener("click",()=>void g("")),m.append(f),!r)return;let w=r.split("/").filter(Boolean),x="";for(let L of w){x=x?`${x}/${L}`:L;let P=x;m.append(z("span","bp-vh-sep","/"));let A=z("button","bp-crumb-btn",L);A.type="button",A.addEventListener("click",()=>void g(P)),m.append(A)}}async function u(f,w,x){a=f,h.replaceChildren();let L=z("div","bp-files-prev-head");L.append(z("span","bp-files-prev-name",f));let P=z("div","bp-files-prev-acts"),A=hr(w);if(A){let V=z("button","bp-v-btn is-primary",`Open in ${A}`);V.type="button",V.setAttribute("data-testid","files-open-viewer"),V.addEventListener("click",()=>i(A,f)),P.append(V)}let M=`/files/get?thread=${encodeURIComponent(n)}&path=${encodeURIComponent(f)}`,T=z("a","bp-v-btn","Download");T.href=M,T.download=w,P.append(T),L.append(P),h.append(L);let R=is(w);if(ur(R)){let V=z("div","bp-files-img-wrap"),H=document.createElement("img");H.className="bp-files-img",H.alt=w,H.src=M,V.append(H),h.append(V);return}if(x>524288&&!ns(R)){h.append(z("div","bp-pane-empty",`Binary file (${zt(x)}). Use Download to save.`));return}if(ns(R)||x<=65536){let V=z("div","bp-pane-empty","Loading…");h.append(V);try{let H=await fetch(M,{credentials:"same-origin"});if(!s||a!==f)return;if(!H.ok){V.textContent=`Could not load file (${H.status})`;return}if((H.headers.get("content-type")||"").startsWith("image/")){V.remove();let ne=document.createElement("img");ne.className="bp-files-img",ne.alt=w,ne.src=M,h.append(ne);return}let ue=262144,oe=[],we=0,Le=!1;if(H.body){let ne=H.body.getReader();try{while(!0){let{done:X,value:ce}=await ne.read();if(X||!ce)break;if(we+ce.byteLength>ue){let E=ue-we;if(E>0)oe.push(ce.subarray(0,E)),we+=E;Le=!0,await ne.cancel();break}oe.push(ce),we+=ce.byteLength}}finally{ne.releaseLock()}}if(!s||a!==f)return;let Me=new Uint8Array(we),he=0;for(let ne of oe)Me.set(ne,he),he+=ne.byteLength;let be=!1;for(let ne=0;neL.dir===P.dir?L.name.localeCompare(P.name):L.dir?-1:1),l.replaceChildren(),f){let L=z("button","bp-file-row is-dir");L.type="button",L.append(z("span","bp-file-icon","↰"),z("span","bp-file-name",".."));let P=f.includes("/")?f.slice(0,f.lastIndexOf("/")):"";L.addEventListener("click",()=>void g(P)),l.append(L)}if(x.length===0){l.append(z("div","bp-pane-empty","Empty folder"));return}for(let L of x){let P=f?`${f}/${L.name}`:L.name,A=z("button","bp-file-row"+(L.dir?" is-dir":"")+(P===a?" is-sel":""));A.type="button",A.setAttribute("data-testid",`file-row-${L.name}`),A.append(z("span","bp-file-icon",L.dir?"▸":"·"),z("span","bp-file-name",L.name),z("span","bp-file-size",L.dir?"":zt(L.size))),A.addEventListener("click",()=>{if(L.dir)g(P);else l.querySelectorAll(".bp-file-row.is-sel").forEach((M)=>M.classList.remove("is-sel")),A.classList.add("is-sel"),u(P,L.name,L.size)}),l.append(A)}}catch(w){if(!s)return;l.replaceChildren(z("div","bp-pane-empty",w instanceof Error?w.message:String(w)))}}return g(""),{destroy(){s=!1}}}function rs(e,t,n){let i=!0,s=z("div","bp-pane bp-diff-pane");s.setAttribute("data-testid","pane-diff");let r=z("div","bp-pane-bar"),a=z("span","bp-diff-summary","Loading diff…"),o=z("button","bp-v-btn","Refresh");o.type="button",o.addEventListener("click",()=>void m()),r.append(a,o);let c=z("div","bp-diff-body");c.setAttribute("data-testid","diff-body"),s.append(r,c),e.replaceChildren(s);async function m(){a.textContent="Loading diff…",c.replaceChildren();try{let d=await t.hub.rpc("viewer.diff",{thread:n});if(!i)return;if(d?.nogit){a.textContent="Not a git repository",c.append(z("div","bp-pane-empty","This project is not a git repository."));return}let p=typeof d?.diff==="string"?d.diff:"";if(!p.trim()){a.textContent="Clean working tree",c.append(z("div","bp-pane-empty","No uncommitted changes."));return}let l=p.split(`
+`),h=0,v=0,u=0,g=document.createDocumentFragment(),f=z("div","bp-diff-file");for(let w of l){if(w.startsWith("diff --git ")){if(f.childNodes.length>0)g.append(f);f=z("div","bp-diff-file"),h++;let x=w.match(/ b\/(.+)$/);f.append(z("div","bp-diff-file-head",x?x[1]:w));continue}if(w.startsWith("index ")||w.startsWith("--- ")||w.startsWith("+++ "))f.append(z("div","bp-diff-line is-meta",w));else if(w.startsWith("@@"))f.append(z("div","bp-diff-line is-hunk",w));else if(w.startsWith("+"))v++,f.append(z("div","bp-diff-line is-add",w));else if(w.startsWith("-"))u++,f.append(z("div","bp-diff-line is-del",w));else f.append(z("div","bp-diff-line",w))}if(f.childNodes.length>0)g.append(f);a.textContent=`${h||1} file${h===1?"":"s"} · +${v} -${u}`,c.append(g)}catch(d){if(!i)return;a.textContent="Diff unavailable",c.append(z("div","bp-pane-empty",d instanceof Error?d.message:String(d)))}}return m(),{destroy(){i=!1}}}function as(e,t,n){let i=!0,s="checks",r=z("div","bp-pane bp-review-pane");r.setAttribute("data-testid","pane-review");let a=z("div","bp-pane-bar"),o=z("div","bp-review-tabs"),c=z("button","bp-v-btn is-on","Checks"),m=z("button","bp-v-btn","BOM"),d=z("button","bp-v-btn","Comments");c.type=m.type=d.type="button",o.append(c,m,d);let p=z("button","bp-v-btn","Refresh");p.type="button",p.addEventListener("click",()=>void u()),a.append(o,p);let l=z("div","bp-review-body");l.setAttribute("data-testid","review-body"),r.append(a,l),e.replaceChildren(r);function h(g){s=g,c.classList.toggle("is-on",s==="checks"),m.classList.toggle("is-on",s==="bom"),d.classList.toggle("is-on",s==="comments"),u()}c.addEventListener("click",()=>h("checks")),m.addEventListener("click",()=>h("bom")),d.addEventListener("click",()=>h("comments"));function v(g){let f=z("div","bp-review-md"),w=g.split(`
+`),x=0;while(x{M.preventDefault();let T=P.value.trim();if(!T)return;A.disabled=!0,t.hub.rpc("review.comment",{thread:n,text:T}).then(()=>{P.value="",A.disabled=!1,u()},()=>{A.disabled=!1})}),l.append(L),x.length===0){l.append(z("div","bp-pane-empty","No review comments yet."));return}for(let M of x){let T=z("div","bp-review-comment"+(M.resolved?" is-resolved":"")),R=[M.by||"review",M.file,M.layer,M.item].filter(Boolean).join(" · ");T.append(z("div","bp-review-comment-meta",R),z("div","bp-review-comment-text",M.text)),l.append(T)}return}let g=await t.hub.rpc("review.page",{thread:n,page:s});if(!i)return;let f=g?.report||{};if(l.replaceChildren(),f.line||f.gate){let w=z("div","bp-review-gate",[f.gate,f.line].filter(Boolean).join(" · "));l.append(w)}if(f.err)l.append(z("div","bp-review-err",f.err));if(Array.isArray(f.tasks)&&f.tasks.length>0){let w=z("div","bp-review-tasks");f.tasks.forEach((x,L)=>{let P=z("label","bp-review-task"),A=document.createElement("input");A.type="checkbox",A.checked=!!(x.done??x.checked);let M=typeof x.index==="number"?x.index:L;A.addEventListener("change",()=>{t.hub.rpc("review.tick",{thread:n,index:M}).then(()=>void u(),()=>{})}),P.append(A,z("span",void 0,x.text||x.label||`Item ${L+1}`)),w.append(P)}),l.append(w)}if(f.md&&f.md.trim())l.append(v(f.md));else if(!f.err&&(!f.tasks||f.tasks.length===0))l.append(z("div","bp-pane-empty",`No ${s==="bom"?"BOM":"design checks"} report available.`))}catch(g){if(!i)return;l.replaceChildren(z("div","bp-pane-empty",g instanceof Error?g.message:String(g)))}}return u(),{destroy(){i=!1}}}function os(e,t){let n=e>>>16&255,i=e>>>8&255,s=e&255;return t>=0.999?`rgb(${n},${i},${s})`:`rgba(${n},${i},${s},${t.toFixed(3)})`}class An{canvas;ctx;frame=null;masks={off:0,dim:0,lift:255};highlights=new Set;lightTheme=!1;cx=0;cy=0;scale=0.0001;fittedKey="";fitW=0;fitH=0;userMoved=!1;dirty=!1;rafId=0;pointers=new Map;dragStart=null;pinchStart=null;resizeObs;cbs;constructor(e,t={}){this.cbs=t,this.canvas=document.createElement("canvas"),this.canvas.className="bp-viewer-canvas",this.canvas.style.width="100%",this.canvas.style.height="100%",this.canvas.style.display="block",this.canvas.style.touchAction="none",e.appendChild(this.canvas);let n=this.canvas.getContext("2d");if(!n)throw Error("Canvas2D unavailable");this.ctx=n,this.resizeObs=new ResizeObserver(()=>this.scheduleDraw()),this.resizeObs.observe(this.canvas),this.canvas.addEventListener("pointerdown",this.onPointerDown),this.canvas.addEventListener("pointermove",this.onPointerMove),this.canvas.addEventListener("pointerup",this.onPointerUp),this.canvas.addEventListener("pointercancel",this.onPointerUp),this.canvas.addEventListener("wheel",this.onWheel,{passive:!1}),this.canvas.addEventListener("dblclick",this.onDblClick)}setTheme(e){if(this.lightTheme!==e)this.lightTheme=e,this.scheduleDraw()}setFrame(e){if(this.frame=e,e&&e.key!==this.fittedKey)this.fittedKey=e.key,this.fit();else this.scheduleDraw()}setLayers(e){this.masks=e,this.scheduleDraw()}setHighlights(e){this.highlights.clear();for(let[t,n]of e)this.highlights.add(`${t}:${n}`);this.scheduleDraw()}presentMask(){if(!this.frame)return 0;let e=0;for(let t of this.frame.chunks)if(t.layer<32)e=(e|1<>>0;return e>>>0}presentColors(){let e=new Map;if(!this.frame)return e;for(let t of this.frame.chunks)if(!e.has(t.layer))e.set(t.layer,t.color);return e}applyFit(e,t){if(!this.frame||e<10||t<10)return;let n=this.frame.box,i=Math.max(n[2]-n[0],1000),s=Math.max(n[3]-n[1],1000);this.cx=(n[0]+n[2])*0.5,this.cy=(n[1]+n[3])*0.5,this.scale=Math.min(e/i,t/s)*0.92,this.fitW=e,this.fitH=t,this.userMoved=!1}fit(){if(!this.frame)return;this.userMoved=!1,this.fitW=0,this.fitH=0;let e=this.canvas.getBoundingClientRect();if(e.width>=10&&e.height>=10)this.applyFit(e.width,e.height);this.scheduleDraw()}zoomToBoxMm(e){let t=e[0]*1000,n=e[1]*1000,i=e[2]*1000,s=e[3]*1000,r=Math.max(i-t,1000),a=Math.max(s-n,1000),o=this.canvas.getBoundingClientRect(),c=Math.max(o.width,200),m=Math.max(o.height,200);this.cx=(t+i)*0.5,this.cy=(n+s)*0.5,this.scale=Math.min(c/r,m/a)*0.85,this.userMoved=!0,this.scheduleDraw()}scheduleDraw(){if(this.dirty)return;this.dirty=!0,this.rafId=requestAnimationFrame(()=>{this.dirty=!1,this.rafId=0,this.draw()})}draw(){let e=this.canvas.getBoundingClientRect(),t=Math.max(1,Math.round(e.width)),n=Math.max(1,Math.round(e.height)),i=Math.min(window.devicePixelRatio||1,2),s=Math.round(t*i),r=Math.round(n*i);if(this.canvas.width!==s||this.canvas.height!==r)this.canvas.width=s,this.canvas.height=r;let a=this.ctx;a.setTransform(i,0,0,i,0,0),a.fillStyle=this.lightTheme?"#f5f4ef":"#08090b",a.fillRect(0,0,t,n);let o=this.frame;if(!o)return;if(!this.userMoved&&t>=10&&n>=10&&(Math.abs(this.fitW-t)>2||Math.abs(this.fitH-n)>2))this.applyFit(t,n);let c=t*0.5,m=n*0.5,d=this.scale,p=this.cx,l=this.cy,h=p-c/d,v=p+c/d,u=l-m/d,g=l+m/d,{off:f,dim:w,lift:x}=this.masks,L=[],P=[];for(let M=0;M>>T&1)===1)continue;if(T===x)P.push(M);else L.push(M)}let A=L.concat(P);a.lineCap="round",a.lineJoin="round";for(let M=0;M>>R.layer&1)===1,H=R.alpha*(V?0.25:1);if(H<=0.01)continue;this.drawChunk(a,R,H,h,u,v,g,p,l,d,c,m)}if(this.highlights.size>0){a.fillStyle=this.lightTheme?"rgba(245,244,239,0.72)":"rgba(8,9,11,0.72)",a.fillRect(0,0,t,n);let M=this.lightTheme?"rgba(27,29,33,0.77)":"rgba(217,221,228,0.77)";for(let T=0;Tr||g.y1a)continue;if(g.n<3)continue;let f=(l[g.at]-o)*m+d,w=(l[g.at+1]-c)*m+p;e.moveTo(f,w);for(let x=1;x0)e.fill()}else if(t.mode===2){let v=Math.max(0.75,t.r*m);e.fillStyle=h,e.beginPath();let u=0;for(let g=0;gr||f.y1a)continue;let w=(l[f.at]-o)*m+d,x=(l[f.at+1]-c)*m+p;e.moveTo(w+v,x),e.arc(w,x,v,0,Math.PI*2),u++}if(u>0)e.fill()}else{e.strokeStyle=h,e.lineWidth=Math.max(1,t.r*2*m),e.beginPath();let v=0;for(let u=0;ur||g.y1a)continue;let f=(l[g.at]-o)*m+d,w=(l[g.at+1]-c)*m+p;if(g.n===1)e.moveTo(f,w),e.lineTo(f+0.01,w);else{e.moveTo(f,w);for(let x=1;x0)e.stroke()}}drawLitPieces(e,t,n,i,s,r,a,o,c,m,d,p,l){let h=t.pts,v=os(t.color,t.alpha);for(let u=0;ua||g.y1o)continue;let f=(h[g.at]-c)*d+p,w=(h[g.at+1]-m)*d+l;if(g.kind===2){let x=Math.max(1.5,t.r*d);e.fillStyle=v,e.beginPath(),e.arc(f,w,x,0,Math.PI*2),e.fill(),e.strokeStyle=i,e.lineWidth=1.5,e.stroke()}else if(g.kind===0&&g.n>=3){e.fillStyle=v,e.beginPath(),e.moveTo(f,w);for(let x=1;x=0;d--){let p=n.chunks[d];if(p.layer<32&&(m>>>p.layer&1)===1)continue;for(let l=0;lh.x1+a||rh.y1+a)continue;let v=(h.x1-h.x0+1)*(h.y1-h.y0+1);if(v{if(this.canvas.setPointerCapture(e.pointerId),this.pointers.set(e.pointerId,{x:e.clientX,y:e.clientY}),this.pointers.size===1)this.dragStart={x:e.clientX,y:e.clientY,cx:this.cx,cy:this.cy,moved:!1},this.pinchStart=null;else if(this.pointers.size===2){let[t,n]=Array.from(this.pointers.values());this.pinchStart={dist:Math.hypot(n.x-t.x,n.y-t.y)||1,midX:(t.x+n.x)*0.5,midY:(t.y+n.y)*0.5,scale:this.scale,cx:this.cx,cy:this.cy},this.dragStart=null}};onPointerMove=(e)=>{if(!this.pointers.has(e.pointerId))return;if(this.pointers.set(e.pointerId,{x:e.clientX,y:e.clientY}),this.pointers.size===2&&this.pinchStart){let[t,n]=Array.from(this.pointers.values()),i=Math.hypot(n.x-t.x,n.y-t.y)||1,s=(t.x+n.x)*0.5,r=(t.y+n.y)*0.5,a=i/this.pinchStart.dist,o=Math.max(0.0000001,Math.min(2,this.pinchStart.scale*a)),c=this.canvas.getBoundingClientRect(),m=this.pinchStart.midX-c.left-c.width*0.5,d=this.pinchStart.midY-c.top-c.height*0.5,p=s-c.left-c.width*0.5,l=r-c.top-c.height*0.5;this.scale=o,this.cx=this.pinchStart.cx+m/this.pinchStart.scale-p/o,this.cy=this.pinchStart.cy+d/this.pinchStart.scale-l/o,this.userMoved=!0,this.cbs.onUserMove?.(),this.scheduleDraw();return}if(this.dragStart&&this.pointers.size===1){let t=e.clientX-this.dragStart.x,n=e.clientY-this.dragStart.y;if(Math.hypot(t,n)>3)this.dragStart.moved=!0;if(this.dragStart.moved)this.cx=this.dragStart.cx-t/this.scale,this.cy=this.dragStart.cy-n/this.scale,this.userMoved=!0,this.cbs.onUserMove?.(),this.scheduleDraw()}};onPointerUp=(e)=>{let t=this.dragStart&&!this.dragStart.moved&&this.pointers.size===1;if(this.pointers.delete(e.pointerId),this.pointers.size<2)this.pinchStart=null;if(this.pointers.size===0)this.dragStart=null;if(t&&this.cbs.onPick){let n=this.canvas.getBoundingClientRect(),i=this.hitTest(e.clientX-n.left,e.clientY-n.top);this.cbs.onPick(i)}};onWheel=(e)=>{e.preventDefault();let t=this.canvas.getBoundingClientRect(),n=e.clientX-t.left-t.width*0.5,i=e.clientY-t.top-t.height*0.5,s=e.deltaY<0?1.16:0.8620689655172414,r=Math.max(0.0000001,Math.min(2,this.scale*s));this.cx+=n/this.scale-n/r,this.cy+=i/this.scale-i/r,this.scale=r,this.userMoved=!0,this.cbs.onUserMove?.(),this.scheduleDraw()};onDblClick=()=>{this.fit()};destroy(){if(this.rafId)cancelAnimationFrame(this.rafId);this.resizeObs.disconnect(),this.canvas.removeEventListener("pointerdown",this.onPointerDown),this.canvas.removeEventListener("pointermove",this.onPointerMove),this.canvas.removeEventListener("pointerup",this.onPointerUp),this.canvas.removeEventListener("pointercancel",this.onPointerUp),this.canvas.removeEventListener("wheel",this.onWheel),this.canvas.removeEventListener("dblclick",this.onDblClick),this.canvas.remove()}}var ls=[{id:"fit",label:"Fit"},{id:"iso",label:"Iso"},{id:"top",label:"Top"},{id:"bottom",label:"Bottom"},{id:"front",label:"Front"},{id:"right",label:"Right"},{id:"back",label:"Back"},{id:"left",label:"Left"}];function cs(e){switch(e){case"top":return{yaw:0,pitch:Math.PI*0.499};case"bottom":return{yaw:0,pitch:-Math.PI*0.499};case"front":return{yaw:0,pitch:0};case"right":return{yaw:Math.PI*0.5,pitch:0};case"back":return{yaw:Math.PI,pitch:0};case"left":return{yaw:-Math.PI*0.5,pitch:0};case"iso":case"fit":default:return{yaw:0.6,pitch:0.7}}}function Ln(e,t,n,i){if(!e||!t||!n||!i)return!1;if(!e.startsWith(t))return!1;let s=e.slice(t.length).split(`
+`),r=(s[0]||"").split("\t");if(r[0]!=="git"||r[2]!==n)return!1;let a=s[1]||r.slice(4).join("\t");if(!a)return!1;let o=a.replace(/\\/g,"/"),c=i.replace(/\\/g,"/");if(c.startsWith("/")||/^[A-Za-z]:\//.test(c))return o===c;return o===c||o.endsWith(`/${c}`)}class Sn{refs=[];index=-1;lastCommit="";highlightEdits=!1;playing=!1;setRefs(e){if(this.refs=e,this.index>=e.length)this.index=-1,this.highlightEdits=!1}isLive(){return this.index<0||this.index>=this.refs.length}activeRef(){return this.isLive()?null:this.refs[this.index]}step(e){if(this.refs.length===0)return!1;let t=this.index;if(e>0)this.index=Math.min(this.refs.length-1,this.index+1);else this.index=Math.max(-1,this.index-1);if(this.index===-1)this.playing=!1,this.highlightEdits=!1;else this.lastCommit=this.refs[this.index].commit,this.highlightEdits=!0;return this.index!==t}selectCommit(e){if(!e)return this.goLive();let t=this.refs.findIndex((i)=>i.commit===e);if(t<0)return!1;let n=this.index!==t||!this.highlightEdits;return this.index=t,this.lastCommit=e,this.highlightEdits=!0,n}goLive(){let e=this.index!==-1||this.playing||this.highlightEdits;return this.index=-1,this.playing=!1,this.highlightEdits=!1,e}toggleHighlight(){if(this.highlightEdits)return this.goLive(),!1;if(this.refs.length===0)return!1;let e=this.lastCommit?this.refs.findIndex((t)=>t.commit===this.lastCommit):0;return this.index=e>=0?e:0,this.lastCommit=this.refs[this.index].commit,this.highlightEdits=!0,!0}compareRequest(){let e=this.activeRef();if(!e||!this.highlightEdits)return null;return{commit:e.commit,bits:0}}}var br=`#version 300 es
precision highp float;
out vec2 vUv;
void main() {
@@ -18,7 +19,7 @@ void main() {
vUv = vec2(x * 0.5 + 0.5, 1.0 - (y * 0.5 + 0.5));
gl_Position = vec4(x, y, 0.0, 1.0);
}
-`,or=`#version 300 es
+`,gr=`#version 300 es
precision highp float;
in vec2 vUv;
uniform vec3 uBgTop;
@@ -35,7 +36,7 @@ void main() {
vec3 lin = mix(uBgTop, uBgBot, clamp(vUv.y, 0.0, 1.0));
outColor = vec4(linearToSrgb(clamp(lin, 0.0, 1.0)), 1.0);
}
-`,lr=`#version 300 es
+`,fr=`#version 300 es
precision highp float;
layout(location = 0) in vec3 aPos;
layout(location = 1) in vec3 aNrm;
@@ -53,7 +54,7 @@ void main() {
vCol = aCol;
gl_Position = uMvp * vec4(aPos, 1.0);
}
-`,cr=`#version 300 es
+`,vr=`#version 300 es
precision highp float;
in vec3 vPos;
in vec3 vNrm;
@@ -149,8 +150,8 @@ void main() {
rgb = rgb / (vec3(1.0) + max(rgb - vec3(0.8), vec3(0.0)) * 0.28);
outColor = vec4(linearToSrgb(clamp(rgb, 0.0, 1.0)), alpha * uFade);
}
-`;function ze(e){let t=e/255;return t<=0.04045?t/12.92:Math.pow((t+0.055)/1.055,2.4)}var dr=[ze(77),ze(83),ze(94)],pr=[ze(53),ze(58),ze(67)],mr=[ze(245),ze(246),ze(248)],ur=[ze(225),ze(228),ze(233)];function ls(e,t,n){let i=e.createShader(t);if(!i)throw Error("createShader failed");if(e.shaderSource(i,n),e.compileShader(i),!e.getShaderParameter(i,e.COMPILE_STATUS)){let s=e.getShaderInfoLog(i)||"shader compile error";throw e.deleteShader(i),Error(s)}return i}function cs(e,t,n){let i=ls(e,e.VERTEX_SHADER,t),s=ls(e,e.FRAGMENT_SHADER,n),r=e.createProgram();if(!r)throw Error("createProgram failed");if(e.attachShader(r,i),e.attachShader(r,s),e.linkProgram(r),e.deleteShader(i),e.deleteShader(s),!e.getProgramParameter(r,e.LINK_STATUS)){let a=e.getProgramInfoLog(r)||"program link error";throw e.deleteProgram(r),Error(a)}return r}function hr(e,t){let n=new Float32Array(16);for(let i=0;i<4;i++)for(let s=0;s<4;s++)n[i*4+s]=e[0+s]*t[i*4+0]+e[4+s]*t[i*4+1]+e[8+s]*t[i*4+2]+e[12+s]*t[i*4+3];return n}function br(e,t,n,i){let s=1/Math.tan(e*0.5),r=1/(n-i),a=new Float32Array(16);return a[0]=s/t,a[5]=s,a[10]=(i+n)*r,a[11]=-1,a[14]=2*i*n*r,a}function ds(e){let t=Math.hypot(e[0],e[1],e[2])||1;return[e[0]/t,e[1]/t,e[2]/t]}function ps(e,t){return[e[1]*t[2]-e[2]*t[1],e[2]*t[0]-e[0]*t[2],e[0]*t[1]-e[1]*t[0]]}function Ln(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]}class Pn{canvas;gl=null;bgProg=null;bgVao=null;uBgTop=null;uBgBot=null;prog=null;uMvp=null;uEye=null;uRight=null;uUp=null;uFwd=null;uFade=null;worker=null;boardBatch=null;partBatches=[];activeKey="";lastMeshId="";nextJobId=1;partsTotal=0;partsDone=0;center=[0,0,0];target=[0,0,0];radius=50;dist=120;yaw=0.6;pitch=0.7;lightTheme=!1;dirty=!1;rafId=0;pointers=new Map;pinchDist=0;resizeObs;cbs;constructor(e,t={}){this.cbs=t,this.canvas=document.createElement("canvas"),this.canvas.className="bp-viewer-canvas",this.canvas.style.width="100%",this.canvas.style.height="100%",this.canvas.style.display="block",this.canvas.style.touchAction="none",e.appendChild(this.canvas);let n=this.canvas.getContext("webgl2",{antialias:!0,alpha:!1,preserveDrawingBuffer:!0});if(n)this.gl=n,this.bgProg=cs(n,ar,or),this.bgVao=n.createVertexArray(),this.uBgTop=n.getUniformLocation(this.bgProg,"uBgTop"),this.uBgBot=n.getUniformLocation(this.bgProg,"uBgBot"),this.prog=cs(n,lr,cr),this.uMvp=n.getUniformLocation(this.prog,"uMvp"),this.uEye=n.getUniformLocation(this.prog,"uEye"),this.uRight=n.getUniformLocation(this.prog,"uRight"),this.uUp=n.getUniformLocation(this.prog,"uUp"),this.uFwd=n.getUniformLocation(this.prog,"uFwd"),this.uFade=n.getUniformLocation(this.prog,"uFade"),n.enable(n.DEPTH_TEST),n.blendFunc(n.SRC_ALPHA,n.ONE_MINUS_SRC_ALPHA);else this.cbs.onStatus?.("WebGL2 is unavailable in this browser");try{this.worker=new Worker("/assets/mesh-worker.js",{type:"module"}),this.worker.onmessage=(i)=>this.onWorkerMessage(i.data)}catch{this.cbs.onStatus?.("3D worker unavailable")}this.resizeObs=new ResizeObserver(()=>this.scheduleDraw()),this.resizeObs.observe(this.canvas),this.canvas.addEventListener("pointerdown",this.onPointerDown),this.canvas.addEventListener("pointermove",this.onPointerMove),this.canvas.addEventListener("pointerup",this.onPointerUp),this.canvas.addEventListener("pointercancel",this.onPointerUp),this.canvas.addEventListener("wheel",this.onWheel,{passive:!1}),this.canvas.addEventListener("dblclick",this.onDblClick),this.canvas.addEventListener("contextmenu",this.onContextMenu)}keptToken(){return this.activeKey&&this.lastMeshId?`${this.activeKey} ${this.lastMeshId}`:""}setTheme(e){if(this.lightTheme!==e)this.lightTheme=e,this.scheduleDraw()}handleFrame(e){let t=typeof e.key==="string"?e.key:"";if(!t)return;if(e.mesh instanceof Uint8Array&&typeof e.n==="number"&&!e.part){this.activeKey=t,this.lastMeshId=Ki(e.mesh),this.clearParts(),this.cbs.onStatus?.("Building 3D model…");let n=new Uint8Array(e.mesh),i=e.faces instanceof Uint8Array?new Uint8Array(e.faces):void 0,s=[n.buffer];if(i)s.push(i.buffer);this.worker?.postMessage({id:this.nextJobId++,kind:"solid",key:t,n:e.n,mesh:n,faces:i},s);return}if(e.parts&&typeof e.parts==="object"&&!Array.isArray(e.parts)&&!(e.parts instanceof Uint8Array)){if(this.activeKey&&t!==this.activeKey)return;if(this.activeKey=t,this.clearParts(),this.partsTotal=typeof e.parts.of==="number"?e.parts.of:0,this.partsDone=0,this.partsTotal>0)this.cbs.onStatus?.(`Loading parts 0/${this.partsTotal}…`);this.scheduleDraw();return}if(typeof e.part==="string"&&e.mesh instanceof Uint8Array&&e.at instanceof Uint8Array&&typeof e.n==="number"){if(this.activeKey&&t!==this.activeKey)return;let n=new Uint8Array(e.mesh),i=new Uint8Array(e.at),s=e.faces instanceof Uint8Array?new Uint8Array(e.faces):void 0,r=[n.buffer,i.buffer];if(s)r.push(s.buffer);this.worker?.postMessage({id:this.nextJobId++,kind:"part",key:t,partId:e.part,n:e.n,mesh:n,at:i,faces:s,refs:Array.isArray(e.refs)?e.refs:[],done:typeof e.done==="number"?e.done:0},r)}}onWorkerMessage(e){if(e.error){this.cbs.onStatus?.(e.error);return}if(e.key!==this.activeKey||!this.gl)return;if(e.kind==="solid")this.deleteBatch(this.boardBatch),this.boardBatch=this.uploadBatch(e.positions,e.normals,e.colors,0),this.center=[e.center[0],e.center[1],e.center[2]],this.target=[e.center[0],e.center[1],e.center[2]],this.radius=e.radius,this.fit(),this.cbs.onStatus?.(""),this.scheduleDraw();else if(e.kind==="part"){let t=this.uploadBatch(e.positions,e.normals,e.colors,performance.now());if(t)this.partBatches.push(t);if(this.partsDone=e.done||this.partsDone+1,this.partsTotal>0&&this.partsDone>>24===0)r++;else a++;let o=r>0?new Float32Array(r*9):null,c=r>0?new Float32Array(r*9):null,m=r>0?new Float32Array(r*12):null,d=a>0?new Float32Array(a*9):null,p=a>0?new Float32Array(a*9):null,l=a>0?new Float32Array(a*12):null,h=0,v=0;for(let f=0;f>>24&255,S=1-x/255,N=(w>>>16&255)/255,A=(w>>>8&255)/255,M=(w&255)/255,T=f*9;if(x===0&&o&&c&&m){let R=h*9;for(let H=0;H<9;H++)o[R+H]=e[T+H],c[R+H]=t[T+H];let V=h*12;for(let H=0;H<3;H++)m[V+H*4]=N,m[V+H*4+1]=A,m[V+H*4+2]=M,m[V+H*4+3]=1;h++}else if(d&&p&&l){let R=v*9;for(let H=0;H<9;H++)d[R+H]=e[T+H],p[R+H]=t[T+H];let V=v*12;for(let H=0;H<3;H++)l[V+H*4]=N,l[V+H*4+1]=A,l[V+H*4+2]=M,l[V+H*4+3]=S;v++}}let u=o&&c&&m?this.createSubBatch(o,c,m,r*3):null,g=d&&p&&l?this.createSubBatch(d,p,l,a*3):null;if(!u&&!g)return null;return{opaque:u,translucent:g,fadeStartMs:i}}deleteSubBatch(e){let t=this.gl;if(!t||!e)return;t.deleteVertexArray(e.vao),t.deleteBuffer(e.posBuf),t.deleteBuffer(e.nrmBuf),t.deleteBuffer(e.colBuf)}deleteBatch(e){if(!e)return;this.deleteSubBatch(e.opaque),this.deleteSubBatch(e.translucent)}clearParts(){for(let e of this.partBatches)this.deleteBatch(e);this.partBatches=[]}fit(){this.setView("fit")}setView(e){let t=35*Math.PI/180;this.dist=this.radius/Math.sin(t*0.5)*1.15,this.target=[this.center[0],this.center[1],this.center[2]];let{yaw:n,pitch:i}=os(e);this.yaw=n,this.pitch=i,this.scheduleDraw()}snapPng(){return this.draw(performance.now()),new Promise((e)=>{this.canvas.toBlob((t)=>e(t),"image/png")})}scheduleDraw(){if(this.dirty)return;this.dirty=!0,this.rafId=requestAnimationFrame((e)=>{if(this.dirty=!1,this.rafId=0,this.draw(e))this.scheduleDraw()})}drawSubBatch(e){if(!e||!this.gl)return;this.gl.bindVertexArray(e.vao),this.gl.drawArrays(this.gl.TRIANGLES,0,e.vertCount)}draw(e){let t=this.gl;if(!t||!this.prog)return!1;let n=this.canvas.getBoundingClientRect(),i=Math.max(1,Math.round(n.width)),s=Math.max(1,Math.round(n.height)),r=Math.min(window.devicePixelRatio||1,2),a=Math.round(i*r),o=Math.round(s*r);if(this.canvas.width!==a||this.canvas.height!==o)this.canvas.width=a,this.canvas.height=o;if(t.viewport(0,0,a,o),!this.boardBatch&&this.partBatches.length===0)return!1;if(t.depthMask(!0),t.clear(t.DEPTH_BUFFER_BIT),this.bgProg&&this.bgVao){t.disable(t.DEPTH_TEST),t.disable(t.BLEND),t.depthMask(!1),t.useProgram(this.bgProg);let R=this.lightTheme?mr:dr,V=this.lightTheme?ur:pr;t.uniform3f(this.uBgTop,R[0],R[1],R[2]),t.uniform3f(this.uBgBot,V[0],V[1],V[2]),t.bindVertexArray(this.bgVao),t.drawArrays(t.TRIANGLE_STRIP,0,4),t.bindVertexArray(null)}let c=Math.cos(this.pitch),m=Math.sin(this.pitch),d=Math.cos(this.yaw),p=Math.sin(this.yaw),l=[this.target[0]+this.dist*c*p,this.target[1]-this.dist*c*d,this.target[2]+this.dist*m],h=ds([this.target[0]-l[0],this.target[1]-l[1],this.target[2]-l[2]]),v=Math.abs(h[2])>0.99?[0,1,0]:[0,0,1],u=ds(ps(h,v)),g=ps(u,h),f=new Float32Array([u[0],g[0],-h[0],0,u[1],g[1],-h[1],0,u[2],g[2],-h[2],0,-Ln(u,l),-Ln(g,l),Ln(h,l),1]),w=Math.max(0.05,this.dist*0.01),x=Math.max(this.dist*10,this.radius*20),S=br(35*Math.PI/180,a/o,w,x),N=hr(S,f);t.useProgram(this.prog),t.uniformMatrix4fv(this.uMvp,!1,N),t.uniform3f(this.uEye,l[0],l[1],l[2]),t.uniform3f(this.uRight,u[0],u[1],u[2]),t.uniform3f(this.uUp,g[0],g[1],g[2]),t.uniform3f(this.uFwd,h[0],h[1],h[2]);let A=!1,M=[],T=[];for(let R of this.partBatches){let V=e-R.fadeStartMs,H=R.fadeStartMs===0?1:Math.min(1,Math.max(0,V/300));if(H<1){if(A=!0,H>0)T.push({batch:R,fade:H})}else M.push(R)}if(t.enable(t.DEPTH_TEST),t.depthMask(!0),t.disable(t.BLEND),t.uniform1f(this.uFade,1),this.boardBatch)this.drawSubBatch(this.boardBatch.opaque);for(let R of M)this.drawSubBatch(R.opaque);if(t.depthMask(!1),t.enable(t.BLEND),t.uniform1f(this.uFade,1),this.boardBatch)this.drawSubBatch(this.boardBatch.translucent);for(let R of M)this.drawSubBatch(R.translucent);for(let{batch:R,fade:V}of T)t.uniform1f(this.uFade,V),this.drawSubBatch(R.opaque),this.drawSubBatch(R.translucent);return t.depthMask(!0),t.bindVertexArray(null),A}onPointerDown=(e)=>{if(this.canvas.setPointerCapture(e.pointerId),this.pointers.set(e.pointerId,{x:e.clientX,y:e.clientY,button:e.button,shift:e.shiftKey}),this.pointers.size===2){let[t,n]=Array.from(this.pointers.values());this.pinchDist=Math.hypot(n.x-t.x,n.y-t.y)||1}};onPointerMove=(e)=>{let t=this.pointers.get(e.pointerId);if(!t)return;let n=e.clientX-t.x,i=e.clientY-t.y;if(t.x=e.clientX,t.y=e.clientY,this.pointers.size===2){let[s,r]=Array.from(this.pointers.values()),a=Math.hypot(r.x-s.x,r.y-s.y)||1;if(this.pinchDist>0)this.dist=Math.max(this.radius*0.05,Math.min(this.radius*20,this.dist*(this.pinchDist/a)));this.pinchDist=a,this.cbs.onUserMove?.(),this.scheduleDraw();return}if(t.button===2||t.button===1||t.shift){let s=this.dist*0.0014,r=Math.cos(this.yaw),a=Math.sin(this.yaw);this.target[0]-=n*r*s,this.target[1]-=n*a*s,this.target[2]+=i*s}else this.yaw+=n*0.008,this.pitch=Math.max(-Math.PI*0.49,Math.min(Math.PI*0.49,this.pitch+i*0.008));this.cbs.onUserMove?.(),this.scheduleDraw()};onPointerUp=(e)=>{if(this.pointers.delete(e.pointerId),this.pointers.size<2)this.pinchDist=0};onWheel=(e)=>{e.preventDefault();let t=e.deltaY<0?0.8620689655172414:1.16;this.dist=Math.max(this.radius*0.05,Math.min(this.radius*20,this.dist*t)),this.cbs.onUserMove?.(),this.scheduleDraw()};onDblClick=()=>{this.fit()};onContextMenu=(e)=>{e.preventDefault()};destroy(){if(this.rafId)cancelAnimationFrame(this.rafId);if(this.resizeObs.disconnect(),this.canvas.removeEventListener("pointerdown",this.onPointerDown),this.canvas.removeEventListener("pointermove",this.onPointerMove),this.canvas.removeEventListener("pointerup",this.onPointerUp),this.canvas.removeEventListener("pointercancel",this.onPointerUp),this.canvas.removeEventListener("wheel",this.onWheel),this.canvas.removeEventListener("dblclick",this.onDblClick),this.canvas.removeEventListener("contextmenu",this.onContextMenu),this.deleteBatch(this.boardBatch),this.clearParts(),this.gl){if(this.bgVao)this.gl.deleteVertexArray(this.bgVao);if(this.bgProg)this.gl.deleteProgram(this.bgProg);if(this.prog)this.gl.deleteProgram(this.prog)}this.worker?.terminate(),this.canvas.remove()}}var ms=64,gr=16777216;function fr(e,t){switch(e){case"board":case"3d":return t.board!==!1;case"schematic":return t.schematic!==!1;case"mech":return t.mech!==!1;case"gerbers":return t.gerbers!==!1;default:return!0}}function Pt(e){if(!e)return"";let t=e.replace(/\\/g,"/").replace(/\/+$/,""),n=t.lastIndexOf("/");return n>=0?t.slice(n+1):t}function us(e){switch(e){case"board":return b("viewer.board","Board");case"schematic":return b("viewer.schematic","Schematic");case"3d":return b("viewer.solid","3D");case"gerbers":return b("gpui.gerbers","Gerbers");case"mech":return b("viewer.mech","Mech");case"files":return b("viewer.files","Files");case"diff":return b("viewer.diff","Diff");case"review":return b("viewer.review","Review");case"browser":return b("bots.tab.browser","Browser");case"terminal":return b("viewer.terminal","Terminal");default:return e?e.charAt(0).toUpperCase()+e.slice(1):""}}function Nn(e){return e==="board"||e==="schematic"||e==="gerbers"}function vr(e){return e==="files"||e==="diff"||e==="review"||e==="browser"||e==="terminal"}function Mn(e,t){let n=document.createElement("div");n.className="bp-vh";let i=document.createElement("div");i.className="bp-vh-title";let s=document.createElement("span");s.className="bp-vh-page";let r=document.createElement("span");r.className="bp-vh-sep",r.textContent="·",r.hidden=!0;let a=document.createElement("span");a.className="bp-vh-file",a.hidden=!0,i.append(s,r,a);let o=document.createElement("div");o.className="bp-vh-actions",n.append(i,o);let c=document.createElement("div");c.className="bp-solid-bar",c.setAttribute("data-testid","solid-presets-bar"),c.hidden=!0;let m=document.createElement("div");m.className="bp-v-banner",m.hidden=!0;let d=document.createElement("div");d.className="bp-v-stage-wrap";let p=document.createElement("div");p.className="bp-v-stage";let l=document.createElement("div");l.className="bp-v-overlay",l.hidden=!0;let h=document.createElement("div");h.className="bp-v-layers",h.hidden=!0;let v=document.createElement("div");v.className="bp-v-info",v.hidden=!0,d.append(p,l,h,v);let u=document.createElement("div");u.className="bp-history-bar",u.setAttribute("data-testid","viewer-history-bar"),u.hidden=!0,e.replaceChildren(n,c,m,d,u);let g="",f="",w=0,x=!1,S=new Set,N=[],A=0,M=new Map,T=new Map,R={},V=[],H="",ae="",ue=!1,oe=!1,we=0,Se=!1,Me=0,he="",be=0,I=null,le=null,ne=null,X=null,ce=null,E=new Sn,k=0,j=!1,B="",q="",te="",D="";document.addEventListener("click",(F)=>{if(!j)return;if(F.target instanceof Node&&u.contains(F.target))return;j=!1,me()}),document.addEventListener("keydown",(F)=>{if(j&&F.key==="Escape")j=!1,me()});function K(){if(k)window.clearInterval(k),k=0;E.playing=!1}function je(){let F=f==="3d"||f==="mech";if(c.hidden=!F,!F)return;if(c.childElementCount>0)return;for(let _ of as){let U=document.createElement("button");U.type="button",U.className="bp-v-btn",U.textContent=_.label,U.setAttribute("data-testid",`solid-view-${_.id}`),U.addEventListener("click",()=>{ne?.setView(_.id)}),c.append(U)}let W=document.createElement("button");W.type="button",W.className="bp-v-btn",W.textContent="Snap view",W.setAttribute("data-testid","solid-snap"),W.addEventListener("click",()=>{if(!ne)return;ne.snapPng().then((_)=>{if(!_)return;let U=URL.createObjectURL(_),G=document.createElement("a");G.href=U;let Q=(He()||f||"view").replace(/[^a-zA-Z0-9._-]/g,"_");G.download=`${Q}-snap.png`,G.click(),setTimeout(()=>URL.revokeObjectURL(U),1000)})}),c.append(W)}async function Le(){if(!g||f!=="board"&&f!=="schematic")return;me();let F=E.compareRequest();if(!F){B="",q="",te="",D="",await Ge(!1);return}let W=`${f}|${F.commit}|${F.bits}|${ae}`;if(W===D&&S.size>0){ke(E.highlightEdits?`Comparing against ${E.activeRef()?.label||F.commit.slice(0,7)} (edits highlighted)`:`Comparing against ${E.activeRef()?.label||F.commit.slice(0,7)}`,!1);return}let _=++w;S.clear(),M.clear(),Ye(),x=!0,B="",q=F.commit,te="",D=W;try{let U=ae||(f==="schematic"?R.sch:R.pcb)||"";if(!U){let xe=await t.hub.rpc("viewer.files",{thread:g});if(_!==w)return;R=xe||{},re(),U=(f==="schematic"?R.sch:R.pcb)||""}if(!U)throw Error(`Unable to resolve ${f} file path for compare`);let G=await t.hub.rpc("viewer.compare",{thread:g,kind:f,commit:F.commit,bits:F.bits,...ae?{path:ae}:{}});if(_!==w)return;let Q=typeof G?.root==="string"?G.root:"",ee=f==="schematic"?"1":"0";B=Q?`${ee}|${Q}|diff
-`:`${ee}|`,q=F.commit,te=U.startsWith("/")||/^[A-Za-z]:[\\/]/.test(U)||!Q?U:`${Q.replace(/\/+$/,"")}/${U.replace(/^\/+/,"")}`,x=!1;let Ce=N;Ye();for(let xe of Ce)if(xe.kind==="bin")$e(xe.buf);else We(xe.key,xe.none,xe.retryable);ke(E.highlightEdits?`Comparing against ${E.activeRef()?.label||F.commit.slice(0,7)} (edits highlighted)`:`Viewing snapshot: ${E.activeRef()?.label||F.commit.slice(0,7)}`,!1)}catch(U){if(_!==w)return;x=!1,B="",q="",te="",D="",Ye(),ke(U instanceof Error?U.message:String(U),!0)}}function me(){let F=f==="board"||f==="schematic";if(u.hidden=!F,!F)return;let W=document.createElement("div");W.className="bp-history-group";let _=document.createElement("button");_.type="button",_.className="bp-v-btn",_.textContent="<",_.title="Older snapshot",_.disabled=E.refs.length===0||E.index>=E.refs.length-1,_.setAttribute("data-testid","history-prev"),_.addEventListener("click",()=>{if(K(),E.step(1))Le()});let U=document.createElement("button");U.type="button",U.className="bp-v-btn"+(E.playing?" is-on":""),U.textContent=E.playing?"⏸":"▶",U.title=E.playing?"Pause history":"Play history",U.disabled=E.refs.length===0,U.setAttribute("data-testid","history-play"),U.addEventListener("click",()=>{if(E.playing){K(),me();return}if(E.refs.length===0)return;if(E.playing=!0,E.isLive())E.index=E.refs.length-1,Le();else me();k=window.setInterval(()=>{if(!E.playing||f!=="board"&&f!=="schematic"){K(),me();return}if(E.step(-1))Le();else K(),me()},1400)});let G=document.createElement("button");G.type="button",G.className="bp-v-btn",G.textContent=">",G.title="Newer snapshot",G.disabled=E.isLive(),G.setAttribute("data-testid","history-next"),G.addEventListener("click",()=>{if(K(),E.step(-1))Le()});let Q=document.createElement("button");Q.type="button",Q.className="bp-v-btn"+(E.isLive()?" is-on":""),Q.textContent="Live",Q.setAttribute("data-testid","history-live"),Q.addEventListener("click",()=>{if(K(),E.goLive())ke("",!1),Le()});let ee=document.createElement("span");ee.className="bp-history-label",ee.setAttribute("data-testid","history-label");let Ce=E.activeRef();ee.textContent=Ce?Ce.label||Ce.commit.slice(0,7):E.refs.length>0?`Live (${E.refs.length} saved)`:"Live",W.append(_,U,G,Q,ee);let xe=document.createElement("div");xe.className="bp-history-group";let Ne=document.createElement("button");Ne.type="button",Ne.className="bp-v-btn"+(E.highlightEdits?" is-on":""),Ne.textContent="Highlight edits",Ne.disabled=E.refs.length===0,Ne.setAttribute("data-testid","history-highlight"),Ne.addEventListener("click",()=>{K(),E.toggleHighlight(),Le()});let Re=document.createElement("div");Re.className="bp-history-menu-wrap";let ye=document.createElement("button");if(ye.type="button",ye.className="bp-v-btn"+(j||!E.isLive()?" is-on":""),ye.disabled=E.refs.length===0,ye.setAttribute("data-testid","history-compare"),ye.setAttribute("aria-haspopup","menu"),ye.setAttribute("aria-expanded",String(j)),ye.textContent=Ce?`Compare: ${Ce.label||Ce.commit.slice(0,7)} ▾`:"Compare ▾",ye.addEventListener("click",(Be)=>{Be.stopPropagation(),j=!j,me()}),Re.append(ye),j&&E.refs.length>0){let Be=document.createElement("div");Be.className="bp-history-menu",Be.setAttribute("role","menu"),Be.setAttribute("data-testid","history-compare-menu");let qe=(Ie,ht,Tt)=>{let Ke=document.createElement("button");Ke.type="button",Ke.className="bp-history-menu-item"+(Tt?" is-active":""),Ke.setAttribute("role","menuitem"),Ke.setAttribute("data-commit",ht),Ke.textContent=Ie,Ke.addEventListener("click",()=>{if(j=!1,K(),E.selectCommit(ht)){if(E.isLive())ke("",!1);Le()}else me()}),Be.append(Ke)};qe("Live (working tree)","",E.isLive());for(let Ie of E.refs)qe(Ie.label||Ie.commit.slice(0,7),Ie.commit,Ce?.commit===Ie.commit);Re.append(Be)}xe.append(Ne,Re),u.replaceChildren(W,xe)}async function Pe(F){if(!F)return;try{let W=await t.hub.rpc("viewer.refs",{thread:F});if(F!==g)return;E.setRefs(Array.isArray(W?.refs)?W.refs:[]),me()}catch{if(F!==g)return;E.setRefs([]),me()}}function Y(){return document.documentElement.classList.contains("light")}let ve=new MutationObserver(()=>{let F=Y();le?.setTheme(F),ne?.setTheme(F),ce?.setTheme(F)});ve.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]});function ie(F,W="",_=!1){if(F==="none"){l.hidden=!0,l.replaceChildren();return}l.hidden=!1,l.className=`bp-v-overlay is-${F}`;let U=document.createElement("div");U.className="bp-v-state-card";let G=document.createElement("div");if(G.className="bp-v-state-msg",G.textContent=W,U.append(G),_){let Q=document.createElement("button");Q.type="button",Q.className="bp-v-btn is-primary",Q.textContent=b("tools.retry","Retry"),Q.addEventListener("click",()=>void Ge(!0)),U.append(Q)}l.replaceChildren(U)}function ke(F,W){m.textContent=F,m.hidden=!F,m.classList.toggle("is-warn",W)}function He(){if(ae)return Pt(ae);if(f==="board"||f==="3d")return Pt(R.pcb);if(f==="schematic")return Pt(R.sch);if(f==="mech")return Pt(H);return""}function re(){s.textContent=us(f);let F=He();if(r.hidden=!F,a.hidden=!F,a.textContent=F,o.replaceChildren(),f==="mech"&&V.length>1){let _=document.createElement("select");_.className="bp-v-select",_.setAttribute("aria-label",b("viewer.mech","Mech"));for(let U of V){let G=document.createElement("option");G.value=U,G.textContent=Pt(U),G.selected=U===H,_.append(G)}_.addEventListener("change",()=>{H=_.value,re(),Ge(!1)}),o.append(_)}if(Nn(f)){let _=document.createElement("button");_.type="button",_.className="bp-v-btn"+(Se?" is-on":""),_.textContent=I?.layerHead||"Layers",_.setAttribute("data-testid","viewer-layers-btn"),_.addEventListener("click",()=>{if(Se=!Se,h.hidden=!Se,_.classList.toggle("is-on",Se),Se)_e("","")}),o.append(_)}if(f==="board"||f==="schematic"||f==="3d"||f==="mech"||f==="gerbers"){let _=document.createElement("button");_.type="button",_.className="bp-v-btn",_.textContent="Fit",_.setAttribute("data-testid","viewer-fit-btn"),_.addEventListener("click",()=>{le?.fit(),ne?.fit()}),o.append(_)}if((f==="board"||f==="schematic")&&t.hub.hasFeature("follow")){let _=document.createElement("button");_.type="button",_.className="bp-v-btn"+(ue&&!oe?" is-on":""),_.textContent=ue?oe?b("gpui.follow.paused","Follow (paused)"):"Follow agent":"Follow agent",_.setAttribute("data-testid","viewer-follow-btn"),_.addEventListener("click",()=>void nt()),o.append(_)}let W=document.createElement("button");W.type="button",W.className="bp-v-btn bp-v-close",W.textContent="✕",W.title=b("common.close","Close"),W.setAttribute("aria-label",b("common.close","Close")),W.setAttribute("data-testid","viewer-close-btn"),W.addEventListener("click",()=>t.closeViewer()),o.append(W)}function ge(){if(!I){h.replaceChildren();return}let F=document.createDocumentFragment(),W=document.createElement("div");W.className="bp-v-layers-head";let _=document.createElement("span");if(_.textContent=I.layerHead||"Layers",W.append(_),I.layerReset){let ee=document.createElement("button");ee.type="button",ee.className="bp-v-btn",ee.textContent="Reset",ee.addEventListener("click",()=>void _e("reset","")),W.append(ee)}if(F.append(W),I.layerModes){let ee=document.createElement("div");ee.className="bp-v-layers-modes",["All","Dim","Only"].forEach((Ce,xe)=>{let Ne=document.createElement("button");Ne.type="button",Ne.className="bp-v-btn"+(I?.layerMode===xe?" is-on":""),Ne.textContent=Ce,Ne.addEventListener("click",()=>void _e("mode",String(xe))),ee.append(Ne)}),F.append(ee)}let U=le?.presentColors()??new Map,G=(I.layerList||[]).concat(I.layerMarks||[]),Q=document.createElement("div");Q.className="bp-v-layers-list";for(let ee of G){let Ce=U.get(ee.layer);if(Ce===void 0)continue;let xe=document.createElement("div");xe.className="bp-v-layer-row"+(ee.active?" is-focus":"");let Ne=document.createElement("input");Ne.type="checkbox",Ne.checked=ee.on!==!1,Ne.addEventListener("change",()=>void _e("toggle",String(ee.layer)));let Re=document.createElement("span");Re.className="bp-v-layer-swatch";let ye=Ce>>>16&255,Be=Ce>>>8&255,qe=Ce&255;Re.style.background=ee.on!==!1?`rgb(${ye},${Be},${qe})`:`rgba(${ye},${Be},${qe},0.2)`;let Ie=document.createElement("button");Ie.type="button",Ie.className="bp-v-layer-name",Ie.textContent=ee.name,Ie.addEventListener("click",()=>void _e("pick",String(ee.layer))),xe.append(Ne,Re,Ie),Q.append(xe)}F.append(Q),h.replaceChildren(F)}async function _e(F,W){if(!Nn(f))return;let _=w;try{let U=await t.hub.rpc("viewer.layers",{kind:f,present:be,off:Me,focus:he,...F?{action:F,value:W}:{}});if(_!==w||!U)return;Me=Number(U.own)||0,he=typeof U.focus==="string"?U.focus:"",I=U;let G={off:Number(U.off)||0,dim:Number(U.dim)||0,lift:typeof U.lift==="number"?U.lift:255};if(le?.setLayers(G),re(),Se)ge()}catch{}}async function Ue(){if(!ue||oe||!g||!t.hub.hasFeature("follow"))return;oe=!0,re();try{await t.hub.rpc("viewer.follow",{thread:g,action:"pause"})}catch{}}async function nt(){if(!g||!t.hub.hasFeature("follow"))return;let F=!ue?"on":oe?"resume":"off";try{let W=await t.hub.rpc("viewer.follow",{thread:g,action:F});if(ue=!!W.on,oe=!!W.paused,re(),W.on&&!W.paused&&W.focus&&Array.isArray(W.focus.box)&&W.focus.box.length===4&&(W.seq||0)>we)we=W.seq||we,le?.zoomToBoxMm([W.focus.box[0],W.focus.box[1],W.focus.box[2],W.focus.box[3]])}catch{}}function de(){v.hidden=!0,v.replaceChildren(),le?.setHighlights([])}function mt(F){let W=F.split(";").filter(Boolean),_=W.shift()||F,U=[],G="",Q="";for(let Re of W){if(Re.startsWith("g="))continue;let ye=Re.indexOf("=");if(ye>0){let Be=Re.slice(0,ye),qe=Re.slice(ye+1);if((Be==="ref"||Be==="symbol")&&!G)G=qe;if(Be==="net"&&!Q)Q=qe;U.push([Be,qe])}else U.push([Re,""])}let ee=document.createElement("div");ee.className="bp-v-info-head";let Ce=document.createElement("span");Ce.className="bp-v-info-title",Ce.textContent=_;let xe=document.createElement("button");xe.type="button",xe.className="bp-v-info-x",xe.textContent="×",xe.setAttribute("aria-label","Clear selection"),xe.addEventListener("click",de),ee.append(Ce,xe);let Ne=document.createElement("div");Ne.className="bp-v-info-rows";for(let[Re,ye]of U){let Be=document.createElement("span");Be.className="bp-v-info-chip",Be.textContent=ye?`${Re}: ${ye}`:Re,Ne.append(Be)}return v.replaceChildren(ee,...U.length>0?[Ne]:[]),v.hidden=!1,{ref:G||void 0,net:Q||void 0}}async function Je(F){if(!F){de();return}let W=Array.from(S)[0]||"";if(!W)return;let _=w;try{let U=await t.hub.rpc("viewer.info",{key:W,at:F.at,idx:F.idx});if(_!==w)return;let G=typeof U.info==="string"?U.info:"";if(!G){de();return}let{ref:Q,net:ee}=mt(G),Ce=[];if(Q)Ce.push(["ref",Q]);if(ee)Ce.push(["net",ee]);let xe=[[F.at,F.idx]];for(let[Ne,Re]of Ce){let ye=await t.hub.rpc("viewer.probe",{key:W,name:Ne,value:Re});if(_!==w)return;if(Array.isArray(ye.matches))for(let Be of ye.matches)xe.push(Be)}le?.setHighlights(xe)}catch{de()}}function ut(){X?.destroy(),X=null,ce?.destroy(),ce=null,le?.destroy(),le=null,ne?.destroy(),ne=null,p.replaceChildren(),Se=!1,h.hidden=!0,v.hidden=!0,v.replaceChildren(),ke("",!1),ie("none")}function Ye(){N=[],A=0}async function Ge(F){if(!g||!f)return;let W=++w;if(S.clear(),x=!1,Ye(),ut(),re(),je(),me(),(f==="board"||f==="schematic")&&g)Pe(g);if(vr(f)){if(t.hub.rpc("viewer.watch",{thread:g,kind:""}).catch(()=>{}),f==="files")X=ns(p,t,g,(G,Q)=>{if(f=G,ae=Q,G==="mech")H=Q;Ge(!1)});else if(f==="diff")X=is(p,t,g);else if(f==="review")X=ss(p,t,g);else if(f==="browser")X=Zi(p,t,g);else if(f==="terminal")ie("loading","Loading terminal…"),import("/assets/terminal.js").then((Q)=>{if(W!==w)return;if(ie("none"),Q?.mountTerminalPane)ce=Q.mountTerminalPane(p,t,g,Y());else ie("error","Terminal chunk missing",!0)},(Q)=>{if(W!==w)return;ie("error",Q instanceof Error?Q.message:String(Q),!0)});return}if(ie("loading","Loading…"),!R.root)try{let G=await t.hub.rpc("viewer.files",{thread:g});if(W!==w)return;R=G||{},re()}catch{}if(f==="gerbers"&&R.hasGerbers===!1){ie("empty","No Gerbers in this project",!1);return}let _=Y();if(f==="3d"||f==="mech")ne=new Pn(p,{onStatus:(G,Q)=>{if(Q)ie("none"),ke(G,!1);else if(G)ie("loading",G);else ie("none"),ke("",!1)},onUserMove:()=>void Ue()}),ne.setTheme(_);else if(f==="board"||f==="schematic"||f==="gerbers")le=new kn(p,{onPick:(G)=>void Je(G),onUserMove:()=>void Ue()}),le.setTheme(_);else{ie("empty",`${us(f)} is not available in this viewer`,!1);return}let U={thread:g};if(F)U.force=!0;if(f==="mech"){if(V.length===0)try{let G=await t.hub.rpc("mech.list",{thread:g});if(W!==w)return;if(V=Array.isArray(G.parts)?G.parts:[],!H)H=G.primary||V[0]||"";re()}catch(G){if(W!==w)return;ie("error",G instanceof Error?G.message:String(G),!0);return}if(!H){ie("empty",b("gpui.rail.no.mech","No mechanical parts in this project"),!1);return}U.kind="3d",U.path=H}else{if(U.kind=f,ae&&(f==="board"||f==="schematic"))U.path=ae;if(f==="3d"&&!F&&ne){let G=ne.keptToken();if(G)U.kept=G}if((f==="board"||f==="schematic"||f==="gerbers")&&!F&&t.hub.hasFeature("keptChunks"))U.keptChunks=Array.from(T.keys())}x=!0,B="",q="",te="",D="";try{let G=await t.hub.rpc("viewer.watch",U);if(W!==w)return;S=new Set(Array.isArray(G.keys)?G.keys:[]),x=!1;let Q=N;Ye();for(let ee of Q)if(ee.kind==="bin")$e(ee.buf);else We(ee.key,ee.none,ee.retryable)}catch(G){if(W!==w)return;x=!1,S.clear(),Ye();let Q=G instanceof Error?G.message:String(G),ee=/no gerbers|not in this project|another machine/i.test(Q);ie(ee?"empty":"error",Q,!ee)}}function We(F,W,_){if(x){if(N.length{if(F.t==="plot"&&typeof F.none==="string"&&typeof F.key==="string")We(F.key,F.none,F.retryable===!0)}),Oe=jt(()=>{if(f)re()}),Bt=(F)=>{if(F.key==="Escape"&&f&&!v.hidden)de()};return window.addEventListener("keydown",Bt),{open(F,W){if(W!==g){if(g=W,R={},V=[],H="",M.clear(),ue=!1,oe=!1,we=0,Me=0,he="",be=0,I=null,t.hub.hasFeature("follow"))t.hub.rpc("viewer.follow",{thread:W}).then((_)=>{if(W!==g)return;if(ue=!!_.on,oe=!!_.paused,we=Number(_.seq)||0,f)re()}).catch(()=>{})}if(F!==f)K(),E.goLive(),Me=0,he="",be=0,I=null;f=F,ae="",Ge(!1)},reconcileHas(F){if(f&&!fr(f,F))t.closeViewer()},close(){if(w++,x=!1,K(),j=!1,B="",q="",te="",D="",E.goLive(),c.hidden=!0,u.hidden=!0,Ye(),g)t.hub.rpc("viewer.watch",{thread:g,kind:""}).catch(()=>{});f="",S.clear(),ut()}}}var hs="http://www.w3.org/2000/svg";function Nt(e){let t=document.createElementNS(hs,"svg");t.setAttribute("viewBox","0 0 24 24"),t.setAttribute("width","13"),t.setAttribute("height","13"),t.setAttribute("fill","none"),t.setAttribute("stroke","currentColor"),t.setAttribute("stroke-width","1.8"),t.setAttribute("aria-hidden","true");for(let n of e){let i=document.createElementNS(hs,"path");i.setAttribute("d",n),t.appendChild(i)}return t}function yr(e){if(!e)return"bp-dot-idle";let t=e.status||e.state;if(t==="active"||t==="working")return"bp-dot-work";if(t==="finished")return"bp-dot-done";if(t==="waiting"||t==="asking"||t==="blocked"||t==="failed"||(e.waiting??0)>0)return"bp-dot-need";return"bp-dot-idle"}function bs(e,t){if(!e)return!0;if(t==="board"||t==="3d")return e.board!==!1;if(t==="schematic")return e.schematic!==!1;if(t==="mech")return e.mech!==!1;if(t==="gerbers")return e.gerbers!==!1;return!0}function gs(e){if(!e)return;let t=e==="light";document.documentElement.classList.toggle("light",t);try{localStorage.setItem("bp.theme",t?"light":"dark")}catch{}}function wr(){return`web-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`}function fs(){let e=document.getElementById("root");if(!e)return;try{if(localStorage.getItem("bp.theme")==="light")document.documentElement.classList.add("light")}catch{}let t=document.createElement("header");t.className="bp-topbar",t.setAttribute("data-testid","topbar");let n=document.createElement("button");n.type="button",n.className="icon bp-side-toggle",n.textContent="☰",n.title="Toggle sidebar",n.setAttribute("aria-label","Toggle sidebar");let i=document.createElement("div");i.className="bp-brand";let s=document.createElement("img");s.src="/assets/favicon.svg",s.alt="Backplane",s.className="bp-logo";let r=document.createElement("span");r.className="bp-brand-name bp-hide-phone",r.textContent="Backplane";let a=document.createElement("span");a.className="bp-crumb-sep bp-hide-phone",a.textContent="/";let o=document.createElement("span");o.className="bp-crumb-proj bp-hide-phone";let c=document.createElement("span");c.className="bp-crumb-sep bp-hide-phone",c.textContent="/";let m=document.createElement("span");m.className="bp-crumb-thread",m.setAttribute("data-testid","thread-title");let d=document.createElement("span");d.className="bp-plan-top-badge bp-hidden",d.setAttribute("data-testid","plan-top-badge"),i.append(s,r,a,o,c,m,d);let p=document.createElement("div");p.className="bp-top-state bp-hide-phone bp-hidden";let l=document.createElement("span");l.className="bp-top-state-lbl",l.textContent="STATE";let h=document.createElement("span");h.className="bp-dot bp-dot-idle";let v=document.createElement("span");v.className="bp-top-state-word",p.append(l,h,v);let u=document.createElement("div");u.className="bp-top-acts bp-hide-phone bp-hidden";let g=document.createElement("button");g.type="button",g.className="bp-btn-ghost bp-top-act";let f=document.createElement("span");f.textContent=b("menu.pin","Pin"),g.append(Nt(["M12 17v5","M9 3h6l1 7 3 3H5l3-3 1-7z"]),f);let w=document.createElement("button");w.type="button",w.className="bp-btn-ghost bp-top-act";let x=document.createElement("span");x.textContent=b("menu.settle","Settle"),w.append(Nt(["M12 22a10 10 0 1 0 0-20 10 10 0 0 0 0 20z","M9 12l2 2 4-4"]),x);let S=document.createElement("div");S.className="bp-menu-wrap";let N=document.createElement("button");N.type="button",N.className="bp-btn-ghost bp-top-act",N.textContent="▾",N.title="Thread menu",N.setAttribute("aria-label","Thread menu"),N.setAttribute("data-testid","thread-menu-btn");let A=document.createElement("div");A.className="bp-popover bp-hidden",A.setAttribute("data-testid","thread-menu"),S.append(N,A),u.append(g,w,S);let M=document.createElement("div");M.className="bp-top-right";let T=document.createElement("button");T.type="button",T.className="bp-btn-ghost bp-top-act bp-hide-tablet",T.setAttribute("data-testid","improvements-btn");let R=document.createElement("span");R.textContent=b("gpui.improvements","Improvements"),T.append(Nt(["M12 2l2.4 7.4H22l-6.2 4.5 2.4 7.4L12 16.8l-6.2 4.5 2.4-7.4L2 9.4h7.6z"]),R);let V=document.createElement("button");V.type="button",V.className="bp-cmd-box bp-hide-tablet",V.textContent="> Jump or run a command";let H=document.createElement("button");H.type="button",H.className="icon bp-top-icon",H.title="Search",H.setAttribute("aria-label","Search"),H.appendChild(Nt(["M11 19a8 8 0 1 0 0-16 8 8 0 0 0 0 16z","M21 21l-4.3-4.3"]));let ae=document.createElement("button");ae.type="button",ae.className="icon bp-top-icon",ae.title=b("palette.settings","Settings"),ae.setAttribute("aria-label",b("palette.settings","Settings")),ae.setAttribute("data-testid","settings-btn"),ae.appendChild(Nt(["M12 15a3 3 0 1 0 0-6 3 3 0 0 0 0 6z","M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 1 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 1 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 1 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9c.26.6.85 1 1.51 1H21a2 2 0 1 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"])),M.append(T,V,H,ae),t.append(n,i,p,u,M);let ue=document.createElement("div");ue.className="bp-body";let oe=document.createElement("aside");oe.className="bp-sidebar",oe.setAttribute("data-testid","sidebar");let we=document.createElement("main");we.className="bp-center";let Se=document.createElement("div");Se.className="bp-right-area bp-hidden",Se.setAttribute("data-testid","right-area");let Me=document.createElement("div");Me.className="bp-right-top";let he=document.createElement("section");he.className="bp-viewer-pane bp-hidden",he.setAttribute("data-testid","viewer-pane"),Me.appendChild(he),Se.appendChild(Me);let be=document.createElement("nav");be.className="bp-rail",be.setAttribute("aria-label","Viewer rail"),be.setAttribute("data-testid","viewer-rail"),ue.append(oe,we,Se,be),e.append(t,ue);let I=new Cn,le=null,ne=new Set,X=0,ce=null,E=[],k=[],j=[],B=[],q=[],te=[],D="",K=0,je=0,Le=null,me=null,Pe="",Y=null,ve=20,ie={},ke=new Map;function He(y,C){ke.delete(y),ke.set(y,C);while(ke.size>ve){let L=ke.keys().next().value;if(L!==void 0)ke.delete(L);else break}}let re=new yn(oe,{onSelectThread:(y)=>{if(y===D&&Le!==null){oe.classList.remove("bp-sidebar-open");return}Ie(y)},onNewThread:(y)=>{It(y)},onSelectBot:(y)=>{Ie(y.thread)},onQuickOpenViewer:(y,C)=>{let L=k.find((O)=>O.project===y&&!O.archived&&!O.swarm);(async()=>{if(L)await Ie(L.id);else await It(y);if(D)Pe=C,$e.setActive(C),Y?.open(C,D)})()},onThreadAct:(y,C)=>{Ze(y,C)},onSnoozeRow:(y)=>{I.rpc("sidebar.act",{action:"row-snooze",value:y}).then(()=>ye()).catch(()=>{})},onToggleSection:(y)=>{if(ne.has(y))ne.delete(y);else ne.add(y);ye()},onToggleProjectFold:(y)=>{I.rpc("sidebar.act",{action:"project-fold",value:y}).then(()=>ye()).catch(()=>{})},onCollapseSidebar:()=>{oe.classList.remove("bp-sidebar-open"),oe.classList.add("bp-sidebar-collapsed")},onNeedAct:async(y)=>{let C=Ut(y,!1);if(!C)return;if(C.kind==="thread"){Ie(C.id);return}if(C.kind!=="call")return;let L=Hi(await I.rpc(C.method,C.params));if(L?.kind==="thread")Ie(L.id);ye()},hasRoomView:!1,onAddProject:()=>We.open({mode:"folder"})}),ge=new en(we,{onLoadOlder:()=>{Ke()},onGoToEntry:(y)=>{Tt(y)},onOpenAccounts:()=>{F()},onAnswerAsk:(y,C)=>{I.rpc("ask.answer",{ask:y,answer:C}).catch((L)=>{de.showError(L instanceof Error?L.message:"Could not send answer")})},onToggleReview:(y)=>{if(!D)return;let C=K;I.rpc("thread.review",{thread:D,on:y}).then((L)=>{if(C===K)ge.setReview(L.review??null)}).catch(()=>{})},onUnansweredAction:(y,C)=>{if(!D)return;if(y==="again"||y==="thread-again")I.rpc("thread.again",{thread:D,value:C}).catch(()=>{});else I.rpc("thread.act",{thread:D,action:y,value:C}).catch(()=>{})},onReplyEntry:(y)=>{if(!I.hasFeature("reply")){let C=(y.text||"").split(`
+`;function ze(e){let t=e/255;return t<=0.04045?t/12.92:Math.pow((t+0.055)/1.055,2.4)}var yr=[ze(77),ze(83),ze(94)],wr=[ze(53),ze(58),ze(67)],Er=[ze(245),ze(246),ze(248)],Cr=[ze(225),ze(228),ze(233)];function ds(e,t,n){let i=e.createShader(t);if(!i)throw Error("createShader failed");if(e.shaderSource(i,n),e.compileShader(i),!e.getShaderParameter(i,e.COMPILE_STATUS)){let s=e.getShaderInfoLog(i)||"shader compile error";throw e.deleteShader(i),Error(s)}return i}function ps(e,t,n){let i=ds(e,e.VERTEX_SHADER,t),s=ds(e,e.FRAGMENT_SHADER,n),r=e.createProgram();if(!r)throw Error("createProgram failed");if(e.attachShader(r,i),e.attachShader(r,s),e.linkProgram(r),e.deleteShader(i),e.deleteShader(s),!e.getProgramParameter(r,e.LINK_STATUS)){let a=e.getProgramInfoLog(r)||"program link error";throw e.deleteProgram(r),Error(a)}return r}function xr(e,t){let n=new Float32Array(16);for(let i=0;i<4;i++)for(let s=0;s<4;s++)n[i*4+s]=e[0+s]*t[i*4+0]+e[4+s]*t[i*4+1]+e[8+s]*t[i*4+2]+e[12+s]*t[i*4+3];return n}function kr(e,t,n,i){let s=1/Math.tan(e*0.5),r=1/(n-i),a=new Float32Array(16);return a[0]=s/t,a[5]=s,a[10]=(i+n)*r,a[11]=-1,a[14]=2*i*n*r,a}function ms(e){let t=Math.hypot(e[0],e[1],e[2])||1;return[e[0]/t,e[1]/t,e[2]/t]}function us(e,t){return[e[1]*t[2]-e[2]*t[1],e[2]*t[0]-e[0]*t[2],e[0]*t[1]-e[1]*t[0]]}function Nn(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]}class Pn{canvas;gl=null;bgProg=null;bgVao=null;uBgTop=null;uBgBot=null;prog=null;uMvp=null;uEye=null;uRight=null;uUp=null;uFwd=null;uFade=null;worker=null;boardBatch=null;partBatches=[];activeKey="";lastMeshId="";nextJobId=1;partsTotal=0;partsDone=0;center=[0,0,0];target=[0,0,0];radius=50;dist=120;yaw=0.6;pitch=0.7;lightTheme=!1;dirty=!1;rafId=0;pointers=new Map;pinchDist=0;resizeObs;cbs;constructor(e,t={}){this.cbs=t,this.canvas=document.createElement("canvas"),this.canvas.className="bp-viewer-canvas",this.canvas.style.width="100%",this.canvas.style.height="100%",this.canvas.style.display="block",this.canvas.style.touchAction="none",e.appendChild(this.canvas);let n=this.canvas.getContext("webgl2",{antialias:!0,alpha:!1,preserveDrawingBuffer:!0});if(n)this.gl=n,this.bgProg=ps(n,br,gr),this.bgVao=n.createVertexArray(),this.uBgTop=n.getUniformLocation(this.bgProg,"uBgTop"),this.uBgBot=n.getUniformLocation(this.bgProg,"uBgBot"),this.prog=ps(n,fr,vr),this.uMvp=n.getUniformLocation(this.prog,"uMvp"),this.uEye=n.getUniformLocation(this.prog,"uEye"),this.uRight=n.getUniformLocation(this.prog,"uRight"),this.uUp=n.getUniformLocation(this.prog,"uUp"),this.uFwd=n.getUniformLocation(this.prog,"uFwd"),this.uFade=n.getUniformLocation(this.prog,"uFade"),n.enable(n.DEPTH_TEST),n.blendFunc(n.SRC_ALPHA,n.ONE_MINUS_SRC_ALPHA);else this.cbs.onStatus?.("WebGL2 is unavailable in this browser");try{this.worker=new Worker("/assets/mesh-worker.js",{type:"module"}),this.worker.onmessage=(i)=>this.onWorkerMessage(i.data)}catch{this.cbs.onStatus?.("3D worker unavailable")}this.resizeObs=new ResizeObserver(()=>this.scheduleDraw()),this.resizeObs.observe(this.canvas),this.canvas.addEventListener("pointerdown",this.onPointerDown),this.canvas.addEventListener("pointermove",this.onPointerMove),this.canvas.addEventListener("pointerup",this.onPointerUp),this.canvas.addEventListener("pointercancel",this.onPointerUp),this.canvas.addEventListener("wheel",this.onWheel,{passive:!1}),this.canvas.addEventListener("dblclick",this.onDblClick),this.canvas.addEventListener("contextmenu",this.onContextMenu)}keptToken(){return this.activeKey&&this.lastMeshId?`${this.activeKey} ${this.lastMeshId}`:""}setTheme(e){if(this.lightTheme!==e)this.lightTheme=e,this.scheduleDraw()}handleFrame(e){let t=typeof e.key==="string"?e.key:"";if(!t)return;if(e.mesh instanceof Uint8Array&&typeof e.n==="number"&&!e.part){this.activeKey=t,this.lastMeshId=Yi(e.mesh),this.clearParts(),this.cbs.onStatus?.("Building 3D model…");let n=new Uint8Array(e.mesh),i=e.faces instanceof Uint8Array?new Uint8Array(e.faces):void 0,s=[n.buffer];if(i)s.push(i.buffer);this.worker?.postMessage({id:this.nextJobId++,kind:"solid",key:t,n:e.n,mesh:n,faces:i},s);return}if(e.parts&&typeof e.parts==="object"&&!Array.isArray(e.parts)&&!(e.parts instanceof Uint8Array)){if(this.activeKey&&t!==this.activeKey)return;if(this.activeKey=t,this.clearParts(),this.partsTotal=typeof e.parts.of==="number"?e.parts.of:0,this.partsDone=0,this.partsTotal>0)this.cbs.onStatus?.(`Loading parts 0/${this.partsTotal}…`);this.scheduleDraw();return}if(typeof e.part==="string"&&e.mesh instanceof Uint8Array&&e.at instanceof Uint8Array&&typeof e.n==="number"){if(this.activeKey&&t!==this.activeKey)return;let n=new Uint8Array(e.mesh),i=new Uint8Array(e.at),s=e.faces instanceof Uint8Array?new Uint8Array(e.faces):void 0,r=[n.buffer,i.buffer];if(s)r.push(s.buffer);this.worker?.postMessage({id:this.nextJobId++,kind:"part",key:t,partId:e.part,n:e.n,mesh:n,at:i,faces:s,refs:Array.isArray(e.refs)?e.refs:[],done:typeof e.done==="number"?e.done:0},r)}}onWorkerMessage(e){if(e.error){this.cbs.onStatus?.(e.error);return}if(e.key!==this.activeKey||!this.gl)return;if(e.kind==="solid")this.deleteBatch(this.boardBatch),this.boardBatch=this.uploadBatch(e.positions,e.normals,e.colors,0),this.center=[e.center[0],e.center[1],e.center[2]],this.target=[e.center[0],e.center[1],e.center[2]],this.radius=e.radius,this.fit(),this.cbs.onStatus?.(""),this.scheduleDraw();else if(e.kind==="part"){let t=this.uploadBatch(e.positions,e.normals,e.colors,performance.now());if(t)this.partBatches.push(t);if(this.partsDone=e.done||this.partsDone+1,this.partsTotal>0&&this.partsDone>>24===0)r++;else a++;let o=r>0?new Float32Array(r*9):null,c=r>0?new Float32Array(r*9):null,m=r>0?new Float32Array(r*12):null,d=a>0?new Float32Array(a*9):null,p=a>0?new Float32Array(a*9):null,l=a>0?new Float32Array(a*12):null,h=0,v=0;for(let f=0;f>>24&255,L=1-x/255,P=(w>>>16&255)/255,A=(w>>>8&255)/255,M=(w&255)/255,T=f*9;if(x===0&&o&&c&&m){let R=h*9;for(let H=0;H<9;H++)o[R+H]=e[T+H],c[R+H]=t[T+H];let V=h*12;for(let H=0;H<3;H++)m[V+H*4]=P,m[V+H*4+1]=A,m[V+H*4+2]=M,m[V+H*4+3]=1;h++}else if(d&&p&&l){let R=v*9;for(let H=0;H<9;H++)d[R+H]=e[T+H],p[R+H]=t[T+H];let V=v*12;for(let H=0;H<3;H++)l[V+H*4]=P,l[V+H*4+1]=A,l[V+H*4+2]=M,l[V+H*4+3]=L;v++}}let u=o&&c&&m?this.createSubBatch(o,c,m,r*3):null,g=d&&p&&l?this.createSubBatch(d,p,l,a*3):null;if(!u&&!g)return null;return{opaque:u,translucent:g,fadeStartMs:i}}deleteSubBatch(e){let t=this.gl;if(!t||!e)return;t.deleteVertexArray(e.vao),t.deleteBuffer(e.posBuf),t.deleteBuffer(e.nrmBuf),t.deleteBuffer(e.colBuf)}deleteBatch(e){if(!e)return;this.deleteSubBatch(e.opaque),this.deleteSubBatch(e.translucent)}clearParts(){for(let e of this.partBatches)this.deleteBatch(e);this.partBatches=[]}fit(){this.setView("fit")}setView(e){let t=35*Math.PI/180;this.dist=this.radius/Math.sin(t*0.5)*1.15,this.target=[this.center[0],this.center[1],this.center[2]];let{yaw:n,pitch:i}=cs(e);this.yaw=n,this.pitch=i,this.scheduleDraw()}snapPng(){return this.draw(performance.now()),new Promise((e)=>{this.canvas.toBlob((t)=>e(t),"image/png")})}scheduleDraw(){if(this.dirty)return;this.dirty=!0,this.rafId=requestAnimationFrame((e)=>{if(this.dirty=!1,this.rafId=0,this.draw(e))this.scheduleDraw()})}drawSubBatch(e){if(!e||!this.gl)return;this.gl.bindVertexArray(e.vao),this.gl.drawArrays(this.gl.TRIANGLES,0,e.vertCount)}draw(e){let t=this.gl;if(!t||!this.prog)return!1;let n=this.canvas.getBoundingClientRect(),i=Math.max(1,Math.round(n.width)),s=Math.max(1,Math.round(n.height)),r=Math.min(window.devicePixelRatio||1,2),a=Math.round(i*r),o=Math.round(s*r);if(this.canvas.width!==a||this.canvas.height!==o)this.canvas.width=a,this.canvas.height=o;if(t.viewport(0,0,a,o),!this.boardBatch&&this.partBatches.length===0)return!1;if(t.depthMask(!0),t.clear(t.DEPTH_BUFFER_BIT),this.bgProg&&this.bgVao){t.disable(t.DEPTH_TEST),t.disable(t.BLEND),t.depthMask(!1),t.useProgram(this.bgProg);let R=this.lightTheme?Er:yr,V=this.lightTheme?Cr:wr;t.uniform3f(this.uBgTop,R[0],R[1],R[2]),t.uniform3f(this.uBgBot,V[0],V[1],V[2]),t.bindVertexArray(this.bgVao),t.drawArrays(t.TRIANGLE_STRIP,0,4),t.bindVertexArray(null)}let c=Math.cos(this.pitch),m=Math.sin(this.pitch),d=Math.cos(this.yaw),p=Math.sin(this.yaw),l=[this.target[0]+this.dist*c*p,this.target[1]-this.dist*c*d,this.target[2]+this.dist*m],h=ms([this.target[0]-l[0],this.target[1]-l[1],this.target[2]-l[2]]),v=Math.abs(h[2])>0.99?[0,1,0]:[0,0,1],u=ms(us(h,v)),g=us(u,h),f=new Float32Array([u[0],g[0],-h[0],0,u[1],g[1],-h[1],0,u[2],g[2],-h[2],0,-Nn(u,l),-Nn(g,l),Nn(h,l),1]),w=Math.max(0.05,this.dist*0.01),x=Math.max(this.dist*10,this.radius*20),L=kr(35*Math.PI/180,a/o,w,x),P=xr(L,f);t.useProgram(this.prog),t.uniformMatrix4fv(this.uMvp,!1,P),t.uniform3f(this.uEye,l[0],l[1],l[2]),t.uniform3f(this.uRight,u[0],u[1],u[2]),t.uniform3f(this.uUp,g[0],g[1],g[2]),t.uniform3f(this.uFwd,h[0],h[1],h[2]);let A=!1,M=[],T=[];for(let R of this.partBatches){let V=e-R.fadeStartMs,H=R.fadeStartMs===0?1:Math.min(1,Math.max(0,V/300));if(H<1){if(A=!0,H>0)T.push({batch:R,fade:H})}else M.push(R)}if(t.enable(t.DEPTH_TEST),t.depthMask(!0),t.disable(t.BLEND),t.uniform1f(this.uFade,1),this.boardBatch)this.drawSubBatch(this.boardBatch.opaque);for(let R of M)this.drawSubBatch(R.opaque);if(t.depthMask(!1),t.enable(t.BLEND),t.uniform1f(this.uFade,1),this.boardBatch)this.drawSubBatch(this.boardBatch.translucent);for(let R of M)this.drawSubBatch(R.translucent);for(let{batch:R,fade:V}of T)t.uniform1f(this.uFade,V),this.drawSubBatch(R.opaque),this.drawSubBatch(R.translucent);return t.depthMask(!0),t.bindVertexArray(null),A}onPointerDown=(e)=>{if(this.canvas.setPointerCapture(e.pointerId),this.pointers.set(e.pointerId,{x:e.clientX,y:e.clientY,button:e.button,shift:e.shiftKey}),this.pointers.size===2){let[t,n]=Array.from(this.pointers.values());this.pinchDist=Math.hypot(n.x-t.x,n.y-t.y)||1}};onPointerMove=(e)=>{let t=this.pointers.get(e.pointerId);if(!t)return;let n=e.clientX-t.x,i=e.clientY-t.y;if(t.x=e.clientX,t.y=e.clientY,this.pointers.size===2){let[s,r]=Array.from(this.pointers.values()),a=Math.hypot(r.x-s.x,r.y-s.y)||1;if(this.pinchDist>0)this.dist=Math.max(this.radius*0.05,Math.min(this.radius*20,this.dist*(this.pinchDist/a)));this.pinchDist=a,this.cbs.onUserMove?.(),this.scheduleDraw();return}if(t.button===2||t.button===1||t.shift){let s=this.dist*0.0014,r=Math.cos(this.yaw),a=Math.sin(this.yaw);this.target[0]-=n*r*s,this.target[1]-=n*a*s,this.target[2]+=i*s}else this.yaw+=n*0.008,this.pitch=Math.max(-Math.PI*0.49,Math.min(Math.PI*0.49,this.pitch+i*0.008));this.cbs.onUserMove?.(),this.scheduleDraw()};onPointerUp=(e)=>{if(this.pointers.delete(e.pointerId),this.pointers.size<2)this.pinchDist=0};onWheel=(e)=>{e.preventDefault();let t=e.deltaY<0?0.8620689655172414:1.16;this.dist=Math.max(this.radius*0.05,Math.min(this.radius*20,this.dist*t)),this.cbs.onUserMove?.(),this.scheduleDraw()};onDblClick=()=>{this.fit()};onContextMenu=(e)=>{e.preventDefault()};destroy(){if(this.rafId)cancelAnimationFrame(this.rafId);if(this.resizeObs.disconnect(),this.canvas.removeEventListener("pointerdown",this.onPointerDown),this.canvas.removeEventListener("pointermove",this.onPointerMove),this.canvas.removeEventListener("pointerup",this.onPointerUp),this.canvas.removeEventListener("pointercancel",this.onPointerUp),this.canvas.removeEventListener("wheel",this.onWheel),this.canvas.removeEventListener("dblclick",this.onDblClick),this.canvas.removeEventListener("contextmenu",this.onContextMenu),this.deleteBatch(this.boardBatch),this.clearParts(),this.gl){if(this.bgVao)this.gl.deleteVertexArray(this.bgVao);if(this.bgProg)this.gl.deleteProgram(this.bgProg);if(this.prog)this.gl.deleteProgram(this.prog)}this.worker?.terminate(),this.canvas.remove()}}var hs=64,Ar=16777216;function Lr(e,t){switch(e){case"board":case"3d":return t.board!==!1;case"schematic":return t.schematic!==!1;case"mech":return t.mech!==!1;case"gerbers":return t.gerbers!==!1;default:return!0}}function Nt(e){if(!e)return"";let t=e.replace(/\\/g,"/").replace(/\/+$/,""),n=t.lastIndexOf("/");return n>=0?t.slice(n+1):t}function bs(e){switch(e){case"board":return b("viewer.board","Board");case"schematic":return b("viewer.schematic","Schematic");case"3d":return b("viewer.solid","3D");case"gerbers":return b("gpui.gerbers","Gerbers");case"mech":return b("viewer.mech","Mech");case"files":return b("viewer.files","Files");case"diff":return b("viewer.diff","Diff");case"review":return b("viewer.review","Review");case"browser":return b("bots.tab.browser","Browser");case"terminal":return b("viewer.terminal","Terminal");default:return e?e.charAt(0).toUpperCase()+e.slice(1):""}}function Mn(e){return e==="board"||e==="schematic"||e==="gerbers"}function Sr(e){return e==="files"||e==="diff"||e==="review"||e==="browser"||e==="terminal"}function Bn(e,t){let n=document.createElement("div");n.className="bp-vh";let i=document.createElement("div");i.className="bp-vh-title";let s=document.createElement("span");s.className="bp-vh-page";let r=document.createElement("span");r.className="bp-vh-sep",r.textContent="·",r.hidden=!0;let a=document.createElement("span");a.className="bp-vh-file",a.hidden=!0,i.append(s,r,a);let o=document.createElement("div");o.className="bp-vh-actions",n.append(i,o);let c=document.createElement("div");c.className="bp-solid-bar",c.setAttribute("data-testid","solid-presets-bar"),c.hidden=!0;let m=document.createElement("div");m.className="bp-v-banner",m.hidden=!0;let d=document.createElement("div");d.className="bp-v-stage-wrap";let p=document.createElement("div");p.className="bp-v-stage";let l=document.createElement("div");l.className="bp-v-overlay",l.hidden=!0;let h=document.createElement("div");h.className="bp-v-layers",h.hidden=!0;let v=document.createElement("div");v.className="bp-v-info",v.hidden=!0,d.append(p,l,h,v);let u=document.createElement("div");u.className="bp-history-bar",u.setAttribute("data-testid","viewer-history-bar"),u.hidden=!0,e.replaceChildren(n,c,m,d,u);let g="",f="",w=0,x=!1,L=new Set,P=[],A=0,M=new Map,T=new Map,R={},V=[],H="",ae="",ue=!1,oe=!1,we=0,Le=!1,Me=0,he="",be=0,I=null,le=null,ne=null,X=null,ce=null,E=new Sn,k=0,j=!1,B="",q="",te="",D="";document.addEventListener("click",(F)=>{if(!j)return;if(F.target instanceof Node&&u.contains(F.target))return;j=!1,me()}),document.addEventListener("keydown",(F)=>{if(j&&F.key==="Escape")j=!1,me()});function K(){if(k)window.clearInterval(k),k=0;E.playing=!1}function je(){let F=f==="3d"||f==="mech";if(c.hidden=!F,!F)return;if(c.childElementCount>0)return;for(let _ of ls){let U=document.createElement("button");U.type="button",U.className="bp-v-btn",U.textContent=_.label,U.setAttribute("data-testid",`solid-view-${_.id}`),U.addEventListener("click",()=>{ne?.setView(_.id)}),c.append(U)}let W=document.createElement("button");W.type="button",W.className="bp-v-btn",W.textContent="Snap view",W.setAttribute("data-testid","solid-snap"),W.addEventListener("click",()=>{if(!ne)return;ne.snapPng().then((_)=>{if(!_)return;let U=URL.createObjectURL(_),O=document.createElement("a");O.href=U;let Z=(He()||f||"view").replace(/[^a-zA-Z0-9._-]/g,"_");O.download=`${Z}-snap.png`,O.click(),setTimeout(()=>URL.revokeObjectURL(U),1000)})}),c.append(W)}async function Se(){if(!g||f!=="board"&&f!=="schematic")return;me();let F=E.compareRequest();if(!F){B="",q="",te="",D="",await Oe(!1);return}let W=`${f}|${F.commit}|${F.bits}|${ae}`;if(W===D&&L.size>0){ke(E.highlightEdits?`Comparing against ${E.activeRef()?.label||F.commit.slice(0,7)} (edits highlighted)`:`Comparing against ${E.activeRef()?.label||F.commit.slice(0,7)}`,!1);return}let _=++w;L.clear(),M.clear(),Ye(),x=!0,B="",q=F.commit,te="",D=W;try{let U=ae||(f==="schematic"?R.sch:R.pcb)||"";if(!U){let xe=await t.hub.rpc("viewer.files",{thread:g});if(_!==w)return;R=xe||{},re(),U=(f==="schematic"?R.sch:R.pcb)||""}if(!U)throw Error(`Unable to resolve ${f} file path for compare`);let O=await t.hub.rpc("viewer.compare",{thread:g,kind:f,commit:F.commit,bits:F.bits,...ae?{path:ae}:{}});if(_!==w)return;let Z=typeof O?.root==="string"?O.root:"",ee=f==="schematic"?"1":"0";B=Z?`${ee}|${Z}|diff
+`:`${ee}|`,q=F.commit,te=U.startsWith("/")||/^[A-Za-z]:[\\/]/.test(U)||!Z?U:`${Z.replace(/\/+$/,"")}/${U.replace(/^\/+/,"")}`,x=!1;let Ce=P;Ye();for(let xe of Ce)if(xe.kind==="bin")$e(xe.buf);else We(xe.key,xe.none,xe.retryable);ke(E.highlightEdits?`Comparing against ${E.activeRef()?.label||F.commit.slice(0,7)} (edits highlighted)`:`Viewing snapshot: ${E.activeRef()?.label||F.commit.slice(0,7)}`,!1)}catch(U){if(_!==w)return;x=!1,B="",q="",te="",D="",Ye(),ke(U instanceof Error?U.message:String(U),!0)}}function me(){let F=f==="board"||f==="schematic";if(u.hidden=!F,!F)return;let W=document.createElement("div");W.className="bp-history-group";let _=document.createElement("button");_.type="button",_.className="bp-v-btn",_.textContent="<",_.title="Older snapshot",_.disabled=E.refs.length===0||E.index>=E.refs.length-1,_.setAttribute("data-testid","history-prev"),_.addEventListener("click",()=>{if(K(),E.step(1))Se()});let U=document.createElement("button");U.type="button",U.className="bp-v-btn"+(E.playing?" is-on":""),U.textContent=E.playing?"⏸":"▶",U.title=E.playing?"Pause history":"Play history",U.disabled=E.refs.length===0,U.setAttribute("data-testid","history-play"),U.addEventListener("click",()=>{if(E.playing){K(),me();return}if(E.refs.length===0)return;if(E.playing=!0,E.isLive())E.index=E.refs.length-1,Se();else me();k=window.setInterval(()=>{if(!E.playing||f!=="board"&&f!=="schematic"){K(),me();return}if(E.step(-1))Se();else K(),me()},1400)});let O=document.createElement("button");O.type="button",O.className="bp-v-btn",O.textContent=">",O.title="Newer snapshot",O.disabled=E.isLive(),O.setAttribute("data-testid","history-next"),O.addEventListener("click",()=>{if(K(),E.step(-1))Se()});let Z=document.createElement("button");Z.type="button",Z.className="bp-v-btn"+(E.isLive()?" is-on":""),Z.textContent="Live",Z.setAttribute("data-testid","history-live"),Z.addEventListener("click",()=>{if(K(),E.goLive())ke("",!1),Se()});let ee=document.createElement("span");ee.className="bp-history-label",ee.setAttribute("data-testid","history-label");let Ce=E.activeRef();ee.textContent=Ce?Ce.label||Ce.commit.slice(0,7):E.refs.length>0?`Live (${E.refs.length} saved)`:"Live",W.append(_,U,O,Z,ee);let xe=document.createElement("div");xe.className="bp-history-group";let Pe=document.createElement("button");Pe.type="button",Pe.className="bp-v-btn"+(E.highlightEdits?" is-on":""),Pe.textContent="Highlight edits",Pe.disabled=E.refs.length===0,Pe.setAttribute("data-testid","history-highlight"),Pe.addEventListener("click",()=>{K(),E.toggleHighlight(),Se()});let Re=document.createElement("div");Re.className="bp-history-menu-wrap";let ye=document.createElement("button");if(ye.type="button",ye.className="bp-v-btn"+(j||!E.isLive()?" is-on":""),ye.disabled=E.refs.length===0,ye.setAttribute("data-testid","history-compare"),ye.setAttribute("aria-haspopup","menu"),ye.setAttribute("aria-expanded",String(j)),ye.textContent=Ce?`Compare: ${Ce.label||Ce.commit.slice(0,7)} ▾`:"Compare ▾",ye.addEventListener("click",(Be)=>{Be.stopPropagation(),j=!j,me()}),Re.append(ye),j&&E.refs.length>0){let Be=document.createElement("div");Be.className="bp-history-menu",Be.setAttribute("role","menu"),Be.setAttribute("data-testid","history-compare-menu");let qe=(Ie,ht,Tt)=>{let Ke=document.createElement("button");Ke.type="button",Ke.className="bp-history-menu-item"+(Tt?" is-active":""),Ke.setAttribute("role","menuitem"),Ke.setAttribute("data-commit",ht),Ke.textContent=Ie,Ke.addEventListener("click",()=>{if(j=!1,K(),E.selectCommit(ht)){if(E.isLive())ke("",!1);Se()}else me()}),Be.append(Ke)};qe("Live (working tree)","",E.isLive());for(let Ie of E.refs)qe(Ie.label||Ie.commit.slice(0,7),Ie.commit,Ce?.commit===Ie.commit);Re.append(Be)}xe.append(Pe,Re),u.replaceChildren(W,xe)}async function Ne(F){if(!F)return;try{let W=await t.hub.rpc("viewer.refs",{thread:F});if(F!==g)return;E.setRefs(Array.isArray(W?.refs)?W.refs:[]),me()}catch{if(F!==g)return;E.setRefs([]),me()}}function Y(){return document.documentElement.classList.contains("light")}let ve=new MutationObserver(()=>{let F=Y();le?.setTheme(F),ne?.setTheme(F),ce?.setTheme(F)});ve.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]});function ie(F,W="",_=!1){if(F==="none"){l.hidden=!0,l.replaceChildren();return}l.hidden=!1,l.className=`bp-v-overlay is-${F}`;let U=document.createElement("div");U.className="bp-v-state-card";let O=document.createElement("div");if(O.className="bp-v-state-msg",O.textContent=W,U.append(O),_){let Z=document.createElement("button");Z.type="button",Z.className="bp-v-btn is-primary",Z.textContent=b("tools.retry","Retry"),Z.addEventListener("click",()=>void Oe(!0)),U.append(Z)}l.replaceChildren(U)}function ke(F,W){m.textContent=F,m.hidden=!F,m.classList.toggle("is-warn",W)}function He(){if(ae)return Nt(ae);if(f==="board"||f==="3d")return Nt(R.pcb);if(f==="schematic")return Nt(R.sch);if(f==="mech")return Nt(H);return""}function re(){s.textContent=bs(f);let F=He();if(r.hidden=!F,a.hidden=!F,a.textContent=F,o.replaceChildren(),f==="mech"&&V.length>1){let _=document.createElement("select");_.className="bp-v-select",_.setAttribute("aria-label",b("viewer.mech","Mech"));for(let U of V){let O=document.createElement("option");O.value=U,O.textContent=Nt(U),O.selected=U===H,_.append(O)}_.addEventListener("change",()=>{H=_.value,re(),Oe(!1)}),o.append(_)}if(Mn(f)){let _=document.createElement("button");_.type="button",_.className="bp-v-btn"+(Le?" is-on":""),_.textContent=I?.layerHead||"Layers",_.setAttribute("data-testid","viewer-layers-btn"),_.addEventListener("click",()=>{if(Le=!Le,h.hidden=!Le,_.classList.toggle("is-on",Le),Le)_e("","")}),o.append(_)}if(f==="board"||f==="schematic"||f==="3d"||f==="mech"||f==="gerbers"){let _=document.createElement("button");_.type="button",_.className="bp-v-btn",_.textContent="Fit",_.setAttribute("data-testid","viewer-fit-btn"),_.addEventListener("click",()=>{le?.fit(),ne?.fit()}),o.append(_)}if((f==="board"||f==="schematic")&&t.hub.hasFeature("follow")){let _=document.createElement("button");_.type="button",_.className="bp-v-btn"+(ue&&!oe?" is-on":""),_.textContent=ue?oe?b("gpui.follow.paused","Follow (paused)"):"Follow agent":"Follow agent",_.setAttribute("data-testid","viewer-follow-btn"),_.addEventListener("click",()=>void nt()),o.append(_)}let W=document.createElement("button");W.type="button",W.className="bp-v-btn bp-v-close",W.textContent="✕",W.title=b("common.close","Close"),W.setAttribute("aria-label",b("common.close","Close")),W.setAttribute("data-testid","viewer-close-btn"),W.addEventListener("click",()=>t.closeViewer()),o.append(W)}function ge(){if(!I){h.replaceChildren();return}let F=document.createDocumentFragment(),W=document.createElement("div");W.className="bp-v-layers-head";let _=document.createElement("span");if(_.textContent=I.layerHead||"Layers",W.append(_),I.layerReset){let ee=document.createElement("button");ee.type="button",ee.className="bp-v-btn",ee.textContent="Reset",ee.addEventListener("click",()=>void _e("reset","")),W.append(ee)}if(F.append(W),I.layerModes){let ee=document.createElement("div");ee.className="bp-v-layers-modes",["All","Dim","Only"].forEach((Ce,xe)=>{let Pe=document.createElement("button");Pe.type="button",Pe.className="bp-v-btn"+(I?.layerMode===xe?" is-on":""),Pe.textContent=Ce,Pe.addEventListener("click",()=>void _e("mode",String(xe))),ee.append(Pe)}),F.append(ee)}let U=le?.presentColors()??new Map,O=(I.layerList||[]).concat(I.layerMarks||[]),Z=document.createElement("div");Z.className="bp-v-layers-list";for(let ee of O){let Ce=U.get(ee.layer);if(Ce===void 0)continue;let xe=document.createElement("div");xe.className="bp-v-layer-row"+(ee.active?" is-focus":"");let Pe=document.createElement("input");Pe.type="checkbox",Pe.checked=ee.on!==!1,Pe.addEventListener("change",()=>void _e("toggle",String(ee.layer)));let Re=document.createElement("span");Re.className="bp-v-layer-swatch";let ye=Ce>>>16&255,Be=Ce>>>8&255,qe=Ce&255;Re.style.background=ee.on!==!1?`rgb(${ye},${Be},${qe})`:`rgba(${ye},${Be},${qe},0.2)`;let Ie=document.createElement("button");Ie.type="button",Ie.className="bp-v-layer-name",Ie.textContent=ee.name,Ie.addEventListener("click",()=>void _e("pick",String(ee.layer))),xe.append(Pe,Re,Ie),Z.append(xe)}F.append(Z),h.replaceChildren(F)}async function _e(F,W){if(!Mn(f))return;let _=w;try{let U=await t.hub.rpc("viewer.layers",{kind:f,present:be,off:Me,focus:he,...F?{action:F,value:W}:{}});if(_!==w||!U)return;Me=Number(U.own)||0,he=typeof U.focus==="string"?U.focus:"",I=U;let O={off:Number(U.off)||0,dim:Number(U.dim)||0,lift:typeof U.lift==="number"?U.lift:255};if(le?.setLayers(O),re(),Le)ge()}catch{}}async function Ue(){if(!ue||oe||!g||!t.hub.hasFeature("follow"))return;oe=!0,re();try{await t.hub.rpc("viewer.follow",{thread:g,action:"pause"})}catch{}}async function nt(){if(!g||!t.hub.hasFeature("follow"))return;let F=!ue?"on":oe?"resume":"off";try{let W=await t.hub.rpc("viewer.follow",{thread:g,action:F});if(ue=!!W.on,oe=!!W.paused,re(),W.on&&!W.paused&&W.focus&&Array.isArray(W.focus.box)&&W.focus.box.length===4&&(W.seq||0)>we)we=W.seq||we,le?.zoomToBoxMm([W.focus.box[0],W.focus.box[1],W.focus.box[2],W.focus.box[3]])}catch{}}function de(){v.hidden=!0,v.replaceChildren(),le?.setHighlights([])}function mt(F){let W=F.split(";").filter(Boolean),_=W.shift()||F,U=[],O="",Z="";for(let Re of W){if(Re.startsWith("g="))continue;let ye=Re.indexOf("=");if(ye>0){let Be=Re.slice(0,ye),qe=Re.slice(ye+1);if((Be==="ref"||Be==="symbol")&&!O)O=qe;if(Be==="net"&&!Z)Z=qe;U.push([Be,qe])}else U.push([Re,""])}let ee=document.createElement("div");ee.className="bp-v-info-head";let Ce=document.createElement("span");Ce.className="bp-v-info-title",Ce.textContent=_;let xe=document.createElement("button");xe.type="button",xe.className="bp-v-info-x",xe.textContent="×",xe.setAttribute("aria-label","Clear selection"),xe.addEventListener("click",de),ee.append(Ce,xe);let Pe=document.createElement("div");Pe.className="bp-v-info-rows";for(let[Re,ye]of U){let Be=document.createElement("span");Be.className="bp-v-info-chip",Be.textContent=ye?`${Re}: ${ye}`:Re,Pe.append(Be)}return v.replaceChildren(ee,...U.length>0?[Pe]:[]),v.hidden=!1,{ref:O||void 0,net:Z||void 0}}async function Je(F){if(!F){de();return}let W=Array.from(L)[0]||"";if(!W)return;let _=w;try{let U=await t.hub.rpc("viewer.info",{key:W,at:F.at,idx:F.idx});if(_!==w)return;let O=typeof U.info==="string"?U.info:"";if(!O){de();return}let{ref:Z,net:ee}=mt(O),Ce=[];if(Z)Ce.push(["ref",Z]);if(ee)Ce.push(["net",ee]);let xe=[[F.at,F.idx]];for(let[Pe,Re]of Ce){let ye=await t.hub.rpc("viewer.probe",{key:W,name:Pe,value:Re});if(_!==w)return;if(Array.isArray(ye.matches))for(let Be of ye.matches)xe.push(Be)}le?.setHighlights(xe)}catch{de()}}function ut(){X?.destroy(),X=null,ce?.destroy(),ce=null,le?.destroy(),le=null,ne?.destroy(),ne=null,p.replaceChildren(),Le=!1,h.hidden=!0,v.hidden=!0,v.replaceChildren(),ke("",!1),ie("none")}function Ye(){P=[],A=0}async function Oe(F){if(!g||!f)return;let W=++w;if(L.clear(),x=!1,Ye(),ut(),re(),je(),me(),(f==="board"||f==="schematic")&&g)Ne(g);if(Sr(f)){if(t.hub.rpc("viewer.watch",{thread:g,kind:""}).catch(()=>{}),f==="files")X=ss(p,t,g,(O,Z)=>{if(f=O,ae=Z,O==="mech")H=Z;Oe(!1)});else if(f==="diff")X=rs(p,t,g);else if(f==="review")X=as(p,t,g);else if(f==="browser")X=ts(p,t,g);else if(f==="terminal")ie("loading","Loading terminal…"),import("/assets/terminal.js").then((Z)=>{if(W!==w)return;if(ie("none"),Z?.mountTerminalPane)ce=Z.mountTerminalPane(p,t,g,Y());else ie("error","Terminal chunk missing",!0)},(Z)=>{if(W!==w)return;ie("error",Z instanceof Error?Z.message:String(Z),!0)});return}if(ie("loading","Loading…"),!R.root)try{let O=await t.hub.rpc("viewer.files",{thread:g});if(W!==w)return;R=O||{},re()}catch{}if(f==="gerbers"&&R.hasGerbers===!1){ie("empty","No Gerbers in this project",!1);return}let _=Y();if(f==="3d"||f==="mech")ne=new Pn(p,{onStatus:(O,Z)=>{if(Z)ie("none"),ke(O,!1);else if(O)ie("loading",O);else ie("none"),ke("",!1)},onUserMove:()=>void Ue()}),ne.setTheme(_);else if(f==="board"||f==="schematic"||f==="gerbers")le=new An(p,{onPick:(O)=>void Je(O),onUserMove:()=>void Ue()}),le.setTheme(_);else{ie("empty",`${bs(f)} is not available in this viewer`,!1);return}let U={thread:g};if(F)U.force=!0;if(f==="mech"){if(V.length===0)try{let O=await t.hub.rpc("mech.list",{thread:g});if(W!==w)return;if(V=Array.isArray(O.parts)?O.parts:[],!H)H=O.primary||V[0]||"";re()}catch(O){if(W!==w)return;ie("error",O instanceof Error?O.message:String(O),!0);return}if(!H){ie("empty",b("gpui.rail.no.mech","No mechanical parts in this project"),!1);return}U.kind="3d",U.path=H}else{if(U.kind=f,ae&&(f==="board"||f==="schematic"))U.path=ae;if(f==="3d"&&!F&&ne){let O=ne.keptToken();if(O)U.kept=O}if((f==="board"||f==="schematic"||f==="gerbers")&&!F&&t.hub.hasFeature("keptChunks"))U.keptChunks=Array.from(T.keys())}x=!0,B="",q="",te="",D="";try{let O=await t.hub.rpc("viewer.watch",U);if(W!==w)return;L=new Set(Array.isArray(O.keys)?O.keys:[]),x=!1;let Z=P;Ye();for(let ee of Z)if(ee.kind==="bin")$e(ee.buf);else We(ee.key,ee.none,ee.retryable)}catch(O){if(W!==w)return;x=!1,L.clear(),Ye();let Z=O instanceof Error?O.message:String(O),ee=/no gerbers|not in this project|another machine/i.test(Z);ie(ee?"empty":"error",Z,!ee)}}function We(F,W,_){if(x){if(P.length