Spaces:
Running
Running
| import{c as ct,d as ke,r as c,e as lt,u as dt,a as ut,f as ht,g as ft,j as i,h as mt,X as pt}from"./index-Dq4RFSP6.js";import{C as Me,U as gt,A as yt}from"./ChatMessage-DXpEOAh_.js";import{c as bt,g as Oe,t as Qe,r as wt,F as vt,D as _t,l as xt,C as Ye,a as Fe,b as Ue,d as Rt,e as St,P as Ot,f as qe,h as kt,T as Tt,S as Be,u as He,i as Ct,j as Et,k as Lt}from"./chatSessions-DWxbbxRV.js";import{S as jt}from"./chatPrompts-CDY3UGU1.js";import"./katex.min-BSBacQyE.js";import"./hover-card-BxOV7XYi.js";import"./PaperPreviewLink-BqCm1Tow.js";import"./index-CIS6RuaO.js";import"./useQuery-CeQZ3vLa.js";import"./useBaseQuery-BPHJ2Zjo.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 It=ct("Share2",[["circle",{cx:"18",cy:"5",r:"3",key:"gq8acd"}],["circle",{cx:"6",cy:"12",r:"3",key:"w7nqdw"}],["circle",{cx:"18",cy:"19",r:"3",key:"1xt0gg"}],["line",{x1:"8.59",x2:"15.42",y1:"13.51",y2:"17.49",key:"47mynk"}],["line",{x1:"15.41",x2:"8.59",y1:"6.51",y2:"10.49",key:"1n3mei"}]]),P=(l,d)=>new Promise(h=>{const M=setTimeout(f,l);function f(){d==null||d.removeEventListener("abort",f),clearTimeout(M),h()}d==null||d.addEventListener("abort",f)}),V=l=>({arxiv_id:null,source:"arxiv",source_url:null,thumbnail_url:null,authors:[],published:null,conference:null,citation_count:null,tasks:[],methods:[],repositories:[],project_pages:[],...l}),G={name:"Object Detection",slug:"object-detection"},J={name:"Real-Time Object Detection",slug:"real-time-object-detection"},Nt={"2502.12524":{route_id:"2502.12524",title:"YOLOv12: Attention-Centric Real-Time Object Detectors",content:"Enhancing the network architecture of the YOLO framework has been crucial for a long time. This work introduces an attention-centric YOLO framework, namely YOLOv12, built around area attention and residual efficient layer aggregation networks (R-ELAN). YOLOv12-N reaches 40.6 mAP at 1.64 ms on a T4 GPU, closing the gap to attention-based detectors without the usual latency penalty and surpassing YOLOv10/YOLOv11 by +1.2–1.6 mAP at matched latency.",content_truncated:!1,metadata:V({arxiv_id:"2502.12524",authors:[{name:"Y. Tian"},{name:"Q. Ye"},{name:"D. Doermann"}],published:"2025-02-18",citation_count:412,tasks:[G,J],methods:[{name:"Area Attention",slug:"area-attention"}],repositories:[{url:"https://github.com/sunsmarterjie/yolov12",stars:18700}]})},"2407.17140":{route_id:"2407.17140",title:"RT-DETRv2: Improved Baseline with Bag-of-Freebies for Real-Time Detection",content:"RT-DETRv2 improves the real-time DETR baseline with selective multi-scale feature extraction, a discrete sampling operator to ease deployment, and training-only 'bag-of-freebies' that add no inference cost. RT-DETRv2-R18/R50/R101 reach 47.9 / 53.4 / 54.3 mAP on COCO at 217 / 108 / 74 FPS on T4 TensorRT FP16, remaining NMS-free end to end.",content_truncated:!1,metadata:V({arxiv_id:"2407.17140",authors:[{name:"W. Lv"},{name:"Y. Zhao"},{name:"J. Chang"}],published:"2024-07-24",citation_count:268,tasks:[G,J],methods:[{name:"DETR",slug:"detr"}],repositories:[{url:"https://github.com/lyuwenyu/RT-DETR",stars:9400}]})},"2410.13842":{route_id:"2410.13842",title:"D-FINE: Redefining Regression as Fine-grained Distribution Refinement",content:"D-FINE reformulates bounding-box regression in DETR-style detectors as iterative refinement of probability distributions (FDR) and adds a localization self-distillation scheme (GO-LSD). D-FINE-L reaches 54.0 mAP at ~9 ms and D-FINE-X 55.8 mAP on COCO while staying real-time on modern GPUs, dominating RT-DETRv2 and YOLOv10 on the accuracy–latency Pareto front.",content_truncated:!1,metadata:V({arxiv_id:"2410.13842",authors:[{name:"Y. Peng"},{name:"H. Li"},{name:"P. Wu"}],published:"2024-10-17",conference:"ICLR 2025",citation_count:187,tasks:[G,J],methods:[{name:"Knowledge Distillation",slug:"knowledge-distillation"}],repositories:[{url:"https://github.com/Peterande/D-FINE",stars:12100}]})},"2406.03459":{route_id:"2406.03459",title:"LW-DETR: A Transformer Replacement to YOLO for Real-Time Detection",content:"LW-DETR pairs a plain ViT encoder with a lightweight DETR decoder and shows the combination outperforms YOLOv8 and YOLO-NAS at comparable latency, arguing transformer detectors are viable even at the fast end of the accuracy–latency curve. Uses multi-level feature aggregation, window-attention interleaving, and IoU-aware classification.",content_truncated:!1,metadata:V({arxiv_id:"2406.03459",authors:[{name:"Q. Chen"},{name:"X. Su"},{name:"X. Zhang"}],published:"2024-06-05",citation_count:94,tasks:[G,J],methods:[{name:"Vision Transformer",slug:"vision-transformer"}],repositories:[{url:"https://github.com/Atten4Vis/LW-DETR",stars:5200}]})},"2304.08069":{route_id:"2304.08069",title:"DETRs Beat YOLOs on Real-time Object Detection",content:"RT-DETR is the first real-time end-to-end object detector, built on an efficient hybrid encoder that decouples intra-scale interaction and cross-scale fusion, plus IoU-aware query selection. RT-DETR-R50 achieves 53.1 mAP at 108 FPS on COCO, beating comparably sized YOLO detectors in both speed and accuracy while eliminating NMS entirely; its Figure 1 accuracy–latency plot became the reference for later real-time detectors.",content_truncated:!1,metadata:V({arxiv_id:"2304.08069",authors:[{name:"Y. Zhao"},{name:"W. Lv"},{name:"S. Xu"}],published:"2023-04-17",conference:"CVPR 2024",citation_count:2310,tasks:[G,J],methods:[{name:"DETR",slug:"detr"}],repositories:[{url:"https://github.com/lyuwenyu/RT-DETR",stars:9400}]})},"2405.14458":{route_id:"2405.14458",title:"YOLOv10: Real-Time End-to-End Object Detection",content:"YOLOv10 removes NMS from the YOLO pipeline via consistent dual assignments during training and applies a holistic efficiency–accuracy driven design across the architecture. YOLOv10-S is 1.8x faster than RT-DETR-R18 at similar COCO accuracy; the family spans 46.3–54.4 mAP with substantially lower end-to-end latency than prior YOLOs because post-processing disappears.",content_truncated:!1,metadata:V({arxiv_id:"2405.14458",authors:[{name:"A. Wang"},{name:"H. Chen"},{name:"L. Liu"}],published:"2024-05-23",conference:"NeurIPS 2024",citation_count:1650,tasks:[G,J],methods:[{name:"NMS-free Training",slug:"nms-free-training"}],repositories:[{url:"https://github.com/THU-MIG/yolov10",stars:44200}]})},"2401.17270":{route_id:"2401.17270",title:"YOLO-World: Real-Time Open-Vocabulary Object Detection",content:"YOLO-World extends the YOLO paradigm to open-vocabulary detection through vision-language modeling with a re-parameterizable vision-language path aggregation network (RepVL-PAN) and region-text contrastive pretraining. It detects categories never seen at training time while running at 35+ FPS, and its prompt-then-detect deployment re-parameterizes text embeddings for zero runtime text-encoder cost.",content_truncated:!1,metadata:V({arxiv_id:"2401.17270",authors:[{name:"T. Cheng"},{name:"L. Song"},{name:"Y. Ge"}],published:"2024-01-30",conference:"CVPR 2024",citation_count:890,tasks:[{name:"Open-Vocabulary Object Detection",slug:"open-vocabulary-object-detection"},G],methods:[{name:"Contrastive Learning",slug:"contrastive-learning"}],repositories:[{url:"https://github.com/AILab-CVC/YOLO-World",stars:16800}]})},158342:{route_id:"158342",title:"Ultralytics YOLO: real-time detection framework and model zoo",content:"Official Ultralytics framework release covering YOLO11 and YOLOv12 deployment: pretrained COCO checkpoints from nano to x-large, TensorRT/ONNX/CoreML export paths, and reproducible latency benchmarks on T4, Jetson Orin, and CPU targets. Widely used as the practical baseline for real-time detection deployments.",content_truncated:!1,metadata:V({source:"external",source_url:"https://docs.ultralytics.com/models/",authors:[{name:"Ultralytics"}],published:"2025-01-02",tasks:[G,J],repositories:[{url:"https://github.com/ultralytics/ultralytics",stars:46e3}],project_pages:[{url:"https://docs.ultralytics.com"}]})}},Ze=l=>l.map(d=>Nt[d]),We=Ze(["2502.12524","2407.17140","2410.13842","2406.03459","2304.08069","2405.14458","2401.17270","158342"]),Ve=Ze(["2410.13842","2502.12524","2407.17140","2405.14458","2304.08069"]),Ge="The user wants the current state-of-the-art for real-time object detection. That's a moving target split across two lineages — the YOLO family (fast CNN one-stage detectors) and the DETR family (transformer, end-to-end, NMS-free). I should ground the answer in recent papers benchmarked on COCO with reported latency or FPS, not just accuracy. Let me start with a broad hybrid search, see which papers surface, then run a second, narrower query to pin down the head-to-head COCO mAP vs latency trade-offs before I write anything.",Ke="Good — both lineages are well represented. YOLOv12, YOLOv10 and RT-DETRv2 / D-FINE keep coming up. To actually rank them I need the accuracy-vs-latency numbers side by side on the same COCO val2017 protocol, so let me narrow the query to the benchmark comparison specifically.",$e=`There isn't a single winner — real-time object detection in 2026 is a two-horse race between the [YOLO family](paper:2502.12524) (fast one-stage CNNs) and the end-to-end [DETR family](paper:2304.08069) (NMS-free transformers). Which one is “SOTA” depends entirely on where you sit on the accuracy-vs-latency curve. | |
| **At the fast / edge end**, [YOLOv12](paper:2502.12524) is the current leader. Its area-attention design pushes attention into the YOLO backbone without the usual latency hit — YOLOv12-N reaches 40.6 mAP at ~1.6 ms on a T4, roughly +1.5 mAP over [YOLOv10](paper:2405.14458) at matched speed. [YOLOv10](paper:2405.14458) is still very relevant because it made the YOLO head NMS-free, cutting real end-to-end latency. | |
| **At the high-accuracy end**, the transformer detectors win. [D-FINE](paper:2410.13842) currently holds the accuracy-latency Pareto front, reporting 55.8 mAP by reformulating box regression as fine-grained distribution refinement with self-distillation. It builds on [RT-DETRv2](paper:2407.17140), which hardened the [original RT-DETR](paper:2304.08069) recipe (the paper that first showed DETRs beating YOLOs in real time) with training-only “bag-of-freebies” that add no inference cost. | |
| **My recommendation:** for edge or high-FPS deployment, start with [YOLOv12](paper:2502.12524) — the [Ultralytics framework](paper:158342) has ready-made checkpoints and export paths. If you have GPU headroom and want maximum accuracy while staying real-time, use [D-FINE](paper:2410.13842) or [RT-DETRv2](paper:2407.17140). And if you need open-vocabulary detection rather than fixed COCO classes, [YOLO-World](paper:2401.17270) is the one to look at.`,At=["How do these compare on edge devices like Jetson?","Show me open-vocabulary detectors","What about small-object detection?"];async function*Dt(l,d){const h=()=>(d==null?void 0:d.aborted)===!0,M=l.trim().slice(0,90)||"state-of-the-art real-time object detection";if(yield{type:"stream_start",request_id:"req_mock",session_id:null},await P(350,d),!h()){yield{type:"reasoning_start"};for(let f=0;f<Ge.length;f+=6){if(await P(14,d),h())return;yield{type:"reasoning_delta",text:Ge.slice(f,f+6)}}if(await P(400,d),!h()&&(yield{type:"reasoning_end"},await P(300,d),!h()&&(yield{type:"tool_call",id:"call_1",name:"search_papers",args:{query:M,top_k:8}},await P(1100,d),!h()&&(yield{type:"tool_result",id:"call_1",hits:We.length,took_ms:214,results:We},await P(350,d),!h())))){yield{type:"reasoning_start"};for(let f=0;f<Ke.length;f+=6){if(await P(14,d),h())return;yield{type:"reasoning_delta",text:Ke.slice(f,f+6)}}if(await P(350,d),!h()&&(yield{type:"reasoning_end"},await P(300,d),!h()&&(yield{type:"tool_call",id:"call_2",name:"search_papers",args:{query:"RT-DETR vs YOLOv12 COCO mAP latency FPS T4 TensorRT comparison",top_k:5}},await P(900,d),!h()&&(yield{type:"tool_result",id:"call_2",hits:Ve.length,took_ms:176,results:Ve},await P(400,d),!h())))){for(let f=0;f<$e.length;f+=4){if(await P(11,d),h())return;yield{type:"answer_delta",text:$e.slice(f,f+4)}}yield{type:"done",followups:At,finish_reason:"success"}}}}}const me=()=>{const d=String("0").trim().toLowerCase();return d==="1"||d==="true"||d==="yes"};class et extends Error{constructor(d,h){super(d),this.code=h,this.name="ChatStreamError"}}function Pt(l,d){if(me())try{fetch(ke(`/api/v1/chat/latency/${encodeURIComponent(l)}`),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",keepalive:!0,body:JSON.stringify(d)}).catch(()=>{})}catch{}}function Mt(l,d={}){return me()?Yt(l,d.signal):Dt(l.message,d.signal)}async function*Yt(l,d){const h=await fetch(ke("/api/v1/chat/stream"),{method:"POST",headers:{"Content-Type":"application/json",Accept:"text/event-stream"},credentials:"include",body:JSON.stringify(l),signal:d});if(!h.ok||!h.body){const C=await h.json().catch(()=>null),x=C==null?void 0:C.detail,_=h.status===403&&!x;throw new et(_?"Chat on staging is limited to approved Hugging Face users. Sign in with an approved account and try again.":(x==null?void 0:x.message)||x||`Chat stream failed (${h.status})`,(x==null?void 0:x.code)||(_?"staging_access_required":void 0))}const M=h.body.getReader(),f=new TextDecoder;let L="";try{for(;;){const{done:C,value:x}=await M.read();if(C)break;L+=f.decode(x,{stream:!0});let _;for(;(_=L.indexOf(` | |
| `))!==-1;){const S=L.slice(0,_);L=L.slice(_+2);const j=S.split(` | |
| `).filter(k=>k.startsWith("data:")).map(k=>k.slice(5).trimStart()).join(` | |
| `);!j||j==="[DONE]"||(yield JSON.parse(j))}}}finally{M.releaseLock()}}const ze="Preparing research workspace…",Ft=750;function Se(l,d){for(let h=l.length-1;h>=0;h-=1)if(d(l[h]))return h;return-1}function Ut(l){const[d,h]=c.useState([]),[M,f]=c.useState(!1),[L,C]=c.useState(""),x=c.useRef(!1),_=c.useRef(null),S=c.useRef(null),j=c.useRef("cleared"),k=c.useRef(null),E=c.useRef([]),b=c.useRef(l),U=c.useRef(""),X=c.useRef(""),pe=c.useRef(0),I=c.useRef(0),F=c.useRef(l.sessionId),Q=c.useRef(l.sessionId);Q.current!==l.sessionId&&(Q.current=l.sessionId,F.current!==l.sessionId&&(I.current+=1)),b.current=l,E.current=d,c.useEffect(()=>()=>{var n;S.current!==null&&window.clearTimeout(S.current),(n=_.current)==null||n.abort()},[]),c.useEffect(()=>{x.current||(F.current=l.sessionId)},[l.sessionId]);const ge=c.useMemo(()=>{const n={};for(const s of d)for(const r of s.blocks??[])if(r.kind==="tool")for(const o of r.results??[])n[o.route_id]=o;return n},[d]),N=()=>`m${++pe.current}_${Date.now().toString(36)}`,T=n=>h(s=>{if(!s.length)return s;const r=s.slice();return r[r.length-1]=n(r[r.length-1]),r}),re=n=>T(s=>({...s,blocks:[...s.blocks??[],n]})),se=(n,s)=>T(r=>({...r,blocks:(r.blocks??[]).map((o,y,u)=>n(o,y,u)?s(o):o)})),ye=n=>(s,r,o)=>s.kind===n&&Se(o,y=>y.kind===n)===r,Y=n=>{if(_.current!==n||(S.current!==null&&(window.clearTimeout(S.current),S.current=null),j.current==="cleared"))return;const s=j.current==="shown";j.current="cleared",s&&T(r=>{if(r.status!==ze)return r;const{status:o,...y}=r;return y})},B=(n,s)=>{n.requestId&&Pt(n.requestId,s)},q=(n,s)=>{const r=k.current;!r||r.controller!==n||(r.requestId=s,r.streamStartReported||(r.streamStartReported=!0,B(r,{submission_to_stream_start_ms:Math.max(0,performance.now()-r.submittedAt)})),r.firstVisibleAt!==void 0&&!r.firstVisibleReported&&(r.firstVisibleReported=!0,B(r,{submission_to_first_visible_delta_ms:Math.max(0,r.firstVisibleAt-r.submittedAt)})))},H=(n,s)=>{const r=k.current;!r||r.controller!==n||r.terminalReported||(r.terminalReported=!0,B(r,{terminal_classification:s}))};c.useLayoutEffect(()=>{const n=k.current;if(!n||n.firstVisibleAt!==void 0)return;const s=d.at(-1);(s==null?void 0:s.role)!=="assistant"||!(s.blocks??[]).some(o=>o.kind==="tool"||o.kind==="reasoning"&&!!o.text.trim()||o.kind==="answer"&&!!o.text.trim())||(n.firstVisibleAt=performance.now(),n.requestId&&!n.firstVisibleReported&&(n.firstVisibleReported=!0,B(n,{submission_to_first_visible_delta_ms:Math.max(0,n.firstVisibleAt-n.submittedAt)})))},[d]);const Z=n=>{switch(n.type){case"stream_start":n.session_id&&(F.current=n.session_id,b.current.onSessionId(n.session_id));break;case"sandbox_start":case"sandbox_ready":case"workspace_ready":break;case"session_title_start":X.current="";break;case"session_title_delta":X.current+=n.text,b.current.onTitle(X.current.replace(/\s+/g," ").slice(0,80));break;case"session_title_done":X.current=n.title,b.current.onTitle(n.title);break;case"reasoning_start":T(s=>({...s,blocks:[...(s.blocks??[]).map(r=>r.kind==="reasoning"&&r.active?{...r,active:!1,open:!1}:r),{kind:"reasoning",text:"",active:!0,open:!0}]}));break;case"reasoning_delta":se(ye("reasoning"),s=>s.kind==="reasoning"?{...s,text:s.text+n.text}:s);break;case"reasoning_end":T(s=>{const r=s.blocks??[],o=Se(r,v=>v.kind==="reasoning"&&v.active);if(o<0)return s;const y=r[o];if(y.kind!=="reasoning")return s;const u=r[o-1];return(u==null?void 0:u.kind)==="reasoning"&&u.text===y.text?{...s,blocks:r.filter((v,g)=>g!==o)}:{...s,blocks:r.map((v,g)=>g===o?{...y,active:!1,open:!1}:v)}});break;case"tool_call":re({kind:"tool",id:n.id,name:n.name,args:n.args,status:"running",open:!1});break;case"tool_result":se(s=>s.kind==="tool"&&s.id===n.id,s=>s.kind==="tool"?n.status?{...s,schema_version:2,status:n.status,took_ms:n.took_ms,content:n.content,metadata:n.metadata,open:n.status!=="success"}:{...s,status:"done",hits:n.hits,took_ms:n.took_ms,results:n.results}:s);break;case"answer_delta":T(s=>{const r=s.blocks??[],o=r.at(-1);return(o==null?void 0:o.kind)==="answer"&&!o.done?{...s,blocks:[...r.slice(0,-1),{...o,text:o.text+n.text}]}:{...s,blocks:[...r,{kind:"answer",text:n.text,done:!1}]}});break;case"done":T(s=>({...s,streaming:!1,followups:n.followups,finishReason:n.finish_reason,citations:n.citations,blocks:(s.blocks??[]).map(r=>r.kind==="answer"?{...r,done:!0}:r.kind==="reasoning"&&r.active?{...r,active:!1,open:!1}:r)}));break;case"error":T(s=>({...s,streaming:!1,error:n.message,errorCode:n.code,blocks:(s.blocks??[]).map(r=>r.kind==="reasoning"&&r.active?{...r,active:!1,open:!1}:r)}));break}},K=async(n,s)=>{const r=await Oe(n),o=Qe(r);return I.current!==s?null:(h(o),E.current=o,o)},de=(n,s,r,o)=>{const y=++I.current;x.current=!0;const u=new AbortController;return _.current=u,U.current=n,F.current=s.session_id,C(""),h(r),f(!0),k.current={controller:u,submittedAt:performance.now(),streamStartReported:!1,firstVisibleReported:!1,terminalReported:!1},S.current!==null&&window.clearTimeout(S.current),j.current="armed",S.current=window.setTimeout(()=>{S.current=null,!(_.current!==u||u.signal.aborted||I.current!==y)&&(j.current="shown",T(v=>{var g;return v.role==="assistant"&&v.streaming&&(((g=v.blocks)==null?void 0:g.length)??0)===0&&!v.error?{...v,status:ze}:v}))},Ft),(async()=>{var D;let v=!1,g=!1,A=!1;try{for await(const w of Mt(s,{signal:u.signal}))w.type==="stream_start"&&(v=!0,q(u,w.request_id)),(w.type==="workspace_ready"||w.type==="reasoning_start"||w.type==="reasoning_delta"||w.type==="tool_call"||w.type==="answer_delta"||w.type==="done"||w.type==="error")&&Y(u),(w.type==="done"||w.type==="error")&&(g=!0,A=w.type==="error",H(u,w.type==="error"?"error":"complete")),u.signal.aborted||Z(w)}catch(w){A=!0,u.signal.aborted||(Y(u),H(u,"network_error"),Z({type:"error",message:w instanceof Error?w.message:"The assistant stream failed.",code:w instanceof et?w.code:void 0}))}finally{if(_.current===u){if(Y(u),!g&&!u.signal.aborted&&H(u,"network_error"),x.current=!1,f(!1),!u.signal.aborted){const w=F.current;if(o&&!v)h(o.snapshot),E.current=o.snapshot,C("Couldn’t resend this message. Your original conversation was restored.");else if(w){o&&!o.first&&(A||!g)&&(h(o.snapshot),E.current=o.snapshot);try{const O=await K(w,y);O&&o&&!o.first&&O.some($=>$.id===o.targetId)&&C("Couldn’t resend this message. Your original conversation was restored.")}catch{I.current===y&&T(O=>O.streaming?{...O,streaming:!1}:O)}}else T(O=>O.streaming?{...O,streaming:!1}:O);b.current.onSettled(w)}((D=k.current)==null?void 0:D.controller)===u&&(k.current=null)}}})(),!0},ee=c.useCallback(n=>{const s=n.trim();if(!s||s.length>8e3||x.current)return!1;const r=E.current,o=[...r].reverse().find(D=>D.role==="user"),y=o!=null&&o.status&&o.status!=="complete"&&o.revision?{replace_message_id:o.id,prior_revision:o.revision}:null,u={id:N(),role:"user",text:s},v={id:N(),role:"assistant",streaming:!0,blocks:[]},g=y&&o?Se(r,D=>D.id===o.id):-1,A=g<0?[...r,u,v]:[...r.slice(0,g),u,v];return de(s,{message:s,session_id:b.current.sessionId,client_message_id:crypto.randomUUID(),...!b.current.sessionId&&b.current.initialModel?{initial_model:b.current.initialModel}:{},...y??{}},A)},[]),be=c.useCallback((n,s)=>{const r=s.trim();if(!r||r.length>8e3||x.current)return!1;const o=E.current.slice(),y=o.findIndex(O=>O.id===n&&O.role==="user");if(y<0)return!1;const u=o[y],v=o.findIndex(O=>O.role==="user"),g=y===v;if(!g&&(!b.current.sessionId||!u.revision))return!1;const A={id:u.id,role:"user",text:r,revision:g?void 0:u.revision+1,status:"generating"},D={id:N(),role:"assistant",streaming:!0,blocks:[]},w=g?[A,D]:[...o.slice(0,y),A,D];return de(r,{message:r,session_id:g?null:b.current.sessionId,client_message_id:crypto.randomUUID(),...g&&b.current.initialModel?{initial_model:b.current.initialModel}:{},...g?{}:{replace_message_id:u.id,prior_revision:u.revision}},w,{targetId:u.id,snapshot:o,first:g})},[]),te=c.useCallback(()=>{var o;if(!_.current)return;const n=_.current;Y(n),H(n,"stopped"),n.abort(),_.current=null,((o=k.current)==null?void 0:o.controller)===n&&(k.current=null),x.current=!1,f(!1),h(y=>{const u=y.at(-1);if((u==null?void 0:u.role)!=="assistant")return y;const v=(u.blocks??[]).flatMap(g=>g.kind==="tool"&&g.status==="running"?[]:g.kind==="reasoning"&&g.active?[]:g.kind==="answer"?[{...g,done:!0}]:[g]);return[...y.slice(0,-1),{...u,blocks:v,streaming:!1,finishReason:"stopped"}]}),b.current.onInterrupted(U.current);const s=F.current;s&&bt(s).catch(()=>{});const r=++I.current;window.setTimeout(()=>{s&&I.current===r?K(s,r).catch(()=>{}).finally(()=>b.current.onSettled(s)):s||b.current.onSettled(null)},450)},[]),ue=c.useCallback((n,s)=>h(r=>r.map(o=>{var y;return o.id!==n?o:{...o,blocks:(y=o.blocks)==null?void 0:y.map((u,v)=>v===s&&(u.kind==="reasoning"||u.kind==="tool")?{...u,open:!u.open}:u)}})),[]),ae=c.useCallback(()=>{var n;I.current+=1,S.current!==null&&(window.clearTimeout(S.current),S.current=null),j.current="cleared",(n=_.current)==null||n.abort(),_.current=null,k.current=null,x.current=!1,F.current=null,h([]),f(!1),C("")},[]),W=c.useCallback(n=>{var s;I.current+=1,S.current!==null&&(window.clearTimeout(S.current),S.current=null),j.current="cleared",(s=_.current)==null||s.abort(),_.current=null,k.current=null,x.current=!1,h(n),f(!1),C("")},[]);return{messages:d,busy:M,papers:ge,sessionError:L,send:ee,editAndResend:be,stop:te,toggleBlock:ue,reset:ae,load:W}}const qt="https://huggingface.co/settings/inference-providers",Je="pwc.chat.billing-notice-dismissed.v1",Xe=({provider:l})=>{const[d,h]=c.useState(()=>localStorage.getItem(Je)==="1");return!me()||d||l!=="huggingface"?null:i.jsxs("div",{className:"chat-billing-notice",role:"note",children:[i.jsx("span",{children:"Hugging Face models require your own HF token. Add it in Settings; included monthly credits are used first, then extra usage requires purchased credits."}),i.jsxs("div",{className:"chat-billing-notice-actions",children:[i.jsx("a",{href:"/settings",children:"Add HF token"}),i.jsx("a",{href:qt,target:"_blank",rel:"noreferrer",children:"Review usage"}),i.jsx("button",{type:"button",className:"chat-billing-notice-dismiss","aria-label":"Dismiss billing notice",title:"Dismiss",onClick:()=>{localStorage.setItem(Je,"1"),h(!0)},children:i.jsx(pt,{size:15,"aria-hidden":"true"})})]})]})},Zt=()=>{var Ne,Ae,De,Pe;const{sessionId:l}=lt(),d=dt(),[h,M]=ut(),{user:f,isLoading:L}=ht(),{toast:C}=ft(),[x,_]=c.useState([]),[S,j]=c.useState(!1),[k,E]=c.useState(""),[b,U]=c.useState(()=>l?{id:l,status:"loading"}:null),[X,pe]=c.useState(0),I=c.useRef(wt()),F=c.useRef(h.get("model")||((Ne=I.current)==null?void 0:Ne.model)),[Q,ge]=c.useState(vt),[N,T]=c.useState(F.current||_t),re=((Ae=Q.find(e=>e.id===N))==null?void 0:Ae.provider)??"huggingface",se=mt(),[ye,Y]=c.useState(""),[B,q]=c.useState(""),[H,Z]=c.useState(()=>{var e,t;return((e=h.get("q"))==null?void 0:e.trim())||((t=I.current)==null?void 0:t.prompt)||""}),K=c.useRef(!1),[de,ee]=c.useState(null),[be,te]=c.useState(null),[ue,ae]=c.useState(""),[W,n]=c.useState(null),[s,r]=c.useState(()=>typeof window>"u"||window.innerWidth>900),[o,y]=c.useState(!1),[u,v]=c.useState(!1),[g,A]=c.useState(""),D=c.useRef(new Set),w=c.useRef(!1),O=c.useRef(l),$=c.useRef(null),ie=c.useRef(null);O.current=l;const z=c.useCallback(async()=>{if(!f)return;const e=!w.current;e&&j(!0);try{const t=await xt();_(a=>{const p=$.current,R=p?a.find(le=>le.id===p):void 0;if(!R)return t;const fe=t.find(le=>le.id===p);return[fe?{...fe,title:R.title,is_busy:!0}:R,...t.filter(le=>le.id!==p)]}),w.current=!0,E("")}catch(t){E(t instanceof Error?t.message:"Could not load chats")}finally{e&&j(!1)}},[f]),m=Ut({sessionId:l??null,initialModel:N,onSessionId:e=>{$.current=e;const t=e!==O.current,a=new Date().toISOString();_(p=>p.some(R=>R.id===e)?p.map(R=>R.id===e?{...R,is_busy:!0}:R):[{id:e,title:"New chat",selected_model:N,created_at:a,updated_at:a,message_count:1,is_busy:!0},...p]),t&&Y("New chat"),ie.current=e,U({id:e,status:"loaded"}),d(`/chat/${e}`,{replace:!0})},onTitle:e=>{const t=$.current??O.current;t&&!D.current.has(t)&&(Y(e),_(a=>a.map(p=>p.id===t?{...p,title:e}:p)))},onSettled:e=>{e&&_(t=>t.map(a=>a.id===e?{...a,is_busy:!1}:a)),$.current=null,z()},onInterrupted:e=>{q(e)}});m.load;const Te=m.send;c.useEffect(()=>{m.busy&&ee(null)},[m.busy]);const oe=c.useCallback(e=>{if(!f){sessionStorage.setItem(Ye,e),sessionStorage.setItem(Fe,N),sessionStorage.setItem(Ue,"1"),window.location.href=ke(`/api/v1/auth/hf/login?return_to=${encodeURIComponent("/chat")}`);return}Te(e)&&(Rt(),q(""))},[N,Te,f]);c.useEffect(()=>{if(L||!f)return;const e=sessionStorage.getItem(Fe);e&&T(e),z(),St().then(p=>{if(ge(p.items),!O.current){const R=F.current||e;T(R&&p.items.some(fe=>fe.id===R)?R:p.default_model)}});const t=sessionStorage.getItem(Ye),a=sessionStorage.getItem(Ue)==="1";t&&(a?Z(t):q(t))},[L,z,f]),c.useEffect(()=>{if(!l){ie.current!==null&&(ie.current=null,m.reset()),U(null);return}if(ie.current===l||(U(t=>(t==null?void 0:t.id)===l&&t.status==="loading"?t:{id:l,status:"loading"}),L||!f||m.busy))return;let e=!1;return E(""),Oe(l).then(t=>{e||(m.load(Qe(t)),T(t.selected_model),Y(t.title),ie.current=l,U({id:l,status:"loaded"}))}).catch(t=>{if(e)return;const a=t instanceof Error?t.message:"Chat not found";m.reset(),E(a),U({id:l,status:"error",error:a})}),()=>{e=!0}},[L,l,f,m.busy,X]),c.useEffect(()=>{var p;const e=(p=h.get("q"))==null?void 0:p.trim();if(!e)return;K.current=!1;const t=h.get("model");t&&T(t),Z(e);const a=new URLSearchParams(h);a.delete("q"),a.delete("model"),M(a,{replace:!0})},[h,M]),c.useEffect(()=>{if(L||m.busy||!H||K.current)return;const e=window.setTimeout(()=>{if(K.current)return;K.current=!0;const t=H;Z(""),oe(t)},0);return()=>window.clearTimeout(e)},[L,m.busy,H,oe]),c.useEffect(()=>{const e=()=>{!f||m.busy||z()};return window.addEventListener("focus",e),()=>window.removeEventListener("focus",e)},[m.busy,z,f]),c.useEffect(()=>{if(!W)return;const e=()=>n(null),t=a=>{a.key==="Escape"&&e()};return window.addEventListener("click",e),window.addEventListener("keydown",t),()=>{window.removeEventListener("click",e),window.removeEventListener("keydown",t)}},[W]);const Ce=()=>{$.current=null,m.reset(),q(""),Y(""),d("/chat")},Ee=async e=>{const t=ue.trim();if(t)try{const a=await He(e,{title:t});D.current.add(e),e===l&&Y(a.title),_(p=>p.map(R=>R.id===e?a:R)),te(null)}catch(a){E(a instanceof Error?a.message:"Rename failed")}},tt=async e=>{const t=e===l&&m.busy;if(window.confirm(t?"Stop and delete this chat? This cannot be undone.":"Delete this chat? This cannot be undone.")){t&&m.stop();try{if(t){const a=Date.now()+3e3;for(;(await Oe(e)).is_busy;){if(Date.now()>=a)throw new Error("Generation is still stopping. The chat was not deleted.");await new Promise(R=>window.setTimeout(R,150))}}await Ct(e),e===l&&Ce(),await z()}catch(a){E(a instanceof Error?a.message:"Delete failed")}}},nt=async()=>{var e;if(!u){v(!0);try{const t=await Lt();if(await z(),t.archived_count===0){C({title:"No chats were archived",description:"There are no inactive chats older than 30 days."});return}const a=((e=[...m.messages].reverse().find(p=>p.role==="user"))==null?void 0:e.text)??"";m.reset(),q(a),Y(""),C({title:`${t.archived_count} ${t.archived_count===1?"chat":"chats"} archived`,description:"Your question is ready to send again."})}catch(t){C({variant:"destructive",title:"Could not archive old chats",description:t instanceof Error?t.message:"Try again."})}finally{v(!1)}}},Le=async e=>{const t=N;if(T(e),!!l)try{const a=await He(l,{selected_model:e});_(p=>p.map(R=>R.id===l?{...R,selected_model:a.selected_model}:R)),E("")}catch(a){T(t),E(a instanceof Error?a.message:"Model change failed")}},rt=async()=>{var e;if(!(!l||m.busy||o)){y(!0);try{const t=await Et(l),a=new URL(t.public_path,window.location.origin).toString();try{if(!((e=navigator.clipboard)!=null&&e.writeText))throw new Error("Clipboard unavailable");await navigator.clipboard.writeText(a),C({className:"chat-share-toast",duration:5e3,title:"Public link copied to your clipboard",description:"Anyone with this link can see this conversation."})}catch{A(a)}}catch(t){const a=t instanceof Error?t.message:"Could not share this conversation";E(a),C({variant:"destructive",title:"Share failed",description:a})}finally{y(!1)}}},[st,at]=c.useState(60);c.useLayoutEffect(()=>{const e=document.querySelector(".app-header");if(!e)return;const t=()=>at(e.offsetHeight);t();const a=new ResizeObserver(t);return a.observe(e),()=>a.disconnect()},[]);const we=c.useRef(null),he=c.useRef(null),ce=c.useRef(null);c.useEffect(()=>{m.busy||(ce.current=null)},[m.busy]);const it=(e,t)=>{var a;he.current=((a=we.current)==null?void 0:a.scrollTop)??null,m.toggleBlock(e,t)};c.useLayoutEffect(()=>{const e=we.current;if(e){if(he.current!==null){e.scrollTop=he.current,he.current=null;return}if(ce.current){const t=Array.from(e.querySelectorAll("[data-message-id]")).find(a=>a.dataset.messageId===ce.current);if(t){const a=e.getBoundingClientRect(),p=t.getBoundingClientRect();e.scrollTop+=p.top-a.top-24;return}}e.scrollTop=e.scrollHeight}},[m.messages]);const ne=x.find(e=>e.id===l),je=m.messages.filter(e=>e.role==="user"),ve=(De=je[0])==null?void 0:De.id,ot=(Pe=je.at(-1))==null?void 0:Pe.id,_e=m.messages.length===0,xe=(b==null?void 0:b.id)===l,Re=!!(l&&(L||f&&(!xe||(b==null?void 0:b.status)==="loading"))),Ie=xe&&(b==null?void 0:b.status)==="error"?b.error:void 0;return i.jsxs("div",{className:"chat-page",style:{height:`calc(100dvh - ${st}px)`},children:[i.jsxs("aside",{className:`chat-sidebar${s?"":" chat-sidebar-closed"}`,children:[i.jsxs("div",{className:"chat-sidebar-top",children:[i.jsxs("button",{type:"button",className:"chat-new-chat",onClick:Ce,children:[i.jsx(Ot,{})," New chat"]}),i.jsx("button",{type:"button",className:"icon-btn",onClick:()=>r(!1),title:"Collapse sidebar",children:i.jsx(qe,{})})]}),i.jsxs("nav",{className:"chat-sessions","aria-label":"Chat history",children:[S&&i.jsx("div",{className:"chat-sessions-empty",children:"Loading chats…"}),!S&&k&&i.jsx("div",{className:"chat-sessions-empty",children:k}),!S&&!k&&x.length===0&&i.jsx("div",{className:"chat-sessions-empty",children:"Conversations you start will show up here."}),kt(x).map(e=>i.jsxs("div",{className:"chat-session-group",children:[i.jsx("div",{className:"chat-session-group-label",children:e.label}),e.items.map(t=>i.jsxs("div",{className:`chat-session${t.id===l?" chat-session-active":""}`,role:"button",tabIndex:0,onClick:()=>d(`/chat/${t.id}`),onKeyDown:a=>{if(a.key==="Enter"&&d(`/chat/${t.id}`),a.key==="F2"&&(te(t.id),ae(t.title)),a.key==="ContextMenu"||a.shiftKey&&a.key==="F10"){a.preventDefault();const p=a.currentTarget.getBoundingClientRect();n({id:t.id,x:p.right-150,y:p.bottom})}},onContextMenu:a=>{a.preventDefault(),n({id:t.id,x:a.clientX,y:a.clientY})},children:[be===t.id?i.jsx("input",{className:"chat-session-title-input",value:ue,autoFocus:!0,maxLength:80,onClick:a=>a.stopPropagation(),onChange:a=>ae(a.target.value),onBlur:()=>void Ee(t.id),onKeyDown:a=>{a.stopPropagation(),a.key==="Enter"&&Ee(t.id),a.key==="Escape"&&te(null)}}):i.jsx("span",{className:"chat-session-title",children:t.title}),i.jsx("button",{type:"button",className:"chat-session-menu","aria-label":"Chat actions","aria-haspopup":"menu",title:"Chat actions",onClick:a=>{a.stopPropagation();const p=a.currentTarget.getBoundingClientRect();n({id:t.id,x:p.right-150,y:p.bottom})},children:"⋯"}),i.jsx("button",{type:"button",className:"chat-session-delete","aria-label":"Delete conversation",onClick:a=>{a.stopPropagation(),tt(t.id)},children:i.jsx(Tt,{})})]},t.id))]},e.label))]}),W&&i.jsx("div",{className:"chat-session-context-menu",role:"menu",style:{left:W.x,top:W.y},onClick:e=>e.stopPropagation(),children:i.jsx("button",{type:"button",role:"menuitem",autoFocus:!0,onClick:()=>{const e=x.find(t=>t.id===W.id);e&&(te(e.id),ae(e.title)),n(null)},children:"Rename chat"})})]}),i.jsxs("section",{className:"chat-main",children:[i.jsxs("div",{className:"chat-topbar",children:[!s&&i.jsx("button",{type:"button",className:"icon-btn",onClick:()=>r(!0),title:"Open sidebar",children:i.jsx(qe,{})}),i.jsx("span",{className:"chat-topbar-title",children:Re?(ne==null?void 0:ne.title)||"":ye||(ne==null?void 0:ne.title)||(_e?"":"New chat")}),se&&i.jsx("span",{className:"chat-staging-badge",children:"Staging"}),l&&xe&&(b==null?void 0:b.status)==="loaded"&&!_e&&i.jsxs("button",{type:"button",className:"chat-share-button",onClick:()=>void rt(),disabled:m.busy||o||Re,"aria-label":"Share conversation",children:[o?i.jsx(Be,{}):i.jsx(It,{"aria-hidden":"true"}),i.jsx("span",{children:"Share"})]})]}),Re?i.jsxs("div",{className:"chat-session-loading",role:"status","aria-live":"polite",children:[i.jsx(Be,{}),i.jsx("span",{children:"Loading conversation…"})]}):Ie?i.jsxs("div",{className:"chat-session-load-error",role:"alert",children:[i.jsx("p",{children:Ie}),i.jsx("button",{type:"button",onClick:()=>{U({id:l,status:"loading"}),pe(e=>e+1)},children:"Try again"})]}):_e?i.jsx("div",{className:"chat-empty",children:i.jsxs("div",{className:"chat-empty-inner",children:[i.jsx("div",{className:"chat-empty-eyebrow",children:"AI research assistant · Staging preview"}),i.jsxs("h1",{className:"chat-empty-title",children:["Ask ",i.jsx("em",{children:"Papers With Code"})]}),i.jsx("p",{className:"chat-empty-sub",children:"Answers are grounded in a live hybrid search over papers, tasks, and benchmarks — with citations you can follow."}),se&&i.jsx("p",{className:"chat-staging-access-note",children:"This is a limited staging preview. Only approved Hugging Face users can start chats."}),i.jsx(Xe,{provider:re}),i.jsx(Me,{onSend:oe,busy:m.busy,onStop:m.stop,autoFocus:!0,draft:B,onDraftChange:q,models:Q,selectedModel:N,onModelChange:e=>void Le(e)}),i.jsx("div",{className:"chat-examples",children:jt.map(e=>i.jsx("button",{type:"button",className:"chat-example",onClick:()=>oe(e),children:e},e))})]})}):i.jsxs(i.Fragment,{children:[m.sessionError&&i.jsx("div",{className:"chat-session-error",role:"alert",children:m.sessionError}),i.jsx("div",{className:"chat-conversation",ref:we,children:i.jsx("div",{className:"chat-conversation-inner",children:m.messages.map(e=>e.role==="user"?i.jsx(gt,{id:e.id,text:e.text??"",isInitial:e.id===ve,editingAllowed:!m.busy&&!!e.revision,editing:de===e.id,editNotice:e.id===ve?"Sending will start a new chat.":e.id===ot?"Sending will replace the response.":"Sending will replace the response and all messages after it.",onEdit:()=>ee(e.id),onCancel:()=>ee(null),onResend:t=>{e.id!==ve&&(ce.current=e.id);const a=m.editAndResend(e.id,t);return a?ee(null):ce.current=null,a}},e.id):i.jsx(yt,{msg:e,papers:m.papers,onToggleBlock:it,onArchiveOldChats:()=>void nt(),archivePending:u},e.id))})}),i.jsx("div",{className:"chat-composer-wrap",children:i.jsxs("div",{className:"chat-composer-inner",children:[i.jsx(Xe,{provider:re}),i.jsx(Me,{onSend:oe,busy:m.busy,onStop:m.stop,placeholder:B?"Edit and send again…":"Ask a follow-up…",draft:B,onDraftChange:q,models:Q,selectedModel:N,onModelChange:e=>void Le(e)}),i.jsx("div",{className:"chat-composer-foot",children:me()?i.jsxs(i.Fragment,{children:[re==="openrouter"?i.jsxs("span",{className:"chat-provider-attribution",children:["Powered by ",i.jsx("a",{href:"https://openrouter.ai",target:"_blank",rel:"noreferrer",children:"OpenRouter"}),"."]}):i.jsxs("span",{className:"chat-provider-attribution",children:["Powered by 🤗 ",i.jsx("a",{href:"https://huggingface.co/docs/inference-providers/en/index",target:"_blank",rel:"noreferrer",children:"Inference Providers"}),"."]}),i.jsx("span",{children:"The AI assistant can make mistakes. Double-check responses."})]}):i.jsx(i.Fragment,{children:"Assistant preview — responses are simulated."})})]})})]})]}),g&&i.jsx("div",{className:"chat-share-dialog-backdrop",role:"presentation",onMouseDown:()=>A(""),children:i.jsxs("div",{className:"chat-share-dialog",role:"dialog","aria-modal":"true","aria-labelledby":"chat-share-dialog-title",onMouseDown:e=>e.stopPropagation(),children:[i.jsx("h2",{id:"chat-share-dialog-title",children:"Public link created"}),i.jsx("p",{children:"It could not be copied automatically. Copy this link manually:"}),i.jsx("input",{readOnly:!0,value:g,"aria-label":"Public conversation link",autoFocus:!0,onFocus:e=>e.currentTarget.select()}),i.jsx("button",{type:"button",onClick:()=>A(""),children:"Close"})]})})]})};export{Zt as default}; | |