// Commit a small waiting page immediately. Do not keep a browser navigation // pending throughout VM boot; only short authenticated status reads are polled. import {watchPreview} from './lifecycle.js'; const query=new URLSearchParams(location.search),kind=query.get('kind'),reference=query.get('reference'); async function open(){ try{ if(!['run','example','skill'].includes(kind)||!reference)throw Error(); const session=await (await fetch('/api/session',{credentials:'same-origin'})).json(); if(!session.authenticated)throw Error(); let state; for(let retry=0;retry<=6;retry++){ const response=await fetch('/api/preview',{method:'POST',credentials:'same-origin',headers:{'Content-Type':'application/json','X-CSRF-Token':session.csrf},body:JSON.stringify({kind,reference})}); state=await response.json();if(response.ok)break; if(state.code!=='SANDBOX_RELEASING'||retry===6)throw Error(); document.getElementById('status').textContent='正在释放已关闭的应用…'; await new Promise(resolve=>setTimeout(resolve,2000)); } const lease=state.id,started=Date.now(),deadline=started+900000; await watchPreview(lease,session.csrf,'/api/preview/client'); while(state.status==='starting'&&Date.now()setTimeout(resolve,2000)); const status=await fetch('/api/preview?preview_id='+encodeURIComponent(lease),{credentials:'same-origin'}); if(!status.ok)throw Error(); state=await status.json(); if(state.id!==lease||state.kind!==kind||state.reference!==reference)throw Error(); if(state.status==='starting'&&Date.now()-started>=100000)document.getElementById('status').textContent='正在核验预览状态。'; } if(state.status!=='ready'||state.id!==lease||state.kind!==kind||state.reference!==reference)throw Error(); location.replace('/preview-site/?lease='+encodeURIComponent(lease)); }catch{document.getElementById('status').textContent='应用暂未就绪,请回工作台查看运行结果后重试。';} } open();