import React, { useEffect, useState, useRef, lazy, Suspense } from 'react';
import { createRoot } from 'react-dom/client';
import { Moon, Sun, Plus, LayoutDashboard, ScanLine, Layers, History, Bell, BarChart3, BookOpen, ArrowUpRight, ArrowRight, Upload, Check, Activity, ShieldCheck, X, LoaderCircle, FileText, MessageSquare, ChevronRight, CircleHelp, Download, Search, Cpu, ClipboardCheck, UserCircle, CheckCheck, Menu } from 'lucide-react';
import './tokens.css';
import './style.css';
import './theme.css';
import './design.css';
import './comfort.css';
import ActivityChart from './ActivityChart.jsx';
import ErrorBoundary from './ErrorBoundary.jsx';
import {readEnvelope} from './http.mjs';
import {recordIssue,build as appBuild} from './diagnostics.mjs';
import {initialTheme,applyTheme} from './theme.mjs';
import {initialTextSize,applyTextSize,stepTextSize,TEXT_SIZES} from './textSize.mjs';
import {overviewCards,dailyActivity,overviewTabs,overviewRows} from './overview.mjs';
import InspectionViewer from './InspectionViewer.jsx';
import ReferencePhotos from './ReferencePhotos.jsx';
import StaffHelp from './StaffHelp.jsx';
import Tutorial from './Tutorial.jsx';
import TutorialCoach from './TutorialCoach.jsx';
import {practiceActive,practiceApi,practiceRequest,startPracticeMode,stopPracticeMode} from './practice.mjs';
import practiceOriginal from './practiceAssets/candle-original.jpg';
import practiceHeatmap from './practiceAssets/candle-heatmap.jpg';
import {tutorialSeen,rememberTutorial,newPractice,practiceReducer,tutorialSteps} from './tutorial.mjs';
import {resultLabel,answerLabel,friendlyError,productLabels} from './userLanguage.mjs';
import ArchiveDialog from './ArchiveDialog.jsx';
import BenchmarkReport from './BenchmarkReport.jsx';
import {workspaceChanged,cloudClient,cloudConfigured} from './cloud.js';
import {accountSummary,loadAccount} from './account.mjs';
import InspectionAction from './InspectionAction.jsx';
import InspectionDraft from './InspectionDraft.jsx';
import {filterInspectionRows} from './inspectionUX.mjs';
import {inspectionReadiness,loadInspectionAccess} from './inspectionReadiness.mjs';
import {workspaceRefreshGate,readRefreshSections} from './workspaceRefresh.mjs';
import RefreshNotice from './RefreshNotice.jsx';
import LocalSyncPanel from './LocalSyncPanel.jsx';
import PublicDemoNotice from './PublicDemoNotice.jsx';
import {publicDemoAvailable} from './publicDemo.mjs';
import {configureLocalSync,localSyncEnabled,localSyncRequest} from './localSync.mjs';
import ReviewForm from './ReviewForm.jsx';
import WorkspaceShare from './WorkspaceShare.jsx';
import {sharedAssistantAvailable} from './teamNavigation.mjs';
import {activeWorkspace,configureWorkspace,personalEnabled,setWorkspace,startPolling} from './workspace.mjs';
import CommunityGallery,{PublishGalleryPanel} from './CommunityGallery.jsx';
import {createRequestScope,newBatch,continueBatch,batchView} from './workflow.mjs';
import {batchOwner,checkpointBatch,restoreBatch} from './batchCheckpoint.js';
const TeamWorkspace=lazy(()=>import('./TeamWorkspace.jsx'));
import { SHOWCASE, assetUrl, showcaseApi } from './showcase.js';
const url=assetUrl;
const labels=productLabels;
const navGroups=[['',['overview','inspect','batch','history']],['Review',['alerts','cases','team']],['Insight',['performance','benchmark','gallery']],['More',['recovery','about']]];
const nav=[['overview','Overview',LayoutDashboard],['inspect','Image inspection',ScanLine],['batch','Batch inspection',Layers],['history','Inspection history',History],['alerts','Review alerts',Bell],...(!SHOWCASE?[['cases','Corrective Actions',ClipboardCheck]]:[]),['performance','Model performance',BarChart3],['benchmark','Official benchmark',Cpu],...(!SHOWCASE?[['gallery','Community gallery',ScanLine]]:[]),['team','Staff workspace',Layers],['recovery','History recovery',History],['about','Help & references',BookOpen]];
function pageFromLocation(fallback='overview'){
const hash=location.hash.slice(1);
if(/(?:^|&)(access_token|error_description|type)=/.test(hash)||new URLSearchParams(location.search).has('code'))return 'team';
return nav.some(n=>n[0]===hash)?hash:fallback;
}
const number=(v,d=3)=>typeof v==='number'?v.toFixed(d):'—';
const percent=v=>typeof v==='number'?(v*100).toFixed(1)+'%':'—';
const date=v=>v?new Date(v).toLocaleString():'';
async function request(path,options={}) {
if(practiceActive())return practiceRequest(path,options);
if(localSyncEnabled())return localSyncRequest(url(path),options,await cloudClient(),activeWorkspace());
return fetch(url(path),options)
}
async function api(path,options={}) {
if(SHOWCASE) return showcaseApi(path,options);
// Guided practice answers from its in-memory lesson store, never the server.
if(practiceActive()) return practiceApi(path,options);
let response;
try{response=await request(path,options)}
catch(error){recordIssue('network',error?.message||'Request failed',{path});throw error}
return readEnvelope(response,path);
}
// Builds the page content as a child of ErrorBoundary. Inline JSX runs in its parent,
// so without this a bad value would crash App itself instead of only the page.
function PageBody({render}){return render()}
function Badge({value}) {return {resultLabel(value)}}
function Empty({children}) {return
{children}
}
// Small bundled thumbnails load at once; the full sample is fetched only when chosen.
// Under assets/: the Space serves only /assets/* besides the entry files.
const sampleThumb=s=>'./assets/sample-thumbs/'+s.name+'.jpg';
function Gallery({samples,busy,onChoose}){return
{samples.map(s=>)}
}
function Filters({filter,setFilter,stats,filteredCount}){return
{filteredCount} records shown
}
function Table({rows=[],emptyMessage,hasRecords,onOpen,reviewMode=false}){return rows.length?
Inspection / time
Product
Batch
Result
Score / review limit
Time to check
{rows.map(r=>
{r.id.slice(0,8)}{date(r.created_at)}
{labels[r.category]}
{r.batch||'Individual'}
{number(r.score)} / {number(r.threshold)}
{number(r.inference_ms,0)} ms
)}
:{emptyMessage||(hasRecords?'No inspections match these filters. Clear the filters to see saved records.':'No inspections yet. Add an image to start your inspection log.')}}
function App(){
const [page,setPage]=useState(()=>pageFromLocation());
const [theme,setTheme]=useState(initialTheme);
useEffect(()=>applyTheme(theme),[theme]);
const [textSize,setTextSize]=useState(initialTextSize);
useEffect(()=>{applyTextSize(textSize)},[textSize]);
const [chartDays,setChartDays]=useState(30),[overviewTab,setOverviewTab]=useState('recent');
const [tutorialOpen,setTutorialOpen]=useState(false);
const tutorialPrompted=useRef(false),tutorialReturn=useRef('overview');
const [practice,setPractice]=useState(newPractice);
const practiceRunning=tutorialOpen&&practice.started;
function closeTutorial(){
try{rememberTutorial(window.localStorage)}catch{rememberTutorial(null)}
const wasRunning=practice.started;
setTutorialOpen(false);setPractice(newPractice());
if(wasRunning){stopPracticeMode();clearLessonState();go(tutorialReturn.current)}
}
// Practice and real work never share on-screen state: clear it on entry and exit.
function clearLessonState(){
refreshContext.current.invalidate();clearWorkspace();resetInspection();setFiles([]);setCategory('');setBatch('');
setBatchJob(null);setBatchResult(null);batchSelection.current=null;setSharedSelectionId(null);setNotice('');
metadataLoaded.current=false;setInspectionAccess({state:'checking'});setWorkspaceBlock(null);
}
function startPractice(){
if(busy||ragBusy||recordLoading)return;
tutorialReturn.current=page;
startPracticeMode({assets:{original:practiceOriginal,heatmap:practiceHeatmap},metadata:{samples,evaluation,official},onEvent:practiceAction});
clearLessonState();setWorkspace('personal');setWorkspaceState('personal');
setPractice(practiceReducer(newPractice(),{type:'start'}));go('inspect');
}
function practiceAction(action){setPractice(previous=>practiceReducer(previous,action))}
const [official,setOfficial]=useState(null),[archived,setArchived]=useState([]),[archiveOpen,setArchiveOpen]=useState(false),[archiveBusy,setArchiveBusy]=useState(false),[sharing,setSharing]=useState(false),[notice,setNotice]=useState('');
const [health,setHealth]=useState(null),[stats,setStats]=useState({total:0,counts:{},batches:[]}),[samples,setSamples]=useState([]),[records,setRecords]=useState([]),[alerts,setAlerts]=useState([]),[evaluation,setEvaluation]=useState(null);
const [error,setError]=useState(''),[busy,setBusy]=useState(false),[ragBusy,setRagBusy]=useState(false),[result,setResult]=useState(null),[messages,setMessages]=useState([]);
const [category,setCategory]=useState(''),[batch,setBatch]=useState(''),[files,setFiles]=useState([]),[preview,setPreview]=useState(''),[filter,setFilter]=useState({category:'',verdict:'',batch:''}),[question,setQuestion]=useState(''),[heatmap,setHeatmap]=useState(true),[batchResult,setBatchResult]=useState(null);
const context=useRef(createRequestScope()),refreshContext=useRef(createRequestScope()),refreshPoll=useRef(null);
const singleSubmission=useRef(null),artifactRefresh=useRef(0);
const batchIdentity=useRef(null),batchLoad=useRef(0),metadataLoaded=useRef(false),batchSelection=useRef(null);
const [signedIn,setSignedIn]=useState(false);
const [sharedSelectionId,setSharedSelectionId]=useState(null);
const [workspace,setWorkspaceState]=useState('personal'),[workspaceStatus,setWorkspaceStatus]=useState(null),[sync,setSync]=useState({state:'refreshing'});
function clearWorkspace(){refreshContext.current.invalidate();setRecords([]);setAlerts([]);setArchived([]);setStats({total:0,counts:{},batches:[]});setWorkspaceStatus(null);setSectionErrors(previous=>previous.filter(name=>['Connection','Samples','Performance','Benchmark'].includes(name)))}
function changeWorkspace(value){
const keepDraft=workspace==='team'&&value==='personal'&&!busy&&!ragBusy&&!recordLoading;
setWorkspace(value);setWorkspaceState(value);clearWorkspace();resetInspection();
if(!keepDraft)setFiles([]);
setFilter({category:'',verdict:'',batch:''});
}
function switchToPersonalWorkspace(){if(busy||ragBusy||recordLoading)return;changeWorkspace('personal')}
function openSharedReview(row){setSharedSelectionId(row.id);go('team')}
function openCorrectiveActions(row){setSharedSelectionId(row?.id||null);go('cases')}
function chooseTeamInspection(){setSharedSelectionId(null);go('team')}
function openTeamRecord(row){if(health?.personal_workspace_enabled)changeWorkspace('team');openRecord({...row.payload,id:row.id,storage:'supabase',workspace:'team'})}
const [batchJob,setBatchJob]=useState(null),[batchWarning,setBatchWarning]=useState('');
const [sectionErrors,setSectionErrors]=useState([]),[review,setReview]=useState(null),[recordLoading,setRecordLoading]=useState(false);
const resultHeading=useRef(null);
useEffect(()=>{
const ready=page==='inspect'&&result||page==='batch'&&batchResult;
if(ready&&!busy&&!recordLoading){resultHeading.current?.focus({preventScroll:true});resultHeading.current?.scrollIntoView({block:'start',behavior:'instant'})}
},[page,result?.id,batchResult?.records?.length,busy,recordLoading,practiceRunning]);
const [inspectionAccess,setInspectionAccess]=useState({state:'checking'}),[workspaceBlock,setWorkspaceBlock]=useState(null);
const [localSyncStatus,setLocalSyncStatus]=useState(null);
const [account,setAccount]=useState(null);
useEffect(()=>{
if(SHOWCASE||practiceRunning||!cloudConfigured()){setAccount(null);return}
let alive=true;
const load=()=>cloudClient().then(loadAccount).then(value=>{if(alive)setAccount(value)}).catch(()=>{if(alive)setAccount(null)});
load();window.addEventListener('defectrag-auth-change',load);
return()=>{alive=false;window.removeEventListener('defectrag-auth-change',load)};
},[practiceRunning]);
const who=accountSummary(account);
const [seenAll,setSeenAll]=useState({phase:'idle',done:0,total:0});
const [menuOpen,setMenuOpen]=useState(false);
useEffect(()=>{if(!menuOpen)return;const close=e=>{if(e.key==='Escape')setMenuOpen(false)};window.addEventListener('keydown',close);return()=>window.removeEventListener('keydown',close)},[menuOpen]);
// Row buttons (mark as seen, restore) run once per press: a second press while
// the first is still saving is ignored, and the button says it is working.
const [pending,setPending]=useState({}),pendingKeys=useRef(new Set());
async function once(key,action){
if(pendingKeys.current.has(key))return;
pendingKeys.current.add(key);setPending(v=>({...v,[key]:true}));setError('');
try{await action()}catch(e){setError(e.message)}
finally{pendingKeys.current.delete(key);setPending(v=>{const next={...v};delete next[key];return next})}
}
function acknowledgeOne(id){return once('ack:'+id,async()=>{await api('/api/alerts/'+id+'/acknowledge',{method:'POST'});setAlerts(list=>list.map(a=>a.id===id?{...a,acknowledged:a.acknowledged||1}:a));workspaceChanged()})}
function restoreOne(id){return once('restore:'+id,async()=>{await api('/api/history/restore',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({ids:[id]})});setArchived(list=>list.filter(r=>r.id!==id));setNotice('Inspection restored to active history.');workspaceChanged()})}
const unseenCount=alerts.filter(a=>!a.acknowledged).length;
// A confirm prompt must not outlive the alerts it was about.
useEffect(()=>{if(seenAll.phase==='confirm'&&unseenCount<2)setSeenAll({phase:'idle',done:0,total:0})},[unseenCount,seenAll.phase]);
useEffect(()=>{if(page!=='overview'||!health||busy||ragBusy||recordLoading||tutorialPrompted.current)return;tutorialPrompted.current=true;let seen=false;try{seen=tutorialSeen(window.localStorage)}catch{seen=tutorialSeen(null)}if(!seen)setTutorialOpen(true)},[page,health?.mode,busy,ragBusy,recordLoading]);
function currentReadiness(multiple=false,retry=false){
const continuing=multiple&&batchJob&&batchSelection.current===files&&batchJob.category===category&&batchJob.batch===batch.trim();
return inspectionReadiness({health,workspace,access:inspectionAccess,files,categoryValid:Boolean(labels[category]),batch:multiple?batch:'',knownBatches:[...stats.batches,...archived],multiple,retry:retry||Boolean(continuing),busy,ragBusy,recordLoading,offline:sync.state==='offline',connectionFailed:sectionErrors.includes('Connection')});
}
const go=p=>{setPage(p);location.hash=p;setError('');setNotice('');setMenuOpen(false);setSeenAll(v=>v.phase==='working'?v:{phase:'idle',done:0,total:0})};
function openPublicDemo(){
if(!publicDemoAvailable(health,inspectionAccess))return;
switchToPersonalWorkspace();go('inspect');
}
function resetInspection(){
context.current.invalidate();setBusy(false);setRagBusy(false);setRecordLoading(false);
setResult(null);setMessages([]);setReview(null);setQuestion('');
return context.current.capture();
}
async function refresh(full=false){
refreshContext.current.invalidate();const current=refreshContext.current.capture();
let settings=health;
// Resolve the public routing configuration before any private request.
// On first load activeWorkspace otherwise defaults to the legacy Team route.
if(full||!settings){
const metadata=[['Connection','/api/health',value=>{settings=value;setHealth(value)}],['Samples','/api/samples',setSamples],['Performance','/api/evaluation',setEvaluation],['Benchmark','/api/benchmark/official',setOfficial]];
const read=await readRefreshSections(metadata,api,current);if(!read)return false;
read.apply();
const failed=read.failures.map(row=>row.name);
setSectionErrors(previous=>[...previous.filter(name=>!metadata.some(row=>row[0]===name)),...failed]);
metadataLoaded.current=!failed.length;
if(failed.includes('Connection'))throw new Error('The inspection service could not be reached.');
const changed=Boolean(settings.personal_workspace_enabled)!==personalEnabled();
configureLocalSync(settings.local_sync_enabled);
configureWorkspace(settings.personal_workspace_enabled);setWorkspaceState(activeWorkspace());
if(changed){clearWorkspace();setSectionErrors(failed);return false}
}
let access={state:'not_required'};
if(!SHOWCASE&&(settings?.mode==='cloud_session_workspace'||settings?.local_sync_enabled)&&settings.auth_workflow_enabled){
try{access=await loadInspectionAccess(await cloudClient())}catch{access={state:'unavailable'}}
if(!current())return false;
}
setInspectionAccess(access);
const block=SHOWCASE?null:workspaceRefreshGate(settings,access,activeWorkspace());
setWorkspaceBlock(block);
if(block){
clearWorkspace();resetInspection();setLocalSyncStatus(null);
return {state:'blocked',reason:block.reason};
}
if(settings?.local_sync_enabled&&access.state==='authorized'&&activeWorkspace()==='personal'){
try{const value=await api('/api/local-sync/run',{method:'POST'});if(!current())return false;setLocalSyncStatus(value)}
catch{if(!current())return false;setLocalSyncStatus({state:'unavailable',message:'Cloud synchronization could not be confirmed. Local records remain saved.'})}
}
const requests=[['Overview','/api/stats',setStats],['History','/api/inspections?limit=500',setRecords],['Alerts','/api/alerts',setAlerts],['Recovery','/api/archives',setArchived]];
if(!SHOWCASE&&(settings?.mode==='cloud_session_workspace'||settings?.local_sync_enabled))requests.push(['Workspace','/api/workspace',setWorkspaceStatus]);
if(page==='inspect'&&result&&!SHOWCASE&&!busy&&!ragBusy){
requests.push(['Selected conversation','/api/inspections/'+result.id+'/messages',setMessages],['Selected review','/api/inspections/'+result.id+'/reviews',value=>setReview(value.at(-1)||null)]);
if(Date.now()-artifactRefresh.current>8*60*1000)requests.push(['Selected images','/api/inspections/'+result.id,value=>{artifactRefresh.current=Date.now();setResult(value)}]);
}
const read=await readRefreshSections(requests,api,current);if(!read)return false;
if(read.failures.some(row=>[401,403].includes(row.status))){
// Permission may have changed since the posture check. Never retain private
// records or silently retry under an anonymous identity after a denial.
clearWorkspace();resetInspection();setInspectionAccess({state:'denied'});setLocalSyncStatus(null);
const denied={reason:'Workspace access was denied or the session expired. Open Staff workspace to check sign-in and authenticator verification.',action:'account'};
setWorkspaceBlock(denied);return {state:'blocked',reason:denied.reason};
}
read.apply();
setSectionErrors(previous=>[...previous.filter(name=>!requests.some(row=>row[0]===name)),...read.failures.map(row=>row.name)]);
if(read.failures.length||!metadataLoaded.current)throw new Error('Some workspace data could not synchronize.');
}
function retryRefresh(){metadataLoaded.current=false;refreshPoll.current?.refresh()}
async function resolveLocalConflict(inspection_id,choice){
const current=refreshContext.current.capture();
const value=await api('/api/local-sync/resolve',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({inspection_id,choice})});
if(current()){setLocalSyncStatus(value);retryRefresh()}
}
// One button for every unseen alert. Sends the same request the per-row button uses,
// a few at a time, and reports exactly how many could not be saved.
async function markAllSeen(){
if(seenAll.phase==='working')return;
const ids=alerts.filter(a=>!a.acknowledged).map(a=>a.id);
if(!ids.length){setSeenAll({phase:'idle',done:0,total:0});return}
setSeenAll({phase:'working',done:0,total:ids.length});setError('');
let failed=0,done=0;
try{
for(let i=0;iapi('/api/alerts/'+id+'/acknowledge',{method:'POST'})));
failed+=results.filter(r=>r.status==='rejected').length;done+=part.length;
setSeenAll({phase:'working',done,total:ids.length});
}
}finally{
setSeenAll({phase:'idle',done:0,total:0});
workspaceChanged();await refresh().catch(()=>{});
}
if(failed)setError(failed+' of '+ids.length+' alerts could not be marked. Press the button again to retry.');
else setNotice(ids.length+(ids.length===1?' alert':' alerts')+' marked as seen.');
}
async function importLocalHistory(ids){
const current=refreshContext.current.capture();
const result=await api('/api/local-sync/import',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({ids,confirmation:'IMPORT_PRIVATE'})});
if(current()){setLocalSyncStatus(result.status);retryRefresh()}
}
async function downloadLocalBackup(id){
const current=refreshContext.current.capture();
try{const backup=await api('/api/local-sync/backups/'+id);if(!current())return;
const href=URL.createObjectURL(new Blob([JSON.stringify(backup,null,2)],{type:'application/json'}));
const link=document.createElement('a');link.href=href;link.download='defectrag-private-recovery-'+id+'.json';link.click();setTimeout(()=>URL.revokeObjectURL(href),1000);
}catch{if(current())setError('Recovery backup could not be downloaded. Verify account access and retry.')}
}
async function loadBatch(){
if(SHOWCASE)return;
const generation=++batchLoad.current,current=context.current.capture();
try{
const owner=await batchOwner();const job=await restoreBatch(owner);
if(generation!==batchLoad.current)return;
batchIdentity.current=owner;setSignedIn(owner.startsWith('staff:'));setBatchJob(job);setBatchResult(job?batchView(job):null);
if(job&¤t()&&location.hash==='#batch'){setCategory(job.category);setBatch(job.batch)}
}catch{if(generation===batchLoad.current)setBatchWarning('Browser batch recovery is unavailable. Keep this page open to retain pending files.')}
}
useEffect(()=>{const poll=startPolling(()=>refresh(!metadataLoaded.current),{onState:setSync});refreshPoll.current=poll;return()=>{poll.stop();refreshContext.current.invalidate();if(refreshPoll.current===poll)refreshPoll.current=null}},[page,workspace,health?.mode,health?.personal_workspace_enabled,health?.auth_workflow_enabled,health?.local_sync_enabled,result?.id,busy,ragBusy,practiceRunning]);
useEffect(()=>{if(health?.personal_workspace_enabled)loadBatch()},[health?.personal_workspace_enabled]);
useEffect(()=>{
loadBatch();
const navigate=()=>{setPage(current=>pageFromLocation(current));setError('');setNotice('');setMenuOpen(false)};
const update=async event=>{
if(event.type==='defectrag-auth-change'&&event.detail.event!=='TOKEN_REFRESHED'){
refreshContext.current.invalidate();setInspectionAccess({state:'checking'});setWorkspaceBlock(null);setLocalSyncStatus(null);
const previous=batchIdentity.current,next=event.detail.userId?'staff:'+event.detail.userId:'browser';
if(previous?.replace(/:personal$/,'')!==next){
clearWorkspace();setSharedSelectionId(null);setWorkspace('personal');setWorkspaceState('personal');
context.current.invalidate();setBusy(false);setRagBusy(false);setRecordLoading(false);
if(next==='browser'||previous?.startsWith('staff:'))resetInspection();
setSignedIn(next.startsWith('staff:'));setFiles([]);setBatchJob(null);setBatchResult(null);batchIdentity.current=next;loadBatch();
}
}
refreshPoll.current?.refresh();
};
window.addEventListener('hashchange',navigate);window.addEventListener('defectrag-auth-change',update);
return()=>{context.current.invalidate();refreshContext.current.invalidate();batchLoad.current++;window.removeEventListener('hashchange',navigate);window.removeEventListener('defectrag-auth-change',update)};
},[]);
useEffect(()=>{if(!files[0]){setPreview('');return}const local=URL.createObjectURL(files[0]);setPreview(local);return()=>URL.revokeObjectURL(local)},[files]);
useEffect(()=>{if(!practiceRunning)return;const event=tutorialSteps()[practice.step]?.event;
if(event==='product'&&category)practiceAction({type:'complete',event:'product',value:category});
if(event==='photo'&&files.length===1&&category==='candle')practiceAction({type:'complete',event:'photo'});
},[practiceRunning,practice.step,category,files]);
const filtered=filterInspectionRows(records,filter,page);
async function openRecord(r){
if(practiceRunning&&page==='history')practiceAction({type:'complete',event:'open'});
const current=resetInspection();setCategory(r.category);setBatch(r.batch||'');setFiles([]);setRecordLoading(true);go('inspect');
try{
const [record,history,reviews]=await Promise.all([api('/api/inspections/'+r.id),api('/api/inspections/'+r.id+'/messages'),SHOWCASE?[]:api('/api/inspections/'+r.id+'/reviews')]);
if(!current())return;
setResult(record);setMessages(history);setReview(reviews.at(-1)||null);setCategory(record.category);setBatch(record.batch||'');
}catch(e){if(current())setError(e.message)}finally{if(current())setRecordLoading(false)}
}
// Batch needs no local dataset: the chosen product's sample photos can be added in one step.
async function useSamplePhotos(){
const chosen=samples.filter(s=>s.category===category);if(!chosen.length)return;
const current=resetInspection();setBatchResult(null);setBatchJob(null);batchSelection.current=null;
try{
const photos=await Promise.all(chosen.map(async s=>{const response=await fetch(practiceRunning?practiceOriginal:url(s.url));if(!response.ok)throw new Error('Sample unavailable');return new File([await response.blob()],s.name+'.jpg',{type:'image/jpeg'})}));
if(current())setFiles(photos);
}catch{if(current())setError('Sample photos could not load. Try again, or choose your own photos.')}
}
async function sampleFile(sample){
if(busy||ragBusy||recordLoading)return;
if(SHOWCASE){const saved=records.find(r=>r.id===sample.record_id);if(saved)await openRecord(saved);else setError('Saved example not found.');return}
const current=resetInspection();
try{const response=await fetch(practiceRunning?practiceOriginal:url(sample.url));if(!response.ok)throw new Error('Sample unavailable');const blob=await response.blob();if(!current())return;setFiles([new File([blob],sample.name+'.jpg',{type:'image/jpeg'})]);setCategory(sample.category);go('inspect')}catch(e){if(current())setError(e.message)}
}
async function inspect(multiple=false,retry=false){
if(busy)return;
const readiness=currentReadiness(multiple,retry);
if(readiness.disabled){setError(readiness.reason);return}
if(multiple&&batchJob&&batchSelection.current===files&&batchJob.category===category&&batchJob.batch===batch.trim()){
if(batchJob.items.every(item=>item.status==='completed')){setNotice('This batch is already complete. Choose a new batch name and select images to start another batch.');return}
retry=true;
}
if(!retry){
if(!files.length){setError('Choose an image first.');return}
if(multiple&&!batch.trim()){setError('Add a batch label so these inspections can be filtered together.');return}
if(files.some(f=>f.size>10*1024*1024)){setError('Each image must be no larger than 10 MB.');return}
if(files.reduce((total,f)=>total+f.size,0)>20*1024*1024){setError('Keep each batch upload under 20 MB.');return}
if(files.length>20){setError('Inspect up to 20 files per batch.');return}
}
const current=resetInspection();setBusy(true);setError('');
const send=async(file,product,label,requestId='')=>{const body=new FormData();body.append('category',product);body.append('batch',label);body.append('file',file);if(requestId)body.append('request_id',requestId);return api('/api/inspect',{method:'POST',body})};
try{
if(multiple){
batchLoad.current++;
const owner=await batchOwner();batchIdentity.current=owner;
if(!retry){const check=await api('/api/batch-name?name='+encodeURIComponent(batch.trim()));if(!current())return;if(!check.available)throw new Error('This batch name is already used in this workspace. Choose a different name. No images were submitted.')}
const job=retry?batchJob:newBatch(files,category,batch.trim());if(!retry)batchSelection.current=files;
if(!job)throw new Error('No unfinished batch is available.');
if(!current())return;
setCategory(job.category);setBatch(job.batch);
const save=async updated=>{
try{await checkpointBatch(owner,updated)}catch{if(current())setBatchWarning('Progress is retained in this tab, but browser recovery could not be saved.')}
if(current()){setBatchJob(updated);setBatchResult(batchView(updated))}
};
await save(job);await continueBatch(job,send,save,()=>current()&&batchIdentity.current===owner);
}else{
// Single photos are individual inspections; batch labels belong to Batch inspection.
const previous=singleSubmission.current;
if(!previous||previous.file!==files[0]||previous.category!==category)singleSubmission.current={file:files[0],category,batch:'',id:newBatch([files[0]],category,'').items[0].id};
const data=await send(files[0],category,'',singleSubmission.current.id);if(current())setResult(data)
}
await refresh().catch(()=>{});
}catch(e){if(current())setError(e.message)}finally{if(current())setBusy(false)}
}
async function ask(text=question){
if(!result||ragBusy||text.trim().length<3)return;
const current=context.current.capture(),identifier=result.id;
setRagBusy(true);setError('');setQuestion('');
try{const answer=await api('/api/assistant',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({inspection_id:identifier,question:text})});if(current())setMessages(old=>[...old,{role:'user',question:text},{role:'assistant',...answer}])}catch(e){if(current()){setError(e.message);setQuestion(text)}}finally{if(current())setRagBusy(false)}
}
async function exportHistory(all=false){
try{
const query=new URLSearchParams(all?{}:Object.fromEntries(Object.entries(filter).filter(([,value])=>value)));
const response=await request('/api/export.csv'+(query.size?'?'+query:''));
if(!response.ok)throw new Error('Export could not be downloaded. Refresh the workspace and try again.');
const blob=await response.blob(),link=document.createElement('a');link.href=URL.createObjectURL(blob);link.download=all?'defectrag-all.csv':'defectrag-filtered.csv';link.click();setTimeout(()=>URL.revokeObjectURL(link.href),1000);
}catch(e){setError(e.message)}
}
const demoBanner=!SHOWCASE&&publicDemoAvailable(health,inspectionAccess)&&['overview','inspect','batch','team'].includes(page);
const syncLine=sync.state==='synced'?'Updated '+new Date(sync.at).toLocaleTimeString([],{hour:'numeric',minute:'2-digit'}):sync.state==='offline'?'Offline · shown results may be out of date':sync.state==='stale'?'Update failed · shown results may be out of date':sync.state==='blocked'?'Open Staff workspace to finish the account check':'Updating saved work…';
const heading={cases:['TEAM OPERATIONS','Corrective actions','Fix confirmed defects. See who is fixing each one, and by when.'],gallery:['PUBLIC DEMO','Community gallery','Inspections that visitors chose to make public.'],benchmark:['OFFICIAL BENCHMARK','Official benchmark','Saved test results that compare two models. These are not new inspections.'],team:['CONNECTED QUALITY','Staff workspace',signedIn?'Review shared inspections with your team.':'Sign in to review shared inspections.'],recovery:publicDemoAvailable(health,inspectionAccess)?['DEMO RECOVERY','Recover demo inspections','Restore this browser’s archived demo results. They are separate from account and Team history.']:health?.personal_workspace_enabled&&workspace==='personal'?['PERSONAL RECOVERY','Recover private inspections','Bring archived inspections, conversations and review alerts back into this account’s history.']:['DEVELOPER WORKSPACE','Archived inspections','Bring archived inspections and their saved details back into the current history.'],overview:['INSPECTION WORKSPACE','Overview','Check a photo. Review unusual results. Fix real defects.'],inspect:['VISUAL INSPECTION','Image inspection','Pick the product, add a photo, check the result.'],batch:['OPERATIONS','Batch inspection','Check many photos at once.'],history:['INSPECTION LOG','Inspection history','Find past photos and results.'],alerts:['REVIEW QUEUE','Review alerts','Unusual results that need a person to look.'],performance:['MODEL RESULTS','Model performance','How accurate the checks are, product by product.'],about:['HELP & GUIDANCE','Help & references','How to inspect, save, share and review.']}[page]||['','',''];
return
{nav.find(n=>n[0]===page)?.[1]}
{!SHOWCASE&&!practiceRunning&&(who.signedIn?Signed in as {who.name}{who.role&&{who.role}}:)}
{practiceRunning?'Practice workspace · lesson data only. Nothing is saved, shared or emailed.':['team','cases'].includes(page)?'Team workspace · shared with approved Staff':signedIn&&!workspaceStatus?'Account access needs checking · online saving is not confirmed':signedIn?(health.personal_workspace_enabled?(workspace==='personal'?'Personal workspace · only you can see it':'Team workspace · shared with approved Staff'):'Team workspace · shared Staff work'):(health.local_sync_enabled?'Demo workspace · work stays on this computer':'Demo workspace · temporary results for this browser')}
{health?.personal_workspace_enabled?(signedIn?'New results save privately in Personal Workspace. Check the save status. Sharing with the team or public gallery is always a separate choice.':(health?.local_sync_enabled?'Without signing in, results stay on this computer. Copy them into an approved account later if needed.':'Demo results belong to this browser session and may disappear when the online app restarts.')):'Photos and results stay on this computer'}
>}
{page==='batch'?'Batch run':'Inspection result'}
02 / EVIDENCE
{recordLoading?
Opening the saved photo and result…
:busy&&page!=='batch'?
Checking the product photo
The first inspection may take longer while the app gets ready.
0} rows={batchResult.records} emptyMessage="No batch images have completed yet."/>{batchJob&&<>
{busy?'Processing one image at a time. Completed images are kept.':'Continue an unfinished batch in the same browser and account. Photos still waiting are kept on this computer; completed photos are not inspected again.'} {batchJob.items.filter(i=>i.status==='running').map(i=>'Inspecting '+i.filename).join('')}
}>:{SHOWCASE?'Browse the saved batch in the table below, or select an example.':'Choose a product, label the batch and select up to 20 images.'}:result?<>{evaluation?.categories?.[result.category]?.metrics?.image_auroc<0.6&&
Tests showed less reliable results for this product. A Staff member should check the photo before a decision is made.
}
{result.verdict==='Good'?'Looks similar to normal examples':result.verdict==='Anomalous'?'Unusual appearance found':'A closer review is needed'}
{labels[result.category]} · {result.id.slice(0,8)} · {number(result.inference_ms,0)} ms · Model: {result.model_id||'Not recorded'}
A higher score means the photo looks more different from normal examples. It is not a percentage chance of a defect. Highlighted areas need checking; they do not identify the defect or its cause.
>:The result and highlighted photo will appear here after the inspection.}
{page==='inspect'&&result&&!SHOWCASE&&{const current=context.current.capture();const saved=await api('/api/inspections/'+result.id+'/review',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(value)});if(current()){setReview(saved);setNotice(publicDemoAvailable(health,inspectionAccess)?'Demo review saved in this browser session. No Team review or product approval was created.':'Staff review saved. The original inspection result has not changed.')}workspaceChanged();refresh().catch(()=>{})}}/>}
{page==='inspect'&&result&&
Evidence Assistant
Linked to inspection {result.id.slice(0,8)} · explains the saved result using reference information
{[result.verdict==='Good'?'Is this image normal?':'Is this image anomalous?','Does the score mean accuracy?','What does the heatmap show?','Explain this result and its limits.'].map(q=>)}
{s.scope}{s.url.startsWith('https://')&&Open source })}}What this answer is based on
The answer uses the saved inspection result and, when relevant, the references shown above. Some questions can be answered from the saved result alone.
Finding supporting information and preparing an answer…
}
{SHOWCASE&&'These are saved answers, not a live conversation. Some examples have no saved conversation. '}The assistant explains saved results and reference information; it does not look at the photo itself. Check important answers against the original photo and workplace guidance. A reference does not guarantee that every explanation is correct.
}
{page==='inspect'&&result&&!SHOWCASE&&
}
{page==='inspect'&&!result&&
Or try a sample photo
CC BY 4.0 · resized previews; predictions may differ slightly from original-resolution evaluation
}
{page==='batch'&&
Batch history
{stats.batches.filter(b=>b.batch).length} named batches
r.batch?.trim())} emptyMessage={records.some(r=>r.batch?.trim())?undefined:"No batch inspections yet. Choose a new batch name and add photos above."}/>}>}
{page==='history'&&
{SHOWCASE?'Saved verification examples. CSV exports the same saved measurements.':'Showing the latest 500 inspections. Spreadsheet downloads include up to 10,000 matching inspections.'}
Open each one and check the photo. Then mark it as seen.
}
!a.acknowledged)?' warn':' ok')}>{alerts.filter(a=>!a.acknowledged).length} not seen{!SHOWCASE&&alerts.filter(a=>!a.acknowledged).length>1&&(seenAll.phase==='confirm'?<>>:)}
Restore an inspection with its photos, result, conversation and review alerts.
{archived.length} archived
{SHOWCASE?Saved showcase records cannot be archived. Cloud developers recover staff records in Staff workspace.:archived.length?
Inspection
Product
Result
Saved
{archived.map(r=>
{r.id.slice(0,8)}
{labels[r.category]}
{date(r.created_at)}
)}
:No archived inspections here. Archive history moves inspections out of the active list without deleting their saved files.}
{publicDemoAvailable(health,inspectionAccess)?'Only this browser’s demo archive is shown. It may disappear when the online app restarts.':health?.personal_workspace_enabled?(workspace==='personal'?'This account can restore its own Personal inspections.':'Ask a Developer to restore archived Team inspections.'):'This page restores work in the selected workspace. Team work can only be restored by a Developer.'}
}
{page==='performance'&&<>
Results for the app’s inspection settings
This page shows the app’s operating results: precision, recall, F1 and other measurements at its saved review limits. Official benchmark uses a separate benchmark test, so its figures may differ.
Results vary by product. Some unusual photos are missed, and some normal photos are flagged. Use the inspection as a screening aid and follow workplace quality rules before deciding.
Precision means how often a flag was correct. Recall means how many unusual photos were found. Higher recall can also mean more false alarms. These are results from test photos, not a guarantee for the next inspection.
Active model · evaluation protocol
{evaluation?.protocol||'Evaluation results are not available.'}
Retrospective image performance
Binary metrics use the versioned decision threshold. The dashboard also applies a ±5% review band. Precision measures correct anomaly flags; recall measures anomaly coverage. High precision with low recall means many annotated anomalies are missed. AUROC measures ranking across thresholds, not recall at this operating point.
{evaluation?.decision_policy&&
Sensitivity policy: {evaluation.decision_policy==='macaroni-recall-v1'?'Macaroni 1/2 normal 80th percentile; other products normal 95th percentile.':'Held-out normal 95th percentile.'} Mean recall {percent(evaluation.macro_mean?.recall)} · precision {percent(evaluation.macro_mean?.precision)} · normal false-alarm rate {percent(evaluation.macro_mean?.false_positive_rate)}. More anomalies are caught with more review alerts. Historical inspections retain their original thresholds; future rates may differ. {evaluation.decision_policy==='macaroni-recall-v1'&&'Macaroni 1/2 falsely flag 24%/28% of normal benchmark images; review workload is substantially higher.'}
{[['Decision threshold',number(c.threshold,4)],[c.profile?'Pixel AUROC · 224 × 224':'Pixel AUROC · 64 × 64',number(c.metrics?.pixel_auroc_224 ?? c.metrics?.pixel_auroc_64)],['Pixel average precision',number(c.metrics?.pixel_average_precision_224 ?? c.metrics?.pixel_average_precision_64)],['Close-call range coverage',percent(c.metrics?.uncertain_fraction)],['Median model inference',(c.metrics?.latency_median_ms==null&&!evaluation?.serving_profile?.categories?.[k]?'Not profiled':number(evaluation?.serving_profile?.categories?.[k]?.core_median_ms ?? c.metrics?.latency_median_ms,0)+' ms')],['Peak PyTorch GPU allocation',(c.metrics?.peak_gpu_mb==null&&!evaluation?.serving_profile?.categories?.[k]?'Not profiled':number(evaluation?.serving_profile?.categories?.[k]?.peak_torch_allocated_gpu_mb ?? c.metrics?.peak_gpu_mb,1)+' MB')],['Normal bank size',typeof c.bank_size_bytes==='number'?(c.bank_size_bytes/1024**2).toFixed(1)+' MB':'—']].map(([name,v])=>
{name}
{v}
)}
)}
Frozen nearest-normal memory, not Dinomaly. Performance varies by category; inspect image and pixel metrics separately. No supervised defect-type classifier or factory acceptance claim. Core latency excludes image decoding and heatmap rendering. Historical clean serving measurements apply only to their original model profile. GPU allocation excludes other processes and driver memory.
>}
{page==='about'&&}
setArchiveOpen(false)} busy={archiveBusy} onConfirm={async()=>{setArchiveBusy(true);try{const archived=await api('/api/history/archive',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({...filter,confirmation:'ARCHIVE'})});setArchiveOpen(false);setNotice(`${archived.archived} ${archived.archived===1?'inspection':'inspections'} archived. Restore them in History recovery.`);workspaceChanged();refresh().catch(()=>{})}catch(e){setError(e.message)}finally{setArchiveBusy(false)}}}/>
>}/>
{practiceRunning&&practiceAction({type:'back'})}/>}
}
createRoot(document.getElementById('root')).render();