diff --git "a/assets/PaperDetailView-DLBdTe9q.js" "b/assets/PaperDetailView-DLBdTe9q.js" new file mode 100644--- /dev/null +++ "b/assets/PaperDetailView-DLBdTe9q.js" @@ -0,0 +1,24 @@ +import{d as Dt,n as Ss,u as Ht,e as te,f as Ps,r as p,j as e,g as de,C as he,P as Mt,h as xe,k as zt,l as Se,m as Ce,o as qt,p as ht,q as Re,X as pt,L as le,s as Is,t as $s,R as As,I as Rs,v as Kt,w as Fs,x as Ls,T as Ts,A as it,y as Le,z as Fe,B as ot,D as Ot,E as Us,c as Bs,F as Ds,b as Hs,G as Ms,H as zs,J as qs,K as Ks,M as Os}from"./index-BJHhPv_M.js";import{I as G,T as Qs,M as Gs,S as Vs,a as Js}from"./components-wRHDLoMO.js";import{L as Ae,a as Xs}from"./LatexTitle-Cb0dDCMw.js";import{e as Te,C as Ws,E as Ys}from"./ExternalSourceEvalBadge-D-cpVwI4.js";import{p as V}from"./papers-CWyBrS8M.js";import{s as ce}from"./safeExternalHref-CkBrsh84.js";import{u as Z}from"./useQuery-B9A-sza5.js";import{b as Zs}from"./usePapers-Dubaj0sc.js";import{f as ea,D as ta}from"./latexPlainText-DI8YEXVe.js";import{s as sa}from"./transform-DDP8kg8V.js";import{S as Ne}from"./skeleton-utCOClux.js";import{A as aa,a as ra}from"./alert-BiDOKM0e.js";import{B as D}from"./button-BL7Wfk99.js";import{I as W}from"./textarea-EPRANuVM.js";import{D as se,a as ae,b as re,c as ne,d as ie,e as oe}from"./dialog-DINVvlE3.js";import{S as Et,a as Ee}from"./searchable-select-NpNOjZCr.js";import{u as ue}from"./useMutation-rrsjzB5Q.js";import{c as ge}from"./catalog-DOuThn7M.js";import{s as pe}from"./submissions-Dz2yQ0h0.js";import{P as Ue,S as ft,L as Y,a as na}from"./SignInToEditDialog-vE3vqpo1.js";import{L as ee}from"./loader-circle-CaPI_8_v.js";import{T as Be,n as Ge,g as St}from"./github-B2SnkTVu.js";import{D as ia,B as Qt,c as oa,g as la,s as ca,a as da,b as ua,d as ma,i as ha,e as pa}from"./codexAddEvals-CLThdzle.js";import{u as Gt}from"./index-mZqTNISL.js";import{G as Pt}from"./github-BnuvDeYu.js";import{M as fa,r as ga}from"./index-RvWGcsIO.js";import{S as It,s as xa}from"./savedPapersAuth-QFHV9d-7.js";import"./katex.min-BSBacQyE.js";import"./hover-card-CBNxKixP.js";import"./useInfiniteQuery-DeWbJxMK.js";import"./popover-ByfOmyUl.js";/** + * @license lucide-react v0.462.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const $t=Dt("Globe",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20",key:"13o1zl"}],["path",{d:"M2 12h20",key:"9i4pu4"}]]);/** + * @license lucide-react v0.462.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Vt=Dt("Star",[["path",{d:"M11.525 2.295a.53.53 0 0 1 .95 0l2.31 4.679a2.123 2.123 0 0 0 1.595 1.16l5.166.756a.53.53 0 0 1 .294.904l-3.736 3.638a2.123 2.123 0 0 0-.611 1.878l.882 5.14a.53.53 0 0 1-.771.56l-4.618-2.428a2.122 2.122 0 0 0-1.973 0L6.396 21.01a.53.53 0 0 1-.77-.56l.881-5.139a2.122 2.122 0 0 0-.611-1.879L2.16 9.795a.53.53 0 0 1 .294-.906l5.165-.755a2.122 2.122 0 0 0 1.597-1.16z",key:"r04s7s"}]]);function ba(t){return t!=null&&t.can_directly_edit_catalog?"direct":"pending"}function ja(t){return(t??[]).filter(s=>!!(s.dataset_slug&&s.task_slug))}function va(t,s,a="https://paperswithcode.co"){return s.map(r=>{const n=encodeURIComponent(r.evaluation_id),l=`${a}/api/v1/papers/${encodeURIComponent(t)}/leaderboard-badge.svg?eval=${n}&live=1`,i=`${a}/api/v1/papers/${encodeURIComponent(t)}/leaderboard-badge-link?eval=${n}`;return`[![${`Papers with Code: ${r.best_rank===1?"SOTA":`#${r.best_rank}`} on ${r.dataset_name}`}](${l})](${i})`}).join(` +`)}function ya(t){const s=ce(t);if(!s)return!1;const a=new URL(s);return`${a.pathname}?${a.search}`.toLowerCase().includes(".pdf")||a.pathname.toLowerCase().includes("/pdf")}function ka(t,s){if(t.source==="external")return(ya(t.source_url)||!!ce(t.conference_url_pdf))&&t.id?`/pdf/${t.id}`:null;const a=(t.arxiv_id||s).replace(/v\d+$/i,"");return ce(t.url_pdf)&&a?`/pdf/${a}`:null}function wa(t,s=!0){return Z({queryKey:["evaluations","paper",t],queryFn:()=>{if(!t)throw new Error("Paper ID is required");return Te.byPaper(t)},enabled:s&&!!t,staleTime:0,refetchOnMount:"always"})}const Jt=t=>t.replace(/v\d+$/,""),_a={models:"https://huggingface.co/",datasets:"https://huggingface.co/datasets/",spaces:"https://huggingface.co/spaces/"},Ve=(t,s)=>{const a=(t[s]||[]).length;return a<100?{count:a,isLimited:!1}:{count:a,isLimited:!0}},Je=(t,s)=>{const a=t[s];return Array.isArray(a)?a.map(r=>{if(typeof r=="string")return r;if(r&&typeof r=="object"){const n=r;return n.id||n.repoId||null}return null}).filter(r=>!!r).map(r=>`${_a[s]}${r}`):[]},Na=async t=>{try{return(await fetch(`https://huggingface.co/api/papers/${Jt(t)}`)).ok}catch{return!1}},Ca=async t=>{const s=Jt(t),[a,r]=await Promise.all([fetch(`https://huggingface.co/api/arxiv/${s}/repos`).then(async o=>o.ok?o.json():(console.warn(`Failed to fetch repos for arXiv:${s}, status: ${o.status}`),null)).catch(o=>(console.warn(`Failed to fetch repos for arXiv:${s}:`,o),null)),Na(s)]);if(!a)return{models:0,datasets:0,spaces:0,modelUrls:[],datasetUrls:[],spaceUrls:[],isLimited:!1,paperExists:r};const n=Ve(a,"models"),l=Ve(a,"datasets"),i=Ve(a,"spaces");return{models:n.count,datasets:l.count,spaces:i.count,modelUrls:Je(a,"models"),datasetUrls:Je(a,"datasets"),spaceUrls:Je(a,"spaces"),isLimited:n.isLimited||l.isLimited||i.isLimited,paperExists:r}},Ea=t=>Z({queryKey:["huggingface-repos",t],queryFn:()=>Ca(t),enabled:!!t,staleTime:10*60*1e3,retry:1});function Sa(t,s){try{const a=new URL(t),r=a.pathname.replace(/\/$/,"").split("/").filter(Boolean).at(-1);return(r==null?void 0:r.replace(/[-_]+/g," "))||a.hostname.replace(/^www\./,"")}catch{return s}}function Xe(t,s,a){return[...new Set([...t,...s??[]])].map(r=>({href:r,label:Sa(r,a)}))}function We(t,s,a){if(a==null&&t.length===0&&!(s!=null&&s.length))return;const r=new Set([...t,...s??[]]);return Math.max(r.size,a??0)}function Ye(t){return t[0]??"https://huggingface.co"}function Ze(t,s){return s[0]??t}function Pa(t){const s=`${t.title.slice(0,60)}${t.title.length>60?"…":""}`,a=`${t.authors[0]||""}${t.authors.length>1?" et al.":""}`,r=t.authors.join(" and "),n=(t.published||"").slice(0,4)||"—",l=(i,o)=>t.arxiv_id?`@article{${t.arxiv_id.replace(".","")}, + title={{${i}}}, + author=${o}, + year={{${n}}}, + eprint={{${t.arxiv_id}}}, + archivePrefix={{arXiv}} +}`:`@misc{paper${t.id}, + title={{${i}}}, + author=${o}, + year={{${n}}}, + url={{${t.source_url||t.url_abs||""}}} +}`;return{citationDisplay:l(s,`{{${a}}}`),citationCopy:l(t.title,`{${r}}`)}}function Ia(t,s,a){var m,k,E,y;const r={models:t.hf_models??[],datasets:t.hf_datasets??[],spaces:t.hf_spaces??[]},n={models:Xe(r.models,s==null?void 0:s.modelUrls,"Model"),datasets:Xe(r.datasets,s==null?void 0:s.datasetUrls,"Dataset"),spaces:Xe(r.spaces,s==null?void 0:s.spaceUrls,"Space")},l={models:n.models.map(({href:j})=>j),datasets:n.datasets.map(({href:j})=>j),spaces:n.spaces.map(({href:j})=>j)},i=((m=t.arxiv_id)==null?void 0:m.replace(/v\d+$/,""))??null,o=t.arxiv_id?{isLoading:a,paperHref:`https://huggingface.co/papers/${i}`,rows:[{label:"Models",href:Ze(`https://huggingface.co/models?other=arxiv:${t.arxiv_id}`,r.models),count:We(r.models,s==null?void 0:s.modelUrls,s==null?void 0:s.models),isLimited:s==null?void 0:s.isLimited,links:n.models},{label:"Datasets",href:Ze(`https://huggingface.co/datasets?other=arxiv:${t.arxiv_id}`,r.datasets),count:We(r.datasets,s==null?void 0:s.datasetUrls,s==null?void 0:s.datasets),isLimited:s==null?void 0:s.isLimited,links:n.datasets},{label:"Spaces",href:Ze(`https://huggingface.co/papers/${i}`,r.spaces),count:We(r.spaces,s==null?void 0:s.spaceUrls,s==null?void 0:s.spaces),isLimited:s==null?void 0:s.isLimited,links:n.spaces}],footer:`Cite arxiv.org/abs/${i} in a HF README to link it here.`}:{isLoading:!1,paperHref:null,rows:[{label:"Models",href:Ye(r.models),count:r.models.length,links:n.models},{label:"Datasets",href:Ye(r.datasets),count:r.datasets.length,links:n.datasets},{label:"Spaces",href:Ye(r.spaces),count:r.spaces.length,links:n.spaces}],footer:null},c=(t.methods??[]).filter(({source_paper_id:j})=>j===t.id),g=t.introduced_benchmarks??[],x=t.introduced_frameworks??[],u=[c.length&&(c.length===1?"this method":"these methods"),g.length&&(g.length===1?"this benchmark":"these benchmarks"),x.length&&(x.length===1?"this framework":"these frameworks")].filter(j=>!!j);return{...Pa(t),allHfArtifactUrls:l,authorEntries:t.authors.map((j,R)=>{var $,T,N,v;return{name:j,id:((T=($=t.author_links)==null?void 0:$[R])==null?void 0:T.id)??null,hf_username:((v=(N=t.author_links)==null?void 0:N[R])==null?void 0:v.hf_username)??null}}),copyableRanks:ja(t.leaderboard_ranks),hasIntroducedItems:u.length>0,hasLineageItems:!!((k=t.predecessor_papers)!=null&&k.length||(E=t.successor_papers)!=null&&E.length),hfArtifactViewer:o,hfPaperExists:!!(s!=null&&s.paperExists),introducedBenchmarks:g,introducedFrameworks:x,introducedMethods:c,introducedSummary:u.join(" and "),numPages:t.num_pages||null,paperSourceLabel:t.arxiv_id?`arXiv:${t.arxiv_id}`:"External resource",predecessorPapers:t.predecessor_papers??[],projectPages:((y=t.project_pages)==null?void 0:y.filter(({url:j})=>j).map(j=>({...j,safeHref:ce(j.url)})))??[],repoSummary:sa(t.repositories),safeAbstractUrl:ce(t.url_abs),safeConferenceUrl:ce(t.conference_url_abs),safePdfUrl:ce(t.url_pdf),sourceActionLabel:t.source==="external"?"Source page":"arXiv page",successorPapers:t.successor_papers??[]}}const $a=["tldr","abstract","tasks","methods","results"];function Aa(t){if(!t)return{section:null,resultsTaskSlug:null};const[s,a]=t.split("?",2);if(!$a.includes(s))return{section:null,resultsTaskSlug:null};const r=s;return r!=="results"||!a?{section:r,resultsTaskSlug:null}:{section:r,resultsTaskSlug:new URLSearchParams(a).get("task")}}const Xt=t=>`results-task-${t}`,Ra=t=>`#results?task=${encodeURIComponent(t)}`;function Fa(t,s){return t&&!!s}function La({direct:t,paperId:s,refetchEvaluations:a,refetchPaper:r}){r(),a(),!(!t||!s)&&(V.primeCurationState(s,!0).catch(()=>{}),Te.primeCurationState(s,!0).catch(()=>{}))}function Ta(t,s){const a=t?Ss(t):"",r=Ht(),{toast:n}=te(),{preferences:l}=Ps(),i=Zs(a,!!a),o=i.data,[c,g]=p.useState(!1);p.useEffect(()=>{!t||t===a||r(`/paper/${a}${window.location.search}${window.location.hash}`,{replace:!0})},[a,r,t]),p.useEffect(()=>{if(o!=null&&o.title)return document.title=ea(o.title),()=>{document.title=ta}},[o==null?void 0:o.title]),p.useEffect(()=>{if(g(!1),!(o!=null&&o.id))return;const N=window.setTimeout(()=>g(!0),0);return()=>window.clearTimeout(N)},[o==null?void 0:o.id]);const x=Fa(c,o==null?void 0:o.id),u=Ea(c?o==null?void 0:o.arxiv_id:void 0),m=wa(o==null?void 0:o.id,x),k=Z({queryKey:["paper-versions",o==null?void 0:o.arxiv_id],queryFn:()=>V.versions(o.arxiv_id.replace(/v\d+$/,"")),enabled:x&&!!(o!=null&&o.arxiv_id),staleTime:10*60*1e3}),E=Z({queryKey:["related-papers",o==null?void 0:o.id],queryFn:()=>V.related(o.arxiv_id||o.id,4),enabled:x,staleTime:10*60*1e3});p.useEffect(()=>{const N=()=>{La({direct:s==="direct",paperId:o==null?void 0:o.id,refetchEvaluations:m.refetch,refetchPaper:i.refetch}),n({title:"This section changed",description:"The latest state has been reloaded. Review your changes before submitting again.",variant:"destructive"})};return window.addEventListener("pwc:catalog-conflict",N),()=>window.removeEventListener("pwc:catalog-conflict",N)},[s,m.refetch,o==null?void 0:o.id,i.refetch,n]);const y=p.useMemo(()=>{const N=m.data;return!N||!l.hide_closed_source_evals?N:N.filter(v=>v.is_open!==!1)},[m.data,l.hide_closed_source_evals]),j=p.useMemo(()=>{if(!y)return[];const N=new Map;for(const v of y){const h=N.get(v.task_id);h?h.rows.push(v):N.set(v.task_id,{taskId:v.task_id,taskName:v.task_name||"—",taskSlug:v.task_slug,rows:[v]})}return[...N.values()]},[y]),R=p.useMemo(()=>j.map(({taskSlug:N})=>N??"").join("|"),[j]),$=p.useMemo(()=>o?Ia(o,u.data,u.isLoading):null,[u.data,u.isLoading,o]),T=p.useRef(!1);return p.useEffect(()=>{T.current=!1},[a]),p.useEffect(()=>{let N=0;const v=(f=!1,_=!1)=>{const{section:A,resultsTaskSlug:U}=Aa(window.location.hash.slice(1));if(!A||!o||A==="tldr"&&!o.tldr||A==="results"&&(!x||m.isLoading)||!f&&T.current)return;let H=A==="results"&&U?document.getElementById(Xt(U)):document.getElementById(A);if(!H&&A==="results"&&U){if(j.some(({taskSlug:O})=>O===U))return;H=document.getElementById("results")}H&&(N=window.requestAnimationFrame(()=>{T.current=!0,H.scrollIntoView({block:"start",behavior:_?"smooth":"auto"})}))};v();const h=()=>{T.current=!1,v(!0,!0)};return window.addEventListener("hashchange",h),()=>{window.removeEventListener("hashchange",h),N&&window.cancelAnimationFrame(N)}},[j,m.isLoading,o,R,x]),{arxivId:a,evaluations:m.data,evaluationsByTask:j,evaluationsLoading:m.isLoading,hfLoading:u.isLoading,hfRepos:u.data,paper:o,paperError:i.error,paperLoading:i.isLoading,presentation:$,refetchEvaluations:m.refetch,refetchPaper:i.refetch,relatedQuery:E,versions:k.data??[],visibleEvaluations:y}}const Ua={tasks:"tasks",methods:"methods",evaluations:"results",repositories:"repositories",project_pages:"project-pages",hf_artifacts:"hf-artifacts",organizations:"organizations",source_url:"source-url"};function Ba(t){return Ua[t]??null}function Da(){const[t,s]=p.useState(null),a=p.useCallback(n=>{s(n)},[]),r=p.useCallback((n,l)=>{s(i=>l?n:i===n?null:i)},[]);return{activeEditor:t,openEditor:a,setEditorOpen:r}}function Ha(t){const s=t==null?void 0:t.trim();if(!s)return;const a=Number(s);return Number.isFinite(a)?Math.trunc(a):void 0}function At(t){const s=t.trim();if(!s)return null;const a=Number(s);return Number.isFinite(a)&&a>=0?Math.trunc(a):null}function et(t){return t.trim()||null}function Ma(t){const s=Number.parseInt(t.task_id,10),a=Number.parseInt(t.dataset_id,10);return Number.isFinite(s)&&Number.isFinite(a)?{taskId:s,datasetId:a}:null}function za(t,s){const a=[];for(const r of t){if(r.operation==="delete"&&r.id){a.push({kind:"delete",evaluationId:Number.parseInt(r.id,10)});continue}if(r.operation!=="create"&&r.operation!=="update")continue;const n=Ma(r),l=r.metric_name.trim();if(!n||!l||!r.metric_value.trim())continue;const i=s(r.task_id,r.dataset_id),o={task_id:n.taskId,dataset_id:n.datasetId,metrics:{[l]:r.metric_value},best_metric:l,is_open:r.is_open},c=r.model_name.trim(),g=Ha(r.best_rank);if(r.operation==="create"){const x=At(r.num_parameters),u=et(r.hf_model_url);a.push({kind:"create",data:{...o,...c?{model_name:c}:{},...i&&r.harness.trim()?{harness:r.harness.trim()}:{},...g!==void 0?{best_rank:g}:{},...x!==null?{num_parameters:x}:{},...u!==null?{hf_model_url:u}:{}}});continue}r.id&&a.push({kind:"update",evaluationId:Number.parseInt(r.id,10),data:{...o,...c?{model_name:c}:{},harness:i?et(r.harness):null,...g!==void 0?{best_rank:g}:{},num_parameters:At(r.num_parameters),hf_model_url:et(r.hf_model_url)}})}return a}function qa(t,s){return s.map(a=>a.kind==="delete"?{operation:"delete",evaluation_id:a.evaluationId}:{operation:a.kind,...a.kind==="update"?{evaluation_id:a.evaluationId}:{},payload:a.kind==="create"?{paper_id:t,...a.data}:a.data})}function Ka(t){return t.map(s=>s.kind==="delete"?{op:"delete",evaluation_id:s.evaluationId}:s.kind==="update"?{op:"update",evaluation_id:s.evaluationId,data:s.data}:{op:"create",data:s.data})}function fe({isAuthor:t=!1}){const s=typeof window<"u"&&window.location.hostname==="staging.paperswithcode.co";return e.jsxs("div",{className:"rounded-md border border-amber-200 bg-amber-50 px-3 py-2 text-xs text-amber-900 dark:border-amber-900 dark:bg-amber-950/40 dark:text-amber-100",children:[e.jsx("p",{className:"font-medium",children:s?"Test-only: this change stays on staging.":"Your changes will be reviewed by an admin."}),e.jsx("p",{className:"mt-1 leading-snug",children:s?"This exercises staging-local pending behavior and is not queued for production review.":t?"We can see this paper is yours. While we're in early access an admin still reviews each edit; this will become automatic for authors soon.":"Submissions are queued for review and don't change the paper page until an admin approves them."})]})}const tt=100;function Oa(t){return(t??[]).some(s=>s.slug==="coding-agents"||s.name.trim().toLowerCase()==="coding agents")}function Qa(t){return t.map(s=>{const a=s.best_metric||Object.keys(s.metrics)[0],r=s.metrics[a];return{id:s.id,task_id:s.task_id,dataset_id:s.dataset_id,model_name:s.model_name||"",harness:s.harness||"",metric_name:a||"",metric_value:String(r||""),best_rank:s.best_rank?String(s.best_rank):"",num_parameters:s.num_parameters!=null?String(s.num_parameters):"",hf_model_url:s.hf_model_url||"",is_open:s.is_open!==!1,operation:"unchanged"}})}function Ga(t){const s=new Map;return t.forEach(a=>{a.task_id&&a.task_name&&s.set(a.task_id,{id:a.task_id,name:a.task_name,slug:a.task_slug,level:0})}),s}function Va(t){const s=new Map;return t.forEach(a=>{a.dataset_id&&a.dataset_name&&s.set(a.dataset_id,{id:a.dataset_id,name:a.dataset_name,slug:a.dataset_slug})}),s}function Rt(t,s){return`${t}:${s}`}function Ja({open:t,onOpenChange:s,paperId:a,arxivId:r,initialEvaluations:n,paperTasks:l,onSuccess:i,submitMode:o="direct",isAdmin:c=!1,isAuthor:g=!1}){const x=Oa(l),[u,m]=p.useState([]),[k,E]=p.useState(null),[y,j]=p.useState(new Map),[R,$]=p.useState(new Map),T=de(),{toast:N}=te(),v=p.useRef(!1),h=p.useRef(!1);p.useEffect(()=>{if(!t){v.current=!1,h.current=!1;return}v.current||h.current||n.length!==0&&(v.current=!0,m(Qa(n)),j(Ga(n)),$(Va(n)))},[t,n]);const f=p.useMemo(()=>Array.from(new Set(u.map(b=>b.task_id).filter(b=>b&&b!==""))),[u]),_=p.useMemo(()=>{const b=new Set;return u.forEach(P=>{P.task_id&&P.dataset_id&&b.add(Rt(P.task_id,P.dataset_id))}),Array.from(b)},[u]),A=Z({queryKey:["datasets-by-tasks-for-eval-edit",f,t],queryFn:async()=>{const b={};return await Promise.all(f.map(async P=>{try{const F=await ge.listDatasets({task_id:parseInt(P),page_size:tt});b[P]=F.results}catch(F){console.error(`Error fetching datasets for task ${P}:`,F),b[P]=[]}})),b},enabled:t&&f.length>0});p.useEffect(()=>{A.data&&$(b=>{const P=new Map(b);return Object.values(A.data).forEach(F=>{F.forEach(B=>{P.set(B.id,B)})}),P})},[A.data]);const U=Z({queryKey:["leaderboard-metrics-for-eval-edit",_,t],queryFn:async()=>{const b={};return await Promise.all(_.map(async P=>{const[F,B]=P.split(":");try{b[P]=await ge.leaderboardMetrics(B,F)}catch(M){console.error(`Error fetching metrics for leaderboard ${P}:`,M),b[P]=[]}})),b},enabled:t&&_.length>0}),H=async b=>{const P=await ge.listTasks({page_size:tt,...b?{q:b}:{}});return j(F=>{const B=new Map(F);return P.results.forEach(M=>B.set(M.id,M)),B}),P.results.map(F=>{var B;return{value:F.id,label:F.name,description:(B=F.description)==null?void 0:B.slice(0,100)}})},O=b=>async P=>{const F=await ge.listDatasets({task_id:parseInt(b),page_size:tt,...P?{q:P}:{}});return $(B=>{const M=new Map(B);return F.results.forEach(Q=>M.set(Q.id,Q)),M}),F.results.map(B=>({value:B.id,label:B.name,description:B.full_name}))},J=(b,P)=>{if(!b||!P)return!1;const F=R.get(P);return!!(F!=null&&F.supports_harness)},d=(b,P,F)=>{var Q;if(!b||!P)return[];const M=(((Q=U.data)==null?void 0:Q[Rt(b,P)])||[]).map(z=>({value:z.metric_name,label:z.metric_name,description:z.metric_direction==="higher_is_better"?"Higher is better":"Lower is better"}));return F&&!M.some(z=>z.value===F)&&M.unshift({value:F,label:`${F} (legacy)`}),M},C=ue({mutationFn:async({paperId:b,evaluations:P})=>{const F=za(P,J);if(!c&&o==="direct"&&F.length>50)throw new Error("Contributor evaluation batches are limited to 50 operations; contact an admin.");if(F.length===0)return{submitted:!1};const B=Number.parseInt(b,10);return o==="pending"?await pe.submit({paper_id:B,edit_type:"evaluations",proposed_payload:{operations:Ka(F)}}):await Te.batch(B,qa(B,F)),{submitted:!0}},onSuccess:b=>{if(o==="pending"){b!=null&&b.submitted?N({title:"Edit submitted for review",description:"Thanks! An admin will review your proposed evaluation changes shortly."}):N({title:"No changes to submit",description:"Your evaluation list matches the existing data."}),i==null||i(),s(!1);return}T.invalidateQueries({queryKey:["paper-arxiv",r]}),T.invalidateQueries({queryKey:["evaluations","paper",a]}),i==null||i(),s(!1)},onError:b=>{var B;const P=b;let F=P.message||(o==="pending"?"Failed to submit your edit. Please try again.":"Failed to update evaluations.");if(P.response)try{const M=JSON.parse(P.response);typeof(M==null?void 0:M.detail)=="string"?F=M.detail:Array.isArray(M==null?void 0:M.detail)&&((B=M.detail[0])!=null&&B.msg)&&(F=M.detail[0].msg)}catch{F=P.response}N({title:o==="pending"?"Could not submit edit":"Could not save evaluations",description:F,variant:"destructive"})}}),I=()=>{h.current=!0,m([...u,{task_id:"",dataset_id:"",model_name:"",harness:"",metric_name:"",metric_value:"",best_rank:"",num_parameters:"",hf_model_url:"",is_open:!0,operation:"create"}])},L=b=>{if(h.current=!0,u[b].id){if(!window.confirm("Delete this evaluation? You will be asked to sign in again if your session is older than 15 minutes."))return;m(u.map((F,B)=>B===b?{...F,operation:"delete"}:F))}else m(u.filter((F,B)=>B!==b))},S=(b,P,F)=>{h.current=!0,m(u.map((B,M)=>{if(M!==b)return B;const Q={...B,[P]:F};return P==="task_id"&&(Q.dataset_id="",Q.metric_name="",Q.harness=""),P==="dataset_id"&&(Q.metric_name="",F&&!J(Q.task_id,F)&&(Q.harness="")),B.operation==="unchanged"&&(Q.operation="update"),Q}))},K=(b,P)=>{h.current=!0,m(u.map((F,B)=>{if(B!==b)return F;const M={...F,is_open:P};return F.operation==="unchanged"&&(M.operation="update"),M}))},X=()=>{const b=u.filter(P=>P.operation!=="delete"||P.id);C.mutate({paperId:a,evaluations:b})};return e.jsxs(se,{open:t,onOpenChange:s,children:[e.jsxs(ae,{className:"max-w-6xl max-h-[800px]",children:[e.jsxs(re,{children:[e.jsx(ne,{children:"Edit Evaluation Results"}),e.jsx(ie,{children:"Add, edit, or remove evaluation results for this paper. Each row represents a benchmark result."})]}),o==="pending"&&e.jsx(fe,{isAuthor:g}),e.jsxs("div",{className:"py-4 overflow-y-auto max-h-[600px]",children:[u.filter(b=>b.operation!=="delete").length>0?e.jsx("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-2 px-2 font-medium text-sm min-w-[180px]",children:"Task"}),e.jsx("th",{className:"text-left py-2 px-2 font-medium text-sm min-w-[180px]",children:"Dataset"}),e.jsx("th",{className:`text-left py-2 px-2 font-medium text-sm ${x?"min-w-[140px]":"min-w-[240px]"}`,children:"Model"}),x&&e.jsx("th",{className:"text-left py-2 px-2 font-medium text-sm min-w-[140px]",children:"Harness"}),e.jsx("th",{className:"text-left py-2 px-2 font-medium text-sm min-w-[140px]",children:"Metric"}),e.jsx("th",{className:"text-left py-2 px-2 font-medium text-sm",children:"Value"}),e.jsx("th",{className:"text-left py-2 px-2 font-medium text-sm",children:"Parameters"}),e.jsx("th",{className:"text-left py-2 px-2 font-medium text-sm min-w-[200px]",children:"HF model URL"}),e.jsx("th",{className:"text-left py-2 px-2 font-medium text-sm w-20",children:"Open source"}),e.jsx("th",{className:"text-left py-2 px-2 font-medium text-sm w-16",children:"Action"})]})}),e.jsx("tbody",{children:u.map((b,P)=>{if(b.operation==="delete")return null;const F=y.get(b.task_id),B=R.get(b.dataset_id),M=d(b.task_id,b.dataset_id,b.metric_name),Q=!!(b.task_id&&b.dataset_id)&&U.isFetching;return e.jsxs("tr",{className:"border-b border-border",children:[e.jsx("td",{className:"py-2 px-2",children:e.jsx(Et,{value:b.task_id,onChange:z=>S(P,"task_id",z),placeholder:"Select task",searchPlaceholder:"Search tasks...",emptyMessage:"No tasks found.",selectedOption:F?{value:F.id,label:F.name}:null,queryKey:["eval-edit-task-search"],queryFn:H,enabled:t})}),e.jsx("td",{className:"py-2 px-2",children:e.jsx(Et,{value:b.dataset_id,onChange:z=>S(P,"dataset_id",z),placeholder:b.task_id?"Select dataset":"Select task first",searchPlaceholder:"Search datasets...",emptyMessage:b.task_id?"No datasets found for this task.":"Select a task first.",disabled:!b.task_id,selectedOption:B?{value:B.id,label:B.name}:null,queryKey:["eval-edit-dataset-search",b.task_id],queryFn:O(b.task_id),enabled:t&&!!b.task_id})}),e.jsx("td",{className:"py-2 px-2",children:e.jsx(W,{type:"text",className:"w-full text-sm",placeholder:"Model name",value:b.model_name,onChange:z=>S(P,"model_name",z.target.value)})}),x&&e.jsx("td",{className:"py-2 px-2",children:J(b.task_id,b.dataset_id)?e.jsx(W,{type:"text",className:"w-full text-sm",placeholder:"Claude Code, Terminus, ...",value:b.harness,onChange:z=>S(P,"harness",z.target.value)}):e.jsx("span",{className:"text-xs text-muted-foreground",children:"Not supported"})}),e.jsx("td",{className:"py-2 px-2",children:!b.task_id||!b.dataset_id?e.jsx("span",{className:"text-xs text-muted-foreground",children:"Select task + dataset"}):Q?e.jsxs("span",{className:"inline-flex items-center text-xs text-muted-foreground",children:[e.jsx(ee,{className:"mr-1 h-3 w-3 animate-spin"}),"Loading metrics..."]}):M.length>0?e.jsxs("select",{className:"w-full rounded-md border border-border bg-background px-2 py-1 text-sm",value:b.metric_name,onChange:z=>S(P,"metric_name",z.target.value),children:[e.jsx("option",{value:"",children:"Select metric"}),M.map(z=>e.jsx("option",{value:z.value,children:z.label},z.value))]}):e.jsx("span",{className:"text-xs text-muted-foreground",children:"No configured metrics"})}),e.jsx("td",{className:"py-2 px-2",children:e.jsx(W,{type:"text",className:"w-full text-sm",placeholder:"44.9",value:b.metric_value,onChange:z=>S(P,"metric_value",z.target.value)})}),e.jsx("td",{className:"py-2 px-2",children:e.jsx(W,{type:"number",min:0,step:1,className:"w-full text-sm",placeholder:"e.g. 7000000000",value:b.num_parameters,onChange:z=>S(P,"num_parameters",z.target.value),title:"Raw model parameter count (e.g. 7000000000 for a 7B model). Leave blank if unknown."})}),e.jsx("td",{className:"py-2 px-2",children:e.jsx(W,{type:"url",className:"w-full text-sm",placeholder:"https://huggingface.co/org/model",value:b.hf_model_url,onChange:z=>S(P,"hf_model_url",z.target.value),title:"Hugging Face model page for this row (must start with https://huggingface.co/). Leave blank if none."})}),e.jsx("td",{className:"py-2 px-2 text-center",children:e.jsx("input",{type:"checkbox",className:"h-4 w-4 align-middle",checked:b.is_open,onChange:z=>K(P,z.target.checked),title:"Whether the evaluated model is open-source. Uncheck for closed-source models."})}),e.jsx("td",{className:"py-2 px-2",children:e.jsx(D,{variant:"ghost",size:"sm",onClick:()=>L(P),className:"h-8 w-8 p-0 text-destructive hover:text-destructive",title:"Delete row",children:e.jsx(Be,{className:"w-4 h-4"})})})]},P)})})]})}):e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(ia,{className:"w-12 h-12 mx-auto mb-3 opacity-30"}),e.jsx("p",{children:"No evaluation results yet"}),e.jsx("p",{className:"text-sm mt-2",children:'Click "Add Row" below to add a new evaluation'})]}),e.jsx("div",{className:"mt-4",children:e.jsxs(D,{variant:"outline",size:"sm",onClick:I,className:"flex items-center space-x-2",children:[e.jsx(Ue,{className:"w-4 h-4"}),e.jsx("span",{children:"Add Row"})]})})]}),e.jsxs(oe,{children:[e.jsxs("div",{className:"flex flex-wrap gap-2 sm:mr-auto",children:[e.jsx(D,{variant:"ghost",onClick:()=>E("benchmark"),children:"Suggest a new benchmark"}),e.jsx(D,{variant:"ghost",onClick:()=>E("metric"),children:"Suggest a new metric"})]}),e.jsx(D,{variant:"outline",onClick:()=>s(!1),children:"Cancel"}),e.jsx(D,{onClick:X,disabled:C.isPending,children:C.isPending?e.jsxs(e.Fragment,{children:[e.jsx(ee,{className:"w-4 h-4 mr-2 animate-spin"}),o==="pending"?"Submitting...":"Saving..."]}):e.jsxs(e.Fragment,{children:[e.jsx(he,{className:"w-4 h-4 mr-2"}),o==="pending"?"Submit for review":"Save Changes"]})})]})]}),e.jsx(ft,{open:k!==null,onOpenChange:b=>{b||E(null)},paperId:a,kind:k??"benchmark"})]})}function Xa(t,s,a){if(!t)return t;const r=n=>n.paper_id!==s||n.paper_title===a?n:{...n,paper_title:a};if(Array.isArray(t)){const n=t.map(r);return n.some((i,o)=>i!==t[o])?n:t}if(Array.isArray(t.results)){const n=t.results.map(r);return n.some((i,o)=>i!==t.results[o])?{...t,results:n}:t}return t}function je(t,s,a){new Set([...a,s.id,s.arxiv_id].filter(i=>!!i)).forEach(i=>{t.setQueryData(["paper",i],s),t.setQueryData(["paper-arxiv",i],s)}),t.invalidateQueries({queryKey:["papers"],refetchType:"none"}),t.invalidateQueries({queryKey:["papers-infinite"],refetchType:"none"}),t.invalidateQueries({queryKey:["task-papers-infinite"],refetchType:"none"});const n=String(s.id),l=i=>Xa(i,n,s.title);t.setQueriesData({queryKey:["evaluations"]},l),t.setQueriesData({queryKey:["dataset-evals"]},l),t.invalidateQueries({queryKey:["evaluations"],refetchType:"none"}),t.invalidateQueries({queryKey:["dataset-evals"],refetchType:"none"})}const st=[{key:"hf_models",label:"Models",placeholder:"https://huggingface.co/org/model"},{key:"hf_datasets",label:"Datasets",placeholder:"https://huggingface.co/datasets/org/data"},{key:"hf_spaces",label:"Spaces",placeholder:"https://huggingface.co/spaces/org/demo"}];function Ft(t){return t.map(s=>s.trim()).filter(Boolean)}function at(t,s){const a=Ft(t).sort(),r=Ft(s).sort();return a.length!==r.length?!1:a.every((n,l)=>n===r[l])}function Wa(t,s){return at(t.hf_models,s.hf_models)&&at(t.hf_datasets,s.hf_datasets)&&at(t.hf_spaces,s.hf_spaces)}function Ya({open:t,onOpenChange:s,paperId:a,arxivId:r,initialArtifacts:n,onSuccess:l,submitMode:i="direct",isAuthor:o=!1}){const[c,g]=p.useState(n),[x,u]=p.useState({hf_models:"",hf_datasets:"",hf_spaces:""}),m=de(),{toast:k}=te(),E=p.useRef(!1);p.useEffect(()=>{if(!t){E.current=!1;return}E.current||(E.current=!0,g(n),u({hf_models:"",hf_datasets:"",hf_spaces:""}))},[t,n]);const y=ue({mutationFn:async({paperId:v,artifacts:h})=>i==="pending"?(await pe.submit({paper_id:parseInt(v),edit_type:"hf_artifacts",proposed_payload:h}),null):V.updateHfArtifacts(v,h),onSuccess:v=>{if(i==="pending"){k({title:"Edit submitted for review",description:"Thanks! An admin will review your proposed Hugging Face artifact changes shortly."}),l==null||l(),s(!1),u({hf_models:"",hf_datasets:"",hf_spaces:""});return}v&&je(m,v,[a,r]),l==null||l(),s(!1),u({hf_models:"",hf_datasets:"",hf_spaces:""})},onError:v=>{var _;const h=v;let f=h.message||(i==="pending"?"Failed to submit your edit. Please try again.":"Failed to update Hugging Face artifacts.");if(h.response)try{const A=JSON.parse(h.response);typeof(A==null?void 0:A.detail)=="string"?f=A.detail:Array.isArray(A==null?void 0:A.detail)&&((_=A.detail[0])!=null&&_.msg)&&(f=A.detail[0].msg)}catch{f=h.response}k({title:i==="pending"?"Could not submit edit":"Could not save Hugging Face artifacts",description:f,variant:"destructive"})}}),j=()=>{const v={hf_models:[...c.hf_models],hf_datasets:[...c.hf_datasets],hf_spaces:[...c.hf_spaces]};for(const{key:h}of st){const f=x[h].trim();if(f){if(v[h].some(_=>_.trim()===f))return alert(`This ${h.replace("hf_","")} URL is already added`),null;v[h]=[...v[h],f]}}return v},R=v=>{const h=x[v].trim();if(h){if(c[v].some(f=>f.trim()===h)){alert(`This ${v.replace("hf_","")} URL is already added`);return}g(f=>({...f,[v]:[...f[v],h]})),u(f=>({...f,[v]:""}))}},$=(v,h)=>{g(f=>({...f,[v]:f[v].filter(_=>_!==h)}))},T=()=>{const v=j();if(v===null)return;const h=Object.keys(n).some(f=>n[f].some(_=>!v[f].includes(_)));i==="direct"&&h&&!window.confirm("Remove one or more Hugging Face artifact links?")||y.mutate({paperId:a,artifacts:v})},N=p.useMemo(()=>{const v={hf_models:[...c.hf_models],hf_datasets:[...c.hf_datasets],hf_spaces:[...c.hf_spaces]};for(const{key:h}of st){const f=x[h].trim();if(f){if(v[h].some(_=>_.trim()===f))return!1;v[h]=[...v[h],f]}}return!Wa(v,n)},[c,x,n]);return e.jsx(se,{open:t,onOpenChange:s,children:e.jsxs(ae,{className:"max-w-2xl max-h-[700px]",children:[e.jsxs(re,{children:[e.jsx(ne,{children:"Edit Hugging Face Artifacts"}),e.jsx(ie,{children:"Add or remove linked Hugging Face models, datasets, and Spaces for this paper."})]}),i==="pending"&&e.jsx(fe,{isAuthor:o}),e.jsx("div",{className:"space-y-6 py-2 overflow-y-auto max-h-[460px]",children:st.map(({key:v,label:h,placeholder:f})=>e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm font-medium",children:h}),e.jsxs("div",{className:"flex space-x-2",children:[e.jsx(W,{type:"url",placeholder:f,value:x[v],onChange:_=>u(A=>({...A,[v]:_.target.value})),onKeyPress:_=>{_.key==="Enter"&&(_.preventDefault(),R(v))},className:"flex-1"}),e.jsxs(D,{onClick:()=>R(v),size:"sm",disabled:!x[v].trim(),children:[e.jsx(Ue,{className:"w-4 h-4 mr-1"}),"Add"]})]}),c[v].length>0?e.jsx("div",{className:"space-y-2",children:c[v].map(_=>e.jsxs("div",{className:"flex items-center space-x-2 p-3 bg-muted/30 rounded-lg hover:bg-muted/50 transition-colors",children:[e.jsx("span",{className:"text-sm font-medium text-paper-blue truncate flex-1",children:_}),e.jsx(D,{variant:"ghost",size:"sm",onClick:()=>$(v,_),className:"h-8 px-2 text-destructive hover:text-destructive",title:`Remove ${h.toLowerCase()} URL`,children:e.jsx(Be,{className:"w-4 h-4"})})]},_))}):e.jsxs("div",{className:"text-xs text-muted-foreground",children:["No ",h.toLowerCase()," linked yet."]})]},v))}),e.jsxs(oe,{children:[e.jsx(D,{variant:"outline",onClick:()=>s(!1),children:"Cancel"}),e.jsx(D,{onClick:T,disabled:y.isPending||!N,children:y.isPending?e.jsxs(e.Fragment,{children:[e.jsx(ee,{className:"w-4 h-4 mr-2 animate-spin"}),i==="pending"?"Submitting...":"Saving..."]}):e.jsxs(e.Fragment,{children:[e.jsx(he,{className:"w-4 h-4 mr-2"}),i==="pending"?"Submit for review":"Save Changes"]})})]})]})})}var De="Checkbox",[Za]=ht(De),[er,gt]=Za(De);function tr(t){const{__scopeCheckbox:s,checked:a,children:r,defaultChecked:n,disabled:l,form:i,name:o,onCheckedChange:c,required:g,value:x="on",internal_do_not_use_render:u}=t,[m,k]=zt({prop:a,defaultProp:n??!1,onChange:c,caller:De}),[E,y]=p.useState(null),[j,R]=p.useState(null),$=p.useRef(!1),T=E?!!i||!!E.closest("form"):!0,N={checked:m,disabled:l,setChecked:k,control:E,setControl:y,name:o,form:i,value:x,hasConsumerStoppedPropagationRef:$,required:g,defaultChecked:me(n)?!1:n,isFormControl:T,bubbleInput:j,setBubbleInput:R};return e.jsx(er,{scope:s,...N,children:sr(u)?u(N):r})}var Wt="CheckboxTrigger",Yt=p.forwardRef(({__scopeCheckbox:t,onKeyDown:s,onClick:a,...r},n)=>{const{control:l,value:i,disabled:o,checked:c,required:g,setControl:x,setChecked:u,hasConsumerStoppedPropagationRef:m,isFormControl:k,bubbleInput:E}=gt(Wt,t),y=Se(n,x),j=p.useRef(c);return p.useEffect(()=>{const R=l==null?void 0:l.form;if(R){const $=()=>u(j.current);return R.addEventListener("reset",$),()=>R.removeEventListener("reset",$)}},[l,u]),e.jsx(xe.button,{type:"button",role:"checkbox","aria-checked":me(c)?"mixed":c,"aria-required":g,"data-state":as(c),"data-disabled":o?"":void 0,disabled:o,value:i,...r,ref:y,onKeyDown:Ce(s,R=>{R.key==="Enter"&&R.preventDefault()}),onClick:Ce(a,R=>{u($=>me($)?!0:!$),E&&k&&(m.current=R.isPropagationStopped(),m.current||R.stopPropagation())})})});Yt.displayName=Wt;var xt=p.forwardRef((t,s)=>{const{__scopeCheckbox:a,name:r,checked:n,defaultChecked:l,required:i,disabled:o,value:c,onCheckedChange:g,form:x,...u}=t;return e.jsx(tr,{__scopeCheckbox:a,checked:n,defaultChecked:l,disabled:o,required:i,onCheckedChange:g,name:r,form:x,value:c,internal_do_not_use_render:({isFormControl:m})=>e.jsxs(e.Fragment,{children:[e.jsx(Yt,{...u,ref:s,__scopeCheckbox:a}),m&&e.jsx(ss,{__scopeCheckbox:a})]})})});xt.displayName=De;var Zt="CheckboxIndicator",es=p.forwardRef((t,s)=>{const{__scopeCheckbox:a,forceMount:r,...n}=t,l=gt(Zt,a);return e.jsx(Mt,{present:r||me(l.checked)||l.checked===!0,children:e.jsx(xe.span,{"data-state":as(l.checked),"data-disabled":l.disabled?"":void 0,...n,ref:s,style:{pointerEvents:"none",...t.style}})})});es.displayName=Zt;var ts="CheckboxBubbleInput",ss=p.forwardRef(({__scopeCheckbox:t,...s},a)=>{const{control:r,hasConsumerStoppedPropagationRef:n,checked:l,defaultChecked:i,required:o,disabled:c,name:g,value:x,form:u,bubbleInput:m,setBubbleInput:k}=gt(ts,t),E=Se(a,k),y=Gt(l),j=qt(r);p.useEffect(()=>{const $=m;if(!$)return;const T=window.HTMLInputElement.prototype,v=Object.getOwnPropertyDescriptor(T,"checked").set,h=!n.current;if(y!==l&&v){const f=new Event("click",{bubbles:h});$.indeterminate=me(l),v.call($,me(l)?!1:l),$.dispatchEvent(f)}},[m,y,l,n]);const R=p.useRef(me(l)?!1:l);return e.jsx(xe.input,{type:"checkbox","aria-hidden":!0,defaultChecked:i??R.current,required:o,disabled:c,name:g,value:x,form:u,...s,tabIndex:-1,ref:E,style:{...s.style,...j,position:"absolute",pointerEvents:"none",opacity:0,margin:0,transform:"translateX(-100%)"}})});ss.displayName=ts;function sr(t){return typeof t=="function"}function me(t){return t==="indeterminate"}function as(t){return me(t)?"indeterminate":t?"checked":"unchecked"}const He=p.forwardRef(({className:t,style:s,...a},r)=>e.jsx(xt,{ref:r,className:Re("peer h-4 w-4 shrink-0 rounded-sm ring-offset-background data-[state=checked]:!bg-black data-[state=checked]:!text-white focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",t),style:{border:"1px solid #000",...s},...a,children:e.jsx(es,{className:Re("flex items-center justify-center text-current"),children:e.jsx(he,{className:"h-4 w-4"})})}));He.displayName=xt.displayName;const ar=250,rr=100;function nr({open:t,onOpenChange:s,paperId:a,arxivId:r,initialMethodIds:n,initialMethods:l,onSuccess:i,submitMode:o="direct",isAuthor:c=!1}){const[g,x]=p.useState(n),[u,m]=p.useState(!1),[k,E]=p.useState(""),[y,j]=p.useState(""),[R,$]=p.useState(new Map),T=de(),{toast:N}=te(),v=p.useRef(!1);p.useEffect(()=>{if(!t){v.current=!1;return}if(v.current)return;v.current=!0,x(n),E(""),j("");const d=new Map;(l||[]).forEach(C=>{const I=parseInt(C.id);Number.isNaN(I)||d.set(I,C)}),$(d)},[t,n,l]),p.useEffect(()=>{const d=window.setTimeout(()=>{j(k.trim())},ar);return()=>window.clearTimeout(d)},[k]);const{data:h,isFetching:f}=Z({queryKey:["methods-search",y],queryFn:()=>ge.listMethods({page_size:rr,...y?{q:y}:{}}),enabled:t});p.useEffect(()=>{var d;(d=h==null?void 0:h.results)!=null&&d.length&&$(C=>{const I=new Map(C);return h.results.forEach(L=>{const S=parseInt(L.id);Number.isNaN(S)||I.set(S,L)}),I})},[h]);const _=p.useMemo(()=>{const d=(h==null?void 0:h.results)||[],C=new Set,I=[];return g.forEach(L=>{if(C.has(L))return;const S=R.get(L);S&&(I.push(S),C.add(L))}),d.forEach(L=>{const S=parseInt(L.id);Number.isNaN(S)||C.has(S)||(I.push(L),C.add(S))}),I},[h,g,R]),A=ue({mutationFn:async({paperId:d,methodIds:C})=>o==="pending"?(await pe.submit({paper_id:parseInt(d),edit_type:"methods",proposed_payload:{method_ids:C}}),null):V.updateMethods(d,C),onSuccess:d=>{if(o==="pending"){N({title:"Edit submitted for review",description:"Thanks! An admin will review your proposed method changes shortly."}),i==null||i(),s(!1);return}d&&je(T,d,[a,r]),N({title:"Methods updated",description:`Saved ${g.length} method${g.length===1?"":"s"} for this paper.`}),i==null||i(),s(!1)},onError:d=>{var L;const C=d;let I=C.message||(o==="pending"?"Failed to submit your edit. Please try again.":"Failed to update paper methods.");if(C.response)try{const S=JSON.parse(C.response);typeof(S==null?void 0:S.detail)=="string"?I=S.detail:Array.isArray(S==null?void 0:S.detail)&&((L=S.detail[0])!=null&&L.msg)&&(I=S.detail[0].msg)}catch{I=C.response}N({title:o==="pending"?"Could not submit edit":"Could not save methods",description:I,variant:"destructive"})}}),U=()=>{o==="direct"&&n.some(d=>!g.includes(d))&&!window.confirm("Remove one or more method links from this paper?")||A.mutate({paperId:a,methodIds:g})},H=p.useMemo(()=>{if(g.length!==n.length)return!0;const d=new Set(n);return g.some(C=>!d.has(C))},[g,n]),O=(d,C)=>{x(I=>C?I.includes(d)?I:[...I,d]:I.filter(L=>L!==d))},J=()=>E("");return e.jsxs(se,{open:t,onOpenChange:s,children:[e.jsxs(ae,{className:"max-w-2xl max-h-[600px]",children:[e.jsxs(re,{children:[e.jsx(ne,{children:"Edit Paper Methods"}),e.jsx(ie,{children:"Select the methods and techniques used in this paper. You can select multiple methods."})]}),o==="pending"&&e.jsx(fe,{isAuthor:c}),e.jsxs("div",{className:"relative mb-4",children:[e.jsx(Ee,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground"}),e.jsx(W,{type:"text",placeholder:"Search methods...",value:k,onChange:d=>E(d.target.value),className:"pl-9 pr-9"}),k&&e.jsx("button",{type:"button",onClick:J,className:"absolute right-2 top-1/2 -translate-y-1/2 p-1 text-muted-foreground hover:text-foreground","aria-label":"Clear search",children:e.jsx(pt,{className:"w-4 h-4"})})]}),e.jsx("div",{className:"py-4 overflow-y-auto max-h-[400px]",children:_.length>0?e.jsx("div",{className:"space-y-2",children:_.map(d=>{const C=parseInt(d.id),I=g.includes(C);return e.jsxs("div",{className:"flex items-center space-x-2 p-2 hover:bg-muted/50 rounded-md",children:[e.jsx(He,{id:`method-${d.id}`,checked:I,onCheckedChange:L=>O(C,L===!0),className:"!border !border-black data-[state=checked]:!bg-black data-[state=checked]:!text-white"}),e.jsxs("label",{htmlFor:`method-${d.id}`,className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70 cursor-pointer flex-1",children:[d.name,d.full_name&&d.full_name!==d.name&&e.jsx("span",{className:"block text-xs text-muted-foreground font-normal",children:d.full_name}),d.description&&e.jsxs("span",{className:"block text-xs text-muted-foreground font-normal mt-1",children:[d.description.substring(0,100),d.description.length>100?"...":""]})]})]},d.id)})}):f?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(ee,{className:"w-8 h-8 mx-auto mb-2 animate-spin"}),e.jsx("p",{children:"Loading methods..."})]}):e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(Ee,{className:"w-8 h-8 mx-auto mb-2 opacity-50"}),e.jsx("p",{children:y?`No methods found matching "${y}"`:"No methods available"})]})}),e.jsxs(oe,{children:[e.jsx(D,{variant:"ghost",className:"sm:mr-auto",onClick:()=>m(!0),children:"Suggest a new method"}),e.jsx(D,{variant:"outline",onClick:()=>s(!1),children:"Cancel"}),e.jsx(D,{onClick:U,disabled:A.isPending||!H,children:A.isPending?e.jsxs(e.Fragment,{children:[e.jsx(ee,{className:"w-4 h-4 mr-2 animate-spin"}),o==="pending"?"Submitting...":"Saving..."]}):e.jsxs(e.Fragment,{children:[e.jsx(he,{className:"w-4 h-4 mr-2"}),o==="pending"?"Submit for review":"Save Changes"]})})]})]}),e.jsx(ft,{open:u,onOpenChange:m,paperId:a,kind:"method"})]})}const ir=({open:t,onOpenChange:s,paperId:a,initialOrganizationIds:r,submitMode:n,isAuthor:l})=>{var E;const[i,o]=p.useState(r),[c,g]=p.useState(""),x=de();p.useEffect(()=>{t&&(o(r),g(""))},[r,t]);const u=Z({queryKey:["organizations","curation"],queryFn:()=>ge.organizations(!1),enabled:t}),m=p.useMemo(()=>{var j,R;const y=c.trim().toLocaleLowerCase();return y?(((R=u.data)==null?void 0:R.results)??[]).filter($=>$.name.toLocaleLowerCase().includes(y)):((j=u.data)==null?void 0:j.results)??[]},[(E=u.data)==null?void 0:E.results,c]),k=ue({mutationFn:async()=>{r.some(j=>!i.includes(j))&&!window.confirm("Remove one or more organizations from this paper? Destructive edits may require a fresh sign-in.")||(n==="pending"?await pe.submit({paper_id:Number(a),edit_type:"organizations",proposed_payload:{organization_ids:i}}):await V.updateOrganizations(a,i))},onSuccess:()=>{x.invalidateQueries({queryKey:["paper-arxiv"]}),s(!1)}});return e.jsx(se,{open:t,onOpenChange:s,children:e.jsxs(ae,{children:[e.jsxs(re,{children:[e.jsx(ne,{children:"Edit organizations"}),e.jsx(ie,{children:"Associate existing organizations with this paper. Organization creation remains admin-only."})]}),n==="pending"&&e.jsx(fe,{isAuthor:l}),e.jsxs("div",{className:"relative",children:[e.jsx(Ee,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(W,{type:"search","aria-label":"Search organizations",placeholder:"Search organizations...",value:c,onChange:y=>g(y.target.value),className:"pl-9 pr-9"}),c&&e.jsx("button",{type:"button",onClick:()=>g(""),className:"absolute right-2 top-1/2 -translate-y-1/2 p-1 text-muted-foreground hover:text-foreground","aria-label":"Clear organization search",children:e.jsx(pt,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"max-h-80 space-y-2 overflow-auto",children:[m.map(y=>{const j=Number(y.id);return e.jsxs("label",{className:"flex items-center gap-2 rounded border p-2",children:[e.jsx("input",{type:"checkbox",checked:i.includes(j),onChange:R=>o($=>R.target.checked?[...$,j]:$.filter(T=>T!==j))}),y.name]},y.id)}),!u.isLoading&&m.length===0&&e.jsx("p",{className:"py-8 text-center text-sm text-muted-foreground",children:c.trim()?`No organizations found matching "${c.trim()}"`:"No organizations available"})]}),e.jsxs(oe,{children:[e.jsx(D,{variant:"outline",onClick:()=>s(!1),children:"Cancel"}),e.jsx(D,{onClick:()=>k.mutate(),disabled:k.isPending,children:n==="pending"?"Submit test edit":"Save changes"})]})]})})};function or({open:t,onOpenChange:s,paperId:a,arxivId:r,initialProjectPages:n,onSuccess:l,submitMode:i="direct",isAuthor:o=!1}){const[c,g]=p.useState(n),[x,u]=p.useState(""),m=de(),{toast:k}=te(),E=p.useRef(!1);p.useEffect(()=>{if(!t){E.current=!1;return}E.current||(E.current=!0,g(n),u(""))},[t,n]);const y=ue({mutationFn:async({paperId:h,projectPages:f})=>i==="pending"?(await pe.submit({paper_id:parseInt(h),edit_type:"project_pages",proposed_payload:{project_pages:f}}),null):V.updateProjectPages(h,f),onSuccess:h=>{if(i==="pending"){k({title:"Edit submitted for review",description:"Thanks! An admin will review your proposed project page changes shortly."}),l==null||l(),s(!1),u("");return}h&&je(m,h,[a,r]),l==null||l(),s(!1),u("")},onError:h=>{var A;const f=h;let _=f.message||(i==="pending"?"Failed to submit your edit. Please try again.":"Failed to update project pages.");if(f.response)try{const U=JSON.parse(f.response);typeof(U==null?void 0:U.detail)=="string"?_=U.detail:Array.isArray(U==null?void 0:U.detail)&&((A=U.detail[0])!=null&&A.msg)&&(_=U.detail[0].msg)}catch{_=f.response}k({title:i==="pending"?"Could not submit edit":"Could not save project pages",description:_,variant:"destructive"})}}),j=()=>{const h=x.trim();return h?c.some(f=>f.url===h)?(alert("This project page URL is already added"),null):[...c,{url:h,is_official:!1}]:c},R=()=>{const h=j();h!==null&&h.length!==c.length&&(g(h),u(""))},$=h=>{g(c.filter(f=>f.url!==h))},T=h=>{g(c.map(f=>f.url===h?{...f,is_official:!f.is_official}:f))},N=()=>{const h=j();h!==null&&(i==="direct"&&n.some(f=>!h.some(_=>_.url===f.url))&&!window.confirm("Remove one or more project pages from this paper?")||y.mutate({paperId:a,projectPages:h}))},v=p.useMemo(()=>{const h=x.trim(),f=h?[...c,{url:h,is_official:!1}]:c;if(f.length!==n.length)return!0;const _=new Map(n.map(A=>[A.url.trim(),!!A.is_official]));return f.some(A=>{const U=_.get(A.url.trim());return U===void 0||U!==!!A.is_official})},[c,x,n]);return e.jsx(se,{open:t,onOpenChange:s,children:e.jsxs(ae,{className:"max-w-2xl max-h-[600px]",children:[e.jsxs(re,{children:[e.jsx(ne,{children:"Edit Paper Project Pages"}),e.jsx(ie,{children:"Add or remove project page URLs (e.g. authors' demo or landing pages) associated with this paper. Mark pages as official if they are created by the paper authors."})]}),i==="pending"&&e.jsx(fe,{isAuthor:o}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm font-medium",children:"Add Project Page URL"}),e.jsxs("div",{className:"flex space-x-2",children:[e.jsx(W,{type:"url",placeholder:"https://example.com/project",value:x,onChange:h=>u(h.target.value),onKeyPress:h=>{h.key==="Enter"&&(h.preventDefault(),R())},className:"flex-1"}),e.jsxs(D,{onClick:R,size:"sm",disabled:!x.trim(),children:[e.jsx(Ue,{className:"w-4 h-4 mr-1"}),"Add"]})]})]}),e.jsx("div",{className:"py-4 overflow-y-auto max-h-[350px]",children:c.length>0?e.jsx("div",{className:"space-y-2",children:c.map((h,f)=>e.jsxs("div",{className:"flex items-center space-x-2 p-3 bg-muted/30 rounded-lg hover:bg-muted/50 transition-colors",children:[e.jsx($t,{className:"w-4 h-4 text-muted-foreground flex-shrink-0"}),e.jsx("div",{className:"flex-1 min-w-0",children:e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx("span",{className:"text-sm font-medium text-paper-blue truncate",children:h.url}),h.is_official&&e.jsx(Qt,{variant:"secondary",className:"text-xs",children:"Official"})]})}),e.jsxs("div",{className:"flex items-center space-x-1",children:[e.jsxs(D,{variant:h.is_official?"default":"outline",size:"sm",onClick:()=>T(h.url),className:"h-8 px-2 text-xs",title:h.is_official?"Click to unmark as official (created by paper authors)":"Click to mark as official (created by paper authors)",children:[e.jsx(Vt,{className:`w-3.5 h-3.5 mr-1 ${h.is_official?"fill-current":""}`}),h.is_official?"Official":"Mark official"]}),e.jsx(D,{variant:"ghost",size:"sm",onClick:()=>$(h.url),className:"h-8 px-2 text-destructive hover:text-destructive",title:"Remove project page",children:e.jsx(Be,{className:"w-4 h-4"})})]})]},f))}):e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx($t,{className:"w-8 h-8 mx-auto mb-2 opacity-50"}),e.jsx("p",{className:"text-sm",children:"No project pages added yet"}),e.jsx("p",{className:"text-xs mt-1",children:"Add a project page URL above to get started"})]})}),e.jsxs(oe,{children:[e.jsx(D,{variant:"outline",onClick:()=>s(!1),children:"Cancel"}),e.jsx(D,{onClick:N,disabled:y.isPending||!v,children:y.isPending?e.jsxs(e.Fragment,{children:[e.jsx(ee,{className:"w-4 h-4 mr-2 animate-spin"}),i==="pending"?"Submitting...":"Saving..."]}):e.jsxs(e.Fragment,{children:[e.jsx(he,{className:"w-4 h-4 mr-2"}),i==="pending"?"Submit for review":"Save Changes"]})})]})]})})}function lr({open:t,onOpenChange:s,paperId:a,arxivId:r,initialRepositories:n,onSuccess:l,submitMode:i="direct",isAuthor:o=!1}){const[c,g]=p.useState(n),[x,u]=p.useState(""),m=de(),{toast:k}=te(),E=p.useRef(!1);p.useEffect(()=>{if(!t){E.current=!1;return}E.current||(E.current=!0,g(n),u(""))},[t,n]);const y=ue({mutationFn:async({paperId:f,repositories:_})=>i==="pending"?(await pe.submit({paper_id:parseInt(f),edit_type:"repositories",proposed_payload:{repositories:_}}),null):V.updateRepositories(f,_),onSuccess:f=>{if(i==="pending"){k({title:"Edit submitted for review",description:"Thanks! An admin will review your proposed repository changes shortly."}),l==null||l(),s(!1),u("");return}f&&je(m,f,[a,r]),l==null||l(),s(!1),u("")},onError:f=>{var U;const _=f;let A=_.message||(i==="pending"?"Failed to submit your edit. Please try again.":"Failed to update paper repositories.");if(_.response)try{const H=JSON.parse(_.response);typeof(H==null?void 0:H.detail)=="string"?A=H.detail:Array.isArray(H==null?void 0:H.detail)&&((U=H.detail[0])!=null&&U.msg)&&(A=H.detail[0].msg)}catch{A=_.response}k({title:i==="pending"?"Could not submit edit":"Could not save repositories",description:A,variant:"destructive"})}}),j=f=>{const _=[];for(const A of f){const U=_.find(H=>St(H.url,A.url));if(U)U.is_official=U.is_official||A.is_official;else{const H=Ge(A.url);_.push({url:H??A.url.trim(),is_official:A.is_official})}}return _},R=()=>{const f=x.trim(),_=f?[...c,{url:f,is_official:!1}]:c;return f&&c.some(A=>St(A.url,f))?(alert("This repository URL is already added"),null):j(_)},$=()=>{const f=R();f!==null&&f.length!==c.length&&(g(f),u(""))},T=f=>{g(c.filter(_=>_.url!==f))},N=f=>{g(c.map(_=>_.url===f?{..._,is_official:!_.is_official}:_))},v=()=>{const f=R();f!==null&&(i==="direct"&&n.some(_=>!f.some(A=>A.url===_.url))&&!window.confirm("Remove one or more repositories from this paper?")||y.mutate({paperId:a,repositories:f}))},h=p.useMemo(()=>{const f=x.trim(),_=f?[...c,{url:f,is_official:!1}]:c;if(_.length!==n.length)return!0;const A=j(n),U=j(_);if(U.length!==A.length)return!0;const H=new Map(A.map(O=>[Ge(O.url)??O.url.trim(),!!O.is_official]));return U.some(O=>{const J=Ge(O.url)??O.url.trim(),d=H.get(J);return d===void 0||d!==!!O.is_official})},[c,x,n]);return e.jsx(se,{open:t,onOpenChange:s,children:e.jsxs(ae,{className:"max-w-2xl max-h-[600px]",children:[e.jsxs(re,{children:[e.jsx(ne,{children:"Edit Paper Repositories"}),e.jsx(ie,{children:"Add or remove GitHub repository URLs associated with this paper. Mark repositories as official if they are created by the paper authors."})]}),i==="pending"&&e.jsx(fe,{isAuthor:o}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm font-medium",children:"Add Repository URL"}),e.jsxs("div",{className:"flex space-x-2",children:[e.jsx(W,{type:"url",placeholder:"https://github.com/owner/repo",value:x,onChange:f=>u(f.target.value),onKeyPress:f=>{f.key==="Enter"&&(f.preventDefault(),$())},className:"flex-1"}),e.jsxs(D,{onClick:$,size:"sm",disabled:!x.trim(),children:[e.jsx(Ue,{className:"w-4 h-4 mr-1"}),"Add"]})]})]}),e.jsx("div",{className:"py-4 overflow-y-auto max-h-[350px]",children:c.length>0?e.jsx("div",{className:"space-y-2",children:c.map((f,_)=>e.jsxs("div",{className:"flex items-center space-x-2 p-3 bg-muted/30 rounded-lg hover:bg-muted/50 transition-colors",children:[e.jsx(Pt,{className:"w-4 h-4 text-muted-foreground flex-shrink-0"}),e.jsx("div",{className:"flex-1 min-w-0",children:e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx("span",{className:"text-sm font-medium text-paper-blue truncate",children:f.url}),f.is_official&&e.jsx(Qt,{variant:"secondary",className:"text-xs",children:"Official"})]})}),e.jsxs("div",{className:"flex items-center space-x-1",children:[e.jsxs(D,{variant:f.is_official?"default":"outline",size:"sm",onClick:()=>N(f.url),className:"h-8 px-2 text-xs",title:f.is_official?"Click to unmark as official (created by paper authors)":"Click to mark as official (created by paper authors)",children:[e.jsx(Vt,{className:`w-3.5 h-3.5 mr-1 ${f.is_official?"fill-current":""}`}),f.is_official?"Official":"Mark official"]}),e.jsx(D,{variant:"ghost",size:"sm",onClick:()=>T(f.url),className:"h-8 px-2 text-destructive hover:text-destructive",title:"Remove repository",children:e.jsx(Be,{className:"w-4 h-4"})})]})]},_))}):e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(Pt,{className:"w-8 h-8 mx-auto mb-2 opacity-50"}),e.jsx("p",{className:"text-sm",children:"No repositories added yet"}),e.jsx("p",{className:"text-xs mt-1",children:"Add a repository URL above to get started"})]})}),e.jsxs(oe,{children:[e.jsx(D,{variant:"outline",onClick:()=>s(!1),children:"Cancel"}),e.jsx(D,{onClick:v,disabled:y.isPending||!h,children:y.isPending?e.jsxs(e.Fragment,{children:[e.jsx(ee,{className:"w-4 h-4 mr-2 animate-spin"}),i==="pending"?"Submitting...":"Saving..."]}):e.jsxs(e.Fragment,{children:[e.jsx(he,{className:"w-4 h-4 mr-2"}),i==="pending"?"Submit for review":"Save Changes"]})})]})]})})}function cr({open:t,onOpenChange:s,paperId:a,arxivId:r,initialUrl:n,onSuccess:l,submitMode:i="direct",isAuthor:o=!1}){const[c,g]=p.useState(n),x=de(),{toast:u}=te(),m=p.useRef(!1);p.useEffect(()=>{if(!t){m.current=!1;return}m.current||(m.current=!0,g(n))},[t,n]);const k=ue({mutationFn:async({paperId:$,sourceUrl:T})=>i==="pending"?(await pe.submit({paper_id:parseInt($),edit_type:"source_url",proposed_payload:{source_url:T}}),null):V.updateSourceUrl($,T),onSuccess:$=>{if(i==="pending"){u({title:"Edit submitted for review",description:"Thanks! An admin will review your proposed source URL change shortly."}),l==null||l(),s(!1);return}$&&je(x,$,[a,r]),l==null||l(),s(!1)},onError:$=>{var v;const T=$;let N=T.message||(i==="pending"?"Failed to submit your edit. Please try again.":"Failed to update source URL.");if(T.response)try{const h=JSON.parse(T.response);typeof(h==null?void 0:h.detail)=="string"?N=h.detail:Array.isArray(h==null?void 0:h.detail)&&((v=h.detail[0])!=null&&v.msg)&&(N=h.detail[0].msg)}catch{N=T.response}u({title:i==="pending"?"Could not submit edit":"Could not save source URL",description:N,variant:"destructive"})}}),E=c.trim(),y=/^https?:\/\//i.test(E),j=E!==(n||"").trim(),R=()=>{y&&k.mutate({paperId:a,sourceUrl:E})};return e.jsx(se,{open:t,onOpenChange:s,children:e.jsxs(ae,{className:"max-w-2xl",children:[e.jsxs(re,{children:[e.jsx(ne,{children:"Edit Source URL"}),e.jsxs(ie,{children:["Update the canonical URL for this external paper. This is the page the ",'"Source page"'," button links to. ArXiv papers cannot edit this field."]})]}),i==="pending"&&e.jsx(fe,{isAuthor:o}),e.jsxs("div",{className:"space-y-2 py-2",children:[e.jsx("label",{className:"text-sm font-medium",children:"Source URL"}),e.jsx(W,{type:"url",placeholder:"https://example.com/paper",value:c,onChange:$=>g($.target.value),onKeyPress:$=>{$.key==="Enter"&&y&&j&&($.preventDefault(),R())}}),!y&&E.length>0&&e.jsx("p",{className:"text-xs text-destructive",children:"URL must start with http:// or https://"})]}),e.jsxs(oe,{children:[e.jsx(D,{variant:"outline",onClick:()=>s(!1),children:"Cancel"}),e.jsx(D,{onClick:R,disabled:k.isPending||!y||!j,children:k.isPending?e.jsxs(e.Fragment,{children:[e.jsx(ee,{className:"w-4 h-4 mr-2 animate-spin"}),i==="pending"?"Submitting...":"Saving..."]}):e.jsxs(e.Fragment,{children:[e.jsx(he,{className:"w-4 h-4 mr-2"}),i==="pending"?"Submit for review":"Save Changes"]})})]})]})})}const dr=250,ur=100;function mr({open:t,onOpenChange:s,paperId:a,arxivId:r,initialTaskIds:n,initialTasks:l,onSuccess:i,submitMode:o="direct",isAuthor:c=!1}){const[g,x]=p.useState(n),[u,m]=p.useState(!1),[k,E]=p.useState(""),[y,j]=p.useState(""),[R,$]=p.useState(new Map),T=de(),{toast:N}=te(),v=p.useRef(!1);p.useEffect(()=>{if(!t){v.current=!1;return}if(v.current)return;v.current=!0,x(n),E(""),j("");const d=new Map;(l||[]).forEach(C=>{const I=parseInt(C.id);Number.isNaN(I)||d.set(I,C)}),$(d)},[t,n,l]),p.useEffect(()=>{const d=window.setTimeout(()=>{j(k.trim())},dr);return()=>window.clearTimeout(d)},[k]);const{data:h,isFetching:f}=Z({queryKey:["tasks-search",y],queryFn:()=>ge.listTasks({page_size:ur,...y?{q:y}:{}}),enabled:t});p.useEffect(()=>{var d;(d=h==null?void 0:h.results)!=null&&d.length&&$(C=>{const I=new Map(C);return h.results.forEach(L=>{const S=parseInt(L.id);Number.isNaN(S)||I.set(S,L)}),I})},[h]);const _=p.useMemo(()=>{const d=(h==null?void 0:h.results)||[],C=new Set,I=[];return g.forEach(L=>{if(C.has(L))return;const S=R.get(L);S&&(I.push(S),C.add(L))}),d.forEach(L=>{const S=parseInt(L.id);Number.isNaN(S)||C.has(S)||(I.push(L),C.add(S))}),I},[h,g,R]),A=ue({mutationFn:async({paperId:d,taskIds:C})=>o==="pending"?(await pe.submit({paper_id:parseInt(d),edit_type:"tasks",proposed_payload:{task_ids:C}}),null):V.updateTasks(d,C),onMutate:async({taskIds:d})=>{if(o==="pending")return{snapshots:[]};const C=d.map(S=>R.get(S)).filter(S=>!!S).map(S=>({id:S.id,name:S.name,slug:S.slug})).sort((S,K)=>S.name.localeCompare(K.name)),I=Array.from(new Set([a,r].filter(S=>!!S)));await Promise.all(I.flatMap(S=>[T.cancelQueries({queryKey:["paper",S]}),T.cancelQueries({queryKey:["paper-arxiv",S]})]));const L=[];return I.forEach(S=>{["paper","paper-arxiv"].forEach(K=>{const X=[K,S],b=T.getQueryData(X);L.push({key:X,data:b}),b&&T.setQueryData(X,{...b,tasks:C})})}),N({title:"Tasks updated",description:`Saved ${d.length} task${d.length===1?"":"s"} for this paper.`}),i==null||i(),s(!1),{snapshots:L}},onSuccess:d=>{if(o==="pending"){N({title:"Edit submitted for review",description:"Thanks! An admin will review your proposed task changes shortly."}),i==null||i(),s(!1);return}d&&je(T,d,[a,r])},onError:(d,C,I)=>{var K,X;(K=I==null?void 0:I.snapshots)==null||K.forEach(({key:b,data:P})=>{T.setQueryData(b,P)});const L=d;let S=L.message||(o==="pending"?"Failed to submit your edit. Please try again.":"Failed to update paper tasks.");if(L.response)try{const b=JSON.parse(L.response);typeof(b==null?void 0:b.detail)=="string"?S=b.detail:Array.isArray(b==null?void 0:b.detail)&&((X=b.detail[0])!=null&&X.msg)&&(S=b.detail[0].msg)}catch{S=L.response}N({title:o==="pending"?"Could not submit edit":"Could not save tasks",description:S,variant:"destructive"})}}),U=()=>{o==="direct"&&n.some(d=>!g.includes(d))&&!window.confirm("Remove one or more task links from this paper?")||A.mutate({paperId:a,taskIds:g})},H=p.useMemo(()=>{if(g.length!==n.length)return!0;const d=new Set(n);return g.some(C=>!d.has(C))},[g,n]),O=(d,C)=>{x(I=>C?I.includes(d)?I:[...I,d]:I.filter(L=>L!==d))},J=()=>E("");return e.jsxs(se,{open:t,onOpenChange:s,children:[e.jsxs(ae,{className:"max-w-2xl max-h-[600px]",children:[e.jsxs(re,{children:[e.jsx(ne,{children:"Edit Paper Tasks"}),e.jsx(ie,{children:"Select the tasks that this paper addresses. You can select multiple tasks."})]}),o==="pending"&&e.jsx(fe,{isAuthor:c}),e.jsxs("div",{className:"relative mb-4",children:[e.jsx(Ee,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground"}),e.jsx(W,{type:"text",placeholder:"Search tasks...",value:k,onChange:d=>E(d.target.value),className:"pl-9 pr-9"}),k&&e.jsx("button",{type:"button",onClick:J,className:"absolute right-2 top-1/2 -translate-y-1/2 p-1 text-muted-foreground hover:text-foreground","aria-label":"Clear search",children:e.jsx(pt,{className:"w-4 h-4"})})]}),e.jsx("div",{className:"py-4 overflow-y-auto max-h-[400px]",children:_.length>0?e.jsx("div",{className:"space-y-2",children:_.map(d=>{const C=parseInt(d.id),I=g.includes(C);return e.jsxs("div",{className:"flex items-center space-x-2 p-2 hover:bg-muted/50 rounded-md",children:[e.jsx(He,{id:`task-${d.id}`,checked:I,onCheckedChange:L=>O(C,L===!0),className:"!border !border-black data-[state=checked]:!bg-black data-[state=checked]:!text-white"}),e.jsxs("label",{htmlFor:`task-${d.id}`,className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70 cursor-pointer flex-1",children:[d.name,d.description&&e.jsxs("span",{className:"block text-xs text-muted-foreground font-normal mt-1",children:[d.description.substring(0,100),d.description.length>100?"...":""]})]})]},d.id)})}):f?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(ee,{className:"w-8 h-8 mx-auto mb-2 animate-spin"}),e.jsx("p",{children:"Loading tasks..."})]}):e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(Ee,{className:"w-8 h-8 mx-auto mb-2 opacity-50"}),e.jsx("p",{children:y?`No tasks found matching "${y}"`:"No tasks available"})]})}),e.jsxs(oe,{children:[e.jsx(D,{variant:"ghost",className:"sm:mr-auto",onClick:()=>m(!0),children:"Suggest a new task"}),e.jsx(D,{variant:"outline",onClick:()=>s(!1),children:"Cancel"}),e.jsx(D,{onClick:U,disabled:A.isPending||!H,children:A.isPending?e.jsxs(e.Fragment,{children:[e.jsx(ee,{className:"w-4 h-4 mr-2 animate-spin"}),o==="pending"?"Submitting...":"Saving..."]}):e.jsxs(e.Fragment,{children:[e.jsx(he,{className:"w-4 h-4 mr-2"}),o==="pending"?"Submit for review":"Save Changes"]})})]})]}),e.jsx(ft,{open:u,onOpenChange:m,paperId:a,kind:"task"})]})}function hr({activeEditor:t,arxivId:s,editSubmitMode:a,evaluations:r,isAdmin:n,isLinkedAuthor:l,onOpenChange:i,paper:o}){if(!t)return null;const c={open:!0,paperId:o.id,arxivId:s,submitMode:a,isAuthor:l},g=u=>m=>i(u,m);return{tasks:()=>{var u;return e.jsx(mr,{...c,onOpenChange:g("tasks"),initialTaskIds:((u=o.tasks)==null?void 0:u.map(m=>Number(m.id)))??[],initialTasks:o.tasks??[]})},methods:()=>{var u;return e.jsx(nr,{...c,onOpenChange:g("methods"),initialMethodIds:((u=o.methods)==null?void 0:u.map(m=>Number(m.id)))??[],initialMethods:o.methods??[]})},repositories:()=>{var u;return e.jsx(lr,{...c,onOpenChange:g("repositories"),initialRepositories:((u=o.repositories)==null?void 0:u.map(({url:m,is_official:k})=>({url:m,is_official:!!k})))??[]})},"project-pages":()=>{var u;return e.jsx(or,{...c,onOpenChange:g("project-pages"),initialProjectPages:((u=o.project_pages)==null?void 0:u.map(({url:m,is_official:k})=>({url:m,is_official:!!k})))??[]})},results:()=>e.jsx(Ja,{...c,onOpenChange:g("results"),initialEvaluations:r,paperTasks:o.tasks??[],isAdmin:n}),"source-url":()=>e.jsx(cr,{...c,onOpenChange:g("source-url"),initialUrl:o.source_url??o.url_abs??""}),"hf-artifacts":()=>e.jsx(Ya,{...c,onOpenChange:g("hf-artifacts"),initialArtifacts:{hf_models:o.hf_models??[],hf_datasets:o.hf_datasets??[],hf_spaces:o.hf_spaces??[]}}),organizations:()=>e.jsx(ir,{open:!0,paperId:o.id,onOpenChange:g("organizations"),initialOrganizationIds:(o.organizations??[]).map(({id:u})=>Number(u)),submitMode:a,isAuthor:l})}[t]()}const pr={"add-evals":{trigger:"add evals",running:"adding evals…",complete:"add evals ✓",title:"Add evaluations with Codex",description:t=>e.jsxs(e.Fragment,{children:["Codex will run the repository’s add-evals skill for “",t,"”. It will import only paper-native results onto existing, metric-compatible leaderboards. Accepted rows are written directly to the live database."]}),notice:"Comparator rows, unknown benchmarks, and unconfigured metrics will be skipped. Jobs run one at a time in submission order.",progress:"Codex is researching the paper and validating results against the configured leaderboards.",action:"Run add-evals",start:ma,get:ua,cancel:da},"enrich-paper":{trigger:"enrich paper",running:"enriching…",complete:"enriched ✓",title:"Enrich paper with Codex",description:t=>e.jsxs(e.Fragment,{children:["Codex will run the repository’s enrich-paper skill for “",t,"”. It will validate official code and project links, merge high-confidence taxonomy tags, and check the paper thumbnail. Accepted changes are written directly to the live database."]}),notice:"Uncertain URLs and missing taxonomy concepts will be reported rather than guessed. Jobs run one at a time in submission order.",progress:"Codex is validating artifacts, taxonomy tags, and thumbnail quality for this paper.",action:"Run enrich-paper",start:ca,get:la,cancel:oa}};function fr({report:t}){return e.jsx("div",{className:"min-w-0 max-h-[50vh] overflow-y-auto overflow-x-hidden rounded-md border bg-muted/40 p-4 text-sm leading-relaxed",children:e.jsx(fa,{remarkPlugins:[ga],components:{a:({children:s,...a})=>e.jsx("a",{...a,className:"break-all underline underline-offset-2",target:"_blank",rel:"noreferrer",children:s}),p:({children:s})=>e.jsx("p",{className:"mb-3 break-words last:mb-0",children:s}),ul:({children:s})=>e.jsx("ul",{className:"mb-3 list-disc space-y-1 pl-5 last:mb-0",children:s}),ol:({children:s})=>e.jsx("ol",{className:"mb-3 list-decimal space-y-1 pl-5 last:mb-0",children:s}),h1:({children:s})=>e.jsx("h3",{className:"mb-2 font-semibold",children:s}),h2:({children:s})=>e.jsx("h3",{className:"mb-2 font-semibold",children:s}),h3:({children:s})=>e.jsx("h3",{className:"mb-2 font-semibold",children:s}),code:({children:s})=>e.jsx("code",{className:"break-all rounded bg-background/80 px-1 py-0.5 font-mono text-xs",children:s}),pre:({children:s})=>e.jsx("pre",{className:"mb-3 max-w-full overflow-x-auto whitespace-pre-wrap break-words rounded bg-background/80 p-3 font-mono text-xs last:mb-0",children:s})},children:t})})}function rs({kind:t,paperId:s,paperTitle:a,triggerClassName:r,onComplete:n}){const l=pr[t],[i,o]=p.useState(!1),[c,g]=p.useState(null),[x,u]=p.useState(!1),[m,k]=p.useState(null),E=p.useRef(null),y=(c==null?void 0:c.status)==="queued"||(c==null?void 0:c.status)==="dispatching"||(c==null?void 0:c.status)==="running",j=c==null?void 0:c.id;p.useEffect(()=>{if(!y||!j)return;let N=!1;const v=window.setInterval(async()=>{try{const h=await l.get(j);N||(g(h),k(null))}catch(h){N||k(h instanceof Error?h.message:"Could not check job status.")}},2e3);return()=>{N=!0,window.clearInterval(v)}},[y,l,j]),p.useEffect(()=>{(c==null?void 0:c.status)!=="completed"||E.current===c.id||(E.current=c.id,n())},[c,n]);const R=async()=>{u(!0),k(null);try{g(await l.start(s))}catch(N){k(N instanceof Error?N.message:"Could not start Codex.")}finally{u(!1)}},$=()=>{g(null),k(null),E.current=null},T=async()=>{if(c){k(null);try{g(await l.cancel(c.id))}catch(N){k(N instanceof Error?N.message:"Could not cancel Codex.")}}};return e.jsxs(se,{open:i,onOpenChange:o,children:[e.jsx("button",{type:"button",className:r,onClick:()=>o(!0),children:y?l.running:(c==null?void 0:c.status)==="completed"?l.complete:l.trigger}),e.jsxs(ae,{className:"max-h-[90vh] w-[calc(100vw-2rem)] min-w-0 max-w-2xl overflow-hidden",children:[e.jsxs(re,{className:"min-w-0",children:[e.jsx(ne,{children:l.title}),e.jsx(ie,{children:l.description(a)})]}),c?e.jsxs("div",{className:"min-w-0 space-y-3 overflow-hidden",children:[e.jsxs("div",{className:"font-mono text-xs uppercase tracking-wide text-muted-foreground",children:["Status: ",c.status]}),c.hf_job_url&&e.jsx("a",{className:"text-sm underline",href:c.hf_job_url,target:"_blank",rel:"noreferrer",children:"View Hugging Face Job"}),y&&e.jsxs("div",{className:"rounded-md border bg-muted/40 p-3 text-sm",children:[c.status==="queued"?"This job is queued and will start after the current Codex job finishes.":l.progress," ","This can take several minutes; you can close this window and return."]}),c.report&&e.jsx(fr,{report:c.report}),c.error&&e.jsx("div",{className:"rounded-md border border-destructive/40 bg-destructive/10 p-3 text-sm text-destructive",children:c.error})]}):e.jsx("div",{className:"rounded-md border bg-muted/40 p-3 text-sm text-muted-foreground",children:l.notice}),m&&e.jsx("div",{className:"rounded-md border border-destructive/40 bg-destructive/10 p-3 text-sm text-destructive",children:m}),e.jsxs(oe,{children:[e.jsx(D,{variant:"outline",onClick:()=>o(!1),children:y?"Close":"Cancel"}),y&&e.jsx(D,{variant:"outline",onClick:()=>void T(),children:"Cancel job"}),!c&&e.jsx(D,{onClick:R,disabled:x,children:x?"Starting…":l.action}),c&&!y&&e.jsx(D,{variant:"outline",onClick:$,children:"Run again"})]})]})]})}function gr(t){return e.jsx(rs,{...t,kind:"add-evals",triggerClassName:"edit-link"})}function we({accent:t,id:s,label:a}){return e.jsxs("div",{className:"section-rule paper-section-anchor",id:s,children:[e.jsx("span",{children:e.jsx("a",{href:`#${s}`,className:"section-anchor-link",children:a})}),t]})}function xr({canCopyBadge:t,canEdit:s,evaluationsByTask:a,evaluationsLoading:r,isAdmin:n,onCopyBadge:l,onEdit:i,onRefresh:o,paper:c,visibleEvaluationCount:g}){return e.jsxs(e.Fragment,{children:[e.jsx(we,{id:"results",label:"Results",accent:e.jsxs("span",{className:"accent",children:[g," benchmarks",t&&e.jsxs("button",{type:"button",className:"edit-link results-badge-copy",onClick:l,title:"Copy live leaderboard badges for your repository README",children:[e.jsx(G,{name:"copy",size:10})," Copy PwC badge"]}),n&&ha()&&e.jsx(gr,{paperId:Number(c.id),paperTitle:c.title,onComplete:o}),s&&e.jsx("button",{type:"button",onClick:i,className:"edit-link",children:"edit"})]})}),r?e.jsx(Ne,{className:"h-32 w-full"}):a.length>0?a.map(x=>e.jsxs("div",{className:x.taskSlug?"paper-section-anchor":void 0,id:x.taskSlug?Xt(x.taskSlug):void 0,children:[e.jsxs("div",{className:"section-rule",children:[e.jsx("span",{children:x.taskSlug?e.jsxs(e.Fragment,{children:[e.jsx(le,{to:`/tasks/${x.taskSlug}`,children:x.taskName}),e.jsx("a",{href:Ra(x.taskSlug),className:"section-anchor-link results-task-permalink","aria-label":`Permalink to ${x.taskName} results on this paper`,title:"Link to this task's results",children:"#"})]}):x.taskName}),e.jsxs("span",{className:"accent",children:[x.rows.length," ",x.rows.length===1?"result":"results"]})]}),e.jsxs("table",{className:"results-table",children:[e.jsxs("colgroup",{children:[e.jsx("col",{style:{width:"28%"}}),e.jsx("col",{style:{width:"28%"}}),e.jsx("col",{style:{width:"14%"}}),e.jsx("col",{style:{width:"12%"}}),e.jsx("col",{style:{width:"8%"}}),e.jsx("col",{style:{width:"10%"}})]}),e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Benchmark"}),e.jsx("th",{children:"Model"}),e.jsx("th",{children:"Metric"}),e.jsx("th",{children:"Value"}),e.jsx("th",{children:"Rank"}),e.jsx("th",{children:"Compare"})]})}),e.jsx("tbody",{children:x.rows.map(u=>{var m;return e.jsxs("tr",{children:[e.jsx("td",{className:"benchmark",children:u.dataset_slug?e.jsx(le,{to:`/benchmark/${u.dataset_slug}`,children:u.dataset_name||"—"}):u.dataset_name||"—"}),e.jsxs("td",{className:"model",title:u.model_name||void 0,children:[u.hf_model_url?e.jsx("a",{href:u.hf_model_url,target:"_blank",rel:"noopener noreferrer",className:"model-hf-link",title:`Open ${u.model_name||"model"} on Hugging Face`,children:u.model_name||"—"}):u.model_name||"—",u.is_open===!1&&e.jsx(Ws,{}),(u.external??u.is_external)&&e.jsx(Ys,{sourceUrl:u.source_url||u.external_source_url||u.result_url})]}),e.jsx("td",{className:"metric",children:u.best_metric}),e.jsx("td",{className:"value",children:Is((m=u.metrics)==null?void 0:m[u.best_metric||""])}),e.jsx("td",{className:"rank",children:u.best_rank!=null?`#${u.best_rank}`:"—"}),e.jsx("td",{className:"compare",children:u.dataset_slug&&e.jsx(le,{to:`/benchmark/${u.dataset_slug}?${[u.task_slug?`task=${encodeURIComponent(u.task_slug)}`:"",`eval=${encodeURIComponent(u.id)}`].filter(Boolean).join("&")}`,children:"Compare →"})})]},u.id)})})]})]},x.taskId)):e.jsx("p",{style:{fontFamily:"var(--mono)",fontSize:12,color:"var(--ink-faint)"},children:"No benchmark results recorded yet."})]})}var bt="Radio",[br,ns]=ht(bt),[jr,vr]=br(bt),is=p.forwardRef((t,s)=>{const{__scopeRadio:a,name:r,checked:n=!1,required:l,disabled:i,value:o="on",onCheck:c,form:g,...x}=t,[u,m]=p.useState(null),k=Se(s,j=>m(j)),E=p.useRef(!1),y=u?g||!!u.closest("form"):!0;return e.jsxs(jr,{scope:a,checked:n,disabled:i,children:[e.jsx(xe.button,{type:"button",role:"radio","aria-checked":n,"data-state":ds(n),"data-disabled":i?"":void 0,disabled:i,value:o,...x,ref:k,onClick:Ce(t.onClick,j=>{n||c==null||c(),y&&(E.current=j.isPropagationStopped(),E.current||j.stopPropagation())})}),y&&e.jsx(cs,{control:u,bubbles:!E.current,name:r,value:o,checked:n,required:l,disabled:i,form:g,style:{transform:"translateX(-100%)"}})]})});is.displayName=bt;var os="RadioIndicator",ls=p.forwardRef((t,s)=>{const{__scopeRadio:a,forceMount:r,...n}=t,l=vr(os,a);return e.jsx(Mt,{present:r||l.checked,children:e.jsx(xe.span,{"data-state":ds(l.checked),"data-disabled":l.disabled?"":void 0,...n,ref:s})})});ls.displayName=os;var yr="RadioBubbleInput",cs=p.forwardRef(({__scopeRadio:t,control:s,checked:a,bubbles:r=!0,...n},l)=>{const i=p.useRef(null),o=Se(i,l),c=Gt(a),g=qt(s);return p.useEffect(()=>{const x=i.current;if(!x)return;const u=window.HTMLInputElement.prototype,k=Object.getOwnPropertyDescriptor(u,"checked").set;if(c!==a&&k){const E=new Event("click",{bubbles:r});k.call(x,a),x.dispatchEvent(E)}},[c,a,r]),e.jsx(xe.input,{type:"radio","aria-hidden":!0,defaultChecked:a,...n,tabIndex:-1,ref:o,style:{...n.style,...g,position:"absolute",pointerEvents:"none",opacity:0,margin:0}})});cs.displayName=yr;function ds(t){return t?"checked":"unchecked"}var kr=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],Me="RadioGroup",[wr]=ht(Me,[Kt,ns]),us=Kt(),ms=ns(),[_r,Nr]=wr(Me),hs=p.forwardRef((t,s)=>{const{__scopeRadioGroup:a,name:r,defaultValue:n,value:l,required:i=!1,disabled:o=!1,orientation:c,dir:g,loop:x=!0,onValueChange:u,...m}=t,k=us(a),E=$s(g),[y,j]=zt({prop:l,defaultProp:n??null,onChange:u,caller:Me});return e.jsx(_r,{scope:a,name:r,required:i,disabled:o,value:y,onValueChange:j,children:e.jsx(As,{asChild:!0,...k,orientation:c,dir:E,loop:x,children:e.jsx(xe.div,{role:"radiogroup","aria-required":i,"aria-orientation":c,"data-disabled":o?"":void 0,dir:E,...m,ref:s})})})});hs.displayName=Me;var ps="RadioGroupItem",fs=p.forwardRef((t,s)=>{const{__scopeRadioGroup:a,disabled:r,...n}=t,l=Nr(ps,a),i=l.disabled||r,o=us(a),c=ms(a),g=p.useRef(null),x=Se(s,g),u=l.value===n.value,m=p.useRef(!1);return p.useEffect(()=>{const k=y=>{kr.includes(y.key)&&(m.current=!0)},E=()=>m.current=!1;return document.addEventListener("keydown",k),document.addEventListener("keyup",E),()=>{document.removeEventListener("keydown",k),document.removeEventListener("keyup",E)}},[]),e.jsx(Rs,{asChild:!0,...o,focusable:!i,active:u,children:e.jsx(is,{disabled:i,required:l.required,checked:u,...c,...n,name:l.name,ref:x,onCheck:()=>l.onValueChange(n.value),onKeyDown:Ce(k=>{k.key==="Enter"&&k.preventDefault()}),onFocus:Ce(n.onFocus,()=>{var k;m.current&&((k=g.current)==null||k.click())})})})});fs.displayName=ps;var Cr="RadioGroupIndicator",gs=p.forwardRef((t,s)=>{const{__scopeRadioGroup:a,...r}=t,n=ms(a);return e.jsx(ls,{...n,...r,ref:s})});gs.displayName=Cr;var xs=hs,bs=fs,Er=gs;const lt=p.forwardRef(({className:t,...s},a)=>e.jsx(xs,{className:Re("grid gap-2",t),...s,ref:a}));lt.displayName=xs.displayName;const _e=p.forwardRef(({className:t,...s},a)=>e.jsx(bs,{ref:a,className:Re("aspect-square h-4 w-4 rounded-full border border-primary text-primary ring-offset-background focus:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",t),...s,children:e.jsx(Er,{className:"flex items-center justify-center",children:e.jsx(Fs,{className:"h-2.5 w-2.5 fill-current text-current"})})}));_e.displayName=bs.displayName;const Sr={pdf:"PDF",model:"Model",dataset:"Dataset",space:"Space",github:"GitHub"},ct=/^[A-Za-z0-9][A-Za-z0-9._-]*$/,Pr=/^[A-Za-z0-9][\w.-]*\/[A-Za-z0-9][\w.-]*$/,Ir=20,dt="copy_to_bucket";function $r(t){const s=t.trim();if(!Pr.test(s))return null;const[a,r]=s.split("/");return`https://huggingface.co/buckets/${encodeURIComponent(a)}/${encodeURIComponent(r)}`}function ut(t){return`pwc:bucket-copy:${t}`}function Ar(t){if(typeof window>"u"||new URL(window.location.href).searchParams.get(dt)!==t)return null;try{const a=window.sessionStorage.getItem(ut(t));if(!a)return null;const r=JSON.parse(a);return r.paperId!==t||typeof r.bucketId!="string"||!["new","existing"].includes(r.destinationMode)||!["public","private"].includes(r.visibility)||!Array.isArray(r.selectedIds)||r.selectedIds.some(n=>typeof n!="string")?null:r}catch{return null}}function Rr(t,s=Ir){if(s<1)throw new Error("Bucket copy batch size must be positive");const a=[];for(let r=0;r!ct.test(c)))return null;const i=l.join("/"),o=s==="model"?"":`${s}s/`;return{id:`${s}:${i}`,kind:s,label:i,url:`https://huggingface.co/${o}${i}`,source:`hf://${o}${i}/`,destination:`${s}s/${i}/`,repoId:i}}catch{return null}}function Fr(t){try{const s=new URL(t);if(s.hostname!=="github.com"&&s.hostname!=="www.github.com")return null;const a=s.pathname.split("/").filter(Boolean);if(a.length<2)return null;const r=a[0],n=a[1].replace(/\.git$/,"");if(!ct.test(r)||!ct.test(n))return null;const l=`${r}/${n}`;return{id:`github:${l}`,kind:"github",label:l,url:`https://github.com/${l}`,source:`https://github.com/${l}.git`,destination:`github/${l}/`}}catch{return null}}function Lr({githubUrls:t,hfModelUrls:s,hfDatasetUrls:a,hfSpaceUrls:r,paperId:n,pdfName:l,pdfUrl:i}){const o=[i?{id:"pdf",kind:"pdf",label:"Paper PDF",url:i,source:i,destination:`paper/${l||n}.pdf`}:null,...s.map(g=>rt(g,"model")),...a.map(g=>rt(g,"dataset")),...r.map(g=>rt(g,"space")),...t.map(Fr)],c=new Set;return o.filter(g=>!g||c.has(g.id)?!1:(c.add(g.id),!0))}function Tr(t,s,a){const r=["# Requires the Hugging Face CLI: https://huggingface.co/docs/huggingface_hub/guides/cli",`HF_BUCKET=${Ie(t.trim())}`];a.create&&r.push(`hf buckets create "$HF_BUCKET" --exist-ok${a.isPrivate?" --private":""}`);for(const i of s.filter(o=>o.kind!=="github"&&o.kind!=="pdf"))r.push(`hf cp ${Ie(i.source)} "hf://buckets/$HF_BUCKET/${i.destination}"`);const n=s.find(i=>i.kind==="pdf");n&&r.push('PWC_PDF="$(mktemp)"',`trap 'rm -f "$PWC_PDF"' EXIT`,`curl --fail --location ${Ie(n.source)} --output "$PWC_PDF"`,`hf cp "$PWC_PDF" "hf://buckets/$HF_BUCKET/${n.destination}"`);const l=s.filter(i=>i.kind==="github");if(l.length){r.push('PWC_COPY_DIR="$(mktemp -d)"',`trap 'rm -rf "$PWC_COPY_DIR"' EXIT`);for(const i of l){const o=`$PWC_COPY_DIR/${i.destination.replace(/\/$/,"")}`;r.push(`git clone --depth 1 -- ${Ie(i.source)} "${o}"`,`hf sync "${o}" "hf://buckets/$HF_BUCKET/${i.destination}" --exclude '.git/**'`)}}return r.join(` +`)}function Ur(t){return`${(t.split(/[:|–—]/,1)[0]||t).normalize("NFKD").replace(/[\u0300-\u036f]/g,"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48).replace(/-+$/g,"")||"paper"}-artifacts`}function Br(t){const{toast:s}=te(),a=p.useMemo(()=>Lr({githubUrls:t.githubUrls,hfDatasetUrls:t.hfDatasetUrls,hfModelUrls:t.hfModelUrls,hfSpaceUrls:t.hfSpaceUrls,paperId:t.paperId,pdfName:t.pdfName,pdfUrl:t.pdfUrl}),[t.githubUrls,t.hfDatasetUrls,t.hfModelUrls,t.hfSpaceUrls,t.paperId,t.pdfName,t.pdfUrl]),r=p.useMemo(()=>Ar(t.paperId),[t.paperId]),[n,l]=p.useState(!!r),[i,o]=p.useState((r==null?void 0:r.destinationMode)??"new"),[c,g]=p.useState((r==null?void 0:r.bucketId)??""),[x,u]=p.useState((r==null?void 0:r.visibility)??"public"),[m,k]=p.useState(()=>new Set((r==null?void 0:r.selectedIds)??a.map(d=>d.id))),[E,y]=p.useState(!1),[j,R]=p.useState(null),[$,T]=p.useState(!!r),N=a.filter(d=>m.has(d.id)),v=N.length===a.length,h=$r(c),f=h!==null,_=Tr(c,N,{create:i==="new",isPrivate:x==="private"}),A=(d,C)=>{k(I=>{const L=new Set(I);return C?L.add(d):L.delete(d),L})},U=async()=>{try{await navigator.clipboard.writeText(_),s({title:"Bucket copy commands copied",description:"Run them in a terminal where the Hugging Face CLI is signed in."})}catch{s({title:"Copy failed",description:"Could not access the clipboard. Select and copy the commands manually.",variant:"destructive"})}},H=p.useCallback(()=>{const d=Ls("/api/v1/auth/hf/login"),C=new URL(window.location.href);C.searchParams.set(dt,t.paperId),window.sessionStorage.setItem(ut(t.paperId),JSON.stringify({paperId:t.paperId,bucketId:c.trim(),destinationMode:i,visibility:x,selectedIds:Array.from(m)}));const I=new URLSearchParams({return_to:C.toString(),authorize_bucket:"true"});i==="new"&&I.set("bucket_create","true"),window.location.assign(`${d}?${I.toString()}`)},[c,i,t.paperId,m,x]),O=p.useCallback(async()=>{if(!t.isSignedIn){H();return}y(!0);let d=0,C=0;try{const I=N.filter(K=>K.kind!=="pdf"&&K.kind!=="github"&&!!K.repoId).map(K=>({kind:K.kind,repo_id:K.repoId})),L=Rr(I);L.length||L.push([]);for(const[K,X]of L.entries()){R({current:K+1,total:L.length});const b=await V.copyToBucket(t.paperId,{bucket_id:c.trim(),create:K===0&&i==="new",private:x==="private",include_pdf:K===0&&N.some(P=>P.kind==="pdf"),artifacts:X});d+=b.copied.length,C+=b.errors.length}const S=N.filter(K=>K.kind==="github").length;s({title:C?"Bucket copy partially completed":"Copied to bucket",description:[`${d} item${d===1?"":"s"} copied.`,C?`${C} item${C===1?"":"s"} failed.`:"",S?"Use the generated commands below to copy GitHub repositories.":""].filter(Boolean).join(" "),variant:C?"destructive":void 0,action:h?e.jsx(Ts,{altText:"Open destination bucket",asChild:!0,children:e.jsx("a",{href:h,target:"_blank",rel:"noopener noreferrer",children:"Open bucket"})}):void 0}),!C&&!S&&l(!1)}catch(I){if(I instanceof it&&I.code==="bucket_authorization_required"){H();return}s({title:d?"Bucket copy partially completed":"Bucket copy failed",description:d?`${d} item${d===1?"":"s"} copied before the request failed. You can retry or use the CLI commands below.`:I instanceof it&&typeof I.detail=="string"?I.detail:"Hugging Face could not complete the copy. You can still use the CLI commands below.",variant:"destructive"})}finally{y(!1),R(null)}},[H,c,h,i,t.isSignedIn,t.paperId,N,s,x]);p.useEffect(()=>{if(!$||!t.isSignedIn)return;T(!1),window.sessionStorage.removeItem(ut(t.paperId));const d=new URL(window.location.href);d.searchParams.delete(dt),window.history.replaceState({},"",`${d.pathname}${d.search}${d.hash}`),O()},[O,t.isSignedIn,t.paperId,$]);const J=()=>{k(new Set(a.map(d=>d.id))),!c&&t.suggestedBucketId&&g(t.suggestedBucketId),l(!0)};return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"sidebar-card copy-to-bucket-card",children:[e.jsxs("button",{type:"button",className:"copy-to-bucket-trigger",onClick:J,children:[e.jsx("span",{className:"copy-to-bucket-arrow","aria-hidden":"true",children:"→"}),e.jsx("span",{className:"copy-to-bucket-title",children:"Copy to bucket"}),e.jsx("span",{className:"copy-to-bucket-new",children:"New"})]}),e.jsx("div",{className:"copy-to-bucket-meta",children:a.length?`${a.length} linked artifact${a.length===1?"":"s"}`:"No linked artifacts yet"})]}),e.jsx(se,{open:n,onOpenChange:l,children:e.jsxs(ae,{className:"max-h-[90vh] max-w-2xl grid-rows-[auto_minmax(0,1fr)_auto] overflow-hidden",children:[e.jsxs(re,{children:[e.jsxs(ne,{className:"flex items-center gap-2",children:[e.jsx("span",{className:"copy-to-bucket-dialog-arrow","aria-hidden":"true",children:"→"}),"Copy to bucket"]}),e.jsx(ie,{children:"Keep your own copy of this paper's PDF, linked code, and Hugging Face artifacts. Hub repositories use Xet's server-side copy; GitHub repositories use the generated CLI fallback."})]}),e.jsx("div",{className:"-mx-6 min-h-0 overflow-y-auto px-6",children:a.length?e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(Y,{children:"Choose your destination"}),e.jsxs(lt,{value:i,onValueChange:d=>o(d),className:"grid grid-cols-2 gap-2",children:[e.jsxs(Y,{className:"bucket-choice",children:[e.jsx(_e,{value:"new"}),"New bucket"]}),e.jsxs(Y,{className:"bucket-choice",children:[e.jsx(_e,{value:"existing"}),"Existing bucket"]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Y,{htmlFor:"bucket-id",children:"Bucket name"}),e.jsx(W,{id:"bucket-id",value:c,onChange:d=>g(d.target.value),placeholder:t.suggestedBucketId||"username/paper-artifacts","aria-invalid":c.length>0&&!f}),e.jsxs("div",{className:"flex items-center justify-between gap-3 text-xs",children:[e.jsx("p",{className:"text-muted-foreground",children:"Use the full Hugging Face bucket ID: namespace/name."}),h&&e.jsxs("a",{href:h,target:"_blank",rel:"noopener noreferrer",className:"inline-flex shrink-0 items-center gap-1 underline underline-offset-4",children:["View bucket",e.jsx(G,{name:"external",size:10})]})]})]}),i==="new"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(Y,{children:"Bucket visibility"}),e.jsxs(lt,{value:x,onValueChange:d=>u(d),className:"flex gap-5",children:[e.jsxs(Y,{className:"flex items-center gap-2 font-normal",children:[e.jsx(_e,{value:"public"}),"Public"]}),e.jsxs(Y,{className:"flex items-center gap-2 font-normal",children:[e.jsx(_e,{value:"private"}),"Private"]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx(Y,{children:"Artifacts"}),e.jsx(D,{type:"button",variant:"outline",size:"sm",className:"h-7 px-2 text-xs",onClick:()=>k(v?new Set:new Set(a.map(d=>d.id))),children:v?"Deselect all":"Select all"})]}),e.jsx("div",{className:"bucket-artifact-list",children:a.map(d=>e.jsxs("div",{className:"bucket-artifact-row",children:[e.jsx(He,{id:`bucket-artifact-${d.id}`,checked:m.has(d.id),onCheckedChange:C=>A(d.id,C===!0)}),e.jsxs(Y,{htmlFor:`bucket-artifact-${d.id}`,className:"min-w-0 flex-1 cursor-pointer font-normal",children:[e.jsx("span",{className:"bucket-artifact-kind",children:Sr[d.kind]}),e.jsx("span",{className:"bucket-artifact-name",children:d.label})]}),e.jsxs("a",{href:ce(d.url)??void 0,target:"_blank",rel:"noopener noreferrer",className:"bucket-artifact-open",children:["Open",e.jsx(G,{name:"external",size:10})]})]},d.id))}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"The PDF and Hugging Face artifacts can be copied directly. GitHub repositories require the CLI workflow below."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Y,{htmlFor:"bucket-copy-commands",children:"CLI fallback"}),e.jsx("pre",{id:"bucket-copy-commands",className:"bucket-copy-commands h-[190px]",children:f?_:"Enter a bucket name above to prepare the copy commands."})]})]}):e.jsx("p",{className:"py-5 text-sm text-muted-foreground",children:"This paper does not have a linked GitHub repository or Hugging Face artifact to copy yet."})}),e.jsxs(oe,{children:[e.jsx("a",{href:"https://huggingface.co/docs/huggingface_hub/en/guides/buckets",target:"_blank",rel:"noopener noreferrer",className:"mr-auto text-sm text-muted-foreground underline underline-offset-4",children:"About Hugging Face Buckets"}),e.jsxs(D,{type:"button",onClick:U,variant:"outline",disabled:!f||N.length===0,children:[e.jsx(G,{name:"copy",size:12}),"Copy commands"]}),e.jsx(D,{type:"button",onClick:O,disabled:E||t.isSignedIn&&(!f||!N.some(d=>d.kind!=="github")),children:E?j&&j.total>1?`Copying ${j.current}/${j.total}…`:"Copying…":t.isSignedIn?"Copy now":"Sign in & copy"})]})]})})]})}function Dr({isLoading:t,papers:s}){return t?e.jsxs("div",{className:"sidebar-card","aria-busy":"true",children:[e.jsx("div",{className:"sidebar-card-title",children:"Related papers"}),e.jsx("div",{className:"related-meta",children:"Finding related work…"})]}):s!=null&&s.length?e.jsxs("div",{className:"sidebar-card",children:[e.jsx("div",{className:"sidebar-card-title",children:"Related papers"}),s.map(a=>e.jsxs(le,{to:`/paper/${a.arxiv_id||a.id}`,target:"_blank",rel:"noopener noreferrer",className:"related-paper",style:{textDecoration:"none",color:"inherit"},children:[e.jsx("div",{className:"related-title",children:e.jsx(Ae,{title:a.title})}),e.jsxs("div",{className:"related-meta",children:[e.jsx("span",{children:a.arxiv_id?`arXiv:${a.arxiv_id}`:"External resource"}),a.citation_count!=null&&e.jsxs("span",{children:[a.citation_count.toLocaleString()," cites"]})]})]},a.id))]}):null}const nt=3,Lt=3;function Hr(t){return t>=1e3?`${(t/1e3).toFixed(1)}k`:String(t)}function Mr({allHfArtifactUrls:t,citationCopied:s,citationDisplay:a,hfArtifactViewer:r,onCopyCitation:n,onEditHfArtifacts:l,onEditRepositories:i,paper:o,relatedIsLoading:c,relatedPapers:g,user:x}){var y;const[u,m]=p.useState(!1),k=[...o.repositories??[]].sort((j,R)=>Number(R.is_official)-Number(j.is_official)||(R.num_stars||0)-(j.num_stars||0)),E=(u?k:k.slice(0,nt)).map(j=>({...j,safeHref:ce(j.url)}));return e.jsxs("aside",{className:"detail-sidebar",children:[e.jsxs("div",{className:"sidebar-card",children:[e.jsxs("div",{className:"sidebar-card-title",children:[e.jsx("span",{children:"GitHub"}),e.jsxs("span",{className:"badge",children:[k.length," repo",k.length===1?"":"s",e.jsx("button",{type:"button",onClick:i,className:"edit-link",children:"edit"})]})]}),E.filter(({safeHref:j})=>j).map(j=>e.jsxs("a",{href:j.safeHref??void 0,target:"_blank",rel:"noopener noreferrer",className:"code-line",style:{textDecoration:"none"},children:[e.jsxs("span",{className:"code-line-repo",children:[e.jsx(G,{name:"github",size:12}),e.jsxs("span",{className:"code-line-repo-name",children:[j.owner,"/",j.name]}),j.is_official&&e.jsx("span",{className:"code-line-official",children:"· Official"})]}),e.jsxs("span",{className:"code-line-stars",children:["★ ",Hr(j.num_stars)]})]},j.id)),k.length===0&&e.jsx("div",{style:{fontFamily:"var(--mono)",fontSize:11,color:"var(--ink-faint)",padding:"6px 0"},children:"No GitHub repositories linked yet."}),k.length>nt&&e.jsx("button",{type:"button",className:"bench-show-more",onClick:()=>m(j=>!j),children:u?"− show top 3":`+ show ${k.length-nt} more repos`})]}),e.jsx(zr,{viewer:r,onEdit:l}),e.jsx(Br,{githubUrls:k.map(({url:j})=>j),hfModelUrls:t.models,hfDatasetUrls:t.datasets,hfSpaceUrls:t.spaces,paperId:o.id,pdfName:((y=o.arxiv_id)==null?void 0:y.replace("/","-"))||o.id,pdfUrl:o.url_pdf,isSignedIn:!!x,suggestedBucketId:x?`${x.username}/${Ur(o.title)}`:void 0}),e.jsx(Dr,{isLoading:c,papers:g}),e.jsxs("div",{className:"sidebar-card",children:[e.jsxs("div",{className:"sidebar-card-title",children:[e.jsx("span",{children:"Citation"}),e.jsxs("button",{type:"button",className:"citation-copy-btn",onClick:n,"aria-label":"Copy citation to clipboard",title:"Copy citation to clipboard",children:[e.jsx(G,{name:"copy",size:11}),s?"Copied":"Copy"]})]}),e.jsx("pre",{style:{fontFamily:"var(--mono)",fontSize:10.5,lineHeight:1.5,color:"var(--ink-soft)",whiteSpace:"pre-wrap",wordBreak:"break-word",margin:0},children:a})]})]})}function zr({onEdit:t,viewer:s}){return e.jsxs("div",{className:"sidebar-card",children:[e.jsxs("div",{className:"sidebar-card-title",children:[s.paperHref?e.jsx("a",{href:s.paperHref,target:"_blank",rel:"noopener noreferrer",style:{color:"inherit",textDecoration:"none"},children:"🤗 Hugging Face"}):e.jsx("span",{children:"🤗 Hugging Face"}),e.jsx("button",{type:"button",onClick:t,className:"edit-link",children:"edit"})]}),s.isLoading?e.jsx(Ne,{className:"h-16 w-full"}):e.jsxs(e.Fragment,{children:[s.rows.map(a=>e.jsx(qr,{...a},a.label)),s.footer&&e.jsx("div",{style:{fontFamily:"var(--mono)",fontSize:10,color:"var(--ink-faint)",marginTop:12},children:s.footer})]})]})}function qr({count:t,href:s,isLimited:a,label:r,links:n}){const[l,i]=p.useState(!1),o=((n==null?void 0:n.length)??0)>Lt,c=l?n:n==null?void 0:n.slice(0,Lt),g=t!=null?`${t}${a?"+":""}`:"—";return e.jsxs("div",{className:"hf-artifact-row",children:[e.jsxs("div",{className:"hf-artifact-row-header",children:[e.jsx("span",{children:r}),t?e.jsx("a",{href:s,target:"_blank",rel:"noopener noreferrer",className:"hf-artifact-count",children:g}):e.jsx("span",{className:"hf-artifact-count hf-artifact-count--empty",children:g})]}),c!=null&&c.length?e.jsxs("div",{className:"hf-artifact-links",children:[c.map(x=>e.jsx("a",{href:x.href,target:"_blank",rel:"noopener noreferrer",children:x.label},x.href)),o&&e.jsx("button",{type:"button",className:"hf-artifact-toggle","aria-expanded":l,onClick:()=>i(x=>!x),children:l?"Show fewer":`View all ${n.length}`})]}):null]})}const Tt=360;function Kr({canEdit:t,onEditMethods:s,onEditTasks:a,paper:r}){var g,x;const[n,l]=p.useState(!1),i=r.abstract||"",o=i.length>Tt,c=n||!o?i:`${i.slice(0,Tt)}…`;return e.jsxs(e.Fragment,{children:[r.tldr&&e.jsxs(e.Fragment,{children:[e.jsx(we,{id:"tldr",label:"TL;DR · AI-generated"}),e.jsx("div",{className:"tldr-box",children:r.tldr})]}),e.jsx(we,{id:"abstract",label:"Abstract"}),e.jsx("p",{className:"abstract-text",style:{marginBottom:8},children:e.jsx(Xs,{text:c})}),o&&e.jsx("button",{type:"button",className:"read-full",onClick:()=>l(u=>!u),children:n?"− collapse abstract":"+ read full abstract"}),e.jsx(we,{id:"tasks",label:"Tasks",accent:e.jsxs("span",{className:"accent",children:[((g=r.tasks)==null?void 0:g.length)||0," tagged",t&&e.jsx("button",{type:"button",onClick:a,className:"edit-link",children:"edit"})]})}),e.jsx("div",{className:"paper-tags",style:{marginBottom:8},children:(r.tasks??[]).map(u=>e.jsx(Qs,{slug:u.slug||"",label:u.name},u.id))}),e.jsx(we,{id:"methods",label:"Methods",accent:e.jsxs("span",{className:"accent",children:[((x=r.methods)==null?void 0:x.length)||0," used",t&&e.jsx("button",{type:"button",onClick:s,className:"edit-link",children:"edit"})]})}),e.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:6,marginBottom:8},children:(r.methods??[]).map(u=>e.jsx(Gs,{method:u},u.id))})]})}const be=["my-bookmark-ids"],mt="pwc:pending-bookmark";function Or(t){window.sessionStorage.setItem(mt,JSON.stringify(t)),window.location.assign(xa(!0))}function Qr(){var r,n;const{user:t}=Le(),s=Z({queryKey:be,queryFn:()=>ot.getBookmarkIds(),enabled:!!t,staleTime:60*1e3,refetchOnWindowFocus:!1}),a=Fe.useMemo(()=>{var l;return new Set(((l=s.data)==null?void 0:l.paper_ids)??[])},[(r=s.data)==null?void 0:r.paper_ids]);return{ids:((n=s.data)==null?void 0:n.paper_ids)??[],idSet:a,isLoading:s.isLoading,isError:s.isError}}function Gr(){const{user:t}=Le(),s=de(),a=ue({mutationFn:async({paperId:n,isBookmarked:l})=>{l?await ot.removeBookmark(n):await ot.addBookmark(n)},onMutate:async({paperId:n,isBookmarked:l})=>{await s.cancelQueries({queryKey:be});const i=s.getQueryData(be),o=typeof n=="string"?Number(n):n,c=(i==null?void 0:i.paper_ids)??[],g=l?c.filter(x=>x!==o):[o,...c.filter(x=>x!==o)];return s.setQueryData(be,{paper_ids:g}),{previous:i}},onError:(n,l,i)=>{i!=null&&i.previous&&s.setQueryData(be,i.previous),n instanceof it&&n.code==="saved_papers_bucket_authorization_required"&&Or(l)},onSettled:()=>{s.invalidateQueries({queryKey:be}),s.invalidateQueries({queryKey:["my-bookmarks"]})}});return Fe.useEffect(()=>{if(!t||a.isPending)return;const n=new URL(window.location.href);if(n.searchParams.get(It)!=="1")return;n.searchParams.delete(It),window.history.replaceState({},"",`${n.pathname}${n.search}${n.hash}`);const l=window.sessionStorage.getItem(mt);if(l){window.sessionStorage.removeItem(mt);try{const i=JSON.parse(l);(typeof i.paperId=="number"||typeof i.paperId=="string")&&typeof i.isBookmarked=="boolean"&&a.mutate(i)}catch{}}},[a,t]),{toggle:Fe.useCallback((n,l)=>{if(!t){if(Ot())return;const i=typeof window<"u"?window.location.pathname+window.location.search:"/";window.location.href=Us(`/api/v1/auth/hf/login?return_to=${encodeURIComponent(i)}`);return}a.mutate({paperId:n,isBookmarked:l})},[a,t]),isPending:a.isPending}}const Vr=({paperId:t})=>{const{user:s}=Le(),{idSet:a}=Qr(),{toggle:r,isPending:n}=Gr();if(Ot())return null;const l=Number(t),i=!!s&&a.has(l),o=()=>{Number.isFinite(l)&&r(l,i)},c=s&&i?"Saved":"Save",g=s?i?"Remove from saved papers":"Save this paper":"Sign in with Hugging Face to save this paper";return e.jsxs("button",{type:"button",className:`action-btn${i?" is-saved":""}`,onClick:o,disabled:n,"aria-pressed":i,"aria-label":g,title:g,children:[e.jsx(G,{name:"bookmark",size:12}),c]})};function $e({children:t,showEdit:s=!1,onEdit:a,editAriaLabel:r}){return s?e.jsxs("span",{className:"action-btn-composite",children:[t,e.jsx("button",{type:"button",className:"action-btn-segment action-btn-edit",onClick:a,"aria-label":r,children:"edit"})]}):t}function Jr(t){return e.jsx(rs,{...t,kind:"enrich-paper",triggerClassName:"action-btn"})}const Xr={tasks:"tasks",methods:"methods",results:"evaluation results",repositories:"GitHub repositories","project-pages":"project pages","hf-artifacts":"Hugging Face artifacts",organizations:"organizations","source-url":"source URL"};function Ut(t){if(!t)return"—";try{return new Date(t).toLocaleDateString("en-US",{year:"numeric",month:"short",day:"numeric"})}catch{return"—"}}function Wr(t){return t>=1e3?`${(t/1e3).toFixed(1)}k`:String(t)}function Bt(t,s){try{const a=new URL(t),n=a.pathname.replace(/\/$/,"").split("/").filter(Boolean).at(-1);return n?n.replace(/[-_]+/g," "):a.hostname.replace(/^www\./,"")}catch{return s}}const In=()=>{const{arxivId:t}=Bs(),s=Ht(),{toast:a}=te(),{user:r}=Le(),n=(r==null?void 0:r.is_admin)??!1,l=!!r,i=ba(r),o=!0,{arxivId:c,evaluations:g,evaluationsByTask:x,evaluationsLoading:u,paper:m,paperError:k,paperLoading:E,presentation:y,refetchEvaluations:j,refetchPaper:R,relatedQuery:$,versions:T,visibleEvaluations:N}=Ta(t,i),[v,h]=p.useState(!1),{activeEditor:f,openEditor:_,setEditorOpen:A}=Da();p.useEffect(()=>{i!=="direct"||!(m!=null&&m.id)||(f&&f!=="results"&&V.primeCurationState(m.id).catch(()=>{}),f==="results"&&Te.primeCurationState(m.id).catch(()=>{}))},[f,i,m==null?void 0:m.id]);const[U,H]=p.useState(null),O=p.useRef(!1);p.useEffect(()=>{if(!r||!m||O.current)return;const w=sessionStorage.getItem("pwc:fresh-auth-edit");if(!w)return;O.current=!0;const q=Ba(w);if(!V.freshAuthMutationDraft()){sessionStorage.removeItem("pwc:fresh-auth-edit"),q&&_(q);return}if(!window.confirm("You signed in again. Apply the saved destructive catalog edit now? The server will recheck the current catalog version before changing anything.")){a({title:"Edit kept locally",description:"Nothing was changed. Reload this paper when you are ready to confirm the saved edit."});return}V.resumeFreshAuthMutation().then(()=>{a({title:"Edit applied",description:"The restored catalog edit was applied."}),window.location.reload()}).catch(Ct=>{a({variant:"destructive",title:"Could not apply the saved edit",description:Ct instanceof Error?Ct.message:"Please reload and review the edit again."})})},[_,m,a,r]);const J=p.useMemo(()=>{if(!r||!(m!=null&&m.author_links))return!1;const w=r.username.toLowerCase();return m.author_links.some(q=>!!q.hf_username&&q.hf_username.toLowerCase()===w)},[r,m==null?void 0:m.author_links]),d=w=>{if(!l){H(w);return}_(w)},[C,I]=p.useState("idle"),[L,S]=p.useState(null),[K,X]=p.useState(null),b=async()=>{if(c){I("indexing"),S(null),X(null);try{await V.indexFromArxiv(c),a({title:"Indexed",description:"Paper added to database."}),setTimeout(()=>R(),1200),I("idle")}catch(w){const q=w;let ke=q.message||"Failed to index paper";if(q.response)try{ke=JSON.parse(q.response).detail||ke}catch{ke=q.response}S(ke),(q.status===429||q.status===503)&&X("Try again later after arXiv has lifted the temporary limit."),I("idle")}}},P=(y==null?void 0:y.citationCopy)??"",F=(y==null?void 0:y.copyableRanks)??[],[B,M]=p.useState(!1),Q=async()=>{if(P)try{await navigator.clipboard.writeText(P),M(!0),a({title:"Citation copied",description:"BibTeX entry copied to clipboard."}),window.setTimeout(()=>M(!1),1500)}catch{a({title:"Copy failed",description:"Could not access the clipboard. Please copy manually.",variant:"destructive"})}},z=async()=>{if(!m)return;const w=m.arxiv_id||m.id,q=va(w,F);if(q)try{await navigator.clipboard.writeText(q),a({title:"PwC badges copied",description:"Each badge follows its current leaderboard result."})}catch{a({title:"Copy failed",description:"Could not access the clipboard. Please try again.",variant:"destructive"})}};if(E)return e.jsxs("div",{className:"page",children:[e.jsx(Ne,{className:"h-12 w-3/4 mb-4"}),e.jsx(Ne,{className:"h-6 w-1/3 mb-8"}),e.jsx(Ne,{className:"h-64 w-full"})]});if(k||!m)return e.jsxs("div",{className:"page",children:[e.jsxs("div",{className:"breadcrumb",children:[e.jsx(le,{to:"/papers",children:"Papers"}),e.jsx("span",{className:"sep",children:"/"}),e.jsxs("span",{style:{color:"var(--ink)"},children:["arXiv:",c]})]}),e.jsx("h1",{className:"detail-title",children:"Paper not indexed yet"}),e.jsxs("p",{style:{fontFamily:"var(--serif)",color:"var(--ink-soft)",marginTop:16,maxWidth:640},children:["We don't have ",e.jsxs("span",{style:{fontFamily:"var(--mono)"},children:["arXiv:",c]})," in the database. You can index it from arXiv right now."]}),L&&e.jsx(aa,{variant:"destructive",className:"mt-4 max-w-xl",children:e.jsxs(ra,{children:[e.jsx("div",{children:L}),K&&e.jsx("div",{className:"mt-2",children:K})]})}),e.jsxs("div",{className:"action-row",children:[n&&e.jsxs("button",{className:"action-btn",onClick:b,disabled:C==="indexing",children:[e.jsx(G,{name:"sparkle",size:12}),C==="indexing"?"Indexing…":"Index from arXiv"]}),e.jsx(D,{variant:"outline",onClick:()=>s("/papers"),children:"Browse Papers"})]})]});if(!y)return null;const{allHfArtifactUrls:js,authorEntries:ze,citationDisplay:vs,hasIntroducedItems:ys,hasLineageItems:ks,hfArtifactViewer:qe,hfPaperExists:ws,introducedBenchmarks:_s,introducedFrameworks:jt,introducedMethods:Ns,introducedSummary:Cs,numPages:vt,paperSourceLabel:yt,predecessorPapers:Ke,projectPages:ve,repoSummary:ye,safeAbstractUrl:kt,safeConferenceUrl:wt,safePdfUrl:_t,sourceActionLabel:Es,successorPapers:Oe}=y,Pe=12,Qe=ka(m,c),Nt=v||ze.length<=Pe?ze:ze.slice(0,Pe);return e.jsxs("div",{className:"page",children:[e.jsxs("div",{className:"breadcrumb",children:[e.jsx(le,{to:"/",children:"Trending"}),e.jsx("span",{className:"sep",children:"/"}),e.jsx("span",{children:yt})]}),e.jsxs("div",{className:"detail-grid",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"detail-hero",children:[e.jsxs("div",{className:"detail-hero-main",children:[e.jsx("h1",{className:"detail-title",children:e.jsx(Ae,{title:m.title})}),e.jsxs("div",{className:"detail-meta",children:[e.jsx("span",{children:yt}),e.jsx("span",{children:"·"}),e.jsxs("span",{children:["Submitted ",Ut(m.published)]}),vt&&e.jsxs(e.Fragment,{children:[e.jsx("span",{children:"·"}),e.jsxs("span",{children:[vt," pages"]})]}),m.citation_count!=null&&e.jsxs(e.Fragment,{children:[e.jsx("span",{children:"·"}),e.jsxs("span",{children:[m.citation_count.toLocaleString()," citations"]})]}),(m.proceeding||m.conference_slug)&&e.jsxs(e.Fragment,{children:[e.jsx("span",{children:"·"}),m.conference_slug?e.jsx("a",{href:`/conferences/${m.conference_slug}`,target:"_blank",rel:"noopener noreferrer",style:{color:"var(--accent-text)"},children:(m.proceeding||m.conference_name||"").replace(/\s+\d{1,2}$/,"")}):e.jsx("span",{children:m.proceeding.replace(/\s+\d{1,2}$/,"")})]}),T.length>1&&e.jsxs(e.Fragment,{children:[e.jsx("span",{children:"·"}),e.jsx("select",{className:"version-select",value:m.version,onChange:w=>{const q=w.target.value;m.arxiv_id&&s(`/paper/${m.arxiv_id.replace(/v\d+$/,"")}${q?`?version=${q}`:""}`)},children:T.map(w=>e.jsxs("option",{value:w.version,children:[w.version," — ",Ut(w.published)]},w.version))})]})]}),e.jsxs("div",{className:"detail-authors",children:[Nt.map((w,q)=>e.jsxs(Fe.Fragment,{children:[w.id?e.jsx(le,{to:`/authors/${w.id}`,children:w.name}):w.hf_username?e.jsx("a",{href:`https://huggingface.co/${w.hf_username}`,target:"_blank",rel:"noopener noreferrer",title:`@${w.hf_username} on Hugging Face`,children:w.name}):e.jsx("a",{children:w.name}),qPe&&e.jsx("button",{className:"show-more-authors",onClick:()=>h(w=>!w),style:{marginLeft:8,background:"none",border:"none",cursor:"pointer",color:"var(--accent-text)",fontFamily:"var(--mono)",fontSize:12},children:v?"show fewer":`+${m.authors.length-Pe} more`})]}),e.jsxs("div",{className:"action-row",children:[Qe&&Ds()&&(!Hs()||r!=null&&r.is_admin)?e.jsxs(le,{className:"action-btn",to:Qe,onClick:()=>{const w=Qe.slice(5);sessionStorage.removeItem(`pwc:reader:session:${w}`),sessionStorage.removeItem(`pwc:reader:assistant-collapsed:${w}`),sessionStorage.removeItem(`pwc:reader:page:${w}`)},children:[e.jsx(G,{name:"pdf",size:12})," Read paper",e.jsx("span",{className:"nav-new-badge","aria-hidden":"true",children:"New"})]}):_t?e.jsxs("a",{className:"action-btn",href:_t,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(G,{name:"pdf",size:12})," View PDF"]}):null,kt&&e.jsx($e,{showEdit:m.source==="external"&&o,onEdit:()=>d("source-url"),editAriaLabel:"Edit source URL",children:e.jsxs("a",{className:m.source==="external"&&o?"action-btn-segment action-btn-main":"action-btn",href:kt,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(G,{name:"external",size:12})," ",Es]})}),qe.paperHref&&ws&&e.jsxs("a",{className:"bm-action-btn",href:qe.paperHref,target:"_blank",rel:"noopener noreferrer","aria-label":"View on Hugging Face",children:["View on ",e.jsx("span",{"aria-hidden":"true",children:"🤗"})]}),ye.githubUrl&&e.jsx($e,{showEdit:o,onEdit:()=>d("repositories"),editAriaLabel:"Edit code repositories",children:e.jsxs("a",{className:"action-btn-segment action-btn-main",href:ye.githubUrl,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(G,{name:"github",size:12})," Code",ye.github!=null&&e.jsxs("span",{style:{opacity:.7,marginLeft:4},children:["· ",Wr(ye.github)," ★"]})]})}),ye.githubUrl?null:e.jsxs("button",{type:"button",className:"action-btn",onClick:()=>d("repositories"),title:"Add GitHub repository",children:[e.jsx(G,{name:"github",size:12})," Add code"]}),ve.length===1?e.jsx($e,{showEdit:o,onEdit:()=>d("project-pages"),editAriaLabel:"Edit project pages",children:e.jsxs("a",{className:"action-btn-segment action-btn-main",href:ve[0].safeHref??void 0,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(G,{name:"globe",size:12})," Project page"]})}):null,ve.length>1?e.jsx($e,{showEdit:o,onEdit:()=>d("project-pages"),editAriaLabel:"Edit project pages",children:e.jsxs(Ms,{children:[e.jsx(zs,{asChild:!0,children:e.jsxs("button",{type:"button",className:"action-btn-segment action-btn-main",children:[e.jsx(G,{name:"globe",size:12})," Project page"]})}),e.jsx(qs,{align:"start",className:"project-page-menu",children:ve.map((w,q)=>e.jsx(Ks,{asChild:!0,children:w.safeHref?e.jsx("a",{href:w.safeHref,target:"_blank",rel:"noopener noreferrer",children:Bt(w.url,`Project page ${q+1}`)}):e.jsx("span",{children:Bt(w.url,`Project page ${q+1}`)})},w.url))})]})}):null,ve.length===0&&l?e.jsxs("button",{type:"button",className:"action-btn",onClick:()=>d("project-pages"),title:"Add project page",children:[e.jsx(G,{name:"globe",size:12})," Add project page"]}):null,wt&&e.jsxs("a",{className:"action-btn",href:wt,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(G,{name:"external",size:12})," Conference"]}),(m.organizations||[]).map(w=>e.jsxs(le,{to:`/orgs/${w.slug}`,className:"action-btn",title:w.name,"aria-label":w.name,children:[w.logo_url&&e.jsx("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",height:16,width:16,borderRadius:3,overflow:"hidden"},children:e.jsx("img",{src:w.logo_url,alt:"",style:{height:"150%",width:"150%",objectFit:"contain"},onError:q=>{q.currentTarget.style.display="none"}})}),w.name]},w.id)),e.jsx("button",{type:"button",className:"action-btn",onClick:()=>d("organizations"),children:"Edit organizations"}),n&&pa()&&e.jsx(Jr,{paperId:Number(m.id),paperTitle:m.title,onComplete:()=>void R()}),e.jsx(Vr,{paperId:m.id})]}),m.leaderboard_ranks&&m.leaderboard_ranks.length>0&&e.jsx(Vs,{wrap:!0,paperHref:`/paper/${m.arxiv_id||m.id}`,ranks:m.leaderboard_ranks.filter(w=>w.best_rank>=1&&w.best_rank<=3).map(w=>({name:w.dataset_name,slug:w.dataset_slug||null,rank:w.best_rank}))})]}),e.jsx("div",{className:"detail-hero-thumb detail-thumb-wrap",children:e.jsx(Js,{paperId:m.arxiv_id||m.id,title:m.title,thumbnailUrl:Os(m.thumbnail_url),priority:!0})})]}),ys&&e.jsxs("div",{className:`introduced-banner${jt.length>0?" introduced-banner--framework":""}`,children:[e.jsx("span",{className:"introduced-label",children:"Introduced"}),e.jsxs("div",{className:"introduced-methods",children:[Ns.map(w=>e.jsxs("button",{type:"button",className:"introduced-pill",onClick:()=>s(`/methods/${w.slug||w.id}`),children:[w.name,e.jsx("span",{className:"introduced-arrow",children:"→"})]},`method-${w.id}`)),_s.map(w=>e.jsxs("button",{type:"button",className:"introduced-pill",onClick:()=>s(`/benchmark/${w.slug||w.id}`),children:[w.name,e.jsx("span",{className:"introduced-arrow",children:"→"})]},`benchmark-${w.id}`)),jt.map(w=>e.jsxs("button",{type:"button",className:"introduced-pill",onClick:()=>s(`/frameworks#framework-${w.slug}`),children:[w.name,e.jsx("span",{className:"introduced-arrow",children:"→"})]},`framework-${w.slug}`))]}),e.jsxs("span",{className:"introduced-note",children:["This paper is the canonical source for ",Cs,"."]})]}),ks&&e.jsxs("div",{className:"introduced-banner lineage-banner",children:[Oe.length>0&&e.jsxs("div",{className:"lineage-row",children:[e.jsx("span",{className:"introduced-label lineage-label",children:Oe.length===1?"Follow-up paper":"Follow-up papers"}),e.jsx("div",{className:"introduced-methods",children:Oe.map(w=>e.jsxs("button",{type:"button",className:"introduced-pill lineage-pill",onClick:()=>s(`/paper/${w.route_identifier}`),children:[e.jsx(Ae,{title:w.title}),e.jsx("span",{className:"introduced-arrow",children:"→"})]},`successor-${w.id}`))})]}),Ke.length>0&&e.jsxs("div",{className:"lineage-row",children:[e.jsx("span",{className:"introduced-label lineage-label",children:Ke.length===1?"Predecessor paper":"Predecessor papers"}),e.jsx("div",{className:"introduced-methods",children:Ke.map(w=>e.jsxs("button",{type:"button",className:"introduced-pill lineage-pill",onClick:()=>s(`/paper/${w.route_identifier}`),children:[e.jsx("span",{className:"introduced-arrow lineage-arrow-back",children:"←"}),e.jsx(Ae,{title:w.title})]},`predecessor-${w.id}`))})]})]}),e.jsx(Kr,{canEdit:o,onEditMethods:()=>d("methods"),onEditTasks:()=>d("tasks"),paper:m}),e.jsx(xr,{canCopyBadge:F.length>0,canEdit:o,evaluationsByTask:x,evaluationsLoading:u,isAdmin:n,onCopyBadge:z,onEdit:()=>d("results"),onRefresh:()=>void j(),paper:m,visibleEvaluationCount:(N==null?void 0:N.length)??0})]}),e.jsx(Mr,{allHfArtifactUrls:js,citationCopied:B,citationDisplay:vs,hfArtifactViewer:qe,onCopyCitation:Q,onEditHfArtifacts:()=>d("hf-artifacts"),onEditRepositories:()=>d("repositories"),paper:m,relatedIsLoading:$.isLoading,relatedPapers:$.data,user:r})]}),e.jsx(hr,{activeEditor:f,arxivId:c,editSubmitMode:i,evaluations:g??[],isAdmin:n,isLinkedAuthor:J,onOpenChange:A,paper:m}),e.jsx(na,{open:U!==null,onOpenChange:w=>{w||H(null)},sectionLabel:U?Xr[U]:"this paper",returnTo:typeof window<"u"?window.location.pathname:"/"})]})};export{In as default};