diff --git "a/assets/ChatView-Cmfq7SkU.js" "b/assets/ChatView-Cmfq7SkU.js" new file mode 100644--- /dev/null +++ "b/assets/ChatView-Cmfq7SkU.js" @@ -0,0 +1,16 @@ +var xt=Object.defineProperty;var Rt=(e,t,n)=>t in e?xt(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var ke=(e,t,n)=>Rt(e,typeof t!="symbol"?t+"":t,n);import{c as St,A as Et,n as Ct,j as r,r as o,X as Tt,d as ft,e as kt,u as Ot,a as It,f as At,g as jt,h as Nt,b as Lt}from"./index-CIcc4W5J.js";import{u as Mt}from"./useQuery-DVhceR1_.js";import{C as Dt,U as rt,A as Pt}from"./ChatMessage-ClmppWXU.js";import{c as Ge}from"./chat-1lcY_4Bq.js";import{u as Ft,r as Yt,a as Ut,O as qt,b as Bt}from"./openrouter-CsC9lVLW.js";import{d as Ht,e as mt,g as Wt,T as Vt,f as pt,h as Gt,i as Kt,j as $t,k as Qt,l as nt,t as gt,r as zt,S as Jt,P as Xt,D as Zt,m as en,C as et,n as Je,o as tn,p as Xe,s as Ze,v as nn,w as rn,x as tt,y as sn}from"./chatSessions-DZULhc8o.js";import{S as an}from"./chatPrompts-CDY3UGU1.js";import"./katex.min-BSBacQyE.js";import"./hover-card-BsP3fLuI.js";import"./github-DJVZN66b.js";import"./github-DKUi50J1.js";import"./PaperPreviewLink-BKRqPUPr.js";import"./index-CqFeb455.js";import"./papers-CrWpvfDB.js";import"./file-text-CHDj8EAn.js";import"./chevron-down-CgZudZot.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 on=St("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"}]]),ee=(e,t)=>new Promise(n=>{const a=setTimeout(s,e);function s(){t==null||t.removeEventListener("abort",s),clearTimeout(a),n()}t==null||t.addEventListener("abort",s)}),_e=e=>({arxiv_id:null,source:"arxiv",source_url:null,thumbnail_url:null,authors:[],published:null,conference:null,citation_count:null,tasks:[],methods:[],repositories:[],project_pages:[],...e}),ve={name:"Object Detection",slug:"object-detection"},Oe={name:"Real-Time Object Detection",slug:"real-time-object-detection"},cn={"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:_e({arxiv_id:"2502.12524",authors:[{name:"Y. Tian"},{name:"Q. Ye"},{name:"D. Doermann"}],published:"2025-02-18",citation_count:412,tasks:[ve,Oe],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:_e({arxiv_id:"2407.17140",authors:[{name:"W. Lv"},{name:"Y. Zhao"},{name:"J. Chang"}],published:"2024-07-24",citation_count:268,tasks:[ve,Oe],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:_e({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:[ve,Oe],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:_e({arxiv_id:"2406.03459",authors:[{name:"Q. Chen"},{name:"X. Su"},{name:"X. Zhang"}],published:"2024-06-05",citation_count:94,tasks:[ve,Oe],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:_e({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:[ve,Oe],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:_e({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:[ve,Oe],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:_e({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"},ve],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:_e({source:"external",source_url:"https://docs.ultralytics.com/models/",authors:[{name:"Ultralytics"}],published:"2025-01-02",tasks:[ve,Oe],repositories:[{url:"https://github.com/ultralytics/ultralytics",stars:46e3}],project_pages:[{url:"https://docs.ultralytics.com"}]})}},yt=e=>e.map(t=>cn[t]),st=yt(["2502.12524","2407.17140","2410.13842","2406.03459","2304.08069","2405.14458","2401.17270","158342"]),at=yt(["2410.13842","2502.12524","2407.17140","2405.14458","2304.08069"]),it="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.",ot="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.",ct=`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.`,ln=["How do these compare on edge devices like Jetson?","Show me open-vocabulary detectors","What about small-object detection?"];async function*un(e,t){const n=()=>(t==null?void 0:t.aborted)===!0,a=e.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 ee(350,t),!n()){yield{type:"reasoning_start"};for(let s=0;s{const t=String("0").trim().toLowerCase();return t==="1"||t==="true"||t==="yes"},dn=()=>!0;class Ne extends Error{constructor(t,n,a,s){super(t),this.code=n,this.status=a,this.retryAfterSeconds=s,this.name="ChatStreamError"}}function hn(e,t){if(Le())try{Ge.reportLatency(e,t).catch(()=>{})}catch{}}function fn(e,t={}){return Le()?pn(e,t.signal):un(e.message,t.signal)}function mn(e,t={}){return gn(e,t.signal)}async function*pn(e,t){const n=await Ge.stream(e,t);yield*bt(n)}async function*gn(e,t){const n=await Ge.resumeStream(e,t);yield*bt(n)}async function*bt(e){if(!e.ok||!e.body){const s=e.ok?null:new Et(e,await e.text());s&&Ct(s);const d=s==null?void 0:s.detail,l=typeof d=="object"&&d!==null?d:null,m=e.status===403&&!d,h=Number(e.headers.get("Retry-After")),x=Number.isFinite(h)&&h>=0?Math.min(300,Math.ceil(h)):void 0;throw new Ne(m?"Chat on staging is limited to approved Hugging Face users. Sign in with an approved account and try again.":(s==null?void 0:s.message)||`Chat stream failed (${e.status})`,l&&"code"in l&&typeof l.code=="string"?l.code:m?"staging_access_required":void 0,e.status,x)}const t=e.body.getReader(),n=new TextDecoder;let a="";try{for(;;){const{done:s,value:d}=await t.read();if(s)break;a+=n.decode(d,{stream:!0});let l;for(;(l=a.indexOf(` + +`))!==-1;){const m=a.slice(0,l);a=a.slice(l+2);const h=m.split(` +`).filter(x=>x.startsWith("data:")).map(x=>x.slice(5).trimStart()).join(` +`);!h||h==="[DONE]"||(yield JSON.parse(h))}}}finally{t.releaseLock()}}const yn="https://huggingface.co/settings/inference-providers",bn="https://paperswithcode.co/chat",lt="pwc.chat.billing-notice-dismissed.v1";function _n({provider:e}){const[t,n]=o.useState(()=>localStorage.getItem(lt)==="1");return!Le()||t||e!=="huggingface"?null:r.jsxs("div",{className:"chat-billing-notice",role:"note",children:[r.jsx("span",{children:"Hugging Face models use the inference permission granted when you start chatting. Included monthly credits are used first, then extra usage requires purchased credits. You can choose organization billing in Settings."}),r.jsxs("div",{className:"chat-billing-notice-actions",children:[r.jsx("a",{href:"/settings",children:"Review billing"}),r.jsx("a",{href:yn,target:"_blank",rel:"noreferrer",children:"Review usage"}),r.jsx("button",{type:"button",className:"chat-billing-notice-dismiss","aria-label":"Dismiss billing notice",title:"Dismiss",onClick:()=>{localStorage.setItem(lt,"1"),n(!0)},children:r.jsx(Tt,{size:15,"aria-hidden":"true"})})]})]})}function vn({enabled:e,fallbackEnabled:t,byokExpected:n}){const a=Ft(e);if(!e||!a.data)return null;const s=a.data,d=Yt(s.resets_at),l=s.unavailable_reason==="staging_funding_disabled",m=s.unavailable_reason==="shared_credits_exhausted"||s.unavailable_reason==="workspace_limit_exhausted"||s.unavailable_reason==="provider_status_unavailable";return r.jsxs("div",{className:"chat-openrouter-usage",role:"status",children:[r.jsx("span",{children:l?r.jsx("strong",{children:"Chat is now live on paperswithcode.co"}):m?r.jsxs(r.Fragment,{children:[r.jsx("strong",{children:"Shared OpenRouter credits unavailable"})," · ",s.remaining_percent,"% of your allowance remains"]}):r.jsxs(r.Fragment,{children:[r.jsxs("strong",{children:[s.remaining_percent,"% left"]})," this month · resets ",d.local]})}),l?r.jsxs("span",{children:[r.jsx("a",{href:s.production_chat_url||bn,children:"Continue on production"}),t&&" · Your connected OpenRouter key remains available on staging."]}):(!s.available||n)&&r.jsx("span",{children:t?"Your connected OpenRouter key will be used on your next explicit send.":r.jsxs(r.Fragment,{children:[r.jsx("a",{href:"/settings#openrouter-byok",children:"Connect your own key in Settings"})," to continue."]})})]})}function ut({variant:e,composerProps:t,provider:n,openRouterFallbackEnabled:a,byokExpected:s,paused:d,suggestions:l=[]}){var h;const m=r.jsxs(r.Fragment,{children:[r.jsx(_n,{provider:n}),r.jsx(vn,{enabled:n==="openrouter",fallbackEnabled:a,byokExpected:s}),d&&r.jsx("div",{id:"chat-paused-description",className:"chat-paused-banner",role:"status",children:"Chat is temporarily disabled. You can keep browsing and editing your conversations. New research runs will return when chat is restored."}),r.jsx(Dt,{...t,...e==="empty"?{autoFocus:!0}:{placeholder:(h=t.draft)!=null&&h.text?"Edit and send again…":"Ask a follow-up…"}}),e==="empty"&&r.jsx("div",{className:"chat-examples",children:l.map(x=>r.jsx("button",{type:"button",className:"chat-example",disabled:d,onClick:()=>t.onSend({text:x,paperMentions:[]}),children:x},x))})]});return e==="empty"?m:r.jsx("div",{className:"chat-composer-wrap",children:r.jsxs("div",{className:"chat-composer-inner",children:[m,r.jsx("div",{className:"chat-composer-foot",children:Le()?r.jsxs(r.Fragment,{children:[n==="openrouter"?r.jsxs("span",{className:"chat-provider-attribution",children:["Powered by ",r.jsx("a",{href:"https://openrouter.ai",target:"_blank",rel:"noreferrer",children:"OpenRouter"}),"."]}):r.jsxs("span",{className:"chat-provider-attribution",children:["Powered by 🤗 ",r.jsx("a",{href:"https://huggingface.co/docs/inference-providers/en/index",target:"_blank",rel:"noreferrer",children:"Inference Providers"}),"."]}),r.jsx("span",{children:"The AI assistant can make mistakes. Double-check responses."})]}):r.jsx(r.Fragment,{children:"Assistant preview — responses are simulated."})})]})})}function wn({messages:e,papers:t,busy:n,queuedDraft:a,paperMentionsEnabled:s,archivePending:d,openRouterFallbackEnabled:l,onToggleBlock:m,onEditAndResend:h,onArchiveOld:x,onArchiveOldest:D}){var g,y;const[_,k]=o.useState(null),H=o.useRef(null),O=o.useRef(null),E=o.useRef(null);o.useEffect(()=>{n?k(null):E.current=null},[n]),o.useLayoutEffect(()=>{const u=H.current;if(u){if(O.current!==null){u.scrollTop=O.current,O.current=null;return}if(E.current){const q=Array.from(u.querySelectorAll("[data-message-id]")).find(C=>C.dataset.messageId===E.current);if(q){const C=u.getBoundingClientRect(),V=q.getBoundingClientRect();u.scrollTop+=V.top-C.top-24;return}}u.scrollTop=u.scrollHeight}},[e]);const S=e.filter(u=>u.role==="user"),F=(g=S[0])==null?void 0:g.id,ne=(y=S.at(-1))==null?void 0:y.id,j=(u,q)=>{var C;O.current=((C=H.current)==null?void 0:C.scrollTop)??null,m(u,q)};return r.jsx("div",{className:"chat-conversation",ref:H,children:r.jsxs("div",{className:"chat-conversation-inner",children:[e.length===0&&(a==null?void 0:a.text)&&r.jsx(rt,{id:"queued-launch-preview",text:a.text,paperMentions:a.paperMentions,isInitial:!0}),e.map(u=>u.role==="user"?r.jsx(rt,{id:u.id,text:u.text??"",paperMentions:u.paperMentions??[],paperMentionsEnabled:s,isInitial:u.id===F,editingAllowed:!n&&!!u.revision,editing:_===u.id,editNotice:u.id===F?"Sending will replace this conversation.":u.id===ne?"Sending will replace the response.":"Sending will replace the response and all messages after it.",onEdit:()=>k(u.id),onCancel:()=>k(null),onResendDraft:q=>{u.id!==F&&(E.current=u.id);const C=h(u.id,q);return C?k(null):E.current=null,C}},u.id):r.jsx(Pt,{msg:u,papers:t,onToggleBlock:j,onArchiveOldChats:x,onArchiveOldestChats:D,archivePending:d,hfBilling:null,openRouterFallbackEnabled:l,feedbackEnabled:!0},u.id))]})})}function xn({retryAt:e,onRetry:t,onCancel:n}){const[a,s]=o.useState(()=>Math.max(0,Math.ceil((e-Date.now())/1e3))),d=o.useRef(null);return o.useEffect(()=>{var x;const l=document.activeElement instanceof HTMLElement?document.activeElement:null;(x=d.current)==null||x.focus();const m=()=>s(Math.max(0,Math.ceil((e-Date.now())/1e3)));m();const h=window.setInterval(m,250);return()=>{window.clearInterval(h),l==null||l.focus()}},[e]),r.jsx("div",{className:"chat-capacity-dialog-backdrop",role:"presentation",children:r.jsxs("div",{className:"chat-capacity-dialog",role:"dialog","aria-modal":"true","aria-labelledby":"chat-capacity-dialog-title","aria-describedby":"chat-capacity-dialog-description",onKeyDown:l=>{l.key==="Escape"&&(l.preventDefault(),n())},children:[r.jsx("h2",{id:"chat-capacity-dialog-title",children:"All research slots are currently in use"}),r.jsx("p",{id:"chat-capacity-dialog-description",children:"Your message was not sent or billed. Try again in a few seconds."}),r.jsx("p",{className:"chat-capacity-countdown","aria-live":"polite",children:a>0?`Try again available in ${a} second${a===1?"":"s"}.`:"You can try again now."}),r.jsxs("div",{className:"chat-capacity-dialog-actions",children:[r.jsx("button",{type:"button",className:"chat-capacity-cancel",ref:d,onClick:n,children:"Cancel"}),r.jsx("button",{type:"button",className:"chat-capacity-retry",disabled:a>0,onClick:t,children:"Try again"})]})]})})}function Rn({onClose:e}){const t=o.useRef(null);return o.useEffect(()=>{var a;const n=document.activeElement instanceof HTMLElement?document.activeElement:null;return(a=t.current)==null||a.focus(),()=>n==null?void 0:n.focus()},[]),r.jsx("div",{className:"chat-capacity-dialog-backdrop",role:"presentation",children:r.jsxs("div",{className:"chat-capacity-dialog",role:"dialog","aria-modal":"true","aria-labelledby":"chat-disabled-title","aria-describedby":"chat-disabled-description",onKeyDown:n=>{n.key==="Escape"&&(n.preventDefault(),e())},children:[r.jsx("h2",{id:"chat-disabled-title",children:"Chat is temporarily disabled"}),r.jsx("p",{id:"chat-disabled-description",children:"We've temporarily paused new research runs. Your message wasn't sent, and your draft is still here. Please try again later."}),r.jsx("div",{className:"chat-capacity-dialog-actions",children:r.jsx("button",{ref:t,type:"button",className:"chat-capacity-cancel",onClick:e,children:"Keep editing"})})]})})}function Sn({url:e,onClose:t}){return e?r.jsx("div",{className:"chat-share-dialog-backdrop",role:"presentation",onMouseDown:t,children:r.jsxs("div",{className:"chat-share-dialog",role:"dialog","aria-modal":"true","aria-labelledby":"chat-share-dialog-title",onMouseDown:n=>n.stopPropagation(),children:[r.jsx("h2",{id:"chat-share-dialog-title",children:"Public link created"}),r.jsx("p",{children:"Anyone with this link can see this conversation. It could not be copied automatically, so copy it manually:"}),r.jsx("input",{readOnly:!0,value:e,"aria-label":"Public conversation link",autoFocus:!0,onFocus:n=>n.currentTarget.select()}),r.jsx("button",{type:"button",onClick:t,children:"Close"})]})}):null}function En({sessions:e,activeSessionId:t,loading:n,error:a,open:s,onClose:d,onNew:l,onNavigate:m,onRename:h,onDelete:x}){const[D,_]=o.useState(null),[k,H]=o.useState(""),[O,E]=o.useState(null);o.useEffect(()=>{if(!O)return;const j=()=>E(null),g=y=>{y.key==="Escape"&&j()};return window.addEventListener("click",j),window.addEventListener("keydown",g),()=>{window.removeEventListener("click",j),window.removeEventListener("keydown",g)}},[O]);const S=j=>{_(j.id),H(j.title)},F=async j=>{const g=k.trim();g&&await h(j,g)&&_(null)},ne=(j,g,y)=>E({id:j,x:g,y});return r.jsxs("aside",{className:`chat-sidebar${s?"":" chat-sidebar-closed"}`,children:[r.jsxs("div",{className:"chat-sidebar-top",children:[r.jsxs("button",{type:"button",className:"chat-new-chat",onClick:l,children:[r.jsx(Ht,{})," New chat"]}),r.jsx("button",{type:"button",className:"icon-btn",onClick:d,title:"Collapse sidebar",children:r.jsx(mt,{})})]}),r.jsxs("nav",{className:"chat-sessions","aria-label":"Chat history",children:[n&&r.jsx("div",{className:"chat-sessions-empty",children:"Loading chats…"}),!n&&a&&r.jsx("div",{className:"chat-sessions-empty",children:a}),!n&&!a&&e.length===0&&r.jsx("div",{className:"chat-sessions-empty",children:"Conversations you start will show up here."}),Wt(e).map(j=>r.jsxs("div",{className:"chat-session-group",children:[r.jsx("div",{className:"chat-session-group-label",children:j.label}),j.items.map(g=>r.jsxs("div",{className:`chat-session${g.id===t?" chat-session-active":""}`,role:"button",tabIndex:0,onClick:()=>m(g.id),onKeyDown:y=>{if(y.key==="Enter"&&m(g.id),y.key==="F2"&&S(g),y.key==="ContextMenu"||y.shiftKey&&y.key==="F10"){y.preventDefault();const u=y.currentTarget.getBoundingClientRect();ne(g.id,u.right-150,u.bottom)}},onContextMenu:y=>{y.preventDefault(),ne(g.id,y.clientX,y.clientY)},children:[D===g.id?r.jsx("input",{className:"chat-session-title-input",value:k,autoFocus:!0,maxLength:80,onClick:y=>y.stopPropagation(),onChange:y=>H(y.target.value),onBlur:()=>void F(g.id),onKeyDown:y=>{y.stopPropagation(),y.key==="Enter"&&F(g.id),y.key==="Escape"&&_(null)}}):r.jsx("span",{className:"chat-session-title",children:g.title}),r.jsx("button",{type:"button",className:"chat-session-menu","aria-label":"Chat actions","aria-haspopup":"menu",title:"Chat actions",onClick:y=>{y.stopPropagation();const u=y.currentTarget.getBoundingClientRect();ne(g.id,u.right-150,u.bottom)},children:"⋯"}),r.jsx("button",{type:"button",className:"chat-session-delete","aria-label":"Delete conversation",onClick:y=>{y.stopPropagation(),x(g.id)},children:r.jsx(Vt,{})})]},g.id))]},j.label))]}),O&&r.jsx("div",{className:"chat-session-context-menu",role:"menu",style:{left:O.x,top:O.y},onClick:j=>j.stopPropagation(),children:r.jsx("button",{type:"button",role:"menuitem",autoFocus:!0,onClick:()=>{const j=e.find(g=>g.id===O.id);j&&S(j),E(null)},children:"Rename chat"})})]})}function Cn({sessionId:e,busy:t,loading:n,onError:a}){const{toast:s}=ft(),[d,l]=o.useState(!1),[m,h]=o.useState(""),x=async()=>{var D;if(!(t||d)){l(!0);try{const _=await Gt(e),k=new URL(_.public_path,window.location.origin).toString();try{if(!((D=navigator.clipboard)!=null&&D.writeText))throw new Error("Clipboard unavailable");await navigator.clipboard.writeText(k),s({className:"chat-share-toast",duration:5e3,title:"Public link copied to your clipboard",description:"Anyone with this link can see this conversation."})}catch{h(k)}}catch(_){const k=_ instanceof Error?_.message:"Could not share this conversation";a(k),s({variant:"destructive",title:"Share failed",description:k})}finally{l(!1)}}};return r.jsxs(r.Fragment,{children:[r.jsxs("button",{type:"button",className:"chat-share-button",onClick:()=>void x(),disabled:t||d||n,"aria-label":"Share conversation",children:[d?r.jsx(pt,{}):r.jsx(on,{"aria-hidden":"true"}),r.jsx("span",{children:"Share"})]}),r.jsx(Sn,{url:m,onClose:()=>h("")})]})}function Tn({messages:e,refreshSessions:t,resetChat:n,restoreDraft:a,clearTitle:s}){const{toast:d}=ft(),[l,m]=o.useState(null),h=()=>{const _=[...e].reverse().find(k=>k.role==="user");n(),a({text:(_==null?void 0:_.text)??"",paperMentions:(_==null?void 0:_.paperMentions)??[]}),s()};return{pending:l,archiveOld:async()=>{if(l===null){m("old");try{const _=await $t();if(await t(),_.archived_count===0){d({title:"No chats were archived",description:"There are no inactive chats older than 30 days."});return}h(),d({title:`${_.archived_count} ${_.archived_count===1?"chat":"chats"} archived`,description:"Your question is ready to send again."})}catch(_){d({variant:"destructive",title:"Could not archive old chats",description:_ instanceof Error?_.message:"Try again."})}finally{m(null)}}},archiveOldest:async()=>{if(l===null){m("oldest");try{const _=await Kt();await t(),h(),d({title:`${_.archived_count} ${_.archived_count===1?"chat":"chats"} archived`,description:"Your question is ready to send again."})}catch(_){d({variant:"destructive",title:"Could not archive chats",description:_ instanceof Error?_.message:"Try again."})}finally{m(null)}}}}}class kn{constructor(t,n=hn){ke(this,"requestId");ke(this,"firstVisibleAt");ke(this,"streamStartReported",!1);ke(this,"firstVisibleReported",!1);ke(this,"terminalReported",!1);ke(this,"semanticReported",new Set);this.submittedAt=t,this.report=n}recordStreamStart(t,n){this.requestId=t,this.streamStartReported||(this.streamStartReported=!0,this.send({submission_to_stream_start_ms:Math.max(0,n-this.submittedAt)})),this.reportFirstVisible()}recordFirstVisible(t){this.firstVisibleAt===void 0&&(this.firstVisibleAt=t,this.reportFirstVisible())}recordSemantic(t,n){if(this.semanticReported.has(t))return;this.semanticReported.add(t);const a=Math.max(0,n-this.submittedAt);this.send(t==="reasoning"?{submission_to_first_reasoning_delta_ms:a}:t==="tool"?{submission_to_first_tool_call_ms:a}:{submission_to_first_answer_delta_ms:a})}recordTerminal(t){this.terminalReported||(this.terminalReported=!0,this.send({terminal_classification:t}))}reportFirstVisible(){!this.requestId||this.firstVisibleAt===void 0||this.firstVisibleReported||(this.firstVisibleReported=!0,this.send({submission_to_first_visible_delta_ms:Math.max(0,this.firstVisibleAt-this.submittedAt)}))}send(t){this.requestId&&this.report(this.requestId,t)}}const _t="Preparing research workspace…",vt={preparing_workspace:"Preparing secure workspace…",starting_agent:"Starting research agent…",connecting_model:"Connecting to model…"},wt=()=>({messages:[],sessionId:null,title:"",phase:"idle"});function dt(e,t){for(let n=e.length-1;n>=0;n-=1)if(t(e[n]))return n;return-1}function Ve(e){if(e.status!==_t&&!Object.values(vt).includes(e.status))return e;const{status:t,...n}=e;return n}function te(e,t){if(!e.length)return e;const n=e.slice();return n[n.length-1]=t(n[n.length-1]),n}function ht(e,t,n){return te(e,a=>{const s=Ve(a),d=s.blocks??[];return{...s,blocks:d.map((l,m)=>t(l,m,d)?n(l):l)}})}function On(e,t){switch(t.type){case"stream_start":return t.session_id?{...e,sessionId:t.session_id}:e;case"sandbox_start":case"sandbox_ready":case"workspace_ready":return e;case"lifecycle":return{...e,messages:te(e.messages,n=>{var a;return n.role==="assistant"&&n.streaming&&(((a=n.blocks)==null?void 0:a.length)??0)===0?{...n,status:vt[t.phase]}:n})};case"session_title_start":return{...e,title:""};case"session_title_delta":return{...e,title:`${e.title}${t.text}`.replace(/\s+/g," ").slice(0,80)};case"session_title_done":return{...e,title:t.title};case"reasoning_start":return{...e,messages:te(e.messages,n=>{const a=Ve(n);return{...a,blocks:[...(a.blocks??[]).map(s=>s.kind==="reasoning"&&s.active?{...s,active:!1,open:!1}:s),{kind:"reasoning",text:"",active:!0,open:!0}]}})};case"reasoning_delta":return{...e,messages:ht(e.messages,(n,a,s)=>n.kind==="reasoning"&&dt(s,d=>d.kind==="reasoning")===a,n=>n.kind==="reasoning"?{...n,text:n.text+t.text}:n)};case"reasoning_end":return{...e,messages:te(e.messages,n=>{const a=n.blocks??[],s=dt(a,m=>m.kind==="reasoning"&&m.active);if(s<0)return n;const d=a[s];if(d.kind!=="reasoning")return n;const l=a[s-1];return(l==null?void 0:l.kind)==="reasoning"&&l.text===d.text?{...n,blocks:a.filter((m,h)=>h!==s)}:{...n,blocks:a.map((m,h)=>h===s?{...d,active:!1,open:!1}:m)}})};case"tool_call":return{...e,messages:te(e.messages,n=>{const a=Ve(n);return{...a,blocks:[...a.blocks??[],{kind:"tool",id:t.id,name:t.name,args:t.args,status:"running",open:!1}]}})};case"tool_result":return{...e,messages:ht(e.messages,n=>n.kind==="tool"&&n.id===t.id,n=>n.kind!=="tool"?n:t.status?{...n,schema_version:2,status:t.status,took_ms:t.took_ms,content:t.content,metadata:t.metadata,open:t.status!=="success"}:{...n,status:"done",hits:t.hits,took_ms:t.took_ms,results:t.results})};case"answer_delta":return{...e,messages:te(e.messages,n=>{const a=Ve(n),s=a.blocks??[],d=s.at(-1);return(d==null?void 0:d.kind)==="answer"&&!d.done?{...a,blocks:[...s.slice(0,-1),{...d,text:d.text+t.text}]}:{...a,blocks:[...s,{kind:"answer",text:t.text,done:!1}]}})};case"done":return{...e,phase:"complete",messages:te(e.messages,n=>({...n,streaming:!1,followups:t.followups,finishReason:t.finish_reason,citations:t.citations,blocks:(n.blocks??[]).map(a=>a.kind==="answer"?{...a,done:!0}:a.kind==="reasoning"&&a.active?{...a,active:!1,open:!1}:a)}))};case"error":return{...e,phase:"failed",messages:te(e.messages,n=>({...n,streaming:!1,error:t.message,errorCode:t.code,blocks:(n.blocks??[]).map(a=>a.kind==="reasoning"&&a.active?{...a,active:!1,open:!1}:a)}))}}}function In(e){return te(e,t=>{if(t.role!=="assistant")return t;const n=(t.blocks??[]).flatMap(a=>a.kind==="tool"&&a.status==="running"?[]:a.kind==="reasoning"&&a.active?a.text?[{...a,active:!1,open:!1}]:[]:a.kind==="answer"?[{...a,done:!0}]:[a]);return{...t,blocks:n,streaming:!1,finishReason:"stopped"}})}function He(e,t){switch(t.type){case"start":return{messages:t.messages,sessionId:t.sessionId,title:"",phase:"streaming"};case"event":return On(e,t.event);case"load":return{messages:t.messages,sessionId:t.sessionId,title:e.title,phase:"idle"};case"workspace_status":return{...e,messages:te(e.messages,n=>{var a;return n.role==="assistant"&&n.streaming&&(((a=n.blocks)==null?void 0:a.length)??0)===0&&!n.error?{...n,status:_t}:n})};case"clear_workspace_status":return{...e,messages:te(e.messages,Ve)};case"settle":return{...e,phase:"idle",messages:te(e.messages,n=>n.streaming?{...n,streaming:!1}:n)};case"stop":return{...e,messages:In(e.messages),phase:"stopped"};case"reset":return wt()}}const we={minDelayMs:5,maxDelayMs:80,minRateCharsPerMs:.3,maxBufferedMs:400,arrivalRateTauMs:1e3,arrivalRateHeadroom:1.1,maxPendingChars:64},An={now:()=>performance.now(),sleep:(e,t)=>new Promise(n=>{if(t!=null&&t.aborted||e<=0){n();return}const a=window.setTimeout(s,e);function s(){t==null||t.removeEventListener("abort",s),window.clearTimeout(a),n()}t==null||t.addEventListener("abort",s,{once:!0})})};function jn(e){return!["stream_start","sandbox_start","sandbox_ready","workspace_ready","session_title_start","session_title_delta","session_title_done"].includes(e.type)}function Nn(e,t=!1,n=we.maxPendingChars){var s;if(!e)return{pieces:[],pending:""};if(t)return{pieces:[e],pending:""};const a=Intl.Segmenter;if(a){const l=[...new a(void 0,{granularity:"word"}).segment(e)].filter(h=>h.isWordLike);let m=0;if(l.length>1&&(m=l.at(-1).index),l.length&&/\s$/u.test(e)&&(m=e.length),m>0){const h=e.slice(0,m),x=[],_=[...new a(void 0,{granularity:"word"}).segment(h)].filter(k=>k.isWordLike);for(let k=0;k<_.length;k+=1){const H=k===0?0:_[k].index,O=((s=_[k+1])==null?void 0:s.index)??h.length;O>H&&x.push(h.slice(H,O))}return _.length||x.push(h),{pieces:x,pending:e.slice(m)}}}else{const d=[...e.matchAll(/\s+/gu)];if(d.length){const l=[];let m=0;for(const h of d){const x=h.index+h[0].length;l.push(e.slice(m,x)),m=x}return{pieces:l,pending:e.slice(m)}}}return e.length>=n?{pieces:[e.slice(0,n)],pending:e.slice(n)}:{pieces:[],pending:e}}function Ln(e,t={}){const n={minDelayMs:t.minDelayMs??we.minDelayMs,maxDelayMs:t.maxDelayMs??we.maxDelayMs,minRateCharsPerMs:t.minRateCharsPerMs??we.minRateCharsPerMs,maxBufferedMs:t.maxBufferedMs??we.maxBufferedMs,arrivalRateTauMs:t.arrivalRateTauMs??we.arrivalRateTauMs,arrivalRateHeadroom:t.arrivalRateHeadroom??we.arrivalRateHeadroom,maxPendingChars:t.maxPendingChars??we.maxPendingChars},a=t.clock??An,s=[];let d="",l=null,m=0,h=!0,x=!1,D=null,_=0,k=a.now();const H=()=>{D==null||D(),D=null},O=(g,y)=>{const u=g.type==="reasoning_delta"||g.type==="answer_delta"?g.text.length:0;s.push({kind:"event",event:g,arrivedAt:y,chars:u}),H()},E=g=>{if(!l||!d)return;const y=Nn(d,g,n.maxPendingChars);for(const u of y.pieces)u&&O({type:l,text:u},m),m=a.now();d=y.pending,d||(l=null)},S=g=>{if(!h)return;const y=a.now();if(g.type==="reasoning_delta"||g.type==="answer_delta"){const u=g.type;if(!g.text)return;l&&l!==u&&E(!0),l||(l=u,m=y),d+=g.text;const q=Math.max(0,y-k);for(_*=Math.exp(-q/n.arrivalRateTauMs),_+=g.text.length,k=y,E(!1);d.length>=n.maxPendingChars;)E(!1);return}jn(g)&&E(!0),O(g,y)},F=(async()=>{var g;try{for await(const y of e)S(y);h&&E(!0)}catch(y){h&&!((g=t.signal)!=null&&g.aborted)&&(E(!0),s.push({kind:"error",error:y,arrivedAt:a.now(),chars:0}))}finally{x=!0,H()}})(),ne=()=>s.length||x?Promise.resolve():new Promise(g=>{D=g});return{events:async function*(){var y,u,q,C;let g=Number.NEGATIVE_INFINITY;try{for(;;){if(await ne(),!s.length){if(x||!h)return;continue}const V=s[0];if(V.kind==="error")throw s.shift(),V.error;if(V.chars&&!((y=t.isHidden)!=null&&y.call(t))){const Y=a.now(),A=s.reduce((J,ge)=>J+ge.chars,0),xe=((u=s.find(J=>J.chars))==null?void 0:u.arrivedAt)??Y,Ie=Math.max(0,n.maxBufferedMs-(Y-xe)),P=_*Math.exp(-Math.max(0,Y-k)/n.arrivalRateTauMs)/n.arrivalRateTauMs,K=Ie>0?A/Ie:Number.POSITIVE_INFINITY,$=Math.max(n.minRateCharsPerMs,P*n.arrivalRateHeadroom,K),he=Math.min(n.maxDelayMs,Math.max(n.minDelayMs,V.chars/$)),ae=Math.max(0,V.arrivedAt+n.maxBufferedMs-Y),Q=Math.max(V.arrivedAt,g+Math.min(he,ae));if(await a.sleep(Math.max(0,Q-a.now()),t.signal),!h||(q=t.signal)!=null&&q.aborted)return}s.shift(),g=a.now(),yield V.event}}finally{h&&(h=!1,H(),await((C=e.return)==null?void 0:C.call(e,void 0))),await F}}(),takeAcceptedForStop(){var y;if(!h)return[];h=!1,l&&d&&(O({type:l,text:d},m),d="",l=null);const g=s.flatMap(u=>u.kind==="event"&&u.event.type!=="done"&&u.event.type!=="error"?[u.event]:[]);return s.length=0,H(),(y=e.return)==null||y.call(e,void 0),g}}}const Mn=750;function Dn(e,t){for(let n=e.length-1;n>=0;n-=1)if(t(e[n]))return n;return-1}function We(e){const t=o.useRef(e);return o.useLayoutEffect(()=>{t.current=e}),o.useCallback((...n)=>t.current(...n),[])}function Pn(e){const[t,n]=o.useState([]),[a,s]=o.useState(!1),[d,l]=o.useState(""),m=o.useRef(!1),h=o.useRef(null),x=o.useRef(null),D=o.useRef(null),_=o.useRef(null),k=o.useRef(!1),H=o.useRef(null),O=o.useRef(null),E=o.useRef("cleared"),S=o.useRef(null),F=o.useRef(null),[ne,j]=o.useState(null),[g,y]=o.useState(null),u=o.useRef([]),q=o.useRef(wt()),C=o.useRef(null),V=o.useRef(null),Y=o.useRef(!1),A=o.useRef(e),xe=o.useRef({text:"",paperMentions:[]}),Ie=o.useRef(0),P=o.useRef(0),K=o.useRef(e.sessionId),$=o.useRef(e.sessionId);$.current!==e.sessionId&&($.current=e.sessionId,K.current!==e.sessionId&&(P.current+=1,S.current=null)),A.current=e,u.current=t,o.useEffect(()=>()=>{var c;O.current!==null&&window.clearTimeout(O.current),(c=h.current)==null||c.abort(),x.current=null,D.current!==null&&cancelAnimationFrame(D.current),_.current!==null&&window.clearTimeout(_.current),F.current=null},[]),o.useEffect(()=>{m.current||(K.current=e.sessionId)},[e.sessionId]),o.useEffect(()=>{const c=m.current&&e.sessionId===K.current?C.current:null;Y.current=c!==null,c&&(n(c),u.current=c)},[e.sessionId]);const he=o.useMemo(()=>{const c={};for(const v of t)for(const R of v.blocks??[])if(R.kind==="tool")for(const p of R.results??[])c[p.route_id]=p;return c},[t]),ae=()=>`m${++Ie.current}_${Date.now().toString(36)}`,Q=(c,v=!0)=>{const R={...q.current,messages:C.current??u.current,sessionId:K.current},p=He(R,c);q.current=p,C.current&&(C.current=p.messages);const b=c.type==="event"&&c.event.type==="stream_start"?c.event.session_id:null;return b?(K.current=b,A.current.onSessionId(b)):p.sessionId&&p.sessionId!==R.sessionId&&(K.current=p.sessionId,A.current.onSessionId(p.sessionId)),p.title!==R.title&&A.current.onTitle(p.title),v&&(u.current=p.messages,n(p.messages)),p},J=()=>V.current===P.current||Y.current,ge=()=>{D.current!==null&&(cancelAnimationFrame(D.current),D.current=null),_.current!==null&&(window.clearTimeout(_.current),_.current=null)},Z=()=>{ge(),document.visibilityState!=="hidden"&&(!Y.current||!C.current||(k.current=!1,u.current=C.current,n(C.current)))},Re=()=>{if(!Y.current||document.visibilityState==="hidden"||D.current!==null||_.current!==null)return;const c=()=>{D.current=null,_.current=null,Z()};typeof requestAnimationFrame=="function"?D.current=requestAnimationFrame(c):_.current=window.setTimeout(c,0)};o.useEffect(()=>{const c=()=>{document.visibilityState==="visible"&&k.current&&Re()};return document.addEventListener("visibilitychange",c),()=>document.removeEventListener("visibilitychange",c)});const ie=c=>{if(h.current!==c||(O.current!==null&&(window.clearTimeout(O.current),O.current=null),E.current==="cleared"))return;const v=E.current==="shown";E.current="cleared",v&&Q({type:"clear_workspace_status"},J())},Ke=(c,v)=>{O.current!==null&&window.clearTimeout(O.current),E.current="armed",O.current=window.setTimeout(()=>{O.current=null,!(E.current!=="armed"||h.current!==c||c.signal.aborted||P.current!==v)&&(E.current="shown",Q({type:"workspace_status"},J()))},Mn)},Me=(c,v)=>{const R=S.current;!R||R.controller!==c||R.tracker.recordStreamStart(v,performance.now())},Se=(c,v)=>{const R=S.current;!R||R.controller!==c||R.tracker.recordTerminal(v)};o.useLayoutEffect(()=>{const c=S.current;if(!c)return;const v=t.at(-1);if((v==null?void 0:v.role)!=="assistant"||!(v.blocks??[]).some(b=>b.kind==="tool"||b.kind==="reasoning"&&!!b.text.trim()||b.kind==="answer"&&!!b.text.trim()))return;const p=performance.now();c.tracker.recordFirstVisible(p);for(const b of v.blocks??[])b.kind==="reasoning"&&b.text.trim()?c.tracker.recordSemantic("reasoning",p):b.kind==="tool"?c.tracker.recordSemantic("tool",p):b.kind==="answer"&&b.text.trim()&&c.tracker.recordSemantic("answer",p)},[t]);const ye=(c,v=!0)=>{Q({type:"event",event:c},v)},De=async(c,v)=>{var b;const R=await nt(c);let p=gt(R);return((b=H.current)==null?void 0:b.sessionId)===c&&(p=H.current.messages,H.current=null),P.current!==v&&!(V.current===v&&Y.current&&A.current.sessionId===c)?null:(n(p),u.current=p,C.current=p,q.current=He(q.current,{type:"load",messages:p,sessionId:c}),p)},Ee=(c,v,R,p,b,M)=>{const N=++P.current;V.current=N,Y.current=!0,m.current=!0;const I=new AbortController;h.current=I;const oe=c.text;return xe.current=c,K.current=v.session_id,l(""),n(R),C.current=R,q.current=He(q.current,{type:"start",messages:R,sessionId:v.session_id}),s(!0),S.current=M?null:{controller:I,tracker:new kn(performance.now())},E.current="cleared",(async()=>{var Ae,Ye,je,Ue;let me=!1,G=!1,se=!1,ce=!1,le=!1,pe=!1;try{const B=M?mn(M,{signal:I.signal}):fn(v,{signal:I.signal}),z=!M&&Le()&&dn(),X=z?Ln(B,{signal:I.signal,isHidden:()=>document.visibilityState==="hidden"}):null;X&&(x.current={controller:I,stream:X});for await(const L of(X==null?void 0:X.events)??B){L.type==="stream_start"&&(me=!0,G=L.provider_execution!==!1,Me(I,L.request_id)),L.type==="sandbox_start"&&Ke(I,N),L.type==="lifecycle"&&ie(I),(L.type==="reasoning_start"||L.type==="reasoning_delta"||L.type==="tool_call"||L.type==="answer_delta"||L.type==="done"||L.type==="error")&&ie(I),(L.type==="done"||L.type==="error")&&(ce=!0,le=L.type==="error",Se(I,L.type==="error"?"error":"complete"),L.type==="error"&&["openrouter_monthly_budget_exhausted","openrouter_unavailable","openrouter_byok_credential_invalid","openrouter_byok_billing_error","openrouter_byok_rate_limit","hf_inference_billing_exhausted"].includes(L.code??"")&&(se=!0,A.current.onInterrupted(c)));const Te=J(),qe=Te&&!(z&&document.visibilityState==="hidden"),Qe=L.type==="reasoning_delta"||L.type==="answer_delta",ze=!["stream_start","sandbox_start","sandbox_ready","workspace_ready","session_title_start","session_title_delta","session_title_done","reasoning_delta","answer_delta"].includes(L.type);z&&ze&&Z(),!I.signal.aborted&&(Te||L.type==="stream_start"||L.type==="session_title_start"||L.type==="session_title_delta"||L.type==="session_title_done")?z&&Qe?(ye(L,!1),k.current=k.current||Te,Re()):(ye(L,qe),z&&Te&&!qe&&(k.current=!0)):I.signal.aborted||ye(L,!1)}}catch(B){if(le=!0,!I.signal.aborted){if(ie(I),B instanceof Ne&&B.code==="chat_temporarily_disabled")pe=!0,y({question:oe,draft:c}),P.current===N&&(n(p),u.current=p,l(""));else if(B instanceof Ne&&B.code==="chat_capacity"){pe=!0;const z=B.retryAfterSeconds??5,X={question:oe,draft:c,request:v,optimistic:R,original:p,edit:b,retryAfterSeconds:z,retryAt:Date.now()+z*1e3};F.current=X,j({question:oe,draft:c,retryAt:X.retryAt,retryAfterSeconds:z}),P.current===N&&(n(p),u.current=p,l(""))}else Se(I,"network_error"),B instanceof Ne&&["paper_context_unavailable","paper_mention_unavailable","paper_mentions_disabled","chat_storage_quota_exceeded"].includes(B.code??"")&&(pe=!0,A.current.onInterrupted(c),P.current===N&&(n(p),u.current=p,l(B.message))),B instanceof Ne&&["openrouter_monthly_budget_exhausted","openrouter_unavailable","openrouter_byok_credential_invalid","openrouter_byok_billing_error","openrouter_byok_rate_limit","hf_inference_billing_exhausted"].includes(B.code??"")&&(se=!0,A.current.onInterrupted(c));!pe&&P.current===N&&ye({type:"error",message:B instanceof Error?B.message:"The assistant stream failed.",code:B instanceof Ne?B.code:void 0})}}finally{if(h.current===I){if(((Ae=x.current)==null?void 0:Ae.controller)===I&&(Z(),x.current=null),ie(I),!ce&&!I.signal.aborted&&Se(I,"network_error"),m.current=!1,s(!1),pe)A.current.onSettled(v.session_id);else if(!I.signal.aborted){(me&&G||se)&&((je=(Ye=A.current).onProviderTerminal)==null||je.call(Ye));const B=K.current;if(b&&!me)P.current===N&&(n(b.snapshot),u.current=b.snapshot,l("Couldn’t resend this message. Your original conversation was restored."));else if(B){P.current===N&&b&&(le||!ce)&&(n(b.snapshot),u.current=b.snapshot);try{const z=await De(B,N);z&&b&&z.some(X=>X.id===b.targetId)&&l("Couldn’t resend this message. Your original conversation was restored.")}catch{P.current===N&&Q({type:"settle"})}}else P.current===N&&Q({type:"settle"});A.current.onSettled(B)}((Ue=S.current)==null?void 0:Ue.controller)===I&&(S.current=null)}}})(),!0},re=We(c=>{const v=typeof c=="string"?{text:c.trim(),paperMentions:[]}:c,R=v.text;if(!R||R.length>8e3||m.current||F.current)return!1;const p=u.current,b=[...p].reverse().find(G=>G.role==="user"),M=b!=null&&b.status&&b.status!=="complete"&&b.revision?{replace_message_id:b.id,prior_revision:b.revision}:null,N={id:ae(),role:"user",text:R,paperMentions:v.paperMentions},I={id:ae(),role:"assistant",streaming:!0,blocks:[]},oe=M&&b?Dn(p,G=>G.id===b.id):-1,me=oe<0?[...p,N,I]:[...p.slice(0,oe),N,I];return Ee(v,{message:R,paper_mentions:v.paperMentions.map(({route_id:G,title:se,start:ce,end:le})=>({route_id:G,title:se,start:ce,end:le})),session_id:A.current.sessionId,client_message_id:crypto.randomUUID(),web_search_enabled:!!A.current.webSearchEnabled,reasoning_effort:A.current.reasoningEffort??"low",...!A.current.sessionId&&A.current.initialModel?{initial_model:A.current.initialModel}:{},...M??{}},me,p)}),be=We((c,v)=>{const R=typeof v=="string"?{text:v.trim(),paperMentions:[]}:v,p=R.text;if(!p||p.length>8e3||m.current||F.current)return!1;const b=u.current.slice(),M=b.findIndex(G=>G.id===c&&G.role==="user");if(M<0)return!1;const N=b[M];if(!A.current.sessionId||!N.revision)return!1;const I={id:N.id,role:"user",text:p,paperMentions:R.paperMentions,revision:N.revision+1,status:"generating"},oe={id:ae(),role:"assistant",streaming:!0,blocks:[]},me=[...b.slice(0,M),I,oe];return Ee(R,{message:p,paper_mentions:R.paperMentions.map(({route_id:G,title:se,start:ce,end:le})=>({route_id:G,title:se,start:ce,end:le})),session_id:A.current.sessionId,client_message_id:crypto.randomUUID(),web_search_enabled:!!A.current.webSearchEnabled,reasoning_effort:A.current.reasoningEffort??"low",replace_message_id:N.id,prior_revision:N.revision},me,b,{targetId:N.id,snapshot:b})}),Pe=o.useCallback(()=>{F.current=null,j(null)},[]),Ce=We(()=>{const c=F.current;return!c||Date.now(){var M,N;if(!h.current)return;const c=h.current;ie(c),Se(c,"stopped"),c.abort();const v=((M=x.current)==null?void 0:M.controller)===c?x.current.stream.takeAcceptedForStop():[];x.current=null;for(const I of v)ye(I,!1);Z(),h.current=null,((N=S.current)==null?void 0:N.controller)===c&&(S.current=null),m.current=!1,s(!1);const R=Q({type:"stop"},!1).messages;C.current=R,u.current=R,n(R),A.current.onInterrupted(xe.current);const p=K.current;p&&(H.current={sessionId:p,messages:R}),p&&Qt(p).catch(()=>{});const b=++P.current;window.setTimeout(()=>{p&&P.current===b?De(p,b).catch(()=>{}).finally(()=>A.current.onSettled(p)):p||A.current.onSettled(null)},450)}),T=o.useCallback((c,v)=>n(R=>R.map(p=>{var b;return p.id!==c?p:{...p,blocks:(b=p.blocks)==null?void 0:b.map((M,N)=>N===v&&(M.kind==="reasoning"||M.kind==="tool")?{...M,open:!M.open}:M)}})),[]),$e=o.useCallback(()=>{var c;P.current+=1,O.current!==null&&(window.clearTimeout(O.current),O.current=null),E.current="cleared",(c=h.current)==null||c.abort(),h.current=null,x.current=null,ge(),k.current=!1,H.current=null,S.current=null,F.current=null,j(null),m.current=!1,K.current=null,C.current=null,q.current=He(q.current,{type:"reset"}),V.current=null,Y.current=!1,n([]),s(!1),l("")},[]),Fe=We((c,v,R=!1)=>{var p;if(P.current+=1,O.current!==null&&(window.clearTimeout(O.current),O.current=null),E.current="cleared",ge(),k.current=!1,S.current=null,F.current=null,j(null),m.current&&v!==void 0&&v===K.current&&C.current){Y.current=!0,n(C.current),u.current=C.current,l("");return}if(Y.current=!1,m.current||((p=h.current)==null||p.abort(),h.current=null,C.current=null,V.current=null,Y.current=!1),R&&v){const b=[...c].reverse().find(M=>M.role==="user");if(b){const M={text:b.text??"",paperMentions:b.paperMentions??[]},N=[...c,{id:`${b.id}-active`,role:"assistant",streaming:!0,blocks:[]}];Ee(M,{message:M.text,session_id:v,client_message_id:"reconnect",web_search_enabled:!!A.current.webSearchEnabled,reasoning_effort:A.current.reasoningEffort??"low"},N,c,void 0,v);return}}n(c),u.current=c,q.current=He(q.current,{type:"load",messages:c,sessionId:v??A.current.sessionId}),m.current||s(!1),l("")});return{messages:t,busy:a,papers:he,sessionError:d,capacityRequest:ne,disabledRequest:g,send:re,editAndResend:be,retryCapacity:Ce,cancelCapacity:Pe,dismissDisabled:()=>y(null),stop:fe,toggleBlock:T,reset:$e,load:Fe}}const de=(e="")=>({text:e,paperMentions:[]}),Fn=()=>{const e=sessionStorage.getItem(et);if(!e)return null;try{const t=JSON.parse(e);if(typeof t.text=="string"&&Array.isArray(t.paperMentions))return t}catch{}return de(e)},rr=()=>{var B,z,X,L,Te,qe,Qe,ze;const{sessionId:e}=kt(),t=Ot(),[n,a]=It(),{user:s,isLoading:d}=At(),l=jt(),m=Lt(),h=Mt({queryKey:["chatAvailability"],queryFn:()=>Ge.getAvailability(),refetchInterval:3e4,retry:!1,enabled:Le()&&!!s}),x=((B=h.data)==null?void 0:B.status)==="paused",[D,_]=o.useState([]),[k,H]=o.useState(!1),[O,E]=o.useState(""),[S,F]=o.useState(()=>e?{id:e,status:"loading"}:null),[ne,j]=o.useState(0),g=o.useRef(zt()),y=o.useRef(n.get("model")||((z=g.current)==null?void 0:z.model)),[u,q]=o.useState(m?Jt:Xt),[C,V]=o.useState(y.current||Zt),Y=((X=u.find(i=>i.id===C))==null?void 0:X.provider)??"huggingface",A=Ut(!!(s&&Y==="openrouter")),xe=o.useRef(Y);xe.current=Y;const[Ie,P]=o.useState(""),[K,$]=o.useState(()=>de()),[he,ae]=o.useState(()=>{var i;return((i=g.current)==null?void 0:i.webSearchEnabled)??!1}),[Q,J]=o.useState(()=>{var i;return((i=g.current)==null?void 0:i.reasoningEffort)??"low"}),ge=!!((L=h.data)!=null&&L.web_search_available),[Z,Re]=o.useState(()=>{var f,w;const i=(f=n.get("q"))==null?void 0:f.trim();return i?de(i):((w=g.current)==null?void 0:w.draft)??de()}),ie=o.useRef(!1),Ke=o.useRef(!1),Me=o.useRef(!1),[Se,ye]=o.useState(()=>typeof window>"u"||window.innerWidth>900),De=o.useRef(new Set),Ee=o.useRef(!1),re=o.useRef(e),be=o.useRef(null),Pe=o.useRef(null),Ce=o.useRef(null);re.current=e;const fe=o.useCallback(async()=>{if(!s)return;const i=!Ee.current;i&&H(!0);try{const f=await en();_(w=>{const U=be.current,W=U?w.find(Be=>Be.id===U):void 0;if(!W)return f;const ue=f.find(Be=>Be.id===U);return[ue?{...ue,title:W.title,is_busy:!0}:W,...f.filter(Be=>Be.id!==U)]}),Ee.current=!0,E("")}catch(f){E(f instanceof Error?f.message:"Could not load chats")}finally{i&&H(!1)}},[s]),T=Pn({sessionId:e??null,initialModel:C,webSearchEnabled:ge&&he,reasoningEffort:Q,onSessionId:i=>{be.current=i;const f=i!==re.current,w=(re.current??null)===Pe.current,U=new Date().toISOString();_(W=>W.some(ue=>ue.id===i)?W.map(ue=>ue.id===i?{...ue,is_busy:!0}:ue):[{id:i,title:"New chat",selected_model:C,created_at:U,updated_at:U,message_count:1,is_busy:!0,web_search_enabled:he,reasoning_effort:Q},...W]),f&&w&&P("New chat"),w&&(Ce.current=i,F({id:i,status:"loaded"}),f&&t(`/chat/${i}`,{replace:!0}))},onTitle:i=>{const f=be.current??re.current;f&&!De.current.has(f)&&(f===re.current&&P(i),_(w=>w.map(U=>U.id===f?{...U,title:i}:U)))},onSettled:i=>{i&&_(f=>f.map(w=>w.id===i?{...w,is_busy:!1}:w)),be.current=null,Pe.current=null,fe()},onProviderTerminal:()=>{xe.current==="openrouter"&&(l.invalidateQueries({queryKey:qt}),l.invalidateQueries({queryKey:Bt}))},onInterrupted:i=>{$(i)}}),$e=T.send;o.useEffect(()=>{T.capacityRequest&&$(T.capacityRequest.draft)},[T.capacityRequest]);const Fe=o.useCallback(i=>{sessionStorage.setItem(et,JSON.stringify(i)),sessionStorage.setItem(Je,C),sessionStorage.setItem(tn,Q),sessionStorage.setItem(Xe,"1"),sessionStorage.setItem(Ze,"1");const f=re.current?`/chat/${re.current}`:"/chat";window.location.href=Nt(f,Y==="huggingface")},[Q,C,Y]),c=o.useCallback((i,f)=>{sessionStorage.setItem(et,JSON.stringify(i)),sessionStorage.setItem(Je,C),sessionStorage.removeItem(Xe),sessionStorage.removeItem(Ze),Re(de()),$(i),E(f)},[C]),v=o.useCallback(async i=>{if(!s){Fe(i);return}if(Y==="huggingface"&&!Ke.current){if(Me.current)return;Me.current=!0;try{if(!(await Ge.getInferenceBilling()).connected){if(sessionStorage.getItem(Ze)==="1"){c(i,"Hugging Face inference authorization was not completed. Your prompt is ready to retry.");return}Fe(i);return}Ke.current=!0}catch(w){c(i,w instanceof Error?w.message:"Could not check Hugging Face authorization.");return}finally{Me.current=!1}}const f=re.current??null;if(sessionStorage.removeItem(Xe),!$e(i)){c(i,"Your prompt was not sent. It is ready to retry.");return}Pe.current=f,be.current=f,sessionStorage.removeItem(et),sessionStorage.removeItem(Je),sessionStorage.removeItem(Ze),nn(),$(de())},[Fe,c,Y,$e,s]);o.useEffect(()=>{if(d||!s)return;const i=sessionStorage.getItem(Je);i&&V(i),fe(),rn().then(U=>{if(q(U.items),!re.current){const W=y.current||i;V(W&&U.items.some(ue=>ue.id===W)?W:U.default_model)}});const f=Fn(),w=sessionStorage.getItem(Xe)==="1";f&&(w?Re(f):$(f))},[d,fe,s]),o.useEffect(()=>{if(!e){Ce.current!==null&&(Ce.current=null,T.reset(),ae(!1),J("low")),F(null);return}if(Ce.current===e||(F(f=>(f==null?void 0:f.id)===e&&f.status==="loading"?f:{id:e,status:"loading"}),d||!s))return;let i=!1;return E(""),nt(e).then(f=>{i||(T.load(gt(f),e,f.is_busy),V(f.selected_model),ae(g.current&&f.messages.length===0?g.current.webSearchEnabled:f.web_search_enabled),J(g.current&&f.messages.length===0?g.current.reasoningEffort:f.reasoning_effort??"high"),P(f.title),Ce.current=e,F({id:e,status:"loaded"}))}).catch(f=>{if(i)return;const w=f instanceof Error?f.message:"Chat not found";T.reset(),E(w),F({id:e,status:"error",error:w})}),()=>{i=!0}},[d,e,s,T.busy,ne]),o.useEffect(()=>{var U;const i=(U=n.get("q"))==null?void 0:U.trim();if(!i)return;ie.current=!1;const f=n.get("model");f&&V(f),Re(de(i));const w=new URLSearchParams(n);w.delete("q"),w.delete("model"),a(w,{replace:!0})},[n,a]),o.useEffect(()=>{if(d||T.busy||!Z.text||ie.current||s&&he&&h.isFetching||e&&(S==null?void 0:S.status)!=="loaded")return;const i=window.setTimeout(()=>{if(ie.current)return;ie.current=!0,v(Z).finally(()=>Re(de()))},0);return()=>window.clearTimeout(i)},[d,h.isFetching,T.busy,Z,e,S==null?void 0:S.status,v,s,he]),o.useEffect(()=>{const i=()=>{!s||T.busy||fe()};return window.addEventListener("focus",i),()=>window.removeEventListener("focus",i)},[T.busy,fe,s]);const R=()=>{be.current=null,T.reset(),$(de()),ae(!1),J("low"),P(""),t("/chat")},p=async(i,f)=>{try{const w=await tt(i,{title:f});return De.current.add(i),i===e&&P(w.title),_(U=>U.map(W=>W.id===i?w:W)),!0}catch(w){return E(w instanceof Error?w.message:"Rename failed"),!1}},b=async i=>{const f=i===e&&T.busy;if(window.confirm(f?"Stop and delete this chat? This cannot be undone.":"Delete this chat? This cannot be undone.")){f&&T.stop();try{if(f){const w=Date.now()+3e3;for(;(await nt(i)).is_busy;){if(Date.now()>=w)throw new Error("Generation is still stopping. The chat was not deleted.");await new Promise(W=>window.setTimeout(W,150))}}await sn(i),i===e&&R(),await fe()}catch(w){E(w instanceof Error?w.message:"Delete failed")}}},M=Tn({messages:T.messages,refreshSessions:fe,resetChat:T.reset,restoreDraft:$,clearTitle:()=>P("")}),N=async i=>{const f=C;if(V(i),!!e)try{const w=await tt(e,{selected_model:i});_(U=>U.map(W=>W.id===e?{...W,selected_model:w.selected_model}:W)),E("")}catch(w){V(f),E(w instanceof Error?w.message:"Model change failed")}},I=async i=>{const f=Q;if(J(i),!!e)try{const w=await tt(e,{reasoning_effort:i});_(U=>U.map(W=>W.id===e?w:W))}catch(w){J(f),E(w instanceof Error?w.message:"Effort change failed")}},[oe,me]=o.useState(60);o.useLayoutEffect(()=>{const i=document.querySelector(".app-header");if(!i)return;const f=()=>me(i.offsetHeight);f();const w=new ResizeObserver(f);return w.observe(i),()=>w.disconnect()},[]);const G=D.find(i=>i.id===e),se=T.messages.length===0,ce=(Te=[...T.messages].reverse().find(i=>i.role==="assistant"&&i.errorCode))==null?void 0:Te.errorCode,le=ce==="openrouter_unavailable"||ce==="openrouter_monthly_budget_exhausted",pe=(S==null?void 0:S.id)===e,Ae=!!(e&&(d||s&&(!pe||(S==null?void 0:S.status)==="loading"))),Ye=pe&&(S==null?void 0:S.status)==="error"?S.error:void 0,je=!!((qe=A.data)!=null&&qe.fallback_enabled),Ue={onSend:v,busy:T.busy,onStop:T.stop,draft:K,onDraftChange:$,models:u,selectedModel:C,onModelChange:i=>void N(i),disabled:x,describedBy:x?"chat-paused-description":void 0,paperMentionsEnabled:!!((Qe=h.data)!=null&&Qe.paper_mentions_enabled),webSearchAvailable:ge,webSearchEnabled:he,onWebSearchChange:ae,reasoningEffort:Q,onReasoningEffortChange:i=>void I(i)};return r.jsxs("div",{className:"chat-page",style:{height:`calc(100dvh - ${oe}px)`},children:[r.jsx(En,{sessions:D,activeSessionId:e,loading:k,error:O,open:Se,onClose:()=>ye(!1),onNew:R,onNavigate:i=>t(`/chat/${i}`),onRename:p,onDelete:i=>void b(i)}),r.jsxs("section",{className:"chat-main",children:[r.jsxs("div",{className:"chat-topbar",children:[!Se&&r.jsx("button",{type:"button",className:"icon-btn",onClick:()=>ye(!0),title:"Open sidebar",children:r.jsx(mt,{})}),r.jsx("span",{className:"chat-topbar-title",children:Ae?(G==null?void 0:G.title)||"":Ie||(G==null?void 0:G.title)||(se?"":"New chat")}),m&&r.jsx("span",{className:"chat-staging-badge",children:"Staging"}),e&&pe&&(S==null?void 0:S.status)==="loaded"&&!se&&r.jsx(Cn,{sessionId:e,busy:T.busy,loading:Ae,onError:E})]}),Ae&&!Z.text?r.jsxs("div",{className:"chat-session-loading",role:"status","aria-live":"polite",children:[r.jsx(pt,{}),r.jsx("span",{children:"Loading conversation…"})]}):Ye?r.jsxs("div",{className:"chat-session-load-error",role:"alert",children:[r.jsx("p",{children:Ye}),r.jsx("button",{type:"button",onClick:()=>{F({id:e,status:"loading"}),j(i=>i+1)},children:"Try again"})]}):se&&!Z.text?r.jsx("div",{className:"chat-empty",children:r.jsxs("div",{className:"chat-empty-inner",children:[r.jsx("div",{className:"chat-empty-eyebrow",children:"AI research assistant"}),r.jsxs("h1",{className:"chat-empty-title",children:["Ask ",r.jsx("em",{children:"Papers With Code"})]}),r.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."}),m&&r.jsx("p",{className:"chat-staging-access-note",children:"This is a limited staging preview. Only approved Hugging Face users can start chats."}),r.jsx(ut,{variant:"empty",composerProps:Ue,provider:Y,openRouterFallbackEnabled:je,byokExpected:le,paused:x,suggestions:an})]})}):r.jsxs(r.Fragment,{children:[T.sessionError&&r.jsx("div",{className:"chat-session-error",role:"alert",children:T.sessionError}),r.jsx(wn,{messages:T.messages,papers:T.papers,busy:T.busy,queuedDraft:Z.text?Z:void 0,paperMentionsEnabled:!!((ze=h.data)!=null&&ze.paper_mentions_enabled),archivePending:M.pending,openRouterFallbackEnabled:je,onToggleBlock:T.toggleBlock,onEditAndResend:T.editAndResend,onArchiveOld:()=>void M.archiveOld(),onArchiveOldest:()=>void M.archiveOldest()}),r.jsx(ut,{variant:"followup",composerProps:Ue,provider:Y,openRouterFallbackEnabled:je,byokExpected:le,paused:x})]})]}),T.capacityRequest&&r.jsx(xn,{retryAt:T.capacityRequest.retryAt,onCancel:T.cancelCapacity,onRetry:()=>{T.retryCapacity()&&$(de())}}),T.disabledRequest&&r.jsx(Rn,{onClose:()=>{var i;$(((i=T.disabledRequest)==null?void 0:i.draft)??K),T.dismissDisabled(),h.refetch()}})]})};export{xn as ChatCapacityDialog,vn as OpenRouterUsageNotice,rr as default};