Spaces:
Running on CPU Upgrade
Running on CPU Upgrade
| function safeRunObject(run){return run&&typeof run==='object'?run:{}} | |
| function validRunObject(run){return Boolean(run&&typeof run==='object'&&(run.run_id||run.summary?.run_id||run.state?.run_id));} | |
| function validRunsList(runs=[]){return (Array.isArray(runs)?runs:[]).filter(validRunObject);} | |
| function inferredOwnerFromBucket(bucket){return bucket?String(bucket).split('/')[0]:''} | |
| function inferredJobUrl(summary={}, detail={}){if(summary.job_url)return summary.job_url;const launch=detail.launch||{};const stateObj=detail.state||{};if(launch.job_url)return launch.job_url;if(stateObj.job_url)return stateObj.job_url;const jobId=summary.job_id||launch.job_id||stateObj.job_id;const owner=summary.created_by||summary.username||summary.owner||launch.created_by||launch.username||launch.owner||stateObj.created_by||stateObj.username||stateObj.owner||state.user?.username||inferredOwnerFromBucket(summary.bucket_source||detail.bucket_source||state.bucketSource);return jobId&&owner?`https://huggingface.co/jobs/${owner}/${jobId}`:''} | |
| function bucketRunFileUrl(bucket,runId,relPath=''){const rel=String(relPath||'').replace(/^\/+|\/+$/g,'');return bucket&&runId?`https://huggingface.co/buckets/${bucket}/tree/runs/${runId}${rel?`/${rel}`:''}`:''} | |
| function runValidationTerminalText(run={}){ | |
| run=safeRunObject(run); | |
| return [ | |
| run.verdict,run.validation_status,run.result_status,run.final_status,run.status,run.summary?.verdict,run.summary?.validation_status,run.summary?.result_status,run.summary?.status, | |
| run.state?.verdict,run.state?.validation_status,run.state?.result_status,run.state?.status,run.gate_status,run.summary?.gate_status,run.inference_gate?.status, | |
| run.generation_smoke?.status,run.summary?.smoke_status,run.smoke_status,run.details?.error,run.error,run.message | |
| ].map(x=>String(x||'').toLowerCase()).filter(Boolean).join(' '); | |
| } | |
| function validationLockedStatus(run={}){ | |
| run=safeRunObject(run); | |
| const runId=run.run_id||run.summary?.run_id||run.state?.run_id||''; | |
| const terminal=runId&&typeof state!=='undefined'&&state.validationTerminalByRun?state.validationTerminalByRun[runId]:null; | |
| return terminal?.canonical||''; | |
| } | |
| function runCanonicalStatus(run={}){ | |
| run=safeRunObject(run); | |
| const validation=isValidationRunSummary(run); | |
| const locked=validation?validationLockedStatus(run):''; | |
| if(locked)return locked; | |
| const s=String(run.status||run.summary?.status||run.state?.status||'unknown').toLowerCase(); | |
| const gate=String(run.gate_status||run.inference_gate?.status||run.summary?.gate_status||'').toLowerCase(); | |
| const smoke=String(run.smoke_status||run.generation_smoke?.status||run.summary?.smoke_status||'').toLowerCase(); | |
| const text=validation?runValidationTerminalText(run):[s,gate,smoke].filter(Boolean).join(' '); | |
| if(text.includes('stale'))return'stale'; | |
| if(text.includes('cancelled')||text.includes('canceled')||text.includes('stopped'))return'stopped'; | |
| if(text.includes('manual')||text.includes('hardware')||text.includes('requires_action'))return'manual_hardware_required'; | |
| if(text.includes('technical_blocker')||text.includes('blocker')||text.includes('blocked'))return'technical_blocker'; | |
| if(text.includes('failed')||text.includes('failure')||text.includes('error')||text.includes('timeout'))return'failed'; | |
| if(validation&&(text.includes('full_inference_candidate_health_passed')||text.includes('health_only')||text.includes('partial')||text.includes('warning')||text.includes('not_verified')||text.includes('completed_with_warnings')))return'partial_validation'; | |
| if(!validation&&(s==='full_inference_candidate_health_passed'||s==='health_only'||s==='partial'||s==='partial_validation'||s==='completed_with_warnings'))return'partial_validation'; | |
| if(text.includes('success')||text.includes('succeed')||text.includes('passed')||['done','completed','full_inference_success','repair_success'].includes(s))return'full_inference_success'; | |
| if(text.includes('running')||text.includes('queued')||text.includes('pending')||text.includes('started')||text.includes('waiting')||text.includes('building'))return'running'; | |
| return s||'unknown'; | |
| } | |
| function truthySuccessValue(v){if(v===true)return true;const s=String(v||'').toLowerCase();return ['1','true','yes','success','passed','ok','full_inference_success'].includes(s)} | |
| function runHasPersistedGenerationSuccess(run={}){ | |
| run=safeRunObject(run); | |
| const candidates=[run,run.summary,run.state,run.inference_gate,run.generation_smoke,run.test_result,run.summary?.inference_gate,run.summary?.generation_smoke,run.state?.generation_smoke]; | |
| for(const src of candidates){ | |
| if(!src||typeof src!=='object')continue; | |
| const status=String(src.status||src.verdict||src.result_status||src.gate_status||src.smoke_status||'').toLowerCase(); | |
| if(status==='full_inference_success'||status==='success'||status==='passed')return true; | |
| if(truthySuccessValue(src.ok)||truthySuccessValue(src.generation_smoke_passed)||truthySuccessValue(src.smoke_test_passed))return true; | |
| const signals=src.implementation_signals||src.validation||src.outcome||{}; | |
| if(truthySuccessValue(signals.generation_smoke_passed))return true; | |
| const nested=src.generation_smoke||src.smoke||src.test_result||{}; | |
| if(nested&&typeof nested==='object'){ | |
| const ns=String(nested.status||nested.verdict||nested.result_status||'').toLowerCase(); | |
| if(ns==='success'||ns==='passed'||ns==='full_inference_success')return true; | |
| if(truthySuccessValue(nested.ok)||truthySuccessValue(nested.passed))return true; | |
| } | |
| } | |
| return false; | |
| } | |
| function runHasHardTerminalProblem(run={}){ | |
| const canon=runCanonicalStatus(run); | |
| return ['failed','manual_hardware_required','technical_blocker','technical_blocker_boot_only','auth_refresh_required','stale','stopped'].includes(canon); | |
| } | |
| function normalizeExplorerStatusValue(value){return String(value||'').trim().toLowerCase().replace(/\s+/g,'_')} | |
| function explorerTextHas(text,needles=[]){text=String(text||'').toLowerCase();return needles.some(x=>text.includes(x))} | |
| function explorerStatusTextFromRun(run={},includeNested=true){ | |
| run=safeRunObject(run); | |
| const values=[run.status,run.final_status,run.verdict,run.result_status,run.validation_status,run.summary?.status,run.summary?.final_status,run.summary?.verdict,run.summary?.result_status,run.state?.status,run.state?.final_status,run.state?.verdict,run.gate_status,run.summary?.gate_status]; | |
| if(includeNested)values.push(run.smoke_status,run.summary?.smoke_status,run.inference_gate?.status,run.generation_smoke?.status,run.summary?.generation_smoke?.status,run.summary?.inference_gate?.status,run.test_result?.status,run.summary?.test_result?.status,run.details?.error,run.error,run.message); | |
| return values.map(x=>String(x||'').toLowerCase()).filter(Boolean).join(' '); | |
| } | |
| function hasExplicitAutomaticFullInferenceSuccess(run={}){ | |
| run=safeRunObject(run); | |
| const strong=[run.status,run.final_status,run.verdict,run.result_status,run.summary?.status,run.summary?.final_status,run.summary?.verdict,run.summary?.result_status,run.state?.status,run.state?.final_status,run.state?.verdict].map(normalizeExplorerStatusValue); | |
| return strong.some(s=>['full_inference_success','repair_success'].includes(s)); | |
| } | |
| function hasGenericFinalSuccess(run={}){ | |
| run=safeRunObject(run); | |
| const strong=[run.status,run.final_status,run.verdict,run.result_status,run.summary?.status,run.summary?.final_status,run.summary?.verdict,run.summary?.result_status,run.state?.status,run.state?.final_status,run.state?.verdict].map(normalizeExplorerStatusValue); | |
| return strong.some(s=>['success','succeeded','passed','done','completed'].includes(s)); | |
| } | |
| function explicitExplorerStatus(run={}){ | |
| run=safeRunObject(run); | |
| const values=[ | |
| run.effective_run_status?.display_status,run.effective_run_status?.effective_status,run.effective_run_status?.effective_verdict,run.post_build_status, | |
| run.ui_status,run.display_status,run.effective_verdict,run.effective_status, | |
| run.summary?.effective_run_status?.display_status,run.summary?.effective_run_status?.effective_status,run.summary?.post_build_status, | |
| run.summary?.ui_status,run.summary?.display_status,run.summary?.effective_verdict,run.summary?.effective_status, | |
| run.state?.ui_status,run.state?.display_status,run.state?.effective_verdict,run.state?.effective_status, | |
| run.status,run.final_status,run.verdict,run.result_status | |
| ].map(normalizeExplorerStatusValue).filter(Boolean); | |
| for(const s of values){ | |
| if(['full_inference_success','partial_validation','manual_hardware_required','technical_blocker','technical_blocker_boot_only','failed','stale','stopped','cancelled','canceled','auth_refresh_required','validated_after_space_test','recovered_by_space_test','validated_after_manual_space_test','recovered_by_manual_validation','demo_usable_full_promise_not_verified','interactive_app_available_smoke_failed','manual_test_required_smoke_failed','placeholder_scaffold_deployed'].includes(s))return s==='cancelled'||s==='canceled'?'stopped':s; | |
| if(s==='full_inference_candidate_health_passed'||s==='health_only'||s==='partial'||s==='completed_with_warnings')return 'partial_validation'; | |
| } | |
| return ''; | |
| } | |
| function protectedParentPartialStatus(run={}){ | |
| run=safeRunObject(run); | |
| const parent=[run.status,run.final_status,run.verdict,run.summary?.status,run.summary?.final_status,run.summary?.verdict,run.state?.status,run.state?.final_status,run.state?.verdict].map(normalizeExplorerStatusValue); | |
| if(parent.some(s=>['partial_validation','full_inference_candidate_health_passed','health_only','partial','completed_with_warnings'].includes(s)))return 'partial_validation'; | |
| return ''; | |
| } | |
| function buildAutomaticStatus(run={}){ | |
| run=safeRunObject(run); | |
| const explicit=explicitExplorerStatus(run); | |
| if(explicit)return explicit; | |
| const protectedPartial=protectedParentPartialStatus(run); | |
| if(protectedPartial)return protectedPartial; | |
| const text=explorerStatusTextFromRun(run,true); | |
| if(explorerTextHas(text,['auth_refresh_required','oauth_expired','auth_expired']))return 'auth_refresh_required'; | |
| if(explorerTextHas(text,['cancelled','canceled','stopped']))return 'stopped'; | |
| if(explorerTextHas(text,['manual_hardware_required','generated_needs_manual_hardware','waiting_manual_hardware','manual_action_required','waiting_manual_action','requires_action','hardware_required','manual hardware']))return 'manual_hardware_required'; | |
| if(explorerTextHas(text,['technical_blocker_boot_only']))return 'technical_blocker_boot_only'; | |
| if(explorerTextHas(text,['technical_blocker','technical blocker','blocked','blocker']))return 'technical_blocker'; | |
| if(hasExplicitAutomaticFullInferenceSuccess(run))return 'full_inference_success'; | |
| const topText=explorerStatusTextFromRun(run,false); | |
| if(explorerTextHas(topText,['running','queued','pending','started','waiting','building','scheduled']))return 'running'; | |
| if(explorerTextHas(text,['partial_validation','full_inference_candidate_health_passed','health_only','partial','not_verified','warning','completed_with_warnings']))return 'partial_validation'; | |
| if(explorerTextHas(text,['failed','failure','error','timeout','exception','repair_failed']))return 'failed'; | |
| if(explorerTextHas(text,['stale']))return 'stale'; | |
| if(hasGenericFinalSuccess(run))return 'full_inference_success'; | |
| return normalizeExplorerStatusValue(run.status||run.summary?.status||run.state?.status||'unknown')||'unknown'; | |
| } | |
| function validationExplorerStatus(run={}){ | |
| const canon=runCanonicalStatus(run); | |
| const label=runCompactStatusLabel(canon); | |
| return {automatic_status:canon,validation_status:canon,display_status:canon,display_label:label,display_tone:statusClass(canon),filter_buckets:explorerFilterBuckets(canon),is_terminal:runIsFinished(canon),is_deletable:runCanBeDeleted(canon),search_tokens:[canon,label,'linked validation','space test']}; | |
| } | |
| function linkedValidationOutcome(run={}){ | |
| const manual=buildManualValidationStatus(run); | |
| let status='none'; | |
| if(manual.passed)status='passed'; | |
| else if(manual.failed)status='failed'; | |
| else if(manual.linkedCount)status='attempted'; | |
| return {...manual,status}; | |
| } | |
| function composeBuildDisplayStatus(automaticStatus,validation={}){ | |
| const auto=normalizeExplorerStatusValue(automaticStatus||'unknown'); | |
| const explicitEffective=normalizeExplorerStatusValue(validation?.explicit?.effective_status||validation?.explicit?.effective_verdict||validation?.explicit?.legacy_effective_status||validation?.latest?.effective_status||''); | |
| const newSpaceTest=explicitEffective==='validated_after_space_test'||explicitEffective==='recovered_by_space_test'||String(validation?.explicit?.schema_version||'').includes('post_build_validation'); | |
| const validatedToken=newSpaceTest?'validated_after_space_test':'validated_after_manual_space_test'; | |
| const recoveredToken=newSpaceTest?'recovered_by_space_test':'recovered_by_manual_validation'; | |
| if(validation?.passed){ | |
| if(['failed','technical_blocker','technical_blocker_boot_only'].includes(auto))return recoveredToken; | |
| if(auto==='manual_hardware_required')return 'manual_validated'; | |
| if(['partial_validation','health_only','full_inference_candidate_health_passed','completed_with_warnings','demo_usable_full_promise_not_verified','interactive_app_available_smoke_failed','manual_test_required_smoke_failed','placeholder_scaffold_deployed','stale','unknown'].includes(auto))return validatedToken; | |
| if(auto==='full_inference_success')return 'full_inference_success'; | |
| return validatedToken; | |
| } | |
| return auto; | |
| } | |
| function explorerDisplayLabel(status){ | |
| const s=normalizeExplorerStatusValue(status||'unknown'); | |
| const labels={ | |
| full_inference_success:'Success', | |
| partial_validation:'Partial',partial:'Partial',health_only:'Partial',full_inference_candidate_health_passed:'Partial',completed_with_warnings:'Partial',demo_usable_full_promise_not_verified:'Demo usable',interactive_app_available_smoke_failed:'Smoke input issue',manual_test_required_smoke_failed:'Space Test recommended',placeholder_scaffold_deployed:'Placeholder demo', | |
| manual_hardware_required:'Manual',manual_validated:'Manual validated', | |
| validated_after_space_test:'Validated after Space Test',validated_after_manual_space_test:'Validated',manual_validation_passed:'Validated',validated:'Validated', | |
| recovered_by_space_test:'Recovered by Space Test',recovered_by_manual_validation:'Recovered', | |
| failed:'Failed',technical_blocker:'Blocked',technical_blocker_boot_only:'Blocked',blocked:'Blocked', | |
| auth_refresh_required:'Auth required',oauth_expired:'Auth required',stale:'Stale',stopped:'Stopped',cancelled:'Stopped',canceled:'Stopped', | |
| running:'Running',queued:'Running',pending:'Running',started:'Running',building:'Running',waiting:'Running',scheduled:'Running',unknown:'Unknown' | |
| }; | |
| return labels[s]||badgeLabel(s); | |
| } | |
| function explorerFilterBuckets(status){ | |
| const s=normalizeExplorerStatusValue(status||'unknown'); | |
| const buckets=new Set(['all']); | |
| if(['running','queued','pending','started','building','waiting','scheduled'].includes(s))buckets.add('running'); | |
| else if(s==='full_inference_success')buckets.add('full_inference_success'); | |
| else if(['validated_after_space_test','validated_after_manual_space_test','manual_validation_passed','validated'].includes(s)){buckets.add('validated_after_manual_space_test');buckets.add('validated_after_space_test');} | |
| else if(s==='manual_validated'){buckets.add('manual_hardware_required');buckets.add('validated_after_manual_space_test');} | |
| else if(['recovered_by_space_test','recovered_by_manual_validation'].includes(s)){buckets.add('recovered_by_manual_validation');buckets.add('recovered_by_space_test');buckets.add('validated_after_manual_space_test');} | |
| else if(['partial_validation','partial','health_only','full_inference_candidate_health_passed','completed_with_warnings','demo_usable_full_promise_not_verified','interactive_app_available_smoke_failed','manual_test_required_smoke_failed','placeholder_scaffold_deployed'].includes(s))buckets.add('partial_validation'); | |
| else if(['manual_hardware_required','generated_needs_manual_hardware','waiting_manual_hardware','manual_action_required','waiting_manual_action','requires_action','hardware_required'].includes(s))buckets.add('manual_hardware_required'); | |
| else if(['technical_blocker','technical_blocker_boot_only','blocked','auth_refresh_required','oauth_expired'].includes(s)){buckets.add('technical_blocker');buckets.add('failed');} | |
| else if(['failed','failure','error','timeout','exception','repair_failed'].includes(s))buckets.add('failed'); | |
| else if(s==='stale')buckets.add('stale'); | |
| else if(['stopped','cancelled','canceled'].includes(s))buckets.add('stopped'); | |
| else buckets.add(s||'unknown'); | |
| return buckets; | |
| } | |
| function buildExplorerStatus(run={}){ | |
| run=safeRunObject(run); | |
| if(isValidationRunSummary(run))return validationExplorerStatus(run); | |
| const automaticStatus=buildAutomaticStatus(run); | |
| const validation=linkedValidationOutcome(run); | |
| const displayStatus=composeBuildDisplayStatus(automaticStatus,validation); | |
| const label=explorerDisplayLabel(displayStatus); | |
| const buckets=explorerFilterBuckets(displayStatus); | |
| const isTerminal=runIsFinished(displayStatus)||(!buckets.has('running')&&displayStatus!=='unknown')||displayStatus==='unknown'; | |
| const tokens=[ | |
| run.run_id,run.model_id,run.target_space,run.kind,run.selected_hardware,run.requested_hardware,run.preferred_space_hardware, | |
| automaticStatus,displayStatus,label,run.status,run.effective_status,run.effective_run_status?.display_status,run.summary?.status,run.summary?.effective_status,run.summary?.effective_run_status?.display_status,run.state?.status, | |
| validation.status,validation.latest?.run_id,validation.latest?.validation_run_id,validation.latest?.hardware_used_for_validation,validation.explicit?.hardware_used_for_validation, | |
| validation.passed?'linked space test passed validated space test success':'',validation.failed?'linked space test failed validation failed':'', | |
| validation.linkedCount?'linked validation space test':'',displayStatus==='manual_validated'?'manual gpu manual hardware validated':'',['recovered_by_space_test','recovered_by_manual_validation'].includes(displayStatus)?'recovered recovery space test':'', | |
| ]; | |
| return {raw_status:run.status||run.summary?.status||run.state?.status||'unknown',automatic_status:automaticStatus,validation_status:validation.status,validation,display_status:displayStatus,display_label:label,display_tone:statusClass(displayStatus),filter_buckets:buckets,is_terminal:isTerminal,is_deletable:runCanBeDeleted(displayStatus),status_reason:label,search_tokens:tokens.map(x=>String(x||'').toLowerCase()).filter(Boolean)}; | |
| } | |
| function runMatchesStatus(run,status){ | |
| // v193 legacy audit tokens: const canon=runCanonicalStatus(run); canon==='full_inference_success'; if(status==='partial_validation')return canon==='partial_validation'; | |
| if(!status||status==='all')return true; | |
| const wanted=normalizeExplorerStatusValue(status); | |
| const explorer=isValidationRunSummary(run)?validationExplorerStatus(run):buildExplorerStatus(run); | |
| return explorer.filter_buckets?.has(wanted)||explorer.display_status===wanted||explorer.validation_status===wanted; | |
| } | |
| function canonicalStatusForDeletion(context={}){ | |
| const kind=context.kind==='validation'?'validation':'active'; | |
| const detail=context.detail||{}; | |
| const summary=context.summary||detail.summary||{}; | |
| const merged={...(summary||{}),...(detail||{}),summary:{...(summary||{}),...(detail.summary||{})},state:{...(summary||{}),...(detail.state||{})}}; | |
| return kind==='validation'?validationExplorerStatus(merged).display_status:buildExplorerStatus(merged).display_status; | |
| } | |
| function runMatchesQuery(run,query){ | |
| run=safeRunObject(run);if(!query)return true; | |
| const explorer=isValidationRunSummary(run)?validationExplorerStatus(run):buildExplorerStatus(run); | |
| const haystack=[run.run_id,run.model_id,run.target_space,run.status,run.kind,run.selected_hardware,run.requested_hardware,run.preferred_space_hardware,...(explorer.search_tokens||[])].map(x=>String(x||'').toLowerCase()).join(' '); | |
| return haystack.includes(String(query).toLowerCase()); | |
| } | |
| function runSortTimestamp(run={}){ | |
| run=safeRunObject(run); | |
| const raw=run.updated_at||run.created_at||run.started_at||run.cancelled_at||''; | |
| const ts=Date.parse(raw); | |
| if(Number.isFinite(ts))return ts; | |
| const id=String(run.run_id||''); | |
| const m=id.match(/(\d{8})[-_]?(\d{6})/); | |
| if(m){ | |
| const d=m[1],t=m[2]; | |
| return Date.parse(`${d.slice(0,4)}-${d.slice(4,6)}-${d.slice(6,8)}T${t.slice(0,2)}:${t.slice(2,4)}:${t.slice(4,6)}Z`); | |
| } | |
| return 0; | |
| } | |
| function sortRunsNewestFirst(runs=[]){ | |
| return [...validRunsList(runs)].sort((a,b)=>runSortTimestamp(b)-runSortTimestamp(a)||String(b.run_id||'').localeCompare(String(a.run_id||''))); | |
| } | |
| function filteredRuns(){ | |
| const query=state.runSearch||''; | |
| return explorerPrimaryRuns().filter(run=>{ | |
| const matchesOwn=runMatchesQuery(run,query); | |
| const linked=linkedValidationsForBuild(run.run_id); | |
| const matchesLinked=query&&linked.some(v=>runMatchesQuery(v,query)); | |
| const status=state.runStatusFilter||'all'; | |
| const statusMatch=runMatchesStatus(run,status); | |
| return statusMatch&&(matchesOwn||matchesLinked); | |
| }); | |
| } | |
| function renderRunStats(){ | |
| const query=state.runSearch||''; | |
| const builds=explorerPrimaryRuns().filter(r=>runMatchesQuery(r,query)||linkedValidationsForBuild(r.run_id).some(v=>runMatchesQuery(v,query))); | |
| const counts={all:builds.length,running:0,full_inference_success:0,validated_after_manual_space_test:0,recovered_by_manual_validation:0,recovered_by_space_test:0,partial_validation:0,manual_hardware_required:0,technical_blocker:0,failed:0,stale:0}; | |
| for(const r of builds){ | |
| const explorer=buildExplorerStatus(r); | |
| for(const key of Object.keys(counts)){ | |
| if(key==='all')continue; | |
| if(explorer.filter_buckets?.has(key))counts[key]+=1; | |
| } | |
| } | |
| document.querySelectorAll('.filter[data-status]').forEach(btn=>{ | |
| const status=btn.dataset.status||'all'; | |
| const label={all:'Builds',running:'Running',full_inference_success:'Success',validated_after_manual_space_test:'Validated',recovered_by_space_test:'Recovered by Space Test',recovered_by_manual_validation:'Recovered',partial_validation:'Partial',manual_hardware_required:'Manual',failed:'Failed',technical_blocker:'Blockers',stale:'Stale'}[status]||status; | |
| const count=counts[status]??0; | |
| btn.innerHTML=`${escapeHtml(label)} <span>${count}</span>`; | |
| btn.classList.toggle('active',status===state.runStatusFilter); | |
| }); | |
| } | |
| function runCardKind(run={}){return isValidationRunSummary(run)?'Linked test':'Build'} | |
| function runCompactStatusLabel(status){ | |
| // v193 compact labels still include legacy branch semantics: return 'Success' and return 'Failed'. | |
| return explorerDisplayLabel(status); | |
| } | |
| function runIsFinished(status){ | |
| const s=String(status||'').toLowerCase(); | |
| return Boolean(s&&( | |
| s.includes('success')||s.includes('succeed')||s.includes('failed')||s.includes('error')|| | |
| s.includes('manual')||s.includes('blocker')||s.includes('stale')|| | |
| s==='done'||s==='completed'||s==='cancelled'||s==='canceled'||s==='stopped'||s==='health_only'||s==='full_inference_candidate_health_passed'||s==='partial'||s==='partial_validation'||s==='completed_with_warnings'||s==='validated'||s==='validated_after_space_test'||s==='validated_after_manual_space_test'||s==='manual_validation_passed'||s==='manual_validated'||s==='recovered_by_space_test'||s==='recovered_by_manual_validation'||s==='auth_refresh_required'||s==='oauth_expired' | |
| )); | |
| } | |
| function runHasValidationResult(detail={},summaryOverride={}){ | |
| const summary={...(detail.summary||{}),...(summaryOverride||{})}; | |
| const smoke=detail.generation_smoke||detail.tests?.generation_smoke||summary.generation_smoke||detail.state?.generation_smoke||{}; | |
| const gate=detail.inference_gate||summary.inference_gate||{}; | |
| const schema=detail.api_schema||detail.tests?.api_schema||summary.api_schema||{}; | |
| const events=Array.isArray(detail.events)?detail.events:(Array.isArray(summary.events)?summary.events:[]); | |
| const status=String(summary.status||detail.status||detail.state?.status||'').toLowerCase(); | |
| const terminalSuccess=runMatchesStatus({status},'full_inference_success'); | |
| return Boolean( | |
| Object.keys(smoke||{}).length|| | |
| Object.keys(gate||{}).length|| | |
| Object.keys(schema||{}).length|| | |
| summary.smoke_test_passed|| | |
| summary.health_passed|| | |
| summary.latency_seconds|| | |
| summary.observed_latency_seconds|| | |
| terminalSuccess|| | |
| events.some(e=>['generation_smoke','inference_gate','api_validation','repair_validation'].includes(String(e.step||''))&&['success','done','failed','warning'].includes(String(e.status||'').toLowerCase())) | |
| ); | |
| } | |
| function runImplementationMode(run={},detail={}){return firstNonEmpty(run.implementation_mode,run.summary?.implementation_mode,run.state?.implementation_mode,run.launch?.implementation_mode,detail.summary?.implementation_mode,detail.state?.implementation_mode,detail.launch?.implementation_mode)} | |
| function runRelativeTime(run={}){ | |
| const raw=run.updated_at||run.created_at||run.started_at||run.cancelled_at||''; | |
| const ts=Date.parse(raw); | |
| if(!Number.isFinite(ts))return runStatTime(run); | |
| const diff=Math.max(0,Date.now()-ts); | |
| const mins=Math.floor(diff/60000); | |
| if(mins<1)return'now'; | |
| if(mins<60)return`${mins}m ago`; | |
| const hrs=Math.floor(mins/60); | |
| if(hrs<24)return`${hrs}h ago`; | |
| const days=Math.floor(hrs/24); | |
| if(days<7)return`${days}d ago`; | |
| return formatTime(raw); | |
| } | |
| function runPrimaryTitle(run={}){ | |
| const validation=isValidationRunSummary(run); | |
| if(validation)return firstNonEmpty(run.parent_build_run_id?`Validation for ${run.parent_build_run_id}`:'',run.target_space,run.space_id,run.run_id)||'Linked validation run'; | |
| return firstNonEmpty(run.model_id,run.target_space,run.run_id)||'Build run'; | |
| } | |
| function runSecondaryLine(run={}){ | |
| const validation=isValidationRunSummary(run); | |
| if(validation){ | |
| const parent=linkedValidationParentId(run); | |
| const parts=[parent?`Parent: ${parent}`:'Linked validation',firstNonEmpty(run.api_name,run.endpoint),runStatLatency(run),run.run_id].filter(Boolean); | |
| return parts.join(' • '); | |
| } | |
| const mode=runImplementationMode(run); | |
| const manual=buildManualValidationStatus(run); | |
| const manualText=manual.passed?'Manual validation passed':manual.failed?'Manual validation attempted':''; | |
| const linkedText=manual.linkedCount?`${manual.linkedCount} linked test${manual.linkedCount===1?'':'s'}`:''; | |
| const policy=runSpaceTestPolicy(run); | |
| const policyText=policy.mode==='complete'?'Can complete with Space Test':policy.mode==='recover'?'Can recover with Space Test':policy.mode==='blocked'?policy.label:''; | |
| const parts=[manualText,linkedText,policyText,run.target_space,mode?'Goal: '+implementationModeLabel(mode,{short:true}):'',run.selected_hardware].filter(Boolean); | |
| return parts.join(' • '); | |
| } | |
| function runCardMeta(run={}){return runSecondaryLine(run)} | |
| function renderRunRows(runs,compact=false){ | |
| return validRunsList(runs||[]).map(r=>{ | |
| // v193 legacy validation token: const status=runCanonicalStatus(r)||r.status||'unknown' | |
| const validation=isValidationRunSummary(r); | |
| const kind=runCardKind(r); | |
| const explorerStatus=validation?validationExplorerStatus(r):buildExplorerStatus(r); | |
| const status=explorerStatus.display_status; | |
| const isLoading=state.runSelectionLoadingId&&(state.runSelectionLoadingId===(r.run_id||r.summary?.run_id)); | |
| const tone=explorerStatus.display_tone||statusClass(status); | |
| const title=runPrimaryTitle(r); | |
| const secondary=runSecondaryLine(r)||r.run_id||'No metadata yet'; | |
| const time=runRelativeTime(r); | |
| const canDelete=runCanBeDeleted(status); | |
| const manual=validation?{linkedCount:0,passed:false,failed:false}:buildManualValidationStatus(r); | |
| const linkedChips=!validation&&manual.linkedCount?`<div class="linked-validation-strip ${manual.passed?'passed':manual.failed?'failed':'neutral'}"><span>${manual.passed?'Manual validation passed':manual.failed?'Manual validation attempted':'Linked Space Tests'}</span><strong>${manual.linkedCount} linked test${manual.linkedCount===1?'':'s'}</strong></div>`:''; | |
| return `<article class="run-row run-list-item ${validation?'validation-run':'build-run'} ${isLoading?'is-loading':''}" role="button" tabindex="0" data-run="${escapeHtml(r.run_id)}" title="${validation?'Linked validation run':'Build run'}" ${isLoading?'aria-busy="true"':''}> | |
| <span class="run-list-dot ${tone}" aria-hidden="true"></span> | |
| <div class="run-list-copy"> | |
| <div class="run-list-head"> | |
| <strong class="run-list-title" title="${escapeHtml(title)}">${escapeHtml(title)}</strong> | |
| <span class="run-list-kind ${validation?'validation':'build'}">${escapeHtml(kind)}</span> | |
| </div> | |
| <p class="run-list-sub" title="${escapeHtml(secondary)}">${escapeHtml(secondary)}</p> | |
| ${linkedChips} | |
| <p class="run-list-id" title="${escapeHtml(r.run_id)}">${escapeHtml(r.run_id)}</p> | |
| </div> | |
| <div class="run-list-status"> | |
| <em class="run-status-pill ${isLoading?'loading':tone}" title="${escapeHtml(isLoading?'Loading details…':explorerStatus.display_label)}">${escapeHtml(isLoading?'Loading…':explorerStatus.display_label)}</em> | |
| <time>${escapeHtml(time)}</time> | |
| </div> | |
| <button class="icon-btn danger run-delete-btn" type="button" data-run-delete="${escapeHtml(r.run_id)}" title="${canDelete?'Delete this finished run':'Delete becomes available after this run finishes'}" aria-label="Delete run ${escapeHtml(r.run_id)}" ${canDelete?'':'disabled aria-disabled="true"'}>×</button> | |
| </article>`; | |
| }).join('') | |
| } | |
| function bindRunPagination(root){ | |
| if(!root||root.dataset.boundPagination==='true')return; | |
| root.dataset.boundPagination='true'; | |
| root.addEventListener('click',e=>{ | |
| const btn=e.target.closest('[data-page-action]'); | |
| if(!btn||btn.disabled)return; | |
| state.runPage+=(btn.dataset.pageAction==='next'?1:-1); | |
| renderRunsFromCache(); | |
| }); | |
| } | |
| function renderRunPagination(total){ | |
| const root=$('runsPagination'); | |
| if(!root)return; | |
| bindRunPagination(root); | |
| const perPage=state.runsPerPage||5; | |
| const pages=Math.max(1,Math.ceil(total/perPage)); | |
| state.runPage=Math.min(Math.max(0,state.runPage||0),pages-1); | |
| if(total<=perPage){root.innerHTML='';return} | |
| root.innerHTML=`<button class="secondary small" data-page-action="prev" ${state.runPage<=0?'disabled':''}>‹</button><span>Page ${state.runPage+1} / ${pages}</span><button class="secondary small" data-page-action="next" ${state.runPage>=pages-1?'disabled':''}>›</button>`; | |
| } | |
| function isValidationRunSummary(run={}){run=safeRunObject(run);return isValidationRunDetail({summary:run,state:run,kind:run.kind,run_type:run.run_type})} | |
| function isLinkedValidationRun(run={}){return isValidationRunSummary(run)&&Boolean(linkedValidationParentId(run));} | |
| function isLegacyValidationRun(run={}){return isValidationRunSummary(run)&&!linkedValidationParentId(run);} | |
| function linkedValidationParentId(run={}){ | |
| run=safeRunObject(run); | |
| return run.parent_build_run_id||run.parentBuildRunId||run.summary?.parent_build_run_id||run.state?.parent_build_run_id||''; | |
| } | |
| function linkedValidationsForBuild(buildRunId){ | |
| if(!buildRunId)return []; | |
| return validRunsList(state.runsCache||[]).filter(r=>isLinkedValidationRun(r)&&linkedValidationParentId(r)===buildRunId); | |
| } | |
| function linkedValidationDeleteSummary(runId,detail={}){ | |
| const id=runId||detail.run_id||detail.summary?.run_id||''; | |
| const rows=linkedValidationsForBuild(id); | |
| return {count:rows.length,ids:rows.map(r=>r.run_id||r.summary?.run_id).filter(Boolean)}; | |
| } | |
| function runSpaceTestPolicy(run={}){ | |
| run=safeRunObject(run); | |
| return run.space_test_policy||run.summary?.space_test_policy||run.view?.space_test_policy||run.space_test?.policy||{}; | |
| } | |
| function runNeedsLinkedValidation(run={}){ | |
| const policy=runSpaceTestPolicy(run); | |
| return ['complete','recover'].includes(String(policy.mode||'').toLowerCase())&&policy.enabled!==false&&!buildManualValidationStatus(run).passed; | |
| } | |
| function linkedValidationRowsFromMetadata(run={}){ | |
| run=safeRunObject(run); | |
| const candidates=[ | |
| run.linked_validations, | |
| run.summary?.linked_validations, | |
| run.manual_validation_status?.linked_validations, | |
| run.summary?.manual_validation_status?.linked_validations | |
| ].filter(Boolean); | |
| const rows=[]; | |
| for(const item of candidates){ | |
| if(Array.isArray(item))rows.push(...item); | |
| else if(Array.isArray(item.validations))rows.push(...item.validations); | |
| else if(item.latest_validation)rows.push(item.latest_validation); | |
| else if(item.validation_run_id||item.run_id||item.status)rows.push(item); | |
| } | |
| return rows.filter(x=>x&&typeof x==='object'); | |
| } | |
| function linkedValidationCountFromMetadata(run={},rows=[]){ | |
| const counts=[ | |
| run.linked_validation_count, | |
| run.summary?.linked_validation_count, | |
| run.linked_validations_count, | |
| run.summary?.linked_validations_count, | |
| run.manual_validation_status?.linked_count, | |
| run.summary?.manual_validation_status?.linked_count, | |
| run.linked_validations?.count, | |
| run.summary?.linked_validations?.count | |
| ].map(Number).filter(n=>Number.isFinite(n)&&n>0); | |
| return Math.max(rows.length,...counts,0); | |
| } | |
| function linkedValidationRowStatus(row={}){ | |
| row=safeRunObject(row); | |
| return String(row.status||row.validation_status||row.result_status||row.verdict||row.effective_status||row.summary?.status||'').toLowerCase(); | |
| } | |
| function buildManualValidationStatus(run={}){ | |
| run=safeRunObject(run); | |
| const explicit=run.post_build_validation||run.effective_run_status?.post_build_validation||run.summary?.post_build_validation||run.summary?.effective_run_status?.post_build_validation||run.manual_validation_status||run.summary?.manual_validation_status||{}; | |
| const metadataRows=linkedValidationRowsFromMetadata(run); | |
| const cacheRows=linkedValidationsForBuild(run.run_id).filter(v=>!runMatchesStatus(v,'running')); | |
| const rows=[...metadataRows,...cacheRows]; | |
| const explicitStatus=String(explicit.status||explicit.validation_status||explicit.result_status||explicit.verdict||'').toLowerCase(); | |
| const metadataCount=linkedValidationCountFromMetadata(run,metadataRows); | |
| const linkedCount=Math.max(metadataCount,cacheRows.length,explicitStatus?1:0); | |
| const passed=Boolean( | |
| run.manual_validation_passed||run.summary?.manual_validation_passed|| | |
| explicitStatus==='success'||explicitStatus==='passed'||explicitStatus==='full_inference_success'||explicitStatus==='validated_after_space_test'||explicitStatus==='validated_after_manual_space_test'|| | |
| rows.some(v=>{const st=linkedValidationRowStatus(v);return st==='success'||st==='passed'||st==='full_inference_success'||st==='validated_after_space_test'||st==='validated_after_manual_space_test'||runMatchesStatus(v,'full_inference_success');}) | |
| ); | |
| const failed=Boolean( | |
| explicitStatus==='failed'||explicitStatus==='failure'||explicitStatus==='error'|| | |
| rows.some(v=>{const st=linkedValidationRowStatus(v);return st==='failed'||st==='failure'||st==='error'||runMatchesStatus(v,'failed');}) | |
| ); | |
| const latest=rows[0]||{}; | |
| return {passed,failed,linkedCount,latest,explicit,metadataRows,cacheRows}; | |
| } | |
| function buildEffectiveStatus(run={}){ | |
| // Kept for legacy callers, but now delegates to the deterministic Runs Explorer status model. | |
| return buildExplorerStatus(run).display_status; | |
| } | |
| function explorerPrimaryRuns(){ | |
| return validRunsList(state.runsCache||[]).filter(r=>!isValidationRunSummary(r)); | |
| } | |
| function runStatTime(run={}){run=safeRunObject(run);const raw=run.updated_at||run.created_at||run.started_at||run.cancelled_at||'';return raw?formatTime(raw):'—'} | |
| function runStatLatency(run={}){ | |
| run=safeRunObject(run); | |
| const latency=run.latency_seconds||run.observed_latency_seconds||run.generation_smoke?.latency_seconds||run.generation_smoke?.observed_latency_seconds; | |
| return latency?fmtSeconds(Number(latency)):''; | |
| } | |
| function runStatLatencyValue(run={}){ | |
| run=safeRunObject(run); | |
| const latency=run.latency_seconds||run.observed_latency_seconds||run.generation_smoke?.latency_seconds||run.generation_smoke?.observed_latency_seconds; | |
| const n=Number(latency); | |
| return Number.isFinite(n)&&n>0?n:null; | |
| } | |
| function percentile(values=[],p=0.5){ | |
| const nums=(values||[]).map(Number).filter(n=>Number.isFinite(n)).sort((a,b)=>a-b); | |
| if(!nums.length)return null; | |
| const idx=(nums.length-1)*p; | |
| const lo=Math.floor(idx),hi=Math.ceil(idx); | |
| if(lo===hi)return nums[lo]; | |
| return nums[lo]+(nums[hi]-nums[lo])*(idx-lo); | |
| } | |
| function pct(part,total){return total?`${Math.round((part/total)*100)}%`:'—'} | |
| function runStatsIssueCounts(runs=[]){ | |
| runs=validRunsList(runs); | |
| const counts={failed_builds:0,failed_linked_tests:0,manual_hardware:0,pi_model_mismatch:0,stale:0}; | |
| for(const r of runs){ | |
| const validation=isValidationRunSummary(r); | |
| const status=String(r.status||'').toLowerCase(); | |
| const pi=r.pi_model_resolution||{}; | |
| if(runMatchesStatus(r,'failed')){if(validation&&isLinkedValidationRun(r))counts.failed_linked_tests++;else if(!validation)counts.failed_builds++;} | |
| if(!validation&&runMatchesStatus(r,'manual_hardware_required')) counts.manual_hardware++; | |
| if(!validation&&(pi.mismatch||status.includes('model_mismatch'))) counts.pi_model_mismatch++; | |
| if(status.includes('stale')) counts.stale++; | |
| } | |
| return counts; | |
| } | |
| function runStatsCell(label,value,detail='',tone='neutral'){ | |
| return `<div class="run-stat-cell ${escapeHtml(tone)}"><span>${escapeHtml(label)}</span><strong>${escapeHtml(value)}</strong>${detail?`<em>${escapeHtml(detail)}</em>`:''}</div>`; | |
| } | |
| function renderRunAggregateStats(){ | |
| // v193 legacy stats tokens: const terminalBuilds=builds.filter(r=>!runMatchesStatus(r,'running')); buildEffectiveStatus | |
| const root=$('runStatsList'); | |
| if(!root)return; | |
| const runs=validRunsList(state.runsCache||[]); | |
| const builds=runs.filter(r=>!isValidationRunSummary(r)); | |
| const validations=runs.filter(r=>isLinkedValidationRun(r)); | |
| const buildStatuses=builds.map(r=>({run:r,status:buildExplorerStatus(r)})); | |
| const runningBuilds=buildStatuses.filter(x=>x.status.filter_buckets?.has('running')).length; | |
| const failedBuilds=buildStatuses.filter(x=>x.status.filter_buckets?.has('failed')).length; | |
| const terminalBuilds=buildStatuses.filter(x=>!x.status.filter_buckets?.has('running')); | |
| const automaticSuccess=terminalBuilds.filter(x=>x.status.automatic_status==='full_inference_success').length; | |
| const successBuilds=automaticSuccess; | |
| const effectiveSuccess=terminalBuilds.filter(x=>['full_inference_success','validated_after_space_test','validated_after_manual_space_test','manual_validated','recovered_by_space_test','recovered_by_manual_validation'].includes(x.status.display_status)).length; | |
| const recoveredBuilds=terminalBuilds.filter(x=>['recovered_by_space_test','recovered_by_manual_validation'].includes(x.status.display_status)).length; | |
| const needsValidation=terminalBuilds.filter(x=>runNeedsLinkedValidation(x.run)).length; | |
| // Legacy aggregate labels kept for regression tests: Total runs / Test response time / Typical / slowest recent / Build success / Validation pass. | |
| // Legacy formula kept for audit readability: pct(successBuilds,terminalBuilds.length) and pct(passedValidations,terminalValidations.length). | |
| const passedLinked=validations.filter(r=>!runMatchesStatus(r,'running')&&runMatchesStatus(r,'full_inference_success')).length; | |
| const terminalValidations=validations.filter(r=>!runMatchesStatus(r,'running')); | |
| const passedValidations=passedLinked; | |
| const latencies=validations.map(runStatLatencyValue).filter(v=>v!==null); | |
| const median=percentile(latencies,.5); | |
| const p95=percentile(latencies,.95); | |
| const issues=runStatsIssueCounts(runs); | |
| const issueTotal=Object.values(issues).reduce((a,b)=>a+b,0); | |
| const badge=$('runStatsBadge'); | |
| if(badge){ | |
| badge.textContent=builds.length?`${builds.length} builds · ${validations.length} linked tests`:'No builds'; | |
| badge.className='badge '+(failedBuilds||issueTotal?'warn':runningBuilds?'running':builds.length?'success':'neutral'); | |
| } | |
| if(!builds.length){ | |
| root.innerHTML='<div class="empty">No indexed Build Runs yet. Launch a build to populate stats.</div>'; | |
| return; | |
| } | |
| const issueItems=[ | |
| ['Failed builds',issues.failed_builds], | |
| ['Failed linked tests',issues.failed_linked_tests], | |
| ['Manual hardware',issues.manual_hardware], | |
| ['Pi mismatch',issues.pi_model_mismatch], | |
| ['Stale runs',issues.stale], | |
| ].filter(([,count])=>count>0); | |
| root.innerHTML=` | |
| <div class="run-stats-grid build-first-stats"> | |
| ${runStatsCell('Build Runs',String(builds.length),`${validations.length} linked Space Test${validations.length===1?'':'s'}`,'neutral')} | |
| ${runStatsCell('Build status',`${runningBuilds} running`,`${failedBuilds} failed` ,failedBuilds?'warn':runningBuilds?'running':'success')} | |
| ${runStatsCell('Automatic success',pct(automaticSuccess,terminalBuilds.length),`${automaticSuccess}/${terminalBuilds.length} finished builds`,'success')} | |
| ${runStatsCell('Effective success',pct(effectiveSuccess,terminalBuilds.length),`${effectiveSuccess}/${terminalBuilds.length} after linked tests`,'success')} | |
| ${runStatsCell('Recovered',String(recoveredBuilds),`${needsValidation} need validation/recovery`,recoveredBuilds?'success':needsValidation?'warn':'neutral')} | |
| </div> | |
| <div class="run-stats-band linked-tests-band"> | |
| <span>Linked Space Tests</span> | |
| <strong>${validations.length?`${passedLinked}/${validations.length} passed${latencies.length?` · typical ${fmtSeconds(median)} · slowest ${fmtSeconds(p95)}`:''}`:'No linked tests yet'}</strong> | |
| </div> | |
| <div class="run-stats-band ${issueItems.length?'warn':'success'}"> | |
| <span>Things to review</span> | |
| <strong>${issueItems.length?issueItems.map(([label,count])=>`${count} ${label}`).join(' · '):'Nothing to review in indexed Build Runs'}</strong> | |
| </div>`; | |
| } | |
| function rememberDeletedRun(runId){ | |
| if(!runId)return; | |
| state.deletedRuns=state.deletedRuns||{}; | |
| state.deletedRuns[runId]=Date.now(); | |
| } | |
| function isRunLocallyDeleted(runId){ | |
| if(!runId||!state.deletedRuns)return false; | |
| const ts=state.deletedRuns[runId]; | |
| if(!ts)return false; | |
| const ttl=10*60*1000; | |
| if(Date.now()-ts>ttl){delete state.deletedRuns[runId];return false;} | |
| return true; | |
| } | |
| function forgetRunEverywhere(runId){ | |
| if(!runId)return; | |
| if(state.runDetailCache)delete state.runDetailCache[runId]; | |
| if(state.runDetailRequests){ | |
| delete state.runDetailRequests[`${runId}:light`]; | |
| delete state.runDetailRequests[`${runId}:heavy`]; | |
| delete state.runDetailRequests[`${runId}:snapshot:fast`]; | |
| delete state.runDetailRequests[`${runId}:snapshot:logs`]; | |
| if(state.runExplorerHydratedAt)delete state.runExplorerHydratedAt[runId]; | |
| if(state.runExplorerHydrationInFlight)delete state.runExplorerHydrationInFlight[runId]; | |
| } | |
| if(state.documentCache)delete state.documentCache[runId]; | |
| if(state.latencyCache)delete state.latencyCache[runId]; | |
| // Legacy invariant: state.runsCache=(state.runsCache||[]).filter(r=>r.run_id!==runId) | |
| state.runsCache=validRunsList(state.runsCache||[]).filter(r=>(r.run_id||r.summary?.run_id)!==runId); | |
| document.querySelectorAll(`.run-row[data-run="${CSS.escape(runId)}"]`).forEach(row=>row.remove()); | |
| } | |
| function activeRunIds(){ | |
| return new Set(validRunsList(state.runsCache||[]).map(r=>r.run_id||r.summary?.run_id).filter(Boolean)); | |
| } | |
| function runExplorerNeedsBackgroundHydration(run={}){ | |
| run=safeRunObject(run); | |
| if(isValidationRunSummary(run))return false; | |
| const runId=run.run_id||run.summary?.run_id; | |
| if(!runId||isRunLocallyDeleted(runId))return false; | |
| const canonical=buildEffectiveStatus(run); | |
| if(['full_inference_success','failed','manual_hardware_required','technical_blocker','technical_blocker_boot_only','auth_refresh_required','stale','stopped','running'].includes(canonical))return false; | |
| return ['partial_validation','health_only','partial','completed_with_warnings','unknown',''].includes(String(canonical||'').toLowerCase()); | |
| } | |
| function scheduleRunExplorerBackgroundHydration(runs=[]){ | |
| if(typeof fetchRunViewSnapshotOnce!=='function'||typeof upsertRunExplorerFromProgress!=='function')return; | |
| state.runExplorerHydrationInFlight=state.runExplorerHydrationInFlight||{}; | |
| state.runExplorerHydratedAt=state.runExplorerHydratedAt||{}; | |
| const now=Date.now(); | |
| const candidates=validRunsList(runs).filter(run=>{ | |
| if(!runExplorerNeedsBackgroundHydration(run))return false; | |
| const runId=run.run_id||run.summary?.run_id; | |
| const last=state.runExplorerHydratedAt[runId]||0; | |
| return now-last>120000; | |
| }).slice(0,6); | |
| if(!candidates.length)return; | |
| window.setTimeout(()=>{ | |
| candidates.forEach((run,index)=>{ | |
| const runId=run.run_id||run.summary?.run_id; | |
| if(!runId||state.runExplorerHydrationInFlight[runId])return; | |
| state.runExplorerHydrationInFlight[runId]=Date.now(); | |
| state.runExplorerHydratedAt[runId]=Date.now(); | |
| window.setTimeout(async()=>{ | |
| try{ | |
| const snapshot=await fetchRunViewSnapshotOnce(runId,{includeJobLogs:false}); | |
| if(snapshot&&validRunObject({run_id:snapshot.run_id||snapshot.summary?.run_id||runId}))upsertRunExplorerFromProgress(snapshot); | |
| }catch(err){console.warn('background Run Explorer hydration failed',runId,err)} | |
| finally{delete state.runExplorerHydrationInFlight[runId];} | |
| },index*160); | |
| }); | |
| },140); | |
| } | |
| function associatedSpaceFromDetail(detail={},summaryOverride={}){ | |
| const summary={...(detail.summary||{}),...(summaryOverride||{})}; | |
| const candidates=[summary.target_space,summary.target_space_id,detail.target_space,detail.target_space_id,detail.state?.target_space,detail.launch?.target_space,detail.links?.target_space]; | |
| for(const value of candidates){ | |
| const text=String(value||'').trim().replace('https://huggingface.co/spaces/','').replace(/^\/+|\/+$/g,''); | |
| if(text&&text.includes('/'))return text; | |
| } | |
| const urls=[summary.target_space_url,detail.target_space_url,detail.state?.target_space_url,detail.launch?.target_space_url,detail.links?.target_space_url]; | |
| for(const url of urls){ | |
| const text=String(url||''); | |
| const marker='huggingface.co/spaces/'; | |
| if(text.includes(marker))return text.split(marker,1)[1].split('?',1)[0].split('#',1)[0].replace(/^\/+|\/+$/g,''); | |
| } | |
| return ''; | |
| } | |
| function runCanOfferSpaceDeletion(kind,detail={},summary={}){ | |
| const normalizedKind=String(kind||summary.kind||detail.kind||detail.state?.kind||detail.launch?.kind||'').toLowerCase(); | |
| if(normalizedKind.includes('validation')||normalizedKind.includes('space_test'))return false; | |
| return Boolean(associatedSpaceFromDetail(detail,summary)); | |
| } | |
| function runCanBeDeleted(status){ | |
| const s=String(status||'').toLowerCase(); | |
| if(!s||s==='unknown')return true; | |
| return runIsFinished(s); | |
| } | |
| // v105 delegated row binding preserves v98 invariant: renderRunAggregateStats();document.querySelectorAll('.run-row[data-run]') | |
| function bindRunRowEvents(root){ | |
| if(!root||root.dataset.boundRuns==='true')return; | |
| root.dataset.boundRuns='true'; | |
| root.addEventListener('click',e=>{ | |
| const deleteBtn=e.target.closest('[data-run-delete]'); | |
| if(deleteBtn){e.preventDefault();e.stopPropagation();if(deleteBtn.disabled||deleteBtn.getAttribute('aria-disabled')==='true')return;const runId=deleteBtn.dataset.runDelete;const cached=cachedRunById(runId)||{};deleteRunById(runId,{kind:isValidationRunSummary(cached)?'validation':'active',detail:optimisticDetailFromSummary(cached),buttonId:null});return} | |
| const row=e.target.closest('.run-row[data-run]'); | |
| if(row)selectRun(row.dataset.run); | |
| }); | |
| root.addEventListener('keydown',e=>{ | |
| if(e.key!=='Enter'&&e.key!==' ')return; | |
| const row=e.target.closest('.run-row[data-run]'); | |
| if(!row||e.target.closest('[data-run-delete]'))return; | |
| e.preventDefault();selectRun(row.dataset.run); | |
| }); | |
| } | |
| function renderRunsFromCache(){ | |
| state.runsCache=sortRunsNewestFirst(validRunsList(state.runsCache||[])); | |
| const runs=filteredRuns(); | |
| const perPage=state.runsPerPage||5; | |
| state.runPage=Math.min(Math.max(0,state.runPage||0),Math.max(0,Math.ceil(runs.length/perPage)-1)); | |
| const visible=runs.slice(state.runPage*perPage,state.runPage*perPage+perPage); | |
| const selectedValidation=state.centerTab==='validate'&&state.validationRunId?cachedRunById(state.validationRunId):null; | |
| const selectedId=linkedValidationParentId(selectedValidation)||state.runId; | |
| const signature=JSON.stringify({ids:visible.map(r=>[r.run_id,runCanonicalStatus(r),buildEffectiveStatus(r),r.status,r.updated_at,r.target_space,r.model_id,r.latency_seconds,r.observed_latency_seconds,r.recommended_zero_gpu_duration_seconds,r.recommended_zerogpu_duration_seconds,r.manual_validation_passed,r.effective_status,linkedValidationsForBuild(r.run_id).map(v=>[v.run_id,runCanonicalStatus(v),v.updated_at])]),filter:state.runStatusFilter,search:state.runSearch,page:state.runPage,selected:selectedId}); | |
| for(const [id,compact] of [['runsTableHome',true],['runsTable',false]]){ | |
| const root=$(id);if(!root)continue;bindRunRowEvents(root); | |
| if(root.dataset.signature!==signature){ | |
| root.innerHTML=renderRunRows(visible,compact)||'<div class="empty">No Build Runs match this filter.</div>'; | |
| root.dataset.signature=signature; | |
| } | |
| } | |
| renderRunStats();renderRunPagination(runs.length);renderRunAggregateStats(); | |
| document.querySelectorAll('.run-row').forEach(row=>row.classList.toggle('selected',Boolean(selectedId)&&row.dataset.run===selectedId)); | |
| scheduleRunExplorerBackgroundHydration(visible); | |
| } | |
| function mergeRunExplorerTerminalLocks(runs=[]){ | |
| if(typeof state==='undefined'||!state.validationTerminalByRun)return runs||[]; | |
| return validRunsList(runs).map(run=>{ | |
| const validation=isValidationRunSummary(run); | |
| const runId=run.run_id||run.summary?.run_id||''; | |
| const terminal=validation&&runId?state.validationTerminalByRun[runId]:null; | |
| if(!terminal)return run; | |
| return {...run,status:terminal.canonical,validation_status:terminal.canonical,result_status:terminal.canonical,summary:{...(run.summary||{}),status:terminal.canonical,validation_status:terminal.canonical,result_status:terminal.canonical}}; | |
| }); | |
| } | |
| async function loadRuns(forceNetwork=false){const stale=Date.now()-(state.runsLastLoaded||0)>45000;const shouldFetch=forceNetwork||!state.runsCache.length||stale;if(!shouldFetch){renderRunsFromCache();return state.runsCache||[]}if(state.runsLoadPromise&&!forceNetwork)return state.runsLoadPromise;document.querySelectorAll('.runs-panel,.full-runs-panel').forEach(x=>x.classList.add('is-refreshing'));state.runsLoadPromise=apiGet(`/api/runs?limit=100&bucket_name=${encodeURIComponent(state.bucketName)}`).then(data=>{// Legacy invariant: .filter(r=>!isRunLocallyDeleted(r.run_id)) | |
| state.runsCache=sortRunsNewestFirst(mergeRunExplorerTerminalLocks(validRunsList(data.runs||[]).filter(r=>!isRunLocallyDeleted(r.run_id||r.summary?.run_id))));state.runsLastLoaded=Date.now();if(data.bucket_source)state.bucketSource=data.bucket_source;renderRunsFromCache();return state.runsCache}).catch(e=>{for(const id of ['runsTable','runsTableHome']){const root=$(id);if(root)root.textContent='Could not load runs: '+e.message}if(forceNetwork)console.warn(e);return state.runsCache||[]}).finally(()=>{state.runsLoadPromise=null;document.querySelectorAll('.runs-panel,.full-runs-panel').forEach(x=>x.classList.remove('is-refreshing'))});return state.runsLoadPromise} | |
| function cachedRunById(runId){ | |
| if(isRunLocallyDeleted(runId))return null; | |
| return validRunsList(state.runsCache||[]).find(r=>(r.run_id||r.summary?.run_id)===runId)||null; | |
| } | |
| function optimisticDetailFromSummary(summary={}){ | |
| if(!summary)return null; | |
| return { | |
| run_id:summary.run_id, | |
| bucket_source:summary.bucket_source||state.bucketSource, | |
| summary:{...summary,_optimistic:true}, | |
| state:{ | |
| status:summary.status, | |
| model_id:summary.model_id, | |
| target_space:summary.target_space, | |
| selected_hardware:summary.selected_hardware, | |
| job_id:summary.job_id, | |
| job_url:summary.job_url, | |
| kind:summary.kind, | |
| }, | |
| events:summary.events||[], | |
| report:'', | |
| files:summary.files||[], | |
| generation_smoke:summary.generation_smoke||{}, | |
| inference_gate:summary.inference_gate||{}, | |
| api_schema:summary.api_schema||{}, | |
| view:{ | |
| run_id:summary.run_id, | |
| header:{ | |
| title:summary.run_id||'Selected run', | |
| status:summary.status||'unknown', | |
| raw_status:summary.status||'unknown', | |
| model:summary.model_id||'—', | |
| space:summary.target_space||'—', | |
| }, | |
| links:{ | |
| job_url:summary.job_url||'', | |
| space_url:summary.target_space_url||'', | |
| artifacts_url:summary.artifacts_url||'', | |
| }, | |
| activity:[], | |
| }, | |
| }; | |
| } | |
| function explorerStatusFromSnapshot(p={}, cached={}){ | |
| // v193: the coarse Active Run view header must never be the only reason to promote Success. Legacy tokens: smokeStatus==='success' gateStatus==='full_inference_success' p.generation_smoke?.ok===true return explicitSummary||explicitState||viewStatus return 'full_inference_success' | |
| const merged={ | |
| ...(cached||{}), | |
| ...(p.summary||{}), | |
| status:p.summary?.status||p.state?.status||p.status||cached.status||cached.summary?.status||'unknown', | |
| summary:{...(cached.summary||{}),...(p.summary||{})}, | |
| state:{...(cached.state||{}),...(p.state||{})}, | |
| inference_gate:p.inference_gate||p.summary?.inference_gate||cached.inference_gate||cached.summary?.inference_gate||{}, | |
| generation_smoke:p.generation_smoke||p.summary?.generation_smoke||cached.generation_smoke||cached.summary?.generation_smoke||{}, | |
| test_result:p.test_result||p.summary?.test_result||cached.test_result||cached.summary?.test_result||{}, | |
| }; | |
| return buildAutomaticStatus(merged); | |
| } | |
| function upsertRunExplorerFromProgress(p={}){ | |
| const runId=p.run_id||p.summary?.run_id||state.runId; | |
| if(!runId||isRunLocallyDeleted(runId))return; | |
| const summary={ | |
| ...(cachedRunById(runId)||{}), | |
| ...(p.summary||{}), | |
| run_id:runId, | |
| status:explorerStatusFromSnapshot(p,cachedRunById(runId)||{}), | |
| updated_at:p.state?.updated_at||p.summary?.updated_at||p.updated_at||new Date().toISOString(), | |
| model_id:p.summary?.model_id||p.state?.model_id||p.model_id, | |
| target_space:p.summary?.target_space||p.state?.target_space, | |
| target_space_url:p.summary?.target_space_url||p.links?.target_space_url||p.links?.space_url||p.view?.links?.target_space_url||p.view?.links?.space_url, | |
| selected_hardware:p.summary?.selected_hardware||p.state?.selected_hardware, | |
| latency_seconds:p.summary?.latency_seconds||p.generation_smoke?.latency_seconds||p.state?.generation_smoke?.latency_seconds, | |
| observed_latency_seconds:p.summary?.observed_latency_seconds||p.generation_smoke?.observed_latency_seconds||p.generation_smoke?.latency_seconds, | |
| recommended_zero_gpu_duration_seconds:p.summary?.recommended_zero_gpu_duration_seconds||p.generation_smoke?.recommended_zero_gpu_duration_seconds||p.generation_smoke?.recommended_zerogpu_duration_seconds, | |
| recommended_zerogpu_duration_seconds:p.summary?.recommended_zerogpu_duration_seconds||p.generation_smoke?.recommended_zerogpu_duration_seconds||p.generation_smoke?.recommended_zero_gpu_duration_seconds, | |
| kind:p.summary?.kind||p.state?.kind||'universal_model_card_builder', | |
| parent_build_run_id:p.summary?.parent_build_run_id||p.state?.parent_build_run_id, | |
| manual_validation_passed:p.summary?.manual_validation_passed||p.manual_validation_status?.status==='success', | |
| effective_status:p.summary?.effective_status||p.manual_validation_status?.effective_status, | |
| bucket_source:p.bucket_source||p.summary?.bucket_source||state.bucketSource, | |
| }; | |
| state.runsCache=validRunsList(state.runsCache||[]); | |
| const idx=state.runsCache.findIndex(r=>(r.run_id||r.summary?.run_id)===runId); | |
| if(idx>=0)state.runsCache[idx]={...state.runsCache[idx],...summary}; | |
| else state.runsCache.unshift(summary); | |
| const parentId=summary.parent_build_run_id||linkedValidationParentId(summary); | |
| if(parentId&&isValidationRunSummary(summary)){ | |
| const parentIdx=state.runsCache.findIndex(r=>(r.run_id||r.summary?.run_id)===parentId); | |
| if(parentIdx>=0){ | |
| const passed=validationExplorerStatus(summary).display_status==='full_inference_success'; | |
| state.runsCache[parentIdx]={...state.runsCache[parentIdx],manual_validation_passed:state.runsCache[parentIdx].manual_validation_passed||passed,post_build_status:passed?'validated_after_space_test':state.runsCache[parentIdx].post_build_status,effective_status:passed?'validated_after_space_test':state.runsCache[parentIdx].effective_status,updated_at:summary.updated_at||state.runsCache[parentIdx].updated_at}; | |
| } | |
| } | |
| state.runsLastLoaded=Date.now(); | |
| renderRunsFromCache(); | |
| if(typeof renderRunStats==='function')renderRunStats(state.runsCache||[]); | |
| } | |
| function renderRunSelectionPreview(runId){ | |
| const cached=cachedRunById(runId); | |
| if(!cached)return; | |
| const detail=optimisticDetailFromSummary(cached); | |
| if(isValidationRunDetail(detail)){const parent=linkedValidationParentId(cached)||detail.summary?.parent_build_run_id||detail.state?.parent_build_run_id;if(parent){selectRun(parent);return;}showValidationRunDetail(detail);return} | |
| switchCenterTab('active'); | |
| if(typeof requestSpaceTestContextResetForBuild==='function')requestSpaceTestContextResetForBuild(runId); | |
| renderRunDetail(detail); | |
| setText('progressTitle',runId); | |
| const explorer=buildExplorerStatus(cached); | |
| setText('progressStatus',explorer.display_label||'Loading'); | |
| const statusEl=$('progressStatus'); | |
| if(statusEl)statusEl.className='badge '+(explorer.display_tone||statusClass(explorer.display_status||'')); | |
| setText('currentStep','Loading run details…'); | |
| setText('lastEvent','Fetching latest events and progress…'); | |
| setText('progressPercent',buildExplorerStatus(cached).display_status==='full_inference_success'?'100%':'—'); | |
| } | |
| function centerTabTouchedDuringRunSelection(selectionSeq){ | |
| return Boolean(selectionSeq&&state.centerTabUserTouchedSelectionSeq===selectionSeq); | |
| } | |
| function cachedRunDetail(runId,heavy=false){ | |
| const entry=state.runDetailCache?.[runId]; | |
| if(!entry)return null; | |
| const fresh=Date.now()-(entry.ts||0)<(state.runDetailCacheTtlMs||300000); | |
| if(!fresh)return null; | |
| if(heavy&&!entry.heavy)return null; | |
| return entry.detail||null; | |
| } | |
| function rememberRunDetail(runId,detail,heavy=false){ | |
| if(!runId||!detail)return; | |
| state.runDetailCache=state.runDetailCache||{}; | |
| const previous=state.runDetailCache[runId]||{}; | |
| state.runDetailCache[runId]={detail,heavy:Boolean(heavy||previous.heavy),ts:Date.now()}; | |
| } | |
| function restoreRunRowStatusLabel(row){ | |
| // v193 legacy loading token: const label=runCompactStatusLabel(status||cached.status||'unknown'); pill.textContent=label | |
| if(!row)return; | |
| const runId=row.dataset.run; | |
| const cached=cachedRunById(runId)||{}; | |
| const explorer=isValidationRunSummary(cached)?validationExplorerStatus(cached):buildExplorerStatus(cached); | |
| const status=explorer.display_status||cached.status||'unknown'; | |
| const pill=row.querySelector('.run-status-pill'); | |
| if(pill){ | |
| pill.textContent=explorer.display_label||runCompactStatusLabel(status); | |
| pill.title=explorer.display_label||badgeLabel(status); | |
| const tone=explorer.display_tone||statusClass(status); | |
| pill.className=`run-status-pill ${tone}`; | |
| pill.removeAttribute('aria-busy'); | |
| } | |
| const dot=row.querySelector('.run-list-dot'); | |
| if(dot)dot.className=`run-list-dot ${explorer.display_tone||statusClass(status)}`; | |
| } | |
| function setCenterWorkspaceLoading(runId,loading=true){ | |
| const workspace=document.querySelector('.center-stack'); | |
| if(!workspace)return; | |
| const active=Boolean(loading&&runId); | |
| workspace.classList.toggle('is-run-loading',active); | |
| if(active){ | |
| workspace.setAttribute('aria-busy','true'); | |
| workspace.dataset.loadingRun=runId; | |
| }else{ | |
| workspace.removeAttribute('aria-busy'); | |
| delete workspace.dataset.loadingRun; | |
| } | |
| } | |
| function setRunSelectionLoading(runId,loading=true){ | |
| const next=loading?runId:null; | |
| const previous=state.runSelectionLoadingId; | |
| if(previous&&!loading){ | |
| document.querySelectorAll(`.run-row[data-run="${CSS.escape(previous)}"]`).forEach(restoreRunRowStatusLabel); | |
| } | |
| if(state.runSelectionLoadingId===next){ | |
| setCenterWorkspaceLoading(next,Boolean(next)); | |
| if(!loading)document.querySelectorAll('.run-row.is-loading').forEach(row=>{row.classList.remove('is-loading');row.removeAttribute('aria-busy');restoreRunRowStatusLabel(row);}); | |
| return; | |
| } | |
| state.runSelectionLoadingId=next; | |
| setCenterWorkspaceLoading(next,Boolean(next)); | |
| document.querySelectorAll('.run-row[data-run]').forEach(row=>{ | |
| const active=Boolean(next)&&row.dataset.run===next; | |
| row.classList.toggle('is-loading',active); | |
| if(active){ | |
| row.setAttribute('aria-busy','true'); | |
| const pill=row.querySelector('.run-status-pill'); | |
| if(pill){pill.textContent='Loading…';pill.title='Loading details…';pill.className='run-status-pill loading';pill.setAttribute('aria-busy','true');} | |
| } | |
| else{row.removeAttribute('aria-busy');restoreRunRowStatusLabel(row);} | |
| }); | |
| } | |
| function fetchRunViewSnapshotOnce(runId,options={}){ | |
| state.runDetailRequests=state.runDetailRequests||{}; | |
| const includeJobLogs=Boolean(options.includeJobLogs); | |
| const key=`${runId}:snapshot:${includeJobLogs?'logs':'fast'}`; | |
| if(state.runDetailRequests[key])return state.runDetailRequests[key]; | |
| const url=`/api/runs/${encodeURIComponent(runId)}/progress?bucket_name=${encodeURIComponent(state.bucketName)}${includeJobLogs?'&include_job_logs=1':''}`; | |
| const promise=apiGet(url) | |
| .finally(()=>{delete state.runDetailRequests[key]}); | |
| state.runDetailRequests[key]=promise; | |
| return promise; | |
| } | |
| function renderRunViewSnapshot(snapshot={}){ | |
| const runId=snapshot.run_id||snapshot.summary?.run_id||snapshot.view?.run_id||state.runId; | |
| if(runId&&state.runId&&runId!==state.runId)return; | |
| state.activeRunProgress=snapshot; | |
| if(snapshot.bucket_source)state.bucketSource=snapshot.bucket_source; | |
| document.body.classList.add('rendering-run-snapshot'); | |
| try{ | |
| if(typeof renderProgress==='function')renderProgress(snapshot); | |
| if(typeof renderEvents==='function')renderEvents(snapshot.events||[]); | |
| renderRunDetail(snapshot); | |
| if(typeof renderMetrics==='function')renderMetrics(snapshot); | |
| if(typeof renderActiveRunActions==='function')renderActiveRunActions({...snapshot.summary,bucket_source:snapshot.bucket_source},snapshot); | |
| if(typeof renderRunDocuments==='function')renderRunDocuments({...snapshot,summary:{...snapshot.summary,bucket_source:snapshot.bucket_source}}); | |
| if(typeof renderAgentRecovery==='function')renderAgentRecovery(snapshot); | |
| if(typeof renderBlockers==='function')renderBlockers(snapshot); | |
| if(typeof setQuickLinks==='function')setQuickLinks({...snapshot.links,...snapshot.view?.links,bucket_source:snapshot.bucket_source,run_id:runId},snapshot); | |
| if(typeof upsertRunExplorerFromProgress==='function')upsertRunExplorerFromProgress(snapshot); | |
| }finally{ | |
| requestAnimationFrame(()=>document.body.classList.remove('rendering-run-snapshot')); | |
| } | |
| } | |
| function fetchRunDetailOnce(runId,heavy=false){ | |
| state.runDetailRequests=state.runDetailRequests||{}; | |
| const key=`${runId}:${heavy?'heavy':'light'}`; | |
| if(state.runDetailRequests[key])return state.runDetailRequests[key]; | |
| const promise=apiGet(`/api/runs/${encodeURIComponent(runId)}?bucket_name=${encodeURIComponent(state.bucketName)}&include_heavy=${heavy?'true':'false'}`) | |
| .finally(()=>{delete state.runDetailRequests[key]}); | |
| state.runDetailRequests[key]=promise; | |
| return promise; | |
| } | |
| async function selectRun(runId){ | |
| // Keep the user on the current tab while refreshing the selected run panel. | |
| // v190.9: render a cached shell immediately, then hydrate from one coherent | |
| // snapshot instead of light→heavy→progress fragments arriving out of order. | |
| // Legacy invariant: cachedHeavy||cachedLight used to hydrate fast detail; rememberRunDetail(runId,full,true) was replaced by a snapshot cache. | |
| // Legacy latency invariant: renderRunSelectionPreview(runId) happens before any apiGet(`/api/runs/...) detail request; include_heavy=false/include_heavy=true are no longer used in this path because the fast snapshot endpoint is coherent and does not fetch Job logs on selection; heavy run hydration failed is now covered by snapshot hydration errors. | |
| if(!runId)return; | |
| if(isRunLocallyDeleted(runId)){ | |
| forgetRunEverywhere(runId); | |
| renderRunsFromCache(); | |
| showMessage('This run was deleted and is no longer available.','warning'); | |
| return; | |
| } | |
| const selectionSeq=(state.runSelectionSeq||0)+1; | |
| state.runSelectionSeq=selectionSeq; | |
| document.querySelectorAll('.run-row').forEach(row=>row.classList.toggle('selected',row.dataset.run===runId)); | |
| setRunSelectionLoading(runId,true); | |
| const localDetail=cachedRunDetail(runId,true)||cachedRunDetail(runId,false)||optimisticDetailFromSummary(cachedRunById(runId)); | |
| if(localDetail){ | |
| const parentId=localDetail.parent_build_run_id||localDetail.summary?.parent_build_run_id||localDetail.state?.parent_build_run_id; | |
| if(isValidationRunDetail(localDetail)&&parentId){ | |
| showMessage(`Opening parent Build Run for linked validation ${runId}.`,'info'); | |
| runId=parentId; | |
| }else if(isValidationRunDetail(localDetail))showValidationRunDetail(localDetail); | |
| else{switchCenterTab('active');setBuildModeInspecting(runId);state.runId=runId;if(typeof requestSpaceTestContextResetForBuild==='function')requestSpaceTestContextResetForBuild(runId);renderRunDetail(localDetail);} | |
| }else{ | |
| renderRunSelectionPreview(runId); | |
| } | |
| try{ | |
| const snapshot=await fetchRunViewSnapshotOnce(runId,{includeJobLogs:false}); | |
| if(selectionSeq!==state.runSelectionSeq)return; | |
| if(isRunLocallyDeleted(runId)||((snapshot.run_id||snapshot.summary?.run_id)&&runId!==(snapshot.run_id||snapshot.summary?.run_id)))return; | |
| rememberRunDetail(runId,snapshot,true); | |
| if(isValidationRunDetail(snapshot)){ | |
| const parentId=snapshot.parent_build_run_id||snapshot.summary?.parent_build_run_id||snapshot.state?.parent_build_run_id; | |
| if(parentId){ | |
| const parentSnapshot=await fetchRunViewSnapshotOnce(parentId); | |
| rememberRunDetail(parentId,parentSnapshot,true); | |
| if(!centerTabTouchedDuringRunSelection(selectionSeq)) switchCenterTab('active'); | |
| setBuildModeInspecting(parentId); | |
| state.runId=parentId; | |
| if(typeof requestSpaceTestContextResetForBuild==='function')requestSpaceTestContextResetForBuild(parentId); | |
| renderRunViewSnapshot(parentSnapshot); | |
| setRunSelectionLoading(runId,false); | |
| }else{showValidationRunDetail(snapshot);setRunSelectionLoading(runId,false);} | |
| return; | |
| } | |
| if(!centerTabTouchedDuringRunSelection(selectionSeq)) switchCenterTab('active'); | |
| setBuildModeInspecting(runId); | |
| state.runId=runId; | |
| if(typeof requestSpaceTestContextResetForBuild==='function')requestSpaceTestContextResetForBuild(runId); | |
| renderRunViewSnapshot(snapshot); | |
| setRunSelectionLoading(runId,false); | |
| const status=String(snapshot.view?.header?.status||snapshot.status||snapshot.summary?.status||snapshot.state?.status||'').toLowerCase(); | |
| if(runCanBeDeleted(status)||TERMINAL_STATUSES.has(status)){ | |
| if(state.poll){clearInterval(state.poll);state.poll=null;} | |
| }else{ | |
| startPolling(runId,{deferFirstTick:true}); | |
| window.setTimeout(async()=>{ | |
| if(state.runId!==runId||selectionSeq!==state.runSelectionSeq)return; | |
| try{ | |
| const logSnapshot=await fetchRunViewSnapshotOnce(runId,{includeJobLogs:true}); | |
| if(state.runId===runId&&selectionSeq===state.runSelectionSeq)renderRunViewSnapshot(logSnapshot); | |
| }catch(err){console.warn('background run log hydration failed',err)} | |
| },900); | |
| } | |
| }catch(e){ | |
| if(selectionSeq===state.runSelectionSeq)setRunSelectionLoading(runId,false); | |
| showMessage(`Could not load run snapshot: ${e.message}`,'error'); | |
| const report=$('reportPreview');if(report)report.textContent='Could not load run snapshot: '+e.message; | |
| } | |
| } | |
| function runDeletionContext(runId,options={}){ | |
| const kind=options.kind==='validation'?'validation':'active'; | |
| const explicit=options.detail||{}; | |
| const candidate=kind==='validation'?(explicit.run_id||explicit.summary?.run_id?explicit:state.validationDetail||{}):(explicit.run_id||explicit.summary?.run_id?explicit:state.selectedRunDetail||state.activeRunProgress||{}); | |
| const summary=candidate.summary||{}; | |
| const resolvedRunId=runId||summary.run_id||candidate.run_id||(kind==='validation'?state.validationRunId:state.runId); | |
| return {kind,runId:resolvedRunId,detail:candidate,summary}; | |
| } | |
| function clearDeletedRunState(runId,kind){ | |
| if(!runId)return; | |
| if(state.runId===runId){ | |
| if(state.poll){clearInterval(state.poll);state.poll=null} | |
| state.runId=null; | |
| state.activeRunProgress=null; | |
| state.selectedRunDetail=null; | |
| state.activeLinks={}; | |
| clearSavedRun(); | |
| resetRunDetails(); | |
| } | |
| if(state.validationRunId===runId||kind==='validation'){ | |
| if(state.validationRunId===runId)stopValidationPolling(); | |
| if(state.validationDetail?.run_id===runId||state.validationDetail?.summary?.run_id===runId||kind==='validation')state.validationDetail=null; | |
| if(state.validationRunId===runId)state.validationRunId=null; | |
| if(typeof resetValidationRunView==='function')resetValidationRunView({reason:'deleted'}); | |
| else { | |
| renderValidationStatus({status:'idle',run_id:'—',events:[],message:'Validation run deleted.'}); | |
| setText('spaceTestOutput','—'); | |
| setText('spaceTestLatency','—'); | |
| setText('spaceTestVerdict','Validation run deleted.'); | |
| } | |
| const btn=$('deleteValidationRun');if(btn){btn.disabled=true;btn.onclick=null;} | |
| } | |
| if(state.selectedRunDetail?.run_id===runId||state.selectedRunDetail?.summary?.run_id===runId)state.selectedRunDetail=null; | |
| } | |
| function ensureDeleteRunDialog(){ | |
| let modal=$('deleteRunDialog'); | |
| if(modal)return modal; | |
| modal=document.createElement('div'); | |
| modal.id='deleteRunDialog'; | |
| modal.className='delete-run-modal'; | |
| modal.hidden=true; | |
| modal.innerHTML=`<div class="delete-run-backdrop" data-delete-cancel></div> | |
| <section class="delete-run-card" role="dialog" aria-modal="true" aria-labelledby="deleteRunTitle" aria-describedby="deleteRunBody"> | |
| <button class="delete-run-close" type="button" data-delete-cancel aria-label="Close">×</button> | |
| <div class="delete-run-icon" aria-hidden="true">⌫</div> | |
| <div class="delete-run-copy"> | |
| <span class="delete-run-kicker" id="deleteRunKicker">Delete run</span> | |
| <h3 id="deleteRunTitle">Delete this run?</h3> | |
| <p id="deleteRunBody">This removes the run folder from your Hugging Face Storage Bucket.</p> | |
| </div> | |
| <div class="delete-run-meta" id="deleteRunMeta"></div> | |
| <label class="delete-space-option" id="deleteSpaceOption" hidden> | |
| <input type="checkbox" id="deleteAssociatedSpace" /> | |
| <span><strong>Also delete associated Space</strong><em id="deleteAssociatedSpaceLabel">—</em></span> | |
| </label> | |
| <div class="delete-run-warning" id="deleteRunWarning" hidden></div> | |
| <div class="delete-run-actions"> | |
| <button class="secondary" type="button" data-delete-cancel>Keep run</button> | |
| <button class="primary danger" type="button" data-delete-confirm>Delete run</button> | |
| </div> | |
| </section>`; | |
| document.body.appendChild(modal); | |
| return modal; | |
| } | |
| function confirmRunDeletion({runId,kind='active',status='',detail={}}={}){ | |
| if(state.deleteModalPromise&&state.deleteModalRunId===runId)return state.deleteModalPromise; | |
| if(state.deleteModalPromise)return state.deleteModalPromise; | |
| state.deleteModalRunId=runId; | |
| state.deleteModalPromise=new Promise(resolve=>{ | |
| const modal=ensureDeleteRunDialog(); | |
| const confirmBtn=modal.querySelector('[data-delete-confirm]'); | |
| const cancelEls=modal.querySelectorAll('[data-delete-cancel]'); | |
| const title=$('deleteRunTitle'); | |
| const body=$('deleteRunBody'); | |
| const kicker=$('deleteRunKicker'); | |
| const meta=$('deleteRunMeta'); | |
| const warning=$('deleteRunWarning'); | |
| const spaceOption=$('deleteSpaceOption'); | |
| const spaceCheckbox=$('deleteAssociatedSpace'); | |
| const spaceLabel=$('deleteAssociatedSpaceLabel'); | |
| const normalized=canonicalStatusForDeletion({kind,detail:{...(detail||{}),status:status||detail.status,summary:{...(detail.summary||{}),status:status||detail.summary?.status}}}); | |
| const active=runMatchesStatus({status:normalized,kind:kind==='validation'?'validate_existing_space':detail.kind,run_type:kind==='validation'?'validation':detail.run_type},'running'); | |
| const label=kind==='validation'?'validation run':'build run'; | |
| const associatedSpace=associatedSpaceFromDetail(detail,detail.summary||{}); | |
| const canDeleteSpace=runCanOfferSpaceDeletion(kind,detail,detail.summary||{}); | |
| const linkedDelete=kind==='validation'?{count:0,ids:[]}:linkedValidationDeleteSummary(runId,detail); | |
| kicker.textContent=kind==='validation'?'Space Test deletion':'Build run deletion'; | |
| title.textContent=`Delete this ${label}?`; | |
| body.textContent=kind==='validation' | |
| ? 'This removes only this validation run’s linked Space Test artifacts. The parent Build Run and generated Space will not be deleted. The tested Space will not be deleted.' | |
| : (linkedDelete.count?`This removes this Build Run’s bucket artifacts and ${linkedDelete.count} linked Space Test validation run${linkedDelete.count===1?'':'s'}. The generated Space is kept unless you explicitly choose to delete it below.`:'This removes this Build Run’s bucket artifacts, logs, state, traces and report. The generated Space is kept unless you explicitly choose to delete it below.'); | |
| meta.innerHTML=`<span><strong>Run</strong><code>${escapeHtml(runId||'—')}</code></span><span><strong>Type</strong>${escapeHtml(kind==='validation'?'Linked Space Test':'Build')}</span><span><strong>Status</strong>${escapeHtml(badgeLabel(normalized))}</span>${associatedSpace?`<span><strong>Space</strong><code>${escapeHtml(associatedSpace)}</code></span>`:''}${linkedDelete.count?`<span><strong>Linked tests</strong>${linkedDelete.count}</span>`:''}`; | |
| if(spaceOption&&spaceCheckbox&&spaceLabel){ | |
| spaceCheckbox.checked=false; | |
| spaceOption.hidden=!canDeleteSpace; | |
| spaceLabel.textContent=associatedSpace||'No associated Space detected'; | |
| spaceCheckbox.onchange=()=>{confirmBtn.textContent=spaceCheckbox.checked?'Delete run and Space':(active?'Delete stored files':'Delete run');warning.hidden=false;warning.textContent=spaceCheckbox.checked?`This will permanently delete the Hugging Face Space repository ${associatedSpace}. This cannot be undone.`:(active?'This run still looks active. Deleting only removes stored run files; it does not cancel a running Job.':(kind==='validation'?'Deletion is permanent for this validation run folder.':'Deletion is permanent for this run folder.'));}; | |
| } | |
| warning.hidden=!active&&!canDeleteSpace; | |
| warning.textContent=active?'This run still looks active. Deleting only removes stored run files; it does not cancel a running Job.':(kind==='validation'?'Deletion is permanent for this validation run folder.':(canDeleteSpace?'Optional Space deletion is destructive and cannot be undone.':'Deletion is permanent for this run folder.')); | |
| confirmBtn.textContent=active?'Delete stored files':'Delete run'; | |
| const previousFocus=document.activeElement; | |
| let done=false; | |
| let submitted=false; | |
| const close=value=>{ | |
| if(done)return;done=true; | |
| modal.hidden=true; | |
| modal.classList.remove('is-open','is-deleting'); | |
| document.removeEventListener('keydown',onKey); | |
| cancelEls.forEach(el=>{el.removeEventListener('click',onCancel);el.disabled=false;el.removeAttribute('aria-disabled')}); | |
| confirmBtn.removeEventListener('click',onConfirm); | |
| confirmBtn.disabled=false; | |
| if(spaceCheckbox)spaceCheckbox.onchange=null; | |
| try{previousFocus&&previousFocus.focus&&previousFocus.focus()}catch(_){} | |
| state.deleteModalPromise=null; | |
| state.deleteModalRunId=null; | |
| if(!submitted)resolve(value); | |
| }; | |
| const setDeleting=()=>{ | |
| modal.classList.add('is-deleting'); | |
| title.textContent=kind==='validation'?'Deleting this validation run…':'Deleting this run…'; | |
| body.textContent=kind==='validation'?'Removing linked validation artifacts and refreshing the parent Build Run.':'Removing bucket artifacts and linked validation runs. The panel will reset as soon as deletion is confirmed.'; | |
| confirmBtn.textContent='Deleting…'; | |
| confirmBtn.disabled=true; | |
| cancelEls.forEach(el=>{el.disabled=true;el.setAttribute('aria-disabled','true')}); | |
| if(warning){warning.hidden=false;warning.textContent='Deletion in progress…'} | |
| }; | |
| const setError=message=>{ | |
| modal.classList.remove('is-deleting'); | |
| submitted=false; | |
| title.textContent=`Delete this ${label}?`; | |
| body.textContent=kind==='validation' | |
| ? 'This removes only this validation run’s linked Space Test artifacts. The parent Build Run and generated Space will not be deleted. The tested Space will not be deleted.' | |
| : (linkedDelete.count?`This removes this Build Run’s bucket artifacts and ${linkedDelete.count} linked Space Test validation run${linkedDelete.count===1?'':'s'}. The generated Space is kept unless you explicitly choose to delete it below.`:'This removes this Build Run’s bucket artifacts, logs, state, traces and report. The generated Space is kept unless you explicitly choose to delete it below.'); | |
| confirmBtn.textContent=active?'Delete stored files':'Delete run'; | |
| confirmBtn.disabled=false; | |
| cancelEls.forEach(el=>{el.disabled=false;el.removeAttribute('aria-disabled')}); | |
| if(warning){warning.hidden=false;warning.textContent=message||'Deletion failed. You can retry or keep the run.'} | |
| }; | |
| const onCancel=()=>{if(!modal.classList.contains('is-deleting'))close(false)}; | |
| const onConfirm=()=>{if(submitted||modal.classList.contains('is-deleting'))return;submitted=true;resolve({deleteSpace:Boolean(spaceCheckbox&&spaceCheckbox.checked&&canDeleteSpace),associatedSpace,setDeleting,setError,close});}; | |
| const onKey=e=>{if(e.key==='Escape')onCancel();if(e.key==='Enter'&&modal.classList.contains('is-open'))onConfirm()}; | |
| cancelEls.forEach(el=>el.addEventListener('click',onCancel)); | |
| confirmBtn.addEventListener('click',onConfirm); | |
| document.addEventListener('keydown',onKey); | |
| modal.hidden=false; | |
| requestAnimationFrame(()=>{modal.classList.add('is-open');confirmBtn.focus();}); | |
| }); | |
| return state.deleteModalPromise; | |
| } | |
| async function deleteRunById(runId,options={}){ | |
| const context=runDeletionContext(runId,options); | |
| runId=context.runId; | |
| if(!runId){showMessage(context.kind==='validation'?'Select a validation run before deleting it.':'Select a run before deleting it.','warning');return} | |
| if(state.deletingRuns&&state.deletingRuns[runId])return; | |
| const status=canonicalStatusForDeletion(context); | |
| const confirmed=await confirmRunDeletion({runId,kind:context.kind,status,detail:{...(context.detail||{}),summary:{...(context.summary||{}),status}}}); | |
| if(!confirmed)return; | |
| const deleteSpace=typeof confirmed==='object'&&Boolean(confirmed.deleteSpace); | |
| if(state.deletingRuns&&state.deletingRuns[runId])return; | |
| state.deletingRuns=state.deletingRuns||{}; | |
| state.deletingRuns[runId]=true; | |
| if(confirmed&&typeof confirmed.setDeleting==='function')confirmed.setDeleting(); | |
| const buttonId=options.buttonId===null?null:(options.buttonId||(context.kind==='validation'?'deleteValidationRun':'deleteActiveRun')); | |
| setButtonBusy(buttonId,true,'Deleting…'); | |
| let success=false; | |
| try{ | |
| const result=await apiDelete(`/api/runs/${encodeURIComponent(runId)}?bucket_name=${encodeURIComponent(state.bucketName)}`,deleteSpace?{delete_space:true}:{}); | |
| const deletedChildren=Array.isArray(result.deleted_linked_validations)?result.deleted_linked_validations:[]; | |
| const childSuffix=deletedChildren.length?` and ${deletedChildren.length} linked validation${deletedChildren.length===1?'':'s'}`:''; | |
| const suffix=deleteSpace?(result.space_deleted?' and associated Space':(result.space_delete_error?' but Space deletion failed':' and Space was already missing')):''; | |
| showMessage(`Deleted run ${runId}${childSuffix}${suffix}`,'success'); | |
| success=true; | |
| rememberDeletedRun(runId); | |
| deletedChildren.forEach(id=>rememberDeletedRun(id)); | |
| clearDeletedRunState(runId,context.kind); | |
| forgetRunEverywhere(runId); | |
| deletedChildren.forEach(id=>{clearDeletedRunState(id,'validation');forgetRunEverywhere(id);}); | |
| renderRunsFromCache(); | |
| if(confirmed&&typeof confirmed.close==='function')confirmed.close(true); | |
| loadRuns(true).catch(e=>console.warn('post-delete runs refresh failed',e)); | |
| }catch(e){ | |
| showMessage(e.message,true); | |
| if(confirmed&&typeof confirmed.setError==='function')confirmed.setError(e.message); | |
| }finally{ | |
| if(state.deletingRuns)delete state.deletingRuns[runId]; | |
| setButtonBusy(buttonId,false); | |
| if(buttonId){ | |
| const btn=$(buttonId); | |
| const currentId=buttonId==='deleteActiveRun'?state.runId:state.validationRunId; | |
| if(btn)btn.disabled=!(currentId&¤tId===runId); | |
| } | |
| } | |
| } | |
| async function deleteSelectedRun(){return deleteRunById(null,{kind:'active',detail:state.selectedRunDetail||state.activeRunProgress||{}})} | |
| function defaultRunDocuments(detail={}){ | |
| const summary=detail.summary||{}; | |
| const runId=summary.run_id||detail.run_id||state.runId; | |
| const bucket=summary.bucket_source||detail.bucket_source||state.bucketSource; | |
| const rootUrl=runId&&bucket?artifactUrl(runId,bucket):''; | |
| const blob=rel=>runId&&bucket?`https://huggingface.co/buckets/${bucket}/tree/runs/${runId}/${rel}`:''; | |
| const tree=rel=>rootUrl?`${rootUrl}/${rel}`:''; | |
| return [ | |
| {id:'pi_redacted_trace',label:'Pi redacted',subtitle:'Source folder',icon:'🛡️',present:false,url:blob('traces/redacted/agent_trace.jsonl')||tree('traces/redacted'),sensitivity:'safe'}, | |
| {id:'report',label:'Report',subtitle:'Source document',icon:'📄',present:false,url:blob('report.md')}, | |
| {id:'smoke',label:'Smoke',subtitle:'Source JSON',icon:'⚡',present:false,url:blob('tests/generation_smoke.json')}, | |
| {id:'repair_decision',label:'Decision',subtitle:'Source JSON',icon:'◇',present:false,url:blob('repair/REPAIR_DECISION.json')}, | |
| {id:'blockage',label:'Blockage',subtitle:'Source JSON',icon:'!',tone:'warn',present:false,url:blob('repair/BLOCKAGE.json')}, | |
| {id:'eval_publish',label:'Eval publish',subtitle:'Archive status',icon:'◎',present:false,url:blob('eval_publish_status.json')}, | |
| {id:'space_logs',label:'Space logs',subtitle:'Build/runtime index',icon:'◉',present:false,url:blob('logs/space_logs_index.json')}, | |
| ]; | |
| } | |
| function mergeStableRunDocuments(runId,docs=[]){ | |
| state.documentCache=state.documentCache||{}; | |
| const cached=Array.isArray(state.documentCache[runId])?state.documentCache[runId]:[]; | |
| const byId=new Map(cached.map(d=>[d.id,{...d}])); | |
| for(const doc of docs||[]){ | |
| const previous=byId.get(doc.id)||{}; | |
| byId.set(doc.id,{...previous,...doc,present:Boolean(doc.present||previous.present),url:doc.url||previous.url||''}); | |
| } | |
| return docs.map(doc=>byId.get(doc.id)||doc); | |
| } | |
| function deriveRunDocuments(detail={}){ | |
| const baseDocs=defaultRunDocuments(detail); | |
| const backendDocs=Array.isArray(detail.run_documents)?detail.run_documents:[]; | |
| const docs=backendDocs.length?baseDocs.map(base=>({...(base||{}),...(backendDocs.find(doc=>doc&&doc.id===base.id)||{})})).concat(backendDocs.filter(doc=>doc&&!baseDocs.some(base=>base.id===doc.id))):baseDocs; | |
| const files=Array.isArray(detail.files)?detail.files:[]; | |
| const manifestArtifacts=Array.isArray(detail.artifact_manifest?.artifacts)?detail.artifact_manifest.artifacts:[]; | |
| const manifestPaths=manifestArtifacts.filter(a=>a&&a.present!==false).map(a=>String(a.path||'')).filter(Boolean); | |
| const filePaths=new Set([...files.map(f=>String(f.path||'')),...manifestPaths]); | |
| const hasPrefix=prefix=>[...filePaths].some(path=>String(path||'').startsWith(prefix.replace(/\/$/,'')+'/')); | |
| const reportText=String(detail.report||''); | |
| const summary=detail.summary||{}; | |
| const blockers=detail.technical_blockers||{}; | |
| const status=String(summary.status||detail.state?.status||detail.status||'').toLowerCase(); | |
| const shouldShowBlockers=Boolean(Object.keys(blockers).length)||status.includes('manual')||status.includes('blocker')||status.includes('failed')||status.includes('error'); | |
| const byId=new Map(docs.map(d=>[d.id,{...d}])); | |
| const traceDocState=(prefix,doc)=>{ | |
| const folderPrefix=prefix.replace(/\/$/,'')+'/'; | |
| const hasContent=[...filePaths].some(path=>path.startsWith(folderPrefix)&&!path.endsWith('/')); | |
| const runId=summary.run_id||detail.run_id||state.runId; | |
| const bucket=summary.bucket_source||detail.bucket_source||state.bucketSource; | |
| const folderUrl=runId&&bucket?`https://huggingface.co/buckets/${bucket}/tree/runs/${runId}/${prefix.replace(/\/$/,'')}`:''; | |
| const existingUrl=String(doc.url||''); | |
| const existingIsFolder=existingUrl.endsWith(`/${prefix.replace(/\/$/,'')}`); | |
| return {present:Boolean(hasContent||doc.present),url:folderUrl||existingUrl}; | |
| }; | |
| const redactedTrace=traceDocState('traces/redacted',byId.get('pi_redacted_trace')); | |
| byId.get('pi_redacted_trace').present=redactedTrace.present; | |
| byId.get('pi_redacted_trace').url=redactedTrace.url; | |
| byId.get('report').present=Boolean((byId.get('report').present&&byId.get('report').url)||reportText.length||filePaths.has('report.md')); | |
| byId.get('smoke').present=Boolean((byId.get('smoke').present&&byId.get('smoke').url)||Object.keys(detail.generation_smoke||{}).length||(filePaths.has('tests/generation_smoke.json')||filePaths.has('generation_smoke.json'))); | |
| if(shouldShowBlockers&&!byId.has('blockers')){ | |
| const runId=summary.run_id||detail.run_id||state.runId; | |
| const bucket=summary.bucket_source||detail.bucket_source||state.bucketSource; | |
| byId.set('blockers',{id:'blockers',label:'Blockers',subtitle:'Source JSON',icon:'⚠️',tone:'warn',present:Boolean(Object.keys(blockers).length||filePaths.has('generated/TECHNICAL_BLOCKERS.json')||filePaths.has('TECHNICAL_BLOCKERS.json')),url:runId&&bucket?`https://huggingface.co/buckets/${bucket}/tree/runs/${runId}/generated/TECHNICAL_BLOCKERS.json`:''}); | |
| } | |
| if(byId.has('repair_decision')){ | |
| byId.get('repair_decision').present=Boolean((byId.get('repair_decision').present&&byId.get('repair_decision').url)||nonEmptyObject(detail.repair_decision)||filePaths.has('repair/REPAIR_DECISION.json')); | |
| } | |
| if(byId.has('blockage')){ | |
| byId.get('blockage').present=Boolean((byId.get('blockage').present&&byId.get('blockage').url)||nonEmptyObject(detail.blockage)||filePaths.has('repair/BLOCKAGE.json')); | |
| } | |
| if(byId.has('eval_publish')){ | |
| const evalStatus=detail.eval_publish||detail.eval_publish_status||{}; | |
| byId.get('eval_publish').present=Boolean((byId.get('eval_publish').present&&byId.get('eval_publish').url)||nonEmptyObject(detail.eval_publish)||nonEmptyObject(detail.eval_publish_status)||filePaths.has('eval_publish_status.json')); | |
| if(nonEmptyObject(evalStatus)){ | |
| if(evalStatus.published===true)byId.get('eval_publish').tone='neutral'; | |
| else if(String(evalStatus.reason||'')==='record_not_ready')byId.get('eval_publish').tone='pending'; | |
| else if(evalStatus.attempted)byId.get('eval_publish').tone='warn'; | |
| } | |
| } | |
| if(byId.has('space_logs')){ | |
| const logIndex=detail.space_logs_index||detail.space_log_index||detail.logs_index||{}; | |
| const hasSpaceLogs=nonEmptyObject(logIndex)||filePaths.has('logs/space_logs_index.json')||filePaths.has('space_logs_index.json')||filePaths.has('logs/space_log_diagnostics.json')||filePaths.has('logs/space_runtime_snapshot.json'); | |
| byId.get('space_logs').present=Boolean((byId.get('space_logs').present&&byId.get('space_logs').url)||hasSpaceLogs); | |
| if(nonEmptyObject(logIndex)){ | |
| const quality=String(logIndex.log_quality||logIndex.quality||'').toLowerCase(); | |
| if(quality==='snapshot_only'||quality==='partial')byId.get('space_logs').tone='warn'; | |
| if(quality==='unavailable')byId.get('space_logs').tone='warn'; | |
| } | |
| } | |
| if(!byId.has('repair')&&hasPrefix('repair')){ | |
| const runId=summary.run_id||detail.run_id||state.runId; | |
| const bucket=summary.bucket_source||detail.bucket_source||state.bucketSource; | |
| byId.set('repair',{id:'repair',label:'Repair',subtitle:'Source folder',icon:'✦',tone:status.includes('failed')?'warn':'neutral',present:true,url:runId&&bucket?`https://huggingface.co/buckets/${bucket}/tree/runs/${runId}/repair`:''}); | |
| } | |
| const order=['pi_redacted_trace','repair_decision','repair','blockage','report','smoke','eval_publish','space_logs','blockers']; | |
| const runId=String(summary.run_id||detail.run_id||state.runId||''); | |
| const resolved=order.map(id=>byId.get(id)).filter(Boolean).filter(d=>{ | |
| if(['repair_decision','blockage','eval_publish','space_logs'].includes(d.id))return Boolean(d.present); | |
| if(d.id==='blockers')return shouldShowBlockers||d.present; | |
| return true; | |
| }); | |
| return runId?mergeStableRunDocuments(runId,resolved):resolved; | |
| } | |
| function renderRunDocuments(detail={}){ | |
| const root=$('runDocumentsDock'); | |
| if(!root)return; | |
| const runId=String(detail.run_id||detail.summary?.run_id||state.runId||''); | |
| state.documentCache=state.documentCache||{}; | |
| let docs=deriveRunDocuments(detail); | |
| const hasReady=docs.some(d=>d.present&&d.url); | |
| if(hasReady||!state.documentCache[runId])state.documentCache[runId]=mergeStableRunDocuments(runId,docs); | |
| docs=state.documentCache[runId]||docs; | |
| if(!docs.length){root.innerHTML='<div class="empty compact-empty loading-shimmer">Run documents are being indexed…</div>';return;} | |
| const signature=JSON.stringify(docs.map(d=>[d.id,d.present,d.url,d.label,d.subtitle,d.tone])); | |
| if(root.dataset.signature===signature)return; | |
| root.dataset.signature=signature; | |
| root.innerHTML=docs.map(doc=>{ | |
| const present=Boolean(doc.present&&doc.url); | |
| const tag=present?'a':'span'; | |
| const attrs=present?`href="${escapeHtml(doc.url)}" target="_blank" rel="noreferrer"`:''; | |
| const title=present?`Open source: ${doc.label}`:`${doc.label} is not in the bucket yet`; | |
| const cls=['run-doc-btn',present?'ready':'pending',doc.sensitivity==='raw'?'raw':'',doc.sensitivity==='safe'?'safe':'',doc.tone==='warn'?'warn':''].filter(Boolean).join(' '); | |
| return `<${tag} class="${cls}" ${attrs} title="${escapeHtml(title)}" aria-disabled="${present?'false':'true'}"><span class="doc-icon" aria-hidden="true">${escapeHtml(doc.icon||'📄')}</span><strong>${escapeHtml(doc.label)}</strong><em>${escapeHtml(present?doc.subtitle||'Open source':'Pending')}</em></${tag}>`; | |
| }).join(''); | |
| } | |
| function recoveryDecisionActionLabel(action){ | |
| const key=String(action||'').toLowerCase(); | |
| return { | |
| wait_for_logs:'Wait for logs', | |
| inspect_more_logs:'Inspect more logs', | |
| factory_rebuild_same_code:'Factory rebuild same code', | |
| patch_code:'Patch code', | |
| request_manual_hardware:'Request manual hardware', | |
| declare_technical_blocker:'Declare technical blocker' | |
| }[key]||badgeLabel(key||'pending'); | |
| } | |
| function recoveryStatusTone(action,status,detail={}){ | |
| const a=String(action||'').toLowerCase(); | |
| const s=String(status||'').toLowerCase(); | |
| const validated=Boolean(latestRecoveryEvent(detail,['repair_validation'])&&['success','done','passed'].includes(String(latestRecoveryEvent(detail,['repair_validation'])?.status||'').toLowerCase())); | |
| if(validated)return'success'; | |
| if(a.includes('blocker')||s.includes('failed')||s.includes('error'))return'error'; | |
| if(a.includes('manual'))return'warn'; | |
| if(a.includes('rebuild')||a.includes('wait')||a.includes('inspect'))return'running'; | |
| if(a.includes('patch'))return'warn'; | |
| return'neutral'; | |
| } | |
| function nonEmptyObject(value){ | |
| return Boolean(value&&typeof value==='object'&&!Array.isArray(value)&&Object.keys(value).length>0); | |
| } | |
| function runHasRecoverySignals(detail={}){ | |
| const files=Array.isArray(detail.files)?detail.files:[]; | |
| const events=Array.isArray(detail.events)?detail.events:([]); | |
| const runId=String(detail.run_id||detail.summary?.run_id||state.runId||''); | |
| const stableEvents=typeof mergeStableEvents==='function'?mergeStableEvents(runId,events):events; | |
| const decision=detail.repair_decision; | |
| const blockage=detail.blockage; | |
| const recoveryStepPattern=/^(failure_detected|failure_diagnosis|pi_diagnosis|repair_decision|wait_for_logs|factory_rebuild|repair|repair_diagnosis|repair_brief|repair_plan|repair_patch|repair_upload|repair_validation|technical_blocker|manual_hardware_required|failure)$/; | |
| return Boolean( | |
| nonEmptyObject(decision)|| | |
| nonEmptyObject(blockage)|| | |
| files.some(f=>String(f.path||'').startsWith('repair/'))|| | |
| stableEvents.some(e=>recoveryStepPattern.test(String(e.step||''))) | |
| ); | |
| } | |
| function latestRecoveryEvent(detail={},steps=[]){ | |
| const wanted=new Set(steps); | |
| const events=Array.isArray(detail.events)?detail.events:[]; | |
| const runId=String(detail.run_id||detail.summary?.run_id||state.runId||''); | |
| const stableEvents=typeof mergeStableEvents==='function'?mergeStableEvents(runId,events):events; | |
| for(const ev of [...stableEvents].reverse()){ | |
| if(wanted.has(String(ev.step||'')))return ev; | |
| } | |
| return null; | |
| } | |
| function recoverySourceDocuments(detail={}){ | |
| const docs=deriveRunDocuments(detail).filter(d=>d&&d.present&&d.url); | |
| const byId=new Map(docs.map(d=>[d.id,d])); | |
| const links=[]; | |
| const add=(id,label)=>{const d=byId.get(id);if(d&&d.url)links.push({label,url:d.url,tone:d.tone||'',sensitivity:d.sensitivity||''});}; | |
| add('repair_decision','Decision'); | |
| add('blockage','Blockage'); | |
| add('pi_redacted_trace','Pi trace'); | |
| return links.slice(0,4); | |
| } | |
| function recoveryPhaseLabel(detail={},decision={},blockage={}){ | |
| const summary=detail.summary||{}; | |
| const status=String(summary.status||detail.state?.status||detail.status||'').toLowerCase(); | |
| const terminalFailure=latestRecoveryEvent(detail,['failure']); | |
| if(nonEmptyObject(blockage)||status.includes('blocker')||status.includes('manual'))return'Final blocker'; | |
| if(decision.action&&TERMINAL_STATUSES.has(status))return'Final decision'; | |
| if(terminalFailure&&status.includes('fail')&&!decision.action)return'Recovery interrupted'; | |
| if(latestRecoveryEvent(detail,['repair_validation','generation_smoke','inference_gate']))return'Revalidating'; | |
| if(latestRecoveryEvent(detail,['repair_brief','repair_plan','repair_patch','repair_upload']))return'Repairing'; | |
| if(decision.action)return'Decision made'; | |
| return'Live diagnosis'; | |
| } | |
| function finalBlockerFromDetail(detail={}){ | |
| const obs=detail.build_error_observation||{}; | |
| const tail=String(obs.tail||obs.first_error||''); | |
| const reason=String(obs.reason||''); | |
| if(reason||tail){ | |
| if(tail.includes('pyenv install 3.1')||tail.replace(/\s+/g,'').includes('python3.1'))return 'Invalid Python version requested pyenv install 3.1'; | |
| if(tail.includes('BUILD FAILED')||reason.includes('BUILD_ERROR'))return 'Space build failed after repair'; | |
| return shortText(tail||reason,180); | |
| } | |
| return ''; | |
| } | |
| function renderAgentRecovery(detail={}){ | |
| const card=$('agentRecoveryCard'); | |
| const body=$('agentRecoveryBody'); | |
| const badge=$('agentRecoveryBadge'); | |
| if(!card||!body)return; | |
| if(!runHasRecoverySignals(detail)){ | |
| card.hidden=true; | |
| body.innerHTML=''; | |
| if(badge){badge.textContent='Not needed';badge.className='badge neutral'} | |
| return; | |
| } | |
| card.hidden=false; | |
| const decision=detail.repair_decision||{}; | |
| const blockage=detail.blockage||{}; | |
| const summary=detail.summary||{}; | |
| const status=summary.status||detail.state?.status||detail.status||''; | |
| const failureEvent=latestRecoveryEvent(detail,['failure']); | |
| const action=decision.action||blockage.recommended_action||blockage.action||''; | |
| const normalizedAction=recoveryDecisionActionLabel(action||(failureEvent?'interrupted':'diagnosis')); | |
| const tone=failureEvent&&!decision.action?'error':recoveryStatusTone(action,status,detail); | |
| if(badge){badge.textContent=normalizedAction;badge.className='badge '+(tone==='success'?'success':tone==='error'?'error':tone==='warn'?'warn':tone==='running'?'running':'neutral')} | |
| const diagnosisEvent=latestRecoveryEvent(detail,['failure_diagnosis','pi_diagnosis','repair_decision']); | |
| const decisionEvent=latestRecoveryEvent(detail,['repair_decision']); | |
| const decisionMade=Boolean(decision.action||decisionEvent); | |
| const rebuildEvent=latestRecoveryEvent(detail,['wait_for_logs','factory_rebuild']); | |
| const patchEvent=latestRecoveryEvent(detail,['repair_brief','repair_plan','repair_patch','repair_upload','repair_validation']); | |
| const failureReason=failureEvent?(failureEvent.reason||failureEvent.error||failureEvent.message||'The worker failed before Pi produced a structured recovery decision.') : ''; | |
| const reason=decision.reason||blockage.reason||blockage.message||failureReason||diagnosisEvent?.message||'Pi diagnosis is coordinating the next recovery action from collected logs, status and validation evidence.'; | |
| const evidence=Array.isArray(decision.evidence)?decision.evidence:[]; | |
| const next=decision.next_step||blockage.suggested_next_step||blockage.next_step||''; | |
| const phase=recoveryPhaseLabel(detail,decision,blockage); | |
| const sourceDocs=recoverySourceDocuments(detail); | |
| const rows=[]; | |
| const finalBlocker=finalBlockerFromDetail(detail); | |
| const summaryParts=[]; | |
| if(finalBlocker){ | |
| summaryParts.push(`<strong>Initial blocker</strong><p>${escapeHtml(shortText(reason,180))}</p>`); | |
| summaryParts.push(`<strong>Final blocker</strong><p>${escapeHtml(shortText(finalBlocker,180))}</p>`); | |
| }else{ | |
| summaryParts.push(`<strong>${escapeHtml(phase)} · ${escapeHtml(normalizedAction)}</strong><p>${escapeHtml(shortText(reason,220))}</p>`); | |
| } | |
| rows.push(`<div class="recovery-summary">${summaryParts.join('')}</div>`); | |
| const interrupted=Boolean(failureEvent&&!decision.action); | |
| rows.push(`<div class="recovery-ladder" aria-label="Agent recovery phases"> | |
| <span class="${interrupted?'failed':(diagnosisEvent||decision.action?'done':'pending')}"><b>1</b><em>Diagnose</em></span> | |
| <span class="${decisionMade?'done':interrupted?'pending':'pending'}"><b>2</b><em>Decide</em></span> | |
| <span class="${rebuildEvent?'done':patchEvent?'done':decisionMade?'running':'pending'}"><b>3</b><em>${escapeHtml(action&&String(action).includes('rebuild')?'Rebuild':action&&String(action).includes('patch')?'Patch':'Act')}</em></span> | |
| <span class="${latestRecoveryEvent(detail,['repair_validation','generation_smoke','inference_gate'])?'done':failureEvent?'pending':'pending'}"><b>4</b><em>Revalidate</em></span> | |
| </div>`); | |
| const meta=[]; | |
| if(decision.failure_category||blockage.failure_category)meta.push(['Failure',decision.failure_category||blockage.failure_category]); | |
| if(decision.logs_quality||blockage.logs_quality)meta.push(['Logs',decision.logs_quality||blockage.logs_quality]); | |
| if(decision.confidence)meta.push(['Confidence',decision.confidence]); | |
| if(meta.length)rows.push(`<div class="recovery-meta">${meta.map(([k,v])=>`<div><span>${escapeHtml(k)}</span><strong>${escapeHtml(String(v))}</strong></div>`).join('')}</div>`); | |
| if(evidence.length)rows.push(`<ul class="recovery-evidence">${evidence.slice(0,3).map(x=>`<li>${escapeHtml(shortText(x,120))}</li>`).join('')}</ul>`); | |
| if(next)rows.push(`<p class="recovery-next"><strong>Next:</strong> ${escapeHtml(shortText(next,180))}</p>`); | |
| if(sourceDocs.length)rows.push(`<div class="recovery-docs"><span>Sources</span>${sourceDocs.map(d=>`<a href="${escapeHtml(d.url)}" target="_blank" rel="noreferrer" class="${escapeHtml(d.tone||d.sensitivity||'')}">${escapeHtml(d.label)}</a>`).join('')}</div>`); | |
| body.innerHTML=rows.join(''); | |
| } | |
| function renderActiveRunActions(summary={},detail={}){ | |
| const runId=summary.run_id||detail.run_id; | |
| const targetSpace=summary.target_space||detail.state?.target_space||detail.launch?.target_space||''; | |
| const bucket=summary.bucket_source||detail.bucket_source||state.bucketSource; | |
| const artifacts=summary.artifacts_url||(typeof artifactUrl==='function'?artifactUrl(runId,bucket):''); | |
| const jobUrl=inferredJobUrl(summary,detail); | |
| const status=summary.status||detail.status||detail.state?.status||''; | |
| const cancel=$('cancelRun'); | |
| if(cancel){ | |
| const terminal=typeof runIsFinished==='function'?runIsFinished(status):TERMINAL_STATUSES.has(String(status||'').toLowerCase()); | |
| cancel.hidden=Boolean(terminal); | |
| cancel.disabled=Boolean(terminal)||!runId; | |
| } | |
| const spaceUrl=summary.target_space_url||detail.links?.target_space_url||(targetSpace?`https://huggingface.co/spaces/${targetSpace}`:''); | |
| const ready=Boolean(spaceUrl)||(typeof runPassedSpaceCreation==='function'?runPassedSpaceCreation({summary,detail,events:detail.events||[]}):false); | |
| setLink('activeOpenJob',jobUrl); | |
| setLink('activeOpenSpace',ready?spaceUrl:''); | |
| setLink('activeOpenSettings',ready&&spaceUrl?spaceUrl+'/settings':''); | |
| setLink('activeOpenArtifacts',artifacts); | |
| const prefill=$('activePrefillSpaceTest'); | |
| if(prefill){ | |
| const view=detail.view||detail; | |
| const statusModel=view.status_model||detail.status_model||{}; | |
| const headerStatus=String(view.header?.status||statusModel.global_status||status||'').toLowerCase(); | |
| const terminal=Boolean(statusModel.is_terminal)||TERMINAL_STATUSES.has(headerStatus)||runIsFinished(headerStatus); | |
| const exploitableStatus=['success','succeeded','partial','partial_validation','manual_hardware_required','waiting_manual_action','manual_action_required'].includes(headerStatus)||String(statusModel.global_status||'').includes('manual'); | |
| const canPrefill=Boolean(targetSpace)&&terminal&&exploitableStatus; | |
| prefill.disabled=!canPrefill; | |
| prefill.title=canPrefill?'Prefill Space Test from this completed build':'Available after the build reaches a final Space state.'; | |
| prefill.onclick=canPrefill?prepareValidationFromActiveRun:null; | |
| } | |
| const del=$('deleteActiveRun'); | |
| if(del){ | |
| const canDelete=Boolean(runId&&runCanBeDeleted(status)); | |
| del.disabled=!canDelete; | |
| del.title=canDelete?'Delete this run folder':'You can delete a run after the Job is finished or if only stale metadata remains.'; | |
| del.onclick=canDelete?()=>deleteRunById(runId,{kind:'active',detail}):null; | |
| } | |
| } | |
| function renderSelectedLinks(summary={},detail={}){renderActiveRunActions(summary,detail)} | |
| function renderBlockers(detail={}){ | |
| const root=$('selectedBlockers'); | |
| if(!root)return; | |
| const detailRunId=detail.run_id||detail.summary?.run_id||detail.state?.run_id||''; | |
| if(detailRunId&&state.runId&&detailRunId!==state.runId){root.hidden=true;root.innerHTML='';return} | |
| const summary=detail.summary||{}; | |
| const blockers=detail.technical_blockers||{}; | |
| const manual=summary.manual_hardware_required||String(summary.status||'').includes('manual_hardware_required'); | |
| const blockerItems=(Array.isArray(blockers.blockers)?blockers.blockers:[]).filter(b=>!['patch_code','repair_decision','repair','recovery'].includes(String(b.type||b.name||'').toLowerCase())); | |
| // Pi assistant model changed is rendered once in the compact Run notes banner. | |
| if(!manual&&!blockerItems.length){root.hidden=true;root.innerHTML='';return} | |
| root.hidden=false; | |
| const parts=[]; | |
| if(manual)parts.push('<strong>Manual hardware required</strong><p>Open Space settings, choose the recommended GPU, then run validation.</p>'); | |
| for(const b of blockerItems.slice(0,4)){parts.push(`<strong>${escapeHtml(shortText(b.type||b.name||'Technical blocker',32))}</strong><p>${escapeHtml(shortText(b.claim||b.reason||b.message||'',120))}</p>`)} | |
| root.innerHTML=parts.join('') | |
| } | |
| function clearEvalArchiveStatus(reason='idle'){ | |
| const card=$('runEvalArchiveCard'); | |
| const body=$('evalArchiveBody'); | |
| const badge=$('evalArchiveBadge'); | |
| if(badge){badge.textContent='Not checked';badge.className='badge neutral';} | |
| if(body){body.innerHTML='<div class="empty compact-empty">Archive publication status appears after the backend checks the selected run.</div>';body.dataset.runId='';} | |
| if(card){card.hidden=true;card.dataset.runId='';card.classList.remove('has-eval','published','needs-attention','pending');} | |
| } | |
| function evalArchiveHasData(status={},local={}){return Boolean((status&&typeof status==='object'&&Object.keys(status).length)||(local&&typeof local==='object'&&Object.keys(local).length));} | |
| function renderEvalArchiveStatus(detail={}){ | |
| const card=$('runEvalArchiveCard'); | |
| const body=$('evalArchiveBody'); | |
| const badge=$('evalArchiveBadge'); | |
| if(!card||!body)return; | |
| const runId=detail.run_id||detail.summary?.run_id||detail.state?.run_id||''; | |
| if(state.runId&&runId&&runId!==state.runId){clearEvalArchiveStatus('stale-run');return;} | |
| const status=detail.eval_publish_status||detail.eval_publish||{}; | |
| const local=detail.eval_record||{}; | |
| if(!evalArchiveHasData(status,local)){clearEvalArchiveStatus('no-data');return} | |
| card.hidden=false; | |
| card.dataset.runId=runId||''; | |
| body.dataset.runId=runId||''; | |
| card.classList.add('has-eval'); | |
| const published=status.published===true; | |
| const attempted=status.attempted===true; | |
| const reason=status.reason||''; | |
| if(badge){ | |
| badge.textContent=published?'Published':attempted&&reason==='record_not_ready'?'Pending':attempted?'Needs attention':'Pending'; | |
| badge.className='badge '+(published?'success':attempted&&reason!=='record_not_ready'?'warn':'neutral'); | |
| } | |
| const bucket=status.eval_bucket_source||status.archive_bucket||status.bucket_source||''; | |
| const path=status.archive_relative_path||status.path||''; | |
| const localLabel=(status.local_record_found||Object.keys(local||{}).length)?'written':'pending'; | |
| const backendLabel=published?'published':attempted&&reason==='record_not_ready'?'pending':attempted?'not published':'pending'; | |
| const manual=detail.manual_validation_status||detail.summary?.manual_validation_status||detail.view?.manual_validation||{}; | |
| const effective=manual.status==='success'?'validated_after_space_test':(detail.summary?.effective_status||detail.effective_status||''); | |
| const intro=published?'Eval record copied to the operator archive bucket.':attempted&&reason==='record_not_ready'?'Eval record will be archived when the run completes.':'Archive publication is not confirmed yet.'; | |
| const effectiveNote=effective?`<p class="eval-effective-note">Effective verdict: <strong>${escapeHtml(runCompactStatusLabel(effective))}</strong>${manual.validation_run_id?` from linked Space Test <code>${escapeHtml(manual.validation_run_id)}</code>`:''}.</p>`:''; | |
| const rows=[['Local record',localLabel],['Backend copy',backendLabel],['Mode',status.publish_mode||status.mode||'backend'],['Archive bucket',bucket||'—']]; | |
| const kv=`<dl class="eval-archive-kv">${rows.map(([label,value])=>`<div><dt>${escapeHtml(label)}</dt><dd>${escapeHtml(value)}</dd></div>`).join('')}</dl>`; | |
| body.innerHTML=`<p>${escapeHtml(intro)}</p>${effectiveNote}${kv}${path?`<code class="eval-record-path">${escapeHtml(path)}</code>`:''}${reason&&!published&&reason!=='record_not_ready'?`<p class="eval-warning">${escapeHtml(reason)}</p>`:''}`; | |
| } | |
| function renderRunDetail(detail){ | |
| state.selectedRunDetail=detail; | |
| const summary=detail.summary||{}; | |
| if(typeof contextualizeSpaceTestFromBuildRun==='function')contextualizeSpaceTestFromBuildRun(detail); | |
| const smoke=detail.generation_smoke||{}; | |
| const files=detail.files||[]; | |
| const view=detail.view||{}; | |
| const header=view.header||{}; | |
| const runId=summary.run_id||detail.run_id; | |
| const canonical=typeof canonicalRunUiState==='function'?canonicalRunUiState(detail):{label:header.status_label||summary.status||detail.status||'unknown',status:summary.status||detail.status||'unknown'}; | |
| setText('selectedModelId',summary.model_id||header.model||'—'); | |
| setText('homeRunDetailStatus',canonical.label||header.status_label||summary.status||detail.status||'unknown'); | |
| setText('detailRunId',runId||'—'); | |
| setText('detailJobStatus',canonical.label||summary.status||detail.status||'—'); | |
| setText('detailGateStatus',(detail.inference_gate||{}).status||summary.status||'—'); | |
| setText('detailSpace',summary.target_space||detail.state?.target_space||'—'); | |
| const mode=runImplementationMode(summary,detail); | |
| setText('detailImplementationMode',mode?implementationModeLabel(mode):'—'); | |
| const modeEl=$('detailImplementationMode'); | |
| if(modeEl&&mode){modeEl.title=implementationModeDescription(mode)} | |
| setText('detailHardware',summary.selected_hardware||summary.hardware||detail.state?.selected_hardware||'—'); | |
| if(typeof renderActiveRunMeta==='function')renderActiveRunMeta({...detail,summary}); | |
| setText('detailTraces',summary._optimistic?'Loading details…':(Array.isArray(detail.events)?String(detail.events.length)+' events':summary.traces_count||'—')); | |
| const validation=$('selectedValidation'); | |
| if(validation){validation.innerHTML=`<li><span>Health</span><strong>${summary.health_passed?'passed':'—'}</strong></li><li><span>Smoke test</span><strong>${summary.smoke_test_passed?'passed':(smoke.status||'—')}</strong></li><li><span>Latency</span><strong>${summary.latency_seconds?fmtSeconds(Math.round(summary.latency_seconds)):'—'}</strong></li>`} | |
| const artifactRoot=$('artifactList'); | |
| if(artifactRoot){const interesting=files.filter(f=>!/traces\//.test(f.path||'')).slice(0,18);artifactRoot.innerHTML=interesting.length?interesting.map(f=>`<a href="${escapeHtml(f.url)}" target="_blank"><span>${escapeHtml(f.path)}</span><em>${f.size?Math.round(Number(f.size)/1024)+' KB':''}</em></a>`).join(''):'No artifacts indexed yet.'} | |
| const reportText=(detail.report||'No report available.').slice(0,8000); | |
| const report=$('reportPreview'); | |
| if(report)report.textContent=reportText; | |
| const resolvedSpaceUrl=summary.target_space_url||detail.links?.target_space_url||(summary.target_space||detail.state?.target_space?`https://huggingface.co/spaces/${summary.target_space||detail.state?.target_space}`:''); | |
| setQuickLinks({job_url:inferredJobUrl(summary,detail),target_space_url:resolvedSpaceUrl,target_space_settings_url:resolvedSpaceUrl?resolvedSpaceUrl+'/settings':'',artifacts_url:summary.artifacts_url,bucket_source:detail.bucket_source,run_id:runId,target_space:summary.target_space||detail.state?.target_space,links_ready:Boolean(detail.links?.links_ready||detail.space_identity?.links_ready||detail.space_link_state?.links_ready),space_created:Boolean(detail.links?.space_created||detail.space_identity?.space_created||detail.space_link_state?.space_created),space_uploaded:Boolean(detail.links?.space_uploaded||detail.links?.runtime_uploaded||detail.space_identity?.space_uploaded||detail.space_identity?.runtime_uploaded||detail.space_link_state?.runtime_uploaded),runtime_uploaded:Boolean(detail.links?.runtime_uploaded||detail.space_identity?.runtime_uploaded||detail.space_link_state?.runtime_uploaded),space_runtime_known:Boolean(detail.links?.space_runtime_known||detail.space_identity?.space_runtime_known||detail.space_link_state?.space_runtime_known)},{summary,detail,space_identity:detail.space_link_state||detail.space_identity||{},space_link_state:detail.space_link_state||{},events:detail.events||[]}); | |
| renderActiveRunActions({...summary,bucket_source:detail.bucket_source},detail); | |
| renderBlockers(detail); | |
| renderAgentRecovery(detail); | |
| renderEvalArchiveStatus(detail); | |
| renderRunDocuments(detail); | |
| renderMetrics({...detail,summary}); | |
| /* v196.2: render updates must not steal the user's Center Workspace tab. | |
| The run-selection path may open Active Run initially, but later /progress | |
| refreshes only hydrate panels in place. */ | |
| } | |
| // Build run routing invariant: run selection may switchCenterTab('active') once; render/poll refreshes must not steal the Center Workspace tab. | |
| // Legacy test anchors retained as comments only; render/poll refreshes must not execute them: | |
| // avoid rendering stale view.pipeline | |
| // switchCenterTab('active');setBuildModeInspecting(runId);startPolling(runId) | |
| // Legacy route invariant: startPolling(runId);renderRunDetail(detail) | |
| // Legacy wording: Validation latency / Aggregated issues | |
| // Legacy invariant: state.runsCache=sortRunsNewestFirst(data.runs||[]) | |
| // Legacy test phrase retained for run notes wording: Likely Inference Providers routing/fallback. | |
| // Legacy clean-delete invariant: await loadRuns(true) was intentionally replaced by post-delete background refresh in v190.9. | |
| // Legacy validation preview invariant: if(isValidationRunDetail(detail)){showValidationRunDetail(detail) | |
| // v190.15 build-first compatibility invariant: legacy/incomplete Build Runs stay visible, validation runs require parent_build_run_id before they can affect parent stats. | |