Spaces:
Running
Running
Download assets/ChatView-Dao27m0b.js from huggingface/paperswithcode: direct link, hf CLI and curl.
- Browser
- Download file 77.7 kB
-
https://huggingface.co/spaces/huggingface/paperswithcode/resolve/main/assets/ChatView-Dao27m0b.js
- Command line
-
hf download hf://spaces/huggingface/paperswithcode/assets/ChatView-Dao27m0b.js
-
curl -L -o ChatView-Dao27m0b.js https://huggingface.co/spaces/huggingface/paperswithcode/resolve/main/assets/ChatView-Dao27m0b.js
77.7 kB
| var br=Object.defineProperty;var wr=(t,e,r)=>e in t?br(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r;var Z=(t,e,r)=>wr(t,typeof e!="symbol"?e+"":e,r);import{r as d,A as zt,W as vr,j as n,X as Sr,h as Gt,F as ot,a as Qt,u as xr,b as Rr,d as Er,m as Tr,Y as Cr,L as Nt,f as kr}from"./index-C2uVRBgm.js";import{u as ze}from"./useQuery-DceN3et-.js";import{C as Ir,U as Mt,b as Ar,f as We,c as Or,g as jr,A as Dr,a as Nr}from"./ArtifactWorkspace-DVJN2mAN.js";import{c as qe}from"./chat-BZwHRqJu.js";import{f as Mr,h as Jt,i as Lr,T as Fr,d as Xt,j as qr,k as Pr,l as Yr,m as Ge,n as Br,t as Lt,o as mt,r as Zt,s as Wr,v as Hr,S as Ur,P as Kr,D as ct,w as $r,x as Vr,y as st,z as et,B as zr,E as Gr,F as tt,G as rt,H as Qr,g as Jr,I as Xr,J as lt,K as Zr}from"./chatLaunch-BS5TAhHH.js";import{M as es,S as ts}from"./chatPrompts-B5jCAxs8.js";import{S as rs}from"./share-2-D5ZWP0no.js";import{u as ss,O as ns}from"./openrouter-CLLN-EN-.js";import{q as er}from"./queryOptions-C9woPjwX.js";/* empty css */import"./hover-card-C-7bnL__.js";import"./CatalogEntityPreviewLink-DsNvVEs0.js";import"./catalog-CUh96gFy.js";import"./github-DDLc_fu6.js";import"./file-text-2CvI4_bz.js";import"./PaperPreviewLink-BAYCPzQM.js";import"./index-uJBKFN0s.js";import"./index-KDY-Q1WI.js";import"./katex-DkKDou_j.js";import"./paperQueryKeys-BP2E-0yf.js";import"./papers-BSHjPS5U.js";import"./useMutation-B2A2sn3L.js";import"./copy-CmWW0a8H.js";import"./thumbs-up-YU3nf6d-.js";import"./external-link-BXjtAjOd.js";import"./chevron-down-DSGJs-Ut.js";import"./earth-D7OyK13S.js";import"./AgentLogos-CrC7Cwax.js";function as(t){const[e,r]=d.useState("calc(100dvh - 60px)");return d.useLayoutEffect(()=>{if(!t)return;const s=document.querySelector(".app-header"),a=window.visualViewport,c=()=>{const i=(a==null?void 0:a.height)??window.innerHeight;r(`${Math.max(0,i-((s==null?void 0:s.offsetHeight)??0))}px`)};c();const p=new ResizeObserver(c);return s&&p.observe(s),a==null||a.addEventListener("resize",c),window.addEventListener("resize",c),()=>{p.disconnect(),a==null||a.removeEventListener("resize",c),window.removeEventListener("resize",c)}},[t]),t?e:"100%"}const me=(t,e)=>new Promise(r=>{const s=setTimeout(a,t);function a(){e==null||e.removeEventListener("abort",a),clearTimeout(s),r()}e==null||e.addEventListener("abort",a)}),ke=t=>({arxiv_id:null,source:"arxiv",source_url:null,thumbnail_url:null,authors:[],published:null,conference:null,citation_count:null,tasks:[],methods:[],repositories:[],project_pages:[],...t}),Ie={name:"Object Detection",slug:"object-detection"},Le={name:"Real-Time Object Detection",slug:"real-time-object-detection"},is={"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:ke({arxiv_id:"2502.12524",authors:[{name:"Y. Tian"},{name:"Q. Ye"},{name:"D. Doermann"}],published:"2025-02-18",citation_count:412,tasks:[Ie,Le],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:ke({arxiv_id:"2407.17140",authors:[{name:"W. Lv"},{name:"Y. Zhao"},{name:"J. Chang"}],published:"2024-07-24",citation_count:268,tasks:[Ie,Le],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:ke({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:[Ie,Le],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:ke({arxiv_id:"2406.03459",authors:[{name:"Q. Chen"},{name:"X. Su"},{name:"X. Zhang"}],published:"2024-06-05",citation_count:94,tasks:[Ie,Le],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:ke({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:[Ie,Le],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:ke({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:[Ie,Le],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:ke({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"},Ie],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:ke({source:"external",source_url:"https://docs.ultralytics.com/models/",authors:[{name:"Ultralytics"}],published:"2025-01-02",tasks:[Ie,Le],repositories:[{url:"https://github.com/ultralytics/ultralytics",stars:46e3}],project_pages:[{url:"https://docs.ultralytics.com"}]})}},tr=t=>t.map(e=>is[e]),Ft=tr(["2502.12524","2407.17140","2410.13842","2406.03459","2304.08069","2405.14458","2401.17270","158342"]),qt=tr(["2410.13842","2502.12524","2407.17140","2405.14458","2304.08069"]),Pt="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.",Yt="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.",Bt=`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.`,os=["How do these compare on edge devices like Jetson?","Show me open-vocabulary detectors","What about small-object detection?"];async function*cs(t,e){const r=()=>(e==null?void 0:e.aborted)===!0,s=t.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 me(350,e),!r()){yield{type:"reasoning_start"};for(let a=0;a<Pt.length;a+=6){if(await me(14,e),r())return;yield{type:"reasoning_delta",text:Pt.slice(a,a+6)}}if(await me(400,e),!r()&&(yield{type:"reasoning_end"},await me(300,e),!r()&&(yield{type:"tool_call",id:"call_1",name:"search_papers",args:{query:s,top_k:8}},await me(1100,e),!r()&&(yield{type:"tool_result",id:"call_1",hits:Ft.length,took_ms:214,results:Ft},await me(350,e),!r())))){yield{type:"reasoning_start"};for(let a=0;a<Yt.length;a+=6){if(await me(14,e),r())return;yield{type:"reasoning_delta",text:Yt.slice(a,a+6)}}if(await me(350,e),!r()&&(yield{type:"reasoning_end"},await me(300,e),!r()&&(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 me(900,e),!r()&&(yield{type:"tool_result",id:"call_2",hits:qt.length,took_ms:176,results:qt},await me(400,e),!r())))){for(let a=0;a<Bt.length;a+=4){if(await me(11,e),r())return;yield{type:"answer_delta",text:Bt.slice(a,a+4)}}yield{type:"done",followups:os,finish_reason:"success"}}}}}const Pe=()=>{const e=String("0").trim().toLowerCase();return e==="1"||e==="true"||e==="yes"},ls=()=>!0;class Ue extends Error{constructor(e,r,s,a){super(e),this.code=r,this.status=s,this.retryAfterSeconds=a,this.name="ChatStreamError"}}class nt extends Error{constructor(e="The assistant stream was interrupted."){super(e),this.name="ChatTransportError"}}function us(t,e){if(Pe())try{qe.reportLatency(t,e).catch(()=>{})}catch{}}function ds(t,e={}){return Pe()?fs(t,e):cs(t.message,e.signal)}function rr(t,e={}){return ps(t,e)}async function*fs(t,e){try{const r=await qe.stream(t,e.signal);yield*nr(r,e)}catch(r){throw sr(r)}}async function*ps(t,e){try{const r=await qe.resumeStream(t,e.signal,e.afterSequence);yield*nr(r,e)}catch(r){throw sr(r)}}function sr(t){return t instanceof Ue||t instanceof nt?t:t instanceof SyntaxError?new Ue("The assistant returned an invalid stream event.","invalid_stream_event"):new nt(t instanceof Error?t.message:"The assistant stream was interrupted.")}function hs(t){let e=null,r="message";const s=[];for(const a of t.split(` | |
| `))if(a.startsWith("id:")){const c=a.slice(3).trim();/^[1-9]\d*$/.test(c)&&(e=Number(c))}else a.startsWith("event:")?r=a.slice(6).trimStart():a.startsWith("data:")&&s.push(a.slice(5).trimStart());return{sequence:e,event:r,data:s.join(` | |
| `)}}async function*nr(t,e){var p;if(!t.ok||!t.body){const i=t.ok?null:new zt(t,await t.text());i&&vr(i);const h=i==null?void 0:i.detail,A=typeof h=="object"&&h!==null?h:null,f=t.status===403&&!h,C=Number(t.headers.get("Retry-After")),k=Number.isFinite(C)&&C>=0?Math.min(300,Math.ceil(C)):void 0;throw new Ue(f?"Chat on staging is limited to approved Hugging Face users. Sign in with an approved account and try again.":(i==null?void 0:i.message)||`Chat stream failed (${t.status})`,A&&"code"in A&&typeof A.code=="string"?A.code:f?"staging_access_required":void 0,t.status,k)}const r=t.body.getReader(),s=new TextDecoder;let a="",c=e.afterSequence&&e.afterSequence>0?e.afterSequence:0;try{for(;;){const{done:i,value:h}=await r.read();if(i)break;a+=s.decode(h,{stream:!0});let A;for(;(A=a.indexOf(` | |
| `))!==-1;){const f=a.slice(0,A);a=a.slice(A+2);const C=hs(f);if(!C.data||C.data==="[DONE]"||C.sequence!==null&&C.sequence<=c)continue;const k=JSON.parse(C.data);C.sequence!==null&&(c=C.sequence,(p=e.onSequence)==null||p.call(e,C.sequence)),yield k}}}finally{r.releaseLock()}}const ms="https://huggingface.co/settings/inference-providers",Wt="pwc.chat.billing-notice-dismissed.v1";function gs({provider:t}){const[e,r]=d.useState(()=>localStorage.getItem(Wt)==="1");return!Pe()||e||t!=="huggingface"?null:n.jsxs("div",{className:"chat-billing-notice",role:"note",children:[n.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."}),n.jsxs("div",{className:"chat-billing-notice-actions",children:[n.jsx("a",{href:"/settings",children:"Review billing"}),n.jsx("a",{href:ms,target:"_blank",rel:"noreferrer",children:"Review usage"}),n.jsx("button",{type:"button",className:"chat-billing-notice-dismiss","aria-label":"Dismiss billing notice",title:"Dismiss",onClick:()=>{localStorage.setItem(Wt,"1"),r(!0)},children:n.jsx(Sr,{size:15,"aria-hidden":"true"})})]})]})}function Ht({variant:t,composerProps:e,provider:r,sponsored:s=!1,paused:a,error:c,suggestions:p=[]}){var h;const i=n.jsxs(n.Fragment,{children:[!s&&n.jsx(gs,{provider:r}),a&&n.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."}),c&&n.jsx("div",{className:"chat-composer-error",role:"alert",children:c}),n.jsx(Ir,{...e,...t==="empty"?{autoFocus:!0}:{placeholder:(h=e.draft)!=null&&h.text?"Edit and send again…":"Ask a follow-up…"}}),t==="empty"&&n.jsx("div",{className:"chat-examples",children:p.map(A=>n.jsx("button",{type:"button",className:"chat-example",disabled:a,onClick:()=>{var f;return e.onSend({text:A,paperMentions:[],...(f=e.draft)!=null&&f.paperSelection?{paperSelection:e.draft.paperSelection}:{}})},children:A},A))})]});return t==="empty"?i:n.jsx("div",{className:"chat-composer-wrap",children:n.jsxs("div",{className:"chat-composer-inner",children:[i,n.jsx("div",{className:"chat-composer-foot",children:Pe()?n.jsxs(n.Fragment,{children:[r==="huggingface"&&n.jsxs("span",{className:"chat-provider-attribution",children:["Powered by 🤗 ",n.jsx("a",{href:"https://huggingface.co/docs/inference-providers/en/index",target:"_blank",rel:"noreferrer",children:"Inference Providers"}),"."]}),r==="openrouter"&&n.jsxs("span",{className:"chat-provider-attribution",children:["Powered by ",n.jsx("a",{href:"https://openrouter.ai",target:"_blank",rel:"noreferrer",children:"OpenRouter"}),"."]}),r==="openai"&&n.jsx("span",{className:"chat-provider-attribution",children:"Powered by OpenAI."}),n.jsx("span",{children:"The AI assistant can make mistakes. Double-check responses."})]}):n.jsx(n.Fragment,{children:"Assistant preview — responses are simulated."})})]})})}function ys({messages:t,papers:e,busy:r,queuedDraft:s,paperMentionsEnabled:a,archivePending:c,openRouterFallbackEnabled:p,onToggleBlock:i,onEditAndResend:h,onRetryFromProgress:A,onRetryWithLuna:f,onArchiveOld:C,onArchiveOldest:k}){var m,O;const[Y,E]=d.useState(null),M=d.useRef(null),L=d.useRef(null),K=d.useRef("bottom"),$=d.useRef(0),V=d.useRef(0),[se,v]=d.useState(!1),N=d.useRef(null),I=d.useCallback(l=>{K.current=l},[]),w=d.useCallback(()=>{const l=M.current;l&&v(l.scrollHeight-l.scrollTop-l.clientHeight>1)},[]),z=t.filter(l=>l.role==="user"),q=z.length,F=d.useRef(q),Q=d.useRef(!1),te=(m=z[0])==null?void 0:m.id,X=(O=z.at(-1))==null?void 0:O.id;d.useEffect(()=>{r&&E(null)},[r]),d.useLayoutEffect(()=>{const l=M.current;if(l){if(q>F.current||r&&!Q.current){const D=Array.from(l.querySelectorAll("[data-message-id]")).at(-1);if(D){const P=l.getBoundingClientRect().top;$.current=l.scrollTop+D.getBoundingClientRect().top-P-24,I("question")}}if(F.current=q,Q.current=r,L.current!==null){l.scrollTop=L.current,L.current=null;return}K.current==="bottom"&&(l.scrollTop=l.scrollHeight),K.current==="question"&&(l.scrollTop=$.current,V.current=l.scrollTop)}},[t,q,r,I]),d.useLayoutEffect(w),d.useEffect(()=>{const l=M.current;if(!l)return;const D=new ResizeObserver(w);return D.observe(l),l.firstElementChild&&D.observe(l.firstElementChild),()=>D.disconnect()},[w]);const J=(l,D)=>{var P;L.current=((P=M.current)==null?void 0:P.scrollTop)??null,i(l,D)};return n.jsxs("div",{className:"chat-conversation-viewport",children:[n.jsx("div",{className:"chat-conversation",ref:M,tabIndex:0,role:"region","aria-label":"Conversation",onWheel:l=>{(l.deltaY<0||K.current==="question")&&I("free")},onTouchStart:l=>{var D;N.current=((D=l.touches[0])==null?void 0:D.clientY)??null},onTouchMove:l=>{var P;const D=(P=l.touches[0])==null?void 0:P.clientY;D!==void 0&&N.current!==null&&(D>N.current||K.current==="question")&&I("free"),N.current=D??null},onKeyDown:l=>{l.target===l.currentTarget&&((["ArrowUp","PageUp","Home"].includes(l.key)||l.key===" "&&l.shiftKey)&&I("free"),["ArrowDown","PageDown","End"," "].includes(l.key)&&K.current==="question"&&I("free"))},onScroll:l=>{const{scrollHeight:D,scrollTop:P,clientHeight:ne}=l.currentTarget,ae=D-P-ne<=1;K.current==="bottom"&&!ae&&I("free");const ge=P-V.current;K.current==="question"&&(ge>1||ge<-1&&!ae)&&I("free"),w()},children:n.jsxs("div",{className:"chat-conversation-inner",children:[t.length===0&&(s==null?void 0:s.text)&&n.jsx(Mt,{id:"queued-launch-preview",text:s.text,paperMentions:s.paperMentions,paperSelection:s.paperSelection,isInitial:!0}),t.map(l=>{var D,P,ne,ae;return l.role==="user"?n.jsx(Mt,{id:l.id,text:l.text??"",paperMentions:l.paperMentions??[],paperSelection:l.paperSelection,paperMentionsEnabled:a,isInitial:l.id===te,editingAllowed:!r&&!!l.revision,editing:Y===l.id,editNotice:l.id===te?"Sending will replace this conversation.":l.id===X?"Sending will replace the response.":"Sending will replace the response and all messages after it.",onEdit:()=>E(l.id),onCancel:()=>E(null),onResendDraft:ge=>{const we=h(l.id,ge);return we&&E(null),we}},l.id):n.jsx(Ar,{msg:l,papers:e,onToggleBlock:J,onRetryCompaction:!r&&l.id===((D=t.at(-1))==null?void 0:D.id)&&((P=z.at(-1))!=null&&P.revision)?A:void 0,onRetryWithLuna:!r&&l.id===((ne=t.at(-1))==null?void 0:ne.id)&&((ae=z.at(-1))!=null&&ae.revision)?f:void 0,onArchiveOldChats:C,onArchiveOldestChats:k,archivePending:c,hfBilling:null,openRouterFallbackEnabled:p,feedbackEnabled:!0},l.id)})]})}),se&&n.jsx("button",{type:"button",className:"chat-jump-latest",onClick:()=>{I("bottom");const l=M.current;l&&(l.focus({preventScroll:!0}),l.scrollTop=l.scrollHeight,w())},children:"Jump to latest"})]})}function _s({retryAt:t,onRetry:e,onCancel:r}){const[s,a]=d.useState(()=>Math.max(0,Math.ceil((t-Date.now())/1e3))),c=d.useRef(null);return d.useEffect(()=>{var A;const p=document.activeElement instanceof HTMLElement?document.activeElement:null;(A=c.current)==null||A.focus();const i=()=>a(Math.max(0,Math.ceil((t-Date.now())/1e3)));i();const h=window.setInterval(i,250);return()=>{window.clearInterval(h),p==null||p.focus()}},[t]),n.jsx("div",{className:"chat-capacity-dialog-backdrop",role:"presentation",children:n.jsxs("div",{className:"chat-capacity-dialog",role:"dialog","aria-modal":"true","aria-labelledby":"chat-capacity-dialog-title","aria-describedby":"chat-capacity-dialog-description",onKeyDown:p=>{p.key==="Escape"&&(p.preventDefault(),r())},children:[n.jsx("h2",{id:"chat-capacity-dialog-title",children:"All research slots are currently in use"}),n.jsx("p",{id:"chat-capacity-dialog-description",children:"Your message was not sent or billed. Try again in a few seconds."}),n.jsx("p",{className:"chat-capacity-countdown","aria-live":"polite",children:s>0?`Try again available in ${s} second${s===1?"":"s"}.`:"You can try again now."}),n.jsxs("div",{className:"chat-capacity-dialog-actions",children:[n.jsx("button",{type:"button",className:"chat-capacity-cancel",ref:c,onClick:r,children:"Cancel"}),n.jsx("button",{type:"button",className:"chat-capacity-retry",disabled:s>0,onClick:e,children:"Try again"})]})]})})}function bs({onClose:t}){const e=d.useRef(null);return d.useEffect(()=>{var s;const r=document.activeElement instanceof HTMLElement?document.activeElement:null;return(s=e.current)==null||s.focus(),()=>r==null?void 0:r.focus()},[]),n.jsx("div",{className:"chat-capacity-dialog-backdrop",role:"presentation",children:n.jsxs("div",{className:"chat-capacity-dialog",role:"dialog","aria-modal":"true","aria-labelledby":"chat-disabled-title","aria-describedby":"chat-disabled-description",onKeyDown:r=>{r.key==="Escape"&&(r.preventDefault(),t())},children:[n.jsx("h2",{id:"chat-disabled-title",children:"Chat is temporarily disabled"}),n.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."}),n.jsx("div",{className:"chat-capacity-dialog-actions",children:n.jsx("button",{ref:e,type:"button",className:"chat-capacity-cancel",onClick:t,children:"Keep editing"})})]})})}function ws({url:t,onClose:e}){return t?n.jsx("div",{className:"chat-share-dialog-backdrop",role:"presentation",onMouseDown:e,children:n.jsxs("div",{className:"chat-share-dialog",role:"dialog","aria-modal":"true","aria-labelledby":"chat-share-dialog-title",onMouseDown:r=>r.stopPropagation(),children:[n.jsx("h2",{id:"chat-share-dialog-title",children:"Public link created"}),n.jsx("p",{children:"Anyone with this link can see this conversation. It could not be copied automatically, so copy it manually:"}),n.jsx("input",{readOnly:!0,value:t,"aria-label":"Public conversation link",autoFocus:!0,onFocus:r=>r.currentTarget.select()}),n.jsx("button",{type:"button",onClick:e,children:"Close"})]})}):null}const ut="pwc:chat:sidebar-width",dt=280,ft=200,pt=480,vs=12,ht=t=>Math.max(ft,Math.min(pt,t)),Ss=()=>{if(typeof window>"u")return dt;const t=Number(localStorage.getItem(ut));return Number.isFinite(t)&&t>0?ht(t):dt};function xs({sessions:t,activeSessionId:e,loading:r,error:s,open:a,onClose:c,onNew:p,onNavigate:i,onRename:h,onDelete:A}){const[f,C]=d.useState(Ss),k=d.useRef(null),Y=d.useRef(f),[E,M]=d.useState(null),[L,K]=d.useState(""),[$,V]=d.useState(null),[se,v]=d.useState(!1),N=[...t].sort((m,O)=>Date.parse(O.updated_at)-Date.parse(m.updated_at)),I=N.filter((m,O)=>O<vs||m.id===e),w=se?N:I,z=t.length-I.length;d.useEffect(()=>{if(!$)return;const m=()=>V(null),O=l=>{l.key==="Escape"&&m()};return window.addEventListener("click",m),window.addEventListener("keydown",O),()=>{window.removeEventListener("click",m),window.removeEventListener("keydown",O)}},[$]);const q=m=>{M(m.id),K(m.title)},F=async m=>{const O=L.trim();O&&await h(m,O)&&M(null)},Q=(m,O,l)=>V({id:m,x:O,y:l}),te=m=>{if(!k.current)return;const O=ht(k.current.width+m-k.current.x);Y.current=O,C(O)},X=()=>{k.current&&(k.current=null,localStorage.setItem(ut,String(Y.current)))},J=m=>{const O=ht(m);Y.current=O,C(O),localStorage.setItem(ut,String(O))};return n.jsxs(n.Fragment,{children:[a&&n.jsx("div",{className:"chat-sidebar-backdrop","aria-hidden":"true",onClick:c}),n.jsxs("aside",{className:`chat-sidebar${a?"":" chat-sidebar-closed"}`,style:{"--chat-sidebar-width":`${f}px`},children:[n.jsxs("div",{className:"chat-sidebar-top",children:[n.jsxs("button",{type:"button",className:"chat-new-chat",onClick:()=>{We()&&p()},children:[n.jsx(Mr,{})," New chat"]}),n.jsx("button",{type:"button",className:"icon-btn",onClick:c,title:"Collapse sidebar",children:n.jsx(Jt,{})})]}),n.jsxs("nav",{className:"chat-sessions","aria-label":"Chat history",children:[r&&n.jsx("div",{className:"chat-sessions-empty",children:"Loading chats…"}),!r&&s&&n.jsx("div",{className:"chat-sessions-empty",children:s}),!r&&!s&&t.length===0&&n.jsx("div",{className:"chat-sessions-empty",children:"Conversations you start will show up here."}),Lr(w).map(m=>n.jsxs("div",{className:"chat-session-group",children:[n.jsx("div",{className:"chat-session-group-label",children:m.label}),m.items.map(O=>n.jsxs("div",{className:`chat-session${O.id===e?" chat-session-active":""}`,role:"button",tabIndex:0,onClick:()=>{We()&&i(O.id)},onKeyDown:l=>{if(l.key==="Enter"&&We()&&i(O.id),l.key==="F2"&&q(O),l.key==="ContextMenu"||l.shiftKey&&l.key==="F10"){l.preventDefault();const D=l.currentTarget.getBoundingClientRect();Q(O.id,D.right-150,D.bottom)}},onContextMenu:l=>{l.preventDefault(),Q(O.id,l.clientX,l.clientY)},children:[E===O.id?n.jsx("input",{className:"chat-session-title-input",value:L,autoFocus:!0,maxLength:80,onClick:l=>l.stopPropagation(),onChange:l=>K(l.target.value),onBlur:()=>void F(O.id),onKeyDown:l=>{l.stopPropagation(),l.key==="Enter"&&F(O.id),l.key==="Escape"&&M(null)}}):n.jsx("span",{className:"chat-session-title",children:O.title}),n.jsx("button",{type:"button",className:"chat-session-menu","aria-label":"Chat actions","aria-haspopup":"menu",title:"Chat actions",onClick:l=>{l.stopPropagation();const D=l.currentTarget.getBoundingClientRect();Q(O.id,D.right-150,D.bottom)},children:"⋯"}),n.jsx("button",{type:"button",className:"chat-session-delete","aria-label":"Delete conversation",onClick:l=>{l.stopPropagation(),We()&&A(O.id)},children:n.jsx(Fr,{})})]},O.id))]},m.label)),z>0&&n.jsx("button",{type:"button",className:"chat-sessions-toggle","aria-expanded":se,onClick:()=>v(m=>!m),children:se?"Show less":`Show ${z} older ${z===1?"chat":"chats"}`})]}),n.jsx(es,{className:"chat-sidebar-tools",canNavigate:We}),n.jsx("div",{className:"chat-sidebar-resize-handle",role:"separator","aria-label":"Resize chat history","aria-orientation":"vertical","aria-valuemin":ft,"aria-valuemax":pt,"aria-valuenow":f,title:"Drag to resize; double-click to reset",tabIndex:0,onPointerDown:m=>{m.button===0&&(k.current={x:m.clientX,width:f},Y.current=f,m.currentTarget.setPointerCapture(m.pointerId))},onPointerMove:m=>te(m.clientX),onPointerUp:X,onPointerCancel:X,onLostPointerCapture:X,onDoubleClick:()=>J(dt),onKeyDown:m=>{(m.key==="ArrowLeft"||m.key==="ArrowRight")&&(m.preventDefault(),J(f+(m.key==="ArrowRight"?10:-10))),(m.key==="Home"||m.key==="End")&&(m.preventDefault(),J(m.key==="Home"?ft:pt))}}),$&&n.jsx("div",{className:"chat-session-context-menu",role:"menu",style:{left:$.x,top:$.y},onClick:m=>m.stopPropagation(),children:n.jsx("button",{type:"button",role:"menuitem",autoFocus:!0,onClick:()=>{const m=t.find(O=>O.id===$.id);m&&q(m),V(null)},children:"Rename chat"})})]})]})}function Rs({sessionId:t,busy:e,loading:r,hasPaperSelection:s=!1,onError:a}){const{toast:c}=Gt(),[p,i]=d.useState(!1),[h,A]=d.useState(""),f=async()=>{var C;if(!(e||p)&&!(s&&!window.confirm("This public link will include the selected paper passage. Anyone with the link can read that passage. Continue?"))){i(!0);try{const k=await qr(t),Y=new URL(k.public_path,window.location.origin).toString();try{if(!((C=navigator.clipboard)!=null&&C.writeText))throw new Error("Clipboard unavailable");await navigator.clipboard.writeText(Y),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(Y)}}catch(k){const Y=k instanceof Error?k.message:"Could not share this conversation";a(Y),c({variant:"destructive",title:"Share failed",description:Y})}finally{i(!1)}}};return n.jsxs(n.Fragment,{children:[n.jsxs("button",{type:"button",className:"chat-share-button",onClick:()=>void f(),disabled:e||p||r,"aria-label":"Share conversation",children:[p?n.jsx(Xt,{}):n.jsx(rs,{"aria-hidden":"true"}),n.jsx("span",{children:"Share"})]}),n.jsx(ws,{url:h,onClose:()=>A("")})]})}const Es=({descriptor:t})=>{const e=Or(),{open:r,register:s,unregister:a}=e,c=ot.useRef(null),p=t.source_head??t.preview_head,i=ot.useMemo(()=>p?{kind:"artifact",schema_version:1,scope:"owner",artifact_id:t.artifact_id,version_id:p.version_id,identifier:"latex-paper",version:p.version,artifact_kind:"latex_paper",title:t.title,status:"ready",preview_mime:"application/pdf",source_language:"latex",total_bytes:0}:null,[t.artifact_id,t.title,p]),h=i?jr(i):null;return ot.useEffect(()=>{if(!(!i||!h))return s(i),c.current!==h&&(c.current=h,r(i)),()=>a(h)},[i,h,r,s,a]),null};function Ts({messages:t,refreshSessions:e,resetChat:r,restoreDraft:s}){const{toast:a}=Gt(),[c,p]=d.useState(null),i=()=>{const f=[...t].reverse().find(C=>C.role==="user");r(),s({text:(f==null?void 0:f.text)??"",paperMentions:(f==null?void 0:f.paperMentions)??[],...f!=null&&f.paperSelection?{paperSelection:f.paperSelection}:{}})};return{pending:c,archiveOld:async()=>{if(c===null){p("old");try{const f=await Yr();if(await e(),f.archived_count===0){a({title:"No chats were archived",description:"There are no inactive chats older than 30 days."});return}i(),a({title:`${f.archived_count} ${f.archived_count===1?"chat":"chats"} archived`,description:"Your question is ready to send again."})}catch(f){a({variant:"destructive",title:"Could not archive old chats",description:f instanceof Error?f.message:"Try again."})}finally{p(null)}}},archiveOldest:async()=>{if(c===null){p("oldest");try{const f=await Pr();await e(),i(),a({title:`${f.archived_count} ${f.archived_count===1?"chat":"chats"} archived`,description:"Your question is ready to send again."})}catch(f){a({variant:"destructive",title:"Could not archive chats",description:f instanceof Error?f.message:"Try again."})}finally{p(null)}}}}}class Cs{constructor(e,r=us){Z(this,"requestId");Z(this,"firstVisibleAt");Z(this,"streamStartReported",!1);Z(this,"firstVisibleReported",!1);Z(this,"terminalReported",!1);Z(this,"semanticReported",new Set);this.submittedAt=e,this.report=r}recordStreamStart(e,r){this.requestId=e,this.streamStartReported||(this.streamStartReported=!0,this.send({submission_to_stream_start_ms:Math.max(0,r-this.submittedAt)})),this.reportFirstVisible()}recordFirstVisible(e){this.firstVisibleAt===void 0&&(this.firstVisibleAt=e,this.reportFirstVisible())}recordSemantic(e,r){if(this.semanticReported.has(e))return;this.semanticReported.add(e);const s=Math.max(0,r-this.submittedAt);this.send(e==="reasoning"?{submission_to_first_reasoning_delta_ms:s}:e==="tool"?{submission_to_first_tool_call_ms:s}:{submission_to_first_answer_delta_ms:s})}recordTerminal(e){this.terminalReported||(this.terminalReported=!0,this.send({terminal_classification:e}))}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(e){this.requestId&&this.report(this.requestId,e)}}const ar="Preparing research workspace…",ir={preparing_workspace:"Preparing secure workspace…",starting_agent:"Starting research agent…",connecting_model:"Connecting to model…"},or=()=>({messages:[],sessionId:null,title:"",phase:"idle"});function Ut(t,e){for(let r=t.length-1;r>=0;r-=1)if(e(t[r]))return r;return-1}function je(t){if(t.status!==ar&&!Object.values(ir).includes(t.status))return t;const{status:e,...r}=t;return r}function ee(t,e){if(!t.length)return t;const r=t.slice();return r[r.length-1]=e(r[r.length-1]),r}function Fe(t,e,r){return ee(t,s=>{const a=je(s),c=a.blocks??[];return{...a,blocks:c.map((p,i)=>e(p,i,c)?r(p):p)}})}function ks(t,e){switch(e.type){case"stream_start":return e.session_id?{...t,sessionId:e.session_id}:t;case"sandbox_start":case"sandbox_ready":case"workspace_ready":return t;case"lifecycle":return{...t,messages:ee(t.messages,r=>{var s;return r.role==="assistant"&&r.streaming&&(((s=r.blocks)==null?void 0:s.length)??0)===0?{...r,status:ir[e.phase]}:r})};case"session_title_start":return{...t,title:""};case"session_title_delta":return{...t,title:`${t.title}${e.text}`.replace(/\s+/g," ").slice(0,80)};case"session_title_done":return{...t,title:e.title};case"compaction_status":return{...t,messages:ee(t.messages,r=>({...r,compacting:!!(r.streaming&&e.state==="started")}))};case"reasoning_start":return{...t,messages:ee(t.messages,r=>{const s=je(r);return{...s,blocks:[...(s.blocks??[]).map(a=>a.kind==="reasoning"&&a.active?{...a,active:!1,open:!1}:a),{kind:"reasoning",text:"",active:!0,open:!0}]}})};case"reasoning_delta":return{...t,messages:Fe(t.messages,(r,s,a)=>r.kind==="reasoning"&&Ut(a,c=>c.kind==="reasoning")===s,r=>r.kind==="reasoning"?{...r,text:r.text+e.text}:r)};case"reasoning_end":return{...t,messages:ee(t.messages,r=>{const s=r.blocks??[],a=Ut(s,i=>i.kind==="reasoning"&&i.active);if(a<0)return r;const c=s[a];if(c.kind!=="reasoning")return r;const p=s[a-1];return(p==null?void 0:p.kind)==="reasoning"&&p.text===c.text?{...r,blocks:s.filter((i,h)=>h!==a)}:{...r,blocks:s.map((i,h)=>h===a?{...c,active:!1,open:!1}:i)}})};case"tool_call":return{...t,messages:ee(t.messages,r=>{const s=je(r);return{...s,blocks:[...s.blocks??[],{kind:"tool",id:e.id,name:e.name,args:e.args,status:"running",open:!1}]}})};case"tool_call_start":return{...t,messages:ee(t.messages,r=>{const s=je(r);return{...s,blocks:[...s.blocks??[],{kind:"tool",schema_version:2,id:e.id,name:e.name,args:{},argumentText:"",argumentState:"streaming",arguments_redacted:e.redacted,status:"running",open:!1}]}})};case"tool_call_arguments_delta":return{...t,messages:Fe(t.messages,r=>r.kind==="tool"&&r.id===e.id,r=>r.kind==="tool"?{...r,args:e.partial_args,argumentText:e.snapshot?e.delta:`${r.argumentText??""}${e.delta}`,arguments_redacted:r.arguments_redacted||e.redacted}:r)};case"tool_call_arguments_done":return{...t,messages:Fe(t.messages,r=>r.kind==="tool"&&r.id===e.id,r=>r.kind==="tool"?{...r,args:e.args,argumentText:JSON.stringify(e.args),argumentState:"done",arguments_redacted:r.arguments_redacted||e.redacted}:r)};case"app_start":return{...t,messages:ee(t.messages,r=>{const s=je(r);return{...s,blocks:[...s.blocks??[],{kind:"app",schema_version:1,instance_id:e.instance_id,provider:e.provider,server:e.server,tool:e.tool,resource_uri:e.resource_uri,status:"loading",input:e.input,result:{content:[],structuredContent:{},isError:!1},csp:{},permissions:{clipboardWrite:!0},height:525}]}})};case"app_result":return{...t,messages:Fe(t.messages,r=>r.kind==="app"&&r.instance_id===e.id,r=>r.kind==="app"?{...r,status:e.status,result:e.result}:r)};case"tool_result":return{...t,messages:Fe(t.messages,r=>r.kind==="tool"&&r.id===e.id,r=>r.kind!=="tool"?r:e.status?{...r,schema_version:2,status:e.status,took_ms:e.took_ms,content:e.content,metadata:e.metadata,open:e.status!=="success"}:{...r,status:"done",hits:e.hits,took_ms:e.took_ms,results:e.results})};case"artifact_start":return{...t,messages:ee(t.messages,r=>{const s=je(r);return{...s,blocks:[...s.blocks??[],{kind:"artifact",schema_version:1,scope:"owner",publication_id:e.publication_id,identifier:e.identifier,artifact_kind:"posterly",title:e.title,status:"generating",phase:"publishing_poster"}]}})};case"artifact_ready":return{...t,messages:Fe(t.messages,r=>r.kind==="artifact"&&r.publication_id===e.publication_id,r=>r.kind==="artifact"?{...r,artifact_id:e.artifact_id,version_id:e.version_id,identifier:e.identifier,version:e.version,title:e.title,status:"ready",preview_mime:e.preview_mime,source_language:e.source_language,gate_status:e.gate_status,total_bytes:e.total_bytes,phase:void 0}:r)};case"artifact_error":return{...t,messages:Fe(t.messages,r=>r.kind==="artifact"&&r.publication_id===e.publication_id,r=>r.kind==="artifact"?{...r,status:"error",phase:void 0,error_code:e.code,error_message:e.message}:r)};case"answer_delta":return{...t,messages:ee(t.messages,r=>{const s=je(r),a=s.blocks??[],c=a.at(-1);return(c==null?void 0:c.kind)==="answer"&&!c.done?{...s,blocks:[...a.slice(0,-1),{...c,text:c.text+e.text}]}:{...s,blocks:[...a,{kind:"answer",text:e.text,done:!1}]}})};case"done":return{...t,phase:"complete",messages:ee(t.messages,r=>({...r,streaming:!1,compacting:!1,followups:e.followups,finishReason:e.finish_reason,citations:e.citations,blocks:(r.blocks??[]).map(s=>s.kind==="answer"?{...s,done:!0}:s.kind==="reasoning"&&s.active?{...s,active:!1,open:!1}:s)}))};case"error":return{...t,phase:"failed",messages:ee(t.messages,r=>({...r,streaming:!1,compacting:!1,error:e.message,errorCode:e.code,blocks:(r.blocks??[]).map(s=>s.kind==="reasoning"&&s.active?{...s,active:!1,open:!1}:s.kind==="tool"&&s.status==="running"?{...s,status:"error",open:!0}:s)}))};default:return t}}function Is(t){return ee(t,e=>{if(e.role!=="assistant")return e;const r=(e.blocks??[]).flatMap(s=>s.kind==="tool"&&s.status==="running"?[{...s,status:"error",open:!0}]:s.kind==="reasoning"&&s.active?s.text?[{...s,active:!1,open:!1}]:[]:s.kind==="answer"?[{...s,done:!0}]:[s]);return{...e,blocks:r,streaming:!1,compacting:!1,finishReason:"stopped"}})}function As(t,e){switch(e.type){case"start":return{messages:e.messages,sessionId:e.sessionId,title:"",phase:"streaming"};case"event":return ks(t,e.event);case"load":return{messages:e.messages,sessionId:e.sessionId,title:t.title,phase:"idle"};case"workspace_status":return{...t,messages:ee(t.messages,r=>{var s;return r.role==="assistant"&&r.streaming&&(((s=r.blocks)==null?void 0:s.length)??0)===0&&!r.error?{...r,status:ar}:r})};case"clear_workspace_status":return{...t,messages:ee(t.messages,je)};case"settle":return{...t,phase:"idle",messages:ee(t.messages,r=>r.streaming?{...r,streaming:!1,compacting:!1}:r)};case"stop":return{...t,messages:Is(t.messages),phase:"stopped"};case"toggle_block":return{...t,messages:cr(t.messages,e.messageId,e.blockIndex)};case"reset":return or()}}function cr(t,e,r){return t.map(s=>{var a;return s.id!==e?s:{...s,blocks:(a=s.blocks)==null?void 0:a.map((c,p)=>p===r&&(c.kind==="reasoning"||c.kind==="tool")?{...c,open:!c.open}:c)}})}const Oe={minDelayMs:5,maxDelayMs:80,minRateCharsPerMs:.3,maxBufferedMs:400,arrivalRateTauMs:1e3,arrivalRateHeadroom:1.1,maxPendingChars:64},Os={now:()=>performance.now(),sleep:(t,e)=>new Promise(r=>{if(e!=null&&e.aborted||t<=0){r();return}const s=window.setTimeout(a,t);function a(){e==null||e.removeEventListener("abort",a),window.clearTimeout(s),r()}e==null||e.addEventListener("abort",a,{once:!0})})};function js(t){return!["stream_start","sandbox_start","sandbox_ready","workspace_ready","session_title_start","session_title_delta","session_title_done"].includes(t.type)}function Ds(t,e=!1,r=Oe.maxPendingChars){var a;if(!t)return{pieces:[],pending:""};if(e)return{pieces:[t],pending:""};const s=Intl.Segmenter;if(s){const p=[...new s(void 0,{granularity:"word"}).segment(t)].filter(h=>h.isWordLike);let i=0;if(p.length>1&&(i=p.at(-1).index),p.length&&/\s$/u.test(t)&&(i=t.length),i>0){const h=t.slice(0,i),A=[],C=[...new s(void 0,{granularity:"word"}).segment(h)].filter(k=>k.isWordLike);for(let k=0;k<C.length;k+=1){const Y=k===0?0:C[k].index,E=((a=C[k+1])==null?void 0:a.index)??h.length;E>Y&&A.push(h.slice(Y,E))}return C.length||A.push(h),{pieces:A,pending:t.slice(i)}}}else{const c=[...t.matchAll(/\s+/gu)];if(c.length){const p=[];let i=0;for(const h of c){const A=h.index+h[0].length;p.push(t.slice(i,A)),i=A}return{pieces:p,pending:t.slice(i)}}}return t.length>=r?{pieces:[t.slice(0,r)],pending:t.slice(r)}:{pieces:[],pending:t}}function Ns(t,e={}){const r={minDelayMs:e.minDelayMs??Oe.minDelayMs,maxDelayMs:e.maxDelayMs??Oe.maxDelayMs,minRateCharsPerMs:e.minRateCharsPerMs??Oe.minRateCharsPerMs,maxBufferedMs:e.maxBufferedMs??Oe.maxBufferedMs,arrivalRateTauMs:e.arrivalRateTauMs??Oe.arrivalRateTauMs,arrivalRateHeadroom:e.arrivalRateHeadroom??Oe.arrivalRateHeadroom,maxPendingChars:e.maxPendingChars??Oe.maxPendingChars},s=e.clock??Os,a=[];let c="",p=null,i=0,h=!0,A=!1,f=null,C=0,k=s.now(),Y=!1;const E=()=>{f==null||f(),f=null},M=(v,N)=>{const I=v.type==="reasoning_delta"||v.type==="answer_delta"?v.text.length:0;a.push({kind:"event",event:v,arrivedAt:N,chars:I}),E()},L=v=>{if(!p||!c)return;const N=Ds(c,v,r.maxPendingChars);for(const I of N.pieces)I&&M({type:p,text:I},i),i=s.now();c=N.pending,c||(p=null)},K=v=>{if(!h)return;const N=s.now();if(v.type==="reasoning_delta"||v.type==="answer_delta"){const I=v.type;if(!v.text)return;if(!Y){Y=!0,C+=v.text.length,k=N;const z=Array.from(v.text)[0];M({type:I,text:z},N);const q=v.text.slice(z.length);if(q)for(p=I,c=q,i=N,L(!1);c.length>=r.maxPendingChars;)L(!1);return}p&&p!==I&&L(!0),p||(p=I,i=N),c+=v.text;const w=Math.max(0,N-k);for(C*=Math.exp(-w/r.arrivalRateTauMs),C+=v.text.length,k=N,L(!1);c.length>=r.maxPendingChars;)L(!1);return}js(v)&&L(!0),M(v,N)},$=(async()=>{var v;try{for await(const N of t)K(N);h&&L(!0)}catch(N){h&&!((v=e.signal)!=null&&v.aborted)&&(L(!0),a.push({kind:"error",error:N,arrivedAt:s.now(),chars:0}))}finally{A=!0,E()}})(),V=()=>a.length||A?Promise.resolve():new Promise(v=>{f=v});return{events:async function*(){var N,I,w,z;let v=Number.NEGATIVE_INFINITY;try{for(;;){if(await V(),!a.length){if(A||!h)return;continue}const q=a[0];if(q.kind==="error")throw a.shift(),q.error;if(q.chars&&!((N=e.isHidden)!=null&&N.call(e))){const F=s.now(),Q=a.reduce((ne,ae)=>ne+ae.chars,0),te=((I=a.find(ne=>ne.chars))==null?void 0:I.arrivedAt)??F,X=Math.max(0,r.maxBufferedMs-(F-te)),J=C*Math.exp(-Math.max(0,F-k)/r.arrivalRateTauMs)/r.arrivalRateTauMs,m=X>0?Q/X:Number.POSITIVE_INFINITY,O=Math.max(r.minRateCharsPerMs,J*r.arrivalRateHeadroom,m),l=Math.min(r.maxDelayMs,Math.max(r.minDelayMs,q.chars/O)),D=Math.max(0,q.arrivedAt+r.maxBufferedMs-F),P=Math.max(q.arrivedAt,v+Math.min(l,D));if(await s.sleep(Math.max(0,P-s.now()),e.signal),!h||(w=e.signal)!=null&&w.aborted)return}a.shift(),v=s.now(),yield q.event}}finally{h&&(h=!1,E(),await((z=t.return)==null?void 0:z.call(t,void 0))),await $}}(),takeAcceptedForStop(){var N;if(!h)return[];h=!1,p&&c&&(M({type:p,text:c},i),c="",p=null);const v=a.flatMap(I=>I.kind==="event"&&I.event.type!=="done"&&I.event.type!=="error"?[I.event]:[]);return a.length=0,E(),(N=t.return)==null||N.call(t,void 0),v}}}const Kt=[250,500,1e3],Ms=(t,e)=>new Promise(r=>{const s=()=>{window.clearTimeout(a),e.removeEventListener("abort",s),r()},a=window.setTimeout(s,t);e.addEventListener("abort",s,{once:!0})});async function*Ls(t,e){let r=t,s=0;for(;;){let a=!1;try{for await(const c of r)(c.type==="done"||c.type==="error")&&(a=!0),yield c;if(a||e.signal.aborted)return;throw new nt}catch(c){e.onDisconnect();const p=e.getSessionId();if(e.signal.aborted||a||!(c instanceof nt)||!p||s>=Kt.length)throw c;if(await Ms(Kt[s],e.signal),e.signal.aborted)return;s+=1,r=rr(p,{signal:e.signal,afterSequence:e.getAfterSequence(),onSequence:e.onSequence})}}}const $t=new Set(["openrouter_monthly_budget_exhausted","openrouter_unavailable","openrouter_byok_credential_invalid","openrouter_byok_billing_error","openrouter_byok_rate_limit","hf_inference_billing_exhausted"]),Fs=new Set(["paper_context_unavailable","paper_mention_unavailable","paper_mentions_disabled","paper_selection_disabled","paper_selection_requires_reader","paper_selection_paper_mismatch","paper_selection_version_mismatch","paper_selection_page_invalid","paper_selection_too_large","chat_storage_quota_exceeded"]);class qs{constructor(){Z(this,"configuration");Z(this,"lifecycle",or());Z(this,"_busy",!1);Z(this,"_pendingCapacity",null);Z(this,"_sawStreamStart",!1);Z(this,"_providerExecuted",!1);Z(this,"_providerStatusChanged",!1);Z(this,"terminal","pending");Z(this,"rejection",null)}get busy(){return this._busy}get pendingCapacity(){return this._pendingCapacity}get sawStreamStart(){return this._sawStreamStart}get sawTerminalEvent(){return this.terminal==="complete"||this.terminal==="error"}get streamFailed(){return this.terminal==="error"||this.terminal==="transport_error"}get admissionRejected(){return this.rejection!==null}get shouldRefreshProvider(){return this._sawStreamStart&&this._providerExecuted||this._providerStatusChanged}finish(){this._busy=!1}queueCapacity(e){this._pendingCapacity=e}cancelCapacity(){this._pendingCapacity=null}projectSession(e){return this._busy&&e===this.sessionId?this.messages:null}get state(){return this.lifecycle}get messages(){return this.lifecycle.messages}get sessionId(){return this.lifecycle.sessionId}transition(e){return this.lifecycle=As(this.lifecycle,e),this.lifecycle}start(e,r,s){this.configuration=s,this._busy=!0,this._sawStreamStart=this._providerExecuted=this._providerStatusChanged=!1,this.terminal="pending",this.rejection=null,this.transition({type:"start",messages:e,sessionId:r})}restore(e,r=this.sessionId){return this.transition({type:"load",messages:e,sessionId:r})}observe(e){return e.type==="stream_start"&&(this._sawStreamStart=!0,this._providerExecuted=e.provider_execution!==!1),(e.type==="done"||e.type==="error")&&(this.terminal=e.type==="done"?"complete":"error"),e.type==="error"&&$t.has(e.code??"")?(this._providerStatusChanged=!0,!0):!1}reject(e,r){const s=e instanceof Ue?e.code:void 0,a=r&&s==="chat_not_busy"?"completed":s==="chat_temporarily_disabled"?"disabled":s==="chat_capacity"?"capacity":Fs.has(s??"")?"draft":$t.has(s??"")?"provider":"network";return this.terminal=a==="completed"?"already_complete":"transport_error",this.rejection=a==="disabled"||a==="capacity"||a==="draft"?a:null,this._providerStatusChanged||(this._providerStatusChanged=a==="provider"),a}reset(){this._busy=!1,this._pendingCapacity=null,this.transition({type:"reset"})}}const Ps=750;function Ys(t,e){for(let r=t.length-1;r>=0;r-=1)if(e(t[r]))return r;return-1}function Ae(t){const e=d.useRef(t);return d.useLayoutEffect(()=>{e.current=t}),d.useCallback((...r)=>e.current(...r),[])}function Bs(t){const[e,r]=d.useState([]),[s,a]=d.useState(!1),[c,p]=d.useState(""),[i]=d.useState(()=>new qs),h=d.useRef(null),A=d.useRef(null),f=d.useRef(null),C=d.useRef(null),k=d.useRef(!1),Y=d.useRef(null),E=d.useRef(null),M=d.useRef("cleared"),L=d.useRef(null),[K,$]=d.useState(null),[V,se]=d.useState(null),v=d.useRef([]),N=d.useRef(null),I=d.useRef(!1),w=d.useRef(t),z=d.useRef(Ge()),q=d.useRef(0),F=d.useRef(0),Q=d.useRef(t.sessionId);if(Q.current!==t.sessionId){Q.current=t.sessionId;const u=i.projectSession(t.sessionId);u&&r(u),i.sessionId!==t.sessionId&&(F.current+=1,L.current=null)}w.current=t,v.current=e,d.useEffect(()=>()=>{var u;E.current!==null&&window.clearTimeout(E.current),(u=h.current)==null||u.abort(),A.current=null,f.current!==null&&cancelAnimationFrame(f.current),C.current!==null&&window.clearTimeout(C.current),i.cancelCapacity()},[i]),d.useEffect(()=>{i.busy||i.restore(i.messages,t.sessionId)},[t.sessionId,i]),d.useEffect(()=>{const u=i.projectSession(t.sessionId);I.current=u!==null,u&&(r(u),v.current=u)},[t.sessionId,i]);const te=d.useMemo(()=>{const u={};for(const g of e)for(const R of g.blocks??[])if(R.kind==="tool")for(const S of R.results??[])u[S.route_id]=S;return u},[e]),X=()=>`m${++q.current}_${Date.now().toString(36)}`,J=(u,g=!0)=>{const R=i.state,S=i.transition(u),y=u.type==="event"&&u.event.type==="stream_start"?u.event.session_id:null;return y?w.current.onSessionId(y,R.sessionId,i.configuration):S.sessionId&&S.sessionId!==R.sessionId&&w.current.onSessionId(S.sessionId,R.sessionId,i.configuration),S.title!==R.title&&w.current.onTitle(S.title,S.sessionId),g&&(v.current=S.messages,r(S.messages)),S},m=()=>N.current===F.current||I.current,O=()=>{f.current!==null&&(cancelAnimationFrame(f.current),f.current=null),C.current!==null&&(window.clearTimeout(C.current),C.current=null)},l=()=>{O(),document.visibilityState!=="hidden"&&I.current&&(k.current=!1,v.current=i.messages,r(i.messages))},D=()=>{if(!I.current||document.visibilityState==="hidden"||f.current!==null||C.current!==null)return;const u=()=>{f.current=null,C.current=null,l()};typeof requestAnimationFrame=="function"?f.current=requestAnimationFrame(u):C.current=window.setTimeout(u,0)};d.useEffect(()=>{const u=()=>{document.visibilityState==="visible"&&k.current&&D()};return document.addEventListener("visibilitychange",u),()=>document.removeEventListener("visibilitychange",u)});const P=u=>{if(h.current!==u||(E.current!==null&&(window.clearTimeout(E.current),E.current=null),M.current==="cleared"))return;const g=M.current==="shown";M.current="cleared",g&&J({type:"clear_workspace_status"},m())},ne=(u,g)=>{E.current!==null&&window.clearTimeout(E.current),M.current="armed",E.current=window.setTimeout(()=>{E.current=null,!(M.current!=="armed"||h.current!==u||u.signal.aborted||F.current!==g)&&(M.current="shown",J({type:"workspace_status"},m()))},Ps)},ae=(u,g)=>{const R=L.current;!R||R.controller!==u||R.tracker.recordStreamStart(g,performance.now())},ge=(u,g)=>{const R=L.current;!R||R.controller!==u||R.tracker.recordTerminal(g)};d.useLayoutEffect(()=>{const u=L.current;if(!u)return;const g=e.at(-1);if((g==null?void 0:g.role)!=="assistant"||!(g.blocks??[]).some(y=>y.kind==="tool"||y.kind==="reasoning"&&!!y.text.trim()||y.kind==="answer"&&!!y.text.trim()))return;const S=performance.now();u.tracker.recordFirstVisible(S);for(const y of g.blocks??[])y.kind==="reasoning"&&y.text.trim()?u.tracker.recordSemantic("reasoning",S):y.kind==="tool"?u.tracker.recordSemantic("tool",S):y.kind==="answer"&&y.text.trim()&&u.tracker.recordSemantic("answer",S)},[e]);const we=(u,g=!0)=>{J({type:"event",event:u},g)},Qe=async(u,g)=>{var y;const R=await(w.current.loadSession??mt)(u);let S=Zt(R);return((y=Y.current)==null?void 0:y.sessionId)===u&&(S=Y.current.messages,Y.current=null),F.current!==g&&!(N.current===g&&I.current&&w.current.sessionId===u)?null:(r(S),v.current=S,i.restore(S,u),S)},De=(u,g,R,S,y,W,U)=>{const H=++F.current;N.current=H,I.current=!0;const j=new AbortController;h.current=j;const ie=u.text;return z.current=u,p(""),r(R),i.start(R,g.session_id,U??{model:w.current.initialModel,webSearchEnabled:!!g.web_search_enabled,reasoningEffort:g.reasoning_effort??"low"}),a(!0),L.current=W?null:{controller:j,tracker:new Cs(performance.now())},M.current="cleared",(async()=>{var pe,G,ye,re,_e,Ke;let T=0;const fe=B=>{B>T&&(T=B)};try{const B=W?rr(W,{signal:j.signal,onSequence:fe}):ds(g,{signal:j.signal,onSequence:fe}),ue=Ls(B,{signal:j.signal,getSessionId:()=>i.sessionId,onDisconnect:()=>{!j.signal.aborted&&h.current===j&&we({type:"compaction_status",state:"finished"},m())},getAfterSequence:()=>T,onSequence:fe}),de=!W&&Pe()&&ls(),oe=de?Ns(ue,{signal:j.signal,isHidden:()=>document.visibilityState==="hidden"}):null;oe&&(A.current={controller:j,stream:oe});for await(const x of(oe==null?void 0:oe.events)??ue){if(j.signal.aborted||h.current!==j)break;x.type==="paper_artifact"&&((G=(pe=w.current).onPaperArtifact)==null||G.call(pe,x,i.sessionId)),x.type==="stream_start"&&ae(j,x.request_id),x.type==="sandbox_start"&&ne(j,H),(x.type==="sandbox_ready"||x.type==="workspace_ready"||x.type==="lifecycle")&&P(j),(x.type==="reasoning_start"||x.type==="reasoning_delta"||x.type==="tool_call"||x.type==="tool_call_start"||x.type==="tool_call_arguments_delta"||x.type==="tool_call_arguments_done"||x.type==="app_start"||x.type==="app_result"||x.type==="artifact_start"||x.type==="artifact_ready"||x.type==="artifact_error"||x.type==="answer_delta"||x.type==="done"||x.type==="error")&&P(j),i.observe(x)&&m()&&w.current.onInterrupted(u),(x.type==="done"||x.type==="error")&&ge(j,x.type==="error"?"error":"complete");const xe=m(),$e=xe&&!(de&&document.visibilityState==="hidden"),Xe=x.type==="reasoning_delta"||x.type==="answer_delta"||x.type==="tool_call_arguments_delta",Ve=!["stream_start","sandbox_start","sandbox_ready","workspace_ready","session_title_start","session_title_delta","session_title_done","reasoning_delta","answer_delta","tool_call_arguments_delta"].includes(x.type);de&&Ve&&l(),de&&Xe?(we(x,!1),k.current||(k.current=xe),D()):(we(x,$e),de&&xe&&!$e&&(k.current=!0))}}catch(B){if(!j.signal.aborted&&h.current===j){const ue=i.reject(B,!!W),de=ue==="completed";if(P(j),!de)if(ue==="disabled")se({question:ie,draft:u}),i.restore(S),F.current===H&&(r(S),v.current=S,p(""));else if(ue==="capacity"){const oe=B instanceof Ue?B.retryAfterSeconds??5:5,x={question:ie,draft:u,request:g,optimistic:R,original:S,edit:y,retryAfterSeconds:oe,retryAt:Date.now()+oe*1e3};i.queueCapacity(x),$({question:ie,draft:u,retryAt:x.retryAt,retryAfterSeconds:oe}),i.restore(S),F.current===H&&(r(S),v.current=S,p(""))}else ge(j,"network_error"),ue==="draft"&&(m()&&w.current.onInterrupted(u),i.restore(S),F.current===H&&(r(S),v.current=S,p(B instanceof Error?B.message:"The assistant stream failed."))),ue==="provider"&&m()&&w.current.onInterrupted(u);!de&&!i.admissionRejected&&F.current===H&&we({type:"error",message:B instanceof Error?B.message:"The assistant stream failed.",code:B instanceof Ue?B.code:void 0})}}finally{if(h.current===j){if(((ye=A.current)==null?void 0:ye.controller)===j&&(l(),A.current=null),P(j),!i.sawTerminalEvent&&!j.signal.aborted&&ge(j,"network_error"),i.finish(),a(!1),i.admissionRejected)w.current.onSettled(g.session_id);else if(!j.signal.aborted){i.shouldRefreshProvider&&((_e=(re=w.current).onProviderTerminal)==null||_e.call(re));const B=i.sessionId;if(y&&!i.sawStreamStart)i.restore(y.snapshot),F.current===H&&(r(y.snapshot),v.current=y.snapshot,p("Couldn’t resend this message. Your original conversation was restored."));else if(B){F.current===H&&y&&(i.streamFailed||!i.sawTerminalEvent)&&(i.restore(y.snapshot),r(y.snapshot),v.current=y.snapshot);try{const ue=await Qe(B,H);ue&&y&&ue.some(de=>de.id===y.targetId)&&p("Couldn’t resend this message. Your original conversation was restored.")}catch{F.current===H&&J({type:"settle"})}}else F.current===H&&J({type:"settle"});(!h.current||h.current===j)&&w.current.onSettled(B)}((Ke=L.current)==null?void 0:Ke.controller)===j&&(L.current=null)}}})(),!0},Ye=Ae(u=>{var fe,pe;const g=typeof u=="string"?Ge(u.trim()):u,R=g.text;if(!R||R.length>8e3||i.busy||i.pendingCapacity)return!1;const S=v.current,y=[...S].reverse().find(G=>G.role==="user"),W=y!=null&&y.status&&y.status!=="complete"&&y.revision?{replace_message_id:y.id,prior_revision:y.revision}:null,U={id:X(),role:"user",text:R,paperMentions:g.paperMentions,paperSelection:g.paperSelection},H={id:X(),role:"assistant",streaming:!0,blocks:[]},j=W&&y?Ys(S,G=>G.id===y.id):-1,ie=j<0?[...S,U,H]:[...S.slice(0,j),U,H],T=(pe=(fe=w.current).viewerContext)==null?void 0:pe.call(fe);return De(g,{message:R,paper_mentions:g.paperMentions.map(({route_id:G,title:ye,start:re,end:_e})=>({route_id:G,title:ye,start:re,end:_e})),session_id:w.current.sessionId,client_message_id:crypto.randomUUID(),web_search_enabled:!!w.current.webSearchEnabled,reasoning_effort:w.current.reasoningEffort??"low",...w.current.primaryPaperRouteId?{primary_paper_route_id:w.current.primaryPaperRouteId}:{},...T?{viewer_context:T}:{},...g.paperSelection?{paper_selection:Lt(g.paperSelection)}:{},...!w.current.sessionId&&w.current.initialModel?{initial_model:w.current.initialModel}:{},...W??{}},ie,S)}),Ee=Ae((u,g)=>{var fe,pe;const R=typeof g=="string"?Ge(g.trim()):g,S=R.text;if(!S||S.length>8e3||i.busy||i.pendingCapacity)return!1;const y=v.current.slice(),W=y.findIndex(G=>G.id===u&&G.role==="user");if(W<0)return!1;const U=y[W];if(!w.current.sessionId||!U.revision)return!1;const H={id:U.id,role:"user",text:S,paperMentions:R.paperMentions,paperSelection:R.paperSelection,revision:U.revision+1,status:"generating"},j={id:X(),role:"assistant",streaming:!0,blocks:[]},ie=[...y.slice(0,W),H,j],T=(pe=(fe=w.current).viewerContext)==null?void 0:pe.call(fe);return De(R,{message:S,paper_mentions:R.paperMentions.map(({route_id:G,title:ye,start:re,end:_e})=>({route_id:G,title:ye,start:re,end:_e})),session_id:w.current.sessionId,client_message_id:crypto.randomUUID(),web_search_enabled:!!w.current.webSearchEnabled,reasoning_effort:w.current.reasoningEffort??"low",...w.current.primaryPaperRouteId?{primary_paper_route_id:w.current.primaryPaperRouteId}:{},...T?{viewer_context:T}:{},...R.paperSelection?{paper_selection:Lt(R.paperSelection)}:{},replace_message_id:U.id,prior_revision:U.revision},ie,y,{targetId:U.id,snapshot:y})}),le=Ae(()=>{const u=v.current.slice(),g=[...u].reverse().find(y=>y.role==="user");if(!w.current.sessionId||!(g!=null&&g.revision)||i.busy||i.pendingCapacity)return!1;const R=Ge(g.text??"Continue the interrupted response from saved progress."),S=[...u,{id:X(),role:"user",text:R.text,paperMentions:[]},{id:X(),role:"assistant",streaming:!0,blocks:[]}];return De(R,{message:R.text,session_id:w.current.sessionId,client_message_id:crypto.randomUUID(),retry_message_id:g.id,...w.current.primaryPaperRouteId?{primary_paper_route_id:w.current.primaryPaperRouteId}:{},web_search_enabled:!!w.current.webSearchEnabled,reasoning_effort:w.current.reasoningEffort??"low"},S,u)}),ve=Ae(()=>{const u=[...v.current].reverse().find(g=>g.role==="user");return u!=null&&u.text?Ee(u.id,{text:u.text,paperMentions:u.paperMentions??[],...u.paperSelection?{paperSelection:u.paperSelection}:{}}):!1}),Ne=d.useCallback(()=>{i.cancelCapacity(),$(null)},[i]),Te=Ae(()=>{const u=i.pendingCapacity;return!u||Date.now()<u.retryAt||i.busy?!1:(i.cancelCapacity(),$(null),De(u.draft,u.request,u.optimistic,u.original,u.edit))}),Ce=Ae(()=>{var U,H;if(!h.current)return;const u=h.current;P(u),ge(u,"stopped"),u.abort();const g=((U=A.current)==null?void 0:U.controller)===u?A.current.stream.takeAcceptedForStop():[];A.current=null;for(const j of g)we(j,!1);l(),h.current=null,((H=L.current)==null?void 0:H.controller)===u&&(L.current=null),i.finish(),a(!1);const R=m(),S=J({type:"stop"},!1).messages;R&&(v.current=S,r(S),w.current.onInterrupted(z.current));const y=i.sessionId;y&&(Y.current={sessionId:y,messages:S}),y&&Br(y).catch(()=>{});const W=++F.current;window.setTimeout(()=>{y&&R&&F.current===W?Qe(y,W).catch(()=>{}).finally(()=>{h.current||w.current.onSettled(y)}):h.current||w.current.onSettled(y)},450)}),Je=Ae((u,g)=>{const R=I.current?i.transition({type:"toggle_block",messageId:u,blockIndex:g}).messages:cr(v.current,u,g);v.current=R,r(R)}),Se=d.useCallback(()=>{var u;F.current+=1,E.current!==null&&(window.clearTimeout(E.current),E.current=null),M.current="cleared",(u=h.current)==null||u.abort(),h.current=null,A.current=null,O(),k.current=!1,Y.current=null,L.current=null,$(null),i.reset(),N.current=null,I.current=!1,r([]),a(!1),p("")},[i]),Be=Ae((u,g,R=!1,S)=>{var y;if(F.current+=1,E.current!==null&&(window.clearTimeout(E.current),E.current=null),M.current="cleared",O(),k.current=!1,L.current=null,i.cancelCapacity(),$(null),i.busy&&g!==void 0&&g===i.sessionId){I.current=!0,r(i.messages),v.current=i.messages,p("");return}if(I.current=!1,i.busy||((y=h.current)==null||y.abort(),h.current=null,N.current=null,I.current=!1),R&&g&&!i.busy){const W=[...u].reverse().find(U=>U.role==="user");if(W){const U={text:W.text??"",paperMentions:W.paperMentions??[],...W.paperSelection?{paperSelection:W.paperSelection}:{}},H=[...u,{id:`${W.id}-active`,role:"assistant",streaming:!0,blocks:[]}];De(U,{message:U.text,session_id:g,client_message_id:"reconnect",web_search_enabled:!!w.current.webSearchEnabled,reasoning_effort:w.current.reasoningEffort??"low"},H,u,void 0,g,S);return}}r(u),v.current=u,i.busy||i.restore(u,g??w.current.sessionId),i.busy||a(!1),p("")});return{messages:e,busy:s,activeSessionId:s?i.sessionId:null,activeTitle:i.state.title,activeConfiguration:i.configuration,selectedBusy:s&&i.sessionId===t.sessionId,papers:te,sessionError:c,capacityRequest:K,disabledRequest:V,send:Ye,editAndResend:Ee,retryFromProgress:le,retryLatest:ve,retryCapacity:Te,cancelCapacity:Ne,dismissDisabled:()=>se(null),stop:Ce,toggleBlock:Je,reset:Se,load:Be}}const lr=["chat","openai","usage"],Ws=90,ur="pwc:chat:openai-credits-notice:dismissed";function Hs(t=!0){return ze({queryKey:lr,queryFn:()=>qe.getOpenAIUsage(),enabled:t,staleTime:3e4,retry:!1,refetchOnWindowFocus:!0})}function Us(t,e,r){if(!t||e!=="openai"||t.used_percent<Ws||r===t.resets_at)return null;const s=new Intl.DateTimeFormat(void 0,{month:"long",day:"numeric"}).format(new Date(t.resets_at));return{message:`You have ${t.remaining_percent}% left of your monthly OpenAI credits. They reset on ${s}.`,resetsAt:t.resets_at}}function Ks(){try{return localStorage.getItem(ur)}catch{return null}}function $s(t){try{localStorage.setItem(ur,t)}catch{}}const He={list:t=>["chatSessions",t],detail:(t,e)=>["chatSession",t,e]},Vs=t=>er({queryKey:He.list(t),queryFn:Wr,staleTime:0,refetchOnWindowFocus:!1,retry:!1}),Vt=(t,e)=>er({queryKey:He.detail(t,e),queryFn:()=>{if(!e)throw new Error("A saved conversation is required");return mt(e)},staleTime:0,refetchOnWindowFocus:!1,retry:!1}),be=Ge,zs=["Summarize the main contributions","Explain in simple terms","Identify the main limitations"],Gs=()=>{const t=sessionStorage.getItem(st);if(!t)return null;try{return Xr(JSON.parse(t),t)}catch{}return be(t)},Qs=({enabled:t,workspaceKey:e,children:r,onAskAiFix:s})=>t?n.jsx(Dr,{workspaceKey:e,onAskAiFix:s,children:r}):n.jsx(n.Fragment,{children:r}),Js=({enabled:t,children:e})=>t?n.jsx(Nr,{variant:"chat",children:e}):n.jsx(n.Fragment,{children:e}),Xs=({mode:t="general",routeSessionId:e,primaryPaper:r,currentPage:s,paperSelection:a,onPaperSelectionChange:c,onSessionId:p,onReaderSubmit:i,onReaderNewChat:h})=>{var wt,vt,St,xt,Rt,Et,Tt,Ct,kt,It,At,Ot,jt,Dt;const{sessionId:A}=xr(),f=e??(t==="general"?A:void 0),C=Rr(),[k,Y]=Er(),{user:E,isLoading:M}=Qt(),L=Tr(),K=(E==null?void 0:E.hf_subject)??null,$=kr(),V=ze({queryKey:["chatAvailability"],queryFn:()=>qe.getAvailability(),refetchInterval:3e4,retry:!1,enabled:Pe()&&!!E}),se=((wt=V.data)==null?void 0:wt.status)==="paused"||t==="paper"&&((vt=V.data)==null?void 0:vt.paper_reader_chat_enabled)===!1,v=ze({...Vs(K),enabled:!!E&&!M}),N=v.data??[],[I,w]=d.useState(null),[z,q]=d.useState(""),F=o=>{L.setQueryData(He.list(K),_=>o(_??[]))},Q=(o,_)=>{F(b=>b.map(ce=>ce.id===o?{...ce,..._}:ce)),L.setQueryData(He.detail(K,o),b=>b&&{...b,..._})},te=d.useRef(Hr()),X=d.useRef(f??null),J=d.useRef(k.get("model")||((St=te.current)==null?void 0:St.model)),[m,O]=d.useState($?Ur:Kr),[l,D]=d.useState(J.current||ct),P=$r(m,l),ne=Vr(m,l),ae=P==="huggingface"&&!ne,ge=ss(!!(E&&P==="openrouter")),we=Hs(Pe()&&!!E&&P==="openai"),[Qe,De]=d.useState(()=>Ks()),Ye=Us(we.data,P,Qe),[Ee,le]=d.useState(()=>be()),[ve,Ne]=d.useState(()=>{var o;return((o=te.current)==null?void 0:o.webSearchEnabled)??!0}),[Te,Ce]=d.useState(()=>{var o;return((o=te.current)==null?void 0:o.reasoningEffort)??"low"}),Je=!!((xt=V.data)!=null&&xt.web_search_available),[Se,Be]=d.useState(()=>{var _,b;const o=(_=k.get("q"))==null?void 0:_.trim();return o?be(o):((b=te.current)==null?void 0:b.draft)??be()}),u=d.useRef(!1),g=d.useRef(!1),R=d.useRef(!1),[S,y]=d.useState(()=>typeof window>"u"||window.innerWidth>900),W=d.useRef(new Set),U=d.useRef(f);U.current=f;const[H,j]=d.useState(void 0),ie=d.useCallback(async()=>{await L.invalidateQueries({queryKey:He.list(K)})},[L,K]),T=Bs({sessionId:f??null,initialModel:l,webSearchEnabled:Je&&ve,reasoningEffort:Te,primaryPaperRouteId:t==="paper"?r==null?void 0:r.routeId:void 0,viewerContext:t==="paper"&&s?()=>({page:Math.max(1,Math.min(1e4,s()))}):void 0,loadSession:async o=>{const _=await L.fetchQuery(Vt(K,o));return w(b=>(b==null?void 0:b.sessionId)===o?null:b),_},onSessionId:(o,_,b)=>{L.cancelQueries({queryKey:He.list(K)});const ce=new Date().toISOString();F(Re=>Re.some(Me=>Me.id===o)?Re.map(Me=>Me.id===o?{...Me,is_busy:!0}:Me):[{id:o,title:"New chat",selected_model:(b==null?void 0:b.model)??l,created_at:ce,updated_at:ce,message_count:1,is_busy:!0,web_search_enabled:(b==null?void 0:b.webSearchEnabled)??ve,reasoning_effort:(b==null?void 0:b.reasoningEffort)??Te},...Re]),(U.current??null)===_&&o!==_&&(t==="paper"?p==null||p(o):C(`/chat/${o}`,{replace:!0}))},onTitle:(o,_)=>{_&&!W.current.has(_)&&Q(_,{title:o})},onSettled:o=>{o&&Q(o,{is_busy:!1}),L.invalidateQueries({queryKey:lr}),ie()},onProviderTerminal:()=>{L.invalidateQueries({queryKey:ns})},onPaperArtifact:(o,_)=>{_&&w({sessionId:_,descriptor:o.descriptor})},onInterrupted:o=>{le(o),c==null||c(o.paperSelection)}}),fe=T.send;d.useEffect(()=>{T.capacityRequest&&(le(T.capacityRequest.draft),c==null||c(T.capacityRequest.draft.paperSelection))},[T.capacityRequest,c]);const pe=d.useCallback(o=>{sessionStorage.setItem(st,JSON.stringify(o)),sessionStorage.setItem(et,l),sessionStorage.setItem(zr,Te),sessionStorage.setItem(Gr,ve?"1":"0"),sessionStorage.setItem(tt,"1"),sessionStorage.setItem(rt,"1");const _=t==="paper"&&r?`/pdf/${r.routeId}`:U.current?`/chat/${U.current}`:"/chat";window.location.href=Cr(_,ae)},[t,r,Te,l,ae,ve]),G=d.useCallback((o,_)=>{sessionStorage.setItem(st,JSON.stringify(o)),sessionStorage.setItem(et,l),sessionStorage.removeItem(tt),sessionStorage.removeItem(rt),Be(be()),le(o),c==null||c(o.paperSelection),q(_)},[c,l]),ye=d.useCallback(async o=>{const _=c?a?{...o,paperSelection:a}:{text:o.text,paperMentions:o.paperMentions}:o;if(!E){pe(_);return}if(ae&&!g.current){if(R.current)return;R.current=!0;try{if(!(await qe.getInferenceBilling()).connected){if(sessionStorage.getItem(rt)==="1"){G(_,"Hugging Face inference authorization was not completed. Your prompt is ready to retry.");return}pe(_);return}g.current=!0}catch(b){G(_,b instanceof Error?b.message:"Could not check Hugging Face authorization.");return}finally{R.current=!1}}if(sessionStorage.removeItem(tt),!fe(_)){G(_,"Your prompt was not sent. It is ready to retry.");return}sessionStorage.removeItem(st),sessionStorage.removeItem(et),sessionStorage.removeItem(rt),Qr(),te.current=null,le(be()),c==null||c(void 0),t==="paper"&&(i==null||i())},[pe,t,c,i,a,G,fe,E,ae]);d.useEffect(()=>{if(M||!E)return;const o=sessionStorage.getItem(et);o&&D(o),Jr().then(ce=>{if(O(ce.items),!U.current){const Re=J.current||o;D(Re&&ce.items.some(Me=>Me.id===Re)?Re:ce.default_model)}});const _=Gs(),b=sessionStorage.getItem(tt)==="1";_&&(c==null||c(_.paperSelection),b?Be(_):le(_))},[M,c,ie,E]);const re=T.selectedBusy,{load:_e,activeConfiguration:Ke}=T,B=ze({...Vt(K,f??null),enabled:!!(f&&E&&!M&&!re),refetchOnMount:"always"}),ue=!M&&(!E||B.error instanceof zt&&B.error.status===404),de=ze({queryKey:["chatSessionPublicShare",f],queryFn:()=>qe.getSessionPublicShare(f??""),enabled:t==="general"&&!!f&&ue,retry:!1}),oe=(Rt=de.data)==null?void 0:Rt.public_path;d.useEffect(()=>{oe&&C(oe,{replace:!0})},[C,oe]);const x=B.data,xe=re||H===(f??null),$e=I&&I.sessionId===f?I.descriptor:x==null?void 0:x.latex_paper,Xe=(Tt=(Et=[...(x==null?void 0:x.messages)??[]].reverse().find(o=>o.role==="user"&&o.viewer_context))==null?void 0:Et.viewer_context)==null?void 0:Tt.page;d.useLayoutEffect(()=>{const o=f??null;if(H===o)return;if(re){j(o);const b=Ke;b&&(b.model&&D(b.model),Ne(b.webSearchEnabled),Ce(b.reasoningEffort));return}if(!o){_e([],null),H!==void 0&&(Ne(!0),Ce("low")),j(null);return}if(!x||B.isFetching)return;j(o),_e(Zt(x),o,x.is_busy,{model:x.selected_model,webSearchEnabled:x.web_search_enabled,reasoningEffort:x.reasoning_effort??"high"}),q(""),D(x.selected_model);const _=o===X.current?te.current:null;Ne(_?_.webSearchEnabled:x.web_search_enabled),Ce(_?_.reasoningEffort:x.reasoning_effort??"high")},[f,re,x,_e,Ke,B.isFetching,H]),d.useEffect(()=>{var ce;if(M)return;const o=(ce=k.get("q"))==null?void 0:ce.trim();if(!o)return;u.current=!1;const _=k.get("model");_&&D(_),Be(be(o));const b=new URLSearchParams(k);b.delete("q"),b.delete("model"),Y(b,{replace:!0})},[M,k,Y]),d.useEffect(()=>{if(M||T.busy||!Se.text||u.current||E&&ve&&V.isFetching||f&&!xe)return;const o=window.setTimeout(()=>{if(u.current)return;u.current=!0,ye(Se).finally(()=>Be(be()))},0);return()=>window.clearTimeout(o)},[M,V.isFetching,T.busy,Se,f,xe,ye,E,ve]),d.useEffect(()=>{const o=()=>{!E||T.busy||ie()};return window.addEventListener("focus",o),()=>window.removeEventListener("focus",o)},[T.busy,ie,E]);const Ve=()=>{window.innerWidth<=900&&y(!1),_e([],null),j(null),le(be()),c==null||c(void 0),Ne(!0),Ce("low"),t==="paper"?h==null||h():C("/chat")},dr=async(o,_)=>{try{const b=await lt(o,{title:_});return W.current.add(o),Q(o,b),!0}catch(b){return q(b instanceof Error?b.message:"Rename failed"),!1}},fr=async o=>{const _=T.busy&&o===T.activeSessionId;if(window.confirm(_?"Stop and delete this chat? This cannot be undone.":"Delete this chat? This cannot be undone.")){_&&T.stop();try{if(_){const b=Date.now()+3e3;for(;(await mt(o)).is_busy;){if(Date.now()>=b)throw new Error("Generation is still stopping. The chat was not deleted.");await new Promise(Re=>window.setTimeout(Re,150))}}await Zr(o),o===f&&Ve(),await ie()}catch(b){q(b instanceof Error?b.message:"Delete failed")}}},at=Ts({messages:T.messages,refreshSessions:ie,resetChat:T.reset,restoreDraft:le}),gt=async o=>{const _=l;if(D(o),!f)return!0;try{const b=await lt(f,{selected_model:o});return Q(f,{selected_model:b.selected_model}),q(""),!0}catch(b){return D(_),q(b instanceof Error?b.message:"Model change failed"),!1}},pr=m.some(o=>o.id===ct),hr=async()=>{await gt(ct)&&T.retryLatest()},mr=async o=>{const _=Te;if(Ce(o),!!f)try{const b=await lt(f,{reasoning_effort:o});Q(f,b)}catch(b){Ce(_),q(b instanceof Error?b.message:"Effort change failed")}},gr=as(t==="general"),yt=N.map(o=>o.id===T.activeSessionId&&T.busy?{...o,is_busy:!0,title:W.current.has(o.id)?o.title:T.activeTitle||o.title}:o),he=yt.find(o=>o.id===f),it=T.messages.length===0,Ze=!!(f&&(M||E&&!xe&&!B.isError||de.isFetching||oe)),_t=!xe&&!Ze&&((Ct=B.error)==null?void 0:Ct.message),yr=!!((kt=ge.data)!=null&&kt.fallback_enabled),_r=c?a?{...Ee,paperSelection:a}:{text:Ee.text,paperMentions:Ee.paperMentions}:Ee,bt={onSend:ye,busy:re,onStop:T.stop,draft:_r,onDraftChange:o=>{c?(le({text:o.text,paperMentions:o.paperMentions}),o.paperSelection!==a&&c(o.paperSelection)):le(o)},models:m,selectedModel:l,onModelChange:o=>void gt(o),disabled:se||M||T.busy&&!re,describedBy:se?"chat-paused-description":void 0,paperMentionsEnabled:!!((It=V.data)!=null&&It.paper_mentions_enabled),paperSelectionEnabled:((At=V.data)==null?void 0:At.paper_reader_selection_enabled)===!0,paperArtifactsEnabled:t==="general"&&((Ot=V.data)==null?void 0:Ot.paper_artifacts_enabled)===!0,webSearchAvailable:Je,webSearchEnabled:ve,onWebSearchChange:Ne,reasoningEffort:Te,onReasoningEffortChange:o=>void mr(o)};return n.jsx(Qs,{enabled:t==="general",workspaceKey:f??"new-chat",onAskAiFix:o=>{ye(be(o))},children:n.jsxs("div",{className:`chat-page${t==="paper"?" chat-page--reader":""}`,style:{height:gr},children:[t==="general"&&n.jsx(xs,{sessions:yt,activeSessionId:f,loading:v.isLoading,error:z||((jt=v.error)==null?void 0:jt.message)||"",open:S,onClose:()=>y(!1),onNew:Ve,onNavigate:o=>{window.innerWidth<=900&&y(!1),C(`/chat/${o}`)},onRename:dr,onDelete:o=>void fr(o)}),n.jsx(Js,{enabled:t==="general",children:n.jsxs("section",{className:"chat-main","data-testid":"active-chat-pane",children:[n.jsxs("div",{className:"chat-topbar",children:[t==="general"&&!S&&n.jsx("button",{type:"button",className:"icon-btn",onClick:()=>y(!0),title:"Open sidebar",children:n.jsx(Jt,{})}),t==="paper"&&n.jsx("button",{type:"button",className:"chat-reader-action",onClick:Ve,children:"New chat"}),n.jsx("span",{className:"chat-topbar-title",children:Ze?(he==null?void 0:he.title)||"":(he==null?void 0:he.title)||(x==null?void 0:x.title)||(it?"":"New chat")}),$&&n.jsx("span",{className:"chat-staging-badge",children:"Staging"}),t==="paper"&&n.jsx(Nt,{className:"chat-reader-action",to:"/chat",children:"All chats"}),t==="general"&&(he==null?void 0:he.primary_paper)&&n.jsx(Nt,{className:"chat-reader-action",to:`/pdf/${he.primary_paper.route_id}`,onClick:o=>{if(!We()){o.preventDefault();return}const _=he.primary_paper.route_id;sessionStorage.setItem(`pwc:reader:session:${_}`,he.id),Xe&&sessionStorage.setItem(`pwc:reader:page:${_}`,String(Xe))},children:"Open reader"}),f&&xe&&!it&&n.jsx(Rs,{sessionId:f,busy:re,loading:Ze,hasPaperSelection:T.messages.some(o=>!!o.paperSelection),onError:q})]}),Ye&&n.jsxs("div",{className:"chat-credits-notice",role:"status",children:[n.jsx("span",{children:Ye.message}),n.jsx("button",{type:"button",className:"chat-credits-notice-close","aria-label":"Dismiss credits notice",onClick:()=>{$s(Ye.resetsAt),De(Ye.resetsAt)},children:"×"})]}),t==="general"&&$e&&n.jsx(Es,{descriptor:$e}),Ze&&!Se.text?n.jsxs("div",{className:"chat-session-loading",role:"status","aria-live":"polite",children:[n.jsx(Xt,{}),n.jsx("span",{children:"Loading conversation…"})]}):_t?n.jsxs("div",{className:"chat-session-load-error",role:"alert",children:[n.jsx("p",{children:_t}),n.jsx("button",{type:"button",onClick:()=>{B.refetch()},children:"Try again"})]}):it&&!Se.text?n.jsx("div",{className:"chat-empty",children:n.jsxs("div",{className:"chat-empty-inner",children:[n.jsx("div",{className:"chat-empty-eyebrow",children:t==="paper"?"Paper chat":"Research chat"}),n.jsx("h1",{className:"chat-empty-title",children:t==="paper"?"Ask about this paper":n.jsxs(n.Fragment,{children:["Ask ",n.jsx("em",{children:"Papers With Code"})]})}),n.jsx("p",{className:"chat-empty-sub",children:t==="paper"?"Questions are grounded in the open paper. Add up to three other papers with @.":"Answers are grounded in a live hybrid search over papers, tasks, and benchmarks — with citations you can follow."}),$&&n.jsx("p",{className:"chat-staging-access-note",children:"This is a limited staging preview. Only approved Hugging Face users can start chats."}),n.jsx(Ht,{variant:"empty",composerProps:bt,provider:P,sponsored:ne,paused:se,error:T.sessionError,suggestions:t==="paper"?zs:ts})]})}):n.jsxs(n.Fragment,{children:[n.jsx(ys,{messages:T.messages,papers:T.papers,busy:re,queuedDraft:Se.text?Se:void 0,paperMentionsEnabled:!!((Dt=V.data)!=null&&Dt.paper_mentions_enabled),archivePending:at.pending,openRouterFallbackEnabled:yr,onToggleBlock:T.toggleBlock,onEditAndResend:T.editAndResend,onRetryFromProgress:T.retryFromProgress,onRetryWithLuna:pr?()=>void hr():void 0,onArchiveOld:()=>void at.archiveOld(),onArchiveOldest:()=>void at.archiveOldest()}),n.jsx(Ht,{variant:"followup",composerProps:bt,provider:P,sponsored:ne,paused:se,error:T.sessionError})]})]})}),T.capacityRequest&&n.jsx(_s,{retryAt:T.capacityRequest.retryAt,onCancel:T.cancelCapacity,onRetry:()=>{T.retryCapacity()&&(le(be()),c==null||c(void 0))}}),T.disabledRequest&&n.jsx(bs,{onClose:()=>{var _;const o=((_=T.disabledRequest)==null?void 0:_.draft)??Ee;le(o),c==null||c(o.paperSelection),T.dismissDisabled(),V.refetch()}})]})})},Zs=t=>{const{user:e}=Qt();return n.jsx(Xs,{...t},(e==null?void 0:e.hf_subject)??"guest")},An=()=>n.jsx(Zs,{});export{Zs as ChatExperience,An as default}; | |