PageSourceSearch

https://intel-base.ai/assets/RAGAdmin-BlL3ub7L.js

js intel-base.ai collected 2026-10-05 15:36:25 UTC 37,774 bytes, 9 lines download raw bytes

1const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/reprocessDocument-C2ENA1Dn.js","assets/index-CnoOAt8u.js","assets/react-vendor-BDFCGFgF.js","assets/supabase-Cw9ajmI9.js","assets/radix-C1DJG546.js","assets/index-DMnF-8kU.css"])))=>i.map(i=>d[i]);
2import{r as V,j as e,u as he}from"./react-vendor-BDFCGFgF.js";import{s as u,bu as ge,g as k,h as _,i as P,j as B,k as S,B as b,a0 as I,Z as le,b as L,n as w,T as se,K as U,P as de,J as pe,O as oe,l as x,e as fe,aN as je,aG as ye,y as te,x as re,a as ee,f as Ne,C as ie,bD as we,r as ce}from"./index-CnoOAt8u.js";import{T as me,a as ue,b as q,c as z}from"./tabs-voX3A16L.js";import{S as F}from"./separator-4cb0Ekkv.js";import{A as ae,a as ne}from"./alert-CkIZoW7i.js";import{B as Q}from"./brain-DDyRmg04.js";import{F as ve}from"./file-search-BAwJJA0l.js";import{E as be}from"./eye-BrR0jv-m.js";import{T as ke}from"./trending-up-BhU4781b.js";import{C as Y}from"./circle-check-big-DF-36XLb.js";import{P as xe}from"./play-D-cbg_QQ.js";import"./supabase-Cw9ajmI9.js";import"./radix-C1DJG546.js";class H{static async generateEmbedding(a){const{data:t,error:c}=await u.functions.invoke("generate-embedding",{body:{text:a.substring(0,8192)}});if(c)throw console.error("Error generating embedding:",c),new Error("Failed to generate embedding");return t.embedding}static async searchDocuments(a,t={}){var d;const{similarityThreshold:c=.7,maxResults:i=10,userId:o}=t;try{const l=await this.generateEmbedding(a),r=o||((d=(await u.auth.getUser()).data.user)==null?void 0:d.id);if(!r)throw new Error("User authentication required");const{data:n,error:C}=await u.rpc("search_document_chunks",{query_embedding:l,similarity_threshold:c,match_limit:i,user_id_filter:r});if(C)throw console.error("Semantic search error:",C),new Error("Search failed");const v=(n||[]).map(f=>({id:f.id,document_id:f.document_id,content:f.content,chunk_index:0,token_count:0,metadata:f.metadata,similarity:f.similarity,document_title:f.document_title,document_type:f.document_type}));return{chunks:v,totalResults:v.length,searchQuery:a}}catch(l){throw console.error("RAG search error:",l),l}}static async getDocumentChunks(a){const{data:t,error:c}=await u.from("document_chunks").select(`
3        id,
4        document_id,
5        content,
6        chunk_index,
7        token_count,
8        metadata
9      `).eq("document_id",a).order("chunk_index");if(c)throw console.error("Error fetching document chunks:",c),new Error("Failed to fetch document chunks");return(t||[]).map(i=>({...i,metadata:i.metadata||{}}))}static async getDetailedDocumentStats(){try{const{data:a,error:t}=await u.from("knowledge_base_items").select("id, title, type, created_at").order("created_at",{ascending:!1});if(t)throw t;return await Promise.all((a||[]).map(async i=>{const[o,d,l]=await Promise.all([u.from("document_chunks").select("*",{count:"exact",head:!0}).eq("document_id",i.id),u.from("document_chunks").select("id, token_count, embedding, metadata").eq("document_id",i.id).range(0,5e3),u.from("file_uploads").select("id, processing_status").eq("knowledge_base_item_id",i.id).order("created_at",{ascending:!1})]),{count:r}=o,{data:n,error:C}=d,{data:v}=l;let f=0,E=0,A=0,g=0,y=0,R=0;if(v&&v.length>0)for(const T of v){const{data:m}=await u.from("pdf_page_queue").select("processing_type, status").eq("file_upload_id",T.id);if(m&&m.length>0){R=m.length,f=m.filter(h=>h.processing_type==="vision").length,E=m.filter(h=>h.processing_type==="text").length,A=m.filter(h=>h.status==="completed").length,g=m.filter(h=>h.status==="pending"||h.status==="processing").length,y=m.filter(h=>h.status==="failed").length;break}}if(C)return console.error(`Error fetching chunks for document ${i.id}:`,C),{...i,chunkCount:0,averageChunkSize:0,hasEmbeddings:!1,processingType:"unknown",visionAiPages:0,textOnlyPages:0,totalPagesProcessed:0,reportedPageCount:null,queueVisionPages:f,queueTextPages:E,queueCompletedPages:A,queuePendingPages:g,queueFailedPages:y,queueTotalPages:R};const Z=r||0,J=(n==null?void 0:n.some(T=>T.embedding))||!1,$=n||[],X=$.length>0?Math.round($.reduce((T,m)=>T+(m.token_count||0),0)/$.length):0,O=new Set,M=new Set;let G=null;
9n==null||n.forEach(T=>{const m=T.metadata,h=m==null?void 0:m.page_number;if(m!=null&&m.page_count&&!G&&(G=m.page_count),h){const D=(m==null?void 0:m.processing_method)||"",K=(m==null?void 0:m.source)||"";D==="gpt4v-production"||D==="smart-hybrid-vision"||K==="pdf_page_image"||K==="vision_ai_analysis"||D.includes("gpt4v")||D.includes("vision")?O.add(h):(D==="text-extraction"||D==="smart-hybrid-text"||D==="text-ocr"||D==="pdfjs-text"||K==="text"||K==="pdf_text_extraction"||K==="pdf_text_page"||K==="pdf_text"||D==="text")&&M.add(h)}});const s=O.size,j=M.size,N=new Set([...O,...M]).size,W=!n||n.length===0?"unknown":s>0&&j>0?"hybrid":s>0?"vision-ai":n.some(m=>{const h=m.metadata;return(h==null?void 0:h.processing_method)==="ai-enhanced"||(h==null?void 0:h.image_processing)===!0})?"ai-enhanced":J?"text":"unknown";return{...i,chunkCount:Z,averageChunkSize:X,hasEmbeddings:J,processingType:W,visionAiPages:s,textOnlyPages:j,totalPagesProcessed:N,reportedPageCount:G,queueVisionPages:f,queueTextPages:E,queueCompletedPages:A,queuePendingPages:g,queueFailedPages:y,queueTotalPages:R}}))}catch(a){throw console.error("Error getting detailed document stats:",a),a}}static async getKnowledgeBaseStats(){try{const{count:a}=await u.from("knowledge_base_items").select("*",{count:"exact",head:!0}),{count:t}=await u.from("document_chunks").select("*",{count:"exact",head:!0}).not("embedding","is",null),{data:c,error:i}=await u.from("document_chunks").select("token_count").not("embedding","is",null).range(0,1e4);if(i)throw console.error("Error fetching token stats:",i),i;const o=c&&c.length>0?Math.round(c.reduce((r,n)=>r+(n.token_count||0),0)/c.length):0,{data:d}=await u.from("document_chunks").select("document_id").not("embedding","is",null).range(0,1e4),l=new Set(d==null?void 0:d.map(r=>r.document_id)).size;return{totalDocuments:a||0,totalChunks:t||0,averageChunkSize:o,documentsWithEmbeddings:l}}catch(a){throw console.error("Error getting knowledge base stats:",a),a}}static async reprocessDocument(a){try{const{reprocessDocument:t}=await ge(async()=>{const{reprocessDocument:c}=await import("./reprocessDocument-C2ENA1Dn.js");return{reprocessDocument:c}},__vite__mapDeps([0,1,2,3,4,5]));await t(a)}catch(t){throw console.error("Error reprocessing document:",t),t}}static async testRAGSystem(a="business strategy"){const t=Date.now();try{const c=await this.searchDocuments(a,{maxResults:5,similarityThreshold:.5}),i=Date.now()-t;return{query:a,results:c.chunks,processingTime:i}}catch(c){throw console.error("RAG system test failed:",c),c}}static async bulkProcessKnowledgeItems(){try{const{data:a,error:t}=await u.from("knowledge_base_items").select("id, type, content").in("type",["note","link"]).not("content","is",null);if(t)throw new Error(`Failed to fetch knowledge items: ${t.message}`);let c=0;const i=a.length,o=5;for(let d=0;d<a.length;d+=o){const l=a.slice(d,d+o);await Promise.all(l.map(async r=>{try{await u.functions.invoke("process-knowledge-item",{body:{knowledgeItemId:r.id,type:r.type}}),c++}catch(n){console.error(`Error processing item ${r.id}:`,n)}})),d+o<a.length&&await new Promise(r=>setTimeout(r,1e3))}return{processed:c,total:i}}catch(a){throw console.error("Error in bulkProcessKnowledgeItems:",a),a}}static async bulkProcessTrainingData(){try{const{data:a,error:t}=await u.from("training_data_points").select("*").order("created_at",{ascending:!1});if(t)throw new Error(`Failed to fetch training data points: ${t.message}`);let c=0;const i=a.length,o=5;for(let d=0;d<a.length;d+=o){const l=a.slice(d,d+o);await Promise.all(l.map(async r=>{try{const n={id:r.id,type:r.type,scenario:r.scenario,context:r.context,idealResponse:r.ideal_response,dataSource:r.data_source,businessValues:r.business_values||[],leadershipTone:r.leadership_tone,decisionRationale:r.decision_rationale,metadata:{timestamp:new Date(r.created_at),confidence:r.confidence,impact:r.impact,tags:r.tags||[],relatedData:r.related_data||[],aiEnhanced:r.ai_enhanced}};await u.functions.invoke("process-training-data",{body:{trainingDataPoint:n,userId:r.user_id}}),c++}catch(n){console.error(`Error processing training data point ${r.id}:`,n)}})),d+o<a.length&&await new Promise(r=>setTimeout(r,1e3))}return{processed:c,total:i}}catch(a){throw console.error("Error in bulkProcessTrainingData:",a),a}}}async function _e(){try{console.log("Testing PDF.co secret access...");const{data:p,error:a}=await u.functions.invoke("test-pdf-secret",{body:{}});return a?(console.error("Error calling test-pdf-secret function:",a),{success:!1,error:a.message}):(console.log("Test function response:",p),{success:!0,data:p})}catch(p){return console.error("Exception calling test function:",p),{success:!1,error:p.message}}}const Pe=async()=>{try{const{data:p,error:a}=await u.functions.invoke("test-openai-secret");if(a)throw new Error(a.message);return p}catch(p){throw console.error("Error testing OpenAI secret:",p),p}},Se=({knowledgeItemId:p,onReprocessComplete:a})=>{const[t,c]=V.useState(null),[i,o]=V.useState(!1),[d,l]=V.useState(!1),[r,n]=V.useState("analysis"),C=async(g=!0)=>{o(!0);try{console.log("Running intelligent document analysis...");const{data:y,error:R}=await u.functions.invoke("intelligent-document-analyzer",{body:{knowledgeItemId:p,analyzeOnly:g}});if(R)throw new Error(`Analysis failed: ${R.message}`);c(y),n("results"),g?x.success("Document analysis completed!"):(x.success("Intelligent reprocessing completed!"),a==null||a())}catch(y){console.error("Analysis error:",y),x.error(`Analysis failed: ${y.message}`)}finally{o(!1),l(!1)}},v=async()=>
9{l(!0),await C(!1)},f=g=>{const y=g/1048576;return y<1?`${(g/1024).toFixed(1)}KB`:`${y.toFixed(1)}MB`},E=g=>{switch(g){case"simple":return"bg-green-100 text-green-800";case"medium":return"bg-yellow-100 text-yellow-800";case"complex":return"bg-red-100 text-red-800";default:return"bg-gray-100 text-gray-800"}},A=g=>g>=.8?"text-green-600":g>=.6?"text-yellow-600":"text-red-600";return e.jsxs(k,{className:"w-full",children:[e.jsxs(_,{children:[e.jsxs(P,{className:"flex items-center gap-2",children:[e.jsx(Q,{className:"h-5 w-5"}),"Intelligent Document Reprocessing"]}),e.jsx(B,{children:"AI-powered analysis to determine the optimal processing approach for your document"})]}),e.jsx(S,{children:e.jsxs(me,{value:r,onValueChange:n,className:"space-y-4",children:[e.jsxs(ue,{className:"grid w-full grid-cols-3",children:[e.jsx(q,{value:"analysis",children:"Analysis"}),e.jsx(q,{value:"results",disabled:!t,children:"Results"}),e.jsx(q,{value:"processing",disabled:!t,children:"Processing"})]}),e.jsxs(z,{value:"analysis",className:"space-y-4",children:[e.jsxs(ae,{children:[e.jsx(ve,{className:"h-4 w-4"}),e.jsx(ne,{children:"Our AI will analyze your document's characteristics, size, and complexity to recommend the best processing approach."})]}),e.jsxs("div",{className:"grid gap-3",children:[e.jsx(b,{onClick:()=>C(!0),disabled:i,className:"w-full",children:i?e.jsxs(e.Fragment,{children:[e.jsx(I,{className:"h-4 w-4 mr-2 animate-spin"}),"Analyzing Document..."]}):e.jsxs(e.Fragment,{children:[e.jsx(be,{className:"h-4 w-4 mr-2"}),"Analyze Document"]})}),t&&e.jsx(b,{onClick:v,disabled:d,variant:"default",className:"w-full",children:d?e.jsxs(e.Fragment,{children:[e.jsx(I,{className:"h-4 w-4 mr-2 animate-spin"}),"Processing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(le,{className:"h-4 w-4 mr-2"}),"Run Intelligent Reprocessing"]})})]})]}),e.jsx(z,{value:"results",className:"space-y-4",children:t&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsxs(k,{children:[e.jsx(_,{className:"pb-3",children:e.jsxs(P,{className:"text-base flex items-center gap-2",children:[e.jsx(L,{className:"h-4 w-4"}),"Document Analysis"]})}),e.jsxs(S,{className:"space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-2 text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"File:"}),e.jsx("span",{className:"font-medium",children:t.analysis.fileName}),e.jsx("span",{className:"text-muted-foreground",children:"Size:"}),e.jsx("span",{children:f(t.analysis.fileSize)}),e.jsx("span",{className:"text-muted-foreground",children:"Type:"}),e.jsx("span",{children:t.analysis.fileType}),e.jsx("span",{className:"text-muted-foreground",children:"Pages:"}),e.jsxs("span",{children:["~",t.analysis.estimatedPages]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(w,{className:E(t.analysis.complexity),children:[t.analysis.complexity," complexity"]}),t.analysis.isPDF&&e.jsx(w,{variant:"outline",children:"PDF"}),t.analysis.isImage&&e.jsx(w,{variant:"outline",children:"Image"})]})]})]}),e.jsxs(k,{children:[e.jsx(_,{className:"pb-3",children:e.jsxs(P,{className:"text-base flex items-center gap-2",children:[e.jsx(ke,{className:"h-4 w-4"}),"Processing Status"]})}),e.jsx(S,{className:"space-y-3",children:e.jsxs("div",{className:"grid grid-cols-2 gap-2 text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Existing chunks:"}),e.jsx("span",{className:"font-medium",children:t.processingState.chunkCount}),e.jsx("span",{className:"text-muted-foreground",children:"Has manifest:"}),e.jsxs("span",{className:"flex items-center gap-1",children:[t.processingState.hasManifest?e.jsx(Y,{className:"h-3 w-3 text-green-600"}):e.jsx(se,{className:"h-3 w-3 text-yellow-600"}),t.processingState.hasManifest?"Yes":"No"]}),e.jsx("span",{className:"text-muted-foreground",children:"Last processed:"}),e.jsx("span",{children:t.processingState.lastProcessed?U(t.processingState.lastProcessed):"Never"})]})})]})]}),e.jsxs(k,{children:[e.jsx(_,{className:"pb-3",children:e.jsxs(P,{className:"text-base flex items-center gap-2",children:[e.jsx(Q,{className:"h-4 w-4"}),"AI Recommendation"]})}),e.jsxs(S,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"font-medium",children:"Recommended Function:"}),e.jsx(w,{variant:"default",children:t.recommendation.recommendedFunction})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"font-medium",children:"Confidence:"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(de,{value:t.recommendation.confidence*100,className:"w-20"}
9),e.jsxs("span",{className:`font-medium ${A(t.recommendation.confidence)}`,children:[(t.recommendation.confidence*100).toFixed(0),"%"]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("span",{className:"font-medium",children:"Reason:"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:t.recommendation.reason})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4 text-sm",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(pe,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("span",{children:["Est. cost: $",t.recommendation.estimatedCost.toFixed(3)]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(oe,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("span",{children:["Est. time: ",t.recommendation.estimatedTime]})]})]}),t.recommendation.fallbackOptions.length>0&&e.jsxs("div",{children:[e.jsx("span",{className:"font-medium text-sm",children:"Fallback options:"}),e.jsx("div",{className:"flex gap-1 mt-1",children:t.recommendation.fallbackOptions.map((g,y)=>e.jsx(w,{variant:"outline",className:"text-xs",children:g},y))})]})]})]})]})}),e.jsx(z,{value:"processing",className:"space-y-4",children:(t==null?void 0:t.processingResult)&&e.jsxs(k,{children:[e.jsx(_,{children:e.jsxs(P,{className:"text-base flex items-center gap-2",children:[t.processingResult.success?e.jsx(Y,{className:"h-4 w-4 text-green-600"}):e.jsx(se,{className:"h-4 w-4 text-red-600"}),"Processing Results"]})}),e.jsxs(S,{className:"space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-2 text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Function used:"}),e.jsx("span",{className:"font-medium",children:t.processingResult.function}),e.jsx("span",{className:"text-muted-foreground",children:"Status:"}),e.jsx(w,{variant:t.processingResult.success?"default":"destructive",children:t.processingResult.success?"Success":"Failed"}),t.processingResult.wasFallback&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-muted-foreground",children:"Used fallback:"}),e.jsx("span",{className:"text-yellow-600",children:"Yes"})]})]}),t.processingResult.data&&e.jsx("div",{className:"mt-4 p-3 bg-muted rounded-lg",children:e.jsx("pre",{className:"text-xs overflow-x-auto",children:JSON.stringify(t.processingResult.data,null,2)})})]})]})})]})})]})};function Ae({onResume:p}){const{data:a,isLoading:t}=te({queryKey:["stalled-jobs"],queryFn:async()=>{const i=new Date(Date.now()-3e5).toISOString(),{data:o,error:d}=await u.from("file_uploads").select("id, file_name, file_path, file_type, processing_meta, updated_at").eq("processing_status","processing").not("file_path","like","ai-processing-temp/%").not("file_name","ilike","%_page_%").lt("updated_at",i);if(d)throw d;return o||[]},refetchInterval:3e4}),c=async i=>{try{const{data:o,error:d}=await u.functions.invoke("resume-pdf-processing",{body:{fileUploadId:i}});if(d)throw d;x.success(`Resumed processing from page ${o.resumeFromPage}`),p()}catch(o){x.error(`Resume failed: ${o.message}`)}};return t||!a||a.length===0?null:e.jsxs(ae,{variant:"destructive",className:"border-amber-500 bg-amber-50 dark:bg-amber-950/20",children:[e.jsx(se,{className:"h-4 w-4 text-amber-600"}),e.jsxs(ne,{className:"ml-2",children:[e.jsxs("div",{className:"font-medium text-amber-800 dark:text-amber-300 mb-2",children:[a.length," stalled processing job(s) detected"]}),e.jsx("div",{className:"space-y-2",children:a.map(i=>{const o=i.processing_meta||{},d=o.last_checkpoint_page||0,l=o.total_pages||o.estimated_pages||"?",r=Math.round((Date.now()-new Date(i.updated_at).getTime())/6e4);return e.jsxs("div",{className:"flex items-center justify-between p-2 bg-white dark:bg-background rounded border",children:[e.jsxs("div",{className:"text-sm",children:[e.jsx("span",{className:"font-medium",children:i.file_name}),e.jsxs("span",{className:"text-muted-foreground ml-2",children:["Page ",d,"/",l," • Stalled ",r,"m ago"]})]}),e.jsxs(b,{onClick:()=>c(i.id),variant:"outline",size:"sm",className:"ml-2",children:[e.jsx(xe,{className:"h-3 w-3 mr-1"}),"Resume"]})]},i.id)})})]})]})}const Ke=()=>{var O,M,G;const{isSuperAdmin:p}=fe(),[a,t]=V.useState(null),[c,i]=V.useState(null),o=je(),d=he(),{items:l,loading:r}=ye(),{data:n,isLoading:C,refetch:v}=te({queryKey:["rag-stats"],queryFn:()=>H.getKnowledgeBaseStats(),refetchInterval:3e4}),{data:f,isLoading:E}=te({queryKey:["rag-detailed-stats"],queryFn:()=>H.getDetailedDocumentStats(),refetchInterval:3e4}),A=re({mutationFn:s=>H.testRAGSystem(s),onSuccess:s=>{x.success(`RAG test completed in ${s.processingTime}ms`)},onError:s=>{x.error(`RAG test failed: ${s.message}`)}}),g=re({mutationFn:s=>H.reprocessDocument(s),onSuccess:()=>{x.success("Document reprocessing initiated"),o.invalidateQueries({queryKey:["knowledge-items"]}),v(),t(null)},onError:s=>{x.error(`Reprocessing failed: ${s.message}`),t(null)}}),y=async s=>{t(s),g.mutate(s)},R=()=>{A.mutate("business strategy and decision making")},Z=async()=>{const s=await _e();s.success?x.success(`PDF.co secret test successful: ${JSON.stringify(s.data,null,2)}`):x.error(`PDF.co secret test failed: ${s.error}`)},J=async()=>{try{const{data:s,error:j}=await u.from("file_uploads").select("id, file_name, file_path").or("file_path.like.%invalid%,file_path.like.%nonexistent%,file_path.like.%test-batch%,file_name.like.%test%");if(j)throw j;if(!s||s.length===0){x.success("Database is clean - no invalid test entries found ✅");return}const{error:N}=await u.from("file_uploads").delete().or("file_path.like.%invalid%,file_path.like.%nonexistent%,file_path.like.%test-batch%,file_name.like.%test%");if(N)throw N;x.success(`Cleaned up ${s.length} invalid test entries ✅`)}catch(s){x.error(`Database cleanup failed: ${s.message}`)}},$=()=>n&&n.totalDocuments>0?Math.round(n.documentsWithEmbeddings/n.totalDocuments*100):0,X=s=>s?e.jsx(Y,{className:"h-4 w-4 text-green-600"}):e.jsx(ce,{className:"h-4 w-4 text-yellow-600"});return C||r?e.jsxs("div",{className:"container mx-auto p-4 space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ee,{className:"h-6 w-6"}),e.jsx("h1",{className:"text-2xl font-bold",children:"RAG System Admin"})]}),e.jsx("div",{className:"grid gap-4",children:[1,2,3].map(s=>e.jsx("div",{className:"h-32 bg-muted animate-pulse rounded-lg"},s))})]}):e.jsxs("div",{className:"container mx-auto p-4 space-y-6",children:[e.jsx("div",{className:"flex items-center justify-between",children:e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs(b,{onClick:()=>d("/dashboard"),variant:"ghost",size:"sm",className:"flex items-center gap-2",children:[e.jsx(Ne,{className:"h-4 w-4"}),"Back to Dashboard"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ee,{className:"h-6 w-6"}),e.jsx("h1",{className:"text-2xl font-bold",children:"RAG System Admin"})]})]})}),e.jsxs(me,{defaultValue:"overview",className:"space-y-4",children:[e.jsxs(ue,{className:`grid w-full ${p?"grid-cols-4":"grid-cols-3"}`,children:[e.jsx(q,{value:"overview",children:"Overview"}),e.jsx(q,{value:"documents",children:"Documents"}),e.jsx(q,{value:"intelligent",children:"Intelligent"}),p&&e.jsx(q,{value:"settings",children:"Settings"})]}),e.jsxs(z,{value:"overview",className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-4",children:[e.jsxs(k,{children:[e.jsxs(_,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(P,{className:"text-sm font-medium",children:"Total Documents"}),e.jsx(L,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(S,{children:[e.jsx("div",{className:"text-2xl font-bold",children:(n==null?void 0:n.totalDocuments)||0}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Knowledge base items"})]})]}),e.jsxs(k,{children:[e.jsxs(_,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(P,{className:"text-sm font-medium",children:"Document Chunks"}),e.jsx(ie,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(S,{children:[e.jsx("div",{className:"text-2xl font-bold",children:(n==null?void 0:n.totalChunks)||0}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Processed text chunks"})]})]}),e.jsxs(k,{children:[e.jsxs(_,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(P,{className:"text-sm font-medium",children:"Avg Chunk Size"}),e.jsx(we,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(S,{children:[e.jsx("div",{className:"text-2xl font-bold",children:(n==null?void 0:n.averageChunkSize)||0}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Tokens per 
9chunk"})]})]}),e.jsxs(k,{children:[e.jsxs(_,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(P,{className:"text-sm font-medium",children:"Embedding Coverage"}),e.jsx(ee,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(S,{children:[e.jsxs("div",{className:"text-2xl font-bold",children:[$(),"%"]}),e.jsx(de,{value:$(),className:"mt-2"}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:[(n==null?void 0:n.documentsWithEmbeddings)||0," of ",(n==null?void 0:n.totalDocuments)||0," documents"]})]})]})]}),e.jsxs(k,{children:[e.jsxs(_,{children:[e.jsx(P,{children:"Document Processing Details"}),e.jsx(B,{children:"Detailed breakdown of each document's processing status and chunk information"})]}),e.jsx(S,{children:E?e.jsx("div",{className:"space-y-3",children:[1,2,3].map(s=>e.jsx("div",{className:"h-16 bg-muted animate-pulse rounded-lg"},s))}):e.jsxs("div",{className:"overflow-x-auto",children:[e.jsxs("table",{className:"w-full border-collapse",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-border",children:[e.jsx("th",{className:"text-left py-3 px-4 font-medium text-sm",children:"Document"}),e.jsx("th",{className:"text-left py-3 px-4 font-medium text-sm",children:"Type"}),e.jsx("th",{className:"text-center py-3 px-4 font-medium text-sm",children:"Chunks"}),e.jsx("th",{className:"text-center py-3 px-4 font-medium text-sm",children:"Pages Processed"}),e.jsx("th",{className:"text-center py-3 px-4 font-medium text-sm",children:"Processing"}),e.jsx("th",{className:"text-center py-3 px-4 font-medium text-sm",children:"Status"}),e.jsx("th",{className:"text-center py-3 px-4 font-medium text-sm",children:"Actions"})]})}),e.jsx("tbody",{children:f==null?void 0:f.map(s=>e.jsxs("tr",{className:"border-b border-border/50 hover:bg-muted/50",children:[e.jsx("td",{className:"py-3 px-4",children:e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"font-medium text-sm",children:s.title}),e.jsx("span",{className:"text-xs text-muted-foreground",children:U(s.created_at)})]})}),e.jsx("td",{className:"py-3 px-4",children:e.jsx(w,{variant:"secondary",className:"text-xs",children:s.type})}),e.jsx("td",{className:"py-3 px-4 text-center",children:e.jsxs("div",{className:"flex flex-col items-center",children:[e.jsx("span",{className:"font-medium",children:s.chunkCount}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[s.averageChunkSize," tokens avg"]})]})}),e.jsx("td",{className:"py-3 px-4 text-center",children:s.queueTotalPages>0?e.jsxs("div",{className:"flex flex-col items-center gap-1",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"font-medium",children:s.queueCompletedPages}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:["/ ",s.queueTotalPages]})]}),e.jsxs("div",{className:"flex gap-1 text-xs flex-wrap justify-center",children:[s.queueVisionPages>0&&e.jsxs(w,{variant:"default",className:"text-[10px] px-1.5 py-0",children:[s.queueVisionPages," Vision"]}),s.queueTextPages>0&&e.jsxs(w,{variant:"outline",className:"text-[10px] px-1.5 py-0",children:[s.queueTextPages," Text"]})]}),s.queuePendingPages>0&&e.jsxs("span",{className:"text-xs text-amber-600 font-medium",children:[s.queuePendingPages," pending"]}),s.queueFailedPages>0&&e.jsxs("span",{className:"text-xs text-destructive font-medium",children:[s.queueFailedPages," failed"]})]}):s.reportedPageCount?e.jsxs("div",{className:"flex flex-col items-center gap-1",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"font-medium",children:s.totalPagesProcessed}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:["/ ",s.reportedPageCount]})]}),e.jsxs("div",{className:"flex gap-1 text-xs",children:[s.visionAiPages>0&&e.jsxs(w,{variant:"default",className:"text-[10px] px-1.5 py-0",children:[s.visionAiPages," Vision"]}),s.textOnlyPages>0&&e.jsxs(w,{variant:"outline",className:"text-[10px] px-1.5 py-0",children:[s.textOnlyPages," Text"]})]}),s.totalPagesProcessed<s.reportedPageCount&&e.jsxs("span",{className:"text-xs text-destructive font-medium",children:[s.reportedPageCount-s.totalPagesProcessed," pages missing!"]})]}):e.jsx("span",{className:"text-xs text-muted-foreground",children:"N/A"})}),e.jsx("td",{className:"py-3 px-4 text-center",children:e.jsx(w,{variant:s.processingType==="vision-ai"||s.processingType==="ai-enhanced"||s.processingType==="hybrid"?"default":"outline",className:"text-xs",children:s.processingType==="vision-ai"?"Vision AI":s.processingType==="hybrid"?"Hybrid":s.processingType==="ai-enhanced"?"AI Enhanced":s.processingType==="text"?"Text Only":"Unknown"})}),e.jsx("td",{className:"py-3 px-4 text-center",children:s.hasEmbeddings?e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsx(Y,{className:"h-4 w-4 text-green-600"}),e.jsx("span",{className:"text-xs text-green-600",children:"Ready"})]}):e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsx(ce,{className:"h-4 w-4 text-yellow-600"}),e.jsx("span",{className:"text-xs text-yellow-600",children:"Pending"})]})}),e.jsx("td",{className:"py-3 px-4 text-center",children:e.jsx(b,{onClick:()=>y(s.id),disabled:a===s.id||g.isPending,variant:"ghost",size:"sm",children:a===s.id?e.jsx(I,{className:"h-3 w-3 animate-spin"}):e.jsx(I,{className:"h-3 w-3"})})})]},s.id))})]}),(!f||f.length===0)&&e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(L,{className:"h-8 w-8 mx-auto mb-2 opacity-50"}),e.jsx("p",{children:"No documents found"})]})]})})]})]}),e.jsx(z,{value:"documents",className:"space-y-4",children:e.jsxs(k,{children:[e.jsxs(_,{children:[e.jsx(P,{children:"Document Management"}),e.jsx(B,{children:"Manage embeddings and reprocess documents"})]}),e.jsx(S,{children:e.jsx("div",{className:"space-y-3",children:l==null?void 0:l.map(s=>{const j=(n==null?void 0:n.documentsWithEmbeddings)&&l.filter(N=>N.id===s.id).length>0;return e.jsxs("div",{className:"flex items-center justify-between p-3 border rounded",children:[e.jsxs("div",{className:"flex items-center gap-3 flex-1 min-w-0",children:[X(!!j),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium truncate",children:s.title}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[s.type," • ",U(s.created_at)]})]})]}),e.jsxs(b,{onClick:()=>y(s.id),disabled:a===s.id||g.isPending,variant:"outline",size:"sm",children:[a===s.id?e.jsx(I,{className:"h-4 w-4 animate-spin"}):e.jsx(I,{className:"h-4 w-4"}),e.jsx("span",{className:"ml-2 hidden sm:inline",children:"Reprocess"})]})]},s.id)})})})]})}),e.jsx(z,{value:"intelligent",className:"space-y-4",children:e.jsxs(k,{children:[e.jsxs(_,{children:[e.jsxs(P,{className:"flex items-center gap-2",children:[e.jsx(Q,{className:"h-5 w-5"}),"AI-Powered Document Analysis"]}),e.jsx(B,{children:"Select a document to analyze and get intelligent reprocessing recommendations"})]}),e.jsx(S,{children:c?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"font-medium",children:(O=l==null?void 0:l.find(s=>
9s.id===c))==null?void 0:O.title}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[(M=l==null?void 0:l.find(s=>s.id===c))==null?void 0:M.type," •",U(((G=l==null?void 0:l.find(s=>s.id===c))==null?void 0:G.created_at)||"")]})]}),e.jsx(b,{onClick:()=>i(null),variant:"outline",size:"sm",children:"Change Document"})]}),e.jsx(Se,{knowledgeItemId:c,onReprocessComplete:()=>{o.invalidateQueries({queryKey:["knowledge-items"]}),v()}})]}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs(ae,{children:[e.jsx(Q,{className:"h-4 w-4"}),e.jsx(ne,{children:"Choose a document below to run AI-powered analysis and get optimal reprocessing recommendations."})]}),e.jsxs("div",{className:"space-y-2",children:[l==null?void 0:l.map(s=>e.jsxs("div",{className:"flex items-center justify-between p-3 border rounded hover:bg-muted/50 cursor-pointer",onClick:()=>i(s.id),children:[e.jsxs("div",{className:"flex items-center gap-3 flex-1 min-w-0",children:[e.jsx(L,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium truncate",children:s.title}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[s.type," • ",U(s.created_at)]})]})]}),e.jsxs(b,{variant:"ghost",size:"sm",className:"shrink-0",children:[e.jsx(Q,{className:"h-4 w-4"}),e.jsx("span",{className:"ml-2 hidden sm:inline",children:"Analyze"})]})]},s.id)),(!l||l.length===0)&&e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(L,{className:"h-8 w-8 mx-auto mb-2 opacity-50"}),e.jsx("p",{children:"No documents available for analysis"})]})]})]})})]})}),e.jsx(z,{value:"settings",className:"space-y-4",children:p&&e.jsxs(e.Fragment,{children:[e.jsxs(k,{children:[e.jsxs(_,{children:[e.jsx(P,{children:"System Settings"}),e.jsx(B,{children:"Configure RAG system parameters and manual reprocessing"})]}),e.jsxs(S,{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Similarity Threshold"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Minimum similarity score for search results"})]}),e.jsx(w,{variant:"outline",children:"0.7"})]}),e.jsx(F,{}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Max Results"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Maximum number of chunks to return"})]}),e.jsx(w,{variant:"outline",children:"10"})]}),e.jsx(F,{}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Embedding Model"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"OpenAI text embedding model"})]}),e.jsx(w,{variant:"outline",children:"text-embedding-3-small"})]})]}),e.jsx(F,{}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"PDF.co Integration Test"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Test if PDF.co API key is accessible to Edge Functions"})]}),e.jsx(b,{onClick:Z,variant:"outline",size:"sm",children:"Test PDF.co Secret"})]}),e.jsx(F,{}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"OpenAI Integration Test"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Test if OpenAI API key is accessible for GPT-4V processing"})]}),e.jsx(b,{onClick:async()=>{try{const s=await Pe();s.success?x.success(`OpenAI API key is accessible! Found ${s.modelsCount} models ✅`):x.error(`OpenAI test failed: ${s.error}`)}catch(s){x.error(`OpenAI test error: ${s.message}`)}},variant:"outline",size:"sm",children:"Test OpenAI Secret"})]}),e.jsx(F,{}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Database Cleanup"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Remove invalid test entries and orphaned file records"})]}),e.jsx(b,{onClick:J,variant:"outline",size:"sm",children:"Clean Database"})]}),e.jsx(F,{}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Resume Stalled Processing"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:'Find and resume jobs stuck in "processing" for over 5 minutes'})]}),e.jsxs(b,{onClick:async()=>{var s,j;try{const{data:N,error:W}=await u.functions.invoke("resume-pdf-processing",{body:{checkAllStalled:!0}});if(W)throw W;((s=N.resumed)==null?void 0:s.length)>0?x.success(`Resumed ${N.resumed.length} stalled job(s)`):((j=N.failed)==null?void 0:j.length)>0?x.warning(`${N.failed.length} job(s) exceeded max retries`):x.success("No stalled jobs found ✅"),o.invalidateQueries({queryKey:["knowledge-items"]}),v()}catch(N){x.error(`Resume failed: ${N.message}`)}},variant:"outline",size:"sm",children:[e.jsx(xe,{className:"h-4 w-4 mr-2"}),"Resume Stalled"]})]}),e.jsx(F,{}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Resume Incomplete Documents"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:'Find jobs marked "completed" but with missing pages (e.g., 62/183 processed)'})]}),e.jsxs(b,{onClick:async()=>{var s;try{x.info("Scanning for incomplete documents...");const{data:j,error:N}=await u.functions.invoke("resume-pdf-processing",{body:{forceResumeIncomplete:!0}});if(N)throw N;((s=j.resumed)==null?void 0:s.length)>0?x.success(`Force-resumed ${j.resumed.length} incomplete job(s): ${j.resumed.join(", ")}`):x.success("All documents are complete ✅"),o.invalidateQueries({queryKey:["knowledge-items"]}),v()}catch(j){x.error(`Resume incomplete failed: ${j.message}`)}},variant:"outline",size:"sm",children:[e.jsx(I,{className:"h-4 w-4 mr-2"}),"Resume Incomplete"]})]})]})]}),e.jsx(Ae,{onResume:()=>{o.invalidateQueries({queryKey:["knowledge-items"]}),v()}}),e.jsxs(k,{children:[e.jsxs(_,{children:[e.jsx(P,{children:"Test RAG System"}),e.jsx(B,{children:"Run a test query against the RAG system to verify it's working"})]}),e.jsxs(S,{className:"space-y-4",children:[e.jsxs(b,{onClick:R,disabled:A.isPending,variant:"outline",children:[e.jsx(le,{className:"h-4 w-4 mr-2"}),A.isPending?"Testing...":"Test RAG"]}),A.data&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(oe,{className:"h-4 w-4"}),e.jsxs("span",{className:"text-sm",children:["Processing time: ",A.data.processingTime,"ms"]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ie,{className:"h-4 w-4"}),e.jsxs("span",{className:"text-sm",children:["Results found: ",A.data.results.length]})]}),A.data.results.map((s,j)=>e.jsxs("div",{className:"border rounded p-3 text-sm",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsxs(w,{variant:"secondary",children:["Similarity: ",(s.similarity*100).toFixed(1),"%"]}),e.jsx("span",{className:"text-muted-foreground",children:s.document_title})]}),e.jsxs("p",{className:"text-muted-foreground line-clamp-2",children:[s.content.substring(0,150),"..."]})]},s.id))]})]})]})]})})]})]})};export{Ke as default};

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.