DefectRAG / frontend /src /main.jsx
Wizzas's picture
Upload source code (part 2)
ecb2a3f verified
Raw History Blame Contribute Delete
70.2 kB
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 <span className={'badge '+value?.toLowerCase()}><i/>{resultLabel(value)}</span>}
function Empty({children}) {return <div className="empty"><ScanLine size={30}/><p>{children}</p></div>}
// 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 <div className="gallery">{samples.map(s=><button className="sample" key={s.name} disabled={busy} onClick={()=>onChoose(s)}><img src={sampleThumb(s)} loading="lazy" decoding="async" onError={e=>{if(!e.currentTarget.dataset.fallback){e.currentTarget.dataset.fallback='1';e.currentTarget.src=url(s.url)}}} alt={labels[s.category]+' sample photo'}/><div><strong>{labels[s.category]}</strong><span>{s.name.endsWith('_good')?'Normal sample':'Unusual sample'} <ArrowUpRight size={14}/></span></div></button>)}</div>}
function Filters({filter,setFilter,stats,filteredCount}){return <div className="filters"><Search size={17}/><select aria-label="Filter category" value={filter.category} onChange={e=>setFilter({...filter,category:e.target.value})}><option value="">All products</option>{Object.entries(labels).map(([k,v])=><option key={k} value={k}>{v}</option>)}</select><select aria-label="Filter result" value={filter.verdict} onChange={e=>setFilter({...filter,verdict:e.target.value})}><option value="">All results</option>{['Good','Anomalous','Uncertain'].map(v=><option key={v} value={v}>{resultLabel(v)}</option>)}</select><select aria-label="Filter batch" value={filter.batch} onChange={e=>setFilter({...filter,batch:e.target.value})}><option value="">All batches</option>{stats.batches.filter(b=>b.batch).map(b=><option key={b.batch}>{b.batch}</option>)}</select><button className="text-button" onClick={()=>setFilter({category:'',verdict:'',batch:''})}>Clear filters</button><span>{filteredCount} records shown</span></div>}
function Table({rows=[],emptyMessage,hasRecords,onOpen,reviewMode=false}){return rows.length?<div className="table-wrap"><table className="stackable"><thead><tr><th>Inspection / time</th><th>Product</th><th>Batch</th><th>Result</th><th>Score / review limit</th><th>Time to check</th><th/></tr></thead><tbody>{rows.map(r=><tr key={r.id}><td data-label="Inspection"><strong>{r.id.slice(0,8)}</strong><small>{date(r.created_at)}</small></td><td data-label="Product">{labels[r.category]}</td><td data-label="Batch">{r.batch||'Individual'}</td><td data-label="Result"><Badge value={r.verdict}/></td><td data-label="Score / limit">{number(r.score)} <span className="muted">/ {number(r.threshold)}</span></td><td data-label="Time to check">{number(r.inference_ms,0)} ms</td><td className="row-action"><button className={reviewMode?"text-button":"icon-button"} aria-label={(reviewMode?'Review shared inspection ':'Open inspection ')+r.id.slice(0,8)} onClick={()=>onOpen(r)}>{reviewMode?'Review':<><ArrowUpRight size={18}/><span className="row-open-label">Open</span></>}</button></td></tr>)}</tbody></table></div>:<Empty>{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.')}</Empty>}
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;i<ids.length;i+=5){
const part=ids.slice(i,i+5);
const results=await Promise.allSettled(part.map(id=>api('/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&&current()&&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 <div className="app"><aside className="sidebar"><a className="brand" href="#overview" onClick={()=>go('overview')}><span className="brand-mark"><img src="./logo.svg" alt=""/></span><div>DefectRAG<span>INSPECTION INTELLIGENCE</span></div></a><button type="button" className="menu-toggle" aria-expanded={menuOpen} aria-controls="app-nav" onClick={()=>setMenuOpen(v=>!v)}>{menuOpen?<X size={20}/>:<Menu size={20}/>}<span>{menuOpen?'Close':'Menu'}</span>{!menuOpen&&unseenCount>0&&<span className="nav-count" aria-label={unseenCount+' alerts not seen'}>{unseenCount}</span>}</button>{!practiceRunning&&<button className="sidebar-new" disabled={busy||ragBusy||recordLoading} title={busy||ragBusy||recordLoading?'Finish the current inspection or answer before starting another.':undefined} onClick={()=>{if(busy||ragBusy||recordLoading)return;if(health?.personal_workspace_enabled)changeWorkspace('personal');resetInspection();setFiles([]);go('inspect')}}><Plus size={16}/> {SHOWCASE?'Browse examples':'New inspection'}</button>}<nav id="app-nav" aria-label="Workspace pages" className={menuOpen?'open':undefined}>{navGroups.map(([title,ids])=>{const items=nav.filter(n=>ids.includes(n[0]));return items.length?<div className="nav-group" key={title||'main'}>{title&&<h6>{title}</h6>}{items.map(([id,label,Icon])=><button key={id} className={page===id?'active':''} aria-current={page===id?'page':undefined} onClick={()=>go(id)}><Icon size={16}/>{label}{id==='alerts'&&alerts.some(a=>!a.acknowledged)&&<span className="nav-count">{alerts.filter(a=>!a.acknowledged).length}</span>}</button>)}</div>:null})}</nav><div className="sidebar-bottom"><div className="local-card"><span className={'status-dot '+(!health||['offline','stale'].includes(sync.state)?'offline':'')}/><strong>{practiceRunning?'Practice workspace':SHOWCASE?'Saved example showcase':health?(sync.state==='offline'?'Workspace offline':sync.state==='stale'?'Updates need attention':'Workspace online'):'Connecting to workspace'}</strong><p>{practiceRunning?'Temporary lesson only':SHOWCASE?'Saved examples only':(signedIn?(health?.personal_workspace_enabled?(['team','cases'].includes(page)||workspace==='team'?'Team · shared with approved Staff':'Personal · private to this account'):'Team · shared with approved Staff'):health?.mode==='cloud_session_workspace'?'Temporary demo session':'Saved on this computer')}<br/>Product photo checks</p></div><div className="sidebar-foot"><ShieldCheck size={15}/> Check the result before deciding.</div></div></aside>
<main><div className="topbar"><span className="topbar-title">{nav.find(n=>n[0]===page)?.[1]}</span><div>{!SHOWCASE&&!practiceRunning&&(who.signedIn?<span className="who" role="status" title={who.email}><UserCircle size={18}/><span>Signed in as <strong>{who.name}</strong>{who.role&&<em>{who.role}</em>}</span></span>:<button type="button" className="who who-out" onClick={()=>go('team')}><UserCircle size={18}/><span>Not signed in</span><u>Sign in</u></button>)}<div className="text-size" role="group" aria-label="Text size"><button type="button" aria-label="Smaller text" title="Smaller text" disabled={textSize===TEXT_SIZES[0]} onClick={()=>setTextSize(stepTextSize(textSize,-1))}>A<small>−</small></button><button type="button" aria-label="Larger text" title={'Larger text · now '+Math.round(textSize*100)+'%'} disabled={textSize===TEXT_SIZES.at(-1)} onClick={()=>setTextSize(stepTextSize(textSize,1))}>A<small>+</small></button></div><button type="button" className="theme-toggle" aria-label={theme==='dark'?'Switch to light mode':'Switch to dark mode'} title={theme==='dark'?'Light mode':'Dark mode'} onClick={()=>setTheme(value=>value==='dark'?'light':'dark')}>{theme==='dark'?<Sun size={16}/>:<Moon size={16}/>}</button></div></div><div className="content" key={page+(practiceRunning?':practice':'')}>{!practiceRunning&&<RefreshNotice errors={sectionErrors} block={workspaceBlock} refreshing={sync.state==='refreshing'} onRetry={retryRefresh} onAccount={()=>go('team')} onPersonal={switchToPersonalWorkspace} showAccess={['overview','inspect','batch','history','alerts','recovery'].includes(page)}/>}<header className="page-heading"><div><p className="eyebrow">{heading[0]}</p><h1>{heading[1]}</h1><p>{heading[2]}</p></div><div className="button-row">{page==='overview'&&!practiceRunning&&<button className="secondary" disabled={busy||ragBusy||recordLoading} title={busy||ragBusy||recordLoading?'Finish the current task before starting practice.':undefined} onClick={()=>setTutorialOpen(true)}><BookOpen size={17}/> Tutorial</button>}</div></header>
<ErrorBoundary resetKey={page} onHome={()=>go('overview')} context={()=>({page,mode:SHOWCASE?'showcase':practiceRunning?'practice':health?.mode,sync:sync.state,signedIn,workspace,theme,textSize})}><PageBody render={()=><>
{!SHOWCASE&&!demoBanner&&(health?.mode==='cloud_session_workspace'||health?.local_sync_enabled)&&<section className="note" role="status"><div><strong>{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')}</strong><p>{syncLine}</p>{signedIn&&health.personal_workspace_enabled&&!['team','cases'].includes(page)&&<label>Show inspections from <select aria-label="Inspection data source" value={workspace} disabled={busy||ragBusy||recordLoading} onChange={e=>changeWorkspace(e.target.value)}><option value="personal">Personal Workspace</option><option value="team">Team Workspace</option></select></label>}{health.personal_workspace_enabled&&workspace==='team'&&<p>Start new inspections in Personal workspace. Then share them with the team.</p>}</div></section>}
{health?.local_sync_enabled&&workspace==='personal'&&<LocalSyncPanel key={batchIdentity.current||'browser'} status={localSyncStatus} onRetry={retryRefresh} onResolve={resolveLocalConflict} onBackup={downloadLocalBackup} onListImports={()=>api('/api/local-sync/importable')} onImport={importLocalHistory} canImport={inspectionAccess.state==='authorized'} refreshing={sync.state==='refreshing'}/>}
{demoBanner&&<PublicDemoNotice cloud={health?.mode==='cloud_session_workspace'} status={syncLine+'.'} onStart={page==='inspect'?undefined:openPublicDemo}/>}
{SHOWCASE&&<div className="showcase-banner" role="note"><BookOpen size={21}/><div><strong>Public showcase · saved real results</strong><p>These are saved examples. Photos, results and any conversations can be viewed, but this version cannot check new photos or answer new questions.</p></div><a className="showcase-live" href="https://wizzas-defectrag.hf.space" target="_blank" rel="noopener noreferrer">Try a real inspection on Hugging Face <ArrowRight size={16}/></a></div>}
{notice&&<div className="success" role="status"><Check size={18}/><span>{notice}</span><button className="icon-button" aria-label="Dismiss notice" onClick={()=>setNotice('')}><X size={16}/></button></div>}
{error&&<div role="alert" className="error"><CircleHelp size={18}/><span>{friendlyError(error)}</span><button aria-label="Dismiss error" onClick={()=>setError('')}><X size={17}/></button></div>}
{page==='gallery'&&!SHOWCASE&&<CommunityGallery api={api} staff={Boolean(workspaceStatus?.role)} local={health?.mode==='local_single_user'}/>}
{page==='overview'&&<>{!SHOWCASE&&<ol className="quick-steps" aria-label="What to do"><li><button type="button" onClick={()=>go('inspect')}><b>1</b><span><strong>Check a photo</strong><small>Start a new inspection</small></span><ArrowRight size={18}/></button></li><li><button type="button" onClick={()=>go('alerts')}><b>2</b><span><strong>Look at unusual results</strong><small>{alerts.filter(a=>!a.acknowledged).length?alerts.filter(a=>!a.acknowledged).length+' waiting for you':'Nothing waiting'}</small></span><ArrowRight size={18}/></button></li><li><button type="button" onClick={()=>go('cases')}><b>3</b><span><strong>Fix real defects</strong><small>Assign a person and a deadline</small></span><ArrowRight size={18}/></button></li></ol>}<div className="stats-grid">{overviewCards(stats,{showcase:SHOWCASE}).map(c=><section className="stat card" key={c.title}><div className="stat-head"><span>{c.title}</span>{c.share&&<span className={'stat-trend '+c.tone}>{c.share}</span>}</div><strong>{c.value.toLocaleString()}</strong><div className="stat-foot"><b>{c.line}</b><small>{c.detail}</small></div></section>)}</div><section className="card chart-card"><div className="section-title"><div><h2>Inspections over time</h2><p>{SHOWCASE?'Saved examples per day':'Results saved per day in this workspace'}</p></div><div className="segmented" role="group" aria-label="Chart period">{[[7,'7 days'],[30,'30 days'],[90,'3 months']].map(([d,l])=><button type="button" key={d} className={chartDays===d?'on':''} aria-pressed={chartDays===d} onClick={()=>setChartDays(d)}>{l}</button>)}</div></div><ActivityChart series={dailyActivity(records,chartDays)}/></section><section className="card"><div className="tabs-row"><div className="tab-list" role="tablist" aria-label="Recent inspections">{overviewTabs.map(([id,label,rule])=><button type="button" role="tab" key={id} aria-selected={overviewTab===id} className={overviewTab===id?'on':''} onClick={()=>setOverviewTab(id)}>{label}{id!=='recent'&&<span className="count">{records.filter(rule).length}</span>}</button>)}</div><button className="text-button" onClick={()=>go('history')}>View history <ArrowRight size={15}/></button></div><Table onOpen={openRecord} hasRecords={records.length>0} rows={overviewRows(records,overviewTab)}/></section><section><div className="section-title"><div><h2>Explore with a sample</h2><p>VisA images · Zou et al., ECCV 2022 · CC BY 4.0 · resized previews</p></div></div><Gallery samples={samples} busy={busy||ragBusy||recordLoading} onChoose={sampleFile}/></section></>}
{(page==='inspect'||page==='batch')&&<><div className="inspection-grid"><section className="card upload-card" data-tour={page==='batch'?'batch':undefined}>{SHOWCASE?<><div className="section-title"><h2>Choose a saved inspection</h2><span className="subtle-tag">READ ONLY</span></div><p className="muted">Choose an example to see its saved photo, highlighted areas, result and any saved conversation.</p><Gallery samples={samples} busy={busy||ragBusy||recordLoading} onChoose={sampleFile}/><p className="caption">Batch inspection below shows saved examples only. Use the working app to check new photos.</p></>:<><div className="section-title"><h2>{page==='batch'?'Create a batch':'Add a product photo'}</h2><span className="subtle-tag">01 / INPUT</span></div><label className="field" data-tour="product">Product category<select value={category} onChange={e=>{resetInspection();setError('');setCategory(e.target.value)}} disabled={busy||ragBusy||recordLoading}><option value="">Choose the product in the photo</option>{Object.entries(labels).map(([k,v])=><option key={k} value={k}>{v}</option>)}</select></label>{page==='batch'&&<label className="field">Batch label <span>required</span><input placeholder="e.g. PCB-LINE-01" value={batch} maxLength={80} disabled={busy||ragBusy||recordLoading} onChange={e=>setBatch(e.target.value)}/></label>}<label className="drop-zone">{preview?<img src={preview} alt="Selected upload preview"/>:<Upload size={29}/>}<strong>{files.length?`${files.length} image${files.length>1?'s':''} selected`:'Choose an image'+(page==='batch'?' group':'')}</strong><span>JPEG, PNG or WebP · up to 10 MB each</span><input aria-label="Upload inspection images" type="file" accept="image/jpeg,image/png,image/webp" multiple={page==='batch'} disabled={busy||ragBusy||recordLoading} onChange={e=>{resetInspection();setError('');setBatchResult(null);setBatchJob(null);batchSelection.current=null;setFiles(Array.from(e.target.files||[]));e.target.value=''}}/></label>{page==='batch'&&<div className="batch-samples"><div><strong>No photos to hand?</strong><span>{category?'Add the '+labels[category]+' sample photos to try a batch.':'Choose a product first to see its sample photos.'}</span></div>{category&&<div className="batch-sample-row">{samples.filter(s=>s.category===category).map(s=><img key={s.name} src={sampleThumb(s)} alt={labels[s.category]+' sample photo'} loading="lazy"/>)}</div>}<button type="button" className="secondary" disabled={busy||!samples.some(s=>s.category===category)} onClick={useSamplePhotos}>Add sample photos</button></div>}<InspectionDraft multiple={page==='batch'} files={!result&&!busy&&!(page==='batch'&&batchResult)?files:[]}/><p className="caption">Use a clear photo of the selected product. Other products or unrelated photos may give unreliable results.</p><div data-tour="run"><InspectionAction readiness={currentReadiness(page==='batch')} busy={busy} multiple={page==='batch'} onRun={()=>inspect(page==='batch')} onSwitch={switchToPersonalWorkspace} switchDisabled={busy||ragBusy||recordLoading}/></div><p className="caption">{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'}</p></>}</section><section className="card result-card"><div className="section-title"><h2 ref={resultHeading} tabIndex={-1}>{page==='batch'?'Batch run':'Inspection result'}</h2><span className="subtle-tag">02 / EVIDENCE</span></div>{recordLoading?<div className="empty" role="status"><LoaderCircle className="spin" size={32}/><p>Opening the saved photo and result…</p></div>:busy&&page!=='batch'?<div className="empty"><LoaderCircle className="spin" size={32}/><h3>Checking the product photo</h3><p>The first inspection may take longer while the app gets ready.</p></div>:page==='batch'?batchResult?<><div className="batch-summary"><h3>{batchResult.batch}</h3><p>{batchResult.records.length} completed · {batchResult.errors.length} unfinished</p></div>{batchResult.errors.map((e,i)=><div key={i} className={e.status&&e.status!=='failed'?'note':'error'}>{e.filename}: {friendlyError(e.message)}</div>)}<Table onOpen={openRecord} hasRecords={records.length>0} rows={batchResult.records} emptyMessage="No batch images have completed yet."/>{batchJob&&<><p className="caption" role="status">{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('')}</p>{batchJob.items.some(i=>i.status!=='completed')&&<button className="primary" disabled={busy} onClick={()=>inspect(true,true)}>Continue unfinished photos</button>}</>}{batchWarning&&<p className="error" role="alert">{batchWarning}</p>}</>:<Empty>{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.'}</Empty>:result?<>{evaluation?.categories?.[result.category]?.metrics?.image_auroc<0.6&&<div className="error">Tests showed less reliable results for this product. A Staff member should check the photo before a decision is made.</div>}<div className="result-banner"><div><Badge value={result.verdict}/><h2>{result.verdict==='Good'?'Looks similar to normal examples':result.verdict==='Anomalous'?'Unusual appearance found':'A closer review is needed'}</h2><p>{labels[result.category]} · {result.id.slice(0,8)} · {number(result.inference_ms,0)} ms · Model: {result.model_id||'Not recorded'}</p></div><div className="button-row">{!SHOWCASE&&<div data-tour="share"><WorkspaceShare key={result.id+workspace} record={result} messages={messages} url={url} api={api} enabled={health?.personal_workspace_enabled} local={health?.mode==='local_single_user'} access={inspectionAccess} onNotice={setNotice} onChanged={()=>openRecord(result)}/></div>}<a className="secondary" href={url(result.report_url||`/api/inspections/${result.id}/report`)} target="_blank" rel="noreferrer"><FileText size={16}/> Report</a></div></div><div className="image-toolbar"><span>{heatmap?'Highlighted unusual areas':'Uploaded image'}</span><button className="text-button" onClick={()=>setHeatmap(!heatmap)}>{heatmap?'Show original':'Show highlights'}</button></div><div data-tour="viewer"><InspectionViewer record={result} url={url} heatmap={heatmap} onComparisonUsed={practiceRunning?()=>practiceAction({type:'complete',event:'compare'}):undefined}/></div><div className="score-grid"><div><small>Difference score</small><strong>{number(result.score,4)}</strong></div><div><small>Review limit</small><strong>{number(result.threshold,4)}</strong></div><div><small>Close-call range</small><strong>±{number(result.uncertainty_margin,4)}</strong></div></div><div className="note"><CircleHelp size={16}/> 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.</div><ReferencePhotos record={result}/></>:<Empty>The result and highlighted photo will appear here after the inspection.</Empty>}</section></div>
{page==='inspect'&&result&&!SHOWCASE&&<section className="card"><ReviewForm key={result.id+String(review?.created_at)} demo={publicDemoAvailable(health,inspectionAccess)} current={review} onSave={async value=>{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(()=>{})}}/></section>}
{page==='inspect'&&result&&<section className="card assistant" data-tour="assistant"><div className="section-title"><div><h2><MessageSquare size={19}/> Evidence Assistant</h2><p>Linked to inspection {result.id.slice(0,8)} · explains the saved result using reference information</p></div><span className="subtle-tag">RESULT HELP</span></div><div className="observation"><strong>SAVED RESULT</strong><span>{resultLabel(result.verdict)} · score {number(result.score,4)} · review limit {number(result.threshold,4)} · {labels[result.category]}</span></div>{!SHOWCASE&&<div className="suggestions">{[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=><button key={q} onClick={()=>ask(q)} disabled={ragBusy}>{q}<ArrowUpRight size={14}/></button>)}</div>}<div className="conversation">{messages.map((m,i)=>m.role==='user'?<div key={i} className="user-message"><strong>Inspection question</strong><p>{m.question}</p></div>:<div key={i} className="assistant-message"><div><strong>Evidence Assistant</strong><span className="subtle-tag">{answerLabel(m.mode,SHOWCASE)}</span></div><p className="answer-text">{m.answer}</p>{m.error&&<p className="caption">{friendlyError(m.error)}</p>}{m.evidence?.length>0&&<details><summary>{m.evidence.length} supporting references</summary>{m.evidence.map(s=><article className="source" key={s.chunk_id}><strong>{s.chunk_id} · {s.title}</strong><p>{s.text}</p><small>{s.scope}</small>{s.url.startsWith('https://')&&<a href={s.url} target="_blank" rel="noreferrer">Open source <ArrowUpRight size={12}/></a>}</article>)}</details>}<details className="workflow-details"><summary>What this answer is based on</summary><p>The answer uses the saved inspection result and, when relevant, the references shown above. Some questions can be answered from the saved result alone.</p><details><summary>Technical processing details</summary><small className="trace">{m.trace?.join(' → ')}</small></details></details></div>)}</div>{ragBusy&&<p role="status" className="generating"><LoaderCircle size={17} className="spin"/> Finding supporting information and preparing an answer…</p>}<form className="question-form" onSubmit={e=>{e.preventDefault();ask()}}><input aria-label="Ask a follow-up question" placeholder={SHOWCASE?'Saved conversation only - run locally to ask new questions':'Ask about this inspection or the supporting evidence…'} value={question} maxLength={1200} onChange={e=>setQuestion(e.target.value)} disabled={ragBusy||SHOWCASE}/><button className="primary" disabled={SHOWCASE||ragBusy||question.trim().length<3}>Ask <ArrowRight size={16}/></button></form><p className="caption">{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.</p></section>}
{page==='inspect'&&result&&!SHOWCASE&&<div data-tour="publish"><PublishGalleryPanel key={result.id+workspace} record={result} api={api}/></div>}
{page==='inspect'&&!result&&<section data-tour="samples"><div className="section-title"><div><h2>Or try a sample photo</h2><p>CC BY 4.0 · resized previews; predictions may differ slightly from original-resolution evaluation</p></div></div><Gallery samples={samples} busy={busy||ragBusy||recordLoading} onChoose={sampleFile}/></section>}
{page==='batch'&&<section className="card"><div className="section-title"><h2>Batch history</h2><span className="subtle-tag">{stats.batches.filter(b=>b.batch).length} named batches</span></div><Filters filter={filter} setFilter={setFilter} stats={stats} filteredCount={filtered.length}/><Table rows={filtered} onOpen={openRecord} hasRecords={records.some(r=>r.batch?.trim())} emptyMessage={records.some(r=>r.batch?.trim())?undefined:"No batch inspections yet. Choose a new batch name and add photos above."}/></section>}</>}
{page==='history'&&<section className="card" data-tour="history"><div className="section-title"><h2>Saved inspections</h2><div className="button-row">{!SHOWCASE&&<button className="secondary danger" onClick={()=>setArchiveOpen(true)}>Archive history</button>}{SHOWCASE?<a className="secondary" href={url('/api/export.csv')}><Download size={15}/> Download spreadsheet</a>:<><button className="secondary" onClick={()=>exportHistory()}><Download size={15}/> Download filtered spreadsheet</button><button className="text-button" onClick={()=>exportHistory(true)}>Download all as spreadsheet</button></>}</div></div><Filters filter={filter} setFilter={setFilter} stats={stats} filteredCount={filtered.length}/><Table rows={filtered} reviewMode={workspace==='team'&&sharedAssistantAvailable(health,SHOWCASE)} onOpen={workspace==='team'&&sharedAssistantAvailable(health,SHOWCASE)?openSharedReview:openRecord} hasRecords={records.length>0}/><p className="caption table-caption">{SHOWCASE?'Saved verification examples. CSV exports the same saved measurements.':'Showing the latest 500 inspections. Spreadsheet downloads include up to 10,000 matching inspections.'}</p></section>}
{page==='alerts'&&<section className="card" data-tour="alerts"><div className="section-title alert-head"><div><h2>{SHOWCASE?'Saved review alerts':'Inspections needing review'}</h2>{!SHOWCASE&&<p>Open each one and check the photo. Then mark it as seen.</p>}</div><div className="button-row"><span className={'count-pill'+(alerts.some(a=>!a.acknowledged)?' warn':' ok')}>{alerts.filter(a=>!a.acknowledged).length} not seen</span>{!SHOWCASE&&alerts.filter(a=>!a.acknowledged).length>1&&(seenAll.phase==='confirm'?<><button type="button" className="primary" onClick={markAllSeen}><CheckCheck size={17}/> Yes, mark all {alerts.filter(a=>!a.acknowledged).length}</button><button type="button" className="secondary" onClick={()=>setSeenAll({phase:'idle',done:0,total:0})}>Cancel</button></>:<button type="button" className="primary" disabled={seenAll.phase==='working'} aria-busy={seenAll.phase==='working'} onClick={()=>setSeenAll({phase:'confirm',done:0,total:0})}>{seenAll.phase==='working'?<><LoaderCircle className="spin" size={17}/> Marking {seenAll.done} of {seenAll.total}…</>:<><CheckCheck size={17}/> Mark all as seen</>}</button>)}</div></div>{alerts.length?alerts.map(a=>{const r=records.find(row=>row.id===a.inspection_id);return <div className={'alert-row'+(a.acknowledged?' seen':'')} key={a.id}>{r?.image_url?<img className="alert-thumb" src={url(r.image_url)} loading="lazy" decoding="async" alt={labels[r.category]+' inspection photo'}/>:<Bell size={19}/>}<div><strong>{r?labels[r.category]+' · ':''}{a.kind==='Anomalous'?'Unusual appearance found':'Result needs a closer look'}</strong><p>{r?.batch?.trim()?'Batch '+r.batch+' · ':''}{a.inspection_id.slice(0,8)} · {date(a.created_at)}</p></div><Badge value={a.kind}/><button className="secondary" disabled={SHOWCASE||Boolean(a.acknowledged)||pending['ack:'+a.id]||seenAll.phase==='working'} aria-busy={Boolean(pending['ack:'+a.id])} onClick={()=>acknowledgeOne(a.id)}>{SHOWCASE?'Saved alert':a.acknowledged?<><Check size={15}/> Seen</>:pending['ack:'+a.id]?'Saving…':'Mark as seen'}</button><button className="secondary" aria-label={'Open alerted inspection '+a.inspection_id.slice(0,8)} onClick={()=>{if(r)openRecord(r);else api('/api/inspections/'+a.inspection_id).then(openRecord).catch(e=>setError(e.message))}}>Open <ArrowUpRight size={15}/></button></div>}):<Empty>No alerts. Unusual results will appear here.</Empty>}<div className="note"><CircleHelp size={16}/> “Seen” only means someone looked. It does not approve the product.</div></section>}
{page==='benchmark'&&<BenchmarkReport report={official} labels={labels}/>}
{['team','cases'].includes(page)&&<Suspense fallback={<div className="empty"><LoaderCircle className="spin" size={28}/>Loading staff workspace…</div>}><TeamWorkspace casesView={page==='cases'} initialInspectionId={sharedSelectionId} onOpenCorrectiveActions={openCorrectiveActions} onChooseInspection={chooseTeamInspection} onOpenInspection={sharedAssistantAvailable(health,SHOWCASE)?openTeamRecord:undefined}/></Suspense>}
{page==='recovery'&&<section className="card"><div className="section-title"><div><h2>Archived inspections</h2><p>Restore an inspection with its photos, result, conversation and review alerts.</p></div><span className="subtle-tag">{archived.length} archived</span></div>{SHOWCASE?<Empty>Saved showcase records cannot be archived. Cloud developers recover staff records in Staff workspace.</Empty>:archived.length?<div className="table-wrap"><table className="stackable"><thead><tr><th>Inspection</th><th>Product</th><th>Result</th><th>Saved</th><th/></tr></thead><tbody>{archived.map(r=><tr key={r.id}><td data-label="Inspection">{r.id.slice(0,8)}</td><td data-label="Product">{labels[r.category]}</td><td data-label="Result"><Badge value={r.verdict}/></td><td data-label="Saved">{date(r.created_at)}</td><td className="row-action"><button className="secondary" disabled={pending['restore:'+r.id]} aria-busy={Boolean(pending['restore:'+r.id])} onClick={()=>restoreOne(r.id)}>{pending['restore:'+r.id]?'Restoring…':'Restore inspection'}</button></td></tr>)}</tbody></table></div>:<Empty>No archived inspections here. Archive history moves inspections out of the active list without deleting their saved files.</Empty>}<p className="caption">{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.'}</p></section>}
{page==='performance'&&<><section className="card"><h2>Results for the app’s inspection settings</h2><p>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.</p><p>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.</p><p>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.</p></section><div className="note standalone"><ShieldCheck size={20}/><div><strong>Active model · evaluation protocol</strong><p>{evaluation?.protocol||'Evaluation results are not available.'}</p></div></div><section className="card"><div className="section-title"><div><h2>Retrospective image performance</h2><p>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.</p>{evaluation?.decision_policy&&<p className="caption">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.'}</p>}</div><span className="subtle-tag">REAL PREDICTIONS</span></div><div className="table-wrap"><table><thead><tr><th>Product</th><th>Images</th><th>AUROC</th><th>Avg. precision</th><th>Precision</th><th>Recall</th><th>F1</th></tr></thead><tbody>{Object.entries(evaluation?.categories||{}).map(([k,c])=><tr key={k}><td><strong>{labels[k]}</strong></td><td>{c.metrics?.n_images??'—'}</td>{['image_auroc','average_precision','precision','recall','f1'].map(key=><td key={key}>{number(c.metrics?.[key])}</td>)}</tr>)}</tbody></table></div></section><div className="performance-grid">{Object.entries(evaluation?.categories||{}).map(([k,c])=><section className="card" key={k}><div className="section-title"><h2>{labels[k]}</h2><span className="subtle-tag">{c.train_normal_count} NORMAL FIT</span></div><p className="muted">Confusion matrix · true rows / predicted columns</p><div className="matrix"><span/><small>Good</small><small>Anomalous</small><small>Good</small>{(c.metrics?.confusion_matrix?.[0]||['—','—']).map((n,i)=><b key={i} className={i===0?'correct':''}>{n}</b>)}<small>Anomalous</small>{(c.metrics?.confusion_matrix?.[1]||['—','—']).map((n,i)=><b key={i} className={i===1?'correct':''}>{n}</b>)}</div><dl>{[['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])=><div key={name}><dt>{name}</dt><dd>{v}</dd></div>)}</dl></section>)}</div><div className="note"><CircleHelp size={17}/><p>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.</p></div></>}
{page==='about'&&<StaffHelp health={health} showcase={SHOWCASE} context={{page,mode:SHOWCASE?'showcase':health?.mode,sync:sync.state,signedIn,workspace,theme,textSize}}/>}
<ArchiveDialog scope={health?.mode==='cloud_session_workspace'?(signedIn?(health.personal_workspace_enabled?workspace:'team'):'guest'):'local'} open={archiveOpen} onClose={()=>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)}}}/>
</>}/></ErrorBoundary>
<footer>DefectRAG <span>{SHOWCASE?'Saved examples only':'Inspection & evidence workspace'}</span><span>Screening aid · Staff review before product decisions</span><span className="build-tag" title={'Build '+appBuild.commit+(appBuild.built?' · '+appBuild.built:'')}>v{appBuild.version} · {appBuild.commit}</span></footer></div></main><Tutorial open={tutorialOpen&&!practice.started} onDismiss={closeTutorial} onStart={startPractice}/>{practiceRunning&&<TutorialCoach state={practice} page={page} onGo={go} onSkip={closeTutorial} onFinish={closeTutorial} onBack={()=>practiceAction({type:'back'})}/>}</div>
}
createRoot(document.getElementById('root')).render(<App/>);