Spaces:
Running
Running
Download assets/ChatView-CUJNrJ0L.js from huggingface/paperswithcode: direct link, hf CLI and curl.
- Browser
- Download file 61 kB
-
https://huggingface.co/spaces/huggingface/paperswithcode/resolve/main/assets/ChatView-CUJNrJ0L.js
- Command line
-
hf download hf://spaces/huggingface/paperswithcode/assets/ChatView-CUJNrJ0L.js
-
curl -L -o ChatView-CUJNrJ0L.js https://huggingface.co/spaces/huggingface/paperswithcode/resolve/main/assets/ChatView-CUJNrJ0L.js
61 kB
| var $t=Object.defineProperty;var Yt=(t,e,n)=>e in t?$t(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var $=(t,e,n)=>Yt(t,typeof e!="symbol"?e+"":e,n);import{d as Gt,i as o,j as s,X as kt,M as At,b as je,L as It,al as Xt,am as Jt,an as Zt,ao as pt,ad as Ue,f as Mt,t as Tt,G as Nt,v as Dt,l as es,a as Ft,u as ts,A as ss}from"./index-BASp1Jlg.js";import{C as ns,U as mt,b as rs,f as Ee,A as is,a as as,c as os,g as cs,h as ls,i as qe,j as us,k as gt,t as ds,l as hs,E as fs,m as ps,n as ms,o as gs,p as yt,q as bt}from"./chatLifecycle-CxDZ6qO2.js";import{k as Te,l as ys,m as bs,n as Lt,T as wt,h as Bt,o as Me,r as Qe,s as ws,t as vs,v as he,D as $e,w as Ss,x as xs,y as _s,z as Es,B as Cs,E as Rs,F as js,G as ks,H as As,I as tt,J as Is,K as vt,L as Ot,M as St,N as Ye,j as Ms,O as Ts,Q as Ns,R as qt,U as Ds,V as Fs,W as Ls,X as Bs,S as Os,Y as Pt}from"./index-RY-JbNzf.js";import{c as ne}from"./chat-CX2NZ81t.js";import{M as qs}from"./McpShowcase-CE9dCqp6.js";import{S as Ps}from"./share-2-BzPDfiIY.js";import{u as He}from"./useMutation-xugMiFBh.js";import{I as Us}from"./Icon-BcUEVdYy.js";import{m as Hs}from"./mlIntern-CV3kPuvX.js";import{u as Vs,O as Ks}from"./openrouter-BSE0I7wN.js";/* empty css */import"./hover-card-_8wQQfUX.js";import"./CatalogEntityPreviewLink-C7sQQm0Z.js";import"./github-C7w5kXhu.js";import"./file-text-DZZy1wIH.js";import"./PaperPreviewLink-BemGp5Gv.js";import"./index-1knUYnUW.js";import"./index-BHdIUY4i.js";import"./index-CCWA1Suy.js";import"./katex-DkKDou_j.js";import"./thumbs-up-CZdkIxIJ.js";import"./copy-CrUkgC6n.js";import"./arrow-left-h7Ju0hG8.js";import"./external-link-BZXqyD4v.js";import"./plus-CVmfXvuq.js";import"./search-YB9HB-wG.js";import"./chevron-up-C6L9me8K.js";import"./AuthorAvatar-BAJQT_MK.js";import"./trash-2-Bqm24T_F.js";import"./AgentLogos-BeJ1dOob.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 Ws=Gt("EllipsisVertical",[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["circle",{cx:"12",cy:"5",r:"1",key:"gxeob9"}],["circle",{cx:"12",cy:"19",r:"1",key:"lyex9k"}]]);function zs(t){const[e,n]=o.useState("calc(100dvh - 60px)");return o.useLayoutEffect(()=>{if(!t)return;const i=document.querySelector(".app-header"),l=window.visualViewport,c=()=>{const p=l?l.height*l.scale:window.innerHeight;n(`${Math.max(0,p-((i==null?void 0:i.offsetHeight)??0))}px`)};c();const d=new ResizeObserver(c);return i&&d.observe(i),l==null||l.addEventListener("resize",c),window.addEventListener("resize",c),()=>{d.disconnect(),l==null||l.removeEventListener("resize",c),window.removeEventListener("resize",c)}},[t]),t?e:"100%"}const Qs="https://huggingface.co/settings/inference-providers",xt="pwc.chat.billing-notice-dismissed.v1";function $s({provider:t}){const[e,n]=o.useState(()=>localStorage.getItem(xt)==="1");return!Te()||e||t!=="huggingface"?null:s.jsxs("div",{className:"chat-billing-notice",role:"note",children:[s.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."}),s.jsxs("div",{className:"chat-billing-notice-actions",children:[s.jsx("a",{href:"/settings",children:"Review billing"}),s.jsx("a",{href:Qs,target:"_blank",rel:"noreferrer",children:"Review usage"}),s.jsx("button",{type:"button",className:"chat-billing-notice-dismiss","aria-label":"Dismiss billing notice",title:"Dismiss",onClick:()=>{localStorage.setItem(xt,"1"),n(!0)},children:s.jsx(kt,{size:15,"aria-hidden":"true"})})]})]})}function _t({variant:t,composerProps:e,provider:n,sponsored:i=!1,paused:l,uploading:c=!1,error:d,suggestions:p=[],suggestionLinks:u}){var T;const y=s.jsxs(s.Fragment,{children:[!i&&s.jsx($s,{provider:n}),l&&s.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."}),d&&s.jsx("div",{className:"chat-composer-error",role:"alert",children:d}),s.jsx(ns,{...e,...t==="empty"?{autoFocus:!0}:{placeholder:(T=e.draft)!=null&&T.text?"Edit and send again…":"Ask a follow-up…"}}),t==="empty"&&s.jsxs("div",{className:"chat-examples",children:[p.map(h=>s.jsx("button",{type:"button",className:"chat-example",disabled:l||c,onClick:()=>e.onSend({...e.draft,text:h,paperMentions:[]}),children:h},h)),u]})]});return t==="empty"?y:s.jsx("div",{className:"chat-composer-wrap",children:s.jsxs("div",{className:"chat-composer-inner",children:[y,s.jsx("div",{className:"chat-composer-foot",children:Te()?s.jsxs(s.Fragment,{children:[n==="huggingface"&&s.jsxs("span",{className:"chat-provider-attribution",children:["Powered by 🤗 ",s.jsx("a",{href:"https://huggingface.co/docs/inference-providers/en/index",target:"_blank",rel:"noreferrer",children:"Inference Providers"}),"."]}),n==="openrouter"&&s.jsxs("span",{className:"chat-provider-attribution",children:["Powered by ",s.jsx("a",{href:"https://openrouter.ai",target:"_blank",rel:"noreferrer",children:"OpenRouter"}),"."]}),s.jsx("span",{children:"The AI assistant can make mistakes. Double-check responses."})]}):s.jsx(s.Fragment,{children:"Assistant preview — responses are simulated."})})]})})}function Ys({messages:t,papers:e,busy:n,queuedDraft:i,paperMentionsEnabled:l,archivePending:c,openRouterFallbackEnabled:d,onToggleBlock:p,onEditAndResend:u,onRetryFromProgress:y,onRetryWithLuna:T,onArchiveOld:h,onArchiveOldest:v}){var ce,ae;const[F,x]=o.useState(null),C=o.useRef(null),B=o.useRef(null),V=o.useRef("bottom"),R=o.useRef(0),A=o.useRef(0),[j,E]=o.useState(!1),M=o.useRef(null),I=o.useCallback(f=>{V.current=f},[]),P=o.useCallback(()=>{const f=C.current;f&&E(f.scrollHeight-f.scrollTop-f.clientHeight>1)},[]),W=t.filter(f=>f.role==="user"),N=W.length,Z=o.useRef(N),fe=o.useRef(!1),re=(ce=W[0])==null?void 0:ce.id,ie=(ae=W.at(-1))==null?void 0:ae.id;o.useEffect(()=>{n&&x(null)},[n]);const[te,Y]=o.useState(""),K=o.useRef(n),z=t.at(-1);o.useEffect(()=>{n?Y(""):K.current&&(z==null?void 0:z.role)==="assistant"&&Y(z.error?"The answer failed.":"Answer complete."),K.current=n},[n,z]),o.useLayoutEffect(()=>{const f=C.current;if(f){if(N>Z.current||n&&!fe.current){const L=Array.from(f.querySelectorAll("[data-message-id]")).at(-1);if(L){const U=f.getBoundingClientRect().top;R.current=f.scrollTop+L.getBoundingClientRect().top-U-24,I("question")}}if(Z.current=N,fe.current=n,B.current!==null){f.scrollTop=B.current,B.current=null;return}V.current==="bottom"&&(f.scrollTop=f.scrollHeight),V.current==="question"&&(f.scrollTop=R.current,A.current=f.scrollTop)}},[t,N,n,I]),o.useLayoutEffect(P),o.useEffect(()=>{const f=C.current;if(!f)return;const L=new ResizeObserver(P);return L.observe(f),f.firstElementChild&&L.observe(f.firstElementChild),()=>L.disconnect()},[P]);const G=(f,L)=>{var U;B.current=((U=C.current)==null?void 0:U.scrollTop)??null,p(f,L)};return s.jsxs("div",{className:"chat-conversation-viewport",children:[s.jsx("div",{className:"chat-conversation",ref:C,tabIndex:0,role:"region","aria-label":"Conversation",onWheel:f=>{(f.deltaY<0||V.current==="question")&&I("free")},onTouchStart:f=>{var L;M.current=((L=f.touches[0])==null?void 0:L.clientY)??null},onTouchMove:f=>{var U;const L=(U=f.touches[0])==null?void 0:U.clientY;L!==void 0&&M.current!==null&&(L>M.current||V.current==="question")&&I("free"),M.current=L??null},onKeyDown:f=>{f.target===f.currentTarget&&((["ArrowUp","PageUp","Home"].includes(f.key)||f.key===" "&&f.shiftKey)&&I("free"),["ArrowDown","PageDown","End"," "].includes(f.key)&&V.current==="question"&&I("free"))},onScroll:f=>{const{scrollHeight:L,scrollTop:U,clientHeight:pe}=f.currentTarget,se=L-U-pe<=1;V.current==="bottom"&&!se&&I("free");const X=U-A.current;V.current==="question"&&(X>1||X<-1&&!se)&&I("free"),P()},children:s.jsxs("div",{className:"chat-conversation-inner",children:[t.length===0&&(i==null?void 0:i.text)&&s.jsx(mt,{id:"queued-launch-preview",text:i.text,paperMentions:i.paperMentions,paperSelection:i.paperSelection,isInitial:!0}),t.map(f=>{var L,U,pe,se;return f.role==="user"?s.jsx(mt,{id:f.id,text:f.text??"",paperMentions:f.paperMentions??[],paperSelection:f.paperSelection,attachedFiles:f.attachedFiles,paperMentionsEnabled:l,isInitial:f.id===re,editingAllowed:!n&&!!f.revision,editing:F===f.id,editNotice:f.id===re?"Sending will replace this conversation.":f.id===ie?"Sending will replace the response.":"Sending will replace the response and all messages after it.",onEdit:()=>x(f.id),onCancel:()=>x(null),onResendDraft:X=>{const oe=u(f.id,X);return oe&&x(null),oe}},f.id):s.jsx(rs,{msg:f,papers:e,onToggleBlock:G,onRetryCompaction:!n&&f.id===((L=t.at(-1))==null?void 0:L.id)&&((U=W.at(-1))!=null&&U.revision)?y:void 0,onRetryWithLuna:!n&&f.id===((pe=t.at(-1))==null?void 0:pe.id)&&((se=W.at(-1))!=null&&se.revision)?T:void 0,onArchiveOldChats:h,onArchiveOldestChats:v,archivePending:c,hfBilling:null,openRouterFallbackEnabled:d,feedbackEnabled:!0},f.id)})]})}),j&&s.jsx("button",{type:"button",className:"chat-jump-latest",onClick:()=>{I("bottom");const f=C.current;f&&(f.focus({preventScroll:!0}),f.scrollTop=f.scrollHeight,P())},children:"Jump to latest"}),s.jsx("div",{className:"sr-only",role:"status","aria-live":"polite",children:te})]})}function Gs({retryAt:t,onRetry:e,onCancel:n}){const[i,l]=o.useState(()=>Math.max(0,Math.ceil((t-Date.now())/1e3))),c=o.useRef(null);return o.useEffect(()=>{var y;const d=document.activeElement instanceof HTMLElement?document.activeElement:null;(y=c.current)==null||y.focus();const p=()=>l(Math.max(0,Math.ceil((t-Date.now())/1e3)));p();const u=window.setInterval(p,250);return()=>{window.clearInterval(u),d==null||d.focus()}},[t]),s.jsx("div",{className:"chat-capacity-dialog-backdrop",role:"presentation",children:s.jsxs("div",{className:"chat-capacity-dialog",role:"dialog","aria-modal":"true","aria-labelledby":"chat-capacity-dialog-title","aria-describedby":"chat-capacity-dialog-description",onKeyDown:d=>{d.key==="Escape"&&(d.preventDefault(),n())},children:[s.jsx("h2",{id:"chat-capacity-dialog-title",children:"All research slots are currently in use"}),s.jsx("p",{id:"chat-capacity-dialog-description",children:"Your message was not sent or billed. Try again in a few seconds."}),s.jsx("p",{className:"chat-capacity-countdown","aria-live":"polite",children:i>0?`Try again available in ${i} second${i===1?"":"s"}.`:"You can try again now."}),s.jsxs("div",{className:"chat-capacity-dialog-actions",children:[s.jsx("button",{type:"button",className:"chat-capacity-cancel",ref:c,onClick:n,children:"Cancel"}),s.jsx("button",{type:"button",className:"chat-capacity-retry",disabled:i>0,onClick:e,children:"Try again"})]})]})})}function Xs({onClose:t}){const e=o.useRef(null);return o.useEffect(()=>{var i;const n=document.activeElement instanceof HTMLElement?document.activeElement:null;return(i=e.current)==null||i.focus(),()=>n==null?void 0:n.focus()},[]),s.jsx("div",{className:"chat-capacity-dialog-backdrop",role:"presentation",children:s.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(),t())},children:[s.jsx("h2",{id:"chat-disabled-title",children:"Chat is temporarily disabled"}),s.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."}),s.jsx("div",{className:"chat-capacity-dialog-actions",children:s.jsx("button",{ref:e,type:"button",className:"chat-capacity-cancel",onClick:t,children:"Keep editing"})})]})})}function Js({url:t,onClose:e}){return t?s.jsx("div",{className:"chat-share-dialog-backdrop",role:"presentation",onMouseDown:e,children:s.jsxs("div",{className:"chat-share-dialog",role:"dialog","aria-modal":"true","aria-labelledby":"chat-share-dialog-title",onMouseDown:n=>n.stopPropagation(),children:[s.jsx("h2",{id:"chat-share-dialog-title",children:"Public link created"}),s.jsx("p",{children:"Anyone with this link can see this conversation. It could not be copied automatically, so copy it manually:"}),s.jsx("input",{readOnly:!0,value:t,"aria-label":"Public conversation link",autoFocus:!0,onFocus:n=>n.currentTarget.select()}),s.jsx("button",{type:"button",onClick:e,children:"Close"})]})}):null}const Ge="pwc:chat:sidebar-width",Xe=280,Je=200,Ze=480,Zs=12,et=t=>Math.max(Je,Math.min(Ze,t)),en=()=>{if(typeof window>"u")return Xe;const t=Number(localStorage.getItem(Ge));return Number.isFinite(t)&&t>0?et(t):Xe};function tn({sessions:t,activeSessionId:e,loading:n,error:i,open:l,onClose:c,onNew:d,onNavigate:p,onRename:u,onDelete:y,onDeleteMany:T}){const[h,v]=o.useState(en),F=o.useRef(null),x=o.useRef(h),[C,B]=o.useState(null),[V,R]=o.useState(""),[A,j]=o.useState(null),[E,M]=o.useState(!1),[I,P]=o.useState(new Set),W=t.filter(g=>I.has(g.id)).map(g=>g.id),N=W.length>0,[Z,fe]=o.useState(!1),re=[...t].sort((g,r)=>Date.parse(r.updated_at)-Date.parse(g.updated_at)),ie=re.filter((g,r)=>r<Zs||g.id===e),te=E?re:ie,Y=t.length-ie.length;o.useEffect(()=>{if(!A)return;const g=()=>j(null),r=a=>{a.key==="Escape"&&g()};return window.addEventListener("click",g),window.addEventListener("keydown",r),()=>{window.removeEventListener("click",g),window.removeEventListener("keydown",r)}},[A]),o.useEffect(()=>{if(!N)return;const g=r=>{r.key==="Escape"&&P(new Set)};return window.addEventListener("keydown",g),()=>window.removeEventListener("keydown",g)},[N]);const K=ys(te),z=K.flatMap(g=>g.items.map(r=>r.id)),G=o.useRef(null),ce=g=>{G.current=g,P(r=>{const a=new Set(r);return a.has(g)?a.delete(g):a.add(g),a})},ae=g=>{const a=(G.current&&I.has(G.current)?G.current:null)??(N?null:e??null);a&&(G.current=a);const S=a?z.indexOf(a):-1,w=z.indexOf(g);if(S<0||w<0){G.current=g,P(D=>new Set([...D,g]));return}const b=z.slice(Math.min(S,w),Math.max(S,w)+1);P(D=>new Set([...D,...b]))},f=async()=>{if(!(Z||!Ee())){fe(!0);try{await T(W)&&P(new Set)}finally{fe(!1)}}},L=g=>{B(g.id),R(g.title)},U=async g=>{const r=V.trim();r&&await u(g,r)&&B(null)},pe=(g,r,a)=>j({id:g,x:r,y:a}),se=g=>{if(!F.current)return;const r=et(F.current.width+g-F.current.x);x.current=r,v(r)},X=()=>{F.current&&(F.current=null,localStorage.setItem(Ge,String(x.current)))},oe=g=>{const r=et(g);x.current=r,v(r),localStorage.setItem(Ge,String(r))};return s.jsxs(s.Fragment,{children:[l&&s.jsx("div",{className:"chat-sidebar-backdrop","aria-hidden":"true",onClick:c}),s.jsxs("aside",{className:`chat-sidebar${l?"":" chat-sidebar-closed"}`,style:{"--chat-sidebar-width":`${h}px`},children:[s.jsxs("div",{className:"chat-sidebar-top",children:[s.jsxs("button",{type:"button",className:"chat-new-chat",onClick:()=>{Ee()&&d()},children:[s.jsx(bs,{})," New chat"]}),s.jsx("button",{type:"button",className:"icon-btn",onClick:c,title:"Collapse sidebar","aria-label":"Collapse sidebar",children:s.jsx(Lt,{})})]}),N&&s.jsxs("div",{className:"chat-sessions-bulk",role:"toolbar","aria-label":"Selected chats",children:[s.jsxs("span",{className:"chat-sessions-bulk-count",children:[W.length," selected"]}),s.jsxs("button",{type:"button",className:"chat-sessions-bulk-delete",disabled:Z,onClick:()=>void f(),children:[s.jsx(wt,{})," ",Z?"Deleting…":"Delete"]}),s.jsx("button",{type:"button",className:"chat-sessions-bulk-cancel",disabled:Z,onClick:()=>P(new Set),children:"Cancel"})]}),s.jsxs("nav",{className:"chat-sessions","aria-label":"Chat history",children:[n&&s.jsx("div",{className:"chat-sessions-empty",children:"Loading chats…"}),!n&&i&&s.jsx("div",{className:"chat-sessions-empty",children:i}),!n&&!i&&t.length===0&&s.jsx("div",{className:"chat-sessions-empty",children:"Conversations you start will show up here."}),K.map(g=>s.jsxs("div",{className:"chat-session-group",children:[s.jsx("div",{className:"chat-session-group-label",children:g.label}),g.items.map(r=>s.jsxs("div",{className:`chat-session${r.id===e?" chat-session-active":""}${I.has(r.id)?" chat-session-selected":""}`,role:"button",tabIndex:0,"aria-pressed":N?I.has(r.id):void 0,title:N?"Shift-click to select every chat up to here":"Shift-click to select several chats",onMouseDown:a=>{a.shiftKey&&a.preventDefault()},onClick:a=>{a.shiftKey?ae(r.id):N?ce(r.id):Ee()&&p(r.id)},onKeyDown:a=>{if(a.key==="Enter"&&a.shiftKey?ae(r.id):a.key==="Enter"&&N?ce(r.id):a.key==="Enter"&&Ee()&&p(r.id),a.key==="F2"&&L(r),a.key==="ContextMenu"||a.shiftKey&&a.key==="F10"){a.preventDefault();const S=a.currentTarget.getBoundingClientRect();pe(r.id,S.right-150,S.bottom)}},onContextMenu:a=>{a.preventDefault(),pe(r.id,a.clientX,a.clientY)},children:[C===r.id?s.jsx("input",{className:"chat-session-title-input",value:V,autoFocus:!0,maxLength:80,onClick:a=>a.stopPropagation(),onChange:a=>R(a.target.value),onBlur:()=>void U(r.id),onKeyDown:a=>{a.stopPropagation(),a.key==="Enter"&&U(r.id),a.key==="Escape"&&B(null)}}):s.jsx("span",{className:"chat-session-title",children:r.title}),s.jsx("button",{type:"button",className:"chat-session-menu","aria-label":"Chat actions","aria-haspopup":"menu",title:"Chat actions",onClick:a=>{a.stopPropagation();const S=a.currentTarget.getBoundingClientRect();pe(r.id,S.right-150,S.bottom)},children:"⋯"}),s.jsx("button",{type:"button",className:"chat-session-delete","aria-label":I.has(r.id)?"Delete selected conversations":"Delete conversation",onClick:a=>{a.stopPropagation(),I.has(r.id)?f():Ee()&&y(r.id)},children:s.jsx(wt,{})})]},r.id))]},g.label)),Y>0&&s.jsx("button",{type:"button",className:"chat-sessions-toggle","aria-expanded":E,onClick:()=>M(g=>!g),children:E?"Show less":`Show ${Y} older ${Y===1?"chat":"chats"}`})]}),s.jsx(qs,{className:"chat-sidebar-tools",canNavigate:Ee}),s.jsx("div",{className:"chat-sidebar-resize-handle",role:"separator","aria-label":"Resize chat history","aria-orientation":"vertical","aria-valuemin":Je,"aria-valuemax":Ze,"aria-valuenow":h,title:"Drag to resize; double-click to reset",tabIndex:0,onPointerDown:g=>{g.button===0&&(F.current={x:g.clientX,width:h},x.current=h,g.currentTarget.setPointerCapture(g.pointerId))},onPointerMove:g=>se(g.clientX),onPointerUp:X,onPointerCancel:X,onLostPointerCapture:X,onDoubleClick:()=>oe(Xe),onKeyDown:g=>{(g.key==="ArrowLeft"||g.key==="ArrowRight")&&(g.preventDefault(),oe(h+(g.key==="ArrowRight"?10:-10))),(g.key==="Home"||g.key==="End")&&(g.preventDefault(),oe(g.key==="Home"?Je:Ze))}}),A&&s.jsxs("div",{className:"chat-session-context-menu",role:"menu",style:{left:A.x,top:A.y},onClick:g=>g.stopPropagation(),children:[s.jsx("button",{type:"button",role:"menuitem",autoFocus:!0,onClick:()=>{const g=t.find(r=>r.id===A.id);g&&L(g),j(null)},children:"Rename chat"}),s.jsx("button",{type:"button",role:"menuitem",onClick:()=>{ce(A.id),j(null)},children:I.has(A.id)?"Deselect chat":"Select chat"})]})]})]})}function sn({sessionId:t,busy:e,loading:n,hasPaperSelection:i=!1,onError:l}){const{toast:c}=At(),[d,p]=o.useState(!1),[u,y]=o.useState(""),T=async()=>{var h;if(!(e||d)&&!(i&&!window.confirm("This public link will include the selected paper passage. Anyone with the link can read that passage. Continue?"))){p(!0);try{const v=await ne.createOrRefreshShare(t),F=new URL(v.public_path,window.location.origin).toString();try{if(!((h=navigator.clipboard)!=null&&h.writeText))throw new Error("Clipboard unavailable");await navigator.clipboard.writeText(F),c({className:"chat-share-toast",duration:5e3,title:"Public link copied to your clipboard",description:"Anyone with this link can see this conversation."})}catch{y(F)}}catch(v){const F=v instanceof Error?v.message:"Could not share this conversation";l(F),c({variant:"destructive",title:"Share failed",description:F})}finally{p(!1)}}};return s.jsxs(s.Fragment,{children:[s.jsxs("button",{type:"button",className:"chat-share-button",onClick:()=>void T(),disabled:e||d||n,"aria-label":"Share conversation",children:[d?s.jsx(Bt,{}):s.jsx(Ps,{"aria-hidden":"true"}),s.jsx("span",{children:"Share"})]}),s.jsx(Js,{url:u,onClose:()=>y("")})]})}const Ut=["chat","openai","usage"],nn=90,Ht="pwc:chat:openai-credits-notice:dismissed";function rn(t=!0){return je({queryKey:Ut,queryFn:()=>ne.getOpenAIUsage(),enabled:t,staleTime:3e4,retry:!1,refetchOnWindowFocus:!0})}function an(t,e,n){if(!t||e!=="openai"||t.used_percent<nn||n===t.resets_at)return null;const i=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 ${i}.`,resetsAt:t.resets_at}}function on(){try{return localStorage.getItem(Ht)}catch{return null}}function cn(t){try{localStorage.setItem(Ht,t)}catch{}}const ln=({enabled:t,workspaceKey:e,children:n,onAskAiFix:i})=>t?s.jsx(is,{workspaceKey:e,onAskAiFix:i,children:n}):s.jsx(s.Fragment,{children:n}),un=({enabled:t,children:e})=>t?s.jsx(as,{variant:"chat",children:e}):s.jsx(s.Fragment,{children:e}),dn=({provider:t,enabled:e})=>{const n=rn(e),[i,l]=Ue.useState(()=>on()),c=an(n.data,t,i);return c?s.jsxs("div",{className:"chat-credits-notice",role:"status",children:[s.jsx("span",{children:c.message}),s.jsx("button",{type:"button",className:"chat-credits-notice-close","aria-label":"Dismiss credits notice",onClick:()=>{cn(c.resetsAt),l(c.resetsAt)},children:"×"})]}):null},hn=({onNewChat:t,onClose:e})=>s.jsxs(s.Fragment,{children:[s.jsxs(Xt,{children:[s.jsx(Jt,{asChild:!0,children:s.jsx("button",{type:"button",className:"icon-btn chat-reader-icon-btn","aria-label":"Chat options",title:"Chat options",children:s.jsx(Ws,{"aria-hidden":"true"})})}),s.jsxs(Zt,{align:"end",children:[s.jsx(pt,{onSelect:t,children:"New chat"}),s.jsx(pt,{asChild:!0,children:s.jsx(It,{to:"/chat",children:"All chats"})})]})]}),e&&s.jsx("button",{type:"button",className:"icon-btn chat-reader-icon-btn",onClick:e,"aria-label":"Close chat",title:"Close chat",children:s.jsx(kt,{"aria-hidden":"true"})})]}),fn=({routeId:t,sessionId:e,page:n})=>s.jsx(It,{className:"chat-reader-action",to:`/pdf/${t}`,onClick:i=>{if(!Ee()){i.preventDefault();return}sessionStorage.setItem(`pwc:reader:session:${t}`,e),n&&sessionStorage.setItem(`pwc:reader:page:${t}`,String(n))},children:"Open reader"}),pn=({mode:t,staging:e,children:n})=>s.jsx("div",{className:"chat-empty",children:s.jsxs("div",{className:"chat-empty-inner",children:[s.jsx("div",{className:"chat-empty-eyebrow",children:t==="paper"?"Paper chat":"Research chat"}),s.jsx("h1",{className:"chat-empty-title",children:t==="paper"?"Ask about this paper":s.jsxs(s.Fragment,{children:["Ask ",s.jsx("em",{children:"Papers With Code"})]})}),s.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."}),e&&s.jsx("p",{className:"chat-staging-access-note",children:"This is a limited staging preview. Only approved Hugging Face users can start chats."}),n]})}),mn=({descriptor:t})=>{const e=os(),{open:n,register:i,unregister:l}=e,c=Ue.useRef(null),d=t.source_head??t.preview_head,p=Ue.useMemo(()=>d?{kind:"artifact",schema_version:1,scope:"owner",artifact_id:t.artifact_id,version_id:d.version_id,identifier:"latex-paper",version:d.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,d]),u=p?cs(p):null;return Ue.useEffect(()=>{if(!(!p||!u))return i(p),c.current!==u&&(c.current=u,n(p)),()=>l(u)},[p,u,n,i,l]),null},gn={old:"Could not archive old chats",oldest:"Could not archive chats"};function yn({messages:t,refreshSessions:e,resetChat:n,restoreDraft:i}){const{toast:l}=At(),c=He({mutationFn:async u=>{const y=u==="old"?await ne.archiveOldChats():await ne.archiveOldestChats();return await e(),y},onSuccess:({archived_count:u},y)=>{if(y==="old"&&u===0){l({title:"No chats were archived",description:"There are no inactive chats older than 30 days."});return}const T=Me(t);n(),i(Qe(T)),l({title:`${u} ${u===1?"chat":"chats"} archived`,description:"Your question is ready to send again."})},onError:(u,y)=>{l({variant:"destructive",title:gn[y],description:u instanceof Error?u.message:"Try again."})}}),d=c.isPending?c.variables??null:null,p=async u=>{d===null&&await c.mutateAsync(u).catch(()=>{})};return{pending:d,archiveOld:()=>p("old"),archiveOldest:()=>p("oldest")}}function bn({pendingDraft:t,setPendingDraft:e,blocked:n,authLoading:i,signedIn:l,send:c,restoreDraft:d,setSelectedModel:p,onPaperSelectionChange:u}){const[y,T]=Mt(),h=o.useRef(!1);o.useEffect(()=>{if(i||!l)return;const v=ws();v&&(v.draft.paperSelection&&(u==null||u(v.draft.paperSelection)),v.autoSend?e(v.draft):(d(v.draft),vs()))},[i,u,d,e,l]),o.useEffect(()=>{var C;if(i)return;const v=(C=y.get("q"))==null?void 0:C.trim();if(!v)return;h.current=!1;const F=y.get("model");F&&p(F),e(he(v));const x=new URLSearchParams(y);x.delete("q"),x.delete("model"),T(x,{replace:!0})},[i,y,e,T,p]),o.useEffect(()=>{if(n||!t.text||h.current)return;const v=window.setTimeout(()=>{h.current||(h.current=!0,c(t).finally(()=>e(he())))},0);return()=>window.clearTimeout(v)},[n,t,c,e])}function wn(t,e){var c;const n=Tt(),i=je({queryKey:["chatSessionPublicShare",t],queryFn:()=>ne.getSessionPublicShare(t??""),enabled:!!t&&e,retry:!1}),l=(c=i.data)==null?void 0:c.public_path;return o.useEffect(()=>{l&&n(l,{replace:!0})},[n,l]),{pending:i.isFetching||!!l}}function vn({userId:t,signedIn:e,authLoading:n,requestedModel:i,routeSessionIdRef:l}){const c=o.useRef(i),d=o.useRef(null),[p,u]=o.useState(i||$e),y=o.useCallback(C=>{c.current=C,u(C)},[]),h=je({...ls(t),enabled:e&&!n}).data,v=(h==null?void 0:h.items)??(Nt()?Ss:xs);o.useEffect(()=>{if(n||!e)return;const C=_s();d.current=C,C&&u(C)},[n,e]),o.useEffect(()=>{if(!h||l.current)return;const C=c.current||d.current;u(C&&h.items.some(B=>B.id===C)?C:h.default_model)},[h,l]);const F=Es(v,p),x=Cs(v,p);return{models:v,selectedModel:p,setSelectedModel:y,provider:F,sponsored:x,userBilledInference:F==="huggingface"&&!x,lunaAvailable:v.some(C=>C.id===$e)}}const Sn=3e3,xn=150,ze=(t,e)=>t instanceof Error?t.message:e;function _n(t){const e=Dt(),n=o.useCallback(d=>{e.setQueryData(qe.list(t),p=>d(p??[]))},[e,t]),i=o.useCallback((d,p)=>{n(u=>u.map(y=>y.id===d?{...y,...p}:y)),e.setQueryData(qe.detail(t,d),u=>u&&{...u,...p})},[e,n,t]),l=o.useCallback(async()=>{await e.invalidateQueries({queryKey:qe.list(t)})},[e,t]);return{markSessionBusy:o.useCallback((d,p)=>{e.cancelQueries({queryKey:qe.list(t)});const u=new Date().toISOString();n(y=>y.some(T=>T.id===d)?y.map(T=>T.id===d?{...T,is_busy:!0}:T):[{id:d,title:"New chat",selected_model:p.model,created_at:u,updated_at:u,message_count:1,is_busy:!0,web_search_enabled:p.webSearchEnabled,reasoning_effort:p.reasoningEffort},...y])},[e,n,t]),patchSession:i,refreshSessions:l}}function En({routeSessionId:t,selectedModel:e,setSelectedModel:n,patchSession:i,onRenamed:l,refreshSessions:c,onError:d,onSelectedDeleted:p,isActive:u,stopActive:y}){const T=He({mutationFn:({id:R,title:A})=>ne.updateSession(R,{title:A}),onSuccess:(R,{id:A})=>{l(A),i(A,R)},onError:R=>d(ze(R,"Rename failed"))}),h=async(R,A)=>{if(A){const j=Date.now()+Sn;for(;(await ne.getSession(R)).is_busy;){if(Date.now()>=j)throw new Error("Generation is still stopping. The chat was not deleted.");await new Promise(M=>window.setTimeout(M,xn))}}await ne.removeSession(R)},v=He({mutationFn:async({ids:R,activeId:A})=>{let j=!1;try{for(const E of R)await h(E,E===A),E===t&&(j=!0)}finally{j&&p(),await c()}},onError:R=>d(ze(R,"Delete failed"))}),F=He({mutationFn:({sessionId:R,model:A})=>ne.updateSession(R,{selected_model:A}),onSuccess:(R,{sessionId:A})=>{i(A,{selected_model:R.selected_model}),d("")},onError:(R,{previous:A})=>{n(A),d(ze(R,"Model change failed"))}}),x=(R,A)=>T.mutateAsync({id:R,title:A}).then(()=>!0,()=>!1),C=async R=>{if(R.length===0)return!1;const A=R.find(u),j=R.length===1?"this chat":`these ${R.length} chats`;return window.confirm(`${A?"Stop and delete":"Delete"} ${j}? This cannot be undone.`)?(A&&y(),v.mutateAsync({ids:R,activeId:A}).then(()=>!0,()=>!1)):!1};return{rename:x,remove:async R=>{await C([R])},removeMany:C,changeModel:async R=>{const A=e;return n(R),t?F.mutateAsync({sessionId:t,model:R,previous:A}).then(()=>!0,()=>!1):!0}}}function Cn({returnTo:t,selectedModel:e,reasoningEffort:n,userBilledInference:i,onPromptRestored:l}){const c=o.useRef(!1),d=o.useRef(!1),p=o.useCallback(h=>{Rs(h,e,n),window.location.href=es(t(),{authorizeInference:i})},[n,t,e,i]),u=o.useCallback((h,v)=>{js(h,e),l(h,v)},[l,e]),y=o.useCallback(async h=>{if(d.current)return!1;d.current=!0;try{return(await ne.getInferenceBilling()).connected?(c.current=!0,!0):ks()?(u(h,"Hugging Face inference authorization was not completed. Your prompt is ready to retry."),!1):(p(h),!1)}catch(v){return u(h,v instanceof Error?v.message:"Could not check Hugging Face authorization."),!1}finally{d.current=!1}},[p,u]);return{authorizeSend:o.useCallback((h,v)=>v?i&&!c.current?y(h):!0:(p(h),!1),[p,y,i]),restorePrompt:u}}function Rn(t,e,n){return{message:e,...n,web_search_enabled:!!t.webSearchEnabled,reasoning_effort:t.reasoningEffort??tt}}function Vt(t){return t.primaryPaperRouteId?{primary_paper_route_id:t.primaryPaperRouteId}:{}}function Et(t,e){var i,l;const n=(i=t.viewerContext)==null?void 0:i.call(t);return{paper_mentions:e.paperMentions.map(({route_id:c,title:d,start:p,end:u})=>({route_id:c,title:d,start:p,end:u})),...Vt(t),...n?{viewer_context:n}:{},...e.paperSelection?{paper_selection:As(e.paperSelection)}:{},...(l=e.files)!=null&&l.length?{file_ids:e.files.map(c=>c.id)}:{}}}class jn{constructor(e,n=Is){$(this,"requestId");$(this,"firstVisibleAt");$(this,"streamStartReported",!1);$(this,"firstVisibleReported",!1);$(this,"terminalReported",!1);$(this,"semanticReported",new Set);this.submittedAt=e,this.report=n}recordStreamStart(e,n){this.requestId=e,this.streamStartReported||(this.streamStartReported=!0,this.send({submission_to_stream_start_ms:Math.max(0,n-this.submittedAt)})),this.reportFirstVisible()}recordFirstVisible(e){this.firstVisibleAt===void 0&&(this.firstVisibleAt=e,this.reportFirstVisible())}recordSemantic(e,n){if(this.semanticReported.has(e))return;this.semanticReported.add(e);const i=Math.max(0,n-this.submittedAt);this.send(e==="reasoning"?{submission_to_first_reasoning_delta_ms:i}:e==="tool"?{submission_to_first_tool_call_ms:i}:{submission_to_first_answer_delta_ms:i})}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 _e={minDelayMs:5,maxDelayMs:80,minRateCharsPerMs:.3,maxBufferedMs:400,arrivalRateTauMs:1e3,arrivalRateHeadroom:1.1,maxPendingChars:64},kn={now:()=>performance.now(),sleep:(t,e)=>new Promise(n=>{if(e!=null&&e.aborted||t<=0){n();return}const i=window.setTimeout(l,t);function l(){e==null||e.removeEventListener("abort",l),window.clearTimeout(i),n()}e==null||e.addEventListener("abort",l,{once:!0})})};function An(t){return!["stream_start","sandbox_start","sandbox_ready","workspace_ready","session_title_start","session_title_delta","session_title_done"].includes(t.type)}function In(t,e=!1,n=_e.maxPendingChars){var l;if(!t)return{pieces:[],pending:""};if(e)return{pieces:[t],pending:""};const i=Intl.Segmenter;if(i){const d=[...new i(void 0,{granularity:"word"}).segment(t)].filter(u=>u.isWordLike);let p=0;if(d.length>1&&(p=d.at(-1).index),d.length&&/\s$/u.test(t)&&(p=t.length),p>0){const u=t.slice(0,p),y=[],h=[...new i(void 0,{granularity:"word"}).segment(u)].filter(v=>v.isWordLike);for(let v=0;v<h.length;v+=1){const F=v===0?0:h[v].index,x=((l=h[v+1])==null?void 0:l.index)??u.length;x>F&&y.push(u.slice(F,x))}return h.length||y.push(u),{pieces:y,pending:t.slice(p)}}}else{const c=[...t.matchAll(/\s+/gu)];if(c.length){const d=[];let p=0;for(const u of c){const y=u.index+u[0].length;d.push(t.slice(p,y)),p=y}return{pieces:d,pending:t.slice(p)}}}return t.length>=n?{pieces:[t.slice(0,n)],pending:t.slice(n)}:{pieces:[],pending:t}}function Mn(t,e={}){const n={minDelayMs:e.minDelayMs??_e.minDelayMs,maxDelayMs:e.maxDelayMs??_e.maxDelayMs,minRateCharsPerMs:e.minRateCharsPerMs??_e.minRateCharsPerMs,maxBufferedMs:e.maxBufferedMs??_e.maxBufferedMs,arrivalRateTauMs:e.arrivalRateTauMs??_e.arrivalRateTauMs,arrivalRateHeadroom:e.arrivalRateHeadroom??_e.arrivalRateHeadroom,maxPendingChars:e.maxPendingChars??_e.maxPendingChars},i=e.clock??kn,l=[];let c="",d=null,p=0,u=!0,y=!1,T=null,h=0,v=i.now(),F=!1;const x=()=>{T==null||T(),T=null},C=(E,M)=>{const I=E.type==="reasoning_delta"||E.type==="answer_delta"?E.text.length:0;l.push({kind:"event",event:E,arrivedAt:M,chars:I}),x()},B=E=>{if(!d||!c)return;const M=In(c,E,n.maxPendingChars);for(const I of M.pieces)I&&C({type:d,text:I},p),p=i.now();c=M.pending,c||(d=null)},V=E=>{if(!u)return;const M=i.now();if(E.type==="reasoning_delta"||E.type==="answer_delta"){const I=E.type;if(!E.text)return;if(!F){F=!0,h+=E.text.length,v=M;const W=Array.from(E.text)[0];C({type:I,text:W},M);const N=E.text.slice(W.length);if(N)for(d=I,c=N,p=M,B(!1);c.length>=n.maxPendingChars;)B(!1);return}d&&d!==I&&B(!0),d||(d=I,p=M),c+=E.text;const P=Math.max(0,M-v);for(h*=Math.exp(-P/n.arrivalRateTauMs),h+=E.text.length,v=M,B(!1);c.length>=n.maxPendingChars;)B(!1);return}An(E)&&B(!0),C(E,M)},R=(async()=>{var E;try{for await(const M of t)V(M);u&&B(!0)}catch(M){u&&!((E=e.signal)!=null&&E.aborted)&&(B(!0),l.push({kind:"error",error:M,arrivedAt:i.now(),chars:0}))}finally{y=!0,x()}})(),A=()=>l.length||y?Promise.resolve():new Promise(E=>{T=E});return{events:async function*(){var M,I,P,W;let E=Number.NEGATIVE_INFINITY;try{for(;;){if(await A(),!l.length){if(y||!u)return;continue}const N=l[0];if(N.kind==="error")throw l.shift(),N.error;if(N.chars&&!((M=e.isHidden)!=null&&M.call(e))){const Z=i.now(),fe=l.reduce((ae,f)=>ae+f.chars,0),re=((I=l.find(ae=>ae.chars))==null?void 0:I.arrivedAt)??Z,ie=Math.max(0,n.maxBufferedMs-(Z-re)),te=h*Math.exp(-Math.max(0,Z-v)/n.arrivalRateTauMs)/n.arrivalRateTauMs,Y=ie>0?fe/ie:Number.POSITIVE_INFINITY,K=Math.max(n.minRateCharsPerMs,te*n.arrivalRateHeadroom,Y),z=Math.min(n.maxDelayMs,Math.max(n.minDelayMs,N.chars/K)),G=Math.max(0,N.arrivedAt+n.maxBufferedMs-Z),ce=Math.max(N.arrivedAt,E+Math.min(z,G));if(await i.sleep(Math.max(0,ce-i.now()),e.signal),!u||(P=e.signal)!=null&&P.aborted)return}l.shift(),E=i.now(),yield N.event}}finally{u&&(u=!1,x(),await((W=t.return)==null?void 0:W.call(t,void 0))),await R}}(),takeAcceptedForStop(){var M;if(!u)return[];u=!1,d&&c&&(C({type:d,text:c},p),c="",d=null);const E=l.flatMap(I=>I.kind==="event"&&I.event.type!=="done"&&I.event.type!=="error"?[I.event]:[]);return l.length=0,x(),(M=t.return)==null||M.call(t,void 0),E}}}const Ct=[250,500,1e3],Tn=(t,e)=>new Promise(n=>{const i=()=>{window.clearTimeout(l),e.removeEventListener("abort",i),n()},l=window.setTimeout(i,t);e.addEventListener("abort",i,{once:!0})});async function*Nn(t,e){let n=t,i=0;for(;;){let l=!1;try{for await(const c of n)(c.type==="done"||c.type==="error")&&(l=!0),yield c;if(l||e.signal.aborted)return;throw new vt}catch(c){e.onDisconnect();const d=e.getSessionId();if(e.signal.aborted||l||!(c instanceof vt)||!d||i>=Ct.length)throw c;if(await Tn(Ct[i],e.signal),e.signal.aborted)return;i+=1,n=Ot(d,{signal:e.signal,afterSequence:e.getAfterSequence(),onSequence:e.onSequence})}}}class Dn{constructor(){$(this,"configuration");$(this,"lifecycle",us());$(this,"_phase",{status:"idle"});$(this,"_pendingCapacity",null);$(this,"view",{messages:[],sessionError:"",disabledRequest:null});$(this,"snapshot",this.buildSnapshot());$(this,"listeners",new Set);$(this,"viewEpoch",0);$(this,"activeEpoch",null);$(this,"current",null);$(this,"projecting",!1);$(this,"subscribe",e=>(this.listeners.add(e),()=>{this.listeners.delete(e)}));$(this,"getSnapshot",()=>this.snapshot)}beginRun(){const e=++this.viewEpoch;return this.activeEpoch=e,this.projecting=!0,this.current=new AbortController,{controller:this.current,epoch:e}}detachView(){return++this.viewEpoch}isCurrent(e){return this.current===e}get running(){return this.current!==null}get controller(){return this.current}ownsView(e){return this.viewEpoch===e}get projectsActive(){return this.activeEpoch===this.viewEpoch||this.projecting}projectsRun(e){return this.activeEpoch===e&&this.projecting}releaseRun(){this.current=null}abortRun(){var e;(e=this.current)==null||e.abort(),this.current=null,this.activeEpoch=null}buildSnapshot(){return{...this.view,busy:this.busy,capacityRequest:this._pendingCapacity}}publish(){const e=this.buildSnapshot(),n=this.snapshot;if(!Object.keys(e).every(i=>e[i]===n[i])){this.snapshot=e;for(const i of this.listeners)i()}}get visibleMessages(){return this.view.messages}present(e){this.view={...this.view,...e},this.publish()}get phase(){return this._phase}get busy(){return this._phase.status==="streaming"}get pendingCapacity(){return this._pendingCapacity}get sawStreamStart(){return this._phase.status!=="idle"&&this._phase.streamStart!==null}get outcome(){return this._phase.status==="idle"?{kind:"pending"}:this._phase.outcome}get sawTerminalEvent(){const{kind:e}=this.outcome;return e==="complete"||e==="error"}get streamFailed(){const{kind:e}=this.outcome;return e==="error"||e==="transport_error"||e==="admission_rejected"}get admissionRejected(){return this.outcome.kind==="admission_rejected"}get shouldRefreshProvider(){var e;return this._phase.status==="idle"?!1:!!((e=this._phase.streamStart)!=null&&e.providerExecuted)||this._phase.providerStatusChanged}progress(e){this._phase.status!=="idle"&&(this._phase={...this._phase,...e})}finish(){this._phase.status==="streaming"&&(this._phase={...this._phase,status:"settled"}),this.publish()}queueCapacity(e){this._pendingCapacity=e,this.publish()}cancelCapacity(){this._pendingCapacity=null,this.publish()}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,n=!1){return this.lifecycle=gt(this.lifecycle,e),n&&(this.view={...this.view,messages:this.lifecycle.messages}),this.publish(),this.lifecycle}start(e,n,i){this.configuration=i,this._phase={status:"streaming",streamStart:null,providerStatusChanged:!1,outcome:{kind:"pending"}},this.view={...this.view,messages:e,sessionError:""},this.transition({type:"start",messages:e,sessionId:n})}restore(e,{sessionId:n=this.sessionId,show:i=!1,view:l}={}){return this.lifecycle=gt(this.lifecycle,{type:"load",messages:e,sessionId:n}),this.view={...this.view,...i?{messages:e}:{},...l},this.publish(),this.lifecycle}observe(e){return e.type==="stream_start"&&this.progress({streamStart:{providerExecuted:e.provider_execution!==!1}}),(e.type==="done"||e.type==="error")&&this.progress({outcome:{kind:e.type==="done"?"complete":"error"}}),e.type==="error"&&St(e.code)==="provider"?(this.progress({providerStatusChanged:!0}),!0):!1}reject(e,n){const i=e instanceof Ye?e.code:void 0,l=St(i),c=n&&i==="chat_not_busy"?{kind:"already_complete"}:i==="chat_temporarily_disabled"?{kind:"admission_rejected",reason:"disabled"}:i==="chat_capacity"?{kind:"admission_rejected",reason:"capacity"}:l==="draft"?{kind:"admission_rejected",reason:"draft"}:{kind:"transport_error",provider:l==="provider"},d=c.kind==="transport_error"&&c.provider;return this.progress({outcome:c,...d?{providerStatusChanged:!0}:{}}),c}reset(){this._phase={status:"idle"},this._pendingCapacity=null,this.view={...this.view,messages:[],sessionError:""},this.transition({type:"reset"})}}const Fn=750,Ln=8e3,Bn="The assistant stream failed.",Rt="Couldn’t resend this message. Your original conversation was restored.";function Se(t){const e=o.useRef(t);return o.useLayoutEffect(()=>{e.current=t}),o.useCallback((...n)=>e.current(...n),[])}const Pe=t=>({id:t,role:"assistant",streaming:!0,blocks:[]});function On(t){const[e]=o.useState(()=>new Dn),n=o.useSyncExternalStore(e.subscribe,e.getSnapshot),i=o.useRef(t);i.current=t;const l=o.useRef(t.sessionId),c=o.useRef(null),d=o.useRef(null),p=o.useRef(!1),u=o.useRef({state:"cleared",timer:null}),y=o.useRef(null),T=o.useRef(null),h=o.useRef(he()),v=o.useRef(0),x=(l.current!==t.sessionId?e.projectSession(t.sessionId):null)??n.messages,C=n.busy,B=()=>{var r;(r=d.current)==null||r.cancel(),d.current=null},V=()=>{const r=u.current;r.timer!==null&&window.clearTimeout(r.timer),u.current={state:"cleared",timer:null}},R=Se(()=>{var a;const{timer:r}=u.current;r!==null&&window.clearTimeout(r),(a=e.controller)==null||a.abort(),c.current=null,B(),e.cancelCapacity()});o.useEffect(()=>R,[R]),o.useLayoutEffect(()=>{l.current!==t.sessionId&&(l.current=t.sessionId,e.sessionId!==t.sessionId&&(e.detachView(),y.current=null));const r=e.projectSession(t.sessionId);e.projecting=r!==null,r&&e.present({messages:r})},[t.sessionId,e]),o.useEffect(()=>{e.busy||e.restore(e.messages,{sessionId:t.sessionId})},[t.sessionId,e]);const A=o.useMemo(()=>Ms(x),[x]),j=()=>`m${++v.current}_${Date.now().toString(36)}`,E=(r,a=!0)=>{const S=e.state,w=e.transition(r,a),b=r.type==="event"&&r.event.type==="stream_start"?r.event.session_id:null;return b?i.current.onSessionId(b,S.sessionId,e.configuration):w.sessionId&&w.sessionId!==S.sessionId&&i.current.onSessionId(w.sessionId,S.sessionId,e.configuration),w.title!==S.title&&i.current.onTitle(w.title,w.sessionId),w},M=(r,a=!0)=>{E({type:"event",event:r},a)},I=(r,a,S,w={})=>{const b=e.ownsView(a);e.restore(r,{show:b,view:{...w,...b?{sessionError:S}:{}}})},P=()=>{B(),document.visibilityState!=="hidden"&&e.projecting&&(p.current=!1,e.present({messages:e.messages}))},W=()=>{if(!e.projecting||document.visibilityState==="hidden"||d.current!==null)return;const r=()=>{d.current=null,P()};if(typeof requestAnimationFrame=="function"){const a=requestAnimationFrame(r);d.current={cancel:()=>cancelAnimationFrame(a)}}else{const a=window.setTimeout(r,0);d.current={cancel:()=>window.clearTimeout(a)}}};o.useEffect(()=>{const r=()=>{document.visibilityState==="visible"&&p.current&&W()};return document.addEventListener("visibilitychange",r),()=>document.removeEventListener("visibilitychange",r)});const N=r=>{if(!e.isCurrent(r))return;const{state:a}=u.current;V(),a==="shown"&&E({type:"clear_workspace_status"},e.projectsActive)},Z=(r,a)=>{const{timer:S}=u.current;S!==null&&window.clearTimeout(S);const w=window.setTimeout(()=>{u.current={...u.current,timer:null},!(u.current.state!=="armed"||!e.isCurrent(r)||r.signal.aborted||!e.ownsView(a))&&(u.current={state:"shown",timer:null},E({type:"workspace_status"},e.projectsActive))},Fn);u.current={state:"armed",timer:w}},fe=(r,a)=>{const S=y.current;!S||S.controller!==r||S.tracker.recordStreamStart(a,performance.now())},re=(r,a)=>{const S=y.current;!S||S.controller!==r||S.tracker.recordTerminal(a)};o.useLayoutEffect(()=>{const r=y.current;if(!r)return;const a=x.at(-1);if((a==null?void 0:a.role)!=="assistant"||!(a.blocks??[]).some(b=>b.kind==="tool"||b.kind==="reasoning"&&!!b.text.trim()||b.kind==="answer"&&!!b.text.trim()))return;const w=performance.now();r.tracker.recordFirstVisible(w);for(const b of a.blocks??[])b.kind==="reasoning"&&b.text.trim()?r.tracker.recordSemantic("reasoning",w):b.kind==="tool"?r.tracker.recordSemantic("tool",w):b.kind==="answer"&&b.text.trim()&&r.tracker.recordSemantic("answer",w)},[x]);const ie=async(r,a)=>{var D;const w=await(i.current.loadSession??(H=>ne.getSession(H)))(r);let b=ps(e.state.messages,qt(w));return((D=T.current)==null?void 0:D.sessionId)===r&&(b=T.current.messages,T.current=null),!e.ownsView(a)&&!(e.projectsRun(a)&&i.current.sessionId===r)?null:(e.restore(b,{sessionId:r,show:!0}),b)},te=(r,a)=>Rn(i.current,r,a),Y=r=>{const a=typeof r=="string"?he(r.trim()):r;return!a.text||a.text.length>Ln||e.busy||e.pendingCapacity?null:a},K=(r,a,S,w,b,D,H)=>{const{controller:k,epoch:_}=e.beginRun(),we=r.text;return h.current=r,e.start(S,a.session_id,H??{model:i.current.initialModel,webSearchEnabled:!!a.web_search_enabled,reasoningEffort:a.reasoning_effort??tt}),y.current=D?null:{controller:k,tracker:new jn(performance.now())},u.current={...u.current,state:"cleared"},(async()=>{var Ne,ke,Ae,Ce,Re,Ie;let be=0;const ve=ee=>{ee>be&&(be=ee)};try{const ee=D?Ot(D,{signal:k.signal,onSequence:ve}):Ts(a,{signal:k.signal,onSequence:ve}),le=Nn(ee,{signal:k.signal,getSessionId:()=>e.sessionId,onDisconnect:()=>{!k.signal.aborted&&e.isCurrent(k)&&M({type:"compaction_status",state:"finished"},e.projectsActive)},getAfterSequence:()=>be,onSequence:ve}),ue=!D&&Te()&&Ns(),J=ue?Mn(le,{signal:k.signal,isHidden:()=>document.visibilityState==="hidden"}):null;J&&(c.current={controller:k,stream:J});for await(const de of(J==null?void 0:J.events)??le){if(k.signal.aborted||!e.isCurrent(k))break;const me=fs[de.type];de.type==="paper_artifact"&&((ke=(Ne=i.current).onPaperArtifact)==null||ke.call(Ne,de,e.sessionId)),de.type==="stream_start"&&fe(k,de.request_id),me.workspaceStatus==="arm"&&Z(k,_),me.workspaceStatus==="clear"&&N(k),e.observe(de)&&e.projectsActive&&i.current.onInterrupted(r),me.terminal&&re(k,me.terminal);const ge=e.projectsActive,De=ge&&!(ue&&document.visibilityState==="hidden");ue&&me.presentation==="structural"&&P(),ue&&me.presentation==="delta"?(M(de,!1),p.current||(p.current=ge),W()):(M(de,De),ue&&ge&&!De&&(p.current=!0))}}catch(ee){if(!k.signal.aborted&&e.isCurrent(k)){const le=e.reject(ee,!!D);N(k);const ue=ee instanceof Error?ee.message:Bn;switch(le.kind){case"already_complete":break;case"admission_rejected":if(le.reason==="disabled")I(w,_,"",{disabledRequest:{question:we,draft:r}});else if(le.reason==="capacity"){const J=ee instanceof Ye?ee.retryAfterSeconds??5:5;e.queueCapacity({question:we,draft:r,request:a,optimistic:S,original:w,edit:b,retryAfterSeconds:J,retryAt:Date.now()+J*1e3}),I(w,_,"")}else re(k,"network_error"),e.projectsActive&&i.current.onInterrupted(r),I(w,_,ue);break;case"transport_error":re(k,"network_error"),le.provider&&e.projectsActive&&i.current.onInterrupted(r),e.ownsView(_)&&M({type:"error",message:ue,code:ee instanceof Ye?ee.code:void 0});break}}}finally{if(e.isCurrent(k)){if(((Ae=c.current)==null?void 0:Ae.controller)===k&&(P(),c.current=null),N(k),!e.sawTerminalEvent&&!k.signal.aborted&&re(k,"network_error"),e.finish(),e.admissionRejected)i.current.onSettled(a.session_id);else if(!k.signal.aborted){e.shouldRefreshProvider&&((Re=(Ce=i.current).onProviderTerminal)==null||Re.call(Ce));const ee=e.sessionId,le=e.ownsView(_);if(b&&!e.sawStreamStart)I(b.snapshot,_,Rt);else if(ee){le&&b&&(e.streamFailed||!e.sawTerminalEvent)&&e.restore(b.snapshot,{show:!0});try{const ue=await ie(ee,_);ue&&b&&ue.some(J=>J.id===b.targetId)&&e.present({sessionError:Rt})}catch{e.ownsView(_)&&E({type:"settle"})}}else le&&E({type:"settle"});(!e.running||e.isCurrent(k))&&i.current.onSettled(ee)}((Ie=y.current)==null?void 0:Ie.controller)===k&&(y.current=null)}}})(),!0},z=Se(r=>{const a=Y(r);if(!a)return!1;const S=e.visibleMessages,w=Me(S),b=w!=null&&w.status&&w.status!=="complete"&&w.revision?{replace_message_id:w.id,prior_revision:w.revision}:null,D={id:j(),role:"user",text:a.text,paperMentions:a.paperMentions,paperSelection:a.paperSelection,attachedFiles:a.files},H=Pe(j()),k=b&&w?hs(S,ve=>ve.id===w.id):-1,_=k<0?[...S,D,H]:[...S.slice(0,k),D,H],we=i.current.sessionId??a.fileSessionId??null,{initialModel:be}=i.current;return K(a,te(a.text,{session_id:we,client_message_id:crypto.randomUUID(),...Et(i.current,a),...!we&&be?{initial_model:be}:{},...b??{}}),_,S)}),G=Se((r,a)=>{var be;const S=Y(a);if(!S)return!1;const w=e.visibleMessages.slice(),b=w.findIndex(ve=>ve.id===r&&ve.role==="user");if(b<0)return!1;const D=w[b],H=S.files||!((be=D.attachedFiles)!=null&&be.length)?S:{...S,files:D.attachedFiles},{sessionId:k}=i.current;if(!k||!D.revision)return!1;const _={id:D.id,role:"user",text:H.text,paperMentions:H.paperMentions,paperSelection:H.paperSelection,attachedFiles:H.files,revision:D.revision+1,status:"generating"},we=[...w.slice(0,b),_,Pe(j())];return K(H,te(H.text,{session_id:k,client_message_id:crypto.randomUUID(),...Et(i.current,H),replace_message_id:D.id,prior_revision:D.revision}),we,w,{targetId:D.id,snapshot:w})}),ce=Se(()=>{const r=e.visibleMessages.slice(),a=Me(r),{sessionId:S}=i.current;if(!S||!(a!=null&&a.revision)||e.busy||e.pendingCapacity)return!1;const w=he(a.text??"Continue the interrupted response from saved progress."),b=[...r,{id:j(),role:"user",text:w.text,paperMentions:[]},Pe(j())];return K(w,te(w.text,{session_id:S,client_message_id:crypto.randomUUID(),retry_message_id:a.id,...Vt(i.current)}),b,r)}),ae=Se(()=>{const r=Me(e.visibleMessages);return r!=null&&r.text?G(r.id,Qe(r)):!1}),f=o.useCallback(()=>{e.cancelCapacity()},[e]),L=Se(()=>{const r=e.pendingCapacity;return!r||Date.now()<r.retryAt||e.busy?!1:(e.cancelCapacity(),K(r.draft,r.request,r.optimistic,r.original,r.edit))}),U=Se(()=>{var H,k;const r=e.controller;if(!r)return;N(r),re(r,"stopped"),r.abort();const a=((H=c.current)==null?void 0:H.controller)===r?c.current.stream.takeAcceptedForStop():[];c.current=null;for(const _ of a)M(_,!1);P(),e.releaseRun(),((k=y.current)==null?void 0:k.controller)===r&&(y.current=null),e.finish();const S=e.projectsActive,w=E({type:"stop"},S).messages;S&&i.current.onInterrupted(h.current);const b=e.sessionId;b&&(T.current={sessionId:b,messages:w}),b&&ne.cancelSession(b).catch(()=>{});const D=e.detachView();window.setTimeout(()=>{b&&S&&e.ownsView(D)?ie(b,D).catch(()=>{}).finally(()=>{e.running||i.current.onSettled(b)}):e.running||i.current.onSettled(b)},450)}),pe=Se((r,a)=>{e.projecting?e.transition({type:"toggle_block",messageId:r,blockIndex:a},!0):e.present({messages:ds(e.visibleMessages,r,a)})}),se=()=>{e.detachView(),V(),B(),p.current=!1,y.current=null},X=Se(()=>{se(),e.abortRun(),c.current=null,T.current=null,e.projecting=!1,e.reset()}),oe=Se((r,a,S=!1,w)=>{if(se(),e.cancelCapacity(),e.busy&&a!==void 0&&a===e.sessionId){e.projecting=!0,e.present({messages:e.messages,sessionError:""});return}if(e.projecting=!1,e.busy||e.abortRun(),S&&a&&!e.busy){const b=Me(r);if(b){const D=Qe(b),H=[...r,Pe(`${b.id}-active`)];K(D,te(D.text,{session_id:a,client_message_id:"reconnect"}),H,r,void 0,a,w);return}}e.busy?e.present({messages:r,sessionError:""}):e.restore(r,{sessionId:a??i.current.sessionId,show:!0,view:{sessionError:""}})}),g=n.capacityRequest;return{messages:x,busy:C,activeSessionId:C?e.sessionId:null,activeTitle:e.state.title,activeConfiguration:e.configuration,selectedBusy:C&&e.sessionId===t.sessionId,papers:A,sessionError:n.sessionError,capacityRequest:g,disabledRequest:n.disabledRequest,send:z,editAndResend:G,retryFromProgress:ce,retryLatest:ae,retryCapacity:L,cancelCapacity:f,dismissDisabled:()=>e.present({disabledRequest:null}),stop:U,toggleBlock:pe,reset:X,load:oe}}const jt=(t,e,n)=>e?n?{...t,paperSelection:n}:Pt(t):t,qn=({mode:t="general",routeSessionId:e,primaryPaper:n,currentPage:i,paperSelection:l,onPaperSelectionChange:c,onSessionId:d,onReaderSubmit:p,onReaderNewChat:u,onReaderClose:y})=>{var ot,ct,lt,ut,dt;const{sessionId:T}=ts(),h=e??(t==="general"?T:void 0),v=Tt(),[F]=Mt(),{user:x,isLoading:C}=Ft(),B=Dt(),V=(x==null?void 0:x.hf_subject)??null,R=Nt(),A=je({...ms(),enabled:Te()&&!!x}),j=A.data,E=(j==null?void 0:j.status)==="paused"||t==="paper"&&(j==null?void 0:j.paper_reader_chat_enabled)===!1,M=je({...gs(V),enabled:!!x&&!C}),I=M.data??[],{markSessionBusy:P,patchSession:W,refreshSessions:N}=_n(V),[Z,fe]=o.useState(null),[re,ie]=o.useState(""),[te]=o.useState(Ds),Y=o.useRef(h);Y.current=h;const K=o.useRef(null),z=o.useRef(null),G=o.useRef(0),ce=o.useCallback(()=>{G.current+=1,K.current=null,z.current=null},[]),ae=o.useRef(h);ae.current!==h&&(ae.current=h,ce());const f=vn({userId:V,signedIn:!!x,authLoading:C,requestedModel:F.get("model")||(te==null?void 0:te.model),routeSessionIdRef:Y}),{selectedModel:L,setSelectedModel:U}=f,pe=Vs(!!(x&&f.provider==="openrouter")),[se,X]=o.useState(()=>he()),oe=tt,g=!!(j!=null&&j.web_search_available),[r,a]=o.useState(()=>{var O;const m=(O=F.get("q"))==null?void 0:O.trim();return m?he(m):(te==null?void 0:te.draft)??he()}),[S,w]=o.useState(()=>typeof window>"u"||window.innerWidth>900),b=o.useRef(new Set),[D,H]=o.useState(void 0),k=o.useCallback(m=>{X(m),c==null||c(m.paperSelection)},[c]),_=On({sessionId:h??null,initialModel:L,webSearchEnabled:g,reasoningEffort:oe,primaryPaperRouteId:t==="paper"?n==null?void 0:n.routeId:void 0,viewerContext:t==="paper"&&i?()=>({page:Math.max(1,Math.min(1e4,i()))}):void 0,loadSession:async m=>{const O=await B.fetchQuery(bt(V,m));return fe(q=>(q==null?void 0:q.sessionId)===m?null:q),O},onSessionId:(m,O,q)=>{P(m,{model:(q==null?void 0:q.model)??L,webSearchEnabled:(q==null?void 0:q.webSearchEnabled)??g,reasoningEffort:(q==null?void 0:q.reasoningEffort)??oe});const ye=Y.current??null,Oe=ye===null&&K.current!==null&&(m===K.current||O===K.current);(ye===O||Oe)&&m!==ye&&(t==="paper"?d==null||d(m):v(`/chat/${m}`,{replace:!0}))},onTitle:(m,O)=>{O&&!b.current.has(O)&&W(O,{title:m})},onSettled:m=>{m&&W(m,{is_busy:!1}),B.invalidateQueries({queryKey:Ut}),N()},onProviderTerminal:()=>{B.invalidateQueries({queryKey:Ks})},onPaperArtifact:(m,O)=>{O&&fe({sessionId:O,descriptor:m.descriptor})},onInterrupted:k}),we=_.send;o.useEffect(()=>{_.capacityRequest&&k(_.capacityRequest.draft)},[_.capacityRequest,k]);const be=o.useCallback(()=>t==="paper"&&n?`/pdf/${n.routeId}`:Y.current?`/chat/${Y.current}`:"/chat",[t,n]),ve=o.useCallback((m,O)=>{a(he()),k(m),ie(O)},[k]),Ne=Cn({returnTo:be,selectedModel:L,reasoningEffort:oe,userBilledInference:f.userBilledInference,onPromptRestored:ve}),{authorizeSend:ke,restorePrompt:Ae}=Ne,Ce=!!c,Re=o.useCallback(async m=>{const O=jt(m,Ce,l),q=!Y.current&&!O.fileSessionId&&K.current?{...O,fileSessionId:K.current}:O,ye=ke(q,!!x);if(!(ye!==!0&&!await ye)){if(Fs(),!we(q)){Ae(q,"Your prompt was not sent. It is ready to retry.");return}Ls(),X(he()),c==null||c(void 0),t==="paper"&&(p==null||p())}},[ke,t,c,p,l,Ce,Ae,we,x]),Ie=o.useCallback(async(m,O)=>{const q=G.current;let ye=Y.current??O??K.current;if(!ye){if(!z.current){const ht=ne.createSession(L,oe,t==="paper"?n==null?void 0:n.routeId:void 0).then(ft=>(q===G.current&&(K.current=ft.id),N(),ft.id)).finally(()=>{z.current===ht&&(z.current=null)});z.current=ht}ye=await z.current}if(q!==G.current)throw new yt;const Oe=await ne.uploadFile(ye,m);if(q!==G.current)throw ne.deleteFile(ye,Oe.id).catch(()=>{}),new yt;return{sessionId:ye,file:Oe}},[t,n==null?void 0:n.routeId,oe,N,L]),[ee,le]=o.useState(0),ue=o.useMemo(()=>({upload:async(m,O)=>{le(q=>q+1);try{return await Ie(m,O)}finally{le(q=>q-1)}},remove:(m,O)=>{ne.deleteFile(m,O).catch(()=>{})}}),[Ie]),J=_.selectedBusy,{load:de,activeConfiguration:me}=_,ge=je({...bt(V,h??null),enabled:!!(h&&x&&!C&&!J),refetchOnMount:"always"}),De=wn(t==="general"?h:void 0,!C&&(!x||ge.error instanceof ss&&ge.error.status===404)),Q=ge.data,Fe=J||D===(h??null),st=Z&&Z.sessionId===h?Z.descriptor:Q==null?void 0:Q.latex_paper,Kt=(ct=(ot=[...(Q==null?void 0:Q.messages)??[]].reverse().find(m=>m.role==="user"&&m.viewer_context))==null?void 0:ot.viewer_context)==null?void 0:ct.page;o.useLayoutEffect(()=>{const m=h??null;if(D!==m){if(J){H(m),me!=null&&me.model&&U(me.model);return}if(!m){de([],null),H(null);return}!Q||ge.isFetching||(H(m),de(qt(Q),m,Q.is_busy,{model:Q.selected_model,webSearchEnabled:Q.web_search_enabled,reasoningEffort:Q.reasoning_effort??"high"}),ie(""),U(Q.selected_model))}},[h,J,Q,de,me,ge.isFetching,D,U]),bn({pendingDraft:r,setPendingDraft:a,blocked:C||_.busy||!!x&&A.isFetching||!!(h&&!Fe),authLoading:C,signedIn:!!x,send:Re,restoreDraft:X,setSelectedModel:U,onPaperSelectionChange:c}),o.useEffect(()=>{const m=()=>{!x||_.busy||N()};return window.addEventListener("focus",m),()=>window.removeEventListener("focus",m)},[_.busy,N,x]);const Ve=()=>{ce(),window.innerWidth<=900&&w(!1),de([],null),H(null),X(he()),c==null||c(void 0),t==="paper"?u==null||u():v("/chat")},Le=En({routeSessionId:h,selectedModel:L,setSelectedModel:U,patchSession:W,onRenamed:m=>b.current.add(m),refreshSessions:N,onError:ie,onSelectedDeleted:Ve,isActive:m=>_.busy&&m===_.activeSessionId,stopActive:_.stop}),Ke=yn({messages:_.messages,refreshSessions:N,resetChat:_.reset,restoreDraft:X}),Wt=async()=>{await Le.changeModel($e)&&_.retryLatest()},zt=zs(t==="general"),nt=I.map(m=>m.id===_.activeSessionId&&_.busy?{...m,is_busy:!0,title:b.current.has(m.id)?m.title:_.activeTitle||m.title}:m),xe=nt.find(m=>m.id===h),rt=(xe==null?void 0:xe.primary_paper)??(Q==null?void 0:Q.primary_paper),We=_.messages.length===0,Be=!!(h&&(C||x&&!Fe&&!ge.isError||De.pending)),it=!Fe&&!Be&&((lt=ge.error)==null?void 0:lt.message),Qt=!se.fileSessionId||se.fileSessionId===(h??K.current)?se:{...se,files:void 0,fileSessionId:void 0},at={composerProps:{onSend:Re,busy:J,onStop:_.stop,draft:jt(Qt,Ce,l),onDraftChange:m=>{c?(X(Pt(m)),m.paperSelection!==l&&c(m.paperSelection)):X(m)},disabled:E||C||_.busy&&!J,describedBy:E?"chat-paused-description":void 0,paperMentionsEnabled:!!(j!=null&&j.paper_mentions_enabled),paperSelectionEnabled:(j==null?void 0:j.paper_reader_selection_enabled)===!0,paperArtifactsEnabled:t==="general"&&(j==null?void 0:j.paper_artifacts_enabled)===!0,fileUploads:(j==null?void 0:j.file_uploads_enabled)===!0&&x?ue:void 0},provider:f.provider,sponsored:f.sponsored,paused:E,uploading:ee>0,error:_.sessionError};return s.jsx(ln,{enabled:t==="general",workspaceKey:h??"new-chat",onAskAiFix:m=>{Re(he(m))},children:s.jsxs("div",{className:`chat-page${t==="paper"?" chat-page--reader":""}`,style:{height:zt},children:[t==="general"&&s.jsx(tn,{sessions:nt,activeSessionId:h,loading:M.isLoading,error:re||((ut=M.error)==null?void 0:ut.message)||"",open:S,onClose:()=>w(!1),onNew:Ve,onNavigate:m=>{window.innerWidth<=900&&w(!1),v(`/chat/${m}`)},onRename:Le.rename,onDelete:m=>void Le.remove(m),onDeleteMany:Le.removeMany}),s.jsx(un,{enabled:t==="general",children:s.jsxs("section",{className:"chat-main","data-testid":"active-chat-pane",children:[s.jsxs("div",{className:"chat-topbar",children:[t==="general"&&!S&&s.jsx("button",{type:"button",className:"icon-btn",onClick:()=>w(!0),title:"Open sidebar","aria-label":"Open sidebar",children:s.jsx(Lt,{})}),s.jsx("span",{className:"chat-topbar-title",children:Be?(xe==null?void 0:xe.title)||"":(xe==null?void 0:xe.title)||(Q==null?void 0:Q.title)||(We?"":"New chat")}),R&&s.jsx("span",{className:"chat-staging-badge",children:"Staging"}),t==="general"&&h&&rt&&s.jsx(fn,{routeId:rt.route_id,sessionId:h,page:Kt}),h&&Fe&&!We&&s.jsx(sn,{sessionId:h,busy:J,loading:Be,hasPaperSelection:_.messages.some(m=>!!m.paperSelection),onError:ie}),t==="paper"&&s.jsx(hn,{onNewChat:Ve,onClose:y})]}),s.jsx(dn,{provider:f.provider,enabled:Te()&&!!x&&f.provider==="openai"}),t==="general"&&st&&s.jsx(mn,{descriptor:st}),Be&&!r.text?s.jsxs("div",{className:"chat-session-loading",role:"status","aria-live":"polite",children:[s.jsx(Bt,{}),s.jsx("span",{children:"Loading conversation…"})]}):it?s.jsxs("div",{className:"chat-session-load-error",role:"alert",children:[s.jsx("p",{children:it}),s.jsx("button",{type:"button",onClick:()=>{ge.refetch()},children:"Try again"})]}):We&&!r.text?s.jsx(pn,{mode:t,staging:R,children:s.jsx(_t,{variant:"empty",...at,suggestions:t==="paper"?Bs:Os,suggestionLinks:t==="paper"&&n&&s.jsxs("a",{className:"chat-example",href:Hs(n.title,n.arxivId),target:"_blank",rel:"noopener noreferrer",title:"Ask Hugging Face ML Intern to reproduce this paper",children:[s.jsx("span",{className:"chat-example-icon",children:s.jsx(Us,{name:"robot",size:14})}),"Reproduce with ML Intern"]})})}):s.jsxs(s.Fragment,{children:[s.jsx(Ys,{messages:_.messages,papers:_.papers,busy:J,queuedDraft:r.text?r:void 0,paperMentionsEnabled:!!(j!=null&&j.paper_mentions_enabled),archivePending:Ke.pending,openRouterFallbackEnabled:!!((dt=pe.data)!=null&&dt.fallback_enabled),onToggleBlock:_.toggleBlock,onEditAndResend:_.editAndResend,onRetryFromProgress:_.retryFromProgress,onRetryWithLuna:f.lunaAvailable?()=>void Wt():void 0,onArchiveOld:()=>void Ke.archiveOld(),onArchiveOldest:()=>void Ke.archiveOldest()}),s.jsx(_t,{variant:"followup",...at})]})]})}),_.capacityRequest&&s.jsx(Gs,{retryAt:_.capacityRequest.retryAt,onCancel:_.cancelCapacity,onRetry:()=>{_.retryCapacity()&&(X(he()),c==null||c(void 0))}}),_.disabledRequest&&s.jsx(Xs,{onClose:()=>{var m;k(((m=_.disabledRequest)==null?void 0:m.draft)??se),_.dismissDisabled(),A.refetch()}})]})})},Pn=t=>{const{user:e}=Ft();return s.jsx(qn,{...t},(e==null?void 0:e.hf_subject)??"guest")},wr=()=>s.jsx(Pn,{});export{Pn as ChatExperience,wr as default}; | |